fork download
  1. from unittest import mock
  2.  
  3. class MyClass(object):
  4. def __int__(self):
  5. self.my_attribute = 10
  6.  
  7. @property
  8. def my_property(self):
  9. return self.my_attribute + 1
  10.  
  11. def unit_under_test():
  12. inst = MyClass()
  13. return inst.my_property
  14.  
  15. class MyMock(mock.PropertyMock):
  16. def __init__(self, *args, **kwargs):
  17. super().__init__(*args, **kwargs)
  18. print("MyMock __init__ called.")
  19.  
  20. with mock.patch.object(mock, 'MagicMock', MyMock) as property_mock:
  21. with mock.patch.object(MyClass, 'my_property', autospec=True) as spy:
  22. property_mock.side_effect = lambda self: 2
  23. # or property_mock.return_value = 2
  24. result = unit_under_test()
  25. assert result == 2
  26. assert spy.call_count == 1
Success #stdin #stdout 0.08s 16832KB
stdin
Standard input is empty
stdout
MyMock __init__ called.
MyMock __init__ called.