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

时间:2013-02-21 21:26:24

标签: pytest

我是pytest的新手,我正在尝试将一些功能测试脚本转换成与pytest很好地兼容的脚本。我的模块有自定义错误类型,我正在尝试使用“with pytest.raises()作为excinfo”方法。这是一个科学/数字包,我需要测试某些方法在调用时是否一致,所以我不能只深入到较低级别的东西。感谢

1 个答案:

答案 0 :(得分:28)

什么阻止您导入特定例外并在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)