Пример #1
0
    def test_article_rating(self):
        article = ArticleFactory()

        VoteFactory(content_object=article, score=3)
        VoteFactory(content_object=article, score=5)

        article.refresh_from_db()
        self.assertEqual(article.rating, 4)
        self.assertEqual(article.vote_count, 2)
 def test_made_articles_as_draft_if_yet_not(self):
     # create new article and published it
     article = ArticleFactory(status=Article.STATUS_ARTICLE.published)
     self.assertEqual(article.status, Article.STATUS_ARTICLE.published)
     # made published article as draft
     Article.objects.made_articles_as_draft_if_yet_not(article)
     article.refresh_from_db()
     self.assertEqual(article.status, Article.STATUS_ARTICLE.draft)
     # attermpt again made article as draft
     Article.objects.made_articles_as_draft_if_yet_not(article)
     article.refresh_from_db()
     self.assertEqual(article.status, Article.STATUS_ARTICLE.draft)
Пример #3
0
    def test_video_section_page(self):
        section = VideoSectionFactory()
        ArticleFactory.create_batch(4, section=section)

        resp = self.app.get('/material/video/')
        self.assertEqual(resp.status_code, 200)

        self.assertEqual(resp.context['partition'].slug, 'video')
        self.assertIsNone(resp.context['nav_section'])
        self.assertEqual(len(resp.context['object_list']), 4)

        self.assertContains(resp, 'Видео')
 def test_publish_articles_if_yet_not(self):
     # create new draft article
     article = ArticleFactory(status=Article.STATUS_ARTICLE.draft)
     self.assertEqual(article.status, Article.STATUS_ARTICLE.draft)
     # publish article
     Article.objects.publish_articles_if_yet_not(article)
     article.refresh_from_db()
     self.assertEqual(article.status, Article.STATUS_ARTICLE.published)
     # attempt again publish article
     Article.objects.publish_articles_if_yet_not(article)
     article.refresh_from_db()
     self.assertEqual(article.status, Article.STATUS_ARTICLE.published)
Пример #5
0
    def test_section_page_200(self):
        section = SectionFactory(name='Политика', slug='politic')
        article = ArticleFactory(section=section, title='Радуга в окне')
        ArticleFactory(title='Плотный звук')

        resp = self.app.get('/pda/material/politic/')
        self.assertEqual(resp.status_code, 200)
        self.assertEqual(resp.template_name[0], 'pda/articles/list.html')

        self.assertEqual(resp.context['partition'], section)
        self.assertEqual(set(resp.context['object_list']), {article})

        self.assertContains(resp, 'Политика')
        self.assertContains(resp, 'Радуга в окне')
        self.assertNotContains(resp, 'Плотный звук')
Пример #6
0
    def test_vote_atricle_fail(self):
        self.app.get('/')  # create session_key

        # fake comment id
        resp = self.app.post('/votes/comment/', {
            'object_id': 999999999,
            'score': 1
        },
                             HTTP_REFERER='/material/news/1/')
        self.assertEqual(resp.status_code, 302)
        self.assertEqual(resp.url, '/material/news/1/')
        self.assertFalse(Vote.objects.exists())

        article = ArticleFactory()
        comment = CommentFactory(article=article)

        # bad score
        resp = self.app.post('/votes/comment/', {
            'object_id': comment.id,
            'score': 2
        },
                             HTTP_REFERER='/material/news/{}/'.format(
                                 article.id),
                             follow=True)
        url, status_code = resp.redirect_chain[0]
        self.assertEqual(status_code, 302)
        self.assertEqual(url, '/material/news/{}/'.format(article.id))
        self.assertFalse(Vote.objects.exists())
        self.assertContains(
            resp, 'Возможность оценить комментарий временно недоступна')
Пример #7
0
    def test_create_ok(self):
        article = ArticleFactory(section__slug='politic')

        data = {
            'article': article.id,
            'parent': '',
            'username': '******',
            'title': 'История начинается',
            'content': 'Жили-были старик со старухой',
            'captcha_0': '*',
            'captcha_1': 'passed'
        }
        resp = self.app.post('/comment/create/', data, follow=True)
        url, status_code = resp.redirect_chain[0]
        self.assertEqual(status_code, 302)
        self.assertEqual(url, '/material/politic/{}/'.format(article.id))

        comments = Comment.objects.all()
        self.assertEqual(len(comments), 1)
        self.assertEqual(comments[0].article, article)
        self.assertEqual(comments[0].username, 'Колобок')
        self.assertEqual(comments[0].content, 'Жили-были старик со старухой')

        # comment exists on page
        self.assertContains(resp, 'Колобок')
        self.assertContains(resp, 'История начинается')
        self.assertContains(resp, 'Жили-были старик со старухой')
