2012-01-25 48 views
6

我使用Python的單元測試與簡單的代碼如下所示:如何從TestSuite中提取測試用例列表?

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

不過,我想要做一些自定義的東西,每個測試,他們已經被收集套件後。我想我可以做這樣的事情的測試用例迭代的套件:

print suite.countTestCases() 
for test in suite:    # Also tried with suite.__iter__() 
    # Do something with test 
    print test.__class__ 

然而,對於儘可能多的測試案例,因爲我加載,它永遠只能打印

3 
<class 'unittest.suite.TestSuite'> 

有沒有一種方法我可以從套件中獲取TestCase類的所有對象?有沒有其他一些方法可以加載測試用例來促進這一點?

回答

5

嘗試

for test in suite: 
    print test._tests 
+1

好的,我認爲這就是我想要的。我注意到_tests,但我試圖稱它爲'print suite._tests'。我想我會把它當成Python的noob。 – denaje

+0

我打算去,但顯然你必須等10分鐘才能接受。非常感謝! – denaje

1

我使用這個功能在一些對suite._tests元素都是自己的套房:

def list_of_tests_gen(s): 
    """ a generator of tests from a suite 

    """ 
    for test in s: 
    if unittest.suite._isnotsuite(test): 
     yield test 
    else: 
     for t in list_of_tests_gen(test): 
     yield t 
0

獲得的測試列表的一個巧妙的辦法是使用nose2收集插入。

$ nose2 -s <testdir> -v --plugin nose2.plugins.collect --collect-only 
test_1 (test_test.TestClass1) 
Test Desc 1 ... ok 
test_2 (test_test.TestClass1) 
Test Desc 2 ... ok 
test_3 (test_test.TestClass1) 
Test Desc 3 ... ok 
test_2_1 (test_test.TestClass2) 
Test Desc 2_1 ... ok 
test_2_2 (test_test.TestClass2) 
Test Desc 2_2 ... ok 

---------------------------------------------------------------------- 
Ran 5 tests in 0.001s 

OK 

它並沒有真正運行測試。

您可以安裝nose2(和它的插件)是這樣的:

$ pip install nose2 

當然,你可以用nose2到例如運行單元測試像這樣或這樣:

# run tests from testfile.py 
$ nose2 -v -s . testfile 

# generate junit xml results: 
$ nose2 -v --plugin nose2.plugins.junitxml -X testfile --junit-xml 
$ mv nose2-junit.xml results_testfile.xml 
相關問題