Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Test braintree
Pacu209d65950de75
diff --git a/docs/architecture/payments.rst b/docs/architecture/payments.rstindex da268f3c1c..91aa3c587c 100644--- a/docs/architecture/payments.rst+++ b/docs/architecture/payments.rst@@ -1,7 +1,7 @@Payments========-Saleor uses the concept of Payment Methods and Transactions to fulfill the payment process.+Saleor uses the concept of Payments and Transactions to fulfill the payment process.Payment Methods---------------diff --git a/saleor/payment/models.py b/saleor/payment/models.pyindex ec8e55d660..f38117edbf 100644--- a/saleor/payment/models.py+++ b/saleor/payment/models.py@@ -65,6 +65,14 @@ class Payment(models.Model):order = models.ForeignKey(Order, null=True, related_name='payments', on_delete=models.PROTECT)+ def __repr__(self):+ return """+ Payment(variant=%s, is_active=%s, created=%s, charge_status=%s)+ """ % (self.variant, self.is_active, self.created, self.charge_status)++ def __iter__(self):+ return iter(self.transactions.all())+def get_auth_transaction(self):txn = self.transactions.get(transaction_type=TransactionType.AUTH, is_success=True)@@ -116,3 +124,7 @@ class Transaction(models.Model):default=zero_money)gateway_response = JSONField()++ def __repr__(self):+ return 'Transaction(created=%s, type=%s, is_success=%s)' % (+ self.created, self.transaction_type, self.is_success)diff --git a/saleor/payment/providers/braintree/__init__.py b/saleor/payment/providers/braintree/__init__.pyindex ad4e02e881..0a106fc2ff 100644--- a/saleor/payment/providers/braintree/__init__.py+++ b/saleor/payment/providers/braintree/__init__.py@@ -1,12 +1,16 @@+import loggingfrom typing import Dict+import braintree as braintree_sdk+from django.conf import settingsfrom django.core.exceptions import ImproperlyConfiguredfrom django.utils.translation import pgettext_lazy-import braintree as braintree_sdkfrom ... import TransactionTypefrom ...utils import create_transaction+logger = logging.getLogger(__name__)+# FIXME: Move to SiteSettings# If this option is checked, then one needs to authorize the amount paid@@ -14,9 +18,13 @@ from ...utils import create_transactionCONFIRM_MANUALLY = FalseTHREE_D_SECURE_REQUIRED = False+# FIXME: Provide list of visible errors and messages translations+# FIXME: We should also store universal visible errors for all payment+# gateways, and parse gateway-specific errors to this unified version+ERROR_CODES_WHITELIST = []+def get_customer_data(payment):- # FIXME: TESTMEreturn {'billing': {'first_name': payment.billing_first_name,@@ -38,25 +46,34 @@ def get_error_for_client(errors):"""Filters all error messages and decides which one is visible for theclient side."""- # FIXME: TESTMEif not errors:return ''default_msg = pgettext_lazy('payment error','Unable to process transaction. Please try again in a moment')- # FIXME: Provide list of visible errors and messages translations- # FIXME: We should also store universal visible errors for all payment- # gateways, and parse gateway-specific errors to this unified version- error_codes_whitelist = []for error in errors:- if error['code'] in error_codes_whitelist:+ if error['code'] in ERROR_CODES_WHITELIST:return error['message']return default_msg+def transaction_and_incorrect_token_error(payment, token, type, amount=None):+ amount = payment.total.amount if amount is None else amount+ txn = create_transaction(+ payment=payment,+ transaction_type=type,+ amount=amount,+ gateway_response={},+ token=token,+ is_success=False)+ error = (+ 'Unable to process the transaction. Transaction\'s token is incorrect '+ 'or expired.')+ return txn, error++def extract_gateway_response(braintree_result) -> Dict:- # FIXME: TESTME"""Extract data from Braintree response that will be stored locally."""errors = []if not braintree_result.is_success:@@ -67,7 +84,14 @@ def extract_gateway_response(braintree_result) -> Dict:bt_transaction = braintree_result.transactionif not bt_transaction:return {'errors': errors}+ if bt_transaction.currency_iso_code != settings.DEFAULT_CURRENCY:+ logger.error(+ 'Braintree\'s currency is different than shop\'s currency')+gateway_response = {+ 'currency_iso_code': bt_transaction.currency_iso_code,+ 'amount': bt_transaction.amount,+ 'created_at': bt_transaction.created_at,'credit_card': bt_transaction.credit_card,'additional_processor_response': bt_transaction.additional_processor_response, # noqa'gateway_rejection_reason': bt_transaction.gateway_rejection_reason,@@ -82,40 +106,42 @@ def extract_gateway_response(braintree_result) -> Dict:def get_gateway(sandbox_mode, merchant_id, public_key, private_key):- # FIXME: TESTMEif not all([merchant_id, private_key, public_key]):raise ImproperlyConfigured('Incorrectly configured Braintree gateway.')environment = braintree_sdk.Environment.Sandboxif not sandbox_mode:environment = braintree_sdk.Environment.Production- gateway = braintree_sdk.BraintreeGateway(- braintree_sdk.Configuration(- environment=environment,- merchant_id=merchant_id,- public_key=public_key,- private_key=private_key))+ config = braintree_sdk.Configuration(+ environment=environment,+ merchant_id=merchant_id,+ public_key=public_key,+ private_key=private_key)+ gateway = braintree_sdk.BraintreeGateway(config=config)return gatewaydef get_client_token(**client_kwargs):- # FIXME: TESTMEgateway = get_gateway(**client_kwargs)client_token = gateway.client_token.generate()return client_tokendef authorize(payment, transaction_token, **client_kwargs):- # FIXME: TESTMEgateway = get_gateway(**client_kwargs)- result = gateway.transaction.sale({- 'amount': str(payment.total.amount),- 'payment_method_nonce': transaction_token,- 'options': {- 'submit_for_settlement': CONFIRM_MANUALLY,- 'three_d_secure': {- 'required': THREE_D_SECURE_REQUIRED}},- **get_customer_data(payment)})+ try:+ result = gateway.transaction.sale({+ 'amount': str(payment.total.amount),+ 'payment_method_nonce': transaction_token,+ 'options': {+ 'submit_for_settlement': CONFIRM_MANUALLY,+ 'three_d_secure': {+ 'required': THREE_D_SECURE_REQUIRED}},+ **get_customer_data(payment)})+ except braintree_sdk.exceptions.NotFoundError:+ return transaction_and_incorrect_token_error(+ payment, type=TransactionType.AUTH, token=transaction_token)+gateway_response = extract_gateway_response(result)error = get_error_for_client(gateway_response['errors'])txn = create_transaction(@@ -130,15 +156,21 @@ def authorize(payment, transaction_token, **client_kwargs):def capture(payment, amount=None, **client_kwargs):gateway = get_gateway(**client_kwargs)- # FIXME we are assuming that appropriate transaction exists without- # forcing the flow- # FIXME: TESTMEauth_transaction = payment.transactions.filter(transaction_type=TransactionType.AUTH).first()if not amount:amount = payment.total.amount- result = gateway.transaction.submit_for_settlement(- transaction_id=auth_transaction.token, amount=amount)++ try:+ result = gateway.transaction.submit_for_settlement(+ transaction_id=auth_transaction.token, amount=str(amount))+ except braintree_sdk.exceptions.NotFoundError:+ return transaction_and_incorrect_token_error(+ payment,+ type=TransactionType.CAPTURE,+ token=auth_transaction.token,+ amount=amount)+gateway_response = extract_gateway_response(result)error = get_error_for_client(gateway_response['errors'])@@ -146,7 +178,7 @@ def capture(payment, amount=None, **client_kwargs):payment=payment,transaction_type=TransactionType.CAPTURE,amount=amount,- token=result.transaction.id,+ token=getattr(result.transaction, 'id', ''),is_success=result.is_success,gateway_response=gateway_response)return txn, error@@ -154,12 +186,15 @@ def capture(payment, amount=None, **client_kwargs):def void(payment, **client_kwargs):gateway = get_gateway(**client_kwargs)- # FIXME we are assuming that appropriate transaction exists without- # forcing the flow- # FIXME: TESTMEauth_transaction = payment.transactions.filter(transaction_type=TransactionType.AUTH).first()- result = gateway.transaction.void(transaction_id=auth_transaction.token)+ try:+ result = gateway.transaction.void(+ transaction_id=auth_transaction.token)+ except braintree_sdk.exceptions.NotFoundError:+ return transaction_and_incorrect_token_error(+ payment, type=TransactionType.VOID, token=auth_transaction.token)+gateway_response = extract_gateway_response(result)error = get_error_for_client(gateway_response['errors'])txn = create_transaction(@@ -167,27 +202,34 @@ def void(payment, **client_kwargs):transaction_type=TransactionType.VOID,amount=payment.total.amount,gateway_response=gateway_response,- token=result.transaction.id,+ token=getattr(result.transaction, 'id', ''),is_success=result.is_success)return txn, errordef refund(payment, amount=None, **client_kwargs):gateway = get_gateway(**client_kwargs)- # FIXME we are assuming that appropriate transaction exists without- # forcing the flow- # FIXME: TESTMEauth_transaction = payment.transactions.filter(transaction_type=TransactionType.CAPTURE).first()- result = gateway.transaction.refund(- transaction_id=auth_transaction.token, amount=amount)+ if not amount:+ amount = payment.total.amount++ try:+ result = gateway.transaction.refund(+ transaction_id=auth_transaction.token,+ amount_or_options=str(amount))+ except braintree_sdk.exceptions.NotFoundError:+ return transaction_and_incorrect_token_error(+ payment, type=TransactionType.REFUND, token=auth_transaction.token,+ amount=amount)+gateway_response = extract_gateway_response(result)error = get_error_for_client(gateway_response['errors'])txn = create_transaction(payment=payment,transaction_type=TransactionType.REFUND,amount=amount,- token=result.transaction.id,+ token=getattr(result.transaction, 'id', ''),is_success=result.is_success,gateway_response=gateway_response)return txn, errordiff --git a/saleor/payment/utils.py b/saleor/payment/utils.pyindex b441d5d350..6b743e2ee2 100644--- a/saleor/payment/utils.py+++ b/saleor/payment/utils.py@@ -27,7 +27,7 @@ def get_billing_data(order):'billing_address_2': order.billing_address.street_address_2,'billing_city': order.billing_address.city,'billing_postal_code': order.billing_address.postal_code,- 'billing_country_code': order.billing_address.country,+ 'billing_country_code': order.billing_address.country.code,'billing_email': order.user_email,'billing_country_area': order.billing_address.country_area}return data@@ -57,7 +57,7 @@ def validate_payment(view):@wraps(view)def func(payment, *args, **kwargs):if not payment.is_active:- raise PaymentError('This payment is no longer authorized.')+ raise PaymentError('This payment is no longer active.')return view(payment, *args, **kwargs)return func@@ -107,6 +107,7 @@ def gateway_authorize(payment: Payment, transaction_token: str) -> Transaction:if txn.is_success:payment.charge_status = ChargeStatus.NOT_CHARGEDpayment.save(update_fields=['charge_status'])+ # FIXME Create an order event ?if not txn.is_success:# TODO: Handle gateway response here somehowraise PaymentError(error)@@ -136,6 +137,7 @@ def gateway_capture(payment: Payment, amount: Decimal) -> Transaction:order = payment.orderif order and order.is_fully_paid():handle_fully_paid_order(order)+ # FIXME Create an order event ?if not txn.is_success:# TODO: Handle gateway response here somehowraise PaymentError(error)@@ -152,6 +154,7 @@ def gateway_void(payment) -> Transaction:if txn.is_success:payment.is_active = Falsepayment.save(update_fields=['is_active'])+ # FIXME Create an order event ?if not txn.is_success:raise PaymentError(error)return txn@@ -179,6 +182,7 @@ def gateway_refund(payment, amount: Decimal) -> Transaction:payment.captured_amount -= Money(txn.amount, settings.DEFAULT_CURRENCY)payment.save(update_fields=changed_fields)+ # FIXME Create an order event ?if not txn.is_success:raise PaymentError(error)return txndiff --git a/tests/test_payments.py b/tests/test_payment.pysimilarity index 100%rename from tests/test_payments.pyrename to tests/test_payment.pydiff --git a/tests/test_payment_braintree.py b/tests/test_payment_braintree.pynew file mode 100644index 0000000000..b0f121f895--- /dev/null+++ b/tests/test_payment_braintree.py@@ -0,0 +1,451 @@+import datetime+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 saleor.payment.providers.braintree as payment_module+from saleor.payment import TransactionType+from saleor.payment.providers.braintree import (+ CONFIRM_MANUALLY, THREE_D_SECURE_REQUIRED, authorize, capture,+ extract_gateway_response, get_client_token, get_customer_data,+ get_error_for_client, get_gateway, refund,+ transaction_and_incorrect_token_error, void)++INCORRECT_TOKEN_ERROR = (+ 'Unable to process the transaction. Transaction\'s token is incorrect '+ 'or expired.')+DEFAULT_ERROR = 'Unable to process transaction. Please try again in a moment'+++def braintree_success_response():+ return Mock(+ spec=SuccessfulResult,+ is_success=True,+ transaction=Mock(+ id='1x02131',+ spec=Transaction,+ amount='0.20',+ created_at='2018-10-20 18:34:22',+ credit_card={+ 'token': None,+ 'bin': '400000',+ 'last_4': '0002',+ 'card_type': 'Visa',+ 'expiration_month': '01',+ 'expiration_year': '2020',+ 'customer_location': 'International'},+ additional_processor_response='',+ gateway_rejection_reason='',+ processor_response_code='1000',+ processor_response_text='Approved',+ processor_settlement_response_code='',+ processor_settlement_response_text='',+ risk_data='',+ currency_iso_code='EUR',+ status='authorized'))++def braintree_error():+ return Mock(+ spec=ValidationError,+ code='91507',+ attribute='base',+ message='Cannot submit for settlement unless status is authorized.')+++def braintree_error_response(braintree_error):+ return Mock(+ spec=ErrorResult,+ is_success=False,+ transaction=None,+ errors=Mock(+ spec=Errors,+ deep_errors=[braintree_error]))+++def braintree_not_found_error():+ return Mock(side_effect=NotFoundError)+++def gateway_config():+ return {+ 'sandbox_mode': False,+ 'merchant_id': '123',+ 'public_key': '456',+ 'private_key': '789'}+++def test_get_customer_data(payment_dummy):+ payment = payment_dummy+ result = get_customer_data(payment)+ expected_result = {+ 'billing': {+ 'first_name': payment.billing_first_name,+ 'last_name': payment.billing_last_name,+ 'company': payment.billing_company_name,+ 'postal_code': payment.billing_postal_code,+ 'street_address': payment.billing_address_1[:255],+ 'extended_address': payment.billing_address_2[:255],+ "locality": payment.billing_city,+ 'region': payment.billing_country_area,+ 'country_code_alpha2': payment.billing_country_code},+ 'risk_data': {+ 'customer_ip': payment.customer_ip_address or ''},+ 'customer': {+ 'email': payment.billing_email}}+ assert result == expected_result+++def test_get_error_for_client(braintree_error):+ # no error+ assert get_error_for_client([]) == ''++ # error not whitelisted+ payment_module.ERROR_CODES_WHITELIST = []+ error = {'code': braintree_error.code, 'message': braintree_error.message}+ assert get_error_for_client([error]) == DEFAULT_ERROR++ payment_module.ERROR_CODES_WHITELIST = [braintree_error.code]+ assert get_error_for_client([error]) == braintree_error.message+++def test_extract_gateway_response(braintree_success_response):+ result = extract_gateway_response(braintree_success_response)+ t = braintree_success_response.transaction+ expected_result = {+ 'currency_iso_code': t.currency_iso_code,+ 'amount': t.amount,+ 'created_at': t.created_at,+ 'credit_card': t.credit_card,+ 'additional_processor_response': t.additional_processor_response,+ 'gateway_rejection_reason': t.gateway_rejection_reason,+ 'processor_response_code': t.processor_response_code,+ 'processor_response_text': t.processor_response_text,+ 'processor_settlement_response_code': t.processor_settlement_response_code, # noqa+ 'processor_settlement_response_text': t.processor_settlement_response_text, # noqa+ 'risk_data': t.risk_data,+ 'status': t.status,+ 'errors': []}+ assert result == expected_result+++def test_extract_gateway_response_no_transaction(+ braintree_error_response, braintree_error):+ result = extract_gateway_response(braintree_error_response)+ assert result == {+ 'errors': [+ {+ 'code': braintree_error.code,+ 'message': braintree_error.message}]}+++def test_get_gateway(gateway_config):+ result = get_gateway(**gateway_config)+ assert gateway_config['sandbox_mode'] == False+ assert result.config.environment == Environment.Production+ assert result.config.merchant_id == gateway_config['merchant_id']+ assert result.config.public_key == gateway_config['public_key']+ assert result.config.private_key == gateway_config['private_key']+++def test_get_gateway_sandbox(gateway_config):+ gateway_config['sandbox_mode'] = True+ result = get_gateway(**gateway_config)+ assert result.config.environment == Environment.Sandbox+++def test_get_gateway_inproperly_configured(gateway_config):+ with pytest.raises(ImproperlyConfigured):+ gateway_config['private_key'] = None+ get_gateway(**gateway_config)+++@patch('saleor.payment.providers.braintree.get_gateway')+def test_get_client_token(mock_gateway, gateway_config):+ client_token = 'client-token'+ mock_generate = Mock(return_value='client-token')+ mock_gateway.return_value = Mock(client_token=Mock(generate=mock_generate))+ result = get_client_token(**gateway_config)+ mock_gateway.assert_called_once_with(**gateway_config)+ mock_generate.assert_called_once()+ assert result == client_token+++@patch('saleor.payment.providers.braintree.get_gateway')+def test_authorize_error_response(+ mock_gateway, payment_dummy, braintree_error_response):+ payment = payment_dummy+ token = 'example-token'+ mock_response = Mock(return_value=braintree_error_response)+ mock_gateway.return_value = Mock(transaction=Mock(sale=mock_response))+ txn, error = authorize(payment, token)++ assert txn.gateway_response == extract_gateway_response(+ braintree_error_response)+ assert not txn.is_success+ assert error == DEFAULT_ERROR++++@patch('saleor.payment.providers.braintree.transaction_and_incorrect_token_error')+@patch('saleor.payment.providers.braintree.get_gateway')+def test_authorize_incorrect_token(+ mock_gateway, mock_transaction, payment_dummy,+ braintree_not_found_error):+ payment = payment_dummy+ token = 'example-token'+ mock_response = Mock(side_effect=braintree_not_found_error)+ mock_gateway.return_value = Mock(transaction=Mock(sale=mock_response))+ expected_result = ('txn', 'error')+ mock_transaction.return_value = expected_result+ result = authorize(payment, token)+ assert result == expected_result+ mock_transaction.assert_called_once_with(+ payment, type=TransactionType.AUTH, token=token)+++@patch('saleor.payment.providers.braintree.get_gateway')+def test_authorize(+ mock_gateway, payment_dummy, braintree_success_response):+ payment = payment_dummy+ mock_response = Mock(return_value=braintree_success_response)+ mock_gateway.return_value = Mock(transaction=Mock(sale=mock_response))+ txn, error = authorize(payment, 'transaction-token')+ assert not error++ assert txn.payment == payment+ assert txn.transaction_type == TransactionType.AUTH+ assert txn.amount == payment.total.amount+ assert txn.gateway_response == extract_gateway_response(+ braintree_success_response)+ assert txn.token == braintree_success_response.transaction.id+ assert txn.is_success == braintree_success_response.is_success++ mock_response.assert_called_once_with({+ 'amount': str(payment.total.amount),+ 'payment_method_nonce': 'transaction-token',+ 'options': {+ 'submit_for_settlement': CONFIRM_MANUALLY,+ 'three_d_secure': {+ 'required': THREE_D_SECURE_REQUIRED}},+ **get_customer_data(payment)})+++@patch('saleor.payment.providers.braintree.get_gateway')+def test_refund(+ mock_gateway, payment_txn_captured, braintree_success_response):+ payment = payment_txn_captured+ amount = Decimal('10.00')+ mock_response = Mock(return_value=braintree_success_response)+ mock_gateway.return_value = Mock(transaction=Mock(refund=mock_response))+ txn, error = refund(payment, amount)+ assert not error++ assert txn.payment == payment+ assert txn.transaction_type == TransactionType.REFUND+ assert txn.amount == amount+ assert txn.gateway_response == extract_gateway_response(+ braintree_success_response)+ assert txn.token == braintree_success_response.transaction.id+ assert txn.is_success == braintree_success_response.is_success++ capture_txn = payment.transactions.filter(+ transaction_type=TransactionType.CAPTURE).first()+ mock_response.assert_called_once_with(+ amount_or_options=str(amount), transaction_id=capture_txn.token)+++@patch('saleor.payment.providers.braintree.transaction_and_incorrect_token_error')+@patch('saleor.payment.providers.braintree.get_gateway')+def test_refund_incorrect_token(+ mock_gateway, mock_transaction, payment_txn_captured,+ braintree_not_found_error):+ payment = payment_txn_captured+ amount = Decimal('10.00')+ mock_response = Mock(side_effect=braintree_not_found_error)+ mock_gateway.return_value = Mock(transaction=Mock(refund=mock_response))+ expected_result = ('txn', 'error')+ mock_transaction.return_value = expected_result+ result = refund(payment, amount)+ assert result == expected_result+ capture_txn = payment.transactions.filter(+ transaction_type=TransactionType.CAPTURE).first()+ mock_transaction.assert_called_once_with(+ payment, type=TransactionType.REFUND, token=capture_txn.token,+ amount=amount)+++@patch('saleor.payment.providers.braintree.get_gateway')+def test_refund_error_response(+ mock_gateway, payment_txn_captured, braintree_error_response):+ payment = payment_txn_captured+ amount = Decimal('10.00')+ mock_response = Mock(return_value=braintree_error_response)+ mock_gateway.return_value = Mock(transaction=Mock(refund=mock_response))+ txn, error = refund(payment, amount)++ assert txn.gateway_response == extract_gateway_response(+ braintree_error_response)+ assert not txn.is_success+ assert error == DEFAULT_ERROR+++@patch('saleor.payment.providers.braintree.get_gateway')+def test_capture(+ mock_gateway, payment_txn_preauth, braintree_success_response):+ payment = payment_txn_preauth+ amount = Decimal('10.00')+ mock_response = Mock(return_value=braintree_success_response)+ mock_gateway.return_value = Mock(+ transaction=Mock(+ submit_for_settlement=mock_response))+ txn, error = capture(payment, amount)+ assert not error++ assert txn.payment == payment+ assert txn.transaction_type == TransactionType.CAPTURE+ assert txn.amount == amount+ assert txn.gateway_response == extract_gateway_response(+ braintree_success_response)+ assert txn.token == braintree_success_response.transaction.id+ assert txn.is_success == braintree_success_response.is_success++ auth_txn = payment.transactions.filter(+ transaction_type=TransactionType.AUTH).first()+ mock_response.assert_called_once_with(+ amount=str(amount), transaction_id=auth_txn.token)+++@patch('saleor.payment.providers.braintree.transaction_and_incorrect_token_error')+@patch('saleor.payment.providers.braintree.get_gateway')+def test_capture_incorrect_token(+ mock_gateway, mock_transaction, payment_txn_preauth,+ braintree_not_found_error):+ payment = payment_txn_preauth+ amount = Decimal('10.00')+ mock_response = Mock(side_effect=braintree_not_found_error)+ mock_gateway.return_value = Mock(+ transaction=Mock(+ submit_for_settlement=mock_response))+ expected_result = ('txn', 'error')+ mock_transaction.return_value = expected_result+ result = capture(payment, amount)+ assert result == expected_result+ auth_txn = payment.transactions.filter(+ transaction_type=TransactionType.AUTH).first()+ mock_transaction.assert_called_once_with(+ payment, type=TransactionType.CAPTURE, token=auth_txn.token,+ amount=amount)+++@patch('saleor.payment.providers.braintree.get_gateway')+def test_capture_error_response(+ mock_gateway, payment_txn_preauth, braintree_error_response):+ payment = payment_txn_preauth+ amount = Decimal('10.00')+ mock_response = Mock(return_value=braintree_error_response)+ mock_gateway.return_value = Mock(+ transaction=Mock(submit_for_settlement=mock_response))+ txn, error = capture(payment, amount)++ assert txn.gateway_response == extract_gateway_response(+ braintree_error_response)+ assert not txn.is_success+ assert error == DEFAULT_ERROR++++@patch('saleor.payment.providers.braintree.get_gateway')+def test_void(+ mock_gateway, payment_txn_preauth, braintree_success_response):+ payment = payment_txn_preauth+ mock_response = Mock(return_value=braintree_success_response)+ mock_gateway.return_value = Mock(transaction=Mock(void=mock_response))+ txn, error = void(payment)+ assert not error++ assert txn.payment == payment+ assert txn.transaction_type == TransactionType.VOID+ assert txn.amount == payment.total.amount+ assert txn.gateway_response == extract_gateway_response(+ braintree_success_response)+ assert txn.token == braintree_success_response.transaction.id+ assert txn.is_success == braintree_success_response.is_success++ auth_txn = payment.transactions.filter(+ transaction_type=TransactionType.AUTH).first()+ mock_response.assert_called_once_with(transaction_id=auth_txn.token)+++@patch('saleor.payment.providers.braintree.transaction_and_incorrect_token_error')+@patch('saleor.payment.providers.braintree.get_gateway')+def test_void_incorrect_token(+ mock_gateway, mock_transaction, payment_txn_preauth,+ braintree_not_found_error):+ payment = payment_txn_preauth+ mock_response = Mock(side_effect=braintree_not_found_error)+ mock_gateway.return_value = Mock(transaction=Mock(void=mock_response))+ expected_result = ('txn', 'error')+ mock_transaction.return_value = expected_result+ result = void(payment)+ assert result == expected_result+ auth_txn = payment.transactions.filter(+ transaction_type=TransactionType.AUTH).first()+ mock_transaction.assert_called_once_with(+ payment, type=TransactionType.VOID, token=auth_txn.token)+++@patch('saleor.payment.providers.braintree.get_gateway')+def test_void_error_response(+ mock_gateway, payment_txn_preauth, braintree_error_response):+ payment = payment_txn_preauth+ mock_response = Mock(return_value=braintree_error_response)+ mock_gateway.return_value = Mock(transaction=Mock(void=mock_response))+ txn, error = void(payment)++ assert txn.gateway_response == extract_gateway_response(+ braintree_error_response)+ assert not txn.is_success+ assert error == DEFAULT_ERROR+++def test_transaction_and_incorrect_token_error_helper(payment_dummy):+ amount = Decimal('10.00')+ txn, error = transaction_and_incorrect_token_error(+ payment_dummy, 'example-token', TransactionType.AUTH, amount=amount)+ assert error == INCORRECT_TOKEN_ERROR+ assert not txn.is_success+ assert txn.transaction_type == TransactionType.AUTH+ assert txn.token == 'example-token'+ assert not txn.gateway_response+ assert txn.amount == amount+++def test_transaction_and_incorrect_token_error_helper_no_amount(payment_dummy):+ txn, error = transaction_and_incorrect_token_error(+ payment_dummy, 'example-token', TransactionType.AUTH)+ assert txn.amount == payment_dummy.total.amount