为何pytest coverage跳过自定义异常消息断言?

时间:2019-09-20 20:28:19

标签: python api testing exception pytest

我正在为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而不是我的包装程序引用异常消息?

2 个答案:

答案 0 :(得分:1)

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

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

我会说您得到一个错误“ AssertionError:在“日期数据'测试'中找不到模式'无效输入'与格式'%Y-%m-%d%H:%M:%S'不匹配”响应代码为200时-因此不会引发异常。

答案 1 :(得分:0)

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