Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Move new dummy payment to separate plugin
IKarbowiake632cf8e8ad8
diff --git a/saleor/graphql/checkout/tests/test_checkout.py b/saleor/graphql/checkout/tests/test_checkout.pyindex d65bc404bd..afa24fd185 100644--- a/saleor/graphql/checkout/tests/test_checkout.py+++ b/saleor/graphql/checkout/tests/test_checkout.py@@ -18,7 +18,7 @@ from ....core.payments import PaymentInterfacefrom ....core.taxes import zero_moneyfrom ....order.models import Orderfrom ....payment import TransactionKind-from ....payment.gateways.dummy import TOKEN_VALIDATION_MAPPING+from ....payment.gateways.dummy_credit_card import TOKEN_VALIDATION_MAPPINGfrom ....payment.interface import GatewayResponsefrom ....plugins.manager import PluginsManagerfrom ....plugins.tests.sample_plugins import ActiveDummyPaymentGateway@@ -647,6 +647,16 @@ def expected_dummy_gateway():}+def expected_dummy_credit_card_gateway():+ return {+ "id": "mirumee.payments.dummy_credit_card",+ "name": "Dummy Credit Card",+ "config": [{"field": "store_customer_card", "value": "false"}],+ "currencies": ["USD"],+ }++GET_CHECKOUT_PAYMENTS_QUERY = """query getCheckoutPayments($token: UUID!) {checkout(token: $token) {@@ -665,7 +675,10 @@ query getCheckoutPayments($token: UUID!) {def test_checkout_available_payment_gateways(- api_client, checkout_with_item, expected_dummy_gateway+ api_client,+ checkout_with_item,+ expected_dummy_gateway,+ expected_dummy_credit_card_gateway,):query = GET_CHECKOUT_PAYMENTS_QUERYvariables = {"token": str(checkout_with_item.token)}@@ -673,11 +686,18 @@ def test_checkout_available_payment_gateways(content = get_graphql_content(response)data = content["data"]["checkout"]- assert data["availablePaymentGateways"] == [expected_dummy_gateway]+ assert data["availablePaymentGateways"] == [+ expected_dummy_gateway,+ expected_dummy_credit_card_gateway,+ ]def test_checkout_available_payment_gateways_currency_specified_USD(- api_client, checkout_with_item, expected_dummy_gateway, sample_gateway+ api_client,+ checkout_with_item,+ expected_dummy_gateway,+ expected_dummy_credit_card_gateway,+ sample_gateway,):checkout_with_item.currency = "USD"checkout_with_item.save(update_fields=["currency"])@@ -691,6 +711,7 @@ def test_checkout_available_payment_gateways_currency_specified_USD(data = content["data"]["checkout"]assert {gateway["id"] for gateway in data["availablePaymentGateways"]} == {expected_dummy_gateway["id"],+ expected_dummy_credit_card_gateway["id"],ActiveDummyPaymentGateway.PLUGIN_ID,}@@ -1889,7 +1910,7 @@ def test_checkout_complete_error_in_gateway_response(user_api_client,checkout_with_gift_card,gift_card,- payment_dummy,+ payment_dummy_credit_card,address,shipping_method,):@@ -1905,7 +1926,7 @@ def test_checkout_complete_error_in_gateway_response(checkout.save()total = calculations.checkout_total(checkout=checkout, lines=list(checkout))- payment = payment_dummy+ payment = payment_dummy_credit_cardpayment.is_active = Truepayment.order = Nonepayment.total = total.gross.amountdiff --git a/saleor/graphql/invoice/tests/test_invoice_request.py b/saleor/graphql/invoice/tests/test_invoice_request.pyindex 7180e7fae9..af99af8e17 100644--- a/saleor/graphql/invoice/tests/test_invoice_request.py+++ b/saleor/graphql/invoice/tests/test_invoice_request.py@@ -1,6 +1,7 @@from unittest.mock import patchimport graphene+import pytestfrom ....core import JobStatusfrom ....graphql.tests.utils import get_graphql_content@@ -31,6 +32,14 @@ INVOICE_REQUEST_MUTATION = """"""[email protected](autouse=True)+def setup_dummy_gateways(settings):+ settings.PLUGINS = [+ "saleor.payment.gateways.dummy.plugin.DummyGatewayPlugin",+ ]+ return settings++@patch("saleor.plugins.base_plugin.BasePlugin.invoice_request")def test_invoice_request(plugin_mock, staff_api_client, permission_manage_orders, orderdiff --git a/saleor/graphql/invoice/tests/test_invoice_request_delete.py b/saleor/graphql/invoice/tests/test_invoice_request_delete.pyindex 6a2c2ba6bf..92d3c037d4 100644--- a/saleor/graphql/invoice/tests/test_invoice_request_delete.py+++ b/saleor/graphql/invoice/tests/test_invoice_request_delete.py@@ -1,6 +1,7 @@from unittest.mock import patchimport graphene+import pytestfrom ....graphql.tests.utils import assert_no_permission, get_graphql_contentfrom ....invoice.error_codes import InvoiceErrorCode@@ -20,6 +21,14 @@ INVOICE_REQUEST_DELETE_MUTATION = """"""[email protected](autouse=True)+def setup_dummy_gateways(settings):+ settings.PLUGINS = [+ "saleor.payment.gateways.dummy.plugin.DummyGatewayPlugin",+ ]+ return settings++@patch("saleor.plugins.base_plugin.BasePlugin.invoice_delete")def test_invoice_request_delete(plugin_mock, staff_api_client, permission_manage_orders, orderdiff --git a/saleor/graphql/payment/tests/test_payment.py b/saleor/graphql/payment/tests/test_payment.pyindex 6ee4d4c29c..444a4890f8 100644--- a/saleor/graphql/payment/tests/test_payment.py+++ b/saleor/graphql/payment/tests/test_payment.py@@ -6,7 +6,10 @@ from django_countries.fields import Countryfrom ....checkout import calculationsfrom ....payment.error_codes import PaymentErrorCode-from ....payment.gateways.dummy import TOKEN_EXPIRED, TOKEN_VALIDATION_MAPPING+from ....payment.gateways.dummy_credit_card import (+ TOKEN_EXPIRED,+ TOKEN_VALIDATION_MAPPING,+)from ....payment.interface import CreditCardInfo, CustomerSource, TokenConfigfrom ....payment.models import ChargeStatus, Payment, TransactionKindfrom ....payment.utils import fetch_customer_id, store_customer_id@@ -469,9 +472,43 @@ def test_payment_capture_with_payment_non_authorized_yet(def test_payment_capture_gateway_error(staff_api_client, permission_manage_orders, payment_txn_preauth, monkeypatch):+ # given+ payment = payment_txn_preauth++ assert payment.charge_status == ChargeStatus.NOT_CHARGED+ payment_id = graphene.Node.to_global_id("Payment", payment.pk)+ variables = {"paymentId": payment_id, "amount": str(payment_txn_preauth.total)}+ monkeypatch.setattr("saleor.payment.gateways.dummy.dummy_success", lambda: False)++ # when+ response = staff_api_client.post_graphql(+ CAPTURE_QUERY, variables, permissions=[permission_manage_orders]+ )++ # then+ content = get_graphql_content(response)+ data = content["data"]["paymentCapture"]+ assert data["errors"] == [{"field": None, "message": "Unable to process capture"}]++ payment_txn_preauth.refresh_from_db()+ assert payment.charge_status == ChargeStatus.NOT_CHARGED+ assert payment.transactions.count() == 2+ txn = payment.transactions.last()+ assert txn.kind == TransactionKind.CAPTURE+ assert not txn.is_success+++def test_payment_capture_gateway_dummy_credit_card_error(+ staff_api_client, permission_manage_orders, payment_txn_preauth, monkeypatch+):+ # giventoken = TOKEN_EXPIREDerror = TOKEN_VALIDATION_MAPPING[token]+payment = payment_txn_preauth+ payment.gateway = "mirumee.payments.dummy_credit_card"+ payment.save()+transaction = payment.transactions.last()transaction.token = tokentransaction.save()@@ -479,10 +516,16 @@ def test_payment_capture_gateway_error(assert payment.charge_status == ChargeStatus.NOT_CHARGEDpayment_id = graphene.Node.to_global_id("Payment", payment.pk)variables = {"paymentId": payment_id, "amount": str(payment_txn_preauth.total)}- monkeypatch.setattr("saleor.payment.gateways.dummy.dummy_success", lambda: False)+ monkeypatch.setattr(+ "saleor.payment.gateways.dummy_credit_card.dummy_success", lambda: False+ )++ # whenresponse = staff_api_client.post_graphql(CAPTURE_QUERY, variables, permissions=[permission_manage_orders])++ # thencontent = get_graphql_content(response)data = content["data"]["paymentCapture"]assert data["errors"] == [{"field": None, "message": error}]diff --git a/saleor/graphql/shop/tests/test_shop.py b/saleor/graphql/shop/tests/test_shop.pyindex 8499ba03e0..d3d9e90c90 100644--- a/saleor/graphql/shop/tests/test_shop.py+++ b/saleor/graphql/shop/tests/test_shop.py@@ -701,9 +701,14 @@ def test_query_available_payment_gateways(user_api_client, sample_gateway):data = content["data"]["shop"]["availablePaymentGateways"]assert {gateway["id"] for gateway in data} == {"mirumee.payments.dummy",+ "mirumee.payments.dummy_credit_card","sampleDummy.active",}- assert {gateway["name"] for gateway in data} == {"Dummy", "SampleDummy"}+ assert {gateway["name"] for gateway in data} == {+ "Dummy",+ "Dummy Credit Card",+ "SampleDummy",+ }def test_query_available_payment_gateways_specified_currency_USD(@@ -715,9 +720,14 @@ def test_query_available_payment_gateways_specified_currency_USD(data = content["data"]["shop"]["availablePaymentGateways"]assert {gateway["id"] for gateway in data} == {"mirumee.payments.dummy",+ "mirumee.payments.dummy_credit_card","sampleDummy.active",}- assert {gateway["name"] for gateway in data} == {"Dummy", "SampleDummy"}+ assert {gateway["name"] for gateway in data} == {+ "Dummy",+ "Dummy Credit Card",+ "SampleDummy",+ }def test_query_available_payment_gateways_specified_currency_PLN(diff --git a/saleor/payment/gateways/dummy/__init__.py b/saleor/payment/gateways/dummy/__init__.pyindex eb45c28f3a..ee4eae71c5 100644--- a/saleor/payment/gateways/dummy/__init__.py+++ b/saleor/payment/gateways/dummy/__init__.py@@ -1,35 +1,13 @@import uuid-from typing import Optional-from ... import TransactionKind+from ... import ChargeStatus, TransactionKindfrom ...interface import GatewayConfig, GatewayResponse, PaymentData-TOKEN_PREAUTHORIZE_SUCCESS = "4111111111111112"-TOKEN_PREAUTHORIZE_DECLINE = "4111111111111111"-TOKEN_EXPIRED = "4000000000000069"-TOKEN_INSUFFICIENT_FUNDS = "4000000000009995"-TOKEN_INCORRECT_CVV = "4000000000000127"-TOKEN_DECLINE = "4000000000000002"--PREAUTHORIZED_TOKENS = [TOKEN_PREAUTHORIZE_DECLINE, TOKEN_PREAUTHORIZE_SUCCESS]--TOKEN_VALIDATION_MAPPING = {- TOKEN_EXPIRED: "Card expired",- TOKEN_INSUFFICIENT_FUNDS: "Insufficient funds",- TOKEN_INCORRECT_CVV: "Incorrect CVV",- TOKEN_DECLINE: "Card declined",- TOKEN_PREAUTHORIZE_DECLINE: "Card declined",-}-def dummy_success():return True-def validate_token(token: Optional[str]):- return TOKEN_VALIDATION_MAPPING.get(token, None) if token else None--def get_client_token(**_):return str(uuid.uuid4())@@ -70,8 +48,10 @@ def void(payment_information: PaymentData, config: GatewayConfig) -> GatewayRespdef capture(payment_information: PaymentData, config: GatewayConfig) -> GatewayResponse:"""Perform capture transaction."""- error = validate_token(payment_information.token)- success = not error+ error = None+ success = dummy_success()+ if not success:+ error = "Unable to process capture"return GatewayResponse(is_success=success,@@ -124,9 +104,21 @@ def process_payment("""Process the payment."""token = payment_information.token- if token in PREAUTHORIZED_TOKENS:- authorize_response = authorize(payment_information, config)- if not config.auto_capture:- return authorize_response+ # Process payment normally if payment token is valid+ if token not in dict(ChargeStatus.CHOICES):+ return capture(payment_information, config)++ # Process payment by charge status which is selected in the payment form+ # Note that is for testing by dummy gateway only+ charge_status = token+ authorize_response = authorize(payment_information, config)+ if charge_status == ChargeStatus.NOT_CHARGED:+ return authorize_response++ if not config.auto_capture:+ return authorize_response- return capture(payment_information, config)+ capture_response = capture(payment_information, config)+ if charge_status == ChargeStatus.FULLY_REFUNDED:+ return refund(payment_information, config)+ return capture_responsediff --git a/saleor/payment/gateways/dummy/tests/test_dummy.py b/saleor/payment/gateways/dummy/tests/test_dummy.pyindex 9ff39bf780..dab6f8f503 100644--- a/saleor/payment/gateways/dummy/tests/test_dummy.py+++ b/saleor/payment/gateways/dummy/tests/test_dummy.py@@ -3,24 +3,6 @@ from decimal import Decimalimport pytestfrom .... import ChargeStatus, PaymentError, TransactionKind, gateway-from .. import (- PREAUTHORIZED_TOKENS,- TOKEN_EXPIRED,- TOKEN_VALIDATION_MAPPING,- authorize,- capture,- process_payment,- refund,- void,-)--NO_LONGER_ACTIVE = "This payment is no longer active."-CANNOT_BE_AUTHORIZED_AGAIN = "Charged transactions cannot be authorized again."-LACK_OF_SUCCESSFUL_TRANSACTION = "Cannot find successful auth transaction."-CANNOT_BE_CAPTURED = "This payment cannot be captured."-CANNOT_REFUND_MORE_THAN_CAPTURE = "Cannot refund more than captured."-AMOUNT_SHOULD_BE_POSITIVE = "Amount should be a positive number."-CANNOT_CHARGE_MORE_THAN_UNCAPTURED = "Unable to charge more than un-captured amount."@pytest.fixture(autouse=True)@@ -39,49 +21,36 @@ def test_authorize_success(payment_dummy):@pytest.mark.parametrize(- "is_active, charge_status, error",+ "is_active, charge_status",[- (False, ChargeStatus.NOT_CHARGED, NO_LONGER_ACTIVE),- (False, ChargeStatus.PARTIALLY_CHARGED, NO_LONGER_ACTIVE),- (False, ChargeStatus.FULLY_CHARGED, NO_LONGER_ACTIVE),- (False, ChargeStatus.PARTIALLY_REFUNDED, NO_LONGER_ACTIVE),- (False, ChargeStatus.FULLY_REFUNDED, NO_LONGER_ACTIVE),- (True, ChargeStatus.PARTIALLY_CHARGED, CANNOT_BE_AUTHORIZED_AGAIN),- (True, ChargeStatus.FULLY_CHARGED, CANNOT_BE_AUTHORIZED_AGAIN),- (True, ChargeStatus.PARTIALLY_REFUNDED, CANNOT_BE_AUTHORIZED_AGAIN),- (True, ChargeStatus.FULLY_REFUNDED, CANNOT_BE_AUTHORIZED_AGAIN),+ (False, ChargeStatus.NOT_CHARGED),+ (False, ChargeStatus.PARTIALLY_CHARGED),+ (False, ChargeStatus.FULLY_CHARGED),+ (False, ChargeStatus.PARTIALLY_REFUNDED),+ (False, ChargeStatus.FULLY_REFUNDED),+ (True, ChargeStatus.PARTIALLY_CHARGED),+ (True, ChargeStatus.FULLY_CHARGED),+ (True, ChargeStatus.PARTIALLY_REFUNDED),+ (True, ChargeStatus.FULLY_REFUNDED),],)-def test_authorize_failed(is_active, charge_status, error, payment_dummy):+def test_authorize_failed(is_active, charge_status, payment_dummy):payment = payment_dummypayment.is_active = is_activepayment.charge_status = charge_statuspayment.save()- with pytest.raises(PaymentError) as e:- gateway.authorize(payment=payment, token="Fake")-- assert e._excinfo[1].message == error+ with pytest.raises(PaymentError):+ txn = gateway.authorize(payment=payment, token="Fake")+ assert txn is Nonedef test_authorize_gateway_error(payment_dummy, monkeypatch):monkeypatch.setattr("saleor.payment.gateways.dummy.dummy_success", lambda: False)- with pytest.raises(PaymentError) as e:- gateway.authorize(payment=payment_dummy, token="Fake")-- assert e._excinfo[1].message == "Unable to authorize transaction"---def test_authorize_method_error(dummy_payment_data, dummy_gateway_config, monkeypatch):- # given- monkeypatch.setattr("saleor.payment.gateways.dummy.dummy_success", lambda: False)-- # when- response = authorize(dummy_payment_data, dummy_gateway_config)-- # then- assert not response.is_success- assert response.kind == TransactionKind.AUTH- assert response.error == "Unable to authorize transaction"+ with pytest.raises(PaymentError):+ txn = gateway.authorize(payment=payment_dummy, token="Fake")+ assert txn.kind == TransactionKind.AUTH+ assert not txn.is_success+ assert txn.payment == payment_dummydef test_void_success(payment_txn_preauth):@@ -97,125 +66,81 @@ def test_void_success(payment_txn_preauth):@pytest.mark.parametrize(- "is_active, charge_status, error",+ "is_active, charge_status",[- (False, ChargeStatus.NOT_CHARGED, NO_LONGER_ACTIVE),- (False, ChargeStatus.PARTIALLY_CHARGED, NO_LONGER_ACTIVE),- (False, ChargeStatus.FULLY_CHARGED, NO_LONGER_ACTIVE),- (False, ChargeStatus.PARTIALLY_REFUNDED, NO_LONGER_ACTIVE),- (False, ChargeStatus.FULLY_REFUNDED, NO_LONGER_ACTIVE),- (True, ChargeStatus.PARTIALLY_CHARGED, LACK_OF_SUCCESSFUL_TRANSACTION),- (True, ChargeStatus.FULLY_CHARGED, LACK_OF_SUCCESSFUL_TRANSACTION),- (True, ChargeStatus.PARTIALLY_REFUNDED, LACK_OF_SUCCESSFUL_TRANSACTION),- (True, ChargeStatus.FULLY_REFUNDED, LACK_OF_SUCCESSFUL_TRANSACTION),+ (False, ChargeStatus.NOT_CHARGED),+ (False, ChargeStatus.PARTIALLY_CHARGED),+ (False, ChargeStatus.FULLY_CHARGED),+ (False, ChargeStatus.PARTIALLY_REFUNDED),+ (False, ChargeStatus.FULLY_REFUNDED),+ (True, ChargeStatus.PARTIALLY_CHARGED),+ (True, ChargeStatus.FULLY_CHARGED),+ (True, ChargeStatus.PARTIALLY_REFUNDED),+ (True, ChargeStatus.FULLY_REFUNDED),],)-def test_void_failed(is_active, charge_status, error, payment_dummy):+def test_void_failed(is_active, charge_status, payment_dummy):payment = payment_dummypayment.is_active = is_activepayment.charge_status = charge_statuspayment.save()- with pytest.raises(PaymentError) as e:- gateway.void(payment=payment)-- assert e._excinfo[1].message == error+ with pytest.raises(PaymentError):+ txn = gateway.void(payment=payment)+ assert txn is Nonedef test_void_gateway_error(payment_txn_preauth, monkeypatch):monkeypatch.setattr("saleor.payment.gateways.dummy.dummy_success", lambda: False)- with pytest.raises(PaymentError) as e:- gateway.void(payment=payment_txn_preauth)-- assert e._excinfo[1].message == "Unable to void the transaction."---def test_void_method_error(dummy_payment_data, dummy_gateway_config, monkeypatch):- # given- monkeypatch.setattr("saleor.payment.gateways.dummy.dummy_success", lambda: False)-- # when- response = void(dummy_payment_data, dummy_gateway_config)-- # then- assert not response.is_success- assert response.kind == TransactionKind.VOID- assert response.error == "Unable to void the transaction."+ with pytest.raises(PaymentError):+ txn = gateway.void(payment=payment_txn_preauth)+ assert txn.kind == TransactionKind.VOID+ assert not txn.is_success+ assert txn.payment == payment_txn_preauth@pytest.mark.parametrize(- "amount, charge_status, token",- [- ("98.40", ChargeStatus.FULLY_CHARGED, "1111111111111111"),- (70, ChargeStatus.PARTIALLY_CHARGED, "2222222222222222"),- (70, ChargeStatus.PARTIALLY_CHARGED, "fake"),- ],+ "amount, charge_status",+ [("98.40", ChargeStatus.FULLY_CHARGED), (70, ChargeStatus.PARTIALLY_CHARGED)],)-def test_capture_success(amount, charge_status, token, payment_txn_preauth):- transaction = payment_txn_preauth.transactions.last()- transaction.token = token- transaction.save()-+def test_capture_success(amount, charge_status, payment_txn_preauth):txn = gateway.capture(payment=payment_txn_preauth, amount=Decimal(amount))assert txn.is_successassert txn.payment == payment_txn_preauth- assert not txn.errorpayment_txn_preauth.refresh_from_db()assert payment_txn_preauth.charge_status == charge_statusassert payment_txn_preauth.is_active@pytest.mark.parametrize(- "amount, captured_amount, charge_status, is_active, error",+ "amount, captured_amount, charge_status, is_active",[- (80, 0, ChargeStatus.NOT_CHARGED, False, NO_LONGER_ACTIVE),- (120, 0, ChargeStatus.NOT_CHARGED, True, CANNOT_CHARGE_MORE_THAN_UNCAPTURED),- (80, 20, ChargeStatus.PARTIALLY_CHARGED, True, CANNOT_BE_CAPTURED),- (80, 80, ChargeStatus.FULLY_CHARGED, True, CANNOT_BE_CAPTURED),- (80, 0, ChargeStatus.FULLY_REFUNDED, True, CANNOT_BE_CAPTURED),+ (80, 0, ChargeStatus.NOT_CHARGED, False),+ (120, 0, ChargeStatus.NOT_CHARGED, True),+ (80, 20, ChargeStatus.PARTIALLY_CHARGED, True),+ (80, 80, ChargeStatus.FULLY_CHARGED, True),+ (80, 0, ChargeStatus.FULLY_REFUNDED, True),],)def test_capture_failed(- amount, captured_amount, charge_status, error, is_active, payment_dummy+ amount, captured_amount, charge_status, is_active, payment_dummy):payment = payment_dummypayment.is_active = is_activepayment.captured_amount = captured_amountpayment.charge_status = charge_statuspayment.save()- with pytest.raises(PaymentError) as e:- gateway.capture(payment=payment, amount=amount)-- assert e._excinfo[1].message == error--[email protected]("token, error", list(TOKEN_VALIDATION_MAPPING.items()))-def test_capture_error_in_response(token, error, payment_txn_preauth):- # given- transaction = payment_txn_preauth.transactions.last()- transaction.token = token- transaction.save()-- # when- with pytest.raises(PaymentError) as e:- gateway.capture(payment=payment_txn_preauth)-- assert e._excinfo[1].message == error--[email protected]("token, error", list(TOKEN_VALIDATION_MAPPING.items()))-def test_capture_method_error(- token, error, dummy_payment_data, dummy_gateway_config, monkeypatch-):- # given- dummy_payment_data.token = token+ with pytest.raises(PaymentError):+ txn = gateway.capture(payment=payment, amount=amount)+ assert txn is None- # when- response = capture(dummy_payment_data, dummy_gateway_config)- # then- assert not response.is_success- assert response.kind == TransactionKind.CAPTURE- assert response.error == error+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)+ assert txn.kind == TransactionKind.CAPTURE+ assert not txn.is_success+ assert txn.payment == payment_txn_preauth@pytest.mark.parametrize(@@ -250,26 +175,25 @@ def test_refund_success(@pytest.mark.parametrize(- "initial_captured_amount, refund_amount, initial_charge_status, error",+ "initial_captured_amount, refund_amount, initial_charge_status",[- (0, 10, ChargeStatus.NOT_CHARGED, CANNOT_REFUND_MORE_THAN_CAPTURE),- (10, 20, ChargeStatus.PARTIALLY_CHARGED, CANNOT_REFUND_MORE_THAN_CAPTURE),- (10, 20, ChargeStatus.FULLY_CHARGED, CANNOT_REFUND_MORE_THAN_CAPTURE),- (10, 20, ChargeStatus.PARTIALLY_REFUNDED, CANNOT_REFUND_MORE_THAN_CAPTURE),- (80, 0, ChargeStatus.FULLY_REFUNDED, AMOUNT_SHOULD_BE_POSITIVE),+ (0, 10, ChargeStatus.NOT_CHARGED),+ (10, 20, ChargeStatus.PARTIALLY_CHARGED),+ (10, 20, ChargeStatus.FULLY_CHARGED),+ (10, 20, ChargeStatus.PARTIALLY_REFUNDED),+ (80, 0, ChargeStatus.FULLY_REFUNDED),],)def test_refund_failed(- initial_captured_amount, refund_amount, error, initial_charge_status, payment_dummy+ initial_captured_amount, refund_amount, initial_charge_status, payment_dummy):payment = payment_dummypayment.charge_status = initial_charge_statuspayment.captured_amount = Decimal(initial_captured_amount)payment.save()- with pytest.raises(PaymentError) as e:- gateway.refund(payment=payment, amount=Decimal(refund_amount))-- assert e._excinfo[1].message == error+ with pytest.raises(PaymentError):+ txn = gateway.refund(payment=payment, amount=Decimal(refund_amount))+ assert txn is Nonedef test_refund_gateway_error(payment_txn_captured, monkeypatch):@@ -288,119 +212,3 @@ def test_refund_gateway_error(payment_txn_captured, monkeypatch):assert txn.payment == paymentassert payment.charge_status == ChargeStatus.FULLY_CHARGEDassert payment.captured_amount == Decimal("80.00")--[email protected]("token", ["111", PREAUTHORIZED_TOKENS[1]])-def test_process_payment_success(token, payment_dummy):- # when- txn = gateway.process_payment(payment=payment_dummy, token=token)-- # then- assert txn.is_success- assert txn.payment == payment_dummy- assert txn.kind == TransactionKind.CAPTURE- assert not txn.error- payment_dummy.refresh_from_db()- assert payment_dummy.is_active--[email protected]("token, error", list(TOKEN_VALIDATION_MAPPING.items()))-def test_process_payment_failed(token, error, payment_dummy):- # when- with pytest.raises(PaymentError) as e:- gateway.process_payment(payment=payment_dummy, token=token)-- assert e._excinfo[1].message == error---def test_refund_method_error(dummy_payment_data, dummy_gateway_config, monkeypatch):- # given- monkeypatch.setattr("saleor.payment.gateways.dummy.dummy_success", lambda: False)-- # when- response = refund(dummy_payment_data, dummy_gateway_config)-- # then- assert not response.is_success- assert response.kind == TransactionKind.REFUND- assert response.error == "Unable to process refund"---def test_process_payment_pre_authorized(- payment_dummy, dummy_gateway_config, monkeypatch-):- # given- token = PREAUTHORIZED_TOKENS[1]- dummy_gateway_config.auto_capture = False- monkeypatch.setattr(- "saleor.payment.gateways.dummy.plugin.DummyGatewayPlugin._get_gateway_config",- lambda _: dummy_gateway_config,- )-- # when- txn = gateway.process_payment(payment=payment_dummy, token=token)-- # then- assert txn.is_success- assert txn.payment == payment_dummy- assert txn.kind == TransactionKind.AUTH- assert not txn.error- payment_dummy.refresh_from_db()- assert payment_dummy.is_active---def test_process_payment_pre_authorized_and_capture(- payment_dummy, dummy_gateway_config, monkeypatch-):- # given- token = PREAUTHORIZED_TOKENS[1]- dummy_gateway_config.auto_capture = True- monkeypatch.setattr(- "saleor.payment.gateways.dummy.plugin.DummyGatewayPlugin._get_gateway_config",- lambda _: dummy_gateway_config,- )-- # when- txn = gateway.process_payment(payment=payment_dummy, token=token)-- # then- assert txn.is_success- assert txn.payment == payment_dummy- assert txn.kind == TransactionKind.CAPTURE- assert not txn.error- payment_dummy.refresh_from_db()- assert payment_dummy.is_active---def test_process_payment_pre_authorized_and_capture_error(- payment_dummy, dummy_gateway_config, monkeypatch-):- # given- token = TOKEN_EXPIRED- dummy_gateway_config.auto_capture = True- monkeypatch.setattr(- "saleor.payment.gateways.dummy.plugin.DummyGatewayPlugin._get_gateway_config",- lambda _: dummy_gateway_config,- )-- # when- with pytest.raises(PaymentError) as e:- gateway.process_payment(payment=payment_dummy, token=token)-- assert e._excinfo[1].message == TOKEN_VALIDATION_MAPPING[token]--[email protected]("token, error", list(TOKEN_VALIDATION_MAPPING.items()))-def test_process_payment_method_error_in_response(- token, error, dummy_gateway_config, dummy_payment_data-):- # given- dummy_payment_data.token = token-- # when- response = process_payment(dummy_payment_data, dummy_gateway_config)-- # then- assert not response.is_success- assert response.kind == TransactionKind.CAPTURE- assert response.error == errordiff --git a/saleor/payment/gateways/dummy_credit_card/__init__.py b/saleor/payment/gateways/dummy_credit_card/__init__.pynew file mode 100644index 0000000000..eb45c28f3a--- /dev/null+++ b/saleor/payment/gateways/dummy_credit_card/__init__.py@@ -0,0 +1,132 @@+import uuid+from typing import Optional++from ... import TransactionKind+from ...interface import GatewayConfig, GatewayResponse, PaymentData++TOKEN_PREAUTHORIZE_SUCCESS = "4111111111111112"+TOKEN_PREAUTHORIZE_DECLINE = "4111111111111111"+TOKEN_EXPIRED = "4000000000000069"+TOKEN_INSUFFICIENT_FUNDS = "4000000000009995"+TOKEN_INCORRECT_CVV = "4000000000000127"+TOKEN_DECLINE = "4000000000000002"++PREAUTHORIZED_TOKENS = [TOKEN_PREAUTHORIZE_DECLINE, TOKEN_PREAUTHORIZE_SUCCESS]++TOKEN_VALIDATION_MAPPING = {+ TOKEN_EXPIRED: "Card expired",+ TOKEN_INSUFFICIENT_FUNDS: "Insufficient funds",+ TOKEN_INCORRECT_CVV: "Incorrect CVV",+ TOKEN_DECLINE: "Card declined",+ TOKEN_PREAUTHORIZE_DECLINE: "Card declined",+}+++def dummy_success():+ return True+++def validate_token(token: Optional[str]):+ return TOKEN_VALIDATION_MAPPING.get(token, None) if token else None+++def get_client_token(**_):+ return str(uuid.uuid4())+++def authorize(+ payment_information: PaymentData, config: GatewayConfig+) -> GatewayResponse:+ success = dummy_success()+ error = None+ if not success:+ error = "Unable to authorize transaction"+ return GatewayResponse(+ is_success=success,+ action_required=False,+ kind=TransactionKind.AUTH,+ amount=payment_information.amount,+ currency=payment_information.currency,+ transaction_id=payment_information.token,+ error=error,+ )+++def void(payment_information: PaymentData, config: GatewayConfig) -> GatewayResponse:+ error = None+ success = dummy_success()+ if not success:+ error = "Unable to void the transaction."+ return GatewayResponse(+ is_success=success,+ action_required=False,+ kind=TransactionKind.VOID,+ amount=payment_information.amount,+ currency=payment_information.currency,+ transaction_id=payment_information.token,+ error=error,+ )+++def capture(payment_information: PaymentData, config: GatewayConfig) -> GatewayResponse:+ """Perform capture transaction."""+ error = validate_token(payment_information.token)+ success = not error++ return GatewayResponse(+ is_success=success,+ action_required=False,+ kind=TransactionKind.CAPTURE,+ amount=payment_information.amount,+ currency=payment_information.currency,+ transaction_id=payment_information.token,+ error=error,+ )+++def confirm(payment_information: PaymentData, config: GatewayConfig) -> GatewayResponse:+ """Perform confirm transaction."""+ error = None+ success = dummy_success()+ if not success:+ error = "Unable to process capture"++ return GatewayResponse(+ is_success=success,+ action_required=False,+ kind=TransactionKind.CAPTURE,+ amount=payment_information.amount,+ currency=payment_information.currency,+ transaction_id=payment_information.token,+ error=error,+ )+++def refund(payment_information: PaymentData, config: GatewayConfig) -> GatewayResponse:+ error = None+ success = dummy_success()+ if not success:+ error = "Unable to process refund"+ return GatewayResponse(+ is_success=success,+ action_required=False,+ kind=TransactionKind.REFUND,+ amount=payment_information.amount,+ currency=payment_information.currency,+ transaction_id=payment_information.token,+ error=error,+ )+++def process_payment(+ payment_information: PaymentData, config: GatewayConfig+) -> GatewayResponse:+ """Process the payment."""+ token = payment_information.token++ if token in PREAUTHORIZED_TOKENS:+ authorize_response = authorize(payment_information, config)+ if not config.auto_capture:+ return authorize_response++ return capture(payment_information, config)diff --git a/saleor/payment/gateways/dummy_credit_card/plugin.py b/saleor/payment/gateways/dummy_credit_card/plugin.pynew file mode 100644index 0000000000..99b9f9806c--- /dev/null+++ b/saleor/payment/gateways/dummy_credit_card/plugin.py@@ -0,0 +1,125 @@+from typing import TYPE_CHECKING++from django.conf import settings++from saleor.plugins.base_plugin import BasePlugin, ConfigurationTypeField++from ..utils import get_supported_currencies+from . import (+ GatewayConfig,+ authorize,+ capture,+ confirm,+ get_client_token,+ process_payment,+ refund,+ void,+)++GATEWAY_NAME = "Dummy Credit Card"++if TYPE_CHECKING:+ from ...interface import GatewayResponse, PaymentData, TokenConfig+++def require_active_plugin(fn):+ def wrapped(self, *args, **kwargs):+ previous = kwargs.get("previous_value", None)+ if not self.active:+ return previous+ return fn(self, *args, **kwargs)++ return wrapped+++class DummyCreditCardGatewayPlugin(BasePlugin):+ PLUGIN_ID = "mirumee.payments.dummy_credit_card"+ PLUGIN_NAME = GATEWAY_NAME+ DEFAULT_ACTIVE = True+ DEFAULT_CONFIGURATION = [+ {"name": "Store customers card", "value": False},+ {"name": "Automatic payment capture", "value": True},+ {"name": "Supported currencies", "value": settings.DEFAULT_CURRENCY},+ ]+ CONFIG_STRUCTURE = {+ "Store customers card": {+ "type": ConfigurationTypeField.BOOLEAN,+ "help_text": "Determines if Saleor should store cards.",+ "label": "Store customers card",+ },+ "Automatic payment capture": {+ "type": ConfigurationTypeField.BOOLEAN,+ "help_text": "Determines if Saleor should automaticaly capture payments.",+ "label": "Automatic payment capture",+ },+ "Supported currencies": {+ "type": ConfigurationTypeField.STRING,+ "help_text": "Determines currencies supported by gateway."+ " Please enter currency codes separated by a comma.",+ "label": "Supported currencies",+ },+ }++ def __init__(self, *args, **kwargs):+ super().__init__(*args, **kwargs)+ configuration = {item["name"]: item["value"] for item in self.configuration}+ self.config = GatewayConfig(+ gateway_name=GATEWAY_NAME,+ auto_capture=configuration["Automatic payment capture"],+ supported_currencies=configuration["Supported currencies"],+ connection_params={},+ store_customer=configuration["Store customers card"],+ )++ def _get_gateway_config(self):+ return self.config++ @require_active_plugin+ def authorize_payment(+ self, payment_information: "PaymentData", previous_value+ ) -> "GatewayResponse":+ return authorize(payment_information, self._get_gateway_config())++ @require_active_plugin+ def capture_payment(+ self, payment_information: "PaymentData", previous_value+ ) -> "GatewayResponse":+ return capture(payment_information, self._get_gateway_config())++ @require_active_plugin+ def confirm_payment(+ self, payment_information: "PaymentData", previous_value+ ) -> "GatewayResponse":+ return confirm(payment_information, self._get_gateway_config())++ @require_active_plugin+ def refund_payment(+ self, payment_information: "PaymentData", previous_value+ ) -> "GatewayResponse":+ return refund(payment_information, self._get_gateway_config())++ @require_active_plugin+ def void_payment(+ self, payment_information: "PaymentData", previous_value+ ) -> "GatewayResponse":+ return void(payment_information, self._get_gateway_config())++ @require_active_plugin+ def process_payment(+ self, payment_information: "PaymentData", previous_value+ ) -> "GatewayResponse":+ return process_payment(payment_information, self._get_gateway_config())++ @require_active_plugin+ def get_client_token(self, token_config: "TokenConfig", previous_value):+ return get_client_token()++ @require_active_plugin+ def get_supported_currencies(self, previous_value):+ config = self._get_gateway_config()+ return get_supported_currencies(config, GATEWAY_NAME)++ @require_active_plugin+ def get_payment_config(self, previous_value):+ config = self._get_gateway_config()+ return [{"field": "store_customer_card", "value": config.store_customer}]diff --git a/saleor/payment/gateways/dummy_credit_card/tests/__init__.py b/saleor/payment/gateways/dummy_credit_card/tests/__init__.pynew file mode 100644index 0000000000..e69de29bb2diff --git a/saleor/payment/gateways/dummy_credit_card/tests/test_dummy_credit_card.py b/saleor/payment/gateways/dummy_credit_card/tests/test_dummy_credit_card.pynew file mode 100644index 0000000000..96cc020b8f--- /dev/null+++ b/saleor/payment/gateways/dummy_credit_card/tests/test_dummy_credit_card.py@@ -0,0 +1,439 @@+from decimal import Decimal++import pytest++from .... import ChargeStatus, PaymentError, TransactionKind, gateway+from .. import (+ PREAUTHORIZED_TOKENS,+ TOKEN_EXPIRED,+ TOKEN_VALIDATION_MAPPING,+ authorize,+ capture,+ process_payment,+ refund,+ void,+)++NO_LONGER_ACTIVE = "This payment is no longer active."+CANNOT_BE_AUTHORIZED_AGAIN = "Charged transactions cannot be authorized again."+LACK_OF_SUCCESSFUL_TRANSACTION = "Cannot find successful auth transaction."+CANNOT_BE_CAPTURED = "This payment cannot be captured."+CANNOT_REFUND_MORE_THAN_CAPTURE = "Cannot refund more than captured."+AMOUNT_SHOULD_BE_POSITIVE = "Amount should be a positive number."+CANNOT_CHARGE_MORE_THAN_UNCAPTURED = "Unable to charge more than un-captured amount."++[email protected](autouse=True)+def setup_dummy_credit_card_gateway(settings):+ settings.PLUGINS = [+ "saleor.payment.gateways.dummy_credit_card.plugin.DummyCreditCardGatewayPlugin"+ ]+ return settings+++def test_authorize_success(payment_dummy_credit_card):+ txn = gateway.authorize(payment=payment_dummy_credit_card, token="Fake")+ assert txn.is_success+ assert txn.kind == TransactionKind.AUTH+ assert txn.payment == payment_dummy_credit_card+ payment_dummy_credit_card.refresh_from_db()+ assert payment_dummy_credit_card.is_active+++ "is_active, charge_status, error",+ [+ (False, ChargeStatus.NOT_CHARGED, NO_LONGER_ACTIVE),+ (False, ChargeStatus.PARTIALLY_CHARGED, NO_LONGER_ACTIVE),+ (False, ChargeStatus.FULLY_CHARGED, NO_LONGER_ACTIVE),+ (False, ChargeStatus.PARTIALLY_REFUNDED, NO_LONGER_ACTIVE),+ (False, ChargeStatus.FULLY_REFUNDED, NO_LONGER_ACTIVE),+ (True, ChargeStatus.PARTIALLY_CHARGED, CANNOT_BE_AUTHORIZED_AGAIN),+ (True, ChargeStatus.FULLY_CHARGED, CANNOT_BE_AUTHORIZED_AGAIN),+ (True, ChargeStatus.PARTIALLY_REFUNDED, CANNOT_BE_AUTHORIZED_AGAIN),+ (True, ChargeStatus.FULLY_REFUNDED, CANNOT_BE_AUTHORIZED_AGAIN),+ ],+)+def test_authorize_failed(is_active, charge_status, error, payment_dummy_credit_card):+ payment = payment_dummy_credit_card+ payment.is_active = is_active+ payment.charge_status = charge_status+ payment.save()+ with pytest.raises(PaymentError) as e:+ gateway.authorize(payment=payment, token="Fake")++ assert e._excinfo[1].message == error+++def test_authorize_gateway_error(payment_dummy_credit_card, monkeypatch):+ monkeypatch.setattr(+ "saleor.payment.gateways.dummy_credit_card.dummy_success", lambda: False+ )+ with pytest.raises(PaymentError) as e:+ gateway.authorize(payment=payment_dummy_credit_card, token="Fake")++ assert e._excinfo[1].message == "Unable to authorize transaction"+++def test_authorize_method_error(dummy_payment_data, dummy_gateway_config, monkeypatch):+ # given+ monkeypatch.setattr(+ "saleor.payment.gateways.dummy_credit_card.dummy_success", lambda: False+ )++ # when+ response = authorize(dummy_payment_data, dummy_gateway_config)++ # then+ assert not response.is_success+ assert response.kind == TransactionKind.AUTH+ assert response.error == "Unable to authorize transaction"+++def test_void_success(payment_txn_preauth):+ payment_txn_preauth.gateway = "mirumee.payments.dummy_credit_card"+ payment_txn_preauth.save()++ assert payment_txn_preauth.is_active+ assert payment_txn_preauth.charge_status == ChargeStatus.NOT_CHARGED+ txn = gateway.void(payment=payment_txn_preauth)+ assert txn.is_success+ assert txn.kind == TransactionKind.VOID+ assert txn.payment == payment_txn_preauth+ payment_txn_preauth.refresh_from_db()+ assert not payment_txn_preauth.is_active+ assert payment_txn_preauth.charge_status == ChargeStatus.NOT_CHARGED+++ "is_active, charge_status, error",+ [+ (False, ChargeStatus.NOT_CHARGED, NO_LONGER_ACTIVE),+ (False, ChargeStatus.PARTIALLY_CHARGED, NO_LONGER_ACTIVE),+ (False, ChargeStatus.FULLY_CHARGED, NO_LONGER_ACTIVE),+ (False, ChargeStatus.PARTIALLY_REFUNDED, NO_LONGER_ACTIVE),+ (False, ChargeStatus.FULLY_REFUNDED, NO_LONGER_ACTIVE),+ (True, ChargeStatus.PARTIALLY_CHARGED, LACK_OF_SUCCESSFUL_TRANSACTION),+ (True, ChargeStatus.FULLY_CHARGED, LACK_OF_SUCCESSFUL_TRANSACTION),+ (True, ChargeStatus.PARTIALLY_REFUNDED, LACK_OF_SUCCESSFUL_TRANSACTION),+ (True, ChargeStatus.FULLY_REFUNDED, LACK_OF_SUCCESSFUL_TRANSACTION),+ ],+)+def test_void_failed(is_active, charge_status, error, payment_dummy_credit_card):+ payment = payment_dummy_credit_card+ payment.is_active = is_active+ payment.charge_status = charge_status+ payment.save()+ with pytest.raises(PaymentError) as e:+ gateway.void(payment=payment)++ assert e._excinfo[1].message == error+++def test_void_gateway_error(payment_txn_preauth, monkeypatch):+ payment_txn_preauth.gateway = "mirumee.payments.dummy_credit_card"+ payment_txn_preauth.save()++ monkeypatch.setattr(+ "saleor.payment.gateways.dummy_credit_card.dummy_success", lambda: False+ )+ with pytest.raises(PaymentError) as e:+ gateway.void(payment=payment_txn_preauth)++ assert e._excinfo[1].message == "Unable to void the transaction."+++def test_void_method_error(dummy_payment_data, dummy_gateway_config, monkeypatch):+ # given+ monkeypatch.setattr(+ "saleor.payment.gateways.dummy_credit_card.dummy_success", lambda: False+ )++ # when+ response = void(dummy_payment_data, dummy_gateway_config)++ # then+ assert not response.is_success+ assert response.kind == TransactionKind.VOID+ assert response.error == "Unable to void the transaction."+++ "amount, charge_status, token",+ [+ ("98.40", ChargeStatus.FULLY_CHARGED, "1111111111111111"),+ (70, ChargeStatus.PARTIALLY_CHARGED, "2222222222222222"),+ (70, ChargeStatus.PARTIALLY_CHARGED, "fake"),+ ],+)+def test_capture_success(amount, charge_status, token, payment_txn_preauth):+ payment_txn_preauth.gateway = "mirumee.payments.dummy_credit_card"+ transaction = payment_txn_preauth.transactions.last()+ transaction.token = token+ transaction.save()++ txn = gateway.capture(payment=payment_txn_preauth, amount=Decimal(amount))+ assert txn.is_success+ assert txn.payment == payment_txn_preauth+ assert not txn.error+ payment_txn_preauth.refresh_from_db()+ assert payment_txn_preauth.charge_status == charge_status+ assert payment_txn_preauth.is_active+++ "amount, captured_amount, charge_status, is_active, error",+ [+ (80, 0, ChargeStatus.NOT_CHARGED, False, NO_LONGER_ACTIVE),+ (120, 0, ChargeStatus.NOT_CHARGED, True, CANNOT_CHARGE_MORE_THAN_UNCAPTURED),+ (80, 20, ChargeStatus.PARTIALLY_CHARGED, True, CANNOT_BE_CAPTURED),+ (80, 80, ChargeStatus.FULLY_CHARGED, True, CANNOT_BE_CAPTURED),+ (80, 0, ChargeStatus.FULLY_REFUNDED, True, CANNOT_BE_CAPTURED),+ ],+)+def test_capture_failed(+ amount, captured_amount, charge_status, error, is_active, payment_dummy_credit_card+):+ payment = payment_dummy_credit_card+ payment.is_active = is_active+ payment.captured_amount = captured_amount+ payment.charge_status = charge_status+ payment.save()+ with pytest.raises(PaymentError) as e:+ gateway.capture(payment=payment, amount=amount)++ assert e._excinfo[1].message == error++[email protected]("token, error", list(TOKEN_VALIDATION_MAPPING.items()))+def test_capture_error_in_response(token, error, payment_txn_preauth):+ # given+ payment_txn_preauth.gateway = "mirumee.payments.dummy_credit_card"+ payment_txn_preauth.save()++ transaction = payment_txn_preauth.transactions.last()+ transaction.token = token+ transaction.save()++ # when+ with pytest.raises(PaymentError) as e:+ gateway.capture(payment=payment_txn_preauth)++ assert e._excinfo[1].message == error++[email protected]("token, error", list(TOKEN_VALIDATION_MAPPING.items()))+def test_capture_method_error(+ token, error, dummy_payment_data, dummy_gateway_config, monkeypatch+):+ # given+ dummy_payment_data.token = token++ # when+ response = capture(dummy_payment_data, dummy_gateway_config)++ # then+ assert not response.is_success+ assert response.kind == TransactionKind.CAPTURE+ assert response.error == error+++ (+ "initial_captured_amount, refund_amount, final_captured_amount, "+ "final_charge_status, active_after"+ ),+ [+ (80, 80, 0, ChargeStatus.FULLY_REFUNDED, False),+ (80, 10, 70, ChargeStatus.PARTIALLY_REFUNDED, True),+ ],+)+def test_refund_success(+ initial_captured_amount,+ refund_amount,+ final_captured_amount,+ final_charge_status,+ active_after,+ payment_txn_captured,+):+ payment = payment_txn_captured+ payment.gateway = "mirumee.payments.dummy_credit_card"+ payment.charge_status = ChargeStatus.FULLY_CHARGED+ payment.captured_amount = initial_captured_amount+ payment.save()+ txn = gateway.refund(payment=payment, amount=Decimal(refund_amount))+ assert txn.kind == TransactionKind.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+++ "initial_captured_amount, refund_amount, initial_charge_status, error",+ [+ (0, 10, ChargeStatus.NOT_CHARGED, CANNOT_REFUND_MORE_THAN_CAPTURE),+ (10, 20, ChargeStatus.PARTIALLY_CHARGED, CANNOT_REFUND_MORE_THAN_CAPTURE),+ (10, 20, ChargeStatus.FULLY_CHARGED, CANNOT_REFUND_MORE_THAN_CAPTURE),+ (10, 20, ChargeStatus.PARTIALLY_REFUNDED, CANNOT_REFUND_MORE_THAN_CAPTURE),+ (80, 0, ChargeStatus.FULLY_REFUNDED, AMOUNT_SHOULD_BE_POSITIVE),+ ],+)+def test_refund_failed(+ initial_captured_amount,+ refund_amount,+ error,+ initial_charge_status,+ payment_dummy_credit_card,+):+ payment = payment_dummy_credit_card+ payment.charge_status = initial_charge_status+ payment.captured_amount = Decimal(initial_captured_amount)+ payment.save()+ with pytest.raises(PaymentError) as e:+ gateway.refund(payment=payment, amount=Decimal(refund_amount))++ assert e._excinfo[1].message == error+++def test_refund_gateway_error(payment_txn_captured, monkeypatch):+ monkeypatch.setattr(+ "saleor.payment.gateways.dummy_credit_card.dummy_success", lambda: False+ )+ payment = payment_txn_captured+ payment.gateway = "mirumee.payments.dummy_credit_card"+ payment.charge_status = ChargeStatus.FULLY_CHARGED+ payment.captured_amount = Decimal("80.00")+ payment.save()+ with pytest.raises(PaymentError):+ gateway.refund(payment=payment, amount=Decimal("80.00"))++ payment.refresh_from_db()+ txn = payment.transactions.last()+ assert txn.kind == TransactionKind.REFUND+ assert not txn.is_success+ assert txn.payment == payment+ assert payment.charge_status == ChargeStatus.FULLY_CHARGED+ assert payment.captured_amount == Decimal("80.00")++[email protected]("token", ["111", PREAUTHORIZED_TOKENS[1]])+def test_process_payment_success(token, payment_dummy_credit_card):+ # when+ txn = gateway.process_payment(payment=payment_dummy_credit_card, token=token)++ # then+ assert txn.is_success+ assert txn.payment == payment_dummy_credit_card+ assert txn.kind == TransactionKind.CAPTURE+ assert not txn.error+ payment_dummy_credit_card.refresh_from_db()+ assert payment_dummy_credit_card.is_active++[email protected]("token, error", list(TOKEN_VALIDATION_MAPPING.items()))+def test_process_payment_failed(token, error, payment_dummy_credit_card):+ # when+ with pytest.raises(PaymentError) as e:+ gateway.process_payment(payment=payment_dummy_credit_card, token=token)++ assert e._excinfo[1].message == error+++def test_refund_method_error(dummy_payment_data, dummy_gateway_config, monkeypatch):+ # given+ monkeypatch.setattr(+ "saleor.payment.gateways.dummy_credit_card.dummy_success", lambda: False+ )++ # when+ response = refund(dummy_payment_data, dummy_gateway_config)++ # then+ assert not response.is_success+ assert response.kind == TransactionKind.REFUND+ assert response.error == "Unable to process refund"+++def test_process_payment_pre_authorized(+ payment_dummy_credit_card, dummy_gateway_config, monkeypatch+):+ # given+ token = PREAUTHORIZED_TOKENS[1]+ dummy_gateway_config.auto_capture = False+ monkeypatch.setattr(+ "saleor.payment.gateways.dummy_credit_card.plugin."+ "DummyCreditCardGatewayPlugin._get_gateway_config",+ lambda _: dummy_gateway_config,+ )++ # when+ txn = gateway.process_payment(payment=payment_dummy_credit_card, token=token)++ # then+ assert txn.is_success+ assert txn.payment == payment_dummy_credit_card+ assert txn.kind == TransactionKind.AUTH+ assert not txn.error+ payment_dummy_credit_card.refresh_from_db()+ assert payment_dummy_credit_card.is_active+++def test_process_payment_pre_authorized_and_capture(+ payment_dummy_credit_card, dummy_gateway_config, monkeypatch+):+ # given+ token = PREAUTHORIZED_TOKENS[1]+ dummy_gateway_config.auto_capture = True+ monkeypatch.setattr(+ "saleor.payment.gateways.dummy_credit_card.plugin."+ "DummyCreditCardGatewayPlugin._get_gateway_config",+ lambda _: dummy_gateway_config,+ )++ # when+ txn = gateway.process_payment(payment=payment_dummy_credit_card, token=token)++ # then+ assert txn.is_success+ assert txn.payment == payment_dummy_credit_card+ assert txn.kind == TransactionKind.CAPTURE+ assert not txn.error+ payment_dummy_credit_card.refresh_from_db()+ assert payment_dummy_credit_card.is_active+++def test_process_payment_pre_authorized_and_capture_error(+ payment_dummy_credit_card, dummy_gateway_config, monkeypatch+):+ # given+ token = TOKEN_EXPIRED+ dummy_gateway_config.auto_capture = True+ monkeypatch.setattr(+ "saleor.payment.gateways.dummy_credit_card.plugin."+ "DummyCreditCardGatewayPlugin._get_gateway_config",+ lambda _: dummy_gateway_config,+ )++ # when+ with pytest.raises(PaymentError) as e:+ gateway.process_payment(payment=payment_dummy_credit_card, token=token)++ assert e._excinfo[1].message == TOKEN_VALIDATION_MAPPING[token]++[email protected]("token, error", list(TOKEN_VALIDATION_MAPPING.items()))+def test_process_payment_method_error_in_response(+ token, error, dummy_gateway_config, dummy_payment_data+):+ # given+ dummy_payment_data.token = token++ # when+ response = process_payment(dummy_payment_data, dummy_gateway_config)++ # then+ assert not response.is_success+ assert response.kind == TransactionKind.CAPTURE+ assert response.error == errordiff --git a/saleor/settings.py b/saleor/settings.pyindex 5fc76d842d..08e73a4817 100644--- a/saleor/settings.py+++ b/saleor/settings.py@@ -511,6 +511,7 @@ PLUGINS = ["saleor.plugins.vatlayer.plugin.VatlayerPlugin","saleor.plugins.webhook.plugin.WebhookPlugin","saleor.payment.gateways.dummy.plugin.DummyGatewayPlugin",+ "saleor.payment.gateways.dummy_credit_card.plugin.DummyCreditCardGatewayPlugin","saleor.payment.gateways.stripe.plugin.StripeGatewayPlugin","saleor.payment.gateways.braintree.plugin.BraintreeGatewayPlugin","saleor.payment.gateways.razorpay.plugin.RazorpayGatewayPlugin",diff --git a/saleor/tests/fixtures.py b/saleor/tests/fixtures.pyindex fbdfd6efed..29be0e7bac 100644--- a/saleor/tests/fixtures.py+++ b/saleor/tests/fixtures.py@@ -187,8 +187,11 @@ def setup_vatlayer(settings):@pytest.fixture(autouse=True)-def setup_dummy_gateway(settings):- settings.PLUGINS = ["saleor.payment.gateways.dummy.plugin.DummyGatewayPlugin"]+def setup_dummy_gateways(settings):+ settings.PLUGINS = [+ "saleor.payment.gateways.dummy.plugin.DummyGatewayPlugin",+ "saleor.payment.gateways.dummy_credit_card.plugin.DummyCreditCardGatewayPlugin",+ ]return settings@@ -1930,6 +1933,32 @@ def payment_dummy(db, order_with_lines):)+def payment_dummy_credit_card(db, order_with_lines):+ return Payment.objects.create(+ gateway="mirumee.payments.dummy_credit_card",+ order=order_with_lines,+ is_active=True,+ cc_first_digits="4111",+ cc_last_digits="1111",+ cc_brand="VISA",+ cc_exp_month=12,+ cc_exp_year=2027,+ total=order_with_lines.total.gross.amount,+ currency=order_with_lines.total.gross.currency,+ billing_first_name=order_with_lines.billing_address.first_name,+ billing_last_name=order_with_lines.billing_address.last_name,+ billing_company_name=order_with_lines.billing_address.company_name,+ billing_address_1=order_with_lines.billing_address.street_address_1,+ billing_address_2=order_with_lines.billing_address.street_address_2,+ billing_city=order_with_lines.billing_address.city,+ billing_postal_code=order_with_lines.billing_address.postal_code,+ billing_country_code=order_with_lines.billing_address.country.code,+ billing_country_area=order_with_lines.billing_address.country_area,+ billing_email=order_with_lines.user_email,+ )++@pytest.fixturedef digital_content(category, media_root, warehouse) -> DigitalContent:product_type = ProductType.objects.create(