13
我是pytest的新手,并试图将一些功能测试脚本转换成pytest很好地运行的脚本。我的模块具有自定义错误类型,我试图使用“with pytest.raises()as excinfo”方法。这是一个科学/数值软件包,我需要测试某些方法在调用时是否一致,因此我不能深入到低层次的东西。谢谢使用pytest.raises捕获预期的自定义错误
我是pytest的新手,并试图将一些功能测试脚本转换成pytest很好地运行的脚本。我的模块具有自定义错误类型,我试图使用“with pytest.raises()as excinfo”方法。这是一个科学/数值软件包,我需要测试某些方法在调用时是否一致,因此我不能深入到低层次的东西。谢谢使用pytest.raises捕获预期的自定义错误
什么是阻止您导入特定异常并在您的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)
看起来像你的最后'与py.test.raises'应该是'与pytest.raises' – 2014-04-12 05:32:57
@IanHunter现在已经更新,谢谢(你能告诉我现在还在使用“py.test”版本: )) – pfctdayelise 2014-04-13 15:45:22
对于python3:'assert str(excinfo.value)=='一切都坏了' – incognick 2016-09-20 16:58:12