如何获取上下文来测试我的视图页面?

我正在尝试测试我的搜索结果,以检查没有结果时的响应。


这是我认为的功能:


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'

如何检查我的图书查询是否得到空结果?


杨__羊羊
浏览 37回答 1
1回答

PIPIONE

如果这一行:result['book'] = get_object_or_404(books,ISBN = query)导致404被提出,那么,你将在 中什么都没有result['book']。因为404is 和引发的异常。get_object_or_404不返回您可以在测试中断言的空值。
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python