我有一些在 python 3 中使用自定义异常的代码。
就像是:
def get_my_custom_error()
try:
1.0/0.0
except ZeroDivisionError as err:
raise MyCustomError() from err
在我的测试文件中,我有以下内容:
with pytest.raises(MyCustomError)
get_my_custom_error()
我目前得到一个输出
ZeroDivisionError
the above exception was the direct cause of the following error:
MyCustomError
这会导致测试失败。
所以代码似乎正在运行,但 pytest 似乎没有检查最高级别的错误(这是我希望它做的)。
Python 3.6.1:: python 4.4.0
pytest 3.0.7
任何帮助都会很棒。
最佳答案
捕获并明确检查它:
try:
get_my_custom_error()
except ZeroDivisionError as err:
assert hasattr(err, '__cause__') and isinstance(err.__cause__, MyCustomError)
关于python-3.x - 当异常被链接时,如何使用 pytest 测试 python 3 中的异常,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/48675053/