Skip to content

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

Improvements and test fixes

Michał Jelonek987ddfbf05e9
diff --git a/saleor/payment/gateways/braintree/__init__.py b/saleor/payment/gateways/braintree/__init__.py
index 1c3589edd3..11cfcd11c3 100644
--- a/saleor/payment/gateways/braintree/__init__.py
+++ b/saleor/payment/gateways/braintree/__init__.py
@@ -120,28 +120,18 @@ def get_client_token(**connection_params: Dict) -> str:
def process_payment(
payment: Dict, payment_token: str, amount: Decimal,
- **connection_params: Dict) -> Tuple[bool, str, Dict, str]:
- auth_success, auth_response, auth_errors = authorize(
- payment, payment_token, **connection_params)
- transaction_token = auth_response['transaction_id']
+ **connection_params: Dict) -> Dict:
+ auth_resp = authorize(payment, payment_token, **connection_params)
+ transaction_token = auth_resp['transaction_id']
try:
- capture_success, capture_response, capture_errors = capture(
- transaction_token, amount, **connection_params)
+ return capture(transaction_token, amount, **connection_params)
except Exception as e:
void(transaction_token, **connection_params)
- return {
- 'is_successful': capture_success,
- 'transaction_token': capture_response['transaction_id'],
- 'gateway_response': capture_response,
- 'errors': capture_errors}
-
def authorize(
- payment: Dict,
- payment_token: str,
- **connection_params: Dict) -> Tuple[bool, Dict, str]:
+ payment: Dict, payment_token: str, **connection_params: Dict) -> Dict:
gateway = get_braintree_gateway(**connection_params)
try:
@@ -161,13 +151,17 @@ def authorize(
gateway_response = extract_gateway_response(result)
error = get_error_for_client(gateway_response['errors'])
- return result.is_success, gateway_response, error
+ return {
+ 'is_success': result.is_success,
+ 'transaction_id': gateway_response['transaction_id'],
+ 'gateway_response': gateway_response,
+ 'errors': error,
+ }
def capture(
- payment_token: str,
- amount: Decimal,
- **connection_params: Dict) -> Tuple[bool, Dict, str]:
+ payment: Dict, payment_token: str, amount: Decimal,
+ **connection_params: Dict) -> Dict:
gateway = get_braintree_gateway(**connection_params)
try:
@@ -180,12 +174,16 @@ def capture(
gateway_response = extract_gateway_response(result)
error = get_error_for_client(gateway_response['errors'])
- return result.is_success, gateway_response, error
+ return {
+ 'is_success': result.is_success,
+ 'transaction_id': gateway_response['transaction_id'],
+ 'gateway_response': gateway_response,
+ 'errors': error,
+ }
def void(
- payment_token: str,
- **connection_params: Dict) -> Tuple[bool, Dict, str]:
+ payment: Dict, payment_token: str, **connection_params: Dict) -> Dict:
gateway = get_braintree_gateway(**connection_params)
try:
@@ -197,13 +195,17 @@ def void(
gateway_response = extract_gateway_response(result)
error = get_error_for_client(gateway_response['errors'])
- return result.is_success, gateway_response, error
+ return {
+ 'is_success': result.is_success,
+ 'transaction_id': gateway_response['transaction_id'],
+ 'gateway_response': gateway_response,
+ 'errors': error,
+ }
def refund(
- payment_token: str,
- amount: Decimal,
- **connection_params: Dict) -> Tuple[bool, Dict, str]:
+ payment: Dict, payment_token: str, amount: Decimal,
+ **connection_params: Dict) -> Dict:
gateway = get_braintree_gateway(**connection_params)
try:
@@ -217,4 +219,9 @@ def refund(
gateway_response = extract_gateway_response(result)
error = get_error_for_client(gateway_response['errors'])
- return result.is_success, gateway_response, error
+ return {
+ 'is_success': result.is_success,
+ 'transaction_id': gateway_response['transaction_id'],
+ 'gateway_response': gateway_response,
+ 'errors': error,
+ }
diff --git a/saleor/payment/gateways/dummy/__init__.py b/saleor/payment/gateways/dummy/__init__.py
index 41952387cd..c8a23e3202 100644
--- a/saleor/payment/gateways/dummy/__init__.py
+++ b/saleor/payment/gateways/dummy/__init__.py
@@ -28,52 +28,75 @@ def get_form_class():
def process_payment(
- payment: Payment, payment_token: str, amount: Decimal,
+ payment: Dict, payment_token: str, amount: Decimal,
**connection_params):
- authorize(payment_token)
- capture_success, capture_response, capture_errors = capture(
- payment, payment_token)
+ auth_resp = authorize(payment, payment_token)
+ if auth_resp['errors']:
+ return auth_resp
+ return capture(payment, payment_token, amount)
- return capture_success, capture_response, capture_errors
-
-def authorize(payment: Payment, payment_token: str, **connection_params):
+def authorize(payment: Dict, payment_token: str, **connection_params):
success = dummy_success()
error = None
if not success:
error = 'Unable to authorize transaction'
- return success, {}, error
+ return {
+ 'is_success': success,
+ 'transaction_id': payment_token,
+ 'gateway_response': {},
+ 'errors': error,
+ }
-def void(payment: Payment, **connection_params: Dict):
+def void(payment: Dict, payment_token: str, **connection_params: Dict):
error = None
success = dummy_success()
if not success:
error = 'Unable to void the transaction.'
- return success, {}, error
+ return {
+ 'is_success': success,
+ 'transaction_id': payment_token,
+ 'gateway_response': {},
+ 'errors': error,
+ }
-def capture(payment: Payment, amount: Decimal, **connection_params: Dict):
+def capture(
+ payment: Dict, payment_token: str, amount: Decimal,
+ **connection_params: Dict):
error = None
success = dummy_success()
if not success:
error = 'Unable to process capture'
- return success, {}, error
+ return {
+ 'is_success': success,
+ 'transaction_id': payment_token,
+ 'gateway_response': {},
+ 'errors': error,
+ }
-def refund(payment: Payment, amount: Decimal, **connection_params: Dict):
+def refund(
+ payment: Dict, payment_token: str, amount: Decimal,
+ **connection_params: Dict):
error = None
success = dummy_success()
if not success:
error = 'Unable to process refund'
- return success, {}, error
+ return {
+ 'is_success': success,
+ 'transaction_id': payment_token,
+ 'gateway_response': {},
+ 'errors': error,
+ }
def charge(
- payment: Payment, payment_token: str, amount: Decimal,
+ payment: Dict, payment_token: str, amount: Decimal,
**connection_params):
"""Performs Authorize and Capture transactions in a single run."""
- is_success, response, error = authorize(payment, payment_token)
- if error:
- return is_success, response, error
- return capture(payment, amount)
+ auth_resp = authorize(payment, payment_token)
+ if auth_resp['errors']:
+ return auth_resp
+ return capture(payment, payment_token, amount)
diff --git a/saleor/payment/utils.py b/saleor/payment/utils.py
index 3192ede053..0445783eac 100644
--- a/saleor/payment/utils.py
+++ b/saleor/payment/utils.py
@@ -74,14 +74,14 @@ def create_payment(**payment_data):
def create_transaction(payment: Payment, kind: str, payment_token: str,
- gateway_response: Dict) -> Transaction:
+ gateway_response: Dict, **extra_params) -> Transaction:
"""Creates a Transaction based on transaction kind and gateway response."""
txn, _ = Transaction.objects.get_or_create(
payment=payment,
kind=kind,
token=gateway_response.get('transaction_id', payment_token),
is_success=gateway_response.get('is_success', False),
- amount=payment.total,
+ amount=extra_params.get('amount', payment.total),
currency=payment.currency,
gateway_response=gateway_response)
return txn
@@ -131,9 +131,12 @@ def call_gateway(
gateway, gateway_params = get_payment_gateway(payment.gateway)
gateway_response = dict()
+ #TODO: improve so only one argument is sent (dict?) instead of passing
+ # multiple kwargs, eventually keep connection params separate
+ #TODO: add additional information to payment data (e.g. shipping/billing)
try:
gateway_response = getattr(gateway, func_name)(
- payment=payment, payment_token=payment_token,
+ payment=model_to_dict(payment), payment_token=payment_token,
**extra_params, **gateway_params)
validate_gateway_response(gateway_response)
except AttributeError:
@@ -147,22 +150,26 @@ def call_gateway(
payment=payment,
kind=transaction_kind,
payment_token=payment_token,
- gateway_response=gateway_response)
+ gateway_response=gateway_response,
+ **extra_params)
if not transaction.is_success:
# attempt to get errors from response, if none raise a generic one
raise PaymentError(gateway_response.get(
'errors', GENERIC_TRANSACTION_ERROR))
+ return transaction
+
def validate_gateway_response(response):
"""Validates response to be a correct format for Saleor to process."""
if not isinstance(response, dict):
raise GatewayError('Gateway needs to return a dictionary')
- required_fields = {'transaction_id', 'is_success'}
+ required_fields = {
+ 'transaction_id', 'is_success', 'gateway_response', 'errors'}
if not required_fields.issubset(response):
raise GatewayError(
- 'Gateway response needs to contain following keys: '.format(
+ 'Gateway response needs to contain following keys: {}'.format(
required_fields - response.keys()))
@@ -172,7 +179,7 @@ def gateway_process_payment(
"""Performs whole payment process on a gateway."""
transaction = call_gateway(
func_name='process_payment', transaction_kind=TransactionKind.CAPTURE,
- payment=payment, payment_token=payment_token)
+ payment=payment, payment_token=payment_token, amount=payment.total)
if transaction.is_success:
payment.charge_status = ChargeStatus.CHARGED
diff --git a/tests/api/test_order.py b/tests/api/test_order.py
index 2014183262..470a9ebdba 100644
--- a/tests/api/test_order.py
+++ b/tests/api/test_order.py
@@ -1091,6 +1091,7 @@ def test_order_refund(
def test_clean_order_void_payment():
payment = MagicMock(spec=Payment)
payment.is_active = False
+ payment.gateway = 'dummy'
errors = clean_void_payment(payment, [])
assert errors[0].field == 'payment'
assert errors[0].message == 'Only pre-authorized payments can be voided'
diff --git a/tests/gateway/test_braintree.py b/tests/gateway/test_braintree.py
index edbe9bfa9d..6ff1b07f23 100644
--- a/tests/gateway/test_braintree.py
+++ b/tests/gateway/test_braintree.py
@@ -15,8 +15,7 @@ from saleor.payment import TransactionKind, get_payment_gateway
from saleor.payment.gateways.braintree import (
CONFIRM_MANUALLY, THREE_D_SECURE_REQUIRED, authorize, capture,
extract_gateway_response, get_braintree_gateway, get_client_token,
- get_customer_data, get_error_for_client, refund,
- transaction_and_incorrect_token_error, void)
+ get_customer_data, get_error_for_client, refund, void)
from saleor.payment.gateways.braintree.forms import BraintreePaymentForm
INCORRECT_TOKEN_ERROR = (
@@ -450,25 +449,6 @@ def test_void_error_response(
assert error == DEFAULT_ERROR
-def test_transaction_and_incorrect_token_error_helper(payment_dummy, settings):
- amount = Decimal('10.00')
- txn, error = transaction_and_incorrect_token_error(
- payment_dummy, 'example-token', TransactionKind.AUTH, amount=amount)
- assert error == INCORRECT_TOKEN_ERROR
- assert not txn.is_success
- assert txn.kind == TransactionKind.AUTH
- assert txn.token == 'example-token'
- assert not txn.gateway_response
- assert txn.amount == amount
- assert txn.currency == settings.DEFAULT_CURRENCY
-
-
-def test_transaction_and_incorrect_token_error_helper_no_amount(payment_dummy):
- txn, error = transaction_and_incorrect_token_error(
- payment_dummy, 'example-token', TransactionKind.AUTH)
- assert txn.amount == payment_dummy.total
-
-
def test_braintree_payment_form_incorrect_amount(payment_dummy):
amount = Decimal('0.01')
data = {'amount': amount, 'payment_method_nonce': 'fake-nonce'}
@@ -477,8 +457,7 @@ def test_braintree_payment_form_incorrect_amount(payment_dummy):
payment_gateway, gateway_params = get_payment_gateway(
payment_dummy.gateway)
form = BraintreePaymentForm(
- data=data, payment=payment_dummy, gateway=payment_gateway,
- gateway_params=gateway_params)
+ data=data, amount=payment_dummy.total, gateway=payment_gateway)
assert not form.is_valid()
assert form.non_field_errors
@@ -487,11 +466,9 @@ def test_braintree_payment_form(settings, payment_dummy):
payment = payment_dummy
payment.gateway = settings.BRAINTREE
data = {'amount': payment.total, 'payment_method_nonce': 'fake-nonce'}
- payment_gateway, gateway_params = get_payment_gateway(payment.gateway)
form = BraintreePaymentForm(
- data=data, payment=payment, gateway=payment_gateway,
- gateway_params=gateway_params)
+ data=data, amount=payment.total, currency=payment.currency)
assert form.is_valid()
diff --git a/tests/gateway/test_dummy.py b/tests/gateway/test_dummy.py
index 1cdcd7276b..6c85b43961 100644
--- a/tests/gateway/test_dummy.py
+++ b/tests/gateway/test_dummy.py
@@ -11,18 +11,13 @@ from saleor.payment.gateways.dummy.forms import DummyPaymentForm
def test_charge_success(payment_dummy):
- payment_dummy.charge(
- payment_token='fake-token', amount=payment_dummy.total)
- capture_txn, auth_txn = payment_dummy.transactions.all()
+ gateway_charge(payment=payment_dummy, payment_token='fake-token')
+ charge_txn = payment_dummy.transactions.all()
- assert auth_txn.is_success
- assert auth_txn.kind == TransactionKind.AUTH
- assert auth_txn.payment == payment_dummy
-
- assert capture_txn.is_success
- assert capture_txn.kind == TransactionKind.CAPTURE
- assert capture_txn.payment == payment_dummy
- assert capture_txn.amount == payment_dummy.total
+ assert charge_txn.is_success
+ assert charge_txn.kind == TransactionKind.CAPTURE
+ assert charge_txn.payment == payment_dummy
+ assert charge_txn.amount == payment_dummy.total
payment_dummy.refresh_from_db()
assert payment_dummy.charge_status == ChargeStatus.CHARGED
@@ -228,6 +223,7 @@ def test_refund_gateway_error(payment_txn_captured, monkeypatch):
assert payment.captured_amount == Decimal('80.00')
[email protected]('This is currently not supported')
@pytest.mark.parametrize(
'kind, charge_status',
(
diff --git a/tests/test_payment.py b/tests/test_payment.py
index 0ab66e35f5..063b29112e 100644
--- a/tests/test_payment.py
+++ b/tests/test_payment.py
@@ -25,12 +25,11 @@ EXAMPLE_ERROR = 'Example dummy error'
def transaction_data(payment_dummy, settings):
return {
'payment': payment_dummy,
- 'token': 'token',
+ 'payment_token': 'token',
'kind': TransactionKind.CAPTURE,
'is_success': True,
- 'amount': Decimal('10.00'),
- 'currency': settings.DEFAULT_CURRENCY,
'gateway_response': {
+ 'is_success': True,
'credit_cart': '4321'}}
@@ -234,12 +233,15 @@ def test_gateway_authorize_errors(payment_dummy):
def test_gateway_capture(
mock_get_payment_gateway, mock_handle_fully_paid_order, payment_txn_preauth,
gateway_params):
- txn = payment_txn_preauth.transactions.first()
payment = payment_txn_preauth
assert not payment.captured_amount
amount = payment.total
- mock_capture = Mock(return_value=(txn, ''))
+ mock_capture = Mock(return_value={
+ 'is_success': True,
+ 'transaction_id': 'token',
+ 'gateway_response': {},
+ 'errors': None})
mock_get_payment_gateway.return_value = (
Mock(capture=mock_capture), gateway_params)
@@ -265,7 +267,11 @@ def test_gateway_capture_partial_capture(
txn.amount = amount
txn.currency = settings.DEFAULT_CURRENCY
- mock_capture = Mock(return_value=(txn, ''))
+ mock_capture = Mock(return_value={
+ 'is_success': True,
+ 'transaction_id': 'token',
+ 'gateway_response': {},
+ 'errors': None})
mock_get_payment_gateway.return_value = (
Mock(capture=mock_capture), gateway_params)
@@ -289,7 +295,11 @@ def test_gateway_capture_failed(
payment = payment_txn_preauth
amount = payment.total
- mock_capture = Mock(return_value=(txn, EXAMPLE_ERROR))
+ mock_capture = Mock(return_value={
+ 'is_success': False,
+ 'transaction_id': 'token',
+ 'gateway_response': {},
+ 'errors': EXAMPLE_ERROR})
mock_get_payment_gateway.return_value = (
Mock(capture=mock_capture), gateway_params)
with pytest.raises(PaymentError) as exc:
@@ -329,7 +339,11 @@ def test_gateway_charge(
assert not payment.captured_amount
amount = payment.total
- mock_charge = Mock(return_value=(txn, ''))
+ mock_charge = Mock(return_value={
+ 'is_success': True,
+ 'transaction_id': 'token',
+ 'gateway_response': {},
+ 'errors': None})
mock_get_payment_gateway.return_value = (
Mock(charge=mock_charge), gateway_params)
@@ -356,7 +370,11 @@ def test_gateway_capture_partial_charge(
txn.amount = amount
txn.currency = settings.DEFAULT_CURRENCY
- mock_charge = Mock(return_value=(txn, ''))
+ mock_charge = Mock(return_value={
+ 'is_success': True,
+ 'transaction_id': 'token',
+ 'gateway_response': {},
+ 'errors': None})
mock_get_payment_gateway.return_value = (
Mock(charge=mock_charge), gateway_params)
@@ -381,7 +399,11 @@ def test_gateway_charge_failed(
payment = payment_txn_preauth
amount = payment.total
- mock_charge = Mock(return_value=(False, {}, EXAMPLE_ERROR))
+ mock_charge = Mock(return_value={
+ 'is_success': False,
+ 'transaction_id': 'token',
+ 'gateway_response': {},
+ 'errors': EXAMPLE_ERROR})
mock_get_payment_gateway.return_value = (
Mock(charge=mock_charge), gateway_params)
with pytest.raises(PaymentError) as exc: