Python: How to run unittest.main() for all source files in a subdirectory?
I knew there was an obvious solution:
dirFoo\
__init__.py
test.py
dirBar\
__init__.py
Foo.py
Bar.py
Contents of dirFoo/test.py
from dirBar import *
import unittest
if __name__ == "__main__":
unittest.main()
Run the tests:
$ python test.py
...........
----------------------------------------------------------------------
Ran 11 tests in 2.305s
OK
As of Python 2.7, test discovery is automated in the unittest package. From the docs:
Unittest supports simple test discovery. In order to be compatible with test discovery, all of the test files must be modules or packages importable from the top-level directory of the project (this means that their filenames must be valid identifiers).
Test discovery is implemented in
TestLoader.discover()
, but can also be used from the command line. The basic command-line usage is:cd project_directory python -m unittest discover
By default it looks for packages named test*.py
, but this can be changed so you might use something like
python -m unittest discover --pattern=*.py
In place of your test.py script.
Here is my test discovery code that seems to do the job. I wanted to make sure I can extend the tests easily without having to list them in any of the involved files, but also avoid writing all tests in one single Übertest file.
So the structure is
myTests.py
testDir\
__init__.py
testA.py
testB.py
myTest.py look like this:
import unittest
if __name__ == '__main__':
testsuite = unittest.TestLoader().discover('.')
unittest.TextTestRunner(verbosity=1).run(testsuite)
I believe this is the simplest solution for writing several test cases in one directory. The solution requires Python 2.7 or Python 3.