测试自定义Django模板过滤器

Bel*_*dez 17 python django django-template-filters

我有一个我创建的自定义模板过滤器project/app/templatetags.

我想为我刚发现的一些错误添加一些回归测试.我该怎么做呢?

Mik*_*bov 16

测试模板过滤器的最简单方法是将其作为常规函数进行测试.

@register.filter装饰器不会损害底层函数,你可以导入过滤器并使用就像它没有装饰一样.此方法对于测试过滤器逻辑很有用.

如果你想编写更多集成式测试,那么你应该创建一个django Template实例并检查输出是否正确(如Gabriel的答案所示).


Gab*_*ant 15

这是我的方式(从我的django-multiforloop中提取):

from django.test import TestCase
from django.template import Context, Template

class TagTests(TestCase):
    def tag_test(self, template, context, output):
        t = Template('{% load multifor %}'+template)
        c = Context(context)
        self.assertEqual(t.render(c), output)
    def test_for_tag_multi(self):
        template = "{% for x in x_list; y in y_list %}{{ x }}:{{ y }}/{% endfor %}"
        context = {"x_list": ('one', 1, 'carrot'), "y_list": ('two', 2, 'orange')}
        output = u"one:two/1:2/carrot:orange/"
        self.tag_test(template, context, output)
Run Code Online (Sandbox Code Playgroud)

这与Django自己的测试套件中的测试方式非常相似,但不依赖于django的复杂测试机制.