开发者

How can I access response.context when testing a Jinja2 powered Django view

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 unsubscripta开发者_如何学编程ble

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.


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') 


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.


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

from jinja2 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.


Jinja sets context_data variable, not context:

response = client.get('/')
print response.context_data
0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