Пример #8
0
    def test_create_with_parent(self):
        article = ArticleFactory(section__slug='politic')
        comment = CommentFactory(article=article)

        data = {
            'article': article.id,
            'parent': comment.id,
            'username': '******',
            'content': 'Бабушка и волки',
            'captcha_0': '*',
            'captcha_1': 'passed'
        }
        resp = self.app.post('/comment/create/', data, follow=True)
        url, status_code = resp.redirect_chain[0]
        self.assertEqual(status_code, 302)
        self.assertEqual(url, '/material/politic/{}/'.format(article.id))

        comments = Comment.objects.order_by('-id')
        self.assertEqual(len(comments), 2)
        self.assertEqual(comments[0].article, article)
        self.assertEqual(comments[0].parent, comment)

        # comment exists on page
        self.assertContains(resp, 'Шапочка')
        self.assertContains(resp, '(без названия)')
Пример #9
0
    def test_index_video_page(self):
        section1 = VideoSectionFactory(name='Политика',
                                       slug='video_politic')  # 3 item block
        section2 = VideoSectionFactory(
            name='ТВ', slug='video_partner_nevextv')  # 2 item block
        section3 = VideoSectionFactory(name='Народ',
                                       slug='video_national')  # 5 item block
        SectionFactory(name='Экономика', slug='video_economic')  # non video

        for section in (section1, section2, section3):
            ArticleFactory.create_batch(4,
                                        section=section,
                                        image=None,
                                        with_video=True)
            ArticleFactory(section=section,
                           image=None,
                           with_video=True,
                           is_news=True,
                           is_main_news=True)  # news
            ArticleFactory(section=section,
                           image=None,
                           with_video=True,
                           is_day_material=True)  # main material

        resp = self.app.get('/video/')
        self.assertEqual(resp.status_code, 200)
        self.assertIn('main_news', resp.context)
        self.assertIn('main_material', resp.context)

        data = resp.context['materials']
        self.assertEqual(len(data), 3)

        self.assertEqual(data['video_politic']['section'], section1)
        self.assertEqual(len(data['video_politic']['articles']), 3)

        self.assertEqual(data['video_partner_nevextv']['section'], section2)
        self.assertEqual(len(data['video_partner_nevextv']['articles']), 2)

        self.assertEqual(data['video_national']['section'], section3)
        self.assertEqual(len(data['video_national']['articles']), 5)

        self.assertContains(resp, 'Репортаж дня')
        self.assertContains(resp, 'Главный сюжет')
        self.assertContains(resp, 'Политика')
        self.assertContains(resp, 'ТВ')
        self.assertContains(resp, 'Народ')
Пример #10
0
    def test_index_page_200(self):
        article = ArticleFactory(title='Свет фар', is_news=True)

        resp = self.app.get('/pda/')
        self.assertEqual(resp.status_code, 200)
        self.assertEqual(resp.template_name[0], 'pda/index.html')
        self.assertEqual(resp.context['main_news'], article)

        self.assertContains(resp, 'Свет фар')
Пример #11
0
    def test_index_page(self):
        author = AuthorFactory(first_name='Глеб', last_name='Круглый')

        ArticleFactory(title='Белая бумага', authors=[author])
        ArticleFactory(title='Плотный картон', is_active=False)
        ArticleFactory(title='Толстая тетрадь')
        ArticleFactory(title='Ватман', discussion_status='close')

        resp = self.app.get('/forum/')
        self.assertEqual(resp.status_code, 200)

        articles = resp.context['object_list']
        self.assertEqual(len(articles), 2)
        self.assertEqual(articles[0].title, 'Толстая тетрадь')
        self.assertEqual(articles[1].title, 'Белая бумага')

        self.assertContains(resp, 'Белая бумага')
        self.assertContains(resp, 'Толстая тетрадь')
        self.assertContains(resp, 'Круглый Глеб')
        self.assertNotContains(resp, 'Плотный картон')
Пример #12
0
    def test_article_detail_page_200(self):
        article = ArticleFactory(section__slug='politic',
                                 title='Сильный шок',
                                 content='Долгоживущий поток')

        resp = self.app.get('/pda/material/politic/{}/'.format(article.id))
        self.assertEqual(resp.status_code, 200)
        self.assertEqual(resp.template_name[0], 'pda/articles/detail.html')

        self.assertEqual(resp.context['object'], article)
        self.assertEqual(resp.context['art_section'].slug, 'politic')

        self.assertContains(resp, 'Сильный шок')
        self.assertContains(resp, 'Долгоживущий поток')
