I have a parent object, which receives a connection object.
I run a method on this connection object to generate a config object. When I mock this, instead of Foo
I get:
<Mock name='mock().get_properties().property_c' id='1910891784064'>
Code:
# Real
class ClassC:
property_c = "Foo"
class ClassB:
def __init__(self):
pass
def login(self):
print("Logged in...")
def get_properties(self):
return ClassC()
class ClassA:
def __init__(self, conn):
self.conn = conn
self.conn.login()
a = ClassA(conn=ClassB()) >>> Logged in...
result = a.conn.get_properties()
print(result.property_c) >>> Foo
# Mocked
from unittest.mock import Mock
mock_b = Mock()
mock_c = Mock()
mock_c.property_c.return_value = "Foo_Mock"
mock_b.get_properties.return_value = mock_c
a = ClassA(conn=mock_b())
result = a.conn.get_properties()
print(result.property_c) >>> Output shown above
How do I mock this properly?
Edit1 - The suggested duplicate S.O answer only partially answers the question.
Edit2 - I forgot to include the mock login behaviour
mock_b.login.return_value = print("Logged in...")
awesoon's answer still works with this modification:
mock_b = Mock()
mock_c = Mock()
type(mock_c).property_c = PropertyMock(return_value="Foo_Mock")
mock_b.get_properties.return_value = mock_c
mock_b.login.return_value = print("Logged in...")