diff --git a/README.md b/README.md index 8eafe32..ef369d0 100644 --- a/README.md +++ b/README.md @@ -72,8 +72,8 @@ See [RELEASE.md](RELEASE.md) for how releases and release labels work. ## Usage -Under development: the Prices API methods (`product`, `products`) are implemented; the Marketplace -API methods are not yet. +Under development: the Prices API methods (`product`, `products`) and the Marketplace `offers` +method are implemented; the other Marketplace API methods are not yet. ```python from pypricecharting import AsyncPriceCharting, PriceCharting diff --git a/docs/index.md b/docs/index.md index 2347ec3..1857a52 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 It provides a synchronous client, `PriceCharting`, and an asynchronous client, `AsyncPriceCharting`, both authenticated with a 40-character API token. -Under development: the Prices API methods (`product`, `products`) are implemented; the -Marketplace API methods are not yet. +Under development: the Prices API methods (`product`, `products`) and the Marketplace `offers` +method are implemented; the other Marketplace API methods are not yet. ## Authentication @@ -65,6 +65,24 @@ with PriceCharting() as client: An empty or whitespace-only query raises `ParameterError`. +## Listing offers + +`offers` lists marketplace offers. It takes an `OffersRequestParams`; only `status` is required, +and the other fields narrow the results: + +```python +from pypricecharting import Console, OffersRequestParams, OffersSort, OffersStatus, PriceCharting + +with PriceCharting() as client: + params = OffersRequestParams( + status=OffersStatus.AVAILABLE, console=Console.NES, sort=OffersSort.LOWEST_PRICE + ) + for offer in client.offers(params).offers: + print(offer.offer_id, offer.product_name, offer.price) +``` + +The API allows the same `offers` request at most once every 5 minutes. + ## Errors All errors subclass `PriceChartingError`: diff --git a/src/pypricecharting/__init__.py b/src/pypricecharting/__init__.py index 3155302..be188ad 100644 --- a/src/pypricecharting/__init__.py +++ b/src/pypricecharting/__init__.py @@ -2,7 +2,12 @@ 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.requests import ( + OfferPublishRequestParams, + OffersRequestParams, + OffersSort, + OffersStatus, +) from pypricecharting.responses import ( ErrorResponse, OfferDetailsResponse, @@ -16,9 +21,6 @@ ProductsResponse, ) from pypricecharting.types import ( - Cards, - Coins, - Comics, Condition, Console, Genre, @@ -27,16 +29,12 @@ Rating, State, Status, - VideoGames, ) __all__ = [ "APIError", "AsyncPriceCharting", "Buyer", - "Cards", - "Coins", - "Comics", "Condition", "Console", "ErrorResponse", @@ -45,12 +43,15 @@ "OfferDetailsResponse", "OfferEndResponse", "OfferFeedbackResponse", - "OfferPublishRequest", + "OfferPublishRequestParams", "OfferPublishResponse", "OfferRefundResponse", "OfferShipResponse", "OfferStatus", + "OffersRequestParams", "OffersResponse", + "OffersSort", + "OffersStatus", "ParameterError", "PriceCharting", "PriceChartingError", @@ -62,5 +63,4 @@ "Rating", "State", "Status", - "VideoGames", ] diff --git a/src/pypricecharting/asyncpricecharting.py b/src/pypricecharting/asyncpricecharting.py index 81a8dd6..d675f19 100644 --- a/src/pypricecharting/asyncpricecharting.py +++ b/src/pypricecharting/asyncpricecharting.py @@ -8,15 +8,16 @@ from pypricecharting._auth import _REDACT_FILTER, _TokenAuth from pypricecharting.error import ParameterError -from pypricecharting.responses import ProductResponse, ProductsResponse, _parse +from pypricecharting.requests import OffersRequestParams +from pypricecharting.responses import OffersResponse, ProductResponse, ProductsResponse, _parse from pypricecharting.route import BASE_URL, Route class AsyncPriceCharting: """Asynchronous PriceCharting API client. - Reuse one client for all requests and close it when done (`async with` or `aclose()`). The Marketplace API - methods are not implemented yet and return `None`. + Reuse one client for all requests and close it when done (`async with` or `aclose()`). The Marketplace + methods other than `offers` are not implemented yet and return `None`. """ TOKEN_KEY = "PRICECHARTING_TOKEN" @@ -126,9 +127,26 @@ async def products(self, q: str) -> ProductsResponse: response = await self._client.get(Route.Prices.PRODUCTS, params={"q": q}) return _parse(response, ProductsResponse) - async def offers(self): - """List marketplace offers.""" - pass + async def offers(self, params: OffersRequestParams) -> OffersResponse: + """List marketplace offers matching the given filters. + + The same request can be made at most once every 5 minutes. + + Args: + params: Offer filters. Only `status` is required. + + Returns: + The matching offers. + + Raises: + APIError: If the API returns an error. + + """ + response = await self._client.get( + Route.Marketplace.OFFERS, + params=params.model_dump(mode="json", by_alias=True, exclude_none=True), + ) + return _parse(response, OffersResponse) async def offer_details(self): """Get the details of a marketplace offer.""" diff --git a/src/pypricecharting/pricecharting.py b/src/pypricecharting/pricecharting.py index 1c1eb2f..4575127 100644 --- a/src/pypricecharting/pricecharting.py +++ b/src/pypricecharting/pricecharting.py @@ -8,15 +8,16 @@ from pypricecharting._auth import _REDACT_FILTER, _TokenAuth from pypricecharting.error import ParameterError -from pypricecharting.responses import ProductResponse, ProductsResponse, _parse +from pypricecharting.requests import OffersRequestParams +from pypricecharting.responses import OffersResponse, ProductResponse, ProductsResponse, _parse from pypricecharting.route import BASE_URL, Route class PriceCharting: """Synchronous PriceCharting API client. - Reuse one client for all requests and close it when done (`with` or `close()`). The Marketplace API - methods are not implemented yet and return `None`. + Reuse one client for all requests and close it when done (`with` or `close()`). The Marketplace + methods other than `offers` are not implemented yet and return `None`. """ TOKEN_KEY = "PRICECHARTING_TOKEN" @@ -125,9 +126,26 @@ def products(self, q: str) -> ProductsResponse: response = self._client.get(Route.Prices.PRODUCTS, params={"q": q}) return _parse(response, ProductsResponse) - def offers(self): - """List marketplace offers.""" - pass + def offers(self, params: OffersRequestParams) -> OffersResponse: + """List marketplace offers matching the given filters. + + The same request can be made at most once every 5 minutes. + + Args: + params: Offer filters. Only `status` is required. + + Returns: + The matching offers. + + Raises: + APIError: If the API returns an error. + + """ + response = self._client.get( + Route.Marketplace.OFFERS, + params=params.model_dump(mode="json", by_alias=True, exclude_none=True), + ) + return _parse(response, OffersResponse) def offer_details(self): """Get the details of a marketplace offer.""" diff --git a/src/pypricecharting/requests.py b/src/pypricecharting/requests.py index aff4773..73aff5b 100644 --- a/src/pypricecharting/requests.py +++ b/src/pypricecharting/requests.py @@ -1,12 +1,13 @@ +from enum import StrEnum from typing import Self from pydantic import PositiveInt, model_validator from pypricecharting.models import PriceChartingModel -from pypricecharting.types import State +from pypricecharting.types import Console, Genre, State -class OfferPublishRequest(PriceChartingModel): +class OfferPublishRequestParams(PriceChartingModel): """api/offer-publish request Set one of `product`, `upc`, `asin`, or `epid` to create an offer, or `offer_id` to edit one. @@ -24,7 +25,7 @@ class OfferPublishRequest(PriceChartingModel): """ID of an existing offer to edit. The other identifiers create a new offer.""" price_max: int """Price in pennies buyers pay, or the starting price when `price_min` is set.""" - condition_id: str + condition_id: int """Condition ID for the product's category. See `types.Condition`.""" add_to_collection: str | None = None """Add the item to your collection instead of listing it for sale.""" @@ -62,3 +63,45 @@ def check_identifier(self) -> Self: if id is not None: return self raise ValueError("One of product, upc, asin, epid, or offer_id is required") + + +class OffersStatus(StrEnum): + """Offer status to filter api/offers by""" + + AVAILABLE = "available" + SOLD = "sold" + ENDED = "ended" + COLLECTION = "collection" + """Tracked in the seller's collection, not listed for sale.""" + + +class OffersSort(StrEnum): + """Sort order for api/offers results""" + + NAME = "name" + """Alphabetical.""" + STARTS = "starts" + """Newest listings first.""" + LOWEST_PRICE = "lowest-price" + + +class OffersRequestParams(PriceChartingModel): + """api/offers request + + Only `status` is required. The other fields narrow the results. + + https://www.pricecharting.com/api-documentation#offers + """ + + status: OffersStatus + buyer: str | None = None + """Buyer user ID.""" + console: Console | None = None + condition_id: int | None = None + """Condition ID for the product's category. See `types.Condition`.""" + genre: Genre | None = None + id: str | None = None + """PriceCharting product ID.""" + seller: str | None = None + """Seller user ID.""" + sort: OffersSort | None = None diff --git a/src/pypricecharting/types.py b/src/pypricecharting/types.py index d58ea92..92f2ba4 100644 --- a/src/pypricecharting/types.py +++ b/src/pypricecharting/types.py @@ -1,5 +1,5 @@ import datetime -from enum import Enum, unique +from enum import Enum, IntEnum, StrEnum, unique @unique @@ -36,7 +36,7 @@ class Rating(Enum): @unique class State(Enum): - """Value of a set form flag, such as an `OfferPublishRequest` condition tag""" + """Value of a set form flag, such as an `OfferPublishRequestParams` condition tag""" ON = "on" @@ -53,107 +53,97 @@ class RateLimit(Enum): """The same `/api/offers` URL: once every 5 minutes.""" -@unique -class VideoGames(Enum): - """Condition IDs for video game products. - - https://www.pricecharting.com/api-documentation#includes - """ - - LOOSE = 1 - NEW_AND_SEALED = 2 - CIB = 3 - """Complete in box: item, box, and manual.""" - GRADED = 5 - BOX_ONLY = 6 - MANUAL_ONLY = 7 - ITEM_AND_BOX = 8 - ITEM_AND_MANUAL = 9 - BOX_AND_MANUAL = 10 - GRADED_CIB = 13 - - -@unique -class Cards(Enum): - """Condition IDs for trading card products. - - https://www.pricecharting.com/api-documentation#includes - """ - - UNGRADED = 1 - GRADE_8 = 2 - GRADE_7 = 3 - GRADE_9 = 5 - GRADE_9_5 = 6 - GRADE_10 = 7 - BGS_10 = 8 - GRADE_1 = 9 - GRADE_2 = 10 - GRADE_3 = 13 - - -@unique -class Comics(Enum): - """Condition IDs for comic book products. - - https://www.pricecharting.com/api-documentation#includes - """ - - UNGRADED = 1 - GRADE_6_0 = 2 - GRADE_4_0 = 3 - GRADE_8_0 = 5 - GRADE_9_2 = 6 - GRADE_9_8 = 7 - GRADE_10_0 = 8 - GRADE_2_0 = 9 - GRADE_9_6 = 10 - GRADE_3_0 = 13 - - -@unique -class Coins(Enum): - """Condition IDs for coin products. - - https://www.pricecharting.com/api-documentation#includes - """ - - UNGRADED = 1 - AU_50_58 = 2 - """About Uncirculated, grade 50-58.""" - VF_20_35 = 3 - """Very Fine, grade 20-35.""" - MS_62 = 5 - """Mint State 62.""" - MS_64 = 6 - """Mint State 64.""" - MS_66 = 7 - """Mint State 66.""" - F_12_15 = 8 - """Fine, grade 12-15.""" - XF_40_45 = 9 - """Extremely Fine, grade 40-45.""" - MS_60 = 10 - """Mint State 60.""" - MS_61 = 13 - """Mint State 61.""" - - -@unique -class Condition(Enum): +class Condition: """Condition ID enums grouped by product category. https://www.pricecharting.com/api-documentation#includes """ - VIDEOGAMES = VideoGames - CARDS = Cards - COMICS = Comics - COINS = Coins + @unique + class VideoGames(IntEnum): + """Condition IDs for video game products. + + https://www.pricecharting.com/api-documentation#includes + """ + + LOOSE = 1 + NEW_AND_SEALED = 2 + CIB = 3 + """Complete in box: item, box, and manual.""" + GRADED = 5 + BOX_ONLY = 6 + MANUAL_ONLY = 7 + ITEM_AND_BOX = 8 + ITEM_AND_MANUAL = 9 + BOX_AND_MANUAL = 10 + GRADED_CIB = 13 + + @unique + class Cards(IntEnum): + """Condition IDs for trading card products. + + https://www.pricecharting.com/api-documentation#includes + """ + + UNGRADED = 1 + GRADE_8 = 2 + GRADE_7 = 3 + GRADE_9 = 5 + GRADE_9_5 = 6 + GRADE_10 = 7 + BGS_10 = 8 + GRADE_1 = 9 + GRADE_2 = 10 + GRADE_3 = 13 + + @unique + class Comics(IntEnum): + """Condition IDs for comic book products. + + https://www.pricecharting.com/api-documentation#includes + """ + + UNGRADED = 1 + GRADE_6_0 = 2 + GRADE_4_0 = 3 + GRADE_8_0 = 5 + GRADE_9_2 = 6 + GRADE_9_8 = 7 + GRADE_10_0 = 8 + GRADE_2_0 = 9 + GRADE_9_6 = 10 + GRADE_3_0 = 13 + + @unique + class Coins(IntEnum): + """Condition IDs for coin products. + + https://www.pricecharting.com/api-documentation#includes + """ + + UNGRADED = 1 + AU_50_58 = 2 + """About Uncirculated, grade 50-58.""" + VF_20_35 = 3 + """Very Fine, grade 20-35.""" + MS_62 = 5 + """Mint State 62.""" + MS_64 = 6 + """Mint State 64.""" + MS_66 = 7 + """Mint State 66.""" + F_12_15 = 8 + """Fine, grade 12-15.""" + XF_40_45 = 9 + """Extremely Fine, grade 40-45.""" + MS_60 = 10 + """Mint State 60.""" + MS_61 = 13 + """Mint State 61.""" @unique -class Genre(Enum): +class Genre(StrEnum): """Product genres as labeled by PriceCharting. https://www.pricecharting.com/api-documentation#genres @@ -204,7 +194,7 @@ class Genre(Enum): @unique -class Console(Enum): +class Console(StrEnum): """PriceCharting Console IDs https://www.pricecharting.com/api-documentation#console-ids diff --git a/tests/mocks/json.py b/tests/mocks/json.py index 3debd1a..17e8ee4 100644 --- a/tests/mocks/json.py +++ b/tests/mocks/json.py @@ -15,9 +15,9 @@ OFFER_JSON = { - "offer-id": "smzksacsy5i2dsrddxsrlzsp6i", + "offer-id": "testofferid", "offer-status": "sold", - "offer-url": "/offer/smzksacsy5i2dsrddxsrlzsp6i", + "offer-url": "/offer/testofferid", "id": 9307, "product-name": "M.C. Kids", "console-name": "NES", @@ -49,13 +49,24 @@ "product": "6910", "price-max": 2500, "price-min": 1500, - "condition-id": "1", + "condition-id": 1, "cost-basis": 1000, "broken": "on", "sku": "ABC-123", "quantity": 2, } +OFFERS_REQUEST_JSON = { + "status": "sold", + "buyer": "7cgdyu5ynzos3mxwhfh46xj3f4", + "console": "G17", + "condition-id": 1, + "genre": "Football", + "id": "6910", + "seller": "3mxwhfh46xj3f47cgdyu5ynzos", + "sort": "lowest-price", +} + # Responses @@ -64,7 +75,7 @@ OFFERS_JSON = { "status": "success", "offers": [ - {"offer-id": "smzksacsy5i2dsrddxsrlzsp6i", "offer-status": "sold", "price": 1473}, + {"offer-id": "testofferid", "offer-status": "sold", "price": 1473}, {"offer-id": "vtdsww72uyslgooawzyyijsllm", "offer-status": "available", "price": 2500}, ], } @@ -100,9 +111,9 @@ "is-refunded": False, "is-shipped": True, "is-sold": True, - "offer-id": "smzksacsy5i2dsrddxsrlzsp6i", + "offer-id": "testofferid", "offer-status": "sold", - "offer-url": "/offer/smzksacsy5i2dsrddxsrlzsp6i", + "offer-url": "/offer/testofferid", "sku": "ABC-123", "tracking-number": "901234567890000", "start-time": "2017-10-01", diff --git a/tests/models/test_offer.py b/tests/models/test_offer.py index 6ef34f6..60639bc 100644 --- a/tests/models/test_offer.py +++ b/tests/models/test_offer.py @@ -12,9 +12,9 @@ def test_offer_json_to_model(): offer = Offer.model_validate_json(json.dumps(OFFER_JSON)) - assert offer.offer_id == "smzksacsy5i2dsrddxsrlzsp6i" + assert offer.offer_id == "testofferid" assert offer.offer_status is OfferStatus.SOLD - assert offer.offer_url == "/offer/smzksacsy5i2dsrddxsrlzsp6i" + assert offer.offer_url == "/offer/testofferid" assert offer.id == 9307 assert offer.product_name == "M.C. Kids" assert offer.console_name == "NES" @@ -34,9 +34,9 @@ def test_offer_json_to_model(): def test_offer_model_to_json(): offer = Offer( - offer_id="smzksacsy5i2dsrddxsrlzsp6i", + offer_id="testofferid", offer_status=OfferStatus.SOLD, - offer_url="/offer/smzksacsy5i2dsrddxsrlzsp6i", + offer_url="/offer/testofferid", id=9307, product_name="M.C. Kids", console_name="NES", diff --git a/tests/requests/test_offers.py b/tests/requests/test_offers.py new file mode 100644 index 0000000..891b5a1 --- /dev/null +++ b/tests/requests/test_offers.py @@ -0,0 +1,81 @@ +import json + +import pytest +from pydantic import ValidationError + +from pypricecharting.requests import OffersRequestParams, OffersSort, OffersStatus +from pypricecharting.types import Console, Genre +from tests.mocks.json import OFFERS_REQUEST_JSON + + +def test_offers_status_members(): + assert len(OffersStatus) == 4 + assert OffersStatus.AVAILABLE == "available" + assert OffersStatus.SOLD == "sold" + assert OffersStatus.ENDED == "ended" + assert OffersStatus.COLLECTION == "collection" + + +def test_offers_status_unknown_value_raises(): + with pytest.raises(ValueError, match="is not a valid"): + OffersStatus("pending") + + +def test_offers_sort_members(): + assert len(OffersSort) == 3 + assert OffersSort.NAME == "name" + assert OffersSort.STARTS == "starts" + assert OffersSort.LOWEST_PRICE == "lowest-price" + + +def test_offers_sort_unknown_value_raises(): + with pytest.raises(ValueError, match="is not a valid"): + OffersSort("price") + + +def test_offers_json_to_model(): + request = OffersRequestParams.model_validate_json(json.dumps(OFFERS_REQUEST_JSON)) + + assert request.status is OffersStatus.SOLD + assert request.buyer == "7cgdyu5ynzos3mxwhfh46xj3f4" + assert request.console is Console.NES + assert request.condition_id == 1 + assert request.genre is Genre.FOOTBALL + assert request.id == "6910" + assert request.seller == "3mxwhfh46xj3f47cgdyu5ynzos" + assert request.sort is OffersSort.LOWEST_PRICE + + +def test_offers_model_to_json(): + request = OffersRequestParams( + status=OffersStatus.SOLD, + buyer="7cgdyu5ynzos3mxwhfh46xj3f4", + console=Console.NES, + condition_id=1, + genre=Genre.FOOTBALL, + id="6910", + seller="3mxwhfh46xj3f47cgdyu5ynzos", + sort=OffersSort.LOWEST_PRICE, + ) + + dumped = request.model_dump_json(by_alias=True, exclude_none=True) + + assert json.loads(dumped) == OFFERS_REQUEST_JSON + + +def test_offers_only_status_is_required(): + request = OffersRequestParams(status=OffersStatus.AVAILABLE) + + assert request.model_dump(mode="json", by_alias=True, exclude_none=True) == { + "status": "available" + } + + +def test_offers_requires_status(): + with pytest.raises(ValidationError, match="status"): + OffersRequestParams.model_validate({}) + + +def test_offers_rejects_unknown_status(): + with pytest.raises(ValidationError, match="status"): + OffersRequestParams.model_validate({"status": "pending"}) diff --git a/tests/requests/test_request.py b/tests/requests/test_offers_publish.py similarity index 74% rename from tests/requests/test_request.py rename to tests/requests/test_offers_publish.py index 32cbf30..cb5256d 100644 --- a/tests/requests/test_request.py +++ b/tests/requests/test_offers_publish.py @@ -3,18 +3,18 @@ import pytest from pydantic import ValidationError -from pypricecharting.requests import OfferPublishRequest +from pypricecharting.requests import OfferPublishRequestParams from pypricecharting.types import State 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_REQUEST_JSON)) + request = OfferPublishRequestParams.model_validate_json(json.dumps(OFFER_PUBLISH_REQUEST_JSON)) assert request.product == "6910" assert request.price_max == 2500 assert request.price_min == 1500 - assert request.condition_id == "1" + assert request.condition_id == 1 assert request.cost_basis == 1000 assert request.broken is State.ON assert request.sku == "ABC-123" @@ -23,11 +23,11 @@ def test_offer_publish_json_to_model(): def test_offer_publish_model_to_json(): - request = OfferPublishRequest( + request = OfferPublishRequestParams( product="6910", price_max=2500, price_min=1500, - condition_id="1", + condition_id=1, cost_basis=1000, broken=State.ON, sku="ABC-123", @@ -41,4 +41,4 @@ def test_offer_publish_model_to_json(): def test_offer_publish_model_raises(): with pytest.raises(ValidationError, match="One of product, upc, asin, epid, or offer_id"): - OfferPublishRequest(price_max=2500, condition_id="1") + OfferPublishRequestParams(price_max=2500, condition_id=1) diff --git a/tests/responses/test_offer_details.py b/tests/responses/test_offer_details.py index 61eb2ec..1f11f42 100644 --- a/tests/responses/test_offer_details.py +++ b/tests/responses/test_offer_details.py @@ -39,9 +39,9 @@ def test_offer_details_json_to_model(): assert details.is_refunded is False assert details.is_shipped is True assert details.is_sold is True - assert details.offer_id == "smzksacsy5i2dsrddxsrlzsp6i" + assert details.offer_id == "testofferid" assert details.offer_status is OfferStatus.SOLD - assert details.offer_url == "/offer/smzksacsy5i2dsrddxsrlzsp6i" + assert details.offer_url == "/offer/testofferid" assert details.sku == "ABC-123" assert details.tracking_number == "901234567890000" assert details.start_time == date(2017, 10, 1) diff --git a/tests/responses/test_offers.py b/tests/responses/test_offers.py index f9f304a..54abb07 100644 --- a/tests/responses/test_offers.py +++ b/tests/responses/test_offers.py @@ -11,7 +11,7 @@ def test_offers_json_to_model(): assert response.status is Status.SUCCESS assert response.offers == [ - Offer(offer_id="smzksacsy5i2dsrddxsrlzsp6i", offer_status=OfferStatus.SOLD, price=1473), + Offer(offer_id="testofferid", offer_status=OfferStatus.SOLD, price=1473), Offer( offer_id="vtdsww72uyslgooawzyyijsllm", offer_status=OfferStatus.AVAILABLE, price=2500 ), @@ -22,7 +22,7 @@ def test_offers_model_to_json(): response = OffersResponse( status=Status.SUCCESS, offers=[ - Offer(offer_id="smzksacsy5i2dsrddxsrlzsp6i", offer_status=OfferStatus.SOLD, price=1473), + Offer(offer_id="testofferid", offer_status=OfferStatus.SOLD, price=1473), Offer( offer_id="vtdsww72uyslgooawzyyijsllm", offer_status=OfferStatus.AVAILABLE, diff --git a/tests/test_asyncpricecharting_marketplace.py b/tests/test_asyncpricecharting_marketplace.py index 66c2cd7..dd7a803 100644 --- a/tests/test_asyncpricecharting_marketplace.py +++ b/tests/test_asyncpricecharting_marketplace.py @@ -1,14 +1,55 @@ +import pytest +from httpx2 import Request, Response + from pypricecharting.asyncpricecharting import AsyncPriceCharting -from tests.mocks.mock_pricecharting import TOKEN +from pypricecharting.error import APIError +from pypricecharting.requests import OffersRequestParams, OffersStatus +from pypricecharting.responses import OffersResponse +from pypricecharting.types import Status +from tests.mocks.json import OFFERS_JSON, OFFERS_REQUEST_JSON +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. async def test_offers(): - client = AsyncPriceCharting(TOKEN) - assert await client.offers() is None - await client.aclose() + requests: list[Request] = [] + params = OffersRequestParams.model_validate(OFFERS_REQUEST_JSON) + + async with mocked_async_client(TOKEN, Response(200, json=OFFERS_JSON), requests) as client: + response = await client.offers(params) + + assert isinstance(response, OffersResponse) + assert response.status == Status.SUCCESS + assert len(response.offers) == 2 + assert response.offers[0].offer_id == "testofferid" + + assert len(requests) == 1 + assert requests[0].method == "GET" + assert requests[0].url.path == "/api/offers" + expected = {key: str(value) for key, value in OFFERS_REQUEST_JSON.items()} + assert dict(requests[0].url.params) == {**expected, "t": TOKEN} + + +async def test_offers_sends_only_set_parameters(): + requests: list[Request] = [] + params = OffersRequestParams(status=OffersStatus.AVAILABLE) + + async with mocked_async_client(TOKEN, Response(200, json=OFFERS_JSON), requests) as client: + await client.offers(params) + + assert dict(requests[0].url.params) == {"status": "available", "t": TOKEN} + + +async def test_offers_raises_api_error(): + requests: list[Request] = [] + params = OffersRequestParams(status=OffersStatus.SOLD) + async with mocked_async_client( + TOKEN, Response(400, json=error_body("Invalid status")), requests + ) as client: + with pytest.raises(APIError, match="400: Invalid status"): + await client.offers(params) async def test_offer_details(): diff --git a/tests/test_pricecharting_marketplace.py b/tests/test_pricecharting_marketplace.py index 319b161..ebac6fa 100644 --- a/tests/test_pricecharting_marketplace.py +++ b/tests/test_pricecharting_marketplace.py @@ -1,14 +1,55 @@ +import pytest +from httpx2 import Request, Response + +from pypricecharting.error import APIError from pypricecharting.pricecharting import PriceCharting -from tests.mocks.mock_pricecharting import TOKEN +from pypricecharting.requests import OffersRequestParams, OffersStatus +from pypricecharting.responses import OffersResponse +from pypricecharting.types import Status +from tests.mocks.json import OFFERS_JSON, OFFERS_REQUEST_JSON +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. def test_offers(): - client = PriceCharting(TOKEN) - assert client.offers() is None - client.close() + requests: list[Request] = [] + params = OffersRequestParams.model_validate(OFFERS_REQUEST_JSON) + + with mocked_client(TOKEN, Response(200, json=OFFERS_JSON), requests) as client: + response = client.offers(params) + + assert isinstance(response, OffersResponse) + assert response.status == Status.SUCCESS + assert len(response.offers) == 2 + assert response.offers[0].offer_id == "testofferid" + + assert len(requests) == 1 + assert requests[0].method == "GET" + assert requests[0].url.path == "/api/offers" + expected = {key: str(value) for key, value in OFFERS_REQUEST_JSON.items()} + assert dict(requests[0].url.params) == {**expected, "t": TOKEN} + + +def test_offers_sends_only_set_parameters(): + requests: list[Request] = [] + params = OffersRequestParams(status=OffersStatus.AVAILABLE) + + with mocked_client(TOKEN, Response(200, json=OFFERS_JSON), requests) as client: + client.offers(params) + + assert dict(requests[0].url.params) == {"status": "available", "t": TOKEN} + + +def test_offers_raises_api_error(): + requests: list[Request] = [] + params = OffersRequestParams(status=OffersStatus.SOLD) + with ( + mocked_client(TOKEN, Response(400, json=error_body("Invalid status")), requests) as client, + pytest.raises(APIError, match="400: Invalid status"), + ): + client.offers(params) def test_offer_details(): diff --git a/tests/types/test_condition.py b/tests/types/test_condition.py index ba52754..a9e0a7a 100644 --- a/tests/types/test_condition.py +++ b/tests/types/test_condition.py @@ -1,109 +1,101 @@ import pytest -from pypricecharting.types import Cards, Coins, Comics, Condition, VideoGames +from pypricecharting.types import Condition # Source: https://www.pricecharting.com/api-documentation#includes def test_video_games_members(): - assert len(VideoGames) == 10 - assert VideoGames.LOOSE.value == 1 - assert VideoGames.NEW_AND_SEALED.value == 2 - assert VideoGames.CIB.value == 3 - assert VideoGames.GRADED.value == 5 - assert VideoGames.BOX_ONLY.value == 6 - assert VideoGames.MANUAL_ONLY.value == 7 - assert VideoGames.ITEM_AND_BOX.value == 8 - assert VideoGames.ITEM_AND_MANUAL.value == 9 - assert VideoGames.BOX_AND_MANUAL.value == 10 - assert VideoGames.GRADED_CIB.value == 13 + assert len(Condition.VideoGames) == 10 + assert Condition.VideoGames.LOOSE == 1 + assert Condition.VideoGames.NEW_AND_SEALED == 2 + assert Condition.VideoGames.CIB == 3 + assert Condition.VideoGames.GRADED == 5 + assert Condition.VideoGames.BOX_ONLY == 6 + assert Condition.VideoGames.MANUAL_ONLY == 7 + assert Condition.VideoGames.ITEM_AND_BOX == 8 + assert Condition.VideoGames.ITEM_AND_MANUAL == 9 + assert Condition.VideoGames.BOX_AND_MANUAL == 10 + assert Condition.VideoGames.GRADED_CIB == 13 def test_video_games_lookup_by_id(): - for member in VideoGames: - assert VideoGames(member.value) is member + for member in Condition.VideoGames: + assert Condition.VideoGames(member) is member def test_video_games_unknown_id_raises(): with pytest.raises(ValueError, match="is not a valid"): - VideoGames(4) + Condition.VideoGames(4) def test_cards_members(): - assert len(Cards) == 10 - assert Cards.UNGRADED.value == 1 - assert Cards.GRADE_8.value == 2 - assert Cards.GRADE_7.value == 3 - assert Cards.GRADE_9.value == 5 - assert Cards.GRADE_9_5.value == 6 - assert Cards.GRADE_10.value == 7 - assert Cards.BGS_10.value == 8 - assert Cards.GRADE_1.value == 9 - assert Cards.GRADE_2.value == 10 - assert Cards.GRADE_3.value == 13 + assert len(Condition.Cards) == 10 + assert Condition.Cards.UNGRADED == 1 + assert Condition.Cards.GRADE_8 == 2 + assert Condition.Cards.GRADE_7 == 3 + assert Condition.Cards.GRADE_9 == 5 + assert Condition.Cards.GRADE_9_5 == 6 + assert Condition.Cards.GRADE_10 == 7 + assert Condition.Cards.BGS_10 == 8 + assert Condition.Cards.GRADE_1 == 9 + assert Condition.Cards.GRADE_2 == 10 + assert Condition.Cards.GRADE_3 == 13 def test_cards_lookup_by_id(): - for member in Cards: - assert Cards(member.value) is member + for member in Condition.Cards: + assert Condition.Cards(member) is member def test_cards_unknown_id_raises(): with pytest.raises(ValueError, match="is not a valid"): - Cards(4) + Condition.Cards(4) def test_comics_members(): - assert len(Comics) == 10 - assert Comics.UNGRADED.value == 1 - assert Comics.GRADE_6_0.value == 2 - assert Comics.GRADE_4_0.value == 3 - assert Comics.GRADE_8_0.value == 5 - assert Comics.GRADE_9_2.value == 6 - assert Comics.GRADE_9_8.value == 7 - assert Comics.GRADE_10_0.value == 8 - assert Comics.GRADE_2_0.value == 9 - assert Comics.GRADE_9_6.value == 10 - assert Comics.GRADE_3_0.value == 13 + assert len(Condition.Comics) == 10 + assert Condition.Comics.UNGRADED == 1 + assert Condition.Comics.GRADE_6_0 == 2 + assert Condition.Comics.GRADE_4_0 == 3 + assert Condition.Comics.GRADE_8_0 == 5 + assert Condition.Comics.GRADE_9_2 == 6 + assert Condition.Comics.GRADE_9_8 == 7 + assert Condition.Comics.GRADE_10_0 == 8 + assert Condition.Comics.GRADE_2_0 == 9 + assert Condition.Comics.GRADE_9_6 == 10 + assert Condition.Comics.GRADE_3_0 == 13 def test_comics_lookup_by_id(): - for member in Comics: - assert Comics(member.value) is member + for member in Condition.Comics: + assert Condition.Comics(member) is member def test_comics_unknown_id_raises(): with pytest.raises(ValueError, match="is not a valid"): - Comics(4) + Condition.Comics(4) def test_coins_members(): - assert len(Coins) == 10 - assert Coins.UNGRADED.value == 1 - assert Coins.AU_50_58.value == 2 - assert Coins.VF_20_35.value == 3 - assert Coins.MS_62.value == 5 - assert Coins.MS_64.value == 6 - assert Coins.MS_66.value == 7 - assert Coins.F_12_15.value == 8 - assert Coins.XF_40_45.value == 9 - assert Coins.MS_60.value == 10 - assert Coins.MS_61.value == 13 + assert len(Condition.Coins) == 10 + assert Condition.Coins.UNGRADED == 1 + assert Condition.Coins.AU_50_58 == 2 + assert Condition.Coins.VF_20_35 == 3 + assert Condition.Coins.MS_62 == 5 + assert Condition.Coins.MS_64 == 6 + assert Condition.Coins.MS_66 == 7 + assert Condition.Coins.F_12_15 == 8 + assert Condition.Coins.XF_40_45 == 9 + assert Condition.Coins.MS_60 == 10 + assert Condition.Coins.MS_61 == 13 def test_coins_lookup_by_id(): - for member in Coins: - assert Coins(member.value) is member + for member in Condition.Coins: + assert Condition.Coins(member) is member def test_coins_unknown_id_raises(): with pytest.raises(ValueError, match="is not a valid"): - Coins(4) - - -def test_condition_categories(): - assert len(Condition) == 4 - assert Condition.VIDEOGAMES.value is VideoGames - assert Condition.CARDS.value is Cards - assert Condition.COMICS.value is Comics - assert Condition.COINS.value is Coins + Condition.Coins(4)