Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/349.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 如何在pytest中捕获异常后打印消息_Python_Python 3.x_Pytest - Fatal编程技术网

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.fail

pytest.fail
满足我的需要。据我所知,
pytest.raises
旨在测试在预期的错误输入时,代码是否正确失败。但那不是我的情况。在上面的代码片段中,
bar
可能存在,也可能不存在,这取决于参数,因此我认为
python.raises
对我没有用处。将使用
pytest.fail