2017-02-20 30 views
13

我寫了一個python腳本爲我自動完成所有測試,並生成一個HTML報告。前幾天我發現了discover for unittests,它讓我可以在給定的目錄下運行所有​​的unittests,而不用明確地命名它們,我真的很希望能夠以同樣的方式來完成我的doctests,而不是必須明確地導入每個模塊。如何將doctests與unittest的測試發現結合起來?

我在https://docs.python.org/2/library/doctest.html上發現了一些關於如何做到這一點的信息,但並沒有真正得到它。你能幫我用discover與我的doctests?

Python test discovery with doctests, coverage and parallelism是相關的,但仍然不回答我的問題。

coverage_module

import coverage 
import doctest 
import unittest 
import os 

# import test_module 
import my_module 

cov = coverage.Coverage() 
cov.start() 

# running doctest by explicity naming the module 
doctest.testmod(my_module) 

# running unittests by just specifying the folder to look into 
testLoad = unittest.TestLoader() 
testSuite = testLoad.discover(start_dir=os.getcwd()) 
runner = unittest.TextTestRunner() 
runner.run(testSuite) 

cov.stop() 
cov.save() 
cov.html_report() 
print "tests completed" 

test_module

import unittest 
import doctest 

from my_module import My_Class 


class My_Class_Tests(unittest.TestCase): 
    def setUp(self): 
     # setup variables 

    def test_1(self): 
     # test code 

# The bit that should load up the doctests? What's loader, tests, and ignore though? 
# Is this in the right place? 
def load_tests(loader, tests, ignore): 
    tests.addTests(doctest.DocTestSuite(module_with_doctests)) 
    return tests 

if __name__ == '__main__': 
    unittest.main() 
+5

pytest'現在被認爲是Python測試的標準具,所以我建議檢查一下。看起來它也支持doctests:http://doc.pytest.org/en/latest/doctest.html – yedpodtrzitko

回答

4

讓我們弄清楚發生了什麼有

1)unittest.discovery

它不具備doctests的線索,因爲doctests是一個不同的框架。 所以unittest是不應該發現框外的doctests。 這意味着你將需要手動

2)文檔測試

它本質上是一個獨立的框架,雖然它有一些膠粘類文檔測試轉換成單元測試樣的TestCase粘合在一起他們。 https://docs.python.org/2.7/library/doctest.html#doctest.DocTestSuite

3)發現

沒得到什麼discover你的意思,我想這是

python -m unittest discover 

如果不和你談論https://pypi.python.org/pypi/discover然後忘掉它 - 這是python早期版本的backport

4)怎麼辦

要麼撒了很多load_tests鉤在您的代碼如下描述https://docs.python.org/2.7/library/doctest.html#unittest-api或代碼的方法來收集所有擁有的這些模塊在同一個地方,並將其轉換成DocTestSuite [S] https://docs.python.org/2.7/library/doctest.html#doctest.DocTestSuite

但說實話這兩種方法時下,使任何意義,因爲它歸結爲:

$ py.test --doctest-modules 

$ nosetests --with-doctest 

當然coverage和大量的鐘聲&口哨也由這些框架提供,你可能會堅持單元測試。TestCase,你甚至不需要創建一個coverage_module所以我會深入其中的一個,而不是試圖想出你自己的解決方案

相關問題