简体   繁体   English

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

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

I have the following directory structure:我有以下目录结构:

./
    src/
    tests/
        unit/
        integration/

I would like to use pytest to run all of the tests in both unit/ and integration/ , but I would only like coverage.py to calculate coverage for the src/ directory when running the unit/ tests (not when running integration/ tests).我想使用 pytest 在unit/integration/运行所有测试,但我只想在运行unit/测试时(而不是在运行integration/测试时)使用coverage.py来计算src/目录的覆盖率.

The command I'm using now (calculates coverage for all tests under tests/ ):我现在使用的命令(计算tests/下所有测试的覆盖率):

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

with a setup.cfg file:使用 setup.cfg 文件:

[tool:pytest]
testpaths = tests

[coverage:run]
branch = True

I understand that I could add the @pytest.mark.no_cover decorator to each test function in the integration tests, but I would prefer to mark the whole directory rather than to decorate a large number of functions.我知道我可以在集成测试中为每个测试函数添加@pytest.mark.no_cover装饰器,但我更愿意标记整个目录而不是装饰大量函数。

You can attach markers dynamically.您可以动态附加标记。 The below example does that in the custom impl of the pytest_collection_modifyitems hook.下面的示例在pytest_collection_modifyitems挂钩的自定义实现中执行此pytest_collection_modifyitems Put the code in a conftest.py in the project root dir:将代码放在项目根目录的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)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM