Skip to content

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

Test payments gateway

Pacu2282ef50477e5
diff --git a/saleor/payment/__init__.py b/saleor/payment/__init__.py
index 1db12fb3f8..88b636389d 100644
--- a/saleor/payment/__init__.py
+++ b/saleor/payment/__init__.py
@@ -6,7 +6,10 @@ from django.utils.translation import pgettext_lazy
class PaymentError(Exception):
- pass
+
+ def __init__(self, message):
+ super(PaymentError, self).__init__(message)
+ self.message = message
class TransactionType:
diff --git a/saleor/payment/providers/braintree/__init__.py b/saleor/payment/providers/braintree/__init__.py
index 931bbbca47..5a447538af 100644
--- a/saleor/payment/providers/braintree/__init__.py
+++ b/saleor/payment/providers/braintree/__init__.py
@@ -6,6 +6,7 @@ import braintree as braintree_sdk
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
from django.utils.translation import pgettext_lazy
+from prices import Money
from ... import TransactionType
from ...models import Payment, Transaction
@@ -64,7 +65,9 @@ def transaction_and_incorrect_token_error(
token: str,
type: TransactionType,
amount: Decimal = None) -> Tuple[Transaction, str]:
- amount = payment.total.amount if amount is None else amount
+ amount = (
+ payment.total
+ if amount is None else Money(amount, settings.DEFAULT_CURRENCY))
txn = create_transaction(
payment=payment,
transaction_type=type,
@@ -156,7 +159,7 @@ def authorize(
txn = create_transaction(
payment=payment,
transaction_type=TransactionType.AUTH,
- amount=payment.total.amount,
+ amount=payment.total,
gateway_response=gateway_response,
token=getattr(result.transaction, 'id', ''),
is_success=result.is_success)
@@ -186,7 +189,7 @@ def capture(
txn = create_transaction(
payment=payment,
transaction_type=TransactionType.CAPTURE,
- amount=amount,
+ amount=Money(amount, settings.DEFAULT_CURRENCY),
token=getattr(result.transaction, 'id', ''),
is_success=result.is_success,
gateway_response=gateway_response)
@@ -211,7 +214,7 @@ def void(
txn = create_transaction(
payment=payment,
transaction_type=TransactionType.VOID,
- amount=payment.total.amount,
+ amount=payment.total,
gateway_response=gateway_response,
token=getattr(result.transaction, 'id', ''),
is_success=result.is_success)
@@ -239,7 +242,7 @@ def refund(
txn = create_transaction(
payment=payment,
transaction_type=TransactionType.REFUND,
- amount=amount,
+ amount=Money(amount, settings.DEFAULT_CURRENCY),
token=getattr(result.transaction, 'id', ''),
is_success=result.is_success,
gateway_response=gateway_response)
diff --git a/saleor/payment/providers/dummy/__init__.py b/saleor/payment/providers/dummy/__init__.py
index 75bf985e06..8c79555b0f 100644
--- a/saleor/payment/providers/dummy/__init__.py
+++ b/saleor/payment/providers/dummy/__init__.py
@@ -1,6 +1,12 @@
import uuid
+from decimal import Decimal
+from typing import Dict
+
+from django.conf import settings
+from prices import Money
from ... import TransactionType
+from ...models import Payment
from ...utils import create_transaction
@@ -12,7 +18,7 @@ def get_transaction_token(**connection_params):
return str(uuid.uuid4())
-def authorize(payment, transaction_token, **connection_params):
+def authorize(payment: Payment, transaction_token: str, **connection_params):
success = dummy_success()
error = None
if not success:
@@ -27,7 +33,7 @@ def authorize(payment, transaction_token, **connection_params):
return txn, error
-def void(payment, **connection_params):
+def void(payment: Payment, **connection_params: Dict):
error = None
success = dummy_success()
if not success:
@@ -42,7 +48,7 @@ def void(payment, **connection_params):
return txn, error
-def capture(payment, amount):
+def capture(payment: Payment, amount: Decimal):
error = None
success = dummy_success()
if not success:
@@ -50,13 +56,13 @@ def capture(payment, amount):
txn = create_transaction(
payment=payment,
transaction_type=TransactionType.CAPTURE,
- amount=amount,
+ amount=Money(amount, settings.DEFAULT_CURRENCY),
token=str(uuid.uuid4()),
is_success=success)
return txn, error
-def refund(payment, amount):
+def refund(payment: Payment, amount: Decimal):
error = None
success = dummy_success()
if not success:
@@ -64,7 +70,7 @@ def refund(payment, amount):
txn = create_transaction(
payment=payment,
transaction_type=TransactionType.REFUND,
- amount=amount,
+ amount=Money(amount, settings.DEFAULT_CURRENCY),
token=str(uuid.uuid4()),
is_success=success)
return txn, error
diff --git a/saleor/payment/utils.py b/saleor/payment/utils.py
index 126d2cfe0a..290f7438e6 100644
--- a/saleor/payment/utils.py
+++ b/saleor/payment/utils.py
@@ -73,7 +73,7 @@ def create_transaction(
token: str,
transaction_type: str,
is_success: bool,
- amount: Decimal,
+ amount: Money,
gateway_response: Optional[Dict] = None) -> Transaction:
if not gateway_response:
gateway_response = {}
@@ -103,12 +103,8 @@ def gateway_authorize(payment: Payment, transaction_token: str) -> Transaction:
with transaction.atomic():
txn, error = provider.authorize(
payment, transaction_token, **provider_params)
- if txn.is_success:
- payment.charge_status = ChargeStatus.NOT_CHARGED
- payment.save(update_fields=['charge_status'])
# FIXME Create an order event ?
if not txn.is_success:
- # TODO: Handle gateway response here somehow
raise PaymentError(error)
return txn
@@ -130,15 +126,13 @@ def gateway_capture(payment: Payment, amount: Decimal) -> Transaction:
payment, amount=amount, **provider_params)
if txn.is_success:
payment.charge_status = ChargeStatus.CHARGED
- payment.captured_amount += Money(
- txn.amount, settings.DEFAULT_CURRENCY)
+ payment.captured_amount += txn.amount
payment.save(update_fields=['charge_status', 'captured_amount'])
order = payment.order
if order and order.is_fully_paid():
handle_fully_paid_order(order)
# FIXME Create an order event ?
if not txn.is_success:
- # TODO: Handle gateway response here somehow
raise PaymentError(error)
return txn
@@ -146,7 +140,7 @@ def gateway_capture(payment: Payment, amount: Decimal) -> Transaction:
@validate_payment
def gateway_void(payment) -> Transaction:
if not can_be_voided(payment):
- raise PaymentError('Only pre-authorized transactions can be void.')
+ raise PaymentError('Only pre-authorized transactions can be voided.')
provider, provider_params = get_provider(payment.variant)
with transaction.atomic():
txn, error = provider.void(payment, **provider_params)
@@ -174,12 +168,11 @@ def gateway_refund(payment, amount: Decimal) -> Transaction:
txn, error = provider.refund(payment, amount, **provider_params)
if txn.is_success:
changed_fields = ['captured_amount']
- if txn.amount == payment.total.amount:
+ if txn.amount == payment.total:
payment.charge_status = ChargeStatus.FULLY_REFUNDED
payment.is_active = False
changed_fields += ['charge_status', 'is_active']
- payment.captured_amount -= Money(
- txn.amount, settings.DEFAULT_CURRENCY)
+ payment.captured_amount -= txn.amount
payment.save(update_fields=changed_fields)
# FIXME Create an order event ?
if not txn.is_success:
diff --git a/tests/test_payment.py b/tests/test_payment.py
index a912175a3f..3fc64896ee 100644
--- a/tests/test_payment.py
+++ b/tests/test_payment.py
@@ -1,156 +1,408 @@
+from decimal import Decimal
+from unittest.mock import Mock, patch
+
import pytest
+from django.core.exceptions import ImproperlyConfigured
+from prices import Money
-from saleor.payment import ChargeStatus, PaymentError, TransactionType
+from saleor.order import OrderEvents, OrderEventsEmails
+from saleor.payment import (
+ ChargeStatus, PaymentError, TransactionType, get_provider)
+from saleor.payment.utils import (
+ create_payment, create_transaction, gateway_authorize, gateway_capture,
+ gateway_get_transaction_token, gateway_refund, gateway_void,
+ get_billing_data, handle_fully_paid_order, validate_payment)
-from .utils import money
+NOT_ACTIVE_PAYMENT_ERROR = 'This payment is no longer active.'
+EXAMPLE_ERROR = 'Example dummy error'
-def test_authorize(payment_dummy):
- txn = payment_dummy.authorize(transaction_token='Fake')
- assert txn.is_success
- assert txn.transaction_type == TransactionType.AUTH
- assert txn.payment == payment_dummy
- payment_dummy.refresh_from_db()
- assert payment_dummy.is_active
+def transaction_data(payment_dummy):
+ return {
+ 'payment': payment_dummy,
+ 'token': 'token',
+ 'transaction_type': TransactionType.CAPTURE,
+ 'is_success': True,
+ 'amount': Decimal('10.00'),
+ 'gateway_response': {
+ 'credit_cart': '4321'}}
-def test_authorize_gateway_error(payment_dummy, monkeypatch):
- monkeypatch.setattr(
- 'saleor.payment.providers.dummy.dummy_success', lambda: False)
- with pytest.raises(PaymentError):
- txn = payment_dummy.authorize(transaction_token='Fake')
- assert txn.transaction_type == TransactionType.AUTH
- assert not txn.is_success
- assert txn.payment == payment_dummy
+def provider_params():
+ return {'secret-key': 'nobodylikesspanishinqusition'}
-def test_void_success(payment_dummy):
- assert payment_dummy.is_active
- assert payment_dummy.charge_status == ChargeStatus.NOT_CHARGED
- txn = payment_dummy.void()
- assert txn.is_success
- assert txn.transaction_type == TransactionType.VOID
- assert txn.payment == payment_dummy
- payment_dummy.refresh_from_db()
- assert not payment_dummy.is_active
- assert payment_dummy.charge_status == ChargeStatus.NOT_CHARGED
+def transaction_token():
+ return 'transaction-token'
- 'is_active, charge_status', [
- (False, ChargeStatus.NOT_CHARGED),
- (False, ChargeStatus.CHARGED),
- (True, ChargeStatus.CHARGED),
- (True, ChargeStatus.FULLY_REFUNDED), ])
-def test_void_failed(is_active, charge_status, payment_dummy):
- payment = payment_dummy
- payment.is_active = is_active
- payment.charge_status = charge_status
- payment.save()
- with pytest.raises(PaymentError):
- txn = payment.void()
- assert txn is None
+def test_get_billing_data(order):
+ assert order.billing_address
+ result = get_billing_data(order)
+ expected_result = {
+ 'billing_first_name': order.billing_address.first_name,
+ 'billing_last_name': order.billing_address.last_name,
+ 'billing_company_name': order.billing_address.company_name,
+ 'billing_address_1': order.billing_address.street_address_1,
+ 'billing_address_2': order.billing_address.street_address_2,
+ 'billing_city': order.billing_address.city,
+ 'billing_postal_code': order.billing_address.postal_code,
+ 'billing_country_code': order.billing_address.country.code,
+ 'billing_email': order.user_email,
+ 'billing_country_area': order.billing_address.country_area}
+ assert result == expected_result
+ order.billing_address = None
+ assert get_billing_data(order) == {}
-def test_void_gateway_error(payment_dummy, monkeypatch):
- monkeypatch.setattr(
- 'saleor.payment.providers.dummy.dummy_success', lambda: False)
- with pytest.raises(PaymentError):
- txn = payment_dummy.void()
- assert txn.transaction_type == TransactionType.VOID
- assert not txn.is_success
- assert txn.payment == payment_dummy
+def test_get_provider_non_existing_name():
+ with pytest.raises(ImproperlyConfigured):
+ get_provider('Non existing provider')
[email protected]('amount', [80, 70])
-def test_charge_success(amount, payment_dummy):
- txn = payment_dummy.capture(amount=amount)
- assert txn.is_success
- assert txn.payment == payment_dummy
- payment_dummy.refresh_from_db()
- assert payment_dummy.charge_status == ChargeStatus.CHARGED
- assert payment_dummy.is_active
+def test_get_provider(settings):
+ provider_name = list(settings.PAYMENT_PROVIDERS.keys())[0]
+ provider = settings.PAYMENT_PROVIDERS[provider_name]
+ provider_module, provider_params = get_provider(provider_name)
+ assert provider_module.__name__ == provider['module']
+ assert provider_params == provider['connection_params']
- 'amount, captured_amount, charge_status, is_active', [
- (80, money(0), ChargeStatus.NOT_CHARGED, False),
- (80, money(0), ChargeStatus.FULLY_REFUNDED, True),
- (80, money(80), ChargeStatus.CHARGED, True),
- (120, money(0), ChargeStatus.NOT_CHARGED, True), ])
-def test_charge_failed(
- amount, captured_amount, charge_status, is_active,
- payment_dummy):
- payment = payment_dummy
- payment.is_active = is_active
- payment.captured_amount = captured_amount
- payment.charge_status = charge_status
- payment.save()
- with pytest.raises(PaymentError):
- txn = payment.capture(amount=amount)
- assert txn is None
+@patch('saleor.order.emails.send_payment_confirmation.delay')
+def test_handle_fully_paid_order_no_email(
+ mock_send_payment_confirmation, order):
+ order.user = None
+ order.user_email = ''
+
+ handle_fully_paid_order(order)
+ event = order.events.get()
+ assert event.type == OrderEvents.ORDER_FULLY_PAID.value
+ assert not mock_send_payment_confirmation.called
+
+
+@patch('saleor.order.emails.send_payment_confirmation.delay')
+def test_handle_fully_paid_order(mock_send_payment_confirmation, order):
+ handle_fully_paid_order(order)
+ event_order_paid, event_email_sent = order.events.all()
+ assert event_order_paid.type == OrderEvents.ORDER_FULLY_PAID.value
+
+ assert event_email_sent.type == OrderEvents.EMAIL_SENT.value
+ assert event_email_sent.parameters == {
+ 'email': order.get_user_current_email(),
+ 'email_type': OrderEventsEmails.PAYMENT.value}
-def test_charge_gateway_error(payment_dummy, monkeypatch):
- monkeypatch.setattr(
- 'saleor.payment.providers.dummy.dummy_success', lambda: False)
+ mock_send_payment_confirmation.assert_called_once_with(order.pk)
+
+
+def test_validate_payment():
+ @validate_payment
+ def test_function(payment, *args, **kwargs):
+ return True
+
+ payment = Mock(is_active=True)
+ test_function(payment)
+
+ non_active_payment = Mock(is_active=False)
with pytest.raises(PaymentError):
- txn = payment_dummy.capture(80)
- assert txn.transaction_type == TransactionType.CHARGE
- assert not txn.is_success
- assert txn.payment == payment_dummy
+ test_function(non_active_payment)
- 'initial_captured_amount, refund_amount, final_captured_amount, final_charge_status, active_after',
- [
- (money(80), 80, money(0), ChargeStatus.FULLY_REFUNDED, False),
- (money(80), 10, money(70), ChargeStatus.CHARGED, True), ])
-def test_refund_success(
- initial_captured_amount, refund_amount, final_captured_amount,
- final_charge_status, active_after, payment_dummy):
- payment = payment_dummy
- payment.charge_status = ChargeStatus.CHARGED
- payment.captured_amount = initial_captured_amount
- payment.save()
- txn = payment.refund(refund_amount)
- assert txn.transaction_type == TransactionType.REFUND
- assert txn.is_success
- assert txn.payment == payment
- assert payment.charge_status == final_charge_status
- assert payment.captured_amount == final_captured_amount
- assert payment.is_active == active_after
+def test_create_payment():
+ data = {'variant': 'default'}
+ payment = create_payment(**data)
+ assert payment.variant == 'default'
+
+ same_payment = create_payment(**data)
+ assert payment == same_payment
+
+
+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.transaction_type == transaction_data['transaction_type']
+ assert txn.is_success == transaction_data['is_success']
+ assert txn.amount == transaction_data['amount']
+ assert txn.gateway_response == transaction_data['gateway_response']
+
+ same_txn = create_transaction(**transaction_data)
+ assert txn == same_txn
+
+
+def test_create_transaction_no_gateway_response(transaction_data):
+ transaction_data.pop('gateway_response')
+ txn = create_transaction(**transaction_data)
+ assert txn.gateway_response == {}
+
+
+def test_gateway_get_transaction_token(settings):
+ provider_name = list(settings.PAYMENT_PROVIDERS.keys())[0]
+ provider = settings.PAYMENT_PROVIDERS[provider_name]
+ module = provider['module']
+ with patch('%s.get_transaction_token' % module) as transaction_token_mock:
+ gateway_get_transaction_token(provider_name)
+ transaction_token_mock.assert_called_once()
+
+
+def test_gateway_get_transaction_token_not_existing_provider():
+ with pytest.raises(ImproperlyConfigured):
+ gateway_get_transaction_token('Non existent provider')
@pytest.mark.parametrize(
- 'initial_captured_amount, refund_amount, initial_charge_status', [
- (money(80), 0, ChargeStatus.FULLY_REFUNDED),
- (money(0), 10, ChargeStatus.NOT_CHARGED),
- (money(10), 20, ChargeStatus.CHARGED), ])
-def test_refund_failed(
- initial_captured_amount, refund_amount, initial_charge_status,
- payment_dummy):
- payment = payment_dummy
- payment.charge_status = initial_charge_status
- payment.captured_amount = initial_captured_amount
- payment.save()
- with pytest.raises(PaymentError):
- txn = payment.refund(refund_amount)
- assert txn is None
+ 'func', [gateway_authorize, gateway_capture, gateway_refund, gateway_void])
+def test_payment_needs_to_be_active_for_any_action(func, payment_dummy):
+ payment_dummy.is_active = False
+ with pytest.raises(PaymentError) as exc:
+ func(payment_dummy, 'transaction-token')
+ assert exc.value.message == NOT_ACTIVE_PAYMENT_ERROR
-def test_refund_gateway_error(payment_dummy, monkeypatch):
- monkeypatch.setattr(
- 'saleor.payment.providers.dummy.dummy_success', lambda: False)
- payment = payment_dummy
- payment.charge_status = ChargeStatus.CHARGED
- payment.captured_amount = money(80)
- payment.save()
- with pytest.raises(PaymentError):
- txn = payment.refund(80)
- payment.refresh_from_db()
- assert txn.transaction_type == TransactionType.REFUND
- assert not txn.is_success
- assert txn.payment == payment
- assert payment.charge_status == ChargeStatus.CHARGED
- assert payment.captured_amount == money(80)
+def test_gateway_authorize_errors(payment_dummy):
+ payment_dummy.charge_status = ChargeStatus.CHARGED
+ with pytest.raises(PaymentError) as exc:
+ gateway_authorize(payment_dummy, 'transaction-token')
+ assert exc.value.message == (
+ 'Charged transactions cannot be authorized again.')
+
+
+@patch('saleor.payment.utils.get_provider')
+def test_gateway_authorize(
+ mock_get_provider, payment_txn_preauth, provider_params,
+ transaction_token):
+ txn = payment_txn_preauth.transactions.first()
+ payment = payment_txn_preauth
+
+ mock_authorize = Mock(return_value=(txn, ''))
+ mock_get_provider.return_value = (
+ Mock(authorize=mock_authorize), provider_params)
+
+ gateway_authorize(payment, transaction_token)
+ mock_get_provider.assert_called_once_with(payment.variant)
+ mock_authorize.assert_called_once_with(
+ payment, transaction_token, **provider_params)
+
+
+@patch('saleor.payment.utils.get_provider')
+def test_gateway_authorize_failed(
+ mock_get_provider, payment_txn_preauth, provider_params,
+ transaction_token):
+ txn = payment_txn_preauth.transactions.first()
+ txn.is_success = False
+ payment = payment_txn_preauth
+
+ mock_authorize = Mock(return_value=(txn, EXAMPLE_ERROR))
+ mock_get_provider.return_value = (
+ Mock(authorize=mock_authorize), provider_params)
+ with pytest.raises(PaymentError) as exc:
+ gateway_authorize(payment, transaction_token)
+ assert exc.value.message == EXAMPLE_ERROR
+
+
+@patch('saleor.payment.utils.handle_fully_paid_order')
+@patch('saleor.payment.utils.get_provider')
+def test_gateway_capture(
+ mock_get_provider, mock_handle_fully_paid_order, payment_txn_preauth,
+ provider_params):
+ txn = payment_txn_preauth.transactions.first()
+ payment = payment_txn_preauth
+ assert not payment.captured_amount
+ amount = payment.total.amount
+
+ mock_capture = Mock(return_value=(txn, ''))
+ mock_get_provider.return_value = (
+ Mock(capture=mock_capture), provider_params)
+
+ gateway_capture(payment, amount)
+ mock_get_provider.assert_called_once_with(payment.variant)
+ mock_capture.assert_called_once_with(
+ payment, amount=amount, **provider_params)
+
+ payment.refresh_from_db()
+ assert payment.charge_status == ChargeStatus.CHARGED
+ assert payment.captured_amount == payment.total
+ mock_handle_fully_paid_order.assert_called_once_with(payment.order)
+
+
+@patch('saleor.payment.utils.handle_fully_paid_order')
+@patch('saleor.payment.utils.get_provider')
+def test_gateway_capture_partial_capture(
+ mock_get_provider, mock_handle_fully_paid_order, payment_txn_preauth,
+ provider_params, settings):
+ payment = payment_txn_preauth
+ amount = payment.total.amount * Decimal('0.5')
+ txn = payment.transactions.first()
+ txn.amount = Money(amount, settings.DEFAULT_CURRENCY)
+
+ mock_capture = Mock(return_value=(txn, ''))
+ mock_get_provider.return_value = (
+ Mock(capture=mock_capture), provider_params)
+
+ gateway_capture(payment, amount)
+
+ payment.refresh_from_db()
+ assert payment.charge_status == ChargeStatus.CHARGED
+ assert payment.captured_amount == Money(amount, settings.DEFAULT_CURRENCY)
+ assert not mock_handle_fully_paid_order.called
+
+
+@patch('saleor.payment.utils.handle_fully_paid_order')
+@patch('saleor.payment.utils.get_provider')
+def test_gateway_capture_failed(
+ mock_get_provider, mock_handle_fully_paid_order, payment_txn_preauth,
+ provider_params):
+ txn = payment_txn_preauth.transactions.first()
+ txn.is_success = False
+
+ payment = payment_txn_preauth
+ amount = payment.total.amount
+
+ mock_capture = Mock(return_value=(txn, EXAMPLE_ERROR))
+ mock_get_provider.return_value = (
+ Mock(capture=mock_capture), provider_params)
+ with pytest.raises(PaymentError) as exc:
+ gateway_capture(payment, amount)
+ assert exc.value.message == EXAMPLE_ERROR
+ payment.refresh_from_db()
+ assert payment.charge_status == ChargeStatus.NOT_CHARGED
+ assert not payment.captured_amount
+ assert not mock_handle_fully_paid_order.called
+
+
+def test_gateway_capture_errors(payment_dummy):
+ with pytest.raises(PaymentError) as exc:
+ gateway_capture(payment_dummy, Decimal('0'))
+ assert exc.value.message == 'Amount should be a positive number.'
+
+ payment_dummy.charge_status = ChargeStatus.FULLY_REFUNDED
+ with pytest.raises(PaymentError) as exc:
+ gateway_capture(payment_dummy, Decimal('10'))
+ assert exc.value.message == 'This payment cannot be captured.'
+
+ payment_dummy.charge_status = ChargeStatus.NOT_CHARGED
+ with pytest.raises(PaymentError) as exc:
+ gateway_capture(payment_dummy, Decimal('1000000'))
+ assert exc.value.message == (
+ 'Unable to capture more than authorized amount.')
+
+
+@patch('saleor.payment.utils.get_provider')
+def test_gateway_void(mock_get_provider, payment_txn_preauth, provider_params):
+ txn = payment_txn_preauth.transactions.first()
+ payment = payment_txn_preauth
+ assert payment.is_active
+
+ mock_void = Mock(return_value=(txn, ''))
+ mock_get_provider.return_value = (Mock(void=mock_void), provider_params)
+
+ gateway_void(payment)
+ mock_get_provider.assert_called_once_with(payment.variant)
+ mock_void.assert_called_once_with(payment, **provider_params)
+
+ payment.refresh_from_db()
+ assert payment.is_active == False
+
+
+@patch('saleor.payment.utils.get_provider')
+def test_gateway_void_failed(
+ mock_get_provider, payment_txn_preauth, provider_params):
+ txn = payment_txn_preauth.transactions.first()
+ txn.is_success = False
+ payment = payment_txn_preauth
+
+ mock_void = Mock(return_value=(txn, EXAMPLE_ERROR))
+ mock_get_provider.return_value = (Mock(void=mock_void), provider_params)
+ with pytest.raises(PaymentError) as exc:
+ gateway_void(payment)
+ assert exc.value.message == EXAMPLE_ERROR
+
+ payment.refresh_from_db()
+ assert payment.is_active
+
+
+def test_gateway_void_errors(payment_dummy):
+ payment_dummy.charge_status = ChargeStatus.CHARGED
+ with pytest.raises(PaymentError) as exc:
+ gateway_void(payment_dummy)
+ exc.value.message == 'Only pre-authorized transactions can be voided.'
+
+
+@patch('saleor.payment.utils.get_provider')
+def test_gateway_refund(
+ mock_get_provider, payment_txn_captured, provider_params):
+ txn = payment_txn_captured.transactions.first()
+ payment = payment_txn_captured
+ amount = payment.total.amount
+
+ mock_refund = Mock(return_value=(txn, ''))
+ mock_get_provider.return_value = (
+ Mock(refund=mock_refund), provider_params)
+
+ gateway_refund(payment, amount)
+ mock_get_provider.assert_called_once_with(payment.variant)
+ mock_refund.assert_called_once_with(payment, amount, **provider_params)
+
+ payment.refresh_from_db()
+ assert payment.charge_status == ChargeStatus.FULLY_REFUNDED
+ assert not payment.captured_amount
+
+
+@patch('saleor.payment.utils.get_provider')
+def test_gateway_refund_partial_refund(
+ mock_get_provider, payment_txn_captured, provider_params, settings):
+ payment = payment_txn_captured
+ amount = payment.total.amount * Decimal('0.5')
+ txn = payment_txn_captured.transactions.first()
+ txn.amount = Money(amount, settings.DEFAULT_CURRENCY)
+
+ mock_refund = Mock(return_value=(txn, ''))
+ mock_get_provider.return_value = (
+ Mock(refund=mock_refund), provider_params)
+
+ gateway_refund(payment, amount)
+
+ payment.refresh_from_db()
+ assert payment.charge_status == ChargeStatus.CHARGED
+ assert payment.captured_amount == payment.total - Money(
+ amount, settings.DEFAULT_CURRENCY)
+
+
+@patch('saleor.payment.utils.get_provider')
+def test_gateway_refund_failed(
+ mock_get_provider, payment_txn_captured, provider_params, settings):
+ txn = payment_txn_captured.transactions.first()
+ payment = payment_txn_captured
+ captured_before = payment.captured_amount
+ txn.is_success = False
+
+ mock_refund = Mock(return_value=(txn, EXAMPLE_ERROR))
+ mock_get_provider.return_value = (
+ Mock(refund=mock_refund), provider_params)
+
+ with pytest.raises(PaymentError) as exc:
+ gateway_refund(payment, Decimal('10.00'))
+ exc.value.message == EXAMPLE_ERROR
+ payment.refresh_from_db()
+ assert payment.captured_amount == captured_before
+
+
+def test_gateway_refund_errors(payment_txn_captured):
+ payment = payment_txn_captured
+ with pytest.raises(PaymentError) as exc:
+ gateway_refund(payment, Decimal('1000000'))
+ assert exc.value.message == 'Cannot refund more than captured'
+
+ with pytest.raises(PaymentError) as exc:
+ gateway_refund(payment, Decimal('0'))
+ assert exc.value.message == 'Amount should be a positive number.'
+
+ payment.charge_status = ChargeStatus.NOT_CHARGED
+ with pytest.raises(PaymentError) as exc:
+ gateway_refund(payment, Decimal('1'))
+ assert exc.value.message == (
+ 'Refund is possible only when transaction is captured.')
diff --git a/tests/test_payment_braintree.py b/tests/test_payment_braintree.py
index 1842ee78f9..2d72f148c1 100644
--- a/tests/test_payment_braintree.py
+++ b/tests/test_payment_braintree.py
@@ -8,6 +8,7 @@ from braintree.errors import Errors
from braintree.exceptions import NotFoundError
from braintree.validation_error import ValidationError
from django.core.exceptions import ImproperlyConfigured
+from prices import Money
from saleor.payment import TransactionType
from saleor.payment.providers.braintree import (
@@ -234,7 +235,7 @@ def test_authorize(
assert txn.payment == payment
assert txn.transaction_type == TransactionType.AUTH
- assert txn.amount == payment.total.amount
+ assert txn.amount == payment.total
assert txn.gateway_response == extract_gateway_response(
braintree_success_response)
assert txn.token == braintree_success_response.transaction.id
@@ -253,7 +254,8 @@ def test_authorize(
@pytest.mark.integration
@patch('saleor.payment.providers.braintree.get_gateway')
def test_refund(
- mock_gateway, payment_txn_captured, braintree_success_response):
+ mock_gateway, payment_txn_captured, braintree_success_response,
+ settings):
payment = payment_txn_captured
amount = Decimal('10.00')
mock_response = Mock(return_value=braintree_success_response)
@@ -263,7 +265,7 @@ def test_refund(
assert txn.payment == payment
assert txn.transaction_type == TransactionType.REFUND
- assert txn.amount == amount
+ assert txn.amount == Money(amount, settings.DEFAULT_CURRENCY)
assert txn.gateway_response == extract_gateway_response(
braintree_success_response)
assert txn.token == braintree_success_response.transaction.id
@@ -315,7 +317,8 @@ def test_refund_error_response(
@pytest.mark.integration
@patch('saleor.payment.providers.braintree.get_gateway')
def test_capture(
- mock_gateway, payment_txn_preauth, braintree_success_response):
+ mock_gateway, payment_txn_preauth, braintree_success_response,
+ settings):
payment = payment_txn_preauth
amount = Decimal('10.00')
mock_response = Mock(return_value=braintree_success_response)
@@ -327,7 +330,7 @@ def test_capture(
assert txn.payment == payment
assert txn.transaction_type == TransactionType.CAPTURE
- assert txn.amount == amount
+ assert txn.amount == Money(amount, settings.DEFAULT_CURRENCY)
assert txn.gateway_response == extract_gateway_response(
braintree_success_response)
assert txn.token == braintree_success_response.transaction.id
@@ -392,7 +395,7 @@ def test_void(
assert txn.payment == payment
assert txn.transaction_type == TransactionType.VOID
- assert txn.amount == payment.total.amount
+ assert txn.amount == payment.total
assert txn.gateway_response == extract_gateway_response(
braintree_success_response)
assert txn.token == braintree_success_response.transaction.id
@@ -437,7 +440,7 @@ def test_void_error_response(
assert error == DEFAULT_ERROR
-def test_transaction_and_incorrect_token_error_helper(payment_dummy):
+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', TransactionType.AUTH, amount=amount)
@@ -446,10 +449,10 @@ def test_transaction_and_incorrect_token_error_helper(payment_dummy):
assert txn.transaction_type == TransactionType.AUTH
assert txn.token == 'example-token'
assert not txn.gateway_response
- assert txn.amount == amount
+ assert txn.amount == Money(amount, 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', TransactionType.AUTH)
- assert txn.amount == payment_dummy.total.amount
+ assert txn.amount == payment_dummy.total