Просмотр исходного кода

Extract fake user creation to util functions

rafalp 6 лет назад
Родитель
Сommit
b59e41a6a0

+ 1 - 1
misago/faker/englishcorpus.py

@@ -30,7 +30,7 @@ class EnglishCorpus:
     def shuffle(self):
         random.shuffle(self.phrases)
 
-    def random_choice(self):
+    def random_sentence(self):
         self._countdown_to_shuffle()
 
         choice = None

+ 1 - 1
misago/faker/management/commands/createfakethreads.py

@@ -72,7 +72,7 @@ class Command(BaseCommand):
                     is_hidden=thread_is_hidden,
                     is_closed=thread_is_closed,
                 )
-                thread.set_title(corpus_short.random_choice())
+                thread.set_title(corpus_short.random_sentence())
                 thread.save()
 
                 original, parsed = self.fake_post_content()

+ 13 - 32
misago/faker/management/commands/createfakeusers.py

@@ -1,17 +1,12 @@
 import random
 import time
 
-from django.contrib.auth import get_user_model
-from django.core.exceptions import ValidationError
 from django.core.management.base import BaseCommand
-from django.db import IntegrityError
 from faker import Factory
 
 from ....core.management.progressbar import show_progress
-from ....users.avatars import dynamic, gallery
 from ....users.models import Rank
-
-User = get_user_model()
+from ... import user
 
 
 class Command(BaseCommand):
@@ -26,8 +21,7 @@ class Command(BaseCommand):
         items_to_create = options["users"]
 
         fake = Factory.create()
-
-        ranks = [r for r in Rank.objects.all()]
+        ranks = list(Rank.objects.all())
 
         message = "Creating %s fake user accounts...\n"
         self.stdout.write(message % items_to_create)
@@ -37,31 +31,18 @@ class Command(BaseCommand):
         show_progress(self, created_count, items_to_create)
 
         while created_count < items_to_create:
-            try:
-                possible_usernames = [
-                    fake.first_name(),
-                    fake.last_name(),
-                    fake.name().replace(" ", ""),
-                    fake.user_name(),
-                ]
-
-                user = User.objects.create_user(
-                    random.choice(possible_usernames),
-                    fake.email(),
-                    "pass123",
-                    rank=random.choice(ranks),
-                )
-
-                if random.randint(0, 100) < 80:
-                    gallery.set_random_avatar(user)
-                else:
-                    dynamic.set_avatar(user)
-                user.save()
-            except (ValidationError, IntegrityError):
-                pass
+            rank = random.choice(ranks)
+            if random.randint(0, 100) > 80:
+                user.get_fake_inactive_user(fake, rank)
+            elif random.randint(0, 100) > 90:
+                user.get_fake_admin_activated_user(fake, rank)
+            elif random.randint(0, 100) > 90:
+                user.get_fake_banned_user(fake, rank)
             else:
-                created_count += 1
-                show_progress(self, created_count, items_to_create, start_time)
+                user.get_fake_user(fake, rank)
+
+            created_count += 1
+            show_progress(self, created_count, items_to_create, start_time)
 
         total_time = time.time() - start_time
         total_humanized = time.strftime("%H:%M:%S", time.gmtime(total_time))

+ 7 - 0
misago/faker/tests/conftest.py

@@ -0,0 +1,7 @@
+import pytest
+from faker import Factory
+
+
+@pytest.fixture
+def fake():
+    return Factory.create()

+ 13 - 0
misago/faker/tests/test_create_fake_users_command.py

@@ -0,0 +1,13 @@
+from io import StringIO
+
+from django.contrib.auth import get_user_model
+from django.core.management import call_command
+
+from ..management.commands import createfakeusers
+
+User = get_user_model()
+
+
+def test_management_command_creates_fake_users(db):
+    call_command(createfakeusers.Command(), stdout=StringIO())
+    assert User.objects.exists()

+ 29 - 32
misago/faker/tests/test_englishcorpus.py

@@ -3,35 +3,32 @@ from django.test import TestCase
 from ..englishcorpus import EnglishCorpus
 
 
-class EnglishCorpusTests(TestCase):
-    def test_corpus_has_length(self):
-        """corpus returns length"""
-        corpus = EnglishCorpus()
-        self.assertTrue(len(corpus))
-
-    def test_corpus_can_be_shuffled(self):
-        """corpus returns length"""
-        corpus = EnglishCorpus()
-        corpus.shuffle()
-
-    def test_shorter_than_100(self):
-        """corpus returns phrases shorter than 100"""
-        corpus = EnglishCorpus(max_length=100)
-        self.assertTrue(len(corpus))
-
-    def test_longer_than_150(self):
-        """corpus returns phrases longer than 150"""
-        corpus = EnglishCorpus(min_length=100)
-        self.assertTrue(len(corpus))
-
-    def test_random_choice(self):
-        """corpus random choice renturns non-repeatable choices"""
-        corpus = EnglishCorpus()
-
-        choices = [corpus.random_choice() for _ in range(2)]
-        self.assertEqual(len(choices), len(set(choices)))
-
-    def test_random_sentences(self):
-        """corpus random_sentences returns x random sentences"""
-        corpus = EnglishCorpus()
-        self.assertEqual(len(corpus.random_sentences(5)), 5)
+def test_corpus_has_length():
+    corpus = EnglishCorpus()
+    assert len(corpus) > 0
+
+
+def test_corpus_can_be_shuffled():
+    corpus = EnglishCorpus()
+    corpus.shuffle()
+
+
+def test_corpus_can_be_limited_to_phrases_shorter_than_specified():
+    corpus = EnglishCorpus(max_length=100)
+    assert len(corpus) > 0
+
+
+def test_corpus_can_be_limited_to_phrases_longer_than_specified():
+    corpus = EnglishCorpus(min_length=100)
+    assert len(corpus) > 0
+
+
+def test_corpus_produces_random_sequence():
+    corpus = EnglishCorpus()
+    choices = [corpus.random_sentence() for _ in range(2)]
+    assert len(choices) == len(set(choices))
+
+
+def test_corpus_produces_list_of_random_sentences():
+    corpus = EnglishCorpus()
+    assert len(corpus.random_sentences(5)) == 5

