Skip to content

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

Improve transaction json schema (#17752)

Iga Karbowiak8b409d8dfba5
diff --git a/saleor/payment/tests/test_utils.py b/saleor/payment/tests/test_utils.py
index 2301ac1319..465c4ac176 100644
--- a/saleor/payment/tests/test_utils.py
+++ b/saleor/payment/tests/test_utils.py
@@ -384,7 +384,7 @@ def test_parse_transaction_action_data_with_incorrect_result():
assert parsed_data is None
assert (
error_msg
- == f"Incorrect value ({response_data['result']}) for field: result. Error: Input should be '{TransactionEventType.REFUND_SUCCESS.upper()}' or '{TransactionEventType.REFUND_FAILURE.upper()}'."
+ == f"Missing or invalid value for `result`: {response_data['result']}. Possible values: {TransactionEventType.REFUND_SUCCESS.upper()}, {TransactionEventType.REFUND_FAILURE.upper()}."
)
@@ -658,10 +658,7 @@ 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()} "
- "action result."
- )
+ error_msg = f"Missing value for field: pspReference. Input: {response_data}."
assert error_msg in event.message
assert caplog.records[0].levelno == logging.WARNING
assert error_msg in caplog.records[0].message
@@ -2447,11 +2444,11 @@ def test_create_transaction_event_for_transaction_session_not_success_events_wit
[
(
TransactionEventType.AUTHORIZATION_SUCCESS,
- "Providing `pspReference` is required for AUTHORIZATION_SUCCESS action result.",
+ "Missing value for field: pspReference.",
),
(
TransactionEventType.CHARGE_SUCCESS,
- "Providing `pspReference` is required for CHARGE_SUCCESS action result.",
+ "Missing value for field: pspReference.",
),
(
TransactionEventType.CHARGE_FAILURE,
@@ -2459,11 +2456,11 @@ def test_create_transaction_event_for_transaction_session_not_success_events_wit
),
(
TransactionEventType.CHARGE_REQUEST,
- "Providing `pspReference` is required for CHARGE_REQUEST action result.",
+ "Missing value for field: pspReference.",
),
(
TransactionEventType.AUTHORIZATION_REQUEST,
- "Providing `pspReference` is required for AUTHORIZATION_REQUEST action result.",
+ "Missing value for field: pspReference.",
),
],
)
diff --git a/saleor/payment/utils.py b/saleor/payment/utils.py
index 01a22a5c03..4a588dab83 100644
--- a/saleor/payment/utils.py
+++ b/saleor/payment/utils.py
@@ -1,7 +1,7 @@
import json
import logging
from decimal import Decimal
-from typing import Any, Optional, cast, overload
+from typing import Any, Optional, cast, get_args, overload
import graphene
from babel.numbers import get_currency_precision
@@ -36,13 +36,7 @@ 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,
- TransactionSchema,
- TransactionSessionSchema,
-)
+from ..webhook.response_schemas import transaction as transaction_schemas
from ..webhook.response_schemas.utils.helpers import parse_validation_error
from . import (
ChargeStatus,
@@ -836,16 +830,12 @@ def parse_transaction_action_data(
returns TransactionRequestResponse with all details.
If unable to parse, None will be returned.
"""
-
- request_type_to_schema_map: dict[str, type[TransactionSchema]] = {
- TransactionEventType.CHARGE_REQUEST: TransactionChargeRequestedSchema,
- TransactionEventType.REFUND_REQUEST: TransactionRefundRequestedSchema,
- TransactionEventType.CANCEL_REQUEST: TransactionCancelRequestedSchema,
- SESSION_REQUEST_EVENT_TYPE: TransactionSessionSchema,
- }
-
- request_schema = request_type_to_schema_map.get(request_type)
- if not request_schema:
+ if request_type not in [
+ TransactionEventType.CHARGE_REQUEST,
+ TransactionEventType.REFUND_REQUEST,
+ TransactionEventType.CANCEL_REQUEST,
+ SESSION_REQUEST_EVENT_TYPE,
+ ]:
logger.error(
"Request type %s not supported for parsing transaction action data.",
request_type,
@@ -853,10 +843,37 @@ def parse_transaction_action_data(
)
return None, "Request type not supported"
- error_msg_response = None
try:
- response_data_model = request_schema.model_validate(
- response_data, context={"is_event_optional": event_is_optional}
+ if request_type in [
+ TransactionEventType.CHARGE_REQUEST,
+ TransactionEventType.REFUND_REQUEST,
+ TransactionEventType.CANCEL_REQUEST,
+ ]:
+ response_data_model = _validate_transaction_action_data(
+ response_data,
+ request_type,
+ event_is_optional,
+ )
+ else:
+ response_data_model = _validate_transaction_session_action_data(
+ response_data,
+ )
+ except ValidationError as error:
+ error_msg_response = parse_validation_error(error)
+ logger.warning(error_msg_response)
+ return None, truncate_transaction_event_message(error_msg_response)
+ except ValueError as error:
+ error_msg_response = str(error)
+ logger.warning(
+ "Error while parsing transaction action data: %s",
+ error_msg_response,
+ extra={"request_type": request_type},
+ )
+ return None, truncate_transaction_event_message(error_msg_response)
+ event = None
+ if getattr(response_data_model, "result", None):
+ response_data_model = cast(
+ transaction_schemas.TransactionSessionBaseSchema, response_data_model
)
event = TransactionRequestEventResponse(
psp_reference=response_data_model.psp_reference,
@@ -866,19 +883,95 @@ def parse_transaction_action_data(
external_url=str(response_data_model.external_url),
message=response_data_model.message,
)
- return (
- TransactionRequestResponse(
- psp_reference=response_data_model.psp_reference,
- available_actions=response_data_model.actions,
- event=event if response_data_model.result else None,
- ),
- None,
- )
- except ValidationError as error:
- error_msg_response = parse_validation_error(error)
- logger.warning(error_msg_response)
- error_msg_response = truncate_transaction_event_message(error_msg_response)
- return None, error_msg_response
+ return (
+ TransactionRequestResponse(
+ psp_reference=response_data_model.psp_reference,
+ available_actions=response_data_model.actions,
+ event=event,
+ ),
+ None,
+ )
+
+
+def _validate_transaction_action_data(
+ response_data: Any,
+ request_type: str,
+ event_is_optional: bool,
+) -> (
+ transaction_schemas.TransactionBaseSchema
+ | transaction_schemas.TransactionAsyncSchema
+):
+ request_type_to_schemas_map: dict[str, tuple] = {
+ TransactionEventType.CHARGE_REQUEST: (
+ transaction_schemas.TransactionChargeRequestedSyncSuccessSchema,
+ transaction_schemas.TransactionChargeRequestedSyncFailureSchema,
+ transaction_schemas.TransactionChargeRequestedAsyncSchema,
+ ),
+ TransactionEventType.REFUND_REQUEST: (
+ transaction_schemas.TransactionRefundRequestedSyncSuccessSchema,
+ transaction_schemas.TransactionRefundRequestedSyncFailureSchema,
+ transaction_schemas.TransactionRefundRequestedAsyncSchema,
+ ),
+ TransactionEventType.CANCEL_REQUEST: (
+ transaction_schemas.TransactionCancelRequestedSyncSuccessSchema,
+ transaction_schemas.TransactionCancelRequestedSyncFailureSchema,
+ transaction_schemas.TransactionCancelRequestedAsyncSchema,
+ ),
+ }
+ success_schema, failure_schema, async_schema = request_type_to_schemas_map[
+ request_type
+ ]
+ result_value = response_data.get("result")
+ if result_value in get_args(success_schema.model_fields["result"].annotation):
+ return success_schema.model_validate(response_data)
+ if result_value in get_args(failure_schema.model_fields["result"].annotation):
+ return failure_schema.model_validate(response_data)
+ if result_value is None and event_is_optional:
+ return async_schema.model_validate(response_data)
+ possible_values = ", ".join(
+ list(get_args(success_schema.model_fields["result"].annotation))
+ + list(get_args(failure_schema.model_fields["result"].annotation))
+ )
+ logger.warning(
+ "Invalid value for `result`: %s. Possible values: %s.",
+ result_value,
+ possible_values,
+ )
+ raise ValueError(
+ f"Missing or invalid value for `result`: {result_value}. Possible values: {possible_values}."
+ )
+
+
+def _validate_transaction_session_action_data(
+ response_data: Any,
+) -> transaction_schemas.TransactionSessionBaseSchema:
+ success_schema = transaction_schemas.TransactionSessionSuccessSchema
+ failure_schema = transaction_schemas.TransactionSessionFailureSchema
+ action_required_schema = transaction_schemas.TransactionSessionActionRequiredSchema
+
+ result_value = response_data.get("result")
+ if result_value in get_args(success_schema.model_fields["result"].annotation):
+ return success_schema.model_validate(response_data)
+ if result_value in get_args(failure_schema.model_fields["result"].annotation):
+ return failure_schema.model_validate(response_data)
+ if result_value in get_args(
+ action_required_schema.model_fields["result"].annotation
+ ):
+ return action_required_schema.model_validate(response_data)
+ possible_values = ", ".join(
+ [
+ value.name
+ for value in transaction_schemas.TransactionEventTypeEnum.__members__.values()
+ ]
+ )
+ logger.warning(
+ "Invalid value for `result`: %s. Possible values: %s.",
+ result_value,
+ possible_values,
+ )
+ raise ValueError(
+ f"Missing or invalid value for `result`: {result_value}. Possible values: {possible_values}."
+ )
def parse_available_actions(available_actions):
diff --git a/saleor/webhook/response_schemas/transaction.py b/saleor/webhook/response_schemas/transaction.py
index d3b6f8cb56..f6305afeab 100644
--- a/saleor/webhook/response_schemas/transaction.py
+++ b/saleor/webhook/response_schemas/transaction.py
@@ -11,9 +11,7 @@ from pydantic import (
Field,
HttpUrl,
JsonValue,
- ValidationInfo,
field_validator,
- model_validator,
)
from ...graphql.core.utils import str_to_enum
@@ -33,7 +31,7 @@ TransactionActionEnum = Enum( # type: ignore[misc]
)
-class TransactionSchema(BaseModel):
+class TransactionBaseSchema(BaseModel):
psp_reference: Annotated[
DefaultIfNone[str],
Field(
@@ -94,24 +92,6 @@ class TransactionSchema(BaseModel):
Field(description="Result of the action"),
]
- @model_validator(mode="after")
- def clean_event(self, info: ValidationInfo):
- is_event_optional = (
- info.context.get("is_event_optional", False) if info.context else False
- )
-
- if self.result is None:
- if not is_event_optional:
- raise ValueError("Providing `result` is required.")
- if not self.psp_reference:
- raise ValueError("Providing `pspReference` is required.")
- elif (
- 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 | None) -> Decimal | None:
@@ -174,61 +154,173 @@ class TransactionSchema(BaseModel):
return result.lower()
+class TransactionAsyncSchema(BaseModel):
+ psp_reference: Annotated[
+ str,
+ Field(
+ validation_alias="pspReference",
+ description=("Psp reference received from payment provider."),
+ ),
+ ]
+ 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
+
+
+class TransactionSyncFailureSchema(TransactionBaseSchema):
+ psp_reference: Annotated[
+ DefaultIfNone[str],
+ Field(
+ validation_alias="pspReference",
+ default=None,
+ description=("Psp reference received from payment provider."),
+ ),
+ ]
+
+
+class TransactionSyncSuccessSchema(TransactionBaseSchema):
+ psp_reference: Annotated[
+ str,
+ Field(
+ validation_alias="pspReference",
+ description=("Psp reference received from payment provider."),
+ ),
+ ]
+
+
TransactionEventTypeEnum = Enum( # type: ignore[misc]
"TransactionEventTypeEnum",
[(str_to_enum(value), value) for value, _ in TransactionEventType.CHOICES],
)
-class TransactionChargeRequestedSchema(TransactionSchema):
+class TransactionChargeRequestedAsyncSchema(TransactionAsyncSchema):
+ pass
+
+
+class TransactionChargeRequestedSyncSuccessSchema(TransactionSyncSuccessSchema):
result: Annotated[ # type: ignore[name-defined]
- Literal[
- TransactionEventTypeEnum.CHARGE_SUCCESS.name,
- TransactionEventTypeEnum.CHARGE_FAILURE.name,
- ],
- Field(description="Result of the action", default=None),
+ Literal[TransactionEventTypeEnum.CHARGE_SUCCESS.name,],
+ Field(description="Result of the action"),
+ ]
+
+
+class TransactionChargeRequestedSyncFailureSchema(TransactionSyncFailureSchema):
+ result: Annotated[ # type: ignore[name-defined]
+ Literal[TransactionEventTypeEnum.CHARGE_FAILURE.name,],
+ Field(description="Result of the action"),
+ ]
+
+
+class TransactionCancelRequestedAsyncSchema(TransactionAsyncSchema):
+ pass
+
+
+class TransactionCancelRequestedSyncSuccessSchema(TransactionSyncSuccessSchema):
+ result: Annotated[ # type: ignore[name-defined]
+ Literal[TransactionEventTypeEnum.CANCEL_SUCCESS.name,],
+ Field(description="Result of the action"),
+ ]
+
+
+class TransactionCancelRequestedSyncFailureSchema(TransactionSyncFailureSchema):
+ result: Annotated[ # type: ignore[name-defined]
+ Literal[TransactionEventTypeEnum.CANCEL_FAILURE.name,],
+ Field(description="Result of the action"),
+ ]
+
+
+class TransactionRefundRequestedAsyncSchema(TransactionAsyncSchema):
+ pass
+
+
+class TransactionRefundRequestedSyncSuccessSchema(TransactionSyncSuccessSchema):
+ result: Annotated[ # type: ignore[name-defined]
+ Literal[TransactionEventTypeEnum.REFUND_SUCCESS.name,],
+ Field(description="Result of the action"),
+ ]
+
+
+class TransactionRefundRequestedSyncFailureSchema(TransactionSyncFailureSchema):
+ result: Annotated[ # type: ignore[name-defined]
+ Literal[TransactionEventTypeEnum.REFUND_FAILURE.name,],
+ Field(description="Result of the action"),
]
-class TransactionCancelRequestedSchema(TransactionSchema):
+class TransactionSessionBaseSchema(TransactionBaseSchema):
+ data: Annotated[
+ DefaultIfNone[JsonValue],
+ Field(
+ description="The JSON data that will be returned to storefront",
+ default=None,
+ ),
+ ]
+
+
+class TransactionSessionFailureSchema(TransactionSessionBaseSchema):
result: Annotated[ # type: ignore[name-defined]
Literal[
- TransactionEventTypeEnum.CANCEL_SUCCESS.name,
- TransactionEventTypeEnum.CANCEL_FAILURE.name,
+ TransactionEventTypeEnum.AUTHORIZATION_FAILURE.name,
+ TransactionEventTypeEnum.CHARGE_FAILURE.name,
],
- Field(description="Result of the action", default=None),
+ Field(description="Result of the action"),
+ ]
+ psp_reference: Annotated[
+ DefaultIfNone[str],
+ Field(
+ validation_alias="pspReference",
+ default=None,
+ description=("Psp reference received from payment provider."),
+ ),
]
-class TransactionRefundRequestedSchema(TransactionSchema):
+class TransactionSessionActionRequiredSchema(TransactionSessionBaseSchema):
result: Annotated[ # type: ignore[name-defined]
Literal[
- TransactionEventTypeEnum.REFUND_SUCCESS.name,
- TransactionEventTypeEnum.REFUND_FAILURE.name,
+ TransactionEventTypeEnum.AUTHORIZATION_ACTION_REQUIRED.name,
+ TransactionEventTypeEnum.CHARGE_ACTION_REQUIRED.name,
],
- Field(description="Result of the action", default=None),
+ Field(description="Result of the action"),
+ ]
+ psp_reference: Annotated[
+ DefaultIfNone[str],
+ Field(
+ validation_alias="pspReference",
+ default=None,
+ description=("Psp reference received from payment provider."),
+ ),
]
-class TransactionSessionSchema(TransactionSchema):
+class TransactionSessionSuccessSchema(TransactionSessionBaseSchema):
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.AUTHORIZATION_REQUEST.name,
TransactionEventTypeEnum.CHARGE_REQUEST.name,
],
Field(description="Result of the action"),
]
- data: Annotated[
- DefaultIfNone[JsonValue],
+ psp_reference: Annotated[
+ str,
Field(
- description="The JSON data that will be returned to storefront",
- default=None,
+ validation_alias="pspReference",
+ description=("Psp reference received from payment provider."),
),
]
diff --git a/saleor/webhook/tests/response_schemas/test_transaction.py b/saleor/webhook/tests/response_schemas/test_transaction.py
index 0af2b4c3d3..c3c9259702 100644
--- a/saleor/webhook/tests/response_schemas/test_transaction.py
+++ b/saleor/webhook/tests/response_schemas/test_transaction.py
@@ -10,11 +10,20 @@ from pydantic import ValidationError
from ....payment import TransactionAction, TransactionEventType
from ...response_schemas.transaction import (
PaymentGatewayInitializeSessionSchema,
- TransactionCancelRequestedSchema,
- TransactionChargeRequestedSchema,
- TransactionRefundRequestedSchema,
- TransactionSchema,
- TransactionSessionSchema,
+ TransactionBaseSchema,
+ TransactionCancelRequestedAsyncSchema,
+ TransactionCancelRequestedSyncFailureSchema,
+ TransactionCancelRequestedSyncSuccessSchema,
+ TransactionChargeRequestedAsyncSchema,
+ TransactionChargeRequestedSyncFailureSchema,
+ TransactionChargeRequestedSyncSuccessSchema,
+ TransactionRefundRequestedAsyncSchema,
+ TransactionRefundRequestedSyncFailureSchema,
+ TransactionRefundRequestedSyncSuccessSchema,
+ TransactionSessionActionRequiredSchema,
+ TransactionSessionBaseSchema,
+ TransactionSessionFailureSchema,
+ TransactionSessionSuccessSchema,
)
@@ -31,7 +40,7 @@ def test_transaction_schema_valid_full_data():
}
# when
- transaction = TransactionSchema.model_validate(data)
+ transaction = TransactionBaseSchema.model_validate(data)
# then
assert transaction.psp_reference == data["pspReference"]
@@ -66,7 +75,7 @@ def test_transaction_schema_valid_full_data():
@freeze_time("2023-01-01T12:00:00+00:00")
def test_transaction_schema_valid_only_required_fields(data):
# when
- transaction = TransactionSchema.model_validate(data)
+ transaction = TransactionBaseSchema.model_validate(data)
# then
assert transaction.psp_reference is None
@@ -91,7 +100,7 @@ def test_transaction_schema_with_various_amount_types(amount):
}
# when
- transaction = TransactionSchema.model_validate(data)
+ transaction = TransactionBaseSchema.model_validate(data)
# then
assert transaction.amount == Decimal(str(amount))
@@ -128,7 +137,7 @@ def test_transaction_schema_time_valid(time, expected_datetime):
}
# when
- transaction = TransactionSchema.model_validate(data)
+ transaction = TransactionBaseSchema.model_validate(data)
# then
assert transaction.time == expected_datetime
@@ -182,7 +191,7 @@ def test_transaction_schema_actions_validation(actions, expected_actions):
}
# when
- transaction = TransactionSchema.model_validate(data)
+ transaction = TransactionBaseSchema.model_validate(data)
# then
assert transaction.actions == expected_actions
@@ -224,59 +233,196 @@ def test_transaction_schema_actions_validation(actions, expected_actions):
def test_transaction_schema_invalid(data, invalid_field):
# when
with pytest.raises(ValidationError) as exc_info:
- TransactionSchema.model_validate(data)
+ TransactionBaseSchema.model_validate(data)
# then
assert len(exc_info.value.errors()) == 1
assert exc_info.value.errors()[0]["loc"] == (invalid_field,)
+def test_transaction_charge_requested_sync_success_schema_valid():
+ # given
+ result = TransactionEventType.CHARGE_SUCCESS
+ 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 = TransactionChargeRequestedSyncSuccessSchema.model_validate(data)
+
+ # then
+ assert transaction.result == result
+
+
@pytest.mark.parametrize(
"result",
[
- TransactionEventType.AUTHORIZATION_SUCCESS,
- TransactionEventType.CHARGE_SUCCESS,
TransactionEventType.CANCEL_SUCCESS,
TransactionEventType.REFUND_SUCCESS,
- TransactionEventType.CHARGE_BACK,
- TransactionEventType.REFUND_REVERSE,
+ TransactionEventType.CANCEL_FAILURE,
+ TransactionEventType.REFUND_FAILURE,
],
)
-def test_transaction_schema_time_missing_psp_reference(result):
+def test_transaction_charge_requested_sync_success_schema_invalid(result):
# given
data = {
- "amount": Decimal("100.00"),
+ "pspReference": "psp-123",
+ "amount": Decimal("100.50"),
+ "result": result.upper(),
+ }
+
+ # when
+ with pytest.raises(ValidationError) as exc_info:
+ TransactionChargeRequestedSyncSuccessSchema.model_validate(data)
+ assert len(exc_info.value.errors()) == 1
+
+ # then
+ assert exc_info.value.errors()[0]["loc"] == ("result",)
+
+
+def test_transaction_charge_requested_sync_failure_schema_valid():
+ # given
+ result = TransactionEventType.CHARGE_FAILURE
+ data = {
+ "pspReference": "psp-123",
+ "amount": Decimal("100.50"),
+ "time": "2023-01-01T12:00:00+00:00",
+ "externalUrl": "https://example.com/",
+ "message": "Transaction failed.",
+ "actions": [TransactionAction.CHARGE.upper(), TransactionAction.REFUND.upper()],
+ "result": result.upper(),
+ }
+
+ # when
+ transaction = TransactionChargeRequestedSyncFailureSchema.model_validate(data)
+
+ # then
+ assert transaction.result == result
+
+
+ "result",
+ [
+ TransactionEventType.CANCEL_SUCCESS,
+ TransactionEventType.REFUND_SUCCESS,
+ TransactionEventType.CANCEL_FAILURE,
+ TransactionEventType.REFUND_FAILURE,
+ ],
+)
+def test_transaction_charge_requested_sync_failure_schema_invalid(result):
+ # given
+ data = {
+ "pspReference": "psp-123",
+ "amount": Decimal("100.50"),
"result": result.upper(),
}
- # when/then
+ # when
with pytest.raises(ValidationError) as exc_info:
- TransactionSchema.model_validate(data)
+ TransactionChargeRequestedSyncFailureSchema.model_validate(data)
+ # then
assert len(exc_info.value.errors()) == 1
+ assert exc_info.value.errors()[0]["loc"] == ("result",)
+
+
+def test_transaction_charge_requested_async_schema_valid():
+ # given
+ data = {
+ "pspReference": "psp-async-123",
+ "actions": [TransactionAction.CHARGE.upper()],
+ }
+
+ # when
+ transaction = TransactionChargeRequestedAsyncSchema.model_validate(data)
+
+ # then
+ assert transaction.psp_reference == "psp-async-123"
+
+
+def test_transaction_charge_requested_async_schema_invalid():
+ # given
+ data = {
+ "pspReference": 123,
+ "actions": [TransactionAction.CHARGE.upper()],
+ }
+
+ # when
+ with pytest.raises(ValidationError) as exc_info:
+ TransactionChargeRequestedAsyncSchema.model_validate(data)
+
+ # then
+ assert len(exc_info.value.errors()) == 1
+ assert exc_info.value.errors()[0]["loc"] == ("pspReference",)
+
+
+def test_transaction_cancel_requested_sync_success_schema_valid():
+ # given
+ result = TransactionEventType.CANCEL_SUCCESS
+ data = {
+ "pspReference": "psp-123",
+ "amount": Decimal("100.50"),
+ "time": "2023-01-01T12:00:00+00:00",
+ "externalUrl": "https://example.com/",
+ "message": "Transaction cancelled successfully.",
+ "actions": [TransactionAction.CANCEL.upper(), TransactionAction.REFUND.upper()],
+ "result": result.upper(),
+ }
+
+ # when
+ transaction = TransactionCancelRequestedSyncSuccessSchema.model_validate(data)
+
+ # then
+ assert transaction.result == result
@pytest.mark.parametrize(
"result",
[
TransactionEventType.CHARGE_SUCCESS,
+ TransactionEventType.REFUND_SUCCESS,
TransactionEventType.CHARGE_FAILURE,
+ TransactionEventType.REFUND_FAILURE,
],
)
-def test_transaction_charge_requested_schema_valid(result):
+def test_transaction_cancel_requested_sync_success_schema_invalid(result):
# given
+ data = {
+ "pspReference": "psp-123",
+ "amount": Decimal("100.50"),
+ "result": result.upper(),
+ }
+
+ # when
+ with pytest.raises(ValidationError) as exc_info:
+ TransactionCancelRequestedSyncSuccessSchema.model_validate(data)
+
+ # then
+ assert len(exc_info.value.errors()) == 1
+ assert exc_info.value.errors()[0]["loc"] == ("result",)
+
+
+def test_transaction_cancel_requested_sync_failure_schema_valid():
+ # given
+ result = TransactionEventType.CANCEL_FAILURE
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()],
+ "message": "Transaction cancel failed.",
+ "actions": [TransactionAction.CANCEL.upper(), TransactionAction.REFUND.upper()],
"result": result.upper(),
}
# when
- transaction = TransactionChargeRequestedSchema.model_validate(data)
+ transaction = TransactionCancelRequestedSyncFailureSchema.model_validate(data)
# then
assert transaction.result == result
@@ -285,54 +431,120 @@ def test_transaction_charge_requested_schema_valid(result):
@pytest.mark.parametrize(
"result",
[
- TransactionEventType.CANCEL_FAILURE,
- TransactionEventType.REFUND_FAILURE,
- TransactionEventType.CANCEL_SUCCESS,
+ TransactionEventType.CHARGE_SUCCESS,
TransactionEventType.REFUND_SUCCESS,
+ TransactionEventType.CHARGE_FAILURE,
+ TransactionEventType.REFUND_FAILURE,
],
)
-def test_transaction_charge_requested_schema_invalid(result):
+def test_transaction_cancel_requested_sync_failure_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)
+ TransactionCancelRequestedSyncFailureSchema.model_validate(data)
# then
assert len(exc_info.value.errors()) == 1
assert exc_info.value.errors()[0]["loc"] == ("result",)
+def test_transaction_cancel_requested_async_schema_valid():
+ # given
+ data = {
+ "pspReference": "psp-async-123",
+ "actions": [TransactionAction.CANCEL.upper()],
+ }
+
+ # when
+ transaction = TransactionCancelRequestedAsyncSchema.model_validate(data)
+
+ # then
+ assert transaction.psp_reference == "psp-async-123"
+
+
+def test_transaction_cancel_requested_async_schema_invalid():
+ # given
+ data = {
+ "pspReference": 123,
+ "actions": [TransactionAction.CANCEL.upper()],
+ }
+
+ # when
+ with pytest.raises(ValidationError) as exc_info:
+ TransactionCancelRequestedAsyncSchema.model_validate(data)
+
+ # then
+ assert len(exc_info.value.errors()) == 1
+ assert exc_info.value.errors()[0]["loc"] == ("pspReference",)
+
+
+def test_transaction_refund_requested_sync_success_schema_valid():
+ # given
+ result = TransactionEventType.REFUND_SUCCESS
+ data = {
+ "pspReference": "psp-123",
+ "amount": Decimal("100.50"),
+ "time": "2023-01-01T12:00:00+00:00",
+ "externalUrl": "https://example.com/",
+ "message": "Transaction refunded successfully.",
+ "actions": [TransactionAction.REFUND.upper(), TransactionAction.CHARGE.upper()],
+ "result": result.upper(),
+ }
+
+ # when
+ transaction = TransactionRefundRequestedSyncSuccessSchema.model_validate(data)
+
+ # then
+ assert transaction.result == result
+
+
@pytest.mark.parametrize(
"result",
[
+ TransactionEventType.CHARGE_SUCCESS,
TransactionEventType.CANCEL_SUCCESS,
+ TransactionEventType.CHARGE_FAILURE,
TransactionEventType.CANCEL_FAILURE,
],
)
-def test_transaction_cancel_requested_schema_valid(result):
+def test_transaction_refund_requested_sync_success_schema_invalid(result):
+ # given
+ data = {
+ "pspReference": "psp-123",
+ "amount": Decimal("100.50"),
+ "result": result.upper(),
+ }
+
+ # when
+ with pytest.raises(ValidationError) as exc_info:
+ TransactionRefundRequestedSyncSuccessSchema.model_validate(data)
+
+ # then
+ assert len(exc_info.value.errors()) == 1
+ assert exc_info.value.errors()[0]["loc"] == ("result",)
+
+
+def test_transaction_refund_requested_sync_failure_schema_valid():
# given
+ result = TransactionEventType.REFUND_FAILURE
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()],
+ "message": "Transaction refund failed.",
+ "actions": [TransactionAction.REFUND.upper(), TransactionAction.CHARGE.upper()],
"result": result.upper(),
}
# when
- transaction = TransactionCancelRequestedSchema.model_validate(data)
+ transaction = TransactionRefundRequestedSyncFailureSchema.model_validate(data)
# then
assert transaction.result == result
@@ -341,54 +553,77 @@ def test_transaction_cancel_requested_schema_valid(result):
@pytest.mark.parametrize(
"result",
[
- TransactionEventType.CHARGE_FAILURE,
- TransactionEventType.REFUND_FAILURE,
TransactionEventType.CHARGE_SUCCESS,
- TransactionEventType.REFUND_SUCCESS,
+ TransactionEventType.CANCEL_SUCCESS,
+ TransactionEventType.CHARGE_FAILURE,
+ TransactionEventType.CANCEL_FAILURE,
],
)
-def test_transaction_cancel_requested_schema_invalid(result):
+def test_transaction_refund_requested_sync_failure_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)
+ TransactionRefundRequestedSyncFailureSchema.model_validate(data)
# then
assert len(exc_info.value.errors()) == 1
assert exc_info.value.errors()[0]["loc"] == ("result",)
+def test_transaction_refund_requested_async_schema_valid():
+ # given
+ data = {
+ "pspReference": "psp-async-123",
+ "actions": [TransactionAction.REFUND.upper()],
+ }
+
+ # when
+ transaction = TransactionRefundRequestedAsyncSchema.model_validate(data)
+
+ # then
+ assert transaction.psp_reference == "psp-async-123"
+
+
+def test_transaction_refund_requested_async_schema_invalid():
+ # given
+ data = {
+ "pspReference": 123,
+ "actions": [TransactionAction.REFUND.upper()],
+ }
+
+ # when
+ with pytest.raises(ValidationError) as exc_info:
+ TransactionRefundRequestedAsyncSchema.model_validate(data)
+
+ # then
+ assert len(exc_info.value.errors()) == 1
+ assert exc_info.value.errors()[0]["loc"] == ("pspReference",)
+
+
@pytest.mark.parametrize(
"result",
[
- TransactionEventType.REFUND_SUCCESS,
- TransactionEventType.REFUND_FAILURE,
+ TransactionEventType.AUTHORIZATION_ACTION_REQUIRED,
+ TransactionEventType.CHARGE_ACTION_REQUIRED,
],
)
-def test_transaction_refund_requested_schema_valid(result):
+def test_transaction_session_action_required_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 = TransactionRefundRequestedSchema.model_validate(data)
+ transaction = TransactionSessionActionRequiredSchema.model_validate(data)
# then
assert transaction.result == result
@@ -397,27 +632,28 @@ def test_transaction_refund_requested_schema_valid(result):
@pytest.mark.parametrize(
"result",
[
- TransactionEventType.CHARGE_FAILURE,
- TransactionEventType.CANCEL_FAILURE,
+ TransactionEventType.AUTHORIZATION_SUCCESS,
TransactionEventType.CHARGE_SUCCESS,
+ TransactionEventType.AUTHORIZATION_FAILURE,
+ TransactionEventType.CHARGE_FAILURE,
+ TransactionEventType.AUTHORIZATION_REQUEST,
+ TransactionEventType.CHARGE_REQUEST,
+ TransactionEventType.REFUND_SUCCESS,
TransactionEventType.CANCEL_SUCCESS,
],
)
-def test_transaction_refund_requested_schema_invalid(result):
+def test_transaction_session_action_required_schema_invalid_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
with pytest.raises(ValidationError) as exc_info:
- TransactionRefundRequestedSchema.model_validate(data)
+ TransactionSessionActionRequiredSchema.model_validate(data)
# then
assert len(exc_info.value.errors()) == 1
@@ -428,30 +664,74 @@ def test_transaction_refund_requested_schema_invalid(result):
"result",
[
TransactionEventType.AUTHORIZATION_SUCCESS,
- TransactionEventType.AUTHORIZATION_FAILURE,
- TransactionEventType.AUTHORIZATION_ACTION_REQUIRED,
- TransactionEventType.AUTHORIZATION_REQUEST,
TransactionEventType.CHARGE_SUCCESS,
+ TransactionEventType.AUTHORIZATION_REQUEST,
+ TransactionEventType.CHARGE_REQUEST,
+ ],
+)
+def test_transaction_session_success_schema_valid_result(result):
+ # given
+ data = {
+ "pspReference": "psp-123",
+ "amount": Decimal("100.50"),
+ "result": result.upper(),
+ "data": "test-data",
+ }
+
+ # when
+ transaction = TransactionSessionSuccessSchema.model_validate(data)
+
+ # then
+ assert transaction.result == result
+
+
+ "result",
+ [
+ TransactionEventType.AUTHORIZATION_FAILURE,
TransactionEventType.CHARGE_FAILURE,
+ TransactionEventType.AUTHORIZATION_ACTION_REQUIRED,
TransactionEventType.CHARGE_ACTION_REQUIRED,
- TransactionEventType.CHARGE_REQUEST,
+ TransactionEventType.REFUND_SUCCESS,
+ TransactionEventType.CANCEL_SUCCESS,
],
)
-def test_transaction_session_schema_valid_result(result):
+def test_transaction_session_success_schema_invalid_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)
+ with pytest.raises(ValidationError) as exc_info:
+ TransactionSessionSuccessSchema.model_validate(data)
+
+ # then
+ assert len(exc_info.value.errors()) == 1
+ assert exc_info.value.errors()[0]["loc"] == ("result",)
+
+
+ "result",
+ [
+ TransactionEventType.AUTHORIZATION_FAILURE,
+ TransactionEventType.CHARGE_FAILURE,
+ ],
+)
+def test_transaction_session_failure_schema_valid_result(result):
+ # given
+ data = {
+ "pspReference": "psp-123",
+ "amount": Decimal("100.50"),
+ "result": result.upper(),
+ "data": "test-data",
+ }
+
+ # when
+ transaction = TransactionSessionFailureSchema.model_validate(data)
# then
assert transaction.result == result
@@ -460,23 +740,28 @@ def test_transaction_session_schema_valid_result(result):
@pytest.mark.parametrize(
"result",
[
- TransactionEventType.REFUND_FAILURE,
- TransactionEventType.CANCEL_FAILURE,
+ TransactionEventType.AUTHORIZATION_SUCCESS,
+ TransactionEventType.CHARGE_SUCCESS,
+ TransactionEventType.AUTHORIZATION_ACTION_REQUIRED,
+ TransactionEventType.CHARGE_ACTION_REQUIRED,
+ TransactionEventType.AUTHORIZATION_REQUEST,
+ TransactionEventType.CHARGE_REQUEST,
TransactionEventType.REFUND_SUCCESS,
TransactionEventType.CANCEL_SUCCESS,
],
)
-def test_transaction_session_schema_invalid_result(result):
+def test_transaction_session_failure_schema_invalid_result(result):
# given
data = {
"pspReference": "psp-123",
"amount": Decimal("100.50"),
"result": result.upper(),
+ "data": "test-data",
}
# when
with pytest.raises(ValidationError) as exc_info:
- TransactionSessionSchema.model_validate(data)
+ TransactionSessionFailureSchema.model_validate(data)
# then
assert len(exc_info.value.errors()) == 1
@@ -504,7 +789,7 @@ def test_transaction_session_schema_invalid_result(result):
123,
],
)
-def test_transaction_session_schema_valid_data(data_value):
+def test_transaction_session_base_schema_valid_data(data_value):
# given
data = {
"pspReference": "psp-123",
@@ -514,7 +799,7 @@ def test_transaction_session_schema_valid_data(data_value):
}
# when
- transaction = TransactionSessionSchema.model_validate(data)
+ transaction = TransactionSessionBaseSchema.model_validate(data)
# then
assert transaction.data == data_value
@@ -533,7 +818,7 @@ def test_transaction_session_schema_valid_data(data_value):
open,
],
)
-def test_transaction_session_schema_invalid_data(data_value):
+def test_transaction_session_base_schema_invalid_data(data_value):
# given
data = {
"pspReference": "psp-123",
@@ -544,7 +829,7 @@ def test_transaction_session_schema_invalid_data(data_value):
# when
with pytest.raises(ValidationError) as exc_info:
- TransactionSessionSchema.model_validate(data)
+ TransactionSessionBaseSchema.model_validate(data)
# then
assert len(exc_info.value.errors()) == 1