Skip to content

Tracker

provide.testkit.quality.coverage.tracker

Coverage tracking implementation.

Classes

CoverageTracker

CoverageTracker(config: dict[str, Any] | None = None)

Wrapper for coverage.py library with testkit integration.

Provides high-level interface for coverage tracking with automatic artifact management and integration with the quality framework.

Initialize coverage tracker.

Parameters:

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

Coverage configuration options

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

    Args:
        config: Coverage configuration options
    """
    if not COVERAGE_AVAILABLE:
        raise QualityToolError(
            "Coverage.py not available. Install with: pip install coverage", tool="coverage"
        )

    self.config = config or {}
    self.coverage: Coverage | None = None
    self.is_running = False
    self.artifact_dir: Path | None = None
Functions
analyze
analyze(path: Path, **kwargs: Any) -> QualityResult

Run coverage analysis on the given path.

Parameters:

Name Type Description Default
path Path

Path to analyze

required
**kwargs Any

Additional options including artifact_dir

{}

Returns:

Type Description
QualityResult

QualityResult with coverage data

Source code in provide/testkit/quality/coverage/tracker.py
def analyze(self, path: Path, **kwargs: Any) -> QualityResult:
    """Run coverage analysis on the given path.

    Args:
        path: Path to analyze
        **kwargs: Additional options including artifact_dir

    Returns:
        QualityResult with coverage data
    """
    self.artifact_dir = kwargs.get("artifact_dir", Path(".coverage"))
    start_time = time.time()

    try:
        # If coverage is already running, get current data
        if self.is_running and self.coverage:
            self.stop()

        # Start fresh coverage analysis
        self.start()

        # For analysis mode, we need to combine existing coverage data
        # This is typically used when coverage was collected during test runs
        self._load_existing_data()

        # Generate report
        result = self._create_result()
        result.execution_time = time.time() - start_time

        # Generate artifacts
        self._generate_artifacts(result)

        return result

    except Exception as e:
        return QualityResult(
            tool="coverage",
            passed=False,
            details={"error": str(e), "error_type": type(e).__name__},
            execution_time=time.time() - start_time,
        )
generate_report
generate_report(format: str = 'terminal') -> str

Generate coverage report.

Parameters:

Name Type Description Default
format str

Report format (terminal, html, xml, json)

'terminal'

Returns:

Type Description
str

Report content (for terminal/json) or path (for html/xml)

Source code in provide/testkit/quality/coverage/tracker.py
def generate_report(self, format: str = "terminal") -> str:
    """Generate coverage report.

    Args:
        format: Report format (terminal, html, xml, json)

    Returns:
        Report content (for terminal/json) or path (for html/xml)
    """
    if not self.coverage:
        return "No coverage data available"

    if format == "terminal":
        return self._generate_terminal_report()
    elif format == "html" and self.artifact_dir:
        html_dir = self.artifact_dir / "htmlcov"
        self.coverage.html_report(directory=str(html_dir))
        return str(html_dir / "index.html")
    elif format == "xml" and self.artifact_dir:
        xml_file = self.artifact_dir / "coverage.xml"
        self.coverage.xml_report(outfile=str(xml_file))
        return str(xml_file)
    elif format == "json" and self.artifact_dir:
        json_file = self.artifact_dir / "coverage.json"
        self.coverage.json_report(outfile=str(json_file))
        return json_file.read_text()
    else:
        return f"Unsupported format: {format}"
get_coverage
get_coverage() -> float

Get current coverage percentage.

Returns:

Type Description
float

Coverage percentage (0-100)

Source code in provide/testkit/quality/coverage/tracker.py
def get_coverage(self) -> float:
    """Get current coverage percentage.

    Returns:
        Coverage percentage (0-100)
    """
    if not self.coverage:
        return 0.0

    try:
        # Get coverage data
        total = self.coverage.report(file=None, show_missing=False)
        return round(total, 2)
    except Exception:
        return 0.0
report
report(
    result: QualityResult, format: str = "terminal"
) -> str

Generate report from QualityResult (implements QualityTool protocol).

Parameters:

Name Type Description Default
result QualityResult

Coverage result

required
format str

Report format

'terminal'

Returns:

Type Description
str

Formatted report

Source code in provide/testkit/quality/coverage/tracker.py
def report(self, result: QualityResult, format: str = "terminal") -> str:
    """Generate report from QualityResult (implements QualityTool protocol).

    Args:
        result: Coverage result
        format: Report format

    Returns:
        Formatted report
    """
    if format == "terminal":
        lines = [
            f"Coverage Report - {result.tool}",
            "=" * 40,
        ]

        if result.score is not None:
            lines.append(f"Coverage: {result.score}%")

        if "total_statements" in result.details:
            details = result.details
            lines.extend(
                [
                    f"Total Statements: {details.get('total_statements', 0)}",
                    f"Missing Statements: {details.get('missing_statements', 0)}",
                    f"Branch Coverage: {details.get('branch_coverage', 'N/A')}%",
                ]
            )

        return "\n".join(lines)

    return str(result.details)
start
start() -> None

Start coverage tracking.

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

    coverage_config = self._build_coverage_config()
    self.coverage = Coverage(**coverage_config)
    self.coverage.start()
    self.is_running = True
stop
stop() -> None

Stop coverage tracking and save data.

Source code in provide/testkit/quality/coverage/tracker.py
def stop(self) -> None:
    """Stop coverage tracking and save data."""
    if not self.is_running or not self.coverage:
        return

    self.coverage.stop()
    self.coverage.save()
    self.is_running = False