Issue 1207: Load tests from path (patch included) (original) (raw)

Something very nice about unittest is that it can find automatically the TestCase that you declare, and the test methods of every test case. This makes the operation of adding or removing tests very simple.

For test modules however, there is nothing to automatically load all the modules of a given directory. I think that would be very helpful.

Here is my proposal, to add to the set of TestLoader methods:

============================ def loadTestsFromPath( path='', filePattern='test*.py' ): '''Load all the TestCase in all the module of the given path.

path: directory containing test files
filePattern: glob pattern to find test modules inside path. Default

is test*.py

The path will be converted into an import statement so anything that

can not be imported will not work. The path must be relative to the current directory, and can not include '.' and '..' directories.

To simply load all the test files of the current directories, pass

an empty path (the default).

Return a test suite containing all the tests.
'''

if len(path) == 0:
    pathPattern = filePattern
else:
    pathPattern = path + '/' + filePattern
pathPattern = os.path.normpath( pathPattern )
fileList = glob.glob( pathPattern )

mainSuite = TestSuite()
for f in fileList:
    importName = f[:-3]
    importName = importName.replace( '\\', '.' )
    importName = importName.replace( '/', '.' )

    suite = defaultTestLoader.loadTestsFromName(importName)
    mainSuite._tests.extend( suite._tests )

return mainSuite

===================

I use it like this: on my project, I have the following directory organisation:

vy

I can do either:

Each time I add a new test module, it is automatically picked up by the test runners thank to the loadFromPath() feature. It makes it easy to maintain the global test suite that runs all the tests. That's the most important one because that test suite is responsible for non regression.

run_tests.py:

if name == 'main': mainSuite = TestSuite() mainSuite._tests.extend( loadTestsFromPath('.')._tests ) ttr = TextTestRunner(verbosity=2) ttr.run( mainSuite )

run_all_tests.py:

if name == 'main': mainSuite = TestSuite() mainSuite._tests.extend( loadTestsFromPath( 'libvy/tests' )._tests ) mainSuite._tests.extend( loadTestsFromPath( 'qvy/tests' )._tests ) mainSuite._tests.extend( loadTestsFromPath( 'tests' )._tests ) ttr = TextTestRunner(verbosity=2) ttr.run( mainSuite )