Skip to content

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

Export get_random_avatar to account utils

Paweł Zarębski16e5572e9069
diff --git a/saleor/account/utils.py b/saleor/account/utils.py
index a7adf7aa5d..273afca405 100644
--- a/saleor/account/utils.py
+++ b/saleor/account/utils.py
@@ -1,3 +1,8 @@
+import os
+import random
+
+from django.core.files import File
+
from ..checkout import AddressType
@@ -52,3 +57,11 @@ def get_user_last_name(user):
if user.default_billing_address:
return user.default_billing_address.last_name
return None
+
+
+def get_random_avatar():
+ """Return random avatar picked from a pool of static avatars."""
+ avatars_dir = 'saleor/static/images/avatars/'
+ avatar_name = random.choice(os.listdir(avatars_dir))
+ avatar_path = os.path.join(avatars_dir, avatar_name)
+ return File(open(avatar_path, 'rb'), name=avatar_name)
diff --git a/saleor/core/management/commands/populatedb.py b/saleor/core/management/commands/populatedb.py
index 7916eb09a3..8839902d63 100644
--- a/saleor/core/management/commands/populatedb.py
+++ b/saleor/core/management/commands/populatedb.py
@@ -16,7 +16,6 @@ from ...utils.random_data import (
class Command(BaseCommand):
help = 'Populate database with test objects'
placeholders_dir = 'saleor/static/placeholders/'
- avatars_dir = 'saleor/static/images/avatars/'
def add_arguments(self, parser):
parser.add_argument(
@@ -99,7 +98,7 @@ class Command(BaseCommand):
if options['createsuperuser']:
credentials = {'email': '[email protected]', 'password': 'admin'}
- msg = create_superuser(credentials, self.avatars_dir)
+ msg = create_superuser(credentials)
self.stdout.write(msg)
add_address_to_admin(credentials['email'])
if not options['withoutsearch']:
diff --git a/saleor/core/utils/__init__.py b/saleor/core/utils/__init__.py
index ef2c67a1ab..073f9f2ae7 100644
--- a/saleor/core/utils/__init__.py
+++ b/saleor/core/utils/__init__.py
@@ -10,7 +10,6 @@ from django import forms
from django.conf import settings
from django.contrib.sites.models import Site
from django.core import serializers
-from django.core.files import File
from django.core.paginator import InvalidPage, Paginator
from django.http import Http404
from django.utils.encoding import iri_to_uri, smart_text
@@ -24,6 +23,7 @@ from prices import MoneyRange
from versatileimagefield.image_warmer import VersatileImageFieldWarmer
from ...account.models import User
+from ...account.utils import get_random_avatar
from ...core.i18n import COUNTRY_CODE_CHOICES
georeader = geolite2.reader()
@@ -136,20 +136,17 @@ def serialize_decimal(obj):
return JSONEncoder().default(obj)
-def create_superuser(credentials, avatars_dir):
+def create_superuser(credentials):
user, created = User.objects.get_or_create(
email=credentials['email'], defaults={
'is_active': True, 'is_staff': True, 'is_superuser': True})
if created:
- avatar = get_image(avatars_dir, 'avatar1.png')
- user.avatar = avatar
+ user.avatar = get_random_avatar()
user.set_password(credentials['password'])
user.save()
create_thumbnails(
- pk=user.pk,
- model=User,
- size_set='user_avatars',
- image_attr='avatar',
+ pk=user.pk, model=User,
+ size_set='user_avatars', image_attr='avatar',
)
msg = 'Superuser - %(email)s/%(password)s' % credentials
else:
@@ -182,8 +179,3 @@ def get_country_name_by_code(country_code):
(name for code, name in COUNTRY_CODE_CHOICES if code == country_code),
country_code)
return country_name
-
-
-def get_image(image_dir, image_name):
- img_path = os.path.join(image_dir, image_name)
- return File(open(img_path, 'rb'), name=image_name)
diff --git a/saleor/core/utils/random_data.py b/saleor/core/utils/random_data.py
index 6912e447e6..061a13f078 100644
--- a/saleor/core/utils/random_data.py
+++ b/saleor/core/utils/random_data.py
@@ -9,6 +9,7 @@ from unittest.mock import patch
from django.conf import settings
from django.contrib.sites.models import Site
+from django.core.files import File
from django_countries.fields import Country
from faker import Factory
from faker.providers import BaseProvider
@@ -39,7 +40,6 @@ from ...product.thumbnails import (
create_collection_background_image_thumbnails, create_product_thumbnails)
from ...shipping.models import ShippingMethod, ShippingMethodType, ShippingZone
from ...shipping.utils import get_taxed_shipping_price
-from ..utils import get_image
fake = Factory.create()
@@ -692,3 +692,8 @@ def get_product_list_images_dir(placeholder_dir):
product_list_images_dir = os.path.join(
placeholder_dir, PRODUCTS_LIST_DIR)
return product_list_images_dir
+
+
+def get_image(image_dir, image_name):
+ img_path = os.path.join(image_dir, image_name)
+ return File(open(img_path, 'rb'), name=image_name)
diff --git a/saleor/graphql/account/mutations.py b/saleor/graphql/account/mutations.py
index f946ae9df2..af6148cc56 100644
--- a/saleor/graphql/account/mutations.py
+++ b/saleor/graphql/account/mutations.py
@@ -1,12 +1,9 @@
-import os
-import random
from textwrap import dedent
import graphene
from django.conf import settings
from django.contrib.auth.tokens import default_token_generator
from django.core.exceptions import ObjectDoesNotExist
-from django.core.files import File
from django.utils.encoding import force_bytes
from django.utils.http import urlsafe_base64_encode
from graphql_jwt.decorators import (
@@ -15,6 +12,7 @@ from graphql_jwt.exceptions import PermissionDenied
from ...account import emails, models, utils
from ...account.thumbnails import create_user_avatar_thumbnails
+from ...account.utils import get_random_avatar
from ...checkout import AddressType
from ...core.permissions import MODELS_PERMISSIONS, get_permissions
from ...dashboard.emails import (
@@ -257,18 +255,11 @@ class StaffCreate(ModelMutation):
cleaned_input['user_permissions'] = permission_objs
return cleaned_input
- @classmethod
- def get_avatar(cls):
- avatars_dir = 'saleor/static/images/avatars/'
- avatar_name = random.choice(os.listdir(avatars_dir))
- avatar_path = os.path.join(avatars_dir, avatar_name)
- return File(open(avatar_path, 'rb'), name=avatar_name)
-
@classmethod
def save(cls, info, user, cleaned_input):
- user.avatar = cls.get_avatar()
+ user.avatar = get_random_avatar()
user.save()
- create_user_avatar_thumbnails(user_id=user.pk)
+ create_user_avatar_thumbnails.delay(user_id=user.pk)
if cleaned_input.get('send_password_email'):
send_set_password_staff_email.delay(user.pk)
diff --git a/saleor/graphql/core/types/common.py b/saleor/graphql/core/types/common.py
index 2fad5e7c28..4e02247bde 100644
--- a/saleor/graphql/core/types/common.py
+++ b/saleor/graphql/core/types/common.py
@@ -65,7 +65,6 @@ class Image(graphene.ObjectType):
@staticmethod
def get_adjusted(image, alt, size, rendition_key_set, info):
"""Return Image adjusted with given size."""
-
if size:
url = get_thumbnail(
image_file=image,
@@ -75,7 +74,5 @@ class Image(graphene.ObjectType):
)
else:
url = image.url
-
url = info.context.build_absolute_uri(url)
-
return Image(url, alt)
diff --git a/tests/test_account.py b/tests/test_account.py
index 51e51c05dc..b7ff2abdea 100644
--- a/tests/test_account.py
+++ b/tests/test_account.py
@@ -1,4 +1,5 @@
import os
+import re
import uuid
from unittest.mock import patch
from urllib.parse import urlencode
@@ -8,6 +9,7 @@ import pytest
from captcha import constants as recaptcha_constants
from captcha.client import RecaptchaResponse
from django.core.exceptions import ValidationError
+from django.core.files import File
from django.forms import Form
from django.http import QueryDict
from django.template import Context, Template
@@ -18,7 +20,8 @@ from saleor.account import forms, i18n
from saleor.account.forms import FormWithReCaptcha, NameForm
from saleor.account.models import User
from saleor.account.templatetags.i18n_address_tags import format_address
-from saleor.account.utils import get_user_first_name, get_user_last_name
+from saleor.account.utils import (
+ get_random_avatar, get_user_first_name, get_user_last_name)
from saleor.account.validators import validate_possible_number
@@ -282,6 +285,12 @@ def test_get_user_last_name(last_name, default_billing_address_last_name,
assert get_user_last_name(user) == result
+def test_get_random_avatar():
+ avatar = get_random_avatar()
+ assert isinstance(avatar, File)
+ assert re.match(r"avatar\d+.png", avatar.name)
+
+
def test_disabled_recaptcha():
"""
This test creates a new form that should not contain any recaptcha field.
diff --git a/tests/test_core.py b/tests/test_core.py
index b11f70f42b..2b3ddf4c45 100644
--- a/tests/test_core.py
+++ b/tests/test_core.py
@@ -64,20 +64,17 @@ def test_get_currency_for_country(country, expected_currency, monkeypatch):
assert currency == expected_currency
-def test_create_superuser(db, client, monkeypatch, image):
- monkeypatch.setattr(
- 'saleor.core.utils.get_image',
- Mock(return_value=image)
- )
+def test_create_superuser(db, client):
credentials = {'email': '[email protected]', 'password': 'admin'}
# Test admin creation
assert User.objects.all().count() == 0
- create_superuser(credentials, '')
+ create_superuser(credentials)
assert User.objects.all().count() == 1
admin = User.objects.all().first()
assert admin.is_superuser
+ assert admin.avatar
# Test duplicating
- create_superuser(credentials, '')
+ create_superuser(credentials)
assert User.objects.all().count() == 1
# Test logging in
response = client.post(reverse('account:login'),