Python 如何在pytest中捕获异常后打印消息
假设以下示例代码:Python 如何在pytest中捕获异常后打印消息,python,python-3.x,pytest,Python,Python 3.x,Pytest,假设以下示例代码: def test_foo(): dict = load_dict() try: value = dict[foo][bar] except KeyError: print('missing foo or bar') 如果由于foo或bar不存在而引发KeyError,则测试不会因为捕获异常而失败。如果我添加一个raisesystemexit(1),它将失败,打印消息并显示所有回溯 我的问题是,我如何告诉pytest,如
def test_foo():
dict = load_dict()
try:
value = dict[foo][bar]
except KeyError:
print('missing foo or bar')
如果由于foo
或bar
不存在而引发KeyError
,则测试不会因为捕获异常而失败。如果我添加一个raisesystemexit(1)
,它将失败,打印消息并显示所有回溯
我的问题是,我如何告诉pytest,如果发生
KeyError
,这意味着测试失败,因此我不需要提出SystemExit
?您可以将与pytest一起使用。提出构造函数:
def test_connection_fails(self,):
with pytest.raises(KeyError) as excinfo:
buckets = list_all_buckets()
然后,您可以在不使用sys的情况下引发错误。exit
有一个函数明显未通过测试:
import pytest
def test_foo():
d1 = {'foo': 'bar'}
try:
value = d1['baz']
except KeyError as err:
pytest.fail('this was unexpected: {}'.format(err))
但是,惯用的方法是使用上下文管理器来验证引发的异常,并使用一些方便的实用程序捕获异常进行分析:
import pytest
def test_foo():
d1 = {'foo': 'bar'}
with pytest.raises(KeyError) as excinfo:
value = d1['baz']
assert excinfo.type == KeyError
assert excinfo.match('baz')
查看文档了解更多示例。如果您熟悉unittest
,pytest.raises
是unittest.TestCase.assertRaises
,而pytest.fail
是unittest.TestCase.failpytest.fail
满足我的需要。据我所知,pytest.raises
旨在测试在预期的错误输入时,代码是否正确失败。但那不是我的情况。在上面的代码片段中,bar
可能存在,也可能不存在,这取决于参数,因此我认为python.raises
对我没有用处。将使用pytest.fail
。