#!/usr/bin/env python3 """Run an explicit-package extension repository's tests with real CLI inputs. Each case builds a throwaway consumer project whose `dependencies.` path points at a copy of this repository's package (`marqdo.yaml` + `index.mq.md`), runs `marqdo lock` once, then executes the migrated `.mq.md` test through the public `@alias` import. Inputs are explicit: `MARQDO_BIN` (verified CLI) and `MARQDO_STDLIB_DIR` (installed Bundle for the remaining `std:` imports, if any). Nothing reads a sibling repository or a floating branch. """ from __future__ import annotations import base64 import json import os import shutil import subprocess import sys import tempfile from pathlib import Path REPO = Path(__file__).resolve().parents[1] CASES = REPO / "tests" / "cases" SCHEMA = "marqdo.package-test-case" SCHEMA_VERSION = 1 class CaseError(Exception): pass def substitute(value, binary: str, package_root: Path): if isinstance(value, dict): if set(value) == {"$bin_version"}: return subprocess.run([binary, "--version"], capture_output=True, text=True).stdout if set(value) == {"$package_root"}: return str(package_root) return {k: substitute(v, binary, package_root) for k, v in value.items()} if isinstance(value, list): return [substitute(v, binary, package_root) for v in value] return value def channel_text(events, channel): parts = [] for event in events: if event.get("kind") != channel: continue payload = event["payload"] data = base64.b64decode(payload["data_base64"]) if len(data) != payload["byte_count"]: raise CaseError(f"{channel} byte_count mismatch") parts.append(data) return b"".join(parts).decode() def consumer_manifest(alias: str) -> str: return ( "project:\n" " name: package-test-consumer\n" " version: 0.0.0\n" ' marqdo: ">=3.0.0-beta.1,<4.0.0"\n' "dependencies:\n" f" {alias}:\n" f" path: ./deps/{alias}\n" ) def run_case(case: dict, binary: str, bundle: Path) -> None: name = case["name"] alias = case["dep_alias"] env = os.environ.copy() env["MARQDO_STDLIB_DIR"] = str(bundle) for key, value in case.get("env", {}).items(): env[key] = str(value).replace("$MARQDO_BIN", binary) source = REPO / "tests" / case["file"] if not source.is_file(): raise CaseError(f"{name}: missing test source {source}") with tempfile.TemporaryDirectory(prefix="mq-package-test-") as tmp: consumer = Path(tmp) / "consumer" package = consumer / "deps" / alias package.mkdir(parents=True) shutil.copy2(REPO / "marqdo.yaml", package / "marqdo.yaml") shutil.copy2(REPO / "index.mq.md", package / "index.mq.md") (consumer / "marqdo.yaml").write_text(consumer_manifest(alias)) (consumer / "tests").mkdir() shutil.copy2(source, consumer / "tests" / case["file"]) lock = subprocess.run([binary, "lock"], cwd=consumer, env=env, capture_output=True) if lock.returncode != 0: raise CaseError(f"{name}: marqdo lock failed: {lock.stderr.decode(errors='replace')}") args = [str(arg).replace("$MARQDO_BIN", binary) for arg in case.get("args", [])] result = subprocess.run( [binary, "run", str(consumer / "tests" / case["file"]), *args, "--output", "json"], cwd=consumer, env=env, input=case.get("stdin", "").encode(), capture_output=True, ) if result.returncode != 0: raise CaseError(f"{name}: CLI exited {result.returncode}:\n{result.stderr.decode(errors='replace')}") report = json.loads(result.stdout) if report.get("run", {}).get("status") != "ok": raise CaseError(f"{name}: run status not ok") terminal = report["events"][-1]["payload"] if terminal.get("status") != "ok": raise CaseError(f"{name}: terminal status not ok") expected = substitute(case["expected_terminal"], binary, REPO) if terminal.get("value") != expected: raise CaseError( f"{name}: terminal value changed\nexpected: " f"{json.dumps(expected, ensure_ascii=False, sort_keys=True)}\nactual: " f"{json.dumps(terminal.get('value'), ensure_ascii=False, sort_keys=True)}" ) stdout = channel_text(report["events"], "stdout.chunk") if stdout != case.get("expected_stdout", ""): raise CaseError(f"{name}: stdout changed: {stdout!r}") def main() -> int: binary = os.environ.get("MARQDO_BIN") bundle = os.environ.get("MARQDO_STDLIB_DIR") if not binary or not shutil.which(binary): print("MARQDO_BIN must point at a verified marqdo executable", file=sys.stderr) return 2 if not bundle or not Path(bundle).is_dir(): print("MARQDO_STDLIB_DIR must point at an installed Bundle", file=sys.stderr) return 2 bundle = Path(bundle).resolve() paths = sorted(CASES.glob("*.json")) if not paths: print("no test cases", file=sys.stderr) return 2 failures = 0 ran = 0 for path in paths: case = json.loads(path.read_text()) if case.get("schema") != SCHEMA or case.get("schema_version") != SCHEMA_VERSION: print(f"FAIL {path.name}: unsupported schema", file=sys.stderr) failures += 1 continue ran += 1 try: run_case(case, binary, bundle) print(f"PASS {case['name']}") except (CaseError, json.JSONDecodeError) as error: print(f"FAIL {error}", file=sys.stderr) failures += 1 if failures: print(f"{failures} of {ran} cases failed", file=sys.stderr) return 1 print(f"{ran} cases passed") return 0 if __name__ == "__main__": sys.exit(main())