Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Add currency validation to `ShippingMethodSchema` (#17754)
Iga Karbowiakb2782842a8d6
diff --git a/saleor/plugins/webhook/plugin.py b/saleor/plugins/webhook/plugin.pyindex b6fcd66b17..5e4ee966b3 100644--- a/saleor/plugins/webhook/plugin.py+++ b/saleor/plugins/webhook/plugin.py@@ -3595,7 +3595,7 @@ class WebhookPlugin(BasePlugin):if response_data:shipping_methods = parse_list_shipping_methods_response(- response_data, webhook.app+ response_data, webhook.app, checkout.currency)methods.extend(shipping_methods)return methodsdiff --git a/saleor/plugins/webhook/tests/test_shipping_webhook.py b/saleor/plugins/webhook/tests/test_shipping_webhook.pyindex 2e5a9d90db..ec53c3b204 100644--- a/saleor/plugins/webhook/tests/test_shipping_webhook.py+++ b/saleor/plugins/webhook/tests/test_shipping_webhook.py@@ -1301,7 +1301,7 @@ def test_parse_list_shipping_methods_response_response_incorrect_format(response_data_with_incorrect_format = [[1], 2, "3"]# whenresult = parse_list_shipping_methods_response(- response_data_with_incorrect_format, app+ response_data_with_incorrect_format, app, "USD")# thenassert result == []@@ -1326,7 +1326,7 @@ def test_parse_list_shipping_methods_with_metadata(app):}]# when- response = parse_list_shipping_methods_response(response_data_with_meta, app)+ response = parse_list_shipping_methods_response(response_data_with_meta, app, "USD")# thenassert response[0].metadata == response_data_with_meta[0]["metadata"]assert response[0].description == response_data_with_meta[0]["description"]@@ -1347,7 +1347,7 @@ def test_parse_list_shipping_methods_with_metadata_in_incorrect_format(app):}]# when- response = parse_list_shipping_methods_response(response_data_with_meta, app)+ response = parse_list_shipping_methods_response(response_data_with_meta, app, "USD")# thenassert response[0].metadata == {}@@ -1366,7 +1366,7 @@ def test_parse_list_shipping_methods_metadata_absent_in_response(app):}]# when- response = parse_list_shipping_methods_response(response_data_with_meta, app)+ response = parse_list_shipping_methods_response(response_data_with_meta, app, "USD")# thenassert response[0].metadata == {}@@ -1387,6 +1387,6 @@ def test_parse_list_shipping_methods_metadata_is_none(app):}]# when- response = parse_list_shipping_methods_response(response_data_with_meta, app)+ response = parse_list_shipping_methods_response(response_data_with_meta, app, "USD")# thenassert response[0].metadata == {}diff --git a/saleor/webhook/response_schemas/shipping.py b/saleor/webhook/response_schemas/shipping.pyindex 1cd5b94948..e68c297a75 100644--- a/saleor/webhook/response_schemas/shipping.py+++ b/saleor/webhook/response_schemas/shipping.py@@ -27,13 +27,54 @@ T = TypeVar("T")class ShippingMethodSchema(BaseModel):- id: Annotated[str, Field(coerce_numbers_to_str=True)]- name: Annotated[str, Field(max_length=name_max_length)]- amount: Annotated[Decimal, Field(ge=0)]- currency: str- maximum_delivery_days: Annotated[int, Field(ge=0)] | None = None- minimum_delivery_days: Annotated[int, Field(ge=0)] | None = None- description: str | None = None+ id: Annotated[+ str, Field(coerce_numbers_to_str=True, description="ID of the shipping method.")+ ]+ name: Annotated[+ str,+ Field(max_length=name_max_length, description="Name of the shipping method."),+ ]+ amount: Annotated[+ Decimal,+ Field(+ ge=Decimal("0"),+ description="Non-negative price the customer pays for delivery using this shipping method.",+ examples=[Decimal("10.00")],+ ),+ ]+ currency: Annotated[+ str,+ Field(+ description="Currency code for amount. Must match the currency of object for which the methods are defined."+ ),+ ]+ maximum_delivery_days: (+ Annotated[+ int,+ Field(+ ge=0,+ description="Maximum delivery days for delivery promise of shipping carrier.",+ ),+ ]+ | None+ ) = None+ minimum_delivery_days: (+ Annotated[+ int,+ Field(+ ge=0,+ description="Minimum delivery days for delivery promise of shipping carrier.",+ ),+ ]+ | None+ ) = None+ description: (+ Annotated[+ str,+ Field(max_length=255, description="Description of the shipping method."),+ ]+ | None+ ) = Nonemetadata: DefaultIfNone[Metadata] = {}@property@@ -48,6 +89,20 @@ class ShippingMethodSchema(BaseModel):raise RuntimeError("Missing app in context")return to_shipping_app_id(app, shipping_method_id)+ @field_validator("currency", mode="before")+ @classmethod+ def clean_currency(cls, value: str, info: ValidationInfo) -> str:+ currency: str | None = (+ info.context.get("currency", None) if info.context else None+ )+ if not currency:+ raise ValueError("Missing currency in context")+ if value != currency:+ error_msg = "ShippingMethod currency mismatch: expected %s, got %s"+ logger.warning(error_msg, currency, value, extra={"value": value})+ raise ValueError(error_msg % (currency, value))+ return value.upper()+class ListShippingMethodsSchema(RootModel):root: DefaultIfNone[list[OnErrorSkip[ShippingMethodSchema]]] = []diff --git a/saleor/webhook/tests/response_schemas/test_shipping.py b/saleor/webhook/tests/response_schemas/test_shipping.pyindex 519d829aab..e486030333 100644--- a/saleor/webhook/tests/response_schemas/test_shipping.py+++ b/saleor/webhook/tests/response_schemas/test_shipping.py@@ -97,7 +97,7 @@ def decode_id(id):def test_shipping_method_schema_valid(data, app):# whenshipping_method_model = ShippingMethodSchema.model_validate(- data, context={"app": app}+ data, context={"app": app, "currency": data["currency"]})# then@@ -130,7 +130,7 @@ def test_shipping_method_schema_invalid_metadata_skipped(metadata, app):# whenshipping_method_model = ShippingMethodSchema.model_validate(- data, context={"app": app}+ data, context={"app": app, "currency": data["currency"]})# then@@ -145,99 +145,156 @@ def test_shipping_method_schema_invalid_metadata_skipped(metadata, app):@pytest.mark.parametrize(- "data",+ ("data", "invalid_field"),[# Missing required fields - missing id- {- "name": "Standard Shipping",- "amount": Decimal("10.00"),- "currency": "USD",- },+ (+ {+ "name": "Standard Shipping",+ "amount": Decimal("10.00"),+ "currency": "USD",+ },+ "id",+ ),# Missing required fields - missing name- {- "id": 0,- "amount": Decimal("10.00"),- "currency": "USD",- },+ (+ {+ "id": 0,+ "amount": Decimal("10.00"),+ "currency": "USD",+ },+ "name",+ ),# Missing required fields - missing amount- {- "id": 0,- "name": "Standard Shipping",- "currency": "USD",- },+ (+ {+ "id": 0,+ "name": "Standard Shipping",+ "currency": "USD",+ },+ "amount",+ ),+ # Missing required fields - missing currency+ (+ {+ "id": 0,+ "amount": Decimal("10.00"),+ "name": "Standard Shipping",+ },+ "currency",+ ),# Invalid type for "id"- {- "id": {"invalid": "dict"},- "name": "Standard Shipping",- "amount": Decimal("10.00"),- "currency": "USD",- },+ (+ {+ "id": {"invalid": "dict"},+ "name": "Standard Shipping",+ "amount": Decimal("10.00"),+ "currency": "USD",+ },+ "id",+ ),# Invalid type for "amount"- {- "id": "1",- "name": "Standard Shipping",- "amount": "invalid_amount",- "currency": "USD",- },+ (+ {+ "id": "1",+ "name": "Standard Shipping",+ "amount": "invalid_amount",+ "currency": "USD",+ },+ "amount",+ ),# Negative value for "amount"- {- "id": "2",- "name": "Express Shipping",- "amount": Decimal("-10.00"),- "currency": "USD",- },+ (+ {+ "id": "2",+ "name": "Express Shipping",+ "amount": Decimal("-10.00"),+ "currency": "USD",+ },+ "amount",+ ),# Invalid type for "maximum_delivery_days"- {- "id": "5",- "name": "International Shipping",- "amount": Decimal("30.00"),- "currency": "USD",- "maximum_delivery_days": "invalid_days",- },+ (+ {+ "id": "5",+ "name": "International Shipping",+ "amount": Decimal("30.00"),+ "currency": "USD",+ "maximum_delivery_days": "invalid_days",+ },+ "maximum_delivery_days",+ ),# Invalid type for "minimum_delivery_days"- {- "id": "5",- "name": "International Shipping",- "amount": Decimal("30.00"),- "currency": "USD",- "minimum_delivery_days": "invalid_days",- },+ (+ {+ "id": "5",+ "name": "International Shipping",+ "amount": Decimal("30.00"),+ "currency": "USD",+ "minimum_delivery_days": "invalid_days",+ },+ "minimum_delivery_days",+ ),# Negative value for "maximum_delivery_days"- {- "id": 6,- "name": "Economy Shipping",- "amount": Decimal("5.00"),- "currency": "USD",- "maximum_delivery_days": -1,- },+ (+ {+ "id": 6,+ "name": "Economy Shipping",+ "amount": Decimal("5.00"),+ "currency": "USD",+ "maximum_delivery_days": -1,+ },+ "maximum_delivery_days",+ ),# Negative value for "minimum_delivery_days"- {- "id": 6,- "name": "Economy Shipping",- "amount": Decimal("5.00"),- "currency": "USD",- "minimum_delivery_days": -1,- },+ (+ {+ "id": 6,+ "name": "Economy Shipping",+ "amount": Decimal("5.00"),+ "currency": "USD",+ "minimum_delivery_days": -1,+ },+ "minimum_delivery_days",+ ),# Name exceeds max length- {- "id": 7,- "name": "A" * 300,- "amount": Decimal("15.00"),- "currency": "USD",- },+ (+ {+ "id": 7,+ "name": "A" * 300,+ "amount": Decimal("15.00"),+ "currency": "USD",+ },+ "name",+ ),+ # Currency mismatch+ (+ {+ "id": 0,+ "amount": Decimal("10.00"),+ "name": "Standard Shipping",+ "currency": "PLN",+ },+ "currency",+ ),],)-def test_shipping_method_schema_invalid(data, app):- with pytest.raises(ValidationError) as e:- ShippingMethodSchema.model_validate(data, context={"app": app})+def test_shipping_method_schema_invalid(data, app, invalid_field):+ with pytest.raises(ValidationError) as exc_info:+ ShippingMethodSchema.model_validate(+ data, context={"app": app, "currency": "USD"}+ )- assert len(e.value.errors()) == 1+ assert len(exc_info.value.errors()) == 1+ assert exc_info.value.errors()[0]["loc"] == (invalid_field,)@pytest.mark.parametrize("data", [None, []])def test_list_shipping_methods_schema_skipped_values(data, app):# when- list_methods = ListShippingMethodsSchema.model_validate(data, context={"app": app})+ list_methods = ListShippingMethodsSchema.model_validate(+ data, context={"app": app, "currency": "USD"}+ )# Then the root should be an empty listassert list_methods.root == []@@ -262,18 +319,26 @@ def test_list_shipping_methods_schema_invalid_element_skipped(mocked_logger, app"id": "2","name": "Express Shipping","amount": "invalid_amount", # Invalid amount- "currency": "EUR",+ "currency": "USD",+ },+ {+ "id": "2",+ "name": "Express Shipping",+ "amount": Decimal("10.00"),+ "currency": "PLN", # Currency mismatch},]# when- schema = ListShippingMethodsSchema.model_validate(data, context={"app": app})+ schema = ListShippingMethodsSchema.model_validate(+ data, context={"app": app, "currency": "USD"}+ )# then only the valid shipping method should be includedassert len(schema.root) == 1assert schema.root[0].id == to_shipping_app_id(app, data[0]["id"])assert schema.root[0].name == data[0]["name"]- assert mocked_logger.call_count == 1+ assert mocked_logger.call_count == 2@pytest.mark.parametrize(diff --git a/saleor/webhook/transport/shipping.py b/saleor/webhook/transport/shipping.pyindex 4af722b8c9..f8245901a4 100644--- a/saleor/webhook/transport/shipping.py+++ b/saleor/webhook/transport/shipping.py@@ -28,13 +28,14 @@ logger = logging.getLogger(__name__)def parse_list_shipping_methods_response(- response_data: Any, app: "App"+ response_data: Any, app: "App", object_currency: str) -> list["ShippingMethodData"]:try:list_shipping_method_model = ListShippingMethodsSchema.model_validate(response_data,context={"app": app,+ "currency": object_currency,"custom_message": "Skipping invalid shipping method (ListShippingMethodsSchema)",},)