Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Fixes to tests and functionality
Michał Jelonek7af1aaafaf46
diff --git a/saleor/payment/gateways/braintree/__init__.py b/saleor/payment/gateways/braintree/__init__.pyindex 11cfcd11c3..06dca1e899 100644--- a/saleor/payment/gateways/braintree/__init__.py+++ b/saleor/payment/gateways/braintree/__init__.py@@ -128,6 +128,7 @@ def process_payment(return capture(transaction_token, amount, **connection_params)except Exception as e:void(transaction_token, **connection_params)+ raisedef authorize(@@ -154,7 +155,7 @@ def authorize(return {'is_success': result.is_success,'transaction_id': gateway_response['transaction_id'],- 'gateway_response': gateway_response,+ 'raw_response': gateway_response,'errors': error,}@@ -177,7 +178,7 @@ def capture(return {'is_success': result.is_success,'transaction_id': gateway_response['transaction_id'],- 'gateway_response': gateway_response,+ 'raw_response': gateway_response,'errors': error,}@@ -198,7 +199,7 @@ def void(return {'is_success': result.is_success,'transaction_id': gateway_response['transaction_id'],- 'gateway_response': gateway_response,+ 'raw_response': gateway_response,'errors': error,}@@ -222,6 +223,6 @@ def refund(return {'is_success': result.is_success,'transaction_id': gateway_response['transaction_id'],- 'gateway_response': gateway_response,+ 'raw_response': gateway_response,'errors': error,}diff --git a/saleor/payment/utils.py b/saleor/payment/utils.pyindex 0445783eac..b7ccd57b3c 100644--- a/saleor/payment/utils.py+++ b/saleor/payment/utils.py@@ -74,8 +74,10 @@ def create_payment(**payment_data):def create_transaction(payment: Payment, kind: str, payment_token: str,- gateway_response: Dict, **extra_params) -> Transaction:+ gateway_response: Dict=None, **extra_params) -> Transaction:"""Creates a Transaction based on transaction kind and gateway response."""+ if gateway_response is None:+ gateway_response = {}txn, _ = Transaction.objects.get_or_create(payment=payment,kind=kind,@@ -129,7 +131,7 @@ def call_gateway(Additionally does validation of the returned gateway response."""gateway, gateway_params = get_payment_gateway(payment.gateway)- gateway_response = dict()+ gateway_response = None#TODO: improve so only one argument is sent (dict?) instead of passing# multiple kwargs, eventually keep connection params separate@@ -143,6 +145,7 @@ def call_gateway(logger.exception('Gateway doesn\'t implement %s', func_name)except GatewayError:logger.exception('Gateway response validation failed')+ gateway_response = None # set response none as the validation failedexcept Exception:logger.exception('Gateway encountered an error')finally:@@ -165,8 +168,7 @@ 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', 'gateway_response', 'errors'}+ required_fields = {'transaction_id', 'is_success', 'errors'}if not required_fields.issubset(response):raise GatewayError('Gateway response needs to contain following keys: {}'.format(@@ -296,7 +298,7 @@ def gateway_refund(payment, amount: Decimal=None) -> Transaction:if amount <= 0:raise PaymentError('Amount should be a positive number.')- elif amount > payment.captured_amount:+ if amount > payment.captured_amount:raise PaymentError('Cannot refund more than captured')transaction = payment.transactions.filter(diff --git a/tests/gateway/test_dummy.py b/tests/gateway/test_dummy.pyindex 6c85b43961..0150677979 100644--- a/tests/gateway/test_dummy.py+++ b/tests/gateway/test_dummy.py@@ -12,10 +12,10 @@ from saleor.payment.gateways.dummy.forms import DummyPaymentFormdef test_charge_success(payment_dummy):gateway_charge(payment=payment_dummy, payment_token='fake-token')- charge_txn = payment_dummy.transactions.all()+ charge_txn = payment_dummy.transactions.last()assert charge_txn.is_success- assert charge_txn.kind == TransactionKind.CAPTURE+ assert charge_txn.kind == TransactionKind.CHARGEassert charge_txn.payment == payment_dummyassert charge_txn.amount == payment_dummy.total@@ -215,7 +215,7 @@ def test_refund_gateway_error(payment_txn_captured, monkeypatch):gateway_refund(payment=payment, amount=Decimal('80.00'))payment.refresh_from_db()- txn = payment.transactions.first()+ txn = payment.transactions.last()assert txn.kind == TransactionKind.REFUNDassert not txn.is_successassert txn.payment == payment@@ -223,7 +223,8 @@ def test_refund_gateway_error(payment_txn_captured, monkeypatch):assert payment.captured_amount == Decimal('80.00')[email protected]('This is currently not supported')+ reason='Setting payment status through the form is currently not supported')@pytest.mark.parametrize('kind, charge_status',(diff --git a/tests/test_order.py b/tests/test_order.pyindex 3ef0f25249..1a22014772 100644--- a/tests/test_order.py+++ b/tests/test_order.py@@ -477,7 +477,7 @@ def test_order_payment_flow(assert payment.total == order.total.gross.amountassert payment.currency == order.total.gross.currencyassert payment.transactions.count() == 1- assert payment.transactions.first().kind == 'auth'+ assert payment.transactions.first().kind == 'capture'def test_create_user_after_order(order, client):diff --git a/tests/test_payment.py b/tests/test_payment.pyindex 063b29112e..ce18c7ab9a 100644--- a/tests/test_payment.py+++ b/tests/test_payment.py@@ -5,6 +5,7 @@ import pytestfrom django.conf import settingsfrom django.core.exceptions import ImproperlyConfiguredfrom django.template.loader import get_template+from django.forms.models import model_to_dictfrom saleor.order import OrderEvents, OrderEventsEmailsfrom saleor.order.views import PAYMENT_TEMPLATE@@ -27,10 +28,14 @@ def transaction_data(payment_dummy, settings):'payment': payment_dummy,'payment_token': 'token','kind': TransactionKind.CAPTURE,- 'is_success': True,+ 'amount': Decimal(14.50),'gateway_response': {'is_success': True,- 'credit_cart': '4321'}}+ 'transaction_id': 'token',+ 'errors': None,+ 'raw_response': {+ 'credit_card': '4321',+ 'transaction': 'token'}}}@pytest.fixture@@ -137,10 +142,10 @@ def test_create_transaction(transaction_data):txn = create_transaction(**transaction_data)assert txn.payment == transaction_data['payment']- assert txn.token == transaction_data['token']assert txn.kind == transaction_data['kind']- assert txn.is_success == transaction_data['is_success']assert txn.amount == transaction_data['amount']+ 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']same_txn = create_transaction(**transaction_data)@@ -193,14 +198,18 @@ def test_gateway_authorize(txn = payment_txn_preauth.transactions.first()payment = payment_txn_preauth- mock_authorize = Mock(return_value=(txn, ''))+ mock_authorize = Mock(return_value={+ 'is_success': True,+ 'transaction_id': 'token',+ 'errors': None})mock_get_payment_gateway.return_value = (Mock(authorize=mock_authorize), gateway_params)+ payment_info = model_to_dict(payment)gateway_authorize(payment, payment_token)mock_get_payment_gateway.assert_called_once_with(payment.gateway)mock_authorize.assert_called_once_with(- payment=payment, payment_token=payment_token, **gateway_params)+ payment=payment_info, payment_token=payment_token, **gateway_params)@patch('saleor.payment.utils.get_payment_gateway')@@ -212,7 +221,10 @@ def test_gateway_authorize_failed(txn.is_success = Falsepayment = payment_txn_preauth- mock_authorize = Mock(return_value=(txn, EXAMPLE_ERROR))+ mock_authorize = Mock(return_value={+ 'is_success': False,+ 'transaction_id': 'token',+ 'errors': EXAMPLE_ERROR})mock_get_payment_gateway.return_value = (Mock(authorize=mock_authorize), gateway_params)with pytest.raises(PaymentError) as exc:@@ -240,15 +252,15 @@ def test_gateway_capture(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)+ payment_info = model_to_dict(payment)gateway_capture(payment, amount)mock_get_payment_gateway.assert_called_once_with(payment.gateway)mock_capture.assert_called_once_with(- payment=payment, amount=amount, **gateway_params)+ payment=payment_info, payment_token='', amount=amount, **gateway_params)payment.refresh_from_db()assert payment.charge_status == ChargeStatus.CHARGED@@ -270,7 +282,6 @@ def test_gateway_capture_partial_capture(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)@@ -298,7 +309,6 @@ def test_gateway_capture_failed(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)@@ -342,15 +352,16 @@ def test_gateway_charge(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)+ payment_info = model_to_dict(payment)gateway_charge(payment, payment_token, amount)mock_get_payment_gateway.assert_called_once_with(payment.gateway)mock_charge.assert_called_once_with(- payment=payment, payment_token=payment_token, amount=amount, **gateway_params)+ payment=payment_info, payment_token=payment_token, amount=amount,+ **gateway_params)payment.refresh_from_db()assert payment.charge_status == ChargeStatus.CHARGED@@ -373,7 +384,6 @@ def test_gateway_capture_partial_charge(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)@@ -402,7 +412,6 @@ def test_gateway_charge_failed(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)@@ -441,13 +450,17 @@ def test_gateway_void(mock_get_payment_gateway, payment_txn_preauth, gateway_parpayment = payment_txn_preauthassert payment.is_active- mock_void = Mock(return_value=(True, {}, ''))+ mock_void = Mock(return_value={+ 'is_success': True,+ 'transaction_id': 'token',+ 'errors': None})mock_get_payment_gateway.return_value = (Mock(void=mock_void), gateway_params)+ payment_info = model_to_dict(payment)gateway_void(payment)mock_get_payment_gateway.assert_called_once_with(payment.gateway)mock_void.assert_called_once_with(- payment_token=txn.transaction_id, **gateway_params)+ payment=payment_info, payment_token=txn.token, **gateway_params)payment.refresh_from_db()assert payment.is_active == False@@ -460,7 +473,10 @@ def test_gateway_void_failed(txn.is_success = Falsepayment = payment_txn_preauth- mock_void = Mock(return_value=(False, {}, EXAMPLE_ERROR))+ mock_void = Mock(return_value={+ 'is_success': False,+ 'transaction_id': 'token',+ 'errors': EXAMPLE_ERROR})mock_get_payment_gateway.return_value = (Mock(void=mock_void), gateway_params)with pytest.raises(PaymentError) as exc:gateway_void(payment)@@ -484,14 +500,19 @@ def test_gateway_refund(payment = payment_txn_capturedamount = payment.total- mock_refund = Mock(return_value=(True, {}, ''))+ mock_refund = Mock(return_value={+ 'is_success': True,+ 'transaction_id': 'token',+ 'errors': None})mock_get_payment_gateway.return_value = (Mock(refund=mock_refund), gateway_params)+ payment_info = model_to_dict(payment)gateway_refund(payment, amount)mock_get_payment_gateway.assert_called_once_with(payment.gateway)mock_refund.assert_called_once_with(- payment=payment, amount=amount, **gateway_params)+ payment=payment_info, payment_token='',+ amount=amount, **gateway_params)payment.refresh_from_db()assert payment.charge_status == ChargeStatus.FULLY_REFUNDED@@ -507,7 +528,10 @@ def test_gateway_refund_partial_refund(txn.amount = amounttxn.currency = settings.DEFAULT_CURRENCY- mock_refund = Mock(return_value=(True, {}, ''))+ mock_refund = Mock(return_value={+ 'is_success': True,+ 'transaction_id': 'token',+ 'errors': None})mock_get_payment_gateway.return_value = (Mock(refund=mock_refund), gateway_params)@@ -526,7 +550,10 @@ def test_gateway_refund_failed(captured_before = payment.captured_amounttxn.is_success = False- mock_refund = Mock(return_value=(False, {}, EXAMPLE_ERROR))+ mock_refund = Mock(return_value={+ 'is_success': False,+ 'transaction_id': 'token',+ 'errors': EXAMPLE_ERROR})mock_get_payment_gateway.return_value = (Mock(refund=mock_refund), gateway_params)