I am not a super experience in mock 1 but I executed it using the shell functions, and not the default MagicMock :
class FuncWrapper(object): def __init__(self, func): self.call_count = 0 self.func = func def __call__(self, *args, **kwargs): self.call_count += 1 return self.func(*args, **kwargs) class CounterTest(unittest.TestCase): def test_call_count(self): c = Counter() new_call = FuncWrapper(c.increment) with mock.patch.object(c, 'increment', new=new_call) as fake_increment: print fake_increment self.assertEquals(0, fake_increment.call_count) c.increment() self.assertEquals(1, fake_increment.call_count) self.assertEquals(1, c.count)
Of course, this FuncWrapper pretty minimal. It just counts the calls and then passes the flow control back to the original function. If you need to test other things at the same time, you need to add FuncWrapper to the class. I also just fixed the class instance, not the whole class. The main reason for this is because I need an instance method in FuncWrapper .
1 Actually, I just started to study - think about yourself, -).
source share