Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/298.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python pytest断言消息自定义,带有变量内省_Python_Rest_Testing_Pytest_Pytest Django - Fatal编程技术网

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
,并且不需要编写更多的代码。啊,对不起,没有理解您的问题。上述回答中的第一个示例正是我要找的!