Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Add mutation to create product image
Marcin Gębalae53ef3038928
diff --git a/saleor/graphql/api.py b/saleor/graphql/api.pyindex 8e1122496f..b8d9dc18f1 100644--- a/saleor/graphql/api.py+++ b/saleor/graphql/api.py@@ -17,7 +17,8 @@ from .product.mutations import (ProductCreateMutation, ProductDeleteMutation, ProductUpdateMutation,ProductTypeCreateMutation, ProductTypeDeleteMutation,ProductTypeUpdateMutation, ProductVariantCreateMutation,- ProductVariantDeleteMutation, ProductVariantUpdateMutation)+ ProductVariantDeleteMutation, ProductVariantUpdateMutation,+ ProductImageCreateMutation)from .product.resolvers import (resolve_attributes, resolve_categories, resolve_products,resolve_product_types)@@ -117,6 +118,8 @@ class Mutations(graphene.ObjectType):product_delete = ProductDeleteMutation.Field()product_update = ProductUpdateMutation.Field()+ product_image_create = ProductImageCreateMutation.Field()+product_type_create = ProductTypeCreateMutation.Field()product_type_update = ProductTypeUpdateMutation.Field()product_type_delete = ProductTypeDeleteMutation.Field()diff --git a/saleor/graphql/core/mutations.py b/saleor/graphql/core/mutations.pyindex a20f6936eb..215383b96f 100644--- a/saleor/graphql/core/mutations.py+++ b/saleor/graphql/core/mutations.py@@ -206,6 +206,7 @@ class StaffMemberRequiredMixin(graphene.Mutation):mutate = permission_required(cls.permissions)(super().mutate)return mutate(root, info, *args, **kwargs)+class CreateToken(ObtainJSONWebToken):"""Mutation that authenticates a user and returns token and user data.diff --git a/saleor/graphql/product/mutations.py b/saleor/graphql/product/mutations.pyindex 8617a955a6..4e2a231937 100644--- a/saleor/graphql/product/mutations.py+++ b/saleor/graphql/product/mutations.py@@ -1,5 +1,6 @@import graphenefrom graphene.types import InputObjectType+from graphql_jwt.decorators import permission_requiredfrom ...dashboard.category.forms import CategoryFormfrom ...dashboard.product.forms import ProductTypeForm@@ -9,7 +10,8 @@ from ..core.mutations import (StaffMemberRequiredMixin)from ..utils import get_attributes_dict_from_list, get_nodefrom .forms import ProductForm, ProductVariantForm-from .types import Category, Product, ProductAttribute, ProductType+from .types import (+ Category, Product, ProductAttribute, ProductImage, ProductType)class CategoryCreateMutation(StaffMemberRequiredMixin, ModelFormMutation):@@ -280,3 +282,27 @@ class ProductTypeDeleteMutation(StaffMemberRequiredMixin, ModelDeleteMutation):class Meta:description = 'Deletes a product type.'model = models.ProductType+++class ProductImageCreateMutation(graphene.Mutation):+ class Arguments:+ product_id = graphene.Argument(+ graphene.ID, description='ID of an product.')++ class Meta:+ description = 'Creates a product image.'++ product_image = graphene.Field(+ ProductImage, description='A newly created product image.')++ @permission_required('product.edit_product')+ def mutate(self, info, product_id, **kwargs):+ files = info.context.FILES+ if not 'image' in files:+ raise ValueError('Expected \'image\' key with a file.')++ image_file = files['image']+ product = get_node(info, product_id, only_type=Product)+ product_image = models.ProductImage(product=product)+ product_image.image.save(image_file.name, image_file)+ return ProductImageCreateMutation(product_image=product_image)diff --git a/tests/api/test_product.py b/tests/api/test_product.pyindex 8c0facfb26..8837dc642a 100644--- a/tests/api/test_product.py+++ b/tests/api/test_product.py@@ -6,7 +6,7 @@ import pytestfrom django.shortcuts import reversefrom django.utils.text import slugifyfrom prices import Money-from tests.utils import get_graphql_content+from tests.utils import create_image, get_graphql_contentfrom saleor.product.models import (Category, Product, ProductAttribute, ProductType)@@ -802,3 +802,29 @@ def test_product_type_delete_mutation(admin_api_client, product_type):assert data['productType']['name'] == product_type.namewith pytest.raises(product_type._meta.model.DoesNotExist):product_type.refresh_from_db()+++def test_product_image_create_mutation(admin_api_client, product):+ query = """+ mutation createProductImage($productId: ID!) {+ productImageCreate(productId: $productId) {+ productImage {+ id+ image+ url+ order+ }+ }+ }+ """+ variables = json.dumps({+ 'productId': graphene.Node.to_global_id('Product', product.id)})+ image, image_name = create_image()+ response = admin_api_client.post(+ reverse('api'),+ {'query': query, 'variables': variables, 'image': image})+ content = get_graphql_content(response)+ data = content['data']['productImageCreate']+ file_name = data['productImage']['image']+ product.refresh_from_db()+ assert product.images.first().image.name == file_namediff --git a/tests/dashboard/test_product.py b/tests/dashboard/test_product.pyindex 4fae769abd..4effb9d57f 100644--- a/tests/dashboard/test_product.py+++ b/tests/dashboard/test_product.py@@ -1,9 +1,8 @@import jsonfrom io import BytesIO-from unittest.mock import MagicMock, Mock+from unittest.mock import MagicMock, Mock, patchfrom django.conf import settings-from django.core.files.uploadedfile import SimpleUploadedFilefrom django.forms import HiddenInputfrom django.forms.models import model_to_dictfrom django.urls import reverse@@ -17,16 +16,7 @@ from saleor.product.forms import VariantChoiceFieldfrom saleor.product.models import (AttributeChoiceValue, Collection, Product, ProductAttribute, ProductImage,ProductType, ProductVariant)---def create_image():- img_data = BytesIO()- image = Image.new('RGB', size=(1, 1), color=(255, 0, 0, 0))- image.save(img_data, format='JPEG')- image_name = 'product2'- image = SimpleUploadedFile(- image_name + '.jpg', img_data.getvalue(), 'image/png')- return image, image_name+from ..utils import create_imagedef test_view_product_list_with_filters(admin_client, product_list):@@ -262,6 +252,19 @@ def test_view_product_bulk_update_unpublish(admin_client, product_list):response = admin_client.post(url, data)++def test_product_variant_form(product):+ variant = product.variants.first()+ variant.name = ''+ variant.save()+ example_size = 'Small Size'+ data = {'attribute-size': example_size, 'sku': '1111', 'quantity': 2}+ form = ProductVariantForm(data, instance=variant)+ assert form.is_valid()+ form.save()+ variant.refresh_from_db()+ assert variant.name == example_size+assert response.status_code == 302assert get_redirect_location(response) == reverse('dashboard:product-list')diff --git a/tests/utils.py b/tests/utils.pyindex a3aec15121..05852b0b70 100644--- a/tests/utils.py+++ b/tests/utils.py@@ -1,8 +1,11 @@import json+from io import BytesIOfrom urllib.parse import urlparse+from django.core.files.uploadedfile import SimpleUploadedFilefrom django.db.models import Qfrom django.utils.encoding import smart_text+from PIL import Imagedef get_url_path(url):@@ -39,3 +42,13 @@ def compare_taxes(taxes_1, taxes_2):value_1 = tax['value']value_2 = taxes_2.get(rate_name)['value']assert value_1 == value_2+++def create_image():+ img_data = BytesIO()+ image = Image.new('RGB', size=(1, 1), color=(255, 0, 0, 0))+ image.save(img_data, format='JPEG')+ image_name = 'product2'+ image = SimpleUploadedFile(+ image_name + '.jpg', img_data.getvalue(), 'image/png')+ return image, image_name