Oleksiy Oleksiy - 4 years ago 189
Python Question

Mocking nested properties with mock

I have a function call that returns an object:

r = Foo(x,y)

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

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

I do not care about intermediate properties much.

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

dbw dbw
Answer Source

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

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

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

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

Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download