From 7ace0ec253e3ef4125e164e35a6701991b848a46 Mon Sep 17 00:00:00 2001 From: Aaron <7063649+ahcodedev@users.noreply.github.com> Date: Mon, 9 Nov 2026 15:23:26 -0800 Subject: [PATCH] Update clients and add product endpoint support --- README.md | 21 +++- docs/api/errors.md | 3 + docs/index.md | 74 +++++++++++- mkdocs.yml | 1 + pyproject.toml | 2 + src/pypricecharting/__init__.py | 62 ++++++++++- src/pypricecharting/asyncpricecharting.py | 55 +++++++-- src/pypricecharting/error.py | 16 +++ src/pypricecharting/pricecharting.py | 53 +++++++-- src/pypricecharting/responses.py | 31 ++++++ tests/mocks/mock_pricecharting.py | 26 +++++ tests/responses/test_parse.py | 52 +++++++++ tests/test_asyncpricecharting.py | 122 +++++++++++++++++--- tests/test_error.py | 23 ++++ tests/test_init.py | 37 ++++++ tests/test_pricecharting.py | 130 +++++++++++++++++++--- 16 files changed, 658 insertions(+), 50 deletions(-) create mode 100644 docs/api/errors.md create mode 100644 src/pypricecharting/error.py create mode 100644 tests/mocks/mock_pricecharting.py create mode 100644 tests/responses/test_parse.py create mode 100644 tests/test_error.py create mode 100644 tests/test_init.py diff --git a/README.md b/README.md index 583c0cd..ef708a8 100644 --- a/README.md +++ b/README.md @@ -1,6 +1,13 @@ -# PyPriceCharting API Client ![](https://github.com/ahcodedev/pypricecharting/actions/workflows/python.yml/badge.svg?branch=main) +# PyPriceCharting API Client + +[![CI](https://github.com/ahcodedev/pypricecharting/actions/workflows/python.yml/badge.svg?branch=main)](https://github.com/ahcodedev/pypricecharting/actions/workflows/python.yml) +[![Docs](https://github.com/ahcodedev/pypricecharting/actions/workflows/docs.yml/badge.svg?branch=main)](https://github.com/ahcodedev/pypricecharting/actions/workflows/docs.yml) [![Security](https://github.com/ahcodedev/pypricecharting/actions/workflows/security.yml/badge.svg?branch=main)](https://github.com/ahcodedev/pypricecharting/actions/workflows/security.yml) [![gitleaks](https://img.shields.io/badge/protected%20by-gitleaks-blue)](https://github.com/gitleaks/gitleaks) +[![uv](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/uv/main/assets/badge/v0.json)](https://github.com/astral-sh/uv) +[![Ruff](https://img.shields.io/endpoint?url=https://raw.githubusercontent.com/astral-sh/ruff/main/assets/badge/v2.json)](https://github.com/astral-sh/ruff) +![Python](https://img.shields.io/badge/python-3.15-blue) +[![License: MIT](https://img.shields.io/badge/license-MIT-green)](LICENSE) PriceCharting API Client written in Python @@ -65,19 +72,23 @@ See [RELEASE.md](RELEASE.md) for how releases and release labels work. ## Usage -The client is under development. `PriceCharting` and `AsyncPriceCharting` can be created and used -as context managers, but their API methods are not implemented yet. +The client is under development. `product` is implemented on both clients; the other API methods +are not implemented yet. ```python from pypricecharting import AsyncPriceCharting, PriceCharting with PriceCharting("<40-character API token>") as client: - ... + game = client.product(id="6910") + print(game.product_name, game.cib_price) # prices are in pennies async with AsyncPriceCharting("<40-character API token>") as client: - ... + game = await client.product(q="earthbound") ``` +If the token is omitted, it is read from the `PRICECHARTING_TOKEN` environment variable. See the +docs site for errors and client options. + ## Supporting Files Project contains an OpenAPI spec and a Bruno project for easy testing and mocking diff --git a/docs/api/errors.md b/docs/api/errors.md new file mode 100644 index 0000000..3b8f068 --- /dev/null +++ b/docs/api/errors.md @@ -0,0 +1,3 @@ +# Errors + +::: pypricecharting.error diff --git a/docs/index.md b/docs/index.md index 96c40b4..7a9d439 100644 --- a/docs/index.md +++ b/docs/index.md @@ -5,8 +5,8 @@ Python client for the [PriceCharting API](https://www.pricecharting.com/api-docu The package provides a synchronous client, `PriceCharting`, and an asynchronous client, `AsyncPriceCharting`. Both authenticate with a 40-character PriceCharting API token. -The client is under development: the clients can be created and used as context managers, but -their API methods are not implemented yet. +The client is under development: `product` is implemented on both clients, and the other API +methods are not implemented yet. ## Authentication @@ -30,6 +30,76 @@ with PriceCharting("your-40-character-token") as client: The environment variable is recommended, because it keeps the token out of your code. Both clients raise `ValueError` if no token is found or the token is not 40 characters. +## Getting a product + +`product` looks up a single product by exactly one of `id` (PriceCharting product ID), `upc` +(UPC barcode), or `q` (full text search, best match only): + +```python +from pypricecharting import AsyncPriceCharting, PriceCharting + +with PriceCharting() as client: + game = client.product(id="6910") + print(game.product_name, game.cib_price) # EarthBound 42995 + +async with AsyncPriceCharting() as client: + game = await client.product(upc="045496830434") +``` + +Prices are integer pennies, so `42995` is $429.95. + +Create one client and reuse it for all your requests, so they share a connection pool. Close it +when you are done, either with a `with` block or by calling `close()` (`aclose()` for the async +client). + +## Errors + +All errors subclass `PriceChartingError` and can be imported from `pypricecharting`: + +- `ParameterError` (also a `ValueError`) is raised before any request is sent when a method gets + invalid parameters, such as `product()` with none or more than one of `id`, `upc`, and `q`. +- `APIError` is raised when the API returns an error. It has the API's `message` and the HTTP + `status_code`. + +```python +from pypricecharting import APIError + +try: + game = client.product(id="0") +except APIError as error: + print(error.status_code, error.message) +``` + +## Client options + +Both clients accept two optional arguments, mainly for testing: + +- `base_url` sends requests to another server, such as a local mock server. It defaults to + `https://www.pricecharting.com`. +- `transport` replaces the `httpx2` transport that sends requests, such as + `httpx2.MockTransport`. + +```python +from httpx2 import MockTransport, Response + +client = PriceCharting( + base_url="http://localhost:8080", + transport=MockTransport(lambda request: Response(200, json={"status": "success"})), +) +``` + +## Imports + +Everything public can be imported from `pypricecharting` directly: the clients, the errors, the +request and response models, the shared models (`ProductSummary`, `Offer`, `Buyer`), and the enums +in `types` (`Condition`, `Console`, `Genre`, `Status`, and others): + +```python +from pypricecharting import Condition, PriceCharting, ProductResponse +``` + +They can also be imported from their own modules, such as `pypricecharting.responses`. + ## Security The PriceCharting API requires the token in the query string of `GET` requests, so it is part of diff --git a/mkdocs.yml b/mkdocs.yml index 6cf1512..75f450b 100644 --- a/mkdocs.yml +++ b/mkdocs.yml @@ -46,4 +46,5 @@ nav: - Requests: api/requests.md - Responses: api/responses.md - Types: api/types.md + - Errors: api/errors.md - Routes: api/route.md diff --git a/pyproject.toml b/pyproject.toml index d8b667d..2ac53a6 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -3,6 +3,8 @@ name = "pypricecharting" description = "Python PriceCharting API Client" version = "0.0.1" requires-python = ">=3.15" +license = "MIT" +license-files = ["LICENSE"] dependencies = [ "httpx2>=2.16.0", diff --git a/src/pypricecharting/__init__.py b/src/pypricecharting/__init__.py index 4631696..ae2927f 100644 --- a/src/pypricecharting/__init__.py +++ b/src/pypricecharting/__init__.py @@ -1,4 +1,64 @@ from pypricecharting.asyncpricecharting import AsyncPriceCharting +from pypricecharting.error import APIError, ParameterError, PriceChartingError +from pypricecharting.models import Buyer, Offer, PriceChartingModel, ProductSummary from pypricecharting.pricecharting import PriceCharting +from pypricecharting.requests import OfferPublishRequest +from pypricecharting.responses import ( + OfferDetailsResponse, + OfferEndResponse, + OfferFeedbackResponse, + OfferPublishResponse, + OfferRefundResponse, + OfferShipResponse, + OffersResponse, + ProductResponse, + ProductsResponse, +) +from pypricecharting.types import ( + Cards, + Coins, + Comics, + Condition, + Console, + Genre, + OfferStatus, + RateLimit, + Rating, + State, + Status, + VideoGames, +) -__all__ = ["AsyncPriceCharting", "PriceCharting"] +__all__ = [ + "APIError", + "AsyncPriceCharting", + "Buyer", + "Cards", + "Coins", + "Comics", + "Condition", + "Console", + "Genre", + "Offer", + "OfferDetailsResponse", + "OfferEndResponse", + "OfferFeedbackResponse", + "OfferPublishRequest", + "OfferPublishResponse", + "OfferRefundResponse", + "OfferShipResponse", + "OfferStatus", + "OffersResponse", + "ParameterError", + "PriceCharting", + "PriceChartingError", + "PriceChartingModel", + "ProductResponse", + "ProductSummary", + "ProductsResponse", + "RateLimit", + "Rating", + "State", + "Status", + "VideoGames", +] diff --git a/src/pypricecharting/asyncpricecharting.py b/src/pypricecharting/asyncpricecharting.py index 46a14e7..fd8fac7 100644 --- a/src/pypricecharting/asyncpricecharting.py +++ b/src/pypricecharting/asyncpricecharting.py @@ -3,10 +3,13 @@ from types import TracebackType from typing import Self -from httpx2 import AsyncClient +from httpx2 import AsyncBaseTransport, AsyncClient from pydantic import SecretStr from pypricecharting._auth import _REDACT_FILTER, _TokenAuth +from pypricecharting.error import ParameterError +from pypricecharting.responses import ProductResponse, _parse +from pypricecharting.route import BASE_URL, Prices class AsyncPriceCharting: @@ -14,7 +17,12 @@ class AsyncPriceCharting: TOKEN_KEY = "PRICECHARTING_TOKEN" - def __init__(self, token: str | None = None): + def __init__( + self, + token: str | None = None, + base_url: str = BASE_URL, + transport: AsyncBaseTransport | None = None, + ): """Create a client authenticated with a PriceCharting API token. The client adds a logging filter to the `httpx2` logger that replaces the token in @@ -23,6 +31,11 @@ def __init__(self, token: str | None = None): Args: token: The 40-character PriceCharting API token. If omitted, it is read from the `PRICECHARTING_TOKEN` environment variable. + base_url: The API base URL. Defaults to `route.BASE_URL`. Override it to send + requests to another server, such as a mock server in tests. + transport: The `httpx2` async transport that sends requests, such as + `httpx2.MockTransport` in tests. If omitted, the default `httpx2` transport is + used. Raises: ValueError: If no token is passed or set in the environment, or the token is not @@ -39,12 +52,14 @@ def __init__(self, token: str | None = None): raise ValueError("PriceCharting API token is not 40 characters") self._token = SecretStr(token) - self.client = AsyncClient(auth=_TokenAuth(self._token)) + self._client = AsyncClient( + base_url=base_url, auth=_TokenAuth(self._token), transport=transport + ) logging.getLogger("httpx2").addFilter(_REDACT_FILTER) async def aclose(self): """Close the underlying HTTP client.""" - await self.client.aclose() + await self._client.aclose() async def __aenter__(self) -> Self: """Enter the async context and return the client.""" @@ -59,9 +74,35 @@ async def __aexit__( """Close the underlying HTTP client on exit.""" await self.aclose() - async def product(self): - """Get a single product.""" - pass + async def product( + self, id: str | None = None, upc: str | None = None, q: str | None = None + ) -> ProductResponse: + """Get a single product by exactly one of `id`, `upc`, or `q`. + + Args: + id: PriceCharting product ID. + upc: UPC barcode. + q: Full text search on title and/or console. Only the best match is returned. + + Returns: + The matching product. + + Raises: + ParameterError: If not exactly one of `id`, `upc`, or `q` is given. + APIError: If the API returns an error. + + """ + params = { + key: value for key, value in {"id": id, "upc": upc, "q": q}.items() if value is not None + } + + if len(params) == 0: + raise ParameterError("Invalid parameters. Either id, upc, or q are required.") + if len(params) > 1: + raise ParameterError("Invalid parameters. Only one of id, upc, or q is allowed.") + + response = await self._client.get(Prices.PRODUCT.value, params=params) + return _parse(response, ProductResponse) async def products(self): """Search for products.""" diff --git a/src/pypricecharting/error.py b/src/pypricecharting/error.py new file mode 100644 index 0000000..2b6dc91 --- /dev/null +++ b/src/pypricecharting/error.py @@ -0,0 +1,16 @@ +class PriceChartingError(Exception): + """Base class for all PriceCharting errors""" + + +class ParameterError(PriceChartingError, ValueError): + """Raised when an API method is called with invalid parameters""" + + +class APIError(PriceChartingError): + """Raised when the API returns an error response""" + + def __init__(self, message: str, status_code: int): + """Store the API error message and HTTP status code.""" + super().__init__(f"{status_code}: {message}") + self.message = message + self.status_code = status_code diff --git a/src/pypricecharting/pricecharting.py b/src/pypricecharting/pricecharting.py index 36b12e4..2cd8508 100644 --- a/src/pypricecharting/pricecharting.py +++ b/src/pypricecharting/pricecharting.py @@ -3,10 +3,13 @@ from types import TracebackType from typing import Self -from httpx2 import Client +from httpx2 import BaseTransport, Client from pydantic import SecretStr from pypricecharting._auth import _REDACT_FILTER, _TokenAuth +from pypricecharting.error import ParameterError +from pypricecharting.responses import ProductResponse, _parse +from pypricecharting.route import BASE_URL, Prices class PriceCharting: @@ -14,7 +17,12 @@ class PriceCharting: TOKEN_KEY = "PRICECHARTING_TOKEN" - def __init__(self, token: str | None = None): + def __init__( + self, + token: str | None = None, + base_url: str = BASE_URL, + transport: BaseTransport | None = None, + ): """Create a client authenticated with a PriceCharting API token. The client adds a logging filter to the `httpx2` logger that replaces the token in @@ -23,6 +31,11 @@ def __init__(self, token: str | None = None): Args: token: The 40-character PriceCharting API token. If omitted, it is read from the `PRICECHARTING_TOKEN` environment variable. + base_url: The API base URL. Defaults to `route.BASE_URL`. Override it to send + requests to another server, such as a mock server in tests. + transport: The `httpx2` transport that sends requests, such as + `httpx2.MockTransport` in tests. If omitted, the default `httpx2` transport is + used. Raises: ValueError: If no token is passed or set in the environment, or the token is not @@ -40,12 +53,12 @@ def __init__(self, token: str | None = None): raise ValueError("PriceCharting API token is not 40 characters") self._token = SecretStr(token) - self.client = Client(auth=_TokenAuth(self._token)) + self._client = Client(base_url=base_url, auth=_TokenAuth(self._token), transport=transport) logging.getLogger("httpx2").addFilter(_REDACT_FILTER) def close(self): """Close the underlying HTTP client.""" - self.client.close() + self._client.close() def __enter__(self) -> Self: """Enter the context and return the client.""" @@ -60,9 +73,35 @@ def __exit__( """Close the underlying HTTP client on exit.""" self.close() - def product(self): - """Get a single product.""" - pass + def product( + self, id: str | None = None, upc: str | None = None, q: str | None = None + ) -> ProductResponse: + """Get a single product by exactly one of `id`, `upc`, or `q`. + + Args: + id: PriceCharting product ID. + upc: UPC barcode. + q: Full text search on title and/or console. Only the best match is returned. + + Returns: + The matching product. + + Raises: + ParameterError: If not exactly one of `id`, `upc`, or `q` is given. + APIError: If the API returns an error. + + """ + params = { + key: value for key, value in {"id": id, "upc": upc, "q": q}.items() if value is not None + } + + if len(params) == 0: + raise ParameterError("Invalid parameters. Either id, upc, or q are required.") + if len(params) > 1: + raise ParameterError("Invalid parameters. Only one of id, upc, or q is allowed.") + + response = self._client.get(Prices.PRODUCT.value, params=params) + return _parse(response, ProductResponse) def products(self): """Search for products.""" diff --git a/src/pypricecharting/responses.py b/src/pypricecharting/responses.py index a6b8023..0c92e52 100644 --- a/src/pypricecharting/responses.py +++ b/src/pypricecharting/responses.py @@ -1,7 +1,9 @@ from datetime import date +from httpx2 import Response from pydantic import Field +from pypricecharting.error import APIError from pypricecharting.models import Buyer, Offer, PriceChartingModel, ProductSummary from pypricecharting.types import OfferStatus, Rating, Status @@ -240,3 +242,32 @@ class OfferRefundResponse(PriceChartingModel): offer_id: str | None = None is_refunded: bool | None = None refunded_time: date | None = None + + +def _parse[M: PriceChartingModel](response: Response, model: type[M]) -> M: + """Validate an HTTP response into a response model. + + Args: + response: The HTTP response from the PriceCharting API. + model: The response model to validate the JSON body into. + + Returns: + The validated response model. + + Raises: + APIError: If the response is not JSON, has a non-2xx status code, or has + `status: error`. + + """ + try: + data = response.json() + except ValueError: + raise APIError( + 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) + + return model.model_validate(data) diff --git a/tests/mocks/mock_pricecharting.py b/tests/mocks/mock_pricecharting.py new file mode 100644 index 0000000..a75cdaa --- /dev/null +++ b/tests/mocks/mock_pricecharting.py @@ -0,0 +1,26 @@ +from httpx2 import MockTransport, Request, Response + +from pypricecharting.asyncpricecharting import AsyncPriceCharting +from pypricecharting.pricecharting import PriceCharting + + +def mocked_client(token: str | None, response: Response, requests: list[Request]) -> PriceCharting: + """Create a `PriceCharting` client that records requests and returns `response`.""" + + def handler(request: Request) -> Response: + requests.append(request) + return response + + return PriceCharting(token=token, transport=MockTransport(handler)) + + +def mocked_async_client( + token: str | None, response: Response, requests: list[Request] +) -> AsyncPriceCharting: + """Create an `AsyncPriceCharting` client that records requests and returns `response`.""" + + def handler(request: Request) -> Response: + requests.append(request) + return response + + return AsyncPriceCharting(token=token, transport=MockTransport(handler)) diff --git a/tests/responses/test_parse.py b/tests/responses/test_parse.py new file mode 100644 index 0000000..c65bdf2 --- /dev/null +++ b/tests/responses/test_parse.py @@ -0,0 +1,52 @@ +from datetime import date + +import pytest +from httpx2 import Response + +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", +} + + +def test_parse_success(): + response = _parse(Response(200, json=OFFER_END_JSON), OfferEndResponse) + + assert isinstance(response, OfferEndResponse) + assert response.status is Status.SUCCESS + assert response.offer_id == "vtdsww72uyslgooawzyyijsllm" + assert response.is_ended is True + assert response.ended_time == date(2017, 10, 31) + + +def test_parse_error_status_code(): + body = {"status": "error", "error-message": "No such offer"} + + with pytest.raises(APIError, match="404: No such offer") as exc_info: + _parse(Response(404, json=body), OfferEndResponse) + + assert exc_info.value.message == "No such offer" + assert exc_info.value.status_code == 404 + + +def test_parse_error_status_with_success_code(): + body = {"status": "error", "error-message": "Offer already ended"} + + with pytest.raises(APIError, match="200: Offer already ended"): + _parse(Response(200, 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_non_json_response(): + with pytest.raises(APIError, match="502: Bad Gateway"): + _parse(Response(502, text="Bad Gateway"), OfferEndResponse) diff --git a/tests/test_asyncpricecharting.py b/tests/test_asyncpricecharting.py index 6d906f9..1194ee7 100644 --- a/tests/test_asyncpricecharting.py +++ b/tests/test_asyncpricecharting.py @@ -1,10 +1,14 @@ import pytest -from httpx2 import AsyncClient +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.mock_pricecharting import mocked_async_client -# Template tests: the API methods are placeholders, so these only check they can be called. -# Replace the `is None` assertions once each method is implemented. +# 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" @@ -51,28 +55,66 @@ async def test_init_raises_on_incorrect_env_variable(monkeypatch): async def test_init_creates_http_client(): client = AsyncPriceCharting(TOKEN) - assert isinstance(client.client, AsyncClient) - assert not client.client.is_closed + assert isinstance(client._client, AsyncClient) + assert not client._client.is_closed await client.aclose() +async def test_init_uses_transport(): + requests: list[Request] = [] + + def handler(request: Request) -> Response: + requests.append(request) + return Response(200, json={"status": "success"}) + + async with AsyncPriceCharting(TOKEN, transport=MockTransport(handler)) as client: + response = await client._client.get("/api/product") + + assert response.status_code == 200 + assert len(requests) == 1 + assert requests[0].url == f"{BASE_URL}/api/product?t={TOKEN}" + + +async def test_init_sets_base_url(): + async with AsyncPriceCharting(TOKEN) as client: + assert client._client.base_url == BASE_URL + + +async def test_init_uses_base_url(): + requests: list[Request] = [] + + def handler(request: Request) -> Response: + requests.append(request) + return Response(200, json={"status": "success"}) + + base_url = "http://localhost:8080" + async with AsyncPriceCharting( + TOKEN, base_url=base_url, transport=MockTransport(handler) + ) as client: + assert client._client.base_url == base_url + await client._client.get("/api/product") + + assert len(requests) == 1 + assert requests[0].url == f"{base_url}/api/product?t={TOKEN}" + + async def test_aclose_closes_http_client(): client = AsyncPriceCharting(TOKEN) await client.aclose() - assert client.client.is_closed + assert client._client.is_closed async def test_async_with_returns_client(): client = AsyncPriceCharting(TOKEN) async with client as entered: assert entered is client - assert not client.client.is_closed + assert not client._client.is_closed async def test_async_with_closes_http_client(): async with AsyncPriceCharting(TOKEN) as client: pass - assert client.client.is_closed + assert client._client.is_closed async def test_async_with_closes_http_client_on_error(): @@ -80,13 +122,67 @@ async def test_async_with_closes_http_client_on_error(): with pytest.raises(ValueError, match="boom"): async with client: raise ValueError("boom") - assert client.client.is_closed + 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: + 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(): - client = AsyncPriceCharting(TOKEN) - assert await client.product() is None - await client.aclose() +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: + 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(): diff --git a/tests/test_error.py b/tests/test_error.py new file mode 100644 index 0000000..de5ef6b --- /dev/null +++ b/tests/test_error.py @@ -0,0 +1,23 @@ +import pytest + +from pypricecharting.error import APIError, PriceChartingError + + +def test_api_error_attributes(): + error = APIError("No such product", 404) + assert error.message == "No such product" + assert error.status_code == 404 + + +def test_api_error_str(): + assert str(APIError("No such product", 404)) == "404: No such product" + + +def test_api_error_is_pricecharting_error(): + assert issubclass(APIError, PriceChartingError) + assert not issubclass(APIError, ValueError) + + +def test_api_error_caught_as_pricecharting_error(): + with pytest.raises(PriceChartingError, match="500: Internal error"): + raise APIError("Internal error", 500) diff --git a/tests/test_init.py b/tests/test_init.py new file mode 100644 index 0000000..b2a2277 --- /dev/null +++ b/tests/test_init.py @@ -0,0 +1,37 @@ +import pypricecharting +from pypricecharting import error, models, requests, responses, types +from pypricecharting.asyncpricecharting import AsyncPriceCharting +from pypricecharting.pricecharting import PriceCharting + + +def test_all_names_are_importable(): + for name in pypricecharting.__all__: + assert hasattr(pypricecharting, name), name + + +def test_all_has_no_duplicates(): + assert len(pypricecharting.__all__) == len(set(pypricecharting.__all__)) + + +def test_exports_clients(): + assert pypricecharting.PriceCharting is PriceCharting + assert pypricecharting.AsyncPriceCharting is AsyncPriceCharting + + +def test_exports_errors(): + assert pypricecharting.PriceChartingError is error.PriceChartingError + assert pypricecharting.ParameterError is error.ParameterError + assert pypricecharting.APIError is error.APIError + + +def test_exports_public_classes_from_modules(): + for module in (models, requests, responses, types): + public = [ + name + for name, value in vars(module).items() + if isinstance(value, type) + and value.__module__ == module.__name__ + and not name.startswith("_") + ] + for name in public: + assert name in pypricecharting.__all__, f"{module.__name__}.{name} is not exported" diff --git a/tests/test_pricecharting.py b/tests/test_pricecharting.py index 079964f..286ef5e 100644 --- a/tests/test_pricecharting.py +++ b/tests/test_pricecharting.py @@ -1,10 +1,14 @@ import pytest -from httpx2 import Client +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.mock_pricecharting import mocked_client -# Template tests: the API methods are placeholders, so these only check they can be called. -# Replace the `is None` assertions once each method is implemented. +# 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" @@ -51,41 +55,137 @@ def test_init_raises_on_incorrect_env_variable(monkeypatch): def test_init_creates_http_client(): client = PriceCharting(TOKEN) - assert isinstance(client.client, Client) - assert not client.client.is_closed + assert isinstance(client._client, Client) + assert not client._client.is_closed client.close() +def test_init_uses_transport(): + requests: list[Request] = [] + + def handler(request: Request) -> Response: + requests.append(request) + return Response(200, json={"status": "success"}) + + with PriceCharting(TOKEN, transport=MockTransport(handler)) as client: + response = client._client.get("/api/product") + + assert response.status_code == 200 + assert len(requests) == 1 + assert requests[0].url == f"{BASE_URL}/api/product?t={TOKEN}" + + +def test_init_sets_base_url(): + with PriceCharting(TOKEN) as client: + assert client._client.base_url == BASE_URL + + +def test_init_uses_base_url(): + requests: list[Request] = [] + + def handler(request: Request) -> Response: + requests.append(request) + return Response(200, json={"status": "success"}) + + base_url = "http://localhost:8080" + with PriceCharting(TOKEN, base_url=base_url, transport=MockTransport(handler)) as client: + assert client._client.base_url == base_url + client._client.get("/api/product") + + assert len(requests) == 1 + assert requests[0].url == f"{base_url}/api/product?t={TOKEN}" + + def test_close_closes_http_client(): client = PriceCharting(TOKEN) client.close() - assert client.client.is_closed + assert client._client.is_closed def test_with_returns_client(): client = PriceCharting(TOKEN) with client as entered: assert entered is client - assert not client.client.is_closed + assert not client._client.is_closed def test_with_closes_http_client(): with PriceCharting(TOKEN) as client: pass - assert client.client.is_closed + assert client._client.is_closed def test_with_closes_http_client_on_error(): client = PriceCharting(TOKEN) with pytest.raises(ValueError, match="boom"), client: raise ValueError("boom") - assert client.client.is_closed - - -def test_product(): - client = PriceCharting(TOKEN) - assert client.product() is None - client.close() + 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: + 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_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():