2009-11-06 85 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) 
相關問題