我正在为 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/