Skip to content

Fixture

provide.testkit.quality.coverage.fixture

Pytest fixtures for coverage tracking.

Classes

CoverageFixture

CoverageFixture(
    config: dict[str, Any] | None = None,
    artifact_dir: Path | None = None,
)

Bases: BaseQualityFixture

Pytest fixture for coverage tracking integration.

Initialize coverage fixture.

Parameters:

Name Type Description Default
config dict[str, Any] | None

Coverage configuration

None
artifact_dir Path | None

Directory for artifacts

None
Source code in provide/testkit/quality/coverage/fixture.py
def __init__(self, config: dict[str, Any] | None = None, artifact_dir: Path | None = None) -> None:
    """Initialize coverage fixture.

    Args:
        config: Coverage configuration
        artifact_dir: Directory for artifacts
    """
    super().__init__(config, artifact_dir)
    self.tracker: CoverageTracker | None = None
Functions
generate_report
generate_report(format: str = 'terminal') -> str

Generate coverage report.

Source code in provide/testkit/quality/coverage/fixture.py
def generate_report(self, format: str = "terminal") -> str:
    """Generate coverage report."""
    if not self.tracker:
        return "No coverage data"
    return self.tracker.generate_report(format)
get_coverage
get_coverage() -> float

Get current coverage percentage.

Source code in provide/testkit/quality/coverage/fixture.py
def get_coverage(self) -> float:
    """Get current coverage percentage."""
    if not self.tracker:
        return 0.0
    return self.tracker.get_coverage()
setup
setup() -> None

Setup coverage tracking.

Source code in provide/testkit/quality/coverage/fixture.py
def setup(self) -> None:
    """Setup coverage tracking."""
    if not COVERAGE_AVAILABLE:
        pytest.skip("Coverage.py not available")

    try:
        self.tracker = CoverageTracker(self.config)
    except Exception as e:
        pytest.skip(f"Failed to initialize coverage: {e}")
start_tracking
start_tracking() -> None

Start coverage tracking.

Source code in provide/testkit/quality/coverage/fixture.py
def start_tracking(self) -> None:
    """Start coverage tracking."""
    self.ensure_setup()
    if self.tracker:
        self.tracker.start()
stop_tracking
stop_tracking() -> None

Stop coverage tracking.

Source code in provide/testkit/quality/coverage/fixture.py
def stop_tracking(self) -> None:
    """Stop coverage tracking."""
    if self.tracker:
        self.tracker.stop()
teardown
teardown() -> None

Stop coverage and generate reports.

Source code in provide/testkit/quality/coverage/fixture.py
def teardown(self) -> None:
    """Stop coverage and generate reports."""
    if self.tracker and self.tracker.is_running:
        self.tracker.stop()

Functions

auto_coverage

auto_coverage(
    coverage_tracker: CoverageFixture,
) -> Generator[CoverageFixture, None, None]

Automatic coverage tracking fixture.

Automatically starts coverage at the beginning of the test and stops at the end. Ideal for tests that want zero-configuration coverage.

Usage

def test_automatic_coverage(auto_coverage): # Coverage automatically tracked result = some_function() assert result is not None # Coverage automatically stopped and saved

Source code in provide/testkit/quality/coverage/fixture.py
@pytest.fixture
def auto_coverage(coverage_tracker: CoverageFixture) -> Generator[CoverageFixture, None, None]:
    """Automatic coverage tracking fixture.

    Automatically starts coverage at the beginning of the test and stops
    at the end. Ideal for tests that want zero-configuration coverage.

    Usage:
        def test_automatic_coverage(auto_coverage):
            # Coverage automatically tracked
            result = some_function()
            assert result is not None
            # Coverage automatically stopped and saved
    """
    coverage_tracker.start_tracking()
    try:
        yield coverage_tracker
    finally:
        coverage_tracker.stop_tracking()

auto_coverage_marker

auto_coverage_marker(
    request: FixtureRequest,
) -> Generator[None, None, None]

Automatically apply coverage to marked tests.

Tests marked with @pytest.mark.coverage will automatically get coverage tracking without needing to explicitly use fixtures.

Source code in provide/testkit/quality/coverage/fixture.py
@pytest.fixture(autouse=True)
def auto_coverage_marker(request: FixtureRequest) -> Generator[None, None, None]:
    """Automatically apply coverage to marked tests.

    Tests marked with @pytest.mark.coverage will automatically
    get coverage tracking without needing to explicitly use fixtures.
    """
    if request.node.get_closest_marker("coverage"):
        # Test is marked for coverage - enable automatic tracking
        if not request.node.get_closest_marker("no_coverage"):
            # Create temporary coverage fixture
            coverage_fixture = CoverageFixture()
            try:
                coverage_fixture.setup()
                coverage_fixture.start_tracking()
                yield
            finally:
                coverage_fixture.stop_tracking()
                coverage_fixture.teardown()
        else:
            yield
    else:
        yield
        yield

coverage_config

coverage_config() -> dict[str, Any]

Default coverage configuration fixture.

Returns standard coverage configuration that can be customized per test or project.

Usage

