我最近开始使用pytest,甚至最近开始使用mock来模拟requests库。我已经创建了一个requests.Response对象,对于200状态代码,它工作得很好。我在这里尝试做的是,使用raise_for_status()来检查是否存在超过速率限制的错误,并测试它是否使用pytest处理了异常。
我使用的是模拟side_effect选项,它似乎触发了我希望的异常,但是pytest似乎没有意识到这是已经发生的,所以测试失败。
有什么想法吗?我相信这显然是我遗漏了一些东西!
我为这个类编写的代码是:
class APIClient:
def get_records(self, url):
try:
r = requests.get(url)
r.raise_for_status()
return r.json()
except requests.HTTPError as e:
print("Handling the exception")在测试类中,我得到了:
@pytest.fixture
def http_error_response(rate_limit_json):
mock_response = mock.Mock()
mock_response.json.return_value = rate_limit_json
mock_response.status_code = 429
mock_response.raise_for_status.side_effect = requests.exceptions.HTTPError
return mock_response
class TestRecovery(object):
@mock.patch('requests.get')
def test_throws_exception_for_rate_limit_error\
(self, mock_get, api_query_object, http_error_response):
mock_get.return_value = http_error_response
print(http_error_response.raise_for_status.side_effect)
url = api_query_object.get_next_url()
with pytest.raises(requests.exceptions.HTTPError):
api_query_object.get_records(url)我得到的输出是:
with pytest.raises(requests.exceptions.HTTPError):
> api_query_object.get_records(url)
E Failed: DID NOT RAISE
---------------------- Captured stdout call ----------------------
<class 'requests.exceptions.HTTPError'>
Handling the exception发布于 2020-08-26 19:36:22
您正在指示pytest期待一个应该在APIClient.get_records中引发的异常,但是在该方法定义中,您已经捕获了该异常并只执行了一次打印。
异常实际上正在发生,并通过在控制台输出中查看打印结果证明了这一点。
相反,您应该通过模拟检查raise_for_status方法是否已被调用。
https://stackoverflow.com/questions/35523402
复制相似问题