コード例 #1
0
    def setUp(self):

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

        self.user_author = ProfileFactory().user
        self.user = ProfileFactory().user
        self.staff = StaffProfileFactory().user

        self.licence = LicenceFactory()

        self.article = ArticleFactory()
        self.article.authors.add(self.user_author)
        self.article.licence = self.licence
        self.article.save()

        # connect with user
        login_check = self.client.login(username=self.user_author.username,
                                        password='******')
        self.assertEqual(login_check, True)

        # ask public article
        pub = self.client.post(reverse('zds.article.views.modify'), {
            'article': self.article.pk,
            'comment': u'Valides moi ce bébé',
            'pending': 'Demander validation',
            'version': self.article.sha_draft,
            'is_major': True
        },
                               follow=False)
        self.assertEqual(pub.status_code, 302)
        self.assertEqual(Validation.objects.count(), 1)

        login_check = self.client.login(username=self.staff.username,
                                        password='******')
        self.assertEqual(login_check, True)

        # reserve tutorial
        validation = Validation.objects.get(article__pk=self.article.pk)
        pub = self.client.post(reverse('zds.article.views.reservation',
                                       args=[validation.pk]),
                               follow=False)
        self.assertEqual(pub.status_code, 302)

        # publish article
        pub = self.client.post(reverse('zds.article.views.modify'), {
            'article': self.article.pk,
            'comment-v': u'Cet article est excellent',
            'valid-article': 'Demander validation',
            'is_major': True
        },
                               follow=False)
        self.assertEqual(pub.status_code, 302)
        self.assertEquals(len(mail.outbox), 1)
        mail.outbox = []

        self.articlefeed = LastArticlesFeedRSS()
コード例 #2
0
ファイル: tests_models.py プロジェクト: arirawr/zds-site
 def test_get_articles(self):
     # Start with 0
     self.assertEqual(len(self.user1.get_articles()), 0)
     # Create Tuto !
     article = ArticleFactory()
     article.authors.add(self.user1.user)
     article.save()
     # Should be 1
     articles = self.user1.get_articles()
     self.assertEqual(len(articles), 1)
     self.assertEqual(article, articles[0])
コード例 #3
0
ファイル: tests_models.py プロジェクト: Akulen/zds-site
 def test_get_articles(self):
     # Start with 0
     self.assertEqual(len(self.user1.get_articles()), 0)
     # Create Tuto !
     article = ArticleFactory()
     article.authors.add(self.user1.user)
     article.save()
     # Should be 1
     articles = self.user1.get_articles()
     self.assertEqual(len(articles), 1)
     self.assertEqual(article, articles[0])
コード例 #4
0
ファイル: tests.py プロジェクト: Dryusdan/zds-site
    def setUp(self):

        settings.EMAIL_BACKEND = "django.core.mail.backends.locmem.EmailBackend"
        self.mas = ProfileFactory().user
        settings.BOT_ACCOUNT = self.mas.username

        self.user_author = ProfileFactory().user
        self.user = ProfileFactory().user
        self.staff = StaffProfileFactory().user

        self.licence = LicenceFactory()

        self.article = ArticleFactory()
        self.article.authors.add(self.user_author)
        self.article.licence = self.licence
        self.article.save()

        # connect with user
        login_check = self.client.login(username=self.user_author.username, password="******")
        self.assertEqual(login_check, True)

        # ask public article
        pub = self.client.post(
            reverse("zds.article.views.modify"),
            {
                "article": self.article.pk,
                "comment": u"Valides moi ce bébé",
                "pending": "Demander validation",
                "version": self.article.sha_draft,
                "is_major": True,
            },
            follow=False,
        )
        self.assertEqual(pub.status_code, 302)
        self.assertEqual(Validation.objects.count(), 1)

        login_check = self.client.login(username=self.staff.username, password="******")
        self.assertEqual(login_check, True)

        # reserve tutorial
        validation = Validation.objects.get(article__pk=self.article.pk)
        pub = self.client.post(reverse("zds.article.views.reservation", args=[validation.pk]), follow=False)
        self.assertEqual(pub.status_code, 302)

        # publish article
        pub = self.client.post(
            reverse("zds.article.views.modify"),
            {
                "article": self.article.pk,
                "comment-v": u"Cet article est excellent",
                "valid-article": "Demander validation",
                "is_major": True,
            },
            follow=False,
        )
        self.assertEqual(pub.status_code, 302)
        self.assertEquals(len(mail.outbox), 1)
        mail.outbox = []
コード例 #5
0
ファイル: tests.py プロジェクト: pquentin/zds-site
    def test_read_not_public_article(self):
        """To test if nobody can read a not public article."""

        # member can't read public articles which is not published
        article_no_public = ArticleFactory()
        article_no_public.on_line = False
        article_no_public.save()

        result = self.client.get(reverse(
            'zds.article.views.view_online',
            args=[article_no_public.pk, article_no_public.slug]),
                                 follow=False)
        self.assertEqual(result.status_code, 404)

        # logout before
        self.client.logout()

        result = self.client.get(reverse(
            'zds.article.views.view_online',
            args=[article_no_public.pk, article_no_public.slug]),
                                 follow=False)
        self.assertEqual(result.status_code, 404)
コード例 #6
0
class LastArticlesFeedRSSTest(TestCase):
    def setUp(self):

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

        self.user_author = ProfileFactory().user
        self.user = ProfileFactory().user
        self.staff = StaffProfileFactory().user

        self.licence = LicenceFactory()

        self.article = ArticleFactory()
        self.article.authors.add(self.user_author)
        self.article.licence = self.licence
        self.article.save()

        # connect with user
        login_check = self.client.login(username=self.user_author.username,
                                        password='******')
        self.assertEqual(login_check, True)

        # ask public article
        pub = self.client.post(reverse('zds.article.views.modify'), {
            'article': self.article.pk,
            'comment': u'Valides moi ce bébé',
            'pending': 'Demander validation',
            'version': self.article.sha_draft,
            'is_major': True
        },
                               follow=False)
        self.assertEqual(pub.status_code, 302)
        self.assertEqual(Validation.objects.count(), 1)

        login_check = self.client.login(username=self.staff.username,
                                        password='******')
        self.assertEqual(login_check, True)

        # reserve tutorial
        validation = Validation.objects.get(article__pk=self.article.pk)
        pub = self.client.post(reverse('zds.article.views.reservation',
                                       args=[validation.pk]),
                               follow=False)
        self.assertEqual(pub.status_code, 302)

        # publish article
        pub = self.client.post(reverse('zds.article.views.modify'), {
            'article': self.article.pk,
            'comment-v': u'Cet article est excellent',
            'valid-article': 'Demander validation',
            'is_major': True
        },
                               follow=False)
        self.assertEqual(pub.status_code, 302)
        self.assertEquals(len(mail.outbox), 1)
        mail.outbox = []

        self.articlefeed = LastArticlesFeedRSS()

    def test_is_well_setup(self):
        """ Test that base parameters are Ok """

        self.assertEqual(self.articlefeed.link, '/articles/')
        reftitle = u"Articles sur {}".format(
            settings.ZDS_APP['site']['litteral_name'])
        self.assertEqual(self.articlefeed.title, reftitle)
        refdescription = u"Les derniers articles parus sur {}.".format(
            settings.ZDS_APP['site']['litteral_name'])
        self.assertEqual(self.articlefeed.description, refdescription)

        atom = LastArticlesFeedATOM()
        self.assertEqual(atom.subtitle, refdescription)

    def test_get_items(self):
        """ basic test sending back the article """

        ret = self.articlefeed.items()
        self.assertEqual(ret[0], self.article)

    def test_get_pubdate(self):
        """ test the return value of pubdate """

        ref = Article.objects.get(pk=self.article.pk).pubdate
        article = self.articlefeed.items()[0]
        ret = self.articlefeed.item_pubdate(item=article)
        self.assertEqual(ret.date(), ref.date())

    def test_get_title(self):
        """ test the return value of title """

        ref = self.article.title
        article = self.articlefeed.items()[0]
        ret = self.articlefeed.item_title(item=article)
        self.assertEqual(ret, ref)

    def test_get_description(self):
        """ test the return value of description """

        ref = self.article.description
        article = self.articlefeed.items()[0]
        ret = self.articlefeed.item_description(item=article)
        self.assertEqual(ret, ref)

    def test_get_author_name(self):
        """ test the return value of author name """

        ref = self.user_author.username
        article = self.articlefeed.items()[0]
        ret = self.articlefeed.item_author_name(item=article)
        self.assertEqual(ret, ref)

    def test_get_item_link(self):
        """ test the return value of item link """

        ref = self.article.get_absolute_url_online()
        article = self.articlefeed.items()[0]
        ret = self.articlefeed.item_link(item=article)
        self.assertEqual(ret, ref)

    def tearDown(self):
        if os.path.isdir(settings.ZDS_APP['article']['repo_path']):
            shutil.rmtree(settings.ZDS_APP['article']['repo_path'])
        if os.path.isdir(settings.MEDIA_ROOT):
            shutil.rmtree(settings.MEDIA_ROOT)
コード例 #7
0
ファイル: tests_utils.py プロジェクト: pquentin/zds-site
    def test_migrate_zep12(self):
        private_mini_tuto = MiniTutorialFactory(title="Private Mini tuto")
        private_mini_tuto.authors.add(self.user_author)
        private_mini_tuto.save()
        multi_author_tuto = MiniTutorialFactory(title="Multi User Tuto")
        multi_author_tuto.authors.add(self.user_author)
        multi_author_tuto.authors.add(self.staff)
        multi_author_tuto.save()
        public_mini_tuto = PublishedMiniTutorial(title="Public Mini Tuto")
        public_mini_tuto.authors.add(self.user_author)
        public_mini_tuto.save()
        OldTutoValidation(
            tutorial=public_mini_tuto,
            version=public_mini_tuto.sha_public,
            date_proposition=datetime.datetime.now(),
            comment_authors=u"La vie est belle, le destin s'en écarte.",
            comment_validator=u"Personne ne joue avec les mêmes cartes.",
            validator=self.staff,
            status="ACCEPT",
            date_reserve=datetime.datetime.now(),
            date_validation=datetime.datetime.now()).save()
        staff_note = NoteFactory(tutorial=public_mini_tuto,
                                 position=1,
                                 author=self.staff)
        liked_note = NoteFactory(tutorial=public_mini_tuto,
                                 position=2,
                                 author=self.user_author)
        t_read = TutorialRead()
        t_read.tutorial = public_mini_tuto
        t_read.user = self.staff
        t_read.note = staff_note
        t_read.save()
        like = CommentLike()
        like.comments = liked_note
        like.user = self.staff
        like.save()
        big_tuto = BigTutorialFactory(title="Big tuto")
        big_tuto.authors.add(self.user_author)
        big_tuto.save()
        public_big_tuto = PublishedBigTutorial(light=False,
                                               title="Public Big Tuto")
        public_big_tuto.authors.add(self.user_author)
        public_big_tuto.save()
        private_article = ArticleFactory(title="Private Article")
        private_article.authors.add(self.user_author)
        private_article.save()
        multi_author_article = ArticleFactory(title="Multi Author Article")
        multi_author_article.authors.add(self.user_author)
        multi_author_article.authors.add(self.staff)
        multi_author_article.save()
        public_article = PublishedArticleFactory(title="Public Article")
        public_article.authors.add(self.user_author)
        public_article.save()
        OldArticleValidation(
            article=public_article,
            version=public_article.sha_public,
            date_proposition=datetime.datetime.now(),
            comment_authors=u"Pourquoi fortune et infortune?",
            comment_validator=u"Pourquoi suis-je né les poches vides?",
            validator=self.staff,
            status="ACCEPT",
            date_reserve=datetime.datetime.now(),
            date_validation=datetime.datetime.now()).save()
        staff_note = ReactionFactory(article=public_article,
                                     position=1,
                                     author=self.staff)
        liked_reaction = ReactionFactory(article=public_article,
                                         position=2,
                                         author=self.user_author)
        a_read = ArticleRead()
        a_read.article = public_article
        a_read.user = self.staff
        a_read.reaction = staff_note
        a_read.save()
        like = CommentLike()
        like.comments = liked_reaction
        like.user = self.staff
        like.save()
        category1 = CategoryFactory(position=1)
        forum11 = ForumFactory(category=category1, position_in_category=1)
        beta_tuto = BetaMiniTutorialFactory(title=u"Beta Tuto",
                                            forum=forum11,
                                            author=self.user_author)
        beta_tuto.authors.add(self.user_author)
        beta_tuto.save()
        call_command('migrate_to_zep12')
        # 1 tuto in setup, 4 mini tutos, 1 big tuto, 3 articles
        self.assertEqual(
            PublishableContent.objects.filter(
                authors__pk__in=[self.user_author.pk]).count(), 10)
        # if we had n published content we must have 2 * n PublishedContent entities to handle redirections.
        self.assertEqual(
            PublishedContent.objects.filter(
                content__authors__pk__in=[self.user_author.pk]).count(), 2 * 3)
        self.assertEqual(
            ContentReaction.objects.filter(author__pk=self.staff.pk).count(),
            2)
        migrated_pulished_article = PublishableContent.objects.filter(
            authors__in=[self.user_author],
            title=public_article.title,
            type="ARTICLE").first()
        self.assertIsNotNone(migrated_pulished_article)
        self.assertIsNotNone(migrated_pulished_article.last_note)
        self.assertEqual(
            2,
            ContentReaction.objects.filter(
                related_content=migrated_pulished_article).count())
        self.assertEqual(
            1,
            ContentRead.objects.filter(
                content=migrated_pulished_article).count())
        self.assertTrue(
            migrated_pulished_article.is_public(
                migrated_pulished_article.sha_public))
        self.assertTrue(
            migrated_pulished_article.load_version(
                migrated_pulished_article.sha_public).has_extracts())
        self.assertEqual(
            len(
                migrated_pulished_article.load_version(
                    migrated_pulished_article.sha_public).children), 2)

        migrated_pulished_tuto = PublishableContent.objects.filter(
            authors__in=[self.user_author],
            title=public_mini_tuto.title,
            type="TUTORIAL").first()
        self.assertIsNotNone(migrated_pulished_tuto)
        self.assertIsNotNone(migrated_pulished_tuto.last_note)
        self.assertEqual(
            2,
            ContentReaction.objects.filter(
                related_content=migrated_pulished_tuto).count())
        self.assertEqual(
            1,
            ContentRead.objects.filter(content=migrated_pulished_tuto).count())
        self.assertTrue(
            migrated_pulished_tuto.is_public(
                migrated_pulished_tuto.sha_public))
        beta_content = PublishableContent.objects.filter(
            title=beta_tuto.title).first()
        self.assertIsNotNone(beta_content)
        self.assertEqual(beta_content.sha_beta, beta_tuto.sha_beta)
        self.assertEqual(
            Topic.objects.filter(key=beta_tuto.pk).first().pk,
            beta_content.beta_topic.pk)

        multi_author_content = PublishableContent.objects.filter(type="TUTORIAL", title=multi_author_tuto.title)\
            .first()
        self.assertIsNotNone(multi_author_content)
        self.assertEqual(multi_author_content.authors.count(),
                         multi_author_tuto.authors.count())
        multi_author_content = PublishableContent.objects.filter(type="ARTICLE", title=multi_author_article.title)\
            .first()
        self.assertIsNotNone(multi_author_content)
        self.assertEqual(multi_author_content.authors.count(),
                         multi_author_article.authors.count())
        old_tutorial_module_prefix = "oldtutoriels"
        old_article_module_prefix = "oldarticles"
        new_tutorial_module_prefix = "tutoriels"
        new_article_module_prefix = "articles"
        public_article_url = public_article.get_absolute_url_online()\
            .replace(old_article_module_prefix, new_article_module_prefix)
        public_tutorial_url = public_mini_tuto.get_absolute_url_online()\
            .replace(old_tutorial_module_prefix, new_tutorial_module_prefix)
        self.assertEqual(301, self.client.get(public_article_url).status_code)
        self.assertEqual(301, self.client.get(public_tutorial_url).status_code)
        public_chapter = Chapter.objects.filter(
            part__tutorial__pk=public_big_tuto.pk).first()
        self.assertIsNotNone(public_chapter)
        public_chapter_url = public_chapter.get_absolute_url_online()
        public_chapter_url = public_chapter_url.replace(
            old_tutorial_module_prefix, new_tutorial_module_prefix)

        self.assertEqual(301, self.client.get(public_chapter_url).status_code)
        self.assertEqual(
            200,
            self.client.get(public_chapter_url, follow=True).status_code)
        self.assertEqual(
            200,
            self.client.get(public_article_url, follow=True).status_code)
        self.assertEqual(
            200,
            self.client.get(public_tutorial_url, follow=True).status_code)
        tuto_validation = Validation.objects.filter(
            content__pk=migrated_pulished_tuto.pk).first()
        self.assertIsNotNone(tuto_validation)
        self.assertEqual(tuto_validation.status, "ACCEPT")
        self.assertEqual(tuto_validation.validator.pk, self.staff.pk)
        article_validation = Validation.objects.filter(
            content__pk=migrated_pulished_article.pk).first()
        self.assertIsNotNone(article_validation)
        self.assertEqual(article_validation.status, "ACCEPT")
        self.assertEqual(article_validation.validator.pk, self.staff.pk)
