测试自定义Django模板过滤器

18 投票
2 回答
2913 浏览
提问于 2025-04-16 08:49

我在project/app/templatetags目录下创建了一个自定义的模板过滤器。

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

2 个回答

17

测试一个模板过滤器最简单的方法就是把它当成普通的函数来测试。

@register.filter 这个装饰器不会影响到原来的函数,你可以直接导入这个过滤器,像使用普通函数一样使用它。这种方法对于测试过滤器的逻辑非常有用。

如果你想写更像集成测试那样的测试,就应该创建一个 Django 模板实例,然后检查输出是否正确(就像 Gabriel 的回答中展示的那样)。

16

这是我实现的方法(摘自我的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)

这个方法和Django自带的测试套件中的测试布局很相似,不过不需要依赖Django那套比较复杂的测试工具。

撰写回答