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

标签 python api testing exception 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:在“日期数据‘test’不匹配格式‘%Y-%m-%d %H:%M:%S’”中找不到模式‘无效输入’

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

最佳答案

由于引发的异常,它没有到达您的第二个断言。您可以做的是以这种方式断言它的值(value):

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

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

关于python - 为什么 pytest 覆盖会跳过自定义异常消息断言?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/58034783/

相关文章:

angularjs - 当我使用 browser().navigateTo() 时,我如何才能看到 karma 看到的内容

python - 通过同一垂直线中的圆进行圆识别和画线

java - 将 Salesforce 报告导出为 CSV (Java)

python - 如何在 Rhythmbox 中查询数据

javascript - API 在未发送/api/users/create 响应的情况下解析,这可能会导致请求停止。下一个

c# - C# 中的 Google Geocoding Json 解析问题

testing - 如何在 Grails 2.0 服务中单元或集成测试使用注入(inject)的 messageSource for i18n

asp.net-mvc - Controller 测试问题

python - 如何检查字典是否包含字典?

python - pandas 数据框在 matplotlibm 中绘制为表格,但缺少第一列