部分代码适用于Windows,部分代码适用于其他平台。我想通过适当放置
#pragma: no cover
来增加代码的覆盖范围。因此,当程序在Windows平台上运行时,与其他平台相关的代码应该被忽略,反之亦然。我怎样才能实现这个目标?
创建
.coveragerc
并定义报告生成期间跳行的规则:
[report]
exclude_lines =
pragma: no cover
更好的解决方案是根本不忽略这些线路,而是测量所有平台上的覆盖范围,然后将它们组合在一起。
您可以在“并行模式”下运行覆盖率,以便每个数据文件都有一个不同的名称,且parallel=true。然后将所有数据文件复制到一处,运行“覆盖率合并”,然后运行“覆盖率报告”。
如果您使用
tox
,就有一种解决方案。
首先,将以下内容添加到
tox.ini
:
# tox.ini
[tox]
envlist = py{36,37,38,39}-{linux,macos,windows}
[testenv]
platform = linux: linux
macos: darwin
windows: win32
setenv =
linux: PLATFORM = linux
macos: PLATFORM = macos
windows: PLATFORM = windows
[testenv:py{36,37,38,39}-{linux,macos,windows}]
setenv =
COVERAGE_RCFILE = {envtmpdir}/coveragerc
commands_pre =
{envpython} -c 'from pathlib import Path; Path(r"{env:COVERAGE_RCFILE}").write_text(Path(".coveragerc.in").read_text().format(platform="{env:PLATFORM}"))'
commands =
coverage run -m pytest -v
上面的代码片段使 tox 平台感知并创建一个由 Coverage.py 识别的coveragerc 文件。
然后,将以下内容添加到
.coveragerc.in
:
[coverage:report]
exclude_lines =
pragma: no cover {platform}
此行根据平台设置排除线。现在,用
# pragma: no cover windows
、# pragma: no cover linux
或 # pragma: no cover macos
标记您的代码行,以排除这些行在特定平台上的执行。
现在运行
tox -e py39-windows
(或其他 Python 版本和操作系统,例如 tox -e py38-linux
)将根据平台测量覆盖范围。
参考:https://www.topbug.net/blog/2020/12/19/platform-dependent-python-coverage-test-with-tox/
似乎您可以使用 coverage-conditional-plugin 轻松完成此操作。
pip install coverage-conditional-plugin
然后将该工具添加到 pyproject.toml 中(位于存储库的根目录):
[tool.coverage.run]
plugins = ["coverage_conditional_plugin"]
在配置“省略”部分中完成。在 pyproject.toml 中:
[tool.coverage.coverage_conditional_plugin.omit]
# Include some/windows_specific/*.py only on Windows
"platform_system != 'Windows'" = "some/windows_specific/*.py"
# Skip "some/not_for_windows/*.py" on Windows
"platform_system == 'Windows'" = "some/not_for_windows/*.py"
完成
# pragma some-comment
和配置。在 pyproject.toml 中:
[tool.coverage.coverage_conditional_plugin.rules]
no-cover-if-windows = "platform_system == 'Windows'"
no-cover-if-not-windows = "platform_system != 'Windows'"
然后在代码中:
if ON_WINDOWS: # pragma: no-cover-if-not-windows
do_something_only_on_windows()
else: # pragma: no-cover-if-windows
do_something_on_other_systems()