Reputation: 11774
I'm using the hammock library to abstract requests to an internal API. In my code, wherein self.api
is a Hammock object, I make the following call:
posts = self.api.posts().GET(params=params).json().get('objects')
where .GET returns a response object, .json converts it to a dictionary, and .get returns the value for the 'objects' key in that dictionary.
What I want is for that whole call to simply return a fixture I have already set up. When I try something like self.worker.api.posts.get = Mock(return_value=fixture)
, however, it doesn't work. It calls out to the actual API.
Is this possible, or should I give up on attempting to mock such a specific call and just settle for mocking the method that contains it?
Upvotes: 1
Views: 1323
Reputation: 940
You need to set all return_values
on mocks. When you call self.api.posts()
a mock is returned and you want to get this mock and set it's return value, which will be an object that has a GET()
method which you also want to mock it's return value until the last call you want to mock.
Here's the example:
self.api.posts.return_value.GET.return_value.json.return_value.get = Mock(return_value=fixture)
My working example:
json_obj = mock.MagicMock(return_value=self.hardcoced_labels)
con.return_value.repos.return_value.labels.GET.return_value.json = json_obj
Upvotes: 2