2012-09-14 97 views
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 

上述代碼失敗,因爲模擬方法不適用於「內容」提供一個模擬/存根存在於請求庫屬性。有誰知道如何存根內容屬性?

回答

0

我發現了以下解決方案,其中僅修改mock_requests_post方法,添加內部類我需要的屬性:

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) 

    class classWithAttributes(object): 
     content = json.dumps(self.fixtures[url]) 

    if url: 
     return classWithAttributes() 
0

您的嘲笑帖子函數需要返回一個更類似於requests的響應對象的對象,該對象具有.content屬性。例如:

from mock import Mock, patch 
#[...] 
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. 
    ''' 
    mock_response = Mock() 
    mock_response.content = 'my test response content' 
    url = self.encode_url(url, data) 
    if url: 
     mock_response.url_called = self.fixtures[url] 
    return mock_response 
相關問題