From f05f552954dbf1e36d57fa8eaf26a2729af0cbd2 Mon Sep 17 00:00:00 2001 From: Aaron <7063649+ahcodedev@users.noreply.github.com> Date: Mon, 9 Nov 2026 16:01:53 -0800 Subject: [PATCH 1/3] Consolidate JSON data mocks --- tests/mocks/json.py | 200 +++++++++++++++++++++++++ tests/models/test_buyer.py | 12 +- tests/models/test_offer.py | 22 +-- tests/models/test_product_summary.py | 7 +- tests/requests/test_request.py | 16 +- tests/responses/test_offer_details.py | 43 +----- tests/responses/test_offer_end.py | 8 +- tests/responses/test_offer_feedback.py | 8 +- tests/responses/test_offer_publish.py | 23 +-- tests/responses/test_offer_refund.py | 8 +- tests/responses/test_offer_ship.py | 9 +- tests/responses/test_offers.py | 9 +- tests/responses/test_parse.py | 8 +- tests/responses/test_products.py | 24 +-- tests/test_asyncpricecharting.py | 21 +-- tests/test_pricecharting.py | 17 +-- 16 files changed, 227 insertions(+), 208 deletions(-) create mode 100644 tests/mocks/json.py diff --git a/tests/mocks/json.py b/tests/mocks/json.py new file mode 100644 index 0000000..73d7dbc --- /dev/null +++ b/tests/mocks/json.py @@ -0,0 +1,200 @@ +"""Shared JSON test data, in the API's kebab-case format.""" + +# Models + +BUYER_JSON = { + "buyer-email": "buyer@example.com", + "shipping-name": "Jane Doe", + "shipping-line1": "123 Main St", + "shipping-line2": "Apt 4", + "shipping-city": "Springfield", + "shipping-state": "IL", + "shipping-zip": "62701", + "shipping-country": "US", +} + + +OFFER_JSON = { + "offer-id": "smzksacsy5i2dsrddxsrlzsp6i", + "offer-status": "sold", + "offer-url": "/offer/smzksacsy5i2dsrddxsrlzsp6i", + "id": 9307, + "product-name": "M.C. Kids", + "console-name": "NES", + "condition-string": "Normal wear", + "include-string": "Game only", + "price": 1473, + "is-available": False, + "is-sold": True, + "is-ended": True, + "is-shipped": False, + "sale-time": "2017-10-31", + "shipped-time": "0001-01-01", + "ended-time": "2017-10-31", + "cert-id": "5672930123", + "grade-co-id": 1, +} + + +PRODUCT_SUMMARY_JSON = { + "id": "4801", + "product-name": "Tactics Ogre", + "console-name": "Playstation", +} + + +# Requests + +OFFER_PUBLISH_REQUEST_JSON = { + "product": "6910", + "price-max": 2500, + "price-min": 1500, + "condition-id": "1", + "cost-basis": 1000, + "broken": "on", + "sku": "ABC-123", + "quantity": 2, +} + + +# Responses + +OFFERS_JSON = { + "status": "success", + "offers": [ + {"offer-id": "smzksacsy5i2dsrddxsrlzsp6i", "offer-status": "sold", "price": 1473}, + {"offer-id": "vtdsww72uyslgooawzyyijsllm", "offer-status": "available", "price": 2500}, + ], +} + + +OFFER_DETAILS_JSON = { + "status": "success", + "buyer": { + "buyer-email": "buyer@example.com", + "shipping-name": "Jane Doe", + "shipping-line1": "123 Main St", + "shipping-city": "Springfield", + "shipping-state": "IL", + "shipping-zip": "62701", + "shipping-country": "US", + }, + "buyer-left-feedback": False, + "seller-left-feedback": True, + "id": 9307, + "product-name": "M.C. Kids", + "console-name": "NES", + "condition": "Normal wear", + "includes": "Game only", + "cost-basis": 500, + "price": 1473, + "max-price": 2000, + "min-price": 1000, + "shipping-premium": 0, + "has-pictures": True, + "is-collection": False, + "is-ended": True, + "is-price-descending": True, + "is-refunded": False, + "is-shipped": True, + "is-sold": True, + "offer-id": "smzksacsy5i2dsrddxsrlzsp6i", + "offer-status": "sold", + "offer-url": "/offer/smzksacsy5i2dsrddxsrlzsp6i", + "sku": "ABC-123", + "tracking-number": "901234567890000", + "start-time": "2017-10-01", + "sale-time": "2017-10-31", + "shipped-time": "2017-11-01", + "ended-time": "2017-10-31", + "refunded-time": "0001-01-01", +} + + +OFFER_END_JSON = { + "status": "success", + "offer-id": "vtdsww72uyslgooawzyyijsllm", + "is-ended": True, + "ended-time": "2017-10-31", +} + + +OFFER_FEEDBACK_JSON = { + "status": "success", + "offer-id": "vtdsww72uyslgooawzyyijsllm", + "rating": 2, + "comment": "Great buyer", +} + + +OFFER_PUBLISH_RESPONSE_JSON = { + "status": "success", + "offer-id": "vtdsww72uyslgooawzyyijsllm", + "offer-url": "/offer/vtdsww72uyslgooawzyyijsllm", + "offer-status": "available", + "product-name": "EarthBound", + "console-name": "Super Nintendo", + "condition-string": "Normal wear", + "include-string": "Game only", + "has-pictures": False, + "price": 2500, + "cost-basis": 1000, + "sku": "ABC-123", + "is-collection": False, + "quantity": 2, + "start-time": "2017-10-31", +} + + +OFFER_REFUND_JSON = { + "status": "success", + "offer-id": "vtdsww72uyslgooawzyyijsllm", + "is-refunded": True, + "refunded-time": "2017-10-31", +} + + +OFFER_SHIP_JSON = { + "status": "success", + "offer-id": "vtdsww72uyslgooawzyyijsllm", + "is-shipped": True, + "shipped-time": "2017-10-31", + "tracking-number": "901234567890000", +} + + +PRODUCTS_JSON = { + "status": "success", + "products": [ + PRODUCT_SUMMARY_JSON, + {"console-name": "GameBoy Advance", "id": "2611", "product-name": "Tactics Ogre"}, + ], +} + + +PRODUCT_BASIC_JSON = { + "status": "success", + "id": "6910", + "product-name": "EarthBound", + "console-name": "Super Nintendo", + "loose-price": 17244, + "cib-price": 42995, + "new-price": 53000, + "release-date": "1995-06-05", +} + + +PRODUCT_JSON = { + "status": "success", + "id": "6910", + "product-name": "EarthBound", + "console-name": "Super Nintendo", + "release-date": "1995-06-05", + "sales-volume": 120, + "loose-price": 17244, + "cib-price": 42995, + "new-price": 53000, + "bgs-10-price": 60000, + "condition-9-price": 9000, + "retail-loose-buy": 12000, +} diff --git a/tests/models/test_buyer.py b/tests/models/test_buyer.py index 4642fd0..0108213 100644 --- a/tests/models/test_buyer.py +++ b/tests/models/test_buyer.py @@ -1,17 +1,7 @@ import json from pypricecharting.models import Buyer - -BUYER_JSON = { - "buyer-email": "buyer@example.com", - "shipping-name": "Jane Doe", - "shipping-line1": "123 Main St", - "shipping-line2": "Apt 4", - "shipping-city": "Springfield", - "shipping-state": "IL", - "shipping-zip": "62701", - "shipping-country": "US", -} +from tests.mocks.json import BUYER_JSON def test_buyer_json_to_model(): diff --git a/tests/models/test_offer.py b/tests/models/test_offer.py index fcac5bb..6ef34f6 100644 --- a/tests/models/test_offer.py +++ b/tests/models/test_offer.py @@ -6,27 +6,7 @@ from pypricecharting.models import Offer from pypricecharting.types import OfferStatus - -OFFER_JSON = { - "offer-id": "smzksacsy5i2dsrddxsrlzsp6i", - "offer-status": "sold", - "offer-url": "/offer/smzksacsy5i2dsrddxsrlzsp6i", - "id": 9307, - "product-name": "M.C. Kids", - "console-name": "NES", - "condition-string": "Normal wear", - "include-string": "Game only", - "price": 1473, - "is-available": False, - "is-sold": True, - "is-ended": True, - "is-shipped": False, - "sale-time": "2017-10-31", - "shipped-time": "0001-01-01", - "ended-time": "2017-10-31", - "cert-id": "5672930123", - "grade-co-id": 1, -} +from tests.mocks.json import OFFER_JSON def test_offer_json_to_model(): diff --git a/tests/models/test_product_summary.py b/tests/models/test_product_summary.py index c801bd0..797a446 100644 --- a/tests/models/test_product_summary.py +++ b/tests/models/test_product_summary.py @@ -1,12 +1,7 @@ import json from pypricecharting.models import ProductSummary - -PRODUCT_SUMMARY_JSON = { - "id": "4801", - "product-name": "Tactics Ogre", - "console-name": "Playstation", -} +from tests.mocks.json import PRODUCT_SUMMARY_JSON def test_product_summary_json_to_model(): diff --git a/tests/requests/test_request.py b/tests/requests/test_request.py index 1853d74..32cbf30 100644 --- a/tests/requests/test_request.py +++ b/tests/requests/test_request.py @@ -5,21 +5,11 @@ from pypricecharting.requests import OfferPublishRequest from pypricecharting.types import State - -OFFER_PUBLISH_JSON = { - "product": "6910", - "price-max": 2500, - "price-min": 1500, - "condition-id": "1", - "cost-basis": 1000, - "broken": "on", - "sku": "ABC-123", - "quantity": 2, -} +from tests.mocks.json import OFFER_PUBLISH_REQUEST_JSON def test_offer_publish_json_to_model(): - request = OfferPublishRequest.model_validate_json(json.dumps(OFFER_PUBLISH_JSON)) + request = OfferPublishRequest.model_validate_json(json.dumps(OFFER_PUBLISH_REQUEST_JSON)) assert request.product == "6910" assert request.price_max == 2500 @@ -46,7 +36,7 @@ def test_offer_publish_model_to_json(): dumped = request.model_dump_json(by_alias=True, exclude_none=True) - assert json.loads(dumped) == OFFER_PUBLISH_JSON + assert json.loads(dumped) == OFFER_PUBLISH_REQUEST_JSON def test_offer_publish_model_raises(): diff --git a/tests/responses/test_offer_details.py b/tests/responses/test_offer_details.py index ffd7fc6..61eb2ec 100644 --- a/tests/responses/test_offer_details.py +++ b/tests/responses/test_offer_details.py @@ -4,48 +4,7 @@ from pypricecharting.models import Buyer from pypricecharting.responses import OfferDetailsResponse from pypricecharting.types import OfferStatus, Status - -OFFER_DETAILS_JSON = { - "status": "success", - "buyer": { - "buyer-email": "buyer@example.com", - "shipping-name": "Jane Doe", - "shipping-line1": "123 Main St", - "shipping-city": "Springfield", - "shipping-state": "IL", - "shipping-zip": "62701", - "shipping-country": "US", - }, - "buyer-left-feedback": False, - "seller-left-feedback": True, - "id": 9307, - "product-name": "M.C. Kids", - "console-name": "NES", - "condition": "Normal wear", - "includes": "Game only", - "cost-basis": 500, - "price": 1473, - "max-price": 2000, - "min-price": 1000, - "shipping-premium": 0, - "has-pictures": True, - "is-collection": False, - "is-ended": True, - "is-price-descending": True, - "is-refunded": False, - "is-shipped": True, - "is-sold": True, - "offer-id": "smzksacsy5i2dsrddxsrlzsp6i", - "offer-status": "sold", - "offer-url": "/offer/smzksacsy5i2dsrddxsrlzsp6i", - "sku": "ABC-123", - "tracking-number": "901234567890000", - "start-time": "2017-10-01", - "sale-time": "2017-10-31", - "shipped-time": "2017-11-01", - "ended-time": "2017-10-31", - "refunded-time": "0001-01-01", -} +from tests.mocks.json import OFFER_DETAILS_JSON def test_offer_details_json_to_model(): diff --git a/tests/responses/test_offer_end.py b/tests/responses/test_offer_end.py index 8f8d402..1807bb9 100644 --- a/tests/responses/test_offer_end.py +++ b/tests/responses/test_offer_end.py @@ -3,13 +3,7 @@ from pypricecharting.responses import OfferEndResponse from pypricecharting.types import Status - -OFFER_END_JSON = { - "status": "success", - "offer-id": "vtdsww72uyslgooawzyyijsllm", - "is-ended": True, - "ended-time": "2017-10-31", -} +from tests.mocks.json import OFFER_END_JSON def test_offer_end_json_to_model(): diff --git a/tests/responses/test_offer_feedback.py b/tests/responses/test_offer_feedback.py index ba45a70..40304eb 100644 --- a/tests/responses/test_offer_feedback.py +++ b/tests/responses/test_offer_feedback.py @@ -5,13 +5,7 @@ from pypricecharting.responses import OfferFeedbackResponse from pypricecharting.types import Rating, Status - -OFFER_FEEDBACK_JSON = { - "status": "success", - "offer-id": "vtdsww72uyslgooawzyyijsllm", - "rating": 2, - "comment": "Great buyer", -} +from tests.mocks.json import OFFER_FEEDBACK_JSON def test_offer_feedback_json_to_model(): diff --git a/tests/responses/test_offer_publish.py b/tests/responses/test_offer_publish.py index 58f1eda..5e8a5f0 100644 --- a/tests/responses/test_offer_publish.py +++ b/tests/responses/test_offer_publish.py @@ -3,28 +3,11 @@ from pypricecharting.responses import OfferPublishResponse from pypricecharting.types import OfferStatus, Status - -OFFER_PUBLISH_JSON = { - "status": "success", - "offer-id": "vtdsww72uyslgooawzyyijsllm", - "offer-url": "/offer/vtdsww72uyslgooawzyyijsllm", - "offer-status": "available", - "product-name": "EarthBound", - "console-name": "Super Nintendo", - "condition-string": "Normal wear", - "include-string": "Game only", - "has-pictures": False, - "price": 2500, - "cost-basis": 1000, - "sku": "ABC-123", - "is-collection": False, - "quantity": 2, - "start-time": "2017-10-31", -} +from tests.mocks.json import OFFER_PUBLISH_RESPONSE_JSON def test_offer_publish_json_to_model(): - response = OfferPublishResponse.model_validate_json(json.dumps(OFFER_PUBLISH_JSON)) + response = OfferPublishResponse.model_validate_json(json.dumps(OFFER_PUBLISH_RESPONSE_JSON)) assert response.status is Status.SUCCESS assert response.offer_id == "vtdsww72uyslgooawzyyijsllm" @@ -64,4 +47,4 @@ def test_offer_publish_model_to_json(): dumped = response.model_dump_json(by_alias=True, exclude_none=True) - assert json.loads(dumped) == OFFER_PUBLISH_JSON + assert json.loads(dumped) == OFFER_PUBLISH_RESPONSE_JSON diff --git a/tests/responses/test_offer_refund.py b/tests/responses/test_offer_refund.py index ec48080..877e5c3 100644 --- a/tests/responses/test_offer_refund.py +++ b/tests/responses/test_offer_refund.py @@ -3,13 +3,7 @@ from pypricecharting.responses import OfferRefundResponse from pypricecharting.types import Status - -OFFER_REFUND_JSON = { - "status": "success", - "offer-id": "vtdsww72uyslgooawzyyijsllm", - "is-refunded": True, - "refunded-time": "2017-10-31", -} +from tests.mocks.json import OFFER_REFUND_JSON def test_offer_refund_json_to_model(): diff --git a/tests/responses/test_offer_ship.py b/tests/responses/test_offer_ship.py index 7ead4c6..fd79844 100644 --- a/tests/responses/test_offer_ship.py +++ b/tests/responses/test_offer_ship.py @@ -3,14 +3,7 @@ from pypricecharting.responses import OfferShipResponse from pypricecharting.types import Status - -OFFER_SHIP_JSON = { - "status": "success", - "offer-id": "vtdsww72uyslgooawzyyijsllm", - "is-shipped": True, - "shipped-time": "2017-10-31", - "tracking-number": "901234567890000", -} +from tests.mocks.json import OFFER_SHIP_JSON def test_offer_ship_json_to_model(): diff --git a/tests/responses/test_offers.py b/tests/responses/test_offers.py index e53112b..f9f304a 100644 --- a/tests/responses/test_offers.py +++ b/tests/responses/test_offers.py @@ -3,14 +3,7 @@ from pypricecharting.models import Offer from pypricecharting.responses import OffersResponse from pypricecharting.types import OfferStatus, Status - -OFFERS_JSON = { - "status": "success", - "offers": [ - {"offer-id": "smzksacsy5i2dsrddxsrlzsp6i", "offer-status": "sold", "price": 1473}, - {"offer-id": "vtdsww72uyslgooawzyyijsllm", "offer-status": "available", "price": 2500}, - ], -} +from tests.mocks.json import OFFERS_JSON def test_offers_json_to_model(): diff --git a/tests/responses/test_parse.py b/tests/responses/test_parse.py index c65bdf2..aa867ee 100644 --- a/tests/responses/test_parse.py +++ b/tests/responses/test_parse.py @@ -6,13 +6,7 @@ from pypricecharting.error import APIError from pypricecharting.responses import OfferEndResponse, _parse from pypricecharting.types import Status - -OFFER_END_JSON = { - "status": "success", - "offer-id": "vtdsww72uyslgooawzyyijsllm", - "is-ended": True, - "ended-time": "2017-10-31", -} +from tests.mocks.json import OFFER_END_JSON def test_parse_success(): diff --git a/tests/responses/test_products.py b/tests/responses/test_products.py index 7baea4b..f88260e 100644 --- a/tests/responses/test_products.py +++ b/tests/responses/test_products.py @@ -4,29 +4,7 @@ from pypricecharting.models import ProductSummary from pypricecharting.responses import ProductResponse, ProductsResponse from pypricecharting.types import Status - -PRODUCT_JSON = { - "status": "success", - "id": "6910", - "product-name": "EarthBound", - "console-name": "Super Nintendo", - "release-date": "1995-06-05", - "sales-volume": 120, - "loose-price": 17244, - "cib-price": 42995, - "new-price": 53000, - "bgs-10-price": 60000, - "condition-9-price": 9000, - "retail-loose-buy": 12000, -} - -PRODUCTS_JSON = { - "status": "success", - "products": [ - {"console-name": "Playstation", "id": "4801", "product-name": "Tactics Ogre"}, - {"console-name": "GameBoy Advance", "id": "2611", "product-name": "Tactics Ogre"}, - ], -} +from tests.mocks.json import PRODUCT_JSON, PRODUCTS_JSON def test_product_json_to_model(): diff --git a/tests/test_asyncpricecharting.py b/tests/test_asyncpricecharting.py index 1194ee7..d051c3d 100644 --- a/tests/test_asyncpricecharting.py +++ b/tests/test_asyncpricecharting.py @@ -5,6 +5,7 @@ from pypricecharting.error import APIError, ParameterError from pypricecharting.responses import ProductResponse from pypricecharting.route import BASE_URL +from tests.mocks.json import PRODUCT_BASIC_JSON from tests.mocks.mock_pricecharting import mocked_async_client # Template tests: methods that are still placeholders only check they can be called. @@ -125,25 +126,15 @@ async def test_async_with_closes_http_client_on_error(): assert client._client.is_closed -PRODUCT_JSON = { - "status": "success", - "id": "6910", - "product-name": "EarthBound", - "console-name": "Super Nintendo", - "loose-price": 17244, - "cib-price": 42995, - "new-price": 53000, - "release-date": "1995-06-05", -} - - @pytest.mark.parametrize( ("kwargs", "param"), [({"id": "6910"}, "id"), ({"upc": "045496830434"}, "upc"), ({"q": "earthbound"}, "q")], ) async def test_product(kwargs, param): requests: list[Request] = [] - async with mocked_async_client(TOKEN, Response(200, json=PRODUCT_JSON), requests) as client: + async with mocked_async_client( + TOKEN, Response(200, json=PRODUCT_BASIC_JSON), requests + ) as client: product = await client.product(**kwargs) assert isinstance(product, ProductResponse) @@ -176,7 +167,9 @@ async def test_product_raises_for_invalid_parameters(): async def test_product_raises_for_multiple_parameters(): requests: list[Request] = [] - async with mocked_async_client(TOKEN, Response(200, json=PRODUCT_JSON), requests) as client: + async with mocked_async_client( + TOKEN, Response(200, json=PRODUCT_BASIC_JSON), requests + ) as client: with pytest.raises( ParameterError, match=r"Invalid parameters. Only one of id, upc, or q is allowed." ): diff --git a/tests/test_pricecharting.py b/tests/test_pricecharting.py index 286ef5e..86bfb3a 100644 --- a/tests/test_pricecharting.py +++ b/tests/test_pricecharting.py @@ -5,6 +5,7 @@ from pypricecharting.pricecharting import PriceCharting from pypricecharting.responses import ProductResponse from pypricecharting.route import BASE_URL +from tests.mocks.json import PRODUCT_BASIC_JSON from tests.mocks.mock_pricecharting import mocked_client # Template tests: methods that are still placeholders only check they can be called. @@ -122,25 +123,13 @@ def test_with_closes_http_client_on_error(): assert client._client.is_closed -PRODUCT_JSON = { - "status": "success", - "id": "6910", - "product-name": "EarthBound", - "console-name": "Super Nintendo", - "loose-price": 17244, - "cib-price": 42995, - "new-price": 53000, - "release-date": "1995-06-05", -} - - @pytest.mark.parametrize( ("kwargs", "param"), [({"id": "6910"}, "id"), ({"upc": "045496830434"}, "upc"), ({"q": "earthbound"}, "q")], ) def test_product(kwargs, param): requests: list[Request] = [] - with mocked_client(TOKEN, Response(200, json=PRODUCT_JSON), requests) as client: + with mocked_client(TOKEN, Response(200, json=PRODUCT_BASIC_JSON), requests) as client: product = client.product(**kwargs) assert isinstance(product, ProductResponse) @@ -178,7 +167,7 @@ def test_product_raises_for_invalid_parameters(): def test_product_raises_for_multiple_parameters(): requests: list[Request] = [] with ( - mocked_client(TOKEN, Response(200, json=PRODUCT_JSON), requests) as client, + mocked_client(TOKEN, Response(200, json=PRODUCT_BASIC_JSON), requests) as client, pytest.raises( ParameterError, match=r"Invalid parameters. Only one of id, upc, or q is allowed." ), From 85e69e3acb7256762c259a9cdfd4a1e8dd5a4ff4 Mon Sep 17 00:00:00 2001 From: Aaron <7063649+ahcodedev@users.noreply.github.com> Date: Mon, 9 Nov 2026 16:13:07 -0800 Subject: [PATCH 2/3] Restructure test files and mock data --- tests/mocks/mock_pricecharting.py | 3 + tests/test_asyncpricecharting.py | 110 +----------------- tests/test_asyncpricecharting_marketplace.py | 47 ++++++++ tests/test_asyncpricecharting_prices.py | 69 ++++++++++++ tests/test_auth.py | 2 +- tests/test_pricecharting.py | 112 +------------------ tests/test_pricecharting_marketplace.py | 47 ++++++++ tests/test_pricecharting_prices.py | 71 ++++++++++++ 8 files changed, 240 insertions(+), 221 deletions(-) create mode 100644 tests/test_asyncpricecharting_marketplace.py create mode 100644 tests/test_asyncpricecharting_prices.py create mode 100644 tests/test_pricecharting_marketplace.py create mode 100644 tests/test_pricecharting_prices.py diff --git a/tests/mocks/mock_pricecharting.py b/tests/mocks/mock_pricecharting.py index a75cdaa..4769e90 100644 --- a/tests/mocks/mock_pricecharting.py +++ b/tests/mocks/mock_pricecharting.py @@ -3,6 +3,9 @@ from pypricecharting.asyncpricecharting import AsyncPriceCharting from pypricecharting.pricecharting import PriceCharting +TOKEN = "test-token-12345678901234567890123456789" +"""A fake 40-character API token for tests.""" + def mocked_client(token: str | None, response: Response, requests: list[Request]) -> PriceCharting: """Create a `PriceCharting` client that records requests and returns `response`.""" diff --git a/tests/test_asyncpricecharting.py b/tests/test_asyncpricecharting.py index d051c3d..554fa4d 100644 --- a/tests/test_asyncpricecharting.py +++ b/tests/test_asyncpricecharting.py @@ -2,16 +2,8 @@ from httpx2 import AsyncClient, MockTransport, Request, Response from pypricecharting.asyncpricecharting import AsyncPriceCharting -from pypricecharting.error import APIError, ParameterError -from pypricecharting.responses import ProductResponse from pypricecharting.route import BASE_URL -from tests.mocks.json import PRODUCT_BASIC_JSON -from tests.mocks.mock_pricecharting import mocked_async_client - -# Template tests: methods that are still placeholders only check they can be called. -# Replace their `is None` assertions once each method is implemented. - -TOKEN = "test-token-12345678901234567890123456789" +from tests.mocks.mock_pricecharting import TOKEN def test_token_constant(): @@ -124,103 +116,3 @@ async def test_async_with_closes_http_client_on_error(): async with client: raise ValueError("boom") assert client._client.is_closed - - -@pytest.mark.parametrize( - ("kwargs", "param"), - [({"id": "6910"}, "id"), ({"upc": "045496830434"}, "upc"), ({"q": "earthbound"}, "q")], -) -async def test_product(kwargs, param): - requests: list[Request] = [] - async with mocked_async_client( - TOKEN, Response(200, json=PRODUCT_BASIC_JSON), requests - ) as client: - product = await client.product(**kwargs) - - assert isinstance(product, ProductResponse) - assert product.id == "6910" - assert product.product_name == "EarthBound" - assert product.cib_price == 42995 - - assert len(requests) == 1 - request = requests[0] - assert request.method == "GET" - assert request.url.path == "/api/product" - assert dict(request.url.params) == {param: kwargs[param], "t": TOKEN} - - -async def test_product_raises_api_error(): - body = {"status": "error", "error-message": "No such product"} - requests: list[Request] = [] - async with mocked_async_client(TOKEN, Response(404, json=body), requests) as client: - with pytest.raises(APIError, match="404: No such product"): - await client.product(id="0") - - -async def test_product_raises_for_invalid_parameters(): - async with AsyncPriceCharting(TOKEN) as client: - with pytest.raises( - ParameterError, match=r"Invalid parameters. Either id, upc, or q are required." - ): - await client.product() - - -async def test_product_raises_for_multiple_parameters(): - requests: list[Request] = [] - async with mocked_async_client( - TOKEN, Response(200, json=PRODUCT_BASIC_JSON), requests - ) as client: - with pytest.raises( - ParameterError, match=r"Invalid parameters. Only one of id, upc, or q is allowed." - ): - await client.product(id="6910", upc="045496830434") - - assert requests == [] - - -async def test_products(): - client = AsyncPriceCharting(TOKEN) - assert await client.products() is None - await client.aclose() - - -async def test_offers(): - client = AsyncPriceCharting(TOKEN) - assert await client.offers() is None - await client.aclose() - - -async def test_offer_details(): - client = AsyncPriceCharting(TOKEN) - assert await client.offer_details() is None - await client.aclose() - - -async def test_offer_publish(): - client = AsyncPriceCharting(TOKEN) - assert await client.offer_publish() is None - await client.aclose() - - -async def test_offer_feedback(): - client = AsyncPriceCharting(TOKEN) - assert await client.offer_feedback() is None - await client.aclose() - - -async def test_offer_ship(): - client = AsyncPriceCharting(TOKEN) - assert await client.offer_ship() is None - await client.aclose() - - -async def test_offer_end(): - client = AsyncPriceCharting(TOKEN) - assert await client.offer_end() is None - await client.aclose() - - -async def test_offer_refund(): - client = AsyncPriceCharting(TOKEN) - assert await client.offer_refund() is None - await client.aclose() diff --git a/tests/test_asyncpricecharting_marketplace.py b/tests/test_asyncpricecharting_marketplace.py new file mode 100644 index 0000000..66c2cd7 --- /dev/null +++ b/tests/test_asyncpricecharting_marketplace.py @@ -0,0 +1,47 @@ +from pypricecharting.asyncpricecharting import AsyncPriceCharting +from tests.mocks.mock_pricecharting import TOKEN + +# Template tests: methods that are still placeholders only check they can be called. +# Replace their `is None` assertions once each method is implemented. + + +async def test_offers(): + client = AsyncPriceCharting(TOKEN) + assert await client.offers() is None + await client.aclose() + + +async def test_offer_details(): + client = AsyncPriceCharting(TOKEN) + assert await client.offer_details() is None + await client.aclose() + + +async def test_offer_publish(): + client = AsyncPriceCharting(TOKEN) + assert await client.offer_publish() is None + await client.aclose() + + +async def test_offer_feedback(): + client = AsyncPriceCharting(TOKEN) + assert await client.offer_feedback() is None + await client.aclose() + + +async def test_offer_ship(): + client = AsyncPriceCharting(TOKEN) + assert await client.offer_ship() is None + await client.aclose() + + +async def test_offer_end(): + client = AsyncPriceCharting(TOKEN) + assert await client.offer_end() is None + await client.aclose() + + +async def test_offer_refund(): + client = AsyncPriceCharting(TOKEN) + assert await client.offer_refund() is None + await client.aclose() diff --git a/tests/test_asyncpricecharting_prices.py b/tests/test_asyncpricecharting_prices.py new file mode 100644 index 0000000..8bd2655 --- /dev/null +++ b/tests/test_asyncpricecharting_prices.py @@ -0,0 +1,69 @@ +import pytest +from httpx2 import Request, Response + +from pypricecharting.asyncpricecharting import AsyncPriceCharting +from pypricecharting.error import APIError, ParameterError +from pypricecharting.responses import ProductResponse +from tests.mocks.json import PRODUCT_BASIC_JSON +from tests.mocks.mock_pricecharting import TOKEN, mocked_async_client + +# Template tests: methods that are still placeholders only check they can be called. +# Replace their `is None` assertions once each method is implemented. + + +@pytest.mark.parametrize( + ("kwargs", "param"), + [({"id": "6910"}, "id"), ({"upc": "045496830434"}, "upc"), ({"q": "earthbound"}, "q")], +) +async def test_product(kwargs, param): + requests: list[Request] = [] + async with mocked_async_client( + TOKEN, Response(200, json=PRODUCT_BASIC_JSON), requests + ) as client: + product = await client.product(**kwargs) + + assert isinstance(product, ProductResponse) + assert product.id == "6910" + assert product.product_name == "EarthBound" + assert product.cib_price == 42995 + + assert len(requests) == 1 + request = requests[0] + assert request.method == "GET" + assert request.url.path == "/api/product" + assert dict(request.url.params) == {param: kwargs[param], "t": TOKEN} + + +async def test_product_raises_api_error(): + body = {"status": "error", "error-message": "No such product"} + requests: list[Request] = [] + async with mocked_async_client(TOKEN, Response(404, json=body), requests) as client: + with pytest.raises(APIError, match="404: No such product"): + await client.product(id="0") + + +async def test_product_raises_for_invalid_parameters(): + async with AsyncPriceCharting(TOKEN) as client: + with pytest.raises( + ParameterError, match=r"Invalid parameters. Either id, upc, or q are required." + ): + await client.product() + + +async def test_product_raises_for_multiple_parameters(): + requests: list[Request] = [] + async with mocked_async_client( + TOKEN, Response(200, json=PRODUCT_BASIC_JSON), requests + ) as client: + with pytest.raises( + ParameterError, match=r"Invalid parameters. Only one of id, upc, or q is allowed." + ): + await client.product(id="6910", upc="045496830434") + + assert requests == [] + + +async def test_products(): + client = AsyncPriceCharting(TOKEN) + assert await client.products() is None + await client.aclose() diff --git a/tests/test_auth.py b/tests/test_auth.py index 081e37d..64dba21 100644 --- a/tests/test_auth.py +++ b/tests/test_auth.py @@ -7,8 +7,8 @@ from pypricecharting import AsyncPriceCharting, PriceCharting from pypricecharting._auth import _REDACT_FILTER, _RedactTokenFilter, _TokenAuth +from tests.mocks.mock_pricecharting import TOKEN -TOKEN = "test-token-12345678901234567890123456789" URL = "https://example.com/api/product" diff --git a/tests/test_pricecharting.py b/tests/test_pricecharting.py index 86bfb3a..3ee6214 100644 --- a/tests/test_pricecharting.py +++ b/tests/test_pricecharting.py @@ -1,17 +1,9 @@ import pytest from httpx2 import Client, MockTransport, Request, Response -from pypricecharting.error import APIError, ParameterError from pypricecharting.pricecharting import PriceCharting -from pypricecharting.responses import ProductResponse from pypricecharting.route import BASE_URL -from tests.mocks.json import PRODUCT_BASIC_JSON -from tests.mocks.mock_pricecharting import mocked_client - -# Template tests: methods that are still placeholders only check they can be called. -# Replace their `is None` assertions once each method is implemented. - -TOKEN = "test-token-12345678901234567890123456789" +from tests.mocks.mock_pricecharting import TOKEN def test_token_constant(): @@ -121,105 +113,3 @@ def test_with_closes_http_client_on_error(): with pytest.raises(ValueError, match="boom"), client: raise ValueError("boom") assert client._client.is_closed - - -@pytest.mark.parametrize( - ("kwargs", "param"), - [({"id": "6910"}, "id"), ({"upc": "045496830434"}, "upc"), ({"q": "earthbound"}, "q")], -) -def test_product(kwargs, param): - requests: list[Request] = [] - with mocked_client(TOKEN, Response(200, json=PRODUCT_BASIC_JSON), requests) as client: - product = client.product(**kwargs) - - assert isinstance(product, ProductResponse) - assert product.id == "6910" - assert product.product_name == "EarthBound" - assert product.cib_price == 42995 - - assert len(requests) == 1 - request = requests[0] - assert request.method == "GET" - assert request.url.path == "/api/product" - assert dict(request.url.params) == {param: kwargs[param], "t": TOKEN} - - -def test_product_raises_api_error(): - body = {"status": "error", "error-message": "No such product"} - requests: list[Request] = [] - with ( - mocked_client(TOKEN, Response(404, json=body), requests) as client, - pytest.raises(APIError, match="404: No such product"), - ): - client.product(id="0") - - -def test_product_raises_for_invalid_parameters(): - with ( - PriceCharting(TOKEN) as client, - pytest.raises( - ParameterError, match=r"Invalid parameters. Either id, upc, or q are required." - ), - ): - client.product() - - -def test_product_raises_for_multiple_parameters(): - requests: list[Request] = [] - with ( - mocked_client(TOKEN, Response(200, json=PRODUCT_BASIC_JSON), requests) as client, - pytest.raises( - ParameterError, match=r"Invalid parameters. Only one of id, upc, or q is allowed." - ), - ): - client.product(id="6910", upc="045496830434") - - assert requests == [] - - -def test_products(): - client = PriceCharting(TOKEN) - assert client.products() is None - client.close() - - -def test_offers(): - client = PriceCharting(TOKEN) - assert client.offers() is None - client.close() - - -def test_offer_details(): - client = PriceCharting(TOKEN) - assert client.offer_details() is None - client.close() - - -def test_offer_publish(): - client = PriceCharting(TOKEN) - assert client.offer_publish() is None - client.close() - - -def test_offer_feedback(): - client = PriceCharting(TOKEN) - assert client.offer_feedback() is None - client.close() - - -def test_offer_ship(): - client = PriceCharting(TOKEN) - assert client.offer_ship() is None - client.close() - - -def test_offer_end(): - client = PriceCharting(TOKEN) - assert client.offer_end() is None - client.close() - - -def test_offer_refund(): - client = PriceCharting(TOKEN) - assert client.offer_refund() is None - client.close() diff --git a/tests/test_pricecharting_marketplace.py b/tests/test_pricecharting_marketplace.py new file mode 100644 index 0000000..319b161 --- /dev/null +++ b/tests/test_pricecharting_marketplace.py @@ -0,0 +1,47 @@ +from pypricecharting.pricecharting import PriceCharting +from tests.mocks.mock_pricecharting import TOKEN + +# Template tests: methods that are still placeholders only check they can be called. +# Replace their `is None` assertions once each method is implemented. + + +def test_offers(): + client = PriceCharting(TOKEN) + assert client.offers() is None + client.close() + + +def test_offer_details(): + client = PriceCharting(TOKEN) + assert client.offer_details() is None + client.close() + + +def test_offer_publish(): + client = PriceCharting(TOKEN) + assert client.offer_publish() is None + client.close() + + +def test_offer_feedback(): + client = PriceCharting(TOKEN) + assert client.offer_feedback() is None + client.close() + + +def test_offer_ship(): + client = PriceCharting(TOKEN) + assert client.offer_ship() is None + client.close() + + +def test_offer_end(): + client = PriceCharting(TOKEN) + assert client.offer_end() is None + client.close() + + +def test_offer_refund(): + client = PriceCharting(TOKEN) + assert client.offer_refund() is None + client.close() diff --git a/tests/test_pricecharting_prices.py b/tests/test_pricecharting_prices.py new file mode 100644 index 0000000..0febd70 --- /dev/null +++ b/tests/test_pricecharting_prices.py @@ -0,0 +1,71 @@ +import pytest +from httpx2 import Request, Response + +from pypricecharting.error import APIError, ParameterError +from pypricecharting.pricecharting import PriceCharting +from pypricecharting.responses import ProductResponse +from tests.mocks.json import PRODUCT_BASIC_JSON +from tests.mocks.mock_pricecharting import TOKEN, mocked_client + +# Template tests: methods that are still placeholders only check they can be called. +# Replace their `is None` assertions once each method is implemented. + + +@pytest.mark.parametrize( + ("kwargs", "param"), + [({"id": "6910"}, "id"), ({"upc": "045496830434"}, "upc"), ({"q": "earthbound"}, "q")], +) +def test_product(kwargs, param): + requests: list[Request] = [] + with mocked_client(TOKEN, Response(200, json=PRODUCT_BASIC_JSON), requests) as client: + product = client.product(**kwargs) + + assert isinstance(product, ProductResponse) + assert product.id == "6910" + assert product.product_name == "EarthBound" + assert product.cib_price == 42995 + + assert len(requests) == 1 + request = requests[0] + assert request.method == "GET" + assert request.url.path == "/api/product" + assert dict(request.url.params) == {param: kwargs[param], "t": TOKEN} + + +def test_product_raises_api_error(): + body = {"status": "error", "error-message": "No such product"} + requests: list[Request] = [] + with ( + mocked_client(TOKEN, Response(404, json=body), requests) as client, + pytest.raises(APIError, match="404: No such product"), + ): + client.product(id="0") + + +def test_product_raises_for_invalid_parameters(): + with ( + PriceCharting(TOKEN) as client, + pytest.raises( + ParameterError, match=r"Invalid parameters. Either id, upc, or q are required." + ), + ): + client.product() + + +def test_product_raises_for_multiple_parameters(): + requests: list[Request] = [] + with ( + mocked_client(TOKEN, Response(200, json=PRODUCT_BASIC_JSON), requests) as client, + pytest.raises( + ParameterError, match=r"Invalid parameters. Only one of id, upc, or q is allowed." + ), + ): + client.product(id="6910", upc="045496830434") + + assert requests == [] + + +def test_products(): + client = PriceCharting(TOKEN) + assert client.products() is None + client.close() From 765122dbae77c04985f8d7a04e3476cf358728d2 Mon Sep 17 00:00:00 2001 From: Aaron <7063649+ahcodedev@users.noreply.github.com> Date: Mon, 9 Nov 2026 16:28:16 -0800 Subject: [PATCH 3/3] Add ErrorResponse --- src/pypricecharting/__init__.py | 2 ++ src/pypricecharting/responses.py | 30 ++++++++++++++++++++----- tests/mocks/json.py | 2 ++ tests/mocks/mock_pricecharting.py | 9 ++++++++ tests/responses/test_error_response.py | 26 +++++++++++++++++++++ tests/responses/test_parse.py | 17 +++++++------- tests/test_asyncpricecharting_prices.py | 4 ++-- tests/test_pricecharting_prices.py | 4 ++-- 8 files changed, 76 insertions(+), 18 deletions(-) create mode 100644 tests/responses/test_error_response.py diff --git a/src/pypricecharting/__init__.py b/src/pypricecharting/__init__.py index ae2927f..3155302 100644 --- a/src/pypricecharting/__init__.py +++ b/src/pypricecharting/__init__.py @@ -4,6 +4,7 @@ from pypricecharting.pricecharting import PriceCharting from pypricecharting.requests import OfferPublishRequest from pypricecharting.responses import ( + ErrorResponse, OfferDetailsResponse, OfferEndResponse, OfferFeedbackResponse, @@ -38,6 +39,7 @@ "Comics", "Condition", "Console", + "ErrorResponse", "Genre", "Offer", "OfferDetailsResponse", diff --git a/src/pypricecharting/responses.py b/src/pypricecharting/responses.py index 0c92e52..33752e2 100644 --- a/src/pypricecharting/responses.py +++ b/src/pypricecharting/responses.py @@ -1,13 +1,28 @@ +from contextlib import suppress from datetime import date from httpx2 import Response -from pydantic import Field +from pydantic import Field, ValidationError from pypricecharting.error import APIError from pypricecharting.models import Buyer, Offer, PriceChartingModel, ProductSummary from pypricecharting.types import OfferStatus, Rating, Status +class ErrorResponse(PriceChartingModel): + """Error response from any endpoint + + Returned with a 4xx or 5xx status code and `status: error`. The clients raise + `error.APIError` with the message instead of returning this model. + + https://www.pricecharting.com/api-documentation + """ + + status: Status + error_message: str | None = None + """Why the request failed.""" + + class ProductResponse(ProductSummary): """api/product response @@ -255,8 +270,9 @@ def _parse[M: PriceChartingModel](response: Response, model: type[M]) -> M: The validated response model. Raises: - APIError: If the response is not JSON, has a non-2xx status code, or has - `status: error`. + APIError: If the response is not JSON or has a non-2xx status code. The message is + the `error-message` from the body, parsed as an `ErrorResponse`, or the HTTP + reason phrase if the body has none. """ try: @@ -266,8 +282,10 @@ def _parse[M: PriceChartingModel](response: Response, model: type[M]) -> M: response.reason_phrase or "Invalid JSON response", response.status_code ) from None - if not response.is_success or data.get("status") == "error": - message = data.get("error-message", response.reason_phrase or "Unknown error") - raise APIError(message, response.status_code) + if not response.is_success: + message = None + with suppress(ValidationError): + message = ErrorResponse.model_validate(data).error_message + raise APIError(message or response.reason_phrase or "Unknown error", response.status_code) return model.model_validate(data) diff --git a/tests/mocks/json.py b/tests/mocks/json.py index 73d7dbc..3debd1a 100644 --- a/tests/mocks/json.py +++ b/tests/mocks/json.py @@ -59,6 +59,8 @@ # Responses +ERROR_JSON = {"status": "error", "error-message": "No such product"} + OFFERS_JSON = { "status": "success", "offers": [ diff --git a/tests/mocks/mock_pricecharting.py b/tests/mocks/mock_pricecharting.py index 4769e90..5e39f36 100644 --- a/tests/mocks/mock_pricecharting.py +++ b/tests/mocks/mock_pricecharting.py @@ -2,6 +2,8 @@ from pypricecharting.asyncpricecharting import AsyncPriceCharting from pypricecharting.pricecharting import PriceCharting +from pypricecharting.responses import ErrorResponse +from pypricecharting.types import Status TOKEN = "test-token-12345678901234567890123456789" """A fake 40-character API token for tests.""" @@ -27,3 +29,10 @@ def handler(request: Request) -> Response: return response return AsyncPriceCharting(token=token, transport=MockTransport(handler)) + + +def error_body(message: str | None = None) -> dict: + """Build an API error response body in JSON form, with an optional `error-message`.""" + return ErrorResponse(status=Status.ERROR, error_message=message).model_dump( + mode="json", by_alias=True, exclude_none=True + ) diff --git a/tests/responses/test_error_response.py b/tests/responses/test_error_response.py new file mode 100644 index 0000000..16eabf4 --- /dev/null +++ b/tests/responses/test_error_response.py @@ -0,0 +1,26 @@ +import json + +from pypricecharting.responses import ErrorResponse +from pypricecharting.types import Status +from tests.mocks.json import ERROR_JSON + + +def test_error_json_to_model(): + response = ErrorResponse.model_validate_json(json.dumps(ERROR_JSON)) + + assert response.status is Status.ERROR + assert response.error_message == "No such product" + + +def test_error_model_to_json(): + response = ErrorResponse(status=Status.ERROR, error_message="No such product") + + dumped = response.model_dump_json(by_alias=True, exclude_none=True) + + assert json.loads(dumped) == ERROR_JSON + + +def test_error_message_defaults_to_none(): + response = ErrorResponse.model_validate_json('{"status": "error"}') + + assert response.error_message is None diff --git a/tests/responses/test_parse.py b/tests/responses/test_parse.py index aa867ee..4b2b224 100644 --- a/tests/responses/test_parse.py +++ b/tests/responses/test_parse.py @@ -7,6 +7,7 @@ from pypricecharting.responses import OfferEndResponse, _parse from pypricecharting.types import Status from tests.mocks.json import OFFER_END_JSON +from tests.mocks.mock_pricecharting import error_body def test_parse_success(): @@ -20,7 +21,7 @@ def test_parse_success(): def test_parse_error_status_code(): - body = {"status": "error", "error-message": "No such offer"} + body = error_body("No such offer") with pytest.raises(APIError, match="404: No such offer") as exc_info: _parse(Response(404, json=body), OfferEndResponse) @@ -29,16 +30,16 @@ def test_parse_error_status_code(): assert exc_info.value.status_code == 404 -def test_parse_error_status_with_success_code(): - body = {"status": "error", "error-message": "Offer already ended"} +def test_parse_error_without_message_uses_reason_phrase(): + body = error_body() - with pytest.raises(APIError, match="200: Offer already ended"): - _parse(Response(200, json=body), OfferEndResponse) + with pytest.raises(APIError, match="400: Bad Request"): + _parse(Response(400, json=body), OfferEndResponse) -def test_parse_error_without_message_uses_reason_phrase(): - with pytest.raises(APIError, match="400: Bad Request"): - _parse(Response(400, json={"status": "error"}), OfferEndResponse) +def test_parse_error_body_without_status_uses_reason_phrase(): + with pytest.raises(APIError, match="503: Service Unavailable"): + _parse(Response(503, json={"detail": "maintenance"}), OfferEndResponse) def test_parse_non_json_response(): diff --git a/tests/test_asyncpricecharting_prices.py b/tests/test_asyncpricecharting_prices.py index 8bd2655..80376b0 100644 --- a/tests/test_asyncpricecharting_prices.py +++ b/tests/test_asyncpricecharting_prices.py @@ -5,7 +5,7 @@ from pypricecharting.error import APIError, ParameterError from pypricecharting.responses import ProductResponse from tests.mocks.json import PRODUCT_BASIC_JSON -from tests.mocks.mock_pricecharting import TOKEN, mocked_async_client +from tests.mocks.mock_pricecharting import TOKEN, error_body, mocked_async_client # Template tests: methods that are still placeholders only check they can be called. # Replace their `is None` assertions once each method is implemented. @@ -35,7 +35,7 @@ async def test_product(kwargs, param): async def test_product_raises_api_error(): - body = {"status": "error", "error-message": "No such product"} + body = error_body("No such product") requests: list[Request] = [] async with mocked_async_client(TOKEN, Response(404, json=body), requests) as client: with pytest.raises(APIError, match="404: No such product"): diff --git a/tests/test_pricecharting_prices.py b/tests/test_pricecharting_prices.py index 0febd70..ea42b47 100644 --- a/tests/test_pricecharting_prices.py +++ b/tests/test_pricecharting_prices.py @@ -5,7 +5,7 @@ from pypricecharting.pricecharting import PriceCharting from pypricecharting.responses import ProductResponse from tests.mocks.json import PRODUCT_BASIC_JSON -from tests.mocks.mock_pricecharting import TOKEN, mocked_client +from tests.mocks.mock_pricecharting import TOKEN, error_body, mocked_client # Template tests: methods that are still placeholders only check they can be called. # Replace their `is None` assertions once each method is implemented. @@ -33,7 +33,7 @@ def test_product(kwargs, param): def test_product_raises_api_error(): - body = {"status": "error", "error-message": "No such product"} + body = error_body("No such product") requests: list[Request] = [] with ( mocked_client(TOKEN, Response(404, json=body), requests) as client,