def setUpTestData(cls): """Create test report.""" cls.user = UserFactory() cls.reported_user = UserFactory() cls.report = UserReportFactory(created_by=cls.user, user=cls.reported_user) return super().setUpTestData()
def test_natural_key(self): poll = PollFactory() choice = ChoiceFactory() user = UserFactory() vote = Vote.objects.create(user=user, poll=poll, choice=choice) self.assertTupleEqual(vote.natural_key(), (poll.natural_key(), user.natural_key(), choice.natural_key()))
def test_delete(self): comment = CommentFactory() # anonymous resp = self.app.get('/comment/{}/delete/'.format(comment.id), HTTP_REFERER='/material/news/1/') self.assertEqual(resp.status_code, 403) self.assertTrue(Comment.objects.active().exists()) # auth user user = UserFactory(username='******') user.set_password('secret') user.save() self.app.login(username='******', password='******') resp = self.app.get('/comment/{}/delete/'.format(comment.id), HTTP_REFERER='/material/news/1/') self.assertEqual(resp.status_code, 403) self.assertTrue(Comment.objects.active().exists()) # admin user.is_staff = True user.save() resp = self.app.get('/comment/{}/delete/'.format(comment.id), HTTP_REFERER='/material/news/1/') self.assertEqual(resp.status_code, 302) self.assertEqual(resp.url, '/material/news/1/') self.assertFalse(Comment.objects.active().exists())
def setUp(self): self.user = UserFactory() self.user_token = TokenFactory(user=self.user) self.client.credentials( HTTP_AUTHORIZATION="Urbvan {}".format(self.user_token.key) )
def setUp(self): """Test case setup.""" self.user = UserFactory() self.token = Token.objects.create(user=self.user) self.user2 = UserFactory() self.token2 = Token.objects.create(user=self.user2) self.playlist = PlaylistFactory(user=self.user) self.playlist2 = PlaylistFactory() for i in range(3): PlaylistFactory() self.song = SongFactory() self.client.credentials(HTTP_AUTHORIZATION=f'Token {self.token}')
def setUp(self): owner = UserFactory() self.default_data = { "name": "My new location", "latitude": "1.120000000000003", "longitude": "1.0000000000000004", "owner": owner }
class LocationFactory(factory.django.DjangoModelFactory): class Meta: model = Location name = factory.Faker('slug') latitude = factory.Faker('latitude') longitude = factory.Faker('longitude') owner = UserFactory()
def test_create_forbidden(self): self.user = UserFactory() self.user_token = TokenFactory(user=self.user) self.client.credentials( HTTP_AUTHORIZATION="Urbvan {}".format(self.user_token)) data = {"name": "line", "color": "rojo"} response = self.client.post(self.url_create, data, format="json") self.assertEquals(response.status_code, 403)
class StationFactory(factory.django.DjangoModelFactory): class Meta: model = Station id = 'sta_20197633059d4231eab' location = LocationFactory() order = factory.Faker('random_number') is_active = factory.Faker('boolean') owner = UserFactory()
def setUp(self): """ Initialize the objects to use in tests for Location endpoints. In stations app. """ self.user = UserFactory() self.user_token = TokenFactory(user=self.user) self.client.credentials( HTTP_AUTHORIZATION="Urbvan {}".format(self.user_token.key))
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)
def setUp(self): """Test case setup.""" self.user = UserFactory() self.user_token = Token.objects.create(user=self.user) self.client.credentials(HTTP_AUTHORIZATION=f'Token {self.user_token}') self.artist = ArtistFactory() self.artist2 = ArtistFactory() self.artist3 = ArtistFactory() self.artist4 = ArtistFactory()
def test_detail_forbidden(self): self.user = UserFactory() self.user_token = TokenFactory(user=self.user) self.client.credentials( HTTP_AUTHORIZATION="Urbvan {}".format(self.user_token.key)) station = StationFactory() data = {"pk": station.id} url = str(self.url_detail).replace("pk", data["pk"]) response = self.client.get(url, data, format="json") self.assertEquals(response.status_code, 403)
def test_create_forbidden(self): self.user = UserFactory() self.user_token = TokenFactory(user=self.user) self.client.credentials( HTTP_AUTHORIZATION="Urbvan {}".format(self.user_token.key)) location = LocationFactory() data = {"order": 1, "is_active": True, "location": location.id} response = self.client.post(self.url_create, data, format="json") self.assertEquals(response.status_code, 403)
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'))
def setUp(self): self.user = UserFactory() self.user_token = TokenFactory(user=self.user) self.client.credentials( HTTP_AUTHORIZATION="Urbvan {}".format(self.user_token.key) ) instance, created = LineModel.objects.get_or_create(name='South', color='Red') self.create_read_url = reverse('lines:lines-list') self.read_update_delete_url = reverse( 'lines:lines-detail', kwargs={'pk': instance.pk} )
def test_create_vote_user(self): user = UserFactory(username='******') user.set_password('secret') user.save() self.app.login(username='******', password='******') poll = PollFactory() choice = ChoiceFactory(poll=poll) resp = self.app.post('/polls/', {'poll_id': poll.id, 'choices': choice.id}) self.assertEqual(resp.status_code, 302) self.assertEqual(resp.url, '/polls/{}/'.format(poll.id)) votes = Vote.objects.all() self.assertEqual(len(votes), 1) self.assertEqual(votes[0].content_object, choice) choice.refresh_from_db() self.assertEqual(choice.vote_count, 1) poll.refresh_from_db() self.assertEqual(poll.sum_votes, 1) # try again: has no effect resp = self.app.post('/polls/', {'poll_id': poll.id, 'choices': choice.id}) self.assertEqual(resp.status_code, 302) self.assertEqual(Vote.objects.count(), 1) choice.refresh_from_db() self.assertEqual(choice.vote_count, 1) poll.refresh_from_db() self.assertEqual(poll.sum_votes, 1)
def setUp(self): self.count = 10 # Create 10 tasks for random users for _ in range(self.count): TaskFactory() self.test_user = UserFactory() # Create 19 tasks for test user for _ in range(self.count * 2 - 1): TaskFactory(user=self.test_user) # Create 1 more testing task for test user self.test_task = TaskFactory(user=self.test_user) self.list_create_url = reverse('todo-list') self.access_token = self.get_access_token()
def test_redirect_auth_user(self): user = UserFactory(username='******') user.set_password('secret') user.save() self.app.login(username='******', password='******') resp = self.app.get('/login/') self.assertEqual(resp.status_code, 302)
def test_budgets_list(self): user_one_budget = UserFactory.create() user_two_budgets = UserFactory.create() budget = BudgetFactory.create(owner=user_one_budget) budget.members.add(user_two_budgets) BudgetFactory.create(owner=user_two_budgets) keys = ["id", "name", "owner", "is_owner"] response = self.client.get(reverse(self.LIST_USER_BUDGETS_REVERSE)) self.assertEquals(response.status_code, status.HTTP_401_UNAUTHORIZED) self.client.login(username=user_one_budget.username, password="******") response = self.client.get(reverse(self.LIST_USER_BUDGETS_REVERSE)) self.assertEquals(response.status_code, status.HTTP_200_OK) results = response.data["results"] self.assertEquals(len(results), 1) for key in keys: self.assertTrue(key in results[0]) self.client.logout() self.client.login(username=user_two_budgets.username, password="******") response = self.client.get(reverse(self.LIST_USER_BUDGETS_REVERSE)) self.assertEquals(response.status_code, status.HTTP_200_OK) results = response.data["results"] self.assertEquals(len(results), 2) self.client.logout()
def setUp(self): """Test case set up.""" self.song = SongFactory() self.song2 = SongFactory() for i in range(3): SongFactory() self.artist = ArtistFactory() self.artist_token = Token.objects.create(user=self.artist.user) self.user = UserFactory() self.user_token = Token.objects.create(user=self.user) self.client.credentials(HTTP_AUTHORIZATION=f'Token {self.user_token}')
def setUp(self): self.album = AlbumFactory() self.album2 = AlbumFactory() for i in range(3): AlbumFactory() self.artist = ArtistFactory() self.artist_token = Token.objects.create(user=self.artist.user) self.song = SongFactory(artist=self.artist, release_date=datetime.now()) self.user = UserFactory() self.user_token = Token.objects.create(user=self.user) self.client.credentials(HTTP_AUTHORIZATION=f'Token {self.user_token}')
def setUp(self): """ Initialize the objects to use in tests for Location endpoints. In stations app. """ self.user = UserFactory() self.user_token = TokenFactory(user=self.user) self.client.credentials( HTTP_AUTHORIZATION="Urbvan {}".format(self.user_token.key)) self.location = LocationFactory(owner=self.user) self.url = reverse("api_v1_stations:v1_retrieve_location", kwargs={'pk': self.location.id})
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, )
def test_create_forbidden(self): self.user = UserFactory() self.user_token = TokenFactory(user=self.user) self.client.credentials( HTTP_AUTHORIZATION="Urbvan {}".format(self.user_token)) line = LineFactory() station = StationFactory() data = { "line": line.id, "stations": [station.id], "direction": True, "is_active": True, } response = self.client.post(self.url_create, data, format="json") self.assertEquals(response.status_code, 403)
def test_report_only_once(self): """Report can be sent only once""" user = UserFactory() post = PostFactory() request = MagicMock() request.user = user request.method = 'POST' request.POST = {'reason': Report.HARASSMENT} view = ReportCreate() view.kwargs = {'pk': post.id} view.request = request view.post(request, pk=post.id) view.post(request, pk=post.id) self.assertEqual(post.reports.count(), 1) self.assertEqual(user.reports.count(), 1)
def test_login(self): user = UserFactory(username='******') user.set_password('secret') user.save() data = { 'username': '******', 'password': '******', 'captcha_0': '*', 'captcha_1': 'passed' } resp = self.app.post('/login/?next=/forum/', data) self.assertEqual(resp.status_code, 302) self.assertEqual(resp.url, '/forum/')
def setUp(self): owner = UserFactory() self.location_attributes = { "name": "My new location", "latitude": "1.120000000000003", "longitude": "1.0000000000000004", "owner": owner } self.serializer_data = { "name": "My new location", "latitude": "1.120000000000003", "longitude": "1.0000000000000004", "owner": owner } self.location = Location.objects.create(**self.location_attributes) self.serializer = LocationSerializer(instance=self.location)
def test_create_vote_comment_user(self): comment = CommentFactory() user = UserFactory(username='******') user.set_password('secret') user.save() self.app.login(username='******', password='******') resp = self.app.post('/votes/comment/', { 'object_id': comment.id, 'score': 1 }, 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, comment.id) self.assertEqual(votes[0].score, 1)
def test_login_fail(self): user = UserFactory(username='******') user.set_password('secret') user.save() data = { 'username': '******', 'password': '******', 'captcha_0': '*', 'captcha_1': 'passed' } resp = self.app.post('/login/', data) self.assertEqual(resp.status_code, 200) self.assertIn('введите правильные имя пользователя и пароль', resp.context['form'].errors['__all__'][0]) self.assertContains(resp, 'введите правильные имя пользователя и пароль') data = {'password': '******', 'captcha_0': '*', 'captcha_1': 'passed'} resp = self.app.post('/login/', data) self.assertEqual(resp.status_code, 200) self.assertContains(resp, 'Обязательное поле')
def test_update_vote_article_user(self): article = ArticleFactory() user = UserFactory(username='******') user.set_password('secret') user.save() self.app.login(username='******', password='******') VoteFactory(content_object=article, score=2, user=user) resp = self.app.post('/votes/article/', { 'object_id': article.id, 'score': 3 }, 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, 3)
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)