Пример #13
0
    def test_detail_page(self):
        author = AuthorFactory(first_name='Игорь',
                               last_name='Светлов',
                               description='Родился, женился и т.д.')

        ArticleFactory(authors=[author], title='Суббота')
        ArticleFactory(authors=[author], title='Воскресенье')
        ArticleFactory(authors=[author], is_active=False)
        ArticleFactory(with_author=True)

        resp = self.app.get('/author/{}/'.format(author.id))
        self.assertEqual(resp.status_code, 200)

        articles = resp.context['obj_atricles']
        self.assertEqual(len(articles), 2)
        self.assertEqual(resp.context['object'], author)

        self.assertContains(resp, 'Автор - Светлов Игорь')
        self.assertContains(resp, 'Об авторе')
        self.assertContains(resp, 'Родился, женился и т.д.')

        self.assertContains(resp, 'Последние статьи автора')
        self.assertContains(resp, 'Суббота')
        self.assertContains(resp, 'Воскресенье')
Пример #14
0
    def test_create_vote_article_anonymous(self):
        article = ArticleFactory()

        self.app.get('/')  # create session_key
        token = Session.objects.first().session_key

        resp = self.app.post('/votes/article/', {
            'object_id': article.id,
            'score': 4
        },
                             HTTP_REFERER='/material/news/1/')
        self.assertEqual(resp.status_code, 302)
        self.assertEqual(resp.url, '/material/news/1/')

        votes = Vote.objects.all()
        self.assertEqual(len(votes), 1)
        self.assertEqual(votes[0].token, token)
        self.assertEqual(votes[0].object_id, article.id)
        self.assertEqual(votes[0].score, 4)
Пример #15
0
    def test_create_fail(self):
        article = ArticleFactory(section__slug='politic')

        data = {
            'article': article.id,
            'parent': '',
            'username': '******',
            'title': '',
            'content': '',
            'captcha_0': '*',
            'captcha_1': 'passed'
        }
        resp = self.app.post('/comment/create/', data)
        self.assertEqual(resp.status_code, 200)
        self.assertEqual(resp.template_name[0], 'articles/create_comment.html')

        self.assertEqual(resp.context['form'].errors['content'][0],
                         'Обязательное поле.')
        self.assertContains(resp, 'Обязательное поле.')
Пример #16
0
    def test_thread_page(self):
        article = ArticleFactory(title='Печенька')

        CommentFactory(title='Круг', content='Яркий', article=article)
        CommentFactory(title='Квадрат', content='Бледный', article=article)
        CommentFactory(title='Ромб', content='Серый')

        resp = self.app.get('/forum/{}/'.format(article.id))
        self.assertEqual(resp.status_code, 200)

        comments = resp.context['object_list']
        self.assertEqual(len(comments), 2)
        self.assertEqual(comments[0].title, 'Круг')
        self.assertEqual(comments[1].title, 'Квадрат')

        self.assertContains(resp, ':: Печенька')
        self.assertContains(resp, 'Яркий')
        self.assertContains(resp, 'Бледный')
        self.assertNotContains(resp, 'Серый')
        self.assertContains(resp, 'Ответить')
Пример #17
0
    def test_create_vote_article_user(self):
        article = ArticleFactory()

        user = UserFactory(username='******')
        user.set_password('secret')
        user.save()
        self.app.login(username='******', password='******')

        resp = self.app.post('/votes/article/', {
            'object_id': article.id,
            'score': 2
        },
                             HTTP_REFERER='/material/news/1/')
        self.assertEqual(resp.status_code, 302)
        self.assertEqual(resp.url, '/material/news/1/')

        votes = Vote.objects.all()
        self.assertEqual(len(votes), 1)
        self.assertEqual(votes[0].user, user)
        self.assertEqual(votes[0].object_id, article.id)
        self.assertEqual(votes[0].score, 2)
Пример #18
0
    def test_detail_video_page(self):
        section = VideoSectionFactory(name='Политика', slug='video_politic')
        article = ArticleFactory(title='Скорость света',
                                 section=section,
                                 image=None,
                                 video='https://www.youtube.com/watch?v=bob')

        resp = self.app.get('/video/{}/'.format(article.id))
        self.assertEqual(resp.status_code, 200)

        self.assertNotIn('main_material', resp.context)
        self.assertEqual(resp.context['main_news'], article)

        data = resp.context['materials']
        self.assertEqual(data['video_politic']['section'], section)
        self.assertEqual(len(data['video_politic']['articles']), 1)

        self.assertContains(resp, 'Скорость света')
        self.assertContains(
            resp,
            '<iframe width="560" height="315" src="https://www.youtube.com/embed/bob"'
        )
