okami.mom/strata

git clone https://git.nkp.pet/okami.mom/strata

Niko1221Merge branch 'f-clean-step0' into f-clean-1abe32c7f3f

main
4.6 KiB90 linesraw
1"""The config snapshot test: for every machine class x model set x entry point, what the engine would be started with must equal the golden file.
2
3  python -m pytest tests/snapshot -q                          (or: python -m unittest tests.snapshot.test_config_snapshot)
4  STRATA_SNAPSHOT_UPDATE=1 python -m pytest tests/snapshot    (rewrite the golden files after an intended change; the diff of golden/ is the review)
5
6No GPU, no model, no download, no network and no real user folder is needed (see tests/snapshot/README.md).  The app entry points run the host's own code in Node,
7so `node` (24 or newer) must be installed; STRATA_SNAPSHOT_SKIP_APP=1 skips those two entries by name and the test says so.
8"""
9
10from __future__ import annotations
11
12import difflib
13import json
14import os
15import shutil
16import sys
17import unittest
18from pathlib import Path
19
20ROOT = Path(__file__).resolve().parents[2]
21if str(ROOT) not in sys.path:
22    sys.path.insert(0, str(ROOT))
23
24from tests.snapshot.driver import drive  # noqa: E402
25from tests.snapshot.generate import GOLDEN, dump  # noqa: E402
26from tests.snapshot.matrix import ENTRY_POINTS, MACHINES, MODEL_SETS  # noqa: E402
27
28UPDATE = os.environ.get("STRATA_SNAPSHOT_UPDATE") == "1"
29SKIP_APP = os.environ.get("STRATA_SNAPSHOT_SKIP_APP") == "1"
30APP_ENTRIES = ("app_plain", "app_models")
31
32
33def readable_diff(want: dict, got: dict, label: str) -> str:
34    a = json.dumps(want, indent=1, ensure_ascii=False).splitlines()
35    b = json.dumps(got, indent=1, ensure_ascii=False).splitlines()
36    lines = list(difflib.unified_diff(a, b, "golden " + label, "now " + label, lineterm="", n=2))
37    head = [f"changed top-level fields: {sorted(k for k in set(want) | set(got) if want.get(k) != got.get(k))}"]
38    return "\n".join(head + lines[:160] + (["... (%d more diff lines)" % (len(lines) - 160)] if len(lines) > 160 else []))
39
40
41class ConfigSnapshot(unittest.TestCase):
42    maxDiff = None
43
44    def check_cell(self, machine_key: str, set_key: str) -> None:
45        path = GOLDEN / machine_key / f"{set_key}.json"
46        want = json.loads(path.read_text(encoding="utf-8")) if path.is_file() else None
47        got_entries = {}
48        for entry in ENTRY_POINTS:
49            if entry in APP_ENTRIES and SKIP_APP:
50                print(f"SKIPPED (STRATA_SNAPSHOT_SKIP_APP=1): {machine_key}/{set_key}/{entry}")
51                continue
52            if entry in APP_ENTRIES and not shutil.which(os.environ.get("STRATA_SNAPSHOT_NODE") or "node"):
53                self.fail("node is not installed: the app entry points cannot be driven (install Node 24, or set STRATA_SNAPSHOT_SKIP_APP=1 to skip them by name)")
54            got_entries[entry] = drive(machine_key, set_key, entry)
55        if UPDATE:
56            merged = dict(want["entries"]) if want else {}
57            merged.update(got_entries)
58            path.parent.mkdir(parents=True, exist_ok=True)
59            path.write_text(dump({"machine": machine_key, "set": set_key, "entries": {e: merged[e] for e in ENTRY_POINTS if e in merged}}), encoding="utf-8", newline="\n")
60            return
61        self.assertIsNotNone(want, f"no golden file {path}: run with STRATA_SNAPSHOT_UPDATE=1 and review the new file")
62        for entry, got in got_entries.items():
63            with self.subTest(machine=machine_key, set=set_key, entry=entry):
64                self.assertNotIn("failed", got, f"{machine_key}/{set_key}/{entry} could not be driven: {got.get('failed')}")
65                if want["entries"].get(entry) != got:
66                    self.fail(f"\n{machine_key} / {set_key} / {entry}: what the engine would be started with changed.\n"
67                              + readable_diff(want["entries"].get(entry, {}), got, f"{machine_key}/{set_key}/{entry}")
68                              + "\nIf the change is intended: STRATA_SNAPSHOT_UPDATE=1 python -m pytest tests/snapshot, then review the golden/ diff.")
69
70    def test_every_golden_file_belongs_to_the_matrix(self):
71        have = {(p.parent.name, p.stem) for p in GOLDEN.glob("*/*.json")}
72        want = {(m.key, s.key) for m in MACHINES for s in MODEL_SETS}
73        self.assertEqual(sorted(have - want), [], "golden files for a class or set that is no longer in the matrix")
74        if not UPDATE:
75            self.assertEqual(sorted(want - have), [], "a class x set without a golden file")
76
77
78def _add(machine_key: str, set_key: str) -> None:
79    def test(self):
80        self.check_cell(machine_key, set_key)
81    test.__name__ = f"test_{machine_key}__{set_key}"
82    setattr(ConfigSnapshot, test.__name__, test)
83
84
85for _m in MACHINES:
86    for _s in MODEL_SETS:
87        _add(_m.key, _s.key)
88
89if __name__ == "__main__":
90    unittest.main()