|
| 1 | +"""Replay the locked OpenCLI 1.8.8 manifest, help and browser output fixtures.""" |
| 2 | +from __future__ import annotations |
| 3 | + |
| 4 | +import argparse |
| 5 | +import hashlib |
| 6 | +import json |
| 7 | +import os |
| 8 | +import subprocess |
| 9 | +import tempfile |
| 10 | +from pathlib import Path |
| 11 | + |
| 12 | +ROOT = Path(__file__).resolve().parents[1] |
| 13 | +FIXTURES = ROOT / "src/test/resources/opencli-contracts/v1" |
| 14 | +HELP_CASES = { |
| 15 | + "root.json": (), |
| 16 | + "browser.stdout": ("browser",), |
| 17 | + "browser-tab.json": ("browser", "fixture", "tab"), |
| 18 | + "browser-get.json": ("browser", "fixture", "get"), |
| 19 | + "browser-state.json": ("browser", "fixture", "state"), |
| 20 | + "meta-auth.json": ("auth",), |
| 21 | + "meta-list.txt": ("list",), |
| 22 | + "meta-profile.json": ("profile",), |
| 23 | + "site-zhihu-hot.json": ("zhihu", "hot"), |
| 24 | + "site-npm.json": ("npm",), |
| 25 | + "site-npm-search.json": ("npm", "search"), |
| 26 | +} |
| 27 | +PAGE_URL = "http://127.0.0.1:18765/basic.html" |
| 28 | +BROWSER_CASES = { |
| 29 | + "tab-list.json": (("tab", "list"), {}), |
| 30 | + "tab-list-empty.json": (("tab", "list"), {"OPENCLI_FIXTURE_EMPTY": "1"}), |
| 31 | + "open.json": (("open", PAGE_URL), {}), |
| 32 | + "state-dom.stdout": (("state", "--source", "dom"), {}), |
| 33 | + "state-ax.stdout": (("state", "--source", "ax"), {}), |
| 34 | + "state-compare.json": (("state", "--source", "ax", "--compare-sources"), {}), |
| 35 | + "state-compare-ax-failure.json": ( |
| 36 | + ("state", "--compare-sources"), {"OPENCLI_FIXTURE_AX_FAILURE": "1"}, |
| 37 | + ), |
| 38 | + "find.json": (("find", "--css", "#fixture", "--limit", "1"), {}), |
| 39 | + "console.json": (("console",), {}), |
| 40 | + "console-level.json": (("console", "--level", "warning"), {"OPENCLI_FIXTURE_CONSOLE_LEVEL": "1"}), |
| 41 | + "network.json": (("network",), {}), |
| 42 | + "analyze.json": (("analyze", PAGE_URL), {}), |
| 43 | +} |
| 44 | + |
| 45 | + |
| 46 | +def verify_manifest(package: Path, lock: dict) -> None: |
| 47 | + metadata = json.loads((package / "package.json").read_bytes()) |
| 48 | + if metadata.get("name") != "@jackwener/opencli" or metadata.get("version") != lock["version"]: |
| 49 | + raise SystemExit(f"expected @jackwener/opencli@{lock['version']}") |
| 50 | + baseline = lock["manifest"] |
| 51 | + content = (package / "cli-manifest.json").read_bytes() |
| 52 | + if hashlib.sha256(content).hexdigest() != baseline["sha256"]: |
| 53 | + raise SystemExit("installed cli-manifest.json SHA-256 differs from the lock") |
| 54 | + actual = {f"{entry['site']} {entry['name']}" for entry in json.loads(content)} |
| 55 | + historical = { |
| 56 | + f"{entry['site']} {entry['subcommand']}" |
| 57 | + for entry in json.loads((ROOT / baseline["historicalComparison"]).read_bytes()) |
| 58 | + } |
| 59 | + if sorted(actual - historical) != baseline["addedAdapterCommands"]: |
| 60 | + raise SystemExit("added adapter commands differ from the locked comparison") |
| 61 | + if sorted(historical - actual) != baseline["removedAdapterCommands"]: |
| 62 | + raise SystemExit("removed adapter commands differ from the locked comparison") |
| 63 | + print(f"Manifest verified against the lock and historical snapshot ({len(actual)} commands)") |
| 64 | + |
| 65 | + |
| 66 | +def replay(entry: Path, preload: Path, fixture: Path, argv: tuple[str, ...], settings: dict) -> None: |
| 67 | + with tempfile.TemporaryDirectory(prefix="opencli-fixture-") as isolated: |
| 68 | + state = Path(isolated) |
| 69 | + env = { |
| 70 | + name: value for name, value in os.environ.items() |
| 71 | + if not name.startswith("OPENCLI_") and name != "NODE_OPTIONS" |
| 72 | + } |
| 73 | + env.update({ |
| 74 | + "CI": "1", |
| 75 | + "NO_COLOR": "1", |
| 76 | + "OPENCLI_FIXTURE_HOME": isolated, |
| 77 | + "OPENCLI_CONFIG_DIR": str(state / "config"), |
| 78 | + "OPENCLI_CACHE_DIR": str(state / "cache"), |
| 79 | + }) |
| 80 | + env.update(settings) |
| 81 | + result = subprocess.run( |
| 82 | + ["node", "--import", str(preload), str(entry), *argv], |
| 83 | + cwd=state, env=env, capture_output=True, timeout=20, |
| 84 | + ) |
| 85 | + if result.returncode or result.stderr or result.stdout != fixture.read_bytes(): |
| 86 | + raise SystemExit(f"{fixture.name}: replay differs (exit {result.returncode}, " |
| 87 | + f"stderr {len(result.stderr)} bytes, stdout {len(result.stdout)} bytes)") |
| 88 | + |
| 89 | + |
| 90 | +def main() -> None: |
| 91 | + parser = argparse.ArgumentParser(description=__doc__) |
| 92 | + parser.add_argument("package", type=Path, help="Installed @jackwener/opencli package directory") |
| 93 | + package = parser.parse_args().package.resolve() |
| 94 | + lock = json.loads((FIXTURES / "upstream-1.8.8.lock.json").read_bytes()) |
| 95 | + verify_manifest(package, lock) |
| 96 | + entry = package / "dist/src/main.js" |
| 97 | + help_dir = (FIXTURES / lock["structuredHelp"]["checksums"]).parent |
| 98 | + browser_dir = (FIXTURES / lock["browserOutput"]["checksums"]).parent |
| 99 | + with tempfile.TemporaryDirectory(prefix="opencli-help-preload-") as tmp: |
| 100 | + preload = Path(tmp) / "isolate.mjs" |
| 101 | + preload.write_text( |
| 102 | + "import os from 'node:os';\n" |
| 103 | + "import { syncBuiltinESMExports } from 'node:module';\n" |
| 104 | + "os.homedir = () => process.env.OPENCLI_FIXTURE_HOME;\n" |
| 105 | + "syncBuiltinESMExports();\n", |
| 106 | + encoding="utf-8", |
| 107 | + ) |
| 108 | + for name, argv in HELP_CASES.items(): |
| 109 | + replay(entry, preload, help_dir / name, (*argv, "--help", "-f", "json"), {}) |
| 110 | + for name, (argv, settings) in BROWSER_CASES.items(): |
| 111 | + replay(entry, browser_dir / "capture.mjs", browser_dir / name, ("browser", "fixture", *argv), |
| 112 | + {"OPENCLI_FIXTURE_FIXED_CLOCK": "1", **settings}) |
| 113 | + print(f"Replay matched {len(HELP_CASES)} help and {len(BROWSER_CASES)} browser samples byte for byte") |
| 114 | + |
| 115 | + |
| 116 | +if __name__ == "__main__": |
| 117 | + main() |
0 commit comments