Mar*_*vin 34 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.
"""
Run Code Online (Sandbox Code Playgroud)
所以我的问题是你通常测试你的模板标签,如果你这样做你怎么做?
Gre*_*ger 35
这是我的一个测试文件的简短段落,其中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" %}'
)
Run Code Online (Sandbox Code Playgroud)
它非常基础,并使用黑盒测试.它只需要一个字符串作为模板源,渲染它并检查输出是否等于预期的字符串.
该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)
Run Code Online (Sandbox Code Playgroud)
Mar*_*vin 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)
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
9942 次 |
| 最近记录: |