Exemplo n.º 1
0
    def setUp(self):
        self.user1 = ProfileFactory().user
        self.user2 = ProfileFactory().user

        self.category1 = ForumCategoryFactory(position=1)
        self.forum11 = ForumFactory(category=self.category1, position_in_category=1)
        self.forum12 = ForumFactory(category=self.category1, position_in_category=2)

        self.tag1 = TagFactory(title="Linux")
        self.tag2 = TagFactory(title="Windows")

        self.client.force_login(self.user1)
Exemplo n.º 2
0
 def setUp(self):
     self.user1 = ProfileFactory().user
     self.user2 = ProfileFactory().user
     self.to_be_changed_staff = StaffProfileFactory().user
     self.staff = StaffProfileFactory().user
     self.assertTrue(self.staff.has_perm("forum.change_topic"))
     self.category1 = ForumCategoryFactory(position=1)
     self.forum11 = ForumFactory(category=self.category1,
                                 position_in_category=1)
     self.forum12 = ForumFactory(category=self.category1,
                                 position_in_category=2)
     for group in self.staff.groups.all():
         self.forum12.groups.add(group)
     self.forum12.save()
Exemplo n.º 3
0
    def test_subscription_deactivated_and_notification_read_when_topic_moved(self):
        """
        When a topic is moved to a forum where subscribers can't read it, the subscriptions
        should be deactivated and notifications marked as read.
        """
        topic = TopicFactory(forum=self.forum11, author=self.user1)
        PostFactory(topic=topic, author=self.user1, position=1)
        other_user = ProfileFactory().user
        TopicAnswerSubscription.objects.toggle_follow(topic, other_user)
        PostFactory(topic=topic, author=ProfileFactory().user, position=2)

        self.assertIsNotNone(TopicAnswerSubscription.objects.get_existing(self.user1, topic, is_active=True))
        self.assertIsNotNone(Notification.objects.get(subscription__user=self.user1, is_read=False))

        forum_not_read = ForumFactory(category=self.category1, position_in_category=2)
        forum_not_read.groups.add(Group.objects.create(name="DummyGroup_1"))

        self.client.force_login(StaffProfileFactory().user)
        data = {"move": "", "forum": forum_not_read.pk, "topic": topic.pk}
        response = self.client.post(reverse("topic-edit"), data, follow=False)

        self.assertEqual(302, response.status_code)
        self.assertIsNotNone(TopicAnswerSubscription.objects.get_existing(self.user1, topic, is_active=False))
        self.assertIsNotNone(Notification.objects.get(subscription__user=self.user1, is_read=True))
        self.assertFalse(TopicAnswerSubscription.objects.get_existing(other_user, topic).is_active)
        self.assertIsNotNone(Notification.objects.get(subscription__user=other_user, is_read=True))
Exemplo n.º 4
0
    def setUp(self):
        # Create some forum's category
        self.category1 = ForumCategoryFactory(position=1)
        self.category2 = ForumCategoryFactory(position=2)

        # Create forum
        self.forum11 = ForumFactory(category=self.category1,
                                    position_in_category=1)

        # Only for staff
        self.staff1 = StaffProfileFactory()

        self.forum12 = ForumFactory(category=self.category2,
                                    position_in_category=2)
        self.forum12.groups.add(Group.objects.filter(name="staff").first())
        self.forum12.save()
Exemplo n.º 5
0
    def setUp(self):
        self.overridden_zds_app = overridden_zds_app
        # don't build PDF to speed up the tests
        overridden_zds_app["content"]["build_pdf_when_published"] = False

        self.staff = StaffProfileFactory().user

        settings.EMAIL_BACKEND = "django.core.mail.backends.locmem.EmailBackend"
        self.mas = ProfileFactory().user
        overridden_zds_app["member"]["bot_account"] = self.mas.username

        bot = Group(name=overridden_zds_app["member"]["bot_group"])
        bot.save()
        self.external = UserFactory(
            username=overridden_zds_app["member"]["external_account"],
            password="******")

        self.beta_forum = ForumFactory(
            pk=overridden_zds_app["forum"]["beta_forum_id"],
            category=ForumCategoryFactory(position=1),
            position_in_category=1,
        )  # ensure that the forum, for the beta versions, is created

        self.licence = LicenceFactory()
        self.subcategory = SubCategoryFactory()
        self.tag = TagFactory()

        self.user_author = ProfileFactory().user
        self.user_staff = StaffProfileFactory().user
        self.user_guest = ProfileFactory().user

        # create an article
        self.article = PublishableContentFactory(type="ARTICLE")
        self.article.authors.add(self.user_author)
        UserGalleryFactory(gallery=self.article.gallery,
                           user=self.user_author,
                           mode="W")
        self.article.licence = self.licence
        self.article.subcategory.add(self.subcategory)
        self.article.tags.add(self.tag)
        self.article.save()

        # fill it with one extract
        self.article_draft = self.article.load_version()
        self.extract1 = ExtractFactory(container=self.article_draft,
                                       db_object=self.article)

        # then, publish it !
        version = self.article_draft.current_version
        self.published = publish_content(self.article,
                                         self.article_draft,
                                         is_major_update=True)

        self.article.sha_public = version
        self.article.sha_draft = version
        self.article.public_version = self.published
        self.article.save()

        self.articlefeed = LastArticlesFeedRSS()
Exemplo n.º 6
0
    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)
Exemplo n.º 7
0
    def test_no_duplicate_subscription(self):
        """
        Creating two same subscriptions is rejected by the database.
        """
        category = ForumCategoryFactory(position=1)
        forum = ForumFactory(category=category, position_in_category=1)
        topic = TopicFactory(forum=forum, author=self.user1)
        TopicAnswerSubscription.objects.toggle_follow(topic, self.user1, True)

        subscription = TopicAnswerSubscription(user=self.user1, content_object=topic)
        with self.assertRaises(IntegrityError):
            subscription.save()
Exemplo n.º 8
0
    def setUp(self):
        # prepare a user and 2 Topic (with and without tags)

        settings.EMAIL_BACKEND = "django.core.mail.backends.locmem.EmailBackend"

        self.category1 = ForumCategoryFactory(position=1)
        self.forum = ForumFactory(category=self.category1,
                                  position_in_category=1)
        self.forum2 = ForumFactory(category=self.category1,
                                   position_in_category=2)

        self.user = ProfileFactory().user
        self.client.force_login(self.user)

        self.tag = TagFactory()
        self.topic1 = TopicFactory(forum=self.forum, author=self.user)
        self.topic2 = TopicFactory(forum=self.forum2, author=self.user)
        self.topic2.tags.add(self.tag)
        self.topic2.save()

        self.topicfeed = LastTopicsFeedRSS()
Exemplo n.º 9
0
    def setUp(self):
        settings.EMAIL_BACKEND = "django.core.mail.backends.locmem.EmailBackend"
        self.mas = ProfileFactory()
        settings.ZDS_APP["member"]["bot_account"] = self.mas.user.username
        self.anonymous = UserFactory(username=settings.ZDS_APP["member"]["anonymous_account"], password="******")
        self.external = UserFactory(username=settings.ZDS_APP["member"]["external_account"], password="******")
        self.category1 = ForumCategoryFactory(position=1)
        self.forum11 = ForumFactory(category=self.category1, position_in_category=1)
        self.staff = StaffProfileFactory().user

        self.bot = Group(name=settings.ZDS_APP["member"]["bot_group"])
        self.bot.save()
