【问题标题】:How to stub a method decorator using mock?如何使用模拟存根方法装饰器?
【发布时间】:2013-07-19 03:20:04
【问题描述】:

如何使用 python mock 将方法装饰器的行为存根,以便我不依赖它们来测试当前方法?

import utils
class Router(object):
    @utils.with_user
    @utils.formatted_response('resources', with_pagination=True)
    def get_resources(self, user_id=None, offset=None, limit=None):
        # do stuff
        pass

我已经试过了:

# @patch('utils.with_tenant')
# @patch.object(utils, 'with_tenant')
def test_stub_decorator(self):
    # patch('utils.with_tenant')
    # patch.object(utils, 'with_tenant')

而且这些似乎都不起作用!有什么想法吗?

【问题讨论】:

    标签: python unit-testing mocking stub


    【解决方案1】:

    对于模拟装饰器,您需要更早地模拟它们(在加载该模块之前):

    from mock import patch
    # mock the retry decorator before any module loads it
    patch('utils.with_user', lambda x: x).start()
    import utils  # or any module which imports utils
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2010-10-14
      • 2016-06-11
      • 1970-01-01
      • 1970-01-01
      • 2019-02-03
      相关资源
      最近更新 更多