测试自定义Django模板过滤器

时间:2010-12-21 03:47:59

标签: python django django-template-filters

我在project/app/templatetags下创建了自定义模板过滤器。

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

2 个答案:

答案 0 :(得分:15)

我是这样做的(从my 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's own test suite中的测试方法非常相似,但不依赖于django的复杂测试机制。

答案 1 :(得分:15)

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

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

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

相关问题