Python: How to run unittest.main() for all source files in a subdirectory?

Posted by Pete on Stack Overflow See other posts from Stack Overflow or by Pete
Published on 2009-03-13T22:20:31Z Indexed on 2012/11/23 17:06 UTC
Read the original article Hit count: 197

Filed under:
|

I am developing a Python module with several source files, each with its own test class derived from unittest right in the source. Consider the directory structure:

dirFoo\
    test.py
    dirBar\
        __init__.py
        Foo.py
        Bar.py

To test either Foo.py or Bar.py, I would add this at the end of the Foo.py and Bar.py source files:

if __name__ == "__main__":
    unittest.main()

And run Python on either source, i.e.

$ python Foo.py
...........
----------------------------------------------------------------------
Ran 11 tests in 2.314s

OK

Ideally, I would have "test.py" automagically search dirBar for any unittest derived classes and make one call to "unittest.main()". What's the best way to do this in practice?

I tried using Python to call execfile for every *.py file in dirBar, which runs once for the first .py file found & exits the calling test.py, plus then I have to duplicate my code by adding unittest.main() in every source file--which violates DRY principles.

© Stack Overflow or respective owner

Related posts about python

Related posts about unit-testing