def test_user_count(settings): """A basic test to execute the get_users_count Celery task.""" UserFactory.create_batch(3) settings.CELERY_TASK_ALWAYS_EAGER = True task_result = get_users_count.delay() assert isinstance(task_result, EagerResult) assert task_result.result == 3
def test_find_available_username( mocker, username_base, suffixed_to_create, expected_available_username ): """find_available_username should return an available username with the lowest possible suffix""" # Change the username max length to 10 for test data simplicity's sake temp_username_max_len = 10 mocker.patch("users.api.USERNAME_MAX_LEN", temp_username_max_len) def suffixed_username_generator(): """Generator for usernames with suffixes that will not exceed the username character limit""" for suffix_int in range(1, suffixed_to_create + 1): suffix = str(suffix_int) username = "******".format(username_base, suffix) if len(username) <= temp_username_max_len: yield username else: num_extra_characters = len(username) - temp_username_max_len yield "{}{}".format( username_base[0 : len(username_base) - num_extra_characters], suffix ) UserFactory.create(username=username_base) UserFactory.create_batch( suffixed_to_create, username=factory.Iterator(suffixed_username_generator()) ) available_username = find_available_username(username_base) assert available_username == expected_available_username
def test_list_unauthorized(self): UserFactory.create_batch(3) self.assertEqual(User.objects.count(), 3) path = self.get_path() response = self.client.get(path) self.assertEqual( response.status_code, status.HTTP_401_UNAUTHORIZED, msg=response.data )
def test_fetch_users_fail(prop, existing_values, missing_values): """ fetch_users should raise an exception if any provided values did not match a User, and the exception message should contain info about the values that did not match. """ fetch_users_values = existing_values + missing_values UserFactory.create_batch( len(existing_values), **{prop: factory.Iterator(existing_values)} ) expected_missing_value_output = str(sorted(list(missing_values))) with pytest.raises(User.DoesNotExist, match=expected_missing_value_output): fetch_users(fetch_users_values)
def test_setup_website_groups_permissions(): """ Permissions should be assigned as expected """ owner, admin, editor = UserFactory.create_batch(3) website = WebsiteFactory.create(owner=owner) # permissions should have all been added via signal assert setup_website_groups_permissions(website) == (0, 0, False) website.admin_group.delete() assert setup_website_groups_permissions(website) == (1, 0, False) remove_perm(constants.PERMISSION_VIEW, website.editor_group, website) assert setup_website_groups_permissions(website) == (0, 1, False) remove_perm(constants.PERMISSION_PUBLISH, website.owner, website) assert setup_website_groups_permissions(website) == (0, 0, True) admin.groups.add(website.admin_group) editor.groups.add(website.editor_group) for permission in constants.PERMISSIONS_EDITOR: assert editor.has_perm(permission, website) is True for permission in constants.PERMISSIONS_ADMIN: for user in [owner, admin]: assert user.has_perm(permission, website) is True for permission in [ constants.PERMISSION_PUBLISH, constants.PERMISSION_COLLABORATE ]: assert editor.has_perm(permission, website) is False
def test_repair_faulty_courseware_users(mocker, exception_raised): """ Tests that repair_faulty_courseware_users loops through all incorrectly configured Users, attempts to repair them, and continues iterating through the Users if an exception is raised """ with freeze_time(now_in_utc() - timedelta(days=1)): users = UserFactory.create_batch(3) user_count = len(users) patched_log_exception = mocker.patch("courseware.api.log.exception") patched_faulty_user_qset = mocker.patch( "users.models.FaultyCoursewareUserManager.get_queryset", return_value=User.objects.all(), ) patched_repair_user = mocker.patch( "courseware.api.repair_faulty_edx_user", side_effect=[ (True, True), # Function should continue executing if an exception is thrown exception_raised or (True, True), (True, True), ], ) repaired_users = repair_faulty_courseware_users() patched_faulty_user_qset.assert_called_once() assert patched_repair_user.call_count == user_count assert len(repaired_users) == (3 if exception_raised is None else 2) assert patched_log_exception.called == bool(exception_raised) if exception_raised: failed_user = patched_repair_user.call_args_list[1][0] expected_repaired_users = [ user for user in users if user != failed_user ] assert {u.id for u in users} == {u.id for u in expected_repaired_users}
def permission_groups(): """Set up groups, users and websites for permission testing""" ( global_admin, global_author, site_owner, site_admin, site_editor, ) = UserFactory.create_batch(5) websites = WebsiteFactory.create_batch(2, owner=site_owner) global_admin.groups.add(Group.objects.get(name=constants.GLOBAL_ADMIN)) global_author.groups.add(Group.objects.get(name=constants.GLOBAL_AUTHOR)) site_admin.groups.add(websites[0].admin_group) site_editor.groups.add(websites[0].editor_group) website = websites[0] owner_content = WebsiteContentFactory.create(website=website, owner=website.owner) editor_content = WebsiteContentFactory.create(website=website, owner=site_editor) yield SimpleNamespace( global_admin=global_admin, global_author=global_author, site_admin=site_admin, site_editor=site_editor, websites=websites, owner_content=owner_content, editor_content=editor_content, )
def test_messages_for_recipients(): """Tests that messages_for_recipients works as expected""" users = UserFactory.create_batch(5) messages = list( messages_for_recipients( [ ( recipient, context_for_user( user=user, extra_context={"url": "https://example.com"} ), ) for recipient, user in safe_format_recipients(users) ], "sample", ) ) assert len(messages) == len(users) for user, msg in zip(users, messages): assert user.email in str(msg.to[0]) assert msg.subject == "Welcome {}".format(user.name)
def test_send_message_failure(mocker): """Tests that send_messages logs all exceptions""" sendmail = mocker.patch("mail.api.AnymailMessage.send", side_effect=ConnectionError) patched_logger = mocker.patch("mail.api.log") users = UserFactory.create_batch(2) messages = list( messages_for_recipients( [ ( recipient, context_for_user( user=user, extra_context={"url": "https://example.com"} ), ) for recipient, user in safe_format_recipients(users) ], "sample", ) ) send_messages(messages) assert sendmail.call_count == len(users) assert patched_logger.exception.call_count == len(users)
def test_mail_transcripts_complete_notification(settings, mocker): """mail_transcripts_complete_notification should send correct email to correct users""" website = WebsiteFactory.create() users = UserFactory.create_batch(4) for user in users[:2]: user.groups.add(website.admin_group) for user in users[2:]: user.groups.add(website.editor_group) mock_get_message_sender = mocker.patch("videos.tasks.get_message_sender") mock_sender = mock_get_message_sender.return_value.__enter__.return_value mail_transcripts_complete_notification(website) mock_get_message_sender.assert_called_once_with(VideoTranscriptingCompleteMessage) assert mock_sender.build_and_send_message.call_count == len(users) + 1 for user in users: mock_sender.build_and_send_message.assert_any_call( user, { "site": { "title": website.title, "url": urljoin(settings.SITE_BASE_URL, f"/sites/{website.name}"), }, }, )
def test_fetch_users_case_sens(): """fetch_users should be able to fetch Users with a case-insensitive filter""" emails = ["*****@*****.**", "*****@*****.**", "*****@*****.**"] users = UserFactory.create_batch(len(emails), email=factory.Iterator(emails)) upper_emails = list(map(str.upper, emails)) with pytest.raises(User.DoesNotExist): fetch_users(upper_emails, ignore_case=False) assert set(fetch_users(upper_emails, ignore_case=True)) == set(users)
def handle(self, *args, **options): users = UserFactory.create_batch(options['size_batch']) self.stdout.write( self.style.SUCCESS('Создали {} записей'.format( options['size_batch']))) for user in users: self.stdout.write( self.style.SUCCESS('{0.username} - {0.name}'.format(user)))
def test_fetch_users(prop, values, db_values): """ fetch_users should return a set of Users that match some provided values which represent ids, emails, or usernames """ users = UserFactory.create_batch( len(values), **{prop: factory.Iterator(db_values or values)} ) found_users = fetch_users(values) assert set(users) == set(found_users)
def test_list(self): users = UserFactory.create_batch(3) self.assertEqual(User.objects.count(), 3) self.set_user(users[0]) path = self.get_path() response = self.client.get(path, HTTP_AUTHORIZATION=self.auth) self.assertEqual(response.status_code, status.HTTP_200_OK, msg=response.data) self.assertEqual(len(response.data.get("results")), 1, msg=response.data)
def handle(self, *args, **options): users = UserFactory.create_batch(USERS) for user in users: for _ in range(randint(0, MAX_RECIPES)): RecipeFactory(author=user, tags=(0, 1, 2)) for user in User.objects.all(): recipes = list(Recipe.objects.all()) to_favorite = sample(recipes, k=randint(1, MAX_FAVORITES)) Favorite.objects.bulk_create( [Favorite(user=user, recipe=recipe) for recipe in to_favorite])
def db_data(): """Fixture that seeds the database with data needed for this test suite""" users = UserFactory.create_batch(2) website = WebsiteFactory.create() website_contents = WebsiteContentFactory.create_batch( 5, website=website, updated_by=factory.Iterator( [users[0], users[0], users[0], users[1], users[1]]), ) return SimpleNamespace(users=users, website=website, website_contents=website_contents)
def setUp(self): self.api_client = self.client self.assert_equal = self.assertEqual self.assert_list_equal = self.assertListEqual self.endpoint = "/api/rooms/" self.model_class = Room self.serializer_class = RoomSerializer self.detail_serializer_class = RoomDetailSerializer self.factory_class = RoomFactory self.pop_keys = ["id", "datetime_created", "members"] self.maxDiff = self.max_diff users = UserFactory.create_batch(5, connected_users=[], blocked_users=[]) items = self.factory_class.create_batch(5, members=users) self.api_client.login(email=users[0].email, password="******")
def mock_mail(mocker): """ Objects and mocked functions for mail tests""" mock_get_message_sender = mocker.patch("videos.youtube.get_message_sender") mock_sender = mock_get_message_sender.return_value.__enter__.return_value video_file = VideoFileFactory.create() users = UserFactory.create_batch(4) for user in users[:2]: user.groups.add(video_file.video.website.admin_group) for user in users[2:]: user.groups.add(video_file.video.website.editor_group) return SimpleNamespace( mock_get_message_sender=mock_get_message_sender, mock_sender=mock_sender, video_file=video_file, users=users, )
def test_faulty_user_qset(): """User.faulty_courseware_users should return a User queryset that contains incorrectly configured active Users""" users = UserFactory.create_batch(5) # An inactive user should not be returned even if they lack auth and courseware user records UserFactory.create(is_active=False) good_users = users[0:2] expected_faulty_users = users[2:] OpenEdxApiAuthFactory.create_batch(3, user=factory.Iterator(good_users + [users[3]])) CoursewareUserFactory.create_batch(3, user=factory.Iterator(good_users + [users[4]])) assert set(User.faulty_courseware_users.values_list( "id", flat=True)) == {user.id for user in expected_faulty_users}
def handle(self, *args, **options): users = UserFactory.create_batch(USERS) tags = Tag.objects.all() ing = Ingredient.objects.all() for user in users: for _ in range(randint(0, MAX_RECIPES)): RecipeFactory(user=user) for user in User.objects.all(): # User cannot favorite his own recipes recipes = list(Recipe.objects.exclude(user=user)) to_favorite = sample(recipes, k=randint(1, MAX_FAVORITES)) Favorite.objects.bulk_create( [Favorite(user=user, recipe=recipe) for recipe in to_favorite]) for user in User.objects.all(): recipes = list(Recipe.objects.all()) to_shopping_cart = sample(recipes, k=randint(1, MAX_FAVORITES)) ShoppingCart.objects.bulk_create([ ShoppingCart(user=user, recipe=recipe) for recipe in to_shopping_cart ]) for user in User.objects.all(): other_users = list(User.objects.exclude(username=user.username)) to_followings = sample(other_users, k=randint(1, MAX_FAVORITES)) Follow.objects.bulk_create([ Follow(follower=user, following=person) for person in to_followings ]) for recipe in Recipe.objects.all(): recipe.tag.add(tags[randint(0, 2)]) q = randint(1, 4) ing_to_add = sample(list(ing), q) for i in ing_to_add: rp = RecipeIngredient.objects.create(recipe=recipe, ingredient=i, quantity=randint(50, 500)) rp.save()
def test_send_message(mailoutbox): """Tests that send_messages works as expected""" users = UserFactory.create_batch(5) messages = list( messages_for_recipients( [ ( recipient, context_for_user( user=user, extra_context={"url": "https://example.com"} ), ) for recipient, user in safe_format_recipients(users) ], "sample", ) ) send_messages(messages) for message in mailoutbox: assert message in messages
def test_create_global_groups(): """Global permission groups should be created and have appropriate permissions""" # Groups already exist assert create_global_groups() == (0, 0) # Delete one so it can be recreated Group.objects.get(name=constants.GLOBAL_ADMIN).delete() # Clear permissions from another Group.objects.get(name=constants.GLOBAL_AUTHOR).permissions.clear() assert create_global_groups() == (1, 1) admin, author = UserFactory.create_batch(2) admin_group = Group.objects.get(name=constants.GLOBAL_ADMIN) admin.groups.add(admin_group) author_group = Group.objects.get(name=constants.GLOBAL_AUTHOR) author.groups.add(author_group) for permission in constants.PERMISSIONS_ADMIN: assert admin.has_perm(permission) is True for permission in constants.PERMISSIONS_EDITOR: assert author.has_perm(permission) is False assert author.has_perm(constants.PERMISSION_ADD) is True
def setUp(self): self.user_list = UserFactory.create_batch(size=1, is_staff=False) self.staff_list = UserFactory.create_batch(size=1, is_staff=True) self.object_list = self.user_list + self.staff_list
def setUp(self): self.user_list = UserFactory.create_batch(size=1, is_staff=False) self.staff_list = UserFactory.create_batch(size=1, is_staff=True) self.object_list = self.user_list + self.staff_list
from posts.factories import PostFactory from posts.models import Post from balance.factories import RecordFactory from allauth.account.models import EmailAddress from rest_framework.test import APIClient from django.urls import reverse from django.contrib.contenttypes.models import ContentType from faker import Faker if __name__ == '__main__': site = SiteFactory() c = APIClient() fake = Faker() # 生成 5 个用户 UserFactory.create_batch(5) print('users created...') # 生成 5 个标签 user = UserFactory(username='******') TagFactory.create_batch(5, creator=user) print('tags created...') tags = list(Tag.objects.all()) users = list(User.objects.all()) # 每个用户发布一定量的帖子 for user in users: post_count = random.randint(5, 10) for i in range(post_count):
from posts.factories import PostFactory from posts.models import Post from balance.factories import RecordFactory from allauth.account.models import EmailAddress from rest_framework.test import APIClient from django.urls import reverse from django.contrib.contenttypes.models import ContentType from faker import Faker if __name__ == '__main__': site = SiteFactory() c = APIClient() fake = Faker() # 生成 10 个用户 UserFactory.create_batch(10) print('users created...') # 生成 10 个标签 user = UserFactory(username='******') TagFactory.create_batch(10, creator=user) print('tags created...') tags = list(Tag.objects.all()) users = list(User.objects.all()) # 每个用户发布一定量的帖子 for user in users: post_count = random.randint(10, 15) for i in range(post_count):
def handle(self, *args, **options): item_count = options["item_count"] start_time = datetime.now() print("Task begin!") print("Creating users...") UserFactory.create_batch(item_count, connected_users=[], blocked_users=[]) users = CustomUser.objects.all() print("Assigning connected and blocked users...") for user in users: connect_users = random_users(users, item_count) blocked_users = random_users(users, item_count) for a in connect_users: user.connected_users.add(a) for b in blocked_users: user.blocked_users.add(b) print(f"Creating {item_count} items...") for i in range(item_count): rand_int1 = random.randint(0, 12) rand_int2 = random.randint(0, 12) ad = AdFactory( liked_users=random_users(users, item_count), tagged_users=random_users(users, item_count), saved_users=random_users(users, item_count), creator=users.get(id=random.randint(1, item_count)), contacted_users=random_users(users, item_count), confirmed_users=random_users(users, item_count), ) event = EventFactory( liked_users=random_users(users, item_count), tagged_users=random_users(users, item_count), saved_users=random_users(users, item_count), creator=users.get(id=random.randint(1, item_count)), interested_users=random_users(users, item_count), attending_users=random_users(users, item_count), ) job = JobFactory(creator=users.get( id=random.randint(1, item_count))) listing = ListingFactory( liked_users=random_users(users, item_count), tagged_users=random_users(users, item_count), saved_users=random_users(users, item_count), creator=users.get(id=random.randint(1, item_count)), contacted_users=random_users(users, item_count), confirmed_users=random_users(users, item_count), ) room = RoomFactory(members=random_users(users, item_count), ) for j in range(rand_int1): message = MessageFactory( liked_users=random_users(users, item_count), tagged_users=random_users(users, item_count), creator=users.get(id=random.randint(1, item_count)), room=room, ) poll = PollFactory( liked_users=random_users(users, item_count), tagged_users=random_users(users, item_count), saved_users=random_users(users, item_count), creator=users.get(id=random.randint(1, item_count)), ) for m in range(rand_int2): option = OptionFactory( creator=users.get(id=random.randint(1, item_count)), poll=poll) for n in range(rand_int1): vote = VoteFactory( creator=users.get(id=random.randint(1, item_count)), option=option, ) post = PostFactory( liked_users=random_users(users, item_count), tagged_users=random_users(users, item_count), saved_users=random_users(users, item_count), creator=users.get(id=random.randint(1, item_count)), ) postings = [ad, event, listing, poll, post] for x in range(rand_int1): comment = CommentFactory( liked_users=random_users(users, item_count), tagged_users=random_users(users, item_count), saved_users=random_users(users, item_count), creator=users.get(id=random.randint(1, item_count)), content_object=postings[random.randint( 0, len(postings) - 1)], ) for y in range(rand_int2): reply = ReplyFactory( liked_users=random_users(users, item_count), tagged_users=random_users(users, item_count), saved_users=random_users(users, item_count), creator=users.get(id=random.randint(1, item_count)), comment=comment, ) if (i + 1) % 10 == 0: print(f"\n{i + 1} items created...\n") end_time = datetime.now() time_diff = end_time - start_time total_seconds = time_diff.total_seconds() print( f"Task complete after {total_seconds // 60} min and {total_seconds // 1 % 60} seconds!" )