Skip to content

Index

provide.testkit.quality.complexity

Complexity analysis integration for provide-testkit.

Provides code complexity analysis using radon and other complexity tools. Integrates with the quality framework for comprehensive complexity analysis.

Features: - Cyclomatic complexity analysis with radon - Maintainability index calculation - Raw metrics (lines of code, etc.) - Integration with quality gates - Grade-based reporting (A, B, C, D, F)

Usage

Basic complexity analysis

def test_with_complexity(complexity_analyzer): result = complexity_analyzer.analyze(path) assert result.passed

Complexity with quality gates

runner = QualityRunner() results = runner.run_with_gates(path, {"complexity": "B"})

Classes

ComplexityAnalyzer

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

Code complexity analyzer using radon and other tools.

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

Initialize complexity analyzer.

Parameters:

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

Complexity analyzer configuration options

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

    Args:
        config: Complexity analyzer configuration options
    """
    if not RADON_AVAILABLE:
        raise QualityToolError("Radon not available. Install with: pip install radon", tool="complexity")

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

Run complexity 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 complexity analysis data

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

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

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

    try:
        # Run radon complexity analysis
        result = self._run_radon_analysis(path)
        result.execution_time = time.time() - start_time

        # Generate artifacts
        self._generate_artifacts(result)

        return result

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

Generate report from QualityResult (implements QualityTool protocol).

Parameters:

Name Type Description Default
result QualityResult

Complexity result

required
format str

Report format

'terminal'

Returns:

Type Description
str

Formatted report

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

    Args:
        result: Complexity result
        format: Report format

    Returns:
        Formatted report
    """
    if format == "terminal":
        return self._generate_text_report(result)
    elif format == "json":
        return json.dumps(
            {
                "tool": result.tool,
                "passed": result.passed,
                "score": result.score,
                "details": result.details,
            },
            indent=2,
        )
    else:
        return str(result.details)

ComplexityFixture

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

Bases: BaseQualityFixture

Pytest fixture for complexity analysis integration.

Initialize complexity fixture.

Parameters:

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

Complexity analyzer configuration

None
artifact_dir Path | None

Directory for artifacts

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

    Args:
        config: Complexity analyzer configuration
        artifact_dir: Directory for artifacts
    """
    super().__init__(config, artifact_dir)
    self.analyzer: ComplexityAnalyzer | None = None
Functions
analyze
analyze(path: Path) -> dict[str, Any]

Perform complexity analysis.

Parameters:

Name Type Description Default
path Path

Path to analyze

required

Returns:

Type Description
dict[str, Any]

Complexity analysis results

Source code in provide/testkit/quality/complexity/fixture.py
def analyze(self, path: Path) -> dict[str, Any]:
    """Perform complexity analysis.

    Args:
        path: Path to analyze

    Returns:
        Complexity analysis results
    """
    self.ensure_setup()
    if not self.analyzer:
        return {"error": "Analyzer not available"}

    result = self.analyzer.analyze(path, artifact_dir=self.artifact_dir)
    self.add_result(result)
    return {
        "passed": result.passed,
        "score": result.score,
        "grade": result.details.get("overall_grade", "F"),
        "average_complexity": result.details.get("average_complexity", 0),
        "max_complexity": result.details.get("max_complexity", 0),
        "details": result.details,
    }
generate_report
generate_report(format: str = 'terminal') -> str

Generate complexity report.

Parameters:

Name Type Description Default
format str

Report format (terminal, json)

'terminal'

Returns:

Type Description
str

Formatted report

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

    Args:
        format: Report format (terminal, json)

    Returns:
        Formatted report
    """
    if not self.analyzer:
        return "No complexity analyzer available"

    results = self.get_results_by_tool()
    if "complexity" not in results:
        return "No complexity results available"

    return self.analyzer.report(results["complexity"], format)
setup
setup() -> None

Setup complexity analysis.

Source code in provide/testkit/quality/complexity/fixture.py
def setup(self) -> None:
    """Setup complexity analysis."""
    if not RADON_AVAILABLE:
        pytest.skip("Radon not available")

    try:
        self.analyzer = ComplexityAnalyzer(self.config)
    except Exception as e:
        pytest.skip(f"Failed to initialize complexity analyzer: {e}")
teardown
teardown() -> None

Cleanup complexity analyzer.

Source code in provide/testkit/quality/complexity/fixture.py
def teardown(self) -> None:
    """Cleanup complexity analyzer."""
    # No cleanup needed for complexity analyzer
    pass