Django unit test response context is None
Asked Answered
N

4

5

Why is response.context None in the following tests? I've checked response.content and it is ''. if I remove the assertIsNotNone line I get a TypeError: 'NoneType' object is not subscribable

def test_log_view_with_no_entries(self):
    """
    If no logs are available, an appropriate message should be displayed.
    """
    response = self.client.get(reverse('swpgr:logs'))
    self.assertIsNotNone(response.context)
    self.assertEqual(response.status_code, 200)
    self.assertContains(response, "No logs are available.")
    self.assertQuerysetEqual(response.context['log_list'], [])

def test_log_view_with_one_entry(self):
    """
    Logs should be displayed it table.
    """
    time = timezone.now()
    t = LogEntry.objects.create(event_date=time, command_type="Test", command_source="Test Case",
        username="user")
    response = self.client.get(reverse('swpgr:logs'))
    self.assertIsNotNone(response.context)
    self.assertQuerysetEqual(
        response.context['log_list'],
        ['<LogEntry: 1 Test user: user>']
    )`
Neoterize answered 25/11, 2014 at 20:26 Comment(1)
For me this error happened when I enabled memcache caching on my development instance. After changing the cache configuration back to the DummyCache the error did vanish.Appropriate
R
6

Quick workaround

There is another member dict of Context class (derived from SimpleTemplateResponse) which is called context_data. Using this instead of just context will give the expected context dict (django 1.9). But be aware, it's defined to be deprecated since django 1.8. So use it at your own risk. Unfortunately I didn't research a proper alternative until now.

Background

The existence of the context attribute of a response seems to be dependent on the type of template engine (templates) you are using. If you go for another engine than the one coming with django (default) you likely find the dict at the context_data attribute

References

Ratcliffe answered 18/4, 2016 at 20:16 Comment(2)
context_data itself is not deprecated. The deprecation was "context_data used to accept a Context". 2.1 no longer mentions any deprecationCu
In fact, the Django docs themselves recommend using context_data for other template enginesCu
C
4

I was having this issue and to fix it did the following in the setUp function:

from django.test.utils import setup_test_environment
setup_test_environment()
Christophe answered 19/6, 2015 at 13:25 Comment(0)
R
1

In our case the problem was not in setup_test_environment() (since pytest-django does call it for us automatically) but, as @tobltobs mentioned in his/her comment, it was caching.

Swapping

CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.locmem.LocMemCache',
        'LOCATION': 'test-cache',
    }
}

with

CACHES = {
    'default': {
        'BACKEND': 'django.core.cache.backends.dummy.DummyCache',
    }
}

solved all the problems for us.

Radiometeorograph answered 6/5, 2022 at 7:54 Comment(0)
T
0

setup_test_environment() installs a template renderer which will allow us to examine some additional attributes on responses such as response.context that otherwise wouldn’t be available. Note that this method does not set up a test database, so the following will be run against the existing database and the output may differ slightly depending on what questions you already created. You might get unexpected results if your TIME_ZONE in settings.py isn’t correct. If you don’t remember setting it earlier, check it before continuing.

ref:https://docs.djangoproject.com/en/5.0/intro/tutorial05/#the-django-test-client

Taphouse answered 15/3 at 1:4 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.