예제 #1
0
파일: tests.py 프로젝트: cephey/country
    def test_import_entries(self):
        blogger1 = BloggerFactory(ext_id=11299)
        blogger2 = BloggerFactory(ext_id=14500)
        call_command(
            'migrate_entries',
            path=os.path.join(settings.BASE_DIR, 'fixtures/csv/forum_bloggers_news.csv')
        )
        entries = Entry.objects.order_by('id')
        self.assertEqual(len(entries), 4)

        self.assertEqual(entries[0].title, 'К киприотам России')
        self.assertTrue(entries[0].description.startswith('итак, г-н Медведев сообщил, что на Кипре заблокированы '
                                                          'деньги российских\nгосударственных структур.'))
        self.assertEqual(entries[0].blogger, blogger2)
        self.assertEqual(entries[0].link, 'http://denis-bilunov.livejournal.com/193383.html')
        self.assertEqual(entries[0].publish_date, datetime(2013, 3, 21, 7, 50, 35, tzinfo=pytz.utc))

        self.assertEqual(entries[1].title, 'Жанаозен: неизвестная трагедия')
        self.assertEqual(entries[1].blogger, blogger2)

        self.assertEqual(entries[2].description, 'Так так )))\n\n')
        self.assertEqual(entries[2].blogger, blogger1)

        self.assertEqual(entries[3].blogger, blogger1)
        self.assertEqual(entries[3].publish_date, datetime(2014, 4, 11, 9, 48, 39, tzinfo=pytz.utc))
예제 #2
0
파일: tests.py 프로젝트: cephey/country
    def test_download_blogger_photo(self):
        responses.add(responses.GET, 'http://anna.country.com/data/rss/',
                      body=open('fixtures/xml/blogger_rss.xml').read())
        responses.add(responses.GET, 'http://anna.country.com/12345678/87654321',
                      body=open('fixtures/i/flag.jpg', 'rb').read())

        blogger = BloggerFactory(link='http://anna.country.com', photo=None)
        update_bloggers_photos()

        blogger.refresh_from_db()
        self.assertTrue(blogger.photo)
        self.assertIn('bloggers/', blogger.photo.name)
예제 #3
0
파일: tests.py 프로젝트: cephey/country
    def test_last_entry_list_200(self):
        blogger1 = BloggerFactory()
        blogger2 = BloggerFactory()
        blogger3 = BloggerFactory(is_active=False)

        EntryFactory(blogger=blogger1, description='Красный волк')
        EntryFactory(blogger=blogger1, description='Черная лиса')
        EntryFactory(blogger=blogger2, description='Белый петух')
        EntryFactory(blogger=blogger2, description='Синие цыплята', is_active=False)
        EntryFactory(blogger=blogger3, description='Желтый медведь')

        resp = self.app.get('/bloggers/')
        self.assertEqual(resp.status_code, 200)
        self.assertEqual(resp.context['blogger_list'][0].id, blogger2.id)
        self.assertEqual(resp.context['blogger_list'][1].id, blogger1.id)

        self.assertContains(resp, 'Красный волк')
        self.assertContains(resp, 'Черная лиса')
        self.assertContains(resp, 'Белый петух')
        self.assertNotContains(resp, 'Синие цыплята')
        self.assertNotContains(resp, 'Желтый медведь')
예제 #4
0
파일: tests.py 프로젝트: cephey/country
    def test_blogger_entry_list_200(self):
        blogger = BloggerFactory()
        EntryFactory(blogger=blogger, description='Ниф-Ниф')
        EntryFactory(blogger=blogger, description='Наф-Наф')
        EntryFactory(blogger=blogger, description='Нуф-Нуф', is_active=False)

        resp = self.app.get('/bloggers/{}/'.format(blogger.id))
        self.assertEqual(resp.status_code, 200)
        self.assertEqual(resp.context['blogger_obj'].id, blogger.id)

        self.assertContains(resp, 'Ниф-Ниф')
        self.assertContains(resp, 'Наф-Наф')
        self.assertNotContains(resp, 'Нуф-Нуф')
예제 #5
0
파일: tests.py 프로젝트: cephey/country
    def test_download_latest_entries(self):
        responses.add(responses.GET, 'http://anna.country.com/data/rss/',
                      body=open('fixtures/xml/blogger_rss.xml').read())

        blogger = BloggerFactory(link='http://anna.country.com')
        download_latest_entries()

        entries = Entry.objects.order_by('id')
        self.assertEqual(len(entries), 2)

        self.assertEqual(entries[0].blogger, blogger)
        self.assertEqual(entries[0].title, 'Национальная валюта')
        self.assertEqual(entries[0].link, 'http://anna.country.com/260976.html')
        self.assertEqual(entries[0].publish_date, datetime(2017, 5, 3, 4, 5, 30, tzinfo=pytz.utc))
        self.assertTrue(entries[0].description.startswith('Сказать же публично правду о том, чем на самом деле'))

        self.assertEqual(entries[1].blogger, blogger)
        self.assertEqual(entries[1].title, 'Это круто!')
        self.assertEqual(entries[1].link, 'http://anna.country.com/260710.html')
        self.assertEqual(entries[1].publish_date, datetime(2017, 5, 2, 3, 43, 48, tzinfo=pytz.utc))
        self.assertIn('Первое\n\nи основное', entries[1].description)
예제 #6
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)
예제 #7
0
파일: tests.py 프로젝트: cephey/country
 def test_deprecated_url(self):
     blogger = BloggerFactory(ext_id=454540)
     resp = self.app.get('/bloggers/454540.html')
     self.assertEqual(resp.status_code, 200)
     self.assertEqual(resp.context['blogger_obj'].id, blogger.id)
예제 #8
0
파일: tests.py 프로젝트: cephey/country
 def test_blogger_entry_list_404(self):
     blogger = BloggerFactory(is_active=False)
     resp = self.app.get('/bloggers/{}/'.format(blogger.id))
     self.assertEqual(resp.status_code, 404)