使用pytest.raises捕获预期的自定义错误

26 投票
1 回答
30937 浏览
提问于 2025-04-17 16:41

我刚接触pytest,想把一些功能测试脚本改成能和pytest配合得好的版本。我的模块里有自定义的错误类型,我想用with pytest.raises() as excinfo这个方法。因为这是一个科学/数值计算的包,我需要测试某些方法在调用时的一致性,所以不能只关注底层的细节。

1 个回答

45

是什么阻止你导入特定的异常并在你的 with pytest.raises 语句中使用它呢?为什么这样做不行?如果你能提供更多关于你遇到的问题的细节,那会更有帮助。

# your code

class CustomError(Exception):
    pass


def foo():
    raise ValueError('everything is broken')

def bar():
    raise CustomError('still broken')    

#############    
# your test

import pytest
# import your module, or functions from it, incl. exception class    

def test_fooErrorHandling():
    with pytest.raises(ValueError) as excinfo:
        foo()
    assert excinfo.value.message == 'everything is broken'

def test_barSimpleErrorHandling():
    # don't care about the specific message
    with pytest.raises(CustomError):
        bar()

def test_barSpecificErrorHandling():
    # check the specific error message
    with pytest.raises(MyErr) as excinfo:
        bar()
    assert excinfo.value.message == 'oh no!'

def test_barWithoutImportingExceptionClass():
    # if for some reason you can't import the specific exception class,
    # catch it as generic and verify it's in the str(excinfo)
    with pytest.raises(Exception) as excinfo:
        bar()
    assert 'MyErr:' in str(excinfo)

撰写回答