Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Move some of cart methods to utils, refactor tests
Anna Siwika2343030246d
diff --git a/saleor/cart/forms.py b/saleor/cart/forms.pyindex 94b843bb90..84ea003271 100644--- a/saleor/cart/forms.py+++ b/saleor/cart/forms.py@@ -5,6 +5,7 @@ from django.core.exceptions import NON_FIELD_ERRORS, ObjectDoesNotExistfrom django.utils.translation import npgettext_lazy, pgettext_lazyfrom django_countries.fields import LazyTypedChoiceField, countries+from ..cart.utils import add_variant_to_cartfrom ..core.exceptions import InsufficientStockfrom ..shipping.utils import get_shipment_options@@ -61,16 +62,16 @@ class AddToCartForm(forms.Form):if quantity is None:return cleaned_datatry:- product_variant = self.get_variant(cleaned_data)+ variant = self.get_variant(cleaned_data)except ObjectDoesNotExist:msg = self.error_messages['variant-does-not-exists']self.add_error(NON_FIELD_ERRORS, msg)else:- cart_line = self.cart.get_line(product_variant)- used_quantity = cart_line.quantity if cart_line else 0+ line = self.cart.get_line(variant)+ used_quantity = line.quantity if line else 0new_quantity = quantity + used_quantitytry:- product_variant.check_quantity(new_quantity)+ variant.check_quantity(new_quantity)except InsufficientStock as e:remaining = e.item.quantity_available - used_quantityif remaining:@@ -83,9 +84,9 @@ class AddToCartForm(forms.Form):def save(self):"""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'])+ variant = self.get_variant(self.cleaned_data)+ quantity = self.cleaned_data['quantity']+ add_variant_to_cart(self.cart, variant, quantity)def get_variant(self, cleaned_data):"""Return a product variant that matches submitted values.@@ -142,9 +143,9 @@ class ReplaceCartLineForm(AddToCartForm):def save(self):"""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)+ variant = self.get_variant(self.cleaned_data)+ quantity = self.cleaned_data['quantity']+ add_variant_to_cart(self.cart, variant, quantity, replace=True)class CountryForm(forms.Form):diff --git a/saleor/cart/migrations/0007_merge_checkout_into_cart.py b/saleor/cart/migrations/0007_merge_checkout_into_cart.pyindex bb47eedf9a..d7f3c86621 100644--- a/saleor/cart/migrations/0007_merge_checkout_into_cart.py+++ b/saleor/cart/migrations/0007_merge_checkout_into_cart.py@@ -1,4 +1,4 @@-# Generated by Django 2.0.3 on 2018-05-23 12:30+# Generated by Django 2.0.3 on 2018-05-24 09:14from django.db import migrations, modelsimport django.db.models.deletion@@ -8,12 +8,17 @@ import django_prices.modelsclass Migration(migrations.Migration):dependencies = [- ('account', '0018_auto_20180426_0641'),('shipping', '0008_auto_20180108_0814'),+ ('product', '0063_required_attr_value_order'),+ ('account', '0018_auto_20180426_0641'),('cart', '0006_auto_20180221_0825'),]operations = [+ migrations.RemoveField(+ model_name='cart',+ name='checkout_data',+ ),migrations.RemoveField(model_name='cart',name='voucher',@@ -25,37 +30,33 @@ class Migration(migrations.Migration):),migrations.AddField(model_name='cart',- name='shipping_address',- field=models.ForeignKey(editable=False, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='+', to='account.Address'),+ name='discount_amount',+ field=django_prices.models.MoneyField(currency='USD', decimal_places=2, default=0, max_digits=12),),migrations.AddField(model_name='cart',- name='shipping_method',- field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='carts', to='shipping.ShippingMethodCountry'),+ name='discount_name',+ field=models.CharField(blank=True, max_length=255, null=True),),migrations.AddField(model_name='cart',- name='user_email',- field=models.EmailField(blank=True, default='', max_length=254),- ),- migrations.RemoveField(- model_name='cart',- name='checkout_data',+ name='note',+ field=models.TextField(blank=True, default=''),),migrations.AddField(model_name='cart',- name='note',- field=models.TextField(blank=True, default=''),+ name='shipping_address',+ field=models.ForeignKey(editable=False, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='+', to='account.Address'),),migrations.AddField(model_name='cart',- name='discount_amount',- field=django_prices.models.MoneyField(currency='USD', decimal_places=2, default=0, max_digits=12),+ name='shipping_method',+ field=models.ForeignKey(blank=True, null=True, on_delete=django.db.models.deletion.SET_NULL, related_name='carts', to='shipping.ShippingMethodCountry'),),migrations.AddField(model_name='cart',- name='discount_name',- field=models.CharField(blank=True, max_length=255, null=True),+ name='user_email',+ field=models.EmailField(blank=True, default='', max_length=254),),migrations.AddField(model_name='cart',diff --git a/saleor/cart/migrations/fix_empty_data_in_lines.py b/saleor/cart/migrations/fix_empty_data_in_lines.pyindex 7b0c33e2e5..26da4c6a76 100644--- a/saleor/cart/migrations/fix_empty_data_in_lines.py+++ b/saleor/cart/migrations/fix_empty_data_in_lines.py@@ -21,5 +21,5 @@ class Migration(migrations.Migration):]operations = [- migrations.RunPython(convert_lines_data)+ migrations.RunPython(convert_lines_data, migrations.RunPython.noop)]diff --git a/saleor/cart/models.py b/saleor/cart/models.pyindex 8547211a1b..75eae07c8c 100644--- a/saleor/cart/models.py+++ b/saleor/cart/models.py@@ -10,7 +10,7 @@ from django.utils.timezone import nowfrom django_prices.models import MoneyFieldfrom jsonfield import JSONField-from . import CartStatus, logger+from . import CartStatusfrom ..account.models import Addressfrom ..core.utils.taxes import ZERO_TAXED_MONEYfrom ..shipping.models import ShippingMethodCountry@@ -18,31 +18,13 @@ from ..shipping.models import ShippingMethodCountryCENTS = Decimal('0.01')-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 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 canceled(self):- """Return `CANCELED` carts."""- return self.filter(status=CartStatus.CANCELED)-def for_display(self):"""Annotate the queryset for display purposes.@@ -101,14 +83,6 @@ class Cart(models.Model):def __len__(self):return self.lines.count()- def update_quantity(self):- """Recalculate cart quantity based on lines."""- total_lines = self.count()['total_quantity']- if not total_lines:- total_lines = 0- self.quantity = total_lines- self.save(update_fields=['quantity'])-def change_status(self, status):"""Change cart status."""# FIXME: investigate replacing with django-fsm transitions@@ -119,18 +93,6 @@ class Cart(models.Model):self.last_status_change = now()self.save()- def change_user(self, 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 = user- self.shipping_address = user.default_shipping_address- self.save(update_fields=['user', 'shipping_address'])-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())@@ -149,68 +111,15 @@ class Cart(models.Model):def get_total(self, discounts=None, taxes=None):"""Return the total cost of the cart."""- total = self.get_subtotal(discounts, taxes)- total += self.get_shipping_price(taxes)- total -= self.discount_amount- return total-- def count(self):- """Return the total quantity in cart."""- lines = self.lines.all()- return lines.aggregate(total_quantity=models.Sum('quantity'))-- def create_line(self, variant, quantity, data):- """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 {})+ return (+ self.get_subtotal(discounts, taxes)+ + self.get_shipping_price(taxes)+ - self.discount_amount)- def get_line(self, variant, data=None):+ def get_line(self, variant):"""Return a line matching the given variant and data if any."""- all_lines = self.lines.all()- if data is None:- data = {}- line = [- line for line in all_lines- if line.variant_id == variant.id and line.data == data]- if line:- return line[0]- return None-- def add(self, variant, quantity=1, data=None, replace=False,- check_quantity=True):- """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- else:- new_quantity = cart_line.quantity + quantity-- if new_quantity < 0:- raise ValueError('%r is not a valid quantity (results in %r)' % (- quantity, new_quantity))-- if check_quantity:- variant.check_quantity(new_quantity)-- cart_line.quantity = new_quantity-- if not cart_line.quantity:- cart_line.delete()- else:- cart_line.save(update_fields=['quantity'])- self.update_quantity()+ matching_lines = (l for l in self.lines.all() if l.variant == variant)+ return next(matching_lines, None)class CartLine(models.Model):@@ -240,21 +149,20 @@ class CartLine(models.Model):return (self.variant == other.variant and- self.quantity == other.quantity and- self.data == other.data)+ self.quantity == other.quantity)def __ne__(self, other):return not self == other # pragma: no coverdef __repr__(self):- return 'CartLine(variant=%r, quantity=%r, data=%r)' % (- self.variant, self.quantity, self.data)+ return 'CartLine(variant=%r, quantity=%r)' % (+ self.variant, self.quantity)def __getstate__(self):- return self.variant, self.quantity, self.data+ return self.variant, self.quantitydef __setstate__(self, data):- self.variant, self.quantity, self.data = data+ self.variant, self.quantity = datadef get_total(self, discounts=None, taxes=None):"""Return the total price of this line."""diff --git a/saleor/cart/utils.py b/saleor/cart/utils.pyindex febc3356f4..c655912a1e 100644--- a/saleor/cart/utils.py+++ b/saleor/cart/utils.py@@ -5,11 +5,12 @@ from uuid import UUIDfrom django.contrib import messagesfrom django.db import transaction+from django.db.models import Sumfrom django.utils.timezone import nowfrom django.utils.translation import pgettext_lazyfrom prices import TaxedMoneyRange-from . import CartStatus+from . import CartStatus, loggerfrom ..core.exceptions import InsufficientStockfrom ..core.utils import to_local_currencyfrom .models import Cart@@ -52,10 +53,11 @@ 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)+ add_variant_to_cart(+ cart, line.variant, line.quantity, replace=True)except InsufficientStock as e:quantity = e.item.quantity_available- cart.add(line.variant, quantity=quantity, replace=True)+ add_variant_to_cart(cart, line.variant, quantity, replace=True)def get_product_variants_and_prices(cart, product):@@ -110,7 +112,7 @@ def find_and_assign_anonymous_cart(queryset=Cart.objects.all()):return responseif request.user.is_authenticated:with transaction.atomic():- cart.change_user(request.user)+ change_cart_user(cart, request.user)carts_to_close = Cart.objects.open().filter(user=request.user)carts_to_close = carts_to_close.exclude(token=token)@@ -239,3 +241,66 @@ def get_cart_data(cart, shipping_range, currency, discounts, taxes):'shipping_required': shipping_required,'total_with_shipping': total_with_shipping,'local_total_with_shipping': local_total_with_shipping}+++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()+++def change_cart_user(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)+ cart.user = user+ cart.shipping_address = user.default_shipping_address+ cart.save(update_fields=['user', 'shipping_address'])+++def update_cart_quantity(cart):+ """Update the total quantity in cart."""+ total_lines = cart.lines.aggregate(+ total_quantity=Sum('quantity'))['total_quantity']+ if not total_lines:+ total_lines = 0+ cart.quantity = total_lines+ cart.save(update_fields=['quantity'])+++def add_variant_to_cart(+ cart, variant, quantity=1, replace=False, check_quantity=True):+ """Add a product variant 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.+ """+ line, _ = cart.lines.get_or_create(+ variant=variant, defaults={'quantity': 0, 'data': {}})+ new_quantity = quantity if replace else (quantity + line.quantity)++ if new_quantity < 0:+ raise ValueError('%r is not a valid quantity (results in %r)' % (+ quantity, new_quantity))++ if new_quantity == 0:+ line.delete()+ else:+ if check_quantity:+ variant.check_quantity(new_quantity)++ line.quantity = new_quantity+ line.save(update_fields=['quantity'])++ update_cart_quantity(cart)diff --git a/tests/conftest.py b/tests/conftest.pyindex 22f8e94dd9..8214860ad3 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -1,4 +1,3 @@-from decimal import Decimalfrom io import BytesIOfrom unittest.mock import MagicMock, Mock@@ -18,6 +17,7 @@ from prices import Moneyfrom saleor.account.models import Address, Userfrom saleor.cart import utilsfrom saleor.cart.models import Cart+from saleor.cart.utils import add_variant_to_cartfrom saleor.dashboard.order.utils import fulfill_order_linefrom saleor.discount.models import Sale, Voucherfrom saleor.menu.models import Menu, MenuItem@@ -88,8 +88,7 @@ def request_cart(cart, monkeypatch):@pytest.fixturedef request_cart_with_item(product, request_cart):variant = product.variants.get()- # Prepare some data- request_cart.add(variant)+ add_variant_to_cart(request_cart, variant)return request_cartdiff --git a/tests/test_cart.py b/tests/test_cart.pyindex 5ef1206f01..c40bd3de07 100644--- a/tests/test_cart.py+++ b/tests/test_cart.py@@ -12,7 +12,9 @@ from prices import Money, TaxedMoneyfrom saleor.cart import CartStatus, forms, utilsfrom saleor.cart.context_processors import cart_counter-from saleor.cart.models import Cart, find_open_cart_for_user+from saleor.cart.models import Cart+from saleor.cart.utils import (+ add_variant_to_cart, change_cart_user, find_open_cart_for_user)from saleor.cart.views import updatefrom saleor.core.exceptions import InsufficientStockfrom saleor.core.utils.taxes import ZERO_TAXED_MONEY@@ -280,52 +282,45 @@ def test_find_and_assign_anonymous_cart_and_close_opened(def test_adding_without_checking(cart, product):variant = product.variants.get()- cart.add(variant, 1000, check_quantity=False)+ add_variant_to_cart(cart, variant, 1000, check_quantity=False)assert len(cart) == 1def test_adding_zero_quantity(cart, product):variant = product.variants.get()- cart.add(variant, 0)+ add_variant_to_cart(cart, variant, 0)assert len(cart) == 0def test_adding_same_variant(cart, product, taxes):variant = product.variants.get()- cart.add(variant, 1)- cart.add(variant, 2)+ add_variant_to_cart(cart, variant, 1)+ add_variant_to_cart(cart, variant, 2)assert len(cart) == 1- assert cart.count() == {'total_quantity': 3}+ assert cart.quantity == 3cart_total = TaxedMoney(net=Money('24.39', 'USD'), gross=Money(30, 'USD'))assert cart.get_subtotal(taxes=taxes) == cart_totaldef test_replacing_same_variant(cart, product):variant = product.variants.get()- cart.add(variant, 1, replace=True)- cart.add(variant, 2, replace=True)+ add_variant_to_cart(cart, variant, 1, replace=True)+ add_variant_to_cart(cart, variant, 2, replace=True)assert len(cart) == 1- assert cart.count() == {'total_quantity': 2}+ assert cart.quantity == 2def test_adding_invalid_quantity(cart, product):variant = product.variants.get()with pytest.raises(ValueError):- cart.add(variant, -1)+ add_variant_to_cart(cart, variant, -1)[email protected]('create_line_data, get_line_data, lines_equal', [- (None, None, True),- ({'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):+def test_getting_line(cart, product):variant = product.variants.get()assert cart.get_line(variant) is None- line = cart.create_line(variant, 1, create_line_data)- fetched_line = cart.get_line(variant, data=get_line_data)- lines_are_equal = fetched_line == line- assert lines_equal is lines_are_equal+ add_variant_to_cart(cart, variant)+ assert cart.lines.get() == cart.get_line(variant)def test_change_status(cart):@@ -339,9 +334,9 @@ def test_change_status(cart):def test_shipping_detection(cart, product):- variant = product.variants.get()assert not cart.is_shipping_required()- cart.add(variant, 1, replace=True)+ variant = product.variants.get()+ add_variant_to_cart(cart, variant, replace=True)assert cart.is_shipping_required()@@ -375,7 +370,7 @@ def test_contains_unavailable_variants():def test_remove_unavailable_variants(cart, product):variant = product.variants.get()- cart.add(variant, 1)+ add_variant_to_cart(cart, variant)variant.quantity = 0variant.save()utils.remove_unavailable_variants(cart)@@ -385,7 +380,7 @@ def test_remove_unavailable_variants(cart, product):def test_check_product_availability_and_warn(monkeypatch, cart, product):variant = product.variants.get()- cart.add(variant, 1)+ add_variant_to_cart(cart, variant)monkeypatch.setattr('django.contrib.messages.warning', Mock(warning=Mock()))monkeypatch.setattr(@@ -400,17 +395,19 @@ def test_check_product_availability_and_warn(Mock(return_value=True))monkeypatch.setattr('saleor.cart.utils.remove_unavailable_variants',- lambda c: c.add(variant, 0, replace=True))+ lambda c: add_variant_to_cart(cart, variant, 0, replace=True))utils.check_product_availability_and_warn(MagicMock(), cart)assert len(cart) == 0-def test_add_to_cart_form():+def test_add_to_cart_form(monkeypatch):cart_lines = []cart = Mock(- add=lambda variant, quantity: cart_lines.append(variant),get_line=Mock(return_value=Mock(quantity=1)))+ monkeypatch.setattr(+ 'saleor.cart.forms.add_variant_to_cart',+ lambda c, variant, quantity: cart_lines.append(variant))data = {'quantity': 1}form = forms.AddToCartForm(data=data, cart=cart, product=Mock())@@ -459,7 +456,7 @@ def test_replace_cart_line_form(cart, product):initial_quantity = 1replaced_quantity = 4- cart.add(variant, initial_quantity)+ add_variant_to_cart(cart, variant, initial_quantity)data = {'quantity': replaced_quantity}form = forms.ReplaceCartLineForm(data=data, cart=cart, variant=variant)assert form.is_valid()@@ -473,7 +470,7 @@ def test_replace_cartline_form_when_insufficient_stock(initial_quantity = 1replaced_quantity = 4- cart.add(variant, initial_quantity)+ add_variant_to_cart(cart, variant, initial_quantity)exception_mock = InsufficientStock(Mock(get_stock_quantity=Mock(return_value=2)))monkeypatch.setattr(@@ -597,12 +594,6 @@ def test_cart_line_total_with_discount_and_taxes(net=Money('4.07', 'USD'), gross=Money('5.00', 'USD'))-def test_cart_queryset():- canceled_cart = Cart.objects.create(status=CartStatus.CANCELED)- canceled = Cart.objects.canceled()- assert canceled.filter(pk=canceled_cart.pk).exists()--def test_find_open_cart_for_user(customer_user, opened_user_cart):assert find_open_cart_for_user(customer_user) == opened_user_cart@@ -628,11 +619,10 @@ def test_cart_get_total_empty(db):def test_cart_change_user(customer_user):cart1 = Cart.objects.create()+ change_cart_user(cart1, customer_user)- cart1.change_user(customer_user)cart2 = Cart.objects.create()-- cart2.change_user(customer_user)+ change_cart_user(cart2, customer_user)old_cart = Cart.objects.get(pk=cart1.pk)@@ -643,17 +633,17 @@ def test_cart_change_user(customer_user):def test_cart_line_repr(product, request_cart_with_item):variant = product.variants.get()line = request_cart_with_item.lines.first()- assert repr(line) == 'CartLine(variant=%r, quantity=%r, data=%r)' % (- variant, line.quantity, line.data)+ assert repr(line) == 'CartLine(variant=%r, quantity=%r)' % (+ variant, line.quantity)def test_cart_line_state(product, request_cart_with_item):variant = product.variants.get()line = request_cart_with_item.lines.first()- assert line.__getstate__() == (variant, line.quantity, line.data)+ assert line.__getstate__() == (variant, line.quantity)- line.__setstate__((variant, 2, line.data))+ line.__setstate__((variant, 2))assert line.quantity == 2diff --git a/tests/test_checkout.py b/tests/test_checkout.pyindex 4c9f121d8b..5e6430f74d 100644--- a/tests/test_checkout.py+++ b/tests/test_checkout.py@@ -10,6 +10,7 @@ from saleor.cart.checkout import viewsfrom saleor.cart.checkout.forms import CartVoucherFormfrom saleor.cart.checkout.utils import (create_order, get_voucher_discount_for_cart)+from saleor.cart.utils import add_variant_to_cartfrom saleor.core.exceptions import InsufficientStockfrom saleor.discount import DiscountValueType, VoucherTypefrom saleor.discount.models import NotApplicable, Voucher@@ -53,7 +54,7 @@ def test_checkout_discount(request_cart_with_item, sale, vatlayer):def test_checkout_create_order_insufficient_stock(request_cart, customer_user, product_without_shipping):variant = product_without_shipping.variants.get()- request_cart.add(variant, quantity=10, check_quantity=False)+ add_variant_to_cart(request_cart, variant, 10, check_quantity=False)request_cart.user = customer_userrequest_cart.billing_address = customer_user.default_billing_addressrequest_cart.save()diff --git a/tests/test_checkout_integration.py b/tests/test_checkout_integration.pyindex 57271113f6..8c56583e07 100644--- a/tests/test_checkout_integration.py+++ b/tests/test_checkout_integration.py@@ -4,6 +4,7 @@ from django.urls import reversefrom payments import FraudStatus, PaymentStatusfrom saleor.account.models import User+from saleor.cart.utils import add_variant_to_cartfrom .utils import get_redirect_location@@ -142,7 +143,7 @@ def test_checkout_flow_authenticated_user(def test_address_without_shipping(request_cart, product_without_shipping, client):variant = product_without_shipping.variants.get()- request_cart.add(variant)+ add_variant_to_cart(request_cart, variant)response = client.get(reverse('cart:checkout-shipping-address'))assert response.status_code == 302@@ -152,7 +153,7 @@ def test_address_without_shipping(def test_shipping_method_without_shipping(request_cart, product_without_shipping, client):variant = product_without_shipping.variants.get()- request_cart.add(variant)+ add_variant_to_cart(request_cart, variant)response = client.get(reverse('cart:checkout-shipping-method'))assert response.status_code == 302diff --git a/tests/test_product.py b/tests/test_product.pyindex 7e1d0ac988..0b36af55f6 100644--- a/tests/test_product.py+++ b/tests/test_product.py@@ -8,6 +8,7 @@ from prices import Money, TaxedMoney, TaxedMoneyRangefrom saleor.cart import CartStatus, utilsfrom saleor.cart.models import Cart+from saleor.cart.utils import add_variant_to_cartfrom saleor.discount.models import Salefrom saleor.product import ProductAvailabilityStatus, modelsfrom saleor.product.thumbnails import create_product_thumbnails@@ -147,7 +148,7 @@ def test_render_product_detail_with_taxes(client, product, vatlayer):def test_view_invalid_add_to_cart(client, product, request_cart):variant = product.variants.get()- request_cart.add(variant, 2)+ add_variant_to_cart(request_cart, variant, 2)response = client.post(reverse('product:add-to-cart',@@ -159,9 +160,8 @@ def test_view_invalid_add_to_cart(client, product, request_cart):assert request_cart.quantity == 2-def test_view_add_to_cart(client, product, request_cart):- variant = product.variants.get()- request_cart.add(variant, 1)+def test_view_add_to_cart(client, product, request_cart_with_item):+ variant = request_cart_with_item.lines.get().variantresponse = client.post(reverse('product:add-to-cart',@@ -169,118 +169,119 @@ def test_view_add_to_cart(client, product, request_cart):'product_id': product.pk}),{'quantity': 1, 'variant': variant.pk})assert response.status_code == 302- assert request_cart.quantity == 1+ assert request_cart_with_item.quantity == 1def test_adding_to_cart_with_current_user_token(- admin_user, admin_client, product):- client = admin_client+ customer_user, authorized_client, product, request_cart_with_item):key = utils.COOKIE_NAME- cart = Cart.objects.create(user=admin_user)- variant = product.variants.first()- cart.add(variant, 1)+ request_cart_with_item.user = customer_user+ request_cart_with_item.save()- response = client.get(reverse('cart:index'))- utils.set_cart_cookie(cart, response)- client.cookies[key] = response.cookies[key]+ response = authorized_client.get(reverse('cart:index'))- client.post(- reverse('product:add-to-cart',- kwargs={'slug': product.get_slug(),- 'product_id': product.pk}),- {'quantity': 1, 'variant': variant.pk})+ utils.set_cart_cookie(request_cart_with_item, response)+ authorized_client.cookies[key] = response.cookies[key]+ variant = request_cart_with_item.lines.first().variant+ url = reverse(+ 'product:add-to-cart',+ kwargs={'slug': product.get_slug(), 'product_id': product.pk})+ data = {'quantity': 1, 'variant': variant.pk}++ authorized_client.post(url, data)assert Cart.objects.count() == 1- assert Cart.objects.get(user=admin_user).pk == cart.pk+ assert Cart.objects.get(user=customer_user).pk == request_cart_with_item.pkdef test_adding_to_cart_with_another_user_token(- admin_user, admin_client, product, customer_user):+ admin_user, admin_client, product, customer_user, request_cart_with_item):client = admin_clientkey = utils.COOKIE_NAME- cart = Cart.objects.create(user=customer_user)- variant = product.variants.first()- cart.add(variant, 1)+ request_cart_with_item.user = customer_user+ request_cart_with_item.save()response = client.get(reverse('cart:index'))- utils.set_cart_cookie(cart, response)++ utils.set_cart_cookie(request_cart_with_item, response)client.cookies[key] = response.cookies[key]+ variant = request_cart_with_item.lines.first().variant+ url = reverse(+ 'product:add-to-cart',+ kwargs={'slug': product.get_slug(), 'product_id': product.pk})+ data = {'quantity': 1, 'variant': variant.pk}- client.post(- reverse('product:add-to-cart',- kwargs={'slug': product.get_slug(),- 'product_id': product.pk}),- {'quantity': 1, 'variant': variant.pk})+ client.post(url, data)assert Cart.objects.count() == 2- assert Cart.objects.get(user=admin_user).pk != cart.pk+ assert Cart.objects.get(user=admin_user).pk != request_cart_with_item.pkdef test_anonymous_adding_to_cart_with_another_user_token(- client, product, customer_user):+ client, product, customer_user, request_cart_with_item):key = utils.COOKIE_NAME- cart = Cart.objects.create(user=customer_user)- variant = product.variants.first()- cart.add(variant, 1)+ request_cart_with_item.user = customer_user+ request_cart_with_item.save()response = client.get(reverse('cart:index'))- utils.set_cart_cookie(cart, response)++ utils.set_cart_cookie(request_cart_with_item, response)client.cookies[key] = response.cookies[key]+ variant = product.variants.get()+ url = reverse(+ 'product:add-to-cart',+ kwargs={'slug': product.get_slug(), 'product_id': product.pk})+ data = {'quantity': 1, 'variant': variant.pk}- client.post(- reverse('product:add-to-cart',- kwargs={'slug': product.get_slug(),- 'product_id': product.pk}),- {'quantity': 1, 'variant': variant.pk})+ client.post(url, data)assert Cart.objects.count() == 2- assert Cart.objects.get(user=None).pk != cart.pk+ assert Cart.objects.get(user=None).pk != request_cart_with_item.pkdef test_adding_to_cart_with_deleted_cart_token(- admin_user, admin_client, product):- client = admin_client+ customer_user, authorized_client, product, request_cart_with_item):key = utils.COOKIE_NAME- cart = Cart.objects.create(user=admin_user)- old_token = cart.token- variant = product.variants.first()- cart.add(variant, 1)+ request_cart_with_item.user = customer_user+ request_cart_with_item.save()+ old_token = request_cart_with_item.token- response = client.get(reverse('cart:index'))- utils.set_cart_cookie(cart, response)- client.cookies[key] = response.cookies[key]- cart.delete()+ response = authorized_client.get(reverse('cart:index'))- client.post(- reverse('product:add-to-cart',- kwargs={'slug': product.get_slug(),- 'product_id': product.pk}),- {'quantity': 1, 'variant': variant.pk})+ utils.set_cart_cookie(request_cart_with_item, response)+ authorized_client.cookies[key] = response.cookies[key]+ request_cart_with_item.delete()+ variant = product.variants.get()+ url = reverse(+ 'product:add-to-cart',+ kwargs={'slug': product.get_slug(), 'product_id': product.pk})+ data = {'quantity': 1, 'variant': variant.pk}++ authorized_client.post(url, data)assert Cart.objects.count() == 1assert not Cart.objects.filter(token=old_token).exists()def test_adding_to_cart_with_closed_cart_token(- admin_user, admin_client, product):- client = admin_client+ customer_user, authorized_client, product, request_cart_with_item):key = utils.COOKIE_NAME- cart = Cart.objects.create(user=admin_user)- variant = product.variants.first()- cart.add(variant, 1)+ request_cart_with_item.user = customer_user+ request_cart_with_item.save()- response = client.get(reverse('cart:index'))- utils.set_cart_cookie(cart, response)- client.cookies[key] = response.cookies[key]+ response = authorized_client.get(reverse('cart:index'))+ utils.set_cart_cookie(request_cart_with_item, response)+ authorized_client.cookies[key] = response.cookies[key]+ variant = product.variants.get()+ url = reverse(+ 'product:add-to-cart',+ kwargs={'slug': product.get_slug(), 'product_id': product.pk})+ data = {'quantity': 1, 'variant': variant.pk}- client.post(- reverse('product:add-to-cart',- kwargs={'slug': product.get_slug(),- 'product_id': product.pk}),- {'quantity': 1, 'variant': variant.pk})+ authorized_client.post(url, data)assert Cart.objects.filter(- user=admin_user, status=CartStatus.OPEN).count() == 1+ user=customer_user, status=CartStatus.OPEN).count() == 1def test_product_filter_before_filtering(@@ -288,9 +289,13 @@ def test_product_filter_before_filtering(products = models.Product.objects.all().filter(category__name=default_category).order_by('-price')url = reverse(- 'product:category', kwargs={'path': default_category.slug,- 'category_id': default_category.pk})+ 'product:category',+ kwargs={+ 'path': default_category.slug,+ 'category_id': default_category.pk})+response = authorized_client.get(url)+assert list(products) == list(response.context['filter_set'].qs)@@ -301,20 +306,28 @@ def test_product_filter_product_exists(authorized_client, product,.filter(category__name=default_category).order_by('-price'))url = reverse(- 'product:category', kwargs={- 'path': default_category.slug, 'category_id': default_category.pk})+ 'product:category',+ kwargs={+ 'path': default_category.slug,+ 'category_id': default_category.pk})data = {'price_0': [''], 'price_1': ['20']}+response = authorized_client.get(url, data)+assert list(response.context['filter_set'].qs) == list(products)def test_product_filter_product_does_not_exist(authorized_client, product, default_category):url = reverse(- 'product:category', kwargs={- 'path': default_category.slug, 'category_id': default_category.pk})+ 'product:category',+ kwargs={+ 'path': default_category.slug,+ 'category_id': default_category.pk})data = {'price_0': ['20'], 'price_1': ['']}+response = authorized_client.get(url, data)+assert not list(response.context['filter_set'].qs)@@ -325,9 +338,13 @@ def test_product_filter_form(authorized_client, product,.filter(category__name=default_category).order_by('-price'))url = reverse(- 'product:category', kwargs={- 'path': default_category.slug, 'category_id': default_category.pk})+ 'product:category',+ kwargs={+ 'path': default_category.slug,+ 'category_id': default_category.pk})+response = authorized_client.get(url)+assert 'price' in response.context['filter_set'].form.fields.keys()assert 'sort_by' in response.context['filter_set'].form.fields.keys()assert list(response.context['filter_set'].qs) == list(products)@@ -340,20 +357,28 @@ def test_product_filter_sorted_by_price_descending(.filter(category__name=default_category, is_published=True).order_by('-price'))url = reverse(- 'product:category', kwargs={- 'path': default_category.slug, 'category_id': default_category.pk})+ 'product:category',+ kwargs={+ 'path': default_category.slug,+ 'category_id': default_category.pk})data = {'sort_by': '-price'}+response = authorized_client.get(url, data)+assert list(response.context['filter_set'].qs) == list(products)def test_product_filter_sorted_by_wrong_parameter(authorized_client, product, default_category):url = reverse(- 'product:category', kwargs={- 'path': default_category.slug, 'category_id': default_category.pk})+ 'product:category',+ kwargs={+ 'path': default_category.slug,+ 'category_id': default_category.pk})data = {'sort_by': 'aaa'}+response = authorized_client.get(url, data)+assert not list(response.context['filter_set'].qs)@@ -368,22 +393,22 @@ def test_view_ajax_available_variants_list(admin_client, product):variant = product.variants.first()variant_list = [{'id': variant.pk, 'text': '123, Test product (123), $10.00'}]-url = reverse('dashboard:ajax-available-variants')+response = admin_client.get(url, HTTP_X_REQUESTED_WITH='XMLHttpRequest')- resp_decoded = json.loads(response.content.decode('utf-8'))+ resp_decoded = json.loads(response.content.decode('utf-8'))assert response.status_code == 200assert resp_decoded == {'results': variant_list}def test_view_ajax_available_products_list(admin_client, product):product_list = [{'id': product.pk, 'text': 'Test product'}]-url = reverse('dashboard:ajax-products')+response = admin_client.get(url, HTTP_X_REQUESTED_WITH='XMLHttpRequest')- resp_decoded = json.loads(response.content.decode('utf-8'))+ resp_decoded = json.loads(response.content.decode('utf-8'))assert response.status_code == 200assert resp_decoded == {'results': product_list}