【问题标题】:Python Mock - return_value - getting the "real" return valuePython Mock - return_value - 获取“真实”返回值
【发布时间】:2017-07-22 03:18:00
【问题描述】:

当使用patch.object 来模拟一个方法时,有没有办法指定对于某些参数值,该方法将运行,因为它根本没有被模拟,并将返回“真实的”return_value,并且对于其他参数值设置具体的return_value?

谢谢。

【问题讨论】:

    标签: python pytest python-mock


    【解决方案1】:

    这是一个运行良好的解决方案(从我使用它的地方修改)。它涉及将补丁的side_effect 设置为函数。

    import os.path
    from unittest import mock
    
    def different_return_values(dct):
         def f(*args):
             return dct[args]
         return f
    
    with mock.patch.object(
        os.path,
        'exists',
        side_effect=different_return_values({
            # The "generic" version above makes the arguments in order
            # the keys to this map, you could write a specialized version
            # which has a single argument or *whatever* key combination you
            # like
            ('myfile',): True,
            ('wat',): 'not a real return value but hey, monkeypatch!',
            ('otherfile',): False,
        }),
    ):
        print(os.path.exists('myfile'))
        print(os.path.exists('wat'))
        print(os.path.exists('otherfile'))
    
    OUTPUT = """\
    True
    not a real return value but hey, monkeypatch!
    False
    """
    

    这里的要点是你可以提供一个更智能的你正在修补的函数的实现side_effect:https://docs.python.org/3/library/unittest.mock.html#unittest.mock.Mock.side_effect

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2015-09-09
      • 2014-09-08
      • 2015-10-13
      • 2016-11-07
      • 2017-04-03
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多