Пример #1
0
def load_forums(cli, size, fake, *_, **__):
    """
    Load forums
    """
    nb_forums = size * 8
    cli.stdout.write("Nombres de Forums à créer : {}".format(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(" Forum {}/{}  \r".format(i + 1, nb_forums))
            sys.stdout.flush()
        tps2 = time.time()
        cli.stdout.write("\nFait en {} sec".format(tps2 - tps1))
Пример #2
0
class ForumNotification(TestCase):
    def setUp(self):
        self.user1 = ProfileFactory().user
        self.user2 = ProfileFactory().user
        self.staff = StaffProfileFactory().user
        self.assertTrue(self.staff.has_perm('forum.change_topic'))
        self.category1 = CategoryFactory(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_no_dead_notif_on_moving(self):
        NewTopicSubscription.objects.get_or_create_active(
            self.user1, self.forum11)
        self.assertTrue(
            self.client.login(username=self.user2.username,
                              password='******'))
        result = self.client.post(reverse('topic-new') +
                                  '?forum={0}'.format(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.assertTrue(
            self.client.login(username=self.staff.username,
                              password='******'))
        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')
Пример #3
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 = CategoryFactory(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):
        overridden_zds_app['comment']['enable_pings'] = True
        self.assertTrue(self.client.login(username=self.user2.username, password='******'))
        result = self.client.post(
            reverse('topic-new') + '?forum={0}'.format(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):
        overridden_zds_app['comment']['enable_pings'] = True
        self.assertTrue(self.client.login(username=self.user2.username, password='******'))
        result = self.client.post(
            reverse('topic-new') + '?forum={0}'.format(self.forum11.pk),
            {
                'title': 'Super sujet',
                'subtitle': 'Pour tester les notifs',
                'text': '@{} is pinged, not @{}'.format(self.user1.username, 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_no_reping_on_edition(self):
        """
        to be more accurate : on edition, only ping **new** members
        """
        overridden_zds_app['comment']['enable_pings'] = True
        self.assertTrue(self.client.login(username=self.user2.username, password='******'))
        result = self.client.post(
            reverse('topic-new') + '?forum={0}'.format(self.forum11.pk),
            {
                'title': 'Super sujet',
                'subtitle': 'Pour tester les notifs',
                'text': '@{} is pinged'.format(self.user1.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.')
        self.assertEqual(1, Notification.objects.count())
        user3 = ProfileFactory().user
        post = Topic.objects.last().last_message
        result = self.client.post(
            reverse('post-edit') + '?message={0}'.format(post.pk),
            {
                'title': 'Super sujet',
                'subtitle': 'Pour tester les notifs',
                'text': '@{} is pinged even twice @{}'.format(self.user1.username, 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') + '?message={0}'.format(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
        """
        overridden_zds_app['comment']['enable_pings'] = True
        self.assertTrue(self.client.login(username=self.user2.username, password='******'))
        result = self.client.post(
            reverse('topic-new') + '?forum={0}'.format(self.forum11.pk),
            {
                'title': 'Super sujet',
                'subtitle': 'Pour tester les notifs',
                'text': '@{} is pinged'.format(self.user1.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.')
        self.assertEqual(1, Notification.objects.count())
        post = Topic.objects.last().last_message
        result = self.client.post(
            reverse('post-edit') + '?message={0}'.format(post.pk),
            {
                'title': 'Super sujet',
                'subtitle': 'Pour tester les notifs',
                'text': '@ {} is no more pinged '.format(self.user1.username),
                '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.assertTrue(self.client.login(username=self.user2.username, password='******'))
        result = self.client.post(
            reverse('topic-new') + '?forum={0}'.format(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.assertTrue(self.client.login(username=self.staff.username, password='******'))
        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.assertTrue(self.client.login(username=self.staff.username, password='******'))
        result = self.client.post(
            reverse('topic-new') + '?forum={0}'.format(self.forum12.pk),
            {
                'title': 'Super sujet',
                'subtitle': 'Pour tester les notifs',
                'text': 'ping @{}'.format(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.assertTrue(self.client.login(username=self.user2.username, password='******'))
        result = self.client.post(
            reverse('topic-new') + '?forum={0}'.format(self.forum11.pk),
            {
                'title': 'Super sujet',
                'subtitle': 'Pour tester les notifs',
                'text': 'ping @{}'.format(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.assertTrue(self.client.login(username=self.staff.username, password='******'))
        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_notif_on_losing_all_groups(self):
        NewTopicSubscription.objects.get_or_create_active(self.to_be_changed_staff, self.forum12)
        self.assertTrue(self.client.login(username=self.staff.username, password='******'))
        self.client.post(
            reverse('topic-new') + '?forum={0}'.format(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.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, 'There must be an active subscription for now')
        self.assertFalse(subscription.is_active)

    def test_no_more_notif_on_losing_one_group(self):
        NewTopicSubscription.objects.get_or_create_active(self.to_be_changed_staff, self.forum12)
        self.assertTrue(self.client.login(username=self.staff.username, password='******'))
        self.client.post(
            reverse('topic-new') + '?forum={0}'.format(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.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 active subscription for now')
        self.assertFalse(subscription.is_active)
Пример #4
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)
Пример #5
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 = CategoryFactory(position=1)
        forum1 = ForumFactory(category=category1, position_in_category=1)
        forum1.group.add(group)
        forum1.save()
        forum2 = ForumFactory(category=category1, position_in_category=2)
        forum2.group.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)
        login_check = self.client.login(username=staff.user.username,
                                        password='******')
        self.assertEqual(login_check, True)

        # 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 user rights and 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],
                                      'superuser': "******",
                                  },
                                  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)
        self.assertTrue(tester.user.is_superuser)

        # 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.assertFalse(tester.user.is_superuser)
        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)

        # check that staff can't take away it's own super user rights
        result = self.client.post(reverse('member-settings-promote',
                                          kwargs={'user_pk': staff.user.id}),
                                  {'activation': "on"},
                                  follow=False)
        self.assertEqual(result.status_code, 302)
        staff = Profile.objects.get(id=staff.id)  # refresh
        self.assertTrue(staff.user.is_superuser)  # still superuser !

        # 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 !
Пример #6
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":
                "@{} @{} are pinged".format(pinged_users[1].user.username,
                                            pinged_users[3].user.username),
                "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_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.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,
                             "There must be an active subscription for now")
        self.assertFalse(subscription.is_active)

    def test_no_more_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.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 active subscription for now")
        self.assertFalse(subscription.is_active)
Пример #7
0
class TopBarTests(TestCase):
    def setUp(self):

        # Create some forum's category
        self.category1 = CategoryFactory(position=1)
        self.category2 = CategoryFactory(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):
        """Unit testing top_categories method """

        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 = top_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 = top_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
        overridden_zds_app['forum']['top_tag_exclu'] = {'tag-4-4'}

        # User only sees the only 'public' tag left
        top_tags = top_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):
        """Unit testing top_categories_content method """

        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 = top_categories_content('TUTORIAL').get('tags')
        top_tags_article = top_categories_content('ARTICLE').get('tags')

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

    def tearDown(self):

        if os.path.isdir(overridden_zds_app['content']['repo_private_path']):
            shutil.rmtree(overridden_zds_app['content']['repo_private_path'])
        if os.path.isdir(overridden_zds_app['content']['repo_public_path']):
            shutil.rmtree(overridden_zds_app['content']['repo_public_path'])
        if os.path.isdir(settings.MEDIA_ROOT):
            shutil.rmtree(settings.MEDIA_ROOT)
Пример #8
0
class TopBarTests(TestCase):
    def setUp(self):

        # Create some forum's category
        self.category1 = CategoryFactory(position=1)
        self.category2 = CategoryFactory(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.group.add(Group.objects.filter(name="staff").first())
        self.forum12.save()

    def test_top_tags(self):
        """Unit testing top_categories method """

        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 = top_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 = top_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
        settings.ZDS_APP['forum']['top_tag_exclu'] = {'tag-4-4'}

        # User only sees the only 'public' tag left
        top_tags = top_categories(user).get('tags')
        self.assertEqual(top_tags[0].title, 'tag-3-5')
        self.assertEqual(len(top_tags), 1)
Пример #9
0
class TopBarTests(TutorialTestMixin, TestCase):

    def setUp(self):
        # Create some forum's category
        self.category1 = CategoryFactory(position=1)
        self.category2 = CategoryFactory(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)
Пример #10
0
class TopBarTests(TestCase):
    def setUp(self):
        # Create some forum's category
        self.category1 = CategoryFactory(position=1)
        self.category2 = CategoryFactory(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
        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)

    def tearDown(self):
        if os.path.isdir(overridden_zds_app['content']['repo_private_path']):
            shutil.rmtree(overridden_zds_app['content']['repo_private_path'])
        if os.path.isdir(overridden_zds_app['content']['repo_public_path']):
            shutil.rmtree(overridden_zds_app['content']['repo_public_path'])
        if os.path.isdir(settings.MEDIA_ROOT):
            shutil.rmtree(settings.MEDIA_ROOT)
Пример #11
0
class TopBarTests(TestCase):
    def setUp(self):

        # Create some forum's category
        self.category1 = CategoryFactory(position=1)
        self.category2 = CategoryFactory(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.group.add(Group.objects.filter(name="staff").first())
        self.forum12.save()

    def test_top_tags(self):
        """Unit testing top_categories method """

        user = ProfileFactory().user

        # Create some topics
        topic = TopicFactory(forum=self.forum11, author=user)
        topic.add_tags({'C#'})

        topic1 = TopicFactory(forum=self.forum11, author=user)
        topic1.add_tags({'C#'})

        topic2 = TopicFactory(forum=self.forum11, author=user)
        topic2.add_tags({'C#'})

        topic3 = TopicFactory(forum=self.forum11, author=user)
        topic3.add_tags({'PHP'})

        topic4 = TopicFactory(forum=self.forum11, author=user)
        topic4.add_tags({'PHP'})

        topic5 = TopicFactory(forum=self.forum12, author=user)
        topic5.add_tags({'stafftag'})

        # Now call the function, should be "C#", "PHP"
        top_tags = top_categories(user).get('tags')

        # Assert
        self.assertEqual(top_tags[0].title, 'c#')
        self.assertEqual(top_tags[1].title, 'php')
        self.assertEqual(len(top_tags), 2)

        # Admin should see theirs specifics tags
        top_tags_for_staff = top_categories(self.staff1.user).get('tags')
        self.assertEqual(top_tags_for_staff[2].title, 'stafftag')

        # Now we want to exclude a tag
        settings.ZDS_APP['forum']['top_tag_exclu'] = {'php'}
        top_tags = top_categories(user).get('tags')

        # Assert that we should only have one tags
        self.assertEqual(top_tags[0].title, 'c#')
        self.assertEqual(len(top_tags), 1)