Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Tests, clean up
Pacu265afcd713730
diff --git a/docs/guides/orders.rst b/docs/guides/orders.rstindex 01c3c8e980..b0b7dec812 100644--- a/docs/guides/orders.rst+++ b/docs/guides/orders.rst@@ -9,7 +9,7 @@ Draft ordersTo create draft order, first you must go to dashboard ``Orders`` tab and choose circular **+** button visible above the list of existing orders.-Those orders can be fully edited until confirmed by clicking `Create order`. You can modify ordered items, customer (also just set an email), billing and shipping address, shipping methods and discount. Any voucher you apply will cause automatic order recalculation to fit actual state of an order every time it changes.+Those orders can be fully edited until confirmed by clicking `Create order`. You can modify ordered items, customer (also just set an email), billing and shipping address, shipping method and discount. Any voucher you apply will cause automatic order recalculation to fit actual state of an order every time it changes.Confirming an order by clicking `Create order` will change status to unfulfilled and disable most of the edit actions. You can optionally notify customer - if attached any - about that order by sending email.diff --git a/docs/guides/taxes.rst b/docs/guides/taxes.rstindex db6c58d0fa..2218cdf99c 100644--- a/docs/guides/taxes.rst+++ b/docs/guides/taxes.rst@@ -21,7 +21,7 @@ There are three ways in which you can configure taxes:If selected, prices displayed for customers in storefront will be gross. Taxes will be properly calculated at checkout. Changing this setting has no effect on displaying orders placed in the past.-#. Charge taxes on shipping methods+#. Charge taxes on shipping ratesIf selected, standard tax rate will be charged on shipping price.diff --git a/saleor/checkout/forms.py b/saleor/checkout/forms.pyindex 716a23e951..1cc7d1f351 100644--- a/saleor/checkout/forms.py+++ b/saleor/checkout/forms.py@@ -15,7 +15,7 @@ from ..core.utils import format_moneyfrom ..core.utils.taxes import display_gross_prices, get_taxed_shipping_pricefrom ..discount.models import NotApplicable, Voucherfrom ..shipping.models import ShippingMethod-from ..shipping.utils import shipping_price_estimate+from ..shipping.utils import get_shipping_price_estimatefrom .models import Cart@@ -167,12 +167,12 @@ class CountryForm(forms.Form):self.taxes = kwargs.pop('taxes', {})super().__init__(*args, **kwargs)- def shipping_price_estimate(self, price, weight):+ def get_shipping_price_estimate(self, price, weight):"""Return a shipping price range for given order for the selectedcountry."""code = self.cleaned_data['country']- return shipping_price_estimate(price, weight, code, self.taxes)+ return get_shipping_price_estimate(price, weight, code, self.taxes)class AnonymousUserShippingForm(forms.ModelForm):diff --git a/saleor/checkout/utils.py b/saleor/checkout/utils.pyindex d4da44fa57..a4d4729deb 100644--- a/saleor/checkout/utils.py+++ b/saleor/checkout/utils.py@@ -782,7 +782,7 @@ def shipping_method_applicable(price, weight, method):maximum=method.maximum_order_weight, value=weight)-def check_shipping_method(cart, taxes, discounts):+def is_valid_shipping_method(cart, taxes, discounts):"""Check if shipping method is valid and remove (if not)."""if not cart.shipping_method:return False@@ -790,20 +790,21 @@ def check_shipping_method(cart, taxes, discounts):cart.shipping_address.country.code not incart.shipping_method.shipping_zone.countries)if shipping_outside_the_shipping_zone:- return clear_shipping_method(cart)+ clear_shipping_method(cart)+ return False- shipping_method_is_valid = shipping_method_applicable(+ is_valid_shipping = shipping_method_applicable(price=cart.get_subtotal(discounts, taxes).gross,weight=cart.get_total_weight(), method=cart.shipping_method)- if not shipping_method_is_valid:- return clear_shipping_method(cart)+ if not is_valid_shipping:+ clear_shipping_method(cart)+ return Falsereturn Truedef clear_shipping_method(cart):cart.shipping_method = Nonecart.save(update_fields=['shipping_method'])- return Falsedef _process_voucher_data_for_order(cart):diff --git a/saleor/checkout/views/__init__.py b/saleor/checkout/views/__init__.pyindex e256470b17..1137fc8309 100644--- a/saleor/checkout/views/__init__.py+++ b/saleor/checkout/views/__init__.py@@ -7,13 +7,13 @@ from ...account.forms import LoginFormfrom ...core.utils import (format_money, get_user_shipping_country, to_local_currency)from ...product.models import ProductVariant-from ...shipping.utils import shipping_price_estimate+from ...shipping.utils import get_shipping_price_estimatefrom ..forms import CartShippingMethodForm, CountryForm, ReplaceCartLineFormfrom ..models import Cartfrom ..utils import (- check_product_availability_and_warn, check_shipping_method, get_cart_data,+ check_product_availability_and_warn, get_cart_data,get_cart_data_for_checkout, get_or_empty_db_cart, get_taxes_for_cart,- update_cart_quantity)+ is_valid_shipping_method, update_cart_quantity)from .discount import add_voucher_form, validate_voucherfrom .shipping import (anonymous_user_shipping_address_view, user_shipping_address_view)@@ -64,7 +64,7 @@ def checkout_shipping_address(request, cart):def checkout_shipping_method(request, cart):"""Display the shipping method selection step."""taxes = get_taxes_for_cart(cart, request.taxes)- check_shipping_method(cart, request.taxes, request.discounts)+ is_valid_shipping_method(cart, request.taxes, request.discounts)form = CartShippingMethodForm(request.POST or None, taxes=taxes, instance=cart,@@ -128,7 +128,7 @@ def cart_index(request, cart):default_country = get_user_shipping_country(request)country_form = CountryForm(initial={'country': default_country})- shipping_price_range = shipping_price_estimate(+ shipping_price_range = get_shipping_price_estimate(price=cart.get_subtotal(discounts, taxes).gross,weight=cart.get_total_weight(), country_code=default_country,taxes=taxes)@@ -149,7 +149,7 @@ def cart_shipping_options(request, cart):"""Display shipping options to get a price estimate."""country_form = CountryForm(request.POST or None, taxes=request.taxes)if country_form.is_valid():- shipping_price_range = country_form.shipping_price_estimate(+ shipping_price_range = country_form.get_shipping_price_estimate(price=cart.get_subtotal(request.discounts, request.taxes).gross,weight=cart.get_total_weight())else:diff --git a/saleor/checkout/views/validators.py b/saleor/checkout/views/validators.pyindex 044bfa062b..47a7375ac8 100644--- a/saleor/checkout/views/validators.py+++ b/saleor/checkout/views/validators.py@@ -3,7 +3,7 @@ from functools import wrapsfrom django.core.exceptions import ValidationErrorfrom django.shortcuts import redirect-from ..utils import check_shipping_method+from ..utils import is_valid_shipping_methoddef validate_cart(view):@@ -49,7 +49,8 @@ def validate_shipping_method(view):"""@wraps(view)def func(request, cart):- if not check_shipping_method(cart, request.taxes, request.discounts):+ if not is_valid_shipping_method(+ cart, request.taxes, request.discounts):return redirect('checkout:shipping-method')return view(request, cart)return funcdiff --git a/saleor/dashboard/product/forms.py b/saleor/dashboard/product/forms.pyindex 5cb9bc1745..dc976f4d56 100644--- a/saleor/dashboard/product/forms.py+++ b/saleor/dashboard/product/forms.py@@ -87,7 +87,14 @@ class ProductTypeForm(forms.ModelForm):'Attributes common to all variants'),'is_shipping_required': pgettext_lazy('Shipping toggle',- 'Require shipping')}+ 'Require shipping'),+ 'weight': pgettext_lazy(+ 'Product type weight', 'Weight')}+ help_texts = {+ 'weight': pgettext_lazy(+ 'Weight help text',+ 'Default weight that will be used for calculating shipping'+ ' price for products of that type.')}def __init__(self, *args, **kwargs):super().__init__(*args, **kwargs)@@ -223,6 +230,11 @@ class ProductForm(forms.ModelForm, AttributesMixin):'Product published toggle', 'Published'),'charge_taxes': pgettext_lazy('Charge taxes on product', 'Charge taxes on this product')}+ help_texts = {+ 'weight': pgettext_lazy(+ 'Weight field help text',+ 'Weight will be used to calculate shipping price, '+ 'if empty, equal to default value used on the ProductType.')}def __init__(self, *args, **kwargs):super().__init__(*args, **kwargs)@@ -247,6 +259,12 @@ class ProductForm(forms.ModelForm, AttributesMixin):self.fields['price'].label = pgettext_lazy('Currency net amount', 'Net price')+ if not product_type.is_shipping_required:+ del self.fields['weight']+ else:+ self.fields['weight'].widget.attrs['placeholder'] = (+ product_type.weight.value)+def clean_seo_description(self):seo_description = prepare_seo_description(seo_description=self.cleaned_data['seo_description'],@@ -270,10 +288,11 @@ class ProductVariantForm(forms.ModelForm, AttributesMixin):class Meta:model = ProductVariantfields = [- 'sku', 'price_override',+ 'sku', 'price_override', 'weight','quantity', 'cost_price', 'track_inventory']labels = {'sku': pgettext_lazy('SKU', 'SKU'),+ 'weight': pgettext_lazy('ProductVariant weight', 'Weight'),'price_override': pgettext_lazy('Override price', 'Selling price override'),'quantity': pgettext_lazy('Integer number', 'Number in stock'),@@ -283,7 +302,11 @@ class ProductVariantForm(forms.ModelForm, AttributesMixin):help_texts = {'track_inventory': pgettext_lazy('product variant handle stock field help text',- 'Automatically track this product\'s inventory')}+ 'Automatically track this product\'s inventory'),+ 'weight': pgettext_lazy(+ 'ProductVariant weight help text',+ 'Weight will be used to calculate shipping price. '+ 'If empty, weight from Product or ProductType will be used.')}def __init__(self, *args, **kwargs):super().__init__(*args, **kwargs)@@ -307,6 +330,13 @@ class ProductVariantForm(forms.ModelForm, AttributesMixin):self.fields['cost_price'].label = pgettext_lazy('Currency amount', 'Cost net price')+ if not self.instance.product.product_type.is_shipping_required:+ del self.fields['weight']+ else:+ self.fields['weight'].widget.attrs['placeholder'] = (+ getattr(self.instance.product.weight, 'value', None) or+ self.instance.product.product_type.weight.value)+def save(self, commit=True):attributes = self.get_saved_attributes()self.instance.attributes = attributesdiff --git a/saleor/dashboard/taxes/forms.py b/saleor/dashboard/taxes/forms.pyindex 6c69cf73d3..52679d654d 100644--- a/saleor/dashboard/taxes/forms.py+++ b/saleor/dashboard/taxes/forms.py@@ -18,5 +18,5 @@ class TaxesConfigurationForm(forms.ModelForm):'Display gross prices','Show gross prices to customers in the storefront'),'charge_taxes_on_shipping': pgettext_lazy(- 'Charge taxes on shipping methods',- 'Charge taxes on shipping methods')}+ 'Charge taxes on shipping rates',+ 'Charge taxes on shipping rates')}diff --git a/saleor/graphql/product/mutations/products.py b/saleor/graphql/product/mutations/products.pyindex a87aa6bd3c..55cd1f70ed 100644--- a/saleor/graphql/product/mutations/products.py+++ b/saleor/graphql/product/mutations/products.py@@ -7,10 +7,10 @@ from ....product import modelsfrom ....product.utils.attributes import get_name_from_attributesfrom ...core.mutations import BaseMutation, ModelDeleteMutation, ModelMutationfrom ...core.types.common import Decimal, Error, SeoInput-from ...shipping.types import WeightScalarfrom ...core.utils import clean_seo_fieldsfrom ...file_upload.types import Uploadfrom ...utils import get_attributes_dict_from_list+from ...shipping.types import WeightScalarfrom ..types import Collection, Product, ProductImage, ProductVariantdiff --git a/saleor/graphql/shipping/types.py b/saleor/graphql/shipping/types.pyindex 67fab3d4e1..d7fa3bb20c 100644--- a/saleor/graphql/shipping/types.py+++ b/saleor/graphql/shipping/types.py@@ -1,13 +1,12 @@import graphenefrom graphene import relay+from graphene.types import Scalarfrom graphene_django import DjangoObjectType+from measurement.measures import Mass-from ...shipping import ShippingMethodType-from ...shipping import models+from ...shipping import ShippingMethodType, modelsfrom ..core.types.common import CountableDjangoObjectTypefrom ..core.types.money import MoneyRange-from graphene.types import Scalar-from measurement.measures import Massclass ShippingZone(CountableDjangoObjectType):diff --git a/saleor/product/models.py b/saleor/product/models.pyindex 05732e2794..6e35de66ea 100644--- a/saleor/product/models.py+++ b/saleor/product/models.py@@ -168,7 +168,7 @@ class Product(SeoModel):return images[0].image if images else Nonedef get_price_range(self, discounts=None, taxes=None):- if self.variants.exists():+ if self.variants.all():prices = [variant.get_price(discounts=discounts, taxes=taxes)for variant in self]diff --git a/saleor/shipping/__init__.py b/saleor/shipping/__init__.pyindex bfce0850f6..f5a0c16697 100644--- a/saleor/shipping/__init__.py+++ b/saleor/shipping/__init__.py@@ -7,10 +7,6 @@ class ShippingMethodType:CHOICES = [(PRICE_BASED, pgettext_lazy(- 'Type of shipping',- 'Price based shipping'- )),+ 'Type of shipping', 'Price based shipping')),(WEIGHT_BASED, pgettext_lazy(- 'Type of shipping',- 'Weight based shipping'- ))]+ 'Type of shipping', 'Weight based shipping'))]diff --git a/saleor/shipping/models.py b/saleor/shipping/models.pyindex 14c8ab0ba5..aadb00580c 100644--- a/saleor/shipping/models.py+++ b/saleor/shipping/models.py@@ -1,6 +1,5 @@from django.conf import settingsfrom django.db import models-from django.db.models import Qfrom django.utils.safestring import mark_safefrom django.utils.translation import pgettext_lazyfrom django_countries.fields import CountryField@@ -12,30 +11,9 @@ from prices import MoneyRangefrom . import ShippingMethodTypefrom ..core.utils import format_moneyfrom ..core.utils.taxes import get_taxed_shipping_price---def applicable_weight_based_methods(weight, qs):- """Returns weight based ShippingMethods that can be applied to an order- with given total weight.- """- qs = qs.weight_based()- min_weight_matched = Q(minimum_order_weight__lte=weight)- no_weight_limit = Q(maximum_order_weight__isnull=True)- max_weight_matched = Q(maximum_order_weight__gte=weight)- return qs.filter(- min_weight_matched & (no_weight_limit | max_weight_matched))---def applicable_price_based_methods(price, qs):- """Returns price based ShippingMethods that can be applied to an order- with given price total.- """- qs = qs.price_based()- min_price_matched = Q(minimum_order_price__lte=price)- no_price_limit = Q(maximum_order_price__isnull=True)- max_price_matched = Q(maximum_order_price__gte=price)- return qs.filter(- min_price_matched & (no_price_limit | max_price_matched))+from .utils import (+ applicable_price_based_methods, applicable_weight_based_methods,+ get_price_type_display, get_weight_type_display)class ShippingZone(models.Model):@@ -128,7 +106,8 @@ class ShippingMethod(models.Model):return 'ShippingMethod(type=%s min=%s, max=%s)' % (self.type, minimum, maximum)return 'ShippingMethod(type=%s weight_range=(%s)' % (- self.type, self.get_weight_type_display())+ self.type, get_weight_type_display(+ self.minimum_order_weight, self.maximum_order_weight))def get_total_price(self, taxes=None):return get_taxed_shipping_price(self.price, taxes)@@ -138,32 +117,9 @@ class ShippingMethod(models.Model):label = mark_safe('%s %s' % (self, price_html))return label- def get_weight_type_display(self):- if self.maximum_order_weight is None:- return pgettext_lazy(- 'Applies to orders heavier than the threshold',- '%(minimum_order_weight)s and up') % {- 'minimum_order_weight': self.minimum_order_weight}- return pgettext_lazy(- 'Applies to orders of total weight within this range',- '%(minimum_order_weight)s to %(maximum_order_weight)s' % {- 'minimum_order_weight': self.minimum_order_weight,- 'maximum_order_weight': self.maximum_order_weight})-- def get_price_type_display(self):- if self.maximum_order_price is None:- return pgettext_lazy(- 'Applies to orders more expensive than the min value',- '%(minimum_order_price)s and up') % {- 'minimum_order_price': format_money(- self.minimum_order_price)}- return pgettext_lazy(- 'Applies to order valued within this price range',- '%(minimum_order_price)s to %(maximum_order_price)s') % {- 'minimum_order_price': format_money(self.minimum_order_price),- 'maximum_order_price': format_money(self.maximum_order_price)}-def get_type_display(self):if self.type == ShippingMethodType.PRICE_BASED:- return self.get_price_type_display()- return self.get_weight_type_display()+ return get_price_type_display(+ self.minimum_order_price, self.maximum_order_price)+ return get_weight_type_display(+ self.minimum_order_weight, self.maximum_order_weight)diff --git a/saleor/shipping/utils.py b/saleor/shipping/utils.pyindex 88c7af2949..6f81289a96 100644--- a/saleor/shipping/utils.py+++ b/saleor/shipping/utils.py@@ -1,11 +1,14 @@+from django.db.models import Q+from django.utils.translation import pgettext_lazyfrom prices import MoneyRangefrom ..core.utils.taxes import get_taxed_shipping_price-from .models import ShippingMethod-def shipping_price_estimate(price, weight, country_code, taxes):+def get_shipping_price_estimate(price, weight, country_code, taxes):"""Returns estimated price range for shipping for given order."""+ from .models import ShippingMethod+shipping_methods = ShippingMethod.objects.applicable_shipping_methods(price, weight, country_code)shipping_methods = shipping_methods.values_list('price', flat=True)@@ -14,3 +17,55 @@ def shipping_price_estimate(price, weight, country_code, taxes):prices = MoneyRange(start=min(shipping_methods), stop=max(shipping_methods))return get_taxed_shipping_price(prices, taxes)+++def applicable_weight_based_methods(weight, qs):+ """Returns weight based ShippingMethods that can be applied to an order+ with given total weight.+ """+ qs = qs.weight_based()+ min_weight_matched = Q(minimum_order_weight__lte=weight)+ no_weight_limit = Q(maximum_order_weight__isnull=True)+ max_weight_matched = Q(maximum_order_weight__gte=weight)+ return qs.filter(+ min_weight_matched & (no_weight_limit | max_weight_matched))+++def applicable_price_based_methods(price, qs):+ """Returns price based ShippingMethods that can be applied to an order+ with given price total.+ """+ qs = qs.price_based()+ min_price_matched = Q(minimum_order_price__lte=price)+ no_price_limit = Q(maximum_order_price__isnull=True)+ max_price_matched = Q(maximum_order_price__gte=price)+ return qs.filter(+ min_price_matched & (no_price_limit | max_price_matched))+++def get_price_type_display(minimum_order_price, maximum_order_price):+ from ..core.utils import format_money++ if maximum_order_price is None:+ return pgettext_lazy(+ 'Applies to orders more expensive than the min value',+ '%(minimum_order_price)s and up') % {+ 'minimum_order_price': format_money(minimum_order_price)}+ return pgettext_lazy(+ 'Applies to order valued within this price range',+ '%(minimum_order_price)s to %(maximum_order_price)s') % {+ 'minimum_order_price': format_money(minimum_order_price),+ 'maximum_order_price': format_money(maximum_order_price)}+++def get_weight_type_display(minimum_order_weight, maximum_order_weight):+ if maximum_order_weight is None:+ return pgettext_lazy(+ 'Applies to orders heavier than the threshold',+ '%(minimum_order_weight)s and up') % {+ 'minimum_order_weight': minimum_order_weight}+ return pgettext_lazy(+ 'Applies to orders of total weight within this range',+ '%(minimum_order_weight)s to %(maximum_order_weight)s' % {+ 'minimum_order_weight': minimum_order_weight,+ 'maximum_order_weight': maximum_order_weight})diff --git a/saleor/site/models.py b/saleor/site/models.pyindex 0768aa13ec..53187e9cd0 100644--- a/saleor/site/models.py+++ b/saleor/site/models.py@@ -27,6 +27,9 @@ class SiteSettings(models.Model):homepage_collection = models.ForeignKey('product.Collection', on_delete=models.SET_NULL, related_name='+',blank=True, null=True)+ default_weight_unit = models.CharField(+ max_length=10, choices=[],+ default=0)translated = TranslationProxy()diff --git a/templates/dashboard/product/form.html b/templates/dashboard/product/form.htmlindex f652c21c91..d07cdc95e7 100644--- a/templates/dashboard/product/form.html+++ b/templates/dashboard/product/form.html@@ -107,6 +107,11 @@<div class="row">{{ product_form.collections|materializecss }}</div>+ {% if product.product_type.is_shipping_required %}+ <span class="card-title">{% trans "Shipping" %}</span>+ <br>+ {{ product_form.weight|materializecss }}+ {% endif %}<span class="card-title">{% trans "Attributes" %}</span><br><h6>diff --git a/templates/dashboard/product/product_variant/form.html b/templates/dashboard/product/product_variant/form.htmlindex 29e850ef33..b2b98f2e70 100644--- a/templates/dashboard/product/product_variant/form.html+++ b/templates/dashboard/product/product_variant/form.html@@ -81,6 +81,10 @@{% empty %}{% trans "No attributes found." %}{% endfor %}+ {% if variant.product.product_type.is_shipping_required %}+ <p class="card-title">{% trans "Shipping" %}</p>+ {{ form.weight|materializecss }}+ {% endif %}</div><div class="col s12 m4"><div class="row">diff --git a/templates/dashboard/taxes/list.html b/templates/dashboard/taxes/list.htmlindex 8fd9da6615..f539c3aef4 100644--- a/templates/dashboard/taxes/list.html+++ b/templates/dashboard/taxes/list.html@@ -105,13 +105,13 @@<div class="row"><div class="col s12"><h4>- {% trans "Charge taxes on shipping methods" context "Site settings field" %}+ {% trans "Charge taxes on shipping rates" context "Site settings field" %}</h4><p>{% if site.settings.charge_taxes_on_shipping %}- {% trans "Yes" context "Charge taxes on shipping methods setting description" %}+ {% trans "Yes" context "Charge taxes on shipping rates setting description" %}{% else %}- {% trans "No" context "Charge taxes on shipping methods setting description" %}+ {% trans "No" context "Charge taxes on shipping rates setting description" %}{% endif %}</p></div>diff --git a/tests/api/test_variant.py b/tests/api/test_variant.pyindex 3d047feffa..e9b25a5a0f 100644--- a/tests/api/test_variant.py+++ b/tests/api/test_variant.py@@ -53,7 +53,7 @@ def test_fetch_variant(admin_api_client, product):variant = product.variants.first()variant_id = graphene.Node.to_global_id('ProductVariant', variant.pk)- variables = json.dumps({ 'id': variant_id })+ variables = json.dumps({ 'id': variant_id})response = admin_api_client.post(reverse('api'), {'query': query, 'variables': variables})content = get_graphql_content(response)diff --git a/tests/conftest.py b/tests/conftest.pyindex 52b3e49567..5d1885fcfc 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -106,7 +106,7 @@ def site_settings(db, settings):@pytest.fixture-def cart(db): # pylint: disable=W0613+def cart(db):return Cart.objects.create()diff --git a/tests/test_cart.py b/tests/test_cart.pyindex e2ed88edfe..44eebbca68 100644--- a/tests/test_cart.py+++ b/tests/test_cart.py@@ -19,7 +19,7 @@ from saleor.checkout.views import update_cart_line, clear_cartfrom saleor.core.exceptions import InsufficientStockfrom saleor.core.utils.taxes import ZERO_TAXED_MONEYfrom saleor.discount.models import Sale-from saleor.shipping.utils import shipping_price_estimate+from saleor.shipping.utils import get_shipping_price_estimate@pytest.fixture()@@ -628,7 +628,7 @@ def test_get_or_create_db_cart(customer_user, db, rf):def test_get_cart_data(request_cart_with_item, shipping_zone, vatlayer):cart = request_cart_with_item- shipment_option = shipping_price_estimate(+ shipment_option = get_shipping_price_estimate(cart.get_subtotal().gross, cart.get_total_weight(), 'PL', vatlayer)cart_data = utils.get_cart_data(cart, shipment_option, 'USD', None, vatlayer)@@ -640,7 +640,7 @@ def test_get_cart_data(request_cart_with_item, shipping_zone, vatlayer):def test_get_cart_data_no_shipping(request_cart_with_item, vatlayer):cart = request_cart_with_item- shipment_option = shipping_price_estimate(+ shipment_option = get_shipping_price_estimate(cart.get_subtotal().gross, cart.get_total_weight(), 'PL', vatlayer)cart_data = utils.get_cart_data(cart, shipment_option, 'USD', None, vatlayer)diff --git a/tests/test_checkout.py b/tests/test_checkout.pyindex 5a4f3be94f..c30865058b 100644--- a/tests/test_checkout.py+++ b/tests/test_checkout.py@@ -2,30 +2,141 @@ import datetimefrom unittest.mock import Mock, patchimport pytest+from django.urls import reversefrom django_countries.fields import Countryfrom freezegun import freeze_time+from measurement.measures import Massfrom prices import Money, TaxedMoney-from saleor.account.models import Addressfrom saleor.checkout import viewsfrom saleor.checkout.forms import CartVoucherFormfrom saleor.checkout.utils import (add_variant_to_cart, change_billing_address_in_cart,- change_shipping_address_in_cart, create_order, get_cart_data_for_checkout,+ change_shipping_address_in_cart, clear_shipping_method, create_order,+ get_cart_data_for_checkout,get_prices_of_products_in_discounted_categories, get_taxes_for_cart,get_voucher_discount_for_cart, get_voucher_for_cart,- recalculate_cart_discount, remove_voucher_from_cart)+ is_valid_shipping_method, recalculate_cart_discount,+ remove_voucher_from_cart, shipping_method_applicable, value_in_range)from saleor.core.exceptions import InsufficientStockfrom saleor.core.utils.taxes import (ZERO_MONEY, ZERO_TAXED_MONEY, get_taxes_for_country)from saleor.discount import DiscountValueType, VoucherTypefrom saleor.discount.models import NotApplicable, Voucherfrom saleor.product.models import Category+from saleor.shipping import ShippingMethodTypefrom .utils import compare_taxes, get_redirect_location+ 'minimum, maximum, value, result',+ (+ (10, None, 1500, True),+ (10, 20, 15, True),+ (10, 20, 20, True),+ (10, 20, 10, True),+ (10, 20, 9, False),+ (10, 21, 9, False)))+def test_value_in_range(minimum, maximum, value, result):+ assert result == value_in_range(minimum, maximum, value)+++ 'weight, minimum_order_weight, maximum_order_weight, result',+ (+ (Mass(kg=15), Mass(kg=10), Mass(kg=20), True),+ (Mass(kg=15), Mass(kg=15), Mass(kg=20), True),+ (Mass(kg=15), Mass(kg=10), Mass(kg=15), True),+ (Mass(kg=15), Mass(kg=10), None, True),+ (Mass(kg=26), Mass(kg=10), Mass(kg=25), False),+ (Mass(kg=9), Mass(kg=10), Mass(kg=15), False)))+def test_weight_shipping_method_applicable(+ weight, minimum_order_weight, maximum_order_weight, result):+ shipping_method = Mock(+ type=ShippingMethodType.WEIGHT_BASED,+ minimum_order_weight=minimum_order_weight,+ maximum_order_weight=maximum_order_weight)+ assert result == shipping_method_applicable(+ Money(0, 'USD'), weight, shipping_method)+++ 'price, minimum_order_price, maximum_order_price, result',+ (+ (Money(15, 'USD'), Money(10, 'USD'), Money(20, 'USD'), True),+ (Money(15, 'USD'), Money(15, 'USD'), Money(20, 'USD'), True),+ (Money(15, 'USD'), Money(10, 'USD'), Money(15, 'USD'), True),+ (Money(15, 'USD'), Money(10, 'USD'), None, True),+ (Money(26, 'USD'), Money(10, 'USD'), Money(25, 'USD'), False),+ (Money(9, 'USD'), Money(10, 'USD'), Money(15, 'USD'), False)))+def test_price_shipping_method_applicable(+ price, minimum_order_price, maximum_order_price, result):+ shipping_method = Mock(+ type=ShippingMethodType.PRICE_BASED,+ minimum_order_price=minimum_order_price,+ maximum_order_price=maximum_order_price)+ assert result == shipping_method_applicable(+ price, Mass(kg=0), shipping_method)+++def test_is_valid_shipping_method_no_shipping_method(vatlayer):+ cart = Mock(shipping_method=False)+ assert not is_valid_shipping_method(cart, vatlayer, None)+++@patch('saleor.checkout.utils.clear_shipping_method')+def test_is_valid_shipping_method_shipping_outside_the_shipping_zone(+ mock_clear_shipping_method, vatlayer):+ cart = Mock(+ shipping_address=Mock(country=Country('PL')),+ shipping_method=Mock(shipping_zone=Mock(countries=['DE'])))+ assert not is_valid_shipping_method(cart, vatlayer, None)+ mock_clear_shipping_method.assert_called_once_with(cart)+++@patch('saleor.checkout.utils.clear_shipping_method')+def test_is_valid_shipping_method_not_valid(+ mock_clear_shipping_method, vatlayer):+ cart = Mock(+ shipping_address=Mock(country=Country('PL')),+ shipping_method=Mock(+ shipping_zone=Mock(countries=['PL']),+ minimum_order_price=Money(10, 'USD'),+ maximum_order_price=None,+ type=ShippingMethodType.PRICE_BASED),+ get_total_weight=Mock(return_value=Mass(kg=0)),+ get_subtotal=Mock(+ return_value=TaxedMoney(+ gross=Money(5, 'USD'), net=Money(5, 'USD'))))+ assert not is_valid_shipping_method(cart, vatlayer, None)+ mock_clear_shipping_method.assert_called_once_with(cart)+++def test_is_valid_shipping_method(vatlayer):+ cart = Mock(+ shipping_address=Mock(country=Country('PL')),+ shipping_method=Mock(+ shipping_zone=Mock(countries=['PL']),+ minimum_order_price=Money(10, 'USD'),+ maximum_order_price=None,+ type=ShippingMethodType.PRICE_BASED),+ get_total_weight=Mock(return_value=Mass(kg=0)),+ get_subtotal=Mock(+ return_value=TaxedMoney(+ gross=Money(15, 'USD'), net=Money(15, 'USD'))))+ assert is_valid_shipping_method(cart, vatlayer, None)+++def test_clear_shipping_method(cart, shipping_method):+ cart.shipping_method = shipping_method+ cart.save()+ clear_shipping_method(cart)+ cart.refresh_from_db()+ assert not cart.shipping_method++@pytest.mark.parametrize('cart_length, is_shipping_required, redirect_url', [(0, True, reverse('cart:index')),(0, False, reverse('cart:index')),@@ -505,7 +616,9 @@ def test_get_discount_for_cart_value_voucher(type=VoucherType.VALUE,discount_value_type=discount_type,discount_value=discount_value,- min_amount_spent=Money(min_amount_spent, 'USD') if min_amount_spent is not None else None)+ min_amount_spent=(+ Money(min_amount_spent, 'USD')+ if min_amount_spent is not None else None))subtotal = TaxedMoney(net=Money(total, 'USD'), gross=Money(total, 'USD'))cart = Mock(get_subtotal=Mock(return_value=subtotal))discount = get_voucher_discount_for_cart(voucher, cart)@@ -539,20 +652,17 @@ def test_get_discount_for_cart_shipping_voucher(subtotal = TaxedMoney(net=Money(100, 'USD'), gross=Money(100, 'USD'))shipping_total = TaxedMoney(net=Money(shipping_cost, 'USD'), gross=Money(shipping_cost, 'USD'))- #FIXME below should be the cart not the mockcart = Mock(get_subtotal=Mock(return_value=subtotal),is_shipping_required=Mock(return_value=True),shipping_method=Mock(- price=Money(shipping_cost, 'USD'),- country_code=shipping_country_code,- get_total_price=Mock(return_value=shipping_total)))+ get_total_price=Mock(return_value=shipping_total)),+ shipping_address=Mock(country=Country(shipping_country_code)))voucher = Voucher(code='unique', type=VoucherType.SHIPPING,discount_value_type=discount_type,discount_value=discount_value,- countries=countries,- min_amount_spent=None)+ countries=countries)discount = get_voucher_discount_for_cart(voucher, cart)assert discount == Money(expected_value, 'USD')@@ -573,14 +683,13 @@ def test_get_discount_for_cart_shipping_voucher(DiscountValueType.FIXED, [], 5, Money(2, 'USD'),'This offer is only valid for orders over $5.00.')])def test_get_discount_for_cart_shipping_voucher_not_applicable(- is_shipping_required, shipping_method, discount_value, cart_with_item,+ is_shipping_required, shipping_method, discount_value,discount_type, countries, min_amount_spent, subtotal, error_msg):- variant = cart_with_item.lines.first().variant- variant.price_override = subtotal- variant.save()- cart_with_item.is_shipping_required = is_shipping_required- cart_with_item.shipping_method = shipping_method- cart_with_item.save()+ subtotal_price = TaxedMoney(net=subtotal, gross=subtotal)+ cart = Mock(+ get_subtotal=Mock(return_value=subtotal_price),+ is_shipping_required=Mock(return_value=is_shipping_required),+ shipping_method=shipping_method)voucher = Voucher(code='unique', type=VoucherType.SHIPPING,discount_value_type=discount_type,@@ -590,7 +699,7 @@ def test_get_discount_for_cart_shipping_voucher_not_applicable(if min_amount_spent is not None else None),countries=countries)with pytest.raises(NotApplicable) as e:- get_voucher_discount_for_cart(voucher, cart_with_item)+ get_voucher_discount_for_cart(voucher, cart)assert str(e.value) == error_msgdiff --git a/tests/test_shipping.py b/tests/test_shipping.pyindex 86f2fdedf2..a6672d4665 100644--- a/tests/test_shipping.py+++ b/tests/test_shipping.py@@ -99,7 +99,7 @@ def test_applicable_shipping_methods_country_code_outside_shipping_zone(assert method not in result-def test_applicable_shipping_methods_proper_shipping_method_type(+def test_applicable_shipping_methods_inproper_shipping_method_type(shipping_zone):"""Case when shipping suits the price requirements of the weight typeshipping method and the other way around.