Skip to content

Saleor Core: the high performance, composable, headless commerce API.

Add static typing for transaction events (#17655)

Iga Karbowiak4fbc4ca80e87
diff --git a/saleor/graphql/payment/mutations/transaction/payment_gateway_initialize.py b/saleor/graphql/payment/mutations/transaction/payment_gateway_initialize.py
index 01f79be7a1..640e7c6a07 100644
--- a/saleor/graphql/payment/mutations/transaction/payment_gateway_initialize.py
+++ b/saleor/graphql/payment/mutations/transaction/payment_gateway_initialize.py
@@ -90,7 +90,7 @@ class PaymentGatewayInitialize(TransactionSessionBase):
app_identifier = identifier
payment_gateway_response = payment_gateways_response_dict.get(identifier)
if payment_gateway_response:
- response_data = payment_gateway_response.data
+ data_to_return = payment_gateway_response.data
errors = []
if payment_gateway_response.error:
code = common_types.PaymentGatewayConfigErrorCode.INVALID.value
@@ -103,7 +103,7 @@ class PaymentGatewayInitialize(TransactionSessionBase):
]
else:
- response_data = None
+ data_to_return = None
code = common_types.PaymentGatewayConfigErrorCode.NOT_FOUND.value
msg = (
"Active app with `HANDLE_PAYMENT` permissions or "
@@ -116,7 +116,6 @@ class PaymentGatewayInitialize(TransactionSessionBase):
"code": code,
}
]
- data_to_return = response_data.get("data") if response_data else None
response.append(
PaymentGatewayConfig(
id=app_identifier, data=data_to_return, errors=errors
diff --git a/saleor/graphql/payment/tests/mutations/test_payment_gateway_initialize.py b/saleor/graphql/payment/tests/mutations/test_payment_gateway_initialize.py
index 699befe642..1b24851220 100644
--- a/saleor/graphql/payment/tests/mutations/test_payment_gateway_initialize.py
+++ b/saleor/graphql/payment/tests/mutations/test_payment_gateway_initialize.py
@@ -57,12 +57,9 @@ def test_for_checkout_without_payment_gateways(
checkout = checkout_info.checkout
expected_app_identifier = "app.id"
expected_data = {"json": "data"}
- expected_response = {"data": expected_data}
mocked_initialize.return_value = [
- PaymentGatewayData(
- app_identifier=expected_app_identifier, data=expected_response
- )
+ PaymentGatewayData(app_identifier=expected_app_identifier, data=expected_data)
]
variables = {"id": to_global_id_or_none(checkout), "paymentGateways": None}
@@ -128,12 +125,9 @@ def test_for_order_without_payment_gateways(
order = order_with_lines
expected_app_identifier = "app.id"
expected_data = {"json": "data"}
- expected_response = {"data": expected_data}
mocked_initialize.return_value = [
- PaymentGatewayData(
- app_identifier=expected_app_identifier, data=expected_response
- )
+ PaymentGatewayData(app_identifier=expected_app_identifier, data=expected_data)
]
variables = {"id": to_global_id_or_none(order), "paymentGateways": None}
@@ -170,12 +164,9 @@ def test_for_checkout_with_payment_gateways(
expected_app_identifier = "app.id"
expected_data = {"json": "data"}
expected_input_data = {"input": "json"}
- expected_response = {"data": expected_data}
mocked_initialize.return_value = [
- PaymentGatewayData(
- app_identifier=expected_app_identifier, data=expected_response
- )
+ PaymentGatewayData(app_identifier=expected_app_identifier, data=expected_data)
]
variables = {
@@ -222,12 +213,9 @@ def test_for_order_with_payment_gateways(
expected_app_identifier = "app.id"
expected_data = {"json": "data"}
expected_input_data = {"input": "json"}
- expected_response = {"data": expected_data}
mocked_initialize.return_value = [
- PaymentGatewayData(
- app_identifier=expected_app_identifier, data=expected_response
- )
+ PaymentGatewayData(app_identifier=expected_app_identifier, data=expected_data)
]
variables = {
@@ -273,14 +261,11 @@ def test_for_checkout_with_payment_gateways_and_amount(
checkout = checkout_with_prices
expected_app_identifier = "app.id"
expected_data = {"json": "data"}
- expected_response = {"data": expected_data}
expected_input_data = {"input": "json"}
excpected_amount = Decimal(30)
mocked_initialize.return_value = [
- PaymentGatewayData(
- app_identifier=expected_app_identifier, data=expected_response
- )
+ PaymentGatewayData(app_identifier=expected_app_identifier, data=expected_data)
]
variables = {
@@ -327,13 +312,10 @@ def test_for_order_with_payment_gateways_and_amount(
order = order_with_lines
expected_app_identifier = "app.id"
expected_data = {"json": "data"}
- expected_response = {"data": expected_data}
expected_input_data = {"input": "json"}
excpected_amount = Decimal(30)
mocked_initialize.return_value = [
- PaymentGatewayData(
- app_identifier=expected_app_identifier, data=expected_response
- )
+ PaymentGatewayData(app_identifier=expected_app_identifier, data=expected_data)
]
variables = {
"id": to_global_id_or_none(order),
@@ -610,7 +592,6 @@ def test_for_checkout_with_multiple_payment_gateways(
excpected_amount = Decimal(30)
first_expected_app_identifier = "app.id"
first_expected_data = {"json": "data"}
- first_expected_response = {"data": first_expected_data}
first_expected_input_data = {"input": "json"}
second_expected_input_data = {"input": "json2"}
@@ -626,7 +607,7 @@ def test_for_checkout_with_multiple_payment_gateways(
mocked_initialize.return_value = [
PaymentGatewayData(
- app_identifier=first_expected_app_identifier, data=first_expected_response
+ app_identifier=first_expected_app_identifier, data=first_expected_data
),
PaymentGatewayData(
app_identifier=second_expected_app_identifier, error=second_error_msg
@@ -717,7 +698,6 @@ def test_for_order_with_multiple_payment_gateways(
excpected_amount = Decimal(30)
first_expected_app_identifier = "app.id"
first_expected_data = {"json": "data"}
- first_expected_response = {"data": first_expected_data}
first_expected_input_data = {"input": "json"}
second_expected_input_data = {"input": "json2"}
@@ -733,7 +713,7 @@ def test_for_order_with_multiple_payment_gateways(
mocked_initialize.return_value = [
PaymentGatewayData(
- app_identifier=first_expected_app_identifier, data=first_expected_response
+ app_identifier=first_expected_app_identifier, data=first_expected_data
),
PaymentGatewayData(
app_identifier=second_expected_app_identifier, error=second_error_msg
@@ -823,13 +803,10 @@ def test_with_payment_gateways_and_amount_with_lot_of_decimal_places(
order = order_with_lines
expected_app_identifier = "app.id"
expected_data = {"json": "data"}
- expected_response = {"data": expected_data}
expected_input_data = {"input": "json"}
excpected_amount = Decimal("28.1256977854")
mocked_initialize.return_value = [
- PaymentGatewayData(
- app_identifier=expected_app_identifier, data=expected_response
- )
+ PaymentGatewayData(app_identifier=expected_app_identifier, data=expected_data)
]
variables = {
"id": to_global_id_or_none(order),
diff --git a/saleor/payment/interface.py b/saleor/payment/interface.py
index 52a6f82ff4..2b2b9ef527 100644
--- a/saleor/payment/interface.py
+++ b/saleor/payment/interface.py
@@ -147,7 +147,7 @@ class TransactionData:
@dataclass
class PaymentGatewayData:
app_identifier: str
- data: dict[Any, Any] | None = None
+ data: JSONValue | None = None
error: str | None = None
diff --git a/saleor/payment/tests/test_utils.py b/saleor/payment/tests/test_utils.py
index a08551a930..153b8a5be8 100644
--- a/saleor/payment/tests/test_utils.py
+++ b/saleor/payment/tests/test_utils.py
@@ -28,6 +28,7 @@ from ..utils import (
get_channel_slug_from_payment,
get_correct_event_types_based_on_request_type,
get_transaction_event_amount,
+ logger,
parse_transaction_action_data,
recalculate_refundable_for_checkout,
try_void_or_refund_inactive_payment,
@@ -566,10 +567,6 @@ def test_create_transaction_event_from_request_and_webhook_response_with_no_psp_
TransactionEventType.CANCEL_REQUEST,
TransactionEventType.CANCEL_SUCCESS,
),
- (
- TransactionEventType.AUTHORIZATION_REQUEST,
- TransactionEventType.AUTHORIZATION_SUCCESS,
- ),
],
)
def test_create_transaction_event_from_request_and_webhook_response_with_no_psp_reference_invalid_event(
@@ -607,10 +604,13 @@ def test_create_transaction_event_from_request_and_webhook_response_with_no_psp_
assert transaction.events.count() == event_count + 1
assert event.psp_reference is None
assert event.transaction_id == transaction.id
- error_msg = f"Providing `pspReference` is required for {result_event_type.upper()}."
- assert event.message == error_msg
+ error_msg = (
+ f"Providing `pspReference` is required for {result_event_type.upper()} "
+ "action result."
+ )
+ assert error_msg in event.message
assert caplog.records[0].levelno == logging.WARNING
- assert caplog.records[0].message == error_msg
+ assert error_msg in caplog.records[0].message
@freeze_time("2018-05-31 12:00:01")
@@ -892,6 +892,7 @@ def test_create_transaction_event_from_request_triggers_webhooks_when_authorized
app,
order_with_lines,
django_capture_on_commit_callbacks,
+ plugins_manager,
):
# given
order = order_with_lines
@@ -916,8 +917,8 @@ def test_create_transaction_event_from_request_triggers_webhooks_when_authorized
# when
with django_capture_on_commit_callbacks(execute=True):
- create_transaction_event_from_request_and_webhook_response(
- request_event, app, response_data
+ create_transaction_event_for_transaction_session(
+ request_event, app, plugins_manager, response_data
)
# then
@@ -929,7 +930,7 @@ def test_create_transaction_event_from_request_triggers_webhooks_when_authorized
@freeze_time("2018-05-31 12:00:01")
def test_create_transaction_event_from_request_updates_order_authorize(
- transaction_item_generator, app, order_with_lines
+ transaction_item_generator, app, order_with_lines, plugins_manager
):
# given
order = order_with_lines
@@ -953,8 +954,8 @@ def test_create_transaction_event_from_request_updates_order_authorize(
}
# when
- create_transaction_event_from_request_and_webhook_response(
- request_event, app, response_data
+ create_transaction_event_for_transaction_session(
+ request_event, app, plugins_manager, response_data
)
# then
@@ -1062,11 +1063,13 @@ def test_create_transaction_event_from_request_when_paid(
mocked_automatic_checkout_completion_task.assert_not_called()
[email protected](logger, "error")
@patch("saleor.checkout.tasks.automatic_checkout_completion_task.delay")
@patch("saleor.plugins.manager.PluginsManager.checkout_fully_paid")
-def test_create_transaction_event_from_request_when_authorized(
+def test_create_transaction_event_from_request_when_authorized_logs_warnning(
mocked_checkout_fully_paid,
mocked_automatic_checkout_completion_task,
+ mocked_logger,
transaction_item_generator,
app,
checkout_with_prices,
@@ -1078,9 +1081,10 @@ def test_create_transaction_event_from_request_when_authorized(
channel = checkout.channel
assert channel.automatically_complete_fully_paid_checkouts is False
+ request_event_type = TransactionEventType.AUTHORIZATION_REQUEST
transaction = transaction_item_generator(checkout_id=checkout.pk)
request_event = TransactionEvent.objects.create(
- type=TransactionEventType.AUTHORIZATION_REQUEST,
+ type=request_event_type,
amount_value=checkout.total.gross.amount,
currency="USD",
transaction_id=transaction.id,
@@ -1104,10 +1108,14 @@ def test_create_transaction_event_from_request_when_authorized(
)
# then
+ # the `create_transaction_event_from_request_and_webhook_response` should never
+ # be called for `AUTHORIZATION_REQUEST` event type
+ assert checkout.authorize_status == CheckoutAuthorizeStatus.NONE
checkout.refresh_from_db()
- assert checkout.authorize_status == CheckoutAuthorizeStatus.FULL
mocked_checkout_fully_paid.assert_not_called()
mocked_automatic_checkout_completion_task.assert_not_called()
+ assert mocked_logger.call_count == 1
+ assert len(mocked_logger.call_args) == 2
@patch("saleor.checkout.tasks.automatic_checkout_completion_task.delay")
@@ -1166,7 +1174,7 @@ def test_create_transaction_event_from_request_when_paid_triggers_checkout_compl
@patch("saleor.checkout.tasks.automatic_checkout_completion_task.delay")
@patch("saleor.plugins.manager.PluginsManager.checkout_fully_paid")
-def test_create_transaction_event_from_request_when_authorized_triggers_checkout_completion(
+def test_create_transaction_event_from_session_when_authorized_triggers_checkout_completion(
mocked_checkout_fully_paid,
mocked_automatic_checkout_completion_task,
transaction_item_generator,
@@ -1205,8 +1213,8 @@ def test_create_transaction_event_from_request_when_authorized_triggers_checkout
# when
with django_capture_on_commit_callbacks(execute=True):
- create_transaction_event_from_request_and_webhook_response(
- request_event, app, response_data
+ create_transaction_event_for_transaction_session(
+ request_event, app, plugins_manager, response_data
)
# then
@@ -1249,9 +1257,10 @@ def test_create_transaction_event_from_request_and_webhook_response_incorrect_da
@freeze_time("2018-05-31 12:00:01")
-def test_create_transaction_event_from_request_and_webhook_response_twice_auth(
+def test_create_transaction_event_for_transaction_session_twice_auth(
transaction_item_generator,
app,
+ plugins_manager,
):
# given
transaction = transaction_item_generator()
@@ -1284,17 +1293,14 @@ def test_create_transaction_event_from_request_and_webhook_response_twice_auth(
}
# when
- failed_event = create_transaction_event_from_request_and_webhook_response(
- request_event, app, response_data
+ failed_event = create_transaction_event_for_transaction_session(
+ request_event, app, plugins_manager, response_data
)
# then
assert TransactionEvent.objects.count() == 3
- request_event.refresh_from_db()
- assert request_event.psp_reference == expected_psp_reference
- assert request_event.include_in_calculations is True
assert failed_event
- assert failed_event.psp_reference == expected_psp_reference
+ assert failed_event.psp_reference == request_event.psp_reference
assert failed_event.type == TransactionEventType.AUTHORIZATION_FAILURE
@@ -1312,7 +1318,7 @@ def test_create_transaction_event_from_request_and_webhook_response_same_event(
# given
expected_psp_reference = "psp:122:222"
event_amount = first_event_amount
- event_type = TransactionEventType.AUTHORIZATION_SUCCESS
+ event_type = TransactionEventType.CHARGE_SUCCESS
event_time = "2022-11-18T13:25:58.169685+00:00"
event_url = "http://localhost:3000/event/ref123"
@@ -1325,7 +1331,7 @@ def test_create_transaction_event_from_request_and_webhook_response_same_event(
)
request_event = TransactionEvent.objects.create(
- type=TransactionEventType.AUTHORIZATION_REQUEST,
+ type=TransactionEventType.CHARGE_REQUEST,
amount_value=second_event_amount,
currency="USD",
transaction_id=transaction.id,
@@ -1409,7 +1415,7 @@ def test_create_transaction_event_from_request_and_webhook_response_different_am
# given
expected_psp_reference = "psp:122:222"
authorize_event_amount = Decimal(12.00)
- event_type = TransactionEventType.AUTHORIZATION_SUCCESS
+ event_type = TransactionEventType.CHARGE_SUCCESS
event_time = "2022-11-18T13:25:58.169685+00:00"
event_url = "http://localhost:3000/event/ref123"
@@ -1423,7 +1429,7 @@ def test_create_transaction_event_from_request_and_webhook_response_different_am
second_authorize_event_amount = Decimal(33.00)
request_event = TransactionEvent.objects.create(
- type=TransactionEventType.AUTHORIZATION_REQUEST,
+ type=TransactionEventType.CHARGE_REQUEST,
amount_value=second_authorize_event_amount,
currency="USD",
transaction_id=transaction.id,
@@ -1449,7 +1455,7 @@ def test_create_transaction_event_from_request_and_webhook_response_different_am
assert request_event.include_in_calculations is True
assert failed_event
assert failed_event.psp_reference == expected_psp_reference
- assert failed_event.type == TransactionEventType.AUTHORIZATION_FAILURE
+ assert failed_event.type == TransactionEventType.CHARGE_FAILURE
@freeze_time("2018-05-31 12:00:01")
@@ -2222,11 +2228,11 @@ def test_create_transaction_event_for_transaction_session_not_success_events(
[
(
TransactionEventType.AUTHORIZATION_SUCCESS,
- "Providing `pspReference` is required for AUTHORIZATION_SUCCESS.",
+ "Providing `pspReference` is required for AUTHORIZATION_SUCCESS action result.",
),
(
TransactionEventType.CHARGE_SUCCESS,
- "Providing `pspReference` is required for CHARGE_SUCCESS.",
+ "Providing `pspReference` is required for CHARGE_SUCCESS action result.",
),
(
TransactionEventType.CHARGE_FAILURE,
@@ -2234,11 +2240,11 @@ def test_create_transaction_event_for_transaction_session_not_success_events(
),
(
TransactionEventType.CHARGE_REQUEST,
- "Providing `pspReference` is required for CHARGE_REQUEST.",
+ "Providing `pspReference` is required for CHARGE_REQUEST action result.",
),
(
TransactionEventType.AUTHORIZATION_REQUEST,
- "Providing `pspReference` is required for AUTHORIZATION_REQUEST.",
+ "Providing `pspReference` is required for AUTHORIZATION_REQUEST action result.",
),
],
)
@@ -2274,7 +2280,7 @@ def test_create_transaction_event_for_transaction_session_missing_psp_reference(
# then
assert response_event.amount_value == expected_amount
assert response_event.type == TransactionEventType.CHARGE_FAILURE
- assert response_event.message == message
+ assert message in response_event.message
transaction.refresh_from_db()
assert transaction.authorized_value == Decimal("0")
assert transaction.charged_value == Decimal("0")
diff --git a/saleor/payment/utils.py b/saleor/payment/utils.py
index 827d44add1..c8821f6198 100644
--- a/saleor/payment/utils.py
+++ b/saleor/payment/utils.py
@@ -1,4 +1,3 @@
-import datetime
import decimal
import json
import logging
@@ -13,6 +12,7 @@ from django.db import IntegrityError, transaction
from django.db.models import Q
from django.template.defaultfilters import truncatechars
from django.utils import timezone
+from pydantic import ValidationError
from ..account.models import User
from ..app.models import App
@@ -37,6 +37,12 @@ from ..order.utils import (
updates_amounts_for_order,
)
from ..plugins.manager import PluginsManager, get_plugins_manager
+from ..webhook.response_schemas.transaction import (
+ TransactionCancelRequestedSchema,
+ TransactionChargeRequestedSchema,
+ TransactionRefundRequestedSchema,
+ TransactionSessionSchema,
+)
from . import (
OPTIONAL_PSP_REFERENCE_EVENTS,
ChargeStatus,
@@ -75,6 +81,7 @@ ALLOWED_GATEWAY_KINDS = {choices[0] for choices in TransactionKind.CHOICES}
TRANSACTION_EVENT_MSG_MAX_LENGTH: int = TransactionEvent._meta.get_field( # type: ignore[assignment]
"message"
).max_length
+SESSION_REQUEST_EVENT_TYPE = "session-request"
def _recalculate_last_refund_success_for_transaction(
@@ -841,102 +848,6 @@ def parse_transaction_event_amount(
error_field_msg.append(missing_msg % "amount")
-def parse_transaction_event_data(
- event_data: dict,
- parsed_event_data: dict,
- error_field_msg: list[str],
- psp_reference: str | None,
- request_type: str,
- event_is_optional: bool = True,
-):
- if (
- event_is_optional
- and event_data.get("amount") is None
- and not event_data.get("result")
- ):
- return
- missing_msg = (
- "Missing value for field: %s in response of transaction action webhook."
- )
- invalid_msg = (
- "Incorrect value for field: %s, value: %s in "
- "response of transaction action webhook."
- )
-
- parsed_event_data["psp_reference"] = psp_reference
-
- possible_event_types = {
- str_to_enum(event_result): event_result
- for event_result in get_correct_event_types_based_on_request_type(request_type)
- }
-
- result = event_data.get("result")
- if result:
- if result in possible_event_types:
- parsed_event_data["type"] = possible_event_types[result]
- else:
- possible_types = ",".join(possible_event_types.keys())
- msg = (
- "Incorrect value: %s for field: `result` in the response. Request: %s "
- "can accept only types: %s"
- )
- logger.warning(msg, result, request_type.upper(), possible_types)
- error_field_msg.append(msg % (result, request_type.upper(), possible_types))
- else:
- logger.warning(missing_msg, "result")
- error_field_msg.append(missing_msg % "result")
-
- parsed_event_data["message"] = _clean_message(event_data)
-
- amount_data = event_data.get("amount")
- parse_transaction_event_amount(
- amount_data,
- parsed_event_data=parsed_event_data,
- error_field_msg=error_field_msg,
- invalid_msg=invalid_msg,
- missing_msg=missing_msg,
- )
-
- if event_time_data := event_data.get("time"):
- try:
- parsed_event_data["time"] = (
- datetime.datetime.fromisoformat(event_time_data).replace(
- tzinfo=datetime.UTC
- )
- if event_time_data
- else None
- )
- except ValueError:
- logger.warning(invalid_msg, "time", event_time_data)
- error_field_msg.append(invalid_msg % ("time", event_time_data))
- else:
- parsed_event_data["time"] = timezone.now()
-
- parsed_event_data["external_url"] = event_data.get("externalUrl", "")
-
-
-def _clean_message(event_data):
- message = event_data.get("message") or ""
- try:
- message = str(message)
- except (UnicodeEncodeError, TypeError, ValueError):
- invalid_err_msg = (
- "Incorrect value for field: %s in response of transaction action webhook."
- )
- logger.warning(invalid_err_msg, "message")
- message = ""
-
- if message and len(message) > TRANSACTION_EVENT_MSG_MAX_LENGTH:
- message = truncate_transaction_event_message(message)
- field_limit_exceeded_msg = (
- "Value for field: %s in response of transaction action webhook "
- "exceeds the character field limit. Message has been truncated."
- )
- logger.warning(field_limit_exceeded_msg, "message")
-
- return message
-
-
error_msg = str
@@ -951,57 +862,88 @@ def parse_transaction_action_data(
returns TransactionRequestResponse with all details.
If unable to parse, None will be returned.
"""
- psp_reference: str = response_data.get("pspReference")
- available_actions = response_data.get("actions", None)
- if available_actions is not None:
- possible_actions = {
- str_to_enum(event_action): event_action
- for event_action, _ in TransactionAction.CHOICES
- }
- available_actions = [
- possible_actions[action]
- for action in available_actions
- if action in possible_actions
- ]
-
- parsed_event_data: dict = {}
- error_field_msg: list[str] = []
- parse_transaction_event_data(
- event_data=response_data,
- parsed_event_data=parsed_event_data,
- error_field_msg=error_field_msg,
- psp_reference=psp_reference,
- request_type=request_type,
- event_is_optional=event_is_optional,
+ skip_data_parsing = (
+ event_is_optional
+ and response_data.get("amount") is None
+ and not response_data.get("result")
)
+ if skip_data_parsing:
+ psp_reference = response_data.get("pspReference")
+ if not psp_reference and request_type not in OPTIONAL_PSP_REFERENCE_EVENTS:
+ msg = f"Providing `pspReference` is required for {request_type.upper()}."
+ logger.warning(msg)
+ return None, msg
+ return (
+ TransactionRequestResponse(
+ psp_reference=psp_reference,
+ available_actions=parse_available_actions(
+ response_data.get("actions", None)
+ ),
+ event=None,
+ ),
+ None,
+ )
- if error_field_msg:
- # error field msg can contain details of the value returned by payment app
- # which means that we need to confirm that we don't exceed the field limit.
- msg = "\n".join(error_field_msg)
- msg = truncate_transaction_event_message(msg)
- return None, msg
+ response_data_model = None
+ request_type_to_schema_map = {
+ TransactionEventType.CHARGE_REQUEST: TransactionChargeRequestedSchema,
+ TransactionEventType.REFUND_REQUEST: TransactionRefundRequestedSchema,
+ TransactionEventType.CANCEL_REQUEST: TransactionCancelRequestedSchema,
+ SESSION_REQUEST_EVENT_TYPE: TransactionSessionSchema,
+ }
- request_event_type = parsed_event_data.get("type", request_type)
- if not psp_reference and request_event_type not in OPTIONAL_PSP_REFERENCE_EVENTS:
- msg = f"Providing `pspReference` is required for {request_event_type.upper()}."
- logger.warning(msg)
+ request_schema = request_type_to_schema_map.get(request_type)
+ if not request_schema:
+ logger.error(
+ "Request type %s not supported for parsing transaction action data.",
+ request_type,
+ extra={"request_type": request_type},
+ )
+ return None, "Request type not supported"
+
+ try:
+ response_data_model = (
+ request_schema.model_validate(response_data) # type: ignore[attr-defined]
+ )
+ except ValidationError as error:
+ error_msg = str(error)
+ logger.warning(error_msg)
+ msg = truncate_transaction_event_message(error_msg)
return None, msg
return (
TransactionRequestResponse(
- psp_reference=psp_reference,
- available_actions=available_actions,
+ psp_reference=response_data_model.psp_reference,
+ available_actions=response_data_model.actions,
event=(
- TransactionRequestEventResponse(**parsed_event_data)
- if parsed_event_data
- else None
+ TransactionRequestEventResponse(
+ psp_reference=response_data_model.psp_reference,
+ type=response_data_model.result,
+ amount=response_data_model.amount,
+ time=response_data_model.time,
+ external_url=str(response_data_model.external_url),
+ message=response_data_model.message,
+ )
),
),
None,
)
+def parse_available_actions(available_actions):
+ if available_actions is not None:
+ possible_actions = {
+ str_to_enum(event_action): event_action
+ for event_action, _ in TransactionAction.CHOICES
+ }
+ available_actions = [
+ possible_actions[action]
+ for action in available_actions
+ if action in possible_actions
+ ]
+ return available_actions
+
+
def truncate_transaction_event_message(message: str):
return truncatechars(message, TRANSACTION_EVENT_MSG_MAX_LENGTH)
@@ -1217,11 +1159,9 @@ def create_transaction_event_for_transaction_session(
manager: "PluginsManager",
transaction_webhook_response: dict[str, Any] | None = None,
):
- request_event_type = "session-request"
-
transaction_request_response, error_msg = _get_parsed_transaction_action_data(
transaction_webhook_response=transaction_webhook_response,
- event_type=request_event_type,
+ event_type=SESSION_REQUEST_EVENT_TYPE,
event_is_optional=False,
)
if not transaction_request_response or not transaction_request_response.event:
diff --git a/saleor/plugins/webhook/plugin.py b/saleor/plugins/webhook/plugin.py
index 186e871542..c53ea55a6c 100644
--- a/saleor/plugins/webhook/plugin.py
+++ b/saleor/plugins/webhook/plugin.py
@@ -91,6 +91,9 @@ from ...webhook.payloads import (
generate_transaction_session_payload,
generate_translation_payload,
)
+from ...webhook.response_schemas.transaction import (
+ PaymentGatewayInitializeSessionSchema,
+)
from ...webhook.transport.asynchronous.transport import (
WebhookPayloadData,
send_webhook_request_async,
@@ -3130,9 +3133,20 @@ class WebhookPlugin(BasePlugin):
error_msg = None
if response_data is None:
error_msg = "Unable to process a payment gateway response."
+
+ response_data_model = None
+ if response_data:
+ try:
+ response_data_model = (
+ PaymentGatewayInitializeSessionSchema.model_validate(response_data)
+ )
+ except ValidationError as e:
+ response_data = None
+ error_msg = str(e)
+
response_gateway[webhook.app.identifier] = PaymentGatewayData(
app_identifier=webhook.app.identifier,
- data=response_data,
+ data=response_data_model.data if response_data_model else None,
error=error_msg,
)
diff --git a/saleor/plugins/webhook/tests/test_payment_gateway_initialize_session_webhook.py b/saleor/plugins/webhook/tests/test_payment_gateway_initialize_session_webhook.py
index 17b34c9aba..5eb90b8df6 100644
--- a/saleor/plugins/webhook/tests/test_payment_gateway_initialize_session_webhook.py
+++ b/saleor/plugins/webhook/tests/test_payment_gateway_initialize_session_webhook.py
@@ -95,7 +95,9 @@ def test_gateway_initialize_checkout_without_request_data_and_static_payload(
):
# given
expected_data = {"some": "json data"}
- mock_request.return_value = expected_data
+ mock_request.return_value = {
+ "data": expected_data,
+ }
plugin = webhook_plugin()
webhook_app.identifier = "app.identifier"
@@ -130,7 +132,9 @@ def test_gateway_initialize_checkout_with_request_data_and_static_payload(
# given
data = {"some": "request-data"}
expected_data = {"some": "json data"}
- mock_request.return_value = expected_data
+ mock_request.return_value = {
+ "data": expected_data,
+ }
plugin = webhook_plugin()
webhook_app.identifier = "app.identifier"
@@ -167,7 +171,9 @@ def test_gateway_initialize_checkout_without_request_data(
):
# given
expected_data = {"some": "json data"}
- mock_request.return_value = expected_data
+ mock_request.return_value = {
+ "data": expected_data,
+ }
plugin = webhook_plugin()
webhook_app.identifier = "app.identifier"
@@ -204,7 +210,9 @@ def test_gateway_initialize_checkout_with_request_data(
# given
data = {"some": "request-data"}
expected_data = {"some": "json data"}
- mock_request.return_value = expected_data
+ mock_request.return_value = {
+ "data": expected_data,
+ }
plugin = webhook_plugin()
webhook_app.identifier = "app.identifier"
@@ -274,7 +282,9 @@ def test_gateway_initialize_order_without_request_data_static_payload(
):
# given
expected_data = {"some": "json data"}
- mock_request.return_value = expected_data
+ mock_request.return_value = {
+ "data": expected_data,
+ }
plugin = webhook_plugin()
webhook_app.identifier = "app.identifier"
@@ -309,7 +319,9 @@ def test_gateway_initialize_order_with_request_data_static_payload(
# given
data = {"some": "request-data"}
expected_data = {"some": "json data"}
- mock_request.return_value = expected_data
+ mock_request.return_value = {
+ "data": expected_data,
+ }
plugin = webhook_plugin()
webhook_app.identifier = "app.identifier"
@@ -346,7 +358,9 @@ def test_gateway_initialize_session_for_order_without_request_data(
):
# given
expected_data = {"some": "json data"}
- mock_request.return_value = expected_data
+ mock_request.return_value = {
+ "data": expected_data,
+ }
plugin = webhook_plugin()
webhook_app.identifier = "app.identifier"
@@ -384,7 +398,9 @@ def test_gateway_initialize_session_for_order_with_request_data(
# given
data = {"some": "request-data"}
expected_data = {"some": "json data"}
- mock_request.return_value = expected_data
+ mock_request.return_value = {
+ "data": expected_data,
+ }
plugin = webhook_plugin()
webhook_app.identifier = "app.identifier"
diff --git a/saleor/webhook/response_schemas/annotations.py b/saleor/webhook/response_schemas/annotations.py
index 4c3e5ba486..62d9d308b6 100644
--- a/saleor/webhook/response_schemas/annotations.py
+++ b/saleor/webhook/response_schemas/annotations.py
@@ -1,13 +1,20 @@
+import logging
+from datetime import UTC, datetime
from typing import Annotated, Any, TypeVar
from pydantic import (
+ AfterValidator,
BeforeValidator,
+ ValidationError,
+ ValidatorFunctionWrapHandler,
+ WrapValidator,
)
-from pydantic_core import PydanticUseDefault
+from pydantic_core import PydanticOmit, PydanticUseDefault
from ...core.utils.metadata_manager import metadata_is_valid
M = TypeVar("M")
+logger = logging.getLogger(__name__)
def skip_invalid_metadata(value: M) -> M:
@@ -27,3 +34,16 @@ def default_if_none(value: Any) -> Any:
T = TypeVar("T")
DefaultIfNone = Annotated[T, BeforeValidator(default_if_none)]
+
+DatetimeUTC = Annotated[datetime, AfterValidator(lambda v: v.replace(tzinfo=UTC))]
+
+
+def skip_invalid_literal(value: T, handler: ValidatorFunctionWrapHandler) -> T:
+ try:
+ return handler(value)
+ except ValidationError as err:
+ logger.warning("Skipping invalid literal value: %s", err)
+ raise PydanticOmit() from err
+
+
+OnErrorSkipLiteral = Annotated[T, WrapValidator(skip_invalid_literal)]
diff --git a/saleor/webhook/response_schemas/transaction.py b/saleor/webhook/response_schemas/transaction.py
new file mode 100644
index 0000000000..dc56664e07
--- /dev/null
+++ b/saleor/webhook/response_schemas/transaction.py
@@ -0,0 +1,217 @@
+import logging
+from datetime import datetime
+from decimal import Decimal
+from enum import Enum
+from typing import Annotated, Any, Literal
+
+from django.conf import settings
+from django.utils import timezone
+from pydantic import (
+ BaseModel,
+ Field,
+ HttpUrl,
+ JsonValue,
+ field_validator,
+ model_validator,
+)
+
+from ...graphql.core.utils import str_to_enum
+from ...payment import (
+ OPTIONAL_PSP_REFERENCE_EVENTS,
+ TransactionAction,
+ TransactionEventType,
+)
+from .annotations import DatetimeUTC, DefaultIfNone, OnErrorSkipLiteral
+
+logger = logging.getLogger(__name__)
+
+
+TransactionActionEnum = Enum( # type: ignore[misc]
+ "TransactionActionEnum",
+ [(str_to_enum(value), value) for value, _ in TransactionAction.CHOICES],
+)
+
+
+class TransactionSchema(BaseModel):
+ psp_reference: Annotated[
+ DefaultIfNone[str],
+ Field(
+ validation_alias="pspReference",
+ default=None,
+ description=(
+ "Psp reference received from payment provider. Optional for the following results: "
+ + ", ".join([event.upper() for event in OPTIONAL_PSP_REFERENCE_EVENTS])
+ ),
+ ),
+ ]
+ amount: Annotated[
+ Decimal, Field(description="Decimal amount of the processed action")
+ ]
+ time: Annotated[
+ DefaultIfNone[DatetimeUTC],
+ Field(
+ description="Time of the action in ISO 8601 format",
+ default_factory=timezone.now,
+ ),
+ ]
+ external_url: Annotated[
+ DefaultIfNone[HttpUrl],
+ Field(
+ validation_alias="externalUrl",
+ description="External url with action details",
+ default="",
+ ),
+ ]
+ message: Annotated[
+ DefaultIfNone[str],
+ Field(
+ description="Message related to the action. The maximum length is 512 characters; any text exceeding this limit will be truncated",
+ default="",
+ ),
+ ]
+ actions: ( # type: ignore[name-defined]
+ Annotated[
+ list[
+ OnErrorSkipLiteral[
+ Literal[
+ TransactionActionEnum.CHARGE.name,
+ TransactionActionEnum.REFUND.name,
+ TransactionActionEnum.CANCEL.name,
+ ]
+ ]
+ ],
+ Field(description="List of actions available for the transaction."),
+ ]
+ | None
+ ) = None
+ result: Annotated[
+ str,
+ Field(description="Result of the action"),
+ ]
+
+ @model_validator(mode="after")
+ def clean_psp_reference(self):
+ if not self.psp_reference and self.result not in OPTIONAL_PSP_REFERENCE_EVENTS:
+ error_msg = f"Providing `pspReference` is required for {self.result.upper()} action result."
+ raise ValueError(error_msg)
+ return self
+
+ @field_validator("amount", mode="after")
+ @classmethod
+ def clean_amount(cls, amount: Decimal) -> Decimal:
+ amount = amount.quantize(Decimal(10) ** (-settings.DEFAULT_DECIMAL_PLACES))
+ return amount
+
+ @field_validator("time", mode="before")
+ @classmethod
+ def clean_time(cls, time: Any) -> datetime | None:
+ # pydantic do not support all ISO 8601 formats so in case of string
+ # we need to parse it manually; different types are handled by pydantic
+ if isinstance(time, str):
+ try:
+ time = datetime.fromisoformat(time)
+ except ValueError as e:
+ raise ValueError(
+ "Invalid value for field 'time': {time}. Expected ISO 8601 format."
+ ) from e
+
+ return time
+
+ @field_validator("message", mode="before")
+ @classmethod
+ def clean_message(cls, value: Any):
+ from ...payment.utils import (
+ TRANSACTION_EVENT_MSG_MAX_LENGTH,
+ truncate_transaction_event_message,
+ )
+
+ message = value or ""
+ try:
+ message = str(message)
+ except (UnicodeEncodeError, TypeError, ValueError):
+ invalid_err_msg = "Incorrect value for field: %s in response of transaction action webhook."
+ logger.warning(invalid_err_msg, "message")
+ message = ""
+
+ if message and len(message) > TRANSACTION_EVENT_MSG_MAX_LENGTH:
+ message = truncate_transaction_event_message(message)
+ field_limit_exceeded_msg = (
+ "Value for field: %s in response of transaction action webhook "
+ "exceeds the character field limit. Message has been truncated."
+ )
+ logger.warning(field_limit_exceeded_msg, "message")
+
+ return message
+
+ @field_validator("actions", mode="after")
+ @classmethod
+ def clean_actions(cls, actions: list[str] | None) -> list[str] | None:
+ return [action.lower() for action in actions] if actions else actions
+
+ @field_validator("result", mode="after")
+ @classmethod
+ def clean_result(cls, result: str) -> str:
+ return result.lower()
+
+
+TransactionEventTypeEnum = Enum( # type: ignore[misc]
+ "TransactionEventTypeEnum",
+ [(str_to_enum(value), value) for value, _ in TransactionEventType.CHOICES],
+)
+
+
+class TransactionChargeRequestedSchema(TransactionSchema):
+ result: Annotated[ # type: ignore[name-defined]
+ Literal[
+ TransactionEventTypeEnum.CHARGE_SUCCESS.name,
+ TransactionEventTypeEnum.CHARGE_FAILURE.name,
+ ],
+ Field(description="Result of the action"),
+ ]
+
+
+class TransactionCancelRequestedSchema(TransactionSchema):
+ result: Annotated[ # type: ignore[name-defined]
+ Literal[
+ TransactionEventTypeEnum.CANCEL_SUCCESS.name,
+ TransactionEventTypeEnum.CANCEL_FAILURE.name,
+ ],
+ Field(description="Result of the action"),
+ ]
+
+
+class TransactionRefundRequestedSchema(TransactionSchema):
+ result: Annotated[ # type: ignore[name-defined]
+ Literal[
+ TransactionEventTypeEnum.REFUND_SUCCESS.name,
+ TransactionEventTypeEnum.REFUND_FAILURE.name,
+ ],
+ Field(description="Result of the action"),
+ ]
+
+
+class TransactionSessionSchema(TransactionSchema):
+ result: Annotated[ # type: ignore[name-defined]
+ Literal[
+ TransactionEventTypeEnum.AUTHORIZATION_SUCCESS.name,
+ TransactionEventTypeEnum.AUTHORIZATION_FAILURE.name,
+ TransactionEventTypeEnum.AUTHORIZATION_ACTION_REQUIRED.name,
+ TransactionEventTypeEnum.AUTHORIZATION_REQUEST.name,
+ TransactionEventTypeEnum.CHARGE_SUCCESS.name,
+ TransactionEventTypeEnum.CHARGE_FAILURE.name,
+ TransactionEventTypeEnum.CHARGE_ACTION_REQUIRED.name,
+ TransactionEventTypeEnum.CHARGE_REQUEST.name,
+ ],
+ Field(description="Result of the action"),
+ ]
+ data: Annotated[
+ DefaultIfNone[JsonValue],
+ Field(
+ description="The JSON data that will be returned to storefront",
+ default=None,
+ ),
+ ]
+
+
+class PaymentGatewayInitializeSessionSchema(BaseModel):
+ data: JsonValue
diff --git a/saleor/webhook/tests/response_schemas/test_transaction.py b/saleor/webhook/tests/response_schemas/test_transaction.py
new file mode 100644
index 0000000000..362b7e30f4
--- /dev/null
+++ b/saleor/webhook/tests/response_schemas/test_transaction.py
@@ -0,0 +1,612 @@
+import math
+from datetime import UTC, datetime
+from decimal import Decimal
+
+import pytest
+from django.utils import timezone
+from freezegun import freeze_time
+from pydantic import ValidationError
+
+from ....payment import TransactionAction, TransactionEventType
+from ...response_schemas.transaction import (
+ PaymentGatewayInitializeSessionSchema,
+ TransactionCancelRequestedSchema,
+ TransactionChargeRequestedSchema,
+ TransactionRefundRequestedSchema,
+ TransactionSchema,
+ TransactionSessionSchema,
+)
+
+
+def test_transaction_schema_valid_full_data():
+ # given
+ data = {
+ "pspReference": "psp-123",
+ "amount": Decimal("100.50"),
+ "time": "2023-01-01T12:00:00+00:00",
+ "externalUrl": "https://example.com/",
+ "message": "Transaction completed successfully.",
+ "actions": [TransactionAction.CHARGE.upper(), TransactionAction.REFUND.upper()],
+ "result": TransactionEventType.CHARGE_SUCCESS.upper(),
+ }
+
+ # when
+ transaction = TransactionSchema.model_validate(data)
+
+ # then
+ assert transaction.psp_reference == data["pspReference"]
+ assert transaction.amount == data["amount"]
+ assert transaction.time.isoformat() == data["time"]
+ assert str(transaction.external_url) == data["externalUrl"]
+ assert transaction.message == data["message"]
+ assert transaction.actions == [action.lower() for action in data.get("actions")]
+ assert transaction.result == data["result"].lower()
+
+
+ "data",
+ [
+ # Only required fields with values
+ {
+ "pspReference": None,
+ "amount": Decimal("100.50"),
+ "time": None,
+ "externalUrl": None,
+ "message": None,
+ "actions": None,
+ "result": TransactionEventType.CHARGE_ACTION_REQUIRED.upper(),
+ },
+ # Only required fields with values
+ {
+ "amount": Decimal("100.50"),
+ "result": TransactionEventType.CHARGE_ACTION_REQUIRED.upper(),
+ },
+ ],
+)
+@freeze_time("2023-01-01T12:00:00+00:00")
+def test_transaction_schema_valid_only_required_fields(data):
+ # when
+ transaction = TransactionSchema.model_validate(data)
+
+ # then
+ assert transaction.psp_reference is None
+ assert transaction.amount == data["amount"]
+ assert transaction.time.isoformat() == timezone.now().isoformat()
+ assert str(transaction.external_url) == ""
+ assert transaction.message == ""
+ assert transaction.actions is None
+ assert transaction.result == data["result"].lower()
+
+
+ "amount",
+ [Decimal("100.50"), 100.50, 100, "100.50"],
+)
+def test_transaction_schema_with_various_amount_types(amount):
+ # given
+ data = {
+ "pspReference": "psp-123",
+ "amount": amount,
+ "result": TransactionEventType.CHARGE_SUCCESS.upper(),
+ }
+
+ # when
+ transaction = TransactionSchema.model_validate(data)
+
+ # then
+ assert transaction.amount == Decimal(str(amount))
+
+
+ ("time", "time_parser"),
+ [
+ # ISO 8601 format with timezone
+ ("2023-01-01T12:00:00+00:00", datetime.fromisoformat),
+ # ISO 8601 format without timezone
+ ("2023-01-01T12:00:00", datetime.fromisoformat),
+ # ISO 8601 format with milliseconds
+ ("2023-01-01T12:00:00.123+00:00", datetime.fromisoformat),
+ # ISO 8601 format with week-based date
+ ("2023-W01-1T12:00:00", datetime.fromisoformat),
+ # Time as integer
+ (1672531200, datetime.fromtimestamp),
+ # No time provided (should use current time)
+ (None, None),
+ ],
+)
+@freeze_time("2023-01-01T12:00:00+00:00")
+def test_transaction_schema_time_valid(time, time_parser):
+ # given
+ data = {
+ "pspReference": "123",
+ "amount": Decimal("100.00"),
+ "result": TransactionEventType.CHARGE_SUCCESS.upper(),
+ "time": time,
+ }
+
+ # when
+ transaction = TransactionSchema.model_validate(data)
+
+ # then
+ time = data.get("time")
+ parsed_time = time_parser(time) if time else timezone.now()
+ assert transaction.time == parsed_time.replace(tzinfo=UTC)
+
+
+ ("actions", "expected_actions"),
+ [
+ # Valid actions
+ (
+ [
+ TransactionAction.CHARGE.upper(),
+ TransactionAction.REFUND.upper(),
+ TransactionAction.CANCEL.upper(),
+ ],
+ [
+ TransactionAction.CHARGE,
+ TransactionAction.REFUND,
+ TransactionAction.CANCEL,
+ ],
+ ),
+ # Just one action
+ (
+ [TransactionAction.CANCEL.upper()],
+ [TransactionAction.CANCEL],
+ ),
+ # Invalid actions (should skip invalid ones)
+ (
+ ["INVALID", TransactionAction.REFUND.upper()],
+ [TransactionAction.REFUND],
+ ),
+ # Empty actions list
+ (
+ [],
+ [],
+ ),
+ # None actions
+ (
+ None,
+ None,
+ ),
+ ],
+)
+def test_transaction_schema_actions_validation(actions, expected_actions):
+ # given
+ data = {
+ "pspReference": "123",
+ "amount": Decimal("100.00"),
+ "result": TransactionEventType.CHARGE_SUCCESS.upper(),
+ "actions": actions,
+ }
+
+ # when
+ transaction = TransactionSchema.model_validate(data)
+
+ # then
+ assert transaction.actions == expected_actions
+
+
+ ("data", "invalid_field"),
+ [
+ # Time as a string value
+ (
+ {
+ "pspReference": "123",
+ "amount": Decimal("100.00"),
+ "result": TransactionEventType.CHARGE_SUCCESS.upper(),
+ "time": "invalid-time",
+ },
+ "time",
+ ),
+ # Invalid external URL
+ (
+ {
+ "amount": "100.50",
+ "result": TransactionEventType.CHARGE_SUCCESS.upper(),
+ "externalUrl": "invalid-url",
+ },
+ "externalUrl",
+ ),
+ # Infinitive amount
+ (
+ {
+ "pspReference": "123",
+ "amount": math.inf,
+ "result": TransactionEventType.CHARGE_SUCCESS.upper(),
+ },
+ "amount",
+ ),
+ ],
+)
+def test_transaction_schema_invalid(data, invalid_field):
+ # when
+ with pytest.raises(ValidationError) as exc_info:
+ TransactionSchema.model_validate(data)
+
+ # then
+ assert len(exc_info.value.errors()) == 1
+ assert exc_info.value.errors()[0]["loc"] == (invalid_field,)
+
+
+ "result",
+ [
+ TransactionEventType.AUTHORIZATION_SUCCESS,
+ TransactionEventType.CHARGE_SUCCESS,
+ TransactionEventType.CANCEL_SUCCESS,
+ TransactionEventType.REFUND_SUCCESS,
+ TransactionEventType.CHARGE_BACK,
+ TransactionEventType.REFUND_REVERSE,
+ ],
+)
+def test_transaction_schema_time_missing_psp_reference(result):
+ # given
+ data = {
+ "amount": Decimal("100.00"),
+ "result": result.upper(),
+ }
+
+ # when/then
+ with pytest.raises(ValidationError) as exc_info:
+ TransactionSchema.model_validate(data)
+
+ assert len(exc_info.value.errors()) == 1
+
+
+ "result",
+ [
+ TransactionEventType.CHARGE_SUCCESS,
+ TransactionEventType.CHARGE_FAILURE,
+ ],
+)
+def test_transaction_charge_requested_schema_valid(result):
+ # given
+ data = {
+ "pspReference": "psp-123",
+ "amount": Decimal("100.50"),
+ "time": "2023-01-01T12:00:00+00:00",
+ "externalUrl": "https://example.com/",
+ "message": "Transaction completed successfully.",
+ "actions": [TransactionAction.CHARGE.upper(), TransactionAction.REFUND.upper()],
+ "result": result.upper(),
+ }
+
+ # when
+ transaction = TransactionChargeRequestedSchema.model_validate(data)
+
+ # then
+ assert transaction.result == result
+
+
+ "result",
+ [
+ TransactionEventType.CANCEL_FAILURE,
+ TransactionEventType.REFUND_FAILURE,
+ TransactionEventType.CANCEL_SUCCESS,
+ TransactionEventType.REFUND_SUCCESS,
+ ],
+)
+def test_transaction_charge_requested_schema_invalid(result):
+ # given
+ data = {
+ "pspReference": "psp-123",
+ "amount": Decimal("100.50"),
+ "time": "2023-01-01T12:00:00+00:00",
+ "externalUrl": "https://example.com/",
+ "message": "Transaction completed successfully.",
+ "actions": [TransactionAction.CHARGE.upper(), TransactionAction.REFUND.upper()],
+ "result": result.upper(),
+ }
+
+ # when
+ with pytest.raises(ValidationError) as exc_info:
+ TransactionChargeRequestedSchema.model_validate(data)
+
+ # then
+ assert len(exc_info.value.errors()) == 1
+ assert exc_info.value.errors()[0]["loc"] == ("result",)
+
+
+ "result",
+ [
+ TransactionEventType.CANCEL_SUCCESS,
+ TransactionEventType.CANCEL_FAILURE,
+ ],
+)
+def test_transaction_cancel_requested_schema_valid(result):
+ # given
+ data = {
+ "pspReference": "psp-123",
+ "amount": Decimal("100.50"),
+ "time": "2023-01-01T12:00:00+00:00",
+ "externalUrl": "https://example.com/",
+ "message": "Transaction completed successfully.",
+ "actions": [TransactionAction.CHARGE.upper(), TransactionAction.REFUND.upper()],
+ "result": result.upper(),
+ }
+
+ # when
+ transaction = TransactionCancelRequestedSchema.model_validate(data)
+
+ # then
+ assert transaction.result == result
+
+
+ "result",
+ [
+ TransactionEventType.CHARGE_FAILURE,
+ TransactionEventType.REFUND_FAILURE,
+ TransactionEventType.CHARGE_SUCCESS,
+ TransactionEventType.REFUND_SUCCESS,
+ ],
+)
+def test_transaction_cancel_requested_schema_invalid(result):
+ # given
+ data = {
+ "pspReference": "psp-123",
+ "amount": Decimal("100.50"),
+ "time": "2023-01-01T12:00:00+00:00",
+ "externalUrl": "https://example.com/",
+ "message": "Transaction completed successfully.",
+ "actions": [TransactionAction.CHARGE.upper(), TransactionAction.REFUND.upper()],
+ "result": result.upper(),
+ }
+
+ # when
+ with pytest.raises(ValidationError) as exc_info:
+ TransactionCancelRequestedSchema.model_validate(data)
+
+ # then
+ assert len(exc_info.value.errors()) == 1
+ assert exc_info.value.errors()[0]["loc"] == ("result",)
+
+
+ "result",
+ [
+ TransactionEventType.REFUND_SUCCESS,
+ TransactionEventType.REFUND_FAILURE,
+ ],
+)
+def test_transaction_refund_requested_schema_valid(result):
+ # given
+ data = {
+ "pspReference": "psp-123",
+ "amount": Decimal("100.50"),
+ "time": "2023-01-01T12:00:00+00:00",
+ "externalUrl": "https://example.com/",
+ "message": "Transaction completed successfully.",
+ "actions": [TransactionAction.CHARGE.upper(), TransactionAction.REFUND.upper()],
+ "result": result.upper(),
+ }
+
+ # when
+ transaction = TransactionRefundRequestedSchema.model_validate(data)
+
+ # then
+ assert transaction.result == result
+
+
+ "result",
+ [
+ TransactionEventType.CHARGE_FAILURE,
+ TransactionEventType.CANCEL_FAILURE,
+ TransactionEventType.CHARGE_SUCCESS,
+ TransactionEventType.CANCEL_SUCCESS,
+ ],
+)
+def test_transaction_refund_requested_schema_invalid(result):
+ # given
+ data = {
+ "pspReference": "psp-123",
+ "amount": Decimal("100.50"),
+ "time": "2023-01-01T12:00:00+00:00",
+ "externalUrl": "https://example.com/",
+ "message": "Transaction completed successfully.",
+ "actions": [TransactionAction.CHARGE.upper(), TransactionAction.REFUND.upper()],
+ "result": result.upper(),
+ }
+
+ # when
+ with pytest.raises(ValidationError) as exc_info:
+ TransactionRefundRequestedSchema.model_validate(data)
+
+ # then
+ assert len(exc_info.value.errors()) == 1
+ assert exc_info.value.errors()[0]["loc"] == ("result",)
+
+
+ "result",
+ [
+ TransactionEventType.AUTHORIZATION_SUCCESS,
+ TransactionEventType.AUTHORIZATION_FAILURE,
+ TransactionEventType.AUTHORIZATION_ACTION_REQUIRED,
+ TransactionEventType.AUTHORIZATION_REQUEST,
+ TransactionEventType.CHARGE_SUCCESS,
+ TransactionEventType.CHARGE_FAILURE,
+ TransactionEventType.CHARGE_ACTION_REQUIRED,
+ TransactionEventType.CHARGE_REQUEST,
+ ],
+)
+def test_transaction_session_schema_valid_result(result):
+ # given
+ data = {
+ "pspReference": "psp-123",
+ "amount": Decimal("100.50"),
+ "time": "2023-01-01T12:00:00+00:00",
+ "externalUrl": "https://example.com/",
+ "message": "Transaction completed successfully.",
+ "actions": [TransactionAction.CHARGE.upper(), TransactionAction.REFUND.upper()],
+ "result": result.upper(),
+ "data": "test-data",
+ }
+
+ # when
+ transaction = TransactionSessionSchema.model_validate(data)
+
+ # then
+ assert transaction.result == result
+
+
+ "result",
+ [
+ TransactionEventType.REFUND_FAILURE,
+ TransactionEventType.CANCEL_FAILURE,
+ TransactionEventType.REFUND_SUCCESS,
+ TransactionEventType.CANCEL_SUCCESS,
+ ],
+)
+def test_transaction_session_schema_invalid_result(result):
+ # given
+ data = {
+ "pspReference": "psp-123",
+ "amount": Decimal("100.50"),
+ "result": result.upper(),
+ }
+
+ # when
+ with pytest.raises(ValidationError) as exc_info:
+ TransactionSessionSchema.model_validate(data)
+
+ # then
+ assert len(exc_info.value.errors()) == 1
+ assert exc_info.value.errors()[0]["loc"] == ("result",)
+
+
+ "data_value",
+ [
+ # Valid data
+ {"key": "value", "another_key": "another_value"},
+ # Empty data
+ {},
+ # Data with special characters
+ {"key": "!@#$%^&*()_+"},
+ # Data with nested structure
+ {"nested": {"key": "value"}},
+ # Data with list
+ {"list": ["item1", "item2", "item3"]},
+ # Data as None
+ None,
+ # Data as string
+ "string_data",
+ # Data as integer
+ 123,
+ ],
+)
+def test_transaction_session_schema_valid_data(data_value):
+ # given
+ data = {
+ "pspReference": "psp-123",
+ "amount": Decimal("100.50"),
+ "result": TransactionEventType.AUTHORIZATION_SUCCESS.upper(),
+ "data": data_value,
+ }
+
+ # when
+ transaction = TransactionSessionSchema.model_validate(data)
+
+ # then
+ assert transaction.data == data_value
+
+
+ "data_value",
+ [
+ # Non-serializable object
+ object(),
+ # Set - not JSON serializable
+ {1, 2, 3},
+ # Function
+ lambda x: x,
+ # File handle
+ open,
+ ],
+)
+def test_transaction_session_schema_invalid_data(data_value):
+ # given
+ data = {
+ "pspReference": "psp-123",
+ "amount": Decimal("100.50"),
+ "result": TransactionEventType.CHARGE_SUCCESS.upper(),
+ "data": data_value,
+ }
+
+ # when
+ with pytest.raises(ValidationError) as exc_info:
+ TransactionSessionSchema.model_validate(data)
+
+ # then
+ assert len(exc_info.value.errors()) == 1
+ assert exc_info.value.errors()[0]["loc"] == ("data",)
+
+
+ "data_value",
+ [
+ # Valid data
+ {"key": "value", "another_key": "another_value"},
+ # Empty data
+ {},
+ # Data with special characters
+ {"key": "!@#$%^&*()_+"},
+ # Data with nested structure
+ {"nested": {"key": "value"}},
+ # Data with list
+ {"list": ["item1", "item2", "item3"]},
+ # Data as None
+ None,
+ # Data as string
+ "string_data",
+ # Data as integer
+ 123,
+ ],
+)
+def test_payment_gateway_initialize_schema_valid_data(data_value):
+ # given
+ data = {
+ "data": data_value,
+ }
+
+ # when
+ response = PaymentGatewayInitializeSessionSchema.model_validate(data)
+
+ # then
+ assert response.data == data_value
+
+
+ "data_value",
+ [
+ # Non-serializable object
+ object(),
+ # Set - not JSON serializable
+ {1, 2, 3},
+ # Function
+ lambda x: x,
+ # File handle
+ open,
+ ],
+)
+def test_payment_gateway_initialize_schema_invalid_data(data_value):
+ # given
+ data = {
+ "data": data_value,
+ }
+
+ # when
+ with pytest.raises(ValidationError) as exc_info:
+ PaymentGatewayInitializeSessionSchema.model_validate(data)
+
+ # then
+ assert len(exc_info.value.errors()) == 1
+ assert exc_info.value.errors()[0]["loc"] == ("data",)