gbuffer_census, navmesh_cell_fit, root_spill_census: a wrong input is one ERROR line, not a traceback

This commit is contained in:
Reece Barker
2026-11-24 15:49:27 +01:00
committed by Jan Trencansky
parent d2a564b66a
commit 51f94c885d
6 changed files with 114 additions and 15 deletions

View File

@ -2,6 +2,7 @@
import json
from pathlib import Path
import struct
import subprocess
import sys
import tempfile
import unittest
@ -67,5 +68,31 @@ class CensusTests(unittest.TestCase):
self.assertEqual(group["observed_exports"], {"mrt0 compr": 2})
class WrongInputTests(unittest.TestCase):
"""A path that is not a shader_carve folder is one ERROR line and exit 2, not a traceback."""
TOOL = Path(__file__).resolve().parents[1] / "tools" / "gbuffer_census.py"
def run_tool(self, *args):
return subprocess.run([sys.executable, "-I", str(self.TOOL), *args],
capture_output=True, text=True, timeout=120)
def test_a_file_instead_of_the_carve_folder(self):
with tempfile.TemporaryDirectory() as tmp:
blob = Path(tmp) / "blob.bin"
blob.write_bytes(bytes(range(256)))
p = self.run_tool(str(blob))
self.assertEqual(p.returncode, 2, p.stderr)
self.assertNotIn("Traceback", p.stderr)
self.assertIn("not a shader_carve folder", p.stderr)
def test_a_malformed_index(self):
with tempfile.TemporaryDirectory() as tmp:
(Path(tmp) / "index.json").write_bytes(b"\xe6 not json")
p = self.run_tool(tmp)
self.assertEqual(p.returncode, 2, p.stderr)
self.assertNotIn("Traceback", p.stderr)
self.assertTrue(p.stderr.startswith("ERROR: "), p.stderr)
if __name__ == "__main__":
unittest.main()

View File

@ -1,7 +1,9 @@
"""tools/navmesh_cell_fit.py: the grid fit, its chance baseline and the per-cell summary, on synthetic vertices.
No game files."""
import os
import subprocess
import sys
import tempfile
import unittest
sys.path.insert(0, os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "tools"))
@ -81,5 +83,21 @@ class CellFit(unittest.TestCase):
self.assertEqual(len(h), 4)
class WrongInput(unittest.TestCase):
"""A file that is not an RPF archive is one ERROR line and exit 2, not a traceback."""
TOOL = os.path.join(os.path.dirname(os.path.abspath(__file__)), "..", "tools", "navmesh_cell_fit.py")
def test_not_an_archive(self):
with tempfile.TemporaryDirectory() as tmp:
junk = os.path.join(tmp, "junk.rpf")
with open(junk, "wb") as f:
f.write(b"\x00" * 4096)
p = subprocess.run([sys.executable, "-I", self.TOOL, junk], capture_output=True, text=True, timeout=120)
self.assertEqual(p.returncode, 2, p.stderr)
self.assertNotIn("Traceback", p.stderr)
self.assertEqual(len(p.stderr.strip().splitlines()), 1, p.stderr)
self.assertTrue(p.stderr.startswith("ERROR: "), p.stderr)
if __name__ == "__main__":
unittest.main()

View File

@ -267,5 +267,38 @@ class CliTest(unittest.TestCase):
self.assertIn("containers: 1, with an RTS0 part: 1", result.stdout)
class WrongInputTests(unittest.TestCase):
"""An index that is not UTF-8 JSON, or a folder, is one ERROR line and exit 2, not a traceback."""
def run_tool(self, *args):
return subprocess.run([sys.executable, "-I", TOOL, *args], capture_output=True, text=True, timeout=120)
def check_one_error(self, p, name):
self.assertEqual(p.returncode, 2, p.stderr)
self.assertNotIn("Traceback", p.stderr)
self.assertEqual(len(p.stderr.strip().splitlines()), 1, p.stderr)
self.assertIn(f"ERROR: cannot read {name}", p.stderr)
def test_index_not_utf8(self):
with tempfile.TemporaryDirectory() as tmp:
index = os.path.join(tmp, "index.json")
with open(index, "wb") as f:
f.write(b"\xe6\x00\xff")
self.check_one_error(self.run_tool(index), index)
def test_index_is_a_folder(self):
with tempfile.TemporaryDirectory() as tmp:
self.check_one_error(self.run_tool(tmp), tmp)
def test_carve_not_json(self):
with tempfile.TemporaryDirectory() as tmp:
index = os.path.join(tmp, "index.json")
carve = os.path.join(tmp, "carve.json")
with open(index, "w", encoding="utf-8", newline="\n") as f:
f.write("{}")
with open(carve, "w", encoding="utf-8", newline="\n") as f:
f.write("not json")
self.check_one_error(self.run_tool(index, "--carve", carve), carve)
if __name__ == "__main__":
unittest.main()

