Django测试更新帖子

时间:2018-12-19 17:00:44

标签: django unit-testing testing

我收到此消息“ feed.models.Post.DoesNotExist:帖子匹配查询不存在。”我相信它属于我不了解的UpdatePost类,因为有一个ID为1的帖子。为什么是这样?编辑:我添加了删除以完全测试CRUD功能

from django.test import TestCase, SimpleTestCase
from django.contrib.auth.models import User
from django.urls import reverse

from feed.models import Post

class Setup_Class(TestCase):

 def setUp(self):
    self.user = User.objects.create_user(username='jtur', email='jtur@accenture.com', password='onion')
    user = User.objects.first()
    Post.objects.create(title='test', content='more testing', author=user)

class PostTests(Setup_Class):

 def test_content(self):
    post = Post.objects.get(id=1)
    expected_post_title = f'{post.title}'
    expected_post_content = f'{post.content}'
    self.assertEquals(expected_post_title, 'test')
    self.assertEquals(expected_post_content, 'more testing')

 def test_post_list_view(self):
    response = self.client.get(reverse('feed-home'))
    self.assertEqual(response.status_code, 200)
    self.assertContains(response, 'more testing')
    self.assertTemplateUsed(response, 'feed/home.html')

class UpdatePost(Setup_Class):
  def test_post_update(self):
    post = Post.objects.first()
    post.title = "This has been changed"
    expected_post_title = f'{post.title}'
    self.assertEquals(expected_post_title, 'This has been changed')

 def test_post_updated_view(self):
    response = self.client.get(reverse('feed-home'))
    self.assertEqual(response.status_code, 200)
    self.assertContains(response, 'This has been changed')
    self.assertTemplateUsed(response, 'feed/home.html')

class DeletePost(Setup_Class):
 def test_post_delete(self):
    post = Post.objects.first()
    post.delete()
    val = False

    if post is None:
        val = True
    else:
        val = False

    self.assertTrue(val)

 def test_post_list_view(self):
    response = self.client.get(reverse('feed-home'))
    self.assertEqual(response.status_code, 200)
    self.assertNotContains(response, 'test')
    self.assertTemplateUsed(response, 'feed/home.html')

1 个答案:

答案 0 :(得分:0)

没有理由假定在您的setUp方法中创建的帖子的ID = 1。实际上,它可能不会在第一次测试后出现。即使每次运行后都会清空数据库,但通常不会重置序列。

您应该使用Post.objects.first()来获得第一篇帖子。

(但是请注意,您的test_content和test_post_update方法是毫无意义的;它们仅调用本机Django功能,您无需测试。测试应与测试应用程序的功能有关,例如更新或显示的视图帖子。)