问题描述
我正在尝试测试搜索结果,以在没有结果时检查响应。
这是我认为的功能:
def get_context_data(self,*args,**kwargs):
result = super().get_context_data(**kwargs)
query = self.request.GET.get('q')
result['book'] = get_object_or_404(books,ISBN = query)
return result
这是我的测试类和功能
class Test_Search_results_view(TestCase):
def test_no_results(self):
response1 = self.client.get('/TextSearch/results1/?books=new&q=9780815345244')
response2 = self.client.get('/TextSearch/results2/?books=new&author=Bruce+Alberts&Book+Name=Molecular+Biology+of+the+Cell&edition=6')
self.assertEqual(response1.status_code,404)
self.assertEqual(response2.status_code,404)
self.assertQuerysetEqual(response2.context['book'],[])
但我一直收到此错误
self.assertQuerysetEqual(response2.context['book'],[])
File "C:----\context.py",line 83,in __getitem__
raise KeyError(key)
KeyError: 'book'
如何检查我的图书查询是否有空结果?
解决方法
如果以下行:result['book'] = get_object_or_404(books,ISBN = query)
引起404
升高,那么result['book']
中将什么也没有。因为404
是和引发的异常。 get_object_or_404
不会返回您可以在测试中断言的空值。