Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Change dummy payment implementation
IKarbowiak2611830c819e
diff --git a/saleor/graphql/payment/tests/test_payment.py b/saleor/graphql/payment/tests/test_payment.pyindex 8054b70b7f..31ec4e4f3c 100644--- a/saleor/graphql/payment/tests/test_payment.py+++ b/saleor/graphql/payment/tests/test_payment.py@@ -469,6 +469,10 @@ def test_payment_capture_gateway_error(staff_api_client, permission_manage_orders, payment_txn_preauth, monkeypatch):payment = payment_txn_preauth+ transaction = payment.transactions.last()+ transaction.token = "4000000000000069"+ transaction.save()+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)}@@ -478,7 +482,7 @@ def test_payment_capture_gateway_error()content = get_graphql_content(response)data = content["data"]["paymentCapture"]- assert data["errors"] == [{"field": None, "message": "Unable to process capture"}]+ assert data["errors"] == [{"field": None, "message": "Card expired"}]payment_txn_preauth.refresh_from_db()assert payment.charge_status == ChargeStatus.NOT_CHARGEDdiff --git a/saleor/payment/gateways/dummy/__init__.py b/saleor/payment/gateways/dummy/__init__.pyindex ee4eae71c5..e10ff8a121 100644--- a/saleor/payment/gateways/dummy/__init__.py+++ b/saleor/payment/gateways/dummy/__init__.py@@ -1,13 +1,28 @@import uuid+from typing import Optional-from ... import ChargeStatus, TransactionKind+from ... import TransactionKindfrom ...interface import GatewayConfig, GatewayResponse, PaymentData+PREAUTHORIZED_TOKENS = ["4111111111111111", "4111111111111112"]++TOKEN_VALIDATION_MAPPING = {+ "4000000000000069": "Card expired",+ "4000000000009995": "Insufficient funds",+ "4000000000000127": "Incorrect csv",+ "4000000000000002": "Card declined",+ "4111111111111111": "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())@@ -48,10 +63,8 @@ def void(payment_information: PaymentData, config: GatewayConfig) -> GatewayRespdef capture(payment_information: PaymentData, config: GatewayConfig) -> GatewayResponse:"""Perform capture transaction."""- error = None- success = dummy_success()- if not success:- error = "Unable to process capture"+ error = validate_token(payment_information.token)+ success = not errorreturn GatewayResponse(is_success=success,@@ -104,21 +117,7 @@ def process_payment("""Process the payment."""token = payment_information.token- # 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+ if token in PREAUTHORIZED_TOKENS and not config.auto_capture:+ return authorize(payment_information, config)- capture_response = capture(payment_information, config)- if charge_status == ChargeStatus.FULLY_REFUNDED:- return refund(payment_information, config)- return capture_response+ return capture(payment_information, config)diff --git a/saleor/payment/gateways/dummy/tests/test_dummy.py b/saleor/payment/gateways/dummy/tests/test_dummy.pyindex dab6f8f503..8534f2a25d 100644--- a/saleor/payment/gateways/dummy/tests/test_dummy.py+++ b/saleor/payment/gateways/dummy/tests/test_dummy.py@@ -3,6 +3,7 @@ from decimal import Decimalimport pytestfrom .... import ChargeStatus, PaymentError, TransactionKind, gateway+from .. import PREAUTHORIZED_TOKENS, process_payment@pytest.fixture(autouse=True)@@ -99,13 +100,22 @@ def test_void_gateway_error(payment_txn_preauth, monkeypatch):@pytest.mark.parametrize(- "amount, charge_status",- [("98.40", ChargeStatus.FULLY_CHARGED), (70, ChargeStatus.PARTIALLY_CHARGED)],+ "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, payment_txn_preauth):+def test_capture_success(amount, charge_status, token, payment_txn_preauth):+ transaction = payment_txn_preauth.transactions.last()+ transaction.token = token+ transaction.save()+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@@ -134,13 +144,27 @@ def test_capture_failed(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)- assert txn.kind == TransactionKind.CAPTURE- assert not txn.is_success- assert txn.payment == payment_txn_preauth+ "token, error",+ [+ ("4000000000000069", "Card expired"),+ ("4000000000009995", "Insufficient funds"),+ ("4000000000000127", "Incorrect csv"),+ ("4000000000000002", "Card declined"),+ ("4111111111111111", "Card declined"),+ ],+)+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)++ e._excinfo[1].message == error@pytest.mark.parametrize(@@ -212,3 +236,83 @@ 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+++ "token, error",+ [+ ("4000000000000069", "Card expired"),+ ("4000000000009995", "Insufficient funds"),+ ("4000000000000127", "Incorrect csv"),+ ("4000000000000002", "Card declined"),+ ("4111111111111111", "Card declined"),+ ],+)+def test_process_payment_failed(token, error, payment_dummy):+ # when+ with pytest.raises(PaymentError) as e:+ gateway.process_payment(payment=payment_dummy, token=token)++ e._excinfo[1].message == error++[email protected]("token", PREAUTHORIZED_TOKENS)+def test_process_payment_pre_authorized(+ token, payment_dummy, dummy_gateway_config, monkeypatch+):+ # given+ 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+++ "token, error",+ [+ ("4000000000000069", "Card expired"),+ ("4000000000009995", "Insufficient funds"),+ ("4000000000000127", "Incorrect csv"),+ ("4000000000000002", "Card declined"),+ ("4111111111111111", "Card declined"),+ ],+)+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/tests/test_payment.py b/saleor/payment/tests/test_payment.pyindex 02daf3f1df..25c76009b6 100644--- a/saleor/payment/tests/test_payment.py+++ b/saleor/payment/tests/test_payment.py@@ -6,7 +6,7 @@ import pytestfrom ...checkout.calculations import checkout_totalfrom .. import ChargeStatus, GatewayError, PaymentError, TransactionKind, gatewayfrom ..error_codes import PaymentErrorCode-from ..interface import CreditCardInfo, GatewayConfig, GatewayResponse+from ..interface import CreditCardInfo, GatewayResponsefrom ..models import Paymentfrom ..utils import (ALLOWED_GATEWAY_KINDS,@@ -60,16 +60,6 @@ def transaction_data(payment_dummy, gateway_response):}-def gateway_config():- return GatewayConfig(- gateway_name="Dummy",- auto_capture=True,- supported_currencies="USD",- connection_params={"secret-key": "nobodylikesspanishinqusition"},- )--@pytest.fixturedef transaction_token():return "transaction-token"@@ -462,12 +452,12 @@ def test_validate_gateway_response_not_json_serializable(gateway_response):@pytest.mark.parametrize("currency, exp_response", [("EUR", True), ("USD", True), ("PLN", False)],)-def test_is_currency_supported(currency, exp_response, gateway_config, monkeypatch):+def test_is_currency_supported(currency, exp_response, dummy_gateway_config, monkeypatch):# given- gateway_config.supported_currencies = "USD, EUR"+ dummy_gateway_config.supported_currencies = "USD, EUR"monkeypatch.setattr("saleor.payment.gateways.dummy.plugin.DummyGatewayPlugin._get_gateway_config",- lambda _: gateway_config,+ lambda _: dummy_gateway_config,)# whendiff --git a/saleor/tests/fixtures.py b/saleor/tests/fixtures.pyindex 6ba7218f59..fbdfd6efed 100644--- a/saleor/tests/fixtures.py+++ b/saleor/tests/fixtures.py@@ -50,6 +50,7 @@ from ..order.models import FulfillmentStatus, Order, OrderEvent, OrderLinefrom ..order.utils import recalculate_orderfrom ..page.models import Page, PageTranslationfrom ..payment import ChargeStatus, TransactionKind+from ..payment.interface import GatewayConfig, PaymentDatafrom ..payment.models import Paymentfrom ..plugins.invoicing.plugin import InvoicingPluginfrom ..plugins.models import PluginConfiguration@@ -1551,6 +1552,29 @@ def payment_not_authorized(payment_dummy):return payment_dummy+def dummy_gateway_config():+ return GatewayConfig(+ gateway_name="Dummy",+ auto_capture=True,+ supported_currencies="USD",+ connection_params={"secret-key": "nobodylikesspanishinqusition"},+ )+++def dummy_payment_data():+ return PaymentData(+ amount=10,+ currency="USD",+ billing=None,+ shipping=None,+ order_id=None,+ customer_ip_address=None,+ customer_email="[email protected]",+ )++@pytest.fixturedef sale(product, category, collection):sale = Sale.objects.create(name="Sale", value=5)