[英]How do i get the context to test my view page?
I'm trying to test my search results to check the response when there are no results.我正在尝试测试我的搜索结果,以在没有结果时检查响应。
this is the function in my view:这是我认为的功能:
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
this is my test class and function这是我的测试类和函数
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'],[])
but i keep getting this error但我一直收到这个错误
self.assertQuerysetEqual(response2.context['book'],[])
File "C:----\context.py", line 83, in __getitem__
raise KeyError(key)
KeyError: 'book'
how do I check if my book query got empty results?如何检查我的图书查询结果是否为空?
If this line: result['book'] = get_object_or_404(books,ISBN = query)
causes 404
to be raised, then, you will have nothing in result['book']
.如果这一行:
result['book'] = get_object_or_404(books,ISBN = query)
导致404
被引发,那么,你在result['book']
中将一无所有。 Because the 404
is and exception which is raised.因为
404
是引发的异常。 get_object_or_404
does not return an empty value which you could assert in your test. get_object_or_404
不会返回您可以在测试中断言的空值。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.