using pytest.raises to catch expected custom error
本问题已经有最佳答案,请猛点这里访问。
我是pytest的新手,正在尝试将一些功能测试脚本转换为可以与pytest完美配合的脚本。 我的模块具有自定义错误类型,我正在尝试使用" with pytest.raises()as excinfo"方法。 这是一个科学/数字软件包,我需要测试某些方法在调用时是否一致,因此我不能仅深入到较低层次的内容。 谢谢
是什么导致您停止导入特定异常并在您的
1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 | # 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) |