From a5fbe68937a87e351f7902df59eb9daa64a51a8e Mon Sep 17 00:00:00 2001 From: levi2m <55702618+levi2m@users.noreply.github.com> Date: Tue, 24 Nov 2026 23:20:50 -0300 Subject: [PATCH] dstorage_census: a wrong input is one ERROR line, not a traceback (DSTORAGE-CENSUS-WRONG-INPUT) A trace path that does not exist (FileNotFoundError), a folder for the trace (IsADirectoryError) and a ds-request line with a missing field (KeyError) or a malformed number (ValueError) stopped the tool with a traceback. Each now prints one ERROR line and exits 2, like tools/recomp_census.py. census() wraps the unchanged loop and names the line and the field; main() is split out so it can be tested. Synthetic traces only; no game files. --- tests/test_dstorage_census.py | 87 +++++++++++++++++++++++++++++++++++ tools/dstorage_census.py | 54 ++++++++++++++++++---- 2 files changed, 133 insertions(+), 8 deletions(-) create mode 100644 tests/test_dstorage_census.py diff --git a/tests/test_dstorage_census.py b/tests/test_dstorage_census.py new file mode 100644 index 0000000000..65efcbcc18 --- /dev/null +++ b/tests/test_dstorage_census.py @@ -0,0 +1,87 @@ +"""Unit tests for tools/dstorage_census.py: a wrong input is one ERROR line and exit 2, not a traceback. + +The traces are built by hand, so the test needs no game files and no third-party packages. + + python -I tests/test_dstorage_census.py +""" +import os +import subprocess +import sys +import tempfile +import unittest + +ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) +TOOLS_DIR = os.path.join(ROOT, "tools") +if TOOLS_DIR not in sys.path: + sys.path.insert(0, TOOLS_DIR) + +import dstorage_census as dc # noqa: E402 + +TOOL = os.path.join(TOOLS_DIR, "dstorage_census.py") +REQUEST = ("[rt] ds-request file=a.bin offset=0 dest=pages options=0 zlib=0 sw=0 src=16 dst=32 " + "hr=0 cancelled=0 tick_ms=5") + + +def run_tool(*args): + return subprocess.run([sys.executable, "-I", TOOL, *args], capture_output=True, text=True, + encoding="utf-8", errors="replace") + + +class CensusTest(unittest.TestCase): + def test_one_good_request_is_counted(self): + report = dc.census([REQUEST]) + self.assertEqual(report["totals"]["requests"], 1) + self.assertEqual(report["totals"]["successful"], 1) + self.assertEqual(report["totals"]["destination_bytes"], 32) + + def test_missing_field_names_the_line_and_the_field(self): + with self.assertRaises(dc.TraceError) as caught: + dc.census([REQUEST, "[rt] ds-request file=a.bin offset=0 options=0"]) + self.assertIn("line 2", str(caught.exception)) + self.assertIn("dest=", str(caught.exception)) + + def test_malformed_number_names_the_line(self): + with self.assertRaises(dc.TraceError) as caught: + dc.census([REQUEST.replace("options=0", "options=zz")]) + self.assertIn("line 1", str(caught.exception)) + self.assertIn("malformed number", str(caught.exception)) + + +class WrongInputTest(unittest.TestCase): + def assert_one_error_line(self, result): + self.assertEqual(result.returncode, 2, result.stderr) + self.assertNotIn("Traceback", result.stderr) + lines = result.stderr.strip().splitlines() + self.assertEqual(len(lines), 1, result.stderr) + self.assertTrue(lines[0].startswith("ERROR: "), result.stderr) + self.assertEqual(result.stdout, "") + + def test_missing_trace(self): + with tempfile.TemporaryDirectory() as tmp: + self.assert_one_error_line(run_tool(os.path.join(tmp, "no_such_trace.log"))) + + def test_folder_for_the_trace(self): + with tempfile.TemporaryDirectory() as tmp: + self.assert_one_error_line(run_tool(tmp)) + + def test_truncated_request_line(self): + with tempfile.TemporaryDirectory() as tmp: + path = os.path.join(tmp, "trace.log") + with open(path, "w", encoding="utf-8", newline="\n") as stream: + stream.write(REQUEST + "\n[rt] ds-request file=a.bin offset=0\n") + result = run_tool(path) + self.assert_one_error_line(result) + self.assertIn("line 2", result.stderr) + + def test_a_good_trace_still_prints_the_report_and_exits_zero(self): + with tempfile.TemporaryDirectory() as tmp: + path = os.path.join(tmp, "trace.log") + with open(path, "w", encoding="utf-8", newline="\n") as stream: + stream.write(REQUEST + "\n") + result = run_tool(path) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertIn('"requests": 1', result.stdout) + + +if __name__ == "__main__": + unittest.main() diff --git a/tools/dstorage_census.py b/tools/dstorage_census.py index 0d3fa7691b..496af9b327 100644 --- a/tools/dstorage_census.py +++ b/tools/dstorage_census.py @@ -1,4 +1,8 @@ -"""Summarize a local LEONIDA_DSTORAGE_TRACE=1 run in one pass (no filenames in the report).""" +"""Summarize a local LEONIDA_DSTORAGE_TRACE=1 run in one pass (no filenames in the report). + +A trace that cannot be read, or a ds-request line with a missing or malformed field, is one ERROR line and exit +code 2. +""" import argparse from collections import Counter, defaultdict import json @@ -6,7 +10,28 @@ import sys +class TraceError(Exception): + """A ds-request line the census cannot read: names the line and the field.""" + + def census(lines, from_file=None): + """Summarize the trace; a line with a missing or malformed field raises TraceError.""" + seen = [0] + + def counted(): + for line in lines: + seen[0] += 1 + yield line + + try: + return _census(counted(), from_file) + except KeyError as exc: + raise TraceError(f"line {seen[0]}: ds-request has no {exc.args[0]}=") from None + except ValueError as exc: + raise TraceError(f"line {seen[0]}: ds-request has a malformed number ({exc})") from None + + +def _census(lines, from_file=None): groups = defaultdict(Counter) errors = Counter() priorities = Counter() @@ -83,15 +108,28 @@ def census(lines, from_file=None): return result +def main(argv=None): + parser = argparse.ArgumentParser(description=__doc__) + parser.add_argument("trace") + parser.add_argument("--from-file", metavar="SUBSTRING", + help="start with the first matching source path, then include all queues and files") + args = parser.parse_args(argv) + try: + with open(args.trace, encoding="utf-8", errors="replace") as stream: + report = census(stream, args.from_file) + except OSError as exc: # a missing trace, a folder, no permission: one line, not a traceback + print(f"ERROR: {exc}", file=sys.stderr) + return 2 + except TraceError as exc: + print(f"ERROR: {args.trace}: {exc}", 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: pass - parser = argparse.ArgumentParser(description=__doc__) - parser.add_argument("trace") - parser.add_argument("--from-file", metavar="SUBSTRING", - help="start with the first matching source path, then include all queues and files") - args = parser.parse_args() - with open(args.trace, encoding="utf-8", errors="replace") as stream: - print(json.dumps(census(stream, args.from_file), indent=2, sort_keys=True)) + sys.exit(main())