pytest使用可变内省来断言消息定制

时间:2017-06-13 12:39:53

标签: python rest testing pytest pytest-django

pytest documentation中,它表示您可以在assert失败时自定义输出消息。我想在测试REST API方法时自定义assert消息,它会返回无效的状态代码:

def test_api_call(self, client):
    response = client.get(reverse('api:my_api_call'))
    assert response.status_code == 200

所以我试着在conftest.py

中添加一段这样的代码
def pytest_assertrepr_compare(op, left, right):
    if isinstance(left, rest_framework.response.Response):
        return left.json()

但问题是leftresponse.status_code的实际值,所以它是int而不是Response。但是,默认输出消息会抛出类似:

  

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

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

我的观点是对被评估的变量有一种反省。那么,我如何以一种舒适的方式自定义断言错误消息,以获得上面发布的示例的类似输出?

1 个答案:

答案 0 :(得分:7)

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

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

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

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)

也结帐:https://wiki.python.org/moin/UsingAssertionsEffectively