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.
This commit is contained in:
levi2m
2026-11-24 23:20:50 -03:00
parent 3ff2a2adcd
commit a5fbe68937
2 changed files with 133 additions and 8 deletions

View File

@ -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()

View File

@ -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 re
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())