python 測試代碼覆蓋率- coverage

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
最后編輯于
?著作權(quán)歸作者所有,轉(zhuǎn)載或內(nèi)容合作請聯(lián)系作者
【社區(qū)內(nèi)容提示】社區(qū)部分內(nèi)容疑似由AI輔助生成,瀏覽時請結(jié)合常識與多方信息審慎甄別。
平臺聲明:文章內(nèi)容(如有圖片或視頻亦包括在內(nèi))由作者上傳并發(fā)布,文章內(nèi)容僅代表作者本人觀點,簡書系信息發(fā)布平臺,僅提供信息存儲服務(wù)。

相關(guān)閱讀更多精彩內(nèi)容

友情鏈接更多精彩內(nèi)容