コード例 #8
0
class ArticleTests(TestCase):
    def setUp(self):

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

        self.user_author = ProfileFactory().user
        self.user = ProfileFactory().user
        self.staff = StaffProfileFactory().user

        self.licence = LicenceFactory()

        self.article = ArticleFactory()
        self.article.authors.add(self.user_author)
        self.article.licence = self.licence
        self.article.save()

        # connect with user
        login_check = self.client.login(username=self.user_author.username,
                                        password='******')
        self.assertEqual(login_check, True)

        # ask public article
        pub = self.client.post(reverse('zds.article.views.modify'), {
            'article': self.article.pk,
            'comment': u'Valides moi ce bébé',
            'pending': 'Demander validation',
            'version': self.article.sha_draft,
            'is_major': True
        },
                               follow=False)
        self.assertEqual(pub.status_code, 302)
        self.assertEqual(Validation.objects.count(), 1)

        login_check = self.client.login(username=self.staff.username,
                                        password='******')
        self.assertEqual(login_check, True)

        # reserve tutorial
        validation = Validation.objects.get(article__pk=self.article.pk)
        pub = self.client.post(reverse('zds.article.views.reservation',
                                       args=[validation.pk]),
                               follow=False)
        self.assertEqual(pub.status_code, 302)

        # publish article
        pub = self.client.post(reverse('zds.article.views.modify'), {
            'article': self.article.pk,
            'comment-v': u'Cet article est excellent',
            'valid-article': 'Demander validation',
            'is_major': True
        },
                               follow=False)
        self.assertEqual(pub.status_code, 302)
        self.assertEquals(len(mail.outbox), 1)
        mail.outbox = []

    def test_delete_image_on_change(self):
        """test que l'image est bien supprimée quand on la change"""

        root = settings.SITE_ROOT
        if not os.path.isdir(settings.MEDIA_ROOT):
            os.mkdir(settings.MEDIA_ROOT)
        shutil.copyfile(os.path.join(root, 'fixtures', 'logo.png'),
                        os.path.join(settings.MEDIA_ROOT, 'logo2.png'))
        shutil.copyfile(os.path.join(settings.MEDIA_ROOT, 'logo2.png'),
                        os.path.join(settings.MEDIA_ROOT, 'logo.png'))
        self.logo1 = os.path.join(settings.MEDIA_ROOT, 'logo.png')
        self.logo2 = os.path.join(settings.MEDIA_ROOT, 'logo2.png')

        self.article.image = self.logo1
        self.article.save()
        self.assertEqual(
            os.path.exists(
                os.path.join(settings.MEDIA_ROOT, self.article.image.name)),
            True)
        # now that we have a first image, let's change it

        oldAddress = self.article.image.name
        self.article.image = self.logo2
        self.article.save()
        self.assertEqual(
            os.path.exists(
                os.path.join(settings.MEDIA_ROOT, self.article.image.name)),
            True)
        self.assertEqual(
            os.path.exists(os.path.join(settings.MEDIA_ROOT, oldAddress)),
            False)
        os.unlink(self.logo2)
        # shutil.rmtree(settings.MEDIA_ROOT)

    def test_alert(self):
        user1 = ProfileFactory().user
        reaction = ReactionFactory(article=self.article,
                                   author=user1,
                                   position=1)
        login_check = self.client.login(username=self.user.username,
                                        password='******')
        self.assertEqual(login_check, True)
        # signal reaction
        result = self.client.post(reverse('zds.article.views.edit_reaction') +
                                  '?message={0}'.format(reaction.pk), {
                                      'signal_text': 'Troll',
                                      'signal_message': 'Confirmer',
                                  },
                                  follow=False)
        self.assertEqual(result.status_code, 302)
        self.assertEqual(Alert.objects.all().count(), 1)

        # connect with staff
        login_check = self.client.login(username=self.staff.username,
                                        password='******')
        self.assertEqual(login_check, True)
        # solve alert
        result = self.client.post(reverse('zds.article.views.solve_alert'), {
            'alert_pk': Alert.objects.first().pk,
            'text': 'Ok',
            'delete_message': 'Resoudre',
        },
                                  follow=False)
        self.assertEqual(result.status_code, 302)
        self.assertEqual(Alert.objects.all().count(), 0)
        self.assertEqual(
            PrivateTopic.objects.filter(author=self.user).count(), 1)
        self.assertEquals(len(mail.outbox), 0)

    def test_add_reaction(self):
        """To test add reaction for article."""
        user1 = ProfileFactory().user
        self.client.login(username=user1.username, password='******')

        # add empty reaction
        result = self.client.post(reverse('zds.article.views.answer') +
                                  '?article={0}'.format(self.article.pk), {
                                      'last_reaction': '0',
                                      'text': u''
                                  },
                                  follow=False)
        self.assertEqual(result.status_code, 200)
        # check reactions's number
        self.assertEqual(Reaction.objects.all().count(), 0)

        # add reaction
        result = self.client.post(
            reverse('zds.article.views.answer') +
            '?article={0}'.format(self.article.pk), {
                'last_reaction': '0',
                'text': u'Histoire de blablater dans les comms de l\'article'
            },
            follow=False)
        self.assertEqual(result.status_code, 302)

        # check reactions's number
        self.assertEqual(Reaction.objects.all().count(), 1)

        # check values
        art = Article.objects.get(pk=self.article.pk)
        first_art = Reaction.objects.first()
        self.assertEqual(first_art.article, art)
        self.assertEqual(first_art.author.pk, user1.pk)
        self.assertEqual(first_art.position, 1)
        self.assertEqual(first_art.pk, art.last_reaction.pk)
        self.assertEqual(
            Reaction.objects.first().text,
            u'Histoire de blablater dans les comms de l\'article')

        # test antispam return 403
        result = self.client.post(reverse('zds.article.views.answer') +
                                  '?article={0}'.format(self.article.pk), {
                                      'last_reaction': art.last_reaction.pk,
                                      'text': u'Histoire de tester l\'antispam'
                                  },
                                  follow=False)
        self.assertEqual(result.status_code, 403)

        ReactionFactory(article=self.article, position=2, author=self.staff)

        # test more reaction
        result = self.client.post(
            reverse('zds.article.views.answer') +
            '?article={0}'.format(self.article.pk), {
                'last_reaction': self.article.last_reaction.pk,
                'text': u'Histoire de tester l\'antispam'
            },
            follow=False)
        self.assertEqual(result.status_code, 302)

    def test_url_for_guest(self):
        """Test simple get request by guest."""

        # logout before
        self.client.logout()

        # guest can read public articles
        result = self.client.get(reverse(
            'zds.article.views.view_online',
            args=[self.article.pk, self.article.slug]),
                                 follow=True)
        self.assertEqual(result.status_code, 200)

        # guest can't read offline articles
        result = self.client.get(reverse(
            'zds.article.views.view',
            args=[self.article.pk, self.article.slug]),
                                 follow=False)
        self.assertEqual(result.status_code, 302)

    def test_url_for_member(self):
        """Test simple get request by simple member."""

        # logout before
        self.client.logout()
        # login with simple member
        self.assertEqual(
            self.client.login(username=self.user.username,
                              password='******'), True)

        # member who isn't author can read public articles
        result = self.client.get(reverse(
            'zds.article.views.view_online',
            args=[self.article.pk, self.article.slug]),
                                 follow=True)
        self.assertEqual(result.status_code, 200)

        # member who isn't author  can't read offline articles
        result = self.client.get(reverse(
            'zds.article.views.view',
            args=[self.article.pk, self.article.slug]),
                                 follow=True)
        self.assertEqual(result.status_code, 403)

    def test_url_for_author(self):
        """Test simple get request by author."""

        # logout before
        self.client.logout()
        # login with simple member
        self.assertEqual(
            self.client.login(username=self.user_author.username,
                              password='******'), True)

        # member who isn't author can read public articles
        result = self.client.get(reverse(
            'zds.article.views.view_online',
            args=[self.article.pk, self.article.slug]),
                                 follow=True)
        self.assertEqual(result.status_code, 200)

        # member who isn't author  can't read offline articles
        result = self.client.get(reverse(
            'zds.article.views.view',
            args=[self.article.pk, self.article.slug]),
                                 follow=True)
        self.assertEqual(result.status_code, 200)

    def test_url_for_staff(self):
        """Test simple get request by staff."""

        # logout before
        self.client.logout()
        # login with simple member
        self.assertEqual(
            self.client.login(username=self.staff.username,
                              password='******'), True)

        # member who isn't author can read public articles
        result = self.client.get(reverse(
            'zds.article.views.view_online',
            args=[self.article.pk, self.article.slug]),
                                 follow=True)
        self.assertEqual(result.status_code, 200)

        # member who isn't author  can't read offline articles
        result = self.client.get(reverse(
            'zds.article.views.view',
            args=[self.article.pk, self.article.slug]),
                                 follow=True)
        self.assertEqual(result.status_code, 200)

    def test_workflow_licence(self):
        '''Ensure the behavior of licence on articles'''

        # create a new licence
        new_licence = LicenceFactory(code='CC_BY', title='Creative Commons BY')
        new_licence = Licence.objects.get(pk=new_licence.pk)

        # check value first
        article = Article.objects.get(pk=self.article.pk)
        self.assertEqual(article.licence.pk, self.licence.pk)

        # logout before
        self.client.logout()
        # login with author
        self.assertTrue(
            self.client.login(username=self.user_author.username,
                              password='******'))

        # change licence (get 302) :
        result = self.client.post(
            reverse('zds.article.views.edit') +
            '?article={}'.format(self.article.pk), {
                'title': self.article.title,
                'description': self.article.description,
                'text': self.article.get_text(),
                'subcategory': self.article.subcategory.all(),
                'licence': new_licence.pk
            },
            follow=False)
        self.assertEqual(result.status_code, 302)

        # test change :
        article = Article.objects.get(pk=self.article.pk)
        self.assertNotEqual(article.licence.pk, self.licence.pk)
        self.assertEqual(article.licence.pk, new_licence.pk)

        # test change in JSON :
        json = article.load_json()
        self.assertEquals(json['licence'].code, new_licence.code)

        # then logout ...
        self.client.logout()
        # ... and login with staff
        self.assertTrue(
            self.client.login(username=self.staff.username,
                              password='******'))

        # change licence back to old one (get 302, staff can change licence) :
        result = self.client.post(
            reverse('zds.article.views.edit') +
            '?article={}'.format(self.article.pk), {
                'title': self.article.title,
                'description': self.article.description,
                'text': self.article.get_text(),
                'subcategory': self.article.subcategory.all(),
                'licence': self.licence.pk
            },
            follow=False)
        self.assertEqual(result.status_code, 302)

        # test change :
        article = Article.objects.get(pk=self.article.pk)
        self.assertEqual(article.licence.pk, self.licence.pk)
        self.assertNotEqual(article.licence.pk, new_licence.pk)

        # test change in JSON :
        json = article.load_json()
        self.assertEquals(json['licence'].code, self.licence.code)

        # then logout ...
        self.client.logout()

        # change licence (get 302, redirection to login page) :
        result = self.client.post(
            reverse('zds.article.views.edit') +
            '?article={}'.format(self.article.pk), {
                'title': self.article.title,
                'description': self.article.description,
                'text': self.article.get_text(),
                'subcategory': self.article.subcategory.all(),
                'licence': new_licence.pk
            },
            follow=False)
        self.assertEqual(result.status_code, 302)

        # test change (normaly, nothing has) :
        article = Article.objects.get(pk=self.article.pk)
        self.assertEqual(article.licence.pk, self.licence.pk)
        self.assertNotEqual(article.licence.pk, new_licence.pk)

        # login with random user
        self.assertTrue(
            self.client.login(username=self.user.username,
                              password='******'))

        # change licence (get 403, random user cannot edit article if not in
        # authors list) :
        result = self.client.post(
            reverse('zds.article.views.edit') +
            '?article={}'.format(self.article.pk), {
                'title': self.article.title,
                'description': self.article.description,
                'text': self.article.get_text(),
                'subcategory': self.article.subcategory.all(),
                'licence': new_licence.pk
            },
            follow=False)
        self.assertEqual(result.status_code, 403)

        # test change (normaly, nothing has) :
        article = Article.objects.get(pk=self.article.pk)
        self.assertEqual(article.licence.pk, self.licence.pk)
        self.assertNotEqual(article.licence.pk, new_licence.pk)

        # test change in JSON (normaly, nothing has) :
        json = article.load_json()
        self.assertEquals(json['licence'].code, self.licence.code)

    def test_workflow_archive_article(self):
        """ensure the behavior of archive with an article"""

        # login with author
        self.assertEqual(
            self.client.login(username=self.user_author.username,
                              password='******'), True)

        # modify article content and title (NOTE: zipfile does not ensure UTF-8)
        article_title = u'Le titre, mais pas pareil'
        article_content = u'Mais nous c\'est pas pareil ...'
        result = self.client.post(
            reverse('zds.article.views.edit') +
            '?article={}'.format(self.article.pk), {
                'title': article_title,
                'description': self.article.description,
                'text': article_content,
                'subcategory': self.article.subcategory.all(),
                'licence': self.licence.pk
            },
            follow=False)
        self.assertEqual(result.status_code, 302)

        # now, draft and public version are not the same
        article = Article.objects.get(pk=self.article.pk)
        self.assertNotEqual(article.sha_draft, article.sha_public)

        # fetch archives :
        # 1. draft version
        result = self.client.get(reverse('zds.article.views.download') +
                                 '?article={0}'.format(self.article.pk),
                                 follow=False)
        self.assertEqual(result.status_code, 200)
        draft_zip_path = os.path.join(tempfile.gettempdir(), '__draft.zip')
        f = open(draft_zip_path, 'w')
        f.write(result.content)
        f.close()
        # 2. online version :
        result = self.client.get(reverse('zds.article.views.download') +
                                 '?article={0}&online'.format(self.article.pk),
                                 follow=False)
        self.assertEqual(result.status_code, 200)
        online_zip_path = os.path.join(tempfile.gettempdir(), '__online.zip')
        f = open(online_zip_path, 'w')
        f.write(result.content)
        f.close()

        # now check if modification are in draft version of archive and not in the public one
        draft_zip = zipfile.ZipFile(draft_zip_path, 'r')
        online_zip = zipfile.ZipFile(online_zip_path, 'r')

        # first, test in manifest
        online_manifest = json_reader.loads(online_zip.read('manifest.json'))
        self.assertNotEqual(
            online_manifest['title'],
            article_title)  # title has not changed in online version

        draft_manifest = json_reader.loads(draft_zip.read('manifest.json'))
        self.assertNotEqual(
            online_manifest['title'],
            article_title)  # title has not changed in online version

        self.assertNotEqual(online_zip.read(online_manifest['text']),
                            article_content)
        self.assertEqual(draft_zip.read(draft_manifest['text']),
                         article_content)  # content is good in draft

        draft_zip.close()
        online_zip.close()

        # then logout and test access
        self.client.logout()

        # public cannot access to draft version of article
        result = self.client.get(reverse('zds.article.views.download') +
                                 '?article={0}'.format(self.article.pk),
                                 follow=False)
        self.assertEqual(result.status_code, 403)
        # ... but can access to online version
        result = self.client.get(reverse('zds.article.views.download') +
                                 '?article={0}&online'.format(self.article.pk),
                                 follow=False)
        self.assertEqual(result.status_code, 200)

        # login with random user
        self.assertEqual(
            self.client.login(username=self.user.username,
                              password='******'), True)

        # cannot access to draft version of article (if not author or staff)
        result = self.client.get(reverse('zds.article.views.download') +
                                 '?article={0}'.format(self.article.pk),
                                 follow=False)
        self.assertEqual(result.status_code, 403)
        # but can access to online one
        result = self.client.get(reverse('zds.article.views.download') +
                                 '?article={0}&online'.format(self.article.pk),
                                 follow=False)
        self.assertEqual(result.status_code, 200)
        self.client.logout()

        # login with staff user
        self.assertEqual(
            self.client.login(username=self.staff.username,
                              password='******'), True)

        # staff can access to draft version of article
        result = self.client.get(reverse('zds.article.views.download') +
                                 '?article={0}'.format(self.article.pk),
                                 follow=False)
        self.assertEqual(result.status_code, 200)
        # ... and also to online version
        result = self.client.get(reverse('zds.article.views.download') +
                                 '?article={0}&online'.format(self.article.pk),
                                 follow=False)
        self.assertEqual(result.status_code, 200)

        # finally, clean up things:
        os.remove(draft_zip_path)
        os.remove(online_zip_path)

    def tearDown(self):
        if os.path.isdir(settings.ZDS_APP['article']['repo_path']):
            shutil.rmtree(settings.ZDS_APP['article']['repo_path'])
        if os.path.isdir(settings.MEDIA_ROOT):
            shutil.rmtree(settings.MEDIA_ROOT)
