164 lines
7.0 KiB
Python
164 lines
7.0 KiB
Python
"""Automated Test Runner and Coverage Reporter for Iterations 01 & 02.
|
|
|
|
Measures AST statement coverage across backend modules (auth, rbac, session, tenancy, RLS, audit, mock)
|
|
and validates adherence to UP-AI v1.5 coverage budgets (≥95% domain FSM, ≥90% adapter).
|
|
"""
|
|
import ast
|
|
import sys
|
|
import unittest
|
|
import trace
|
|
from pathlib import Path
|
|
|
|
# Add paths
|
|
repo_root = Path(__file__).resolve().parents[2]
|
|
workspace = Path(__file__).resolve().parents[1]
|
|
if str(repo_root) not in sys.path:
|
|
sys.path.insert(0, str(repo_root))
|
|
if str(workspace) not in sys.path:
|
|
sys.path.insert(0, str(workspace))
|
|
|
|
|
|
def get_executable_ast_statements(file_path: Path):
|
|
"""Parses Python file AST and returns set of line numbers containing executable statements.
|
|
|
|
Explicitly excludes docstrings (which are not executable bytecode statements).
|
|
"""
|
|
with open(file_path, "r", encoding="utf-8") as f:
|
|
tree = ast.parse(f.read())
|
|
docstring_lines = set()
|
|
for node in ast.walk(tree):
|
|
if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.ClassDef, ast.Module)):
|
|
if (node.body and isinstance(node.body[0], ast.Expr) and
|
|
isinstance(node.body[0].value, ast.Constant) and
|
|
isinstance(node.body[0].value.value, str)):
|
|
docstring_lines.add(node.body[0].lineno)
|
|
stmt_lines = {node.lineno for node in ast.walk(tree) if isinstance(node, ast.stmt)}
|
|
return stmt_lines - docstring_lines
|
|
|
|
|
|
def run_tests_with_coverage():
|
|
# Purge target modules from sys.modules so import execution is traced
|
|
for mod in list(sys.modules.keys()):
|
|
if mod.startswith("backend") or mod.startswith("sandbox"):
|
|
sys.modules.pop(mod, None)
|
|
|
|
tracer = trace.Trace(
|
|
count=1,
|
|
trace=0,
|
|
ignoredirs=[sys.prefix, sys.exec_prefix]
|
|
)
|
|
|
|
def run_suite():
|
|
loader = unittest.TestLoader()
|
|
start_dir = str(workspace / "tests" / "backend")
|
|
suite = loader.discover(start_dir, pattern="test_*.py")
|
|
runner = unittest.TextTestRunner(verbosity=1)
|
|
return runner.run(suite)
|
|
|
|
result = tracer.runfunc(run_suite)
|
|
|
|
# Calculate coverage for target modules across Iteration 01 and Iteration 02
|
|
target_files = [
|
|
# Iteration 01 Modules
|
|
workspace / "backend" / "app" / "auth" / "rbac.py",
|
|
workspace / "backend" / "app" / "auth" / "session.py",
|
|
workspace / "backend" / "app" / "auth" / "oidc.py",
|
|
workspace / "backend" / "app" / "api" / "auth.py",
|
|
# Iteration 02 Modules
|
|
workspace / "backend" / "app" / "models" / "tenant.py",
|
|
workspace / "backend" / "app" / "db" / "session.py",
|
|
workspace / "backend" / "app" / "auth" / "tenant_context.py",
|
|
workspace / "backend" / "app" / "api" / "tenants.py",
|
|
# Iteration 03 Modules
|
|
workspace / "backend" / "app" / "models" / "market.py",
|
|
workspace / "backend" / "app" / "api" / "market.py",
|
|
workspace / "backend" / "app" / "models" / "procurement.py",
|
|
workspace / "backend" / "app" / "api" / "procurement.py",
|
|
workspace / "backend" / "app" / "models" / "receiving.py",
|
|
workspace / "backend" / "app" / "api" / "receiving.py",
|
|
workspace / "backend" / "app" / "models" / "quality.py",
|
|
workspace / "backend" / "app" / "api" / "quality.py",
|
|
# Iteration 04 Modules
|
|
workspace / "backend" / "app" / "models" / "inventory.py",
|
|
workspace / "backend" / "app" / "api" / "inventory.py",
|
|
workspace / "backend" / "app" / "models" / "sales.py",
|
|
workspace / "backend" / "app" / "api" / "sales.py",
|
|
workspace / "backend" / "app" / "models" / "logistics.py",
|
|
workspace / "backend" / "app" / "api" / "logistics.py",
|
|
# Iteration 05 Modules
|
|
workspace / "backend" / "app" / "models" / "finance.py",
|
|
workspace / "backend" / "app" / "api" / "finance.py",
|
|
# Iteration 06 Modules
|
|
workspace / "backend" / "app" / "models" / "reporting.py",
|
|
workspace / "backend" / "app" / "api" / "alerts.py",
|
|
workspace / "backend" / "app" / "api" / "reporting.py",
|
|
workspace / "backend" / "app" / "api" / "analytics.py",
|
|
# Iteration 07 Modules
|
|
workspace / "backend" / "app" / "models" / "master_data.py",
|
|
workspace / "backend" / "app" / "api" / "master_data.py",
|
|
workspace / "backend" / "app" / "models" / "support.py",
|
|
workspace / "backend" / "app" / "api" / "support.py",
|
|
workspace / "backend" / "app" / "models" / "policy.py",
|
|
workspace / "backend" / "app" / "api" / "policies.py",
|
|
# Phase 2 Expansion Modules
|
|
workspace / "backend" / "app" / "models" / "bardana.py",
|
|
workspace / "backend" / "app" / "api" / "bardana.py",
|
|
workspace / "backend" / "app" / "models" / "mandi_compliance.py",
|
|
workspace / "backend" / "app" / "api" / "mandi_compliance.py",
|
|
workspace / "backend" / "app" / "models" / "processing.py",
|
|
workspace / "backend" / "app" / "api" / "processing.py",
|
|
workspace / "backend" / "app" / "models" / "farmer_settlement.py",
|
|
workspace / "backend" / "app" / "api" / "farmer_settlement.py",
|
|
# Sandboxes
|
|
|
|
workspace / "sandbox" / "identity_mock.py",
|
|
workspace / "sandbox" / "master_data_mock.py",
|
|
workspace / "sandbox" / "weighbridge_mock.py",
|
|
workspace / "sandbox" / "warehouse_mock.py",
|
|
workspace / "sandbox" / "customer_credit_mock.py",
|
|
workspace / "sandbox" / "fleet_mock.py",
|
|
workspace / "sandbox" / "payment_mock.py",
|
|
workspace / "sandbox" / "notification_mock.py",
|
|
]
|
|
|
|
print("\n" + "=" * 68)
|
|
print("STATEMENT COVERAGE REPORT — ITERATION 01, 02, 03, 04, 05, 06 & 07 (UP-AI v1.5)")
|
|
print("=" * 68)
|
|
|
|
|
|
results = tracer.results()
|
|
total_exec = 0
|
|
total_stmts = 0
|
|
|
|
for tf in target_files:
|
|
if not tf.exists():
|
|
continue
|
|
rel_path = tf.relative_to(repo_root)
|
|
stmt_lines = get_executable_ast_statements(tf)
|
|
|
|
hits = {line for (fn, line), count in results.counts.items() if Path(fn).resolve() == tf.resolve()}
|
|
executed_stmts = stmt_lines.intersection(hits)
|
|
coverage_pct = (len(executed_stmts) / len(stmt_lines) * 100) if stmt_lines else 100.0
|
|
|
|
total_exec += len(executed_stmts)
|
|
total_stmts += len(stmt_lines)
|
|
|
|
print(f" {str(rel_path):<48} {len(executed_stmts):>3}/{len(stmt_lines):<3} ({coverage_pct:5.1f}%)")
|
|
|
|
overall_pct = (total_exec / total_stmts * 100) if total_stmts else 100.0
|
|
print("-" * 68)
|
|
print(f" TOTAL DOMAIN & CONTROLLER COVERAGE: {total_exec:>3}/{total_stmts:<3} ({overall_pct:5.1f}%)")
|
|
print("=" * 68)
|
|
|
|
threshold = 95.0
|
|
if overall_pct >= threshold:
|
|
print(f"✅ PASS: Code coverage {overall_pct:.1f}% satisfies UP-AI v1.5 target (≥{threshold}%).")
|
|
else:
|
|
print(f"⚠️ NOTE: Code coverage {overall_pct:.1f}% (target: {threshold}%).")
|
|
|
|
return 0 if result.wasSuccessful() and overall_pct >= threshold else 1
|
|
|
|
|
|
if __name__ == "__main__":
|
|
sys.exit(run_tests_with_coverage())
|