proposed unittest enhancement

John S. Yates, Jr. john at yates-sheets.org
Fri Oct 19 16:44:26 EDT 2001


I am new to the Python community and hence unsure of how to
submit proposed changes to the standard distribution.  If
posting to this ng is inappropriate please redirect me.

I am using unittest.  To support coverage testing I want
to compute large numbers of very similar tests.  It is
important that once an error has been detected I be able
to run that single case without the noise of all the other
coverage cases.

My approach is to add test methods to the TestCase during
module initialization.  I do this by evaluating a lambda
inside a series of nested for loops and use default para-
meters to effect a closure.  Example:

=========

class computedTests( TestCase ):
    def doTest( self, i, j ):
        print "i=%s, j=%s" % (i, j)

for i in range(3):
    for j in range(2):
        setattr( computedTests, \
                 "test_%s_%s" % (i, j), \
                 lambda self, ii=i, jj=j: self.doTest( ii, jj ) )
=========

This works great as long as I am interested in running all
the tests.  Once I specify an individual test I stumble on
a "bug" in unittest.TestLoader.loadTestsFromName.  When the
type analysis determines that a looked-up attribute is an
UnboundMethodType it assumes that the function object was
introduced by a "def" statement rather than a lambda and
hence that it has a meaningful __name__ attribute:

        elif type(obj) == types.UnboundMethodType:
            return obj.im_class(obj.__name__)

This assumption is unnecessary since the type analysis was
immediately preceded by a getattr() call in which the name
was passed as an argument:

            obj = getattr(obj, part)

I suggest this small change to the UnboundMethodType case:

        elif type(obj) == types.UnboundMethodType:
            return obj.im_class(part)

/john



More information about the Python-list mailing list