57 synthetic cases with a written-out basis, an independent oracle (gen_validity.py --check) and a unittest that runs validity.py through its INTERFACE v1; fails 57/57 until STRA-312 exists. Co-Authored-By: Claude Sonnet 5.5 <noreply@anthropic.com>
176 lines
8.4 KiB
Python
176 lines
8.4 KiB
Python
"""Golden-vector tests of the validity module validity.py (STRA-311, S0.1t, role SDET), written BEFORE validity.py exists.
|
|
|
|
Run: python -m unittest scripts.e2e.evidence.test_validity_golden -v (from the repository root)
|
|
Stdlib only, Python >= 3.9 (SC15). One test per case of golden/validity_cases.json; each runs validity.py through its command line
|
|
(INTERFACE v1 in the STRA-312 body) on fixture files built by golden/gen_validity.py:materialize(), and compares the result with the
|
|
expected verdict, which gen_validity.py recomputes independently of validity.py (`gen_validity.py --check`).
|
|
|
|
Tests-first: with no validity.py every test FAILS with 'validity.py not found' (an assertion, never an error in this file).
|
|
STRA-312 must pass every case UNCHANGED; the golden cases are not edited by that leaf.
|
|
"""
|
|
import importlib.util
|
|
import json
|
|
import os
|
|
import subprocess
|
|
import sys
|
|
import tempfile
|
|
import unittest
|
|
from fractions import Fraction
|
|
|
|
HERE = os.path.dirname(os.path.abspath(__file__))
|
|
REPO = os.path.abspath(os.path.join(HERE, "..", "..", ".."))
|
|
GOLDEN = os.path.join(HERE, "golden")
|
|
VALIDITY = os.path.join(HERE, "validity.py")
|
|
SERIES_EVAL = os.path.join(HERE, "series_eval.py")
|
|
LN2 = 0.6931471805599453
|
|
|
|
|
|
def _load_generator():
|
|
spec = importlib.util.spec_from_file_location("gen_validity_golden", os.path.join(GOLDEN, "gen_validity.py"))
|
|
module = importlib.util.module_from_spec(spec)
|
|
spec.loader.exec_module(module)
|
|
return module
|
|
|
|
|
|
G = _load_generator()
|
|
with open(os.path.join(GOLDEN, "validity_cases.json"), "r", encoding="utf-8") as _fh:
|
|
DOC = json.load(_fh)
|
|
|
|
|
|
def run_cli(script, *args):
|
|
proc = subprocess.run([sys.executable, script] + list(args), stdout=subprocess.PIPE, stderr=subprocess.PIPE,
|
|
universal_newlines=True, cwd=REPO, timeout=120)
|
|
return proc.returncode, proc.stdout, proc.stderr
|
|
|
|
|
|
def write(path, obj):
|
|
with open(path, "w", encoding="utf-8", newline="\n") as fh:
|
|
fh.write(obj if isinstance(obj, str) else json.dumps(obj, indent=2))
|
|
|
|
|
|
class GoldenValidity(unittest.TestCase):
|
|
maxDiff = None
|
|
|
|
def require_validity(self):
|
|
if not os.path.exists(VALIDITY):
|
|
self.fail("validity.py not found: %s (tests-first: STRA-312 has not been written yet)" % VALIDITY)
|
|
|
|
def where(self, case, rc, out, err):
|
|
return "case %s (%s)\nbasis: %s\nexit=%s\nstdout: %s\nstderr: %s" % (case["name"], case["kind"], case["basis"], rc, out[-2000:], err[-2000:])
|
|
|
|
# -- kinds --------------------------------------------------------------------------------------------------
|
|
def run_pairs(self, case):
|
|
exp = case["expected"]
|
|
with tempfile.TemporaryDirectory() as tmp:
|
|
mat = G.materialize(case["input"], DOC["templates"], DOC["schedules"], {p["pair"]: p for p in exp.get("pairs", [])})
|
|
rec_dir = os.path.join(tmp, "records")
|
|
os.makedirs(rec_dir)
|
|
for fname, rec in mat["records"].items():
|
|
write(os.path.join(rec_dir, fname), rec)
|
|
write(os.path.join(tmp, "schedule.json"), mat["schedule"])
|
|
write(os.path.join(tmp, "ledger.jsonl"), "".join(json.dumps(line) + "\n" for line in mat["ledger"]))
|
|
rc, out, err = run_cli(VALIDITY, "pairs", "--records", rec_dir, "--schedule", os.path.join(tmp, "schedule.json"),
|
|
"--ledger", os.path.join(tmp, "ledger.jsonl"), "--machine", case["input"]["machine"])
|
|
info = self.where(case, rc, out, err)
|
|
self.assertEqual(rc, exp["exit"], info)
|
|
if exp["exit"] != 0:
|
|
for name in exp.get("names", []):
|
|
self.assertIn(name, out + err, "the offending run id %s must be named\n%s" % (name, info))
|
|
return
|
|
try:
|
|
result = json.loads(out)
|
|
except ValueError:
|
|
self.fail("stdout is not JSON\n" + info)
|
|
self.assertIn("pairs", result, info)
|
|
got = {}
|
|
for p in result["pairs"]:
|
|
self.assertNotIn(p["pair"], got, "pair %s listed twice\n%s" % (p["pair"], info))
|
|
got[p["pair"]] = p
|
|
self.assertEqual(sorted(got), sorted(p["pair"] for p in exp["pairs"]), "pairs listed\n" + info)
|
|
for want in exp["pairs"]:
|
|
have = got[want["pair"]]
|
|
self.assertIs(have["valid"], want["valid"], "pair %d valid\n%s" % (want["pair"], info))
|
|
self.assertEqual(sorted(have["reasons"]), sorted(want["reasons"]), "pair %d reasons\n%s" % (want["pair"], info))
|
|
self.assertEqual(have.get("event"), want["event"], "pair %d event\n%s" % (want["pair"], info))
|
|
self.assertIs(result.get("manifest_ok"), exp["manifest_ok"], info)
|
|
self.assertAlmostEqual(result.get("invalid_rate"), exp["invalid_rate"], places=9, msg=info)
|
|
|
|
def check_schedule(self, case, sched_text, extra_name="schedule.json"):
|
|
with tempfile.TemporaryDirectory() as tmp:
|
|
path = os.path.join(tmp, extra_name)
|
|
write(path, sched_text)
|
|
return run_cli(VALIDITY, "schedule", "--check", path)
|
|
|
|
def run_schedule(self, case):
|
|
exp = case["expected"]
|
|
rc, out, err = self.check_schedule(case, DOC["schedules"][case["input"]["schedule"]])
|
|
info = self.where(case, rc, out, err)
|
|
self.assertEqual(rc, exp["exit"], info)
|
|
result = json.loads(out)
|
|
self.assertIs(result["balanced"], exp["balanced"], info)
|
|
self.assertRegex(result["hash"], r"^[0-9a-f]{64}$", info)
|
|
|
|
def run_schedule_hash(self, case):
|
|
exp = case["expected"]
|
|
base = DOC["schedules"][case["input"]["schedule"]]
|
|
hashes = []
|
|
for variant in case["input"]["variants"]:
|
|
rc, out, err = self.check_schedule(case, G.serialise_schedule(base, variant))
|
|
info = self.where(case, rc, out, err)
|
|
self.assertEqual(rc, exp["exit"], info)
|
|
result = json.loads(out)
|
|
self.assertRegex(result["hash"], r"^[0-9a-f]{64}$", info)
|
|
hashes.append(result["hash"])
|
|
rc, out, err = self.check_schedule(case, DOC["schedules"][case["input"]["other"]])
|
|
info = self.where(case, rc, out, err)
|
|
self.assertEqual(rc, exp["exit"], info)
|
|
other = json.loads(out)["hash"]
|
|
self.assertEqual(len(set(hashes)) == 1, exp["same_across_variants"], "hashes across serialisations: %s\n%s" % (hashes, info))
|
|
self.assertEqual(other not in hashes, exp["differs_from_other"], info)
|
|
|
|
def run_schedule_raw(self, case):
|
|
rc, out, err = self.check_schedule(case, case["input"]["raw"])
|
|
self.assertEqual(rc, case["expected"]["exit"], self.where(case, rc, out, err))
|
|
|
|
def run_order_tables(self, case):
|
|
# The tables belong to series_eval.py (STRA-290), which does not exist when validity.py is written: optional until then.
|
|
if not os.path.exists(SERIES_EVAL):
|
|
self.skipTest("series_eval.py not found (STRA-290): order tables are checked once it exists")
|
|
series = json.loads(json.dumps(case["input"]["series"]))
|
|
for pair in series["pairs"]:
|
|
for vals in pair["arms"].values():
|
|
vals.pop("exp2", None)
|
|
with tempfile.TemporaryDirectory() as tmp:
|
|
path = os.path.join(tmp, "series.json")
|
|
write(path, series)
|
|
rc, out, err = run_cli(SERIES_EVAL, path)
|
|
info = self.where(case, rc, out, err)
|
|
self.assertEqual(rc, 0, info)
|
|
tables = json.loads(out).get("order_tables")
|
|
self.assertIsNotNone(tables, "series_eval.py output lacks 'order_tables' (golden requirement of STRA-311)\n" + info)
|
|
for which, key in (("by_position", "by_position"), ("by_predecessor", "by_predecessor")):
|
|
got = tables[which]["wall_norm"]
|
|
want = case["expected"][key]
|
|
self.assertEqual(sorted(got), sorted(want), "%s arms\n%s" % (which, info))
|
|
for arm, rows in want.items():
|
|
self.assertEqual(sorted(got[arm]), sorted(rows), "%s keys of %s\n%s" % (which, arm, info))
|
|
for k, units in rows.items():
|
|
self.assertAlmostEqual(got[arm][k], float(Fraction(units)) * LN2, places=9, msg="%s %s %s\n%s" % (which, arm, k, info))
|
|
|
|
|
|
def _make(case):
|
|
def test(self):
|
|
self.require_validity()
|
|
getattr(self, "run_" + case["kind"])(case)
|
|
test.__name__ = "test_" + case["name"]
|
|
test.__doc__ = "%s: %s" % (case["class"], case["basis"][:200])
|
|
return test
|
|
|
|
|
|
for _case in DOC["cases"]:
|
|
setattr(GoldenValidity, "test_" + _case["name"], _make(_case))
|
|
|
|
|
|
if __name__ == "__main__":
|
|
unittest.main()
|