Skip to content

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

Use dataclasses as a structure for payment's gateways

Maciej Korycinskie7227954dfc1
diff --git a/Pipfile b/Pipfile
index e22cc2698a..fae6afc168 100644
--- a/Pipfile
+++ b/Pipfile
@@ -65,6 +65,7 @@ braintree = "==3.49.0"
razorpay = ">=1.1.1"
stripe = "*"
"urllib3" = "*"
+"dataclasses" = {version = "*", markers="python_version < '3.7'"}
[dev-packages]
pytest = "*"
diff --git a/Pipfile.lock b/Pipfile.lock
index b9768e02ea..0f6c080d54 100644
--- a/Pipfile.lock
+++ b/Pipfile.lock
@@ -1,7 +1,7 @@
{
"_meta": {
"hash": {
- "sha256": "ceaf3fccfc09a4e0b71b2559370f7c12857514544bb35a400d12107a3844166b"
+ "sha256": "50a5689e542d5e8910e729d9685b2a2e485c2adbec9adf2692772a9aaa6b4b01"
},
"pipfile-spec": 6,
"requires": {
@@ -159,6 +159,15 @@
],
"version": "==0.2.1"
},
+ "dataclasses": {
+ "hashes": [
+ "sha256:454a69d788c7fda44efd71e259be79577822f5e3f53f029a22d08004e951dc9f",
+ "sha256:6988bd2b895eef432d562370bb707d540f32f7360ab13da45340101bc2307d84"
+ ],
+ "index": "pypi",
+ "markers": "python_version < '3.7'",
+ "version": "==0.6"
+ },
"defusedxml": {
"hashes": [
"sha256:6687150770438374ab581bb7a1b327a847dd9c5749e396102de3fad4e8a3ef93",
diff --git a/requirements.txt b/requirements.txt
index 98e6fddf37..88ba15cd0a 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -15,6 +15,7 @@ certifi==2019.3.9
cffi==1.12.3
chardet==3.0.4
cssselect2==0.2.1
+dataclasses==0.6 ; python_version < '3.7'
defusedxml==0.6.0 ; python_version >= '3.0'
dj-database-url==0.5.0
dj-email-url==0.2.0
diff --git a/saleor/payment/gateway_dataclasses.py b/saleor/payment/gateway_dataclasses.py
new file mode 100644
index 0000000000..35f455fa9c
--- /dev/null
+++ b/saleor/payment/gateway_dataclasses.py
@@ -0,0 +1,16 @@
+from dataclasses import dataclass
+from decimal import Decimal
+from typing import Dict, Optional
+
+
+@dataclass
+class GatewayResponse:
+ """Dataclass for storing gateway response"""
+
+ is_success: bool
+ kind: str
+ amount: Decimal
+ currency: str
+ transaction_id: str
+ error: Optional[str]
+ raw_response: Optional[Dict[str, str]] = None
diff --git a/saleor/payment/gateways/braintree/__init__.py b/saleor/payment/gateways/braintree/__init__.py
index ae01e0e5d4..569d630031 100644
--- a/saleor/payment/gateways/braintree/__init__.py
+++ b/saleor/payment/gateways/braintree/__init__.py
@@ -5,6 +5,7 @@ import braintree as braintree_sdk
from django.core.exceptions import ImproperlyConfigured
from django.utils.translation import pgettext_lazy
+from ...gateway_dataclasses import GatewayResponse
from .errors import DEFAULT_ERROR_MESSAGE, BraintreeException
from .forms import BraintreePaymentForm
@@ -119,7 +120,8 @@ def get_client_token(connection_params: Dict) -> str:
return client_token
-def authorize(payment_information: Dict, connection_params: Dict) -> Dict:
+def authorize(
+ payment_information: Dict, connection_params: Dict) -> GatewayResponse:
gateway = get_braintree_gateway(**connection_params)
try:
@@ -136,21 +138,22 @@ def authorize(payment_information: Dict, connection_params: Dict) -> Dict:
gateway_response = extract_gateway_response(result)
error = get_error_for_client(gateway_response['errors'])
-
- return {
- 'is_success': result.is_success,
- 'kind': TransactionKind.AUTH,
- 'amount': gateway_response.get(
+ return GatewayResponse(
+ is_success=result.is_success,
+ kind=TransactionKind.AUTH,
+ amount=gateway_response.get(
'amount', payment_information['amount']),
- 'currency': gateway_response.get(
+ currency=gateway_response.get(
'currency', payment_information['currency']),
- 'transaction_id': gateway_response.get(
+ transaction_id=gateway_response.get(
'transaction_id', payment_information['token']),
- 'error': error,
- 'raw_response': gateway_response}
+ error=error,
+ raw_response=gateway_response
+ )
-def capture(payment_information: Dict, connection_params: Dict) -> Dict:
+def capture(
+ payment_information: Dict, connection_params: Dict) -> GatewayResponse:
gateway = get_braintree_gateway(**connection_params)
try:
@@ -163,20 +166,22 @@ def capture(payment_information: Dict, connection_params: Dict) -> Dict:
gateway_response = extract_gateway_response(result)
error = get_error_for_client(gateway_response['errors'])
- return {
- 'is_success': result.is_success,
- 'kind': TransactionKind.CAPTURE,
- 'amount': gateway_response.get(
+ return GatewayResponse(
+ is_success=result.is_success,
+ kind=TransactionKind.CAPTURE,
+ amount=gateway_response.get(
'amount', payment_information['amount']),
- 'currency': gateway_response.get(
+ currency=gateway_response.get(
'currency', payment_information['currency']),
- 'transaction_id': gateway_response.get(
+ transaction_id=gateway_response.get(
'transaction_id', payment_information['token']),
- 'error': error,
- 'raw_response': gateway_response}
+ error=error,
+ raw_response=gateway_response
+ )
-def void(payment_information: Dict, connection_params: Dict) -> Dict:
+def void(
+ payment_information: Dict, connection_params: Dict) -> GatewayResponse:
gateway = get_braintree_gateway(**connection_params)
try:
@@ -188,20 +193,22 @@ def void(payment_information: Dict, connection_params: Dict) -> Dict:
gateway_response = extract_gateway_response(result)
error = get_error_for_client(gateway_response['errors'])
- return {
- 'is_success': result.is_success,
- 'kind': TransactionKind.VOID,
- 'amount': gateway_response.get(
+ return GatewayResponse(
+ is_success=result.is_success,
+ kind=TransactionKind.VOID,
+ amount=gateway_response.get(
'amount', payment_information['amount']),
- 'currency': gateway_response.get(
+ currency=gateway_response.get(
'currency', payment_information['currency']),
- 'transaction_id': gateway_response.get(
+ transaction_id=gateway_response.get(
'transaction_id', payment_information['token']),
- 'error': error,
- 'raw_response': gateway_response}
+ error=error,
+ raw_response=gateway_response
+ )
-def refund(payment_information: Dict, connection_params: Dict) -> Dict:
+def refund(
+ payment_information: Dict, connection_params: Dict) -> GatewayResponse:
gateway = get_braintree_gateway(**connection_params)
try:
@@ -214,23 +221,26 @@ def refund(payment_information: Dict, connection_params: Dict) -> Dict:
gateway_response = extract_gateway_response(result)
error = get_error_for_client(gateway_response['errors'])
- return {
- 'is_success': result.is_success,
- 'kind': TransactionKind.REFUND,
- 'amount': gateway_response.get(
+ return GatewayResponse(
+ is_success=result.is_success,
+ kind=TransactionKind.REFUND,
+ amount=gateway_response.get(
'amount', payment_information['amount']),
- 'currency': gateway_response.get(
+ currency=gateway_response.get(
'currency', payment_information['currency']),
- 'transaction_id': gateway_response.get(
+ transaction_id=gateway_response.get(
'transaction_id', payment_information['token']),
- 'error': error,
- 'raw_response': gateway_response}
+ error=error,
+ raw_response=gateway_response
+
+ )
def process_payment(
- payment_information: Dict, connection_params: Dict) -> Dict:
+ payment_information: Dict, connection_params: Dict) -> GatewayResponse:
auth_resp = authorize(payment_information, connection_params)
- if auth_resp['is_success']:
- payment_information['token'] = auth_resp['transaction_id']
- return [auth_resp, capture(payment_information, connection_params)]
- return [auth_resp, void(payment_information, connection_params)]
+ if auth_resp.is_success:
+ print("SUKCESSS")
+ payment_information['token'] = auth_resp.transaction_id
+ return capture(payment_information, connection_params)
+ return auth_resp
diff --git a/saleor/payment/gateways/dummy/__init__.py b/saleor/payment/gateways/dummy/__init__.py
index d5987c35e4..e8bdd187c9 100644
--- a/saleor/payment/gateways/dummy/__init__.py
+++ b/saleor/payment/gateways/dummy/__init__.py
@@ -1,7 +1,8 @@
import uuid
-from typing import Dict
+from typing import Dict, List
from ... import ChargeStatus
+from ...gateway_dataclasses import GatewayResponse
from .forms import DummyPaymentForm
TEMPLATE_PATH = 'order/payment/dummy.html'
@@ -27,71 +28,83 @@ def create_form(data, payment_information, connection_params):
return DummyPaymentForm(data=data)
-def authorize(payment_information: Dict, connection_params) -> Dict:
+def authorize(
+ payment_information: Dict, connection_params) -> GatewayResponse:
success = dummy_success()
error = None
if not success:
error = 'Unable to authorize transaction'
- return {
- 'is_success': success,
- 'kind': TransactionKind.AUTH,
- 'amount': payment_information['amount'],
- 'currency': payment_information['currency'],
- 'transaction_id': payment_information['token'],
- 'error': error}
-
-
-def void(payment_information: Dict, connection_params) -> Dict:
+ return GatewayResponse(
+ is_success=success,
+ kind=TransactionKind.AUTH,
+ amount=payment_information['amount'],
+ currency=payment_information['currency'],
+ transaction_id=payment_information['token'],
+ error=error
+ )
+
+
+def void(
+ payment_information: Dict, connection_params) -> GatewayResponse:
error = None
success = dummy_success()
if not success:
error = 'Unable to void the transaction.'
- return {
- 'is_success': success,
- 'kind': TransactionKind.VOID,
- 'amount': payment_information['amount'],
- 'currency': payment_information['currency'],
- 'transaction_id': payment_information['token'],
- 'error': error}
-
-
-def capture(payment_information: Dict, connection_params: Dict) -> Dict:
+ return GatewayResponse(
+ is_success=success,
+ kind=TransactionKind.VOID,
+ amount=payment_information['amount'],
+ currency=payment_information['currency'],
+ transaction_id=payment_information['token'],
+ error=error
+ )
+
+
+def capture(
+ payment_information: Dict, connection_params: Dict
+) -> GatewayResponse:
error = None
success = dummy_success()
if not success:
error = 'Unable to process capture'
- return {
- 'is_success': success,
- 'kind': TransactionKind.CAPTURE,
- 'amount': payment_information['amount'],
- 'currency': payment_information['currency'],
- 'transaction_id': payment_information['token'],
- 'error': error}
+ return GatewayResponse(
+ is_success=success,
+ kind=TransactionKind.CAPTURE,
+ amount=payment_information['amount'],
+ currency=payment_information['currency'],
+ transaction_id=payment_information['token'],
+ error=error
+ )
-def refund(payment_information: Dict, connection_params: Dict):
+
+def refund(
+ payment_information: Dict, connection_params: Dict) -> GatewayResponse:
error = None
success = dummy_success()
if not success:
error = 'Unable to process refund'
- return {
- 'is_success': success,
- 'kind': TransactionKind.REFUND,
- 'amount': payment_information['amount'],
- 'currency': payment_information['currency'],
- 'transaction_id': payment_information['token'],
- 'error': error}
-
-
-def charge(payment_information: Dict, connection_params):
+ return GatewayResponse(
+ is_success=success,
+ kind=TransactionKind.REFUND,
+ amount=payment_information['amount'],
+ currency=payment_information['currency'],
+ transaction_id=payment_information['token'],
+ error=error
+ )
+
+
+def charge(
+ payment_information: Dict, connection_params) -> GatewayResponse:
"""Performs Authorize and Capture transactions in a single run."""
auth_resp = authorize(payment_information, connection_params)
- if not auth_resp['is_success']:
+ if not auth_resp.is_success:
return auth_resp
- return [auth_resp, capture(payment_information, connection_params)]
+ return capture(payment_information, connection_params)
-def process_payment(payment_information: Dict, connection_params) -> Dict:
+def process_payment(
+ payment_information: Dict, connection_params) -> GatewayResponse:
"""Process the payment."""
token = payment_information.get('token')
@@ -102,11 +115,11 @@ def process_payment(payment_information: Dict, connection_params) -> Dict:
# Process payment by charge status which is selected in the payment form
# Note that is for testing by dummy gateway only
charge_status = token
- responses = [authorize(payment_information, connection_params)]
+ authorize_response = authorize(payment_information, connection_params)
if charge_status == ChargeStatus.NOT_CHARGED:
- return responses
+ return authorize_response
- responses.append(capture(payment_information, connection_params))
+ capture_response = capture(payment_information, connection_params)
if charge_status == ChargeStatus.FULLY_REFUNDED:
- responses.append(refund(payment_information, connection_params))
- return responses
+ return refund(payment_information, connection_params)
+ return capture_response
diff --git a/saleor/payment/gateways/razorpay/__init__.py b/saleor/payment/gateways/razorpay/__init__.py
index b156ff5030..098713e188 100644
--- a/saleor/payment/gateways/razorpay/__init__.py
+++ b/saleor/payment/gateways/razorpay/__init__.py
@@ -1,11 +1,12 @@
import logging
import uuid
from decimal import Decimal
-from typing import Dict
+from typing import Dict, List
import razorpay
import razorpay.errors
+from ...gateway_dataclasses import GatewayResponse
from . import errors
from .forms import RazorPaymentForm
from .utils import get_amount_for_razorpay, get_error_response
@@ -36,17 +37,18 @@ class TransactionKind:
def _generate_response(
- payment_information: Dict, kind: str, data: Dict) -> Dict:
+ payment_information: Dict, kind: str, data: Dict) -> GatewayResponse:
"""Generate Saleor transaction information from
Razorpay's success payload or from passed data."""
- return {
- 'transaction_id': data.get('id', payment_information['token']),
- 'kind': kind,
- 'amount': data.get('amount', payment_information['amount']),
- 'currency': data.get('currency', payment_information['currency']),
- 'error': data.get('error', None),
- 'is_success': data.get('is_success', True),
- 'raw_response': data}
+ return GatewayResponse(
+ transaction_id=data.get('id', payment_information['token']),
+ kind=kind,
+ amount=data.get('amount', payment_information['amount']),
+ currency=data.get('currency', payment_information['currency']),
+ error=data.get('error'),
+ is_success=data.get('is_success', True),
+ raw_response=data
+ )
def check_payment_supported(payment_information: Dict):
@@ -91,7 +93,8 @@ def get_client_token(**_):
return str(uuid.uuid4())
-def charge(payment_information: Dict, connection_params: Dict) -> Dict:
+def charge(
+ payment_information: Dict, connection_params: Dict) -> GatewayResponse:
"""Charge a authorized payment using the razorpay client.
But it first check if the given payment instance is supported
@@ -125,7 +128,8 @@ def charge(payment_information: Dict, connection_params: Dict) -> Dict:
kind=TransactionKind.CHARGE, data=response)
-def refund(payment_information: Dict, connection_params) -> Dict:
+def refund(
+ payment_information: Dict, connection_params) -> GatewayResponse:
"""Refund a payment using the razorpay client.
But it first check if the given payment instance is supported
@@ -158,7 +162,8 @@ def refund(payment_information: Dict, connection_params) -> Dict:
kind=TransactionKind.REFUND, data=response)
-def process_payment(payment_information: Dict, connection_params) -> Dict:
+def process_payment(
+ payment_information: Dict, connection_params) -> GatewayResponse:
return charge(
payment_information=payment_information,
connection_params=connection_params)
diff --git a/saleor/payment/gateways/stripe/__init__.py b/saleor/payment/gateways/stripe/__init__.py
index f100c416e5..3394285958 100644
--- a/saleor/payment/gateways/stripe/__init__.py
+++ b/saleor/payment/gateways/stripe/__init__.py
@@ -2,6 +2,7 @@ from typing import Dict
import stripe
+from ...gateway_dataclasses import GatewayResponse
from .forms import StripePaymentModalForm
from .utils import (
get_amount_for_stripe, get_amount_from_stripe, get_currency_for_stripe,
@@ -26,7 +27,7 @@ def get_client_token(**_):
return
-def authorize(payment_information, connection_params):
+def authorize(payment_information, connection_params) -> GatewayResponse:
client, error = _get_client(**connection_params), None
try:
@@ -44,7 +45,7 @@ def authorize(payment_information, connection_params):
kind=TransactionKind.AUTH, response=response, error=error)
-def capture(payment_information, connection_params):
+def capture(payment_information, connection_params) -> GatewayResponse:
client, error = _get_client(**connection_params), None
# Get amount from argument or payment, and convert to stripe's amount
@@ -66,7 +67,7 @@ def capture(payment_information, connection_params):
kind=TransactionKind.CAPTURE, response=response, error=error)
-def charge(payment_information, connection_params):
+def charge(payment_information, connection_params) -> GatewayResponse:
client, error = _get_client(**connection_params), None
try:
@@ -84,7 +85,7 @@ def charge(payment_information, connection_params):
kind=TransactionKind.CHARGE, response=response, error=error)
-def refund(payment_information, connection_params):
+def refund(payment_information, connection_params) -> GatewayResponse:
client, error = _get_client(**connection_params), None
# Get amount from payment, and convert to stripe's amount
@@ -107,7 +108,7 @@ def refund(payment_information, connection_params):
kind=TransactionKind.REFUND, response=response, error=error)
-def void(payment_information, connection_params):
+def void(payment_information, connection_params) -> GatewayResponse:
client, error = _get_client(**connection_params), None
try:
@@ -124,7 +125,7 @@ def void(payment_information, connection_params):
kind=TransactionKind.VOID, response=response, error=error)
-def process_payment(payment_information, connection_params):
+def process_payment(payment_information, connection_params) -> GatewayResponse:
return charge(payment_information, connection_params)
@@ -177,7 +178,8 @@ def _create_stripe_charge(client, payment_information, should_capture: bool):
return client.Charge.create(**charge_payload)
-def _create_response(payment_information, kind, response, error):
+def _create_response(
+ payment_information, kind, response, error) -> GatewayResponse:
# Get currency from response or payment
currency = get_currency_from_stripe(
response.get('currency', payment_information['currency']))
@@ -198,15 +200,15 @@ def _create_response(payment_information, kind, response, error):
# Check if the response's status is flagged as succeeded
is_success = (response.get('status') == 'succeeded')
- return {
- 'is_success': is_success,
- 'transaction_id': token,
- 'kind': kind,
- 'amount': amount,
- 'currency': currency,
- 'error': error,
- 'raw_response': response,
- }
+ return GatewayResponse(
+ is_success=is_success,
+ transaction_id=token,
+ kind=kind,
+ amount=amount,
+ currency=currency,
+ error=error,
+ raw_response=response
+ )
def _get_error_response_from_exc(exc):
diff --git a/saleor/payment/utils.py b/saleor/payment/utils.py
index 824bf3bd40..253e1395d6 100644
--- a/saleor/payment/utils.py
+++ b/saleor/payment/utils.py
@@ -1,3 +1,4 @@
+import dataclasses
import json
import logging
from decimal import Decimal
@@ -18,6 +19,7 @@ from ..order.models import Order
from . import (
ChargeStatus, CustomPaymentChoices, GatewayError, OperationType,
PaymentError, TransactionKind, get_payment_gateway)
+from .gateway_dataclasses import GatewayResponse
from .models import Payment, Transaction
logger = logging.getLogger(__name__)
@@ -173,24 +175,34 @@ def mark_order_as_paid(order: Order, request_user: User):
def create_transaction(
payment: Payment, kind: str, payment_information: Dict,
- gateway_response: Dict = None, error_msg=None) -> Transaction:
+ gateway_response: GatewayResponse = None, error_msg=None
+) -> Transaction:
"""Create a transaction based on transaction kind and gateway response."""
- if gateway_response is None:
- gateway_response = {}
# Default values for token, amount, currency are only used in cases where
# response from gateway was invalid or an exception occured
+ if not gateway_response:
+ gateway_response = GatewayResponse(
+ kind=kind,
+ transaction_id=payment_information['token'],
+ is_success=False,
+ amount=payment_information['amount'],
+ currency=payment_information['currency'],
+ error=error_msg,
+ )
+ gateway_response_dict = {}
+ else:
+ gateway_response_dict = dataclasses.asdict(gateway_response)
+
txn = Transaction.objects.create(
payment=payment,
- kind=gateway_response.get('kind', kind),
- token=gateway_response.get(
- 'transaction_id', payment_information['token']),
- is_success=gateway_response.get('is_success', False),
- amount=gateway_response.get('amount', payment_information['amount']),
- currency=gateway_response.get(
- 'currency', payment_information['currency']),
- error=gateway_response.get('error', error_msg),
- gateway_response=gateway_response)
+ kind=gateway_response.kind,
+ token=gateway_response.transaction_id,
+ is_success=gateway_response.is_success,
+ amount=gateway_response.amount,
+ currency=gateway_response.currency,
+ error=gateway_response.error,
+ gateway_response=gateway_response_dict)
return txn
@@ -288,67 +300,40 @@ def call_gateway(operation_type, payment, payment_token, **extra_params):
error_msg = 'Gateway encountered an error'
logger.exception(error_msg)
finally:
- if not isinstance(gateway_response, list):
- gateway_response = [gateway_response]
- transactions = []
- for response in gateway_response:
- transactions.append(create_transaction(
- payment=payment,
- kind=default_transaction_kind,
- payment_information=payment_information,
- error_msg=error_msg,
- gateway_response=response))
-
- for transaction in transactions:
- if not transaction.is_success:
- # Attempt to get errors from response, if none raise a generic one
- raise PaymentError(transaction.error or GENERIC_TRANSACTION_ERROR)
-
- return transactions[-1]
-
-
-def validate_gateway_response(responses):
+ payment_transaction = create_transaction(
+ payment=payment,
+ kind=default_transaction_kind,
+ payment_information=payment_information,
+ error_msg=error_msg,
+ gateway_response=gateway_response)
+
+ if not payment_transaction.is_success:
+ # Attempt to get errors from response, if none raise a generic one
+ raise PaymentError(
+ payment_transaction.error or GENERIC_TRANSACTION_ERROR)
+
+ return payment_transaction
+
+
+def validate_gateway_response(response: GatewayResponse):
"""Validates response to be a correct format for Saleor to process."""
- if not isinstance(responses, (dict, list)):
- raise GatewayError('Gateway needs to return a dictionary or a list')
-
- if not isinstance(responses, list):
- responses = [responses]
-
- field_types = {
- 'amount': Decimal,
- 'currency': str,
- 'is_success': bool,
- 'kind': str,
- 'transaction_id': str,
- 'error': (type(None), str),
- }
-
- for response in responses:
- if not REQUIRED_GATEWAY_KEYS.issubset(response):
- raise GatewayError(
- 'Gateway response needs to contain following keys: {}'.format(
- sorted(REQUIRED_GATEWAY_KEYS)))
-
- for name, value in response.items():
- if name in field_types:
- if not isinstance(value, field_types[name]):
- raise GatewayError('{} must be of type {}, was {}'.format(
- name, field_types[name], type(value)))
-
- if response['kind'] not in ALLOWED_GATEWAY_KINDS:
- raise GatewayError(
- 'Gateway response kind must be one of {}'.format(
- sorted(ALLOWED_GATEWAY_KINDS)))
-
- if response['currency'] != settings.DEFAULT_CURRENCY:
- logger.warning('Transaction currency is different than Saleor\'s.')
-
- try:
- json.dumps(response, cls=DjangoJSONEncoder)
- except (TypeError, ValueError):
- raise GatewayError(
- 'Gateway response needs to be json serializable')
+
+ if not isinstance(response, GatewayResponse):
+ raise GatewayError('Gateway needs to return a GatewayResponse obj')
+
+ if response.kind not in ALLOWED_GATEWAY_KINDS:
+ raise GatewayError(
+ 'Gateway response kind must be one of {}'.format(
+ sorted(ALLOWED_GATEWAY_KINDS)))
+
+ if response.currency != settings.DEFAULT_CURRENCY:
+ logger.warning('Transaction currency is different than Saleor\'s.')
+
+ try:
+ json.dumps(dataclasses.asdict(response), cls=DjangoJSONEncoder)
+ except (TypeError, ValueError):
+ raise GatewayError(
+ 'Gateway response needs to be json serializable')
def _gateway_postprocess(transaction, payment):
diff --git a/tests/api/test_checkout.py b/tests/api/test_checkout.py
index 00b9c5ceff..c7b2e87091 100644
--- a/tests/api/test_checkout.py
+++ b/tests/api/test_checkout.py
@@ -918,7 +918,7 @@ def test_checkout_complete(
assert order.payments.exists()
order_payment = order.payments.first()
assert order_payment == payment
- assert payment.transactions.count() == 2
+ assert payment.transactions.count() == 1
# assert that the checkout instance has been deleted after checkout
with pytest.raises(Checkout.DoesNotExist):
diff --git a/tests/gateway/test_braintree.py b/tests/gateway/test_braintree.py
index 12dffe4237..1ecbde6e43 100644
--- a/tests/gateway/test_braintree.py
+++ b/tests/gateway/test_braintree.py
@@ -201,11 +201,7 @@ def test_process_payment_error_response(
payment_info = create_payment_information(payment, payment_token)
response = process_payment(payment_info, gateway_config)
- assert isinstance(response, list)
- auth_resp, void_resp = response
-
- assert auth_resp['kind'] == TransactionKind.AUTH
- assert void_resp['kind'] == TransactionKind.VOID
+ assert response.kind == TransactionKind.AUTH
@pytest.mark.integration
@@ -221,11 +217,8 @@ def test_process_payment(
payment_info = create_payment_information(payment, payment_token)
response = process_payment(payment_info, gateway_config)
- assert isinstance(response, list)
- auth_resp, capture_resp = response
+ assert response.kind == TransactionKind.CAPTURE
- assert auth_resp['kind'] == TransactionKind.AUTH
- assert capture_resp['kind'] == TransactionKind.CAPTURE
@pytest.mark.integration
@patch('saleor.payment.gateways.braintree.get_braintree_gateway')
@@ -239,9 +232,9 @@ def test_authorize_error_response(
payment_info = create_payment_information(payment, payment_token)
response = authorize(payment_info, gateway_config)
- assert response['raw_response'] == extract_gateway_response(braintree_error_response)
- assert not response['is_success']
- assert response['error'] == DEFAULT_ERROR
+ assert response.raw_response == extract_gateway_response(braintree_error_response)
+ assert not response.is_success
+ assert response.error == DEFAULT_ERROR
@pytest.mark.integration
@@ -271,13 +264,13 @@ def test_authorize(
payment_info = create_payment_information(payment, 'auth-token')
response = authorize(payment_info, gateway_config)
- assert not response['error']
+ assert not response.error
- assert response['kind'] == TransactionKind.AUTH
- assert response['amount'] == braintree_success_response.transaction.amount
- assert response['currency'] == braintree_success_response.transaction.currency_iso_code
- assert response['transaction_id'] == braintree_success_response.transaction.id
- assert response['is_success'] == braintree_success_response.is_success
+ assert response.kind == TransactionKind.AUTH
+ assert response.amount == braintree_success_response.transaction.amount
+ assert response.currency == braintree_success_response.transaction.currency_iso_code
+ assert response.transaction_id == braintree_success_response.transaction.id
+ assert response.is_success == braintree_success_response.is_success
mock_response.assert_called_once_with({
'amount': str(payment.total),
@@ -293,7 +286,7 @@ def test_authorize(
@patch('saleor.payment.gateways.braintree.get_braintree_gateway')
def test_refund(
mock_gateway, payment_txn_captured, braintree_success_response,
- settings, gateway_config):
+ gateway_config):
payment = payment_txn_captured
amount = Decimal('10.00')
mock_response = Mock(return_value=braintree_success_response)
@@ -301,13 +294,13 @@ def test_refund(
payment_info = create_payment_information(payment, 'token', amount)
response = refund(payment_info, gateway_config)
- assert not response['error']
+ assert not response.error
- assert response['kind'] == TransactionKind.REFUND
- assert response['amount'] == braintree_success_response.transaction.amount
- assert response['currency'] == braintree_success_response.transaction.currency_iso_code
- assert response['transaction_id'] == braintree_success_response.transaction.id
- assert response['is_success'] == braintree_success_response.is_success
+ assert response.kind == TransactionKind.REFUND
+ assert response.amount == braintree_success_response.transaction.amount
+ assert response.currency == braintree_success_response.transaction.currency_iso_code
+ assert response.transaction_id == braintree_success_response.transaction.id
+ assert response.is_success == braintree_success_response.is_success
mock_response.assert_called_once_with(
amount_or_options=str(amount), transaction_id=payment_info['token'])
@@ -342,17 +335,17 @@ def test_refund_error_response(
payment_info = create_payment_information(payment, 'token', amount)
response = refund(payment_info, gateway_config)
- assert response['raw_response'] == extract_gateway_response(
+ assert response.raw_response == extract_gateway_response(
braintree_error_response)
- assert not response['is_success']
- assert response['error'] == DEFAULT_ERROR
+ assert not response.is_success
+ assert response.error == DEFAULT_ERROR
@pytest.mark.integration
@patch('saleor.payment.gateways.braintree.get_braintree_gateway')
def test_capture(
mock_gateway, payment_txn_preauth, braintree_success_response,
- settings, gateway_config):
+ gateway_config):
payment = payment_txn_preauth
amount = Decimal('10.00')
mock_response = Mock(return_value=braintree_success_response)
@@ -361,13 +354,13 @@ def test_capture(
payment_info = create_payment_information(payment, 'token', amount)
response = capture(payment_info, gateway_config)
- assert not response['error']
+ assert not response.error
- assert response['kind'] == TransactionKind.CAPTURE
- assert response['amount'] == braintree_success_response.transaction.amount
- assert response['currency'] == braintree_success_response.transaction.currency_iso_code
- assert response['transaction_id'] == braintree_success_response.transaction.id
- assert response['is_success'] == braintree_success_response.is_success
+ assert response.kind == TransactionKind.CAPTURE
+ assert response.amount == braintree_success_response.transaction.amount
+ assert response.currency == braintree_success_response.transaction.currency_iso_code
+ assert response.transaction_id == braintree_success_response.transaction.id
+ assert response.is_success == braintree_success_response.is_success
mock_response.assert_called_once_with(
amount=str(amount), transaction_id=payment_info['token'])
@@ -379,7 +372,6 @@ def test_capture_incorrect_token(
mock_gateway, payment_txn_preauth, braintree_not_found_error,
gateway_config):
payment = payment_txn_preauth
- amount = Decimal('10.00')
mock_response = Mock(side_effect=braintree_not_found_error)
mock_gateway.return_value = Mock(
transaction=Mock(submit_for_settlement=mock_response))
@@ -396,7 +388,6 @@ def test_capture_error_response(
mock_gateway, payment_txn_preauth, braintree_error_response,
gateway_config):
payment = payment_txn_preauth
- amount = Decimal('10.00')
mock_response = Mock(return_value=braintree_error_response)
mock_gateway.return_value = Mock(
transaction=Mock(submit_for_settlement=mock_response))
@@ -404,10 +395,10 @@ def test_capture_error_response(
payment_info = create_payment_information(payment, 'token')
response = capture(payment_info, gateway_config)
- assert response['raw_response'] == extract_gateway_response(
+ assert response.raw_response == extract_gateway_response(
braintree_error_response)
- assert not response['is_success']
- assert response['error'] == DEFAULT_ERROR
+ assert not response.is_success
+ assert response.error == DEFAULT_ERROR
@pytest.mark.integration
@@ -421,13 +412,13 @@ def test_void(
payment_info = create_payment_information(payment, 'token')
response = void(payment_info, gateway_config)
- assert not response['error']
+ assert not response.error
- assert response['kind'] == TransactionKind.VOID
- assert response['amount'] == braintree_success_response.transaction.amount
- assert response['currency'] == braintree_success_response.transaction.currency_iso_code
- assert response['transaction_id'] == braintree_success_response.transaction.id
- assert response['is_success'] == braintree_success_response.is_success
+ assert response.kind == TransactionKind.VOID
+ assert response.amount == braintree_success_response.transaction.amount
+ assert response.currency == braintree_success_response.transaction.currency_iso_code
+ assert response.transaction_id == braintree_success_response.transaction.id
+ assert response.is_success == braintree_success_response.is_success
mock_response.assert_called_once_with(transaction_id=payment_info['token'])
@@ -446,6 +437,7 @@ def test_void_incorrect_token(
void(payment_info, gateway_config)
assert str(e.value) == DEFAULT_ERROR_MESSAGE
+
@pytest.mark.integration
@patch('saleor.payment.gateways.braintree.get_braintree_gateway')
def test_void_error_response(
@@ -458,10 +450,10 @@ def test_void_error_response(
payment_info = create_payment_information(payment)
response = void(payment_info, gateway_config)
- assert response['raw_response'] == extract_gateway_response(
+ assert response.raw_response == extract_gateway_response(
braintree_error_response)
- assert not response['is_success']
- assert response['error'] == DEFAULT_ERROR
+ assert not response.is_success
+ assert response.error == DEFAULT_ERROR
def test_braintree_payment_form_incorrect_amount(payment_dummy):
diff --git a/tests/gateway/test_razorpay.py b/tests/gateway/test_razorpay.py
index 8fd43dda71..e02c45dfb7 100644
--- a/tests/gateway/test_razorpay.py
+++ b/tests/gateway/test_razorpay.py
@@ -148,14 +148,14 @@ def test_charge(
response = charge(payment_info, gateway_params)
# Ensure the was no error returned
- assert not response['error']
- assert response['is_success']
+ assert not response.error
+ assert response.is_success
- assert response['kind'] == TransactionKind.CHARGE
- assert response['amount'] == TRANSACTION_AMOUNT
- assert response['currency'] == razorpay_success_response['currency']
- assert response['raw_response'] == razorpay_success_response
- assert response['transaction_id'] == razorpay_success_response['id']
+ assert response.kind == TransactionKind.CHARGE
+ assert response.amount == TRANSACTION_AMOUNT
+ assert response.currency == razorpay_success_response['currency']
+ assert response.raw_response == razorpay_success_response
+ assert response.transaction_id == razorpay_success_response['id']
@pytest.mark.integration
@@ -174,13 +174,13 @@ def test_charge_unsupported_currency(razorpay_payment, gateway_params):
response = charge(payment_info, gateway_params)
# Ensure a error was returned
- assert response['error'] == (
+ assert response.error == (
errors.UNSUPPORTED_CURRENCY % {'currency': 'USD'})
- assert not response['is_success']
+ assert not response.is_success
# Ensure the response is correctly set
- assert response['kind'] == TransactionKind.CHARGE
- assert response['transaction_id'] == payment_token
+ assert response.kind == TransactionKind.CHARGE
+ assert response.transaction_id == payment_token
@patch.object(logger, 'exception')
@@ -206,12 +206,12 @@ def test_charge_invalid_request(
response = charge(payment_info, gateway_params)
# Ensure an error was returned
- assert response['error'] == errors.INVALID_REQUEST
- assert not response['is_success']
+ assert response.error == errors.INVALID_REQUEST
+ assert not response.is_success
# Ensure the response is correctly set
- assert response['kind'] == TransactionKind.CHARGE
- assert response['transaction_id'] == payment_token
+ assert response.kind == TransactionKind.CHARGE
+ assert response.transaction_id == payment_token
# Ensure the HTTP error was logged
assert mocked_logger.call_count == 1
@@ -236,14 +236,14 @@ def test_refund(
response = refund(payment_info, gateway_params)
# Ensure the was no error returned
- assert not response['error']
- assert response['is_success']
+ assert not response.error
+ assert response.is_success
- assert response['kind'] == TransactionKind.REFUND
- assert response['amount'] == TRANSACTION_AMOUNT
- assert response['currency'] == razorpay_success_response['currency']
- assert response['raw_response'] == razorpay_success_response
- assert response['transaction_id'] == razorpay_success_response['id']
+ assert response.kind == TransactionKind.REFUND
+ assert response.amount == TRANSACTION_AMOUNT
+ assert response.currency == razorpay_success_response['currency']
+ assert response.raw_response == razorpay_success_response
+ assert response.transaction_id == razorpay_success_response['id']
@pytest.mark.integration
@@ -259,12 +259,12 @@ def test_refund_unsupported_currency(
response = refund(payment_info, gateway_params)
# Ensure a error was returned
- assert response['error'] == (
+ assert response.error == (
errors.UNSUPPORTED_CURRENCY % {'currency': 'USD'})
- assert not response['is_success']
+ assert not response.is_success
# Ensure the kind is correctly set
- assert response['kind'] == TransactionKind.REFUND
+ assert response.kind == TransactionKind.REFUND
@pytest.mark.integration
@@ -287,11 +287,11 @@ def test_refund_invalid_data(
response = refund(payment_info, gateway_params)
# Ensure a error was returned
- assert response['error'] == errors.SERVER_ERROR
- assert not response['is_success']
+ assert response.error == errors.SERVER_ERROR
+ assert not response.is_success
# Ensure the transaction is correctly set
- assert response['kind'] == TransactionKind.REFUND
+ assert response.kind == TransactionKind.REFUND
# Ensure the HTTP error was logged
assert mocked_logger.call_count == 1
diff --git a/tests/gateway/test_stripe.py b/tests/gateway/test_stripe.py
index 2ba03c55f8..d634aa5812 100644
--- a/tests/gateway/test_stripe.py
+++ b/tests/gateway/test_stripe.py
@@ -322,10 +322,10 @@ def test_create_transaction_with_charge_success_response(
payment_information=payment_info, kind='ANYKIND',
response=stripe_charge_success_response, error=None)
- assert response['transaction_id'] == TRANSACTION_TOKEN
- assert response['is_success'] is True
- assert isclose(response['amount'], TRANSACTION_AMOUNT)
- assert response['currency'] == TRANSACTION_CURRENCY
+ assert response.transaction_id == TRANSACTION_TOKEN
+ assert response.is_success is True
+ assert isclose(response.amount, TRANSACTION_AMOUNT)
+ assert response.currency == TRANSACTION_CURRENCY
def test_create_transaction_with_partial_charge_success_response(
@@ -337,11 +337,11 @@ def test_create_transaction_with_partial_charge_success_response(
payment_information=payment_info, kind='ANYKIND',
response=stripe_partial_charge_success_response, error=None)
- assert response['transaction_id'] == TRANSACTION_TOKEN
- assert response['is_success'] is True
+ assert response.transaction_id == TRANSACTION_TOKEN
+ assert response.is_success is True
assert isclose(
- response['amount'], TRANSACTION_AMOUNT - TRANSACTION_REFUND_AMOUNT)
- assert response['currency'] == TRANSACTION_CURRENCY
+ response.amount, TRANSACTION_AMOUNT - TRANSACTION_REFUND_AMOUNT)
+ assert response.currency == TRANSACTION_CURRENCY
def test_create_transaction_with_refund_success_response(
@@ -353,10 +353,10 @@ def test_create_transaction_with_refund_success_response(
payment_information=payment_info, kind='ANYKIND',
response=stripe_refund_success_response, error=None)
- assert response['transaction_id'] == TRANSACTION_TOKEN
- assert response['is_success'] is True
- assert isclose(response['amount'], TRANSACTION_REFUND_AMOUNT)
- assert response['currency'] == TRANSACTION_CURRENCY
+ assert response.transaction_id == TRANSACTION_TOKEN
+ assert response.is_success is True
+ assert isclose(response.amount, TRANSACTION_REFUND_AMOUNT)
+ assert response.currency == TRANSACTION_CURRENCY
def test_create_response_with_error_response(stripe_payment):
@@ -368,10 +368,10 @@ def test_create_response_with_error_response(stripe_payment):
payment_information=payment_info, kind='ANYKIND',
response=stripe_error_response, error=None)
- assert response['transaction_id'] == FAKE_TOKEN
- assert response['is_success'] is False
- assert response['amount'] == payment.total
- assert response['currency'] == payment.currency
+ assert response.transaction_id == FAKE_TOKEN
+ assert response.is_success is False
+ assert response.amount == payment.total
+ assert response.currency == payment.currency
@pytest.mark.integration
@@ -388,13 +388,13 @@ def test_authorize(
response = authorize(payment_info, gateway_params)
- assert not response['error']
- assert response['transaction_id'] == TRANSACTION_TOKEN
- assert response['kind'] == TransactionKind.AUTH
- assert response['is_success']
- assert isclose(response['amount'], TRANSACTION_AMOUNT)
- assert response['currency'] == TRANSACTION_CURRENCY
- assert response['raw_response'] == stripe_charge_success_response
+ assert not response.error
+ assert response.transaction_id == TRANSACTION_TOKEN
+ assert response.kind == TransactionKind.AUTH
+ assert response.is_success
+ assert isclose(response.amount, TRANSACTION_AMOUNT)
+ assert response.currency == TRANSACTION_CURRENCY
+ assert response.raw_response == stripe_charge_success_response
@pytest.mark.integration
@@ -411,14 +411,13 @@ def test_authorize_error_response(
response = authorize(payment_info, gateway_params)
- assert response['error'] == ERROR_MESSAGE
- assert response['transaction_id'] == FAKE_TOKEN
- assert response['kind'] == TransactionKind.AUTH
- assert not response['is_success']
- assert response['amount'] == payment.total
- assert response['currency'] == payment.currency
- assert response['raw_response'] == _get_error_response_from_exc(
- stripe_error)
+ assert response.error == ERROR_MESSAGE
+ assert response.transaction_id == FAKE_TOKEN
+ assert response.kind == TransactionKind.AUTH
+ assert not response.is_success
+ assert response.amount == payment.total
+ assert response.currency == payment.currency
+ assert response.raw_response == _get_error_response_from_exc(stripe_error)
@pytest.mark.integration
@@ -437,13 +436,13 @@ def test_capture(
response = capture(payment_info, gateway_params)
- assert not response['error']
- assert response['transaction_id'] == TRANSACTION_TOKEN
- assert response['kind'] == TransactionKind.CAPTURE
- assert response['is_success']
- assert isclose(response['amount'], TRANSACTION_AMOUNT)
- assert response['currency'] == TRANSACTION_CURRENCY
- assert response['raw_response'] == stripe_charge_success_response
+ assert not response.error
+ assert response.transaction_id == TRANSACTION_TOKEN
+ assert response.kind == TransactionKind.CAPTURE
+ assert response.is_success
+ assert isclose(response.amount, TRANSACTION_AMOUNT)
+ assert response.currency == TRANSACTION_CURRENCY
+ assert response.raw_response == stripe_charge_success_response
@pytest.mark.integration
@@ -462,13 +461,14 @@ def test_partial_capture(
response = capture(payment_info, gateway_params)
- assert not response['error']
- assert response['transaction_id'] == TRANSACTION_TOKEN
- assert response['kind'] == TransactionKind.CAPTURE
- assert response['is_success']
- assert isclose(response['amount'], TRANSACTION_AMOUNT - TRANSACTION_REFUND_AMOUNT)
- assert response['currency'] == TRANSACTION_CURRENCY
- assert response['raw_response'] == stripe_partial_charge_success_response
+ assert not response.error
+ assert response.transaction_id == TRANSACTION_TOKEN
+ assert response.kind == TransactionKind.CAPTURE
+ assert response.is_success
+ assert isclose(
+ response.amount, TRANSACTION_AMOUNT - TRANSACTION_REFUND_AMOUNT)
+ assert response.currency == TRANSACTION_CURRENCY
+ assert response.raw_response == stripe_partial_charge_success_response
@pytest.mark.integration
@@ -486,14 +486,13 @@ def test_capture_error_response(
response = capture(payment_info, gateway_params)
- assert response['error'] == ERROR_MESSAGE
- assert response['transaction_id'] == TRANSACTION_TOKEN
- assert response['kind'] == TransactionKind.CAPTURE
- assert not response['is_success']
- assert response['amount'] == payment.total
- assert response['currency'] == payment.currency
- assert response['raw_response'] == _get_error_response_from_exc(
- stripe_error)
+ assert response.error == ERROR_MESSAGE
+ assert response.transaction_id == TRANSACTION_TOKEN
+ assert response.kind == TransactionKind.CAPTURE
+ assert not response.is_success
+ assert response.amount == payment.total
+ assert response.currency == payment.currency
+ assert response.raw_response == _get_error_response_from_exc(stripe_error)
@pytest.mark.integration
@@ -511,13 +510,13 @@ def test_charge(
response = charge(payment_info, gateway_params)
- assert not response['error']
- assert response['transaction_id'] == TRANSACTION_TOKEN
- assert response['kind'] == TransactionKind.CHARGE
- assert response['is_success']
- assert isclose(response['amount'], TRANSACTION_AMOUNT)
- assert response['currency'] == TRANSACTION_CURRENCY
- assert response['raw_response'] == stripe_charge_success_response
+ assert not response.error
+ assert response.transaction_id == TRANSACTION_TOKEN
+ assert response.kind == TransactionKind.CHARGE
+ assert response.is_success
+ assert isclose(response.amount, TRANSACTION_AMOUNT)
+ assert response.currency == TRANSACTION_CURRENCY
+ assert response.raw_response == stripe_charge_success_response
@pytest.mark.integration
@@ -535,14 +534,13 @@ def test_charge_error_response(
response = charge(payment_info, gateway_params)
- assert response['error'] == ERROR_MESSAGE
- assert response['transaction_id'] == FAKE_TOKEN
- assert response['kind'] == TransactionKind.CHARGE
- assert not response['is_success']
- assert response['amount'] == payment.total
- assert response['currency'] == payment.currency
- assert response['raw_response'] == _get_error_response_from_exc(
- stripe_error)
+ assert response.error == ERROR_MESSAGE
+ assert response.transaction_id == FAKE_TOKEN
+ assert response.kind == TransactionKind.CHARGE
+ assert not response.is_success
+ assert response.amount == payment.total
+ assert response.currency == payment.currency
+ assert response.raw_response == _get_error_response_from_exc(stripe_error)
@pytest.mark.integration
@@ -563,13 +561,13 @@ def test_refund_charged(
response = refund(payment_info, gateway_params)
- assert not response['error']
- assert response['transaction_id'] == TRANSACTION_TOKEN
- assert response['kind'] == TransactionKind.REFUND
- assert response['is_success']
- assert isclose(response['amount'], TRANSACTION_REFUND_AMOUNT)
- assert response['currency'] == TRANSACTION_CURRENCY
- assert response['raw_response'] == stripe_refund_success_response
+ assert not response.error
+ assert response.transaction_id == TRANSACTION_TOKEN
+ assert response.kind == TransactionKind.REFUND
+ assert response.is_success
+ assert isclose(response.amount, TRANSACTION_REFUND_AMOUNT)
+ assert response.currency == TRANSACTION_CURRENCY
+ assert response.raw_response == stripe_refund_success_response
@pytest.mark.integration
@@ -590,13 +588,13 @@ def test_refund_captured(
response = refund(payment_info, gateway_params)
- assert not response['error']
- assert response['transaction_id'] == TRANSACTION_TOKEN
- assert response['kind'] == TransactionKind.REFUND
- assert response['is_success']
- assert isclose(response['amount'], TRANSACTION_REFUND_AMOUNT)
- assert response['currency'] == TRANSACTION_CURRENCY
- assert response['raw_response'] == stripe_refund_success_response
+ assert not response.error
+ assert response.transaction_id == TRANSACTION_TOKEN
+ assert response.kind == TransactionKind.REFUND
+ assert response.is_success
+ assert isclose(response.amount, TRANSACTION_REFUND_AMOUNT)
+ assert response.currency == TRANSACTION_CURRENCY
+ assert response.raw_response == stripe_refund_success_response
@pytest.mark.integration
@@ -617,14 +615,13 @@ def test_refund_error_response(
response = refund(payment_info, gateway_params)
- assert response['error'] == ERROR_MESSAGE
- assert response['transaction_id'] == TRANSACTION_TOKEN
- assert response['kind'] == TransactionKind.REFUND
- assert not response['is_success']
- assert response['amount'] == payment.total
- assert response['currency'] == TRANSACTION_CURRENCY
- assert response['raw_response'] == _get_error_response_from_exc(
- stripe_error)
+ assert response.error == ERROR_MESSAGE
+ assert response.transaction_id == TRANSACTION_TOKEN
+ assert response.kind == TransactionKind.REFUND
+ assert not response.is_success
+ assert response.amount == payment.total
+ assert response.currency == TRANSACTION_CURRENCY
+ assert response.raw_response == _get_error_response_from_exc(stripe_error)
@pytest.mark.integration
@@ -644,13 +641,13 @@ def test_void(
response = void(payment_info, gateway_params)
- assert not response['error']
- assert response['transaction_id'] == TRANSACTION_TOKEN
- assert response['kind'] == TransactionKind.VOID
- assert response['is_success']
- assert isclose(response['amount'], TRANSACTION_REFUND_AMOUNT)
- assert response['currency'] == TRANSACTION_CURRENCY
- assert response['raw_response'] == stripe_refund_success_response
+ assert not response.error
+ assert response.transaction_id == TRANSACTION_TOKEN
+ assert response.kind == TransactionKind.VOID
+ assert response.is_success
+ assert isclose(response.amount, TRANSACTION_REFUND_AMOUNT)
+ assert response.currency == TRANSACTION_CURRENCY
+ assert response.raw_response == stripe_refund_success_response
@pytest.mark.integration
@@ -670,10 +667,10 @@ def test_void_error_response(
response = void(payment_info, gateway_params)
- assert response['error'] == ERROR_MESSAGE
- assert response['transaction_id'] == TRANSACTION_TOKEN
- assert response['kind'] == TransactionKind.VOID
- assert not response['is_success']
- assert response['amount'] == payment.total
- assert response['currency'] == TRANSACTION_CURRENCY
- assert response['raw_response'] == {}
+ assert response.error == ERROR_MESSAGE
+ assert response.transaction_id == TRANSACTION_TOKEN
+ assert response.kind == TransactionKind.VOID
+ assert not response.is_success
+ assert response.amount == payment.total
+ assert response.currency == TRANSACTION_CURRENCY
+ assert response.raw_response == {}
diff --git a/tests/test_order.py b/tests/test_order.py
index 23991ca354..209dda5c3e 100644
--- a/tests/test_order.py
+++ b/tests/test_order.py
@@ -481,8 +481,7 @@ def test_order_payment_flow(
payment = order.payments.all()[0]
assert payment.total == order.total.gross.amount
assert payment.currency == order.total.gross.currency
- assert payment.transactions.count() == 2
- assert payment.transactions.first().kind == 'auth'
+ assert payment.transactions.count() == 1
assert payment.transactions.last().kind == 'capture'
diff --git a/tests/test_payment.py b/tests/test_payment.py
index 368dbe169d..4ea2beff6e 100644
--- a/tests/test_payment.py
+++ b/tests/test_payment.py
@@ -1,3 +1,4 @@
+import dataclasses
from decimal import Decimal
from unittest.mock import Mock, patch
@@ -11,6 +12,7 @@ from saleor.order.views import PAYMENT_TEMPLATE
from saleor.payment import (
ChargeStatus, GatewayError, OperationType, PaymentError, TransactionKind,
get_payment_gateway)
+from saleor.payment.gateway_dataclasses import GatewayResponse
from saleor.payment.models import Payment
from saleor.payment.utils import (
ALLOWED_GATEWAY_KINDS, REQUIRED_GATEWAY_KEYS, call_gateway,
@@ -27,18 +29,19 @@ EXAMPLE_ERROR = 'Example dummy error'
@pytest.fixture
def gateway_response(settings):
- return {
- 'is_success': True,
- 'transaction_id': 'transaction-token',
- 'amount': Decimal(14.50),
- 'currency': settings.DEFAULT_CURRENCY,
- 'kind': TransactionKind.CAPTURE,
- 'error': None,
- 'raw_response': {
+ return GatewayResponse(
+ is_success=True,
+ transaction_id='transaction-token',
+ amount=Decimal(14.50),
+ currency=settings.DEFAULT_CURRENCY,
+ kind=TransactionKind.CAPTURE,
+ error=None,
+ raw_response={
'credit_card_four': '1234',
'transaction-id': 'transaction-token',
}
- }
+ )
+
@pytest.fixture
@@ -63,13 +66,15 @@ def transaction_token():
@pytest.fixture
def dummy_response(payment_dummy, transaction_data, transaction_token):
- return {
- 'is_success': True,
- 'transaction_id': transaction_token,
- 'error': EXAMPLE_ERROR,
- 'amount': payment_dummy.total,
- 'currency': payment_dummy.currency,
- 'kind': TransactionKind.AUTH}
+ return GatewayResponse(
+ is_success=True,
+ transaction_id=transaction_token,
+ error=EXAMPLE_ERROR,
+ amount=payment_dummy.total,
+ currency=payment_dummy.currency,
+ kind=TransactionKind.AUTH,
+ raw_response=None
+ )
def test_get_payment_gateway_not_allowed_checkout_choice(settings):
@@ -168,12 +173,13 @@ def test_create_transaction(transaction_data):
txn = create_transaction(**transaction_data)
assert txn.payment == transaction_data['payment']
- assert txn.kind == transaction_data['gateway_response']['kind']
- assert txn.amount == transaction_data['gateway_response']['amount']
- assert txn.currency == transaction_data['gateway_response']['currency']
- assert txn.token == transaction_data['gateway_response']['transaction_id']
- assert txn.is_success == transaction_data['gateway_response']['is_success']
- assert txn.gateway_response == transaction_data['gateway_response']
+ gateway_response = transaction_data['gateway_response']
+ assert txn.kind == gateway_response.kind
+ assert txn.amount == gateway_response.amount
+ assert txn.currency == gateway_response.currency
+ assert txn.token == gateway_response.transaction_id
+ assert txn.is_success == gateway_response.is_success
+ assert txn.gateway_response == dataclasses.asdict(gateway_response)
def test_create_transaction_no_gateway_response(transaction_data):
@@ -224,7 +230,7 @@ def test_gateway_process_payment(
transaction_token, dummy_response):
payment_token = transaction_token
payment = payment_txn_preauth
- mock_process_payment = Mock(return_value=[dummy_response, dummy_response])
+ mock_process_payment = Mock(return_value=dummy_response)
mock_get_payment_gateway.return_value = (
Mock(process_payment=mock_process_payment), gateway_params)
@@ -259,13 +265,12 @@ def test_gateway_authorize(
def test_gateway_authorize_failed(
mock_get_payment_gateway, payment_txn_preauth, gateway_params,
transaction_token, dummy_response):
- payment = payment_txn_preauth
payment_token = transaction_token
txn = payment_txn_preauth.transactions.first()
txn.is_success = False
payment = payment_txn_preauth
- dummy_response['is_success'] = False
+ dummy_response.is_success = False
mock_authorize = Mock(return_value=dummy_response)
mock_get_payment_gateway.return_value = (
Mock(authorize=mock_authorize), gateway_params)
@@ -291,7 +296,7 @@ def test_gateway_capture(
assert not payment.captured_amount
amount = payment.total
- dummy_response['kind'] = TransactionKind.CAPTURE
+ dummy_response.kind = TransactionKind.CAPTURE
mock_capture = Mock(return_value=dummy_response)
mock_get_payment_gateway.return_value = (
Mock(capture=mock_capture), gateway_params)
@@ -320,8 +325,8 @@ def test_gateway_capture_partial_capture(
txn.amount = amount
txn.currency = settings.DEFAULT_CURRENCY
- dummy_response['kind'] = TransactionKind.CAPTURE
- dummy_response['amount'] = amount
+ dummy_response.kind = TransactionKind.CAPTURE
+ dummy_response.amount = amount
mock_capture = Mock(return_value=dummy_response)
mock_get_payment_gateway.return_value = (
Mock(capture=mock_capture), gateway_params)
@@ -346,8 +351,8 @@ def test_gateway_capture_failed(
payment = payment_txn_preauth
amount = payment.total
- dummy_response['is_success'] = False
- dummy_response['kind'] = TransactionKind.CAPTURE
+ dummy_response.is_success = False
+ dummy_response.kind = TransactionKind.CAPTURE
mock_capture = Mock(return_value=dummy_response)
mock_get_payment_gateway.return_value = (
Mock(capture=mock_capture), gateway_params)
@@ -383,12 +388,11 @@ def test_gateway_charge(
mock_get_payment_gateway, mock_handle_fully_paid_order, payment_txn_preauth,
gateway_params, transaction_token, dummy_response):
payment_token = transaction_token
- txn = payment_txn_preauth.transactions.first()
payment = payment_txn_preauth
assert not payment.captured_amount
amount = payment.total
- dummy_response['kind'] = TransactionKind.CHARGE
+ dummy_response.kind = TransactionKind.CHARGE
mock_charge = Mock(return_value=dummy_response)
mock_get_payment_gateway.return_value = (
Mock(charge=mock_charge), gateway_params)
@@ -418,8 +422,8 @@ def test_gateway_capture_partial_charge(
txn.amount = amount
txn.currency = settings.DEFAULT_CURRENCY
- dummy_response['kind'] = TransactionKind.CAPTURE
- dummy_response['amount'] = amount
+ dummy_response.kind = TransactionKind.CAPTURE
+ dummy_response.amount = amount
mock_charge = Mock(return_value=dummy_response)
mock_get_payment_gateway.return_value = (
Mock(charge=mock_charge), gateway_params)
@@ -445,8 +449,8 @@ def test_gateway_charge_failed(
payment = payment_txn_preauth
amount = payment.total
- dummy_response['is_success'] = False
- dummy_response['kind'] = TransactionKind.CAPTURE
+ dummy_response.is_success = False
+ dummy_response.kind = TransactionKind.CAPTURE
mock_charge = Mock(return_value=dummy_response)
mock_get_payment_gateway.return_value = (
Mock(charge=mock_charge), gateway_params)
@@ -487,7 +491,7 @@ def test_gateway_void(
payment = payment_txn_preauth
assert payment.is_active
- dummy_response['kind'] = TransactionKind.VOID
+ dummy_response.kind = TransactionKind.VOID
mock_void = Mock(return_value=dummy_response)
mock_get_payment_gateway.return_value = (Mock(void=mock_void), gateway_params)
@@ -510,8 +514,8 @@ def test_gateway_void_failed(
txn.is_success = False
payment = payment_txn_preauth
- dummy_response['kind'] = TransactionKind.VOID
- dummy_response['is_success'] = False
+ dummy_response.kind = TransactionKind.VOID
+ dummy_response.is_success = False
mock_void = Mock(return_value=dummy_response)
mock_get_payment_gateway.return_value = (Mock(void=mock_void), gateway_params)
with pytest.raises(PaymentError) as exc:
@@ -537,7 +541,7 @@ def test_gateway_refund(
payment = payment_txn_captured
amount = payment.total
- dummy_response['kind'] = TransactionKind.REFUND
+ dummy_response.kind = TransactionKind.REFUND
mock_refund = Mock(return_value=dummy_response)
mock_get_payment_gateway.return_value = (
Mock(refund=mock_refund), gateway_params)
@@ -564,8 +568,8 @@ def test_gateway_refund_partial_refund(
txn.amount = amount
txn.currency = settings.DEFAULT_CURRENCY
- dummy_response['kind'] = TransactionKind.REFUND
- dummy_response['amount'] = amount
+ dummy_response.kind = TransactionKind.REFUND
+ dummy_response.amount = amount
mock_refund = Mock(return_value=dummy_response)
mock_get_payment_gateway.return_value = (
Mock(refund=mock_refund), gateway_params)
@@ -586,8 +590,8 @@ def test_gateway_refund_failed(
captured_before = payment.captured_amount
txn.is_success = False
- dummy_response['kind'] = TransactionKind.REFUND
- dummy_response['is_success'] = False
+ dummy_response.kind = TransactionKind.REFUND
+ dummy_response.is_success = False
mock_refund = Mock(return_value=dummy_response)
mock_get_payment_gateway.return_value = (
Mock(refund=mock_refund), gateway_params)
@@ -818,19 +822,8 @@ def test_validate_gateway_response(gateway_response):
validate_gateway_response(gateway_response)
-def test_validate_gateway_response_missing_required_key(gateway_response):
- del gateway_response['is_success']
-
- with pytest.raises(GatewayError) as e:
- validate_gateway_response(gateway_response)
-
- assert str(e.value) == (
- 'Gateway response needs to contain following keys: {}'.format(
- sorted(REQUIRED_GATEWAY_KEYS)))
-
-
def test_validate_gateway_response_incorrect_transaction_kind(gateway_response):
- gateway_response['kind'] = 'incorrect-kind'
+ gateway_response.kind = 'incorrect-kind'
with pytest.raises(GatewayError) as e:
validate_gateway_response(gateway_response)
@@ -843,7 +836,7 @@ def test_validate_gateway_response_incorrect_transaction_kind(gateway_response):
def test_validate_gateway_response_not_json_serializable(gateway_response):
class CustomClass(object):
pass
- gateway_response['extra'] = CustomClass()
+ gateway_response.raw_response = CustomClass()
with pytest.raises(GatewayError) as e:
validate_gateway_response(gateway_response)
@@ -851,16 +844,6 @@ def test_validate_gateway_response_not_json_serializable(gateway_response):
assert str(e.value) == 'Gateway response needs to be json serializable'
-def test_validate_gateway_response_incorrect_field_type(gateway_response):
- gateway_response['amount'] = 'should-be-decimal'
-
- with pytest.raises(GatewayError) as e:
- validate_gateway_response(gateway_response)
-
- assert str(e.value) == 'amount must be of type {}, was {}'.format(
- Decimal, str)
-
-
@patch('saleor.payment.utils.get_payment_gateway')
def test_call_gateway_invalid_response(
mock_get_payment_gateway, payment_dummy):