2012-03-28 50 views

回答

0

這是一個簡單的解決方案,它使用coverage可執行文件的子進程調用。我假設你有一個名爲mycoolpackage的Python包,其中包含你想測量測試覆蓋的代碼,並且你有一個mytests包,它揭示了返回測試套件的suite函數。

首先,創建一個run-tests.py文件:

import os.path, sys 
sys.path.insert(0, os.path.abspath(os.path.dirname(__file__))) 

import unittest 
from mytests import suite 

unittest.main(defaultTest='suite')  

然後在setup.py創建下面的命令,並將其添加到setup()功能的cmdclass說法。

class run_coverage(Command): 
    description = "Generate a test coverage report." 
    user_options = []  
    def initialize_options(self): pass 
    def finalize_options(self): pass 
    def run(self): 
     import subprocess 
     subprocess.call(['coverage', 'run', '--source=mycoolpackage', 'run-tests.py']) 
     subprocess.call(['coverage', 'html']) 

注意coverage.py確實有一個API,它可以讓你做到這一點,而無需使用一個子進程調用。

+0

如果您使用setuptools的內部testrunner,那麼添加coverage命令只會非常有用。有了這個,你只需運行coverage命令即可。 – 2013-01-31 15:15:29