本文介绍了如何对jinja2模板逻辑进行单元测试?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我一直在寻找对jinja2模板进行单元测试的方法.我已经做了一些研究,但是我唯一能找到的与如何测试传递给模板的变量有关:如何对模板变量进行单元测试从webapp2请求处理程序传递到jinja2模板

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.

还有其他想法吗?

推荐答案

为什么不简单地在测试中将模板呈现为字符串,然后检查呈现的模板是否正确?

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

与此类似:

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.

这篇关于如何对jinja2模板逻辑进行单元测试?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!

09-02 02:28