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

前端 未结 6 1257
野趣味
野趣味 2020-12-04 13:17

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:

6条回答
  •  孤城傲影
    2020-12-04 13:33

    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.

提交回复
热议问题