Jeremy Satterfield
Coding, Making and Tulsa Life

Unit Testing Recursion in Python

Today I finally figured out the solution to a problem I've been trying to solve for a while. It's kind of hacky and maybe a bad idea, but now I know it's possible. The problem has always been that I'd like to test that a function recurses, but not needing it to actually have the recursion execute within to test. Just a unit test to assert that recursion is happening. After a little thought about how Python stores references I came up with this.

class ExampleTest(TestCase):
    def setUp(self):
        self.task = Task()
    # ...
    # other test stuff
    # ...

    def test_recursion(self):
        original_func = self.task.run
        self.mock.StubOutWithMock(Task, 'run')

        Task.run(id=44)

        self.mock.ReplayAll()
        original_func(id=22)
        self.mock.VerifyAll()

Because variables in Python are just references to objects in memory, if you create a new reference before stubbing out the primary reference, pointing it to a mock object, you can still access it via this new reference. You're now free to check that recusion is happening, without the need for it to actually recurse in the test.