我正在写一个单元测试,我想断言我得到的错误:
<ValidationError: "'a list' is not of type 'array'">
= too
assert ValidationError(message="'a list' is not of type 'array'")
我使用一个简单的断言:
assert actual == expected
当我运行pytest
时,我得到以下错误:
assert <ValidationError: "'a list' is not of type 'array'"> == <ValidationError: "'a list' is not of type 'array'">
验证错误来自jsonschema
from jsonschema import ValidationError
即使它们是相同的,断言仍然失败。有人知道为什么吗?
这个异常似乎没有定义__eq__
方法,所以它正在使用id进行比较-并且因为它们是2个不同的对象,它们具有不同的id。就像这段代码会抛出一个错误,因为Python并不知道两个不同的typeerror应该如何比较。
assert TypeError('a') == TypeError('a')
如果您检查pytest文档,建议处理预期异常的方法如下:
def test_zero_division():
with pytest.raises(ZeroDivisionError):
1 / 0
通常我会使用pytest.raises
def test_validation_error():
with pytest.raises(ValidationError, match="'a list' is not of type 'array'"):
# whatever you are doing to raise the error
assert ValidationError(message="'a list' is not of type 'array'")