I recently started using pytest and more recently I started using mock to mock the requests library . I made requests. The response object is good, and for status code 200 it works fine. What I'm trying to do here is to use the raise_for_status () function to check if the speed limit is exceeded and to verify that it handles the exception with pytest.
I am using the Mock side_effect parameter, which seems to throw an exception that I hope for, but pytest doesn't seem to recognize this as an event and fails the test.
Any thoughts? I'm sure this is something obvious, I miss you!
The code I have for the class is:
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")
In the testing class, I have:
@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
<class 'requests.exceptions.HTTPError'>
Handling the exception