Jeremy Satterfield
Coding, Brewing 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.mock.StubOutWithMock(Task, 'run')


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.