[Tutor] unittest.makeSuite question

Danny Yoo dyoo at hkn.eecs.berkeley.edu
Fri Dec 3 10:05:26 CET 2004



On Thu, 2 Dec 2004, Kent Johnson wrote:

> makeSuite() creates a TestSuite object that consolidates all the test
> methods of the class named by the first argument. Test methods are
> identified by having names starting with the second argument.


[text cut]

The unit testing framework is closely related to a similar system written
in Java called "JUnit", and the JUnit folks have written a nice tutorial
on the concepts behind their framework:

   http://junit.sourceforge.net/doc/testinfected/testing.htm

I highly recommend the article... even if the programming language syntax
seems a bit stuffy.  *grin*

The authors do a good job to explain the core ideas behind unit testing.
One is that a "suite" is a collection of tests.  With a suite, we can glue
a bunch of tests together.


Being able to aggregate tests doesn't sound too sexy, but it's actually
very powerful.  As a concrete example, we can write a module that
dynamically aggregates all unit tests in a directory into a single suite:

###
"""test_all.py: calls all the 'test_*' modules in the current
directory.

Danny Yoo (dyoo at hkn.eecs.berkeley.edu)
"""

import unittest
from glob import glob
from unittest import defaultTestLoader


def suite():
    s = unittest.TestSuite()
    for moduleName in glob("test_*.py"):
        if moduleName == 'test_all.py': continue
        testModule = __import__(moduleName[:-3])
        s.addTest(defaultTestLoader.loadTestsFromModule(testModule))
    return s

if __name__ == '__main__':
    unittest.TextTestRunner().run(suite())
###

Here, we search for all the other test classes in our relative vicinity,
and start adding them to our test suite.  We then run them en-masse.  And
now we have a "regression test" that exercises all the test classes in a
package.


Hope this helps!



More information about the Tutor mailing list