unit test nested functions

Raymond Hettinger python at rcn.com
Sat Jul 23 18:01:02 CEST 2005

> How can you unit test nested functions?  Or do you have to pull them out to
> unit test them, which basically means I will never use nested functions.

Several commons use cases (closures and factory functions) ultimately
expose the inner function through the return value.  If that is the
case, the answer is simple, call the enclosing function and then run
the test on the result.

If the inner function never gets exposed, an argument could be made
that you don't want to write a test for it -- that the inner function
is just an implementation detail.  This is black box testing and
consistent with a test driven development approach.

For whitebox testing, you could make an inner function visible by
binding it to the enclosing function's attribute namespace.

   def f(x):
       def g(y):
          . . .
       f.g = g        # make g visible as an attribute of f
       . . .


More information about the Python-list mailing list