Skip to content

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

Switch use to the new gateway for void payment method

Jakub Draganeka0744ccf93c2
diff --git a/saleor/core/utils/random_data.py b/saleor/core/utils/random_data.py
index 34816d5dfd..59d4451bca 100644
--- a/saleor/core/utils/random_data.py
+++ b/saleor/core/utils/random_data.py
@@ -31,12 +31,12 @@ from ...menu.utils import update_menu
from ...order.models import Fulfillment, Order, OrderLine
from ...order.utils import update_order_status
from ...page.models import Page
+from ...payment import gateway
from ...payment.utils import (
create_payment,
gateway_authorize,
gateway_capture,
gateway_refund,
- gateway_void,
)
from ...product.models import (
AssignedProductAttribute,
@@ -62,7 +62,6 @@ from ...product.thumbnails import (
from ...shipping.models import ShippingMethod, ShippingMethodType, ShippingZone
fake = Factory.create()
-
PRODUCTS_LIST_DIR = "products-list/"
IMAGES_MAPPING = {
@@ -393,7 +392,7 @@ def create_fake_payment(mock_email_confirmation, order):
gateway_authorize(payment, payment.token)
# 20% chance to void the transaction at this stage
if random.choice([0, 0, 0, 0, 1]):
- gateway_void(payment)
+ gateway.void(payment)
return payment
# 25% to end the payment at the authorization stage
if not random.choice([1, 1, 1, 0]):
diff --git a/saleor/dashboard/order/forms.py b/saleor/dashboard/order/forms.py
index 652a796275..99055804f1 100644
--- a/saleor/dashboard/order/forms.py
+++ b/saleor/dashboard/order/forms.py
@@ -25,12 +25,11 @@ from ...order.utils import (
fulfill_order_line,
recalculate_order,
)
-from ...payment import ChargeStatus, CustomPaymentChoices, PaymentError
+from ...payment import ChargeStatus, CustomPaymentChoices, PaymentError, gateway
from ...payment.utils import (
clean_mark_order_as_paid,
gateway_capture,
gateway_refund,
- gateway_void,
mark_order_as_paid,
)
from ...product.models import Product, ProductVariant
@@ -388,7 +387,7 @@ class VoidPaymentForm(BasePaymentForm):
raise forms.ValidationError(self.clean_error)
def void(self, user):
- return self.try_payment_action(user, gateway_void)
+ return self.try_payment_action(user, gateway.void)
class OrderMarkAsPaidForm(forms.Form):
diff --git a/saleor/graphql/checkout/mutations.py b/saleor/graphql/checkout/mutations.py
index 2346c525a4..63efc04a65 100644
--- a/saleor/graphql/checkout/mutations.py
+++ b/saleor/graphql/checkout/mutations.py
@@ -29,8 +29,7 @@ from ...core import analytics
from ...core.exceptions import InsufficientStock
from ...core.taxes import TaxError
from ...discount import models as voucher_model
-from ...payment import PaymentError
-from ...payment.gateway import PaymentGateway
+from ...payment import PaymentError, gateway
from ...payment.interface import AddressData
from ...payment.utils import store_customer_id
from ...product import models as product_models
@@ -643,7 +642,6 @@ class CheckoutComplete(BaseMutation):
info, checkout_id, only_type=Checkout, field="checkout_id"
)
- gateway = PaymentGateway()
user = info.context.user
clean_checkout(checkout, info.context.discounts)
diff --git a/saleor/graphql/order/mutations/orders.py b/saleor/graphql/order/mutations/orders.py
index ca9afe2f54..56f540e3bc 100644
--- a/saleor/graphql/order/mutations/orders.py
+++ b/saleor/graphql/order/mutations/orders.py
@@ -10,12 +10,10 @@ from ....order.utils import (
get_valid_shipping_methods_for_order,
recalculate_order,
)
-from ....payment import CustomPaymentChoices, PaymentError
+from ....payment import CustomPaymentChoices, PaymentError, gateway
from ....payment.utils import (
clean_mark_order_as_paid,
- gateway_capture,
gateway_refund,
- gateway_void,
mark_order_as_paid,
)
from ...account.types import AddressInput
@@ -352,7 +350,7 @@ class OrderCapture(BaseMutation):
clean_order_capture(payment)
try_payment_action(
- order, info.context.user, payment, gateway_capture, payment, amount
+ order, info.context.user, payment, gateway.capture, payment, amount
)
events.payment_captured_event(
@@ -379,7 +377,7 @@ class OrderVoid(BaseMutation):
payment = order.get_last_payment()
clean_void_payment(payment)
- try_payment_action(order, info.context.user, payment, gateway_void, payment)
+ try_payment_action(order, info.context.user, payment, gateway.void, payment)
events.payment_voided_event(
order=order, user=info.context.user, payment=payment
diff --git a/saleor/graphql/payment/mutations.py b/saleor/graphql/payment/mutations.py
index 4e5c8b3aa9..2ccd7e796c 100644
--- a/saleor/graphql/payment/mutations.py
+++ b/saleor/graphql/payment/mutations.py
@@ -4,14 +4,13 @@ from django.core.exceptions import ValidationError
from ...core.taxes import zero_taxed_money
from ...core.utils import get_client_ip
-from ...payment import PaymentError, models
+from ...payment import PaymentError, gateway, models
from ...payment.error_codes import PaymentErrorCode
from ...payment.utils import (
create_payment,
gateway_capture,
gateway_confirm,
gateway_refund,
- gateway_void,
)
from ..account.i18n import I18nMixin
from ..account.types import AddressInput
@@ -186,7 +185,7 @@ class PaymentVoid(BaseMutation):
info, payment_id, field="payment_id", only_type=Payment
)
try:
- gateway_void(payment)
+ gateway.void(payment)
except PaymentError as e:
raise ValidationError(str(e), code=PaymentErrorCode.PAYMENT_ERROR)
return PaymentVoid(payment=payment)
diff --git a/saleor/order/forms.py b/saleor/order/forms.py
index 0e7f08c889..9a53b428bb 100644
--- a/saleor/order/forms.py
+++ b/saleor/order/forms.py
@@ -3,8 +3,8 @@ from django.conf import settings
from django.utils.translation import pgettext_lazy
from ..account.forms import SignupForm
+from ..payment import gateway
from ..payment.models import Payment
-from ..payment.utils import gateway_void
from . import events
from .models import Order
@@ -49,7 +49,7 @@ class PaymentDeleteForm(forms.Form):
def save(self):
payment = self.cleaned_data["payment"]
- gateway_void(payment)
+ gateway.void(payment)
class PasswordForm(SignupForm):
diff --git a/saleor/order/utils.py b/saleor/order/utils.py
index 9a84b18bdb..f507815001 100644
--- a/saleor/order/utils.py
+++ b/saleor/order/utils.py
@@ -15,7 +15,7 @@ from ..discount.models import NotApplicable
from ..extensions.manager import get_extensions_manager
from ..order import FulfillmentStatus, OrderStatus, emails
from ..order.models import Fulfillment, FulfillmentLine, Order, OrderLine
-from ..payment import ChargeStatus
+from ..payment import ChargeStatus, gateway
from ..product.utils import (
allocate_stock,
deallocate_stock,
@@ -209,13 +209,11 @@ def cancel_order(user, order, restock):
charge_status=ChargeStatus.FULLY_REFUNDED
)
- from ..payment.utils import gateway_refund, gateway_void
-
for payment in payments:
if payment.can_refund():
- gateway_refund(payment)
+ gateway.refund(payment)
elif payment.can_void():
- gateway_void(payment)
+ gateway.void(payment)
def update_order_status(order):
diff --git a/saleor/payment/gateway.py b/saleor/payment/gateway.py
index 0c2af8523a..2f18049f34 100644
--- a/saleor/payment/gateway.py
+++ b/saleor/payment/gateway.py
@@ -49,8 +49,8 @@ def require_active_payment(fn):
return wrapped
-@raise_payment_error
@payment_postprocess
+@raise_payment_error
@require_active_payment
def process_payment(
payment: Payment, token: str, store_source: bool = False
@@ -72,11 +72,9 @@ def process_payment(
)
-@raise_payment_error
@payment_postprocess
-def authorize(
- payment: Payment, token: str, store_source: bool = False
-) -> Transaction:
+@raise_payment_error
+def authorize(payment: Payment, token: str, store_source: bool = False) -> Transaction:
plugin_manager = get_extensions_manager()
clean_authorize(payment)
gateway = _get_gateway(payment)
@@ -95,8 +93,8 @@ def authorize(
)
-@raise_payment_error
@payment_postprocess
+@raise_payment_error
def capture(
payment: Payment, amount: Decimal = None, store_source: bool = False
) -> Transaction:
@@ -107,10 +105,7 @@ def capture(
gateway = _get_gateway(payment)
token = _get_past_transaction_token(payment, TransactionKind.AUTH)
payment_data = create_payment_information(
- payment=payment,
- payment_token=token,
- amount=amount,
- store_source=store_source,
+ payment=payment, payment_token=token, amount=amount, store_source=store_source
)
response, error = _fetch_gateway_response(
plugin_manager.capture_payment, gateway, payment_data
@@ -124,8 +119,8 @@ def capture(
)
-@raise_payment_error
@payment_postprocess
+@raise_payment_error
def refund(payment: Payment, amount: Decimal = None) -> Transaction:
plugin_manager = get_extensions_manager()
if amount is None:
@@ -150,8 +145,8 @@ def refund(payment: Payment, amount: Decimal = None) -> Transaction:
)
-@raise_payment_error
@payment_postprocess
+@raise_payment_error
@require_active_payment
def void(payment: Payment) -> Transaction:
plugin_manager = get_extensions_manager()
@@ -170,8 +165,8 @@ def void(payment: Payment) -> Transaction:
)
-@raise_payment_error
@payment_postprocess
+@raise_payment_error
@require_active_payment
def confirm(payment: Payment) -> Transaction:
plugin_manager = get_extensions_manager()
diff --git a/saleor/payment/gateways/dummy/plugin.py b/saleor/payment/gateways/dummy/plugin.py
index 97b4324bb7..d8b81152de 100644
--- a/saleor/payment/gateways/dummy/plugin.py
+++ b/saleor/payment/gateways/dummy/plugin.py
@@ -36,12 +36,14 @@ class DummyGatewayPlugin(BasePlugin):
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
- self.config = None
-
- @classmethod
- def _get_default_configuration(cls):
- defaults = None
- return defaults
+ self.active = True
+ self.config = GatewayConfig(
+ gateway_name=GATEWAY_NAME,
+ auto_capture=True,
+ connection_params={},
+ template_path="",
+ store_customer=False,
+ )
def _initialize_plugin_configuration(self):
super()._initialize_plugin_configuration()
diff --git a/saleor/payment/gateways/stripe/plugin.py b/saleor/payment/gateways/stripe/plugin.py
index efdbbe02d7..661b980ba3 100644
--- a/saleor/payment/gateways/stripe/plugin.py
+++ b/saleor/payment/gateways/stripe/plugin.py
@@ -62,11 +62,6 @@ class StripeGatewayPlugin(BasePlugin):
super().__init__(*args, **kwargs)
self.config = None
- @classmethod
- def _get_default_configuration(cls):
- defaults = None
- return defaults
-
def _initialize_plugin_configuration(self):
super()._initialize_plugin_configuration()
diff --git a/saleor/payment/utils.py b/saleor/payment/utils.py
index 8adeea044f..e8a532c4dd 100644
--- a/saleor/payment/utils.py
+++ b/saleor/payment/utils.py
@@ -374,10 +374,13 @@ def validate_gateway_response(response: GatewayResponse):
@transaction.atomic
def _gateway_postprocess(transaction, payment):
+ if not transaction.is_success:
+ return
+
transaction_kind = transaction.kind
if transaction_kind in {TransactionKind.CAPTURE, TransactionKind.CONFIRM}:
- payment.captured_amount += transaction.amount
+ payment.captured_amount += Decimal(transaction.amount)
# Set payment charge status to fully charged
# only if there is no more amount needs to charge
@@ -463,19 +466,6 @@ def gateway_capture(payment: Payment, amount: Decimal = None) -> Transaction:
return transaction
-@require_active_payment
-def gateway_void(payment) -> Transaction:
- if not payment.can_void():
- raise PaymentError("Only pre-authorized transactions can be voided.")
-
- payment_token = get_payment_token(payment)
- transaction = call_gateway(
- operation_type=OperationType.VOID, payment=payment, payment_token=payment_token
- )
- _gateway_postprocess(transaction, payment)
- return transaction
-
-
@require_active_payment
def gateway_confirm(payment) -> Transaction:
if not payment.can_confirm():
diff --git a/tests/api/test_checkout.py b/tests/api/test_checkout.py
index 8e4721d82d..786b656ab8 100644
--- a/tests/api/test_checkout.py
+++ b/tests/api/test_checkout.py
@@ -6,13 +6,12 @@ import graphene
import pytest
from django.core.exceptions import ValidationError
from prices import Money, TaxedMoney
-from tests.api.utils import get_graphql_content
from saleor.checkout.error_codes import CheckoutErrorCode
from saleor.checkout.models import Checkout
from saleor.checkout.utils import clean_checkout, is_fully_paid
-from saleor.core.taxes import zero_money
from saleor.core.payments import PaymentInterface
+from saleor.core.taxes import zero_money
from saleor.graphql.checkout.mutations import (
clean_shipping_method,
update_checkout_shipping_method_if_invalid,
@@ -24,6 +23,7 @@ from saleor.payment.interface import GatewayResponse
from saleor.payment.models import Transaction
from saleor.shipping import ShippingMethodType
from saleor.shipping.models import ShippingMethod
+from tests.api.utils import get_graphql_content
@pytest.fixture
@@ -1159,10 +1159,10 @@ def fake_manager(mocker):
def mock_get_manager(mocker, fake_manager):
mgr = mocker.patch(
"saleor.payment.gateway.get_extensions_manager",
- auto_spec=True,
+ autospec=True,
return_value=fake_manager,
)
- yield mgr
+ yield fake_manager
mgr.assert_called_once()
@@ -1202,13 +1202,12 @@ def test_checkout_complete_does_not_delete_checkout_after_unsuccessful_payment(
response = user_api_client.post_graphql(MUTATION_CHECKOUT_COMPLETE, variables)
content = get_graphql_content(response)
data = content["data"]["checkoutComplete"]
- assert data["errors"] == [{"field": None, "message": expected_error}]
assert Order.objects.count() == orders_count
payment.refresh_from_db(fields=["order"])
transaction = payment.transactions.get()
- assert transaction.error == expected_error
+ assert transaction.error
assert payment.order is None
# ensure the voucher usage count was not incremented
diff --git a/tests/api/test_order.py b/tests/api/test_order.py
index e12dca12d2..852c25fe95 100644
--- a/tests/api/test_order.py
+++ b/tests/api/test_order.py
@@ -1530,23 +1530,20 @@ def test_order_void(
def test_order_void_payment_error(
- staff_api_client, permission_manage_orders, payment_txn_preauth
+ mock_get_manager, staff_api_client, permission_manage_orders, payment_txn_preauth
):
- msg = "error has happened"
+ msg = "Oops! Something went wrong."
order = payment_txn_preauth.order
order_id = graphene.Node.to_global_id("Order", order.id)
variables = {"id": order_id}
- with patch(
- "saleor.graphql.order.mutations.orders.gateway_void",
- side_effect=ValueError(msg),
- ):
- response = staff_api_client.post_graphql(
- ORDER_VOID, variables, permissions=[permission_manage_orders]
- )
- content = get_graphql_content(response)
- errors = content["data"]["orderVoid"]["errors"]
- assert errors[0]["field"] == "payment"
- assert errors[0]["message"] == msg
+ mock_get_manager.void_payment.side_effect = ValueError(msg)
+ response = staff_api_client.post_graphql(
+ ORDER_VOID, variables, permissions=[permission_manage_orders]
+ )
+ content = get_graphql_content(response)
+ errors = content["data"]["orderVoid"]["errors"]
+ assert errors[0]["field"] == "payment"
+ assert errors[0]["message"] == msg
order_errors = content["data"]["orderVoid"]["orderErrors"]
assert order_errors[0]["code"] == OrderErrorCode.PAYMENT_ERROR.name
diff --git a/tests/conftest.py b/tests/conftest.py
index 535f5a6424..fb9f85101b 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -20,6 +20,7 @@ from saleor.account.models import Address, User
from saleor.checkout import utils
from saleor.checkout.models import Checkout
from saleor.checkout.utils import add_variant_to_checkout
+from saleor.core.payments import PaymentInterface
from saleor.discount import DiscountInfo, DiscountValueType, VoucherType
from saleor.discount.models import Sale, Voucher, VoucherCustomer, VoucherTranslation
from saleor.giftcard.models import GiftCard
@@ -54,6 +55,12 @@ from saleor.site.models import AuthorizationKey, SiteSettings
from tests.utils import create_image
[email protected](autouse=True)
+def setup_dummy_gateway(settings):
+ settings.PLUGINS = ["saleor.payment.gateways.dummy.plugin.DummyGatewayPlugin"]
+ return settings
+
+
@pytest.fixture(autouse=True)
def site_settings(db, settings):
"""Create a site and matching site settings.
@@ -1418,3 +1425,19 @@ def other_description_raw():
"Saleor is powered by a GraphQL server running on top of Python 3 "
"and a Django 2 framework."
)
+
+
+def fake_payment_interface(mocker):
+ return mocker.Mock(spec=PaymentInterface)
+
+
+def mock_get_manager(mocker, fake_payment_interface):
+ mgr = mocker.patch(
+ "saleor.payment.gateway.get_extensions_manager",
+ autospec=True,
+ return_value=fake_payment_interface,
+ )
+ yield fake_payment_interface
+ mgr.assert_called_once()
diff --git a/tests/gateway/test_dummy.py b/tests/gateway/test_dummy.py
index 75bbc9e115..787babb8f3 100644
--- a/tests/gateway/test_dummy.py
+++ b/tests/gateway/test_dummy.py
@@ -6,20 +6,20 @@ from saleor.payment import (
ChargeStatus,
PaymentError,
TransactionKind,
+ gateway,
get_payment_gateway,
)
-from saleor.payment.utils import (
- create_payment_information,
- gateway_authorize,
- gateway_capture,
- gateway_process_payment,
- gateway_refund,
- gateway_void,
-)
+from saleor.payment.utils import create_payment_information
+
+
[email protected](autouse=True)
+def setup_dummy_gateway(settings):
+ settings.PLUGINS = ["saleor.payment.gateways.dummy.plugin.DummyGatewayPlugin"]
+ return settings
def test_authorize_success(payment_dummy):
- txn = gateway_authorize(payment=payment_dummy, payment_token="Fake")
+ txn = gateway.authorize(payment=payment_dummy, token="Fake")
assert txn.is_success
assert txn.kind == TransactionKind.AUTH
assert txn.payment == payment_dummy
@@ -47,14 +47,14 @@ def test_authorize_failed(is_active, charge_status, payment_dummy):
payment.charge_status = charge_status
payment.save()
with pytest.raises(PaymentError):
- txn = gateway_authorize(payment=payment, payment_token="Fake")
+ txn = gateway.authorize(payment=payment, token="Fake")
assert txn is None
def test_authorize_gateway_error(payment_dummy, monkeypatch):
monkeypatch.setattr("saleor.payment.gateways.dummy.dummy_success", lambda: False)
with pytest.raises(PaymentError):
- txn = gateway_authorize(payment=payment_dummy, payment_token="Fake")
+ txn = gateway.authorize(payment=payment_dummy, token="Fake")
assert txn.kind == TransactionKind.AUTH
assert not txn.is_success
assert txn.payment == payment_dummy
@@ -63,7 +63,7 @@ def test_authorize_gateway_error(payment_dummy, monkeypatch):
def test_void_success(payment_txn_preauth):
assert payment_txn_preauth.is_active
assert payment_txn_preauth.charge_status == ChargeStatus.NOT_CHARGED
- txn = gateway_void(payment=payment_txn_preauth)
+ txn = gateway.void(payment=payment_txn_preauth)
assert txn.is_success
assert txn.kind == TransactionKind.VOID
assert txn.payment == payment_txn_preauth
@@ -92,14 +92,14 @@ def test_void_failed(is_active, charge_status, payment_dummy):
payment.charge_status = charge_status
payment.save()
with pytest.raises(PaymentError):
- txn = gateway_void(payment=payment)
+ txn = gateway.void(payment=payment)
assert txn is None
def test_void_gateway_error(payment_txn_preauth, monkeypatch):
monkeypatch.setattr("saleor.payment.gateways.dummy.dummy_success", lambda: False)
with pytest.raises(PaymentError):
- txn = gateway_void(payment=payment_txn_preauth)
+ txn = gateway.void(payment=payment_txn_preauth)
assert txn.kind == TransactionKind.VOID
assert not txn.is_success
assert txn.payment == payment_txn_preauth
@@ -110,7 +110,7 @@ def test_void_gateway_error(payment_txn_preauth, monkeypatch):
[("98.40", ChargeStatus.FULLY_CHARGED), (70, ChargeStatus.PARTIALLY_CHARGED)],
)
def test_capture_success(amount, charge_status, payment_txn_preauth):
- txn = gateway_capture(payment=payment_txn_preauth, amount=Decimal(amount))
+ txn = gateway.capture(payment=payment_txn_preauth, amount=Decimal(amount))
assert txn.is_success
assert txn.payment == payment_txn_preauth
payment_txn_preauth.refresh_from_db()
@@ -137,14 +137,14 @@ def test_capture_failed(
payment.charge_status = charge_status
payment.save()
with pytest.raises(PaymentError):
- txn = gateway_capture(payment=payment, amount=amount)
+ txn = gateway.capture(payment=payment, amount=amount)
assert txn is None
def test_capture_gateway_error(payment_txn_preauth, monkeypatch):
monkeypatch.setattr("saleor.payment.gateways.dummy.dummy_success", lambda: False)
with pytest.raises(PaymentError):
- txn = gateway_capture(payment=payment_txn_preauth, amount=80)
+ txn = gateway.capture(payment=payment_txn_preauth, amount=80)
assert txn.kind == TransactionKind.CAPTURE
assert not txn.is_success
assert txn.payment == payment_txn_preauth
@@ -172,7 +172,7 @@ def test_refund_success(
payment.charge_status = ChargeStatus.FULLY_CHARGED
payment.captured_amount = initial_captured_amount
payment.save()
- txn = gateway_refund(payment=payment, amount=Decimal(refund_amount))
+ txn = gateway.refund(payment=payment, amount=Decimal(refund_amount))
assert txn.kind == TransactionKind.REFUND
assert txn.is_success
assert txn.payment == payment
@@ -199,7 +199,7 @@ def test_refund_failed(
payment.captured_amount = Decimal(initial_captured_amount)
payment.save()
with pytest.raises(PaymentError):
- txn = gateway_refund(payment=payment, amount=Decimal(refund_amount))
+ txn = gateway.refund(payment=payment, amount=Decimal(refund_amount))
assert txn is None
@@ -210,7 +210,7 @@ def test_refund_gateway_error(payment_txn_captured, monkeypatch):
payment.captured_amount = Decimal("80.00")
payment.save()
with pytest.raises(PaymentError):
- gateway_refund(payment=payment, amount=Decimal("80.00"))
+ gateway.refund(payment=payment, amount=Decimal("80.00"))
payment.refresh_from_db()
txn = payment.transactions.last()
@@ -241,6 +241,6 @@ def test_dummy_payment_form(kind, charge_status, payment_dummy):
connection_params=gateway_config.connection_params,
)
assert form.is_valid()
- gateway_process_payment(payment=payment, payment_token=form.get_payment_token())
+ gateway.process_payment(payment=payment, token=form.get_payment_token())
payment.refresh_from_db()
assert payment.transactions.last().kind == kind
diff --git a/tests/gateway/test_gateway.py b/tests/gateway/test_gateway.py
index 5db34b1319..bd5ce34b69 100644
--- a/tests/gateway/test_gateway.py
+++ b/tests/gateway/test_gateway.py
@@ -2,9 +2,9 @@ from decimal import Decimal
import pytest
-from saleor.core.payments import Gateway, PaymentInterface
+import saleor.payment.gateway as gateway
+from saleor.core.payments import Gateway
from saleor.payment import ChargeStatus, TransactionKind
-from saleor.payment.gateway import PaymentGateway
from saleor.payment.interface import GatewayResponse
from saleor.payment.utils import create_payment_information
@@ -84,35 +84,25 @@ USED_GATEWAY = Gateway.DUMMY
@pytest.fixture
-def fake_manager(mocker):
- return mocker.Mock(spec=PaymentInterface)
-
-
[email protected](autouse=True, scope="function")
-def mock_get_manager(mocker, fake_manager):
+def mock_payment_interface(mocker, fake_payment_interface):
mgr = mocker.patch(
"saleor.payment.gateway.get_extensions_manager",
- auto_spec=True,
- return_value=fake_manager,
+ autospec=True,
+ return_value=fake_payment_interface,
)
- yield mgr
+ yield fake_payment_interface
mgr.assert_called_once()
-def gateway():
- return PaymentGateway()
-
-
-def test_process_payment(gateway, payment_txn_preauth):
+def test_process_payment(mock_payment_interface, payment_txn_preauth):
PAYMENT_DATA = create_payment_information(
payment=payment_txn_preauth, payment_token=TOKEN
)
- gateway.plugin_manager.process_payment.return_value = PROCESS_PAYMENT_RESPONSE
+ mock_payment_interface.process_payment.return_value = PROCESS_PAYMENT_RESPONSE
transaction = gateway.process_payment(payment=payment_txn_preauth, token=TOKEN)
- gateway.plugin_manager.process_payment.assert_called_once_with(
+ mock_payment_interface.process_payment.assert_called_once_with(
USED_GATEWAY, PAYMENT_DATA
)
assert transaction.amount == PROCESS_PAYMENT_RESPONSE.amount
@@ -121,31 +111,33 @@ def test_process_payment(gateway, payment_txn_preauth):
assert transaction.gateway_response == RAW_RESPONSE
-def test_store_source_when_processing_payment(gateway, payment_txn_preauth):
+def test_store_source_when_processing_payment(
+ mock_payment_interface, payment_txn_preauth
+):
PAYMENT_DATA = create_payment_information(
payment=payment_txn_preauth, payment_token=TOKEN, store_source=True
)
- gateway.plugin_manager.process_payment.return_value = PROCESS_PAYMENT_RESPONSE
+ mock_payment_interface.process_payment.return_value = PROCESS_PAYMENT_RESPONSE
transaction = gateway.process_payment(
payment=payment_txn_preauth, token=TOKEN, store_source=True
)
- gateway.plugin_manager.process_payment.assert_called_once_with(
+ mock_payment_interface.process_payment.assert_called_once_with(
USED_GATEWAY, PAYMENT_DATA
)
assert transaction.customer_id == PROCESS_PAYMENT_RESPONSE.customer_id
-def test_authorize_payment(gateway, payment_dummy):
+def test_authorize_payment(mock_payment_interface, payment_dummy):
PAYMENT_DATA = create_payment_information(
payment=payment_dummy, payment_token=TOKEN
)
- gateway.plugin_manager.authorize_payment.return_value = AUTHORIZE_RESPONSE
+ mock_payment_interface.authorize_payment.return_value = AUTHORIZE_RESPONSE
transaction = gateway.authorize(payment=payment_dummy, token=TOKEN)
- gateway.plugin_manager.authorize_payment.assert_called_once_with(
+ mock_payment_interface.authorize_payment.assert_called_once_with(
USED_GATEWAY, PAYMENT_DATA
)
assert transaction.amount == AUTHORIZE_RESPONSE.amount
@@ -154,16 +146,16 @@ def test_authorize_payment(gateway, payment_dummy):
assert transaction.gateway_response == RAW_RESPONSE
-def test_capture_payment(gateway, payment_txn_preauth):
+def test_capture_payment(mock_payment_interface, payment_txn_preauth):
auth_transaction = payment_txn_preauth.transactions.get()
PAYMENT_DATA = create_payment_information(
payment=payment_txn_preauth, payment_token=auth_transaction.token
)
- gateway.plugin_manager.capture_payment.return_value = PROCESS_PAYMENT_RESPONSE
+ mock_payment_interface.capture_payment.return_value = PROCESS_PAYMENT_RESPONSE
transaction = gateway.capture(payment=payment_txn_preauth)
- gateway.plugin_manager.capture_payment.assert_called_once_with(
+ mock_payment_interface.capture_payment.assert_called_once_with(
USED_GATEWAY, PAYMENT_DATA
)
assert transaction.amount == PROCESS_PAYMENT_RESPONSE.amount
@@ -172,18 +164,18 @@ def test_capture_payment(gateway, payment_txn_preauth):
assert transaction.gateway_response == RAW_RESPONSE
-def test_partial_refund_payment(gateway, payment_txn_captured):
+def test_partial_refund_payment(mock_payment_interface, payment_txn_captured):
capture_transaction = payment_txn_captured.transactions.get()
PAYMENT_DATA = create_payment_information(
payment=payment_txn_captured,
amount=PARTIAL_REFUND_AMOUNT,
payment_token=capture_transaction.token,
)
- gateway.plugin_manager.refund_payment.return_value = PARTIAL_REFUND_RESPONSE
+ mock_payment_interface.refund_payment.return_value = PARTIAL_REFUND_RESPONSE
transaction = gateway.refund(
payment=payment_txn_captured, amount=PARTIAL_REFUND_AMOUNT
)
- gateway.plugin_manager.refund_payment.assert_called_once_with(
+ mock_payment_interface.refund_payment.assert_called_once_with(
USED_GATEWAY, PAYMENT_DATA
)
@@ -195,16 +187,16 @@ def test_partial_refund_payment(gateway, payment_txn_captured):
assert transaction.gateway_response == RAW_RESPONSE
-def test_full_refund_payment(gateway, payment_txn_captured):
+def test_full_refund_payment(mock_payment_interface, payment_txn_captured):
capture_transaction = payment_txn_captured.transactions.get()
PAYMENT_DATA = create_payment_information(
payment=payment_txn_captured,
amount=FULL_REFUND_AMOUNT,
payment_token=capture_transaction.token,
)
- gateway.plugin_manager.refund_payment.return_value = FULL_REFUND_RESPONSE
+ mock_payment_interface.refund_payment.return_value = FULL_REFUND_RESPONSE
transaction = gateway.refund(payment=payment_txn_captured)
- gateway.plugin_manager.refund_payment.assert_called_once_with(
+ mock_payment_interface.refund_payment.assert_called_once_with(
USED_GATEWAY, PAYMENT_DATA
)
@@ -216,18 +208,18 @@ def test_full_refund_payment(gateway, payment_txn_captured):
assert transaction.gateway_response == RAW_RESPONSE
-def test_void_payment(gateway, payment_txn_preauth):
+def test_void_payment(mock_payment_interface, payment_txn_preauth):
auth_transaction = payment_txn_preauth.transactions.get()
PAYMENT_DATA = create_payment_information(
payment=payment_txn_preauth,
payment_token=auth_transaction.token,
amount=VOID_AMOUNT,
)
- gateway.plugin_manager.void_payment.return_value = VOID_RESPONSE
+ mock_payment_interface.void_payment.return_value = VOID_RESPONSE
transaction = gateway.void(payment=payment_txn_preauth)
- gateway.plugin_manager.void_payment.assert_called_once_with(
+ mock_payment_interface.void_payment.assert_called_once_with(
USED_GATEWAY, PAYMENT_DATA
)
payment_txn_preauth.refresh_from_db()
@@ -238,18 +230,18 @@ def test_void_payment(gateway, payment_txn_preauth):
assert transaction.gateway_response == RAW_RESPONSE
-def test_confirm_payment(gateway, payment_txn_preauth):
+def test_confirm_payment(mock_payment_interface, payment_txn_preauth):
auth_transaction = payment_txn_preauth.transactions.get()
PAYMENT_DATA = create_payment_information(
payment=payment_txn_preauth,
payment_token=auth_transaction.token,
amount=CONFIRM_AMOUNT,
)
- gateway.plugin_manager.confirm_payment.return_value = CONFIRM_RESPONSE
+ mock_payment_interface.confirm_payment.return_value = CONFIRM_RESPONSE
transaction = gateway.confirm(payment=payment_txn_preauth)
- gateway.plugin_manager.confirm_payment.assert_called_once_with(
+ mock_payment_interface.confirm_payment.assert_called_once_with(
USED_GATEWAY, PAYMENT_DATA
)
assert transaction.amount == CONFIRM_RESPONSE.amount
diff --git a/tests/test_payment.py b/tests/test_payment.py
index 10794cbcda..f3117847ff 100644
--- a/tests/test_payment.py
+++ b/tests/test_payment.py
@@ -13,6 +13,7 @@ from saleor.payment import (
OperationType,
PaymentError,
TransactionKind,
+ gateway,
get_payment_gateway,
)
from saleor.payment.interface import (
@@ -36,7 +37,6 @@ from saleor.payment.utils import (
gateway_get_client_token,
gateway_process_payment,
gateway_refund,
- gateway_void,
handle_fully_paid_order,
mark_order_as_paid,
require_active_payment,
@@ -318,7 +318,7 @@ def test_gateway_get_client_token_not_existing_gateway(settings):
@pytest.mark.parametrize(
- "func", [gateway_authorize, gateway_capture, gateway_refund, gateway_void]
+ "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
@@ -327,31 +327,6 @@ def test_payment_needs_to_be_active_for_any_action(func, payment_dummy):
assert exc.value.message == NOT_ACTIVE_PAYMENT_ERROR
-@patch("saleor.payment.utils.get_payment_gateway")
-def test_gateway_process_payment(
- mock_get_payment_gateway,
- payment_txn_preauth,
- gateway_config,
- transaction_token,
- dummy_response,
-):
- payment_token = transaction_token
- payment = payment_txn_preauth
- mock_process_payment = Mock(return_value=dummy_response)
- mock_get_payment_gateway.return_value = (
- Mock(process_payment=mock_process_payment),
- gateway_config,
- )
-
- payment_info = create_payment_information(payment, payment_token)
- gateway_process_payment(payment, payment_token)
-
- mock_get_payment_gateway.assert_called_with(payment.gateway)
- mock_process_payment.assert_called_once_with(
- payment_information=payment_info, config=gateway_config
- )
-
-
@patch("saleor.payment.utils.get_payment_gateway")
def test_gateway_authorize(
mock_get_payment_gateway,
@@ -596,57 +571,6 @@ def test_gateway_charge_errors(payment_dummy, transaction_token, settings):
assert exc.value.message == ("Unable to charge more than un-captured amount.")
-@patch("saleor.payment.utils.get_payment_gateway")
-def test_gateway_void(
- mock_get_payment_gateway, payment_txn_preauth, gateway_config, dummy_response
-):
- txn = payment_txn_preauth.transactions.first()
- payment = payment_txn_preauth
- assert payment.is_active
-
- dummy_response.kind = TransactionKind.VOID
- mock_void = Mock(return_value=dummy_response)
- mock_get_payment_gateway.return_value = (Mock(void=mock_void), gateway_config)
-
- payment_info = create_payment_information(payment, txn.token)
- gateway_void(payment)
-
- mock_get_payment_gateway.assert_called_once_with(payment.gateway)
- mock_void.assert_called_once_with(
- payment_information=payment_info, config=gateway_config
- )
-
- payment.refresh_from_db()
- assert payment.is_active is False
-
-
-@patch("saleor.payment.utils.get_payment_gateway")
-def test_gateway_void_failed(
- mock_get_payment_gateway, payment_txn_preauth, gateway_config, dummy_response
-):
- txn = payment_txn_preauth.transactions.first()
- txn.is_success = False
- payment = payment_txn_preauth
-
- 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_config)
- 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.FULLY_CHARGED
- with pytest.raises(PaymentError) as exc:
- gateway_void(payment_dummy)
- assert exc.value.message == "Only pre-authorized transactions can be voided."
-
-
@patch("saleor.payment.utils.get_payment_gateway")
def test_gateway_refund(
mock_get_payment_gateway, payment_txn_captured, gateway_config, dummy_response