Skip to content
Open
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
19 changes: 12 additions & 7 deletions fintoc/paginator.py
Original file line number Diff line number Diff line change
Expand Up @@ -11,8 +11,8 @@
def paginate(
client: httpx.Client,
url: str,
params: dict[str, str] = {},
headers: dict[str, str] = {},
params: dict[str, str] = None,
headers: dict[str, str] = None,
):
"""
Fetch a paginated resource and return a generator with all of
Expand All @@ -32,18 +32,23 @@ def paginate(
def request(
client: httpx.Client,
url: str,
params: dict[str, str] = {},
headers: dict[str, str] = {},
params: dict[str, str] = None,
headers: dict[str, str] = None,
):
"""
Fetch a page of a resource and return its elements and the next
page of the resource.
"""
_request = httpx.Request("get", url, params=params, headers=headers)
_request = httpx.Request(
"get",
url,
params=params or None,
headers=headers,
)
response = client.send(_request)
response.raise_for_status()
headers = parse_link_headers(response.headers.get("link"))
next_ = headers and headers.get("next")
link_headers = parse_link_headers(response.headers.get("link"))
next_ = link_headers and link_headers.get("next")
elements = response.json()
return {
"next": next_,
Expand Down
18 changes: 18 additions & 0 deletions tests/test_paginator.py
Original file line number Diff line number Diff line change
Expand Up @@ -82,6 +82,13 @@ def test_request_params_get_passed_to_next_url(self):
assert "next" in data
assert "link_token=sample_link_token" in data["next"]

def test_request_preserves_query_params_in_url(self):
client = httpx.Client(base_url="https://test.com")
data = request(client, "/movements?custom_param=value&page=2")
assert "next" in data
assert "custom_param=value" in data["next"]
assert "page=3" in data["next"]


class TestPaginate:
@pytest.fixture(autouse=True)
Expand All @@ -98,3 +105,14 @@ def test_pagination(self):

for element in elements:
assert isinstance(element, dict)

def test_pagination_with_initial_query_params(self):
client = httpx.Client(base_url="https://test.com")
data = paginate(
client,
"/movements",
params={"filter": "recent"},
)
assert isinstance(data, GeneratorType)
elements = list(data)
assert len(elements) == 100