Saleor Core: the high performance, composable, headless commerce API.
Python cartcheckoutcommercecomposablee-commerceecommercegraphqlheadlessheadless-commercemultichannelomsorder-managementpaymentspimpythonshopshopping-cartstore
Export get_random_avatar to account utils
Paweł Zarębski16e5572e9069
diff --git a/saleor/account/utils.py b/saleor/account/utils.pyindex 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_namereturn 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.pyindex 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__.pyindex ef2c67a1ab..073f9f2ae7 100644--- a/saleor/core/utils/__init__.py+++ b/saleor/core/utils/__init__.py@@ -10,7 +10,6 @@ from django import formsfrom django.conf import settingsfrom django.contrib.sites.models import Sitefrom django.core import serializers-from django.core.files import Filefrom django.core.paginator import InvalidPage, Paginatorfrom django.http import Http404from django.utils.encoding import iri_to_uri, smart_text@@ -24,6 +23,7 @@ from prices import MoneyRangefrom versatileimagefield.image_warmer import VersatileImageFieldWarmerfrom ...account.models import User+from ...account.utils import get_random_avatarfrom ...core.i18n import COUNTRY_CODE_CHOICESgeoreader = 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' % credentialselse:@@ -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.pyindex 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 patchfrom django.conf import settingsfrom django.contrib.sites.models import Site+from django.core.files import Filefrom django_countries.fields import Countryfrom faker import Factoryfrom 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, ShippingZonefrom ...shipping.utils import get_taxed_shipping_price-from ..utils import get_imagefake = 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.pyindex f946ae9df2..af6148cc56 100644--- a/saleor/graphql/account/mutations.py+++ b/saleor/graphql/account/mutations.py@@ -1,12 +1,9 @@-import os-import randomfrom textwrap import dedentimport graphenefrom django.conf import settingsfrom django.contrib.auth.tokens import default_token_generatorfrom django.core.exceptions import ObjectDoesNotExist-from django.core.files import Filefrom django.utils.encoding import force_bytesfrom django.utils.http import urlsafe_base64_encodefrom graphql_jwt.decorators import (@@ -15,6 +12,7 @@ from graphql_jwt.exceptions import PermissionDeniedfrom ...account import emails, models, utilsfrom ...account.thumbnails import create_user_avatar_thumbnails+from ...account.utils import get_random_avatarfrom ...checkout import AddressTypefrom ...core.permissions import MODELS_PERMISSIONS, get_permissionsfrom ...dashboard.emails import (@@ -257,18 +255,11 @@ class StaffCreate(ModelMutation):cleaned_input['user_permissions'] = permission_objsreturn 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)-@classmethoddef 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.pyindex 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):@staticmethoddef 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.pyindex 51e51c05dc..b7ff2abdea 100644--- a/tests/test_account.py+++ b/tests/test_account.py@@ -1,4 +1,5 @@import os+import reimport uuidfrom unittest.mock import patchfrom urllib.parse import urlencode@@ -8,6 +9,7 @@ import pytestfrom captcha import constants as recaptcha_constantsfrom captcha.client import RecaptchaResponsefrom django.core.exceptions import ValidationError+from django.core.files import Filefrom django.forms import Formfrom django.http import QueryDictfrom django.template import Context, Template@@ -18,7 +20,8 @@ from saleor.account import forms, i18nfrom saleor.account.forms import FormWithReCaptcha, NameFormfrom saleor.account.models import Userfrom 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.pyindex 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 creationassert User.objects.all().count() == 0- create_superuser(credentials, '')+ create_superuser(credentials)assert User.objects.all().count() == 1admin = 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 inresponse = client.post(reverse('account:login'),