I am testing a method, geodata_collect._request_loc_data(), and within that method I call another method, geodata_collect.utils.loadJSON(...) which I need to mock in order to unit-test the first mentioned method.
My problem is that I need geodata_collect.utils.loadJSON(...) to return a different value the third time it is called from within geodata_collect._request_loc_data().
I have been exploring MagicMock and side_effect in order to do this.
mock = MagicMock()
mock.side_effect = [self._create_request_dict(next_page_token=True),
self._create_request_dict(next_page_token=True), self._create_request_dict()]
with patch('geodata_collect.utils.loadJSON',return_value=mock):
geodata_collect._request_loc_data()
However, when geodata_collect.utils.loadJSON(...) is called from within geodata_collect._request_loc_data() the MagicMock class is returned, instead of the actual value.
<MagicMock id='140642209064888'>
What should be returned:
{'status': 'OK', 'next_page_token': 'Next Page EXISTS!!', 'result': [1, 2, 3, 4, 5]}
{'status': 'OK', 'next_page_token': 'Next Page EXISTS!!', 'result': [1, 2, 3, 4, 5]}
{'status': 'OK', 'result': [1, 2, 3, 4, 5]}
print(mock.called())produce, for instance?with patch('geodata_collect.utils.loadJSON') as mock:, then setmock.return_value.side_effectin thewithblock. But that's just my preference. That way you also have access to the mock that actually replacedloadJSON, not just the result of calling that mock.