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

sugi 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

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…

The Insidiousness of The Slow Solution

In software development, slow solutions can be worse than no progress at all. I'll even say its usually worse and if you find yourself making slow progress on a problem, consider stopping while you're a head.

Its easy to see why fast progress is better: either you solve the problem or you prove a proposed solution wrong and find a better one. Even a total standstill in pushing forward on a task or a bug or a request can force you to seek out new information or a second opinion.

Slow solutions, on the other hand, is kind of sneaky. Its insidious. Slow solution is related the Sunk Cost Fallacy, but maybe worse. Slow solutions have you constantly dripping more of your time, energy, and hope into a path that's still unproven, constantly digging a hole. Slow solutions are deceptive, because they still do offer real progress. It is hard to justify abandoning it or trying another route, because it is "working", technically.

We tend to romanticize the late night hacking…

Why I Switched From Git to Microsoft OneDrive

I made the unexpected move with a string of recent projects to drop Git to sync between my different computers in favor of OneDrive, the file sync offering from Microsoft. Its like Dropbox, but "enterprise."

Feeling a little ashamed at what I previously would have scoffed at should I hear of it from another developer, I felt a little write up of the why and the experience could be a good idea. Now, I should emphasize that I'm not dropping Git for all my projects, just specific kinds of projects. I've been making this change in habit for projects that are just for me, not shared with anyone else. It has been especially helpful in projects I work on sporadically. More on why a little later.

So, what drove me away from Git, exactly?

On the smallest projects, like game jam hacks, I just wanted to code. I didn't want to think about revisions and commit messages. I didn't need branching or merges. I didn't even need to rollback to another version, ever. I just …