为了账号安全,请及时绑定邮箱和手机立即绑定

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

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

偶然的你 2022-06-02 17:55:14
我正在为 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 scrapedef 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 而不是我的包装器的异常消息?
查看完整描述

2 回答

?
莫回无

TA贡献1865条经验 获得超7个赞

由于引发的异常,它不会到达您的第二个断言。你可以做的就是以这种方式断言它的价值:


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 - 所以没有引发异常。


查看完整回答
反对 回复 2022-06-02
?
DIEA

TA贡献1820条经验 获得超2个赞

您的抓取函数引发异常,因此函数调用之后的行将不会执行。您可以将最后一个断言放在 pytest.raises 子句之外,如下所示:


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'


查看完整回答
反对 回复 2022-06-02
  • 2 回答
  • 0 关注
  • 142 浏览
慕课专栏
更多

添加回答

举报

0/150
提交
取消
意见反馈 帮助中心 APP下载
官方微信