惩戒用模拟嵌套属性(Mocking nested properties with mock)

2019-09-21 06:36发布

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

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'

我不关心中间的属性了。

有没有嘲笑与嵌套属性优雅的方式模拟 ?

Answer 1:

替换模拟对象的属性,调用你所期望的:

>> 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'

这可以让你嘲讽,同时定义一个特定值的全部力量。



Answer 2:

如果你想在其他地方露出原有的特性,你可以定义一个包装类:

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'


文章来源: Mocking nested properties with mock