views:

102

answers:

3

When I use the Django test.client and I do something like:

class MyTestCase(TestCase):
    def test_this(self):
        c = self.client
        response = c.get('/')
        assert False, response.context['name']

I get an error:

assert False, response.context['name']
TypeError: 'NoneType' object is unsubscriptable

My only guess is something with using Jinja2 is preventing the context from showing up when I test.

Note this test is intentionally rigged to fail.

+1  A: 

I've been meaning to readup on TestCase. After perusing the docs it looks you might have an error. Assertions are methods of the TestCase class.

class MyTestCase(TestCase):
  def test_this(self):
    response=self.client.get('/')
    self.assertEquals(response.context['name'],'Jim')
czarchaic
Thanks for the typo catch, I meant assert False, response.context['name'] I want the test to fail, because I want to see what's in response.context['name']
dd
I would think this test would fail unless 'Jim' is `response.context['name']`
czarchaic
+1  A: 

Django's monkey patches the Template class overriding the render method to be able to send the template_rendered signal and populate response.context.

If you dig the code you will be able to do this for Jinja2's Template class.

Rho
A: 

I've done what @Rho has suggested this way (in the beginning of the page load tests file)

from jinja2.template import Template as Jinja2Template
from django.test import signals

#note - this code can be run only once
ORIGINAL_JINJA2_RENDERER = Jinja2Template.render
def instrumented_render(template_object, *args, **kwargs):
    context = dict(*args, **kwargs)
    signals.template_rendered.send(
                            sender=template_object,
                            template=template_object,
                            context=context
                        )
    return ORIGINAL_JINJA2_RENDERER(template_object, *args, **kwargs)
Jinja2Template.render = instrumented_render

Then you can pick out the response context and template name (however response.template is not a list in this case) and instead of response.template[0].name you'll need to use response.template.name.

Evgeny