8

I've been looking for a way to unit test a jinja2 template. I already did some research, but the only thing I was able to find was related to how to test the variables passed to the template: how to unittest the template variables passed to jinja2 template from webapp2 request handler

In other words, I would like to test if the logic used within the template is generating an expected output.

I thought I could create a "golden" file so I could compare the files being generated with the golden file, however that would require too many "golden" files due to the number of possibilities.

Any other ideas?

Felipe Santiago
  • 143
  • 1
  • 8

1 Answers1

10

Why not simply render the template to string in your test, and then check if rendered template is correct?

Something simillar to this:

import jinja2

# assume it is an unittest function
context = {  # your variables to pass to template
    'test_var': 'test_value'
}
path = 'path/to/template/dir'
filename = 'tempalte_to_test.tpl'

rendered = jinja2.Environment(
    loader=jinja2.FileSystemLoader(path)
).get_template(filename).render(context)

# `rendered` is now a string with rendered template
# do some asserts on `rendered` string 
# i.e.
assert 'test_value' in rendered

I am not sure how to calculate coverage though.

030
  • 10,842
  • 12
  • 78
  • 123
Pax0r
  • 2,324
  • 2
  • 31
  • 49
  • 2
    Thank you for your answer. I was expecting something more specific to test the logic inside the template. I mean, the value I will assert can be generated by different cases in the template. Checking only the output does not guarantee that the flow the template did is what I was expecting. But anyway, I will accept your answer since I will use it anyway. Thanks again! – Felipe Santiago Feb 10 '17 at 12:15