Skip to content

armgit / forma

Public Imported from GitHub
0

A 1.2 MB pure-Rust rewrite of headless Blender built for AI agents — 3D B-rep modeling engine, CLI, and MCP server

11.3 KB
Raw Blame
#!/usr/bin/env python3
"""Opaque-box 4-tier E2E test runner for forma-print."""

from __future__ import annotations

import argparse
import json
import pathlib
import re
import sys
import time
import traceback
from collections import Counter
from typing import Any

E2E_DIR = pathlib.Path(__file__).resolve().parent
if str(E2E_DIR) not in sys.path:
    sys.path.insert(0, str(E2E_DIR))

import helpers as h  # noqa: E402
import test_tier1_features  # noqa: E402
import test_tier2_boundaries  # noqa: E402
import test_tier3_cross_feature  # noqa: E402
import test_tier4_scenarios  # noqa: E402

FEATURE_IDS = [f"#{i}" for i in range(2, 21)]


def discover_all_tests() -> list[h.TestCase]:
    tests: list[h.TestCase] = []
    for mod in (
        test_tier1_features,
        test_tier2_boundaries,
        test_tier3_cross_feature,
        test_tier4_scenarios,
    ):
        tests.extend(h.collect_tests_from_module(mod))
    return tests


def run_dry_run_checks(all_tests: list[h.TestCase]) -> dict[str, Any]:
    errors: list[str] = []

    # 1. Duplicate ID & coverage threshold checks
    ids = [t.id for t in all_tests]
    dups = [k for k, v in Counter(ids).items() if v > 1]
    if dups:
        errors.append(f"Duplicate test IDs: {dups}")

    by_tier = Counter(t.tier for t in all_tests)
    if by_tier[1] < 95:
        errors.append(f"Tier 1 count {by_tier[1]} < 95")
    if by_tier[2] < 95:
        errors.append(f"Tier 2 count {by_tier[2]} < 95")
    if by_tier[3] < 19:
        errors.append(f"Tier 3 count {by_tier[3]} < 19")
    if by_tier[4] < 10:
        errors.append(f"Tier 4 count {by_tier[4]} < 10")

    for fid in FEATURE_IDS:
        t1_cnt = sum(1 for t in all_tests if t.tier == 1 and t.feature_id == fid)
        t2_cnt = sum(1 for t in all_tests if t.tier == 2 and t.feature_id == fid)
        if t1_cnt < 5:
            errors.append(f"Feature {fid} has {t1_cnt} < 5 Tier 1 tests")
        if t2_cnt < 5:
            errors.append(f"Feature {fid} has {t2_cnt} < 5 Tier 2 tests")

    # 2. Validate .forma fixtures via core forma eval --strict --json
    forma_results: dict[str, str] = {}
    forma_files = sorted(h.FIXTURES_DIR.glob("*.forma"))
    if not forma_files:
        errors.append("No .forma fixtures found in tests/e2e/fixtures/")
    for fpath in forma_files:
        expect_ok = fpath.name != "invalid_syntax.forma"
        try:
            h.verify_forma_fixture(fpath, expect_ok=expect_ok)
            forma_results[fpath.name] = "ok" if expect_ok else "expected_error_ok"
        except Exception as exc:
            errors.append(f"Forma fixture {fpath.name}: {exc}")
            forma_results[fpath.name] = f"ERROR: {exc}"

    # 3. Validate .stl fixtures
    stl_results: dict[str, str] = {}
    expected_stl_valid = {"cube_40mm.stl", "cube_ascii_25mm.stl", "non_manifold.stl"}
    expected_stl_corrupt = {"corrupt_truncated.stl", "empty.stl"}
    for stl_name in sorted(expected_stl_valid | expected_stl_corrupt):
        spath = h.FIXTURES_DIR / stl_name
        if not spath.is_file():
            errors.append(f"Missing STL fixture: {stl_name}")
            stl_results[stl_name] = "MISSING"
            continue
        if stl_name in expected_stl_valid:
            try:
                info = h.inspect_stl(spath)
                proc = h.run_forma(["eval", "--strict", "--json"], stdin_text=f'p = load("{spath}")\n')
                if stl_name == "non_manifold.stl":
                    if proc.returncode == 0:
                        errors.append("non_manifold.stl unexpectedly passed forma eval --strict")
                    stl_results[stl_name] = f"expected_non_manifold_ok (tris={info['triangles']})"
                else:
                    if proc.returncode != 0:
                        errors.append(f"{stl_name} failed forma eval --strict: {proc.stdout} {proc.stderr}")
                    stl_results[stl_name] = f"ok (tris={info['triangles']}, fmt={info['format']})"
            except Exception as exc:
                errors.append(f"STL fixture {stl_name}: {exc}")
                stl_results[stl_name] = f"ERROR: {exc}"
        else:
            try:
                h.inspect_stl(spath)
                errors.append(f"Corrupt/empty STL fixture {stl_name} unexpectedly parsed cleanly")
                stl_results[stl_name] = "ERROR: parsed"
            except ValueError:
                stl_results[stl_name] = "expected_invalid_ok"

    # 4. Zero-bloat Cargo.toml / package.json isolation check
    isolation: dict[str, Any] = {}
    try:
        toml_text = (h.REPO_ROOT / "Cargo.toml").read_text(encoding="utf-8")
        m = re.search(r"default-members\s*=\s*\[(.*?)\]", toml_text, flags=re.S)
        assert m and "forma-print" not in m.group(1), "forma-print in Cargo.toml default-members"
        pkg = json.loads((h.REPO_ROOT / "package.json").read_text(encoding="utf-8"))
        files = pkg.get("files", [])
        assert not any("research" in f or "forma-print" in f for f in files), f"package.json leak: {files}"
        isolation["ok"] = True
    except Exception as exc:
        isolation["ok"] = False
        isolation["error"] = str(exc)
        errors.append(f"Zero-bloat isolation check: {exc}")

    return {
        "mode": "dry-run",
        "ok": len(errors) == 0,
        "counts": {
            "total": len(all_tests),
            "tier_1": by_tier[1],
            "tier_2": by_tier[2],
            "tier_3": by_tier[3],
            "tier_4": by_tier[4],
        },
        "forma_fixtures": forma_results,
        "stl_fixtures": stl_results,
        "isolation": isolation,
        "errors": errors,
    }


