pytest:检查是否引发了特定的异常(如果引发了父异常,则失败)

时间:2020-10-18 12:09:56

标签: python exception pytest

thread开始,用pytest似乎无法检查是否引发了特定异常:如果提到父异常,则测试也将通过。

我做了一个小例子来说明,所有三个测试都通过了。我希望只有一个人能通过。

您能确认吗?我应该检查excinfo吗?

(为什么会出现这个问题?在某些情况下,我正在测试的函数可以返回真正的TypeError异常,我希望我的测试能够准确地检测何时引发一个或另一个) / p>

谢谢


import pytest

class CustomExc(TypeError):
    pass

def a_random_function():
    raise CustomExc

def test_random_function1():
    with pytest.raises(TypeError):
        a_random_function()

def test_random_function2():
    with pytest.raises(CustomExc):
        a_random_function()

def test_random_function3():
    with pytest.raises(BaseException):
        a_random_function()

1 个答案:

答案 0 :(得分:1)

CustomExc既是TypeError也是BaseException,因此这是预期的行为。使用isinstance检查引发的异常的类型,这意味着所有基类也将通过。

如果要测试具体异常,而不是任何派生异常,则必须自己进行检查。如前所述,您可以检查异常信息:

def test_random_function():
    with pytest.raises(TypeError) as e:
        a_random_function()
    assert e.type == CustomExc