Skip to content

✨ Adds paginated method #2

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 4 commits into from
Jan 22, 2024
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
53 changes: 53 additions & 0 deletions tests/test_request.py
Original file line number Diff line number Diff line change
@@ -1,3 +1,4 @@
import json
import pytest
from unittest.mock import MagicMock
from wc_client.request import WCRequest
Expand All @@ -8,6 +9,12 @@ def __init__(self, content, status_code=200):
self.content = content
self.status_code = status_code

def json(self):
# Decode bytes to string
json_str = self.content.decode("utf-8")
# Convert string to dict
return json.loads(json_str)


@pytest.fixture
def wc_request():
Expand Down Expand Up @@ -74,3 +81,49 @@ def test_make_request(wc_request):
)
assert response.status_code == 200
assert response.content == b'{"key": "value"}'


def test_make_request_paginated(wc_request):
# Mocking httpx.Client.get for the paginated case
client = MagicMock()
client.__enter__.return_value = client
client.__exit__.return_value = False
client.get.side_effect = [
MockResponse(b'[{"foo": "bar"}, {"fizz": "buzz"}]', 200),
MockResponse(b"[]", 200),
]
wc_request.client = client

data = wc_request.paginated(
query_params={"param": "value"}, headers={"Authorization": "foo-bar"}
)

assert client.get.call_count == 2

calls = client.get.call_args_list
first_call = calls[0].kwargs
second_call = calls[1].kwargs

assert first_call["url"] == "https://example.com/consumer/orders/1"
assert first_call["headers"] == {
"Accept": "application/json",
"Authorization": "foo-bar",
}
assert first_call["params"] == {
"param": "value",
"per_page": WCRequest.DEFAULT_PAGE_LIMIT,
"page": 1,
}

assert second_call["url"] == "https://example.com/consumer/orders/1"
assert second_call["headers"] == {
"Accept": "application/json",
"Authorization": "foo-bar",
}
assert second_call["params"] == {
"param": "value",
"per_page": WCRequest.DEFAULT_PAGE_LIMIT,
"page": 2,
}

assert data == [{"foo": "bar"}, {"fizz": "buzz"}]
2 changes: 1 addition & 1 deletion wc_client/__init__.py
Original file line number Diff line number Diff line change
@@ -1,6 +1,6 @@
"""Small WooCommerce API Client"""

__version__ = "0.2.0"
__version__ = "0.2.1"

from .client import WCClient

Expand Down
35 changes: 33 additions & 2 deletions wc_client/request.py
Original file line number Diff line number Diff line change
@@ -1,4 +1,4 @@
from typing import Any, Dict
from typing import Any, Dict, List

import httpx

Expand All @@ -9,6 +9,7 @@ class WCRequest:
"""

METHODS = {"delete", "get", "patch", "post", "put"}
DEFAULT_PAGE_LIMIT = 20

def __init__(self, base_url: str, headers: Dict, *args):
"""
Expand Down Expand Up @@ -36,7 +37,6 @@ def _build_url(self) -> str:
Returns:
str: The URL for the request
"""
print(self._url_path)
return "/".join(self._url_path)

def _update_headers(self, headers):
Expand Down Expand Up @@ -83,5 +83,36 @@ def make_request(body=None, query_params=None, headers=None):

return make_request

elif resource == "paginated":

def make_request_paginated(query_params={}, headers=None) -> List[Dict]:
if headers:
self._update_headers(headers)

query_params["per_page"] = self.DEFAULT_PAGE_LIMIT
query_params["page"] = 1

data = []

with self.client as client:
while True:
res = client.get(
url=self._build_url(),
headers=self.headers,
params=query_params.copy(),
)

res_json = res.json()
data.extend(res_json)

if len(res_json) == 0:
break

query_params["page"] += 1

return data

return make_request_paginated

else:
return self._(resource)