Django的单元测试客户端响应具有空上下文(Django unit test client res

2019-07-18 08:59发布

我的影片未能在通过在同一个测试用例类另一个测试断言单元测试。

下面是测试通过:

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第二次考试。

我通过标准的“蟒蛇manage.py测试...”界面运行我的Django的单元测试,所以我不相信我跑步进入“ 上下文是从壳空 ”的问题。

这是怎么回事这个?

编辑:

如果我添加print type(resp.context['a_formset'])对每个试验中,用于工作测试我得到<class 'django.forms.formsets.AFormFormSet'> 对于非工作测试,我得到TypeError: 'NoneType' object has no attribute '__getitem__'一次。

Answer 1:

Today I run into the same issue. The second test gets same page has nothing in response.context

I made a research and found that 1) test client uses signals to populate context, 2) my view method is not called for the second test

I turned on a debugger and found that the guilty one is 'Cache middleware'. Knowing that I found this ticket and this SO question (the latter has a solution).

So, in short: the second request is served from cache, not from a view, thus a view is not executed and test-client doesn't get the signal and have no ability to populate context.

I can not disable cache middleware for my project, so I added next hack-lines into my settings:

if 'test' in sys.argv:
   CACHE_MIDDLEWARE_SECONDS = 0

Hope this helps someone



Answer 2:

这是因为你遇到了一些错误,退出外壳,并重新启动它。

但是你忘了启动环境 ......

from django.test.utils import setup_test_environment
>>> setup_test_environment()

这是我的问题。 希望它的工作原理...



文章来源: Django unit test client response has empty context