我是新手pytest
,正在尝试将一些功能测试脚本转换为与pytest
. 我的模块具有自定义错误类型,我正在尝试使用该with pytest.raises() as excinfo
方法。这是一个科学/数值包,我需要测试某些方法在调用时是否一致,所以我不能只深入到较低级别的东西。
问问题
21977 次
1 回答
40
是什么阻止您导入特定异常并在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)
于 2013-03-01T06:58:32.833 回答