2011-02-11 43 views
-1

以下python腳本搜索並執行當前文件夾中的所有pyunit測試。如何使附加的pyunit python腳本搜索子文件夾中的測試

 

"""Regression testing framework 

This module will search for scripts in the same directory named 
XYZtest.py. Each such script should be a test suite that tests a 
module through PyUnit. (As of Python 2.1, PyUnit is included in 
the standard library as 'unittest'.) This script will aggregate all 
found test suites into one big test suite and run them all at once. 
""" 

import sys, os, re, unittest 

def regressionTest(): 
    path = os.path.abspath(os.path.dirname(sys.argv[0])) 
    files = os.listdir(path) 
    print 'You are HERE! ' ,os.getcwd() 
    test = re.compile(".test\.py$", re.IGNORECASE) 
    files = filter(test.search, files) 
    filenameToModuleName = lambda f: os.path.splitext(f)[0] 
    moduleNames = map(filenameToModuleName, files) 
    modules = map(__import__, moduleNames) 
    load = unittest.defaultTestLoader.loadTestsFromModule 
    return unittest.TestSuite(map(load, modules)) 

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

我怎樣才能得到它在子文件夾中搜索測試文件。

也許是這樣的:

 
import sys, os, re, unittest, fnmatch 
 

    for root, dirs, files in os.walk(path): 
     for filename in fnmatch.filter(files, pattern): 
      print os.path.join(root, filename) 
+0

你可以使用[鼻子](http://somethingaboutorange.com/mrl/projects/nose/1.0.0/)。它幾乎爲你自動完成。 – chmullig 2011-02-11 16:54:38

回答

0

變化:

def regressionTest(): 
    path = os.path.abspath(os.path.dirname(sys.argv[0])) 

要:

def regressionTest(somearg): 
    path = os.path.abspath(os.path.dirname(somearg)) 

然後:

for root, dirs, files in os.walk(path): 
    regressionTest(root)