Пример #19
0
    def handle(self, *args, **kwargs):
        STR = LOW
        if kwargs.get('middle'):
            STR = MIDDLE
        elif kwargs.get('height'):
            STR = HEIGHT
        self.stdout.write('A <{}> strategy is chosen'.format(STR['label']))

        article_ct = ContentType.objects.get_for_model(Article)
        comment_ct = ContentType.objects.get_for_model(Comment)
        choice_ct = ContentType.objects.get_for_model(Choice)

        self.stdout.write('Remove all data from DB')
        Comment.objects.all().delete()
        Multimedia.objects.all().delete()

        if kwargs.get('dev'):
            Article.objects.all().delete()
            Section.objects.all().delete()
            Notice.objects.all().delete()

        if kwargs.get('dev'):
            Author.objects.all().delete()

        if kwargs.get('dev'):
            Entry.objects.all().delete()
            Blogger.objects.all().delete()

        Choice.objects.all().delete()
        Poll.objects.all().delete()

        if kwargs.get('dev'):
            Tag.objects.all().delete()

        Vote.objects.all().delete()

        Resource.objects.all().delete()
        if kwargs.get('dev'):
            Partition.objects.all().delete()

        get_user_model().objects.exclude(is_staff=True).delete()

        # ---------------------

        tokens = [
            str(uuid.uuid4()).replace('-', '')
            for i in range(STR['token_count'])
        ]
        self.stdout.write('Generate users...')
        users = UserFactory.create_batch(STR['user_count'])

        if kwargs.get('dev'):
            self.stdout.write('Generate authors...')
            authors = AuthorFactory.create_batch(STR['author_count'])
        else:
            authors = list(Author.objects.all())

        if kwargs.get('dev'):
            self.stdout.write('Generate tags...')
            tags = TagFactory.create_batch(STR['tag_count'])
        else:
            tags = list(Tag.objects.all())

        if kwargs.get('dev'):
            self.stdout.write('Generate sections...')
            sections = [
                SectionFactory(name='Политический расклад', slug='politic'),
                SectionFactory(name='Экономическая реальность',
                               slug='economic'),
                SectionFactory(name='Жизнь регионов', slug='region'),
                SectionFactory(name='Общество и его культура', slug='society'),
                SectionFactory(name='Силовые структуры', slug='power'),
                SectionFactory(name='Особенности внешней политики',
                               slug='fpolitic'),
                SectionFactory(name='Компрометирующие материалы',
                               slug='kompromat'),
                SectionFactory(name='Московский листок', slug='moscow'),

                # video
                VideoSectionFactory(name='Новости политики',
                                    slug='video_politic'),
                VideoSectionFactory(name='Экономический расклад',
                                    slug='video_economic'),
                VideoSectionFactory(name='Проиcшествия',
                                    slug='video_accidents'),
                VideoSectionFactory(name='Внешняя политика',
                                    slug='video_fpolitic'),
                VideoSectionFactory(name='Общество и его культура',
                                    slug='video_society'),
                VideoSectionFactory(name='Народное видео',
                                    slug='video_national'),

                # partner video
                PartnerVideoSectionFactory(name='Луганск 24',
                                           slug='video_partner_lugansk24'),
                PartnerVideoSectionFactory(name='Программа Сергея Доренко',
                                           slug='video_partner_dorenko'),
                PartnerVideoSectionFactory(name='Красное.ТВ',
                                           slug='video_partner_krasnoetv'),
                PartnerVideoSectionFactory(name='Nevex.TV',
                                           slug='video_partner_nevextv')
            ]
        else:
            sections = list(Section.objects.all())

        a_count_list = [2, 0, 0, 0, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1, 1]

        if kwargs.get('dev'):
            self.stdout.write('Generate articles...')
            for i in range(len(sections) * STR['avg_art_count'] * 2):
                section = random.choice(sections)

                if section.is_video and not random.randint(0, 1):
                    continue

                params = dict(
                    section=section,
                    is_news=not bool(random.randint(0, 8)),
                    is_ticker=not bool(random.randint(0, 8)),
                    is_main_news=not bool(random.randint(0, 8)),
                    is_day_material=not bool(random.randint(0, 8)),
                )

                # authors
                a_count = random.choice(a_count_list)
                if not a_count:  # no authors
                    if random.randint(0, 1):
                        params['author_names'] = AuthorFactory.build(
                        ).cover_name
                else:
                    params['authors'] = random.sample(authors, a_count)

                # tags
                a_tags = random.sample(tags, random.randint(0, 6))
                if a_tags:
                    params['tags'] = a_tags

                # source
                if not random.randint(0, 5):
                    params['with_source'] = True
                    if random.randint(0, 1):
                        params['with_source_link'] = True

                if not random.randint(0, 20):
                    params['show_comments'] = False  # hide comments
                if not random.randint(0, 3):
                    params[
                        'discussion_status'] = Article.DISCUSSION_STATUS.close  # close discussion

                if section.is_video:
                    params.update(image=None, with_video=True)

                ArticleFactory(**params)

        self.stdout.write('Generate articles comments and media...')
        for article in Article.objects.all():
            # comments
            comment_count = random.randint(0, STR['max_com_count'])
            comment_tokens = random.sample(tokens, comment_count)
            comment_users = random.sample(users, comment_count)
            for j in range(comment_count):
                c_params = dict(article=article)
                if random.randint(0, 1):
                    c_params['token'] = comment_tokens[j]
                else:
                    c_params['user'] = comment_users[j]
                CommentFactory(**c_params)

            # multimedia
            if not random.randint(0, 8):
                if random.randint(0, 5):
                    MultimediaFactory(article=article)
                else:
                    MultimediaFactory.create_batch(2, article=article)

        if kwargs.get('dev'):
            self.stdout.write('Generate resources...')
            resource_types = [
                PartitionFactory(name='Персональные сайты'),
                PartitionFactory(name='Партии и общественные движения'),
                PartitionFactory(name='Оппозиционные СМИ'),
                PartitionFactory(name='Аналитика'),
                PartitionFactory(name='Креативные проекты'),
                PartitionFactory(name='Блоги и форумы'),
                PartitionFactory(name='Музыка'),
                PartitionFactory(name='Литература и искусство'),
                PartitionFactory(name='Региональные организации'),
                PartitionFactory(name='Библиотеки'),
                PartitionFactory(name='История')
            ]
        else:
            resource_types = list(Partition.objects.all())
        for i in range(len(resource_types) * 6):
            ResourceFactory(partition=random.choice(resource_types),
                            rating=random.randint(0, 10))

        self.stdout.write('Generate ratings(articles votes)...')
        all_article_ids = list(Article.objects.values_list('id', flat=True))
        article_ids = random.sample(all_article_ids,
                                    int(len(all_article_ids) *
                                        0.9))  # 90% articles with votes
        for article_id in article_ids:
            self.create_votes_for(article_id, article_ct,
                                  STR['max_art_vote_count'], tokens, users,
                                  lambda: random.randint(1, 5))

        self.stdout.write('Generate likes(comments votes)...')
        all_comment_ids = list(Comment.objects.values_list('id', flat=True))
        comment_ids = random.sample(all_comment_ids,
                                    int(len(all_comment_ids) *
                                        0.9))  # 90% comments with likes
        for comment_id in comment_ids:
            self.create_votes_for(comment_id, comment_ct,
                                  STR['max_like_count'], tokens, users,
                                  lambda: random.choice([-1, 1]))

        if kwargs.get('dev'):
            self.stdout.write('Generate notices...')
            for i in range(STR['notice_count']):
                random_status = random.randint(0, 2)
                if random_status == 1:
                    NoticeFactory(status=Notice.STATUS.new)
                elif random_status == 2:
                    NoticeFactory(status=Notice.STATUS.rejected)
                else:
                    NoticeFactory()

        self.stdout.write('Generate polls...')
        polls = PollFactory.create_batch(STR['poll_count'])
        for poll in polls:
            choices = ChoiceFactory.create_batch(random.randint(3, 8),
                                                 poll=poll)
            for choice in choices:
                self.create_votes_for(choice.id, choice_ct,
                                      STR['max_choice_vote_count'], tokens,
                                      users, lambda: 1)

        if kwargs.get('dev'):
            self.stdout.write('Generate bloggers with entries...')
            bloggers = BloggerFactory.create_batch(10)
            for blogger in bloggers:
                EntryFactory.create_batch(random.randint(
                    STR['min_entry_count'], STR['max_entry_count']),
                                          blogger=blogger)
