#!/usr/bin/env python3 """Capability self-report (`--capabilities`): the engine's own answer about what it supports. Batch 5a. The control plane (`hoelee/hevc-transcode`) drives this engine but cannot import it, so before this it GUESSED - a regex over this file for `ROOT`/`WORK` and `"--work-dir" in src`. Guesses rot silently. `library_run.py --capabilities --json` replaces them with a self-report, and this test is what keeps the self-report from becoming the next hand-written copy that drifts: 1. the JSON is ONE line, ASCII-only, and parses; 2. the shape is exactly the contract (entry / version / contract / tiers / flags / quality_knobs / defaults / locks) - a missing key breaks the control plane, so assert the key SETS; 3. every flag reported `true` really exists on the command line: `--help` shows it AND argparse accepts it (feed it a value; a phantom flag would exit 2); 4. `tiers` equals the real `--tier` choices in `--help`; 5. `defaults.work` / `defaults.root` equal the module's own constants, and crf/cq equal the real parser defaults - the numbers the control plane will believe; 6. asking creates NOTHING on disk (the report must be free and side-effect-free: no stage dir, no ledger, no lock, not even the `--work-dir` it was handed); 7. the human-readable listing agrees with the JSON. Exit code 0 = every assertion held. Usage: python scripts/test_capabilities.py """ import json import os import re import subprocess import sys import tempfile HERE = os.path.dirname(os.path.abspath(__file__)) sys.path.insert(0, HERE) import library_run as LR # noqa: E402 ENTRY = os.path.join(HERE, "library_run.py") PY = sys.executable def run(*args, **kw): return subprocess.run([PY, "-u", ENTRY] + list(args), capture_output=True, text=True, encoding="utf-8", errors="replace", **kw) checks = {} def check(name, ok, detail=""): checks[name] = bool(ok) print("%-52s %s%s" % (name, "PASS" if ok else "FAIL", (" " + str(detail)) if detail else "")) # ---- 1/2: the payload itself --------------------------------------------------------------- p = run("--capabilities", "--json") stdout = p.stdout or "" check("json_probe_exits_zero", p.returncode == 0, "rc=%d %s" % (p.returncode, (p.stderr or "")[:200])) lines = [l for l in stdout.splitlines() if l.strip()] check("json_is_exactly_one_line", len(lines) == 1, "%d line(s)" % len(lines)) check("json_is_ascii", all(ord(c) < 128 for c in stdout), "non-ASCII survives a cp1252 console badly") cap = {} try: cap = json.loads(lines[0]) except Exception as e: # noqa: BLE001 check("json_parses", False, repr(e)) else: check("json_parses", True) check("top_level_keys", set(cap) == {"entry", "version", "contract", "tiers", "flags", "quality_knobs", "defaults", "locks"}, sorted(cap)) check("entry_names_this_file", cap.get("entry") == "library_run.py", str(cap.get("entry"))) check("version_is_a_string", isinstance(cap.get("version"), str) and cap["version"], str(cap.get("version"))) check("contract_is_an_int", isinstance(cap.get("contract"), int) and cap["contract"] >= 1, str(cap.get("contract"))) check("flags_key_set", set(cap.get("flags") or {}) == {"work_dir", "stage_dir", "dest", "keep_source", "lock_tag"}, sorted(cap.get("flags") or {})) check("quality_knobs_key_set", set(cap.get("quality_knobs") or {}) == {"crf", "cq", "qsv_quality", "qsv_preset", "x265_preset", "nvenc_preset"}, sorted(cap.get("quality_knobs") or {})) check("defaults_key_set", set(cap.get("defaults") or {}) == {"work", "root", "crf", "cq", "x265_preset", "nvenc_preset", "qsv_quality", "qsv_preset"}, sorted(cap.get("defaults") or {})) # Batch 4b-1: the QSV knobs must have NO default. `null` is the report SAYING "the caller has to supply # a measured number" - a value here would be an invented gear, which this repo does not encode with. check("qsv_reports_no_invented_default", (cap.get("defaults") or {}).get("qsv_quality") is None and (cap.get("defaults") or {}).get("qsv_preset") is None, "%s / %s" % ((cap.get("defaults") or {}).get("qsv_quality"), (cap.get("defaults") or {}).get("qsv_preset"))) check("qsv_knobs_are_advertised", (cap.get("quality_knobs") or {}).get("qsv_quality") == "--qsv-quality" and (cap.get("quality_knobs") or {}).get("qsv_preset") == "--qsv-preset", (cap.get("quality_knobs") or {})) check("locks_key_set", set(cap.get("locks") or {}) == {"template", "tags"}, sorted(cap.get("locks") or {})) # ---- 3: a reported flag must really be accepted by the parser ------------------------------ FLAG_OF = {"work_dir": "--work-dir", "stage_dir": "--stage-dir", "dest": "--dest", "keep_source": "--keep-source", "lock_tag": "--lock-tag"} ARG_OF = {"work_dir": "X", "stage_dir": "X", "dest": "X", "lock_tag": "probe"} help_txt = run("--help").stdout or "" for key, opt in FLAG_OF.items(): claimed = bool((cap.get("flags") or {}).get(key)) in_help = re.search(r"^\s*%s\b" % re.escape(opt), help_txt, re.M) is not None check("flag_%s_matches_help" % key, claimed == in_help, "claimed=%s help=%s" % (claimed, in_help)) if claimed: argv = [opt] + ([ARG_OF[key]] if key in ARG_OF else []) probe = run(*(argv + ["--capabilities", "--json"])) check("flag_%s_is_accepted" % key, probe.returncode == 0 and probe.stdout.strip().startswith("{"), "rc=%d %s" % (probe.returncode, (probe.stderr or "")[-160:].replace("\n", " "))) # ... and every knob it names must be in --help too for key, opt in (cap.get("quality_knobs") or {}).items(): if opt: check("knob_%s_matches_help" % key, re.search(r"^\s*%s\b" % re.escape(opt), help_txt, re.M) is not None, "%s -> %s" % (key, opt)) # ---- 4: tiers == the real --tier choices --------------------------------------------------- m = re.search(r"--tier\s*\{([^}]*)\}", help_txt) check("tiers_match_help_choices", m is not None and [t.strip() for t in m.group(1).split(",")] == list(cap.get("tiers") or []), "help=%s json=%s" % (m.group(1) if m else None, cap.get("tiers"))) # ---- 5: the defaults are the module's own numbers ------------------------------------------- d = cap.get("defaults") or {} check("default_work_is_the_constant", d.get("work") == LR.WORK, "%r vs %r" % (d.get("work"), LR.WORK)) check("default_root_is_the_constant", d.get("root") == LR.ROOT, "%r vs %r" % (d.get("root"), LR.ROOT)) parser = LR.build_parser() check("default_crf_is_the_parser_default", d.get("crf") == parser.parse_args(["--capabilities"]).crf, "%r vs %r" % (d.get("crf"), LR.CRF_X265)) check("default_cq_is_the_parser_default", d.get("cq") == parser.parse_args(["--capabilities"]).cq, "%r vs %r" % (d.get("cq"), LR.CQ_NVENC)) check("lock_template_is_what_main_builds", (cap.get("locks") or {}).get("template") == LR.LOCK_TEMPLATE and LR.LOCK_TEMPLATE % "x265" == "run-x265.lock", str((cap.get("locks") or {}).get("template"))) # ---- 6: asking must not create anything ---------------------------------------------------- with tempfile.TemporaryDirectory(prefix="caps_") as tmp: work = os.path.join(tmp, "work") os.makedirs(work) probe = run("--work-dir", work, "--capabilities", "--json") left = os.listdir(work) check("asking_creates_nothing", probe.returncode == 0 and not left, "left behind: %s" % left) check("work_dir_flag_does_not_move_the_report", json.loads(probe.stdout.strip()).get("defaults", {}).get("work") == LR.WORK, "the report always describes the compiled-in default") # ---- 7: the human listing agrees with the JSON --------------------------------------------- human = run("--capabilities").stdout or "" check("human_lists_the_version", LR.__version__ in human and "contract" in human, human.splitlines()[:1]) check("human_lists_every_tier", all(t in human for t in (cap.get("tiers") or [])), cap.get("tiers")) check("human_carries_the_defaults", all(str(x) in human for x in (d.get("crf"), d.get("cq"))), "crf=%s cq=%s" % (d.get("crf"), d.get("cq"))) check("human_and_json_agree_on_version", json.loads(lines[0])["version"] == LR.__version__, LR.__version__) print("\n%d/%d checks passed" % (sum(checks.values()), len(checks))) sys.exit(0 if all(checks.values()) else 1)