コード例 #9
0
ファイル: tests.py プロジェクト: Aer-o/zds-site
    def setUp(self):

        settings.EMAIL_BACKEND = \
            'django.core.mail.backends.locmem.EmailBackend'
        self.mas = ProfileFactory().user
        settings.BOT_ACCOUNT = self.mas.username

        self.user_author = ProfileFactory().user
        self.user = ProfileFactory().user
        self.staff = StaffProfileFactory().user

        self.article = ArticleFactory()
        self.article.authors.add(self.user_author)
        self.article.save()

        # connect with user
        login_check = self.client.login(
            username=self.user_author.username,
            password='******')
        self.assertEqual(login_check, True)

        # ask public article
        pub = self.client.post(
            reverse('zds.article.views.modify'),
            {
                'article': self.article.pk,
                'comment': u'Valides moi ce bébé',
                'pending': 'Demander validation',
                'version': self.article.sha_draft,
                'is_major': True
            },
            follow=False)
        self.assertEqual(pub.status_code, 302)
        self.assertEqual(Validation.objects.count(), 1)

        login_check = self.client.login(
            username=self.staff.username,
            password='******')
        self.assertEqual(login_check, True)

        # reserve tutorial
        validation = Validation.objects.get(
            article__pk=self.article.pk)
        pub = self.client.post(
            reverse('zds.article.views.reservation', args=[validation.pk]),
            follow=False)
        self.assertEqual(pub.status_code, 302)

        # publish article
        pub = self.client.post(
            reverse('zds.article.views.modify'),
            {
                'article': self.article.pk,
                'comment-v': u'Cet article est excellent',
                'valid-article': 'Demander validation',
                'is_major': True
            },
            follow=False)
        self.assertEqual(pub.status_code, 302)
        self.assertEquals(len(mail.outbox), 1)
        mail.outbox = []
コード例 #10
0
ファイル: tests.py プロジェクト: Aer-o/zds-site
class ArticleTests(TestCase):

    def setUp(self):

        settings.EMAIL_BACKEND = \
            'django.core.mail.backends.locmem.EmailBackend'
        self.mas = ProfileFactory().user
        settings.BOT_ACCOUNT = self.mas.username

        self.user_author = ProfileFactory().user
        self.user = ProfileFactory().user
        self.staff = StaffProfileFactory().user

        self.article = ArticleFactory()
        self.article.authors.add(self.user_author)
        self.article.save()

        # connect with user
        login_check = self.client.login(
            username=self.user_author.username,
            password='******')
        self.assertEqual(login_check, True)

        # ask public article
        pub = self.client.post(
            reverse('zds.article.views.modify'),
            {
                'article': self.article.pk,
                'comment': u'Valides moi ce bébé',
                'pending': 'Demander validation',
                'version': self.article.sha_draft,
                'is_major': True
            },
            follow=False)
        self.assertEqual(pub.status_code, 302)
        self.assertEqual(Validation.objects.count(), 1)

        login_check = self.client.login(
            username=self.staff.username,
            password='******')
        self.assertEqual(login_check, True)

        # reserve tutorial
        validation = Validation.objects.get(
            article__pk=self.article.pk)
        pub = self.client.post(
            reverse('zds.article.views.reservation', args=[validation.pk]),
            follow=False)
        self.assertEqual(pub.status_code, 302)

        # publish article
        pub = self.client.post(
            reverse('zds.article.views.modify'),
            {
                'article': self.article.pk,
                'comment-v': u'Cet article est excellent',
                'valid-article': 'Demander validation',
                'is_major': True
            },
            follow=False)
        self.assertEqual(pub.status_code, 302)
        self.assertEquals(len(mail.outbox), 1)
        mail.outbox = []

    def test_delete_image_on_change(self):
        """test que l'image est bien supprimée quand on la change"""

        root = settings.SITE_ROOT
        if not os.path.isdir(settings.MEDIA_ROOT):
            os.mkdir(settings.MEDIA_ROOT)
        shutil.copyfile(
            os.path.join(root, 'fixtures', 'logo.png'),
            os.path.join(settings.MEDIA_ROOT, 'logo2.png')
        )
        shutil.copyfile(
            os.path.join(settings.MEDIA_ROOT, 'logo2.png'),
            os.path.join(settings.MEDIA_ROOT, 'logo.png')
        )
        self.logo1 = os.path.join(settings.MEDIA_ROOT, 'logo.png')
        self.logo2 = os.path.join(settings.MEDIA_ROOT, 'logo2.png')

        self.article.image = self.logo1
        self.article.save()
        self.assertEqual(
            os.path.exists(
                os.path.join(
                    settings.MEDIA_ROOT, self.article.image.name
                )
            ),
            True
        )
        # now that we have a first image, let's change it

        oldAddress = self.article.image.name
        self.article.image = self.logo2
        self.article.save()
        self.assertEqual(
            os.path.exists(
                os.path.join(
                    settings.MEDIA_ROOT, self.article.image.name
                )
            ),
            True
        )
        self.assertEqual(
            os.path.exists(
                os.path.join(settings.MEDIA_ROOT, oldAddress)
            ),
            False
        )
        os.unlink(self.logo2)
        # shutil.rmtree(settings.MEDIA_ROOT)

    def test_alert(self):
        user1 = ProfileFactory().user
        reaction = ReactionFactory(
            article=self.article,
            author=user1,
            position=1)
        login_check = self.client.login(
            username=self.user.username,
            password='******')
        self.assertEqual(login_check, True)
        # signal reaction
        result = self.client.post(
            reverse('zds.article.views.edit_reaction') +
            '?message={0}'.format(
                reaction.pk),
            {
                'signal_text': 'Troll',
                'signal_message': 'Confirmer',
            },
            follow=False)
        self.assertEqual(result.status_code, 302)
        self.assertEqual(Alert.objects.all().count(), 1)

        # connect with staff
        login_check = self.client.login(
            username=self.staff.username,
            password='******')
        self.assertEqual(login_check, True)
        # solve alert
        result = self.client.post(
            reverse('zds.article.views.solve_alert'),
            {
                'alert_pk': Alert.objects.first().pk,
                'text': 'Ok',
                'delete_message': 'Resoudre',
            },
            follow=False)
        self.assertEqual(result.status_code, 302)
        self.assertEqual(Alert.objects.all().count(), 0)
        self.assertEqual(
            PrivateTopic.objects.filter(
                author=self.user).count(),
            1)
        self.assertEquals(len(mail.outbox), 0)

    def test_add_reaction(self):
        """To test add reaction for article."""
        user1 = ProfileFactory().user
        self.client.login(username=user1.username, password='******')

        # add empty reaction
        result = self.client.post(
            reverse('zds.article.views.answer') +
            '?article={0}'.format(
                self.article.pk),
            {
                'last_reaction': '0',
                'text': u''},
            follow=False)
        self.assertEqual(result.status_code, 200)
        # check reactions's number
        self.assertEqual(Reaction.objects.all().count(), 0)

        # add reaction
        result = self.client.post(
            reverse('zds.article.views.answer') +
            '?article={0}'.format(
                self.article.pk),
            {
                'last_reaction': '0',
                'text': u'Histoire de blablater dans les comms de l\'article'},
            follow=False)
        self.assertEqual(result.status_code, 302)

        # check reactions's number
        self.assertEqual(Reaction.objects.all().count(), 1)

        # check values
        art = Article.objects.get(pk=self.article.pk)
        self.assertEqual(Reaction.objects.get(pk=1).article, art)
        self.assertEqual(Reaction.objects.get(pk=1).author.pk, user1.pk)
        self.assertEqual(Reaction.objects.get(pk=1).position, 1)
        self.assertEqual(Reaction.objects.get(pk=1).pk, art.last_reaction.pk)
        self.assertEqual(
            Reaction.objects.get(
                pk=1).text,
            u'Histoire de blablater dans les comms de l\'article')

        # test antispam return 403
        result = self.client.post(
            reverse('zds.article.views.answer') +
            '?article={0}'.format(
                self.article.pk),
            {
                'last_reaction': art.last_reaction.pk,
                'text': u'Histoire de tester l\'antispam'},
            follow=False)
        self.assertEqual(result.status_code, 403)

        ReactionFactory(
            article=self.article,
            position=2,
            author=self.staff)

        # test more reaction
        result = self.client.post(
            reverse('zds.article.views.answer') +
            '?article={0}'.format(
                self.article.pk),
            {
                'last_reaction': self.article.last_reaction.pk,
                'text': u'Histoire de tester l\'antispam'},
            follow=False)
        self.assertEqual(result.status_code, 302)

    def test_url_for_guest(self):
        """Test simple get request by guest."""

        # logout before
        self.client.logout()

        # guest can read public articles
        result = self.client.get(
            reverse(
                'zds.article.views.view_online',
                args=[
                    self.article.pk,
                    self.article.slug]),
            follow=True)
        self.assertEqual(result.status_code, 200)

        # guest can't read offline articles
        result = self.client.get(
            reverse(
                'zds.article.views.view',
                args=[
                    self.article.pk,
                    self.article.slug]),
            follow=False)
        self.assertEqual(result.status_code, 302)

    def test_url_for_member(self):
        """Test simple get request by simple member."""

        # logout before
        self.client.logout()
        # login with simple member
        self.assertEqual(
            self.client.login(
                username=self.user.username,
                password='******'),
            True)

        # member who isn't author can read public articles
        result = self.client.get(
            reverse(
                'zds.article.views.view_online',
                args=[
                    self.article.pk,
                    self.article.slug]),
            follow=True)
        self.assertEqual(result.status_code, 200)

        # member who isn't author  can't read offline articles
        result = self.client.get(
            reverse(
                'zds.article.views.view',
                args=[
                    self.article.pk,
                    self.article.slug]),
            follow=True)
        self.assertEqual(result.status_code, 403)

    def test_url_for_author(self):
        """Test simple get request by author."""

        # logout before
        self.client.logout()
        # login with simple member
        self.assertEqual(
            self.client.login(
                username=self.user_author.username,
                password='******'),
            True)

        # member who isn't author can read public articles
        result = self.client.get(
            reverse(
                'zds.article.views.view_online',
                args=[
                    self.article.pk,
                    self.article.slug]),
            follow=True)
        self.assertEqual(result.status_code, 200)

        # member who isn't author  can't read offline articles
        result = self.client.get(
            reverse(
                'zds.article.views.view',
                args=[
                    self.article.pk,
                    self.article.slug]),
            follow=True)
        self.assertEqual(result.status_code, 200)

    def test_url_for_staff(self):
        """Test simple get request by staff."""

        # logout before
        self.client.logout()
        # login with simple member
        self.assertEqual(
            self.client.login(
                username=self.staff.username,
                password='******'),
            True)

        # member who isn't author can read public articles
        result = self.client.get(
            reverse(
                'zds.article.views.view_online',
                args=[
                    self.article.pk,
                    self.article.slug]),
            follow=True)
        self.assertEqual(result.status_code, 200)

        # member who isn't author  can't read offline articles
        result = self.client.get(
            reverse(
                'zds.article.views.view',
                args=[
                    self.article.pk,
                    self.article.slug]),
            follow=True)
        self.assertEqual(result.status_code, 200)

    def tearDown(self):
        if os.path.isdir(settings.REPO_ARTICLE_PATH):
            shutil.rmtree(settings.REPO_ARTICLE_PATH)
        if os.path.isdir(settings.MEDIA_ROOT):
            shutil.rmtree(settings.MEDIA_ROOT)
