I try to test some codes which don\'t return anything but save the result to the DB. By mocking the save method, I wish to check whether things have been processed correctly
Sometime you just want to check that a method has been called, but you have no control over where its class is instantiated or the method called. Here's an approach that could save some time to whoever stumble upon this pattern:
# first get a reference to the original unbound method we want to mock
original_save = Item.save
# then create a wrapper whose main purpose is to record a reference to `self`
# when it will be passed, then delegates the actual work to the unbound method
def side_fx(self, *a, **kw):
side_fx.self = self
return original_save(self, *a, **kw)
# you're now ready to play
with patch.object(Item, 'save', autospec=True, side_effect=side_fx) as mock_save:
data = "the data"
# your "system under test"
instance = SomeClass()
# the method where your mock is used
instance.some_method(data)
# you now want to check if it was indeed called with all the proper arguments
mock_save.assert_called_once_with(side_fx.self, data)
You need autospec=True
def mock_save(self):
assert self.attr == 'dest_val'
with mock.patch.object(Item, "save", autospec=True) as save:
save.side_effect = mock_save
func_to_call()