Exemplo n.º 10
0
def load_forums(cli, size, fake, *_, **__):
    """
    Load forums
    """
    nb_forums = size * 8
    cli.stdout.write(f"Nombres de Forums à créer : {nb_forums}")
    tps1 = time.time()
    nb_categories = ForumCategory.objects.count()
    if nb_categories == 0:
        cli.stdout.write(
            "Il n'y a aucune catgorie actuellement. "
            "Vous devez rajouter les categories de forum dans vos fixtures (category_forum)"
        )
    else:
        categories = list(ForumCategory.objects.all())
        for i in range(0, nb_forums):
            with contextlib.suppress(IntegrityError):
                forum = ForumFactory(
                    category=categories[i % nb_categories], position_in_category=(i / nb_categories) + 1
                )
                forum.title = fake.word()
                forum.subtitle = fake.sentence(nb_words=15, variable_nb_words=True)
                forum.save()
            sys.stdout.write(f" Forum {i + 1}/{nb_forums}  \r")
            sys.stdout.flush()
        tps2 = time.time()
        cli.stdout.write(f"\nFait en {tps2 - tps1} sec")
Exemplo n.º 11
0
    def setUp(self):
        # prepare a user and 2 Topic (with and without tags)

        settings.EMAIL_BACKEND = "django.core.mail.backends.locmem.EmailBackend"

        self.category1 = ForumCategoryFactory(position=1)
        self.forum = ForumFactory(category=self.category1,
                                  position_in_category=1)
        self.forum2 = ForumFactory(category=self.category1,
                                   position_in_category=2)
        self.forum3 = ForumFactory(category=self.category1,
                                   position_in_category=3)

        self.user = ProfileFactory().user
        self.client.force_login(self.user)

        self.tag = TagFactory()
        self.topic1 = TopicFactory(forum=self.forum, author=self.user)
        self.topic2 = TopicFactory(forum=self.forum2, author=self.user)
        self.topic2.tags.add(self.tag)
        self.topic2.save()

        # create 2 posts un each forum
        PostFactory(topic=self.topic1, author=self.user, position=1)
        PostFactory(topic=self.topic1, author=self.user, position=2)
        PostFactory(topic=self.topic2, author=self.user, position=1)
        PostFactory(topic=self.topic2, author=self.user, position=2)

        # and last topic + post alone
        self.tag2 = TagFactory()
        self.topic3 = TopicFactory(forum=self.forum3, author=self.user)
        self.post3 = PostFactory(topic=self.topic3,
                                 author=self.user,
                                 position=1)
        self.topic3.tags.add(self.tag2)
        self.topic3.save()

        self.postfeed = LastPostsFeedRSS()
Exemplo n.º 12
0
 def test_success_initial_content_topic(self):
     author = ProfileFactory().user
     category = ForumCategoryFactory(position=1)
     forum = ForumFactory(category=category, position_in_category=1)
     topic = TopicFactory(forum=forum, author=author)
     staff = StaffProfileFactory()
     self.client.force_login(staff.user)
     response = self.client.get(
         "{}?content_type=topic&content_id={}".format(reverse("featured-resource-create"), topic.id)
     )
     initial_dict = response.context["form"].initial
     self.assertEqual(initial_dict["title"], topic.title)
     self.assertEqual(initial_dict["authors"], str(author))
     self.assertEqual(initial_dict["type"], _("Un sujet"))
     self.assertEqual(initial_dict["url"], f"http://testserver{topic.get_absolute_url()}")
Exemplo n.º 13
0
    def test_update(self):
        # create topic and content and toggle request
        author = ProfileFactory().user
        category = ForumCategoryFactory(position=1)
        forum = ForumFactory(category=category, position_in_category=1)
        topic = TopicFactory(forum=forum, author=author)

        FeaturedRequested.objects.toogle_request(topic, author)

        # ignore
        staff = StaffProfileFactory()
        self.client.force_login(staff.user)

        content_type = ContentType.objects.get_for_model(topic)
        q = FeaturedRequested.objects.get(object_id=topic.pk, content_type__pk=content_type.pk)
        self.assertFalse(q.rejected)

        response = self.client.post(
            reverse("featured-resource-request-update", kwargs={"pk": q.pk}), {"operation": "REJECT"}, follow=False
        )
        self.assertEqual(200, response.status_code)

        q = FeaturedRequested.objects.get(pk=q.pk)
        self.assertTrue(q.rejected)
        self.assertFalse(q.rejected_for_good)

        response = self.client.post(
            reverse("featured-resource-request-update", kwargs={"pk": q.pk}), {"operation": "CONSIDER"}, follow=False
        )
        self.assertEqual(200, response.status_code)

        q = FeaturedRequested.objects.get(pk=q.pk)
        self.assertFalse(q.rejected)

        response = self.client.post(
            reverse("featured-resource-request-update", kwargs={"pk": q.pk}),
            {"operation": "REJECT_FOR_GOOD"},
            follow=False,
        )
        self.assertEqual(200, response.status_code)

        q = FeaturedRequested.objects.get(pk=q.pk)
        self.assertTrue(q.rejected)
        self.assertTrue(q.rejected_for_good)
Exemplo n.º 14
0
    def test_mark_all_notifications_as_read_when_toggle_follow(self):
        """
        When a user unsubscribes from a content, we mark all notifications for
        this content as read.
        """
        category = ForumCategoryFactory(position=1)
        forum = ForumFactory(category=category, position_in_category=1)
        topic = TopicFactory(forum=forum, author=self.user1)
        PostFactory(topic=topic, author=self.user1, position=1)
        PostFactory(topic=topic, author=self.user2, position=2)

        notifications = Notification.objects.get_unread_notifications_of(self.user1)
        self.assertEqual(1, len(notifications))
        self.assertIsNotNone(notifications.first())
        self.assertEqual(topic.last_message, notifications.first().content_object)

        TopicAnswerSubscription.objects.toggle_follow(topic, self.user1)

        self.assertEqual(0, len(Notification.objects.get_unread_notifications_of(self.user1)))
Exemplo n.º 15
0
    def setUp(self):
        self.staff = StaffProfileFactory().user

        settings.EMAIL_BACKEND = "django.core.mail.backends.locmem.EmailBackend"
        self.mas = ProfileFactory().user
        self.overridden_zds_app["member"]["bot_account"] = self.mas.username

        self.licence = LicenceFactory()
        self.subcategory = SubCategoryFactory()

        self.user_author = ProfileFactory().user
        self.user_staff = StaffProfileFactory().user
        self.user_guest = ProfileFactory().user

        self.tuto = PublishableContentFactory(type="TUTORIAL")
        self.tuto.authors.add(self.user_author)
        UserGalleryFactory(gallery=self.tuto.gallery,
                           user=self.user_author,
                           mode="W")
        self.tuto.licence = self.licence
        self.tuto.subcategory.add(self.subcategory)
        self.tuto.save()

        self.beta_forum = ForumFactory(
            pk=self.overridden_zds_app["forum"]["beta_forum_id"],
            category=ForumCategoryFactory(position=1),
            position_in_category=1,
        )  # ensure that the forum, for the beta versions, is created

        self.tuto_draft = self.tuto.load_version()
        self.part1 = ContainerFactory(parent=self.tuto_draft,
                                      db_object=self.tuto)
        self.chapter1 = ContainerFactory(parent=self.part1,
                                         db_object=self.tuto)

        self.extract1 = ExtractFactory(container=self.chapter1,
                                       db_object=self.tuto)
        bot = Group(name=self.overridden_zds_app["member"]["bot_group"])
        bot.save()
        self.external = UserFactory(
            username=self.overridden_zds_app["member"]["external_account"],
            password="******")
