Skip to content
Merged
Show file tree
Hide file tree
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
27 changes: 27 additions & 0 deletions tests/test_gbuffer_census.py
Original file line number Diff line number Diff line change
Expand Up @@ -2,6 +2,7 @@
import json
from pathlib import Path
import struct
import subprocess
import sys
import tempfile
import unittest
Expand Down Expand Up @@ -67,5 +68,31 @@ def test_cohorts_and_independent_coverage(self):
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()
18 changes: 18 additions & 0 deletions tests/test_navmesh_cell_fit.py
Original file line number Diff line number Diff line change
@@ -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"))
Expand Down Expand Up @@ -81,5 +83,21 @@ def test_name_hashes_cover_case_and_suffix(self):
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()
33 changes: 33 additions & 0 deletions tests/test_root_spill_census.py
Original file line number Diff line number Diff line change
Expand Up @@ -267,5 +267,38 @@ def test_carve_index_saved_with_bom_is_read(self):
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()
14 changes: 11 additions & 3 deletions tools/gbuffer_census.py
Original file line number Diff line number Diff line change
Expand Up @@ -138,13 +138,21 @@ 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__":
try: # a redirected stdout is strict ANSI code page under -I; write '?' for what it cannot encode
sys.stdout.reconfigure(errors="replace")
except (AttributeError, ValueError, OSError):
pass
main()
sys.exit(main())
21 changes: 13 additions & 8 deletions tools/navmesh_cell_fit.py
Original file line number Diff line number Diff line change
Expand Up @@ -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
Expand Down
16 changes: 12 additions & 4 deletions tools/root_spill_census.py
Original file line number Diff line number Diff line change
Expand Up @@ -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)
Expand Down