+ 44 - 0
misago/faker/tests/test_fake_user.py

@@ -0,0 +1,44 @@
+from ...users.bans import get_user_ban
+from ...users.models import Rank
+from ..user import (
+    PASSWORD,
+    get_fake_admin_activated_user,
+    get_fake_banned_user,
+    get_fake_inactive_user,
+    get_fake_user,
+)
+
+
+def test_fake_user_can_be_created(db, fake):
+    assert get_fake_user(fake)
+
+
+def test_fake_user_is_created_with_predictable_password(db, fake):
+    user = get_fake_user(fake)
+    assert user.check_password(PASSWORD)
+
+
+def test_fake_user_is_created_with_test_avatars(db, fake):
+    user = get_fake_user(fake)
+    assert user.avatars
+
+
+def test_fake_user_is_created_with_explicit_rank(db, fake):
+    rank = Rank.objects.create(name="Test Rank")
+    user = get_fake_user(fake, rank)
+    assert user.rank is rank
+
+
+def test_banned_fake_user_can_be_created(db, cache_versions, fake):
+    user = get_fake_banned_user(fake)
+    assert get_user_ban(user, cache_versions)
+
+
+def test_inactivate_fake_user_can_be_created(db, fake):
+    user = get_fake_inactive_user(fake)
+    assert user.requires_activation
+
+
+def test_admin_activated_fake_user_can_be_created(db, fake):
+    user = get_fake_admin_activated_user(fake)
+    assert user.requires_activation

+ 10 - 0
misago/faker/tests/test_fake_username.py

@@ -0,0 +1,10 @@
+from ..username import get_fake_username
+
+
+def test_fake_username_can_be_created(fake):
+    assert get_fake_username(fake)
+
+
+def test_different_fake_username_is_created_every_time(fake):
+    fake_usernames = [get_fake_username(fake) for i in range(5)]
+    assert len(fake_usernames) == len(set(fake_usernames))

+ 36 - 0
misago/faker/user.py

@@ -0,0 +1,36 @@
+from django.contrib.auth import get_user_model
+
+from ..users.bans import ban_user
+from ..users.test import create_test_user
+from .username import get_fake_username
+from .utils import retry_on_db_error
+
+User = get_user_model()
+
+PASSWORD = "password"
+
+
+@retry_on_db_error
+def get_fake_user(fake, rank=None, requires_activation=User.ACTIVATION_NONE):
+    username = get_fake_username(fake)
+    return create_test_user(
+        username,
+        fake.email(),
+        PASSWORD,
+        rank=rank,
+        requires_activation=requires_activation,
+    )
+
+
+def get_fake_banned_user(fake, rank=None):
+    user = get_fake_user(fake, rank=rank)
+    ban_user(user)
+    return user
+
+
+def get_fake_inactive_user(fake, rank=None):
+    return get_fake_user(fake, rank=rank, requires_activation=User.ACTIVATION_USER)
+
+
+def get_fake_admin_activated_user(fake, rank=None):
+    return get_fake_user(fake, rank=rank, requires_activation=User.ACTIVATION_ADMIN)

+ 16 - 0
misago/faker/username.py

@@ -0,0 +1,16 @@
+import random
+
+from django.utils.crypto import get_random_string
+from faker import Factory
+
+
+def get_fake_username(fake):
+    possible_usernames = [
+        fake.first_name(),
+        fake.last_name(),
+        fake.name().replace(" ", ""),
+        fake.user_name(),
+        get_random_string(random.randint(4, 8)),
+    ]
+
+    return random.choice(possible_usernames)

+ 11 - 0
misago/faker/utils.py

@@ -0,0 +1,11 @@
+from django.db import IntegrityError
+
+
+def retry_on_db_error(f):
+    def wrapper(*args, **kwargs):
+        try:
+            return f(*args, **kwargs)
+        except IntegrityError:
+            return wrapper(*args, **kwargs)
+
+    return wrapper

+ 3 - 3
misago/users/models/user.py

@@ -32,14 +32,14 @@ class UserManager(BaseUserManager):
         if not email:
             raise ValueError("User must have an email address.")
 
+        if not extra_fields.get("rank"):
+            extra_fields["rank"] = Rank.objects.get_default()
+
         user = self.model(**extra_fields)
         user.set_username(username)
         user.set_email(email)
         user.set_password(password)
 
-        if "rank" not in extra_fields:
-            user.rank = Rank.objects.get_default()
-
         now = timezone.now()
         user.last_login = now
         user.joined_on = now