"""Tests for tools/world_census.py, built from synthetic 0x7a resources (no game data). python -I tests/test_world_census.py """ import argparse import contextlib import hashlib import importlib.util import io import json import os import shutil import struct import subprocess import sys import tempfile import unittest import zlib from pathlib import Path from unittest import mock ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) def load(name, path): spec = importlib.util.spec_from_file_location(name, path) module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) return module WC = load("world_census_under_test", os.path.join(ROOT, "tools", "world_census.py")) TWI = load("world_index_test_builder", os.path.join(ROOT, "tests", "test_world_index.py")) def make_archive(path): """A small RPF9: normal map, zlib-split map, raw-split map, meta and a duplicate.""" out = bytearray(0x40) out[:4] = b"9FPR" struct.pack_into(" 1000: raise RuntimeError("shard planning never finished") return other + int(self) for size in (0, -5): Counted.adds = 0 with self.subTest(size=size), self.assertRaises(ValueError): WC._expected_shards(0, 10, Counted(size)) def test_cli_rejects_shard_size_and_jobs_below_one(self): with tempfile.TemporaryDirectory() as tmp: arc = os.path.join(tmp, "sample.rpf") make_archive(arc) out = os.path.join(tmp, "out") tool = os.path.join(ROOT, "tools", "world_census.py") for flag, value in (("--shard-size", "0"), ("--shard-size", "-1"), ("--jobs", "0")): with self.subTest(flag=flag, value=value): # A subprocess with a timeout, so the old endless loop fails the test instead of hanging it. p = subprocess.run([sys.executable, "-I", tool, arc, "--out", out, flag, value], capture_output=True, text=True, timeout=10) self.assertEqual(p.returncode, 2, p.stderr) self.assertIn("must be at least 1", p.stderr) self.assertNotIn("Traceback", p.stderr) self.assertFalse(os.path.exists(out)) def test_jobs_above_the_platform_limit_are_rejected(self): """--jobs 100 crashed on Windows: ProcessPoolExecutor allows at most 61 workers there.""" saved = WC.MAX_JOBS try: WC.MAX_JOBS = 61 self.assertEqual(WC.job_count("61"), 61) for value in ("62", "100"): with self.subTest(value=value), self.assertRaises(argparse.ArgumentTypeError) as ctx: WC.job_count(value) self.assertIn("at most 61", str(ctx.exception)) WC.MAX_JOBS = None self.assertEqual(WC.job_count("100"), 100) finally: WC.MAX_JOBS = saved self.assertEqual(WC.MAX_JOBS, 61 if os.name == "nt" else None) @unittest.skipUnless(os.name == "nt", "the 61-worker limit is Windows-only") def test_cli_rejects_jobs_above_61_on_windows(self): with tempfile.TemporaryDirectory() as tmp: arc = os.path.join(tmp, "sample.rpf") make_archive(arc) tool = os.path.join(ROOT, "tools", "world_census.py") p = subprocess.run([sys.executable, "-I", tool, arc, "--out", os.path.join(tmp, "out"), "--jobs", "100"], capture_output=True, text=True, timeout=30) self.assertEqual(p.returncode, 2, p.stderr) self.assertIn("must be at most 61", p.stderr) self.assertNotIn("Traceback", p.stderr) def aligned(*parts): """Concatenate parts, each starting on a 16-byte boundary (the walker only accepts aligned streams).""" out = bytearray() for part in parts: out.extend(b"\0" * (((len(out) + 15) & ~15) - len(out))) out.extend(part) return bytes(out) def with_block(blob, name, size, pointer): """Add a third block-table entry (the builder leaves 0x220.. free) to a map resource.""" b = bytearray(blob) struct.pack_into(" 0x700 self.assertEqual(WC.required_len(longer), 0x800) self.assertTrue(WC.needs_more(longer)) self.assertFalse(WC.needs_more(self.blob)) def test_graphics_block_does_not_count(self): gfx = self.patched("= legacy["end"]]) rebuilt, new_rows = self.scan(self.arc, "--resume", to_scan=2) self.assertTrue(rebuilt["census_exact"]) self.assertEqual(new_rows, rows) def test_staged_json_restores_write_mode_on_failure(self): with tempfile.TemporaryDirectory() as tmp: dest = os.path.join(tmp, "out.json") with open(dest, "w", encoding="utf-8") as f: f.write("{}") os.chmod(dest, 0o444) chmod_calls = [] real_chmod = os.chmod def track_chmod(p, mode, **kwargs): chmod_calls.append((p, mode)) return real_chmod(p, mode, **kwargs) with mock.patch.object(WC.os, "chmod", side_effect=track_chmod): try: with WC._staged_json(dest, {"test": 1}) as staged: raise RuntimeError("simulated write failure") except RuntimeError: pass self.assertTrue(any(mode == 0o600 for p, mode in chmod_calls)) def setUpModule(): # The tools' main() prints its summary JSON; keep it out of the test log (tests that check it redirect again). quiet = contextlib.redirect_stdout(io.StringIO()) quiet.__enter__() unittest.addModuleCleanup(quiet.__exit__, None, None, None) if __name__ == "__main__": unittest.main()