2009-11-06 101 views
28

我将一组模板标签添加到Django应用程序中,我不知道如何测试它们。我在模板中使用过它们,它们似乎在工作,但我正在寻找更正式的东西。主要逻辑在模型/模型管理器中完成并且已经过测试。该标签只检索数据,并将其存储在作为如何在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. 
""" 

所以我的问题是,你通常测试的模板标签,如果你这样做,你怎么办了一个环境变量这样?

回答

30

这是我的测试文件,凡在TestCase的self.render_template一个简单的辅助方法,一个短通道是:

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) 
+0

如何在项目范围之外测试这种情况,比如说,对于可重用应用程序?渲染包含“{%load custom_tag%}”的模板字符串似乎不起作用,至少没有额外的工作? – Santa 2010-04-23 19:40:37

+2

回答了我自己的问题:使用'register = template.Library(); template.libraries ['django.templatetags.mytest'] = register; register.tag(name ='custom_tag',compile_function = custom_tag)'。 – Santa 2010-04-23 20:15:10

+2

代码示例中的“self”是什么? '我的TestCase'对象没有'render_template'方法 – 2015-01-25 13:37:19

0

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

+0

这些标签只是呈现一个空字符串,而是改变的背景下,但我应该能够测试也是如此。 – 2009-11-06 15:31:16

0

当我测试我的模板标签时,我会让标签本身返回一个包含我正在处理的文本或字典的字符串...按照其他建议的顺序排列。

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

相反的:

return '' 

有它:

return str(my_data_that_I_am_testing) 

除非你是幸福的。

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)