2011-09-15 78 views
2

一個問題我繼續「引導」我的測試。我的問題是what this guy has引導測試和使用Python測試發現

最上面的解決方案是關於創建「boostrap」腳本的。我認爲我必須枚舉所有要運行的測試,或者使用__all__關鍵字在__init__.py文件中使用測試清單。但是,我注意到most recent Python documentation on unittest不再談論__all__了。

在2.7中,我們有一個名爲 「發現」

python -m unittest discover 

python命令這工作,甚至更好。這是因爲: 1)沒有必要對鼻 2)沒有必要進行測試表現

但它似乎並不有一種方法來「引導」

我需要使用另一個測試運行?一個允許引導和發現?

我需要py.test嗎?
http://pytest.org/

我需要引導的原因是this guy has。基本上,如果我直接運行測試,我的導入語句不能正常工作。我想從我的項目頂部執行我的測試套件,就像應用程序運行正常時一樣。

畢竟,導入語句總是相對於它們的物理位置。 (順便說一句,我認爲這是Python的障礙)

定義:什麼是Bootstrapping? Bootstrapping意味着我想在整個項目中運行任何測試之前進行一些設置。這就像我在整個項目級要求「測試設置」一樣。

更新 Here is another posting about the same thing。使用這個2.7命令,我們可以避免鼻子。但是,如何添加引導?

+0

所以問題是,當你不在項目的頂部時,你想用某種方式來做發現+自舉?這似乎是一個非常有限的用例,我只從我的項目頂部運行測試。 – djc

+0

我想我可能輸錯了。我想從我的項目頂部開始它 - 就像我正常運行我的應用程序一樣。 – 010110110101

回答

3

我知道了!

使用我編寫的一個腳本並將其命名爲「runtests.py」並放置在我的項目根目錄中,我能夠「引導」即運行一些初始化代碼並使用發現。活泉!

在我的情況下, 「引導」 的代碼是兩行說:

import sys 
sys.path.insert(0, 'lib.zip') 

謝謝!

#!/usr/bin/python 

import unittest 
import sys 
sys.path.insert(0, 'lib.zip') 

if __name__ == "__main__": 
    all_tests = unittest.TestLoader().discover('.') 
    unittest.TextTestRunner().run(all_tests) 
0

這就是我所做的,我認爲它工作得很好。對於類似這樣的文件/目錄結構:

main_code.py 
run_tests.py 
    /Modules 
     __init__.py 
     some_module1.py 
     some_module2.py 
    /Tests 
     __init__.py 
     test_module1.py 
     test_module2.py 

這是相當輕鬆地組織run_tests.py文件來引導測試。首先,每個測試文件(test_module1.py等)都應該實現一個生成測試套件的函數。例如:

def suite(): 
    suite = unittest.TestSuite() 
    suite.addTest(unittest.makeSuite(Test_Length)) 
    suite.addTest(unittest.makeSuite(Test_Sum)) 
    return suite 

在您的測試代碼的末尾。然後,在run_tests.py文件,這些聚合成一個額外test_suite,並運行:

import unittest 
import Tests.test_module1 as test_module1 
import Tests.test_module2 as test_module2 

module1_test_suite = test_module1.suite() 
module2_test_suite = test_module2.suite() 

aggregate_suite = unittest.TestSuite() 
aggregate_suite.addTest(module1_test_suite) 
aggregate_suite.addTest(module2_test_suite) 

unittest.TextTestsRunner(verbosity = 2).run(aggregate_suite 

然後運行所有這些測試,在命令行中,只需運行

python run_tests.py 
+0

您的回答描述了使用「全部」關鍵字「創建清單」的變體。我試圖避免所有這些工作。我認爲Python 2.7中新的「發現」功能是爲了避免所有這些額外的工作。 – 010110110101

+0

我試圖在Python 2.7中使用自動發現功能。 – 010110110101

+0

這很公平。我想我不明白你的問題是因爲你想要單獨運行每個測試而發生的。僅供參考,我通過將標誌作爲命令行參數傳遞,然後將它們從'sys.argv'中拉出來,以便可以選擇性地導入測試。這允許一些像「不運行任何集成測試」這樣的愛好者行爲。 – Wilduck