【问题标题】:Why does pytest coverage skip custom exception message assertion?为什么 pytest 覆盖跳过自定义异常消息断言?
【发布时间】:2020-01-21 21:23:21
【问题描述】:

我正在为一个 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 而不是我的包装器的异常消息?

【问题讨论】:

    标签: python api testing exception pytest


    【解决方案1】:

    您的抓取函数引发异常,因此函数调用之后的行不会执行。您可以将最后一个断言放在 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'
    

    【讨论】:

    • 现在它仍然有 AssertionError 和一些额外的错误: E assert "date data 't...-%d %H:%M:%S'" == 'Invalid input' E -日期数据 'test' 与格式 '%Y-%m-%d %H:%M:%S' 不匹配 E + 无效输入
    【解决方案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 时 - 因此没有引发异常。

    【讨论】:

      猜你喜欢
      • 2017-02-20
      • 1970-01-01
      • 2018-03-07
      • 2019-10-27
      • 2016-03-05
      • 2023-02-17
      • 2019-11-06
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多