Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
2 changes: 2 additions & 0 deletions src/pypricecharting/__init__.py
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@
from pypricecharting.pricecharting import PriceCharting
from pypricecharting.requests import OfferPublishRequest
from pypricecharting.responses import (
ErrorResponse,
OfferDetailsResponse,
OfferEndResponse,
OfferFeedbackResponse,
Expand Down Expand Up @@ -38,6 +39,7 @@
"Comics",
"Condition",
"Console",
"ErrorResponse",
"Genre",
"Offer",
"OfferDetailsResponse",
Expand Down
30 changes: 24 additions & 6 deletions src/pypricecharting/responses.py
Original file line number Diff line number Diff line change
@@ -1,13 +1,28 @@
from contextlib import suppress
from datetime import date

from httpx2 import Response
from pydantic import Field
from pydantic import Field, ValidationError

from pypricecharting.error import APIError
from pypricecharting.models import Buyer, Offer, PriceChartingModel, ProductSummary
from pypricecharting.types import OfferStatus, Rating, Status


class ErrorResponse(PriceChartingModel):
"""Error response from any endpoint

Returned with a 4xx or 5xx status code and `status: error`. The clients raise
`error.APIError` with the message instead of returning this model.

https://www.pricecharting.com/api-documentation
"""

status: Status
error_message: str | None = None
"""Why the request failed."""


class ProductResponse(ProductSummary):
"""api/product response

Expand Down Expand Up @@ -255,8 +270,9 @@ def _parse[M: PriceChartingModel](response: Response, model: type[M]) -> M:
The validated response model.

Raises:
APIError: If the response is not JSON, has a non-2xx status code, or has
`status: error`.
APIError: If the response is not JSON or has a non-2xx status code. The message is
the `error-message` from the body, parsed as an `ErrorResponse`, or the HTTP
reason phrase if the body has none.

"""
try:
Expand All @@ -266,8 +282,10 @@ def _parse[M: PriceChartingModel](response: Response, model: type[M]) -> M:
response.reason_phrase or "Invalid JSON response", response.status_code
) from None

if not response.is_success or data.get("status") == "error":
message = data.get("error-message", response.reason_phrase or "Unknown error")
raise APIError(message, response.status_code)
if not response.is_success:
message = None
with suppress(ValidationError):
message = ErrorResponse.model_validate(data).error_message
raise APIError(message or response.reason_phrase or "Unknown error", response.status_code)

return model.model_validate(data)
202 changes: 202 additions & 0 deletions tests/mocks/json.py
Original file line number Diff line number Diff line change
@@ -0,0 +1,202 @@
"""Shared JSON test data, in the API's kebab-case format."""

# Models

BUYER_JSON = {
"buyer-email": "buyer@example.com",
"shipping-name": "Jane Doe",
"shipping-line1": "123 Main St",
"shipping-line2": "Apt 4",
"shipping-city": "Springfield",
"shipping-state": "IL",
"shipping-zip": "62701",
"shipping-country": "US",
}


OFFER_JSON = {
"offer-id": "smzksacsy5i2dsrddxsrlzsp6i",
"offer-status": "sold",
"offer-url": "/offer/smzksacsy5i2dsrddxsrlzsp6i",
"id": 9307,
"product-name": "M.C. Kids",
"console-name": "NES",
"condition-string": "Normal wear",
"include-string": "Game only",
"price": 1473,
"is-available": False,
"is-sold": True,
"is-ended": True,
"is-shipped": False,
"sale-time": "2017-10-31",
"shipped-time": "0001-01-01",
"ended-time": "2017-10-31",
"cert-id": "5672930123",
"grade-co-id": 1,
}


PRODUCT_SUMMARY_JSON = {
"id": "4801",
"product-name": "Tactics Ogre",
"console-name": "Playstation",
}


# Requests

OFFER_PUBLISH_REQUEST_JSON = {
"product": "6910",
"price-max": 2500,
"price-min": 1500,
"condition-id": "1",
"cost-basis": 1000,
"broken": "on",
"sku": "ABC-123",
"quantity": 2,
}


# Responses

ERROR_JSON = {"status": "error", "error-message": "No such product"}

OFFERS_JSON = {
"status": "success",
"offers": [
{"offer-id": "smzksacsy5i2dsrddxsrlzsp6i", "offer-status": "sold", "price": 1473},
{"offer-id": "vtdsww72uyslgooawzyyijsllm", "offer-status": "available", "price": 2500},
],
}


OFFER_DETAILS_JSON = {
"status": "success",
"buyer": {
"buyer-email": "buyer@example.com",
"shipping-name": "Jane Doe",
"shipping-line1": "123 Main St",
"shipping-city": "Springfield",
"shipping-state": "IL",
"shipping-zip": "62701",
"shipping-country": "US",
},
"buyer-left-feedback": False,
"seller-left-feedback": True,
"id": 9307,
"product-name": "M.C. Kids",
"console-name": "NES",
"condition": "Normal wear",
"includes": "Game only",
"cost-basis": 500,
"price": 1473,
"max-price": 2000,
"min-price": 1000,
"shipping-premium": 0,
"has-pictures": True,
"is-collection": False,
"is-ended": True,
"is-price-descending": True,
"is-refunded": False,
"is-shipped": True,
"is-sold": True,
"offer-id": "smzksacsy5i2dsrddxsrlzsp6i",
"offer-status": "sold",
"offer-url": "/offer/smzksacsy5i2dsrddxsrlzsp6i",
"sku": "ABC-123",
"tracking-number": "901234567890000",
"start-time": "2017-10-01",
"sale-time": "2017-10-31",
"shipped-time": "2017-11-01",
"ended-time": "2017-10-31",
"refunded-time": "0001-01-01",
}


OFFER_END_JSON = {
"status": "success",
"offer-id": "vtdsww72uyslgooawzyyijsllm",
"is-ended": True,
"ended-time": "2017-10-31",
}


OFFER_FEEDBACK_JSON = {
"status": "success",
"offer-id": "vtdsww72uyslgooawzyyijsllm",
"rating": 2,
"comment": "Great buyer",
}


OFFER_PUBLISH_RESPONSE_JSON = {
"status": "success",
"offer-id": "vtdsww72uyslgooawzyyijsllm",
"offer-url": "/offer/vtdsww72uyslgooawzyyijsllm",
"offer-status": "available",
"product-name": "EarthBound",
"console-name": "Super Nintendo",
"condition-string": "Normal wear",
"include-string": "Game only",
"has-pictures": False,
"price": 2500,
"cost-basis": 1000,
"sku": "ABC-123",
"is-collection": False,
"quantity": 2,
"start-time": "2017-10-31",
}


OFFER_REFUND_JSON = {
"status": "success",
"offer-id": "vtdsww72uyslgooawzyyijsllm",
"is-refunded": True,
"refunded-time": "2017-10-31",
}


OFFER_SHIP_JSON = {
"status": "success",
"offer-id": "vtdsww72uyslgooawzyyijsllm",
"is-shipped": True,
"shipped-time": "2017-10-31",
"tracking-number": "901234567890000",
}


PRODUCTS_JSON = {
"status": "success",
"products": [
PRODUCT_SUMMARY_JSON,
{"console-name": "GameBoy Advance", "id": "2611", "product-name": "Tactics Ogre"},
],
}


PRODUCT_BASIC_JSON = {
"status": "success",
"id": "6910",
"product-name": "EarthBound",
"console-name": "Super Nintendo",
"loose-price": 17244,
"cib-price": 42995,
"new-price": 53000,
"release-date": "1995-06-05",
}


PRODUCT_JSON = {
"status": "success",
"id": "6910",
"product-name": "EarthBound",
"console-name": "Super Nintendo",
"release-date": "1995-06-05",
"sales-volume": 120,
"loose-price": 17244,
"cib-price": 42995,
"new-price": 53000,
"bgs-10-price": 60000,
"condition-9-price": 9000,
"retail-loose-buy": 12000,
}
12 changes: 12 additions & 0 deletions tests/mocks/mock_pricecharting.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,11 @@