Exemplo n.º 16
0
    def test_mark_notifications_as_read(self):
        category = ForumCategoryFactory(position=1)
        forum = ForumFactory(category=category, position_in_category=1)
        topic = TopicFactory(forum=forum, author=self.user1)
        PostFactory(topic=topic, author=self.user1, position=1)
        PostFactory(topic=topic, author=self.user2, position=2)

        self.client.force_login(self.user1)

        notifications = Notification.objects.get_unread_notifications_of(self.user1)
        self.assertEqual(1, len(notifications))

        self.assertFalse(topic.is_read)

        result = self.client.post(reverse("mark-notifications-as-read"), follow=False)
        self.assertEqual(result.status_code, 302)

        notifications = Notification.objects.get_unread_notifications_of(self.user1)
        self.assertEqual(0, len(notifications))

        self.assertTrue(Topic.objects.get(pk=topic.pk).is_read)
Exemplo n.º 17
0
    def setUp(self):
        self.staff = StaffProfileFactory()
        self.dummy_author = ProfileFactory()

        self.category = ForumCategoryFactory(position=1)
        self.forum = ForumFactory(category=self.category,
                                  position_in_category=1)
        self.topic = TopicFactory(forum=self.forum,
                                  author=self.dummy_author.user)
        self.post = PostFactory(topic=self.topic,
                                author=self.dummy_author.user,
                                position=1)

        self.alerts = []
        for i in range(20):
            alert = Alert(
                author=self.dummy_author.user,
                comment=self.post,
                scope="FORUM",
                text=f"pouet-{i}",
                pubdate=(datetime.now() + timedelta(minutes=i)),
            )
            alert.save()
            self.alerts.append(alert)
Exemplo n.º 18
0
    def test_promote_interface(self):
        """
        Test promotion interface.
        """

        # create users (one regular, one staff and one superuser)
        tester = ProfileFactory()
        staff = StaffProfileFactory()
        tester.user.is_active = False
        tester.user.save()
        staff.user.is_superuser = True
        staff.user.save()

        # create groups
        group = Group.objects.create(name="DummyGroup_1")
        groupbis = Group.objects.create(name="DummyGroup_2")

        # create Forums, Posts and subscribe member to them.
        category1 = ForumCategoryFactory(position=1)
        forum1 = ForumFactory(category=category1, position_in_category=1)
        forum1.groups.add(group)
        forum1.save()
        forum2 = ForumFactory(category=category1, position_in_category=2)
        forum2.groups.add(groupbis)
        forum2.save()
        forum3 = ForumFactory(category=category1, position_in_category=3)
        topic1 = TopicFactory(forum=forum1, author=staff.user)
        topic2 = TopicFactory(forum=forum2, author=staff.user)
        topic3 = TopicFactory(forum=forum3, author=staff.user)

        # LET THE TEST BEGIN !

        # tester shouldn't be able to connect
        login_check = self.client.login(username=tester.user.username,
                                        password="******")
        self.assertEqual(login_check, False)

        # connect as staff (superuser)
        self.client.force_login(staff.user)

        # check that we can go through the page
        result = self.client.get(reverse("member-settings-promote",
                                         kwargs={"user_pk": tester.user.id}),
                                 follow=False)
        self.assertEqual(result.status_code, 200)

        # give groups thanks to staff (but account still not activated)
        result = self.client.post(
            reverse("member-settings-promote",
                    kwargs={"user_pk": tester.user.id}),
            {
                "groups": [group.id, groupbis.id],
            },
            follow=False,
        )
        self.assertEqual(result.status_code, 302)
        tester = Profile.objects.get(id=tester.id)  # refresh

        self.assertEqual(len(tester.user.groups.all()), 2)
        self.assertFalse(tester.user.is_active)

        # Now our tester is going to follow one post in every forum (3)
        TopicAnswerSubscription.objects.toggle_follow(topic1, tester.user)
        TopicAnswerSubscription.objects.toggle_follow(topic2, tester.user)
        TopicAnswerSubscription.objects.toggle_follow(topic3, tester.user)

        self.assertEqual(
            len(
                TopicAnswerSubscription.objects.get_objects_followed_by(
                    tester.user)), 3)

        # retract all right, keep one group only and activate account
        result = self.client.post(
            reverse("member-settings-promote",
                    kwargs={"user_pk": tester.user.id}),
            {
                "groups": [group.id],
                "activation": "on"
            },
            follow=False,
        )
        self.assertEqual(result.status_code, 302)
        tester = Profile.objects.get(id=tester.id)  # refresh

        self.assertEqual(len(tester.user.groups.all()), 1)
        self.assertTrue(tester.user.is_active)
        self.assertEqual(
            len(
                TopicAnswerSubscription.objects.get_objects_followed_by(
                    tester.user)), 2)

        # no groups specified
        result = self.client.post(reverse("member-settings-promote",
                                          kwargs={"user_pk": tester.user.id}),
                                  {"activation": "on"},
                                  follow=False)
        self.assertEqual(result.status_code, 302)
        tester = Profile.objects.get(id=tester.id)  # refresh
        self.assertEqual(
            len(
                TopicAnswerSubscription.objects.get_objects_followed_by(
                    tester.user)), 1)

        # Finally, check that user can connect and can not access the interface
        login_check = self.client.login(username=tester.user.username,
                                        password="******")
        self.assertEqual(login_check, True)
        result = self.client.post(reverse("member-settings-promote",
                                          kwargs={"user_pk": staff.user.id}),
                                  {"activation": "on"},
                                  follow=False)
        self.assertEqual(result.status_code, 403)  # forbidden !
Exemplo n.º 19
0
    def test_filters(self):
        # create topic and content and toggle request
        author = ProfileFactory().user
        category = ForumCategoryFactory(position=1)
        forum = ForumFactory(category=category, position_in_category=1)
        topic = TopicFactory(forum=forum, author=author)

        FeaturedRequested.objects.toogle_request(topic, author)

        tutorial = PublishedContentFactory(author_list=[author])
        gallery = GalleryFactory()
        image = ImageFactory(gallery=gallery)
        tutorial.image = image
        tutorial.save()

        FeaturedRequested.objects.toogle_request(tutorial, author)

        # without filter
        staff = StaffProfileFactory()
        self.client.force_login(staff.user)

        response = self.client.get(reverse("featured-resource-requests"))
        self.assertEqual(200, response.status_code)

        self.assertEqual(len(response.context["featured_request_list"]), 2)
        self.assertTrue(any(r.content_object == topic for r in response.context["featured_request_list"]))
        self.assertTrue(any(r.content_object == tutorial for r in response.context["featured_request_list"]))

        # filter topic
        response = self.client.get(reverse("featured-resource-requests") + "?type=topic")
        self.assertEqual(200, response.status_code)

        self.assertEqual(len(response.context["featured_request_list"]), 1)
        self.assertTrue(any(r.content_object == topic for r in response.context["featured_request_list"]))
        self.assertFalse(any(r.content_object == tutorial for r in response.context["featured_request_list"]))

        # filter tuto
        response = self.client.get(reverse("featured-resource-requests") + "?type=content")
        self.assertEqual(200, response.status_code)

        self.assertEqual(len(response.context["featured_request_list"]), 1)
        self.assertFalse(any(r.content_object == topic for r in response.context["featured_request_list"]))
        self.assertTrue(any(r.content_object == tutorial for r in response.context["featured_request_list"]))

        # reject topic
        content_type = ContentType.objects.get_for_model(topic)
        q = FeaturedRequested.objects.get(object_id=topic.pk, content_type__pk=content_type.pk)
        q.rejected = True
        q.save()

        response = self.client.get(reverse("featured-resource-requests") + "?type=topic")
        self.assertEqual(200, response.status_code)

        self.assertEqual(len(response.context["featured_request_list"]), 0)

        # filter ignored
        response = self.client.get(reverse("featured-resource-requests") + "?type=ignored")
        self.assertEqual(200, response.status_code)

        self.assertEqual(len(response.context["featured_request_list"]), 1)
        self.assertTrue(any(r.content_object == topic for r in response.context["featured_request_list"]))

        # put back vote count to 0 for tutorial
        FeaturedRequested.objects.toogle_request(tutorial, author)
        response = self.client.get(reverse("featured-resource-requests") + "?type=content")
        self.assertEqual(200, response.status_code)

        self.assertEqual(len(response.context["featured_request_list"]), 0)  # does not appear with no votes

        # upvote topic
        other = ProfileFactory().user
        FeaturedRequested.objects.toogle_request(topic, other)

        response = self.client.get(reverse("featured-resource-requests") + "?type=topic")
        self.assertEqual(200, response.status_code)

        self.assertEqual(len(response.context["featured_request_list"]), 1)  # it is back!
