Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
17 changes: 7 additions & 10 deletions pyiceberg/catalog/rest/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -1171,7 +1171,7 @@ def add_headers(self, request: PreparedRequest, **kwargs: Any) -> None: # pylin

url = str(request.url).split("?")[0]
query = str(parse.urlsplit(request.url).query)
params = dict(parse.parse_qsl(query))
params = dict(parse.parse_qsl(query, keep_blank_values=True))

# remove the connection header as it will be updated after signing
if "connection" in request.headers:
Expand Down Expand Up @@ -1467,11 +1467,10 @@ def list_tables(self, namespace: str | Identifier) -> list[Identifier]:
params["pageSize"] = str(page_size)

tables: list[Identifier] = []
page_token: str | None = None
page_token: str = ""

while True:
if page_token:
params["pageToken"] = page_token
params["pageToken"] = page_token
response = self._session.get(url, params=params)
try:
response.raise_for_status()
Expand Down Expand Up @@ -1608,11 +1607,10 @@ def list_views(self, namespace: str | Identifier) -> list[Identifier]:
params["pageSize"] = str(page_size)

views: list[Identifier] = []
page_token: str | None = None
page_token: str = ""

while True:
if page_token:
params["pageToken"] = page_token
params["pageToken"] = page_token

response = self._session.get(url, params=params)
try:
Expand Down Expand Up @@ -1732,14 +1730,13 @@ def list_namespaces(self, namespace: str | Identifier = ()) -> list[Identifier]:
params["pageSize"] = str(page_size)

namespaces: list[Identifier] = []
page_token: str | None = None
page_token: str = ""

while True:
if namespace_tuple:
# Query parameters are URL-encoded by requests, so the parts must not be quoted here as well
params["parent"] = self._namespace_separator.join(namespace_tuple)
if page_token:
params["pageToken"] = page_token
params["pageToken"] = page_token
response = self._session.get(self.url(Endpoints.list_namespaces), params=params)

try:
Expand Down
107 changes: 101 additions & 6 deletions tests/catalog/test_rest.py
Original file line number Diff line number Diff line change
Expand Up @@ -84,7 +84,7 @@
from pyiceberg.table.metadata import TableMetadataV1
from pyiceberg.table.sorting import SortField, SortOrder
from pyiceberg.transforms import IdentityTransform, TruncateTransform
from pyiceberg.typedef import RecursiveDict
from pyiceberg.typedef import Identifier, RecursiveDict
from pyiceberg.types import StringType
from pyiceberg.utils.config import Config
from pyiceberg.view import View
Expand Down Expand Up @@ -491,6 +491,7 @@ def test_list_tables_200(rest_mock: Mocker) -> None:
)

assert RestCatalog("rest", uri=TEST_URI, token=TEST_TOKEN).list_tables(namespace) == [("examples", "fooshare")]
assert rest_mock.last_request.qs == {"pagetoken": [""]}


def test_list_tables_paginated_200(rest_mock: Mocker) -> None:
Expand Down Expand Up @@ -592,14 +593,74 @@ def test_list_tables_page_size(rest_mock: Mocker) -> None:
)

result = RestCatalog("rest", uri=TEST_URI, token=TEST_TOKEN, **{PAGE_SIZE: "100"}).list_tables(namespace)
assert rest_mock.last_request.url == f"{TEST_URI}v1/namespaces/examples/tables?pageSize=100"
assert rest_mock.last_request.url == f"{TEST_URI}v1/namespaces/examples/tables?pageSize=100&pageToken="

assert result == [
("examples", "table1"),
("examples", "table2"),
]


@pytest.mark.parametrize(
"list_method, path, first_page, second_page, expected",
[
pytest.param(
"list_tables",
"v1/namespaces/examples/tables",
{"identifiers": [{"namespace": ["examples"], "name": "table1"}], "next-page-token": "page2token"},
{"identifiers": [{"namespace": ["examples"], "name": "table2"}]},
[("examples", "table1"), ("examples", "table2")],
id="tables",
),
pytest.param(
"list_views",
"v1/namespaces/examples/views",
{"identifiers": [{"namespace": ["examples"], "name": "view1"}], "next-page-token": "page2token"},
{"identifiers": [{"namespace": ["examples"], "name": "view2"}]},
[("examples", "view1"), ("examples", "view2")],
id="views",
),
pytest.param(
"list_namespaces",
"v1/namespaces",
{"namespaces": [["ns1"]], "next-page-token": "page2token"},
{"namespaces": [["ns2"]]},
[("ns1",), ("ns2",)],
id="namespaces",
),
],
)
def test_list_page_size_paginated(
rest_mock: Mocker,
list_method: str,
path: str,
first_page: dict[str, Any],
second_page: dict[str, Any],
expected: list[Identifier],
) -> None:
rest_mock.get(
f"{TEST_URI}{path}?pageSize=1&pageToken=",
complete_qs=True,
json=first_page,
status_code=200,
request_headers=TEST_HEADERS,
)
rest_mock.get(
f"{TEST_URI}{path}?pageSize=1&pageToken=page2token",
complete_qs=True,
json=second_page,
status_code=200,
request_headers=TEST_HEADERS,
)