View File

@ -138,8 +138,16 @@ def main():
parser.add_argument("--payload-coverage", action="store_true",
help="count distinct whole FSSM payloads per cohort and histogram their indexed entry counts")
args = parser.parse_args()
print(json.dumps(census(args.dxbc, args.disasm or args.dxbc / "disasm",
payload_coverage=args.payload_coverage), indent=2, sort_keys=True))
if not (args.dxbc / "index.json").is_file():
print(f"ERROR: {args.dxbc}: not a shader_carve folder (no index.json)", file=sys.stderr)
return 2
try:
report = census(args.dxbc, args.disasm or args.dxbc / "disasm", payload_coverage=args.payload_coverage)
except (OSError, ValueError) as e: # an unreadable or malformed index or listing: one line, not a traceback
print(f"ERROR: {e}", file=sys.stderr)
return 2
print(json.dumps(report, indent=2, sort_keys=True))
return 0
if __name__ == "__main__":
@ -147,4 +155,4 @@ if __name__ == "__main__":
sys.stdout.reconfigure(errors="replace")
except (AttributeError, ValueError, OSError):
pass
main()
sys.exit(main())

View File

@ -203,14 +203,19 @@ def main():
print(f"ERROR: cannot read {a.archive}: no such file or folder", file=sys.stderr)
return 2
hashes, docs = None, None
if a.common:
if a.out and os.path.exists(a.out) and any(same_report_path(a.out, p) for p in _carve_inputs(a.common)):
ap.error("--out would overwrite a --common carve input")
cells, names = vehicle_documents(a.common)
hashes = name_hashes(names)
docs = {"documents": sum(cells.values()), "models": len(names),
"cell_sizes": {("absent" if k is None else str(k)): v for k, v in sorted(cells.items(), key=str)}}
summary, scanned, hits, control = measure(a.archive, hashes, a.min_fraction, a.static_every)
try:
if a.common:
if a.out and os.path.exists(a.out) and any(same_report_path(a.out, p) for p in _carve_inputs(a.common)):
ap.error("--out would overwrite a --common carve input")
cells, names = vehicle_documents(a.common)
hashes = name_hashes(names)
docs = {"documents": sum(cells.values()), "models": len(names),
"cell_sizes": {("absent" if k is None else str(k)): v
for k, v in sorted(cells.items(), key=str)}}
summary, scanned, hits, control = measure(a.archive, hashes, a.min_fraction, a.static_every)
except (OSError, ValueError) as e: # not an RPF archive, or a carve that can't be read: one line
print(f"ERROR: {e}", file=sys.stderr)
return 2
report = {"local_space_meshes": summary, "non_grid_scanned": scanned}
if control is not None:
report["static_control"] = control

View File

@ -138,14 +138,22 @@ def main(argv=None):
if a.carve and not os.path.exists(a.carve):
print(f"ERROR: cannot read {a.carve}: no such file", file=sys.stderr)
return 2
with open(a.index, encoding="utf-8-sig") as f: # an index saved with a UTF-8 BOM is still JSON
index = json.load(f)
try:
with open(a.index, encoding="utf-8-sig") as f: # an index saved with a UTF-8 BOM is still JSON
index = json.load(f)
except (OSError, ValueError) as e: # a folder, or not UTF-8 JSON (UnicodeDecodeError is a ValueError)
print(f"ERROR: cannot read {a.index}: {e}", file=sys.stderr)
return 2
if not isinstance(index, dict):
ap.error(f"{a.index} is not a translator index (expected a JSON object)")
carve = None
if a.carve:
with open(a.carve, encoding="utf-8-sig") as f: # same for the carve index
carve = json.load(f)
try:
with open(a.carve, encoding="utf-8-sig") as f: # same for the carve index
carve = json.load(f)
except (OSError, ValueError) as e:
print(f"ERROR: cannot read {a.carve}: {e}", file=sys.stderr)
return 2
# --base overrides the stages it names and keeps the defaults for the rest, so a partial override never drops
# a stage from the check.
summary = census(index, {**DEFAULT_BASE, **dict(a.base)}, carve)