Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Test braintree gateway with real sandbox and record vcr cassettes
Jakub Draganek16fc04dfb98e
diff --git a/saleor/payment/__init__.py b/saleor/payment/__init__.pyindex b761f50fc1..f6b4a743a2 100644--- a/saleor/payment/__init__.py+++ b/saleor/payment/__init__.py@@ -129,6 +129,7 @@ def get_payment_gateway(gateway_name):auto_capture=gateway_config["auto_capture"],template_path=gateway_config["template_path"],connection_params=gateway_config["connection_params"],+ store_customer=gateway_config["store_card"],)return gateway_module, configdiff --git a/saleor/payment/gateways/braintree/__init__.py b/saleor/payment/gateways/braintree/__init__.pyindex a435625a18..5e80aa7d0b 100644--- a/saleor/payment/gateways/braintree/__init__.py+++ b/saleor/payment/gateways/braintree/__init__.py@@ -75,11 +75,13 @@ def extract_gateway_response(braintree_result) -> Dict:{"code": error.code, "message": error.message}for error in braintree_result.errors.deep_errors]- customer_id = None-bt_transaction = braintree_result.transaction- if hasattr(bt_transaction, "customer"):- customer_id = bt_transaction.id++ try:+ customer_id = bt_transaction.customer_details.id+ except:+ # TODO: hack for legacy tests, remove when vcr data used everywhere+ customer_id = Noneif not bt_transaction:return {"errors": errors}diff --git a/saleor/payment/interface.py b/saleor/payment/interface.pyindex f13299d582..4c97f8e968 100644--- a/saleor/payment/interface.py+++ b/saleor/payment/interface.py@@ -70,3 +70,4 @@ class GatewayConfig:# Each gateway has different connection data so we are not able to create# a unified structureconnection_params: Dict[str, Any]+ store_customer: bool = Falsediff --git a/saleor/settings.py b/saleor/settings.pyindex 72a5e998fd..878156d36f 100644--- a/saleor/settings.py+++ b/saleor/settings.py@@ -597,18 +597,18 @@ CHECKOUT_PAYMENT_GATEWAYS = {PAYMENT_GATEWAYS = {DUMMY: {"module": "saleor.payment.gateways.dummy",- "store_card": False,"config": {"auto_capture": True,+ "store_card": False,"connection_params": {},"template_path": "order/payment/dummy.html",},},BRAINTREE: {"module": "saleor.payment.gateways.braintree",- "store_card": False,"config": {"auto_capture": True,+ "store_card": False,"template_path": "order/payment/braintree.html","connection_params": {"sandbox_mode": get_bool_from_env("BRAINTREE_SANDBOX_MODE", True),@@ -620,8 +620,8 @@ PAYMENT_GATEWAYS = {},RAZORPAY: {"module": "saleor.payment.gateways.razorpay",- "store_card": False,"config": {+ "store_card": False,"auto_capture": None,"template_path": "order/payment/razorpay.html","connection_params": {@@ -635,8 +635,8 @@ PAYMENT_GATEWAYS = {},STRIPE: {"module": "saleor.payment.gateways.stripe",- "store_card": False,"config": {+ "store_card": False,"auto_capture": True,"template_path": "order/payment/stripe.html","connection_params": {diff --git a/tests/api/test_payment.py b/tests/api/test_payment.pyindex 4a0aa46e61..79d94b9e7d 100644--- a/tests/api/test_payment.py+++ b/tests/api/test_payment.py@@ -532,3 +532,18 @@ def test_use_customer_id_from_meta_on_client_token_generation(assert mock_get_client_token.called_once_with(PaymentGatewayEnum.BRAINTREE.name, token_config=token_config_with_customer)+++def test_list_payment_sources(mocker, set_braintree_customer_id, user_api_client):+ query = """+ {+ paymentStoredSources {+ gateway+ creditCard {+ lastDigits+ }+ }+ }+ """+ response = user_api_client.post_graphql(query)+ get_graphql_content(response)diff --git a/tests/gateway/cassettes/test_authorize_and_save_customer_id.yaml b/tests/gateway/cassettes/test_authorize_and_save_customer_id.yamlnew file mode 100644index 0000000000..bef1d6f3aa--- /dev/null+++ b/tests/gateway/cassettes/test_authorize_and_save_customer_id.yaml@@ -0,0 +1,97 @@+interactions:+- request:+ body: <transaction><amount>100.0</amount><payment_method_nonce>fake-valid-nonce</payment_method_nonce><options><submit_for_settlement+ type="boolean">true</submit_for_settlement><store_in_vault_on_success type="boolean">true</store_in_vault_on_success><three_d_secure><required+ type="boolean">false</required></three_d_secure></options><order_id type="integer">8</order_id><billing><first_name>John</first_name><last_name>Doe</last_name><company>Mirumee+ Software</company><postal_code>53-601</postal_code><street_address>Tęczowa+ 7</street_address><extended_address></extended_address><locality>WROCŁAW</locality><region></region><country_code_alpha2>PL</country_code_alpha2></billing><risk_data><customer_ip></customer_ip></risk_data><customer><email>[email protected]</email></customer><type>sale</type></transaction>+ headers:+ Accept:+ - application/xml+ Accept-Encoding:+ - gzip+ Connection:+ - keep-alive+ Content-Length:+ - '820'+ Content-type:+ - application/xml+ User-Agent:+ - Braintree Python 3.49.0+ X-ApiVersion:+ - '5'+ method: POST+ uri: https://api.sandbox.braintreegateway.com/merchants/9m6qhfxsqzm3cgzw/transactions+ response:+ body:+ string: !!binary |+ H4sIABWIE10AA8RY23LbNhB9z1dolJm80SR1i5zQTD1J4zTT2GlqJ7VfPCABiohJgAFAWcrXd8Gb+ SBGU1Zl2+ibunsVlbzgr780mTUZrIiTl7GzsnjjjEWEhx5StzsY31++t5fiN/8xTAjGJQgUo/9lo+ 5FHs48wN4vk68mz40DKpkMqlL/MgpUoRfB9xcS+JUglJCVOeXQE0Vm0z4kuUEM8ufmpZmAsBe28t+ KrkFRyD+rzdfPLsv1mCU8pwp33WcE8fx7OpTa1IiwhgxZaEw1EILjpdSkaeESB6pRyRgUxOouEMe+ WAbdiNHkbKxETsZ2uQmSioijoFxgQML6S89ufhf3FQSBmyykRtoHZ2MMn4qmZOxPHPfUchbWZHHt+ zl7Nl68mp3fgicagsM8z/M/sdwaVv6XicAP9UYZ0fjp3ndPlfFbHFMQRFVJZDKVk/2agTNCwLuRp+ htjWoCEpoomviFS/kA1Ks4ScANizS3mJeSSBpMq0bhZzZpJHaGOQrhIeoES7/Hb69Se+OFV3f32M+ Lq8f3E/X5/OrdzeQPDuMdovd9osX0CSBWmh8ZNq48ZD/kcfMs1uCPTf57zgk3+6z4yn/U5mloz+b+ NK01JU4qQQjkGsaCSOlfv3g+Wbqvw5/8EY1e6vLqqCtfbxRhWAe9FJuCyEOUULX1v325evvi+XTi+ vj7/BqesxSVKkBUUvykeHOo6KStzPrUWjuvZbVl9RygPsS2v/ZkniGF9vZawi9OmFkqyGE38z7/v+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R8imAGMFLP+ PJChoNkgfW3pm4ej4OZWBnSJYwsYoqU9aqigPSQcSygjFo68t49+jy14eg3cG1NZ1K1RR8pVeF1q+ A51/aKyFXt0/W3dR4LX6TxK410D1NvrySY4RY6S/KsR8rTlERMjQ66+35Y9WGc2eFtwQ5EKWowUm+ Cqb5egztqsyxac0l5u27mN7/QkfCyUY7AF5BYT6GntEgU4FNmxbMw9AwdkBEBu6ub57lihwa2UqC+ gfB3oA3a3oStnnqLMmDSeTkTaqZTduJ73Yk9ewjU5aItp3Qpa5uODoKeXqsgsE+t1bBcFQOpsaAU+ dY4SOHrEjdOotCIBY86BSa0ZWoeyty7TIT0j6pGLh7352Xd0T3YWk4U7my8np549gBti/DoC6CDj+ r2PUTYiCfBI5/P/eS8uZtl+JIfP2PxMN4zAn2cE/Hg7aGv/caCz6o6f574phgx1Vwh8+xgG7jG+n+ X7JgMo/uPpxvbtOVi9PbDqPqvFD+s78BAAD//wMAxyyLJusWAAA=+ headers:+ Cache-Control:+ - max-age=0, private, must-revalidate+ Content-Encoding:+ - gzip+ Content-Security-Policy:+ - frame-ancestors 'self'+ Content-Type:+ - application/xml; charset=utf-8+ Date:+ - Wed, 26 Jun 2019 14:58:29 GMT+ ETag:+ - W/"56150bda74a4f07c25cb1c1b05c341cd"+ Strict-Transport-Security:+ - max-age=31536000; includeSubDomains+ Transfer-Encoding:+ - chunked+ Vary:+ - Accept-Encoding+ X-Authentication:+ - basic_auth+ X-BroxyId:+ - 01-1561561108.960-79.110.196.19-4474532+ X-Content-Type-Options:+ - nosniff+ X-Frame-Options:+ - SAMEORIGIN+ X-Request-Id:+ - 01-1561561108.960-79.110.196.19-4474532+ X-Runtime:+ - '0.603314'+ X-User:+ - wgs3tg8h39pyypyc+ X-XSS-Protection:+ - 1; mode=block+ status:+ code: 201+ message: Created+version: 1diff --git a/tests/gateway/cassettes/test_authorize_one_time.yaml b/tests/gateway/cassettes/test_authorize_one_time.yamlnew file mode 100644index 0000000000..3046a62995--- /dev/null+++ b/tests/gateway/cassettes/test_authorize_one_time.yaml@@ -0,0 +1,95 @@+interactions:+- request:+ body: <transaction><amount>80.00</amount><payment_method_nonce>fake-valid-nonce</payment_method_nonce><options><submit_for_settlement+ type="boolean">false</submit_for_settlement><store_in_vault_on_success type="boolean">false</store_in_vault_on_success><three_d_secure><required+ type="boolean">false</required></three_d_secure></options><order_id type="integer">1</order_id><billing><first_name>John</first_name><last_name>Doe</last_name><company>Mirumee+ Software</company><postal_code>53-601</postal_code><street_address>Tęczowa+ 7</street_address><extended_address></extended_address><locality>WROCŁAW</locality><region></region><country_code_alpha2>PL</country_code_alpha2></billing><risk_data><customer_ip></customer_ip></risk_data><customer><email>[email protected]</email></customer><type>sale</type></transaction>+ headers:+ Accept:+ - application/xml+ Accept-Encoding:+ - gzip+ Connection:+ - keep-alive+ Content-Length:+ - '822'+ Content-type:+ - application/xml+ User-Agent:+ - Braintree Python 3.49.0+ X-ApiVersion:+ - '5'+ method: POST+ uri: https://api.sandbox.braintreegateway.com/merchants/9m6qhfxsqzm3cgzw/transactions+ response:+ body:+ string: !!binary |+ H4sIANSHE10AA6xYbXPbNgz+nl/hc+/6jZHf4ritoq57u61b0y5L19u+9CgJtthIpEpSjt1fP1CU+ ZMmiHO9u3yzgIUgCIPDA/utdlo62IBUT/GY8vZyMR8AjETO+uRl/vP+ZrMavgwtfS8oVjTSigovR+ yGdxsNQvvi7gOvc9/DAypakuVEALnQjJvkHse5XIaPU+h0DRFHyv/GlkUSEl7rYnTAmCm0Lw08c7+ 3+uLDZhmouA6WE0uJxPfq76MIgMZJZRrQqPICAmeJ2OyyACUWOtHKnFPF6g8dBESh27EWXoz1rKA+ sWc3oUqDPAsqZIxItD/1veZ3eV0JVENMqB4ZF9yMY/zULINxMJtMX5DJksyW99PFy6vrl7PFP+iI+ ZkG5vsjj/7b+sKByt9ICb2A+yhgeHx2FayaVJpxm4FCmdFgXiSynfO/QQEZZGmhQ+jvY0SxP4RLB+ vmflFvMIoWLaZTdPB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Ov+ KG33FVZTFkkYZqrcd9hE04lLBKChKqbm6eKYgIosP3N0aPCNhZPjnfXRwIRmPaSQln+JJd1QDg84+ m6h6EDGna9EeJbDQQUBzhqfoy+0dveNLNpLKMbZkIld1UqQiVJFk+SDNaumbEldySJJjWxcxQSZD+ jAudxbCDxGNJ7cTikY/2MX2DYItwcMSYqTIBnTqwVkRd5wZq1NAohVWlf7auUeRfZirHew1kbaO3+ rQNnZA59qxjzrel1a4ChLmW2FY/ERrOnRTeEhVSWAsegcYKsx6Wuyh2bFn92b9/F9P6IOBMOO+MA+ rNfSfQwzS2CmIutzGSyiyEGPMSIDdzc3zwucr0+MFrYV0vgLNjiz3oWtmhJhHBlfYWcX05NtBfps+ KpDvDYG6nKnllC61atOmQdDTtkqi9ZStho3pBNsvwadochTw6GvhnJoUWUuk4ycmima4Gsre+pkO+ 6TnoRyEfjua8YGKK8GQ5W04XV9ezhe8N4IaYqYkAPclM6xh1E6KkSaCG/1G6JpN5uy0MLW9P0E0b+ dSfZyQH55FrnED7YtIfG6uEFjSaIf3mbhPw2+Xt+l4ezq/Ut/+Mqur9Lb+dvfO8Au+h0qODiXwAA+ AP//AwCzQks1ThUAAA==+ headers:+ Cache-Control:+ - max-age=0, private, must-revalidate+ Content-Encoding:+ - gzip+ Content-Security-Policy:+ - frame-ancestors 'self'+ Content-Type:+ - application/xml; charset=utf-8+ Date:+ - Wed, 26 Jun 2019 14:57:24 GMT+ ETag:+ - W/"699549b866d4f0d64241106d9b3872ad"+ Strict-Transport-Security:+ - max-age=31536000; includeSubDomains+ Transfer-Encoding:+ - chunked+ Vary:+ - Accept-Encoding+ X-Authentication:+ - basic_auth+ X-BroxyId:+ - 01-1561561043.981-79.110.196.19-4468768+ X-Content-Type-Options:+ - nosniff+ X-Frame-Options:+ - SAMEORIGIN+ X-Request-Id:+ - 01-1561561043.981-79.110.196.19-4468768+ X-Runtime:+ - '0.367291'+ X-User:+ - wgs3tg8h39pyypyc+ X-XSS-Protection:+ - 1; mode=block+ status:+ code: 201+ message: Created+version: 1diff --git a/tests/gateway/test_braintree.py b/tests/gateway/test_braintree.pyindex d4be5f3a21..6b3b96798e 100644--- a/tests/gateway/test_braintree.py+++ b/tests/gateway/test_braintree.py@@ -1,13 +1,11 @@-from decimal import Decimal-from unittest.mock import Mock, patch--import pytest-from braintree import Environment, ErrorResult, SuccessfulResult, Transaction-from braintree.errors import Errors-from braintree.exceptions import NotFoundError-from braintree.validation_error import ValidationError-from django.core.exceptions import ImproperlyConfigured-+import os+from saleor.payment.utils import create_payment_information+from saleor.payment.interface import GatewayConfig+from saleor.payment.gateways.braintree.forms import BraintreePaymentForm+from saleor.payment.gateways.braintree.errors import (+ DEFAULT_ERROR_MESSAGE,+ BraintreeException,+)from saleor.payment.gateways.braintree import (CONFIRM_MANUALLY,THREE_D_SECURE_REQUIRED,@@ -24,13 +22,15 @@ from saleor.payment.gateways.braintree import (refund,void,)-from saleor.payment.gateways.braintree.errors import (- DEFAULT_ERROR_MESSAGE,- BraintreeException,-)-from saleor.payment.gateways.braintree.forms import BraintreePaymentForm-from saleor.payment.interface import GatewayConfig-from saleor.payment.utils import create_payment_information+from django.core.exceptions import ImproperlyConfigured+from braintree.validation_error import ValidationError+from braintree.exceptions import NotFoundError+from braintree.errors import Errors+from braintree import Environment, ErrorResult, SuccessfulResult, Transaction+import pytest+from unittest.mock import MagicMock, Mock, patch+from decimal import Decimal+INCORRECT_TOKEN_ERROR = ("Unable to process the transaction. Transaction's token is incorrect " "or expired."@@ -46,7 +46,7 @@ def braintree_success_response():transaction=Mock(id="1x02131",spec=Transaction,- amount=Decimal("0.20"),+ amount=Decimal("80.00"),created_at="2018-10-20 18:34:22",credit_card="", # FIXME we should provide a proper CreditCard mockadditional_processor_response="",@@ -92,6 +92,7 @@ def gateway_config():return GatewayConfig(template_path="template.html",auto_capture=False,+ store_customer=False,connection_params={"sandbox_mode": False,"merchant_id": "123",@@ -313,6 +314,55 @@ def test_authorize()+def sandbox_braintree_gateway_config(gateway_config):+ """ To record communication with Braintree sandbox set up your environment variables """+ gateway_config.connection_params = {+ "merchant_id": os.getenv("BRAINTREE_MERCHANT_ID", "fake_merchant_id"),+ "public_key": os.getenv("BRAINTREE_PUBLIC_KEY", "fake_public_key"),+ "private_key": os.getenv("BRAINTREE_PRIVATE_KEY", "fake_private_key"),+ "sandbox_mode": True,+ }+ gateway_config.auto_capture = True+ return gateway_config++[email protected](filter_headers=["authorization"])+def test_authorize_one_time(+ payment_dummy, sandbox_braintree_gateway_config, braintree_success_response+):+ payment = payment_dummy++ payment_info = create_payment_information(payment, "fake-valid-nonce")+ sandbox_braintree_gateway_config.auto_capture = False++ response = authorize(payment_info, sandbox_braintree_gateway_config)+ assert not response.error+ assert response.kind == TransactionKind.AUTH+ assert response.amount == braintree_success_response.transaction.amount+ assert response.currency == braintree_success_response.transaction.currency_iso_code+ assert response.is_success == True++[email protected](filter_headers=["authorization"])+def test_authorize_and_save_customer_id(+ payment_dummy, sandbox_braintree_gateway_config+):+ CUSTOMER_ID = "595109854" # retrieved from sandbox+ payment = payment_dummy++ payment_info = create_payment_information(payment, "fake-valid-nonce")+ payment_info.amount = 100.00+ payment_info.reuse_source = True++ sandbox_braintree_gateway_config.store_customer = True+ response = authorize(payment_info, sandbox_braintree_gateway_config)+ assert not response.error+ assert response.customer_id == CUSTOMER_ID++@pytest.mark.integration@patch("saleor.payment.gateways.braintree.get_braintree_gateway")def test_refund(@@ -512,8 +562,3 @@ def test_braintree_payment_form(payment_dummy):assert isinstance(form, BraintreePaymentForm)assert form.is_valid()---def test_store_card_on_success():- pass