コード例 #11
0
    def test_unregister(self):
        """Tests that unregistering user is working"""

        # test not logged user can't unregister
        self.client.logout()
        result = self.client.post(reverse('zds.member.views.unregister'),
                                  follow=False)
        self.assertEqual(result.status_code, 302)
        user = ProfileFactory()
        login_check = self.client.login(username=user.user.username,
                                        password='******')
        self.assertEqual(login_check, True)
        result = self.client.post(reverse('zds.member.views.unregister'),
                                  follow=False)
        self.assertEqual(result.status_code, 302)
        self.assertEqual(
            User.objects.filter(username=user.user.username).count(), 0)
        user = ProfileFactory()
        user2 = ProfileFactory()
        aloneGallery = GalleryFactory()
        UserGalleryFactory(gallery=aloneGallery, user=user.user)
        sharedGallery = GalleryFactory()
        UserGalleryFactory(gallery=sharedGallery, user=user.user)
        UserGalleryFactory(gallery=sharedGallery, user=user2.user)
        # first case : a published tutorial with only one author
        publishedTutorialAlone = MiniTutorialFactory(light=True)
        publishedTutorialAlone.authors.add(user.user)
        publishedTutorialAlone.save()
        # second case : a published tutorial with two authors
        publishedTutorial2 = MiniTutorialFactory(light=True)
        publishedTutorial2.authors.add(user.user)
        publishedTutorial2.authors.add(user2.user)
        publishedTutorial2.save()
        # third case : a private tutorial with only one author
        writingTutorialAlone = MiniTutorialFactory(light=True)
        writingTutorialAlone.authors.add(user.user)
        writingTutorialAlone.save()
        writingTutorialAloneGallerPath = writingTutorialAlone.gallery.get_gallery_path(
        )
        writingTutorialAlonePath = writingTutorialAlone.get_path()
        # fourth case : a private tutorial with at least two authors
        writingTutorial2 = MiniTutorialFactory(light=True)
        writingTutorial2.authors.add(user.user)
        writingTutorial2.authors.add(user2.user)
        writingTutorial2.save()
        self.client.login(username=self.staff.username, password="******")
        pub = self.client.post(reverse('zds.tutorial.views.ask_validation'), {
            'tutorial': publishedTutorialAlone.pk,
            'text': u'Ce tuto est excellent',
            'version': publishedTutorialAlone.sha_draft,
            'source': 'http://zestedesavoir.com',
        },
                               follow=False)
        self.assertEqual(pub.status_code, 302)
        # reserve tutorial
        validation = Validation.objects.get(
            tutorial__pk=publishedTutorialAlone.pk)
        pub = self.client.post(reverse('zds.tutorial.views.reservation',
                                       args=[validation.pk]),
                               follow=False)
        self.assertEqual(pub.status_code, 302)
        # publish tutorial
        pub = self.client.post(reverse('zds.tutorial.views.valid_tutorial'), {
            'tutorial': publishedTutorialAlone.pk,
            'text': u'Ce tuto est excellent',
            'is_major': True,
            'source': 'http://zestedesavoir.com',
        },
                               follow=False)
        pub = self.client.post(reverse('zds.tutorial.views.ask_validation'), {
            'tutorial': publishedTutorial2.pk,
            'text': u'Ce tuto est excellent',
            'version': publishedTutorial2.sha_draft,
            'source': 'http://zestedesavoir.com',
        },
                               follow=False)
        self.assertEqual(pub.status_code, 302)
        # reserve tutorial
        validation = Validation.objects.get(tutorial__pk=publishedTutorial2.pk)
        pub = self.client.post(reverse('zds.tutorial.views.reservation',
                                       args=[validation.pk]),
                               follow=False)
        self.assertEqual(pub.status_code, 302)
        # publish tutorial
        pub = self.client.post(reverse('zds.tutorial.views.valid_tutorial'), {
            'tutorial': publishedTutorial2.pk,
            'text': u'Ce tuto est excellent',
            'is_major': True,
            'source': 'http://zestedesavoir.com',
        },
                               follow=False)
        # same thing for articles
        publishedArticleAlone = ArticleFactory()
        publishedArticleAlone.authors.add(user.user)
        publishedArticleAlone.save()
        publishedArticle2 = ArticleFactory()
        publishedArticle2.authors.add(user.user)
        publishedArticle2.authors.add(user2.user)
        publishedArticle2.save()

        writingArticleAlone = ArticleFactory()
        writingArticleAlone.authors.add(user.user)
        writingArticleAlone.save()
        writingArticle2 = ArticleFactory()
        writingArticle2.authors.add(user.user)
        writingArticle2.authors.add(user2.user)
        writingArticle2.save()
        # ask public article
        pub = self.client.post(reverse('zds.article.views.modify'), {
            'article': publishedArticleAlone.pk,
            'comment': u'Valides moi ce bébé',
            'pending': 'Demander validation',
            'version': publishedArticleAlone.sha_draft,
            'is_major': True
        },
                               follow=False)
        self.assertEqual(pub.status_code, 302)

        login_check = self.client.login(username=self.staff.username,
                                        password='******')
        self.assertEqual(login_check, True)

        # reserve article
        validation = ArticleValidation.objects.get(
            article__pk=publishedArticleAlone.pk)
        pub = self.client.post(reverse('zds.article.views.reservation',
                                       args=[validation.pk]),
                               follow=False)
        self.assertEqual(pub.status_code, 302)

        # publish article
        pub = self.client.post(reverse('zds.article.views.modify'), {
            'article': publishedArticleAlone.pk,
            'comment-v': u'Cet article est excellent',
            'valid-article': 'Demander validation',
            'is_major': True
        },
                               follow=False)
        self.assertEqual(pub.status_code, 302)
        # ask public article
        pub = self.client.post(reverse('zds.article.views.modify'), {
            'article': publishedArticle2.pk,
            'comment': u'Valides moi ce bébé',
            'pending': 'Demander validation',
            'version': publishedArticle2.sha_draft,
            'is_major': True
        },
                               follow=False)
        self.assertEqual(pub.status_code, 302)

        login_check = self.client.login(username=self.staff.username,
                                        password='******')
        self.assertEqual(login_check, True)

        # reserve article
        validation = ArticleValidation.objects.get(
            article__pk=publishedArticle2.pk)
        pub = self.client.post(reverse('zds.article.views.reservation',
                                       args=[validation.pk]),
                               follow=False)
        self.assertEqual(pub.status_code, 302)

        # publish article
        pub = self.client.post(reverse('zds.article.views.modify'), {
            'article': publishedArticle2.pk,
            'comment-v': u'Cet article est excellent',
            'valid-article': 'Demander validation',
            'is_major': True
        },
                               follow=False)
        self.assertEqual(pub.status_code, 302)
        # about posts and topics
        authoredTopic = TopicFactory(author=user.user, forum=self.forum11)
        answeredTopic = TopicFactory(author=user2.user, forum=self.forum11)
        PostFactory(topic=answeredTopic, author=user.user, position=2)
        editedAnswer = PostFactory(topic=answeredTopic,
                                   author=user.user,
                                   position=3)
        editedAnswer.editor = user.user
        editedAnswer.save()
        privateTopic = PrivateTopicFactory(author=user.user)
        privateTopic.participants.add(user2.user)
        privateTopic.save()
        PrivatePostFactory(author=user.user,
                           privatetopic=privateTopic,
                           position_in_topic=1)
        login_check = self.client.login(username=user.user.username,
                                        password='******')
        self.assertEqual(login_check, True)
        result = self.client.post(reverse('zds.member.views.unregister'),
                                  follow=False)
        self.assertEqual(result.status_code, 302)
        self.assertEqual(publishedTutorialAlone.authors.count(), 1)
        self.assertEqual(publishedTutorialAlone.authors.first().username,
                         settings.ZDS_APP["member"]["external_account"])
        self.assertFalse(os.path.exists(writingTutorialAloneGallerPath))
        self.assertEqual(publishedTutorial2.authors.count(), 1)
        self.assertEqual(
            publishedTutorial2.authors.filter(
                username=settings.ZDS_APP["member"]
                ["external_account"]).count(), 0)
        self.assertIsNotNone(publishedTutorial2.get_prod_path())
        self.assertTrue(os.path.exists(publishedTutorial2.get_prod_path()))
        self.assertIsNotNone(publishedTutorialAlone.get_prod_path())
        self.assertTrue(os.path.exists(publishedTutorialAlone.get_prod_path()))
        self.assertEqual(
            self.client.get(reverse(
                'zds.tutorial.views.view_tutorial_online',
                args=[publishedTutorialAlone.pk, publishedTutorialAlone.slug]),
                            follow=False).status_code, 200)
        self.assertEqual(
            self.client.get(reverse(
                'zds.tutorial.views.view_tutorial_online',
                args=[publishedTutorial2.pk, publishedTutorial2.slug]),
                            follow=False).status_code, 200)
        self.assertTrue(os.path.exists(publishedArticleAlone.get_path()))
        self.assertEqual(
            self.client.get(reverse(
                'zds.article.views.view_online',
                args=[publishedArticleAlone.pk, publishedArticleAlone.slug]),
                            follow=True).status_code, 200)
        self.assertEqual(
            self.client.get(reverse(
                'zds.article.views.view_online',
                args=[publishedArticle2.pk, publishedArticle2.slug]),
                            follow=True).status_code, 200)
        self.assertEqual(
            Tutorial.objects.filter(pk=writingTutorialAlone.pk).count(), 0)
        self.assertEqual(writingTutorial2.authors.count(), 1)
        self.assertEqual(
            writingTutorial2.authors.filter(username=settings.ZDS_APP["member"]
                                            ["external_account"]).count(), 0)
        self.assertEqual(publishedArticleAlone.authors.count(), 1)
        self.assertEqual(publishedArticleAlone.authors.first().username,
                         settings.ZDS_APP["member"]["external_account"])
        self.assertEqual(publishedArticle2.authors.count(), 1)
        self.assertEqual(
            publishedArticle2.authors.filter(
                username=settings.ZDS_APP["member"]
                ["external_account"]).count(), 0)
        self.assertEqual(
            Article.objects.filter(pk=writingArticleAlone.pk).count(), 0)
        self.assertEqual(writingArticle2.authors.count(), 1)
        self.assertEqual(
            writingArticle2.authors.filter(username=settings.ZDS_APP["member"]
                                           ["external_account"]).count(), 0)
        self.assertEqual(
            Topic.objects.filter(author__username=user.user.username).count(),
            0)
        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.assertFalse(os.path.exists(writingTutorialAlonePath))
        self.assertIsNotNone(Topic.objects.get(pk=authoredTopic.pk))
        self.assertIsNotNone(PrivateTopic.objects.get(pk=privateTopic.pk))
        self.assertIsNotNone(Gallery.objects.get(pk=aloneGallery.pk))
        self.assertEquals(aloneGallery.get_users().count(), 1)
        self.assertEquals(sharedGallery.get_users().count(), 1)
        self.assertEquals(
            UserGallery.objects.filter(user=user.user).count(), 0)
