【发布时间】:2013-01-01 18:52:27
【问题描述】:
我有一个单元测试在一个断言中失败,该断言在同一测试用例类中的另一个测试中通过。
这是通过测试:
def test_home(self):
c = Client()
resp = c.get('/')
self.assertEqual(resp.status_code, 200)
self.assertTrue('a_formset' in resp.context)
这是失败的测试:
def test_number_initial_number_of_forms(self):
c = Client()
resp = c.get('/')
self.assertEqual(resp.context['a_formset'].total_form_count(), 1)
在第二个测试中,我收到错误 TypeError: 'NoneType' object has no attribute '__getitem__'。
如果我以
身份执行第二个测试def test_number_initial_number_of_forms(self):
c = Client()
resp = c.get('/')
self.assertTrue('a_formset' in resp.context)
self.assertEqual(resp.context['a_formset'].total_form_count(), 1)
我收到错误 TypeError: argument of type 'NoneType' is not iterable。我在第二个测试中通过打印语句确认 response.content 包含我希望获得的页面、状态代码正确且模板正确。但在第二次测试中,响应的上下文始终是None。
我正在通过标准的“python manage.py test ...”接口运行我的 Django 单元测试,所以我不相信我遇到了“context is empty from the shell”问题。
这是怎么回事?
编辑:
如果我在每个测试中添加print type(resp.context['a_formset']),对于工作测试,我会得到<class 'django.forms.formsets.AFormFormSet'>。对于非工作测试,我再次得到TypeError: 'NoneType' object has no attribute '__getitem__'。
【问题讨论】:
-
@sneawo 是的,它是一个表单集。
-
在您的工作和非工作测试中,临时添加行
print type(resp.context['a_formset'])。你可能没有得到你所期望的。 -
@EvanPorter 将结果添加到问题中。可以预见(不幸的是),我得到了工作测试的对象和非工作测试的缺失属性错误。 :-/
-
奇怪的是,如果模板已使用该上下文成功呈现,则该上下文将为 None。 PyCharm 支持调试 Django 测试,我会使用这个工具并在你的视图末尾添加一个断点,在任何具有 process_response() 钩子的中间件中,以及你可能添加的任何模板上下文处理器中,跟踪上下文。跨度>
标签: python django django-unittest