Python pytest断言消息自定义,带有变量内省
在中,它表示可以在Python pytest断言消息自定义,带有变量内省,python,rest,testing,pytest,pytest-django,Python,Rest,Testing,Pytest,Pytest Django,在中,它表示可以在断言失败时自定义输出消息。我想自定义assert消息在测试REST API方法时,它返回一个无效的状态代码: 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, r
断言失败时自定义输出消息。我想自定义assert
消息在测试REST API方法时,它返回一个无效的状态代码:
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()
但是问题是left
是响应的实际值。status\u code
因此它是int
而不是响应。但是,默认的输出消息会抛出如下内容:
E断言400==201 E+其中400=.status\u代码
表示错误400来自对象响应的属性status\u code
我的观点是,对被评估的变量有一种内省。那么,如何以一种舒适的方式自定义assert错误消息,以获得与上述示例类似的输出?您可以使用Python内置功能来显示自定义异常消息:
assert response.status_code == 200, f"My custom msg: actual status code {response.status_code}"
或者,您可以构建助手断言函数:
def assert_status(response, status=200): # you can assert other status codes too
assert response.status_code == status, \
f"Expected {status}. Actual status {response.status_code}. Response text {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)
同时结帐:谢谢Dmitry。我知道你提出的两种解决方案,并确信两者都能奏效。然而,我一直在寻找一个奇特的解决方案,您仍然可以使用assert
,并且不需要编写更多的代码。啊,对不起,没有理解您的问题。上述回答中的第一个示例正是我要找的!