Django unit test - response context is None

283 views
Skip to first unread message

Web Architect

unread,
Oct 31, 2018, 8:24:15 AM10/31/18
to Django users
Hi,

We are using django 1.11 for our ecommerce site.

We are developing unit tests for our views using django testing framework. We are facing issue with a simple implementation:

import unittest


from django.urls import reverse

from django.test import Client


class ViewTests(unittest.TestCase):

    def setUp(self):

        self.client = Client()


    def test_View(self):

        url = '/some-url/'

        

        response = self.client.get(url)

        products = response.context['products']


In the above test case, response.context is coming out to be None and hence, response.context['products'] is throwing exception. Whereas when I run the same on django admin shell, response.context has context object dict. 


I am quite confused why this is happening. I couldn't find any reason in the django documents.


Would really appreciate if someone could help me with the above.  


Thanks,

        

Jason

unread,
Oct 31, 2018, 8:49:40 AM10/31/18
to Django users
Two things I can see:

you should be inheriting from TestCase in django.test, not unittest.  
Second, you should find your answer at https://stackoverflow.com/questions/27136048/django-unit-test-response-context-is-none . I believe the attribute you're trying to access was deprecated in django 1.8 and was probably removed in 1.11

Web Architect

unread,
Oct 31, 2018, 9:21:05 AM10/31/18
to Django users
Hi Jason,

Thanks for your prompt response. 

I was using Django TestCase but it wasn't working then. Hence, I resorted to unittest as shown in Django 1.11 documentation. Also, the attribute was working fine in django shell. 

Please refer to the documentation here:

I will check the link you have provided for the solution.

Thanks.
Reply all
Reply to author
Forward
0 new messages