Testing Jinja Templates

2013-07-06 21:43

If you use a powerful HTML templating engine – like Jinja – inevitably you will notice a slow creep of more and more complicated logic entering your templates. Contrary to what many may tell you, it’s not inherently bad. Views can be complex, and keeping that complexity contained within templates is often better than letting it sip into controller code.

But logic, if not trivial, requires testing. Exempting it by saying “That’s just a template!” doesn’t really cut it. It’s pretty crappy excuse, at least in Flask/Jinja, where you can easily import your template macros into Python code:

  1. {% macro hello_world() %}
  2.     Hello world!
  3. {% endmacro %}
  1. import flask
  2. hello_world = flask.get_template_attribute('hello.html', 'hello_world')
  3. print hello_world()

When writing a fully featured test suite, though, you would probably want some more leverage Importing those macros by hand in every test can get stale rather quickly and leave behind a lot of boilerplate code.

Fortunately, this is Python. We have world class tools to combat repetition and verbosity, second only to Lisp macros. There is no reason we couldn’t write tests for our Jinja templates in clean and concise manner:

  1. class Hello(JinjaTestCase):
  2.     __template_imports__ = {
  3.         'hello_world': 'hello.html',
  4.     }
  5.  
  6.     def test_hello_world(self):
  7.         result = self.hello_world()
  8.         self.assert_in("hello", result.lower())
  9.         self.assert_in("world", result.lower())

The JinjaTestCase base, implemented in this gist, provides evidence that a little __metaclass__ can go a long way :)

Be Sociable, Share!
Be Sociable, Share!
Tags: , , , ,
Author: Xion, posted under Programming »



Adding comments is disabled.

Comments are disabled.
 


© 2023 Karol Kuczmarski "Xion". Layout by Urszulka. Powered by WordPress with QuickLaTeX.com.