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

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


def scrape(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 scrape import scrape


def test_scrape():

    with pytest.raises(Exception) as e:

        assert scrape(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 而不是我的包装器的异常消息?


偶然的你
浏览 143回答 2
2回答

莫回无

由于引发的异常,它不会到达您的第二个断言。你可以做的就是以这种方式断言它的价值:def test_scrape():    with pytest.raises(Exception, match='Invalid input') as e:        assert scrape(date='test', x=0, y=0)我会说您在响应时收到错误“AssertionError: Pattern 'Invalid input' not found in "date data 'test' does not match format '%Y-%m-%d %H:%M:%S'"代码是 200 - 所以没有引发异常。

DIEA

您的抓取函数引发异常,因此函数调用之后的行将不会执行。您可以将最后一个断言放在 pytest.raises 子句之外,如下所示:from scrape import scrapedef test_scrape():    with pytest.raises(Exception) as e:        assert scrape(date='test', x=0, y=0)    assert str(e.value) == 'Invalid input'
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python