Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Django: Test client's context is empty from the shell

I cannot access the context attribute of an HttpResponse object from ipython. But the unit test accesses context.

Here is the unit test. The test run passes properly:

from django.test import Client, TestCase
from django.core import mail

class ClientTest(TestCase):
    def test_get_view(self):
        data = {'var': u'\xf2'}
        response = self.client.get('/test04/', data)

        # Check some response details
        self.assertContains(response, 'This is a test')
        self.assertEqual(response.context['var'], u'\xf2')

Here is the code that I used in the shell:

In [10]: from django.test import Client

In [11]: c = Client()

In [12]: r = c.get('/test04/', data)

In [13]: r.context

In [14]: type(r.context)
Out[14]: <type 'NoneType'>

response.context is none in the shell whereas response.context exists in the unit test.

Why does HttpResponse behave inconsistently between the shell and unit test?

like image 434
Mert Nuhoglu Avatar asked Dec 19 '09 11:12

Mert Nuhoglu


1 Answers

You can see in the Django test code where it monkeypatches in special instrumentation to make template rendering send a signal, which the test client listens to so it can annotate the response object with the rendered templates and their contexts.

For this signal to be attached, you'd have to either call the django.test.utils.setup_test_environment() function in your shell session (which has other side effects), or duplicate just the lines that monkeypatch template rendering. Not too hard, but I agree it'd be nice if this particular debugging aspect could be refactored out to make it easier to use outside of tests. Personally I wouldn't mind if this information was always collected when DEBUG is True, not just under test.

like image 189
Carl Meyer Avatar answered Oct 10 '22 05:10

Carl Meyer