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

标签 python-3.x pytest

我有一些在 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/

相关文章:

python - 如何根据某些条件检查字符串中的多个单词?

python - 在 PyTorch 中有条件地应用张量运算

python - 如何从手部图像中获取特征向量

python - 错误 : etheruem-serpent; version conflict

python - 如何在生成的列表上使用 pytest 测试

python - Pytest 不收集静态方法

Python ssl 默认上下文抛出错误的文件描述符错误

python - 如何使对象正确可散列?

python - 如何将 stdlib 日志记录与 py.test 结合起来

python - 使用 pyspark dataframe : how to mock up . repartition() 链式函数测试代码时?