interplane.Get Omega
Read in your language

omnet

aien-dev/omnet

Brought by drakestapleton

branch main Branches Tags History

omnet / om / json / test / run.py

111 lines · 5241 bytes Raw Blame History
1#!/usr/bin/env python3
2# SPDX-License-Identifier: Apache-2.0
3"""Focused host-only JSON checks; generated mutants live only in build/test/json."""
4import collections
5import hashlib
6import json
7import os
8from pathlib import Path
9import subprocess
10import sys
11import time
12
13HERE = Path(__file__).resolve().parent
14ROOT = HERE.parents[2]
15OUT = ROOT / "build/test/json"
16OUT.mkdir(parents=True, exist_ok=True)
17OMC = Path(sys.argv[1]).resolve()
18SOURCE = (HERE.parent / "json.om").read_text()
19DRIVER = (HERE / "driver.om").read_text()
20
21
22def build(source, name):
23 src = OUT / f"{name}.om"
24 src.write_text(source + "\n" + DRIVER)
25 binary = OUT / name
26 with src.open("rb") as inp, binary.open("wb") as out:
27 result = subprocess.run([str(OMC)], stdin=inp, stdout=out, stderr=subprocess.PIPE)
28 if result.returncode:
29 raise RuntimeError(f"{name}: omc exit {result.returncode}: {result.stderr.decode()}")
30 binary.chmod(0o755)
31 return binary
32
33
34def execute(binary, data, expected):
35 result = subprocess.run([str(binary)], input=data, stdout=subprocess.PIPE, stderr=subprocess.PIPE, timeout=120)
36 lines = result.stdout.decode("ascii").splitlines()
37 if result.returncode != 0 or len(lines) != len(expected):
38 return "abnormal", lines, result.returncode
39 return ("match" if lines == expected else "mismatch"), lines, 0
40
41
42go = os.environ.get("GO", "go")
43# Output is compared byte for byte, and Go 1.27 changed encoding/json escaping
44# of invalid UTF-8. Pin the release the committed corpus was generated with;
45# an explicit GOTOOLCHAIN still wins.
46oracle_env = dict(os.environ)
47oracle_env.setdefault("GOTOOLCHAIN", "go1.26.8")
48subprocess.run([go, "build", "-mod=mod", "-o", str(OUT / "oracle"), "."], cwd=HERE / "oracle", env=oracle_env, check=True)
49result = subprocess.run([str(OUT / "oracle")], stdout=subprocess.PIPE, check=True)
50(OUT / "oracle.jsonl").write_bytes(result.stdout)
51rows = [json.loads(line) for line in result.stdout.splitlines()]
52data = "".join(row["mode"] + row["hex"] + "\n" for row in rows).encode()
53expected = [row["want"] for row in rows]
54binary = build(SOURCE, "driver")
55status, lines, rc = execute(binary, data, expected)
56if status != "match":
57 for i, (actual, want) in enumerate(zip(lines, expected)):
58 if actual != want:
59 print(f"json: mismatch {i} {rows[i]['class']} input={rows[i]['hex'][:160]} want={want[:160]} got={actual[:160]}")
60 if sum(a != b for a, b in zip(lines[:i+1], expected[:i+1])) >= 12:
61 break
62 raise SystemExit(f"json: FAIL {status} rc={rc} lines={len(lines)}/{len(expected)}")
63for cls, count in sorted(collections.Counter(row["class"] for row in rows).items()):
64 print(f"json: {cls} {count}/{count} PASS")
65
66worst = [row for row in rows if row["class"] == "member-long-prefix"]
67assert len(worst) == 1 and worst[0]["want"].startswith("O ")
68assert len(bytes.fromhex(worst[0]["hex"])) == 65536
69smoke_runs = 10
70smoke_input = ((worst[0]["mode"] + worst[0]["hex"] + "\n") * smoke_runs).encode()
71started = time.perf_counter()
72status, _, rc = execute(binary, smoke_input, [worst[0]["want"]] * smoke_runs)
73elapsed = time.perf_counter() - started
74assert status == "match", (status, rc)
75print(f"json: long-prefix smoke 256 distinct 250-byte keys, 65536-byte message, "
76 f"{smoke_runs} parse/hash/encode records: {elapsed:.6f}s wall, "
77 f"{elapsed / smoke_runs:.6f}s/record (includes process startup and pipe I/O) PASS")
78
79vectors = json.loads((HERE / "vectors.json").read_text())["parse"]
80golden_input = "".join("P" + row["input"].encode().hex() + "\n" for row in vectors).encode()
81r = subprocess.run([str(binary)], input=golden_input, stdout=subprocess.PIPE, check=True, timeout=120)
82got = r.stdout.decode().splitlines()
83assert len(got) == len(vectors)
84for row, line in zip(vectors, got):
85 if row["output"] is None:
86 assert line == "E", (row, line)
87 else:
88 assert line.startswith("O ") and line.split(" ")[2] == row["output"].encode().hex(), (row, line)
89print(f"json: committed-vectors {len(vectors)}/{len(vectors)} PASS")
90
91mutants = {
92 "duplicates": ("if jsondupe t d id\nret 5", "if false\nret 5"),
93 "unicode": ("ret 65533", "ret 65532"),
94 "depth": ("if ge get st 5 32", "if ge get st 5 31"),
95 "members": ("if ge get t add b 5 512", "if ge get t add b 5 514"),
96 "integer": ("if gt v div sub ulong 18446744073709551615 c 10", "if ge v div sub ulong 18446744073709551615 c 10"),
97 "html": ("or eq v 60 or eq v 62", "or eq v 61 or eq v 62"),
98}
99for name, (old, new) in mutants.items():
100 assert old in SOURCE, name
101 mutant = build(SOURCE.replace(old, new, 1), "mutant-" + name)
102 status, _, rc = execute(mutant, data, expected)
103 assert status == "mismatch", (name, status, rc)
104 print(f"json: completed-result mutant {name} detected PASS")
105trap_source = SOURCE.replace("if jsondupe t d id\nret 5", "if jsondupe t d id\ntrap 5", 1)
106trap = build(trap_source, "mutant-trap")
107status, _, rc = execute(trap, data, expected)
108assert status == "abnormal" and rc == 105, (status, rc)
109print("json: trapping mutant rejected by harness PASS")
110print(f"json: differential {len(rows)}/{len(rows)} PASS")
111print(f"json: compiler sha256 {hashlib.sha256(OMC.read_bytes()).hexdigest()}")