简体   繁体   English

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

[英]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.

相关问题 如何在我的Django模板上下文中获得“debug”变量? - How do I get a “debug” variable in my Django template context? 如何在 Tensorflow 中获得 LSTM 的测试准确度 - How do I get the Test Accuracy for my LSTM in Tensorflow 我如何使用 user_passes_test 查看特定页面? - How do i use user_passes_test view specific page? 如何对自定义上下文管理器进行单元测试? - How do I unit test a custom context manager? 如何为这个模拟的上下文管理器和 ZipFile 编写适当的测试? - How do I write a proper test for this mocked context manager and ZipFile? Django 1.0测试:如何让会话在测试代码和被测试视图之间持久存在? - Django 1.0 Testing: how do I get a session to persist between test code and view being tested? 我如何测试/重构我的测试? - How do i test/refactor my tests? 如何从我的 AJAX 帖子获取数据到我的 Django 视图? - How do I get data from my AJAX Post to my Django View? 如何在Python Flask应用程序中获取记录器以使用每页视图的唯一ID进行记录? - How can I get my logger in a Python Flask app to use unique IDs per page view for logging? 如何正确地获取我的代码来测试二进制搜索的递归函数? - How do I correctly get my code to test out of a recursion function for binary search?
 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM