I have used flask_restful
to create one of my API. The resource or API class called TotalUserResponse has a method called process_get_request that I am trying to unittest.
def process_get_request(self):
params = parser_get.parse_args()
user_id = params.get('user_id')
if not user_id:
raise ValueError("User id is empty")
user = session.query(User).get(user_id)
if not user:
raise MyValidationError("User not found")
# total applied, favourited and archived
aggregated_actions = self.get_aggregated_actions(user_id)
response = dict(applied=aggregated_actions[0],
favourited=aggregated_actions[1],
archived=aggregated_actions[2])
return response
unittest -
@mock.patch('application.resources.user_response.TotalUserResponse', autospec=True)
@mock.patch('application.models.session.query', autospec=True)
@mock.patch('flask_restful.reqparse.RequestParser.parse_args', autospec=True)
def test_process_get_request(self, parse_args_mock, query_mock, total_user_response_mock):
parse_args_mock.return_value = dict(user_id='xxxxxx')
query_mock.return_value.get.return_value = 'something non empty'
expected_applied, expected_favourited, expected_archived = 5, 10, 20
total_user_response_mock.return_value.get_aggregated_actions.return_value = (expected_applied, expected_favourited, expected_archived)
expected_response = dict(applied=expected_applied,
favourited=expected_favourited, archived=expected_archived)
self.assertEqual(self.total_user_response.process_get_request(), expected_response)
My unittest fails saying -
AssertionError: {'applied': <MagicMock name='query().filter().first().__getitem__()' id='1543892 [truncated]... != {'applied': 5, 'archived': 20, 'favourited': 10}
From the above error message, I understand that get_aggregated_user_actions is not getting mocked. When I debug it, I see that the debugger takes me inside the function also which wouldn't have happened if it was properly mocked.
What's wrong? Please help me out.