How do you unit test a nested function?

You don't, because you can't.

You will have to either limit your unit testing to the outer function, or you move the inner function elsewhere.


There is a similar question in this link. But short answer: you can't access an inner function from an outer element.

For testing purposes, maybe an alternative would be to change the inner function for a private outer one?


I had the same doubt and found a way to get tests going for inner functions.

def outer():
    def inner():
        pass

    if __debug__:
        test_inner(inner)
        # return

def test_inner(f):
    f() # this calls the inner function

outer()

Basically you can send the inner function as a parameter to the outside and test it as you wish. When calling outer(), your test will run, and since it's a closure, it will preserve any extra property from the outer function (like variables). Using a list, you can send as many functions as you wish. To ignore the if, an option is to run the code like that:

python -O code.py