fork download
  1. from unittest import mock
  2.  
  3. class MyClass(object):
  4. def my_method(self, arg):
  5. return arg + 1
  6.  
  7. def unit_under_test():
  8. inst = MyClass()
  9. return inst.my_method(1)
  10.  
  11. class MyMock(mock.MagicMock):
  12. def __init__(self, *args, **kwargs):
  13. super().__init__(*args, **kwargs)
  14. print('called with', args, kwargs)
  15.  
  16. with mock.patch.object(mock, 'MagicMock', MyMock):
  17. with mock.patch.object(MyClass, 'my_method', autospec=True, side_effect=MyClass.my_method) as spy:
  18. result = unit_under_test()
  19. assert result == 2
  20. assert spy.call_count == 1
Success #stdin #stdout 0.09s 16816KB
stdin
Standard input is empty
stdout
called with () {'parent': None, '_new_parent': None, '_new_name': '', 'name': 'my_method', 'spec': <function MyClass.my_method at 0x148e3f8289d0>, 'side_effect': <function MyClass.my_method at 0x148e3f8289d0>}
called with () {'_new_parent': <MyMock name='my_method' spec='function' id='22601182987888'>, '_new_name': '()'}