Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Introduce static typing for `LIST_STORED_PAYMENT_METHODS` webhook (#17668)
Iga Karbowiak1ef1f7413cc4
diff --git a/saleor/payment/interface.py b/saleor/payment/interface.pyindex 2b2b9ef527..bbd05c103f 100644--- a/saleor/payment/interface.py+++ b/saleor/payment/interface.py@@ -105,7 +105,7 @@ class PaymentMethodData:supported_payment_flows: list[str] = field(default_factory=list)credit_card_info: PaymentMethodCreditCardInfo | None = Nonename: str | None = None- data: JSONType | None = None+ data: JSONValue | None = None@dataclassdiff --git a/saleor/plugins/webhook/tests/test_shipping_webhook.py b/saleor/plugins/webhook/tests/test_shipping_webhook.pyindex 6400a58928..3d3e917e0a 100644--- a/saleor/plugins/webhook/tests/test_shipping_webhook.py+++ b/saleor/plugins/webhook/tests/test_shipping_webhook.py@@ -17,6 +17,7 @@ from ....webhook.payloads import (generate_excluded_shipping_methods_for_checkout_payload,generate_excluded_shipping_methods_for_order_payload,)+from ....webhook.response_schemas.annotations import logger as annotations_loggerfrom ....webhook.response_schemas.shipping import logger as schema_loggerfrom ....webhook.transport.shipping import (get_excluded_shipping_methods_from_response,@@ -395,8 +396,11 @@ def test_multiple_webhooks_on_the_same_app_with_excluded_shipping_methods_for_or)[email protected](annotations_logger, "warning")@mock.patch.object(schema_logger, "warning")-def test_parse_excluded_shipping_methods_response(mocked_schema_logger, app):+def test_parse_excluded_shipping_methods_response(+ mocked_schema_logger, mocked_annotations_logger, app+):# givenexternal_id = to_shipping_app_id(app, "test-1234")response = {@@ -432,7 +436,44 @@ def test_parse_excluded_shipping_methods_response(mocked_schema_logger, app):assert excluded_methods[0].id == "2"assert excluded_methods[1].id == external_id# 2 warning for each invalid data- assert mocked_schema_logger.call_count == 6+ # warning for malformed id+ assert mocked_schema_logger.call_count == 3+ # warning for skipping shipping method+ assert mocked_annotations_logger.call_count == 3++[email protected](annotations_logger, "warning")[email protected](schema_logger, "warning")+def test_parse_excluded_shipping_methods_response_invalid(+ mocked_schema_logger, mocked_annotations_logger, app+):+ # given+ response = {+ "excluded_methods": [+ {+ "id": "not-an-id",+ },+ ]+ }+ webhook = Webhook.objects.create(+ name="shipping-webhook-1",+ app=app,+ target_url="https://shipping-gateway.com/apiv2/",+ )++ # when+ excluded_methods = get_excluded_shipping_methods_from_response(response, webhook)++ # then+ assert not excluded_methods+ assert mocked_schema_logger.call_count == 1+ assert (+ "Malformed ShippingMethod id was provided:"+ in mocked_schema_logger.call_args[0][0]+ )+ assert mocked_annotations_logger.call_count == 1+ error_msg = mocked_annotations_logger.call_args[0][1]+ assert "Skipping invalid shipping method (FilterShippingMethodsSchema)" in error_msg@mock.patch(@@ -1252,7 +1293,7 @@ def test_get_excluded_shipping_methods_or_fetch_invalid_response_type(mocked_parse.assert_called_once_with([])[email protected](schema_logger, "warning")[email protected](annotations_logger, "warning")def test_parse_list_shipping_methods_response_response_incorrect_format(mocked_logger, app):@@ -1266,6 +1307,8 @@ def test_parse_list_shipping_methods_response_response_incorrect_format(assert result == []# Ensure the warning about invalit method data wa loggedassert mocked_logger.call_count == len(response_data_with_incorrect_format)+ error_msg = mocked_logger.call_args[0][1]+ assert error_msg == "Skipping invalid shipping method (ListShippingMethodsSchema)"def test_parse_list_shipping_methods_with_metadata(app):diff --git a/saleor/webhook/response_schemas/annotations.py b/saleor/webhook/response_schemas/annotations.pyindex 62d9d308b6..31de3daa70 100644--- a/saleor/webhook/response_schemas/annotations.py+++ b/saleor/webhook/response_schemas/annotations.py@@ -6,6 +6,7 @@ from pydantic import (AfterValidator,BeforeValidator,ValidationError,+ ValidationInfo,ValidatorFunctionWrapHandler,WrapValidator,)@@ -16,6 +17,8 @@ from ...core.utils.metadata_manager import metadata_is_validM = TypeVar("M")logger = logging.getLogger(__name__)+logger = logging.getLogger(__name__)+def skip_invalid_metadata(value: M) -> M:if not metadata_is_valid(value):@@ -35,6 +38,53 @@ def default_if_none(value: Any) -> Any:T = TypeVar("T")DefaultIfNone = Annotated[T, BeforeValidator(default_if_none)]++def skip_invalid(+ value: Any, handler: ValidatorFunctionWrapHandler, info: ValidationInfo+) -> Any:+ try:+ return handler(value)+ except ValidationError as err:+ context = info.context or {}+ custom_message = context.get("custom_message", "Skipping invalid value")+ app = context.get("app")+ logger.warning(+ "%s Value: %s Error: %s",+ custom_message,+ value,+ str(err),+ extra={+ "app": app.id if app else None,+ },+ )+ raise PydanticOmit() from err+++OnErrorSkip = Annotated[T, WrapValidator(skip_invalid)]+++def default_if_invalid(+ value: Any, handler: ValidatorFunctionWrapHandler, info: ValidationInfo+) -> Any:+ try:+ return handler(value)+ except ValidationError as err:+ context = info.context or {}+ app = context.get("app")+ logger.warning(+ "Skipping invalid value: %s error: %s",+ value,+ str(err),+ extra={+ "app": app.id if app else None,+ "field_name": info.field_name,+ },+ )+ raise PydanticUseDefault() from err+++OnErrorDefault = Annotated[T, WrapValidator(default_if_invalid)]+DatetimeUTC = Annotated[datetime, AfterValidator(lambda v: v.replace(tzinfo=UTC))]diff --git a/saleor/webhook/response_schemas/payment.py b/saleor/webhook/response_schemas/payment.pynew file mode 100644index 0000000000..5102c2b850--- /dev/null+++ b/saleor/webhook/response_schemas/payment.py@@ -0,0 +1,101 @@+from enum import Enum+from typing import Annotated, Any, Literal++from pydantic import AfterValidator, BaseModel, Field, JsonValue, field_validator++from ...graphql.core.utils import str_to_enum+from ...payment import TokenizedPaymentFlow+from .annotations import DefaultIfNone, OnErrorDefault, OnErrorSkip+from .validators import lower_values++TokenizedPaymentFlowEnum = Enum( # type: ignore[misc]+ "TokenizedPaymentFlowEnum",+ [(str_to_enum(value), value) for value, _ in TokenizedPaymentFlow.CHOICES],+)+++class CreditCardInfoSchema(BaseModel):+ brand: Annotated[str, Field(description="Brand of the credit card.")]+ last_digits: Annotated[+ str,+ Field(+ validation_alias="lastDigits", description="Last digits of the credit card."+ ),+ ]+ exp_year: Annotated[+ int,+ Field(+ validation_alias="expYear",+ description="Expiration year of the credit card.",+ ),+ ]+ exp_month: Annotated[+ int,+ Field(+ validation_alias="expMonth",+ description="Expiration month of the credit card.",+ ),+ ]+ first_digits: Annotated[+ DefaultIfNone[str],+ Field(+ validation_alias="firstDigits",+ description="First digits of the credit card.",+ default=None,+ ),+ ]++ @field_validator("last_digits", "first_digits", mode="before")+ @classmethod+ def clean_digits(cls, value: Any) -> str | None:+ return str(value) if value is not None else None+++class StoredPaymentMethodSchema(BaseModel):+ id: Annotated[str, Field(description="ID of stored payment method.")]+ supported_payment_flows: Annotated[ # type: ignore[name-defined]+ DefaultIfNone[list[Literal[TokenizedPaymentFlowEnum.INTERACTIVE.name,]]],+ Field(+ validation_alias="supportedPaymentFlows",+ description="Supported flows that can be performed with this payment method.",+ default_factory=list,+ ),+ AfterValidator(lower_values),+ ]+ type: Annotated[+ str,+ Field(description="Type of stored payment method. For example: Credit Card."),+ ]+ name: Annotated[+ DefaultIfNone[str],+ Field(+ description="Name of the payment method. For example: last 4 digits of credit card, obfuscated email.",+ default=None,+ ),+ ]+ data: Annotated[+ DefaultIfNone[JsonValue],+ Field(+ description="JSON data that will be returned to client.",+ default=None,+ ),+ ]+ credit_card_info: Annotated[+ OnErrorDefault[CreditCardInfoSchema],+ Field(+ validation_alias="creditCardInfo",+ description="Credit card information.",+ default=None,+ ),+ ]+++class ListStoredPaymentMethodsSchema(BaseModel):+ payment_methods: Annotated[+ DefaultIfNone[list[OnErrorSkip[StoredPaymentMethodSchema]]],+ Field(+ validation_alias="paymentMethods",+ default_factory=list,+ description="List of stored payment methods.",+ ),+ ]diff --git a/saleor/webhook/response_schemas/shipping.py b/saleor/webhook/response_schemas/shipping.pyindex 9a3c69f789..1091de8c03 100644--- a/saleor/webhook/response_schemas/shipping.py+++ b/saleor/webhook/response_schemas/shipping.py@@ -1,6 +1,6 @@import loggingfrom decimal import Decimal-from typing import Annotated, Any, TypeVar+from typing import Annotated, TypeVarfrom graphql.error import GraphQLErrorfrom prices import Money@@ -8,20 +8,16 @@ from pydantic import (BaseModel,Field,RootModel,- ValidationError,ValidationInfo,- ValidatorFunctionWrapHandler,- WrapValidator,field_validator,)-from pydantic_core import PydanticOmitfrom ...app.models import Appfrom ...graphql.core.utils import from_global_id_or_errorfrom ...shipping.models import ShippingMethodfrom ..const import APP_ID_PREFIXfrom ..transport.shipping_helpers import to_shipping_app_id-from .annotations import DefaultIfNone, Metadata+from .annotations import DefaultIfNone, Metadata, OnErrorSkiplogger = logging.getLogger(__name__)@@ -30,19 +26,6 @@ name_max_length = ShippingMethod._meta.get_field("name").max_lengthT = TypeVar("T")-def skip_invalid_shipping_method(- value: Any, handler: ValidatorFunctionWrapHandler-) -> Any:- try:- return handler(value)- except ValidationError as err:- logger.warning("Skipping invalid shipping method: %s", err)- raise PydanticOmit() from err---OnErrorSkipShippingMethod = Annotated[T, WrapValidator(skip_invalid_shipping_method)]--class ShippingMethodSchema(BaseModel):id: Annotated[str, Field(coerce_numbers_to_str=True)]name: Annotated[str, Field(max_length=name_max_length)]@@ -67,7 +50,7 @@ class ShippingMethodSchema(BaseModel):class ListShippingMethodsSchema(RootModel):- root: DefaultIfNone[list[OnErrorSkipShippingMethod[ShippingMethodSchema]]] = []+ root: DefaultIfNone[list[OnErrorSkip[ShippingMethodSchema]]] = []class ExcludedShippingMethodSchema(BaseModel):@@ -93,5 +76,5 @@ class ExcludedShippingMethodSchema(BaseModel):class FilterShippingMethodsSchema(BaseModel):excluded_methods: DefaultIfNone[- list[OnErrorSkipShippingMethod[ExcludedShippingMethodSchema]]+ list[OnErrorSkip[ExcludedShippingMethodSchema]]] = []diff --git a/saleor/webhook/response_schemas/validators.py b/saleor/webhook/response_schemas/validators.pynew file mode 100644index 0000000000..9d32a89fdb--- /dev/null+++ b/saleor/webhook/response_schemas/validators.py@@ -0,0 +1,11 @@+def lower_values(+ values: str | list[str] | None,+) -> str | list[str] | None:+ """Lowercase all values in a string or a list."""+ match values:+ case str():+ return values.lower()+ case list():+ return [value.lower() for value in values]+ case _:+ return valuesdiff --git a/saleor/webhook/tests/response_schemas/test_payment.py b/saleor/webhook/tests/response_schemas/test_payment.pynew file mode 100644index 0000000000..c9d645a1d9--- /dev/null+++ b/saleor/webhook/tests/response_schemas/test_payment.py@@ -0,0 +1,472 @@+from unittest.mock import patch++import pytest+from pydantic import ValidationError++from ...response_schemas.annotations import logger as annotations_logger+from ...response_schemas.payment import (+ CreditCardInfoSchema,+ ListStoredPaymentMethodsSchema,+ StoredPaymentMethodSchema,+)+++ "data",+ [+ # All fields+ {+ "brand": "visa",+ "lastDigits": "1234",+ "expYear": 2023,+ "expMonth": 12,+ "firstDigits": "123456",+ },+ # Only required fields+ {+ "brand": "mastercard",+ "lastDigits": "5678",+ "expYear": 2025,+ "expMonth": 6,+ },+ # All int fields as strings+ {+ "brand": "visa",+ "lastDigits": "1234",+ "expYear": "2023",+ "expMonth": "12",+ "firstDigits": "123456",+ },+ # All digit fields as int+ {+ "brand": "visa",+ "lastDigits": 1234,+ "expYear": 2023,+ "expMonth": 12,+ "firstDigits": 123456,+ },+ ],+)+def test_credit_card_info_schema_valid(data):+ # when+ schema = CreditCardInfoSchema.model_validate(data)++ # then+ assert schema.brand == data["brand"]+ assert schema.last_digits == str(data["lastDigits"])+ assert schema.exp_year == int(data["expYear"])+ assert schema.exp_month == int(data["expMonth"])+ first_digits = data.get("firstDigits")+ assert schema.first_digits == (str(first_digits) if first_digits else None)+++class NonParsableObject:+ def __str__(self):+ raise ValueError("Cannot convert to string")+++ ("data", "invalid_field"),+ [+ # Missing `brand` field+ (+ {+ "lastDigits": "1234",+ "expYear": 2023,+ "expMonth": 12,+ "firstDigits": "123456",+ },+ "brand",+ ),+ # Missing `lastDigits` field+ (+ {+ "brand": "visa",+ "expYear": 2023,+ "expMonth": 12,+ "firstDigits": "123456",+ },+ "lastDigits",+ ),+ # Missing `expYear` field+ (+ {+ "brand": "visa",+ "expMonth": 12,+ "lastDigits": "1234",+ },+ "expYear",+ ),+ # Missing `expMonth` field+ (+ {+ "brand": "visa",+ "expYear": 2023,+ "lastDigits": "1234",+ },+ "expMonth",+ ),+ # Not parsable `expYear`+ (+ {+ "brand": "visa",+ "lastDigits": "1234",+ "expYear": "ABC",+ "expMonth": 12,+ "firstDigits": "123456",+ },+ "expYear",+ ),+ # Not parsable `expMonth`+ (+ {+ "brand": "visa",+ "lastDigits": "1234",+ "expYear": 2023,+ "expMonth": "ABC",+ "firstDigits": "123456",+ },+ "expMonth",+ ),+ # Empty string as `expYear`+ (+ {+ "brand": "visa",+ "lastDigits": "1234",+ "expYear": "",+ "expMonth": 12,+ "firstDigits": "123456",+ },+ "expYear",+ ),+ # Empty string as `expMonth`+ (+ {+ "brand": "visa",+ "lastDigits": "1234",+ "expYear": 2023,+ "expMonth": "",+ "firstDigits": "123456",+ },+ "expMonth",+ ),+ # None as `lastDigits`+ (+ {+ "brand": "visa",+ "lastDigits": None,+ "expYear": 2023,+ "expMonth": 12,+ "firstDigits": "123456",+ },+ "lastDigits",+ ),+ # Not parsable as `lastDigits`+ (+ {+ "brand": "visa",+ "lastDigits": NonParsableObject(),+ "expYear": 2023,+ "expMonth": 12,+ "firstDigits": "123456",+ },+ "lastDigits",+ ),+ # Not parsable as `firstDigits`+ (+ {+ "brand": "visa",+ "lastDigits": "1234",+ "expYear": 2023,+ "expMonth": 12,+ "firstDigits": NonParsableObject(),+ },+ "firstDigits",+ ),+ ],+)+def test_credit_card_info_schema_invalid(data, invalid_field):+ # when+ with pytest.raises(ValidationError) as exc_info:+ CreditCardInfoSchema.model_validate(data)++ # then+ assert len(exc_info.value.errors()) == 1+ assert exc_info.value.errors()[0]["loc"][0] == invalid_field+++ "field",+ [+ "brand",+ "lastDigits",+ "expYear",+ "expMonth",+ ],+)+def test_credit_card_info_schema_required_field_is_none(field):+ # given+ data = {+ "brand": "visa",+ "lastDigits": "1234",+ "expYear": 2023,+ "expMonth": 12,+ "firstDigits": "123456",+ }+ data[field] = None++ # when+ with pytest.raises(ValidationError) as exc_info:+ CreditCardInfoSchema.model_validate(data)++ # then+ assert len(exc_info.value.errors()) == 1+ assert exc_info.value.errors()[0]["loc"][0] == field+++ "data",+ [+ # All fields+ {+ "id": "method-1",+ "supportedPaymentFlows": ["INTERACTIVE"],+ "type": "Credit Card",+ "name": "Visa ***1234",+ "data": {"key": "value"},+ "creditCardInfo": {+ "brand": "visa",+ "lastDigits": "1234",+ "expYear": 2023,+ "expMonth": 12,+ "firstDigits": "123456",+ },+ },+ # Only required fields+ {+ "id": "method-2",+ "type": "Credit Card",+ },+ # Empty not required fields+ {+ "id": "method-3",+ "supportedPaymentFlows": None,+ "type": "Credit Card",+ "name": None,+ "data": None,+ "creditCardInfo": None,+ },+ # Empty list as supportedPaymentFlows+ {+ "id": "method-4",+ "supportedPaymentFlows": [],+ "type": "Credit Card",+ },+ ],+)+def test_stored_payment_method_schema_valid(data):+ # when+ schema = StoredPaymentMethodSchema.model_validate(data)++ # then+ assert schema.id == data["id"]+ assert schema.supported_payment_flows == [+ flow.lower() for flow in data.get("supportedPaymentFlows") or []+ ]+ assert schema.type == data["type"]+ assert schema.name == data.get("name")+ assert schema.data == data.get("data")+ if "creditCardInfo" in data and data["creditCardInfo"]:+ assert schema.credit_card_info.brand == data["creditCardInfo"]["brand"]+ assert (+ schema.credit_card_info.last_digits == data["creditCardInfo"]["lastDigits"]+ )+ assert schema.credit_card_info.exp_year == data["creditCardInfo"]["expYear"]+ assert schema.credit_card_info.exp_month == data["creditCardInfo"]["expMonth"]+ assert (+ schema.credit_card_info.first_digits+ == data["creditCardInfo"]["firstDigits"]+ )+ else:+ assert schema.credit_card_info is None+++ ("data", "invalid_field"),+ [+ # Missing `id` field+ (+ {+ "supportedPaymentFlows": ["INTERACTIVE"],+ "type": "Credit Card",+ },+ "id",+ ),+ # Invalid `supportedPaymentFlows`+ (+ {+ "id": "method-1",+ "supportedPaymentFlows": ["INVALID_FLOW"],+ "type": "Credit Card",+ },+ "supportedPaymentFlows",+ ),+ # Missing `type` field+ (+ {+ "id": "method-1",+ "supportedPaymentFlows": ["INTERACTIVE"],+ },+ "type",+ ),+ # Not parable `data` field+ (+ {+ "id": "method-1",+ "supportedPaymentFlows": ["INTERACTIVE"],+ "type": "Credit Card",+ "data": object(),+ },+ "data",+ ),+ ],+)+def test_stored_payment_method_schema_invalid(data, invalid_field):+ # when+ with pytest.raises(ValidationError) as exc_info:+ StoredPaymentMethodSchema.model_validate(data)++ # then+ assert len(exc_info.value.errors()) == 1+ assert exc_info.value.errors()[0]["loc"][0] == invalid_field++[email protected](annotations_logger, "warning")+def test_stored_payment_method_schema_invalid_credit_card_info_skipped(+ mocked_logger, app+):+ # given+ id = "method-1"+ type = "Credit Card"++ # when+ schema = StoredPaymentMethodSchema.model_validate(+ {+ "id": id,+ "type": type,+ "creditCardInfo": {+ "brand": "visa",+ "lastDigits": NonParsableObject(),+ "expYear": 2023,+ "expMonth": 12,+ "firstDigits": "123456",+ },+ },+ context={+ "app": app,+ },+ )++ # then+ assert schema.credit_card_info is None+ assert schema.id == id+ assert schema.type == type+ assert mocked_logger.call_count == 1+ error_msg = mocked_logger.call_args[0][0]+ assert "Skipping invalid value" in error_msg+ assert mocked_logger.call_args[1]["extra"]["app"] == app.id+ assert mocked_logger.call_args[1]["extra"]["field_name"] == "credit_card_info"+++ "data",+ [+ # All fields+ {+ "paymentMethods": [+ {+ "id": "method-1",+ "supportedPaymentFlows": ["INTERACTIVE"],+ "type": "Credit Card",+ "name": "Visa ***1234",+ "data": {"key": "value"},+ "creditCardInfo": {+ "brand": "visa",+ "lastDigits": "1234",+ "expYear": 2023,+ "expMonth": 12,+ "firstDigits": "123456",+ },+ },+ {+ "id": "method-2",+ "supportedPaymentFlows": ["INTERACTIVE"],+ "type": "Debit Card",+ },+ ]+ },+ # Empty list ad paymentMethods+ {"paymentMethods": []},+ # None as paymentMethods+ {"paymentMethods": None},+ # Only required fields+ {+ "paymentMethods": [+ {+ "id": "method-3",+ "type": "Credit Card",+ }+ ]+ },+ ],+)+def test_list_stored_payment_methods_schema_valid(data):+ # when+ schema = ListStoredPaymentMethodsSchema.model_validate(data)++ # then+ assert len(schema.payment_methods) == (+ len(data["paymentMethods"]) if data["paymentMethods"] else 0+ )+++ "data",+ [{}, {"test": "invalid"}],+)+def test_list_stored_payment_methods_schema_invalid(data):+ # when+ schema = ListStoredPaymentMethodsSchema.model_validate(data)++ # then+ assert schema.payment_methods == []++[email protected](annotations_logger, "warning")+def test_list_stored_payment_methods_schema_invalid_element_skipped(mocked_logger):+ """Test when the input has one valid and one invalid stored payment method."""+ # given a list with one valid and one invalid payment method+ data = {+ "paymentMethods": [+ {+ "id": "method-1",+ "supportedPaymentFlows": ["INTERACTIVE"],+ "type": "Credit Card",+ "name": "Visa ***1234",+ },+ # missing type+ {+ "id": "method-2",+ "name": "Visa ***4321",+ },+ ]+ }++ # when+ schema = ListStoredPaymentMethodsSchema.model_validate(data)++ # then only the valid payment method should be included+ assert len(schema.payment_methods) == 1+ assert schema.payment_methods[0].id == data["paymentMethods"][0]["id"]+ assert schema.payment_methods[0].name == data["paymentMethods"][0]["name"]+ assert mocked_logger.call_count == 1diff --git a/saleor/webhook/tests/response_schemas/test_shipping.py b/saleor/webhook/tests/response_schemas/test_shipping.pyindex dff3325c53..dbd919cb9b 100644--- a/saleor/webhook/tests/response_schemas/test_shipping.py+++ b/saleor/webhook/tests/response_schemas/test_shipping.py@@ -6,6 +6,7 @@ import grapheneimport pytestfrom pydantic import ValidationError+from ...response_schemas.annotations import logger as annotations_loggerfrom ...response_schemas.shipping import (ExcludedShippingMethodSchema,FilterShippingMethodsSchema,@@ -242,7 +243,7 @@ def test_list_shipping_methods_schema_skipped_values(data, app):assert list_methods.root == [][email protected](logger, "warning")[email protected](annotations_logger, "warning")def test_list_shipping_methods_schema_invalid_element_skipped(mocked_logger, app):"""Test when the provided input has 2 elements, one valid and one invalid."""# given a list with one valid and one invalid shipping method@@ -367,7 +368,12 @@ def test_filter_shipping_methods_schema_invalid_element_skipped(mocked_logger):}# when- schema = FilterShippingMethodsSchema.model_validate(data)+ schema = FilterShippingMethodsSchema.model_validate(+ data,+ context={+ "custom_message": "Custom error while validating stored payment methods"+ },+ )# then only the valid shipping method should be includedassert len(schema.excluded_methods) == 2diff --git a/saleor/webhook/tests/response_schemas/test_validators.py b/saleor/webhook/tests/response_schemas/test_validators.pynew file mode 100644index 0000000000..a99111cfab--- /dev/null+++ b/saleor/webhook/tests/response_schemas/test_validators.py@@ -0,0 +1,19 @@+import pytest++from saleor.webhook.response_schemas.validators import lower_values+++ ("input_value", "expected_output"),+ [+ ("HELLO", "hello"),+ ("world", "world"),+ (["HELLO", "WORLD"], ["hello", "world"]),+ (["Python", "TEST"], ["python", "test"]),+ ([], []),+ (None, None),+ (["MiXeD", "CaSe"], ["mixed", "case"]),+ ],+)+def test_lower_values(input_value, expected_output):+ assert lower_values(input_value) == expected_outputdiff --git a/saleor/webhook/tests/test_utils.py b/saleor/webhook/tests/test_utils.pyindex 6af3d65ac8..cc95f493a0 100644--- a/saleor/webhook/tests/test_utils.py+++ b/saleor/webhook/tests/test_utils.py@@ -1,9 +1,14 @@import copy+from unittest.mock import patchimport pytestfrom ...app.models import App-from ...payment.interface import PaymentGateway+from ...payment.interface import (+ PaymentGateway,+ PaymentMethodCreditCardInfo,+ PaymentMethodData,+)from ..event_types import WebhookEventAsyncType, WebhookEventSyncTypefrom ..models import Webhookfrom ..observability.exceptions import (@@ -12,10 +17,10 @@ from ..observability.exceptions import (TruncationError,)from ..observability.payload_schema import ObservabilityEventTypes+from ..response_schemas.annotations import logger as annotations_loggerfrom ..transport.list_stored_payment_methods import (- get_credit_card_info,get_list_stored_payment_methods_from_response,- get_payment_method_from_response,+ logger,)from ..transport.utils import (generate_cache_key_for_webhook,@@ -336,278 +341,107 @@ def test_different_app_produce_different_cache_key():assert cache_key_1 != cache_key_2-def test_get_credit_card_info(app):- # given- brand = "VISA"- last_digits = "1234"- exp_year = "2023"- exp_month = 1- first_digits = "4321"-- credit_card_info = {- "brand": brand,- "lastDigits": last_digits,- "expYear": exp_year,- "expMonth": exp_month,- "firstDigits": first_digits,- }-- # when- response = get_credit_card_info(app, credit_card_info)-- # then- assert response.brand == brand- assert response.last_digits == last_digits- assert response.exp_year == int(exp_year)- assert response.exp_month == exp_month- assert response.first_digits == first_digits---def test_get_credit_card_info_without_first_digits_field(app):- # given- brand = "VISA"- last_digits = "1234"- exp_year = 2023- exp_month = 1-- credit_card_info = {- "brand": brand,- "lastDigits": last_digits,- "expYear": exp_year,- "expMonth": exp_month,- }-- # when- response = get_credit_card_info(app, credit_card_info)-- # then- assert response.brand == brand- assert response.last_digits == last_digits- assert response.exp_year == exp_year- assert response.exp_month == exp_month- assert response.first_digits is None--- "field",- [- "brand",- "lastDigits",- "expYear",- "expMonth",- ],-)-def test_get_credit_card_info_missing_required_field(field, app):- # given- brand = "VISA"- last_digits = "1234"- exp_year = 2023- exp_month = 1- first_digits = "4321"-- credit_card_info = {- "brand": brand,- "lastDigits": last_digits,- "expYear": exp_year,- "expMonth": exp_month,- "firstDigits": first_digits,- }- del credit_card_info[field]-- # when- response = get_credit_card_info(app, credit_card_info)-- # then- assert response is None--- "field",- [- "brand",- "lastDigits",- "expYear",- "expMonth",- ],-)-def test_get_credit_card_info_required_field_is_none(field, app):- # given- brand = "VISA"- last_digits = "1234"- exp_year = 2023- exp_month = 1- first_digits = "4321"-- credit_card_info = {- "brand": brand,- "lastDigits": last_digits,- "expYear": exp_year,- "expMonth": exp_month,- "firstDigits": first_digits,- }- credit_card_info[field] = None-- # when- response = get_credit_card_info(app, credit_card_info)-- # then- assert response is None--[email protected]("exp_year", [None, "", "str"])-def test_get_credit_card_info_incorrect_exp_year(exp_year, app):[email protected](annotations_logger, "warning")+def test_get_list_stored_payment_methods_from_response(+ mocked_logger, payment_method_response, app+):# given- brand = "VISA"- last_digits = "1234"- exp_month = 1- first_digits = "4321"-- credit_card_info = {- "brand": brand,- "lastDigits": last_digits,- "expYear": exp_year,- "expMonth": exp_month,- "firstDigits": first_digits,- }-- # when- response = get_credit_card_info(app, credit_card_info)-- # then- assert response is None-+ # invalid second payment method due to to missing id+ second_payment_method = copy.deepcopy(payment_method_response)+ del second_payment_method["id"][email protected]("exp_month", [None, "", "str"])-def test_get_credit_card_info_incorrect_exp_month(exp_month, app):- # given- brand = "VISA"- last_digits = "1234"- exp_year = 2023- first_digits = "4321"-- credit_card_info = {- "brand": brand,- "lastDigits": last_digits,- "expYear": exp_year,- "expMonth": exp_month,- "firstDigits": first_digits,+ list_stored_payment_methods_response = {+ "paymentMethods": [payment_method_response, second_payment_method]}+ currency = "usd"# when- response = get_credit_card_info(app, credit_card_info)-- # then- assert response is None---def test_get_payment_method_from_response(payment_method_response, app):- # when- payment_method = get_payment_method_from_response(- app, payment_method_response, "usd"+ response = get_list_stored_payment_methods_from_response(+ app, list_stored_payment_methods_response, currency)# then- assert payment_method.id == to_payment_app_id(app, payment_method_response["id"])- assert payment_method.external_id == payment_method_response["id"]- assert payment_method.type == payment_method_response["type"]- assert payment_method.gateway == PaymentGateway(- id=app.identifier, name=app.name, currencies=["usd"], config=[]- )- assert payment_method.supported_payment_flows == [- flow.lower() for flow in payment_method_response["supportedPaymentFlows"]- ]- assert payment_method.credit_card_info == get_credit_card_info(- app, payment_method_response["creditCardInfo"]+ assert len(response) == 1+ assert response[0] == PaymentMethodData(+ id=to_payment_app_id(app, payment_method_response["id"]),+ external_id=payment_method_response["id"],+ supported_payment_flows=[+ flow.lower()+ for flow in payment_method_response.get("supportedPaymentFlows", [])+ ],+ type=payment_method_response["type"],+ credit_card_info=PaymentMethodCreditCardInfo(+ brand=payment_method_response["creditCardInfo"]["brand"],+ last_digits=payment_method_response["creditCardInfo"]["lastDigits"],+ exp_year=payment_method_response["creditCardInfo"]["expYear"],+ exp_month=payment_method_response["creditCardInfo"]["expMonth"],+ first_digits=payment_method_response["creditCardInfo"].get("firstDigits"),+ )+ if payment_method_response.get("creditCardInfo")+ else None,+ name=payment_method_response["name"],+ data=payment_method_response["data"],+ gateway=PaymentGateway(+ id=app.identifier,+ name=app.name,+ currencies=[currency],+ config=[],+ ),)- assert payment_method.name == payment_method_response["name"]- assert payment_method.data == payment_method_response["data"]+ assert mocked_logger.call_count == 1+ error_msg = mocked_logger.call_args[0][1]+ assert error_msg == "Skipping invalid stored payment method"+ assert mocked_logger.call_args[1]["extra"]["app"] == app.id[email protected]("field", ["id", "type", "supportedPaymentFlows"])-def test_get_payment_method_from_response_missing_required_field(- field, payment_method_response, app-):+def test_get_list_stored_payment_methods_from_response_only_required_fields(app):# given- del payment_method_response[field]-- # when- payment_method = get_payment_method_from_response(- app, payment_method_response, "usd"- )-- # then- assert payment_method is None-+ payment_method_response = {+ "id": "method-1",+ "type": "Credit Card",+ }[email protected]("field", ["creditCardInfo", "name", "data"])-def test_get_payment_method_from_response_optional_field(- field, payment_method_response, app-):- del payment_method_response[field]+ list_stored_payment_methods_response = {"paymentMethods": [payment_method_response]}+ currency = "usd"# when- payment_method = get_payment_method_from_response(- app, payment_method_response, "usd"+ response = get_list_stored_payment_methods_from_response(+ app, list_stored_payment_methods_response, currency)# then- assert payment_method.id == to_payment_app_id(app, payment_method_response["id"])- assert payment_method.external_id == payment_method_response["id"]- assert payment_method.type == payment_method_response["type"]- assert payment_method.gateway == PaymentGateway(- id=app.identifier, name=app.name, currencies=["usd"], config=[]- )- assert payment_method.supported_payment_flows == [- flow.lower() for flow in payment_method_response["supportedPaymentFlows"]- ]--[email protected]("field", ["id", "type", "supportedPaymentFlows"])-def test_get_payment_method_from_response_required_field_is_none(- field, payment_method_response, app-):- # given- payment_method_response[field] = None-- # when- payment_method = get_payment_method_from_response(- app, payment_method_response, "usd"+ assert len(response) == 1+ assert response[0] == PaymentMethodData(+ id=to_payment_app_id(app, payment_method_response["id"]),+ external_id=payment_method_response["id"],+ supported_payment_flows=[],+ type=payment_method_response["type"],+ credit_card_info=None,+ gateway=PaymentGateway(+ id=app.identifier,+ name=app.name,+ currencies=[currency],+ config=[],+ ),)- # then- assert payment_method is None--def test_get_payment_method_from_response_incorrect_payment_flow_choices(- payment_method_response, app[email protected](logger, "warning")+def test_get_list_stored_payment_methods_from_response_invalid_input_data(+ mocked_logger, app):# given- payment_method_response["supportedPaymentFlows"] = ["incorrect", "INTERACTIVE"]-- # when- payment_method = get_payment_method_from_response(- app, payment_method_response, "usd"- )-- # then- assert payment_method is None---def test_get_list_stored_payment_methods_from_response(payment_method_response, app):- # given- second_payment_method = copy.deepcopy(payment_method_response)- del second_payment_method["id"]- list_stored_payment_methods_response = {- "paymentMethods": [payment_method_response, second_payment_method]- }+ list_stored_payment_methods_response = None+ currency = "usd"# whenresponse = get_list_stored_payment_methods_from_response(- app, list_stored_payment_methods_response, "usd"+ app, list_stored_payment_methods_response, currency)# then- assert len(response) == 1- assert response == [- get_payment_method_from_response(app, payment_method_response, "usd")- ]+ assert response == []+ assert mocked_logger.call_count == 1+ error_msg = mocked_logger.call_args[0][0]+ assert "Skipping stored payment methods from app" in error_msg+ assert mocked_logger.call_args[1]["extra"]["app"] == app.iddiff --git a/saleor/webhook/transport/list_stored_payment_methods.py b/saleor/webhook/transport/list_stored_payment_methods.pyindex 67fb9401c1..73e3eb7e71 100644--- a/saleor/webhook/transport/list_stored_payment_methods.py+++ b/saleor/webhook/transport/list_stored_payment_methods.py@@ -2,9 +2,9 @@ import loggingimport graphenefrom django.core.cache import cache+from pydantic import ValidationErrorfrom ...app.models import App-from ...payment import TokenizedPaymentFlowfrom ...payment.interface import (PaymentGateway,PaymentGatewayInitializeTokenizationResponseData,@@ -18,135 +18,52 @@ from ...payment.interface import ()from ...webhook.event_types import WebhookEventSyncTypefrom ...webhook.utils import get_webhooks_for_event+from ..response_schemas.payment import ListStoredPaymentMethodsSchemafrom .utils import generate_cache_key_for_webhook, to_payment_app_idlogger = logging.getLogger(__name__)-def get_credit_card_info(- app: App, credit_card_info: dict-) -> PaymentMethodCreditCardInfo | None:- required_fields = [- "brand",- "lastDigits",- "expYear",- "expMonth",- ]- brand = credit_card_info.get("brand")- last_digits = credit_card_info.get("lastDigits")- exp_year = credit_card_info.get("expYear")- exp_month = credit_card_info.get("expMonth")- first_digits = credit_card_info.get("firstDigits")- if not all(field in credit_card_info for field in required_fields):- logger.warning(- "Skipping stored payment method. Missing required fields for credit card "- "info. Required fields: %s, received fields: %s from app %s.",- required_fields,- credit_card_info.keys(),- app.id,- )- return None- if not all([brand, last_digits, exp_year, exp_month]):- logger.warning("Skipping stored credit card info without required fields")- return None- if not isinstance(exp_year, int):- if isinstance(exp_year, str) and exp_year.isdigit():- exp_year = int(exp_year)- else:- logger.warning(- "Skipping stored payment method with invalid expYear, "- "received from app %s",- app.id,- )- return None-- if not isinstance(exp_month, int):- if isinstance(exp_month, str) and exp_month.isdigit():- exp_month = int(exp_month)- else:- logger.warning(- "Skipping stored payment method with invalid expMonth, "- "received from app %s",- app.id,- )- return None-- return PaymentMethodCreditCardInfo(- brand=str(brand),- last_digits=str(last_digits),- exp_year=exp_year,- exp_month=exp_month,- first_digits=str(first_digits) if first_digits else None,- )---def get_payment_method_from_response(- app: "App", payment_method: dict, currency: str-) -> PaymentMethodData | None:- payment_method_external_id = payment_method.get("id")- if not payment_method_external_id:- logger.warning(- "Skipping stored payment method without id, received from app %s", app.id+def get_list_stored_payment_methods_from_response(+ app: "App", response_data: dict, currency: str+) -> list["PaymentMethodData"]:+ try:+ stored_payment_methods_model = ListStoredPaymentMethodsSchema.model_validate(+ response_data,+ context={+ "custom_message": "Skipping invalid stored payment method",+ "app": app,+ },)- return None- payment_method_type = payment_method.get("type")- if not payment_method_type:+ except ValidationError as e:logger.warning(- "Skipping stored payment method without type, received from app %s",+ "Skipping stored payment methods from app %s. Error: %s",app.id,+ str(e),+ extra={"app": app.id},)- return None+ return []- supported_payment_flows = payment_method.get("supportedPaymentFlows")- if not supported_payment_flows or not isinstance(supported_payment_flows, list):- logger.warning(- "Skipping stored payment method with incorrect `supportedPaymentFlows`, "- "received from app %s",- app.id,- )- return None- payment_flow_choices = {- flow[0].upper(): flow[0] for flow in TokenizedPaymentFlow.CHOICES- }- if set(supported_payment_flows).difference(payment_flow_choices.keys()):- logger.warning(- "Skipping stored payment method with unsupported payment flows, "- "received from app %s",- app.id,- )- return Noneapp_identifier = app.identifier- credit_card_info = payment_method.get("creditCardInfo")- name = payment_method.get("name")- return PaymentMethodData(- id=to_payment_app_id(app, payment_method_external_id),- external_id=payment_method_external_id,- supported_payment_flows=[- payment_flow_choices[flow] for flow in supported_payment_flows- ],- type=payment_method_type,- credit_card_info=get_credit_card_info(app, credit_card_info)- if credit_card_info- else None,- name=name if name else None,- data=payment_method.get("data"),- gateway=PaymentGateway(- id=app_identifier, name=app.name, currencies=[currency], config=[]- ),- )---def get_list_stored_payment_methods_from_response(- app: "App", response_data: dict, currency: str-) -> list["PaymentMethodData"]:- payment_methods_response = response_data.get("paymentMethods", [])- payment_methods = []- for payment_method in payment_methods_response:- if parsed_payment_method := get_payment_method_from_response(- app, payment_method, currency- ):- payment_methods.append(parsed_payment_method)- return payment_methods+ return [+ PaymentMethodData(+ id=to_payment_app_id(app, payment_method.id),+ external_id=payment_method.id,+ supported_payment_flows=payment_method.supported_payment_flows,+ type=payment_method.type,+ credit_card_info=PaymentMethodCreditCardInfo(+ **dict(payment_method.credit_card_info),+ )+ if payment_method.credit_card_info+ else None,+ name=payment_method.name,+ data=payment_method.data,+ gateway=PaymentGateway(+ id=app_identifier, name=app.name, currencies=[currency], config=[]+ ),+ )+ for payment_method in stored_payment_methods_model.payment_methods+ ]def get_response_for_stored_payment_method_request_delete(diff --git a/saleor/webhook/transport/shipping.py b/saleor/webhook/transport/shipping.pyindex c82fe5df68..4af722b8c9 100644--- a/saleor/webhook/transport/shipping.py+++ b/saleor/webhook/transport/shipping.py@@ -32,7 +32,11 @@ def parse_list_shipping_methods_response() -> list["ShippingMethodData"]:try:list_shipping_method_model = ListShippingMethodsSchema.model_validate(- response_data, context={"app": app}+ response_data,+ context={+ "app": app,+ "custom_message": "Skipping invalid shipping method (ListShippingMethodsSchema)",+ },)except ValidationError:logger.warning("Skipping invalid shipping method response: %s", response_data)@@ -162,7 +166,10 @@ def get_excluded_shipping_methods_from_response(excluded_methods = []try:filter_methods_schema = FilterShippingMethodsSchema.model_validate(- response_data+ response_data,+ context={+ "custom_message": "Skipping invalid shipping method (FilterShippingMethodsSchema)"+ },)excluded_methods.extend(filter_methods_schema.excluded_methods)except ValidationError: