使用 py.test 和 coverage.py 覆盖 Cython 模块

Coverage of Cython module using py.test and coverage.py

我想使用 Python 中编写的一些(单元)测试来获取 Cython 模块的覆盖率信息。我现在拥有的是 测试本身 的覆盖范围,即测试的哪些行由 运行 py.test 执行。虽然看起来不错,但我宁愿覆盖 .pyx 文件,即我的测试覆盖了 C/Python 接口的哪些行。

我已经找到了一些信息,但无法为我的项目获取 运行:

http://blog.behnel.de/posts/coverage-analysis-for-cython-modules.html

https://medium.com/@dfdeshom/better-test-coverage-workflow-for-cython-modules-631615eb197a

How to use coverage analysis with Cython

这是有问题的代码:https://github.com/SCIP-Interfaces/PySCIPOpt/tree/coverage

这里的当前答案分为两部分:

  • pytest 配置
  • coverage.py配置

让我们从pytest配置开始。当前在您的 coverage 分支上有 .travis.yml 文件,其中包含以下行:py.test --cov tests,这告诉 pytest-cov 向您显示 tests 目录的覆盖范围,您不想。 你可以 运行 py.test tests --cov 或者改变你的 setup.cfg 并且根本不通过 tests

然后您将拥有 setup.cfg 文件:

[tool:pytest]
testpaths = 
    tests

.coverage文件中你需要:

[run]
plugins = Cython.Coverage
source = src/pyscipopt
omit =
    tests
    *__init__.py

单独指定 paths 已过时,我已将其删除。这样 coverage.py 知道它应该只检查 src/pyscipopt 目录的覆盖率。

进行这些更改后,我得到的输出是:

---------- coverage: platform darwin, python 3.6.4-final-0 -----------
Name                          Stmts   Miss Branch BrPart  Cover
---------------------------------------------------------------
src/pyscipopt/Multidict.py       17     17     10      0     0%
src/pyscipopt/conshdlr.pxi      301    129      0      0    57%
src/pyscipopt/expr.pxi          168     57      0      0    66%
src/pyscipopt/heuristic.pxi      44     18      0      0    59%
src/pyscipopt/lp.pxi            235    177      0      0    25%
src/pyscipopt/pricer.pxi         52     24      0      0    54%
---------------------------------------------------------------
TOTAL                           817    422     10      0    48%

这看起来是您想要的正确输出,但我确实看到缺少 scip.pyx 文件。你也可以看看related issue on github。我不会进一步调查,因为它回答了你的问题,我认为你可以从这里开始,无论遗漏什么。