"""Tests for tools/bink_index.py, built from synthetic Bink 2 headers (no game data). python -I tests/test_bink_index.py """ import contextlib import csv import importlib.util import io import json import os import struct import subprocess import tempfile import unittest from unittest import mock ROOT = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) def load_module(): path = os.path.join(ROOT, "tools", "bink_index.py") spec = importlib.util.spec_from_file_location("bink_index_under_test", path) module = importlib.util.module_from_spec(spec) spec.loader.exec_module(module) return module bink = load_module() def make_stream(revision="n", frames=4, width=320, height=240, audio=0, body=256, fps_num=30, fps_den=1): """A plausible Bink 2 stream: fixed header, audio metadata, frame table, payload.""" extra = b"\x00\x05\xe9\x87" if revision in "ijkn" else b"" audio_blob = b"" if audio: audio_blob += struct.pack(" 0) def test_temp_stream_cleanup_removes_file(self): src = os.path.join(self.dir, "one.bk2") name, cleanup = bink._temp_stream(src, 0, 100) self.assertTrue(os.path.exists(name)) cleanup() self.assertFalse(os.path.exists(name)) def test_publish_text_cleans_up_staged_file_when_replace_fails_even_if_readonly(self): path = os.path.join(self.dir, "report.json") with open(path, "w", encoding="utf-8") as fh: fh.write('{"initial": 1}\n') os.chmod(path, 0o444) real_unlink = os.unlink def windows_strict_unlink(p): mode = os.stat(p).st_mode if not (mode & 0o200): raise PermissionError(13, f"Access is denied: {p}") return real_unlink(p) with mock.patch.object(bink, "replace_retry", side_effect=OSError(13, "Permission denied")), \ mock.patch("os.unlink", side_effect=windows_strict_unlink): with self.assertRaises(OSError): bink.write_json(path, self.dir, [], {"streams": 0}, probe=False) leftover = [f for f in os.listdir(self.dir) if f.startswith(".bink_index-")] self.assertEqual(leftover, []) def test_publish_text_applies_published_mode_on_windows(self): path = os.path.join(self.dir, "report.csv") chmod_calls = [] real_chmod = os.chmod def track_chmod(p, mode): chmod_calls.append((p, mode)) real_chmod(p, mode) with mock.patch("os.name", "nt"), mock.patch("os.chmod", side_effect=track_chmod): bink.write_csv(path, [], probe=False) self.assertTrue(len(chmod_calls) > 0) class TestCommandLine(unittest.TestCase): def setUp(self): self.tmp = tempfile.TemporaryDirectory() self.path = os.path.join(self.tmp.name, "one.bk2") with open(self.path, "wb") as fh: fh.write(make_stream(frames=7)) def tearDown(self): self.tmp.cleanup() def test_validated_stream_produces_same_report(self): with open(self.path, "wb") as fh: fh.write(indexed_stream(audio=2)) for fmt in ("json", "csv"): outputs = [] for options in ([], ["--validate-frames"]): out, err = io.StringIO(), io.StringIO() with contextlib.redirect_stdout(out), contextlib.redirect_stderr(err): self.assertEqual(bink.main([self.path, "--format", fmt] + options), 0) self.assertEqual("Frame offsets validated: 3 (streams: 1)" in err.getvalue(), bool(options)) outputs.append(out.getvalue()) self.assertEqual(outputs[0], outputs[1]) def test_invalid_index_in_directory_preserves_existing_report(self): # The first stream is valid. The second has an all-zero index. first = indexed_stream() with open(self.path, "wb") as fh: fh.write(first) fh.write(make_stream()) report = os.path.join(self.tmp.name, "result.json") with open(report, "wb") as fh: fh.write(b"existing report") err, out = io.StringIO(), io.StringIO() with contextlib.redirect_stderr(err), contextlib.redirect_stdout(out): self.assertEqual(bink.main([self.tmp.name, "--validate-frames", "--out", report]), 2) self.assertIn(f"one.bk2 at {len(first)}: frame 0", err.getvalue()) self.assertEqual(out.getvalue(), "") with open(report, "rb") as fh: self.assertEqual(fh.read(), b"existing report") def test_csv_on_stdout_has_one_line_end_per_row(self): # A text stream that writes "\n" as "\r\n", as Windows' stdout does, on any platform. raw = io.BytesIO() out = io.TextIOWrapper(raw, encoding="utf-8", newline="\r\n") with contextlib.redirect_stdout(out), contextlib.redirect_stderr(io.StringIO()): self.assertEqual(bink.main([self.path]), 0) out.flush() data = raw.getvalue() self.assertNotIn(b"\r\r\n", data) rows = list(csv.reader(io.StringIO(data.decode("utf-8"), newline=""))) self.assertEqual(len(rows), 2) # header and the one stream, no blank rows self.assertEqual(rows[0][:len(bink.BASE_FIELDS)], bink.BASE_FIELDS) def test_missing_target_is_an_error_not_a_traceback(self): missing = os.path.join(self.tmp.name, "nonexistent.bk2") err = io.StringIO() with contextlib.redirect_stderr(err), contextlib.redirect_stdout(io.StringIO()): self.assertEqual(bink.main([missing]), 2) self.assertIn("no such file or directory", err.getvalue()) def test_a_named_file_that_is_not_a_stream_is_an_error(self): # The scan only looks for KB2 headers, so a wrong path used to be a successful scan of 0 streams. junk = os.path.join(self.tmp.name, "wrong-path.bin") with open(junk, "wb") as fh: fh.write(b"not a movie" * 64) err = io.StringIO() with contextlib.redirect_stderr(err), contextlib.redirect_stdout(io.StringIO()): self.assertEqual(bink.main([junk]), 2) self.assertEqual(err.getvalue().splitlines(), [f"bink_index: error: {junk}: not a Bink 2 stream (KB2) or an RPF archive"]) def test_an_empty_named_file_is_an_error(self): empty = os.path.join(self.tmp.name, "empty.bk2") with open(empty, "wb"): pass err = io.StringIO() with contextlib.redirect_stderr(err), contextlib.redirect_stdout(io.StringIO()): self.assertEqual(bink.main([empty]), 2) self.assertEqual(err.getvalue().splitlines(), [f"bink_index: error: {empty}: empty file"]) def test_a_named_rpf_without_a_stream_still_scans(self): # An archive that holds no movie is a real answer, not a wrong path. archive = os.path.join(self.tmp.name, "empty-movies.rpf") with open(archive, "wb") as fh: fh.write(b"9FPR" + struct.pack("/index.json is the carve manifest's name even before a carve has written it. carve = os.path.join(self.tmp.name, "carve_no_manifest") os.makedirs(carve, exist_ok=True) manifest = os.path.join(carve, "index.json") err = io.StringIO() with contextlib.redirect_stderr(err), contextlib.redirect_stdout(io.StringIO()): with self.assertRaises(SystemExit) as cm: bink.main([carve, "--out", manifest]) self.assertEqual(cm.exception.code, 2) self.assertIn("would overwrite the carve manifest", err.getvalue()) self.assertFalse(os.path.exists(manifest)) def test_output_cannot_overwrite_carve_manifest(self): carve = os.path.join(self.tmp.name, "carve") os.makedirs(carve, exist_ok=True) manifest = os.path.join(carve, "index.json") with open(manifest, "w", encoding="utf-8") as f: f.write('{"carve_manifest": true}') err = io.StringIO() with contextlib.redirect_stderr(err), contextlib.redirect_stdout(io.StringIO()): with self.assertRaises(SystemExit) as cm: bink.main([carve, "--out", manifest]) self.assertEqual(cm.exception.code, 2) self.assertIn("would overwrite the carve manifest", err.getvalue()) with open(manifest, "r", encoding="utf-8") as f: self.assertEqual(f.read(), '{"carve_manifest": true}') def test_output_cannot_overwrite_a_carved_input(self): carve = os.path.join(self.tmp.name, "carve2") os.makedirs(carve, exist_ok=True) payload = os.path.join(carve, "00000001.bin") with open(payload, "wb") as f: f.write(make_stream()) linked = os.path.join(carve, "linked.json") # a .json alias of the .bin input try: os.link(payload, linked) except OSError: self.skipTest("hard links are not available") err = io.StringIO() with contextlib.redirect_stderr(err), contextlib.redirect_stdout(io.StringIO()): with self.assertRaises(SystemExit) as cm: bink.main([carve, "--out", linked]) self.assertEqual(cm.exception.code, 2) self.assertIn("would overwrite an input file", err.getvalue()) with open(payload, "rb") as f: self.assertEqual(f.read(), make_stream()) def test_output_folder_is_rejected(self): err = io.StringIO() with contextlib.redirect_stderr(err), contextlib.redirect_stdout(io.StringIO()): with self.assertRaises(SystemExit) as cm: bink.main([self.path, "--out", self.tmp.name]) self.assertEqual(cm.exception.code, 2) self.assertIn("is a folder, not a report file", err.getvalue()) def test_repeat_run_produces_identical_summary(self): # A directory with one stream and a chosen report.json: the second run # must not inflate files_scanned/span/unread bytes by scanning the report. work = os.path.join(self.tmp.name, "movies") os.makedirs(work) with open(os.path.join(work, "one.bk2"), "wb") as fh: fh.write(make_stream(frames=11)) report = os.path.join(work, "report.json") summaries = [] for _ in range(2): with contextlib.redirect_stdout(io.StringIO()), \ contextlib.redirect_stderr(io.StringIO()): self.assertEqual(bink.main([work, "--out", report, "--format", "json"]), 0) with open(report, encoding="utf-8") as fh: summaries.append(json.load(fh)["summary"]) self.assertEqual(summaries[0], summaries[1]) self.assertEqual(summaries[0]["files_scanned"], 1) self.assertEqual(summaries[0]["streams"], 1) def test_a_single_named_file_that_is_not_a_stream_or_rpf_is_refused(self): path = os.path.join(self.tmp.name, "junk.bin") with open(path, "wb") as fh: fh.write(b"not a movie" * 64) out = os.path.join(self.tmp.name, "index.json") err = io.StringIO() with contextlib.redirect_stderr(err), contextlib.redirect_stdout(io.StringIO()): self.assertEqual(bink.main([path, "--out", out]), 2) self.assertIn("not a Bink 2 stream (KB2) or an RPF archive", err.getvalue()) self.assertNotIn("Traceback", err.getvalue()) self.assertFalse(os.path.exists(out)) def test_a_scanned_directory_with_no_stream_still_reports_empty(self): # The refusal is for one named file: an empty folder scan is a valid "0 streams" answer. folder = os.path.join(self.tmp.name, "movies") os.makedirs(folder, exist_ok=True) with open(os.path.join(folder, "notes.bin"), "wb") as fh: fh.write(b"not a movie" * 64) err = io.StringIO() out = io.StringIO() with contextlib.redirect_stderr(err), contextlib.redirect_stdout(out): self.assertEqual(bink.main([folder]), 0) self.assertIn("0 Bink 2 streams", err.getvalue()) self.assertTrue(out.getvalue().splitlines()) def test_an_rpf_archive_with_no_stream_is_still_indexed(self): # A named file with an RPF header is an archive, even if it holds no Bink 2 stream. path = os.path.join(self.tmp.name, "empty.rpf") with open(path, "wb") as fh: fh.write(b"9FPR" + struct.pack("