Suppose you want to want to track all calls (args, kwargs and result) made to a given method while running a command, you can do it using the simple decorator defined in the spy.py
module of this gist.
You can use it to spy either on a single instance or to all instances of given class.
The calls will be stored in a list that must be passed by instantiated beforehand and passed to the decorator.
from mock import patch
from spy import spy
from example_spied_class import Incrementer
instance_calls = []
incrementer_instance = Incrementer(0)
with patch.object(incrementer_instance, 'increment', new=spy(incrementer_instance.increment, instance_calls)):
incrementer_instance.increment(1)
incrementer_instance.increment(2, with_extra=True)
print(instance_calls)
print('Last result: %d' % instance_calls[1].result)
it will result in:
[<Call> 1 args, no keyword arguments, <type 'int'> result, <Call> 1 args, "with_extra" keyword arguments, <type 'int'> result]
Last result: 4
from mock import patch
from spy import spy
from example_spied_class import Incrementer
class_calls = []
with patch.object(Incrementer, 'increment', new=spy(Incrementer.increment, class_calls)):
incrementer_instance = Incrementer(10)
incrementer_instance.increment(1)
incrementer_instance.increment(2, with_extra=True)
print(class_calls)
print('Last result: %d' % class_calls[1].result)
it will result in:
[<Call> 2 args, no keyword arguments, <type 'int'> result, <Call> 2 args, "with_extra" keyword arguments, <type 'int'> result]
Last result: 14
Note that you can as well use patch
syntax instead of patch.object
syntax, in this case see mock documentation for more details.