2017-04-26T18:20:11
Mock Patch Python Requests JSON Return Value
The following code allows us to monkey patch the json()
method that is returned by requests.post()
.
import requests
from mock import MagicMock
@mock.patch.object(requests, 'post')
def my_function(self, post):
attrs = {'json.return_value': {'id': 1}}
post.return_value = MagicMock(**attrs)
r = requests.post()
r.json()['id']
Source: https://docs.python.org/dev/library/unittest.mock.htmll#unittest.mock.NonCallableMock