我正在为一个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的异常消息,而不是我的包装器?
发布于 2019-09-25 22:54:07
它不会到达您的第二个断言,因为引发了异常。你可以这样断言它的价值:
def test_scrape():
with pytest.raises(Exception, match='Invalid input') as e:
assert scrape(date='test', x=0, y=0)我会说当响应代码是200时,你会得到一个错误"AssertionError: Pattern 'Invalid input‘not found in "date data 'test’is not match format‘%Y-%m-%d%H:%M:%S’“,所以不会引发异常。
发布于 2019-09-21 05:17:47
抓取函数会引发异常,因此函数调用后的行将不会执行。您可以将最后一个断言放在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'https://stackoverflow.com/questions/58034783
复制相似问题