pytest使用可变的内省声明消息自定义

Mar*_*urí 7 python testing rest pytest pytest-django

pytest文档中,它说您可以自定义assert失败时的输出消息。我想assert在测试返回错误状态代码的REST API方法时自定义消息:

def test_api_call(self, client):
    response = client.get(reverse('api:my_api_call'))
    assert response.status_code == 200
Run Code Online (Sandbox Code Playgroud)

所以我试图在其中放入一段代码 conftest.py

def pytest_assertrepr_compare(op, left, right):
    if isinstance(left, rest_framework.response.Response):
        return left.json()
Run Code Online (Sandbox Code Playgroud)

但是问题是left的实际值,response.status_code因此它是int而不是Response。但是,默认的输出消息抛出类似以下内容的消息:

E断言400 == 201 E +其中400 = .status_code

说错误400来自status_code对象的属性Response

我的观点是,对要评估的变量有一种自省。因此,如何以一种舒适的方式自定义断言错误消息,以获得与上述示例类似的输出?

Dmi*_*rev 9

您可以使用Python内置功能显示自定义异常消息:

assert response.status_code == 200, "My custom msg: actual status code {}".format(response.status_code)
Run Code Online (Sandbox Code Playgroud)

或者,您可以构建一个帮助程序断言函数:

def assert_status(response, status=200):  # you can assert other status codes too
    assert response.status_code == status, \
        "Expected {} actual status {}. Response text {}".format(status, response.status_code, response.text)

# here is how you'd use it
def test_api_call(self, client):
    response = client.get(reverse('api:my_api_call'))
    assert_status(response)
Run Code Online (Sandbox Code Playgroud)

还要结帐:https : //wiki.python.org/moin/UsingAssertionsEffectlyly

  • 上面回复中的第一个例子正是我正在寻找的! (3认同)