Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Implement versatile generation of Category/ Collection thumbnails And refactored product API tests to proper files.
NyanKiyoshi7a5185cd491e
diff --git a/saleor/dashboard/category/forms.py b/saleor/dashboard/category/forms.pyindex 94d238e694..3d561e16d6 100644--- a/saleor/dashboard/category/forms.py+++ b/saleor/dashboard/category/forms.py@@ -5,6 +5,7 @@ from django.utils.translation import pgettext_lazyfrom text_unidecode import unidecodefrom ...product.models import Category+from ...product.thumbnails import create_category_background_image_thumbnailsfrom ..seo.fields import SeoDescriptionField, SeoTitleField@@ -29,7 +30,14 @@ class CategoryForm(forms.ModelForm):def save(self, commit=True):self.instance.slug = slugify(unidecode(self.instance.name))+if self.parent_pk:self.instance.parent = get_object_or_404(Category, pk=self.parent_pk)- return super().save(commit=commit)++ instance = super().save(commit=commit)++ if instance.pk and 'background_image' in self.changed_data:+ create_category_background_image_thumbnails.delay(instance.pk)++ return instancediff --git a/saleor/dashboard/collection/forms.py b/saleor/dashboard/collection/forms.pyindex 0c250064a4..7a9b36a772 100644--- a/saleor/dashboard/collection/forms.py+++ b/saleor/dashboard/collection/forms.py@@ -5,6 +5,7 @@ from django.utils.translation import pgettext_lazyfrom text_unidecode import unidecodefrom ...product.models import Collection, Product+from ...product.thumbnails import create_collection_background_image_thumbnailsfrom ...site.models import SiteSettingsfrom ..forms import AjaxSelect2MultipleChoiceFieldfrom ..seo.fields import SeoDescriptionField, SeoTitleField@@ -38,7 +39,12 @@ class CollectionForm(forms.ModelForm):def save(self, commit=True):self.instance.slug = slugify(unidecode(self.instance.name))- return super().save(commit=commit)+ instance = super().save(commit=commit)++ if instance.pk and 'background_image' in self.changed_data:+ create_collection_background_image_thumbnails.delay(instance.pk)++ return instanceclass AssignHomepageCollectionForm(forms.ModelForm):diff --git a/saleor/graphql/product/mutations/products.py b/saleor/graphql/product/mutations/products.pyindex f32c557970..7c8f891b3d 100644--- a/saleor/graphql/product/mutations/products.py+++ b/saleor/graphql/product/mutations/products.py@@ -7,7 +7,9 @@ from graphql_jwt.decorators import permission_requiredfrom ....product import modelsfrom ....product.tasks import update_variants_names-from ....product.thumbnails import create_product_thumbnails+from ....product.thumbnails import (+ create_category_background_image_thumbnails,+ create_collection_background_image_thumbnails, create_product_thumbnails)from ....product.utils.attributes import get_name_from_attributesfrom ...core.mutations import BaseMutation, ModelDeleteMutation, ModelMutationfrom ...core.types.common import Decimal, SeoInput@@ -63,6 +65,12 @@ class CategoryCreate(ModelMutation):data['input']['parent_id'] = parent_idreturn super().mutate(root, info, **data)+ @classmethod+ def save(cls, info, instance, cleaned_input):+ instance.save()+ if cleaned_input.get('background_image'):+ create_category_background_image_thumbnails.delay(instance.pk)+class CategoryUpdate(CategoryCreate):class Arguments:@@ -75,6 +83,12 @@ class CategoryUpdate(CategoryCreate):description = 'Updates a category.'model = models.Category+ @classmethod+ def save(cls, info, instance, cleaned_input):+ if cleaned_input.get('background_image'):+ create_category_background_image_thumbnails.delay(instance.pk)+ instance.save()+class CategoryDelete(ModelDeleteMutation):class Arguments:@@ -128,6 +142,12 @@ class CollectionCreate(ModelMutation):clean_seo_fields(cleaned_input)return cleaned_input+ @classmethod+ def save(cls, info, instance, cleaned_input):+ instance.save()+ if cleaned_input.get('background_image'):+ create_collection_background_image_thumbnails.delay(instance.pk)+class CollectionUpdate(CollectionCreate):class Arguments:@@ -141,6 +161,12 @@ class CollectionUpdate(CollectionCreate):description = 'Updates a collection.'model = models.Collection+ @classmethod+ def save(cls, info, instance, cleaned_input):+ if cleaned_input.get('background_image'):+ create_collection_background_image_thumbnails.delay(instance.pk)+ instance.save()+class CollectionDelete(ModelDeleteMutation):class Arguments:diff --git a/saleor/product/migrations/0077_generate_versatile_background_images.py b/saleor/product/migrations/0077_generate_versatile_background_images.pynew file mode 100644index 0000000000..128ca4f668--- /dev/null+++ b/saleor/product/migrations/0077_generate_versatile_background_images.py@@ -0,0 +1,41 @@+# Generated by Django 2.1.2 on 2018-11-11 16:08+from sys import stderr++from django.db import migrations, models+from versatileimagefield.image_warmer import VersatileImageFieldWarmer++from saleor.product.models import Category, Collection+++def log_failed_images(failed_to_create):+ if failed_to_create:+ print('Failed to generate thumbnails:', file=stderr)+ for path in failed_to_create:+ print(path, file=stderr)+++def warm_model_background_images(model: models.Model):+ warmer = VersatileImageFieldWarmer(+ instance_or_queryset=model.objects.all(),+ rendition_key_set='background_images',+ image_attr='background_image',+ verbose=True)+ num_created, failed_to_create = warmer.warm()+ log_failed_images(failed_to_create)+++def warm_background_images(*_):+ print('Failed to generate thumbnails for Categories', file=stderr)+ warm_model_background_images(Category)++ print('Failed to generate thumbnails for Collections', file=stderr)+ warm_model_background_images(Collection)+++class Migration(migrations.Migration):++ dependencies = [+ ('product', '0076_auto_20181012_1146')]++ operations = [+ migrations.RunPython(warm_background_images)]diff --git a/saleor/product/templatetags/product_images.py b/saleor/product/templatetags/product_images.pyindex 4e5c0ab5aa..cc971bb666 100644--- a/saleor/product/templatetags/product_images.py+++ b/saleor/product/templatetags/product_images.py@@ -12,12 +12,13 @@ register = template.Library()# cache available sizes at module leveldef get_available_sizes():- all_sizes = set()+ rendition_sizes = {}keys = settings.VERSATILEIMAGEFIELD_RENDITION_KEY_SETSfor dummy_size_group, sizes in keys.items():+ group_sizes = rendition_sizes.setdefault(dummy_size_group, set())for dummy_size_name, size in sizes:- all_sizes.add(size)- return all_sizes+ group_sizes.add(size)+ return rendition_sizesAVAILABLE_SIZES = get_available_sizes()@@ -45,26 +46,30 @@ def choose_placeholder(size=''):return placeholder-def get_available_sizes_by_method(method):+def get_available_sizes_by_method(method, rendition_key_set):sizes = []- for available_size in AVAILABLE_SIZES:+ for available_size in AVAILABLE_SIZES[rendition_key_set]:available_method, avail_size_str = available_size.split('__')if available_method == method:sizes.append(min([int(s) for s in avail_size_str.split('x')]))return sizes-def get_thumbnail_size(size, method):+def get_thumbnail_size(size, method, rendition_key_set):""" Return closest larger size if not more than 2 times larger, otherwisereturn closest smaller size"""on_demand = settings.VERSATILEIMAGEFIELD_SETTINGS['create_images_on_demand']- size_str = '%sx%s' % (size, size)+ if isinstance(size, int):+ size_str = '%sx%s' % (size, size)+ else:+ size_str = sizesize_name = '%s__%s' % (method, size_str)- if size_name in AVAILABLE_SIZES or on_demand:+ if size_name in AVAILABLE_SIZES[rendition_key_set] or on_demand:return size_str- avail_sizes = sorted(get_available_sizes_by_method(method))+ avail_sizes = sorted(+ get_available_sizes_by_method(method, rendition_key_set))larger = [x for x in avail_sizes if size < x <= size * 2]smaller = [x for x in avail_sizes if x <= size]@@ -80,9 +85,9 @@ def get_thumbnail_size(size, method):@register.simple_tag()-def get_thumbnail(instance, size, method):+def get_thumbnail(instance, size, method, rendition_key_set='products'):if instance:- used_size = get_thumbnail_size(size, method)+ used_size = get_thumbnail_size(size, method, rendition_key_set)try:thumbnail = getattr(instance, method)[used_size]except Exception:diff --git a/saleor/product/thumbnails.py b/saleor/product/thumbnails.pyindex 091aa17edb..2787e0982e 100644--- a/saleor/product/thumbnails.py+++ b/saleor/product/thumbnails.py@@ -1,10 +1,28 @@from celery import shared_taskfrom ..core.utils import create_thumbnails-from .models import ProductImage+from .models import Category, Collection, ProductImage@shared_taskdef create_product_thumbnails(image_id):- """Takes ProductImage model, and creates thumbnails for it."""+ """Takes a ProductImage model, and creates thumbnails for it."""create_thumbnails(pk=image_id, model=ProductImage, size_set='products')+++@shared_task+def create_category_background_image_thumbnails(category_id):+ """Takes a Product model,+ and creates the background image thumbnails for it."""+ create_thumbnails(+ pk=category_id, model=Category,+ size_set='background_images', image_attr='background_image')+++@shared_task+def create_collection_background_image_thumbnails(collection_id):+ """Takes a Collection model,+ and creates the background image thumbnails for it."""+ create_thumbnails(+ pk=collection_id, model=Collection,+ size_set='background_images', image_attr='background_image')diff --git a/saleor/settings.py b/saleor/settings.pyindex dfd6c1afd3..741ce0e967 100644--- a/saleor/settings.py+++ b/saleor/settings.py@@ -400,7 +400,9 @@ VERSATILEIMAGEFIELD_RENDITION_KEY_SETS = {('product_small', 'thumbnail__60x60'),('product_small_2x', 'thumbnail__120x120'),('product_list', 'thumbnail__255x255'),- ('product_list_2x', 'thumbnail__510x510')]}+ ('product_list_2x', 'thumbnail__510x510')],+ 'background_images': [+ ('background_image', 'thumbnail__960x320')]}VERSATILEIMAGEFIELD_SETTINGS = {# Images should be pre-generated on Production environmentdiff --git a/templates/product/product_list_base.html b/templates/product/product_list_base.htmlindex 63936af5cf..29fb2c3456 100644--- a/templates/product/product_list_base.html+++ b/templates/product/product_list_base.html@@ -2,6 +2,7 @@{% load bootstrap_pagination from bootstrap4 %}{% load build_absolute_uri from urls %}{% load get_object_properties from attributes %}+{% load get_thumbnail from product_images %}{% load i18n %}{% load shop %}{% load static %}@@ -113,7 +114,8 @@{% block topcontent %}{% if object.background_image %}- <div class="row" id="product-list-image" style="background-image: url('{{ object.background_image.url }}')"></div>+ <div class="row" id="product-list-image"+ style="background-image: url({% get_thumbnail object.background_image size='960x320' method="thumbnail" rendition_key_set="background_images" %})"></div>{% endif %}{% endblock topcontent %}diff --git a/tests/api/test_category.py b/tests/api/test_category.pyindex 8d72ddf4fb..b41f043bde 100644--- a/tests/api/test_category.py+++ b/tests/api/test_category.py@@ -2,6 +2,8 @@ import pytestimport graphenefrom django.template.defaultfilters import slugify+from unittest.mock import Mock+from saleor.product.models import Categoryfrom tests.utils import create_imagefrom tests.api.utils import get_graphql_content, get_multipart_request_body@@ -45,7 +47,7 @@ def test_category_query(user_api_client, product):def test_category_create_mutation(- staff_api_client, permission_manage_products):+ monkeypatch, staff_api_client, permission_manage_products):query = """mutation($name: String, $slug: String, $description: String, $backgroundImage: Upload, $parentId: ID) {categoryCreate(@@ -75,6 +77,12 @@ def test_category_create_mutation(}"""+ mock_create_thumbnails = Mock(return_value=None)+ monkeypatch.setattr(+ ('saleor.dashboard.category.forms.'+ 'create_category_background_image_thumbnails.delay'),+ mock_create_thumbnails)+category_name = 'Test category'category_slug = slugify(category_name)category_description = 'Test description'@@ -95,6 +103,7 @@ def test_category_create_mutation(assert not data['category']['parent']category = Category.objects.get(name=category_name)assert category.background_image.file+ mock_create_thumbnails.assert_called_once_with(category.pk)# test creating subcategoryparent_id = data['category']['id']@@ -108,8 +117,60 @@ def test_category_create_mutation(assert data['category']['parent']['id'] == parent_id+def test_category_create_mutation_without_background_image(+ monkeypatch, staff_api_client, permission_manage_products):+ query = """+ mutation($name: String, $slug: String, $description: String, $parentId: ID) {+ categoryCreate(+ input: {+ name: $name+ slug: $slug+ description: $description+ },+ parent: $parentId+ ) {+ category {+ id+ name+ slug+ description+ parent {+ name+ id+ }+ }+ errors {+ field+ message+ }+ }+ }+ """++ mock_create_thumbnails = Mock(return_value=None)+ monkeypatch.setattr(+ ('saleor.dashboard.category.forms.'+ 'create_category_background_image_thumbnails.delay'),+ mock_create_thumbnails)++ category_name = 'Test category'+ category_slug = slugify(category_name)+ category_description = 'Test description'++ # test creating root category+ variables = {+ 'name': category_name, 'description': category_description,+ 'slug': category_slug}+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_products])+ content = get_graphql_content(response)+ data = content['data']['categoryCreate']+ assert data['errors'] == []+ assert mock_create_thumbnails.call_count == 0++def test_category_update_mutation(- staff_api_client, category, permission_manage_products):+ monkeypatch, staff_api_client, category, permission_manage_products):query = """mutation($id: ID!, $name: String, $slug: String, $backgroundImage: Upload, $description: String) {categoryUpdate(@@ -136,6 +197,13 @@ def test_category_update_mutation(}}"""++ mock_create_thumbnails = Mock(return_value=None)+ monkeypatch.setattr(+ ('saleor.dashboard.category.forms.'+ 'create_category_background_image_thumbnails.delay'),+ mock_create_thumbnails)+# create child category and test that the update mutation won't change# it's parentchild_category = category.children.create(name='child')@@ -164,6 +232,65 @@ def test_category_update_mutation(assert data['category']['parent']['id'] == parent_idcategory = Category.objects.get(name=category_name)assert category.background_image.file+ mock_create_thumbnails.assert_called_once_with(category.pk)+++def test_category_update_mutation_without_background_image(+ monkeypatch, staff_api_client, category, permission_manage_products):+ query = """+ mutation($id: ID!, $name: String, $slug: String, $description: String) {+ categoryUpdate(+ id: $id+ input: {+ name: $name+ description: $description+ slug: $slug+ }+ ) {+ category {+ id+ name+ description+ parent {+ id+ }+ }+ errors {+ field+ message+ }+ }+ }+ """++ mock_create_thumbnails = Mock(return_value=None)+ monkeypatch.setattr(+ ('saleor.dashboard.category.forms.'+ 'create_category_background_image_thumbnails.delay'),+ mock_create_thumbnails)++ # create child category and test that the update mutation won't change+ # it's parent+ child_category = category.children.create(name='child')++ category_name = 'Updated name'+ category_slug = slugify(category_name)+ category_description = 'Updated description'++ category_id = graphene.Node.to_global_id('Category', child_category.pk)++ # test creating root category+ variables = {+ 'id': category_id,+ 'name': category_name, 'description': category_description,+ 'slug': category_slug}+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_products])++ content = get_graphql_content(response)+ data = content['data']['categoryUpdate']+ assert data['errors'] == []+ assert mock_create_thumbnails.call_count == 0def test_category_delete_mutation(@@ -213,7 +340,7 @@ def test_category_level(user_api_client, category):content = get_graphql_content(response)category_data = content['data']['categories']['edges'][0]['node']assert category_data['name'] == category.name- assert category_data['parent'] == None+ assert category_data['parent'] is Nonequery = """query leveled_categories($level: Int) {@@ -235,3 +362,48 @@ def test_category_level(user_api_client, category):category_data = content['data']['categories']['edges'][0]['node']assert category_data['name'] == child.nameassert category_data['parent']['name'] == category.name+++def test_category_image_query(user_api_client, non_default_category):+ category = non_default_category+ image_file, image_name = create_image()+ category.background_image = image_file+ category.save()+ category_id = graphene.Node.to_global_id('Category', category.pk)+ query = """+ query fetchCategory($id: ID!){+ category(id: $id) {+ backgroundImage {+ url(size: 120)+ }+ }+ }+ """+ variables = {'id': category_id}+ response = user_api_client.post_graphql(query, variables)+ content = get_graphql_content(response)+ data = content['data']['category']+ thumbnail_url = category.background_image.thumbnail['120x120'].url+ assert thumbnail_url in data['backgroundImage']['url']+++def test_category_image_query_without_associated_file(+ user_api_client, non_default_category):+ category = non_default_category+ category_id = graphene.Node.to_global_id('Category', category.pk)+ query = """+ query fetchCategory($id: ID!){+ category(id: $id) {+ name+ backgroundImage {+ url+ }+ }+ }+ """+ variables = {'id': category_id}+ response = user_api_client.post_graphql(query, variables)+ content = get_graphql_content(response)+ data = content['data']['category']+ assert data['name'] == category.name+ assert data['backgroundImage'] is Nonediff --git a/tests/api/test_checkout.py b/tests/api/test_checkout.pyindex f0523bebd0..c7d21ffdb6 100644--- a/tests/api/test_checkout.py+++ b/tests/api/test_checkout.py@@ -7,7 +7,6 @@ from tests.api.utils import get_graphql_contentfrom saleor.checkout.models import Cartfrom saleor.order.models import Order-from saleor.payment import TransactionKinddef test_checkout_create(user_api_client, variant, graphql_address_data):diff --git a/tests/api/test_collection.py b/tests/api/test_collection.pynew file mode 100644index 0000000000..ec2fe65c6a--- /dev/null+++ b/tests/api/test_collection.py@@ -0,0 +1,353 @@+import graphene+import pytest+from django.utils.text import slugify+from graphql_relay import to_global_id+from unittest.mock import Mock++from saleor.product.models import Collection+from tests.utils import create_image+from .utils import get_graphql_content, get_multipart_request_body+++def test_collections_query(+ user_api_client, staff_api_client, collection, draft_collection,+ permission_manage_products):+ query = """+ query Collections {+ collections(first: 2) {+ edges {+ node {+ isPublished+ name+ slug+ products {+ totalCount+ }+ }+ }+ }+ }+ """++ # query public collections only as regular user+ response = user_api_client.post_graphql(query)+ content = get_graphql_content(response)+ edges = content['data']['collections']['edges']+ assert len(edges) == 1+ collection_data = edges[0]['node']+ assert collection_data['isPublished']+ assert collection_data['name'] == collection.name+ assert collection_data['slug'] == collection.slug+ assert collection_data['products']['totalCount'] == collection.products.count()++ # query all collections only as a staff user with proper permissions+ staff_api_client.user.user_permissions.add(permission_manage_products)+ response = staff_api_client.post_graphql(query)+ content = get_graphql_content(response)+ edges = content['data']['collections']['edges']+ assert len(edges) == 2+++def test_create_collection(+ monkeypatch, staff_api_client, product_list, permission_manage_products):+ query = """+ mutation createCollection(+ $name: String!, $slug: String!, $products: [ID], $backgroundImage: Upload!, $isPublished: Boolean!) {+ collectionCreate(+ input: {name: $name, slug: $slug, products: $products, backgroundImage: $backgroundImage, isPublished: $isPublished}) {+ collection {+ name+ slug+ products {+ totalCount+ }+ }+ }+ }+ """++ mock_create_thumbnails = Mock(return_value=None)+ monkeypatch.setattr(+ ('saleor.dashboard.collection.forms.'+ 'create_collection_background_image_thumbnails.delay'),+ mock_create_thumbnails)++ product_ids = [+ to_global_id('Product', product.pk) for product in product_list]+ image_file, image_name = create_image()+ name = 'test-name'+ slug = 'test-slug'+ variables = {+ 'name': name, 'slug': slug, 'products': product_ids,+ 'backgroundImage': image_name, 'isPublished': True}+ body = get_multipart_request_body(query, variables, image_file, image_name)+ response = staff_api_client.post_multipart(+ body, permissions=[permission_manage_products])+ content = get_graphql_content(response)+ data = content['data']['collectionCreate']['collection']+ assert data['name'] == name+ assert data['slug'] == slug+ assert data['products']['totalCount'] == len(product_ids)+ collection = Collection.objects.get(slug=slug)+ assert collection.background_image.file+ mock_create_thumbnails.assert_called_once_with(collection.pk)+++def test_create_collection_without_background_image(+ monkeypatch, staff_api_client, product_list, permission_manage_products):+ query = """+ mutation createCollection(+ $name: String!, $slug: String!, $products: [ID], $isPublished: Boolean!) {+ collectionCreate(+ input: {name: $name, slug: $slug, products: $products, isPublished: $isPublished}) {+ errors {+ field+ message+ }+ }+ }+ """++ mock_create_thumbnails = Mock(return_value=None)+ monkeypatch.setattr(+ ('saleor.dashboard.collection.forms.'+ 'create_collection_background_image_thumbnails.delay'),+ mock_create_thumbnails)++ variables = {+ 'name': 'test-name', 'slug': 'test-slug', 'isPublished': True}+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_products])+ get_graphql_content(response)+ assert mock_create_thumbnails.call_count == 0+++def test_update_collection(+ monkeypatch, staff_api_client, collection, permission_manage_products):+ query = """+ mutation updateCollection(+ $name: String!, $slug: String!, $id: ID!, $isPublished: Boolean!) {+ collectionUpdate(+ id: $id, input: {name: $name, slug: $slug, isPublished: $isPublished}) {+ collection {+ name+ slug+ }+ }+ }+ """++ mock_create_thumbnails = Mock(return_value=None)+ monkeypatch.setattr(+ ('saleor.dashboard.collection.forms.'+ 'create_collection_background_image_thumbnails.delay'),+ mock_create_thumbnails)++ name = 'new-name'+ slug = 'new-slug'+ variables = {+ 'name': name, 'slug': slug,+ 'id': to_global_id('Collection', collection.id), 'isPublished': True}+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_products])+ content = get_graphql_content(response)+ data = content['data']['collectionUpdate']['collection']+ assert data['name'] == name+ assert data['slug'] == slug+ assert mock_create_thumbnails.call_count == 0+++def test_update_collection_with_background_image(+ monkeypatch, staff_api_client, collection, permission_manage_products):+ query = """+ mutation updateCollection(+ $name: String!, $slug: String!, $id: ID!, $backgroundImage: Upload, $isPublished: Boolean!) {+ collectionUpdate(+ id: $id, input: {+ name: $name,+ slug: $slug,+ backgroundImage: $backgroundImage,+ isPublished: $isPublished+ }+ ) {+ collection {+ slug+ }+ errors {+ field+ message+ }+ }+ }+ """++ mock_create_thumbnails = Mock(return_value=None)+ monkeypatch.setattr(+ ('saleor.dashboard.collection.forms.'+ 'create_collection_background_image_thumbnails.delay'),+ mock_create_thumbnails)++ image_file, image_name = create_image()+ variables = {+ 'name': 'new-name',+ 'slug': 'new-slug',+ 'id': to_global_id('Collection', collection.id),+ 'backgroundImage': image_name,+ 'isPublished': True}+ body = get_multipart_request_body(query, variables, image_file, image_name)+ response = staff_api_client.post_multipart(+ body, permissions=[permission_manage_products])+ content = get_graphql_content(response)+ data = content['data']['collectionUpdate']+ assert not data['errors']+ slug = data['collection']['slug']+ collection = Collection.objects.get(slug=slug)+ assert collection.background_image+ mock_create_thumbnails.assert_called_once_with(collection.pk)+++def test_delete_collection(+ staff_api_client, collection, permission_manage_products):+ query = """+ mutation deleteCollection($id: ID!) {+ collectionDelete(id: $id) {+ collection {+ name+ }+ }+ }+ """+ collection_id = to_global_id('Collection', collection.id)+ variables = {'id': collection_id}+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_products])+ content = get_graphql_content(response)+ data = content['data']['collectionDelete']['collection']+ assert data['name'] == collection.name+ with pytest.raises(collection._meta.model.DoesNotExist):+ collection.refresh_from_db()+++def test_auto_create_slug_on_collection(+ staff_api_client, product_list, permission_manage_products):+ query = """+ mutation createCollection(+ $name: String!, $isPublished: Boolean!) {+ collectionCreate(+ input: {name: $name, isPublished: $isPublished}) {+ collection {+ name+ slug+ }+ }+ }+ """+ name = 'test name123'+ variables = {'name': name, 'isPublished': True}+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_products])+ content = get_graphql_content(response)+ data = content['data']['collectionCreate']['collection']+ assert data['name'] == name+ assert data['slug'] == slugify(name)+++def test_add_products_to_collection(+ staff_api_client, collection, product_list,+ permission_manage_products):+ query = """+ mutation collectionAddProducts(+ $id: ID!, $products: [ID]!) {+ collectionAddProducts(collectionId: $id, products: $products) {+ collection {+ products {+ totalCount+ }+ }+ }+ }+ """+ collection_id = to_global_id('Collection', collection.id)+ product_ids = [+ to_global_id('Product', product.pk) for product in product_list]+ no_products_before = collection.products.count()+ variables = {'id': collection_id, 'products': product_ids}+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_products])+ content = get_graphql_content(response)+ data = content['data']['collectionAddProducts']['collection']+ assert data[+ 'products']['totalCount'] == no_products_before + len(product_ids)+++def test_remove_products_from_collection(+ staff_api_client, collection, product_list,+ permission_manage_products):+ query = """+ mutation collectionRemoveProducts(+ $id: ID!, $products: [ID]!) {+ collectionRemoveProducts(collectionId: $id, products: $products) {+ collection {+ products {+ totalCount+ }+ }+ }+ }+ """+ collection.products.add(*product_list)+ collection_id = to_global_id('Collection', collection.id)+ product_ids = [+ to_global_id('Product', product.pk) for product in product_list]+ no_products_before = collection.products.count()+ variables = {'id': collection_id, 'products': product_ids}+ response = staff_api_client.post_graphql(+ query, variables, permissions=[permission_manage_products])+ content = get_graphql_content(response)+ data = content['data']['collectionRemoveProducts']['collection']+ assert data[+ 'products']['totalCount'] == no_products_before - len(product_ids)+++def test_collection_image_query(user_api_client, collection):+ query = """+ query fetchCollection($id: ID!){+ collection(id: $id) {+ backgroundImage {+ url(size: 120)+ }+ }+ }+ """+ image_file, image_name = create_image()+ collection.background_image = image_file+ collection.save()+ collection_id = graphene.Node.to_global_id('Collection', collection.pk)+ variables = {'id': collection_id}+ response = user_api_client.post_graphql(query, variables)+ content = get_graphql_content(response)+ data = content['data']['collection']+ thumbnail_url = collection.background_image.thumbnail['120x120'].url+ assert thumbnail_url in data['backgroundImage']['url']+++def test_collection_image_query_without_associated_file(+ user_api_client, collection):+ query = """+ query fetchCollection($id: ID!){+ collection(id: $id) {+ name+ backgroundImage {+ url+ }+ }+ }+ """+ collection_id = graphene.Node.to_global_id('Collection', collection.pk)+ variables = {'id': collection_id}+ response = user_api_client.post_graphql(query, variables)+ content = get_graphql_content(response)+ data = content['data']['collection']+ assert data['name'] == collection.name+ assert data['backgroundImage'] is None+diff --git a/tests/api/test_product.py b/tests/api/test_product.pyindex 2c55169e1b..c9219b12bf 100644--- a/tests/api/test_product.py+++ b/tests/api/test_product.py@@ -11,8 +11,7 @@ from tests.utils import create_image, create_pdf_file_with_image_extfrom saleor.graphql.core.types import ReportingPeriodfrom saleor.graphql.product.types import StockAvailabilityfrom saleor.product.models import (- Category, Collection, Product, ProductImage,- ProductType, ProductVariant)+ Category, Product, ProductImage, ProductType, ProductVariant)from saleor.product.tasks import update_variants_namesfrom .utils import assert_no_permission, get_multipart_request_body@@ -160,7 +159,7 @@ def test_query_product_image_by_id(user_api_client, product_with_image):'productId': graphene.Node.to_global_id('Product', product_with_image.pk),'imageId': graphene.Node.to_global_id('ProductImage', image.pk)}response = user_api_client.post_graphql(query, variables)- content = get_graphql_content(response)+ get_graphql_content(response)def test_product_with_collections(@@ -321,7 +320,7 @@ def test_sort_products(user_api_client, product):asc_price_query = query % {'sort_by': 'price'}response = user_api_client.post_graphql(asc_price_query)content = get_graphql_content(response)- product_data = content['data']['products']['edges'][0]['node']+ content['data']['products']['edges'][0]['node']price_0 = content['data']['products']['edges'][0]['node']['price']['amount']price_1 = content['data']['products']['edges'][1]['node']['price']['amount']assert price_0 < price_1@@ -398,9 +397,9 @@ def test_create_product('Category', category.pk)product_description = 'test description'product_name = 'test name'- product_isPublished = True- product_chargeTaxes = True- product_taxRate = 'STANDARD'+ product_is_published = True+ product_charge_taxes = True+ product_tax_rate = 'STANDARD'product_price = 22.33# Default attribute defined in product_type fixture@@ -419,9 +418,9 @@ def test_create_product('categoryId': category_id,'name': product_name,'description': product_description,- 'isPublished': product_isPublished,- 'chargeTaxes': product_chargeTaxes,- 'taxRate': product_taxRate,+ 'isPublished': product_is_published,+ 'chargeTaxes': product_charge_taxes,+ 'taxRate': product_tax_rate,'price': product_price,'attributes': [{'slug': color_attr_slug, 'value': color_value_slug},@@ -434,9 +433,9 @@ def test_create_product(assert data['errors'] == []assert data['product']['name'] == product_nameassert data['product']['description'] == product_description- assert data['product']['isPublished'] == product_isPublished- assert data['product']['chargeTaxes'] == product_chargeTaxes- assert data['product']['taxRate'] == product_taxRate.lower()+ assert data['product']['isPublished'] == product_is_published+ assert data['product']['chargeTaxes'] == product_charge_taxes+ assert data['product']['taxRate'] == product_tax_rate.lower()assert data['product']['productType']['name'] == product_type.nameassert data['product']['category']['name'] == category.namevalues = (@@ -946,7 +945,7 @@ def test_reorder_images('product_id': product_id, 'images_ids': [image_1_id, image_0_id]}response = staff_api_client.post_graphql(query, variables, permissions=[permission_manage_products])- content = get_graphql_content(response)+ get_graphql_content(response)# Check if order has been changedproduct.refresh_from_db()@@ -957,212 +956,6 @@ def test_reorder_images(assert image_1.id == reordered_image_0.id-def test_collections_query(- user_api_client, staff_api_client, collection, draft_collection,- permission_manage_products):- query = """- query Collections {- collections(first: 2) {- edges {- node {- isPublished- name- slug- products {- totalCount- }- }- }- }- }- """-- # query public collections only as regular user- response = user_api_client.post_graphql(query)- content = get_graphql_content(response)- edges = content['data']['collections']['edges']- assert len(edges) == 1- collection_data = edges[0]['node']- assert collection_data['isPublished']- assert collection_data['name'] == collection.name- assert collection_data['slug'] == collection.slug- assert collection_data['products']['totalCount'] == collection.products.count()-- # query all collections only as a staff user with proper permissions- staff_api_client.user.user_permissions.add(permission_manage_products)- response = staff_api_client.post_graphql(query)- content = get_graphql_content(response)- edges = content['data']['collections']['edges']- assert len(edges) == 2---def test_create_collection(- staff_api_client, product_list, permission_manage_products):- query = """- mutation createCollection(- $name: String!, $slug: String!, $products: [ID], $backgroundImage: Upload!, $isPublished: Boolean!) {- collectionCreate(- input: {name: $name, slug: $slug, products: $products, backgroundImage: $backgroundImage, isPublished: $isPublished}) {- collection {- name- slug- products {- totalCount- }- }- }- }- """- product_ids = [- to_global_id('Product', product.pk) for product in product_list]- image_file, image_name = create_image()- name = 'test-name'- slug = 'test-slug'- variables = {- 'name': name, 'slug': slug, 'products': product_ids,- 'backgroundImage': image_name, 'isPublished': True}- body = get_multipart_request_body(query, variables, image_file, image_name)- response = staff_api_client.post_multipart(- body, permissions=[permission_manage_products])- content = get_graphql_content(response)- data = content['data']['collectionCreate']['collection']- assert data['name'] == name- assert data['slug'] == slug- assert data['products']['totalCount'] == len(product_ids)- collection = Collection.objects.get(slug=slug)- assert collection.background_image.file---def test_update_collection(- staff_api_client, collection, permission_manage_products):- query = """- mutation updateCollection(- $name: String!, $slug: String!, $id: ID!, $isPublished: Boolean!) {- collectionUpdate(- id: $id, input: {name: $name, slug: $slug, isPublished: $isPublished}) {- collection {- name- slug- }- }- }- """- collection_id = to_global_id('Collection', collection.id)- name = 'new-name'- slug = 'new-slug'- variables = {- 'name': name, 'slug': slug, 'id': collection_id, 'isPublished': True}- response = staff_api_client.post_graphql(- query, variables, permissions=[permission_manage_products])- content = get_graphql_content(response)- data = content['data']['collectionUpdate']['collection']- assert data['name'] == name- assert data['slug'] == slug---def test_delete_collection(- staff_api_client, collection, permission_manage_products):- query = """- mutation deleteCollection($id: ID!) {- collectionDelete(id: $id) {- collection {- name- }- }- }- """- collection_id = to_global_id('Collection', collection.id)- variables = {'id': collection_id}- response = staff_api_client.post_graphql(- query, variables, permissions=[permission_manage_products])- content = get_graphql_content(response)- data = content['data']['collectionDelete']['collection']- assert data['name'] == collection.name- with pytest.raises(collection._meta.model.DoesNotExist):- collection.refresh_from_db()---def test_auto_create_slug_on_collection(- staff_api_client, product_list, permission_manage_products):- query = """- mutation createCollection(- $name: String!, $isPublished: Boolean!) {- collectionCreate(- input: {name: $name, isPublished: $isPublished}) {- collection {- name- slug- }- }- }- """- name = 'test name123'- variables = {'name': name, 'isPublished': True}- response = staff_api_client.post_graphql(- query, variables, permissions=[permission_manage_products])- content = get_graphql_content(response)- data = content['data']['collectionCreate']['collection']- assert data['name'] == name- assert data['slug'] == slugify(name)---def test_add_products_to_collection(- staff_api_client, collection, product_list,- permission_manage_products):- query = """- mutation collectionAddProducts(- $id: ID!, $products: [ID]!) {- collectionAddProducts(collectionId: $id, products: $products) {- collection {- products {- totalCount- }- }- }- }- """- collection_id = to_global_id('Collection', collection.id)- product_ids = [- to_global_id('Product', product.pk) for product in product_list]- no_products_before = collection.products.count()- variables = {'id': collection_id, 'products': product_ids}- response = staff_api_client.post_graphql(- query, variables, permissions=[permission_manage_products])- content = get_graphql_content(response)- data = content['data']['collectionAddProducts']['collection']- assert data[- 'products']['totalCount'] == no_products_before + len(product_ids)---def test_remove_products_from_collection(- staff_api_client, collection, product_list,- permission_manage_products):- query = """- mutation collectionRemoveProducts(- $id: ID!, $products: [ID]!) {- collectionRemoveProducts(collectionId: $id, products: $products) {- collection {- products {- totalCount- }- }- }- }- """- collection.products.add(*product_list)- collection_id = to_global_id('Collection', collection.id)- product_ids = [- to_global_id('Product', product.pk) for product in product_list]- no_products_before = collection.products.count()- variables = {'id': collection_id, 'products': product_ids}- response = staff_api_client.post_graphql(- query, variables, permissions=[permission_manage_products])- content = get_graphql_content(response)- data = content['data']['collectionRemoveProducts']['collection']- assert data[- 'products']['totalCount'] == no_products_before - len(product_ids)--ASSIGN_VARIANT_QUERY = """mutation assignVariantImageMutation($variantId: ID!, $imageId: ID!) {variantImageAssign(variantId: $variantId, imageId: $imageId) {@@ -1190,7 +983,7 @@ def test_assign_variant_image('imageId': to_global_id('ProductImage', image.pk)}response = staff_api_client.post_graphql(query, variables, permissions=[permission_manage_products])- content = get_graphql_content(response)+ get_graphql_content(response)variant.refresh_from_db()assert variant.images.first() == image@@ -1363,94 +1156,6 @@ def test_product_variants_no_ids_list(user_api_client, variant):assert len(data['edges']) == ProductVariant.objects.count()-def test_category_image_query(user_api_client, non_default_category):- category = non_default_category- image_file, image_name = create_image()- category.background_image = image_file- category.save()- category_id = graphene.Node.to_global_id('Category', category.pk)- query = """- query fetchCategory($id: ID!){- category(id: $id) {- backgroundImage {- url(size: 120)- }- }- }- """- variables = {'id': category_id}- response = user_api_client.post_graphql(query, variables)- content = get_graphql_content(response)- data = content['data']['category']- thumbnail_url = category.background_image.thumbnail['120x120'].url- assert thumbnail_url in data['backgroundImage']['url']---def test_category_image_query_without_associated_file(- user_api_client, non_default_category):- category = non_default_category- category_id = graphene.Node.to_global_id('Category', category.pk)- query = """- query fetchCategory($id: ID!){- category(id: $id) {- name- backgroundImage {- url- }- }- }- """- variables = {'id': category_id}- response = user_api_client.post_graphql(query, variables)- content = get_graphql_content(response)- data = content['data']['category']- assert data['name'] == category.name- assert data['backgroundImage'] is None---def test_collection_image_query(user_api_client, collection):- image_file, image_name = create_image()- collection.background_image = image_file- collection.save()- collection_id = graphene.Node.to_global_id('Collection', collection.pk)- query = """- query fetchCollection($id: ID!){- collection(id: $id) {- backgroundImage {- url(size: 120)- }- }- }- """- variables = {'id': collection_id}- response = user_api_client.post_graphql(query, variables)- content = get_graphql_content(response)- data = content['data']['collection']- thumbnail_url = collection.background_image.thumbnail['120x120'].url- assert thumbnail_url in data['backgroundImage']['url']---def test_collection_image_query_without_associated_file(- user_api_client, collection):- collection_id = graphene.Node.to_global_id('Collection', collection.pk)- query = """- query fetchCollection($id: ID!){- collection(id: $id) {- name- backgroundImage {- url- }- }- }- """- variables = {'id': collection_id}- response = user_api_client.post_graphql(query, variables)- content = get_graphql_content(response)- data = content['data']['collection']- assert data['name'] == collection.name- assert data['backgroundImage'] is None--@pytest.mark.parametrize('product_price, variant_override, api_variant_price', [(100, None, 100),(100, 200, 200),diff --git a/tests/dashboard/test_category.py b/tests/dashboard/test_category.pyindex 2f65fed996..4bc3f076af 100644--- a/tests/dashboard/test_category.py+++ b/tests/dashboard/test_category.py@@ -1,7 +1,8 @@-from unittest.mock import patch+from unittest.mock import patch, Mockfrom django.urls import reversefrom saleor.product.models import Category+from tests.utils import create_imagedef test_category_list(admin_client, category):@@ -10,13 +11,39 @@ def test_category_list(admin_client, category):assert response.status_code == 200-def test_category_add(admin_client):+def test_category_add(monkeypatch, admin_client):+ mock_create_thumbnails = Mock(return_value=None)+ monkeypatch.setattr(+ ('saleor.dashboard.category.forms.'+ 'create_category_background_image_thumbnails.delay'),+ mock_create_thumbnails)+assert Category.objects.count() == 0url = reverse('dashboard:category-add')data = {'name': 'Cars', 'description': 'Fastest cars'}response = admin_client.post(url, data, follow=True)assert response.status_code == 200assert Category.objects.count() == 1+ assert mock_create_thumbnails.call_count == 0+++def test_category_add_with_background_image(monkeypatch, admin_client):+ mock_create_thumbnails = Mock(return_value=None)+ monkeypatch.setattr(+ ('saleor.dashboard.category.forms.'+ 'create_category_background_image_thumbnails.delay'),+ mock_create_thumbnails)++ url = reverse('dashboard:category-add')+ image, image_name = create_image()+ data = {+ 'name': 'Cars',+ 'description': 'Super fast!',+ 'background_image': image}+ response = admin_client.post(url, data, follow=True)+ assert response.status_code == 200++ mock_create_thumbnails.assert_called_once_with(Category.objects.last().pk)def test_category_add_not_valid(admin_client):@@ -42,7 +69,13 @@ def test_category_add_subcategory(admin_client, category):assert subcategories[0].name == 'Cars'-def test_category_edit(admin_client, category):+def test_category_edit(monkeypatch, admin_client, category):+ mock_create_thumbnails = Mock(return_value=None)+ monkeypatch.setattr(+ ('saleor.dashboard.category.forms.'+ 'create_category_background_image_thumbnails.delay'),+ mock_create_thumbnails)+assert Category.objects.count() == 1url = reverse('dashboard:category-edit',kwargs={'root_pk': category.pk})@@ -51,6 +84,29 @@ def test_category_edit(admin_client, category):assert response.status_code == 200assert Category.objects.count() == 1assert Category.objects.all()[0].name == 'Cars'+ assert mock_create_thumbnails.call_count == 0+++def test_category_edit_with_background_image(+ monkeypatch, admin_client, category):+ mock_create_thumbnails = Mock(return_value=None)+ monkeypatch.setattr(+ ('saleor.dashboard.category.forms.'+ 'create_category_background_image_thumbnails.delay'),+ mock_create_thumbnails)++ url = reverse('dashboard:category-edit', kwargs={'root_pk': category.pk})+ image, image_name = create_image()+ data = {+ 'name': 'Cars',+ 'description': 'Super fast!',+ 'background_image': image}+ response = admin_client.post(url, data, follow=True)+ assert response.status_code == 200++ category.refresh_from_db()+ assert category.background_image+ mock_create_thumbnails.assert_called_once_with(category.pk)def test_category_details(admin_client, category):diff --git a/tests/dashboard/test_collection.py b/tests/dashboard/test_collection.pyindex 732ff653d6..4c8da3c481 100644--- a/tests/dashboard/test_collection.py+++ b/tests/dashboard/test_collection.py@@ -2,10 +2,12 @@ import jsonfrom unittest import mockfrom django.urls import reverse+from unittest.mock import Mock+from saleor.dashboard.collection.forms import CollectionFormfrom saleor.product.models import Collection-from ..utils import get_redirect_location+from ..utils import get_redirect_location, create_imagedef test_list_view(admin_client, collection):@@ -58,7 +60,13 @@ def test_collection_form_with_products(product):assert collection.products.count() == 1-def test_collection_create_view(admin_client):+def test_collection_create_view(monkeypatch, admin_client):+ mock_create_thumbnails = Mock(return_value=None)+ monkeypatch.setattr(+ ('saleor.dashboard.collection.forms.'+ 'create_collection_background_image_thumbnails.delay'),+ mock_create_thumbnails)+response = admin_client.get(reverse('dashboard:collection-add'))assert response.status_code == 200@@ -68,9 +76,38 @@ def test_collection_create_view(admin_client):redirected_url = get_redirect_location(response)assert redirected_url == reverse('dashboard:collection-list')+ assert mock_create_thumbnails.call_count == 0++def test_collection_create_with_background_image(+ monkeypatch, admin_client):+ mock_create_thumbnails = Mock(return_value=None)+ monkeypatch.setattr(+ ('saleor.dashboard.collection.forms.'+ 'create_collection_background_image_thumbnails.delay'),+ mock_create_thumbnails)++ image, image_name = create_image()++ data = {+ 'name': 'Name',+ 'background_image': image}+ url = reverse('dashboard:collection-add')++ response = admin_client.post(url, data)+ assert response.status_code == 302+ mock_create_thumbnails.assert_called_once_with(+ Collection.objects.last().pk)+++def test_collection_update_view(+ monkeypatch, admin_client, collection, product):+ mock_create_thumbnails = Mock(return_value=None)+ monkeypatch.setattr(+ ('saleor.dashboard.collection.forms.'+ 'create_collection_background_image_thumbnails.delay'),+ mock_create_thumbnails)-def test_collection_update_view(admin_client, collection, product):url = reverse('dashboard:collection-update', kwargs={'pk': collection.id})response = admin_client.get(url)assert response.status_code == 200@@ -84,6 +121,32 @@ def test_collection_update_view(admin_client, collection, product):assert not current_name == collection.nameassert list(collection.products.all()) == [product]+ assert mock_create_thumbnails.call_count == 0+++def test_collection_update_background_image(+ monkeypatch, admin_client, collection, product):+ mock_create_category_thumbnails = Mock(return_value=None)+ monkeypatch.setattr(+ ('saleor.dashboard.collection.forms.'+ 'create_collection_background_image_thumbnails.delay'),+ mock_create_category_thumbnails)++ url = reverse('dashboard:collection-update', kwargs={'pk': collection.id})+ image, image_name = create_image()++ data = {+ 'name': 'New name',+ 'background_image': image}+ response = admin_client.post(url, data)+ assert response.status_code == 302++ collection.refresh_from_db()+ assert collection.background_image+ assert image_name in collection.background_image.name++ mock_create_category_thumbnails.assert_called_once_with(collection.pk)+@mock.patch('saleor.dashboard.collection.views.get_menus_that_needs_update')@mock.patch('saleor.dashboard.collection.views.update_menus')