Skip to content

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

Add some missing tests

Anna Siwikc2d1ef6b7ed6
diff --git a/saleor/account/models.py b/saleor/account/models.py
index 24220ea26e..614d186d1e 100644
--- a/saleor/account/models.py
+++ b/saleor/account/models.py
@@ -129,8 +129,7 @@ class User(PermissionsMixin, AbstractBaseUser):
def get_short_name(self):
return self.email
- @property
- def ajax_label(self):
+ def get_ajax_label(self):
address = self.default_billing_address
if address:
return '%s %s (%s)' % (
diff --git a/saleor/checkout/core.py b/saleor/checkout/core.py
index ab394acadb..a1c3fa5f9e 100644
--- a/saleor/checkout/core.py
+++ b/saleor/checkout/core.py
@@ -14,7 +14,7 @@ from ..account.utils import store_user_address
from ..cart.models import Cart
from ..cart.utils import get_or_empty_db_cart
from ..core import analytics
-from ..core.utils import ZERO_TAXED_MONEY, get_taxes_for_country
+from ..core.utils.taxes import ZERO_TAXED_MONEY
from ..discount.models import NotApplicable, Voucher
from ..discount.utils import increase_voucher_usage
from ..order.models import Order
diff --git a/saleor/core/templatetags/taxed_prices.py b/saleor/core/templatetags/taxed_prices.py
index bf90d84b2c..daf4cf06d4 100644
--- a/saleor/core/templatetags/taxed_prices.py
+++ b/saleor/core/templatetags/taxed_prices.py
@@ -1,7 +1,7 @@
from django import template
from prices import MoneyRange, TaxedMoney, TaxedMoneyRange
-from ...core.utils import DEFAULT_TAX_RATE_NAME
+from ...core.utils.taxes import DEFAULT_TAX_RATE_NAME
register = template.Library()
diff --git a/saleor/core/utils/__init__.py b/saleor/core/utils/__init__.py
index 19783833c1..48f42a96a9 100644
--- a/saleor/core/utils/__init__.py
+++ b/saleor/core/utils/__init__.py
@@ -17,17 +17,12 @@ from django_prices_openexchangerates import exchange_currency
from django_prices_vatlayer.utils import (
get_tax_rates_for_country, get_tax_for_rate)
from geolite2 import geolite2
-from prices import Money, MoneyRange, TaxedMoney, TaxedMoneyRange
+from prices import MoneyRange
from versatileimagefield.image_warmer import VersatileImageFieldWarmer
from ...account.models import User
from ...core.i18n import COUNTRY_CODE_CHOICES
-
-ZERO_TAXED_MONEY = TaxedMoney(
- net=Money(0, settings.DEFAULT_CURRENCY),
- gross=Money(0, settings.DEFAULT_CURRENCY))
-
-DEFAULT_TAX_RATE_NAME = 'standard'
+from ...core.utils.taxes import DEFAULT_TAX_RATE_NAME
georeader = geolite2.reader()
logger = logging.getLogger(__name__)
@@ -121,29 +116,6 @@ def get_taxes_for_country(country):
return taxes
-def apply_tax_to_price(taxes, rate_name, base):
- if not taxes or not rate_name:
- # Naively convert Money to TaxedMoney for consistency with price
- # handling logic across the codebase, passthrough other money types
- if isinstance(base, Money):
- return TaxedMoney(net=base, gross=base)
- if isinstance(base, MoneyRange):
- return TaxedMoneyRange(
- apply_tax_to_price(taxes, rate_name, base.start),
- apply_tax_to_price(taxes, rate_name, base.stop))
- if isinstance(base, (TaxedMoney, TaxedMoneyRange)):
- return base
- raise TypeError('Unknown base for flat_tax: %r' % (base,))
-
- if rate_name in taxes:
- tax_to_apply = taxes[rate_name]['tax']
- else:
- tax_to_apply = taxes[DEFAULT_TAX_RATE_NAME]['tax']
-
- keep_gross = Site.objects.get_current().settings.include_taxes_in_prices
- return tax_to_apply(base, keep_gross=keep_gross)
-
-
def to_local_currency(price, currency):
if not settings.OPENEXCHANGERATES_API_KEY:
return None
diff --git a/saleor/core/utils/random_data.py b/saleor/core/utils/random_data.py
index e00a5b7f62..e05bf8e376 100644
--- a/saleor/core/utils/random_data.py
+++ b/saleor/core/utils/random_data.py
@@ -17,12 +17,13 @@ from prices import Money
from ...account.models import Address, User
from ...account.utils import store_user_address
from ...core.utils import get_taxes_for_country
+from ...core.utils.taxes import get_tax_rate_by_name
from ...core.utils.text import strip_html_and_truncate
from ...discount import DiscountValueType, VoucherType
from ...discount.models import Sale, Voucher
from ...menu.models import Menu
from ...order.models import Fulfillment, Order, Payment
-from ...order.utils import get_tax_rate_by_name, update_order_status
+from ...order.utils import update_order_status
from ...page.models import Page
from ...product.models import (
AttributeChoiceValue, Category, Collection, Product, ProductAttribute,
diff --git a/saleor/core/utils/taxes.py b/saleor/core/utils/taxes.py
new file mode 100644
index 0000000000..660710ebbf
--- /dev/null
+++ b/saleor/core/utils/taxes.py
@@ -0,0 +1,56 @@
+from django.conf import settings
+from django.contrib.sites.models import Site
+from django_countries.fields import Country
+from prices import Money, MoneyRange, TaxedMoney, TaxedMoneyRange
+
+DEFAULT_TAX_RATE_NAME = 'standard'
+
+ZERO_TAXED_MONEY = TaxedMoney(
+ net=Money(0, settings.DEFAULT_CURRENCY),
+ gross=Money(0, settings.DEFAULT_CURRENCY))
+
+
+def apply_tax_to_price(taxes, rate_name, base):
+ if not taxes or not rate_name:
+ # Naively convert Money to TaxedMoney for consistency with price
+ # handling logic across the codebase, passthrough other money types
+ if isinstance(base, Money):
+ return TaxedMoney(net=base, gross=base)
+ if isinstance(base, MoneyRange):
+ return TaxedMoneyRange(
+ apply_tax_to_price(taxes, rate_name, base.start),
+ apply_tax_to_price(taxes, rate_name, base.stop))
+ if isinstance(base, (TaxedMoney, TaxedMoneyRange)):
+ return base
+ raise TypeError('Unknown base for flat_tax: %r' % (base,))
+
+ if rate_name in taxes:
+ tax_to_apply = taxes[rate_name]['tax']
+ else:
+ tax_to_apply = taxes[DEFAULT_TAX_RATE_NAME]['tax']
+
+ keep_gross = Site.objects.get_current().settings.include_taxes_in_prices
+ return tax_to_apply(base, keep_gross=keep_gross)
+
+
+def get_taxes_for_address(address):
+ from . import get_taxes_for_country
+ """Return proper taxes for address or default country."""
+ if address is not None:
+ country = address.country
+ else:
+ country = Country(settings.DEFAULT_COUNTRY)
+
+ return get_taxes_for_country(country)
+
+
+def get_tax_rate_by_name(rate_name, taxes=None):
+ """Return value of tax rate for current taxes."""
+ if not taxes or not rate_name:
+ tax_rate = 0
+ elif rate_name in taxes:
+ tax_rate = taxes[rate_name]['value']
+ else:
+ tax_rate = taxes[DEFAULT_TAX_RATE_NAME]['value']
+
+ return tax_rate
diff --git a/saleor/dashboard/customer/views.py b/saleor/dashboard/customer/views.py
index 64be2c03f5..9737897429 100644
--- a/saleor/dashboard/customer/views.py
+++ b/saleor/dashboard/customer/views.py
@@ -95,7 +95,7 @@ def ajax_users_list(request):
Q(email__icontains=search_query))
users = [
- {'id': user.pk, 'text': user.ajax_label} for user in queryset]
+ {'id': user.pk, 'text': user.get_ajax_label()} for user in queryset]
return JsonResponse({'results': users})
diff --git a/saleor/dashboard/order/forms.py b/saleor/dashboard/order/forms.py
index 3aa8f5b13e..8930158664 100644
--- a/saleor/dashboard/order/forms.py
+++ b/saleor/dashboard/order/forms.py
@@ -11,7 +11,7 @@ from ...account.i18n import (
from ...account.models import User
from ...cart.forms import QuantityField
from ...core.exceptions import InsufficientStock
-from ...core.utils import ZERO_TAXED_MONEY
+from ...core.utils.taxes import ZERO_TAXED_MONEY
from ...discount.models import Voucher
from ...discount.utils import decrease_voucher_usage, increase_voucher_usage
from ...order import CustomPaymentChoices, OrderStatus
@@ -113,7 +113,7 @@ class OrderCustomerForm(forms.ModelForm):
super().__init__(*args, **kwargs)
user = self.instance.user
if user:
- self.fields['user'].set_initial(user, label=user.ajax_label)
+ self.fields['user'].set_initial(user, label=user.get_ajax_label())
def clean(self):
cleaned_data = super().clean()
@@ -169,8 +169,7 @@ class OrderShippingForm(forms.ModelForm):
method = self.instance.shipping_method
if method:
- method_field.set_initial(
- method, label=method.get_ajax_label(self.taxes))
+ method_field.set_initial(method, label=method.get_ajax_label())
if self.instance.shipping_address:
country_code = self.instance.shipping_address.country.code
diff --git a/saleor/dashboard/order/views.py b/saleor/dashboard/order/views.py
index 0440f3437b..f50ad08434 100644
--- a/saleor/dashboard/order/views.py
+++ b/saleor/dashboard/order/views.py
@@ -15,14 +15,14 @@ from django_prices.templatetags import prices_i18n
from payments import PaymentStatus
from ...core.exceptions import InsufficientStock
-from ...core.utils import ZERO_TAXED_MONEY, get_paginator_items
+from ...core.utils import get_paginator_items
+from ...core.utils.taxes import ZERO_TAXED_MONEY, get_taxes_for_address
from ...order import CustomPaymentChoices, OrderStatus
from ...order.emails import (
send_fulfillment_confirmation, send_fulfillment_update,
send_order_confirmation)
from ...order.models import Fulfillment, FulfillmentLine, Order, OrderNote
-from ...order.utils import (
- get_taxes_for_order, update_order_prices, update_order_status)
+from ...order.utils import update_order_prices, update_order_status
from ...shipping.models import ShippingMethodCountry
from ..views import staff_member_required
from .filters import OrderFilter
@@ -297,7 +297,7 @@ def orderline_cancel(request, order_pk, line_pk):
def add_variant_to_order(request, order_pk):
"""Add variant in given quantity to an order."""
order = get_object_or_404(Order.objects.drafts(), pk=order_pk)
- taxes = get_taxes_for_order(order)
+ taxes = get_taxes_for_address(order.shipping_address)
form = AddVariantToOrderForm(
request.POST or None, order=order, discounts=request.discounts,
taxes=taxes)
@@ -411,7 +411,7 @@ def order_customer_remove(request, order_pk):
@permission_required('order.edit_order')
def order_shipping_edit(request, order_pk):
order = get_object_or_404(Order.objects.drafts(), pk=order_pk)
- taxes = get_taxes_for_order(order)
+ taxes = get_taxes_for_address(order.shipping_address)
form = OrderShippingForm(request.POST or None, instance=order, taxes=taxes)
status = 200
if form.is_valid():
@@ -728,8 +728,7 @@ def ajax_order_shipping_methods_list(request, order_pk):
Q(shipping_method__name__icontains=search_query) |
Q(price__icontains=search_query))
- taxes = get_taxes_for_order(order)
shipping_methods = [
- {'id': method.pk, 'text': method.get_ajax_label(taxes=taxes)}
+ {'id': method.pk, 'text': method.get_ajax_label()}
for method in queryset]
return JsonResponse({'results': shipping_methods})
diff --git a/saleor/dashboard/product/forms.py b/saleor/dashboard/product/forms.py
index cf63c5f1c6..6893b20c98 100644
--- a/saleor/dashboard/product/forms.py
+++ b/saleor/dashboard/product/forms.py
@@ -13,7 +13,7 @@ from mptt.forms import TreeNodeChoiceField
from . import ProductBulkAction
from ...core.i18n import VAT_RATE_TYPE_TRANSLATIONS
-from ...core.utils import DEFAULT_TAX_RATE_NAME
+from ...core.utils.taxes import DEFAULT_TAX_RATE_NAME
from ...product.models import (
AttributeChoiceValue, Category, Collection, Product, ProductAttribute,
ProductImage, ProductType, ProductVariant, VariantImage)
diff --git a/saleor/discount/utils.py b/saleor/discount/utils.py
index 97fc096b6b..370ec8bba1 100644
--- a/saleor/discount/utils.py
+++ b/saleor/discount/utils.py
@@ -4,7 +4,7 @@ from django.utils.translation import pgettext
from prices import Money
from . import VoucherApplyToProduct
-from ..core.utils import ZERO_TAXED_MONEY
+from ..core.utils.taxes import ZERO_TAXED_MONEY
from .models import NotApplicable
diff --git a/saleor/order/models.py b/saleor/order/models.py
index bb3dc491df..d195e701f8 100644
--- a/saleor/order/models.py
+++ b/saleor/order/models.py
@@ -17,7 +17,8 @@ from prices import Money, TaxedMoney
from . import FulfillmentStatus, OrderStatus
from ..account.models import Address
from ..core.models import BaseNote
-from ..core.utils import ZERO_TAXED_MONEY, build_absolute_uri
+from ..core.utils import build_absolute_uri
+from ..core.utils.taxes import ZERO_TAXED_MONEY
from ..discount.models import Voucher
from ..product.models import ProductVariant
from ..shipping.models import ShippingMethodCountry
@@ -302,9 +303,7 @@ class Payment(BasePayment):
gross=Money(self.total, self.currency))
def get_captured_price(self):
- return TaxedMoney(
- net=Money(self.captured_amount, self.currency),
- gross=Money(self.captured_amount, self.currency))
+ return Money(self.captured_amount, self.currency)
class OrderHistoryEntry(models.Model):
diff --git a/saleor/order/utils.py b/saleor/order/utils.py
index 65f155ee25..d5462904ff 100644
--- a/saleor/order/utils.py
+++ b/saleor/order/utils.py
@@ -3,12 +3,11 @@ from functools import wraps
from django.conf import settings
from django.db.models import F
from django.shortcuts import get_object_or_404, redirect
-from django_countries.fields import Country
from prices import Money
from ..account.utils import store_user_address
from ..core.exceptions import InsufficientStock
-from ..core.utils import DEFAULT_TAX_RATE_NAME, get_taxes_for_country
+from ..core.utils.taxes import get_tax_rate_by_name, get_taxes_for_address
from ..dashboard.order.utils import get_voucher_discount_for_order
from ..order import FulfillmentStatus, OrderStatus
from ..order.models import OrderLine
@@ -76,7 +75,7 @@ def recalculate_order(order, **kwargs):
def update_order_prices(order, discounts):
"""Update prices in order with given discounts and proper taxes."""
- taxes = get_taxes_for_order(order)
+ taxes = get_taxes_for_address(order.shipping_address)
for line in order:
if line.variant:
@@ -148,29 +147,6 @@ def attach_order_to_user(order, user):
order.save(update_fields=['user'])
-def get_tax_rate_by_name(rate_name, taxes=None):
- """Return value of tax rate for current taxes."""
- if not taxes or not rate_name:
- tax_rate = 0
- elif rate_name in taxes:
- tax_rate = taxes[rate_name]['value']
- else:
- tax_rate = taxes[DEFAULT_TAX_RATE_NAME]['value']
-
- return tax_rate
-
-
-def get_taxes_for_order(order):
- """Return proper taxes for order.
- Taxes are based on shipping address or default country."""
- if order.shipping_address:
- country = order.shipping_address.country
- else:
- country = Country(settings.DEFAULT_COUNTRY)
-
- return get_taxes_for_country(country)
-
-
def add_variant_to_order(
order, variant, total_quantity, discounts=None, taxes=None,
add_to_existing=True):
diff --git a/saleor/product/models.py b/saleor/product/models.py
index 9657a767c8..2ed35cbec7 100644
--- a/saleor/product/models.py
+++ b/saleor/product/models.py
@@ -19,7 +19,7 @@ from text_unidecode import unidecode
from versatileimagefield.fields import PPOIField, VersatileImageField
from ..core.exceptions import InsufficientStock
-from ..core.utils import apply_tax_to_price, DEFAULT_TAX_RATE_NAME
+from ..core.utils.taxes import DEFAULT_TAX_RATE_NAME, apply_tax_to_price
from ..discount.utils import calculate_discounted_price
from ..seo.models import SeoModel
diff --git a/saleor/product/utils/costs.py b/saleor/product/utils/costs.py
index b3bdd95af9..695d1dfce9 100644
--- a/saleor/product/utils/costs.py
+++ b/saleor/product/utils/costs.py
@@ -1,7 +1,7 @@
from django.conf import settings
from prices import Money, MoneyRange
-from ...core.utils import ZERO_TAXED_MONEY
+from ...core.utils.taxes import ZERO_TAXED_MONEY
def get_product_costs_data(product):
diff --git a/saleor/product/utils/variants_picker.py b/saleor/product/utils/variants_picker.py
index 7b48b57c5e..ddc05a6cfe 100644
--- a/saleor/product/utils/variants_picker.py
+++ b/saleor/product/utils/variants_picker.py
@@ -4,7 +4,7 @@ from django.contrib.sites.models import Site
from django_prices.templatetags import prices_i18n
from ...core.utils import to_local_currency
-from ...order.utils import get_tax_rate_by_name
+from ...core.utils.taxes import get_tax_rate_by_name
from ...seo.schema.product import variant_json_ld
from .availability import get_availability
diff --git a/saleor/shipping/models.py b/saleor/shipping/models.py
index 2d459552d8..f8327b7f52 100644
--- a/saleor/shipping/models.py
+++ b/saleor/shipping/models.py
@@ -97,7 +97,7 @@ class ShippingMethodCountry(models.Model):
def get_total_price(self, taxes=None):
return get_taxed_shipping_price(self.price, taxes)
- def get_ajax_label(self, taxes=None):
- price_html = format_money(self.get_total_price(taxes).gross)
+ def get_ajax_label(self):
+ price_html = format_money(self.price)
label = mark_safe('%s %s' % (self.shipping_method, price_html))
return label
diff --git a/saleor/shipping/utils.py b/saleor/shipping/utils.py
index 9d7142ebb9..3661e74e83 100644
--- a/saleor/shipping/utils.py
+++ b/saleor/shipping/utils.py
@@ -1,7 +1,7 @@
from django.contrib.sites.models import Site
from prices import MoneyRange
-from ..core.utils import apply_tax_to_price, DEFAULT_TAX_RATE_NAME
+from ..core.utils.taxes import DEFAULT_TAX_RATE_NAME, apply_tax_to_price
def get_taxed_shipping_price(price, taxes):
diff --git a/tests/conftest.py b/tests/conftest.py
index 572444d134..ec1f2f304e 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -368,7 +368,8 @@ def voucher(db): # pylint: disable=W0613
@pytest.fixture()
-def order_with_lines(order, product_type, default_category, shipping_method):
+def order_with_lines(
+ order, product_type, default_category, shipping_method, taxes):
product = Product.objects.create(
name='Test product', price=Money('10.00', 'USD'),
product_type=product_type, category=default_category)
@@ -376,13 +377,14 @@ def order_with_lines(order, product_type, default_category, shipping_method):
product=product, sku='SKU_A', cost_price=Money(1, 'USD'), quantity=0,
quantity_allocated=0)
order.lines.create(
- product_name=product.name,
- product_sku='SKU_%d' % (product.pk,),
- is_shipping_required=product.product_type.is_shipping_required,
+ product_name=variant.display_product(),
+ product_sku=variant.sku,
+ is_shipping_required=variant.is_shipping_required(),
quantity=1,
- unit_price_net=Decimal('10.00'),
- unit_price_gross=Decimal('10.00'),
- variant=variant)
+ variant=variant,
+ unit_price=variant.get_price(taxes=taxes),
+ tax_rate=taxes['standard']['value'])
+
product = Product.objects.create(
name='Test product 2', price=Money('20.00', 'USD'),
product_type=product_type, category=default_category)
@@ -390,27 +392,24 @@ def order_with_lines(order, product_type, default_category, shipping_method):
product=product, sku='SKU_B', cost_price=Money(2, 'USD'), quantity=0,
quantity_allocated=0)
order.lines.create(
- product_name=product.name,
- product_sku='SKU_%d' % (product.pk,),
- is_shipping_required=product.product_type.is_shipping_required,
+ product_name=variant.display_product(),
+ product_sku=variant.sku,
+ is_shipping_required=variant.is_shipping_required(),
quantity=1,
- unit_price_net=Decimal('20.00'),
- unit_price_gross=Decimal('20.00'),
- variant=variant)
- Product.objects.create(
- name='Test product 3', price=Money('30.00', 'USD'),
- product_type=product_type, category=default_category)
+ variant=variant,
+ unit_price=variant.get_price(taxes=taxes),
+ tax_rate=taxes['standard']['value'])
order.shipping_address = order.billing_address.get_copy()
order.shipping_method_name = shipping_method.name
method = shipping_method.price_per_country.get()
order.shipping_method = method
- order.shipping_price = method.get_total_price()
+ order.shipping_price = method.get_total_price(taxes)
order.save()
- recalculate_order(order)
- order.refresh_from_db()
recalculate_order(order)
+
+ order.refresh_from_db()
return order
@@ -501,7 +500,8 @@ def payment_preauth(order_with_lines):
return order_with_lines.payments.create(
variant='default', status=PaymentStatus.PREAUTH,
fraud_status=FraudStatus.ACCEPT, currency='USD',
- total=order_with_lines.total_gross.amount)
+ total=order_with_lines.total.gross.amount,
+ tax=order_with_lines.total.tax.amount)
@pytest.fixture()
@@ -725,4 +725,19 @@ def taxes(tax_rates):
def vatlayer(db, settings, tax_rates, taxes):
settings.VATLAYER_ACCESS_KEY = 'enablevatlayer'
VAT.objects.create(country_code='PL', data=tax_rates)
+
+ tax_rates_2 = {
+ 'standard_rate': 19,
+ 'reduced_rates': {
+ 'admission to cultural events': 7,
+ 'admission to entertainment events': 7,
+ 'books': 7,
+ 'foodstuffs': 7,
+ 'hotels': 7,
+ 'medical': 7,
+ 'newspapers': 7,
+ 'passenger transport': 7
+ }
+ }
+ VAT.objects.create(country_code='DE', data=tax_rates_2)
return taxes
diff --git a/tests/dashboard/test_order.py b/tests/dashboard/test_order.py
index b603b4861f..2d2e1d4db2 100644
--- a/tests/dashboard/test_order.py
+++ b/tests/dashboard/test_order.py
@@ -1,13 +1,13 @@
-from unittest.mock import patch
+from unittest.mock import Mock
import pytest
from django.conf import settings
from django.urls import reverse
from payments import PaymentStatus
-from prices import Money, TaxedMoney
+from prices import Money
from tests.utils import get_form_errors, get_redirect_location
-from saleor.core.utils import ZERO_TAXED_MONEY
+from saleor.core.utils.taxes import ZERO_TAXED_MONEY
from saleor.dashboard.order.forms import ChangeQuantityForm, OrderNoteForm
from saleor.dashboard.order.utils import (
fulfill_order_line, remove_customer_from_order, save_address_in_order,
@@ -37,7 +37,7 @@ def test_view_capture_order_payment_preauth(
'amount': str(order.total.gross.amount)})
assert response.status_code == 302
assert order.payments.last().status == PaymentStatus.CONFIRMED
- assert order.payments.last().get_captured_price() == order.total
+ assert order.payments.last().get_captured_price() == order.total.gross
@pytest.mark.integration
@@ -153,8 +153,7 @@ def test_view_refund_order_payment_confirmed(
'amount': str(payment_confirmed.captured_amount)})
assert response.status_code == 302
assert order.payments.last().status == PaymentStatus.REFUNDED
- assert order.payments.last().get_captured_price() == TaxedMoney(
- net=Money(0, 'USD'), gross=Money(0, 'USD'))
+ assert order.payments.last().get_captured_price() == Money(0, 'USD')
@pytest.mark.integration
@@ -274,8 +273,7 @@ def test_view_release_order_payment_preauth(
'csrfmiddlewaretoken': 'hello'})
assert response.status_code == 302
assert order.payments.last().status == PaymentStatus.REFUNDED
- assert order.payments.last().get_captured_price() == TaxedMoney(
- net=Money(0, 'USD'), gross=Money(0, 'USD'))
+ assert order.payments.last().get_captured_price() == Money(0, 'USD')
@pytest.mark.integration
@@ -610,14 +608,14 @@ def test_view_add_variant_to_order(
assert line.quantity == line_quantity_before + added_quantity
-@patch('saleor.dashboard.order.forms.send_note_confirmation')
-def test_note_form_sent_email(
- mock_send_note_confirmation, order_with_lines):
- order = order_with_lines
- note = OrderNote(order=order, user=order.user)
+def test_note_form_sent_email(monkeypatch, order_with_lines):
+ mock_send_mail = Mock(return_value=None)
+ monkeypatch.setattr(
+ 'saleor.dashboard.order.forms.send_note_confirmation', mock_send_mail)
+ note = OrderNote(order=order_with_lines, user=order_with_lines.user)
form = OrderNoteForm({'content': 'test_note'}, instance=note)
form.send_confirmation_email()
- assert mock_send_note_confirmation.called_once()
+ assert mock_send_mail.called_once()
def test_fulfill_order_line(order_with_lines):
diff --git a/tests/dashboard/test_product.py b/tests/dashboard/test_product.py
index 0714b994b4..d8376acaf6 100644
--- a/tests/dashboard/test_product.py
+++ b/tests/dashboard/test_product.py
@@ -419,9 +419,12 @@ def test_view_invalid_reorder_product_images(
assert 'ordered_images' in resp_decoded['error']
-@patch('saleor.dashboard.product.forms.create_product_thumbnails.delay')
def test_view_product_image_add(
- mock_create_thumbnails, admin_client, product_with_image):
+ monkeypatch, admin_client, product_with_image):
+ mock_create_thumbnails = Mock(return_value=None)
+ monkeypatch.setattr(
+ 'saleor.dashboard.product.forms.create_product_thumbnails.delay',
+ mock_create_thumbnails)
assert len(ProductImage.objects.all()) == 1
assert len(product_with_image.images.all()) == 1
url = reverse(
@@ -442,9 +445,12 @@ def test_view_product_image_add(
mock_create_thumbnails.assert_called_once_with(images[1].pk)
-@patch('saleor.dashboard.product.forms.create_product_thumbnails.delay')
def test_view_product_image_edit_same_image_add_description(
- mock_create_thumbnails, admin_client, product_with_image):
+ monkeypatch, admin_client, product_with_image):
+ mock_create_thumbnails = Mock(return_value=None)
+ monkeypatch.setattr(
+ 'saleor.dashboard.product.forms.create_product_thumbnails.delay',
+ mock_create_thumbnails)
assert len(product_with_image.images.all()) == 1
product_image = product_with_image.images.all()[0]
url = reverse(
@@ -463,9 +469,12 @@ def test_view_product_image_edit_same_image_add_description(
mock_create_thumbnails.assert_called_once_with(product_image.pk)
-@patch('saleor.dashboard.product.forms.create_product_thumbnails.delay')
def test_view_product_image_edit_new_image(
- mock_create_thumbnails, admin_client, product_with_image):
+ monkeypatch, admin_client, product_with_image):
+ mock_create_thumbnails = Mock(return_value=None)
+ monkeypatch.setattr(
+ 'saleor.dashboard.product.forms.create_product_thumbnails.delay',
+ mock_create_thumbnails)
assert len(product_with_image.images.all()) == 1
product_image = product_with_image.images.all()[0]
url = reverse(
diff --git a/tests/test_account.py b/tests/test_account.py
index 0ec1891ca9..5728e14478 100644
--- a/tests/test_account.py
+++ b/tests/test_account.py
@@ -200,17 +200,17 @@ def test_user_ajax_label(customer_user):
address = customer_user.default_billing_address
label = '%s %s (%s)' % (
address.first_name, address.last_name, customer_user.email)
- assert customer_user.ajax_label == label
+ assert customer_user.get_ajax_label() == label
def test_user_ajax_label_without_address(admin_user):
- assert admin_user.ajax_label == admin_user.email
+ assert admin_user.get_ajax_label() == admin_user.email
def test_ajax_users_list(admin_client, admin_user, customer_user):
users_list = [
- {'id': admin_user.pk, 'text': admin_user.ajax_label},
- {'id': customer_user.pk, 'text': customer_user.ajax_label}]
+ {'id': admin_user.pk, 'text': admin_user.get_ajax_label()},
+ {'id': customer_user.pk, 'text': customer_user.get_ajax_label()}]
url = reverse('dashboard:ajax-users-list')
response = admin_client.get(url, HTTP_X_REQUESTED_WITH='XMLHttpRequest')
diff --git a/tests/test_checkout.py b/tests/test_checkout.py
index 9c499fea7b..34767da6b8 100644
--- a/tests/test_checkout.py
+++ b/tests/test_checkout.py
@@ -174,9 +174,9 @@ def test_index_view(checkout, cart, status_code, url, rf, monkeypatch):
assert response.url == url
-def test_checkout_discount(checkout_with_items, sale, taxes):
+def test_checkout_discount(checkout_with_items, sale, vatlayer):
checkout_with_items.discounts = (sale,)
- checkout_with_items.taxes = taxes
+ checkout_with_items.taxes = vatlayer
assert checkout_with_items.get_total() == TaxedMoney(
net=Money('4.07', 'USD'), gross=Money('5.00', 'USD'))
diff --git a/tests/test_core.py b/tests/test_core.py
index c87a2cfed3..d969b569e3 100644
--- a/tests/test_core.py
+++ b/tests/test_core.py
@@ -10,8 +10,10 @@ from prices import Money, MoneyRange, TaxedMoney, TaxedMoneyRange
from saleor.account.models import Address, User
from saleor.core.storages import S3MediaStorage
from saleor.core.utils import (
- Country, apply_tax_to_price, create_superuser, create_thumbnails,
- format_money, get_country_by_ip, get_currency_for_country, random_data)
+ Country, create_superuser, create_thumbnails, format_money,
+ get_country_by_ip, get_currency_for_country, get_taxes_for_country,
+ random_data)
+from saleor.core.utils.taxes import apply_tax_to_price, get_taxes_for_address
from saleor.core.utils.text import get_cleaner, strip_html
from saleor.discount.models import Sale, Voucher
from saleor.order.models import Order
@@ -320,3 +322,31 @@ def test_storages_not_setting_s3_bucket_domain(*_patches):
storage = S3MediaStorage()
assert storage.bucket_name == 'media-bucket'
assert storage.custom_domain is None
+
+
+def compare_taxes(taxes_1, taxes_2):
+ assert len(taxes_1) == len(taxes_2)
+
+ for rate_name, tax in taxes_1.items():
+ value_1 = tax['value']
+ value_2 = taxes_2.get(rate_name)['value']
+ assert value_1 == value_2
+
+
+def test_get_taxes_for_address(address, vatlayer):
+ taxes = get_taxes_for_address(address)
+ compare_taxes(taxes, vatlayer)
+
+
+def test_get_taxes_for_address_fallback_default(vatlayer):
+ taxes = get_taxes_for_address(None)
+ compare_taxes(taxes, vatlayer)
+
+
+def test_get_taxes_for_address_other_country(address, vatlayer):
+ address.country = 'DE'
+ address.save()
+ tax_rates = get_taxes_for_country(Country('DE'))
+
+ taxes = get_taxes_for_address(address)
+ compare_taxes(taxes, tax_rates)
diff --git a/tests/test_order.py b/tests/test_order.py
index c5d5315b56..c89cbe20c7 100644
--- a/tests/test_order.py
+++ b/tests/test_order.py
@@ -2,18 +2,20 @@ import json
from decimal import Decimal
from django.urls import reverse
+from django_countries.fields import Country
from payments import PaymentStatus
from prices import Money, TaxedMoney
from tests.utils import get_redirect_location
-from saleor.core.utils import DEFAULT_TAX_RATE_NAME
+from saleor.core.utils import get_taxes_for_country
+from saleor.core.utils.taxes import DEFAULT_TAX_RATE_NAME, get_tax_rate_by_name
from saleor.order import FulfillmentStatus, OrderStatus, models
from saleor.order.forms import OrderNoteForm
from saleor.order.models import Order
from saleor.order.utils import (
- add_variant_to_order, cancel_fulfillment, cancel_order,
- get_tax_rate_by_name, recalculate_order, restock_fulfillment_lines,
- restock_order_lines, update_order_status)
+ add_variant_to_order, cancel_fulfillment, cancel_order, recalculate_order,
+ restock_fulfillment_lines, restock_order_lines, update_order_prices,
+ update_order_status)
def test_total_setter():
@@ -71,6 +73,8 @@ def test_add_variant_to_order_adds_line_for_new_variant(
assert order.lines.count() == lines_before + 1
assert line.product_sku == variant.sku
assert line.quantity == 1
+ assert line.unit_price == TaxedMoney(
+ net=Money('8.13', 'USD'), gross=Money(10, 'USD'))
assert line.tax_rate == taxes[product.tax_rate]['value']
@@ -364,3 +368,26 @@ def test_ajax_order_shipping_methods_list_different_country(
assert response.status_code == 200
assert resp_decoded == {'results': shipping_methods_list}
+
+
+def test_update_order_prices(order_with_lines, vatlayer):
+ taxes = get_taxes_for_country(Country('DE'))
+ address = order_with_lines.shipping_address
+ address.country = 'DE'
+ address.save()
+
+ line_1 = order_with_lines.lines.first()
+ line_2 = order_with_lines.lines.last()
+ price_1 = line_1.variant.get_price(taxes=taxes)
+ price_2 = line_2.variant.get_price(taxes=taxes)
+ shipping_price = order_with_lines.shipping_method.get_total_price(taxes)
+
+ update_order_prices(order_with_lines, None)
+
+ line_1.refresh_from_db()
+ line_2.refresh_from_db()
+ assert line_1.unit_price == price_1
+ assert line_2.unit_price == price_2
+ assert order_with_lines.shipping_price == shipping_price
+ total = price_1 + price_2 + shipping_price
+ assert order_with_lines.total == total
diff --git a/tests/test_product.py b/tests/test_product.py
index e8c9cbc1bd..7e1d0ac988 100644
--- a/tests/test_product.py
+++ b/tests/test_product.py
@@ -555,3 +555,13 @@ def test_product_get_price_range_do_not_charge_taxes(
expected_price = TaxedMoney(
net=Money('5.00', 'USD'), gross=Money('5.00', 'USD'))
assert price == TaxedMoneyRange(start=expected_price, stop=expected_price)
+
+
+def test_variant_base_price(product):
+ variant = product.variants.get()
+ assert variant.base_price == product.price
+
+ variant.price_override = Money('15.00', 'USD')
+ variant.save()
+
+ assert variant.base_price == variant.price_override
diff --git a/tests/test_shipping.py b/tests/test_shipping.py
index d62d93fc60..8bcd6aa267 100644
--- a/tests/test_shipping.py
+++ b/tests/test_shipping.py
@@ -1,4 +1,5 @@
import pytest
+from mock import Mock
from prices import Money, TaxedMoney
from saleor.shipping.utils import get_taxed_shipping_price
@@ -17,3 +18,21 @@ def test_get_taxed_shipping_price(
shipping_price = get_taxed_shipping_price(price, taxes=vatlayer)
assert shipping_price == expected_price
+
+
+def test_shipping_get_total_price(monkeypatch, shipping_method, vatlayer):
+ method = shipping_method.price_per_country.get()
+ price = Money(10, 'USD')
+ taxed_price = TaxedMoney(
+ net=Money('8.13', 'USD'), gross=Money(10, 'USD'))
+ mock_get_price = Mock(return_value=taxed_price)
+ monkeypatch.setattr(
+ 'saleor.shipping.models.get_taxed_shipping_price', mock_get_price)
+ method.get_total_price(taxes=vatlayer)
+ mock_get_price.assert_called_once_with(price, vatlayer)
+
+
+def test_shipping_get_ajax_label(shipping_method):
+ method = shipping_method.price_per_country.get()
+ label = method.get_ajax_label()
+ assert label == 'DHL $10.00'