Exemplo n.º 20
0
    def test_unregister(self):
        """
        To test that unregistering user is working.
        """

        # test not logged user can't unregister.
        self.client.logout()
        result = self.client.post(reverse("member-unregister"), follow=False)
        self.assertEqual(result.status_code, 302)

        # test logged user can unregister.
        user = ProfileFactory()
        self.client.force_login(user.user)
        result = self.client.post(reverse("member-unregister"), follow=False)
        self.assertEqual(result.status_code, 302)
        self.assertEqual(User.objects.filter(username=user.user.username).count(), 0)

        # Attach a user at tutorials, articles, topics and private topics. After that,
        # unregister this user and check that he is well removed in all contents.
        user = ProfileFactory()
        user2 = ProfileFactory()
        alone_gallery = GalleryFactory()
        UserGalleryFactory(gallery=alone_gallery, user=user.user)
        shared_gallery = GalleryFactory()
        UserGalleryFactory(gallery=shared_gallery, user=user.user)
        UserGalleryFactory(gallery=shared_gallery, user=user2.user)
        # first case : a published tutorial with only one author
        published_tutorial_alone = PublishedContentFactory(type="TUTORIAL")
        published_tutorial_alone.authors.add(user.user)
        published_tutorial_alone.save()
        # second case : a published tutorial with two authors
        published_tutorial_2 = PublishedContentFactory(type="TUTORIAL")
        published_tutorial_2.authors.add(user.user)
        published_tutorial_2.authors.add(user2.user)
        published_tutorial_2.save()
        # third case : a private tutorial with only one author
        writing_tutorial_alone = PublishableContentFactory(type="TUTORIAL")
        writing_tutorial_alone.authors.add(user.user)
        writing_tutorial_alone.save()
        writing_tutorial_alone_galler_path = writing_tutorial_alone.gallery.get_gallery_path()
        # fourth case : a private tutorial with at least two authors
        writing_tutorial_2 = PublishableContentFactory(type="TUTORIAL")
        writing_tutorial_2.authors.add(user.user)
        writing_tutorial_2.authors.add(user2.user)
        writing_tutorial_2.save()
        self.client.force_login(self.staff)
        # same thing for articles
        published_article_alone = PublishedContentFactory(type="ARTICLE")
        published_article_alone.authors.add(user.user)
        published_article_alone.save()
        published_article_2 = PublishedContentFactory(type="ARTICLE")
        published_article_2.authors.add(user.user)
        published_article_2.authors.add(user2.user)
        published_article_2.save()
        writing_article_alone = PublishableContentFactory(type="ARTICLE")
        writing_article_alone.authors.add(user.user)
        writing_article_alone.save()
        writing_article_2 = PublishableContentFactory(type="ARTICLE")
        writing_article_2.authors.add(user.user)
        writing_article_2.authors.add(user2.user)
        writing_article_2.save()
        # beta content
        beta_forum = ForumFactory(category=ForumCategoryFactory())
        beta_content = BetaContentFactory(author_list=[user.user], forum=beta_forum)
        beta_content_2 = BetaContentFactory(author_list=[user.user, user2.user], forum=beta_forum)
        # about posts and topics
        authored_topic = TopicFactory(author=user.user, forum=self.forum11, solved_by=user.user)
        answered_topic = TopicFactory(author=user2.user, forum=self.forum11)
        PostFactory(topic=answered_topic, author=user.user, position=2)
        edited_answer = PostFactory(topic=answered_topic, author=user.user, position=3)
        edited_answer.editor = user.user
        edited_answer.save()

        upvoted_answer = PostFactory(topic=answered_topic, author=user2.user, position=4)
        upvoted_answer.like += 1
        upvoted_answer.save()
        CommentVote.objects.create(user=user.user, comment=upvoted_answer, positive=True)

        private_topic = PrivateTopicFactory(author=user.user)
        private_topic.participants.add(user2.user)
        private_topic.save()
        PrivatePostFactory(author=user.user, privatetopic=private_topic, position_in_topic=1)

        # add API key
        self.assertEqual(Application.objects.count(), 0)
        self.assertEqual(AccessToken.objects.count(), 0)
        api_application = Application()
        api_application.client_id = "foobar"
        api_application.user = user.user
        api_application.client_type = "confidential"
        api_application.authorization_grant_type = "password"
        api_application.client_secret = "42"
        api_application.save()
        token = AccessToken()
        token.user = user.user
        token.token = "r@d0m"
        token.application = api_application
        token.expires = datetime.now()
        token.save()
        self.assertEqual(Application.objects.count(), 1)
        self.assertEqual(AccessToken.objects.count(), 1)

        # add a karma note and a sanction with this user
        note = KarmaNote(moderator=user.user, user=user2.user, note="Good!", karma=5)
        note.save()
        ban = Ban(moderator=user.user, user=user2.user, type="Ban définitif", note="Test")
        ban.save()

        # login and unregister:
        self.client.force_login(user.user)
        result = self.client.post(reverse("member-unregister"), follow=False)
        self.assertEqual(result.status_code, 302)

        # check that the bot have taken authorship of tutorial:
        self.assertEqual(published_tutorial_alone.authors.count(), 1)
        self.assertEqual(
            published_tutorial_alone.authors.first().username, settings.ZDS_APP["member"]["external_account"]
        )
        self.assertFalse(os.path.exists(writing_tutorial_alone_galler_path))
        self.assertEqual(published_tutorial_2.authors.count(), 1)
        self.assertEqual(
            published_tutorial_2.authors.filter(username=settings.ZDS_APP["member"]["external_account"]).count(), 0
        )

        # check that published tutorials remain published and accessible
        self.assertIsNotNone(published_tutorial_2.public_version.get_prod_path())
        self.assertTrue(os.path.exists(published_tutorial_2.public_version.get_prod_path()))
        self.assertIsNotNone(published_tutorial_alone.public_version.get_prod_path())
        self.assertTrue(os.path.exists(published_tutorial_alone.public_version.get_prod_path()))
        self.assertEqual(
            self.client.get(
                reverse("tutorial:view", args=[published_tutorial_alone.pk, published_tutorial_alone.slug]),
                follow=False,
            ).status_code,
            200,
        )
        self.assertEqual(
            self.client.get(
                reverse("tutorial:view", args=[published_tutorial_2.pk, published_tutorial_2.slug]), follow=False
            ).status_code,
            200,
        )

        # test that published articles remain accessible
        self.assertTrue(os.path.exists(published_article_alone.public_version.get_prod_path()))
        self.assertEqual(
            self.client.get(
                reverse("article:view", args=[published_article_alone.pk, published_article_alone.slug]), follow=True
            ).status_code,
            200,
        )
        self.assertEqual(
            self.client.get(
                reverse("article:view", args=[published_article_2.pk, published_article_2.slug]), follow=True
            ).status_code,
            200,
        )

        # check that the tutorial for which the author was alone does not exists anymore
        self.assertEqual(PublishableContent.objects.filter(pk=writing_tutorial_alone.pk).count(), 0)
        self.assertFalse(os.path.exists(writing_tutorial_alone.get_repo_path()))

        # check that bot haven't take the authorship of the tuto with more than one author
        self.assertEqual(writing_tutorial_2.authors.count(), 1)
        self.assertEqual(
            writing_tutorial_2.authors.filter(username=settings.ZDS_APP["member"]["external_account"]).count(), 0
        )

        # authorship for the article for which user was the only author
        self.assertEqual(published_article_alone.authors.count(), 1)
        self.assertEqual(
            published_article_alone.authors.first().username, settings.ZDS_APP["member"]["external_account"]
        )
        self.assertEqual(published_article_2.authors.count(), 1)

        self.assertEqual(PublishableContent.objects.filter(pk=writing_article_alone.pk).count(), 0)
        self.assertFalse(os.path.exists(writing_article_alone.get_repo_path()))

        # not bot if another author:
        self.assertEqual(
            published_article_2.authors.filter(username=settings.ZDS_APP["member"]["external_account"]).count(), 0
        )
        self.assertEqual(writing_article_2.authors.count(), 1)
        self.assertEqual(
            writing_article_2.authors.filter(username=settings.ZDS_APP["member"]["external_account"]).count(), 0
        )

        # topics, gallery and PMs:
        self.assertEqual(Topic.objects.filter(author__username=user.user.username).count(), 0)
        self.assertEqual(Topic.objects.filter(solved_by=user.user).count(), 0)
        self.assertEqual(Topic.objects.filter(solved_by=self.anonymous).count(), 1)
        self.assertEqual(Post.objects.filter(author__username=user.user.username).count(), 0)
        self.assertEqual(Post.objects.filter(editor__username=user.user.username).count(), 0)
        self.assertEqual(PrivatePost.objects.filter(author__username=user.user.username).count(), 0)
        self.assertEqual(PrivateTopic.objects.filter(author__username=user.user.username).count(), 0)

        self.assertIsNotNone(Topic.objects.get(pk=authored_topic.pk))
        self.assertIsNotNone(PrivateTopic.objects.get(pk=private_topic.pk))
        self.assertIsNotNone(Gallery.objects.get(pk=alone_gallery.pk))
        self.assertEqual(alone_gallery.get_linked_users().count(), 1)
        self.assertEqual(shared_gallery.get_linked_users().count(), 1)
        self.assertEqual(UserGallery.objects.filter(user=user.user).count(), 0)
        self.assertEqual(CommentVote.objects.filter(user=user.user, positive=True).count(), 0)
        self.assertEqual(Post.objects.filter(pk=upvoted_answer.id).first().like, 0)

        # zep 12, published contents and beta
        self.assertIsNotNone(PublishedContent.objects.filter(content__pk=published_tutorial_alone.pk).first())
        self.assertIsNotNone(PublishedContent.objects.filter(content__pk=published_tutorial_2.pk).first())
        self.assertTrue(Topic.objects.get(pk=beta_content.beta_topic.pk).is_locked)
        self.assertFalse(Topic.objects.get(pk=beta_content_2.beta_topic.pk).is_locked)

        # check API
        self.assertEqual(Application.objects.count(), 0)
        self.assertEqual(AccessToken.objects.count(), 0)

        # check that the karma note and the sanction were kept
        self.assertTrue(KarmaNote.objects.filter(pk=note.pk).exists())
        self.assertTrue(Ban.objects.filter(pk=ban.pk).exists())
