unittest: collecting tests from many modules?
Scott David Daniels
Scott.Daniels at Acm.Org
Sun Jun 12 12:10:10 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()
> ....
>
> 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?
> Something like:
>
> import unittest
> import test_foo
> import test_bar
>
> if __name__ == "__main__":
> unittest.main(modules = ['test_foo',
> 'test_bar'])
>
> Seems to me this should be possible, since all the logic for doing it /is/
> there for the local module; I'd assume there would be a way to make unittest
> search additional modules for test classes. But my head starts spinning
> when I read the source code ...
>
> /Jorgen
>
How about some variant of:
import unittest
import test_foo, test_bar, ...
def set_globals(modules):
glbl = globals()
for module in modules:
modprefix = module.__name__[5:] + '__'
for element in dir(module):
data = getattr(module, element)
if isinstance(data, type) and issubclass(data,
unittest.TestCase):
glbl[modprefix + element] = data
if __name__ == "__main__":
module = type(unittest)
set_globals([mod for name, mod in globals().items()
if name.lower().beginswith('test')
and isinstance(mod, module)])
unittest.main()
--Scott David Daniels
Scott.Daniels at Acm.Org
More information about the Python-list
mailing list