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)


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?

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

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