def run_live_tests(
    selected: list[h.TestCase],
    *,
    allow_unbuilt: bool,
    verbose: bool,
    json_mode: bool,
) -> dict[str, Any]:
    results: list[dict[str, Any]] = []
    passed = 0
    failed = 0
    skipped = 0

    req_cache: dict[tuple[str, ...], tuple[bool, str]] = {}

    for tc in selected:
        t0 = time.monotonic()
        if tc.requires not in req_cache:
            req_cache[tc.requires] = h.check_requirements_available(tc.requires)
        avail, reason = req_cache[tc.requires]
        if not avail:
            skipped += 1
            entry = {
                "id": tc.id,
                "tier": tc.tier,
                "feature_id": tc.feature_id,
                "title": tc.title,
                "requires": list(tc.requires),
                "status": "SKIP_NOT_BUILT",
                "duration_ms": round((time.monotonic() - t0) * 1000.0, 2),
                "detail": reason,
            }
            results.append(entry)
            if not json_mode and verbose:
                print(f"[SKIP_NOT_BUILT] {tc.id} ({tc.feature_id}) {tc.title}: {reason}")
            continue

        try:
            tc.fn()
            passed += 1
            entry = {
                "id": tc.id,
                "tier": tc.tier,
                "feature_id": tc.feature_id,
                "title": tc.title,
                "requires": list(tc.requires),
                "status": "PASS",
                "duration_ms": round((time.monotonic() - t0) * 1000.0, 2),
                "detail": "",
            }
            results.append(entry)
            if not json_mode and verbose:
                print(f"[PASS] {tc.id} ({tc.feature_id}) {tc.title} ({entry['duration_ms']}ms)")
        except h.SkipNotBuilt as exc:
            skipped += 1
            entry = {
                "id": tc.id,
                "tier": tc.tier,
                "feature_id": tc.feature_id,
                "title": tc.title,
                "requires": list(tc.requires),
                "status": "SKIP_NOT_BUILT",
                "duration_ms": round((time.monotonic() - t0) * 1000.0, 2),
                "detail": str(exc),
            }
            results.append(entry)
            if not json_mode and verbose:
                print(f"[SKIP_NOT_BUILT] {tc.id} ({tc.feature_id}) {tc.title}: {exc}")
        except Exception as exc:
            failed += 1
            tb = traceback.format_exc()
            entry = {
                "id": tc.id,
                "tier": tc.tier,
                "feature_id": tc.feature_id,
                "title": tc.title,
                "requires": list(tc.requires),
                "status": "FAIL",
                "duration_ms": round((time.monotonic() - t0) * 1000.0, 2),
                "detail": f"{type(exc).__name__}: {exc}",
                "traceback": tb,
            }
            results.append(entry)
            if not json_mode:
                print(f"[FAIL] {tc.id} ({tc.feature_id}) {tc.title}: {exc}")
                if verbose:
                    print(tb)

    ok = (failed == 0) and (allow_unbuilt or skipped == 0)
    return {
        "mode": "live",
        "ok": ok,
        "allow_unbuilt": allow_unbuilt,
        "summary": {
            "total": len(selected),
            "passed": passed,
            "failed": failed,
            "skipped_not_built": skipped,
        },
        "results": results,
    }


