class SetLastVisitMiddlewareTest(TestCase): def setUp(self): self.user = ProfileFactory() def test_process_response(self): profile_pk = self.user.pk # login self.client.force_login(self.user.user) # set last login to a recent date self.user.last_visit = datetime.now() - timedelta(seconds=10) self.user.save() # load a page self.client.get(reverse("homepage")) # the date of last visit should not have been updated profile = get_object_or_404(Profile, pk=profile_pk) self.assertTrue( datetime.now() - profile.last_visit > timedelta(seconds=5)) # set last login to an old date self.user.last_visit = datetime.now() - timedelta(seconds=45) self.user.save() # load a page self.client.get(reverse("homepage")) # the date of last visit should have been updated profile = get_object_or_404(Profile, pk=profile_pk) self.assertTrue( datetime.now() - profile.last_visit < timedelta(seconds=5))
class SubscriptionsTest(TestCase): def setUp(self): self.userStandard1 = ProfileFactory(email_for_answer=True, email_for_new_mp=True).user self.userOAuth1 = ProfileFactory(email_for_answer=True, email_for_new_mp=True).user self.userOAuth2 = ProfileFactory(email_for_answer=True, email_for_new_mp=True).user self.userOAuth1.email = "" self.userOAuth2.email = "this is not an email" self.userOAuth1.save() self.userOAuth2.save() def test_no_emails_for_those_who_have_none(self): """ Test that we do not try to send e-mails to those who have not registered one. """ self.assertEqual(0, len(mail.outbox)) topic = send_mp( author=self.userStandard1, users=[self.userOAuth1], title="Testing", subtitle="", text="", send_by_mail=True, leave=False, ) self.assertEqual(0, len(mail.outbox)) send_message_mp(self.userOAuth1, topic, "", send_by_mail=True) self.assertEqual(1, len(mail.outbox)) def test_no_emails_for_those_who_have_other_things_in_that_place(self): """ Test that we do not try to send e-mails to those who have not registered a valid one. """ self.assertEqual(0, len(mail.outbox)) topic = send_mp( author=self.userStandard1, users=[self.userOAuth2], title="Testing", subtitle="", text="", send_by_mail=True, leave=False, ) self.assertEqual(0, len(mail.outbox)) send_message_mp(self.userOAuth2, topic, "", send_by_mail=True) self.assertEqual(1, len(mail.outbox))
def test_profiler(self): result = self.client.get("/?prof", follow=True) self.assertEqual(result.status_code, 200) admin = ProfileFactory() admin.user.is_superuser = True admin.save() self.client.force_login(admin.user) result = self.client.get("/?prof", follow=True) self.assertEqual(result.status_code, 200)
def test_failure_reaction_karma_with_sanctioned_user(self): author = ProfileFactory() reaction = ContentReactionFactory(author=author.user, position=1, related_content=self.content) profile = ProfileFactory() profile.can_read = False profile.can_write = False profile.save() self.client.force_login(profile.user) response = self.client.put(reverse("api:content:reaction-karma", args=(reaction.pk,))) self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
def test_members_are_contactable(self): """ The PM button is displayed to logged in users, except if it's the profile of a banned user. """ user_ban = ProfileFactory() user_ban.can_read = False user_ban.can_write = False user_ban.save() user_1 = ProfileFactory() user_2 = ProfileFactory() phrase = "Envoyer un message" # The PM button is hidden for anonymous users result = self.client.get(reverse("member-detail", args=[user_1.user.username]), follow=False) self.assertNotContains(result, phrase) # Also for anonymous users viewing banned members profiles result = self.client.get(reverse("member-detail", args=[user_ban.user.username]), follow=False) self.assertNotContains(result, phrase) self.client.force_login(user_2.user) # If an user is logged in, the PM button is shown for other normal users result = self.client.get(reverse("member-detail", args=[user_1.user.username]), follow=False) self.assertContains(result, phrase) # But not for banned users result = self.client.get(reverse("member-detail", args=[user_ban.user.username]), follow=False) self.assertNotContains(result, phrase) self.client.logout() self.client.force_login(user_1.user) # Neither for his own profile result = self.client.get(reverse("member-detail", args=[user_1.user.username]), follow=False) self.assertNotContains(result, phrase) self.client.logout()
def load_member(cli, size, fake, root, *_): """ Load members """ nb_users = size * 10 cli.stdout.write(f"Nombres de membres à créer : {nb_users}") tps1 = time.time() cpt = 1 # member in settings users_set = [ "admin", settings.ZDS_APP["member"]["external_account"], settings.ZDS_APP["member"]["anonymous_account"], ] for default_user in users_set: current_user = Profile.objects.filter(user__username=default_user).first() if current_user is None: profile = ProfileFactory(user__username=default_user) profile.user.set_password(default_user) profile.user.first_name = default_user profile.user.email = fake.free_email() if default_user == "admin": profile.user.is_superuser = True profile.user.is_staff = True with contextlib.suppress(IntegrityError): profile.user.save() profile.site = fake.url() profile.biography = fake.text(max_nb_chars=200) profile.last_ip_address = fake.ipv4() profile.save() for i in range(0, nb_users): while Profile.objects.filter(user__username=f"{root}{cpt}").count() > 0: cpt += 1 profile = ProfileFactory(user__username=f"{root}{cpt}") profile.user.set_password(profile.user.username) profile.user.first_name = fake.first_name() profile.user.last_name = fake.last_name() profile.user.email = fake.free_email() profile.user.save() profile.site = fake.url() profile.biography = fake.text(max_nb_chars=200) profile.last_ip_address = fake.ipv4() profile.save() cpt += 1 sys.stdout.write(f" User {i + 1}/{nb_users} \r") sys.stdout.flush() tps2 = time.time() cli.stdout.write(f"\nFait en {tps2 - tps1} sec")
def test_failure_post_karma_with_sanctioned_user(self): profile = ProfileFactory() category, forum = create_category_and_forum() topic = create_topic_in_forum(forum, profile) another_profile = ProfileFactory() post = PostFactory(topic=topic, author=another_profile.user, position=2) profile = ProfileFactory() profile.can_read = False profile.can_write = False profile.save() self.client.force_login(profile.user) response = self.client.put(reverse("api:forum:post-karma", args=(post.pk,))) self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN)
def test_char_count_after_publication(self): """Test the ``get_char_count()`` function. Special care should be taken with this function, since: - The username of the author is, by default "Firmxxx" where "xxx" depends on the tests before ; - The titles (!) also contains a number that also depends on the number of tests before ; - The date is ``datetime.now()`` and contains the months, which is never a fixed number of letters. """ author = ProfileFactory().user author.username = "******" author.save() len_date_now = len(date(datetime.now(), "d F Y")) article = PublishedContentFactory(type="ARTICLE", author_list=[author], title="Un titre") published = PublishedContent.objects.filter(content=article).first() self.assertEqual(published.get_char_count(), 160 + len_date_now) tuto = PublishableContentFactory(type="TUTORIAL", author_list=[author], title="Un titre") # add a chapter, so it becomes a middle tutorial tuto_draft = tuto.load_version() chapter1 = ContainerFactory(parent=tuto_draft, db_object=tuto, title="Un chapitre") ExtractFactory(container=chapter1, db_object=tuto, title="Un extrait") published = publish_content(tuto, tuto_draft, is_major_update=True) tuto.sha_public = tuto_draft.current_version tuto.sha_draft = tuto_draft.current_version tuto.public_version = published tuto.save() published = PublishedContent.objects.filter(content=tuto).first() self.assertEqual(published.get_char_count(), 335 + len_date_now)
def test_no_notification_on_a_tag_subscribed_in_hidden_forum(self): """ When a user subscribes to a tag and a topic is created using that tag in a hidden forum, no notification is sent """ # Subscribe. user1 = ProfileFactory().user user2 = ProfileFactory().user group = Group.objects.create(name="Restricted") user2.groups.add(group) user2.save() category, forum = create_category_and_forum(group) tag1 = TagFactory(title="MyTagInHiddenForum") NewTopicSubscription.objects.toggle_follow(tag1, user1) topic1 = TopicFactory(forum=forum, author=user2) topic1.add_tags([tag1.title]) notifications = Notification.objects.filter(object_id=topic1.pk, is_read=False).all() self.assertEqual(0, len(notifications))
def test_members_with_provider(self): # create two members with the same provider member1 = ProfileFactory().user member2 = ProfileFactory().user member1.email = "*****@*****.**" member1.save() member2.email = "*****@*****.**" member2.save() # ban this provider provider = BannedEmailProvider.objects.create(moderator=self.staff, provider="test-members.com") # check that this page is only available for staff self.client.logout() result = self.client.get(reverse("members-with-provider", args=[provider.pk]), follow=False) self.assertEqual(result.status_code, 302) self.client.force_login(member1) result = self.client.get(reverse("members-with-provider", args=[provider.pk]), follow=False) self.assertEqual(result.status_code, 403) self.client.force_login(self.staff) result = self.client.get(reverse("members-with-provider", args=[provider.pk]), follow=False) self.assertEqual(result.status_code, 200) # check that it contains the two members self.assertIn(member1.profile, result.context["members"]) self.assertIn(member2.profile, result.context["members"])
def test_reachable_manager(self): # profile types profile_normal = ProfileFactory() profile_superuser = ProfileFactory() profile_superuser.user.is_superuser = True profile_superuser.user.save() profile_inactive = ProfileFactory() profile_inactive.user.is_active = False profile_inactive.user.save() profile_bot = ProfileFactory() profile_bot.user.username = settings.ZDS_APP["member"]["bot_account"] profile_bot.user.save() profile_anonymous = ProfileFactory() profile_anonymous.user.username = settings.ZDS_APP["member"][ "anonymous_account"] profile_anonymous.user.save() profile_external = ProfileFactory() profile_external.user.username = settings.ZDS_APP["member"][ "external_account"] profile_external.user.save() profile_ban_def = ProfileFactory() profile_ban_def.can_read = False profile_ban_def.can_write = False profile_ban_def.save() profile_ban_temp = ProfileFactory() profile_ban_temp.can_read = False profile_ban_temp.can_write = False profile_ban_temp.end_ban_read = datetime.now() + timedelta(days=1) profile_ban_temp.save() profile_unban = ProfileFactory() profile_unban.can_read = False profile_unban.can_write = False profile_unban.end_ban_read = datetime.now() - timedelta(days=1) profile_unban.save() profile_ls_def = ProfileFactory() profile_ls_def.can_write = False profile_ls_def.save() profile_ls_temp = ProfileFactory() profile_ls_temp.can_write = False profile_ls_temp.end_ban_write = datetime.now() + timedelta(days=1) profile_ls_temp.save() # groups bot = Group(name=settings.ZDS_APP["member"]["bot_group"]) bot.save() # associate account to groups bot.user_set.add(profile_anonymous.user) bot.user_set.add(profile_external.user) bot.user_set.add(profile_bot.user) bot.save() # test reachable user profiles_reacheable = Profile.objects.contactable_members().all() self.assertIn(profile_normal, profiles_reacheable) self.assertIn(profile_superuser, profiles_reacheable) self.assertNotIn(profile_inactive, profiles_reacheable) self.assertNotIn(profile_anonymous, profiles_reacheable) self.assertNotIn(profile_external, profiles_reacheable) self.assertNotIn(profile_bot, profiles_reacheable) self.assertIn(profile_unban, profiles_reacheable) self.assertNotIn(profile_ban_def, profiles_reacheable) self.assertNotIn(profile_ban_temp, profiles_reacheable) self.assertIn(profile_ls_def, profiles_reacheable) self.assertIn(profile_ls_temp, profiles_reacheable)
class MemberModelsTest(TutorialTestMixin, TestCase): def setUp(self): self.user1 = ProfileFactory() self.staff = StaffProfileFactory() # Create a forum for later test self.forumcat = ForumCategoryFactory() self.forum = ForumFactory(category=self.forumcat) self.forumtopic = TopicFactory(forum=self.forum, author=self.staff.user) def test_get_absolute_url_for_details_of_member(self): self.assertEqual(self.user1.get_absolute_url(), f"/@{self.user1.user.username}") def test_get_avatar_url(self): # if no url was specified -> gravatar ! self.assertEqual( self.user1.get_avatar_url(), "https://secure.gravatar.com/avatar/{}?d=identicon".format( md5(self.user1.user.email.lower().encode()).hexdigest()), ) # if an url is specified -> take it ! user2 = ProfileFactory() testurl = "http://test.com/avatar.jpg" user2.avatar_url = testurl self.assertEqual(user2.get_avatar_url(), testurl) # if url is relative, send absolute url gallerie_avtar = GalleryFactory() image_avatar = ImageFactory(gallery=gallerie_avtar) user2.avatar_url = image_avatar.physical.url self.assertNotEqual(user2.get_avatar_url(), image_avatar.physical.url) self.assertIn("http", user2.get_avatar_url()) def test_get_post_count(self): # Start with 0 self.assertEqual(self.user1.get_post_count(), 0) # Post ! PostFactory(topic=self.forumtopic, author=self.user1.user, position=1) # Should be 1 self.assertEqual(self.user1.get_post_count(), 1) def test_get_topic_count(self): # Start with 0 self.assertEqual(self.user1.get_topic_count(), 0) # Create Topic ! TopicFactory(forum=self.forum, author=self.user1.user) # Should be 1 self.assertEqual(self.user1.get_topic_count(), 1) def test_get_tuto_count(self): # Start with 0 self.assertEqual(self.user1.get_tuto_count(), 0) # Create Tuto ! minituto = PublishableContentFactory(type="TUTORIAL") minituto.authors.add(self.user1.user) minituto.gallery = GalleryFactory() minituto.save() # Should be 1 self.assertEqual(self.user1.get_tuto_count(), 1) def test_get_tutos(self): # Start with 0 self.assertEqual(len(self.user1.get_tutos()), 0) # Create Tuto ! minituto = PublishableContentFactory(type="TUTORIAL") minituto.authors.add(self.user1.user) minituto.gallery = GalleryFactory() minituto.save() # Should be 1 tutos = self.user1.get_tutos() self.assertEqual(len(tutos), 1) self.assertEqual(minituto, tutos[0]) def test_get_draft_tutos(self): # Start with 0 self.assertEqual(len(self.user1.get_draft_tutos()), 0) # Create Tuto ! drafttuto = PublishableContentFactory(type="TUTORIAL") drafttuto.authors.add(self.user1.user) drafttuto.gallery = GalleryFactory() drafttuto.save() # Should be 1 drafttutos = self.user1.get_draft_tutos() self.assertEqual(len(drafttutos), 1) self.assertEqual(drafttuto, drafttutos[0]) def test_get_public_tutos(self): # Start with 0 self.assertEqual(len(self.user1.get_public_tutos()), 0) # Create Tuto ! publictuto = PublishableContentFactory(type="TUTORIAL") publictuto.authors.add(self.user1.user) publictuto.gallery = GalleryFactory() publictuto.sha_public = "whatever" publictuto.save() # Should be 0 because publication was not used publictutos = self.user1.get_public_tutos() self.assertEqual(len(publictutos), 0) PublishedContentFactory(author_list=[self.user1.user]) self.assertEqual(len(self.user1.get_public_tutos()), 1) def test_get_validate_tutos(self): # Start with 0 self.assertEqual(len(self.user1.get_validate_tutos()), 0) # Create Tuto ! validatetuto = PublishableContentFactory(type="TUTORIAL", author_list=[self.user1.user]) validatetuto.sha_validation = "whatever" validatetuto.save() # Should be 1 validatetutos = self.user1.get_validate_tutos() self.assertEqual(len(validatetutos), 1) self.assertEqual(validatetuto, validatetutos[0]) def test_get_beta_tutos(self): # Start with 0 self.assertEqual(len(self.user1.get_beta_tutos()), 0) # Create Tuto ! betatetuto = PublishableContentFactory(type="TUTORIAL") betatetuto.authors.add(self.user1.user) betatetuto.gallery = GalleryFactory() betatetuto.sha_beta = "whatever" betatetuto.save() # Should be 1 betatetutos = self.user1.get_beta_tutos() self.assertEqual(len(betatetutos), 1) self.assertEqual(betatetuto, betatetutos[0]) def test_get_article_count(self): # Start with 0 self.assertEqual(self.user1.get_tuto_count(), 0) # Create article ! minituto = PublishableContentFactory(type="ARTICLE") minituto.authors.add(self.user1.user) minituto.gallery = GalleryFactory() minituto.save() # Should be 1 self.assertEqual(self.user1.get_article_count(), 1) def test_get_articles(self): # Start with 0 self.assertEqual(len(self.user1.get_articles()), 0) # Create article ! article = PublishableContentFactory(type="ARTICLE") article.authors.add(self.user1.user) article.save() # Should be 1 articles = self.user1.get_articles() self.assertEqual(len(articles), 1) self.assertEqual(article, articles[0]) def test_get_public_articles(self): # Start with 0 self.assertEqual(len(self.user1.get_public_articles()), 0) # Create article ! article = PublishableContentFactory(type="ARTICLE") article.authors.add(self.user1.user) article.sha_public = "whatever" article.save() # Should be 0 articles = self.user1.get_public_articles() self.assertEqual(len(articles), 0) # Should be 1 PublishedContentFactory(author_list=[self.user1.user], type="ARTICLE") self.assertEqual(len(self.user1.get_public_articles()), 1) self.assertEqual(len(self.user1.get_public_tutos()), 0) def test_get_validate_articles(self): # Start with 0 self.assertEqual(len(self.user1.get_validate_articles()), 0) # Create article ! article = PublishableContentFactory(type="ARTICLE") article.authors.add(self.user1.user) article.sha_validation = "whatever" article.save() # Should be 1 articles = self.user1.get_validate_articles() self.assertEqual(len(articles), 1) self.assertEqual(article, articles[0]) def test_get_draft_articles(self): # Start with 0 self.assertEqual(len(self.user1.get_draft_articles()), 0) # Create article ! article = PublishableContentFactory(type="ARTICLE") article.authors.add(self.user1.user) article.save() # Should be 1 articles = self.user1.get_draft_articles() self.assertEqual(len(articles), 1) self.assertEqual(article, articles[0]) def test_get_beta_articles(self): # Start with 0 self.assertEqual(len(self.user1.get_beta_articles()), 0) # Create article ! article = PublishableContentFactory(type="ARTICLE") article.authors.add(self.user1.user) article.sha_beta = "whatever" article.save() # Should be 1 articles = self.user1.get_beta_articles() self.assertEqual(len(articles), 1) self.assertEqual(article, articles[0]) def test_get_posts(self): # Start with 0 self.assertEqual(len(self.user1.get_posts()), 0) # Post ! apost = PostFactory(topic=self.forumtopic, author=self.user1.user, position=1) # Should be 1 posts = self.user1.get_posts() self.assertEqual(len(posts), 1) self.assertEqual(apost, posts[0]) def test_get_hidden_by_staff_posts_count(self): # Start with 0 self.assertEqual(self.user1.get_hidden_by_staff_posts_count(), 0) # Post and hide it by poster PostFactory(topic=self.forumtopic, author=self.user1.user, position=1, is_visible=False, editor=self.user1.user) # Should be 0 self.assertEqual(self.user1.get_hidden_by_staff_posts_count(), 0) # Post and hide it by staff PostFactory(topic=self.forumtopic, author=self.user1.user, position=1, is_visible=False, editor=self.staff.user) # Should be 1 self.assertEqual(self.user1.get_hidden_by_staff_posts_count(), 1) def test_get_hidden_by_staff_posts_count_staff_poster(self): # Start with 0 self.assertEqual(self.staff.get_hidden_by_staff_posts_count(), 0) # Post and hide it by poster which is staff PostFactory(topic=self.forumtopic, author=self.staff.user, position=1, is_visible=False, editor=self.staff.user) # Should be 0 because even if poster is staff, he is the poster self.assertEqual(self.staff.get_hidden_by_staff_posts_count(), 0) def test_get_active_alerts_count(self): # Start with 0 self.assertEqual(self.user1.get_active_alerts_count(), 0) # Post and Alert it ! post = PostFactory(topic=self.forumtopic, author=self.user1.user, position=1) Alert.objects.create(author=self.user1.user, comment=post, scope="FORUM", pubdate=datetime.now()) # Should be 1 self.assertEqual(self.user1.get_active_alerts_count(), 1) def test_can_read_now(self): profile = ProfileFactory() profile.is_active = True profile.can_read = True self.assertTrue(profile.can_read_now()) # Was banned in the past, ban no longer active profile = ProfileFactory() profile.end_ban_read = datetime.now() - timedelta(days=1) self.assertTrue(profile.can_read_now()) profile = ProfileFactory() profile.is_active = True profile.can_read = False self.assertFalse(profile.can_read_now()) # Ban is active profile = ProfileFactory() profile.is_active = True profile.can_read = False profile.end_ban_read = datetime.now() + timedelta(days=1) self.assertFalse(profile.can_read_now()) self.user1.user.is_active = False self.assertFalse(self.user1.can_read_now()) def test_can_write_now(self): self.user1.user.is_active = True self.user1.user.can_write = True self.assertTrue(self.user1.can_write_now()) # Was banned in the past, ban no longer active profile = ProfileFactory() profile.can_write = True profile.end_ban_read = datetime.now() - timedelta(days=1) self.assertTrue(profile.can_write_now()) profile = ProfileFactory() profile.can_write = False profile.is_active = True self.assertFalse(profile.can_write_now()) # Ban is active profile = ProfileFactory() profile.can_write = False profile.end_ban_write = datetime.now() + timedelta(days=1) self.assertFalse(profile.can_write_now()) self.user1.user.is_active = False self.user1.user.can_write = True self.assertFalse(self.user1.can_write_now()) def test_get_followed_topics(self): # Start with 0 self.assertEqual( len( TopicAnswerSubscription.objects.get_objects_followed_by( self.user1.user)), 0) self.assertEqual(self.user1.get_followed_topic_count(), 0) # Follow ! TopicAnswerSubscription.objects.toggle_follow(self.forumtopic, self.user1.user) # Should be 1 topicsfollowed = TopicAnswerSubscription.objects.get_objects_followed_by( self.user1.user) self.assertEqual(len(topicsfollowed), 1) self.assertEqual(self.forumtopic, topicsfollowed[0]) self.assertEqual(self.user1.get_followed_topic_count(), 1) self.assertIn(self.forumtopic, self.user1.get_followed_topics()) def test_get_city_with_wrong_ip(self): # Set a local IP to the user self.user1.last_ip_address = "127.0.0.1" # Then the get_city is not found and return empty string self.assertEqual("", self.user1.get_city()) # Same goes for IPV6 # Set a local IP to the user self.user1.last_ip_address = "0000:0000:0000:0000:0000:0000:0000:0001" # Then the get_city is not found and return empty string self.assertEqual("", self.user1.get_city()) def test_remove_token_on_removing_from_dev_group(self): dev = DevProfileFactory() dev.github_token = "test" dev.save() dev.user.save() self.assertEqual("test", dev.github_token) # remove dev from dev group dev.user.groups.clear() dev.user.save() self.assertEqual("", dev.github_token) def test_reachable_manager(self): # profile types profile_normal = ProfileFactory() profile_superuser = ProfileFactory() profile_superuser.user.is_superuser = True profile_superuser.user.save() profile_inactive = ProfileFactory() profile_inactive.user.is_active = False profile_inactive.user.save() profile_bot = ProfileFactory() profile_bot.user.username = settings.ZDS_APP["member"]["bot_account"] profile_bot.user.save() profile_anonymous = ProfileFactory() profile_anonymous.user.username = settings.ZDS_APP["member"][ "anonymous_account"] profile_anonymous.user.save() profile_external = ProfileFactory() profile_external.user.username = settings.ZDS_APP["member"][ "external_account"] profile_external.user.save() profile_ban_def = ProfileFactory() profile_ban_def.can_read = False profile_ban_def.can_write = False profile_ban_def.save() profile_ban_temp = ProfileFactory() profile_ban_temp.can_read = False profile_ban_temp.can_write = False profile_ban_temp.end_ban_read = datetime.now() + timedelta(days=1) profile_ban_temp.save() profile_unban = ProfileFactory() profile_unban.can_read = False profile_unban.can_write = False profile_unban.end_ban_read = datetime.now() - timedelta(days=1) profile_unban.save() profile_ls_def = ProfileFactory() profile_ls_def.can_write = False profile_ls_def.save() profile_ls_temp = ProfileFactory() profile_ls_temp.can_write = False profile_ls_temp.end_ban_write = datetime.now() + timedelta(days=1) profile_ls_temp.save() # groups bot = Group(name=settings.ZDS_APP["member"]["bot_group"]) bot.save() # associate account to groups bot.user_set.add(profile_anonymous.user) bot.user_set.add(profile_external.user) bot.user_set.add(profile_bot.user) bot.save() # test reachable user profiles_reacheable = Profile.objects.contactable_members().all() self.assertIn(profile_normal, profiles_reacheable) self.assertIn(profile_superuser, profiles_reacheable) self.assertNotIn(profile_inactive, profiles_reacheable) self.assertNotIn(profile_anonymous, profiles_reacheable) self.assertNotIn(profile_external, profiles_reacheable) self.assertNotIn(profile_bot, profiles_reacheable) self.assertIn(profile_unban, profiles_reacheable) self.assertNotIn(profile_ban_def, profiles_reacheable) self.assertNotIn(profile_ban_temp, profiles_reacheable) self.assertIn(profile_ls_def, profiles_reacheable) self.assertIn(profile_ls_temp, profiles_reacheable) def test_remove_hats_linked_to_group(self): # create a hat linked to a group hat_name = "Test hat" hat, _ = Hat.objects.get_or_create(name__iexact=hat_name, defaults={"name": hat_name}) group, _ = Group.objects.get_or_create(name="test_hat") hat.group = group hat.save() # add it to a user self.user1.hats.add(hat) self.user1.save() # the user shound't have the hat through their profile self.assertNotIn(hat, self.user1.hats.all())
class EditContentLicenseFunctionalTests(TutorialTestMixin, TestCase): """Test the detailed behavior of the feature, such as updates of the database or repositories.""" def setUp(self): # Create a user self.author = ProfileFactory() # Create licenses self.license_1 = LicenceFactory() self.license_2 = LicenceFactory() # Create a content self.content = PublishableContentFactory( author_list=[self.author.user], add_license=False) # Get information to be reused in tests self.form_url = reverse("content:edit-license", kwargs={"pk": self.content.pk}) # Log in with an authorized user (e.g the author of the content) to perform the tests self.client.force_login(self.author.user) def test_form_function(self): """Test many use cases for the form.""" test_cases = self.get_test_cases() for case_name, case in test_cases.items(): with self.subTest(msg=case_name): self.enforce_preconditions(case["preconditions"]) self.post_form(case["inputs"]) self.check_effects(case["expected_outputs"]) def get_test_cases(self): """List test cases for the license editing form.""" return { "from blank to license 1, no preference, no udpate of preferences": { "preconditions": { "content_license": None, "preferred_license": None }, "inputs": { "license": self.license_1, "update_preferred_license": False }, "expected_outputs": { "content_license": self.license_1, "preferred_license": None }, }, "from blank to license 1, no preference, udpate of preferences": { "preconditions": { "content_license": None, "preferred_license": None }, "inputs": { "license": self.license_1, "update_preferred_license": True }, "expected_outputs": { "content_license": self.license_1, "preferred_license": self.license_1 }, }, "from blank to license 2, no preference, no udpate of preferences": { "preconditions": { "content_license": None, "preferred_license": None }, "inputs": { "license": self.license_2, "update_preferred_license": False }, "expected_outputs": { "content_license": self.license_2, "preferred_license": None }, }, "from blank to license 2, no preference, udpate of preferences": { "preconditions": { "content_license": None, "preferred_license": None }, "inputs": { "license": self.license_2, "update_preferred_license": True }, "expected_outputs": { "content_license": self.license_2, "preferred_license": self.license_2 }, }, "from blank to license 1, preference, no udpate of preferences": { "preconditions": { "content_license": None, "preferred_license": self.license_2 }, "inputs": { "license": self.license_1, "update_preferred_license": False }, "expected_outputs": { "content_license": self.license_1, "preferred_license": self.license_2 }, }, "from blank to license 1, preference, udpate of preferences": { "preconditions": { "content_license": None, "preferred_license": self.license_2 }, "inputs": { "license": self.license_1, "update_preferred_license": True }, "expected_outputs": { "content_license": self.license_1, "preferred_license": self.license_1 }, }, "from license 1 to license 2, no preference, no udpate of preferences": { "preconditions": { "content_license": self.license_1, "preferred_license": None }, "inputs": { "license": self.license_2, "update_preferred_license": False }, "expected_outputs": { "content_license": self.license_2, "preferred_license": None }, }, "from license 1 to license 2, no preference, udpate of preferences": { "preconditions": { "content_license": self.license_1, "preferred_license": None }, "inputs": { "license": self.license_2, "update_preferred_license": True }, "expected_outputs": { "content_license": self.license_2, "preferred_license": self.license_2 }, }, } def enforce_preconditions(self, preconditions): """Prepare the test environment to match given preconditions""" # Enforce preconditions for license in database self.content.licence = preconditions["content_license"] self.content.save() self.assertEqual(self.content.licence, preconditions["content_license"]) # Enforce preconditions for license in repository versioned = self.content.load_version() versioned.licence = preconditions["content_license"] sha = versioned.repo_update_top_container("Title", self.content.slug, "introduction", "conclusion") updated_versioned = self.content.load_version(sha) self.assertEqual(updated_versioned.licence, preconditions["content_license"]) # Enforce preconditions for preferred license self.author.licence = preconditions["preferred_license"] self.author.save() updated_profile = Profile.objects.get(pk=self.author.pk) self.assertEqual(updated_profile.licence, preconditions["preferred_license"]) def post_form(self, inputs): """Post the form with given inputs.""" form_data = { "license": inputs["license"].pk, "update_preferred_license": inputs["update_preferred_license"] } self.client.post(self.form_url, form_data) def check_effects(self, expected_outputs): """Check the effects of having sent the form.""" # Check updating of the database updated_content = PublishableContent.objects.get(pk=self.content.pk) updated_profile = Profile.objects.get(pk=self.author.pk) self.assertEqual(updated_content.licence, expected_outputs["content_license"]) self.assertEqual(updated_profile.licence, expected_outputs["preferred_license"]) # Check updating of the repository versioned = updated_content.load_version() self.assertEqual(versioned.licence, expected_outputs["content_license"])