Пример #20
0
    def test_get_rss(self):
        with freeze_time('2017-04-20 21:44:02'):
            section1 = SectionFactory(name='Политика', slug='politic')
            article1 = ArticleFactory(section=section1,
                                      title='Береза',
                                      description='Белая тонкая')

            section2 = VideoSectionFactory(name='Народ', slug='video_national')
            article2 = ArticleFactory(section=section2,
                                      title='Клен',
                                      description='Шуршащие листья')
            ArticleFactory(section=section2,
                           title='Ива',
                           description='Мягкие ветки',
                           is_active=False)

        resp = self.app.get('/export/rss/')
        self.assertEqual(resp.status_code, 200)
        self.assertEqual(resp.get('Content-Type'),
                         'application/rss+xml; charset=utf-8')

        root = ET.fromstring(resp.content)
        self.assertEqual(root.tag, 'rss')
        self.assertEqual(len(root), 1)

        channel = root[0]
        self.assertEqual(channel.tag, 'channel')
        self.assertEqual(len(channel), 9)

        self.assertEqual(channel[0].tag, 'title')
        self.assertEqual(channel[0].text, 'ФОРУМ.мск')

        self.assertEqual(channel[1].tag, 'link')
        self.assertEqual(channel[1].text, 'http://forum-msk.org')

        self.assertEqual(channel[2].tag, 'description')
        self.assertEqual(
            channel[2].text,
            'ФОРУМ.мск - Интернет-портал объединяющейся оппозиции')

        self.assertEqual(channel[4].tag, 'language')
        self.assertEqual(channel[4].text, 'ru-RU')

        self.assertEqual(channel[5].tag, 'lastBuildDate')
        self.assertEqual(channel[5].text, 'Thu, 20 Apr 2017 21:44:02 +0000')

        self.assertEqual(channel[6].tag, 'pubDate')
        self.assertEqual(channel[6].text, 'Thu, 20 Apr 2017 21:44:02 +0000')

        # article2
        self.assertEqual(channel[7].tag, 'item')
        self.assertEqual(len(channel[7]), 6)

        self.assertEqual(channel[7][0].tag, 'title')
        self.assertEqual(channel[7][0].text, 'Клен')
        self.assertEqual(channel[7][1].tag, 'link')
        self.assertTrue(channel[7][1].text.endswith(
            '/material/video/{}/'.format(article2.id)))
        self.assertEqual(channel[7][2].tag, 'description')
        self.assertEqual(channel[7][2].text, 'Шуршащие листья')
        self.assertEqual(channel[7][3].tag, 'pubDate')
        self.assertEqual(channel[7][3].text, 'Thu, 20 Apr 2017 21:44:02 +0000')
        self.assertEqual(channel[7][4].tag, 'guid')
        self.assertTrue(channel[7][4].text.endswith(
            '/material/video/{}/'.format(article2.id)))
        self.assertEqual(channel[7][5].tag, 'category')
        self.assertTrue(channel[7][5].attrib['domain'].endswith(
            '/material/video_national/'))

        # article1
        self.assertEqual(channel[8].tag, 'item')
        self.assertEqual(len(channel[8]), 6)

        self.assertEqual(channel[8][0].text, 'Береза')
        self.assertTrue(channel[8][1].text.endswith(
            '/material/politic/{}/'.format(article1.id)))
        self.assertEqual(channel[8][2].text, 'Белая тонкая')
        self.assertEqual(channel[8][3].text, 'Thu, 20 Apr 2017 21:44:02 +0000')
        self.assertTrue(
            channel[8][5].attrib['domain'].endswith('/material/politic/'))