コード例 #12
0
ファイル: load_fixtures.py プロジェクト: Lucas-ech/zds-site
def load_articles(cli, size, fake):
    """
    Load articles
    """

    articles = []

    nb_arts = size * 10
    percent_arts_in_validation = 0.4
    percent_arts_with_validator = 0.2
    percent_arts_public = 0.3
    cli.stdout.write(u"Nombres d'articles à créer : {}".format(nb_arts))
    cli.stdout.write(u"Nombres d'articles en validations : {}"
                     .format(str(int(nb_arts * percent_arts_in_validation))))
    cli.stdout.write(u"Nombres d'articles réservé en validations : {}"
                     .format(str(int(nb_arts * percent_arts_with_validator))))
    cli.stdout.write(u"Nombres d'articles publiés : {}"
                     .format(str(int(nb_arts * percent_arts_public))))
    tps1 = time.time()
    nb_users = User.objects.count()
    if nb_users == 0:
        cli.stdout.write(u"Il n'y a aucun membre actuellement."
                         u"Vous devez rajouter les membre dans vos fixtures (member)")
    else:
        nb_sub_categories = SubCategory.objects.count()
        if nb_sub_categories == 0:
            cli.stdout.write(u"Il n'y a aucune catégories actuellement."
                             u"Vous devez rajouter les membre dans vos fixtures (category_content)")
        else:
            sub_categories = list(SubCategory.objects.all())
            profiles = list(Profile.objects.all())
            perms = list(Permission.objects.filter(codename__startswith='change_').all())
            staffs = list(User.objects.filter(groups__permissions__in=perms).all())
            nb_staffs = len(staffs)
            if nb_staffs == 0:
                cli.stdout.write(u"Il n'y a aucun staff actuellement."
                                 u"Vous devez rajouter les staffs dans vos fixtures (staff)")
            else:
                for i in range(0, nb_arts):
                    art = ArticleFactory(title=fake.text(max_nb_chars=80),
                                         description=fake.sentence(nb_words=15, variable_nb_words=True))
                    art.authors.add(profiles[i % nb_users].user)
                    art.subcategory.add(sub_categories[random.randint(0, nb_sub_categories - 1)])
                    articles.append(art)

                    if i < int(nb_arts * percent_arts_with_validator):
                        validator = staffs[random.randint(0, nb_staffs - 1)]
                        valid = AValidation(article=art,
                                            version=art.sha_draft,
                                            date_proposition=datetime.now(),
                                            date_reserve=datetime.now(),
                                            validator=validator,
                                            status="PENDING_V")
                        valid.save()
                        art.sha_validation = art.sha_draft
                        art.save()
                    elif i < int(nb_arts * (percent_arts_in_validation +
                                            percent_arts_with_validator)):
                        valid = AValidation(article=art,
                                            version=art.sha_draft,
                                            date_proposition=datetime.now())
                        valid.save()
                        art.sha_validation = art.sha_draft
                        art.save()
                    elif i < int(nb_arts * (percent_arts_in_validation +
                                            percent_arts_with_validator +
                                            percent_arts_public)):
                        mep_art(art, art.sha_draft)
                        valid = AValidation(article=art,
                                            version=art.sha_draft,
                                            date_proposition=datetime.now(),
                                            date_reserve=datetime.now(),
                                            validator=validator,
                                            status="ACCEPT",
                                            comment_validator=fake.text(max_nb_chars=200),
                                            date_validation=datetime.now())
                        valid.save()
                        art.sha_public = art.sha_draft
                        art.pubdate = datetime.now()
                        art.save()
                    sys.stdout.write(" Article {}/{}  \r".format(i + 1, nb_arts))
                    sys.stdout.flush()

                tps2 = time.time()
                cli.stdout.write(u"\nFait en {} sec".format(tps2 - tps1))
コード例 #13
0
ファイル: tests.py プロジェクト: Dryusdan/zds-site
class ArticleTests(TestCase):
    def setUp(self):

        settings.EMAIL_BACKEND = "django.core.mail.backends.locmem.EmailBackend"
        self.mas = ProfileFactory().user
        settings.BOT_ACCOUNT = self.mas.username

        self.user_author = ProfileFactory().user
        self.user = ProfileFactory().user
        self.staff = StaffProfileFactory().user

        self.licence = LicenceFactory()

        self.article = ArticleFactory()
        self.article.authors.add(self.user_author)
        self.article.licence = self.licence
        self.article.save()

        # connect with user
        login_check = self.client.login(username=self.user_author.username, password="******")
        self.assertEqual(login_check, True)

        # ask public article
        pub = self.client.post(
            reverse("zds.article.views.modify"),
            {
                "article": self.article.pk,
                "comment": u"Valides moi ce bébé",
                "pending": "Demander validation",
                "version": self.article.sha_draft,
                "is_major": True,
            },
            follow=False,
        )
        self.assertEqual(pub.status_code, 302)
        self.assertEqual(Validation.objects.count(), 1)

        login_check = self.client.login(username=self.staff.username, password="******")
        self.assertEqual(login_check, True)

        # reserve tutorial
        validation = Validation.objects.get(article__pk=self.article.pk)
        pub = self.client.post(reverse("zds.article.views.reservation", args=[validation.pk]), follow=False)
        self.assertEqual(pub.status_code, 302)

        # publish article
        pub = self.client.post(
            reverse("zds.article.views.modify"),
            {
                "article": self.article.pk,
                "comment-v": u"Cet article est excellent",
                "valid-article": "Demander validation",
                "is_major": True,
            },
            follow=False,
        )
        self.assertEqual(pub.status_code, 302)
        self.assertEquals(len(mail.outbox), 1)
        mail.outbox = []

    def test_delete_image_on_change(self):
        """test que l'image est bien supprimée quand on la change"""

        root = settings.SITE_ROOT
        if not os.path.isdir(settings.MEDIA_ROOT):
            os.mkdir(settings.MEDIA_ROOT)
        shutil.copyfile(os.path.join(root, "fixtures", "logo.png"), os.path.join(settings.MEDIA_ROOT, "logo2.png"))
        shutil.copyfile(os.path.join(settings.MEDIA_ROOT, "logo2.png"), os.path.join(settings.MEDIA_ROOT, "logo.png"))
        self.logo1 = os.path.join(settings.MEDIA_ROOT, "logo.png")
        self.logo2 = os.path.join(settings.MEDIA_ROOT, "logo2.png")

        self.article.image = self.logo1
        self.article.save()
        self.assertEqual(os.path.exists(os.path.join(settings.MEDIA_ROOT, self.article.image.name)), True)
        # now that we have a first image, let's change it

        oldAddress = self.article.image.name
        self.article.image = self.logo2
        self.article.save()
        self.assertEqual(os.path.exists(os.path.join(settings.MEDIA_ROOT, self.article.image.name)), True)
        self.assertEqual(os.path.exists(os.path.join(settings.MEDIA_ROOT, oldAddress)), False)
        os.unlink(self.logo2)
        # shutil.rmtree(settings.MEDIA_ROOT)

    def test_alert(self):
        user1 = ProfileFactory().user
        reaction = ReactionFactory(article=self.article, author=user1, position=1)
        login_check = self.client.login(username=self.user.username, password="******")
        self.assertEqual(login_check, True)
        # signal reaction
        result = self.client.post(
            reverse("zds.article.views.edit_reaction") + "?message={0}".format(reaction.pk),
            {"signal_text": "Troll", "signal_message": "Confirmer"},
            follow=False,
        )
        self.assertEqual(result.status_code, 302)
        self.assertEqual(Alert.objects.all().count(), 1)

        # connect with staff
        login_check = self.client.login(username=self.staff.username, password="******")
        self.assertEqual(login_check, True)
        # solve alert
        result = self.client.post(
            reverse("zds.article.views.solve_alert"),
            {"alert_pk": Alert.objects.first().pk, "text": "Ok", "delete_message": "Resoudre"},
            follow=False,
        )
        self.assertEqual(result.status_code, 302)
        self.assertEqual(Alert.objects.all().count(), 0)
        self.assertEqual(PrivateTopic.objects.filter(author=self.user).count(), 1)
        self.assertEquals(len(mail.outbox), 0)

    def test_add_reaction(self):
        """To test add reaction for article."""
        user1 = ProfileFactory().user
        self.client.login(username=user1.username, password="******")

        # add empty reaction
        result = self.client.post(
            reverse("zds.article.views.answer") + "?article={0}".format(self.article.pk),
            {"last_reaction": "0", "text": u""},
            follow=False,
        )
        self.assertEqual(result.status_code, 200)
        # check reactions's number
        self.assertEqual(Reaction.objects.all().count(), 0)

        # add reaction
        result = self.client.post(
            reverse("zds.article.views.answer") + "?article={0}".format(self.article.pk),
            {"last_reaction": "0", "text": u"Histoire de blablater dans les comms de l'article"},
            follow=False,
        )
        self.assertEqual(result.status_code, 302)

        # check reactions's number
        self.assertEqual(Reaction.objects.all().count(), 1)

        # check values
        art = Article.objects.get(pk=self.article.pk)
        self.assertEqual(Reaction.objects.get(pk=1).article, art)
        self.assertEqual(Reaction.objects.get(pk=1).author.pk, user1.pk)
        self.assertEqual(Reaction.objects.get(pk=1).position, 1)
        self.assertEqual(Reaction.objects.get(pk=1).pk, art.last_reaction.pk)
        self.assertEqual(Reaction.objects.get(pk=1).text, u"Histoire de blablater dans les comms de l'article")

        # test antispam return 403
        result = self.client.post(
            reverse("zds.article.views.answer") + "?article={0}".format(self.article.pk),
            {"last_reaction": art.last_reaction.pk, "text": u"Histoire de tester l'antispam"},
            follow=False,
        )
        self.assertEqual(result.status_code, 403)

        ReactionFactory(article=self.article, position=2, author=self.staff)

        # test more reaction
        result = self.client.post(
            reverse("zds.article.views.answer") + "?article={0}".format(self.article.pk),
            {"last_reaction": self.article.last_reaction.pk, "text": u"Histoire de tester l'antispam"},
            follow=False,
        )
        self.assertEqual(result.status_code, 302)

    def test_url_for_guest(self):
        """Test simple get request by guest."""

        # logout before
        self.client.logout()

        # guest can read public articles
        result = self.client.get(
            reverse("zds.article.views.view_online", args=[self.article.pk, self.article.slug]), follow=True
        )
        self.assertEqual(result.status_code, 200)

        # guest can't read offline articles
        result = self.client.get(
            reverse("zds.article.views.view", args=[self.article.pk, self.article.slug]), follow=False
        )
        self.assertEqual(result.status_code, 302)

    def test_url_for_member(self):
        """Test simple get request by simple member."""

        # logout before
        self.client.logout()
        # login with simple member
        self.assertEqual(self.client.login(username=self.user.username, password="******"), True)

        # member who isn't author can read public articles
        result = self.client.get(
            reverse("zds.article.views.view_online", args=[self.article.pk, self.article.slug]), follow=True
        )
        self.assertEqual(result.status_code, 200)

        # member who isn't author  can't read offline articles
        result = self.client.get(
            reverse("zds.article.views.view", args=[self.article.pk, self.article.slug]), follow=True
        )
        self.assertEqual(result.status_code, 403)

    def test_url_for_author(self):
        """Test simple get request by author."""

        # logout before
        self.client.logout()
        # login with simple member
        self.assertEqual(self.client.login(username=self.user_author.username, password="******"), True)

        # member who isn't author can read public articles
        result = self.client.get(
            reverse("zds.article.views.view_online", args=[self.article.pk, self.article.slug]), follow=True
        )
        self.assertEqual(result.status_code, 200)

        # member who isn't author  can't read offline articles
        result = self.client.get(
            reverse("zds.article.views.view", args=[self.article.pk, self.article.slug]), follow=True
        )
        self.assertEqual(result.status_code, 200)

    def test_url_for_staff(self):
        """Test simple get request by staff."""

        # logout before
        self.client.logout()
        # login with simple member
        self.assertEqual(self.client.login(username=self.staff.username, password="******"), True)

        # member who isn't author can read public articles
        result = self.client.get(
            reverse("zds.article.views.view_online", args=[self.article.pk, self.article.slug]), follow=True
        )
        self.assertEqual(result.status_code, 200)

        # member who isn't author  can't read offline articles
        result = self.client.get(
            reverse("zds.article.views.view", args=[self.article.pk, self.article.slug]), follow=True
        )
        self.assertEqual(result.status_code, 200)

    def test_workflow_licence(self):
        """Ensure the behavior of licence on articles"""

        # create a new licence
        new_licence = LicenceFactory(code="CC_BY", title="Creative Commons BY")
        new_licence = Licence.objects.get(pk=new_licence.pk)

        # check value first
        article = Article.objects.get(pk=self.article.pk)
        self.assertEqual(article.licence.pk, self.licence.pk)

        # logout before
        self.client.logout()
        # login with author
        self.assertTrue(self.client.login(username=self.user_author.username, password="******"))

        # change licence (get 302) :
        result = self.client.post(
            reverse("zds.article.views.edit") + "?article={}".format(self.article.pk),
            {
                "title": self.article.title,
                "description": self.article.description,
                "text": self.article.get_text(),
                "subcategory": self.article.subcategory.all(),
                "licence": new_licence.pk,
            },
            follow=False,
        )
        self.assertEqual(result.status_code, 302)

        # test change :
        article = Article.objects.get(pk=self.article.pk)
        self.assertNotEqual(article.licence.pk, self.licence.pk)
        self.assertEqual(article.licence.pk, new_licence.pk)

        # test change in JSON :
        json = article.load_json()
        self.assertEquals(json["licence"], new_licence.code)

        # then logout ...
        self.client.logout()
        # ... and login with staff
        self.assertTrue(self.client.login(username=self.staff.username, password="******"))

        # change licence back to old one (get 302, staff can change licence) :
        result = self.client.post(
            reverse("zds.article.views.edit") + "?article={}".format(self.article.pk),
            {
                "title": self.article.title,
                "description": self.article.description,
                "text": self.article.get_text(),
                "subcategory": self.article.subcategory.all(),
                "licence": self.licence.pk,
            },
            follow=False,
        )
        self.assertEqual(result.status_code, 302)

        # test change :
        article = Article.objects.get(pk=self.article.pk)
        self.assertEqual(article.licence.pk, self.licence.pk)
        self.assertNotEqual(article.licence.pk, new_licence.pk)

        # test change in JSON :
        json = article.load_json()
        self.assertEquals(json["licence"], self.licence.code)

        # then logout ...
        self.client.logout()

        # change licence (get 302, redirection to login page) :
        result = self.client.post(
            reverse("zds.article.views.edit") + "?article={}".format(self.article.pk),
            {
                "title": self.article.title,
                "description": self.article.description,
                "text": self.article.get_text(),
                "subcategory": self.article.subcategory.all(),
                "licence": new_licence.pk,
            },
            follow=False,
        )
        self.assertEqual(result.status_code, 302)

        # test change (normaly, nothing has) :
        article = Article.objects.get(pk=self.article.pk)
        self.assertEqual(article.licence.pk, self.licence.pk)
        self.assertNotEqual(article.licence.pk, new_licence.pk)

        # login with random user
        self.assertTrue(self.client.login(username=self.user.username, password="******"))

        # change licence (get 403, random user cannot edit article if not in
        # authors list) :
        result = self.client.post(
            reverse("zds.article.views.edit") + "?article={}".format(self.article.pk),
            {
                "title": self.article.title,
                "description": self.article.description,
                "text": self.article.get_text(),
                "subcategory": self.article.subcategory.all(),
                "licence": new_licence.pk,
            },
            follow=False,
        )
        self.assertEqual(result.status_code, 403)

        # test change (normaly, nothing has) :
        article = Article.objects.get(pk=self.article.pk)
        self.assertEqual(article.licence.pk, self.licence.pk)
        self.assertNotEqual(article.licence.pk, new_licence.pk)

        # test change in JSON (normaly, nothing has) :
        json = article.load_json()
        self.assertEquals(json["licence"], self.licence.code)

    def tearDown(self):
        if os.path.isdir(settings.REPO_ARTICLE_PATH):
            shutil.rmtree(settings.REPO_ARTICLE_PATH)
        if os.path.isdir(settings.MEDIA_ROOT):
            shutil.rmtree(settings.MEDIA_ROOT)
