Coverage是一個用來測試代碼覆蓋率的 Python 第三方庫。
安裝
pip install coverage
執(zhí)行
原來的執(zhí)行UT命令假設(shè)是 python run_all_tests.py, 那么需要測試代碼覆蓋率的命令為coverage run --source . run_all_tests.py,跑完命令后,則會在目錄下生成.coverage的文件。
--source .: 指定分析當(dāng)前路徑,不會計算導(dǎo)入庫的覆蓋率
-
coverage report -m
執(zhí)行上述命令,則會在終端上打印以下信息。
Name Stmts Miss Cover Missing
---------------------------------------------------
demo.py 6 1 83% 11
test_demo_class.py 22 3 86% 38-39, 44
test_demo_module.py 37 14 62% 17-18, 20-22, 24, 26, 28, 30, 35-36, 41-48
---------------------------------------------------
TOTAL 65 18 72%
-
coverage html
運行該命令會生成htmlcov的文件夾, 找到index.html文件并用瀏覽器打開,可以看到以下覆蓋率結(jié)果。
index.html
找到demo_py.html文件并用瀏覽器打開,可以看到函數(shù)被測試的結(jié)果。
demo_py.html
更多coverage參數(shù)
(1)命令行用法
- run – 運行Python程序并且收集執(zhí)行數(shù)據(jù)
- report – 報告覆蓋率結(jié)果
- html – 生成覆蓋率結(jié)果的HTML列表且?guī)ё⑨?/li>
- xml – 生成一份覆蓋率結(jié)果的XML報告
- annotate – 使用覆蓋結(jié)果注釋源文件
- erase – 擦除以前收集的覆蓋率數(shù)據(jù)
- combine – 將許多數(shù)據(jù)文件組合在一起
- debug – 獲取診斷信息
(2)配置參考
--rcfile=FILE: 可以用配置文件代替命令參數(shù)
# .coveragerc to control coverage.py
[run]
branch = True
[report]
# Regexes for lines to exclude from consideration
exclude_lines =
# Have to re-enable the standard pragma
pragma: no cover
# Don't complain about missing debug-only code:
def __repr__
if self\.debug
# Don't complain if tests don't hit defensive assertion code:
raise AssertionError
raise NotImplementedError
# Don't complain if non-runnable code isn't run:
if 0:
if __name__ == .__main__.:
ignore_errors = True
[html]
directory = coverage_html_report
(3)指定源文件
--source: 指定分析的路徑,不會分析引用其他庫的覆蓋
--include:指定分析文件或者文件夾,可使用*或者?匹配。
--omit:指定不分析文件或者文件夾,可使用*或者?匹配。
# omit anything in a .local directory anywhere
*/.local/*
# omit everything in /usr
/usr/*
# omit this single file
utils/tirefire.py

