Using python mock to count the number of method calls

advertisements

I'm just starting out using the python mocking framework. I'd like to just count the number of times a method gets called, without removing the effects of actually calling the method.

For example, in this simple counter example, I would like to both increment the counter and track that it was called:

import unittest
import mock

class Counter(object):
    def __init__(self):
        self.count = 0

    def increment(self):
        self.count += 1

class CounterTest(unittest.TestCase):
    def test_increment(self):
        c = Counter()
        c.increment()
        self.assertEquals(1, c.count)

    def test_call_count(self):

        with mock.patch.object(Counter, 'increment') as fake_increment:
            c = Counter()
            self.assertEquals(0, fake_increment.call_count)
            c.increment()
            self.assertEquals(1, fake_increment.call_count)

            # increment() didn't actually get called.
            self.assertEquals(1, c.count)  # Fails.

if __name__ == '__main__':
    unittest.main()

Is it possible to force mock to call the mocked method after it registered the call, or just signify that I want to keep the effects of the mocked function?


Just use wraps:

c = Counter()
with mock.patch.object(Counter, 'increment', wraps=c.increment) as fake_increment:

There can be some binding problems if you initialize c later, as the function passed to wraps won't know about self.