예제 #1
0
파일: tests.py 프로젝트: gannetson/fogg_api
    def test_user_list(self):
        """
        Test the user list
        """
        url = reverse('user-list')
        users = UserFactory.create_batch(4)
        UserCountryFactory.create_batch(15, user=users[0])

        response = self.client.get(url, format='json')
        self.assertEqual(response.status_code, status.HTTP_200_OK)
        self.assertEqual(response.data['count'], 4)
예제 #2
0
 def handle(self, *args, **options):
     ClearDb().handle()
     big = options.get('great_count') or DEFAULT_BIG_NUMBER
     small = options.get('less_count') or DEFAULT_SMALL_NUMBER
     event_user_addr_place = (big - small) // 2
     event_user_addr = (big - small) - event_user_addr_place
     event_org_addr_place = small // 2
     event_org_addr = small - event_org_addr_place
     instances_without_event = small // 4
     User.objects.create_superuser('admin', '*****@*****.**', 'admin')
     EventUserWithPlaceFactory.create_batch(size=event_user_addr_place)
     EventUserWithoutPlaceFactory.create_batch(size=event_user_addr)
     EventOrganizerWithPlaceFactory.create_batch(size=event_org_addr_place)
     EventOrganizerWithoutPlaceFactory.create_batch(size=event_org_addr)
     MemberListFactory.create_batch(size=small)
     UserFactory.create_batch(size=instances_without_event)
     AddressFactory.create_batch(size=instances_without_event)
     PlaceFactory.create_batch(size=instances_without_event)
     SubscriptionFactory.create_batch(size=small)
     ReviewFactory.create_batch(size=small)
     self.stdout.write(self.style.SUCCESS('DB was successfully populated'))
예제 #3
0
def run(**kwargs):
    """Generate 'number' of users with 5 posts

    with 3 comments on each created by different users
    """
    number = kwargs.get('number', 5)

    if number < 1:
        raise ValueError("Incorrect 'number' argument")

    for user in UserFactory.create_batch(number):
        for num, post in enumerate(PostFactory.create_batch(5, user=user)):
            for comment in PostFactory.create_batch(3):
                post.add_comment(comment)

            if num % 3 == 0:
                ReportFactory(post=post, )
예제 #4
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)
예제 #5
0
파일: conftest.py 프로젝트: SmirnovsIgor/TP
def users():
    return UserFactory.create_batch(size=10)