diff --git a/CI.md b/CI.md index 84919aa..a1b30de 100644 --- a/CI.md +++ b/CI.md @@ -10,6 +10,8 @@ * The docs site deploys through GitHub Pages, so the repo's Pages source must be set to **GitHub Actions**. PRs build the docs in strict mode without deploying +* On PRs, `release-drafter.yml` also runs the `require-label` check, which fails until the PR has + at least one release label (see [RELEASE.md](RELEASE.md)) * GitHub Actions are pinned to full commit SHAs, with the version in a trailing comment * Dependabot (`.github/dependabot.yml`) checks weekly for updates to GitHub Actions and Python dependencies, and monthly for the dev container image and dev container features. New releases diff --git a/README.md b/README.md index 69efbec..6e536f0 100644 --- a/README.md +++ b/README.md @@ -72,9 +72,7 @@ See [RELEASE.md](RELEASE.md) for how releases and release labels work. ## Usage -Under development: the Prices API methods (`product`, `products`) and the Marketplace `offers`, -`offer_details`, `offer_publish`, `offer_feedback`, and `offer_ship` methods are implemented; -`offer_end` and `offer_refund` are not yet. +Both clients have a method for every Prices API and Marketplace API operation. ```python from pypricecharting import AsyncPriceCharting, PriceCharting @@ -97,3 +95,18 @@ Project contains an OpenAPI spec and a Bruno project for easy testing and mockin * `./bruno` - Bruno project * `./open_api` - OpenAPI spec + +## TODO / Investigate + +None of the client methods have been run against the live API yet. They are tested against a mock +transport and the two specs only. Items to settle with real responses: + +* **Offer details price limits** - `OfferDetailsResponse` reads `price-max` and `price-min`, the + names in the documentation's key table. If the API sends `max-price` and `min-price` instead, + `price_max` and `price_min` come back as `None` with no error. Check one real + `/api/offer-details` response +* **Extra Marketplace keys** - `pending-reason`, `seller-id`, `image-url`, `best-competing-price`, + `is-best-priced-offer` and `value` are only on `OfferDetailsResponse`. The documentation doesn't + say which endpoint returns each one. If `/api/offers` returns any of them, add them to `Offer` +* **Live test of every endpoint** - call each method once with a real token and compare the + response to its model diff --git a/RELEASE.md b/RELEASE.md index 15a7b5f..7be1f9e 100644 --- a/RELEASE.md +++ b/RELEASE.md @@ -19,8 +19,12 @@ labels; other repository labels (e.g. `good first issue`, `question`) are ignore * Every PR must have at least one release label, or the `Release Drafter / require-label` check fails. If a release has PRs with different labels, the largest bump wins * Release labels are added automatically from the PR's branch name prefix (`feat/`, `fix/`, `chore/`, - `ci/`, `docs/`, `refactor/`) and from the files it changes. You can add or change them by hand + `ci/`, `docs/`, `refactor/`) and from the files it changes: `.github/workflows/*` adds `ci`, + `*.md` adds `documentation`, and `uv.lock` adds `dependencies`. You can add or change them by hand * Merging to `main` updates a draft GitHub Release with the next version and notes * To release, run the **Release** workflow from the Actions tab. It bumps the version in `pyproject.toml`/`uv.lock`, tags the release, and uploads build artifacts. The GitHub Release notes are the changelog +* The Release workflow commits the version bump as `Release vX.Y.Z` and pushes it straight to + `main` as `github-actions[bot]`, with no PR. The tag points at that commit. Branch protection + on `main` must allow this push, or the workflow fails before the release is published diff --git a/bruno/PricechartingAPI/Marketplace API/offer-details.yml b/bruno/PricechartingAPI/Marketplace API/offer-details.yml index fccacc5..880b8c1 100644 --- a/bruno/PricechartingAPI/Marketplace API/offer-details.yml +++ b/bruno/PricechartingAPI/Marketplace API/offer-details.yml @@ -29,7 +29,7 @@ docs: |- { "status":"success", "buyer": { // buyer's shipping info - "buyer-email":"[email protected]", + "buyer-email":"example@email.com", "shipping-city":"Anytown", "shipping-country":"United States", "shipping-line1":"123 Smith St", @@ -52,12 +52,12 @@ docs: |- "is-refunded":false, // has offer been refunded "is-shipped":true, // has offer been shipped "is-sold":true, // has offer sold - "max-price":12000, - "min-price":10000, "offer-id":"vtdsww72uyslgooawzyyijsllm", // unique offer ID "offer-status":"sold", "offer-url":"/offer/vtdsww72uyslgooawzyyijsllm", // url for offer "price":11281, // sales price. $112.81 + "price-max":12000, + "price-min":10000, "product-name":"Mega Man 7", "refunded-time":"0001-01-01", // date of refund. zero value "sale-time":"2017-10-31", @@ -73,7 +73,7 @@ docs: |- - `buyer`: `buyer-email`, `shipping-name`, `shipping-line1`, `shipping-line2`, `shipping-city`, `shipping-state`, `shipping-zip`, `shipping-country` - `buyer-left-feedback`, `seller-left-feedback` - `id`, `product-name`, `console-name`, `condition`, `includes` - - `price`, `max-price`, `min-price`, `cost-basis`, `shipping-premium` - - `has-pictures`, `is-collection`, `is-ended`, `is-price-descending`, `is-refunded`, `is-shipped`, `is-sold` - - `offer-id`, `offer-status`, `offer-url`, `sku`, `tracking-number` + - `price`, `price-max`, `price-min`, `cost-basis`, `shipping-premium`, `best-competing-price`, `value` + - `has-pictures`, `is-best-priced-offer`, `is-collection`, `is-ended`, `is-price-descending`, `is-refunded`, `is-shipped`, `is-sold` + - `offer-id`, `offer-status`, `pending-reason`, `offer-url`, `image-url`, `seller-id`, `sku`, `tracking-number` - `start-time`, `sale-time`, `shipped-time`, `ended-time`, `refunded-time` diff --git a/bruno/PricechartingAPI/Marketplace API/offer-publish.yml b/bruno/PricechartingAPI/Marketplace API/offer-publish.yml index a84b541..e60b05d 100644 --- a/bruno/PricechartingAPI/Marketplace API/offer-publish.yml +++ b/bruno/PricechartingAPI/Marketplace API/offer-publish.yml @@ -92,7 +92,7 @@ settings: docs: |- Publish a new offer, or edit an existing one when `offer-id` is given. - Provide one identifier: `product`, `upc`, `asin`, `epid`, or `offer-id`. + Either `product`, `upc`, `asin`, `epid` or `offer-id` is required. Condition tags (`broken`, `pristine`, `scratch`, `stickers`, `tear`, `writing`) are set to `on`. With no tags, the listing shows "Normal wear". diff --git a/docs/index.md b/docs/index.md index 6ebd9d8..e0cfa86 100644 --- a/docs/index.md +++ b/docs/index.md @@ -5,9 +5,7 @@ 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`) and the Marketplace `offers`, -`offer_details`, `offer_publish`, `offer_feedback`, and `offer_ship` methods are implemented; -`offer_end` and `offer_refund` are not yet. +Both clients have a method for every Prices API and Marketplace API operation. ## Authentication @@ -155,6 +153,34 @@ A valid tracking number can earn you positive feedback if the buyer leaves none, shows shipment within 3 days and delivery to the buyer's address. An empty or whitespace-only offer ID raises `ParameterError`. +## Ending an offer + +`offer_end` ends an offer so it can no longer be purchased. For a collection item, it removes the +item from the collection: + +```python +from pypricecharting import PriceCharting + +with PriceCharting() as client: + ended = client.offer_end("vtdsww72uyslgooawzyyijsllm") + print(ended.offer_id, ended.is_ended, ended.ended_time) +``` + +## Refunding an offer + +`offer_refund` refunds a purchased offer. Payment is returned immediately from your PayPal account +to the buyer: + +```python +from pypricecharting import PriceCharting + +with PriceCharting() as client: + refunded = client.offer_refund("vtdsww72uyslgooawzyyijsllm") + print(refunded.offer_id, refunded.is_refunded, refunded.refunded_time) +``` + +Both raise `ParameterError` for an empty or whitespace-only offer ID. + ## Errors All errors subclass `PriceChartingError`: diff --git a/open_api/pricecharting.yaml b/open_api/pricecharting.yaml index c8ec71c..aae21e5 100644 --- a/open_api/pricecharting.yaml +++ b/open_api/pricecharting.yaml @@ -223,7 +223,7 @@ paths: is-shipped: true is-sold: true offer-id: nw6asacmsbvvoq5yeyrkvzcdky - offer-status: sold + offer-status: available offer-url: /offer/nw6asacmsbvvoq5yeyrkvzcdky price: 6281 product-name: Shatterhand @@ -257,7 +257,7 @@ paths: example: status: success buyer: - buyer-email: buyer@example.com + buyer-email: example@email.com shipping-city: Anytown shipping-country: United States shipping-line1: 123 Smith St @@ -279,12 +279,12 @@ paths: is-refunded: false is-shipped: true is-sold: true - max-price: 12000 - min-price: 10000 offer-id: vtdsww72uyslgooawzyyijsllm offer-status: sold offer-url: /offer/vtdsww72uyslgooawzyyijsllm price: 11281 + price-max: 12000 + price-min: 10000 product-name: Mega Man 7 refunded-time: "0001-01-01" sale-time: "2017-10-31" @@ -307,7 +307,7 @@ paths: description: |- Publishes a new offer, or edits an existing one when `offer-id` is given. - Provide exactly one identifier: `product`, `upc`, `asin`, `epid`, or `offer-id`. + Either `product`, `upc`, `asin`, `epid` or `offer-id` is required. Condition tags (`broken`, `pristine`, `scratch`, `stickers`, `tear`, `writing`) are set to `on`. With no tags, the listing shows "Normal wear". `pristine` displays as @@ -864,15 +864,26 @@ components: $ref: "#/components/schemas/Pennies" price: $ref: "#/components/schemas/Pennies" - max-price: + price-max: $ref: "#/components/schemas/Pennies" - min-price: + description: Maximum price entered, or the starting price of a reverse auction. + price-min: $ref: "#/components/schemas/Pennies" + description: Minimum price of a reverse auction. Not set for standard listings. shipping-premium: $ref: "#/components/schemas/Pennies" description: Extra paid by the buyer for international shipping. + best-competing-price: + $ref: "#/components/schemas/Pennies" + description: Lowest Marketplace price for the same product and includes. + value: + $ref: "#/components/schemas/Pennies" + description: Current value of a collection item. has-pictures: type: boolean + is-best-priced-offer: + type: boolean + description: Whether this is the lowest priced offer for the product. is-collection: type: boolean is-ended: @@ -890,8 +901,17 @@ components: type: string offer-status: $ref: "#/components/schemas/OfferStatus" + pending-reason: + type: string + description: Why `offer-status` is `pending`. offer-url: type: string + image-url: + type: string + description: Relative URL of the offer's main image. + seller-id: + type: string + description: Seller user ID. sku: type: string description: Only returned to the seller. diff --git a/src/pypricecharting/asyncpricecharting.py b/src/pypricecharting/asyncpricecharting.py index dce3578..e73d1ef 100644 --- a/src/pypricecharting/asyncpricecharting.py +++ b/src/pypricecharting/asyncpricecharting.py @@ -11,8 +11,10 @@ from pypricecharting.requests import OfferPublishRequestParams, OffersRequestParams from pypricecharting.responses import ( OfferDetailsResponse, + OfferEndResponse, OfferFeedbackResponse, OfferPublishResponse, + OfferRefundResponse, OfferShipResponse, OffersResponse, ProductResponse, @@ -26,8 +28,7 @@ class AsyncPriceCharting: """Asynchronous PriceCharting API client. - Reuse one client for all requests and close it when done (`async with` or `aclose()`). The Marketplace - methods `offer_end` and `offer_refund` are not implemented yet and return `None`. + Reuse one client for all requests and close it when done (`async with` or `aclose()`). """ TOKEN_KEY = "PRICECHARTING_TOKEN" @@ -261,10 +262,52 @@ async def offer_ship( response = await self._client.post(Route.Marketplace.OFFER_SHIP, data=data) return _parse(response, OfferShipResponse) - async def offer_end(self): - """End a marketplace offer.""" - pass + async def offer_end(self, offer_id: str) -> OfferEndResponse: + """End a marketplace offer so it can no longer be purchased. - async def offer_refund(self): - """Refund a marketplace offer.""" - pass + For a collection item, this removes it from the collection. + + Args: + offer_id: The offer ID. Surrounding whitespace is stripped. + + Returns: + The ended offer. + + Raises: + ParameterError: If `offer_id` is empty or only whitespace. + APIError: If the API returns an error. + + """ + offer_id = offer_id.strip() + + if len(offer_id) == 0: + raise ParameterError("Invalid parameter; offer_id was empty.") + + response = await self._client.post(Route.Marketplace.OFFER_END, data={"offer-id": offer_id}) + return _parse(response, OfferEndResponse) + + async def offer_refund(self, offer_id: str) -> OfferRefundResponse: + """Refund a purchased marketplace offer. + + Payment is returned immediately from the seller's PayPal account to the buyer. + + Args: + offer_id: The offer ID. Surrounding whitespace is stripped. + + Returns: + The refunded offer. + + Raises: + ParameterError: If `offer_id` is empty or only whitespace. + APIError: If the API returns an error. + + """ + offer_id = offer_id.strip() + + if len(offer_id) == 0: + raise ParameterError("Invalid parameter; offer_id was empty.") + + response = await self._client.post( + Route.Marketplace.OFFER_REFUND, data={"offer-id": offer_id} + ) + return _parse(response, OfferRefundResponse) diff --git a/src/pypricecharting/pricecharting.py b/src/pypricecharting/pricecharting.py index 1e37b92..acc2f15 100644 --- a/src/pypricecharting/pricecharting.py +++ b/src/pypricecharting/pricecharting.py @@ -11,8 +11,10 @@ from pypricecharting.requests import OfferPublishRequestParams, OffersRequestParams from pypricecharting.responses import ( OfferDetailsResponse, + OfferEndResponse, OfferFeedbackResponse, OfferPublishResponse, + OfferRefundResponse, OfferShipResponse, OffersResponse, ProductResponse, @@ -26,8 +28,7 @@ class PriceCharting: """Synchronous PriceCharting API client. - Reuse one client for all requests and close it when done (`with` or `close()`). The Marketplace - methods `offer_end` and `offer_refund` are not implemented yet and return `None`. + Reuse one client for all requests and close it when done (`with` or `close()`). """ TOKEN_KEY = "PRICECHARTING_TOKEN" @@ -256,10 +257,50 @@ def offer_ship(self, offer_id: str, tracking_number: str | None = None) -> Offer response = self._client.post(Route.Marketplace.OFFER_SHIP, data=data) return _parse(response, OfferShipResponse) - def offer_end(self): - """End a marketplace offer.""" - pass + def offer_end(self, offer_id: str) -> OfferEndResponse: + """End a marketplace offer so it can no longer be purchased. - def offer_refund(self): - """Refund a marketplace offer.""" - pass + For a collection item, this removes it from the collection. + + Args: + offer_id: The offer ID. Surrounding whitespace is stripped. + + Returns: + The ended offer. + + Raises: + ParameterError: If `offer_id` is empty or only whitespace. + APIError: If the API returns an error. + + """ + offer_id = offer_id.strip() + + if len(offer_id) == 0: + raise ParameterError("Invalid parameter; offer_id was empty.") + + response = self._client.post(Route.Marketplace.OFFER_END, data={"offer-id": offer_id}) + return _parse(response, OfferEndResponse) + + def offer_refund(self, offer_id: str) -> OfferRefundResponse: + """Refund a purchased marketplace offer. + + Payment is returned immediately from the seller's PayPal account to the buyer. + + Args: + offer_id: The offer ID. Surrounding whitespace is stripped. + + Returns: + The refunded offer. + + Raises: + ParameterError: If `offer_id` is empty or only whitespace. + APIError: If the API returns an error. + + """ + offer_id = offer_id.strip() + + if len(offer_id) == 0: + raise ParameterError("Invalid parameter; offer_id was empty.") + + response = self._client.post(Route.Marketplace.OFFER_REFUND, data={"offer-id": offer_id}) + return _parse(response, OfferRefundResponse) diff --git a/src/pypricecharting/requests.py b/src/pypricecharting/requests.py index 73aff5b..2b55cd4 100644 --- a/src/pypricecharting/requests.py +++ b/src/pypricecharting/requests.py @@ -27,8 +27,8 @@ class OfferPublishRequestParams(PriceChartingModel): """Price in pennies buyers pay, or the starting price when `price_min` is set.""" 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.""" + add_to_collection: State | None = None + """Set to `State.ON` to add the item to your collection instead of listing it for sale.""" cost_basis: int | None = None """What you paid for the item, in pennies.""" description: str | None = None diff --git a/src/pypricecharting/responses.py b/src/pypricecharting/responses.py index d032ff5..4b0b3d1 100644 --- a/src/pypricecharting/responses.py +++ b/src/pypricecharting/responses.py @@ -143,25 +143,37 @@ class OfferDetailsResponse(PriceChartingModel): """What the seller paid for the item, in pennies.""" price: int | None = None """Current price in pennies, or the sale price if sold. Includes any shipping premium.""" - max_price: int | None = None + price_max: int | None = None """Listing price in pennies, or the starting price of a reverse auction.""" - min_price: int | None = None + price_min: int | None = None """Lowest price in pennies of a reverse auction. Not set for standard listings.""" shipping_premium: int | None = None """Extra the buyer paid for international shipping, in pennies.""" + best_competing_price: int | None = None + """Lowest Marketplace price in pennies for the same product and includes.""" + value: int | None = None + """Current value in pennies of a collection item.""" has_pictures: bool | None = None + is_best_priced_offer: bool | None = None + """Whether this is the lowest priced offer for the product.""" is_collection: bool | None = None """Whether the item is in the seller's collection instead of listed for sale.""" is_ended: bool | None = None is_price_descending: bool | None = None - """Whether the offer is a reverse auction, dropping toward `min_price`.""" + """Whether the offer is a reverse auction, dropping toward `price_min`.""" is_refunded: bool | None = None is_shipped: bool | None = None is_sold: bool | None = None offer_id: str | None = None offer_status: OfferStatus | None = None + pending_reason: str | None = None + """Why `offer_status` is `pending`.""" offer_url: str | None = None """Relative URL of the offer page. Prepend `route.BASE_URL` for a full link.""" + image_url: str | None = None + """Relative URL of the offer's main image.""" + seller_id: str | None = None + """Seller's user ID.""" sku: str | None = None """Seller's internal SKU. Only returned to the seller.""" tracking_number: str | None = None diff --git a/tests/mocks/json.py b/tests/mocks/json.py index 17e8ee4..10c0dfc 100644 --- a/tests/mocks/json.py +++ b/tests/mocks/json.py @@ -101,10 +101,13 @@ "includes": "Game only", "cost-basis": 500, "price": 1473, - "max-price": 2000, - "min-price": 1000, + "price-max": 2000, + "price-min": 1000, "shipping-premium": 0, + "best-competing-price": 1299, + "value": 1473, "has-pictures": True, + "is-best-priced-offer": False, "is-collection": False, "is-ended": True, "is-price-descending": True, @@ -113,7 +116,10 @@ "is-sold": True, "offer-id": "testofferid", "offer-status": "sold", + "pending-reason": "", "offer-url": "/offer/testofferid", + "image-url": "/images/offers/testofferid.jpg", + "seller-id": "3mxwhfh46xj3f47cgdyu5ynzos", "sku": "ABC-123", "tracking-number": "901234567890000", "start-time": "2017-10-01", diff --git a/tests/requests/test_offers_publish.py b/tests/requests/test_offers_publish.py index cb5256d..d17c495 100644 --- a/tests/requests/test_offers_publish.py +++ b/tests/requests/test_offers_publish.py @@ -42,3 +42,20 @@ 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"): OfferPublishRequestParams(price_max=2500, condition_id=1) + + +def test_offer_publish_add_to_collection(): + request = OfferPublishRequestParams( + product="6910", price_max=2500, condition_id=1, add_to_collection=State.ON + ) + + dumped = request.model_dump(mode="json", by_alias=True, exclude_none=True) + + assert dumped["add-to-collection"] == "on" + + +def test_offer_publish_add_to_collection_rejects_other_values(): + with pytest.raises(ValidationError, match="add-to-collection"): + OfferPublishRequestParams.model_validate( + {"product": "6910", "price-max": 2500, "condition-id": 1, "add-to-collection": "yes"} + ) diff --git a/tests/responses/test_offer_details.py b/tests/responses/test_offer_details.py index 1f11f42..08c62da 100644 --- a/tests/responses/test_offer_details.py +++ b/tests/responses/test_offer_details.py @@ -29,10 +29,13 @@ def test_offer_details_json_to_model(): assert details.includes == "Game only" assert details.cost_basis == 500 assert details.price == 1473 - assert details.max_price == 2000 - assert details.min_price == 1000 + assert details.price_max == 2000 + assert details.price_min == 1000 assert details.shipping_premium == 0 + assert details.best_competing_price == 1299 + assert details.value == 1473 assert details.has_pictures is True + assert details.is_best_priced_offer is False assert details.is_collection is False assert details.is_ended is True assert details.is_price_descending is True @@ -41,7 +44,10 @@ def test_offer_details_json_to_model(): assert details.is_sold is True assert details.offer_id == "testofferid" assert details.offer_status is OfferStatus.SOLD + assert details.pending_reason == "" assert details.offer_url == "/offer/testofferid" + assert details.image_url == "/images/offers/testofferid.jpg" + assert details.seller_id == "3mxwhfh46xj3f47cgdyu5ynzos" assert details.sku == "ABC-123" assert details.tracking_number == "901234567890000" assert details.start_time == date(2017, 10, 1) @@ -63,3 +69,12 @@ def test_offer_details_without_buyer(): details = OfferDetailsResponse.model_validate_json('{"status": "success"}') assert details.buyer is None + + +def test_offer_details_pending_reason(): + details = OfferDetailsResponse.model_validate_json( + '{"status": "success", "offer-status": "pending", "pending-reason": "Vacation hold"}' + ) + + assert details.offer_status is OfferStatus.PENDING + assert details.pending_reason == "Vacation hold" diff --git a/tests/test_asyncpricecharting_marketplace.py b/tests/test_asyncpricecharting_marketplace.py index 32d2748..ebfd67e 100644 --- a/tests/test_asyncpricecharting_marketplace.py +++ b/tests/test_asyncpricecharting_marketplace.py @@ -3,31 +3,31 @@ import pytest from httpx2 import Request, Response -from pypricecharting.asyncpricecharting import AsyncPriceCharting from pypricecharting.error import APIError, ParameterError from pypricecharting.requests import OfferPublishRequestParams, OffersRequestParams, OffersStatus from pypricecharting.responses import ( OfferDetailsResponse, + OfferEndResponse, OfferFeedbackResponse, OfferPublishResponse, + OfferRefundResponse, OfferShipResponse, OffersResponse, ) from pypricecharting.types import Condition, Rating, Status from tests.mocks.json import ( OFFER_DETAILS_JSON, + OFFER_END_JSON, OFFER_FEEDBACK_JSON, OFFER_PUBLISH_REQUEST_JSON, OFFER_PUBLISH_RESPONSE_JSON, + OFFER_REFUND_JSON, OFFER_SHIP_JSON, 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(): requests: list[Request] = [] @@ -294,12 +294,86 @@ async def test_offer_ship_raises_api_error(): async def test_offer_end(): - client = AsyncPriceCharting(TOKEN) - assert await client.offer_end() is None - await client.aclose() + requests: list[Request] = [] + + async with mocked_async_client(TOKEN, Response(200, json=OFFER_END_JSON), requests) as client: + response = await client.offer_end(" vtdsww72uyslgooawzyyijsllm ") + + assert isinstance(response, OfferEndResponse) + assert response.status == Status.SUCCESS + assert response.offer_id == "vtdsww72uyslgooawzyyijsllm" + assert response.is_ended is True + + assert len(requests) == 1 + assert requests[0].method == "POST" + assert requests[0].url.path == "/api/offer-end" + assert "t" not in requests[0].url.params + assert dict(parse_qsl(requests[0].content.decode())) == { + "offer-id": "vtdsww72uyslgooawzyyijsllm", + "t": TOKEN, + } + + +@pytest.mark.parametrize("offer_id", ["", " "]) +async def test_offer_end_empty_offer_id_raises_parameter_error(offer_id: str): + requests: list[Request] = [] + + async with mocked_async_client(TOKEN, Response(200, json=OFFER_END_JSON), requests) as client: + with pytest.raises(ParameterError, match="offer_id was empty"): + await client.offer_end(offer_id) + + assert requests == [] + + +async def test_offer_end_raises_api_error(): + requests: list[Request] = [] + async with mocked_async_client( + TOKEN, Response(404, json=error_body("No such offer")), requests + ) as client: + with pytest.raises(APIError, match="404: No such offer"): + await client.offer_end("missing") async def test_offer_refund(): - client = AsyncPriceCharting(TOKEN) - assert await client.offer_refund() is None - await client.aclose() + requests: list[Request] = [] + + async with mocked_async_client( + TOKEN, Response(200, json=OFFER_REFUND_JSON), requests + ) as client: + response = await client.offer_refund(" vtdsww72uyslgooawzyyijsllm ") + + assert isinstance(response, OfferRefundResponse) + assert response.status == Status.SUCCESS + assert response.offer_id == "vtdsww72uyslgooawzyyijsllm" + assert response.is_refunded is True + + assert len(requests) == 1 + assert requests[0].method == "POST" + assert requests[0].url.path == "/api/offer-refund" + assert "t" not in requests[0].url.params + assert dict(parse_qsl(requests[0].content.decode())) == { + "offer-id": "vtdsww72uyslgooawzyyijsllm", + "t": TOKEN, + } + + +@pytest.mark.parametrize("offer_id", ["", " "]) +async def test_offer_refund_empty_offer_id_raises_parameter_error(offer_id: str): + requests: list[Request] = [] + + async with mocked_async_client( + TOKEN, Response(200, json=OFFER_REFUND_JSON), requests + ) as client: + with pytest.raises(ParameterError, match="offer_id was empty"): + await client.offer_refund(offer_id) + + assert requests == [] + + +async def test_offer_refund_raises_api_error(): + requests: list[Request] = [] + async with mocked_async_client( + TOKEN, Response(404, json=error_body("No such offer")), requests + ) as client: + with pytest.raises(APIError, match="404: No such offer"): + await client.offer_refund("missing") diff --git a/tests/test_pricecharting_marketplace.py b/tests/test_pricecharting_marketplace.py index 7f84daf..f92062f 100644 --- a/tests/test_pricecharting_marketplace.py +++ b/tests/test_pricecharting_marketplace.py @@ -4,30 +4,30 @@ from httpx2 import Request, Response from pypricecharting.error import APIError, ParameterError -from pypricecharting.pricecharting import PriceCharting from pypricecharting.requests import OfferPublishRequestParams, OffersRequestParams, OffersStatus from pypricecharting.responses import ( OfferDetailsResponse, + OfferEndResponse, OfferFeedbackResponse, OfferPublishResponse, + OfferRefundResponse, OfferShipResponse, OffersResponse, ) from pypricecharting.types import Condition, Rating, Status from tests.mocks.json import ( OFFER_DETAILS_JSON, + OFFER_END_JSON, OFFER_FEEDBACK_JSON, OFFER_PUBLISH_REQUEST_JSON, OFFER_PUBLISH_RESPONSE_JSON, + OFFER_REFUND_JSON, OFFER_SHIP_JSON, 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(): requests: list[Request] = [] @@ -282,12 +282,86 @@ def test_offer_ship_raises_api_error(): def test_offer_end(): - client = PriceCharting(TOKEN) - assert client.offer_end() is None - client.close() + requests: list[Request] = [] + + with mocked_client(TOKEN, Response(200, json=OFFER_END_JSON), requests) as client: + response = client.offer_end(" vtdsww72uyslgooawzyyijsllm ") + + assert isinstance(response, OfferEndResponse) + assert response.status == Status.SUCCESS + assert response.offer_id == "vtdsww72uyslgooawzyyijsllm" + assert response.is_ended is True + + assert len(requests) == 1 + assert requests[0].method == "POST" + assert requests[0].url.path == "/api/offer-end" + assert "t" not in requests[0].url.params + assert dict(parse_qsl(requests[0].content.decode())) == { + "offer-id": "vtdsww72uyslgooawzyyijsllm", + "t": TOKEN, + } + + +@pytest.mark.parametrize("offer_id", ["", " "]) +def test_offer_end_empty_offer_id_raises_parameter_error(offer_id: str): + requests: list[Request] = [] + + with ( + mocked_client(TOKEN, Response(200, json=OFFER_END_JSON), requests) as client, + pytest.raises(ParameterError, match="offer_id was empty"), + ): + client.offer_end(offer_id) + + assert requests == [] + + +def test_offer_end_raises_api_error(): + requests: list[Request] = [] + with ( + mocked_client(TOKEN, Response(404, json=error_body("No such offer")), requests) as client, + pytest.raises(APIError, match="404: No such offer"), + ): + client.offer_end("missing") def test_offer_refund(): - client = PriceCharting(TOKEN) - assert client.offer_refund() is None - client.close() + requests: list[Request] = [] + + with mocked_client(TOKEN, Response(200, json=OFFER_REFUND_JSON), requests) as client: + response = client.offer_refund(" vtdsww72uyslgooawzyyijsllm ") + + assert isinstance(response, OfferRefundResponse) + assert response.status == Status.SUCCESS + assert response.offer_id == "vtdsww72uyslgooawzyyijsllm" + assert response.is_refunded is True + + assert len(requests) == 1 + assert requests[0].method == "POST" + assert requests[0].url.path == "/api/offer-refund" + assert "t" not in requests[0].url.params + assert dict(parse_qsl(requests[0].content.decode())) == { + "offer-id": "vtdsww72uyslgooawzyyijsllm", + "t": TOKEN, + } + + +@pytest.mark.parametrize("offer_id", ["", " "]) +def test_offer_refund_empty_offer_id_raises_parameter_error(offer_id: str): + requests: list[Request] = [] + + with ( + mocked_client(TOKEN, Response(200, json=OFFER_REFUND_JSON), requests) as client, + pytest.raises(ParameterError, match="offer_id was empty"), + ): + client.offer_refund(offer_id) + + assert requests == [] + + +def test_offer_refund_raises_api_error(): + requests: list[Request] = [] + with ( + mocked_client(TOKEN, Response(404, json=error_body("No such offer")), requests) as client, + pytest.raises(APIError, match="404: No such offer"), + ): + client.offer_refund("missing")