Skip to content

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

Implement upload according to spec; adjust GraphQL tests

Marcin Gębalaf01e85145462
diff --git a/requirements.in b/requirements.in
index 3993a1968b..2103dd3b91 100644
--- a/requirements.in
+++ b/requirements.in
@@ -34,6 +34,7 @@ freezegun>=0.3.9
google-measurement-protocol>=1.0.0
google-i18n-address>=2.3.0
graphene-django>=2.0.dev
+graphene-file-upload==0.1.1
jsonfield>=2.0.2
Markdown>=2.4
maxminddb
diff --git a/requirements.txt b/requirements.txt
index fe38d08924..8fbb559427 100644
--- a/requirements.txt
+++ b/requirements.txt
@@ -59,6 +59,7 @@ freezegun==0.3.10
google-i18n-address==2.3.0
google-measurement-protocol==1.0.0
graphene-django==2.0.0
+graphene-file-upload==0.1.1
graphene==2.0.1 # via django-graphql-jwt, graphene-django
graphql-core==2.0 # via graphene, graphql-relay
graphql-relay==0.4.5 # via graphene
diff --git a/saleor/graphql/product/mutations.py b/saleor/graphql/product/mutations.py
index 28bb80306d..92e66b0b3c 100644
--- a/saleor/graphql/product/mutations.py
+++ b/saleor/graphql/product/mutations.py
@@ -1,5 +1,6 @@
import graphene
from graphene.types import InputObjectType
+from graphene_file_upload import Upload
from graphql_jwt.decorators import permission_required
from ...dashboard.category.forms import CategoryForm
@@ -284,16 +285,11 @@ class ProductTypeDeleteMutation(StaffMemberRequiredMixin, ModelDeleteMutation):
model = models.ProductType
-class Upload(graphene.Scalar):
- def serialize(self):
- pass
-
-
class ProductImageCreateMutation(BaseMutation):
class Arguments:
+ file = Upload(required=True)
product_id = graphene.Argument(
graphene.ID, description='ID of an product.')
- file = Upload()
class Meta:
description = 'Creates a product image.'
@@ -302,13 +298,8 @@ class ProductImageCreateMutation(BaseMutation):
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:
- return ProductImageCreateMutation(
- errors=[Error(message='No file provided.')])
-
- image_file = files['image']
+ def mutate(self, info, product_id, file, **kwargs):
+ image_file = info.context.FILES.get(file)
product = get_node(info, product_id, only_type=Product)
product_image = models.ProductImage(product=product)
product_image.image.save(image_file.name, image_file)
diff --git a/saleor/graphql/product/types.py b/saleor/graphql/product/types.py
index 1b2305adc6..9efcd41601 100644
--- a/saleor/graphql/product/types.py
+++ b/saleor/graphql/product/types.py
@@ -170,7 +170,7 @@ class Product(CountableDjangoObjectType):
def resolve_product_type(self, info):
return self.product_type
- @permission_required(('product.view_product'))
+ @permission_required('product.view_product')
def resolve_purchase_cost(self, info):
purchase_cost, _ = get_product_costs_data(self)
return purchase_cost
diff --git a/saleor/urls.py b/saleor/urls.py
index 02c0d5e58a..563a4db971 100644
--- a/saleor/urls.py
+++ b/saleor/urls.py
@@ -7,6 +7,7 @@ from django.contrib.staticfiles.views import serve
from django.views.decorators.csrf import csrf_exempt
from django.views.i18n import JavaScriptCatalog, set_language
from graphene_django.views import GraphQLView
+from graphene_file_upload import ModifiedGraphQLView
from .account.urls import urlpatterns as account_urls
from .checkout.urls import (
@@ -26,7 +27,7 @@ handler404 = 'saleor.core.views.handle_404'
non_translatable_urlpatterns = [
url(r'^dashboard/',
include((dashboard_urls, 'dashboard'), namespace='dashboard')),
- url(r'^graphql/', csrf_exempt(GraphQLView.as_view(
+ url(r'^graphql/', csrf_exempt(ModifiedGraphQLView.as_view(
schema=schema, graphiql=settings.DEBUG)), name='api'),
url(r'^sitemap\.xml$', sitemap, {'sitemaps': sitemaps},
name='django.contrib.sitemaps.views.sitemap'),
diff --git a/tests/api/test_account.py b/tests/api/test_account.py
index dd0ad7ca2b..8b0ea89017 100644
--- a/tests/api/test_account.py
+++ b/tests/api/test_account.py
@@ -1,3 +1,4 @@
+import json
import graphene
from django.shortcuts import reverse
from tests.utils import get_graphql_content
@@ -16,7 +17,9 @@ def test_create_token_mutation(admin_client, staff_user):
}
'''
success_query = query % {'email': staff_user.email, 'password': 'password'}
- response = admin_client.post(reverse('api'), {'query': success_query})
+ response = admin_client.post(
+ reverse('api'), json.dumps({'query': success_query}),
+ content_type='application/json')
content = get_graphql_content(response)
assert 'errors' not in content
token_data = content['data']['tokenCreate']
@@ -24,7 +27,9 @@ def test_create_token_mutation(admin_client, staff_user):
assert not token_data['errors']
error_query = query % {'email': staff_user.email, 'password': 'wat'}
- response = admin_client.post(reverse('api'), {'query': error_query})
+ response = admin_client.post(
+ reverse('api'), json.dumps({'query': error_query}),
+ content_type='application/json')
content = get_graphql_content(response)
assert 'errors' not in content
token_data = content['data']['tokenCreate']
@@ -59,7 +64,9 @@ def test_token_create_user_data(
user_id = graphene.Node.to_global_id('User', staff_user.id)
query = query % {'email': staff_user.email, 'password': 'password'}
- response = staff_client.post(reverse('api'), {'query': query})
+ response = staff_client.post(
+ reverse('api'), json.dumps({'query': query}),
+ content_type='application/json')
content = get_graphql_content(response)
assert 'errors' not in content
token_data = content['data']['tokenCreate']
diff --git a/tests/api/test_category.py b/tests/api/test_category.py
index 57f38fc764..ed8145c8af 100644
--- a/tests/api/test_category.py
+++ b/tests/api/test_category.py
@@ -8,7 +8,7 @@ from tests.utils import get_graphql_content
from saleor.product.models import Category
-def test_category_query(client, product):
+def test_category_query(user_api_client, product):
category = Category.objects.first()
query = '''
query {
@@ -32,7 +32,7 @@ def test_category_query(client, product):
}
}
''' % {'category_pk': graphene.Node.to_global_id('Category', category.pk)}
- response = client.post(reverse('api'), {'query': query})
+ response = user_api_client.post(reverse('api'), {'query': query})
content = get_graphql_content(response)
assert 'errors' not in content
category_data = content['data']['category']
diff --git a/tests/api/test_graphql.py b/tests/api/test_graphql.py
index ccfdff87fb..25a8b04502 100644
--- a/tests/api/test_graphql.py
+++ b/tests/api/test_graphql.py
@@ -39,7 +39,7 @@ def test_jwt_middleware(admin_client, admin_user):
assert request.user == admin_user
-def test_real_query(admin_client, product):
+def test_real_query(user_api_client, product):
product_attr = product.product_type.product_attributes.first()
category = product.category
attr_value = product_attr.values.first()
@@ -176,7 +176,7 @@ def test_real_query(admin_client, product):
__typename
}
'''
- response = admin_client.post(
+ response = user_api_client.post(
reverse('api'), {
'query': query,
'variables': json.dumps(
diff --git a/tests/api/test_page.py b/tests/api/test_page.py
index 54ce9b84c6..63523c06f1 100644
--- a/tests/api/test_page.py
+++ b/tests/api/test_page.py
@@ -8,7 +8,7 @@ from tests.utils import get_graphql_content
from saleor.page.models import Page
-def test_page_query(client, page):
+def test_page_query(user_api_client, page):
page.is_visible = True
query = """
query PageQuery($id: ID!) {
@@ -20,7 +20,7 @@ def test_page_query(client, page):
"""
variables = json.dumps({
'id': graphene.Node.to_global_id('Page', page.id)})
- response = client.post(
+ response = user_api_client.post(
reverse('api'), {'query': query, 'variables': variables})
content = get_graphql_content(response)
assert 'errors' not in content
@@ -102,7 +102,7 @@ def test_page_delete_mutation(admin_api_client, page):
page.refresh_from_db()
-def test_paginate_pages(client, page):
+def test_paginate_pages(user_api_client, page):
page.is_visible = True
data_02 = {
'slug': 'test02-url',
@@ -129,7 +129,7 @@ def test_paginate_pages(client, page):
}
}
"""
- response = client.post(
+ response = user_api_client.post(
reverse('api'), {'query': query})
content = get_graphql_content(response)
assert 'errors' not in content
diff --git a/tests/api/test_product.py b/tests/api/test_product.py
index 8837dc642a..65f8ba8e94 100644
--- a/tests/api/test_product.py
+++ b/tests/api/test_product.py
@@ -10,9 +10,10 @@ from tests.utils import create_image, get_graphql_content
from saleor.product.models import (
Category, Product, ProductAttribute, ProductType)
+from .utils import get_multipart_request_body
-def test_fetch_all_products(client, product):
+def test_fetch_all_products(user_api_client, product):
query = '''
query {
products {
@@ -25,7 +26,7 @@ def test_fetch_all_products(client, product):
}
}
'''
- response = client.post(reverse('api'), {'query': query})
+ response = user_api_client.post(reverse('api'), {'query': query})
content = get_graphql_content(response)
assert 'errors' not in content
num_products = Product.objects.count()
@@ -34,7 +35,7 @@ def test_fetch_all_products(client, product):
@pytest.mark.djangodb
-def test_fetch_unavailable_products(client, product):
+def test_fetch_unavailable_products(user_api_client, product):
Product.objects.update(is_published=False)
query = '''
query {
@@ -48,7 +49,7 @@ def test_fetch_unavailable_products(client, product):
}
}
'''
- response = client.post(reverse('api'), {'query': query})
+ response = user_api_client.post(reverse('api'), {'query': query})
content = get_graphql_content(response)
assert 'errors' not in content
assert content['data']['products']['totalCount'] == 0
@@ -172,7 +173,7 @@ def test_product_with_collections(admin_api_client, product, collection):
assert len(data['collections']['edges']) == 1
-def test_filter_product_by_category(client, product):
+def test_filter_product_by_category(user_api_client, product):
category = product.category
query = '''
query getProducts($categoryId: ID) {
@@ -185,7 +186,7 @@ def test_filter_product_by_category(client, product):
}
}
'''
- response = client.post(
+ response = user_api_client.post(
reverse('api'),
{
'query': query,
@@ -200,7 +201,7 @@ def test_filter_product_by_category(client, product):
assert product_data['name'] == product.name
-def test_fetch_product_by_id(client, product):
+def test_fetch_product_by_id(user_api_client, product):
query = '''
query ($productId: ID!) {
node(id: $productId) {
@@ -210,7 +211,7 @@ def test_fetch_product_by_id(client, product):
}
}
'''
- response = client.post(
+ response = user_api_client.post(
reverse('api'),
{
'query': query,
@@ -224,7 +225,7 @@ def test_fetch_product_by_id(client, product):
assert product_data['name'] == product.name
-def test_filter_product_by_attributes(client, product):
+def test_filter_product_by_attributes(user_api_client, product):
product_attr = product.product_type.product_attributes.first()
category = product.category
attr_value = product_attr.values.first()
@@ -244,14 +245,14 @@ def test_filter_product_by_attributes(client, product):
''' % {
'category_id': graphene.Node.to_global_id('Category', category.id),
'filter_by': filter_by}
- response = client.post(reverse('api'), {'query': query})
+ response = user_api_client.post(reverse('api'), {'query': query})
content = get_graphql_content(response)
assert 'errors' not in content
product_data = content['data']['category']['products']['edges'][0]['node']
assert product_data['name'] == product.name
-def test_sort_products(client, product):
+def test_sort_products(user_api_client, product):
# set price of the first product
product.price = Money('10.00', 'USD')
product.save()
@@ -276,7 +277,7 @@ def test_sort_products(client, product):
'''
asc_price_query = query % {'sort_by': 'price'}
- response = client.post(reverse('api'), {'query': asc_price_query})
+ response = user_api_client.post(reverse('api'), {'query': asc_price_query})
content = get_graphql_content(response)
assert 'errors' not in content
product_data = content['data']['products']['edges'][0]['node']
@@ -285,7 +286,7 @@ def test_sort_products(client, product):
assert price_0 < price_1
desc_price_query = query % {'sort_by': '-price'}
- response = client.post(reverse('api'), {'query': desc_price_query})
+ response = user_api_client.post(reverse('api'), {'query': desc_price_query})
content = get_graphql_content(response)
assert 'errors' not in content
product_data = content['data']['products']['edges'][0]['node']
@@ -294,7 +295,7 @@ def test_sort_products(client, product):
assert price_0 > price_1
-def test_attributes_query(client, product):
+def test_attributes_query(user_api_client, product):
attributes = ProductAttribute.objects.prefetch_related('values')
query = '''
query {
@@ -314,14 +315,14 @@ def test_attributes_query(client, product):
}
}
'''
- response = client.post(reverse('api'), {'query': query})
+ response = user_api_client.post(reverse('api'), {'query': query})
content = get_graphql_content(response)
assert 'errors' not in content
attributes_data = content['data']['attributes']['edges']
assert len(attributes_data) == attributes.count()
-def test_attributes_in_category_query(client, product):
+def test_attributes_in_category_query(user_api_client, product):
category = Category.objects.first()
query = '''
query {
@@ -341,7 +342,7 @@ def test_attributes_in_category_query(client, product):
}
}
''' % {'category_id': graphene.Node.to_global_id('Category', category.id)}
- response = client.post(reverse('api'), {'query': query})
+ response = user_api_client.post(reverse('api'), {'query': query})
content = get_graphql_content(response)
assert 'errors' not in content
attributes_data = content['data']['attributes']['edges']
@@ -586,7 +587,7 @@ def test_delete_product(admin_api_client, product):
product.refresh_from_db()
-def test_product_type(client, product_type):
+def test_product_type(user_api_client, product_type):
query = """
query {
productTypes {
@@ -600,7 +601,7 @@ def test_product_type(client, product_type):
}
}
"""
- response = client.post(reverse('api'), {'query': query})
+ response = user_api_client.post(reverse('api'), {'query': query})
content = get_graphql_content(response)
no_product_types = ProductType.objects.count()
assert 'errors' not in content
@@ -609,7 +610,7 @@ def test_product_type(client, product_type):
def test_product_type_query(
- client, admin_api_client, product_type, product):
+ user_api_client, admin_api_client, product_type, product):
query = """
query getProductType($id: ID!) {
productType(id: $id) {
@@ -631,7 +632,7 @@ def test_product_type_query(
variables = json.dumps({
'id': graphene.Node.to_global_id('ProductType', product_type.id)})
- response = client.post(
+ response = user_api_client.post(
reverse('api'), {'query': query, 'variables': variables})
content = get_graphql_content(response)
assert 'errors' not in content
@@ -806,8 +807,8 @@ def test_product_type_delete_mutation(admin_api_client, product_type):
def test_product_image_create_mutation(admin_api_client, product):
query = """
- mutation createProductImage($productId: ID!) {
- productImageCreate(productId: $productId) {
+ mutation createProductImage($file: Upload!, $productId: ID!) {
+ productImageCreate(file: $file, productId: $productId) {
productImage {
id
image
@@ -817,12 +818,12 @@ def test_product_image_create_mutation(admin_api_client, product):
}
}
"""
- 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})
+ image_file, image_name = create_image()
+ variables = {
+ 'productId': graphene.Node.to_global_id('Product', product.id),
+ 'file': image_file.name}
+ body = get_multipart_request_body(query, variables, image_file, image_name)
+ response = admin_api_client.post_multipart(reverse('api'), body)
content = get_graphql_content(response)
data = content['data']['productImageCreate']
file_name = data['productImage']['image']
diff --git a/tests/api/utils.py b/tests/api/utils.py
new file mode 100644
index 0000000000..d21c2e7d03
--- /dev/null
+++ b/tests/api/utils.py
@@ -0,0 +1,12 @@
+import json
+
+
+def get_multipart_request_body(query, variables, file, file_name):
+ """Create request body for multipart GraphQL requests.
+
+ Multipart requests are different than standard GraphQL requests, because
+ of additional 'operations' and 'map' keys.
+ """
+ return {
+ 'operations': json.dumps({'query': query, 'variables': variables}),
+ 'map': json.dumps({file_name: ['variables.file']}), file_name: file}
diff --git a/tests/conftest.py b/tests/conftest.py
index 4e16a5f189..d4b49767f9 100644
--- a/tests/conftest.py
+++ b/tests/conftest.py
@@ -1,3 +1,4 @@
+import json
from io import BytesIO
from unittest.mock import MagicMock, Mock
@@ -7,7 +8,7 @@ from django.contrib.sites.models import Site
from django.core.files import File
from django.core.files.uploadedfile import SimpleUploadedFile
from django.forms import ModelForm
-from django.test.client import Client
+from django.test.client import Client, MULTIPART_CONTENT
from django.utils.encoding import smart_text
from django_prices_vatlayer.models import VAT
from django_prices_vatlayer.utils import get_tax_for_rate
@@ -35,6 +36,7 @@ from saleor.site.models import AuthorizationKey, SiteSettings
class ApiClient(Client):
+ """GraphQL API client."""
def __init__(self, *args, **kwargs):
user = kwargs.pop('user')
@@ -46,6 +48,27 @@ class ApiClient(Client):
environ.update({'HTTP_AUTHORIZATION': 'JWT %s' % self.token})
return environ
+ def post(self, path, data=None, **kwargs):
+ """Send a POST request.
+
+ This wrapper sets the `application/json` content type which is
+ more suitable for standard GraphQL requests and doesn't mismatch with
+ handling multipart requests in Graphene.
+ """
+ if data:
+ data = json.dumps(data)
+ kwargs['content_type'] = 'application/json'
+ return super().post(path, data, **kwargs)
+
+ def post_multipart(self, *args, **kwargs):
+ """Send a multipart POST request.
+
+ This is used to send multipart requests to GraphQL API when e.g.
+ uploading files.
+ """
+ kwargs['content_type'] = MULTIPART_CONTENT
+ return super().post(*args, **kwargs)
+
@pytest.fixture
def admin_api_client(admin_user):