Interplane page as plain text, for reading tools and agents. English is the reference text: translate it with your own tool. Text in backticks and in ``` blocks (commands, fingerprints, file names) and link targets in <...> are exact: copy them, never translate them. Page: /drakestapleton/omnet/blob/main/om/json/test/run.py # omnet aien-dev/omnet Brought by drakestapleton Sign in to star 0 stars 0 watching About Files History Releases Proposed changes Issues For developers 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.""" 4 import collections 5 import hashlib 6 import json 7 import os 8 from pathlib import Path 9 import subprocess 10 import sys 11 import time 12 13 HERE = Path(__file__).resolve().parent 14 ROOT = HERE.parents[2] 15 OUT = ROOT / "build/test/json" 16 OUT.mkdir(parents=True, exist_ok=True) 17 OMC = Path(sys.argv[1]).resolve() 18 SOURCE = (HERE.parent / "json.om").read_text() 19 DRIVER = (HERE / "driver.om").read_text() 20 21 22 def 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 34 def 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 42 go = 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. 46 oracle_env = dict(os.environ) 47 oracle_env.setdefault("GOTOOLCHAIN", "go1.26.8") 48 subprocess.run([go, "build", "-mod=mod", "-o", str(OUT / "oracle"), "."], cwd=HERE / "oracle", env=oracle_env, check=True) 49 result = subprocess.run([str(OUT / "oracle")], stdout=subprocess.PIPE, check=True) 50 (OUT / "oracle.jsonl").write_bytes(result.stdout) 51 rows = [json.loads(line) for line in result.stdout.splitlines()] 52 data = "".join(row["mode"] + row["hex"] + "\n" for row in rows).encode() 53 expected = [row["want"] for row in rows] 54 binary = build(SOURCE, "driver") 55 status, lines, rc = execute(binary, data, expected) 56 if 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)}") 63 for cls, count in sorted(collections.Counter(row["class"] for row in rows).items()): 64 print(f"json: {cls} {count}/{count} PASS") 65 66 worst = [row for row in rows if row["class"] == "member-long-prefix"] 67 assert len(worst) == 1 and worst[0]["want"].startswith("O ") 68 assert len(bytes.fromhex(worst[0]["hex"])) == 65536 69 smoke_runs = 10 70 smoke_input = ((worst[0]["mode"] + worst[0]["hex"] + "\n") * smoke_runs).encode() 71 started = time.perf_counter() 72 status, _, rc = execute(binary, smoke_input, [worst[0]["want"]] * smoke_runs) 73 elapsed = time.perf_counter() - started 74 assert status == "match", (status, rc) 75 print(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 79 vectors = json.loads((HERE / "vectors.json").read_text())["parse"] 80 golden_input = "".join("P" + row["input"].encode().hex() + "\n" for row in vectors).encode() 81 r = subprocess.run([str(binary)], input=golden_input, stdout=subprocess.PIPE, check=True, timeout=120) 82 got = r.stdout.decode().splitlines() 83 assert len(got) == len(vectors) 84 for 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) 89 print(f"json: committed-vectors {len(vectors)}/{len(vectors)} PASS") 90 91 mutants = { 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 } 99 for 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") 105 trap_source = SOURCE.replace("if jsondupe t d id\nret 5", "if jsondupe t d id\ntrap 5", 1) 106 trap = build(trap_source, "mutant-trap") 107 status, _, rc = execute(trap, data, expected) 108 assert status == "abnormal" and rc == 105, (status, rc) 109 print("json: trapping mutant rejected by harness PASS") 110 print(f"json: differential {len(rows)}/{len(rows)} PASS") 111 print(f"json: compiler sha256 {hashlib.sha256(OMC.read_bytes()).hexdigest()}")