1
我想修補方法返回的數據的屬性。模擬修補方法和屬性
假設我有以下簡化片代碼:
@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
上述代碼失敗,因爲模擬方法不適用於「內容」提供一個模擬/存根存在於請求庫屬性。有誰知道如何存根內容屬性?