I would like to patch an attribute of the data returned by a method.
Assuming I have the following simplified piece code:
@patch('requests.post')
class TestKeywordsApi(BaseTest):
# Instantiate API class and set the apikey
def setUp(self):
BaseTest.setUp(self)
self.fixtures = FIXTURES
self.api = BaseApi()
def mock_requests_post(self, url, data=None):
''' Mock method for post method from responses library.
It replaces the responses.post calls in Api class.
'''
url = self.encode_url(url, data)
if url:
return self.fixtures[url]
def test_save_success(self, mock_post):
mock_post.side_effect = self.mock_requests_post
response = self.api.post(keyword, params={...})
# list of asserts
# original class calling requests.post
import requests
class BaseApi(object):
def post(self, action, params):
''' Sends a POST request to API '''
response = requests.post(self.build_url(action), data=params).content
The code above fails because the mock method does not provide a mock/stub for ‘content’ attribute present in requests library. Does anyone know how to stub the content attribute?
I found the following solution, which only modifies the mock_requests_post method, adding an internal class with the attribute that I need: