如何断言django在pytest中使用特定模板

How to assert django uses certain template in pytest

unittest 样式中,我可以通过调用 assertTemplateUsed 来测试页面是否使用特定模板。这很有用,例如,当 Django 通过模板插入值时,我不能只测试字符串是否相等。

我应该如何在pytest中编写等效语句?

我一直在寻找 pytest-django 但不知道如何去做。

如果我理解清楚的话,你想测试一下 Django 是否正确渲染了你传递给模板的数据。如果是这种情况,那么概念就错了,你应该先测试视图中收集的数据,然后确保它调用了模板。测试模板是否包含正确的数据将测试 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 中可用。参见 举个例子。

要断言给定模板是否用于呈现特定视图,您可以(甚至应该)使用 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 甚至在 documentation.

中使用这个确切的断言作为示例