unittest: collecting tests from many modules?

Robert Brewer fumanchu at amor.org
Sun Jun 26 17:59:47 EDT 2005


"Jorgen Grahn" wrote:
> I have a set of tests in different modules: test_foo.py, 
> test_bar.py and so on. All of these use the simplest
> possible internal layout: a number of classes containing
> test*() methods, and the good old lines at the end:
> >>
> >>   if __name__ == "__main__":
> >>       unittest.main()
> >>
> This is great, because each of the modules are runnable, 
> and I can select classes or tests to run on the commandline
> if I want to.  However, running all the tests from e.g.
> a Makefile is not that fun; I don't get a single pass/fail
> summary across the modules.
>
> What's the best way of creating a test.py which
> - aggregates the tests from all the test_*.py modules?
> - doesn't require me to enumerate all the test classes in test.py
>   (forcing each module to define test_foo.theSuite or 
> someting would be OK though)
> - retains the ability to select tests and verbosity (-q, 
> -v) from the
>   command line?

I missed the first post somehow; hope this gets in the conversation in
the right place.

Anyway, use normal os.walk() calls to gather the files which start with
"test_"; then use the TestLoader.loadTestsFromName method to instruct
unittest to test them as a group. If you want a working example, see the
CherryPy test loader at:
http://www.cherrypy.org/file/trunk/cherrypy/test/test.py (In that
example, I overrode loadTestsFromName in a subclass, in order to be less
verbose in exactly the way I wanted, but the default works just as
well).


Robert Brewer
System Architect
Amor Ministries
fumanchu at amor.org



More information about the Python-list mailing list