コード例 #14
0
ファイル: tests.py プロジェクト: maynalysa/zds-site
class ArticleTests(TestCase):

    def setUp(self):

        settings.EMAIL_BACKEND = \
            'django.core.mail.backends.locmem.EmailBackend'
        self.mas = ProfileFactory().user
        settings.BOT_ACCOUNT = self.mas.username

        self.user_author = ProfileFactory().user
        self.user = ProfileFactory().user
        self.staff = StaffProfileFactory().user
        
        self.licence = LicenceFactory()

        self.article = ArticleFactory()
        self.article.authors.add(self.user_author)
        self.article.licence = self.licence
        self.article.save()

        # connect with user
        login_check = self.client.login(
            username=self.user_author.username,
            password='******')
        self.assertEqual(login_check, True)

        # ask public article
        pub = self.client.post(
            reverse('zds.article.views.modify'),
            {
                'article': self.article.pk,
                'comment': u'Valides moi ce bébé',
                'pending': 'Demander validation',
                'version': self.article.sha_draft,
                'is_major': True
            },
            follow=False)
        self.assertEqual(pub.status_code, 302)
        self.assertEqual(Validation.objects.count(), 1)

        login_check = self.client.login(
            username=self.staff.username,
            password='******')
        self.assertEqual(login_check, True)

        # reserve tutorial
        validation = Validation.objects.get(
            article__pk=self.article.pk)
        pub = self.client.post(
            reverse('zds.article.views.reservation', args=[validation.pk]),
            follow=False)
        self.assertEqual(pub.status_code, 302)

        # publish article
        pub = self.client.post(
            reverse('zds.article.views.modify'),
            {
                'article': self.article.pk,
                'comment-v': u'Cet article est excellent',
                'valid-article': 'Demander validation',
                'is_major': True
            },
            follow=False)
        self.assertEqual(pub.status_code, 302)
        self.assertEquals(len(mail.outbox), 1)
        mail.outbox = []

    def test_delete_image_on_change(self):
        """test que l'image est bien supprimée quand on la change"""

        root = settings.SITE_ROOT
        if not os.path.isdir(settings.MEDIA_ROOT):
            os.mkdir(settings.MEDIA_ROOT)
        shutil.copyfile(
            os.path.join(root, 'fixtures', 'logo.png'),
            os.path.join(settings.MEDIA_ROOT, 'logo2.png')
        )
        shutil.copyfile(
            os.path.join(settings.MEDIA_ROOT, 'logo2.png'),
            os.path.join(settings.MEDIA_ROOT, 'logo.png')
        )
        self.logo1 = os.path.join(settings.MEDIA_ROOT, 'logo.png')
        self.logo2 = os.path.join(settings.MEDIA_ROOT, 'logo2.png')

        self.article.image = self.logo1
        self.article.save()
        self.assertEqual(
            os.path.exists(
                os.path.join(
                    settings.MEDIA_ROOT, self.article.image.name
                )
            ),
            True
        )
        # now that we have a first image, let's change it

        oldAddress = self.article.image.name
        self.article.image = self.logo2
        self.article.save()
        self.assertEqual(
            os.path.exists(
                os.path.join(
                    settings.MEDIA_ROOT, self.article.image.name
                )
            ),
            True
        )
        self.assertEqual(
            os.path.exists(
                os.path.join(settings.MEDIA_ROOT, oldAddress)
            ),
            False
        )
        os.unlink(self.logo2)
        # shutil.rmtree(settings.MEDIA_ROOT)

    def test_alert(self):
        user1 = ProfileFactory().user
        reaction = ReactionFactory(
            article=self.article,
            author=user1,
            position=1)
        login_check = self.client.login(
            username=self.user.username,
            password='******')
        self.assertEqual(login_check, True)
        # signal reaction
        result = self.client.post(
            reverse('zds.article.views.edit_reaction') +
            '?message={0}'.format(
                reaction.pk),
            {
                'signal_text': 'Troll',
                'signal_message': 'Confirmer',
            },
            follow=False)
        self.assertEqual(result.status_code, 302)
        self.assertEqual(Alert.objects.all().count(), 1)

        # connect with staff
        login_check = self.client.login(
            username=self.staff.username,
            password='******')
        self.assertEqual(login_check, True)
        # solve alert
        result = self.client.post(
            reverse('zds.article.views.solve_alert'),
            {
                'alert_pk': Alert.objects.first().pk,
                'text': 'Ok',
                'delete_message': 'Resoudre',
            },
            follow=False)
        self.assertEqual(result.status_code, 302)
        self.assertEqual(Alert.objects.all().count(), 0)
        self.assertEqual(
            PrivateTopic.objects.filter(
                author=self.user).count(),
            1)
        self.assertEquals(len(mail.outbox), 0)

    def test_add_reaction(self):
        """To test add reaction for article."""
        user1 = ProfileFactory().user
        self.client.login(username=user1.username, password='******')

        # add empty reaction
        result = self.client.post(
            reverse('zds.article.views.answer') +
            '?article={0}'.format(
                self.article.pk),
            {
                'last_reaction': '0',
                'text': u''},
            follow=False)
        self.assertEqual(result.status_code, 200)
        # check reactions's number
        self.assertEqual(Reaction.objects.all().count(), 0)

        # add reaction
        result = self.client.post(
            reverse('zds.article.views.answer') +
            '?article={0}'.format(
                self.article.pk),
            {
                'last_reaction': '0',
                'text': u'Histoire de blablater dans les comms de l\'article'},
            follow=False)
        self.assertEqual(result.status_code, 302)

        # check reactions's number
        self.assertEqual(Reaction.objects.all().count(), 1)

        # check values
        art = Article.objects.get(pk=self.article.pk)
        self.assertEqual(Reaction.objects.get(pk=1).article, art)
        self.assertEqual(Reaction.objects.get(pk=1).author.pk, user1.pk)
        self.assertEqual(Reaction.objects.get(pk=1).position, 1)
        self.assertEqual(Reaction.objects.get(pk=1).pk, art.last_reaction.pk)
        self.assertEqual(
            Reaction.objects.get(
                pk=1).text,
            u'Histoire de blablater dans les comms de l\'article')

        # test antispam return 403
        result = self.client.post(
            reverse('zds.article.views.answer') +
            '?article={0}'.format(
                self.article.pk),
            {
                'last_reaction': art.last_reaction.pk,
                'text': u'Histoire de tester l\'antispam'},
            follow=False)
        self.assertEqual(result.status_code, 403)

        ReactionFactory(
            article=self.article,
            position=2,
            author=self.staff)

        # test more reaction
        result = self.client.post(
            reverse('zds.article.views.answer') +
            '?article={0}'.format(
                self.article.pk),
            {
                'last_reaction': self.article.last_reaction.pk,
                'text': u'Histoire de tester l\'antispam'},
            follow=False)
        self.assertEqual(result.status_code, 302)

    def test_url_for_guest(self):
        """Test simple get request by guest."""

        # logout before
        self.client.logout()

        # guest can read public articles
        result = self.client.get(
            reverse(
                'zds.article.views.view_online',
                args=[
                    self.article.pk,
                    self.article.slug]),
            follow=True)
        self.assertEqual(result.status_code, 200)

        # guest can't read offline articles
        result = self.client.get(
            reverse(
                'zds.article.views.view',
                args=[
                    self.article.pk,
                    self.article.slug]),
            follow=False)
        self.assertEqual(result.status_code, 302)

    def test_url_for_member(self):
        """Test simple get request by simple member."""

        # logout before
        self.client.logout()
        # login with simple member
        self.assertEqual(
            self.client.login(
                username=self.user.username,
                password='******'),
            True)

        # member who isn't author can read public articles
        result = self.client.get(
            reverse(
                'zds.article.views.view_online',
                args=[
                    self.article.pk,
                    self.article.slug]),
            follow=True)
        self.assertEqual(result.status_code, 200)

        # member who isn't author  can't read offline articles
        result = self.client.get(
            reverse(
                'zds.article.views.view',
                args=[
                    self.article.pk,
                    self.article.slug]),
            follow=True)
        self.assertEqual(result.status_code, 403)

    def test_url_for_author(self):
        """Test simple get request by author."""

        # logout before
        self.client.logout()
        # login with simple member
        self.assertEqual(
            self.client.login(
                username=self.user_author.username,
                password='******'),
            True)

        # member who isn't author can read public articles
        result = self.client.get(
            reverse(
                'zds.article.views.view_online',
                args=[
                    self.article.pk,
                    self.article.slug]),
            follow=True)
        self.assertEqual(result.status_code, 200)

        # member who isn't author  can't read offline articles
        result = self.client.get(
            reverse(
                'zds.article.views.view',
                args=[
                    self.article.pk,
                    self.article.slug]),
            follow=True)
        self.assertEqual(result.status_code, 200)

    def test_url_for_staff(self):
        """Test simple get request by staff."""

        # logout before
        self.client.logout()
        # login with simple member
        self.assertEqual(
            self.client.login(
                username=self.staff.username,
                password='******'),
            True)

        # member who isn't author can read public articles
        result = self.client.get(
            reverse(
                'zds.article.views.view_online',
                args=[
                    self.article.pk,
                    self.article.slug]),
            follow=True)
        self.assertEqual(result.status_code, 200)

        # member who isn't author  can't read offline articles
        result = self.client.get(
            reverse(
                'zds.article.views.view',
                args=[
                    self.article.pk,
                    self.article.slug]),
            follow=True)
        self.assertEqual(result.status_code, 200)

    def test_workflow_licence(self):
        '''Ensure the behavior of licence on articles'''

        # create a new licence
        new_licence = LicenceFactory(code='CC_BY', title='Creative Commons BY')
        new_licence = Licence.objects.get(pk=new_licence.pk)

        # check value first
        article = Article.objects.get(pk=self.article.pk)
        self.assertEqual(article.licence.pk, self.licence.pk)

        # logout before
        self.client.logout()
        # login with author
        self.assertTrue(
            self.client.login(
                username=self.user_author.username,
                password='******')
        )

        # change licence (get 302) :
        result = self.client.post(
            reverse('zds.article.views.edit') + 
                '?article={}'.format(self.article.pk),
            {
                'title': self.article.title,
                'description': self.article.description,
                'text': self.article.get_text(),
                'subcategory': self.article.subcategory.all(),
                'licence' : new_licence.pk
            },
            follow=False)
        self.assertEqual(result.status_code, 302)

        # test change :
        article = Article.objects.get(pk=self.article.pk)
        self.assertNotEqual(article.licence.pk, self.licence.pk)
        self.assertEqual(article.licence.pk, new_licence.pk)

        # test change in JSON :
        json = article.load_json()
        self.assertEquals(json['licence'], new_licence.code)

        # then logout ...
        self.client.logout()
        # ... and login with staff
        self.assertTrue(
            self.client.login(
                username=self.staff.username,
                password='******')
        )

        # change licence back to old one (get 302, staff can change licence) :
        result = self.client.post(
            reverse('zds.article.views.edit') + 
                '?article={}'.format(self.article.pk),
            {
                'title': self.article.title,
                'description': self.article.description,
                'text': self.article.get_text(),
                'subcategory': self.article.subcategory.all(),
                'licence' : self.licence.pk
            },
            follow=False)
        self.assertEqual(result.status_code, 302)

        # test change :
        article = Article.objects.get(pk=self.article.pk)
        self.assertEqual(article.licence.pk, self.licence.pk)
        self.assertNotEqual(article.licence.pk, new_licence.pk)

        # test change in JSON :
        json = article.load_json()
        self.assertEquals(json['licence'], self.licence.code)

        # then logout ...
        self.client.logout()

        # change licence (get 302, redirection to login page) :
        result = self.client.post(
            reverse('zds.article.views.edit') + 
                '?article={}'.format(self.article.pk),
            {
                'title': self.article.title,
                'description': self.article.description,
                'text': self.article.get_text(),
                'subcategory': self.article.subcategory.all(),
                'licence' : new_licence.pk
            },
            follow=False)
        self.assertEqual(result.status_code, 302)

        # test change (normaly, nothing has) :
        article = Article.objects.get(pk=self.article.pk)
        self.assertEqual(article.licence.pk, self.licence.pk)
        self.assertNotEqual(article.licence.pk, new_licence.pk)
        
        # login with random user
        self.assertTrue(
            self.client.login(
                username=self.user.username,
                password='******')
        )

        # change licence (get 403, random user cannot edit article if not in
        # authors list) :
        result = self.client.post(
            reverse('zds.article.views.edit') + 
                '?article={}'.format(self.article.pk),
            {
                'title': self.article.title,
                'description': self.article.description,
                'text': self.article.get_text(),
                'subcategory': self.article.subcategory.all(),
                'licence' : new_licence.pk
            },
            follow=False)
        self.assertEqual(result.status_code, 403)

        # test change (normaly, nothing has) :
        article = Article.objects.get(pk=self.article.pk)
        self.assertEqual(article.licence.pk, self.licence.pk)
        self.assertNotEqual(article.licence.pk, new_licence.pk)

        # test change in JSON (normaly, nothing has) :
        json = article.load_json()
        self.assertEquals(json['licence'], self.licence.code)

    def tearDown(self):
        if os.path.isdir(settings.REPO_ARTICLE_PATH):
            shutil.rmtree(settings.REPO_ARTICLE_PATH)
        if os.path.isdir(settings.MEDIA_ROOT):
            shutil.rmtree(settings.MEDIA_ROOT)
