Skip to main content

How To Test Django Template Tags - Part 1

I'm involved in a project that has gone for a long time without tests and everyone involved knows tests are rilly rilly important. There is a point where acknowledged best practices simply meets the reality of the development mind and it doesn't always work out like you'd hope. We know tests are important, but we need to resolve this ticket right freaking now. You understand. The point was reached that this just couldn't continue and the costs of fixing the same bugs over and over were way too obvious to ignore. Tests are now popping up for things we're fixing and new things we're writing. As it happens, I came across my first real need to create a custom template tag. Of course, I wanted to test it. So how do you test something that is so entrenched in the Django processing pipeline as a template tag?

Incidentally, I'm just going to assume you either know all about testing and Django template tags or you can follow along just fine.

Testing breaks down into individual functions and we try to keep them individually small, to be easier to test and less likely to be broken. The simpler something is, the more likely you actually understand it. So our custom template is really two functions: the tag parser and the renderer. The first is the function we actually tell Django to call when it needs to parse our tag. The second is the render() method of a Node subclass.

Here is an example of a kind of tag we might be working with. It creates a link to an email address, and optionally can obfuscate it instead. For example, the obfuscate flag might come from whether or not the page is being viewed by an anonymous user or a friend.

{% link_to_email "bob@company.com" do_obfuscate %}

The parsing first, which I do in LinkEmail.tag(), a classmethod.

...
@classmethod
def tag(cls, parser, token):
    parts = token.split_contents()
    email = template.Variable(parts[1])
    try:
        obfuscate = parts[2]
    except IndexError:
        obfuscate = False
    return cls(email, obfuscate)

So we have two conditions that can happen here. Either the tag is used with just an email and we default to not obfuscating, or we are told to obfuscate or not by the optional second tag parameter. To simplify this post, the second parameter is simply given or not. If its given, we obfuscate, we don't resolve it as a variable like the email.

So we need to test this function getting called when the parser gives us the different possible sets of tokens we're dealing with. Mocking comes in handy.

@patch('django.template.Variable')
def test_tag(self, Variable):
    parser = Mock()
    token = Mock(methods=['split_contents'])

    token.split_contents.return_value = ('link_to_email', 'bob@company.com')

Now we actually call the tag method to test it.

    node = LinkToEmail.tag(parser, token)

    self.assertEqual(node.email, Variable.return_value)
    assert not node.obfuscate

This is the axiom of good testing: we're only testing one thing at a time. We don't actually invoke any template processing to test our one little tag. We don't even let the function we're testing do anything else that might break, except for a pretty innocent creation of an instance of our node. That's OK, because it can't break:

def __init__(self, email, obfuscate):
    self.email = email
    self.obfuscate = obfuscate

The only things it tries to do outside of the function we're testing is split_contents() to parse the parameters and create a template.Variable instance, but we mock both. We control what split_contents() returns, instead of relying on actually parsing a template. We replace template.Variable with a Mock instance, so it doesn't do anything other than record that it was called and let us test some things about how it was called and what the tag() method did with the result.

We'll also want a second test where split_contents() returns three items and we verify the obfuscate parameter was handled properly.

In an effort to remember that I don't usually read any blog post longer than this, I'm not making this longer. So, I'll make it two parts. Tomorrow, I'll write about the larger issue of testing the template renderer, while trying to keep our test as clean as possible. It is a little trickier.

Read Part 2 on testing tag rendering.

Comments

Anonymous said…
It is really helpful. But can you explain with another example for templatetag using node and parser...I need more clarification.
stefodestructo said…
I think I found a grammar mistake.
"We tests are important"

I found this post very informative. I'm pointing out the typo to help improve the post, not to nag.

Thanks
Calvin Spealman said…
@stefodestructo

Thanks for pointing that out! It has been corrected.

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

Announcing Feet, a Python Runner

I've been working on a problem that's bugged me for about as long as I've used Python and I want to announce my stab at a solution, finally! I've been working on the problem of "How do i get this little thing I made to my friend so they can try it out?" Python is great. Python is especially a great language to get started in, when you don't know a lot about software development, and probably don't even know a lot about computers in general. Yes, Python has a lot of options for tackling some of these distribution problems for games and apps. Py2EXE was an early option, PyInstaller is very popular now, and PyOxide is an interesting recent entry. These can be great options, but they didn't fit the kind of use case and experience that made sense to me. I'd never really been about to put my finger on it, until earlier this year: Python needs LÖVE . LÖVE, also known as "Love 2D", is a game engine that makes it super easy to build ...