Skip to content

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

Move payments to dedicated module. Add test suite

Artur Smęt899bfb8c3668
diff --git a/saleor/checkout/__init__.py b/saleor/checkout/__init__.py
index c650761f77..1577315920 100644
--- a/saleor/checkout/__init__.py
+++ b/saleor/checkout/__init__.py
@@ -9,12 +9,33 @@ class AddressType:
BILLING = 'billing'
SHIPPING = 'shipping'
+ CHOICES = [(
+ BILLING,
+ pgettext_lazy('Type of address used to fulfill order', 'Billing')), (
+ SHIPPING,
+ pgettext_lazy('Type of address used to fulfill order',
+ 'Shipping'))]
+
+
+class TransactionType:
+ AUTH = 'auth'
+ CHARGE = 'charge'
+ VOID = 'void'
+ REFUND = 'refund'
+
+ CHOICES = [(AUTH, pgettext_lazy('transaction type', 'Authorization')),
+ (CHARGE, pgettext_lazy('transaction type', 'Charge')),
+ (REFUND, pgettext_lazy('transaction type', 'Refund')),
+ (VOID, pgettext_lazy('transaction type', 'Void'))]
+
+
+class PaymentMethodChargeStatus:
+ CHARGED = 'charged'
+ NOT_CHARGED = 'not-charged'
+ FULLY_REFUNDED = 'fully-refunded'
+
CHOICES = [
- (BILLING, pgettext_lazy(
- 'Type of address used to fulfill order',
- 'Billing'
- )),
- (SHIPPING, pgettext_lazy(
- 'Type of address used to fulfill order',
- 'Shipping'
- ))]
+ (CHARGED, pgettext_lazy('payment method status', 'Charged')),
+ (NOT_CHARGED, pgettext_lazy('payment method status', 'Not charged')), (
+ FULLY_REFUNDED,
+ pgettext_lazy('payment method status', 'Fully refunded'))]
diff --git a/saleor/checkout/forms.py b/saleor/checkout/forms.py
index 6682cd5ed3..8260d53ad2 100644
--- a/saleor/checkout/forms.py
+++ b/saleor/checkout/forms.py
@@ -367,9 +367,3 @@ class CartVoucherForm(forms.ModelForm):
if voucher.translated.name != voucher.name else '')
self.instance.discount_amount = self.cleaned_data['discount_amount']
return super().save(commit)
-
-
-class PaymentMethodForm(forms.ModelForm):
- class Meta:
- model = PaymentMethod
- fields = ['variant', 'is_active', 'total', 'charge_status']
diff --git a/saleor/checkout/models.py b/saleor/checkout/models.py
index ce824655c7..06060c8303 100644
--- a/saleor/checkout/models.py
+++ b/saleor/checkout/models.py
@@ -8,13 +8,10 @@ from django.core.validators import MinValueValidator
from django.db import models
from django.utils.encoding import smart_str
from django_prices.models import MoneyField
-from jsonfield import JSONField
from measurement.measures import Weight
-from prices import Money
from ..account.models import Address
from ..core.utils.taxes import ZERO_TAXED_MONEY
-from ..order.models import Order
from ..shipping.models import ShippingMethod
CENTS = Decimal('0.01')
@@ -173,126 +170,3 @@ class CartLine(models.Model):
def is_shipping_required(self):
"""Return `True` if the related product variant requires shipping."""
return self.variant.is_shipping_required()
-
-
-class TransactionType:
- AUTH = 'auth'
- CHARGE = 'charge'
- VOID = 'void'
- REFUND = 'refund'
-
- CHOICES = [(AUTH, pgettext_lazy('transaction type', 'Authorization')),
- (CHARGE, pgettext_lazy('transaction type', 'Charge')),
- (REFUND, pgettext_lazy('transaction type', 'Refund')),
- (VOID, pgettext_lazy('transaction type', 'Void'))]
-
-
-class PaymentMethodChargeStatus:
- CHARGED = 'charged'
- NOT_CHARGED = 'not-charged'
- FULLY_REFUNDED = 'fully-refunded'
-
- CHOICES = [
- (CHARGED, pgettext_lazy('payment method status', 'Charged')),
- (NOT_CHARGED, pgettext_lazy('payment method status', 'Not charged')), (
- FULLY_REFUNDED,
- pgettext_lazy('payment method status', 'Fully refunded'))]
-
-
-class PaymentMethod(models.Model):
- variant = models.CharField(max_length=255)
- is_active = models.BooleanField(default=True)
- #: Creation date and time
- created = models.DateTimeField(auto_now_add=True)
- #: Date and time of last modification
- modified = models.DateTimeField(auto_now=True)
- charge_status = models.CharField(
- max_length=15,
- choices=PaymentMethodChargeStatus.CHOICES,
- default=PaymentMethodChargeStatus.NOT_CHARGED)
- billing_first_name = models.CharField(max_length=256, blank=True)
- billing_last_name = models.CharField(max_length=256, blank=True)
- billing_address_1 = models.CharField(max_length=256, blank=True)
- billing_address_2 = models.CharField(max_length=256, blank=True)
- billing_city = models.CharField(max_length=256, blank=True)
- billing_postcode = models.CharField(max_length=256, blank=True)
- billing_country_code = models.CharField(max_length=2, blank=True)
- billing_country_area = models.CharField(max_length=256, blank=True)
- billing_email = models.EmailField(blank=True)
- customer_ip_address = models.GenericIPAddressField(blank=True, null=True)
- extra_data = models.TextField(blank=True, default='')
- token = models.CharField(max_length=36, blank=True, default='')
-
- total = models.DecimalField(max_digits=9, decimal_places=2, default='0.0')
- currency = models.CharField(max_length=10)
- captured_amount = models.DecimalField(
- max_digits=9, decimal_places=2, default='0.0')
- tax = models.DecimalField(max_digits=9, decimal_places=2, default='0.0')
-
- checkout = models.ForeignKey(
- Cart,
- null=True,
- related_name='payment_methods',
- on_delete=models.SET_NULL)
- order = models.ForeignKey(
- Order,
- null=True,
- related_name='payment_methods',
- on_delete=models.CASCADE)
-
- def _get_money(self, amount):
- return Money(amount=amount, currency=self.currency)
-
- def get_total(self):
- return self._get_money(self.total)
-
- def get_captured_money(self):
- return self._get_money(self.captured_amount)
-
- def get_tax_money(self):
- return self._get_money(self.tax)
-
- def authorize(self):
- # Check if payment method is active and create Transaction with AUTH type
- pass
-
- def void(self):
- # Check if payment method is active and create Transaction with VOID type
- pass
-
- def charge(self, amount=None):
- # Check if payment method is active and create Transaction with CHARGE type
- pass
-
- def refund(self, amount=None):
- # Check if payment method is active and create Transaction with REFUND type
- pass
-
-
-class Transaction(models.Model):
- payment_method = models.ForeignKey(
- PaymentMethod, related_name='transactions', on_delete=models.CASCADE)
- token = models.CharField(max_length=64, blank=True, default='')
- transaction_type = models.CharField(
- max_length=10, choices=TransactionType.CHOICES)
- is_success = models.BooleanField(default=False)
-
- total = models.DecimalField(max_digits=9, decimal_places=2, default='0.0')
- currency = models.CharField(max_length=10)
- captured_amount = models.DecimalField(
- max_digits=9, decimal_places=2, default='0.0')
- tax = models.DecimalField(max_digits=9, decimal_places=2, default='0.0')
-
- gateway_response = JSONField()
-
- def _get_money(self, amount):
- return Money(amount=amount, currency=self.currency)
-
- def get_total(self):
- return self._get_money(self.total)
-
- def get_captured_money(self):
- return self._get_money(self.captured_amount)
-
- def get_tax_money(self):
- return self._get_money(self.tax)
diff --git a/saleor/order/models.py b/saleor/order/models.py
index df310d2277..e4135db330 100644
--- a/saleor/order/models.py
+++ b/saleor/order/models.py
@@ -181,15 +181,18 @@ class Order(models.Model):
return reverse('order:details', kwargs={'token': self.token})
def get_last_payment(self):
+ # FIXME Adapt to new API
return max(self.payments.all(), default=None, key=attrgetter('pk'))
def get_last_payment_status(self):
+ # FIXME Adapt to new API
last_payment = self.get_last_payment()
if last_payment:
return last_payment.status
return None
def get_last_payment_status_display(self):
+ # FIXME Adapt to new API
last_payment = max(
self.payments.all(), default=None, key=attrgetter('pk'))
if last_payment:
@@ -197,6 +200,7 @@ class Order(models.Model):
return None
def is_pre_authorized(self):
+ # FIXME Adapt to new API
# FIXME: Check for really pre-authorized transactions
return self.payment_methods.filter(is_active=True).exists()
diff --git a/saleor/order/views.py b/saleor/order/views.py
index 0555e590d1..502d704f79 100644
--- a/saleor/order/views.py
+++ b/saleor/order/views.py
@@ -10,13 +10,14 @@ from django.template.response import TemplateResponse
from django.urls import reverse
from django.utils.translation import pgettext_lazy
from django.views.decorators.csrf import csrf_exempt
-from payments import PaymentStatus, RedirectNeeded
+from payments import PaymentStatus
from . import FulfillmentStatus
from ..account.forms import LoginForm
from ..account.models import User
from ..core.utils import get_client_ip
-from ..checkout.models import PaymentMethod
+from ..payment.forms import PaymentMethodForm
+from ..payment.models import PaymentMethod
from .forms import (
CustomerNoteForm, PasswordForm, PaymentDeleteForm, PaymentMethodsForm)
from .models import Order, Payment
@@ -113,7 +114,6 @@ def start_payment(request, order, variant):
with transaction.atomic():
payment_method, dummy_created = PaymentMethod.objects.get_or_create(
variant=variant, is_active=True, order=order, defaults=defaults)
- from ..checkout.forms import PaymentMethodForm
form = PaymentMethodForm(
data=request.POST or None, instance=payment_method)
form.method = "POST"
diff --git a/saleor/payment/__init__.py b/saleor/payment/__init__.py
new file mode 100644
index 0000000000..abd508277e
--- /dev/null
+++ b/saleor/payment/__init__.py
@@ -0,0 +1,44 @@
+from django.utils.translation import pgettext_lazy
+import importlib
+from django.core.exceptions import ImproperlyConfigured
+
+
+class PaymentError(Exception):
+ pass
+
+
+class TransactionType:
+ AUTH = 'auth'
+ CHARGE = 'charge'
+ VOID = 'void'
+ REFUND = 'refund'
+
+ CHOICES = [(AUTH, pgettext_lazy('transaction type', 'Authorization')),
+ (CHARGE, pgettext_lazy('transaction type', 'Charge')),
+ (REFUND, pgettext_lazy('transaction type', 'Refund')),
+ (VOID, pgettext_lazy('transaction type', 'Void'))]
+
+
+class PaymentMethodChargeStatus:
+ CHARGED = 'charged'
+ NOT_CHARGED = 'not-charged'
+ FULLY_REFUNDED = 'fully-refunded'
+
+ CHOICES = [
+ (CHARGED, pgettext_lazy('payment method status', 'Charged')),
+ (NOT_CHARGED, pgettext_lazy('payment method status', 'Not charged')), (
+ FULLY_REFUNDED,
+ pgettext_lazy('payment method status', 'Fully refunded'))]
+
+
+# FIXME: move to settings
+PROVIDERS_MAP = {'dummy': 'saleor.payment.providers.dummy'}
+
+
+def get_provider(provider_name):
+ if provider_name not in PROVIDERS_MAP:
+ raise ImproperlyConfigured(
+ f'Payment provider {provider_name} is not configured.')
+ provider_module = importlib.import_module(PROVIDERS_MAP[provider_name])
+
+ return provider_module
diff --git a/saleor/payment/forms.py b/saleor/payment/forms.py
new file mode 100644
index 0000000000..9b28e54090
--- /dev/null
+++ b/saleor/payment/forms.py
@@ -0,0 +1,8 @@
+from django import forms
+from .models import PaymentMethod
+
+
+class PaymentMethodForm(forms.ModelForm):
+ class Meta:
+ model = PaymentMethod
+ fields = ['variant', 'is_active', 'total', 'charge_status']
diff --git a/saleor/checkout/migrations/0010_paymentmethod_transaction.py b/saleor/payment/migrations/0001_initial.py
similarity index 84%
rename from saleor/checkout/migrations/0010_paymentmethod_transaction.py
rename to saleor/payment/migrations/0001_initial.py
index 172c40b0fa..fa7ff78900 100644
--- a/saleor/checkout/migrations/0010_paymentmethod_transaction.py
+++ b/saleor/payment/migrations/0001_initial.py
@@ -1,15 +1,17 @@
-# Generated by Django 2.0.3 on 2018-08-13 13:14
+# Generated by Django 2.0.3 on 2018-08-14 08:46
+import django.contrib.postgres.fields.jsonb
from django.db import migrations, models
import django.db.models.deletion
-import jsonfield.fields
class Migration(migrations.Migration):
+ initial = True
+
dependencies = [
('order', '0051_merge_20180807_0704'),
- ('checkout', '0009_cart_translated_discount_name'),
+ ('checkout', '0010_auto_20180814_0216'),
]
operations = [
@@ -49,12 +51,9 @@ class Migration(migrations.Migration):
('token', models.CharField(blank=True, default='', max_length=64)),
('transaction_type', models.CharField(choices=[('auth', 'Authorization'), ('charge', 'Charge'), ('refund', 'Refund'), ('void', 'Void')], max_length=10)),
('is_success', models.BooleanField(default=False)),
- ('total', models.DecimalField(decimal_places=2, default='0.0', max_digits=9)),
- ('currency', models.CharField(max_length=10)),
- ('captured_amount', models.DecimalField(decimal_places=2, default='0.0', max_digits=9)),
- ('tax', models.DecimalField(decimal_places=2, default='0.0', max_digits=9)),
- ('gateway_response', jsonfield.fields.JSONField()),
- ('payment_method', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='transactions', to='checkout.PaymentMethod')),
+ ('amount', models.DecimalField(decimal_places=2, default='0.0', max_digits=9)),
+ ('gateway_response', django.contrib.postgres.fields.jsonb.JSONField()),
+ ('payment_method', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, related_name='transactions', to='payment.PaymentMethod')),
],
),
]
diff --git a/saleor/payment/migrations/__init__.py b/saleor/payment/migrations/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/saleor/payment/models.py b/saleor/payment/models.py
new file mode 100644
index 0000000000..9c4a88c41f
--- /dev/null
+++ b/saleor/payment/models.py
@@ -0,0 +1,90 @@
+from decimal import Decimal
+from django.db import models
+from prices import Money
+from django.contrib.postgres.fields import JSONField
+from . import PaymentMethodChargeStatus, TransactionType
+from ..checkout.models import Cart
+from ..order.models import Order
+from . import utils
+
+
+class PaymentMethod(models.Model):
+ variant = models.CharField(max_length=255)
+ is_active = models.BooleanField(default=True)
+ #: Creation date and time
+ created = models.DateTimeField(auto_now_add=True)
+ #: Date and time of last modification
+ modified = models.DateTimeField(auto_now=True)
+ charge_status = models.CharField(
+ max_length=15,
+ choices=PaymentMethodChargeStatus.CHOICES,
+ default=PaymentMethodChargeStatus.NOT_CHARGED)
+ billing_first_name = models.CharField(max_length=256, blank=True)
+ billing_last_name = models.CharField(max_length=256, blank=True)
+ billing_address_1 = models.CharField(max_length=256, blank=True)
+ billing_address_2 = models.CharField(max_length=256, blank=True)
+ billing_city = models.CharField(max_length=256, blank=True)
+ billing_postcode = models.CharField(max_length=256, blank=True)
+ billing_country_code = models.CharField(max_length=2, blank=True)
+ billing_country_area = models.CharField(max_length=256, blank=True)
+ billing_email = models.EmailField(blank=True)
+ customer_ip_address = models.GenericIPAddressField(blank=True, null=True)
+ extra_data = models.TextField(blank=True, default='')
+ token = models.CharField(max_length=36, blank=True, default='')
+
+ total = models.DecimalField(
+ max_digits=9, decimal_places=2, default=Decimal('0.0'))
+ currency = models.CharField(max_length=10)
+ captured_amount = models.DecimalField(
+ max_digits=9, decimal_places=2, default=Decimal('0.0'))
+ tax = models.DecimalField(
+ max_digits=9, decimal_places=2, default=Decimal('0.0'))
+
+ checkout = models.ForeignKey(
+ Cart,
+ null=True,
+ related_name='payment_methods',
+ on_delete=models.SET_NULL)
+ order = models.ForeignKey(
+ Order,
+ null=True,
+ related_name='payment_methods',
+ on_delete=models.CASCADE)
+
+ def _get_money(self, amount):
+ return Money(amount=amount, currency=self.currency)
+
+ def get_total(self):
+ return self._get_money(self.total)
+
+ def get_captured_money(self):
+ return self._get_money(self.captured_amount)
+
+ def get_tax_money(self):
+ return self._get_money(self.tax)
+
+ def authorize(self):
+ return utils.gateway_authorize(payment_method=self)
+
+ def void(self):
+ return utils.gateway_void(payment_method=self)
+
+ def charge(self, amount=None):
+ return utils.gateway_charge(payment_method=self, amount=amount)
+
+ def refund(self, amount=None):
+ return utils.gateway_refund(payment_method=self, amount=amount)
+
+
+class Transaction(models.Model):
+ payment_method = models.ForeignKey(
+ PaymentMethod, related_name='transactions', on_delete=models.CASCADE)
+ token = models.CharField(max_length=64, blank=True, default='')
+ transaction_type = models.CharField(
+ max_length=10, choices=TransactionType.CHOICES)
+ is_success = models.BooleanField(default=False)
+ amount = models.DecimalField(max_digits=9, decimal_places=2, default='0.0')
+ gateway_response = JSONField()
+
+ def get_amount(self):
+ return Money(amount=self.amount, currency=self.payment_method.currency)
diff --git a/saleor/payment/providers/__init__.py b/saleor/payment/providers/__init__.py
new file mode 100644
index 0000000000..e69de29bb2
diff --git a/saleor/payment/providers/dummy/__init__.py b/saleor/payment/providers/dummy/__init__.py
new file mode 100644
index 0000000000..3d0338593b
--- /dev/null
+++ b/saleor/payment/providers/dummy/__init__.py
@@ -0,0 +1,57 @@
+import uuid
+from django.db import transaction
+
+from ... import TransactionType, PaymentMethodChargeStatus
+from ...models import Transaction
+
+
+def dummy_success():
+ return True
+
+
+def authorize(payment_method):
+ txn = Transaction.objects.get_or_create(
+ payment_method=payment_method,
+ transaction_type=TransactionType.AUTH,
+ amount=payment_method.total,
+ gateway_response={},
+ defaults={
+ 'token': str(uuid.uuid4()),
+ 'is_success': dummy_success()})[0]
+ return txn
+
+
+def void(payment_method):
+ txn = Transaction.objects.get_or_create(
+ payment_method=payment_method,
+ transaction_type=TransactionType.VOID,
+ amount=payment_method.total,
+ gateway_response={},
+ defaults={
+ 'token': str(uuid.uuid4()),
+ 'is_success': dummy_success()})[0]
+ return txn
+
+
+def charge(payment_method, amount=None):
+ txn = Transaction.objects.get_or_create(
+ payment_method=payment_method,
+ transaction_type=TransactionType.CHARGE,
+ amount=amount,
+ defaults={
+ 'token': str(uuid.uuid4()),
+ 'gateway_response': {},
+ 'is_success': dummy_success()})[0]
+ return txn
+
+
+def refund(payment_method, amount=None):
+ txn = Transaction.objects.get_or_create(
+ payment_method=payment_method,
+ transaction_type=TransactionType.REFUND,
+ amount=amount,
+ defaults={
+ 'token': str(uuid.uuid4()),
+ 'gateway_response': {},
+ 'is_success': dummy_success()})[0]
+ return txn
diff --git a/saleor/payment/utils.py b/saleor/payment/utils.py
new file mode 100644
index 0000000000..a76e4ec9a8
--- /dev/null
+++ b/saleor/payment/utils.py
@@ -0,0 +1,87 @@
+from django.db import transaction
+
+from . import PaymentError, PaymentMethodChargeStatus, get_provider
+
+
+def gateway_authorize(payment_method):
+ if not payment_method.is_active:
+ raise PaymentError('This payment method is no longer active')
+ if not payment_method.charge_status == PaymentMethodChargeStatus.NOT_CHARGED:
+ raise PaymentError('Charged transactions cannot be authorized again')
+
+ provider = get_provider(payment_method.variant)
+ with transaction.atomic():
+ txn = provider.authorize(payment_method)
+ if txn.is_success:
+ payment_method.charge_status = PaymentMethodChargeStatus.NOT_CHARGED
+ payment_method.save(update_fields=['charge_status'])
+ if not txn.is_success:
+ # TODO: Handle gateway response here somehow
+ raise PaymentError('Unable to authorize transaction')
+ return txn
+
+
+def gateway_charge(payment_method, amount):
+ if not payment_method.is_active:
+ raise PaymentError('This payment method is no longer active')
+ if not payment_method.charge_status in {
+ PaymentMethodChargeStatus.CHARGED,
+ PaymentMethodChargeStatus.NOT_CHARGED}:
+ raise PaymentError('This payment method cannot be charged')
+ if amount > payment_method.total or amount > (
+ payment_method.total - payment_method.captured_amount):
+ raise PaymentError('Unable to charge more than authozied amount')
+ provider = get_provider(payment_method.variant)
+ with transaction.atomic():
+ txn = provider.charge(payment_method, amount=amount)
+ if txn.is_success:
+ payment_method.charge_status = PaymentMethodChargeStatus.CHARGED
+ payment_method.captured_amount += txn.amount
+ payment_method.save(
+ update_fields=['charge_status', 'captured_amount'])
+
+ if not txn.is_success:
+ # TODO: Handle gateway response here somehow
+ raise PaymentError('Unable to process transaction')
+ return txn
+
+
+def gateway_void(payment_method):
+ if not payment_method.is_active:
+ raise PaymentError('This payment method is no longer active')
+ if not payment_method.charge_status == PaymentMethodChargeStatus.NOT_CHARGED:
+ raise PaymentError('Only pre-authorized transactions can be void')
+ provider = get_provider(payment_method.variant)
+ with transaction.atomic():
+ txn = provider.void(payment_method)
+ if txn.is_success:
+ payment_method.is_active = False
+ payment_method.save(update_fields=['is_active'])
+ if not txn.is_success:
+ raise PaymentError('Unable to void transaction')
+ return txn
+
+
+def gateway_refund(payment_method, amount):
+ if not payment_method.is_active:
+ raise PaymentError('This payment method is no longer active')
+ if amount > payment_method.captured_amount:
+ raise PaymentError('Cannot refund more than captured')
+ if not payment_method.charge_status == PaymentMethodChargeStatus.CHARGED:
+ raise PaymentError(
+ 'Refund is possible only when transaction is charged')
+
+ provider = get_provider(payment_method.variant)
+ with transaction.atomic():
+ txn = provider.refund(payment_method, amount)
+ if txn.is_success:
+ changed_fields = ['captured_amount']
+ if txn.amount == payment_method.total:
+ payment_method.charge_status = PaymentMethodChargeStatus.FULLY_REFUNDED
+ payment_method.is_active = False
+ changed_fields += ['charge_status', 'is_active']
+ payment_method.captured_amount -= amount
+ payment_method.save(update_fields=changed_fields)
+ if not txn.is_success:
+ raise PaymentError('Unable to process refund')
+ return txn
diff --git a/saleor/settings.py b/saleor/settings.py
index 450620b49c..f4e5f62eaa 100644
--- a/saleor/settings.py
+++ b/saleor/settings.py
@@ -215,6 +215,7 @@ INSTALLED_APPS = [
'saleor.site',
'saleor.data_feeds',
'saleor.page',
+ 'saleor.payment',
# External apps
'versatileimagefield',
diff --git a/tests/conftest.py b/tests/conftest.py
index ba66319457..7cdb648e9b 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -29,6 +29,7 @@ from saleor.order import OrderStatus, OrderEvents
from saleor.order.models import Order, OrderEvent
from saleor.order.utils import recalculate_order
from saleor.page.models import Page
+from saleor.payment.models import PaymentMethod
from saleor.product.models import (
Attribute, AttributeTranslation, AttributeValue, Category, Collection,
Product, ProductImage, ProductTranslation, ProductType, ProductVariant)
@@ -89,7 +90,8 @@ def cart_with_voucher(cart, product, voucher):
@pytest.fixture
def address(db): # pylint: disable=W0613
return Address.objects.create(
- first_name='John', last_name='Doe',
+ first_name='John',
+ last_name='Doe',
company_name='Mirumee Software',
street_address_1='Tęczowa 7',
city='Wrocław',
@@ -114,7 +116,8 @@ def customer_user(address): # pylint: disable=W0613
def request_cart(cart, monkeypatch):
# FIXME: Fixtures should not have any side effects
monkeypatch.setattr(
- utils, 'get_cart_from_request',
+ utils,
+ 'get_cart_from_request',
lambda request, cart_queryset=None: cart)
return cart
@@ -153,7 +156,9 @@ def admin_client(admin_user):
def staff_user(db):
"""Return a staff member."""
return User.objects.create_user(
- email='[email protected]', password='password', is_staff=True,
+ password='password',
+ is_staff=True,
is_active=True)
@@ -191,8 +196,7 @@ def shipping_method(shipping_zone):
@pytest.fixture
def color_attribute(db): # pylint: disable=W0613
- attribute = Attribute.objects.create(
- slug='color', name='Color')
+ attribute = Attribute.objects.create(slug='color', name='Color')
AttributeValue.objects.create(
attribute=attribute, name='Red', slug='red')
AttributeValue.objects.create(
@@ -273,15 +277,22 @@ def product(product_type, category):
smart_text(variant_attr.pk): smart_text(variant_attr_value.pk)}
ProductVariant.objects.create(
- product=product, sku='123', attributes=variant_attributes,
- cost_price=Money('1.00', 'USD'), quantity=10, quantity_allocated=1)
+ product=product,
+ sku='123',
+ attributes=variant_attributes,
+ cost_price=Money('1.00', 'USD'),
+ quantity=10,
+ quantity_allocated=1)
return product
@pytest.fixture
def variant(product):
product_variant = ProductVariant.objects.create(
- product=product, sku='SKU_A', cost_price=Money(1, 'USD'), quantity=5,
+ product=product,
+ sku='SKU_A',
+ cost_price=Money(1, 'USD'),
+ quantity=5,
quantity_allocated=3)
return product_variant
@@ -289,7 +300,8 @@ def variant(product):
@pytest.fixture
def product_without_shipping(category):
product_type = ProductType.objects.create(
- name='Type with no shipping', has_variants=False,
+ name='Type with no shipping',
+ has_variants=False,
is_shipping_required=False)
product = Product.objects.create(
name='Test product', price=Money('10.00', 'USD'),
@@ -323,7 +335,8 @@ def product_list(product_type, category):
def order_list(customer_user):
address = customer_user.default_billing_address.get_copy()
data = {
- 'billing_address': address, 'user': customer_user,
+ 'billing_address': address,
+ 'user': customer_user,
'user_email': customer_user.email}
order = Order.objects.create(**data)
order1 = Order.objects.create(**data)
@@ -381,7 +394,10 @@ def order_with_lines(
name='Test product', price=Money('10.00', 'USD'),
product_type=product_type, category=category)
variant = ProductVariant.objects.create(
- product=product, sku='SKU_A', cost_price=Money(1, 'USD'), quantity=5,
+ product=product,
+ sku='SKU_A',
+ cost_price=Money(1, 'USD'),
+ quantity=5,
quantity_allocated=3)
order.lines.create(
product_name=variant.display_product(),
@@ -396,7 +412,10 @@ def order_with_lines(
name='Test product 2', price=Money('20.00', 'USD'),
product_type=product_type, category=category)
variant = ProductVariant.objects.create(
- product=product, sku='SKU_B', cost_price=Money(2, 'USD'), quantity=2,
+ product=product,
+ sku='SKU_B',
+ cost_price=Money(2, 'USD'),
+ quantity=2,
quantity_allocated=2)
order.lines.create(
product_name=variant.display_product(),
@@ -456,16 +475,20 @@ def draft_order(order_with_lines):
@pytest.fixture()
def payment_waiting(order_with_lines):
return order_with_lines.payments.create(
- variant='default', status=PaymentStatus.WAITING,
- fraud_status=FraudStatus.ACCEPT, currency='USD',
+ variant='default',
+ status=PaymentStatus.WAITING,
+ fraud_status=FraudStatus.ACCEPT,
+ currency='USD',
total=order_with_lines.total_gross.amount)
@pytest.fixture()
def payment_preauth(order_with_lines):
return order_with_lines.payments.create(
- variant='default', status=PaymentStatus.PREAUTH,
- fraud_status=FraudStatus.ACCEPT, currency='USD',
+ variant='default',
+ status=PaymentStatus.PREAUTH,
+ fraud_status=FraudStatus.ACCEPT,
+ currency='USD',
total=order_with_lines.total.gross.amount,
tax=order_with_lines.total.tax.amount)
@@ -474,41 +497,52 @@ def payment_preauth(order_with_lines):
def payment_confirmed(order_with_lines):
order_amount = order_with_lines.total_gross.amount
return order_with_lines.payments.create(
- variant='default', status=PaymentStatus.CONFIRMED,
- fraud_status=FraudStatus.ACCEPT, currency='USD',
- total=order_amount, captured_amount=order_amount,
+ variant='default',
+ status=PaymentStatus.CONFIRMED,
+ fraud_status=FraudStatus.ACCEPT,
+ currency='USD',
+ total=order_amount,
+ captured_amount=order_amount,
tax=order_with_lines.total.tax.amount)
@pytest.fixture()
def payment_rejected(order_with_lines):
return order_with_lines.payments.create(
- variant='default', status=PaymentStatus.REJECTED,
- fraud_status=FraudStatus.ACCEPT, currency='USD',
+ variant='default',
+ status=PaymentStatus.REJECTED,
+ fraud_status=FraudStatus.ACCEPT,
+ currency='USD',
total=order_with_lines.total_gross.amount)
@pytest.fixture()
def payment_refunded(order_with_lines):
return order_with_lines.payments.create(
- variant='default', status=PaymentStatus.REFUNDED,
- fraud_status=FraudStatus.ACCEPT, currency='USD',
+ variant='default',
+ status=PaymentStatus.REFUNDED,
+ fraud_status=FraudStatus.ACCEPT,
+ currency='USD',
total=order_with_lines.total_gross.amount)
@pytest.fixture()
def payment_error(order_with_lines):
return order_with_lines.payments.create(
- variant='default', status=PaymentStatus.ERROR,
- fraud_status=FraudStatus.ACCEPT, currency='USD',
+ variant='default',
+ status=PaymentStatus.ERROR,
+ fraud_status=FraudStatus.ACCEPT,
+ currency='USD',
total=order_with_lines.total_gross.amount)
@pytest.fixture()
def payment_input(order_with_lines):
return order_with_lines.payments.create(
- variant='default', status=PaymentStatus.INPUT,
- fraud_status=FraudStatus.ACCEPT, currency='USD',
+ variant='default',
+ status=PaymentStatus.INPUT,
+ fraud_status=FraudStatus.ACCEPT,
+ currency='USD',
total=order_with_lines.total_gross.amount)
@@ -620,9 +654,7 @@ def menu(db):
@pytest.fixture
def menu_item(menu):
return MenuItem.objects.create(
- menu=menu,
- name='Link 1',
- url='http://example.com/')
+ menu=menu, name='Link 1', url='http://example.com/')
@pytest.fixture
@@ -655,9 +687,10 @@ def tax_rates():
@pytest.fixture
def taxes(tax_rates):
- taxes = {'standard': {
- 'value': tax_rates['standard_rate'],
- 'tax': get_tax_for_rate(tax_rates)}}
+ taxes = {
+ 'standard': {
+ 'value': tax_rates['standard_rate'],
+ 'tax': get_tax_for_rate(tax_rates)}}
if tax_rates['reduced_rates']:
taxes.update({
rate: {
@@ -712,5 +745,13 @@ def voucher_translation_fr(voucher):
@pytest.fixture
def product_translation_fr(product):
return ProductTranslation.objects.create(
- language_code='fr', product=product, name='French name',
+ language_code='fr',
+ product=product,
+ name='French name',
description='French description')
+
+
+def payment_method_dummy(db):
+ return PaymentMethod.objects.create(
+ variant='dummy', is_active=True, total=100, currency='USD')
diff --git a/tests/test_payments.py b/tests/test_payments.py
new file mode 100644
index 0000000000..18d0d4651d
--- /dev/null
+++ b/tests/test_payments.py
@@ -0,0 +1,153 @@
+import pytest
+from saleor.payment import PaymentError, TransactionType, PaymentMethodChargeStatus
+
+
+def test_authorize(payment_method_dummy):
+ txn = payment_method_dummy.authorize()
+ assert txn.is_success
+ assert txn.transaction_type == TransactionType.AUTH
+ assert txn.payment_method == payment_method_dummy
+ payment_method_dummy.refresh_from_db()
+ assert payment_method_dummy.is_active
+
+
+def test_authorize_gateway_error(payment_method_dummy, monkeypatch):
+ monkeypatch.setattr(
+ 'saleor.payment.providers.dummy.dummy_success', lambda: False)
+ with pytest.raises(PaymentError):
+ txn = payment_method_dummy.authorize()
+ assert txn.transaction_type == TransactionType.AUTH
+ assert not txn.is_success
+ assert txn.payment_method == payment_method_dummy
+
+
+def test_void_success(payment_method_dummy):
+ assert payment_method_dummy.is_active
+ assert payment_method_dummy.charge_status == PaymentMethodChargeStatus.NOT_CHARGED
+ txn = payment_method_dummy.void()
+ assert txn.is_success
+ assert txn.transaction_type == TransactionType.VOID
+ assert txn.payment_method == payment_method_dummy
+ payment_method_dummy.refresh_from_db()
+ assert not payment_method_dummy.is_active
+ assert payment_method_dummy.charge_status == PaymentMethodChargeStatus.NOT_CHARGED
+
+
+ 'is_active, charge_status', [
+ (False, PaymentMethodChargeStatus.NOT_CHARGED),
+ (False, PaymentMethodChargeStatus.CHARGED),
+ (True, PaymentMethodChargeStatus.CHARGED),
+ (True, PaymentMethodChargeStatus.FULLY_REFUNDED), ])
+def test_void_failed(is_active, charge_status, payment_method_dummy):
+ payment_method = payment_method_dummy
+ payment_method.is_active = is_active
+ payment_method.charge_status = charge_status
+ payment_method.save()
+ with pytest.raises(PaymentError):
+ txn = payment_method.void()
+ assert txn is None
+
+
+def test_void_gateway_error(payment_method_dummy, monkeypatch):
+ monkeypatch.setattr(
+ 'saleor.payment.providers.dummy.dummy_success', lambda: False)
+ with pytest.raises(PaymentError):
+ txn = payment_method_dummy.authorize()
+ assert txn.transaction_type == TransactionType.VOID
+ assert not txn.is_success
+ assert txn.payment_method == payment_method_dummy
+
+
[email protected]('amount', [100, 90])
+def test_charge_success(amount, payment_method_dummy):
+ txn = payment_method_dummy.charge(amount=amount)
+ assert txn.is_success
+ assert txn.payment_method == payment_method_dummy
+ payment_method_dummy.refresh_from_db()
+ assert payment_method_dummy.charge_status == PaymentMethodChargeStatus.CHARGED
+ assert payment_method_dummy.is_active
+
+
+ 'amount, captured_amount, charge_status, is_active', [
+ (100, 0, PaymentMethodChargeStatus.NOT_CHARGED, False),
+ (100, 0, PaymentMethodChargeStatus.FULLY_REFUNDED, True),
+ (100, 100, PaymentMethodChargeStatus.CHARGED, True),
+ (120, 0, PaymentMethodChargeStatus.NOT_CHARGED, True), ])
+def test_charge_failed(
+ amount, captured_amount, charge_status, is_active,
+ payment_method_dummy):
+ payment_method = payment_method_dummy
+ payment_method.is_active = is_active
+ payment_method.captured_amount = captured_amount
+ payment_method.charge_status = charge_status
+ payment_method.save()
+ with pytest.raises(PaymentError):
+ txn = payment_method.charge(amount=amount)
+ assert txn is None
+
+
+def test_charge_gateway_error(payment_method_dummy, monkeypatch):
+ monkeypatch.setattr(
+ 'saleor.payment.providers.dummy.dummy_success', lambda: False)
+ with pytest.raises(PaymentError):
+ txn = payment_method_dummy.charge(100)
+ assert txn.transaction_type == TransactionType.CHARGE
+ assert not txn.is_success
+ assert txn.payment_method == payment_method_dummy
+
+
+ 'initial_captured_amount, refund_amount, final_captured_amount, final_charge_status, active_after',
+ [
+ (100, 100, 0, PaymentMethodChargeStatus.FULLY_REFUNDED, False),
+ (100, 10, 90, PaymentMethodChargeStatus.CHARGED, True), ])
+def test_refund_success(
+ initial_captured_amount, refund_amount, final_captured_amount,
+ final_charge_status, active_after, payment_method_dummy):
+ payment_method = payment_method_dummy
+ payment_method.charge_status = PaymentMethodChargeStatus.CHARGED
+ payment_method.captured_amount = initial_captured_amount
+ payment_method.save()
+ txn = payment_method.refund(refund_amount)
+ assert txn.transaction_type == TransactionType.REFUND
+ assert txn.is_success
+ assert txn.payment_method == payment_method
+ assert payment_method.charge_status == final_charge_status
+ assert payment_method.captured_amount == final_captured_amount
+ assert payment_method.is_active == active_after
+
+
+ 'initial_captured_amount, refund_amount, initial_charge_status', [
+ (100, 0, PaymentMethodChargeStatus.FULLY_REFUNDED),
+ (0, 10, PaymentMethodChargeStatus.NOT_CHARGED),
+ (10, 20, PaymentMethodChargeStatus.CHARGED), ])
+def test_refund_failed(
+ initial_captured_amount, refund_amount, initial_charge_status,
+ payment_method_dummy):
+ payment_method = payment_method_dummy
+ payment_method.charge_status = initial_charge_status
+ payment_method.captured_amount = initial_captured_amount
+ payment_method.save()
+ with pytest.raises(PaymentError):
+ txn = payment_method.refund(refund_amount)
+ assert txn is None
+
+
+def test_refund_gateway_error(payment_method_dummy, monkeypatch):
+ monkeypatch.setattr(
+ 'saleor.payment.providers.dummy.dummy_success', lambda: False)
+ payment_method = payment_method_dummy
+ payment_method.charge_status = PaymentMethodChargeStatus.CHARGED
+ payment_method.captured_amount = 100
+ payment_method.save()
+ with pytest.raises(PaymentError):
+ txn = payment_method.refund(100)
+ payment_method.refresh_from_db()
+ assert txn.transaction_type == TransactionType.REFUND
+ assert not txn.is_success
+ assert txn.payment_method == payment_method
+ assert payment_method.charge_status == PaymentMethodChargeStatus.CHARGED
+ assert payment_method.captured_amount == 100