コード例 #15
0
ファイル: tests.py プロジェクト: pquentin/zds-site
class ArticleTests(TestCase):
    def setUp(self):
        settings.EMAIL_BACKEND = \
            'django.core.mail.backends.locmem.EmailBackend'
        self.mas = ProfileFactory().user
        settings.ZDS_APP['member']['bot_account'] = self.mas.username

        self.user_author = ProfileFactory().user
        self.user = ProfileFactory().user
        self.staff = StaffProfileFactory().user

        self.licence = LicenceFactory()

        self.article = ArticleFactory()
        self.article.authors.add(self.user_author)
        self.article.licence = self.licence
        self.article.save()

        # connect with user
        login_check = self.client.login(username=self.user_author.username,
                                        password='******')
        self.assertEqual(login_check, True)

        # ask public article
        pub = self.client.post(reverse('zds.article.views.modify'), {
            'article': self.article.pk,
            'comment': u'Valides moi ce bébé',
            'pending': 'Demander validation',
            'version': self.article.sha_draft,
            'is_major': True
        },
                               follow=False)
        self.assertEqual(pub.status_code, 302)
        self.assertEqual(Validation.objects.count(), 1)

        login_check = self.client.login(username=self.staff.username,
                                        password='******')
        self.assertEqual(login_check, True)

        # reserve tutorial
        validation = Validation.objects.get(article__pk=self.article.pk)
        pub = self.client.post(reverse('zds.article.views.reservation',
                                       args=[validation.pk]),
                               follow=False)
        self.assertEqual(pub.status_code, 302)

        # publish article
        pub = self.client.post(reverse('zds.article.views.modify'), {
            'article': self.article.pk,
            'comment-v': u'Cet article est excellent',
            'valid-article': 'Demander validation',
            'is_major': True
        },
                               follow=False)
        self.assertEqual(pub.status_code, 302)
        self.assertEquals(len(mail.outbox), 1)
        mail.outbox = []

        bot = Group(name=settings.ZDS_APP["member"]["bot_group"])
        bot.save()

    def test_delete_image_on_change(self):
        """test que l'image est bien supprimée quand on la change"""

        root = settings.BASE_DIR
        if not os.path.isdir(settings.MEDIA_ROOT):
            os.mkdir(settings.MEDIA_ROOT)
        shutil.copyfile(os.path.join(root, 'fixtures', 'logo.png'),
                        os.path.join(settings.MEDIA_ROOT, 'logo2.png'))
        shutil.copyfile(os.path.join(settings.MEDIA_ROOT, 'logo2.png'),
                        os.path.join(settings.MEDIA_ROOT, 'logo.png'))
        self.logo1 = os.path.join(settings.MEDIA_ROOT, 'logo.png')
        self.logo2 = os.path.join(settings.MEDIA_ROOT, 'logo2.png')

        self.article.image = self.logo1
        self.article.save()
        self.assertEqual(
            os.path.exists(
                os.path.join(settings.MEDIA_ROOT, self.article.image.name)),
            True)
        # now that we have a first image, let's change it

        old_address = self.article.image.name
        self.article.image = self.logo2
        self.article.save()
        self.assertEqual(
            os.path.exists(
                os.path.join(settings.MEDIA_ROOT, self.article.image.name)),
            True)
        self.assertEqual(
            os.path.exists(os.path.join(settings.MEDIA_ROOT, old_address)),
            False)
        os.unlink(self.logo2)
        # shutil.rmtree(settings.MEDIA_ROOT)

    def test_alert(self):
        user1 = ProfileFactory().user
        reaction = ReactionFactory(article=self.article,
                                   author=user1,
                                   position=1)
        login_check = self.client.login(username=self.user.username,
                                        password='******')
        self.assertEqual(login_check, True)
        # signal reaction
        result = self.client.post(reverse('zds.article.views.edit_reaction') +
                                  '?message={0}'.format(reaction.pk), {
                                      'signal_text': 'Troll',
                                      'signal_message': 'Confirmer',
                                  },
                                  follow=False)
        self.assertEqual(result.status_code, 302)
        self.assertEqual(Alert.objects.all().count(), 1)

        # connect with staff
        login_check = self.client.login(username=self.staff.username,
                                        password='******')
        self.assertEqual(login_check, True)
        # solve alert
        result = self.client.post(reverse('zds.article.views.solve_alert'), {
            'alert_pk': Alert.objects.first().pk,
            'text': 'Ok',
            'delete_message': 'Resoudre',
        },
                                  follow=False)
        self.assertEqual(result.status_code, 302)
        self.assertEqual(Alert.objects.all().count(), 0)
        self.assertEqual(
            PrivateTopic.objects.filter(author=self.user).count(), 1)
        self.assertEquals(len(mail.outbox), 0)

    def test_add_reaction(self):
        """To test add reaction for article."""
        user1 = ProfileFactory().user
        self.client.login(username=user1.username, password='******')

        # add empty reaction
        result = self.client.post(reverse('zds.article.views.answer') +
                                  '?article={0}'.format(self.article.pk), {
                                      'last_reaction': '0',
                                      'text': u''
                                  },
                                  follow=False)
        self.assertEqual(result.status_code, 200)
        # check reactions's number
        self.assertEqual(Reaction.objects.all().count(), 0)

        # add reaction
        result = self.client.post(
            reverse('zds.article.views.answer') +
            '?article={0}'.format(self.article.pk), {
                'last_reaction': '0',
                'text': u'Histoire de blablater dans les comms de l\'article'
            },
            follow=False)
        self.assertEqual(result.status_code, 302)

        # check reactions's number
        self.assertEqual(Reaction.objects.all().count(), 1)

        # check values
        art = Article.objects.get(pk=self.article.pk)
        first_art = Reaction.objects.first()
        self.assertEqual(first_art.article, art)
        self.assertEqual(first_art.author.pk, user1.pk)
        self.assertEqual(first_art.position, 1)
        self.assertEqual(first_art.pk, art.last_reaction.pk)
        self.assertEqual(
            Reaction.objects.first().text,
            u'Histoire de blablater dans les comms de l\'article')

        # test antispam return 403
        result = self.client.post(reverse('zds.article.views.answer') +
                                  '?article={0}'.format(self.article.pk), {
                                      'last_reaction': art.last_reaction.pk,
                                      'text': u'Histoire de tester l\'antispam'
                                  },
                                  follow=False)
        self.assertEqual(result.status_code, 403)

        ReactionFactory(article=self.article, position=2, author=self.staff)

        # test more reaction
        result = self.client.post(
            reverse('zds.article.views.answer') +
            '?article={0}'.format(self.article.pk), {
                'last_reaction': self.article.last_reaction.pk,
                'text': u'Histoire de tester l\'antispam'
            },
            follow=False)
        self.assertEqual(result.status_code, 302)

    def test_read_not_public_article(self):
        """To test if nobody can read a not public article."""

        # member can't read public articles which is not published
        article_no_public = ArticleFactory()
        article_no_public.on_line = False
        article_no_public.save()

        result = self.client.get(reverse(
            'zds.article.views.view_online',
            args=[article_no_public.pk, article_no_public.slug]),
                                 follow=False)
        self.assertEqual(result.status_code, 404)

        # logout before
        self.client.logout()

        result = self.client.get(reverse(
            'zds.article.views.view_online',
            args=[article_no_public.pk, article_no_public.slug]),
                                 follow=False)
        self.assertEqual(result.status_code, 404)

    def test_url_for_guest(self):
        """Test simple get request by guest."""

        # logout before
        self.client.logout()

        # guest can read public articles
        result = self.client.get(reverse(
            'zds.article.views.view_online',
            args=[self.article.pk, self.article.slug]),
                                 follow=True)
        self.assertEqual(result.status_code, 200)

        # guest can't read offline articles
        result = self.client.get(reverse(
            'zds.article.views.view',
            args=[self.article.pk, self.article.slug]),
                                 follow=False)
        self.assertEqual(result.status_code, 302)

    def test_url_for_member(self):
        """Test simple get request by simple member."""

        # logout before
        self.client.logout()
        # login with simple member
        self.assertEqual(
            self.client.login(username=self.user.username,
                              password='******'), True)

        # member who isn't author can read public articles
        result = self.client.get(reverse(
            'zds.article.views.view_online',
            args=[self.article.pk, self.article.slug]),
                                 follow=True)
        self.assertEqual(result.status_code, 200)

        # member who isn't author  can't read offline articles
        result = self.client.get(reverse(
            'zds.article.views.view',
            args=[self.article.pk, self.article.slug]),
                                 follow=True)
        self.assertEqual(result.status_code, 403)

    def test_url_for_author(self):
        """Test simple get request by author."""

        # logout before
        self.client.logout()
        # login with simple member
        self.assertEqual(
            self.client.login(username=self.user_author.username,
                              password='******'), True)

        # author can read public articles
        result = self.client.get(reverse(
            'zds.article.views.view_online',
            args=[self.article.pk, self.article.slug]),
                                 follow=True)
        self.assertEqual(result.status_code, 200)

        # author can use js
        self.article.js_support = True
        self.article.save()

        result = self.client.get(reverse(
            'zds.article.views.view',
            args=[self.article.pk, self.article.slug]),
                                 follow=True)
        self.assertEqual(result.status_code, 200)

    def test_url_for_staff(self):
        """Test simple get request by staff."""

        # logout before
        self.client.logout()
        # login with simple member
        self.assertEqual(
            self.client.login(username=self.staff.username,
                              password='******'), True)

        # member who isn't author can read public articles
        result = self.client.get(reverse(
            'zds.article.views.view_online',
            args=[self.article.pk, self.article.slug]),
                                 follow=True)
        self.assertEqual(result.status_code, 200)

        # member who isn't author  can't read offline articles
        result = self.client.get(reverse(
            'zds.article.views.view',
            args=[self.article.pk, self.article.slug]),
                                 follow=True)
        self.assertEqual(result.status_code, 200)

    def test_workflow_licence(self):
        """Ensure the behavior of licence on articles"""

        # create a new licence
        new_licence = LicenceFactory(code='CC_BY', title='Creative Commons BY')
        new_licence = Licence.objects.get(pk=new_licence.pk)

        # check value first
        article = Article.objects.get(pk=self.article.pk)
        self.assertEqual(article.licence.pk, self.licence.pk)

        # logout before
        self.client.logout()
        # login with author
        self.assertTrue(
            self.client.login(username=self.user_author.username,
                              password='******'))

        # change licence (get 302) :
        result = self.client.post(
            reverse('zds.article.views.edit') +
            '?article={}'.format(self.article.pk), {
                'title': self.article.title,
                'description': self.article.description,
                'text': self.article.get_text(),
                'subcategory': self.article.subcategory.all(),
                'licence': new_licence.pk
            },
            follow=False)
        self.assertEqual(result.status_code, 302)

        # test change :
        article = Article.objects.get(pk=self.article.pk)
        self.assertNotEqual(article.licence.pk, self.licence.pk)
        self.assertEqual(article.licence.pk, new_licence.pk)

        # test change in JSON :
        json = article.load_json()
        self.assertEquals(json['licence'].code, new_licence.code)

        # then logout ...
        self.client.logout()
        # ... and login with staff
        self.assertTrue(
            self.client.login(username=self.staff.username,
                              password='******'))

        # change licence back to old one (get 302, staff can change licence) :
        result = self.client.post(
            reverse('zds.article.views.edit') +
            '?article={}'.format(self.article.pk), {
                'title': self.article.title,
                'description': self.article.description,
                'text': self.article.get_text(),
                'subcategory': self.article.subcategory.all(),
                'licence': self.licence.pk
            },
            follow=False)
        self.assertEqual(result.status_code, 302)

        # test change :
        article = Article.objects.get(pk=self.article.pk)
        self.assertEqual(article.licence.pk, self.licence.pk)
        self.assertNotEqual(article.licence.pk, new_licence.pk)

        # test change in JSON :
        json = article.load_json()
        self.assertEquals(json['licence'].code, self.licence.code)

        # then logout ...
        self.client.logout()

        # change licence (get 302, redirection to login page) :
        result = self.client.post(
            reverse('zds.article.views.edit') +
            '?article={}'.format(self.article.pk), {
                'title': self.article.title,
                'description': self.article.description,
                'text': self.article.get_text(),
                'subcategory': self.article.subcategory.all(),
                'licence': new_licence.pk
            },
            follow=False)
        self.assertEqual(result.status_code, 302)

        # test change (normaly, nothing has) :
        article = Article.objects.get(pk=self.article.pk)
        self.assertEqual(article.licence.pk, self.licence.pk)
        self.assertNotEqual(article.licence.pk, new_licence.pk)

        # login with random user
        self.assertTrue(
            self.client.login(username=self.user.username,
                              password='******'))

        # change licence (get 403, random user cannot edit article if not in
        # authors list) :
        result = self.client.post(
            reverse('zds.article.views.edit') +
            '?article={}'.format(self.article.pk), {
                'title': self.article.title,
                'description': self.article.description,
                'text': self.article.get_text(),
                'subcategory': self.article.subcategory.all(),
                'licence': new_licence.pk
            },
            follow=False)
        self.assertEqual(result.status_code, 403)

        # test change (normaly, nothing has) :
        article = Article.objects.get(pk=self.article.pk)
        self.assertEqual(article.licence.pk, self.licence.pk)
        self.assertNotEqual(article.licence.pk, new_licence.pk)

        # test change in JSON (normaly, nothing has) :
        json = article.load_json()
        self.assertEquals(json['licence'].code, self.licence.code)

    def test_workflow_archive_article(self):
        """ensure the behavior of archive with an article"""

        # login with author
        self.assertEqual(
            self.client.login(username=self.user_author.username,
                              password='******'), True)

        # modify article content and title (NOTE: zipfile does not ensure UTF-8)
        article_title = u'Le titre, mais pas pareil'
        article_content = u'Mais nous c\'est pas pareil ...'
        result = self.client.post(
            reverse('zds.article.views.edit') +
            '?article={}'.format(self.article.pk), {
                'title': article_title,
                'description': self.article.description,
                'text': article_content,
                'subcategory': self.article.subcategory.all(),
                'licence': self.licence.pk
            },
            follow=False)
        self.assertEqual(result.status_code, 302)

        # now, draft and public version are not the same
        article = Article.objects.get(pk=self.article.pk)
        self.assertNotEqual(article.sha_draft, article.sha_public)

        # fetch archives :
        # 1. draft version
        result = self.client.get(reverse('zds.article.views.download') +
                                 '?article={0}'.format(self.article.pk),
                                 follow=False)
        self.assertEqual(result.status_code, 200)
        draft_zip_path = os.path.join(tempfile.gettempdir(), '__draft.zip')
        f = open(draft_zip_path, 'w')
        f.write(result.content)
        f.close()
        # 2. online version :
        result = self.client.get(reverse('zds.article.views.download') +
                                 '?article={0}&online'.format(self.article.pk),
                                 follow=False)
        self.assertEqual(result.status_code, 200)
        online_zip_path = os.path.join(tempfile.gettempdir(), '__online.zip')
        f = open(online_zip_path, 'w')
        f.write(result.content)
        f.close()

        # now check if modification are in draft version of archive and not in the public one
        draft_zip = zipfile.ZipFile(draft_zip_path, 'r')
        online_zip = zipfile.ZipFile(online_zip_path, 'r')

        # first, test in manifest
        online_manifest = json_reader.loads(online_zip.read('manifest.json'))
        self.assertNotEqual(
            online_manifest['title'],
            article_title)  # title has not changed in online version

        draft_manifest = json_reader.loads(draft_zip.read('manifest.json'))
        self.assertNotEqual(
            online_manifest['title'],
            article_title)  # title has not changed in online version

        self.assertNotEqual(online_zip.read(online_manifest['text']),
                            article_content)
        self.assertEqual(draft_zip.read(draft_manifest['text']),
                         article_content)  # content is good in draft

        draft_zip.close()
        online_zip.close()

        # then logout and test access
        self.client.logout()

        # public cannot access to draft version of article
        result = self.client.get(reverse('zds.article.views.download') +
                                 '?article={0}'.format(self.article.pk),
                                 follow=False)
        self.assertEqual(result.status_code, 403)
        # ... but can access to online version
        result = self.client.get(reverse('zds.article.views.download') +
                                 '?article={0}&online'.format(self.article.pk),
                                 follow=False)
        self.assertEqual(result.status_code, 200)

        # login with random user
        self.assertEqual(
            self.client.login(username=self.user.username,
                              password='******'), True)

        # cannot access to draft version of article (if not author or staff)
        result = self.client.get(reverse('zds.article.views.download') +
                                 '?article={0}'.format(self.article.pk),
                                 follow=False)
        self.assertEqual(result.status_code, 403)
        # but can access to online one
        result = self.client.get(reverse('zds.article.views.download') +
                                 '?article={0}&online'.format(self.article.pk),
                                 follow=False)
        self.assertEqual(result.status_code, 200)
        self.client.logout()

        # login with staff user
        self.assertEqual(
            self.client.login(username=self.staff.username,
                              password='******'), True)

        # staff can access to draft version of article
        result = self.client.get(reverse('zds.article.views.download') +
                                 '?article={0}'.format(self.article.pk),
                                 follow=False)
        self.assertEqual(result.status_code, 200)
        # ... and also to online version
        result = self.client.get(reverse('zds.article.views.download') +
                                 '?article={0}&online'.format(self.article.pk),
                                 follow=False)
        self.assertEqual(result.status_code, 200)

        # and test also some failing cases

        # When the pk is missing for the edit
        result = self.client.get(reverse('zds.article.views.download') +
                                 '?&online',
                                 follow=False)
        self.assertEqual(result.status_code, 404)

        # When the pk is weird
        result = self.client.get(reverse('zds.article.views.download') +
                                 '?article={abc}&online',
                                 follow=False)
        self.assertEqual(result.status_code, 404)

        # When the pk is not yet existing
        result = self.client.get(reverse('zds.article.views.download') +
                                 '?article={424242}&online',
                                 follow=False)
        self.assertEqual(result.status_code, 404)

        # finally, clean up things:
        os.remove(draft_zip_path)
        os.remove(online_zip_path)

    def test_change_update(self):
        """test the change of `article.update` if modified (ensure #1956)"""

        # login with author
        self.assertEqual(
            self.client.login(username=self.user_author.username,
                              password='******'), True)

        time_0 = datetime.datetime.fromtimestamp(0)  # way deep in the past
        article = Article.objects.get(pk=self.article.pk)
        article.update = time_0
        article.save()

        # first check if this modification is performed :
        self.assertEqual(
            Article.objects.get(pk=self.article.pk).update, time_0)

        # modify article content and title (implicit call to `maj_repo_article()`)
        article_title = u'Le titre, mais pas pareil'
        article_content = u'Mais nous c\'est pas pareil ...'
        result = self.client.post(
            reverse('zds.article.views.edit') +
            '?article={}'.format(self.article.pk), {
                'title': article_title,
                'description': self.article.description,
                'text': article_content,
                'subcategory': self.article.subcategory.all(),
                'licence': self.licence.pk
            },
            follow=False)
        self.assertEqual(result.status_code, 302)
        self.assertNotEqual(
            Article.objects.get(pk=self.article.pk).update, time_0)

        # and also test some failing cases

        # When the pk is missing for the edit
        article_title = u'Le titre, mais pas pareil encore'
        article_content = u'Mais nous c\'est pas pareil encore...'
        result = self.client.post(reverse('zds.article.views.edit'), {
            'title': article_title,
            'description': self.article.description,
            'text': article_content,
            'subcategory': self.article.subcategory.all(),
            'licence': self.licence.pk
        },
                                  follow=False)
        self.assertEqual(result.status_code, 404)

        # When the pk is weird for the edit
        result = self.client.post(
            reverse('zds.article.views.edit') + '?article=' + 'abc', {
                'title': article_title,
                'description': self.article.description,
                'text': article_content,
                'subcategory': self.article.subcategory.all(),
                'licence': self.licence.pk
            },
            follow=False)
        self.assertEqual(result.status_code, 404)

        # When the pk is not yet existing for the edit
        result = self.client.post(
            reverse('zds.article.views.edit') + '?article=' + '424242', {
                'title': article_title,
                'description': self.article.description,
                'text': article_content,
                'subcategory': self.article.subcategory.all(),
                'licence': self.licence.pk
            },
            follow=False)
        self.assertEqual(result.status_code, 404)

    def test_list_article(self):
        # Test if we can display an article
        result = self.client.get(reverse('zds.article.views.index'), {},
                                 follow=True)
        self.assertEqual(result.status_code, 200)
        self.assertIn(self.article.title, result.content)

    def test_list_article_with_subcategory(self):
        # Test with tag restriction

        # Create an article with subcategory
        subcat = SubCategoryFactory()

        article_with_tag = PublishedArticleFactory()
        article_with_tag.subcategory.add(subcat.pk)
        article_with_tag.save()

        # Create another article with another subcategory
        subcat2 = SubCategoryFactory()

        article_with_other_tag = PublishedArticleFactory()
        article_with_other_tag.subcategory.add(subcat2.pk)
        article_with_other_tag.save()

        # Launch test with a subcategory in params url
        result = self.client.post(reverse('zds.article.views.index') +
                                  '?tag=' + subcat.slug, {},
                                  follow=True)
        self.assertEqual(result.status_code, 200)
        self.assertNotIn(self.article.title, result.content)
        self.assertNotIn(article_with_other_tag.title, result.content)
        self.assertIn(article_with_tag.title, result.content)

        # Launch test with no subcategory
        result = self.client.post(reverse('zds.article.views.index') +
                                  '?tag=None', {},
                                  follow=True)
        self.assertEqual(result.status_code, 200)
        self.assertIn(self.article.title, result.content)
        self.assertIn(article_with_other_tag.title, result.content)
        self.assertIn(article_with_tag.title, result.content)

    def test_new_article(self):
        # Create a Gallery
        gallery = GalleryFactory()

        # Attach an image of a gallery
        image_article = ImageFactory(gallery=gallery)
        UserGalleryFactory(user=self.user_author, gallery=gallery)

        # Create a subcategory
        subcat = SubCategoryFactory()

        # Try the preview button
        result = self.client.post(reverse('zds.article.views.new'), {
            'text': 'A wonderful poetry by Victor Hugo',
            'preview': '',
            'title': '',
            'description': '',
            'text': '',
            'image': image_article.pk,
            'subcategory': subcat.pk,
            'licence': self.licence.pk,
            'msg_commit': ''
        },
                                  follow=True)
        self.assertEqual(result.status_code, 200)

        # Create an article
        result = self.client.post(reverse('zds.article.views.new'), {
            'title':
            'Create a new article test',
            'description':
            'Describe the mew article',
            'text':
            'A wonderful poetry by Victor Hugo',
            'image':
            image_article.pk,
            'subcategory':
            subcat.pk,
            'licence':
            self.licence.pk,
            'msg_commit':
            'Celui qui ouvre une porte d\'école, ferme une prison.'
        },
                                  follow=True)
        self.assertEqual(result.status_code, 200)
        self.assertEqual(
            Article.objects.filter(title='Create a new article test').count(),
            1)

    def test_warn_typo(self):
        """
        Add a non-regression test about warning the author(s) of a typo in an article
        """

        typo_text = u'T\'as fait une faute, t\'es nul'

        # login with author
        self.assertEqual(
            self.client.login(username=self.user_author.username,
                              password='******'), True)

        # check if author get error when warning typo on its own tutorial
        result = self.client.post(reverse('zds.article.views.warn_typo',
                                          args=[self.article.pk]),
                                  {
                                      'explication': u'ceci est un test',
                                  },
                                  follow=True)
        self.assertEqual(result.status_code, 200)

        msgs = result.context['messages']
        last = None
        for msg in msgs:
            last = msg
        self.assertEqual(last.level, messages.ERROR)

        # login with normal user
        self.client.logout()

        self.assertEqual(
            self.client.login(username=self.user.username,
                              password='******'), True)

        # check if user can warn typo in tutorial
        result = self.client.post(reverse('zds.article.views.warn_typo',
                                          args=[self.article.pk]), {
                                              'explication': typo_text,
                                          },
                                  follow=True)
        self.assertEqual(result.status_code, 200)

        msgs = result.context['messages']
        last = None
        for msg in msgs:
            last = msg
        self.assertEqual(last.level, messages.SUCCESS)

        # check PM :
        sent_pm = PrivateTopic.objects.filter(author=self.user.pk).last()
        self.assertIn(self.user_author,
                      sent_pm.participants.all())  # author is in participants
        self.assertIn(typo_text,
                      sent_pm.last_message.text)  # typo is in message
        self.assertIn(self.article.get_absolute_url_online(),
                      sent_pm.last_message.text)  # public url is in message

        # Check if we send a wrong pk key
        result = self.client.post(reverse('zds.article.views.warn_typo',
                                          args=["1111"]), {
                                              'explication': typo_text,
                                          },
                                  follow=False)
        self.assertEqual(result.status_code, 404)

        # Check if we send no explanation
        result = self.client.post(reverse('zds.article.views.warn_typo',
                                          args=[self.article.pk]), {
                                              'explication': '',
                                          },
                                  follow=True)
        self.assertEqual(result.status_code, 200)

        msgs = result.context['messages']
        last = None
        for msg in msgs:
            last = msg
        self.assertEqual(last.level, messages.ERROR)

        # Check if we send an explanation with only space
        result = self.client.post(reverse('zds.article.views.warn_typo',
                                          args=[self.article.pk]), {
                                              'explication': '  ',
                                          },
                                  follow=True)
        self.assertEqual(result.status_code, 200)

        msgs = result.context['messages']
        last = None
        for msg in msgs:
            last = msg
        self.assertEqual(last.level, messages.ERROR)

        # Check if a guest can not warn the author
        self.client.logout()

        result = self.client.post(reverse('zds.article.views.warn_typo',
                                          args=[self.article.pk]), {
                                              'explication': typo_text,
                                          },
                                  follow=False)
        self.assertEqual(result.status_code, 302)

    def tearDown(self):
        if os.path.isdir(settings.ZDS_APP['article']['repo_path']):
            shutil.rmtree(settings.ZDS_APP['article']['repo_path'])
        if os.path.isdir(settings.MEDIA_ROOT):
            shutil.rmtree(settings.MEDIA_ROOT)