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

Unknown 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

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 operat...

Statement Functions

At a small suggestion in #python, I wrote up a simple module that allows the use of many python statements in places requiring statements. This post serves as the announcement and documentation. You can find the release here . The pattern is the statement's keyword appended with a single underscore, so the first, of course, is print_. The example writes 'some+text' to an IOString for a URL query string. This mostly follows what it seems the print function will be in py3k. print_("some", "text", outfile=query_iostring, sep="+", end="") An obvious second choice was to wrap if statements. They take a condition value, and expect a truth value or callback an an optional else value or callback. Values and callbacks are named if_true, cb_true, if_false, and cb_false. if_(raw_input("Continue?")=="Y", cb_true=play_game, cb_false=quit) Of course, often your else might be an error case, so raising an exception could be useful...

How To Teach Software Development

How To Teach Software Development Introduction Developers Quality Control Motivation Execution Businesses Students Schools Education is broken. Education about software development is even more broken. It is a sad observation of the industry from my eyes. I come to see good developers from what should be great educations as survivors, more than anything. Do they get a headstart from their education or do they overcome it? This is the first part in a series on software education. I want to open a discussion here. Please comment if you have thoughts. Blog about it, yourself. Write about how you disagree with me. Write more if you don't. We have a troubled industry. We care enough to do something about it. We hark on the bad developers the way people used to point at freak shows, but we only hurt ourselves but not improving the situation. We have to deal with their bad code. We are the twenty percent and we can't talk to the eighty percent, by definition, so we need to impro...