Пример #21
0
class ArticleSubsectionTest(TestCase):
    """
    Tests for subsections of articles.
    """

    @classmethod
    def setUpTestData(cls):
        tags_factory(15)
        web_links_factory(15)
        badges_factory()
        accounts_factory(15)

    def setUp(self):
        self.article = ArticleFactory()
        self.article.full_clean()
        self.subsection = ArticleSubsectionFactory(article=self.article)
        self.subsection.full_clean()

    def test_create_subsection(self):
        data = dict(
            title='How to white obfusted python.',
            content=generate_text_by_min_length(1000, as_p=True),
            article=self.article,
        )
        subsection = ArticleSubsection(**data)
        subsection.full_clean()
        subsection.save()
        self.assertEqual(subsection.title, data['title'])
        self.assertEqual(subsection.slug, slugify(data['title'], allow_unicode=True))
        self.assertEqual(subsection.article, data['article'])
        self.assertEqual(subsection.content, data['content'])

    def test_update_subsection(self):
        data = dict(
            title='I never Meta model I didn`t like.',
            content=generate_text_by_min_length(1000, as_p=True),
            article=self.article,
        )
        #
        self.subsection.title = data['title']
        self.subsection.article = data['article']
        self.subsection.content = data['content']
        self.subsection.full_clean()
        self.subsection.save()
        #
        self.assertEqual(self.subsection.title, data['title'])
        self.assertEqual(self.subsection.slug, slugify(data['title'], allow_unicode=True))
        self.assertEqual(self.subsection.article, data['article'])
        self.assertEqual(self.subsection.content, data['content'])

    def test_delete_subsection(self):
        self.subsection.delete()

    def test_unique_slug(self):
        same_title = 'All grammer of English for nineteen minutes and thirty-sever seconds, in other words - quickly.'
        same_title_as_lower = same_title.lower()
        same_title_as_upper = same_title.upper()
        same_title_as_title = same_title.title()
        article1 = ArticleFactory()
        article2 = ArticleFactory()
        slug_same_title = slugify(same_title, allow_unicode=True)
        #
        subsection11 = ArticleSubsectionFactory(article=article1, title=same_title_as_lower)
        subsection12 = ArticleSubsectionFactory(article=article1, title=same_title_as_upper)
        subsection13 = ArticleSubsectionFactory(article=article1, title=same_title_as_title)
        subsection21 = ArticleSubsectionFactory(article=article2, title=same_title_as_lower)
        subsection22 = ArticleSubsectionFactory(article=article2, title=same_title_as_upper)
        subsection23 = ArticleSubsectionFactory(article=article2, title=same_title_as_title)
        #
        self.assertEqual(subsection11.title, same_title_as_lower)
        self.assertEqual(subsection11.slug, slug_same_title)
        self.assertEqual(subsection12.title, same_title_as_upper)
        self.assertEqual(subsection12.slug, slug_same_title + '-2')
        self.assertEqual(subsection13.title, same_title_as_title)
        self.assertEqual(subsection13.slug, slug_same_title + '-3')
        self.assertEqual(subsection21.title, same_title_as_lower)
        self.assertEqual(subsection21.slug, slug_same_title)
        self.assertEqual(subsection22.title, same_title_as_upper)
        self.assertEqual(subsection22.slug, slug_same_title + '-2')
        self.assertEqual(subsection23.title, same_title_as_title)
        self.assertEqual(subsection23.slug, slug_same_title + '-3')
