Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Improve cart code and fix checkout tests
Patryk Zawadzkie514a2248e66
diff --git a/saleor/cart/__init__.py b/saleor/cart/__init__.pyindex 04d604073e..faef746e0b 100644--- a/saleor/cart/__init__.py+++ b/saleor/cart/__init__.py@@ -8,6 +8,8 @@ logger = logging.getLogger(__name__)class CartStatus:+ """Enum of possible cart statuses."""+OPEN = 'open'SAVED = 'saved'WAITING_FOR_PAYMENT = 'payment'diff --git a/saleor/cart/context_processors.py b/saleor/cart/context_processors.pyindex 039da03046..81eedbab4c 100644--- a/saleor/cart/context_processors.py+++ b/saleor/cart/context_processors.py@@ -1,8 +1,9 @@+"""Cart-related context processors."""from __future__ import unicode_literalsfrom .utils import get_cart_from_requestdef cart_counter(request):- """ Return number of items from cart """+ """Expose the number of items in cart."""cart = get_cart_from_request(request)return {'cart_counter': cart.quantity}diff --git a/saleor/cart/forms.py b/saleor/cart/forms.pyindex f8b7636639..d51db0580a 100644--- a/saleor/cart/forms.py+++ b/saleor/cart/forms.py@@ -1,3 +1,4 @@+"""Cart-related forms and fields."""from __future__ import unicode_literalsfrom django import forms@@ -10,6 +11,7 @@ from ..shipping.utils import get_shipment_optionsclass QuantityField(forms.IntegerField):+ """A specialized integer field with initial quantity and min/max values."""def __init__(self, **kwargs):super(QuantityField, self).__init__(@@ -18,31 +20,29 @@ class QuantityField(forms.IntegerField):class AddToCartForm(forms.Form):- """Add-to-cart form+ """Add-to-cart form.Allows selection of a product variant and quantity.+The save method adds it to the cart."""- quantity = QuantityField(label=pgettext_lazy('Add to cart form field label', 'Quantity'))++ quantity = QuantityField(+ label=pgettext_lazy('Add to cart form field label', 'Quantity'))error_messages = {'not-available': pgettext_lazy('Add to cart form error',- 'Sorry. This product is currently not available.'- ),+ 'Sorry. This product is currently not available.'),'empty-stock': pgettext_lazy('Add to cart form error',- 'Sorry. This product is currently out of stock.'- ),+ 'Sorry. This product is currently out of stock.'),'variant-does-not-exists': pgettext_lazy('Add to cart form error',- 'Oops. We could not find that product.'- ),+ 'Oops. We could not find that product.'),'insufficient-stock': npgettext_lazy('Add to cart form error','Only %d remaining in stock.',- 'Only %d remaining in stock.'- )- }+ 'Only %d remaining in stock.')}def __init__(self, *args, **kwargs):self.cart = kwargs.pop('cart')@@ -51,6 +51,11 @@ class AddToCartForm(forms.Form):super(AddToCartForm, self).__init__(*args, **kwargs)def clean(self):+ """Clean the form.++ Makes sure the total quantity in cart (taking into account what was+ already there) does not exceed available quantity.+ """cleaned_data = super(AddToCartForm, self).clean()quantity = cleaned_data.get('quantity')if quantity is None:@@ -77,20 +82,27 @@ class AddToCartForm(forms.Form):return cleaned_datadef save(self):- """Adds the selected product variant and quantity to the cart"""+ """Add the selected product variant and quantity to the cart."""product_variant = self.get_variant(self.cleaned_data)return self.cart.add(variant=product_variant,quantity=self.cleaned_data['quantity'])def get_variant(self, cleaned_data):+ """Return a product variant that matches submitted values.++ This allows specialized implementations to select the variant based on+ multiple fields (like size and color) instead of having a single+ variant selection widget.+ """raise NotImplementedError()class ReplaceCartLineForm(AddToCartForm):- """Replace quantity form+ """Replace quantity in cart form.Similar to AddToCartForm but its save method replaces the quantity."""+def __init__(self, *args, **kwargs):self.variant = kwargs.pop('variant')kwargs['product'] = self.variant.product@@ -100,6 +112,11 @@ class ReplaceCartLineForm(AddToCartForm):'min': 1, 'max': settings.MAX_CART_LINE_QUANTITY}def clean_quantity(self):+ """Clean the quantity field.++ Checks if target quantity does not exceed the currently available+ quantity.+ """quantity = self.cleaned_data['quantity']try:self.variant.check_quantity(quantity)@@ -109,26 +126,34 @@ class ReplaceCartLineForm(AddToCartForm):return quantitydef clean(self):+ """Clean the form skipping the add-to-form checks."""# explicitly skip parent's implementation# pylint: disable=E1003return super(AddToCartForm, self).clean()def get_variant(self, cleaned_data):+ """Return the matching variant.++ In this case we explicitly know the variant as we're modifying an+ existing line in cart.+ """return self.variantdef save(self):- """Replaces the selected product's quantity in cart"""+ """Replace the selected product's quantity in cart."""product_variant = self.get_variant(self.cleaned_data)return self.cart.add(product_variant, self.cleaned_data['quantity'],replace=True)class CountryForm(forms.Form):+ """Country selection form."""country = LazyTypedChoiceField(label=pgettext_lazy('Country form field label', 'Country'),choices=countries)def get_shipment_options(self):+ """Return a list of shipping methods for the selected country."""code = self.cleaned_data['country']return get_shipment_options(code)diff --git a/saleor/cart/models.py b/saleor/cart/models.pyindex ea8c6d37af..c205bf5e2b 100644--- a/saleor/cart/models.py+++ b/saleor/cart/models.py@@ -1,8 +1,8 @@+"""Cart-related ORM models."""from __future__ import unicode_literalsfrom collections import namedtuplefrom decimal import Decimal-from prices import Pricefrom uuid import uuid4from django.conf import settings@@ -13,41 +13,66 @@ from django.utils.timezone import nowfrom django.utils.translation import pgettext_lazyfrom django_prices.models import PriceFieldfrom jsonfield import JSONField+from prices import Pricefrom satchless.item import ItemLine, ItemList, partitionfrom . import CartStatus, logger-CENTS = Decimal('0.01')SimpleCart = namedtuple('SimpleCart', ('quantity', 'total', 'token'))+def find_open_cart_for_user(user):+ """Find an open cart for the given user."""+ carts = user.carts.open()+ if len(carts) > 1:+ logger.warning('%s has more than one open basket', user)+ for cart in carts[1:]:+ cart.change_status(CartStatus.CANCELED)+ return carts.first()++class ProductGroup(ItemList):+ """A group of products."""+def is_shipping_required(self):+ """Return `True` if any product in group requires shipping."""return any(p.is_shipping_required() for p in self)class CartQueryset(models.QuerySet):+ """A specialized queryset for dealing with carts."""def anonymous(self):+ """Return unassigned carts."""return self.filter(user=None)def open(self):+ """Return `OPEN` carts."""return self.filter(status=CartStatus.OPEN)def saved(self):+ """Return `SAVED` carts."""return self.filter(status=CartStatus.SAVED)def waiting_for_payment(self):+ """Return `SAVED_FOR_PAYMENT` carts."""return self.filter(status=CartStatus.WAITING_FOR_PAYMENT)def checkout(self):+ """Return carts in `CHECKOUT` state."""return self.filter(status=CartStatus.CHECKOUT)def canceled(self):+ """Return `CANCELED` carts."""return self.filter(status=CartStatus.CANCELED)def for_display(self):+ """Annotate the queryset for display purposes.++ Prefetches additional data from the database to avoid the n+1 queries+ problem.+ """return self.prefetch_related('lines__variant__product__categories','lines__variant__product__images',@@ -57,6 +82,8 @@ class CartQueryset(models.QuerySet):class Cart(models.Model):+ """A shopping cart."""+status = models.CharField(pgettext_lazy('Cart field', 'order status'),max_length=32, choices=CartStatus.CHOICES, default=CartStatus.OPEN)@@ -79,7 +106,6 @@ class Cart(models.Model):checkout_data = JSONField(verbose_name=pgettext_lazy('Cart field', 'checkout data'), null=True,editable=False,)-total = PriceField(pgettext_lazy('Cart field', 'total'),currency=settings.DEFAULT_CURRENCY, max_digits=12, decimal_places=2,@@ -99,6 +125,7 @@ class Cart(models.Model):super(Cart, self).__init__(*args, **kwargs)def update_quantity(self):+ """Recalculate cart quantity based on lines."""total_lines = self.count()['total_quantity']if not total_lines:total_lines = 0@@ -106,6 +133,8 @@ class Cart(models.Model):self.save(update_fields=['quantity'])def change_status(self, status):+ """Change cart status."""+ # FIXME: investigate replacing with django-fsm transitionsif status not in dict(CartStatus.CHOICES):raise ValueError('Not expected status')if status != self.status:@@ -114,22 +143,18 @@ class Cart(models.Model):self.save()def change_user(self, user):- open_cart = Cart.get_user_open_cart(user)+ """Assign cart to a user.++ If the user already has an open cart assigned, cancel it.+ """+ open_cart = find_open_cart_for_user(user)if open_cart is not None:open_cart.change_status(status=CartStatus.CANCELED)self.user = userself.save(update_fields=['user'])- @staticmethod- def get_user_open_cart(user):- carts = user.carts.open()- if len(carts) > 1:- logger.warning('%s has more than one open basket', user)- for cart in carts[1:]:- cart.change_status(CartStatus.CANCELED)- return carts.first()-def is_shipping_required(self):+ """Return `True` if any of the lines requires shipping."""return any(line.is_shipping_required() for line in self.lines.all())def __repr__(self):@@ -138,30 +163,40 @@ class Cart(models.Model):def __len__(self):return self.lines.count()+ # pylint: disable=R0201def get_subtotal(self, item, **kwargs):+ """Return the cost of a cart line."""return item.get_total(**kwargs)def get_total(self, **kwargs):- subtotals = [self.get_subtotal(item, **kwargs)- for item in self.lines.all()]+ """Return the total cost of the cart prior to shipping."""+ subtotals = [+ self.get_subtotal(item, **kwargs) for item in self.lines.all()]if not subtotals:raise AttributeError('Calling get_total() on an empty item set')zero = Price(0, currency=settings.DEFAULT_CURRENCY)return sum(subtotals, zero)def count(self):+ """Return the total quantity in cart."""lines = self.lines.all()return lines.aggregate(total_quantity=models.Sum('quantity'))def clear(self):+ """Remove the cart."""self.delete()def create_line(self, variant, quantity, data):- line = self.lines.create(variant=variant, quantity=quantity,- data=data or {})- return line+ """Create a cart line for given variant, quantity and optional data.++ The `data` parameter may be used to differentiate between items with+ different customization options.+ """+ return self.lines.create(+ variant=variant, quantity=quantity, data=data or {})def get_line(self, variant, data=None):+ """Return a line matching the given variant and data if any."""all_lines = self.lines.all()if data is None:data = {}@@ -172,7 +207,15 @@ class Cart(models.Model):def add(self, variant, quantity=1, data=None, replace=False,check_quantity=True):- cart_line, created = self.lines.get_or_create(+ """Add a product vartiant to cart.++ The `data` parameter may be used to differentiate between items with+ different customization options.++ If `replace` is truthy then any previous quantity is discarded instead+ of added to.+ """+ cart_line, dummy_created = self.lines.get_or_create(variant=variant, defaults={'quantity': 0, 'data': data or {}})if replace:new_quantity = quantity@@ -195,6 +238,7 @@ class Cart(models.Model):self.update_quantity()def partition(self):+ """Split the card into a list of groups for shipping."""grouper = (lambda p: 'physical' if p.is_shipping_required() else 'digital')return partition(self.lines.all(), grouper, ProductGroup)@@ -202,6 +246,11 @@ class Cart(models.Model):@python_2_unicode_compatibleclass CartLine(models.Model, ItemLine):+ """A single cart line.++ Multiple lines in the same cart can refer to the same product variant if+ their `data` field is different.+ """cart = models.ForeignKey(Cart, related_name='lines',@@ -246,14 +295,19 @@ class CartLine(models.Model, ItemLine):self.variant, self.quantity, self.data = datadef get_total(self, **kwargs):+ """Return the total price of this line."""amount = super(CartLine, self).get_total(**kwargs)return amount.quantize(CENTS)def get_quantity(self, **kwargs):+ """Return the line's quantity."""return self.quantity+ # pylint: disable=W0221def get_price_per_item(self, discounts=None, **kwargs):+ """Return the unit price of the line."""return self.variant.get_price_per_item(discounts=discounts, **kwargs)def is_shipping_required(self):+ """Return `True` if the related product variant requires shipping."""return self.variant.is_shipping_required()diff --git a/saleor/cart/urls.py b/saleor/cart/urls.pyindex bbd6cde209..82173b6513 100644--- a/saleor/cart/urls.py+++ b/saleor/cart/urls.py@@ -8,5 +8,4 @@ urlpatterns = [url(r'^update/(?P<variant_id>\d+)/$', views.update, name='update-line'),url(r'^summary/$', views.summary, name='cart-summary'),url(r'^shipingoptions/$', views.get_shipping_options,- name='shipping-options')-]+ name='shipping-options')]diff --git a/saleor/cart/utils.py b/saleor/cart/utils.pyindex 3d40a0af71..98cce038cb 100644--- a/saleor/cart/utils.py+++ b/saleor/cart/utils.py@@ -1,3 +1,4 @@+"""Cart-related utility functions."""from __future__ import unicode_literalsfrom datetime import timedelta@@ -19,12 +20,15 @@ COOKIE_NAME = 'cart'def set_cart_cookie(simple_cart, response):+ """Update respons with a cart token cookie."""+ # FIXME: document why session is not usedten_years = timedelta(days=(365 * 10))response.set_signed_cookie(COOKIE_NAME, simple_cart.token, max_age=ten_years.total_seconds())def contains_unavailable_variants(cart):+ """Return `True` if cart contains any unfulfillable lines."""try:for line in cart.lines.all():line.variant.check_quantity(line.quantity)@@ -34,6 +38,7 @@ def contains_unavailable_variants(cart):def token_is_valid(token):+ """Validate a cart token."""if token is None:return Falseif isinstance(token, UUID):@@ -46,6 +51,7 @@ def token_is_valid(token):def remove_unavailable_variants(cart):+ """Remove any unavailable items from cart."""for line in cart.lines.all():try:cart.add(line.variant, quantity=line.quantity, replace=True)@@ -55,28 +61,36 @@ def remove_unavailable_variants(cart):def get_product_variants_and_prices(cart, product):- lines = (cart_line for cart_line in cart.lines.all()- if cart_line.variant.product_id == product.id)+ """Get variants and unit prices from cart lines matching the product."""+ lines = (+ cart_line for cart_line in cart.lines.all()+ if cart_line.variant.product_id == product.id)for line in lines:for dummy_i in range(line.quantity):yield line.variant, line.get_price_per_item()-def get_category_variants_and_prices(cart, discounted_category):+def get_category_variants_and_prices(cart, root_category):+ """Get variants and unit prices from cart lines matching the category.++ Product is assumed to be in the the category if it belongs to any of its+ descendant subcategories.+ """products = {cart_line.variant.product for cart_line in cart.lines.all()}- discounted_products = set()+ matching_products = set()for product in products:for category in product.categories.all():is_descendant = category.is_descendant_of(- discounted_category, include_self=True)+ root_category, include_self=True)if is_descendant:- discounted_products.add(product)- for product in discounted_products:+ matching_products.add(product)+ for product in matching_products:for line in get_product_variants_and_prices(cart, product):yield linedef check_product_availability_and_warn(request, cart):+ """Warn if cart contains any lines that cannot be fulfilled."""if contains_unavailable_variants(cart):msg = pgettext_lazy('Cart warning message',@@ -87,9 +101,7 @@ def check_product_availability_and_warn(request, cart):def find_and_assign_anonymous_cart(queryset=Cart.objects.all()):- """Assign cart from cookie to request user- :type request: django.http.HttpRequest- """+ """Assign cart from cookie to request user."""def get_cart(view):@wraps(view)def func(request, *args, **kwargs):@@ -118,59 +130,36 @@ def find_and_assign_anonymous_cart(queryset=Cart.objects.all()):def get_or_create_anonymous_cart_from_token(token, cart_queryset=Cart.objects.all()):- """Returns open anonymous cart with given token or creates new.- :type cart_queryset: saleor.cart.models.CartQueryset- :type token: string- :rtype: Cart- """+ """Return an open unassigned cart with given token or create a new one."""return cart_queryset.open().filter(token=token, user=None).get_or_create(defaults={'user': None})[0]def get_or_create_user_cart(user, cart_queryset=Cart.objects.all()):- """Returns open cart for given user or creates one.- :type cart_queryset: saleor.cart.models.CartQueryset- :type user: User- :rtype: Cart- """+ """Return an open cart for given user or create a new one."""return cart_queryset.open().get_or_create(user=user)[0]def get_anonymous_cart_from_token(token, cart_queryset=Cart.objects.all()):- """Returns open anonymous cart with given token or None if not found.- :rtype: Cart | None- """+ """Return an open unassigned cart with given token if any."""return cart_queryset.open().filter(token=token, user=None).first()def get_user_cart(user, cart_queryset=Cart.objects.all()):- """Returns open cart for given user or None if not found.- :type cart_queryset: saleor.cart.models.CartQueryset- :type user: User- :rtype: Cart | None- """+ """Return an open cart for given user if any."""return cart_queryset.open().filter(user=user).first()def get_or_create_cart_from_request(request, cart_queryset=Cart.objects.all()):- """Get cart from database or create new Cart if not found- :type cart_queryset: saleor.cart.models.CartQueryset- :type request: django.http.HttpRequest- :rtype: Cart- """+ """Fetch cart from database or create a new one based on cookie."""if request.user.is_authenticated:return get_or_create_user_cart(request.user, cart_queryset)- else:- token = request.get_signed_cookie(COOKIE_NAME, default=None)- return get_or_create_anonymous_cart_from_token(token, cart_queryset)+ token = request.get_signed_cookie(COOKIE_NAME, default=None)+ return get_or_create_anonymous_cart_from_token(token, cart_queryset)def get_cart_from_request(request, cart_queryset=Cart.objects.all()):- """Get cart from database or return unsaved Cart- :type cart_queryset: saleor.cart.models.CartQueryset- :type request: django.http.HttpRequest- :rtype: Cart- """+ """Fetch cart from database or return a new instance based on cookie."""discounts = request.discountsif request.user.is_authenticated:cart = get_user_cart(request.user, cart_queryset)@@ -182,14 +171,19 @@ def get_cart_from_request(request, cart_queryset=Cart.objects.all()):if cart is not None:cart.discounts = discountsreturn cart- else:- return Cart(user=user, discounts=discounts)+ return Cart(user=user, discounts=discounts)def get_or_create_db_cart(cart_queryset=Cart.objects.all()):- """Get cart or create if necessary. Example: adding items to cart- :type cart_queryset: saleor.cart.models.CartQueryset+ """Decorate view to always receive a saved cart instance.++ Changes the view signature from `fund(request, ...)` to+ `func(request, cart, ...)`.++ If no matching cart is found, one will be created and a cookie will be set+ for users who are not logged in."""+ # FIXME: behave like middleware and assign cart to request insteaddef get_cart(view):@wraps(view)def func(request, *args, **kwargs):@@ -203,10 +197,14 @@ def get_or_create_db_cart(cart_queryset=Cart.objects.all()):def get_or_empty_db_cart(cart_queryset=Cart.objects.all()):- """Get cart if exists. Prevents creating empty carts in views which not- need it- :type cart_queryset: saleor.cart.models.CartQueryset+ """Decorate view to receive a cart if one exists.++ Changes the view signature from `fund(request, ...)` to+ `func(request, cart, ...)`.++ If no matching cart is found, an unsaved `Cart` instance will be used."""+ # FIXME: behave like middleware and assign cart to request insteaddef get_cart(view):@wraps(view)def func(request, *args, **kwargs):@@ -217,6 +215,7 @@ def get_or_empty_db_cart(cart_queryset=Cart.objects.all()):def get_cart_data(cart, shipping_range, currency, discounts):+ """Return a JSON-serializable representation of the cart."""cart_total = Nonelocal_cart_total = Noneshipping_required = Falsediff --git a/saleor/cart/views.py b/saleor/cart/views.pyindex 6d56c16d47..637f9b4948 100644--- a/saleor/cart/views.py+++ b/saleor/cart/views.py@@ -1,3 +1,4 @@+"""Cart-related views."""from __future__ import unicode_literalsfrom babeldjango.templatetags.babel import currencyfmt@@ -17,6 +18,7 @@ from .utils import (check_product_availability_and_warn, get_or_empty_db_cart,@get_or_empty_db_cart(cart_queryset=Cart.objects.for_display())def index(request, cart):+ """Display cart details."""discounts = request.discountscart_lines = []check_product_availability_and_warn(request, cart)@@ -49,6 +51,7 @@ def index(request, cart):@get_or_empty_db_cart(cart_queryset=Cart.objects.for_display())def get_shipping_options(request, cart):+ """Display shipping options to get a price estimate."""country_form = CountryForm(request.POST or None)if country_form.is_valid():shipments = country_form.get_shipment_options()@@ -66,22 +69,23 @@ def get_shipping_options(request, cart):@get_or_empty_db_cart()def update(request, cart, variant_id):+ """Update the line quantities."""if not request.is_ajax():return redirect('cart:index')variant = get_object_or_404(ProductVariant, pk=variant_id)discounts = request.discountsstatus = None- form = ReplaceCartLineForm(request.POST, cart=cart, variant=variant,- discounts=discounts)+ form = ReplaceCartLineForm(+ request.POST, cart=cart, variant=variant, discounts=discounts)if form.is_valid():form.save()- response = {'variantId': variant_id,- 'subtotal': 0,- 'total': 0,- 'cart': {- 'numItems': cart.quantity,- 'numLines': len(cart)- }}+ response = {+ 'variantId': variant_id,+ 'subtotal': 0,+ 'total': 0,+ 'cart': {+ 'numItems': cart.quantity,+ 'numLines': len(cart)}}updated_line = cart.get_line(form.cart_line.variant)if updated_line:response['subtotal'] = currencyfmt(@@ -90,13 +94,11 @@ def update(request, cart, variant_id):if cart:cart_total = cart.get_total(discounts=discounts)response['total'] = currencyfmt(- cart_total.gross,- cart_total.currency)+ cart_total.gross, cart_total.currency)local_cart_total = to_local_currency(cart_total, request.currency)if local_cart_total:response['localTotal'] = currencyfmt(- local_cart_total.gross,- local_cart_total.currency)+ local_cart_total.gross, local_cart_total.currency)status = 200elif request.POST is not None:response = {'error': form.errors}@@ -106,7 +108,7 @@ def update(request, cart, variant_id):@get_or_empty_db_cart(cart_queryset=Cart.objects.for_display())def summary(request, cart):-+ """Display a cart summary suitable for displaying on all pages."""def prepare_line_data(line):product_class = line.variant.product.product_classattributes = product_class.variant_attributes.all()@@ -122,8 +124,8 @@ def summary(request, cart):'price_per_item': currencyfmt(price_per_item.gross, price_per_item.currency),'line_total': currencyfmt(line_total.gross, line_total.currency),- 'update_url': reverse('cart:update-line',- kwargs={'variant_id': line.variant_id}),+ 'update_url': reverse(+ 'cart:update-line', kwargs={'variant_id': line.variant_id}),'variant_url': line.variant.get_absolute_url()}if cart.quantity == 0:data = {'quantity': 0}diff --git a/saleor/discount/models.py b/saleor/discount/models.pyindex e64beebd55..ae052b9417 100644--- a/saleor/discount/models.py+++ b/saleor/discount/models.py@@ -17,7 +17,15 @@ from ..cart.utils import (class NotApplicable(ValueError):- pass+ """Exception raised when a discount is not applicable to a checkout.++ If the error is raised because the order value is too low the minimum+ price limit will be available as the `limit` attribute.+ """++ def __init__(self, msg, limit=None):+ super(NotApplicable, self).__init__(msg)+ self.limit = limitclass VoucherQueryset(models.QuerySet):@@ -47,30 +55,38 @@ class Voucher(models.Model):APPLY_TO_ONE_PRODUCT = 'one'APPLY_TO_ALL_PRODUCTS = 'all'- APPLY_TO_PRODUCT_CHOICES = (- (APPLY_TO_ONE_PRODUCT,- pgettext_lazy('Voucher application', 'Apply to a single item')),- (APPLY_TO_ALL_PRODUCTS,- pgettext_lazy('Voucher application', 'Apply to all matching products')))+ APPLY_TO_PRODUCT_CHOICES = [+ (+ APPLY_TO_ONE_PRODUCT,+ pgettext_lazy('Voucher application', 'Apply to a single item')),+ (+ APPLY_TO_ALL_PRODUCTS,+ pgettext_lazy(+ 'Voucher application', 'Apply to all matching products'))]DISCOUNT_VALUE_FIXED = 'fixed'DISCOUNT_VALUE_PERCENTAGE = 'percentage'- DISCOUNT_VALUE_TYPE_CHOICES = (- (DISCOUNT_VALUE_FIXED,- pgettext_lazy('Voucher discount type', settings.DEFAULT_CURRENCY)),- (DISCOUNT_VALUE_PERCENTAGE, pgettext_lazy('Voucher discount type', '%')))+ DISCOUNT_VALUE_TYPE_CHOICES = [+ (+ DISCOUNT_VALUE_FIXED,+ pgettext_lazy('Voucher discount type', settings.DEFAULT_CURRENCY)),+ (+ DISCOUNT_VALUE_PERCENTAGE,+ pgettext_lazy('Voucher discount type', '%'))]PRODUCT_TYPE = 'product'CATEGORY_TYPE = 'category'SHIPPING_TYPE = 'shipping'VALUE_TYPE = 'value'- TYPE_CHOICES = (+ TYPE_CHOICES = [(VALUE_TYPE, pgettext_lazy('Voucher: discount for', 'All purchases')),(PRODUCT_TYPE, pgettext_lazy('Voucher: discount for', 'One product')),- (CATEGORY_TYPE, pgettext_lazy('Voucher: discount for', 'A category of products')),- (SHIPPING_TYPE, pgettext_lazy('Voucher: discount for', 'Shipping')))+ (+ CATEGORY_TYPE,+ pgettext_lazy('Voucher: discount for', 'A category of products')),+ (SHIPPING_TYPE, pgettext_lazy('Voucher: discount for', 'Shipping'))]type = models.CharField(pgettext_lazy('Voucher field', 'discount for'), max_length=20,@@ -136,15 +152,21 @@ class Voucher(models.Model):if self.is_free:return pgettext('Voucher type', 'Free shipping')else:- return pgettext('Voucher type', '%(discount)s off shipping') % {- 'discount': discount}+ return pgettext(+ 'Voucher type',+ '%(discount)s off shipping') % {'discount': discount}if self.type == Voucher.PRODUCT_TYPE:- return pgettext('Voucher type', '%(discount)s off %(product)s') % {- 'discount': discount, 'product': self.product}+ return pgettext(+ 'Voucher type',+ '%(discount)s off %(product)s') % {+ 'discount': discount, 'product': self.product}if self.type == Voucher.CATEGORY_TYPE:- return pgettext('Voucher type', '%(discount)s off %(category)s') % {- 'discount': discount, 'category': self.category}- return pgettext('Voucher type', '%(discount)s off') % {'discount': discount}+ return pgettext(+ 'Voucher type',+ '%(discount)s off %(category)s') % {+ 'discount': discount, 'category': self.category}+ return pgettext(+ 'Voucher type', '%(discount)s off') % {'discount': discount}def get_apply_to_display(self):if self.type == Voucher.SHIPPING_TYPE and self.apply_to:@@ -179,8 +201,9 @@ class Voucher(models.Model):limit = self.limit if self.limit is not None else valueif value < limit:msg = pgettext(- 'Voucher not applicable', 'This offer is only valid for orders over %(amount)s.')- raise NotApplicable(msg % {'amount': net(limit)})+ 'Voucher not applicable',+ 'This offer is only valid for orders over %(amount)s.')+ raise NotApplicable(msg % {'amount': net(limit)}, limit=limit)def get_discount_for_checkout(self, checkout):if self.type == Voucher.VALUE_TYPE:@@ -191,19 +214,22 @@ class Voucher(models.Model):elif self.type == Voucher.SHIPPING_TYPE:if not checkout.is_shipping_required:msg = pgettext(- 'Voucher not applicable', 'Your order does not require shipping.')+ 'Voucher not applicable',+ 'Your order does not require shipping.')raise NotApplicable(msg)shipping_method = checkout.shipping_methodif not shipping_method:msg = pgettext(- 'Voucher not applicable', 'Please select a shipping method first.')+ 'Voucher not applicable',+ 'Please select a shipping method first.')raise NotApplicable(msg)if (self.apply_to andshipping_method.country_code != self.apply_to):msg = pgettext(- 'Voucher not applicable', 'This offer is only valid in %(country)s.')- raise NotApplicable(msg % {- 'country': self.get_apply_to_display()})+ 'Voucher not applicable',+ 'This offer is only valid in %(country)s.')+ raise NotApplicable(+ msg % {'country': self.get_apply_to_display()})cart_total = checkout.get_subtotal()self.validate_limit(cart_total)return self.get_fixed_discount_for(shipping_method.price)@@ -247,7 +273,8 @@ class Sale(models.Model):(FIXED, pgettext_lazy('Discount type', settings.DEFAULT_CURRENCY)),(PERCENTAGE, pgettext_lazy('Discount type', '%')))- name = models.CharField(pgettext_lazy('Sale (discount) field', 'name'), max_length=255)+ name = models.CharField(+ pgettext_lazy('Sale (discount) field', 'name'), max_length=255)type = models.CharField(pgettext_lazy('Sale (discount) field', 'type'),max_length=10, choices=DISCOUNT_TYPE_CHOICES, default=FIXED)@@ -305,7 +332,8 @@ class Sale(models.Model):return self.get_discount()raise NotApplicable(pgettext(- 'Voucher not applicable', 'Discount not applicable for this product'))+ 'Voucher not applicable',+ 'Discount not applicable for this product'))def get_product_discounts(product, discounts, **kwargs):diff --git a/tests/test_cart.py b/tests/test_cart.pyindex fed439507c..1046952b0f 100644--- a/tests/test_cart.py+++ b/tests/test_cart.py@@ -16,7 +16,7 @@ from satchless.item import InsufficientStockfrom saleor.cart import CartStatus, forms, utilsfrom saleor.cart.context_processors import cart_counter-from saleor.cart.models import Cart, ProductGroup+from saleor.cart.models import Cart, ProductGroup, find_open_cart_for_userfrom saleor.cart.views import updatefrom saleor.discount.models import Salefrom saleor.product.models import Category@@ -59,12 +59,14 @@ def cancelled_user_cart(customer_user):return Cart.objects.get_or_create(user=customer_user, status=CartStatus.CANCELED)[0]+@pytest.fixture()def local_currency(monkeypatch):def side_effect(price, currency):return pricemonkeypatch.setattr('saleor.cart.views.to_local_currency', side_effect)+def test_get_or_create_anonymous_cart_from_token(opened_anonymous_cart, cancelled_anonymous_cart, opened_user_cart,cancelled_user_cart):@@ -93,7 +95,8 @@ def test_get_or_create_anonymous_cart_from_token(cart.delete()# test against getting cart assigned to user- cart = utils.get_or_create_anonymous_cart_from_token(opened_user_cart.token)+ cart = utils.get_or_create_anonymous_cart_from_token(+ opened_user_cart.token)assert Cart.objects.all().count() == 5assert cart not in cartsassert cart.user is None@@ -159,8 +162,8 @@ def test_get_user_cart(assert cart is None-def test_get_or_create_cart_from_request(cart_request_factory, monkeypatch,- customer_user):+def test_get_or_create_cart_from_request(+ cart_request_factory, monkeypatch, customer_user):token = uuid4()queryset = Cart.objects.all()request = cart_request_factory(user=customer_user, token=token)@@ -183,8 +186,8 @@ def test_get_or_create_cart_from_request(cart_request_factory, monkeypatch,assert returned_cart == anonymous_cart-def test_get_cart_from_request(monkeypatch, customer_user,- cart_request_factory):+def test_get_cart_from_request(+ monkeypatch, customer_user, cart_request_factory):queryset = Cart.objects.all()token = uuid4()request = cart_request_factory(user=customer_user, token=token)@@ -271,8 +274,8 @@ def test_find_and_assign_anonymous_cart_and_close_opened(token = opened_anonymous_cart.tokentoken_user = opened_user_cart.tokenrequest = cart_request_factory(user=customer_user, token=token)- mock_view = lambda request: Mock(delete_cookie=lambda name: None)- utils.find_and_assign_anonymous_cart()(mock_view)(request)+ utils.find_and_assign_anonymous_cart()(+ lambda request: Mock(delete_cookie=lambda name: None))(request)token_cart = Cart.objects.filter(token=token).first()user_cart = Cart.objects.filter(token=token_user).first()assert token_cart.user.pk == customer_user.pk@@ -321,8 +324,8 @@ def test_adding_invalid_quantity(cart, product_in_stock):({'gift-wrap': True}, None, False),({'gift-wrap': True}, {'gift-wrap': True}, True)])-def test_getting_line(create_line_data, get_line_data, lines_equal,- cart, product_in_stock):+def test_getting_line(+ create_line_data, get_line_data, lines_equal, cart, product_in_stock):variant = product_in_stock.variants.get()assert cart.get_line(variant) is Noneline = cart.create_line(variant, 1, create_line_data)@@ -349,8 +352,9 @@ def test_shipping_detection(cart, product_in_stock):def test_cart_counter(monkeypatch):- monkeypatch.setattr('saleor.cart.context_processors.get_cart_from_request',- Mock(return_value=Mock(quantity=4)))+ monkeypatch.setattr(+ 'saleor.cart.context_processors.get_cart_from_request',+ Mock(return_value=Mock(quantity=4)))ret = cart_counter(Mock())assert ret == {'cart_counter': 4}@@ -359,8 +363,9 @@ def test_get_product_variants_and_prices():variant = Mock(product_id=1, id=1)cart = MagicMock(spec=Cart)cart.lines.all.return_value = [- Mock(quantity=1, variant=variant,- get_price_per_item=Mock(return_value=10))]+ Mock(+ quantity=1, variant=variant,+ get_price_per_item=Mock(return_value=10))]variants = list(utils.get_product_variants_and_prices(cart, variant))assert variants == [(variant, 10)]@@ -389,18 +394,21 @@ def test_check_product_availability_and_warn(monkeypatch, cart, product_in_stock):variant = product_in_stock.variants.get()cart.add(variant, 1)- monkeypatch.setattr('django.contrib.messages.warning',- Mock(warning=Mock()))- monkeypatch.setattr('saleor.cart.utils.contains_unavailable_variants',- Mock(return_value=False))+ monkeypatch.setattr(+ 'django.contrib.messages.warning', Mock(warning=Mock()))+ monkeypatch.setattr(+ 'saleor.cart.utils.contains_unavailable_variants',+ Mock(return_value=False))utils.check_product_availability_and_warn(MagicMock(), cart)assert len(cart) == 1- monkeypatch.setattr('saleor.cart.utils.contains_unavailable_variants',- Mock(return_value=True))- monkeypatch.setattr('saleor.cart.utils.remove_unavailable_variants',- lambda c: c.add(variant, 0, replace=True))+ monkeypatch.setattr(+ 'saleor.cart.utils.contains_unavailable_variants',+ Mock(return_value=True))+ monkeypatch.setattr(+ 'saleor.cart.utils.remove_unavailable_variants',+ lambda c: c.add(variant, 0, replace=True))utils.check_product_availability_and_warn(MagicMock(), cart)assert len(cart) == 0@@ -408,8 +416,9 @@ def test_check_product_availability_and_warn(def test_add_to_cart_form():cart_lines = []- cart = Mock(add=lambda variant, quantity: cart_lines.append(variant),- get_line=Mock(return_value=Mock(quantity=1)))+ cart = Mock(+ add=lambda variant, quantity: cart_lines.append(variant),+ get_line=Mock(return_value=Mock(quantity=1)))data = {'quantity': 1}form = forms.AddToCartForm(data=data, cart=cart, product=Mock())@@ -432,8 +441,9 @@ def test_add_to_cart_form():def test_form_when_variant_does_not_exist():cart_lines = []- cart = Mock(add=lambda variant, quantity: cart_lines.append(Mock()),- get_line=Mock(return_value=Mock(quantity=1)))+ cart = Mock(+ add=lambda variant, quantity: cart_lines.append(Mock()),+ get_line=Mock(return_value=Mock(quantity=1)))form = forms.AddToCartForm(data={'quantity': 1}, cart=cart, product=Mock())form.get_variant = Mock(side_effect=ObjectDoesNotExist)@@ -442,8 +452,9 @@ def test_form_when_variant_does_not_exist():def test_add_to_cart_form_when_empty_stock():cart_lines = []- cart = Mock(add=lambda variant, quantity: cart_lines.append(Mock()),- get_line=Mock(return_value=Mock(quantity=1)))+ cart = Mock(+ add=lambda variant, quantity: cart_lines.append(Mock()),+ get_line=Mock(return_value=Mock(quantity=1)))form = forms.AddToCartForm(data={'quantity': 1}, cart=cart, product=Mock())exception_mock = InsufficientStock(@@ -455,8 +466,9 @@ def test_add_to_cart_form_when_empty_stock():def test_add_to_cart_form_when_insufficient_stock():cart_lines = []- cart = Mock(add=lambda variant, quantity: cart_lines.append(variant),- get_line=Mock(return_value=Mock(quantity=1)))+ cart = Mock(+ add=lambda variant, quantity: cart_lines.append(variant),+ get_line=Mock(return_value=Mock(quantity=1)))form = forms.AddToCartForm(data={'quantity': 1}, cart=cart, product=Mock())exception_mock = InsufficientStock(@@ -488,8 +500,9 @@ def test_replace_cartline_form_when_insufficient_stock(cart.add(variant, initial_quantity)exception_mock = InsufficientStock(Mock(get_stock_quantity=Mock(return_value=2)))- monkeypatch.setattr('saleor.product.models.ProductVariant.check_quantity',- Mock(side_effect=exception_mock))+ monkeypatch.setattr(+ 'saleor.product.models.ProductVariant.check_quantity',+ Mock(side_effect=exception_mock))data = {'quantity': replaced_quantity}form = forms.ReplaceCartLineForm(data=data, cart=cart, variant=variant)assert not form.is_valid()@@ -513,7 +526,8 @@ def test_view_cart(client, sale, product_in_stock, request_cart):assert response.status_code == 200-def test_view_update_cart_quantity(client, local_currency, product_in_stock, request_cart):+def test_view_update_cart_quantity(+ client, local_currency, product_in_stock, request_cart):variant = product_in_stock.variants.get()request_cart.add(variant, 1)response = client.post(@@ -596,11 +610,13 @@ def test_total_with_discount(client, sale, request_cart, product_in_stock):def test_product_group():- group = ProductGroup([Mock(is_shipping_required=Mock(return_value=False)),- Mock(is_shipping_required=Mock(return_value=False))])+ group = ProductGroup([+ Mock(is_shipping_required=Mock(return_value=False)),+ Mock(is_shipping_required=Mock(return_value=False))])assert not group.is_shipping_required()- group = ProductGroup([Mock(is_shipping_required=Mock(return_value=True)),- Mock(is_shipping_required=Mock(return_value=False))])+ group = ProductGroup([+ Mock(is_shipping_required=Mock(return_value=True)),+ Mock(is_shipping_required=Mock(return_value=False))])assert group.is_shipping_required()@@ -626,23 +642,21 @@ def test_cart_queryset(customer_user):assert canceled.filter(pk=canceled_cart.pk).exists()-def test_get_user_open_cart(customer_user, opened_user_cart):-- assert Cart.get_user_open_cart(customer_user) == opened_user_cart+def test_find_open_cart_for_user(customer_user, opened_user_cart):+ assert find_open_cart_for_user(customer_user) == opened_user_cartcart = Cart.objects.create(user=customer_user)- assert Cart.get_user_open_cart(customer_user) == cart- assert Cart.objects.get(pk=opened_user_cart.pk).status == CartStatus.CANCELED+ assert find_open_cart_for_user(customer_user) == cart+ assert (+ Cart.objects.get(pk=opened_user_cart.pk).status == CartStatus.CANCELED)def test_cart_repr():cart = Cart()-assert repr(cart) == 'Cart(quantity=0)'cart.quantity = 1-assert repr(cart) == 'Cart(quantity=1)'@@ -685,15 +699,15 @@ def test_cart_line_state(product_in_stock, request_cart_with_item):assert line.quantity == 2-def test_get_category_variants_and_prices(default_category, product_in_stock,- request_cart_with_item):+def test_get_category_variants_and_prices(+ default_category, product_in_stock, request_cart_with_item):variant = product_in_stock.variants.get()top_category = Category.objects.create(name='foo', slug='bar')product_in_stock.categories.add(top_category)default_category.parent = top_categorydefault_category.save()- result = list(utils.get_category_variants_and_prices(request_cart_with_item,- top_category))+ result = list(utils.get_category_variants_and_prices(+ request_cart_with_item, top_category))assert result[0][0] == variantdiff --git a/tests/test_checkout_integration.py b/tests/test_checkout_integration.pyindex 668630bc30..8ade191eaa 100644--- a/tests/test_checkout_integration.py+++ b/tests/test_checkout_integration.py@@ -1,18 +1,12 @@-from django.contrib.auth import get_user_modelfrom django.core.urlresolvers import reversefrom payments import FraudStatus, PaymentStatus-from tests.utils import get_redirect_location+from saleor.userprofile.models import User+from .utils import get_redirect_location-User = get_user_model()---def test_checkout_flow(request_cart_with_item, client, shipping_method): # pylint: disable=W0613,R0914- """- Basic test case that confirms if core checkout flow works- """+def test_checkout_flow(request_cart_with_item, client, shipping_method):# Enter checkoutcheckout_index = client.get(reverse('checkout:index'), follow=True)# Checkout index redirects directly to shipping address step@@ -30,28 +24,32 @@ def test_checkout_flow(request_cart_with_item, client, shipping_method): # pyli'country_area': '','postal_code': '00-374','country': 'PL'}- shipping_response = client.post(shipping_address.request['PATH_INFO'],- data=shipping_data, follow=True)+ shipping_response = client.post(+ shipping_address.request['PATH_INFO'], data=shipping_data, follow=True)# Select shipping methodshipping_method_page = client.get(shipping_response.request['PATH_INFO'])# Redirect to summary after shipping method selection- shipping_method_data = {'method': shipping_method.pk}- shipping_method_response = client.post(shipping_method_page.request['PATH_INFO'],- data=shipping_method_data, follow=True)+ shipping_method_data = {+ 'method': shipping_method.price_per_country.first().pk}+ shipping_method_response = client.post(+ shipping_method_page.request['PATH_INFO'], data=shipping_method_data,+ follow=True)# Summary page asks for Billing address, default is the same as shippingaddress_data = {'address': 'shipping_address'}- summary_response = client.post(shipping_method_response.request['PATH_INFO'],- data=address_data, follow=True)+ summary_response = client.post(+ shipping_method_response.request['PATH_INFO'], data=address_data,+ follow=True)# After summary step, order is created and it waits for paymentorder = summary_response.context['order']# Select payment method- payment_page = client.post(summary_response.request['PATH_INFO'],- data={'method': 'default'}, follow=True)+ payment_page = client.post(+ summary_response.request['PATH_INFO'], data={'method': 'default'},+ follow=True)assert len(payment_page.redirect_chain) == 1assert payment_page.status_code == 200# Go to payment details page, enter payment data@@ -63,17 +61,14 @@ def test_checkout_flow(request_cart_with_item, client, shipping_method): # pyli'verification_result': 'waiting'}payment_response = client.post(payment_page_url, data=payment_data)assert payment_response.status_code == 302- order_password = reverse('order:create-password',- kwargs={'token': order.token})+ order_password = reverse(+ 'order:create-password', kwargs={'token': order.token})assert get_redirect_location(payment_response) == order_password-def test_checkout_flow_authenticated_user(authorized_client, billing_address, # pylint: disable=R0914- request_cart_with_item, customer_user,- shipping_method):- """- Checkout with authenticated user and previously saved address- """+def test_checkout_flow_authenticated_user(+ authorized_client, billing_address, request_cart_with_item,+ customer_user, shipping_method):# Prepare some datacustomer_user.addresses.add(billing_address)request_cart_with_item.user = customer_user@@ -81,29 +76,34 @@ def test_checkout_flow_authenticated_user(authorized_client, billing_address, ## Enter checkout# Checkout index redirects directly to shipping address step- shipping_address = authorized_client.get(reverse('checkout:index'), follow=True)+ shipping_address = authorized_client.get(+ reverse('checkout:index'), follow=True)# Enter shipping address datashipping_data = {'address': billing_address.pk}- shipping_method_page = authorized_client.post(shipping_address.request['PATH_INFO'],- data=shipping_data, follow=True)+ shipping_method_page = authorized_client.post(+ shipping_address.request['PATH_INFO'], data=shipping_data, follow=True)# Select shipping method- shipping_method_data = {'method': shipping_method.pk}- shipping_method_response = authorized_client.post(shipping_method_page.request['PATH_INFO'],- data=shipping_method_data, follow=True)+ shipping_method_data = {+ 'method': shipping_method.price_per_country.first().pk}+ shipping_method_response = authorized_client.post(+ shipping_method_page.request['PATH_INFO'], data=shipping_method_data,+ follow=True)# Summary page asks for Billing address, default is the same as shippingpayment_method_data = {'address': 'shipping_address'}- payment_method_page = authorized_client.post(shipping_method_response.request['PATH_INFO'],- data=payment_method_data, follow=True)+ payment_method_page = authorized_client.post(+ shipping_method_response.request['PATH_INFO'],+ data=payment_method_data, follow=True)# After summary step, order is created and it waits for paymentorder = payment_method_page.context['order']# Select payment method- payment_page = authorized_client.post(payment_method_page.request['PATH_INFO'],- data={'method': 'default'}, follow=True)+ payment_page = authorized_client.post(+ payment_method_page.request['PATH_INFO'], data={'method': 'default'},+ follow=True)# Go to payment details page, enter payment datapayment_data = {@@ -111,35 +111,26 @@ def test_checkout_flow_authenticated_user(authorized_client, billing_address, #'fraud_status': FraudStatus.UNKNOWN,'gateway_response': '3ds-disabled','verification_result': 'waiting'}- payment_response = authorized_client.post(payment_page.request['PATH_INFO'],- data=payment_data)+ payment_response = authorized_client.post(+ payment_page.request['PATH_INFO'], data=payment_data)assert payment_response.status_code == 302- order_password = reverse('order:create-password',- kwargs={'token': order.token})+ order_password = reverse(+ 'order:create-password', kwargs={'token': order.token})assert get_redirect_location(payment_response) == order_password-def test_address_without_shipping(request_cart_with_item, client, monkeypatch): # pylint: disable=W0613- """- user tries to get shipping address step in checkout without shipping -- if is redirected to summary step- """-- monkeypatch.setattr('saleor.checkout.core.Checkout.is_shipping_required',- False)+def test_address_without_shipping(request_cart_with_item, client, monkeypatch):+ monkeypatch.setattr(+ 'saleor.checkout.core.Checkout.is_shipping_required', False)response = client.get(reverse('checkout:shipping-address'))assert response.status_code == 302assert get_redirect_location(response) == reverse('checkout:summary')-def test_shipping_method_without_shipping(request_cart_with_item, client, monkeypatch): # pylint: disable=W0613- """- user tries to get shipping method step in checkout without shipping -- if is redirected to summary step- """-+def test_shipping_method_without_shipping(+ request_cart_with_item, client, monkeypatch):monkeypatch.setattr('saleor.checkout.core.Checkout.is_shipping_required',False)@@ -148,47 +139,36 @@ def test_shipping_method_without_shipping(request_cart_with_item, client, monkeyassert get_redirect_location(response) == reverse('checkout:summary')-def test_shipping_method_without_address(request_cart_with_item, client): # pylint: disable=W0613- """- user tries to get shipping method step without saved shipping address -- if is redirected to shipping address step- """-+def test_shipping_method_without_address(request_cart_with_item, client):response = client.get(reverse('checkout:shipping-method'))assert response.status_code == 302- assert get_redirect_location(response) == reverse('checkout:shipping-address')-+ assert (+ get_redirect_location(response) ==+ reverse('checkout:shipping-address'))-def test_summary_without_address(request_cart_with_item, client): # pylint: disable=W0613- """- user tries to get summary step without saved shipping method -- if is redirected to shipping method step- """+def test_summary_without_address(request_cart_with_item, client):response = client.get(reverse('checkout:summary'))assert response.status_code == 302- assert get_redirect_location(response) == reverse('checkout:shipping-method')+ assert (+ get_redirect_location(response) == reverse('checkout:shipping-method'))-def test_summary_without_shipping_method(request_cart_with_item, client, monkeypatch): # pylint: disable=W0613- """- user tries to get summary step without saved shipping method -- if is redirected to shipping method step- """+def test_summary_without_shipping_method(+ request_cart_with_item, client, monkeypatch):# address test return true- monkeypatch.setattr('saleor.checkout.core.Checkout.email',- True)+ monkeypatch.setattr(+ 'saleor.checkout.core.Checkout.email', True)response = client.get(reverse('checkout:summary'))assert response.status_code == 302- assert get_redirect_location(response) == reverse('checkout:shipping-method')+ assert (+ get_redirect_location(response) == reverse('checkout:shipping-method'))-def test_email_is_saved_in_order(authorized_client, billing_address, customer_user, # pylint: disable=R0914- request_cart_with_item, shipping_method):- """- authorized user change own email after checkout - if is not changed in order- """+def test_email_is_saved_in_order(+ authorized_client, billing_address, customer_user,+ request_cart_with_item, shipping_method):# Prepare some datacustomer_user.addresses.add(billing_address)request_cart_with_item.user = customer_user@@ -196,32 +176,35 @@ def test_email_is_saved_in_order(authorized_client, billing_address, customer_us# Enter checkout# Checkout index redirects directly to shipping address step- shipping_address = authorized_client.get(reverse('checkout:index'), follow=True)+ shipping_address = authorized_client.get(+ reverse('checkout:index'), follow=True)# Enter shipping address datashipping_data = {'address': billing_address.pk}- shipping_method_page = authorized_client.post(shipping_address.request['PATH_INFO'],- data=shipping_data, follow=True)+ shipping_method_page = authorized_client.post(+ shipping_address.request['PATH_INFO'], data=shipping_data, follow=True)# Select shipping method- shipping_method_data = {'method': shipping_method.pk}- shipping_method_response = authorized_client.post(shipping_method_page.request['PATH_INFO'],- data=shipping_method_data, follow=True)+ shipping_method_data = {+ 'method': shipping_method.price_per_country.first().pk}+ shipping_method_response = authorized_client.post(+ shipping_method_page.request['PATH_INFO'], data=shipping_method_data,+ follow=True)# Summary page asks for Billing address, default is the same as shippingpayment_method_data = {'address': 'shipping_address'}- payment_method_page = authorized_client.post(shipping_method_response.request['PATH_INFO'],- data=payment_method_data, follow=True)+ payment_method_page = authorized_client.post(+ shipping_method_response.request['PATH_INFO'],+ data=payment_method_data, follow=True)# After summary step, order is created and it waits for paymentorder = payment_method_page.context['order']assert order.user_email == customer_user.email-def test_voucher_invalid(client, request_cart_with_item, shipping_method, voucher): # pylint: disable=W0613,R0914- """- Look: #549 #544- """+def test_voucher_invalid(+ client, request_cart_with_item, shipping_method, voucher):+ # related issues: #549 #544voucher.usage_limit = 3voucher.save()# Enter checkout@@ -248,15 +231,18 @@ def test_voucher_invalid(client, request_cart_with_item, shipping_method, voucheshipping_method_page = client.get(shipping_response.request['PATH_INFO'])# Redirect to summary after shipping method selection- shipping_method_data = {'method': shipping_method.pk}- shipping_method_response = client.post(shipping_method_page.request['PATH_INFO'],- data=shipping_method_data, follow=True)+ shipping_method_data = {+ 'method': shipping_method.price_per_country.first().pk}+ shipping_method_response = client.post(+ shipping_method_page.request['PATH_INFO'], data=shipping_method_data,+ follow=True)# Summary page asks for Billing address, default is the same as shippingurl = shipping_method_response.request['PATH_INFO']discount_data = {'discount-voucher': voucher.code}- voucher_response = client.post('{url}?next={url}'.format(url=url),- follow=True, data=discount_data, HTTP_REFERER=url)+ voucher_response = client.post(+ '{url}?next={url}'.format(url=url), follow=True, data=discount_data,+ HTTP_REFERER=url)assert voucher_response.context['checkout'].voucher_code == voucher.codevoucher.used = 3voucher.save()@@ -269,7 +255,8 @@ def test_voucher_invalid(client, request_cart_with_item, shipping_method, voucheassert summary_response.context['order'].voucher is None-def test_remove_voucher(client, request_cart_with_item, shipping_method, voucher): # pylint: disable=W0613,R0914+def test_remove_voucher(+ client, request_cart_with_item, shipping_method, voucher):# Enter checkoutcheckout_index = client.get(reverse('checkout:index'), follow=True)# Checkout index redirects directly to shipping address step@@ -294,28 +281,29 @@ def test_remove_voucher(client, request_cart_with_item, shipping_method, vouchershipping_method_page = client.get(shipping_response.request['PATH_INFO'])# Redirect to summary after shipping method selection- shipping_method_data = {'method': shipping_method.pk}- shipping_method_response = client.post(shipping_method_page.request['PATH_INFO'],- data=shipping_method_data, follow=True)+ shipping_method_data = {+ 'method': shipping_method.price_per_country.first().pk}+ shipping_method_response = client.post(+ shipping_method_page.request['PATH_INFO'], data=shipping_method_data,+ follow=True)# Summary page asks for Billing address, default is the same as shippingurl = shipping_method_response.request['PATH_INFO']discount_data = {'discount-voucher': voucher.code}- voucher_response = client.post('{url}?next={url}'.format(url=url),- follow=True, data=discount_data, HTTP_REFERER=url)+ voucher_response = client.post(+ '{url}?next={url}'.format(url=url), follow=True, data=discount_data,+ HTTP_REFERER=url)assert voucher_response.context['checkout'].voucher_code is not None# Remove voucher from checkout- voucher_response = client.post(reverse('checkout:remove-voucher'),- follow=True, HTTP_REFERER=url)+ voucher_response = client.post(+ reverse('checkout:remove-voucher'), follow=True, HTTP_REFERER=url)assert voucher_response.status_code == 200assert voucher_response.context['checkout'].voucher_code is None-def test_language_is_saved_in_order(authorized_client, billing_address, customer_user, # pylint: disable=R0913, R0914- request_cart_with_item, settings, shipping_method):- """- authorized user change own email after checkout - if is not changed in order- """+def test_language_is_saved_in_order(+ authorized_client, billing_address, customer_user,+ request_cart_with_item, settings, shipping_method):# Prepare some datauser_language = 'fr'settings.LANGUAGE_CODE = 'en'@@ -324,26 +312,29 @@ def test_language_is_saved_in_order(authorized_client, billing_address, customerrequest_cart_with_item.save()# Enter checkout# Checkout index redirects directly to shipping address step- shipping_address = authorized_client.get(reverse('checkout:index'),- follow=True, HTTP_ACCEPT_LANGUAGE=user_language)+ shipping_address = authorized_client.get(+ reverse('checkout:index'), follow=True,+ HTTP_ACCEPT_LANGUAGE=user_language)# Enter shipping address datashipping_data = {'address': billing_address.pk}- shipping_method_page = authorized_client.post(shipping_address.request['PATH_INFO'],- data=shipping_data, follow=True,- HTTP_ACCEPT_LANGUAGE=user_language)+ shipping_method_page = authorized_client.post(+ shipping_address.request['PATH_INFO'], data=shipping_data, follow=True,+ HTTP_ACCEPT_LANGUAGE=user_language)# Select shipping method- shipping_method_data = {'method': shipping_method.pk}- shipping_method_response = authorized_client.post(shipping_method_page.request['PATH_INFO'],- data=shipping_method_data, follow=True,- HTTP_ACCEPT_LANGUAGE=user_language)+ shipping_method_data = {+ 'method': shipping_method.price_per_country.first().pk}+ shipping_method_response = authorized_client.post(+ shipping_method_page.request['PATH_INFO'], data=shipping_method_data,+ follow=True, HTTP_ACCEPT_LANGUAGE=user_language)# Summary page asks for Billing address, default is the same as shippingpayment_method_data = {'address': 'shipping_address'}- payment_method_page = authorized_client.post(shipping_method_response.request['PATH_INFO'],- data=payment_method_data, follow=True,- HTTP_ACCEPT_LANGUAGE=user_language)+ payment_method_page = authorized_client.post(+ shipping_method_response.request['PATH_INFO'],+ data=payment_method_data, follow=True,+ HTTP_ACCEPT_LANGUAGE=user_language)# After summary step, order is created and it waits for paymentorder = payment_method_page.context['order']diff --git a/tests/test_discounts.py b/tests/test_discounts.pyindex 8c8819bec3..76591b1b04 100644--- a/tests/test_discounts.py+++ b/tests/test_discounts.py@@ -4,8 +4,6 @@ import pytestfrom mock import Mockfrom prices import FixedDiscount, FractionalDiscount, Price-from django_prices.templatetags.prices_i18n import net-from saleor.cart.utils import get_category_variants_and_pricesfrom saleor.checkout.core import Checkoutfrom saleor.discount.forms import CheckoutDiscountForm@@ -14,25 +12,16 @@ from saleor.product.models import Categoryfrom saleor.product.models import Product, ProductVariant[email protected]('limit, value, valid', [- (Price(5, currency='USD'), Price(10, currency='USD'), True),- (Price(10, currency='USD'), Price(10, currency='USD'), True),- (Price(10, currency='USD'), Price(5, currency='USD'), False),-])-def test_voucher_limit_validation(settings, limit, value, valid):[email protected]('limit, value', [+ (Price(5, currency='USD'), Price(10, currency='USD')),+ (Price(10, currency='USD'), Price(10, currency='USD'))])+def test_valid_voucher_limit(settings, limit, value):voucher = Voucher(code='unique', type=Voucher.SHIPPING_TYPE,discount_value_type=Voucher.DISCOUNT_VALUE_FIXED,discount_value=Price(10, currency='USD'),limit=limit)- if valid:- voucher.validate_limit(value)- else:- with pytest.raises(NotApplicable) as e:- voucher.validate_limit(value)- msg = 'This offer is only valid for orders over %(amount)s.' % {- 'amount': net(limit)}- assert str(e.value) == msg+ voucher.validate_limit(value)@pytest.mark.integration@@ -101,7 +90,7 @@ def test_value_voucher_checkout_discount_not_applicable(settings):return_value=Price(10, currency='USD')))with pytest.raises(NotApplicable) as e:voucher.get_discount_for_checkout(checkout)- assert str(e.value) == 'This offer is only valid for orders over $100.00.'+ assert e.value.limit == Price(100, currency='USD')@pytest.mark.parametrize(@@ -252,23 +241,27 @@ def test_sale_applies_to_correct_products(product_class):@pytest.mark.django_db-def test_get_category_variants_and_prices_product_with_many_categories(cart, default_category,- product_in_stock):+def test_get_category_variants_and_prices_product_with_many_categories(+ cart, default_category, product_in_stock):# Test: don't duplicate percentage voucher# when product is in more than one category with discount- category = Category.objects.create(name='Foobar', slug='foo', parent=default_category)+ category = Category.objects.create(+ name='Foobar', slug='foo', parent=default_category)product_in_stock.price = Decimal('10.00')product_in_stock.save()product_in_stock.categories.add(category)variant = product_in_stock.variants.first()cart.add(variant, check_quantity=False)- discounted_products = list(get_category_variants_and_prices(cart, default_category))+ discounted_products = list(+ get_category_variants_and_prices(cart, default_category))assert len(discounted_products) == 1- voucher = Voucher.objects.create(category=default_category, type=Voucher.CATEGORY_TYPE,- discount_value='10.0', code='foobar',- discount_value_type=Voucher.DISCOUNT_VALUE_PERCENTAGE)+ voucher = Voucher.objects.create(+ category=default_category, type=Voucher.CATEGORY_TYPE,+ discount_value='10.0', code='foobar',+ discount_value_type=Voucher.DISCOUNT_VALUE_PERCENTAGE)checkout_mock = Mock(spec=Checkout, cart=cart)discount = voucher.get_discount_for_checkout(checkout_mock)- assert discount.amount == Price('1.00', currency=discount.amount.currency) # 10% for 10 is 1+ # 10% of 10.00 is 1.00+ assert discount.amount == Price('1.00', currency=discount.amount.currency)