如何在Django中测试自定义模板标签?

时间:2009-11-06 14:11:26

标签: django django-templates django-testing

我正在为Django应用程序添加一组模板标签,我不知道如何测试它们。我已经在我的模板中使用它们,它们似乎正在工作但我正在寻找更正式的东西。主要逻辑在模型/模型管理器中完成,并已经过测试。标签只是检索数据并将其存储在上下文变量中,例如

{% views_for_object widget as views %}
"""
Retrieves the number of views and stores them in a context variable.
"""
# or
{% most_viewed_for_model main.model_name as viewed_models %}
"""
Retrieves the ViewTrackers for the most viewed instances of the given model.
"""

所以我的问题是你通常会测试你的模板标签,如果你这样做,你会怎么做?

5 个答案:

答案 0 :(得分:33)

这是我的一个测试文件的简短段落,其中self.render_template是TestCase中的一个简单帮助方法:

    rendered = self.render_template(
        '{% load templatequery %}'
        '{% displayquery django_templatequery.KeyValue all() with "list.html" %}'
    )
    self.assertEqual(rendered,"foo=0\nbar=50\nspam=100\negg=200\n")

    self.assertRaises(
        template.TemplateSyntaxError,
        self.render_template,
        '{% load templatequery %}'
        '{% displayquery django_templatequery.KeyValue all() notwith "list.html" %}'
    )

这是非常基本的,并使用黑盒测试。它只需要一个字符串作为模板源,渲染它并检查输出是否等于预期的字符串。

render_template方法非常简单:

from django.template import Context, Template

class MyTest(TestCase):
    def render_template(self, string, context=None):
        context = context or {}
        context = Context(context)
        return Template(string).render(context)

答案 1 :(得分:17)

你们让我走上正轨。可以在渲染后检查上下文是否已正确更改:

class TemplateTagsTestCase(unittest.TestCase):        
    def setUp(self):    
        self.obj = TestObject.objects.create(title='Obj a')

    def testViewsForOjbect(self):
        ViewTracker.add_view_for(self.obj)
        t = Template('{% load my_tags %}{% views_for_object obj as views %}')
        c = Context({"obj": self.obj})
        t.render(c)
        self.assertEqual(c['views'], 1)

答案 2 :(得分:9)

如何测试模板标签的一个很好的示例test of flatpage templatetags

答案 3 :(得分:0)

字符串可以呈现为模板,因此您可以使用templatetag作为字符串编写包含简单“模板”的测试,并确保在给定特定上下文的情况下正确呈现。

答案 4 :(得分:0)

当我测试我的模板标签时,我会让标签本身返回一个字符串,其中包含我正在使用的文本或字典......有点像其他建议的行。

由于标签可以修改上下文和/或返回要呈现的字符串 - 我发现查看呈现的字符串最快。

而不是:

return ''

拥有它:

return str(my_data_that_I_am_testing)

直到你快乐。