Exemplo n.º 21
0
    def test_toggle(self):
        author = ProfileFactory()
        self.client.force_login(author.user)

        # create topic and toggle request
        category = ForumCategoryFactory(position=1)
        forum = ForumFactory(category=category, position_in_category=1)
        topic = TopicFactory(forum=forum, author=author.user)

        response = self.client.post(
            reverse("topic-edit") + f"?topic={topic.pk}",
            {"request_featured": 1},
            HTTP_X_REQUESTED_WITH="XMLHttpRequest",
        )
        self.assertEqual(200, response.status_code)

        self.assertEqual(FeaturedRequested.objects.count(), 1)
        r = FeaturedRequested.objects.last()
        self.assertEqual(r.content_object, topic)
        self.assertIn(author.user, r.users_voted.all())

        # lock topic: cannot vote anymore
        topic.is_locked = True
        topic.save()

        response = self.client.post(
            reverse("topic-edit") + f"?topic={topic.pk}",
            {"request_featured": 1},
            HTTP_X_REQUESTED_WITH="XMLHttpRequest",
        )
        self.assertEqual(403, response.status_code)
        self.assertEqual(FeaturedRequested.objects.count(), 1)

        # create tutorial and toggle request
        tutorial = PublishedContentFactory(author_list=[author.user])
        gallery = GalleryFactory()
        image = ImageFactory(gallery=gallery)
        tutorial.image = image
        tutorial.save()

        response = self.client.post(
            reverse("content:request-featured", kwargs={"pk": tutorial.pk}),
            {"request_featured": 1},
            HTTP_X_REQUESTED_WITH="XMLHttpRequest",
        )
        self.assertEqual(200, response.status_code)

        self.assertEqual(FeaturedRequested.objects.count(), 2)
        r = FeaturedRequested.objects.last()
        self.assertEqual(r.content_object, tutorial)
        self.assertIn(author.user, r.users_voted.all())

        # create opinion: cannot toggle request!
        opinion = PublishedContentFactory(type="OPINION", author_list=[author.user])
        gallery = GalleryFactory()
        image = ImageFactory(gallery=gallery)
        opinion.image = image
        opinion.save()

        response = self.client.post(
            reverse("content:request-featured", kwargs={"pk": opinion.pk}),
            {"request_featured": 1},
            HTTP_X_REQUESTED_WITH="XMLHttpRequest",
        )
        self.assertEqual(403, response.status_code)
        self.assertEqual(FeaturedRequested.objects.count(), 2)

        # set tutorial as obsolete: cannot toggle
        tutorial.is_obsolete = True
        tutorial.save()

        response = self.client.post(
            reverse("content:request-featured", kwargs={"pk": tutorial.pk}),
            {"request_featured": 1},
            HTTP_X_REQUESTED_WITH="XMLHttpRequest",
        )
        self.assertEqual(403, response.status_code)

        r = FeaturedRequested.objects.get(pk=r.pk)
        self.assertEqual(r.content_object, tutorial)
        self.assertIn(author.user, r.users_voted.all())

        # reject tutorial proposition
        tutorial.is_obsolete = False  # can vote again
        tutorial.save()

        r = FeaturedRequested.objects.get(pk=r.pk)
        r.rejected = True
        r.save()

        # upvote with other user
        other = ProfileFactory()
        self.client.force_login(other.user)

        response = self.client.post(
            reverse("content:request-featured", kwargs={"pk": tutorial.pk}),
            {"request_featured": 1},
            HTTP_X_REQUESTED_WITH="XMLHttpRequest",
        )
        self.assertEqual(200, response.status_code)

        r = FeaturedRequested.objects.get(pk=r.pk)
        self.assertIn(other.user, r.users_voted.all())
        self.assertFalse(r.rejected)  # not rejected anymore

        # reject for good, cannot vote anymore!
        r.rejected_for_good = True
        r.save()

        response = self.client.post(
            reverse("content:request-featured", kwargs={"pk": tutorial.pk}),
            {"request_featured": 1},
            HTTP_X_REQUESTED_WITH="XMLHttpRequest",
        )
        self.assertEqual(403, response.status_code)

        r = FeaturedRequested.objects.get(pk=r.pk)
        self.assertIn(other.user, r.users_voted.all())
