Move the official stdlib system modules to their unique source authority without changing public std: paths or host authorization. Carry the pre-migration product assertions into component cases captured from the baseline Bundle; the process case resolves the granted program and expected stdout from the verified CLI. Refs cflmy/marqdo#9, cflmy/marqdo-std-system#1
208 lines
7.3 KiB
Python
Executable File
208 lines
7.3 KiB
Python
Executable File
#!/usr/bin/env python3
|
|
"""Run this component's public `.mq.md` self-tests against a real CLI Bundle.
|
|
|
|
Inputs are explicit and never discovered from sibling checkouts:
|
|
|
|
* ``MARQDO_BIN`` verified ``marqdo`` executable;
|
|
* ``MARQDO_STDLIB_DIR`` Bundle that already installs this component's modules at
|
|
their frozen bundle paths (the Bundle identity is the caller's responsibility;
|
|
the CLI itself verifies the manifest digest before loading a module).
|
|
|
|
Each ``tests/cases/*.json`` file pins one self-test: the source file, stdin, CLI
|
|
flags, environment, the expected bundle module path and the expected observation
|
|
terminal value / stdout. The expected values are the baseline captured from the
|
|
pre-migration CLI Bundle; a change is a public behaviour change and must be
|
|
reviewed as one.
|
|
|
|
Usage: scripts/test.sh [CASE_NAME...]
|
|
"""
|
|
|
|
from __future__ import annotations
|
|
|
|
import argparse
|
|
import base64
|
|
import json
|
|
import os
|
|
import shutil
|
|
import subprocess
|
|
import sys
|
|
from pathlib import Path
|
|
|
|
REPO = Path(__file__).resolve().parents[1]
|
|
CASES = REPO / "tests" / "cases"
|
|
SCHEMA = "marqdo.stdlib-test-case"
|
|
SCHEMA_VERSION = 1
|
|
|
|
|
|
class CaseError(Exception):
|
|
pass
|
|
|
|
|
|
def _substitute(value, bin_version: str):
|
|
if isinstance(value, dict):
|
|
if set(value) == {"$bin_version"}:
|
|
return bin_version
|
|
return {key: _substitute(item, bin_version) for key, item in value.items()}
|
|
if isinstance(value, list):
|
|
return [_substitute(item, bin_version) for item in value]
|
|
return value
|
|
|
|
|
|
def _channel_text(events: list[dict], channel: str) -> str:
|
|
chunks = []
|
|
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 does not match decoded bytes")
|
|
chunks.append(data)
|
|
return b"".join(chunks).decode("utf-8")
|
|
|
|
|
|
def _run_case(case: dict, case_path: Path, binary: str, bundle: Path) -> None:
|
|
name = case["name"]
|
|
module = case.get("require_module")
|
|
if module and not (bundle / module).is_file():
|
|
raise CaseError(f"{name}: Bundle {bundle} does not install {module}")
|
|
source = REPO / "tests" / case["file"]
|
|
if not source.is_file():
|
|
raise CaseError(f"{name}: missing test source {source}")
|
|
for relative in case.get("clean", []):
|
|
target = (REPO / relative).resolve()
|
|
if REPO not in target.parents:
|
|
raise CaseError(f"{name}: clean path escapes the repository")
|
|
if target.is_dir():
|
|
shutil.rmtree(target)
|
|
elif target.exists():
|
|
target.unlink()
|
|
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)
|
|
version = subprocess.run(
|
|
[binary, "--version"], capture_output=True, text=True, check=True
|
|
).stdout
|
|
args = [str(arg).replace("$MARQDO_BIN", binary) for arg in case.get("args", [])]
|
|
command = [binary, "run", str(source), *args, "--output", "json"]
|
|
result = subprocess.run(
|
|
command,
|
|
cwd=REPO,
|
|
env=env,
|
|
input=case.get("stdin", "").encode(),
|
|
capture_output=True,
|
|
)
|
|
if result.returncode != 0:
|
|
raise CaseError(
|
|
f"{name}: CLI exited {result.returncode}\nstderr:\n"
|
|
f"{result.stderr.decode(errors='replace')}"
|
|
)
|
|
try:
|
|
report = json.loads(result.stdout)
|
|
except json.JSONDecodeError as error:
|
|
raise CaseError(f"{name}: CLI did not emit a JSON report: {error}") from error
|
|
if report.get("run", {}).get("status") != "ok":
|
|
raise CaseError(f"{name}: run status is not ok: {report.get('run')}")
|
|
events = report.get("events") or []
|
|
if not events or events[-1].get("kind") not in (
|
|
"run.completed",
|
|
"run.failed",
|
|
"run.rejected",
|
|
):
|
|
raise CaseError(f"{name}: report has no terminal event")
|
|
terminal = events[-1]["payload"]
|
|
if terminal.get("status") != "ok":
|
|
raise CaseError(f"{name}: terminal status is not ok: {terminal.get('status')}")
|
|
actual_value = terminal.get("value")
|
|
expected_value = _substitute(case["expected_terminal"], version)
|
|
if actual_value != expected_value:
|
|
raise CaseError(
|
|
f"{name}: terminal value changed\nexpected: "
|
|
f"{json.dumps(expected_value, ensure_ascii=False, sort_keys=True)}\n"
|
|
f"actual: {json.dumps(actual_value, ensure_ascii=False, sort_keys=True)}"
|
|
)
|
|
expected_stdout = case.get("expected_stdout", "")
|
|
actual_stdout = _channel_text(events, "stdout.chunk")
|
|
if actual_stdout != expected_stdout:
|
|
raise CaseError(
|
|
f"{name}: stdout changed: expected {expected_stdout!r}, got {actual_stdout!r}"
|
|
)
|
|
for check in case.get("event_checks", []):
|
|
matching = [
|
|
event
|
|
for event in events
|
|
if event.get("kind") == check["kind"]
|
|
and all(
|
|
_dig(event.get("payload"), pointer) == expected
|
|
for pointer, expected in check.get("payload", {}).items()
|
|
)
|
|
]
|
|
if not matching:
|
|
raise CaseError(
|
|
f"{name}: no {check['kind']} event matched {check.get('payload')}"
|
|
)
|
|
|
|
|
|
def _dig(value, pointer: str):
|
|
current = value
|
|
for part in pointer.split("."):
|
|
if isinstance(current, list):
|
|
current = current[int(part)]
|
|
elif isinstance(current, dict):
|
|
current = current[part]
|
|
else:
|
|
return object()
|
|
return current
|
|
|
|
|
|
def main() -> int:
|
|
parser = argparse.ArgumentParser(description=__doc__)
|
|
parser.add_argument("cases", nargs="*", help="case names to run")
|
|
args = parser.parse_args()
|
|
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 in tests/cases", file=sys.stderr)
|
|
return 2
|
|
selected = set(args.cases)
|
|
failures = 0
|
|
ran = 0
|
|
for path in paths:
|
|
try:
|
|
case = json.loads(path.read_text(encoding="utf-8"))
|
|
except json.JSONDecodeError as error:
|
|
print(f"FAIL {path.name}: invalid JSON: {error}", file=sys.stderr)
|
|
failures += 1
|
|
continue
|
|
if case.get("schema") != SCHEMA or case.get("schema_version") != SCHEMA_VERSION:
|
|
print(f"FAIL {path.name}: unsupported case schema", file=sys.stderr)
|
|
failures += 1
|
|
continue
|
|
if selected and case["name"] not in selected:
|
|
continue
|
|
ran += 1
|
|
try:
|
|
_run_case(case, path, binary, bundle)
|
|
print(f"PASS {case['name']}")
|
|
except CaseError 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())
|