为什么pytest覆盖率跳过自定义异常消息断言?

2024-09-21 11:36:38 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在为一个api做一个包装器。我希望函数在输入无效时返回自定义异常消息。你知道吗

def scrap(date, x, y):
    response = requests.post(api_url, json={'date': date, 'x': x, 'y': y})
    if response.status_code == 200:
        output = loads(response.content.decode('utf-8'))
        return output
    else:
        raise Exception('Invalid input')

这是对它的测试:

from scrap import scrap

def test_scrap():
    with pytest.raises(Exception) as e:
        assert scrap(date='test', x=0, y=0)
        assert str(e.value) == 'Invalid input'

但由于某种原因,覆盖率测试跳过了最后一行。有人知道为什么吗?我试图将代码更改为with pytest.raises(Exception, match = 'Invalid input') as e,但出现了一个错误:

AssertionError: Pattern 'Invalid input' not found in "date data 'test' does not match format '%Y-%m-%d %H:%M:%S'"

这是否意味着它实际上引用的是来自api的异常消息,而不是我的包装器?你知道吗


Tags: testapi消息inputoutputdatepytestresponse
2条回答

scrape函数引发异常,因此函数调用后的行不会执行。你可以把最后的断言放在pytest.raises公司子句,如下所示:

from scrap import scrap

def test_scrap():
    with pytest.raises(Exception) as e:
        assert scrap(date='test', x=0, y=0)
    assert str(e.value) == 'Invalid input'

由于引发的异常,它不会到达您的第二个断言。你所能做的就是这样断言它的价值:

def test_scrap():
    with pytest.raises(Exception, match='Invalid input') as e:
        assert scrap(date='test', x=0, y=0)

如果响应代码为200,则会出现错误“AssertionError:Pattern'Invalid input'not found in“date data'test'does not match format'%Y-%m-%d%H:%m:%S'”,因此不会引发异常。你知道吗

相关问题 更多 >

    热门问题