我有一個單元測試失敗的斷言,通過在同一個測試用例類的另一個測試。Django單元測試客戶端響應具有空的上下文
下面是測試通過:
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__'
。
'a_form'是一個formset? – sneawo
@sneawo是的,這是一個formset。 –
在您的工作和非工作測試中,臨時添加'print type(resp.context ['a_formset'])''行。你可能沒有得到你所期望的。 –