Search code examples
pythondjangodjango-testing

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?


Solution

  • 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']. Because the 404 is and exception which is raised. get_object_or_404 does not return an empty value which you could assert in your test.