Exemplo n.º 22
0
class TopBarTests(TutorialTestMixin, TestCase):
    def setUp(self):
        # Create some forum's category
        self.category1 = ForumCategoryFactory(position=1)
        self.category2 = ForumCategoryFactory(position=2)

        # Create forum
        self.forum11 = ForumFactory(category=self.category1,
                                    position_in_category=1)

        # Only for staff
        self.staff1 = StaffProfileFactory()

        self.forum12 = ForumFactory(category=self.category2,
                                    position_in_category=2)
        self.forum12.groups.add(Group.objects.filter(name="staff").first())
        self.forum12.save()

        # don't build PDF to speed up the tests

    def test_top_tags(self):
        user = ProfileFactory().user

        # Create 7 topics and give them tags on both public and staff topics
        # in random order to make sure it works
        # tags are named tag-X-Y, where X is the # times it's assigned to a public topic
        # and Y is the total (public + staff) it's been assigned

        topic = TopicFactory(forum=self.forum11, author=user)
        topic.add_tags({"tag-3-5"})

        topic = TopicFactory(forum=self.forum11, author=user)
        topic.add_tags({"tag-3-5"})
        topic.add_tags({"tag-4-4"})

        topic = TopicFactory(forum=self.forum12, author=self.staff1.user)
        topic.add_tags({"tag-0-1"})
        topic.add_tags({"tag-0-2"})
        topic.add_tags({"tag-3-5"})

        topic = TopicFactory(forum=self.forum12, author=self.staff1.user)
        topic.add_tags({"tag-0-2"})
        topic.add_tags({"tag-3-5"})

        topic = TopicFactory(forum=self.forum11, author=user)
        topic.add_tags({"tag-4-4"})
        topic.add_tags({"tag-3-5"})

        topic = TopicFactory(forum=self.forum11, author=user)
        topic.add_tags({"tag-4-4"})

        topic = TopicFactory(forum=self.forum11, author=user)
        topic.add_tags({"tag-4-4"})

        # Now call the function, should be "tag-4-4", "tag-3-5"
        top_tags = topbar_forum_categories(user).get("tags")

        # tag-X-Y : X should be decreasing
        self.assertEqual(top_tags[0].title, "tag-4-4")
        self.assertEqual(top_tags[1].title, "tag-3-5")
        self.assertEqual(len(top_tags), 2)

        # Admin should see theirs specifics tags
        top_tags = topbar_forum_categories(self.staff1.user).get("tags")

        # tag-X-Y : Y should be decreasing
        self.assertEqual(top_tags[0].title, "tag-3-5")
        self.assertEqual(top_tags[1].title, "tag-4-4")
        self.assertEqual(top_tags[2].title, "tag-0-2")
        self.assertEqual(top_tags[3].title, "tag-0-1")
        self.assertEqual(len(top_tags), 4)

        # Now we want to exclude a tag
        self.overridden_zds_app["forum"]["top_tag_exclu"] = {"tag-4-4"}

        # User only sees the only 'public' tag left
        top_tags = topbar_forum_categories(user).get("tags")
        self.assertEqual(top_tags[0].title, "tag-3-5")
        self.assertEqual(len(top_tags), 1)

    def test_top_tags_content(self):
        tags_tuto = ["a", "b", "c"]
        tags_article = ["a", "d", "e"]

        content = PublishedContentFactory(type="TUTORIAL",
                                          author_list=[ProfileFactory().user])
        content.add_tags(tags_tuto)
        content.save()
        tags_tuto = content.tags.all()

        content = PublishedContentFactory(type="ARTICLE",
                                          author_list=[ProfileFactory().user])
        content.add_tags(tags_article)
        content.save()
        tags_article = content.tags.all()

        top_tags_tuto = topbar_publication_categories("TUTORIAL").get("tags")
        top_tags_article = topbar_publication_categories("ARTICLE").get("tags")

        self.assertEqual(list(top_tags_tuto), list(tags_tuto))
        self.assertEqual(list(top_tags_article), list(tags_article))

    def test_content_ordering(self):
        category_1 = ContentCategoryFactory()
        category_2 = ContentCategoryFactory()
        subcategory_1 = SubCategoryFactory(category=category_1)
        subcategory_1.position = 5
        subcategory_1.save()
        subcategory_2 = SubCategoryFactory(category=category_1)
        subcategory_2.position = 1
        subcategory_2.save()
        subcategory_3 = SubCategoryFactory(category=category_2)

        tuto_1 = PublishableContentFactory(type="TUTORIAL")
        tuto_1.subcategory.add(subcategory_1)
        tuto_1_draft = tuto_1.load_version()
        publish_content(tuto_1, tuto_1_draft, is_major_update=True)

        top_categories_tuto = topbar_publication_categories("TUTORIAL").get(
            "categories")
        expected = [(subcategory_1.title, subcategory_1.slug, category_1.slug)]
        self.assertEqual(top_categories_tuto[category_1.title], expected)

        tuto_2 = PublishableContentFactory(type="TUTORIAL")
        tuto_2.subcategory.add(subcategory_2)
        tuto_2_draft = tuto_2.load_version()
        publish_content(tuto_2, tuto_2_draft, is_major_update=True)

        top_categories_tuto = topbar_publication_categories("TUTORIAL").get(
            "categories")
        # New subcategory is now first is the list
        expected.insert(
            0, (subcategory_2.title, subcategory_2.slug, category_1.slug))
        self.assertEqual(top_categories_tuto[category_1.title], expected)

        article_1 = PublishableContentFactory(type="TUTORIAL")
        article_1.subcategory.add(subcategory_3)
        article_1_draft = tuto_2.load_version()
        publish_content(article_1, article_1_draft, is_major_update=True)

        # New article has no impact
        top_categories_tuto = topbar_publication_categories("TUTORIAL").get(
            "categories")
        self.assertEqual(top_categories_tuto[category_1.title], expected)

        top_categories_contents = topbar_publication_categories(
            ["TUTORIAL", "ARTICLE"]).get("categories")
        expected_2 = [(subcategory_3.title, subcategory_3.slug,
                       category_2.slug)]
        self.assertEqual(top_categories_contents[category_1.title], expected)
        self.assertEqual(top_categories_contents[category_2.title], expected_2)
Exemplo n.º 23
0
class ForumNotification(TestCase):
    def setUp(self):
        self.user1 = ProfileFactory().user
        self.user2 = ProfileFactory().user
        self.to_be_changed_staff = StaffProfileFactory().user
        self.staff = StaffProfileFactory().user
        self.assertTrue(self.staff.has_perm("forum.change_topic"))
        self.category1 = ForumCategoryFactory(position=1)
        self.forum11 = ForumFactory(category=self.category1,
                                    position_in_category=1)
        self.forum12 = ForumFactory(category=self.category1,
                                    position_in_category=2)
        for group in self.staff.groups.all():
            self.forum12.groups.add(group)
        self.forum12.save()

    def test_ping_unknown(self):
        self.client.force_login(self.user2)
        result = self.client.post(
            reverse("topic-new") + f"?forum={self.forum11.pk}",
            {
                "title": "Super sujet",
                "subtitle": "Pour tester les notifs",
                "text":
                "@anUnExistingUser is pinged, also a special chars user @{}",
                "tags": "",
            },
            follow=False,
        )
        self.assertEqual(result.status_code, 302, "Request must succeed")
        self.assertEqual(
            0, PingSubscription.objects.count(),
            "As one user is pinged, only one subscription is created.")

    def test_no_auto_ping(self):
        self.client.force_login(self.user2)
        result = self.client.post(
            reverse("topic-new") + f"?forum={self.forum11.pk}",
            {
                "title": "Super sujet",
                "subtitle": "Pour tester les notifs",
                "text":
                f"@{self.user1.username} is pinged, not @{self.user2.username}",
                "tags": "",
            },
            follow=False,
        )
        self.assertEqual(result.status_code, 302)
        self.assertEqual(
            1, PingSubscription.objects.count(),
            "As one user is pinged, only one subscription is created.")

    def test_edit_with_more_than_max_ping(self):
        overridden_zds_app["comment"]["max_pings"] = 2
        pinged_users = [
            ProfileFactory(),
            ProfileFactory(),
            ProfileFactory(),
            ProfileFactory()
        ]
        self.client.force_login(self.user2)
        self.client.post(
            reverse("topic-new") + f"?forum={self.forum11.pk}",
            {
                "title":
                "Super sujet",
                "subtitle":
                "Pour tester les notifs",
                "text":
                "@{} @{} are pinged, not @{} @{}".format(
                    *[a.user.username for a in pinged_users]),
                "tags":
                "",
            },
            follow=False,
        )
        topic = Topic.objects.last()
        post = topic.last_message
        self.assertEqual(2, PingSubscription.objects.count())
        self.assertTrue(
            PingSubscription.objects.get_existing(pinged_users[0].user, post,
                                                  True))
        self.assertTrue(
            PingSubscription.objects.get_existing(pinged_users[1].user, post,
                                                  True))
        self.assertFalse(
            PingSubscription.objects.get_existing(pinged_users[2].user, post,
                                                  True))
        self.assertFalse(
            PingSubscription.objects.get_existing(pinged_users[3].user, post,
                                                  True))
        self.client.post(
            reverse("topic-edit") + f"?topic={topic.pk}",
            {
                "title": "Super sujet",
                "subtitle": "Pour tester les notifs",
                "text":
                f"@{pinged_users[1].user.username} @{pinged_users[3].user.username} are pinged",
                "tags": "",
            },
            follow=False,
        )
        self.assertTrue(
            PingSubscription.objects.get_existing(pinged_users[3].user, post,
                                                  True))
        self.assertTrue(
            PingSubscription.objects.get_existing(pinged_users[1].user, post,
                                                  True))
        self.assertFalse(
            PingSubscription.objects.get_existing(pinged_users[0].user, post,
                                                  True))

    def test_no_reping_on_edition(self):
        """
        to be more accurate : on edition, only ping **new** members
        """
        self.client.force_login(self.user2)
        result = self.client.post(
            reverse("topic-new") + f"?forum={self.forum11.pk}",
            {
                "title": "Super sujet",
                "subtitle": "Pour tester les notifs",
                "text": f"@{self.user1.username} is pinged",
                "tags": "",
            },
            follow=False,
        )
        self.assertEqual(result.status_code, 302)
        self.assertEqual(
            1, PingSubscription.objects.count(),
            "As one user is pinged, only one subscription is created.")
        self.assertEqual(1, Notification.objects.count())
        user3 = ProfileFactory().user
        post = Topic.objects.last().last_message
        result = self.client.post(
            reverse("post-edit") + f"?message={post.pk}",
            {
                "title": "Super sujet",
                "subtitle": "Pour tester les notifs",
                "text":
                f"@{self.user1.username} is pinged even twice @{self.user1.username}",
                "tags": "",
            },
            follow=False,
        )
        self.assertEqual(result.status_code, 302)
        self.assertEqual(1, PingSubscription.objects.count(),
                         "No added subscription.")
        self.assertEqual(1, Notification.objects.count())
        result = self.client.post(
            reverse("post-edit") + f"?message={post.pk}",
            {
                "title":
                "Super sujet",
                "subtitle":
                "Pour tester les notifs",
                "text":
                "@{} is pinged even twice @{} and add @{}".format(
                    self.user1.username, self.user1.username, user3.username),
                "tags":
                "",
            },
            follow=False,
        )
        self.assertEqual(result.status_code, 302)
        self.assertEqual(2, PingSubscription.objects.count())
        self.assertEqual(2, Notification.objects.count())

    def test_loose_ping_on_edition(self):
        """
        to be more accurate : on edition, only ping **new** members
        """
        self.client.force_login(self.user2)
        result = self.client.post(
            reverse("topic-new") + f"?forum={self.forum11.pk}",
            {
                "title": "Super sujet",
                "subtitle": "Pour tester les notifs",
                "text": f"@{self.user1.username} is pinged",
                "tags": "",
            },
            follow=False,
        )
        self.assertEqual(result.status_code, 302)
        self.assertEqual(
            1, PingSubscription.objects.count(),
            "As one user is pinged, only one subscription is created.")
        self.assertEqual(1, Notification.objects.count())
        post = Topic.objects.last().last_message
        result = self.client.post(
            reverse("post-edit") + f"?message={post.pk}",
            {
                "title": "Super sujet",
                "subtitle": "Pour tester les notifs",
                "text": f"@ {self.user1.username} is no more pinged ",
                "tags": "",
            },
            follow=False,
        )
        self.assertEqual(result.status_code, 302)
        self.assertEqual(1, PingSubscription.objects.count(),
                         "No added subscription.")
        self.assertFalse(PingSubscription.objects.first().is_active)
        self.assertEqual(1, Notification.objects.count())
        self.assertTrue(Notification.objects.first().is_read)

    def test_no_dead_notif_on_moving(self):
        NewTopicSubscription.objects.get_or_create_active(
            self.user1, self.forum11)
        self.client.force_login(self.user2)
        result = self.client.post(
            reverse("topic-new") + f"?forum={self.forum11.pk}",
            {
                "title": "Super sujet",
                "subtitle": "Pour tester les notifs",
                "text": "En tout cas l'un abonnement",
                "tags": "",
            },
            follow=False,
        )
        self.assertEqual(result.status_code, 302)

        topic = Topic.objects.filter(title="Super sujet").first()
        subscription = NewTopicSubscription.objects.get_existing(
            self.user1, self.forum11, True)
        self.assertIsNotNone(subscription,
                             "There must be an active subscription for now")
        self.assertIsNotNone(subscription.last_notification,
                             "There must be a notification for now")
        self.assertFalse(subscription.last_notification.is_read)
        self.client.logout()
        self.client.force_login(self.staff)
        data = {"move": "", "forum": self.forum12.pk, "topic": topic.pk}
        response = self.client.post(reverse("topic-edit"), data, follow=False)
        self.assertEqual(302, response.status_code)
        subscription = NewTopicSubscription.objects.get_existing(
            self.user1, self.forum11, True)
        self.assertIsNotNone(subscription,
                             "There must still be an active subscription")
        self.assertIsNotNone(
            subscription.last_notification,
            "There must still be a notification as object is not removed.")
        self.assertEqual(
            subscription.last_notification,
            Notification.objects.filter(sender=self.user2).first())
        self.assertTrue(subscription.last_notification.is_read,
                        "As forum is not reachable, notification is read")

    def test_no_ping_on_private_forum(self):
        self.client.force_login(self.staff)
        result = self.client.post(
            reverse("topic-new") + f"?forum={self.forum12.pk}",
            {
                "title": "Super sujet",
                "subtitle": "Pour tester les notifs",
                "text": f"ping @{self.user1.username}",
                "tags": "",
            },
            follow=False,
        )
        self.assertEqual(result.status_code, 302)

        topic = Topic.objects.filter(title="Super sujet").first()
        subscription = PingSubscription.objects.get_existing(
            self.user1, topic.last_message, True)
        self.assertIsNone(subscription,
                          "There must be no active subscription for now")

    def test_no_dead_ping_notif_on_moving_to_private_forum(self):
        self.client.force_login(self.user2)
        result = self.client.post(
            reverse("topic-new") + f"?forum={self.forum11.pk}",
            {
                "title": "Super sujet",
                "subtitle": "Pour tester les notifs",
                "text": f"ping @{self.user1.username}",
                "tags": "",
            },
            follow=False,
        )
        self.assertEqual(result.status_code, 302)

        topic = Topic.objects.filter(title="Super sujet").first()
        subscription = PingSubscription.objects.get_existing(
            self.user1, topic.last_message, True)
        self.assertIsNotNone(subscription,
                             "There must be an active subscription for now")
        self.assertIsNotNone(subscription.last_notification,
                             "There must be a notification for now")
        self.assertFalse(subscription.last_notification.is_read)
        self.client.logout()
        self.client.force_login(self.staff)
        data = {"move": "", "forum": self.forum12.pk, "topic": topic.pk}
        response = self.client.post(reverse("topic-edit"), data, follow=False)
        self.assertEqual(302, response.status_code)
        subscription = PingSubscription.objects.get_existing(
            self.user1, topic.last_message, True)
        self.assertIsNotNone(subscription,
                             "There must still be an active subscription")
        self.assertIsNotNone(
            subscription.last_notification,
            "There must still be a notification as object is not removed.")
        self.assertEqual(
            subscription.last_notification,
            Notification.objects.filter(sender=self.user2).first())
        self.assertTrue(subscription.last_notification.is_read,
                        "As forum is not reachable, notification is read")

    def test_no_more_new_topic_notif_on_losing_all_groups(self):
        NewTopicSubscription.objects.get_or_create_active(
            self.to_be_changed_staff, self.forum12)
        self.client.force_login(self.staff)
        self.client.post(
            reverse("topic-new") + f"?forum={self.forum12.pk}",
            {
                "title": "Super sujet",
                "subtitle": "Pour tester les notifs",
                "text": "En tout cas l'un abonnement",
                "tags": "",
            },
            follow=False,
        )
        subscription = NewTopicSubscription.objects.get_existing(
            self.to_be_changed_staff, self.forum12, True)
        self.assertIsNotNone(subscription,
                             "There must be an active subscription for now")
        self.assertIsNotNone(subscription.last_notification,
                             "There must be a notification.")
        self.assertFalse(subscription.last_notification.is_read,
                         "The notification has not been read yet")

        self.to_be_changed_staff.groups.clear()
        self.to_be_changed_staff.save()

        subscription = NewTopicSubscription.objects.get_existing(
            self.to_be_changed_staff, self.forum12, False)
        self.assertIsNotNone(subscription,
                             "The subscription should now be inactive")
        self.assertFalse(subscription.is_active)
        self.assertTrue(subscription.last_notification.is_read,
                        "As forum is not reachable, notification is read")

    def test_no_more_new_topic_notif_on_losing_one_group(self):
        NewTopicSubscription.objects.get_or_create_active(
            self.to_be_changed_staff, self.forum12)
        self.client.force_login(self.staff)
        self.client.post(
            reverse("topic-new") + f"?forum={self.forum12.pk}",
            {
                "title": "Super sujet",
                "subtitle": "Pour tester les notifs",
                "text": "En tout cas l'un abonnement",
                "tags": "",
            },
            follow=False,
        )
        subscription = NewTopicSubscription.objects.get_existing(
            self.to_be_changed_staff, self.forum12, True)
        self.assertIsNotNone(subscription,
                             "There must be an active subscription for now")
        self.assertIsNotNone(subscription.last_notification,
                             "There must be a notification.")
        self.assertFalse(subscription.last_notification.is_read,
                         "The notification has not been read yet")

        self.to_be_changed_staff.groups.remove(
            list(self.to_be_changed_staff.groups.all())[0])
        self.to_be_changed_staff.save()

        subscription = NewTopicSubscription.objects.get_existing(
            self.to_be_changed_staff, self.forum12, False)
        self.assertIsNotNone(subscription,
                             "There must be an inactive subscription now")
        self.assertFalse(subscription.is_active)
        self.assertTrue(subscription.last_notification.is_read,
                        "As forum is not reachable, notification is read")

    def test_no_more_topic_answer_notif_on_losing_all_groups(self):
        self.client.force_login(self.to_be_changed_staff)
        self.client.post(
            reverse("topic-new") + f"?forum={self.forum12.pk}",
            {
                "title": "Super sujet",
                "subtitle": "Pour tester les notifs",
                "text": "En tout cas l'un abonnement",
                "tags": "",
            },
            follow=False,
        )
        topic = Topic.objects.filter(title="Super sujet").first()

        self.client.force_login(self.staff)
        self.client.post(
            reverse("post-new") + f"?sujet={topic.pk}",
            {
                "last_post":
                topic.last_message.pk,
                "text":
                "C'est tout simplement l'histoire de la ville de Paris que je voudrais vous conter ",
            },
            follow=False,
        )

        subscription = TopicAnswerSubscription.objects.get_existing(
            content_object=topic,
            user=self.to_be_changed_staff,
            is_active=True)
        self.assertIsNotNone(subscription,
                             "There must be an active subscription for now")
        self.assertIsNotNone(subscription.last_notification,
                             "There must be a notification.")
        self.assertFalse(subscription.last_notification.is_read,
                         "The notification has not been read yet")

        self.to_be_changed_staff.groups.clear()
        self.to_be_changed_staff.save()

        subscription = TopicAnswerSubscription.objects.get_existing(
            content_object=topic,
            user=self.to_be_changed_staff,
            is_active=False)
        self.assertIsNotNone(subscription,
                             "The subscription must now be inactive")
        self.assertFalse(subscription.is_active)
        self.assertTrue(subscription.last_notification.is_read,
                        "As forum is not reachable, notification is read")

    def test_no_more_topic_answer_notif_on_losing_one_group(self):
        self.client.force_login(self.to_be_changed_staff)
        self.client.post(
            reverse("topic-new") + f"?forum={self.forum12.pk}",
            {
                "title": "Super sujet",
                "subtitle": "Pour tester les notifs",
                "text": "En tout cas l'un abonnement",
                "tags": "",
            },
            follow=False,
        )
        topic = Topic.objects.filter(title="Super sujet").first()

        self.client.force_login(self.staff)
        self.client.post(
            reverse("post-new") + f"?sujet={topic.pk}",
            {
                "last_post":
                topic.last_message.pk,
                "text":
                "C'est tout simplement l'histoire de la ville de Paris que je voudrais vous conter ",
            },
            follow=False,
        )

        subscription = TopicAnswerSubscription.objects.get_existing(
            content_object=topic,
            user=self.to_be_changed_staff,
            is_active=True)
        self.assertIsNotNone(subscription,
                             "There must be an active subscription for now")
        self.assertIsNotNone(subscription.last_notification,
                             "There must be a notification.")
        self.assertFalse(subscription.last_notification.is_read,
                         "The notification has not been read yet")

        self.to_be_changed_staff.groups.remove(
            list(self.to_be_changed_staff.groups.all())[0])
        self.to_be_changed_staff.save()

        subscription = TopicAnswerSubscription.objects.get_existing(
            content_object=topic,
            user=self.to_be_changed_staff,
            is_active=False)
        self.assertIsNotNone(subscription,
                             "The subscription must now be inactive")
        self.assertFalse(subscription.is_active)
        self.assertTrue(subscription.last_notification.is_read,
                        "As forum is not reachable, notification is read")