如何在 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.
"""
所以我的问题是您通常会测试您的模板标签吗?如果这样做,您会如何做?
I'm adding a set of template tags to a Django application and I'm not sure how to test them. I've used them in my templates and they seem to be working but I was looking for something more formal. The main logic is done in the models/model managers and has been tested. The tags simply retrieve data and store it in a context variable such as
{% 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.
"""
So my question is do you typically test your template tags and if you do how do you do it?
如果你对这篇内容有疑问,欢迎到本站社区发帖提问 参与讨论,获取更多帮助,或者扫码二维码加入 Web 技术交流群。
绑定邮箱获取回复消息
由于您还没有绑定你的真实邮箱,如果其他用户或者作者回复了您的评论,将不能在第一时间通知您!
发布评论
评论(5)
这是我的一个测试文件的一小段,其中 self.render_template 是 TestCase 中的一个简单辅助方法:
它非常基本,并且使用黑盒测试。它只是将一个字符串作为模板源,渲染它并检查输出是否等于预期的字符串。
render_template
方法非常简单:This is a short passage of one of my test files, where self.render_template a simple helper method in the TestCase is:
It is very basic and uses blackbox testing. It just takes a string as template source, renders it and checks if the output equals the expected string.
The
render_template
method is quite simplistic:你们让我走上了正轨。可以检查渲染后上下文是否已正确更改:
You guys got me on the right track. It's possible to check that the context was correctly changed after the render:
如何测试模板标签的一个很好的示例平面模板标签测试
A good example of how to test template tags test of flatpage templatetags
字符串可以呈现为模板,因此您可以使用模板标签作为字符串编写一个包含简单“模板”的测试,并确保它在给定特定上下文的情况下正确呈现。
Strings can be rendered as templates, so you could write a test that includes a simple 'template' using your templatetag as a string and just make sure it renders correctly given a certain context.
当我测试我的模板标签时,我会让标签本身返回一个包含我正在使用的文本或字典的字符串......有点类似于其他建议。
由于标签可以修改上下文和/或返回要渲染的字符串——我发现仅查看渲染的字符串是最快的。
而不是:
拥有它:
直到你快乐为止。
When I was testing my template tags, I would have the tag, itself, return a string containing the text or dict I was working with ... sort of along the lines of the other suggestion.
Since tags can modify the context and/or return a string to be rendered -- I found it was fastest just to view the rendered string.
Instead of:
Have it:
Until you are happy.