pytest-cov - 不要计算集成测试目录的覆盖率

pytest-cov - Don't count coverage for the directory of integration tests

我的目录结构如下:

./
    src/
    tests/
        unit/
        integration/

我想使用 pytest 运行 unit/integration/ 中的所有测试,但我只想 coverage.py 计算覆盖率src/ 目录在 运行 宁 unit/ 测试时(不是 运行 宁 integration/ 测试时)。

我现在使用的命令(计算tests/下所有测试的覆盖率):

pytest --cov-config=setup.cfg --cov=src

带有 setup.cfg 文件:

[tool:pytest]
testpaths = tests

[coverage:run]
branch = True

我知道我可以在集成测试中为每个测试函数添加 @pytest.mark.no_cover 装饰器,但我更愿意标记整个目录而不是装饰大量函数。

您可以动态附加标记。下面的示例在 pytest_collection_modifyitems 挂钩的自定义实现中执行此操作。将代码放在项目根目录的 conftest.py 中:

from pathlib import Path
import pytest


def pytest_collection_modifyitems(items):
    no_cov = pytest.mark.no_cover
    for item in items:
        if "integration" in Path(item.fspath).parts:
            item.add_marker(no_cov)