James Lin
James Lin

Reputation: 26558

How to make a mocked object's arbitrary nested attributes/methods to return specific values in Python?

Let's say I am creating a mock object:

mocked = MagicMock()

And I would like to set this mocked instance's all arbitrary nested attributes/methods to return specific values:

mocked = MagicMock()
# mock.all_return_value = 'expected'
# so calling the following will return `expected`
mocked.a.b.c.d()

Is it possible?

Upvotes: 2

Views: 234

Answers (1)

Mark
Mark

Reputation: 92460

You may be able to subclass and override _get_child_mock().

It is designed for subclasses to override to return customized values for properties:

_get_child_mock(**kw)

Create the child mocks for attributes and return value. By default child mocks will be the same type as the parent. Subclasses of Mock may want to override this to customize the way child mocks are made.

If you make it return a new instance and set the return_value you should get the effect you want:

class NestMock(MagicMock):
    def _get_child_mock(self, **kw):
        return NestMock(return_value = kw['parent'].return_value)


m = NestMock(return_value="expected")
m()               # 'expected'
m.a.b()           # 'expected'
m.call_count      # 1
m.a.b.call_count  # 1
m.c.call_count    # 0

Upvotes: 1

Related Questions