在unittest
样式中,我可以通过调用assertTemplateUsed
. 这很有用,例如,当 Django 通过模板插入值时,我不能只测试字符串是否相等。
我应该如何在pytest中编写等效语句?
我一直在寻找pytest-django但不知道该怎么做。
在unittest
样式中,我可以通过调用assertTemplateUsed
. 这很有用,例如,当 Django 通过模板插入值时,我不能只测试字符串是否相等。
我应该如何在pytest中编写等效语句?
我一直在寻找pytest-django但不知道该怎么做。
正如评论中的phd所述,使用以下内容断言模板文件实际用于视图中:
response = client.get(article.get_absolute_url())
assert 'article_detail.html' in (t.name for t in response.templates)
更新:由于 v3.8.0 (2020-01-14) pytest-django 使 Django 的 TestCase 中的所有断言都可以在pytest_django.asserts
.
有关示例,请参见Stan Redoute 的答案。
要断言给定模板是否用于呈现特定视图,您可以(甚至应该)使用由以下提供的帮助器pytest-django
:
import pytest
from pytest_django.asserts import assertTemplateUsed
...
def test_should_use_correct_template_to_render_a_view(client):
response = client.get('.../your-url/')
assertTemplateUsed(response, 'template_name.html')
pytest-django
甚至在文档中使用这个确切的断言作为示例。
如果我理解清楚,您想测试 Django 是否正确呈现您传递给模板的数据。如果是这种情况,那么概念是错误的,您应该先测试在您的视图中收集的数据,然后确保它调用模板。测试模板是否包含正确的数据将测试 Django 框架本身。