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
thanks for this article.
I really would like to know which mock library you used for your testing.
Thanks :-)
phxx