Mocking nested properties with mock

2020-08-22 14:46发布

I have a function call that returns an object:

r = Foo(x,y)

where r has a rich set of nested properties. For example, I can access r.prop_a.prop_b.prop_c. I would like to mock Foo, such that a specific leaf property of r is modified, i.e. such that r.prop_a.prop_b.prop_c returns a value under my control:

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

I do not care about intermediate properties much.

Is there an elegant way to mock nested properties with mock?

2条回答
Root(大扎)
2楼-- · 2020-08-22 15:22

Replace the mock object's attribute call as you would expect:

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

This allows you the full power of mocking while defining a specific value.

查看更多
祖国的老花朵
3楼-- · 2020-08-22 15:24

If you want to expose the original properties elsewhere, you can define a wrapper class:

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)

Usage is then as follows:

>>> r = Foo(x,y)
>>> r2 = OverrideAttributePath(r, ['prop_a', 'prop_b', 'prop_c'], 'my_fish')
>>> r2.prop_a.prop_b.prop_c
'my_fish'
查看更多
登录 后发表回答