Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How can I unit test the jinja2 template logic?

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?

like image 800
Felipe Santiago Avatar asked Feb 07 '17 12:02

Felipe Santiago


People also ask

How do I run a Unittest test?

If you're using the PyCharm IDE, you can run unittest or pytest by following these steps: In the Project tool window, select the tests directory. On the context menu, choose the run command for unittest . For example, choose Run 'Unittests in my Tests…'.


1 Answers

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.

like image 96
Pax0r Avatar answered Oct 19 '22 09:10

Pax0r