Search code examples
pythonunit-testingtemplatesjinja2

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?


Solution

  • 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 = 'template_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.