def test_with_custom_coverage(coverage_config): coverage_config["fail_under"] = 95 # Use with parametrized coverage_tracker

Source code in provide/testkit/quality/coverage/fixture.py
@pytest.fixture
def coverage_config() -> dict[str, Any]:
    """Default coverage configuration fixture.

    Returns standard coverage configuration that can be customized
    per test or project.

    Usage:
        def test_with_custom_coverage(coverage_config):
            coverage_config["fail_under"] = 95
            # Use with parametrized coverage_tracker
    """
    return {
        "branch": True,
        "source": ["src"],
        "omit": [
            "*/tests/*",
            "*/test_*",
            "*/.venv/*",
            "*/venv/*",
        ],
        "fail_under": 80,
        "show_missing": True,
        "skip_covered": False,
    }

coverage_tracker

coverage_tracker(
    request: FixtureRequest, tmp_path: Path
) -> Generator[CoverageFixture, None, None]

Pytest fixture for coverage tracking.

Provides a CoverageFixture instance that automatically starts and stops coverage tracking around individual tests.

Usage

def test_with_coverage(coverage_tracker): coverage_tracker.start_tracking() # ... test code coverage_tracker.stop_tracking() assert coverage_tracker.get_coverage() > 80

Source code in provide/testkit/quality/coverage/fixture.py
@pytest.fixture
def coverage_tracker(
    request: FixtureRequest,
    tmp_path: Path,
) -> Generator[CoverageFixture, None, None]:
    """Pytest fixture for coverage tracking.

    Provides a CoverageFixture instance that automatically starts and stops
    coverage tracking around individual tests.

    Usage:
        def test_with_coverage(coverage_tracker):
            coverage_tracker.start_tracking()
            # ... test code
            coverage_tracker.stop_tracking()
            assert coverage_tracker.get_coverage() > 80
    """
    # Get configuration from pytest request
    config = getattr(request, "param", {})

    # Create artifact directory for this test
    artifact_dir = tmp_path / "coverage"

    # Initialize fixture
    fixture = CoverageFixture(config=config, artifact_dir=artifact_dir)

    try:
        fixture.setup()
        yield fixture
    finally:
        fixture.teardown()

parametrized_coverage

parametrized_coverage(
    request: FixtureRequest, tmp_path: Path
) -> Generator[CoverageFixture, None, None]

Parametrized coverage fixture for testing different configurations.

Automatically runs tests with different coverage configurations to validate behavior under various settings.

Usage

def test_coverage_configs(parametrized_coverage): # Test runs multiple times with different configs pass

Source code in provide/testkit/quality/coverage/fixture.py
@pytest.fixture(
    params=[
        {"fail_under": 80, "branch": True},
        {"fail_under": 90, "branch": False},
        {"fail_under": 95, "branch": True, "show_missing": True},
    ]
)
def parametrized_coverage(
    request: FixtureRequest,
    tmp_path: Path,
) -> Generator[CoverageFixture, None, None]:
    """Parametrized coverage fixture for testing different configurations.

    Automatically runs tests with different coverage configurations
    to validate behavior under various settings.

    Usage:
        def test_coverage_configs(parametrized_coverage):
            # Test runs multiple times with different configs
            pass
    """
    config = request.param
    artifact_dir = tmp_path / f"coverage_{id(config)}"

    fixture = CoverageFixture(config=config, artifact_dir=artifact_dir)

    try:
        fixture.setup()
        yield fixture
    finally:
        fixture.teardown()

pytest_configure

pytest_configure(config: Config) -> None

Configure pytest with coverage markers.

Source code in provide/testkit/quality/coverage/fixture.py
def pytest_configure(config: pytest.Config) -> None:
    """Configure pytest with coverage markers."""
    config.addinivalue_line("markers", "coverage: mark test to run with coverage tracking")
    config.addinivalue_line("markers", "no_coverage: mark test to skip coverage tracking")

session_coverage

session_coverage(
    tmp_path_factory: TempPathFactory,
) -> Generator[CoverageFixture, None, None]

Session-wide coverage tracking.

Tracks coverage across all tests in the session. Useful for getting overall coverage metrics for the entire test suite.

Usage

def test_part_one(session_coverage): # Coverage tracked across all tests pass

def test_part_two(session_coverage): # Same coverage instance pass

Source code in provide/testkit/quality/coverage/fixture.py
@pytest.fixture(scope="session")
def session_coverage(
    tmp_path_factory: TempPathFactory,
) -> Generator[CoverageFixture, None, None]:
    """Session-wide coverage tracking.

    Tracks coverage across all tests in the session. Useful for getting
    overall coverage metrics for the entire test suite.

    Usage:
        def test_part_one(session_coverage):
            # Coverage tracked across all tests
            pass

        def test_part_two(session_coverage):
            # Same coverage instance
            pass
    """
    # Create session-wide artifact directory
    artifact_dir = tmp_path_factory.mktemp("session_coverage")

    # Initialize session fixture
    fixture = CoverageFixture(artifact_dir=artifact_dir)

    try:
        fixture.setup()
        fixture.start_tracking()
        yield fixture
    finally:
        fixture.stop_tracking()
        fixture.teardown()