Mock property return value gets overridden when instantiating mock object Mock property return value gets overridden when instantiating mock object python-3.x python-3.x

Mock property return value gets overridden when instantiating mock object


The following line:

type(mock_foo).bar = mock_bar

mocks mock_foo which, at that point, is the return value of enter_context. If I understand the documentation correctly it means you're now actually handling the result of __enter__ of the return value of patch('__main__.Foo', spec=True).

If you change that line to:

type(Foo.return_value).bar = mock_bar

then you'll mock the property bar of instances of Foo (as the return value of calling a class is an instance). The second print statement will then print mock value as expected.


This is not an answer to the question, but was my solution to a simpler problem, having learned from Simeon's answer.

In my case I wanted to mock obj.my_method().my_property and was getting PropertyMock as the return, as I was setting my return value's property directly to my PropertyMock instance, instead of the type of the mock returned by the method. This was the fixed code:

with patch.object(MyObj, "my_method") as method_mock:    property_mock = PropertyMock(return_value='foo')    type(method_mock.return_value).my_property = property_mock