import requests
import requests.exceptions
from requests.exceptions import HTTPError, ConnectionError
import unittest
from unittest.mock import Mock, MagicMock, patch
def request_API_response(query_str : str) -> requests.Response :
'''
get the response from the API, if the status code is not 200, raise an error
Parameters
query : any - query to control the input
response : requests.Response - the response from the API
'''
try:
url = 'https://api.example.com/range/' + query_str
response = requests.get(url, timeout=10)
response.raise_for_status() # raise an error if the status code is not 200 HACK x test use a mock response HOWTO?
except HTTPError:
raise HTTPError('Something went wrong with the server, try again later.')
except ConnectionError:
raise ConnectionError('Something went wrong with the connection, try again later.')
except TimeoutError as e:
raise TimeoutError(f'Unexpected error: {e.__cause__}')
else:
if response.status_code.ok:
return response
# then the test i want to perform on the raise_for_status():
class Test_the_raise_exception(unittest.TestCase):
@patch('this_module_name.requests.get')
def test_request_API_response_raise_for_status(self, mock_requests):
mock_response = MagicMock(status_code=403)
mock_response.raise_for_status.side_effect = requests.HTTPError('Something went wrong with the server, try again later.')
input_query = 'hello'
response = request_API_response_raise_exception(input_query)
with self.assertRaises(HTTPError) as context:
response
self.assertEqual(context.exception, 'Something went wrong with the server, try again later.')
i tried to add this line in the test_request_API_response_raise_for_status
mock_requests.get.side_effect = requests.HTTPError('Something went wrong with the server, try again later.')
i tried to print(response) - > None # it must be ok since the function doesn't return anything
also print(type(response)) -> NoneType
i already resolved this issue if i return a string.
but for my use i need to raise exception in the body of request_API_response(..)
Renato Eliasy is a new contributor to this site. Take care in asking for clarification, commenting, and answering.
Check out our Code of Conduct.