Skip to content

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

Increase tests coverage

Pacu2b22ceeb4f661
diff --git a/docs/architecture/payments.rst b/docs/architecture/payments.rst
index 50e97049b8..adc44c38ca 100644
--- a/docs/architecture/payments.rst
+++ b/docs/architecture/payments.rst
@@ -74,7 +74,7 @@ Payment has 3 possible charge statuses:
Transactions
------------
-Transactions represent attempts to transfer money between your store
+Transaction represent attempts to transfer money between your store
and your customers, within a chosen payment method.
There are 5 possible transaction kinds:
diff --git a/docs/guides/payments.rst b/docs/guides/payments.rst
index 16362fdfce..3e5025052d 100644
--- a/docs/guides/payments.rst
+++ b/docs/guides/payments.rst
@@ -58,7 +58,7 @@ Example
txn = Transaction.objects.create(
payment=payment,
- kind=Transactions.AUTH,
+ kind=TransactionKind.AUTH,
amount=payment.total,
currency=payment.currency,
gateway_response=get_payment_gateway_response(response),
@@ -84,7 +84,7 @@ Example
# Please note that token from the last AUTH transaction should be used
capture_txn = payment.transactions.filter(
- kind=Transactions.CAPTURE).first()
+ kind=TransactionKind.CAPTURE).first()
transaction_token = capture_txn.token
# Handle connecting to the gateway and sending the refund request here
@@ -92,7 +92,7 @@ Example
txn = create_transaction(
payment=payment,
- kind=Transactions.REFUND,
+ kind=TransactionKind.REFUND,
amount=amount,
currency=payment.currency,
token=response.transaction.id,
@@ -117,7 +117,7 @@ Example
# Please note that token from the last AUTH transaction should be used
auth_transaction = payment.transactions.filter(
- kind=Transactions.AUTH).first()
+ kind=TransactionKind.AUTH).first()
transaction_token = auth_transaction.token
# Handle connecting to the gateway and sending the capture request here
@@ -125,7 +125,7 @@ Example
txn = create_transaction(
payment=payment,
- kind=Transactions.CAPTURE,
+ kind=TransactionKind.CAPTURE,
amount=amount,
currency=payment.currency,
token=response.transaction.id,
@@ -149,7 +149,7 @@ Example
# Please note that token from the last AUTH transaction should be used
auth_transaction = payment.transactions.filter(
- kind=Transactions.AUTH).first()
+ kind=TransactionKind.AUTH).first()
transaction_token = auth_transaction.token
# Handle connecting to the gateway and sending the void request here
@@ -157,7 +157,7 @@ Example
txn = create_transaction(
payment=payment,
- kind=Transactions.VOID,
+ kind=TransactionKind.VOID,
amount=payment.total,
currency=payment.currency,
gateway_response=get_payment_gateway_response(response),
diff --git a/saleor/core/utils/random_data.py b/saleor/core/utils/random_data.py
index f6895c42f6..ad3c128f44 100644
--- a/saleor/core/utils/random_data.py
+++ b/saleor/core/utils/random_data.py
@@ -29,7 +29,7 @@ from ...menu.models import Menu
from ...order.models import Fulfillment, Order
from ...order.utils import update_order_status
from ...page.models import Page
-from ...payment import ChargeStatus, Transactions
+from ...payment import ChargeStatus, TransactionKind
from ...payment.models import Payment
from ...payment.utils import get_billing_data
from ...product.models import (
diff --git a/saleor/graphql/payment/types.py b/saleor/graphql/payment/types.py
index 92f47dca12..ba065f6b64 100644
--- a/saleor/graphql/payment/types.py
+++ b/saleor/graphql/payment/types.py
@@ -41,7 +41,7 @@ class Transaction(CountableDjangoObjectType):
description = 'An object representing a single payment.'
interfaces = [relay.Node]
model = models.Transaction
- filter_fields = ['id', 'charge_status', 'is_success']
+ filter_fields = ['id']
exclude_fields = ['currency']
@staticmethod
@@ -54,7 +54,7 @@ class CreditCard(graphene.ObjectType):
description='Card brand.', required=True)
first_digits = graphene.String(
description='The host name of the domain.', required=True)
- last_digits = graphene.Boolean(
+ last_digits = graphene.String(
description='Last 4 digits of the card number.', required=True)
exp_month = graphene.Int(
description='Two-digit number representing the card’s expiration month.',
diff --git a/saleor/order/models.py b/saleor/order/models.py
index 875040de92..04e200c313 100644
--- a/saleor/order/models.py
+++ b/saleor/order/models.py
@@ -22,7 +22,7 @@ from ..core.utils.json_serializer import CustomJsonEncoder
from ..core.utils.taxes import ZERO_TAXED_MONEY, zero_money
from ..core.weight import WeightUnits, zero_weight
from ..discount.models import Voucher
-from ..payment import ChargeStatus, Transactions
+from ..payment import ChargeStatus, TransactionKind
from ..shipping.models import ShippingMethod
@@ -187,7 +187,7 @@ class Order(models.Model):
# payment gateways in the future.
return self.payments.filter(
is_active=True,
- transactions__kind=Transactions.AUTH).exists()
+ transactions__kind=TransactionKind.AUTH).exists()
@property
def quantity_fulfilled(self):
diff --git a/saleor/order/views.py b/saleor/order/views.py
index 3dff8aa73e..1250b17fe8 100644
--- a/saleor/order/views.py
+++ b/saleor/order/views.py
@@ -15,7 +15,7 @@ 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, Transactions, get_payment_gateway
+from ..payment import ChargeStatus, PaymentError, TransactionKind, get_payment_gateway
from ..payment.forms import get_form_for_payment
from ..payment.models import Payment
from ..payment.utils import get_billing_data
@@ -63,7 +63,7 @@ def payment(request, token):
waiting_payment = payments.filter(
is_active=True,
charge_status=ChargeStatus.NOT_CHARGED,
- transactions__kind=Transactions.AUTH).first()
+ transactions__kind=TransactionKind.AUTH).first()
if not waiting_payment:
waiting_payment_form = None
else:
diff --git a/saleor/payment/__init__.py b/saleor/payment/__init__.py
index f6a9a41f63..46ac1eff11 100644
--- a/saleor/payment/__init__.py
+++ b/saleor/payment/__init__.py
@@ -33,7 +33,7 @@ class TransactionError(Enum):
-class Transactions:
+class TransactionKind:
"""
- Authorization: An amount reserved against the customer's funding
source. Money does not change hands until the
@@ -45,7 +45,7 @@ class Transactions:
- Refund: Full or partial return of captured funds to the customer.
"""
AUTH = 'auth'
- CHARGE = 'capture'
+ CHARGE = 'charge'
CAPTURE = 'capture'
VOID = 'void'
REFUND = 'refund'
@@ -70,9 +70,11 @@ class ChargeStatus:
NOT_CHARGED = 'not-charged'
FULLY_REFUNDED = 'fully-refunded'
# FIXME
- # We should probably support other statuses, like:
+ # We could probably support other statuses, like:
# partially charged
# partially refunded
+ # fully charged
+ # ...?
CHOICES = [
(CHARGED, pgettext_lazy('payment status', 'Charged')),
diff --git a/saleor/payment/forms.py b/saleor/payment/forms.py
index af0d3c517b..388bf715ce 100644
--- a/saleor/payment/forms.py
+++ b/saleor/payment/forms.py
@@ -3,7 +3,7 @@ from django.conf import settings
from django.core.exceptions import ValidationError
from django.utils.translation import pgettext_lazy
-from . import ChargeStatus, PaymentError, Transactions, get_payment_gateway
+from . import ChargeStatus, PaymentError, TransactionKind, get_payment_gateway
from .models import Payment
from .utils import gateway_authorize, gateway_capture, gateway_refund
@@ -85,8 +85,7 @@ class BraintreePaymentForm(PaymentForm):
# FIXME add tests
payment_token = self.cleaned_data['payment_method_nonce']
self.payment.token = payment_token
- self.payment.save(updated_fields=['token'])
-
+ self.payment.save(update_fields=['token'])
self.payment.authorize(payment_token)
try:
self.payment.capture(self.payment.total)
diff --git a/saleor/payment/gateways/braintree/__init__.py b/saleor/payment/gateways/braintree/__init__.py
index 5adbfa13e2..a66fd449fc 100644
--- a/saleor/payment/gateways/braintree/__init__.py
+++ b/saleor/payment/gateways/braintree/__init__.py
@@ -8,7 +8,7 @@ from django.core.exceptions import ImproperlyConfigured
from django.utils.translation import pgettext_lazy
from prices import Money
-from ... import Transactions
+from ... import TransactionKind
from ...models import Payment, Transaction
from ...utils import create_transaction
@@ -72,7 +72,7 @@ def get_error_for_client(errors: List) -> str:
def transaction_and_incorrect_token_error(
payment: Payment,
token: str,
- kind: Transactions,
+ kind: TransactionKind,
amount: Decimal = None) -> Tuple[Transaction, str]:
amount = amount or payment.total
txn = create_transaction(
@@ -150,7 +150,7 @@ def authorize(
**get_customer_data(payment)})
except braintree_sdk.exceptions.NotFoundError:
return transaction_and_incorrect_token_error(
- payment, kind=Transactions.AUTH, token=payment_token)
+ 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')
@@ -166,7 +166,7 @@ def authorize(
txn = create_transaction(
payment=payment,
- kind=Transactions.AUTH,
+ kind=TransactionKind.AUTH,
amount=gateway_response.pop('amount', payment.total),
currency=gateway_response.pop('currency', payment.currency),
gateway_response=gateway_response,
@@ -181,14 +181,14 @@ def capture(
**connection_params: Dict) -> Tuple[Transaction, str]:
gateway = get_braintree_gateway(**connection_params)
auth_transaction = payment.transactions.filter(
- kind=Transactions.AUTH, is_success=True).first()
+ kind=TransactionKind.AUTH, is_success=True).first()
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,
- kind=Transactions.CAPTURE,
+ kind=TransactionKind.CAPTURE,
token=auth_transaction.token,
amount=amount)
@@ -198,7 +198,7 @@ def capture(
txn = create_transaction(
payment=payment,
parent=auth_transaction,
- kind=Transactions.CAPTURE,
+ kind=TransactionKind.CAPTURE,
amount=gateway_response.pop('amount', amount),
currency=gateway_response.pop('currency', payment.currency),
token=getattr(result.transaction, 'id', ''),
@@ -212,20 +212,20 @@ def void(
**connection_params: Dict) -> Tuple[Transaction, str]:
gateway = get_braintree_gateway(**connection_params)
auth_transaction = payment.transactions.filter(
- kind=Transactions.AUTH, is_success=True).first()
+ kind=TransactionKind.AUTH, is_success=True).first()
try:
result = gateway.transaction.void(
transaction_id=auth_transaction.token)
except braintree_sdk.exceptions.NotFoundError:
return transaction_and_incorrect_token_error(
- payment, kind=Transactions.VOID, token=auth_transaction.token)
+ payment, kind=TransactionKind.VOID, token=auth_transaction.token)
gateway_response = extract_gateway_response(result)
error = get_error_for_client(gateway_response['errors'])
txn = create_transaction(
payment=payment,
parent=auth_transaction,
- kind=Transactions.VOID,
+ kind=TransactionKind.VOID,
amount=gateway_response.pop('amount', payment.total),
currency=gateway_response.pop('currency', payment.currency),
gateway_response=gateway_response,
@@ -240,14 +240,14 @@ def refund(
**connection_params: Dict) -> Tuple[Transaction, str]:
gateway = get_braintree_gateway(**connection_params)
capture_txn = payment.transactions.filter(
- kind=Transactions.CAPTURE, is_success=True).first()
+ kind=TransactionKind.CAPTURE, is_success=True).first()
try:
result = gateway.transaction.refund(
transaction_id=capture_txn.token,
amount_or_options=str(amount))
except braintree_sdk.exceptions.NotFoundError:
return transaction_and_incorrect_token_error(
- payment, kind=Transactions.REFUND, token=capture_txn.token,
+ payment, kind=TransactionKind.REFUND, token=capture_txn.token,
amount=amount)
gateway_response = extract_gateway_response(result)
@@ -255,7 +255,7 @@ def refund(
txn = create_transaction(
payment=payment,
parent=capture_txn,
- kind=Transactions.REFUND,
+ kind=TransactionKind.REFUND,
amount=gateway_response.pop('amount', amount),
currency=gateway_response.pop('currency', payment.currency),
token=getattr(result.transaction, 'id', ''),
diff --git a/saleor/payment/gateways/dummy/__init__.py b/saleor/payment/gateways/dummy/__init__.py
index 0cc7d57f09..fffc71eeee 100644
--- a/saleor/payment/gateways/dummy/__init__.py
+++ b/saleor/payment/gateways/dummy/__init__.py
@@ -5,7 +5,7 @@ from typing import Dict
from django.conf import settings
from prices import Money
-from ... import Transactions
+from ... import TransactionKind
from ...models import Payment
from ...utils import create_transaction
@@ -25,7 +25,7 @@ def authorize(payment: Payment, payment_token: str, **connection_params):
error = 'Unable to authorize transaction'
txn = create_transaction(
payment=payment,
- kind=Transactions.AUTH,
+ kind=TransactionKind.AUTH,
amount=payment.total,
currency=payment.currency,
gateway_response={},
@@ -41,7 +41,7 @@ def void(payment: Payment, **connection_params: Dict):
error = 'Unable to void transaction'
txn = create_transaction(
payment=payment,
- kind=Transactions.VOID,
+ kind=TransactionKind.VOID,
amount=payment.total,
currency=payment.currency,
gateway_response={},
@@ -57,7 +57,7 @@ def capture(payment: Payment, amount: Decimal):
error = 'Unable to process capture'
txn = create_transaction(
payment=payment,
- kind=Transactions.CAPTURE,
+ kind=TransactionKind.CAPTURE,
amount=amount,
currency=payment.currency,
token=str(uuid.uuid4()),
@@ -72,7 +72,7 @@ def refund(payment: Payment, amount: Decimal):
error = 'Unable to process refund'
txn = create_transaction(
payment=payment,
- kind=Transactions.REFUND,
+ kind=TransactionKind.REFUND,
amount=amount,
currency=payment.currency,
token=str(uuid.uuid4()),
diff --git a/saleor/payment/migrations/0002_transfer_payment_to_payment_method.py b/saleor/payment/migrations/0002_transfer_payment_to_payment_method.py
index b343cec6f7..15698601cf 100644
--- a/saleor/payment/migrations/0002_transfer_payment_to_payment_method.py
+++ b/saleor/payment/migrations/0002_transfer_payment_to_payment_method.py
@@ -3,7 +3,7 @@ from django.db import migrations
from prices import Money
from django.conf import settings
-from .. import ChargeStatus, Transactions
+from .. import ChargeStatus, TransactionKind
from ..models import Transaction
class PaymentStatus:
@@ -39,12 +39,13 @@ def get_is_active(status, payment):
return True
-def create_transaction(method, kind, created, amount, is_success):
+def create_transaction(method, kind, created, amount, is_success, currency):
return method.transactions.create(
created=created,
kind=kind,
is_success=is_success,
amount=amount,
+ currency=currency,
gateway_response={})
@@ -56,27 +57,27 @@ def create_transactions(method, payment):
# Other payments needed to be authorized first
created = payment.created
create_transaction(
- method=method, kind=Transactions.AUTH,
+ method=method, kind=TransactionKind.AUTH,
created=created, amount=payment.total, currency=payment.currency,
is_success=True, token=payment.transaction_id)
# This kind of payment needs an unsuccessful capture transaction
if payment.status in [PaymentStatus.ERROR, PaymentStatus.REJECTED]:
create_transaction(
- method=method, kind=Transactions.CAPTURE,
+ method=method, kind=TransactionKind.CAPTURE,
created=created, amount=payment.total, currency=payment.currency,
is_success=False, token=payment.transaction_id)
return
# Two other payments left - CONFIRMED and REFUNDED needs to be captured
create_transaction(
- method=method, kind=Transactions.CAPTURE,
+ method=method, kind=TransactionKind.CAPTURE,
created=created, amount=payment.total, currency=payment.currency,
is_success=True, token=payment.transaction_id)
# If payment was refunded, we need to create a refund transaction for it
if payment.status == PaymentStatus.REFUNDED:
create_transaction(
- method=method, kind=Transactions.REFUND,
+ method=method, kind=TransactionKind.REFUND,
created=created, amount=payment.total, currency=payment.currency,
is_success=True, token=payment.transaction_id)
diff --git a/saleor/payment/models.py b/saleor/payment/models.py
index 53255cd1e1..69b2459e9e 100644
--- a/saleor/payment/models.py
+++ b/saleor/payment/models.py
@@ -9,7 +9,7 @@ from django_prices.models import MoneyField
from prices import Money
from . import (
- ChargeStatus, CustomPaymentChoices, TransactionError, Transactions)
+ ChargeStatus, CustomPaymentChoices, TransactionError, TransactionKind)
from ..checkout.models import Cart
from ..core.utils.taxes import zero_money
from ..order.models import Order
@@ -140,14 +140,14 @@ class Payment(models.Model):
class Transaction(models.Model):
- """Transactions represent attempts to transfer money between your store
+ """Transaction represent attempts to transfer money between your store
and your customers, with a chosen payment method.
"""
created = models.DateTimeField(auto_now_add=True, editable=False)
payment = models.ForeignKey(
Payment, related_name='transactions', on_delete=models.PROTECT)
token = models.CharField(max_length=64, blank=True, default='')
- kind = models.CharField(max_length=10, choices=Transactions.CHOICES)
+ kind = models.CharField(max_length=10, choices=TransactionKind.CHOICES)
# FIXME probably we should have error/pending/success status instead of
# a bool, eg for payments with 3d secure
is_success = models.BooleanField(default=False)
diff --git a/saleor/payment/utils.py b/saleor/payment/utils.py
index e5c97423b6..c28c885ff2 100644
--- a/saleor/payment/utils.py
+++ b/saleor/payment/utils.py
@@ -93,6 +93,36 @@ 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):
+ if amount <= 0:
+ raise PaymentError('Amount should be a positive number.')
+ if not payment.can_capture():
+ raise PaymentError('This payment cannot be captured.')
+ if amount > payment.total or amount > (
+ payment.total - payment.captured_amount):
+ raise PaymentError('Unable to capture more than authorized amount.')
+
+def clean_authorize(payment: Payment):
+ if not payment.can_authorize():
+ raise PaymentError('Charged transactions cannot be authorized again.')
+
+
+@validate_payment
+def gateway_charge(
+ payment: Payment,
+ payment_token: str,
+ amount: Decimal) -> Transaction:
+ clean_authorize(payment)
+ clean_capture(payment, amount)
+
+ gateway, gateway_params = get_payment_gateway(payment.gateway)
+ with transaction.atomic():
+ txn, error = gateway.charge(
+ payment, payment_token, **gateway_params)
+ if not txn.is_success:
+ raise PaymentError(error)
+ return txn
+
@validate_payment
def gateway_authorize(payment: Payment, payment_token: str) -> Transaction:
@@ -101,8 +131,7 @@ def gateway_authorize(payment: Payment, payment_token: str) -> Transaction:
Args:
- payment_token: One-time-use reference to payment information.
"""
- if not payment.can_authorize():
- raise PaymentError('Charged transactions cannot be authorized again.')
+ clean_authorize(payment)
gateway, gateway_params = get_payment_gateway(payment.gateway)
with transaction.atomic():
@@ -116,13 +145,7 @@ def gateway_authorize(payment: Payment, payment_token: str) -> Transaction:
@validate_payment
def gateway_capture(payment: Payment, amount: Decimal) -> Transaction:
- if amount <= 0:
- raise PaymentError('Amount should be a positive number.')
- if not payment.can_capture():
- raise PaymentError('This payment cannot be captured.')
- if amount > payment.total or amount > (
- payment.total - payment.captured_amount):
- raise PaymentError('Unable to capture more than authorized amount.')
+ clean_capture(payment, amount)
gateway, gateway_params = get_payment_gateway(payment.gateway)
with transaction.atomic():
diff --git a/tests/api/test_checkout.py b/tests/api/test_checkout.py
index d02d454944..58dc3738c6 100644
--- a/tests/api/test_checkout.py
+++ b/tests/api/test_checkout.py
@@ -7,7 +7,7 @@ from tests.api.utils import get_graphql_content
from saleor.checkout.models import Cart
from saleor.order.models import Order
-from saleor.payment import Transactions
+from saleor.payment import TransactionKind
def test_checkout_create(user_api_client, variant, graphql_address_data):
diff --git a/tests/api/test_payment.py b/tests/api/test_payment.py
index c7e0b16f78..c97d61f1a2 100644
--- a/tests/api/test_payment.py
+++ b/tests/api/test_payment.py
@@ -2,7 +2,7 @@ import graphene
from tests.api.utils import get_graphql_content
from saleor.payment.models import (
- ChargeStatus, Payment, Transaction, Transactions)
+ ChargeStatus, Payment, Transaction, TransactionKind)
from saleor.graphql.payment.types import (
PaymentChargeStatusEnum, PaymentGatewayEnum, OrderAction)
from saleor.core.utils import get_country_name_by_code
@@ -38,7 +38,7 @@ def test_payment_void_success(
assert payment_dummy.is_active == False
assert payment_dummy.transactions.count() == 1
txn = payment_dummy.transactions.first()
- assert txn.kind == Transactions.VOID
+ assert txn.kind == TransactionKind.VOID
def test_payment_charge_gateway_error(
@@ -63,7 +63,7 @@ def test_payment_charge_gateway_error(
assert payment_dummy.is_active == True
assert payment_dummy.transactions.count() == 1
txn = payment_dummy.transactions.first()
- assert txn.kind == Transactions.VOID
+ assert txn.kind == TransactionKind.VOID
assert not txn.is_success
@@ -151,7 +151,7 @@ def test_payment_charge_success(
assert payment.charge_status == ChargeStatus.CHARGED
assert payment.transactions.count() == 1
txn = payment.transactions.first()
- assert txn.kind == Transactions.CHARGE
+ assert txn.kind == TransactionKind.CHARGE
def test_payment_charge_gateway_error(
@@ -178,7 +178,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 == Transactions.CHARGE
+ assert txn.kind == TransactionKind.CHARGE
assert not txn.is_success
@@ -219,7 +219,7 @@ def test_payment_refund_success(
assert payment.charge_status == ChargeStatus.FULLY_REFUNDED
assert payment.transactions.count() == 1
txn = payment.transactions.first()
- assert txn.kind == Transactions.REFUND
+ assert txn.kind == TransactionKind.REFUND
def test_payment_refund_error(
@@ -248,7 +248,7 @@ def test_payment_refund_error(
assert payment.charge_status == ChargeStatus.CHARGED
assert payment.transactions.count() == 1
txn = payment.transactions.first()
- assert txn.kind == Transactions.REFUND
+ assert txn.kind == TransactionKind.REFUND
assert not txn.is_success
diff --git a/tests/conftest.py b/tests/conftest.py
index 7319d9fa7e..c151d18457 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -28,7 +28,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 import ChargeStatus, Transactions
+from saleor.payment import ChargeStatus, TransactionKind
from saleor.payment.models import Payment
from saleor.product.models import (
Attribute, AttributeTranslation, AttributeValue, Category, Collection,
@@ -476,7 +476,7 @@ def payment_txn_preauth(order_with_lines, payment_dummy):
payment.transactions.create(
amount=payment.total,
- kind=Transactions.AUTH,
+ kind=TransactionKind.AUTH,
gateway_response={},
is_success=True)
return payment
@@ -493,7 +493,7 @@ def payment_txn_captured(order_with_lines, payment_dummy):
payment.transactions.create(
amount=payment.total,
- kind=Transactions.CAPTURE,
+ kind=TransactionKind.CAPTURE,
gateway_response={},
is_success=True)
return payment
@@ -510,7 +510,7 @@ def payment_txn_refunded(order_with_lines, payment_dummy):
payment.transactions.create(
amount=payment.total,
- kind=Transactions.REFUND,
+ kind=TransactionKind.REFUND,
gateway_response={},
is_success=True)
return payment
diff --git a/tests/dashboard/test_order.py b/tests/dashboard/test_order.py
index 27f4cd01d2..0f7a5ca8a7 100644
--- a/tests/dashboard/test_order.py
+++ b/tests/dashboard/test_order.py
@@ -18,7 +18,7 @@ from saleor.order import (
FulfillmentStatus, OrderEvents, OrderEventsEmails, OrderStatus)
from saleor.order.models import Order, OrderEvent, OrderLine
from saleor.order.utils import add_variant_to_order, change_order_line_quantity
-from saleor.payment import ChargeStatus, Transactions
+from saleor.payment import ChargeStatus, TransactionKind
from saleor.product.models import ProductVariant
from saleor.shipping.models import ShippingZone
@@ -211,7 +211,7 @@ def test_view_void_order_payment_preauth(
assert order_payment.charge_status == ChargeStatus.NOT_CHARGED
last_transaction = order_payment.transactions.latest('pk')
- assert last_transaction.kind == Transactions.VOID
+ assert last_transaction.kind == TransactionKind.VOID
assert order_payment.captured_amount == Decimal('0.00')
diff --git a/tests/gateway/test_braintree.py b/tests/gateway/test_braintree.py
index 52ca6fdac4..dbcd94921c 100644
--- a/tests/gateway/test_braintree.py
+++ b/tests/gateway/test_braintree.py
@@ -10,7 +10,7 @@ from braintree.validation_error import ValidationError
from django.core.exceptions import ImproperlyConfigured
from prices import Money
-from saleor.payment import Transactions
+from saleor.payment import TransactionKind
from saleor.payment.gateways.braintree import (
CONFIRM_MANUALLY, THREE_D_SECURE_REQUIRED, authorize, capture,
extract_gateway_response, get_client_token, get_customer_data,
@@ -232,7 +232,7 @@ def test_authorize_incorrect_token(
result = authorize(payment, payment_token)
assert result == expected_result
mock_transaction.assert_called_once_with(
- payment, type=Transactions.AUTH, token=payment_token)
+ payment, kind=TransactionKind.AUTH, token=payment_token)
@pytest.mark.integration
@@ -247,7 +247,7 @@ def test_authorize(
assert not error
assert txn.payment == payment
- assert txn.kind == Transactions.AUTH
+ assert txn.kind == TransactionKind.AUTH
assert txn.amount == braintree_success_response.transaction.amount
assert txn.currency == braintree_success_response.transaction.currency_iso_code
assert txn.gateway_response == success_gateway_response(
@@ -278,7 +278,7 @@ def test_refund(
assert not error
assert txn.payment == payment
- assert txn.kind == Transactions.REFUND
+ assert txn.kind == TransactionKind.REFUND
assert txn.amount == braintree_success_response.transaction.amount
assert txn.currency == braintree_success_response.transaction.currency_iso_code
assert txn.gateway_response == success_gateway_response(
@@ -287,7 +287,7 @@ def test_refund(
assert txn.is_success == braintree_success_response.is_success
capture_txn = payment.transactions.filter(
- kind=Transactions.CAPTURE).first()
+ kind=TransactionKind.CAPTURE).first()
mock_response.assert_called_once_with(
amount_or_options=str(amount), transaction_id=capture_txn.token)
@@ -307,9 +307,9 @@ def test_refund_incorrect_token(
result = refund(payment, amount)
assert result == expected_result
capture_txn = payment.transactions.filter(
- kind=Transactions.CAPTURE).first()
+ kind=TransactionKind.CAPTURE).first()
mock_transaction.assert_called_once_with(
- payment, type=Transactions.REFUND, token=capture_txn.token,
+ payment, kind=TransactionKind.REFUND, token=capture_txn.token,
amount=amount)
@@ -346,7 +346,7 @@ def test_capture(
assert not error
assert txn.payment == payment
- assert txn.kind == Transactions.CAPTURE
+ assert txn.kind == TransactionKind.CAPTURE
assert txn.amount == braintree_success_response.transaction.amount
assert txn.currency == braintree_success_response.transaction.currency_iso_code
assert txn.gateway_response == success_gateway_response(
@@ -355,7 +355,7 @@ def test_capture(
assert txn.is_success == braintree_success_response.is_success
auth_txn = payment.transactions.filter(
- kind=Transactions.AUTH).first()
+ kind=TransactionKind.AUTH).first()
mock_response.assert_called_once_with(
amount=str(amount), transaction_id=auth_txn.token)
@@ -377,9 +377,9 @@ def test_capture_incorrect_token(
result = capture(payment, amount)
assert result == expected_result
auth_txn = payment.transactions.filter(
- kind=Transactions.AUTH).first()
+ kind=TransactionKind.AUTH).first()
mock_transaction.assert_called_once_with(
- payment, type=Transactions.CAPTURE, token=auth_txn.token,
+ payment, kind=TransactionKind.CAPTURE, token=auth_txn.token,
amount=amount)
@@ -414,7 +414,7 @@ def test_void(
assert not error
assert txn.payment == payment
- assert txn.kind == Transactions.VOID
+ assert txn.kind == TransactionKind.VOID
assert txn.amount == braintree_success_response.transaction.amount
assert txn.currency == braintree_success_response.transaction.currency_iso_code
assert txn.gateway_response == success_gateway_response(
@@ -423,7 +423,7 @@ def test_void(
assert txn.is_success == braintree_success_response.is_success
auth_txn = payment.transactions.filter(
- kind=Transactions.AUTH).first()
+ kind=TransactionKind.AUTH).first()
mock_response.assert_called_once_with(transaction_id=auth_txn.token)
@@ -441,9 +441,9 @@ def test_void_incorrect_token(
result = void(payment)
assert result == expected_result
auth_txn = payment.transactions.filter(
- kind=Transactions.AUTH).first()
+ kind=TransactionKind.AUTH).first()
mock_transaction.assert_called_once_with(
- payment, type=Transactions.VOID, token=auth_txn.token)
+ payment, kind=TransactionKind.VOID, token=auth_txn.token)
@pytest.mark.integration
@@ -466,10 +466,10 @@ def test_void_error_response(
def test_transaction_and_incorrect_token_error_helper(payment_dummy, settings):
amount = Decimal('10.00')
txn, error = transaction_and_incorrect_token_error(
- payment_dummy, 'example-token', Transactions.AUTH, amount=amount)
+ payment_dummy, 'example-token', TransactionKind.AUTH, amount=amount)
assert error == INCORRECT_TOKEN_ERROR
assert not txn.is_success
- assert txn.kind == Transactions.AUTH
+ assert txn.kind == TransactionKind.AUTH
assert txn.token == 'example-token'
assert not txn.gateway_response
assert txn.amount == amount
@@ -478,5 +478,5 @@ def test_transaction_and_incorrect_token_error_helper(payment_dummy, settings):
def test_transaction_and_incorrect_token_error_helper_no_amount(payment_dummy):
txn, error = transaction_and_incorrect_token_error(
- payment_dummy, 'example-token', Transactions.AUTH)
+ payment_dummy, 'example-token', TransactionKind.AUTH)
assert txn.amount == payment_dummy.total
diff --git a/tests/gateway/test_dummy.py b/tests/gateway/test_dummy.py
index 2f78a463ae..2ee181e42f 100644
--- a/tests/gateway/test_dummy.py
+++ b/tests/gateway/test_dummy.py
@@ -2,13 +2,13 @@ from decimal import Decimal
import pytest
-from saleor.payment import ChargeStatus, PaymentError, Transactions
+from saleor.payment import ChargeStatus, PaymentError, TransactionKind
def test_authorize(payment_dummy):
txn = payment_dummy.authorize(payment_token='Fake')
assert txn.is_success
- assert txn.kind == Transactions.AUTH
+ assert txn.kind == TransactionKind.AUTH
assert txn.payment == payment_dummy
payment_dummy.refresh_from_db()
assert payment_dummy.is_active
@@ -19,7 +19,7 @@ def test_authorize_gateway_error(payment_dummy, monkeypatch):
'saleor.payment.gateways.dummy.dummy_success', lambda: False)
with pytest.raises(PaymentError):
txn = payment_dummy.authorize(payment_token='Fake')
- assert txn.kind == Transactions.AUTH
+ assert txn.kind == TransactionKind.AUTH
assert not txn.is_success
assert txn.payment == payment_dummy
@@ -29,7 +29,7 @@ def test_void_success(payment_dummy):
assert payment_dummy.charge_status == ChargeStatus.NOT_CHARGED
txn = payment_dummy.void()
assert txn.is_success
- assert txn.kind == Transactions.VOID
+ assert txn.kind == TransactionKind.VOID
assert txn.payment == payment_dummy
payment_dummy.refresh_from_db()
assert not payment_dummy.is_active
@@ -57,7 +57,7 @@ def test_void_gateway_error(payment_dummy, monkeypatch):
'saleor.payment.gateways.dummy.dummy_success', lambda: False)
with pytest.raises(PaymentError):
txn = payment_dummy.void()
- assert txn.kind == Transactions.VOID
+ assert txn.kind == TransactionKind.VOID
assert not txn.is_success
assert txn.payment == payment_dummy
@@ -96,7 +96,7 @@ def test_charge_gateway_error(payment_dummy, monkeypatch):
'saleor.payment.gateways.dummy.dummy_success', lambda: False)
with pytest.raises(PaymentError):
txn = payment_dummy.capture(80)
- assert txn.kind == Transactions.CHARGE
+ assert txn.kind == TransactionKind.CHARGE
assert not txn.is_success
assert txn.payment == payment_dummy
@@ -114,7 +114,7 @@ def test_refund_success(
payment.captured_amount = initial_captured_amount
payment.save()
txn = payment.refund(refund_amount)
- assert txn.kind == Transactions.REFUND
+ assert txn.kind == TransactionKind.REFUND
assert txn.is_success
assert txn.payment == payment
assert payment.charge_status == final_charge_status
@@ -151,7 +151,7 @@ def test_refund_gateway_error(payment_dummy, monkeypatch):
payment.refresh_from_db()
txn = payment.transactions.first()
- assert txn.kind == Transactions.REFUND
+ assert txn.kind == TransactionKind.REFUND
assert not txn.is_success
assert txn.payment == payment
assert payment.charge_status == ChargeStatus.CHARGED
diff --git a/tests/test_payment.py b/tests/test_payment.py
index 876fb56c6f..8c85f951bf 100644
--- a/tests/test_payment.py
+++ b/tests/test_payment.py
@@ -4,12 +4,15 @@ from unittest.mock import Mock, patch
import pytest
from django.conf import settings
from django.core.exceptions import ImproperlyConfigured
+from django.template.loader import get_template
from prices import Money
from saleor.order import OrderEvents, OrderEventsEmails
from saleor.order.views import PAYMENT_TEMPLATE
from saleor.payment import (
- ChargeStatus, PaymentError, Transactions, get_payment_gateway)
+ 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,
@@ -24,7 +27,7 @@ def transaction_data(payment_dummy, settings):
return {
'payment': payment_dummy,
'token': 'token',
- 'kind': Transactions.CAPTURE,
+ 'kind': TransactionKind.CAPTURE,
'is_success': True,
'amount': Decimal('10.00'),
'currency': settings.DEFAULT_CURRENCY,
@@ -433,9 +436,73 @@ def test_gateway_refund_errors(payment_txn_captured):
@pytest.mark.parametrize('gateway_name', settings.PAYMENT_GATEWAYS.keys())
-def test_payment_provider_templates_exists(gateway_name):
- """Test if for each payment provider there's a corresponding
+def test_payment_gateway_templates_exists(gateway_name):
+ """Test if for each payment gateway there's a corresponding
template for the old checkout.
"""
template = PAYMENT_TEMPLATE % gateway_name
- django.template.loader.get_template(template)
+ 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)
+
+
[email protected]('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
+ form for the old checkout.
+
+ 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