开发者

Testing a custom Django template filter

I have a custom template filter I created under project/app/templatetags.

I want to add some regression tests for some bugs I just found. How would I go开发者_高级运维 about doing so?


The easiest way to test a template filter is to test it as a regular function.

@register.filter decorator doesn't harm the underlying function, you can import the filter and use just it like if it is not decorated. This approach is useful for testing filter logic.

If you want to write more integration-style test then you should create a django Template instance and check if the output is correct (as shown in Gabriel's answer).


Here's how I do it (extracted from 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)

This is fairly similar to how tests are laid out in Django's own test suite, but without relying on django's somewhat complicated testing machinery.

0

上一篇:

下一篇:

精彩评论

暂无评论...
验证码 换一张
取 消

最新问答

问答排行榜