2014-02-18 16 views
0

我使用Python的單元測試與簡單的代碼如下所示:Fecthing單元測試用例在Python自動

suite = unittest.TestSuite() 
suite.addTest(unittest.defaultTestLoader.loadTestsFromTestCase(module1)) 
suite.addTest(unittest.defaultTestLoader.loadTestsFromTestCase(module2)) 

我希望我的測試套件,自動解析所有模塊和搜索所有的單元測試用例的文件,我們已經寫了?例如對於例如

有5個文件,

1)。 f1.py

2)。 f2.py

3)。 f3.py

4)。 f4.py

5)。 f5.py

我們不知道這個文件是單元測試用例文件。我想辦法通過每個文件都將被解析並只擁有單元測試的情況下,模塊的名稱應返回

注: - 我使用Python 2.6.6所以無法真正利用unittest.TestLoaded.discover()

+0

由於這個原因,我將單元測試從unittest更改爲py.test。 – Alex

回答

2

考慮使用nose工具,它會徹底改變您的單元測試生活。您只需在源文件夾根目錄中運行它:

> nosetests 

然後它會自動查找所有測試用例。

如果您還想運行所有的文檔測試,使用方法:

> nosetests --with-doctest 

在情況下,如果你只是想找到模塊的列表編程,nose提供了一些API(不幸的是,不是很方便的TestLoader.discover())。

更新:我剛剛發現(雙關語意),有一個叫unittest2庫backports中所有的後來unittest功能,早期版本的Python。我會保留考古學家的代碼,但我認爲,unittest2是更好的選擇。

import nose.loader 
import nose.suite 
import types 

def _iter_modules(tests): 
    ''' 
    Recursively find all the modules containing tests. 
    (Some may repeat) 
    ''' 
    for item in tests: 
     if isinstance(item, nose.suite.ContextSuite): 
      for t in _iter_modules(item): 
       yield t 
     elif isinstance(item.context, types.ModuleType): 
      yield item.context.__name__ 
     else: 
      yield item.context.__module__ 

def find_test_modules(basedir): 
    ''' 
    Get a list of all the modules that contain tests. 
    ''' 
    loader = nose.loader.TestLoader() 
    tests = loader.loadTestsFromDir(basedir) 
    modules = list(set(_iter_modules(tests))) # remove duplicates 
    return modules 
+0

感謝您的建議,但對我的問題有任何補救措施。我肯定會調查鼻子。 –

+0

鼻子也有一些不錯的API。將現在更新... – bereal

+0

順便說一句,剛剛簽出鼻子支持從Python 3.我使用2.6.6。 –