#!/usr/bin/env python3 """Unit tests for tools/navmesh_links.py using synthetic navmesh tiles only.""" import contextlib import io import json import os import struct import subprocess import sys import tempfile import unittest from unittest import mock import zlib ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) if ROOT not in sys.path: sys.path.insert(0, ROOT) from tools import navmesh_decode as nd from tools import navmesh_links as nl TOOL = os.path.join(ROOT, "tools", "navmesh_links.py") BASE = nd.BASE def make_rpf(path, streams, pad_between=16): body = bytearray() for s in streams: body.extend(zlib.compress(s)) body.extend(b"\x00" * pad_between) hdr = bytearray(0x40) hdr[0:4] = b"9FPR" struct.pack_into(" poly 2 (100, 200, 300, 400, 500, 600, 0, 2, sector, sector, 0x0200, 0x0050, 63, 0), # link 1: cross-tile poly 0 (s0=sector) -> poly 999 (s1=sector+1) (110, 210, 310, 410, 510, 610, 0, 999, sector, sector + 1, 0x0400, 0x0040, 127, 0), # link 2: cross-tile poly 888 (s0=sector-1) -> poly 2 (s1=sector) (120, 220, 320, 420, 520, 620, 888, 2, sector - 1, sector, 0x0000, 0x0030, 254, 0), ] if link_indices is None: # poly 0 gets links [0, 1], poly 1 gets [], poly 2 gets [0, 2] link_indices = [0, 1, 0, 2] d4 = len(links) d8 = len(link_indices) sx, sy = sector & 0x1FF, sector >> 9 x0, y0, dx, dy, dz = (sx - 256) * 128.0, (sy - 256) * 128.0, 128.0, 128.0, 16.0 struct.pack_into(" len(buf): buf.extend(bytes(cur - len(buf))) return off if has_links: la = alloc(32 * d4) lb = alloc(2 * d8) for i, lk in enumerate(links): rec = list(lk) if i == d4 - 1: if corrupt_link_heading: rec[12] = 256 if corrupt_link_pad: rec[13] = 1 if corrupt_link_sector: rec[8] = sector + 5 rec[9] = sector + 6 if corrupt_link_poly_oob: rec[8] = sector rec[6] = n_polys struct.pack_into("<6HHHIIHHHH", buf, la + 32 * i, *rec) for k, li in enumerate(link_indices): val = 1 if (corrupt_b0_endpoint and k == d8 - 1) else li struct.pack_into(" 0: lcnt -= 1 hi9 = poly_hi9_flags[i] if i < len(poly_hi9_flags) else 0 w20 = (hi9 << 23) | ((lstart & 0x1FFFF) << 6) | (lcnt & 0x3F) struct.pack_into("1 and one 1->0. Self edges match themselves. a = [local(1)] * 3 + [local(0), local(0), local(1), open_edge, local(2), (sector + 1, 0, 0, 0)] # Tile B has the opposite imbalance. Combining tiles first would hide it. b = [local(1)] + [local(0)] * 3 first = build_tile(flags=1, sector=sector, poly_sizes=(4, 5), edges=a) second = build_tile(flags=1, sector=sector, poly_sizes=(1, 3), edges=b) bad = bytearray(second[0]) polygons = nd.split_array(bad, 0x98, 44, 2) struct.pack_into(" [0], poly 1 -> [1] (spurious!), poly 2 -> [0, 1] link_indices=[0, 1, 0, 1], poly_link_counts=(1, 1, 2), )[0] st = nl.new_stats() chk = nl.verify_tile(tile, st) self.assertTrue(chk["special_links_valid"]) self.assertTrue(chk["poly_link_chain"]) self.assertFalse(chk["link_indices_endpoints"]) def test_scan_validates_start_and_limit(self): with tempfile.TemporaryDirectory() as tmp: rpf = os.path.join(tmp, "nav.rpf") make_rpf(rpf, build_tile()) for kwargs in ( {"start": -1}, {"start": True}, {"start": False}, {"limit": 0}, {"limit": -5}, {"limit": True}, {"limit": False}, ): with self.subTest(kwargs=kwargs): with self.assertRaises(ValueError): nl.scan(rpf, **kwargs) def test_atomic_out_write_preserves_existing_report_on_failure_and_reports_oserror(self): with tempfile.TemporaryDirectory() as tmp: rpf = os.path.join(tmp, "nav.rpf") make_rpf(rpf, build_tile()) out = os.path.join(tmp, "report.json") with open(out, "wb") as fh: fh.write(b'{"previous": true}\n') err = io.StringIO() with mock.patch.object(nl, "replace_retry", side_effect=OSError("disk full")): with contextlib.redirect_stderr(err): rc = nl.main([rpf, "--out", out, "--quiet"]) self.assertEqual(rc, 2) self.assertIn("error:", err.getvalue()) # Existing report stays intact and no temporary file is left behind. with open(out, "rb") as fh: self.assertEqual(fh.read(), b'{"previous": true}\n') leftovers = [f for f in os.listdir(tmp) if f.endswith(".tmp")] self.assertEqual(leftovers, []) # Unwritable parent (blocked by regular file) exits 2 with one error line, no traceback. blocker = os.path.join(tmp, "blocker") with open(blocker, "wb") as fh: fh.write(b"x") proc = subprocess.run( [sys.executable, "-I", TOOL, rpf, "--out", os.path.join(blocker, "out.json"), "--quiet"], capture_output=True, text=True, ) self.assertEqual(proc.returncode, 2) self.assertIn("error:", proc.stderr) self.assertNotIn("Traceback", proc.stderr) # Strict JSON rejects NaN in both --out and stdout. with self.assertRaises(ValueError): nl._write_json_atomic(os.path.join(tmp, "nan.json"), {"bad": float("nan")}) with mock.patch.object(nl, "scan", return_value={"bad": float("nan")}): with self.assertRaises(ValueError): nl.main([rpf]) if __name__ == "__main__": unittest.main()