class PostTest(TestCase): """Tests for Post model.""" def setUp(self): self.post_1 = PostFactory(published=False) self.post_2 = PostFactory() def test_post_str(self): post_1 = Post.objects.get(id=self.post_1.id) post_2 = Post.objects.get(id=self.post_2.id) self.assertEqual(str(post_1), self.post_1.title) self.assertNotEqual(str(post_2), self.post_1.id) def test_post_url(self): django = Post.objects.get(id=self.post_1.id) self.assertEqual(f"/post/{django.id}/", django.get_absolute_url()) def test_post_published(self): post = Post.objects.get(title=self.post_1.title) self.post_1.published = True self.post_1.save() self.post_1.refresh_from_db() self.assertNotEquals(post.pub_date, self.post_1.pub_date)
def test_with_post_counts_adds_post_count_to_queryset(self): Tag.objects.create(name="docker") PostFactory.create(tags=["python"]) qs = Tag.objects.with_post_counts() values = qs.values("name", "post_count") self.assertIn({"name": "python", "post_count": 1}, values) self.assertIn({"name": "docker", "post_count": 0}, values)
def test_increment(self): test_post = PostFactory(views=10) current_views = test_post.views test_post.increment_views() incremented_views = test_post.views self.assertEqual(10, current_views) self.assertGreater(incremented_views, current_views)
def test_the_number_of_posts_to_display_when_a_user_visits(self): ''' superuserのリクエストはすべての投稿を表示 それ以外のユーザーは公開済みの投稿を表示 ''' self.assertEqual(Post.objects.all().count(), 0) non_published_count = 2 published_count = 3 PostFactory.create_batch(size=non_published_count, author=self.superuser, published_at=None) PostFactory.create_batch(size=published_count, author=self.superuser) # superuserのリクエスト client = Client() client.force_login(self.superuser) response = client.get('/') self.assertTrue(response.wsgi_request.user.is_superuser) self.assertEqual(len(response.context['posts']), non_published_count + published_count) self.assertQuerysetEqual(response.context['posts'], Post.objects.all(), transform=lambda x: x) # 一般ユーザーのリクエスト response = self.client.get('/') self.assertIn('posts', response.context) self.assertTrue(Post.objects.all().count() == non_published_count + published_count) self.assertTrue(len(response.context['posts']) == published_count) self.assertQuerysetEqual(response.context['posts'], Post.objects.published(), transform=lambda x: x)
def test_returns_correct_list_of_posts(self): post1 = PostFactory(status='published') post2 = PostFactory() post3 = PostFactory(status='published') response = self.client.get('/blog/') self.assertContains(response, post1.title) self.assertNotContains(response, post2.title) self.assertContains(response, post3.title)
def setUp(self): tags = {} for name in ['Python', 'Kaggle', 'Django']: tags[name] = TagFactory(name=name) PostFactory(tags=(tags['Python'], )) PostFactory(tags=(tags['Python'], tags['Django'])) PostFactory(tags=(tags['Kaggle'], ))
def setUp(self): posts = [ PostFactory.create(tags=["python", "docker"]), PostFactory.create(tags=["python"]), PostFactory.create(tags=["aws"]), PostFactory.create(), ] for post in posts: post.publish()
def test_search_for_post_contains_keyword(self): PostFactory(title='今日', content='Today', description='0') PostFactory(title='Today', content='今日', description='0') PostFactory(title='明日', content='tomorrow', description='-1') PostFactory(title='tomorrow', content='明日', description='-1') response = self.client.get('/?keyword=今日') self.assertEqual(response.context['posts'].count(), 2) self.assertEqual(Post.objects.all().count(), 4)
def populate(): ProfileFactory.create_batch(size=10) PostFactory.create_batch(size=4) PostImageFactory.create_batch(size=16) PaperFactory.create_batch(size=10) for p in Post.objects.all(): print(p) print("...population finished")
def _create_posts(self): """ """ count = randint(5, 10) for i in range(count): PostFactory.create(tags=(self.tags[i] for i in range(randint(1, 10)))) print("Created {0} Posts".format(count))
def _create_posts(self): """ """ count = randint(5, 10) for i in range(count): PostFactory.create( tags=(self.tags[i] for i in range(randint(1, 10)))) print("Created {0} Posts".format(count))
def test_can_get_user_posts(self): user1 = UserFactory() user2 = UserFactory() post1 = PostFactory(author=user1) PostFactory(author=user2) post3 = PostFactory(author=user1) user1_posts = user1.blog_posts.all() self.assertEqual(len(user1_posts), 2) self.assertIn(post1, user1_posts) self.assertIn(post3, user1_posts)
def handle(self, *args, **options): tags = TagFactory.create_batch(5) python_tag = TagFactory.create(word="python") for _ in range(10): post = PostFactory.create(tags=tags) print("post", post) for _ in range(5): post = PostFactory.create(tags=[python_tag]) print("post", post) for _ in range(2): post = PostFactory.create(published_date=None, tags=[python_tag] + tags)
def test_filter_not_draft_returns_in_published_date_order(self): now = timezone.now() yesterday = timezone.now() - timedelta(days=1) now_post = PostFactory.create(published=now) sleep(0.01) # make `created` different for each post yesterday_post = PostFactory.create(published=yesterday) posts = self.perform(draft=False) by_published_desc = sorted(posts, key=lambda post: post["published"], reverse=True) self.assertListEqual([p["id"] for p in by_published_desc], [now_post.pk, yesterday_post.pk])
def test_filter_draft_returns_drafts_only(self): # Create a draft PostFactory.create() # And a published post post = PostFactory.create() post.publish() posts = self.perform(draft=True) self.assertEqual(len(posts), 1) self.assertNotIn(post.pk, map(lambda post: post["id"], posts)) for post in posts: self.assertTrue(post["is_draft"])
class PostDetailTest(TestCase): def setUp(self): self.post = PostFactory(status='published') self.response = self.client.get(self.post.get_absolute_url()) def test_post_detail_renders_detail_template(self): self.assertTemplateUsed(self.response, 'blog/post/detail.html') def test_response_contains_post_title(self): self.assertContains(self.response, self.post.title) def test_unknown_post_returns_404(self): response = self.client.get('/blog/2000/01/02/hello-world/') self.assertEqual(response.status_code, 404) def test_no_comments(self): self.assertEqual(self.response.context['post'], self.post) self.assertEqual(list(self.response.context['comments']), []) self.assertEqual(self.response.context['new_comment'], None) def test_incorrect_post(self): bad_response = self.client.post(self.post.get_absolute_url(), {}) self.assertContains(bad_response, 'This field is required') self.assertEqual(self.response.context['new_comment'], None) def test_correct_post(self): good_response = self.client.post( self.post.get_absolute_url(), { 'name': 'user', 'email': '*****@*****.**', 'body': 'Sample comment body' }) self.assertContains(good_response, 'Sample comment body') self.assertContains(good_response, 'Your comment has been added.') self.assertEqual(good_response.context['new_comment'], Comment.objects.get(post=self.post)) def test_similar_posts(self): PostFactory(status='published') post2 = PostFactory(status='published') post3 = PostFactory(status='published') post4 = PostFactory(status='published') post4.tags.add('tag0', 'tag1', 'tag2') post3.tags.add('tag0', 'tag1') post2.tags.add('tag0') response = self.client.get(post4.get_absolute_url()) self.assertEqual(list(response.context['similar_posts']), [post3, post2])
def test_blog_tags__show_latest_posts(self): """Custom show_latest_posts tag works fine""" self.post5 = PostFactory(status='published') self.post6 = PostFactory(status='published') self.browser.get(self.live_server_url + '/blog/') # User sees five latest posts expected_posts = [ self.post6, self.post5, self.post4, self.post3, self.post1 ] actual_post_elements = self.browser.find_elements_by_css_selector( '#latest-posts a') actual_post_titles = [post.text for post in actual_post_elements] self.assertEqual(actual_post_titles, [post.title for post in expected_posts])
def test_filter_by_slug(self): post = PostFactory.create(title="Hello, world!", slug="hello-world") posts = self.perform(slug=post.slug) self.assertEqual(len(posts), 1) self.assertEqual(posts[0]["slug"], "hello-world") posts = self.perform(slug="good-bye") self.assertEqual(len(posts), 0)
def handle(self, *args, **options): # ==================================================================================== # Users & Groups # ==================================================================================== # create authors group authors_group, _ = Group.objects.get_or_create(name='authors') add_permission_to_add_model(Post, authors_group) # create 2 authors alberti, _ = User.objects.get_or_create(username='******', first_name='Rafael', last_name='Alberti') if authors_group not in alberti.groups.all(): alberti.groups.add(authors_group) douglas, _ = User.objects.get_or_create(username='******', first_name='Douglas', last_name='Adams') if authors_group not in douglas.groups.all(): douglas.groups.add(authors_group) authors = [alberti, douglas] # ==================================================================================== # Posts # ==================================================================================== if Post.objects.count() > 10: logger.info('There are {} posts already in DB, not generating more...'.format(Post.objects.count())) else: for _ in range(42): PostFactory(author=authors[int(round(random()))])
def test_post(self): test_post = PostFactory.create(author__first_name='Sebastian', author__last_name='Fest', title='My test title', subtitle='A subtitle for the test post') self.assertTrue(isinstance(test_post, Post)) self.assertEqual('My test title', test_post.__str__())
def test_filter_not_draft_returns_published_only(self): post = PostFactory.create() post.publish() posts = self.perform(draft=False) self.assertEqual(len(posts), 1) post_data = posts[0] self.assertEqual(post_data["id"], post.pk) self.assertFalse(post_data["is_draft"])
def test_if_tag_is_provided_filter_post_by_it(self): posts = [PostFactory(status='published') for _ in range(4)] posts[0].tags.add('test') posts[2].tags.add('test') response = self.client.get('/blog/tag/test/') self.assertContains(response, 'Posts tagged with "test"') self.assertEqual(list(response.context['posts']), [posts[2], posts[0]]) self.assertEqual(response.context['tag'], Tag.objects.get(name='test'))
def backgrond(context): posts = [] for row in context.table: user = User.objects.filter(username=row['author']).first() posts.append( PostFactory(id=row['id'], title=row['title'], text=row['text'], author=user))
def test_if_published_and_has_relative_then_relative_with_fields(self): now = timezone.now() post = PostFactory.create(published=now) relative = self.get_relative(now) response = self.perform(post) expected = {"title": relative.title, "slug": relative.slug} data = response.data[self.relative_field] actual = {field: data.get(field) for field in expected} self.assertEqual(actual, expected)
def setUp(self): self.user_1 = UserFactory() self.user_2 = UserFactory() for i in range(15): user = self.user_1 if i % 2 == 0 else self.user_2 published = True if i % 2 == 0 else False PostFactory(published=published, author=user)
def setUp(self): self.user_1 = UserFactory() self.user_2 = UserFactory() for i in range(10): user = self.user_1 if i % 2 == 0 else self.user_2 published = True if i % 2 == 0 else False post = PostFactory(published=published, author=user, tags=(self.tag_1, )) print(post.tags)
def test_can_update_image_url(self): initial_url = "https://fakeimg.pl/128/" new_url = "https://fakeimg.pl/256/" post = PostFactory.create(image_url=initial_url) url = f"/api/posts/{post.slug}/" data = {"image_url": new_url} response = self.client.patch(url, data=data, format="json") self.assertEqual(response.status_code, 200) post = Post.objects.get(pk=post.pk) # reload from DB self.assertEqual(post.image_url, new_url)
def test_pagination(self): ''' ページネーションの動作確認 ''' # 1ページ当たりの表示するPost数 views.IndexView.paginate_by = 10 # 15件のPostを作成 PostFactory.create_batch(size=15, author=self.superuser) # 1ページ目 response = self.client.get('/') self.assertIn('paginator', response.context) self.assertEquals(10, response.context['posts'].count()) self.assertEquals(15, Post.objects.all().count()) # 2ページ目 response = self.client.get('/?page=2') self.assertEquals(5, response.context['posts'].count()) # 3ページ目 response = self.client.get('/?page=3') self.assertEquals(404, response.status_code)
class PostShareTest(TestCase): def setUp(self): self.post = PostFactory(status='published') self.response = self.client.get('/blog/%s/share/' % self.post.id) def sample_post_share(self): return self.client.post('/blog/%s/share/' % self.post.id, data={ 'name': 'user', 'sender': '*****@*****.**', 'recipient': '*****@*****.**', 'comments': 'sample comments' }) def test_post_share_renders_share_template(self): self.assertTemplateUsed(self.response, 'blog/post/share.html') def test_response_contains_post_title(self): self.assertContains(self.response, self.post.title) def test_unknown_post_returns_404(self): response = self.client.get('/blog/999/share/') self.assertEqual(response.status_code, 404) def test_get_method_does_not_send_email(self): self.assertEqual(len(mail.outbox), 0) def test_get_method_returns_form(self): self.assertContains(self.response, 'form') def test_post_method_send_email(self): self.sample_post_share() subject = 'user ([email protected]) recommends you reading "%s"' % self.post.title self.assertEqual(len(mail.outbox), 1) self.assertEqual(mail.outbox[0].subject, subject) def test_post_method_send_email_with_correct_url(self): self.sample_post_share() self.assertIn(self.post.get_absolute_url(), mail.outbox[0].body) def test_post_method_returns_success_message(self): post_response = self.sample_post_share() self.assertContains(post_response, '"%s" was successfully sent.' % self.post.title) def test_post_with_invalid_form_returns_form(self): bad_post_response = self.client.post('/blog/%s/share/' % self.post.id) self.assertContains(bad_post_response, 'form')
def setUp(self): self.post0 = PostFactory(status='published') self.post1 = PostFactory(status='published') self.post2 = PostFactory() self.post3 = PostFactory(status='published') self.post4 = PostFactory(status='published') self.post3.tags.add('test_tag_0') self.post4.tags.add('test_tag_0') self.post4.tags.add('test_tag_1') self.browser = webdriver.Firefox() self.browser.get(self.live_server_url + '/blog/') # Go to the main page
def test_similar_posts(self): PostFactory(status='published') post2 = PostFactory(status='published') post3 = PostFactory(status='published') post4 = PostFactory(status='published') post4.tags.add('tag0', 'tag1', 'tag2') post3.tags.add('tag0', 'tag1') post2.tags.add('tag0') response = self.client.get(post4.get_absolute_url()) self.assertEqual(list(response.context['similar_posts']), [post3, post2])
class TestPostShare(StaticLiveServerTestCase): def setUp(self): self.browser = webdriver.Firefox() self.post = PostFactory(status='published') def tearDown(self): self.browser.quit() def test_post_share(self): # User can saw share link on a post detail page self.browser.get(self.live_server_url + self.post.get_absolute_url()) share_url = self.browser.find_element_by_link_text('Share this post') # He click on it and redirects to share form share_url.click() self.assertEqual( self.browser.find_element_by_tag_name('h1').text, 'Share "%s" by e-mail' % self.post.title) # He clicks send button and sees required errors self.browser.find_element_by_id('send').click() self.assertEqual( len(self.browser.find_elements_by_class_name('errorlist')), 3) # He fills out the form and clicks send, than he sees a success page self.browser.find_element_by_id('id_name').send_keys('user') self.browser.find_element_by_id('id_sender').send_keys( '*****@*****.**') self.browser.find_element_by_id('id_recipient').send_keys( '*****@*****.**') self.browser.find_element_by_id('id_comments').send_keys( 'sample comment') self.browser.find_element_by_id('send').click() self.assertEqual( self.browser.find_element_by_tag_name('h1').text, 'E-mail successfully sent') # Email has been sent self.assertEqual(len(mail.outbox), 1) subject = 'user ([email protected]) recommends you reading "%s"' % self.post.title self.assertEqual(mail.outbox[0].subject, subject)
def setUp(self): self.browser = webdriver.Firefox() self.post = PostFactory(status='published', publish=timezone.datetime(2016, 10, 11, 2, 27, tzinfo=UTC)) self.post.tags.add('tag0', 'tag1') # He create and tag few posts self.post1 = PostFactory(status='published') self.post2 = PostFactory(status='published') self.post3 = PostFactory(status='published') self.post1.tags.add('tag0', 'tag1') self.post2.tags.add('tag0') # User goes to the post page self.browser.get(self.live_server_url + self.post.get_absolute_url())
def step_impl(context): posts = [PostFactory(title=row['title'], slug=row['slug'], author=UserFactory(username=row['author']), body=row['body']) for row in context.table]
def test_image(self): test_post = PostFactory(background=TEST_IMAGE) self.assertTrue('default.jpg' in test_post.image) setattr(test_post, 'background', None) test_post.save() self.assertTrue(test_post.image is None)
def test_post_image(self): PostFactory.create_batch(size=2) test_image = PostImageFactory(caption='Test') self.assertTrue(isinstance(test_image, PostImage)) self.assertEqual('Test', test_image.__str__())
def test_last_viewed(self): test_post = PostFactory(last_accessed=(timezone.now() - datetime.timedelta(days=1))) last = test_post.last_accessed test_post.last_viewed() now = test_post.last_accessed self.assertGreater(now, last)