Пример #22
0
class ArticleTest(TestCase):
    """
    Tests for articles.
    """

    @classmethod
    def setUpTestData(cls):
        tags_factory(15)
        web_links_factory(15)
        badges_factory()
        accounts_factory(15)

    def setUp(self):
        self.article = ArticleFactory()
        self.article.full_clean()

    def test_create_article(self):
        data = dict(
            title='Кому и зачем потребовалась комната чёрной материи.',
            quotation='Страха не должно быть ни перед чем!',
            header=generate_text_by_min_length(100, as_p=True),
            conclusion=generate_text_by_min_length(100, as_p=True),
            picture='http://levashov.com/foto111.jpeg',
            status=Article.STATUS_ARTICLE.published,
            account=Account.objects.random_accounts(1),
            source='http://levashov.com/komy_boitsia_net_smerti_ratibor.html',
        )
        article = Article(**data)
        article.full_clean()
        article.save()
        # adding tags and links
        article.tags.add(*Tag.objects.random_tags(4))
        article.links.add(*WebLink.objects.random_weblinks(3))
        # adding subsections
        ArticleSubsectionFactory(article=article)
        ArticleSubsectionFactory(article=article)
        ArticleSubsectionFactory(article=article)
        ArticleSubsectionFactory(article=article)
        ArticleSubsectionFactory(article=article)
        # adding comments
        for i in range(8):
            CommentFactory(content_object=article)
        # adding marks
        for i in range(10):
            MarkFactory(content_object=article)
        #
        self.assertEqual(article.title, data['title'])
        self.assertEqual(article.slug, slugify(data['title'], allow_unicode=True))
        self.assertEqual(article.header, data['header'])
        self.assertEqual(article.conclusion, data['conclusion'])
        self.assertEqual(article.picture, data['picture'])
        self.assertEqual(article.status, data['status'])
        self.assertEqual(article.quotation, data['quotation'])
        self.assertEqual(article.source, data['source'])
        self.assertEqual(article.account, data['account'])
        self.assertEqual(article.marks.count(), 10)
        self.assertEqual(article.subsections.count(), 5)
        self.assertEqual(article.tags.count(), 4)
        self.assertEqual(article.links.count(), 3)
        self.assertEqual(article.comments.count(), 8)

    def test_update_article(self):
        data = dict(
            title='Why Python does not have operator CASE-SWITCH.',
            quotation='Важно чтобы было что показать.',
            header=generate_text_by_min_length(100, as_p=True),
            conclusion=generate_text_by_min_length(100, as_p=True),
            picture='http://python.org/foto211.jpeg',
            status=Article.STATUS_ARTICLE.draft,
            account=AccountFactory(is_active=True),
            source='http://pydanny.com/django/why_python_does_not_have_operator_case_switch.html',
        )
        self.article.title = data['title']
        self.article.quotation = data['quotation']
        self.article.header = data['header']
        self.article.conclusion = data['conclusion']
        self.article.picture = data['picture']
        self.article.status = data['status']
        self.article.account = data['account']
        self.article.source = data['source']
        self.article.full_clean()
        self.article.save()
        self.assertEqual(self.article.title, data['title'])
        self.assertEqual(self.article.slug, slugify(data['title'], allow_unicode=True))
        self.assertEqual(self.article.quotation, data['quotation'])
        self.assertEqual(self.article.header, data['header'])
        self.assertEqual(self.article.conclusion, data['conclusion'])
        self.assertEqual(self.article.picture, data['picture'])
        self.assertEqual(self.article.status, data['status'])
        self.assertEqual(self.article.account, data['account'])
        self.assertEqual(self.article.source, data['source'])

    def test_delete_article(self):
        self.article.delete()

    def test_unique_slug(self):
        same_title = 'Использование Python для Web. Сравненительный анализ и смелые выводы.'
        same_title_as_lower = same_title.lower()
        same_title_as_upper = same_title.upper()
        same_title_as_title = same_title.title()
        slug_same_title = slugify(same_title, allow_unicode=True)
        account = Account.objects.random_accounts(1)
        new_account = Account.objects.exclude(pk=account.pk).random_accounts(1)
        #
        article11 = ArticleFactory(title=same_title_as_lower, account=account)
        article12 = ArticleFactory(title=same_title_as_upper, account=account)
        article13 = ArticleFactory(title=same_title_as_title, account=account)
        article21 = ArticleFactory(title=same_title_as_lower, account=new_account)
        article22 = ArticleFactory(title=same_title_as_upper, account=new_account)
        article23 = ArticleFactory(title=same_title_as_title, account=new_account)
        #
        self.assertEqual(article11.title, same_title_as_lower)
        self.assertEqual(article11.slug, slug_same_title)
        self.assertEqual(article12.title, same_title_as_upper)
        self.assertEqual(article12.slug, slug_same_title + '-2')
        self.assertEqual(article13.title, same_title_as_title)
        self.assertEqual(article13.slug, slug_same_title + '-3')
        self.assertEqual(article21.title, same_title_as_lower)
        self.assertEqual(article21.slug, slug_same_title)
        self.assertEqual(article22.title, same_title_as_upper)
        self.assertEqual(article22.slug, slug_same_title + '-2')
        self.assertEqual(article23.title, same_title_as_title)
        self.assertEqual(article23.slug, slug_same_title + '-3')

    def test_get_absolute_url(self):
        response = self.client.get(self.article.get_absolute_url())
        self.assertEqual(response.status_code, 200)

    def test_get_admin_page_url(self):
        raise NotImplementedError

    def test_get_rating(self):
        self.article.marks.clear()
        self.assertEqual(self.article.get_rating(), .0)
        MarkFactory(content_object=self.article, mark=2)
        MarkFactory(content_object=self.article, mark=1)
        MarkFactory(content_object=self.article, mark=0)
        MarkFactory(content_object=self.article, mark=4)
        MarkFactory(content_object=self.article, mark=5)
        MarkFactory(content_object=self.article, mark=1)
        MarkFactory(content_object=self.article, mark=4)
        self.assertEqual(self.article.get_rating(), 2.4286)

    def test_get_volume(self):

        # length header and conclusion
        self.article.header = generate_text_certain_length(300)
        self.article.conclusion = generate_text_certain_length(541)
        self.article.full_clean()
        self.article.save()

        # clear and a anew adding the subsections
        ArticleSubsectionFactory(article=self.article, content=generate_text_certain_length(300))
        ArticleSubsectionFactory(article=self.article, content=generate_text_certain_length(258))
        ArticleSubsectionFactory(article=self.article, content=generate_text_certain_length(941))
        self.assertEqual(self.article.get_volume(), 2340)

        # checkup with without subsections
        self.article.subsections.filter().delete()
        self.assertEqual(self.article.get_volume(), 841)

    def test_related_articles(self):
        raise NotImplementedError
Пример #23
0
 def setUp(self):
     self.article = ArticleFactory()
     self.article.full_clean()
     self.subsection = ArticleSubsectionFactory(article=self.article)
     self.subsection.full_clean()
Пример #24
0
 def setUp(self):
     self.article = ArticleFactory()
     self.article.full_clean()