如何断言django在pytest中使用某些模板

Hat*_*sut 6 python django pytest pytest-django

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

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

我一直在寻找pytest-django,但不知道该怎么做.

jnn*_*nns 8

正如phd在注释中所述,使用以下命令断言模板文件实际上在视图中使用:

response = client.get(article.get_absolute_url())
assert 'article_detail.html' in (t.name for t in response.templates)
Run Code Online (Sandbox Code Playgroud)


Sta*_*ute 6

要断言给定模板是否用于呈现特定视图,您可以(甚至应该)使用以下提供的帮助程序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')
Run Code Online (Sandbox Code Playgroud)

pytest-django甚至在文档中使用这个确切的断言作为示例。