Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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).

The command I'm using now (calculates coverage for all tests under tests/):

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

with a setup.cfg file:

[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.

like image 796
Jonathan Dayton Avatar asked Sep 13 '25 16:09

Jonathan Dayton


1 Answers

You can attach markers dynamically. The below example does that in the custom impl of the pytest_collection_modifyitems hook. Put the code in a conftest.py in the project root dir:

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)
like image 192
hoefling Avatar answered Sep 16 '25 07:09

hoefling