Skip to content

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

WIP

Pacu2c1c55e6eb9fd
diff --git a/saleor/graphql/api.py b/saleor/graphql/api.py
index ab1d961eff..79e285ff69 100644
--- a/saleor/graphql/api.py
+++ b/saleor/graphql/api.py
@@ -3,6 +3,8 @@ from textwrap import dedent
import graphene
import graphql_jwt
from graphql_jwt.decorators import login_required, permission_required
+import graphene_django_optimizer as gql_optimizer
+from graphene_django.fields import DjangoConnectionField
from .account.mutations import (
CustomerCreate, CustomerDelete, CustomerUpdate, CustomerPasswordReset,
@@ -76,8 +78,8 @@ class Query(ProductQueries):
checkout = graphene.Field(
Checkout, description='Single checkout.',
token=graphene.Argument(graphene.UUID))
- checkouts = PrefetchingConnectionField(
- Checkout, description='List of checkouts.')
+ checkouts = DjangoConnectionField(
+ Checkout,description='List of checkouts.')
checkout_lines = PrefetchingConnectionField(
CheckoutLine, description='List of checkout lines')
checkout_line = graphene.Field(
diff --git a/saleor/graphql/checkout/mutations.py b/saleor/graphql/checkout/mutations.py
index 01373314c8..e2df33facd 100644
--- a/saleor/graphql/checkout/mutations.py
+++ b/saleor/graphql/checkout/mutations.py
@@ -24,7 +24,8 @@ from .types import Checkout, CheckoutLine
def clean_shipping_method(
- checkout, method, errors, discounts, taxes, country_code=None):
+ checkout, method, errors, discounts, taxes, country_code=None,
+ remove=True):
# FIXME Add tests for this function
if not method:
return errors
@@ -48,11 +49,14 @@ def clean_shipping_method(
country_code=country_code or checkout.shipping_address.country.code
))
valid_methods = valid_methods.values_list('id', flat=True)
- if method.pk not in valid_methods:
+ if method.pk not in valid_methods and not remove:
errors.append(
Error(
field='shippingMethod',
message='Shipping method cannot be used with this checkout.'))
+ if remove:
+ checkout.shipping_method = None
+ checkout.save(update_fields=['shipping_method'])
return errors
@@ -401,7 +405,7 @@ class CheckoutShippingMethodUpdate(BaseMutation):
clean_shipping_method(
checkout, shipping_method, errors, info.context.discounts,
- info.context.taxes)
+ info.context.taxes, remove=False)
if errors:
return CheckoutShippingMethodUpdate(errors=errors)
diff --git a/saleor/graphql/payment/mutations.py b/saleor/graphql/payment/mutations.py
index bddbdd710f..00ad0853d8 100644
--- a/saleor/graphql/payment/mutations.py
+++ b/saleor/graphql/payment/mutations.py
@@ -1,8 +1,11 @@
+import decimal
+
import graphene
from django.conf import settings
from graphql_jwt.decorators import permission_required
from prices import Money, TaxedMoney
+from ...core.utils.taxes import get_taxes_for_address
from ...payment import PaymentError
from ...payment.utils import (
create_payment, gateway_authorize, gateway_capture, gateway_refund,
@@ -18,8 +21,11 @@ from .types import Payment, PaymentGatewayEnum
class PaymentInput(graphene.InputObjectType):
gateway = PaymentGatewayEnum()
checkout_id = graphene.ID(description='Checkout ID.')
- transaction_token = graphene.String(
- required=True, description='One time transaction token.')
+ token = graphene.String(
+ required=True,
+ description=(
+ 'Client-side generated token, representing customer\'s billing'
+ 'data in secure manner.'))
amount = Decimal(
required=True,
description=(
@@ -57,17 +63,28 @@ class CheckoutPaymentCreate(BaseMutation, I18nMixin):
return CheckoutPaymentCreate(errors=errors)
billing_data = cls.clean_billing_address(billing_address)
extra_data = cls.get_extra_info(info)
- # FIXME as we allow only one payment make sure that amount
- # is same as checkout's total
+
+ amount = input['amount']
+ checkout_total = checkout.get_total(
+ discounts=info.context.discounts,
+ taxes=get_taxes_for_address(checkout.shipping_address))
+
+ if decimal.Decimal(str(amount)) != checkout_total.gross.amount:
+ cls.add_error(
+ errors, 'amount',
+ 'Partial payments are not allowed, '
+ 'amount should be equal checkout\'s total.')
+ return CheckoutPaymentCreate(errors=errors)
+
payment = create_payment(
- total=input['amount'],
+ total=amount,
currency=settings.DEFAULT_CURRENCY,
gateway=input['gateway'],
billing_email=checkout.email,
is_active=True,
extra_data=extra_data,
checkout=checkout,
- token=input['transaction_token'],
+ token=input['token'],
**billing_data)
return CheckoutPaymentCreate(payment=payment, errors=errors)
diff --git a/saleor/order/views.py b/saleor/order/views.py
index 1250b17fe8..0b0ce8d5ce 100644
--- a/saleor/order/views.py
+++ b/saleor/order/views.py
@@ -15,8 +15,8 @@ from . import FulfillmentStatus
from ..account.forms import LoginForm
from ..account.models import User
from ..core.utils import get_client_ip
-from ..payment import ChargeStatus, PaymentError, TransactionKind, get_payment_gateway
-from ..payment.forms import get_form_for_payment
+from ..payment import (
+ ChargeStatus, PaymentError, TransactionKind, get_payment_gateway)
from ..payment.models import Payment
from ..payment.utils import get_billing_data
from .forms import (
@@ -89,6 +89,7 @@ def payment(request, token):
@check_order_status
def start_payment(request, order, gateway):
+ # FIXME We should test this flow for each payment gateway
defaults = {
'customer_ip_address': get_client_ip(request),
**get_billing_data(order)}
@@ -104,7 +105,7 @@ def start_payment(request, order, gateway):
return redirect(order.get_absolute_url())
payment_gateway, gateway_params = get_payment_gateway(payment.gateway)
client_token = payment_gateway.get_client_token(**gateway_params)
- form = get_form_for_payment(payment)
+ form = payment_gateway.get_form_class()
form = form(
data=request.POST or None, payment=payment,
gateway=payment_gateway, gateway_params=gateway_params)
diff --git a/saleor/payment/forms.py b/saleor/payment/forms.py
index 388bf715ce..8964cce288 100644
--- a/saleor/payment/forms.py
+++ b/saleor/payment/forms.py
@@ -1,23 +1,11 @@
from django import forms
from django.conf import settings
-from django.core.exceptions import ValidationError
-from django.utils.translation import pgettext_lazy
-
-from . import ChargeStatus, PaymentError, TransactionKind, get_payment_gateway
-from .models import Payment
-from .utils import gateway_authorize, gateway_capture, gateway_refund
-
-
-def get_form_for_payment(payment):
- if payment.gateway == settings.DUMMY:
- return DummyPaymentForm
- elif payment.gateway == settings.BRAINTREE:
- return BraintreePaymentForm
- raise NotImplementedError('Unknown payment gateway')
class PaymentForm(forms.Form):
- """FIXME: DOCS & DOCSTRINGS."""
+ """Abstract Payment form that should be used as a base for every
+ payment gateway implemented.
+ """
def __init__(self, payment, gateway, gateway_params, *args, **kwargs):
self.payment = payment
@@ -27,70 +15,3 @@ class PaymentForm(forms.Form):
def process_payment(self):
raise NotImplementedError()
-
-
-class DummyPaymentForm(PaymentForm):
- charge_status = forms.ChoiceField(
- label=pgettext_lazy('Payment status form field', 'Payment status'),
- choices=ChargeStatus.CHOICES, initial=ChargeStatus.NOT_CHARGED,
- widget=forms.RadioSelect)
-
-
- def process_payment(self):
- # FIXME add tests
- # Dummy provider requires no real token
- fake_token = self.gateway.get_client_token(**self.gateway_params)
- self.payment.authorize(fake_token)
- charge_status = self.cleaned_data['charge_status']
- if charge_status == ChargeStatus.NOT_CHARGED:
- return
- self.payment.capture()
- if charge_status == ChargeStatus.FULLY_REFUNDED:
- self.payment.refund()
- return self.payment
-
-
-class BraintreePaymentForm(PaymentForm):
- amount = forms.DecimalField()
-
- # Unique transaction identifier returned by Braintree
- # for testing in the sandbox mode please refer to
- # https://developers.braintreepayments.com/reference/general/testing/python#nonces-representing-cards
- # as it's values should be hardcoded to simulate each payment gateway
- # response
- payment_method_nonce = forms.CharField()
-
- def __init__(self, *args, **kwargs):
- super().__init__(*args, **kwargs)
- self.fields['amount'].initial = self.payment.total
- # FIXME if environment is Sandbox, we could provide couple of predefined
- # nounces for easier testing
-
- def clean(self):
- cleaned_data = super().clean()
- # Amount is sent client-side
- # authorizing different amount than payments' total could happen only
- # when manually adjusting the template value as we do not allow
- # partial-payments at this moment, error is returned instead.
- amount = cleaned_data.get('amount')
- if amount and amount != self.payment.total:
- msg = pgettext_lazy(
- 'payment error',
- 'Unable to process transaction. Please try again in a moment')
- raise ValidationError(msg)
- cleaned_data['payment_method_nonce'] = 'fake-valid-nonce' # FIXME remove after testing
- return cleaned_data
-
- def process_payment(self):
- # FIXME add tests
- payment_token = self.cleaned_data['payment_method_nonce']
- self.payment.token = payment_token
- self.payment.save(update_fields=['token'])
- self.payment.authorize(payment_token)
- try:
- self.payment.capture(self.payment.total)
- except PaymentError as exc:
- # Void authorization if the capture failed
- self.payment.void()
- raise exc
- return self.payment
diff --git a/saleor/payment/gateways/braintree/__init__.py b/saleor/payment/gateways/braintree/__init__.py
index a66fd449fc..25f73e506d 100644
--- a/saleor/payment/gateways/braintree/__init__.py
+++ b/saleor/payment/gateways/braintree/__init__.py
@@ -11,6 +11,7 @@ from prices import Money
from ... import TransactionKind
from ...models import Payment, Transaction
from ...utils import create_transaction
+from .forms import BraintreePaymentForm
logger = logging.getLogger(__name__)
# FIXME: Move to SiteSettings
@@ -112,6 +113,10 @@ def extract_gateway_response(braintree_result) -> Dict:
return gateway_response
+def get_form_class():
+ return BraintreePaymentForm
+
+
def get_braintree_gateway(sandbox_mode, merchant_id, public_key, private_key):
if not all([merchant_id, private_key, public_key]):
raise ImproperlyConfigured('Incorrectly configured Braintree gateway.')
@@ -153,7 +158,7 @@ def authorize(
payment, kind=TransactionKind.AUTH, token=payment_token)
gateway_response = extract_gateway_response(result)
error = get_error_for_client(gateway_response['errors'])
- credit_card_data = gateway_response.pop('credit_cart')
+ credit_card_data = gateway_response.pop('credit_cart', None)
if credit_card_data:
payment.cc_first_digits = credit_card_data.bin
payment.cc_last_digits = credit_card_data.last_4
@@ -197,7 +202,6 @@ def capture(
txn = create_transaction(
payment=payment,
- parent=auth_transaction,
kind=TransactionKind.CAPTURE,
amount=gateway_response.pop('amount', amount),
currency=gateway_response.pop('currency', payment.currency),
@@ -224,7 +228,6 @@ def void(
error = get_error_for_client(gateway_response['errors'])
txn = create_transaction(
payment=payment,
- parent=auth_transaction,
kind=TransactionKind.VOID,
amount=gateway_response.pop('amount', payment.total),
currency=gateway_response.pop('currency', payment.currency),
@@ -254,7 +257,6 @@ def refund(
error = get_error_for_client(gateway_response['errors'])
txn = create_transaction(
payment=payment,
- parent=capture_txn,
kind=TransactionKind.REFUND,
amount=gateway_response.pop('amount', amount),
currency=gateway_response.pop('currency', payment.currency),
diff --git a/saleor/payment/gateways/dummy/__init__.py b/saleor/payment/gateways/dummy/__init__.py
index fffc71eeee..3db25eed91 100644
--- a/saleor/payment/gateways/dummy/__init__.py
+++ b/saleor/payment/gateways/dummy/__init__.py
@@ -8,6 +8,7 @@ from prices import Money
from ... import TransactionKind
from ...models import Payment
from ...utils import create_transaction
+from .forms import DummyPaymentForm
def dummy_success():
@@ -18,6 +19,10 @@ def get_client_token(**connection_params):
return str(uuid.uuid4())
+def get_form_class():
+ return DummyPaymentForm
+
+
def authorize(payment: Payment, payment_token: str, **connection_params):
success = dummy_success()
error = None
@@ -38,7 +43,7 @@ def void(payment: Payment, **connection_params: Dict):
error = None
success = dummy_success()
if not success:
- error = 'Unable to void transaction'
+ error = 'Unable to void the transaction.'
txn = create_transaction(
payment=payment,
kind=TransactionKind.VOID,
diff --git a/saleor/payment/migrations/0001_initial.py b/saleor/payment/migrations/0001_initial.py
index 3ca37f7f51..f01fef5fda 100644
--- a/saleor/payment/migrations/0001_initial.py
+++ b/saleor/payment/migrations/0001_initial.py
@@ -46,7 +46,7 @@ class Migration(migrations.Migration):
('cc_first_digits', models.CharField(blank=True, default='', max_length=6)),
('cc_last_digits', models.CharField(blank=True, default='', max_length=4)),
('extra_data', models.TextField(blank=True, default='')),
- ('token', models.CharField(blank=True, default='', max_length=36)),
+ ('token', models.CharField(blank=True, default='', max_length=128)),
('currency', models.CharField(max_length=10)),
('total', models.DecimalField(decimal_places=2, default=Decimal('0.0'), max_digits=12)),
('captured_amount', models.DecimalField(decimal_places=2, default=Decimal('0.0'), max_digits=12)),
@@ -59,8 +59,8 @@ class Migration(migrations.Migration):
fields=[
('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')),
('created', models.DateTimeField(auto_now_add=True)),
- ('token', models.CharField(blank=True, default='', max_length=64)),
- ('kind', models.CharField(choices=[('auth', 'Authorization'), ('capture', 'Charge'), ('refund', 'Refund'), ('capture', 'Capture'), ('void', 'Void')], max_length=10)),
+ ('token', models.CharField(blank=True, default='', max_length=128)),
+ ('kind', models.CharField(choices=[('auth', 'Authorization'), ('charge', 'Charge'), ('refund', 'Refund'), ('capture', 'Capture'), ('void', 'Void')], max_length=10)),
('is_success', models.BooleanField(default=False)),
('currency', models.CharField(max_length=10)),
('amount', models.DecimalField(decimal_places=2, default=Decimal('0.0'), max_digits=12)),
diff --git a/saleor/payment/models.py b/saleor/payment/models.py
index 69b2459e9e..db7d5c3b7b 100644
--- a/saleor/payment/models.py
+++ b/saleor/payment/models.py
@@ -87,6 +87,9 @@ class Payment(models.Model):
return 'Payment(gateway=%s, is_active=%s, created=%s, charge_status=%s)' % (
self.gateway, self.is_active, self.created, self.charge_status)
+ def get_last_transaction(self):
+ return max(self.transactions.all(), default=None, key=attrgetter('pk'))
+
def get_total(self):
return Money(self.total, self.currency or settings.DEFAULT_CURRENCY)
@@ -163,10 +166,6 @@ class Transaction(models.Model):
error = models.CharField(
choices=[(tag, tag.value) for tag in TransactionError],
max_length=256, null=True)
- # Parent transaction, from which the transaction_id was used
- parent = models.ForeignKey(
- 'payment.Transaction', related_name='children',
- on_delete=models.PROTECT, blank=True, null=True)
gateway_response = JSONField()
def __repr__(self):
diff --git a/saleor/payment/utils.py b/saleor/payment/utils.py
index c28c885ff2..efadb4ae85 100644
--- a/saleor/payment/utils.py
+++ b/saleor/payment/utils.py
@@ -93,7 +93,9 @@ def gateway_get_client_token(gateway_name: str):
gateway, gateway_params = get_payment_gateway(gateway_name)
return gateway.get_client_token(**gateway_params)
+
def clean_capture(payment: Payment, amount: Decimal):
+ # FIXME add tests
if amount <= 0:
raise PaymentError('Amount should be a positive number.')
if not payment.can_capture():
@@ -102,7 +104,9 @@ def clean_capture(payment: Payment, amount: Decimal):
payment.total - payment.captured_amount):
raise PaymentError('Unable to capture more than authorized amount.')
+
def clean_authorize(payment: Payment):
+ # FIXME add tests
if not payment.can_authorize():
raise PaymentError('Charged transactions cannot be authorized again.')
@@ -119,6 +123,13 @@ def gateway_charge(
with transaction.atomic():
txn, error = gateway.charge(
payment, payment_token, **gateway_params)
+ if txn.is_success:
+ payment.charge_status = ChargeStatus.CHARGED
+ payment.captured_amount += txn.amount
+ payment.save(update_fields=['charge_status', 'captured_amount'])
+ order = payment.order
+ if order and order.is_fully_paid():
+ handle_fully_paid_order(order)
if not txn.is_success:
raise PaymentError(error)
return txn
@@ -137,7 +148,6 @@ def gateway_authorize(payment: Payment, payment_token: str) -> Transaction:
with transaction.atomic():
txn, error = gateway.authorize(
payment, payment_token, **gateway_params)
- # FIXME Create an order event ?
if not txn.is_success:
raise PaymentError(error)
return txn
@@ -158,7 +168,6 @@ def gateway_capture(payment: Payment, amount: Decimal) -> Transaction:
order = payment.order
if order and order.is_fully_paid():
handle_fully_paid_order(order)
- # FIXME Create an order event ?
if not txn.is_success:
raise PaymentError(error)
return txn
@@ -174,7 +183,6 @@ def gateway_void(payment) -> Transaction:
if txn.is_success:
payment.is_active = False
payment.save(update_fields=['is_active'])
- # FIXME Create an order event ?
if not txn.is_success:
raise PaymentError(error)
return txn
@@ -200,7 +208,6 @@ def gateway_refund(payment, amount: Decimal) -> Transaction:
payment.is_active = False
changed_fields += ['charge_status', 'is_active']
payment.save(update_fields=changed_fields)
- # FIXME Create an order event ?
if not txn.is_success:
raise PaymentError(error)
return txn
diff --git a/tests/api/test_checkout.py b/tests/api/test_checkout.py
index 58dc3738c6..9e59139de7 100644
--- a/tests/api/test_checkout.py
+++ b/tests/api/test_checkout.py
@@ -522,4 +522,4 @@ def test_checkout_shipping_method_update(
checkout.refresh_from_db()
assert checkout.shipping_method == shipping_method
mock_clean_shipping.assert_called_once_with(
- checkout, shipping_method, [], ANY, ANY)
+ checkout, shipping_method, [], ANY, ANY, remove=False)
diff --git a/tests/api/test_payment.py b/tests/api/test_payment.py
index c97d61f1a2..f6306f12ce 100644
--- a/tests/api/test_payment.py
+++ b/tests/api/test_payment.py
@@ -41,10 +41,10 @@ def test_payment_void_success(
assert txn.kind == TransactionKind.VOID
-def test_payment_charge_gateway_error(
+def test_payment_void_gateway_error(
staff_api_client, permission_manage_orders, payment_dummy,
monkeypatch):
- assert payment.charge_status == ChargeStatus.NOT_CHARGED
+ assert payment_dummy.charge_status == ChargeStatus.NOT_CHARGED
payment_id = graphene.Node.to_global_id(
'Payment', payment_dummy.pk)
variables = {'paymentId': payment_id}
@@ -53,11 +53,10 @@ def test_payment_charge_gateway_error(
response = staff_api_client.post_graphql(
VOID_QUERY, variables, permissions=[permission_manage_orders])
content = get_graphql_content(response)
- data = content['data']['paymentCapture']
+ data = content['data']['paymentVoid']
assert data['errors']
assert data['errors'][0]['field'] is None
- assert data['errors'][0]['message'] == (
- 'Only pre-authorized transactions can be void.')
+ assert data['errors'][0]['message'] == 'Unable to void the transaction.'
payment_dummy.refresh_from_db()
assert payment_dummy.charge_status == ChargeStatus.NOT_CHARGED
assert payment_dummy.is_active == True
@@ -97,7 +96,7 @@ def test_checkout_add_payment(
'input': {
'checkoutId': checkout_id,
'gateway': 'DUMMY',
- 'transactionToken': 'sample-token',
+ 'token': 'sample-token',
'amount': str(cart.get_total().gross.amount),
'billingAddress': graphql_address_data}}
response = user_api_client.post_graphql(CREATE_QUERY, variables)
@@ -116,7 +115,7 @@ def test_checkout_add_payment(
assert payment.charge_status == ChargeStatus.NOT_CHARGED
-CHARGE_QUERY = """
+CAPTURE_QUERY = """
mutation PaymentCharge($paymentId: ID!, $amount: Decimal!) {
paymentCapture(paymentId: $paymentId, amount: $amount) {
payment {
@@ -143,7 +142,7 @@ def test_payment_charge_success(
'paymentId': payment_id,
'amount': str(payment_dummy.total)}
response = staff_api_client.post_graphql(
- CHARGE_QUERY, variables, permissions=[permission_manage_orders])
+ CAPTURE_QUERY, variables, permissions=[permission_manage_orders])
content = get_graphql_content(response)
data = content['data']['paymentCapture']
assert not data['errors']
@@ -151,7 +150,7 @@ def test_payment_charge_success(
assert payment.charge_status == ChargeStatus.CHARGED
assert payment.transactions.count() == 1
txn = payment.transactions.first()
- assert txn.kind == TransactionKind.CHARGE
+ assert txn.kind == TransactionKind.CAPTURE
def test_payment_charge_gateway_error(
@@ -167,7 +166,7 @@ def test_payment_charge_gateway_error(
monkeypatch.setattr(
'saleor.payment.gateways.dummy.dummy_success', lambda: False)
response = staff_api_client.post_graphql(
- CHARGE_QUERY, variables, permissions=[permission_manage_orders])
+ CAPTURE_QUERY, variables, permissions=[permission_manage_orders])
content = get_graphql_content(response)
data = content['data']['paymentCapture']
assert data['errors']
@@ -178,7 +177,7 @@ def test_payment_charge_gateway_error(
assert payment.charge_status == ChargeStatus.NOT_CHARGED
assert payment.transactions.count() == 1
txn = payment.transactions.first()
- assert txn.kind == TransactionKind.CHARGE
+ assert txn.kind == TransactionKind.CAPTURE
assert not txn.is_success
diff --git a/tests/gateway/test_braintree.py b/tests/gateway/test_braintree.py
index dbcd94921c..2b9daa64a6 100644
--- a/tests/gateway/test_braintree.py
+++ b/tests/gateway/test_braintree.py
@@ -1,21 +1,23 @@
import datetime
from decimal import Decimal
-from unittest.mock import Mock, patch
+from unittest.mock import Mock, patch, MagicMock
import pytest
-from braintree import Environment, ErrorResult, SuccessfulResult, Transaction
+from braintree import (
+ CreditCard, 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
from prices import Money
-from saleor.payment import TransactionKind
+from saleor.payment import TransactionKind, get_payment_gateway
from saleor.payment.gateways.braintree import (
CONFIRM_MANUALLY, THREE_D_SECURE_REQUIRED, authorize, capture,
- extract_gateway_response, get_client_token, get_customer_data,
- get_error_for_client, get_braintree_gateway, refund,
+ extract_gateway_response, get_braintree_gateway, get_client_token,
+ get_customer_data, get_error_for_client, refund,
transaction_and_incorrect_token_error, void)
+from saleor.payment.gateways.braintree.forms import BraintreePaymentForm
INCORRECT_TOKEN_ERROR = (
'Unable to process the transaction. Transaction\'s token is incorrect '
@@ -33,14 +35,7 @@ def braintree_success_response():
spec=Transaction,
amount=Decimal('0.20'),
created_at='2018-10-20 18:34:22',
- credit_card=Mock(
- token=None,
- bin='400000',
- last_4='0002',
- card_type='Visa',
- expiration_month='01',
- expiration_year='2020',
- customer_location='International'),
+ credit_card='', # FIXME we should provide a proper CreditCard mock
additional_processor_response='',
gateway_rejection_reason='',
processor_response_code='1000',
@@ -51,6 +46,7 @@ def braintree_success_response():
currency_iso_code='EUR',
status='authorized'))
+
@pytest.fixture
def braintree_error():
return Mock(
@@ -91,10 +87,12 @@ def success_gateway_response(gateway_response):
data.pop('amount')
return data
+
def test_get_customer_data(payment_dummy):
payment = payment_dummy
result = get_customer_data(payment)
expected_result = {
+ 'order_id': payment.order_id,
'billing': {
'first_name': payment.billing_first_name,
'last_name': payment.billing_last_name,
@@ -140,16 +138,7 @@ def test_extract_gateway_response(braintree_success_response):
expected_result = {
'currency': t.currency_iso_code,
'amount': t.amount,
- 'created_at': str(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
@@ -216,7 +205,6 @@ def test_authorize_error_response(
assert error == DEFAULT_ERROR
-
@pytest.mark.integration
@patch('saleor.payment.gateways.braintree.transaction_and_incorrect_token_error')
@patch('saleor.payment.gateways.braintree.get_braintree_gateway')
@@ -402,7 +390,6 @@ def test_capture_error_response(
assert error == DEFAULT_ERROR
-
@pytest.mark.integration
@patch('saleor.payment.gateways.braintree.get_braintree_gateway')
def test_void(
@@ -480,3 +467,36 @@ def test_transaction_and_incorrect_token_error_helper_no_amount(payment_dummy):
txn, error = transaction_and_incorrect_token_error(
payment_dummy, 'example-token', TransactionKind.AUTH)
assert txn.amount == payment_dummy.total
+
+
+def test_braintree_payment_form_incorrect_amount(payment_dummy):
+ amount = Decimal('0.01')
+ data = {'amount': amount, 'payment_method_nonce': 'fake-nonce'}
+ assert amount != payment_dummy.total
+
+ payment_gateway, gateway_params = get_payment_gateway(
+ payment_dummy.gateway)
+ form = BraintreePaymentForm(
+ data=data, payment=payment_dummy, gateway=payment_gateway,
+ gateway_params=gateway_params)
+ assert not form.is_valid()
+ assert form.non_field_errors
+
+
+def test_braintree_payment_form(settings, payment_dummy):
+ payment = payment_dummy
+ payment.gateway = settings.BRAINTREE
+ data = {'amount': payment.total, 'payment_method_nonce': 'fake-nonce'}
+ payment_gateway, gateway_params = get_payment_gateway(payment.gateway)
+
+ form = BraintreePaymentForm(
+ data=data, payment=payment, gateway=payment_gateway,
+ gateway_params=gateway_params)
+ assert form.is_valid()
+ # FIXME check if appropriate methods were called
+ form.process_payment()
+
+
+def test_get_form_class(settings):
+ payment_gateway, gateway_params = get_payment_gateway(settings.BRAINTREE)
+ assert payment_gateway.get_form_class() == BraintreePaymentForm
diff --git a/tests/gateway/test_dummy.py b/tests/gateway/test_dummy.py
index 2ee181e42f..7956ad7ae0 100644
--- a/tests/gateway/test_dummy.py
+++ b/tests/gateway/test_dummy.py
@@ -2,8 +2,9 @@ from decimal import Decimal
import pytest
-from saleor.payment import ChargeStatus, PaymentError, TransactionKind
-
+from saleor.payment import (
+ ChargeStatus, PaymentError, TransactionKind, get_payment_gateway)
+from saleor.payment.gateways.dummy.forms import DummyPaymentForm
def test_authorize(payment_dummy):
txn = payment_dummy.authorize(payment_token='Fake')
@@ -156,3 +157,28 @@ def test_refund_gateway_error(payment_dummy, monkeypatch):
assert txn.payment == payment
assert payment.charge_status == ChargeStatus.CHARGED
assert payment.captured_amount == Decimal('80.00')
+
+
+ 'kind, charge_status',
+ (
+ (TransactionKind.REFUND, ChargeStatus.FULLY_REFUNDED),
+ (TransactionKind.AUTH, ChargeStatus.NOT_CHARGED),
+ (TransactionKind.CAPTURE, ChargeStatus.CHARGED)))
+def test_dummy_payment_form(kind, charge_status, settings, payment_dummy):
+ payment = payment_dummy
+ data = {'charge_status': charge_status}
+ payment_gateway, gateway_params = get_payment_gateway(payment.gateway)
+
+ form = DummyPaymentForm(
+ data=data, payment=payment, gateway=payment_gateway,
+ gateway_params=gateway_params)
+ assert form.is_valid()
+ form.process_payment()
+ payment.refresh_from_db()
+ assert payment.transactions.last().kind == kind
+
+
+def test_get_form_class(settings):
+ payment_gateway, gateway_params = get_payment_gateway(settings.DUMMY)
+ assert payment_gateway.get_form_class() == DummyPaymentForm
diff --git a/tests/test_payment.py b/tests/test_payment.py
index 8c85f951bf..91784ea8cc 100644
--- a/tests/test_payment.py
+++ b/tests/test_payment.py
@@ -11,8 +11,6 @@ from saleor.order import OrderEvents, OrderEventsEmails
from saleor.order.views import PAYMENT_TEMPLATE
from saleor.payment import (
ChargeStatus, PaymentError, TransactionKind, get_payment_gateway)
-from saleor.payment.forms import (
- BraintreePaymentForm, DummyPaymentForm, get_form_for_payment)
from saleor.payment.utils import (
create_payment, create_transaction, gateway_authorize, gateway_capture,
gateway_get_client_token, gateway_refund, gateway_void, get_billing_data,
@@ -444,19 +442,6 @@ def test_payment_gateway_templates_exists(gateway_name):
get_template(template)
-def test_get_form_for_payment(settings, payment_dummy):
- payment_dummy.gateway = settings.BRAINTREE
- assert get_form_for_payment(payment_dummy) == BraintreePaymentForm
- payment_dummy.gateway = settings.DUMMY
- assert get_form_for_payment(payment_dummy) == DummyPaymentForm
-
-
-def test_get_form_for_payment_non_existing_gateway(payment_dummy):
- with pytest.raises(NotImplementedError):
- payment_dummy.gateway = 'non-existing-provider'
- get_form_for_payment(payment_dummy)
-
-
@pytest.mark.parametrize('gateway_name', settings.PAYMENT_GATEWAYS.keys())
def test_payment_gateway_form_exists(gateway_name, payment_dummy):
"""Test if for each payment gateway there's a corresponding
@@ -464,45 +449,6 @@ def test_payment_gateway_form_exists(gateway_name, payment_dummy):
An error will be raised if it's missing.
"""
- payment_dummy.gateway = gateway_name
- get_form_for_payment(payment_dummy)
-
-
-def test_braintree_payment_form_incorrect_amount(payment_dummy):
- amount = Decimal('0.01')
- data = {'amount': amount, 'payment_method_nonce': 'fake-nonce'}
- assert amount != payment_dummy.total
-
payment_gateway, gateway_params = get_payment_gateway(
- payment_dummy.gateway)
- form = BraintreePaymentForm(
- data=data, payment=payment_dummy, gateway=payment_gateway,
- gateway_params=gateway_params)
- assert not form.is_valid()
- assert form.non_field_errors
-
-
-def test_braintree_payment_form(settings, payment_dummy):
- payment = payment_dummy
- payment.gateway = settings.BRAINTREE
- data = {'amount': payment.total, 'payment_method_nonce': 'fake-nonce'}
- payment_gateway, gateway_params = get_payment_gateway(payment.gateway)
-
- form = BraintreePaymentForm(
- data=data, payment=payment, gateway=payment_gateway,
- gateway_params=gateway_params)
- assert form.is_valid()
- # FIXME check if appropriate methods were called
- form.process_payment()
-
-
-def test_start_payment_braintree():
- raise ValueError
-
-
-def test_start_payment_dummy():
- raise ValueError
-
-
-def test_dummy_payment_form():
- raise ValueError
+ gateway_name)
+ payment_gateway.get_form_class()