2009-02-18 18 views
0

我有一個充滿Python單元測試的heirarchical文件夾。它們都是可定義TestCase對象的可導入的「.py」文件。該文件夾包含許多嵌套子目錄中的數千個文件,並由其他人編寫。我沒有權限改變它,我只需要運行它。我想將所有的單元測試加載到樹中,是否可以完成?

我想生成一個包含文件夾中所有TestCases的TestSuite對象。有沒有一種簡單而優雅的方式來做到這一點?

感謝

回答

4

鼻子應用程序可能對您有用,無論是直接或展示如何實現這一點。

http://code.google.com/p/python-nose/似乎是主頁。

基本上,你想要做的就是走在源代碼樹(os.walk),使用imp.load_module 加載模塊,使用unittest.defaultTestLoader從模塊測試加載到TestSuite,然後用在任何你需要的方式使用它。

或者至少這大約是我在我的自定義TestRunner實施 (bzr get http://code.liw.fi/coverage-test-runner/bzr/trunk)做的。

2

看那unittest.TestLoader(https://docs.python.org/library/unittest.html#loading-and-running-tests

而os.walk(https://docs.python.org/library/os.html#files-and-directories

您應該能夠使用TestLoader建立了一套,然後您可以運行遍歷包樹。

沿着這條線的東西。

runner = unittest.TextTestRunner() 
superSuite = unittest.TestSuite() 
for path, dirs, files in os.walk('path/to/tree'): 
    # if a CVS dir or whatever: continue 
    for f in files: 
     # if not a python file: continue 
     suite= unittest.defaultTestLoader.loadTestsFromModule(os.path.join(path,f) 
     superSuite .addTests(suite) # OR runner.run(suite) 
runner.run(superSuite) 

您可以通過樹步行只需運行每個測試(runner.run(suite)可以積累個人所有套房的superSuite和運行質量整體作爲一個單一的測試(runner.run(superSuite))。

你不需要同時做這兩件事,但我在上面(未經測試)的代碼中包含了兩套建議。

1

Python Library source的測試目錄顯示了方式。 README文件描述瞭如何爲庫模塊編寫Python迴歸測試。

regrtest.py module開始有:

"""Regression test. 

This will find all modules whose name is "test_*" in the test 
directory, and run them. 
相關問題