Skip to main content

How To Test Django Template Tags - Part 2

In Part 1 I wrote about my method of testing the actual tag function for a custom Django template tag. I said I would follow it with a Part 2 on testing the rendering of the resulting Node. This is that follow up post for any of you who were waiting for it.

Testing the rendering poses some more problems than our little tag function. Rendering is going to do a bit more, including loading the templates, resolving any variables in question, doing any processing on those results (like looking up a record from the database based on the variable value), and finally populating a new context to render the tag's template with. How do we test all of that, without actually doing any of that? This is the goal we're reaching here, for unittests. We want each test to be so specific that we test what something will do, without actually relying on those things it does. We aren't testing any of those things, just that our render() method does them.

What can we mock easily? get_template() is an easy call, so we can patch that to return a mock inside of our test. Our render() needs to load the template, do its processing, and then render the template. We can assert the rendering was done properly afterwards, thanks to the mock template.

So far...

@patch('django.template.loader.get_template')
def test_link_to_email_render(self, get_template):
    node = LinkToEmail(obfuscate=False, email=Mock())
    node.email.resolve.return_value = 'bob@company.com'

    ...

But now we get to our problem. We have to call our render method to test it, and its expecting a Context to be passed. Normally, we want to mock things we aren't directly testing, but it doesn't always present itself as easy.

As of mock 0.4.0 the Mock class does not support subscripting, and contexts are dict-like objects. My first inclination? Just pass a dictionary. Unfortunately, the context also has an important attribute, autoescape, which needs to be inherited by the context we use inside the render() method, and dictionaries don't have this.

class ContextMock(dict):
    autoescape = object()

@patch('django.template.loader.get_template')
def test_link_to_email_render(self, get_template):
    node = LinkToEmail(obfuscate=False, email=Mock())
    node.email.resolve.return_value = 'bob@company.com'

    context = ContextMock({})

We're making progress and we're at the point where we need to actually call the render() method. Now, after its basic processing its going to create the Context in which to render the template. For the sake of limiting what "real things" we invoke during our test, this might be something we watch to mock.

class ContextMock(dict):
    autoescape = object()

@patch('django.template.loader.get_template')
@patch('django.template.Context')
def test_link_to_email_render(self, get_template, Context):
    template = get_template.return_value
    node = LinkToEmail(obfuscate=False, email=Mock())
    node.email.resolve.return_value = 'bob@company.com'

    context = ContextMock({
        'email': Mock(),
        'obfuscate': Mock(),
    })

    node.render(context)
    template.render.assert_called_with(Context.return_value)

    args, kwargs = Context.call_args
    assert kwargs['autoescape'] is context.autoescape
    assert args[0]['email'] is context['email']
    assert args[0]['obfuscate'] is context['obfuscate']

The testing itself is pretty basic. We want to make sure the mocked context is given go the template to use in rendering and that the context properly inherits the autoescape property. We also test that the context matches the data we're giving. In the end, this was pretty easy. I actually cleaned up the code I based this on in response to writing the article and discovering cleaner ways to do it.

We need to put some thought into our tests. Often we are tempted to take shortcuts. We might write a unittest which simply calls the function, maybe checks the result, and we call it a day. We need to test different conditions under which a function is called. We need to ensure we are testing reliably, and using things like mocks help us ensure that when our test calls the function, we know what the world looks like to that function. Mocks are our rose colored glasses.

This two parter on testing Django template tags is hopefully the start of more similar writings on specific testing targets. Many of them will likely focus on Django, for two reasons. Firstly, I think there is a lack of good testing practices in the Django world, where I see. Secondly, I'm in the process of adding tests to a not-small codebase and these posts both document my journey and guide me.

Comments

phxx said…
Hi,
thanks for this article.

I really would like to know which mock library you used for your testing.

Thanks :-)
phxx
Anonymous said…
@phxx http://www.voidspace.org.uk/python/mock/
phxx said…
Nice coincident ... I used this afternoon a mock library the first time :) and I used "mock". Thanks anyway!

Popular posts from this blog

Respect and Code Reviews

Code Reviews in a development team only function best, or possible at all, when everyone approaches them with respect. That’s something I’ve usually taken for granted because I’ve had the opportunity to work with amazing developers who shine not just in their technical skills but in their interpersonal skills on a team. That isn’t always the case, so I’m going to put into words something that often exists just in assumptions.
You have to respect your code. This is first only because the nature and intent of code reviews are to safeguard the quality of your code, so even having code reviews demonstrates a baseline of respect for that code. But, maybe not everyone on the team has the same level of respect or entered a team with existing review traditions that they aren’t acquainted with.
There can be culture shock when you enter a team that’s really heavy on code reviews, but also if you enter a team or interact with a colleague who doesn’t share that level of respect for the process or…

On Pruning Your Passions

We live in a hobby-rich world. There is no shortage of pastimes to grow a passion for. There is a shortage of one thing: time to indulge those passions. If you're someone who pours your heart into that one thing that makes your life worthwhile, that's a great deal. But, what if you've got no shortage of interests that draw your attention and you realize you will never have the time for all of them?

If I look at all the things I'd love to do with my life as a rose bush I'm tending, I realize that careful pruning is essential for the best outcome. This is a hard lesson to learn, because it can mean cutting beautiful flowers and watching the petals fall to the ground to wither. It has to be done.

I have a full time job that takes a lot of my mental energy. I have a wife and a son and family time is very important in my house. I try to read more, and I want to keep up with new developments in my career, and I'm trying to make time for simple, intentional relaxing t…

CARDIAC: The Cardboard Computer

I am just so excited about this.


CARDIAC. The Cardboard Computer. How cool is that? This piece of history is amazing and better than that: it is extremely accessible. This fantastic design was built in 1969 by David Hagelbarger at Bell Labs to explain what computers were to those who would otherwise have no exposure to them. Miraculously, the CARDIAC (CARDboard Interactive Aid to Computation) was able to actually function as a slow and rudimentary computer. 
One of the most fascinating aspects of this gem is that at the time of its publication the scope it was able to demonstrate was actually useful in explaining what a computer was. Could you imagine trying to explain computers today with anything close to the CARDIAC?

It had 100 memory locations and only ten instructions. The memory held signed 3-digit numbers (-999 through 999) and instructions could be encoded such that the first digit was the instruction and the second two digits were the address of memory to operate on. The only re…