def main(argv: list[str] | None = None) -> int:
    parser = argparse.ArgumentParser(description="Run forma-print 4-tier opaque-box E2E test suite.")
    parser.add_argument("--tier", choices=("1", "2", "3", "4", "all"), default="all", help="Select tier to run")
    parser.add_argument("--dry-run", action="store_true", help="Validate suite counts, fixtures, and zero-bloat isolation without running live tests")
    parser.add_argument("--allow-unbuilt", action="store_true", help="Exit 0 even if unbuilt artifacts cause SKIP_NOT_BUILT")
    parser.add_argument("--json", action="store_true", help="Emit JSON output")
    parser.add_argument("--filter", default="", help="Substring filter on test id, feature_id, or title")
    parser.add_argument("--verbose", action="store_true", help="Verbose per-test output")
    args = parser.parse_args(argv)

    all_tests = discover_all_tests()

    if args.dry_run:
        report = run_dry_run_checks(all_tests)
        if args.json:
            print(json.dumps(report, indent=2))
        else:
            c = report["counts"]
            print(
                f"DRY-RUN {'OK' if report['ok'] else 'FAILED'}: "
                f"total={c['total']} (T1={c['tier_1']}, T2={c['tier_2']}, T3={c['tier_3']}, T4={c['tier_4']}), "
                f"forma_fixtures={len(report['forma_fixtures'])}, stl_fixtures={len(report['stl_fixtures'])}"
            )
            if report["errors"]:
                for err in report["errors"]:
                    print(f"  ERROR: {err}")
        return 0 if report["ok"] else 1

    selected = all_tests
    if args.tier != "all":
        tnum = int(args.tier)
        selected = [t for t in selected if t.tier == tnum]
    if args.filter:
        needle = args.filter.lower()
        selected = [
            t
            for t in selected
            if needle in t.id.lower() or needle in t.feature_id.lower() or needle in t.title.lower()
        ]

    report = run_live_tests(
        selected,
        allow_unbuilt=args.allow_unbuilt,
        verbose=args.verbose,
        json_mode=args.json,
    )
    if args.json:
        print(json.dumps(report, indent=2))
    else:
        s = report["summary"]
        print(
            f"E2E {'PASS' if report['ok'] else 'INCOMPLETE/FAIL'}: "
            f"total={s['total']} passed={s['passed']} failed={s['failed']} skipped_not_built={s['skipped_not_built']}"
        )
    return 0 if report["ok"] else 1


if __name__ == "__main__":
    raise SystemExit(main())