unit test nested functions

Raymond Hettinger python at rcn.com
Sat Jul 23 12:59:12 EDT 2005


> > [Andy]
> >>How can you unit test nested functions?

[Raymond Hettinger]
> > 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
> >        . . .

[Benji York]
> Note that when using this technique, f.g will not be bound until after
> you call the function:

That is a feature, not a bug.  The inner function isn't even created
until the outer function is run.

>>> def f(x):
	z = 30
	def g(y):
		return 10
	return 20

>>> from dis import dis
>>> dis(f)
  2           0 LOAD_CONST               1 (30)
              3 STORE_FAST               1 (z)

  3           6 LOAD_CONST               2 (<code object g at 00A33660,
file "<pyshell#37>", line 3>)
              9 MAKE_FUNCTION            0
             12 STORE_FAST               2 (g)

  5          15 LOAD_CONST               3 (20)
             18 RETURN_VALUE

The MAKE_FUNCTION step is where g comes into existence.  That is a
run-time operation, not compile time.

If you are willing to be tricky, it is possible to write an accessor
function that goes into f.func_code.co_consts, finds the code object
whose co_name attribute is 'g', builds a wrapper function using
types.FunctionType, and returns the result for unittesting.  But that
is not for the faint of heart ;-)



Raymond




More information about the Python-list mailing list