numpy.testing.assert_raises

numpy.testing.assert_raises(exception_class, callable, *args, **kwargs)[source]

失败,除非在使用参数args和关键字参数kwargs调用时,callable抛出类exception_class的异常。如果抛出不同类型的异常,它不会被捕获,并且测试用例将被视为已经遭遇错误,正如异常意外。

或者,assert_raises可用作上下文管理器:

>>> from numpy.testing import assert_raises
>>> with assert_raises(ZeroDivisionError):
...   1 / 0

相当于

>>> def div(x, y):
...    return x / y
>>> assert_raises(ZeroDivisionError, div, 1, 0)