在 coverage.py 中启用分支覆盖时如何计算覆盖百分比

How is coverage percentage calculated when branch coverage is enabled in coverage.py

我正在使用 coverage.py 工具来覆盖 python 代码。如果我使用不带 --branch 标志的命令,如下所示,

coverage run test_cmd

我得到这样的覆盖率报告,

Name                                                                              Stmts   Miss  Cover
--------------------------------------------------------------------------------------------------------------------------
/path/file.py                                                                      9      2    78%

由此我了解到覆盖百分比值是这样得出的

cover = (Stmts Covered/total stmts)*100 = (9-2/9)*100 = 77.77%

但是当我 运行 像这样启用 --branch 标志时

coverage run --branch test_cmd

我得到这样的覆盖率报告,

Name                                                                           Stmts   Miss Branch BrPart  Cover
----------------------------------------------------------------------------------------------------------------------------------------
/path/file.py                                                                    9      2      2      1    73%

从这份报告中我无法理解用于计算 Cover=73% 的公式

这个数字是怎么来的?这个代码覆盖率值是否正确?

虽然您可能不必太担心确切的数字,但它们的计算方式如下:

从您提供的输出中读取,我们有:

n_statements = 9
n_missing = 2
n_branches = 2
n_missing_branches = 1

然后计算(我稍微简化了语法,在实际代码中,所有内容都隐藏在属性后面。)

https://github.com/nedbat/coveragepy/blob/a9d582a47b41068d2a08ecf6c46bb10218cb5eec/coverage/results.py#L205-L207

n_executed = n_statements - n_missing

https://github.com/nedbat/coveragepy/blob/8a5049e0fe6b717396f2af14b38d67555f9c51ba/coverage/results.py#L210-L212

n_executed_branches = n_branches - n_missing_branches

https://github.com/nedbat/coveragepy/blob/8a5049e0fe6b717396f2af14b38d67555f9c51ba/coverage/results.py#L259-L263

numerator = n_executed + n_executed_branches
denominator = n_statements + n_branches

https://github.com/nedbat/coveragepy/blob/master/coverage/results.py#L215-L222

pc_covered = (100.0 * numerator) / denominator

现在将所有这些放在一个脚本中,添加 print(pc_covered) 和 运行 它:

72.72727272727273

当然是rounded,所以你有你的73%