#!/usr/bin/env python3 """Tests of the tree root's judge and format checker, and that the five judges share their code. Each sub-problem has its own tests in sub/kissing-d/test/. Run: python3 -I checks/test_judge.py""" import json import os import subprocess import sys import tempfile from fractions import Fraction from itertools import combinations from pathlib import Path PKG = Path(__file__).resolve().parent.parent JUDGE, REPO = PKG / "checks" / "judge", PKG COUNT = {5: 40, 7: 126, 9: 272, 10: 308} def run(script, *args, cwd): # as the check runs it (python3 checks/judge/check.py), without the environment's PYTHON* variables or user site env = {"PATH": os.environ.get("PATH", "/usr/bin:/bin"), "SS_ROUTE_DIR": "routes/x"} p = subprocess.run([sys.executable, "-E", "-s", "-B", str(script), *map(str, args)], cwd=cwd, capture_output=True, text=True, env=env, timeout=120) return p.returncode, p.stdout, p.stderr def check(files): """Runs verify, as checks/verify.sbatch does, on a route folder holding these files.""" with tempfile.TemporaryDirectory() as tmp: folder = Path(tmp, "routes", "x") folder.mkdir(parents=True) for name, content in files.items(): path = folder / name path.parent.mkdir(parents=True, exist_ok=True) if isinstance(content, bytes): path.write_bytes(content) else: path.write_text(content if isinstance(content, str) else json.dumps(content)) code, out, err = run(JUDGE / "check.py", folder, cwd=tmp) metrics = Path(tmp, "metrics.json") return code, out, err, json.loads(metrics.read_text()) if metrics.exists() else None def seed(d): return json.loads((REPO / "constructions" / f"d{d}.json").read_text()) def kissing(vs): """Independent of the judge: unit vectors pairwise at least 60 degrees apart, in plain Fractions.""" V = [[Fraction(e) for e in v] for v in vs] dot = lambda x, y: sum(a * b for a, b in zip(x, y)) return all(dot(x, x) for x in V) and all(dot(x, y) <= 0 or 4 * dot(x, y) ** 2 <= dot(x, x) * dot(y, y) for x, y in combinations(V, 2)) def test_all_four_seeds(): for d in COUNT: assert seed(d)["d"] == d and len(seed(d)["vectors"]) == COUNT[d] and kissing(seed(d)["vectors"]), d code, out, err, m = check({f"d{d}/seed.json": seed(d) for d in COUNT}) assert code == 0 and not err, out + err assert m == {"score": 2, "score_exact": "2", "subtasks": {"d5": 40, "d7": 126, "d9": 272, "d10": 308}}, m assert out.splitlines()[-1] == "d5: 40; d7: 126; d9: 272; d10: 308; 2 of 4 dimensions at the record or above", out code, out, err, m = check({"a.json": seed(9), "b.json": {"d": 9, "vectors": seed(9)["vectors"][:10]}}) assert code == 0 and m == {"score": 0, "score_exact": "0", "subtasks": {"d9": 272}} and out.splitlines()[-1] == "d9: 272; 0 of 4 dimensions at the record or above", out def test_invalid_candidates_fail_cleanly(): v = seed(7)["vectors"] cases = { "six": ({"d": 6, "vectors": [x[:6] for x in v[:3]]}, '"d" must be 5 or 7 or 9 or 10'), "repeat": ({"d": 7, "vectors": v + [v[0]]}, "vectors 0 and 126 are less than 60 degrees apart"), "zero": ({"d": 7, "vectors": [[0] * 7]}, "vector 0 is zero"), "float": ({"d": 7, "vectors": [[1.0] * 7]}, "must be an integer or a string"), "many": ({"d": 7, "vectors": v * 8}, "list of 1 to 1000"), } for name, (candidate, message) in cases.items(): code, out, err, m = check({"ok.json": seed(5), f"{name}.json": candidate}) assert code == 1 and message in out and not err and m["subtasks"] == {"d5": 40}, (name, out, err) for content in ("{not json", b"\xff\xfe{"): code, out, err, m = check({"bad.json": content}) assert code == 1 and "unreadable" in out and not err and m is None, out def test_no_candidates(): for files in ({}, {"notes.json": {"d": 5}}): code, out, err, m = check(files) assert code == 0 and out.strip() == "no candidates to check" and m is None, out def test_check_format(): tool = REPO / "tools" / "check_format.py" with tempfile.TemporaryDirectory() as tmp: for d in COUNT: Path(tmp, f"d{d}.json").write_text(json.dumps(seed(d))) code, out, err = run(tool, tmp, cwd=tmp) assert code == 0 and out.strip().endswith("4 candidates, 0 files with format errors"), out + err Path(tmp, "six.json").write_text('{"d": 6, "vectors": [[1, 0, 0, 0, 0, 0]]}') code, out, err = run(tool, tmp, cwd=tmp) assert code == 1 and '"d" must be 5 or 7 or 9 or 10' in out, out if __name__ == "__main__": failed = 0 for name, test in list(globals().items()): if name.startswith("test_"): try: test() print(f"ok {name}") except Exception as exc: failed += 1 print(f"FAIL {name}: {exc!r}") sys.exit(1 if failed else 0)