unit test nested functions

Andrew Dalke dalke at dalkescientific.com
Sat Jul 23 04:03:37 EDT 2005


Andy wrote:
> How can you unit test nested functions?

I can't think of a good way.  When I write a nested function it's because
the function uses variables from the scope of the function in which it's
embedded, which means it makes little sense to test it independent of the
larger function.

My tests in that case are only of the enclosing function.

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

You don't test every line in a function by itself, right?  Nor
every loop in a function.  It should be possible to test the outer
function enough that the implementation detail - of using an inner
function - doesn't make much difference.

> Also, same thing with private member functions protected by __.  Seems
> like there is a conflict there between using these features and unit
> testing.

In that case the spec defined that the real function name is of
the form "_<CLASSNAME>__<METHODNAME>".  For example

>>> class Spam:
...   def __sing(self):
...     print "I don't see any Vikings."
... 
>>> spam = Spam()
>>> spam._Spam__sing()
I don't see any Vikings.
>>> 

I've found though that the double-leading-underscore is overkill.
Using a single underscore is enough of a hint that the given
method shouldn't be called directly.

Then again, I don't write enough deep hierarchies where I need
to worry about a subclass implementation using the same private
name as a superclass.
				Andrew
				dalke at dalkescientific.com




More information about the Python-list mailing list