Files
mandy/tests/test_audio_config.py
bbareth 166eeee2a0 audio_config.py: a missing source or unreadable input is one line
A missing source went through files_in() as a folder and ended in a
FileNotFoundError traceback from os.listdir. A --names pool that is
missing or a folder, and a stream that can't be read, ended the same
way. Each now exits through sys.exit() with one line naming the path,
like the tool's existing "no audio-config records found" message.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-11-22 01:52:45 +01:00

167 lines
7.5 KiB
Python

"""Synthetic tests for tools/audio_config.py (no game data)."""
import json
import os
import struct
import subprocess
import sys
import tempfile
import unittest
from unittest.mock import patch
ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
TOOL = os.path.join(ROOT, "tools", "audio_config.py")
sys.path.insert(0, os.path.join(ROOT, "tools"))
import audio_config as A # noqa: E402
def make_record(config_id, duration_ms, hash_a=0x11111111, hash_b=0x22222222, tail=b"\x00" * 22):
"""One 46-byte record: duration, then the marker block at +4."""
b = bytearray(46)
struct.pack_into("<I", b, 0, duration_ms)
b[4:6] = b"\x0c\x01"
struct.pack_into("<H", b, 6, config_id)
b[8:12] = b"\x02\x00\x0c\x00"
struct.pack_into("<I", b, 12, hash_a)
struct.pack_into("<I", b, 16, hash_b)
b[20:24] = b"\x00\x00\x02\x23"
b[24:24 + len(tail)] = tail
return bytes(b)
class TestHash(unittest.TestCase):
def test_joaat_vectors(self):
self.assertEqual(A.joaat("test"), 0x3F75CCC1)
self.assertEqual(A.joaat("Radio_Test"), 0xE663FCAE)
self.assertEqual(A.joaat(""), 0)
def test_normalized_name(self):
self.assertEqual(A.normalized_name("Hello, World!"), "hello_world")
self.assertEqual(A.normalized_name("A.B-C"), "a_b_c")
self.assertEqual(A.normalized_name("Already_ok"), "already_ok")
def test_title_stream_id(self):
title = "Hello, World!"
self.assertEqual(A.title_stream_id(title), A.joaat("hello_world") & A.STREAM_MASK)
self.assertEqual(A.title_stream_id("Test Song"),
A.joaat(A.normalized_name("Test Song")) & A.STREAM_MASK)
class TestScan(unittest.TestCase):
def test_single_record(self):
blob = b"\x00\x00\x00\x00" + make_record(0xB422, 264_091, 0x49FC8153, 0xDAA8AC2F)
got = A.scan(blob)
self.assertEqual(len(got), 1)
self.assertEqual(got[0]["id"], 0xB422)
self.assertEqual(got[0]["duration_ms"], 264_091)
self.assertEqual(got[0]["duration_s"], 264.091)
self.assertEqual(got[0]["hash_a"], 0x49FC8153)
self.assertEqual(got[0]["hash_b"], 0xDAA8AC2F)
self.assertEqual(got[0]["stream_id"], 0xDAA8AC2F & A.STREAM_MASK)
self.assertEqual(got[0]["offset"], 8)
def test_two_adjacent_records(self):
blob = b"\x00" * 4 + make_record(0x1000, 100_000) + make_record(0x1001, 200_000)
got = A.scan(blob)
self.assertEqual([r["id"] for r in got], [0x1000, 0x1001])
self.assertEqual([r["offset"] for r in got], [8, 54])
def test_rejects_bad_marker_and_duration(self):
wrong_marker = bytearray(make_record(0x1000, 100_000))
wrong_marker[8] = 0
low = make_record(0x1001, 1_000)
high = make_record(0x1002, 3_000_000)
blob = b"\x00" * 4 + bytes(wrong_marker) + low + high
self.assertEqual(A.scan(blob), [])
def test_truncated_record(self):
# A partial record (marker present, third marker cut off) must not be reported.
blob = b"\x00" * 4 + make_record(0x1000, 100_000)[:22]
self.assertEqual(A.scan(blob), [])
def test_join_across_streams(self):
# A zlib block boundary can split a record. Split before the third marker ends.
record = make_record(0x3000, 150_000)
with tempfile.TemporaryDirectory() as tmp:
with open(os.path.join(tmp, "00000001.bin"), "wb") as f:
f.write(b"\x00" * 4 + record[:22])
with open(os.path.join(tmp, "00000002.bin"), "wb") as f:
f.write(record[22:])
self.assertEqual(len(A.collect(tmp)), 0)
self.assertEqual(len(A.collect(tmp, join=True)), 1)
def test_non_joined_scan_processes_each_blob_before_reading_the_next(self):
def parts(_src):
yield "first.bin", make_record(0x1000, 100_000)
self.assertEqual(scan.call_count, 1)
yield "second.bin", make_record(0x1001, 200_000)
with patch.object(A, "files_in", parts), patch.object(A, "scan", wraps=A.scan) as scan:
rows = A.collect("unused")
self.assertEqual([(row["file"], row["id"]) for row in rows],
[("first.bin", 0x1000), ("second.bin", 0x1001)])
def test_join_marker_at_stream_boundary_uses_the_file_containing_it(self):
record = make_record(0x3000, 150_000)
name = "\U0001f3b5.bin"
with tempfile.TemporaryDirectory() as tmp:
for filename, data in (("a.bin", record[:4]), ("b.bin", b""), (name, record[4:])):
with open(os.path.join(tmp, filename), "wb") as f:
f.write(data)
rows = A.collect(tmp, join=True)
self.assertEqual([(row["offset"], row["file"]) for row in rows], [(4, name)])
class TestCli(unittest.TestCase):
def test_missing_or_unreadable_inputs_are_one_line(self):
with tempfile.TemporaryDirectory() as tmp:
blob = os.path.join(tmp, "00000001.bin")
with open(blob, "wb") as f:
f.write(b"\x00" * 4 + make_record(0x2000, 123_456))
missing = os.path.join(tmp, "missing")
cases = (([missing], missing, "does not exist"),
([tmp, "--names", os.path.join(tmp, "no_pool.txt")], "no_pool.txt", "name pool"),
([tmp, "--names", tmp], tmp, "name pool")) # a folder as the pool
for args, path, message in cases:
with self.subTest(message=message, args=[os.path.basename(x) for x in args]):
p = subprocess.run([sys.executable, "-I", TOOL, *args], capture_output=True, text=True)
self.assertEqual(p.returncode, 1)
self.assertIn(path, p.stderr)
self.assertIn(message, p.stderr)
self.assertNotIn("Traceback", p.stderr)
self.assertEqual(p.stdout, "")
def test_unreadable_stream_is_one_line(self):
with tempfile.TemporaryDirectory() as tmp:
with open(os.path.join(tmp, "00000001.bin"), "wb") as f:
f.write(b"\x00" * 4 + make_record(0x2000, 123_456))
denied = PermissionError(13, "Permission denied", os.path.join(tmp, "00000001.bin"))
with patch.object(sys, "argv", ["audio_config.py", tmp]), \
patch.object(A, "collect", side_effect=denied), self.assertRaises(SystemExit) as ctx:
A.main()
self.assertIn("00000001.bin: cannot read: Permission denied", str(ctx.exception.code))
def test_json_and_names(self):
with tempfile.TemporaryDirectory() as tmp:
name = "Test Song"
hb = A.joaat(A.normalized_name(name))
blob = b"\x00" * 4 + make_record(0x2000, 123_456, hash_b=hb)
with open(os.path.join(tmp, "00000001.bin"), "wb") as f:
f.write(blob)
pool = os.path.join(tmp, "names.txt")
with open(pool, "wb") as f:
f.write(name.encode() + b"\x00Other\x00")
p = subprocess.run([sys.executable, "-I", TOOL, tmp, "--json", "--names", pool],
capture_output=True, text=True)
self.assertEqual(p.returncode, 0, p.stderr)
doc = json.loads(p.stdout)
self.assertEqual(doc["summary"]["records"], 1)
self.assertEqual(doc["summary"]["distinct_ids"], 1)
self.assertEqual(doc["summary"]["named"], 1)
self.assertEqual(doc["records"][0]["name"], name)
self.assertEqual(doc["records"][0]["stream_id"], hb & A.STREAM_MASK)
if __name__ == "__main__":
unittest.main()