I would like to write a unit test case for HTTPError exception part based on the error response content I get. But I have now idea how I can mock the response so that the unit test can reach doSomething1() instead of doSomething2().
foo.py
def get_result_from_API():
#Try to call API here...
def getSomething():
try:
result = get_result_from_API()
except HTTPError as error:
error_json = error.response.json()
if error_json.get("error").get("code") == "00001":
doSomething1()
else:
doSomething2()
raise error
Unit Test
@patch('foo.doSomething2')
@patch('foo.doSomething1')
@patch('foo.get_result_from_API')
def testGetSomething(get_result_from_API,doSomething1,doSomething2):
mock_response = Mock()
mock_response.return_value = {
"error":{
"code": "00001",
"message": "error message for foo reason"
}
}
get_result_from_API.side_effect = HTTPError(response=mock_response)
with self.assertRaises(HTTPError):
foo.getSomething()
doSomething1.assert_called_once()
The current result is that doSomething1() is not called where as doSomething2() is called.