模拟补丁方法和属性

时间:2012-09-14 12:35:08

标签: python mocking patch

我想修补方法返回的数据的属性。

假设我有以下简化的部分代码:

@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

上面的代码失败,因为mock方法没有为请求库中的'content'属性提供模拟/存根。有谁知道如何存根内容属性?

1 个答案:

答案 0 :(得分: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()