【问题标题】:How to assert django uses certain template in pytest如何断言 django 在 pytest 中使用某些模板
【发布时间】:2017-08-28 20:02:24
【问题描述】:

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

pytest中的等价语句应该怎么写?

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

【问题讨论】:

  • 我不明白你想测试传递给模板的数据是否正确呈现的问题?
  • @Augustin 不,我想测试当我得到一个页面时,它使用的是我希望它使用的模板文件。
  • 如果你得到“页面”,那么你得到的是模板,如果没有,你得到一个“页面”是什么意思?你能提供一些代码让我帮你吗?
  • assertTemplateUsed_assert_template_used 的代码显示reponse 中有一个属性.templates。所以你需要像assert response.templates and ('mytemplate' in [t.name for t in response.templates if t.name is not None])这样的东西。

标签: python django pytest pytest-django


【解决方案1】:

正如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's answer 举个例子。

【讨论】:

  • 这是一种变通方法,而不是问题的实际解决方案。
  • 你为什么这么说?这就是 Django 在assertTemplateUsed() 中所做的。将它包装在一个函数中,就是这样。您还希望它不是“解决方法”吗?
  • 也许“解决方法”是夸大其词,但是pytest_django 提供了一个专门的断言。
【解决方案2】:

要断言给定模板是否用于呈现特定视图,您可以(甚至应该)使用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 中使用这个确切的断言作为示例。

【讨论】:

    【解决方案3】:

    如果我理解清楚,您想测试 Django 是否正确呈现您传递给模板的数据。如果是这种情况,那么概念是错误的,您应该先测试在您的视图中收集的数据,然后确保它调用模板。测试模板是否包含正确的数据就是测试 Django 框架本身。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2021-12-22
      • 1970-01-01
      • 2021-10-14
      • 2013-08-09
      • 2019-11-02
      • 2021-12-11
      相关资源
      最近更新 更多