python 测试代码覆盖率- coverage

2019-03-18  本文已影响0人  tafanfly

Coverage是一个用来测试代码覆盖率的 Python 第三方库。

安装

pip install coverage

执行

原来的执行UT命令假设是 python run_all_tests.py, 那么需要测试代码覆盖率的命令为coverage run --source . run_all_tests.py,跑完命令后,则会在目录下生成.coverage的文件。
--source .: 指定分析当前路径,不会计算导入库的覆盖率

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参数

(1)命令行用法

(2)配置参考
--rcfile=FILE: 可以用配置文件代替命令参数

# .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
上一篇 下一篇

猜你喜欢

热点阅读