python - 如何测试为 CBV ListView 生成的上下文中是否存在 'object_list'

标签 python django unit-testing testing tdd

我正在尝试编写一个测试,测试在基于类的 View ListView 传递的上下文中是否存在 object_list

目前我有代码:

View .py

    class BlogView(ListView):
        model = Post
        template_name = 'core/blog.html'

模型.py:

    class Post(models.Model):
        title = models.CharField(max_length=500)
        content = models.TextField()

测试.py

    class BlogListViewTests(TestCase):

        def setUp(self):
            self.resp = self.client.get('/blog/')

        def test_has_a_post_list(self):
            self.assertContains(u'post_list', self.resp.context)

当我运行测试时出现如下错误:

    Traceback (most recent call last):
      File "/home/breno/projects/blog/core/tests.py", line 36, in test_has_a_post_list
          self.assertContains(self.resp.context, 'post_list')
      File "/home/breno/.virtualenvs/blog/local/lib/python2.7/site-packages/django/test/testcases.py", line 325, in assertContains
          self.assertEqual(response.status_code, status_code,
     AttributeError: 'ContextList' object has no attribute 'status_code'

打印 self.resp.context 我看到一个带有键 u'post_list' 的 Tuble:

[[{'False': False, 'None': None, 'True': True}, {u'paginator': None, u'post_list': [], u'object_list': [ ],...,]]

我的测试出了什么问题?我怎样才能做这个测试?泰

最佳答案

class BlogListViewTests(TestCase):

    def setUp(self):
        self.resp = self.client.get('/blog/')

    def test_has_a_post_list(self):
        self.assertTrue('post_list' in self.resp.context)

关于python - 如何测试为 CBV ListView 生成的上下文中是否存在 'object_list',我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/22434217/

相关文章:

python - 如何提取 HTML 中元素的内容?

python - 如何重现由 sqlalchemy session 缓存引起的错误

python - 使用 python 社交身份验证邀请 Facebook 好友加入网站

带循环的 Python doctest

javascript - 在不发出值的情况下完成的 Rxjs 可观察通过单元测试,但不应该

java - 使用注释注入(inject)依赖项是否会消除依赖注入(inject)(外部配置)的主要好处?

python - 使用带有引号字符串列表的正则表达式

Django:来自 View 的初始值

python - Django allauth 重定向到注册

python - Python中的版本号比较