使用mock模拟嵌套属性

时间:2012-08-15 23:56:17

标签: python unit-testing properties mocking nested

我有一个返回对象的函数调用:

r = Foo(x,y)

其中r具有丰富的嵌套属性集。例如,我可以访问r.prop_a.prop_b.prop_c。我想模仿Foo,以便修改r的特定叶属性,即r.prop_a.prop_b.prop_c返回我控制下的值:

>> r = Foo(x,y)
>> r.prop_a.prop_b.prop_c
'fish'
>> # some mock magic patching of Foo is taking place here
>> r = Foo(x,y)
>> r.prop_a.prop_b.prop_c
'my_fish'

我不太关心中间性质。

是否有一种使用mock模拟嵌套属性的优雅方法?

2 个答案:

答案 0 :(得分:13)

按预期更换模拟对象的属性调用:

>> r1 = r_original(x, y)
>> r1.prop_a.prop_b.prop_c
'fish'

>> returner = mock.MagicMock()
>> returner.prop_a.prop_b.prop_c = 'fish'
>> r_mocked = mock.MagicMock(spec_set=r_original, return_value=returner)
>> r2 = r_mocked(x, y)
>> r2.prop_a.prop_b
MagicMock name='returner.prop_a.prop_b' id='87412560'>
>> r2.prop_a.prop_b.prop_c
'fish'

这可以让您在定义特定值时充分发挥模拟作用。

答案 1 :(得分:3)

如果要在其他地方公开原始属性,可以定义包装类:

class OverrideAttributePath(object):
    """A proxy class where we override a specific attribute path with the
    value given. For any other attribute path, we just return
    attributes on the wrapped object.

    """
    def __init__(self, thing, path, value):
        self._thing = thing
        self._path = path
        self._value = value

    def __dir__(self):
        return dir(self._thing)

    def __len__(self):
        return len(self._thing)

    def __getitem__(self, index):
        if self._path == [index]:
            return self._value
        elif self._path[0] == index:
            return OverrideAttributePath(
                self._thing[index], self._path[1:], self._value)
        else:
            return self._thing[index]

    def __getattr__(self, key):
        if self._path == [key]:
            return self._value
        elif self._path[0] == key:
            return OverrideAttributePath(
                getattr(self._thing, key), self._path[1:], self._value)
        else:
            return getattr(self._thing, key)

用法如下:

>>> r = Foo(x,y)
>>> r2 = OverrideAttributePath(r, ['prop_a', 'prop_b', 'prop_c'], 'my_fish')
>>> r2.prop_a.prop_b.prop_c
'my_fish'