Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
More stylistic fixes
Patryk Zawadzki300899b514ab
diff --git a/.pylintrc b/.pylintrcindex d9211441ee..4c36c6986f 100644--- a/.pylintrc+++ b/.pylintrc@@ -2,4 +2,8 @@load-plugins=pylint_django[MESSAGES CONTROL]-disable = C0103, C0111, I0011, W0621+disable=C0103, C0111, I0011, W0621++[SIMILARITIES]+ignore-imports=yes+min-similarity-lines=8diff --git a/saleor/checkout/forms.py b/saleor/checkout/forms.pyindex 7cdbb7cb0f..a98e4e7d22 100644--- a/saleor/checkout/forms.py+++ b/saleor/checkout/forms.py@@ -116,8 +116,8 @@ class AnonymousUserBillingForm(forms.Form):class NoteForm(forms.Form):- """ Form to add a note to an order as it is- created for shop staff to see """+ """Form to add a note to an order."""+note = forms.CharField(max_length=250, required=False, strip=True, label=False)note.widget = forms.Textarea({'rows': 3})diff --git a/saleor/checkout/views/__init__.py b/saleor/checkout/views/__init__.pyindex 44d2c8997c..ed3e55aedb 100644--- a/saleor/checkout/views/__init__.py+++ b/saleor/checkout/views/__init__.py@@ -11,7 +11,7 @@ from .validators import (validate_cart, validate_shipping_address,validate_shipping_method, validate_is_shipping_required)from ..core import load_checkout-from ..forms import ShippingMethodForm, NoteForm+from ..forms import ShippingMethodFormfrom ...registration.forms import LoginFormdiff --git a/saleor/core/__init__.py b/saleor/core/__init__.pyindex 51c03d1771..a26d54fed4 100644--- a/saleor/core/__init__.py+++ b/saleor/core/__init__.py@@ -16,6 +16,7 @@ def check_session_caching(app_configs, **kwargs): # pragma: no covererrors.append(Warning('Session caching cannot work with locmem backend',- 'User sessions need to be globally shared, use a cache server like Redis.',+ 'User sessions need to be globally shared, use a cache server'+ ' like Redis.','saleor.W001'))return errorsdiff --git a/saleor/core/filters.py b/saleor/core/filters.pyindex a519de43bc..e22c654c13 100644--- a/saleor/core/filters.py+++ b/saleor/core/filters.py@@ -3,11 +3,12 @@ from django_filters import FilterSetclass SortedFilterSet(FilterSet):+ """Base class for filter sets used in dashboard views.++ Adds flag `is_bound_unsorted` to indicate if filter set has data from+ filters other than `sort_by` or `page`."""- Base class for filter sets used in dashboard views. Adds flag- is_bound_unsorted to indicate if FilterSet has data from filters- other than sort_by or page.- """+def __init__(self, data, *args, **kwargs):self.is_bound_unsorted = self.set_is_bound_unsorted(data)super(SortedFilterSet, self).__init__(data, *args, **kwargs)@@ -16,8 +17,10 @@ class SortedFilterSet(FilterSet):return any([key not in {'sort_by', 'page'} for key in data.keys()])def get_summary_message(self):- """Returns message displayed in dashboard filter cards.- Inherited by subclasses for record specific naming."""+ """Return message displayed in dashboard filter cards.++ Inherited by subclasses for record specific naming.+ """counter = self.qs.count()return npgettext('Number of matching records in the dashboard list',diff --git a/saleor/core/management/commands/populatedb.py b/saleor/core/management/commands/populatedb.pyindex dc96e5472a..c05bdfa978 100644--- a/saleor/core/management/commands/populatedb.py+++ b/saleor/core/management/commands/populatedb.py@@ -35,11 +35,11 @@ class Command(BaseCommand):help='Don\'t update search index')def make_database_faster(self):- '''Sacrifices some of the safeguards of sqlite3 for speed+ """Sacrifice some of the safeguards of sqlite3 for speed.Users are not likely to run this command in a production environment.They are even less likely to run it in production while using sqlite3.- '''+ """if 'sqlite3' in connection.settings_dict['ENGINE']:cursor = connection.cursor()cursor.execute('PRAGMA temp_store = MEMORY;')diff --git a/saleor/core/middleware.py b/saleor/core/middleware.pyindex 091802e15d..47331b86c7 100644--- a/saleor/core/middleware.py+++ b/saleor/core/middleware.py@@ -65,13 +65,11 @@ def currency(get_response):def site(get_response):- """- This middleware clears the Sites cache, refetches the current Site- and sets it as attribute in request object for future uses in this- request cycle.+ """Clear the Sites cache and assign the current site to `request.site`.+By default django.contrib.sites caches Site instances at the module- level, which leads to problems when updating Site instances, such- as necessity to restart the application server in order to invalidate+ level. This leads to problems when updating Site instances, as it's+ required to restart all application servers in order to invalidatethe cache. Using this middleware solves this problem."""def middleware(request):diff --git a/saleor/core/sitemaps.py b/saleor/core/sitemaps.pyindex 2258d8d189..7583755363 100644--- a/saleor/core/sitemaps.py+++ b/saleor/core/sitemaps.py@@ -15,7 +15,7 @@ class CategorySitemap(Sitemap):categories = Category.objects.all().order_by('id')return categories.only('id', 'name', 'slug')+sitemaps = {'categories': CategorySitemap,- 'products': ProductSitemap-}+ 'products': ProductSitemap}diff --git a/saleor/core/utils/random_data.py b/saleor/core/utils/random_data.pyindex 224aa0dd28..e74bf9ee7d 100644--- a/saleor/core/utils/random_data.py+++ b/saleor/core/utils/random_data.py@@ -37,73 +37,56 @@ DEFAULT_SCHEMA = {'product_attributes': {'Color': ['Blue', 'White'],'Collar': ['Round', 'V-Neck', 'Polo'],- 'Brand': ['Saleor']- },+ 'Brand': ['Saleor']},'variant_attributes': {- 'Size': ['XS', 'S', 'M', 'L', 'XL', 'XXL']- },+ 'Size': ['XS', 'S', 'M', 'L', 'XL', 'XXL']},'images_dir': 't-shirts/',- 'is_shipping_required': True- },+ 'is_shipping_required': True},'Mugs': {'category': 'Accessories','product_attributes': {- 'Brand': ['Saleor']- },+ 'Brand': ['Saleor']},'variant_attributes': {},'images_dir': 'mugs/',- 'is_shipping_required': True- },+ 'is_shipping_required': True},'Coffee': {'category': 'Groceries','product_attributes': {'Coffee Genre': ['Arabica', 'Robusta'],- 'Brand': ['Saleor']- },+ 'Brand': ['Saleor']},'variant_attributes': {- 'Box Size': ['100g', '250g', '500g', '1kg']- },+ 'Box Size': ['100g', '250g', '500g', '1kg']},'different_variant_prices': True,'images_dir': 'coffee/',- 'is_shipping_required': True- },+ 'is_shipping_required': True},'Candy': {'category': 'Groceries','product_attributes': {'Flavor': ['Sour', 'Sweet'],- 'Brand': ['Saleor']- },+ 'Brand': ['Saleor']},'variant_attributes': {- 'Candy Box Size': ['100g', '250g', '500g']- },+ 'Candy Box Size': ['100g', '250g', '500g']},'images_dir': 'candy/',- 'is_shipping_required': True- },+ 'is_shipping_required': True},'E-books': {'category': 'Books','product_attributes': {'Author': ['John Doe', 'Milionare Pirate'],'Publisher': ['Mirumee Press', 'Saleor Publishing'],- 'Language': ['English', 'Pirate']- },+ 'Language': ['English', 'Pirate']},'variant_attributes': {},'images_dir': 'books/',- 'is_shipping_required': False- },+ 'is_shipping_required': False},'Books': {'category': 'Books','product_attributes': {'Author': ['John Doe', 'Milionare Pirate'],'Publisher': ['Mirumee Press', 'Saleor Publishing'],- 'Language': ['English', 'Pirate']- },+ 'Language': ['English', 'Pirate']},'variant_attributes': {- 'Cover': ['Soft', 'Hard']- },+ 'Cover': ['Soft', 'Hard']},'images_dir': 'books/',- 'is_shipping_required': True- }-}+ 'is_shipping_required': True}}def create_attributes_and_values(attribute_data):@@ -254,6 +237,8 @@ class SaleorProvider(BaseProvider):def shipping_method(self):return random.choice(ShippingMethod.objects.all())++fake.add_provider(SaleorProvider)@@ -370,7 +355,10 @@ def create_fake_user():def create_payment(delivery_group):order = delivery_group.orderstatus = random.choice(- [PaymentStatus.WAITING, PaymentStatus.PREAUTH, PaymentStatus.CONFIRMED])+ [+ PaymentStatus.WAITING,+ PaymentStatus.PREAUTH,+ PaymentStatus.CONFIRMED])payment = Payment.objects.create(order=order,status=status,diff --git a/saleor/core/utils/schema.py b/saleor/core/utils/schema.pyindex 09909223d1..a428582f18 100644--- a/saleor/core/utils/schema.py+++ b/saleor/core/utils/schema.py@@ -8,7 +8,7 @@ from . import build_absolute_uridef get_webpage_schema(request):- """Build a schema.org representation of the website"""+ """Build a schema.org representation of the website."""site = get_current_site(request)url = build_absolute_uri(location='/')data = {diff --git a/saleor/dashboard/discount/views.py b/saleor/dashboard/discount/views.pyindex ddebbee741..fc27c7a5ad 100644--- a/saleor/dashboard/discount/views.py+++ b/saleor/dashboard/discount/views.py@@ -14,7 +14,7 @@ from .filters import SaleFilter, VoucherFilterdef get_voucher_type_forms(voucher, data):- """Returns dict consisting of specific due to voucher type forms."""+ """Return a dict of specific voucher type forms."""return {VoucherType.SHIPPING: forms.ShippingVoucherForm(data or None, instance=voucher, prefix=VoucherType.SHIPPING),diff --git a/saleor/dashboard/forms.py b/saleor/dashboard/forms.pyindex 758d77fb4b..2d4ed7a116 100644--- a/saleor/dashboard/forms.py+++ b/saleor/dashboard/forms.py@@ -5,7 +5,7 @@ from django.core.exceptions import ValidationErrorclass AjaxSelect2ChoiceField(forms.ChoiceField):- """ This field enables usage of select2 with ajax fetched data.+ """An AJAX-based choice field using Select2.fetch_data_url - specifies url, from which select2 will fetch datainitial - initial object@@ -34,14 +34,13 @@ class AjaxSelect2ChoiceField(forms.ChoiceField):return Truedef set_initial(self, obj):- """ Sets initially selected objects on field's widget. """+ """Set initially selected objects on field's widget."""selected = {'id': obj.pk, 'text': str(obj)}self.widget.attrs['data-initial'] = json.dumps(selected)class AjaxSelect2MultipleChoiceField(forms.MultipleChoiceField):- """ This field enables selecting multiple values in select2- with ajax fetched data.+ """An AJAX-base multiple choice field using Select2.fetch_data_url - specifies url, from which select2 will fetch datainitial - list of initial objects@@ -79,6 +78,6 @@ class AjaxSelect2MultipleChoiceField(forms.MultipleChoiceField):return Truedef set_initial(self, objects):- """ Sets initially selected objects on field's widget. """+ """Set initially selected objects on field's widget."""selected = [{'id': obj.pk, 'text': str(obj)} for obj in objects]self.widget.attrs['data-initial'] = json.dumps(selected)diff --git a/saleor/dashboard/group/forms.py b/saleor/dashboard/group/forms.pyindex fa82e0bda4..2870a91d36 100644--- a/saleor/dashboard/group/forms.py+++ b/saleor/dashboard/group/forms.py@@ -15,5 +15,4 @@ class GroupPermissionsForm(forms.ModelForm):permissions = forms.ModelMultipleChoiceField(queryset=get_permissions(),- widget=forms.CheckboxSelectMultiple- )+ widget=forms.CheckboxSelectMultiple)diff --git a/saleor/dashboard/order/filters.py b/saleor/dashboard/order/filters.pyindex e80651380c..5ede5171c5 100644--- a/saleor/dashboard/order/filters.py+++ b/saleor/dashboard/order/filters.py@@ -11,13 +11,12 @@ from ...order import OrderStatusfrom ...order.models import Orderfrom ..widgets import DateRangeWidget, PriceRangeWidget-SORT_BY_FIELDS = (+SORT_BY_FIELDS = [('pk', 'pk'),('payments__status', 'payment_status'),('user__email', 'email'),('created', 'created'),- ('total_net', 'total')-)+ ('total_net', 'total')]SORT_BY_FIELDS_LABELS = {'pk': pgettext_lazy('Order list sorting option', '#'),diff --git a/saleor/dashboard/order/forms.py b/saleor/dashboard/order/forms.pyindex 51c73a197b..89729c5ba2 100644--- a/saleor/dashboard/order/forms.py+++ b/saleor/dashboard/order/forms.py@@ -63,9 +63,10 @@ class ManagePaymentForm(forms.Form):raise forms.ValidationError(self.clean_error)def payment_error(self, message):- self.add_error(None,- pgettext_lazy('Payment form error',- 'Payment gateway error: %s') % message)+ self.add_error(+ None, pgettext_lazy(+ 'Payment form error',+ 'Payment gateway error: %s') % message)def try_payment_action(self, action):amount = self.cleaned_data['amount']@@ -100,23 +101,23 @@ class RefundPaymentForm(ManagePaymentForm):class ReleasePaymentForm(ManagePaymentForm):clean_status = PaymentStatus.PREAUTH- clean_error = pgettext_lazy('Payment form error',- 'Only pre-authorized payments can be released')+ clean_error = pgettext_lazy(+ 'Payment form error', 'Only pre-authorized payments can be released')def release(self):return self.try_payment_action(self.payment.release)class MoveLinesForm(forms.Form):- """ Moves part of products in order line to existing or new group. """+ """Allows splitting an order line into an existing or new group."""+quantity = QuantityField(label=pgettext_lazy('Move lines form label', 'Quantity'),validators=[MinValueValidator(1)])target_group = forms.ModelChoiceField(queryset=DeliveryGroup.objects.none(), required=False,empty_label=pgettext_lazy(- 'Shipment group value for `target_group` field',- 'New shipment'),+ 'Shipment group value for `target_group` field', 'New shipment'),label=pgettext_lazy('Move lines form label', 'Target shipment'))def __init__(self, *args, **kwargs):@@ -184,8 +185,9 @@ class ChangeQuantityForm(forms.ModelForm):'Change quantity form error','Only %(remaining)d remaining in stock.','Only %(remaining)d remaining in stock.',- 'remaining') % {'remaining': (- self.initial_quantity + stock.quantity_available)})+ 'remaining') % {+ 'remaining': (+ self.initial_quantity + stock.quantity_available)})return quantitydef save(self):@@ -201,8 +203,12 @@ class ChangeQuantityForm(forms.ModelForm):class ShipGroupForm(forms.ModelForm):- """Decreases corresponding stocks ans sets delivery group tracking- number."""+ """Dispatch a group and optionally assigns a tracking number.++ This process involves permanently decreasing the previously allocated+ stock.+ """+class Meta:model = DeliveryGroupfields = ['tracking_number']@@ -231,8 +237,12 @@ class ShipGroupForm(forms.ModelForm):class CancelGroupForm(forms.ModelForm):- """Deallocates or increases corresponding stocks, depending whether new- or shipped group is cancelled."""+ """Allow canceling a single group in an order.++ Deallocates or increases corresponding stocks, depending whether new+ or shipped group is cancelled.+ """+class Meta:model = DeliveryGroupfields = []@@ -243,8 +253,12 @@ class CancelGroupForm(forms.ModelForm):class CancelOrderForm(forms.Form):- """Deallocates or increases corresponding stocks in each delivery group,- depending whether new or shipped group is cancelled."""+ """Allow canceling an entire order.++ Deallocates or increases corresponding stocks in each delivery group,+ depending whether new or shipped group is cancelled.+ """+def __init__(self, *args, **kwargs):self.order = kwargs.pop('order')super().__init__(*args, **kwargs)@@ -255,7 +269,7 @@ class CancelOrderForm(forms.Form):raise forms.ValidationError(pgettext_lazy('Cancel order form error',- 'This order can\'t be cancelled'))+ "This order can't be cancelled"))return datadef cancel_order(self):@@ -285,9 +299,9 @@ class RemoveVoucherForm(forms.Form):recalculate_order(self.order)-PAYMENT_STATUS_CHOICES = [- ('', pgettext_lazy('Payment status field value', 'All')),-] + PaymentStatus.CHOICES+PAYMENT_STATUS_CHOICES = (+ [('', pgettext_lazy('Payment status field value', 'All'))] ++ PaymentStatus.CHOICES)class PaymentFilterForm(forms.Form):@@ -339,7 +353,8 @@ class ChangeStockForm(forms.ModelForm):class AddVariantToDeliveryGroupForm(forms.Form):- """ Adds variant in given quantity to shipment group. """+ """Allow adding lines with given quantity to a shipment group."""+variant = AjaxSelect2ChoiceField(queryset=ProductVariant.objects.filter(product__in=Product.objects.available_products()),@@ -355,7 +370,7 @@ class AddVariantToDeliveryGroupForm(forms.Form):super().__init__(*args, **kwargs)def clean(self):- """ Checks if given quantity is available in stocks. """+ """Check if given quantity is available in stocs."""cleaned_data = super().clean()variant = cleaned_data.get('variant')quantity = cleaned_data.get('quantity')@@ -373,7 +388,10 @@ class AddVariantToDeliveryGroupForm(forms.Form):return cleaned_datadef save(self):- """ Adds variant to target group. Updates stocks and order. """+ """Add variant to target group.++ Updates stocks and order.+ """variant = self.cleaned_data.get('variant')quantity = self.cleaned_data.get('quantity')add_variant_to_delivery_group(diff --git a/saleor/dashboard/order/views.py b/saleor/dashboard/order/views.pyindex 18e26586f9..711c3fafc6 100644--- a/saleor/dashboard/order/views.py+++ b/saleor/dashboard/order/views.py@@ -307,7 +307,7 @@ def cancel_delivery_group(request, order_pk, group_pk):@staff_member_required@permission_required('order.edit_order')def add_variant_to_group(request, order_pk, group_pk):- """ Adds variant in given quantity to existing or new group in order. """+ """Add variant in given quantity to an existing or new order group."""order = get_object_or_404(Order, pk=order_pk)group = get_object_or_404(order.groups.all(), pk=group_pk)form = AddVariantToDeliveryGroupForm(@@ -317,8 +317,7 @@ def add_variant_to_group(request, order_pk, group_pk):msg_dict = {'quantity': form.cleaned_data.get('quantity'),'variant': form.cleaned_data.get('variant'),- 'group': group- }+ 'group': group}try:with transaction.atomic():form.save()diff --git a/saleor/dashboard/product/__init__.py b/saleor/dashboard/product/__init__.pyindex d4262839e1..18cc29d707 100644--- a/saleor/dashboard/product/__init__.py+++ b/saleor/dashboard/product/__init__.py@@ -3,6 +3,7 @@ from django.utils.translation import pgettext_lazyclass ProductBulkAction:"""Represents types of product bulk actions handled in dashboard."""+PUBLISH = 'Publish'UNPUBLISH = 'Unpublish'diff --git a/saleor/dashboard/product/views.py b/saleor/dashboard/product/views.pyindex 2e30f7c37d..e6a6355033 100644--- a/saleor/dashboard/product/views.py+++ b/saleor/dashboard/product/views.py@@ -779,9 +779,9 @@ def product_bulk_update(request):@staff_member_requireddef ajax_available_variants_list(request):- """- Returns variants list filtered by request GET parameters.- Response format is as required by select2 field.+ """Return variants filtered by request GET parameters.++ Response format is that of a Select2 JS widget."""def get_variant_label(variant, discounts):return '%s, %s, %s' % (@@ -807,9 +807,9 @@ def ajax_available_variants_list(request):@staff_member_requireddef ajax_products_list(request):- """- Returns products list filtered by request GET parameters.- Response format is as required by select2 field.+ """Return products filtered by request GET parameters.++ Response format is that of a Select2 JS widget."""queryset = (Product.objects.all() if request.user.has_perm('product.view_product')diff --git a/saleor/dashboard/search/urls.py b/saleor/dashboard/search/urls.pyindex 939a9ef8d6..dc4e6a953c 100644--- a/saleor/dashboard/search/urls.py+++ b/saleor/dashboard/search/urls.py@@ -3,5 +3,4 @@ from django.conf.urls import urlfrom . import viewsurlpatterns = [- url(r'^$', views.search, name='search')-]+ url(r'^$', views.search, name='search')]diff --git a/saleor/dashboard/search/views.py b/saleor/dashboard/search/views.pyindex e970c495a7..74549ae382 100644--- a/saleor/dashboard/search/views.py+++ b/saleor/dashboard/search/views.py@@ -7,7 +7,7 @@ from .forms import DashboardSearchFormdef limit_results(*results):- '''Pass-through only first few best items for each result query'''+ """Pass-through only first few best items for each result query."""limit = settings.DASHBOARD_SEARCH_LIMITreturn (qs[:limit] for qs in results)diff --git a/saleor/dashboard/staff/utils.py b/saleor/dashboard/staff/utils.pyindex 7c9f885ebd..857c479f53 100644--- a/saleor/dashboard/staff/utils.py+++ b/saleor/dashboard/staff/utils.py@@ -1,6 +1,8 @@def remove_staff_member(staff):- """Removes staff member account only if has no orders placed.- Otherwise, switches is_staff status to False."""+ """Remove staff member account only if it has no orders placed.++ Otherwise, switches is_staff status to False.+ """if staff.orders.exists():staff.is_staff = Falsestaff.save()diff --git a/saleor/dashboard/templatetags/chips.py b/saleor/dashboard/templatetags/chips.pyindex 984cb2154b..ff3b526713 100644--- a/saleor/dashboard/templatetags/chips.py+++ b/saleor/dashboard/templatetags/chips.py@@ -92,7 +92,8 @@ def get_cancel_url(request_get, param_name, param_value=None):`request_get` - dictionary of query parameters`param_name` - name of a parameter to exclude`param_value` - value of a parameter value to exclude (in case a parameter- has multiple values)"""+ has multiple values)+ """new_request_get = {k: request_get.getlist(k) for k in request_get if k != param_name}param_values_list = request_get.getlist(param_name)diff --git a/saleor/dashboard/templatetags/utils.py b/saleor/dashboard/templatetags/utils.pyindex 6ce5dea356..a05d1339d2 100644--- a/saleor/dashboard/templatetags/utils.py+++ b/saleor/dashboard/templatetags/utils.py@@ -33,19 +33,13 @@ def construct_get_query(context, **params):@register.filterdef is_versatile_image_ppoi_click_widget(field):- '''- This filter checks if image field widget is used when user wants to edit- existing product image.- '''+ """Check if image field widget is used when editing a product image."""return isinstance(field.field.widget, VersatileImagePPOIClickWidget)@register.filterdef is_image_preview_widget(field):- '''- This filter checks if image field widget is used when user wants to add new- product image.- '''+ """Check if image field widget is used when adding a product image."""return isinstance(field.field.widget, ImagePreviewWidget)@@ -79,7 +73,7 @@ def margins_for_variant(variant):@register.inclusion_tag('dashboard/includes/_filters.html', takes_context=True)def filters(context, filter_set, sort_by_filter_name='sort_by'):- """Rendering filters template based on FilterSet."""+ """Render the filtering template based on the filter set."""chips = []request_get = context['request'].GET.copy()for filter_name in filter_set.form.cleaned_data.keys():@@ -111,7 +105,7 @@ def filters(context, filter_set, sort_by_filter_name='sort_by'):@register.simple_tag(takes_context=True)def serialize_messages(context):- """Serialize django.contrib.messages to JSON"""+ """Serialize django.contrib.messages to JSON."""messages = context.get('messages', [])data = {}for i, message in enumerate(messages):@@ -122,7 +116,7 @@ def serialize_messages(context):@register.inclusion_tag('dashboard/includes/_sorting_header.html', takes_context=True)def sorting_header(context, field, label, is_wide=False):- """This template tag renders table sorting header."""+ """Render a table sorting header."""request = context['request']request_get = request.GET.copy()sort_by = request_get.get('sort_by')diff --git a/saleor/dashboard/views.py b/saleor/dashboard/views.pyindex 6dc03c3484..3ab7cceb9f 100644--- a/saleor/dashboard/views.py+++ b/saleor/dashboard/views.py@@ -14,17 +14,17 @@ def staff_member_required(f):return _staff_member_required(f, login_url='account_login')-def superuser_required(view_func=None, redirect_field_name=REDIRECT_FIELD_NAME,- login_url='account_login'):- """- Decorator for views that checks that the user is logged in and is a- superuser, redirecting to the login page if necessary.+def superuser_required(+ view_func=None, redirect_field_name=REDIRECT_FIELD_NAME,+ login_url='account_login'):+ """Check if the user is logged in and is a superuser.++ Otherwise redirects to the login page."""actual_decorator = user_passes_test(lambda u: u.is_active and u.is_superuser,login_url=login_url,- redirect_field_name=redirect_field_name- )+ redirect_field_name=redirect_field_name)if view_func:return actual_decorator(view_func)return actual_decorator@@ -32,7 +32,7 @@ def superuser_required(view_func=None, redirect_field_name=REDIRECT_FIELD_NAME,@staff_member_requireddef index(request):- INDEX_PAGINATE_BY = 10+ paginate_by = 10orders_to_ship = Order.objects.open().select_related('user').prefetch_related('groups', 'groups__lines', 'payments')orders_to_ship = [@@ -41,9 +41,9 @@ def index(request):status=PaymentStatus.PREAUTH).order_by('-created')payments = payments.select_related('order', 'order__user')low_stock = get_low_stock_products()- ctx = {'preauthorized_payments': payments[:INDEX_PAGINATE_BY],- 'orders_to_ship': orders_to_ship[:INDEX_PAGINATE_BY],- 'low_stock': low_stock[:INDEX_PAGINATE_BY]}+ ctx = {'preauthorized_payments': payments[:paginate_by],+ 'orders_to_ship': orders_to_ship[:paginate_by],+ 'low_stock': low_stock[:paginate_by]}return TemplateResponse(request, 'dashboard/index.html', ctx)diff --git a/saleor/dashboard/widgets.py b/saleor/dashboard/widgets.pyindex 6b2b650a6c..470921fff6 100644--- a/saleor/dashboard/widgets.py+++ b/saleor/dashboard/widgets.py@@ -11,6 +11,7 @@ from ..userprofile.widgets import (class DateRangeWidget(RangeWidget):def __init__(self, attrs=None):widgets = (forms.DateInput, forms.DateInput)+ # pylint: disable=bad-super-callsuper(RangeWidget, self).__init__(widgets, attrs)@@ -18,6 +19,7 @@ class PriceRangeWidget(RangeWidget):def __init__(self, attrs=None):self.currency = getattr(settings, 'DEFAULT_CURRENCY')widgets = (PriceInput(self.currency), PriceInput(self.currency))+ # pylint: disable=bad-super-callsuper(RangeWidget, self).__init__(widgets, attrs)@@ -26,9 +28,8 @@ class PhonePrefixWidget(StorefrontPhonePrefixWidget):class RichTextEditorWidget(Textarea):- """- This widget is used to initialize medium-editor out-of-the-box- """+ """A WYSIWYG editor widget using medium-editor."""+def __init__(self, attrs=None):default_attrs = {'class': 'rich-text-editor'}if attrs:diff --git a/saleor/data_feeds/urls.py b/saleor/data_feeds/urls.pyindex bf67b240e2..85458564ee 100644--- a/saleor/data_feeds/urls.py+++ b/saleor/data_feeds/urls.py@@ -4,5 +4,7 @@ from django.views.generic.base import RedirectViewfrom .google_merchant import get_feed_file_urlurlpatterns = [- url(r'google/$', RedirectView.as_view(- get_redirect_url=get_feed_file_url, permanent=True), name='google-feed')]+ url(r'google/$',+ RedirectView.as_view(+ get_redirect_url=get_feed_file_url, permanent=True),+ name='google-feed')]diff --git a/saleor/discount/templatetags/voucher.py b/saleor/discount/templatetags/voucher.pyindex 0a9d42410f..7ed48e5856 100644--- a/saleor/discount/templatetags/voucher.py+++ b/saleor/discount/templatetags/voucher.py@@ -8,4 +8,4 @@ register = template.Library()@register.simple_tagdef discount_as_negative(discount, html=False):zero = Price(0, currency=discount.amount.currency)- return gross(zero-discount.amount, html=html)+ return gross(zero - discount.amount, html=html)diff --git a/saleor/graphql/utils.py b/saleor/graphql/utils.pyindex 1410780d6f..22c81b4b32 100644--- a/saleor/graphql/utils.py+++ b/saleor/graphql/utils.py@@ -2,10 +2,11 @@ import grapheneclass CategoryAncestorsCache:- """- Cache used to store ancestors of a category in GraphQL context in order to- reduce number of database queries. Categories of the same tree depth level- have common ancestors, which allows us to cache them by the level.+ """Cache used to store ancestors of a category in GraphQL context.++ Allows to reduce the number of database queries. Categories of the same+ tree depth level have common ancestors, which allows us to cache them by+ the level."""def __init__(self, category):@@ -18,9 +19,8 @@ class CategoryAncestorsCache:class DjangoPkInterface(graphene.Interface):- """- Exposes the Django model primary key- """+ """Exposes the Django model primary key."""+pk = graphene.ID(description="Primary key")def resolve_pk(self, info):diff --git a/saleor/order/models.py b/saleor/order/models.pyindex 61f6b11832..cdcda62861 100644--- a/saleor/order/models.py+++ b/saleor/order/models.py@@ -196,8 +196,9 @@ class Order(models.Model, ItemSet):class DeliveryGroup(models.Model, ItemSet):"""Represents a single shipment.- A single order can consist of many shipment groups.+ A single order can consist of multiple shipment groups."""+status = FSMField(max_length=32, default=GroupStatus.NEW, choices=GroupStatus.CHOICES,protected=True)diff --git a/saleor/order/signals.py b/saleor/order/signals.pyindex d0cf2f8e9e..12e16d6ea9 100644--- a/saleor/order/signals.py+++ b/saleor/order/signals.py@@ -8,7 +8,7 @@ logger = logging.getLogger(__name__)def order_status_change(sender, instance, **kwargs):- """Handles payment status change and sets suitable order status."""+ """Handle payment status change and set suitable order status."""order = instance.orderif order.is_fully_paid():order.create_history_entry(diff --git a/saleor/order/transitions.py b/saleor/order/transitions.pyindex 837a3a3e8c..b284d15006 100644--- a/saleor/order/transitions.py+++ b/saleor/order/transitions.py@@ -5,7 +5,7 @@ from saleor.product.utils import (def process_delivery_group(group, cart_lines, discounts=None):- """Fills shipment group with order lines created from partition items."""+ """Fill shipment group with order lines created from partition items."""for line in cart_lines:add_variant_to_delivery_group(group, line.variant, line.get_quantity(), discounts,@@ -13,7 +13,7 @@ def process_delivery_group(group, cart_lines, discounts=None):def cancel_delivery_group(group):- """Cancels delivery group by returning products to stocks."""+ """Cancel delivery group and return products to stock."""if group.status == GroupStatus.NEW:for line in group:if line.stock:@@ -25,7 +25,7 @@ def cancel_delivery_group(group):def ship_delivery_group(group, tracking_number=''):- """Ships delivery group by decreasing products in stocks."""+ """Ship delivery group and decrease stock levels."""for line in group.lines.all():if line.stock:decrease_stock(line.stock, line.quantity)diff --git a/saleor/order/utils.py b/saleor/order/utils.pyindex 03e76b27e1..20759f5ae7 100644--- a/saleor/order/utils.py+++ b/saleor/order/utils.py@@ -13,8 +13,11 @@ from ..userprofile.utils import store_user_addressdef check_order_status(func):- """Preserves execution of function if order is fully paid by redirecting- to order's details page."""+ """Prevent execution of decorated function if order is fully paid.++ Instead redirects to order details page.+ """+ # pylint: disable=cyclic-importfrom .models import Order@wraps(func)@@ -30,15 +33,17 @@ def check_order_status(func):def cancel_order(order):- """Cancels order by cancelling all associated shipment groups."""+ """Cancel order by cancelling all associated shipment groups."""for group in order.groups.all():group.cancel()group.save()def recalculate_order(order):- """Recalculates and assigns total price of order.- Total price is a sum of items and shippings in order shipment groups."""+ """Recalculate and assigns total price of order.++ Total price is a sum of items and shippings in order shipment groups.+ """prices = [group.get_total() for group in orderif group.status != GroupStatus.CANCELLED]@@ -62,7 +67,8 @@ def attach_order_to_user(order, user):def add_variant_to_delivery_group(group, variant, total_quantity, discounts=None, add_to_existing=True):- """Adds total_quantity of variant to group.+ """Add total_quantity of variant to group.+Raises InsufficientStock exception if quantity could not be fulfilled.By default, first adds variant to existing lines with same variant.@@ -102,7 +108,7 @@ def add_variant_to_delivery_group(def add_variant_to_existing_lines(group, variant, total_quantity):- """Adds variant to existing lines with same variant.+ """Add variant to existing lines with same variant.Variant is added by increasing quantity of lines with same variant,as long as total_quantity of variant will be added@@ -132,7 +138,8 @@ def add_variant_to_existing_lines(group, variant, total_quantity):def merge_duplicates_into_order_line(line):- """Merges duplicated lines in shipment group into one (given) line.+ """Merge duplicated lines in shipment group into one (given) line.+If there are no duplicates, nothing will happen."""lines = line.delivery_group.lines.filter(@@ -161,9 +168,11 @@ def change_order_line_quantity(line, new_quantity):def remove_empty_groups(line, force=False):- """Removes order line and associated shipment group and order.+ """Remove order line and associated shipment group and order.+Remove is done only if quantity of order line or items in group or in order- is equal to 0."""+ is equal to 0.+ """source_group = line.delivery_grouporder = source_group.orderif line.quantity:@@ -181,7 +190,7 @@ def remove_empty_groups(line, force=False):def move_order_line_to_group(line, target_group, quantity):from .models import OrderLine- """Moves given quantity of order line to another shipment group."""+ """Split given quantity of order line to another shipment group."""try:target_line = target_group.lines.get(product=line.product, product_name=line.product_name,diff --git a/saleor/order/views.py b/saleor/order/views.pyindex 0d094b7619..32af07de16 100644--- a/saleor/order/views.py+++ b/saleor/order/views.py@@ -78,27 +78,29 @@ def payment(request, token):@check_order_statusdef start_payment(request, order, variant):- waiting_payments = order.payments.filter(status=PaymentStatus.WAITING).exists()+ waiting_payments = order.payments.filter(+ status=PaymentStatus.WAITING).exists()if waiting_payments:return redirect('order:payment', token=order.token)billing = order.billing_addresstotal = order.get_total()- defaults = {'total': total.gross,- 'tax': total.tax, 'currency': total.currency,- 'delivery': order.shipping_price.gross,- 'billing_first_name': billing.first_name,- 'billing_last_name': billing.last_name,- 'billing_address_1': billing.street_address_1,- 'billing_address_2': billing.street_address_2,- 'billing_city': billing.city,- 'billing_postcode': billing.postal_code,- 'billing_country_code': billing.country.code,- 'billing_email': order.user_email,- 'description': pgettext_lazy(- 'Payment description', 'Order %(order_number)s') % {- 'order_number': order},- 'billing_country_area': billing.country_area,- 'customer_ip_address': get_client_ip(request)}+ defaults = {+ 'total': total.gross,+ 'tax': total.tax, 'currency': total.currency,+ 'delivery': order.shipping_price.gross,+ 'billing_first_name': billing.first_name,+ 'billing_last_name': billing.last_name,+ 'billing_address_1': billing.street_address_1,+ 'billing_address_2': billing.street_address_2,+ 'billing_city': billing.city,+ 'billing_postcode': billing.postal_code,+ 'billing_country_code': billing.country.code,+ 'billing_email': order.user_email,+ 'description': pgettext_lazy(+ 'Payment description', 'Order %(order_number)s') % {+ 'order_number': order},+ 'billing_country_area': billing.country_area,+ 'customer_ip_address': get_client_ip(request)}variant_choices = settings.CHECKOUT_PAYMENT_CHOICESif variant not in [code for code, dummy_name in variant_choices]:raise Http404('%r is not a valid payment variant' % (variant,))@@ -136,8 +138,12 @@ def cancel_payment(request, order):def checkout_success(request, token):- """Redirects user to checkout success page or, in case of successful- registration, to order details page with attaching order to an account."""+ """Redirect user after placing an order.++ Anonymous users are redirected to the checkout success page.+ Registered users are redirected to order details page and the order+ is attached to their account.+ """order = get_object_or_404(Order, token=token)email = order.user_emailctx = {'email': email, 'order': order}@@ -165,7 +171,7 @@ def checkout_success(request, token):@login_requireddef connect_order_with_user(request, token):- """Connects newly created order to authenticated user."""+ """Connect newly created order to an authenticated user."""try:order = Order.objects.get(user_email=request.user.email, token=token)except Order.DoesNotExist:@@ -173,8 +179,8 @@ def connect_order_with_user(request, token):if not order:msg = pgettext_lazy('Connect order with user warning message',- 'We couldn\'t assign the order to your account as the email'- ' addresses don\'t match')+ "We couldn't assign the order to your account as the email"+ " addresses don't match")messages.warning(request, msg)return redirect('profile:details')attach_order_to_user(order, request.user)diff --git a/saleor/product/forms.py b/saleor/product/forms.pyindex 025b053947..8a3db2067a 100644--- a/saleor/product/forms.py+++ b/saleor/product/forms.py@@ -21,13 +21,14 @@ class VariantChoiceField(forms.ModelChoiceField):return labeldef update_field_data(self, variants, cart):- """ Function initializing fields custom data """+ """Initialize variant picker metadata."""self.queryset = variantsself.discounts = cart.discountsself.empty_label = None- images_map = {variant.pk: [vi.image.image.url- for vi in variant.variant_images.all()]- for variant in variants.all()}+ images_map = {+ variant.pk: [+ vi.image.image.url for vi in variant.variant_images.all()]+ for variant in variants.all()}self.widget.attrs['data-images'] = json.dumps(images_map)# Don't display select input if there are less than two variantsif self.queryset.count() < 2:diff --git a/saleor/product/templatetags/product_images.py b/saleor/product/templatetags/product_images.pyindex 864046b42e..3f43daddd7 100644--- a/saleor/product/templatetags/product_images.py+++ b/saleor/product/templatetags/product_images.py@@ -25,9 +25,11 @@ AVAILABLE_SIZES = get_available_sizes()def choose_placeholder(size=''):# type: (str) -> str- """Assign placeholder at least as big as provided size if possible.+ """Assign a placeholder at least as big as provided size if possible.+When size is bigger than available, return the biggest.- If size is invalid or not provided, return DEFAULT_PLACEHOLDER"""+ If size is invalid or not provided, return DEFAULT_PLACEHOLDER.+ """placeholder = settings.DEFAULT_PLACEHOLDERparsed_sizes = re.match(r'(\d+)x(\d+)', size)available_sizes = sorted(settings.PLACEHOLDER_IMAGES.keys())@@ -46,11 +48,13 @@ def choose_placeholder(size=''):@register.simple_tag()def get_thumbnail(instance, size, method='crop'):size_name = '%s__%s' % (method, size)+ on_demand = settings.VERSATILEIMAGEFIELD_SETTINGS[+ 'create_images_on_demand']if instance:- if (size_name not in AVAILABLE_SIZES and not- settings.VERSATILEIMAGEFIELD_SETTINGS['create_images_on_demand']):- msg = ('Thumbnail size %s is not defined in settings '- 'and it won\'t be generated automatically' % size_name)+ if (size_name not in AVAILABLE_SIZES and not on_demand):+ msg = (+ "Thumbnail size %s is not defined in settings "+ "and it won't be generated automatically" % size_name)warnings.warn(msg)try:if method == 'crop':@@ -58,8 +62,9 @@ def get_thumbnail(instance, size, method='crop'):else:thumbnail = instance.thumbnail[size]except Exception:- logger.exception('Thumbnail fetch failed',- extra={'instance': instance, 'size': size})+ logger.exception(+ 'Thumbnail fetch failed',+ extra={'instance': instance, 'size': size})else:return thumbnail.urlreturn static(choose_placeholder(size))@@ -67,9 +72,7 @@ def get_thumbnail(instance, size, method='crop'):@register.simple_tag()def product_first_image(product, size, method='crop'):- """- Returns main product image- """+ """Return the main image of the given product."""all_images = product.images.all() if product else []main_image = all_images[0].image if all_images else Nonereturn get_thumbnail(main_image, size, method)diff --git a/saleor/product/utils.py b/saleor/product/utils.pyindex 3323ffff09..1319fe8510 100644--- a/saleor/product/utils.py+++ b/saleor/product/utils.py@@ -16,6 +16,7 @@ from .forms import ProductFormdef products_visible_to_user(user):+ # pylint: disable=cyclic-importfrom .models import Productif user.is_authenticated and user.is_active and user.is_staff:return Product.objects.all()@@ -40,9 +41,7 @@ def products_for_homepage():def get_product_images(product):- """- Returns list of product images that will be placed in product gallery- """+ """Return list of product images that will be placed in product gallery."""return list(product.images.all())@@ -112,7 +111,7 @@ def products_for_cart(user):def product_json_ld(product, attributes=None):# type: (saleor.product.models.Product, saleor.product.utils.ProductAvailability, dict) -> dict # noqa- """Generates JSON-LD data for product"""+ """Generate JSON-LD data for product."""data = {'@context': 'http://schema.org/','@type': 'Product','name': smart_text(product),diff --git a/saleor/product/views.py b/saleor/product/views.pyindex 8aefc73bd7..98d46c438f 100644--- a/saleor/product/views.py+++ b/saleor/product/views.py@@ -17,7 +17,7 @@ from .utils import (def product_details(request, slug, product_id, form=None):- """Product details page+ """Product details page.The following variables are available to the template:@@ -93,7 +93,8 @@ def product_add_to_cart(request, slug, product_id):if form.is_valid():form.save()if request.is_ajax():- response = JsonResponse({'next': reverse('cart:index')}, status=200)+ response = JsonResponse(+ {'next': reverse('cart:index')}, status=200)else:response = redirect('cart:index')else:diff --git a/saleor/registration/backends/__init__.py b/saleor/registration/backends/__init__.pyindex da8748e66d..70e03b6cfc 100644--- a/saleor/registration/backends/__init__.py+++ b/saleor/registration/backends/__init__.py@@ -3,9 +3,8 @@ from ...site.utils import get_authorization_key_for_backendclass BaseBackend:def get_key_and_secret(self):- """Return tuple with Consumer Key and Consumer Secret for current- service provider. Must return (key, secret), order *must* be respected.- """+ """Return a tuple of `(key, secret)` for current provider."""+ # pylint: disable=maybe-no-memberauthorization_key = get_authorization_key_for_backend(self.DB_NAME)if authorization_key:return authorization_key.key_and_secret()diff --git a/saleor/registration/forms.py b/saleor/registration/forms.pyindex 07ec4373a7..aef95bf974 100644--- a/saleor/registration/forms.py+++ b/saleor/registration/forms.py@@ -49,7 +49,9 @@ class SignupForm(forms.ModelForm):class PasswordResetForm(django_forms.PasswordResetForm):- """PasswordResetForm that overrides sending emails to use templated email.+ """Allow resetting passwords.++ This subclass overrides sending emails to use templated email."""def get_users(self, email):diff --git a/saleor/search/backends/elasticsearch_dashboard.py b/saleor/search/backends/elasticsearch_dashboard.pyindex b337f284bb..f7a6374fed 100644--- a/saleor/search/backends/elasticsearch_dashboard.py+++ b/saleor/search/backends/elasticsearch_dashboard.py@@ -28,14 +28,23 @@ def _search_orders(phrase):def get_search_queries(phrase):- ''' Execute external search for all objects matching phrase '''+ """Return querysets to lookup different types of objects.++ Args:+ phrase (str): searched phrase+ """return {'products': _search_products(phrase),'users': _search_users(phrase),- 'orders': _search_orders(phrase)- }+ 'orders': _search_orders(phrase)}def search(phrase):- ''' Provide queryset for every search result '''+ """Return all matching objects for dashboard views.++ Composes independent search querysets into a single dictionary.++ Args:+ phrase (str): searched phrase+ """return {k: s.to_queryset() for k, s in get_search_queries(phrase).items()}diff --git a/saleor/search/backends/elasticsearch_storefront.py b/saleor/search/backends/elasticsearch_storefront.pyindex 6b72c3f68a..b5f7187e55 100644--- a/saleor/search/backends/elasticsearch_storefront.py+++ b/saleor/search/backends/elasticsearch_storefront.py@@ -4,7 +4,7 @@ from ..documents import ProductDocumentdef get_search_query(phrase):- ''' Execute external search for product matching phrase '''+ """Return matching products for storefront views."""query = MultiMatch(fields=['title', 'name', 'description'], query=phrase)return (ProductDocument.search()diff --git a/saleor/search/backends/picker.py b/saleor/search/backends/picker.pyindex 11abd885db..5c37ddb6bc 100644--- a/saleor/search/backends/picker.py+++ b/saleor/search/backends/picker.py@@ -3,18 +3,16 @@ from django.utils.module_loading import import_moduledef pick_backend():- '''Get storefront search function of configured backend+ """Return the currently configured storefront search function.- :rtype: callable with one argument of type str-- '''+ Returns a callable that accepts the search phrase.+ """return import_module(settings.SEARCH_BACKEND).search_storefrontdef pick_dashboard_backend():- '''Get dashboard search function of configured backend-- :rtype: callable with one argument of type str+ """Return the currently configured dashboard search function.- '''+ Returns a callable that accepts the search phrase.+ """return import_module(settings.SEARCH_BACKEND).search_dashboarddiff --git a/saleor/search/backends/postgresql_dashboard.py b/saleor/search/backends/postgresql_dashboard.pyindex 0975c1287a..03d93048fd 100644--- a/saleor/search/backends/postgresql_dashboard.py+++ b/saleor/search/backends/postgresql_dashboard.py@@ -7,7 +7,7 @@ from ...userprofile.models import Userdef search_products(phrase):- '''Dashboard full text product search'''+ """Return matching products for dashboard views."""sv = (SearchVector('name', weight='A') +SearchVector('description', weight='B'))rank = SearchRank(sv, SearchQuery(phrase))@@ -16,12 +16,11 @@ def search_products(phrase):def search_orders(phrase):- '''Dashboard full text order search+ """Return matching orders for dashboard views.When phrase is convertable to int, no full text search is performed,- just order with according id is looked up.-- '''+ just order with matching id is looked up.+ """try:order_id = int(phrase.strip())return Order.objects.filter(id=order_id)@@ -29,8 +28,8 @@ def search_orders(phrase):passsv = (- SearchVector('user__default_shipping_address__first_name',- weight='B') ++ SearchVector(+ 'user__default_shipping_address__first_name', weight='B') +SearchVector('user__default_shipping_address__last_name', weight='B') +SearchVector('user__email', weight='A'))rank = SearchRank(sv, SearchQuery(phrase))@@ -39,7 +38,7 @@ def search_orders(phrase):def search_users(phrase):- '''Dashboard full text user search'''+ """Return matching users for dashboard views."""sv = (SearchVector('email', weight='A') +SearchVector('default_billing_address__first_name', weight='B') +SearchVector('default_billing_address__last_name', weight='B'))@@ -49,16 +48,14 @@ def search_users(phrase):def search(phrase):- '''Dashboard full text postgres products, orders and users search+ """Return all matching objects for dashboard views.- Composes independent search querysets into dictionary result.+ Composes independent search querysets into a single dictionary.Args:phrase (str): searched phrase-- '''+ """return {'products': search_products(phrase),'orders': search_orders(phrase),- 'users': search_users(phrase)- }+ 'users': search_users(phrase)}diff --git a/saleor/search/backends/postgresql_storefront.py b/saleor/search/backends/postgresql_storefront.pyindex 405aea655b..0756c7747f 100644--- a/saleor/search/backends/postgresql_storefront.py+++ b/saleor/search/backends/postgresql_storefront.py@@ -5,7 +5,7 @@ from ...product.models import Productdef search(phrase):- '''Storefront full text product search+ """Return matching products for storefront views.Fuzzy storefront search that is resistant to small typing errors madeby user. Name is matched using trigram similarity, description uses@@ -14,7 +14,7 @@ def search(phrase):Args:phrase (str): searched phrase- '''+ """name_sim = TrigramSimilarity('name', phrase)published = Q(is_published=True)ft_in_description = Q(description__search=phrase)diff --git a/saleor/search/backends/test_elasticsearch_dashboard.py b/saleor/search/backends/test_elasticsearch_dashboard.pyindex 8de21aed70..dbf77ac9e8 100644--- a/saleor/search/backends/test_elasticsearch_dashboard.py+++ b/saleor/search/backends/test_elasticsearch_dashboard.py@@ -7,20 +7,14 @@ PRODUCT_QUERY = {'multi_match': {'fields': ['name', 'title', 'description'],'query': PHRASE,- 'type': 'cross_fields'- }- },- 'sort': ['_score']-}+ 'type': 'cross_fields'}},+ 'sort': ['_score']}ORDERS_QUERY = {'_source': False,'query': {'multi_match': {'fields': ['user', 'discount_name'],- 'query': PHRASE- }- }-}+ 'query': PHRASE}}}USERS_QUERY = {'_source': False,'query': {@@ -28,10 +22,7 @@ USERS_QUERY = {'fields': ['user', 'email', 'first_name', 'last_name'],'operator': 'and','query': PHRASE,- 'type': 'cross_fields'- }- }-}+ 'type': 'cross_fields'}}}def test_dashboard_search_query_syntax():diff --git a/saleor/search/backends/test_elasticsearch_storefront.py b/saleor/search/backends/test_elasticsearch_storefront.pyindex eef5ed8bc6..0a2c38e425 100644--- a/saleor/search/backends/test_elasticsearch_storefront.py+++ b/saleor/search/backends/test_elasticsearch_storefront.py@@ -11,17 +11,10 @@ QUERY = {'must': [{'multi_match': {'query': PHRASE,- 'fields': FIELDS- }- }],+ 'fields': FIELDS}}],'filter': [{'term': {- 'is_published': True- }- }]- }- }-}+ 'is_published': True}}]}}}def test_storefront_product_search_query_syntax():diff --git a/saleor/settings.py b/saleor/settings.pyindex 20acd74a24..789c8161f0 100644--- a/saleor/settings.py+++ b/saleor/settings.py@@ -81,12 +81,10 @@ STATIC_URL = '/static/'STATICFILES_DIRS = [('assets', os.path.join(PROJECT_ROOT, 'saleor', 'static', 'assets')),('images', os.path.join(PROJECT_ROOT, 'saleor', 'static', 'images')),- ('dashboard', os.path.join(PROJECT_ROOT, 'saleor', 'static', 'dashboard'))-]+ ('dashboard', os.path.join(PROJECT_ROOT, 'saleor', 'static', 'dashboard'))]STATICFILES_FINDERS = ['django.contrib.staticfiles.finders.FileSystemFinder',- 'django.contrib.staticfiles.finders.AppDirectoriesFinder'-]+ 'django.contrib.staticfiles.finders.AppDirectoriesFinder']context_processors = ['django.contrib.auth.context_processors.auth',@@ -103,8 +101,7 @@ context_processors = ['saleor.core.context_processors.search_enabled','saleor.site.context_processors.site','social_django.context_processors.backends',- 'social_django.context_processors.login_redirect',-]+ 'social_django.context_processors.login_redirect']loaders = ['django.template.loaders.filesystem.Loader',@@ -139,8 +136,7 @@ MIDDLEWARE = ['saleor.core.middleware.currency','saleor.core.middleware.site','social_django.middleware.SocialAuthExceptionMiddleware',- 'impersonate.middleware.ImpersonateMiddleware'-]+ 'impersonate.middleware.ImpersonateMiddleware']INSTALLED_APPS = [# External apps that need to go before django's@@ -188,61 +184,46 @@ INSTALLED_APPS = ['django_filters','django_celery_results','impersonate',- 'phonenumber_field',-]+ 'phonenumber_field']LOGGING = {'version': 1,'disable_existing_loggers': False,'root': {'level': 'INFO',- 'handlers': ['console']- },+ 'handlers': ['console']},'formatters': {'verbose': {'format': ('%(levelname)s %(name)s %(message)s'- ' [PID:%(process)d:%(threadName)s]')- },+ ' [PID:%(process)d:%(threadName)s]')},'simple': {- 'format': '%(levelname)s %(message)s'- }- },+ 'format': '%(levelname)s %(message)s'}},'filters': {'require_debug_false': {- '()': 'django.utils.log.RequireDebugFalse'- }- },+ '()': 'django.utils.log.RequireDebugFalse'}},'handlers': {'mail_admins': {'level': 'ERROR','filters': ['require_debug_false'],- 'class': 'django.utils.log.AdminEmailHandler'- },+ 'class': 'django.utils.log.AdminEmailHandler'},'console': {'level': 'DEBUG','class': 'logging.StreamHandler',- 'formatter': 'verbose'- }- },+ 'formatter': 'verbose'}},'loggers': {'django': {'handlers': ['console', 'mail_admins'],'level': 'INFO',- 'propagate': True- },+ 'propagate': True},'django.server': {'handlers': ['console'],'level': 'INFO',- 'propagate': True- },+ 'propagate': True},'saleor': {'handlers': ['console'],'level': 'DEBUG',- 'propagate': True- }- }-}+ 'propagate': True}}}AUTH_USER_MODEL = 'userprofile.User'@@ -294,9 +275,7 @@ bootstrap4 = {'set_required': False,'success_css_class': '','form_renderers': {- 'default': 'saleor.core.utils.form_renderer.FormRenderer',- },-}+ 'default': 'saleor.core.utils.form_renderer.FormRenderer'}}TEST_RUNNER = ''@@ -341,8 +320,7 @@ PLACEHOLDER_IMAGES = {120: 'images/placeholder120x120.png',255: 'images/placeholder255x255.png',540: 'images/placeholder540x540.png',- 1080: 'images/placeholder1080x1080.png'-}+ 1080: 'images/placeholder1080x1080.png'}DEFAULT_PLACEHOLDER = 'images/placeholder255x255.png'@@ -375,25 +353,20 @@ if ES_URL:INSTALLED_APPS.append('django_elasticsearch_dsl')ELASTICSEARCH_DSL = {'default': {- 'hosts': ES_URL- },- }+ 'hosts': ES_URL}}GRAPHENE = {'MIDDLEWARE': [- 'graphene_django.debug.DjangoDebugMiddleware'- ],+ 'graphene_django.debug.DjangoDebugMiddleware'],'SCHEMA': 'saleor.graphql.api.schema','SCHEMA_OUTPUT': os.path.join(- PROJECT_ROOT, 'saleor', 'static', 'schema.json')-}+ PROJECT_ROOT, 'saleor', 'static', 'schema.json')}AUTHENTICATION_BACKENDS = ['saleor.registration.backends.facebook.CustomFacebookOAuth2','saleor.registration.backends.google.CustomGoogleOAuth2',- 'django.contrib.auth.backends.ModelBackend',-]+ 'django.contrib.auth.backends.ModelBackend']SOCIAL_AUTH_PIPELINE = ['social_core.pipeline.social_auth.social_details',@@ -404,8 +377,7 @@ SOCIAL_AUTH_PIPELINE = ['social_core.pipeline.user.create_user','social_core.pipeline.social_auth.associate_user','social_core.pipeline.social_auth.load_extra_data',- 'social_core.pipeline.user.user_details',-]+ 'social_core.pipeline.user.user_details']SOCIAL_AUTH_USERNAME_IS_FULL_EMAIL = TrueSOCIAL_AUTH_USER_MODEL = AUTH_USER_MODEL@@ -426,5 +398,4 @@ IMPERSONATE = {'URI_EXCLUSIONS': [r'^dashboard/'],'CUSTOM_USER_QUERYSET': 'saleor.userprofile.impersonate.get_impersonatable_users', # noqa'USE_HTTP_REFERER': True,- 'CUSTOM_ALLOW': 'saleor.userprofile.impersonate.can_impersonate'-}+ 'CUSTOM_ALLOW': 'saleor.userprofile.impersonate.can_impersonate'}diff --git a/saleor/site/context_processors.py b/saleor/site/context_processors.pyindex 569735d3ea..a0d6c640ee 100644--- a/saleor/site/context_processors.py+++ b/saleor/site/context_processors.py@@ -3,5 +3,5 @@ from django.contrib.sites.shortcuts import get_current_sitedef site(request):# type: (django.http.request.HttpRequest) -> dict- """Returns site settings which can be accessed with 'site' key."""+ """Add site settings to the context under the 'site' key."""return {'site': get_current_site(request)}diff --git a/saleor/site/patch_sites.py b/saleor/site/patch_sites.pyindex 4c514d1fc0..f1415c5e2e 100644--- a/saleor/site/patch_sites.py+++ b/saleor/site/patch_sites.py@@ -1,8 +1,9 @@-'''+"""A hack to allow safe clearing of the cache in django.contrib.sites.+Since django.contrib.sites may not be thread-safe when there aremultiple instances of the application server, we're patching it witha thread-safe structure and methods that use it underneath.-'''+"""import threadingfrom django.contrib.sites.models import Site, SiteManager@@ -44,11 +45,10 @@ def new_get_current(self, request=None):return THREADED_SITE_CACHE[domain]raise ImproperlyConfigured(- "You're using the Django \"sites framework\" without having "- "set the SITE_ID setting. Create a site in your database and "- "set the SITE_ID setting or pass a request to "- "Site.objects.get_current() to fix this error."- )+ "You're using the Django sites framework without having"+ " set the SITE_ID setting. Create a site in your database and"+ " set the SITE_ID setting or pass a request to"+ " Site.objects.get_current() to fix this error.")def new_clear_cache(self):diff --git a/saleor/urls.py b/saleor/urls.pyindex e667d1fa71..9d851fb430 100644--- a/saleor/urls.py+++ b/saleor/urls.py@@ -41,11 +41,10 @@ urlpatterns = [url(r'^sitemap\.xml$', sitemap, {'sitemaps': sitemaps},name='django.contrib.sitemaps.views.sitemap'),url(r'', include('payments.urls')),- url('', include('social_django.urls', namespace='social')),-]+ url('', include('social_django.urls', namespace='social'))]if settings.DEBUG:# static files (images, css, javascript, etc.)urlpatterns += [- url(r'^static/(?P<path>.*)$', serve)- ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)+ url(r'^static/(?P<path>.*)$', serve)] + static(+ settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)diff --git a/saleor/userprofile/forms.py b/saleor/userprofile/forms.pyindex 733c918149..32e3cddc33 100644--- a/saleor/userprofile/forms.py+++ b/saleor/userprofile/forms.py@@ -5,7 +5,8 @@ from phonenumbers.phonenumberutil import country_code_for_regionfrom .i18n import AddressMetaForm, get_address_form_class-def get_address_form(data, country_code, initial=None, instance=None, **kwargs):+def get_address_form(+ data, country_code, initial=None, instance=None, **kwargs):country_form = AddressMetaForm(data, initial=initial)preview = Falseif country_form.is_valid():diff --git a/saleor/userprofile/i18n.py b/saleor/userprofile/i18n.pyindex 8d53376a81..5114db3c57 100644--- a/saleor/userprofile/i18n.py+++ b/saleor/userprofile/i18n.py@@ -39,12 +39,7 @@ AREA_TYPE_TRANSLATIONS = {class PossiblePhoneNumberFormField(PhoneNumberField):- """- Modify PhoneNumberField form field to allow using phone numbers from- countries other than selected one.- To achieve this both default_validator attribute and to_python method needs- to be overwritten.- """+ """A PhoneNumberField that allows phone numbers from other countries."""default_validators = [validate_possible_number]@@ -80,7 +75,7 @@ class AddressMetaForm(forms.ModelForm):class AddressForm(forms.ModelForm):- AUTOCOMPLETE_MAPPING = (+ AUTOCOMPLETE_MAPPING = [('first_name', 'given-name'),('last_name', 'family-name'),('company_name', 'organization'),@@ -92,8 +87,7 @@ class AddressForm(forms.ModelForm):('country', 'country'),('city_area', 'address-level3'),('phone', 'tel'),- ('email', 'email')- )+ ('email', 'email')]class Meta:model = Address@@ -141,7 +135,7 @@ class AddressForm(forms.ModelForm):class CountryAwareAddressForm(AddressForm):- I18N_MAPPING = (+ I18N_MAPPING = [('name', ['first_name', 'last_name']),('street_address', ['street_address_1', 'street_address_2']),('city_area', ['city_area']),@@ -150,7 +144,7 @@ class CountryAwareAddressForm(AddressForm):('postal_code', ['postal_code']),('city', ['city']),('sorting_code', []),- ('country_code', ['country']))+ ('country_code', ['country'])]class Meta:model = Address@@ -216,7 +210,8 @@ def get_form_i18n_lines(form_instance):def update_base_fields(form_class, i18n_rules):if i18n_rules.country_area_choices:- form_class.base_fields['country_area'] = CountryAreaChoiceField(choices=i18n_rules.country_area_choices)+ form_class.base_fields['country_area'] = CountryAreaChoiceField(+ choices=i18n_rules.country_area_choices)labels_map = {'country_area': i18n_rules.country_area_type,diff --git a/saleor/userprofile/impersonate.py b/saleor/userprofile/impersonate.pyindex 85ad614038..e5cbfb3c63 100644--- a/saleor/userprofile/impersonate.py+++ b/saleor/userprofile/impersonate.py@@ -3,15 +3,14 @@ from .models import Userdef get_impersonatable_users(request):- '''- Returns QuerySet containing all .models.User(s) that can be impersonated- '''+ """Return all users that can be impersonated."""return User.objects.filter(is_staff=False, is_superuser=False)def can_impersonate(request):- '''Checks if user has right permissions to impersonate customers;- django-impersonate module requires a function as input argument,+ """Check if the current user can impersonate customers.++ `django-impersonate` module requires a function as input argument,not just permission name.- '''+ """return request.user.has_perm('userprofile.impersonate_user')diff --git a/saleor/userprofile/models.py b/saleor/userprofile/models.pyindex cf537bb8da..aa8c97bfa3 100644--- a/saleor/userprofile/models.py+++ b/saleor/userprofile/models.py@@ -11,9 +11,8 @@ from .validators import validate_possible_numberclass PossiblePhoneNumberField(PhoneNumberField):- """- Less strict rule for phone numbers written to database.- """+ """Less strict field for phone numbers written to database."""+default_validators = [validate_possible_number]diff --git a/saleor/userprofile/views.py b/saleor/userprofile/views.pyindex 8a5b809ec0..b5304e9b05 100755--- a/saleor/userprofile/views.py+++ b/saleor/userprofile/views.py@@ -43,7 +43,8 @@ def address_edit(request, pk):country_code=address.country.code)if address_form.is_valid() and not preview:address_form.save()- message = pgettext('Storefront message', 'Address successfully updated.')+ message = pgettext(+ 'Storefront message', 'Address successfully updated.')messages.success(request, message)return HttpResponseRedirect(reverse('profile:details') + '#addresses')return TemplateResponse(diff --git a/saleor/userprofile/widgets.py b/saleor/userprofile/widgets.pyindex b43b292d23..dc4c6a6ff3 100644--- a/saleor/userprofile/widgets.py+++ b/saleor/userprofile/widgets.py@@ -2,16 +2,14 @@ from django.forms import Select, TextInputfrom phonenumber_field.widgets import PhoneNumberPrefixWidgetfrom phonenumbers import COUNTRY_CODE_TO_REGION_CODE-from .validators import validate_possible_number-phone_prefixes = [('+{}'.format(k), '+{}'.format(k)) for(k, v) in sorted(COUNTRY_CODE_TO_REGION_CODE.items())]class PhonePrefixWidget(PhoneNumberPrefixWidget):- """- Overwrite widget to use choices with tuple in a simple form of "+XYZ: +XYZ"+ """Uses choices with tuple in a simple form of "+XYZ: +XYZ".+Workaround for an issue:https://github.com/stefanfoulis/django-phonenumber-field/issues/82"""@@ -20,6 +18,7 @@ class PhonePrefixWidget(PhoneNumberPrefixWidget):def __init__(self, attrs=None):widgets = (Select(attrs=attrs, choices=phone_prefixes), TextInput())+ # pylint: disable=bad-super-callsuper(PhoneNumberPrefixWidget, self).__init__(widgets, attrs)diff --git a/saleor/wsgi/__init__.py b/saleor/wsgi/__init__.pyindex 3d04e8426d..df2072548d 100644--- a/saleor/wsgi/__init__.py+++ b/saleor/wsgi/__init__.py@@ -1,5 +1,4 @@-"""-WSGI config for saleor project.+"""WSGI config for saleor project.This module contains the WSGI application used by Django's development serverand any production WSGI deployments. It should expose a module-level variable@@ -11,7 +10,6 @@ might make sense to replace the whole Django WSGI application with a custom onethat later delegates to the Django one. For example, you could introduce WSGImiddleware here, or combine a Django application with an application of anotherframework.-"""import osos.environ.setdefault('DJANGO_SETTINGS_MODULE', 'saleor.settings')@@ -19,12 +17,12 @@ os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'saleor.settings')# This application object is used by any WSGI server configured to use this# file. This includes Django's development server, if the WSGI_APPLICATION# setting points here.-from django.core.wsgi import get_wsgi_application+from django.core.wsgi import get_wsgi_application # noqaapplication = get_wsgi_application()# Apply WSGI middleware here.# from helloworld.wsgi import HelloWorldApplication# application = HelloWorldApplication(application)-from .health_check import health_check+from .health_check import health_check # noqaapplication = health_check(application, '/health/')diff --git a/setup.cfg b/setup.cfgindex 0859b52ec5..90ef6a664b 100644--- a/setup.cfg+++ b/setup.cfg@@ -35,13 +35,18 @@ exclude =*/migrations/ignore = H101,H238,H301,H306+[pydocstyle]+ignore = D100, D104, D105, D106, D107, D203, D213+inherit = false+match-dir = (?!migrations)[^\.].*+[isort]-skip=migrations,-indent=' '-multi_line_output=4-length_sort=false+skip = migrations,+indent = ' '+multi_line_output = 4+length_sort = falsebalanced_wrapping = false-combine_as_imports=true-combine_star=true-use_parentheses=true-force_sort_within_sections=true+combine_as_imports = true+combine_star = true+use_parentheses = true+force_sort_within_sections = truediff --git a/tests/conftest.py b/tests/conftest.pyindex e78fbef7a6..ae043ad929 100644--- a/tests/conftest.py+++ b/tests/conftest.py@@ -28,12 +28,14 @@ from saleor.userprofile.models import Address, User@pytest.fixture(autouse=True)def site_settings(db, settings):- '''- This fixture is autouse set to True because- django.contrib.sites.models.Site and saleor.site.models.SiteSettings has- OneToOne relationship and Site should never exist without SiteSettings.- '''- site = Site.objects.get_or_create(name="mirumee.com", domain="mirumee.com")[0]+ """Create a site and matching site settings.++ This fixture is autouse because django.contrib.sites.models.Site and+ saleor.site.models.SiteSettings have a one-to-one relationship and a site+ should never exist without a matching settings object.+ """+ site = Site.objects.get_or_create(+ name="mirumee.com", domain="mirumee.com")[0]obj = SiteSettings.objects.get_or_create(site=site)[0]settings.SITE_ID = site.pkreturn obj@@ -73,15 +75,14 @@ def order(billing_address):@pytest.fixture()-def admin_user(db): # pylint: disable=W0613- """A Django admin user.- """+def admin_user(db):+ """Return a Django admin user."""return User.objects.create_superuser('[email protected]', 'password')@pytest.fixture()def admin_client(admin_user):- """A Django test client logged in as an admin user."""+ """Return a Django test client logged in as an admin user."""from django.test.client import Clientclient = Client()client.login(username=admin_user.email, password='password')@@ -90,7 +91,7 @@ def admin_client(admin_user):@pytest.fixture()def staff_user(db):- """A Django staff user"""+ """Return a staff member."""return User.objects.create_user(email='[email protected]', password='password', is_staff=True,is_active=True)@@ -98,7 +99,7 @@ def staff_user(db):@pytest.fixture()def staff_client(client, staff_user):- """A Django test client logged in as an staff member"""+ """Return a Django test client logged in as an staff member."""client.login(username=staff_user.email, password='password')return client@@ -224,11 +225,6 @@ def permission_edit_order():return Permission.objects.get(codename='edit_order')-def permission_view_user():- return Permission.objects.get(codename='view_user')--@pytest.fixturedef product_type(color_attribute, size_attribute):product_type = ProductType.objects.create(@@ -252,8 +248,7 @@ def product_in_stock(product_type, default_category):variant_attr = product_type.variant_attributes.first()variant_attr_value = variant_attr.values.first()variant_attributes = {- smart_text(variant_attr.pk): smart_text(variant_attr_value.pk)- }+ smart_text(variant_attr.pk): smart_text(variant_attr_value.pk)}variant = ProductVariant.objects.create(product=product, sku='123', attributes=variant_attributes)@@ -280,7 +275,7 @@ def product_without_shipping(default_category):product = Product.objects.create(name='Test product', price=Decimal('10.00'),product_type=product_type, category=default_category)- variant = ProductVariant.objects.create(product=product, sku='SKU_B')+ ProductVariant.objects.create(product=product, sku='SKU_B')return product@@ -389,8 +384,7 @@ def order_with_lines(order, product_type, default_category):is_shipping_required=product.product_type.is_shipping_required,quantity=1,unit_price_net=Decimal('10.00'),- unit_price_gross=Decimal('10.00'),- )+ unit_price_gross=Decimal('10.00'))product = Product.objects.create(name='Test product 2', price=Decimal('20.00'),product_type=product_type, category=default_category)@@ -403,8 +397,7 @@ def order_with_lines(order, product_type, default_category):is_shipping_required=product.product_type.is_shipping_required,quantity=1,unit_price_net=Decimal('20.00'),- unit_price_gross=Decimal('20.00'),- )+ unit_price_gross=Decimal('20.00'))product = Product.objects.create(name='Test product 3', price=Decimal('30.00'),product_type=product_type, category=default_category)@@ -417,8 +410,7 @@ def order_with_lines(order, product_type, default_category):is_shipping_required=product.product_type.is_shipping_required,quantity=1,unit_price_net=Decimal('30.00'),- unit_price_gross=Decimal('30.00'),- )+ unit_price_gross=Decimal('30.00'))recalculate_order(order)return order@@ -445,8 +437,7 @@ def order_with_lines_and_stock(order, product_type, default_category):unit_price_net=Decimal('30.00'),unit_price_gross=Decimal('30.00'),stock=stock,- stock_location=stock.location.name- )+ stock_location=stock.location.name)product = Product.objects.create(name='Test product 2', price=Decimal('20.00'),product_type=product_type, category=default_category)@@ -464,8 +455,7 @@ def order_with_lines_and_stock(order, product_type, default_category):unit_price_net=Decimal('20.00'),unit_price_gross=Decimal('20.00'),stock=stock,- stock_location=stock.location.name- )+ stock_location=stock.location.name)recalculate_order(order)order.refresh_from_db()return order@@ -489,8 +479,7 @@ def order_with_variant_from_different_stocks(order_with_lines_and_stock):unit_price_net=Decimal('30.00'),unit_price_gross=Decimal('30.00'),stock=stock,- stock_location=stock.location.name- )+ stock_location=stock.location.name)warehouse_2 = StockLocation.objects.create(name='Warehouse 3')Stock.objects.create(variant=variant, cost_price=1, quantity=5, quantity_allocated=0,@@ -602,8 +591,10 @@ def permission_impersonate_user():@pytest.fixturedef open_orders(billing_address):+ def group_data(orders, status):+ return {'order': orders[-1], 'status': status}+orders = []- group_data = lambda orders, status: {'order': orders[-1], 'status': status}orders.append(Order.objects.create(billing_address=billing_address))DeliveryGroup.objects.create(**group_data(orders, GroupStatus.NEW))@@ -626,8 +617,10 @@ def open_orders(billing_address):@pytest.fixturedef closed_orders(billing_address):+ def group_data(orders, status):+ return {'order': orders[-1], 'status': status}+orders = []- group_data = lambda orders, status: {'order': orders[-1], 'status': status}orders.append(Order.objects.create(billing_address=billing_address))DeliveryGroup.objects.create(**group_data(orders, GroupStatus.SHIPPED))diff --git a/tests/dashboard/test_category.py b/tests/dashboard/test_category.pyindex e4d17d0cf6..e25602d4d9 100644--- a/tests/dashboard/test_category.py+++ b/tests/dashboard/test_category.py@@ -1,4 +1,3 @@-import pytestfrom django.urls import reversefrom saleor.product.models import Categorydiff --git a/tests/dashboard/test_chips.py b/tests/dashboard/test_chips.pyindex dbe1c2858b..2d755bd0ab 100644--- a/tests/dashboard/test_chips.py+++ b/tests/dashboard/test_chips.py@@ -1,5 +1,3 @@-import pytest-import django_filtersfrom django.http import QueryDictdiff --git a/tests/dashboard/test_group.py b/tests/dashboard/test_group.pyindex 2f862c39b6..94855619ff 100644--- a/tests/dashboard/test_group.py+++ b/tests/dashboard/test_group.py@@ -44,7 +44,7 @@ def test_delete_group(admin_client, staff_group):assert response['Location'] == '/dashboard/groups/'-def test_delete_group_no_POST(admin_client, staff_group):+def test_delete_group_no_post(admin_client, staff_group):url = reverse('dashboard:group-delete', args=[staff_group.pk])admin_client.get(url)assert Group.objects.all().count() == 1diff --git a/tests/dashboard/test_order.py b/tests/dashboard/test_order.pyindex 5b1d1aa6ae..7e85b918f6 100644--- a/tests/dashboard/test_order.py+++ b/tests/dashboard/test_order.py@@ -1,5 +1,5 @@from decimal import Decimal-from unittest.mock import MagicMock, patch+from unittest.mock import patchfrom django.urls import reverseimport pytest@@ -10,7 +10,7 @@ from tests.utils import get_redirect_location, get_url_pathfrom saleor.cart.models import Cartfrom saleor.dashboard.order.forms import ChangeQuantityForm-from saleor.order import GroupStatus, OrderStatus+from saleor.order import GroupStatusfrom saleor.dashboard.order.forms import OrderNoteFormfrom saleor.order.models import (DeliveryGroup, Order, OrderHistoryEntry, OrderLine, OrderNote)@@ -46,10 +46,12 @@ def test_view_cancel_order_line(admin_client, order_with_lines_and_stock):lines_after = Order.objects.get().get_lines()assert lines_before_count - 1 == lines_after.count()# check stock deallocation- assert Stock.objects.first().quantity_allocated == quantity_allocated_before - line_quantity+ assert Stock.objects.first().quantity_allocated == (+ quantity_allocated_before - line_quantity)# check note in the order's historyassert OrderHistoryEntry.objects.get(- order=order_with_lines_and_stock).content == 'Cancelled item %s' % product+ order=order_with_lines_and_stock).content == (+ 'Cancelled item %s' % product)url = reverse('dashboard:orderline-cancel', kwargs={'order_pk': order_with_lines_and_stock.pk,@@ -65,11 +67,8 @@ def test_view_cancel_order_line(admin_client, order_with_lines_and_stock):@pytest.mark.integration@pytest.mark.django_db-def test_view_change_order_line_quantity(admin_client, order_with_lines_and_stock):- """- user goes to order details page- user selects first order line with quantity 3 and changes it to 2- """+def test_view_change_order_line_quantity(+ admin_client, order_with_lines_and_stock):lines_before_quantity_change = order_with_lines_and_stock.get_lines()lines_before_quantity_change_count = lines_before_quantity_change.count()line = lines_before_quantity_change.first()@@ -106,20 +105,15 @@ def test_view_change_order_line_quantity(admin_client, order_with_lines_and_stocorder=order_with_lines_and_stock).content == ('Changed quantity for product %(product)s from'' %(old_quantity)s to %(new_quantity)s') % {- 'product': line.product,- 'old_quantity': line_quantity_before_quantity_change,- 'new_quantity': 2}+ 'product': line.product,+ 'old_quantity': line_quantity_before_quantity_change,+ 'new_quantity': 2}@pytest.mark.integration@pytest.mark.django_dbdef test_view_change_order_line_quantity_with_invalid_data(admin_client, order_with_lines_and_stock):- """- user goes to order details page- user selects the first order line with quantity 3 and try to change it to 0 and -1- user gets an error.- """lines = order_with_lines_and_stock.get_lines()line = lines.first()url = reverse(@@ -178,13 +172,6 @@ def test_dashboard_change_quantity_form(request_cart_with_item, order):@pytest.mark.integration@pytest.mark.django_dbdef test_view_split_order_line(admin_client, order_with_lines_and_stock):- """- user goes to order details page- user selects first order line with quantity 3 and moves 2 items- to a new shipment- user selects the line from the new shipment and moves all items- back to the first shipment- """lines_before_split = order_with_lines_and_stock.get_lines()lines_before_split_count = lines_before_split.count()line = lines_before_split.first()@@ -214,7 +201,8 @@ def test_view_split_order_line(admin_client, order_with_lines_and_stock):# order should have one more lineassert lines_before_split_count + 1 == lines_after.count()# stock allocation should not be changed- assert Stock.objects.first().quantity_allocated == quantity_allocated_before_split+ assert Stock.objects.first().quantity_allocated == (+ quantity_allocated_before_split)line.refresh_from_db()# source line quantity should be decreased to 1assert line.quantity == line_quantity_before_split - 2@@ -224,11 +212,11 @@ def test_view_split_order_line(admin_client, order_with_lines_and_stock):new_group = DeliveryGroup.objects.last()assert OrderHistoryEntry.objects.get(order=order_with_lines_and_stock).content == (- 'Moved 2 items %(item)s from '- '%(old_group)s to %(new_group)s') % {- 'item': line,- 'old_group': old_delivery_group,- 'new_group': new_group}+ 'Moved 2 items %(item)s from '+ '%(old_group)s to %(new_group)s') % {+ 'item': line,+ 'old_group': old_delivery_group,+ 'new_group': new_group}new_line = new_group.lines.get()# the new line should contain the moved quantityassert new_line.quantity == 2@@ -240,7 +228,7 @@ def test_view_split_order_line(admin_client, order_with_lines_and_stock):url, {'quantity': 2, 'target_group': old_delivery_group.pk})# an other note in the order's history should be createdassert OrderHistoryEntry.objects.filter(- order=order_with_lines_and_stock).last().content ==(+ order=order_with_lines_and_stock).last().content == ('Moved 2 items %(item)s from removed ''group to %(new_group)s') % {'item': line,@@ -257,12 +245,8 @@ def test_view_split_order_line(admin_client, order_with_lines_and_stock):@pytest.mark.integration@pytest.mark.django_db@pytest.mark.parametrize('quantity', [0, 4])-def test_view_split_order_line_with_invalid_data(admin_client, order_with_lines_and_stock, quantity):- """- user goes to order details page- user selects first order line with quantity 3 and try move 0 and 4 items to a new shipment- user gets an error and no shipment groups are created.- """+def test_view_split_order_line_with_invalid_data(+ admin_client, order_with_lines_and_stock, quantity):lines = order_with_lines_and_stock.get_lines()line = lines.first()url = reverse(@@ -300,18 +284,12 @@ def test_ordered_item_remove_empty_group_with_force(@pytest.mark.django_dbdef test_view_order_invoice(admin_client, order_with_lines_and_stock, billing_address):- """- user goes to order details page- user clicks on Invoice button- user downloads the invoice as PDF file- """order_with_lines_and_stock.shipping_address = billing_addressorder_with_lines_and_stock.billing_address = billing_addressorder_with_lines_and_stock.save()url = reverse('dashboard:order-invoice', kwargs={- 'order_pk': order_with_lines_and_stock.id- })+ 'order_pk': order_with_lines_and_stock.id})response = admin_client.get(url)assert response.status_code == 200assert response['content-type'] == 'application/pdf'@@ -323,16 +301,12 @@ def test_view_order_invoice(@pytest.mark.django_dbdef test_view_order_invoice_without_shipping(admin_client, order_with_lines_and_stock, billing_address):- """- Regression test for #1536:- user downloads the invoice for order without shipping address- """+ # Regression test for #1536:order_with_lines_and_stock.billing_address = billing_addressorder_with_lines_and_stock.save()url = reverse('dashboard:order-invoice', kwargs={- 'order_pk': order_with_lines_and_stock.id- })+ 'order_pk': order_with_lines_and_stock.id})response = admin_client.get(url)assert response.status_code == 200assert response['content-type'] == 'application/pdf'@@ -342,18 +316,12 @@ def test_view_order_invoice_without_shipping(@pytest.mark.django_dbdef test_view_order_packing_slips(admin_client, order_with_lines_and_stock, billing_address):- """- user goes to order details page- user clicks on Packing Slips button- user downloads the packing slips as PDF file- """order_with_lines_and_stock.shipping_address = billing_addressorder_with_lines_and_stock.billing_address = billing_addressorder_with_lines_and_stock.save()url = reverse('dashboard:order-packing-slips', kwargs={- 'group_pk': order_with_lines_and_stock.groups.all()[0].pk- })+ 'group_pk': order_with_lines_and_stock.groups.all()[0].pk})response = admin_client.get(url)assert response.status_code == 200assert response['content-type'] == 'application/pdf'@@ -367,15 +335,12 @@ def test_view_order_packing_slips(@pytest.mark.django_dbdef test_view_order_packing_slips_without_shipping(admin_client, order_with_lines_and_stock, billing_address):- """Regression test for #1536:- user downloads the packaging slips for order without shipping address- """+ # Regression test for #1536order_with_lines_and_stock.billing_address = billing_addressorder_with_lines_and_stock.save()url = reverse('dashboard:order-packing-slips', kwargs={- 'group_pk': order_with_lines_and_stock.groups.all()[0].pk- })+ 'group_pk': order_with_lines_and_stock.groups.all()[0].pk})response = admin_client.get(url)assert response.status_code == 200assert response['content-type'] == 'application/pdf'@@ -466,8 +431,7 @@ def test_view_change_order_line_stock_merges_lines(unit_price_net=Decimal('30.00'),unit_price_gross=Decimal('30.00'),stock=stock,- stock_location=stock.location.name- )+ stock_location=stock.location.name)lines_before = group.lines.count()url = reverse(@@ -493,7 +457,6 @@ def test_add_variant_to_existing_lines_one_line(lines = order.get_lines().filter(product_sku='SKU_A')variant_lines_before = lines.count()line = lines.get(stock_location='Warehouse 2')- quantity_before = line.quantityvariant = ProductVariant.objects.get(sku='SKU_A')quantity_left = add_variant_to_existing_lines(@@ -703,7 +666,7 @@ def test_cant_process_shipped_delivery_group(@patch('saleor.dashboard.order.forms.send_note_confirmation')def test_note_form_sent_email(- mock_send_note_confirmation, order_with_lines_and_stock):+ mock_send_note_confirmation, order_with_lines_and_stock):order = order_with_lines_and_stocknote = OrderNote(order=order, user=order.user)form = OrderNoteForm({'content': 'test_note'}, instance=note)diff --git a/tests/dashboard/test_permissions.py b/tests/dashboard/test_permissions.pyindex 69610a08d5..3634c0ce0d 100644--- a/tests/dashboard/test_permissions.py+++ b/tests/dashboard/test_permissions.py@@ -182,7 +182,8 @@ def test_admin_can_view_product_image_update(admin_client, product_with_image):assert response.status_code == 200-def test_staff_cant_view_product_image_update(staff_client, product_with_image):+def test_staff_cant_view_product_image_update(+ staff_client, product_with_image):product_image = product_with_image.images.all()[0]url = reverse('dashboard:product-image-update',kwargs={'img_pk': product_image.pk,@@ -217,7 +218,8 @@ def test_admin_can_view_shipping_methods_update(admin_client, shipping_method):assert response.status_code == 200-def test_staff_cant_view_shipping_methods_update(staff_client, shipping_method):+def test_staff_cant_view_shipping_methods_update(+ staff_client, shipping_method):response = staff_client.get(reverse('dashboard:shipping-method-update',args=[shipping_method.pk]))assert response.status_code == 302@@ -229,7 +231,8 @@ def test_admin_can_view_shipping_methods_detail(admin_client, shipping_method):assert response.status_code == 200-def test_staff_cant_view_shipping_methods_detail(staff_client, shipping_method):+def test_staff_cant_view_shipping_methods_detail(+ staff_client, shipping_method):response = staff_client.get(reverse('dashboard:shipping-method-detail',args=[shipping_method.pk]))assert response.status_code == 302@@ -241,7 +244,8 @@ def test_admin_can_view_shipping_methods_delete(admin_client, shipping_method):assert response.status_code == 200-def test_staff_cant_view_shipping_methods_delete(staff_client, shipping_method):+def test_staff_cant_view_shipping_methods_delete(+ staff_client, shipping_method):response = staff_client.get(reverse('dashboard:shipping-method-delete',args=[shipping_method.pk]))assert response.status_code == 302@@ -603,7 +607,8 @@ def test_staff_group_member_can_view_order_list(def test_staff_group_member_can_view_order_details(- staff_client, staff_user, staff_group, permission_view_order, order_with_lines_and_stock):+ staff_client, staff_user, staff_group, permission_view_order,+ order_with_lines_and_stock):assert not staff_user.has_perm("order.view_order")response = staff_client.get(reverse('dashboard:order-details',args=[order_with_lines_and_stock.pk]))diff --git a/tests/dashboard/test_product.py b/tests/dashboard/test_product.pyindex 6cec5f18dd..65aacb7242 100644--- a/tests/dashboard/test_product.py+++ b/tests/dashboard/test_product.py@@ -162,8 +162,9 @@ def test_attribute_list(db, product_in_stock, color_attribute, admin_client):def test_attribute_detail(color_attribute, admin_client):- url = reverse('dashboard:product-attribute-detail',- kwargs={'pk': color_attribute.pk})+ url = reverse(+ 'dashboard:product-attribute-detail',+ kwargs={'pk': color_attribute.pk})response = admin_client.get(url)assert response.status_code == 200@@ -188,8 +189,9 @@ def test_attribute_add_not_valid(color_attribute, admin_client):def test_attribute_edit(color_attribute, admin_client):assert len(ProductAttribute.objects.all()) == 1- url = reverse('dashboard:product-attribute-update',- kwargs={'pk': color_attribute.pk})+ url = reverse(+ 'dashboard:product-attribute-update',+ kwargs={'pk': color_attribute.pk})data = {'name': 'new_name', 'slug': 'new_slug'}response = admin_client.post(url, data, follow=True)assert response.status_code == 200@@ -201,8 +203,9 @@ def test_attribute_edit(color_attribute, admin_client):def test_attribute_delete(color_attribute, admin_client):assert len(ProductAttribute.objects.all()) == 1- url = reverse('dashboard:product-attribute-delete',- kwargs={'pk': color_attribute.pk})+ url = reverse(+ 'dashboard:product-attribute-delete',+ kwargs={'pk': color_attribute.pk})response = admin_client.post(url, follow=True)assert response.status_code == 200assert len(ProductAttribute.objects.all()) == 0@@ -211,8 +214,9 @@ def test_attribute_delete(color_attribute, admin_client):def test_attribute_choice_value_add(color_attribute, admin_client):values = AttributeChoiceValue.objects.filter(attribute=color_attribute.pk)assert len(values) == 2- url = reverse('dashboard:product-attribute-value-add',- kwargs={'attribute_pk': color_attribute.pk})+ url = reverse(+ 'dashboard:product-attribute-value-add',+ kwargs={'attribute_pk': color_attribute.pk})data = {'name': 'Pink', 'color': '#FFF', 'attribute': color_attribute.pk}response = admin_client.post(url, data, follow=True)assert response.status_code == 200@@ -223,8 +227,9 @@ def test_attribute_choice_value_add(color_attribute, admin_client):def test_attribute_choice_value_add_not_valid(color_attribute, admin_client):values = AttributeChoiceValue.objects.filter(attribute=color_attribute.pk)assert len(values) == 2- url = reverse('dashboard:product-attribute-value-add',- kwargs={'attribute_pk': color_attribute.pk})+ url = reverse(+ 'dashboard:product-attribute-value-add',+ kwargs={'attribute_pk': color_attribute.pk})data = {}response = admin_client.post(url, data, follow=True)assert response.status_code == 200@@ -235,9 +240,9 @@ def test_attribute_choice_value_add_not_valid(color_attribute, admin_client):def test_attribute_choice_value_edit(color_attribute, admin_client):values = AttributeChoiceValue.objects.filter(attribute=color_attribute.pk)assert len(values) == 2- url = reverse('dashboard:product-attribute-value-update',- kwargs={'attribute_pk': color_attribute.pk,- 'value_pk': values[0].pk})+ url = reverse(+ 'dashboard:product-attribute-value-update',+ kwargs={'attribute_pk': color_attribute.pk, 'value_pk': values[0].pk})data = {'name': 'Pink', 'color': '#FFF', 'attribute': color_attribute.pk}response = admin_client.post(url, data, follow=True)assert response.status_code == 200@@ -251,9 +256,10 @@ def test_attribute_choice_value_delete(color_attribute, admin_client):values = AttributeChoiceValue.objects.filter(attribute=color_attribute.pk)assert len(values) == 2deleted_value = values[0]- url = reverse('dashboard:product-attribute-value-delete',- kwargs={'attribute_pk': color_attribute.pk,- 'value_pk': deleted_value.pk})+ url = reverse(+ 'dashboard:product-attribute-value-delete',+ kwargs={+ 'attribute_pk': color_attribute.pk, 'value_pk': deleted_value.pk})response = admin_client.post(url, follow=True)assert response.status_code == 200values = AttributeChoiceValue.objects.filter(attribute=color_attribute.pk)@@ -666,8 +672,7 @@ def test_assign_collection_to_product(product_in_stock):'price': product.price.gross,'category': product.category.pk,'description': 'description',- 'collections': [collection.pk]- }+ 'collections': [collection.pk]}form = ProductForm(data, instance=product)assert form.is_valid()form.save()diff --git a/tests/dashboard/test_site_settings.py b/tests/dashboard/test_site_settings.pyindex f3fd75069c..ebd4c97274 100644--- a/tests/dashboard/test_site_settings.py+++ b/tests/dashboard/test_site_settings.py@@ -67,11 +67,6 @@ def test_get_authorization_key_for_backend(site_settings, authorization_key):assert key_for_backend == authorization_key-def test_get_authorization_key_for_backend(site_settings):- assert utils.get_authorization_key_for_backend('Backend') is None--@pytest.mark.django_dbdef test_get_authorization_key_no_settings_site(settings, authorization_key):settings.SITE_ID = Nonediff --git a/tests/dashboard/test_staff.py b/tests/dashboard/test_staff.pyindex 7f69eb71bb..ceed5419f6 100644--- a/tests/dashboard/test_staff.py+++ b/tests/dashboard/test_staff.py@@ -57,7 +57,7 @@ def test_delete_staff(admin_client, staff_user):assert response['Location'] == '/dashboard/staff/'-def test_delete_staff_no_POST(admin_client, staff_user):+def test_delete_staff_no_post(admin_client, staff_user):url = reverse('dashboard:staff-delete', kwargs={'pk': staff_user.pk})admin_client.get(url)assert User.objects.all().count() == 2diff --git a/tests/dashboard/test_templatetags.py b/tests/dashboard/test_templatetags.pyindex d5e075f1ea..56d9fc36d6 100644--- a/tests/dashboard/test_templatetags.py+++ b/tests/dashboard/test_templatetags.py@@ -1,5 +1,3 @@-import pytest-from django.urls import reversefrom saleor.dashboard.templatetags.utils import sorting_header@@ -10,7 +8,7 @@ def test_sorting_header_prepare_initial_data(admin_client):response = admin_client.get(url)result = sorting_header(response.context, 'name', 'Name')assert result['url'] == url + '?sort_by=name'- assert result['is_active'] == False+ assert result['is_active'] is Falseassert result['sorting_icon'] == ''@@ -20,13 +18,13 @@ def test_sorting_header_name_field(admin_client):response = admin_client.get(url, data)result = sorting_header(response.context, 'name', 'Name')assert result['url'] == url + '?sort_by=-name'- assert result['is_active'] == True+ assert result['is_active'] is Truedata = {'sort_by': '-name'}response = admin_client.get(url, data)result = sorting_header(response.context, 'name', 'Name')assert result['url'] == url + '?sort_by=name'- assert result['is_active'] == True+ assert result['is_active'] is Truedef test_sorting_header_many_fields(admin_client):@@ -35,10 +33,10 @@ def test_sorting_header_many_fields(admin_client):response = admin_client.get(url, data)result = sorting_header(response.context, 'name', 'Name')assert result['url'] == url + '?sort_by=-name'- assert result['is_active'] == True+ assert result['is_active'] is Truedata = {'sort_by': 'price'}response = admin_client.get(url, data)result = sorting_header(response.context, 'price', 'Price')assert result['url'] == url + '?sort_by=-price'- assert result['is_active'] == True+ assert result['is_active'] is Truediff --git a/tests/settings.py b/tests/settings.pyindex 2dc615e6aa..0c21be82cf 100644--- a/tests/settings.py+++ b/tests/settings.py@@ -7,7 +7,7 @@ DEFAULT_CURRENCY = 'USD'LANGUAGE_CODE = 'en-us'-if 'sqlite' in DATABASES['default']['ENGINE']:+if 'sqlite' in DATABASES['default']['ENGINE']: # noqaDATABASES['default']['TEST'] = { # noqa'SERIALIZE': False,'NAME': ':memory:',diff --git a/tests/test_cart.py b/tests/test_cart.pyindex 0dac48cab0..5e5942650f 100644--- a/tests/test_cart.py+++ b/tests/test_cart.py@@ -17,7 +17,6 @@ from saleor.cart.context_processors import cart_counterfrom saleor.cart.models import Cart, ProductGroup, find_open_cart_for_userfrom saleor.cart.views import updatefrom saleor.discount.models import Sale-from saleor.product.models import Categoryfrom saleor.shipping.utils import get_shipment_options@@ -30,8 +29,8 @@ def cart_request_factory(rf, monkeypatch):else:request.user = userrequest.discounts = Sale.objects.all()- monkeypatch.setattr(request, 'get_signed_cookie',- Mock(return_value=token))+ monkeypatch.setattr(+ request, 'get_signed_cookie', Mock(return_value=token))return requestreturn create_request@@ -153,8 +152,6 @@ def test_get_user_cart(# test against getting closed cartsCart.objects.create(user=admin_user, status=CartStatus.CANCELED)- queryset = Cart.objects.all()- carts = list(queryset)cart = utils.get_user_cart(admin_user)assert Cart.objects.all().count() == 5assert cart is None@@ -169,8 +166,8 @@ def test_get_or_create_cart_from_request(anonymous_cart = Cart()mock_get_for_user = Mock(return_value=user_cart)mock_get_for_anonymous = Mock(return_value=anonymous_cart)- monkeypatch.setattr('saleor.cart.utils.get_or_create_user_cart',- mock_get_for_user)+ monkeypatch.setattr(+ 'saleor.cart.utils.get_or_create_user_cart', mock_get_for_user)monkeypatch.setattr('saleor.cart.utils.get_or_create_anonymous_cart_from_token',mock_get_for_anonymous)@@ -191,8 +188,8 @@ def test_get_cart_from_request(request = cart_request_factory(user=customer_user, token=token)user_cart = Cart(user=customer_user)mock_get_for_user = Mock(return_value=user_cart)- monkeypatch.setattr('saleor.cart.utils.get_user_cart',- mock_get_for_user)+ monkeypatch.setattr(+ 'saleor.cart.utils.get_user_cart', mock_get_for_user)returned_cart = utils.get_cart_from_request(request, queryset)mock_get_for_user.assert_called_once_with(customer_user, queryset)assert returned_cart == user_cart@@ -200,8 +197,8 @@ def test_get_cart_from_request(assert list(returned_cart.discounts) == list(request.discounts)mock_get_for_user = Mock(return_value=None)- monkeypatch.setattr('saleor.cart.utils.get_user_cart',- mock_get_for_user)+ monkeypatch.setattr(+ 'saleor.cart.utils.get_user_cart', mock_get_for_user)returned_cart = utils.get_cart_from_request(request, queryset)mock_get_for_user.assert_called_once_with(customer_user, queryset)assert not Cart.objects.filter(token=returned_cart.token).exists()@@ -320,8 +317,7 @@ def test_adding_invalid_quantity(cart, product_in_stock):@pytest.mark.parametrize('create_line_data, get_line_data, lines_equal', [(None, None, True),({'gift-wrap': True}, None, False),- ({'gift-wrap': True}, {'gift-wrap': True}, True)-])+ ({'gift-wrap': True}, {'gift-wrap': True}, True)])def test_getting_line(create_line_data, get_line_data, lines_equal, cart, product_in_stock):variant = product_in_stock.variants.get()@@ -540,8 +536,7 @@ def test_view_invalid_update_cart(client, product_in_stock, request_cart):variant = product_in_stock.variants.get()request_cart.add(variant, 1)response = client.post(- '/cart/update/%s/' % (variant.pk,),- {},+ '/cart/update/%s/' % (variant.pk,), {},HTTP_X_REQUESTED_WITH='XMLHttpRequest')resp_decoded = json.loads(response.content.decode('utf-8'))assert response.status_code == 400diff --git a/tests/test_checkout.py b/tests/test_checkout.pyindex 829f2c74d8..b898e846f0 100644--- a/tests/test_checkout.py+++ b/tests/test_checkout.py@@ -1,8 +1,7 @@-from unittest.mock import MagicMock, Mock, patch+from unittest.mock import MagicMock, Mockfrom django.conf import settingsfrom django.contrib.auth.models import AnonymousUser-from django_countries.fields import Countryfrom prices import Priceimport pytestfrom satchless.item import InsufficientStock@@ -10,13 +9,9 @@ from satchless.item import InsufficientStockfrom saleor.checkout import viewsfrom saleor.checkout.core import STORAGE_SESSION_KEY, Checkoutfrom saleor.checkout.forms import NoteForm-from saleor.checkout.views.summary import (- anonymous_summary_without_shipping,- summary_with_shipping_view,- summary_without_shipping)from saleor.shipping.models import ShippingMethodCountry-from saleor.userprofile.models import Address, User+from saleor.userprofile.models import Addressdef test_checkout_version():@@ -26,12 +21,13 @@ def test_checkout_version():@pytest.mark.parametrize('storage_data, expected_storage', [- ({'version': Checkout.VERSION, 'new': 1}, {'version': Checkout.VERSION, 'new': 1}),+ (+ {'version': Checkout.VERSION, 'new': 1},+ {'version': Checkout.VERSION, 'new': 1}),({'version': 'wrong', 'new': 1}, {'version': Checkout.VERSION}),({'new': 1}, {'version': Checkout.VERSION}),({}, {'version': Checkout.VERSION}),- (None, {'version': Checkout.VERSION}),-])+ (None, {'version': Checkout.VERSION})])def test_checkout_version_with_from_storage(storage_data, expected_storage):checkout = Checkout.from_storage(storage_data, Mock(), AnonymousUser(), 'tracking_code')@@ -55,8 +51,10 @@ def test_checkout_is_shipping_required():def test_checkout_deliveries():partition = Mock(- get_total=Mock(return_value=Price(10, currency=settings.DEFAULT_CURRENCY)),- get_price_per_item=Mock(return_value=Price(10, currency=settings.DEFAULT_CURRENCY)))+ get_total=Mock(+ return_value=Price(10, currency=settings.DEFAULT_CURRENCY)),+ get_price_per_item=Mock(+ return_value=Price(10, currency=settings.DEFAULT_CURRENCY)))def f():yield partition@@ -78,32 +76,41 @@ def test_checkout_deliveries_with_shipping_method(monkeypatch):partition = Mock(is_shipping_required=MagicMock(return_value=True),- get_total=Mock(return_value=Price(items_cost, currency=settings.DEFAULT_CURRENCY)),- get_price_per_item=Mock(return_value=Price(items_cost, currency=settings.DEFAULT_CURRENCY)))+ get_total=Mock(+ return_value=Price(+ items_cost, currency=settings.DEFAULT_CURRENCY)),+ get_price_per_item=Mock(+ return_value=Price(+ items_cost, currency=settings.DEFAULT_CURRENCY)))def f():yield partitionpartition.__iter__ = Mock(return_value=f())- cart = Mock(partition=Mock(return_value=[partition]),- currency=settings.DEFAULT_CURRENCY)-- shipping_method_mock = Mock(get_total=Mock(return_value=Price(shipping_cost, currency=settings.DEFAULT_CURRENCY)))+ cart = Mock(+ partition=Mock(return_value=[partition]),+ currency=settings.DEFAULT_CURRENCY)++ shipping_method_mock = Mock(+ get_total=Mock(+ return_value=Price(+ shipping_cost, currency=settings.DEFAULT_CURRENCY)))monkeypatch.setattr(Checkout, 'shipping_method', shipping_method_mock)checkout = Checkout(cart, AnonymousUser(), 'tracking_code')deliveries = list(checkout.deliveries)- assert deliveries[0][1] == Price(shipping_cost, currency=settings.DEFAULT_CURRENCY)- assert deliveries[0][2] == Price(items_cost + shipping_cost, currency=settings.DEFAULT_CURRENCY)+ assert deliveries[0][1] == Price(+ shipping_cost, currency=settings.DEFAULT_CURRENCY)+ assert deliveries[0][2] == Price(+ items_cost + shipping_cost, currency=settings.DEFAULT_CURRENCY)assert deliveries[0][0][0][0] == partition@pytest.mark.parametrize('user, shipping', [(Mock(default_shipping_address='user_shipping'), 'user_shipping'),- (AnonymousUser(), None),-])+ (AnonymousUser(), None)])def test_checkout_shipping_address_with_anonymous_user(user, shipping):checkout = Checkout(Mock(), user, 'tracking_code')assert checkout._shipping_address is None@@ -113,10 +120,11 @@ def test_checkout_shipping_address_with_anonymous_user(user, shipping):@pytest.mark.parametrize('address_objects, shipping', [(Mock(get=Mock(return_value='shipping')), 'shipping'),- (Mock(get=Mock(side_effect=Address.DoesNotExist)), None),-])-def test_checkout_shipping_address_with_storage(address_objects, shipping, monkeypatch):- monkeypatch.setattr('saleor.checkout.core.Address.objects', address_objects)+ (Mock(get=Mock(side_effect=Address.DoesNotExist)), None)])+def test_checkout_shipping_address_with_storage(+ address_objects, shipping, monkeypatch):+ monkeypatch.setattr(+ 'saleor.checkout.core.Address.objects', address_objects)checkout = Checkout(Mock(), AnonymousUser(), 'tracking_code')checkout.storage['shipping_address'] = {'id': 1}assert checkout.shipping_address == shipping@@ -129,22 +137,35 @@ def test_checkout_shipping_address_setter():checkout.shipping_address = addressassert checkout._shipping_address == addressassert checkout.storage['shipping_address'] == {- 'city': '', 'city_area': '', 'company_name': '', 'country': '', 'phone': '',- 'country_area': '', 'first_name': 'Jan', 'id': None, 'last_name': 'Kowalski',- 'postal_code': '', 'street_address_1': '', 'street_address_2': ''}+ 'city': '',+ 'city_area': '',+ 'company_name': '',+ 'country': '',+ 'country_area': '',+ 'first_name': 'Jan',+ 'id': None,+ 'last_name': 'Kowalski',+ 'phone': '',+ 'postal_code': '',+ 'street_address_1': '',+ 'street_address_2': ''}@pytest.mark.parametrize('shipping_address, shipping_method, value', [- (Mock(country=Mock(code='PL')),- Mock(country_code='PL', __eq__=lambda n, o: n.country_code == o.country_code),- Mock(country_code='PL')),+ (+ Mock(country=Mock(code='PL')),+ Mock(+ country_code='PL',+ __eq__=lambda n, o: n.country_code == o.country_code),+ Mock(country_code='PL')),(Mock(country=Mock(code='DE')), Mock(country_code='PL'), None),- (None, Mock(country_code='PL'), None),-])-def test_checkout_shipping_method(shipping_address, shipping_method, value, monkeypatch):+ (None, Mock(country_code='PL'), None)])+def test_checkout_shipping_method(+ shipping_address, shipping_method, value, monkeypatch):queryset = Mock(get=Mock(return_value=shipping_method))monkeypatch.setattr(Checkout, 'shipping_address', shipping_address)- monkeypatch.setattr('saleor.checkout.core.ShippingMethodCountry.objects', queryset)+ monkeypatch.setattr(+ 'saleor.checkout.core.ShippingMethodCountry.objects', queryset)checkout = Checkout(Mock(), AnonymousUser(), 'tracking_code')checkout.storage['shipping_method_country_id'] = 1assert checkout._shipping_method is None@@ -154,7 +175,8 @@ def test_checkout_shipping_method(shipping_address, shipping_method, value, monkdef test_checkout_shipping_does_not_exists(monkeypatch):queryset = Mock(get=Mock(side_effect=ShippingMethodCountry.DoesNotExist))- monkeypatch.setattr('saleor.checkout.core.ShippingMethodCountry.objects', queryset)+ monkeypatch.setattr(+ 'saleor.checkout.core.ShippingMethodCountry.objects', queryset)checkout = Checkout(Mock(), AnonymousUser(), 'tracking_code')checkout.storage['shipping_method_country_id'] = 1assert checkout.shipping_method is None@@ -173,9 +195,12 @@ def test_checkout_shipping_method_setter():@pytest.mark.parametrize('user, address', [(AnonymousUser(), None),- (Mock(default_billing_address='billing_address',- addresses=Mock(is_authenticated=Mock(return_value=True))), 'billing_address'),-])+ (+ Mock(+ default_billing_address='billing_address',+ addresses=Mock(+ is_authenticated=Mock(return_value=True))),+ 'billing_address')])def test_checkout_billing_address(user, address):checkout = Checkout(Mock(), user, 'tracking_code')assert checkout.billing_address == address@@ -183,23 +208,29 @@ def test_checkout_billing_address(user, address):@pytest.mark.parametrize('cart, status_code, url', [(Mock(__len__=Mock(return_value=0)), 302, '/cart/'),- (Mock(__len__=Mock(return_value=1),- is_shipping_required=Mock(return_value=True)),- 302, '/checkout/shipping-address/'),- (Mock(__len__=Mock(return_value=1),- is_shipping_required=Mock(return_value=False)),- 302, '/checkout/summary/'),- (Mock(__len__=Mock(return_value=0),- is_shipping_required=Mock(return_value=False)), 302, '/cart/'),-])+ (+ Mock(+ __len__=Mock(return_value=1),+ is_shipping_required=Mock(return_value=True)),+ 302, '/checkout/shipping-address/'),+ (+ Mock(+ __len__=Mock(return_value=1),+ is_shipping_required=Mock(return_value=False)),+ 302, '/checkout/summary/'),+ (+ Mock(+ __len__=Mock(return_value=0),+ is_shipping_required=Mock(return_value=False)),+ 302, '/cart/')])def test_index_view(cart, status_code, url, rf, monkeypatch):checkout = Checkout(cart, AnonymousUser(), 'tracking_code')request = rf.get('checkout:index')request.user = checkout.userrequest.session = {STORAGE_SESSION_KEY: checkout.for_storage()}request.discounts = []- monkeypatch.setattr('saleor.cart.utils.get_cart_from_request',- lambda req, qs : cart)+ monkeypatch.setattr(+ 'saleor.cart.utils.get_cart_from_request', lambda req, qs: cart)response = views.index_view(request)assert response.status_code == status_codeassert response.url == url@@ -228,8 +259,10 @@ def test_checkout_create_order_insufficient_stock(@pytest.mark.parametrize('note_value', [- '', ' ', ' test_note ','test_note'-])+ '',+ ' ',+ ' test_note ',+ 'test_note'])def test_note_form(note_value):checkout = Checkout(Mock(), AnonymousUser(), 'tracking_code')form = NoteForm({'note': note_value}, checkout=checkout)diff --git a/tests/test_collection.py b/tests/test_collection.pyindex 10c5eba6e1..2c232cfa04 100644--- a/tests/test_collection.py+++ b/tests/test_collection.py@@ -7,6 +7,13 @@ from saleor.dashboard.collection.forms import CollectionFormfrom saleor.product.models import Collection+def collection(db):+ collection = Collection.objects.create(+ name="Collection", slug='collection')+ return collection++def test_list_view(admin_client, collection):response = admin_client.get(reverse('dashboard:collection-list'))assert response.status_code == 200diff --git a/tests/test_core.py b/tests/test_core.pyindex 02b7be864a..22d7569aa5 100644--- a/tests/test_core.py+++ b/tests/test_core.py@@ -13,17 +13,16 @@ from saleor.shipping.models import ShippingMethodfrom saleor.userprofile.models import Address, User-type_schema = {'Vegetable': {- 'category': 'Food',- 'product_attributes': {- 'Sweetness': ['Sweet', 'Sour'],- 'Healthiness': ['Healthy', 'Not really']- },- 'variant_attributes': {- 'GMO': ['Yes', 'No']- },- 'images_dir': 'candy/',- 'is_shipping_required': True}}+type_schema = {+ 'Vegetable': {+ 'category': 'Food',+ 'product_attributes': {+ 'Sweetness': ['Sweet', 'Sour'],+ 'Healthiness': ['Healthy', 'Not really']},+ 'variant_attributes': {+ 'GMO': ['Yes', 'No']},+ 'images_dir': 'candy/',+ 'is_shipping_required': True}}@pytest.mark.parametrize('ip_data, expected_country', [@@ -117,9 +116,9 @@ def test_create_products_by_type(db):how_many = 5product_type = random_data.create_product_types_by_schema(type_schema)[0][0]- random_data.create_products_by_type(product_type, type_schema['Vegetable'],- '/', how_many=how_many,- create_images=False)+ random_data.create_products_by_type(+ product_type, type_schema['Vegetable'], '/',+ how_many=how_many, create_images=False)assert Product.objects.all().count() == how_manydiff --git a/tests/test_data_feeds.py b/tests/test_data_feeds.pyindex a518ec100c..22b19a0af9 100644--- a/tests/test_data_feeds.py+++ b/tests/test_data_feeds.py@@ -58,7 +58,8 @@ def test_write_feed(product_in_stock, monkeypatch):@patch('saleor.data_feeds.google_merchant.item_link')-def test_feed_contains_site_settings_domain(mocked_item_link, product_in_stock):+def test_feed_contains_site_settings_domain(+ mocked_item_link, product_in_stock):write_feed(StringIO())mocked_item_link.assert_called_once_with(product_in_stock.variants.first(), Site.objects.get_current())diff --git a/tests/test_discounts.py b/tests/test_discounts.pyindex 1548894e30..5ab268794b 100644--- a/tests/test_discounts.py+++ b/tests/test_discounts.py@@ -1,4 +1,4 @@-from datetime import date, datetime, timedelta+from datetime import date, timedeltafrom decimal import Decimalfrom unittest.mock import Mock@@ -6,15 +6,13 @@ import pytestfrom freezegun import freeze_timefrom prices import FixedDiscount, FractionalDiscount, Price-from saleor.cart.utils import get_category_variants_and_prices-from saleor.checkout.core import Checkoutfrom saleor.discount import (DiscountValueType, VoucherApplyToProduct, VoucherType)from saleor.discount.forms import CheckoutDiscountFormfrom saleor.discount.models import NotApplicable, Sale, Voucherfrom saleor.discount.utils import (decrease_voucher_usage, increase_voucher_usage)-from saleor.product.models import Category, Product, ProductVariant+from saleor.product.models import Product, ProductVariant@pytest.mark.parametrize('limit, value', [diff --git a/tests/test_elasticsearch.py b/tests/test_elasticsearch.pyindex 8b9246798f..8f26796d98 100644--- a/tests/test_elasticsearch.py+++ b/tests/test_elasticsearch.py@@ -33,7 +33,7 @@ def elasticsearch_enabled(settings):@pytest.fixture(scope='function', autouse=True)def elasticsearch_autosync_disabled(settings):- ''' Prevent ES index from being refreshed every time obj is saved '''+ """Prevent ES index from being refreshed every time objects are saved."""settings.ELASTICSEARCH_DSL_AUTO_REFRESH = Falsesettings.ELASTICSEARCH_DSL_AUTOSYNC = False@@ -41,13 +41,13 @@ def elasticsearch_autosync_disabled(settings):@pytest.mark.vcr()@pytest.fixturedef indexed_products(product_type, default_category):- ''' Products to be found by search backend+ """Products to be found by search backend.We need existing objects with primary keys same as search servicereturned in response. Otherwise search view won't find anything.Purpose of this fixture is for integration with search service only!pks must be in response in appropiate recorded cassette.- '''+ """def gen_product_with_id(object_id):product = Product.objects.create(pk=object_id,@@ -69,21 +69,20 @@ def execute_search(client, phrase):@pytest.mark.integration@pytest.mark.vcr(record_mode='once', match_on=MATCH_SEARCH_REQUEST)def test_new_search_with_empty_results(db, client):- ''' no products found with foo '''assert 0 == len(execute_search(client, PHRASE_WITHOUT_RESULTS))@pytest.mark.integration@pytest.mark.vcr(record_mode='once', match_on=MATCH_SEARCH_REQUEST)def test_new_search_with_result(db, indexed_products, client):- ''' some products founds, only those both in search result and objects '''found_products = execute_search(client, PHRASE_WITH_RESULTS)assert STOREFRONT_PRODUCTS == set(found_products)@pytest.fixturedef products_with_mixed_publishing(indexed_products):- products_to_unpublish = Product.objects.filter(pk__in=PRODUCTS_TO_UNPUBLISH)+ products_to_unpublish = Product.objects.filter(+ pk__in=PRODUCTS_TO_UNPUBLISH)for prod in products_to_unpublish:prod.is_published = Falseprod.save()@@ -92,8 +91,8 @@ def products_with_mixed_publishing(indexed_products):@pytest.mark.integration@pytest.mark.vcr(record_mode='once', match_on=MATCH_SEARCH_REQUEST)-def test_new_search_doesnt_show_unpublished(db, products_with_mixed_publishing,- client):+def test_new_search_doesnt_show_unpublished(+ db, products_with_mixed_publishing, client):published_products = STOREFRONT_PRODUCTS - PRODUCTS_TO_UNPUBLISHfound_products = execute_search(client, PHRASE_WITH_RESULTS)assert published_products == set(found_products)@@ -111,9 +110,8 @@ def execute_dashboard_search(client, phrase):@pytest.mark.integration@pytest.mark.vcr(record_mode='once', match_on=MATCH_SEARCH_REQUEST)def test_dashboard_search_with_empty_results(db, admin_client):- ''' no products found with foo '''- products, users, orders = execute_dashboard_search(admin_client,- PHRASE_WITHOUT_RESULTS)+ products, users, orders = execute_dashboard_search(+ admin_client, PHRASE_WITHOUT_RESULTS)assert 0 == len(products)assert 0 == len(users)assert 0 == len(orders)@@ -121,9 +119,8 @@ def test_dashboard_search_with_empty_results(db, admin_client):@pytest.mark.integration@pytest.mark.vcr(record_mode='once', match_on=MATCH_SEARCH_REQUEST)-def test_dashboard_search_with_product_result(db, indexed_products,- admin_client):- ''' products found in dashboard search view '''+def test_dashboard_search_with_product_result(+ db, indexed_products, admin_client):products, _, _ = execute_dashboard_search(admin_client,PHRASE_WITH_RESULTS)assert DASHBOARD_PRODUCTS == products@@ -151,7 +148,6 @@ def customers(db):@pytest.mark.integration@pytest.mark.vcr(record_mode='once', match_on=MATCH_SEARCH_REQUEST)def test_dashboard_search_user_by_email(db, admin_client, customers):- ''' user can be found in dashboard search by email address '''_, users, _ = execute_dashboard_search(admin_client, EXISTING_EMAIL)assert {USERS[EXISTING_EMAIL]} == users@@ -159,7 +155,6 @@ def test_dashboard_search_user_by_email(db, admin_client, customers):@pytest.mark.integration@pytest.mark.vcr(record_mode='once', match_on=MATCH_SEARCH_REQUEST)def test_dashboard_search_user_name(db, admin_client, customers):- ''' user can be found in dashboard search by partial name match '''_, users, _ = execute_dashboard_search(admin_client, EXISTING_NAME)assert USERS[EXISTING_NAME_FULL] in users@@ -178,6 +173,5 @@ def orders(db, billing_address):@pytest.mark.integration@pytest.mark.vcr(record_mode='once', match_on=MATCH_SEARCH_REQUEST)def test_dashboard_search_orders_by_user(db, admin_client, customers, orders):- ''' order can be found in dashboard search by customers email '''_, _, orders = execute_dashboard_search(admin_client, USER_WITH_ORDER)assert ORDERS[USER_WITH_ORDER] == ordersdiff --git a/tests/test_order.py b/tests/test_order.pyindex bf5a3d25b3..98b8ac6082 100644--- a/tests/test_order.py+++ b/tests/test_order.py@@ -1,5 +1,4 @@from decimal import Decimal-from django.test.client import RequestFactoryfrom django.urls import reversefrom prices import Pricediff --git a/tests/test_payment.py b/tests/test_payment.pyindex 0a8fa296fe..591f39ad37 100644--- a/tests/test_payment.py+++ b/tests/test_payment.py@@ -8,9 +8,11 @@ def test_get_purchased_items(order_with_lines, settings, voucher):payment = Payment.objects.create(order=order_with_lines, variant='paypal')discount = Price('10.0', currency=settings.DEFAULT_CURRENCY)- assert len(payment.get_purchased_items()) == len(order_with_lines.get_lines())+ assert len(payment.get_purchased_items()) == len(+ order_with_lines.get_lines())- for p, o in zip(payment.get_purchased_items(), order_with_lines.get_lines()):+ for p, o in zip(+ payment.get_purchased_items(), order_with_lines.get_lines()):assert p.sku == o.product_skuassert p.quantity == o.quantity@@ -19,11 +21,13 @@ def test_get_purchased_items(order_with_lines, settings, voucher):order_with_lines.voucher = voucherorder_with_lines.save()- settings.PAYMENT_VARIANTS = { 'paypal': ('PaypalProvider', {})}+ settings.PAYMENT_VARIANTS = {'paypal': ('PaypalProvider', {})}- assert len(payment.get_purchased_items()) == len(order_with_lines.get_lines()) + 1+ assert len(payment.get_purchased_items()) == len(+ order_with_lines.get_lines()) + 1- for p, o in zip(payment.get_purchased_items()[:-1], order_with_lines.get_lines()):+ for p, o in zip(+ payment.get_purchased_items()[:-1], order_with_lines.get_lines()):assert p.sku == o.product_skuassert p.quantity == o.quantitydiff --git a/tests/test_postgresql_search.py b/tests/test_postgresql_search.pyindex 31655e52f5..9de73177fd 100644--- a/tests/test_postgresql_search.py+++ b/tests/test_postgresql_search.py@@ -32,7 +32,7 @@ def named_products(default_category, product_type):def search_storefront(client, phrase):- '''Execute storefront search on client mathing phrase'''+ """Execute storefront search on client matching phrase."""resp = client.get(reverse('search:search'), {'q': phrase})return [prod for prod, _ in resp.context['results'].object_list]@@ -64,7 +64,7 @@ def test_storefront_filter_published_products(client, named_products):def search_dashboard(client, phrase):- '''Execute dashboard search on client mathing phrase'''+ """Execute dashboard search on client matching phrase."""response = client.get(reverse('dashboard:search'), {'q': phrase})assert response.context['query'] in phrasecontext = response.context@@ -109,13 +109,13 @@ ORDERS = [[pk] + list(user) for pk, user in zip(ORDER_IDS, USERS)]def gen_address_for_user(first_name, last_name):return Address.objects.create(- first_name=first_name,- last_name=last_name,- company_name='Mirumee Software',- street_address_1='Tęczowa 7',- city='Wrocław',- postal_code='53-601',- country='PL')+ first_name=first_name,+ last_name=last_name,+ company_name='Mirumee Software',+ street_address_1='Tęczowa 7',+ city='Wrocław',+ postal_code='53-601',+ country='PL')@pytest.fixturediff --git a/tests/test_product.py b/tests/test_product.pyindex 72fc87aefe..a3d0097f42 100644--- a/tests/test_product.py+++ b/tests/test_product.py@@ -413,12 +413,13 @@ def test_product_filter_before_filtering(def test_product_filter_product_exists(authorized_client, product_in_stock,default_category):- products = (models.Product.objects.all()- .filter(category__name=default_category)- .order_by('-price'))+ 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})data = {'price_0': [''], 'price_1': ['20']}response = authorized_client.get(url, data)assert list(response.context['filter_set'].qs) == list(products)@@ -427,8 +428,8 @@ def test_product_filter_product_exists(authorized_client, product_in_stock,def test_product_filter_product_does_not_exist(authorized_client, product_in_stock, 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)@@ -436,12 +437,13 @@ def test_product_filter_product_does_not_exist(def test_product_filter_form(authorized_client, product_in_stock,default_category):- products = (models.Product.objects.all()- .filter(category__name=default_category)- .order_by('-price'))+ 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 'price' in response.context['filter_set'].form.fields.keys()assert 'sort_by' in response.context['filter_set'].form.fields.keys()@@ -449,13 +451,14 @@ def test_product_filter_form(authorized_client, product_in_stock,def test_product_filter_sorted_by_price_descending(- authorized_client, product_list, default_category):- products = (models.Product.objects.all()- .filter(category__name=default_category, is_published=True)- .order_by('-price'))+ authorized_client, product_list, default_category):+ products = (+ models.Product.objects.all()+ .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)@@ -464,19 +467,14 @@ def test_product_filter_sorted_by_price_descending(def test_product_filter_sorted_by_wrong_parameter(authorized_client, product_in_stock, 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)def test_get_variant_picker_data_proper_variant_count(product_in_stock):- """- test checks if get_variant_picker_data provide proper count of- variant information from available product variants and not count- of variant attributes from product type- """data = get_variant_picker_data(product_in_stock, discounts=None, local_currency=None)@@ -485,24 +483,23 @@ def test_get_variant_picker_data_proper_variant_count(product_in_stock):def test_view_ajax_available_variants_list(admin_client, product_in_stock):variant = product_in_stock.variants.first()- variants_list = [- {'id': variant.pk, 'text': '123, Test product (Size: Small), $10.00'}- ]+ variant_list = [+ {'id': variant.pk, 'text': '123, Test product (Size: Small), $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'))assert response.status_code == 200- assert resp_decoded == {'results': variants_list}+ assert resp_decoded == {'results': variant_list}def test_view_ajax_available_products_list(admin_client, product_in_stock):- products_list = [{'id': product_in_stock.pk, 'text': 'Test product'}]+ product_list = [{'id': product_in_stock.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'))assert response.status_code == 200- assert resp_decoded == {'results': products_list}+ assert resp_decoded == {'results': product_list}diff --git a/tests/test_product_tags.py b/tests/test_product_tags.pyindex 91458c5039..3de94651cf 100644--- a/tests/test_product_tags.py+++ b/tests/test_product_tags.py@@ -19,7 +19,6 @@ def test_get_thumbnail():def test_get_thumbnail_no_instance(monkeypatch):- """When no instance, function should return placeholder"""monkeypatch.setattr('saleor.product.templatetags.product_images.choose_placeholder',lambda x: 'placeholder')diff --git a/tests/test_templatetags.py b/tests/test_templatetags.pyindex 72d546aa1a..e6c4d61870 100644--- a/tests/test_templatetags.py+++ b/tests/test_templatetags.py@@ -1,5 +1,3 @@-import pytest-from django.urls import reversefrom saleor.core.templatetags.shop import get_sort_by_urldiff --git a/tests/test_userprofile.py b/tests/test_userprofile.pyindex d643da3698..cba400d3b2 100644--- a/tests/test_userprofile.py+++ b/tests/test_userprofile.py@@ -9,7 +9,7 @@ from django.template import Context, Templatefrom django.urls import reversefrom django_countries.fields import Country-from saleor.userprofile import forms, i18n, models+from saleor.userprofile import forms, i18nfrom saleor.userprofile.templatetags.i18n_address_tags import format_addressfrom saleor.userprofile.validators import validate_possible_number@@ -59,21 +59,22 @@ def test_address_form_postal_code_validation():assert 'postal_code' in errors[email protected]('form_data, form_valid, expected_preview, expected_country',[- ({'preview': True}, False, True, 'PL'),- ({'preview': False,- 'street_address_1': 'Foo bar',- 'postal_code': '00-123',- 'city': 'Warsaw'- }, True, False, 'PL'),- ({'preview': True, 'country': 'US'}, False, True, 'US'),- ({'preview': False,- 'street_address_1': 'Foo bar',- 'postal_code': '0213',- 'city': 'Warsaw'- }, False, False, 'PL'),-])-def test_get_address_form(form_data, form_valid, expected_preview, expected_country):+ 'form_data, form_valid, expected_preview, expected_country', [+ ({'preview': True}, False, True, 'PL'),+ ({+ 'preview': False,+ 'street_address_1': 'Foo bar',+ 'postal_code': '00-123',+ 'city': 'Warsaw'}, True, False, 'PL'),+ ({'preview': True, 'country': 'US'}, False, True, 'US'),+ ({+ 'preview': False,+ 'street_address_1': 'Foo bar',+ 'postal_code': '0213',+ 'city': 'Warsaw'}, False, False, 'PL')])+def test_get_address_form(+ form_data, form_valid, expected_preview, expected_country):data = {'first_name': 'John','last_name': 'Doe',@@ -145,8 +146,9 @@ def test_format_address_all_options(billing_address):address_html = ', '.join(map(str, formatted_address['address_lines']))context = Context({'address': billing_address})tpl = Template(- '{% load i18n_address_tags %}'- '{% format_address address include_phone=False inline=True latin=True %}')+ r'{% load i18n_address_tags %}'+ r'{% format_address address include_phone=False inline=True'+ r' latin=True %}')rendered_html = tpl.render(context)assert address_html in rendered_htmlassert 'inline-address' in rendered_html