首页 > 解决方案 > pytest-cov - 不计算集成测试目录的覆盖率

问题描述

我有以下目录结构:

./
    src/
    tests/
        unit/
        integration/

我想使用 pytest 在unit/和中运行所有测试,但我只想在运行测试时(而不是在运行测试时)计算目录的integration/覆盖率。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在集成测试中为每个测试函数添加装饰器,但我更愿意标记整个目录而不是装饰大量函数。

标签: pythonunit-testingpytestcoverage.py

解决方案


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

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)

推荐阅读