当异常链接时,如何使用 pytest 测试 python 3 中的异常

ben*_*756 7 pytest python-3.x

我有一些在 python 3 中使用自定义异常的代码。

就像是:

def get_my_custom_error():
    try:
        1.0/0.0
    except ZeroDivisionError as err:
        raise MyCustomError() from err
Run Code Online (Sandbox Code Playgroud)

在我的测试文件中我有以下内容:

with pytest.raises(MyCustomError):
    get_my_custom_error()
Run Code Online (Sandbox Code Playgroud)

我目前得到的输出如下

ZeroDivisionError
    
the above exception was the direct cause of the following error:

MyCustomError
Run Code Online (Sandbox Code Playgroud)

这会导致测试失败。

所以代码似乎可以工作,但 pytest 似乎没有检查最高级别的错误(这就是我希望它做的)。

Python 3.6.1 :: Anaconda 4.4.0 pytest 3.0.7

任何帮助都会很棒。

phd*_*phd 2

捕获并显式检查它:

try:
    get_my_custom_error()
except ZeroDivisionError as err:
    assert hasattr(err, '__cause__') and isinstance(err.__cause__, MyCustomError)
Run Code Online (Sandbox Code Playgroud)