from pypricecharting.asyncpricecharting import AsyncPriceCharting
from pypricecharting.pricecharting import PriceCharting
from pypricecharting.responses import ErrorResponse
from pypricecharting.types import Status

TOKEN = "test-token-12345678901234567890123456789"
"""A fake 40-character API token for tests."""


def mocked_client(token: str | None, response: Response, requests: list[Request]) -> PriceCharting:
Expand All @@ -24,3 +29,10 @@ def handler(request: Request) -> Response:
return response

return AsyncPriceCharting(token=token, transport=MockTransport(handler))


def error_body(message: str | None = None) -> dict:
"""Build an API error response body in JSON form, with an optional `error-message`."""
return ErrorResponse(status=Status.ERROR, error_message=message).model_dump(
mode="json", by_alias=True, exclude_none=True
)
12 changes: 1 addition & 11 deletions tests/models/test_buyer.py
Original file line number Diff line number Diff line change
@@ -1,17 +1,7 @@
import json

from pypricecharting.models import Buyer

BUYER_JSON = {
"buyer-email": "buyer@example.com",
"shipping-name": "Jane Doe",
"shipping-line1": "123 Main St",
"shipping-line2": "Apt 4",
"shipping-city": "Springfield",
"shipping-state": "IL",
"shipping-zip": "62701",
"shipping-country": "US",
}
from tests.mocks.json import BUYER_JSON


def test_buyer_json_to_model():
Expand Down
22 changes: 1 addition & 21 deletions tests/models/test_offer.py
Original file line number Diff line number Diff line change
Expand Up @@ -6,27 +6,7 @@

from pypricecharting.models import Offer
from pypricecharting.types import OfferStatus

OFFER_JSON = {
"offer-id": "smzksacsy5i2dsrddxsrlzsp6i",
"offer-status": "sold",
"offer-url": "/offer/smzksacsy5i2dsrddxsrlzsp6i",
"id": 9307,
"product-name": "M.C. Kids",
"console-name": "NES",
"condition-string": "Normal wear",
"include-string": "Game only",
"price": 1473,
"is-available": False,
"is-sold": True,
"is-ended": True,
"is-shipped": False,
"sale-time": "2017-10-31",
"shipped-time": "0001-01-01",
"ended-time": "2017-10-31",
"cert-id": "5672930123",
"grade-co-id": 1,
}
from tests.mocks.json import OFFER_JSON


def test_offer_json_to_model():
Expand Down
7 changes: 1 addition & 6 deletions tests/models/test_product_summary.py
Original file line number Diff line number Diff line change
@@ -1,12 +1,7 @@
import json

from pypricecharting.models import ProductSummary

PRODUCT_SUMMARY_JSON = {
"id": "4801",
"product-name": "Tactics Ogre",
"console-name": "Playstation",
}
from tests.mocks.json import PRODUCT_SUMMARY_JSON


def test_product_summary_json_to_model():
Expand Down
16 changes: 3 additions & 13 deletions tests/requests/test_request.py
Original file line number Diff line number Diff line change
Expand Up @@ -5,21 +5,11 @@

from pypricecharting.requests import OfferPublishRequest
from pypricecharting.types import State

OFFER_PUBLISH_JSON = {
"product": "6910",
"price-max": 2500,
"price-min": 1500,
"condition-id": "1",
"cost-basis": 1000,
"broken": "on",
"sku": "ABC-123",
"quantity": 2,
}
from tests.mocks.json import OFFER_PUBLISH_REQUEST_JSON


def test_offer_publish_json_to_model():
request = OfferPublishRequest.model_validate_json(json.dumps(OFFER_PUBLISH_JSON))
request = OfferPublishRequest.model_validate_json(json.dumps(OFFER_PUBLISH_REQUEST_JSON))

assert request.product == "6910"
assert request.price_max == 2500
Expand All @@ -46,7 +36,7 @@ def test_offer_publish_model_to_json():

dumped = request.model_dump_json(by_alias=True, exclude_none=True)

assert json.loads(dumped) == OFFER_PUBLISH_JSON
assert json.loads(dumped) == OFFER_PUBLISH_REQUEST_JSON


def test_offer_publish_model_raises():
Expand Down
Loading
Loading