catalog = RestCatalog("rest", uri=TEST_URI, token=TEST_TOKEN, **{PAGE_SIZE: "1"})
if list_method == "list_namespaces":
result = catalog.list_namespaces()
else:
result = getattr(catalog, list_method)("examples")
assert result == expected


def test_list_tables_200_sigv4(rest_mock: Mocker) -> None:
namespace = "examples"
rest_mock.get(
Expand Down Expand Up @@ -671,6 +732,37 @@ def test_sigv4_sign_request_with_body(rest_mock: Mocker) -> None:
assert prepared.headers.get("x-amz-content-sha256") != EMPTY_BODY_SHA256


def test_sigv4_sign_request_keeps_blank_query_params(rest_mock: Mocker) -> None:
from botocore.auth import SigV4Auth
from botocore.credentials import Credentials

catalog = RestCatalog(
"rest",
**{
"uri": TEST_URI,
"token": TEST_TOKEN,
"rest.sigv4-enabled": "true",
"rest.signing-region": "us-west-2",
"client.access-key-id": "id",
"client.secret-access-key": "secret",
},
)

prepared = catalog._session.prepare_request(
Request("GET", f"{TEST_URI}v1/namespaces", params={"pageSize": "1", "pageToken": ""})
)
adapter = catalog._session.adapters[catalog.uri]
assert isinstance(adapter, HTTPAdapter)
with mock.patch("botocore.auth.SigV4Auth.add_auth", autospec=True) as add_auth:
adapter.add_headers(prepared)

signed_request = add_auth.call_args.args[1]
canonical_query_string = SigV4Auth(Credentials("id", "secret"), "execute-api", "us-west-2").canonical_query_string(
signed_request
)
assert canonical_query_string == "pageSize=1&pageToken="


def test_sigv4_adapter_default_retry_config(rest_mock: Mocker) -> None:
catalog = RestCatalog(
"rest",
Expand Down Expand Up @@ -760,6 +852,7 @@ def test_list_views_200(rest_mock: Mocker) -> None:
)

assert RestCatalog("rest", uri=TEST_URI, token=TEST_TOKEN).list_views(namespace) == [("examples", "fooshare")]
assert rest_mock.last_request.qs == {"pagetoken": [""]}


def test_list_views_paginated_200(rest_mock: Mocker) -> None:
Expand Down Expand Up @@ -861,7 +954,7 @@ def test_list_views_page_size(rest_mock: Mocker) -> None:
)

result = RestCatalog("rest", uri=TEST_URI, token=TEST_TOKEN, **{PAGE_SIZE: "100"}).list_views(namespace)
assert rest_mock.last_request.url == f"{TEST_URI}v1/namespaces/examples/views?pageSize=100"
assert rest_mock.last_request.url == f"{TEST_URI}v1/namespaces/examples/views?pageSize=100&pageToken="

assert result == [
("examples", "view1"),
Expand Down Expand Up @@ -1018,6 +1111,7 @@ def test_list_namespaces_200(rest_mock: Mocker) -> None:
("fokko",),
("system",),
]
assert rest_mock.last_request.qs == {"pagetoken": [""]}


def test_list_namespace_with_parent_200(rest_mock: Mocker) -> None:
Expand Down Expand Up @@ -1178,7 +1272,7 @@ def test_list_namespaces_page_size(rest_mock: Mocker) -> None:
)

result = RestCatalog("rest", uri=TEST_URI, token=TEST_TOKEN, **{PAGE_SIZE: "100"}).list_namespaces()
assert rest_mock.last_request.url == f"{TEST_URI}v1/namespaces?pageSize=100"
assert rest_mock.last_request.url == f"{TEST_URI}v1/namespaces?pageSize=100&pageToken="

assert result == [
("ns1",),
Expand Down Expand Up @@ -2588,9 +2682,10 @@ def do_POST(self) -> None:
self.do_GET()

def do_GET(self) -> None:
if self.path.endswith("/v1/config"):
path = urlsplit(self.path).path
if path.endswith("/v1/config"):
self._respond(200, config_body)
elif self.path.endswith("/v1/namespaces"):
elif path.endswith("/v1/namespaces"):
state["namespace_calls"] += 1
state["idempotency_keys"].append(self.headers.get(IDEMPOTENCY_KEY_HEADER))
if state["namespace_calls"] <= num_failures:
Expand Down