diff --git a/scripts/resolve/nativemode.py b/scripts/resolve/nativemode.py index 0afacdc15..7e2b70ac6 100644 --- a/scripts/resolve/nativemode.py +++ b/scripts/resolve/nativemode.py @@ -25,7 +25,7 @@ from __future__ import annotations DEFAULT_MODE = "existence" #: Every verification mode a platform YAML may declare. Mirrors the enum in -#: schemas/platform.schema.json, and tests/test_audit_regressions.py pins them +#: schemas/platform.schema.json, and tests/test_native_mode.py pins them #: together so a new mode cannot be added to one without the other. MODES = ("existence", "md5", "sha1") diff --git a/scripts/run_tests.py b/scripts/run_tests.py index e456b6ff6..0c8308e82 100644 --- a/scripts/run_tests.py +++ b/scripts/run_tests.py @@ -4,7 +4,7 @@ Usage: python scripts/run_tests.py # every module, a few at a time python scripts/run_tests.py --jobs 1 # one at a time, as discover runs - python scripts/run_tests.py tests.test_install tests.test_e2e + python scripts/run_tests.py tests.test_install tests.test_e2e_region unittest's discovery runs 8,500 tests in one process: about 40 minutes here and 85 on the CI runner, and a module that left a variable or a flag diff --git a/tests/auditsupport.py b/tests/auditsupport.py new file mode 100644 index 000000000..1198ef951 --- /dev/null +++ b/tests/auditsupport.py @@ -0,0 +1,18 @@ +"""Constants shared by the audit regression suites.""" + +from __future__ import annotations + +import tests +from pathlib import Path + + +try: + import jsonschema +except ImportError: + jsonschema = None + + +HAS_JSONSCHEMA = jsonschema is not None + + +ROOT = Path(__file__).resolve().parent.parent diff --git a/tests/e2esupport.py b/tests/e2esupport.py new file mode 100644 index 000000000..a29ef95f4 --- /dev/null +++ b/tests/e2esupport.py @@ -0,0 +1,699 @@ +"""Shared synthetic scenario of the end-to-end suites: BIOS files, database, platforms and profiles.""" + +from __future__ import annotations + +import tests +import hashlib +import os +import shutil +import tempfile +import unittest +import zipfile +import yaml + + +def _h(data: bytes) -> dict: + """Return sha1, md5, crc32 for test data.""" + return { + "sha1": hashlib.sha1(data).hexdigest(), + "md5": hashlib.md5(data).hexdigest(), + "crc32": format(hashlib.new("crc32", data).digest()[0], "08x") + if False + else "", # not needed for tests + } + + +class E2EFixture(unittest.TestCase): + """One synthetic repository exercising every code path, rebuilt for each test.""" + + # --------------------------------------------------------------- + # Fixture setup + # --------------------------------------------------------------- + + def setUp(self): + # Clear emulator profile cache to avoid stale data between tests + from model.profiles import emulator_profiles_cache + + emulator_profiles_cache.clear() + + self.root = tempfile.mkdtemp() + self.bios_dir = os.path.join(self.root, "bios") + self.platforms_dir = os.path.join(self.root, "platforms") + self.emulators_dir = os.path.join(self.root, "emulators") + os.makedirs(self.bios_dir) + os.makedirs(self.platforms_dir) + os.makedirs(self.emulators_dir) + + # -- Create synthetic BIOS files -- + self.files = {} + self._make_file("present_req.bin", b"PRESENT_REQUIRED") + self._make_file("present_opt.bin", b"PRESENT_OPTIONAL") + self._make_file("correct_hash.bin", b"CORRECT_HASH_DATA") + self._make_file("wrong_hash.bin", b"WRONG_CONTENT_ON_DISK") + self._make_file("no_md5.bin", b"NO_MD5_CHECK") + self._make_file("truncated.bin", b"BATOCERA_TRUNCATED") + self._make_file("alias_target.bin", b"ALIAS_FILE_DATA") + self._make_file( + "leading_zero_crc.bin", b"LEADING_ZERO_CRC_12" + ) # crc32=0179e92e + + # Regional variant files (same name, different content, in subdirs) + os.makedirs(os.path.join(self.bios_dir, "TestConsole", "USA"), exist_ok=True) + os.makedirs(os.path.join(self.bios_dir, "TestConsole", "EUR"), exist_ok=True) + self._make_file("BIOS.bin", b"BIOS_USA_CONTENT", subdir="TestConsole/USA") + self._make_file("BIOS.bin", b"BIOS_EUR_CONTENT", subdir="TestConsole/EUR") + + # .variants/ file (should be deprioritized) + variants_dir = os.path.join(self.bios_dir, ".variants") + os.makedirs(variants_dir) + self._make_file("present_req.bin", b"VARIANT_DATA", subdir=".variants") + + # ZIP with correct inner ROM + self._make_zip("good.zip", {"inner.rom": b"GOOD_INNER_ROM"}) + # ZIP with wrong inner ROM + self._make_zip("bad_inner.zip", {"inner.rom": b"BAD_INNER"}) + # ZIP with missing inner ROM name + self._make_zip("missing_inner.zip", {"other.rom": b"OTHER_ROM"}) + # ZIP for md5_composite (Recalbox) + self._make_zip("composite.zip", {"b.rom": b"BBBB", "a.rom": b"AAAA"}) + # ZIP for multi-hash + self._make_zip("multi.zip", {"rom.bin": b"MULTI_HASH_DATA"}) + # Archive BIOS ZIP (like neogeo.zip) containing multiple ROMs + self._make_zip( + "test_archive.zip", + { + "rom_a.bin": b"ARCHIVE_ROM_A", + "rom_b.bin": b"ARCHIVE_ROM_B", + }, + ) + + # -- Build synthetic database -- + self.db = self._build_db() + + # -- Create platform YAMLs -- + self._create_existence_platform() + self._create_md5_platform() + self._create_shared_groups() + self._create_inherited_platform() + self._create_sha1_platform() + + # -- Create emulator YAMLs -- + self._create_emulator_profiles() + + def tearDown(self): + shutil.rmtree(self.root) + + # --------------------------------------------------------------- + # File helpers + # --------------------------------------------------------------- + + def _make_file(self, name: str, data: bytes, subdir: str = "") -> str: + d = os.path.join(self.bios_dir, subdir) if subdir else self.bios_dir + os.makedirs(d, exist_ok=True) + path = os.path.join(d, name) + with open(path, "wb") as f: + f.write(data) + h = _h(data) + self.files[f"{subdir}/{name}" if subdir else name] = { + "path": path, + "data": data, + **h, + } + return path + + def _make_zip(self, name: str, contents: dict[str, bytes]) -> str: + path = os.path.join(self.bios_dir, name) + with zipfile.ZipFile(path, "w") as zf: + for fname, data in contents.items(): + zf.writestr(fname, data) + with open(path, "rb") as f: + zdata = f.read() + h = _h(zdata) + inner_md5s = {fn: hashlib.md5(d).hexdigest() for fn, d in contents.items()} + self.files[name] = {"path": path, "data": zdata, "inner_md5s": inner_md5s, **h} + return path + + def _build_db(self) -> dict: + files_db = {} + by_md5 = {} + by_name: dict[str, list[str]] = {} + for key, info in self.files.items(): + name = os.path.basename(key) + sha1 = info["sha1"] + files_db[sha1] = { + "path": info["path"], + "md5": info["md5"], + "name": name, + "crc32": info.get("crc32", ""), + "size": len(info["data"]), + } + by_md5[info["md5"]] = sha1 + by_name.setdefault(name, []).append(sha1) + # Add alias name to by_name + alias_sha1 = self.files["alias_target.bin"]["sha1"] + by_name.setdefault("alias_alt.bin", []).append(alias_sha1) + # Build by_path_suffix for regional variant resolution + by_path_suffix: dict[str, list[str]] = {} + for key, info in self.files.items(): + if "/" in key: + # key is subdir/name, suffix is the subdir path + by_path_suffix.setdefault(key, []).append(info["sha1"]) + return { + "files": files_db, + "indexes": { + "by_md5": by_md5, + "by_name": by_name, + "by_crc32": {}, + "by_path_suffix": by_path_suffix, + }, + } + + # --------------------------------------------------------------- + # Platform YAML creators + # --------------------------------------------------------------- + + def _create_existence_platform(self): + config = { + "platform": "TestExistence", + "version": "9.1", + "verification_mode": "existence", + "base_destination": "system", + "systems": { + "console-a": { + "files": [ + { + "name": "present_req.bin", + "destination": "present_req.bin", + "required": True, + }, + { + "name": "missing_req.bin", + "destination": "missing_req.bin", + "required": True, + }, + { + "name": "present_opt.bin", + "destination": "present_opt.bin", + "required": False, + }, + { + "name": "missing_opt.bin", + "destination": "missing_opt.bin", + "required": False, + }, + ], + }, + }, + } + with open(os.path.join(self.platforms_dir, "test_existence.yml"), "w") as fh: + yaml.dump(config, fh) + + def _create_md5_platform(self): + f = self.files + good_inner_md5 = f["good.zip"]["inner_md5s"]["inner.rom"] + bad_inner_md5 = "deadbeefdeadbeefdeadbeefdeadbeef" + composite_md5 = hashlib.md5( + b"AAAA" + b"BBBB" + ).hexdigest() # sorted: a.rom, b.rom + multi_wrong = "0000000000000000000000000000000" + multi_right = f["multi.zip"]["inner_md5s"]["rom.bin"] + truncated_md5 = f["truncated.bin"]["md5"][:29] # shorter than 32 characters + + config = { + "platform": "TestMD5", + "verification_mode": "md5", + "systems": { + "sys-md5": { + "includes": ["test_shared"], + "files": [ + # Correct hash + { + "name": "correct_hash.bin", + "destination": "correct_hash.bin", + "md5": f["correct_hash.bin"]["md5"], + "required": True, + }, + # Wrong hash on disk ->untested + { + "name": "wrong_hash.bin", + "destination": "wrong_hash.bin", + "md5": "ffffffffffffffffffffffffffffffff", + "required": True, + }, + # No MD5 ->OK (existence within md5 platform) + { + "name": "no_md5.bin", + "destination": "no_md5.bin", + "required": False, + }, + # Missing required + { + "name": "gone_req.bin", + "destination": "gone_req.bin", + "md5": "abcd", + "required": True, + }, + # Missing optional + { + "name": "gone_opt.bin", + "destination": "gone_opt.bin", + "md5": "abcd", + "required": False, + }, + # zipped_file correct + { + "name": "good.zip", + "destination": "good.zip", + "md5": good_inner_md5, + "zipped_file": "inner.rom", + "required": True, + }, + # zipped_file wrong inner + { + "name": "bad_inner.zip", + "destination": "bad_inner.zip", + "md5": bad_inner_md5, + "zipped_file": "inner.rom", + "required": False, + }, + # zipped_file inner not found + { + "name": "missing_inner.zip", + "destination": "missing_inner.zip", + "md5": "abc", + "zipped_file": "nope.rom", + "required": False, + }, + # md5_composite (Recalbox) + { + "name": "composite.zip", + "destination": "composite.zip", + "md5": composite_md5, + "required": True, + }, + # Multi-hash comma-separated (Recalbox) + { + "name": "multi.zip", + "destination": "multi.zip", + "md5": f"{multi_wrong},{multi_right}", + "zipped_file": "rom.bin", + "required": True, + }, + # MD5 shorter than 32 characters + { + "name": "truncated.bin", + "destination": "truncated.bin", + "md5": truncated_md5, + "required": True, + }, + # Same destination from different entry ->worst status wins + { + "name": "correct_hash.bin", + "destination": "dedup_target.bin", + "md5": f["correct_hash.bin"]["md5"], + "required": True, + }, + { + "name": "correct_hash.bin", + "destination": "dedup_target.bin", + "md5": "wrong_for_dedup_test", + "required": True, + }, + ], + "data_directories": [ + {"ref": "test-data-dir", "destination": "TestData"}, + ], + }, + "sys-renamed": { + "files": [ + { + "name": "renamed_file.bin", + "destination": "renamed_file.bin", + "md5": f["correct_hash.bin"]["md5"], + "required": True, + }, + ], + }, + }, + } + with open(os.path.join(self.platforms_dir, "test_md5.yml"), "w") as fh: + yaml.dump(config, fh) + + def _create_shared_groups(self): + shared = { + "shared_groups": { + "test_shared": [ + { + "name": "shared_file.rom", + "destination": "shared_file.rom", + "required": False, + }, + ], + }, + } + with open(os.path.join(self.platforms_dir, "_shared.yml"), "w") as fh: + yaml.dump(shared, fh) + + def _create_inherited_platform(self): + child = { + "inherits": "test_existence", + "platform": "TestInherited", + "base_destination": "BIOS", + } + with open(os.path.join(self.platforms_dir, "test_inherited.yml"), "w") as fh: + yaml.dump(child, fh) + + def _create_sha1_platform(self): + f = self.files + config = { + "platform": "TestSHA1", + "verification_mode": "sha1", + "base_destination": "system", + "systems": { + "sys-sha1": { + "files": [ + { + "name": "correct_hash.bin", + "destination": "correct_hash.bin", + "sha1": f["correct_hash.bin"]["sha1"], + "required": True, + }, + { + "name": "wrong_hash.bin", + "destination": "wrong_hash.bin", + "sha1": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", + "required": True, + }, + { + "name": "missing_sha1.bin", + "destination": "missing_sha1.bin", + "sha1": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", + "required": True, + }, + { + "name": "optional_missing_sha1.bin", + "destination": "optional_missing_sha1.bin", + "sha1": "cccccccccccccccccccccccccccccccccccccccc", + "required": False, + }, + { + "name": "no_md5.bin", + "destination": "no_md5.bin", + "required": True, + }, + ], + }, + }, + } + with open(os.path.join(self.platforms_dir, "test_sha1.yml"), "w") as fh: + yaml.dump(config, fh) + + def _create_emulator_profiles(self): + # Regular emulator with aliases, standalone file, undeclared file + emu = { + "emulator": "TestEmu", + "type": "standalone + libretro", + "systems": ["console-a", "sys-md5"], + "data_directories": [{"ref": "test-data-dir"}], + "files": [ + {"name": "present_req.bin", "required": True}, + { + "name": "alias_target.bin", + "required": False, + "aliases": ["alias_alt.bin"], + }, + { + "name": "standalone_only.bin", + "required": False, + "mode": "standalone", + }, + {"name": "undeclared_req.bin", "required": True}, + {"name": "undeclared_opt.bin", "required": False}, + ], + } + with open(os.path.join(self.emulators_dir, "test_emu.yml"), "w") as fh: + yaml.dump(emu, fh) + + # Emulator with HLE fallback + emu_hle = { + "emulator": "TestHLE", + "type": "libretro", + "systems": ["console-a"], + "files": [ + {"name": "present_req.bin", "required": True, "hle_fallback": True}, + {"name": "hle_missing.bin", "required": True, "hle_fallback": True}, + {"name": "no_hle_missing.bin", "required": True, "hle_fallback": False}, + ], + } + with open(os.path.join(self.emulators_dir, "test_hle.yml"), "w") as fh: + yaml.dump(emu_hle, fh) + + # Launcher profile (should be excluded from cross-reference) + launcher = { + "emulator": "TestLauncher", + "type": "launcher", + "systems": ["console-a"], + "files": [{"name": "launcher_bios.bin", "required": True}], + } + with open(os.path.join(self.emulators_dir, "test_launcher.yml"), "w") as fh: + yaml.dump(launcher, fh) + + # Alias profile (should be skipped) + alias = { + "emulator": "TestAlias", + "type": "alias", + "alias_of": "test_emu", + "files": [], + } + with open(os.path.join(self.emulators_dir, "test_alias.yml"), "w") as fh: + yaml.dump(alias, fh) + + # Emulator with data_dir that matches platform ->gaps suppressed + emu_dd = { + "emulator": "TestEmuDD", + "type": "libretro", + "systems": ["sys-md5"], + "data_directories": [{"ref": "test-data-dir"}], + "files": [ + {"name": "dd_covered.bin", "required": False}, + ], + } + with open(os.path.join(self.emulators_dir, "test_emu_dd.yml"), "w") as fh: + yaml.dump(emu_dd, fh) + + # Emulator with archived files (like FBNeo with neogeo.zip) + emu_archive = { + "emulator": "TestArchiveEmu", + "type": "libretro", + "systems": ["console-a"], + "files": [ + {"name": "rom_a.bin", "required": True, "archive": "test_archive.zip"}, + {"name": "rom_b.bin", "required": False, "archive": "test_archive.zip"}, + { + "name": "missing_rom.bin", + "required": True, + "archive": "missing_archive.zip", + }, + ], + } + with open(os.path.join(self.emulators_dir, "test_archive_emu.yml"), "w") as fh: + yaml.dump(emu_archive, fh) + + # Emulator with descriptive name and path (like QEMU SeaBIOS) + emu_descriptive = { + "emulator": "TestDescriptive", + "type": "libretro", + "systems": ["console-a"], + "files": [ + { + "name": "Descriptive BIOS Name", + "required": True, + "path": "present_req.bin", + }, + { + "name": "Missing Descriptive", + "required": True, + "path": "nonexistent_path.bin", + }, + ], + } + with open(os.path.join(self.emulators_dir, "test_descriptive.yml"), "w") as fh: + yaml.dump(emu_descriptive, fh) + + # Emulator with validation checks (size, crc32) + emu_val = { + "emulator": "TestValidation", + "type": "libretro", + "systems": ["console-a", "sys-md5"], + "files": [ + # Size validation: correct size (16 bytes = len(b"PRESENT_REQUIRED")) + { + "name": "present_req.bin", + "required": True, + "validation": ["size"], + "size": 16, + "source_ref": "test.c:10-20", + }, + # Size validation: wrong expected size + { + "name": "present_opt.bin", + "required": False, + "validation": ["size"], + "size": 9999, + }, + # CRC32 validation: correct crc32 + { + "name": "correct_hash.bin", + "required": True, + "validation": ["crc32"], + "crc32": "91d0b1d3", + "source_ref": "hash.c:42", + }, + # CRC32 validation: wrong crc32 + { + "name": "no_md5.bin", + "required": False, + "validation": ["crc32"], + "crc32": "deadbeef", + }, + # CRC32 starting with '0' (regression: lstrip("0x") bug) + { + "name": "leading_zero_crc.bin", + "required": True, + "validation": ["crc32"], + "crc32": "0179e92e", + }, + # MD5 validation: correct md5 + { + "name": "correct_hash.bin", + "required": True, + "validation": ["md5"], + "md5": "4a8db431e3b1a1acacec60e3424c4ce8", + }, + # SHA1 validation: correct sha1 + { + "name": "correct_hash.bin", + "required": True, + "validation": ["sha1"], + "sha1": "a2ab6c95c5bbd191b9e87e8f4e85205a47be5764", + }, + # MD5 validation: wrong md5 + { + "name": "alias_target.bin", + "required": False, + "validation": ["md5"], + "md5": "0000000000000000000000000000dead", + }, + # Adler32: known_hash_adler32 field + { + "name": "present_req.bin", + "required": True, + "known_hash_adler32": None, + }, # placeholder, set below + # Min/max size range validation + { + "name": "present_req.bin", + "required": True, + "validation": ["size"], + "min_size": 10, + "max_size": 100, + }, + # Signature: crypto check we can't reproduce, but size applies + { + "name": "correct_hash.bin", + "required": True, + "validation": ["size", "signature"], + "size": 17, + }, + ], + } + # Compute the actual adler32 of present_req.bin for the test fixture + import zlib as _zlib + + with open(self.files["present_req.bin"]["path"], "rb") as _f: + _data = _f.read() + _adler = format(_zlib.adler32(_data) & 0xFFFFFFFF, "08x") + # Set the adler32 entry (the one with known_hash_adler32=None) + for entry in emu_val["files"]: + if ( + entry.get("known_hash_adler32") is None + and "known_hash_adler32" in entry + ): + entry["known_hash_adler32"] = f"0x{_adler}" + break + with open(os.path.join(self.emulators_dir, "test_validation.yml"), "w") as fh: + yaml.dump(emu_val, fh) + + # Emulator A: declares present_req.bin at root (no path) + emu_root = { + "emulator": "TestRootCore", + "type": "libretro", + "systems": ["console-a"], + "files": [ + {"name": "present_req.bin", "required": True}, + ], + } + with open(os.path.join(self.emulators_dir, "test_root_core.yml"), "w") as fh: + yaml.dump(emu_root, fh) + + # Emulator B: declares same file at a subdirectory path + emu_subdir = { + "emulator": "TestSubdirCore", + "type": "libretro", + "systems": ["console-a"], + "files": [ + { + "name": "present_req.bin", + "required": True, + "path": "subcore/bios/present_req.bin", + }, + ], + } + with open(os.path.join(self.emulators_dir, "test_subdir_core.yml"), "w") as fh: + yaml.dump(emu_subdir, fh) + + # Emulator whose file is declared by platform under a different name + # (e.g. gsplus ROM vs Batocera ROM1): hash-based matching should resolve + emu_renamed = { + "emulator": "TestRenamed", + "type": "standalone", + "systems": ["sys-renamed"], + "files": [ + {"name": "correct_hash.bin", "required": True}, + ], + } + with open(os.path.join(self.emulators_dir, "test_renamed.yml"), "w") as fh: + yaml.dump(emu_renamed, fh) + + # Agnostic profile (bios_mode: agnostic), skipped by find_undeclared_files + emu_agnostic = { + "emulator": "TestAgnostic", + "type": "standalone", + "bios_mode": "agnostic", + "systems": ["console-a"], + "files": [ + { + "name": "correct_hash.bin", + "required": True, + "min_size": 1, + "max_size": 999999, + }, + ], + } + with open(os.path.join(self.emulators_dir, "test_agnostic.yml"), "w") as fh: + yaml.dump(emu_agnostic, fh) + + # Mixed profile with per-file agnostic + emu_mixed_agnostic = { + "emulator": "TestMixedAgnostic", + "type": "libretro", + "systems": ["console-a"], + "files": [ + {"name": "undeclared_req.bin", "required": True}, + {"name": "agnostic_file.bin", "required": True, "agnostic": True}, + ], + } + with open( + os.path.join(self.emulators_dir, "test_mixed_agnostic.yml"), "w" + ) as fh: + yaml.dump(emu_mixed_agnostic, fh) diff --git a/tests/test_audit_cli.py b/tests/test_audit_cli.py new file mode 100644 index 000000000..c0e054f66 --- /dev/null +++ b/tests/test_audit_cli.py @@ -0,0 +1,1354 @@ +"""Audit regressions on the command line tools and the pipeline: flags, refusals, exits and summaries.""" + +from __future__ import annotations + +import tests +from tests.sources import script_source +import ast +import contextlib +import io +import json +import os +import re +import subprocess +import sys +import tempfile +import unittest +from pathlib import Path +from unittest import mock +from scripts import pipeline +from orchestrate import checks, consistency, results, runner +from tests.auditsupport import ROOT + + +class VerboseAppliesToJson(unittest.TestCase): + """verify accepted --verbose beside --json in every mode and dropped it: + the output was byte for byte the same, and the passing entries a script + asked for never came.""" + + def _run(self, *args: str) -> dict: + import json + import subprocess + + completed = subprocess.run( + [sys.executable, "scripts/verify.py", *args, "--json"], + capture_output=True, text=True, cwd=ROOT, timeout=900, check=False, + ) + self.assertEqual(completed.returncode, 0, completed.stderr[-2000:]) + return json.loads(completed.stdout) + + def test_emulator_and_system_modes_list_the_passing_entries(self): + for mode in (("--emulator", "handy"), ("--system", "atari-lynx")): + with self.subTest(mode=mode[0]): + plain = self._run(*mode) + verbose = self._run(*mode, "--verbose") + self.assertGreater(len(verbose["details"]), len(plain["details"])) + self.assertIn("ok", {d["status"] for d in verbose["details"]}) + + def test_every_json_branch_reads_the_flag(self): + source = script_source("verify.py") + # Defined once, called by the emulator and system output and the platform output. + self.assertEqual(source.count("json_details("), 3) + self.assertNotIn('if d["status"] != Status.OK\n ]', source) + + +class OnePlatformPerFlag(unittest.TestCase): + """generate_pack validated --platform as a comma list, then used the whole + string as one name: `--platform bizhawk,misterfpga` passed and ended in a + FileNotFoundError traceback. Every script now says it takes one name.""" + + def test_a_list_is_refused_with_a_message(self): + import subprocess + + runs = { + "generate_pack.py": ["--list-systems"], + "verify.py": [], + "cross_reference.py": [], + } + for script, extra in runs.items(): + with self.subTest(script=script): + completed = subprocess.run( + [sys.executable, f"scripts/{script}", "--platform", + "bizhawk,misterfpga", *extra], + capture_output=True, text=True, cwd=ROOT, timeout=600, check=False, + ) + self.assertNotEqual(completed.returncode, 0) + self.assertIn("takes one platform", completed.stderr) + self.assertNotIn("Traceback", completed.stderr) + + def test_unknown_names_still_get_a_suggestion(self): + from model.cliargs import require_platform + + with self.assertRaises(SystemExit) as caught: + require_platform("batocra", str(ROOT / "platforms")) + self.assertIn("batocera", str(caught.exception)) + + def test_a_file_that_is_no_platform_is_refused(self): + """_shared and the emulatorjs base config are YAML files under + platforms/, not platforms: verify --platform _shared reported 0/0.""" + from model.cliargs import require_platform + + for name in ("_shared", "_registry", "emulatorjs"): + with self.subTest(name=name), self.assertRaises(SystemExit) as caught: + require_platform(name, str(ROOT / "platforms")) + self.assertIn("unknown platform", str(caught.exception)) + + +class PipelineRegressions(unittest.TestCase): + def test_integrity_checks_the_variants_step_4_built(self): + """Step 6 ran --verify-packs without --all-variants: the five + narrowed packs were never opened and an empty _Platform passed.""" + import argparse + + def command(**flags) -> list[str]: + base = {"output_dir": "dist", "target": None, "all_variants": False} + return checks.integrity_command(argparse.Namespace(**{**base, **flags})) + + self.assertIn("--all-variants", command(all_variants=True)) + self.assertNotIn("--all-variants", command()) + self.assertEqual(command(target="switch")[-2:], ["--target", "switch"]) + + @staticmethod + def _verified(label: str, ok: int, total: int, core_files: int = 0) -> dict: + """One platform as verify.py --destinations records it.""" + key = label.lower().replace(" ", "") + return {key: {"platform": key, "label": label, "ok": ok, "total": total, + "core_files": core_files, "pack_destinations": []}} + + @staticmethod + def _packed(label: str, ok: int, total: int, core_files: int = 0, + unsafe_excluded: int = 0) -> dict: + """One full pack as generate_pack.py --counts records it.""" + return {"label": label, "platforms": [label.lower().replace(" ", "")], + "archive": "pack.zip", "ok": ok, "total": total, + "core_files": core_files, "unsafe_excluded": unsafe_excluded, "trees": []} + + def test_missing_pack_is_a_consistency_failure(self): + verify = self._verified("RetroArch", 2, 2) + with contextlib.redirect_stdout(io.StringIO()): + self.assertFalse(consistency.compare_counts(verify, [])) + + def test_display_name_and_registry_id_meet_by_id(self): + verify = self._verified("MiSTer FPGA", 65, 65) + pack = {**self._packed("misterfpga", 65, 65), "platforms": ["misterfpga"]} + with contextlib.redirect_stdout(io.StringIO()): + self.assertTrue(consistency.compare_counts(verify, [pack])) + + def test_the_cores_share_is_compared_too(self): + """RomM passed this step while verify counted 412 core files and game + data in the pack and the builder placed 60.""" + verify = self._verified("RomM", 383, 383, core_files=412) + pack = self._packed("RomM", 383, 383, core_files=60) + with contextlib.redirect_stdout(io.StringIO()) as out: + self.assertFalse(consistency.compare_counts(verify, [pack])) + self.assertIn("RomM: MISMATCH core files verify 412 != pack 60", out.getvalue()) + agreed = self._verified("RomM", 383, 383, core_files=60) + with contextlib.redirect_stdout(io.StringIO()): + self.assertTrue(consistency.compare_counts(agreed, [pack])) + + def test_an_exclusion_never_covers_a_file_verify_counts_ok(self): + """An existence platform packs a file whose hash disagrees and a hash + platform's verify reports it untested: exclusions that make up the + difference hid the very divergence this step exists to catch.""" + verify = self._verified("RetroArch", 3, 3) + pack = self._packed("RetroArch", 2, 3, unsafe_excluded=1) + with contextlib.redirect_stdout(io.StringIO()) as out: + self.assertFalse(consistency.compare_counts(verify, [pack])) + self.assertIn("(1 unsafe excluded)", out.getvalue()) + + def test_a_pack_more_optimistic_than_verify_is_a_failure(self): + """The invariant held one way only: a pack counting more OK files + than the report passed as 'pack resolves more'.""" + verify = self._verified("DupTest", 0, 1) + pack = self._packed("DupTest", 1, 1) + with contextlib.redirect_stdout(io.StringIO()): + self.assertFalse(consistency.compare_counts(verify, [pack])) + + def test_nothing_read_is_not_consistent(self): + """A build that recorded nothing must not pass with no platform compared.""" + with contextlib.redirect_stdout(io.StringIO()): + self.assertFalse(consistency.compare_counts(self._verified("RetroArch", 2, 2), [])) + self.assertFalse(consistency.compare_counts({}, [])) + + def test_an_unwritten_record_file_is_a_failure(self): + """A step that crashed leaves its file empty: the check fails, it + does not compare nothing and pass.""" + with tempfile.TemporaryDirectory() as root: + empty = os.path.join(root, "empty.json") + Path(empty).write_text("") + with contextlib.redirect_stdout(io.StringIO()) as out: + self.assertFalse(consistency.check_consistency(empty, empty)) + self.assertFalse(consistency.check_pack_destinations(empty, empty)) + self.assertIn("unreadable counts", out.getvalue()) + + def test_pack_without_verify_result_is_a_failure(self): + verify = self._verified("RetroArch", 2, 2) + packs = [self._packed("RetroArch", 2, 2), self._packed("Batocera", 2, 2)] + with contextlib.redirect_stdout(io.StringIO()) as out: + self.assertFalse(consistency.compare_counts(verify, packs)) + self.assertIn("Batocera: pack with no verify result", out.getvalue()) + + def test_a_build_that_recorded_nothing_skips_step_five(self): + """An empty counts file is a build that stopped before its record: + step 4 already fails, and step 5 has nothing to compare.""" + import argparse + + args = argparse.Namespace(source="full", all_variants=False, skip_packs=True) + with tempfile.TemporaryDirectory() as root: + empty = os.path.join(root, "counts.json") + Path(empty).write_text("") + step_results: dict = {} + with contextlib.redirect_stdout(io.StringIO()): + checks.check_steps(args, step_results, pack_counts_file=empty, + destinations_file=empty) + self.assertIs(step_results["consistency"], results.SKIPPED) + + def test_only_the_full_variant_is_recorded(self): + """--all-variants built six packs under one label, and the last won.""" + source = script_source("generate_pack.py") + self.assertIn('[] if record_counts and (source, required_only) == ("full", False) else None', + source) + + def test_slot_step_reaches_the_summary(self): + source = script_source("pipeline.py") + self.assertIn('results["slots"] = ok', source) + + def test_every_refresh_failure_reaches_pipeline_exit_status(self): + for failed_label in ( + "2 refresh data directories", + "2a refresh MAME hashes", + "2a2 refresh FBNeo hashes", + ): + with self.subTest(failed_label=failed_label): + def fake_run(_command, label, failed_label=failed_label): + return label != failed_label, "RetroArch: 1/1 OK\n" + + argv = ["pipeline.py", "--skip-packs", "--skip-docs"] + with ( + mock.patch.object(sys, "argv", argv), + mock.patch.object(runner, "run", side_effect=fake_run), + contextlib.redirect_stdout(io.StringIO()), + self.assertRaises(SystemExit) as raised, + ): + pipeline.main() + self.assertEqual(raised.exception.code, 1) + + + def test_a_targeted_export_reads_a_full_model(self): + """--target wrote truth// only, but the export read truth/.""" + commands: list[list[str]] = [] + + def fake_run(command, _label): + commands.append([str(part) for part in command]) + return True, "RetroArch: 1/1 OK\n" + + argv = ["pipeline.py", "--offline", "--skip-packs", "--skip-docs", + "--with-export", "--target", "switch"] + # The originals the offline export patches are not cached in a + # checkout: the run would be refused before any step. + with mock.patch.object(sys, "argv", argv), mock.patch.object( + runner, "run", side_effect=fake_run + ), mock.patch.object(pipeline, "refuse_offline_export_without_originals"), \ + contextlib.redirect_stdout(io.StringIO()), contextlib.suppress(SystemExit): + pipeline.main() + truth_runs = [c for c in commands if "scripts/generate_truth.py" in c] + export = next(c for c in commands if "scripts/export_native.py" in c) + read_dir = export[export.index("--truth-dir") + 1] + full_models = [ + c for c in truth_runs + if "--target" not in c and c[c.index("--output-dir") + 1] == read_dir + ] + self.assertTrue(full_models, truth_runs) + + +class OneRefreshPerOnlineRun(unittest.TestCase): + """An online run refreshed the data trees at step 2, again in the pack + build and again in the manifest build: a moving tree (fbneo-cheats on + master) could change between the two, and the pack and the manifest + described different revisions.""" + + def test_the_builds_reuse_step_twos_trees(self): + import contextlib + import io + from unittest import mock + + from scripts import pipeline + + commands: dict[str, list[str]] = {} + + def record(cmd, label): + commands[label] = cmd + return True, "" + + # A scratch output directory: step 4 purges the ZIPs of the one it + # is given, and this run must never touch dist/. + with tempfile.TemporaryDirectory() as out, \ + mock.patch.object(runner, "run", record), \ + mock.patch.object( + sys, "argv", ["pipeline.py", "--skip-docs", "--output-dir", out] + ), \ + contextlib.redirect_stdout(io.StringIO()), \ + self.assertRaises(SystemExit): + pipeline.main() + self.assertIn("2 refresh data directories", commands) + for label in ("4 generate packs", "4b generate install manifests"): + with self.subTest(step=label): + self.assertIn("--no-refresh-data", commands[label]) + self.assertNotIn("--offline", commands[label]) + + +class PipelineReportsWhatItDid(unittest.TestCase): + """A step that did not run must not be summarised as OK. + + --offline skips the network steps and --with-export gates three more. + Reporting them as OK claims work nobody did, and a run whose export + never happened read exactly like one where it had. + """ + + def test_a_skipped_step_is_not_reported_as_done(self): + self.assertTrue(bool(results.SKIPPED), "a skip must not fail the run") + self.assertEqual(repr(results.SKIPPED), "SKIPPED") + self.assertIsNot(results.SKIPPED, True) + + def test_every_skip_branch_uses_the_sentinel(self): + source = script_source("pipeline.py") + stale = re.findall(r'results\["(\w+)"\] = True', source) + self.assertEqual(stale, [], f"steps still claiming OK when skipped: {stale}") + + +class ACheckThatCannotAnswerDoesNotPass(unittest.TestCase): + """Exiting zero says the question was answered and the answer was yes. + + Four scripts said that without answering: a refresh that reached no + remote, a freshness check whose upstream was unreachable, a restore whose + cache could not supply a declared path, and a pack verification asked + about one platform whose pack was not there. + """ + + def test_naming_a_platform_with_no_pack_is_not_a_pass(self): + with tempfile.TemporaryDirectory() as directory: + named = subprocess.run( + [sys.executable, "scripts/generate_pack.py", "--platform", + "retroarch", "--verify-packs", "--output-dir", directory], + capture_output=True, text=True, cwd=str(ROOT), timeout=300, + check=False, + ) + self.assertNotEqual( + named.returncode, 0, + "a named platform with no pack reported success:\n" + + named.stdout + named.stderr, + ) + # --all is a sweep: a platform nobody built is out of scope and + # skipped, but a sweep that found no pack at all checked nothing. + swept = subprocess.run( + [sys.executable, "scripts/generate_pack.py", "--all", + "--verify-packs", "--output-dir", directory], + capture_output=True, text=True, cwd=str(ROOT), timeout=300, + check=False, + ) + self.assertIn("SKIP (no pack in", swept.stdout) + self.assertNotEqual(swept.returncode, 0, swept.stdout + swept.stderr) + + def test_an_unsatisfiable_declared_path_is_reported(self): + from scripts.release.restore import restore + + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + cache = root / "cache" + cache.mkdir() + (root / ".gitignore").write_text("bios/absent.bin\n", encoding="utf-8") + (root / "database.json").write_text( + json.dumps({"files": {"a" * 40: {"path": "bios/absent.bin"}}}), + encoding="utf-8", + ) + result = restore( + str(cache), str(root / "database.json"), str(root / ".gitignore"), + root=root, + ) + self.assertEqual(result.restored, []) + self.assertEqual(result.unsatisfied, ["bios/absent.bin"]) + + def test_an_unreachable_buildbot_is_not_a_fresh_verdict(self): + """Every HEAD unanswered printed "16 unknown" and exited 0, so the + online pipeline printed check_buildbot OK.""" + import check_buildbot_system as cbs + from scraper import buildbot_system + + registry = str(ROOT / "platforms" / "_data_dirs.yml") + tracked = buildbot_system.load_tracked_entries(registry) + self.assertTrue(tracked) + cases = { + "index unreachable": mock.patch.object( + buildbot_system, "fetch_index", side_effect=OSError("down")), + "every HEAD unanswered": mock.patch.object( + buildbot_system, "fetch_index", return_value=set(tracked)), + } + for label, index in cases.items(): + with self.subTest(label), index, \ + mock.patch.object(buildbot_system, "get_remote_etag", return_value=None), \ + mock.patch.object(sys, "argv", ["check_buildbot_system.py", + "--registry", registry]), \ + contextlib.redirect_stdout(io.StringIO()), \ + self.assertRaises(SystemExit) as stop: + cbs.main() + self.assertEqual(stop.exception.code, 1) + + def test_a_missing_profile_directory_says_so(self): + # Bare names, as the loader imports them: scripts.core.cli would be a + # second copy of the module, with a second InputMissing. + from core.cli import InputMissing + from model.profiles import load_emulator_profiles + + with self.assertRaisesRegex(InputMissing, "no emulator profile directory"): + load_emulator_profiles(str(ROOT / "no-such-emulator-dir")) + + +class PipelineStepsSpeakAsTheyGo(unittest.TestCase): + """run() captured a step and printed it at the end, stderr after stdout: + a twenty-minute pack build was silent and a warning lost its place.""" + + def test_output_keeps_its_order_and_is_returned(self): + script = ("import sys; print('one', flush=True); " + "print('two', file=sys.stderr, flush=True); print('three')") + echoed = io.StringIO() + with contextlib.redirect_stdout(echoed): + ok, output = runner.run([sys.executable, "-c", script], "probe") + self.assertTrue(ok) + self.assertEqual(output, "one\ntwo\nthree\n") + text = echoed.getvalue() + self.assertLess(text.index("one"), text.index("two")) + self.assertLess(text.index("two"), text.index("three")) + self.assertLess(text.index("three"), text.index("--- probe: OK")) + + +class TriageSurvivesAForgeRefusal(unittest.TestCase): + """git.eden-emu.dev answers 403 to commit lookups: `--all --triage` + died on the traceback after half an hour and printed no ranking.""" + + def test_the_ranking_is_printed_with_the_profile_marked(self): + from types import SimpleNamespace + + from scripts.profiling import reports as profiling_reports + from scripts.profiling import triage + + reports = [ + profiling_reports.ProfileReport(name="eden", pin="a" * 40, head="b" * 40), + profiling_reports.ProfileReport(name="vice", pin="c" * 40, head="d" * 40), + ] + selected = { + "eden": {"source": "https://git.eden-emu.dev/eden-emu/eden", "core_version": "1"}, + "vice": {"source": "https://github.com/libretro/vice-libretro", "core_version": "1"}, + } + + def check_version(named, *_args): + if "eden" in named.repo.slug: + raise triage.forgehttp.UpstreamError("HTTP 403") + return + + args = SimpleNamespace(cache_dir="", offline=True) + out = io.StringIO() + with mock.patch.object(triage, "check_version", check_version), \ + contextlib.redirect_stdout(out), \ + contextlib.redirect_stderr(io.StringIO()): + triage.print_triage(args, selected, reports) + # A header row and a closing count frame the ranking. + lines = out.getvalue().splitlines()[1:-1] + self.assertEqual(len(lines), 2) + self.assertTrue(any("eden" in line and "unreachable" in line for line in lines)) + + +class VerifyStrictAppliesInEveryMode(unittest.TestCase): + """--strict was read only by the platform branch: `--emulator x --strict` + printed MISSING (required) and exited 0, and the listings accepted it.""" + + @classmethod + def setUpClass(cls): + if not (ROOT / "database.json").exists(): + raise unittest.SkipTest("database.json is not built") + cls.dir = Path(tempfile.mkdtemp()) + (cls.dir / "fakeemu.yml").write_text( + "emulator: FakeEmu\ntype: libretro\nsystems: [zz-console]\nfiles:\n" + " - name: does_not_exist_strict.bin\n required: true\n" + " md5: 0123456789abcdef0123456789abcdef\n validation: [md5]\n" + ) + + @classmethod + def tearDownClass(cls): + __import__("shutil").rmtree(cls.dir, True) + + def run_verify(self, *flags: str) -> int: + return subprocess.run( + [sys.executable, "scripts/verify.py", *flags], cwd=ROOT, + capture_output=True, text=True, + check=False, + ).returncode + + def test_emulator_and_system_modes_fail_on_a_missing_required_file(self): + for mode in (["--emulator", "fakeemu"], ["--system", "zz-console"]): + with self.subTest(mode=mode[0]): + flags = [*mode, "--emulators-dir", str(self.dir)] + self.assertEqual(self.run_verify(*flags), 0) + self.assertEqual(self.run_verify(*flags, "--strict"), 1) + + def test_a_listing_refuses_strict(self): + self.assertEqual(self.run_verify("--list-emulators", "--strict"), 2) + + +class EveryToolRefusesAFlagItWouldDrop(unittest.TestCase): + """The mode x flag matrix existed for generate_pack only: verify took + --strict in --emulator mode and ignored it, pipeline took --source with + --skip-packs and built nothing. Each pair here must exit non-zero + before doing any work.""" + + REFUSED = { + "scripts/verify.py": [ + ["--list-emulators", "--strict"], + ["--list-emulators", "--verbose"], + ["--list-emulators", "--json"], + ["--list-systems", "--region", "us"], + ["--emulator", "handy", "--target", "switch"], + ["--platform", "retroarch", "--standalone"], + ["--all", "--system", "sony-playstation", "--standalone"], + ], + "scripts/cross_reference.py": [ + ["--all", "--platform", "retroarch"], + ["--list-emulators", "--all"], + ], + "scripts/pipeline.py": [ + ["--offline", "--skip-packs", "--source", "truth"], + ["--offline", "--skip-packs", "--all-variants"], + ["--offline", "--skip-packs", "--full-narrowings"], + ["--offline", "--all-variants", "--source", "platform"], + ["--offline", "--all-variants", "--source", "full"], + ["--offline", "--skip-packs", "--source", "full"], + ["--offline", "--source", "truth", "--full-narrowings"], + ["--offline", "--source", "platform", "--full-narrowings"], + ], + # The expert narrowings: what the pack builder refuses beside its + # option of the same name, and a flag with no mode to apply it. + "install.py": [ + ["--json"], + ["--standalone"], + ["--emulator", "duckstation", "--standalone", "--region", "us"], + ["--emulator", "duckstation", "--standalone", "--one-per-slot"], + ["--one-per-slot", "--system", "sony-playstation"], + ["--one-per-slot", "--emulator", "duckstation"], + ["--one-per-slot", "--for-games"], + ["--one-per-slot", "--declared-only"], + ["--one-per-slot", "--list-systems"], + ["--source", "truth", "--system", "sony-playstation"], + ["--source", "truth", "--target", "switch"], + ["--source", "truth", "--one-per-slot"], + ["--source", "truth", "--tui"], + ["--source", "platform"], + ["--find", "0" * 40, "--system", "sony-playstation"], + ["--find", "0" * 40, "--one-per-slot"], + ["--find", "0" * 40, "--check"], + ["--find", "0" * 40, "--list-systems"], + ["--find", "0" * 40, "--json", "--events"], + ["--find", "0" * 40, "--json", "--pack", "tmp/"], + ["--find", "0" * 40, "--json", "--add-app"], + ["--find", "0" * 40, "--json", "--standalone-copies"], + ["--find", "0" * 40, "--json", "--romm-firmware", "{platform}/bios"], + ["--find", "0" * 40, "--json", "--from", "tmp"], + ["--find", "0" * 40, "--pack", "tmp/"], + ["--find", "not-a-hash"], + ["--find", "0" * 12], + ], + } + + def test_each_pair_is_refused(self): + for script, cases in self.REFUSED.items(): + for argv in cases: + with self.subTest(script=script, argv=argv): + proc = subprocess.run( + [sys.executable, script, *argv], cwd=ROOT, + capture_output=True, text=True, timeout=120, + check=False, + ) + self.assertEqual(proc.returncode, 2, proc.stdout + proc.stderr) + + +class AReaderThatLeavesEarlyIsNoCrash(unittest.TestCase): + """`verify.py --list-emulators | head -1` ended on a BrokenPipeError + traceback, and so did every listing and report.""" + + def test_a_closed_pipe_ends_quietly(self): + proc = subprocess.Popen( + [sys.executable, "scripts/verify.py", "--list-emulators"], cwd=ROOT, + stdout=subprocess.PIPE, stderr=subprocess.PIPE, + ) + # The listing fits a 64 KiB pipe: a child that wrote it all before + # the close below never met the broken pipe and exited 0. A 4 KiB + # pipe keeps it writing when the reader leaves. + try: + import fcntl + + fcntl.fcntl(proc.stdout.fileno(), fcntl.F_SETPIPE_SZ, 4096) + except (ImportError, AttributeError, OSError): + pass + proc.stdout.readline() + proc.stdout.close() + _, err = proc.communicate(timeout=120) + self.assertNotIn(b"Traceback", err) + self.assertEqual(proc.returncode, 141) + + def test_every_entry_point_goes_through_run_cli(self): + plain = re.compile(r'if __name__ == "__main__":\n (main\(\)|sys\.exit\(main\(\)\))') + found = [p.name for p in sorted((ROOT / "scripts").glob("*.py")) + if plain.search(p.read_text())] + self.assertEqual(found, []) + + +class VerifyPacksSaysWhatItExcluded(unittest.TestCase): + """--verify-packs read the result tuple by position, dropped the unsafe + exclusions (352/353 shown as OK with no reason) and printed 5 errors.""" + + def test_the_result_is_unpacked_whole_and_every_error_printed(self): + source = script_source("generate_pack.py") + body = source[source.index("def _check_pack"):] + body = body[:body.index("\ndef ")] + self.assertIn("result.shortfall", body) + self.assertIn("for err in result.errors", body) + shortfall = source[source.index("def baseline_shortfall"):] + self.assertIn("unsafe excluded", shortfall[:shortfall.index("\ndef ")]) + self.assertNotIn("errors[:5]", body) + self.assertNotRegex(body, r"result\[\d\]") + + +class TargetListsReadThePinnedRelease(unittest.TestCase): + """Each target scraper asked upstream for its latest tag: a Recalbox + 10.2 board list could filter 10.1.1 systems, and Batocera's target file + did not even record the tag it read.""" + + def test_the_revision_comes_from_the_platform_yaml(self): + from scripts.scraper.targets import BaseTargetScraper + + with tempfile.TemporaryDirectory() as tmp: + for name, source, tag in ( + ("a", "https://raw.githubusercontent.com/o/r/batocera-43.1/x/y", "batocera-43.1"), + ("b", "https://gitlab.com/recalbox/recalbox/-/raw/10.1.1/a/b.xml", "10.1.1"), + ("c", "https://github.com/o/r/blob/v2/f.cs", "v2"), + ): + Path(tmp, f"{name}.yml").write_text(f"source: {source}\n") + self.assertEqual(BaseTargetScraper.pinned_revision(name, tmp), tag) + Path(tmp, "d.yml").write_text("source: https://example.test/x\n") + with self.assertRaises(RuntimeError): + BaseTargetScraper.pinned_revision("d", tmp) + + def test_no_target_scraper_asks_for_the_latest_tag(self): + for name in ("batocera", "rocknix", "recalbox"): + source = (ROOT / "scripts" / "scraper" / "targets" / f"{name}_targets_scraper.py").read_text() + with self.subTest(scraper=name): + # The Batocera scraper reads the pin of the platform it is + # instantiated for (KNULLI subclasses it). + self.assertTrue( + "self.pinned_revision(PLATFORM_NAME)" in source + or "self.pinned_revision(self.PLATFORM)" in source + ) + self.assertNotIn("fetch_stable_tag()", source) + self.assertNotIn("fetch_github_latest_version(", source) + # Lakka inherits its BIOS list and pins the release in its own version:. + source = (ROOT / "scripts" / "scraper" / "targets" / "lakka_targets_scraper.py").read_text() + self.assertIn("self.pinned_version(PLATFORM_NAME)", source) + self.assertNotIn("fetch_github_latest_version(", source) + + +class VerifyAllSummaryNamesWhatIsWrong(unittest.TestCase): + """The closing line counted platform severities only: a required core + file missing on ROCKNIX was absent from it, and the one warning did not + say which platform carried it.""" + + def test_counts_carry_platforms_and_core_misses(self): + from packs import verifysummary + from packs import verdicts + + clean = {"severity_counts": {}, "undeclared_files": []} + warned = {"severity_counts": {verdicts.Severity.WARNING: 1}, "undeclared_files": []} + core_miss = { + "severity_counts": {}, + "undeclared_files": [{ + "name": "n64.psh", "required": True, "in_repo": False, + "category": "bios", "in_pack": True, + }], + } + summary = verifysummary.overall_summary( + [(clean, ["RetroArch"]), (warned, ["RetroDECK"]), (core_miss, ["ROCKNIX"])] + ) + self.assertIn("1 warning (RetroDECK 1)", summary) + self.assertIn("n64.psh (ROCKNIX)", summary) + self.assertIn("0 critical,", summary) + + def test_a_file_missing_on_several_platforms_is_counted_once(self): + """sfiii2a.zip missing on 15 platforms read '24 core file(s)' for 10 + distinct files, the name printed 15 times on one line.""" + from packs import verifysummary + + def missing(*names: str) -> dict: + return {"severity_counts": {}, "undeclared_files": [ + {"name": name, "required": True, "in_repo": False, + "category": "bios", "in_pack": True} for name in names + ]} + + summary = verifysummary.overall_summary([ + (missing("sfiii2a.zip"), ["Batocera"]), + (missing("sfiii2a.zip", "ROM"), ["RetroPie"]), + (missing("sfiii2a.zip"), ["RomM"]), + (missing(), ["MinUI"]), + ]) + self.assertIn( + "2 core file(s) a core cannot run without are missing: " + "sfiii2a.zip (every platform but MinUI); ROM (RetroPie)", + summary, + ) + self.assertEqual(summary.count("sfiii2a.zip"), 1) + + +class OneOutputFormPerRun(unittest.TestCase): + """`diff_truth.py --json --format markdown` printed JSON with rc 0, the + markdown asked for dropped without a word.""" + + def test_json_and_markdown_are_refused_together(self): + for script, argv in ( + ("diff_truth.py", ["--platform", "romm", "--json", "--format", "markdown"]), + ("diff_truth.py", ["--platform", "romm", "--json", "--markdown"]), + ("validate_pr.py", ["--json", "--markdown", "bios/Sony/PlayStation/scph5501.bin"]), + ): + with self.subTest(script=script, argv=argv): + proc = subprocess.run( + [sys.executable, f"scripts/{script}", *argv], capture_output=True, + text=True, cwd=str(ROOT), timeout=120, check=False, + ) + self.assertEqual(proc.returncode, 2, proc.stdout[-300:]) + self.assertIn("not allowed with", proc.stderr) + + +class ATargetIsNamedWhenItRemovesTheCore(unittest.TestCase): + """--platform batocera --target rpi4 --emulator dolphin said "dolphin is + not run by batocera", which runs it on every x86 board.""" + + def test_the_message_names_the_target(self): + result = subprocess.run( + [sys.executable, "scripts/cross_reference.py", "--platform", "batocera", + "--target", "bcm2711", "--emulator", "dolphin"], + cwd=ROOT, capture_output=True, text=True, timeout=600, + check=False, + ) + self.assertEqual(result.returncode, 1) + self.assertIn("bcm2711 target", result.stderr) + self.assertNotIn("is not run by", result.stderr) + + +class ANamedPackThatIsAbsentFails(unittest.TestCase): + """--verify-packs --platform retroarch on an empty directory printed + "SKIP" and exited 1: a skip label on a failure, and no next step.""" + + def test_the_line_says_fail_and_how_to_build(self): + with tempfile.TemporaryDirectory() as directory: + result = subprocess.run( + [sys.executable, "scripts/generate_pack.py", "--platform", "retroarch", + "--verify-packs", "--output-dir", directory], + cwd=ROOT, capture_output=True, text=True, timeout=600, + check=False, + ) + self.assertEqual(result.returncode, 1) + self.assertIn("retroarch: FAIL (no pack in", result.stdout) + self.assertIn("generate_pack.py --platform retroarch", result.stdout) + + def test_all_with_no_pack_is_a_failure(self): + """--all on a mistyped or purged directory skipped every platform + and exited 0, a passed integrity check that checked nothing.""" + with tempfile.TemporaryDirectory() as directory: + result = subprocess.run( + [sys.executable, "scripts/generate_pack.py", "--all", + "--verify-packs", "--output-dir", directory], + cwd=ROOT, capture_output=True, text=True, timeout=600, + check=False, + ) + self.assertEqual(result.returncode, 1) + self.assertIn("no pack to verify", result.stderr) + + +class AnAliasSelectsItsProfile(unittest.TestCase): + """`--emulator mednafen_psx` refused with "use --emulator beetle_psx", + a step the tool could take itself: the name a user reads in RetroArch + now selects the profile it is an alias of, and says so on stderr. An + alias without alias_of is found through the profile whose cores: names + it.""" + + def test_the_alias_selects_its_profile(self): + import contextlib as _contextlib + import io as _io + + from scripts.model.profiles import ProfileSelectionError, select_emulator_profiles + + profiles = { + "flycast": {"type": "libretro", "cores": ["flycast", "flycast_gles2"]}, + "flycast_gles2": {"type": "alias", "alias_of": "flycast"}, + "orphan": {"type": "alias"}, + "core": {"type": "libretro", "cores": ["orphan"]}, + "lost": {"type": "alias"}, + } + for name, expected in (("flycast_gles2", "flycast"), ("orphan", "core")): + err = _io.StringIO() + with self.subTest(name=name), _contextlib.redirect_stderr(err): + selected = select_emulator_profiles([name], profiles) + self.assertEqual([key for key, _ in selected], [expected]) + self.assertIn(f"{name} is {expected}", err.getvalue()) + with _contextlib.redirect_stderr(_io.StringIO()): + both = select_emulator_profiles(["flycast", "flycast_gles2"], profiles) + self.assertEqual([key for key, _ in both], ["flycast"]) + with self.assertRaises(ProfileSelectionError): + select_emulator_profiles(["lost"], profiles) + + def test_verify_runs_the_alias(self): + result = subprocess.run( + [sys.executable, "scripts/verify.py", "--emulator", "mednafen_psx"], + cwd=ROOT, capture_output=True, text=True, timeout=300, check=False, + ) + self.assertEqual(result.returncode, 0, result.stderr) + self.assertIn("beetle_psx", result.stdout) + self.assertIn("mednafen_psx is beetle_psx", result.stderr) + + +class AFailedVerificationIsAnError(unittest.TestCase): + """--all ended on "WARNING: some packs have verification errors" and + exit 1: a warning that fails the run, naming no pack.""" + + def test_the_last_line_names_the_packs(self): + source = script_source("generate_pack.py") + self.assertNotIn("WARNING: some packs have verification errors", source) + self.assertIn('print(f"ERROR: packs failed verification: {\', \'.join(failing)}", file=sys.stderr)', source) + + +class TheGroundTruthFooterSaysWhatItCounts(unittest.TestCase): + """"417 platform-only (no emulator profile)" where 369 of 526 files had + a profile, 20% here for 21% on the site, and "0/81 (0%)" for MiSTer, + which declares no core by design.""" + + def _footer(self, coverage): + import io as _io + from contextlib import redirect_stdout + + from scripts.packs.verdicts import Severity + from scripts.packs.report import print_platform_result + + out = _io.StringIO() + counts = {Severity.OK: 1, Severity.INFO: 0, Severity.WARNING: 0, Severity.CRITICAL: 0} + result = {"platform": "X", "verification_mode": "existence", "total_files": 1, + "severity_counts": counts, "status_counts": {"ok": 1}, + "undeclared_files": [], "exclusion_notes": [], "details": [], + "ground_truth_coverage": coverage} + with redirect_stdout(out): + print_platform_result(result, ["X"]) + return out.getvalue() + + def test_counts_and_rounding(self): + text = self._footer({"with_validation": 109, "with_profile": 369, + "platform_only": 417, "total": 526, "applicable": True}) + self.assertIn("(21%)", text) + self.assertIn("157 platform-only", text) + + def test_not_applicable(self): + text = self._footer({"with_validation": 0, "with_profile": 0, + "platform_only": 81, "total": 81, "applicable": False}) + self.assertIn("not applicable", text) + self.assertNotIn("0/81", text) + + +class ThePipelineSummaryTimesEachStep(unittest.TestCase): + """The summary gave OK per step and one total: the slow step of a + twenty-minute run could only be found by reading the log.""" + + def test_each_outcome_carries_its_time(self): + from unittest import mock + + clock = iter([10.0, 12.5, 12.5, 20.0]) + with mock.patch.object(results.time, "monotonic", lambda: next(clock)): + outcomes = results.StepResults(results.time.monotonic()) + outcomes["generate_db"] = True + outcomes["refresh_data"] = results.SKIPPED + outcomes["verify"] = True + self.assertEqual(outcomes.seconds, {"generate_db": 2.5, "refresh_data": 0.0, "verify": 7.5}) + self.assertEqual(dict(outcomes), {"generate_db": True, "refresh_data": results.SKIPPED, + "verify": True}) + + +class StrictFailsOnMissingOnly(unittest.TestCase): + """The docstring promised exit 1 on a required file missing or rejected, + but a rejected file is UNTESTED, a warning, and --strict never saw it.""" + + def test_the_contract(self): + from scripts.packs.strictgate import platform_strict_failure + from scripts.packs.verdicts import Severity + + self.assertIsNone(platform_strict_failure([{"severity_counts": {Severity.WARNING: 2}}])) + self.assertIsNotNone( + platform_strict_failure([{"severity_counts": {Severity.CRITICAL: 1}}])) + self.assertNotIn("or rejected", platform_strict_failure.__doc__) + + +class TheRepairCommandWritesTheFileNamed(unittest.TestCase): + """--db nosuch.json said to rebuild with --output database.json: the + command wrote another file and the next run failed the same way.""" + + def test_the_command_names_the_path(self): + from scripts.model.database import DatabaseUnreadable, load_database + + with tempfile.TemporaryDirectory() as directory: + target = str(Path(directory) / "nosuch.json") + with self.assertRaises(DatabaseUnreadable) as caught: + load_database(target) + self.assertIn(f"--output {target}", str(caught.exception)) + Path(target).write_text("{") + with self.assertRaises(DatabaseUnreadable) as caught: + load_database(target) + self.assertIn(f"--output {target}", str(caught.exception)) + + def test_a_typo_beside_the_database_names_the_database(self): + """--db databse.json beside database.json was told to rescan the whole + collection into a second file named after the typo.""" + from scripts.model.database import DatabaseUnreadable, load_database + + with tempfile.TemporaryDirectory() as directory: + (Path(directory) / "database.json").write_text("{}") + typo = Path(directory) / "databse.json" + with self.assertRaises(DatabaseUnreadable) as caught: + load_database(str(typo)) + message = str(caught.exception) + self.assertIn(f"Close match: {typo.with_name('database.json')}", message) + self.assertNotIn("generate_db.py", message) + + +class VerifyPacksRefusesWhatItCannotDo(unittest.TestCase): + """The --verify-packs refusals lived in the --all-variants checks, which + return without that flag: --split and --one-per-slot went through, and + a run with neither --platform nor --all failed after taking the lock.""" + + def test_usage_errors_exit_2_before_any_lock(self): + cases = ( + ["--verify-packs"], + ["--verify-packs", "--platform", "retroarch", "--split"], + ["--verify-packs", "--platform", "retroarch", "--one-per-slot"], + ) + for extra in cases: + with self.subTest(args=extra), tempfile.TemporaryDirectory() as out: + result = subprocess.run( + [sys.executable, "scripts/generate_pack.py", *extra, "--output-dir", out], + cwd=ROOT, capture_output=True, text=True, timeout=300, + check=False, + ) + self.assertEqual(result.returncode, 2, result.stderr[-300:]) + self.assertIn("--verify-packs", result.stderr) + self.assertFalse((Path(out) / ".lock").exists()) + + +class ABrokenRegistryIsNotAnEmptyOne(unittest.TestCase): + """A registered platform whose YAML was renamed was skipped without a + word, and a missing registry read as no platforms: verify --all --strict + and every --all build passed having checked nothing.""" + + def test_both_raise(self): + from scripts.model.registry import list_registered_platforms + + with tempfile.TemporaryDirectory() as tmp: + with self.assertRaises(FileNotFoundError): + list_registered_platforms(tmp) + Path(tmp, "_registry.yml").write_text( + "platforms:\n rocknix:\n config: rocknix.yml\n", encoding="utf-8" + ) + with self.assertRaises(FileNotFoundError) as caught: + list_registered_platforms(tmp) + self.assertIn("rocknix", str(caught.exception)) + + +class AForcedRehashIsCheckedAgainstTheLastOne(unittest.TestCase): + """This host has computed a wrong SHA-1 under load. The pipeline's forced + rebuild threw the previous digests away and wrote whatever it read.""" + + def test_a_reading_the_cache_and_a_second_reading_contradict_is_outvoted(self): + from unittest import mock + + from collection import scan + + cached = {"sha1": "a" * 40, "mtime": 1.0, "size": 4} + readings = iter([{"sha1": "b" * 40}, {"sha1": "a" * 40}]) + with mock.patch.object(scan, "compute_hashes", lambda *a, **k: next(readings)), \ + contextlib.redirect_stderr(io.StringIO()) as err: + settled = scan._settled_hashes(Path("x.bin"), cached, 1.0, 4) + self.assertEqual(settled["sha1"], "a" * 40) + self.assertIn("WARNING", err.getvalue()) + + def test_two_agreeing_readings_against_an_unmoved_file_stop_the_run(self): + """The host has returned the same wrong SHA-1 twice in a row + (DSi_Nand_USA.bin as 62b100f2, 2026-10-22). Taking two agreeing + readings as a rewrite put the wrong value in the cache, where every + later run read it back. An unmoved file is never rewritten silently.""" + from unittest import mock + + from collection import scan + + cached = {"sha1": "a" * 40, "mtime": 1.0, "size": 4} + with mock.patch.object(scan, "compute_hashes", lambda *a, **k: {"sha1": "b" * 40}), \ + self.assertRaisesRegex(RuntimeError, "touch"): + scan._settled_hashes(Path("x.bin"), cached, 1.0, 4) + + def test_a_changed_file_takes_its_new_digest(self): + from unittest import mock + + from collection import scan + + cached = {"sha1": "a" * 40, "mtime": 1.0, "size": 4} + with mock.patch.object(scan, "compute_hashes", lambda *a, **k: {"sha1": "c" * 40}): + self.assertEqual( + scan._settled_hashes(Path("x.bin"), cached, 2.0, 4)["sha1"], "c" * 40 + ) + + +class AnUnknownTargetIsRefusedUnderAll(unittest.TestCase): + """--all --target swtich skipped every platform with targets and checked + BizHawk and MiSTer unfiltered: a green run about no Switch at all.""" + + def test_a_typo_is_refused_and_targetless_platforms_are_left_out(self): + from scripts.model.targets import build_target_cores_cache + from scripts.model.registry import list_registered_platforms + + platforms = list_registered_platforms(str(ROOT / "platforms")) + with self.assertRaises(ValueError): + build_target_cores_cache(platforms, "swtich", str(ROOT / "platforms"), is_all=True) + _cache, kept, _notes = build_target_cores_cache( + platforms, "switch", str(ROOT / "platforms"), is_all=True + ) + self.assertNotIn("bizhawk", kept) + self.assertIn("retroarch", kept) + + +class AScraperThatCannotStartSaysWhy(unittest.TestCase): + """Scrapers resolve their tag or branch head in the constructor, and + scraper_cli built the scraper outside its try: a refused API call ended + in a traceback instead of a message saying to set GITHUB_TOKEN.""" + + def _run(self, scraper_class, token: str | None): + import contextlib + import io + from unittest import mock + + from scraper.base_scraper import scraper_cli + + env = {k: v for k, v in os.environ.items() if k != "GITHUB_TOKEN"} + if token: + env["GITHUB_TOKEN"] = token + err = io.StringIO() + with mock.patch.dict(os.environ, env, clear=True), \ + mock.patch.object(sys, "argv", ["x", "--dry-run"]), \ + contextlib.redirect_stderr(err), \ + self.assertRaises(SystemExit) as stop: + scraper_cli(scraper_class) + return stop.exception.code, err.getvalue() + + def test_a_failing_constructor_exits_with_a_hint(self): + class Refused: + def __init__(self): + raise RuntimeError("cannot read the head of a/b@main: HTTP 403") + + code, err = self._run(Refused, None) + self.assertEqual(code, 1) + self.assertIn("HTTP 403", err) + self.assertIn("GITHUB_TOKEN", err) + + def test_with_a_token_the_hint_points_elsewhere(self): + class Offline: + def fetch_requirements(self): + raise ConnectionError("no route to host") + + code, err = self._run(Offline, "t") + self.assertEqual(code, 1) + self.assertNotIn("GITHUB_TOKEN", err) + + +class AStepThatCannotFailTheRunIsNotShownFailed(unittest.TestCase): + """check_buildbot leaves all_ok alone, and the summary printed it FAILED + right above "Pipeline COMPLETE". The total also missed the duration + column by fourteen characters.""" + + def test_every_step_outside_all_ok_is_declared_non_blocking(self): + lines = script_source("pipeline.py").splitlines() + loose = set() + for number, line in enumerate(lines): + found = re.search(r'results\["(\w+)"\] = ok$', line.strip()) + if not found: + continue + after = " ".join(lines[number + 1:number + 4]) + if "all_ok" not in after and "sys.exit" not in after: + loose.add(found.group(1)) + self.assertEqual(loose, set(results.NON_BLOCKING)) + + def test_the_total_sits_under_the_durations(self): + step = f" {'x':.<40} {'OK':<7}{1.0:>8.1f}s" + total = f" {'total':.<40} {'':<7}{12.5:>8.1f}s" + self.assertEqual(len(step), len(total)) + self.assertIn("{'':<7}{total_elapsed:>8.1f}s", + script_source("pipeline.py")) + + +class AHashConflictIsReportedOnce(unittest.TestCase): + """check_freshness opened on six copies of one truth.py warning, one per + platform whose model met the same two GameIndex.yaml declarations.""" + + def test_the_same_pair_prints_once(self): + from resolve import truth + + truth._CONFLICTS_SHOWN.clear() + with self.assertLogs(truth.log, "WARNING") as logged: + for _platform in range(6): + existing = {"name": "x.yaml", "sha1": "a" * 40} + truth._merge_hashes(existing, {"name": "x.yaml", "sha1": "b" * 40}, "core") + self.assertEqual(len(logged.records), 1) + + +class ThePipelineRunsTheSchemaCheckCIRuns(unittest.TestCase): + """The pipeline the repository asks for after every change never ran + validate_schemas.py, which PR validation does: a profile with an + unquoted numeric core name passed it and failed CI on push.""" + + def test_the_ci_command_is_a_pipeline_step(self): + workflow = (ROOT / ".github" / "workflows" / "validate.yml").read_text(encoding="utf-8") + command = re.search(r"python (scripts/validate_schemas\.py[^\n]*)", workflow).group(1) + script, *flags = command.split() + source = script_source("pipeline.py") + self.assertIn(f'"{script}"', source) + for flag in flags: + self.assertIn(f'"{flag}"', source) + + def test_the_site_is_rendered_as_the_deploy_renders_it(self): + """The pipeline generated pages without rendering them: 20 pages with + duplicate ids passed it and failed the deploy.""" + workflow = (ROOT / ".github" / "workflows" / "deploy-site.yml").read_text(encoding="utf-8") + source = script_source("pipeline.py") + self.assertIn("npm run build --prefix website", workflow) + self.assertIn('["npm", "run", "build", "--prefix", "website"]', source) + self.assertIn("scripts/validate_site.py", workflow) + self.assertIn('"scripts/validate_site.py"', source) + + +class TheReleaseBuildsEveryServedPackInOneRun(unittest.TestCase): + """The release ran the pipeline, then built and checked RetroPie by hand: + the consistency check between verify and the pack never covered it.""" + + def test_the_pipeline_step_covers_every_platform(self): + page = (ROOT / "wiki" / "release-process.md").read_text(encoding="utf-8") + self.assertIn("python scripts/pipeline.py\n", page) + self.assertNotIn("generate_pack.py --platform retropie", page) + + +class PlatformSystemTypoGetsTheClosestNames(unittest.TestCase): + """--platform retroarch --system sony-playstaton listed the first ten + systems of the alphabet, 3do to coleco-colecovision.""" + + def test_the_hint_names_the_close_systems(self): + from scripts.packs import platformpack + + out = io.StringIO() + with tempfile.TemporaryDirectory() as tmp, \ + contextlib.redirect_stdout(out): + result = platformpack.generate_pack( + "retroarch", str(ROOT / "platforms"), {"files": {}, "indexes": {}}, + str(ROOT / "bios"), tmp, emulators_dir=str(ROOT / "emulators"), + system_filter=["sony-playstaton"], offline=True, + ) + self.assertIsNone(result) + printed = out.getvalue() + self.assertIn("Close matches: sony-playstation", printed) + self.assertIn("--platform retroarch --list-systems", printed) + self.assertNotIn("3do", printed) + + +class HashInputNamesWhatItAccepts(unittest.TestCase): + """A 12-digit value was looked up as an MD5 and reported NOT FOUND, a + SHA-256 vanished from the input, and the run said only "No valid hashes + found in input".""" + + def test_digests_are_read_by_length(self): + from scripts.packs.hashinput import parse_hash_input + + sha256 = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" + self.assertEqual(parse_hash_input(f"0x1A2B3C4D,{sha256}"), [ + ("crc32", "1a2b3c4d"), ("sha256", sha256), + ]) + self.assertEqual(parse_hash_input("a" * 29), [("md5", "a" * 29)]) + + def test_anything_else_is_refused_with_the_formats(self): + from scripts.packs.hashinput import parse_hash_file, parse_hash_input + + for raw in ("1234567890ab", "zz", "490f666e1afb15b7362b406ed1cea246,zz"): + with self.subTest(raw=raw), self.assertRaises(ValueError) as ctx: + parse_hash_input(raw) + self.assertIn("SHA-256 (64)", str(ctx.exception)) + with tempfile.TemporaryDirectory() as tmp: + listing = Path(tmp, "hashes.txt") + listing.write_text("# list\n490f666e1afb15b7362b406ed1cea246 a.bin\nb.bin\n") + with self.assertRaises(ValueError) as ctx: + parse_hash_file(str(listing)) + self.assertIn("line 3 (b.bin)", str(ctx.exception)) + + def test_a_sha256_finds_its_file(self): + from scripts.resolve.packfiles import sha1_for_hash + + db = json.loads((ROOT / "database.json").read_text(encoding="utf-8")) + sha1, entry = next( + (k, e) for k, e in db["files"].items() if e.get("sha256") + ) + self.assertEqual(sha1_for_hash("sha256", entry["sha256"], db), sha1) + self.assertEqual(sha1_for_hash("md5", entry["md5"][:29], db), sha1) + + def test_the_truth_anchors_a_sha256_only_entry(self): + """rust_dos and ares name files by sha256 alone: the truth left their + md5 empty, so md5 platforms never received them.""" + from scripts.resolve.truthsystems import _enrich_hashes + + db = {"files": {"s" * 40: {"sha1": "s" * 40, "md5": "m" * 32, "sha256": "f" * 64, + "crc32": "0badf00d", "size": 16}}, + "indexes": {"by_sha256": {"f" * 64: "s" * 40}}} + entry = {"name": "5200.rom", "sha256": "F" * 64} + _enrich_hashes(entry, db) + self.assertEqual((entry["md5"], entry["sha1"], entry["size"]), ("m" * 32, "s" * 40, 16)) + + +class ErrorsGoToStderr(unittest.TestCase): + """The lock refusal and "no pack for" went to stdout: a run redirected to + a log showed nothing on the terminal and exited 1.""" + + @staticmethod + def _leading_text(node: ast.expr) -> str: + if isinstance(node, ast.Constant) and isinstance(node.value, str): + return node.value + if isinstance(node, ast.JoinedStr) and node.values: + return ErrorsGoToStderr._leading_text(node.values[0]) + return "" + + def test_no_error_line_is_printed_to_stdout(self): + for script in ("generate_pack.py", "pipeline.py"): + tree = ast.parse(script_source(script)) + seen = 0 + for node in ast.walk(tree): + if not (isinstance(node, ast.Call) and getattr(node.func, "id", "") == "print" + and node.args): + continue + text = self._leading_text(node.args[0]) + # Detail lines under a pack's own verdict stay with it. + if not text.lstrip().startswith("ERROR") or text.startswith(" "): + continue + seen += 1 + with self.subTest(script=script, line=node.lineno): + self.assertIn("file", [k.arg for k in node.keywords]) + self.assertGreater(seen, 0, script) + + +class PipelineOutputDirIsTheOneItWrites(unittest.TestCase): + """Started from scripts/, the pipeline locked and purged scripts/dist/ + while every step, run from the repository root, wrote to dist/.""" + + def test_the_default_is_the_root_dist_wherever_the_run_starts(self): + previous = os.getcwd() + self.addCleanup(os.chdir, previous) + os.chdir(ROOT / "scripts") + self.assertEqual(runner.pack_output_dir(None), str(ROOT / "dist")) + self.assertEqual(runner.pack_output_dir("out"), str(ROOT / "scripts" / "out")) + + def test_main_resolves_it_before_the_lock(self): + source = script_source("pipeline.py") + body = source[source.index("def main("):] + self.assertLess( + body.index("args.output_dir = pack_output_dir(args.output_dir)"), + body.index("hold_artifact_lock(args.output_dir)"), + ) + + +class ToolsRunFromAnyDirectory(unittest.TestCase): + """From scripts/, verify.py and generate_pack.py ended on a + FileNotFoundError traceback about platforms/_registry.yml.""" + + def _run(self, cwd: Path, *argv: str) -> subprocess.CompletedProcess: + return subprocess.run( + [sys.executable, *argv], cwd=cwd, capture_output=True, text=True, + timeout=600, + check=False, + ) + + def test_listing_works_from_scripts(self): + for script in ("verify.py", "generate_pack.py"): + with self.subTest(script=script): + proc = self._run( + ROOT / "scripts", str(ROOT / "scripts" / script), + "--platform", "RetroArch", "--list-systems", + ) + self.assertEqual(proc.returncode, 0, proc.stderr) + self.assertNotIn("Traceback", proc.stderr) + self.assertIn("sony-playstation", proc.stdout) + + def test_a_typed_path_is_read_from_where_it_was_typed(self): + with tempfile.TemporaryDirectory() as tmp: + proc = self._run( + Path(tmp), str(ROOT / "scripts" / "generate_pack.py"), + "--manifest-targets", "--output-dir", "lists", + ) + self.assertEqual(proc.returncode, 0, proc.stderr) + self.assertTrue(Path(tmp, "lists", "retroarch.json").is_file()) + + +class ATargetTypoIsAnErrorInEveryTool(unittest.TestCase): + """cross_reference.py ended a mistyped --target in a traceback, and the + hint sent cross_reference and slots users to a flag they do not have.""" + + def test_each_tool_names_the_closest_target(self): + for script in ("cross_reference.py", "slots.py", "verify.py"): + with self.subTest(script=script): + proc = subprocess.run( + [sys.executable, f"scripts/{script}", "--platform", "retroarch", + "--target", "swich"], + cwd=ROOT, capture_output=True, text=True, timeout=300, + check=False, + ) + output = proc.stdout + proc.stderr + self.assertNotEqual(proc.returncode, 0) + self.assertNotIn("Traceback", output) + self.assertIn("Close matches: switch.", output) + self.assertIn("verify.py --platform retroarch --list-targets", output) + + +class AnUnknownSystemIsRefusedBeforeAnyWork(unittest.TestCase): + """generate_pack checked --system inside the build: a typo took the + output lock and refreshed every data directory, then ended on a WARNING.""" + + def test_refused_before_the_lock_and_the_refresh(self): + with tempfile.TemporaryDirectory() as tmp: + out = Path(tmp) / "never" + with mock.patch.dict(os.environ, {"RETROBIOS_OFFLINE": ""}): + proc = subprocess.run( + [sys.executable, "scripts/generate_pack.py", "--platform", "batocera", + "--system", "playstaton-nothing", "--output-dir", str(out)], + cwd=ROOT, capture_output=True, text=True, timeout=120, + check=False, + ) + self.assertEqual(proc.returncode, 2, proc.stdout + proc.stderr) + self.assertIn( + "error: --system playstaton-nothing: unknown system playstaton-nothing", + proc.stderr, + ) + self.assertFalse(out.exists()) + + def test_a_known_system_passes_the_early_check(self): + import argparse + + from model.cliargs import resolve_system_ids + + parser = argparse.ArgumentParser() + args = argparse.Namespace( + system="sony-playstation", platform="retroarch", all=False, + platforms_dir=str(ROOT / "platforms"), manifest=False, + ) + self.assertEqual(resolve_system_ids(args, parser), ["sony-playstation"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_audit_docs.py b/tests/test_audit_docs.py new file mode 100644 index 000000000..3cb004f05 --- /dev/null +++ b/tests/test_audit_docs.py @@ -0,0 +1,838 @@ +"""Audit regressions on the README, the wiki and the help texts the tools print.""" + +from __future__ import annotations + +import tests +from tests.sources import script_source +import ast +import io +import json +import os +import re +import subprocess +import sys +import unittest +from pathlib import Path +from unittest import mock +import yaml +from tests.auditsupport import ROOT + + +class ReadmeRegressions(unittest.TestCase): + """The README advertises commands, and these must stay executable. + + Wording is the maintainer's, so nothing here asserts prose. What is + asserted is that every flag and URL the README hands a reader is one the + shipped scripts actually accept. + """ + + def _quick_install(self) -> str: + readme = (ROOT / "README.md").read_text(encoding="utf-8") + return readme.split("## Install in one line", 1)[1].split( + "## Or download a ZIP", 1 + )[0] + + def test_advertised_bootstrap_urls_are_the_shipped_ones(self): + from sitegen import bootstrap as sitebootstrap + from sitegen.guidedata import install_base + + quick_install = self._quick_install() + for name in sitebootstrap.SOURCES: + url = f"{install_base()}/{name}" + self.assertIn(f"{url} |", quick_install, f"{name} bootstrap URL missing") + # The site serves each bootstrap with install.py read from the + # commit it was built from, the raw form from main. + commit = "0" * 40 + for name in sitebootstrap.SOURCES: + self.assertIn(sitebootstrap.installer_url(commit), + sitebootstrap.served_text(name, ROOT, commit)) + self.assertIn( + "https://raw.githubusercontent.com/Abdess/retrobios/main/install.py", + (ROOT / "install.sh").read_text(encoding="utf-8"), + ) + + def test_advertised_installer_flags_exist(self): + quick_install = self._quick_install() + advertised = set(re.findall(r"(? str: + from packs.readme import build_readme + + registry = yaml.safe_load((ROOT / "platforms" / "_registry.yml").read_text()) + install = registry["platforms"][platform].get("install") or {} + text = build_readme(platform, platform, "", 1, 1, + detect=install.get("detect", []), + standalone_copies=install.get("standalone_copies", [])) + return text[text.index("INSTALLATION"):text.index("TROUBLESHOOTING")] + + def test_retroarch_offers_the_windows_installer(self): + from sitegen.guidedata import install_ps1, install_sh + + guide = self._guide("retroarch") + self.assertIn(f"{install_sh()} | sh", guide) + self.assertIn(f"{install_ps1()} | iex", guide) + + def test_emudeck_keys_match_the_registry_and_the_flag(self): + import re + + guide = self._guide("emudeck") + self.assertIn("--standalone-copies", guide) + self.assertNotIn("emulator keys automatically", guide) + self.assertNotIn("handles this for you", guide) + with (ROOT / "platforms" / "_registry.yml").open(encoding="utf-8") as handle: + registry = yaml.safe_load(handle) + targets = { + target.rstrip("/").replace("$HOME", "~") + for copy in registry["_standalone_copies"] + for target in copy.get("targets", {}).get("linux", []) + } + named = { + path.rstrip("/") for path in re.findall(r"-> (~/\S+)", guide) + } + self.assertEqual(sorted(named - targets), []) + + def test_retropie_never_sends_a_pc_to_the_linux_partition(self): + guide = self._guide("retropie") + from sitegen.guidedata import install_sh + + self.assertNotIn("Put the SD card in your PC", guide) + self.assertIn(f"{install_sh()} | sh", guide) + + +class FaqRegressions(unittest.TestCase): + """The FAQ states facts the code owns, and these tie it back to the source. + + Three of its claims had drifted: a pinned MAME version, Adler-32 + attributed to Dolphin's IPL instead of its DSP ROMs, and a verbose + per-emulator report described as the only way to catch a bad file on an + existence platform. Readers act on all three. + """ + + @staticmethod + def _faq() -> str: + # The questions about hashes and checks moved to the technical FAQ. + return "\n\n".join( + (ROOT / "wiki" / name).read_text(encoding="utf-8") + for name in ("faq.md", "technical-faq.md") + ) + + @staticmethod + def _profile(key: str) -> dict: + with (ROOT / "emulators" / f"{key}.yml").open(encoding="utf-8") as handle: + return yaml.safe_load(handle) + + def test_the_romset_table_is_written_from_the_profiles(self): + # Typed by hand, the table and the prose under it kept MAME 0.160 + # and FinalBurn Neo 1.0.0.2, versions no source at the pins states, + # and the test holding them to the profiles kept the errors in step. + from sitegen import emulatormetadata + from model.profiles import load_emulator_profiles + + profiles = load_emulator_profiles(str(ROOT / "emulators"), skip_aliases=False) + page = (ROOT / "wiki" / "technical-faq.md").read_text(encoding="utf-8") + self.assertEqual( + page, emulatormetadata.with_romset_table(page, profiles), + "wiki/technical-faq.md romset table is stale: run scripts/generate_site.py", + ) + prose = page.split("### How this is known", 1)[1].split("\n## ", 1)[0] + self.assertIsNone(re.search(r"\(0\.\d", prose), + "the prose under the table types a version again") + + def test_adler32_is_attributed_to_the_files_that_carry_it(self): + dolphin = self._profile("dolphin") + carriers = { + f["name"] for f in dolphin["files"] if f.get("known_hash_adler32") + } + self.assertTrue(carriers, "dolphin.yml declares no Adler-32 hash") + sentence = self._faq().split("Adler-32", 1)[1].split("\n\n", 1)[0] + for name in carriers: + self.assertIn(name, sentence, f"FAQ omits the Adler-32 file {name}") + self.assertNotIn( + "IPL.bin", carriers, + "IPL.bin gained an Adler-32 hash, but the docs say it has none", + ) + for page in ("faq.md", "profiling.md"): + text = (ROOT / "wiki" / page).read_text(encoding="utf-8") + for line in text.splitlines(): + if "Adler-32" in line or "adler32" in line: + self.assertNotIn( + "IPL", line, + f"wiki/{page} ties Adler-32 back to IPL: {line.strip()}", + ) + + def test_existence_platforms_are_not_told_the_verbose_report_is_the_only_check(self): + self.assertIn( + "DISCREPANCY", + self._faq(), + "the FAQ must name the check the platform report performs itself", + ) + self.assertIn( + 'result["discrepancy"]', + script_source("verify.py"), + "verify.py no longer raises the discrepancy the FAQ advertises", + ) + + +class CatalogRatioRegressions(unittest.TestCase): + """The catalog-matched count must read the same on every surface. + + The home page, the provenance page, the README and the stats export each + used to count matches on their own. Two of them dropped the systems + scope, so the site published 566 and 553 for the same quantity, one click + apart, and the export paired the wider number with composition.systems as + its denominator. + """ + + _SURFACES = ("scripts/generate_site.py", "scripts/generate_readme.py") + + def test_no_surface_counts_matches_on_its_own(self): + for relative in self._SURFACES: + tree = ast.parse(script_source(relative.removeprefix("scripts/"))) + inline = [ + node.lineno + for node in ast.walk(tree) + if isinstance(node, ast.Call) + and getattr(node.func, "id", "") == "sum" + and "provenance" in ast.dump(node) + ] + self.assertEqual( + inline, + [], + f"{relative} counts provenance matches inline at {inline}; " + "call common.count_catalog_matched instead", + ) + + def test_arcade_and_engine_data_stay_out_of_the_ratio(self): + from scripts.model.composition import compute_composition, count_catalog_matched + + db = { + "files": { + "a": {"path": "bios/Sony/PlayStation/scph5501.bin", "size": 1, + "provenance": {"redump": {}}}, + "b": {"path": "bios/Arcade/Arcade/neogeo.zip", "size": 1, + "provenance": {"no-intro": {}}}, + "c": {"path": "bios/ScummVM/soundfonts/Roland.sf2", "size": 1, + "provenance": {"tosec": {}}}, + "d": {"path": "bios/Sega/Saturn/sega_101.bin", "size": 1}, + } + } + self.assertEqual(count_catalog_matched(db), 1) + self.assertEqual(compute_composition(db)["systems"]["files"], 2) + + def test_engine_and_publisher_trees_are_game_data(self): + """Engine data collected under `Game Engines/` and under a game + publisher counted as console and computer system files: 7 697 of + them made the README announce 13 564 system files.""" + from scripts.model.composition import composition_tier + + for path in ( + "bios/Game Engines/C-Dogs SDL/cdogs/data/guns.json", + "bios/Id Software/Quake III Arena/baseq3/pak1.pk3", + "bios/Epic MegaGames/Jazz Jackrabbit 2/jazz2/Source/share.j2e", + "bios/RPG Maker/easyrpg/rtp/2000/Backdrop/Bridge.png", + ): + self.assertEqual(composition_tier(path), "game_data", path) + self.assertEqual(composition_tier("bios/Sony/PlayStation/scph5501.bin"), "systems") + self.assertEqual(composition_tier("bios/Microsoft/MSX/MSX2.ROM"), "systems") + + def test_readme_ratio_matches_the_database(self): + from scripts.model.composition import compute_composition, count_catalog_matched + from scripts.model.database import load_database + + database = ROOT / "database.json" + if not database.exists(): + self.skipTest("database.json not generated") + db = load_database(str(database)) + readme = (ROOT / "README.md").read_text(encoding="utf-8") + match = re.search( + r"\*\*([\d,]+) of ([\d,]+) system files\*\* matched to", readme + ) + if match is None: + # The README states no ratio since it leads to the site: a ratio + # it states must still be the database's. + return + matched, total = (int(g.replace(",", "")) for g in match.groups()) + self.assertEqual(matched, count_catalog_matched(db)) + self.assertEqual(total, compute_composition(db)["systems"]["files"]) + + +class ContributorsSurviveAFailedRequest(unittest.TestCase): + """The one part of the README that comes from the network. + + A refused or rate-limited request left the list empty, which deleted the + section from a published README. It happened during a pipeline run and + the result was committed, after which the freshness check regenerated the + section and failed on the difference. Losing the list is a worse answer + than publishing a stale one. + """ + + def _block(self, text: str): + import tempfile + + from sitegen.readme import _existing_contributor_block + + with tempfile.NamedTemporaryFile("w", suffix=".md", delete=False) as handle: + handle.write(text) + name = handle.name + try: + return _existing_contributor_block(name) + finally: + os.unlink(name) + + def test_a_published_list_is_read_back(self): + text = ( + "# Title\n\n## Contributors\n\n" + 'a\n' + 'b\n\n' + "## Community tools\n\nsomething else\n" + ) + block = self._block(text) + self.assertEqual(block[0], "## Contributors") + self.assertIn('alt="a"', "\n".join(block)) + self.assertIn('alt="b"', "\n".join(block)) + self.assertNotIn("Community tools", "\n".join(block)) + self.assertNotIn("something else", "\n".join(block)) + + def test_a_readme_without_the_section_yields_nothing(self): + self.assertEqual(self._block("# Title\n\n## Other\n\ntext\n"), []) + + def test_an_unreadable_file_yields_nothing(self): + from sitegen.readme import _existing_contributor_block + + self.assertEqual(_existing_contributor_block("/nonexistent/README.md"), []) + + def test_the_committed_readme_still_carries_its_contributors(self): + """Regenerating offline must never be the reason this disappears.""" + text = (ROOT / "README.md").read_text() + # Missing is the failure this guards, never a reason to skip. + self.assertIn("## Contributors", text) + self.assertGreater( + text.count('a'] + text = render_readme(readme_inputs(kept_contributors=kept)) + self.assertIn("\n".join(kept) + "\n\n\n## Community tools", text) + + def test_a_fetched_list_replaces_the_kept_block(self): + from sitegen.readme import render_readme + from tests.readmeinputs import readme_inputs + + text = render_readme(readme_inputs( + contributors=[{"login": "someone", "avatar_url": "https://a/x"}], + kept_contributors=["## Contributors", "", "stale"], + )) + self.assertIn( + '## Contributors\n\nsomeone\n', text) + self.assertNotIn("stale", text) + + def test_no_list_and_nothing_kept_leaves_the_section_out(self): + from sitegen.readme import render_readme + from tests.readmeinputs import readme_inputs + + self.assertNotIn("## Contributors", render_readme(readme_inputs())) + + def test_the_loader_keeps_the_published_block_when_the_request_fails(self): + import tempfile + + from sitegen import readme + + with tempfile.TemporaryDirectory() as tmp: + path = Path(tmp) / "README.md" + path.write_text("# T\n\n## Contributors\n\nkept line\n\n## Other\n", encoding="utf-8") + with mock.patch.object(readme, "README_PATH", path), \ + mock.patch.object(readme, "fetch_contributors", return_value=[]), \ + mock.patch.object(readme, "list_registered_platforms", return_value=[]), \ + mock.patch("model.registry.load_data_dir_registry", return_value={}), \ + mock.patch.object(readme, "platform_coverages", return_value={}), \ + mock.patch.object(readme, "load_emulator_profiles", return_value={}), \ + mock.patch.object(readme.releaserecord, "load_advertised", return_value={}), \ + mock.patch.object(readme, "_extract_cells", return_value={}), \ + mock.patch.object(readme.ledger, "rebuild_counts", + return_value={"total": 0, "exact": 0, "canonical": 0}), \ + mock.patch.object(readme, "clone_line", return_value=""), \ + mock.patch("sys.stdout", new_callable=io.StringIO): + inputs = readme.load_readme_inputs({}, "platforms") + self.assertEqual(inputs.kept_contributors, ["## Contributors", "", "kept line"]) + self.assertIn("## Contributors\n\nkept line\n", readme.render_readme(inputs)) + + def test_the_contributor_list_is_not_asked_offline(self): + from sitegen import readme + + with mock.patch.dict(os.environ, {"RETROBIOS_OFFLINE": "1"}), \ + mock.patch.object(readme.forgehttp, "fetch_body", + side_effect=AssertionError("network")): + self.assertEqual(readme.fetch_contributors(), []) + + def test_contributors_are_read_through_the_retrying_client(self): + from sitegen import readme + + answer = json.dumps([ + {"login": "someone", "type": "User"}, + {"login": "dependabot[bot]", "type": "Bot"}, + {"login": readme.REPO.split("/")[0], "type": "User"}, + ]).encode() + with mock.patch.dict(os.environ, {"RETROBIOS_OFFLINE": ""}), \ + mock.patch.object(readme.forgehttp, "fetch_body", return_value=answer) as fetch: + self.assertEqual([c["login"] for c in readme.fetch_contributors()], ["someone"]) + self.assertIn("/contributors", fetch.call_args.args[0]) + + +class EveryReadmeNamesItsFolder(unittest.TestCase): + """The Lakka pack's README reused RetroArch's guide and never named + /storage/system, the folder the registry and the installer use.""" + + def test_the_registry_folder_is_in_the_guide(self): + from scripts.packs.readme import build_readme + + registry = yaml.safe_load((ROOT / "platforms" / "_registry.yml").read_text()) + for name, entry in registry["platforms"].items(): + folder = (entry.get("extract_to") or "").rstrip("/") + if not folder: + continue + with self.subTest(platform=name): + text = build_readme(name, name, "", 1, 1, + detect=[{"os": "linux", "bios_path": folder}]) + self.assertIn(folder, text) + lakka = build_readme("lakka", "Lakka", "", 1, 1) + self.assertNotIn("retroarch/system", lakka) + + +class TheToolsPageSaysWhatDedupDoes(unittest.TestCase): + """tools.md said duplicates move to .variants/ (they are deleted) and + named 2 of the 11 directories dedup leaves alone.""" + + def test_every_protected_tree_is_named(self): + from scripts.model import nodedup + + line = next( + row for row in (ROOT / "wiki" / "tools.md").read_text().splitlines() + if row.startswith("| `dedup.py`") + ) + self.assertNotIn(".variants", line) + for name in nodedup.NODEDUP_DIRS: + self.assertIn(name, line) + + +class ThePipelineTableNamesEveryStep(unittest.TestCase): + """tools.md listed the steps without 1c, 2b2, 3a and 3b.""" + + def test_every_labelled_step_is_documented(self): + labels = set(re.findall( + r'"(\d[a-z]?\d?)(?:/8)? [a-z]', script_source("pipeline.py") + )) + doc = (ROOT / "wiki" / "tools.md").read_text() + documented = set(re.findall(r"^\| (\d[a-z]?\d?)(?:/8)? \|", doc, re.MULTILINE)) + self.assertEqual(labels - documented, set()) + + +class DocumentedHashLookupsFindTheirFile(unittest.TestCase): + """The --from-md5 example was a test fixture hash: copied from the docs, + it answered NOT FOUND, which then exited 0.""" + + def test_every_documented_lookup_is_in_the_database(self): + db = json.loads((ROOT / "database.json").read_text(encoding="utf-8")) + by_md5 = db["indexes"]["by_md5"] + found = 0 + for page in sorted((ROOT / "wiki").glob("*.md")): + text = page.read_text(encoding="utf-8") + for md5 in re.findall(r"--from-md5 ([0-9a-f]{32})\b", text): + found += 1 + with self.subTest(page=page.name, md5=md5): + self.assertIn(md5, by_md5) + self.assertGreater(found, 0) + + +class ToolReferenceListsEveryModule(unittest.TestCase): + """The exporter table described retropie_exporter as a System.dat writer + and left out bizhawk, misterfpga and rocknix, and the target table missed + recalbox and rocknix. A contributor reads these tables as the map.""" + + def _rows(self, heading: str) -> set[str]: + text = (ROOT / "wiki" / "tools.md").read_text(encoding="utf-8") + section = text.split(f"## {heading}\n", 1)[1].split("\n## ", 1)[0] + return set(re.findall(r"^\| `(\w+)` \|", section, re.M)) + + def test_every_exporter_has_a_row(self): + modules = {p.stem for p in (ROOT / "scripts" / "exporter").glob("*_exporter.py")} + self.assertEqual(self._rows("Exporters"), modules - {"base_exporter"}) + + def test_every_target_scraper_has_a_row(self): + modules = { + p.stem for p in (ROOT / "scripts" / "scraper" / "targets").glob("*_targets_scraper.py") + } + self.assertEqual(self._rows("Target scrapers"), modules) + + +class ToolReferenceCountsMatchTheirArtifacts(unittest.TestCase): + """tools.md said 67 derivable entries for 79 and 1,113 identified + archives for 1,181: counts written by hand drift from the tools.""" + + def setUp(self): + self.text = (ROOT / "wiki" / "tools.md").read_text(encoding="utf-8") + + def test_recipe_store_counts(self): + store = json.loads((ROOT / "recipes" / "mame.json").read_text(encoding="utf-8")) + versions = {dat for entry in store["entries"] for dat in entry.get("dats") or [entry["dat"]]} + listed = sum(len(entry.get("dats") or [entry["dat"]]) for entry in store["entries"]) + match = re.search( + r"(\d+) MAME versions produce ([\d,]+) entries but only ([\d,]+)\s+distinct", + self.text, + ) + self.assertIsNotNone(match) + stated = [int(group.replace(",", "")) for group in match.groups()] + self.assertEqual(stated, [len(versions), listed, len(store["entries"])]) + + def test_no_derivable_count(self): + """The count now lives in derivable.json alone, which step 1b rewrites.""" + self.assertNotRegex(self.text, r"\d+ entries on the current snapshots") + + +class WikiProseHasNoTornSentence(unittest.TestCase): + """tools.md read "replaces each destination atomically. The shell and / + Both one-liners verify...": half of an old sentence left in front of + its rewrite, on the page that explains the installer's trust boundary.""" + + STARTERS = {"Both", "The", "This", "It", "A", "An", "Each", "Every", "When", + "If", "They", "These", "That", "There"} + + def test_no_line_ends_on_a_function_word_before_a_new_sentence(self): + for page in sorted((ROOT / "wiki").glob("*.md")): + lines = page.read_text(encoding="utf-8").splitlines() + in_code = False + for number, (line, following) in enumerate(zip(lines, lines[1:]), 1): + if line.startswith("```"): + in_code = not in_code + if in_code: + continue + if (re.search(r"\b(and|or|the|a|an|of|to)$", line.rstrip()) + and following.split(" ")[0] in self.STARTERS): + self.fail(f"{page.name}:{number} ends mid-sentence: {line.strip()!r}") + + +class EveryOptionIsDocumented(unittest.TestCase): + """profile_sync's --system, --stale-before and --ref, auto_fetch + --create-issues, download.py --info and forty more were in no page: a + maintainer ran --all and spent the API quota that --system would have + saved. --help lists a flag, but only a page says when to reach for it.""" + + def test_every_long_option_of_a_tracked_script_is_in_the_docs(self): + tracked = subprocess.run( + ["git", "ls-files", "scripts"], capture_output=True, text=True, + cwd=str(ROOT), check=True, + ).stdout.split() + docs = "\n".join( + path.read_text(encoding="utf-8") + for path in [*sorted((ROOT / "wiki").glob("*.md")), + ROOT / "README.md", ROOT / "CONTRIBUTING.md"] + ) + option = re.compile(r'add_argument\(\s*(?:"-\w",\s*)?"(--[\w-]+)"') + undocumented = sorted( + f"{name}: {flag}" + for name in tracked if name.endswith(".py") + for flag in set(option.findall((ROOT / name).read_text(encoding="utf-8"))) + if not re.search(re.escape(flag) + r"(?![\w-])", docs) + ) + self.assertEqual(undocumented, []) + + +class OfflineHelpSaysWhatItCuts(unittest.TestCase): + """--offline read "Skip data directory freshness check" while it also + stops release assets from downloading: on a fresh clone the gitignored + files were missing from the pack and nothing had announced it.""" + + def test_both_helps_name_the_release_assets(self): + for script in ("generate_pack.py", "pipeline.py"): + with self.subTest(script=script): + out = subprocess.run( + [sys.executable, f"scripts/{script}", "--help"], + capture_output=True, text=True, cwd=str(ROOT), check=True, + ).stdout + block = out.split("--offline", 2)[-1].split("\n --", 1)[0] + self.assertIn("release", " ".join(block.split())) + + +class PipelineDocstringNamesThePrintedSteps(unittest.TestCase): + """The docstring numbered 1 to 9 while the run prints 1/8 to 8/8, and + had no 2a, 2b, 3a, 3b or 6: a reader of a failed `6/8 pack integrity` + found nothing under 6.""" + + def test_the_two_lists_hold_the_same_steps(self): + import ast + + source = (ROOT / "scripts" / "pipeline.py").read_text(encoding="utf-8") + doc = ast.get_docstring(ast.parse(source)) + listed = set(re.findall(r"^ (\d[a-z0-9]*)\s{2,}", doc, re.M)) + from orchestrate.labels import STEP_LABELS, step_number + + printed = {step_number(key) for key in STEP_LABELS} + self.assertEqual(listed, printed) + + +class DocumentedExamplesHoldTogether(unittest.TestCase): + """The verification block downloaded RetroArch_BIOS_Pack.zip*, a name + no release ever published (packs are versioned and split), and the + first-install example ended on "72 files installed" after announcing a + download of 12,893.""" + + def test_the_verification_pattern_matches_published_pack_names(self): + import fnmatch + import re + + page = (ROOT / "wiki" / "release-process.md").read_text(encoding="utf-8") + patterns = re.findall(r"--pattern '([^']*Pack[^']*)'", page) + self.assertTrue(patterns) + for name in ("RetroArch_Lakka_v1.22.2_BIOS_Pack.part1of2.zip", + "RetroArch_v1.22.2_BIOS_Pack.zip"): + with self.subTest(name=name): + self.assertTrue(any(fnmatch.fnmatch(name, p) for p in patterns)) + + def test_the_first_install_example_counts_one_number(self): + import re + + # The annotated run moved from First install to the installer page. + page = (ROOT / "wiki" / "installer.md").read_text(encoding="utf-8") + downloading = re.search(r"Downloading (\d+) files", page).group(1) + done = re.search(r"Done\. (\d+) files installed", page).group(1) + # The data trees come after the download, counted in the index. + index = page[page.index("Fetching file index for batocera"):] + trees = re.search(r"^ .* and (\d+) data files", index, re.M) + self.assertEqual(int(done), int(downloading) + (int(trees.group(1)) if trees else 0)) + + +class TheReadmeCountsSystemsAsListSystemsDoes(unittest.TestCase): + """The README counted every raw spelling (nes and nintendo-nes as two) + and announced 550 systems while the tool it points to listed 513.""" + + def test_one_count(self): + import io + import re + from contextlib import redirect_stdout + + from scripts.model.cliargs import list_system_ids + + out = io.StringIO() + with redirect_stdout(out): + list_system_ids(str(ROOT / "emulators")) + listed = len(out.getvalue().splitlines()) + readme = (ROOT / "README.md").read_text(encoding="utf-8") + announced = int(re.search(r"\*\*(\d+) systems\*\*", readme).group(1)) + self.assertEqual(announced, listed) + + +class DocsDescribeTheRegistriesTheyName(unittest.TestCase): + """The contributing guide said files over 50 MB are release assets and that + RPG Maker and ScummVM were the trees kept out of dedup. `.gitignore` + decides the first, four committed files exceed 50 MB, and NODEDUP_DIRS + holds eleven trees.""" + + SIZE_RULE = re.compile(r"(over|larger than|>)\s*50\s*MB[^\n]*(release|asset)", re.I) + + def _texts(self): + paths = sorted((ROOT / "wiki").glob("*.md")) + paths += [ROOT / "scripts" / "generate_readme.py", ROOT / "CONTRIBUTING.md"] + return [(p, p.read_text(encoding="utf-8")) for p in paths] + + def test_no_page_says_size_decides_a_release_asset(self): + offenders = [str(p.relative_to(ROOT)) for p, text in self._texts() + if self.SIZE_RULE.search(text)] + self.assertEqual(offenders, []) + + def test_the_dedup_list_is_named_whole_or_by_its_constant(self): + from model.nodedup import NODEDUP_DIRS + tools = (ROOT / "wiki" / "tools.md").read_text(encoding="utf-8") + line = next(entry for entry in tools.splitlines() if "NODEDUP_DIRS" in entry) + # Compared as list items: `mame` was missing while the substring + # test found it in `_mame_clones.json` on the same line. + listed = line.split("`NODEDUP_DIRS`", 1)[1].split(":", 1)[1].rstrip(" |") + self.assertEqual( + sorted(item.strip() for item in listed.split(",")), + sorted(NODEDUP_DIRS), + ) + readme_gen = script_source("generate_readme.py") + self.assertIn("NODEDUP_DIRS", readme_gen) + + +class SkipPacksHelpSaysWhatRuns(unittest.TestCase): + """--help said "Only regenerate DB and verify" while the run went on to + rewrite derivable.json, README.md and docs/.""" + + def test_the_help_names_the_steps_that_still_run(self): + proc = subprocess.run( + [sys.executable, "scripts/pipeline.py", "--help"], + cwd=ROOT, capture_output=True, text=True, timeout=60, check=True, + ) + text = " ".join(proc.stdout.split()) + self.assertNotIn("Only regenerate DB and verify", text) + self.assertIn("step 4e still rewrites install/games/, and steps 7 to 8b rewrite README.md " + "and the site unless --skip-docs is given", text) + self.assertNotIn("docs/", text) + + def test_every_step_it_names_is_one_it_skips(self): + from orchestrate.labels import step_number + + source = script_source("pipeline.py") + keys = re.findall(r'skip_notice\("(\w+)", "--skip-packs"\)', source) + skipped = {step_number(key) for key in keys} + self.assertEqual(skipped, {"4", "4b", "4c", "6"}) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_audit_manifests.py b/tests/test_audit_manifests.py new file mode 100644 index 000000000..e61cfe334 --- /dev/null +++ b/tests/test_audit_manifests.py @@ -0,0 +1,809 @@ +"""Audit regressions on install manifests, the installer boundary and release assets.""" + +from __future__ import annotations + +import tests +from tests.sources import script_source +import hashlib +import json +import re +import subprocess +import sys +import tempfile +import unittest +import zipfile +from pathlib import Path +from unittest import mock +import yaml +import install +from orchestrate import runner +from scripts.packs.targets import generate_target_manifests +from tests.auditsupport import HAS_JSONSCHEMA, ROOT + + +class InstallerBoundaryRegressions(unittest.TestCase): + def _manifest(self, dest: str) -> dict: + return { + "manifest_version": 2, + "platform": "retroarch", + "files": [ + { + "dest": dest, + "size": 1, + "sha1": "a" * 40, + "sha256": "b" * 64, + "repo_path": "bios/test.bin", + "cores": None, + } + ], + "standalone_copies": [], + } + + def test_manifest_destination_traversal_is_rejected(self): + with self.assertRaisesRegex(ValueError, "unsafe"): + install._validate_manifest(self._manifest("../escape"), "retroarch") + + def test_manifest_repo_source_is_confined_to_bios(self): + manifest = self._manifest("safe.bin") + manifest["files"][0]["repo_path"] = "scripts/pipeline.py" + with self.assertRaisesRegex(ValueError, "outside bios"): + install._validate_manifest(manifest, "retroarch") + + def test_omitted_destination_cannot_overlap_a_download(self): + manifest = self._manifest("safe.bin") + manifest["omitted_files"] = [ + { + "dest": "safe.bin", + "name": "safe.bin", + "system": "console", + "required": True, + "reason": "hash_mismatch", + "cores": None, + } + ] + manifest["total_omitted"] = 1 + with self.assertRaisesRegex(ValueError, "conflicting omitted"): + install._validate_manifest(manifest, "retroarch") + + def test_omitted_destination_traversal_is_rejected(self): + manifest = self._manifest("safe.bin") + manifest["omitted_files"] = [ + { + "dest": "../unsafe.bin", + "name": "unsafe.bin", + "system": "console", + "required": True, + "reason": "hash_mismatch", + "cores": None, + } + ] + manifest["total_omitted"] = 1 + with self.assertRaisesRegex(ValueError, "unsafe"): + install._validate_manifest(manifest, "retroarch") + + @unittest.skipUnless(HAS_JSONSCHEMA, "validating a schema needs jsonschema") + def test_target_schema_accepts_the_null_the_generator_emits(self): + """The schema and generate_target_manifests must agree on null. + + A target with no core list is written as null, and a schema that rejects + it turns a valid manifest into a CI failure. + """ + from jsonschema import Draft202012Validator + + schema = json.loads( + (ROOT / "schemas" / "target-manifest.schema.json").read_text( + encoding="utf-8" + ) + ) + validator = Draft202012Validator(schema) + document = {"windows": None, "switch": ["a5200"]} + self.assertEqual(list(validator.iter_errors(document)), []) + + @unittest.skipUnless(HAS_JSONSCHEMA, "validating a schema needs jsonschema") + def test_pack_manifests_are_read_from_inside_the_archive(self): + """generate_pack writes manifest.json into the ZIP, not beside it. + + A filesystem glob over dist/ matches nothing and reports success + without validating a single document. + """ + from schemas import packmanifests + + with tempfile.TemporaryDirectory() as directory: + dist = Path(directory) + broken = { + "schema_version": 1, + "version": 1, + "generator": "retrobios generate_pack.py", + "generated": "2026-08-10T00:00:00Z", + "files": [{"path": "a.bin", "sha1": "nope", "md5": "nope", + "size": 1, "status": "verified", "name": "a.bin"}], + "summary": {"total_files": 1, "verified": 1, "untracked": 0, + "errors": 0}, + "errors": [], + } + with zipfile.ZipFile(dist / "Pack.zip", "w") as archive: + archive.writestr("manifest.json", json.dumps(broken)) + + errors = packmanifests.validate_pack_manifests(dist) + self.assertTrue(errors, "an invalid in-archive manifest must be reported") + self.assertTrue(any("sha1" in message for message in errors), errors) + + @unittest.skipUnless(HAS_JSONSCHEMA, "validating a schema needs jsonschema") + def test_packs_being_written_are_a_skip_not_a_pass(self): + """Under a build's lock the reader returned [], the value of packs + that validated, and validate_schemas announced everything valid + without reading one.""" + from core.artifacts import ArtifactLockBusy, artifact_lock + from schemas import packmanifests, run + + with tempfile.TemporaryDirectory() as directory: + dist = Path(directory) / "dist" + dist.mkdir() + (dist / "Bad_BIOS_Pack.zip").write_bytes(b"not a zip") + self.assertTrue(packmanifests.validate_pack_manifests(dist)) + with artifact_lock(str(dist), exclusive=True): + with self.assertRaises(ArtifactLockBusy): + packmanifests.validate_pack_manifests(dist) + outcome = run.Validation() + with mock.patch.object(run.core.paths, "REPO_ROOT", Path(directory)): + run.generated_errors(outcome) + self.assertEqual(outcome.skipped, ["pack manifests skipped, dist in use"]) + + @unittest.skipUnless(HAS_JSONSCHEMA, "validating a schema needs jsonschema") + def test_a_pack_carries_its_install_list_and_board_lists(self): + """pack_systems puts the install list and the per-board core lists + in the pack's manifest.json, which install.py reads with the pack + alone. The pack schema refused both keys, and each is checked under + its own contract.""" + from packs import scope + from schemas import packmanifests + + install_list = json.loads((ROOT / "install" / "romm.json").read_text(encoding="utf-8")) + targets = {"browser": None, "rpi4": {"cores": ["mgba"], "images": ["rpi4"]}} + document = { + "schema_version": 1, "version": 1, + "generator": "retrobios generate_pack.py", + "generated": "2026-08-10T00:00:00Z", "files": [], + "summary": {"total_files": 0, "verified": 0, "untracked": 0, "errors": 0}, + "errors": [], + } + scope.annotate_pack_systems( + document, scope.pack_systems(install_list, targets)) + self.assertIn("install_list", document) + self.assertIn("targets", document) + with tempfile.TemporaryDirectory() as directory: + dist = Path(directory) + with zipfile.ZipFile(dist / "Pack.zip", "w") as archive: + archive.writestr("manifest.json", json.dumps(document)) + self.assertEqual(packmanifests.validate_pack_manifests(dist), []) + + broken = {**document, "targets": {"rpi4": [1]}, + "install_list": {**install_list, "files": "none"}} + with zipfile.ZipFile(dist / "Pack.zip", "w") as archive: + archive.writestr("manifest.json", json.dumps(broken)) + errors = packmanifests.validate_pack_manifests(dist) + self.assertTrue(any(":targets:" in message for message in errors), errors) + self.assertTrue(any(":install_list:" in message for message in errors), errors) + + def test_null_core_list_keeps_the_other_targets(self): + """A target without a core inventory must not void the manifest. + + generate_target_manifests emits null for a target that publishes no + core list. Rejecting the document would silently disable --target for + every target on that platform. + """ + normalized = install._validate_targets({"windows": None, "switch": ["a5200"]}) + self.assertIsNone(normalized["windows"]["cores"]) + self.assertEqual(normalized["switch"]["cores"], ["a5200"]) + + def test_legacy_target_lists_are_normalized(self): + self.assertEqual( + install._validate_targets({"rpi4": ["core-a", "core-b"]}), + {"rpi4": {"cores": ["core-a", "core-b"]}}, + ) + + +class TargetManifestRegressions(unittest.TestCase): + def test_yaml_scalar_core_is_rejected_instead_of_leaking_to_json(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + source = root / "source" + output = root / "output" + source.mkdir() + (source / "platform.yml").write_text( + "targets:\n device:\n cores: [81, valid-core]\n", + encoding="utf-8", + ) + with self.assertRaisesRegex(ValueError, "non-empty strings"): + generate_target_manifests(str(source), str(output)) + + def test_a_missing_targets_directory_fails_the_command(self): + """--manifest-targets printed the missing directory and exited 0 + with nothing written: the pipeline step read that as done.""" + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + with self.assertRaisesRegex(FileNotFoundError, "No targets directory"): + generate_target_manifests(str(root / "absent"), str(root / "out")) + (root / "plat").mkdir() + run = subprocess.run( + [sys.executable, str(ROOT / "scripts" / "generate_pack.py"), + "--manifest-targets", "--platforms-dir", str(root / "plat"), + "--output-dir", str(root / "out")], + capture_output=True, text=True, cwd=ROOT, check=False, + ) + self.assertEqual(run.returncode, 1, run.stderr) + self.assertIn("No targets directory at", run.stderr) + + +def _git_paths(*args: str, stdin: list[str] | None = None) -> set[str] | None: + """The NUL-separated paths a git command prints, or None outside a + checkout. check-ignore exits 1 when it matches nothing, an answer.""" + try: + result = subprocess.run( + ["git", *args], + input="".join(f"{p}\0" for p in stdin or []), + capture_output=True, text=True, cwd=ROOT, check=False, + ) + except FileNotFoundError: + return None + answered = (0, 1) if args[0] == "check-ignore" else (0,) + if result.returncode not in answered: + return None + return {p for p in result.stdout.split("\0") if p} + + +class ManifestVersionIsThePlatformsOwn(unittest.TestCase): + """Every install manifest named its list "1.0", and an inheriting YAML + took its parent's version: Lakka was published as RetroArch v1.22.2. + The installer compares the list's version with the one a machine runs, + so each manifest states the version its own platform YAML records.""" + + def setUp(self): + from scripts.model.platforms import _platform_config_cache + _platform_config_cache.clear() + + def test_committed_manifests_state_their_platform_version(self): + from scripts.model.platforms import load_platform_config + manifests = sorted((ROOT / "install").glob("*.json")) + self.assertTrue(manifests) + for path in manifests: + with self.subTest(manifest=path.name): + data = json.loads(path.read_text()) + config = load_platform_config(data["platform"], str(ROOT / "platforms")) + self.assertTrue(config.get("version")) + self.assertEqual(data["version"], str(config["version"])) + + def test_no_child_shows_its_parents_version(self): + from scripts.model.platforms import load_platform_config + platforms = ROOT / "platforms" + children = {} + for path in sorted(platforms.glob("*.yml")): + raw = yaml.safe_load(path.read_text()) or {} + if isinstance(raw, dict) and raw.get("inherits"): + children[path.stem] = raw + self.assertIn("lakka", children) + for name, raw in children.items(): + with self.subTest(platform=name): + parent = yaml.safe_load( + (platforms / f"{raw['inherits']}.yml").read_text()) + version = load_platform_config(name, str(platforms)).get("version") + self.assertEqual(version, raw.get("version")) + self.assertNotEqual(version, parent.get("version")) + + def test_an_unversioned_child_has_no_version(self): + from scripts.model.platforms import load_platform_config + with tempfile.TemporaryDirectory() as tmp: + Path(tmp, "parent.yml").write_text("platform: P\nversion: '2.0'\nsystems: {}\n") + Path(tmp, "child.yml").write_text("inherits: parent\nplatform: C\n") + self.assertNotIn("version", load_platform_config("child", tmp)) + + def test_lakka_names_the_release_its_cores_are_read_at(self): + platforms = ROOT / "platforms" + lakka = yaml.safe_load((platforms / "lakka.yml").read_text()) + targets = yaml.safe_load((platforms / "targets" / "lakka.yml").read_text()) + tag = re.search(r"/blob/([^/]+)/", targets["source"]).group(1) + self.assertEqual(lakka["version"], tag) + + +class EveryManifestEntryIsFetchable(unittest.TestCase): + """An install manifest may not list a file the installer cannot get. + + install.py fetches a file either from its repo_path or from a release + asset. An entry carrying neither is a line in the download list that can + only ever fail. It happened when resolution landed on a file the database + does not index, so the hash was computed but the repo lookup came back + empty and the entry shipped anyway. + """ + + def test_committed_manifests_all_have_a_source(self): + manifests = sorted((ROOT / "install").glob("*.json")) + self.assertTrue(manifests, "no install manifests to check") + for path in manifests: + with self.subTest(manifest=path.name): + data = json.loads(path.read_text()) + orphans = [ + entry["dest"] + for entry in data.get("files", []) + data.get("case_variants", []) + if not entry.get("repo_path") and not entry.get("release_asset") + ] + self.assertEqual( + orphans, [], f"{path.name} lists unfetchable files: {orphans[:3]}" + ) + + def test_an_unresolvable_file_is_recorded_as_omitted(self): + """The reason must be one install.py knows how to report.""" + for path in sorted((ROOT / "install").glob("*.json")): + with self.subTest(manifest=path.name): + data = json.loads(path.read_text()) + for entry in data.get("omitted_files", []): + self.assertIn(entry.get("reason"), install.OMISSION_REASONS) + + def test_the_installer_accepts_every_published_manifest(self): + """A reason the schema allowed and the installer did not made the + installer refuse the whole RomM manifest: no RomM install ran.""" + for path in sorted((ROOT / "install").glob("*.json")): + with self.subTest(manifest=path.name): + data = json.loads(path.read_text()) + install._validate_manifest(data, data["platform"]) + + def test_every_standalone_layout_goes_with_its_list(self): + """install/standalone/.json, which only --standalone + reads: the installer accepts it against its own list, each item + written whole has a source, and a list naming builds has its file.""" + listed = {path.stem: json.loads(path.read_text()) + for path in sorted((ROOT / "install").glob("*.json"))} + layouts = sorted((ROOT / "install" / "standalone").glob("*.json")) + self.assertEqual({path.stem for path in layouts}, + {plat for plat, data in listed.items() + if data.get("standalone_builds")}) + for path in layouts: + with self.subTest(layout=path.name): + data = json.loads(path.read_text()) + kept = install._check_standalone_layouts(data, listed[path.stem], path.stem) + orphans = [item["dest"] for items in kept.values() for item in items + if isinstance(item, dict) + and not item.get("repo_path") and not item.get("release_asset")] + self.assertEqual(orphans, []) + + def test_schema_and_installer_name_the_same_reasons(self): + schema = json.loads( + (ROOT / "schemas" / "install-manifest.schema.json").read_text() + ) + reasons = schema["properties"]["omitted_files"]["items"]["properties"][ + "reason" + ]["enum"] + self.assertEqual(set(reasons), set(install.OMISSION_REASONS)) + + def _manifests(self) -> list[Path]: + paths = sorted((ROOT / "install").glob("*.json")) + paths += sorted((ROOT / "install" / "targets").glob("*.json")) + self.assertTrue(paths, "no install manifests to check") + return paths + + def test_repo_paths_name_the_file_the_database_holds(self): + """A manifest written before a file moved sends the installer to 404. + + database.json is regenerated whenever a file is refiled, but the manifests + are a separate artefact and were left behind once (the two DS + firmware dumps of the 7 September refile). The installer fetches + repo_path from raw.githubusercontent.com, so a stale one is a + download that can never succeed. + """ + database = ROOT / "database.json" + if not database.is_file(): + self.skipTest("database.json not generated") + files = json.loads(database.read_text(encoding="utf-8"))["files"] + for path in self._manifests(): + with self.subTest(manifest=path.name): + data = json.loads(path.read_text(encoding="utf-8")) + stale = [ + (entry["dest"], entry["repo_path"], files.get(entry["sha1"], {}).get("path")) + for entry in data.get("files", []) + data.get("case_variants", []) + if entry.get("repo_path") + and files.get(entry.get("sha1", ""), {}).get("path") != entry["repo_path"] + ] + self.assertEqual(stale, [], f"{path.name} names moved files: {stale[:3]}") + + def test_release_entries_are_exactly_the_files_git_does_not_hold(self): + """The installer has two sources, and the manifest must pick the right one. + + A committed file is served by the repository, a gitignored one by + the large-files release. Marking a committed file as a release asset + sends the installer to an asset nobody uploaded (sdlpal/5.avi, 83 MB + in git, was announced as release asset `5.avi`). Marking a gitignored + file as a repo file sends it to a raw URL that has no content. A + file neither committed nor ignored is a commit nobody made, and is + named as such rather than as a release asset. + """ + tracked = _git_paths("ls-files", "-z", "--", "bios") + if tracked is None: + self.skipTest("not a git checkout") + manifests: dict[str, list[dict]] = {} + for path in self._manifests(): + data = json.loads(path.read_text(encoding="utf-8")) + manifests[path.name] = [ + entry + for entry in data.get("files", []) + data.get("case_variants", []) + if entry.get("repo_path") + ] + outside = sorted( + {e["repo_path"] for group in manifests.values() for e in group} - tracked + ) + ignored = _git_paths("check-ignore", "-z", "--no-index", "--stdin", stdin=outside) + if ignored is None: + self.skipTest("not a git checkout") + for name, group in manifests.items(): + with self.subTest(manifest=name): + wrong = [] + for entry in group: + repo_path = entry["repo_path"] + state = ( + "committed" if repo_path in tracked + else "gitignored" if repo_path in ignored + else "untracked, never committed" + ) + if state == "untracked, never committed" or ( + bool(entry.get("release_asset")) != (state == "gitignored") + ): + wrong.append((entry["dest"], repo_path, state)) + self.assertEqual(wrong, [], f"{name} picks the wrong source: {wrong[:3]}") + + def test_no_collected_file_is_left_uncommitted(self): + """157 files of the 17 September campaign sat in bios/ untracked: + the database indexed them, the manifests gave them a repo_path and + the installer got a 404. A file under bios/ is either committed or + listed in .gitignore as a release asset, nothing in between.""" + untracked = _git_paths("ls-files", "-z", "--others", "--exclude-standard", "--", "bios") + if untracked is None: + self.skipTest("not a git checkout") + self.assertEqual(sorted(untracked)[:20], [], f"{len(untracked)} untracked files under bios/") + + def test_every_database_path_is_committed_or_a_release_asset(self): + """A git mv under bios/ committed without regenerating anything left + database.json and the manifests agreeing on the old path: the tests + above compare them with each other, so all passed, and the installer + got a 404 (issue 78, with the database stale too).""" + database = ROOT / "database.json" + if not database.is_file(): + self.skipTest("database.json not generated") + files = json.loads(database.read_text(encoding="utf-8"))["files"] + paths = { + path + for entry in files.values() + for path in [entry.get("path"), *(entry.get("paths") or [])] + if path + } + tracked = _git_paths("ls-files", "-z") + if tracked is None: + self.skipTest("not a git checkout") + outside = sorted(paths - tracked) + ignored = _git_paths("check-ignore", "-z", "--no-index", "--stdin", stdin=outside) + if ignored is None: + self.skipTest("not a git checkout") + stale = [path for path in outside if path not in ignored] + self.assertEqual( + stale[:20], [], + f"{len(stale)} database paths git neither holds nor ignores: " + "python scripts/generate_db.py --force --bios-dir bios --output database.json, " + "then the manifests", + ) + + +class ReleaseAssetCriterion(unittest.TestCase): + """What decides whether the installer fetches from the release is git, not size. + + Files over 50 MB are supposed to be gitignored and uploaded to the + large-files release, but four committed files break that rule and one of + them reached a manifest as a release asset that does not exist. The + truthful question is whether the repository serves the bytes, and the + ledger of what it does not serve is .gitignore. + """ + + def _repo(self, directory: str, ignored: str) -> str: + Path(directory, ".gitignore").write_text(ignored + "\n", encoding="utf-8") + return directory + + def test_a_large_committed_file_is_served_by_the_repository(self): + from scripts.packs import manifestentry + + with tempfile.TemporaryDirectory() as directory: + root = self._repo(directory, "bios/elsewhere.bin") + big = Path(root, "bios", "big.avi") + big.parent.mkdir() + with big.open("wb") as handle: + handle.truncate(60_000_000) + manifestentry._registered.cache_clear() + try: + self.assertFalse(manifestentry._is_release_asset(str(big), root)) + finally: + manifestentry._registered.cache_clear() + + def test_the_manifest_names_the_asset_as_github_serves_it(self): + # GitHub publishes a space as a dot. The site linked the dotted + # name while the manifest gave install.py the spaced one, a 404. + from scripts.packs import manifestentry + + with tempfile.TemporaryDirectory() as directory: + root = self._repo(directory, "bios/MAME/MAME 0.174 Arcade XML.dat") + target = Path(root, "bios", "MAME", "MAME 0.174 Arcade XML.dat") + target.parent.mkdir(parents=True) + target.write_bytes(b"x") + manifestentry._registered.cache_clear() + try: + self.assertEqual( + manifestentry._release_asset_name(str(target), root), + "MAME.0.174.Arcade.XML.dat", + ) + finally: + manifestentry._registered.cache_clear() + + def test_a_gitignored_file_is_served_by_the_release_whatever_its_size(self): + from scripts.packs import manifestentry + + with tempfile.TemporaryDirectory() as directory: + root = self._repo(directory, "bios/small.zip") + small = Path(root, "bios", "small.zip") + small.parent.mkdir() + small.write_bytes(b"PK") + manifestentry._registered.cache_clear() + try: + self.assertTrue(manifestentry._is_release_asset(str(small), root)) + finally: + manifestentry._registered.cache_clear() + + +class ReleaseAssetsMatchTheCollection(unittest.TestCase): + """The bytes the release serves must be the bytes the manifests describe. + + install.py checks Content-Length against the manifest size before it + downloads, and the manifest size is that of the local copy. Both FBNeo + sample archives were rebuilt locally after their upload and never + re-uploaded: same members, different container, every install of them + failed. The comparison is offline here on a fixture, while the script runs it + against the live release. + """ + + def test_missing_and_resized_assets_are_reported_and_nothing_else(self): + from scripts.release import assets as release_assets + + expected = { + "bios/Other/fbneo/fbneo/samples/twotiger.zip": 154985212, + "bios/Arcade/MAME/MAME 0.174 Arcade XML.dat": 53677408, + "bios/Other/sdlpal/sdlpal/5.avi": 82833972, + } + assets = { + "twotiger.zip": 154888877, + "MAME.0.174.Arcade.XML.dat": 53677408, + "unrelated.zip": 1, + } + findings = release_assets.compare(expected, assets) + self.assertEqual( + findings, + [ + ("missing", "bios/Other/sdlpal/sdlpal/5.avi", 82833972, None), + ("size", "bios/Other/fbneo/fbneo/samples/twotiger.zip", 154985212, 154888877), + ], + ) + + def test_expected_assets_are_the_gitignored_database_entries(self): + from scripts.release import assets as release_assets + + db = { + "files": { + "a" * 40: {"path": "bios/Other/x/big.zip", "size": 10}, + "b" * 40: {"path": "bios/Other/x/small.bin", "size": 2}, + } + } + gitignore = "# large\nbios/Other/x/big.zip\ntmp/\n" + self.assertEqual( + release_assets.expected_assets(db, gitignore), + {"bios/Other/x/big.zip": 10}, + ) + + def test_release_notes_are_rendered_from_the_collection(self): + """The release page is written by hand and drifts, so it is rendered instead. + + Three assets had no row, three rows carried the SHA1 of an asset + that had since been replaced, and the footer counted 41 files for 44. + Hand-written descriptions survive by name. A new row takes its + description from the profile that declares the file, and an asset the + collection does not index is listed apart, with its size only. + """ + from scripts.release import assets as release_assets + + db = {"files": { + "a" * 40: {"path": "bios/Nintendo/Wii/nand.bin", "size": 553649152}, + "b" * 40: {"path": "bios/Other/fbneo/fbneo/samples/twotiger.zip", "size": 154985212}, + "c" * 40: {"path": "bios/Other/x/small.bin", "size": 2}, + }} + gitignore = "bios/Nintendo/Wii/nand.bin\nbios/Other/fbneo/fbneo/samples/twotiger.zip\n" + assets = {"nand.bin": 553649152, "twotiger.zip": 154985212, + "sdlpal-data.zip": 140773720, "whoopee.zip": 222665810} + previous = ( + "## Arcade\n\n| File | Description | Size | SHA1 |\n|---|---|---|---|\n" + "| [twotiger.zip](u) | Two Tigers samples | 148 MB | `" + "0" * 40 + "` |\n" + "| [whoopee.zip](u) | Toaplan Whoopee samples | 212 MB | `" + "9" * 40 + "` |\n" + ) + descriptions = {"nand.bin": "BootMii NAND backup"} + bundles = {"sdlpal-data.zip": "SDLPAL Chinese Paladin game data (.mkf archives)"} + body = release_assets.render_notes( + db, gitignore, assets, previous, descriptions, bundles, {"sdlpal-data.zip": "d" * 40} + ) + self.assertIn("| [twotiger.zip](https://github.com/Abdess/retrobios/releases/download/large-files/twotiger.zip) | Two Tigers samples | 147.8 MB | `" + "b" * 40 + "` |", body) + self.assertIn("| [nand.bin](https://github.com/Abdess/retrobios/releases/download/large-files/nand.bin) | BootMii NAND backup | 528.0 MB | `" + "a" * 40 + "` |", body) + self.assertIn("| [sdlpal-data.zip](https://github.com/Abdess/retrobios/releases/download/large-files/sdlpal-data.zip) | SDLPAL Chinese Paladin game data (.mkf archives) | 134.3 MB | `" + "d" * 40 + "` |", body) + self.assertIn("## Not indexed", body) + self.assertIn("| [whoopee.zip](https://github.com/Abdess/retrobios/releases/download/large-files/whoopee.zip) | Toaplan Whoopee samples | 212.4 MB |", body) + self.assertNotIn("9" * 40, body) + self.assertNotIn("small.bin", body) + # The total reads in the unit of the rows above it: 1022.4 MB, not 1.0 GB. + self.assertIn("4 files, 1022.4 MB total", body) + self.assertEqual(body.index("## Console firmware"), min( + body.index(h) for h in ("## Console firmware", "## Arcade", "## Not indexed") + )) + + def test_stale_notes_are_a_finding(self): + from scripts.release import assets as release_assets + + findings = release_assets.compare({}, {}, notes_current=False) + self.assertEqual(findings, [("notes", "release description", 0, None)]) + + def test_pipeline_runs_the_check_online_and_marks_it_skipped_offline(self): + """Run with each step recorded instead of executed: reading the + source for two strings stayed green with the guard inverted.""" + import contextlib + import io + from unittest import mock + + from scripts import pipeline + + def steps(*flags: str) -> tuple[list[str], str]: + ran: list[str] = [] + + def record(cmd, label): + ran.append(label) + return True, "" + + argv = ["pipeline.py", "--skip-packs", "--skip-docs", *flags] + with mock.patch.object(runner, "run", record), \ + mock.patch.object(sys, "argv", argv), \ + contextlib.redirect_stdout(io.StringIO()) as out, \ + self.assertRaises(SystemExit) as done: + pipeline.main() + self.assertEqual(done.exception.code, 0) + return ran, out.getvalue() + + online, _ = steps() + self.assertIn("2b2 check release assets", online) + offline, printed = steps("--offline") + self.assertNotIn("2b2 check release assets", offline) + self.assertIn("check_release_assets.................... SKIPPED", printed) + + +class EachRootReadsItsOwnRegistry(unittest.TestCase): + """The release-asset registry was cached once per process whatever root + was asked: a second tree got the first tree's .gitignore.""" + + def test_two_roots_in_one_process(self): + from scripts.packs import manifestentry + + with tempfile.TemporaryDirectory() as a, \ + tempfile.TemporaryDirectory() as b: + Path(a, ".gitignore").write_text("bios/one.bin\n") + Path(b, ".gitignore").write_text("bios/two.bin\n") + self.assertTrue(manifestentry._is_release_asset(str(Path(a, "bios/one.bin")), a)) + self.assertFalse(manifestentry._is_release_asset(str(Path(b, "bios/one.bin")), b)) + self.assertTrue(manifestentry._is_release_asset(str(Path(b, "bios/two.bin")), b)) + + def test_one_parser_reads_the_registry(self): + for module in ("generate_pack.py", "generate_db.py"): + source = script_source(module) + with self.subTest(module=module): + self.assertIn("load_registered_paths", source) + self.assertNotIn('startswith("bios/")\n }', source) + + +class TheInstallerNamesWhatItSkipped(unittest.TestCase): + def test_count_agrees_and_required_files_are_named(self): + one = install._omission_lines(1, [{"name": "diabdat.mpq", "required": True}]) + self.assertTrue(one[0].startswith("1 file was not installed")) + self.assertTrue(any("diabdat.mpq" in line for line in one[1:])) + many = install._omission_lines( + 12, + [{"name": f"f{i:02}", "required": True, "system": f"s{i:02}", + "cores": ["core"]} for i in range(12)], + ) + self.assertTrue(many[0].startswith("12 files were not installed")) + self.assertIn(" s00 (core): f00", many) + self.assertTrue(any("and 4 more systems" in line for line in many)) + + +class AManifestHashesAFileOnce(unittest.TestCase): + """Every manifest entry rehashed its file with five algorithms: 70 476 + calls for 15 011 files, 163 s of a 218 s step.""" + + def test_verified_hashes_are_reused(self): + from scripts.packs import manifestentry + + with tempfile.TemporaryDirectory() as tmp: + path = Path(tmp, "a.bin") + path.write_bytes(b"abc") + sha1 = hashlib.sha1(b"abc").hexdigest() + db = {"files": {sha1: {"path": str(path)}}} + calls = [] + real = manifestentry.compute_hashes + + def counting(file_path, algorithms=None): + calls.append(algorithms) + return real(file_path, algorithms) + + with mock.patch.object(manifestentry, "compute_hashes", counting): + first = manifestentry._stable_hashes(str(path), db) + second = manifestentry._stable_hashes(str(path), db) + self.assertEqual(first, second) + self.assertEqual(len(calls), 1) + self.assertEqual(calls[0], frozenset({"sha1", "sha256"})) + + +class ATreeNobodyHoldsIsMissingNotAnAsset(unittest.TestCase): + """julius's caesar3/ directory, unexpanded, went to the asset store, + which answered with .cache/large/ itself: the emulator pack died on + IsADirectoryError where verify said MISSING.""" + + def test_directory_entries_never_reach_the_asset_store(self): + from scripts.model import largefiles + from scripts.resolve import packfiles as packresolve + + db = {"files": {}, "indexes": {"by_name": {}, "by_md5": {}, "by_crc32": {}, + "by_path_suffix": {}}} + for entry in ({"name": "caesar3/", "type": "directory"}, {"name": "caesar3/"}): + with self.subTest(entry=entry): + self.assertEqual( + packresolve.resolve_file(entry, db, "bios", {}, offline=True), + (None, "not_found"), + ) + self.assertIsNone(largefiles.fetch_large_file("caesar3/", offline=True)) + with tempfile.TemporaryDirectory() as tmp: + Path(tmp, "sub").mkdir() + self.assertIsNone(largefiles._fetch_asset("sub", tmp, "", "", offline=True)) + + +class InstallerJsonKindsNeverOverwriteEachOther(unittest.TestCase): + """Install manifests and target core lists are both .json. + --manifest-targets aimed at install/ replaced install/retroarch.json, the + file every installer downloads, with a target table, exit 0.""" + + def _run(self, *flags: str, held: str) -> tuple: + with tempfile.TemporaryDirectory() as tmp: + target = Path(tmp, "retroarch.json") + before = (ROOT / held).read_text(encoding="utf-8") + target.write_text(before, encoding="utf-8") + proc = subprocess.run( + [sys.executable, "scripts/generate_pack.py", *flags, + "--offline", "--output-dir", tmp], + cwd=ROOT, capture_output=True, text=True, timeout=600, + check=False, + ) + return proc, before, target.read_text(encoding="utf-8") + + def test_target_lists_refuse_a_manifest_directory(self): + proc, before, after = self._run( + "--manifest-targets", held="install/retroarch.json" + ) + self.assertEqual(proc.returncode, 1, proc.stdout + proc.stderr) + self.assertIn("holds install manifests", proc.stderr) + self.assertIn("--output-dir", proc.stderr) + self.assertEqual(after, before) + + def test_manifests_refuse_a_target_list_directory(self): + proc, before, after = self._run( + "--manifest", "--platform", "retroarch", + held="install/targets/retroarch.json", + ) + self.assertEqual(proc.returncode, 1, proc.stdout + proc.stderr) + self.assertIn("holds per-target core lists", proc.stderr) + self.assertEqual(after, before) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_audit_packs.py b/tests/test_audit_packs.py new file mode 100644 index 000000000..4b9ba9098 --- /dev/null +++ b/tests/test_audit_packs.py @@ -0,0 +1,1350 @@ +"""Audit regressions on pack building: baseline verdicts, exclusions, regions, archives and downloads.""" + +from __future__ import annotations + +import tests +from tests.sources import script_source +import ast +import contextlib +import hashlib +import io +import json +import os +import re +import tempfile +import unittest +import urllib.error +import zipfile +from pathlib import Path +from unittest import mock +import yaml +from scripts.resolve import regionaudit, regions +from scripts.packs.extraregions import _emulator_region_group +from scripts.packs.platformcheck import verify_pack_against_platform +from tests.auditsupport import ROOT + + +class APackIsSwappedInWhole(unittest.TestCase): + """Packs were opened on their final name: a rebuild truncated the good + pack at once, and a build that raised half way left a readable ZIP of + part of the files, which the run then verified and summed.""" + + def _dir(self) -> Path: + import shutil + import tempfile + + (ROOT / "tmp").mkdir(exist_ok=True) + directory = Path(tempfile.mkdtemp()) + self.addCleanup(shutil.rmtree, directory, True) + return directory + + def test_a_failed_build_keeps_the_previous_pack(self): + import zipfile + + from packs.archive import writing_pack + + directory = self._dir() + pack = directory / "Pack.zip" + with zipfile.ZipFile(pack, "w") as zf: + zf.writestr("old.bin", b"complete") + with self.assertRaises(OSError), writing_pack(str(pack)) as zf: + zf.writestr("new.bin", b"half") + raise OSError("disk full") + with zipfile.ZipFile(pack) as zf: + self.assertEqual(zf.namelist(), ["old.bin"]) + self.assertEqual(sorted(p.name for p in directory.iterdir()), ["Pack.zip"]) + + def test_a_finished_build_replaces_it(self): + import zipfile + + from packs.archive import writing_pack + + directory = self._dir() + pack = directory / "Pack.zip" + pack.write_bytes(b"stale") + with writing_pack(str(pack)) as zf: + zf.writestr("new.bin", b"whole") + with zipfile.ZipFile(pack) as zf: + self.assertEqual(zf.namelist(), ["new.bin"]) + self.assertEqual(sorted(p.name for p in directory.iterdir()), ["Pack.zip"]) + + def test_no_pack_is_opened_on_its_final_name(self): + source = script_source("generate_pack.py") + self.assertNotIn('ZipFile(zip_path, "w"', source) + + +class EverySharedGroupServesAPlatform(unittest.TestCase): + """Six of the eight shared groups injected nothing: fuse, mt32 and + jiffydos were included by no platform, and kronos, keropi and ep128emu + repeated System.dat entry for entry. load_platform_config keeps the + platform's own entry, so a hash corrected there changed no pack, no + verify and no manifest, and nothing said so.""" + + def test_each_group_contributes_an_entry_somewhere(self): + from model.registry import list_registered_platforms + from model.platforms import load_platform_config + + platforms_dir = str(ROOT / "platforms") + with (ROOT / "platforms" / "_shared.yml").open(encoding="utf-8") as handle: + groups = set((yaml.safe_load(handle) or {}).get("shared_groups") or {}) + served = { + entry.get("shared_group") + for name in list_registered_platforms(platforms_dir) + for system in load_platform_config(name, platforms_dir).get("systems", {}).values() + for entry in system.get("files", []) + } + self.assertEqual(sorted(groups - served), []) + + +class StandaloneCopiesNameTheirSource(unittest.TestCase): + """The registry's anchor names one path per file for every platform, + while each manifest places the file its own way, and the installer copied + nothing where the two differed (EmuDeck's aes_keys.txt, Batocera's + switch/prod.keys).""" + + def _placed(self, copies, dests): + from packs.standalone import _placed_copies + + return _placed_copies(copies, dests) + + def test_a_path_tail_finds_the_file(self): + (copy,) = self._placed( + [{"file": "GC/USA/IPL.bin"}], + ["dolphin-emu/Sys/GC/USA/IPL.bin", "dolphin-emu/Sys/GC/EUR/IPL.bin"], + ) + self.assertEqual(copy["source"], "dolphin-emu/Sys/GC/USA/IPL.bin") + + def test_the_tail_with_least_on_top_wins(self): + (copy,) = self._placed( + [{"file": "GC/USA/IPL.bin"}], + ["bios/GC/USA/IPL.bin", "bios/dolphin-emu/Sys/GC/USA/IPL.bin"], + ) + self.assertEqual(copy["source"], "bios/GC/USA/IPL.bin") + + def test_a_unique_name_finds_the_file_elsewhere(self): + (copy,) = self._placed( + [{"file": "Citra/sysdata/aes_keys.txt"}], ["aes_keys.txt", "bios.bin"] + ) + self.assertEqual(copy["source"], "aes_keys.txt") + + def test_an_ambiguous_or_present_file_is_left_as_written(self): + copies = [{"file": "prod.keys"}, {"file": "IPL.bin"}] + placed = self._placed(copies, ["prod.keys", "a/IPL.bin", "b/IPL.bin"]) + self.assertEqual(placed, copies) + + +class StandaloneCopiesComeFromTheProfiles(unittest.TestCase): + """The copies were a hand-kept list of eight emulators while 61 profiles + give their data_root with the code that builds it: a machine with only + standalone Cemu got none of its keys.""" + + CEMU = { + "data_root": { + "linux": {"path": "$XDG_DATA_HOME/Cemu, else ~/.local/share/Cemu", + "source_ref": "x"}, + "windows": {"path": "%APPDATA%/Cemu", "source_ref": "x"}, + "macos": {"path": "~/Library/Application Support/Cemu", "source_ref": "x"}, + }, + "files": [ + {"name": "keys.txt", "path": "Cemu/keys.txt", "standalone_path": "keys.txt"}, + {"name": "CafeCn.ttf", "path": "Cemu/mlc01/CafeCn.ttf", + "standalone_path": "mlc01/sys/CafeCn.ttf"}, + {"name": "gone.bin", "path": "Cemu/gone.bin", "standalone_path": "gone.bin"}, + {"name": "core.bin", "path": "Cemu/core.bin", "standalone_path": "core.bin", + "mode": "libretro"}, + ], + } + + def _copies(self, profiles, dests, declared=()): + from packs.standalone import _profile_copies + + return _profile_copies(profiles, dests, list(declared)) + + def test_each_file_goes_under_the_data_root(self): + copies = self._copies({"cemu": self.CEMU}, + ["Cemu/keys.txt", "Cemu/mlc01/CafeCn.ttf", "Cemu/core.bin"]) + self.assertEqual(copies, [ + {"file": "Cemu/keys.txt", "targets": { + "linux": ["$HOME/.local/share/Cemu"], "windows": ["%APPDATA%\\Cemu"], + "darwin": ["$HOME/Library/Application Support/Cemu"]}}, + {"file": "Cemu/mlc01/CafeCn.ttf", "targets": { + "linux": ["$HOME/.local/share/Cemu/mlc01/sys"], + "windows": ["%APPDATA%\\Cemu\\mlc01\\sys"], + "darwin": ["$HOME/Library/Application Support/Cemu/mlc01/sys"]}}, + ]) + + def test_a_place_no_run_can_name_is_left_out(self): + melonds = { + "data_root": { + "windows": {"path": "", "source_ref": "x"}, + "linux": {"path": "$XDG_CONFIG_HOME/melonDS, else ~/.config/melonDS", + "source_ref": "x"}, + }, + "files": [{"name": "dsi_sd_card.bin", "standalone_path": "dsisd.bin"}], + } + (copy,) = self._copies({"melonds": melonds}, ["dsi_sd_card.bin"]) + self.assertEqual(copy, {"file": "dsi_sd_card.bin", + "targets": {"linux": ["$HOME/.config/melonDS"]}, + "as": "dsisd.bin"}) + + def test_the_registry_keeps_what_it_already_names(self): + declared = [{"pattern": "k*.txt", "targets": {"linux": ["$HOME/.local/share/Cemu"]}}] + (copy, _font) = self._copies({"cemu": self.CEMU}, + ["Cemu/keys.txt", "Cemu/mlc01/CafeCn.ttf"], declared) + self.assertNotIn("linux", copy["targets"]) + self.assertIn("windows", copy["targets"]) + + def test_a_file_found_by_content_is_left_to_the_scan(self): + amiberry = { + "data_root": {"linux": {"path": "~/Amiberry", "source_ref": "x"}}, + "files": [{"name": "cd32fmv.rom", "path": "roms/cd32fmv.rom", + "standalone_path": "cd32fmv.rom", "found_by": "content"}], + } + self.assertEqual(self._copies({"amiberry": amiberry}, ["roms/cd32fmv.rom"]), []) + + def test_the_published_retroarch_list_reaches_cemu(self): + import json + + manifest = json.loads((ROOT / "install" / "retroarch.json").read_text()) + files = {copy["file"]: copy for copy in manifest["standalone_copies"] + if "file" in copy} + for name in ("Cemu/keys.txt", "Cemu/otp.bin", "Cemu/seeprom.bin"): + with self.subTest(name=name): + self.assertEqual(files[name]["targets"]["linux"], ["$HOME/.local/share/Cemu"]) + + +class ADamagedArchiveIsNotPacked(unittest.TestCase): + """A member whose bytes fail their CRC stops the build. The builder once + copied the damaged archive into the pack "for verify to flag", which + nothing did.""" + + def test_the_rebuild_refusal_reaches_the_run(self): + import zipfile + + from packs.archive import DamagedArchiveError, add_zip_to_pack + + with tempfile.TemporaryDirectory() as directory: + source = Path(directory) / "set.zip" + with zipfile.ZipFile(source, "w", zipfile.ZIP_STORED) as zf: + zf.writestr("rom.bin", b"A" * 64) + data = bytearray(source.read_bytes()) + data[data.index(b"A" * 64)] ^= 0xFF + source.write_bytes(bytes(data)) + pack = Path(directory) / "pack.zip" + with zipfile.ZipFile(pack, "w") as target: + with self.assertRaises(DamagedArchiveError) as caught: + add_zip_to_pack(str(source), "set.zip", target) + self.assertNotIn("set.zip", target.namelist()) + self.assertIsInstance(caught.exception, OSError) + self.assertIn("set.zip", str(caught.exception)) + + +class APackedArchiveKeepsItsBytes(unittest.TestCase): + """Packs rebuilt about 1,500 ZIPs in a fixed byte order while the install + list kept the collection's hash: an extracted pack failed --check on each.""" + + def test_the_member_is_the_source_byte_for_byte(self): + import hashlib + import zipfile + + from packs.archive import add_zip_to_pack + + with tempfile.TemporaryDirectory() as directory: + source = Path(directory) / "set.zip" + with zipfile.ZipFile(source, "w", zipfile.ZIP_DEFLATED) as zf: + zf.writestr(zipfile.ZipInfo("rom.bin", (1999, 1, 2, 3, 4, 5)), b"rom" * 40) + pack = Path(directory) / "pack.zip" + with zipfile.ZipFile(pack, "w") as target: + add_zip_to_pack(str(source), "set.zip", target) + with zipfile.ZipFile(pack) as packed: + inner = packed.read("set.zip") + self.assertEqual(hashlib.sha1(inner).hexdigest(), + hashlib.sha1(source.read_bytes()).hexdigest()) + + +class OneBaselineVerdict(unittest.TestCase): + """The builder and the manifest each wrote the platform baseline. + + The builder looked inside a zipped_file archive whatever the outer + resolution said, the manifest only after a hash_mismatch. An archive + found by name without the member Batocera checks left the pack and + stayed in the manifest. A slot override replaced a release asset in the + manifest and not in the pack. + """ + + def _archive(self, directory: Path, member: str) -> str: + path = directory / "dragon32.zip" + with zipfile.ZipFile(path, "w") as archive: + archive.writestr(member, b"rom") + return str(path) + + def test_a_missing_member_is_refused_whatever_the_outer_status(self): + from scripts.resolve.acceptance import baseline_verdict + + entry = {"name": "dragon32.zip", "zipped_file": "d32.rom", "md5": ""} + with tempfile.TemporaryDirectory() as directory: + path = self._archive(Path(directory), "other.rom") + status, refusal = baseline_verdict(entry, path, "name_exact", "md5") + self.assertEqual(refusal, "d32.rom not found inside ZIP") + # An existence frontend never opens it. + self.assertEqual( + baseline_verdict(entry, path, "name_exact", "existence"), + ("name_exact", None), + ) + + def test_the_pack_check_reads_the_same_verdict(self): + """--verify-packs called the archive missing: its own rule looked + inside only after a hash_mismatch, and an archive found by name + without d32.rom is one the builder left out on purpose.""" + import hashlib + + from scripts.packs.platformcheck import _intentional_hash_exclusion + + entry = {"name": "dragon32.zip", "zipped_file": "d32.rom", "md5": ""} + with tempfile.TemporaryDirectory() as directory: + path = self._archive(Path(directory), "other.rom") + sha1 = hashlib.sha1(Path(path).read_bytes()).hexdigest() + db = {"files": {sha1: {"path": path, "name": "dragon32.zip", "sha1": sha1}}, + "indexes": {"by_name": {"dragon32.zip": [sha1]}, "by_md5": {}, + "by_path_suffix": {}, "by_crc32": {}}} + self.assertTrue(_intentional_hash_exclusion([entry], db, verification_mode="md5")) + self.assertFalse( + _intentional_hash_exclusion([entry], db, verification_mode="existence") + ) + + def test_the_builder_accepts_what_verify_accepts(self): + """verify took a ZIP by its composite, but the builder compared exact + md5s and refused it when another declared hash disagreed. A value cut + short accepts nothing: Batocera compares the whole md5 string + (batocera-systems:1088), and verify accepted any prefix, down to one + digit.""" + import hashlib + + from scripts.core.hashing import md5_composite + from scripts.resolve.acceptance import baseline_verdict, digest_verdict + + with tempfile.TemporaryDirectory() as directory: + loose = Path(directory) / "abc.bin" + loose.write_bytes(b"abc") + md5 = hashlib.md5(b"abc").hexdigest() + truncated = {"name": "abc.bin", "md5": md5[:29], "crc32": "deadbeef"} + self.assertIsNotNone( + baseline_verdict(truncated, str(loose), "hash_mismatch", "md5")[1] + ) + for length in (1, 29, 31): + self.assertFalse( + digest_verdict({"md5": md5[:length]}, 3, lambda: {"md5": md5}, "md5") + ) + self.assertTrue(digest_verdict({"md5": md5}, 3, lambda: {"md5": md5}, "md5")) + archive = self._archive(Path(directory), "rom.bin") + composite = {"name": "dragon32.zip", "md5": md5_composite(archive), + "crc32": "deadbeef"} + self.assertEqual( + baseline_verdict(composite, archive, "hash_mismatch", "md5"), + ("frontend_digest_exact", None), + ) + + def test_a_composite_only_archive_ignores_its_raw_md5(self): + """Recalbox hashes a .zip by its members (Bios.cpp:64-68), and the + pack check accepted the container's own md5 before the composite: + neocd.bin shipped as neocdz.zip passed while Recalbox marks it red.""" + import hashlib + + from scripts.core.hashing import md5_composite + from scripts.resolve.acceptance import digest_verdict + + with tempfile.TemporaryDirectory() as directory: + archive = self._archive(Path(directory), "rom.bin") + raw = hashlib.md5(Path(archive).read_bytes()).hexdigest() + members = md5_composite(archive) + for declared, accepted in ((raw, False), (members, True)): + entry = {"name": "dragon32.zip", "md5": declared, "zip_digest": "composite"} + with self.subTest(declared=declared): + self.assertIs( + digest_verdict(entry, 0, lambda: {"md5": raw}, "md5", "", + lambda: members), + accepted, + ) + plain = {"name": "dragon32.zip", "md5": raw} + self.assertTrue(digest_verdict(plain, 0, lambda: {"md5": raw}, "md5")) + + def test_a_release_asset_keeps_its_answer(self): + from scripts.resolve.packfiles import apply_override + + self.assertEqual( + apply_override("bios/x.bin", "/cache/big.bin", "release_asset"), + ("/cache/big.bin", "release_asset"), + ) + self.assertEqual( + apply_override("bios/x.bin", "bios/y.bin", "name_exact"), + ("bios/x.bin", "slot_arbitrated"), + ) + + def test_the_builder_and_the_manifest_read_the_same_rules(self): + source = script_source("generate_pack.py") + tree = ast.parse(source) + for name in ("build_platform_pack", "generate_manifest"): + function = next( + node for node in tree.body + if isinstance(node, ast.FunctionDef) and node.name == name + ) + body = ast.get_source_segment(source, function) or "" + with self.subTest(function=name): + self.assertIn("DeclarationJudge(", body) + self.assertNotIn('"slot_arbitrated"', body) + judge = next( + node for node in tree.body + if isinstance(node, ast.ClassDef) and node.name == "DeclarationJudge" + ) + body = ast.get_source_segment(source, judge) or "" + self.assertIn("baseline_verdict(", body) + self.assertIn("resolve_declaration(", body) + self.assertNotIn('"slot_arbitrated"', body) + + def test_verify_and_the_region_pass_resolve_as_the_builder(self): + """verify called common.resolve_local_file and put the slot override + first, the region pass passed a destination hint the builder never + gives: a gitignored file absent from bios/ read as missing in verify + while the pack shipped its cached release asset.""" + for module, name in (("verify.py", "_resolve_for_platform"), + ("packs/extraregions.py", "_ships")): + source = script_source(module) + function = next( + node for node in ast.parse(source).body + if isinstance(node, ast.FunctionDef) and node.name == name + ) + body = ast.get_source_segment(source, function) or "" + with self.subTest(function=name): + self.assertIn("resolve_declaration(", body) + self.assertNotIn("resolve_local_file(", body) + self.assertNotIn('"slot_arbitrated"', body) + + def test_verify_finds_the_cached_release_asset(self): + # verify imports the scripts directory's modules by their bare names. + from resolve import packfiles as packresolve + from scripts.packs.platformtally import _resolve_for_platform + + with tempfile.TemporaryDirectory() as directory: + cached = Path(directory) / "BIG.PUP" + cached.write_bytes(b"large firmware") + sha1 = hashlib.sha1(cached.read_bytes()).hexdigest() + db = {"files": {sha1: {"path": f"{directory}/absent/BIG.PUP", + "name": "BIG.PUP", "sha1": sha1}}, + "indexes": {"by_name": {"BIG.PUP": [sha1]}}} + entry = {"name": "BIG.PUP", "sha1": sha1, "destination": "BIG.PUP"} + # The record's path is a registered release asset. + registered = [f"{directory}/absent/BIG.PUP"] + with mock.patch.object( + packresolve, "fetch_large_file", return_value=str(cached) + ), mock.patch("model.largefiles.load_registered_paths", return_value=registered): + found = _resolve_for_platform( + entry, "sys", db, {}, None, {"BIG.PUP": "bios/other.bin"}, + "md5", {}, + ) + self.assertEqual(found, (str(cached), "release_asset")) + + +class PackExclusionRegressions(unittest.TestCase): + def test_slug_platform_core_requirement_uses_the_generated_destination(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + platforms = root / "platforms" + platforms.mkdir() + core_payload = root / "extra.bin" + core_payload.write_bytes(b"mapped core payload") + core_sha1 = hashlib.sha1(core_payload.read_bytes()).hexdigest() + core_md5 = hashlib.md5(core_payload.read_bytes()).hexdigest() + database = { + "files": { + core_sha1: { + "name": "extra.bin", + "path": str(core_payload), + "md5": core_md5, + "size": core_payload.stat().st_size, + } + }, + "indexes": { + "by_name": {"extra.bin": [core_sha1]}, + "by_md5": {core_md5: core_sha1}, + "by_sha256": {}, + "by_crc32": {}, + "by_path_suffix": {}, + }, + } + config = { + "platform": "Slug platform", + "base_destination": "bios", + "verification_mode": "existence", + "cores": ["core_a"], + "systems": { + "console-a": { + "files": [ + { + "name": "base-a.bin", + "destination": "slug-a/base-a.bin", + } + ] + }, + "console-b": { + "files": [ + { + "name": "base-b.bin", + "destination": "slug-b/base-b.bin", + } + ] + }, + }, + } + (platforms / "slug.yml").write_text( + yaml.safe_dump(config), encoding="utf-8" + ) + profiles = { + "core_a": { + "emulator": "Core A", + "type": "libretro", + "systems": ["console-a"], + "files": [ + { + "name": "extra.bin", + "path": "extra.bin", + "sha1": core_sha1, + } + ], + } + } + pack = root / "pack.zip" + with zipfile.ZipFile(pack, "w", zipfile.ZIP_DEFLATED) as archive: + archive.writestr("slug-a/base-a.bin", b"baseline a") + archive.writestr("slug-b/base-b.bin", b"baseline b") + archive.writestr("slug-a/extra.bin", core_payload.read_bytes()) + + result = verify_pack_against_platform( + str(pack), + "slug", + str(platforms), + db=database, + emu_profiles=profiles, + ) + self.assertTrue(result[0], result[3]) + self.assertEqual(result[3], []) + self.assertEqual(result[6:8], (1, 1)) + + def _mismatch_fixture(self, root: Path, mode: str) -> tuple[dict, Path]: + """A platform declaring a hash the only local payload contradicts.""" + platforms = root / "platforms" + platforms.mkdir() + payload = root / "firmware.bin" + payload.write_bytes(b"wrong local variant") + sha1 = hashlib.sha1(payload.read_bytes()).hexdigest() + md5 = hashlib.md5(payload.read_bytes()).hexdigest() + database = { + "files": { + sha1: { + "name": "firmware.bin", + "path": str(payload), + "md5": md5, + "size": payload.stat().st_size, + } + }, + "indexes": { + "by_name": {"firmware.bin": [sha1]}, + "by_md5": {md5: sha1}, + "by_sha256": {}, + "by_crc32": {}, + "by_path_suffix": {}, + }, + } + config = { + "platform": f"Platform {mode}", + "verification_mode": mode, + "systems": { + "console": { + "files": [ + { + "name": "firmware.bin", + "destination": "firmware.bin", + "sha1": "f" * 40, + } + ] + } + }, + } + (platforms / "plat.yml").write_text(yaml.safe_dump(config), encoding="utf-8") + return database, platforms + + def test_hash_platform_accounts_for_an_unsafe_exclusion(self): + """A platform that reads the bytes would reject the local payload.""" + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + database, platforms = self._mismatch_fixture(root, "md5") + pack = root / "pack.zip" + with zipfile.ZipFile(pack, "w", zipfile.ZIP_DEFLATED) as archive: + archive.writestr("README.txt", "safe subset") + + result = verify_pack_against_platform( + str(pack), + "plat", + str(platforms), + db=database, + emu_profiles={}, + ) + self.assertTrue(result[0], result[3]) + self.assertEqual(result[3], []) + self.assertEqual(result[8], 1) + + def test_existence_platform_never_withholds_over_a_declared_hash(self): + """RetroArch and friends only look for the filename. + + An upstream hash the local dump contradicts must not remove a file the + frontend would have loaded, so its absence stays a conformance error. + """ + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + database, platforms = self._mismatch_fixture(root, "existence") + pack = root / "pack.zip" + with zipfile.ZipFile(pack, "w", zipfile.ZIP_DEFLATED) as archive: + archive.writestr("README.txt", "no firmware") + + result = verify_pack_against_platform( + str(pack), + "plat", + str(platforms), + db=database, + emu_profiles={}, + ) + self.assertFalse(result[0]) + self.assertTrue(any("baseline missing" in e for e in result[3]), result[3]) + self.assertEqual(result[8], 0) + + def test_unexplained_missing_file_still_fails_conformance(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + platforms = root / "platforms" + platforms.mkdir() + config = { + "platform": "Missing", + "verification_mode": "existence", + "systems": { + "console": { + "files": [ + {"name": "absent.bin", "destination": "absent.bin"} + ] + } + }, + } + (platforms / "missing.yml").write_text( + yaml.safe_dump(config), encoding="utf-8" + ) + pack = root / "pack.zip" + with zipfile.ZipFile(pack, "w", zipfile.ZIP_DEFLATED) as archive: + archive.writestr("README.txt", "incomplete") + database = { + "files": {}, + "indexes": { + "by_name": {}, + "by_md5": {}, + "by_sha256": {}, + "by_crc32": {}, + "by_path_suffix": {}, + }, + } + + result = verify_pack_against_platform( + str(pack), + "missing", + str(platforms), + db=database, + emu_profiles={}, + ) + self.assertFalse(result[0]) + self.assertTrue(any("baseline missing" in error for error in result[3])) + + +class RegionRegressions(unittest.TestCase): + def test_tagged_and_untagged_same_path_is_preserved(self): + profiles = { + "tagged": { + "type": "libretro", + "files": [ + {"name": "bios.bin", "path": "sys/bios.bin", "region": ["japan"]} + ], + }, + "untagged": { + "type": "libretro", + "files": [{"name": "bios.bin", "path": "sys/bios.bin"}], + }, + } + index = regions.build_region_index(profiles) + self.assertEqual(regions.lookup_regions(index, "sys/bios.bin", "bios.bin"), set()) + drops = regions.resolve_region_drops( + {"system": [("sys/bios.bin", "bios.bin")]}, + index, + ["north-america"], + ) + self.assertEqual(drops, set()) + + def test_world_candidate_beats_unmatched_regional_fallback(self): + profiles = { + "core": { + "type": "libretro", + "files": [ + {"name": "ntsc.bin", "region": ["world"]}, + {"name": "pal.bin", "region": ["europe"]}, + ], + } + } + index = regions.build_region_index(profiles) + groups = {"system": [("ntsc.bin", "ntsc.bin"), ("pal.bin", "pal.bin")]} + self.assertEqual( + regions.resolve_region_drops(groups, index, ["north-america"]), + {"pal.bin"}, + ) + self.assertEqual(regions.resolve_region_drops(groups, index, ["europe"]), set()) + + def test_multi_system_emulator_uses_separate_region_groups(self): + profile = {"systems": ["odyssey2", "videopac"]} + north_america = _emulator_region_group( + "o2em", profile, {"name": "o2rom.bin", "system": "odyssey2"}, "o2rom.bin" + ) + europe = _emulator_region_group( + "o2em", profile, {"name": "c52.bin", "system": "videopac"}, "c52.bin" + ) + self.assertNotEqual(north_america, europe) + + def test_a_systemless_file_groups_alike_in_both_modes(self): + """geargrafx files pac-n1.bin [japan] and pac-n10.bin [north-america] + under none of its four systems: emulator mode grouped them and + dropped pac-n1.bin for --region us, platform mode isolated each and + kept it.""" + from packs.extraregions import extra_region_groups + + profile = {"systems": ["nec-pc-engine", "nec-pc-engine-cd", "nec-supergrafx", + "pioneer-laseractive"]} + names = ["pac-n1.bin", "pac-n10.bin"] + emulator = [ + _emulator_region_group("geargrafx", profile, {"name": n}, n) for n in names + ] + platform = [ + extra_region_groups({ + "source_emulator": "geargrafx", "destination": n, + "source_systems": profile["systems"], + })[0] + for n in names + ] + self.assertEqual(emulator, platform) + + def test_an_entry_systems_list_groups_alike_in_both_modes(self): + """An entry's own one-element `systems:` names its machine on the + platform side. Emulator mode read only `system:`, so --emulator + --region us kept the Japanese file --platform --region us dropped.""" + from model.profiles import entry_system_ids + from packs.extraregions import emulator_region_drops, extra_region_groups + + profile = {"systems": ["sys-a", "sys-b"], "files": [ + {"name": "us.bin", "systems": ["sys-a"], "region": ["north-america"]}, + {"name": "jp.bin", "systems": ["sys-a"], "region": ["japan"]}, + ]} + self.assertEqual( + emulator_region_drops([("emu", profile)], False, ["north-america"]), + {"jp.bin"}, + ) + for fe in profile["files"]: + self.assertEqual( + _emulator_region_group("emu", profile, fe, fe["name"]), + "emu:system:" + extra_region_groups({ + "source_emulator": "emu", "destination": fe["name"], + "source_systems": entry_system_ids(fe, profile), + })[0], + ) + + def test_region_audit_resolves_the_way_the_pack_does(self): + """A private resolver read sha1, md5 and a lone name: an entry + identified by its path (Dolphin's three IPL.bin) was never checked.""" + import hashlib + + with tempfile.TemporaryDirectory() as directory: + previous = os.getcwd() + os.chdir(directory) + self.addCleanup(os.chdir, previous) + files, shas = {}, {} + for rel, payload in (("bios/GC/USA/IPL.bin", b"usa"), ("bios/GC/JAP/IPL.bin", b"jap")): + Path(rel).parent.mkdir(parents=True, exist_ok=True) + Path(rel).write_bytes(payload) + sha1 = hashlib.sha1(payload).hexdigest() + shas[rel] = sha1 + files[sha1] = {"path": rel, "name": "IPL.bin", "size": len(payload), "sha1": sha1, + "md5": hashlib.md5(payload).hexdigest(), + "sha256": hashlib.sha256(payload).hexdigest(), "crc32": "00000001"} + from collection.indexes import build_indexes + + db = {"files": files, "indexes": build_indexes(files, {})} + by_md5 = {e["md5"]: s for s, e in files.items()} + self.assertEqual( + regionaudit.resolve_sha1({"name": "IPL.bin", "md5": [files[shas["bios/GC/USA/IPL.bin"]]["md5"]]}, db), + shas["bios/GC/USA/IPL.bin"], + ) + self.assertEqual( + regionaudit.resolve_sha1({"name": "IPL.bin", "path": "GC/JAP/IPL.bin"}, db), + shas["bios/GC/JAP/IPL.bin"], + ) + self.assertTrue(by_md5) + + +class APackNameFitsAFileName(unittest.TestCase): + """--system snes joined 23 emulator names and died on ENAMETOOLONG + before writing anything, while verify --system snes reported.""" + + def test_a_long_selection_is_bounded_and_told_apart(self): + from scripts.packs.naming import MAX_PACK_NAME_BYTES, bounded_join + + def bounded_pack_name(display: list[str], keys: list[str], suffix: str) -> str: + return bounded_join(display, keys, joiner="_", budget=MAX_PACK_NAME_BYTES, suffix=suffix) + + names = [f"Emulator_Number_{i}" for i in range(23)] + long_name = bounded_pack_name(names, names, "_BIOS_Pack.zip") + self.assertLessEqual(len(long_name.encode()), MAX_PACK_NAME_BYTES) + self.assertTrue(long_name.startswith("Emulator_Number_0_and_22_more_")) + other = bounded_pack_name(names, names[:-1] + ["x"], "_BIOS_Pack.zip") + self.assertNotEqual(long_name, other) + self.assertEqual(bounded_pack_name(["A", "B"], ["a", "b"], ".zip"), "A_B.zip") + + def test_a_long_system_list_is_bounded(self): + """Thirty systems joined made a 261-byte platform pack name.""" + from scripts.packs.naming import MAX_SYSTEM_TAG_BYTES, system_tag + + systems = [f"vendor-console-number-{i}" for i in range(30)] + tag = system_tag(systems) + self.assertLessEqual(len(tag.encode()), MAX_SYSTEM_TAG_BYTES + 1) + self.assertNotEqual(tag, system_tag(systems[:-1] + ["other-console"])) + self.assertEqual(system_tag(["sony-playstation"]), "_Playstation") + + def test_two_systems_never_name_one_system(self): + """sega-dreamcast,arcade and sega-dreamcast-arcade both wrote + RetroArch_..._Dreamcast_Arcade.zip, and the second replaced the first.""" + from scripts.packs.naming import system_tag + + pairs = [ + (["sega-dreamcast", "arcade"], ["sega-dreamcast-arcade"]), + (["mega-cd", "sega-32x"], ["mega-cd-32x"]), + (["x86", "nintendo-64"], ["x86-64"]), + ] + for two, one in pairs: + with self.subTest(two=two): + self.assertNotEqual(system_tag(two), system_tag(one)) + + def test_two_hash_lists_get_two_names(self): + """--from-md5 named its pack after the context only: a second list + overwrote the first pack in the same directory.""" + source = script_source("generate_pack.py") + self.assertIn('_Custom_{selection}', source) + + def test_the_system_pack_names_itself(self): + source = script_source("generate_pack.py") + self.assertIn("pack_name=final_name", source) + + +class AGroupPackIsWrittenUnderItsOwnName(unittest.TestCase): + """The RetroArch + Lakka pack was written as RetroArch_..._BIOS_Pack.zip + and renamed: a `--platform retroarch` pack already in the directory was + overwritten then carried away, and os.rename refuses an existing target + on Windows.""" + + def test_no_pack_is_renamed_after_its_build(self): + source = script_source("generate_pack.py") + self.assertNotIn("os.rename(", source) + self.assertIn("pack_name=group_name", source) + + +class ARegionDroppedExtraBlocksNothing(unittest.TestCase): + """The builder skips a region-dropped core extra before placing it, + but the report placed it anyway, so on a case-folding platform it hid the + next core's FOO.ROM that the pack does carry.""" + + def test_the_report_skips_what_the_region_pass_drops(self): + from unittest import mock + + from scripts.packs import extraresolver + + with tempfile.TemporaryDirectory() as directory: + other = Path(directory) / "FOO.ROM" + other.write_bytes(b"other bytes") + first = Path(directory) / "foo.rom" + first.write_bytes(b"first bytes") + copies = {"foo.rom": str(first), "FOO.ROM": str(other)} + extras = [ + {"name": "foo.rom", "destination": "foo.rom", "source_emulator": "a"}, + {"name": "FOO.ROM", "destination": "FOO.ROM", "source_emulator": "b"}, + ] + config = {"case_insensitive_fs": True, "base_destination": ""} + + def report(region_drops): + with mock.patch.object(extraresolver, "collect_emulator_extras", + return_value=extras), \ + mock.patch.object(extraresolver, "resolve_local_file", + side_effect=lambda fe, *a, **k: ( + copies[fe["name"]], "name_exact")): + return extraresolver.hidden_extras( + config, "emulators", {"files": {}}, {}, {}, None, region_drops + ) + + self.assertTrue(report(None)) + self.assertEqual(report({"foo.rom"}), {}) + + +class APackNoteBesideItsSlotIsANote(unittest.TestCase): + """The builder writes INSTRUCTIONS_.txt beside the slot it + explains, but verify_pack recognised notes at the ZIP root only and failed + a pack holding games/keen6/INSTRUCTIONS_egagraph.ck6.txt.""" + + def test_a_nested_note_is_not_hashed_against_the_collection(self): + from scripts.packs.integrity import verify_pack + + with tempfile.TemporaryDirectory() as directory: + path = Path(directory) / "Pack.zip" + with zipfile.ZipFile(path, "w") as archive: + archive.writestr("games/keen6/INSTRUCTIONS_egagraph.ck6.txt", "File needed") + archive.writestr("bios/RENAMED_x.bin.txt", "renamed") + result = verify_pack(str(path), {"files": {}, "indexes": {}}) + self.assertTrue(result[0], result) + + def test_verify_reads_the_rule_where_it_is_defined(self): + source = script_source("verify.py") + self.assertNotIn("from generate_pack import _preferred_entries", source) + + +class AnArchiveShipsWholeUnderARegion(unittest.TestCase): + """verify --emulator dropped kronos' regional stvbios.zip members before + rebuilding the archive, so its archive held 4 of 14 members and its + required changed, while the emulator pack ships the archive whole.""" + + def test_verify_filters_loose_files_only(self): + loose_only = ( + 'if fe.get("archive")\n or resolve_destination(fe, selection.standalone)' + ' not in selection.region_drops' + ) + # The pack and the report read the same selection. + self.assertIn(loose_only, script_source("verify.py")) + self.assertIn(loose_only, script_source("generate_pack.py")) + + +class APathConflictKeepsTheMainVerdict(unittest.TestCase): + """The builder's file/directory conflict branch judged a declaration by + the raw resolver status: a zipped_file archive whose member is right was + counted excluded while verify counted it OK.""" + + def test_the_branch_reads_baseline_verdict(self): + source = script_source("generate_pack.py") + branch = source[source.index("Content ships under the conflicting shape"):] + branch = branch[: branch.index("storage = file_entry.get")] + self.assertIn("self.declarations.verdict(", branch) + self.assertNotIn('conflict_status == "hash_mismatch"', branch) + + +class AnEmptyTargetIsNotEveryCore(unittest.TestCase): + """A board scraped with `cores: []` and `add_cores: [gpsp]`: the pack + served gpsp's files only, the published list said null (every core).""" + + def test_the_published_list_is_the_builder_reading(self): + from scripts.model.targets import load_target_config + from scripts.packs.targets import generate_target_manifests + + tmp = Path(tempfile.mkdtemp()) + self.addCleanup(lambda: __import__("shutil").rmtree(tmp, True)) + targets = tmp / "platforms" / "targets" + targets.mkdir(parents=True) + (targets / "demo.yml").write_text( + "platform: demo\ntargets:\n" + " board:\n architecture: aarch64\n cores: []\n" + " full:\n architecture: x86_64\n cores: null\n" + ) + (targets / "_overrides.yml").write_text( + "demo:\n targets:\n board:\n add_cores: [gpsp]\n" + ) + with contextlib.redirect_stdout(io.StringIO()): + generate_target_manifests(str(targets), str(tmp / "out")) + published = json.loads((tmp / "out" / "demo.json").read_text()) + builder = load_target_config("demo", "board", str(tmp / "platforms")) + self.assertEqual(published["board"], sorted(builder)) + self.assertEqual(published["board"], ["gpsp"]) + self.assertIsNone(published["full"]) + + +class ADataDirectoryIsHeldWhileRead(unittest.TestCase): + """A pack resolved names against data/bluemsx, then a concurrent refresh + swapped the tree: the index named files that were gone and the copy + died on FileNotFoundError, or shipped bytes nobody had verified.""" + + def setUp(self): + self.tmp = Path(tempfile.mkdtemp()) + self.addCleanup(lambda: __import__("shutil").rmtree(self.tmp, True)) + + def test_the_index_follows_a_swapped_tree(self): + from scripts.resolve.datadirs import _data_dir_basenames + + cache = self.tmp / "cache" + cache.mkdir() + (cache / "old.rom").write_bytes(b"old") + self.assertIn("old.rom", _data_dir_basenames(str(cache))) + cache.rename(self.tmp / "gone") + cache.mkdir() + (cache / "new.rom").write_bytes(b"new") + index = _data_dir_basenames(str(cache)) + self.assertIn("new.rom", index) + self.assertNotIn("old.rom", index) + + def test_a_holder_makes_the_refresh_lock_wait(self): + import fcntl + + from scripts.packs import datadirs + + cache = self.tmp / "bluemsx" + cache.mkdir() + lock = cache.with_name(f".{cache.name}.lock") + + def exclusive_free() -> bool: + with open(lock, "a") as handle: + try: + fcntl.flock(handle, fcntl.LOCK_EX | fcntl.LOCK_NB) + except BlockingIOError: + return False + fcntl.flock(handle, fcntl.LOCK_UN) + return True + + with contextlib.ExitStack() as held: + datadirs.hold_data_dirs(held, {"bluemsx": {"local_cache": str(cache)}}) + self.assertFalse(exclusive_free()) + self.assertTrue(exclusive_free()) + + def test_a_cache_not_yet_on_disk_is_held_too(self): + """Skipped while absent, a tree a refresh installed mid-run was + missing for verify and present for the packs of the same run.""" + import fcntl + + from scripts.packs import datadirs + + cache = self.tmp / "absent" + lock = cache.with_name(f".{cache.name}.lock") + with contextlib.ExitStack() as held: + datadirs.hold_data_dirs(held, {"absent": {"local_cache": str(cache)}}) + self.assertFalse(cache.exists()) + with open(lock, "a") as handle, self.assertRaises(BlockingIOError): + fcntl.flock(handle, fcntl.LOCK_EX | fcntl.LOCK_NB) + + def test_both_entry_points_hold_the_trees(self): + pack = script_source("generate_pack.py") + verify_src = script_source("verify.py") + self.assertIn("hold_data_dirs(held,", verify_src) + refresh = pack.index("results = refresh_all(") + self.assertIn("hold_data_dirs(held, data_registry)", pack[refresh:]) + + def test_verify_packs_alone_holds_the_trees(self): + # --verify-packs returned before the hold and resolved core files + # against data/ while a refresh could swap a tree. + pack = script_source("generate_pack.py") + branch = pack.index("if args.verify_packs and not args.all_variants:") + run = pack.index("run_verify_packs(args)", branch) + self.assertIn("hold_data_dirs(held,", pack[branch:run]) + + +class ReportsHoldTheDataTrees(unittest.TestCase): + """Run on their own, the README, site and slot reports resolved against + data/ without the shared hold, so a concurrent refresh could swap a tree + while they read it and the published counts came from half of it.""" + + def test_each_entry_point_holds_them(self): + import ast + + # export_native holds them in build_export, which the freshness + # check calls too (TheExportHoldsTheDataTrees in test_export_report). + for script in ("generate_readme.py", "generate_site.py", "slots.py", + "cross_reference.py"): + tree = ast.parse((ROOT / "scripts" / script).read_text(encoding="utf-8")) + main = next( + node for node in tree.body + if isinstance(node, ast.FunctionDef) and node.name == "main" + ) + # A thin command holds them in main or in the package run main calls. + called = {getattr(call.func, "id", None) for call in ast.walk(main) + if isinstance(call, ast.Call)} + entry_points = [main] + [ + node for node in ast.walk(ast.parse(script_source(script))) + if isinstance(node, ast.FunctionDef) and node.name in called + ] + with self.subTest(script=script): + self.assertTrue(any( + isinstance(call, ast.Call) + and getattr(call.func, "id", None) == "hold_data_dirs" + for entry in entry_points for call in ast.walk(entry) + )) + + +class ThePackCheckAppliesTheFrontendRule(unittest.TestCase): + """The integrity step compared a member's md5 alone. Under RomM's rule + (size, then any of md5, sha1 and crc32) the builder ships a revision + matched on its sha1, and the check then refused a correct pack.""" + + def test_romm_accepts_on_size_and_sha1(self): + import hashlib + import zipfile + + from scripts.packs.packhashes import _check_member_hash + + payload = b"revision B" + entry = { + "md5": "0" * 32, + "sha1": hashlib.sha1(payload).hexdigest(), + "size": len(payload), + } + with tempfile.TemporaryDirectory() as tmp: + pack = Path(tmp) / "p.zip" + with zipfile.ZipFile(pack, "w") as zf: + zf.writestr("bios/x.bin", payload) + with zipfile.ZipFile(pack) as zf: + self.assertIsNone( + _check_member_hash(zf, "bios/x.bin", entry, "md5", "size_and_any_hash") + ) + self.assertIsNotNone(_check_member_hash(zf, "bios/x.bin", entry, "md5")) + + +class RequiredOnlyReachesDataDirectories(unittest.TestCase): + """--required-only filtered files and packed every data tree anyway: the + Required RetroArch pack still carried the 90 FreeIntv overlays, which the + core reads only with its multi-screen option and replaces by a drawn + keypad when absent (FreeIntv src/libretro.c:294-296, 350-369).""" + + def _members(self, required_only: bool) -> list[str]: + from scripts.packs import datatrees + from scripts.packs.archive import Placed + + with tempfile.TemporaryDirectory() as tmp: + for key in ("needed", "optional"): + Path(tmp, key).mkdir() + Path(tmp, key, f"{key}.bin").write_bytes(b"x") + registry = { + key: {"local_cache": str(Path(tmp, key))} + for key in ("needed", "optional") + } + systems = { + "sys": { + "data_directories": [ + {"ref": "needed", "destination": "a"}, + {"ref": "optional", "destination": "b", "required": False}, + ] + } + } + return [ + dest + for _src, dest in datatrees.data_directory_members( + systems, registry, "retroarch", "", Placed(False), + required_only=required_only, + ) + ] + + def test_an_optional_tree_leaves_the_required_pack(self): + self.assertEqual(self._members(False), ["a/needed.bin", "b/optional.bin"]) + self.assertEqual(self._members(True), ["a/needed.bin"]) + + def test_every_tree_walk_reads_the_flag(self): + source = script_source("generate_pack.py") + # The pack's walk and the manifest's, which records the flag for + # install.py --required-only. + self.assertEqual(source.count('if required_only and dd.get("required") is False:'), 1) + self.assertIn('needed = dd.get("required") is not False\n if required_only and not needed:', + source) + self.assertIn("self.placed, required_only=required_only,", source) + self.assertIn("data_refs, required_only=required_only,", source) + + def test_the_overlays_are_declared_optional(self): + retroarch = yaml.safe_load((ROOT / "platforms" / "retroarch.yml").read_text()) + trees = retroarch["systems"]["mattel-intellivision"]["data_directories"] + self.assertEqual(trees, [ + {"ref": "freeintv-overlays", "destination": "freeintv_overlays", + "required": False}, + ]) + + def test_an_alias_reads_the_trees_of_its_core(self): + """An alias is the same binary under another name. FreeIntv declared + no overlay tree while its alias freeintv_ts_overlay did, so the + emulator pack of the core itself left the overlays out.""" + profiles = { + path.stem: yaml.safe_load(path.read_text(encoding="utf-8")) + for path in (ROOT / "emulators").glob("*.yml") + } + + def trees(profile: dict) -> dict: + return { + dd["ref"]: dd.get("required", True) + for dd in profile.get("data_directories") or [] + } + + for name, profile in profiles.items(): + target = profile.get("alias_of") + if not target or target not in profiles: + continue + with self.subTest(alias=name, core=target): + self.assertEqual(trees(profile), trees(profiles[target])) + + +class _ResponseBody(io.BytesIO): + """A body with the headers attribute urlopen's response carries.""" + + headers: dict[str, str] = {} + + +class ExternalDownloadsFollowTheRunPolicy(unittest.TestCase): + """download_external lived outside packresolve and fetched under + --offline, into the system /tmp, holding the whole body in memory.""" + + ENTRY = {"name": "ext.bin", "source_url": "https://example.invalid/ext.bin", + "sha1": hashlib.sha1(b"payload").hexdigest()} + + def setUp(self): + # tests/__init__ sets RETROBIOS_OFFLINE for the suite: these cases + # download from a mocked urlopen, so the switch is cleared here. + patcher = mock.patch.dict(os.environ, {"RETROBIOS_OFFLINE": ""}) + patcher.start() + self.addCleanup(patcher.stop) + + def _response(self, body: bytes): + stream = _ResponseBody(body) + response = mock.MagicMock() + response.__enter__.return_value = stream + response.__exit__.return_value = False + return response + + def test_offline_never_reaches_the_network(self): + from resolve import packfiles as packresolve + + with tempfile.TemporaryDirectory() as tmp, \ + mock.patch("urllib.request.urlopen") as urlopen, \ + contextlib.redirect_stdout(io.StringIO()) as out: + fetch = packresolve.download_external(self.ENTRY, f"{tmp}/x", offline=True) + self.assertIs(fetch.outcome, packresolve.ExternalOutcome.OFFLINE) + self.assertFalse(fetch.fetched) + self.assertEqual(out.getvalue(), "") + urlopen.assert_not_called() + + def test_each_failure_names_its_own_cause(self): + """Four causes came back as one False, reported as a download failure.""" + from core import forgehttp + from resolve import packfiles as packresolve + + outcome = packresolve.ExternalOutcome + with tempfile.TemporaryDirectory() as tmp: + no_hash = packresolve.download_external( + {"name": "ext.bin", "source_url": "https://example.invalid/x"}, + f"{tmp}/x", offline=False) + offline = packresolve.download_external(self.ENTRY, f"{tmp}/x", offline=True) + with mock.patch("urllib.request.urlopen", + side_effect=urllib.error.URLError("refused")), \ + mock.patch.object(forgehttp, "_sleep", lambda _s: None): + failed = packresolve.download_external(self.ENTRY, f"{tmp}/x", offline=False) + self.assertIs(no_hash.outcome, outcome.NO_HASH) + self.assertIs(offline.outcome, outcome.OFFLINE) + self.assertIs(failed.outcome, outcome.NETWORK_ERROR) + self.assertIn("offline", offline.reason) + self.assertIn("hash", no_hash.reason) + self.assertIn("refused", failed.reason) + + def test_the_run_switch_is_inherited(self): + from resolve import packfiles as packresolve + + saved = packresolve.OFFLINE + packresolve.set_offline(True) + try: + with tempfile.TemporaryDirectory() as tmp, \ + mock.patch("urllib.request.urlopen") as urlopen: + self.assertFalse(packresolve.download_external(self.ENTRY, f"{tmp}/x").fetched) + urlopen.assert_not_called() + finally: + packresolve.set_offline(saved) + + def test_the_environment_switch_holds_whatever_the_caller_passes(self): + """RETROBIOS_OFFLINE stopped release assets but not external URLs.""" + from resolve import packfiles as packresolve + + with tempfile.TemporaryDirectory() as tmp, \ + mock.patch.dict(os.environ, {"RETROBIOS_OFFLINE": "1"}), \ + mock.patch("urllib.request.urlopen") as urlopen: + self.assertFalse( + packresolve.download_external(self.ENTRY, f"{tmp}/x", offline=False).fetched) + urlopen.assert_not_called() + + def test_a_verified_body_lands_and_a_wrong_one_is_removed(self): + from resolve import packfiles as packresolve + + with tempfile.TemporaryDirectory() as tmp: + target = Path(tmp) / "x" + with mock.patch("urllib.request.urlopen", + return_value=self._response(b"payload")): + self.assertTrue( + packresolve.download_external(self.ENTRY, str(target), offline=False).fetched) + self.assertEqual(target.read_bytes(), b"payload") + target.unlink() + with mock.patch("urllib.request.urlopen", + return_value=self._response(b"other")): + fetch = packresolve.download_external(self.ENTRY, str(target), offline=False) + self.assertIs(fetch.outcome, packresolve.ExternalOutcome.MISMATCH) + self.assertFalse(target.exists()) + + def test_every_accepted_value_of_a_listed_field_verifies(self): + # A list or a comma-joined field was compared as its string form + # ("['a', 'b']"), so no body could ever match it. + from resolve import packfiles as packresolve + + good = hashlib.sha1(b"payload").hexdigest().upper() + for sha1 in (["0" * 40, good], f"{'0' * 40}, {good}"): + with self.subTest(sha1=sha1), tempfile.TemporaryDirectory() as tmp, \ + mock.patch.object(packresolve.urllib.request, "urlopen", + return_value=self._response(b"payload")): + entry = {**self.ENTRY, "sha1": sha1} + self.assertTrue( + packresolve.download_external(entry, f"{tmp}/x", offline=False).fetched) + + def test_a_transient_failure_is_retried_and_no_scratch_remains(self): + """One 503 failed the external file for the whole build.""" + from core import forgehttp + from resolve import packfiles as packresolve + + refusal = urllib.error.HTTPError(self.ENTRY["source_url"], 503, "busy", {}, None) + with tempfile.TemporaryDirectory() as tmp: + target = Path(tmp) / "x" + with mock.patch("urllib.request.urlopen", + side_effect=[refusal, self._response(b"payload")]), \ + mock.patch.object(forgehttp, "_sleep", lambda _s: None): + self.assertTrue( + packresolve.download_external(self.ENTRY, str(target), offline=False).fetched) + self.assertEqual(target.read_bytes(), b"payload") + self.assertEqual(os.listdir(tmp), ["x"]) + + def test_scratch_files_stay_in_the_repository(self): + source = script_source("generate_pack.py") + self.assertNotIn("def download_external", source) + self.assertNotIn("urlopen", source) + for call in re.findall(r"NamedTemporaryFile\(([^)]*)\)", source): + self.assertIn("dir=", call) + + +class NoArchiveRepeatsAMemberName(unittest.TestCase): + """s8k_cpu.zip held three member names twice (MAME reuses them across + two ROM_SYSTEM_BIOS of one device). Every pack build printed raw zipfile + warnings and Info-ZIP stops on an interactive replace? at extraction.""" + + def test_member_names_are_unique(self): + archives = sorted((ROOT / "bios").rglob("*.zip")) + if not archives: + self.skipTest("no archive under bios/") + repeated = [] + for path in archives: + try: + with zipfile.ZipFile(path) as zf: + names = zf.namelist() + except (zipfile.BadZipFile, OSError): + continue + if len(names) != len(set(names)): + repeated.append(str(path.relative_to(ROOT))) + self.assertEqual(repeated, []) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_audit_profiles.py b/tests/test_audit_profiles.py new file mode 100644 index 000000000..88e0a99ef --- /dev/null +++ b/tests/test_audit_profiles.py @@ -0,0 +1,1164 @@ +"""Audit regressions on emulator profiles: citations, pins, found-by-content cores and bundled files.""" + +from __future__ import annotations + +import tests +from tests.sources import script_source +import contextlib +import io +import json +import re +import subprocess +import sys +import tempfile +import unittest +from pathlib import Path +from unittest import mock +import yaml +from tests.auditsupport import HAS_JSONSCHEMA, ROOT + + +class UnreachableCitationRegressions(unittest.TestCase): + """A citation must name a place a declared repository can hold. + + kenji-nx carried tmp/es-de/ANDROID.md:470-474, a path from the machine + of whoever profiled it. No revision of any declared repository holds it, + so profile_sync could only report it missing, every pass, forever. The + check is offline and runs on every push. + """ + + @unittest.skipUnless(HAS_JSONSCHEMA, "validating a schema needs jsonschema") + def _hits(self, text: str) -> bool: + from schemas import citations + + return bool(citations.UNREACHABLE_REF.search(" " + text)) + + def test_a_scratch_directory_is_rejected(self): + self.assertTrue(self._hits("tmp/es-de/ANDROID.md:470-474")) + + def test_an_absolute_path_is_rejected(self): + self.assertTrue(self._hits("/home/someone/src/a.c:12")) + self.assertTrue(self._hits(r"C:\work\src\a.c:12")) + + def test_a_path_climbing_out_of_the_tree_is_rejected(self): + self.assertTrue(self._hits("../outside/src/a.c:12")) + + def test_ordinary_citations_pass(self): + for good in ( + "src/core/main.cpp:210", + "libretro.c:5293-5337", + "PCE.emu/src/main/Main.cc:80-91", + "es-de ANDROID.md:470-474", + "see tmp files for details", + ): + with self.subTest(citation=good): + self.assertFalse(self._hits(good)) + + @unittest.skipUnless(HAS_JSONSCHEMA, "validating a schema needs jsonschema") + def test_the_corpus_carries_none(self): + from schemas import citations + + errors = [] + for path in sorted((ROOT / "emulators").glob("*.yml")): + with path.open(encoding="utf-8") as handle: + errors.extend( + citations.unreachable_citations(path, yaml.safe_load(handle)) + ) + self.assertEqual(errors, []) + + +@unittest.skipUnless(HAS_JSONSCHEMA, "validate_schemas needs jsonschema") +class DoubledCitationPaths(unittest.TestCase): + """primehack cited Source/Core/Core/IOS/USB/Bluetooth/ twice in a row in a + comment: no revision holds that path, and the parsed document never + showed it to the citation checks.""" + + def _hits(self, text: str) -> bool: + from schemas import citations + + return bool(citations.DOUBLED_PATH.search(text)) + + def test_a_repeated_directory_is_rejected(self): + self.assertTrue(self._hits( + "# ref: Source/Core/Core/IOS/USB/Bluetooth/Source/Core/Core/IOS/USB/" + "Bluetooth/RealtekFirmwareLoader.cpp:373-416" + )) + + def test_a_directory_named_once_passes(self): + for good in ( + "Source/Core/Core/IOS/USB/Bluetooth/RealtekFirmwareLoader.cpp:383", + "src/src/main.c:10", + "a/b/c/a/b.c:1", + ): + with self.subTest(citation=good): + self.assertFalse(self._hits(good)) + + def test_the_corpus_carries_none(self): + from schemas import citations + + errors = [] + for path in sorted((ROOT / "emulators").glob("*.yml")): + errors.extend(citations.doubled_paths(path)) + self.assertEqual(errors, []) + + +class KidVidTapesStayWithTheContent(unittest.TestCase): + """Stella opens its KidVid tapes by bare name (stella2014, from the + working directory) or from its base directory (stella2023, the content + folder, and stella, a folder under the save directory): never the system + directory. Without load_from every Linux pack put about 68 MB of WAVs at + the BIOS root, in two cases. The save directory is a place a pack + reaches: stella's tapes go there, never to the BIOS tree.""" + + def test_no_pack_places_them_in_the_system_directory(self): + from scripts.model.profiles import load_emulator_profiles + from scripts.resolve.entryscope import ( + outside_gap_scope, + read_from_save_dir, + read_from_system_dir, + ) + + profiles = load_emulator_profiles(str(ROOT / "emulators")) + for name in ("stella", "stella2014", "stella2023"): + tapes = [f for f in profiles[name]["files"] + if f["name"].lower().endswith(".wav")] + with self.subTest(profile=name): + self.assertEqual(len(tapes), 7) + self.assertFalse(any(read_from_system_dir(f, False) for f in tapes)) + for f in tapes: + self.assertTrue( + outside_gap_scope(f, False) or read_from_save_dir(f, False) + ) + + +class GeneralUserGSReachesEveryCoreThatNamesIt(unittest.TestCase): + """The SoundFont was held as dosbox_pure's DOSBOX.SF2 alone: dosbox-staging + and dosbox-x, which name it GeneralUser-GS.sf2 and GeneralUser_GS.sf2, + shipped no General MIDI bank.""" + + def test_each_name_resolves_to_the_one_file(self): + from model import profiles as model_profiles + from resolve import localfile + + if not (ROOT / "database.json").exists(): + self.skipTest("database.json is not generated") + db = json.loads((ROOT / "database.json").read_text()) + profiles = model_profiles.load_emulator_profiles(str(ROOT / "emulators")) + held = "bios/Other/GeneralUser GS/GeneralUser-GS.sf2" + for emulator, name in (("dosbox_pure", "DOSBOX.SF2"), + ("dosbox-staging", "GeneralUser-GS.sf2"), + ("dosbox-x", "GeneralUser_GS.sf2")): + with self.subTest(emulator=emulator): + entry = next(f for f in profiles[emulator]["files"] if f["name"] == name) + path, _status = localfile.resolve_local_file( + {**entry, "source_profile": emulator}, db, dest_hint=entry.get("path", "")) + self.assertEqual(path, held) + + +class APlatformPinDoesNotReplaceTheCoresRevision(unittest.TestCase): + """RetroArch pins ScummVM's kyra.dat and FBNeo's hiscore.dat at older + revisions. Collected as variants with profiles that claimed no content, + the platform's md5 became the only proof and the pack shipped the old + files to cores built against newer ones.""" + + def test_the_profile_revision_serves_the_core(self): + from model import profiles as model_profiles + from resolve import localfile + + if not (ROOT / "database.json").exists(): + self.skipTest("database.json is not generated") + db = json.loads((ROOT / "database.json").read_text()) + profiles = model_profiles.load_emulator_profiles(str(ROOT / "emulators")) + for emulator, name, pinned in (("scummvm", "kyra.dat", "21a57f79886e46f410cfb50186ed8d77"), + ("fbneo", "hiscore.dat", "37fc4e050b53a1ef2c2e7f3042553025")): + with self.subTest(emulator=emulator): + entry = next(f for f in profiles[emulator]["files"] if f["name"] == name) + self.assertTrue(entry.get("sha1"), "the profile claims its revision") + self.assertIn(pinned, db["indexes"]["by_md5"], "the platform's pin is held") + path, status = localfile.resolve_local_file( + {**entry, "source_profile": emulator}, db, dest_hint=entry["path"]) + self.assertEqual(status, "sha1_exact") + self.assertEqual(db["files"][entry["sha1"]]["path"], path) + + +class ProseCitationsUseTheTrackedForm(unittest.TestCase): + """profile_sync tracks `path:line` citations only. `libretro.c + I_FindFile, line 1742` escaped it, and sixteen such citations in six + profiles stayed behind when their pins moved, four already pointing at + other code.""" + + UNTRACKED = re.compile( + r"[\w./+-]+\.(?:c|cc|cpp|cxx|h|hh|hpp|inc|cs|py|rs|go|java|kt|js|ts" + r"|m|mm|s|asm|lua|sh)\b[^\n:]{0,80}?\blines? \d+" + ) + + def test_the_pattern_reads_the_old_forms(self): + for text in ("libretro.c I_FindFile, line 1742", + "memory.c LoadBios() line 1353", + "libretro_core_options.h lines 52-64"): + self.assertRegex(text, self.UNTRACKED) + self.assertNotRegex("I_FindFile, libretro/libretro.c:4176-4252", self.UNTRACKED) + + def test_no_profile_writes_a_line_number_profile_sync_cannot_see(self): + found = [ + f"{path.name}:{number}: {match.group(0)}" + for path in sorted((ROOT / "emulators").glob("*.yml")) + for number, line in enumerate(path.read_text().splitlines(), 1) + for match in self.UNTRACKED.finditer(line) + ] + self.assertEqual(found, []) + + +class ACitationInsideASourceRefIsTracked(unittest.TestCase): + """split_source_ref reads each chunk's located head and drops the rest. + zesarux cited src/cpu.h:545 inside an annotation, four lines off at its + pin, and pce-emu joined two citations with ` + `: neither was anchored.""" + + def citations(self, ref: str) -> list[tuple[str, str]]: + from scripts.profiling.citations import collect_citations + + document = {"files": [{"name": "x.rom", "source_ref": ref}]} + return [(c.kind, c.ref) for c in collect_citations(document)] + + def test_an_annotation_citation_is_read_as_prose(self): + found = self.citations( + "src/cpu.c:3381-3383, src/utils.c:4100 " + "(MACHINE_IS_SPECTRUM_128_P2 covers Pentagon, src/cpu.h:549)" + ) + self.assertIn(("prose", "src/cpu.h:549"), found) + self.assertNotIn(("prose", "src/cpu.c:3381-3383"), found) + + def test_a_joined_citation_is_read_as_prose(self): + found = self.citations( + "src/pce_fast/pce.cpp:477-483 + src/pce_fast/huc.cpp:284-304" + ) + self.assertIn(("prose", "src/pce_fast/huc.cpp:284-304"), found) + self.assertEqual([c for c in found if c[0] == "prose"], + [("prose", "src/pce_fast/huc.cpp:284-304")]) + + def test_offsets_match_the_scalar(self): + from scripts.model.sourceref import ref_prose_text + + ref = "a.c:1-2, 5 (see b.c:7)" + masked = ref_prose_text(ref) + self.assertEqual(len(masked), len(ref)) + self.assertEqual(masked.index("b.c:7"), ref.index("b.c:7")) + self.assertNotIn("a.c", masked) + + +class OpenMsxRomsSitInItsSystemroms(unittest.TestCase): + """openMSX entries had no path and landed at the BIOS root, where no + frontend points FilePool. The profile writes share/systemroms below + openMSX's user folder, the pool's first place (src/file/FilePool.cc, + FileOperations.cc), and RetroBat, which sets OPENMSX_HOME to + bios/openmsx and declares its ROMs under openMSX/share/systemroms, gets + them there.""" + + def test_every_entry_is_under_share_systemroms(self): + from scripts.model.profiles import load_emulator_profiles + from scripts.model.platforms import load_platform_config + from scripts.resolve.standalone import platform_layouts, platform_launches + + profiles = load_emulator_profiles(str(ROOT / "emulators")) + profile = profiles["openmsx"] + retrobat = yaml.safe_load((ROOT / "platforms" / "retrobat.yml").read_text()) + declared_dirs = { + fe["destination"].rsplit("/", 1)[0].lower() + for system in retrobat["systems"].values() + for fe in system.get("files", []) + if "systemroms" in fe.get("destination", "") + } + self.assertEqual(declared_dirs, {"openmsx/share/systemroms"}) + config = load_platform_config("retrobat", str(ROOT / "platforms")) + ((view, _standalone),) = platform_layouts("openmsx", profile, platform_launches(config, profiles)) + placed = {f["name"]: f for f in view["files"]} + for entry in profile["files"]: + with self.subTest(name=entry["name"]): + self.assertEqual(entry.get("path", "").lower(), + f"share/systemroms/{entry['name']}".lower()) + self.assertEqual(placed[entry["name"]].get("standalone_path", "").lower(), + f"openmsx/share/systemroms/{entry['name']}".lower()) + + +class EmuDeckRunsItsEmulatorsStandalone(unittest.TestCase): + """EmuDeck declared no standalone_cores: Dolphin, Cemu, xemu, ARMSX2 and + Supermodel, installed as apps by EmuScripts, got the libretro layout and + lost their standalone-only files.""" + + def test_every_emuscripts_emulator_is_standalone(self): + from scripts.model.platforms import load_platform_config + from scripts.resolve.launches import PlatformLaunches + from scripts.model.profiles import load_emulator_profiles + + config = load_platform_config("emudeck", str(ROOT / "platforms")) + self.assertEqual( + sorted(config["standalone_cores"]), + sorted(c for c in config["cores"] if c != "retroarch"), + ) + profiles = load_emulator_profiles(str(ROOT / "emulators")) + standalone = PlatformLaunches(standalone=frozenset(config["standalone_cores"])) + for name in ("dolphin", "cemu", "armsx2", "supermodel"): + with self.subTest(emulator=name): + self.assertTrue(standalone.runs_standalone(name, profiles[name])) + + def test_retroarch_brings_its_libretro_cores(self): + """The scraper dropped RetroArch's own script: np2kai, neocd and + every core EmuDeck installs through RetroArch got no file that + checkBIOS.sh does not name.""" + from scripts.model.profiles import load_emulator_profiles + from scripts.model.platforms import load_platform_config + from scripts.resolve.cores import resolve_platform_cores + + config = load_platform_config("emudeck", str(ROOT / "platforms")) + self.assertIn("retroarch", config["cores"]) + cores = resolve_platform_cores(config, load_emulator_profiles(str(ROOT / "emulators"))) + for name in ("np2kai", "neocd", "dolphin"): + with self.subTest(core=name): + self.assertIn(name, cores) + + +class BundledFilesAreNotToSource(unittest.TestCase): + """DaedalusX64's n64.psh, the shader library its renderer installs + beside the binary, was reported as a required core file missing and + listed among the files to source, with 19 more like it.""" + + def test_verify_does_not_count_it_missing(self): + from packs import verifysummary + from packs import shares as packs_shares + + entry = {"name": "n64.psh", "required": True, "in_repo": False, + "category": "bios", "in_pack": True, "bundled": True} + self.assertEqual(packs_shares.core_required_missing([entry]), []) + summary = verifysummary.overall_summary( + [({"severity_counts": {}, "undeclared_files": [entry]}, ["ROCKNIX"])] + ) + self.assertNotIn("n64.psh", summary) + + def test_the_site_gives_it_its_own_status(self): + from sitegen import exportrows + + rows = exportrows.gap_export_rows({}, {"daedalusx64": { + "emulator": "DaedalusX64", "systems": ["nintendo-64"], + "gap_details": [{"name": "n64.psh", "source": "missing", "required": True, + "in_repo": False, "bundled": True}], + }}) + self.assertEqual([row["status"] for row in rows], ["bundled"]) + + def test_a_held_bundled_file_is_not_packed(self): + """A file installed with the emulator is already on the user's + machine, so the pack leaves it out even when the collection holds it.""" + from packs import coverage as packs_coverage + + entry = {"name": "n64.psh", "required": True, "in_repo": True, + "emulator": "daedalusx64", "category": "bios", "bundled": True} + with mock.patch("packs.extraresolver.unplaceable_extras", return_value={}): + packs_coverage._mark_unplaced({}, [entry], {}) + self.assertFalse(entry["in_pack"]) + self.assertIn("installed with its emulator", entry["omitted"]) + + def test_a_build_scope_keeps_it_for_the_other_build(self): + """PPSSPP's standalone release ships assets/, its libretro core does + not: bundled for one build, the entry still reaches a core's pack.""" + from resolve.entryscope import deliverable + + entries = [{"ref": "ppsspp-assets", "mode": "libretro"}, + {"name": "a.bin", "bundled": True, "mode": "standalone"}, + {"name": "b.bin", "bundled": True}] + self.assertEqual([e.get("ref") or e["name"] for e in deliverable(entries, False)], + ["ppsspp-assets"]) + self.assertEqual(deliverable(entries, True), []) + + def test_a_platform_package_can_differ_both_ways(self): + """Batocera's hcl package installs the binary alone, its blueMSX core + package copies the machines beside the core.""" + from resolve.entryscope import installed_with_emulator + + hcl = {"name": "data.pak", "bundled": True, "not_bundled_on": ["batocera"]} + machines = {"name": "Machines/MSX/config.ini", "installed_on": ["batocera", "retropie"]} + self.assertTrue(installed_with_emulator(hcl, "retrobat")) + self.assertFalse(installed_with_emulator(hcl, "batocera")) + self.assertTrue(installed_with_emulator(machines, "retropie")) + self.assertFalse(installed_with_emulator(machines, "retroarch")) + self.assertTrue(installed_with_emulator(hcl)) + + def test_a_view_naming_no_setup_keeps_what_one_package_leaves_out(self): + """touchHLE panics without its fonts on ROCKNIX: the emulator page, + the global gap report and the wanted list all still ask for them.""" + from acquire.provenance import profile_needs + from packs.crossref import cross_reference + from resolve.entryscope import installed_everywhere + from sitegen.install import comes_with_app + + font = {"name": "LiberationMono-Regular.ttf", "bundled": True, + "not_bundled_on": ["rocknix"]} + self.assertFalse(installed_everywhere(font)) + self.assertFalse(comes_with_app(font)) + self.assertTrue(installed_everywhere({"name": "a.bin", "bundled": True})) + profiles = {"touchhle": {"emulator": "touchHLE", "type": "standalone", + "systems": ["apple-ios"], "files": [font]}} + report = cross_reference(profiles, {}, {"files": {}, "indexes": {}}) + self.assertFalse(report["touchhle"]["gap_details"][0]["bundled"]) + sized = {**font, "size": 312132} + needs = profile_needs({"touchhle": {"files": [sized]}}, {"files": {}, "indexes": {}}) + self.assertIn("liberationmono-regular.ttf", needs["by_name"]) + everywhere = {**sized, "not_bundled_on": []} + needs = profile_needs({"touchhle": {"files": [everywhere]}}, {"files": {}, "indexes": {}}) + self.assertEqual(needs["by_name"], {}) + + def test_every_platform_named_is_registered(self): + from model.registry import list_registered_platforms + from model.profiles import load_emulator_profiles + + known = set(list_registered_platforms(str(ROOT / "platforms"))) + unknown = sorted({ + (name, platform) + for name, profile in load_emulator_profiles(str(ROOT / "emulators")).items() + for entry in (profile.get("files") or []) + (profile.get("data_directories") or []) + if isinstance(entry, dict) + for field in ("installed_on", "not_bundled_on") + for platform in entry.get(field) or [] + if platform not in known + }) + self.assertEqual(unknown, []) + + def test_a_tree_the_platform_installs_leaves_its_pack(self): + """retroarch.yml names dolphin-sys and ppsspp-assets and Lakka + inherits them, while Lakka's core packages install both trees.""" + from model.profiles import installed_data_refs_in + + profiles = {"dolphin": { + "emulator": "Dolphin", "type": "libretro", "files": [], + "data_directories": [{"ref": "dolphin-sys", "installed_on": ["lakka"]}]}} + self.assertEqual(installed_data_refs_in("lakka", profiles), frozenset({"dolphin-sys"})) + self.assertEqual(installed_data_refs_in("retroarch", profiles), frozenset()) + source = script_source("generate_pack.py") + self.assertIn("if ref_key in installed:", source) + self.assertIn("installed=installed_data_refs_in(plan.platform_name", source) + + def test_the_pack_builder_skips_it(self): + source = (ROOT / "scripts" / "packs" / "extras.py").read_text(encoding="utf-8") + self.assertIn('if u.get("bundled"):', source) + + +class RommRunsTheCoresItsPlayerNames(unittest.TestCase): + """RomM's player merges a nightly core map into the stable one when netplay + is on. Inheriting EmulatorJS's list left azahar, bsnes and + genesis_plus_gx_wide out of the RomM pack, though RomM launches them.""" + + SOURCE = """ +const _EJS_CORES_MAP: Record = { + "3do": ["opera"], + arcade: [ + "mame2003_plus", + "fbneo", + ], +} as const; + +const _EJS_NIGHTLY_CORES_MAP: Record = { + "3ds": ["azahar"], + snes: ["snes9x", "bsnes"], +}; +""" + + def test_both_maps_are_read(self): + from scripts.scraper.romm_scraper import parse_player_cores + + self.assertEqual( + parse_player_cores(self.SOURCE), + ["azahar", "bsnes", "fbneo", "mame2003_plus", "opera", "snes9x"], + ) + + def test_a_missing_map_raises(self): + from scripts.scraper.romm_scraper import parse_player_cores + + source = self.SOURCE.replace("_EJS_NIGHTLY_CORES_MAP", "_RENAMED") + with self.assertRaises(RuntimeError): + parse_player_cores(source) + + def test_the_platform_file_carries_the_nightly_cores(self): + from model.platforms import load_platform_config + + cores = set(load_platform_config("romm", str(ROOT / "platforms"))["cores"]) + self.assertTrue({"azahar", "bsnes", "genesis_plus_gx_wide"} <= cores) + + +class RommNeoGeoFoldersGetTheirBios(unittest.TestCase): + """RomM runs fbneo for neogeoaes and neogeomvs as for arcade and reads + firmware per platform folder, but the fixture gives neogeo.zip to arcade + alone, so a Neo Geo game in its own folder started without it.""" + + def test_the_mirror_is_per_file(self): + from scripts.scraper.romm_scraper import FIRMWARE_MIRRORS, SLUG_MAP + + arcade = FIRMWARE_MIRRORS["arcade"] + self.assertEqual(arcade["neogeoaes"], ("neogeo.zip",)) + self.assertEqual(arcade["neogeomvs"], ("neogeo.zip",)) + self.assertIn("neogeoaes", SLUG_MAP) + + def test_a_file_files_under_its_own_system_only(self): + # Adding the Neo Geo slugs sent MAME 2003's ZN-1 BIOS and data files + # into neogeoaes/, and FBNeo's CPS3 sets already sat in colecovision/: + # a system the platform lacks has no folder, and a mirror-only + # folder attracts no system-less file. + from scripts.packs.extraplace import _slug_for + + config_systems = {"arcade", "snk-neogeo-aes", "nintendo-ds"} + sys_to_slug = {"arcade": "arcade", "snk-neogeo-aes": "neogeoaes", + "nintendo-ds": "nds"} + profiles = {"mame2003": {"systems": ["snk-neogeo-aes", "zn1-acclaim"]}, + "melonds": {"systems": ["nintendo-ds", "nintendo-dsi"]}} + args = (profiles, config_systems, {}, sys_to_slug, {"arcade", "nintendo-ds"}) + self.assertEqual(_slug_for({"profile": "mame2003", "system": "zn1-acclaim"}, *args), "") + self.assertEqual(_slug_for({"profile": "mame2003"}, *args), "") + self.assertEqual(_slug_for({"profile": "melonds", "system": "nintendo-dsi"}, *args), "") + self.assertEqual(_slug_for({"profile": "melonds"}, *args), "nds") + + def test_the_platform_file_carries_it(self): + text = (ROOT / "platforms" / "romm.yml").read_text(encoding="utf-8") + self.assertIn("destination: neogeoaes/neogeo.zip", text) + self.assertIn("destination: neogeomvs/neogeo.zip", text) + self.assertNotIn("neogeoaes/pgm.zip", text) + + +class AProfilePathIsTheEmulatorsNotOurs(unittest.TestCase): + """No guard stopped a profile `path:` naming .variants/, our storage: + the pack would write the file where no emulator reads.""" + + def test_a_variants_path_is_refused(self): + from unittest import mock + + try: + from schemas import sourcetree + except ImportError as exc: + self.skipTest(f"validate_schemas needs jsonschema: {exc}") + + with tempfile.TemporaryDirectory() as directory: + emulators = Path(directory) / "emulators" + emulators.mkdir() + (emulators / "x.yml").write_text( + "emulator: X\nfiles:\n - name: scph1001.bin\n" + " path: .variants/scph1001.bin.abc12345\n" + ) + with mock.patch("core.paths.REPO_ROOT", Path(directory)): + errors = sourcetree.repository_layout_in_profiles() + self.assertEqual(len(errors), 1) + self.assertIn(".variants/", errors[0]) + + +class AHashScanningCoreContradictsNoPlatform(unittest.TestCase): + """ares finds its firmware by sha256 in a folder and opens no file by + name, so its entries' names are labels. Labels reused from other dumps + (MSX2.ROM, bios_CD_U.bin) put ares's revision on a path where RetroBat + pins another: slots called RetroBat's declaration wrong, and the pack + dropped ares's own dump behind the platform's.""" + + def test_no_conflict_names_ares(self): + import json + + from scripts.packs import slotscan + from scripts.model.registry import list_registered_platforms + from scripts.model.profiles import load_emulator_profiles + + root = ROOT + if not (root / "database.json").exists(): + self.skipTest("database.json is not built") + profiles = load_emulator_profiles(str(root / "emulators")) + db = json.loads((root / "database.json").read_text(encoding="utf-8")) + claimed = [ + (platform, conflict.destination) + for platform in list_registered_platforms(str(root / "platforms")) + for conflict in slotscan.scan_platform(platform, profiles, db, str(root / "platforms")) + if any(claim.emulator == "ares" for claim in conflict.profile_claims) + ] + self.assertEqual(claimed, []) + + +class FsUaeKickstartIsFoundByContent(unittest.TestCase): + """FS-UAE scans its Kickstarts directory and names a ROM by checksum + (src/fs-uae/config.c:121-140, main.c:431-470), and with no ROM loads the + AROS replacement (memory.cpp:2374-2379). kick13.rom and its required + flag came from the RetroPie launcher, which the platform layer records.""" + + def test_the_kickstart_is_an_optional_label(self): + from scripts.resolve.entryscope import opens_by_name + + profile = yaml.safe_load((ROOT / "emulators" / "fs-uae.yml").read_text(encoding="utf-8")) + entry = next(f for f in profile["files"] if f.get("sha1") == "891e9a547772fe0c6c19b610baf8bc4ea7fcb785") + self.assertFalse(opens_by_name(entry, profile, standalone=True)) + self.assertFalse(entry.get("required")) + self.assertNotIn("RetroPie launcher", entry.get("note", "")) + + +class NoProfileHashFromASecondarySource(unittest.TestCase): + """ecwolf.yml pinned ecwolf.pk3 to an md5 its note said came from the + .info. The code checks none, and no file shipped at the pin carries it: + a source without a hash gives the profile none.""" + + PATTERN = re.compile( + r"(md5|sha1|crc32|hash)[^.]{0,40}\bfrom (the )?(\.info|core-?info|docs?|documentation)", + re.IGNORECASE, + ) + + def test_no_hashed_entry_names_a_secondary_source(self): + found = [] + for path in sorted((ROOT / "emulators").glob("*.yml")): + profile = yaml.safe_load(path.read_text(encoding="utf-8")) or {} + for entry in profile.get("files") or []: + if not isinstance(entry, dict): + continue + if any(entry.get(k) for k in ("md5", "sha1", "crc32", "sha256")) and ( + self.PATTERN.search(str(entry.get("note", ""))) + ): + found.append(f"{path.name}: {entry.get('name')}") + self.assertEqual(found, []) + + +class XeniosFollowsItsReleaseBranch(unittest.TestCase): + """The xenios pin 87b176a0 sat on `preview`, which diverged from the + default `xenios` branch, and without source_branch profile_sync read the + pin as orphaned. Since November 2026 the releases (2.2 to 2.3.1) come from + `xenios` and `preview` stopped in June: the pin is release 2.3.1 on the + default branch, so the profile names no other branch.""" + + def test_the_profile_follows_the_branch_its_pin_is_on(self): + profile = yaml.safe_load((ROOT / "emulators" / "xenios.yml").read_text(encoding="utf-8")) + self.assertIn(profile.get("source_branch"), (None, "xenios")) + self.assertEqual(profile["source_commit"][:7], "cf7c7ee") + + +class PcemUpstreamPinIsTheLastSync(unittest.TestCase): + """The pcem bump set upstream_commit to dev's HEAD 25b54e3f, and dev was + rewritten: the pin left every branch (compare: diverged 109/114). The + port shares no history with upstream and took mainline patches by hand + until 2016-04-13, whose last upstream commit is 10739b96. Held there, a + bump cannot move it to a HEAD the port never contained.""" + + def test_the_upstream_pin_is_held_at_the_last_sync(self): + profile = yaml.safe_load((ROOT / "emulators" / "pcem.yml").read_text(encoding="utf-8")) + self.assertEqual(profile["upstream_commit"], "10739b9618e388a5bf8c21e752f12b3952fa83e1") + self.assertTrue(profile.get("upstream_frozen")) + + +class AHashScanLabelNamesNoOtherDump(unittest.TestCase): + """A core that finds its firmware by content names no file, so each + entry name is a label. ares labelled its Famicom Disk System revision + (RP2C33-01, crc32 1c7ae5d5) disksys.rom, the name six NES cores read for + the RP2C33A-01A dump: on ROCKNIX the manifest put ares's revision at + disksys.rom for all of them. A label that another profile gives a + different dump is refused, the two dumps compared through the + collection's hash indexes.""" + + # Names the core's own code gives the image, not labels. + CODE_NAMED = { + ("bizhawk", "MSX.rom"): + "FirmwareDatabase.cs:362 names the image MSX.rom", + ("swanstation", "ps1_rom.bin"): + "the whole PS3 image is the file the PS3 itself names ps1_rom.bin, " + "beetle_psx reads its first 512 KB under the same name", + ("duckstation-legacy", "ps1_rom.bin"): + "the same whole PS3 image, whose first 512 KB src/core/bios.cpp:89 hashes", + ("openmsx", "COLECO.ROM"): + "share/machines/ColecoVision_SGM.xml:56 names it, tried beside the machine XML", + ("openmsx", "fmpac.rom"): + "share/machines/Boosted_MSX2_EN.xml:83 names it, tried beside the machine XML", + ("openmsx-libretro", "rs232.rom"): + "share/extensions/rs232.xml:18-22 names it, tried beside the extension XML", + } + + @staticmethod + def _identity(entry: dict, db: dict) -> tuple[set, set]: + raw: set = set() + sha1s: set = set() + indexes = db["indexes"] + for field, index in (("sha1", None), ("md5", "by_md5"), + ("crc32", "by_crc32"), ("sha256", "by_sha256")): + value = entry.get(field) + values = value if isinstance(value, list) else [value] if value else [] + for item in values: + for digest in str(item).lower().split(","): + digest = digest.strip() + if not digest: + continue + raw.add((field, digest)) + sha1 = digest if index is None else indexes[index].get(digest) + if sha1 in db["files"]: + sha1s.add(sha1) + return raw, sha1s + + def test_labels_are_not_other_dumps_names(self): + import json + + from scripts.model.profiles import load_emulator_profiles + + if not (ROOT / "database.json").exists(): + self.skipTest("database.json is not built") + db = json.loads((ROOT / "database.json").read_text(encoding="utf-8")) + profiles = load_emulator_profiles(str(ROOT / "emulators")) + by_name: dict[str, list[tuple[str, dict]]] = {} + for emulator, profile in profiles.items(): + for entry in profile.get("files") or []: + for name in [entry.get("name"), *(entry.get("aliases") or [])]: + if name: + by_name.setdefault(str(name).casefold(), []).append((emulator, entry)) + clashes = [] + for emulator, profile in profiles.items(): + if profile.get("found_by") != "content": + continue + for entry in profile.get("files") or []: + raw, sha1s = self._identity(entry, db) + if not sha1s: + continue + for name in [entry.get("name"), *(entry.get("aliases") or [])]: + if (emulator, name) in self.CODE_NAMED: + continue + for other, other_entry in by_name.get(str(name).casefold(), []): + if other == emulator: + continue + other_raw, other_sha1s = self._identity(other_entry, db) + if other_sha1s and not raw & other_raw and not sha1s & other_sha1s: + clashes.append(f"{emulator} {name} is {other}'s name for another dump") + self.assertEqual(sorted(set(clashes)), []) + + +class ANoteOutsideTheSystemDirCarriesLoadFrom(unittest.TestCase): + """mame2000 opens hiscore.dat, history.dat and mameinfo.dat from the + directory of the loaded content (src/libretro/fileio.c:1002-1014), and + mame2014 and mame2015 open hiscore.dat from the working directory + (src/emu/hiscore.c:330-337). Their notes said so, but no load_from did: + the entries claimed system/hiscore.dat and the RetroArch pack shipped a + file neither core opens there. A libretro entry whose note places the + read outside the system directory declares where.""" + + ELSEWHERE = re.compile( + r"\b(?:opened|read|loaded)\b[^.]*?\bfrom (?:the )?(?:working directory|" + r"ROM directory|content directory|directory of the loaded content)" + r"|IMAMEBASEPATH", + re.IGNORECASE, + ) + + def test_prose_and_load_from_agree(self): + offenders = [] + for path in sorted((ROOT / "emulators").glob("*.yml")): + profile = yaml.safe_load(path.read_text(encoding="utf-8")) or {} + if profile.get("type") != "libretro": + continue + for entry in profile.get("files") or []: + if entry.get("path") or entry.get("load_from") or entry.get("mode") == "standalone": + continue + if self.ELSEWHERE.search(str(entry.get("note") or "")): + offenders.append(f"{path.name}: {entry.get('name')}") + self.assertEqual(offenders, []) + + +class TheTreeKeepsStandaloneEntries(unittest.TestCase): + """With no platform named, the gap report laid every dual profile out as + libretro only: eka2l1, dolphin and xenia-edge lost 133 files that + Batocera and RetroBat run standalone and no platform declares.""" + + def test_a_standalone_only_entry_is_reported(self): + if not (ROOT / "database.json").exists(): + self.skipTest("database.json is not built") + out = subprocess.run( + [sys.executable, "scripts/cross_reference.py", "--emulator", "eka2l1"], + cwd=ROOT, capture_output=True, text=True, timeout=600, check=True, + ).stdout + undeclared = re.search(r"(\d+) undeclared", out) + self.assertIsNotNone(undeclared, out[-500:]) + self.assertGreater(int(undeclared.group(1)), 0) + + +class TheCliSetsBundledFilesApart(unittest.TestCase): + """cross_reference counted daedalusx64's n64.psh and touchHLE's runtime + libraries as missing, to be sourced, though the project leaves them out + by design and verify and the gaps page already say so.""" + + def test_a_bundled_gap_is_not_missing(self): + from scripts.packs.crossreftext import print_report + + gap = {"name": "n64.psh", "required": True, "bundled": True, "note": "", + "source": "missing"} + report = {"emu": { + "emulator": "Emu", "systems": [], "total_files": 1, "platform_covered": 0, + "gaps": 1, "gap_missing": 1, "gap_details": [gap], + }} + out = io.StringIO() + with contextlib.redirect_stdout(out): + print_report(report) + text = out.getvalue() + self.assertIn("0 missing (need to be sourced)", text) + self.assertIn("1 bundled with their emulator", text) + self.assertIn("n64.psh [BUNDLED]", text) + + +class WhatOnlyAnInstallProvidesIsListed(unittest.TestCase): + """A file installed with its emulator is already on the user's machine. + A copy nothing else asks for is dead weight in the collection.""" + + def test_only_the_bundled_only_copy_is_listed(self): + import tempfile + + from packs import bundledonly + + with tempfile.TemporaryDirectory() as tmp, \ + mock.patch.object(bundledonly, "list_registered_platforms", return_value=[]): + def entry(sha1, name): + path = Path(tmp, name) + path.write_bytes(name.encode()) + return {"path": str(path), "name": name, "sha1": sha1, + "md5": sha1[:32], "size": path.stat().st_size} + + db = {"bios_dir": tmp, + "files": {"a" * 40: entry("a" * 40, "icon.png"), + "b" * 40: entry("b" * 40, "bios.rom")}, + "indexes": {"by_name": {"icon.png": ["a" * 40], "bios.rom": ["b" * 40]}, + "by_md5": {}, "by_crc32": {}, "by_sha256": {}, + "by_path_suffix": {}}} + profiles = { + "app": {"files": [{"name": "icon.png", "sha1": "a" * 40, "bundled": True}, + {"name": "bios.rom", "sha1": "b" * 40, "bundled": True}]}, + "core": {"files": [{"name": "bios.rom", "sha1": "b" * 40}]}, + } + rows = bundledonly.bundled_only(db, profiles, tmp, Path(tmp)) + self.assertEqual([row["path"] for row in rows], [str(Path(tmp, "icon.png"))]) + # A platform whose package leaves the file out brings it from the + # collection: the copy stays. + profiles["app"]["files"][0]["not_bundled_on"] = ["someplatform"] + self.assertEqual(bundledonly.bundled_only(db, profiles, tmp, Path(tmp)), []) + + def test_every_copy_of_the_listed_bytes_is_listed(self): + """The database keeps one path per content: splitwolf's sprite + folders hold one file several times and took five passes to empty.""" + import hashlib + import tempfile + + from packs import bundledonly + + with tempfile.TemporaryDirectory() as tmp: + for name in ("dir1/a.bmp", "dir2/a.bmp", "dir2/b.bmp"): + Path(tmp, name).parent.mkdir(exist_ok=True) + Path(tmp, name).write_bytes(b"same" if "a.bmp" in name else b"diff") + sha1 = hashlib.sha1(b"same").hexdigest() + row = {"sha1": sha1, "path": Path(tmp, "dir1/a.bmp").as_posix(), "size": 4, + "emulators": ["splitwolf"]} + copies = bundledonly.other_copies([row], Path(tmp)) + self.assertEqual([c["path"] for c in copies], [Path(tmp, "dir2/a.bmp").as_posix()]) + + def test_the_collection_holds_no_copy_only_an_install_provides(self): + """The pull request checks run this suite, not the pipeline: without + this, a copy only a bundled entry reaches merges green.""" + from packs import bundledonly + from model.database import load_database + from model.profiles import load_emulator_profiles + + rows = bundledonly.bundled_only( + load_database(str(ROOT / "database.json")), + load_emulator_profiles(str(ROOT / "emulators")), + str(ROOT / "platforms"), ROOT / "install", + ) + self.assertEqual([f"{r['path']} ({', '.join(r['emulators'])})" for r in rows], [], + "remove the copy: the emulator's own install provides it") + + +class AFileTheLauncherNeverOpens(unittest.TestCase): + """RetroBat hands standalone BlastEm absolute paths to its own BIOS + names, so the defaults the emulator would read (cdbios.bin) were listed + as required and missing on RetroBat although nothing there opens them.""" + + def test_unread_on_drops_the_entry_for_that_platform_only(self): + from resolve.entryscope import deliverable, unread_on + + entry = {"name": "cdbios.bin", "unread_on": ["retrobat"]} + self.assertTrue(unread_on(entry, "retrobat")) + self.assertFalse(unread_on(entry, "batocera")) + self.assertFalse(unread_on(entry, "")) + self.assertEqual(deliverable([entry], True, "retrobat"), []) + self.assertEqual(deliverable([entry], True, "batocera"), [entry]) + + def test_the_gap_report_reads_it(self): + source = script_source("verify.py") + self.assertIn('unread_on(f, config.get("_key", ""))', source) + + +class AmigaCdDriversLiveInTheExtendedRom(unittest.TestCase): + """WinUAE starts without the CD32 or CDTV extended ROM, but cd.device, + cdtv.device, cdfs.library and cdstrap are resident modules of those ROMs + and the Kickstarts carry none. Its AROS replacement stands in only for a + missing Kickstart (memory.cpp:3055-3063), so the CDTV ROM has no + fallback to downgrade its absence.""" + + def test_both_extended_roms_are_required_without_fallback(self): + profile = yaml.safe_load( + (ROOT / "emulators" / "winuae.yml").read_text(encoding="utf-8") + ) + entries = {f["name"]: f for f in profile["files"]} + for name in ("amiga-ext-310-cd32.rom", "amiga-ext-130-cdtv.rom"): + with self.subTest(name=name): + self.assertIs(entries[name]["required"], True) + self.assertNotIn("hle_fallback", entries[name]) + + +class BizHawkListsEveryDsiNandSlot(unittest.TestCase): + """FirmwareDatabase.cs:405-410 declares six DSi NAND slots, each a + placeholder hash and 251658240 + 64 bytes, and DecideNAND + (MelonDS.cs:684-706) stops a DSi load when none is set. The profile + listed DSi_Firmware.bin, a placeholder slot of the same kind, and left + the NANDs out.""" + + def test_the_six_regional_nands_are_declared(self): + profile = yaml.safe_load( + (ROOT / "emulators" / "bizhawk.yml").read_text(encoding="utf-8") + ) + entries = {f["name"]: f for f in profile["files"]} + for region_code in ("JPN", "EUR", "USA", "AUS", "CHN", "KOR"): + with self.subTest(region=region_code): + entry = entries[f"DSi_Nand_{region_code}.bin"] + self.assertEqual(entry["size"], 251658240 + 64) + self.assertIs(entry["required"], False) + self.assertNotIn("sha1", entry) + + +class HiganSuperGameBoyFolderIsFree(unittest.TestCase): + """higan reads program.rom in the option's folder, SGB.sfc/, then Super + GameBoy.sfc/. bsnes, Mesen-S and ares read SGB1.sfc and SGB2.sfc as files + in the same system directory, and SuperSnes9x sgb.sfc, so a pack that only + had the first two folders never gave the higan cores a Super Game Boy.""" + + def test_each_higan_core_has_a_folder_no_core_reads_as_a_file(self): + import yaml + + file_names: set[str] = set() + for path in (ROOT / "emulators").glob("*.yml"): + document = yaml.safe_load(path.read_text(encoding="utf-8")) or {} + for entry in document.get("files") or []: + for name in [entry.get("name"), *(entry.get("aliases") or [])]: + if name: + file_names.add(str(name).casefold()) + if entry.get("path"): + file_names.add(str(entry["path"]).casefold()) + for profile in ("higan_sfc", "higan_sfc_balanced"): + document = yaml.safe_load( + (ROOT / "emulators" / f"{profile}.yml").read_text(encoding="utf-8") + ) + folders = { + str(entry["path"]).split("/", 1)[0] + for entry in document["files"] + if str(entry.get("path") or "").endswith("/program.rom") + and entry.get("system") == "nintendo-sgb" + } + with self.subTest(profile=profile): + self.assertTrue( + [f for f in folders if f.casefold() not in file_names], folders + ) + + +class ProfileNotesDescribeTheCoreAlone(unittest.TestCase): + """mednafen_pce_fast, sdlpop and x64sdl described the core by what + another profile of this directory does ("unlike beetle_pce", "unlike the + other engines in this directory"), which means nothing once the profile + is read on its own, and 21 lines shouted NOT, ALL or MUST.""" + + SHOUT = re.compile(r"\b(NOT|NEVER|ONLY|MUST|ALL|DIFFERENT)\b(?! FOUND)") + + def test_no_profile_shouts_or_compares_with_another_profile(self): + names = {path.stem.casefold() for path in (ROOT / "emulators").glob("*.yml")} + names |= {name.replace("_", "-") for name in names} + found = [] + for path in sorted((ROOT / "emulators").glob("*.yml")): + text = path.read_text(encoding="utf-8") + for number, line in enumerate(text.splitlines(), 1): + if self.SHOUT.search(line): + found.append(f"{path.stem}:{number}") + found.extend( + f"{path.stem}:{number}" + for match in re.finditer(r"\bunlike (?:the )?([\w+-]+)", line, re.I) + if match.group(1).casefold() in names + ) + self.assertEqual(found, []) + + +class Ps2BiosImagesAreFoundByContent(unittest.TestCase): + """PCSX2 and its forks scan the BIOS folder and keep the first 4 to 8 MB + image with a romdir (pcsx2/ps2/BiosTools.cpp:258-282 at f0523f8a). With + no found_by the label ps2-0230a-20080220.bin read as a name the core + opens, and the RetroDECK export added it as a required file.""" + + def test_every_ps2_image_scan_is_marked(self): + """ARMSX2's arcade scan takes 2 to 8 MB COH-H images by their EXTINFO + serial (BiosTools.cpp:366-419 at 7f914418): r27v1602f.8g read as a + name armsx2 opens on six platforms.""" + import yaml + + from resolve.entryscope import opens_by_name + + named = [] + for path in sorted((ROOT / "emulators").glob("*.yml")): + profile = yaml.safe_load(path.read_text(encoding="utf-8")) or {} + # Whatever the profile's own flags: TeknoParrot documents its + # pcsx2x6 component, whose scan is the same (BiosTools.cpp:268-291 + # at 583f0e90), and carries no agnostic flag. + named.extend( + f"{path.stem}: {entry['name']}" + for entry in profile.get("files") or [] + if ( + entry.get("min_size") in (2097152, 4194304) + and entry.get("max_size") == 8388608 + and opens_by_name(entry, profile) + ) + ) + self.assertEqual(named, []) + + +class SynthRomsAreFoundByContent(unittest.TestCase): + """dosbox-staging's libmt32emu scan identifies each file of the ROM + folder with identifyROMFile (src/midi/mt32_lasynth_model.cpp:68-91 at + fa1856c0), and the Sound Canvas plugin hashes its model folder + (Nuked-SC55-CLAP, RomLoader::Hashing). The truth read the labels as + names dosbox-staging opens, and MT32_CONTROL.ROM did not count.""" + + def test_every_synth_rom_is_marked(self): + import yaml + + from resolve.entryscope import opens_by_name + + profile = yaml.safe_load( + (ROOT / "emulators" / "dosbox-staging.yml").read_text(encoding="utf-8") + ) + named = [ + entry["name"] + for entry in profile["files"] + if str(entry.get("path", "")).startswith(("mt32-roms/", "soundcanvas-roms/")) + and opens_by_name(entry, profile) + ] + self.assertEqual(named, []) + + +class Dev9FilesAreReadFromTheWorkingDirectory(unittest.TestCase): + """DEV9 opens eeprom.dat and flash.dat by bare name (PCSX2 + pcsx2/DEV9/DEV9.cpp:144, AetherSX2 DEV9/flash.cpp:89): the working + directory, never the BIOS folder. Eight profiles left load_from unset, + so the file was packed into the BIOS folder, where nothing reads it.""" + + def test_every_dev9_file_names_the_working_directory(self): + import yaml + + unset = [] + for path in sorted((ROOT / "emulators").glob("*.yml")): + profile = yaml.safe_load(path.read_text(encoding="utf-8")) or {} + unset.extend( + f"{path.stem}: {entry['name']}" + for entry in profile.get("files") or [] + if ( + entry.get("name") in ("eeprom.dat", "flash.dat") + and "DEV9" in str(entry.get("source_ref")) + and entry.get("load_from") != "working_directory" + ) + ) + self.assertEqual(unset, []) + + +class OpenMsxSystemRomsAreFoundBySha1(unittest.TestCase): + """openMSX reaches a ROM in share/systemroms through the file pool by + SHA1 alone, a filename being looked up only beside the machine's XML + (src/memory/Rom.cc:121-170). Read as names the core opens, the labels + were added to the KNULLI and Batocera exports.""" + + def test_no_systemrom_label_reads_as_a_name(self): + import yaml + + from resolve.entryscope import opens_by_name + + profile = yaml.safe_load((ROOT / "emulators" / "openmsx.yml").read_text()) + named = [ + entry["name"] for entry in profile["files"] + if "share/systemroms/" in str(entry.get("path")) + and opens_by_name(entry, profile) + ] + self.assertEqual(named, []) + + +class PrboomPlusCitesFullPaths(unittest.TestCase): + """prboom-plus cited gl_hires.c, e6y.c, d_client.c and g_game.c bare: + none resolves against the repository, so the page showed them as plain + code with no link, and "behind GL_DOOM and PRBOOM_DEBUG" was read as a + seventeenth citation. Each name has one path in the tree at the pin.""" + + def test_every_cited_file_has_its_directory(self): + import yaml + + from scripts.model.sourceref import source_ref_values, split_source_ref + + profile = yaml.safe_load((ROOT / "emulators" / "prboom-plus.yml").read_text(encoding="utf-8")) + refs: list[str] = [] + + def walk(node): + if isinstance(node, dict): + for key, value in node.items(): + if key == "source_ref": + refs.extend(r for _, r in source_ref_values(value)) + else: + walk(value) + elif isinstance(node, list): + for item in node: + walk(item) + + walk(profile) + parts = [p for ref in refs for p in split_source_ref(ref)] + self.assertGreater(len(parts), 40) + for part in parts: + with self.subTest(path=part.path): + self.assertIsNotNone(part.start) + self.assertTrue(part.path.startswith("prboom2/"), part.path) + + +class EveryReaderOfACoreFileIsNamed(unittest.TestCase): + """A requirement two cores read is reported once, the first profile + hosting the others' claims. Whatever drops the host must not drop the + claims with it.""" + + def test_a_host_its_emulator_installs_leaves_the_others_in_the_pack(self): + from packs.gaps import _split_bundled_claims + + dsperate = {"profile": "dsperate", "name": "usrcheat.dat", "in_repo": True} + drastic = {"profile": "drastic", "name": "usrcheat.dat", "bundled": True, + "in_repo": True, "other_claims": [dsperate]} + out = _split_bundled_claims([drastic]) + self.assertEqual([(u["profile"], u.get("other_claims")) for u in out], + [("drastic", None), ("dsperate", None)]) + alone = {"profile": "drastic", "bundled": True, "other_claims": [ + {"profile": "drastic-legacy", "bundled": True}]} + self.assertEqual(_split_bundled_claims([alone]), [alone]) + + def test_a_held_file_out_of_reach_names_every_core_reading_it(self): + """harm1.wad is a release asset: a checkout without it omits the file, + and the omission named gzdoom alone where lzdoom reads it too.""" + from packs.manifestentry import claim_cores + + extra = {"source_profile": "gzdoom", "other_claims": [ + {"source_profile": "uzdoom"}, {"source_profile": "lzdoom"}]} + self.assertEqual(claim_cores(extra), ["gzdoom", "lzdoom", "uzdoom"]) + + def test_a_missing_file_names_every_core_reading_it(self): + from packs.manifestentry import record_absent + + omitted: dict[str, dict] = {} + + def record(full_dest, entry, system, reason, cores): + omitted[full_dest] = {"dest": full_dest, "reason": reason, "cores": cores} + + absent = [ + {"name": "NAPALM.GRP", "destination": "NAPALM.GRP", "source_profile": profile, + "source_system": system} + for profile, system in (("raze", "nam"), ("eduke32", "napalm")) + ] + platform = {"dest": "SHARED.BIN", "reason": "not_found", "cores": None} + omitted["SHARED.BIN"] = platform + absent.append({"name": "SHARED.BIN", "destination": "SHARED.BIN", + "source_profile": "raze"}) + record_absent(absent, {}, "", set(), False, set(), omitted, record) + self.assertEqual(omitted["NAPALM.GRP"]["cores"], ["eduke32", "raze"]) + # A platform's own omission stays the platform's. + self.assertIsNone(omitted["SHARED.BIN"]["cores"]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_audit_project.py b/tests/test_audit_project.py new file mode 100644 index 000000000..d21ff80cd --- /dev/null +++ b/tests/test_audit_project.py @@ -0,0 +1,1206 @@ +"""Audit regressions on the project itself: workflows, test isolation, dependencies and code rules.""" + +from __future__ import annotations + +import tests +from tests.sources import script_source +import ast +import hashlib +import json +import os +import re +import subprocess +import sys +import tempfile +import unittest +from pathlib import Path +from unittest import mock +import yaml +from tests.auditsupport import HAS_JSONSCHEMA, ROOT, jsonschema + + +class AModuleRunAloneHasItsScratchDirectory(unittest.TestCase): + """About forty modules write under tmp/, which git does not track. Only + three created it, as an import side effect, so a module run alone on a + fresh clone raised FileNotFoundError. The test package creates it.""" + + def test_importing_the_package_creates_tmp(self): + with tempfile.TemporaryDirectory() as directory: + clone = Path(directory) + (clone / "tests").mkdir() + (clone / "tests" / "__init__.py").write_bytes( + (ROOT / "tests" / "__init__.py").read_bytes() + ) + # The folder a module gets alone, not the one scripts/run_tests.py + # names for each module it runs beside others. + env = {k: v for k, v in os.environ.items() if k != "RETROBIOS_TEST_SCRATCH"} + proc = subprocess.run( + [sys.executable, "-I", "-c", + "import sys; sys.path.insert(0, '.'); import tests, tempfile, os;" + " print(tempfile.gettempdir()); print(os.environ['TMPDIR'])"], + cwd=clone, env=env, capture_output=True, text=True, timeout=60, check=False, + ) + self.assertEqual(proc.returncode, 0, proc.stderr) + self.assertTrue((clone / "tmp" / "tests").is_dir()) + # 264 TemporaryDirectory() calls without dir= wrote to the /tmp + # tmpfs, and a full tmpfs failed modules no change touched. + scratch = str((clone / "tmp" / "tests").resolve()) + self.assertEqual(proc.stdout.split(), [scratch, scratch]) + + +class EveryTestModuleImportsTheIsolation(unittest.TestCase): + """tests/__init__.py keeps a run offline, its scratch under tmp/ and its + installer cache its own, but only `discover -s tests -t .` imported it: + `discover tests` ran with RETROBIOS_OFFLINE unset, scratch in /tmp and + the user's real cache. Each module now imports the package first.""" + + def test_the_package_import_comes_before_any_other(self): + missing = [] + for path in sorted((ROOT / "tests").glob("test_*.py")): + body = ast.parse(path.read_text(encoding="utf-8")).body + imports = [ + node for node in body + if isinstance(node, (ast.Import, ast.ImportFrom)) + and getattr(node, "module", None) != "__future__" + ] + first = imports[0] if imports else None + if not (isinstance(first, ast.Import) + and [alias.name for alias in first.names] == ["tests"]): + missing.append(path.name) + self.assertEqual(missing, []) + + def test_discover_without_a_top_level_runs_isolated(self): + env = {k: v for k, v in os.environ.items() + if k not in ("RETROBIOS_OFFLINE", "TMPDIR", "RETROBIOS_CACHE", + "RETROBIOS_TEST_SCRATCH")} + proc = subprocess.run( + [sys.executable, "-c", + "import os, sys, tempfile, unittest\n" + "unittest.TestLoader().discover('tests', pattern='test_artifact_lock.py')\n" + "print(os.environ.get('RETROBIOS_OFFLINE'), tempfile.gettempdir()," + " os.environ.get('RETROBIOS_CACHE'))\n"], + cwd=ROOT, env=env, capture_output=True, text=True, timeout=120, + check=False, + ) + self.assertEqual(proc.returncode, 0, proc.stderr) + offline, scratch, cache = proc.stdout.split() + self.assertEqual(offline, "1") + self.assertEqual(scratch, str(ROOT / "tmp" / "tests")) + self.assertEqual(cache, str(ROOT / "tmp" / "tests" / "cache")) + + +class ReleaseSigningRegressions(unittest.TestCase): + """A checksum list published beside its own artifacts proves nothing. + + SHA256SUMS.txt answers corruption, but whoever can rewrite a release rewrites + the list with it. The signature is what a third party checks, and it is + only checkable while allowed_signers, the signing step and the upload + list stay in agreement. + """ + + PRINCIPAL = "releases@retrobios" + + def test_allowed_signers_names_one_usable_key(self): + path = ROOT / "allowed_signers" + self.assertTrue(path.exists(), "allowed_signers is the published trust root") + lines = [ + line for line in path.read_text(encoding="utf-8").splitlines() + if line.strip() and not line.startswith("#") + ] + self.assertTrue(lines, "allowed_signers carries no key") + for line in lines: + principal, keytype, blob = line.split()[:3] + self.assertEqual(principal, self.PRINCIPAL) + self.assertTrue(keytype.startswith(("ssh-", "sk-", "ecdsa-")), keytype) + self.assertTrue(len(blob) > 40, "key material looks truncated") + + def test_the_release_signs_the_list_and_ships_the_signature(self): + process = (ROOT / "wiki" / "release-process.md").read_text(encoding="utf-8") + self.assertIn( + "ssh-keygen -Y sign", process, "the release no longer signs the list" + ) + upload = next( + line for line in process.splitlines() + if line.startswith("for f in dist/SHA256SUMS.txt") + ) + self.assertIn( + "dist/SHA256SUMS.txt.sig", upload, + "the signature is produced but never uploaded", + ) + + def test_the_documented_verification_matches_the_published_principal(self): + process = (ROOT / "wiki" / "release-process.md").read_text(encoding="utf-8") + self.assertIn("ssh-keygen -Y verify", process) + self.assertIn(f"-I {self.PRINCIPAL}", process) + self.assertIn("allowed_signers", process) + + +class WorkflowRegressions(unittest.TestCase): + """The test suite must sit on every road into main. + + run-tests lived in a pull_request-only workflow while the work landed by + direct push, so 1,318 cases guarded a road almost nothing took. What is + asserted here is reachability, not the workflow's shape. + """ + + @staticmethod + def _workflow(name: str) -> dict: + with (ROOT / ".github" / "workflows" / name).open(encoding="utf-8") as f: + document = yaml.safe_load(f) + # PyYAML resolves the bare `on:` key to the boolean True. + document["on"] = document.pop(True, document.get("on")) + return document + + def test_no_validation_step_discards_its_exit_code(self): + """A check whose result is thrown away is not a check. + + The BIOS validation step ended in `|| true`, so validate_pr.py could + exit 1 on a file that failed its hash and the job stayed green. The + report still has to reach the pull request, so the code is recorded + and acted on afterwards rather than swallowed. A best-effort side + action such as adding a label is not a check and keeps its `|| true`. + """ + checks = ("python scripts/", "unittest", "npm run build") + for name in ("validate.yml", "deploy-site.yml"): + workflow = self._workflow(name) + for job_name, job in workflow["jobs"].items(): + for step in job.get("steps", []): + # A shell continuation puts the command and its `|| true` + # on different lines, so they are rejoined before scanning. + body = str(step.get("run", "")).replace("\\\n", " ") + for line in body.splitlines(): + if not any(marker in line for marker in checks): + continue + self.assertNotIn( + "|| true", + line, + f"{name}:{job_name}:{step.get('name', '?')} runs a " + f"check and discards its exit code: {line.strip()}", + ) + + workflow = self._workflow("validate.yml") + steps = workflow["jobs"]["validate-bios"]["steps"] + gate = [s for s in steps if "rc != " in str(s.get("if", ""))] + self.assertTrue( + gate, + "nothing in validate-bios acts on the validation exit code", + ) + + def test_the_suite_runs_on_a_direct_push_to_main(self): + workflow = self._workflow("validate.yml") + triggers = workflow["on"] + self.assertIn("push", triggers, "validate.yml no longer runs on push") + self.assertIn("main", triggers["push"]["branches"]) + job = next( + ( + name + for name, body in workflow["jobs"].items() + if any( + "scripts/run_tests.py" in str(step.get("run", "")) + for step in body.get("steps", []) + ) + ), + None, + ) + self.assertIsNotNone(job, "no job runs the test suite") + self.assertIsNone( + workflow["jobs"][job].get("if"), + f"{job} carries a condition, but the suite must run on push and on PR", + ) + + def test_added_profiles_meet_their_upstream_on_both_roads(self): + """A new profile's refs were confronted only if its author remembered.""" + workflow = self._workflow("validate.yml") + runs = [ + (name, str(step.get("run", ""))) + for name, body in workflow["jobs"].items() + for step in body.get("steps", []) + if "profile_sync.py" in str(step.get("run", "")) + ] + self.assertTrue(runs, "no job confronts profiles with their upstream") + for name, body in runs: + self.assertIn("--strict", body) + self.assertIn("--added", body) + self.assertIsNone(workflow["jobs"][name].get("if"), f"{name} must run on push too") + + def test_both_events_watch_the_same_paths(self): + triggers = self._workflow("validate.yml")["on"] + self.assertEqual( + triggers["pull_request"]["paths"], + triggers["push"]["paths"], + "the two path lists have drifted, so a push would skip what a PR checks", + ) + + def test_pull_request_only_jobs_are_guarded(self): + workflow = self._workflow("validate.yml") + for name, body in workflow["jobs"].items(): + uses_pr_context = "github.event.pull_request" in yaml.dump(body) + if uses_pr_context: + self.assertEqual( + body.get("if"), + "github.event_name == 'pull_request'", + f"{name} reads pull request context and would run on a push", + ) + + def test_no_workflow_relies_on_a_yaml_anchor(self): + """The workflow parser reads no anchor, and PyYAML would hide the break.""" + for path in sorted((ROOT / ".github" / "workflows").glob("*.yml")): + for number, line in enumerate( + path.read_text(encoding="utf-8").splitlines(), 1 + ): + self.assertIsNone( + re.search(r"(?:^|\s)[&*][A-Za-z_]", line), + f"{path.name}:{number} uses a YAML anchor: {line.strip()}", + ) + + +class PatchesTargetWhatRuns(unittest.TestCase): + """mock.patch.object with create set to True builds an attribute on a + module when the name is missing: packextras imported resolve_platform_cores + inside the function, the patch created a global nobody read, and the + real function walked the repository while the test claimed to isolate + it.""" + + def test_no_test_creates_the_attribute_it_patches(self): + needle = "create" + "=True" + offenders = [] + for path in sorted((ROOT / "tests").glob("test_*.py")): + for number, line in enumerate(path.read_text(encoding="utf-8").splitlines(), 1): + code = line.split("#", 1)[0] + if needle in code: + offenders.append(f"{path.name}:{number}") + self.assertEqual(offenders, []) + + +class NoParserAcceptsAnAbbreviation(unittest.TestCase): + """argparse completes a prefix: `slots.py --emulator dolphin` became + --emulators-dir dolphin and reported 0 contested destinations, exit 0, and + `pipeline.py --all` became --all-variants and built six packs per + platform. The flags read like other scripts' and were never refused.""" + + def test_every_parser_refuses_prefixes(self): + import ast + + lax = [] + for path in sorted([*(ROOT / "scripts").rglob("*.py"), ROOT / "install.py"]): + for node in ast.walk(ast.parse(path.read_text(encoding="utf-8"))): + if not isinstance(node, ast.Call): + continue + func = node.func + name = func.attr if isinstance(func, ast.Attribute) else getattr(func, "id", "") + if name != "ArgumentParser": + continue + if not any( + kw.arg == "allow_abbrev" + and isinstance(kw.value, ast.Constant) and kw.value.value is False + for kw in node.keywords + ): + lax.append(f"{path.relative_to(ROOT)}:{node.lineno}") + self.assertEqual(lax, []) + + +class SchemaFormatsAreChecked(unittest.TestCase): + """date-time and uri need jsonschema's format extras. Without them the + published format constraints were accepted unread.""" + + @unittest.skipUnless(HAS_JSONSCHEMA, "validating a schema needs jsonschema") + def test_a_missing_checker_is_named(self): + from schemas import validators + + empty = mock.Mock(checkers={}) + with mock.patch.object(validators, "FormatChecker", return_value=empty): + self.assertEqual(validators.unchecked_formats(), ["date-time", "uri"]) + + def test_every_install_asks_for_the_extras(self): + for path in (".github/workflows/validate.yml", ".github/workflows/deploy-site.yml", + "pyproject.toml"): + text = (ROOT / path).read_text(encoding="utf-8") + with self.subTest(path=path): + self.assertNotRegex(text, r"jsonschema(?!\[format)[=>]") + + +class CheckoutCompletenessRegressions(unittest.TestCase): + """Coverage is resolved against the disk, so the checkout must be whole. + + Files over 50 MB and the data directory caches are gitignored. A job that + regenerates the README or the site without restoring them counts those + files as missing and publishes a coverage the collection does not have. + """ + + def _steps(self, workflow: str, job: str) -> list[dict]: + data = yaml.safe_load((ROOT / ".github" / "workflows" / workflow).read_text()) + return data["jobs"][job]["steps"] + + def _index(self, steps: list[dict], needle: str) -> int: + for position, step in enumerate(steps): + if needle in step.get("name", "") or needle in str(step.get("run", "")): + return position + raise self.failureException(f"no step matching {needle!r}") + + def test_site_deploy_completes_the_checkout_before_generating(self): + steps = self._steps("deploy-site.yml", "build") + generate = self._index(steps, "Generate site") + self.assertLess(self._index(steps, "restore_large_files.py"), generate) + self.assertLess(self._index(steps, "refresh_data_dirs.py"), generate) + + def test_restore_matches_assets_by_content_not_by_name(self): + from scripts.release.restore import restore + + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + cache = root / "cache" + cache.mkdir() + payload = b"firmware bytes" + (cache / "renamed-asset.bin").write_bytes(payload) + sha1 = hashlib.sha1(payload).hexdigest() + (root / ".gitignore").write_text("bios/Sony/big.pup\n", encoding="utf-8") + (root / "database.json").write_text( + json.dumps({"files": {sha1: {"path": "bios/Sony/big.pup"}}}), + encoding="utf-8", + ) + result = restore( + str(cache), str(root / "database.json"), str(root / ".gitignore"), + root=root, + ) + self.assertEqual( + (result.restored, result.unsatisfied), (["bios/Sony/big.pup"], []) + ) + self.assertEqual((root / "bios/Sony/big.pup").read_bytes(), payload) + # A path already in the checkout is never overwritten. + result = restore( + str(cache), str(root / "database.json"), str(root / ".gitignore"), + root=root, + ) + self.assertEqual((result.restored, result.unsatisfied), ([], [])) + + def test_restore_without_its_registry_fails(self): + """A mistyped --gitignore read as an empty registry: nothing to + restore, nothing unsatisfied, exit 0 with every asset absent.""" + import subprocess + + from scripts.release.restore import gitignored_paths + + with tempfile.TemporaryDirectory() as directory: + missing = str(Path(directory) / "absent") + with self.assertRaises(FileNotFoundError): + gitignored_paths(missing) + proc = subprocess.run( + [sys.executable, str(ROOT / "scripts" / "restore_large_files.py"), + "--gitignore", missing, "--cache", directory], + capture_output=True, text=True, timeout=120, + check=False, + ) + self.assertEqual(proc.returncode, 2, proc.stdout + proc.stderr) + self.assertIn("lists the release assets", proc.stderr) + + def test_restore_refuses_a_copy_replaced_after_the_index(self): + """The cache is hashed first and copied later: another run that + replaced the cached name in between put its bytes at a path the + database pins to the old ones.""" + from scripts.release import restore as release_restore + + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + cache = root / "cache" + cache.mkdir() + payload = b"firmware bytes" + (cache / "asset.bin").write_bytes(payload) + sha1 = hashlib.sha1(payload).hexdigest() + (root / ".gitignore").write_text("bios/Sony/big.pup\n", encoding="utf-8") + (root / "database.json").write_text( + json.dumps({"files": {sha1: {"path": "bios/Sony/big.pup"}}}), + encoding="utf-8", + ) + real_index = release_restore.index_cache + + def index_then_replace(cache_dir: str) -> dict[str, str]: + index = real_index(cache_dir) + (cache / "asset.bin").write_bytes(b"re-uploaded bytes") + return index + + with mock.patch.object(release_restore, "index_cache", index_then_replace): + result = release_restore.restore( + str(cache), str(root / "database.json"), + str(root / ".gitignore"), root=root, + ) + self.assertEqual( + (result.restored, result.unsatisfied), ([], ["bios/Sony/big.pup"]) + ) + self.assertFalse((root / "bios/Sony/big.pup").exists()) + self.assertEqual(os.listdir(root / "bios/Sony"), []) + + def test_restore_leaves_tracked_paths_alone(self): + from scripts.release.restore import restore + + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + cache = root / "cache" + cache.mkdir() + payload = b"tracked bytes" + (cache / "asset.bin").write_bytes(payload) + sha1 = hashlib.sha1(payload).hexdigest() + (root / ".gitignore").write_text("bios/other.bin\n", encoding="utf-8") + (root / "database.json").write_text( + json.dumps({"files": {sha1: {"path": "bios/tracked.bin"}}}), + encoding="utf-8", + ) + result = restore( + str(cache), str(root / "database.json"), str(root / ".gitignore"), + root=root, + ) + self.assertEqual((result.restored, result.unsatisfied), ([], [])) + self.assertFalse((root / "bios/tracked.bin").exists()) + + def test_restore_without_a_cache_names_what_is_missing(self): + """A job that skipped `mkdir .cache/large` exited 0 with every + gitignored file absent: the early return ran before the check.""" + from scripts.release.restore import restore + + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + (root / ".gitignore").write_text("bios/big.bin\n", encoding="utf-8") + (root / "database.json").write_text( + json.dumps({"files": {"a" * 40: {"path": "bios/big.bin"}}}), + encoding="utf-8", + ) + result = restore( + str(root / "no-cache"), str(root / "database.json"), + str(root / ".gitignore"), root=root, + ) + self.assertEqual( + (result.restored, result.unsatisfied, result.cache_found), + ([], ["bios/big.bin"], False), + ) + + def test_restore_command_prints_the_report(self): + """The command, not the library, says what was restored and what the + cache could not supply, relative to the directory it runs in.""" + import subprocess + + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + cache = root / "cache" + cache.mkdir() + payload = b"firmware bytes" + (cache / "asset.bin").write_bytes(payload) + sha1 = hashlib.sha1(payload).hexdigest() + (root / ".gitignore").write_text( + "bios/big.bin\nbios/absent.bin\n", encoding="utf-8" + ) + (root / "database.json").write_text( + json.dumps({"files": { + sha1: {"path": "bios/big.bin"}, + "a" * 40: {"path": "bios/absent.bin"}, + }}), + encoding="utf-8", + ) + command = [sys.executable, str(ROOT / "scripts" / "restore_large_files.py")] + proc = subprocess.run( + [*command, "--cache", "cache"], + capture_output=True, text=True, cwd=str(root), timeout=120, + check=False, + ) + self.assertEqual(proc.returncode, 1, proc.stdout + proc.stderr) + self.assertEqual( + proc.stdout, "Restored: bios/big.bin\nTotal: 1 files restored\n" + ) + self.assertEqual( + proc.stderr, + "Unsatisfied: 1 declared paths the cache cannot supply\n" + " bios/absent.bin\n", + ) + self.assertEqual((root / "bios/big.bin").read_bytes(), payload) + without_cache = subprocess.run( + [*command, "--cache", "no-cache"], + capture_output=True, text=True, cwd=str(root), timeout=120, + check=False, + ) + self.assertTrue(without_cache.stdout.startswith("No cache at no-cache\n")) + + +class PreservedBytesAreNeverNormalised(unittest.TestCase): + """git must not rewrite a preserved file's line endings. + + SHA1 is the primary key of this collection. Git for Windows sets + core.autocrlf=true by default, so without an attribute saying otherwise a + clone there rewrites every file git guesses is text -- shaders, .ini, + .txt and .dat assets under bios/ -- and each one arrives with a different + hash from the one published here. + """ + + def _attr(self, path: str) -> str: + import subprocess + + out = subprocess.run( + ["git", "check-attr", "text", "--", path], + capture_output=True, text=True, cwd=ROOT, + check=False, + ).stdout + return out.rsplit(":", 1)[-1].strip() + + def test_gitattributes_exists(self): + self.assertTrue( + (ROOT / ".gitattributes").is_file(), + "without it git guesses, and guesses wrong on Windows", + ) + + def test_collection_paths_are_exempt_from_normalisation(self): + for path in ( + "bios/Sony/PlayStation/scph5501.bin", + "bios/Other/j2me-loader/color.fsh", + "data/anything.txt", + "data/dolphin-sys/config.json", + ): + with self.subTest(path=path): + self.assertEqual(self._attr(path), "unset", f"{path} may be rewritten") + + def test_generated_artefacts_stay_lf(self): + for path in ( + "database.json", + "scripts/dedup.py", + "README.md", + "provenance/redump.json", + ): + with self.subTest(path=path): + self.assertEqual(self._attr(path), "set") + + +class FreshnessGuardMechanics(unittest.TestCase): + """write_if_changed is what makes `git diff --exit-code` a real check. + + deploy-site.yml regenerates README.md and CONTRIBUTING.md and then fails + if git sees a change. That is only a staleness check because a run which + moves nothing but the clock leaves the file untouched. If the comparison + missed a timestamp form, the guard would fail on every run and stop + meaning anything. + """ + + def setUp(self): + from core.artifacts import write_if_changed + + self.write_if_changed = write_if_changed + self._tmp = tempfile.TemporaryDirectory() + self.path = os.path.join(self._tmp.name, "page.md") + + def tearDown(self): + self._tmp.cleanup() + + def test_a_new_file_is_written(self): + self.assertTrue(self.write_if_changed(self.path, "body\n")) + with open(self.path) as handle: + self.assertEqual(handle.read(), "body\n") + + def test_identical_content_is_not_rewritten(self): + self.write_if_changed(self.path, "body\n") + self.assertFalse(self.write_if_changed(self.path, "body\n")) + + def test_real_change_is_written(self): + self.write_if_changed(self.path, "body\n") + self.assertTrue(self.write_if_changed(self.path, "other\n")) + + def test_every_timestamp_form_is_ignored_on_its_own(self): + forms = [ + '{{"generated_at": "{}"}}', + '{{"imported_at": "{}"}}', + '{{"generated": "{}"}}', + '{{"fetched": "{}"}}', + "*Auto-generated on {}*", + "*Generated on {}*", + '
Generated on {}.
', + ] + for form in forms: + with self.subTest(form=form): + first = form.format("2026-01-01T00:00:00Z") + second = form.format("2026-09-09T09:09:09Z") + self.write_if_changed(self.path, first) + self.assertFalse( + self.write_if_changed(self.path, second), + f"a clock-only change rewrote the file for {form!r}", + ) + + def test_a_change_beside_a_moving_timestamp_is_still_written(self): + self.write_if_changed(self.path, "count: 1\n*Generated on A*\n") + self.assertTrue( + self.write_if_changed(self.path, "count: 2\n*Generated on B*\n") + ) + + def test_the_written_file_keeps_the_new_timestamp_when_content_changed(self): + self.write_if_changed(self.path, "count: 1\n*Generated on A*\n") + self.write_if_changed(self.path, "count: 2\n*Generated on B*\n") + with open(self.path) as handle: + self.assertIn("Generated on B", handle.read()) + + +class AMissingDependencyStopsTheBuild(unittest.TestCase): + """generate_db read every alias inside `try: import yaml ... except + ImportError: pass`: on an interpreter without pyyaml the database lost + 3186 alias lines and the run exited 0.""" + + def test_generate_db_without_pyyaml_fails(self): + with tempfile.TemporaryDirectory() as tmp: + output = Path(tmp) / "database.json" + proc = subprocess.run( + [sys.executable, "-S", "scripts/generate_db.py", "--force", + "--bios-dir", "bios", "--output", str(output)], + cwd=ROOT, capture_output=True, text=True, timeout=600, check=False, + ) + self.assertNotEqual(proc.returncode, 0, proc.stdout) + self.assertIn("PyYAML required", proc.stderr) + self.assertFalse(output.exists()) + + def test_every_yaml_command_stops_on_one_line(self): + """refresh_data_dirs and check_buildbot_system ended on a traceback.""" + for command in (["scripts/refresh_data_dirs.py", "--dry-run"], + ["scripts/check_buildbot_system.py"]): + with self.subTest(command=command[0]): + proc = subprocess.run( + [sys.executable, "-S", *command], + cwd=ROOT, capture_output=True, text=True, timeout=120, check=False, + ) + self.assertEqual(proc.returncode, 1, proc.stdout) + self.assertEqual( + proc.stderr.strip(), "Error: PyYAML required (pip install pyyaml)" + ) + + def test_no_script_swallows_an_import_error(self): + offenders = [] + for path in sorted((ROOT / "scripts").rglob("*.py")): + tree = ast.parse(path.read_text(encoding="utf-8")) + offenders.extend( + f"{path.relative_to(ROOT)}:{node.lineno}" + for node in ast.walk(tree) + if ( + isinstance(node, ast.ExceptHandler) + and isinstance(node.type, ast.Name) + and node.type.id in ("ImportError", "ModuleNotFoundError") + and all(isinstance(stmt, ast.Pass) for stmt in node.body) + ) + ) + self.assertEqual(offenders, []) + + +class TestsCleanUpTheirScratch(unittest.TestCase): + """Sixteen classes called mkdtemp() and kept the directory: each suite + run left about 400 of them on the RAM-backed /tmp.""" + + def test_every_class_that_makes_a_directory_removes_it(self): + offenders = [] + for path in sorted((ROOT / "tests").glob("test_*.py")): + source = path.read_text(encoding="utf-8") + for node in ast.parse(source).body: + if not isinstance(node, ast.ClassDef): + continue + body = ast.get_source_segment(source, node) or "" + if "mkdtemp(" in body and not any( + word in body for word in ("rmtree", "addCleanup", "tearDown") + ): + offenders.append(f"{path.name}:{node.name}") + self.assertEqual(offenders, []) + + +class DeclaredDependenciesMatchTheDocumentedWorkflows(unittest.TestCase): + """What the workflows install has to be what the project declares. + + mkdocs-material and pymdown-extensions were hard requirements of the site + build in CI and in the release guide while pyproject declared neither, so + a contributor following either had to read the workflow to find out. + """ + + @staticmethod + def _pyproject() -> dict: + import tomllib + + with (ROOT / "pyproject.toml").open("rb") as handle: + return tomllib.load(handle) + + def test_every_package_ci_installs_is_declared(self): + extras = self._pyproject()["project"]["optional-dependencies"] + declared = { + name.split(">")[0].split("=")[0].split("<")[0].strip('"') + for group in extras.values() + for name in group + } + declared |= set(self._pyproject()["project"]["dependencies"]) + installed: set[str] = set() + for workflow in ("validate.yml", "deploy-site.yml"): + body = (ROOT / ".github" / "workflows" / workflow).read_text( + encoding="utf-8" + ) + for line in body.splitlines(): + if "pip install" not in line: + continue + for token in line.split("pip install", 1)[1].split(): + name = token.strip('"').split(">")[0].split("=")[0] + name = name.split("<")[0].strip() + if name: + installed.add(name) + self.assertEqual( + installed - declared, + set(), + "CI installs packages pyproject does not declare", + ) + + +class TheAnnotationsAreChecked(unittest.TestCase): + """Every signature carried type hints and nothing read them: six pack + helpers declared `zipfile.ZipFile` while every caller also passed a + PackRecord, and 990 such contradictions went through CI green. They sat + in a baseline until the last one was fixed: the code now carries no + type error, and CI runs mypy bare, so any new one fails.""" + + def test_ci_runs_mypy_without_a_baseline(self): + body = (ROOT / ".github" / "workflows" / "validate.yml").read_text( + encoding="utf-8" + ) + self.assertRegex(body, r"(?m)^\s+mypy$") + self.assertNotIn("mypy-baseline", body) + self.assertFalse((ROOT / "mypy-baseline.txt").exists()) + + def test_the_code_reports_no_type_error(self): + try: + __import__("mypy") + except ImportError: + self.skipTest("mypy is not installed (pip install -e '.[dev]')") + report = subprocess.run( + [sys.executable, "-m", "mypy"], + cwd=ROOT, capture_output=True, text=True, check=False, + ) + self.assertEqual(report.returncode, 0, report.stdout[-4000:]) + + +class TheProjectInstallsWithPip(unittest.TestCase): + """pyproject declared a dev extra that pip could not install: without a + [build-system] and an explicit module list, setuptools' flat-layout + discovery found scripts/ and tests/ and refused to build.""" + + def test_setuptools_discovers_nothing_to_package(self): + import importlib.util + + if importlib.util.find_spec("setuptools") is None: + # The dev extra and CI install it: skipped there, the guard held + # nothing on any run. + if os.environ.get("CI"): + self.fail("CI must install setuptools") + self.skipTest("setuptools is not installed") + program = ( + "from setuptools.dist import Distribution\n" + "from setuptools.config.pyprojecttoml import apply_configuration\n" + "dist = apply_configuration(Distribution(), 'pyproject.toml')\n" + "dist.set_defaults()\n" + "print(sorted(dist.packages or []), sorted(dist.py_modules or []))\n" + ) + done = subprocess.run([sys.executable, "-c", program], cwd=ROOT, + capture_output=True, text=True, check=False) + self.assertEqual(done.returncode, 0, done.stderr[-2000:]) + self.assertEqual(done.stdout.strip(), "[] []") + import tomllib + + with (ROOT / "pyproject.toml").open("rb") as handle: + build = tomllib.load(handle)["build-system"] + self.assertEqual(build["build-backend"], "setuptools.build_meta") + + +class TestEntryPointsRunEveryClass(unittest.TestCase): + """`unittest.main()` has to sit after the last test class. + + In this file it sat in the middle, so running it directly discovered only + the classes defined above it: eight cases never ran that way, while + `python -m unittest discover` ran all of them. The two roads have to agree. + """ + + def test_no_module_calls_main_before_its_last_class(self): + for path in sorted((ROOT / "tests").glob("test_*.py")): + lines = path.read_text(encoding="utf-8").splitlines() + # Column zero only: the same text appears inside this very test as + # a string literal, and a substring search matched that instead. + entry = next( + (n for n, line in enumerate(lines) + if line.startswith("if __name__ ==")), + None, + ) + if entry is None: + continue + last_class = max( + (n for n, line in enumerate(lines) if line.startswith("class ")), + default=-1, + ) + self.assertGreater( + entry, + last_class, + f"{path.name} calls unittest.main() before its last class, so " + "running the file directly skips what follows", + ) + + +class ScriptsImportThreeWays(unittest.TestCase): + """A script is run directly, run as a module, and imported as a package. + + The three do not agree on what is on the path: only the first form adds + the scripts directory. Adding the package marker without the bootstrap + made `import scripts.common` (now scripts.core.cli) fail on the first sibling import it reached. + """ + + def _run(self, *args: str): + import subprocess + + return subprocess.run( + [sys.executable, *args], + capture_output=True, text=True, cwd=str(ROOT), timeout=300, + check=False, + ) + + def test_imported_as_a_package(self): + result = self._run( + "-c", "import scripts.core.cli, scripts.model.platforms, scripts.resolve.localfile, " + "scripts.verify, scripts.generate_pack" + ) + self.assertEqual(result.returncode, 0, result.stderr[-400:]) + + def test_run_as_a_module(self): + result = self._run("-m", "scripts.scraper.libretro_scraper", "--help") + self.assertEqual(result.returncode, 0, result.stderr[-400:]) + + def test_run_as_a_script(self): + result = self._run("scripts/list_platforms.py") + self.assertEqual(result.returncode, 0, result.stderr[-400:]) + + +class NoHandlerSwallowsEverything(unittest.TestCase): + """The project forbids `except Exception: pass`, but the edit hook missed + the two-line form and nothing in CI checked it.""" + + def test_no_catch_all_handler_only_passes(self): + import ast + + offenders = [] + for path in [*sorted((ROOT / "scripts").rglob("*.py")), ROOT / "install.py"]: + tree = ast.parse(path.read_text(encoding="utf-8")) + for node in ast.walk(tree): + if not isinstance(node, ast.ExceptHandler): + continue + broad = node.type is None or ( + isinstance(node.type, ast.Name) + and node.type.id in ("Exception", "BaseException") + ) + if broad and all(isinstance(stmt, ast.Pass) for stmt in node.body): + offenders.append(f"{path.relative_to(ROOT)}:{node.lineno}") + self.assertEqual(offenders, []) + + +class ModuleConstantsDeclaredOnce(unittest.TestCase): + """Splitting common.py into modules emitted some constants twice. + + The values matched, so nothing broke, but the second assignment orphans + the comment written above the first and leaves two lines to keep in step + the day a value changes. + """ + + @staticmethod + def _redeclared(path: Path) -> list[str]: + seen: dict[str, str] = {} + again = [] + for node in ast.parse(path.read_text()).body: + if not isinstance(node, ast.Assign) or len(node.targets) != 1: + continue + target = node.targets[0] + if not isinstance(target, ast.Name): + continue + value = ast.unparse(node.value) + if seen.get(target.id) == value: + again.append(target.id) + seen[target.id] = value + return again + + def test_no_module_assigns_the_same_constant_twice(self): + offenders = {} + for path in sorted(ROOT.glob("scripts/**/*.py")) + [ROOT / "install.py"]: + again = self._redeclared(path) + if again: + offenders[path.name] = again + self.assertEqual(offenders, {}) + + +class OnlyTheSchemaValidatorNeedsJsonschema(unittest.TestCase): + """Build scripts and install.py run on stdlib plus pyyaml, and jsonschema is + tooling for the schemas package behind validate_schemas and CI. An import + anywhere else turns a contributor's pipeline run into an ImportError.""" + + @staticmethod + def _imports_jsonschema(source: str) -> bool: + for node in ast.walk(ast.parse(source)): + if isinstance(node, ast.Import): + names = [alias.name for alias in node.names] + elif isinstance(node, ast.ImportFrom): + names = [node.module or ""] + else: + continue + if any(name.split(".")[0] == "jsonschema" for name in names): + return True + return False + + def test_no_other_module_imports_it(self): + offenders = [ + str(path.relative_to(ROOT)) + for path in sorted(ROOT.glob("scripts/**/*.py")) + [ROOT / "install.py"] + if path.parent != ROOT / "scripts" / "schemas" + and self._imports_jsonschema(path.read_text()) + ] + self.assertEqual(offenders, []) + + def test_a_nested_import_is_seen(self): + self.assertTrue( + self._imports_jsonschema("def f():\n from jsonschema import validate\n") + ) + + +class ADuplicateYamlKeyIsRefused(unittest.TestCase): + """PyYAML kept the last of two equal keys: the registry carried two + target_source keys for Recalbox and nothing noticed.""" + + def test_the_loader_names_the_repeated_key(self): + from model.safeparse import yaml_load + + with self.assertRaises(yaml.constructor.ConstructorError) as caught: + yaml_load("platform: x\ntarget_source: a\ntarget_source: b\n") + self.assertIn("duplicate key 'target_source'", str(caught.exception)) + self.assertEqual(yaml_load("a: &x {b: 1}\nc: *x\n"), {"a": {"b": 1}, "c": {"b": 1}}) + + +class NoSourceWarnsWhenCompiled(unittest.TestCase): + """A docstring naming C:\\RetroArch-Win64 with one backslash compiled to + an invalid escape: a SyntaxWarning on every run of the installer.""" + + def test_every_script_compiles_clean(self): + import warnings + + sources = [ROOT / "install.py", *sorted((ROOT / "scripts").rglob("*.py"))] + for path in sources: + with self.subTest(path=path.name), warnings.catch_warnings(): + warnings.simplefilter("error", SyntaxWarning) + warnings.simplefilter("error", DeprecationWarning) + compile(path.read_text(encoding="utf-8"), str(path), "exec") + + +class TestsRunOffline(unittest.TestCase): + def test_the_package_forbids_downloads(self): + self.assertTrue(os.environ.get("RETROBIOS_OFFLINE")) + + def test_every_documented_run_imports_the_package(self): + """`discover tests` makes tests/ the top level, so tests/__init__.py, + which sets RETROBIOS_OFFLINE, never ran: a local run of the documented + command queried the release and wrote into the shared cache. Only CI, + which sets the variable itself, was offline.""" + import subprocess + + listed = subprocess.run( + ["git", "grep", "-n", "unittest discover", "--", ":!tests"], + capture_output=True, text=True, cwd=ROOT, check=False, + ).stdout.splitlines() + self.assertTrue(listed) + self.assertEqual([line for line in listed if "-t ." not in line], []) + + +class MessagesSeparateWithAColon(unittest.TestCase): + """Em-dashes were replaced by " -" in messages: "bios/BLOOD.RFF -raze + says size mismatch" reads as a flag glued to a file name.""" + + PATTERN = re.compile(r"\} -[{a-z]") + + def test_no_message_uses_a_dash_separator(self): + found = [] + for path in [ROOT / "install.py", *sorted((ROOT / "scripts").rglob("*.py"))]: + for number, line in enumerate(path.read_text().splitlines(), 1): + if self.PATTERN.search(line): + found.append(f"{path.name}:{number}: {line.strip()}") + self.assertEqual(found, []) + + +class TheIssueFormListsEveryPlatform(unittest.TestCase): + """The missing-BIOS form offered 7 of the 12 registered platforms.""" + + def test_every_registered_platform_is_an_option(self): + from scripts.model.registry import list_registered_platforms + from scripts.model.platforms import load_platform_config + + form = yaml.safe_load( + (ROOT / ".github" / "ISSUE_TEMPLATE" / "missing-bios.yml").read_text() + ) + options = next( + item["attributes"]["options"] for item in form["body"] + if item.get("id") == "platform" + ) + for name in list_registered_platforms(str(ROOT / "platforms")): + display = load_platform_config(name, str(ROOT / "platforms"))["platform"] + self.assertIn(display, options) + + +class TheTestJobHasTheDataTrees(unittest.TestCase): + """Packs built without data directories exit non-zero, but the CI test job + had none, and two pack parity tests failed there only.""" + + def test_the_trees_are_fetched_before_the_suite(self): + steps = yaml.safe_load( + (ROOT / ".github" / "workflows" / "validate.yml").read_text() + )["jobs"]["run-tests"]["steps"] + runs = [step.get("run", "") for step in steps] + fetch = next(i for i, run in enumerate(runs) if "refresh_data_dirs.py" in run) + suite = next(i for i, run in enumerate(runs) if "scripts/run_tests.py" in run) + self.assertLess(fetch, suite) + + +class GeneratedArtifactsMeetTheirSchemas(unittest.TestCase): + """A manifest field added without its schema passed every local test + and failed the site deploy, which is the first run of the full check.""" + + @unittest.skipUnless(HAS_JSONSCHEMA, "needs jsonschema") + def test_the_full_schema_check_passes(self): + proc = subprocess.run( + [sys.executable, "scripts/validate_schemas.py"], cwd=ROOT, + capture_output=True, text=True, timeout=600, + check=False, + ) + self.assertEqual(proc.returncode, 0, proc.stdout + proc.stderr) + + +class SignaturesCarryTheirTypes(unittest.TestCase): + """Type hints on every signature is a written rule; 177 had none, the + shared API among them (artifact locks, the data-dir resolver, the region + priority list of _select_variants).""" + + # Lowered as modules are annotated, never raised. + CEILING = 0 + COMPLETE = ("core/artifacts.py", "model/platforms.py", "model/profiles.py", "resolve/localfile.py", + "resolve/lookup.py", "resolve/namestages.py", "resolve/validation.py", + "resolve/entryscope.py", "resolve/acceptance.py", "generate_pack.py") + + @staticmethod + def _missing(path: Path) -> list[str]: + found = [] + for node in ast.walk(ast.parse(path.read_text(encoding="utf-8"))): + if not isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)): + continue + args = node.args + params = [a for a in (*args.posonlyargs, *args.args, *args.kwonlyargs) + if a.arg not in ("self", "cls")] + params += [a for a in (args.vararg, args.kwarg) if a] + if node.returns is None or any(a.annotation is None for a in params): + found.append(f"{path.name}:{node.lineno} {node.name}") + return found + + def test_the_count_only_goes_down(self): + paths = [ROOT / "install.py", *sorted((ROOT / "scripts").rglob("*.py"))] + missing = [m for path in paths for m in self._missing(path)] + self.assertLessEqual(len(missing), self.CEILING, missing[:20]) + for name in self.COMPLETE: + with self.subTest(module=name): + self.assertEqual(self._missing(ROOT / "scripts" / name), []) + + +class TheApiSchemaHoldsTheFieldsItPromises(unittest.TestCase): + """The data page promises fields are only added within v1, and the + published schema left items unconstrained: renaming url in + file-locations.json passed validation and broke consumers silently.""" + + def test_a_renamed_field_is_refused(self): + try: + import jsonschema + except ImportError: + self.skipTest("jsonschema is tooling only") + schema = json.loads((ROOT / "schemas" / "site-api-envelope.schema.json").read_text()) + envelope = {"schema_version": 1, "generated_at": "2026-10-20T00:00:00Z", + "kind": "file-locations", "count": 1, + "items": [{"sha1": "a" * 40, "url": "https://x/y"}]} + jsonschema.validate(envelope, schema) + envelope["items"] = [{"sha1": "a" * 40, "href": "https://x/y"}] + with self.assertRaises(jsonschema.ValidationError): + jsonschema.validate(envelope, schema) + + +class CommentsSayWhy(unittest.TestCase): + """A one-line comment that names the next statement ("# Load registry", + "# Build cross-reference indexes") repeats the code. A comment that + stays says why (for, only, so, because).""" + + LABEL = re.compile( + r"^\s*# (Load|Build|Collect|Determine|Resolve|Group|Copy|Count|Append|" + r"Filter|Separate|Compute|Create|Get|Check|Generate|Write|Read|Parse|Sort)" + r"\b[^.:;,()]{0,60}$" + ) + REASON = re.compile(r"\b(for|only|so|because|if|when|unless|before|after)\b") + + def test_no_label_comment_restates_the_next_line(self): + """Three scripts were read, and 22 labels stood in 13 others.""" + tracked = subprocess.run( + ["git", "ls-files", "--", "scripts/*.py", "scripts/**/*.py", "install.py"], + cwd=ROOT, capture_output=True, text=True, check=True, + ).stdout.split() + self.assertIn("install.py", tracked) + self.assertIn("scripts/scraper/mame_parser.py", tracked) + found = [] + for name in sorted(set(tracked)): + lines = (ROOT / name).read_text(encoding="utf-8").splitlines() + for index, line in enumerate(lines): + if not self.LABEL.match(line) or self.REASON.search(line): + continue + around = (lines[index - 1].strip(), lines[index + 1].strip()) + if any(neighbour.startswith("#") for neighbour in around): + continue + if not line.startswith(" "): + continue + found.append(f"{name}:{index + 1}: {line.strip()}") + self.assertEqual(found, []) + + +class PipelineChildrenSkipNodeCompileCache(unittest.TestCase): + """The site build's compile cache filled the 4 GB /tmp tmpfs to 3.4 GB: + every child the pipeline starts carries NODE_DISABLE_COMPILE_CACHE.""" + + def test_the_run_helper_sets_it(self): + source = script_source("pipeline.py") + self.assertIn('"NODE_DISABLE_COMPILE_CACHE": "1"', source) + + +class TupleAnnotationsMatchTheirReturns(unittest.TestCase): + """`_by_affinity.score` gained a fifth sort key while its annotation kept + four, so the signature misread the order that sends C-Dogs' + gamecontrollerdb.txt behind a neutral copy.""" + + @staticmethod + def _own_returns(fn: ast.AST): + stack = list(ast.iter_child_nodes(fn)) + while stack: + node = stack.pop() + if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.Lambda)): + continue + if isinstance(node, ast.Return): + yield node + stack.extend(ast.iter_child_nodes(node)) + + def test_a_fixed_tuple_annotation_counts_its_returned_values(self): + sources = sorted((ROOT / "scripts").rglob("*.py")) + [ROOT / "install.py"] + mismatched = [] + for path in sources: + for fn in ast.walk(ast.parse(path.read_text(encoding="utf-8"))): + if not isinstance(fn, (ast.FunctionDef, ast.AsyncFunctionDef)): + continue + hint = fn.returns + if not (isinstance(hint, ast.Subscript) and isinstance(hint.value, ast.Name) + and hint.value.id == "tuple"): + continue + declared = hint.slice.elts if isinstance(hint.slice, ast.Tuple) else [hint.slice] + if any(isinstance(e, ast.Constant) and e.value is Ellipsis for e in declared): + continue + for ret in self._own_returns(fn): + value = ret.value + if (isinstance(value, ast.Tuple) + and not any(isinstance(e, ast.Starred) for e in value.elts) + and len(value.elts) != len(declared)): + mismatched.append( + f"{path.relative_to(ROOT)}:{ret.lineno} " + f"{len(value.elts)} returned, {len(declared)} declared" + ) + self.assertEqual(mismatched, []) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_audit_regressions.py b/tests/test_audit_regressions.py deleted file mode 100644 index c9e5961a1..000000000 --- a/tests/test_audit_regressions.py +++ /dev/null @@ -1,8391 +0,0 @@ -"""Regression tests for the holistic reliability and security audit.""" - -from __future__ import annotations - -import tests -from tests.sources import script_source - -import ast -import contextlib -import hashlib -import io -import json -import os -import re -import stat -import subprocess -import sys -import tempfile -import unittest -import urllib.error -import zipfile -import zlib -from pathlib import Path -from unittest import mock - -import yaml - -try: - import jsonschema -except ImportError: - jsonschema = None -import install -from packs import verdicts -from scripts import pipeline -from orchestrate import checks, consistency, results, runner -from scripts.resolve import regionaudit, regions -from scripts.resolve.localfile import resolve_local_file -from scripts.core.ziptools import safe_extract_zip -from scripts.packs.extraregions import _emulator_region_group -from scripts.packs.platformcheck import verify_pack_against_platform -from scripts.packs.targets import generate_target_manifests - -HAS_JSONSCHEMA = jsonschema is not None -ROOT = Path(__file__).resolve().parent.parent - - -class ReadmeRegressions(unittest.TestCase): - """The README advertises commands, and these must stay executable. - - Wording is the maintainer's, so nothing here asserts prose. What is - asserted is that every flag and URL the README hands a reader is one the - shipped scripts actually accept. - """ - - def _quick_install(self) -> str: - readme = (ROOT / "README.md").read_text(encoding="utf-8") - return readme.split("## Install in one line", 1)[1].split( - "## Or download a ZIP", 1 - )[0] - - def test_advertised_bootstrap_urls_are_the_shipped_ones(self): - from sitegen import bootstrap as sitebootstrap - from sitegen.guidedata import install_base - - quick_install = self._quick_install() - for name in sitebootstrap.SOURCES: - url = f"{install_base()}/{name}" - self.assertIn(f"{url} |", quick_install, f"{name} bootstrap URL missing") - # The site serves each bootstrap with install.py read from the - # commit it was built from, the raw form from main. - commit = "0" * 40 - for name in sitebootstrap.SOURCES: - self.assertIn(sitebootstrap.installer_url(commit), - sitebootstrap.served_text(name, ROOT, commit)) - self.assertIn( - "https://raw.githubusercontent.com/Abdess/retrobios/main/install.py", - (ROOT / "install.sh").read_text(encoding="utf-8"), - ) - - def test_advertised_installer_flags_exist(self): - quick_install = self._quick_install() - advertised = set(re.findall(r"(? 40, "key material looks truncated") - - def test_the_release_signs_the_list_and_ships_the_signature(self): - process = (ROOT / "wiki" / "release-process.md").read_text(encoding="utf-8") - self.assertIn( - "ssh-keygen -Y sign", process, "the release no longer signs the list" - ) - upload = next( - line for line in process.splitlines() - if line.startswith("for f in dist/SHA256SUMS.txt") - ) - self.assertIn( - "dist/SHA256SUMS.txt.sig", upload, - "the signature is produced but never uploaded", - ) - - def test_the_documented_verification_matches_the_published_principal(self): - process = (ROOT / "wiki" / "release-process.md").read_text(encoding="utf-8") - self.assertIn("ssh-keygen -Y verify", process) - self.assertIn(f"-I {self.PRINCIPAL}", process) - self.assertIn("allowed_signers", process) - - -class WorkflowRegressions(unittest.TestCase): - """The test suite must sit on every road into main. - - run-tests lived in a pull_request-only workflow while the work landed by - direct push, so 1,318 cases guarded a road almost nothing took. What is - asserted here is reachability, not the workflow's shape. - """ - - @staticmethod - def _workflow(name: str) -> dict: - with (ROOT / ".github" / "workflows" / name).open(encoding="utf-8") as f: - document = yaml.safe_load(f) - # PyYAML resolves the bare `on:` key to the boolean True. - document["on"] = document.pop(True, document.get("on")) - return document - - def test_no_validation_step_discards_its_exit_code(self): - """A check whose result is thrown away is not a check. - - The BIOS validation step ended in `|| true`, so validate_pr.py could - exit 1 on a file that failed its hash and the job stayed green. The - report still has to reach the pull request, so the code is recorded - and acted on afterwards rather than swallowed. A best-effort side - action such as adding a label is not a check and keeps its `|| true`. - """ - checks = ("python scripts/", "unittest", "npm run build") - for name in ("validate.yml", "deploy-site.yml"): - workflow = self._workflow(name) - for job_name, job in workflow["jobs"].items(): - for step in job.get("steps", []): - # A shell continuation puts the command and its `|| true` - # on different lines, so they are rejoined before scanning. - body = str(step.get("run", "")).replace("\\\n", " ") - for line in body.splitlines(): - if not any(marker in line for marker in checks): - continue - self.assertNotIn( - "|| true", - line, - f"{name}:{job_name}:{step.get('name', '?')} runs a " - f"check and discards its exit code: {line.strip()}", - ) - - workflow = self._workflow("validate.yml") - steps = workflow["jobs"]["validate-bios"]["steps"] - gate = [s for s in steps if "rc != " in str(s.get("if", ""))] - self.assertTrue( - gate, - "nothing in validate-bios acts on the validation exit code", - ) - - def test_the_suite_runs_on_a_direct_push_to_main(self): - workflow = self._workflow("validate.yml") - triggers = workflow["on"] - self.assertIn("push", triggers, "validate.yml no longer runs on push") - self.assertIn("main", triggers["push"]["branches"]) - job = next( - ( - name - for name, body in workflow["jobs"].items() - if any( - "scripts/run_tests.py" in str(step.get("run", "")) - for step in body.get("steps", []) - ) - ), - None, - ) - self.assertIsNotNone(job, "no job runs the test suite") - self.assertIsNone( - workflow["jobs"][job].get("if"), - f"{job} carries a condition, but the suite must run on push and on PR", - ) - - def test_added_profiles_meet_their_upstream_on_both_roads(self): - """A new profile's refs were confronted only if its author remembered.""" - workflow = self._workflow("validate.yml") - runs = [ - (name, str(step.get("run", ""))) - for name, body in workflow["jobs"].items() - for step in body.get("steps", []) - if "profile_sync.py" in str(step.get("run", "")) - ] - self.assertTrue(runs, "no job confronts profiles with their upstream") - for name, body in runs: - self.assertIn("--strict", body) - self.assertIn("--added", body) - self.assertIsNone(workflow["jobs"][name].get("if"), f"{name} must run on push too") - - def test_both_events_watch_the_same_paths(self): - triggers = self._workflow("validate.yml")["on"] - self.assertEqual( - triggers["pull_request"]["paths"], - triggers["push"]["paths"], - "the two path lists have drifted, so a push would skip what a PR checks", - ) - - def test_pull_request_only_jobs_are_guarded(self): - workflow = self._workflow("validate.yml") - for name, body in workflow["jobs"].items(): - uses_pr_context = "github.event.pull_request" in yaml.dump(body) - if uses_pr_context: - self.assertEqual( - body.get("if"), - "github.event_name == 'pull_request'", - f"{name} reads pull request context and would run on a push", - ) - - def test_no_workflow_relies_on_a_yaml_anchor(self): - """The workflow parser reads no anchor, and PyYAML would hide the break.""" - for path in sorted((ROOT / ".github" / "workflows").glob("*.yml")): - for number, line in enumerate( - path.read_text(encoding="utf-8").splitlines(), 1 - ): - self.assertIsNone( - re.search(r"(?:^|\s)[&*][A-Za-z_]", line), - f"{path.name}:{number} uses a YAML anchor: {line.strip()}", - ) - - -class UnreachableCitationRegressions(unittest.TestCase): - """A citation must name a place a declared repository can hold. - - kenji-nx carried tmp/es-de/ANDROID.md:470-474, a path from the machine - of whoever profiled it. No revision of any declared repository holds it, - so profile_sync could only report it missing, every pass, forever. The - check is offline and runs on every push. - """ - - @unittest.skipUnless(HAS_JSONSCHEMA, "validating a schema needs jsonschema") - def _hits(self, text: str) -> bool: - from schemas import citations - - return bool(citations.UNREACHABLE_REF.search(" " + text)) - - def test_a_scratch_directory_is_rejected(self): - self.assertTrue(self._hits("tmp/es-de/ANDROID.md:470-474")) - - def test_an_absolute_path_is_rejected(self): - self.assertTrue(self._hits("/home/someone/src/a.c:12")) - self.assertTrue(self._hits(r"C:\work\src\a.c:12")) - - def test_a_path_climbing_out_of_the_tree_is_rejected(self): - self.assertTrue(self._hits("../outside/src/a.c:12")) - - def test_ordinary_citations_pass(self): - for good in ( - "src/core/main.cpp:210", - "libretro.c:5293-5337", - "PCE.emu/src/main/Main.cc:80-91", - "es-de ANDROID.md:470-474", - "see tmp files for details", - ): - with self.subTest(citation=good): - self.assertFalse(self._hits(good)) - - @unittest.skipUnless(HAS_JSONSCHEMA, "validating a schema needs jsonschema") - def test_the_corpus_carries_none(self): - from schemas import citations - - errors = [] - for path in sorted((ROOT / "emulators").glob("*.yml")): - with path.open(encoding="utf-8") as handle: - errors.extend( - citations.unreachable_citations(path, yaml.safe_load(handle)) - ) - self.assertEqual(errors, []) - - -@unittest.skipUnless(HAS_JSONSCHEMA, "validate_schemas needs jsonschema") -class DoubledCitationPaths(unittest.TestCase): - """primehack cited Source/Core/Core/IOS/USB/Bluetooth/ twice in a row in a - comment: no revision holds that path, and the parsed document never - showed it to the citation checks.""" - - def _hits(self, text: str) -> bool: - from schemas import citations - - return bool(citations.DOUBLED_PATH.search(text)) - - def test_a_repeated_directory_is_rejected(self): - self.assertTrue(self._hits( - "# ref: Source/Core/Core/IOS/USB/Bluetooth/Source/Core/Core/IOS/USB/" - "Bluetooth/RealtekFirmwareLoader.cpp:373-416" - )) - - def test_a_directory_named_once_passes(self): - for good in ( - "Source/Core/Core/IOS/USB/Bluetooth/RealtekFirmwareLoader.cpp:383", - "src/src/main.c:10", - "a/b/c/a/b.c:1", - ): - with self.subTest(citation=good): - self.assertFalse(self._hits(good)) - - def test_the_corpus_carries_none(self): - from schemas import citations - - errors = [] - for path in sorted((ROOT / "emulators").glob("*.yml")): - errors.extend(citations.doubled_paths(path)) - self.assertEqual(errors, []) - - -class VerboseAppliesToJson(unittest.TestCase): - """verify accepted --verbose beside --json in every mode and dropped it: - the output was byte for byte the same, and the passing entries a script - asked for never came.""" - - def _run(self, *args: str) -> dict: - import json - import subprocess - - completed = subprocess.run( - [sys.executable, "scripts/verify.py", *args, "--json"], - capture_output=True, text=True, cwd=ROOT, timeout=900, check=False, - ) - self.assertEqual(completed.returncode, 0, completed.stderr[-2000:]) - return json.loads(completed.stdout) - - def test_emulator_and_system_modes_list_the_passing_entries(self): - for mode in (("--emulator", "handy"), ("--system", "atari-lynx")): - with self.subTest(mode=mode[0]): - plain = self._run(*mode) - verbose = self._run(*mode, "--verbose") - self.assertGreater(len(verbose["details"]), len(plain["details"])) - self.assertIn("ok", {d["status"] for d in verbose["details"]}) - - def test_every_json_branch_reads_the_flag(self): - source = script_source("verify.py") - # Defined once, called by the emulator and system output and the platform output. - self.assertEqual(source.count("json_details("), 3) - self.assertNotIn('if d["status"] != Status.OK\n ]', source) - - -class OnePlatformPerFlag(unittest.TestCase): - """generate_pack validated --platform as a comma list, then used the whole - string as one name: `--platform bizhawk,misterfpga` passed and ended in a - FileNotFoundError traceback. Every script now says it takes one name.""" - - def test_a_list_is_refused_with_a_message(self): - import subprocess - - runs = { - "generate_pack.py": ["--list-systems"], - "verify.py": [], - "cross_reference.py": [], - } - for script, extra in runs.items(): - with self.subTest(script=script): - completed = subprocess.run( - [sys.executable, f"scripts/{script}", "--platform", - "bizhawk,misterfpga", *extra], - capture_output=True, text=True, cwd=ROOT, timeout=600, check=False, - ) - self.assertNotEqual(completed.returncode, 0) - self.assertIn("takes one platform", completed.stderr) - self.assertNotIn("Traceback", completed.stderr) - - def test_unknown_names_still_get_a_suggestion(self): - from model.cliargs import require_platform - - with self.assertRaises(SystemExit) as caught: - require_platform("batocra", str(ROOT / "platforms")) - self.assertIn("batocera", str(caught.exception)) - - def test_a_file_that_is_no_platform_is_refused(self): - """_shared and the emulatorjs base config are YAML files under - platforms/, not platforms: verify --platform _shared reported 0/0.""" - from model.cliargs import require_platform - - for name in ("_shared", "_registry", "emulatorjs"): - with self.subTest(name=name), self.assertRaises(SystemExit) as caught: - require_platform(name, str(ROOT / "platforms")) - self.assertIn("unknown platform", str(caught.exception)) - - -class APackIsSwappedInWhole(unittest.TestCase): - """Packs were opened on their final name: a rebuild truncated the good - pack at once, and a build that raised half way left a readable ZIP of - part of the files, which the run then verified and summed.""" - - def _dir(self) -> Path: - import shutil - import tempfile - - (ROOT / "tmp").mkdir(exist_ok=True) - directory = Path(tempfile.mkdtemp()) - self.addCleanup(shutil.rmtree, directory, True) - return directory - - def test_a_failed_build_keeps_the_previous_pack(self): - import zipfile - - from packs.archive import writing_pack - - directory = self._dir() - pack = directory / "Pack.zip" - with zipfile.ZipFile(pack, "w") as zf: - zf.writestr("old.bin", b"complete") - with self.assertRaises(OSError), writing_pack(str(pack)) as zf: - zf.writestr("new.bin", b"half") - raise OSError("disk full") - with zipfile.ZipFile(pack) as zf: - self.assertEqual(zf.namelist(), ["old.bin"]) - self.assertEqual(sorted(p.name for p in directory.iterdir()), ["Pack.zip"]) - - def test_a_finished_build_replaces_it(self): - import zipfile - - from packs.archive import writing_pack - - directory = self._dir() - pack = directory / "Pack.zip" - pack.write_bytes(b"stale") - with writing_pack(str(pack)) as zf: - zf.writestr("new.bin", b"whole") - with zipfile.ZipFile(pack) as zf: - self.assertEqual(zf.namelist(), ["new.bin"]) - self.assertEqual(sorted(p.name for p in directory.iterdir()), ["Pack.zip"]) - - def test_no_pack_is_opened_on_its_final_name(self): - source = script_source("generate_pack.py") - self.assertNotIn('ZipFile(zip_path, "w"', source) - - -class EverySharedGroupServesAPlatform(unittest.TestCase): - """Six of the eight shared groups injected nothing: fuse, mt32 and - jiffydos were included by no platform, and kronos, keropi and ep128emu - repeated System.dat entry for entry. load_platform_config keeps the - platform's own entry, so a hash corrected there changed no pack, no - verify and no manifest, and nothing said so.""" - - def test_each_group_contributes_an_entry_somewhere(self): - from model.registry import list_registered_platforms - from model.platforms import load_platform_config - - platforms_dir = str(ROOT / "platforms") - with (ROOT / "platforms" / "_shared.yml").open(encoding="utf-8") as handle: - groups = set((yaml.safe_load(handle) or {}).get("shared_groups") or {}) - served = { - entry.get("shared_group") - for name in list_registered_platforms(platforms_dir) - for system in load_platform_config(name, platforms_dir).get("systems", {}).values() - for entry in system.get("files", []) - } - self.assertEqual(sorted(groups - served), []) - - -class PatchesTargetWhatRuns(unittest.TestCase): - """mock.patch.object with create set to True builds an attribute on a - module when the name is missing: packextras imported resolve_platform_cores - inside the function, the patch created a global nobody read, and the - real function walked the repository while the test claimed to isolate - it.""" - - def test_no_test_creates_the_attribute_it_patches(self): - needle = "create" + "=True" - offenders = [] - for path in sorted((ROOT / "tests").glob("test_*.py")): - for number, line in enumerate(path.read_text(encoding="utf-8").splitlines(), 1): - code = line.split("#", 1)[0] - if needle in code: - offenders.append(f"{path.name}:{number}") - self.assertEqual(offenders, []) - - -class StandaloneCopiesNameTheirSource(unittest.TestCase): - """The registry's anchor names one path per file for every platform, - while each manifest places the file its own way, and the installer copied - nothing where the two differed (EmuDeck's aes_keys.txt, Batocera's - switch/prod.keys).""" - - def _placed(self, copies, dests): - from packs.standalone import _placed_copies - - return _placed_copies(copies, dests) - - def test_a_path_tail_finds_the_file(self): - (copy,) = self._placed( - [{"file": "GC/USA/IPL.bin"}], - ["dolphin-emu/Sys/GC/USA/IPL.bin", "dolphin-emu/Sys/GC/EUR/IPL.bin"], - ) - self.assertEqual(copy["source"], "dolphin-emu/Sys/GC/USA/IPL.bin") - - def test_the_tail_with_least_on_top_wins(self): - (copy,) = self._placed( - [{"file": "GC/USA/IPL.bin"}], - ["bios/GC/USA/IPL.bin", "bios/dolphin-emu/Sys/GC/USA/IPL.bin"], - ) - self.assertEqual(copy["source"], "bios/GC/USA/IPL.bin") - - def test_a_unique_name_finds_the_file_elsewhere(self): - (copy,) = self._placed( - [{"file": "Citra/sysdata/aes_keys.txt"}], ["aes_keys.txt", "bios.bin"] - ) - self.assertEqual(copy["source"], "aes_keys.txt") - - def test_an_ambiguous_or_present_file_is_left_as_written(self): - copies = [{"file": "prod.keys"}, {"file": "IPL.bin"}] - placed = self._placed(copies, ["prod.keys", "a/IPL.bin", "b/IPL.bin"]) - self.assertEqual(placed, copies) - - -class StandaloneCopiesComeFromTheProfiles(unittest.TestCase): - """The copies were a hand-kept list of eight emulators while 61 profiles - give their data_root with the code that builds it: a machine with only - standalone Cemu got none of its keys.""" - - CEMU = { - "data_root": { - "linux": {"path": "$XDG_DATA_HOME/Cemu, else ~/.local/share/Cemu", - "source_ref": "x"}, - "windows": {"path": "%APPDATA%/Cemu", "source_ref": "x"}, - "macos": {"path": "~/Library/Application Support/Cemu", "source_ref": "x"}, - }, - "files": [ - {"name": "keys.txt", "path": "Cemu/keys.txt", "standalone_path": "keys.txt"}, - {"name": "CafeCn.ttf", "path": "Cemu/mlc01/CafeCn.ttf", - "standalone_path": "mlc01/sys/CafeCn.ttf"}, - {"name": "gone.bin", "path": "Cemu/gone.bin", "standalone_path": "gone.bin"}, - {"name": "core.bin", "path": "Cemu/core.bin", "standalone_path": "core.bin", - "mode": "libretro"}, - ], - } - - def _copies(self, profiles, dests, declared=()): - from packs.standalone import _profile_copies - - return _profile_copies(profiles, dests, list(declared)) - - def test_each_file_goes_under_the_data_root(self): - copies = self._copies({"cemu": self.CEMU}, - ["Cemu/keys.txt", "Cemu/mlc01/CafeCn.ttf", "Cemu/core.bin"]) - self.assertEqual(copies, [ - {"file": "Cemu/keys.txt", "targets": { - "linux": ["$HOME/.local/share/Cemu"], "windows": ["%APPDATA%\\Cemu"], - "darwin": ["$HOME/Library/Application Support/Cemu"]}}, - {"file": "Cemu/mlc01/CafeCn.ttf", "targets": { - "linux": ["$HOME/.local/share/Cemu/mlc01/sys"], - "windows": ["%APPDATA%\\Cemu\\mlc01\\sys"], - "darwin": ["$HOME/Library/Application Support/Cemu/mlc01/sys"]}}, - ]) - - def test_a_place_no_run_can_name_is_left_out(self): - melonds = { - "data_root": { - "windows": {"path": "", "source_ref": "x"}, - "linux": {"path": "$XDG_CONFIG_HOME/melonDS, else ~/.config/melonDS", - "source_ref": "x"}, - }, - "files": [{"name": "dsi_sd_card.bin", "standalone_path": "dsisd.bin"}], - } - (copy,) = self._copies({"melonds": melonds}, ["dsi_sd_card.bin"]) - self.assertEqual(copy, {"file": "dsi_sd_card.bin", - "targets": {"linux": ["$HOME/.config/melonDS"]}, - "as": "dsisd.bin"}) - - def test_the_registry_keeps_what_it_already_names(self): - declared = [{"pattern": "k*.txt", "targets": {"linux": ["$HOME/.local/share/Cemu"]}}] - (copy, _font) = self._copies({"cemu": self.CEMU}, - ["Cemu/keys.txt", "Cemu/mlc01/CafeCn.ttf"], declared) - self.assertNotIn("linux", copy["targets"]) - self.assertIn("windows", copy["targets"]) - - def test_a_file_found_by_content_is_left_to_the_scan(self): - amiberry = { - "data_root": {"linux": {"path": "~/Amiberry", "source_ref": "x"}}, - "files": [{"name": "cd32fmv.rom", "path": "roms/cd32fmv.rom", - "standalone_path": "cd32fmv.rom", "found_by": "content"}], - } - self.assertEqual(self._copies({"amiberry": amiberry}, ["roms/cd32fmv.rom"]), []) - - def test_the_published_retroarch_list_reaches_cemu(self): - import json - - manifest = json.loads((ROOT / "install" / "retroarch.json").read_text()) - files = {copy["file"]: copy for copy in manifest["standalone_copies"] - if "file" in copy} - for name in ("Cemu/keys.txt", "Cemu/otp.bin", "Cemu/seeprom.bin"): - with self.subTest(name=name): - self.assertEqual(files[name]["targets"]["linux"], ["$HOME/.local/share/Cemu"]) - - -class ADamagedArchiveIsNotPacked(unittest.TestCase): - """A member whose bytes fail their CRC stops the build. The builder once - copied the damaged archive into the pack "for verify to flag", which - nothing did.""" - - def test_the_rebuild_refusal_reaches_the_run(self): - import zipfile - - from packs.archive import DamagedArchiveError, add_zip_to_pack - - with tempfile.TemporaryDirectory() as directory: - source = Path(directory) / "set.zip" - with zipfile.ZipFile(source, "w", zipfile.ZIP_STORED) as zf: - zf.writestr("rom.bin", b"A" * 64) - data = bytearray(source.read_bytes()) - data[data.index(b"A" * 64)] ^= 0xFF - source.write_bytes(bytes(data)) - pack = Path(directory) / "pack.zip" - with zipfile.ZipFile(pack, "w") as target: - with self.assertRaises(DamagedArchiveError) as caught: - add_zip_to_pack(str(source), "set.zip", target) - self.assertNotIn("set.zip", target.namelist()) - self.assertIsInstance(caught.exception, OSError) - self.assertIn("set.zip", str(caught.exception)) - - -class APackedArchiveKeepsItsBytes(unittest.TestCase): - """Packs rebuilt about 1,500 ZIPs in a fixed byte order while the install - list kept the collection's hash: an extracted pack failed --check on each.""" - - def test_the_member_is_the_source_byte_for_byte(self): - import hashlib - import zipfile - - from packs.archive import add_zip_to_pack - - with tempfile.TemporaryDirectory() as directory: - source = Path(directory) / "set.zip" - with zipfile.ZipFile(source, "w", zipfile.ZIP_DEFLATED) as zf: - zf.writestr(zipfile.ZipInfo("rom.bin", (1999, 1, 2, 3, 4, 5)), b"rom" * 40) - pack = Path(directory) / "pack.zip" - with zipfile.ZipFile(pack, "w") as target: - add_zip_to_pack(str(source), "set.zip", target) - with zipfile.ZipFile(pack) as packed: - inner = packed.read("set.zip") - self.assertEqual(hashlib.sha1(inner).hexdigest(), - hashlib.sha1(source.read_bytes()).hexdigest()) - - -class PackReadmesSayWhatTheInstallerDoes(unittest.TestCase): - """The EmuDeck README promised keys set up automatically (they need - --standalone-copies) and gave a Citra path the installer never uses, and the - RetroArch README offered only `| sh`, which Windows cannot run.""" - - def _guide(self, platform: str) -> str: - from packs.readme import build_readme - - registry = yaml.safe_load((ROOT / "platforms" / "_registry.yml").read_text()) - install = registry["platforms"][platform].get("install") or {} - text = build_readme(platform, platform, "", 1, 1, - detect=install.get("detect", []), - standalone_copies=install.get("standalone_copies", [])) - return text[text.index("INSTALLATION"):text.index("TROUBLESHOOTING")] - - def test_retroarch_offers_the_windows_installer(self): - from sitegen.guidedata import install_ps1, install_sh - - guide = self._guide("retroarch") - self.assertIn(f"{install_sh()} | sh", guide) - self.assertIn(f"{install_ps1()} | iex", guide) - - def test_emudeck_keys_match_the_registry_and_the_flag(self): - import re - - guide = self._guide("emudeck") - self.assertIn("--standalone-copies", guide) - self.assertNotIn("emulator keys automatically", guide) - self.assertNotIn("handles this for you", guide) - with (ROOT / "platforms" / "_registry.yml").open(encoding="utf-8") as handle: - registry = yaml.safe_load(handle) - targets = { - target.rstrip("/").replace("$HOME", "~") - for copy in registry["_standalone_copies"] - for target in copy.get("targets", {}).get("linux", []) - } - named = { - path.rstrip("/") for path in re.findall(r"-> (~/\S+)", guide) - } - self.assertEqual(sorted(named - targets), []) - - def test_retropie_never_sends_a_pc_to_the_linux_partition(self): - guide = self._guide("retropie") - from sitegen.guidedata import install_sh - - self.assertNotIn("Put the SD card in your PC", guide) - self.assertIn(f"{install_sh()} | sh", guide) - - -class AutoFetchReadsListsAndPlacesWithoutClobbering(unittest.TestCase): - """A profile hash list (daedalusx64's n64.psh) stopped auto_fetch with - an unhashable-type error, and a fetched file went to the first folder - sharing one word of the system slug (nintendo-64 into Nintendo/SNES), - overwriting a same-named file there.""" - - def test_a_hash_list_is_every_accepted_revision(self): - import hashlib - - from scripts.acquire import fetch as acquire_fetch - - data = b"second revision" - entry = {"sha1": ["0" * 40, hashlib.sha1(data).hexdigest()]} - self.assertTrue(acquire_fetch.verify_content(data, entry)) - db = {"files": {hashlib.sha1(data).hexdigest(): {"path": "bios/x/n64.psh"}}, - "indexes": {"by_md5": {}}} - self.assertEqual(acquire_fetch.step1_crossref_db(entry, db), "bios/x/n64.psh") - - @staticmethod - def _tables(system: str, folder: str) -> tuple[dict, dict]: - """Hash tables where the collection files *system* under *folder*.""" - return {"system_folders": {system: {folder}}}, {} - - def test_the_review_folder_is_used_and_nothing_is_overwritten(self): - from scripts.acquire import placement as acquire_placement - - with tempfile.TemporaryDirectory() as directory: - bios = Path(directory) - for folder in ("Nintendo/SNES", "Nintendo/N64", "Nintendo/Nintendo 64DD"): - (bios / folder).mkdir(parents=True) - held = bios / "Nintendo" / "N64" / "n64.psh" - held.write_bytes(b"other revision") - placed = Path(acquire_placement.place_file( - b"fetched", {"name": "n64.psh", "system": "nintendo-64"}, str(bios), {}, - *self._tables("nintendo-64", "bios/Nintendo/N64/"), - ).path) - self.assertEqual(placed.parent.parent, bios / "Nintendo" / "N64") - self.assertEqual(placed.parent.name, ".variants") - self.assertEqual(held.read_bytes(), b"other revision") - - def test_a_slug_inside_another_folder_name_is_no_folder(self): - """'ds' is in '3DS': the DS firmware went to Nintendo/3DS.""" - from scripts.acquire import placement as acquire_placement - - with tempfile.TemporaryDirectory() as directory: - bios = Path(directory) - for folder in ("Nintendo/3DS", "Nintendo/Nintendo DS"): - (bios / folder).mkdir(parents=True) - placed = Path(acquire_placement.place_file( - b"fw", {"name": "firmware.bin", "system": "nintendo-ds"}, str(bios), {}, - *self._tables("nintendo-ds", "bios/Nintendo/Nintendo DS/"), - ).path) - self.assertEqual(placed, bios / "Nintendo" / "Nintendo DS" / "firmware.bin") - - def test_an_unsettled_folder_stays_out_of_bios(self): - """snk-neogeo went to a new bios/Unknown/snk-neogeo/.""" - import hashlib - - from scripts.acquire import placement as acquire_placement - - with tempfile.TemporaryDirectory() as directory: - bios, acquired = Path(directory, "bios"), Path(directory, "acquire") - bios.mkdir() - placed = acquire_placement.place_file( - b"set", {"name": "neogeo.zip", "system": "snk-neogeo"}, str(bios), {}, - {}, {}, acquire_dir=acquired, - ) - self.assertTrue(placed.kept_out) - self.assertEqual(Path(placed.path), acquired / hashlib.sha1(b"set").hexdigest()) - self.assertEqual(list(bios.iterdir()), []) - - -class NoParserAcceptsAnAbbreviation(unittest.TestCase): - """argparse completes a prefix: `slots.py --emulator dolphin` became - --emulators-dir dolphin and reported 0 contested destinations, exit 0, and - `pipeline.py --all` became --all-variants and built six packs per - platform. The flags read like other scripts' and were never refused.""" - - def test_every_parser_refuses_prefixes(self): - import ast - - lax = [] - for path in sorted([*(ROOT / "scripts").rglob("*.py"), ROOT / "install.py"]): - for node in ast.walk(ast.parse(path.read_text(encoding="utf-8"))): - if not isinstance(node, ast.Call): - continue - func = node.func - name = func.attr if isinstance(func, ast.Attribute) else getattr(func, "id", "") - if name != "ArgumentParser": - continue - if not any( - kw.arg == "allow_abbrev" - and isinstance(kw.value, ast.Constant) and kw.value.value is False - for kw in node.keywords - ): - lax.append(f"{path.relative_to(ROOT)}:{node.lineno}") - self.assertEqual(lax, []) - - -class FaqRegressions(unittest.TestCase): - """The FAQ states facts the code owns, and these tie it back to the source. - - Three of its claims had drifted: a pinned MAME version, Adler-32 - attributed to Dolphin's IPL instead of its DSP ROMs, and a verbose - per-emulator report described as the only way to catch a bad file on an - existence platform. Readers act on all three. - """ - - @staticmethod - def _faq() -> str: - # The questions about hashes and checks moved to the technical FAQ. - return "\n\n".join( - (ROOT / "wiki" / name).read_text(encoding="utf-8") - for name in ("faq.md", "technical-faq.md") - ) - - @staticmethod - def _profile(key: str) -> dict: - with (ROOT / "emulators" / f"{key}.yml").open(encoding="utf-8") as handle: - return yaml.safe_load(handle) - - def test_the_romset_table_is_written_from_the_profiles(self): - # Typed by hand, the table and the prose under it kept MAME 0.160 - # and FinalBurn Neo 1.0.0.2, versions no source at the pins states, - # and the test holding them to the profiles kept the errors in step. - from sitegen import emulatormetadata - from model.profiles import load_emulator_profiles - - profiles = load_emulator_profiles(str(ROOT / "emulators"), skip_aliases=False) - page = (ROOT / "wiki" / "technical-faq.md").read_text(encoding="utf-8") - self.assertEqual( - page, emulatormetadata.with_romset_table(page, profiles), - "wiki/technical-faq.md romset table is stale: run scripts/generate_site.py", - ) - prose = page.split("### How this is known", 1)[1].split("\n## ", 1)[0] - self.assertIsNone(re.search(r"\(0\.\d", prose), - "the prose under the table types a version again") - - def test_adler32_is_attributed_to_the_files_that_carry_it(self): - dolphin = self._profile("dolphin") - carriers = { - f["name"] for f in dolphin["files"] if f.get("known_hash_adler32") - } - self.assertTrue(carriers, "dolphin.yml declares no Adler-32 hash") - sentence = self._faq().split("Adler-32", 1)[1].split("\n\n", 1)[0] - for name in carriers: - self.assertIn(name, sentence, f"FAQ omits the Adler-32 file {name}") - self.assertNotIn( - "IPL.bin", carriers, - "IPL.bin gained an Adler-32 hash, but the docs say it has none", - ) - for page in ("faq.md", "profiling.md"): - text = (ROOT / "wiki" / page).read_text(encoding="utf-8") - for line in text.splitlines(): - if "Adler-32" in line or "adler32" in line: - self.assertNotIn( - "IPL", line, - f"wiki/{page} ties Adler-32 back to IPL: {line.strip()}", - ) - - def test_existence_platforms_are_not_told_the_verbose_report_is_the_only_check(self): - self.assertIn( - "DISCREPANCY", - self._faq(), - "the FAQ must name the check the platform report performs itself", - ) - self.assertIn( - 'result["discrepancy"]', - script_source("verify.py"), - "verify.py no longer raises the discrepancy the FAQ advertises", - ) - - -class CatalogRatioRegressions(unittest.TestCase): - """The catalog-matched count must read the same on every surface. - - The home page, the provenance page, the README and the stats export each - used to count matches on their own. Two of them dropped the systems - scope, so the site published 566 and 553 for the same quantity, one click - apart, and the export paired the wider number with composition.systems as - its denominator. - """ - - _SURFACES = ("scripts/generate_site.py", "scripts/generate_readme.py") - - def test_no_surface_counts_matches_on_its_own(self): - for relative in self._SURFACES: - tree = ast.parse(script_source(relative.removeprefix("scripts/"))) - inline = [ - node.lineno - for node in ast.walk(tree) - if isinstance(node, ast.Call) - and getattr(node.func, "id", "") == "sum" - and "provenance" in ast.dump(node) - ] - self.assertEqual( - inline, - [], - f"{relative} counts provenance matches inline at {inline}; " - "call common.count_catalog_matched instead", - ) - - def test_arcade_and_engine_data_stay_out_of_the_ratio(self): - from scripts.model.composition import compute_composition, count_catalog_matched - - db = { - "files": { - "a": {"path": "bios/Sony/PlayStation/scph5501.bin", "size": 1, - "provenance": {"redump": {}}}, - "b": {"path": "bios/Arcade/Arcade/neogeo.zip", "size": 1, - "provenance": {"no-intro": {}}}, - "c": {"path": "bios/ScummVM/soundfonts/Roland.sf2", "size": 1, - "provenance": {"tosec": {}}}, - "d": {"path": "bios/Sega/Saturn/sega_101.bin", "size": 1}, - } - } - self.assertEqual(count_catalog_matched(db), 1) - self.assertEqual(compute_composition(db)["systems"]["files"], 2) - - def test_engine_and_publisher_trees_are_game_data(self): - """Engine data collected under `Game Engines/` and under a game - publisher counted as console and computer system files: 7 697 of - them made the README announce 13 564 system files.""" - from scripts.model.composition import composition_tier - - for path in ( - "bios/Game Engines/C-Dogs SDL/cdogs/data/guns.json", - "bios/Id Software/Quake III Arena/baseq3/pak1.pk3", - "bios/Epic MegaGames/Jazz Jackrabbit 2/jazz2/Source/share.j2e", - "bios/RPG Maker/easyrpg/rtp/2000/Backdrop/Bridge.png", - ): - self.assertEqual(composition_tier(path), "game_data", path) - self.assertEqual(composition_tier("bios/Sony/PlayStation/scph5501.bin"), "systems") - self.assertEqual(composition_tier("bios/Microsoft/MSX/MSX2.ROM"), "systems") - - def test_readme_ratio_matches_the_database(self): - from scripts.model.composition import compute_composition, count_catalog_matched - from scripts.model.database import load_database - - database = ROOT / "database.json" - if not database.exists(): - self.skipTest("database.json not generated") - db = load_database(str(database)) - readme = (ROOT / "README.md").read_text(encoding="utf-8") - match = re.search( - r"\*\*([\d,]+) of ([\d,]+) system files\*\* matched to", readme - ) - if match is None: - # The README states no ratio since it leads to the site: a ratio - # it states must still be the database's. - return - matched, total = (int(g.replace(",", "")) for g in match.groups()) - self.assertEqual(matched, count_catalog_matched(db)) - self.assertEqual(total, compute_composition(db)["systems"]["files"]) - - -class PipelineRegressions(unittest.TestCase): - def test_integrity_checks_the_variants_step_4_built(self): - """Step 6 ran --verify-packs without --all-variants: the five - narrowed packs were never opened and an empty _Platform passed.""" - import argparse - - def command(**flags) -> list[str]: - base = {"output_dir": "dist", "target": None, "all_variants": False} - return checks.integrity_command(argparse.Namespace(**{**base, **flags})) - - self.assertIn("--all-variants", command(all_variants=True)) - self.assertNotIn("--all-variants", command()) - self.assertEqual(command(target="switch")[-2:], ["--target", "switch"]) - - @staticmethod - def _verified(label: str, ok: int, total: int, core_files: int = 0) -> dict: - """One platform as verify.py --destinations records it.""" - key = label.lower().replace(" ", "") - return {key: {"platform": key, "label": label, "ok": ok, "total": total, - "core_files": core_files, "pack_destinations": []}} - - @staticmethod - def _packed(label: str, ok: int, total: int, core_files: int = 0, - unsafe_excluded: int = 0) -> dict: - """One full pack as generate_pack.py --counts records it.""" - return {"label": label, "platforms": [label.lower().replace(" ", "")], - "archive": "pack.zip", "ok": ok, "total": total, - "core_files": core_files, "unsafe_excluded": unsafe_excluded, "trees": []} - - def test_missing_pack_is_a_consistency_failure(self): - verify = self._verified("RetroArch", 2, 2) - with contextlib.redirect_stdout(io.StringIO()): - self.assertFalse(consistency.compare_counts(verify, [])) - - def test_display_name_and_registry_id_meet_by_id(self): - verify = self._verified("MiSTer FPGA", 65, 65) - pack = {**self._packed("misterfpga", 65, 65), "platforms": ["misterfpga"]} - with contextlib.redirect_stdout(io.StringIO()): - self.assertTrue(consistency.compare_counts(verify, [pack])) - - def test_the_cores_share_is_compared_too(self): - """RomM passed this step while verify counted 412 core files and game - data in the pack and the builder placed 60.""" - verify = self._verified("RomM", 383, 383, core_files=412) - pack = self._packed("RomM", 383, 383, core_files=60) - with contextlib.redirect_stdout(io.StringIO()) as out: - self.assertFalse(consistency.compare_counts(verify, [pack])) - self.assertIn("RomM: MISMATCH core files verify 412 != pack 60", out.getvalue()) - agreed = self._verified("RomM", 383, 383, core_files=60) - with contextlib.redirect_stdout(io.StringIO()): - self.assertTrue(consistency.compare_counts(agreed, [pack])) - - def test_an_exclusion_never_covers_a_file_verify_counts_ok(self): - """An existence platform packs a file whose hash disagrees and a hash - platform's verify reports it untested: exclusions that make up the - difference hid the very divergence this step exists to catch.""" - verify = self._verified("RetroArch", 3, 3) - pack = self._packed("RetroArch", 2, 3, unsafe_excluded=1) - with contextlib.redirect_stdout(io.StringIO()) as out: - self.assertFalse(consistency.compare_counts(verify, [pack])) - self.assertIn("(1 unsafe excluded)", out.getvalue()) - - def test_a_pack_more_optimistic_than_verify_is_a_failure(self): - """The invariant held one way only: a pack counting more OK files - than the report passed as 'pack resolves more'.""" - verify = self._verified("DupTest", 0, 1) - pack = self._packed("DupTest", 1, 1) - with contextlib.redirect_stdout(io.StringIO()): - self.assertFalse(consistency.compare_counts(verify, [pack])) - - def test_nothing_read_is_not_consistent(self): - """A build that recorded nothing must not pass with no platform compared.""" - with contextlib.redirect_stdout(io.StringIO()): - self.assertFalse(consistency.compare_counts(self._verified("RetroArch", 2, 2), [])) - self.assertFalse(consistency.compare_counts({}, [])) - - def test_an_unwritten_record_file_is_a_failure(self): - """A step that crashed leaves its file empty: the check fails, it - does not compare nothing and pass.""" - with tempfile.TemporaryDirectory() as root: - empty = os.path.join(root, "empty.json") - Path(empty).write_text("") - with contextlib.redirect_stdout(io.StringIO()) as out: - self.assertFalse(consistency.check_consistency(empty, empty)) - self.assertFalse(consistency.check_pack_destinations(empty, empty)) - self.assertIn("unreadable counts", out.getvalue()) - - def test_pack_without_verify_result_is_a_failure(self): - verify = self._verified("RetroArch", 2, 2) - packs = [self._packed("RetroArch", 2, 2), self._packed("Batocera", 2, 2)] - with contextlib.redirect_stdout(io.StringIO()) as out: - self.assertFalse(consistency.compare_counts(verify, packs)) - self.assertIn("Batocera: pack with no verify result", out.getvalue()) - - def test_a_build_that_recorded_nothing_skips_step_five(self): - """An empty counts file is a build that stopped before its record: - step 4 already fails, and step 5 has nothing to compare.""" - import argparse - - args = argparse.Namespace(source="full", all_variants=False, skip_packs=True) - with tempfile.TemporaryDirectory() as root: - empty = os.path.join(root, "counts.json") - Path(empty).write_text("") - step_results: dict = {} - with contextlib.redirect_stdout(io.StringIO()): - checks.check_steps(args, step_results, pack_counts_file=empty, - destinations_file=empty) - self.assertIs(step_results["consistency"], results.SKIPPED) - - def test_only_the_full_variant_is_recorded(self): - """--all-variants built six packs under one label, and the last won.""" - source = script_source("generate_pack.py") - self.assertIn('[] if record_counts and (source, required_only) == ("full", False) else None', - source) - - def test_slot_step_reaches_the_summary(self): - source = script_source("pipeline.py") - self.assertIn('results["slots"] = ok', source) - - def test_every_refresh_failure_reaches_pipeline_exit_status(self): - for failed_label in ( - "2 refresh data directories", - "2a refresh MAME hashes", - "2a2 refresh FBNeo hashes", - ): - with self.subTest(failed_label=failed_label): - def fake_run(_command, label, failed_label=failed_label): - return label != failed_label, "RetroArch: 1/1 OK\n" - - argv = ["pipeline.py", "--skip-packs", "--skip-docs"] - with ( - mock.patch.object(sys, "argv", argv), - mock.patch.object(runner, "run", side_effect=fake_run), - contextlib.redirect_stdout(io.StringIO()), - self.assertRaises(SystemExit) as raised, - ): - pipeline.main() - self.assertEqual(raised.exception.code, 1) - - - def test_a_targeted_export_reads_a_full_model(self): - """--target wrote truth// only, but the export read truth/.""" - commands: list[list[str]] = [] - - def fake_run(command, _label): - commands.append([str(part) for part in command]) - return True, "RetroArch: 1/1 OK\n" - - argv = ["pipeline.py", "--offline", "--skip-packs", "--skip-docs", - "--with-export", "--target", "switch"] - # The originals the offline export patches are not cached in a - # checkout: the run would be refused before any step. - with mock.patch.object(sys, "argv", argv), mock.patch.object( - runner, "run", side_effect=fake_run - ), mock.patch.object(pipeline, "refuse_offline_export_without_originals"), \ - contextlib.redirect_stdout(io.StringIO()), contextlib.suppress(SystemExit): - pipeline.main() - truth_runs = [c for c in commands if "scripts/generate_truth.py" in c] - export = next(c for c in commands if "scripts/export_native.py" in c) - read_dir = export[export.index("--truth-dir") + 1] - full_models = [ - c for c in truth_runs - if "--target" not in c and c[c.index("--output-dir") + 1] == read_dir - ] - self.assertTrue(full_models, truth_runs) - - -class SchemaFormatsAreChecked(unittest.TestCase): - """date-time and uri need jsonschema's format extras. Without them the - published format constraints were accepted unread.""" - - @unittest.skipUnless(HAS_JSONSCHEMA, "validating a schema needs jsonschema") - def test_a_missing_checker_is_named(self): - from schemas import validators - - empty = mock.Mock(checkers={}) - with mock.patch.object(validators, "FormatChecker", return_value=empty): - self.assertEqual(validators.unchecked_formats(), ["date-time", "uri"]) - - def test_every_install_asks_for_the_extras(self): - for path in (".github/workflows/validate.yml", ".github/workflows/deploy-site.yml", - "pyproject.toml"): - text = (ROOT / path).read_text(encoding="utf-8") - with self.subTest(path=path): - self.assertNotRegex(text, r"jsonschema(?!\[format)[=>]") - - -class ResolverRegressions(unittest.TestCase): - def _database(self, entries: dict[str, Path], suffix: str | None = None) -> dict: - files = {} - by_name: dict[str, list[str]] = {} - by_suffix: dict[str, list[str]] = {} - for name, path in entries.items(): - payload = path.read_bytes() - sha1 = hashlib.sha1(payload).hexdigest() - md5 = hashlib.md5(payload).hexdigest() - sha256 = hashlib.sha256(payload).hexdigest() - files[sha1] = { - "path": str(path), - "name": name, - "size": len(payload), - "md5": md5, - "sha256": sha256, - "crc32": "00000000", - } - by_name.setdefault(name, []).append(sha1) - if suffix and name == "firmware.bin": - by_suffix.setdefault(suffix, []).append(sha1) - return { - "files": files, - "indexes": { - "by_name": by_name, - "by_md5": {entry["md5"]: sha1 for sha1, entry in files.items()}, - "by_sha256": { - entry["sha256"]: sha1 for sha1, entry in files.items() - }, - "by_crc32": {}, - "by_path_suffix": by_suffix, - }, - } - - def test_hash_identity_wins_over_wrong_destination_hint(self): - with tempfile.TemporaryDirectory() as directory: - root = Path(directory) - wrong = root / "wrong" / "firmware.bin" - correct = root / "correct" / "firmware.bin" - wrong.parent.mkdir() - correct.parent.mkdir() - wrong.write_bytes(b"wrong") - correct.write_bytes(b"correct") - db = self._database( - {"firmware.bin": wrong, "correct-name.bin": correct}, - suffix="Console/USA/firmware.bin", - ) - expected = hashlib.sha1(b"correct").hexdigest() - path, status = resolve_local_file( - {"name": "firmware.bin", "sha1": expected}, - db, - dest_hint="Console/USA/firmware.bin", - ) - self.assertEqual(path, str(correct)) - self.assertEqual(status, "sha1_exact") - - def test_name_cannot_mask_a_declared_hash_mismatch(self): - with tempfile.TemporaryDirectory() as directory: - path = Path(directory) / "firmware.bin" - path.write_bytes(b"wrong") - db = self._database({"firmware.bin": path}) - resolved, status = resolve_local_file( - {"name": "firmware.bin", "sha1": "f" * 40}, db - ) - self.assertEqual(resolved, str(path)) - self.assertEqual(status, "hash_mismatch") - - -class OneBaselineVerdict(unittest.TestCase): - """The builder and the manifest each wrote the platform baseline. - - The builder looked inside a zipped_file archive whatever the outer - resolution said, the manifest only after a hash_mismatch. An archive - found by name without the member Batocera checks left the pack and - stayed in the manifest. A slot override replaced a release asset in the - manifest and not in the pack. - """ - - def _archive(self, directory: Path, member: str) -> str: - path = directory / "dragon32.zip" - with zipfile.ZipFile(path, "w") as archive: - archive.writestr(member, b"rom") - return str(path) - - def test_a_missing_member_is_refused_whatever_the_outer_status(self): - from scripts.resolve.acceptance import baseline_verdict - - entry = {"name": "dragon32.zip", "zipped_file": "d32.rom", "md5": ""} - with tempfile.TemporaryDirectory() as directory: - path = self._archive(Path(directory), "other.rom") - status, refusal = baseline_verdict(entry, path, "name_exact", "md5") - self.assertEqual(refusal, "d32.rom not found inside ZIP") - # An existence frontend never opens it. - self.assertEqual( - baseline_verdict(entry, path, "name_exact", "existence"), - ("name_exact", None), - ) - - def test_the_pack_check_reads_the_same_verdict(self): - """--verify-packs called the archive missing: its own rule looked - inside only after a hash_mismatch, and an archive found by name - without d32.rom is one the builder left out on purpose.""" - import hashlib - - from scripts.packs.platformcheck import _intentional_hash_exclusion - - entry = {"name": "dragon32.zip", "zipped_file": "d32.rom", "md5": ""} - with tempfile.TemporaryDirectory() as directory: - path = self._archive(Path(directory), "other.rom") - sha1 = hashlib.sha1(Path(path).read_bytes()).hexdigest() - db = {"files": {sha1: {"path": path, "name": "dragon32.zip", "sha1": sha1}}, - "indexes": {"by_name": {"dragon32.zip": [sha1]}, "by_md5": {}, - "by_path_suffix": {}, "by_crc32": {}}} - self.assertTrue(_intentional_hash_exclusion([entry], db, verification_mode="md5")) - self.assertFalse( - _intentional_hash_exclusion([entry], db, verification_mode="existence") - ) - - def test_the_builder_accepts_what_verify_accepts(self): - """verify took a ZIP by its composite, but the builder compared exact - md5s and refused it when another declared hash disagreed. A value cut - short accepts nothing: Batocera compares the whole md5 string - (batocera-systems:1088), and verify accepted any prefix, down to one - digit.""" - import hashlib - - from scripts.core.hashing import md5_composite - from scripts.resolve.acceptance import baseline_verdict, digest_verdict - - with tempfile.TemporaryDirectory() as directory: - loose = Path(directory) / "abc.bin" - loose.write_bytes(b"abc") - md5 = hashlib.md5(b"abc").hexdigest() - truncated = {"name": "abc.bin", "md5": md5[:29], "crc32": "deadbeef"} - self.assertIsNotNone( - baseline_verdict(truncated, str(loose), "hash_mismatch", "md5")[1] - ) - for length in (1, 29, 31): - self.assertFalse( - digest_verdict({"md5": md5[:length]}, 3, lambda: {"md5": md5}, "md5") - ) - self.assertTrue(digest_verdict({"md5": md5}, 3, lambda: {"md5": md5}, "md5")) - archive = self._archive(Path(directory), "rom.bin") - composite = {"name": "dragon32.zip", "md5": md5_composite(archive), - "crc32": "deadbeef"} - self.assertEqual( - baseline_verdict(composite, archive, "hash_mismatch", "md5"), - ("frontend_digest_exact", None), - ) - - def test_a_composite_only_archive_ignores_its_raw_md5(self): - """Recalbox hashes a .zip by its members (Bios.cpp:64-68), and the - pack check accepted the container's own md5 before the composite: - neocd.bin shipped as neocdz.zip passed while Recalbox marks it red.""" - import hashlib - - from scripts.core.hashing import md5_composite - from scripts.resolve.acceptance import digest_verdict - - with tempfile.TemporaryDirectory() as directory: - archive = self._archive(Path(directory), "rom.bin") - raw = hashlib.md5(Path(archive).read_bytes()).hexdigest() - members = md5_composite(archive) - for declared, accepted in ((raw, False), (members, True)): - entry = {"name": "dragon32.zip", "md5": declared, "zip_digest": "composite"} - with self.subTest(declared=declared): - self.assertIs( - digest_verdict(entry, 0, lambda: {"md5": raw}, "md5", "", - lambda: members), - accepted, - ) - plain = {"name": "dragon32.zip", "md5": raw} - self.assertTrue(digest_verdict(plain, 0, lambda: {"md5": raw}, "md5")) - - def test_a_release_asset_keeps_its_answer(self): - from scripts.resolve.packfiles import apply_override - - self.assertEqual( - apply_override("bios/x.bin", "/cache/big.bin", "release_asset"), - ("/cache/big.bin", "release_asset"), - ) - self.assertEqual( - apply_override("bios/x.bin", "bios/y.bin", "name_exact"), - ("bios/x.bin", "slot_arbitrated"), - ) - - def test_the_builder_and_the_manifest_read_the_same_rules(self): - source = script_source("generate_pack.py") - tree = ast.parse(source) - for name in ("build_platform_pack", "generate_manifest"): - function = next( - node for node in tree.body - if isinstance(node, ast.FunctionDef) and node.name == name - ) - body = ast.get_source_segment(source, function) or "" - with self.subTest(function=name): - self.assertIn("DeclarationJudge(", body) - self.assertNotIn('"slot_arbitrated"', body) - judge = next( - node for node in tree.body - if isinstance(node, ast.ClassDef) and node.name == "DeclarationJudge" - ) - body = ast.get_source_segment(source, judge) or "" - self.assertIn("baseline_verdict(", body) - self.assertIn("resolve_declaration(", body) - self.assertNotIn('"slot_arbitrated"', body) - - def test_verify_and_the_region_pass_resolve_as_the_builder(self): - """verify called common.resolve_local_file and put the slot override - first, the region pass passed a destination hint the builder never - gives: a gitignored file absent from bios/ read as missing in verify - while the pack shipped its cached release asset.""" - for module, name in (("verify.py", "_resolve_for_platform"), - ("packs/extraregions.py", "_ships")): - source = script_source(module) - function = next( - node for node in ast.parse(source).body - if isinstance(node, ast.FunctionDef) and node.name == name - ) - body = ast.get_source_segment(source, function) or "" - with self.subTest(function=name): - self.assertIn("resolve_declaration(", body) - self.assertNotIn("resolve_local_file(", body) - self.assertNotIn('"slot_arbitrated"', body) - - def test_verify_finds_the_cached_release_asset(self): - # verify imports the scripts directory's modules by their bare names. - from resolve import packfiles as packresolve - from scripts.packs.platformtally import _resolve_for_platform - - with tempfile.TemporaryDirectory() as directory: - cached = Path(directory) / "BIG.PUP" - cached.write_bytes(b"large firmware") - sha1 = hashlib.sha1(cached.read_bytes()).hexdigest() - db = {"files": {sha1: {"path": f"{directory}/absent/BIG.PUP", - "name": "BIG.PUP", "sha1": sha1}}, - "indexes": {"by_name": {"BIG.PUP": [sha1]}}} - entry = {"name": "BIG.PUP", "sha1": sha1, "destination": "BIG.PUP"} - # The record's path is a registered release asset. - registered = [f"{directory}/absent/BIG.PUP"] - with mock.patch.object( - packresolve, "fetch_large_file", return_value=str(cached) - ), mock.patch("model.largefiles.load_registered_paths", return_value=registered): - found = _resolve_for_platform( - entry, "sys", db, {}, None, {"BIG.PUP": "bios/other.bin"}, - "md5", {}, - ) - self.assertEqual(found, (str(cached), "release_asset")) - - -class PackExclusionRegressions(unittest.TestCase): - def test_slug_platform_core_requirement_uses_the_generated_destination(self): - with tempfile.TemporaryDirectory() as directory: - root = Path(directory) - platforms = root / "platforms" - platforms.mkdir() - core_payload = root / "extra.bin" - core_payload.write_bytes(b"mapped core payload") - core_sha1 = hashlib.sha1(core_payload.read_bytes()).hexdigest() - core_md5 = hashlib.md5(core_payload.read_bytes()).hexdigest() - database = { - "files": { - core_sha1: { - "name": "extra.bin", - "path": str(core_payload), - "md5": core_md5, - "size": core_payload.stat().st_size, - } - }, - "indexes": { - "by_name": {"extra.bin": [core_sha1]}, - "by_md5": {core_md5: core_sha1}, - "by_sha256": {}, - "by_crc32": {}, - "by_path_suffix": {}, - }, - } - config = { - "platform": "Slug platform", - "base_destination": "bios", - "verification_mode": "existence", - "cores": ["core_a"], - "systems": { - "console-a": { - "files": [ - { - "name": "base-a.bin", - "destination": "slug-a/base-a.bin", - } - ] - }, - "console-b": { - "files": [ - { - "name": "base-b.bin", - "destination": "slug-b/base-b.bin", - } - ] - }, - }, - } - (platforms / "slug.yml").write_text( - yaml.safe_dump(config), encoding="utf-8" - ) - profiles = { - "core_a": { - "emulator": "Core A", - "type": "libretro", - "systems": ["console-a"], - "files": [ - { - "name": "extra.bin", - "path": "extra.bin", - "sha1": core_sha1, - } - ], - } - } - pack = root / "pack.zip" - with zipfile.ZipFile(pack, "w", zipfile.ZIP_DEFLATED) as archive: - archive.writestr("slug-a/base-a.bin", b"baseline a") - archive.writestr("slug-b/base-b.bin", b"baseline b") - archive.writestr("slug-a/extra.bin", core_payload.read_bytes()) - - result = verify_pack_against_platform( - str(pack), - "slug", - str(platforms), - db=database, - emu_profiles=profiles, - ) - self.assertTrue(result[0], result[3]) - self.assertEqual(result[3], []) - self.assertEqual(result[6:8], (1, 1)) - - def _mismatch_fixture(self, root: Path, mode: str) -> tuple[dict, Path]: - """A platform declaring a hash the only local payload contradicts.""" - platforms = root / "platforms" - platforms.mkdir() - payload = root / "firmware.bin" - payload.write_bytes(b"wrong local variant") - sha1 = hashlib.sha1(payload.read_bytes()).hexdigest() - md5 = hashlib.md5(payload.read_bytes()).hexdigest() - database = { - "files": { - sha1: { - "name": "firmware.bin", - "path": str(payload), - "md5": md5, - "size": payload.stat().st_size, - } - }, - "indexes": { - "by_name": {"firmware.bin": [sha1]}, - "by_md5": {md5: sha1}, - "by_sha256": {}, - "by_crc32": {}, - "by_path_suffix": {}, - }, - } - config = { - "platform": f"Platform {mode}", - "verification_mode": mode, - "systems": { - "console": { - "files": [ - { - "name": "firmware.bin", - "destination": "firmware.bin", - "sha1": "f" * 40, - } - ] - } - }, - } - (platforms / "plat.yml").write_text(yaml.safe_dump(config), encoding="utf-8") - return database, platforms - - def test_hash_platform_accounts_for_an_unsafe_exclusion(self): - """A platform that reads the bytes would reject the local payload.""" - with tempfile.TemporaryDirectory() as directory: - root = Path(directory) - database, platforms = self._mismatch_fixture(root, "md5") - pack = root / "pack.zip" - with zipfile.ZipFile(pack, "w", zipfile.ZIP_DEFLATED) as archive: - archive.writestr("README.txt", "safe subset") - - result = verify_pack_against_platform( - str(pack), - "plat", - str(platforms), - db=database, - emu_profiles={}, - ) - self.assertTrue(result[0], result[3]) - self.assertEqual(result[3], []) - self.assertEqual(result[8], 1) - - def test_existence_platform_never_withholds_over_a_declared_hash(self): - """RetroArch and friends only look for the filename. - - An upstream hash the local dump contradicts must not remove a file the - frontend would have loaded, so its absence stays a conformance error. - """ - with tempfile.TemporaryDirectory() as directory: - root = Path(directory) - database, platforms = self._mismatch_fixture(root, "existence") - pack = root / "pack.zip" - with zipfile.ZipFile(pack, "w", zipfile.ZIP_DEFLATED) as archive: - archive.writestr("README.txt", "no firmware") - - result = verify_pack_against_platform( - str(pack), - "plat", - str(platforms), - db=database, - emu_profiles={}, - ) - self.assertFalse(result[0]) - self.assertTrue(any("baseline missing" in e for e in result[3]), result[3]) - self.assertEqual(result[8], 0) - - def test_unexplained_missing_file_still_fails_conformance(self): - with tempfile.TemporaryDirectory() as directory: - root = Path(directory) - platforms = root / "platforms" - platforms.mkdir() - config = { - "platform": "Missing", - "verification_mode": "existence", - "systems": { - "console": { - "files": [ - {"name": "absent.bin", "destination": "absent.bin"} - ] - } - }, - } - (platforms / "missing.yml").write_text( - yaml.safe_dump(config), encoding="utf-8" - ) - pack = root / "pack.zip" - with zipfile.ZipFile(pack, "w", zipfile.ZIP_DEFLATED) as archive: - archive.writestr("README.txt", "incomplete") - database = { - "files": {}, - "indexes": { - "by_name": {}, - "by_md5": {}, - "by_sha256": {}, - "by_crc32": {}, - "by_path_suffix": {}, - }, - } - - result = verify_pack_against_platform( - str(pack), - "missing", - str(platforms), - db=database, - emu_profiles={}, - ) - self.assertFalse(result[0]) - self.assertTrue(any("baseline missing" in error for error in result[3])) - - -class RegionRegressions(unittest.TestCase): - def test_tagged_and_untagged_same_path_is_preserved(self): - profiles = { - "tagged": { - "type": "libretro", - "files": [ - {"name": "bios.bin", "path": "sys/bios.bin", "region": ["japan"]} - ], - }, - "untagged": { - "type": "libretro", - "files": [{"name": "bios.bin", "path": "sys/bios.bin"}], - }, - } - index = regions.build_region_index(profiles) - self.assertEqual(regions.lookup_regions(index, "sys/bios.bin", "bios.bin"), set()) - drops = regions.resolve_region_drops( - {"system": [("sys/bios.bin", "bios.bin")]}, - index, - ["north-america"], - ) - self.assertEqual(drops, set()) - - def test_world_candidate_beats_unmatched_regional_fallback(self): - profiles = { - "core": { - "type": "libretro", - "files": [ - {"name": "ntsc.bin", "region": ["world"]}, - {"name": "pal.bin", "region": ["europe"]}, - ], - } - } - index = regions.build_region_index(profiles) - groups = {"system": [("ntsc.bin", "ntsc.bin"), ("pal.bin", "pal.bin")]} - self.assertEqual( - regions.resolve_region_drops(groups, index, ["north-america"]), - {"pal.bin"}, - ) - self.assertEqual(regions.resolve_region_drops(groups, index, ["europe"]), set()) - - def test_multi_system_emulator_uses_separate_region_groups(self): - profile = {"systems": ["odyssey2", "videopac"]} - north_america = _emulator_region_group( - "o2em", profile, {"name": "o2rom.bin", "system": "odyssey2"}, "o2rom.bin" - ) - europe = _emulator_region_group( - "o2em", profile, {"name": "c52.bin", "system": "videopac"}, "c52.bin" - ) - self.assertNotEqual(north_america, europe) - - def test_a_systemless_file_groups_alike_in_both_modes(self): - """geargrafx files pac-n1.bin [japan] and pac-n10.bin [north-america] - under none of its four systems: emulator mode grouped them and - dropped pac-n1.bin for --region us, platform mode isolated each and - kept it.""" - from packs.extraregions import extra_region_groups - - profile = {"systems": ["nec-pc-engine", "nec-pc-engine-cd", "nec-supergrafx", - "pioneer-laseractive"]} - names = ["pac-n1.bin", "pac-n10.bin"] - emulator = [ - _emulator_region_group("geargrafx", profile, {"name": n}, n) for n in names - ] - platform = [ - extra_region_groups({ - "source_emulator": "geargrafx", "destination": n, - "source_systems": profile["systems"], - })[0] - for n in names - ] - self.assertEqual(emulator, platform) - - def test_an_entry_systems_list_groups_alike_in_both_modes(self): - """An entry's own one-element `systems:` names its machine on the - platform side. Emulator mode read only `system:`, so --emulator - --region us kept the Japanese file --platform --region us dropped.""" - from model.profiles import entry_system_ids - from packs.extraregions import emulator_region_drops, extra_region_groups - - profile = {"systems": ["sys-a", "sys-b"], "files": [ - {"name": "us.bin", "systems": ["sys-a"], "region": ["north-america"]}, - {"name": "jp.bin", "systems": ["sys-a"], "region": ["japan"]}, - ]} - self.assertEqual( - emulator_region_drops([("emu", profile)], False, ["north-america"]), - {"jp.bin"}, - ) - for fe in profile["files"]: - self.assertEqual( - _emulator_region_group("emu", profile, fe, fe["name"]), - "emu:system:" + extra_region_groups({ - "source_emulator": "emu", "destination": fe["name"], - "source_systems": entry_system_ids(fe, profile), - })[0], - ) - - def test_region_audit_resolves_the_way_the_pack_does(self): - """A private resolver read sha1, md5 and a lone name: an entry - identified by its path (Dolphin's three IPL.bin) was never checked.""" - import hashlib - - with tempfile.TemporaryDirectory() as directory: - previous = os.getcwd() - os.chdir(directory) - self.addCleanup(os.chdir, previous) - files, shas = {}, {} - for rel, payload in (("bios/GC/USA/IPL.bin", b"usa"), ("bios/GC/JAP/IPL.bin", b"jap")): - Path(rel).parent.mkdir(parents=True, exist_ok=True) - Path(rel).write_bytes(payload) - sha1 = hashlib.sha1(payload).hexdigest() - shas[rel] = sha1 - files[sha1] = {"path": rel, "name": "IPL.bin", "size": len(payload), "sha1": sha1, - "md5": hashlib.md5(payload).hexdigest(), - "sha256": hashlib.sha256(payload).hexdigest(), "crc32": "00000001"} - from collection.indexes import build_indexes - - db = {"files": files, "indexes": build_indexes(files, {})} - by_md5 = {e["md5"]: s for s, e in files.items()} - self.assertEqual( - regionaudit.resolve_sha1({"name": "IPL.bin", "md5": [files[shas["bios/GC/USA/IPL.bin"]]["md5"]]}, db), - shas["bios/GC/USA/IPL.bin"], - ) - self.assertEqual( - regionaudit.resolve_sha1({"name": "IPL.bin", "path": "GC/JAP/IPL.bin"}, db), - shas["bios/GC/JAP/IPL.bin"], - ) - self.assertTrue(by_md5) - - -class ArchiveSecurityRegressions(unittest.TestCase): - def _zip_path(self, directory: Path, name: str = "archive.zip") -> Path: - return directory / name - - def test_member_count_limit_is_enforced(self): - with tempfile.TemporaryDirectory() as directory: - root = Path(directory) - archive = self._zip_path(root) - with zipfile.ZipFile(archive, "w") as handle: - handle.writestr("one.bin", b"1") - handle.writestr("two.bin", b"2") - with self.assertRaisesRegex(ValueError, "members"): - safe_extract_zip(str(archive), str(root / "out"), max_members=1) - - def test_member_modes_follow_the_archive_and_the_umask(self): - """Every member came out 0600, the mode of its temporary file: the - pico8 and vox launchers the RetroDECK pack keeps 0755 lost their - execute bit once download.py extracted them.""" - with tempfile.TemporaryDirectory() as directory: - root = Path(directory) - archive = self._zip_path(root) - program = zipfile.ZipInfo("pico8") - program.create_system = 3 - program.external_attr = (stat.S_IFREG | 0o755) << 16 - plain = zipfile.ZipInfo("bios.bin") - plain.create_system = 0 - plain.external_attr = 0x20 # MS-DOS archive bit, no Unix mode - with zipfile.ZipFile(archive, "w") as handle: - handle.writestr(program, b"\x7fELF") - handle.writestr(plain, b"data") - umask = os.umask(0o022) - try: - safe_extract_zip(str(archive), str(root / "out")) - finally: - os.umask(umask) - self.assertEqual((root / "out" / "pico8").stat().st_mode & 0o777, 0o755) - self.assertEqual((root / "out" / "bios.bin").stat().st_mode & 0o777, 0o644) - - def test_symlink_member_is_rejected(self): - with tempfile.TemporaryDirectory() as directory: - root = Path(directory) - archive = self._zip_path(root) - link = zipfile.ZipInfo("link") - link.create_system = 3 - link.external_attr = (stat.S_IFLNK | 0o777) << 16 - with zipfile.ZipFile(archive, "w") as handle: - handle.writestr(link, "target") - with self.assertRaisesRegex(ValueError, "link or special"): - safe_extract_zip(str(archive), str(root / "out")) - - def test_windows_separator_is_a_path_not_a_rejection(self): - """Archives written on Windows store a backslash separator. - - download.py feeds third-party archives to this function, so a legal - Windows path must extract into a subdirectory instead of failing. - """ - with tempfile.TemporaryDirectory() as directory: - root = Path(directory) - archive = self._zip_path(root) - with zipfile.ZipFile(archive, "w") as handle: - handle.writestr("sub\\rom.bin", b"payload") - out = root / "out" - safe_extract_zip(str(archive), str(out)) - self.assertEqual((out / "sub" / "rom.bin").read_bytes(), b"payload") - - def test_windows_separator_cannot_smuggle_traversal(self): - with tempfile.TemporaryDirectory() as directory: - root = Path(directory) - archive = self._zip_path(root) - with zipfile.ZipFile(archive, "w") as handle: - handle.writestr("..\\escaped.bin", b"payload") - with self.assertRaisesRegex(ValueError, "traversal"): - safe_extract_zip(str(archive), str(root / "out")) - - def test_high_ratio_method_is_bounded_by_size_not_ratio(self): - """bzip2 legitimately exceeds the DEFLATE ceiling.""" - with tempfile.TemporaryDirectory() as directory: - root = Path(directory) - archive = self._zip_path(root) - with zipfile.ZipFile(archive, "w", zipfile.ZIP_BZIP2) as handle: - handle.writestr("zeros.bin", bytes(4_000_000)) - out = root / "out" - safe_extract_zip(str(archive), str(out)) - self.assertEqual((out / "zeros.bin").stat().st_size, 4_000_000) - - def test_compression_ratio_limit_is_enforced(self): - with tempfile.TemporaryDirectory() as directory: - root = Path(directory) - archive = self._zip_path(root) - with zipfile.ZipFile(archive, "w", zipfile.ZIP_DEFLATED) as handle: - handle.writestr("zeros.bin", bytes(16_384)) - with self.assertRaisesRegex(ValueError, "compression ratio"): - safe_extract_zip( - str(archive), str(root / "out"), max_compression_ratio=2 - ) - - -class NoMd5IsNotNothingChecked(unittest.TestCase): - """A declared hash that is not an md5 still contradicts. - - verify_entry_md5 returned OK the moment the entry declared no md5, so an - entry whose sha256 the local file contradicts read as covered while the - builder was already excluding it. RetroDECK's dsifirmware.bin declares a - sha256 and no md5. - """ - - def _entry(self): - return {"name": "dsifirmware.bin", "sha256": "b" * 64} - - def test_a_contradicted_sha256_is_not_reported_ok(self): - result = verdicts.verify_entry_md5( - self._entry(), "bios/whatever.bin", "hash_mismatch" - ) - self.assertNotEqual(result["status"], verdicts.Status.OK) - self.assertIn("contradicted", result.get("reason", "")) - - def test_a_clean_resolution_is_still_ok(self): - result = verdicts.verify_entry_md5( - self._entry(), "bios/whatever.bin", "sha256_exact" - ) - self.assertEqual(result["status"], verdicts.Status.OK) - - -class InstallerBoundaryRegressions(unittest.TestCase): - def _manifest(self, dest: str) -> dict: - return { - "manifest_version": 2, - "platform": "retroarch", - "files": [ - { - "dest": dest, - "size": 1, - "sha1": "a" * 40, - "sha256": "b" * 64, - "repo_path": "bios/test.bin", - "cores": None, - } - ], - "standalone_copies": [], - } - - def test_manifest_destination_traversal_is_rejected(self): - with self.assertRaisesRegex(ValueError, "unsafe"): - install._validate_manifest(self._manifest("../escape"), "retroarch") - - def test_manifest_repo_source_is_confined_to_bios(self): - manifest = self._manifest("safe.bin") - manifest["files"][0]["repo_path"] = "scripts/pipeline.py" - with self.assertRaisesRegex(ValueError, "outside bios"): - install._validate_manifest(manifest, "retroarch") - - def test_omitted_destination_cannot_overlap_a_download(self): - manifest = self._manifest("safe.bin") - manifest["omitted_files"] = [ - { - "dest": "safe.bin", - "name": "safe.bin", - "system": "console", - "required": True, - "reason": "hash_mismatch", - "cores": None, - } - ] - manifest["total_omitted"] = 1 - with self.assertRaisesRegex(ValueError, "conflicting omitted"): - install._validate_manifest(manifest, "retroarch") - - def test_omitted_destination_traversal_is_rejected(self): - manifest = self._manifest("safe.bin") - manifest["omitted_files"] = [ - { - "dest": "../unsafe.bin", - "name": "unsafe.bin", - "system": "console", - "required": True, - "reason": "hash_mismatch", - "cores": None, - } - ] - manifest["total_omitted"] = 1 - with self.assertRaisesRegex(ValueError, "unsafe"): - install._validate_manifest(manifest, "retroarch") - - @unittest.skipUnless(HAS_JSONSCHEMA, "validating a schema needs jsonschema") - def test_target_schema_accepts_the_null_the_generator_emits(self): - """The schema and generate_target_manifests must agree on null. - - A target with no core list is written as null, and a schema that rejects - it turns a valid manifest into a CI failure. - """ - from jsonschema import Draft202012Validator - - schema = json.loads( - (ROOT / "schemas" / "target-manifest.schema.json").read_text( - encoding="utf-8" - ) - ) - validator = Draft202012Validator(schema) - document = {"windows": None, "switch": ["a5200"]} - self.assertEqual(list(validator.iter_errors(document)), []) - - @unittest.skipUnless(HAS_JSONSCHEMA, "validating a schema needs jsonschema") - def test_pack_manifests_are_read_from_inside_the_archive(self): - """generate_pack writes manifest.json into the ZIP, not beside it. - - A filesystem glob over dist/ matches nothing and reports success - without validating a single document. - """ - from schemas import packmanifests - - with tempfile.TemporaryDirectory() as directory: - dist = Path(directory) - broken = { - "schema_version": 1, - "version": 1, - "generator": "retrobios generate_pack.py", - "generated": "2026-08-10T00:00:00Z", - "files": [{"path": "a.bin", "sha1": "nope", "md5": "nope", - "size": 1, "status": "verified", "name": "a.bin"}], - "summary": {"total_files": 1, "verified": 1, "untracked": 0, - "errors": 0}, - "errors": [], - } - with zipfile.ZipFile(dist / "Pack.zip", "w") as archive: - archive.writestr("manifest.json", json.dumps(broken)) - - errors = packmanifests.validate_pack_manifests(dist) - self.assertTrue(errors, "an invalid in-archive manifest must be reported") - self.assertTrue(any("sha1" in message for message in errors), errors) - - @unittest.skipUnless(HAS_JSONSCHEMA, "validating a schema needs jsonschema") - def test_packs_being_written_are_a_skip_not_a_pass(self): - """Under a build's lock the reader returned [], the value of packs - that validated, and validate_schemas announced everything valid - without reading one.""" - from core.artifacts import ArtifactLockBusy, artifact_lock - from schemas import packmanifests, run - - with tempfile.TemporaryDirectory() as directory: - dist = Path(directory) / "dist" - dist.mkdir() - (dist / "Bad_BIOS_Pack.zip").write_bytes(b"not a zip") - self.assertTrue(packmanifests.validate_pack_manifests(dist)) - with artifact_lock(str(dist), exclusive=True): - with self.assertRaises(ArtifactLockBusy): - packmanifests.validate_pack_manifests(dist) - outcome = run.Validation() - with mock.patch.object(run.core.paths, "REPO_ROOT", Path(directory)): - run.generated_errors(outcome) - self.assertEqual(outcome.skipped, ["pack manifests skipped, dist in use"]) - - @unittest.skipUnless(HAS_JSONSCHEMA, "validating a schema needs jsonschema") - def test_a_pack_carries_its_install_list_and_board_lists(self): - """pack_systems puts the install list and the per-board core lists - in the pack's manifest.json, which install.py reads with the pack - alone. The pack schema refused both keys, and each is checked under - its own contract.""" - from packs import scope - from schemas import packmanifests - - install_list = json.loads((ROOT / "install" / "romm.json").read_text(encoding="utf-8")) - targets = {"browser": None, "rpi4": {"cores": ["mgba"], "images": ["rpi4"]}} - document = { - "schema_version": 1, "version": 1, - "generator": "retrobios generate_pack.py", - "generated": "2026-08-10T00:00:00Z", "files": [], - "summary": {"total_files": 0, "verified": 0, "untracked": 0, "errors": 0}, - "errors": [], - } - scope.annotate_pack_systems( - document, scope.pack_systems(install_list, targets)) - self.assertIn("install_list", document) - self.assertIn("targets", document) - with tempfile.TemporaryDirectory() as directory: - dist = Path(directory) - with zipfile.ZipFile(dist / "Pack.zip", "w") as archive: - archive.writestr("manifest.json", json.dumps(document)) - self.assertEqual(packmanifests.validate_pack_manifests(dist), []) - - broken = {**document, "targets": {"rpi4": [1]}, - "install_list": {**install_list, "files": "none"}} - with zipfile.ZipFile(dist / "Pack.zip", "w") as archive: - archive.writestr("manifest.json", json.dumps(broken)) - errors = packmanifests.validate_pack_manifests(dist) - self.assertTrue(any(":targets:" in message for message in errors), errors) - self.assertTrue(any(":install_list:" in message for message in errors), errors) - - def test_null_core_list_keeps_the_other_targets(self): - """A target without a core inventory must not void the manifest. - - generate_target_manifests emits null for a target that publishes no - core list. Rejecting the document would silently disable --target for - every target on that platform. - """ - normalized = install._validate_targets({"windows": None, "switch": ["a5200"]}) - self.assertIsNone(normalized["windows"]["cores"]) - self.assertEqual(normalized["switch"]["cores"], ["a5200"]) - - def test_legacy_target_lists_are_normalized(self): - self.assertEqual( - install._validate_targets({"rpi4": ["core-a", "core-b"]}), - {"rpi4": {"cores": ["core-a", "core-b"]}}, - ) - - -class TargetManifestRegressions(unittest.TestCase): - def test_yaml_scalar_core_is_rejected_instead_of_leaking_to_json(self): - with tempfile.TemporaryDirectory() as directory: - root = Path(directory) - source = root / "source" - output = root / "output" - source.mkdir() - (source / "platform.yml").write_text( - "targets:\n device:\n cores: [81, valid-core]\n", - encoding="utf-8", - ) - with self.assertRaisesRegex(ValueError, "non-empty strings"): - generate_target_manifests(str(source), str(output)) - - def test_a_missing_targets_directory_fails_the_command(self): - """--manifest-targets printed the missing directory and exited 0 - with nothing written: the pipeline step read that as done.""" - with tempfile.TemporaryDirectory() as directory: - root = Path(directory) - with self.assertRaisesRegex(FileNotFoundError, "No targets directory"): - generate_target_manifests(str(root / "absent"), str(root / "out")) - (root / "plat").mkdir() - run = subprocess.run( - [sys.executable, str(ROOT / "scripts" / "generate_pack.py"), - "--manifest-targets", "--platforms-dir", str(root / "plat"), - "--output-dir", str(root / "out")], - capture_output=True, text=True, cwd=ROOT, check=False, - ) - self.assertEqual(run.returncode, 1, run.stderr) - self.assertIn("No targets directory at", run.stderr) - - -class CheckoutCompletenessRegressions(unittest.TestCase): - """Coverage is resolved against the disk, so the checkout must be whole. - - Files over 50 MB and the data directory caches are gitignored. A job that - regenerates the README or the site without restoring them counts those - files as missing and publishes a coverage the collection does not have. - """ - - def _steps(self, workflow: str, job: str) -> list[dict]: - data = yaml.safe_load((ROOT / ".github" / "workflows" / workflow).read_text()) - return data["jobs"][job]["steps"] - - def _index(self, steps: list[dict], needle: str) -> int: - for position, step in enumerate(steps): - if needle in step.get("name", "") or needle in str(step.get("run", "")): - return position - raise self.failureException(f"no step matching {needle!r}") - - def test_site_deploy_completes_the_checkout_before_generating(self): - steps = self._steps("deploy-site.yml", "build") - generate = self._index(steps, "Generate site") - self.assertLess(self._index(steps, "restore_large_files.py"), generate) - self.assertLess(self._index(steps, "refresh_data_dirs.py"), generate) - - def test_restore_matches_assets_by_content_not_by_name(self): - from scripts.release.restore import restore - - with tempfile.TemporaryDirectory() as directory: - root = Path(directory) - cache = root / "cache" - cache.mkdir() - payload = b"firmware bytes" - (cache / "renamed-asset.bin").write_bytes(payload) - sha1 = hashlib.sha1(payload).hexdigest() - (root / ".gitignore").write_text("bios/Sony/big.pup\n", encoding="utf-8") - (root / "database.json").write_text( - json.dumps({"files": {sha1: {"path": "bios/Sony/big.pup"}}}), - encoding="utf-8", - ) - result = restore( - str(cache), str(root / "database.json"), str(root / ".gitignore"), - root=root, - ) - self.assertEqual( - (result.restored, result.unsatisfied), (["bios/Sony/big.pup"], []) - ) - self.assertEqual((root / "bios/Sony/big.pup").read_bytes(), payload) - # A path already in the checkout is never overwritten. - result = restore( - str(cache), str(root / "database.json"), str(root / ".gitignore"), - root=root, - ) - self.assertEqual((result.restored, result.unsatisfied), ([], [])) - - def test_restore_without_its_registry_fails(self): - """A mistyped --gitignore read as an empty registry: nothing to - restore, nothing unsatisfied, exit 0 with every asset absent.""" - import subprocess - - from scripts.release.restore import gitignored_paths - - with tempfile.TemporaryDirectory() as directory: - missing = str(Path(directory) / "absent") - with self.assertRaises(FileNotFoundError): - gitignored_paths(missing) - proc = subprocess.run( - [sys.executable, str(ROOT / "scripts" / "restore_large_files.py"), - "--gitignore", missing, "--cache", directory], - capture_output=True, text=True, timeout=120, - check=False, - ) - self.assertEqual(proc.returncode, 2, proc.stdout + proc.stderr) - self.assertIn("lists the release assets", proc.stderr) - - def test_restore_refuses_a_copy_replaced_after_the_index(self): - """The cache is hashed first and copied later: another run that - replaced the cached name in between put its bytes at a path the - database pins to the old ones.""" - from scripts.release import restore as release_restore - - with tempfile.TemporaryDirectory() as directory: - root = Path(directory) - cache = root / "cache" - cache.mkdir() - payload = b"firmware bytes" - (cache / "asset.bin").write_bytes(payload) - sha1 = hashlib.sha1(payload).hexdigest() - (root / ".gitignore").write_text("bios/Sony/big.pup\n", encoding="utf-8") - (root / "database.json").write_text( - json.dumps({"files": {sha1: {"path": "bios/Sony/big.pup"}}}), - encoding="utf-8", - ) - real_index = release_restore.index_cache - - def index_then_replace(cache_dir: str) -> dict[str, str]: - index = real_index(cache_dir) - (cache / "asset.bin").write_bytes(b"re-uploaded bytes") - return index - - with mock.patch.object(release_restore, "index_cache", index_then_replace): - result = release_restore.restore( - str(cache), str(root / "database.json"), - str(root / ".gitignore"), root=root, - ) - self.assertEqual( - (result.restored, result.unsatisfied), ([], ["bios/Sony/big.pup"]) - ) - self.assertFalse((root / "bios/Sony/big.pup").exists()) - self.assertEqual(os.listdir(root / "bios/Sony"), []) - - def test_restore_leaves_tracked_paths_alone(self): - from scripts.release.restore import restore - - with tempfile.TemporaryDirectory() as directory: - root = Path(directory) - cache = root / "cache" - cache.mkdir() - payload = b"tracked bytes" - (cache / "asset.bin").write_bytes(payload) - sha1 = hashlib.sha1(payload).hexdigest() - (root / ".gitignore").write_text("bios/other.bin\n", encoding="utf-8") - (root / "database.json").write_text( - json.dumps({"files": {sha1: {"path": "bios/tracked.bin"}}}), - encoding="utf-8", - ) - result = restore( - str(cache), str(root / "database.json"), str(root / ".gitignore"), - root=root, - ) - self.assertEqual((result.restored, result.unsatisfied), ([], [])) - self.assertFalse((root / "bios/tracked.bin").exists()) - - def test_restore_without_a_cache_names_what_is_missing(self): - """A job that skipped `mkdir .cache/large` exited 0 with every - gitignored file absent: the early return ran before the check.""" - from scripts.release.restore import restore - - with tempfile.TemporaryDirectory() as directory: - root = Path(directory) - (root / ".gitignore").write_text("bios/big.bin\n", encoding="utf-8") - (root / "database.json").write_text( - json.dumps({"files": {"a" * 40: {"path": "bios/big.bin"}}}), - encoding="utf-8", - ) - result = restore( - str(root / "no-cache"), str(root / "database.json"), - str(root / ".gitignore"), root=root, - ) - self.assertEqual( - (result.restored, result.unsatisfied, result.cache_found), - ([], ["bios/big.bin"], False), - ) - - def test_restore_command_prints_the_report(self): - """The command, not the library, says what was restored and what the - cache could not supply, relative to the directory it runs in.""" - import subprocess - - with tempfile.TemporaryDirectory() as directory: - root = Path(directory) - cache = root / "cache" - cache.mkdir() - payload = b"firmware bytes" - (cache / "asset.bin").write_bytes(payload) - sha1 = hashlib.sha1(payload).hexdigest() - (root / ".gitignore").write_text( - "bios/big.bin\nbios/absent.bin\n", encoding="utf-8" - ) - (root / "database.json").write_text( - json.dumps({"files": { - sha1: {"path": "bios/big.bin"}, - "a" * 40: {"path": "bios/absent.bin"}, - }}), - encoding="utf-8", - ) - command = [sys.executable, str(ROOT / "scripts" / "restore_large_files.py")] - proc = subprocess.run( - [*command, "--cache", "cache"], - capture_output=True, text=True, cwd=str(root), timeout=120, - check=False, - ) - self.assertEqual(proc.returncode, 1, proc.stdout + proc.stderr) - self.assertEqual( - proc.stdout, "Restored: bios/big.bin\nTotal: 1 files restored\n" - ) - self.assertEqual( - proc.stderr, - "Unsatisfied: 1 declared paths the cache cannot supply\n" - " bios/absent.bin\n", - ) - self.assertEqual((root / "bios/big.bin").read_bytes(), payload) - without_cache = subprocess.run( - [*command, "--cache", "no-cache"], - capture_output=True, text=True, cwd=str(root), timeout=120, - check=False, - ) - self.assertTrue(without_cache.stdout.startswith("No cache at no-cache\n")) - - -def _git_paths(*args: str, stdin: list[str] | None = None) -> set[str] | None: - """The NUL-separated paths a git command prints, or None outside a - checkout. check-ignore exits 1 when it matches nothing, an answer.""" - try: - result = subprocess.run( - ["git", *args], - input="".join(f"{p}\0" for p in stdin or []), - capture_output=True, text=True, cwd=ROOT, check=False, - ) - except FileNotFoundError: - return None - answered = (0, 1) if args[0] == "check-ignore" else (0,) - if result.returncode not in answered: - return None - return {p for p in result.stdout.split("\0") if p} - - -class ManifestVersionIsThePlatformsOwn(unittest.TestCase): - """Every install manifest named its list "1.0", and an inheriting YAML - took its parent's version: Lakka was published as RetroArch v1.22.2. - The installer compares the list's version with the one a machine runs, - so each manifest states the version its own platform YAML records.""" - - def setUp(self): - from scripts.model.platforms import _platform_config_cache - _platform_config_cache.clear() - - def test_committed_manifests_state_their_platform_version(self): - from scripts.model.platforms import load_platform_config - manifests = sorted((ROOT / "install").glob("*.json")) - self.assertTrue(manifests) - for path in manifests: - with self.subTest(manifest=path.name): - data = json.loads(path.read_text()) - config = load_platform_config(data["platform"], str(ROOT / "platforms")) - self.assertTrue(config.get("version")) - self.assertEqual(data["version"], str(config["version"])) - - def test_no_child_shows_its_parents_version(self): - from scripts.model.platforms import load_platform_config - platforms = ROOT / "platforms" - children = {} - for path in sorted(platforms.glob("*.yml")): - raw = yaml.safe_load(path.read_text()) or {} - if isinstance(raw, dict) and raw.get("inherits"): - children[path.stem] = raw - self.assertIn("lakka", children) - for name, raw in children.items(): - with self.subTest(platform=name): - parent = yaml.safe_load( - (platforms / f"{raw['inherits']}.yml").read_text()) - version = load_platform_config(name, str(platforms)).get("version") - self.assertEqual(version, raw.get("version")) - self.assertNotEqual(version, parent.get("version")) - - def test_an_unversioned_child_has_no_version(self): - from scripts.model.platforms import load_platform_config - with tempfile.TemporaryDirectory() as tmp: - Path(tmp, "parent.yml").write_text("platform: P\nversion: '2.0'\nsystems: {}\n") - Path(tmp, "child.yml").write_text("inherits: parent\nplatform: C\n") - self.assertNotIn("version", load_platform_config("child", tmp)) - - def test_lakka_names_the_release_its_cores_are_read_at(self): - platforms = ROOT / "platforms" - lakka = yaml.safe_load((platforms / "lakka.yml").read_text()) - targets = yaml.safe_load((platforms / "targets" / "lakka.yml").read_text()) - tag = re.search(r"/blob/([^/]+)/", targets["source"]).group(1) - self.assertEqual(lakka["version"], tag) - - -class EveryManifestEntryIsFetchable(unittest.TestCase): - """An install manifest may not list a file the installer cannot get. - - install.py fetches a file either from its repo_path or from a release - asset. An entry carrying neither is a line in the download list that can - only ever fail. It happened when resolution landed on a file the database - does not index, so the hash was computed but the repo lookup came back - empty and the entry shipped anyway. - """ - - def test_committed_manifests_all_have_a_source(self): - manifests = sorted((ROOT / "install").glob("*.json")) - self.assertTrue(manifests, "no install manifests to check") - for path in manifests: - with self.subTest(manifest=path.name): - data = json.loads(path.read_text()) - orphans = [ - entry["dest"] - for entry in data.get("files", []) + data.get("case_variants", []) - if not entry.get("repo_path") and not entry.get("release_asset") - ] - self.assertEqual( - orphans, [], f"{path.name} lists unfetchable files: {orphans[:3]}" - ) - - def test_an_unresolvable_file_is_recorded_as_omitted(self): - """The reason must be one install.py knows how to report.""" - for path in sorted((ROOT / "install").glob("*.json")): - with self.subTest(manifest=path.name): - data = json.loads(path.read_text()) - for entry in data.get("omitted_files", []): - self.assertIn(entry.get("reason"), install.OMISSION_REASONS) - - def test_the_installer_accepts_every_published_manifest(self): - """A reason the schema allowed and the installer did not made the - installer refuse the whole RomM manifest: no RomM install ran.""" - for path in sorted((ROOT / "install").glob("*.json")): - with self.subTest(manifest=path.name): - data = json.loads(path.read_text()) - install._validate_manifest(data, data["platform"]) - - def test_every_standalone_layout_goes_with_its_list(self): - """install/standalone/.json, which only --standalone - reads: the installer accepts it against its own list, each item - written whole has a source, and a list naming builds has its file.""" - listed = {path.stem: json.loads(path.read_text()) - for path in sorted((ROOT / "install").glob("*.json"))} - layouts = sorted((ROOT / "install" / "standalone").glob("*.json")) - self.assertEqual({path.stem for path in layouts}, - {plat for plat, data in listed.items() - if data.get("standalone_builds")}) - for path in layouts: - with self.subTest(layout=path.name): - data = json.loads(path.read_text()) - kept = install._check_standalone_layouts(data, listed[path.stem], path.stem) - orphans = [item["dest"] for items in kept.values() for item in items - if isinstance(item, dict) - and not item.get("repo_path") and not item.get("release_asset")] - self.assertEqual(orphans, []) - - def test_schema_and_installer_name_the_same_reasons(self): - schema = json.loads( - (ROOT / "schemas" / "install-manifest.schema.json").read_text() - ) - reasons = schema["properties"]["omitted_files"]["items"]["properties"][ - "reason" - ]["enum"] - self.assertEqual(set(reasons), set(install.OMISSION_REASONS)) - - def _manifests(self) -> list[Path]: - paths = sorted((ROOT / "install").glob("*.json")) - paths += sorted((ROOT / "install" / "targets").glob("*.json")) - self.assertTrue(paths, "no install manifests to check") - return paths - - def test_repo_paths_name_the_file_the_database_holds(self): - """A manifest written before a file moved sends the installer to 404. - - database.json is regenerated whenever a file is refiled, but the manifests - are a separate artefact and were left behind once (the two DS - firmware dumps of the 7 September refile). The installer fetches - repo_path from raw.githubusercontent.com, so a stale one is a - download that can never succeed. - """ - database = ROOT / "database.json" - if not database.is_file(): - self.skipTest("database.json not generated") - files = json.loads(database.read_text(encoding="utf-8"))["files"] - for path in self._manifests(): - with self.subTest(manifest=path.name): - data = json.loads(path.read_text(encoding="utf-8")) - stale = [ - (entry["dest"], entry["repo_path"], files.get(entry["sha1"], {}).get("path")) - for entry in data.get("files", []) + data.get("case_variants", []) - if entry.get("repo_path") - and files.get(entry.get("sha1", ""), {}).get("path") != entry["repo_path"] - ] - self.assertEqual(stale, [], f"{path.name} names moved files: {stale[:3]}") - - def test_release_entries_are_exactly_the_files_git_does_not_hold(self): - """The installer has two sources, and the manifest must pick the right one. - - A committed file is served by the repository, a gitignored one by - the large-files release. Marking a committed file as a release asset - sends the installer to an asset nobody uploaded (sdlpal/5.avi, 83 MB - in git, was announced as release asset `5.avi`). Marking a gitignored - file as a repo file sends it to a raw URL that has no content. A - file neither committed nor ignored is a commit nobody made, and is - named as such rather than as a release asset. - """ - tracked = _git_paths("ls-files", "-z", "--", "bios") - if tracked is None: - self.skipTest("not a git checkout") - manifests: dict[str, list[dict]] = {} - for path in self._manifests(): - data = json.loads(path.read_text(encoding="utf-8")) - manifests[path.name] = [ - entry - for entry in data.get("files", []) + data.get("case_variants", []) - if entry.get("repo_path") - ] - outside = sorted( - {e["repo_path"] for group in manifests.values() for e in group} - tracked - ) - ignored = _git_paths("check-ignore", "-z", "--no-index", "--stdin", stdin=outside) - if ignored is None: - self.skipTest("not a git checkout") - for name, group in manifests.items(): - with self.subTest(manifest=name): - wrong = [] - for entry in group: - repo_path = entry["repo_path"] - state = ( - "committed" if repo_path in tracked - else "gitignored" if repo_path in ignored - else "untracked, never committed" - ) - if state == "untracked, never committed" or ( - bool(entry.get("release_asset")) != (state == "gitignored") - ): - wrong.append((entry["dest"], repo_path, state)) - self.assertEqual(wrong, [], f"{name} picks the wrong source: {wrong[:3]}") - - def test_no_collected_file_is_left_uncommitted(self): - """157 files of the 17 September campaign sat in bios/ untracked: - the database indexed them, the manifests gave them a repo_path and - the installer got a 404. A file under bios/ is either committed or - listed in .gitignore as a release asset, nothing in between.""" - untracked = _git_paths("ls-files", "-z", "--others", "--exclude-standard", "--", "bios") - if untracked is None: - self.skipTest("not a git checkout") - self.assertEqual(sorted(untracked)[:20], [], f"{len(untracked)} untracked files under bios/") - - def test_every_database_path_is_committed_or_a_release_asset(self): - """A git mv under bios/ committed without regenerating anything left - database.json and the manifests agreeing on the old path: the tests - above compare them with each other, so all passed, and the installer - got a 404 (issue 78, with the database stale too).""" - database = ROOT / "database.json" - if not database.is_file(): - self.skipTest("database.json not generated") - files = json.loads(database.read_text(encoding="utf-8"))["files"] - paths = { - path - for entry in files.values() - for path in [entry.get("path"), *(entry.get("paths") or [])] - if path - } - tracked = _git_paths("ls-files", "-z") - if tracked is None: - self.skipTest("not a git checkout") - outside = sorted(paths - tracked) - ignored = _git_paths("check-ignore", "-z", "--no-index", "--stdin", stdin=outside) - if ignored is None: - self.skipTest("not a git checkout") - stale = [path for path in outside if path not in ignored] - self.assertEqual( - stale[:20], [], - f"{len(stale)} database paths git neither holds nor ignores: " - "python scripts/generate_db.py --force --bios-dir bios --output database.json, " - "then the manifests", - ) - - -class ReleaseAssetCriterion(unittest.TestCase): - """What decides whether the installer fetches from the release is git, not size. - - Files over 50 MB are supposed to be gitignored and uploaded to the - large-files release, but four committed files break that rule and one of - them reached a manifest as a release asset that does not exist. The - truthful question is whether the repository serves the bytes, and the - ledger of what it does not serve is .gitignore. - """ - - def _repo(self, directory: str, ignored: str) -> str: - Path(directory, ".gitignore").write_text(ignored + "\n", encoding="utf-8") - return directory - - def test_a_large_committed_file_is_served_by_the_repository(self): - from scripts.packs import manifestentry - - with tempfile.TemporaryDirectory() as directory: - root = self._repo(directory, "bios/elsewhere.bin") - big = Path(root, "bios", "big.avi") - big.parent.mkdir() - with big.open("wb") as handle: - handle.truncate(60_000_000) - manifestentry._registered.cache_clear() - try: - self.assertFalse(manifestentry._is_release_asset(str(big), root)) - finally: - manifestentry._registered.cache_clear() - - def test_the_manifest_names_the_asset_as_github_serves_it(self): - # GitHub publishes a space as a dot. The site linked the dotted - # name while the manifest gave install.py the spaced one, a 404. - from scripts.packs import manifestentry - - with tempfile.TemporaryDirectory() as directory: - root = self._repo(directory, "bios/MAME/MAME 0.174 Arcade XML.dat") - target = Path(root, "bios", "MAME", "MAME 0.174 Arcade XML.dat") - target.parent.mkdir(parents=True) - target.write_bytes(b"x") - manifestentry._registered.cache_clear() - try: - self.assertEqual( - manifestentry._release_asset_name(str(target), root), - "MAME.0.174.Arcade.XML.dat", - ) - finally: - manifestentry._registered.cache_clear() - - def test_a_gitignored_file_is_served_by_the_release_whatever_its_size(self): - from scripts.packs import manifestentry - - with tempfile.TemporaryDirectory() as directory: - root = self._repo(directory, "bios/small.zip") - small = Path(root, "bios", "small.zip") - small.parent.mkdir() - small.write_bytes(b"PK") - manifestentry._registered.cache_clear() - try: - self.assertTrue(manifestentry._is_release_asset(str(small), root)) - finally: - manifestentry._registered.cache_clear() - - -class ReleaseAssetsMatchTheCollection(unittest.TestCase): - """The bytes the release serves must be the bytes the manifests describe. - - install.py checks Content-Length against the manifest size before it - downloads, and the manifest size is that of the local copy. Both FBNeo - sample archives were rebuilt locally after their upload and never - re-uploaded: same members, different container, every install of them - failed. The comparison is offline here on a fixture, while the script runs it - against the live release. - """ - - def test_missing_and_resized_assets_are_reported_and_nothing_else(self): - from scripts.release import assets as release_assets - - expected = { - "bios/Other/fbneo/fbneo/samples/twotiger.zip": 154985212, - "bios/Arcade/MAME/MAME 0.174 Arcade XML.dat": 53677408, - "bios/Other/sdlpal/sdlpal/5.avi": 82833972, - } - assets = { - "twotiger.zip": 154888877, - "MAME.0.174.Arcade.XML.dat": 53677408, - "unrelated.zip": 1, - } - findings = release_assets.compare(expected, assets) - self.assertEqual( - findings, - [ - ("missing", "bios/Other/sdlpal/sdlpal/5.avi", 82833972, None), - ("size", "bios/Other/fbneo/fbneo/samples/twotiger.zip", 154985212, 154888877), - ], - ) - - def test_expected_assets_are_the_gitignored_database_entries(self): - from scripts.release import assets as release_assets - - db = { - "files": { - "a" * 40: {"path": "bios/Other/x/big.zip", "size": 10}, - "b" * 40: {"path": "bios/Other/x/small.bin", "size": 2}, - } - } - gitignore = "# large\nbios/Other/x/big.zip\ntmp/\n" - self.assertEqual( - release_assets.expected_assets(db, gitignore), - {"bios/Other/x/big.zip": 10}, - ) - - def test_release_notes_are_rendered_from_the_collection(self): - """The release page is written by hand and drifts, so it is rendered instead. - - Three assets had no row, three rows carried the SHA1 of an asset - that had since been replaced, and the footer counted 41 files for 44. - Hand-written descriptions survive by name. A new row takes its - description from the profile that declares the file, and an asset the - collection does not index is listed apart, with its size only. - """ - from scripts.release import assets as release_assets - - db = {"files": { - "a" * 40: {"path": "bios/Nintendo/Wii/nand.bin", "size": 553649152}, - "b" * 40: {"path": "bios/Other/fbneo/fbneo/samples/twotiger.zip", "size": 154985212}, - "c" * 40: {"path": "bios/Other/x/small.bin", "size": 2}, - }} - gitignore = "bios/Nintendo/Wii/nand.bin\nbios/Other/fbneo/fbneo/samples/twotiger.zip\n" - assets = {"nand.bin": 553649152, "twotiger.zip": 154985212, - "sdlpal-data.zip": 140773720, "whoopee.zip": 222665810} - previous = ( - "## Arcade\n\n| File | Description | Size | SHA1 |\n|---|---|---|---|\n" - "| [twotiger.zip](u) | Two Tigers samples | 148 MB | `" + "0" * 40 + "` |\n" - "| [whoopee.zip](u) | Toaplan Whoopee samples | 212 MB | `" + "9" * 40 + "` |\n" - ) - descriptions = {"nand.bin": "BootMii NAND backup"} - bundles = {"sdlpal-data.zip": "SDLPAL Chinese Paladin game data (.mkf archives)"} - body = release_assets.render_notes( - db, gitignore, assets, previous, descriptions, bundles, {"sdlpal-data.zip": "d" * 40} - ) - self.assertIn("| [twotiger.zip](https://github.com/Abdess/retrobios/releases/download/large-files/twotiger.zip) | Two Tigers samples | 147.8 MB | `" + "b" * 40 + "` |", body) - self.assertIn("| [nand.bin](https://github.com/Abdess/retrobios/releases/download/large-files/nand.bin) | BootMii NAND backup | 528.0 MB | `" + "a" * 40 + "` |", body) - self.assertIn("| [sdlpal-data.zip](https://github.com/Abdess/retrobios/releases/download/large-files/sdlpal-data.zip) | SDLPAL Chinese Paladin game data (.mkf archives) | 134.3 MB | `" + "d" * 40 + "` |", body) - self.assertIn("## Not indexed", body) - self.assertIn("| [whoopee.zip](https://github.com/Abdess/retrobios/releases/download/large-files/whoopee.zip) | Toaplan Whoopee samples | 212.4 MB |", body) - self.assertNotIn("9" * 40, body) - self.assertNotIn("small.bin", body) - # The total reads in the unit of the rows above it: 1022.4 MB, not 1.0 GB. - self.assertIn("4 files, 1022.4 MB total", body) - self.assertEqual(body.index("## Console firmware"), min( - body.index(h) for h in ("## Console firmware", "## Arcade", "## Not indexed") - )) - - def test_stale_notes_are_a_finding(self): - from scripts.release import assets as release_assets - - findings = release_assets.compare({}, {}, notes_current=False) - self.assertEqual(findings, [("notes", "release description", 0, None)]) - - def test_pipeline_runs_the_check_online_and_marks_it_skipped_offline(self): - """Run with each step recorded instead of executed: reading the - source for two strings stayed green with the guard inverted.""" - import contextlib - import io - from unittest import mock - - from scripts import pipeline - - def steps(*flags: str) -> tuple[list[str], str]: - ran: list[str] = [] - - def record(cmd, label): - ran.append(label) - return True, "" - - argv = ["pipeline.py", "--skip-packs", "--skip-docs", *flags] - with mock.patch.object(runner, "run", record), \ - mock.patch.object(sys, "argv", argv), \ - contextlib.redirect_stdout(io.StringIO()) as out, \ - self.assertRaises(SystemExit) as done: - pipeline.main() - self.assertEqual(done.exception.code, 0) - return ran, out.getvalue() - - online, _ = steps() - self.assertIn("2b2 check release assets", online) - offline, printed = steps("--offline") - self.assertNotIn("2b2 check release assets", offline) - self.assertIn("check_release_assets.................... SKIPPED", printed) - - -class OneRefreshPerOnlineRun(unittest.TestCase): - """An online run refreshed the data trees at step 2, again in the pack - build and again in the manifest build: a moving tree (fbneo-cheats on - master) could change between the two, and the pack and the manifest - described different revisions.""" - - def test_the_builds_reuse_step_twos_trees(self): - import contextlib - import io - from unittest import mock - - from scripts import pipeline - - commands: dict[str, list[str]] = {} - - def record(cmd, label): - commands[label] = cmd - return True, "" - - # A scratch output directory: step 4 purges the ZIPs of the one it - # is given, and this run must never touch dist/. - with tempfile.TemporaryDirectory() as out, \ - mock.patch.object(runner, "run", record), \ - mock.patch.object( - sys, "argv", ["pipeline.py", "--skip-docs", "--output-dir", out] - ), \ - contextlib.redirect_stdout(io.StringIO()), \ - self.assertRaises(SystemExit): - pipeline.main() - self.assertIn("2 refresh data directories", commands) - for label in ("4 generate packs", "4b generate install manifests"): - with self.subTest(step=label): - self.assertIn("--no-refresh-data", commands[label]) - self.assertNotIn("--offline", commands[label]) - - -class PreservedBytesAreNeverNormalised(unittest.TestCase): - """git must not rewrite a preserved file's line endings. - - SHA1 is the primary key of this collection. Git for Windows sets - core.autocrlf=true by default, so without an attribute saying otherwise a - clone there rewrites every file git guesses is text -- shaders, .ini, - .txt and .dat assets under bios/ -- and each one arrives with a different - hash from the one published here. - """ - - def _attr(self, path: str) -> str: - import subprocess - - out = subprocess.run( - ["git", "check-attr", "text", "--", path], - capture_output=True, text=True, cwd=ROOT, - check=False, - ).stdout - return out.rsplit(":", 1)[-1].strip() - - def test_gitattributes_exists(self): - self.assertTrue( - (ROOT / ".gitattributes").is_file(), - "without it git guesses, and guesses wrong on Windows", - ) - - def test_collection_paths_are_exempt_from_normalisation(self): - for path in ( - "bios/Sony/PlayStation/scph5501.bin", - "bios/Other/j2me-loader/color.fsh", - "data/anything.txt", - "data/dolphin-sys/config.json", - ): - with self.subTest(path=path): - self.assertEqual(self._attr(path), "unset", f"{path} may be rewritten") - - def test_generated_artefacts_stay_lf(self): - for path in ( - "database.json", - "scripts/dedup.py", - "README.md", - "provenance/redump.json", - ): - with self.subTest(path=path): - self.assertEqual(self._attr(path), "set") - - -class FreshnessGuardMechanics(unittest.TestCase): - """write_if_changed is what makes `git diff --exit-code` a real check. - - deploy-site.yml regenerates README.md and CONTRIBUTING.md and then fails - if git sees a change. That is only a staleness check because a run which - moves nothing but the clock leaves the file untouched. If the comparison - missed a timestamp form, the guard would fail on every run and stop - meaning anything. - """ - - def setUp(self): - from core.artifacts import write_if_changed - - self.write_if_changed = write_if_changed - self._tmp = tempfile.TemporaryDirectory() - self.path = os.path.join(self._tmp.name, "page.md") - - def tearDown(self): - self._tmp.cleanup() - - def test_a_new_file_is_written(self): - self.assertTrue(self.write_if_changed(self.path, "body\n")) - with open(self.path) as handle: - self.assertEqual(handle.read(), "body\n") - - def test_identical_content_is_not_rewritten(self): - self.write_if_changed(self.path, "body\n") - self.assertFalse(self.write_if_changed(self.path, "body\n")) - - def test_real_change_is_written(self): - self.write_if_changed(self.path, "body\n") - self.assertTrue(self.write_if_changed(self.path, "other\n")) - - def test_every_timestamp_form_is_ignored_on_its_own(self): - forms = [ - '{{"generated_at": "{}"}}', - '{{"imported_at": "{}"}}', - '{{"generated": "{}"}}', - '{{"fetched": "{}"}}', - "*Auto-generated on {}*", - "*Generated on {}*", - '
Generated on {}.
', - ] - for form in forms: - with self.subTest(form=form): - first = form.format("2026-01-01T00:00:00Z") - second = form.format("2026-09-09T09:09:09Z") - self.write_if_changed(self.path, first) - self.assertFalse( - self.write_if_changed(self.path, second), - f"a clock-only change rewrote the file for {form!r}", - ) - - def test_a_change_beside_a_moving_timestamp_is_still_written(self): - self.write_if_changed(self.path, "count: 1\n*Generated on A*\n") - self.assertTrue( - self.write_if_changed(self.path, "count: 2\n*Generated on B*\n") - ) - - def test_the_written_file_keeps_the_new_timestamp_when_content_changed(self): - self.write_if_changed(self.path, "count: 1\n*Generated on A*\n") - self.write_if_changed(self.path, "count: 2\n*Generated on B*\n") - with open(self.path) as handle: - self.assertIn("Generated on B", handle.read()) - - - -class AMissingDependencyStopsTheBuild(unittest.TestCase): - """generate_db read every alias inside `try: import yaml ... except - ImportError: pass`: on an interpreter without pyyaml the database lost - 3186 alias lines and the run exited 0.""" - - def test_generate_db_without_pyyaml_fails(self): - with tempfile.TemporaryDirectory() as tmp: - output = Path(tmp) / "database.json" - proc = subprocess.run( - [sys.executable, "-S", "scripts/generate_db.py", "--force", - "--bios-dir", "bios", "--output", str(output)], - cwd=ROOT, capture_output=True, text=True, timeout=600, check=False, - ) - self.assertNotEqual(proc.returncode, 0, proc.stdout) - self.assertIn("PyYAML required", proc.stderr) - self.assertFalse(output.exists()) - - def test_every_yaml_command_stops_on_one_line(self): - """refresh_data_dirs and check_buildbot_system ended on a traceback.""" - for command in (["scripts/refresh_data_dirs.py", "--dry-run"], - ["scripts/check_buildbot_system.py"]): - with self.subTest(command=command[0]): - proc = subprocess.run( - [sys.executable, "-S", *command], - cwd=ROOT, capture_output=True, text=True, timeout=120, check=False, - ) - self.assertEqual(proc.returncode, 1, proc.stdout) - self.assertEqual( - proc.stderr.strip(), "Error: PyYAML required (pip install pyyaml)" - ) - - def test_no_script_swallows_an_import_error(self): - offenders = [] - for path in sorted((ROOT / "scripts").rglob("*.py")): - tree = ast.parse(path.read_text(encoding="utf-8")) - offenders.extend( - f"{path.relative_to(ROOT)}:{node.lineno}" - for node in ast.walk(tree) - if ( - isinstance(node, ast.ExceptHandler) - and isinstance(node.type, ast.Name) - and node.type.id in ("ImportError", "ModuleNotFoundError") - and all(isinstance(stmt, ast.Pass) for stmt in node.body) - ) - ) - self.assertEqual(offenders, []) - - -class TestsCleanUpTheirScratch(unittest.TestCase): - """Sixteen classes called mkdtemp() and kept the directory: each suite - run left about 400 of them on the RAM-backed /tmp.""" - - def test_every_class_that_makes_a_directory_removes_it(self): - offenders = [] - for path in sorted((ROOT / "tests").glob("test_*.py")): - source = path.read_text(encoding="utf-8") - for node in ast.parse(source).body: - if not isinstance(node, ast.ClassDef): - continue - body = ast.get_source_segment(source, node) or "" - if "mkdtemp(" in body and not any( - word in body for word in ("rmtree", "addCleanup", "tearDown") - ): - offenders.append(f"{path.name}:{node.name}") - self.assertEqual(offenders, []) - - -class PipelineReportsWhatItDid(unittest.TestCase): - """A step that did not run must not be summarised as OK. - - --offline skips the network steps and --with-export gates three more. - Reporting them as OK claims work nobody did, and a run whose export - never happened read exactly like one where it had. - """ - - def test_a_skipped_step_is_not_reported_as_done(self): - self.assertTrue(bool(results.SKIPPED), "a skip must not fail the run") - self.assertEqual(repr(results.SKIPPED), "SKIPPED") - self.assertIsNot(results.SKIPPED, True) - - def test_every_skip_branch_uses_the_sentinel(self): - source = script_source("pipeline.py") - stale = re.findall(r'results\["(\w+)"\] = True', source) - self.assertEqual(stale, [], f"steps still claiming OK when skipped: {stale}") - -class DeclaredDependenciesMatchTheDocumentedWorkflows(unittest.TestCase): - """What the workflows install has to be what the project declares. - - mkdocs-material and pymdown-extensions were hard requirements of the site - build in CI and in the release guide while pyproject declared neither, so - a contributor following either had to read the workflow to find out. - """ - - @staticmethod - def _pyproject() -> dict: - import tomllib - - with (ROOT / "pyproject.toml").open("rb") as handle: - return tomllib.load(handle) - - def test_every_package_ci_installs_is_declared(self): - extras = self._pyproject()["project"]["optional-dependencies"] - declared = { - name.split(">")[0].split("=")[0].split("<")[0].strip('"') - for group in extras.values() - for name in group - } - declared |= set(self._pyproject()["project"]["dependencies"]) - installed: set[str] = set() - for workflow in ("validate.yml", "deploy-site.yml"): - body = (ROOT / ".github" / "workflows" / workflow).read_text( - encoding="utf-8" - ) - for line in body.splitlines(): - if "pip install" not in line: - continue - for token in line.split("pip install", 1)[1].split(): - name = token.strip('"').split(">")[0].split("=")[0] - name = name.split("<")[0].strip() - if name: - installed.add(name) - self.assertEqual( - installed - declared, - set(), - "CI installs packages pyproject does not declare", - ) - - -class TheAnnotationsAreChecked(unittest.TestCase): - """Every signature carried type hints and nothing read them: six pack - helpers declared `zipfile.ZipFile` while every caller also passed a - PackRecord, and 990 such contradictions went through CI green. They sat - in a baseline until the last one was fixed: the code now carries no - type error, and CI runs mypy bare, so any new one fails.""" - - def test_ci_runs_mypy_without_a_baseline(self): - body = (ROOT / ".github" / "workflows" / "validate.yml").read_text( - encoding="utf-8" - ) - self.assertRegex(body, r"(?m)^\s+mypy$") - self.assertNotIn("mypy-baseline", body) - self.assertFalse((ROOT / "mypy-baseline.txt").exists()) - - def test_the_code_reports_no_type_error(self): - try: - __import__("mypy") - except ImportError: - self.skipTest("mypy is not installed (pip install -e '.[dev]')") - report = subprocess.run( - [sys.executable, "-m", "mypy"], - cwd=ROOT, capture_output=True, text=True, check=False, - ) - self.assertEqual(report.returncode, 0, report.stdout[-4000:]) - - -class TheProjectInstallsWithPip(unittest.TestCase): - """pyproject declared a dev extra that pip could not install: without a - [build-system] and an explicit module list, setuptools' flat-layout - discovery found scripts/ and tests/ and refused to build.""" - - def test_setuptools_discovers_nothing_to_package(self): - import importlib.util - - if importlib.util.find_spec("setuptools") is None: - # The dev extra and CI install it: skipped there, the guard held - # nothing on any run. - if os.environ.get("CI"): - self.fail("CI must install setuptools") - self.skipTest("setuptools is not installed") - program = ( - "from setuptools.dist import Distribution\n" - "from setuptools.config.pyprojecttoml import apply_configuration\n" - "dist = apply_configuration(Distribution(), 'pyproject.toml')\n" - "dist.set_defaults()\n" - "print(sorted(dist.packages or []), sorted(dist.py_modules or []))\n" - ) - done = subprocess.run([sys.executable, "-c", program], cwd=ROOT, - capture_output=True, text=True, check=False) - self.assertEqual(done.returncode, 0, done.stderr[-2000:]) - self.assertEqual(done.stdout.strip(), "[] []") - import tomllib - - with (ROOT / "pyproject.toml").open("rb") as handle: - build = tomllib.load(handle)["build-system"] - self.assertEqual(build["build-backend"], "setuptools.build_meta") - - -class ACheckThatCannotAnswerDoesNotPass(unittest.TestCase): - """Exiting zero says the question was answered and the answer was yes. - - Four scripts said that without answering: a refresh that reached no - remote, a freshness check whose upstream was unreachable, a restore whose - cache could not supply a declared path, and a pack verification asked - about one platform whose pack was not there. - """ - - def test_naming_a_platform_with_no_pack_is_not_a_pass(self): - with tempfile.TemporaryDirectory() as directory: - named = subprocess.run( - [sys.executable, "scripts/generate_pack.py", "--platform", - "retroarch", "--verify-packs", "--output-dir", directory], - capture_output=True, text=True, cwd=str(ROOT), timeout=300, - check=False, - ) - self.assertNotEqual( - named.returncode, 0, - "a named platform with no pack reported success:\n" - + named.stdout + named.stderr, - ) - # --all is a sweep: a platform nobody built is out of scope and - # skipped, but a sweep that found no pack at all checked nothing. - swept = subprocess.run( - [sys.executable, "scripts/generate_pack.py", "--all", - "--verify-packs", "--output-dir", directory], - capture_output=True, text=True, cwd=str(ROOT), timeout=300, - check=False, - ) - self.assertIn("SKIP (no pack in", swept.stdout) - self.assertNotEqual(swept.returncode, 0, swept.stdout + swept.stderr) - - def test_an_unsatisfiable_declared_path_is_reported(self): - from scripts.release.restore import restore - - with tempfile.TemporaryDirectory() as directory: - root = Path(directory) - cache = root / "cache" - cache.mkdir() - (root / ".gitignore").write_text("bios/absent.bin\n", encoding="utf-8") - (root / "database.json").write_text( - json.dumps({"files": {"a" * 40: {"path": "bios/absent.bin"}}}), - encoding="utf-8", - ) - result = restore( - str(cache), str(root / "database.json"), str(root / ".gitignore"), - root=root, - ) - self.assertEqual(result.restored, []) - self.assertEqual(result.unsatisfied, ["bios/absent.bin"]) - - def test_an_unreachable_buildbot_is_not_a_fresh_verdict(self): - """Every HEAD unanswered printed "16 unknown" and exited 0, so the - online pipeline printed check_buildbot OK.""" - import check_buildbot_system as cbs - from scraper import buildbot_system - - registry = str(ROOT / "platforms" / "_data_dirs.yml") - tracked = buildbot_system.load_tracked_entries(registry) - self.assertTrue(tracked) - cases = { - "index unreachable": mock.patch.object( - buildbot_system, "fetch_index", side_effect=OSError("down")), - "every HEAD unanswered": mock.patch.object( - buildbot_system, "fetch_index", return_value=set(tracked)), - } - for label, index in cases.items(): - with self.subTest(label), index, \ - mock.patch.object(buildbot_system, "get_remote_etag", return_value=None), \ - mock.patch.object(sys, "argv", ["check_buildbot_system.py", - "--registry", registry]), \ - contextlib.redirect_stdout(io.StringIO()), \ - self.assertRaises(SystemExit) as stop: - cbs.main() - self.assertEqual(stop.exception.code, 1) - - def test_a_missing_profile_directory_says_so(self): - # Bare names, as the loader imports them: scripts.core.cli would be a - # second copy of the module, with a second InputMissing. - from core.cli import InputMissing - from model.profiles import load_emulator_profiles - - with self.assertRaisesRegex(InputMissing, "no emulator profile directory"): - load_emulator_profiles(str(ROOT / "no-such-emulator-dir")) - - -class TestEntryPointsRunEveryClass(unittest.TestCase): - """`unittest.main()` has to sit after the last test class. - - In this file it sat in the middle, so running it directly discovered only - the classes defined above it: eight cases never ran that way, while - `python -m unittest discover` ran all of them. The two roads have to agree. - """ - - def test_no_module_calls_main_before_its_last_class(self): - for path in sorted((ROOT / "tests").glob("test_*.py")): - lines = path.read_text(encoding="utf-8").splitlines() - # Column zero only: the same text appears inside this very test as - # a string literal, and a substring search matched that instead. - entry = next( - (n for n, line in enumerate(lines) - if line.startswith("if __name__ ==")), - None, - ) - if entry is None: - continue - last_class = max( - (n for n, line in enumerate(lines) if line.startswith("class ")), - default=-1, - ) - self.assertGreater( - entry, - last_class, - f"{path.name} calls unittest.main() before its last class, so " - "running the file directly skips what follows", - ) - - -class ScriptsImportThreeWays(unittest.TestCase): - """A script is run directly, run as a module, and imported as a package. - - The three do not agree on what is on the path: only the first form adds - the scripts directory. Adding the package marker without the bootstrap - made `import scripts.common` (now scripts.core.cli) fail on the first sibling import it reached. - """ - - def _run(self, *args: str): - import subprocess - - return subprocess.run( - [sys.executable, *args], - capture_output=True, text=True, cwd=str(ROOT), timeout=300, - check=False, - ) - - def test_imported_as_a_package(self): - result = self._run( - "-c", "import scripts.core.cli, scripts.model.platforms, scripts.resolve.localfile, " - "scripts.verify, scripts.generate_pack" - ) - self.assertEqual(result.returncode, 0, result.stderr[-400:]) - - def test_run_as_a_module(self): - result = self._run("-m", "scripts.scraper.libretro_scraper", "--help") - self.assertEqual(result.returncode, 0, result.stderr[-400:]) - - def test_run_as_a_script(self): - result = self._run("scripts/list_platforms.py") - self.assertEqual(result.returncode, 0, result.stderr[-400:]) - - -class ContributorsSurviveAFailedRequest(unittest.TestCase): - """The one part of the README that comes from the network. - - A refused or rate-limited request left the list empty, which deleted the - section from a published README. It happened during a pipeline run and - the result was committed, after which the freshness check regenerated the - section and failed on the difference. Losing the list is a worse answer - than publishing a stale one. - """ - - def _block(self, text: str): - import tempfile - - from sitegen.readme import _existing_contributor_block - - with tempfile.NamedTemporaryFile("w", suffix=".md", delete=False) as handle: - handle.write(text) - name = handle.name - try: - return _existing_contributor_block(name) - finally: - os.unlink(name) - - def test_a_published_list_is_read_back(self): - text = ( - "# Title\n\n## Contributors\n\n" - 'a\n' - 'b\n\n' - "## Community tools\n\nsomething else\n" - ) - block = self._block(text) - self.assertEqual(block[0], "## Contributors") - self.assertIn('alt="a"', "\n".join(block)) - self.assertIn('alt="b"', "\n".join(block)) - self.assertNotIn("Community tools", "\n".join(block)) - self.assertNotIn("something else", "\n".join(block)) - - def test_a_readme_without_the_section_yields_nothing(self): - self.assertEqual(self._block("# Title\n\n## Other\n\ntext\n"), []) - - def test_an_unreadable_file_yields_nothing(self): - from sitegen.readme import _existing_contributor_block - - self.assertEqual(_existing_contributor_block("/nonexistent/README.md"), []) - - def test_the_committed_readme_still_carries_its_contributors(self): - """Regenerating offline must never be the reason this disappears.""" - text = (ROOT / "README.md").read_text() - # Missing is the failure this guards, never a reason to skip. - self.assertIn("## Contributors", text) - self.assertGreater( - text.count('a'] - text = render_readme(readme_inputs(kept_contributors=kept)) - self.assertIn("\n".join(kept) + "\n\n\n## Community tools", text) - - def test_a_fetched_list_replaces_the_kept_block(self): - from sitegen.readme import render_readme - from tests.readmeinputs import readme_inputs - - text = render_readme(readme_inputs( - contributors=[{"login": "someone", "avatar_url": "https://a/x"}], - kept_contributors=["## Contributors", "", "stale"], - )) - self.assertIn( - '## Contributors\n\nsomeone\n', text) - self.assertNotIn("stale", text) - - def test_no_list_and_nothing_kept_leaves_the_section_out(self): - from sitegen.readme import render_readme - from tests.readmeinputs import readme_inputs - - self.assertNotIn("## Contributors", render_readme(readme_inputs())) - - def test_the_loader_keeps_the_published_block_when_the_request_fails(self): - import tempfile - - from sitegen import readme - - with tempfile.TemporaryDirectory() as tmp: - path = Path(tmp) / "README.md" - path.write_text("# T\n\n## Contributors\n\nkept line\n\n## Other\n", encoding="utf-8") - with mock.patch.object(readme, "README_PATH", path), \ - mock.patch.object(readme, "fetch_contributors", return_value=[]), \ - mock.patch.object(readme, "list_registered_platforms", return_value=[]), \ - mock.patch("model.registry.load_data_dir_registry", return_value={}), \ - mock.patch.object(readme, "platform_coverages", return_value={}), \ - mock.patch.object(readme, "load_emulator_profiles", return_value={}), \ - mock.patch.object(readme.releaserecord, "load_advertised", return_value={}), \ - mock.patch.object(readme, "_extract_cells", return_value={}), \ - mock.patch.object(readme.ledger, "rebuild_counts", - return_value={"total": 0, "exact": 0, "canonical": 0}), \ - mock.patch.object(readme, "clone_line", return_value=""), \ - mock.patch("sys.stdout", new_callable=io.StringIO): - inputs = readme.load_readme_inputs({}, "platforms") - self.assertEqual(inputs.kept_contributors, ["## Contributors", "", "kept line"]) - self.assertIn("## Contributors\n\nkept line\n", readme.render_readme(inputs)) - - def test_the_contributor_list_is_not_asked_offline(self): - from sitegen import readme - - with mock.patch.dict(os.environ, {"RETROBIOS_OFFLINE": "1"}), \ - mock.patch.object(readme.forgehttp, "fetch_body", - side_effect=AssertionError("network")): - self.assertEqual(readme.fetch_contributors(), []) - - def test_contributors_are_read_through_the_retrying_client(self): - from sitegen import readme - - answer = json.dumps([ - {"login": "someone", "type": "User"}, - {"login": "dependabot[bot]", "type": "Bot"}, - {"login": readme.REPO.split("/")[0], "type": "User"}, - ]).encode() - with mock.patch.dict(os.environ, {"RETROBIOS_OFFLINE": ""}), \ - mock.patch.object(readme.forgehttp, "fetch_body", return_value=answer) as fetch: - self.assertEqual([c["login"] for c in readme.fetch_contributors()], ["someone"]) - self.assertIn("/contributors", fetch.call_args.args[0]) - - -class APackNameFitsAFileName(unittest.TestCase): - """--system snes joined 23 emulator names and died on ENAMETOOLONG - before writing anything, while verify --system snes reported.""" - - def test_a_long_selection_is_bounded_and_told_apart(self): - from scripts.packs.naming import MAX_PACK_NAME_BYTES, bounded_join - - def bounded_pack_name(display: list[str], keys: list[str], suffix: str) -> str: - return bounded_join(display, keys, joiner="_", budget=MAX_PACK_NAME_BYTES, suffix=suffix) - - names = [f"Emulator_Number_{i}" for i in range(23)] - long_name = bounded_pack_name(names, names, "_BIOS_Pack.zip") - self.assertLessEqual(len(long_name.encode()), MAX_PACK_NAME_BYTES) - self.assertTrue(long_name.startswith("Emulator_Number_0_and_22_more_")) - other = bounded_pack_name(names, names[:-1] + ["x"], "_BIOS_Pack.zip") - self.assertNotEqual(long_name, other) - self.assertEqual(bounded_pack_name(["A", "B"], ["a", "b"], ".zip"), "A_B.zip") - - def test_a_long_system_list_is_bounded(self): - """Thirty systems joined made a 261-byte platform pack name.""" - from scripts.packs.naming import MAX_SYSTEM_TAG_BYTES, system_tag - - systems = [f"vendor-console-number-{i}" for i in range(30)] - tag = system_tag(systems) - self.assertLessEqual(len(tag.encode()), MAX_SYSTEM_TAG_BYTES + 1) - self.assertNotEqual(tag, system_tag(systems[:-1] + ["other-console"])) - self.assertEqual(system_tag(["sony-playstation"]), "_Playstation") - - def test_two_systems_never_name_one_system(self): - """sega-dreamcast,arcade and sega-dreamcast-arcade both wrote - RetroArch_..._Dreamcast_Arcade.zip, and the second replaced the first.""" - from scripts.packs.naming import system_tag - - pairs = [ - (["sega-dreamcast", "arcade"], ["sega-dreamcast-arcade"]), - (["mega-cd", "sega-32x"], ["mega-cd-32x"]), - (["x86", "nintendo-64"], ["x86-64"]), - ] - for two, one in pairs: - with self.subTest(two=two): - self.assertNotEqual(system_tag(two), system_tag(one)) - - def test_two_hash_lists_get_two_names(self): - """--from-md5 named its pack after the context only: a second list - overwrote the first pack in the same directory.""" - source = script_source("generate_pack.py") - self.assertIn('_Custom_{selection}', source) - - def test_the_system_pack_names_itself(self): - source = script_source("generate_pack.py") - self.assertIn("pack_name=final_name", source) - - -class AGroupPackIsWrittenUnderItsOwnName(unittest.TestCase): - """The RetroArch + Lakka pack was written as RetroArch_..._BIOS_Pack.zip - and renamed: a `--platform retroarch` pack already in the directory was - overwritten then carried away, and os.rename refuses an existing target - on Windows.""" - - def test_no_pack_is_renamed_after_its_build(self): - source = script_source("generate_pack.py") - self.assertNotIn("os.rename(", source) - self.assertIn("pack_name=group_name", source) - - -class ARegionDroppedExtraBlocksNothing(unittest.TestCase): - """The builder skips a region-dropped core extra before placing it, - but the report placed it anyway, so on a case-folding platform it hid the - next core's FOO.ROM that the pack does carry.""" - - def test_the_report_skips_what_the_region_pass_drops(self): - from unittest import mock - - from scripts.packs import extraresolver - - with tempfile.TemporaryDirectory() as directory: - other = Path(directory) / "FOO.ROM" - other.write_bytes(b"other bytes") - first = Path(directory) / "foo.rom" - first.write_bytes(b"first bytes") - copies = {"foo.rom": str(first), "FOO.ROM": str(other)} - extras = [ - {"name": "foo.rom", "destination": "foo.rom", "source_emulator": "a"}, - {"name": "FOO.ROM", "destination": "FOO.ROM", "source_emulator": "b"}, - ] - config = {"case_insensitive_fs": True, "base_destination": ""} - - def report(region_drops): - with mock.patch.object(extraresolver, "collect_emulator_extras", - return_value=extras), \ - mock.patch.object(extraresolver, "resolve_local_file", - side_effect=lambda fe, *a, **k: ( - copies[fe["name"]], "name_exact")): - return extraresolver.hidden_extras( - config, "emulators", {"files": {}}, {}, {}, None, region_drops - ) - - self.assertTrue(report(None)) - self.assertEqual(report({"foo.rom"}), {}) - - -class AnotherEmulatorsTreeProvesNothing(unittest.TestCase): - """lrps2 names no hash for pcsx2/resources/GameIndex.yaml, and the only - full-tail copy was ARMSX2's, which counted as path proof and replaced - the GameIndex RetroArch pins on desktop targets, where ARMSX2 does not - exist. Upstream PCSX2 took ARMSX2's patches.zip by name the same way.""" - - def _db(self, root, files): - import hashlib - - db = {"files": {}, "indexes": {"by_name": {}, "by_md5": {}, "by_crc32": {}, - "by_path_suffix": {}}} - for relative, payload in files.items(): - path = root / relative - path.parent.mkdir(parents=True, exist_ok=True) - path.write_bytes(payload) - sha1 = hashlib.sha1(payload).hexdigest() - db["files"][sha1] = {"path": relative, "name": path.name, "sha1": sha1, - "size": len(payload)} - db["indexes"]["by_name"].setdefault(path.name, []).append(sha1) - parts = relative.split("/") - for start in range(1, len(parts) - 1): - db["indexes"]["by_path_suffix"].setdefault( - "/".join(parts[start:]), []).append(sha1) - return db - - def test_neither_the_full_tail_nor_the_name_lands_in_a_foreign_tree(self): - from scripts.resolve.localfile import resolve_local_file - - with tempfile.TemporaryDirectory() as directory: - root = Path(directory) - # The collection's layout, read relative to its root. - previous = os.getcwd() - os.chdir(root) - self.addCleanup(os.chdir, previous) - db = self._db(root, { - "bios/Other/armsx2/pcsx2/resources/GameIndex.yaml": b"fork", - "bios/Other/armsx2/pcsx2/resources/patches.zip": b"fork patches", - "bios/Sony/PlayStation 2/patches.zip": b"upstream patches", - }) - index, status = resolve_local_file( - {"name": "GameIndex.yaml", "path": "pcsx2/resources/GameIndex.yaml", - "source_profile": "lrps2"}, - db, dest_hint="pcsx2/resources/GameIndex.yaml", - ) - # Held only in the fork's tree, the file answers by name and - # proves nothing about this entry. - self.assertEqual(status, "name_exact") - patches, _status = resolve_local_file( - {"name": "patches.zip", "path": "resources/patches.zip", - "source_profile": "pcsx2"}, - db, dest_hint="resources/patches.zip", - ) - self.assertTrue(patches.endswith("PlayStation 2/patches.zip")) - - def test_no_desktop_retroarch_pack_serves_armsx2s_tree(self): - from scripts.packs import slots - from scripts.model.registry import load_data_dir_registry - from scripts.model.database import load_database - from scripts.model.profiles import load_emulator_profiles - from scripts.model.platforms import load_platform_config - from scripts.model.targets import load_target_config - - if not (ROOT / "database.json").exists(): - self.skipTest("database.json is not generated") - db = load_database(str(ROOT / "database.json")) - config = load_platform_config("retroarch", str(ROOT / "platforms")) - profiles = load_emulator_profiles(str(ROOT / "emulators")) - cores = set(load_target_config("retroarch", "x86_64", str(ROOT / "platforms"))) - overrides = slots.pack_overrides( - config, profiles, db, None, load_data_dir_registry(str(ROOT / "platforms")), - target_cores=cores, - ) - self.assertFalse([d for d, p in overrides.items() if "/armsx2/" in p]) - - -class APinnedCoreFileTakesTheSlotFirst(unittest.TestCase): - """hypseus-singe asks for gamecontrollerdb.txt by name and took the BIOS - root of Batocera, RetroBat and RetroPie with C-Dogs' 26 KB table, where - Solarus pins its own by sha1.""" - - def test_the_content_naming_claim_is_placed_first(self): - from unittest import mock - - from scripts.packs import extras as packextras - - undeclared = [ - {"profile": "hypseus", "emulator": "hypseus", "name": "db.txt", - "path": "db.txt", "in_repo": True, "systems": ["a"]}, - {"profile": "solarus", "emulator": "solarus", "name": "db.txt", - "path": "db.txt", "in_repo": True, "systems": ["b"], "sha1": "a" * 40}, - ] - config = {"systems": {}, "base_destination": "bios"} - with mock.patch("packs.gaps.find_undeclared_files", return_value=undeclared), \ - mock.patch.object(packextras, "resolve_platform_cores", - return_value=set()) as cores: - extras = packextras.collect_emulator_extras( - config, "emulators", {"files": {}, "indexes": {}}, set(), "bios", {} - ) - self.assertEqual([e["source_profile"] for e in extras][:1], ["solarus"]) - # The stub is what ran: patched with create=True on a name the module - # imported inside the function, it was never read and the real - # resolve_platform_cores walked the repository's profiles. - cores.assert_called_once() - - -class ANameWithItsDirectoryIsTheDestination(unittest.TestCase): - """gam4980 declares gam4980/E.BIN with no path: resolved by its basename, - verify --emulator and the emulator pack took the A4980's OS while the - platform pack served the GAM4980's.""" - - def test_the_directory_in_the_name_picks_the_copy(self): - import hashlib - - from scripts.resolve.localfile import resolve_local_file - - with tempfile.TemporaryDirectory() as directory: - root = Path(directory) - previous = os.getcwd() - os.chdir(root) - self.addCleanup(os.chdir, previous) - files, by_name, by_suffix = {}, {}, {} - for relative, payload in (("bios/BBK/A4980/A4980/E.BIN", b"a4980"), - ("bios/BBK/GAM4980/gam4980/E.BIN", b"gam4980")): - Path(relative).parent.mkdir(parents=True, exist_ok=True) - Path(relative).write_bytes(payload) - sha1 = hashlib.sha1(payload).hexdigest() - files[sha1] = {"path": relative, "name": "E.BIN", "sha1": sha1} - by_name.setdefault("E.BIN", []).append(sha1) - parent = relative.split("/")[-2] - by_suffix.setdefault(f"{parent}/E.BIN", []).append(sha1) - db = {"files": files, "indexes": {"by_name": by_name, "by_md5": {}, - "by_crc32": {}, "by_path_suffix": by_suffix}} - path, status = resolve_local_file( - {"name": "gam4980/E.BIN", "source_profile": "gam4980"}, db - ) - self.assertEqual((path, status), ("bios/BBK/GAM4980/gam4980/E.BIN", "path_exact")) - - -class AnUnreadableDatabaseStopsTheScan(unittest.TestCase): - """A database.json left with merge markers read as an absent one: every - release-asset entry silently left the rewritten database, then the - manifests.""" - - def test_a_corrupt_database_is_not_an_empty_one(self): - from collection import releaseassets - - with tempfile.TemporaryDirectory() as directory: - path = Path(directory) / "database.json" - path.write_text("<<<<<<< HEAD\n{}\n") - with self.assertRaises(releaseassets.DatabaseUnreadable) as caught: - releaseassets.read_database(str(path)) - self.assertIn("is not valid JSON", str(caught.exception)) - self.assertIsNone( - releaseassets.read_database(str(Path(directory) / "absent.json")) - ) - - def test_the_build_exits_1_on_it(self): - import argparse - import io - from contextlib import redirect_stderr, redirect_stdout - from unittest import mock - - from collection import run - - with tempfile.TemporaryDirectory() as directory: - root = Path(directory) - (root / "bios").mkdir() - output = root / "database.json" - output.write_text("<<<<<<< HEAD\n{}\n") - args = argparse.Namespace( - bios_dir=str(root / "bios"), force=True, output=str(output), - offline=True, platforms_dir=str(root), emulators_dir=str(root), - provenance_dir=str(root), - ) - err = io.StringIO() - with mock.patch.object(run, "load_gitignored_large_files", - return_value={"bios/big.bin"}), \ - redirect_stdout(io.StringIO()), redirect_stderr(err): - self.assertEqual(run.generate(args), 1) - self.assertIn("is not valid JSON", err.getvalue()) - self.assertFalse((root / ".cache").exists()) - self.assertTrue(output.read_text().startswith("<<<<<<<")) - - -class TheDigestCacheBelongsToTheScannedTree(unittest.TestCase): - """The cache path was fixed on the working directory: scanning a copy - (tmp/wt/bios) replaced the repository's cache with the copy's entries, - keyed bios/... like the real ones, and the next run rehashed everything.""" - - def test_a_scan_writes_its_cache_beside_its_tree(self): - import argparse - import io - from contextlib import redirect_stderr, redirect_stdout - - from collection import hashcache, run - - with tempfile.TemporaryDirectory() as directory: - root = Path(directory) - (root / "bios" / "Sony").mkdir(parents=True) - (root / "bios" / "Sony" / "a.bin").write_bytes(b"a") - (root / "_registry.yml").write_text("platforms: {}\n") - args = argparse.Namespace( - bios_dir=str(root / "bios"), force=False, - output=str(root / "database.json"), offline=True, - platforms_dir=str(root), emulators_dir=str(root), - provenance_dir=str(root), - ) - with redirect_stdout(io.StringIO()), redirect_stderr(io.StringIO()): - self.assertEqual(run.generate(args), 0) - cache = root / ".cache" / "db_cache.json" - self.assertEqual(hashcache.cache_path(root / "bios"), str(cache)) - self.assertEqual(list(hashcache.load_cache(str(cache))), ["bios/Sony/a.bin"]) - self.assertEqual(hashcache.cache_path(Path("bios")), ".cache/db_cache.json") - - -class TheZipIndexCacheKnowsItsInputs(unittest.TestCase): - """build_zip_contents_index cached on (path, mtime) alone: a smaller - max_entry_size, or a database giving the same archive another sha1, - got the first call's index back.""" - - def test_the_bound_and_the_sha1_are_part_of_the_key(self): - from scripts.core import ziptools - - with tempfile.TemporaryDirectory() as directory: - path = Path(directory) / "a.zip" - with zipfile.ZipFile(path, "w") as archive: - archive.writestr("big.bin", b"x" * 4096) - ziptools._zip_contents_cache = None - db = {"files": {"a" * 40: {"path": str(path)}}} - self.assertEqual(len(ziptools.build_zip_contents_index(db, Path(directory))), 1) - self.assertEqual(ziptools.build_zip_contents_index(db, Path(directory), max_entry_size=10), {}) - other = {"files": {"b" * 40: {"path": str(path)}}} - self.assertEqual( - set(ziptools.build_zip_contents_index(other, Path(directory)).values()), {"b" * 40} - ) - ziptools._zip_contents_cache = None - - -class GeneratedModelsAreWrittenWhole(unittest.TestCase): - """The truth model and the cumulative MAME clone map were written by - truncate-then-write, and a corrupt clone map also read as empty and was - then overwritten, losing what earlier runs recorded.""" - - def test_both_writers_replace_their_file_atomically(self): - for module in ("generate_truth.py", "dedup.py"): - source = script_source(module) - with self.subTest(module=module): - self.assertIn("write_text_atomic(", source) - self.assertNotIn('open(out_path, "w")', source) - self.assertNotIn('open(clone_path, "w")', source) - - def test_an_unreadable_clone_map_stops_the_run(self): - from collection import dedup - - with tempfile.TemporaryDirectory() as directory: - root = Path(directory) - bios = root / "bios" - # A device clone: two archive names, the same ROMs, in MAME's tree. - (bios / "Arcade" / "MAME").mkdir(parents=True) - for name in ("set.zip", "setclone.zip"): - with zipfile.ZipFile(bios / "Arcade" / "MAME" / name, "w") as archive: - archive.writestr("rom.bin", b"rom") - data = (bios / "Arcade" / "MAME" / "set.zip").read_bytes() - (bios / "Arcade" / "MAME" / "setclone.zip").write_bytes(data) - (root / "_mame_clones.json").write_text("<<<<<<< HEAD") - from model.database import CloneMapUnreadable - - with self.assertRaises(CloneMapUnreadable): - dedup.deduplicate(str(bios), dry_run=False) - # Stopped before removing anything. - self.assertTrue((bios / "Arcade" / "MAME" / "setclone.zip").exists()) - - def test_the_pack_side_reads_the_same_bad_map_the_same_way(self): - from model import database - - with tempfile.TemporaryDirectory() as directory: - root = Path(directory) - (root / "bios").mkdir() - (root / "_mame_clones.json").write_text("<<<<<<< HEAD") - with self.assertRaises(database.CloneMapUnreadable) as caught: - database.get_mame_clone_map(str(root / "bios")) - self.assertIn("Restore it from git", str(caught.exception)) - (root / "_mame_clones.json").write_text("[]") - with self.assertRaises(database.CloneMapUnreadable): - database.get_mame_clone_map(str(root / "bios")) - - -class APackNoteBesideItsSlotIsANote(unittest.TestCase): - """The builder writes INSTRUCTIONS_.txt beside the slot it - explains, but verify_pack recognised notes at the ZIP root only and failed - a pack holding games/keen6/INSTRUCTIONS_egagraph.ck6.txt.""" - - def test_a_nested_note_is_not_hashed_against_the_collection(self): - from scripts.packs.integrity import verify_pack - - with tempfile.TemporaryDirectory() as directory: - path = Path(directory) / "Pack.zip" - with zipfile.ZipFile(path, "w") as archive: - archive.writestr("games/keen6/INSTRUCTIONS_egagraph.ck6.txt", "File needed") - archive.writestr("bios/RENAMED_x.bin.txt", "renamed") - result = verify_pack(str(path), {"files": {}, "indexes": {}}) - self.assertTrue(result[0], result) - - def test_verify_reads_the_rule_where_it_is_defined(self): - source = script_source("verify.py") - self.assertNotIn("from generate_pack import _preferred_entries", source) - - -class NoHandlerSwallowsEverything(unittest.TestCase): - """The project forbids `except Exception: pass`, but the edit hook missed - the two-line form and nothing in CI checked it.""" - - def test_no_catch_all_handler_only_passes(self): - import ast - - offenders = [] - for path in [*sorted((ROOT / "scripts").rglob("*.py")), ROOT / "install.py"]: - tree = ast.parse(path.read_text(encoding="utf-8")) - for node in ast.walk(tree): - if not isinstance(node, ast.ExceptHandler): - continue - broad = node.type is None or ( - isinstance(node.type, ast.Name) - and node.type.id in ("Exception", "BaseException") - ) - if broad and all(isinstance(stmt, ast.Pass) for stmt in node.body): - offenders.append(f"{path.relative_to(ROOT)}:{node.lineno}") - self.assertEqual(offenders, []) - - -class AnArchiveShipsWholeUnderARegion(unittest.TestCase): - """verify --emulator dropped kronos' regional stvbios.zip members before - rebuilding the archive, so its archive held 4 of 14 members and its - required changed, while the emulator pack ships the archive whole.""" - - def test_verify_filters_loose_files_only(self): - loose_only = ( - 'if fe.get("archive")\n or resolve_destination(fe, selection.standalone)' - ' not in selection.region_drops' - ) - # The pack and the report read the same selection. - self.assertIn(loose_only, script_source("verify.py")) - self.assertIn(loose_only, script_source("generate_pack.py")) - - -class APathConflictKeepsTheMainVerdict(unittest.TestCase): - """The builder's file/directory conflict branch judged a declaration by - the raw resolver status: a zipped_file archive whose member is right was - counted excluded while verify counted it OK.""" - - def test_the_branch_reads_baseline_verdict(self): - source = script_source("generate_pack.py") - branch = source[source.index("Content ships under the conflicting shape"):] - branch = branch[: branch.index("storage = file_entry.get")] - self.assertIn("self.declarations.verdict(", branch) - self.assertNotIn('conflict_status == "hash_mismatch"', branch) - - -class TheDatabaseCacheIsWrittenWhole(unittest.TestCase): - """A crash while serializing left a truncated db_cache.json behind, and - the next run rehashed the whole collection from scratch.""" - - def test_a_failed_save_keeps_the_previous_cache(self): - import json - from unittest import mock - - from collection import hashcache - - with tempfile.TemporaryDirectory() as directory: - path = os.path.join(directory, "cache", "db_cache.json") - hashcache.save_cache(path, {"a": 1}) - with mock.patch.object(json, "dumps", side_effect=TypeError("miscomputed")), \ - self.assertRaises(TypeError): - hashcache.save_cache(path, {"a": 2}) - self.assertEqual(hashcache.load_cache(path), {"a": 1}) - self.assertEqual(os.listdir(os.path.dirname(path)), ["db_cache.json"]) - - -class KidVidTapesStayWithTheContent(unittest.TestCase): - """Stella opens its KidVid tapes by bare name (stella2014, from the - working directory) or from its base directory (stella2023, the content - folder, and stella, a folder under the save directory): never the system - directory. Without load_from every Linux pack put about 68 MB of WAVs at - the BIOS root, in two cases. The save directory is a place a pack - reaches: stella's tapes go there, never to the BIOS tree.""" - - def test_no_pack_places_them_in_the_system_directory(self): - from scripts.model.profiles import load_emulator_profiles - from scripts.resolve.entryscope import ( - outside_gap_scope, - read_from_save_dir, - read_from_system_dir, - ) - - profiles = load_emulator_profiles(str(ROOT / "emulators")) - for name in ("stella", "stella2014", "stella2023"): - tapes = [f for f in profiles[name]["files"] - if f["name"].lower().endswith(".wav")] - with self.subTest(profile=name): - self.assertEqual(len(tapes), 7) - self.assertFalse(any(read_from_system_dir(f, False) for f in tapes)) - for f in tapes: - self.assertTrue( - outside_gap_scope(f, False) or read_from_save_dir(f, False) - ) - - -class ModuleConstantsDeclaredOnce(unittest.TestCase): - """Splitting common.py into modules emitted some constants twice. - - The values matched, so nothing broke, but the second assignment orphans - the comment written above the first and leaves two lines to keep in step - the day a value changes. - """ - - @staticmethod - def _redeclared(path: Path) -> list[str]: - seen: dict[str, str] = {} - again = [] - for node in ast.parse(path.read_text()).body: - if not isinstance(node, ast.Assign) or len(node.targets) != 1: - continue - target = node.targets[0] - if not isinstance(target, ast.Name): - continue - value = ast.unparse(node.value) - if seen.get(target.id) == value: - again.append(target.id) - seen[target.id] = value - return again - - def test_no_module_assigns_the_same_constant_twice(self): - offenders = {} - for path in sorted(ROOT.glob("scripts/**/*.py")) + [ROOT / "install.py"]: - again = self._redeclared(path) - if again: - offenders[path.name] = again - self.assertEqual(offenders, {}) - - -class OnlyTheSchemaValidatorNeedsJsonschema(unittest.TestCase): - """Build scripts and install.py run on stdlib plus pyyaml, and jsonschema is - tooling for the schemas package behind validate_schemas and CI. An import - anywhere else turns a contributor's pipeline run into an ImportError.""" - - @staticmethod - def _imports_jsonschema(source: str) -> bool: - for node in ast.walk(ast.parse(source)): - if isinstance(node, ast.Import): - names = [alias.name for alias in node.names] - elif isinstance(node, ast.ImportFrom): - names = [node.module or ""] - else: - continue - if any(name.split(".")[0] == "jsonschema" for name in names): - return True - return False - - def test_no_other_module_imports_it(self): - offenders = [ - str(path.relative_to(ROOT)) - for path in sorted(ROOT.glob("scripts/**/*.py")) + [ROOT / "install.py"] - if path.parent != ROOT / "scripts" / "schemas" - and self._imports_jsonschema(path.read_text()) - ] - self.assertEqual(offenders, []) - - def test_a_nested_import_is_seen(self): - self.assertTrue( - self._imports_jsonschema("def f():\n from jsonschema import validate\n") - ) - - -class HashMergeBackupsAreNotSources(unittest.TestCase): - """The hash merge copies a profile to .old.yml before rewriting it. - - Every loader skipped the copy except validate_schemas, which then failed - on a stale MAME profile nobody would ever ship. - """ - - def test_the_validator_skips_a_backup(self): - try: - from schemas.sourcetree import validate_yaml_directory - except ImportError as exc: - self.skipTest(f"validate_schemas needs jsonschema: {exc}") - - with tempfile.TemporaryDirectory() as directory: - (Path(directory) / "mame.old.yml").write_text("emulator: [\n") - self.assertEqual( - validate_yaml_directory(Path(directory), "emulator.schema.json"), [] - ) - - def test_the_backup_suffix_is_written_once(self): - offenders = [ - str(path.relative_to(ROOT)) - for path in sorted(ROOT.glob("scripts/**/*.py")) - if path.relative_to(ROOT).as_posix() != "scripts/model/profiles.py" - and '".old.yml"' in path.read_text() - ] - self.assertEqual(offenders, []) - - - -class AnUnreadableArchiveIsSaidOutLoud(unittest.TestCase): - """resolve_local_file skipped a ZIP it could not open without a word: a - truncated archive read as a missing dump (not_found) or a wrong one.""" - - def test_the_resolver_names_the_archive(self): - from resolve import localfile - - with tempfile.TemporaryDirectory() as tmp: - broken = Path(tmp) / "neogeo.zip" - broken.write_bytes(b"PK\x03\x04 truncated") - sha1 = hashlib.sha1(broken.read_bytes()).hexdigest() - db = {"files": {sha1: {"path": str(broken), "name": "neogeo.zip", "sha1": sha1, - "md5": "0" * 32, "size": broken.stat().st_size}}, - "indexes": {"by_name": {"neogeo.zip": [sha1]}, "by_md5": {}, - "by_crc32": {}, "by_path_suffix": {}}} - entry = {"name": "neogeo.zip", "md5": "1" * 32, "zipped_file": "sp-s2.sp1"} - stderr = io.StringIO() - with contextlib.redirect_stderr(stderr): - localfile.resolve_local_file(entry, db) - self.assertIn(f"unreadable archive {broken}", stderr.getvalue()) - - -class GeneralUserGSReachesEveryCoreThatNamesIt(unittest.TestCase): - """The SoundFont was held as dosbox_pure's DOSBOX.SF2 alone: dosbox-staging - and dosbox-x, which name it GeneralUser-GS.sf2 and GeneralUser_GS.sf2, - shipped no General MIDI bank.""" - - def test_each_name_resolves_to_the_one_file(self): - from model import profiles as model_profiles - from resolve import localfile - - if not (ROOT / "database.json").exists(): - self.skipTest("database.json is not generated") - db = json.loads((ROOT / "database.json").read_text()) - profiles = model_profiles.load_emulator_profiles(str(ROOT / "emulators")) - held = "bios/Other/GeneralUser GS/GeneralUser-GS.sf2" - for emulator, name in (("dosbox_pure", "DOSBOX.SF2"), - ("dosbox-staging", "GeneralUser-GS.sf2"), - ("dosbox-x", "GeneralUser_GS.sf2")): - with self.subTest(emulator=emulator): - entry = next(f for f in profiles[emulator]["files"] if f["name"] == name) - path, _status = localfile.resolve_local_file( - {**entry, "source_profile": emulator}, db, dest_hint=entry.get("path", "")) - self.assertEqual(path, held) - - -class APlatformPinDoesNotReplaceTheCoresRevision(unittest.TestCase): - """RetroArch pins ScummVM's kyra.dat and FBNeo's hiscore.dat at older - revisions. Collected as variants with profiles that claimed no content, - the platform's md5 became the only proof and the pack shipped the old - files to cores built against newer ones.""" - - def test_the_profile_revision_serves_the_core(self): - from model import profiles as model_profiles - from resolve import localfile - - if not (ROOT / "database.json").exists(): - self.skipTest("database.json is not generated") - db = json.loads((ROOT / "database.json").read_text()) - profiles = model_profiles.load_emulator_profiles(str(ROOT / "emulators")) - for emulator, name, pinned in (("scummvm", "kyra.dat", "21a57f79886e46f410cfb50186ed8d77"), - ("fbneo", "hiscore.dat", "37fc4e050b53a1ef2c2e7f3042553025")): - with self.subTest(emulator=emulator): - entry = next(f for f in profiles[emulator]["files"] if f["name"] == name) - self.assertTrue(entry.get("sha1"), "the profile claims its revision") - self.assertIn(pinned, db["indexes"]["by_md5"], "the platform's pin is held") - path, status = localfile.resolve_local_file( - {**entry, "source_profile": emulator}, db, dest_hint=entry["path"]) - self.assertEqual(status, "sha1_exact") - self.assertEqual(db["files"][entry["sha1"]]["path"], path) - - -class PipelineStepsSpeakAsTheyGo(unittest.TestCase): - """run() captured a step and printed it at the end, stderr after stdout: - a twenty-minute pack build was silent and a warning lost its place.""" - - def test_output_keeps_its_order_and_is_returned(self): - script = ("import sys; print('one', flush=True); " - "print('two', file=sys.stderr, flush=True); print('three')") - echoed = io.StringIO() - with contextlib.redirect_stdout(echoed): - ok, output = runner.run([sys.executable, "-c", script], "probe") - self.assertTrue(ok) - self.assertEqual(output, "one\ntwo\nthree\n") - text = echoed.getvalue() - self.assertLess(text.index("one"), text.index("two")) - self.assertLess(text.index("two"), text.index("three")) - self.assertLess(text.index("three"), text.index("--- probe: OK")) - - -class ADataDirectoryIsWalkedOnce(unittest.TestCase): - """Each unresolved name walked every data-directory cache again: the - resolution cost names x tree on every pack build.""" - - def test_two_lookups_share_one_walk_and_keep_its_order(self): - from resolve.datadirs import forget_data_dir_index, resolve_in_data_dirs - - with tempfile.TemporaryDirectory() as tmp: - cache = Path(tmp) / "cache" - (cache / "a").mkdir(parents=True) - (cache / "b").mkdir() - (cache / "a" / "Font.bin").write_bytes(b"1") - (cache / "b" / "font.bin").write_bytes(b"2") - (cache / "b" / "other.bin").write_bytes(b"3") - registry = {"x": {"local_cache": str(cache)}} - forget_data_dir_index() - walks = [] - real_walk = os.walk - - def counting_walk(top, *a, **k): - walks.append(top) - return real_walk(top, *a, **k) - - with mock.patch.object(os, "walk", counting_walk): - first, _ = resolve_in_data_dirs(["font.bin"], registry, - lambda _p: "name_exact") - second, _ = resolve_in_data_dirs(["other.bin"], registry, - lambda _p: "name_exact") - forget_data_dir_index() - self.assertEqual(len(walks), 1) - expected = sorted(str(p) for p in (cache / "a" / "Font.bin", cache / "b" / "font.bin")) - self.assertIn(first[0], expected) - self.assertEqual(second[0], str(cache / "b" / "other.bin")) - - -class ADuplicateYamlKeyIsRefused(unittest.TestCase): - """PyYAML kept the last of two equal keys: the registry carried two - target_source keys for Recalbox and nothing noticed.""" - - def test_the_loader_names_the_repeated_key(self): - from model.safeparse import yaml_load - - with self.assertRaises(yaml.constructor.ConstructorError) as caught: - yaml_load("platform: x\ntarget_source: a\ntarget_source: b\n") - self.assertIn("duplicate key 'target_source'", str(caught.exception)) - self.assertEqual(yaml_load("a: &x {b: 1}\nc: *x\n"), {"a": {"b": 1}, "c": {"b": 1}}) - - -class AnAcceptedVersionIsNoCoreDiscrepancy(unittest.TestCase): - """eduke32 lists the retail and demo NWINTER.GRP under one name: the extra - carries the first, and a held demo copy is a version the code takes.""" - - PROFILE = {"files": [ - {"name": "NWINTER.GRP", "size": 9, "crc32": "00000000", - "validation": ["size", "crc32"]}, - {"name": "NWINTER.GRP", "size": 4, "crc32": "", - "validation": ["size", "crc32"]}, - ]} - - def _extra(self) -> dict: - # The shape find_undeclared_files gives a core extra: source_path - # defaults to the name when the profile declares no path. - return {"name": "NWINTER.GRP", "source_name": "NWINTER.GRP", - "source_path": "NWINTER.GRP", "source_profile": "eduke32"} - - def test_a_sibling_version_matches(self): - from scripts.packs.platformzip import _matches_an_alternative - - with tempfile.TemporaryDirectory() as tmp: - held = Path(tmp) / "NWINTER.GRP" - held.write_bytes(b"demo") - profile = json.loads(json.dumps(self.PROFILE)) - profile["files"][1]["crc32"] = f"{zlib.crc32(b'demo'):08x}" - self.assertTrue(_matches_an_alternative( - self._extra(), str(held), {"eduke32": profile})) - - def test_a_copy_no_entry_declares_still_disagrees(self): - from scripts.packs.platformzip import _matches_an_alternative - - with tempfile.TemporaryDirectory() as tmp: - held = Path(tmp) / "NWINTER.GRP" - held.write_bytes(b"other") - profile = json.loads(json.dumps(self.PROFILE)) - profile["files"][1]["crc32"] = f"{zlib.crc32(b'demo'):08x}" - self.assertFalse(_matches_an_alternative( - self._extra(), str(held), {"eduke32": profile})) - - def test_the_pack_consults_the_alternatives(self): - source = script_source("generate_pack.py") - self.assertRegex(source, r'status == "hash_mismatch" and not _matches_an_alternative\(') - - -class ADataDirectoryCopyPassesTheNameChecks(unittest.TestCase): - """The name steps over bios/ refuse a candidate outside the size or the - Adler-32 the entry's code checks, but a cache copy found by the same name - was returned without either check.""" - - def setUp(self): - self.tmp = Path(tempfile.mkdtemp()) - self.addCleanup(lambda: __import__("shutil").rmtree(self.tmp, True)) - cache = self.tmp / "cache" - cache.mkdir() - (cache / "wiitdb-pt.txt").write_bytes(b"12345") - self.registry = {"dolphin-sys": {"local_cache": str(cache)}} - self.db = {"files": {}, "indexes": {"by_name": {}, "by_md5": {}, - "by_path_suffix": {}, "by_crc32": {}}} - - def resolve(self, **fields): - entry = {"name": "wiitdb-pt.txt", **fields} - return resolve_local_file(entry, self.db, data_dir_registry=self.registry) - - def test_a_size_the_code_accepts_resolves(self): - self.assertEqual(self.resolve(size=5, validation=["size"])[1], "data_dir") - - def test_another_size_is_a_contradiction(self): - self.assertEqual(self.resolve(size=1, validation=["size"])[1], "hash_mismatch") - - def test_another_adler32_is_a_contradiction(self): - status = self.resolve(validation=["adler32"], known_hash_adler32="0xdeadbeef")[1] - self.assertEqual(status, "hash_mismatch") - - -class AMameCloneNameIsANameStep(unittest.TestCase): - """The clone fallback relaunched resolution on the bare canonical name: - an unsourceable entry and a size the code checks were both served the - parent set.""" - - def setUp(self): - self.tmp = Path(tempfile.mkdtemp()) - self.addCleanup(lambda: __import__("shutil").rmtree(self.tmp, True)) - bios = self.tmp / "bios" / "Arcade" - bios.mkdir(parents=True) - parent = bios / "parent.zip" - parent.write_bytes(b"PARENTSET") - (self.tmp / "_mame_clones.json").write_text( - json.dumps({"parent.zip": {"clones": ["clone.zip"]}}) - ) - sha1 = hashlib.sha1(parent.read_bytes()).hexdigest() - self.db = { - "bios_dir": str(self.tmp / "bios"), - "files": {sha1: {"path": str(parent), "name": "parent.zip", - "sha1": sha1, "size": 9}}, - "indexes": {"by_name": {"parent.zip": [sha1]}, "by_md5": {}, - "by_path_suffix": {}, "by_crc32": {}}, - } - - def resolve(self, **fields): - return resolve_local_file({"name": "clone.zip", **fields}, self.db) - - def test_a_clone_resolves_to_its_parent(self): - self.assertEqual(self.resolve()[1], "mame_clone") - - def test_an_unsourceable_entry_is_not_served_the_parent(self): - self.assertEqual(self.resolve(unsourceable="not held"), (None, "not_found")) - - def test_a_size_the_parent_contradicts_is_not_served(self): - self.assertEqual( - self.resolve(size=5, validation=["size"]), (None, "not_found") - ) - - -class ProseCitationsUseTheTrackedForm(unittest.TestCase): - """profile_sync tracks `path:line` citations only. `libretro.c - I_FindFile, line 1742` escaped it, and sixteen such citations in six - profiles stayed behind when their pins moved, four already pointing at - other code.""" - - UNTRACKED = re.compile( - r"[\w./+-]+\.(?:c|cc|cpp|cxx|h|hh|hpp|inc|cs|py|rs|go|java|kt|js|ts" - r"|m|mm|s|asm|lua|sh)\b[^\n:]{0,80}?\blines? \d+" - ) - - def test_the_pattern_reads_the_old_forms(self): - for text in ("libretro.c I_FindFile, line 1742", - "memory.c LoadBios() line 1353", - "libretro_core_options.h lines 52-64"): - self.assertRegex(text, self.UNTRACKED) - self.assertNotRegex("I_FindFile, libretro/libretro.c:4176-4252", self.UNTRACKED) - - def test_no_profile_writes_a_line_number_profile_sync_cannot_see(self): - found = [ - f"{path.name}:{number}: {match.group(0)}" - for path in sorted((ROOT / "emulators").glob("*.yml")) - for number, line in enumerate(path.read_text().splitlines(), 1) - for match in self.UNTRACKED.finditer(line) - ] - self.assertEqual(found, []) - - -class ACitationInsideASourceRefIsTracked(unittest.TestCase): - """split_source_ref reads each chunk's located head and drops the rest. - zesarux cited src/cpu.h:545 inside an annotation, four lines off at its - pin, and pce-emu joined two citations with ` + `: neither was anchored.""" - - def citations(self, ref: str) -> list[tuple[str, str]]: - from scripts.profiling.citations import collect_citations - - document = {"files": [{"name": "x.rom", "source_ref": ref}]} - return [(c.kind, c.ref) for c in collect_citations(document)] - - def test_an_annotation_citation_is_read_as_prose(self): - found = self.citations( - "src/cpu.c:3381-3383, src/utils.c:4100 " - "(MACHINE_IS_SPECTRUM_128_P2 covers Pentagon, src/cpu.h:549)" - ) - self.assertIn(("prose", "src/cpu.h:549"), found) - self.assertNotIn(("prose", "src/cpu.c:3381-3383"), found) - - def test_a_joined_citation_is_read_as_prose(self): - found = self.citations( - "src/pce_fast/pce.cpp:477-483 + src/pce_fast/huc.cpp:284-304" - ) - self.assertIn(("prose", "src/pce_fast/huc.cpp:284-304"), found) - self.assertEqual([c for c in found if c[0] == "prose"], - [("prose", "src/pce_fast/huc.cpp:284-304")]) - - def test_offsets_match_the_scalar(self): - from scripts.model.sourceref import ref_prose_text - - ref = "a.c:1-2, 5 (see b.c:7)" - masked = ref_prose_text(ref) - self.assertEqual(len(masked), len(ref)) - self.assertEqual(masked.index("b.c:7"), ref.index("b.c:7")) - self.assertNotIn("a.c", masked) - - -class TriageSurvivesAForgeRefusal(unittest.TestCase): - """git.eden-emu.dev answers 403 to commit lookups: `--all --triage` - died on the traceback after half an hour and printed no ranking.""" - - def test_the_ranking_is_printed_with_the_profile_marked(self): - from types import SimpleNamespace - - from scripts.profiling import reports as profiling_reports - from scripts.profiling import triage - - reports = [ - profiling_reports.ProfileReport(name="eden", pin="a" * 40, head="b" * 40), - profiling_reports.ProfileReport(name="vice", pin="c" * 40, head="d" * 40), - ] - selected = { - "eden": {"source": "https://git.eden-emu.dev/eden-emu/eden", "core_version": "1"}, - "vice": {"source": "https://github.com/libretro/vice-libretro", "core_version": "1"}, - } - - def check_version(named, *_args): - if "eden" in named.repo.slug: - raise triage.forgehttp.UpstreamError("HTTP 403") - return - - args = SimpleNamespace(cache_dir="", offline=True) - out = io.StringIO() - with mock.patch.object(triage, "check_version", check_version), \ - contextlib.redirect_stdout(out), \ - contextlib.redirect_stderr(io.StringIO()): - triage.print_triage(args, selected, reports) - # A header row and a closing count frame the ranking. - lines = out.getvalue().splitlines()[1:-1] - self.assertEqual(len(lines), 2) - self.assertTrue(any("eden" in line and "unreachable" in line for line in lines)) - - -class VerifyStrictAppliesInEveryMode(unittest.TestCase): - """--strict was read only by the platform branch: `--emulator x --strict` - printed MISSING (required) and exited 0, and the listings accepted it.""" - - @classmethod - def setUpClass(cls): - if not (ROOT / "database.json").exists(): - raise unittest.SkipTest("database.json is not built") - cls.dir = Path(tempfile.mkdtemp()) - (cls.dir / "fakeemu.yml").write_text( - "emulator: FakeEmu\ntype: libretro\nsystems: [zz-console]\nfiles:\n" - " - name: does_not_exist_strict.bin\n required: true\n" - " md5: 0123456789abcdef0123456789abcdef\n validation: [md5]\n" - ) - - @classmethod - def tearDownClass(cls): - __import__("shutil").rmtree(cls.dir, True) - - def run_verify(self, *flags: str) -> int: - return subprocess.run( - [sys.executable, "scripts/verify.py", *flags], cwd=ROOT, - capture_output=True, text=True, - check=False, - ).returncode - - def test_emulator_and_system_modes_fail_on_a_missing_required_file(self): - for mode in (["--emulator", "fakeemu"], ["--system", "zz-console"]): - with self.subTest(mode=mode[0]): - flags = [*mode, "--emulators-dir", str(self.dir)] - self.assertEqual(self.run_verify(*flags), 0) - self.assertEqual(self.run_verify(*flags, "--strict"), 1) - - def test_a_listing_refuses_strict(self): - self.assertEqual(self.run_verify("--list-emulators", "--strict"), 2) - - -class OpenMsxRomsSitInItsSystemroms(unittest.TestCase): - """openMSX entries had no path and landed at the BIOS root, where no - frontend points FilePool. The profile writes share/systemroms below - openMSX's user folder, the pool's first place (src/file/FilePool.cc, - FileOperations.cc), and RetroBat, which sets OPENMSX_HOME to - bios/openmsx and declares its ROMs under openMSX/share/systemroms, gets - them there.""" - - def test_every_entry_is_under_share_systemroms(self): - from scripts.model.profiles import load_emulator_profiles - from scripts.model.platforms import load_platform_config - from scripts.resolve.standalone import platform_layouts, platform_launches - - profiles = load_emulator_profiles(str(ROOT / "emulators")) - profile = profiles["openmsx"] - retrobat = yaml.safe_load((ROOT / "platforms" / "retrobat.yml").read_text()) - declared_dirs = { - fe["destination"].rsplit("/", 1)[0].lower() - for system in retrobat["systems"].values() - for fe in system.get("files", []) - if "systemroms" in fe.get("destination", "") - } - self.assertEqual(declared_dirs, {"openmsx/share/systemroms"}) - config = load_platform_config("retrobat", str(ROOT / "platforms")) - ((view, _standalone),) = platform_layouts("openmsx", profile, platform_launches(config, profiles)) - placed = {f["name"]: f for f in view["files"]} - for entry in profile["files"]: - with self.subTest(name=entry["name"]): - self.assertEqual(entry.get("path", "").lower(), - f"share/systemroms/{entry['name']}".lower()) - self.assertEqual(placed[entry["name"]].get("standalone_path", "").lower(), - f"openmsx/share/systemroms/{entry['name']}".lower()) - - -class ASameNamedMemberIsNotTheFile(unittest.TestCase): - """The gap report counted touchhle's LiberationMono-Regular.ttf as held - because idtech4a++'s extras.zip has a member of that name, another font, - while verify --emulator said missing.""" - - def test_a_declared_hash_decides_a_member_or_data_hit(self): - from scripts.packs import supplemental - - tmp = Path(tempfile.mkdtemp()) - self.addCleanup(lambda: __import__("shutil").rmtree(tmp, True)) - (tmp / "data").mkdir() - (tmp / "data" / "font.ttf").write_bytes(b"DATA FONT") - (tmp / "bios").mkdir() - with zipfile.ZipFile(tmp / "bios" / "extras.zip", "w") as zf: - zf.writestr("files/other.ttf", b"MEMBER FONT") - names = supplemental.build_supplemental_index(str(tmp / "data"), str(tmp / "bios")) - for fname, data in (("font.ttf", b"DATA FONT"), ("other.ttf", b"MEMBER FONT")): - with self.subTest(name=fname): - held = {"name": fname, "sha1": hashlib.sha1(data).hexdigest()} - other = {"name": fname, "sha1": "0" * 40} - self.assertTrue(supplemental.data_hit(fname, None, held, names)) - self.assertFalse(supplemental.data_hit(fname, None, other, names)) - self.assertTrue(supplemental.data_hit(fname, None, {"name": fname}, names)) - - -class AnEmptyTargetIsNotEveryCore(unittest.TestCase): - """A board scraped with `cores: []` and `add_cores: [gpsp]`: the pack - served gpsp's files only, the published list said null (every core).""" - - def test_the_published_list_is_the_builder_reading(self): - from scripts.model.targets import load_target_config - from scripts.packs.targets import generate_target_manifests - - tmp = Path(tempfile.mkdtemp()) - self.addCleanup(lambda: __import__("shutil").rmtree(tmp, True)) - targets = tmp / "platforms" / "targets" - targets.mkdir(parents=True) - (targets / "demo.yml").write_text( - "platform: demo\ntargets:\n" - " board:\n architecture: aarch64\n cores: []\n" - " full:\n architecture: x86_64\n cores: null\n" - ) - (targets / "_overrides.yml").write_text( - "demo:\n targets:\n board:\n add_cores: [gpsp]\n" - ) - with contextlib.redirect_stdout(io.StringIO()): - generate_target_manifests(str(targets), str(tmp / "out")) - published = json.loads((tmp / "out" / "demo.json").read_text()) - builder = load_target_config("demo", "board", str(tmp / "platforms")) - self.assertEqual(published["board"], sorted(builder)) - self.assertEqual(published["board"], ["gpsp"]) - self.assertIsNone(published["full"]) - - -class ADataDirectoryIsHeldWhileRead(unittest.TestCase): - """A pack resolved names against data/bluemsx, then a concurrent refresh - swapped the tree: the index named files that were gone and the copy - died on FileNotFoundError, or shipped bytes nobody had verified.""" - - def setUp(self): - self.tmp = Path(tempfile.mkdtemp()) - self.addCleanup(lambda: __import__("shutil").rmtree(self.tmp, True)) - - def test_the_index_follows_a_swapped_tree(self): - from scripts.resolve.datadirs import _data_dir_basenames - - cache = self.tmp / "cache" - cache.mkdir() - (cache / "old.rom").write_bytes(b"old") - self.assertIn("old.rom", _data_dir_basenames(str(cache))) - cache.rename(self.tmp / "gone") - cache.mkdir() - (cache / "new.rom").write_bytes(b"new") - index = _data_dir_basenames(str(cache)) - self.assertIn("new.rom", index) - self.assertNotIn("old.rom", index) - - def test_a_holder_makes_the_refresh_lock_wait(self): - import fcntl - - from scripts.packs import datadirs - - cache = self.tmp / "bluemsx" - cache.mkdir() - lock = cache.with_name(f".{cache.name}.lock") - - def exclusive_free() -> bool: - with open(lock, "a") as handle: - try: - fcntl.flock(handle, fcntl.LOCK_EX | fcntl.LOCK_NB) - except BlockingIOError: - return False - fcntl.flock(handle, fcntl.LOCK_UN) - return True - - with contextlib.ExitStack() as held: - datadirs.hold_data_dirs(held, {"bluemsx": {"local_cache": str(cache)}}) - self.assertFalse(exclusive_free()) - self.assertTrue(exclusive_free()) - - def test_a_cache_not_yet_on_disk_is_held_too(self): - """Skipped while absent, a tree a refresh installed mid-run was - missing for verify and present for the packs of the same run.""" - import fcntl - - from scripts.packs import datadirs - - cache = self.tmp / "absent" - lock = cache.with_name(f".{cache.name}.lock") - with contextlib.ExitStack() as held: - datadirs.hold_data_dirs(held, {"absent": {"local_cache": str(cache)}}) - self.assertFalse(cache.exists()) - with open(lock, "a") as handle, self.assertRaises(BlockingIOError): - fcntl.flock(handle, fcntl.LOCK_EX | fcntl.LOCK_NB) - - def test_both_entry_points_hold_the_trees(self): - pack = script_source("generate_pack.py") - verify_src = script_source("verify.py") - self.assertIn("hold_data_dirs(held,", verify_src) - refresh = pack.index("results = refresh_all(") - self.assertIn("hold_data_dirs(held, data_registry)", pack[refresh:]) - - def test_verify_packs_alone_holds_the_trees(self): - # --verify-packs returned before the hold and resolved core files - # against data/ while a refresh could swap a tree. - pack = script_source("generate_pack.py") - branch = pack.index("if args.verify_packs and not args.all_variants:") - run = pack.index("run_verify_packs(args)", branch) - self.assertIn("hold_data_dirs(held,", pack[branch:run]) - - -class EachRootReadsItsOwnRegistry(unittest.TestCase): - """The release-asset registry was cached once per process whatever root - was asked: a second tree got the first tree's .gitignore.""" - - def test_two_roots_in_one_process(self): - from scripts.packs import manifestentry - - with tempfile.TemporaryDirectory() as a, \ - tempfile.TemporaryDirectory() as b: - Path(a, ".gitignore").write_text("bios/one.bin\n") - Path(b, ".gitignore").write_text("bios/two.bin\n") - self.assertTrue(manifestentry._is_release_asset(str(Path(a, "bios/one.bin")), a)) - self.assertFalse(manifestentry._is_release_asset(str(Path(b, "bios/one.bin")), b)) - self.assertTrue(manifestentry._is_release_asset(str(Path(b, "bios/two.bin")), b)) - - def test_one_parser_reads_the_registry(self): - for module in ("generate_pack.py", "generate_db.py"): - source = script_source(module) - with self.subTest(module=module): - self.assertIn("load_registered_paths", source) - self.assertNotIn('startswith("bios/")\n }', source) - - - -class TheSiteCountsSlotsNotVersions(unittest.TestCase): - """raze lists every GRP its code accepts under one name: the site said - 59 files, 46 missing, where verify --emulator said 23 slots, 12 missing.""" - - def test_one_held_version_fills_the_slot(self): - from scripts.sitegen.emulatorintro import emulator_file_summary, emulator_held_line - - files = [ - {"name": "DUKE3D.GRP", "crc32": "1"}, - {"name": "DUKE3D.GRP", "crc32": "2"}, - {"name": "BLOOD.RFF", "crc32": "3"}, - ] - line = emulator_file_summary(files)[0] - self.assertIn("**2 files** (3 accepted versions)", line) - held = emulator_held_line(files, lambda f: f.get("crc32") == "2")[0] - self.assertIn("1 in repo and 1 missing", held) - - - -class EveryReadmeNamesItsFolder(unittest.TestCase): - """The Lakka pack's README reused RetroArch's guide and never named - /storage/system, the folder the registry and the installer use.""" - - def test_the_registry_folder_is_in_the_guide(self): - from scripts.packs.readme import build_readme - - registry = yaml.safe_load((ROOT / "platforms" / "_registry.yml").read_text()) - for name, entry in registry["platforms"].items(): - folder = (entry.get("extract_to") or "").rstrip("/") - if not folder: - continue - with self.subTest(platform=name): - text = build_readme(name, name, "", 1, 1, - detect=[{"os": "linux", "bios_path": folder}]) - self.assertIn(folder, text) - lakka = build_readme("lakka", "Lakka", "", 1, 1) - self.assertNotIn("retroarch/system", lakka) - - - -class NoSourceWarnsWhenCompiled(unittest.TestCase): - """A docstring naming C:\\RetroArch-Win64 with one backslash compiled to - an invalid escape: a SyntaxWarning on every run of the installer.""" - - def test_every_script_compiles_clean(self): - import warnings - - sources = [ROOT / "install.py", *sorted((ROOT / "scripts").rglob("*.py"))] - for path in sources: - with self.subTest(path=path.name), warnings.catch_warnings(): - warnings.simplefilter("error", SyntaxWarning) - warnings.simplefilter("error", DeprecationWarning) - compile(path.read_text(encoding="utf-8"), str(path), "exec") - - -class TheInstallerNamesWhatItSkipped(unittest.TestCase): - def test_count_agrees_and_required_files_are_named(self): - one = install._omission_lines(1, [{"name": "diabdat.mpq", "required": True}]) - self.assertTrue(one[0].startswith("1 file was not installed")) - self.assertTrue(any("diabdat.mpq" in line for line in one[1:])) - many = install._omission_lines( - 12, - [{"name": f"f{i:02}", "required": True, "system": f"s{i:02}", - "cores": ["core"]} for i in range(12)], - ) - self.assertTrue(many[0].startswith("12 files were not installed")) - self.assertIn(" s00 (core): f00", many) - self.assertTrue(any("and 4 more systems" in line for line in many)) - - - -class EveryToolRefusesAFlagItWouldDrop(unittest.TestCase): - """The mode x flag matrix existed for generate_pack only: verify took - --strict in --emulator mode and ignored it, pipeline took --source with - --skip-packs and built nothing. Each pair here must exit non-zero - before doing any work.""" - - REFUSED = { - "scripts/verify.py": [ - ["--list-emulators", "--strict"], - ["--list-emulators", "--verbose"], - ["--list-emulators", "--json"], - ["--list-systems", "--region", "us"], - ["--emulator", "handy", "--target", "switch"], - ["--platform", "retroarch", "--standalone"], - ["--all", "--system", "sony-playstation", "--standalone"], - ], - "scripts/cross_reference.py": [ - ["--all", "--platform", "retroarch"], - ["--list-emulators", "--all"], - ], - "scripts/pipeline.py": [ - ["--offline", "--skip-packs", "--source", "truth"], - ["--offline", "--skip-packs", "--all-variants"], - ["--offline", "--skip-packs", "--full-narrowings"], - ["--offline", "--all-variants", "--source", "platform"], - ["--offline", "--all-variants", "--source", "full"], - ["--offline", "--skip-packs", "--source", "full"], - ["--offline", "--source", "truth", "--full-narrowings"], - ["--offline", "--source", "platform", "--full-narrowings"], - ], - # The expert narrowings: what the pack builder refuses beside its - # option of the same name, and a flag with no mode to apply it. - "install.py": [ - ["--json"], - ["--standalone"], - ["--emulator", "duckstation", "--standalone", "--region", "us"], - ["--emulator", "duckstation", "--standalone", "--one-per-slot"], - ["--one-per-slot", "--system", "sony-playstation"], - ["--one-per-slot", "--emulator", "duckstation"], - ["--one-per-slot", "--for-games"], - ["--one-per-slot", "--declared-only"], - ["--one-per-slot", "--list-systems"], - ["--source", "truth", "--system", "sony-playstation"], - ["--source", "truth", "--target", "switch"], - ["--source", "truth", "--one-per-slot"], - ["--source", "truth", "--tui"], - ["--source", "platform"], - ["--find", "0" * 40, "--system", "sony-playstation"], - ["--find", "0" * 40, "--one-per-slot"], - ["--find", "0" * 40, "--check"], - ["--find", "0" * 40, "--list-systems"], - ["--find", "0" * 40, "--json", "--events"], - ["--find", "0" * 40, "--json", "--pack", "tmp/"], - ["--find", "0" * 40, "--json", "--add-app"], - ["--find", "0" * 40, "--json", "--standalone-copies"], - ["--find", "0" * 40, "--json", "--romm-firmware", "{platform}/bios"], - ["--find", "0" * 40, "--json", "--from", "tmp"], - ["--find", "0" * 40, "--pack", "tmp/"], - ["--find", "not-a-hash"], - ["--find", "0" * 12], - ], - } - - def test_each_pair_is_refused(self): - for script, cases in self.REFUSED.items(): - for argv in cases: - with self.subTest(script=script, argv=argv): - proc = subprocess.run( - [sys.executable, script, *argv], cwd=ROOT, - capture_output=True, text=True, timeout=120, - check=False, - ) - self.assertEqual(proc.returncode, 2, proc.stdout + proc.stderr) - - - -class TestsRunOffline(unittest.TestCase): - def test_the_package_forbids_downloads(self): - self.assertTrue(os.environ.get("RETROBIOS_OFFLINE")) - - def test_every_documented_run_imports_the_package(self): - """`discover tests` makes tests/ the top level, so tests/__init__.py, - which sets RETROBIOS_OFFLINE, never ran: a local run of the documented - command queried the release and wrote into the shared cache. Only CI, - which sets the variable itself, was offline.""" - import subprocess - - listed = subprocess.run( - ["git", "grep", "-n", "unittest discover", "--", ":!tests"], - capture_output=True, text=True, cwd=ROOT, check=False, - ).stdout.splitlines() - self.assertTrue(listed) - self.assertEqual([line for line in listed if "-t ." not in line], []) - - - -class TheWantedPageCountsRomsetMembers(unittest.TestCase): - """The site called build_report without archive_members: the public - Wanted page asked for dumps the collection holds inside romsets.""" - - def test_members_are_read_unless_given(self): - from scripts.acquire import provenance - - calls = [] - - def members(db, root): - calls.append(db) - return {} - - with mock.patch.object(provenance, "archive_members", members): - provenance.build_report({"files": {}}, {}) - provenance.build_report({"files": {}}, {}, {}) - self.assertEqual(len(calls), 1) - - - -class AutoFetchAsksVerifyWhatIsMissing(unittest.TestCase): - """auto_fetch judged presence by sha1 or md5 in the database: Batocera's - pc6001.zip, checked inside the zip and held, was a target, and no core - file was ever one. 721 announced where verify saw none critical.""" - - def test_the_targets_are_verify_verdicts(self): - from scripts.acquire import fetch as acquire_fetch - from packs import coverage as packs_coverage - from packs import verdicts - - config = {"verification_mode": "md5", "systems": {"s": {"files": [ - {"name": "ok.bin", "md5": "1" * 32}, - {"name": "gone.bin", "md5": "2" * 32}, - {"name": "bad.bin", "md5": "3" * 32}, - ]}}} - result = { - "details": [ - {"system": "s", "name": "ok.bin", "status": verdicts.Status.OK}, - {"system": "s", "name": "gone.bin", "status": verdicts.Status.MISSING}, - {"system": "s", "name": "bad.bin", "status": verdicts.Status.UNTESTED}, - ], - "undeclared_files": [ - {"name": "diabdat.mpq", "in_repo": False, "required": True, - "system": "diablo", "emulator": "DevilutionX"}, - {"name": "held.bin", "in_repo": True, "required": True}, - {"name": "extra.bin", "in_repo": False, "required": False}, - # zesarux installs 128s.rom with the emulator: not a target, - # and a copy placed in bios/ fails pipeline step 4d. - {"name": "128s.rom", "in_repo": False, "required": True, - "bundled": True, "emulator": "ZEsarUX"}, - ], - } - with mock.patch.object(packs_coverage, "verify_platform", lambda c, d: result): - names = [m["name"] for m in acquire_fetch.find_missing(config, {})] - self.assertEqual(names, ["gone.bin", "bad.bin", "diabdat.mpq"]) - - - -class MessagesSeparateWithAColon(unittest.TestCase): - """Em-dashes were replaced by " -" in messages: "bios/BLOOD.RFF -raze - says size mismatch" reads as a flag glued to a file name.""" - - PATTERN = re.compile(r"\} -[{a-z]") - - def test_no_message_uses_a_dash_separator(self): - found = [] - for path in [ROOT / "install.py", *sorted((ROOT / "scripts").rglob("*.py"))]: - for number, line in enumerate(path.read_text().splitlines(), 1): - if self.PATTERN.search(line): - found.append(f"{path.name}:{number}: {line.strip()}") - self.assertEqual(found, []) - - - -class AReaderThatLeavesEarlyIsNoCrash(unittest.TestCase): - """`verify.py --list-emulators | head -1` ended on a BrokenPipeError - traceback, and so did every listing and report.""" - - def test_a_closed_pipe_ends_quietly(self): - proc = subprocess.Popen( - [sys.executable, "scripts/verify.py", "--list-emulators"], cwd=ROOT, - stdout=subprocess.PIPE, stderr=subprocess.PIPE, - ) - # The listing fits a 64 KiB pipe: a child that wrote it all before - # the close below never met the broken pipe and exited 0. A 4 KiB - # pipe keeps it writing when the reader leaves. - try: - import fcntl - - fcntl.fcntl(proc.stdout.fileno(), fcntl.F_SETPIPE_SZ, 4096) - except (ImportError, AttributeError, OSError): - pass - proc.stdout.readline() - proc.stdout.close() - _, err = proc.communicate(timeout=120) - self.assertNotIn(b"Traceback", err) - self.assertEqual(proc.returncode, 141) - - def test_every_entry_point_goes_through_run_cli(self): - plain = re.compile(r'if __name__ == "__main__":\n (main\(\)|sys\.exit\(main\(\)\))') - found = [p.name for p in sorted((ROOT / "scripts").glob("*.py")) - if plain.search(p.read_text())] - self.assertEqual(found, []) - - - -class TheToolsPageSaysWhatDedupDoes(unittest.TestCase): - """tools.md said duplicates move to .variants/ (they are deleted) and - named 2 of the 11 directories dedup leaves alone.""" - - def test_every_protected_tree_is_named(self): - from scripts.model import nodedup - - line = next( - row for row in (ROOT / "wiki" / "tools.md").read_text().splitlines() - if row.startswith("| `dedup.py`") - ) - self.assertNotIn(".variants", line) - for name in nodedup.NODEDUP_DIRS: - self.assertIn(name, line) - - - -class ThePipelineTableNamesEveryStep(unittest.TestCase): - """tools.md listed the steps without 1c, 2b2, 3a and 3b.""" - - def test_every_labelled_step_is_documented(self): - labels = set(re.findall( - r'"(\d[a-z]?\d?)(?:/8)? [a-z]', script_source("pipeline.py") - )) - doc = (ROOT / "wiki" / "tools.md").read_text() - documented = set(re.findall(r"^\| (\d[a-z]?\d?)(?:/8)? \|", doc, re.MULTILINE)) - self.assertEqual(labels - documented, set()) - - - -class TheIssueFormListsEveryPlatform(unittest.TestCase): - """The missing-BIOS form offered 7 of the 12 registered platforms.""" - - def test_every_registered_platform_is_an_option(self): - from scripts.model.registry import list_registered_platforms - from scripts.model.platforms import load_platform_config - - form = yaml.safe_load( - (ROOT / ".github" / "ISSUE_TEMPLATE" / "missing-bios.yml").read_text() - ) - options = next( - item["attributes"]["options"] for item in form["body"] - if item.get("id") == "platform" - ) - for name in list_registered_platforms(str(ROOT / "platforms")): - display = load_platform_config(name, str(ROOT / "platforms"))["platform"] - self.assertIn(display, options) - - - -class TheTestJobHasTheDataTrees(unittest.TestCase): - """Packs built without data directories exit non-zero, but the CI test job - had none, and two pack parity tests failed there only.""" - - def test_the_trees_are_fetched_before_the_suite(self): - steps = yaml.safe_load( - (ROOT / ".github" / "workflows" / "validate.yml").read_text() - )["jobs"]["run-tests"]["steps"] - runs = [step.get("run", "") for step in steps] - fetch = next(i for i, run in enumerate(runs) if "refresh_data_dirs.py" in run) - suite = next(i for i, run in enumerate(runs) if "scripts/run_tests.py" in run) - self.assertLess(fetch, suite) - - - -class VerifyPacksSaysWhatItExcluded(unittest.TestCase): - """--verify-packs read the result tuple by position, dropped the unsafe - exclusions (352/353 shown as OK with no reason) and printed 5 errors.""" - - def test_the_result_is_unpacked_whole_and_every_error_printed(self): - source = script_source("generate_pack.py") - body = source[source.index("def _check_pack"):] - body = body[:body.index("\ndef ")] - self.assertIn("result.shortfall", body) - self.assertIn("for err in result.errors", body) - shortfall = source[source.index("def baseline_shortfall"):] - self.assertIn("unsafe excluded", shortfall[:shortfall.index("\ndef ")]) - self.assertNotIn("errors[:5]", body) - self.assertNotRegex(body, r"result\[\d\]") - - - -class TheGapReportKeepsItsShape(unittest.TestCase): - """Multi-line notes fell to column 0 and read as emulator headings, a - profile without systems printed `Abuse ()`, `*` had no legend, and - --platform totals said "across all emulators".""" - - def test_layout(self): - from scripts.packs.crossreftext import print_report - - report = {"abuse": { - "emulator": "Abuse", "systems": [], "gaps": 1, "total_files": 1, - "platform_covered": 0, "gap_missing": 1, - "gap_details": [{"name": "a.spe", "required": True, "source": "missing", - "note": "first line\nsecond line"}], - }} - out = io.StringIO() - with contextlib.redirect_stdout(out): - print_report(report, "the emulators batocera runs") - text = out.getvalue() - self.assertIn("* marks a file the emulator requires", text) - self.assertIn("\nAbuse\n", text) - self.assertIn("a.spe [MISSING]: first line second line", text) - self.assertIn("across the emulators batocera runs", text) - - - -class AFileToSourceIsAFileNotAName(unittest.TestCase): - """The gaps page keyed acquisition targets by name: Fallout 2's - master.dat disappeared behind Fallout 1's.""" - - def test_rows_are_keyed_by_name_and_hash(self): - source = script_source("generate_site.py") - self.assertIn('key = (g["name"], g.get("identity") or f"emulator:{emu_name}")', source) - from scripts.packs.crossrefsource import first_hash - - self.assertEqual(first_hash({"md5": ["AB", "cd"]}), "md5:ab") - self.assertEqual(first_hash({"crc32": "1", "sha1": "F" * 40}), "sha1:" + "f" * 40) - self.assertEqual(first_hash({}), "") - - - -class GeneratedArtifactsMeetTheirSchemas(unittest.TestCase): - """A manifest field added without its schema passed every local test - and failed the site deploy, which is the first run of the full check.""" - - @unittest.skipUnless(HAS_JSONSCHEMA, "needs jsonschema") - def test_the_full_schema_check_passes(self): - proc = subprocess.run( - [sys.executable, "scripts/validate_schemas.py"], cwd=ROOT, - capture_output=True, text=True, timeout=600, - check=False, - ) - self.assertEqual(proc.returncode, 0, proc.stdout + proc.stderr) - - - -class AFileCardSaysAllItKnows(unittest.TestCase): - """Emulator pages cut a set at 10 members without their hashes, never - showed standalone_path, and gave no file an anchor to link to.""" - - def test_members_standalone_path_and_anchor(self): - from scripts.sitegen.emulatorcards import render_emulator_file - - entry = { - "name": "neogeo.zip", "path": "neogeo.zip", "category": "bios_zip", - "standalone_path": "Firmware/neogeo.zip", - "contents": [{"name": f"m{i}.bin", "size": 1024, "crc32": f"{i:08x}"} - for i in range(12)], - } - text = "\n".join(render_emulator_file( - entry, {"files": [entry]}, None, [entry], lambda f: True, "file-neogeo-zip", - )) - # The card is a heading with this id, linked by the heading's own - # permalink. - self.assertIn('

list[str]: - found = [] - for node in ast.walk(ast.parse(path.read_text(encoding="utf-8"))): - if not isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef)): - continue - args = node.args - params = [a for a in (*args.posonlyargs, *args.args, *args.kwonlyargs) - if a.arg not in ("self", "cls")] - params += [a for a in (args.vararg, args.kwarg) if a] - if node.returns is None or any(a.annotation is None for a in params): - found.append(f"{path.name}:{node.lineno} {node.name}") - return found - - def test_the_count_only_goes_down(self): - paths = [ROOT / "install.py", *sorted((ROOT / "scripts").rglob("*.py"))] - missing = [m for path in paths for m in self._missing(path)] - self.assertLessEqual(len(missing), self.CEILING, missing[:20]) - for name in self.COMPLETE: - with self.subTest(module=name): - self.assertEqual(self._missing(ROOT / "scripts" / name), []) - - - -class ATreeNobodyHoldsIsMissingNotAnAsset(unittest.TestCase): - """julius's caesar3/ directory, unexpanded, went to the asset store, - which answered with .cache/large/ itself: the emulator pack died on - IsADirectoryError where verify said MISSING.""" - - def test_directory_entries_never_reach_the_asset_store(self): - from scripts.model import largefiles - from scripts.resolve import packfiles as packresolve - - db = {"files": {}, "indexes": {"by_name": {}, "by_md5": {}, "by_crc32": {}, - "by_path_suffix": {}}} - for entry in ({"name": "caesar3/", "type": "directory"}, {"name": "caesar3/"}): - with self.subTest(entry=entry): - self.assertEqual( - packresolve.resolve_file(entry, db, "bios", {}, offline=True), - (None, "not_found"), - ) - self.assertIsNone(largefiles.fetch_large_file("caesar3/", offline=True)) - with tempfile.TemporaryDirectory() as tmp: - Path(tmp, "sub").mkdir() - self.assertIsNone(largefiles._fetch_asset("sub", tmp, "", "", offline=True)) - - - -class EmuDeckRunsItsEmulatorsStandalone(unittest.TestCase): - """EmuDeck declared no standalone_cores: Dolphin, Cemu, xemu, ARMSX2 and - Supermodel, installed as apps by EmuScripts, got the libretro layout and - lost their standalone-only files.""" - - def test_every_emuscripts_emulator_is_standalone(self): - from scripts.model.platforms import load_platform_config - from scripts.resolve.launches import PlatformLaunches - from scripts.model.profiles import load_emulator_profiles - - config = load_platform_config("emudeck", str(ROOT / "platforms")) - self.assertEqual( - sorted(config["standalone_cores"]), - sorted(c for c in config["cores"] if c != "retroarch"), - ) - profiles = load_emulator_profiles(str(ROOT / "emulators")) - standalone = PlatformLaunches(standalone=frozenset(config["standalone_cores"])) - for name in ("dolphin", "cemu", "armsx2", "supermodel"): - with self.subTest(emulator=name): - self.assertTrue(standalone.runs_standalone(name, profiles[name])) - - def test_retroarch_brings_its_libretro_cores(self): - """The scraper dropped RetroArch's own script: np2kai, neocd and - every core EmuDeck installs through RetroArch got no file that - checkBIOS.sh does not name.""" - from scripts.model.profiles import load_emulator_profiles - from scripts.model.platforms import load_platform_config - from scripts.resolve.cores import resolve_platform_cores - - config = load_platform_config("emudeck", str(ROOT / "platforms")) - self.assertIn("retroarch", config["cores"]) - cores = resolve_platform_cores(config, load_emulator_profiles(str(ROOT / "emulators"))) - for name in ("np2kai", "neocd", "dolphin"): - with self.subTest(core=name): - self.assertIn(name, cores) - - - -class DocumentedHashLookupsFindTheirFile(unittest.TestCase): - """The --from-md5 example was a test fixture hash: copied from the docs, - it answered NOT FOUND, which then exited 0.""" - - def test_every_documented_lookup_is_in_the_database(self): - db = json.loads((ROOT / "database.json").read_text(encoding="utf-8")) - by_md5 = db["indexes"]["by_md5"] - found = 0 - for page in sorted((ROOT / "wiki").glob("*.md")): - text = page.read_text(encoding="utf-8") - for md5 in re.findall(r"--from-md5 ([0-9a-f]{32})\b", text): - found += 1 - with self.subTest(page=page.name, md5=md5): - self.assertIn(md5, by_md5) - self.assertGreater(found, 0) - - - -class ToolReferenceListsEveryModule(unittest.TestCase): - """The exporter table described retropie_exporter as a System.dat writer - and left out bizhawk, misterfpga and rocknix, and the target table missed - recalbox and rocknix. A contributor reads these tables as the map.""" - - def _rows(self, heading: str) -> set[str]: - text = (ROOT / "wiki" / "tools.md").read_text(encoding="utf-8") - section = text.split(f"## {heading}\n", 1)[1].split("\n## ", 1)[0] - return set(re.findall(r"^\| `(\w+)` \|", section, re.M)) - - def test_every_exporter_has_a_row(self): - modules = {p.stem for p in (ROOT / "scripts" / "exporter").glob("*_exporter.py")} - self.assertEqual(self._rows("Exporters"), modules - {"base_exporter"}) - - def test_every_target_scraper_has_a_row(self): - modules = { - p.stem for p in (ROOT / "scripts" / "scraper" / "targets").glob("*_targets_scraper.py") - } - self.assertEqual(self._rows("Target scrapers"), modules) - - - -class ToolReferenceCountsMatchTheirArtifacts(unittest.TestCase): - """tools.md said 67 derivable entries for 79 and 1,113 identified - archives for 1,181: counts written by hand drift from the tools.""" - - def setUp(self): - self.text = (ROOT / "wiki" / "tools.md").read_text(encoding="utf-8") - - def test_recipe_store_counts(self): - store = json.loads((ROOT / "recipes" / "mame.json").read_text(encoding="utf-8")) - versions = {dat for entry in store["entries"] for dat in entry.get("dats") or [entry["dat"]]} - listed = sum(len(entry.get("dats") or [entry["dat"]]) for entry in store["entries"]) - match = re.search( - r"(\d+) MAME versions produce ([\d,]+) entries but only ([\d,]+)\s+distinct", - self.text, - ) - self.assertIsNotNone(match) - stated = [int(group.replace(",", "")) for group in match.groups()] - self.assertEqual(stated, [len(versions), listed, len(store["entries"])]) - - def test_no_derivable_count(self): - """The count now lives in derivable.json alone, which step 1b rewrites.""" - self.assertNotRegex(self.text, r"\d+ entries on the current snapshots") - - - -class WikiProseHasNoTornSentence(unittest.TestCase): - """tools.md read "replaces each destination atomically. The shell and / - Both one-liners verify...": half of an old sentence left in front of - its rewrite, on the page that explains the installer's trust boundary.""" - - STARTERS = {"Both", "The", "This", "It", "A", "An", "Each", "Every", "When", - "If", "They", "These", "That", "There"} - - def test_no_line_ends_on_a_function_word_before_a_new_sentence(self): - for page in sorted((ROOT / "wiki").glob("*.md")): - lines = page.read_text(encoding="utf-8").splitlines() - in_code = False - for number, (line, following) in enumerate(zip(lines, lines[1:]), 1): - if line.startswith("```"): - in_code = not in_code - if in_code: - continue - if (re.search(r"\b(and|or|the|a|an|of|to)$", line.rstrip()) - and following.split(" ")[0] in self.STARTERS): - self.fail(f"{page.name}:{number} ends mid-sentence: {line.strip()!r}") - - - -class EveryOptionIsDocumented(unittest.TestCase): - """profile_sync's --system, --stale-before and --ref, auto_fetch - --create-issues, download.py --info and forty more were in no page: a - maintainer ran --all and spent the API quota that --system would have - saved. --help lists a flag, but only a page says when to reach for it.""" - - def test_every_long_option_of_a_tracked_script_is_in_the_docs(self): - tracked = subprocess.run( - ["git", "ls-files", "scripts"], capture_output=True, text=True, - cwd=str(ROOT), check=True, - ).stdout.split() - docs = "\n".join( - path.read_text(encoding="utf-8") - for path in [*sorted((ROOT / "wiki").glob("*.md")), - ROOT / "README.md", ROOT / "CONTRIBUTING.md"] - ) - option = re.compile(r'add_argument\(\s*(?:"-\w",\s*)?"(--[\w-]+)"') - undocumented = sorted( - f"{name}: {flag}" - for name in tracked if name.endswith(".py") - for flag in set(option.findall((ROOT / name).read_text(encoding="utf-8"))) - if not re.search(re.escape(flag) + r"(?![\w-])", docs) - ) - self.assertEqual(undocumented, []) - - - -class OfflineHelpSaysWhatItCuts(unittest.TestCase): - """--offline read "Skip data directory freshness check" while it also - stops release assets from downloading: on a fresh clone the gitignored - files were missing from the pack and nothing had announced it.""" - - def test_both_helps_name_the_release_assets(self): - for script in ("generate_pack.py", "pipeline.py"): - with self.subTest(script=script): - out = subprocess.run( - [sys.executable, f"scripts/{script}", "--help"], - capture_output=True, text=True, cwd=str(ROOT), check=True, - ).stdout - block = out.split("--offline", 2)[-1].split("\n --", 1)[0] - self.assertIn("release", " ".join(block.split())) - - - -class PipelineDocstringNamesThePrintedSteps(unittest.TestCase): - """The docstring numbered 1 to 9 while the run prints 1/8 to 8/8, and - had no 2a, 2b, 3a, 3b or 6: a reader of a failed `6/8 pack integrity` - found nothing under 6.""" - - def test_the_two_lists_hold_the_same_steps(self): - import ast - - source = (ROOT / "scripts" / "pipeline.py").read_text(encoding="utf-8") - doc = ast.get_docstring(ast.parse(source)) - listed = set(re.findall(r"^ (\d[a-z0-9]*)\s{2,}", doc, re.M)) - from orchestrate.labels import STEP_LABELS, step_number - - printed = {step_number(key) for key in STEP_LABELS} - self.assertEqual(listed, printed) - - - -class VerifyAllSummaryNamesWhatIsWrong(unittest.TestCase): - """The closing line counted platform severities only: a required core - file missing on ROCKNIX was absent from it, and the one warning did not - say which platform carried it.""" - - def test_counts_carry_platforms_and_core_misses(self): - from packs import verifysummary - from packs import verdicts - - clean = {"severity_counts": {}, "undeclared_files": []} - warned = {"severity_counts": {verdicts.Severity.WARNING: 1}, "undeclared_files": []} - core_miss = { - "severity_counts": {}, - "undeclared_files": [{ - "name": "n64.psh", "required": True, "in_repo": False, - "category": "bios", "in_pack": True, - }], - } - summary = verifysummary.overall_summary( - [(clean, ["RetroArch"]), (warned, ["RetroDECK"]), (core_miss, ["ROCKNIX"])] - ) - self.assertIn("1 warning (RetroDECK 1)", summary) - self.assertIn("n64.psh (ROCKNIX)", summary) - self.assertIn("0 critical,", summary) - - def test_a_file_missing_on_several_platforms_is_counted_once(self): - """sfiii2a.zip missing on 15 platforms read '24 core file(s)' for 10 - distinct files, the name printed 15 times on one line.""" - from packs import verifysummary - - def missing(*names: str) -> dict: - return {"severity_counts": {}, "undeclared_files": [ - {"name": name, "required": True, "in_repo": False, - "category": "bios", "in_pack": True} for name in names - ]} - - summary = verifysummary.overall_summary([ - (missing("sfiii2a.zip"), ["Batocera"]), - (missing("sfiii2a.zip", "ROM"), ["RetroPie"]), - (missing("sfiii2a.zip"), ["RomM"]), - (missing(), ["MinUI"]), - ]) - self.assertIn( - "2 core file(s) a core cannot run without are missing: " - "sfiii2a.zip (every platform but MinUI); ROM (RetroPie)", - summary, - ) - self.assertEqual(summary.count("sfiii2a.zip"), 1) - - - -class OneOutputFormPerRun(unittest.TestCase): - """`diff_truth.py --json --format markdown` printed JSON with rc 0, the - markdown asked for dropped without a word.""" - - def test_json_and_markdown_are_refused_together(self): - for script, argv in ( - ("diff_truth.py", ["--platform", "romm", "--json", "--format", "markdown"]), - ("diff_truth.py", ["--platform", "romm", "--json", "--markdown"]), - ("validate_pr.py", ["--json", "--markdown", "bios/Sony/PlayStation/scph5501.bin"]), - ): - with self.subTest(script=script, argv=argv): - proc = subprocess.run( - [sys.executable, f"scripts/{script}", *argv], capture_output=True, - text=True, cwd=str(ROOT), timeout=120, check=False, - ) - self.assertEqual(proc.returncode, 2, proc.stdout[-300:]) - self.assertIn("not allowed with", proc.stderr) - - - -class BundledFilesAreNotToSource(unittest.TestCase): - """DaedalusX64's n64.psh, the shader library its renderer installs - beside the binary, was reported as a required core file missing and - listed among the files to source, with 19 more like it.""" - - def test_verify_does_not_count_it_missing(self): - from packs import verifysummary - from packs import shares as packs_shares - - entry = {"name": "n64.psh", "required": True, "in_repo": False, - "category": "bios", "in_pack": True, "bundled": True} - self.assertEqual(packs_shares.core_required_missing([entry]), []) - summary = verifysummary.overall_summary( - [({"severity_counts": {}, "undeclared_files": [entry]}, ["ROCKNIX"])] - ) - self.assertNotIn("n64.psh", summary) - - def test_the_site_gives_it_its_own_status(self): - from sitegen import exportrows - - rows = exportrows.gap_export_rows({}, {"daedalusx64": { - "emulator": "DaedalusX64", "systems": ["nintendo-64"], - "gap_details": [{"name": "n64.psh", "source": "missing", "required": True, - "in_repo": False, "bundled": True}], - }}) - self.assertEqual([row["status"] for row in rows], ["bundled"]) - - def test_a_held_bundled_file_is_not_packed(self): - """A file installed with the emulator is already on the user's - machine, so the pack leaves it out even when the collection holds it.""" - from packs import coverage as packs_coverage - - entry = {"name": "n64.psh", "required": True, "in_repo": True, - "emulator": "daedalusx64", "category": "bios", "bundled": True} - with mock.patch("packs.extraresolver.unplaceable_extras", return_value={}): - packs_coverage._mark_unplaced({}, [entry], {}) - self.assertFalse(entry["in_pack"]) - self.assertIn("installed with its emulator", entry["omitted"]) - - def test_a_build_scope_keeps_it_for_the_other_build(self): - """PPSSPP's standalone release ships assets/, its libretro core does - not: bundled for one build, the entry still reaches a core's pack.""" - from resolve.entryscope import deliverable - - entries = [{"ref": "ppsspp-assets", "mode": "libretro"}, - {"name": "a.bin", "bundled": True, "mode": "standalone"}, - {"name": "b.bin", "bundled": True}] - self.assertEqual([e.get("ref") or e["name"] for e in deliverable(entries, False)], - ["ppsspp-assets"]) - self.assertEqual(deliverable(entries, True), []) - - def test_a_platform_package_can_differ_both_ways(self): - """Batocera's hcl package installs the binary alone, its blueMSX core - package copies the machines beside the core.""" - from resolve.entryscope import installed_with_emulator - - hcl = {"name": "data.pak", "bundled": True, "not_bundled_on": ["batocera"]} - machines = {"name": "Machines/MSX/config.ini", "installed_on": ["batocera", "retropie"]} - self.assertTrue(installed_with_emulator(hcl, "retrobat")) - self.assertFalse(installed_with_emulator(hcl, "batocera")) - self.assertTrue(installed_with_emulator(machines, "retropie")) - self.assertFalse(installed_with_emulator(machines, "retroarch")) - self.assertTrue(installed_with_emulator(hcl)) - - def test_a_view_naming_no_setup_keeps_what_one_package_leaves_out(self): - """touchHLE panics without its fonts on ROCKNIX: the emulator page, - the global gap report and the wanted list all still ask for them.""" - from acquire.provenance import profile_needs - from packs.crossref import cross_reference - from resolve.entryscope import installed_everywhere - from sitegen.install import comes_with_app - - font = {"name": "LiberationMono-Regular.ttf", "bundled": True, - "not_bundled_on": ["rocknix"]} - self.assertFalse(installed_everywhere(font)) - self.assertFalse(comes_with_app(font)) - self.assertTrue(installed_everywhere({"name": "a.bin", "bundled": True})) - profiles = {"touchhle": {"emulator": "touchHLE", "type": "standalone", - "systems": ["apple-ios"], "files": [font]}} - report = cross_reference(profiles, {}, {"files": {}, "indexes": {}}) - self.assertFalse(report["touchhle"]["gap_details"][0]["bundled"]) - sized = {**font, "size": 312132} - needs = profile_needs({"touchhle": {"files": [sized]}}, {"files": {}, "indexes": {}}) - self.assertIn("liberationmono-regular.ttf", needs["by_name"]) - everywhere = {**sized, "not_bundled_on": []} - needs = profile_needs({"touchhle": {"files": [everywhere]}}, {"files": {}, "indexes": {}}) - self.assertEqual(needs["by_name"], {}) - - def test_every_platform_named_is_registered(self): - from model.registry import list_registered_platforms - from model.profiles import load_emulator_profiles - - known = set(list_registered_platforms(str(ROOT / "platforms"))) - unknown = sorted({ - (name, platform) - for name, profile in load_emulator_profiles(str(ROOT / "emulators")).items() - for entry in (profile.get("files") or []) + (profile.get("data_directories") or []) - if isinstance(entry, dict) - for field in ("installed_on", "not_bundled_on") - for platform in entry.get(field) or [] - if platform not in known - }) - self.assertEqual(unknown, []) - - def test_a_tree_the_platform_installs_leaves_its_pack(self): - """retroarch.yml names dolphin-sys and ppsspp-assets and Lakka - inherits them, while Lakka's core packages install both trees.""" - from model.profiles import installed_data_refs_in - - profiles = {"dolphin": { - "emulator": "Dolphin", "type": "libretro", "files": [], - "data_directories": [{"ref": "dolphin-sys", "installed_on": ["lakka"]}]}} - self.assertEqual(installed_data_refs_in("lakka", profiles), frozenset({"dolphin-sys"})) - self.assertEqual(installed_data_refs_in("retroarch", profiles), frozenset()) - source = script_source("generate_pack.py") - self.assertIn("if ref_key in installed:", source) - self.assertIn("installed=installed_data_refs_in(plan.platform_name", source) - - def test_the_pack_builder_skips_it(self): - source = (ROOT / "scripts" / "packs" / "extras.py").read_text(encoding="utf-8") - self.assertIn('if u.get("bundled"):', source) - - - -class AdlerValuesReadLikeTheDownloads(unittest.TestCase): - """The Dolphin card read Adler32: `['0x66f334fe', '0xe789b5a5']`, a list - repr no download spells, and never said the values are taken over the - byte-swapped ROM, so the raw ea3734fe in files.csv matched neither.""" - - def test_values_and_the_swap_are_stated(self): - from scripts.sitegen.emulatorcards import render_emulator_file - - entry = {"name": "dsp_rom.bin", "path": "dsp_rom.bin", - "known_hash_adler32": ["0x66f334fe", "0xE789B5A5"], - "adler32_byteswap": True} - text = "\n".join(render_emulator_file( - entry, {"files": [entry]}, None, [entry], lambda f: True, "file-dsp", - )) - self.assertIn("`66f334fe`, `e789b5a5`", text) - self.assertIn("byte-swapped", text) - self.assertNotIn("['", text) - - - -class GapsPageCountsOneWay(unittest.TestCase): - """The stats block said 1 untested (by destination) while Problem Files - listed 4 untested entries, three of them at paths another declaration - of the same platform already holds.""" - - def test_settled_declarations_are_listed_apart(self): - from scripts.sitegen.gapproblems import render_problem_files - - problems = [{"platform": "RetroDECK", "name": "dsifirmware.bin", "status": "untested", - "required": True, "reason": "x", "discrepancy": ""}] - settled = [{"platform": "RetroDECK", "name": "cdibios.zip", "status": "untested", - "held_by": "arcade"}] - text = "\n".join(render_problem_files(problems, settled)) - self.assertIn("0 missing, 1 untested", text) - self.assertIn("Other revisions of a held destination", text) - self.assertIn("`cdibios.zip`", text) - - def test_missing_says_the_destination_count_of_the_opening_sentence(self): - # The page opened on "48 are missing" (by destination) above a - # heading that said "10 files": one row per name. - from scripts.sitegen.gapproblems import render_problem_files - - problems = [{"platform": "AmberELEC", "name": "hardwareconfig.xml", - "status": "missing", "required": True, "reason": "", - "discrepancy": "", "category": "unread"}] * 3 - text = "\n".join(render_problem_files(problems, missing_total=3)) - self.assertIn("3 missing under 1 name,", text) - self.assertIn('rb-badge-danger">1 name', text) - self.assertNotIn("1 missing", text) - - def test_a_missing_row_links_each_entry_and_names_its_folder(self): - """The row said `N88_KNJ1.ROM | unread | yes | AmberELEC` in plain text: - neither where the list puts it nor which cores were examined.""" - from scripts.sitegen.gapproblems import render_problem_files - - problems = [{"platform": "AmberELEC", "platform_key": "amberelec", "name": "N88_KNJ1.ROM", - "status": "missing", "required": True, "reason": "", "discrepancy": "", - "category": "unread", "system": "nec-pc-88", - "destination": "bios/quasi88/N88_KNJ1.ROM"}] - text = "\n".join(render_problem_files(problems)) - self.assertIn("| [AmberELEC](platforms/amberelec.md#nec-pc-88) " - "`bios/quasi88/N88_KNJ1.ROM` |", text) - - def test_the_destination_is_the_list_entrys(self): - """AmberELEC declares hardwareconfig.xml under eighteen MSX folders: - each missing one is shown under its own, not under the first.""" - from scripts.sitegen.gaps import _verify_tally - from model.platforms import load_platform_config - - config = load_platform_config("amberelec", str(ROOT / "platforms")) - details, wanted = [], [] - for system, data in (config.get("systems") or {}).items(): - for entry in data.get("files") or []: - missing = entry["name"] in ("hardwareconfig.xml", "N88_KNJ1.ROM") - details.append({"name": entry["name"], "system": system, - "status": "missing" if missing else "ok"}) - if missing: - wanted.append(str(entry.get("destination") or entry["name"])) - coverage = {"platform": "AmberELEC", "config": config, "details": details, - "verified": 0, "untested": 0, "missing": len(wanted), "total": len(details)} - tally = _verify_tally({"amberelec": coverage}) - shown = [p["destination"] for p in tally.problems] - self.assertEqual(shown, wanted) - self.assertGreater(len(set(shown)), 2) - self.assertIn("bios/quasi88/N88_KNJ1.ROM", shown) - - def test_verify_marks_the_settled_entry(self): - from packs import platformtally - from packs import verdicts - - result = {"name": "cdibios.zip", "status": verdicts.Status.UNTESTED} - self.assertTrue(platformtally._twin_unmet(result, "arcade")) - self.assertEqual(result["settled_by"], "arcade") - - - -class UnsourceableCardSaysWhy(unittest.TestCase): - """DraStic's nds_firmware_modified.bin carried an 'unsourceable' badge - and nothing else. The reason was only on the gaps page.""" - - def test_reason_and_link(self): - from scripts.sitegen.emulatorcards import render_emulator_file - - entry = {"name": "nds_firmware_modified.bin", "path": "x.bin", - "unsourceable": "written by the firmware editor, so no dump of it exists"} - text = "\n".join(render_emulator_file( - entry, {"files": [entry]}, None, [entry], lambda f: False, "file-x", - )) - self.assertIn("Not collected yet: written by the firmware editor", text) - self.assertIn("../gaps-not-collected.md", text) - self.assertNotIn("collectable", text) - - def test_the_gaps_page_names_where_a_wanted_file_is_listed(self): - """The section read "Acknowledged gaps ... (verified from source - code)" while No-Intro lists XM7's KANJI2.ROM and MAME's fm7740sx.zip - carries it: the flag only keeps a homonym out, the file is wanted.""" - from scripts.sitegen.gaps import generate_gap_analysis - - unsourced = {"name": "KANJI2.ROM", "reason": "no dump distributed", "source_ref": ""} - report = {"xm7": {"emulator": "XM7", "gaps": 0, "gap_missing": 0, "gap_bios": 0, - "unsourceable": [unsourced], "gap_details": []}} - catalogued = {"no-intro": {"missing": [{ - "name": "KANJI2.rom", - "romsets": [{"source": "mame", "archive": "fm7740sx.zip"}], - "needed_by": [{"emulator": "xm7", "name": "KANJI2.ROM", "required": True}], - }]}} - page = generate_gap_analysis( - {"xm7": {"emulator": "XM7", "files": [{"name": "KANJI2.ROM", - "unsourceable": "no dump distributed"}]}}, - {}, {"files": {}, "indexes": {}}, gap_report=report, catalogued=catalogued) - self.assertIn("## Not collected yet", page) - self.assertIn('', page) - self.assertIn("| No-Intro `KANJI2.rom`, mame `fm7740sx.zip` | yes |", page) - self.assertNotIn("Acknowledged", page) - self.assertNotIn("verified from source code", page) - - - -class CollectionCardsSayWhereToGetTheFile(unittest.TestCase): - """A system page card gave the hashes, readers and provenance of - scph5501.bin and no path or link to the bytes.""" - - def test_raw_and_release_asset_urls(self): - from scripts.sitegen import cards - - cards._RELEASE_ASSET_NAMES = None - self.addCleanup(setattr, cards, "_RELEASE_ASSET_NAMES", None) - self.assertEqual( - cards.fetch_url("bios/Sony/PlayStation/scph5501.bin"), - "https://raw.githubusercontent.com/Abdess/retrobios/main/bios/Sony/PlayStation/scph5501.bin", - ) - self.assertTrue(cards.fetch_url("bios/Arcade/MAME/MAME 0.174 Arcade XML.dat").endswith( - "/releases/download/large-files/MAME.0.174.Arcade.XML.dat" - )) - - - -class CollectionCardsCarryFullHashes(unittest.TestCase): - """A pasted md5 or crc32 found nothing: cards showed 12 characters of - SHA1 and MD5 (the rest in a title the search does not index) and no - CRC32 or SHA256.""" - - def test_every_hash_in_full(self): - from scripts.packs.consumers import FileConsumers - from scripts.sitegen.cards import system_file_card - - entry = {"name": "DUKE.RTS", "path": "bios/x/DUKE.RTS", "size": 10, - "sha1": "a" * 40, "md5": "9d29f9673bbdb56068acf7645c13749c", - "crc32": "504086c1", "sha256": "b" * 64} - text = "\n".join(system_file_card(entry, FileConsumers({}, {}))) - for value in (entry["sha1"], entry["md5"], entry["crc32"], entry["sha256"]): - self.assertIn(f'
{value}
', text) - - -class AHeldRevisionLinksItsBuildFile(unittest.TestCase): - """advanced_drastic's page printed the KNULLI build file that holds its - revision as plain text, while pin_build carries the repository, the tag - and the path a pinned link needs. 36 profiles carry one.""" - - def test_the_build_file_row(self): - from scripts.sitegen.emulatorcards import build_rows - - rows = build_rows({"pin_frozen": "KNULLI builds this revision.", "pin_build": [{ - "platform": "knulli", "repo": "https://github.com/knulli-cfw/knulli-linux", - "revision": "20260511", "path": "package/emulators/advanced_drastic/advanced_drastic.mk", - "variable": "ADVANCED_DRASTIC_VERSION", "value": "eaf41ab9"}]}) - # A tag can move: named, never linked. - self.assertIn( - "| Build file | KNULLI `package/emulators/advanced_drastic/advanced_drastic.mk` " - "at `20260511` sets `ADVANCED_DRASTIC_VERSION` |", rows) - - def test_a_build_read_at_a_recorded_commit_links(self): - from scripts.sitegen.emulatorcards import build_rows - - pin = "46128cd252cdecae852a4d0bafa2aaf9d03ab563" - rows = build_rows({"pin_build": [{ - "platform": "retropie", "repo": "https://github.com/RetroPie/RetroPie-Setup", - "revision": pin, "path": "scriptmodules/emulators/advmame-1.4.sh", - "variable": "rp_module_repo", "value": "x"}]}) - self.assertIn( - f"[RetroPie `scriptmodules/emulators/advmame-1.4.sh`](https://github.com/RetroPie/" - f"RetroPie-Setup/blob/{pin}/scriptmodules/emulators/advmame-1.4.sh)", rows[0]) - - def test_the_record_holds_the_build_files(self): - from sitegen import sources as sitegen_sources - - files = sitegen_sources.build_files({"pin_build": [ - {"repo": "https://github.com/o/r", "revision": "a" * 40, "path": "p.mk"}, - {"repo": "https://github.com/o/r", "revision": "v1", "path": "q.mk"}]}) - self.assertEqual([(f[1], f[2]) for f in files], [("a" * 40, "p.mk")]) - - -class AVariantCardSaysWhatToSaveItAs(unittest.TestCase): - """The Download button of a .variants/ card saved advision.zip.1c086064, - the storage name, and nothing said RetroBat looks for advision.zip.""" - - def test_the_name_to_save_it_under(self): - from scripts.packs.consumers import FileConsumers - from scripts.sitegen.cards import system_file_card - - entry = {"name": "advision.zip", "size": 10, "sha1": "a" * 40, - "path": "bios/Entex/Adventure Vision/.variants/advision.zip.1c086064"} - text = "\n".join(system_file_card(entry, FileConsumers({}, {}))) - self.assertIn("Save as", text) - self.assertIn("advision.zip.1c086064", text) - plain = "\n".join(system_file_card( - {**entry, "path": "bios/Entex/Adventure Vision/advision.zip"}, FileConsumers({}, {}))) - self.assertNotIn("Save as", plain) - - - -class NullReadsAsNone(unittest.TestCase): - """`upstream: ~` printed `| Upstream | None |` and `bios_filename: null` - printed `bios_filename: None`: a stated "there is none" read as a gap.""" - - def test_page_and_values(self): - from scripts.sitegen.fields import _plain_value - from scripts.sitegen.emulatorpage import generate_emulator_page - - self.assertEqual(_plain_value(None), "none") - page = generate_emulator_page( - "own", {"emulator": "Own", "type": "standalone", "source": "https://x/own", - "upstream": None, "core_version": None, "files": []}, - {"files": {}, "indexes": {}}, - ) - self.assertNotIn("None", page) - self.assertIn("none: the source is the project itself", page) - - def test_the_rendered_site_has_no_python_none(self): - from tests import sitepages - - pattern = re.compile(r"\| None \||: None$|: None \|", re.M) - found = [sitepages.name(p) for p in sitepages.pages() - if pattern.search(p.read_text(encoding="utf-8"))] - self.assertEqual(found, []) - - - -class EmulatorCardsLinkTheCopyAndTheSection(unittest.TestCase): - """Dolphin's IPL.bin (GC/USA) read "in repo" without naming the copy, - did not link its collection card, and its platform links landed on the - page top instead of the GameCube section.""" - - def test_copy_and_sections(self): - from types import SimpleNamespace - - from scripts.sitegen.emulatorcards import CardSources, render_emulator_file - - sha1 = "ef9194ab4804aa0aa8540d846caf291b28331165" - consumers = SimpleNamespace( - sha1_of=lambda entry, dest="", owner="": sha1, - path_of=lambda value: "bios/Nintendo/GameCube/GC/USA/IPL.bin", - platforms={sha1: {"batocera"}}, - platform_systems={sha1: {"batocera": {"nintendo-gamecube"}}}, - ) - entry = {"name": "IPL.bin", "path": "GC/USA/IPL.bin"} - text = "\n".join(render_emulator_file( - entry, {"files": [entry]}, CardSources(consumers), [entry], lambda f: True, "file-ipl", "dolphin", - )) - self.assertIn("../systems/nintendo.md#sha1-ef9194ab4804", text) - self.assertIn("../platforms/batocera.md#nintendo-gamecube", text) - - - -class VersionAnchorsFollowContent(unittest.TestCase): - """raze's nine DUKE3D.GRP were anchored -1 to -9 by declaration rank: a - version declared before another moved every later link to another - edition.""" - - @staticmethod - def _anchors(files): - from scripts.sitegen.emulatorpage import generate_emulator_page - - page = generate_emulator_page( - "raze", {"emulator": "Raze", "type": "standalone", "files": files}, - {"files": {}, "indexes": {}}, - ) - return re.findall(r'

`") - self.assertEqual(span.count("`"), 2) - self.assertTrue(span.startswith("`") and span.endswith("`")) - - - -class TheDatasetDescribesItsDownloads(unittest.TestCase): - """data.md was a Dataset named "Data & API" with no distribution, - licence, date or creator: nothing a dataset harvester could index.""" - - def test_distribution_licence_and_date(self): - from scripts.sitegen.structured import dataset_structured_data - - exports = [{"title": "Content database", "url": "api/v1/database.json", - "media_type": "application/json", "bytes": 10, "sha256": "ab" * 32}] - data = dataset_structured_data(exports, {"generated_at": "2026-10-18T07:00:00Z"}) - self.assertEqual(data["dateModified"], "2026-10-18") - self.assertIn("MIT", data["license"]) - (download,) = data["distribution"] - self.assertEqual(download["@type"], "DataDownload") - self.assertTrue(download["contentUrl"].endswith("/api/v1/database.json")) - self.assertEqual(download["sha256"], "ab" * 32) - self.assertNotEqual(data["name"], "Data & API") - - - -class SystemPagesDescribeTheirFiles(unittest.TestCase): - """systems/* published a generic TechArticle: no file, hash or - provenance for the pages that carry a card per file.""" - - def test_parts_carry_hashes_anchor_and_provenance(self): - from scripts.sitegen.structured import system_structured_data - - entry = {"name": "scph5501.bin", "sha1": "0555c6fae8906f3f09baf5988f00e55f88e9f30b", - "md5": "490f666e1afb15b7362b406ed1cea246", "crc32": "8d8cb7e4", "size": 524288, - "provenance": {"redump": {"dat": "Sony - PlayStation - BIOS Images", - "name": "ps-30a.bin"}}} - (part,) = system_structured_data("sony", {"PlayStation": [entry]})["hasPart"] - self.assertTrue(part["url"].endswith("systems/sony/#sha1-0555c6fae890")) - self.assertIn("md5:490f666e1afb15b7362b406ed1cea246", part["identifier"]) - self.assertIn("redump: Sony - PlayStation - BIOS Images (ps-30a.bin)", part["citation"]) - - def test_a_huge_page_lists_its_verified_files_and_points_at_the_table(self): - from scripts.sitegen.structured import SYSTEM_PARTS_IN_FULL, system_structured_data - - plain = [{"name": f"f{i}", "sha1": f"{i:040x}"} for i in range(SYSTEM_PARTS_IN_FULL)] - cited = {"name": "v", "sha1": "f" * 40, - "provenance": {"tosec": {"dat": "d", "name": "n"}}} - data = system_structured_data("engines", {"x": [*plain, cited]}) - self.assertEqual([p["name"] for p in data["hasPart"]], ["v"]) - self.assertTrue(data["isBasedOn"].endswith("downloads/files.csv")) - - - -class TheCollectionShipsADat(unittest.TestCase): - """The exports had JSON, CSV and SQLite and no DAT, the one format - clrmamepro and RomVault read: auditing a BIOS tree meant writing a - converter from files.csv.""" - - def test_round_trip_through_the_logiqx_parser(self): - sys.path.insert(0, str(ROOT / "scripts" / "scraper")) - from logiqx_parser import parse_logiqx - from scripts.sitegen.structured import collection_dat - - db = {"files": { - "a" * 40: {"path": "bios/Sony/PlayStation/scph5501.bin", "size": 4, - "crc32": "8D8CB7E4", "md5": "1" * 32, "sha1": "a" * 40}, - "b" * 40: {"path": "bios/Nintendo/GameCube/GC/USA/IPL.bin", "size": 8, - "crc32": "00000001", "md5": "2" * 32, "sha1": "b" * 40}, - }} - dat = parse_logiqx(collection_dat(db, "2026-10-18T07:00:00Z")) - self.assertEqual(dat.version, "20261018") - roms = {(r.game, r.name): r for r in dat.roms} - # The set name is the subfolder a copy of bios/ holds: named - # "Sony - PlayStation", clrmamepro looked beside Sony/ for it. - self.assertIn(("Sony\\PlayStation", "scph5501.bin"), roms) - self.assertIn(("Nintendo\\GameCube", "GC\\USA\\IPL.bin"), roms) - self.assertEqual(roms[("Sony\\PlayStation", "scph5501.bin")].crc32, "8d8cb7e4") - - def test_each_setup_has_a_dat_of_its_installed_folder(self): - """A Batocera user auditing share/bios against the collection DAT met - thousands of sets laid out by manufacturer, and nothing of the folder - Batocera reads.""" - sys.path.insert(0, str(ROOT / "scripts" / "scraper")) - from logiqx_parser import parse_logiqx - from scripts.sitegen.platformfiles import platform_data_links - from scripts.sitegen.structured import platform_dat - - db = {"files": {"a" * 40: {"size": 4, "crc32": "8D8CB7E4", "md5": "1" * 32, - "sha1": "a" * 40}}} - manifest = { - "platform": "batocera", "display_name": "Batocera", "base_destination": "bios", - "files": [{"dest": "dc/naomi2.zip", "sha1": "a" * 40, "size": 4}, - {"dest": "saves/x.bin", "sha1": "a" * 40, "size": 4, "root": "save"}], - "data_directories": [{"dest": "dolphin-emu/Sys", - "files": {"GC/font.bin": {"sha1": "c" * 40, "size": 2}}}], - } - dat = parse_logiqx(platform_dat(manifest, db, {"c" * 40: {"md5": "3" * 32}}, - "2026-11-05T00:00:00Z")) - roms = {(r.game, r.name): r for r in dat.roms} - self.assertEqual(set(roms), {("bios", "dc\\naomi2.zip"), - ("bios", "dolphin-emu\\Sys\\GC\\font.bin")}) - self.assertEqual(roms[("bios", "dc\\naomi2.zip")].md5, "1" * 32) - self.assertEqual(roms[("bios", "dolphin-emu\\Sys\\GC\\font.bin")].md5, "3" * 32) - self.assertIn("[DAT](../downloads/dat/batocera.dat)", platform_data_links("batocera")) - - - -class ZippedFileMd5IsParsedOnce(unittest.TestCase): - """verify lowercased a comma md5 list, the builder and packverify did - not: an uppercase Recalbox-style md5 on a zipped_file entry was OK for - verify and a mismatch for the pack and the manifest.""" - - def test_an_uppercase_member_md5_is_accepted_everywhere(self): - import hashlib - import zipfile as zf_mod - - from scripts.resolve.acceptance import inner_rom_check - from scripts.packs.verdicts import verify_entry_md5 - - with tempfile.TemporaryDirectory() as directory: - archive = Path(directory, "x.zip") - with zf_mod.ZipFile(archive, "w") as zf: - zf.writestr("rom.bin", b"rom") - member = hashlib.md5(b"rom").hexdigest().upper() - for md5 in (member, f"{member},{'0' * 32}"): - with self.subTest(md5=md5): - entry = {"name": "x.zip", "zipped_file": "rom.bin", "md5": md5} - self.assertEqual(inner_rom_check(entry, str(archive)), "ok") - self.assertEqual( - verify_entry_md5(entry, str(archive))["status"], "ok" - ) - - def test_the_three_sites_share_the_parser(self): - for module in ("resolve/acceptance.py", "verify.py"): - source = script_source(module) - self.assertIn("parse_hash_list(", source, module) - self.assertIn("inner_rom_data_check(", script_source("packs/packhashes.py")) - - - -class AHashListIsReadOneWay(unittest.TestCase): - """mesence declares four sha256 for BS-X.bin as one comma-joined string. - The resolver split it and shipped the file, but the gap report and - profile_sync looked the whole string up and called it missing.""" - - def test_every_reader_splits_the_list(self): - from scripts.packs.supplemental import declared_content - from scripts.core.hashing import parse_hash_list - from scripts.profiling.citations import entry_hashes - - a, b = "a" * 64, "B" * 64 - entry = {"name": "BS-X.bin", "sha256": f"{a}, {b}", "crc32": "0xDEADBEEF"} - self.assertEqual(parse_hash_list(entry["sha256"]), [a, b.lower()]) - self.assertEqual(declared_content(entry)["sha256"], {a, b.lower()}) - self.assertEqual(declared_content(entry)["crc32"], {"deadbeef"}) - self.assertEqual(set(entry_hashes(entry)), {a, b.lower(), "deadbeef"}) - - - -class RommRunsTheCoresItsPlayerNames(unittest.TestCase): - """RomM's player merges a nightly core map into the stable one when netplay - is on. Inheriting EmulatorJS's list left azahar, bsnes and - genesis_plus_gx_wide out of the RomM pack, though RomM launches them.""" - - SOURCE = """ -const _EJS_CORES_MAP: Record = { - "3do": ["opera"], - arcade: [ - "mame2003_plus", - "fbneo", - ], -} as const; - -const _EJS_NIGHTLY_CORES_MAP: Record = { - "3ds": ["azahar"], - snes: ["snes9x", "bsnes"], -}; -""" - - def test_both_maps_are_read(self): - from scripts.scraper.romm_scraper import parse_player_cores - - self.assertEqual( - parse_player_cores(self.SOURCE), - ["azahar", "bsnes", "fbneo", "mame2003_plus", "opera", "snes9x"], - ) - - def test_a_missing_map_raises(self): - from scripts.scraper.romm_scraper import parse_player_cores - - source = self.SOURCE.replace("_EJS_NIGHTLY_CORES_MAP", "_RENAMED") - with self.assertRaises(RuntimeError): - parse_player_cores(source) - - def test_the_platform_file_carries_the_nightly_cores(self): - from model.platforms import load_platform_config - - cores = set(load_platform_config("romm", str(ROOT / "platforms"))["cores"]) - self.assertTrue({"azahar", "bsnes", "genesis_plus_gx_wide"} <= cores) - - -class RommNeoGeoFoldersGetTheirBios(unittest.TestCase): - """RomM runs fbneo for neogeoaes and neogeomvs as for arcade and reads - firmware per platform folder, but the fixture gives neogeo.zip to arcade - alone, so a Neo Geo game in its own folder started without it.""" - - def test_the_mirror_is_per_file(self): - from scripts.scraper.romm_scraper import FIRMWARE_MIRRORS, SLUG_MAP - - arcade = FIRMWARE_MIRRORS["arcade"] - self.assertEqual(arcade["neogeoaes"], ("neogeo.zip",)) - self.assertEqual(arcade["neogeomvs"], ("neogeo.zip",)) - self.assertIn("neogeoaes", SLUG_MAP) - - def test_a_file_files_under_its_own_system_only(self): - # Adding the Neo Geo slugs sent MAME 2003's ZN-1 BIOS and data files - # into neogeoaes/, and FBNeo's CPS3 sets already sat in colecovision/: - # a system the platform lacks has no folder, and a mirror-only - # folder attracts no system-less file. - from scripts.packs.extraplace import _slug_for - - config_systems = {"arcade", "snk-neogeo-aes", "nintendo-ds"} - sys_to_slug = {"arcade": "arcade", "snk-neogeo-aes": "neogeoaes", - "nintendo-ds": "nds"} - profiles = {"mame2003": {"systems": ["snk-neogeo-aes", "zn1-acclaim"]}, - "melonds": {"systems": ["nintendo-ds", "nintendo-dsi"]}} - args = (profiles, config_systems, {}, sys_to_slug, {"arcade", "nintendo-ds"}) - self.assertEqual(_slug_for({"profile": "mame2003", "system": "zn1-acclaim"}, *args), "") - self.assertEqual(_slug_for({"profile": "mame2003"}, *args), "") - self.assertEqual(_slug_for({"profile": "melonds", "system": "nintendo-dsi"}, *args), "") - self.assertEqual(_slug_for({"profile": "melonds"}, *args), "nds") - - def test_the_platform_file_carries_it(self): - text = (ROOT / "platforms" / "romm.yml").read_text(encoding="utf-8") - self.assertIn("destination: neogeoaes/neogeo.zip", text) - self.assertIn("destination: neogeomvs/neogeo.zip", text) - self.assertNotIn("neogeoaes/pgm.zip", text) - - - -class AProfilePathIsTheEmulatorsNotOurs(unittest.TestCase): - """No guard stopped a profile `path:` naming .variants/, our storage: - the pack would write the file where no emulator reads.""" - - def test_a_variants_path_is_refused(self): - from unittest import mock - - try: - from schemas import sourcetree - except ImportError as exc: - self.skipTest(f"validate_schemas needs jsonschema: {exc}") - - with tempfile.TemporaryDirectory() as directory: - emulators = Path(directory) / "emulators" - emulators.mkdir() - (emulators / "x.yml").write_text( - "emulator: X\nfiles:\n - name: scph1001.bin\n" - " path: .variants/scph1001.bin.abc12345\n" - ) - with mock.patch("core.paths.REPO_ROOT", Path(directory)): - errors = sourcetree.repository_layout_in_profiles() - self.assertEqual(len(errors), 1) - self.assertIn(".variants/", errors[0]) - - - -class DocumentedExamplesHoldTogether(unittest.TestCase): - """The verification block downloaded RetroArch_BIOS_Pack.zip*, a name - no release ever published (packs are versioned and split), and the - first-install example ended on "72 files installed" after announcing a - download of 12,893.""" - - def test_the_verification_pattern_matches_published_pack_names(self): - import fnmatch - import re - - page = (ROOT / "wiki" / "release-process.md").read_text(encoding="utf-8") - patterns = re.findall(r"--pattern '([^']*Pack[^']*)'", page) - self.assertTrue(patterns) - for name in ("RetroArch_Lakka_v1.22.2_BIOS_Pack.part1of2.zip", - "RetroArch_v1.22.2_BIOS_Pack.zip"): - with self.subTest(name=name): - self.assertTrue(any(fnmatch.fnmatch(name, p) for p in patterns)) - - def test_the_first_install_example_counts_one_number(self): - import re - - # The annotated run moved from First install to the installer page. - page = (ROOT / "wiki" / "installer.md").read_text(encoding="utf-8") - downloading = re.search(r"Downloading (\d+) files", page).group(1) - done = re.search(r"Done\. (\d+) files installed", page).group(1) - # The data trees come after the download, counted in the index. - index = page[page.index("Fetching file index for batocera"):] - trees = re.search(r"^ .* and (\d+) data files", index, re.M) - self.assertEqual(int(done), int(downloading) + (int(trees.group(1)) if trees else 0)) - - - -class TheReadmeCountsSystemsAsListSystemsDoes(unittest.TestCase): - """The README counted every raw spelling (nes and nintendo-nes as two) - and announced 550 systems while the tool it points to listed 513.""" - - def test_one_count(self): - import io - import re - from contextlib import redirect_stdout - - from scripts.model.cliargs import list_system_ids - - out = io.StringIO() - with redirect_stdout(out): - list_system_ids(str(ROOT / "emulators")) - listed = len(out.getvalue().splitlines()) - readme = (ROOT / "README.md").read_text(encoding="utf-8") - announced = int(re.search(r"\*\*(\d+) systems\*\*", readme).group(1)) - self.assertEqual(announced, listed) - - - -class ATargetIsNamedWhenItRemovesTheCore(unittest.TestCase): - """--platform batocera --target rpi4 --emulator dolphin said "dolphin is - not run by batocera", which runs it on every x86 board.""" - - def test_the_message_names_the_target(self): - result = subprocess.run( - [sys.executable, "scripts/cross_reference.py", "--platform", "batocera", - "--target", "bcm2711", "--emulator", "dolphin"], - cwd=ROOT, capture_output=True, text=True, timeout=600, - check=False, - ) - self.assertEqual(result.returncode, 1) - self.assertIn("bcm2711 target", result.stderr) - self.assertNotIn("is not run by", result.stderr) - - - -class ANamedPackThatIsAbsentFails(unittest.TestCase): - """--verify-packs --platform retroarch on an empty directory printed - "SKIP" and exited 1: a skip label on a failure, and no next step.""" - - def test_the_line_says_fail_and_how_to_build(self): - with tempfile.TemporaryDirectory() as directory: - result = subprocess.run( - [sys.executable, "scripts/generate_pack.py", "--platform", "retroarch", - "--verify-packs", "--output-dir", directory], - cwd=ROOT, capture_output=True, text=True, timeout=600, - check=False, - ) - self.assertEqual(result.returncode, 1) - self.assertIn("retroarch: FAIL (no pack in", result.stdout) - self.assertIn("generate_pack.py --platform retroarch", result.stdout) - - def test_all_with_no_pack_is_a_failure(self): - """--all on a mistyped or purged directory skipped every platform - and exited 0, a passed integrity check that checked nothing.""" - with tempfile.TemporaryDirectory() as directory: - result = subprocess.run( - [sys.executable, "scripts/generate_pack.py", "--all", - "--verify-packs", "--output-dir", directory], - cwd=ROOT, capture_output=True, text=True, timeout=600, - check=False, - ) - self.assertEqual(result.returncode, 1) - self.assertIn("no pack to verify", result.stderr) - - - -class AnAliasSelectsItsProfile(unittest.TestCase): - """`--emulator mednafen_psx` refused with "use --emulator beetle_psx", - a step the tool could take itself: the name a user reads in RetroArch - now selects the profile it is an alias of, and says so on stderr. An - alias without alias_of is found through the profile whose cores: names - it.""" - - def test_the_alias_selects_its_profile(self): - import contextlib as _contextlib - import io as _io - - from scripts.model.profiles import ProfileSelectionError, select_emulator_profiles - - profiles = { - "flycast": {"type": "libretro", "cores": ["flycast", "flycast_gles2"]}, - "flycast_gles2": {"type": "alias", "alias_of": "flycast"}, - "orphan": {"type": "alias"}, - "core": {"type": "libretro", "cores": ["orphan"]}, - "lost": {"type": "alias"}, - } - for name, expected in (("flycast_gles2", "flycast"), ("orphan", "core")): - err = _io.StringIO() - with self.subTest(name=name), _contextlib.redirect_stderr(err): - selected = select_emulator_profiles([name], profiles) - self.assertEqual([key for key, _ in selected], [expected]) - self.assertIn(f"{name} is {expected}", err.getvalue()) - with _contextlib.redirect_stderr(_io.StringIO()): - both = select_emulator_profiles(["flycast", "flycast_gles2"], profiles) - self.assertEqual([key for key, _ in both], ["flycast"]) - with self.assertRaises(ProfileSelectionError): - select_emulator_profiles(["lost"], profiles) - - def test_verify_runs_the_alias(self): - result = subprocess.run( - [sys.executable, "scripts/verify.py", "--emulator", "mednafen_psx"], - cwd=ROOT, capture_output=True, text=True, timeout=300, check=False, - ) - self.assertEqual(result.returncode, 0, result.stderr) - self.assertIn("beetle_psx", result.stdout) - self.assertIn("mednafen_psx is beetle_psx", result.stderr) - - - -class AFailedVerificationIsAnError(unittest.TestCase): - """--all ended on "WARNING: some packs have verification errors" and - exit 1: a warning that fails the run, naming no pack.""" - - def test_the_last_line_names_the_packs(self): - source = script_source("generate_pack.py") - self.assertNotIn("WARNING: some packs have verification errors", source) - self.assertIn('print(f"ERROR: packs failed verification: {\', \'.join(failing)}", file=sys.stderr)', source) - - - -class TheGroundTruthFooterSaysWhatItCounts(unittest.TestCase): - """"417 platform-only (no emulator profile)" where 369 of 526 files had - a profile, 20% here for 21% on the site, and "0/81 (0%)" for MiSTer, - which declares no core by design.""" - - def _footer(self, coverage): - import io as _io - from contextlib import redirect_stdout - - from scripts.packs.verdicts import Severity - from scripts.packs.report import print_platform_result - - out = _io.StringIO() - counts = {Severity.OK: 1, Severity.INFO: 0, Severity.WARNING: 0, Severity.CRITICAL: 0} - result = {"platform": "X", "verification_mode": "existence", "total_files": 1, - "severity_counts": counts, "status_counts": {"ok": 1}, - "undeclared_files": [], "exclusion_notes": [], "details": [], - "ground_truth_coverage": coverage} - with redirect_stdout(out): - print_platform_result(result, ["X"]) - return out.getvalue() - - def test_counts_and_rounding(self): - text = self._footer({"with_validation": 109, "with_profile": 369, - "platform_only": 417, "total": 526, "applicable": True}) - self.assertIn("(21%)", text) - self.assertIn("157 platform-only", text) - - def test_not_applicable(self): - text = self._footer({"with_validation": 0, "with_profile": 0, - "platform_only": 81, "total": 81, "applicable": False}) - self.assertIn("not applicable", text) - self.assertNotIn("0/81", text) - - -class ThePipelineSummaryTimesEachStep(unittest.TestCase): - """The summary gave OK per step and one total: the slow step of a - twenty-minute run could only be found by reading the log.""" - - def test_each_outcome_carries_its_time(self): - from unittest import mock - - clock = iter([10.0, 12.5, 12.5, 20.0]) - with mock.patch.object(results.time, "monotonic", lambda: next(clock)): - outcomes = results.StepResults(results.time.monotonic()) - outcomes["generate_db"] = True - outcomes["refresh_data"] = results.SKIPPED - outcomes["verify"] = True - self.assertEqual(outcomes.seconds, {"generate_db": 2.5, "refresh_data": 0.0, "verify": 7.5}) - self.assertEqual(dict(outcomes), {"generate_db": True, "refresh_data": results.SKIPPED, - "verify": True}) - - -class StrictFailsOnMissingOnly(unittest.TestCase): - """The docstring promised exit 1 on a required file missing or rejected, - but a rejected file is UNTESTED, a warning, and --strict never saw it.""" - - def test_the_contract(self): - from scripts.packs.strictgate import platform_strict_failure - from scripts.packs.verdicts import Severity - - self.assertIsNone(platform_strict_failure([{"severity_counts": {Severity.WARNING: 2}}])) - self.assertIsNotNone( - platform_strict_failure([{"severity_counts": {Severity.CRITICAL: 1}}])) - self.assertNotIn("or rejected", platform_strict_failure.__doc__) - - -class TheRepairCommandWritesTheFileNamed(unittest.TestCase): - """--db nosuch.json said to rebuild with --output database.json: the - command wrote another file and the next run failed the same way.""" - - def test_the_command_names_the_path(self): - from scripts.model.database import DatabaseUnreadable, load_database - - with tempfile.TemporaryDirectory() as directory: - target = str(Path(directory) / "nosuch.json") - with self.assertRaises(DatabaseUnreadable) as caught: - load_database(target) - self.assertIn(f"--output {target}", str(caught.exception)) - Path(target).write_text("{") - with self.assertRaises(DatabaseUnreadable) as caught: - load_database(target) - self.assertIn(f"--output {target}", str(caught.exception)) - - def test_a_typo_beside_the_database_names_the_database(self): - """--db databse.json beside database.json was told to rescan the whole - collection into a second file named after the typo.""" - from scripts.model.database import DatabaseUnreadable, load_database - - with tempfile.TemporaryDirectory() as directory: - (Path(directory) / "database.json").write_text("{}") - typo = Path(directory) / "databse.json" - with self.assertRaises(DatabaseUnreadable) as caught: - load_database(str(typo)) - message = str(caught.exception) - self.assertIn(f"Close match: {typo.with_name('database.json')}", message) - self.assertNotIn("generate_db.py", message) - - -class VerifyPacksRefusesWhatItCannotDo(unittest.TestCase): - """The --verify-packs refusals lived in the --all-variants checks, which - return without that flag: --split and --one-per-slot went through, and - a run with neither --platform nor --all failed after taking the lock.""" - - def test_usage_errors_exit_2_before_any_lock(self): - cases = ( - ["--verify-packs"], - ["--verify-packs", "--platform", "retroarch", "--split"], - ["--verify-packs", "--platform", "retroarch", "--one-per-slot"], - ) - for extra in cases: - with self.subTest(args=extra), tempfile.TemporaryDirectory() as out: - result = subprocess.run( - [sys.executable, "scripts/generate_pack.py", *extra, "--output-dir", out], - cwd=ROOT, capture_output=True, text=True, timeout=300, - check=False, - ) - self.assertEqual(result.returncode, 2, result.stderr[-300:]) - self.assertIn("--verify-packs", result.stderr) - self.assertFalse((Path(out) / ".lock").exists()) - - -class AHashScanningCoreContradictsNoPlatform(unittest.TestCase): - """ares finds its firmware by sha256 in a folder and opens no file by - name, so its entries' names are labels. Labels reused from other dumps - (MSX2.ROM, bios_CD_U.bin) put ares's revision on a path where RetroBat - pins another: slots called RetroBat's declaration wrong, and the pack - dropped ares's own dump behind the platform's.""" - - def test_no_conflict_names_ares(self): - import json - - from scripts.packs import slotscan - from scripts.model.registry import list_registered_platforms - from scripts.model.profiles import load_emulator_profiles - - root = ROOT - if not (root / "database.json").exists(): - self.skipTest("database.json is not built") - profiles = load_emulator_profiles(str(root / "emulators")) - db = json.loads((root / "database.json").read_text(encoding="utf-8")) - claimed = [ - (platform, conflict.destination) - for platform in list_registered_platforms(str(root / "platforms")) - for conflict in slotscan.scan_platform(platform, profiles, db, str(root / "platforms")) - if any(claim.emulator == "ares" for claim in conflict.profile_claims) - ] - self.assertEqual(claimed, []) - - -class FsUaeKickstartIsFoundByContent(unittest.TestCase): - """FS-UAE scans its Kickstarts directory and names a ROM by checksum - (src/fs-uae/config.c:121-140, main.c:431-470), and with no ROM loads the - AROS replacement (memory.cpp:2374-2379). kick13.rom and its required - flag came from the RetroPie launcher, which the platform layer records.""" - - def test_the_kickstart_is_an_optional_label(self): - from scripts.resolve.entryscope import opens_by_name - - profile = yaml.safe_load((ROOT / "emulators" / "fs-uae.yml").read_text(encoding="utf-8")) - entry = next(f for f in profile["files"] if f.get("sha1") == "891e9a547772fe0c6c19b610baf8bc4ea7fcb785") - self.assertFalse(opens_by_name(entry, profile, standalone=True)) - self.assertFalse(entry.get("required")) - self.assertNotIn("RetroPie launcher", entry.get("note", "")) - - -class NoProfileHashFromASecondarySource(unittest.TestCase): - """ecwolf.yml pinned ecwolf.pk3 to an md5 its note said came from the - .info. The code checks none, and no file shipped at the pin carries it: - a source without a hash gives the profile none.""" - - PATTERN = re.compile( - r"(md5|sha1|crc32|hash)[^.]{0,40}\bfrom (the )?(\.info|core-?info|docs?|documentation)", - re.IGNORECASE, - ) - - def test_no_hashed_entry_names_a_secondary_source(self): - found = [] - for path in sorted((ROOT / "emulators").glob("*.yml")): - profile = yaml.safe_load(path.read_text(encoding="utf-8")) or {} - for entry in profile.get("files") or []: - if not isinstance(entry, dict): - continue - if any(entry.get(k) for k in ("md5", "sha1", "crc32", "sha256")) and ( - self.PATTERN.search(str(entry.get("note", ""))) - ): - found.append(f"{path.name}: {entry.get('name')}") - self.assertEqual(found, []) - - -class XeniosFollowsItsReleaseBranch(unittest.TestCase): - """The xenios pin 87b176a0 sat on `preview`, which diverged from the - default `xenios` branch, and without source_branch profile_sync read the - pin as orphaned. Since November 2026 the releases (2.2 to 2.3.1) come from - `xenios` and `preview` stopped in June: the pin is release 2.3.1 on the - default branch, so the profile names no other branch.""" - - def test_the_profile_follows_the_branch_its_pin_is_on(self): - profile = yaml.safe_load((ROOT / "emulators" / "xenios.yml").read_text(encoding="utf-8")) - self.assertIn(profile.get("source_branch"), (None, "xenios")) - self.assertEqual(profile["source_commit"][:7], "cf7c7ee") - - -class PcemUpstreamPinIsTheLastSync(unittest.TestCase): - """The pcem bump set upstream_commit to dev's HEAD 25b54e3f, and dev was - rewritten: the pin left every branch (compare: diverged 109/114). The - port shares no history with upstream and took mainline patches by hand - until 2016-04-13, whose last upstream commit is 10739b96. Held there, a - bump cannot move it to a HEAD the port never contained.""" - - def test_the_upstream_pin_is_held_at_the_last_sync(self): - profile = yaml.safe_load((ROOT / "emulators" / "pcem.yml").read_text(encoding="utf-8")) - self.assertEqual(profile["upstream_commit"], "10739b9618e388a5bf8c21e752f12b3952fa83e1") - self.assertTrue(profile.get("upstream_frozen")) - - -class AHashScanLabelNamesNoOtherDump(unittest.TestCase): - """A core that finds its firmware by content names no file, so each - entry name is a label. ares labelled its Famicom Disk System revision - (RP2C33-01, crc32 1c7ae5d5) disksys.rom, the name six NES cores read for - the RP2C33A-01A dump: on ROCKNIX the manifest put ares's revision at - disksys.rom for all of them. A label that another profile gives a - different dump is refused, the two dumps compared through the - collection's hash indexes.""" - - # Names the core's own code gives the image, not labels. - CODE_NAMED = { - ("bizhawk", "MSX.rom"): - "FirmwareDatabase.cs:362 names the image MSX.rom", - ("swanstation", "ps1_rom.bin"): - "the whole PS3 image is the file the PS3 itself names ps1_rom.bin, " - "beetle_psx reads its first 512 KB under the same name", - ("duckstation-legacy", "ps1_rom.bin"): - "the same whole PS3 image, whose first 512 KB src/core/bios.cpp:89 hashes", - ("openmsx", "COLECO.ROM"): - "share/machines/ColecoVision_SGM.xml:56 names it, tried beside the machine XML", - ("openmsx", "fmpac.rom"): - "share/machines/Boosted_MSX2_EN.xml:83 names it, tried beside the machine XML", - ("openmsx-libretro", "rs232.rom"): - "share/extensions/rs232.xml:18-22 names it, tried beside the extension XML", - } - - @staticmethod - def _identity(entry: dict, db: dict) -> tuple[set, set]: - raw: set = set() - sha1s: set = set() - indexes = db["indexes"] - for field, index in (("sha1", None), ("md5", "by_md5"), - ("crc32", "by_crc32"), ("sha256", "by_sha256")): - value = entry.get(field) - values = value if isinstance(value, list) else [value] if value else [] - for item in values: - for digest in str(item).lower().split(","): - digest = digest.strip() - if not digest: - continue - raw.add((field, digest)) - sha1 = digest if index is None else indexes[index].get(digest) - if sha1 in db["files"]: - sha1s.add(sha1) - return raw, sha1s - - def test_labels_are_not_other_dumps_names(self): - import json - - from scripts.model.profiles import load_emulator_profiles - - if not (ROOT / "database.json").exists(): - self.skipTest("database.json is not built") - db = json.loads((ROOT / "database.json").read_text(encoding="utf-8")) - profiles = load_emulator_profiles(str(ROOT / "emulators")) - by_name: dict[str, list[tuple[str, dict]]] = {} - for emulator, profile in profiles.items(): - for entry in profile.get("files") or []: - for name in [entry.get("name"), *(entry.get("aliases") or [])]: - if name: - by_name.setdefault(str(name).casefold(), []).append((emulator, entry)) - clashes = [] - for emulator, profile in profiles.items(): - if profile.get("found_by") != "content": - continue - for entry in profile.get("files") or []: - raw, sha1s = self._identity(entry, db) - if not sha1s: - continue - for name in [entry.get("name"), *(entry.get("aliases") or [])]: - if (emulator, name) in self.CODE_NAMED: - continue - for other, other_entry in by_name.get(str(name).casefold(), []): - if other == emulator: - continue - other_raw, other_sha1s = self._identity(other_entry, db) - if other_sha1s and not raw & other_raw and not sha1s & other_sha1s: - clashes.append(f"{emulator} {name} is {other}'s name for another dump") - self.assertEqual(sorted(set(clashes)), []) - - -class ANoteOutsideTheSystemDirCarriesLoadFrom(unittest.TestCase): - """mame2000 opens hiscore.dat, history.dat and mameinfo.dat from the - directory of the loaded content (src/libretro/fileio.c:1002-1014), and - mame2014 and mame2015 open hiscore.dat from the working directory - (src/emu/hiscore.c:330-337). Their notes said so, but no load_from did: - the entries claimed system/hiscore.dat and the RetroArch pack shipped a - file neither core opens there. A libretro entry whose note places the - read outside the system directory declares where.""" - - ELSEWHERE = re.compile( - r"\b(?:opened|read|loaded)\b[^.]*?\bfrom (?:the )?(?:working directory|" - r"ROM directory|content directory|directory of the loaded content)" - r"|IMAMEBASEPATH", - re.IGNORECASE, - ) - - def test_prose_and_load_from_agree(self): - offenders = [] - for path in sorted((ROOT / "emulators").glob("*.yml")): - profile = yaml.safe_load(path.read_text(encoding="utf-8")) or {} - if profile.get("type") != "libretro": - continue - for entry in profile.get("files") or []: - if entry.get("path") or entry.get("load_from") or entry.get("mode") == "standalone": - continue - if self.ELSEWHERE.search(str(entry.get("note") or "")): - offenders.append(f"{path.name}: {entry.get('name')}") - self.assertEqual(offenders, []) - - -class ReportsHoldTheDataTrees(unittest.TestCase): - """Run on their own, the README, site and slot reports resolved against - data/ without the shared hold, so a concurrent refresh could swap a tree - while they read it and the published counts came from half of it.""" - - def test_each_entry_point_holds_them(self): - import ast - - # export_native holds them in build_export, which the freshness - # check calls too (TheExportHoldsTheDataTrees in test_export_report). - for script in ("generate_readme.py", "generate_site.py", "slots.py", - "cross_reference.py"): - tree = ast.parse((ROOT / "scripts" / script).read_text(encoding="utf-8")) - main = next( - node for node in tree.body - if isinstance(node, ast.FunctionDef) and node.name == "main" - ) - # A thin command holds them in main or in the package run main calls. - called = {getattr(call.func, "id", None) for call in ast.walk(main) - if isinstance(call, ast.Call)} - entry_points = [main] + [ - node for node in ast.walk(ast.parse(script_source(script))) - if isinstance(node, ast.FunctionDef) and node.name in called - ] - with self.subTest(script=script): - self.assertTrue(any( - isinstance(call, ast.Call) - and getattr(call.func, "id", None) == "hold_data_dirs" - for entry in entry_points for call in ast.walk(entry) - )) - - -class TheTreeKeepsStandaloneEntries(unittest.TestCase): - """With no platform named, the gap report laid every dual profile out as - libretro only: eka2l1, dolphin and xenia-edge lost 133 files that - Batocera and RetroBat run standalone and no platform declares.""" - - def test_a_standalone_only_entry_is_reported(self): - if not (ROOT / "database.json").exists(): - self.skipTest("database.json is not built") - out = subprocess.run( - [sys.executable, "scripts/cross_reference.py", "--emulator", "eka2l1"], - cwd=ROOT, capture_output=True, text=True, timeout=600, check=True, - ).stdout - undeclared = re.search(r"(\d+) undeclared", out) - self.assertIsNotNone(undeclared, out[-500:]) - self.assertGreater(int(undeclared.group(1)), 0) - - -class TheCliSetsBundledFilesApart(unittest.TestCase): - """cross_reference counted daedalusx64's n64.psh and touchHLE's runtime - libraries as missing, to be sourced, though the project leaves them out - by design and verify and the gaps page already say so.""" - - def test_a_bundled_gap_is_not_missing(self): - from scripts.packs.crossreftext import print_report - - gap = {"name": "n64.psh", "required": True, "bundled": True, "note": "", - "source": "missing"} - report = {"emu": { - "emulator": "Emu", "systems": [], "total_files": 1, "platform_covered": 0, - "gaps": 1, "gap_missing": 1, "gap_details": [gap], - }} - out = io.StringIO() - with contextlib.redirect_stdout(out): - print_report(report) - text = out.getvalue() - self.assertIn("0 missing (need to be sourced)", text) - self.assertIn("1 bundled with their emulator", text) - self.assertIn("n64.psh [BUNDLED]", text) - - -class ThePackCheckAppliesTheFrontendRule(unittest.TestCase): - """The integrity step compared a member's md5 alone. Under RomM's rule - (size, then any of md5, sha1 and crc32) the builder ships a revision - matched on its sha1, and the check then refused a correct pack.""" - - def test_romm_accepts_on_size_and_sha1(self): - import hashlib - import zipfile - - from scripts.packs.packhashes import _check_member_hash - - payload = b"revision B" - entry = { - "md5": "0" * 32, - "sha1": hashlib.sha1(payload).hexdigest(), - "size": len(payload), - } - with tempfile.TemporaryDirectory() as tmp: - pack = Path(tmp) / "p.zip" - with zipfile.ZipFile(pack, "w") as zf: - zf.writestr("bios/x.bin", payload) - with zipfile.ZipFile(pack) as zf: - self.assertIsNone( - _check_member_hash(zf, "bios/x.bin", entry, "md5", "size_and_any_hash") - ) - self.assertIsNotNone(_check_member_hash(zf, "bios/x.bin", entry, "md5")) - - -class ABrokenRegistryIsNotAnEmptyOne(unittest.TestCase): - """A registered platform whose YAML was renamed was skipped without a - word, and a missing registry read as no platforms: verify --all --strict - and every --all build passed having checked nothing.""" - - def test_both_raise(self): - from scripts.model.registry import list_registered_platforms - - with tempfile.TemporaryDirectory() as tmp: - with self.assertRaises(FileNotFoundError): - list_registered_platforms(tmp) - Path(tmp, "_registry.yml").write_text( - "platforms:\n rocknix:\n config: rocknix.yml\n", encoding="utf-8" - ) - with self.assertRaises(FileNotFoundError) as caught: - list_registered_platforms(tmp) - self.assertIn("rocknix", str(caught.exception)) - - -@tests.ONLINE -class AnUnansweredSearchIsNotANotFound(unittest.TestCase): - """auto_fetch caught every network error and reported the file as - needing a community contribution: offline, each file became an issue - asking the public for something the tool never looked for.""" - - def _fetch(self, error): - from unittest import mock - - from scripts.acquire import fetch as acquire_fetch - - def refuse(*_args, **_kwargs): - raise error - - entry = {"name": "nowhere.bin", "system": "test-system", "sha1": "0" * 40} - db = {"files": {}, "indexes": {"by_md5": {}, "by_name": {}}} - with mock.patch("urllib.request.urlopen", refuse), \ - mock.patch.object(acquire_fetch.forgehttp, "_sleep", lambda _s: None), \ - mock.patch.object(acquire_fetch, "step2_scan_branches", lambda e: None): - return acquire_fetch.fetch_missing([entry], db, "bios") - - def test_offline_is_not_searched(self): - import urllib.error - - result = self._fetch(urllib.error.URLError("offline")) - self.assertEqual(result["still_missing"], []) - self.assertEqual(result["stats"]["errors"], 1) - - def test_a_404_everywhere_is_not_found(self): - import urllib.error - - result = self._fetch(urllib.error.HTTPError("u", 404, "missing", {}, None)) - self.assertEqual(len(result["still_missing"]), 1) - self.assertEqual(result["stats"]["errors"], 0) - - -class AutoFetchProvesEveryHashItIsGiven(unittest.TestCase): - """auto_fetch checked a download by sha1 or md5 only: RetroDECK's - dsifirmware.bin, pinned by sha256 alone, was announced as searched and - could never be accepted.""" - - DATA = b"firmware bytes" - - def test_a_sha256_proves_a_download(self): - import hashlib - - from scripts.acquire import fetch as acquire_fetch - - sha256 = {"sha256": hashlib.sha256(self.DATA).hexdigest()} - self.assertTrue(acquire_fetch.verify_content(self.DATA, sha256)) - self.assertFalse(acquire_fetch.verify_content(b"other", sha256)) - - def test_every_declared_cryptographic_hash_must_match(self): - import hashlib - - from scripts.acquire import fetch as acquire_fetch - - both = {"sha256": hashlib.sha256(self.DATA).hexdigest(), "md5": "0" * 32} - self.assertFalse(acquire_fetch.verify_content(self.DATA, both)) - both["md5"] = hashlib.md5(self.DATA).hexdigest() - self.assertTrue(acquire_fetch.verify_content(self.DATA, both)) - - def test_crc32_and_size_never_accept_a_download(self): - """A crc32 can be forged: bytes a source crafts to it would land in - bios/.""" - import urllib.request - import zlib - from unittest import mock - - from scripts.acquire import fetch as acquire_fetch - - crc = {"name": "forged.bin", "system": "test-system", - "crc32": f"{zlib.crc32(self.DATA):08X}", "size": len(self.DATA)} - self.assertFalse(acquire_fetch.verify_content(self.DATA, crc)) - self.assertFalse(acquire_fetch.verifiable(crc)) - - served = io.BytesIO(self.DATA) - with tempfile.TemporaryDirectory() as bios, \ - mock.patch.object(urllib.request, "urlopen", lambda *a, **k: served), \ - mock.patch.object(acquire_fetch, "step2_scan_branches", - lambda e: self.DATA): - result = acquire_fetch.fetch_missing([crc], {"files": {}}, bios) - self.assertEqual(list(Path(bios).rglob("*")), []) - self.assertEqual(result["stats"]["found"], 0) - self.assertEqual(result["stats"]["unverifiable"], 1) - self.assertEqual([r.outcome for r in result["records"]], ["unverifiable"]) - - def test_a_held_sha256_is_found_in_the_database(self): - from scripts.acquire import fetch as acquire_fetch - - db = {"files": {"s": {"path": "bios/x/dsi.bin", "size": 3, "sha256": "f" * 64}}, - "indexes": {"by_sha256": {"f" * 64: "s"}}} - self.assertEqual( - acquire_fetch.step1_crossref_db({"sha256": "F" * 64}, db), "bios/x/dsi.bin" - ) - - def test_a_held_file_a_declared_hash_contradicts_is_still_searched(self): - """auto_fetch printed "Found in database" for a crc32 or md5 hit whose - sha1 the entry contradicts, a file verify calls missing.""" - from scripts.acquire import fetch as acquire_fetch - - held = {"path": "bios/x/a.bin", "sha1": "c" * 40, "md5": "d" * 32, - "crc32": "deadbeef", "size": 4} - db = {"files": {"c" * 40: held}, - "indexes": {"by_crc32": {"deadbeef": "c" * 40}, "by_md5": {"d" * 32: "c" * 40}}} - find = acquire_fetch.step1_crossref_db - self.assertIsNone(find({"sha1": "a" * 40, "crc32": "deadbeef", "size": 4}, db)) - self.assertIsNone(find({"sha1": "a" * 40, "md5": "d" * 32}, db)) - self.assertIsNone(find({"crc32": "deadbeef", "size": 5}, db)) - self.assertEqual(find({"crc32": "deadbeef", "size": 4}, db), "bios/x/a.bin") - self.assertEqual(find({"md5": "d" * 29}, db), "bios/x/a.bin") - - def test_an_entry_without_a_hash_is_not_searched(self): - from unittest import mock - - from acquire import fetch as acquire_fetch - from acquire import fetchtext - - entry = {"name": "DICROM.ROM", "system": "fujitsu-fm7"} - out = io.StringIO() - with mock.patch.object(acquire_fetch, "step2_scan_branches") as branches, \ - contextlib.redirect_stdout(out): - result = fetchtext.report_fetch([entry], {"files": {}}, "bios", dry_run=True) - branches.assert_not_called() - self.assertEqual(result["stats"]["unverifiable"], 1) - self.assertNotIn("Would search", out.getvalue()) - self.assertIn("Not searched", out.getvalue()) - - -class AForcedRehashIsCheckedAgainstTheLastOne(unittest.TestCase): - """This host has computed a wrong SHA-1 under load. The pipeline's forced - rebuild threw the previous digests away and wrote whatever it read.""" - - def test_a_reading_the_cache_and_a_second_reading_contradict_is_outvoted(self): - from unittest import mock - - from collection import scan - - cached = {"sha1": "a" * 40, "mtime": 1.0, "size": 4} - readings = iter([{"sha1": "b" * 40}, {"sha1": "a" * 40}]) - with mock.patch.object(scan, "compute_hashes", lambda *a, **k: next(readings)), \ - contextlib.redirect_stderr(io.StringIO()) as err: - settled = scan._settled_hashes(Path("x.bin"), cached, 1.0, 4) - self.assertEqual(settled["sha1"], "a" * 40) - self.assertIn("WARNING", err.getvalue()) - - def test_two_agreeing_readings_against_an_unmoved_file_stop_the_run(self): - """The host has returned the same wrong SHA-1 twice in a row - (DSi_Nand_USA.bin as 62b100f2, 2026-10-22). Taking two agreeing - readings as a rewrite put the wrong value in the cache, where every - later run read it back. An unmoved file is never rewritten silently.""" - from unittest import mock - - from collection import scan - - cached = {"sha1": "a" * 40, "mtime": 1.0, "size": 4} - with mock.patch.object(scan, "compute_hashes", lambda *a, **k: {"sha1": "b" * 40}), \ - self.assertRaisesRegex(RuntimeError, "touch"): - scan._settled_hashes(Path("x.bin"), cached, 1.0, 4) - - def test_a_changed_file_takes_its_new_digest(self): - from unittest import mock - - from collection import scan - - cached = {"sha1": "a" * 40, "mtime": 1.0, "size": 4} - with mock.patch.object(scan, "compute_hashes", lambda *a, **k: {"sha1": "c" * 40}): - self.assertEqual( - scan._settled_hashes(Path("x.bin"), cached, 2.0, 4)["sha1"], "c" * 40 - ) - - -class AnUnknownTargetIsRefusedUnderAll(unittest.TestCase): - """--all --target swtich skipped every platform with targets and checked - BizHawk and MiSTer unfiltered: a green run about no Switch at all.""" - - def test_a_typo_is_refused_and_targetless_platforms_are_left_out(self): - from scripts.model.targets import build_target_cores_cache - from scripts.model.registry import list_registered_platforms - - platforms = list_registered_platforms(str(ROOT / "platforms")) - with self.assertRaises(ValueError): - build_target_cores_cache(platforms, "swtich", str(ROOT / "platforms"), is_all=True) - _cache, kept, _notes = build_target_cores_cache( - platforms, "switch", str(ROOT / "platforms"), is_all=True - ) - self.assertNotIn("bizhawk", kept) - self.assertIn("retroarch", kept) - - -class DocsDescribeTheRegistriesTheyName(unittest.TestCase): - """The contributing guide said files over 50 MB are release assets and that - RPG Maker and ScummVM were the trees kept out of dedup. `.gitignore` - decides the first, four committed files exceed 50 MB, and NODEDUP_DIRS - holds eleven trees.""" - - SIZE_RULE = re.compile(r"(over|larger than|>)\s*50\s*MB[^\n]*(release|asset)", re.I) - - def _texts(self): - paths = sorted((ROOT / "wiki").glob("*.md")) - paths += [ROOT / "scripts" / "generate_readme.py", ROOT / "CONTRIBUTING.md"] - return [(p, p.read_text(encoding="utf-8")) for p in paths] - - def test_no_page_says_size_decides_a_release_asset(self): - offenders = [str(p.relative_to(ROOT)) for p, text in self._texts() - if self.SIZE_RULE.search(text)] - self.assertEqual(offenders, []) - - def test_the_dedup_list_is_named_whole_or_by_its_constant(self): - from model.nodedup import NODEDUP_DIRS - tools = (ROOT / "wiki" / "tools.md").read_text(encoding="utf-8") - line = next(entry for entry in tools.splitlines() if "NODEDUP_DIRS" in entry) - # Compared as list items: `mame` was missing while the substring - # test found it in `_mame_clones.json` on the same line. - listed = line.split("`NODEDUP_DIRS`", 1)[1].split(":", 1)[1].rstrip(" |") - self.assertEqual( - sorted(item.strip() for item in listed.split(",")), - sorted(NODEDUP_DIRS), - ) - readme_gen = script_source("generate_readme.py") - self.assertIn("NODEDUP_DIRS", readme_gen) - - -class AScraperThatCannotStartSaysWhy(unittest.TestCase): - """Scrapers resolve their tag or branch head in the constructor, and - scraper_cli built the scraper outside its try: a refused API call ended - in a traceback instead of a message saying to set GITHUB_TOKEN.""" - - def _run(self, scraper_class, token: str | None): - import contextlib - import io - from unittest import mock - - from scraper.base_scraper import scraper_cli - - env = {k: v for k, v in os.environ.items() if k != "GITHUB_TOKEN"} - if token: - env["GITHUB_TOKEN"] = token - err = io.StringIO() - with mock.patch.dict(os.environ, env, clear=True), \ - mock.patch.object(sys, "argv", ["x", "--dry-run"]), \ - contextlib.redirect_stderr(err), \ - self.assertRaises(SystemExit) as stop: - scraper_cli(scraper_class) - return stop.exception.code, err.getvalue() - - def test_a_failing_constructor_exits_with_a_hint(self): - class Refused: - def __init__(self): - raise RuntimeError("cannot read the head of a/b@main: HTTP 403") - - code, err = self._run(Refused, None) - self.assertEqual(code, 1) - self.assertIn("HTTP 403", err) - self.assertIn("GITHUB_TOKEN", err) - - def test_with_a_token_the_hint_points_elsewhere(self): - class Offline: - def fetch_requirements(self): - raise ConnectionError("no route to host") - - code, err = self._run(Offline, "t") - self.assertEqual(code, 1) - self.assertNotIn("GITHUB_TOKEN", err) - - -class AStepThatCannotFailTheRunIsNotShownFailed(unittest.TestCase): - """check_buildbot leaves all_ok alone, and the summary printed it FAILED - right above "Pipeline COMPLETE". The total also missed the duration - column by fourteen characters.""" - - def test_every_step_outside_all_ok_is_declared_non_blocking(self): - lines = script_source("pipeline.py").splitlines() - loose = set() - for number, line in enumerate(lines): - found = re.search(r'results\["(\w+)"\] = ok$', line.strip()) - if not found: - continue - after = " ".join(lines[number + 1:number + 4]) - if "all_ok" not in after and "sys.exit" not in after: - loose.add(found.group(1)) - self.assertEqual(loose, set(results.NON_BLOCKING)) - - def test_the_total_sits_under_the_durations(self): - step = f" {'x':.<40} {'OK':<7}{1.0:>8.1f}s" - total = f" {'total':.<40} {'':<7}{12.5:>8.1f}s" - self.assertEqual(len(step), len(total)) - self.assertIn("{'':<7}{total_elapsed:>8.1f}s", - script_source("pipeline.py")) - - -class AHashConflictIsReportedOnce(unittest.TestCase): - """check_freshness opened on six copies of one truth.py warning, one per - platform whose model met the same two GameIndex.yaml declarations.""" - - def test_the_same_pair_prints_once(self): - from resolve import truth - - truth._CONFLICTS_SHOWN.clear() - with self.assertLogs(truth.log, "WARNING") as logged: - for _platform in range(6): - existing = {"name": "x.yaml", "sha1": "a" * 40} - truth._merge_hashes(existing, {"name": "x.yaml", "sha1": "b" * 40}, "core") - self.assertEqual(len(logged.records), 1) - - -class ThePipelineRunsTheSchemaCheckCIRuns(unittest.TestCase): - """The pipeline the repository asks for after every change never ran - validate_schemas.py, which PR validation does: a profile with an - unquoted numeric core name passed it and failed CI on push.""" - - def test_the_ci_command_is_a_pipeline_step(self): - workflow = (ROOT / ".github" / "workflows" / "validate.yml").read_text(encoding="utf-8") - command = re.search(r"python (scripts/validate_schemas\.py[^\n]*)", workflow).group(1) - script, *flags = command.split() - source = script_source("pipeline.py") - self.assertIn(f'"{script}"', source) - for flag in flags: - self.assertIn(f'"{flag}"', source) - - def test_the_site_is_rendered_as_the_deploy_renders_it(self): - """The pipeline generated pages without rendering them: 20 pages with - duplicate ids passed it and failed the deploy.""" - workflow = (ROOT / ".github" / "workflows" / "deploy-site.yml").read_text(encoding="utf-8") - source = script_source("pipeline.py") - self.assertIn("npm run build --prefix website", workflow) - self.assertIn('["npm", "run", "build", "--prefix", "website"]', source) - self.assertIn("scripts/validate_site.py", workflow) - self.assertIn('"scripts/validate_site.py"', source) - - -class TheReleaseBuildsEveryServedPackInOneRun(unittest.TestCase): - """The release ran the pipeline, then built and checked RetroPie by hand: - the consistency check between verify and the pack never covered it.""" - - def test_the_pipeline_step_covers_every_platform(self): - page = (ROOT / "wiki" / "release-process.md").read_text(encoding="utf-8") - self.assertIn("python scripts/pipeline.py\n", page) - self.assertNotIn("generate_pack.py --platform retropie", page) - - -class WhatOnlyAnInstallProvidesIsListed(unittest.TestCase): - """A file installed with its emulator is already on the user's machine. - A copy nothing else asks for is dead weight in the collection.""" - - def test_only_the_bundled_only_copy_is_listed(self): - import tempfile - - from packs import bundledonly - - with tempfile.TemporaryDirectory() as tmp, \ - mock.patch.object(bundledonly, "list_registered_platforms", return_value=[]): - def entry(sha1, name): - path = Path(tmp, name) - path.write_bytes(name.encode()) - return {"path": str(path), "name": name, "sha1": sha1, - "md5": sha1[:32], "size": path.stat().st_size} - - db = {"bios_dir": tmp, - "files": {"a" * 40: entry("a" * 40, "icon.png"), - "b" * 40: entry("b" * 40, "bios.rom")}, - "indexes": {"by_name": {"icon.png": ["a" * 40], "bios.rom": ["b" * 40]}, - "by_md5": {}, "by_crc32": {}, "by_sha256": {}, - "by_path_suffix": {}}} - profiles = { - "app": {"files": [{"name": "icon.png", "sha1": "a" * 40, "bundled": True}, - {"name": "bios.rom", "sha1": "b" * 40, "bundled": True}]}, - "core": {"files": [{"name": "bios.rom", "sha1": "b" * 40}]}, - } - rows = bundledonly.bundled_only(db, profiles, tmp, Path(tmp)) - self.assertEqual([row["path"] for row in rows], [str(Path(tmp, "icon.png"))]) - # A platform whose package leaves the file out brings it from the - # collection: the copy stays. - profiles["app"]["files"][0]["not_bundled_on"] = ["someplatform"] - self.assertEqual(bundledonly.bundled_only(db, profiles, tmp, Path(tmp)), []) - - def test_every_copy_of_the_listed_bytes_is_listed(self): - """The database keeps one path per content: splitwolf's sprite - folders hold one file several times and took five passes to empty.""" - import hashlib - import tempfile - - from packs import bundledonly - - with tempfile.TemporaryDirectory() as tmp: - for name in ("dir1/a.bmp", "dir2/a.bmp", "dir2/b.bmp"): - Path(tmp, name).parent.mkdir(exist_ok=True) - Path(tmp, name).write_bytes(b"same" if "a.bmp" in name else b"diff") - sha1 = hashlib.sha1(b"same").hexdigest() - row = {"sha1": sha1, "path": Path(tmp, "dir1/a.bmp").as_posix(), "size": 4, - "emulators": ["splitwolf"]} - copies = bundledonly.other_copies([row], Path(tmp)) - self.assertEqual([c["path"] for c in copies], [Path(tmp, "dir2/a.bmp").as_posix()]) - - def test_the_collection_holds_no_copy_only_an_install_provides(self): - """The pull request checks run this suite, not the pipeline: without - this, a copy only a bundled entry reaches merges green.""" - from packs import bundledonly - from model.database import load_database - from model.profiles import load_emulator_profiles - - rows = bundledonly.bundled_only( - load_database(str(ROOT / "database.json")), - load_emulator_profiles(str(ROOT / "emulators")), - str(ROOT / "platforms"), ROOT / "install", - ) - self.assertEqual([f"{r['path']} ({', '.join(r['emulators'])})" for r in rows], [], - "remove the copy: the emulator's own install provides it") - - -class TheApiSchemaHoldsTheFieldsItPromises(unittest.TestCase): - """The data page promises fields are only added within v1, and the - published schema left items unconstrained: renaming url in - file-locations.json passed validation and broke consumers silently.""" - - def test_a_renamed_field_is_refused(self): - try: - import jsonschema - except ImportError: - self.skipTest("jsonschema is tooling only") - schema = json.loads((ROOT / "schemas" / "site-api-envelope.schema.json").read_text()) - envelope = {"schema_version": 1, "generated_at": "2026-10-20T00:00:00Z", - "kind": "file-locations", "count": 1, - "items": [{"sha1": "a" * 40, "url": "https://x/y"}]} - jsonschema.validate(envelope, schema) - envelope["items"] = [{"sha1": "a" * 40, "href": "https://x/y"}] - with self.assertRaises(jsonschema.ValidationError): - jsonschema.validate(envelope, schema) - - -class AFileTheLauncherNeverOpens(unittest.TestCase): - """RetroBat hands standalone BlastEm absolute paths to its own BIOS - names, so the defaults the emulator would read (cdbios.bin) were listed - as required and missing on RetroBat although nothing there opens them.""" - - def test_unread_on_drops_the_entry_for_that_platform_only(self): - from resolve.entryscope import deliverable, unread_on - - entry = {"name": "cdbios.bin", "unread_on": ["retrobat"]} - self.assertTrue(unread_on(entry, "retrobat")) - self.assertFalse(unread_on(entry, "batocera")) - self.assertFalse(unread_on(entry, "")) - self.assertEqual(deliverable([entry], True, "retrobat"), []) - self.assertEqual(deliverable([entry], True, "batocera"), [entry]) - - def test_the_gap_report_reads_it(self): - source = script_source("verify.py") - self.assertIn('unread_on(f, config.get("_key", ""))', source) - - -class RequiredOnlyReachesDataDirectories(unittest.TestCase): - """--required-only filtered files and packed every data tree anyway: the - Required RetroArch pack still carried the 90 FreeIntv overlays, which the - core reads only with its multi-screen option and replaces by a drawn - keypad when absent (FreeIntv src/libretro.c:294-296, 350-369).""" - - def _members(self, required_only: bool) -> list[str]: - from scripts.packs import datatrees - from scripts.packs.archive import Placed - - with tempfile.TemporaryDirectory() as tmp: - for key in ("needed", "optional"): - Path(tmp, key).mkdir() - Path(tmp, key, f"{key}.bin").write_bytes(b"x") - registry = { - key: {"local_cache": str(Path(tmp, key))} - for key in ("needed", "optional") - } - systems = { - "sys": { - "data_directories": [ - {"ref": "needed", "destination": "a"}, - {"ref": "optional", "destination": "b", "required": False}, - ] - } - } - return [ - dest - for _src, dest in datatrees.data_directory_members( - systems, registry, "retroarch", "", Placed(False), - required_only=required_only, - ) - ] - - def test_an_optional_tree_leaves_the_required_pack(self): - self.assertEqual(self._members(False), ["a/needed.bin", "b/optional.bin"]) - self.assertEqual(self._members(True), ["a/needed.bin"]) - - def test_every_tree_walk_reads_the_flag(self): - source = script_source("generate_pack.py") - # The pack's walk and the manifest's, which records the flag for - # install.py --required-only. - self.assertEqual(source.count('if required_only and dd.get("required") is False:'), 1) - self.assertIn('needed = dd.get("required") is not False\n if required_only and not needed:', - source) - self.assertIn("self.placed, required_only=required_only,", source) - self.assertIn("data_refs, required_only=required_only,", source) - - def test_the_overlays_are_declared_optional(self): - retroarch = yaml.safe_load((ROOT / "platforms" / "retroarch.yml").read_text()) - trees = retroarch["systems"]["mattel-intellivision"]["data_directories"] - self.assertEqual(trees, [ - {"ref": "freeintv-overlays", "destination": "freeintv_overlays", - "required": False}, - ]) - - def test_an_alias_reads_the_trees_of_its_core(self): - """An alias is the same binary under another name. FreeIntv declared - no overlay tree while its alias freeintv_ts_overlay did, so the - emulator pack of the core itself left the overlays out.""" - profiles = { - path.stem: yaml.safe_load(path.read_text(encoding="utf-8")) - for path in (ROOT / "emulators").glob("*.yml") - } - - def trees(profile: dict) -> dict: - return { - dd["ref"]: dd.get("required", True) - for dd in profile.get("data_directories") or [] - } - - for name, profile in profiles.items(): - target = profile.get("alias_of") - if not target or target not in profiles: - continue - with self.subTest(alias=name, core=target): - self.assertEqual(trees(profile), trees(profiles[target])) - - -class InstallerJsonKindsNeverOverwriteEachOther(unittest.TestCase): - """Install manifests and target core lists are both .json. - --manifest-targets aimed at install/ replaced install/retroarch.json, the - file every installer downloads, with a target table, exit 0.""" - - def _run(self, *flags: str, held: str) -> tuple: - with tempfile.TemporaryDirectory() as tmp: - target = Path(tmp, "retroarch.json") - before = (ROOT / held).read_text(encoding="utf-8") - target.write_text(before, encoding="utf-8") - proc = subprocess.run( - [sys.executable, "scripts/generate_pack.py", *flags, - "--offline", "--output-dir", tmp], - cwd=ROOT, capture_output=True, text=True, timeout=600, - check=False, - ) - return proc, before, target.read_text(encoding="utf-8") - - def test_target_lists_refuse_a_manifest_directory(self): - proc, before, after = self._run( - "--manifest-targets", held="install/retroarch.json" - ) - self.assertEqual(proc.returncode, 1, proc.stdout + proc.stderr) - self.assertIn("holds install manifests", proc.stderr) - self.assertIn("--output-dir", proc.stderr) - self.assertEqual(after, before) - - def test_manifests_refuse_a_target_list_directory(self): - proc, before, after = self._run( - "--manifest", "--platform", "retroarch", - held="install/targets/retroarch.json", - ) - self.assertEqual(proc.returncode, 1, proc.stdout + proc.stderr) - self.assertIn("holds per-target core lists", proc.stderr) - self.assertEqual(after, before) - - -class PlatformSystemTypoGetsTheClosestNames(unittest.TestCase): - """--platform retroarch --system sony-playstaton listed the first ten - systems of the alphabet, 3do to coleco-colecovision.""" - - def test_the_hint_names_the_close_systems(self): - from scripts.packs import platformpack - - out = io.StringIO() - with tempfile.TemporaryDirectory() as tmp, \ - contextlib.redirect_stdout(out): - result = platformpack.generate_pack( - "retroarch", str(ROOT / "platforms"), {"files": {}, "indexes": {}}, - str(ROOT / "bios"), tmp, emulators_dir=str(ROOT / "emulators"), - system_filter=["sony-playstaton"], offline=True, - ) - self.assertIsNone(result) - printed = out.getvalue() - self.assertIn("Close matches: sony-playstation", printed) - self.assertIn("--platform retroarch --list-systems", printed) - self.assertNotIn("3do", printed) - - -class HashInputNamesWhatItAccepts(unittest.TestCase): - """A 12-digit value was looked up as an MD5 and reported NOT FOUND, a - SHA-256 vanished from the input, and the run said only "No valid hashes - found in input".""" - - def test_digests_are_read_by_length(self): - from scripts.packs.hashinput import parse_hash_input - - sha256 = "e3b0c44298fc1c149afbf4c8996fb92427ae41e4649b934ca495991b7852b855" - self.assertEqual(parse_hash_input(f"0x1A2B3C4D,{sha256}"), [ - ("crc32", "1a2b3c4d"), ("sha256", sha256), - ]) - self.assertEqual(parse_hash_input("a" * 29), [("md5", "a" * 29)]) - - def test_anything_else_is_refused_with_the_formats(self): - from scripts.packs.hashinput import parse_hash_file, parse_hash_input - - for raw in ("1234567890ab", "zz", "490f666e1afb15b7362b406ed1cea246,zz"): - with self.subTest(raw=raw), self.assertRaises(ValueError) as ctx: - parse_hash_input(raw) - self.assertIn("SHA-256 (64)", str(ctx.exception)) - with tempfile.TemporaryDirectory() as tmp: - listing = Path(tmp, "hashes.txt") - listing.write_text("# list\n490f666e1afb15b7362b406ed1cea246 a.bin\nb.bin\n") - with self.assertRaises(ValueError) as ctx: - parse_hash_file(str(listing)) - self.assertIn("line 3 (b.bin)", str(ctx.exception)) - - def test_a_sha256_finds_its_file(self): - from scripts.resolve.packfiles import sha1_for_hash - - db = json.loads((ROOT / "database.json").read_text(encoding="utf-8")) - sha1, entry = next( - (k, e) for k, e in db["files"].items() if e.get("sha256") - ) - self.assertEqual(sha1_for_hash("sha256", entry["sha256"], db), sha1) - self.assertEqual(sha1_for_hash("md5", entry["md5"][:29], db), sha1) - - def test_the_truth_anchors_a_sha256_only_entry(self): - """rust_dos and ares name files by sha256 alone: the truth left their - md5 empty, so md5 platforms never received them.""" - from scripts.resolve.truthsystems import _enrich_hashes - - db = {"files": {"s" * 40: {"sha1": "s" * 40, "md5": "m" * 32, "sha256": "f" * 64, - "crc32": "0badf00d", "size": 16}}, - "indexes": {"by_sha256": {"f" * 64: "s" * 40}}} - entry = {"name": "5200.rom", "sha256": "F" * 64} - _enrich_hashes(entry, db) - self.assertEqual((entry["md5"], entry["sha1"], entry["size"]), ("m" * 32, "s" * 40, 16)) - - -class ErrorsGoToStderr(unittest.TestCase): - """The lock refusal and "no pack for" went to stdout: a run redirected to - a log showed nothing on the terminal and exited 1.""" - - @staticmethod - def _leading_text(node: ast.expr) -> str: - if isinstance(node, ast.Constant) and isinstance(node.value, str): - return node.value - if isinstance(node, ast.JoinedStr) and node.values: - return ErrorsGoToStderr._leading_text(node.values[0]) - return "" - - def test_no_error_line_is_printed_to_stdout(self): - for script in ("generate_pack.py", "pipeline.py"): - tree = ast.parse(script_source(script)) - seen = 0 - for node in ast.walk(tree): - if not (isinstance(node, ast.Call) and getattr(node.func, "id", "") == "print" - and node.args): - continue - text = self._leading_text(node.args[0]) - # Detail lines under a pack's own verdict stay with it. - if not text.lstrip().startswith("ERROR") or text.startswith(" "): - continue - seen += 1 - with self.subTest(script=script, line=node.lineno): - self.assertIn("file", [k.arg for k in node.keywords]) - self.assertGreater(seen, 0, script) - - -class PipelineOutputDirIsTheOneItWrites(unittest.TestCase): - """Started from scripts/, the pipeline locked and purged scripts/dist/ - while every step, run from the repository root, wrote to dist/.""" - - def test_the_default_is_the_root_dist_wherever_the_run_starts(self): - previous = os.getcwd() - self.addCleanup(os.chdir, previous) - os.chdir(ROOT / "scripts") - self.assertEqual(runner.pack_output_dir(None), str(ROOT / "dist")) - self.assertEqual(runner.pack_output_dir("out"), str(ROOT / "scripts" / "out")) - - def test_main_resolves_it_before_the_lock(self): - source = script_source("pipeline.py") - body = source[source.index("def main("):] - self.assertLess( - body.index("args.output_dir = pack_output_dir(args.output_dir)"), - body.index("hold_artifact_lock(args.output_dir)"), - ) - - -class ToolsRunFromAnyDirectory(unittest.TestCase): - """From scripts/, verify.py and generate_pack.py ended on a - FileNotFoundError traceback about platforms/_registry.yml.""" - - def _run(self, cwd: Path, *argv: str) -> subprocess.CompletedProcess: - return subprocess.run( - [sys.executable, *argv], cwd=cwd, capture_output=True, text=True, - timeout=600, - check=False, - ) - - def test_listing_works_from_scripts(self): - for script in ("verify.py", "generate_pack.py"): - with self.subTest(script=script): - proc = self._run( - ROOT / "scripts", str(ROOT / "scripts" / script), - "--platform", "RetroArch", "--list-systems", - ) - self.assertEqual(proc.returncode, 0, proc.stderr) - self.assertNotIn("Traceback", proc.stderr) - self.assertIn("sony-playstation", proc.stdout) - - def test_a_typed_path_is_read_from_where_it_was_typed(self): - with tempfile.TemporaryDirectory() as tmp: - proc = self._run( - Path(tmp), str(ROOT / "scripts" / "generate_pack.py"), - "--manifest-targets", "--output-dir", "lists", - ) - self.assertEqual(proc.returncode, 0, proc.stderr) - self.assertTrue(Path(tmp, "lists", "retroarch.json").is_file()) - - -class SkipPacksHelpSaysWhatRuns(unittest.TestCase): - """--help said "Only regenerate DB and verify" while the run went on to - rewrite derivable.json, README.md and docs/.""" - - def test_the_help_names_the_steps_that_still_run(self): - proc = subprocess.run( - [sys.executable, "scripts/pipeline.py", "--help"], - cwd=ROOT, capture_output=True, text=True, timeout=60, check=True, - ) - text = " ".join(proc.stdout.split()) - self.assertNotIn("Only regenerate DB and verify", text) - self.assertIn("step 4e still rewrites install/games/, and steps 7 to 8b rewrite README.md " - "and the site unless --skip-docs is given", text) - self.assertNotIn("docs/", text) - - def test_every_step_it_names_is_one_it_skips(self): - from orchestrate.labels import step_number - - source = script_source("pipeline.py") - keys = re.findall(r'skip_notice\("(\w+)", "--skip-packs"\)', source) - skipped = {step_number(key) for key in keys} - self.assertEqual(skipped, {"4", "4b", "4c", "6"}) - - -class AmigaCdDriversLiveInTheExtendedRom(unittest.TestCase): - """WinUAE starts without the CD32 or CDTV extended ROM, but cd.device, - cdtv.device, cdfs.library and cdstrap are resident modules of those ROMs - and the Kickstarts carry none. Its AROS replacement stands in only for a - missing Kickstart (memory.cpp:3055-3063), so the CDTV ROM has no - fallback to downgrade its absence.""" - - def test_both_extended_roms_are_required_without_fallback(self): - profile = yaml.safe_load( - (ROOT / "emulators" / "winuae.yml").read_text(encoding="utf-8") - ) - entries = {f["name"]: f for f in profile["files"]} - for name in ("amiga-ext-310-cd32.rom", "amiga-ext-130-cdtv.rom"): - with self.subTest(name=name): - self.assertIs(entries[name]["required"], True) - self.assertNotIn("hle_fallback", entries[name]) - - -class BizHawkListsEveryDsiNandSlot(unittest.TestCase): - """FirmwareDatabase.cs:405-410 declares six DSi NAND slots, each a - placeholder hash and 251658240 + 64 bytes, and DecideNAND - (MelonDS.cs:684-706) stops a DSi load when none is set. The profile - listed DSi_Firmware.bin, a placeholder slot of the same kind, and left - the NANDs out.""" - - def test_the_six_regional_nands_are_declared(self): - profile = yaml.safe_load( - (ROOT / "emulators" / "bizhawk.yml").read_text(encoding="utf-8") - ) - entries = {f["name"]: f for f in profile["files"]} - for region_code in ("JPN", "EUR", "USA", "AUS", "CHN", "KOR"): - with self.subTest(region=region_code): - entry = entries[f"DSi_Nand_{region_code}.bin"] - self.assertEqual(entry["size"], 251658240 + 64) - self.assertIs(entry["required"], False) - self.assertNotIn("sha1", entry) - - -class CommentsSayWhy(unittest.TestCase): - """A one-line comment that names the next statement ("# Load registry", - "# Build cross-reference indexes") repeats the code. A comment that - stays says why (for, only, so, because).""" - - LABEL = re.compile( - r"^\s*# (Load|Build|Collect|Determine|Resolve|Group|Copy|Count|Append|" - r"Filter|Separate|Compute|Create|Get|Check|Generate|Write|Read|Parse|Sort)" - r"\b[^.:;,()]{0,60}$" - ) - REASON = re.compile(r"\b(for|only|so|because|if|when|unless|before|after)\b") - - def test_no_label_comment_restates_the_next_line(self): - """Three scripts were read, and 22 labels stood in 13 others.""" - tracked = subprocess.run( - ["git", "ls-files", "--", "scripts/*.py", "scripts/**/*.py", "install.py"], - cwd=ROOT, capture_output=True, text=True, check=True, - ).stdout.split() - self.assertIn("install.py", tracked) - self.assertIn("scripts/scraper/mame_parser.py", tracked) - found = [] - for name in sorted(set(tracked)): - lines = (ROOT / name).read_text(encoding="utf-8").splitlines() - for index, line in enumerate(lines): - if not self.LABEL.match(line) or self.REASON.search(line): - continue - around = (lines[index - 1].strip(), lines[index + 1].strip()) - if any(neighbour.startswith("#") for neighbour in around): - continue - if not line.startswith(" "): - continue - found.append(f"{name}:{index + 1}: {line.strip()}") - self.assertEqual(found, []) - - -class _ResponseBody(io.BytesIO): - """A body with the headers attribute urlopen's response carries.""" - - headers: dict[str, str] = {} - - -class ExternalDownloadsFollowTheRunPolicy(unittest.TestCase): - """download_external lived outside packresolve and fetched under - --offline, into the system /tmp, holding the whole body in memory.""" - - ENTRY = {"name": "ext.bin", "source_url": "https://example.invalid/ext.bin", - "sha1": hashlib.sha1(b"payload").hexdigest()} - - def setUp(self): - # tests/__init__ sets RETROBIOS_OFFLINE for the suite: these cases - # download from a mocked urlopen, so the switch is cleared here. - patcher = mock.patch.dict(os.environ, {"RETROBIOS_OFFLINE": ""}) - patcher.start() - self.addCleanup(patcher.stop) - - def _response(self, body: bytes): - stream = _ResponseBody(body) - response = mock.MagicMock() - response.__enter__.return_value = stream - response.__exit__.return_value = False - return response - - def test_offline_never_reaches_the_network(self): - from resolve import packfiles as packresolve - - with tempfile.TemporaryDirectory() as tmp, \ - mock.patch("urllib.request.urlopen") as urlopen, \ - contextlib.redirect_stdout(io.StringIO()) as out: - fetch = packresolve.download_external(self.ENTRY, f"{tmp}/x", offline=True) - self.assertIs(fetch.outcome, packresolve.ExternalOutcome.OFFLINE) - self.assertFalse(fetch.fetched) - self.assertEqual(out.getvalue(), "") - urlopen.assert_not_called() - - def test_each_failure_names_its_own_cause(self): - """Four causes came back as one False, reported as a download failure.""" - from core import forgehttp - from resolve import packfiles as packresolve - - outcome = packresolve.ExternalOutcome - with tempfile.TemporaryDirectory() as tmp: - no_hash = packresolve.download_external( - {"name": "ext.bin", "source_url": "https://example.invalid/x"}, - f"{tmp}/x", offline=False) - offline = packresolve.download_external(self.ENTRY, f"{tmp}/x", offline=True) - with mock.patch("urllib.request.urlopen", - side_effect=urllib.error.URLError("refused")), \ - mock.patch.object(forgehttp, "_sleep", lambda _s: None): - failed = packresolve.download_external(self.ENTRY, f"{tmp}/x", offline=False) - self.assertIs(no_hash.outcome, outcome.NO_HASH) - self.assertIs(offline.outcome, outcome.OFFLINE) - self.assertIs(failed.outcome, outcome.NETWORK_ERROR) - self.assertIn("offline", offline.reason) - self.assertIn("hash", no_hash.reason) - self.assertIn("refused", failed.reason) - - def test_the_run_switch_is_inherited(self): - from resolve import packfiles as packresolve - - saved = packresolve.OFFLINE - packresolve.set_offline(True) - try: - with tempfile.TemporaryDirectory() as tmp, \ - mock.patch("urllib.request.urlopen") as urlopen: - self.assertFalse(packresolve.download_external(self.ENTRY, f"{tmp}/x").fetched) - urlopen.assert_not_called() - finally: - packresolve.set_offline(saved) - - def test_the_environment_switch_holds_whatever_the_caller_passes(self): - """RETROBIOS_OFFLINE stopped release assets but not external URLs.""" - from resolve import packfiles as packresolve - - with tempfile.TemporaryDirectory() as tmp, \ - mock.patch.dict(os.environ, {"RETROBIOS_OFFLINE": "1"}), \ - mock.patch("urllib.request.urlopen") as urlopen: - self.assertFalse( - packresolve.download_external(self.ENTRY, f"{tmp}/x", offline=False).fetched) - urlopen.assert_not_called() - - def test_a_verified_body_lands_and_a_wrong_one_is_removed(self): - from resolve import packfiles as packresolve - - with tempfile.TemporaryDirectory() as tmp: - target = Path(tmp) / "x" - with mock.patch("urllib.request.urlopen", - return_value=self._response(b"payload")): - self.assertTrue( - packresolve.download_external(self.ENTRY, str(target), offline=False).fetched) - self.assertEqual(target.read_bytes(), b"payload") - target.unlink() - with mock.patch("urllib.request.urlopen", - return_value=self._response(b"other")): - fetch = packresolve.download_external(self.ENTRY, str(target), offline=False) - self.assertIs(fetch.outcome, packresolve.ExternalOutcome.MISMATCH) - self.assertFalse(target.exists()) - - def test_every_accepted_value_of_a_listed_field_verifies(self): - # A list or a comma-joined field was compared as its string form - # ("['a', 'b']"), so no body could ever match it. - from resolve import packfiles as packresolve - - good = hashlib.sha1(b"payload").hexdigest().upper() - for sha1 in (["0" * 40, good], f"{'0' * 40}, {good}"): - with self.subTest(sha1=sha1), tempfile.TemporaryDirectory() as tmp, \ - mock.patch.object(packresolve.urllib.request, "urlopen", - return_value=self._response(b"payload")): - entry = {**self.ENTRY, "sha1": sha1} - self.assertTrue( - packresolve.download_external(entry, f"{tmp}/x", offline=False).fetched) - - def test_a_transient_failure_is_retried_and_no_scratch_remains(self): - """One 503 failed the external file for the whole build.""" - from core import forgehttp - from resolve import packfiles as packresolve - - refusal = urllib.error.HTTPError(self.ENTRY["source_url"], 503, "busy", {}, None) - with tempfile.TemporaryDirectory() as tmp: - target = Path(tmp) / "x" - with mock.patch("urllib.request.urlopen", - side_effect=[refusal, self._response(b"payload")]), \ - mock.patch.object(forgehttp, "_sleep", lambda _s: None): - self.assertTrue( - packresolve.download_external(self.ENTRY, str(target), offline=False).fetched) - self.assertEqual(target.read_bytes(), b"payload") - self.assertEqual(os.listdir(tmp), ["x"]) - - def test_scratch_files_stay_in_the_repository(self): - source = script_source("generate_pack.py") - self.assertNotIn("def download_external", source) - self.assertNotIn("urlopen", source) - for call in re.findall(r"NamedTemporaryFile\(([^)]*)\)", source): - self.assertIn("dir=", call) - - -class ATargetTypoIsAnErrorInEveryTool(unittest.TestCase): - """cross_reference.py ended a mistyped --target in a traceback, and the - hint sent cross_reference and slots users to a flag they do not have.""" - - def test_each_tool_names_the_closest_target(self): - for script in ("cross_reference.py", "slots.py", "verify.py"): - with self.subTest(script=script): - proc = subprocess.run( - [sys.executable, f"scripts/{script}", "--platform", "retroarch", - "--target", "swich"], - cwd=ROOT, capture_output=True, text=True, timeout=300, - check=False, - ) - output = proc.stdout + proc.stderr - self.assertNotEqual(proc.returncode, 0) - self.assertNotIn("Traceback", output) - self.assertIn("Close matches: switch.", output) - self.assertIn("verify.py --platform retroarch --list-targets", output) - - -class AnUnknownSystemIsRefusedBeforeAnyWork(unittest.TestCase): - """generate_pack checked --system inside the build: a typo took the - output lock and refreshed every data directory, then ended on a WARNING.""" - - def test_refused_before_the_lock_and_the_refresh(self): - with tempfile.TemporaryDirectory() as tmp: - out = Path(tmp) / "never" - with mock.patch.dict(os.environ, {"RETROBIOS_OFFLINE": ""}): - proc = subprocess.run( - [sys.executable, "scripts/generate_pack.py", "--platform", "batocera", - "--system", "playstaton-nothing", "--output-dir", str(out)], - cwd=ROOT, capture_output=True, text=True, timeout=120, - check=False, - ) - self.assertEqual(proc.returncode, 2, proc.stdout + proc.stderr) - self.assertIn( - "error: --system playstaton-nothing: unknown system playstaton-nothing", - proc.stderr, - ) - self.assertFalse(out.exists()) - - def test_a_known_system_passes_the_early_check(self): - import argparse - - from model.cliargs import resolve_system_ids - - parser = argparse.ArgumentParser() - args = argparse.Namespace( - system="sony-playstation", platform="retroarch", all=False, - platforms_dir=str(ROOT / "platforms"), manifest=False, - ) - self.assertEqual(resolve_system_ids(args, parser), ["sony-playstation"]) - - -class NoArchiveRepeatsAMemberName(unittest.TestCase): - """s8k_cpu.zip held three member names twice (MAME reuses them across - two ROM_SYSTEM_BIOS of one device). Every pack build printed raw zipfile - warnings and Info-ZIP stops on an interactive replace? at extraction.""" - - def test_member_names_are_unique(self): - archives = sorted((ROOT / "bios").rglob("*.zip")) - if not archives: - self.skipTest("no archive under bios/") - repeated = [] - for path in archives: - try: - with zipfile.ZipFile(path) as zf: - names = zf.namelist() - except (zipfile.BadZipFile, OSError): - continue - if len(names) != len(set(names)): - repeated.append(str(path.relative_to(ROOT))) - self.assertEqual(repeated, []) - - -class PipelineChildrenSkipNodeCompileCache(unittest.TestCase): - """The site build's compile cache filled the 4 GB /tmp tmpfs to 3.4 GB: - every child the pipeline starts carries NODE_DISABLE_COMPILE_CACHE.""" - - def test_the_run_helper_sets_it(self): - source = script_source("pipeline.py") - self.assertIn('"NODE_DISABLE_COMPILE_CACHE": "1"', source) - - -class HiganSuperGameBoyFolderIsFree(unittest.TestCase): - """higan reads program.rom in the option's folder, SGB.sfc/, then Super - GameBoy.sfc/. bsnes, Mesen-S and ares read SGB1.sfc and SGB2.sfc as files - in the same system directory, and SuperSnes9x sgb.sfc, so a pack that only - had the first two folders never gave the higan cores a Super Game Boy.""" - - def test_each_higan_core_has_a_folder_no_core_reads_as_a_file(self): - import yaml - - file_names: set[str] = set() - for path in (ROOT / "emulators").glob("*.yml"): - document = yaml.safe_load(path.read_text(encoding="utf-8")) or {} - for entry in document.get("files") or []: - for name in [entry.get("name"), *(entry.get("aliases") or [])]: - if name: - file_names.add(str(name).casefold()) - if entry.get("path"): - file_names.add(str(entry["path"]).casefold()) - for profile in ("higan_sfc", "higan_sfc_balanced"): - document = yaml.safe_load( - (ROOT / "emulators" / f"{profile}.yml").read_text(encoding="utf-8") - ) - folders = { - str(entry["path"]).split("/", 1)[0] - for entry in document["files"] - if str(entry.get("path") or "").endswith("/program.rom") - and entry.get("system") == "nintendo-sgb" - } - with self.subTest(profile=profile): - self.assertTrue( - [f for f in folders if f.casefold() not in file_names], folders - ) - - -class ProfileNotesDescribeTheCoreAlone(unittest.TestCase): - """mednafen_pce_fast, sdlpop and x64sdl described the core by what - another profile of this directory does ("unlike beetle_pce", "unlike the - other engines in this directory"), which means nothing once the profile - is read on its own, and 21 lines shouted NOT, ALL or MUST.""" - - SHOUT = re.compile(r"\b(NOT|NEVER|ONLY|MUST|ALL|DIFFERENT)\b(?! FOUND)") - - def test_no_profile_shouts_or_compares_with_another_profile(self): - names = {path.stem.casefold() for path in (ROOT / "emulators").glob("*.yml")} - names |= {name.replace("_", "-") for name in names} - found = [] - for path in sorted((ROOT / "emulators").glob("*.yml")): - text = path.read_text(encoding="utf-8") - for number, line in enumerate(text.splitlines(), 1): - if self.SHOUT.search(line): - found.append(f"{path.stem}:{number}") - found.extend( - f"{path.stem}:{number}" - for match in re.finditer(r"\bunlike (?:the )?([\w+-]+)", line, re.I) - if match.group(1).casefold() in names - ) - self.assertEqual(found, []) - - -class Ps2BiosImagesAreFoundByContent(unittest.TestCase): - """PCSX2 and its forks scan the BIOS folder and keep the first 4 to 8 MB - image with a romdir (pcsx2/ps2/BiosTools.cpp:258-282 at f0523f8a). With - no found_by the label ps2-0230a-20080220.bin read as a name the core - opens, and the RetroDECK export added it as a required file.""" - - def test_every_ps2_image_scan_is_marked(self): - """ARMSX2's arcade scan takes 2 to 8 MB COH-H images by their EXTINFO - serial (BiosTools.cpp:366-419 at 7f914418): r27v1602f.8g read as a - name armsx2 opens on six platforms.""" - import yaml - - from resolve.entryscope import opens_by_name - - named = [] - for path in sorted((ROOT / "emulators").glob("*.yml")): - profile = yaml.safe_load(path.read_text(encoding="utf-8")) or {} - # Whatever the profile's own flags: TeknoParrot documents its - # pcsx2x6 component, whose scan is the same (BiosTools.cpp:268-291 - # at 583f0e90), and carries no agnostic flag. - named.extend( - f"{path.stem}: {entry['name']}" - for entry in profile.get("files") or [] - if ( - entry.get("min_size") in (2097152, 4194304) - and entry.get("max_size") == 8388608 - and opens_by_name(entry, profile) - ) - ) - self.assertEqual(named, []) - - -class SynthRomsAreFoundByContent(unittest.TestCase): - """dosbox-staging's libmt32emu scan identifies each file of the ROM - folder with identifyROMFile (src/midi/mt32_lasynth_model.cpp:68-91 at - fa1856c0), and the Sound Canvas plugin hashes its model folder - (Nuked-SC55-CLAP, RomLoader::Hashing). The truth read the labels as - names dosbox-staging opens, and MT32_CONTROL.ROM did not count.""" - - def test_every_synth_rom_is_marked(self): - import yaml - - from resolve.entryscope import opens_by_name - - profile = yaml.safe_load( - (ROOT / "emulators" / "dosbox-staging.yml").read_text(encoding="utf-8") - ) - named = [ - entry["name"] - for entry in profile["files"] - if str(entry.get("path", "")).startswith(("mt32-roms/", "soundcanvas-roms/")) - and opens_by_name(entry, profile) - ] - self.assertEqual(named, []) - - -class Dev9FilesAreReadFromTheWorkingDirectory(unittest.TestCase): - """DEV9 opens eeprom.dat and flash.dat by bare name (PCSX2 - pcsx2/DEV9/DEV9.cpp:144, AetherSX2 DEV9/flash.cpp:89): the working - directory, never the BIOS folder. Eight profiles left load_from unset, - so the file was packed into the BIOS folder, where nothing reads it.""" - - def test_every_dev9_file_names_the_working_directory(self): - import yaml - - unset = [] - for path in sorted((ROOT / "emulators").glob("*.yml")): - profile = yaml.safe_load(path.read_text(encoding="utf-8")) or {} - unset.extend( - f"{path.stem}: {entry['name']}" - for entry in profile.get("files") or [] - if ( - entry.get("name") in ("eeprom.dat", "flash.dat") - and "DEV9" in str(entry.get("source_ref")) - and entry.get("load_from") != "working_directory" - ) - ) - self.assertEqual(unset, []) - - -class OpenMsxSystemRomsAreFoundBySha1(unittest.TestCase): - """openMSX reaches a ROM in share/systemroms through the file pool by - SHA1 alone, a filename being looked up only beside the machine's XML - (src/memory/Rom.cc:121-170). Read as names the core opens, the labels - were added to the KNULLI and Batocera exports.""" - - def test_no_systemrom_label_reads_as_a_name(self): - import yaml - - from resolve.entryscope import opens_by_name - - profile = yaml.safe_load((ROOT / "emulators" / "openmsx.yml").read_text()) - named = [ - entry["name"] for entry in profile["files"] - if "share/systemroms/" in str(entry.get("path")) - and opens_by_name(entry, profile) - ] - self.assertEqual(named, []) - - -class TupleAnnotationsMatchTheirReturns(unittest.TestCase): - """`_by_affinity.score` gained a fifth sort key while its annotation kept - four, so the signature misread the order that sends C-Dogs' - gamecontrollerdb.txt behind a neutral copy.""" - - @staticmethod - def _own_returns(fn: ast.AST): - stack = list(ast.iter_child_nodes(fn)) - while stack: - node = stack.pop() - if isinstance(node, (ast.FunctionDef, ast.AsyncFunctionDef, ast.Lambda)): - continue - if isinstance(node, ast.Return): - yield node - stack.extend(ast.iter_child_nodes(node)) - - def test_a_fixed_tuple_annotation_counts_its_returned_values(self): - sources = sorted((ROOT / "scripts").rglob("*.py")) + [ROOT / "install.py"] - mismatched = [] - for path in sources: - for fn in ast.walk(ast.parse(path.read_text(encoding="utf-8"))): - if not isinstance(fn, (ast.FunctionDef, ast.AsyncFunctionDef)): - continue - hint = fn.returns - if not (isinstance(hint, ast.Subscript) and isinstance(hint.value, ast.Name) - and hint.value.id == "tuple"): - continue - declared = hint.slice.elts if isinstance(hint.slice, ast.Tuple) else [hint.slice] - if any(isinstance(e, ast.Constant) and e.value is Ellipsis for e in declared): - continue - for ret in self._own_returns(fn): - value = ret.value - if (isinstance(value, ast.Tuple) - and not any(isinstance(e, ast.Starred) for e in value.elts) - and len(value.elts) != len(declared)): - mismatched.append( - f"{path.relative_to(ROOT)}:{ret.lineno} " - f"{len(value.elts)} returned, {len(declared)} declared" - ) - self.assertEqual(mismatched, []) - - -class PrboomPlusCitesFullPaths(unittest.TestCase): - """prboom-plus cited gl_hires.c, e6y.c, d_client.c and g_game.c bare: - none resolves against the repository, so the page showed them as plain - code with no link, and "behind GL_DOOM and PRBOOM_DEBUG" was read as a - seventeenth citation. Each name has one path in the tree at the pin.""" - - def test_every_cited_file_has_its_directory(self): - import yaml - - from scripts.model.sourceref import source_ref_values, split_source_ref - - profile = yaml.safe_load((ROOT / "emulators" / "prboom-plus.yml").read_text(encoding="utf-8")) - refs: list[str] = [] - - def walk(node): - if isinstance(node, dict): - for key, value in node.items(): - if key == "source_ref": - refs.extend(r for _, r in source_ref_values(value)) - else: - walk(value) - elif isinstance(node, list): - for item in node: - walk(item) - - walk(profile) - parts = [p for ref in refs for p in split_source_ref(ref)] - self.assertGreater(len(parts), 40) - for part in parts: - with self.subTest(path=part.path): - self.assertIsNotNone(part.start) - self.assertTrue(part.path.startswith("prboom2/"), part.path) - - -class AutoFetchIssueBodyReadsAsWritten(unittest.TestCase): - """The --create-issues body was a template: Title Case headings, "The - following...", an exclamation mark, numbered orders to the reader, a - spaced dash, and hashes cut to 12 characters a contributor cannot - match a file against.""" - - ENTRY = {"name": "scph5501.bin", "system": "sony-playstation", - "sha1": "b056ee5a4d65937e1a3a17e1e78f3258ea49c38e", - "md5": "490f666e1afb15b7362b406ed1cea246"} - - def test_full_hashes_and_no_template_phrasing(self): - from scripts.acquire import fetch as acquire_fetch - - body = acquire_fetch.generate_issue_body([self.ENTRY], "RetroArch") - self.assertIn(f"`{self.ENTRY['sha1']}`", body) - self.assertIn(f"`{self.ENTRY['md5']}`", body) - self.assertNotIn("...", body) - self.assertNotIn("!", body) - self.assertNotRegex(body, r"(?i)the following|please| - |\bfork\b") - self.assertNotRegex(body, r"(?m)^\d+\. ") - for heading in re.findall(r"(?m)^#+ (.*)$", body): - later = [w for w in heading.split()[1:] if w != "RetroArch"] - self.assertEqual(later, [w.lower() for w in later], heading) - - def test_the_docstring_says_nothing_is_posted(self): - from scripts import auto_fetch - - self.assertNotIn("Create GitHub Issue", auto_fetch.__doc__) - self.assertIn("posts nothing", auto_fetch.__doc__) - - - -class EveryReaderOfACoreFileIsNamed(unittest.TestCase): - """A requirement two cores read is reported once, the first profile - hosting the others' claims. Whatever drops the host must not drop the - claims with it.""" - - def test_a_host_its_emulator_installs_leaves_the_others_in_the_pack(self): - from packs.gaps import _split_bundled_claims - - dsperate = {"profile": "dsperate", "name": "usrcheat.dat", "in_repo": True} - drastic = {"profile": "drastic", "name": "usrcheat.dat", "bundled": True, - "in_repo": True, "other_claims": [dsperate]} - out = _split_bundled_claims([drastic]) - self.assertEqual([(u["profile"], u.get("other_claims")) for u in out], - [("drastic", None), ("dsperate", None)]) - alone = {"profile": "drastic", "bundled": True, "other_claims": [ - {"profile": "drastic-legacy", "bundled": True}]} - self.assertEqual(_split_bundled_claims([alone]), [alone]) - - def test_a_held_file_out_of_reach_names_every_core_reading_it(self): - """harm1.wad is a release asset: a checkout without it omits the file, - and the omission named gzdoom alone where lzdoom reads it too.""" - from packs.manifestentry import claim_cores - - extra = {"source_profile": "gzdoom", "other_claims": [ - {"source_profile": "uzdoom"}, {"source_profile": "lzdoom"}]} - self.assertEqual(claim_cores(extra), ["gzdoom", "lzdoom", "uzdoom"]) - - def test_a_missing_file_names_every_core_reading_it(self): - from packs.manifestentry import record_absent - - omitted: dict[str, dict] = {} - - def record(full_dest, entry, system, reason, cores): - omitted[full_dest] = {"dest": full_dest, "reason": reason, "cores": cores} - - absent = [ - {"name": "NAPALM.GRP", "destination": "NAPALM.GRP", "source_profile": profile, - "source_system": system} - for profile, system in (("raze", "nam"), ("eduke32", "napalm")) - ] - platform = {"dest": "SHARED.BIN", "reason": "not_found", "cores": None} - omitted["SHARED.BIN"] = platform - absent.append({"name": "SHARED.BIN", "destination": "SHARED.BIN", - "source_profile": "raze"}) - record_absent(absent, {}, "", set(), False, set(), omitted, record) - self.assertEqual(omitted["NAPALM.GRP"]["cores"], ["eduke32", "raze"]) - # A platform's own omission stays the platform's. - self.assertIsNone(omitted["SHARED.BIN"]["cores"]) - - -class VerifySha1ReadsTheBuilderDigest(unittest.TestCase): - """verify_entry_sha1 accepts what the builder's sha1 comparison accepts: - a list of revisions and a padded value, which it crashed on or refused.""" - - def setUp(self): - scratch = tempfile.TemporaryDirectory(dir=Path(__file__).resolve().parents[1] / "tmp") - self.addCleanup(scratch.cleanup) - self.path = str(Path(scratch.name) / "fw.bin") - Path(self.path).write_bytes(b"bizhawk firmware") - self.sha1 = hashlib.sha1(b"bizhawk firmware").hexdigest() - - def _status(self, sha1: object) -> str: - from resolve.acceptance import frontend_digest_matches - - entry = {"name": "fw.bin", "sha1": sha1} - builder = frontend_digest_matches(entry, self.path, "sha1") - status = verdicts.verify_entry_sha1(entry, self.path)["status"] - self.assertEqual(status == verdicts.Status.OK, builder) - return status - - def test_a_list_of_revisions(self): - self.assertEqual(self._status(["0" * 40, self.sha1]), verdicts.Status.OK) - - def test_a_padded_value(self): - self.assertEqual(self._status(self.sha1.upper() + " "), verdicts.Status.OK) - - def test_another_dump(self): - self.assertEqual(self._status("0" * 40), verdicts.Status.UNTESTED) - - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_audit_resolution.py b/tests/test_audit_resolution.py new file mode 100644 index 000000000..8e7c81962 --- /dev/null +++ b/tests/test_audit_resolution.py @@ -0,0 +1,1142 @@ +"""Audit regressions on file resolution, hashing, caches and archive safety.""" + +from __future__ import annotations + +import tests +from tests.sources import script_source +import contextlib +import hashlib +import io +import json +import os +import re +import stat +import tempfile +import unittest +import zipfile +import zlib +from pathlib import Path +from unittest import mock +from packs import verdicts +from scripts.resolve.localfile import resolve_local_file +from scripts.core.ziptools import safe_extract_zip +from tests.auditsupport import ROOT + + +class AutoFetchReadsListsAndPlacesWithoutClobbering(unittest.TestCase): + """A profile hash list (daedalusx64's n64.psh) stopped auto_fetch with + an unhashable-type error, and a fetched file went to the first folder + sharing one word of the system slug (nintendo-64 into Nintendo/SNES), + overwriting a same-named file there.""" + + def test_a_hash_list_is_every_accepted_revision(self): + import hashlib + + from scripts.acquire import fetch as acquire_fetch + + data = b"second revision" + entry = {"sha1": ["0" * 40, hashlib.sha1(data).hexdigest()]} + self.assertTrue(acquire_fetch.verify_content(data, entry)) + db = {"files": {hashlib.sha1(data).hexdigest(): {"path": "bios/x/n64.psh"}}, + "indexes": {"by_md5": {}}} + self.assertEqual(acquire_fetch.step1_crossref_db(entry, db), "bios/x/n64.psh") + + @staticmethod + def _tables(system: str, folder: str) -> tuple[dict, dict]: + """Hash tables where the collection files *system* under *folder*.""" + return {"system_folders": {system: {folder}}}, {} + + def test_the_review_folder_is_used_and_nothing_is_overwritten(self): + from scripts.acquire import placement as acquire_placement + + with tempfile.TemporaryDirectory() as directory: + bios = Path(directory) + for folder in ("Nintendo/SNES", "Nintendo/N64", "Nintendo/Nintendo 64DD"): + (bios / folder).mkdir(parents=True) + held = bios / "Nintendo" / "N64" / "n64.psh" + held.write_bytes(b"other revision") + placed = Path(acquire_placement.place_file( + b"fetched", {"name": "n64.psh", "system": "nintendo-64"}, str(bios), {}, + *self._tables("nintendo-64", "bios/Nintendo/N64/"), + ).path) + self.assertEqual(placed.parent.parent, bios / "Nintendo" / "N64") + self.assertEqual(placed.parent.name, ".variants") + self.assertEqual(held.read_bytes(), b"other revision") + + def test_a_slug_inside_another_folder_name_is_no_folder(self): + """'ds' is in '3DS': the DS firmware went to Nintendo/3DS.""" + from scripts.acquire import placement as acquire_placement + + with tempfile.TemporaryDirectory() as directory: + bios = Path(directory) + for folder in ("Nintendo/3DS", "Nintendo/Nintendo DS"): + (bios / folder).mkdir(parents=True) + placed = Path(acquire_placement.place_file( + b"fw", {"name": "firmware.bin", "system": "nintendo-ds"}, str(bios), {}, + *self._tables("nintendo-ds", "bios/Nintendo/Nintendo DS/"), + ).path) + self.assertEqual(placed, bios / "Nintendo" / "Nintendo DS" / "firmware.bin") + + def test_an_unsettled_folder_stays_out_of_bios(self): + """snk-neogeo went to a new bios/Unknown/snk-neogeo/.""" + import hashlib + + from scripts.acquire import placement as acquire_placement + + with tempfile.TemporaryDirectory() as directory: + bios, acquired = Path(directory, "bios"), Path(directory, "acquire") + bios.mkdir() + placed = acquire_placement.place_file( + b"set", {"name": "neogeo.zip", "system": "snk-neogeo"}, str(bios), {}, + {}, {}, acquire_dir=acquired, + ) + self.assertTrue(placed.kept_out) + self.assertEqual(Path(placed.path), acquired / hashlib.sha1(b"set").hexdigest()) + self.assertEqual(list(bios.iterdir()), []) + + +class ResolverRegressions(unittest.TestCase): + def _database(self, entries: dict[str, Path], suffix: str | None = None) -> dict: + files = {} + by_name: dict[str, list[str]] = {} + by_suffix: dict[str, list[str]] = {} + for name, path in entries.items(): + payload = path.read_bytes() + sha1 = hashlib.sha1(payload).hexdigest() + md5 = hashlib.md5(payload).hexdigest() + sha256 = hashlib.sha256(payload).hexdigest() + files[sha1] = { + "path": str(path), + "name": name, + "size": len(payload), + "md5": md5, + "sha256": sha256, + "crc32": "00000000", + } + by_name.setdefault(name, []).append(sha1) + if suffix and name == "firmware.bin": + by_suffix.setdefault(suffix, []).append(sha1) + return { + "files": files, + "indexes": { + "by_name": by_name, + "by_md5": {entry["md5"]: sha1 for sha1, entry in files.items()}, + "by_sha256": { + entry["sha256"]: sha1 for sha1, entry in files.items() + }, + "by_crc32": {}, + "by_path_suffix": by_suffix, + }, + } + + def test_hash_identity_wins_over_wrong_destination_hint(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + wrong = root / "wrong" / "firmware.bin" + correct = root / "correct" / "firmware.bin" + wrong.parent.mkdir() + correct.parent.mkdir() + wrong.write_bytes(b"wrong") + correct.write_bytes(b"correct") + db = self._database( + {"firmware.bin": wrong, "correct-name.bin": correct}, + suffix="Console/USA/firmware.bin", + ) + expected = hashlib.sha1(b"correct").hexdigest() + path, status = resolve_local_file( + {"name": "firmware.bin", "sha1": expected}, + db, + dest_hint="Console/USA/firmware.bin", + ) + self.assertEqual(path, str(correct)) + self.assertEqual(status, "sha1_exact") + + def test_name_cannot_mask_a_declared_hash_mismatch(self): + with tempfile.TemporaryDirectory() as directory: + path = Path(directory) / "firmware.bin" + path.write_bytes(b"wrong") + db = self._database({"firmware.bin": path}) + resolved, status = resolve_local_file( + {"name": "firmware.bin", "sha1": "f" * 40}, db + ) + self.assertEqual(resolved, str(path)) + self.assertEqual(status, "hash_mismatch") + + +class ArchiveSecurityRegressions(unittest.TestCase): + def _zip_path(self, directory: Path, name: str = "archive.zip") -> Path: + return directory / name + + def test_member_count_limit_is_enforced(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + archive = self._zip_path(root) + with zipfile.ZipFile(archive, "w") as handle: + handle.writestr("one.bin", b"1") + handle.writestr("two.bin", b"2") + with self.assertRaisesRegex(ValueError, "members"): + safe_extract_zip(str(archive), str(root / "out"), max_members=1) + + def test_member_modes_follow_the_archive_and_the_umask(self): + """Every member came out 0600, the mode of its temporary file: the + pico8 and vox launchers the RetroDECK pack keeps 0755 lost their + execute bit once download.py extracted them.""" + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + archive = self._zip_path(root) + program = zipfile.ZipInfo("pico8") + program.create_system = 3 + program.external_attr = (stat.S_IFREG | 0o755) << 16 + plain = zipfile.ZipInfo("bios.bin") + plain.create_system = 0 + plain.external_attr = 0x20 # MS-DOS archive bit, no Unix mode + with zipfile.ZipFile(archive, "w") as handle: + handle.writestr(program, b"\x7fELF") + handle.writestr(plain, b"data") + umask = os.umask(0o022) + try: + safe_extract_zip(str(archive), str(root / "out")) + finally: + os.umask(umask) + self.assertEqual((root / "out" / "pico8").stat().st_mode & 0o777, 0o755) + self.assertEqual((root / "out" / "bios.bin").stat().st_mode & 0o777, 0o644) + + def test_symlink_member_is_rejected(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + archive = self._zip_path(root) + link = zipfile.ZipInfo("link") + link.create_system = 3 + link.external_attr = (stat.S_IFLNK | 0o777) << 16 + with zipfile.ZipFile(archive, "w") as handle: + handle.writestr(link, "target") + with self.assertRaisesRegex(ValueError, "link or special"): + safe_extract_zip(str(archive), str(root / "out")) + + def test_windows_separator_is_a_path_not_a_rejection(self): + """Archives written on Windows store a backslash separator. + + download.py feeds third-party archives to this function, so a legal + Windows path must extract into a subdirectory instead of failing. + """ + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + archive = self._zip_path(root) + with zipfile.ZipFile(archive, "w") as handle: + handle.writestr("sub\\rom.bin", b"payload") + out = root / "out" + safe_extract_zip(str(archive), str(out)) + self.assertEqual((out / "sub" / "rom.bin").read_bytes(), b"payload") + + def test_windows_separator_cannot_smuggle_traversal(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + archive = self._zip_path(root) + with zipfile.ZipFile(archive, "w") as handle: + handle.writestr("..\\escaped.bin", b"payload") + with self.assertRaisesRegex(ValueError, "traversal"): + safe_extract_zip(str(archive), str(root / "out")) + + def test_high_ratio_method_is_bounded_by_size_not_ratio(self): + """bzip2 legitimately exceeds the DEFLATE ceiling.""" + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + archive = self._zip_path(root) + with zipfile.ZipFile(archive, "w", zipfile.ZIP_BZIP2) as handle: + handle.writestr("zeros.bin", bytes(4_000_000)) + out = root / "out" + safe_extract_zip(str(archive), str(out)) + self.assertEqual((out / "zeros.bin").stat().st_size, 4_000_000) + + def test_compression_ratio_limit_is_enforced(self): + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + archive = self._zip_path(root) + with zipfile.ZipFile(archive, "w", zipfile.ZIP_DEFLATED) as handle: + handle.writestr("zeros.bin", bytes(16_384)) + with self.assertRaisesRegex(ValueError, "compression ratio"): + safe_extract_zip( + str(archive), str(root / "out"), max_compression_ratio=2 + ) + + +class NoMd5IsNotNothingChecked(unittest.TestCase): + """A declared hash that is not an md5 still contradicts. + + verify_entry_md5 returned OK the moment the entry declared no md5, so an + entry whose sha256 the local file contradicts read as covered while the + builder was already excluding it. RetroDECK's dsifirmware.bin declares a + sha256 and no md5. + """ + + def _entry(self): + return {"name": "dsifirmware.bin", "sha256": "b" * 64} + + def test_a_contradicted_sha256_is_not_reported_ok(self): + result = verdicts.verify_entry_md5( + self._entry(), "bios/whatever.bin", "hash_mismatch" + ) + self.assertNotEqual(result["status"], verdicts.Status.OK) + self.assertIn("contradicted", result.get("reason", "")) + + def test_a_clean_resolution_is_still_ok(self): + result = verdicts.verify_entry_md5( + self._entry(), "bios/whatever.bin", "sha256_exact" + ) + self.assertEqual(result["status"], verdicts.Status.OK) + + +class AnotherEmulatorsTreeProvesNothing(unittest.TestCase): + """lrps2 names no hash for pcsx2/resources/GameIndex.yaml, and the only + full-tail copy was ARMSX2's, which counted as path proof and replaced + the GameIndex RetroArch pins on desktop targets, where ARMSX2 does not + exist. Upstream PCSX2 took ARMSX2's patches.zip by name the same way.""" + + def _db(self, root, files): + import hashlib + + db = {"files": {}, "indexes": {"by_name": {}, "by_md5": {}, "by_crc32": {}, + "by_path_suffix": {}}} + for relative, payload in files.items(): + path = root / relative + path.parent.mkdir(parents=True, exist_ok=True) + path.write_bytes(payload) + sha1 = hashlib.sha1(payload).hexdigest() + db["files"][sha1] = {"path": relative, "name": path.name, "sha1": sha1, + "size": len(payload)} + db["indexes"]["by_name"].setdefault(path.name, []).append(sha1) + parts = relative.split("/") + for start in range(1, len(parts) - 1): + db["indexes"]["by_path_suffix"].setdefault( + "/".join(parts[start:]), []).append(sha1) + return db + + def test_neither_the_full_tail_nor_the_name_lands_in_a_foreign_tree(self): + from scripts.resolve.localfile import resolve_local_file + + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + # The collection's layout, read relative to its root. + previous = os.getcwd() + os.chdir(root) + self.addCleanup(os.chdir, previous) + db = self._db(root, { + "bios/Other/armsx2/pcsx2/resources/GameIndex.yaml": b"fork", + "bios/Other/armsx2/pcsx2/resources/patches.zip": b"fork patches", + "bios/Sony/PlayStation 2/patches.zip": b"upstream patches", + }) + index, status = resolve_local_file( + {"name": "GameIndex.yaml", "path": "pcsx2/resources/GameIndex.yaml", + "source_profile": "lrps2"}, + db, dest_hint="pcsx2/resources/GameIndex.yaml", + ) + # Held only in the fork's tree, the file answers by name and + # proves nothing about this entry. + self.assertEqual(status, "name_exact") + patches, _status = resolve_local_file( + {"name": "patches.zip", "path": "resources/patches.zip", + "source_profile": "pcsx2"}, + db, dest_hint="resources/patches.zip", + ) + self.assertTrue(patches.endswith("PlayStation 2/patches.zip")) + + def test_no_desktop_retroarch_pack_serves_armsx2s_tree(self): + from scripts.packs import slots + from scripts.model.registry import load_data_dir_registry + from scripts.model.database import load_database + from scripts.model.profiles import load_emulator_profiles + from scripts.model.platforms import load_platform_config + from scripts.model.targets import load_target_config + + if not (ROOT / "database.json").exists(): + self.skipTest("database.json is not generated") + db = load_database(str(ROOT / "database.json")) + config = load_platform_config("retroarch", str(ROOT / "platforms")) + profiles = load_emulator_profiles(str(ROOT / "emulators")) + cores = set(load_target_config("retroarch", "x86_64", str(ROOT / "platforms"))) + overrides = slots.pack_overrides( + config, profiles, db, None, load_data_dir_registry(str(ROOT / "platforms")), + target_cores=cores, + ) + self.assertFalse([d for d, p in overrides.items() if "/armsx2/" in p]) + + +class APinnedCoreFileTakesTheSlotFirst(unittest.TestCase): + """hypseus-singe asks for gamecontrollerdb.txt by name and took the BIOS + root of Batocera, RetroBat and RetroPie with C-Dogs' 26 KB table, where + Solarus pins its own by sha1.""" + + def test_the_content_naming_claim_is_placed_first(self): + from unittest import mock + + from scripts.packs import extras as packextras + + undeclared = [ + {"profile": "hypseus", "emulator": "hypseus", "name": "db.txt", + "path": "db.txt", "in_repo": True, "systems": ["a"]}, + {"profile": "solarus", "emulator": "solarus", "name": "db.txt", + "path": "db.txt", "in_repo": True, "systems": ["b"], "sha1": "a" * 40}, + ] + config = {"systems": {}, "base_destination": "bios"} + with mock.patch("packs.gaps.find_undeclared_files", return_value=undeclared), \ + mock.patch.object(packextras, "resolve_platform_cores", + return_value=set()) as cores: + extras = packextras.collect_emulator_extras( + config, "emulators", {"files": {}, "indexes": {}}, set(), "bios", {} + ) + self.assertEqual([e["source_profile"] for e in extras][:1], ["solarus"]) + # The stub is what ran: patched with create=True on a name the module + # imported inside the function, it was never read and the real + # resolve_platform_cores walked the repository's profiles. + cores.assert_called_once() + + +class ANameWithItsDirectoryIsTheDestination(unittest.TestCase): + """gam4980 declares gam4980/E.BIN with no path: resolved by its basename, + verify --emulator and the emulator pack took the A4980's OS while the + platform pack served the GAM4980's.""" + + def test_the_directory_in_the_name_picks_the_copy(self): + import hashlib + + from scripts.resolve.localfile import resolve_local_file + + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + previous = os.getcwd() + os.chdir(root) + self.addCleanup(os.chdir, previous) + files, by_name, by_suffix = {}, {}, {} + for relative, payload in (("bios/BBK/A4980/A4980/E.BIN", b"a4980"), + ("bios/BBK/GAM4980/gam4980/E.BIN", b"gam4980")): + Path(relative).parent.mkdir(parents=True, exist_ok=True) + Path(relative).write_bytes(payload) + sha1 = hashlib.sha1(payload).hexdigest() + files[sha1] = {"path": relative, "name": "E.BIN", "sha1": sha1} + by_name.setdefault("E.BIN", []).append(sha1) + parent = relative.split("/")[-2] + by_suffix.setdefault(f"{parent}/E.BIN", []).append(sha1) + db = {"files": files, "indexes": {"by_name": by_name, "by_md5": {}, + "by_crc32": {}, "by_path_suffix": by_suffix}} + path, status = resolve_local_file( + {"name": "gam4980/E.BIN", "source_profile": "gam4980"}, db + ) + self.assertEqual((path, status), ("bios/BBK/GAM4980/gam4980/E.BIN", "path_exact")) + + +class AnUnreadableDatabaseStopsTheScan(unittest.TestCase): + """A database.json left with merge markers read as an absent one: every + release-asset entry silently left the rewritten database, then the + manifests.""" + + def test_a_corrupt_database_is_not_an_empty_one(self): + from collection import releaseassets + + with tempfile.TemporaryDirectory() as directory: + path = Path(directory) / "database.json" + path.write_text("<<<<<<< HEAD\n{}\n") + with self.assertRaises(releaseassets.DatabaseUnreadable) as caught: + releaseassets.read_database(str(path)) + self.assertIn("is not valid JSON", str(caught.exception)) + self.assertIsNone( + releaseassets.read_database(str(Path(directory) / "absent.json")) + ) + + def test_the_build_exits_1_on_it(self): + import argparse + import io + from contextlib import redirect_stderr, redirect_stdout + from unittest import mock + + from collection import run + + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + (root / "bios").mkdir() + output = root / "database.json" + output.write_text("<<<<<<< HEAD\n{}\n") + args = argparse.Namespace( + bios_dir=str(root / "bios"), force=True, output=str(output), + offline=True, platforms_dir=str(root), emulators_dir=str(root), + provenance_dir=str(root), + ) + err = io.StringIO() + with mock.patch.object(run, "load_gitignored_large_files", + return_value={"bios/big.bin"}), \ + redirect_stdout(io.StringIO()), redirect_stderr(err): + self.assertEqual(run.generate(args), 1) + self.assertIn("is not valid JSON", err.getvalue()) + self.assertFalse((root / ".cache").exists()) + self.assertTrue(output.read_text().startswith("<<<<<<<")) + + +class TheDigestCacheBelongsToTheScannedTree(unittest.TestCase): + """The cache path was fixed on the working directory: scanning a copy + (tmp/wt/bios) replaced the repository's cache with the copy's entries, + keyed bios/... like the real ones, and the next run rehashed everything.""" + + def test_a_scan_writes_its_cache_beside_its_tree(self): + import argparse + import io + from contextlib import redirect_stderr, redirect_stdout + + from collection import hashcache, run + + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + (root / "bios" / "Sony").mkdir(parents=True) + (root / "bios" / "Sony" / "a.bin").write_bytes(b"a") + (root / "_registry.yml").write_text("platforms: {}\n") + args = argparse.Namespace( + bios_dir=str(root / "bios"), force=False, + output=str(root / "database.json"), offline=True, + platforms_dir=str(root), emulators_dir=str(root), + provenance_dir=str(root), + ) + with redirect_stdout(io.StringIO()), redirect_stderr(io.StringIO()): + self.assertEqual(run.generate(args), 0) + cache = root / ".cache" / "db_cache.json" + self.assertEqual(hashcache.cache_path(root / "bios"), str(cache)) + self.assertEqual(list(hashcache.load_cache(str(cache))), ["bios/Sony/a.bin"]) + self.assertEqual(hashcache.cache_path(Path("bios")), ".cache/db_cache.json") + + +class TheZipIndexCacheKnowsItsInputs(unittest.TestCase): + """build_zip_contents_index cached on (path, mtime) alone: a smaller + max_entry_size, or a database giving the same archive another sha1, + got the first call's index back.""" + + def test_the_bound_and_the_sha1_are_part_of_the_key(self): + from scripts.core import ziptools + + with tempfile.TemporaryDirectory() as directory: + path = Path(directory) / "a.zip" + with zipfile.ZipFile(path, "w") as archive: + archive.writestr("big.bin", b"x" * 4096) + ziptools._zip_contents_cache = None + db = {"files": {"a" * 40: {"path": str(path)}}} + self.assertEqual(len(ziptools.build_zip_contents_index(db, Path(directory))), 1) + self.assertEqual(ziptools.build_zip_contents_index(db, Path(directory), max_entry_size=10), {}) + other = {"files": {"b" * 40: {"path": str(path)}}} + self.assertEqual( + set(ziptools.build_zip_contents_index(other, Path(directory)).values()), {"b" * 40} + ) + ziptools._zip_contents_cache = None + + +class GeneratedModelsAreWrittenWhole(unittest.TestCase): + """The truth model and the cumulative MAME clone map were written by + truncate-then-write, and a corrupt clone map also read as empty and was + then overwritten, losing what earlier runs recorded.""" + + def test_both_writers_replace_their_file_atomically(self): + for module in ("generate_truth.py", "dedup.py"): + source = script_source(module) + with self.subTest(module=module): + self.assertIn("write_text_atomic(", source) + self.assertNotIn('open(out_path, "w")', source) + self.assertNotIn('open(clone_path, "w")', source) + + def test_an_unreadable_clone_map_stops_the_run(self): + from collection import dedup + + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + bios = root / "bios" + # A device clone: two archive names, the same ROMs, in MAME's tree. + (bios / "Arcade" / "MAME").mkdir(parents=True) + for name in ("set.zip", "setclone.zip"): + with zipfile.ZipFile(bios / "Arcade" / "MAME" / name, "w") as archive: + archive.writestr("rom.bin", b"rom") + data = (bios / "Arcade" / "MAME" / "set.zip").read_bytes() + (bios / "Arcade" / "MAME" / "setclone.zip").write_bytes(data) + (root / "_mame_clones.json").write_text("<<<<<<< HEAD") + from model.database import CloneMapUnreadable + + with self.assertRaises(CloneMapUnreadable): + dedup.deduplicate(str(bios), dry_run=False) + # Stopped before removing anything. + self.assertTrue((bios / "Arcade" / "MAME" / "setclone.zip").exists()) + + def test_the_pack_side_reads_the_same_bad_map_the_same_way(self): + from model import database + + with tempfile.TemporaryDirectory() as directory: + root = Path(directory) + (root / "bios").mkdir() + (root / "_mame_clones.json").write_text("<<<<<<< HEAD") + with self.assertRaises(database.CloneMapUnreadable) as caught: + database.get_mame_clone_map(str(root / "bios")) + self.assertIn("Restore it from git", str(caught.exception)) + (root / "_mame_clones.json").write_text("[]") + with self.assertRaises(database.CloneMapUnreadable): + database.get_mame_clone_map(str(root / "bios")) + + +class TheDatabaseCacheIsWrittenWhole(unittest.TestCase): + """A crash while serializing left a truncated db_cache.json behind, and + the next run rehashed the whole collection from scratch.""" + + def test_a_failed_save_keeps_the_previous_cache(self): + import json + from unittest import mock + + from collection import hashcache + + with tempfile.TemporaryDirectory() as directory: + path = os.path.join(directory, "cache", "db_cache.json") + hashcache.save_cache(path, {"a": 1}) + with mock.patch.object(json, "dumps", side_effect=TypeError("miscomputed")), \ + self.assertRaises(TypeError): + hashcache.save_cache(path, {"a": 2}) + self.assertEqual(hashcache.load_cache(path), {"a": 1}) + self.assertEqual(os.listdir(os.path.dirname(path)), ["db_cache.json"]) + + +class HashMergeBackupsAreNotSources(unittest.TestCase): + """The hash merge copies a profile to .old.yml before rewriting it. + + Every loader skipped the copy except validate_schemas, which then failed + on a stale MAME profile nobody would ever ship. + """ + + def test_the_validator_skips_a_backup(self): + try: + from schemas.sourcetree import validate_yaml_directory + except ImportError as exc: + self.skipTest(f"validate_schemas needs jsonschema: {exc}") + + with tempfile.TemporaryDirectory() as directory: + (Path(directory) / "mame.old.yml").write_text("emulator: [\n") + self.assertEqual( + validate_yaml_directory(Path(directory), "emulator.schema.json"), [] + ) + + def test_the_backup_suffix_is_written_once(self): + offenders = [ + str(path.relative_to(ROOT)) + for path in sorted(ROOT.glob("scripts/**/*.py")) + if path.relative_to(ROOT).as_posix() != "scripts/model/profiles.py" + and '".old.yml"' in path.read_text() + ] + self.assertEqual(offenders, []) + + +class AnUnreadableArchiveIsSaidOutLoud(unittest.TestCase): + """resolve_local_file skipped a ZIP it could not open without a word: a + truncated archive read as a missing dump (not_found) or a wrong one.""" + + def test_the_resolver_names_the_archive(self): + from resolve import localfile + + with tempfile.TemporaryDirectory() as tmp: + broken = Path(tmp) / "neogeo.zip" + broken.write_bytes(b"PK\x03\x04 truncated") + sha1 = hashlib.sha1(broken.read_bytes()).hexdigest() + db = {"files": {sha1: {"path": str(broken), "name": "neogeo.zip", "sha1": sha1, + "md5": "0" * 32, "size": broken.stat().st_size}}, + "indexes": {"by_name": {"neogeo.zip": [sha1]}, "by_md5": {}, + "by_crc32": {}, "by_path_suffix": {}}} + entry = {"name": "neogeo.zip", "md5": "1" * 32, "zipped_file": "sp-s2.sp1"} + stderr = io.StringIO() + with contextlib.redirect_stderr(stderr): + localfile.resolve_local_file(entry, db) + self.assertIn(f"unreadable archive {broken}", stderr.getvalue()) + + +class ADataDirectoryIsWalkedOnce(unittest.TestCase): + """Each unresolved name walked every data-directory cache again: the + resolution cost names x tree on every pack build.""" + + def test_two_lookups_share_one_walk_and_keep_its_order(self): + from resolve.datadirs import forget_data_dir_index, resolve_in_data_dirs + + with tempfile.TemporaryDirectory() as tmp: + cache = Path(tmp) / "cache" + (cache / "a").mkdir(parents=True) + (cache / "b").mkdir() + (cache / "a" / "Font.bin").write_bytes(b"1") + (cache / "b" / "font.bin").write_bytes(b"2") + (cache / "b" / "other.bin").write_bytes(b"3") + registry = {"x": {"local_cache": str(cache)}} + forget_data_dir_index() + walks = [] + real_walk = os.walk + + def counting_walk(top, *a, **k): + walks.append(top) + return real_walk(top, *a, **k) + + with mock.patch.object(os, "walk", counting_walk): + first, _ = resolve_in_data_dirs(["font.bin"], registry, + lambda _p: "name_exact") + second, _ = resolve_in_data_dirs(["other.bin"], registry, + lambda _p: "name_exact") + forget_data_dir_index() + self.assertEqual(len(walks), 1) + expected = sorted(str(p) for p in (cache / "a" / "Font.bin", cache / "b" / "font.bin")) + self.assertIn(first[0], expected) + self.assertEqual(second[0], str(cache / "b" / "other.bin")) + + +class AnAcceptedVersionIsNoCoreDiscrepancy(unittest.TestCase): + """eduke32 lists the retail and demo NWINTER.GRP under one name: the extra + carries the first, and a held demo copy is a version the code takes.""" + + PROFILE = {"files": [ + {"name": "NWINTER.GRP", "size": 9, "crc32": "00000000", + "validation": ["size", "crc32"]}, + {"name": "NWINTER.GRP", "size": 4, "crc32": "", + "validation": ["size", "crc32"]}, + ]} + + def _extra(self) -> dict: + # The shape find_undeclared_files gives a core extra: source_path + # defaults to the name when the profile declares no path. + return {"name": "NWINTER.GRP", "source_name": "NWINTER.GRP", + "source_path": "NWINTER.GRP", "source_profile": "eduke32"} + + def test_a_sibling_version_matches(self): + from scripts.packs.platformzip import _matches_an_alternative + + with tempfile.TemporaryDirectory() as tmp: + held = Path(tmp) / "NWINTER.GRP" + held.write_bytes(b"demo") + profile = json.loads(json.dumps(self.PROFILE)) + profile["files"][1]["crc32"] = f"{zlib.crc32(b'demo'):08x}" + self.assertTrue(_matches_an_alternative( + self._extra(), str(held), {"eduke32": profile})) + + def test_a_copy_no_entry_declares_still_disagrees(self): + from scripts.packs.platformzip import _matches_an_alternative + + with tempfile.TemporaryDirectory() as tmp: + held = Path(tmp) / "NWINTER.GRP" + held.write_bytes(b"other") + profile = json.loads(json.dumps(self.PROFILE)) + profile["files"][1]["crc32"] = f"{zlib.crc32(b'demo'):08x}" + self.assertFalse(_matches_an_alternative( + self._extra(), str(held), {"eduke32": profile})) + + def test_the_pack_consults_the_alternatives(self): + source = script_source("generate_pack.py") + self.assertRegex(source, r'status == "hash_mismatch" and not _matches_an_alternative\(') + + +class ADataDirectoryCopyPassesTheNameChecks(unittest.TestCase): + """The name steps over bios/ refuse a candidate outside the size or the + Adler-32 the entry's code checks, but a cache copy found by the same name + was returned without either check.""" + + def setUp(self): + self.tmp = Path(tempfile.mkdtemp()) + self.addCleanup(lambda: __import__("shutil").rmtree(self.tmp, True)) + cache = self.tmp / "cache" + cache.mkdir() + (cache / "wiitdb-pt.txt").write_bytes(b"12345") + self.registry = {"dolphin-sys": {"local_cache": str(cache)}} + self.db = {"files": {}, "indexes": {"by_name": {}, "by_md5": {}, + "by_path_suffix": {}, "by_crc32": {}}} + + def resolve(self, **fields): + entry = {"name": "wiitdb-pt.txt", **fields} + return resolve_local_file(entry, self.db, data_dir_registry=self.registry) + + def test_a_size_the_code_accepts_resolves(self): + self.assertEqual(self.resolve(size=5, validation=["size"])[1], "data_dir") + + def test_another_size_is_a_contradiction(self): + self.assertEqual(self.resolve(size=1, validation=["size"])[1], "hash_mismatch") + + def test_another_adler32_is_a_contradiction(self): + status = self.resolve(validation=["adler32"], known_hash_adler32="0xdeadbeef")[1] + self.assertEqual(status, "hash_mismatch") + + +class AMameCloneNameIsANameStep(unittest.TestCase): + """The clone fallback relaunched resolution on the bare canonical name: + an unsourceable entry and a size the code checks were both served the + parent set.""" + + def setUp(self): + self.tmp = Path(tempfile.mkdtemp()) + self.addCleanup(lambda: __import__("shutil").rmtree(self.tmp, True)) + bios = self.tmp / "bios" / "Arcade" + bios.mkdir(parents=True) + parent = bios / "parent.zip" + parent.write_bytes(b"PARENTSET") + (self.tmp / "_mame_clones.json").write_text( + json.dumps({"parent.zip": {"clones": ["clone.zip"]}}) + ) + sha1 = hashlib.sha1(parent.read_bytes()).hexdigest() + self.db = { + "bios_dir": str(self.tmp / "bios"), + "files": {sha1: {"path": str(parent), "name": "parent.zip", + "sha1": sha1, "size": 9}}, + "indexes": {"by_name": {"parent.zip": [sha1]}, "by_md5": {}, + "by_path_suffix": {}, "by_crc32": {}}, + } + + def resolve(self, **fields): + return resolve_local_file({"name": "clone.zip", **fields}, self.db) + + def test_a_clone_resolves_to_its_parent(self): + self.assertEqual(self.resolve()[1], "mame_clone") + + def test_an_unsourceable_entry_is_not_served_the_parent(self): + self.assertEqual(self.resolve(unsourceable="not held"), (None, "not_found")) + + def test_a_size_the_parent_contradicts_is_not_served(self): + self.assertEqual( + self.resolve(size=5, validation=["size"]), (None, "not_found") + ) + + +class ASameNamedMemberIsNotTheFile(unittest.TestCase): + """The gap report counted touchhle's LiberationMono-Regular.ttf as held + because idtech4a++'s extras.zip has a member of that name, another font, + while verify --emulator said missing.""" + + def test_a_declared_hash_decides_a_member_or_data_hit(self): + from scripts.packs import supplemental + + tmp = Path(tempfile.mkdtemp()) + self.addCleanup(lambda: __import__("shutil").rmtree(tmp, True)) + (tmp / "data").mkdir() + (tmp / "data" / "font.ttf").write_bytes(b"DATA FONT") + (tmp / "bios").mkdir() + with zipfile.ZipFile(tmp / "bios" / "extras.zip", "w") as zf: + zf.writestr("files/other.ttf", b"MEMBER FONT") + names = supplemental.build_supplemental_index(str(tmp / "data"), str(tmp / "bios")) + for fname, data in (("font.ttf", b"DATA FONT"), ("other.ttf", b"MEMBER FONT")): + with self.subTest(name=fname): + held = {"name": fname, "sha1": hashlib.sha1(data).hexdigest()} + other = {"name": fname, "sha1": "0" * 40} + self.assertTrue(supplemental.data_hit(fname, None, held, names)) + self.assertFalse(supplemental.data_hit(fname, None, other, names)) + self.assertTrue(supplemental.data_hit(fname, None, {"name": fname}, names)) + + +class AutoFetchAsksVerifyWhatIsMissing(unittest.TestCase): + """auto_fetch judged presence by sha1 or md5 in the database: Batocera's + pc6001.zip, checked inside the zip and held, was a target, and no core + file was ever one. 721 announced where verify saw none critical.""" + + def test_the_targets_are_verify_verdicts(self): + from scripts.acquire import fetch as acquire_fetch + from packs import coverage as packs_coverage + from packs import verdicts + + config = {"verification_mode": "md5", "systems": {"s": {"files": [ + {"name": "ok.bin", "md5": "1" * 32}, + {"name": "gone.bin", "md5": "2" * 32}, + {"name": "bad.bin", "md5": "3" * 32}, + ]}}} + result = { + "details": [ + {"system": "s", "name": "ok.bin", "status": verdicts.Status.OK}, + {"system": "s", "name": "gone.bin", "status": verdicts.Status.MISSING}, + {"system": "s", "name": "bad.bin", "status": verdicts.Status.UNTESTED}, + ], + "undeclared_files": [ + {"name": "diabdat.mpq", "in_repo": False, "required": True, + "system": "diablo", "emulator": "DevilutionX"}, + {"name": "held.bin", "in_repo": True, "required": True}, + {"name": "extra.bin", "in_repo": False, "required": False}, + # zesarux installs 128s.rom with the emulator: not a target, + # and a copy placed in bios/ fails pipeline step 4d. + {"name": "128s.rom", "in_repo": False, "required": True, + "bundled": True, "emulator": "ZEsarUX"}, + ], + } + with mock.patch.object(packs_coverage, "verify_platform", lambda c, d: result): + names = [m["name"] for m in acquire_fetch.find_missing(config, {})] + self.assertEqual(names, ["gone.bin", "bad.bin", "diabdat.mpq"]) + + +class AZipMemberIsHashedOnce(unittest.TestCase): + """check_inside_zip decompressed a member for every md5 candidate and + every step: 4 788 times for 355 members in verify --all.""" + + def test_repeated_questions_read_the_archive_once(self): + from scripts.core import ziptools + + with tempfile.TemporaryDirectory() as tmp: + archive = Path(tmp, "set.zip") + with zipfile.ZipFile(archive, "w") as zf: + zf.writestr("ROM.bin", b"abc") + good = hashlib.md5(b"abc").hexdigest() + opened = [] + real = ziptools.zipfile.ZipFile + + def counting(*args, **kwargs): + opened.append(args[0]) + return real(*args, **kwargs) + + with mock.patch.object(ziptools.zipfile, "ZipFile", counting): + answers = [ziptools.check_inside_zip(str(archive), "rom.bin", md5) + for md5 in (good, "0" * 32, good)] + self.assertEqual(answers, ["ok", "untested", "ok"]) + self.assertEqual(len(opened), 1) + + +class CompanionsComeFromADirectoryIndex(unittest.TestCase): + """_companions walked the whole database per scanned image.""" + + def test_same_answer_one_walk(self): + from scripts.packs import extrascan + + files_db = { + "a": {"path": "bios/Sony/PS2/ps2.bin", "name": "ps2.bin"}, + "b": {"path": "bios/Sony/PS2/ps2.bin.rom1", "name": "ps2.bin.rom1"}, + "c": {"path": "bios/Sony/PS2/ps2.nvm", "name": "ps2.nvm"}, + "d": {"path": "bios/Other/ps2.nvm", "name": "ps2.nvm"}, + } + found = extrascan._companions("bios/Sony/PS2/ps2.bin", "ps2.bin", {"rom1", "nvm"}, files_db) + self.assertEqual([sha1 for sha1, _ in found], ["b", "c"]) + index = extrascan._files_by_directory(files_db) + self.assertIs(extrascan._files_by_directory(files_db), index) + + +class ZippedFileMd5IsParsedOnce(unittest.TestCase): + """verify lowercased a comma md5 list, the builder and packverify did + not: an uppercase Recalbox-style md5 on a zipped_file entry was OK for + verify and a mismatch for the pack and the manifest.""" + + def test_an_uppercase_member_md5_is_accepted_everywhere(self): + import hashlib + import zipfile as zf_mod + + from scripts.resolve.acceptance import inner_rom_check + from scripts.packs.verdicts import verify_entry_md5 + + with tempfile.TemporaryDirectory() as directory: + archive = Path(directory, "x.zip") + with zf_mod.ZipFile(archive, "w") as zf: + zf.writestr("rom.bin", b"rom") + member = hashlib.md5(b"rom").hexdigest().upper() + for md5 in (member, f"{member},{'0' * 32}"): + with self.subTest(md5=md5): + entry = {"name": "x.zip", "zipped_file": "rom.bin", "md5": md5} + self.assertEqual(inner_rom_check(entry, str(archive)), "ok") + self.assertEqual( + verify_entry_md5(entry, str(archive))["status"], "ok" + ) + + def test_the_three_sites_share_the_parser(self): + for module in ("resolve/acceptance.py", "verify.py"): + source = script_source(module) + self.assertIn("parse_hash_list(", source, module) + self.assertIn("inner_rom_data_check(", script_source("packs/packhashes.py")) + + +class AHashListIsReadOneWay(unittest.TestCase): + """mesence declares four sha256 for BS-X.bin as one comma-joined string. + The resolver split it and shipped the file, but the gap report and + profile_sync looked the whole string up and called it missing.""" + + def test_every_reader_splits_the_list(self): + from scripts.packs.supplemental import declared_content + from scripts.core.hashing import parse_hash_list + from scripts.profiling.citations import entry_hashes + + a, b = "a" * 64, "B" * 64 + entry = {"name": "BS-X.bin", "sha256": f"{a}, {b}", "crc32": "0xDEADBEEF"} + self.assertEqual(parse_hash_list(entry["sha256"]), [a, b.lower()]) + self.assertEqual(declared_content(entry)["sha256"], {a, b.lower()}) + self.assertEqual(declared_content(entry)["crc32"], {"deadbeef"}) + self.assertEqual(set(entry_hashes(entry)), {a, b.lower(), "deadbeef"}) + + +@tests.ONLINE +class AnUnansweredSearchIsNotANotFound(unittest.TestCase): + """auto_fetch caught every network error and reported the file as + needing a community contribution: offline, each file became an issue + asking the public for something the tool never looked for.""" + + def _fetch(self, error): + from unittest import mock + + from scripts.acquire import fetch as acquire_fetch + + def refuse(*_args, **_kwargs): + raise error + + entry = {"name": "nowhere.bin", "system": "test-system", "sha1": "0" * 40} + db = {"files": {}, "indexes": {"by_md5": {}, "by_name": {}}} + with mock.patch("urllib.request.urlopen", refuse), \ + mock.patch.object(acquire_fetch.forgehttp, "_sleep", lambda _s: None), \ + mock.patch.object(acquire_fetch, "step2_scan_branches", lambda e: None): + return acquire_fetch.fetch_missing([entry], db, "bios") + + def test_offline_is_not_searched(self): + import urllib.error + + result = self._fetch(urllib.error.URLError("offline")) + self.assertEqual(result["still_missing"], []) + self.assertEqual(result["stats"]["errors"], 1) + + def test_a_404_everywhere_is_not_found(self): + import urllib.error + + result = self._fetch(urllib.error.HTTPError("u", 404, "missing", {}, None)) + self.assertEqual(len(result["still_missing"]), 1) + self.assertEqual(result["stats"]["errors"], 0) + + +class AutoFetchProvesEveryHashItIsGiven(unittest.TestCase): + """auto_fetch checked a download by sha1 or md5 only: RetroDECK's + dsifirmware.bin, pinned by sha256 alone, was announced as searched and + could never be accepted.""" + + DATA = b"firmware bytes" + + def test_a_sha256_proves_a_download(self): + import hashlib + + from scripts.acquire import fetch as acquire_fetch + + sha256 = {"sha256": hashlib.sha256(self.DATA).hexdigest()} + self.assertTrue(acquire_fetch.verify_content(self.DATA, sha256)) + self.assertFalse(acquire_fetch.verify_content(b"other", sha256)) + + def test_every_declared_cryptographic_hash_must_match(self): + import hashlib + + from scripts.acquire import fetch as acquire_fetch + + both = {"sha256": hashlib.sha256(self.DATA).hexdigest(), "md5": "0" * 32} + self.assertFalse(acquire_fetch.verify_content(self.DATA, both)) + both["md5"] = hashlib.md5(self.DATA).hexdigest() + self.assertTrue(acquire_fetch.verify_content(self.DATA, both)) + + def test_crc32_and_size_never_accept_a_download(self): + """A crc32 can be forged: bytes a source crafts to it would land in + bios/.""" + import urllib.request + import zlib + from unittest import mock + + from scripts.acquire import fetch as acquire_fetch + + crc = {"name": "forged.bin", "system": "test-system", + "crc32": f"{zlib.crc32(self.DATA):08X}", "size": len(self.DATA)} + self.assertFalse(acquire_fetch.verify_content(self.DATA, crc)) + self.assertFalse(acquire_fetch.verifiable(crc)) + + served = io.BytesIO(self.DATA) + with tempfile.TemporaryDirectory() as bios, \ + mock.patch.object(urllib.request, "urlopen", lambda *a, **k: served), \ + mock.patch.object(acquire_fetch, "step2_scan_branches", + lambda e: self.DATA): + result = acquire_fetch.fetch_missing([crc], {"files": {}}, bios) + self.assertEqual(list(Path(bios).rglob("*")), []) + self.assertEqual(result["stats"]["found"], 0) + self.assertEqual(result["stats"]["unverifiable"], 1) + self.assertEqual([r.outcome for r in result["records"]], ["unverifiable"]) + + def test_a_held_sha256_is_found_in_the_database(self): + from scripts.acquire import fetch as acquire_fetch + + db = {"files": {"s": {"path": "bios/x/dsi.bin", "size": 3, "sha256": "f" * 64}}, + "indexes": {"by_sha256": {"f" * 64: "s"}}} + self.assertEqual( + acquire_fetch.step1_crossref_db({"sha256": "F" * 64}, db), "bios/x/dsi.bin" + ) + + def test_a_held_file_a_declared_hash_contradicts_is_still_searched(self): + """auto_fetch printed "Found in database" for a crc32 or md5 hit whose + sha1 the entry contradicts, a file verify calls missing.""" + from scripts.acquire import fetch as acquire_fetch + + held = {"path": "bios/x/a.bin", "sha1": "c" * 40, "md5": "d" * 32, + "crc32": "deadbeef", "size": 4} + db = {"files": {"c" * 40: held}, + "indexes": {"by_crc32": {"deadbeef": "c" * 40}, "by_md5": {"d" * 32: "c" * 40}}} + find = acquire_fetch.step1_crossref_db + self.assertIsNone(find({"sha1": "a" * 40, "crc32": "deadbeef", "size": 4}, db)) + self.assertIsNone(find({"sha1": "a" * 40, "md5": "d" * 32}, db)) + self.assertIsNone(find({"crc32": "deadbeef", "size": 5}, db)) + self.assertEqual(find({"crc32": "deadbeef", "size": 4}, db), "bios/x/a.bin") + self.assertEqual(find({"md5": "d" * 29}, db), "bios/x/a.bin") + + def test_an_entry_without_a_hash_is_not_searched(self): + from unittest import mock + + from acquire import fetch as acquire_fetch + from acquire import fetchtext + + entry = {"name": "DICROM.ROM", "system": "fujitsu-fm7"} + out = io.StringIO() + with mock.patch.object(acquire_fetch, "step2_scan_branches") as branches, \ + contextlib.redirect_stdout(out): + result = fetchtext.report_fetch([entry], {"files": {}}, "bios", dry_run=True) + branches.assert_not_called() + self.assertEqual(result["stats"]["unverifiable"], 1) + self.assertNotIn("Would search", out.getvalue()) + self.assertIn("Not searched", out.getvalue()) + + +class AutoFetchIssueBodyReadsAsWritten(unittest.TestCase): + """The --create-issues body was a template: Title Case headings, "The + following...", an exclamation mark, numbered orders to the reader, a + spaced dash, and hashes cut to 12 characters a contributor cannot + match a file against.""" + + ENTRY = {"name": "scph5501.bin", "system": "sony-playstation", + "sha1": "b056ee5a4d65937e1a3a17e1e78f3258ea49c38e", + "md5": "490f666e1afb15b7362b406ed1cea246"} + + def test_full_hashes_and_no_template_phrasing(self): + from scripts.acquire import fetch as acquire_fetch + + body = acquire_fetch.generate_issue_body([self.ENTRY], "RetroArch") + self.assertIn(f"`{self.ENTRY['sha1']}`", body) + self.assertIn(f"`{self.ENTRY['md5']}`", body) + self.assertNotIn("...", body) + self.assertNotIn("!", body) + self.assertNotRegex(body, r"(?i)the following|please| - |\bfork\b") + self.assertNotRegex(body, r"(?m)^\d+\. ") + for heading in re.findall(r"(?m)^#+ (.*)$", body): + later = [w for w in heading.split()[1:] if w != "RetroArch"] + self.assertEqual(later, [w.lower() for w in later], heading) + + def test_the_docstring_says_nothing_is_posted(self): + from scripts import auto_fetch + + self.assertNotIn("Create GitHub Issue", auto_fetch.__doc__) + self.assertIn("posts nothing", auto_fetch.__doc__) + + +class VerifySha1ReadsTheBuilderDigest(unittest.TestCase): + """verify_entry_sha1 accepts what the builder's sha1 comparison accepts: + a list of revisions and a padded value, which it crashed on or refused.""" + + def setUp(self): + scratch = tempfile.TemporaryDirectory(dir=Path(__file__).resolve().parents[1] / "tmp") + self.addCleanup(scratch.cleanup) + self.path = str(Path(scratch.name) / "fw.bin") + Path(self.path).write_bytes(b"bizhawk firmware") + self.sha1 = hashlib.sha1(b"bizhawk firmware").hexdigest() + + def _status(self, sha1: object) -> str: + from resolve.acceptance import frontend_digest_matches + + entry = {"name": "fw.bin", "sha1": sha1} + builder = frontend_digest_matches(entry, self.path, "sha1") + status = verdicts.verify_entry_sha1(entry, self.path)["status"] + self.assertEqual(status == verdicts.Status.OK, builder) + return status + + def test_a_list_of_revisions(self): + self.assertEqual(self._status(["0" * 40, self.sha1]), verdicts.Status.OK) + + def test_a_padded_value(self): + self.assertEqual(self._status(self.sha1.upper() + " "), verdicts.Status.OK) + + def test_another_dump(self): + self.assertEqual(self._status("0" * 40), verdicts.Status.UNTESTED) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_audit_site.py b/tests/test_audit_site.py new file mode 100644 index 000000000..f52cebdfe --- /dev/null +++ b/tests/test_audit_site.py @@ -0,0 +1,609 @@ +"""Audit regressions on the generated site: cards, gap pages, structured data and exports.""" + +from __future__ import annotations + +import tests +from tests.sources import script_source +import contextlib +import io +import re +import sys +import unittest +from pathlib import Path +from unittest import mock +from tests.auditsupport import ROOT + + +class TheSiteCountsSlotsNotVersions(unittest.TestCase): + """raze lists every GRP its code accepts under one name: the site said + 59 files, 46 missing, where verify --emulator said 23 slots, 12 missing.""" + + def test_one_held_version_fills_the_slot(self): + from scripts.sitegen.emulatorintro import emulator_file_summary, emulator_held_line + + files = [ + {"name": "DUKE3D.GRP", "crc32": "1"}, + {"name": "DUKE3D.GRP", "crc32": "2"}, + {"name": "BLOOD.RFF", "crc32": "3"}, + ] + line = emulator_file_summary(files)[0] + self.assertIn("**2 files** (3 accepted versions)", line) + held = emulator_held_line(files, lambda f: f.get("crc32") == "2")[0] + self.assertIn("1 in repo and 1 missing", held) + + +class TheWantedPageCountsRomsetMembers(unittest.TestCase): + """The site called build_report without archive_members: the public + Wanted page asked for dumps the collection holds inside romsets.""" + + def test_members_are_read_unless_given(self): + from scripts.acquire import provenance + + calls = [] + + def members(db, root): + calls.append(db) + return {} + + with mock.patch.object(provenance, "archive_members", members): + provenance.build_report({"files": {}}, {}) + provenance.build_report({"files": {}}, {}, {}) + self.assertEqual(len(calls), 1) + + +class TheGapReportKeepsItsShape(unittest.TestCase): + """Multi-line notes fell to column 0 and read as emulator headings, a + profile without systems printed `Abuse ()`, `*` had no legend, and + --platform totals said "across all emulators".""" + + def test_layout(self): + from scripts.packs.crossreftext import print_report + + report = {"abuse": { + "emulator": "Abuse", "systems": [], "gaps": 1, "total_files": 1, + "platform_covered": 0, "gap_missing": 1, + "gap_details": [{"name": "a.spe", "required": True, "source": "missing", + "note": "first line\nsecond line"}], + }} + out = io.StringIO() + with contextlib.redirect_stdout(out): + print_report(report, "the emulators batocera runs") + text = out.getvalue() + self.assertIn("* marks a file the emulator requires", text) + self.assertIn("\nAbuse\n", text) + self.assertIn("a.spe [MISSING]: first line second line", text) + self.assertIn("across the emulators batocera runs", text) + + +class AFileToSourceIsAFileNotAName(unittest.TestCase): + """The gaps page keyed acquisition targets by name: Fallout 2's + master.dat disappeared behind Fallout 1's.""" + + def test_rows_are_keyed_by_name_and_hash(self): + source = script_source("generate_site.py") + self.assertIn('key = (g["name"], g.get("identity") or f"emulator:{emu_name}")', source) + from scripts.packs.crossrefsource import first_hash + + self.assertEqual(first_hash({"md5": ["AB", "cd"]}), "md5:ab") + self.assertEqual(first_hash({"crc32": "1", "sha1": "F" * 40}), "sha1:" + "f" * 40) + self.assertEqual(first_hash({}), "") + + +class AFileCardSaysAllItKnows(unittest.TestCase): + """Emulator pages cut a set at 10 members without their hashes, never + showed standalone_path, and gave no file an anchor to link to.""" + + def test_members_standalone_path_and_anchor(self): + from scripts.sitegen.emulatorcards import render_emulator_file + + entry = { + "name": "neogeo.zip", "path": "neogeo.zip", "category": "bios_zip", + "standalone_path": "Firmware/neogeo.zip", + "contents": [{"name": f"m{i}.bin", "size": 1024, "crc32": f"{i:08x}"} + for i in range(12)], + } + text = "\n".join(render_emulator_file( + entry, {"files": [entry]}, None, [entry], lambda f: True, "file-neogeo-zip", + )) + # The card is a heading with this id, linked by the heading's own + # permalink. + self.assertIn('

1 name', text) + self.assertNotIn("1 missing", text) + + def test_a_missing_row_links_each_entry_and_names_its_folder(self): + """The row said `N88_KNJ1.ROM | unread | yes | AmberELEC` in plain text: + neither where the list puts it nor which cores were examined.""" + from scripts.sitegen.gapproblems import render_problem_files + + problems = [{"platform": "AmberELEC", "platform_key": "amberelec", "name": "N88_KNJ1.ROM", + "status": "missing", "required": True, "reason": "", "discrepancy": "", + "category": "unread", "system": "nec-pc-88", + "destination": "bios/quasi88/N88_KNJ1.ROM"}] + text = "\n".join(render_problem_files(problems)) + self.assertIn("| [AmberELEC](platforms/amberelec.md#nec-pc-88) " + "`bios/quasi88/N88_KNJ1.ROM` |", text) + + def test_the_destination_is_the_list_entrys(self): + """AmberELEC declares hardwareconfig.xml under eighteen MSX folders: + each missing one is shown under its own, not under the first.""" + from scripts.sitegen.gaps import _verify_tally + from model.platforms import load_platform_config + + config = load_platform_config("amberelec", str(ROOT / "platforms")) + details, wanted = [], [] + for system, data in (config.get("systems") or {}).items(): + for entry in data.get("files") or []: + missing = entry["name"] in ("hardwareconfig.xml", "N88_KNJ1.ROM") + details.append({"name": entry["name"], "system": system, + "status": "missing" if missing else "ok"}) + if missing: + wanted.append(str(entry.get("destination") or entry["name"])) + coverage = {"platform": "AmberELEC", "config": config, "details": details, + "verified": 0, "untested": 0, "missing": len(wanted), "total": len(details)} + tally = _verify_tally({"amberelec": coverage}) + shown = [p["destination"] for p in tally.problems] + self.assertEqual(shown, wanted) + self.assertGreater(len(set(shown)), 2) + self.assertIn("bios/quasi88/N88_KNJ1.ROM", shown) + + def test_verify_marks_the_settled_entry(self): + from packs import platformtally + from packs import verdicts + + result = {"name": "cdibios.zip", "status": verdicts.Status.UNTESTED} + self.assertTrue(platformtally._twin_unmet(result, "arcade")) + self.assertEqual(result["settled_by"], "arcade") + + +class UnsourceableCardSaysWhy(unittest.TestCase): + """DraStic's nds_firmware_modified.bin carried an 'unsourceable' badge + and nothing else. The reason was only on the gaps page.""" + + def test_reason_and_link(self): + from scripts.sitegen.emulatorcards import render_emulator_file + + entry = {"name": "nds_firmware_modified.bin", "path": "x.bin", + "unsourceable": "written by the firmware editor, so no dump of it exists"} + text = "\n".join(render_emulator_file( + entry, {"files": [entry]}, None, [entry], lambda f: False, "file-x", + )) + self.assertIn("Not collected yet: written by the firmware editor", text) + self.assertIn("../gaps-not-collected.md", text) + self.assertNotIn("collectable", text) + + def test_the_gaps_page_names_where_a_wanted_file_is_listed(self): + """The section read "Acknowledged gaps ... (verified from source + code)" while No-Intro lists XM7's KANJI2.ROM and MAME's fm7740sx.zip + carries it: the flag only keeps a homonym out, the file is wanted.""" + from scripts.sitegen.gaps import generate_gap_analysis + + unsourced = {"name": "KANJI2.ROM", "reason": "no dump distributed", "source_ref": ""} + report = {"xm7": {"emulator": "XM7", "gaps": 0, "gap_missing": 0, "gap_bios": 0, + "unsourceable": [unsourced], "gap_details": []}} + catalogued = {"no-intro": {"missing": [{ + "name": "KANJI2.rom", + "romsets": [{"source": "mame", "archive": "fm7740sx.zip"}], + "needed_by": [{"emulator": "xm7", "name": "KANJI2.ROM", "required": True}], + }]}} + page = generate_gap_analysis( + {"xm7": {"emulator": "XM7", "files": [{"name": "KANJI2.ROM", + "unsourceable": "no dump distributed"}]}}, + {}, {"files": {}, "indexes": {}}, gap_report=report, catalogued=catalogued) + self.assertIn("## Not collected yet", page) + self.assertIn('', page) + self.assertIn("| No-Intro `KANJI2.rom`, mame `fm7740sx.zip` | yes |", page) + self.assertNotIn("Acknowledged", page) + self.assertNotIn("verified from source code", page) + + +class CollectionCardsSayWhereToGetTheFile(unittest.TestCase): + """A system page card gave the hashes, readers and provenance of + scph5501.bin and no path or link to the bytes.""" + + def test_raw_and_release_asset_urls(self): + from scripts.sitegen import cards + + cards._RELEASE_ASSET_NAMES = None + self.addCleanup(setattr, cards, "_RELEASE_ASSET_NAMES", None) + self.assertEqual( + cards.fetch_url("bios/Sony/PlayStation/scph5501.bin"), + "https://raw.githubusercontent.com/Abdess/retrobios/main/bios/Sony/PlayStation/scph5501.bin", + ) + self.assertTrue(cards.fetch_url("bios/Arcade/MAME/MAME 0.174 Arcade XML.dat").endswith( + "/releases/download/large-files/MAME.0.174.Arcade.XML.dat" + )) + + +class CollectionCardsCarryFullHashes(unittest.TestCase): + """A pasted md5 or crc32 found nothing: cards showed 12 characters of + SHA1 and MD5 (the rest in a title the search does not index) and no + CRC32 or SHA256.""" + + def test_every_hash_in_full(self): + from scripts.packs.consumers import FileConsumers + from scripts.sitegen.cards import system_file_card + + entry = {"name": "DUKE.RTS", "path": "bios/x/DUKE.RTS", "size": 10, + "sha1": "a" * 40, "md5": "9d29f9673bbdb56068acf7645c13749c", + "crc32": "504086c1", "sha256": "b" * 64} + text = "\n".join(system_file_card(entry, FileConsumers({}, {}))) + for value in (entry["sha1"], entry["md5"], entry["crc32"], entry["sha256"]): + self.assertIn(f'
{value}
', text) + + +class AHeldRevisionLinksItsBuildFile(unittest.TestCase): + """advanced_drastic's page printed the KNULLI build file that holds its + revision as plain text, while pin_build carries the repository, the tag + and the path a pinned link needs. 36 profiles carry one.""" + + def test_the_build_file_row(self): + from scripts.sitegen.emulatorcards import build_rows + + rows = build_rows({"pin_frozen": "KNULLI builds this revision.", "pin_build": [{ + "platform": "knulli", "repo": "https://github.com/knulli-cfw/knulli-linux", + "revision": "20260511", "path": "package/emulators/advanced_drastic/advanced_drastic.mk", + "variable": "ADVANCED_DRASTIC_VERSION", "value": "eaf41ab9"}]}) + # A tag can move: named, never linked. + self.assertIn( + "| Build file | KNULLI `package/emulators/advanced_drastic/advanced_drastic.mk` " + "at `20260511` sets `ADVANCED_DRASTIC_VERSION` |", rows) + + def test_a_build_read_at_a_recorded_commit_links(self): + from scripts.sitegen.emulatorcards import build_rows + + pin = "46128cd252cdecae852a4d0bafa2aaf9d03ab563" + rows = build_rows({"pin_build": [{ + "platform": "retropie", "repo": "https://github.com/RetroPie/RetroPie-Setup", + "revision": pin, "path": "scriptmodules/emulators/advmame-1.4.sh", + "variable": "rp_module_repo", "value": "x"}]}) + self.assertIn( + f"[RetroPie `scriptmodules/emulators/advmame-1.4.sh`](https://github.com/RetroPie/" + f"RetroPie-Setup/blob/{pin}/scriptmodules/emulators/advmame-1.4.sh)", rows[0]) + + def test_the_record_holds_the_build_files(self): + from sitegen import sources as sitegen_sources + + files = sitegen_sources.build_files({"pin_build": [ + {"repo": "https://github.com/o/r", "revision": "a" * 40, "path": "p.mk"}, + {"repo": "https://github.com/o/r", "revision": "v1", "path": "q.mk"}]}) + self.assertEqual([(f[1], f[2]) for f in files], [("a" * 40, "p.mk")]) + + +class AVariantCardSaysWhatToSaveItAs(unittest.TestCase): + """The Download button of a .variants/ card saved advision.zip.1c086064, + the storage name, and nothing said RetroBat looks for advision.zip.""" + + def test_the_name_to_save_it_under(self): + from scripts.packs.consumers import FileConsumers + from scripts.sitegen.cards import system_file_card + + entry = {"name": "advision.zip", "size": 10, "sha1": "a" * 40, + "path": "bios/Entex/Adventure Vision/.variants/advision.zip.1c086064"} + text = "\n".join(system_file_card(entry, FileConsumers({}, {}))) + self.assertIn("Save as", text) + self.assertIn("advision.zip.1c086064", text) + plain = "\n".join(system_file_card( + {**entry, "path": "bios/Entex/Adventure Vision/advision.zip"}, FileConsumers({}, {}))) + self.assertNotIn("Save as", plain) + + +class NullReadsAsNone(unittest.TestCase): + """`upstream: ~` printed `| Upstream | None |` and `bios_filename: null` + printed `bios_filename: None`: a stated "there is none" read as a gap.""" + + def test_page_and_values(self): + from scripts.sitegen.fields import _plain_value + from scripts.sitegen.emulatorpage import generate_emulator_page + + self.assertEqual(_plain_value(None), "none") + page = generate_emulator_page( + "own", {"emulator": "Own", "type": "standalone", "source": "https://x/own", + "upstream": None, "core_version": None, "files": []}, + {"files": {}, "indexes": {}}, + ) + self.assertNotIn("None", page) + self.assertIn("none: the source is the project itself", page) + + def test_the_rendered_site_has_no_python_none(self): + from tests import sitepages + + pattern = re.compile(r"\| None \||: None$|: None \|", re.M) + found = [sitepages.name(p) for p in sitepages.pages() + if pattern.search(p.read_text(encoding="utf-8"))] + self.assertEqual(found, []) + + +class EmulatorCardsLinkTheCopyAndTheSection(unittest.TestCase): + """Dolphin's IPL.bin (GC/USA) read "in repo" without naming the copy, + did not link its collection card, and its platform links landed on the + page top instead of the GameCube section.""" + + def test_copy_and_sections(self): + from types import SimpleNamespace + + from scripts.sitegen.emulatorcards import CardSources, render_emulator_file + + sha1 = "ef9194ab4804aa0aa8540d846caf291b28331165" + consumers = SimpleNamespace( + sha1_of=lambda entry, dest="", owner="": sha1, + path_of=lambda value: "bios/Nintendo/GameCube/GC/USA/IPL.bin", + platforms={sha1: {"batocera"}}, + platform_systems={sha1: {"batocera": {"nintendo-gamecube"}}}, + ) + entry = {"name": "IPL.bin", "path": "GC/USA/IPL.bin"} + text = "\n".join(render_emulator_file( + entry, {"files": [entry]}, CardSources(consumers), [entry], lambda f: True, "file-ipl", "dolphin", + )) + self.assertIn("../systems/nintendo.md#sha1-ef9194ab4804", text) + self.assertIn("../platforms/batocera.md#nintendo-gamecube", text) + + +class VersionAnchorsFollowContent(unittest.TestCase): + """raze's nine DUKE3D.GRP were anchored -1 to -9 by declaration rank: a + version declared before another moved every later link to another + edition.""" + + @staticmethod + def _anchors(files): + from scripts.sitegen.emulatorpage import generate_emulator_page + + page = generate_emulator_page( + "raze", {"emulator": "Raze", "type": "standalone", "files": files}, + {"files": {}, "indexes": {}}, + ) + return re.findall(r'

`") + self.assertEqual(span.count("`"), 2) + self.assertTrue(span.startswith("`") and span.endswith("`")) + + +class TheDatasetDescribesItsDownloads(unittest.TestCase): + """data.md was a Dataset named "Data & API" with no distribution, + licence, date or creator: nothing a dataset harvester could index.""" + + def test_distribution_licence_and_date(self): + from scripts.sitegen.structured import dataset_structured_data + + exports = [{"title": "Content database", "url": "api/v1/database.json", + "media_type": "application/json", "bytes": 10, "sha256": "ab" * 32}] + data = dataset_structured_data(exports, {"generated_at": "2026-10-18T07:00:00Z"}) + self.assertEqual(data["dateModified"], "2026-10-18") + self.assertIn("MIT", data["license"]) + (download,) = data["distribution"] + self.assertEqual(download["@type"], "DataDownload") + self.assertTrue(download["contentUrl"].endswith("/api/v1/database.json")) + self.assertEqual(download["sha256"], "ab" * 32) + self.assertNotEqual(data["name"], "Data & API") + + +class SystemPagesDescribeTheirFiles(unittest.TestCase): + """systems/* published a generic TechArticle: no file, hash or + provenance for the pages that carry a card per file.""" + + def test_parts_carry_hashes_anchor_and_provenance(self): + from scripts.sitegen.structured import system_structured_data + + entry = {"name": "scph5501.bin", "sha1": "0555c6fae8906f3f09baf5988f00e55f88e9f30b", + "md5": "490f666e1afb15b7362b406ed1cea246", "crc32": "8d8cb7e4", "size": 524288, + "provenance": {"redump": {"dat": "Sony - PlayStation - BIOS Images", + "name": "ps-30a.bin"}}} + (part,) = system_structured_data("sony", {"PlayStation": [entry]})["hasPart"] + self.assertTrue(part["url"].endswith("systems/sony/#sha1-0555c6fae890")) + self.assertIn("md5:490f666e1afb15b7362b406ed1cea246", part["identifier"]) + self.assertIn("redump: Sony - PlayStation - BIOS Images (ps-30a.bin)", part["citation"]) + + def test_a_huge_page_lists_its_verified_files_and_points_at_the_table(self): + from scripts.sitegen.structured import SYSTEM_PARTS_IN_FULL, system_structured_data + + plain = [{"name": f"f{i}", "sha1": f"{i:040x}"} for i in range(SYSTEM_PARTS_IN_FULL)] + cited = {"name": "v", "sha1": "f" * 40, + "provenance": {"tosec": {"dat": "d", "name": "n"}}} + data = system_structured_data("engines", {"x": [*plain, cited]}) + self.assertEqual([p["name"] for p in data["hasPart"]], ["v"]) + self.assertTrue(data["isBasedOn"].endswith("downloads/files.csv")) + + +class TheCollectionShipsADat(unittest.TestCase): + """The exports had JSON, CSV and SQLite and no DAT, the one format + clrmamepro and RomVault read: auditing a BIOS tree meant writing a + converter from files.csv.""" + + def test_round_trip_through_the_logiqx_parser(self): + sys.path.insert(0, str(ROOT / "scripts" / "scraper")) + from logiqx_parser import parse_logiqx + from scripts.sitegen.structured import collection_dat + + db = {"files": { + "a" * 40: {"path": "bios/Sony/PlayStation/scph5501.bin", "size": 4, + "crc32": "8D8CB7E4", "md5": "1" * 32, "sha1": "a" * 40}, + "b" * 40: {"path": "bios/Nintendo/GameCube/GC/USA/IPL.bin", "size": 8, + "crc32": "00000001", "md5": "2" * 32, "sha1": "b" * 40}, + }} + dat = parse_logiqx(collection_dat(db, "2026-10-18T07:00:00Z")) + self.assertEqual(dat.version, "20261018") + roms = {(r.game, r.name): r for r in dat.roms} + # The set name is the subfolder a copy of bios/ holds: named + # "Sony - PlayStation", clrmamepro looked beside Sony/ for it. + self.assertIn(("Sony\\PlayStation", "scph5501.bin"), roms) + self.assertIn(("Nintendo\\GameCube", "GC\\USA\\IPL.bin"), roms) + self.assertEqual(roms[("Sony\\PlayStation", "scph5501.bin")].crc32, "8d8cb7e4") + + def test_each_setup_has_a_dat_of_its_installed_folder(self): + """A Batocera user auditing share/bios against the collection DAT met + thousands of sets laid out by manufacturer, and nothing of the folder + Batocera reads.""" + sys.path.insert(0, str(ROOT / "scripts" / "scraper")) + from logiqx_parser import parse_logiqx + from scripts.sitegen.platformfiles import platform_data_links + from scripts.sitegen.structured import platform_dat + + db = {"files": {"a" * 40: {"size": 4, "crc32": "8D8CB7E4", "md5": "1" * 32, + "sha1": "a" * 40}}} + manifest = { + "platform": "batocera", "display_name": "Batocera", "base_destination": "bios", + "files": [{"dest": "dc/naomi2.zip", "sha1": "a" * 40, "size": 4}, + {"dest": "saves/x.bin", "sha1": "a" * 40, "size": 4, "root": "save"}], + "data_directories": [{"dest": "dolphin-emu/Sys", + "files": {"GC/font.bin": {"sha1": "c" * 40, "size": 2}}}], + } + dat = parse_logiqx(platform_dat(manifest, db, {"c" * 40: {"md5": "3" * 32}}, + "2026-11-05T00:00:00Z")) + roms = {(r.game, r.name): r for r in dat.roms} + self.assertEqual(set(roms), {("bios", "dc\\naomi2.zip"), + ("bios", "dolphin-emu\\Sys\\GC\\font.bin")}) + self.assertEqual(roms[("bios", "dc\\naomi2.zip")].md5, "1" * 32) + self.assertEqual(roms[("bios", "dolphin-emu\\Sys\\GC\\font.bin")].md5, "3" * 32) + self.assertIn("[DAT](../downloads/dat/batocera.dat)", platform_data_links("batocera")) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_e2e.py b/tests/test_e2e.py deleted file mode 100644 index 67f32228e..000000000 --- a/tests/test_e2e.py +++ /dev/null @@ -1,7245 +0,0 @@ -"""End-to-end regression test. - -ONE test scenario with YAML fixtures covering ALL code paths. -Run: python -m unittest tests.test_e2e -v - -Covers: - Resolution: SHA1, MD5, name, alias, truncated MD5, md5_composite, - zip_contents, .variants deprio, not_found, hash_mismatch - Verification: existence mode, md5 mode, required/optional, - zipped_file (match/mismatch/missing inner), multi-hash - Severity: all combos per platform mode - Platform config: inheritance, shared groups, data_directories, grouping - Pack: storage tiers (external/user_provided/embedded), dedup, large file cache - Cross-reference: undeclared files, standalone skipped, alias profiles skipped, - data_dir suppresses gaps -""" - -from __future__ import annotations - -import tests -from tests.sources import script_source - -import contextlib -import hashlib -import io -import os -import shutil -import sys -import tempfile -import unittest -import zipfile -from pathlib import Path -from unittest import mock - -from model import largefiles -import yaml -from core.ziptools import build_zip_contents_index, check_inside_zip, safe_extract_zip -from core.hashing import compute_hashes, md5_composite, parse_hash_list -from model.declarations import expand_platform_declared_names -from resolve.grouping import group_identical_platforms -from model.profiles import ProfileSelectionError, load_emulator_profiles -from model.platforms import load_platform_config -from resolve.localfile import resolve_local_file -from resolve.cores import resolve_platform_cores -from resolve.platformdiff import diff_platform_truth -from resolve.truth import generate_platform_truth -from resolve.validation import build_validation_index, check_file_validation -from resolve.entryscope import filter_files_by_mode -from packs.verdicts import Severity, Status -from packs.gaps import find_exclusion_notes, find_undeclared_files -from packs.emulatorcheck import verify_emulator -from packs.coverage import verify_platform - -try: - import jsonschema -except ImportError: - jsonschema = None -HAS_JSONSCHEMA = jsonschema is not None - - -def _h(data: bytes) -> dict: - """Return sha1, md5, crc32 for test data.""" - return { - "sha1": hashlib.sha1(data).hexdigest(), - "md5": hashlib.md5(data).hexdigest(), - "crc32": format(hashlib.new("crc32", data).digest()[0], "08x") - if False - else "", # not needed for tests - } - - -class TestE2E(unittest.TestCase): - """Single end-to-end scenario exercising every code path.""" - - # --------------------------------------------------------------- - # Fixture setup - # --------------------------------------------------------------- - - def setUp(self): - # Clear emulator profile cache to avoid stale data between tests - from model.profiles import emulator_profiles_cache - - emulator_profiles_cache.clear() - - self.root = tempfile.mkdtemp() - self.bios_dir = os.path.join(self.root, "bios") - self.platforms_dir = os.path.join(self.root, "platforms") - self.emulators_dir = os.path.join(self.root, "emulators") - os.makedirs(self.bios_dir) - os.makedirs(self.platforms_dir) - os.makedirs(self.emulators_dir) - - # -- Create synthetic BIOS files -- - self.files = {} - self._make_file("present_req.bin", b"PRESENT_REQUIRED") - self._make_file("present_opt.bin", b"PRESENT_OPTIONAL") - self._make_file("correct_hash.bin", b"CORRECT_HASH_DATA") - self._make_file("wrong_hash.bin", b"WRONG_CONTENT_ON_DISK") - self._make_file("no_md5.bin", b"NO_MD5_CHECK") - self._make_file("truncated.bin", b"BATOCERA_TRUNCATED") - self._make_file("alias_target.bin", b"ALIAS_FILE_DATA") - self._make_file( - "leading_zero_crc.bin", b"LEADING_ZERO_CRC_12" - ) # crc32=0179e92e - - # Regional variant files (same name, different content, in subdirs) - os.makedirs(os.path.join(self.bios_dir, "TestConsole", "USA"), exist_ok=True) - os.makedirs(os.path.join(self.bios_dir, "TestConsole", "EUR"), exist_ok=True) - self._make_file("BIOS.bin", b"BIOS_USA_CONTENT", subdir="TestConsole/USA") - self._make_file("BIOS.bin", b"BIOS_EUR_CONTENT", subdir="TestConsole/EUR") - - # .variants/ file (should be deprioritized) - variants_dir = os.path.join(self.bios_dir, ".variants") - os.makedirs(variants_dir) - self._make_file("present_req.bin", b"VARIANT_DATA", subdir=".variants") - - # ZIP with correct inner ROM - self._make_zip("good.zip", {"inner.rom": b"GOOD_INNER_ROM"}) - # ZIP with wrong inner ROM - self._make_zip("bad_inner.zip", {"inner.rom": b"BAD_INNER"}) - # ZIP with missing inner ROM name - self._make_zip("missing_inner.zip", {"other.rom": b"OTHER_ROM"}) - # ZIP for md5_composite (Recalbox) - self._make_zip("composite.zip", {"b.rom": b"BBBB", "a.rom": b"AAAA"}) - # ZIP for multi-hash - self._make_zip("multi.zip", {"rom.bin": b"MULTI_HASH_DATA"}) - # Archive BIOS ZIP (like neogeo.zip) containing multiple ROMs - self._make_zip( - "test_archive.zip", - { - "rom_a.bin": b"ARCHIVE_ROM_A", - "rom_b.bin": b"ARCHIVE_ROM_B", - }, - ) - - # -- Build synthetic database -- - self.db = self._build_db() - - # -- Create platform YAMLs -- - self._create_existence_platform() - self._create_md5_platform() - self._create_shared_groups() - self._create_inherited_platform() - self._create_sha1_platform() - - # -- Create emulator YAMLs -- - self._create_emulator_profiles() - - def tearDown(self): - shutil.rmtree(self.root) - - # --------------------------------------------------------------- - # File helpers - # --------------------------------------------------------------- - - def _make_file(self, name: str, data: bytes, subdir: str = "") -> str: - d = os.path.join(self.bios_dir, subdir) if subdir else self.bios_dir - os.makedirs(d, exist_ok=True) - path = os.path.join(d, name) - with open(path, "wb") as f: - f.write(data) - h = _h(data) - self.files[f"{subdir}/{name}" if subdir else name] = { - "path": path, - "data": data, - **h, - } - return path - - def _make_zip(self, name: str, contents: dict[str, bytes]) -> str: - path = os.path.join(self.bios_dir, name) - with zipfile.ZipFile(path, "w") as zf: - for fname, data in contents.items(): - zf.writestr(fname, data) - with open(path, "rb") as f: - zdata = f.read() - h = _h(zdata) - inner_md5s = {fn: hashlib.md5(d).hexdigest() for fn, d in contents.items()} - self.files[name] = {"path": path, "data": zdata, "inner_md5s": inner_md5s, **h} - return path - - def _build_db(self) -> dict: - files_db = {} - by_md5 = {} - by_name: dict[str, list[str]] = {} - for key, info in self.files.items(): - name = os.path.basename(key) - sha1 = info["sha1"] - files_db[sha1] = { - "path": info["path"], - "md5": info["md5"], - "name": name, - "crc32": info.get("crc32", ""), - "size": len(info["data"]), - } - by_md5[info["md5"]] = sha1 - by_name.setdefault(name, []).append(sha1) - # Add alias name to by_name - alias_sha1 = self.files["alias_target.bin"]["sha1"] - by_name.setdefault("alias_alt.bin", []).append(alias_sha1) - # Build by_path_suffix for regional variant resolution - by_path_suffix: dict[str, list[str]] = {} - for key, info in self.files.items(): - if "/" in key: - # key is subdir/name, suffix is the subdir path - by_path_suffix.setdefault(key, []).append(info["sha1"]) - return { - "files": files_db, - "indexes": { - "by_md5": by_md5, - "by_name": by_name, - "by_crc32": {}, - "by_path_suffix": by_path_suffix, - }, - } - - # --------------------------------------------------------------- - # Platform YAML creators - # --------------------------------------------------------------- - - def _create_existence_platform(self): - config = { - "platform": "TestExistence", - "version": "9.1", - "verification_mode": "existence", - "base_destination": "system", - "systems": { - "console-a": { - "files": [ - { - "name": "present_req.bin", - "destination": "present_req.bin", - "required": True, - }, - { - "name": "missing_req.bin", - "destination": "missing_req.bin", - "required": True, - }, - { - "name": "present_opt.bin", - "destination": "present_opt.bin", - "required": False, - }, - { - "name": "missing_opt.bin", - "destination": "missing_opt.bin", - "required": False, - }, - ], - }, - }, - } - with open(os.path.join(self.platforms_dir, "test_existence.yml"), "w") as fh: - yaml.dump(config, fh) - - def _create_md5_platform(self): - f = self.files - good_inner_md5 = f["good.zip"]["inner_md5s"]["inner.rom"] - bad_inner_md5 = "deadbeefdeadbeefdeadbeefdeadbeef" - composite_md5 = hashlib.md5( - b"AAAA" + b"BBBB" - ).hexdigest() # sorted: a.rom, b.rom - multi_wrong = "0000000000000000000000000000000" - multi_right = f["multi.zip"]["inner_md5s"]["rom.bin"] - truncated_md5 = f["truncated.bin"]["md5"][:29] # shorter than 32 characters - - config = { - "platform": "TestMD5", - "verification_mode": "md5", - "systems": { - "sys-md5": { - "includes": ["test_shared"], - "files": [ - # Correct hash - { - "name": "correct_hash.bin", - "destination": "correct_hash.bin", - "md5": f["correct_hash.bin"]["md5"], - "required": True, - }, - # Wrong hash on disk ->untested - { - "name": "wrong_hash.bin", - "destination": "wrong_hash.bin", - "md5": "ffffffffffffffffffffffffffffffff", - "required": True, - }, - # No MD5 ->OK (existence within md5 platform) - { - "name": "no_md5.bin", - "destination": "no_md5.bin", - "required": False, - }, - # Missing required - { - "name": "gone_req.bin", - "destination": "gone_req.bin", - "md5": "abcd", - "required": True, - }, - # Missing optional - { - "name": "gone_opt.bin", - "destination": "gone_opt.bin", - "md5": "abcd", - "required": False, - }, - # zipped_file correct - { - "name": "good.zip", - "destination": "good.zip", - "md5": good_inner_md5, - "zipped_file": "inner.rom", - "required": True, - }, - # zipped_file wrong inner - { - "name": "bad_inner.zip", - "destination": "bad_inner.zip", - "md5": bad_inner_md5, - "zipped_file": "inner.rom", - "required": False, - }, - # zipped_file inner not found - { - "name": "missing_inner.zip", - "destination": "missing_inner.zip", - "md5": "abc", - "zipped_file": "nope.rom", - "required": False, - }, - # md5_composite (Recalbox) - { - "name": "composite.zip", - "destination": "composite.zip", - "md5": composite_md5, - "required": True, - }, - # Multi-hash comma-separated (Recalbox) - { - "name": "multi.zip", - "destination": "multi.zip", - "md5": f"{multi_wrong},{multi_right}", - "zipped_file": "rom.bin", - "required": True, - }, - # MD5 shorter than 32 characters - { - "name": "truncated.bin", - "destination": "truncated.bin", - "md5": truncated_md5, - "required": True, - }, - # Same destination from different entry ->worst status wins - { - "name": "correct_hash.bin", - "destination": "dedup_target.bin", - "md5": f["correct_hash.bin"]["md5"], - "required": True, - }, - { - "name": "correct_hash.bin", - "destination": "dedup_target.bin", - "md5": "wrong_for_dedup_test", - "required": True, - }, - ], - "data_directories": [ - {"ref": "test-data-dir", "destination": "TestData"}, - ], - }, - "sys-renamed": { - "files": [ - { - "name": "renamed_file.bin", - "destination": "renamed_file.bin", - "md5": f["correct_hash.bin"]["md5"], - "required": True, - }, - ], - }, - }, - } - with open(os.path.join(self.platforms_dir, "test_md5.yml"), "w") as fh: - yaml.dump(config, fh) - - def _create_shared_groups(self): - shared = { - "shared_groups": { - "test_shared": [ - { - "name": "shared_file.rom", - "destination": "shared_file.rom", - "required": False, - }, - ], - }, - } - with open(os.path.join(self.platforms_dir, "_shared.yml"), "w") as fh: - yaml.dump(shared, fh) - - def _create_inherited_platform(self): - child = { - "inherits": "test_existence", - "platform": "TestInherited", - "base_destination": "BIOS", - } - with open(os.path.join(self.platforms_dir, "test_inherited.yml"), "w") as fh: - yaml.dump(child, fh) - - def _create_sha1_platform(self): - f = self.files - config = { - "platform": "TestSHA1", - "verification_mode": "sha1", - "base_destination": "system", - "systems": { - "sys-sha1": { - "files": [ - { - "name": "correct_hash.bin", - "destination": "correct_hash.bin", - "sha1": f["correct_hash.bin"]["sha1"], - "required": True, - }, - { - "name": "wrong_hash.bin", - "destination": "wrong_hash.bin", - "sha1": "aaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaaa", - "required": True, - }, - { - "name": "missing_sha1.bin", - "destination": "missing_sha1.bin", - "sha1": "bbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbbb", - "required": True, - }, - { - "name": "optional_missing_sha1.bin", - "destination": "optional_missing_sha1.bin", - "sha1": "cccccccccccccccccccccccccccccccccccccccc", - "required": False, - }, - { - "name": "no_md5.bin", - "destination": "no_md5.bin", - "required": True, - }, - ], - }, - }, - } - with open(os.path.join(self.platforms_dir, "test_sha1.yml"), "w") as fh: - yaml.dump(config, fh) - - def _create_emulator_profiles(self): - # Regular emulator with aliases, standalone file, undeclared file - emu = { - "emulator": "TestEmu", - "type": "standalone + libretro", - "systems": ["console-a", "sys-md5"], - "data_directories": [{"ref": "test-data-dir"}], - "files": [ - {"name": "present_req.bin", "required": True}, - { - "name": "alias_target.bin", - "required": False, - "aliases": ["alias_alt.bin"], - }, - { - "name": "standalone_only.bin", - "required": False, - "mode": "standalone", - }, - {"name": "undeclared_req.bin", "required": True}, - {"name": "undeclared_opt.bin", "required": False}, - ], - } - with open(os.path.join(self.emulators_dir, "test_emu.yml"), "w") as fh: - yaml.dump(emu, fh) - - # Emulator with HLE fallback - emu_hle = { - "emulator": "TestHLE", - "type": "libretro", - "systems": ["console-a"], - "files": [ - {"name": "present_req.bin", "required": True, "hle_fallback": True}, - {"name": "hle_missing.bin", "required": True, "hle_fallback": True}, - {"name": "no_hle_missing.bin", "required": True, "hle_fallback": False}, - ], - } - with open(os.path.join(self.emulators_dir, "test_hle.yml"), "w") as fh: - yaml.dump(emu_hle, fh) - - # Launcher profile (should be excluded from cross-reference) - launcher = { - "emulator": "TestLauncher", - "type": "launcher", - "systems": ["console-a"], - "files": [{"name": "launcher_bios.bin", "required": True}], - } - with open(os.path.join(self.emulators_dir, "test_launcher.yml"), "w") as fh: - yaml.dump(launcher, fh) - - # Alias profile (should be skipped) - alias = { - "emulator": "TestAlias", - "type": "alias", - "alias_of": "test_emu", - "files": [], - } - with open(os.path.join(self.emulators_dir, "test_alias.yml"), "w") as fh: - yaml.dump(alias, fh) - - # Emulator with data_dir that matches platform ->gaps suppressed - emu_dd = { - "emulator": "TestEmuDD", - "type": "libretro", - "systems": ["sys-md5"], - "data_directories": [{"ref": "test-data-dir"}], - "files": [ - {"name": "dd_covered.bin", "required": False}, - ], - } - with open(os.path.join(self.emulators_dir, "test_emu_dd.yml"), "w") as fh: - yaml.dump(emu_dd, fh) - - # Emulator with archived files (like FBNeo with neogeo.zip) - emu_archive = { - "emulator": "TestArchiveEmu", - "type": "libretro", - "systems": ["console-a"], - "files": [ - {"name": "rom_a.bin", "required": True, "archive": "test_archive.zip"}, - {"name": "rom_b.bin", "required": False, "archive": "test_archive.zip"}, - { - "name": "missing_rom.bin", - "required": True, - "archive": "missing_archive.zip", - }, - ], - } - with open(os.path.join(self.emulators_dir, "test_archive_emu.yml"), "w") as fh: - yaml.dump(emu_archive, fh) - - # Emulator with descriptive name and path (like QEMU SeaBIOS) - emu_descriptive = { - "emulator": "TestDescriptive", - "type": "libretro", - "systems": ["console-a"], - "files": [ - { - "name": "Descriptive BIOS Name", - "required": True, - "path": "present_req.bin", - }, - { - "name": "Missing Descriptive", - "required": True, - "path": "nonexistent_path.bin", - }, - ], - } - with open(os.path.join(self.emulators_dir, "test_descriptive.yml"), "w") as fh: - yaml.dump(emu_descriptive, fh) - - # Emulator with validation checks (size, crc32) - emu_val = { - "emulator": "TestValidation", - "type": "libretro", - "systems": ["console-a", "sys-md5"], - "files": [ - # Size validation: correct size (16 bytes = len(b"PRESENT_REQUIRED")) - { - "name": "present_req.bin", - "required": True, - "validation": ["size"], - "size": 16, - "source_ref": "test.c:10-20", - }, - # Size validation: wrong expected size - { - "name": "present_opt.bin", - "required": False, - "validation": ["size"], - "size": 9999, - }, - # CRC32 validation: correct crc32 - { - "name": "correct_hash.bin", - "required": True, - "validation": ["crc32"], - "crc32": "91d0b1d3", - "source_ref": "hash.c:42", - }, - # CRC32 validation: wrong crc32 - { - "name": "no_md5.bin", - "required": False, - "validation": ["crc32"], - "crc32": "deadbeef", - }, - # CRC32 starting with '0' (regression: lstrip("0x") bug) - { - "name": "leading_zero_crc.bin", - "required": True, - "validation": ["crc32"], - "crc32": "0179e92e", - }, - # MD5 validation: correct md5 - { - "name": "correct_hash.bin", - "required": True, - "validation": ["md5"], - "md5": "4a8db431e3b1a1acacec60e3424c4ce8", - }, - # SHA1 validation: correct sha1 - { - "name": "correct_hash.bin", - "required": True, - "validation": ["sha1"], - "sha1": "a2ab6c95c5bbd191b9e87e8f4e85205a47be5764", - }, - # MD5 validation: wrong md5 - { - "name": "alias_target.bin", - "required": False, - "validation": ["md5"], - "md5": "0000000000000000000000000000dead", - }, - # Adler32: known_hash_adler32 field - { - "name": "present_req.bin", - "required": True, - "known_hash_adler32": None, - }, # placeholder, set below - # Min/max size range validation - { - "name": "present_req.bin", - "required": True, - "validation": ["size"], - "min_size": 10, - "max_size": 100, - }, - # Signature: crypto check we can't reproduce, but size applies - { - "name": "correct_hash.bin", - "required": True, - "validation": ["size", "signature"], - "size": 17, - }, - ], - } - # Compute the actual adler32 of present_req.bin for the test fixture - import zlib as _zlib - - with open(self.files["present_req.bin"]["path"], "rb") as _f: - _data = _f.read() - _adler = format(_zlib.adler32(_data) & 0xFFFFFFFF, "08x") - # Set the adler32 entry (the one with known_hash_adler32=None) - for entry in emu_val["files"]: - if ( - entry.get("known_hash_adler32") is None - and "known_hash_adler32" in entry - ): - entry["known_hash_adler32"] = f"0x{_adler}" - break - with open(os.path.join(self.emulators_dir, "test_validation.yml"), "w") as fh: - yaml.dump(emu_val, fh) - - # Emulator A: declares present_req.bin at root (no path) - emu_root = { - "emulator": "TestRootCore", - "type": "libretro", - "systems": ["console-a"], - "files": [ - {"name": "present_req.bin", "required": True}, - ], - } - with open(os.path.join(self.emulators_dir, "test_root_core.yml"), "w") as fh: - yaml.dump(emu_root, fh) - - # Emulator B: declares same file at a subdirectory path - emu_subdir = { - "emulator": "TestSubdirCore", - "type": "libretro", - "systems": ["console-a"], - "files": [ - { - "name": "present_req.bin", - "required": True, - "path": "subcore/bios/present_req.bin", - }, - ], - } - with open(os.path.join(self.emulators_dir, "test_subdir_core.yml"), "w") as fh: - yaml.dump(emu_subdir, fh) - - # Emulator whose file is declared by platform under a different name - # (e.g. gsplus ROM vs Batocera ROM1): hash-based matching should resolve - emu_renamed = { - "emulator": "TestRenamed", - "type": "standalone", - "systems": ["sys-renamed"], - "files": [ - {"name": "correct_hash.bin", "required": True}, - ], - } - with open(os.path.join(self.emulators_dir, "test_renamed.yml"), "w") as fh: - yaml.dump(emu_renamed, fh) - - # Agnostic profile (bios_mode: agnostic), skipped by find_undeclared_files - emu_agnostic = { - "emulator": "TestAgnostic", - "type": "standalone", - "bios_mode": "agnostic", - "systems": ["console-a"], - "files": [ - { - "name": "correct_hash.bin", - "required": True, - "min_size": 1, - "max_size": 999999, - }, - ], - } - with open(os.path.join(self.emulators_dir, "test_agnostic.yml"), "w") as fh: - yaml.dump(emu_agnostic, fh) - - # Mixed profile with per-file agnostic - emu_mixed_agnostic = { - "emulator": "TestMixedAgnostic", - "type": "libretro", - "systems": ["console-a"], - "files": [ - {"name": "undeclared_req.bin", "required": True}, - {"name": "agnostic_file.bin", "required": True, "agnostic": True}, - ], - } - with open( - os.path.join(self.emulators_dir, "test_mixed_agnostic.yml"), "w" - ) as fh: - yaml.dump(emu_mixed_agnostic, fh) - - # --------------------------------------------------------------- - # THE TEST: one method per feature area, all using same fixtures - # --------------------------------------------------------------- - - def test_01_resolve_sha1(self): - entry = { - "name": "present_req.bin", - "sha1": self.files["present_req.bin"]["sha1"], - } - path, status = resolve_local_file(entry, self.db) - self.assertEqual(status, "sha1_exact") - self.assertIn("present_req.bin", path) - - def test_02_resolve_md5(self): - entry = { - "name": "correct_hash.bin", - "md5": self.files["correct_hash.bin"]["md5"], - } - path, status = resolve_local_file(entry, self.db) - self.assertEqual(status, "md5_exact") - - def test_03_resolve_name_no_md5(self): - entry = {"name": "no_md5.bin"} - path, status = resolve_local_file(entry, self.db) - self.assertEqual(status, "name_exact") - - def test_04_resolve_alias(self): - entry = {"name": "alias_alt.bin", "aliases": []} - path, status = resolve_local_file(entry, self.db) - self.assertEqual(status, "name_exact") - self.assertIn("alias_target.bin", path) - - def test_05_resolve_truncated_md5(self): - truncated = self.files["truncated.bin"]["md5"][:29] - entry = {"name": "truncated.bin", "md5": truncated} - path, status = resolve_local_file(entry, self.db) - self.assertEqual(status, "md5_exact") - - def test_06_resolve_not_found(self): - entry = {"name": "nonexistent.bin", "sha1": "0" * 40} - path, status = resolve_local_file(entry, self.db) - self.assertIsNone(path) - self.assertEqual(status, "not_found") - - def test_07_resolve_hash_mismatch(self): - entry = {"name": "wrong_hash.bin", "md5": "ffffffffffffffffffffffffffffffff"} - path, status = resolve_local_file(entry, self.db) - self.assertEqual(status, "hash_mismatch") - - def test_07b_resolve_unsourceable_ignores_homonym(self): - """An unsourceable entry takes content, never a file of the same name.""" - entry = { - "name": "wrong_hash.bin", - "md5": "ffffffffffffffffffffffffffffffff", - "unsourceable": "ships inside a paid application package", - } - path, status = resolve_local_file(entry, self.db) - self.assertIsNone(path) - self.assertEqual(status, "not_found") - - entry = {"name": "no_md5.bin", "unsourceable": "written per title"} - path, status = resolve_local_file(entry, self.db) - self.assertIsNone(path) - self.assertEqual(status, "not_found") - - # Collecting the real bytes still resolves it. - entry = { - "name": "present_req.bin", - "sha1": self.files["present_req.bin"]["sha1"], - "unsourceable": "ships inside a paid application package", - } - path, status = resolve_local_file(entry, self.db) - self.assertEqual(status, "sha1_exact") - self.assertIn("present_req.bin", path) - - def test_08_resolve_variants_deprioritized(self): - entry = {"name": "present_req.bin"} - path, status = resolve_local_file(entry, self.db) - self.assertNotIn(".variants", path) - - def test_09_resolve_zip_contents(self): - zc = build_zip_contents_index(self.db, Path(self.root)) - inner_md5 = self.files["good.zip"]["inner_md5s"]["inner.rom"] - entry = {"name": "good.zip", "md5": inner_md5, "zipped_file": "inner.rom"} - path, status = resolve_local_file(entry, self.db, zc) - # Should find via name match (hash_mismatch since container md5 != inner md5) - # then zip_contents would be fallback - self.assertIsNotNone(path) - - def test_10_md5_composite(self): - expected = hashlib.md5(b"AAAA" + b"BBBB").hexdigest() - actual = md5_composite(self.files["composite.zip"]["path"]) - self.assertEqual(actual, expected) - - def test_11_check_inside_zip_match(self): - inner_md5 = self.files["good.zip"]["inner_md5s"]["inner.rom"] - r = check_inside_zip(self.files["good.zip"]["path"], "inner.rom", inner_md5) - self.assertEqual(r, "ok") - - def test_12_check_inside_zip_mismatch(self): - r = check_inside_zip(self.files["bad_inner.zip"]["path"], "inner.rom", "wrong") - self.assertEqual(r, "untested") - - def test_20b_agnostic_core_fills_existence_slots(self): - """An agnostic core on the platform serves a missing slot, as the pack does.""" - config = load_platform_config("test_existence", self.platforms_dir) - result = verify_platform(config, self.db, self.emulators_dir) - c = result["severity_counts"] - self.assertEqual(c[Severity.OK], result["total_files"]) - - def test_13_check_inside_zip_not_found(self): - r = check_inside_zip(self.files["missing_inner.zip"]["path"], "nope.rom", "abc") - self.assertEqual(r, "not_in_zip") - - def test_14_check_inside_zip_casefold(self): - inner_md5 = self.files["good.zip"]["inner_md5s"]["inner.rom"] - r = check_inside_zip(self.files["good.zip"]["path"], "INNER.ROM", inner_md5) - self.assertEqual(r, "ok") - - def test_20_verify_existence_platform(self): - config = load_platform_config("test_existence", self.platforms_dir) - # Without the filename-agnostic core, which would serve the two - # missing slots under existence (test_20b covers that case). - profiles = { - k: v for k, v in load_emulator_profiles(self.emulators_dir).items() - if v.get("bios_mode") != "agnostic" - } - result = verify_platform(config, self.db, self.emulators_dir, emu_profiles=profiles) - c = result["severity_counts"] - total = result["total_files"] - # 2 present (1 req + 1 opt), 2 missing (1 req WARNING + 1 opt INFO) - self.assertEqual(c[Severity.OK], 2) - self.assertEqual(c[Severity.WARNING], 1) # required missing - self.assertEqual(c[Severity.INFO], 1) # optional missing - self.assertEqual(sum(c.values()), total) - - def test_21_verify_md5_platform(self): - config = load_platform_config("test_md5", self.platforms_dir) - result = verify_platform(config, self.db, self.emulators_dir) - c = result["severity_counts"] - total = result["total_files"] - self.assertEqual(sum(c.values()), total) - # At least some OK and some non-OK - self.assertGreater(c[Severity.OK], 0) - self.assertGreater(total, c[Severity.OK]) - - def test_22_verify_required_propagated(self): - config = load_platform_config("test_md5", self.platforms_dir) - result = verify_platform(config, self.db, self.emulators_dir) - for d in result["details"]: - self.assertIn("required", d) - - def test_23_verify_missing_required_is_critical(self): - config = load_platform_config("test_md5", self.platforms_dir) - result = verify_platform(config, self.db, self.emulators_dir) - c = result["severity_counts"] - self.assertGreater(c[Severity.CRITICAL], 0) - - def test_24_verify_missing_optional_is_warning(self): - config = load_platform_config("test_md5", self.platforms_dir) - result = verify_platform(config, self.db, self.emulators_dir) - c = result["severity_counts"] - self.assertGreater(c[Severity.WARNING], 0) - - def test_24b_a_held_group_member_makes_the_others_optional(self): - """RetroBat's group: one file held is enough (batocera-systems/Program.cs).""" - from model.platforms import _platform_config_cache - - with open(os.path.join(self.platforms_dir, "test_md5.yml")) as fh: - config = yaml.safe_load(fh) - held_md5 = next( - f["md5"] for f in config["systems"]["sys-renamed"]["files"] - ) - config["systems"] = { - "sys-group": {"files": [ - {"name": "correct_hash.bin", "destination": "g/held.bin", - "md5": held_md5, "required": True, "group": "one"}, - {"name": "absent_alt.bin", "destination": "g/absent_alt.bin", - "md5": "0" * 32, "required": True, "group": "one"}, - {"name": "absent_a.bin", "destination": "g/absent_a.bin", - "md5": "1" * 32, "required": True, "group": "none"}, - {"name": "absent_b.bin", "destination": "g/absent_b.bin", - "md5": "2" * 32, "required": True, "group": "none"}, - ]}, - } - with open(os.path.join(self.platforms_dir, "grouped_md5.yml"), "w") as fh: - yaml.dump(config, fh) - _platform_config_cache.clear() - result = verify_platform( - load_platform_config("grouped_md5", self.platforms_dir), self.db, self.emulators_dir - ) - by_name = {d["name"]: d for d in result["details"]} - self.assertEqual(by_name["correct_hash.bin"]["status"], Status.OK) - self.assertIs(by_name["absent_alt.bin"]["required"], False) - self.assertIs(by_name["absent_a.bin"]["required"], True) - self.assertIs(by_name["absent_b.bin"]["required"], True) - self.assertEqual(result["severity_counts"][Severity.CRITICAL], 2) - - def test_25_verify_sha1_platform(self): - config = load_platform_config("test_sha1", self.platforms_dir) - result = verify_platform(config, self.db, self.emulators_dir) - self.assertEqual(result["total_files"], 5) - self.assertEqual(result["verification_mode"], "sha1") - ok_count = result["severity_counts"][Severity.OK] - self.assertEqual(ok_count, 2) - - def test_26_sha1_mismatch_is_warning(self): - config = load_platform_config("test_sha1", self.platforms_dir) - result = verify_platform(config, self.db, self.emulators_dir) - by_name = {d["name"]: d for d in result["details"]} - self.assertEqual(by_name["wrong_hash.bin"]["status"], Status.UNTESTED) - - def test_27_sha1_missing_required_is_critical(self): - config = load_platform_config("test_sha1", self.platforms_dir) - result = verify_platform(config, self.db, self.emulators_dir) - c = result["severity_counts"] - self.assertGreater(c[Severity.CRITICAL], 0) - - def test_28_sha1_missing_optional_is_warning(self): - config = load_platform_config("test_sha1", self.platforms_dir) - result = verify_platform(config, self.db, self.emulators_dir) - c = result["severity_counts"] - self.assertGreater(c[Severity.WARNING], 0) - - def test_29_sha1_no_hash_is_existence_check(self): - config = load_platform_config("test_sha1", self.platforms_dir) - result = verify_platform(config, self.db, self.emulators_dir) - by_name = {d["name"]: d for d in result["details"]} - self.assertEqual(by_name["no_md5.bin"]["status"], Status.OK) - - def test_30_inheritance_inherits_systems(self): - config = load_platform_config("test_inherited", self.platforms_dir) - self.assertEqual(config["platform"], "TestInherited") - self.assertEqual(config["base_destination"], "BIOS") - self.assertIn("console-a", config["systems"]) - - def test_31_shared_groups_injected(self): - config = load_platform_config("test_md5", self.platforms_dir) - names = [f["name"] for f in config["systems"]["sys-md5"]["files"]] - self.assertIn("shared_file.rom", names) - - def test_40_cross_ref_finds_undeclared(self): - config = load_platform_config("test_existence", self.platforms_dir) - profiles = load_emulator_profiles(self.emulators_dir) - undeclared = find_undeclared_files( - config, self.emulators_dir, self.db, profiles - ) - names = {u["name"] for u in undeclared} - self.assertIn("undeclared_req.bin", names) - self.assertIn("undeclared_opt.bin", names) - - def test_41_cross_ref_skips_standalone(self): - config = load_platform_config("test_existence", self.platforms_dir) - profiles = load_emulator_profiles(self.emulators_dir) - undeclared = find_undeclared_files( - config, self.emulators_dir, self.db, profiles - ) - names = {u["name"] for u in undeclared} - self.assertNotIn("standalone_only.bin", names) - - def test_42_cross_ref_skips_alias_profiles(self): - profiles = load_emulator_profiles(self.emulators_dir) - self.assertNotIn("test_alias", profiles) - - def test_42b_profile_hash_fields_load_as_str(self): - """Unquoted digit-only hashes must load as strings, not YAML ints.""" - with tempfile.TemporaryDirectory() as tmp: - Path(tmp, "numcrc.yml").write_text( - "emulator: NumCRC\n" - "type: libretro\n" - "files:\n" - " - name: kernal.bin\n" - " crc32: 70295038\n" - " md5: [12345678901234567890123456789012]\n" - ) - profiles = load_emulator_profiles(tmp) - entry = profiles["numcrc"]["files"][0] - self.assertEqual(entry["crc32"], "70295038") - self.assertEqual(entry["md5"], ["12345678901234567890123456789012"]) - - def test_43_cross_ref_data_dir_does_not_suppress_files(self): - config = load_platform_config("test_md5", self.platforms_dir) - profiles = load_emulator_profiles(self.emulators_dir) - undeclared = find_undeclared_files( - config, self.emulators_dir, self.db, profiles - ) - names = {u["name"] for u in undeclared} - # dd_covered.bin is a file entry, not data_dir content: still undeclared - self.assertIn("dd_covered.bin", names) - - def test_44_cross_ref_skips_launchers(self): - config = load_platform_config("test_existence", self.platforms_dir) - profiles = load_emulator_profiles(self.emulators_dir) - undeclared = find_undeclared_files( - config, self.emulators_dir, self.db, profiles - ) - names = {u["name"] for u in undeclared} - # launcher_bios.bin from TestLauncher should NOT appear - self.assertNotIn("launcher_bios.bin", names) - - def test_45_hle_fallback_downgrades_severity(self): - """Missing file with hle_fallback=true ->INFO severity, not CRITICAL.""" - from packs.verdicts import Severity, compute_severity - - # required + missing + NO HLE = CRITICAL - sev = compute_severity("missing", True, "md5", hle_fallback=False) - self.assertEqual(sev, Severity.CRITICAL) - # required + missing + HLE = INFO - sev = compute_severity("missing", True, "md5", hle_fallback=True) - self.assertEqual(sev, Severity.INFO) - # required + missing + HLE + existence mode = INFO - sev = compute_severity("missing", True, "existence", hle_fallback=True) - self.assertEqual(sev, Severity.INFO) - - def test_46_hle_index_built_from_emulator_profiles(self): - """verify_platform reads hle_fallback from emulator profiles.""" - config = load_platform_config("test_existence", self.platforms_dir) - profiles = load_emulator_profiles(self.emulators_dir) - result = verify_platform(config, self.db, self.emulators_dir, profiles) - # present_req.bin has hle_fallback: true in TestHLE profile - for d in result["details"]: - if d["name"] == "present_req.bin": - self.assertTrue(d.get("hle_fallback", False)) - break - - def test_47_cross_ref_shows_hle_on_undeclared(self): - """Undeclared files include hle_fallback from emulator profile.""" - config = load_platform_config("test_existence", self.platforms_dir) - profiles = load_emulator_profiles(self.emulators_dir) - undeclared = find_undeclared_files( - config, self.emulators_dir, self.db, profiles - ) - hle_files = {u["name"] for u in undeclared if u.get("hle_fallback")} - self.assertIn("hle_missing.bin", hle_files) - - def test_50_platform_grouping_identical(self): - groups = group_identical_platforms( - ["test_existence", "test_inherited"], self.platforms_dir - ) - # With flat ZIPs, base_destination no longer separates groups - # Platforms with same files (regardless of base_dest) are grouped - self.assertEqual(len(groups), 1) - self.assertEqual(len(groups[0][0]), 2) - - def test_51_platform_grouping_same(self): - # Create two identical platforms - for name in ("dup_a", "dup_b"): - config = { - "platform": name, - "verification_mode": "existence", - "systems": { - "s": {"files": [{"name": "x.bin", "destination": "x.bin"}]} - }, - } - with open(os.path.join(self.platforms_dir, f"{name}.yml"), "w") as fh: - yaml.dump(config, fh) - groups = group_identical_platforms(["dup_a", "dup_b"], self.platforms_dir) - self.assertEqual(len(groups), 1) - self.assertEqual(len(groups[0][0]), 2) - - def test_52_platform_grouping_splits_on_cores(self): - """Same baseline, different emulators: the core files differ.""" - declared = { - "cores_all": "all_libretro", - "cores_all_too": "all_libretro", - "cores_listed": ["retroarch", "openmsx"], - } - for name, cores in declared.items(): - config = { - "platform": name, - "verification_mode": "existence", - "cores": cores, - "systems": { - "s": {"files": [{"name": "x.bin", "destination": "x.bin"}]} - }, - } - with open(os.path.join(self.platforms_dir, f"{name}.yml"), "w") as fh: - yaml.dump(config, fh) - groups = group_identical_platforms(list(declared), self.platforms_dir) - self.assertEqual( - sorted(sorted(group) for group, _rep in groups), - [["cores_all", "cores_all_too"], ["cores_listed"]], - ) - - def test_60_storage_external(self): - from resolve.packfiles import resolve_file - - entry = {"name": "large.pup", "storage": "external"} - path, status = resolve_file(entry, self.db, self.bios_dir) - self.assertIsNone(path) - self.assertEqual(status, "external") - - def test_61_storage_user_provided(self): - from resolve.packfiles import resolve_file - - entry = {"name": "user.bin", "storage": "user_provided"} - path, status = resolve_file(entry, self.db, self.bios_dir) - self.assertIsNone(path) - self.assertEqual(status, "user_provided") - - def test_resolve_cores_all_libretro(self): - """all_libretro resolves to all libretro-type profiles, excludes alias/standalone.""" - config = {"cores": "all_libretro", "systems": {"nes": {"files": []}}} - profiles = { - "fceumm": {"type": "libretro", "systems": ["nes"], "files": []}, - "dolphin_standalone": { - "type": "standalone", - "systems": ["gc"], - "files": [], - }, - "gambatte": {"type": "pure_libretro", "systems": ["gb"], "files": []}, - "mednafen_psx_hw": {"type": "alias", "alias_of": "beetle_psx", "files": []}, - } - result = resolve_platform_cores(config, profiles) - self.assertEqual(result, {"fceumm", "gambatte"}) - - def test_a_build_a_platform_compiles_is_reached_by_name(self): - """Recalbox compiles libretro/mame at 0.258 and 0.278, but the buildbot - RetroArch installs from does not, so all_libretro must not reach - them while a platform naming them does.""" - profiles = { - "mame": {"type": "standalone + libretro", "systems": ["arcade"], "files": []}, - "mame0278": {"type": "libretro", "built_by": ["recalbox"], - "cores": ["mame0278"], "systems": ["arcade"], "files": []}, - } - everyone = {"cores": "all_libretro", "systems": {}} - self.assertEqual(resolve_platform_cores(everyone, profiles), {"mame"}) - retroarch_plus = {"cores": ["retroarch"], "systems": {}} - self.assertEqual(resolve_platform_cores(retroarch_plus, profiles), {"mame"}) - recalbox = {"cores": ["mame0278"], "systems": {}} - self.assertEqual(resolve_platform_cores(recalbox, profiles), {"mame0278"}) - - def test_a_platform_s_own_libretro_build_comes_with_its_retroarch(self): - """ROCKNIX ships yabadabadoo with its RetroArch and names it nowhere - else: a list naming retroarch takes the libretro builds whose - built_by names that platform, and no other platform's.""" - profiles = { - "yabause": {"type": "libretro", "systems": ["saturn"], "files": []}, - "yabadabadoo": {"type": "libretro", "built_by": ["rocknix"], - "systems": ["saturn"], "files": []}, - } - rocknix = {"_key": "rocknix", "cores": ["retroarch"], "systems": {}} - self.assertEqual(resolve_platform_cores(rocknix, profiles), - {"yabause", "yabadabadoo"}) - other = {"_key": "batocera", "cores": ["retroarch"], "systems": {}} - self.assertEqual(resolve_platform_cores(other, profiles), {"yabause"}) - everyone = {"_key": "retroarch", "cores": "all_libretro", "systems": {}} - self.assertEqual(resolve_platform_cores(everyone, profiles), {"yabause"}) - - def test_resolve_cores_explicit_list(self): - """Explicit cores list matches against profile dict keys.""" - config = {"cores": ["fbneo", "opera"], "systems": {"arcade": {"files": []}}} - profiles = { - "fbneo": {"type": "pure_libretro", "systems": ["arcade"], "files": []}, - "opera": {"type": "libretro", "systems": ["3do"], "files": []}, - "mame": {"type": "libretro", "systems": ["arcade"], "files": []}, - } - result = resolve_platform_cores(config, profiles) - self.assertEqual(result, {"fbneo", "opera"}) - - def test_resolve_cores_fallback_systems(self): - """Missing cores: field falls back to system ID intersection.""" - config = {"systems": {"nes": {"files": []}}} - profiles = { - "fceumm": {"type": "libretro", "systems": ["nes"], "files": []}, - "dolphin": {"type": "libretro", "systems": ["gc"], "files": []}, - } - result = resolve_platform_cores(config, profiles) - self.assertEqual(result, {"fceumm"}) - - def test_resolve_cores_excludes_alias(self): - """Alias profiles never included even if name matches cores list.""" - config = {"cores": ["mednafen_psx_hw"], "systems": {}} - profiles = { - "mednafen_psx_hw": {"type": "alias", "alias_of": "beetle_psx", "files": []}, - } - result = resolve_platform_cores(config, profiles) - self.assertEqual(result, set()) - - def test_cross_reference_uses_core_resolution(self): - """Cross-reference matches by cores: field, not system intersection.""" - config = { - "cores": ["fbneo"], - "systems": {"arcade": {"files": [{"name": "neogeo.zip", "md5": "abc"}]}}, - } - profiles = { - "fbneo": { - "emulator": "FBNeo", - "systems": ["snk-neogeo-mvs"], - "type": "pure_libretro", - "files": [ - {"name": "neogeo.zip", "required": True}, - {"name": "neocdz.zip", "required": True}, - ], - }, - } - db = {"indexes": {"by_name": {"neocdz.zip": {"sha1": "x"}}}} - undeclared = find_undeclared_files(config, self.emulators_dir, db, profiles) - names = [u["name"] for u in undeclared] - self.assertIn("neocdz.zip", names) - self.assertNotIn("neogeo.zip", names) - - def test_exclusion_notes_uses_core_resolution(self): - """Exclusion notes match by cores: field, not system intersection.""" - config = {"cores": ["desmume2015"], "systems": {"nds": {"files": []}}} - profiles = { - "desmume2015": { - "emulator": "DeSmuME 2015", - "type": "frozen_snapshot", - "systems": ["nintendo-ds"], - "files": [], - "exclusion_note": "Frozen snapshot, code never loads BIOS", - }, - } - notes = find_exclusion_notes(config, self.emulators_dir, profiles) - emu_names = [n["emulator"] for n in notes] - self.assertIn("DeSmuME 2015", emu_names) - - def test_70_validation_index_built(self): - """Validation index extracts checks from emulator profiles.""" - profiles = load_emulator_profiles(self.emulators_dir) - index = build_validation_index(profiles) - self.assertIn("present_req.bin", index) - self.assertIn("size", index["present_req.bin"]["checks"]) - self.assertIn(16, {s for r in index["present_req.bin"]["rules"] for s in r["sizes"]}) - self.assertIn("correct_hash.bin", index) - self.assertIn("crc32", index["correct_hash.bin"]["checks"]) - - def test_71_validation_size_pass(self): - """File with correct size passes validation.""" - profiles = load_emulator_profiles(self.emulators_dir) - index = build_validation_index(profiles) - path = self.files["present_req.bin"]["path"] - reason = check_file_validation(path, "present_req.bin", index) - self.assertIsNone(reason) - - def test_72_validation_size_fail(self): - """File with wrong size fails validation.""" - profiles = load_emulator_profiles(self.emulators_dir) - index = build_validation_index(profiles) - path = self.files["present_opt.bin"]["path"] - result = check_file_validation(path, "present_opt.bin", index) - self.assertIsNotNone(result) - reason, emus = result - self.assertIn("size mismatch", reason) - self.assertIsInstance(emus, list) - - def test_73_validation_crc32_pass(self): - """File with correct CRC32 passes validation.""" - profiles = load_emulator_profiles(self.emulators_dir) - index = build_validation_index(profiles) - path = self.files["correct_hash.bin"]["path"] - reason = check_file_validation(path, "correct_hash.bin", index) - self.assertIsNone(reason) - - def test_74_validation_crc32_fail(self): - """File with wrong CRC32 fails validation.""" - profiles = load_emulator_profiles(self.emulators_dir) - index = build_validation_index(profiles) - path = self.files["no_md5.bin"]["path"] - result = check_file_validation(path, "no_md5.bin", index) - self.assertIsNotNone(result) - reason, emus = result - self.assertIn("crc32 mismatch", reason) - self.assertIsInstance(emus, list) - - def test_75_validation_applied_in_existence_mode(self): - """Existence mode reports discrepancy when validation fails, keeps OK.""" - config = load_platform_config("test_existence", self.platforms_dir) - profiles = load_emulator_profiles(self.emulators_dir) - result = verify_platform(config, self.db, self.emulators_dir, profiles) - # present_opt.bin exists but has wrong expected size - OK with discrepancy - for d in result["details"]: - if d["name"] == "present_opt.bin": - self.assertEqual(d["status"], Status.OK) - self.assertIn("size mismatch", d.get("discrepancy", "")) - break - else: - self.fail("present_opt.bin not found in details") - - def test_77_validation_crc32_leading_zero(self): - """CRC32 starting with '0' must not be truncated (lstrip regression).""" - profiles = load_emulator_profiles(self.emulators_dir) - index = build_validation_index(profiles) - path = self.files["leading_zero_crc.bin"]["path"] - reason = check_file_validation(path, "leading_zero_crc.bin", index) - self.assertIsNone(reason) - - def test_78_validation_multi_size_accepted(self): - """Multiple valid sizes from different profiles are collected as a set.""" - profiles = { - "emu_a": { - "type": "libretro", - "files": [ - {"name": "shared.bin", "validation": ["size"], "size": 512}, - ], - }, - "emu_b": { - "type": "libretro", - "files": [ - {"name": "shared.bin", "validation": ["size"], "size": 1024}, - ], - }, - } - index = build_validation_index(profiles) - self.assertEqual([r["sizes"] for r in index["shared.bin"]["rules"]], [{512}, {1024}]) - - def test_71b_validation_sizes_judged_per_entry(self): - """One core's exact size is never bounded by another core's minimum: - pooled, gsplus's 131072-byte Apple IIGS ROM fell under basiliskii's - min_size and was refused.""" - import tempfile - - profiles = { - "exact": {"type": "libretro", "files": [ - {"name": "ROM", "validation": ["size"], "size": [131072, 262144]}]}, - "ranged": {"type": "libretro", "files": [ - {"name": "ROM", "validation": ["size"], "min_size": 377670}]}, - } - index = build_validation_index(profiles) - with tempfile.TemporaryDirectory() as tmp: - path = os.path.join(tmp, "ROM") - with open(path, "wb") as f: - f.write(b"\0" * 131072) - self.assertIsNone(check_file_validation(path, "ROM", index)) - with open(path, "wb") as f: - f.write(b"\0" * 1000) - reason, emus = check_file_validation(path, "ROM", index) - self.assertIn("size", reason) - self.assertEqual(emus, ["exact", "ranged"]) - - def test_79_validation_md5_pass(self): - """File with correct MD5 passes validation.""" - profiles = load_emulator_profiles(self.emulators_dir) - index = build_validation_index(profiles) - path = self.files["correct_hash.bin"]["path"] - reason = check_file_validation(path, "correct_hash.bin", index) - self.assertIsNone(reason) - - def test_80_validation_md5_fail(self): - """File with wrong MD5 fails validation.""" - profiles = load_emulator_profiles(self.emulators_dir) - index = build_validation_index(profiles) - path = self.files["alias_target.bin"]["path"] - result = check_file_validation(path, "alias_target.bin", index) - self.assertIsNotNone(result) - reason, emus = result - self.assertIn("md5 mismatch", reason) - self.assertIsInstance(emus, list) - - def test_81_validation_index_has_md5_sha1(self): - """Validation index stores md5 and sha1 when declared.""" - profiles = load_emulator_profiles(self.emulators_dir) - index = build_validation_index(profiles) - self.assertIn("md5", index["correct_hash.bin"]["checks"]) - self.assertIn("sha1", index["correct_hash.bin"]["checks"]) - self.assertIsNotNone(index["correct_hash.bin"]["md5"]) - self.assertIsNotNone(index["correct_hash.bin"]["sha1"]) - - def test_82_validation_adler32_pass(self): - """File with correct adler32 passes validation.""" - profiles = load_emulator_profiles(self.emulators_dir) - index = build_validation_index(profiles) - path = self.files["present_req.bin"]["path"] - reason = check_file_validation(path, "present_req.bin", index) - self.assertIsNone(reason) - - def test_83_validation_min_max_size_pass(self): - """File within min/max size range passes validation.""" - profiles = load_emulator_profiles(self.emulators_dir) - index = build_validation_index(profiles) - path = self.files["present_req.bin"]["path"] - reason = check_file_validation(path, "present_req.bin", index) - self.assertIsNone(reason) - # Each entry keeps its own min/max - rules = index["present_req.bin"]["rules"] - self.assertIn((10, 100), {(r["min_size"], r["max_size"]) for r in rules}) - - def test_84_validation_crypto_tracked(self): - """Signature/crypto checks are tracked as non-reproducible.""" - profiles = load_emulator_profiles(self.emulators_dir) - index = build_validation_index(profiles) - # correct_hash.bin has [size, signature] - self.assertIn("signature", index["correct_hash.bin"]["crypto_only"]) - # Size check still applies despite signature being non-reproducible - path = self.files["correct_hash.bin"]["path"] - reason = check_file_validation(path, "correct_hash.bin", index) - self.assertIsNone(reason) # size=16 matches - - def test_76_validation_no_effect_when_no_field(self): - """Files without validation field are unaffected.""" - profiles = load_emulator_profiles(self.emulators_dir) - index = build_validation_index(profiles) - # wrong_hash.bin has no validation in any profile - path = self.files["wrong_hash.bin"]["path"] - reason = check_file_validation(path, "wrong_hash.bin", index) - self.assertIsNone(reason) - - # --------------------------------------------------------------- - # Emulator/system mode verification - # --------------------------------------------------------------- - - def test_90_verify_emulator_basic(self): - """verify_emulator returns correct counts for a profile with mixed present/missing.""" - result = verify_emulator(["test_emu"], self.emulators_dir, self.db) - self.assertIn("test_emu", result["emulators"]) - # present_req.bin and alias_target.bin are present, others missing - self.assertGreater(result["total_files"], 0) - self.assertGreater(result["severity_counts"][Severity.OK], 0) - - def test_91_verify_emulator_standalone_filters(self): - """Standalone mode includes mode:standalone files, excludes mode:libretro.""" - result_lr = verify_emulator( - ["test_emu"], self.emulators_dir, self.db, standalone=False - ) - result_sa = verify_emulator( - ["test_emu"], self.emulators_dir, self.db, standalone=True - ) - lr_names = {d["name"] for d in result_lr["details"]} - sa_names = {d["name"] for d in result_sa["details"]} - # standalone_only.bin should be in standalone, not libretro - self.assertNotIn("standalone_only.bin", lr_names) - self.assertIn("standalone_only.bin", sa_names) - - def test_102_resolve_dest_hint_disambiguates(self): - """dest_hint resolves regional variants with same name to distinct files.""" - usa_path, usa_status = resolve_local_file( - {"name": "BIOS.bin"}, - self.db, - dest_hint="TestConsole/USA/BIOS.bin", - ) - eur_path, eur_status = resolve_local_file( - {"name": "BIOS.bin"}, - self.db, - dest_hint="TestConsole/EUR/BIOS.bin", - ) - self.assertIsNotNone(usa_path) - self.assertIsNotNone(eur_path) - self.assertEqual(usa_status, "path_exact") - self.assertEqual(eur_status, "path_exact") - # Must be DIFFERENT files - self.assertNotEqual(usa_path, eur_path) - # Verify content - with open(usa_path, "rb") as f: - self.assertEqual(f.read(), b"BIOS_USA_CONTENT") - with open(eur_path, "rb") as f: - self.assertEqual(f.read(), b"BIOS_EUR_CONTENT") - - def test_103_resolve_dest_hint_fallback_to_name(self): - """Without dest_hint, falls back to by_name (first candidate).""" - path, status = resolve_local_file({"name": "BIOS.bin"}, self.db) - self.assertIsNotNone(path) - # Still finds something (first candidate by name) - - def test_92_verify_emulator_libretro_only_rejects_standalone(self): - """Libretro-only profile rejects --standalone.""" - with self.assertRaises(ProfileSelectionError): - verify_emulator(["test_hle"], self.emulators_dir, self.db, standalone=True) - - def test_92b_verify_emulator_game_type_rejects_standalone(self): - """Game-type profile rejects --standalone.""" - game = { - "emulator": "TestGame", - "type": "game", - "systems": ["console-a"], - "files": [], - } - with open(os.path.join(self.emulators_dir, "test_game.yml"), "w") as fh: - yaml.dump(game, fh) - with self.assertRaises(ProfileSelectionError): - verify_emulator(["test_game"], self.emulators_dir, self.db, standalone=True) - - def test_93_verify_emulator_alias_selects_its_profile(self): - """An alias verifies the profile it is an alias of.""" - with contextlib.redirect_stderr(io.StringIO()): - via_alias = verify_emulator(["test_alias"], self.emulators_dir, self.db) - direct = verify_emulator(["test_emu"], self.emulators_dir, self.db) - self.assertEqual(via_alias["emulators"], direct["emulators"]) - self.assertEqual(via_alias["details"], direct["details"]) - - def test_94_verify_emulator_launcher_rejected(self): - """Launcher profile produces error.""" - with self.assertRaises(ProfileSelectionError): - verify_emulator(["test_launcher"], self.emulators_dir, self.db) - - def test_95_verify_emulator_validation_applied(self): - """Emulator mode applies validation checks as primary verification.""" - result = verify_emulator(["test_validation"], self.emulators_dir, self.db) - # present_opt.bin has wrong size ->UNTESTED - for d in result["details"]: - if d["name"] == "present_opt.bin": - self.assertEqual(d["status"], Status.UNTESTED) - self.assertIn("size mismatch", d.get("reason", "")) - break - else: - self.fail("present_opt.bin not found in details") - - def test_96_verify_emulator_multi(self): - """Multi-emulator verify aggregates files.""" - result = verify_emulator( - ["test_emu", "test_hle"], - self.emulators_dir, - self.db, - ) - self.assertEqual(len(result["emulators"]), 2) - all_names = {d["name"] for d in result["details"]} - # Files from both profiles - self.assertIn("present_req.bin", all_names) - self.assertIn("hle_missing.bin", all_names) - - def test_97_verify_emulator_data_dir_notice(self): - """Emulator with data_directories reports notice.""" - result = verify_emulator(["test_emu"], self.emulators_dir, self.db) - self.assertIn("test-data-dir", result.get("data_dir_notices", [])) - - def test_97b_a_data_directory_follows_its_build_mode(self): - """A tree only the standalone build reads is no concern of the core.""" - profile = { - "emulator": "ModeDirs", - "type": "standalone + libretro", - "cores": ["mode_dirs"], - "systems": ["console-a"], - "data_directories": [ - {"ref": "standalone-only-dir", "mode": "standalone"}, - {"ref": "shared-dir"}, - ], - "files": [{"name": "present_req.bin", "required": True}], - } - with open(os.path.join(self.emulators_dir, "mode_dirs.yml"), "w") as fh: - yaml.dump(profile, fh) - as_core = verify_emulator(["mode_dirs"], self.emulators_dir, self.db) - self.assertEqual(as_core.get("data_dir_notices", []), ["shared-dir"]) - alone = verify_emulator( - ["mode_dirs"], self.emulators_dir, self.db, standalone=True - ) - self.assertEqual( - sorted(alone.get("data_dir_notices", [])), - ["shared-dir", "standalone-only-dir"], - ) - - def test_97c_one_held_release_fills_a_slot_several_are_accepted_for(self): - """Entries of one profile on one destination are alternatives. - - A profile lists each release the code accepts under a name (the - shareware and the retail archive, told apart by size). Holding one - is the slot filled: the releases not held are not gaps and must not - drag the destination down to the worst status among them. - """ - present = os.path.join(self.bios_dir, "present_req.bin") - size = os.path.getsize(present) - profile = { - "emulator": "Releases", - "type": "standalone", - "cores": ["releases"], - "systems": ["console-a"], - "files": [ - {"name": "present_req.bin", "path": "game/present_req.bin", - "required": False, "size": size + 7, "validation": ["size"], - "description": "retail"}, - {"name": "present_req.bin", "path": "game/present_req.bin", - "required": False, "size": size, "validation": ["size"], - "description": "shareware"}, - {"name": "absent_everywhere.bin", "path": "game/absent.bin", - "required": False}, - ], - } - with open(os.path.join(self.emulators_dir, "releases.yml"), "w") as fh: - yaml.dump(profile, fh) - result = verify_emulator( - ["releases"], self.emulators_dir, self.db, standalone=True - ) - statuses = {d["name"]: d["status"] for d in result["details"]} - self.assertEqual(statuses["present_req.bin"], "ok") - self.assertEqual(statuses["absent_everywhere.bin"], "missing") - self.assertEqual( - sum(1 for d in result["details"] if d["name"] == "present_req.bin"), 1 - ) - self.assertEqual(result["total_files"], 2) - - def test_98_verify_emulator_validation_label(self): - """Validation label reflects the checks used.""" - result = verify_emulator(["test_validation"], self.emulators_dir, self.db) - # test_validation has crc32, md5, sha1, size ->all listed - self.assertEqual(result["verification_mode"], "crc32+md5+sha1+signature+size") - - def test_99filter_files_by_mode(self): - """filter_files_by_mode correctly filters standalone/libretro.""" - files = [ - {"name": "a.bin"}, # no mode ->both - {"name": "b.bin", "mode": "libretro"}, # libretro only - {"name": "c.bin", "mode": "standalone"}, # standalone only - {"name": "d.bin", "mode": "both"}, # explicit both - ] - lr = filter_files_by_mode(files, standalone=False) - sa = filter_files_by_mode(files, standalone=True) - lr_names = {f["name"] for f in lr} - sa_names = {f["name"] for f in sa} - self.assertEqual(lr_names, {"a.bin", "b.bin", "d.bin"}) - self.assertEqual(sa_names, {"a.bin", "c.bin", "d.bin"}) - - def test_100_verify_emulator_empty_profile(self): - """Profile with files:[] produces note, not error.""" - empty = { - "emulator": "TestEmpty", - "type": "libretro", - "systems": ["console-a"], - "files": [], - "exclusion_note": "Code never loads BIOS", - } - with open(os.path.join(self.emulators_dir, "test_empty.yml"), "w") as fh: - yaml.dump(empty, fh) - result = verify_emulator(["test_empty"], self.emulators_dir, self.db) - # Should have a note entry, not crash - self.assertEqual(result["total_files"], 0) - notes = [d for d in result["details"] if d.get("note")] - self.assertTrue(len(notes) > 0) - - def test_101_verify_emulator_severity_missing_required(self): - """Missing required file in emulator mode ->WARNING severity.""" - result = verify_emulator(["test_emu"], self.emulators_dir, self.db) - # undeclared_req.bin is required and missing - for d in result["details"]: - if d["name"] == "undeclared_req.bin": - self.assertEqual(d["status"], Status.MISSING) - self.assertTrue(d["required"]) - break - else: - self.fail("undeclared_req.bin not found") - # Severity should be WARNING (existence mode base) - self.assertGreater(result["severity_counts"][Severity.WARNING], 0) - - def test_102_safe_extract_zip_blocks_traversal(self): - """safe_extract_zip must reject zip-slip path traversal.""" - malicious_zip = os.path.join(self.root, "evil.zip") - with zipfile.ZipFile(malicious_zip, "w") as zf: - zf.writestr("../../etc/passwd", "root:x:0:0") - dest = os.path.join(self.root, "extract_dest") - os.makedirs(dest) - with self.assertRaises(ValueError): - safe_extract_zip(malicious_zip, dest) - - def test_103_safe_extract_zip_normal(self): - """safe_extract_zip extracts valid files correctly.""" - normal_zip = os.path.join(self.root, "normal.zip") - with zipfile.ZipFile(normal_zip, "w") as zf: - zf.writestr("subdir/file.txt", "hello") - dest = os.path.join(self.root, "extract_normal") - os.makedirs(dest) - safe_extract_zip(normal_zip, dest) - extracted = os.path.join(dest, "subdir", "file.txt") - self.assertTrue(os.path.exists(extracted)) - with open(extracted) as f: - self.assertEqual(f.read(), "hello") - - def test_104_compute_hashes_correctness(self): - """compute_hashes returns correct values for known content.""" - test_file = os.path.join(self.root, "hash_test.bin") - data = b"retrobios test content" - with open(test_file, "wb") as f: - f.write(data) - import zlib - - expected_sha1 = hashlib.sha1(data).hexdigest() - expected_md5 = hashlib.md5(data).hexdigest() - expected_sha256 = hashlib.sha256(data).hexdigest() - expected_crc32 = format(zlib.crc32(data) & 0xFFFFFFFF, "08x") - - result = compute_hashes(test_file) - self.assertEqual(result["sha1"], expected_sha1) - self.assertEqual(result["md5"], expected_md5) - self.assertEqual(result["sha256"], expected_sha256) - self.assertEqual(result["crc32"], expected_crc32) - - def test_105_resolve_with_empty_database(self): - """resolve_local_file handles empty database gracefully.""" - empty_db = { - "files": {}, - "indexes": {"by_md5": {}, "by_name": {}, "by_path_suffix": {}}, - } - entry = {"name": "nonexistent.bin", "sha1": "abc123"} - path, status = resolve_local_file(entry, empty_db) - self.assertIsNone(path) - self.assertEqual(status, "not_found") - - def test_106_parse_hash_list(self): - """parse_hash_list normalizes comma-separated MD5s.""" - self.assertEqual(parse_hash_list(""), []) - self.assertEqual(parse_hash_list("ABC123"), ["abc123"]) - self.assertEqual(parse_hash_list("abc, DEF , ghi"), ["abc", "def", "ghi"]) - self.assertEqual(parse_hash_list(",,,"), []) - - def test_107filter_files_by_mode(self): - """filter_files_by_mode filters standalone/libretro correctly.""" - files = [ - {"name": "a.bin", "mode": "standalone"}, - {"name": "b.bin", "mode": "libretro"}, - {"name": "c.bin", "mode": "both"}, - {"name": "d.bin"}, # no mode - ] - # Libretro mode: exclude standalone - result = filter_files_by_mode(files, standalone=False) - names = [f["name"] for f in result] - self.assertNotIn("a.bin", names) - self.assertIn("b.bin", names) - self.assertIn("c.bin", names) - self.assertIn("d.bin", names) - - # Standalone mode: exclude libretro - result = filter_files_by_mode(files, standalone=True) - names = [f["name"] for f in result] - self.assertIn("a.bin", names) - self.assertNotIn("b.bin", names) - self.assertIn("c.bin", names) - self.assertIn("d.bin", names) - - def test_108_standalone_path_in_undeclared(self): - """Undeclared files use standalone_path when core is in standalone_cores.""" - # Create a platform with standalone_cores - config = { - "platform": "TestStandalone", - "verification_mode": "existence", - "cores": ["test_sa"], - "standalone_cores": ["test_sa"], - "systems": { - "console-a": { - "files": [ - { - "name": "present_req.bin", - "destination": "present_req.bin", - "required": True, - }, - ], - }, - }, - } - with open(os.path.join(self.platforms_dir, "test_standalone.yml"), "w") as fh: - yaml.dump(config, fh) - - # Create emulator with standalone_path divergence - emu = { - "emulator": "TestStandaloneEmu", - "type": "standalone + libretro", - "cores": ["test_sa"], - "systems": ["console-a"], - "files": [ - { - "name": "libretro_file.bin", - "path": "subdir/libretro_file.bin", - "standalone_path": "flat_file.bin", - "required": True, - }, - { - "name": "standalone_only.bin", - "mode": "standalone", - "required": False, - }, - {"name": "libretro_only.bin", "mode": "libretro", "required": False}, - ], - } - with open( - os.path.join(self.emulators_dir, "test_standalone_emu.yml"), "w" - ) as fh: - yaml.dump(emu, fh) - - config = load_platform_config("test_standalone", self.platforms_dir) - profiles = load_emulator_profiles(self.emulators_dir) - undeclared = find_undeclared_files( - config, self.emulators_dir, self.db, profiles - ) - by_name = {u["name"]: u for u in undeclared} - - # standalone_path used for undeclared file (core is standalone) - self.assertIn("libretro_file.bin", by_name) - self.assertEqual(by_name["libretro_file.bin"]["path"], "flat_file.bin") - - # standalone-only file IS included (core is standalone) - self.assertIn("standalone_only.bin", by_name) - - # libretro-only file is EXCLUDED (core is standalone) - self.assertNotIn("libretro_only.bin", by_name) - - def test_109_no_standalone_cores_uses_libretro_path(self): - """Without standalone_cores, undeclared files use path: (libretro).""" - config = load_platform_config("test_existence", self.platforms_dir) - profiles = load_emulator_profiles(self.emulators_dir) - undeclared = find_undeclared_files( - config, self.emulators_dir, self.db, profiles - ) - # standalone_only.bin should be excluded (platform has no standalone_cores) - names = {u["name"] for u in undeclared} - self.assertNotIn("standalone_only.bin", names) - - def test_110_cores_alias_reverse_index(self): - """resolve_platform_cores matches via cores: field aliases.""" - emu = { - "emulator": "TestAliasCore", - "type": "libretro", - "cores": ["test_alias_core", "shortname"], - "systems": ["console-a"], - "files": [], - } - with open(os.path.join(self.emulators_dir, "test_alias_core.yml"), "w") as fh: - yaml.dump(emu, fh) - - config = {"cores": ["shortname"]} - profiles = load_emulator_profiles(self.emulators_dir) - resolved = resolve_platform_cores(config, profiles) - self.assertIn("test_alias_core", resolved) - - # --------------------------------------------------------------- - # Target config tests (Task 1) - # --------------------------------------------------------------- - - def _write_target_fixtures(self): - """Create target config fixtures for testing.""" - targets_dir = os.path.join(self.platforms_dir, "targets") - os.makedirs(targets_dir, exist_ok=True) - target_config = { - "platform": "testplatform", - "source": "test", - "scraped_at": "2026-01-01T00:00:00Z", - "targets": { - "target-full": { - "architecture": "x86_64", - "cores": ["core_a", "core_b", "core_c"], - }, - "target-minimal": { - "architecture": "armv7", - "cores": ["core_a"], - }, - }, - } - with open(os.path.join(targets_dir, "testplatform.yml"), "w") as f: - yaml.dump(target_config, f) - single_config = { - "platform": "singleplatform", - "source": "test", - "scraped_at": "2026-01-01T00:00:00Z", - "targets": { - "only-target": { - "architecture": "x86_64", - "cores": ["core_a", "core_b"], - }, - }, - } - with open(os.path.join(targets_dir, "singleplatform.yml"), "w") as f: - yaml.dump(single_config, f) - overrides = { - "testplatform": { - "targets": { - "target-full": { - "aliases": ["full", "pc", "desktop"], - "add_cores": ["core_d"], - "remove_cores": ["core_c"], - }, - "target-minimal": { - "aliases": ["minimal", "arm"], - }, - }, - }, - } - with open(os.path.join(targets_dir, "_overrides.yml"), "w") as f: - yaml.dump(overrides, f) - - def test_load_target_config(self): - self._write_target_fixtures() - from model.targets import load_target_config - - cores = load_target_config("testplatform", "target-minimal", self.platforms_dir) - self.assertEqual(cores, {"core_a"}) - - def test_target_alias_resolution(self): - self._write_target_fixtures() - from model.targets import load_target_config - - cores = load_target_config("testplatform", "full", self.platforms_dir) - self.assertEqual(cores, {"core_a", "core_b", "core_d"}) - - def test_target_unknown_error(self): - self._write_target_fixtures() - from model.targets import load_target_config - - with self.assertRaises(ValueError) as ctx: - load_target_config("testplatform", "nonexistent", self.platforms_dir) - self.assertIn("target-full", str(ctx.exception)) - self.assertIn("target-minimal", str(ctx.exception)) - - def test_target_override_add_remove(self): - self._write_target_fixtures() - from model.targets import load_target_config - - cores = load_target_config("testplatform", "full", self.platforms_dir) - self.assertIn("core_d", cores) - self.assertNotIn("core_c", cores) - self.assertIn("core_a", cores) - self.assertIn("core_b", cores) - - def test_target_default_override_reaches_every_target(self): - """`_default` drops a name on every target, then the target adds its own.""" - self._write_target_fixtures() - from model.targets import load_target_config - - targets_dir = os.path.join(self.platforms_dir, "targets") - overrides = { - "testplatform": { - "targets": { - "_default": {"remove_cores": ["core_a"], "add_cores": ["core_z"]}, - "target-full": {"aliases": ["full"], "add_cores": ["core_a"]}, - }, - }, - } - with open(os.path.join(targets_dir, "_overrides.yml"), "w") as f: - yaml.dump(overrides, f) - self.assertEqual( - load_target_config("testplatform", "target-minimal", self.platforms_dir), - {"core_z"}, - ) - self.assertEqual( - load_target_config("testplatform", "full", self.platforms_dir), - {"core_a", "core_b", "core_c", "core_z"}, - ) - with self.assertRaises(ValueError): - load_target_config("testplatform", "_default", self.platforms_dir) - - def test_target_single_target_noop(self): - self._write_target_fixtures() - from model.targets import load_target_config - - cores = load_target_config("singleplatform", "only-target", self.platforms_dir) - self.assertEqual(cores, {"core_a", "core_b"}) - - def test_target_inherits(self): - self._write_target_fixtures() - targets_dir = os.path.join(self.platforms_dir, "targets") - child_config = { - "platform": "childplatform", - "source": "test", - "scraped_at": "2026-01-01T00:00:00Z", - "targets": { - "target-full": { - "architecture": "x86_64", - "cores": ["core_a"], - }, - }, - } - with open(os.path.join(targets_dir, "childplatform.yml"), "w") as f: - yaml.dump(child_config, f) - from model.targets import load_target_config - - parent = load_target_config( - "testplatform", "target-minimal", self.platforms_dir - ) - child = load_target_config("childplatform", "target-full", self.platforms_dir) - self.assertEqual(parent, {"core_a"}) - self.assertEqual(child, {"core_a"}) - self.assertNotEqual( - load_target_config("testplatform", "full", self.platforms_dir), - child, - ) - - # --------------------------------------------------------------- - # Target filtering in resolve_platform_cores (Task 2) - # --------------------------------------------------------------- - - def test_target_core_intersection(self): - self._write_target_fixtures() - profiles = { - "core_a": {"type": "libretro", "systems": ["sys1"]}, - "core_b": {"type": "libretro", "systems": ["sys1"]}, - "core_c": {"type": "libretro", "systems": ["sys2"]}, - "core_d": {"type": "libretro", "systems": ["sys2"]}, - } - config = {"cores": "all_libretro"} - result = resolve_platform_cores(config, profiles) - self.assertEqual(result, {"core_a", "core_b", "core_c", "core_d"}) - result = resolve_platform_cores( - config, profiles, target_cores={"core_a", "core_b"} - ) - self.assertEqual(result, {"core_a", "core_b"}) - - def test_target_none_no_filter(self): - profiles = { - "core_a": {"type": "libretro", "systems": ["sys1"]}, - "core_b": {"type": "libretro", "systems": ["sys1"]}, - } - config = {"cores": "all_libretro"} - result = resolve_platform_cores(config, profiles, target_cores=None) - self.assertEqual(result, {"core_a", "core_b"}) - - def test_verify_target_filtered(self): - """Verify with target_cores only reports files from filtered cores.""" - self._write_target_fixtures() - core_a_path = os.path.join(self.emulators_dir, "core_a.yml") - core_b_path = os.path.join(self.emulators_dir, "core_b.yml") - with open(core_a_path, "w") as f: - yaml.dump( - { - "emulator": "CoreA", - "type": "libretro", - "systems": ["sys1"], - "files": [{"name": "bios_a.bin", "required": True}], - }, - f, - ) - with open(core_b_path, "w") as f: - yaml.dump( - { - "emulator": "CoreB", - "type": "libretro", - "systems": ["sys1"], - "files": [{"name": "bios_b.bin", "required": True}], - }, - f, - ) - - config = {"cores": "all_libretro", "systems": {"sys1": {"files": []}}} - profiles = load_emulator_profiles(self.emulators_dir) - - # Without target: both cores' files are undeclared - undeclared = find_undeclared_files( - config, self.emulators_dir, self.db, profiles - ) - names = {u["name"] for u in undeclared} - self.assertIn("bios_a.bin", names) - self.assertIn("bios_b.bin", names) - - # With target filtering to core_a only - undeclared = find_undeclared_files( - config, - self.emulators_dir, - self.db, - profiles, - target_cores={"core_a"}, - ) - names = {u["name"] for u in undeclared} - self.assertIn("bios_a.bin", names) - self.assertNotIn("bios_b.bin", names) - - # --------------------------------------------------------------- - # Validation index per-emulator ground truth (Task: ground truth) - # --------------------------------------------------------------- - - def test_111_validation_index_per_emulator(self): - """Validation index includes per-emulator detail for ground truth.""" - profiles = load_emulator_profiles(self.emulators_dir) - index = build_validation_index(profiles) - entry = index["present_req.bin"] - self.assertIn("per_emulator", entry) - pe = entry["per_emulator"] - self.assertIn("test_validation", pe) - detail = pe["test_validation"] - self.assertIn("size", detail["checks"]) - self.assertEqual(detail["expected"]["size"], 16) - - def test_112_build_ground_truth(self): - """build_ground_truth returns per-emulator detail for a filename.""" - from resolve.validation import build_ground_truth - - profiles = load_emulator_profiles(self.emulators_dir) - index = build_validation_index(profiles) - gt = build_ground_truth("present_req.bin", index) - self.assertIsInstance(gt, list) - self.assertTrue(len(gt) >= 1) - emu_names = {g["emulator"] for g in gt} - self.assertIn("test_validation", emu_names) - for g in gt: - if g["emulator"] == "test_validation": - self.assertIn("size", g["checks"]) - self.assertIn("source_ref", g) - self.assertIn("expected", g) - - def test_113_build_ground_truth_empty(self): - """build_ground_truth returns [] for unknown filename.""" - from resolve.validation import build_ground_truth - - profiles = load_emulator_profiles(self.emulators_dir) - index = build_validation_index(profiles) - gt = build_ground_truth("nonexistent.bin", index) - self.assertEqual(gt, []) - - def test_114_platform_result_has_ground_truth(self): - """verify_platform attaches ground_truth to each detail entry.""" - config = load_platform_config("test_existence", self.platforms_dir) - profiles = load_emulator_profiles(self.emulators_dir) - result = verify_platform(config, self.db, self.emulators_dir, profiles) - for d in result["details"]: - self.assertIn("ground_truth", d) - # present_req.bin has validation in test_validation profile - for d in result["details"]: - if d["name"] == "present_req.bin": - self.assertTrue(len(d["ground_truth"]) >= 1) - emu_names = {g["emulator"] for g in d["ground_truth"]} - self.assertIn("test_validation", emu_names) - break - else: - self.fail("present_req.bin not found in details") - - def test_116_undeclared_files_have_ground_truth(self): - """find_undeclared_files attaches ground truth fields.""" - config = load_platform_config("test_existence", self.platforms_dir) - profiles = load_emulator_profiles(self.emulators_dir) - undeclared = find_undeclared_files( - config, self.emulators_dir, self.db, profiles - ) - for u in undeclared: - self.assertIn("checks", u) - self.assertIn("source_ref", u) - self.assertIn("expected", u) - - def test_117_platform_result_ground_truth_coverage(self): - """verify_platform includes ground truth coverage counts.""" - config = load_platform_config("test_existence", self.platforms_dir) - profiles = load_emulator_profiles(self.emulators_dir) - result = verify_platform(config, self.db, self.emulators_dir, profiles) - gt = result["ground_truth_coverage"] - self.assertIn("with_validation", gt) - self.assertIn("total", gt) - self.assertIn("platform_only", gt) - self.assertEqual(gt["total"], result["total_files"]) - self.assertEqual(gt["platform_only"], gt["total"] - gt["with_validation"]) - self.assertGreaterEqual(gt["with_validation"], 1) - - def test_118_emulator_result_has_ground_truth(self): - """verify_emulator attaches ground_truth to each detail entry.""" - result = verify_emulator(["test_validation"], self.emulators_dir, self.db) - for d in result["details"]: - self.assertIn("ground_truth", d) - # present_req.bin should have ground truth from test_validation - for d in result["details"]: - if d["name"] == "present_req.bin": - self.assertTrue(len(d["ground_truth"]) >= 1) - break - - def test_119_emulator_result_ground_truth_coverage(self): - """verify_emulator includes ground truth coverage counts.""" - result = verify_emulator(["test_validation"], self.emulators_dir, self.db) - gt = result["ground_truth_coverage"] - self.assertEqual(gt["total"], result["total_files"]) - - def test_115_platform_result_ground_truth_empty_for_unknown(self): - """Files with no emulator validation get ground_truth=[].""" - config = load_platform_config("test_existence", self.platforms_dir) - profiles = load_emulator_profiles(self.emulators_dir) - result = verify_platform(config, self.db, self.emulators_dir, profiles) - for d in result["details"]: - if d["name"] == "missing_opt.bin": - self.assertEqual(d["ground_truth"], []) - break - - def test_120_format_ground_truth_aggregate(self): - """Aggregate format: one line with all cores.""" - from packs.report import _format_ground_truth_aggregate - - gt = [ - { - "emulator": "beetle_psx", - "checks": ["md5"], - "source_ref": "libretro.cpp:252", - "expected": {"md5": "abc"}, - }, - { - "emulator": "pcsx_rearmed", - "checks": ["existence"], - "source_ref": None, - "expected": {}, - }, - ] - line = _format_ground_truth_aggregate(gt) - self.assertIn("beetle_psx", line) - self.assertIn("[md5]", line) - self.assertIn("pcsx_rearmed", line) - self.assertIn("[existence]", line) - - def test_121_format_ground_truth_verbose(self): - """Verbose format: one line per core with expected values and source ref.""" - from packs.report import _format_ground_truth_verbose - - gt = [ - { - "emulator": "handy", - "checks": ["size", "crc32"], - "source_ref": "rom.h:48-49", - "expected": {"size": 512, "crc32": "0d973c9d"}, - }, - ] - lines = _format_ground_truth_verbose(gt) - self.assertEqual(len(lines), 1) - self.assertIn("handy", lines[0]) - self.assertIn("size=512", lines[0]) - self.assertIn("crc32=0d973c9d", lines[0]) - self.assertIn("[rom.h:48-49]", lines[0]) - - def test_122_format_ground_truth_verbose_no_source_ref(self): - """Verbose format omits bracket when source_ref is None.""" - from packs.report import _format_ground_truth_verbose - - gt = [ - { - "emulator": "core_a", - "checks": ["existence"], - "source_ref": None, - "expected": {}, - }, - ] - lines = _format_ground_truth_verbose(gt) - self.assertEqual(len(lines), 1) - self.assertNotIn("[", lines[0]) - - def test_123_ground_truth_full_chain_verbose(self): - """Full chain: file -> platform -> emulator -> source_ref visible in ground_truth.""" - config = load_platform_config("test_existence", self.platforms_dir) - profiles = load_emulator_profiles(self.emulators_dir) - result = verify_platform(config, self.db, self.emulators_dir, profiles) - for d in result["details"]: - if d["name"] == "present_req.bin": - gt = d["ground_truth"] - for g in gt: - if g["emulator"] == "test_validation": - self.assertIn("size", g["checks"]) - self.assertEqual(g["source_ref"], "test.c:10-20") - self.assertEqual(g["expected"]["size"], 16) - return - self.fail("present_req.bin / test_validation ground truth not found") - - def test_124_ground_truth_json_includes_all(self): - """JSON output includes ground_truth on all detail entries.""" - config = load_platform_config("test_existence", self.platforms_dir) - profiles = load_emulator_profiles(self.emulators_dir) - result = verify_platform(config, self.db, self.emulators_dir, profiles) - # Simulate --json filtering (non-OK only): ground_truth must survive - filtered = [d for d in result["details"] if d["status"] != Status.OK] - for d in filtered: - self.assertIn("ground_truth", d) - # Also check OK entries have it (before filtering) - ok_entries = [d for d in result["details"] if d["status"] == Status.OK] - for d in ok_entries: - self.assertIn("ground_truth", d) - - def test_125_ground_truth_coverage_in_md5_mode(self): - """MD5 platform also gets ground truth coverage.""" - config = load_platform_config("test_md5", self.platforms_dir) - profiles = load_emulator_profiles(self.emulators_dir) - result = verify_platform(config, self.db, self.emulators_dir, profiles) - gt = result["ground_truth_coverage"] - self.assertEqual(gt["total"], result["total_files"]) - self.assertGreaterEqual(gt["with_validation"], 1) - - def test_130_required_only_excludes_optional(self): - """--required-only excludes files with required: false from pack.""" - from packs.platformpack import generate_pack - - output_dir = os.path.join(self.root, "pack_reqonly") - os.makedirs(output_dir, exist_ok=True) - # Create a platform with one required and one optional file - config = { - "platform": "ReqOnlyTest", - "verification_mode": "existence", - "base_destination": "system", - "systems": { - "test-sys": { - "files": [ - { - "name": "present_req.bin", - "destination": "present_req.bin", - "required": True, - }, - { - "name": "present_opt.bin", - "destination": "present_opt.bin", - "required": False, - }, - ], - }, - }, - } - with open(os.path.join(self.platforms_dir, "test_reqonly.yml"), "w") as fh: - yaml.dump(config, fh) - zip_path = generate_pack( - "test_reqonly", - self.platforms_dir, - self.db, - self.bios_dir, - output_dir, - required_only=True, - ) - self.assertIsNotNone(zip_path) - with zipfile.ZipFile(zip_path) as zf: - names = zf.namelist() - self.assertTrue(any("present_req.bin" in n for n in names)) - self.assertFalse(any("present_opt.bin" in n for n in names)) - # Verify _Required tag in filename - self.assertIn("_Required_", os.path.basename(zip_path)) - - def test_130a_consistency_reads_what_the_builder_and_verify_write(self): - """Step 5 compares the records the two tools write, not their wording. - - The builder's counts and verify's go through the files the pipeline - reads, so a reworded line can no longer switch a comparison off. - """ - from orchestrate.consistency import check_consistency - from packs.packcounts import PackCounts, write_pack_counts - from packs.platformpack import build_platform_pack - from packs.verifyoutput import write_pack_destinations - - profiles = load_emulator_profiles(self.emulators_dir) - output_dir = os.path.join(self.root, "counted") - packs: list[tuple[str, list[str], PackCounts]] = [] - groups, group_results = [], [] - for platform in ("test_existence", "test_md5"): - sink: list[PackCounts] = [] - build_platform_pack( - platform, self.platforms_dir, self.db, self.bios_dir, output_dir, - emulators_dir=self.emulators_dir, emu_profiles=profiles, counts=sink, - ) - self.assertEqual(len(sink), 1) - packs.append((platform, [platform], sink[0])) - config = load_platform_config(platform, self.platforms_dir) - result = verify_platform(config, self.db, self.emulators_dir, emu_profiles=profiles) - groups.append(([platform], platform)) - group_results.append((result, [config.get("platform", platform)])) - destinations = os.path.join(self.root, "destinations.json") - counts = os.path.join(self.root, "counts.json") - write_pack_destinations(destinations, groups, group_results) - write_pack_counts(counts, packs) - with contextlib.redirect_stdout(io.StringIO()) as out: - self.assertTrue(check_consistency(destinations, counts), out.getvalue()) - self.assertEqual(out.getvalue().count("== pack"), 2, out.getvalue()) - - skewed = [(label, ids, PackCounts(**{**c.__dict__, "core_files": c.core_files + 1})) - for label, ids, c in packs] - write_pack_counts(counts, skewed) - with contextlib.redirect_stdout(io.StringIO()) as out: - self.assertFalse(check_consistency(destinations, counts)) - self.assertIn("MISMATCH core files", out.getvalue()) - - def test_130b_existence_pack_reports_hash_mismatch(self): - """Existence mode packs a mismatched file but prints the proof.""" - import contextlib - import io - - from packs.platformpack import generate_pack - - output_dir = os.path.join(self.root, "pack_mismatch") - os.makedirs(output_dir, exist_ok=True) - config = { - "platform": "MismatchTest", - "verification_mode": "existence", - "base_destination": "system", - "systems": { - "test-sys": { - "files": [ - { - "name": "wrong_hash.bin", - "destination": "wrong_hash.bin", - "md5": "ffffffffffffffffffffffffffffffff", - "required": True, - }, - ], - }, - }, - } - with open(os.path.join(self.platforms_dir, "test_mismatch.yml"), "w") as fh: - yaml.dump(config, fh) - out = io.StringIO() - with contextlib.redirect_stdout(out): - zip_path = generate_pack( - "test_mismatch", - self.platforms_dir, - self.db, - self.bios_dir, - output_dir, - offline=True, - ) - self.assertIsNotNone(zip_path) - with zipfile.ZipFile(zip_path) as zf: - names = zf.namelist() - self.assertTrue(any("wrong_hash.bin" in n for n in names)) - report = out.getvalue() - self.assertIn("DISCREPANCY", report) - self.assertIn("declared hash ffffffffffffffffffffffffffffffff", report) - - def test_131_required_only_keeps_default_required(self): - """--required-only keeps files with no required field (default = required).""" - from packs.platformpack import generate_pack - - output_dir = os.path.join(self.root, "pack_reqdef") - os.makedirs(output_dir, exist_ok=True) - # File with no required field - config = { - "platform": "ReqDefTest", - "verification_mode": "existence", - "base_destination": "system", - "systems": { - "test-sys": { - "files": [ - {"name": "present_req.bin", "destination": "present_req.bin"}, - ], - }, - }, - } - with open(os.path.join(self.platforms_dir, "test_reqdef.yml"), "w") as fh: - yaml.dump(config, fh) - zip_path = generate_pack( - "test_reqdef", - self.platforms_dir, - self.db, - self.bios_dir, - output_dir, - required_only=True, - ) - self.assertIsNotNone(zip_path) - with zipfile.ZipFile(zip_path) as zf: - names = zf.namelist() - self.assertTrue(any("present_req.bin" in n for n in names)) - - def test_132_platform_system_filter(self): - """--platform + --system filters systems within a platform pack.""" - from packs.platformpack import generate_pack - - output_dir = os.path.join(self.root, "pack_sysfilter") - os.makedirs(output_dir, exist_ok=True) - config = { - "platform": "SysFilterTest", - "verification_mode": "existence", - "base_destination": "system", - "systems": { - "system-a": { - "files": [ - {"name": "present_req.bin", "destination": "present_req.bin"}, - ], - }, - "system-b": { - "files": [ - {"name": "present_opt.bin", "destination": "present_opt.bin"}, - ], - }, - }, - } - with open(os.path.join(self.platforms_dir, "test_sysfilter.yml"), "w") as fh: - yaml.dump(config, fh) - zip_path = generate_pack( - "test_sysfilter", - self.platforms_dir, - self.db, - self.bios_dir, - output_dir, - system_filter=["system-a"], - ) - self.assertIsNotNone(zip_path) - with zipfile.ZipFile(zip_path) as zf: - names = zf.namelist() - self.assertTrue(any("present_req.bin" in n for n in names)) - self.assertFalse(any("present_opt.bin" in n for n in names)) - - def test_133_platform_system_filter_normalized(self): - """norm_system_id normalization matches with manufacturer prefix.""" - from model.systems import norm_system_id - - self.assertEqual( - norm_system_id("sony-playstation"), - norm_system_id("playstation"), - ) - - def test_134_list_systems_platform_context(self): - """list_platform_system_ids lists systems from a platform YAML.""" - import io - - from model.cliargs import list_platform_system_ids - - config = { - "platform": "ListSysTest", - "verification_mode": "existence", - "systems": { - "alpha-sys": { - "files": [ - {"name": "a.bin", "destination": "a.bin"}, - ], - }, - "beta-sys": { - "files": [ - {"name": "b1.bin", "destination": "b1.bin"}, - {"name": "b2.bin", "destination": "b2.bin"}, - ], - }, - }, - } - with open(os.path.join(self.platforms_dir, "test_listsys.yml"), "w") as fh: - yaml.dump(config, fh) - captured = io.StringIO() - old_stdout = sys.stdout - sys.stdout = captured - try: - list_platform_system_ids("test_listsys", self.platforms_dir) - finally: - sys.stdout = old_stdout - output = captured.getvalue() - self.assertIn("alpha-sys", output) - self.assertIn("beta-sys", output) - self.assertIn("1 file", output) - self.assertIn("2 files", output) - - def test_135_split_by_system(self): - """--split generates one ZIP per system in a subdirectory.""" - import tempfile - - with tempfile.TemporaryDirectory() as tmpdir: - plat_dir = os.path.join(tmpdir, "platforms") - os.makedirs(plat_dir) - bios_dir = os.path.join(tmpdir, "bios", "Test") - os.makedirs(os.path.join(bios_dir, "SysA")) - os.makedirs(os.path.join(bios_dir, "SysB")) - emu_dir = os.path.join(tmpdir, "emulators") - os.makedirs(emu_dir) - out_dir = os.path.join(tmpdir, "dist") - - file_a = os.path.join(bios_dir, "SysA", "bios_a.bin") - file_b = os.path.join(bios_dir, "SysB", "bios_b.bin") - with open(file_a, "wb") as f: - f.write(b"system_a") - with open(file_b, "wb") as f: - f.write(b"system_b") - - from core.hashing import compute_hashes - - ha = compute_hashes(file_a) - hb = compute_hashes(file_b) - - db = { - "files": { - ha["sha1"]: { - "name": "bios_a.bin", - "md5": ha["md5"], - "sha1": ha["sha1"], - "sha256": ha["sha256"], - "path": file_a, - "paths": [file_a], - }, - hb["sha1"]: { - "name": "bios_b.bin", - "md5": hb["md5"], - "sha1": hb["sha1"], - "sha256": hb["sha256"], - "path": file_b, - "paths": [file_b], - }, - }, - "indexes": { - "by_md5": {ha["md5"]: ha["sha1"], hb["md5"]: hb["sha1"]}, - "by_name": {"bios_a.bin": [ha["sha1"]], "bios_b.bin": [hb["sha1"]]}, - "by_crc32": {}, - "by_path_suffix": {}, - }, - } - - registry = {"platforms": {"splitplat": {"config": "splitplat.yml"}}} - with open(os.path.join(plat_dir, "_registry.yml"), "w") as f: - yaml.dump(registry, f) - plat_cfg = { - "platform": "SplitTest", - "verification_mode": "existence", - "systems": { - "test-system-a": { - "files": [{"name": "bios_a.bin", "sha1": ha["sha1"]}] - }, - "test-system-b": { - "files": [{"name": "bios_b.bin", "sha1": hb["sha1"]}] - }, - }, - } - with open(os.path.join(plat_dir, "splitplat.yml"), "w") as f: - yaml.dump(plat_cfg, f) - - from core.ziptools import build_zip_contents_index - from model.profiles import load_emulator_profiles - from packs.platformpack import generate_split_packs - - zip_contents = build_zip_contents_index(db, Path(tmpdir)) - emu_profiles = load_emulator_profiles(emu_dir) - - zip_paths = generate_split_packs( - "splitplat", - plat_dir, - db, - os.path.join(tmpdir, "bios"), - out_dir, - emulators_dir=emu_dir, - zip_contents=zip_contents, - emu_profiles=emu_profiles, - group_by="system", - ) - self.assertEqual(len(zip_paths), 2) - - # Check subdirectory exists - split_dir = os.path.join(out_dir, "SplitTest_Split") - self.assertTrue(os.path.isdir(split_dir)) - - # Verify each ZIP contains only its system's files - for zp in zip_paths: - with zipfile.ZipFile(zp) as zf: - names = zf.namelist() - basename = os.path.basename(zp) - if "System_A" in basename: - self.assertIn("bios_a.bin", names) - self.assertNotIn("bios_b.bin", names) - elif "System_B" in basename: - self.assertIn("bios_b.bin", names) - self.assertNotIn("bios_a.bin", names) - - def test_136_derive_manufacturer(self): - """derive_manufacturer extracts manufacturer correctly.""" - from model.systems import derive_manufacturer - - # From system ID prefix - self.assertEqual(derive_manufacturer("sony-playstation", {}), "Sony") - self.assertEqual(derive_manufacturer("nintendo-snes", {}), "Nintendo") - self.assertEqual(derive_manufacturer("sega-saturn", {}), "Sega") - self.assertEqual(derive_manufacturer("atari-5200", {}), "Atari") - # From explicit manufacturer field - self.assertEqual( - derive_manufacturer("3do", {"manufacturer": "Panasonic|GoldStar"}), - "Panasonic", - ) - # Various = skip to prefix check, then Other - self.assertEqual( - derive_manufacturer("arcade", {"manufacturer": "Various"}), "Other" - ) - # Fallback - self.assertEqual(derive_manufacturer("dos", {}), "Other") - - def test_137_group_systems_by_manufacturer(self): - """_group_systems_by_manufacturer groups correctly.""" - from packs.platformpack import _group_systems_by_manufacturer - - systems = { - "sony-playstation": {"files": [{"name": "a.bin"}]}, - "sony-psp": {"files": [{"name": "b.bin"}]}, - "nintendo-snes": {"files": [{"name": "c.bin"}]}, - "arcade": {"manufacturer": "Various", "files": [{"name": "d.bin"}]}, - } - groups = _group_systems_by_manufacturer(systems, {}, "") - self.assertIn("Sony", groups) - self.assertEqual(sorted(groups["Sony"]), ["sony-playstation", "sony-psp"]) - self.assertIn("Nintendo", groups) - self.assertEqual(groups["Nintendo"], ["nintendo-snes"]) - self.assertIn("Other", groups) - self.assertEqual(groups["Other"], ["arcade"]) - - def test_138_parse_hash_input(self): - """parse_hash_input handles various formats.""" - from packs.hashinput import parse_hash_input - - # Plain MD5 - result = parse_hash_input("d8f1206299c48946e6ec5ef96d014eaa") - self.assertEqual(result, [("md5", "d8f1206299c48946e6ec5ef96d014eaa")]) - # Comma-separated - result = parse_hash_input( - "d8f1206299c48946e6ec5ef96d014eaa,d8f1206299c48946e6ec5ef96d014eab" - ) - self.assertEqual(len(result), 2) - # SHA1 - sha1 = "a" * 40 - result = parse_hash_input(sha1) - self.assertEqual(result, [("sha1", sha1)]) - # CRC32 - result = parse_hash_input("abcd1234") - self.assertEqual(result, [("crc32", "abcd1234")]) - - def test_139_parse_hash_file(self): - """parse_hash_file handles comments, empty lines, various formats.""" - from packs.hashinput import parse_hash_file - - with tempfile.NamedTemporaryFile(mode="w", suffix=".txt", delete=False) as f: - f.write("# PS1 BIOS files\n") - f.write("\n") - f.write("d8f1206299c48946e6ec5ef96d014eaa\n") - f.write("d8f1206299c48946e6ec5ef96d014eab scph5501.bin\n") - f.write("scph5502.bin d8f1206299c48946e6ec5ef96d014eac OK\n") - tmp_path = f.name - try: - result = parse_hash_file(tmp_path) - self.assertEqual(len(result), 3) - self.assertTrue(all(t == "md5" for t, _ in result)) - finally: - os.unlink(tmp_path) - - def test_140_lookup_hashes_found(self): - """lookup_hashes returns the record of a known hash.""" - from resolve.packfiles import HashLookup, lookup_hashes - - db = { - "files": { - "sha1abc": { - "name": "test.bin", - "md5": "md5abc", - "sha1": "sha1abc", - "sha256": "sha256abc", - "path": "bios/Mfr/Console/test.bin", - }, - }, - "indexes": { - "by_md5": {"md5abc": "sha1abc"}, - "by_crc32": {}, - }, - } - records = lookup_hashes([("md5", "md5abc")], db, "bios") - # The record's path, the one field the schema gives it. A read of - # "paths" printed nothing. - self.assertEqual(records, [HashLookup( - "md5", "md5abc", "sha1abc", "md5abc", "test.bin", - "bios/Mfr/Console/test.bin", False, - )]) - self.assertTrue(records[0].found) - - def test_140b_lookup_hashes_never_downloads_a_release_asset(self): - """A release asset counted as held streamed the whole asset first.""" - from unittest import mock - - from resolve import packfiles - - path = "bios/Mfr/Console/big.zip" - db = { - "files": {"sha1big": {"name": "big.zip", "md5": "md5big", - "sha1": "sha1big", "path": path}}, - "indexes": {"by_md5": {"md5big": "sha1big"}, "by_crc32": {}}, - } - seen: list[bool] = [] - - def fetch(_path, expected_sha1=None, offline=False): - seen.append(offline) - - with mock.patch("model.largefiles.load_registered_paths", return_value=[path]), \ - mock.patch.object(packfiles, "fetch_large_file", side_effect=fetch), \ - mock.patch.dict(os.environ, {"RETROBIOS_OFFLINE": ""}), \ - mock.patch.object(packfiles, "OFFLINE", False): - records = packfiles.lookup_hashes([("md5", "md5big")], db, "bios") - self.assertTrue(records[0].in_repo) - self.assertEqual(seen, [True]) - - def test_141_lookup_hashes_not_found(self): - """lookup_hashes reports unknown hashes, and the report counts them.""" - import contextlib - import io - - from packs.hashlookup import print_hash_lookup - from resolve.packfiles import lookup_hashes - - db = {"files": {}, "indexes": {"by_md5": {}, "by_crc32": {}}} - unknown = "unknown123" + "0" * 22 - records = lookup_hashes([("md5", unknown)], db, "bios") - self.assertEqual([r.found for r in records], [False]) - buf = io.StringIO() - with contextlib.redirect_stdout(buf): - missing = print_hash_lookup(records) - self.assertIn("NOT FOUND", buf.getvalue()) - # The CLI exited 0 on this, so a script read "found". - self.assertEqual(missing, 1) - - def test_141b_lookup_report_names_the_file(self): - """The printed report gives the file's hashes, name, path and presence.""" - import contextlib - import io - - from packs.hashlookup import print_hash_lookup - from resolve.packfiles import HashLookup - - record = HashLookup("md5", "md5abc", "sha1abc", "md5abc", "test.bin", - "bios/Mfr/Console/test.bin", True) - buf = io.StringIO() - with contextlib.redirect_stdout(buf): - missing = print_hash_lookup([record]) - self.assertEqual(buf.getvalue(), ( - "\nMD5: md5abc\n SHA1: sha1abc\n MD5: md5abc\n Name: test.bin\n" - " Path: bios/Mfr/Console/test.bin\n In repo: YES\n" - )) - self.assertEqual(missing, 0) - - def test_142_from_md5_platform_pack(self): - """--from-md5 with --platform generates correctly laid out ZIP.""" - import tempfile - import zipfile - - import yaml - - with tempfile.TemporaryDirectory() as tmpdir: - plat_dir = os.path.join(tmpdir, "platforms") - os.makedirs(plat_dir) - bios_dir = os.path.join(tmpdir, "bios", "Sony", "PS1") - os.makedirs(bios_dir) - emu_dir = os.path.join(tmpdir, "emulators") - os.makedirs(emu_dir) - out_dir = os.path.join(tmpdir, "dist") - - bios_file = os.path.join(bios_dir, "scph5501.bin") - with open(bios_file, "wb") as f: - f.write(b"ps1_bios_content") - from core.hashing import compute_hashes - - h = compute_hashes(bios_file) - - db = { - "files": { - h["sha1"]: { - "name": "scph5501.bin", - "md5": h["md5"], - "sha1": h["sha1"], - "sha256": h["sha256"], - "path": bios_file, - "paths": ["Sony/PS1/scph5501.bin"], - }, - }, - "indexes": { - "by_md5": {h["md5"]: h["sha1"]}, - "by_name": {"scph5501.bin": [h["sha1"]]}, - "by_crc32": {}, - "by_path_suffix": {}, - }, - } - - registry = {"platforms": {"testplat": {"config": "testplat.yml"}}} - with open(os.path.join(plat_dir, "_registry.yml"), "w") as f: - yaml.dump(registry, f) - plat_cfg = { - "platform": "TestPlat", - "verification_mode": "md5", - "base_destination": "bios", - "systems": { - "sony-playstation": { - "files": [ - { - "name": "scph5501.bin", - "md5": h["md5"], - "destination": "scph5501.bin", - }, - ] - } - }, - } - with open(os.path.join(plat_dir, "testplat.yml"), "w") as f: - yaml.dump(plat_cfg, f) - - from core.ziptools import build_zip_contents_index - from packs.md5pack import generate_md5_pack - - zip_contents = build_zip_contents_index(db, Path(tmpdir)) - - zip_path = generate_md5_pack( - hashes=[("md5", h["md5"])], - db=db, - bios_dir=bios_dir, - output_dir=out_dir, - zip_contents=zip_contents, - platform_name="testplat", - platforms_dir=plat_dir, - ).zip_path - self.assertIsNotNone(zip_path) - with zipfile.ZipFile(zip_path) as zf: - names = zf.namelist() - self.assertIn("bios/scph5501.bin", names) - self.assertIn("Custom", os.path.basename(zip_path)) - - # A profile displayed under the platform's own name: BizHawk is - # both. The two layouts must not write one file. - emu_dir = os.path.join(tmpdir, "emulators-md5") - os.makedirs(emu_dir) - with open(os.path.join(emu_dir, "testplat.yml"), "w") as f: - yaml.dump({ - "emulator": "TestPlat", "type": "standalone", - "systems": ["sony-playstation"], - "files": [{"name": "scph5501.bin", "md5": h["md5"]}], - }, f) - emu_zip = generate_md5_pack( - hashes=[("md5", h["md5"])], - db=db, - bios_dir=bios_dir, - output_dir=out_dir, - zip_contents=zip_contents, - emulator_name="testplat", - emulators_dir=emu_dir, - ).zip_path - self.assertIsNotNone(emu_zip) - self.assertNotEqual(os.path.basename(emu_zip), os.path.basename(zip_path)) - self.assertTrue(os.path.exists(zip_path)) - with zipfile.ZipFile(emu_zip) as zf: - self.assertIn("scph5501.bin", zf.namelist()) - - def test_143_from_md5_not_in_repo(self): - """--from-md5 reports files in DB but missing from repo.""" - import contextlib - import io - import tempfile - - from packs.md5pack import generate_md5_pack - - db = { - "files": { - "sha1known": { - "name": "missing.bin", - "md5": "md5known" + "0" * 25, - "sha1": "sha1known", - "sha256": "sha256known", - "path": "/nonexistent/missing.bin", - "paths": ["Test/missing.bin"], - }, - }, - "indexes": { - "by_md5": {"md5known" + "0" * 25: "sha1known"}, - "by_crc32": {}, - }, - } - with tempfile.TemporaryDirectory() as tmpdir: - out_dir = os.path.join(tmpdir, "dist") - bios_dir = os.path.join(tmpdir, "bios") - os.makedirs(bios_dir) - buf = io.StringIO() - with contextlib.redirect_stdout(buf): - outcome = generate_md5_pack( - hashes=[("md5", "md5known" + "0" * 25)], - db=db, - bios_dir=bios_dir, - output_dir=out_dir, - zip_contents={}, - ) - self.assertEqual(buf.getvalue(), "") - self.assertEqual(outcome.not_in_repo, [("missing.bin", "md5known" + "0" * 25)]) - self.assertEqual((outcome.packed, outcome.not_in_db), ([], [])) - self.assertIsNone(outcome.zip_path) - from packs.packmodes import print_hash_pack - with contextlib.redirect_stdout(buf): - print_hash_pack(outcome) - self.assertIn("NOT IN REPO: missing.bin", buf.getvalue()) - - def test_144_invalid_split_emulator(self): - """--split + --emulator is rejected.""" - import subprocess - - result = subprocess.run( - ["python", "scripts/generate_pack.py", "--emulator", "test", "--split"], - capture_output=True, - text=True, - check=False, - ) - self.assertNotEqual(result.returncode, 0) - self.assertIn("error", result.stderr.lower()) - - def test_145_invalid_from_md5_all(self): - """--from-md5 + --all is rejected.""" - import subprocess - - result = subprocess.run( - [ - "python", - "scripts/generate_pack.py", - "--all", - "--from-md5", - "abc123" + "0" * 26, - ], - capture_output=True, - text=True, - check=False, - ) - self.assertNotEqual(result.returncode, 0) - - def test_146_invalid_from_md5_system(self): - """--from-md5 + --system is rejected.""" - import subprocess - - result = subprocess.run( - [ - "python", - "scripts/generate_pack.py", - "--system", - "psx", - "--from-md5", - "abc123" + "0" * 26, - ], - capture_output=True, - text=True, - check=False, - ) - self.assertNotEqual(result.returncode, 0) - - def test_147_invalid_group_by_without_split(self): - """--group-by without --split is rejected.""" - import subprocess - - result = subprocess.run( - [ - "python", - "scripts/generate_pack.py", - "--platform", - "retroarch", - "--group-by", - "manufacturer", - ], - capture_output=True, - text=True, - check=False, - ) - self.assertNotEqual(result.returncode, 0) - - def test_148_valid_platform_system(self): - """--platform + --system is accepted (not rejected at validation stage).""" - import argparse - - from model.cliargs import mode_conflicts - - def refused(**given: object) -> list[str]: - args = argparse.Namespace(**{ - "platform": None, "all": False, "emulator": None, "system": None, - "standalone": False, "target": None, "no_game_data": False, **given, - }) - return [message for on, message in mode_conflicts(args) if on] - - self.assertEqual(refused(platform="retroarch", system="psx"), []) - self.assertEqual(refused(all=True, system="psx"), []) - self.assertEqual(refused(system="psx", standalone=True), []) - # One table for verify and generate_pack: verify took --all --system - # --standalone and dropped --standalone. - self.assertTrue(refused(all=True, system="psx", standalone=True)) - self.assertTrue(refused(emulator="handy", system="psx")) - self.assertTrue(refused(platform="retroarch", all=True)) - self.assertTrue(refused(system="psx", target="switch")) - self.assertTrue(refused(emulator="handy", no_game_data=True)) - self.assertIn("Specify --platform, --all, --emulator, --system or --from-md5", [ - message for on, message in mode_conflicts( - argparse.Namespace(platform=None, all=False, emulator=None, system=None, - standalone=False), - (("--from-md5", False),), - ) if on - ]) - for script in ("verify.py", "generate_pack.py"): - self.assertIn("mode_conflicts(args", script_source(script), script) - - # BizHawk scraper tests - - def test_150_bizhawk_scraper_parse_firmware_and_option(self): - """Parse FirmwareAndOption() one-liner pattern.""" - from scraper.bizhawk_scraper import parse_firmware_database - - fragment = """ - FirmwareAndOption("DBEBD76A448447CB6E524AC3CB0FD19FC065D944", 256, "32X", "G", "32X_G_BIOS.BIN", "32x 68k BIOS"); - FirmwareAndOption("1E5B0B2441A4979B6966D942B20CC76C413B8C5E", 2048, "32X", "M", "32X_M_BIOS.BIN", "32x SH2 MASTER BIOS"); - """ - records, files = parse_firmware_database(fragment) - self.assertEqual(len(records), 2) - self.assertEqual(records[0]["system"], "32X") - self.assertEqual(records[0]["firmware_id"], "G") - self.assertEqual(records[0]["sha1"], "DBEBD76A448447CB6E524AC3CB0FD19FC065D944") - self.assertEqual(records[0]["name"], "32X_G_BIOS.BIN") - self.assertEqual(records[0]["size"], 256) - - def test_151_bizhawk_scraper_parse_variable_refs(self): - """Parse var = File() + Firmware() + Option() pattern.""" - from scraper.bizhawk_scraper import parse_firmware_database - - fragment = """ - var gbaNormal = File("300C20DF6731A33952DED8C436F7F186D25D3492", 16384, "GBA_bios.rom", "Bios (World)"); - Firmware("GBA", "Bios", "Bios"); - Option("GBA", "Bios", in gbaNormal, FirmwareOptionStatus.Ideal); - """ - records, files = parse_firmware_database(fragment) - self.assertEqual(len(records), 1) - self.assertEqual(records[0]["system"], "GBA") - self.assertEqual(records[0]["sha1"], "300C20DF6731A33952DED8C436F7F186D25D3492") - self.assertEqual(records[0]["name"], "GBA_bios.rom") - self.assertEqual(records[0]["status"], "Ideal") - - def test_152_bizhawk_scraper_skips_comments(self): - """Commented-out blocks (PS2) are skipped.""" - from scraper.bizhawk_scraper import parse_firmware_database - - fragment = """ - FirmwareAndOption("DBEBD76A448447CB6E524AC3CB0FD19FC065D944", 256, "32X", "G", "32X_G_BIOS.BIN", "32x 68k BIOS"); - /* - Firmware("PS2", "BIOS", "PS2 Bios"); - Option("PS2", "BIOS", File("FBD54BFC020AF34008B317DCB80B812DD29B3759", 4194304, "ps2.bin", "PS2 Bios")); - */ - """ - records, files = parse_firmware_database(fragment) - systems = {r["system"] for r in records} - self.assertNotIn("PS2", systems) - self.assertEqual(len(records), 1) - - def test_152b_bizhawk_scraper_skips_line_comments(self): - """FirmwareDatabase.cs 2.11.1 comments out two MSX options with //: - read as live, they were listed required.""" - from scraper.bizhawk_scraper import parse_firmware_database - - fragment = """ - FirmwareAndOption("DBEBD76A448447CB6E524AC3CB0FD19FC065D944", 256, "32X", "G", "32X_G_BIOS.BIN", "see http://x"); - //FirmwareAndOption("E998F0C441F4F1800EF44E42CD1659150206CF79", 32768, "MSX", "bios_pal", "MSX_8020-20bios.rom", "MSX"); - """ - records, _ = parse_firmware_database(fragment) - self.assertEqual([r["name"] for r in records], ["32X_G_BIOS.BIN"]) - - def test_153_bizhawk_scraper_arithmetic_size(self): - """Size expressions like 4 * 1024 * 1024 are evaluated.""" - from scraper.bizhawk_scraper import parse_firmware_database - - fragment = """ - FirmwareAndOption("BF861922DCB78C316360E3E742F4F70FF63C9BC3", 4 * 1024 * 1024, "N64DD", "IPL_JPN", "64DD_IPL.bin", "N64DD JPN IPL"); - """ - records, _ = parse_firmware_database(fragment) - self.assertEqual(records[0]["size"], 4194304) - - def test_154_bizhawk_scraper_dummy_hash(self): - """SHA1Checksum.Dummy entries get no sha1 field.""" - from scraper.bizhawk_scraper import parse_firmware_database - - fragment = """ - FirmwareAndOption(SHA1Checksum.Dummy, 0, "3DS", "aes_keys", "aes_keys.txt", "AES Keys"); - """ - records, _ = parse_firmware_database(fragment) - self.assertEqual(len(records), 1) - self.assertIsNone(records[0]["sha1"]) - - def test_155_bizhawk_scraper_multi_option_picks_ideal(self): - """When multiple options exist, Ideal is selected as canonical.""" - from scraper.bizhawk_scraper import parse_firmware_database - - fragment = """ - var ss_100_j = File("2B8CB4F87580683EB4D760E4ED210813D667F0A2", 524288, "SAT_1.00-(J).bin", "Bios v1.00 (J)"); - var ss_101_j = File("DF94C5B4D47EB3CC404D88B33A8FDA237EAF4720", 524288, "SAT_1.01-(J).bin", "Bios v1.01 (J)"); - Firmware("SAT", "J", "Bios (J)"); - Option("SAT", "J", in ss_100_j); - Option("SAT", "J", in ss_101_j, FirmwareOptionStatus.Ideal); - """ - records, _ = parse_firmware_database(fragment) - self.assertEqual(len(records), 1) - self.assertEqual(records[0]["sha1"], "DF94C5B4D47EB3CC404D88B33A8FDA237EAF4720") - self.assertEqual(records[0]["name"], "SAT_1.01-(J).bin") - - def test_156_bizhawk_scraper_is_bad_excluded(self): - """Files with isBad: true are not selected as canonical.""" - from scraper.bizhawk_scraper import parse_firmware_database - - fragment = """ - var good = File("AAAA", 100, "good.bin", "Good"); - var bad = File("BBBB", 100, "bad.bin", "Bad", isBad: true); - Firmware("TEST", "X", "Test"); - Option("TEST", "X", in bad); - Option("TEST", "X", in good, FirmwareOptionStatus.Ideal); - """ - records, _ = parse_firmware_database(fragment) - self.assertEqual(records[0]["name"], "good.bin") - - def test_157_path_conflict_helpers(self): - """has_path_conflict detects file/directory naming collisions.""" - from packs.paths import has_path_conflict, register_path - - seen_files: set[str] = set() - seen_parents: set[str] = set() - - # Register system/SGB1.sfc as a file - register_path("system/SGB1.sfc", seen_files, seen_parents) - - # Adding system/SGB1.sfc/program.rom should conflict (parent is a file) - self.assertTrue( - has_path_conflict("system/SGB1.sfc/program.rom", seen_files, seen_parents) - ) - - # Adding system/other.bin should not conflict - self.assertFalse( - has_path_conflict("system/other.bin", seen_files, seen_parents) - ) - - # Reverse: register a nested path first, then check flat - seen_files2: set[str] = set() - seen_parents2: set[str] = set() - register_path("system/SGB2.sfc/program.rom", seen_files2, seen_parents2) - - # Adding system/SGB2.sfc as a file should conflict (it's a directory) - self.assertTrue( - has_path_conflict("system/SGB2.sfc", seen_files2, seen_parents2) - ) - - # Adding system/SGB2.sfc/boot.rom should not conflict (sibling in same dir) - self.assertFalse( - has_path_conflict("system/SGB2.sfc/boot.rom", seen_files2, seen_parents2) - ) - - def test_158_pack_skips_file_directory_conflict(self): - """Pack generation skips entries that conflict with existing paths.""" - from packs.platformpack import generate_pack - - output_dir = os.path.join(self.root, "pack_conflict") - os.makedirs(output_dir, exist_ok=True) - - # Platform declares SGB1.sfc as a flat file - config = { - "platform": "ConflictTest", - "verification_mode": "existence", - "base_destination": "system", - "systems": { - "test-sys": { - "files": [ - { - "name": "present_req.bin", - "destination": "present_req.bin", - "required": True, - }, - ], - }, - }, - } - with open(os.path.join(self.platforms_dir, "test_conflict.yml"), "w") as fh: - yaml.dump(config, fh) - - # Create an emulator profile with a nested path that conflicts - emu = { - "emulator": "ConflictCore", - "type": "libretro", - "systems": ["test-sys"], - "files": [ - {"name": "present_req.bin/nested.rom", "required": False}, - ], - } - with open(os.path.join(self.emulators_dir, "conflict_core.yml"), "w") as fh: - yaml.dump(emu, fh) - - zip_path = generate_pack( - "test_conflict", - self.platforms_dir, - self.db, - self.bios_dir, - output_dir, - emulators_dir=self.emulators_dir, - offline=True, - ) - self.assertIsNotNone(zip_path) - with zipfile.ZipFile(zip_path) as zf: - names = zf.namelist() - # Flat file should be present - self.assertTrue( - any("present_req.bin" in n and "/" + "nested" not in n for n in names) - ) - # Nested conflict should NOT be present - self.assertFalse(any("nested.rom" in n for n in names)) - - # --------------------------------------------------------------- - # Archive cross-reference and descriptive name tests - # --------------------------------------------------------------- - - def test_159_cross_ref_archive_in_repo(self): - """Archived files group by archive, in_repo=True when archive exists.""" - config = load_platform_config("test_existence", self.platforms_dir) - profiles = load_emulator_profiles(self.emulators_dir) - undeclared = find_undeclared_files( - config, self.emulators_dir, self.db, profiles - ) - # test_archive.zip should appear as a single grouped entry - archive_entries = [ - u for u in undeclared if u.get("archive") == "test_archive.zip" - ] - self.assertEqual(len(archive_entries), 1) - entry = archive_entries[0] - self.assertTrue(entry["in_repo"]) - self.assertEqual(entry["name"], "test_archive.zip") - self.assertEqual(entry["archive_file_count"], 2) - self.assertTrue(entry["required"]) # at least one file is required - - def test_160_cross_ref_archive_missing(self): - """Missing archive reported as single entry with in_repo=False.""" - config = load_platform_config("test_existence", self.platforms_dir) - profiles = load_emulator_profiles(self.emulators_dir) - undeclared = find_undeclared_files( - config, self.emulators_dir, self.db, profiles - ) - missing_entries = [ - u for u in undeclared if u.get("archive") == "missing_archive.zip" - ] - self.assertEqual(len(missing_entries), 1) - entry = missing_entries[0] - self.assertFalse(entry["in_repo"]) - self.assertEqual(entry["name"], "missing_archive.zip") - self.assertEqual(entry["archive_file_count"], 1) - - def test_161_cross_ref_archive_not_individual_roms(self): - """Individual ROM names from archived files should NOT appear as separate entries.""" - config = load_platform_config("test_existence", self.platforms_dir) - profiles = load_emulator_profiles(self.emulators_dir) - undeclared = find_undeclared_files( - config, self.emulators_dir, self.db, profiles - ) - names = {u["name"] for u in undeclared} - # Individual ROMs should NOT be in the undeclared list - self.assertNotIn("rom_a.bin", names) - self.assertNotIn("rom_b.bin", names) - self.assertNotIn("missing_rom.bin", names) - - def test_162_cross_ref_descriptive_name_resolved_by_path(self): - """Descriptive name with path: fallback resolves via path basename.""" - config = load_platform_config("test_existence", self.platforms_dir) - profiles = load_emulator_profiles(self.emulators_dir) - undeclared = find_undeclared_files( - config, self.emulators_dir, self.db, profiles - ) - desc_entries = { - u["name"]: u for u in undeclared if u["emulator"] == "TestDescriptive" - } - # "Descriptive BIOS Name" has path: "present_req.bin" which IS in by_name - self.assertIn("Descriptive BIOS Name", desc_entries) - self.assertTrue(desc_entries["Descriptive BIOS Name"]["in_repo"]) - # "Missing Descriptive" has path: "nonexistent_path.bin" which is NOT in by_name - self.assertIn("Missing Descriptive", desc_entries) - self.assertFalse(desc_entries["Missing Descriptive"]["in_repo"]) - - def test_163_cross_ref_archive_declared_by_platform_skipped(self): - """Archive files whose archive is declared by platform are skipped.""" - # Create a platform that declares test_archive.zip - config = { - "platform": "TestArchivePlatform", - "verification_mode": "existence", - "systems": { - "console-a": { - "files": [ - { - "name": "test_archive.zip", - "destination": "test_archive.zip", - "required": True, - }, - ], - }, - }, - } - with open( - os.path.join(self.platforms_dir, "test_archive_platform.yml"), "w" - ) as fh: - yaml.dump(config, fh) - config = load_platform_config("test_archive_platform", self.platforms_dir) - profiles = load_emulator_profiles(self.emulators_dir) - undeclared = find_undeclared_files( - config, self.emulators_dir, self.db, profiles - ) - # test_archive.zip is declared ->its archived ROMs should be skipped - archive_entries = [ - u for u in undeclared if u.get("archive") == "test_archive.zip" - ] - self.assertEqual(len(archive_entries), 0) - - def test_164_pack_extras_use_archive_name(self): - """Pack extras for archived files use archive name, not individual ROM.""" - from packs.extras import collect_emulator_extras - - config = load_platform_config("test_existence", self.platforms_dir) - profiles = load_emulator_profiles(self.emulators_dir) - extras = collect_emulator_extras( - config, - self.emulators_dir, - self.db, - set(), - "", - profiles, - ) - extra_names = {e["name"] for e in extras} - # Archive name should be present, not individual ROMs - self.assertIn("test_archive.zip", extra_names) - self.assertNotIn("rom_a.bin", extra_names) - self.assertNotIn("rom_b.bin", extra_names) - # Missing archive should NOT be in extras (in_repo=False) - self.assertNotIn("missing_archive.zip", extra_names) - - def test_165_pack_extras_multi_dest_cross_ref(self): - """Same file at different paths from two profiles produces both destinations.""" - from packs.extras import collect_emulator_extras - - config = load_platform_config("test_existence", self.platforms_dir) - profiles = load_emulator_profiles(self.emulators_dir) - extras = collect_emulator_extras( - config, - self.emulators_dir, - self.db, - set(), - "", - profiles, - ) - extra_dests = {e["destination"] for e in extras} - # Root destination (from test_emu or test_root_core, no path) - self.assertIn("present_req.bin", extra_dests) - # Subdirectory destination (from test_subdir_core) - self.assertIn("subcore/bios/present_req.bin", extra_dests) - - def test_166_pack_extras_multi_dest_platform_declared(self): - """Profile with path different from platform destination adds alternative.""" - from packs.extras import collect_emulator_extras - - config = load_platform_config("test_existence", self.platforms_dir) - profiles = load_emulator_profiles(self.emulators_dir) - # Simulate platform already having present_req.bin at root - seen = {"present_req.bin"} - extras = collect_emulator_extras( - config, - self.emulators_dir, - self.db, - seen, - "", - profiles, - ) - extra_dests = {e["destination"] for e in extras} - # Root is already in pack (in seen), should NOT be duplicated - self.assertNotIn("present_req.bin", extra_dests) - # Subdirectory destination should be added - self.assertIn("subcore/bios/present_req.bin", extra_dests) - - def test_167_resolve_local_file_data_dir_fallback(self): - """resolve_local_file finds files in data directories when not in bios/.""" - data_dir = os.path.join(self.root, "data", "test-data") - os.makedirs(data_dir, exist_ok=True) - data_file = os.path.join(data_dir, "data_only.bin") - with open(data_file, "wb") as f: - f.write(b"DATA_DIR_CONTENT") - - registry = {"test-data": {"local_cache": data_dir}} - - fe = {"name": "data_only.bin"} - path, status = resolve_local_file(fe, self.db, data_dir_registry=registry) - self.assertIsNotNone(path) - self.assertEqual(os.path.basename(path), "data_only.bin") - self.assertEqual(status, "data_dir") - - def test_167b_unsourceable_skips_data_dir_name_match(self): - """The cache walk matches on filename, so unsourceable has to skip it.""" - data_dir = os.path.join(self.root, "data", "other-core") - os.makedirs(data_dir, exist_ok=True) - with open(os.path.join(data_dir, "shared_name.dat"), "wb") as f: - f.write(b"ANOTHER CORE DEFINITIONS") - - registry = {"other-core": {"local_cache": data_dir}} - - fe = {"name": "shared_name.dat", "unsourceable": "ships inside the package"} - path, status = resolve_local_file(fe, self.db, data_dir_registry=registry) - self.assertIsNone(path) - self.assertEqual(status, "not_found") - - # A declared hash is content proof, so the cache still answers for it. - import hashlib - - digest = hashlib.sha1(b"ANOTHER CORE DEFINITIONS").hexdigest() - fe = { - "name": "shared_name.dat", - "sha1": digest, - "unsourceable": "ships inside the package", - } - path, status = resolve_local_file(fe, self.db, data_dir_registry=registry) - self.assertIsNotNone(path) - self.assertEqual(status, "data_dir_hash_exact") - - def test_168_generate_truth_basic(self): - """generate_platform_truth resolves cores and builds system truth.""" - import yaml as _yaml - - profile = { - "emulator": "TestCore", - "type": "libretro", - "systems": ["test-system"], - "cores": ["testcore"], - "files": [ - { - "name": "bios.bin", - "system": "test-system", - "required": True, - "sha1": "aabbccdd" * 5, - "md5": "11223344" * 4, - "size": 1024, - "path": "TestConsole/bios.bin", - "source_ref": "main.cpp:42", - }, - ], - } - profile_path = os.path.join(self.emulators_dir, "testcore.yml") - with open(profile_path, "w") as f: - _yaml.dump(profile, f) - - # Clear profile cache so fresh load picks up our file - from model.profiles import emulator_profiles_cache - - emulator_profiles_cache.clear() - - profiles = load_emulator_profiles(self.emulators_dir) - config = {"cores": ["testcore"]} - - result = generate_platform_truth( - "testplat", - config, - {}, - profiles, - db=None, - data_registry={}, - ) - - self.assertEqual(result["platform"], "testplat") - self.assertTrue(result["generated"]) - self.assertIn("test-system", result["systems"]) - sys_files = result["systems"]["test-system"]["files"] - self.assertEqual(len(sys_files), 1) - fe = sys_files[0] - self.assertEqual(fe["name"], "bios.bin") - self.assertTrue(fe["required"]) - self.assertEqual(fe["sha1"], "aabbccdd" * 5) - self.assertIn("testcore", fe["_cores"]) - self.assertIn("main.cpp:42", fe["_source_refs"]) - - def test_169_generate_truth_mode_filtering(self): - """generate_platform_truth excludes standalone-only files for all_libretro.""" - import yaml as _yaml - from model.profiles import emulator_profiles_cache - - profile = { - "emulator": "DualMode", - "type": "standalone + libretro", - "systems": ["test-system"], - "cores": ["dualmode"], - "files": [ - { - "name": "both.bin", - "system": "test-system", - "required": True, - "mode": "both", - "sha1": "aaaa", - }, - { - "name": "lr_only.bin", - "system": "test-system", - "required": True, - "mode": "libretro", - "sha1": "bbbb", - }, - { - "name": "sa_only.bin", - "system": "test-system", - "required": True, - "mode": "standalone", - "sha1": "cccc", - }, - {"name": "nomode.bin", "system": "test-system", "required": True, "sha1": "dddd"}, - ], - } - with open(os.path.join(self.emulators_dir, "dualmode.yml"), "w") as f: - _yaml.dump(profile, f) - - emulator_profiles_cache.clear() - profiles = load_emulator_profiles(self.emulators_dir) - config = {"cores": "all_libretro"} - - result = generate_platform_truth("testplat", config, {}, profiles, data_registry={}) - names = {fe["name"] for fe in result["systems"]["test-system"]["files"]} - - self.assertIn("both.bin", names) - self.assertIn("lr_only.bin", names) - self.assertIn("nomode.bin", names) - self.assertNotIn("sa_only.bin", names) - - def test_170_generate_truth_standalone_cores(self): - """generate_platform_truth uses standalone mode for standalone_cores.""" - import yaml as _yaml - from model.profiles import emulator_profiles_cache - - profile = { - "emulator": "DualCore", - "type": "standalone + libretro", - "systems": ["test-system"], - "cores": ["dualcore"], - "files": [ - { - "name": "lr_file.bin", - "system": "test-system", - "required": True, - "mode": "libretro", - "sha1": "aaaa", - }, - { - "name": "sa_file.bin", - "system": "test-system", - "required": True, - "mode": "standalone", - "sha1": "bbbb", - }, - ], - } - with open(os.path.join(self.emulators_dir, "dualcore.yml"), "w") as f: - _yaml.dump(profile, f) - - emulator_profiles_cache.clear() - profiles = load_emulator_profiles(self.emulators_dir) - config = { - "cores": ["dualcore"], - "standalone_cores": ["dualcore"], - } - - result = generate_platform_truth("testplat", config, {}, profiles, data_registry={}) - names = {fe["name"] for fe in result["systems"]["test-system"]["files"]} - - self.assertIn("sa_file.bin", names) - self.assertNotIn("lr_file.bin", names) - - def test_171_generate_truth_dedup_required_wins(self): - """Dedup merges cores and required=True wins over required=False.""" - import yaml as _yaml - from model.profiles import emulator_profiles_cache - - core_a = { - "emulator": "CoreA", - "type": "libretro", - "systems": ["test-system"], - "cores": ["core_a"], - "files": [ - { - "name": "shared.bin", - "system": "test-system", - "required": False, - "source_ref": "a.cpp:10", - "sha1": "aaaa", - }, - ], - } - core_b = { - "emulator": "CoreB", - "type": "libretro", - "systems": ["test-system"], - "cores": ["core_b"], - "files": [ - { - "name": "shared.bin", - "system": "test-system", - "required": True, - "source_ref": "b.cpp:20", - "sha1": "aaaa", - }, - ], - } - for name, data in [("core_a", core_a), ("core_b", core_b)]: - with open(os.path.join(self.emulators_dir, f"{name}.yml"), "w") as f: - _yaml.dump(data, f) - - emulator_profiles_cache.clear() - profiles = load_emulator_profiles(self.emulators_dir) - config = {"cores": ["core_a", "core_b"]} - - result = generate_platform_truth("testplat", config, {}, profiles, data_registry={}) - sys_files = result["systems"]["test-system"]["files"] - self.assertEqual(len(sys_files), 1) - - fe = sys_files[0] - self.assertEqual(fe["name"], "shared.bin") - self.assertTrue(fe["required"]) - self.assertIn("core_a", fe["_cores"]) - self.assertIn("core_b", fe["_cores"]) - self.assertIn("a.cpp:10", fe["_source_refs"]) - self.assertIn("b.cpp:20", fe["_source_refs"]) - - def test_172_generate_truth_coverage_metadata(self): - """Coverage tracks profiled vs unprofiled cores.""" - import yaml as _yaml - from model.profiles import emulator_profiles_cache - - profile = { - "emulator": "ProfiledCore", - "type": "libretro", - "systems": ["test-system"], - "cores": ["profiled_core"], - "files": [ - {"name": "fw.bin", "system": "test-system", "required": True}, - ], - } - with open(os.path.join(self.emulators_dir, "profiled_core.yml"), "w") as f: - _yaml.dump(profile, f) - - emulator_profiles_cache.clear() - profiles = load_emulator_profiles(self.emulators_dir) - config = {"cores": ["profiled_core", "unprofiled_core"]} - - result = generate_platform_truth("testplat", config, {}, profiles, data_registry={}) - cov = result["_coverage"] - - self.assertEqual(cov["cores_profiled"], 1) - self.assertNotIn( - "unprofiled_core", [name for name in profiles if name == "unprofiled_core"] - ) - # unprofiled_core has no profile YAML so resolve_platform_cores - # won't include it, so cores_resolved reflects only matched profiles - self.assertEqual(cov["cores_resolved"], 1) - self.assertNotIn("unprofiled_core", cov["cores_unprofiled"]) - - def test_90_registry_install_metadata(self): - """Registry install section is accessible.""" - import yaml - - with open("platforms/_registry.yml") as f: - registry = yaml.safe_load(f) - for name in ( - "retroarch", - "batocera", - "emudeck", - "recalbox", - "retrobat", - "retrodeck", - "lakka", - "romm", - "bizhawk", - ): - plat = registry["platforms"][name] - self.assertIn("install", plat, f"{name} missing install section") - self.assertIn("detect", plat["install"]) - self.assertIsInstance(plat["install"]["detect"], list) - for hint in plat["install"]["detect"]: - self.assertIn("os", hint) - # EmuDeck has standalone_copies - self.assertIn( - "standalone_copies", - registry["platforms"]["emudeck"]["install"], - ) - - def test_91_manifest_required_only_drops_optional_files(self): - """A manifest named _required must hold only the required files. - - The filename carried the narrowing while the content did not, so - install.py fetched every optional file for a user who asked for the - required set, and --all-variants wrote three manifests that duplicated - their non-required twins. - """ - from packs.manifest import generate_manifest - - registry_path = os.path.join(self.platforms_dir, "_test_registry.yml") - with open(registry_path, "w") as fh: - yaml.dump({"platforms": {"test_existence": {"install": {}}}}, fh) - - def names(required_only): - manifest = generate_manifest( - "test_existence", - self.platforms_dir, - self.db, - self.bios_dir, - registry_path, - emulators_dir=self.emulators_dir, - offline=True, - required_only=required_only, - ) - return {entry["dest"] for entry in manifest["files"]} - - every = names(False) - required = names(True) - self.assertIn("present_req.bin", every) - self.assertIn("present_opt.bin", every) - self.assertIn("present_req.bin", required) - self.assertNotIn( - "present_opt.bin", - required, - "an optional file reached a manifest built with required_only", - ) - - def test_91_generate_manifest(self): - """generate_manifest returns valid manifest dict with expected fields.""" - from packs.manifest import generate_manifest - - # Create a minimal registry file for the test - registry_path = os.path.join(self.platforms_dir, "_test_registry.yml") - registry_data = { - "platforms": { - "test_existence": { - "install": { - "detect": [ - { - "os": "linux", - "method": "path_exists", - "path": "/test/bios", - } - ], - }, - }, - }, - } - with open(registry_path, "w") as fh: - yaml.dump(registry_data, fh) - - manifest = generate_manifest( - "test_existence", - self.platforms_dir, - self.db, - self.bios_dir, - registry_path, - emulators_dir=self.emulators_dir, - offline=True, - ) - - self.assertEqual(manifest["manifest_version"], 2) - self.assertEqual(manifest["regions"], []) - self.assertEqual(manifest["platform"], "test_existence") - self.assertEqual(manifest["display_name"], "TestExistence") - self.assertIn("generated", manifest) - self.assertIn("files", manifest) - self.assertIsInstance(manifest["files"], list) - self.assertEqual(manifest["total_files"], len(manifest["files"])) - self.assertEqual(manifest["total_omitted"], len(manifest["omitted_files"])) - self.assertGreater(len(manifest["files"]), 0) - self.assertEqual(manifest["base_destination"], "system") - self.assertEqual( - manifest["detect"], - registry_data["platforms"]["test_existence"]["install"]["detect"], - ) - - for f in manifest["files"]: - self.assertIn("dest", f) - self.assertIn("sha1", f) - self.assertIn("size", f) - self.assertIn("repo_path", f) - self.assertIn("cores", f) - self.assertIsInstance(f["size"], int) - self.assertGreater(len(f["sha1"]), 0) - - def test_91_manifest_version_is_the_platform_list_version(self): - """The manifest names the version of the list it was built from. - - It was the constant "1.0" for every platform, so the installer could - not tell which Batocera or Recalbox release a list described. Two - platforms of different versions show the value comes from each YAML. - A YAML without one, an inheriting child included, is refused rather - than written with a stand-in or its parent's version. - """ - from model.platforms import _platform_config_cache - from packs.manifest import generate_manifest - - registry_path = os.path.join(self.platforms_dir, "_test_registry_version.yml") - with open(registry_path, "w") as fh: - yaml.dump({"platforms": {}}, fh) - with open(os.path.join(self.platforms_dir, "test_md5.yml")) as fh: - config = yaml.safe_load(fh) - config["version"] = "41" - with open(os.path.join(self.platforms_dir, "versioned_md5.yml"), "w") as fh: - yaml.dump(config, fh) - del config["version"] - with open(os.path.join(self.platforms_dir, "unversioned.yml"), "w") as fh: - yaml.dump(config, fh) - _platform_config_cache.clear() - - def version_of(name: str) -> str: - return generate_manifest( - name, self.platforms_dir, self.db, self.bios_dir, registry_path, - emulators_dir=self.emulators_dir, offline=True, - )["version"] - - self.assertEqual(version_of("test_existence"), "9.1") - self.assertEqual(version_of("versioned_md5"), "41") - for name in ("unversioned", "test_inherited"): - with self.subTest(platform=name), \ - self.assertRaisesRegex(ValueError, "records no version"): - version_of(name) - with open(os.path.join(self.platforms_dir, "test_inherited.yml")) as fh: - child = yaml.safe_load(fh) - child["version"] = "2" - with open(os.path.join(self.platforms_dir, "test_inherited.yml"), "w") as fh: - yaml.dump(child, fh) - _platform_config_cache.clear() - self.assertEqual(version_of("test_inherited"), "2") - - def test_91b_manifest_hash_points_at_a_fetchable_file(self): - """A declared hash no local file carries must not blank repo_path. - - install.py builds its download URL from repo_path, so an upstream - hash that resolves to nothing leaves the file unfetchable. - """ - from packs.manifest import generate_manifest - - registry_path = os.path.join(self.platforms_dir, "_test_registry2.yml") - with open(registry_path, "w") as fh: - yaml.dump({"platforms": {"test_existence": {"install": {}}}}, fh) - - config_path = os.path.join(self.platforms_dir, "test_existence.yml") - with open(config_path) as fh: - config = yaml.safe_load(fh) - for system in config.get("systems", {}).values(): - for entry in system.get("files", []): - entry["sha1"] = "0" * 40 # upstream hash, absent from the repo - with open(config_path, "w") as fh: - yaml.dump(config, fh) - from model.platforms import _platform_config_cache - - _platform_config_cache.clear() - - manifest = generate_manifest( - "test_existence", - self.platforms_dir, - self.db, - self.bios_dir, - registry_path, - emulators_dir=self.emulators_dir, - offline=True, - ) - - self.assertGreater(len(manifest["files"]), 0) - self.assertGreater(len(manifest["omitted_files"]), 0) - self.assertTrue( - all( - entry["reason"] in {"hash_mismatch", "not_found"} - for entry in manifest["omitted_files"] - if entry["cores"] is None - ) - ) - for f in manifest["files"]: - if f.get("release_asset"): - continue - self.assertTrue( - f["repo_path"], - f"{f['dest']} has no repo_path, install.py cannot fetch it", - ) - self.assertNotEqual(f["sha1"], "0" * 40) - - def test_92_manifest_matches_zip(self): - """Manifest file destinations match ZIP contents (excluding metadata).""" - from packs.manifest import generate_manifest - from packs.platformpack import generate_pack - - registry_path = os.path.join(self.platforms_dir, "_test_registry.yml") - registry_data = { - "platforms": { - "test_existence": { - "install": {"detect": []}, - }, - }, - } - with open(registry_path, "w") as fh: - yaml.dump(registry_data, fh) - - # Generate ZIP - output_dir = os.path.join(self.root, "pack_manifest_cmp") - os.makedirs(output_dir, exist_ok=True) - zip_path = generate_pack( - "test_existence", - self.platforms_dir, - self.db, - self.bios_dir, - output_dir, - emulators_dir=self.emulators_dir, - offline=True, - ) - self.assertIsNotNone(zip_path) - - # Get ZIP file destinations (exclude metadata) - with zipfile.ZipFile(zip_path) as zf: - zip_names = { - n - for n in zf.namelist() - if not n.rsplit("/", 1)[-1].startswith(("INSTRUCTIONS_", "RENAMED_")) - and n != "manifest.json" - and n != "README.txt" - } - - # Generate manifest - manifest = generate_manifest( - "test_existence", - self.platforms_dir, - self.db, - self.bios_dir, - registry_path, - emulators_dir=self.emulators_dir, - offline=True, - ) - # Detect flat vs nested ZIP to build expected paths - base = manifest.get("base_destination", "") - is_flat = bool(base) and not any( - n.startswith(base + "/") for n in zip_names - ) - manifest_dests = set() - for f in manifest["files"]: - if base and not is_flat: - d = f"{base}/{f['dest']}" - else: - d = f["dest"] - manifest_dests.add(d) - - self.assertEqual(manifest_dests, zip_names) - - # --------------------------------------------------------------- - # install.py tests - # --------------------------------------------------------------- - - def test_93_parse_retroarch_cfg(self): - """Parse system_directory from retroarch.cfg.""" - from install import _parse_retroarch_system_dir - - cfg = os.path.join(self.root, "retroarch.cfg") - # Quoted absolute path - with open(cfg, "w") as f: - f.write('system_directory = "/home/user/ra/system"\n') - result = _parse_retroarch_system_dir(Path(cfg)) - self.assertEqual(result, Path("/home/user/ra/system")) - # Default value - with open(cfg, "w") as f: - f.write('system_directory = "default"\n') - result = _parse_retroarch_system_dir(Path(cfg)) - self.assertEqual(result, Path(self.root) / "system") - # Unquoted - with open(cfg, "w") as f: - f.write("system_directory = /tmp/ra_system\n") - result = _parse_retroarch_system_dir(Path(cfg)) - self.assertEqual(result, Path("/tmp/ra_system")) - - def test_94_parse_emudeck_settings(self): - """Parse emulationPath from EmuDeck settings.sh.""" - from install import _parse_bash_var - - settings = os.path.join(self.root, "settings.sh") - with open(settings, "w") as f: - f.write( - 'emulationPath="/home/deck/Emulation"\nromsPath="/home/deck/Emulation/roms"\n' - ) - result = _parse_bash_var(Path(settings), "emulationPath") - self.assertEqual(result, "/home/deck/Emulation") - - def test_95_parse_ps1_var(self): - """Parse $emulationPath from EmuDeck settings.ps1.""" - from install import _parse_ps1_var - - settings = os.path.join(self.root, "settings.ps1") - with open(settings, "w") as f: - f.write('$emulationPath="C:\\Emulation"\n') - result = _parse_ps1_var(Path(settings), "$emulationPath") - self.assertEqual(result, "C:\\Emulation") - - def test_96_target_filtering(self): - """--target filters files by cores field.""" - from install import _filter_by_target - - files = [ - {"dest": "a.bin", "cores": None}, - {"dest": "b.bin", "cores": ["flycast", "redream"]}, - {"dest": "c.bin", "cores": ["dolphin"]}, - ] - filtered = _filter_by_target(files, ["flycast", "snes9x"]) - dests = [f["dest"] for f in filtered] - self.assertIn("a.bin", dests) - self.assertIn("b.bin", dests) - self.assertNotIn("c.bin", dests) - - def test_97_standalone_copies(self): - """Standalone keys copied to existing emulator dirs.""" - from install import do_standalone_copies - - bios_dir = Path(self.root) / "bios" - bios_dir.mkdir(exist_ok=True) - (bios_dir / "prod.keys").write_bytes(b"KEYS") - yuzu_dir = Path(self.root) / "yuzu_keys" - yuzu_dir.mkdir() - missing_dir = Path(self.root) / "nonexistent" - manifest = { - "base_destination": "bios", - "files": [{"dest": "prod.keys"}], - "standalone_copies": [ - { - "file": "prod.keys", - "targets": {"linux": [str(yuzu_dir), str(missing_dir)]}, - } - ], - } - copied, skipped, _ = do_standalone_copies(manifest, bios_dir, "linux") - self.assertEqual(copied, 1) - self.assertEqual(skipped, 1) - self.assertTrue((yuzu_dir / "prod.keys").exists()) - self.assertFalse((missing_dir / "prod.keys").exists()) - - # --------------------------------------------------------------- - # diff_platform_truth tests - # --------------------------------------------------------------- - - def test_98_diff_truth_missing(self): - """Truth has 2 files, scraped has 1 -> 1 missing with cores/source_refs.""" - truth = { - "systems": { - "test-sys": { - "_coverage": {"cores_profiled": ["core_a"], "cores_unprofiled": []}, - "files": [ - { - "name": "bios_a.bin", - "required": True, - "md5": "aaa", - "_cores": ["core_a"], - "_source_refs": ["src/a.c:10"], - }, - { - "name": "bios_b.bin", - "required": False, - "md5": "bbb", - "_cores": ["core_a"], - "_source_refs": ["src/b.c:20"], - }, - ], - } - } - } - scraped = { - "systems": { - "test-sys": { - "files": [{"name": "bios_a.bin", "md5": "aaa"}], - } - } - } - result = diff_platform_truth(truth, scraped) - self.assertEqual(result["summary"]["total_missing"], 1) - div = result["divergences"]["test-sys"] - self.assertEqual(len(div["missing"]), 1) - m = div["missing"][0] - self.assertEqual(m["name"], "bios_b.bin") - self.assertEqual(m["cores"], ["core_a"]) - self.assertEqual(m["source_refs"], ["src/b.c:20"]) - - def test_99_diff_truth_extra_phantom(self): - """All cores profiled, scraped has extra file -> extra_phantom.""" - truth = { - "systems": { - "test-sys": { - "_coverage": {"cores_profiled": ["core_a"], "cores_unprofiled": []}, - "files": [ - { - "name": "bios.bin", - "md5": "aaa", - "_cores": ["core_a"], - "_source_refs": [], - }, - ], - } - } - } - scraped = { - "systems": { - "test-sys": { - "files": [ - {"name": "bios.bin", "md5": "aaa"}, - {"name": "phantom.bin", "md5": "zzz"}, - ], - } - } - } - result = diff_platform_truth(truth, scraped) - self.assertEqual(result["summary"]["total_extra_phantom"], 1) - div = result["divergences"]["test-sys"] - self.assertEqual(len(div["extra_phantom"]), 1) - self.assertEqual(div["extra_phantom"][0]["name"], "phantom.bin") - - def test_100_diff_truth_extra_unprofiled(self): - """Some cores unprofiled, scraped has extra -> extra_unprofiled.""" - truth = { - "systems": { - "test-sys": { - "_coverage": { - "cores_profiled": ["core_a"], - "cores_unprofiled": ["core_b"], - }, - "files": [ - { - "name": "bios.bin", - "md5": "aaa", - "_cores": ["core_a"], - "_source_refs": [], - }, - ], - } - } - } - scraped = { - "systems": { - "test-sys": { - "files": [ - {"name": "bios.bin", "md5": "aaa"}, - {"name": "extra.bin", "md5": "yyy"}, - ], - } - } - } - result = diff_platform_truth(truth, scraped) - self.assertEqual(result["summary"]["total_extra_unprofiled"], 1) - div = result["divergences"]["test-sys"] - self.assertEqual(len(div["extra_unprofiled"]), 1) - self.assertEqual(div["extra_unprofiled"][0]["name"], "extra.bin") - - def test_101_diff_truth_alias_matching(self): - """Truth file with aliases, scraped uses alias -> not extra or missing.""" - truth = { - "systems": { - "test-sys": { - "_coverage": {"cores_profiled": ["core_a"], "cores_unprofiled": []}, - "files": [ - { - "name": "bios.bin", - "md5": "aaa", - "aliases": ["alt.bin"], - "_cores": ["core_a"], - "_source_refs": [], - }, - ], - } - } - } - scraped = { - "systems": { - "test-sys": { - "files": [{"name": "alt.bin", "md5": "aaa"}], - } - } - } - result = diff_platform_truth(truth, scraped) - self.assertEqual(result["summary"]["total_missing"], 0) - self.assertEqual(result["summary"]["total_extra_phantom"], 0) - self.assertNotIn("test-sys", result.get("divergences", {})) - - def test_102_diff_truth_case_insensitive(self): - """Truth 'BIOS.ROM', scraped 'bios.rom' -> match, no missing.""" - truth = { - "systems": { - "test-sys": { - "_coverage": {"cores_profiled": ["core_a"], "cores_unprofiled": []}, - "files": [ - { - "name": "BIOS.ROM", - "md5": "aaa", - "_cores": ["core_a"], - "_source_refs": [], - }, - ], - } - } - } - scraped = { - "systems": { - "test-sys": { - "files": [{"name": "bios.rom", "md5": "aaa"}], - } - } - } - result = diff_platform_truth(truth, scraped) - self.assertEqual(result["summary"]["total_missing"], 0) - self.assertNotIn("test-sys", result.get("divergences", {})) - - def test_103_diff_truth_hash_mismatch(self): - """Same file, different md5 -> hash_mismatch with truth_cores.""" - truth = { - "systems": { - "test-sys": { - "_coverage": {"cores_profiled": ["core_a"], "cores_unprofiled": []}, - "files": [ - { - "name": "bios.bin", - "md5": "truth_hash", - "_cores": ["core_a", "core_b"], - "_source_refs": ["src/x.c:5"], - }, - ], - } - } - } - scraped = { - "systems": { - "test-sys": { - "files": [{"name": "bios.bin", "md5": "scraped_hash"}], - } - } - } - result = diff_platform_truth(truth, scraped) - self.assertEqual(result["summary"]["total_hash_mismatch"], 1) - div = result["divergences"]["test-sys"] - self.assertEqual(len(div["hash_mismatch"]), 1) - hm = div["hash_mismatch"][0] - self.assertEqual(hm["name"], "bios.bin") - self.assertEqual(hm["truth_cores"], ["core_a", "core_b"]) - self.assertEqual(hm["truth_md5"], "truth_hash") - self.assertEqual(hm["scraped_md5"], "scraped_hash") - - def test_104_diff_truth_normalized_system_ids(self): - """Diff matches systems with different ID formats via normalization.""" - from resolve.platformdiff import diff_platform_truth - - truth = { - "systems": { - "sega-gamegear": { - "_coverage": {"cores_profiled": ["c"], "cores_unprofiled": []}, - "files": [ - { - "name": "bios.gg", - "required": True, - "md5": "a" * 32, - "_cores": ["c"], - "_source_refs": [], - }, - ], - }, - } - } - scraped = { - "systems": { - "sega-game-gear": { - "files": [ - {"name": "bios.gg", "required": True, "md5": "a" * 32}, - ], - }, - } - } - - result = diff_platform_truth(truth, scraped) - self.assertEqual(result["summary"]["systems_uncovered"], 0) - self.assertEqual(result["summary"]["total_missing"], 0) - self.assertEqual(result["summary"]["systems_compared"], 1) - - # --------------------------------------------------------------- - # native_id preservation - # --------------------------------------------------------------- - - def test_native_id_preserved_in_platform_config(self): - """load_platform_config preserves native_id at the system level.""" - config = { - "platform": "TestNativeId", - "verification_mode": "existence", - "base_destination": "system", - "systems": { - "sony-playstation": { - "native_id": "Sony - PlayStation", - "files": [ - { - "name": "scph5501.bin", - "destination": "scph5501.bin", - "required": True, - }, - ], - }, - "nintendo-snes": { - "native_id": "snes", - "files": [ - { - "name": "bs-x.bin", - "destination": "bs-x.bin", - "required": False, - }, - ], - }, - }, - } - with open(os.path.join(self.platforms_dir, "test_native_id.yml"), "w") as fh: - yaml.dump(config, fh) - - loaded = load_platform_config("test_native_id", self.platforms_dir) - psx = loaded["systems"]["sony-playstation"] - self.assertEqual(psx["native_id"], "Sony - PlayStation") - snes = loaded["systems"]["nintendo-snes"] - self.assertEqual(snes["native_id"], "snes") - - # --------------------------------------------------------------- - # Exporter: System.dat round-trip - # --------------------------------------------------------------- - - def test_systemdat_exporter_round_trip(self): - """Export truth data to System.dat and validate round-trip.""" - from exporter import discover_exporters - from exporter.systemdat_exporter import Exporter as SystemDatExporter - - truth = { - "platform": "retroarch", - "systems": { - "sony-playstation": { - "files": [ - { - "name": "scph5501.bin", - "path": "scph5501.bin", - "size": 524288, - "md5": "490f666e1afb15ed6c63b88fc7571f2f", - "sha1": "b056ee5a4d65937e1a3a17e1e78f3258ea49c38e", - "crc32": "71af80b4", - "required": True, - "_cores": ["beetle_psx"], - "_source_refs": ["libretro.c:50"], - }, - ], - }, - }, - } - scraped = { - "systems": { - "sony-playstation": { - "native_id": "Sony - PlayStation", - "files": [ - {"name": "scph5501.bin", "destination": "scph5501.bin"}, - ], - }, - }, - } - - from resolve.reconcile import build_native_model - - systems, report = build_native_model(truth, scraped) - exporter = SystemDatExporter() - produced = exporter.render(systems, report, {}, scraped) - content = produced["System.dat"] - self.assertIn("Sony - PlayStation", content) - self.assertIn("scph5501.bin", content) - self.assertIn("b056ee5a4d65937e1a3a17e1e78f3258ea49c38e", content) - self.assertIn('name "System"', content) - self.assertIn("71AF80B4", content) # CRC uppercase - - issues = exporter.validate(systems, produced) - self.assertEqual(issues, []) - - # Discovery finds the systemdat exporter - exporters = discover_exporters() - self.assertIn("retroarch", exporters) - self.assertIs(exporters["retroarch"], SystemDatExporter) - - def test_systemdat_exporter_numeric_crc(self): - """Digit-only crc32 typed as int by YAML must not break the export.""" - from exporter.systemdat_exporter import Exporter as SystemDatExporter - - truth = { - "platform": "retroarch", - "systems": { - "commodore-plus4": { - "files": [ - { - "name": "kernal-318005-05.bin", - "path": "kernal-318005-05.bin", - "size": 16384, - "crc32": 70295038, - "required": False, - }, - ], - }, - }, - } - - from resolve.reconcile import build_native_model - - systems, report = build_native_model(truth, {"systems": {}}) - original = ('clrmamepro (\n\tname "System"\n)\n\ngame (\n\tname "System"\n' - '\tcomment "commodore-plus4"\n)\n') - produced = SystemDatExporter().render( - systems, report, {"System.dat": original}, {"systems": {}} - ) - self.assertIn("crc 70295038", produced["System.dat"]) - - # --------------------------------------------------------------- - # Full truth + diff integration test - # --------------------------------------------------------------- - - def test_truth_diff_integration(self): - """Full chain: generate truth from profiles, diff against scraped data.""" - # Config: platform with two cores, only core_a has a profile - config = {"cores": ["core_a", "core_b"]} - registry_entry = { - "hash_type": "md5", - "verification_mode": "md5", - } - - # Emulator profile for core_a with 2 files - core_a_profile = { - "emulator": "CoreA", - "type": "libretro", - "systems": ["test-system"], - "files": [ - { - "name": "bios_a.bin", - "system": "test-system", - "required": True, - "md5": "a" * 32, - "sha1": "b" * 40, - "size": 1024, - "path": "bios_a.bin", - "source_ref": "src/a.c:10", - }, - { - "name": "shared.bin", - "system": "test-system", - "required": True, - "md5": "c" * 32, - "path": "shared.bin", - "source_ref": "src/a.c:20", - }, - ], - } - profile_path = os.path.join(self.emulators_dir, "core_a.yml") - with open(profile_path, "w") as f: - yaml.dump(core_a_profile, f) - - # No profile for core_b (unprofiled) - # Clear cache so the new profile is picked up - from model.profiles import emulator_profiles_cache - - emulator_profiles_cache.clear() - profiles = load_emulator_profiles(self.emulators_dir) - self.assertIn("core_a", profiles) - self.assertNotIn("core_b", profiles) - - # Generate truth - truth = generate_platform_truth( - "testplat", config, registry_entry, profiles, db=None, data_registry={} - ) - - # Verify truth structure - self.assertIn("test-system", truth["systems"]) - sys_files = truth["systems"]["test-system"]["files"] - self.assertEqual(len(sys_files), 2) - file_names = {f["name"] for f in sys_files} - self.assertEqual(file_names, {"bios_a.bin", "shared.bin"}) - - # Verify coverage metadata - cov = truth["_coverage"] - self.assertEqual(cov["cores_profiled"], 1) - # core_b has no profile YAML, so resolve_platform_cores never - # includes it, so cores_resolved reflects only matched profiles - self.assertEqual(cov["cores_resolved"], 1) - - # Inject unprofiled info into system-level coverage for diff. - # In production, core_b would be tracked as unprofiled by a - # higher-level orchestrator that knows the declared core list. - injected_cov = { - "cores_profiled": ["core_a"], - "cores_unprofiled": ["core_b"], - } - for sys_data in truth["systems"].values(): - sys_data["_coverage"] = injected_cov - - # Build scraped dict: shared.bin with wrong hash, phantom.bin extra, - # bios_a.bin missing - scraped = { - "systems": { - "test-system": { - "files": [ - { - "name": "shared.bin", - "required": True, - "md5": "d" * 32, - }, - { - "name": "phantom.bin", - "required": False, - "md5": "e" * 32, - }, - ], - }, - }, - } - - # Diff - result = diff_platform_truth(truth, scraped) - summary = result["summary"] - - # bios_a.bin not in scraped -> missing - self.assertEqual(summary["total_missing"], 1) - # shared.bin md5 mismatch (truth "c"*32 vs scraped "d"*32) - self.assertEqual(summary["total_hash_mismatch"], 1) - # phantom.bin extra, core_b unprofiled -> extra_unprofiled - self.assertEqual(summary["total_extra_unprofiled"], 1) - # Unprofiled cores present, so extras are unprofiled not phantom - self.assertEqual(summary["total_extra_phantom"], 0) - - # Verify divergence details - div = result["divergences"]["test-system"] - self.assertEqual(div["missing"][0]["name"], "bios_a.bin") - self.assertEqual(div["hash_mismatch"][0]["name"], "shared.bin") - self.assertEqual(div["extra_unprofiled"][0]["name"], "phantom.bin") - self.assertNotIn("extra_phantom", div) - - def test_173_cross_ref_hash_matching(self): - """Platform file under different name matched by MD5 is not undeclared.""" - config = load_platform_config("test_md5", self.platforms_dir) - profiles = load_emulator_profiles(self.emulators_dir) - undeclared = find_undeclared_files( - config, self.emulators_dir, self.db, profiles - ) - names = {u["name"] for u in undeclared} - # correct_hash.bin is declared by platform as renamed_file.bin with same MD5 - # hash-based matching should suppress it from undeclared - self.assertNotIn("correct_hash.bin", names) - - def test_174_expand_platform_declared_names(self): - """expand_platform_declared_names enriches with DB canonical names.""" - config = load_platform_config("test_md5", self.platforms_dir) - result = expand_platform_declared_names(config, self.db) - # renamed_file.bin is declared directly - self.assertIn("renamed_file.bin", result) - # correct_hash.bin is the DB canonical name for the same MD5 - self.assertIn("correct_hash.bin", result) - - # --------------------------------------------------------------- - # Registry merge + all_libretro expansion + diff hash fallback - # --------------------------------------------------------------- - - def test_175_registry_merge_cores(self): - """load_platform_config merges cores from _registry.yml.""" - from model.platforms import _platform_config_cache - - # Platform YAML with 1 core - config = { - "platform": "TestMerge", - "cores": ["core_a"], - "systems": {"test-system": {"files": []}}, - } - with open(os.path.join(self.platforms_dir, "testmerge.yml"), "w") as f: - yaml.dump(config, f) - - # Registry with 2 cores (superset) - registry = { - "platforms": { - "testmerge": { - "config": "testmerge.yml", - "cores": ["core_a", "core_b"], - } - } - } - with open(os.path.join(self.platforms_dir, "_registry.yml"), "w") as f: - yaml.dump(registry, f) - - _platform_config_cache.clear() - loaded = load_platform_config("testmerge", self.platforms_dir) - cores = [str(c) for c in loaded["cores"]] - self.assertIn("core_a", cores) - self.assertIn("core_b", cores) - - def test_176_all_libretro_in_list(self): - """resolve_platform_cores expands all_libretro/retroarch in a list.""" - from model.profiles import load_emulator_profiles - from resolve.cores import resolve_platform_cores - - # Create a libretro profile and a standalone profile - for name, ptype in [("lr_core", "libretro"), ("sa_core", "standalone")]: - profile = { - "emulator": name, - "type": ptype, - "cores": [name], - "systems": ["test-system"], - "files": [], - } - with open(os.path.join(self.emulators_dir, f"{name}.yml"), "w") as f: - yaml.dump(profile, f) - - profiles = load_emulator_profiles(self.emulators_dir) - - # Config with retroarch + sa_core in cores list - config = {"cores": ["retroarch", "sa_core"]} - resolved = resolve_platform_cores(config, profiles) - self.assertIn("lr_core", resolved) # expanded via retroarch - self.assertIn("sa_core", resolved) # explicit - - def test_177_diff_hash_fallback_rename(self): - """Diff detects platform renames via hash fallback.""" - from resolve.platformdiff import diff_platform_truth - - truth = { - "systems": { - "test-system": { - "_coverage": {"cores_profiled": ["c"], "cores_unprofiled": []}, - "files": [ - { - "name": "ROM", - "required": True, - "md5": "abcd1234" * 4, - "_cores": ["c"], - "_source_refs": [], - }, - ], - } - } - } - scraped = { - "systems": { - "test-system": { - "files": [ - {"name": "ROM1", "required": True, "md5": "abcd1234" * 4}, - ], - } - } - } - - result = diff_platform_truth(truth, scraped) - # ROM and ROM1 share the same hash: a rename, not missing plus phantom - self.assertEqual(result["summary"]["total_missing"], 0) - self.assertEqual(result["summary"]["total_extra_phantom"], 0) - - def test_178_diff_system_normalization(self): - """Diff matches systems with different IDs via normalization.""" - from resolve.platformdiff import diff_platform_truth - - truth = { - "systems": { - "sega-gamegear": { - "_coverage": {"cores_profiled": ["c"], "cores_unprofiled": []}, - "files": [ - { - "name": "bios.gg", - "required": True, - "md5": "a" * 32, - "_cores": ["c"], - "_source_refs": [], - }, - ], - }, - } - } - scraped = { - "systems": { - "sega-game-gear": { - "files": [ - {"name": "bios.gg", "required": True, "md5": "a" * 32}, - ], - }, - } - } - - result = diff_platform_truth(truth, scraped) - self.assertEqual(result["summary"]["systems_uncovered"], 0) - self.assertEqual(result["summary"]["total_missing"], 0) - self.assertEqual(result["summary"]["systems_compared"], 1) - - def test_179_agnostic_profile_skipped_in_undeclared(self): - """bios_mode: agnostic profiles are skipped entirely by find_undeclared_files.""" - config = load_platform_config("test_existence", self.platforms_dir) - profiles = load_emulator_profiles(self.emulators_dir) - undeclared = find_undeclared_files( - config, self.emulators_dir, self.db, profiles - ) - emulators = {u["emulator"] for u in undeclared} - # TestAgnostic should NOT appear in undeclared (bios_mode: agnostic) - self.assertNotIn("TestAgnostic", emulators) - - def test_180_agnostic_file_skipped_in_undeclared(self): - """Files with agnostic: true are skipped, others in same profile are not.""" - config = load_platform_config("test_existence", self.platforms_dir) - profiles = load_emulator_profiles(self.emulators_dir) - undeclared = find_undeclared_files( - config, self.emulators_dir, self.db, profiles - ) - names = {u["name"] for u in undeclared} - # agnostic_file.bin should NOT be in undeclared (agnostic: true) - self.assertNotIn("agnostic_file.bin", names) - # undeclared_req.bin should still be in undeclared (not agnostic) - self.assertIn("undeclared_req.bin", names) - - def test_181_agnostic_extras_scan(self): - """Agnostic profiles add all matching DB files as extras.""" - from packs.extras import collect_emulator_extras - - config = load_platform_config("test_existence", self.platforms_dir) - profiles = load_emulator_profiles(self.emulators_dir) - extras = collect_emulator_extras( - config, - self.emulators_dir, - self.db, - set(), - "system", - profiles, - ) - agnostic_extras = [ - e for e in extras if e.get("source_emulator") == "TestAgnostic" - ] - # Agnostic scan should find files in the same directory as correct_hash.bin - self.assertTrue(len(agnostic_extras) > 0, "Agnostic scan should produce extras") - # All agnostic extras should have agnostic_scan flag - for e in agnostic_extras: - self.assertTrue(e.get("agnostic_scan", False)) - - def test_182_agnostic_rename_readme(self): - """build_agnostic_rename_readme generates correct text.""" - from packs.readme import build_agnostic_rename_readme - - result = build_agnostic_rename_readme( - "dsi_nand.bin", - "DSi_Nand_AUS.bin", - ["DSi_Nand_EUR.bin", "DSi_Nand_USA.bin"], - ) - self.assertIn("dsi_nand.bin <- DSi_Nand_AUS.bin", result) - self.assertIn("DSi_Nand_EUR.bin", result) - self.assertIn("DSi_Nand_USA.bin", result) - self.assertIn("rename it to: dsi_nand.bin", result) - - def test_183_agnostic_resolve_fallback(self): - """resolve_local_file with agnostic fallback finds a system file.""" - file_entry = { - "name": "nonexistent_agnostic.bin", - "agnostic": True, - "min_size": 1, - "max_size": 999999, - "agnostic_path_prefix": self.bios_dir + "/", - } - path, status = resolve_local_file(file_entry, self.db) - self.assertIsNotNone(path) - self.assertEqual(status, "agnostic_fallback") - - def test_179_batocera_exporter_round_trip(self): - """Batocera exporter produces valid Python dict format.""" - from exporter.batocera_exporter import Exporter - - truth = { - "systems": { - "sony-playstation": { - "_coverage": {"cores_profiled": ["c"]}, - "files": [ - { - "name": "scph5501.bin", - "destination": "scph5501.bin", - "required": True, - "md5": "b" * 32, - "_cores": ["c"], - "_source_refs": [], - }, - ], - } - } - } - scraped = { - # The core the platform runs: an addition is written under it. - "cores": ["c"], - "systems": { - "sony-playstation": {"native_id": "psx", "files": []}, - }, - } - from resolve.reconcile import build_native_model - - # The systems dict is one block inside the checker Batocera runs, so - # the exporter is handed the script it patches. - skeleton = ( - "#!/usr/bin/env python\n" - "systems = {\n" - "}\n" - "def checkBios(systems, prefix, filterROMs):\n" - " return {}\n" - ) - systems, report = build_native_model(truth, scraped) - exp = Exporter() - produced = exp.render( - systems, report, {"batocera-systems": skeleton}, scraped - ) - content = produced["batocera-systems"] - self.assertIn('"psx"', content) - self.assertIn("scph5501.bin", content) - self.assertIn("b" * 32, content) - self.assertIn("def checkBios(", content) - self.assertEqual(exp.validate(systems, produced), []) - - def test_180_recalbox_exporter_round_trip(self): - """Recalbox exporter produces valid es_bios.xml.""" - from exporter.recalbox_exporter import Exporter - - truth = { - "systems": { - "sony-playstation": { - "_coverage": {"cores_profiled": ["c"]}, - "files": [ - { - "name": "scph5501.bin", - "destination": "scph5501.bin", - "required": True, - "md5": "b" * 32, - "_cores": ["c"], - "_source_refs": [], - }, - ], - } - } - } - scraped = { - # The core the platform runs: an addition is written under it. - "cores": ["c"], - "systems": { - "sony-playstation": {"native_id": "psx", "files": []}, - }, - } - from resolve.reconcile import build_native_model - - systems, report = build_native_model(truth, scraped) - exp = Exporter() - produced = exp.render(systems, report, {}, scraped) - content = produced["es_bios.xml"] - self.assertIn(" dict: - return load_platform_config(platform_name, self.platforms_dir) - - def test_200_find_undeclared_include_all(self): - """include_all=True returns ALL core files, including declared ones.""" - from packs.gaps import find_undeclared_files - - config = self._load_config("test_existence") - profiles = load_emulator_profiles(self.emulators_dir) - # Without include_all: only undeclared files returned - undeclared = find_undeclared_files( - config, self.emulators_dir, self.db, profiles - ) - undeclared_names = {u["name"] for u in undeclared} - # present_req.bin is declared in platform YAML, should NOT be in undeclared - self.assertNotIn("present_req.bin", undeclared_names) - - # With include_all: ALL core files returned, including declared ones - all_files = find_undeclared_files( - config, self.emulators_dir, self.db, profiles, include_all=True - ) - all_names = {u["name"] for u in all_files} - # present_req.bin IS declared but should be returned with include_all - self.assertIn("present_req.bin", all_names) - # undeclared files should still be present - self.assertIn("undeclared_req.bin", all_names) - # Launcher/alias files should still be excluded - self.assertNotIn("launcher_bios.bin", all_names) - - def test_201_collect_emulator_extras_include_all(self): - """include_all=True passes through to find_undeclared_files.""" - from packs.extras import collect_emulator_extras - - config = self._load_config("test_existence") - profiles = load_emulator_profiles(self.emulators_dir) - base_dest = config.get("base_destination", "") - - # Default call must succeed without TypeError - extras = collect_emulator_extras( - config, self.emulators_dir, self.db, set(), base_dest, profiles - ) - self.assertIsInstance(extras, list) - - # include_all=True must be accepted and return a list - all_extras = collect_emulator_extras( - config, self.emulators_dir, self.db, set(), base_dest, profiles, - include_all=True, - ) - self.assertIsInstance(all_extras, list) - - # include_all=True is a superset: at least as many entries as default - all_names = {e["name"] for e in all_extras} - default_names = {e["name"] for e in extras} - self.assertGreaterEqual(len(all_names), len(default_names)) - # All default entries are present in include_all result - for name in default_names: - self.assertIn(name, all_names) - - - def test_202_pack_source_platform(self): - """source='platform' skips core extras.""" - from packs.platformpack import generate_pack - - output_dir = os.path.join(self.root, "pack_platform") - os.makedirs(output_dir, exist_ok=True) - profiles = load_emulator_profiles(self.emulators_dir) - zip_path = generate_pack( - "test_existence", - self.platforms_dir, - self.db, - self.bios_dir, - output_dir, - emu_profiles=profiles, - emulators_dir=self.emulators_dir, - source="platform", - ) - self.assertIsNotNone(zip_path) - self.assertIn("_Platform_", os.path.basename(zip_path)) - - def test_203_pack_source_truth(self): - """source='truth' uses emulator profile files.""" - from packs.platformpack import generate_pack - - output_dir = os.path.join(self.root, "pack_truth") - os.makedirs(output_dir, exist_ok=True) - profiles = load_emulator_profiles(self.emulators_dir) - zip_path = generate_pack( - "test_existence", - self.platforms_dir, - self.db, - self.bios_dir, - output_dir, - emu_profiles=profiles, - emulators_dir=self.emulators_dir, - source="truth", - ) - self.assertIsNotNone(zip_path) - self.assertIn("_Truth_", os.path.basename(zip_path)) - - def test_204_pack_source_full_unchanged(self): - """source='full' (default) has no source tag in filename.""" - from packs.platformpack import generate_pack - - output_dir = os.path.join(self.root, "pack_full") - os.makedirs(output_dir, exist_ok=True) - profiles = load_emulator_profiles(self.emulators_dir) - zip_path = generate_pack( - "test_existence", - self.platforms_dir, - self.db, - self.bios_dir, - output_dir, - emu_profiles=profiles, - emulators_dir=self.emulators_dir, - source="full", - ) - self.assertIsNotNone(zip_path) - bn = os.path.basename(zip_path) - self.assertNotIn("_Platform_", bn) - self.assertNotIn("_Truth_", bn) - - - def test_205_pack_source_platform_required(self): - """source='platform' + required_only=True.""" - from packs.platformpack import generate_pack - - output_dir = os.path.join(self.root, "pack_plat_req") - os.makedirs(output_dir, exist_ok=True) - profiles = load_emulator_profiles(self.emulators_dir) - zip_path = generate_pack( - "test_existence", - self.platforms_dir, - self.db, - self.bios_dir, - output_dir, - emu_profiles=profiles, - emulators_dir=self.emulators_dir, - source="platform", - required_only=True, - ) - self.assertIsNotNone(zip_path) - self.assertIn("_Platform_Required_", os.path.basename(zip_path)) - with zipfile.ZipFile(zip_path) as zf: - names = zf.namelist() - self.assertTrue(any("present_req.bin" in n for n in names)) - self.assertFalse(any("present_opt.bin" in n for n in names)) - - def test_206_pack_source_truth_required(self): - """source='truth' + required_only=True.""" - from packs.platformpack import generate_pack - - output_dir = os.path.join(self.root, "pack_truth_req") - os.makedirs(output_dir, exist_ok=True) - profiles = load_emulator_profiles(self.emulators_dir) - zip_path = generate_pack( - "test_existence", - self.platforms_dir, - self.db, - self.bios_dir, - output_dir, - emu_profiles=profiles, - emulators_dir=self.emulators_dir, - source="truth", - required_only=True, - ) - self.assertIsNotNone(zip_path) - self.assertIn("_Truth_Required_", os.path.basename(zip_path)) - - def test_207_manifest_source(self): - """generate_manifest respects source param.""" - from packs.manifest import generate_manifest - - profiles = load_emulator_profiles(self.emulators_dir) - registry_path = os.path.join(self.platforms_dir, "_registry.yml") - if not os.path.exists(registry_path): - with open(registry_path, "w") as fh: - yaml.dump({"platforms": {}}, fh) - manifest_full = generate_manifest( - "test_existence", self.platforms_dir, self.db, self.bios_dir, - registry_path, emulators_dir=self.emulators_dir, emu_profiles=profiles, - source="full", offline=True, - ) - manifest_plat = generate_manifest( - "test_existence", self.platforms_dir, self.db, self.bios_dir, - registry_path, emulators_dir=self.emulators_dir, emu_profiles=profiles, - source="platform", offline=True, - ) - self.assertLessEqual(manifest_plat["total_files"], manifest_full["total_files"]) - self.assertEqual(manifest_plat.get("source"), "platform") - self.assertEqual(manifest_full.get("source"), "full") - - def test_208_split_source_tag_in_dirname(self): - """generate_split_packs uses source tag in split directory name.""" - from packs.platformpack import generate_split_packs - - output_dir = os.path.join(self.root, "split_src") - os.makedirs(output_dir, exist_ok=True) - profiles = load_emulator_profiles(self.emulators_dir) - generate_split_packs( - "test_existence", self.platforms_dir, self.db, self.bios_dir, - output_dir, emulators_dir=self.emulators_dir, emu_profiles=profiles, - source="platform", - ) - entries = os.listdir(output_dir) - platform_dirs = [e for e in entries if "_Platform_" in e and "Split" in e] - self.assertTrue(len(platform_dirs) > 0, f"No _Platform_ split dir in {entries}") - - def test_209_all_variants_generates_6_zips(self): - """All 6 source x required combinations produce unique ZIPs.""" - from packs.platformpack import generate_pack - - output_dir = os.path.join(self.root, "pack_allvar") - os.makedirs(output_dir, exist_ok=True) - profiles = load_emulator_profiles(self.emulators_dir) - variants = [ - ("full", False), ("full", True), - ("platform", False), ("platform", True), - ("truth", False), ("truth", True), - ] - for source, required_only in variants: - generate_pack( - "test_existence", self.platforms_dir, self.db, self.bios_dir, - output_dir, emu_profiles=profiles, emulators_dir=self.emulators_dir, - source=source, required_only=required_only, - ) - zips = [f for f in os.listdir(output_dir) if f.endswith(".zip")] - self.assertEqual(len(zips), 6, f"Expected 6 ZIPs, got {len(zips)}: {zips}") - self.assertEqual(len(set(zips)), 6) - - def _make_hash_zip_fixture(self, tmpdir, declare_md5=True): - """Platform fixture with one ZIP file, optionally md5-declared.""" - import hashlib as hl - - plat_dir = os.path.join(tmpdir, "platforms") - bios_dir = os.path.join(tmpdir, "bios", "Arcade") - out_dir = os.path.join(tmpdir, "dist") - os.makedirs(plat_dir) - os.makedirs(bios_dir) - - zip_src = os.path.join(bios_dir, "testbios.zip") - with zipfile.ZipFile(zip_src, "w", zipfile.ZIP_DEFLATED) as zf: - info = zipfile.ZipInfo("rom.bin", date_time=(2020, 6, 15, 12, 0, 0)) - zf.writestr(info, b"rom_content_bytes") - from core.hashing import compute_hashes - - h = compute_hashes(zip_src) - - db = { - "files": { - h["sha1"]: { - "name": "testbios.zip", - "md5": h["md5"], - "sha1": h["sha1"], - "path": zip_src, - "paths": ["Arcade/testbios.zip"], - }, - }, - "indexes": { - "by_md5": {h["md5"]: h["sha1"]}, - "by_name": {"testbios.zip": [h["sha1"]]}, - "by_crc32": {}, - "by_path_suffix": {}, - }, - } - entry = {"name": "testbios.zip", "destination": "dc/testbios.zip"} - if declare_md5: - entry["md5"] = h["md5"] - config = { - "platform": "HashZipTest", - "verification_mode": "md5", - "base_destination": "bios", - "systems": {"arcade-sys": {"files": [entry]}}, - } - with open(os.path.join(plat_dir, "test_hashzip.yml"), "w") as fh: - yaml.dump(config, fh) - return plat_dir, os.path.join(tmpdir, "bios"), out_dir, db, h, hl - - def test_210_pack_copies_md5_declared_zip_byte_identical(self): - """md5-declared ZIPs are copied unchanged, never rebuilt.""" - import tempfile - - from packs.platformpack import generate_pack - - with tempfile.TemporaryDirectory() as tmpdir: - plat_dir, bios_root, out_dir, db, h, hl = self._make_hash_zip_fixture( - tmpdir, declare_md5=True - ) - zip_path = generate_pack( - "test_hashzip", plat_dir, db, bios_root, out_dir - ) - self.assertIsNotNone(zip_path) - with zipfile.ZipFile(zip_path) as zf: - data = zf.read("dc/testbios.zip") - self.assertEqual(hl.md5(data).hexdigest(), h["md5"]) - - def test_211_pack_keeps_zip_bytes_without_declared_hash(self): - """A ZIP with no declared hash keeps the collection's bytes, so it - hashes to what the install list publishes.""" - import io - import tempfile - - from packs.platformpack import generate_pack - - with tempfile.TemporaryDirectory() as tmpdir: - plat_dir, bios_root, out_dir, db, h, hl = self._make_hash_zip_fixture( - tmpdir, declare_md5=False - ) - zip_path = generate_pack( - "test_hashzip", plat_dir, db, bios_root, out_dir - ) - self.assertIsNotNone(zip_path) - with zipfile.ZipFile(zip_path) as zf: - data = zf.read("dc/testbios.zip") - self.assertEqual(hl.md5(data).hexdigest(), h["md5"]) - with zipfile.ZipFile(io.BytesIO(data)) as inner: - self.assertEqual(inner.read("rom.bin"), b"rom_content_bytes") - - def test_212_verify_pack_flags_native_md5_mismatch(self): - """Pack verification reproduces the native md5 check per member.""" - import tempfile - - from packs.platformcheck import verify_pack_against_platform - - with tempfile.TemporaryDirectory() as tmpdir: - plat_dir, bios_root, out_dir, db, h, hl = self._make_hash_zip_fixture( - tmpdir, declare_md5=True - ) - os.makedirs(out_dir) - bad_pack = os.path.join(out_dir, "HashZipTest_BIOS_Pack.zip") - with zipfile.ZipFile(bad_pack, "w") as zf: - zf.writestr("dc/testbios.zip", b"wrong bytes entirely") - result = verify_pack_against_platform( - bad_pack, "test_hashzip", plat_dir, db=None - ) - errors = result[3] - self.assertTrue( - any("md5" in e for e in errors), - f"expected md5 mismatch error, got: {errors}", - ) - - def test_213_verify_pack_passes_correct_member_hash(self): - """Pack verification passes when member bytes match declared md5.""" - import tempfile - - from packs.platformcheck import verify_pack_against_platform - - with tempfile.TemporaryDirectory() as tmpdir: - plat_dir, bios_root, out_dir, db, h, hl = self._make_hash_zip_fixture( - tmpdir, declare_md5=True - ) - os.makedirs(out_dir) - good_pack = os.path.join(out_dir, "HashZipTest_BIOS_Pack.zip") - src = os.path.join(bios_root, "Arcade", "testbios.zip") - with zipfile.ZipFile(good_pack, "w") as zf: - zf.write(src, "dc/testbios.zip") - result = verify_pack_against_platform( - good_pack, "test_hashzip", plat_dir, db=None - ) - self.assertEqual(result[3], [], f"unexpected errors: {result[3]}") - - def test_213b_absent_game_data_is_counted_apart(self): - """Game data the collection lacks is counted apart from the pack's - errors, while firmware the collection lacks stays one.""" - import tempfile - - from packs.platformpack import generate_pack - from packs.platformcheck import verify_pack_against_platform - - profiles = {"eng": {"emulator": "Eng", "type": "game", "cores": ["eng"], - "systems": ["arcade-sys"], - "files": [{"name": "data.pak", "category": "game_data"}, - {"name": "firmware.bin"}]}} - with tempfile.TemporaryDirectory() as tmpdir: - plat_dir, bios_root, out_dir, db, _h, _hl = self._make_hash_zip_fixture( - tmpdir, declare_md5=True - ) - config_path = os.path.join(plat_dir, "test_hashzip.yml") - with open(config_path) as fh: - config = yaml.safe_load(fh) - config["cores"] = ["eng"] - config["systems"]["arcade-sys"]["files"].append( - {"name": "data.pak", "destination": "dc/data.pak"} - ) - with open(config_path, "w") as fh: - yaml.dump(config, fh) - zip_path = generate_pack("test_hashzip", plat_dir, db, bios_root, out_dir, - emu_profiles=profiles) - result = verify_pack_against_platform( - zip_path, "test_hashzip", plat_dir, db=db, emu_profiles=profiles) - self.assertEqual(result[3], []) - self.assertEqual((result[4], result[5], result[9]), (2, 1, 1)) - - config["systems"]["arcade-sys"]["files"][-1]["name"] = "firmware.bin" - config["systems"]["arcade-sys"]["files"][-1]["destination"] = "dc/firmware.bin" - with open(os.path.join(plat_dir, "test_hashzip_fw.yml"), "w") as fh: - yaml.dump(config, fh) - result = verify_pack_against_platform( - zip_path, "test_hashzip_fw", plat_dir, db=db, emu_profiles=profiles) - self.assertEqual([e.rsplit("/", 1)[-1] for e in result[3]], ["firmware.bin"]) - self.assertTrue(result[3][0].startswith("baseline missing: ")) - self.assertEqual(result[9], 0) - - def test_216_resolve_by_sha256(self): - """resolve_local_file matches files by declared sha256.""" - import tempfile - - from resolve.localfile import resolve_local_file - - with tempfile.TemporaryDirectory() as tmpdir: - path = os.path.join(tmpdir, "SNES_dsp1.rom") - with open(path, "wb") as fh: - fh.write(b"dsp firmware bytes") - import hashlib as hl - - sha256 = hl.sha256(b"dsp firmware bytes").hexdigest() - db = { - "files": { - "sha1x": { - "name": "SNES_dsp1.rom", - "path": path, - "sha256": sha256, - }, - }, - "indexes": { - "by_md5": {}, - "by_name": {"SNES_dsp1.rom": ["sha1x"]}, - "by_sha256": {sha256: "sha1x"}, - "by_crc32": {}, - "by_path_suffix": {}, - }, - } - # Name differs, only sha256 identifies the content - entry = {"name": "dsp1.rom", "sha256": sha256} - local, status = resolve_local_file(entry, db) - self.assertEqual(local, path) - self.assertEqual(status, "sha256_exact") - # Multi-hash list also resolves - entry = {"name": "dsp1.rom", "sha256": f"{'0' * 64},{sha256}"} - local, status = resolve_local_file(entry, db) - self.assertEqual(local, path) - # Unknown sha256 falls through to not_found - entry = {"name": "dsp1.rom", "sha256": "f" * 64} - local, status = resolve_local_file(entry, db) - self.assertIsNone(local) - self.assertEqual(status, "not_found") - - def test_220_large_file_dotted_asset_fallback(self): - """Files with spaces resolve to GitHub's dotted asset name.""" - import tempfile - import urllib.error - - from model.largefiles import fetch_large_file - - attempts = [] - - class FakeResponse: - headers: dict = {} - - def __init__(self, payload): - self._payload = payload - - def read(self, _size=None): - data, self._payload = self._payload, b"" - return data - - def __enter__(self): - return self - - def __exit__(self, *_): - return False - - def fake_urlopen(req, timeout=None): - url = req.full_url if hasattr(req, "full_url") else str(req) - attempts.append(url) - if "MAME%200.174" in url: - raise urllib.error.HTTPError(url, 404, "Not Found", {}, None) - return FakeResponse(b"payload") - - original = largefiles.urllib.request.urlopen - largefiles.urllib.request.urlopen = fake_urlopen - try: - with tempfile.TemporaryDirectory() as tmpdir, mock.patch.dict( - os.environ, {"RETROBIOS_OFFLINE": ""} - ): - path = fetch_large_file( - "MAME 0.174 Arcade XML.dat", dest_dir=tmpdir - ) - self.assertIsNotNone(path) - with open(path, "rb") as fh: - self.assertEqual(fh.read(), b"payload") - finally: - largefiles.urllib.request.urlopen = original - - self.assertEqual(len(attempts), 2, attempts) - self.assertIn("MAME%200.174", attempts[0]) - self.assertIn("MAME.0.174.Arcade.XML.dat", attempts[1]) - - def test_219_batocera_stable_tag_selection(self): - """Stable tag picker takes the highest batocera-N(.M) tag.""" - from scripts.scraper.batocera_scraper import pick_stable_tag - - tags = [ - "uboot-rockpro64", "batocera-pre-br2-external", - "batocera-41", "batocera-42", "batocera-43", "batocera-43.1", - "master_20180518", - ] - self.assertEqual(pick_stable_tag(tags), "batocera-43.1") - self.assertEqual(pick_stable_tag(["batocera-9", "batocera-10"]), "batocera-10") - self.assertIsNone(pick_stable_tag(["uboot-x", "random"])) - - def test_218_resolve_by_crc32_and_size(self): - """crc-only profile entries resolve by crc32 confirmed by size.""" - import tempfile - import zlib - - from resolve.localfile import resolve_local_file - - with tempfile.TemporaryDirectory() as tmpdir: - data = b"exos rom bytes" * 100 - path = os.path.join(tmpdir, "exos21.rom") - with open(path, "wb") as fh: - fh.write(data) - crc = f"{zlib.crc32(data) & 0xffffffff:08x}" - db = { - "files": { - "sha1e": { - "name": "exos21.rom", - "path": path, - "size": len(data), - "crc32": crc, - }, - }, - "indexes": { - "by_md5": {}, - "by_name": {"exos21.rom": ["sha1e"]}, - "by_crc32": {crc: "sha1e"}, - "by_path_suffix": {}, - }, - } - # Different extension in the profile, crc32+size identify it - local, status = resolve_local_file( - {"name": "exos21.bin", "crc32": crc, "size": len(data)}, db - ) - self.assertEqual(local, path) - self.assertEqual(status, "crc32_exact") - # Wrong size rejects the crc match - local, status = resolve_local_file( - {"name": "exos21.bin", "crc32": crc, "size": 1}, db - ) - self.assertIsNone(local) - - def test_217_resolve_name_casefold_fallback(self): - """Name resolution falls back to a case-insensitive match.""" - import tempfile - - from resolve.localfile import resolve_local_file - - with tempfile.TemporaryDirectory() as tmpdir: - path = os.path.join(tmpdir, "VEC_Minestorm.vec") - with open(path, "wb") as fh: - fh.write(b"minestorm rom") - db = { - "files": {"sha1v": {"name": "VEC_Minestorm.vec", "path": path}}, - "indexes": { - "by_md5": {}, - "by_name": {"VEC_Minestorm.vec": ["sha1v"]}, - "by_crc32": {}, - "by_path_suffix": {}, - }, - } - # Upstream declares a different casing, no hash - local, status = resolve_local_file( - {"name": "VEC_MineStorm.vec"}, db - ) - self.assertEqual(local, path) - self.assertEqual(status, "name_exact") - - def test_217b_zipped_file_composite_needs_the_member(self): - """One member of another name has the zipped_file md5 as composite. - - Batocera looks the member up by name, so the archive is not proof of - the entry: a MAME rename leaves exactly that archive behind. - """ - import hashlib as hl - import tempfile - - from resolve.localfile import resolve_local_file - - rom = b"inner rom bytes" - rom_md5 = hl.md5(rom).hexdigest() - with tempfile.TemporaryDirectory() as tmpdir: - path = os.path.join(tmpdir, "foo.zip") - with zipfile.ZipFile(path, "w") as zf: - zf.writestr("renamed.bin", rom) - db = { - "files": {"sha1z": {"name": "foo.zip", "path": path, "md5": "f" * 32}}, - "indexes": { - "by_md5": {}, "by_name": {"foo.zip": ["sha1z"]}, - "by_crc32": {}, "by_path_suffix": {}, - }, - } - entry = {"name": "foo.zip", "zipped_file": "expected.bin", "md5": rom_md5} - self.assertNotEqual( - resolve_local_file(entry, db)[1], "md5_composite_exact" - ) - with zipfile.ZipFile(path, "w") as zf: - zf.writestr("expected.bin", rom) - self.assertEqual( - resolve_local_file(entry, db), (path, "md5_composite_exact") - ) - - def test_215_check_member_hash_inside_zip(self): - """zipped_file entries verify the ROM inside the ZIP, not the ZIP.""" - import hashlib as hl - import tempfile - - from packs.packhashes import _check_member_hash - - rom = b"inner rom bytes" - rom_md5 = hl.md5(rom).hexdigest() - with tempfile.TemporaryDirectory() as tmpdir: - pack = os.path.join(tmpdir, "pack.zip") - import io - - inner_buf = io.BytesIO() - with zipfile.ZipFile(inner_buf, "w") as inner: - inner.writestr("EPR-123.IC27", rom) - with zipfile.ZipFile(pack, "w") as zf: - zf.writestr("dc/game.zip", inner_buf.getvalue()) - with zipfile.ZipFile(pack) as zf: - # Case-insensitive inner match (Batocera casefold) - ok = _check_member_hash( - zf, - "dc/game.zip", - {"zipped_file": "epr-123.ic27", "md5": rom_md5}, - "md5", - ) - self.assertIsNone(ok) - bad = _check_member_hash( - zf, - "dc/game.zip", - {"zipped_file": "epr-123.ic27", "md5": "0" * 32}, - "md5", - ) - self.assertIsNotNone(bad) - - - # -- MiSTer FPGA scraper (BiosDB) ------------------------------------- - - MISTER_DB = { - "db_id": "bios_db", - "timestamp": 1785183064, - "files": { - "games/3DO/boot.rom": { - "hash": "f47264dd47fe30f73ab3c010015c155b", - "size": 1048576, - "url": "https://archive.org/download/x/3DO.zip/boot.rom", - }, - "games/GameCom/boot.rom": { - "hash": "3f2178d717dd309ed7424d49ef92987f", - "size": 262144, - "url": "https://archive.org/download/x/GameCom.zip/boot.rom", - }, - }, - "archives": { - "neogeo_unibios": { - "archive_file": {"hash": "a" * 32, "size": 101498, "url": "http://x/u.zip"}, - "summary_inline": { - "files": { - "games/NEOGEO/uni-bios.rom": { - "hash": "4f0aeda8d2d145f596826b62d563c4ef", - "size": 131072, - } - } - }, - } - }, - } - - def _mister_scraper(self): - import json - - from scraper.misterfpga_scraper import Scraper - - scraper = Scraper(url="https://example.test/bios_db.json.zip") - scraper._raw_data = json.dumps(self.MISTER_DB) - return scraper - - def test_221_mister_parse_db_inlines_archive_entries(self): - """Archive-provided files carry the extracted member hash.""" - import json - - from scraper.misterfpga_scraper import parse_db - - entries = parse_db(json.dumps(self.MISTER_DB)) - self.assertIn("games/NEOGEO/uni-bios.rom", entries) - self.assertEqual( - entries["games/NEOGEO/uni-bios.rom"]["hash"], - "4f0aeda8d2d145f596826b62d563c4ef", - ) - self.assertEqual(len(entries), 3) - - def test_222_mister_validate_format_rejects_foreign_db(self): - """Only the bios_db database is accepted.""" - import json - - scraper = self._mister_scraper() - self.assertTrue(scraper.validate_format(json.dumps(self.MISTER_DB))) - self.assertFalse(scraper.validate_format("not json")) - self.assertFalse( - scraper.validate_format(json.dumps({"db_id": "distribution_mister", "files": {}})) - ) - broken = json.loads(json.dumps(self.MISTER_DB)) - broken["files"]["games/3DO/boot.rom"].pop("size") - self.assertFalse(scraper.validate_format(json.dumps(broken))) - - def test_223_mister_requirements_strip_games_prefix(self): - """Destinations are relative to base_destination games.""" - reqs = {r.destination: r for r in self._mister_scraper().fetch_requirements()} - self.assertIn("3DO/boot.rom", reqs) - self.assertEqual(reqs["3DO/boot.rom"].name, "boot.rom") - self.assertEqual(reqs["3DO/boot.rom"].system, "3do") - self.assertEqual(reqs["3DO/boot.rom"].native_id, "3DO") - self.assertEqual(reqs["3DO/boot.rom"].size, 1048576) - - def test_224_mister_platform_yaml_shape(self): - """The generated config declares md5 verification and no cores.""" - config = self._mister_scraper().generate_platform_yaml() - self.assertEqual(config["verification_mode"], "md5") - self.assertEqual(config["base_destination"], "games") - self.assertEqual(config["cores"], []) - self.assertEqual(config["version"], "2026-07-27") - systems = config["systems"] - self.assertEqual( - systems["3do"]["docs"], "https://github.com/MiSTer-devel/3DO_MiSTer" - ) - # No MiSTer-devel repository exists for the Game.com core - self.assertNotIn("docs", systems["tiger-game-com"]) - entry = systems["3do"]["files"][0] - self.assertTrue(entry["required"]) - self.assertEqual(entry["md5"], "f47264dd47fe30f73ab3c010015c155b") - - def test_225_mister_docs_targets_are_unique_per_system(self): - """Every mapped system resolves to a distinct retrobios system ID.""" - from scraper.misterfpga_scraper import SYSTEM_MAP - - folders = list(SYSTEM_MAP) - systems = [SYSTEM_MAP[f][0] for f in folders] - self.assertEqual(len(systems), len(set(systems))) - - - def test_226_cross_reference_platform_filter(self): - """--platform restricts declarations to that platform alone.""" - from packs.crossref import global_report_scope, platform_configs - - with tempfile.TemporaryDirectory() as tmpdir: - plat_dir = os.path.join(tmpdir, "platforms") - os.makedirs(plat_dir) - registry = { - "platforms": { - "alpha": {"config": "alpha.yml"}, - "beta": {"config": "beta.yml"}, - } - } - with open(os.path.join(plat_dir, "_registry.yml"), "w") as f: - yaml.dump(registry, f) - for name, fname in (("alpha", "a.bin"), ("beta", "b.bin")): - cfg = { - "platform": name, - "verification_mode": "md5", - "systems": {"shared-system": {"files": [{"name": fname}]}}, - } - with open(os.path.join(plat_dir, f"{name}.yml"), "w") as f: - yaml.dump(cfg, f) - - # Keyed by the normalized system ID, as profiles spell systems - # differently from platforms. - db = {"files": {}, "indexes": {}} - everything, _ = global_report_scope(platform_configs(plat_dir), db, {}) - self.assertEqual(everything["sharedsystem"], {"a.bin", "b.bin"}) - - only_alpha, _ = global_report_scope(platform_configs(plat_dir, ["alpha"]), db, {}) - self.assertEqual(only_alpha["sharedsystem"], {"a.bin"}) - - - def test_227_manifest_injected_compressed(self): - """The manifest is deflated whichever injection path runs.""" - import json as _json - - from packs.finalize import inject_manifest - - manifest = {"files": [{"path": f"f{i}.bin"} for i in range(200)]} - raw = _json.dumps(manifest, indent=2, ensure_ascii=False) - sizes = [] - with tempfile.TemporaryDirectory() as tmpdir: - for preexisting in (False, True): - path = os.path.join(tmpdir, f"pack{int(preexisting)}.zip") - with zipfile.ZipFile(path, "w", zipfile.ZIP_DEFLATED) as zf: - zf.writestr("bios.bin", b"x" * 4096) - if preexisting: - zf.writestr("manifest.json", "{}") - inject_manifest(path, manifest) - with zipfile.ZipFile(path) as zf: - info = zf.getinfo("manifest.json") - self.assertEqual(info.compress_type, zipfile.ZIP_DEFLATED) - self.assertEqual(_json.loads(zf.read("manifest.json")), manifest) - sizes.append(info.compress_size) - self.assertLess(sizes[0], len(raw)) - self.assertEqual(sizes[0], sizes[1]) - - # --------------------------------------------------------------- - # Region filter - # --------------------------------------------------------------- - - def _region_profiles(self) -> dict: - return { - "rgncore": { - "emulator": "RegionCore", - "type": "libretro", - "cores": ["rgncore"], - "systems": ["region-console"], - "files": [ - {"name": "rgn_us.bin", "region": ["north-america"]}, - {"name": "rgn_jp.bin", "region": ["japan"]}, - {"name": "rgn_eu.bin", "region": ["europe"]}, - {"name": "rgn_world.bin", "region": ["world"]}, - {"name": "rgn_plain.bin"}, - ], - } - } - - def _create_region_fixtures(self) -> None: - names = ( - "rgn_us.bin", - "rgn_jp.bin", - "rgn_eu.bin", - "rgn_world.bin", - "rgn_plain.bin", - ) - for name in names: - self._make_file(name, name.encode()) - self.db = self._build_db() - config = { - "platform": "RegionPlat", - "version": "3.0", - "verification_mode": "existence", - "systems": { - "region-console": { - "files": [ - { - "name": n, - "destination": n, - "required": n - in ("rgn_us.bin", "rgn_jp.bin", "rgn_eu.bin"), - } - for n in names - ] - } - }, - } - with open( - os.path.join(self.platforms_dir, "regionplat.yml"), "w", encoding="utf-8" - ) as fh: - yaml.safe_dump(config, fh) - - def _region_pack(self, **kwargs) -> str: - from packs.platformpack import generate_pack - - self._create_region_fixtures() - out = generate_pack( - "regionplat", - self.platforms_dir, - self.db, - self.bios_dir, - self.root, - emu_profiles=self._region_profiles(), - **kwargs, - ) - self.assertIsNotNone(out) - return out - - @staticmethod - def _names_in(zip_path: str) -> set[str]: - with zipfile.ZipFile(zip_path) as zf: - return {os.path.basename(n) for n in zf.namelist()} - - def test_region_filter_drops_other_regions(self): - names = self._names_in(self._region_pack(regions=["north-america"])) - self.assertIn("rgn_us.bin", names) - self.assertNotIn("rgn_jp.bin", names) - self.assertNotIn("rgn_eu.bin", names) - - def test_region_priority_selects_second_choice(self): - names = self._names_in(self._region_pack(regions=["oceania", "europe"])) - self.assertIn("rgn_eu.bin", names) - self.assertNotIn("rgn_us.bin", names) - self.assertNotIn("rgn_jp.bin", names) - - def test_region_filter_uses_world_when_no_regional_match(self): - names = self._names_in(self._region_pack(regions=["oceania"])) - self.assertIn("rgn_world.bin", names) - for expected in ("rgn_us.bin", "rgn_jp.bin", "rgn_eu.bin"): - self.assertNotIn(expected, names) - - def test_region_filter_keeps_untagged_and_world(self): - names = self._names_in(self._region_pack(regions=["north-america"])) - self.assertIn("rgn_plain.bin", names) - self.assertIn("rgn_world.bin", names) - - def test_region_tag_in_pack_name(self): - out = self._region_pack(regions=["north-america", "japan"]) - self.assertIn("NorthAmerica_Japan", os.path.basename(out)) - - def test_no_region_argument_changes_nothing(self): - names = self._names_in(self._region_pack()) - for expected in ( - "rgn_us.bin", - "rgn_jp.bin", - "rgn_eu.bin", - "rgn_plain.bin", - "rgn_world.bin", - ): - self.assertIn(expected, names) - - def test_region_composes_with_required_only(self): - out = self._region_pack(regions=["north-america"], required_only=True) - names = self._names_in(out) - self.assertIn("rgn_us.bin", names) - self.assertNotIn("rgn_jp.bin", names) - self.assertNotIn("rgn_eu.bin", names) - self.assertIn("NorthAmerica", os.path.basename(out)) - self.assertIn("Required", os.path.basename(out)) - - def test_region_composes_with_source_platform(self): - names = self._names_in( - self._region_pack(regions=["north-america"], source="platform") - ) - self.assertIn("rgn_us.bin", names) - self.assertNotIn("rgn_jp.bin", names) - self.assertNotIn("rgn_eu.bin", names) - self.assertIn("rgn_world.bin", names) - self.assertIn("rgn_plain.bin", names) - - def test_region_composes_with_split(self): - from packs.platformpack import generate_split_packs - - self._create_region_fixtures() - paths = generate_split_packs( - "regionplat", - self.platforms_dir, - self.db, - self.bios_dir, - self.root, - emu_profiles=self._region_profiles(), - regions=["north-america"], - offline=True, - ) - self.assertTrue(paths) - for p in paths: - self.assertIn("NorthAmerica", os.path.basename(p)) - names = self._names_in(p) - self.assertNotIn("rgn_jp.bin", names) - self.assertNotIn("rgn_eu.bin", names) - - def test_region_composes_with_split_and_target(self): - from packs.platformpack import generate_split_packs - - self._create_region_fixtures() - paths = generate_split_packs( - "regionplat", - self.platforms_dir, - self.db, - self.bios_dir, - self.root, - emu_profiles=self._region_profiles(), - target_cores={"rgncore"}, - regions=["north-america"], - ) - self.assertTrue(paths) - for p in paths: - self.assertIn("NorthAmerica", os.path.basename(p)) - names = self._names_in(p) - self.assertNotIn("rgn_jp.bin", names) - self.assertNotIn("rgn_eu.bin", names) - self.assertTrue( - any("rgn_us.bin" in self._names_in(p) for p in paths), - "target filtering removed the whole system", - ) - - def test_region_composes_with_manifest(self): - from packs.manifest import generate_manifest - - self._create_region_fixtures() - registry_path = os.path.join(self.platforms_dir, "_registry.yml") - if not os.path.exists(registry_path): - with open(registry_path, "w", encoding="utf-8") as fh: - yaml.safe_dump({"platforms": {}}, fh) - manifest = generate_manifest( - "regionplat", - self.platforms_dir, - self.db, - self.bios_dir, - registry_path, - emu_profiles=self._region_profiles(), - regions=["north-america"], - ) - packed = {os.path.basename(f["dest"]) for f in manifest["files"]} - self.assertEqual(manifest["regions"], ["north-america"]) - self.assertIn("rgn_us.bin", packed) - self.assertNotIn("rgn_jp.bin", packed) - self.assertNotIn("rgn_eu.bin", packed) - - def test_manifest_without_region_keeps_every_variant(self): - from packs.manifest import generate_manifest - - self._create_region_fixtures() - registry_path = os.path.join(self.platforms_dir, "_registry.yml") - if not os.path.exists(registry_path): - with open(registry_path, "w", encoding="utf-8") as fh: - yaml.safe_dump({"platforms": {}}, fh) - manifest = generate_manifest( - "regionplat", - self.platforms_dir, - self.db, - self.bios_dir, - registry_path, - emu_profiles=self._region_profiles(), - offline=True, - ) - packed = {os.path.basename(f["dest"]) for f in manifest["files"]} - for expected in ("rgn_us.bin", "rgn_jp.bin", "rgn_eu.bin"): - self.assertIn(expected, packed) - - def test_region_composes_with_system_pack(self): - from packs.emulatorpack import generate_system_pack - - self._create_region_fixtures() - os.makedirs(self.emulators_dir, exist_ok=True) - with open( - os.path.join(self.emulators_dir, "rgncore.yml"), "w", encoding="utf-8" - ) as fh: - yaml.safe_dump(self._region_profiles()["rgncore"], fh) - out = generate_system_pack( - ["region-console"], - self.emulators_dir, - self.db, - self.bios_dir, - self.root, - regions=["north-america"], - ) - self.assertIsNotNone(out) - self.assertIn("NorthAmerica", os.path.basename(out)) - names = self._names_in(out) - self.assertIn("rgn_us.bin", names) - self.assertNotIn("rgn_jp.bin", names) - - def test_verify_platform_region_matches_the_pack(self): - from model.platforms import load_platform_config - from packs.coverage import verify_platform - - self._create_region_fixtures() - profiles = self._region_profiles() - config = load_platform_config("regionplat", self.platforms_dir) - - full = verify_platform(config, self.db, self.emulators_dir, profiles) - filtered = verify_platform( - config, - self.db, - self.emulators_dir, - profiles, - regions=["north-america"], - ) - checked = {d["name"] for d in filtered["details"]} - self.assertIn("rgn_us.bin", checked) - self.assertNotIn("rgn_jp.bin", checked) - self.assertNotIn("rgn_eu.bin", checked) - self.assertLess(len(filtered["details"]), len(full["details"])) - - packed = self._names_in(self._region_pack(regions=["north-america"])) - self.assertTrue(checked.issubset(packed), checked - packed) - - def test_verify_emulator_region_matches_the_pack(self): - from packs.emulatorpack import generate_emulator_pack - from packs.emulatorcheck import verify_emulator - - self._create_region_fixtures() - with open( - os.path.join(self.emulators_dir, "rgncore.yml"), "w", encoding="utf-8" - ) as fh: - yaml.safe_dump(self._region_profiles()["rgncore"], fh) - - full = verify_emulator(["rgncore"], self.emulators_dir, self.db) - filtered = verify_emulator( - ["rgncore"], self.emulators_dir, self.db, regions=["north-america"] - ) - checked = {d["name"] for d in filtered["details"]} - self.assertIn("rgn_us.bin", checked) - self.assertNotIn("rgn_jp.bin", checked) - self.assertLess(len(filtered["details"]), len(full["details"])) - - out = generate_emulator_pack( - ["rgncore"], - self.emulators_dir, - self.db, - self.bios_dir, - self.root, - regions=["north-america"], - ) - self.assertTrue(checked.issubset(self._names_in(out))) - - def test_every_narrowing_names_itself_and_says_so(self): - """A dimension that removes files must show in the pack name and in the - README. Both are built from pack_narrowings, so this holds for any new one.""" - from packs.readme import build_readme - from packs.naming import pack_narrowings - - dimensions = [ - {"source": "platform"}, - {"source": "truth"}, - {"regions": ["north-america"]}, - {"target_name": "switch"}, - {"one_per_slot": True}, - {"required_only": True}, - {"no_game_data": True}, - ] - for kwargs in dimensions: - applied = pack_narrowings( - kwargs.get("source", "full"), - kwargs.get("regions"), - kwargs.get("target_name"), - kwargs.get("one_per_slot", False), - kwargs.get("required_only", False), - no_game_data=kwargs.get("no_game_data", False), - ) - self.assertEqual(len(applied), 1, kwargs) - tag, label = applied[0] - self.assertTrue(tag.startswith("_") and len(tag) > 1, kwargs) - self.assertTrue(label.strip(), kwargs) - readme = build_readme("p", "P", "", 1, 1, narrowings=applied) - self.assertIn("PACK TYPE: Narrowed", readme) - self.assertIn(label, readme) - - def test_no_mode_swallows_a_narrowing_flag(self): - """Every mode either honours a narrowing flag or refuses it. - - Silently ignoring one is how --manifest-targets accepted --region and - wrote seven unfiltered manifests, and how --manifest accepted - --one-per-slot. A mode that cannot apply a flag must say so. - """ - import subprocess - - repo = os.path.join(os.path.dirname(__file__), "..") - matrix = [ - (["--manifest-targets"], ["--region", "us"], "refuse"), - (["--manifest-targets"], ["--one-per-slot"], "refuse"), - (["--platform", "retroarch", "--manifest"], ["--one-per-slot"], "refuse"), - (["--emulator", "duckstation"], ["--one-per-slot"], "refuse"), - (["--system", "sony-playstation"], ["--one-per-slot"], "refuse"), - (["--platform", "retroarch", "--system", "sony-playstation"], - ["--one-per-slot"], "refuse"), - (["--platform", "retroarch", "--from-md5", "d8f1"], ["--region", "us"], - "refuse"), - (["--platform", "retroarch", "--from-md5", "d8f1"], ["--one-per-slot"], - "refuse"), - # --verify-packs returns before the argument checks run, so it - # used to accept these and answer about the pack sitting in the - # output directory. --target is honoured instead of refused: the - # check narrows by it. - (["--platform", "retroarch", "--verify-packs"], ["--one-per-slot"], - "refuse"), - (["--platform", "retroarch", "--verify-packs"], ["--required-only"], - "refuse"), - (["--platform", "retroarch", "--verify-packs"], ["--source", "truth"], - "refuse"), - # Modes that read none of these: the flag reached the filename or - # nothing at all, never the selection. - (["--emulator", "duckstation"], ["--source", "truth"], "refuse"), - (["--system", "sony-playstation"], ["--source", "truth"], "refuse"), - (["--manifest-targets"], ["--target", "switch"], "refuse"), - (["--manifest-targets"], ["--required-only"], "refuse"), - (["--manifest-targets"], ["--source", "truth"], "refuse"), - (["--platform", "retroarch", "--from-md5", "d8f1"], - ["--target", "switch"], "refuse"), - (["--platform", "retroarch", "--from-md5", "d8f1"], - ["--required-only"], "refuse"), - (["--platform", "retroarch", "--from-md5", "d8f1"], - ["--source", "truth"], "refuse"), - (["--platform", "retroarch", "--manifest"], - ["--system", "sony-playstation"], "refuse"), - (["--platform", "retroarch", "--split"], - ["--system", "sony-playstation"], "refuse"), - # --all took the same filter and wrote twelve complete manifests. - (["--all", "--manifest"], ["--system", "sony-playstation"], "refuse"), - (["--all", "--split"], ["--system", "sony-playstation"], "refuse"), - # A pack built with --system is named after its systems, but the check - # looked for the full pack instead. - (["--platform", "retroarch", "--verify-packs"], - ["--system", "sony-playstation"], "refuse"), - # --all-variants builds its own six combinations: it overrode these - # and the single-pack modes never read it at all. - (["--platform", "retroarch", "--all-variants"], ["--source", "truth"], - "refuse"), - (["--platform", "retroarch", "--all-variants"], ["--required-only"], - "refuse"), - # The default value typed out is still the flag: compared with its - # default, `--source full` and `--group-by system` went through. - (["--platform", "retroarch", "--all-variants"], ["--source", "full"], - "refuse"), - (["--manifest-targets"], ["--source", "full"], "refuse"), - (["--emulator", "handy"], ["--source", "full"], "refuse"), - (["--platform", "retroarch", "--from-md5", "d8f1"], - ["--source", "full"], "refuse"), - (["--platform", "retroarch", "--offline"], ["--group-by", "system"], - "refuse"), - (["--platform", "retroarch", "--verify-packs"], ["--group-by", "system"], - "refuse"), - (["--emulator", "duckstation"], ["--all-variants"], "refuse"), - (["--system", "sony-playstation"], ["--all-variants"], "refuse"), - (["--emulator", "duckstation", "--verify-packs"], ["--all-variants"], - "refuse"), - (["--all", "--manifest", "--all-variants"], ["--verify-packs"], - "refuse"), - (["--all", "--all-variants", "--verify-packs"], ["--one-per-slot"], - "refuse"), - (["--all", "--all-variants", "--verify-packs"], ["--split"], - "refuse"), - # Every flag a quick mode does not read, from one table. - (["--platform", "retroarch", "--verify-packs"], ["--split"], "refuse"), - (["--platform", "retroarch", "--verify-packs"], ["--manifest"], "refuse"), - (["--platform", "retroarch", "--verify-packs"], ["--emulator", "handy"], - "refuse"), - (["--manifest-targets"], ["--platform", "batocera"], "refuse"), - (["--manifest-targets"], ["--system", "sony-playstation"], "refuse"), - (["--manifest-targets"], ["--all"], "refuse"), - (["--platform", "retroarch", "--from-md5", "d8f1"], ["--manifest"], - "refuse"), - (["--list-systems"], ["--region", "us"], "refuse"), - (["--list-emulators"], ["--target", "switch"], "refuse"), - # Only the platform path refreshes data directories. - (["--emulator", "dolphin"], ["--refresh-data"], "refuse"), - (["--system", "sony-playstation"], ["--refresh-data"], "refuse"), - (["--from-md5", "d8f1"], ["--refresh-data"], "refuse"), - (["--platform", "retroarch", "--offline"], ["--refresh-data"], "refuse"), - (["--emulator", "dolphin"], ["--no-refresh-data"], "refuse"), - (["--system", "sony-playstation"], ["--no-refresh-data"], "refuse"), - (["--platform", "retroarch", "--offline"], ["--no-refresh-data"], "refuse"), - (["--platform", "retroarch", "--refresh-data"], ["--no-refresh-data"], - "refuse"), - # Documented as adding core files, read by nothing. - (["--emulator", "handy"], ["--include-extras"], "refuse"), - (["--system", "atari-lynx"], ["--include-extras"], "refuse"), - # Game data is categorized against a platform's list and the - # cores it runs: the modes without a platform refuse it, and - # --all-variants builds its own fixed set. - (["--emulator", "handy"], ["--no-game-data"], "refuse"), - (["--system", "atari-lynx"], ["--no-game-data"], "refuse"), - (["--platform", "retroarch", "--from-md5", "d8f1"], ["--no-game-data"], - "refuse"), - (["--from-md5", "d8f1"], ["--no-game-data"], "refuse"), - (["--manifest-targets"], ["--no-game-data"], "refuse"), - (["--platform", "retroarch", "--all-variants"], ["--no-game-data"], - "refuse"), - (["--list-systems"], ["--no-game-data"], "refuse"), - (["--list"], ["--no-game-data"], "refuse"), - # --counts records the full platform packs the pipeline compares - # with verify: a mode that builds none refuses it. - (["--emulator", "handy"], ["--counts", "counts.json"], "refuse"), - (["--platform", "retroarch", "--manifest"], ["--counts", "counts.json"], "refuse"), - (["--platform", "retroarch", "--split"], ["--counts", "counts.json"], "refuse"), - (["--platform", "retroarch", "--system", "sony-playstation"], - ["--counts", "counts.json"], "refuse"), - (["--platform", "retroarch", "--from-md5", "d8f1"], ["--counts", "counts.json"], - "refuse"), - (["--platform", "retroarch", "--verify-packs"], ["--counts", "counts.json"], - "refuse"), - (["--list"], ["--counts", "counts.json"], "refuse"), - ] - for mode, flag, expected in matrix: - with self.subTest(mode=mode, flag=flag): - self.assertEqual(expected, "refuse") - result = subprocess.run( - [sys.executable, "scripts/generate_pack.py", *mode, *flag, - "--output-dir", os.path.join(self.root, "modecheck")], - capture_output=True, text=True, cwd=repo, timeout=120, - check=False, - ) - combined = result.stdout + result.stderr - self.assertNotEqual( - result.returncode, 0, - f"{' '.join(mode + flag)} was accepted and ignored:\n{combined}", - ) - self.assertIn("error:", combined) - # The refusal names a flag the command carries: "requires - # --platform or --all" answered --platform --system - # --one-per-slot, and the user could not tell what to drop. - message = combined[combined.index("error:"):].splitlines()[0] - passed = [arg for arg in mode + flag if arg.startswith("--")] - self.assertTrue( - any(arg in message for arg in passed), - f"{' '.join(mode + flag)}: {message}", - ) - demanded = message.partition(" requires ")[2].replace(",", " ").split() - self.assertFalse( - [arg for arg in passed if arg in demanded], - f"{' '.join(mode + flag)} asks for a flag it was given: {message}", - ) - - def test_conformance_narrows_by_target_like_it_does_by_region(self): - """A targeted pack is checked against the targeted expectation. - - --target narrowed the build and nothing else: the conformance stage - held every targeted pack to the platform's whole system list and - core set, so a correct build exited non-zero on hundreds of files it - was never asked to carry. Region was already passed to the check, and - target has to travel the same way, which is why the pack is checked - as a full pack. - """ - import inspect - - from packs import platformcheck - from packs.naming import pack_narrowings, pack_variant - - source = inspect.getsource(platformcheck.verify_pack_against_platform) - self.assertIn( - "target_cores", - inspect.signature(platformcheck.verify_pack_against_platform).parameters, - "the pack verifier takes no target, so it cannot narrow by one", - ) - self.assertIn( - "platform_scope_systems(config, emu_profiles, target_cores)", - source, - "the baseline expectation is not narrowed by the target, as the pack and verify narrow it", - ) - self.assertIn( - "target_cores=target_cores", - source, - "the core-extras expectation is not narrowed by the target", - ) - - # And the pack must not be skipped instead: skipping checks nothing. - for target in ("nintendo-switch", "switch", "rpi4"): - tag = pack_narrowings("full", None, target, False, False)[0][0] - self.assertEqual( - pack_variant(f"Platform_1.0{tag}_BIOS_Pack.zip"), ("full", False), - f"a pack built for {target} would be checked as a narrowed variant", - ) - - def test_standalone_mode_names_itself(self): - """--emulator --standalone ships a different file set, and without a tag it - overwrote the pack built without it.""" - from packs.naming import pack_narrowings - - applied = pack_narrowings("full", None, None, False, False, standalone=True) - self.assertEqual([tag for tag, _l in applied], ["_Standalone"]) - - def test_every_name_builder_uses_the_same_list(self): - """Four places name a pack or a manifest. None may assemble tags by - hand: that is how --one-per-slot reached --split unnamed.""" - source = script_source("generate_pack.py") - for hand_rolled in ( - 'req_tag = "_Required"', - 'source_tag = {"platform": "_Platform"', - 'req_suffix = "_required"', - 'slot_tag = "_OnePerSlot"', - # The --system rename kept the region tag alone, the custom pack - # took no tag at all, and the skip list retyped four of them. - '_Custom_BIOS_Pack.zip"', - '{rgn_tag}_BIOS_Pack.zip"', - '("_Platform_", "_Truth_"', - ): - self.assertNotIn(hand_rolled, source, hand_rolled) - self.assertGreaterEqual(source.count("pack_narrowings("), 8) - - def test_a_narrowed_system_pack_does_not_take_the_full_name(self): - """Every dimension has to show in the filename or two builds collide. - - --system X --required-only produced the same name as --system X and - overwrote it, because the rename kept only the region tag. - """ - import subprocess - - repo = os.path.join(os.path.dirname(__file__), "..") - names = {} - for label, extra in (("full", []), ("required", ["--required-only"])): - out = os.path.join(self.root, f"sysname_{label}") - proc = subprocess.run( - [sys.executable, "scripts/generate_pack.py", "--system", - "atari-lynx", "--offline", *extra, "--output-dir", out], - capture_output=True, text=True, cwd=repo, timeout=300, - check=False, - ) - self.assertEqual(proc.returncode, 0, proc.stdout + proc.stderr) - names[label] = sorted( - f for f in os.listdir(out) if f.endswith("_BIOS_Pack.zip") - ) - self.assertTrue(names["full"] and names["required"]) - self.assertNotEqual( - names["full"], names["required"], - "a required-only system pack took the name of the full one", - ) - - def test_a_platform_without_cores_has_no_truth_pack(self): - """MiSTer declares cores: []: its truth pack held nothing, passed - its check and exited 0 under a name claiming a content.""" - import subprocess - - repo = os.path.join(os.path.dirname(__file__), "..") - out = os.path.join(self.root, "truth_empty") - proc = subprocess.run( - [sys.executable, "scripts/generate_pack.py", "--platform", "misterfpga", - "--offline", "--source", "truth", "--output-dir", out], - capture_output=True, text=True, cwd=repo, timeout=300, - check=False, - ) - self.assertNotEqual(proc.returncode, 0) - self.assertIn("a truth pack would hold nothing", proc.stderr) - self.assertFalse( - [f for f in os.listdir(out) if f.endswith(".zip")] if os.path.isdir(out) else [] - ) - - def test_an_emulator_needing_no_file_succeeds_like_verify(self): - """Handy requires no file. --required-only removed the empty ZIP, - printed its path and exited 1, while verify reported 0/0 OK.""" - import subprocess - - repo = os.path.join(os.path.dirname(__file__), "..") - out = os.path.join(self.root, "no_file_needed") - proc = subprocess.run( - [sys.executable, "scripts/generate_pack.py", "--emulator", "handy", - "--required-only", "--offline", "--output-dir", out], - capture_output=True, text=True, cwd=repo, timeout=300, - check=False, - ) - self.assertEqual(proc.returncode, 0, proc.stdout + proc.stderr) - self.assertIn("no file needed, no pack written", proc.stdout) - self.assertNotIn(".zip", proc.stdout) - verify = subprocess.run( - [sys.executable, "scripts/verify.py", "--emulator", "handy", "--required-only"], - capture_output=True, text=True, cwd=repo, timeout=300, - check=False, - ) - self.assertEqual(verify.returncode, proc.returncode) - - def test_a_platform_without_cores_refuses_profile_narrowings(self): - """MiSTer and BizHawk declare cores: []. --region, --one-per-slot - and --no-game-data read the profiles, so their packs withdrew - nothing under a name and README that said otherwise.""" - import subprocess - - repo = os.path.join(os.path.dirname(__file__), "..") - out = os.path.join(self.root, "blind") - runs = [ - ["scripts/generate_pack.py", "--platform", "misterfpga", "--region", "us"], - ["scripts/generate_pack.py", "--platform", "misterfpga", "--one-per-slot"], - ["scripts/generate_pack.py", "--platform", "misterfpga", "--no-game-data"], - ["scripts/generate_pack.py", "--platform", "bizhawk", "--manifest", - "--region", "us"], - ["scripts/verify.py", "--platform", "bizhawk", "--region", "us"], - ] - for argv in runs: - extra = ["--offline", "--output-dir", out] if "generate_pack" in argv[0] else [] - with self.subTest(argv=argv): - proc = subprocess.run( - [sys.executable, *argv, *extra], - capture_output=True, text=True, cwd=repo, timeout=300, - check=False, - ) - self.assertEqual(proc.returncode, 1, proc.stdout + proc.stderr) - self.assertIn("runs no core a profile describes", proc.stderr) - self.assertFalse(os.listdir(out) if os.path.isdir(out) else []) - - def test_a_full_pack_is_not_announced_as_narrowed(self): - from packs.readme import build_readme - from packs.naming import pack_narrowings - - self.assertEqual(pack_narrowings("full", None, None, False, False), []) - self.assertNotIn( - "PACK TYPE: Narrowed", build_readme("p", "P", "", 1, 1) - ) - - def test_system_filter_is_announced_too(self): - from packs.readme import build_readme - - readme = build_readme( - "p", "P", "", 1, 1, system_filter=["sony-playstation"] - ) - self.assertIn("PACK TYPE: Narrowed", readme) - self.assertIn("sony-playstation", readme) - - def test_extras_group_under_their_system_not_a_shared_bucket(self): - """A core extra competes in its system's group: the chain from the - gap report (system, systems) to platform_region_groups, not a - dictionary built by hand. Without it every extra stood alone and - --region compared nothing.""" - import hashlib - - from packs.extraregions import platform_region_groups - - files, by_name = {}, {} - for name in ("core_us.bin", "core_jp.bin"): - payload = name.encode() - path = os.path.join(self.bios_dir, name) - with open(path, "wb") as handle: - handle.write(payload) - sha1 = hashlib.sha1(payload).hexdigest() - files[sha1] = {"path": path, "name": name, "size": len(payload), - "md5": hashlib.md5(payload).hexdigest()} - by_name[name] = [sha1] - db = {"files": files, "indexes": {"by_name": by_name, "by_md5": {}, - "by_crc32": {}, "by_path_suffix": {}}} - profiles = {"psxcore": { - "emulator": "PSX Core (Display Name)", "type": "libretro", - "systems": ["sony-playstation"], - "files": [{"name": "core_us.bin", "region": ["north-america"]}, - {"name": "core_jp.bin", "region": ["japan"]}], - }} - config = {"platform": "P", "cores": ["psxcore"], "base_destination": "system", - "systems": {"sony-playstation": {"files": [ - {"name": "declared.bin", "destination": "declared.bin"}]}}} - groups, _ = platform_region_groups( - config, config["systems"], self.emulators_dir, db, "system", profiles, - ) - self.assertEqual( - sorted(groups["sony-playstation"]), - [("core_jp.bin", "core_jp.bin"), ("core_us.bin", "core_us.bin"), - ("declared.bin", "declared.bin")], - ) - - def test_a_system_spelled_two_ways_is_one_group(self): - """RetroDECK files the Master System as sega-master-system, the - profiles as sega-mastersystem. Two groups reduced apart, and a - --region us pack kept the declared Japanese BIOS.""" - import hashlib - - from packs.extraregions import platform_region_groups - - files, by_name = {}, {} - for name in ("bios_U.sms", "bios_J.sms"): - payload = name.encode() - path = os.path.join(self.bios_dir, name) - with open(path, "wb") as handle: - handle.write(payload) - sha1 = hashlib.sha1(payload).hexdigest() - files[sha1] = {"path": path, "name": name, "size": len(payload), - "md5": hashlib.md5(payload).hexdigest()} - by_name[name] = [sha1] - db = {"files": files, "indexes": {"by_name": by_name, "by_md5": {}, - "by_crc32": {}, "by_path_suffix": {}}} - profiles = {"smscore": { - "emulator": "SMS Core", "type": "libretro", - "systems": ["sega-mastersystem"], - "files": [{"name": "bios_U.sms", "region": ["north-america"]}, - {"name": "bios_J.sms", "region": ["japan"]}], - }} - config = {"platform": "P", "cores": ["smscore"], "base_destination": "system", - "systems": {"sega-master-system": {"files": [ - {"name": "bios_J.sms", "destination": "bios/bios_J.sms"}]}}} - groups, _ = platform_region_groups( - config, config["systems"], self.emulators_dir, db, "system", profiles, - ) - self.assertNotIn("sega-mastersystem", groups) - self.assertEqual( - sorted(dest for dest, _ in groups["sega-master-system"]), - ["bios/bios_J.sms", "bios_J.sms", "bios_U.sms"], - ) - - def test_slot_narrowed_pack_gets_its_own_name(self): - names = { - os.path.basename(self._region_pack()), - os.path.basename(self._region_pack(one_per_slot=True)), - } - self.assertEqual(len(names), 2, names) - self.assertTrue(any("OnePerSlot" in n for n in names)) - - def test_verify_pack_return_matches_its_annotation(self): - import inspect - import typing - - from packs.platformpack import generate_pack - from packs.platformcheck import verify_pack_against_platform - - self._create_region_fixtures() - profiles = self._region_profiles() - out = generate_pack( - "regionplat", - self.platforms_dir, - self.db, - self.bios_dir, - self.root, - emu_profiles=profiles, - ) - result = verify_pack_against_platform( - out, "regionplat", self.platforms_dir, db=self.db, emu_profiles=profiles - ) - annotated = typing.get_args( - inspect.signature( - verify_pack_against_platform, eval_str=True - ).return_annotation - ) - self.assertEqual(len(result), len(annotated)) - - def test_narrowed_variants_are_checked_as_built(self): - from packs.naming import pack_variant - - for narrowed, variant in ( - ("EmuDeck_2.3.8_Required_BIOS_Pack.zip", ("full", True)), - ("EmuDeck_2.3.8_Platform_BIOS_Pack.zip", ("platform", False)), - ("EmuDeck_2.3.8_Truth_Required_BIOS_Pack.zip", ("truth", True)), - ("EmuDeck_2.3.8_NorthAmerica_Required_BIOS_Pack.zip", ("full", True)), - ): - self.assertEqual(pack_variant(narrowed), variant, narrowed) - - for full in ( - "EmuDeck_2.3.8_BIOS_Pack.zip", - "EmuDeck_2.3.8_NorthAmerica_BIOS_Pack.zip", - "RetroArch_v1.22.2_Switch_BIOS_Pack.zip", - ): - self.assertEqual(pack_variant(full), ("full", False), full) - - def test_target_tag_formats_hardware_names(self): - from packs.naming import _target_tag - - self.assertEqual(_target_tag("switch"), "Switch") - self.assertEqual(_target_tag("rpi4"), "Rpi4") - self.assertEqual(_target_tag("x86_64"), "X86 64".replace(" ", "")) - - def test_targeted_pack_does_not_overwrite_the_full_one(self): - names = { - os.path.basename(self._region_pack()), - os.path.basename(self._region_pack(target_name="switch")), - } - self.assertEqual(len(names), 2, names) - self.assertTrue(any("Switch" in n for n in names)) - - def test_target_and_region_tags_compose_in_the_name(self): - name = os.path.basename( - self._region_pack(regions=["north-america"], target_name="switch") - ) - self.assertIn("NorthAmerica", name) - self.assertIn("Switch", name) - - def test_readme_region_section_lists_fallback_systems(self): - from packs.readme import build_readme - - text = build_readme( - "regionplat", - "RegionPlat", - "", - 10, - 2, - regions=["north-america"], - fallback_systems=["nintendo-fds"], - ) - self.assertIn("PACK TYPE: Region Filtered", text) - self.assertIn("Region priority: North America", text) - self.assertIn("nintendo-fds", text) - self.assertIn("This pack was filtered", text) - self.assertNotIn("All are included", text) - - def test_readme_without_region_keeps_the_regional_note(self): - from packs.readme import build_readme - - text = build_readme("regionplat", "RegionPlat", "", 10, 2) - self.assertNotIn("PACK TYPE: Region Filtered", text) - self.assertIn("All are included", text) - - def test_verify_agrees_with_region_filtered_pack(self): - from packs.platformcheck import verify_pack_against_platform - - out = self._region_pack(regions=["north-america"]) - result = verify_pack_against_platform( - out, - "regionplat", - self.platforms_dir, - db=self.db, - emu_profiles=self._region_profiles(), - regions=["north-america"], - ) - ok, _checked, _present, errors = result[:4] - self.assertTrue(ok, errors) - - def test_verify_reports_the_gap_without_the_region_filter(self): - from packs.platformcheck import verify_pack_against_platform - - out = self._region_pack(regions=["north-america"]) - result = verify_pack_against_platform( - out, - "regionplat", - self.platforms_dir, - db=self.db, - emu_profiles=self._region_profiles(), - ) - ok, _checked, _present, errors = result[:4] - self.assertFalse(ok) - self.assertTrue(any("rgn_jp.bin" in e for e in errors), errors) - - def test_region_composes_with_source_truth(self): - names = self._names_in( - self._region_pack(regions=["north-america"], source="truth") - ) - self.assertIn("rgn_us.bin", names) - self.assertNotIn("rgn_jp.bin", names) - - # ---- gap analysis resolves files the pack can already ship ---- - - @staticmethod - def _gap_db(repo_name: str, sha1: str, crc32: str) -> dict: - return { - "files": {sha1: {"path": f"bios/{repo_name}", "size": 8192, "crc32": crc32}}, - "indexes": { - "by_name": {repo_name: [sha1]}, - "by_md5": {}, - "by_crc32": {crc32: sha1}, - "by_sha256": {}, - "by_path_suffix": {}, - }, - } - - def _gap_source(self, entry: dict, db: dict) -> str: - from packs.crossref import cross_reference - - report = cross_reference( - {"gapemu": {"emulator": "GapEmu", "systems": ["s"], "files": [entry]}}, - {"s": set()}, - db, - ) - return report["gapemu"]["gap_details"][0]["source"] - - def test_gap_analysis_resolves_by_alias(self): - """A file stored under an alias is in the repo, not a sourcing target.""" - db = self._gap_db("REPO_chip.rom", "a" * 40, "465c4e1c") - entry = {"name": "chip.rom", "aliases": ["REPO_chip.rom"], "required": True} - self.assertEqual(self._gap_source(entry, db), "bios") - - def test_gap_analysis_resolves_by_crc32(self): - """crc32 is the only hash some emulators declare.""" - db = self._gap_db("REPO_chip.rom", "a" * 40, "465c4e1c") - entry = {"name": "chip.rom", "crc32": "465c4e1c", "required": True} - self.assertEqual(self._gap_source(entry, db), "bios") - - def test_gap_analysis_reports_unknown_file_missing(self): - db = self._gap_db("REPO_chip.rom", "a" * 40, "465c4e1c") - entry = {"name": "chip.rom", "aliases": ["OTHER.rom"], "crc32": "deadbeef"} - self.assertEqual(self._gap_source(entry, db), "missing") - - def test_gap_analysis_resolves_renamed_mame_set(self): - """A renamed set is held under the name dedup kept, as verify reads it.""" - from model import database - - db = self._gap_db("v4bios.zip", "a" * 40, "465c4e1c") - original = database.get_mame_clone_map - database.get_mame_clone_map = lambda *_a: {"bctvidbs.zip": "v4bios.zip"} - try: - entry = {"name": "bctvidbs.zip", "required": True} - self.assertEqual(self._gap_source(entry, db), "bios") - finally: - database.get_mame_clone_map = original - - -class StandaloneModeRequiresAStandaloneBuild(unittest.TestCase): - """A platform names its standalone emulators by its own names, which can - equal the key of a libretro-only profile (Recalbox and Batocera both - call their standalone ScummVM ``scummvm``). Laid out standalone, such a - profile loses every ``path:`` and drops its files at the root.""" - - def test_libretro_only_profile_keeps_its_layout(self): - from resolve.launches import PlatformLaunches - - libretro_only = {"type": "libretro", "cores": ["scummvm"]} - dual = {"type": "standalone + libretro", "cores": ["dolphin"]} - standalone = {"type": "standalone", "cores": ["xemu"]} - named = PlatformLaunches(standalone=frozenset({"scummvm", "dolphin", "xemu", "hatari"})) - self.assertFalse(named.runs_standalone("scummvm", libretro_only)) - self.assertTrue(named.runs_standalone("dolphin", dual)) - self.assertTrue(named.runs_standalone("xemu", standalone)) - self.assertTrue(named.runs_standalone("other-key", {"type": "standalone", "cores": ["hatari"]})) - self.assertFalse(PlatformLaunches().runs_standalone("dolphin", dual)) - self.assertFalse( - PlatformLaunches(standalone=frozenset({"pcsx2"})).runs_standalone("dolphin", dual) - ) - - - -class OneOfASearchList(unittest.TestCase): - """Entries a core takes the first of are one need (``group:``). - - Yabause tries saturn_bios.bin, sega_101.bin, mpr-17933.bin and loads the - first it finds. Written as required on the first name only, verify and - the gap report called saturn_bios.bin a missing required file while - sega_101.bin was held, and a set held through an optional-looking name - passed for the wrong reason. Synthetic: set ``first`` holds only its - second member, set ``none`` holds nothing. - """ - - def setUp(self): - from model.profiles import emulator_profiles_cache - - emulator_profiles_cache.clear() - self.root = Path(tempfile.mkdtemp()) - self.addCleanup(shutil.rmtree, self.root, True) - previous = os.getcwd() - os.chdir(self.root) - self.addCleanup(os.chdir, previous) - self.db = {"files": {}, "indexes": {"by_md5": {}, "by_name": {}, - "by_crc32": {}, "by_path_suffix": {}}} - for name in ("second.bin", "third.bin", "plain.bin"): - data = name.encode() * 8 - rel = f"bios/Test/Console/{name}" - Path(rel).parent.mkdir(parents=True, exist_ok=True) - Path(rel).write_bytes(data) - sha1 = hashlib.sha1(data).hexdigest() - self.db["files"][sha1] = {"path": rel, "name": name, "size": len(data), - "md5": hashlib.md5(data).hexdigest(), "crc32": ""} - self.db["indexes"]["by_name"][name] = [sha1] - Path("emulators").mkdir() - Path("platforms").mkdir() - - def member(name: str, group: str, rank: int) -> dict: - return {"name": name, "system": "console-a", "group": group, - "priority": rank} - - raw = { - "emulator": "Seq", "type": "libretro", "cores": ["seq"], - "systems": ["console-a"], - "groups": {"first": {"required": True}, "none": {"required": True}}, - "files": [ - member("first.bin", "first", 1), - member("second.bin", "first", 2), - member("third.bin", "first", 3), - member("none_a.bin", "none", 1), - member("none_b.bin", "none", 2), - {"name": "plain.bin", "system": "console-a", "required": True}, - ], - } - Path("emulators/seq.yml").write_text(yaml.safe_dump(raw)) - self.raw = raw - # What every reader sees: the profile as load_emulator_profiles gives it. - self.profile = load_emulator_profiles("emulators")["seq"] - self.config = { - "platform": "Seqs", "verification_mode": "existence", - "base_destination": "system", "cores": ["seq"], - "systems": {"console-a": {"files": []}}, - } - - def _verify(self) -> dict: - return verify_emulator(["seq"], "emulators", self.db, platforms_dir="platforms") - - def test_one_member_held_leaves_no_missing_report_for_its_set(self): - result = self._verify() - reported = {d["name"]: d["status"] for d in result["details"]} - self.assertEqual(reported["second.bin"], "ok") - self.assertEqual(reported["third.bin"], "ok") - self.assertNotIn("first.bin", reported) - self.assertEqual( - sorted(d["name"] for d in result["set_members"]), - ["first.bin", "none_b.bin"], - ) - - def test_a_set_none_holds_is_one_gap(self): - result = self._verify() - missing = [d for d in result["details"] if d["status"] == "missing"] - self.assertEqual([d["name"] for d in missing], ["none_a.bin"]) - self.assertEqual(missing[0]["alternatives"], ["none_b.bin"]) - # Required and missing, judged as the core judges: one warning. - self.assertEqual(result["severity_counts"][Severity.WARNING], 1) - self.assertEqual(result["severity_counts"][Severity.INFO], 0) - self.assertEqual(result["status_counts"].get("missing"), 1) - self.assertEqual(result["total_files"], 4) - - def test_a_required_set_held_through_a_later_member_is_satisfied(self): - """second.bin used to read required: false beside a required - first.bin: the set is required and held, so nothing is critical - for it, and the strict exit names only the set nobody holds.""" - from packs.strictgate import emulator_strict_failure - - result = self._verify() - critical = [d["name"] for d in result["details"] - if d["status"] == "missing" and d["required"]] - self.assertEqual(critical, ["none_a.bin"]) - self.assertIn("1 required file(s) missing: none_a.bin", - emulator_strict_failure(result) or "") - - def test_pack_and_verify_agree(self): - from packs.emulatorpack import generate_emulator_pack - - result = self._verify() - out = io.StringIO() - with contextlib.redirect_stdout(out): - zip_path = generate_emulator_pack( - ["seq"], "emulators", self.db, "bios", "out", offline=True, - platforms_dir="platforms", - ) - with zipfile.ZipFile(zip_path) as zf: - packed = sorted(n for n in zf.namelist() if n != "README.txt") - self.assertEqual(packed, ["plain.bin", "second.bin", "third.bin"]) - self.assertEqual(result["severity_counts"]["ok"], len(packed)) - lines = out.getvalue().splitlines() - self.assertEqual( - [line.split(": ", 1)[1] for line in lines if line.strip().startswith("MISSING:")], - ["none_a.bin"], - ) - self.assertIn("3 files packed, 1 missing", out.getvalue()) - - def test_core_complement_reports_one_gap_per_set(self): - undeclared = find_undeclared_files( - self.config, "emulators", self.db, {"seq": self.profile} - ) - by_name = {u["name"]: u for u in undeclared} - self.assertEqual( - sorted(by_name), ["none_a.bin", "plain.bin", "second.bin", "third.bin"] - ) - self.assertTrue(by_name["second.bin"]["in_repo"]) - self.assertFalse(by_name["none_a.bin"]["in_repo"]) - self.assertEqual(by_name["none_a.bin"]["alternatives"], ["none_b.bin"]) - - def test_a_platform_declaration_speaks_for_the_set(self): - """The platform declares first.bin and reports it in its own check: - the core's other names are not gaps on top of it.""" - config = {**self.config, "systems": {"console-a": {"files": [ - {"name": "first.bin", "destination": "first.bin", "required": True}, - {"name": "none_b.bin", "destination": "none_b.bin", "required": True}, - ]}}} - undeclared = find_undeclared_files( - config, "emulators", self.db, {"seq": self.profile} - ) - self.assertEqual( - sorted(u["name"] for u in undeclared), ["plain.bin", "second.bin", "third.bin"] - ) - - def test_gap_report_counts_the_set_once(self): - from packs import crossref - - index = { - "by_name": self.db["indexes"]["by_name"], - "by_name_lower": {k.lower(): k for k in self.db["indexes"]["by_name"]}, - "by_path_suffix": {}, "by_md5": {}, "by_sha256": {}, "by_crc32": {}, - "data_names": set(), "all_declared": set(), "db_files": self.db["files"], - } - report: dict = {} - crossref._cross_reference_profile("seq", self.profile, {}, report, index) - gaps = {g["name"]: g for g in report["seq"]["gap_details"]} - self.assertEqual(sorted(gaps), ["none_a.bin", "plain.bin", "second.bin", "third.bin"]) - self.assertEqual(gaps["none_a.bin"]["alternatives"], ["none_b.bin"]) - self.assertEqual(report["seq"]["set_aside"]["other_versions"], 2) - - def test_truth_names_no_member_required_on_its_own(self): - from resolve.truth import _fold_into, _new_truth_entry - - entry = _new_truth_entry(dict(self.profile["files"][0]), "seq", None) - self.assertNotIn("required", entry) - self.assertEqual(entry["_required_by"], set()) - self.assertTrue(entry["one_of_required"]) - _fold_into(entry, {"name": "first.bin", "required": True}, "other") - self.assertTrue(entry["required"]) - self.assertEqual(entry["_required_by"], {"other"}) - - def test_ranks_order_one_set_and_never_two(self): - """px68k-sdl ranks its IPL list and its font list each from 1: - --one-per-slot keeps the first of each, not one file of the two.""" - from resolve.slot import build_slot_index, resolve_slot_drops - - profile = {"type": "standalone", "files": [ - {"name": "ipl_a.dat", "group": "ipl", "priority": 1}, - {"name": "ipl_b.dat", "group": "ipl", "priority": 2}, - {"name": "font_a.dat", "group": "font", "priority": 1}, - {"name": "font_b.dat", "group": "font", "priority": 2}, - ]} - index = build_slot_index({"x68": profile}) - groups = {"sharp-x68000": [(n, n) for n in - ("ipl_a.dat", "ipl_b.dat", "font_a.dat", "font_b.dat")]} - drops, undecidable = resolve_slot_drops(groups, index) - self.assertEqual(drops, {"ipl_b.dat", "font_b.dat"}) - self.assertEqual(undecidable, []) - - def test_an_archive_needs_one_member_of_a_set(self): - import zlib - - from resolve.archives import holds_required_members - - path = self.root / "set.zip" - with zipfile.ZipFile(path, "w") as zf: - zf.writestr("boot_b.ic94", b"B") - zf.writestr("eeprom.ic1", b"E") - crc = {n: f"{zlib.crc32(d):08x}" for n, d in (("a", b"A"), ("b", b"B"), ("e", b"E"))} - members = [ - {"crc32": crc["a"], "required": True, "group": "boot"}, - {"crc32": crc["b"], "required": True, "group": "boot"}, - {"crc32": crc["e"], "required": True}, - ] - self.assertTrue(holds_required_members(str(path), members)) - self.assertFalse(holds_required_members(str(path), members[:1] + members[2:])) - - @unittest.skipUnless(HAS_JSONSCHEMA, "validate_schemas needs jsonschema") - def test_schema_refuses_a_set_split_on_required(self): - from schemas.profilechecks import group_requirement_split - from core.paths import REPO_ROOT - - path = REPO_ROOT / "emulators" / "seq.yml" - own_value = {"groups": {"g": {"required": True}}, - "files": [{"name": "a", "group": "g", "required": False}, - {"name": "b", "group": "g"}]} - self.assertEqual(len(group_requirement_split(path, own_value)), 1) - undeclared_set = {"files": [{"name": "a", "group": "g"}]} - self.assertEqual(len(group_requirement_split(path, undeclared_set)), 1) - unused = {"groups": {"g": {"required": True}}, "files": [{"name": "a"}]} - self.assertEqual(len(group_requirement_split(path, unused)), 1) - self.assertEqual(group_requirement_split(path, self.raw), []) - - def test_a_shared_fallback_takes_its_requirement_from_its_sets(self): - """pom2 falls back on apple2e.rom for the //e it boots by default - and for the unenhanced //e it may be switched to. One value on the - file cannot say both: the sets carry it.""" - from model.alternatives import derive_member_requirements - - profile = {"groups": {"iie": {"required": True}, "iie-u": {"required": False}}, - "files": [{"name": "apple2e_unenh.rom", "group": "iie-u"}, - {"name": "apple2e.rom", "group": ["iie", "iie-u"]}]} - derive_member_requirements(profile) - self.assertEqual([f["required"] for f in profile["files"]], [False, True]) - - def test_required_only_keeps_one_held_member_per_required_set(self): - """second.bin and third.bin are both held: a --required-only pack - carries second.bin, the first the code reads among those held, and - verify reports the same single file.""" - from packs.emulatorpack import generate_emulator_pack - - result = verify_emulator(["seq"], "emulators", self.db, - platforms_dir="platforms", required_only=True) - held = sorted(d["name"] for d in result["details"] if d["status"] == "ok") - self.assertEqual(held, ["plain.bin", "second.bin"]) - with contextlib.redirect_stdout(io.StringIO()): - zip_path = generate_emulator_pack( - ["seq"], "emulators", self.db, "bios", "out", offline=True, - platforms_dir="platforms", required_only=True, - ) - with zipfile.ZipFile(zip_path) as zf: - packed = sorted(n for n in zf.namelist() if n != "README.txt") - self.assertEqual(packed, held) - - def test_required_only_core_files_keep_one_member(self): - from model.alternatives import core_file_spares - - undeclared = find_undeclared_files( - self.config, "emulators", self.db, {"seq": self.profile} - ) - spares = core_file_spares(undeclared) - kept = sorted(u["name"] for u in undeclared if id(u) not in spares) - self.assertEqual(kept, ["none_a.bin", "plain.bin", "second.bin"]) - -class AnArchiveIsAMemberOfASet(unittest.TestCase): - """Kronos reads kronos/stvbios.zip, else stvbios.zip at the root: one - archive under two paths, a first-found pair. The archive unit and the - root copy settle as members of one set, and a --required-only pack - carries the first, while the members inside still settle the archive - by its contents.""" - - def _fixture(self, held: bool) -> dict: - import zlib - - from model.profiles import emulator_profiles_cache - - emulator_profiles_cache.clear() - root = Path(tempfile.mkdtemp()) - self.addCleanup(shutil.rmtree, root, True) - previous = os.getcwd() - os.chdir(root) - self.addCleanup(os.chdir, previous) - self.db: dict = {"files": {}, "indexes": {"by_md5": {}, "by_name": {}, - "by_crc32": {}, "by_path_suffix": {}}} - rom = b"STV" * 64 - if held: - rel = "bios/Sega/STV/set.zip" - Path(rel).parent.mkdir(parents=True) - with zipfile.ZipFile(rel, "w") as zf: - zf.writestr("epr.ic8", rom) - data = Path(rel).read_bytes() - sha1 = hashlib.sha1(data).hexdigest() - self.db["files"][sha1] = {"path": rel, "name": "set.zip", "size": len(data), - "md5": hashlib.md5(data).hexdigest(), "crc32": ""} - self.db["indexes"]["by_name"]["set.zip"] = [sha1] - Path("emulators").mkdir() - Path("platforms").mkdir() - Path("emulators/stv.yml").write_text(yaml.safe_dump({ - "emulator": "Stv", "type": "libretro", "cores": ["stv"], - "systems": ["sega-stv"], "archive_prefix": "stv", - "groups": {"stv-bios": {"required": True}}, - "files": [ - {"name": "set.zip", "system": "sega-stv", "group": "stv-bios"}, - {"name": "epr.ic8", "archive": "set.zip", "system": "sega-stv", - "required": True, "crc32": f"{zlib.crc32(rom):08x}"}, - ], - })) - return load_emulator_profiles("emulators")["stv"] - - def test_the_archive_and_its_root_copy_are_one_need(self): - self._fixture(held=False) - result = verify_emulator(["stv"], "emulators", self.db, platforms_dir="platforms") - missing = [d for d in result["details"] if d["status"] == "missing"] - self.assertEqual([d["destination"] for d in missing], ["stv/set.zip"]) - self.assertEqual(missing[0]["alternatives"], ["set.zip"]) - self.assertEqual(result["status_counts"].get("missing"), 1) - - def test_required_only_carries_the_archive_the_code_reads_first(self): - from packs.emulatorpack import generate_emulator_pack - - self._fixture(held=True) - full = verify_emulator(["stv"], "emulators", self.db, platforms_dir="platforms") - self.assertEqual( - sorted(d["destination"] for d in full["details"] if d["status"] == "ok"), - ["set.zip", "stv/set.zip"], - ) - result = verify_emulator(["stv"], "emulators", self.db, - platforms_dir="platforms", required_only=True) - held = sorted(d["destination"] for d in result["details"] if d["status"] == "ok") - self.assertEqual(held, ["stv/set.zip"]) - with contextlib.redirect_stdout(io.StringIO()): - zip_path = generate_emulator_pack( - ["stv"], "emulators", self.db, "bios", "out", offline=True, - platforms_dir="platforms", required_only=True, - ) - with zipfile.ZipFile(zip_path) as zf: - packed = sorted(n for n in zf.namelist() if n != "README.txt") - self.assertEqual(packed, held) - - def test_core_files_report_the_pair_once(self): - profile = self._fixture(held=False) - config = {"platform": "Stvs", "verification_mode": "existence", - "base_destination": "system", "cores": ["stv"], - "systems": {"sega-stv": {"files": []}}} - undeclared = find_undeclared_files(config, "emulators", self.db, {"stv": profile}) - self.assertEqual([u["name"] for u in undeclared], ["set.zip"]) - self.assertTrue(undeclared[0].get("archive")) - -if __name__ == "__main__": - unittest.main() diff --git a/tests/test_e2e_diff_export.py b/tests/test_e2e_diff_export.py new file mode 100644 index 000000000..0f49b4a22 --- /dev/null +++ b/tests/test_e2e_diff_export.py @@ -0,0 +1,990 @@ +"""End-to-end installer configuration, truth diff, exporters and registry merge.""" + +from __future__ import annotations + +import tests +import os +import unittest +from pathlib import Path +import yaml +from model.declarations import expand_platform_declared_names +from model.profiles import load_emulator_profiles +from model.platforms import load_platform_config +from resolve.localfile import resolve_local_file +from resolve.platformdiff import diff_platform_truth +from resolve.truth import generate_platform_truth +from packs.gaps import find_undeclared_files +from tests.e2esupport import E2EFixture + + +class TestE2EInstallerConfig(E2EFixture): + """install.py configuration parsing and standalone copies.""" + + # --------------------------------------------------------------- + # install.py tests + # --------------------------------------------------------------- + + def test_93_parse_retroarch_cfg(self): + """Parse system_directory from retroarch.cfg.""" + from install import _parse_retroarch_system_dir + + cfg = os.path.join(self.root, "retroarch.cfg") + # Quoted absolute path + with open(cfg, "w") as f: + f.write('system_directory = "/home/user/ra/system"\n') + result = _parse_retroarch_system_dir(Path(cfg)) + self.assertEqual(result, Path("/home/user/ra/system")) + # Default value + with open(cfg, "w") as f: + f.write('system_directory = "default"\n') + result = _parse_retroarch_system_dir(Path(cfg)) + self.assertEqual(result, Path(self.root) / "system") + # Unquoted + with open(cfg, "w") as f: + f.write("system_directory = /tmp/ra_system\n") + result = _parse_retroarch_system_dir(Path(cfg)) + self.assertEqual(result, Path("/tmp/ra_system")) + + def test_94_parse_emudeck_settings(self): + """Parse emulationPath from EmuDeck settings.sh.""" + from install import _parse_bash_var + + settings = os.path.join(self.root, "settings.sh") + with open(settings, "w") as f: + f.write( + 'emulationPath="/home/deck/Emulation"\nromsPath="/home/deck/Emulation/roms"\n' + ) + result = _parse_bash_var(Path(settings), "emulationPath") + self.assertEqual(result, "/home/deck/Emulation") + + def test_95_parse_ps1_var(self): + """Parse $emulationPath from EmuDeck settings.ps1.""" + from install import _parse_ps1_var + + settings = os.path.join(self.root, "settings.ps1") + with open(settings, "w") as f: + f.write('$emulationPath="C:\\Emulation"\n') + result = _parse_ps1_var(Path(settings), "$emulationPath") + self.assertEqual(result, "C:\\Emulation") + + def test_96_target_filtering(self): + """--target filters files by cores field.""" + from install import _filter_by_target + + files = [ + {"dest": "a.bin", "cores": None}, + {"dest": "b.bin", "cores": ["flycast", "redream"]}, + {"dest": "c.bin", "cores": ["dolphin"]}, + ] + filtered = _filter_by_target(files, ["flycast", "snes9x"]) + dests = [f["dest"] for f in filtered] + self.assertIn("a.bin", dests) + self.assertIn("b.bin", dests) + self.assertNotIn("c.bin", dests) + + def test_97_standalone_copies(self): + """Standalone keys copied to existing emulator dirs.""" + from install import do_standalone_copies + + bios_dir = Path(self.root) / "bios" + bios_dir.mkdir(exist_ok=True) + (bios_dir / "prod.keys").write_bytes(b"KEYS") + yuzu_dir = Path(self.root) / "yuzu_keys" + yuzu_dir.mkdir() + missing_dir = Path(self.root) / "nonexistent" + manifest = { + "base_destination": "bios", + "files": [{"dest": "prod.keys"}], + "standalone_copies": [ + { + "file": "prod.keys", + "targets": {"linux": [str(yuzu_dir), str(missing_dir)]}, + } + ], + } + copied, skipped, _ = do_standalone_copies(manifest, bios_dir, "linux") + self.assertEqual(copied, 1) + self.assertEqual(skipped, 1) + self.assertTrue((yuzu_dir / "prod.keys").exists()) + self.assertFalse((missing_dir / "prod.keys").exists()) + + +class TestE2EDiffTruth(E2EFixture): + """diff_platform_truth divergences.""" + + # --------------------------------------------------------------- + # diff_platform_truth tests + # --------------------------------------------------------------- + + def test_98_diff_truth_missing(self): + """Truth has 2 files, scraped has 1 -> 1 missing with cores/source_refs.""" + truth = { + "systems": { + "test-sys": { + "_coverage": {"cores_profiled": ["core_a"], "cores_unprofiled": []}, + "files": [ + { + "name": "bios_a.bin", + "required": True, + "md5": "aaa", + "_cores": ["core_a"], + "_source_refs": ["src/a.c:10"], + }, + { + "name": "bios_b.bin", + "required": False, + "md5": "bbb", + "_cores": ["core_a"], + "_source_refs": ["src/b.c:20"], + }, + ], + } + } + } + scraped = { + "systems": { + "test-sys": { + "files": [{"name": "bios_a.bin", "md5": "aaa"}], + } + } + } + result = diff_platform_truth(truth, scraped) + self.assertEqual(result["summary"]["total_missing"], 1) + div = result["divergences"]["test-sys"] + self.assertEqual(len(div["missing"]), 1) + m = div["missing"][0] + self.assertEqual(m["name"], "bios_b.bin") + self.assertEqual(m["cores"], ["core_a"]) + self.assertEqual(m["source_refs"], ["src/b.c:20"]) + + def test_99_diff_truth_extra_phantom(self): + """All cores profiled, scraped has extra file -> extra_phantom.""" + truth = { + "systems": { + "test-sys": { + "_coverage": {"cores_profiled": ["core_a"], "cores_unprofiled": []}, + "files": [ + { + "name": "bios.bin", + "md5": "aaa", + "_cores": ["core_a"], + "_source_refs": [], + }, + ], + } + } + } + scraped = { + "systems": { + "test-sys": { + "files": [ + {"name": "bios.bin", "md5": "aaa"}, + {"name": "phantom.bin", "md5": "zzz"}, + ], + } + } + } + result = diff_platform_truth(truth, scraped) + self.assertEqual(result["summary"]["total_extra_phantom"], 1) + div = result["divergences"]["test-sys"] + self.assertEqual(len(div["extra_phantom"]), 1) + self.assertEqual(div["extra_phantom"][0]["name"], "phantom.bin") + + def test_100_diff_truth_extra_unprofiled(self): + """Some cores unprofiled, scraped has extra -> extra_unprofiled.""" + truth = { + "systems": { + "test-sys": { + "_coverage": { + "cores_profiled": ["core_a"], + "cores_unprofiled": ["core_b"], + }, + "files": [ + { + "name": "bios.bin", + "md5": "aaa", + "_cores": ["core_a"], + "_source_refs": [], + }, + ], + } + } + } + scraped = { + "systems": { + "test-sys": { + "files": [ + {"name": "bios.bin", "md5": "aaa"}, + {"name": "extra.bin", "md5": "yyy"}, + ], + } + } + } + result = diff_platform_truth(truth, scraped) + self.assertEqual(result["summary"]["total_extra_unprofiled"], 1) + div = result["divergences"]["test-sys"] + self.assertEqual(len(div["extra_unprofiled"]), 1) + self.assertEqual(div["extra_unprofiled"][0]["name"], "extra.bin") + + def test_101_diff_truth_alias_matching(self): + """Truth file with aliases, scraped uses alias -> not extra or missing.""" + truth = { + "systems": { + "test-sys": { + "_coverage": {"cores_profiled": ["core_a"], "cores_unprofiled": []}, + "files": [ + { + "name": "bios.bin", + "md5": "aaa", + "aliases": ["alt.bin"], + "_cores": ["core_a"], + "_source_refs": [], + }, + ], + } + } + } + scraped = { + "systems": { + "test-sys": { + "files": [{"name": "alt.bin", "md5": "aaa"}], + } + } + } + result = diff_platform_truth(truth, scraped) + self.assertEqual(result["summary"]["total_missing"], 0) + self.assertEqual(result["summary"]["total_extra_phantom"], 0) + self.assertNotIn("test-sys", result.get("divergences", {})) + + def test_102_diff_truth_case_insensitive(self): + """Truth 'BIOS.ROM', scraped 'bios.rom' -> match, no missing.""" + truth = { + "systems": { + "test-sys": { + "_coverage": {"cores_profiled": ["core_a"], "cores_unprofiled": []}, + "files": [ + { + "name": "BIOS.ROM", + "md5": "aaa", + "_cores": ["core_a"], + "_source_refs": [], + }, + ], + } + } + } + scraped = { + "systems": { + "test-sys": { + "files": [{"name": "bios.rom", "md5": "aaa"}], + } + } + } + result = diff_platform_truth(truth, scraped) + self.assertEqual(result["summary"]["total_missing"], 0) + self.assertNotIn("test-sys", result.get("divergences", {})) + + def test_103_diff_truth_hash_mismatch(self): + """Same file, different md5 -> hash_mismatch with truth_cores.""" + truth = { + "systems": { + "test-sys": { + "_coverage": {"cores_profiled": ["core_a"], "cores_unprofiled": []}, + "files": [ + { + "name": "bios.bin", + "md5": "truth_hash", + "_cores": ["core_a", "core_b"], + "_source_refs": ["src/x.c:5"], + }, + ], + } + } + } + scraped = { + "systems": { + "test-sys": { + "files": [{"name": "bios.bin", "md5": "scraped_hash"}], + } + } + } + result = diff_platform_truth(truth, scraped) + self.assertEqual(result["summary"]["total_hash_mismatch"], 1) + div = result["divergences"]["test-sys"] + self.assertEqual(len(div["hash_mismatch"]), 1) + hm = div["hash_mismatch"][0] + self.assertEqual(hm["name"], "bios.bin") + self.assertEqual(hm["truth_cores"], ["core_a", "core_b"]) + self.assertEqual(hm["truth_md5"], "truth_hash") + self.assertEqual(hm["scraped_md5"], "scraped_hash") + + def test_104_diff_truth_normalized_system_ids(self): + """Diff matches systems with different ID formats via normalization.""" + from resolve.platformdiff import diff_platform_truth + + truth = { + "systems": { + "sega-gamegear": { + "_coverage": {"cores_profiled": ["c"], "cores_unprofiled": []}, + "files": [ + { + "name": "bios.gg", + "required": True, + "md5": "a" * 32, + "_cores": ["c"], + "_source_refs": [], + }, + ], + }, + } + } + scraped = { + "systems": { + "sega-game-gear": { + "files": [ + {"name": "bios.gg", "required": True, "md5": "a" * 32}, + ], + }, + } + } + + result = diff_platform_truth(truth, scraped) + self.assertEqual(result["summary"]["systems_uncovered"], 0) + self.assertEqual(result["summary"]["total_missing"], 0) + self.assertEqual(result["summary"]["systems_compared"], 1) + + +class TestE2EExporters(E2EFixture): + """native_id preservation, the System.dat exporter and the truth diff chain.""" + + # --------------------------------------------------------------- + # native_id preservation + # --------------------------------------------------------------- + + def test_native_id_preserved_in_platform_config(self): + """load_platform_config preserves native_id at the system level.""" + config = { + "platform": "TestNativeId", + "verification_mode": "existence", + "base_destination": "system", + "systems": { + "sony-playstation": { + "native_id": "Sony - PlayStation", + "files": [ + { + "name": "scph5501.bin", + "destination": "scph5501.bin", + "required": True, + }, + ], + }, + "nintendo-snes": { + "native_id": "snes", + "files": [ + { + "name": "bs-x.bin", + "destination": "bs-x.bin", + "required": False, + }, + ], + }, + }, + } + with open(os.path.join(self.platforms_dir, "test_native_id.yml"), "w") as fh: + yaml.dump(config, fh) + + loaded = load_platform_config("test_native_id", self.platforms_dir) + psx = loaded["systems"]["sony-playstation"] + self.assertEqual(psx["native_id"], "Sony - PlayStation") + snes = loaded["systems"]["nintendo-snes"] + self.assertEqual(snes["native_id"], "snes") + + # --------------------------------------------------------------- + # Exporter: System.dat round-trip + # --------------------------------------------------------------- + + def test_systemdat_exporter_round_trip(self): + """Export truth data to System.dat and validate round-trip.""" + from exporter import discover_exporters + from exporter.systemdat_exporter import Exporter as SystemDatExporter + + truth = { + "platform": "retroarch", + "systems": { + "sony-playstation": { + "files": [ + { + "name": "scph5501.bin", + "path": "scph5501.bin", + "size": 524288, + "md5": "490f666e1afb15ed6c63b88fc7571f2f", + "sha1": "b056ee5a4d65937e1a3a17e1e78f3258ea49c38e", + "crc32": "71af80b4", + "required": True, + "_cores": ["beetle_psx"], + "_source_refs": ["libretro.c:50"], + }, + ], + }, + }, + } + scraped = { + "systems": { + "sony-playstation": { + "native_id": "Sony - PlayStation", + "files": [ + {"name": "scph5501.bin", "destination": "scph5501.bin"}, + ], + }, + }, + } + + from resolve.reconcile import build_native_model + + systems, report = build_native_model(truth, scraped) + exporter = SystemDatExporter() + produced = exporter.render(systems, report, {}, scraped) + content = produced["System.dat"] + self.assertIn("Sony - PlayStation", content) + self.assertIn("scph5501.bin", content) + self.assertIn("b056ee5a4d65937e1a3a17e1e78f3258ea49c38e", content) + self.assertIn('name "System"', content) + self.assertIn("71AF80B4", content) # CRC uppercase + + issues = exporter.validate(systems, produced) + self.assertEqual(issues, []) + + # Discovery finds the systemdat exporter + exporters = discover_exporters() + self.assertIn("retroarch", exporters) + self.assertIs(exporters["retroarch"], SystemDatExporter) + + def test_systemdat_exporter_numeric_crc(self): + """Digit-only crc32 typed as int by YAML must not break the export.""" + from exporter.systemdat_exporter import Exporter as SystemDatExporter + + truth = { + "platform": "retroarch", + "systems": { + "commodore-plus4": { + "files": [ + { + "name": "kernal-318005-05.bin", + "path": "kernal-318005-05.bin", + "size": 16384, + "crc32": 70295038, + "required": False, + }, + ], + }, + }, + } + + from resolve.reconcile import build_native_model + + systems, report = build_native_model(truth, {"systems": {}}) + original = ('clrmamepro (\n\tname "System"\n)\n\ngame (\n\tname "System"\n' + '\tcomment "commodore-plus4"\n)\n') + produced = SystemDatExporter().render( + systems, report, {"System.dat": original}, {"systems": {}} + ) + self.assertIn("crc 70295038", produced["System.dat"]) + + # --------------------------------------------------------------- + # Full truth + diff integration test + # --------------------------------------------------------------- + + def test_truth_diff_integration(self): + """Full chain: generate truth from profiles, diff against scraped data.""" + # Config: platform with two cores, only core_a has a profile + config = {"cores": ["core_a", "core_b"]} + registry_entry = { + "hash_type": "md5", + "verification_mode": "md5", + } + + # Emulator profile for core_a with 2 files + core_a_profile = { + "emulator": "CoreA", + "type": "libretro", + "systems": ["test-system"], + "files": [ + { + "name": "bios_a.bin", + "system": "test-system", + "required": True, + "md5": "a" * 32, + "sha1": "b" * 40, + "size": 1024, + "path": "bios_a.bin", + "source_ref": "src/a.c:10", + }, + { + "name": "shared.bin", + "system": "test-system", + "required": True, + "md5": "c" * 32, + "path": "shared.bin", + "source_ref": "src/a.c:20", + }, + ], + } + profile_path = os.path.join(self.emulators_dir, "core_a.yml") + with open(profile_path, "w") as f: + yaml.dump(core_a_profile, f) + + # No profile for core_b (unprofiled) + # Clear cache so the new profile is picked up + from model.profiles import emulator_profiles_cache + + emulator_profiles_cache.clear() + profiles = load_emulator_profiles(self.emulators_dir) + self.assertIn("core_a", profiles) + self.assertNotIn("core_b", profiles) + + # Generate truth + truth = generate_platform_truth( + "testplat", config, registry_entry, profiles, db=None, data_registry={} + ) + + # Verify truth structure + self.assertIn("test-system", truth["systems"]) + sys_files = truth["systems"]["test-system"]["files"] + self.assertEqual(len(sys_files), 2) + file_names = {f["name"] for f in sys_files} + self.assertEqual(file_names, {"bios_a.bin", "shared.bin"}) + + # Verify coverage metadata + cov = truth["_coverage"] + self.assertEqual(cov["cores_profiled"], 1) + # core_b has no profile YAML, so resolve_platform_cores never + # includes it, so cores_resolved reflects only matched profiles + self.assertEqual(cov["cores_resolved"], 1) + + # Inject unprofiled info into system-level coverage for diff. + # In production, core_b would be tracked as unprofiled by a + # higher-level orchestrator that knows the declared core list. + injected_cov = { + "cores_profiled": ["core_a"], + "cores_unprofiled": ["core_b"], + } + for sys_data in truth["systems"].values(): + sys_data["_coverage"] = injected_cov + + # Build scraped dict: shared.bin with wrong hash, phantom.bin extra, + # bios_a.bin missing + scraped = { + "systems": { + "test-system": { + "files": [ + { + "name": "shared.bin", + "required": True, + "md5": "d" * 32, + }, + { + "name": "phantom.bin", + "required": False, + "md5": "e" * 32, + }, + ], + }, + }, + } + + # Diff + result = diff_platform_truth(truth, scraped) + summary = result["summary"] + + # bios_a.bin not in scraped -> missing + self.assertEqual(summary["total_missing"], 1) + # shared.bin md5 mismatch (truth "c"*32 vs scraped "d"*32) + self.assertEqual(summary["total_hash_mismatch"], 1) + # phantom.bin extra, core_b unprofiled -> extra_unprofiled + self.assertEqual(summary["total_extra_unprofiled"], 1) + # Unprofiled cores present, so extras are unprofiled not phantom + self.assertEqual(summary["total_extra_phantom"], 0) + + # Verify divergence details + div = result["divergences"]["test-system"] + self.assertEqual(div["missing"][0]["name"], "bios_a.bin") + self.assertEqual(div["hash_mismatch"][0]["name"], "shared.bin") + self.assertEqual(div["extra_unprofiled"][0]["name"], "phantom.bin") + self.assertNotIn("extra_phantom", div) + + def test_173_cross_ref_hash_matching(self): + """Platform file under different name matched by MD5 is not undeclared.""" + config = load_platform_config("test_md5", self.platforms_dir) + profiles = load_emulator_profiles(self.emulators_dir) + undeclared = find_undeclared_files( + config, self.emulators_dir, self.db, profiles + ) + names = {u["name"] for u in undeclared} + # correct_hash.bin is declared by platform as renamed_file.bin with same MD5 + # hash-based matching should suppress it from undeclared + self.assertNotIn("correct_hash.bin", names) + + def test_174_expand_platform_declared_names(self): + """expand_platform_declared_names enriches with DB canonical names.""" + config = load_platform_config("test_md5", self.platforms_dir) + result = expand_platform_declared_names(config, self.db) + # renamed_file.bin is declared directly + self.assertIn("renamed_file.bin", result) + # correct_hash.bin is the DB canonical name for the same MD5 + self.assertIn("correct_hash.bin", result) + + +class TestE2ERegistryMerge(E2EFixture): + """Registry merge, all_libretro expansion, agnostic profiles and exporter round trips.""" + + # --------------------------------------------------------------- + # Registry merge + all_libretro expansion + diff hash fallback + # --------------------------------------------------------------- + + def test_175_registry_merge_cores(self): + """load_platform_config merges cores from _registry.yml.""" + from model.platforms import _platform_config_cache + + # Platform YAML with 1 core + config = { + "platform": "TestMerge", + "cores": ["core_a"], + "systems": {"test-system": {"files": []}}, + } + with open(os.path.join(self.platforms_dir, "testmerge.yml"), "w") as f: + yaml.dump(config, f) + + # Registry with 2 cores (superset) + registry = { + "platforms": { + "testmerge": { + "config": "testmerge.yml", + "cores": ["core_a", "core_b"], + } + } + } + with open(os.path.join(self.platforms_dir, "_registry.yml"), "w") as f: + yaml.dump(registry, f) + + _platform_config_cache.clear() + loaded = load_platform_config("testmerge", self.platforms_dir) + cores = [str(c) for c in loaded["cores"]] + self.assertIn("core_a", cores) + self.assertIn("core_b", cores) + + def test_176_all_libretro_in_list(self): + """resolve_platform_cores expands all_libretro/retroarch in a list.""" + from model.profiles import load_emulator_profiles + from resolve.cores import resolve_platform_cores + + # Create a libretro profile and a standalone profile + for name, ptype in [("lr_core", "libretro"), ("sa_core", "standalone")]: + profile = { + "emulator": name, + "type": ptype, + "cores": [name], + "systems": ["test-system"], + "files": [], + } + with open(os.path.join(self.emulators_dir, f"{name}.yml"), "w") as f: + yaml.dump(profile, f) + + profiles = load_emulator_profiles(self.emulators_dir) + + # Config with retroarch + sa_core in cores list + config = {"cores": ["retroarch", "sa_core"]} + resolved = resolve_platform_cores(config, profiles) + self.assertIn("lr_core", resolved) # expanded via retroarch + self.assertIn("sa_core", resolved) # explicit + + def test_177_diff_hash_fallback_rename(self): + """Diff detects platform renames via hash fallback.""" + from resolve.platformdiff import diff_platform_truth + + truth = { + "systems": { + "test-system": { + "_coverage": {"cores_profiled": ["c"], "cores_unprofiled": []}, + "files": [ + { + "name": "ROM", + "required": True, + "md5": "abcd1234" * 4, + "_cores": ["c"], + "_source_refs": [], + }, + ], + } + } + } + scraped = { + "systems": { + "test-system": { + "files": [ + {"name": "ROM1", "required": True, "md5": "abcd1234" * 4}, + ], + } + } + } + + result = diff_platform_truth(truth, scraped) + # ROM and ROM1 share the same hash: a rename, not missing plus phantom + self.assertEqual(result["summary"]["total_missing"], 0) + self.assertEqual(result["summary"]["total_extra_phantom"], 0) + + def test_178_diff_system_normalization(self): + """Diff matches systems with different IDs via normalization.""" + from resolve.platformdiff import diff_platform_truth + + truth = { + "systems": { + "sega-gamegear": { + "_coverage": {"cores_profiled": ["c"], "cores_unprofiled": []}, + "files": [ + { + "name": "bios.gg", + "required": True, + "md5": "a" * 32, + "_cores": ["c"], + "_source_refs": [], + }, + ], + }, + } + } + scraped = { + "systems": { + "sega-game-gear": { + "files": [ + {"name": "bios.gg", "required": True, "md5": "a" * 32}, + ], + }, + } + } + + result = diff_platform_truth(truth, scraped) + self.assertEqual(result["summary"]["systems_uncovered"], 0) + self.assertEqual(result["summary"]["total_missing"], 0) + self.assertEqual(result["summary"]["systems_compared"], 1) + + def test_179_agnostic_profile_skipped_in_undeclared(self): + """bios_mode: agnostic profiles are skipped entirely by find_undeclared_files.""" + config = load_platform_config("test_existence", self.platforms_dir) + profiles = load_emulator_profiles(self.emulators_dir) + undeclared = find_undeclared_files( + config, self.emulators_dir, self.db, profiles + ) + emulators = {u["emulator"] for u in undeclared} + # TestAgnostic should NOT appear in undeclared (bios_mode: agnostic) + self.assertNotIn("TestAgnostic", emulators) + + def test_180_agnostic_file_skipped_in_undeclared(self): + """Files with agnostic: true are skipped, others in same profile are not.""" + config = load_platform_config("test_existence", self.platforms_dir) + profiles = load_emulator_profiles(self.emulators_dir) + undeclared = find_undeclared_files( + config, self.emulators_dir, self.db, profiles + ) + names = {u["name"] for u in undeclared} + # agnostic_file.bin should NOT be in undeclared (agnostic: true) + self.assertNotIn("agnostic_file.bin", names) + # undeclared_req.bin should still be in undeclared (not agnostic) + self.assertIn("undeclared_req.bin", names) + + def test_181_agnostic_extras_scan(self): + """Agnostic profiles add all matching DB files as extras.""" + from packs.extras import collect_emulator_extras + + config = load_platform_config("test_existence", self.platforms_dir) + profiles = load_emulator_profiles(self.emulators_dir) + extras = collect_emulator_extras( + config, + self.emulators_dir, + self.db, + set(), + "system", + profiles, + ) + agnostic_extras = [ + e for e in extras if e.get("source_emulator") == "TestAgnostic" + ] + # Agnostic scan should find files in the same directory as correct_hash.bin + self.assertTrue(len(agnostic_extras) > 0, "Agnostic scan should produce extras") + # All agnostic extras should have agnostic_scan flag + for e in agnostic_extras: + self.assertTrue(e.get("agnostic_scan", False)) + + def test_182_agnostic_rename_readme(self): + """build_agnostic_rename_readme generates correct text.""" + from packs.readme import build_agnostic_rename_readme + + result = build_agnostic_rename_readme( + "dsi_nand.bin", + "DSi_Nand_AUS.bin", + ["DSi_Nand_EUR.bin", "DSi_Nand_USA.bin"], + ) + self.assertIn("dsi_nand.bin <- DSi_Nand_AUS.bin", result) + self.assertIn("DSi_Nand_EUR.bin", result) + self.assertIn("DSi_Nand_USA.bin", result) + self.assertIn("rename it to: dsi_nand.bin", result) + + def test_183_agnostic_resolve_fallback(self): + """resolve_local_file with agnostic fallback finds a system file.""" + file_entry = { + "name": "nonexistent_agnostic.bin", + "agnostic": True, + "min_size": 1, + "max_size": 999999, + "agnostic_path_prefix": self.bios_dir + "/", + } + path, status = resolve_local_file(file_entry, self.db) + self.assertIsNotNone(path) + self.assertEqual(status, "agnostic_fallback") + + def test_179_batocera_exporter_round_trip(self): + """Batocera exporter produces valid Python dict format.""" + from exporter.batocera_exporter import Exporter + + truth = { + "systems": { + "sony-playstation": { + "_coverage": {"cores_profiled": ["c"]}, + "files": [ + { + "name": "scph5501.bin", + "destination": "scph5501.bin", + "required": True, + "md5": "b" * 32, + "_cores": ["c"], + "_source_refs": [], + }, + ], + } + } + } + scraped = { + # The core the platform runs: an addition is written under it. + "cores": ["c"], + "systems": { + "sony-playstation": {"native_id": "psx", "files": []}, + }, + } + from resolve.reconcile import build_native_model + + # The systems dict is one block inside the checker Batocera runs, so + # the exporter is handed the script it patches. + skeleton = ( + "#!/usr/bin/env python\n" + "systems = {\n" + "}\n" + "def checkBios(systems, prefix, filterROMs):\n" + " return {}\n" + ) + systems, report = build_native_model(truth, scraped) + exp = Exporter() + produced = exp.render( + systems, report, {"batocera-systems": skeleton}, scraped + ) + content = produced["batocera-systems"] + self.assertIn('"psx"', content) + self.assertIn("scph5501.bin", content) + self.assertIn("b" * 32, content) + self.assertIn("def checkBios(", content) + self.assertEqual(exp.validate(systems, produced), []) + + def test_180_recalbox_exporter_round_trip(self): + """Recalbox exporter produces valid es_bios.xml.""" + from exporter.recalbox_exporter import Exporter + + truth = { + "systems": { + "sony-playstation": { + "_coverage": {"cores_profiled": ["c"]}, + "files": [ + { + "name": "scph5501.bin", + "destination": "scph5501.bin", + "required": True, + "md5": "b" * 32, + "_cores": ["c"], + "_source_refs": [], + }, + ], + } + } + } + scraped = { + # The core the platform runs: an addition is written under it. + "cores": ["c"], + "systems": { + "sony-playstation": {"native_id": "psx", "files": []}, + }, + } + from resolve.reconcile import build_native_model + + systems, report = build_native_model(truth, scraped) + exp = Exporter() + produced = exp.render(systems, report, {}, scraped) + content = produced["es_bios.xml"] + self.assertIn("UNTESTED + for d in result["details"]: + if d["name"] == "present_opt.bin": + self.assertEqual(d["status"], Status.UNTESTED) + self.assertIn("size mismatch", d.get("reason", "")) + break + else: + self.fail("present_opt.bin not found in details") + + def test_96_verify_emulator_multi(self): + """Multi-emulator verify aggregates files.""" + result = verify_emulator( + ["test_emu", "test_hle"], + self.emulators_dir, + self.db, + ) + self.assertEqual(len(result["emulators"]), 2) + all_names = {d["name"] for d in result["details"]} + # Files from both profiles + self.assertIn("present_req.bin", all_names) + self.assertIn("hle_missing.bin", all_names) + + def test_97_verify_emulator_data_dir_notice(self): + """Emulator with data_directories reports notice.""" + result = verify_emulator(["test_emu"], self.emulators_dir, self.db) + self.assertIn("test-data-dir", result.get("data_dir_notices", [])) + + def test_97b_a_data_directory_follows_its_build_mode(self): + """A tree only the standalone build reads is no concern of the core.""" + profile = { + "emulator": "ModeDirs", + "type": "standalone + libretro", + "cores": ["mode_dirs"], + "systems": ["console-a"], + "data_directories": [ + {"ref": "standalone-only-dir", "mode": "standalone"}, + {"ref": "shared-dir"}, + ], + "files": [{"name": "present_req.bin", "required": True}], + } + with open(os.path.join(self.emulators_dir, "mode_dirs.yml"), "w") as fh: + yaml.dump(profile, fh) + as_core = verify_emulator(["mode_dirs"], self.emulators_dir, self.db) + self.assertEqual(as_core.get("data_dir_notices", []), ["shared-dir"]) + alone = verify_emulator( + ["mode_dirs"], self.emulators_dir, self.db, standalone=True + ) + self.assertEqual( + sorted(alone.get("data_dir_notices", [])), + ["shared-dir", "standalone-only-dir"], + ) + + def test_97c_one_held_release_fills_a_slot_several_are_accepted_for(self): + """Entries of one profile on one destination are alternatives. + + A profile lists each release the code accepts under a name (the + shareware and the retail archive, told apart by size). Holding one + is the slot filled: the releases not held are not gaps and must not + drag the destination down to the worst status among them. + """ + present = os.path.join(self.bios_dir, "present_req.bin") + size = os.path.getsize(present) + profile = { + "emulator": "Releases", + "type": "standalone", + "cores": ["releases"], + "systems": ["console-a"], + "files": [ + {"name": "present_req.bin", "path": "game/present_req.bin", + "required": False, "size": size + 7, "validation": ["size"], + "description": "retail"}, + {"name": "present_req.bin", "path": "game/present_req.bin", + "required": False, "size": size, "validation": ["size"], + "description": "shareware"}, + {"name": "absent_everywhere.bin", "path": "game/absent.bin", + "required": False}, + ], + } + with open(os.path.join(self.emulators_dir, "releases.yml"), "w") as fh: + yaml.dump(profile, fh) + result = verify_emulator( + ["releases"], self.emulators_dir, self.db, standalone=True + ) + statuses = {d["name"]: d["status"] for d in result["details"]} + self.assertEqual(statuses["present_req.bin"], "ok") + self.assertEqual(statuses["absent_everywhere.bin"], "missing") + self.assertEqual( + sum(1 for d in result["details"] if d["name"] == "present_req.bin"), 1 + ) + self.assertEqual(result["total_files"], 2) + + def test_98_verify_emulator_validation_label(self): + """Validation label reflects the checks used.""" + result = verify_emulator(["test_validation"], self.emulators_dir, self.db) + # test_validation has crc32, md5, sha1, size ->all listed + self.assertEqual(result["verification_mode"], "crc32+md5+sha1+signature+size") + + def test_99filter_files_by_mode(self): + """filter_files_by_mode correctly filters standalone/libretro.""" + files = [ + {"name": "a.bin"}, # no mode ->both + {"name": "b.bin", "mode": "libretro"}, # libretro only + {"name": "c.bin", "mode": "standalone"}, # standalone only + {"name": "d.bin", "mode": "both"}, # explicit both + ] + lr = filter_files_by_mode(files, standalone=False) + sa = filter_files_by_mode(files, standalone=True) + lr_names = {f["name"] for f in lr} + sa_names = {f["name"] for f in sa} + self.assertEqual(lr_names, {"a.bin", "b.bin", "d.bin"}) + self.assertEqual(sa_names, {"a.bin", "c.bin", "d.bin"}) + + def test_100_verify_emulator_empty_profile(self): + """Profile with files:[] produces note, not error.""" + empty = { + "emulator": "TestEmpty", + "type": "libretro", + "systems": ["console-a"], + "files": [], + "exclusion_note": "Code never loads BIOS", + } + with open(os.path.join(self.emulators_dir, "test_empty.yml"), "w") as fh: + yaml.dump(empty, fh) + result = verify_emulator(["test_empty"], self.emulators_dir, self.db) + # Should have a note entry, not crash + self.assertEqual(result["total_files"], 0) + notes = [d for d in result["details"] if d.get("note")] + self.assertTrue(len(notes) > 0) + + def test_101_verify_emulator_severity_missing_required(self): + """Missing required file in emulator mode ->WARNING severity.""" + result = verify_emulator(["test_emu"], self.emulators_dir, self.db) + # undeclared_req.bin is required and missing + for d in result["details"]: + if d["name"] == "undeclared_req.bin": + self.assertEqual(d["status"], Status.MISSING) + self.assertTrue(d["required"]) + break + else: + self.fail("undeclared_req.bin not found") + # Severity should be WARNING (existence mode base) + self.assertGreater(result["severity_counts"][Severity.WARNING], 0) + + def test_102_safe_extract_zip_blocks_traversal(self): + """safe_extract_zip must reject zip-slip path traversal.""" + malicious_zip = os.path.join(self.root, "evil.zip") + with zipfile.ZipFile(malicious_zip, "w") as zf: + zf.writestr("../../etc/passwd", "root:x:0:0") + dest = os.path.join(self.root, "extract_dest") + os.makedirs(dest) + with self.assertRaises(ValueError): + safe_extract_zip(malicious_zip, dest) + + def test_103_safe_extract_zip_normal(self): + """safe_extract_zip extracts valid files correctly.""" + normal_zip = os.path.join(self.root, "normal.zip") + with zipfile.ZipFile(normal_zip, "w") as zf: + zf.writestr("subdir/file.txt", "hello") + dest = os.path.join(self.root, "extract_normal") + os.makedirs(dest) + safe_extract_zip(normal_zip, dest) + extracted = os.path.join(dest, "subdir", "file.txt") + self.assertTrue(os.path.exists(extracted)) + with open(extracted) as f: + self.assertEqual(f.read(), "hello") + + def test_104_compute_hashes_correctness(self): + """compute_hashes returns correct values for known content.""" + test_file = os.path.join(self.root, "hash_test.bin") + data = b"retrobios test content" + with open(test_file, "wb") as f: + f.write(data) + import zlib + + expected_sha1 = hashlib.sha1(data).hexdigest() + expected_md5 = hashlib.md5(data).hexdigest() + expected_sha256 = hashlib.sha256(data).hexdigest() + expected_crc32 = format(zlib.crc32(data) & 0xFFFFFFFF, "08x") + + result = compute_hashes(test_file) + self.assertEqual(result["sha1"], expected_sha1) + self.assertEqual(result["md5"], expected_md5) + self.assertEqual(result["sha256"], expected_sha256) + self.assertEqual(result["crc32"], expected_crc32) + + def test_105_resolve_with_empty_database(self): + """resolve_local_file handles empty database gracefully.""" + empty_db = { + "files": {}, + "indexes": {"by_md5": {}, "by_name": {}, "by_path_suffix": {}}, + } + entry = {"name": "nonexistent.bin", "sha1": "abc123"} + path, status = resolve_local_file(entry, empty_db) + self.assertIsNone(path) + self.assertEqual(status, "not_found") + + def test_106_parse_hash_list(self): + """parse_hash_list normalizes comma-separated MD5s.""" + self.assertEqual(parse_hash_list(""), []) + self.assertEqual(parse_hash_list("ABC123"), ["abc123"]) + self.assertEqual(parse_hash_list("abc, DEF , ghi"), ["abc", "def", "ghi"]) + self.assertEqual(parse_hash_list(",,,"), []) + + def test_107filter_files_by_mode(self): + """filter_files_by_mode filters standalone/libretro correctly.""" + files = [ + {"name": "a.bin", "mode": "standalone"}, + {"name": "b.bin", "mode": "libretro"}, + {"name": "c.bin", "mode": "both"}, + {"name": "d.bin"}, # no mode + ] + # Libretro mode: exclude standalone + result = filter_files_by_mode(files, standalone=False) + names = [f["name"] for f in result] + self.assertNotIn("a.bin", names) + self.assertIn("b.bin", names) + self.assertIn("c.bin", names) + self.assertIn("d.bin", names) + + # Standalone mode: exclude libretro + result = filter_files_by_mode(files, standalone=True) + names = [f["name"] for f in result] + self.assertIn("a.bin", names) + self.assertNotIn("b.bin", names) + self.assertIn("c.bin", names) + self.assertIn("d.bin", names) + + def test_108_standalone_path_in_undeclared(self): + """Undeclared files use standalone_path when core is in standalone_cores.""" + # Create a platform with standalone_cores + config = { + "platform": "TestStandalone", + "verification_mode": "existence", + "cores": ["test_sa"], + "standalone_cores": ["test_sa"], + "systems": { + "console-a": { + "files": [ + { + "name": "present_req.bin", + "destination": "present_req.bin", + "required": True, + }, + ], + }, + }, + } + with open(os.path.join(self.platforms_dir, "test_standalone.yml"), "w") as fh: + yaml.dump(config, fh) + + # Create emulator with standalone_path divergence + emu = { + "emulator": "TestStandaloneEmu", + "type": "standalone + libretro", + "cores": ["test_sa"], + "systems": ["console-a"], + "files": [ + { + "name": "libretro_file.bin", + "path": "subdir/libretro_file.bin", + "standalone_path": "flat_file.bin", + "required": True, + }, + { + "name": "standalone_only.bin", + "mode": "standalone", + "required": False, + }, + {"name": "libretro_only.bin", "mode": "libretro", "required": False}, + ], + } + with open( + os.path.join(self.emulators_dir, "test_standalone_emu.yml"), "w" + ) as fh: + yaml.dump(emu, fh) + + config = load_platform_config("test_standalone", self.platforms_dir) + profiles = load_emulator_profiles(self.emulators_dir) + undeclared = find_undeclared_files( + config, self.emulators_dir, self.db, profiles + ) + by_name = {u["name"]: u for u in undeclared} + + # standalone_path used for undeclared file (core is standalone) + self.assertIn("libretro_file.bin", by_name) + self.assertEqual(by_name["libretro_file.bin"]["path"], "flat_file.bin") + + # standalone-only file IS included (core is standalone) + self.assertIn("standalone_only.bin", by_name) + + # libretro-only file is EXCLUDED (core is standalone) + self.assertNotIn("libretro_only.bin", by_name) + + def test_109_no_standalone_cores_uses_libretro_path(self): + """Without standalone_cores, undeclared files use path: (libretro).""" + config = load_platform_config("test_existence", self.platforms_dir) + profiles = load_emulator_profiles(self.emulators_dir) + undeclared = find_undeclared_files( + config, self.emulators_dir, self.db, profiles + ) + # standalone_only.bin should be excluded (platform has no standalone_cores) + names = {u["name"] for u in undeclared} + self.assertNotIn("standalone_only.bin", names) + + def test_110_cores_alias_reverse_index(self): + """resolve_platform_cores matches via cores: field aliases.""" + emu = { + "emulator": "TestAliasCore", + "type": "libretro", + "cores": ["test_alias_core", "shortname"], + "systems": ["console-a"], + "files": [], + } + with open(os.path.join(self.emulators_dir, "test_alias_core.yml"), "w") as fh: + yaml.dump(emu, fh) + + config = {"cores": ["shortname"]} + profiles = load_emulator_profiles(self.emulators_dir) + resolved = resolve_platform_cores(config, profiles) + self.assertIn("test_alias_core", resolved) + + +class TestE2ETargets(E2EFixture): + """Hardware target configuration and the core filtering it drives.""" + + # --------------------------------------------------------------- + # Target config tests (Task 1) + # --------------------------------------------------------------- + + def _write_target_fixtures(self): + """Create target config fixtures for testing.""" + targets_dir = os.path.join(self.platforms_dir, "targets") + os.makedirs(targets_dir, exist_ok=True) + target_config = { + "platform": "testplatform", + "source": "test", + "scraped_at": "2026-01-01T00:00:00Z", + "targets": { + "target-full": { + "architecture": "x86_64", + "cores": ["core_a", "core_b", "core_c"], + }, + "target-minimal": { + "architecture": "armv7", + "cores": ["core_a"], + }, + }, + } + with open(os.path.join(targets_dir, "testplatform.yml"), "w") as f: + yaml.dump(target_config, f) + single_config = { + "platform": "singleplatform", + "source": "test", + "scraped_at": "2026-01-01T00:00:00Z", + "targets": { + "only-target": { + "architecture": "x86_64", + "cores": ["core_a", "core_b"], + }, + }, + } + with open(os.path.join(targets_dir, "singleplatform.yml"), "w") as f: + yaml.dump(single_config, f) + overrides = { + "testplatform": { + "targets": { + "target-full": { + "aliases": ["full", "pc", "desktop"], + "add_cores": ["core_d"], + "remove_cores": ["core_c"], + }, + "target-minimal": { + "aliases": ["minimal", "arm"], + }, + }, + }, + } + with open(os.path.join(targets_dir, "_overrides.yml"), "w") as f: + yaml.dump(overrides, f) + + def test_load_target_config(self): + self._write_target_fixtures() + from model.targets import load_target_config + + cores = load_target_config("testplatform", "target-minimal", self.platforms_dir) + self.assertEqual(cores, {"core_a"}) + + def test_target_alias_resolution(self): + self._write_target_fixtures() + from model.targets import load_target_config + + cores = load_target_config("testplatform", "full", self.platforms_dir) + self.assertEqual(cores, {"core_a", "core_b", "core_d"}) + + def test_target_unknown_error(self): + self._write_target_fixtures() + from model.targets import load_target_config + + with self.assertRaises(ValueError) as ctx: + load_target_config("testplatform", "nonexistent", self.platforms_dir) + self.assertIn("target-full", str(ctx.exception)) + self.assertIn("target-minimal", str(ctx.exception)) + + def test_target_override_add_remove(self): + self._write_target_fixtures() + from model.targets import load_target_config + + cores = load_target_config("testplatform", "full", self.platforms_dir) + self.assertIn("core_d", cores) + self.assertNotIn("core_c", cores) + self.assertIn("core_a", cores) + self.assertIn("core_b", cores) + + def test_target_default_override_reaches_every_target(self): + """`_default` drops a name on every target, then the target adds its own.""" + self._write_target_fixtures() + from model.targets import load_target_config + + targets_dir = os.path.join(self.platforms_dir, "targets") + overrides = { + "testplatform": { + "targets": { + "_default": {"remove_cores": ["core_a"], "add_cores": ["core_z"]}, + "target-full": {"aliases": ["full"], "add_cores": ["core_a"]}, + }, + }, + } + with open(os.path.join(targets_dir, "_overrides.yml"), "w") as f: + yaml.dump(overrides, f) + self.assertEqual( + load_target_config("testplatform", "target-minimal", self.platforms_dir), + {"core_z"}, + ) + self.assertEqual( + load_target_config("testplatform", "full", self.platforms_dir), + {"core_a", "core_b", "core_c", "core_z"}, + ) + with self.assertRaises(ValueError): + load_target_config("testplatform", "_default", self.platforms_dir) + + def test_target_single_target_noop(self): + self._write_target_fixtures() + from model.targets import load_target_config + + cores = load_target_config("singleplatform", "only-target", self.platforms_dir) + self.assertEqual(cores, {"core_a", "core_b"}) + + def test_target_inherits(self): + self._write_target_fixtures() + targets_dir = os.path.join(self.platforms_dir, "targets") + child_config = { + "platform": "childplatform", + "source": "test", + "scraped_at": "2026-01-01T00:00:00Z", + "targets": { + "target-full": { + "architecture": "x86_64", + "cores": ["core_a"], + }, + }, + } + with open(os.path.join(targets_dir, "childplatform.yml"), "w") as f: + yaml.dump(child_config, f) + from model.targets import load_target_config + + parent = load_target_config( + "testplatform", "target-minimal", self.platforms_dir + ) + child = load_target_config("childplatform", "target-full", self.platforms_dir) + self.assertEqual(parent, {"core_a"}) + self.assertEqual(child, {"core_a"}) + self.assertNotEqual( + load_target_config("testplatform", "full", self.platforms_dir), + child, + ) + + # --------------------------------------------------------------- + # Target filtering in resolve_platform_cores (Task 2) + # --------------------------------------------------------------- + + def test_target_core_intersection(self): + self._write_target_fixtures() + profiles = { + "core_a": {"type": "libretro", "systems": ["sys1"]}, + "core_b": {"type": "libretro", "systems": ["sys1"]}, + "core_c": {"type": "libretro", "systems": ["sys2"]}, + "core_d": {"type": "libretro", "systems": ["sys2"]}, + } + config = {"cores": "all_libretro"} + result = resolve_platform_cores(config, profiles) + self.assertEqual(result, {"core_a", "core_b", "core_c", "core_d"}) + result = resolve_platform_cores( + config, profiles, target_cores={"core_a", "core_b"} + ) + self.assertEqual(result, {"core_a", "core_b"}) + + def test_target_none_no_filter(self): + profiles = { + "core_a": {"type": "libretro", "systems": ["sys1"]}, + "core_b": {"type": "libretro", "systems": ["sys1"]}, + } + config = {"cores": "all_libretro"} + result = resolve_platform_cores(config, profiles, target_cores=None) + self.assertEqual(result, {"core_a", "core_b"}) + + def test_verify_target_filtered(self): + """Verify with target_cores only reports files from filtered cores.""" + self._write_target_fixtures() + core_a_path = os.path.join(self.emulators_dir, "core_a.yml") + core_b_path = os.path.join(self.emulators_dir, "core_b.yml") + with open(core_a_path, "w") as f: + yaml.dump( + { + "emulator": "CoreA", + "type": "libretro", + "systems": ["sys1"], + "files": [{"name": "bios_a.bin", "required": True}], + }, + f, + ) + with open(core_b_path, "w") as f: + yaml.dump( + { + "emulator": "CoreB", + "type": "libretro", + "systems": ["sys1"], + "files": [{"name": "bios_b.bin", "required": True}], + }, + f, + ) + + config = {"cores": "all_libretro", "systems": {"sys1": {"files": []}}} + profiles = load_emulator_profiles(self.emulators_dir) + + # Without target: both cores' files are undeclared + undeclared = find_undeclared_files( + config, self.emulators_dir, self.db, profiles + ) + names = {u["name"] for u in undeclared} + self.assertIn("bios_a.bin", names) + self.assertIn("bios_b.bin", names) + + # With target filtering to core_a only + undeclared = find_undeclared_files( + config, + self.emulators_dir, + self.db, + profiles, + target_cores={"core_a"}, + ) + names = {u["name"] for u in undeclared} + self.assertIn("bios_a.bin", names) + self.assertNotIn("bios_b.bin", names) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_e2e_pack_options.py b/tests/test_e2e_pack_options.py new file mode 100644 index 000000000..0d06f94d0 --- /dev/null +++ b/tests/test_e2e_pack_options.py @@ -0,0 +1,1030 @@ +"""End-to-end ground truth reporting and pack narrowing options.""" + +from __future__ import annotations + +import tests +from tests.sources import script_source +import contextlib +import io +import os +import sys +import tempfile +import unittest +import zipfile +from pathlib import Path +import yaml +from model.profiles import load_emulator_profiles +from model.platforms import load_platform_config +from resolve.validation import build_validation_index +from packs.verdicts import Status +from packs.gaps import find_undeclared_files +from packs.emulatorcheck import verify_emulator +from packs.coverage import verify_platform +from tests.e2esupport import E2EFixture + + +class TestE2EGroundTruth(E2EFixture): + """Per-emulator ground truth in the validation index and the reports.""" + + # --------------------------------------------------------------- + # Validation index per-emulator ground truth (Task: ground truth) + # --------------------------------------------------------------- + + def test_111_validation_index_per_emulator(self): + """Validation index includes per-emulator detail for ground truth.""" + profiles = load_emulator_profiles(self.emulators_dir) + index = build_validation_index(profiles) + entry = index["present_req.bin"] + self.assertIn("per_emulator", entry) + pe = entry["per_emulator"] + self.assertIn("test_validation", pe) + detail = pe["test_validation"] + self.assertIn("size", detail["checks"]) + self.assertEqual(detail["expected"]["size"], 16) + + def test_112_build_ground_truth(self): + """build_ground_truth returns per-emulator detail for a filename.""" + from resolve.validation import build_ground_truth + + profiles = load_emulator_profiles(self.emulators_dir) + index = build_validation_index(profiles) + gt = build_ground_truth("present_req.bin", index) + self.assertIsInstance(gt, list) + self.assertTrue(len(gt) >= 1) + emu_names = {g["emulator"] for g in gt} + self.assertIn("test_validation", emu_names) + for g in gt: + if g["emulator"] == "test_validation": + self.assertIn("size", g["checks"]) + self.assertIn("source_ref", g) + self.assertIn("expected", g) + + def test_113_build_ground_truth_empty(self): + """build_ground_truth returns [] for unknown filename.""" + from resolve.validation import build_ground_truth + + profiles = load_emulator_profiles(self.emulators_dir) + index = build_validation_index(profiles) + gt = build_ground_truth("nonexistent.bin", index) + self.assertEqual(gt, []) + + def test_114_platform_result_has_ground_truth(self): + """verify_platform attaches ground_truth to each detail entry.""" + config = load_platform_config("test_existence", self.platforms_dir) + profiles = load_emulator_profiles(self.emulators_dir) + result = verify_platform(config, self.db, self.emulators_dir, profiles) + for d in result["details"]: + self.assertIn("ground_truth", d) + # present_req.bin has validation in test_validation profile + for d in result["details"]: + if d["name"] == "present_req.bin": + self.assertTrue(len(d["ground_truth"]) >= 1) + emu_names = {g["emulator"] for g in d["ground_truth"]} + self.assertIn("test_validation", emu_names) + break + else: + self.fail("present_req.bin not found in details") + + def test_116_undeclared_files_have_ground_truth(self): + """find_undeclared_files attaches ground truth fields.""" + config = load_platform_config("test_existence", self.platforms_dir) + profiles = load_emulator_profiles(self.emulators_dir) + undeclared = find_undeclared_files( + config, self.emulators_dir, self.db, profiles + ) + for u in undeclared: + self.assertIn("checks", u) + self.assertIn("source_ref", u) + self.assertIn("expected", u) + + def test_117_platform_result_ground_truth_coverage(self): + """verify_platform includes ground truth coverage counts.""" + config = load_platform_config("test_existence", self.platforms_dir) + profiles = load_emulator_profiles(self.emulators_dir) + result = verify_platform(config, self.db, self.emulators_dir, profiles) + gt = result["ground_truth_coverage"] + self.assertIn("with_validation", gt) + self.assertIn("total", gt) + self.assertIn("platform_only", gt) + self.assertEqual(gt["total"], result["total_files"]) + self.assertEqual(gt["platform_only"], gt["total"] - gt["with_validation"]) + self.assertGreaterEqual(gt["with_validation"], 1) + + def test_118_emulator_result_has_ground_truth(self): + """verify_emulator attaches ground_truth to each detail entry.""" + result = verify_emulator(["test_validation"], self.emulators_dir, self.db) + for d in result["details"]: + self.assertIn("ground_truth", d) + # present_req.bin should have ground truth from test_validation + for d in result["details"]: + if d["name"] == "present_req.bin": + self.assertTrue(len(d["ground_truth"]) >= 1) + break + + def test_119_emulator_result_ground_truth_coverage(self): + """verify_emulator includes ground truth coverage counts.""" + result = verify_emulator(["test_validation"], self.emulators_dir, self.db) + gt = result["ground_truth_coverage"] + self.assertEqual(gt["total"], result["total_files"]) + + def test_115_platform_result_ground_truth_empty_for_unknown(self): + """Files with no emulator validation get ground_truth=[].""" + config = load_platform_config("test_existence", self.platforms_dir) + profiles = load_emulator_profiles(self.emulators_dir) + result = verify_platform(config, self.db, self.emulators_dir, profiles) + for d in result["details"]: + if d["name"] == "missing_opt.bin": + self.assertEqual(d["ground_truth"], []) + break + + def test_120_format_ground_truth_aggregate(self): + """Aggregate format: one line with all cores.""" + from packs.report import _format_ground_truth_aggregate + + gt = [ + { + "emulator": "beetle_psx", + "checks": ["md5"], + "source_ref": "libretro.cpp:252", + "expected": {"md5": "abc"}, + }, + { + "emulator": "pcsx_rearmed", + "checks": ["existence"], + "source_ref": None, + "expected": {}, + }, + ] + line = _format_ground_truth_aggregate(gt) + self.assertIn("beetle_psx", line) + self.assertIn("[md5]", line) + self.assertIn("pcsx_rearmed", line) + self.assertIn("[existence]", line) + + def test_121_format_ground_truth_verbose(self): + """Verbose format: one line per core with expected values and source ref.""" + from packs.report import _format_ground_truth_verbose + + gt = [ + { + "emulator": "handy", + "checks": ["size", "crc32"], + "source_ref": "rom.h:48-49", + "expected": {"size": 512, "crc32": "0d973c9d"}, + }, + ] + lines = _format_ground_truth_verbose(gt) + self.assertEqual(len(lines), 1) + self.assertIn("handy", lines[0]) + self.assertIn("size=512", lines[0]) + self.assertIn("crc32=0d973c9d", lines[0]) + self.assertIn("[rom.h:48-49]", lines[0]) + + def test_122_format_ground_truth_verbose_no_source_ref(self): + """Verbose format omits bracket when source_ref is None.""" + from packs.report import _format_ground_truth_verbose + + gt = [ + { + "emulator": "core_a", + "checks": ["existence"], + "source_ref": None, + "expected": {}, + }, + ] + lines = _format_ground_truth_verbose(gt) + self.assertEqual(len(lines), 1) + self.assertNotIn("[", lines[0]) + + def test_123_ground_truth_full_chain_verbose(self): + """Full chain: file -> platform -> emulator -> source_ref visible in ground_truth.""" + config = load_platform_config("test_existence", self.platforms_dir) + profiles = load_emulator_profiles(self.emulators_dir) + result = verify_platform(config, self.db, self.emulators_dir, profiles) + for d in result["details"]: + if d["name"] == "present_req.bin": + gt = d["ground_truth"] + for g in gt: + if g["emulator"] == "test_validation": + self.assertIn("size", g["checks"]) + self.assertEqual(g["source_ref"], "test.c:10-20") + self.assertEqual(g["expected"]["size"], 16) + return + self.fail("present_req.bin / test_validation ground truth not found") + + def test_124_ground_truth_json_includes_all(self): + """JSON output includes ground_truth on all detail entries.""" + config = load_platform_config("test_existence", self.platforms_dir) + profiles = load_emulator_profiles(self.emulators_dir) + result = verify_platform(config, self.db, self.emulators_dir, profiles) + # Simulate --json filtering (non-OK only): ground_truth must survive + filtered = [d for d in result["details"] if d["status"] != Status.OK] + for d in filtered: + self.assertIn("ground_truth", d) + # Also check OK entries have it (before filtering) + ok_entries = [d for d in result["details"] if d["status"] == Status.OK] + for d in ok_entries: + self.assertIn("ground_truth", d) + + def test_125_ground_truth_coverage_in_md5_mode(self): + """MD5 platform also gets ground truth coverage.""" + config = load_platform_config("test_md5", self.platforms_dir) + profiles = load_emulator_profiles(self.emulators_dir) + result = verify_platform(config, self.db, self.emulators_dir, profiles) + gt = result["ground_truth_coverage"] + self.assertEqual(gt["total"], result["total_files"]) + self.assertGreaterEqual(gt["with_validation"], 1) + + +class TestE2EPackOptions(E2EFixture): + """Required-only, system, split and hash-list packs and their refusals.""" + + def test_130_required_only_excludes_optional(self): + """--required-only excludes files with required: false from pack.""" + from packs.platformpack import generate_pack + + output_dir = os.path.join(self.root, "pack_reqonly") + os.makedirs(output_dir, exist_ok=True) + # Create a platform with one required and one optional file + config = { + "platform": "ReqOnlyTest", + "verification_mode": "existence", + "base_destination": "system", + "systems": { + "test-sys": { + "files": [ + { + "name": "present_req.bin", + "destination": "present_req.bin", + "required": True, + }, + { + "name": "present_opt.bin", + "destination": "present_opt.bin", + "required": False, + }, + ], + }, + }, + } + with open(os.path.join(self.platforms_dir, "test_reqonly.yml"), "w") as fh: + yaml.dump(config, fh) + zip_path = generate_pack( + "test_reqonly", + self.platforms_dir, + self.db, + self.bios_dir, + output_dir, + required_only=True, + ) + self.assertIsNotNone(zip_path) + with zipfile.ZipFile(zip_path) as zf: + names = zf.namelist() + self.assertTrue(any("present_req.bin" in n for n in names)) + self.assertFalse(any("present_opt.bin" in n for n in names)) + # Verify _Required tag in filename + self.assertIn("_Required_", os.path.basename(zip_path)) + + def test_130a_consistency_reads_what_the_builder_and_verify_write(self): + """Step 5 compares the records the two tools write, not their wording. + + The builder's counts and verify's go through the files the pipeline + reads, so a reworded line can no longer switch a comparison off. + """ + from orchestrate.consistency import check_consistency + from packs.packcounts import PackCounts, write_pack_counts + from packs.platformpack import build_platform_pack + from packs.verifyoutput import write_pack_destinations + + profiles = load_emulator_profiles(self.emulators_dir) + output_dir = os.path.join(self.root, "counted") + packs: list[tuple[str, list[str], PackCounts]] = [] + groups, group_results = [], [] + for platform in ("test_existence", "test_md5"): + sink: list[PackCounts] = [] + build_platform_pack( + platform, self.platforms_dir, self.db, self.bios_dir, output_dir, + emulators_dir=self.emulators_dir, emu_profiles=profiles, counts=sink, + ) + self.assertEqual(len(sink), 1) + packs.append((platform, [platform], sink[0])) + config = load_platform_config(platform, self.platforms_dir) + result = verify_platform(config, self.db, self.emulators_dir, emu_profiles=profiles) + groups.append(([platform], platform)) + group_results.append((result, [config.get("platform", platform)])) + destinations = os.path.join(self.root, "destinations.json") + counts = os.path.join(self.root, "counts.json") + write_pack_destinations(destinations, groups, group_results) + write_pack_counts(counts, packs) + with contextlib.redirect_stdout(io.StringIO()) as out: + self.assertTrue(check_consistency(destinations, counts), out.getvalue()) + self.assertEqual(out.getvalue().count("== pack"), 2, out.getvalue()) + + skewed = [(label, ids, PackCounts(**{**c.__dict__, "core_files": c.core_files + 1})) + for label, ids, c in packs] + write_pack_counts(counts, skewed) + with contextlib.redirect_stdout(io.StringIO()) as out: + self.assertFalse(check_consistency(destinations, counts)) + self.assertIn("MISMATCH core files", out.getvalue()) + + def test_130b_existence_pack_reports_hash_mismatch(self): + """Existence mode packs a mismatched file but prints the proof.""" + import contextlib + import io + + from packs.platformpack import generate_pack + + output_dir = os.path.join(self.root, "pack_mismatch") + os.makedirs(output_dir, exist_ok=True) + config = { + "platform": "MismatchTest", + "verification_mode": "existence", + "base_destination": "system", + "systems": { + "test-sys": { + "files": [ + { + "name": "wrong_hash.bin", + "destination": "wrong_hash.bin", + "md5": "ffffffffffffffffffffffffffffffff", + "required": True, + }, + ], + }, + }, + } + with open(os.path.join(self.platforms_dir, "test_mismatch.yml"), "w") as fh: + yaml.dump(config, fh) + out = io.StringIO() + with contextlib.redirect_stdout(out): + zip_path = generate_pack( + "test_mismatch", + self.platforms_dir, + self.db, + self.bios_dir, + output_dir, + offline=True, + ) + self.assertIsNotNone(zip_path) + with zipfile.ZipFile(zip_path) as zf: + names = zf.namelist() + self.assertTrue(any("wrong_hash.bin" in n for n in names)) + report = out.getvalue() + self.assertIn("DISCREPANCY", report) + self.assertIn("declared hash ffffffffffffffffffffffffffffffff", report) + + def test_131_required_only_keeps_default_required(self): + """--required-only keeps files with no required field (default = required).""" + from packs.platformpack import generate_pack + + output_dir = os.path.join(self.root, "pack_reqdef") + os.makedirs(output_dir, exist_ok=True) + # File with no required field + config = { + "platform": "ReqDefTest", + "verification_mode": "existence", + "base_destination": "system", + "systems": { + "test-sys": { + "files": [ + {"name": "present_req.bin", "destination": "present_req.bin"}, + ], + }, + }, + } + with open(os.path.join(self.platforms_dir, "test_reqdef.yml"), "w") as fh: + yaml.dump(config, fh) + zip_path = generate_pack( + "test_reqdef", + self.platforms_dir, + self.db, + self.bios_dir, + output_dir, + required_only=True, + ) + self.assertIsNotNone(zip_path) + with zipfile.ZipFile(zip_path) as zf: + names = zf.namelist() + self.assertTrue(any("present_req.bin" in n for n in names)) + + def test_132_platform_system_filter(self): + """--platform + --system filters systems within a platform pack.""" + from packs.platformpack import generate_pack + + output_dir = os.path.join(self.root, "pack_sysfilter") + os.makedirs(output_dir, exist_ok=True) + config = { + "platform": "SysFilterTest", + "verification_mode": "existence", + "base_destination": "system", + "systems": { + "system-a": { + "files": [ + {"name": "present_req.bin", "destination": "present_req.bin"}, + ], + }, + "system-b": { + "files": [ + {"name": "present_opt.bin", "destination": "present_opt.bin"}, + ], + }, + }, + } + with open(os.path.join(self.platforms_dir, "test_sysfilter.yml"), "w") as fh: + yaml.dump(config, fh) + zip_path = generate_pack( + "test_sysfilter", + self.platforms_dir, + self.db, + self.bios_dir, + output_dir, + system_filter=["system-a"], + ) + self.assertIsNotNone(zip_path) + with zipfile.ZipFile(zip_path) as zf: + names = zf.namelist() + self.assertTrue(any("present_req.bin" in n for n in names)) + self.assertFalse(any("present_opt.bin" in n for n in names)) + + def test_133_platform_system_filter_normalized(self): + """norm_system_id normalization matches with manufacturer prefix.""" + from model.systems import norm_system_id + + self.assertEqual( + norm_system_id("sony-playstation"), + norm_system_id("playstation"), + ) + + def test_134_list_systems_platform_context(self): + """list_platform_system_ids lists systems from a platform YAML.""" + import io + + from model.cliargs import list_platform_system_ids + + config = { + "platform": "ListSysTest", + "verification_mode": "existence", + "systems": { + "alpha-sys": { + "files": [ + {"name": "a.bin", "destination": "a.bin"}, + ], + }, + "beta-sys": { + "files": [ + {"name": "b1.bin", "destination": "b1.bin"}, + {"name": "b2.bin", "destination": "b2.bin"}, + ], + }, + }, + } + with open(os.path.join(self.platforms_dir, "test_listsys.yml"), "w") as fh: + yaml.dump(config, fh) + captured = io.StringIO() + old_stdout = sys.stdout + sys.stdout = captured + try: + list_platform_system_ids("test_listsys", self.platforms_dir) + finally: + sys.stdout = old_stdout + output = captured.getvalue() + self.assertIn("alpha-sys", output) + self.assertIn("beta-sys", output) + self.assertIn("1 file", output) + self.assertIn("2 files", output) + + def test_135_split_by_system(self): + """--split generates one ZIP per system in a subdirectory.""" + import tempfile + + with tempfile.TemporaryDirectory() as tmpdir: + plat_dir = os.path.join(tmpdir, "platforms") + os.makedirs(plat_dir) + bios_dir = os.path.join(tmpdir, "bios", "Test") + os.makedirs(os.path.join(bios_dir, "SysA")) + os.makedirs(os.path.join(bios_dir, "SysB")) + emu_dir = os.path.join(tmpdir, "emulators") + os.makedirs(emu_dir) + out_dir = os.path.join(tmpdir, "dist") + + file_a = os.path.join(bios_dir, "SysA", "bios_a.bin") + file_b = os.path.join(bios_dir, "SysB", "bios_b.bin") + with open(file_a, "wb") as f: + f.write(b"system_a") + with open(file_b, "wb") as f: + f.write(b"system_b") + + from core.hashing import compute_hashes + + ha = compute_hashes(file_a) + hb = compute_hashes(file_b) + + db = { + "files": { + ha["sha1"]: { + "name": "bios_a.bin", + "md5": ha["md5"], + "sha1": ha["sha1"], + "sha256": ha["sha256"], + "path": file_a, + "paths": [file_a], + }, + hb["sha1"]: { + "name": "bios_b.bin", + "md5": hb["md5"], + "sha1": hb["sha1"], + "sha256": hb["sha256"], + "path": file_b, + "paths": [file_b], + }, + }, + "indexes": { + "by_md5": {ha["md5"]: ha["sha1"], hb["md5"]: hb["sha1"]}, + "by_name": {"bios_a.bin": [ha["sha1"]], "bios_b.bin": [hb["sha1"]]}, + "by_crc32": {}, + "by_path_suffix": {}, + }, + } + + registry = {"platforms": {"splitplat": {"config": "splitplat.yml"}}} + with open(os.path.join(plat_dir, "_registry.yml"), "w") as f: + yaml.dump(registry, f) + plat_cfg = { + "platform": "SplitTest", + "verification_mode": "existence", + "systems": { + "test-system-a": { + "files": [{"name": "bios_a.bin", "sha1": ha["sha1"]}] + }, + "test-system-b": { + "files": [{"name": "bios_b.bin", "sha1": hb["sha1"]}] + }, + }, + } + with open(os.path.join(plat_dir, "splitplat.yml"), "w") as f: + yaml.dump(plat_cfg, f) + + from core.ziptools import build_zip_contents_index + from model.profiles import load_emulator_profiles + from packs.platformpack import generate_split_packs + + zip_contents = build_zip_contents_index(db, Path(tmpdir)) + emu_profiles = load_emulator_profiles(emu_dir) + + zip_paths = generate_split_packs( + "splitplat", + plat_dir, + db, + os.path.join(tmpdir, "bios"), + out_dir, + emulators_dir=emu_dir, + zip_contents=zip_contents, + emu_profiles=emu_profiles, + group_by="system", + ) + self.assertEqual(len(zip_paths), 2) + + # Check subdirectory exists + split_dir = os.path.join(out_dir, "SplitTest_Split") + self.assertTrue(os.path.isdir(split_dir)) + + # Verify each ZIP contains only its system's files + for zp in zip_paths: + with zipfile.ZipFile(zp) as zf: + names = zf.namelist() + basename = os.path.basename(zp) + if "System_A" in basename: + self.assertIn("bios_a.bin", names) + self.assertNotIn("bios_b.bin", names) + elif "System_B" in basename: + self.assertIn("bios_b.bin", names) + self.assertNotIn("bios_a.bin", names) + + def test_136_derive_manufacturer(self): + """derive_manufacturer extracts manufacturer correctly.""" + from model.systems import derive_manufacturer + + # From system ID prefix + self.assertEqual(derive_manufacturer("sony-playstation", {}), "Sony") + self.assertEqual(derive_manufacturer("nintendo-snes", {}), "Nintendo") + self.assertEqual(derive_manufacturer("sega-saturn", {}), "Sega") + self.assertEqual(derive_manufacturer("atari-5200", {}), "Atari") + # From explicit manufacturer field + self.assertEqual( + derive_manufacturer("3do", {"manufacturer": "Panasonic|GoldStar"}), + "Panasonic", + ) + # Various = skip to prefix check, then Other + self.assertEqual( + derive_manufacturer("arcade", {"manufacturer": "Various"}), "Other" + ) + # Fallback + self.assertEqual(derive_manufacturer("dos", {}), "Other") + + def test_137_group_systems_by_manufacturer(self): + """_group_systems_by_manufacturer groups correctly.""" + from packs.platformpack import _group_systems_by_manufacturer + + systems = { + "sony-playstation": {"files": [{"name": "a.bin"}]}, + "sony-psp": {"files": [{"name": "b.bin"}]}, + "nintendo-snes": {"files": [{"name": "c.bin"}]}, + "arcade": {"manufacturer": "Various", "files": [{"name": "d.bin"}]}, + } + groups = _group_systems_by_manufacturer(systems, {}, "") + self.assertIn("Sony", groups) + self.assertEqual(sorted(groups["Sony"]), ["sony-playstation", "sony-psp"]) + self.assertIn("Nintendo", groups) + self.assertEqual(groups["Nintendo"], ["nintendo-snes"]) + self.assertIn("Other", groups) + self.assertEqual(groups["Other"], ["arcade"]) + + def test_138_parse_hash_input(self): + """parse_hash_input handles various formats.""" + from packs.hashinput import parse_hash_input + + # Plain MD5 + result = parse_hash_input("d8f1206299c48946e6ec5ef96d014eaa") + self.assertEqual(result, [("md5", "d8f1206299c48946e6ec5ef96d014eaa")]) + # Comma-separated + result = parse_hash_input( + "d8f1206299c48946e6ec5ef96d014eaa,d8f1206299c48946e6ec5ef96d014eab" + ) + self.assertEqual(len(result), 2) + # SHA1 + sha1 = "a" * 40 + result = parse_hash_input(sha1) + self.assertEqual(result, [("sha1", sha1)]) + # CRC32 + result = parse_hash_input("abcd1234") + self.assertEqual(result, [("crc32", "abcd1234")]) + + def test_139_parse_hash_file(self): + """parse_hash_file handles comments, empty lines, various formats.""" + from packs.hashinput import parse_hash_file + + with tempfile.NamedTemporaryFile(mode="w", suffix=".txt", delete=False) as f: + f.write("# PS1 BIOS files\n") + f.write("\n") + f.write("d8f1206299c48946e6ec5ef96d014eaa\n") + f.write("d8f1206299c48946e6ec5ef96d014eab scph5501.bin\n") + f.write("scph5502.bin d8f1206299c48946e6ec5ef96d014eac OK\n") + tmp_path = f.name + try: + result = parse_hash_file(tmp_path) + self.assertEqual(len(result), 3) + self.assertTrue(all(t == "md5" for t, _ in result)) + finally: + os.unlink(tmp_path) + + def test_140_lookup_hashes_found(self): + """lookup_hashes returns the record of a known hash.""" + from resolve.packfiles import HashLookup, lookup_hashes + + db = { + "files": { + "sha1abc": { + "name": "test.bin", + "md5": "md5abc", + "sha1": "sha1abc", + "sha256": "sha256abc", + "path": "bios/Mfr/Console/test.bin", + }, + }, + "indexes": { + "by_md5": {"md5abc": "sha1abc"}, + "by_crc32": {}, + }, + } + records = lookup_hashes([("md5", "md5abc")], db, "bios") + # The record's path, the one field the schema gives it. A read of + # "paths" printed nothing. + self.assertEqual(records, [HashLookup( + "md5", "md5abc", "sha1abc", "md5abc", "test.bin", + "bios/Mfr/Console/test.bin", False, + )]) + self.assertTrue(records[0].found) + + def test_140b_lookup_hashes_never_downloads_a_release_asset(self): + """A release asset counted as held streamed the whole asset first.""" + from unittest import mock + + from resolve import packfiles + + path = "bios/Mfr/Console/big.zip" + db = { + "files": {"sha1big": {"name": "big.zip", "md5": "md5big", + "sha1": "sha1big", "path": path}}, + "indexes": {"by_md5": {"md5big": "sha1big"}, "by_crc32": {}}, + } + seen: list[bool] = [] + + def fetch(_path, expected_sha1=None, offline=False): + seen.append(offline) + + with mock.patch("model.largefiles.load_registered_paths", return_value=[path]), \ + mock.patch.object(packfiles, "fetch_large_file", side_effect=fetch), \ + mock.patch.dict(os.environ, {"RETROBIOS_OFFLINE": ""}), \ + mock.patch.object(packfiles, "OFFLINE", False): + records = packfiles.lookup_hashes([("md5", "md5big")], db, "bios") + self.assertTrue(records[0].in_repo) + self.assertEqual(seen, [True]) + + def test_141_lookup_hashes_not_found(self): + """lookup_hashes reports unknown hashes, and the report counts them.""" + import contextlib + import io + + from packs.hashlookup import print_hash_lookup + from resolve.packfiles import lookup_hashes + + db = {"files": {}, "indexes": {"by_md5": {}, "by_crc32": {}}} + unknown = "unknown123" + "0" * 22 + records = lookup_hashes([("md5", unknown)], db, "bios") + self.assertEqual([r.found for r in records], [False]) + buf = io.StringIO() + with contextlib.redirect_stdout(buf): + missing = print_hash_lookup(records) + self.assertIn("NOT FOUND", buf.getvalue()) + # The CLI exited 0 on this, so a script read "found". + self.assertEqual(missing, 1) + + def test_141b_lookup_report_names_the_file(self): + """The printed report gives the file's hashes, name, path and presence.""" + import contextlib + import io + + from packs.hashlookup import print_hash_lookup + from resolve.packfiles import HashLookup + + record = HashLookup("md5", "md5abc", "sha1abc", "md5abc", "test.bin", + "bios/Mfr/Console/test.bin", True) + buf = io.StringIO() + with contextlib.redirect_stdout(buf): + missing = print_hash_lookup([record]) + self.assertEqual(buf.getvalue(), ( + "\nMD5: md5abc\n SHA1: sha1abc\n MD5: md5abc\n Name: test.bin\n" + " Path: bios/Mfr/Console/test.bin\n In repo: YES\n" + )) + self.assertEqual(missing, 0) + + def test_142_from_md5_platform_pack(self): + """--from-md5 with --platform generates correctly laid out ZIP.""" + import tempfile + import zipfile + + import yaml + + with tempfile.TemporaryDirectory() as tmpdir: + plat_dir = os.path.join(tmpdir, "platforms") + os.makedirs(plat_dir) + bios_dir = os.path.join(tmpdir, "bios", "Sony", "PS1") + os.makedirs(bios_dir) + emu_dir = os.path.join(tmpdir, "emulators") + os.makedirs(emu_dir) + out_dir = os.path.join(tmpdir, "dist") + + bios_file = os.path.join(bios_dir, "scph5501.bin") + with open(bios_file, "wb") as f: + f.write(b"ps1_bios_content") + from core.hashing import compute_hashes + + h = compute_hashes(bios_file) + + db = { + "files": { + h["sha1"]: { + "name": "scph5501.bin", + "md5": h["md5"], + "sha1": h["sha1"], + "sha256": h["sha256"], + "path": bios_file, + "paths": ["Sony/PS1/scph5501.bin"], + }, + }, + "indexes": { + "by_md5": {h["md5"]: h["sha1"]}, + "by_name": {"scph5501.bin": [h["sha1"]]}, + "by_crc32": {}, + "by_path_suffix": {}, + }, + } + + registry = {"platforms": {"testplat": {"config": "testplat.yml"}}} + with open(os.path.join(plat_dir, "_registry.yml"), "w") as f: + yaml.dump(registry, f) + plat_cfg = { + "platform": "TestPlat", + "verification_mode": "md5", + "base_destination": "bios", + "systems": { + "sony-playstation": { + "files": [ + { + "name": "scph5501.bin", + "md5": h["md5"], + "destination": "scph5501.bin", + }, + ] + } + }, + } + with open(os.path.join(plat_dir, "testplat.yml"), "w") as f: + yaml.dump(plat_cfg, f) + + from core.ziptools import build_zip_contents_index + from packs.md5pack import generate_md5_pack + + zip_contents = build_zip_contents_index(db, Path(tmpdir)) + + zip_path = generate_md5_pack( + hashes=[("md5", h["md5"])], + db=db, + bios_dir=bios_dir, + output_dir=out_dir, + zip_contents=zip_contents, + platform_name="testplat", + platforms_dir=plat_dir, + ).zip_path + self.assertIsNotNone(zip_path) + with zipfile.ZipFile(zip_path) as zf: + names = zf.namelist() + self.assertIn("bios/scph5501.bin", names) + self.assertIn("Custom", os.path.basename(zip_path)) + + # A profile displayed under the platform's own name: BizHawk is + # both. The two layouts must not write one file. + emu_dir = os.path.join(tmpdir, "emulators-md5") + os.makedirs(emu_dir) + with open(os.path.join(emu_dir, "testplat.yml"), "w") as f: + yaml.dump({ + "emulator": "TestPlat", "type": "standalone", + "systems": ["sony-playstation"], + "files": [{"name": "scph5501.bin", "md5": h["md5"]}], + }, f) + emu_zip = generate_md5_pack( + hashes=[("md5", h["md5"])], + db=db, + bios_dir=bios_dir, + output_dir=out_dir, + zip_contents=zip_contents, + emulator_name="testplat", + emulators_dir=emu_dir, + ).zip_path + self.assertIsNotNone(emu_zip) + self.assertNotEqual(os.path.basename(emu_zip), os.path.basename(zip_path)) + self.assertTrue(os.path.exists(zip_path)) + with zipfile.ZipFile(emu_zip) as zf: + self.assertIn("scph5501.bin", zf.namelist()) + + def test_143_from_md5_not_in_repo(self): + """--from-md5 reports files in DB but missing from repo.""" + import contextlib + import io + import tempfile + + from packs.md5pack import generate_md5_pack + + db = { + "files": { + "sha1known": { + "name": "missing.bin", + "md5": "md5known" + "0" * 25, + "sha1": "sha1known", + "sha256": "sha256known", + "path": "/nonexistent/missing.bin", + "paths": ["Test/missing.bin"], + }, + }, + "indexes": { + "by_md5": {"md5known" + "0" * 25: "sha1known"}, + "by_crc32": {}, + }, + } + with tempfile.TemporaryDirectory() as tmpdir: + out_dir = os.path.join(tmpdir, "dist") + bios_dir = os.path.join(tmpdir, "bios") + os.makedirs(bios_dir) + buf = io.StringIO() + with contextlib.redirect_stdout(buf): + outcome = generate_md5_pack( + hashes=[("md5", "md5known" + "0" * 25)], + db=db, + bios_dir=bios_dir, + output_dir=out_dir, + zip_contents={}, + ) + self.assertEqual(buf.getvalue(), "") + self.assertEqual(outcome.not_in_repo, [("missing.bin", "md5known" + "0" * 25)]) + self.assertEqual((outcome.packed, outcome.not_in_db), ([], [])) + self.assertIsNone(outcome.zip_path) + from packs.packmodes import print_hash_pack + with contextlib.redirect_stdout(buf): + print_hash_pack(outcome) + self.assertIn("NOT IN REPO: missing.bin", buf.getvalue()) + + def test_144_invalid_split_emulator(self): + """--split + --emulator is rejected.""" + import subprocess + + result = subprocess.run( + ["python", "scripts/generate_pack.py", "--emulator", "test", "--split"], + capture_output=True, + text=True, + check=False, + ) + self.assertNotEqual(result.returncode, 0) + self.assertIn("error", result.stderr.lower()) + + def test_145_invalid_from_md5_all(self): + """--from-md5 + --all is rejected.""" + import subprocess + + result = subprocess.run( + [ + "python", + "scripts/generate_pack.py", + "--all", + "--from-md5", + "abc123" + "0" * 26, + ], + capture_output=True, + text=True, + check=False, + ) + self.assertNotEqual(result.returncode, 0) + + def test_146_invalid_from_md5_system(self): + """--from-md5 + --system is rejected.""" + import subprocess + + result = subprocess.run( + [ + "python", + "scripts/generate_pack.py", + "--system", + "psx", + "--from-md5", + "abc123" + "0" * 26, + ], + capture_output=True, + text=True, + check=False, + ) + self.assertNotEqual(result.returncode, 0) + + def test_147_invalid_group_by_without_split(self): + """--group-by without --split is rejected.""" + import subprocess + + result = subprocess.run( + [ + "python", + "scripts/generate_pack.py", + "--platform", + "retroarch", + "--group-by", + "manufacturer", + ], + capture_output=True, + text=True, + check=False, + ) + self.assertNotEqual(result.returncode, 0) + + def test_148_valid_platform_system(self): + """--platform + --system is accepted (not rejected at validation stage).""" + import argparse + + from model.cliargs import mode_conflicts + + def refused(**given: object) -> list[str]: + args = argparse.Namespace(**{ + "platform": None, "all": False, "emulator": None, "system": None, + "standalone": False, "target": None, "no_game_data": False, **given, + }) + return [message for on, message in mode_conflicts(args) if on] + + self.assertEqual(refused(platform="retroarch", system="psx"), []) + self.assertEqual(refused(all=True, system="psx"), []) + self.assertEqual(refused(system="psx", standalone=True), []) + # One table for verify and generate_pack: verify took --all --system + # --standalone and dropped --standalone. + self.assertTrue(refused(all=True, system="psx", standalone=True)) + self.assertTrue(refused(emulator="handy", system="psx")) + self.assertTrue(refused(platform="retroarch", all=True)) + self.assertTrue(refused(system="psx", target="switch")) + self.assertTrue(refused(emulator="handy", no_game_data=True)) + self.assertIn("Specify --platform, --all, --emulator, --system or --from-md5", [ + message for on, message in mode_conflicts( + argparse.Namespace(platform=None, all=False, emulator=None, system=None, + standalone=False), + (("--from-md5", False),), + ) if on + ]) + for script in ("verify.py", "generate_pack.py"): + self.assertIn("mode_conflicts(args", script_source(script), script) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_e2e_pack_sources.py b/tests/test_e2e_pack_sources.py new file mode 100644 index 000000000..2b5b1c747 --- /dev/null +++ b/tests/test_e2e_pack_sources.py @@ -0,0 +1,983 @@ +"""End-to-end hash scrapers, pack source variants, hashed archives and the MiSTer scraper.""" + +from __future__ import annotations + +import tests +import os +import tempfile +import unittest +import zipfile +from unittest import mock +from model import largefiles +import yaml +from model.profiles import load_emulator_profiles +from model.platforms import load_platform_config +from tests.e2esupport import E2EFixture, _h + + +class TestE2EHashScrapers(E2EFixture): + """MAME and FBNeo parsers and the hash merge.""" + + # --------------------------------------------------------------- + # Hash scraper: parsers + merge + # --------------------------------------------------------------- + + def test_mame_parser_finds_bios_root_sets(self): + from scripts.scraper.mame_parser import find_bios_root_sets, parse_rom_block + + source = """ +ROM_START( neogeo ) + ROM_REGION( 0x020000, "mainbios", 0 ) + ROM_LOAD( "sp-s2.sp1", 0x00000, 0x020000, CRC(9036d879) SHA1(4f834c580f3471ce40c3210ef5e7491df38d8851) ) +ROM_END +GAME( 1990, neogeo, 0, ng, neogeo, ng_state, empty_init, ROT0, "SNK", "Neo Geo", MACHINE_IS_BIOS_ROOT ) +ROM_START( pacman ) + ROM_REGION( 0x10000, "maincpu", 0 ) + ROM_LOAD( "pacman.6e", 0x0000, 0x1000, CRC(c1e6ab10) SHA1(e87e059c5be45753f7e9f33dff851f16d6751181) ) +ROM_END +GAME( 1980, pacman, 0, pacman, pacman, pacman_state, empty_init, ROT90, "Namco", "Pac-Man", 0 ) +""" + sets = find_bios_root_sets(source, "neogeo.cpp") + self.assertIn("neogeo", sets) + self.assertNotIn("pacman", sets) + roms = parse_rom_block(source, "neogeo") + self.assertEqual(len(roms), 1) + self.assertEqual(roms[0]["crc32"], "9036d879") + + def test_fbneo_parser_finds_bios_sets(self): + from scripts.scraper.fbneo_parser import find_bios_sets, parse_rom_info + + source = """ +static struct BurnRomInfo neogeoRomDesc[] = { + { "sp-s2.sp1", 0x020000, 0x9036d879, BRF_ESS | BRF_BIOS }, + { "", 0, 0, 0 } +}; +STD_ROM_PICK(neogeo) +STD_ROM_FN(neogeo) +struct BurnDriver BurnDrvneogeo = { + "neogeo", NULL, NULL, NULL, "1990", + "Neo Geo\\0", "BIOS only", "SNK", "Neo Geo MVS", + NULL, NULL, NULL, NULL, BDF_BOARDROM, 0, 0, + 0, 0, 0, NULL, neogeoRomInfo, neogeoRomName, NULL, NULL, + NULL, NULL, NULL, NULL, 0 +}; +""" + sets = find_bios_sets(source, "d_neogeo.cpp") + self.assertIn("neogeo", sets) + roms = parse_rom_info(source, "neogeo") + self.assertEqual(len(roms), 1) + self.assertEqual(roms[0]["crc32"], "9036d879") + + def test_mame_merge_preserves_manual_fields(self): + from scripts.scraper._hash_merge import merge_mame_profile + + profile = { + "emulator": "Test", + "type": "libretro", + "upstream": "https://github.com/mamedev/mame", + "core_version": "0.285", + "files": [ + { + "name": "neogeo.zip", + "required": True, + "category": "bios_zip", + "system": "snk-neogeo-mvs", + "note": "MVS BIOS", + "source_ref": "old.cpp:1", + "contents": [ + {"name": "sp-s2.sp1", "size": 131072, "crc32": "oldcrc"} + ], + } + ], + } + hashes = { + "source": "mamedev/mame", + "version": "0.286", + "commit": "abc", + "fetched_at": "2026-03-30T00:00:00Z", + "bios_sets": { + "neogeo": { + "source_file": "neo.cpp", + "source_line": 42, + "roms": [ + { + "name": "sp-s2.sp1", + "size": 131072, + "crc32": "newcrc", + "sha1": "abc123", + } + ], + } + }, + } + result = merge_mame_profile(profile, hashes) + neo = next(f for f in result["files"] if f["name"] == "neogeo.zip") + self.assertEqual(neo["contents"][0]["crc32"], "newcrc") + self.assertEqual(neo["system"], "snk-neogeo-mvs") + self.assertEqual(neo["note"], "MVS BIOS") + self.assertEqual(neo["source_ref"], "neo.cpp:42") + self.assertEqual(result["core_version"], "0.286") + + def test_fbneo_merge_updates_individual_roms(self): + from scripts.scraper._hash_merge import merge_fbneo_profile + + profile = { + "emulator": "FBNeo", + "type": "libretro", + "upstream": "https://github.com/finalburnneo/FBNeo", + "core_version": "v1.0.0.02", + "files": [ + { + "name": "sp-s2.sp1", + "archive": "neogeo.zip", + "system": "snk-neogeo-mvs", + "required": True, + "size": 131072, + "crc32": "oldcrc", + } + ], + } + hashes = { + "source": "finalburnneo/FBNeo", + "version": "v1.0.0.03", + "commit": "def", + "fetched_at": "2026-03-30T00:00:00Z", + "bios_sets": { + "neogeo": { + "source_file": "neo.cpp", + "source_line": 10, + "roms": [{"name": "sp-s2.sp1", "size": 131072, "crc32": "newcrc"}], + } + }, + } + result = merge_fbneo_profile(profile, hashes) + rom = next(f for f in result["files"] if f["name"] == "sp-s2.sp1") + self.assertEqual(rom["crc32"], "newcrc") + self.assertEqual(rom["system"], "snk-neogeo-mvs") + # The version is the pin's, read through version_basis. + self.assertEqual(result["core_version"], "v1.0.0.02") + + +class TestE2EPackSource(E2EFixture): + """Pack source variants: platform, truth and full.""" + + def _load_config(self, platform_name: str) -> dict: + return load_platform_config(platform_name, self.platforms_dir) + + def test_200_find_undeclared_include_all(self): + """include_all=True returns ALL core files, including declared ones.""" + from packs.gaps import find_undeclared_files + + config = self._load_config("test_existence") + profiles = load_emulator_profiles(self.emulators_dir) + # Without include_all: only undeclared files returned + undeclared = find_undeclared_files( + config, self.emulators_dir, self.db, profiles + ) + undeclared_names = {u["name"] for u in undeclared} + # present_req.bin is declared in platform YAML, should NOT be in undeclared + self.assertNotIn("present_req.bin", undeclared_names) + + # With include_all: ALL core files returned, including declared ones + all_files = find_undeclared_files( + config, self.emulators_dir, self.db, profiles, include_all=True + ) + all_names = {u["name"] for u in all_files} + # present_req.bin IS declared but should be returned with include_all + self.assertIn("present_req.bin", all_names) + # undeclared files should still be present + self.assertIn("undeclared_req.bin", all_names) + # Launcher/alias files should still be excluded + self.assertNotIn("launcher_bios.bin", all_names) + + def test_201_collect_emulator_extras_include_all(self): + """include_all=True passes through to find_undeclared_files.""" + from packs.extras import collect_emulator_extras + + config = self._load_config("test_existence") + profiles = load_emulator_profiles(self.emulators_dir) + base_dest = config.get("base_destination", "") + + # Default call must succeed without TypeError + extras = collect_emulator_extras( + config, self.emulators_dir, self.db, set(), base_dest, profiles + ) + self.assertIsInstance(extras, list) + + # include_all=True must be accepted and return a list + all_extras = collect_emulator_extras( + config, self.emulators_dir, self.db, set(), base_dest, profiles, + include_all=True, + ) + self.assertIsInstance(all_extras, list) + + # include_all=True is a superset: at least as many entries as default + all_names = {e["name"] for e in all_extras} + default_names = {e["name"] for e in extras} + self.assertGreaterEqual(len(all_names), len(default_names)) + # All default entries are present in include_all result + for name in default_names: + self.assertIn(name, all_names) + + + def test_202_pack_source_platform(self): + """source='platform' skips core extras.""" + from packs.platformpack import generate_pack + + output_dir = os.path.join(self.root, "pack_platform") + os.makedirs(output_dir, exist_ok=True) + profiles = load_emulator_profiles(self.emulators_dir) + zip_path = generate_pack( + "test_existence", + self.platforms_dir, + self.db, + self.bios_dir, + output_dir, + emu_profiles=profiles, + emulators_dir=self.emulators_dir, + source="platform", + ) + self.assertIsNotNone(zip_path) + self.assertIn("_Platform_", os.path.basename(zip_path)) + + def test_203_pack_source_truth(self): + """source='truth' uses emulator profile files.""" + from packs.platformpack import generate_pack + + output_dir = os.path.join(self.root, "pack_truth") + os.makedirs(output_dir, exist_ok=True) + profiles = load_emulator_profiles(self.emulators_dir) + zip_path = generate_pack( + "test_existence", + self.platforms_dir, + self.db, + self.bios_dir, + output_dir, + emu_profiles=profiles, + emulators_dir=self.emulators_dir, + source="truth", + ) + self.assertIsNotNone(zip_path) + self.assertIn("_Truth_", os.path.basename(zip_path)) + + def test_204_pack_source_full_unchanged(self): + """source='full' (default) has no source tag in filename.""" + from packs.platformpack import generate_pack + + output_dir = os.path.join(self.root, "pack_full") + os.makedirs(output_dir, exist_ok=True) + profiles = load_emulator_profiles(self.emulators_dir) + zip_path = generate_pack( + "test_existence", + self.platforms_dir, + self.db, + self.bios_dir, + output_dir, + emu_profiles=profiles, + emulators_dir=self.emulators_dir, + source="full", + ) + self.assertIsNotNone(zip_path) + bn = os.path.basename(zip_path) + self.assertNotIn("_Platform_", bn) + self.assertNotIn("_Truth_", bn) + + + def test_205_pack_source_platform_required(self): + """source='platform' + required_only=True.""" + from packs.platformpack import generate_pack + + output_dir = os.path.join(self.root, "pack_plat_req") + os.makedirs(output_dir, exist_ok=True) + profiles = load_emulator_profiles(self.emulators_dir) + zip_path = generate_pack( + "test_existence", + self.platforms_dir, + self.db, + self.bios_dir, + output_dir, + emu_profiles=profiles, + emulators_dir=self.emulators_dir, + source="platform", + required_only=True, + ) + self.assertIsNotNone(zip_path) + self.assertIn("_Platform_Required_", os.path.basename(zip_path)) + with zipfile.ZipFile(zip_path) as zf: + names = zf.namelist() + self.assertTrue(any("present_req.bin" in n for n in names)) + self.assertFalse(any("present_opt.bin" in n for n in names)) + + def test_206_pack_source_truth_required(self): + """source='truth' + required_only=True.""" + from packs.platformpack import generate_pack + + output_dir = os.path.join(self.root, "pack_truth_req") + os.makedirs(output_dir, exist_ok=True) + profiles = load_emulator_profiles(self.emulators_dir) + zip_path = generate_pack( + "test_existence", + self.platforms_dir, + self.db, + self.bios_dir, + output_dir, + emu_profiles=profiles, + emulators_dir=self.emulators_dir, + source="truth", + required_only=True, + ) + self.assertIsNotNone(zip_path) + self.assertIn("_Truth_Required_", os.path.basename(zip_path)) + + def test_207_manifest_source(self): + """generate_manifest respects source param.""" + from packs.manifest import generate_manifest + + profiles = load_emulator_profiles(self.emulators_dir) + registry_path = os.path.join(self.platforms_dir, "_registry.yml") + if not os.path.exists(registry_path): + with open(registry_path, "w") as fh: + yaml.dump({"platforms": {}}, fh) + manifest_full = generate_manifest( + "test_existence", self.platforms_dir, self.db, self.bios_dir, + registry_path, emulators_dir=self.emulators_dir, emu_profiles=profiles, + source="full", offline=True, + ) + manifest_plat = generate_manifest( + "test_existence", self.platforms_dir, self.db, self.bios_dir, + registry_path, emulators_dir=self.emulators_dir, emu_profiles=profiles, + source="platform", offline=True, + ) + self.assertLessEqual(manifest_plat["total_files"], manifest_full["total_files"]) + self.assertEqual(manifest_plat.get("source"), "platform") + self.assertEqual(manifest_full.get("source"), "full") + + def test_208_split_source_tag_in_dirname(self): + """generate_split_packs uses source tag in split directory name.""" + from packs.platformpack import generate_split_packs + + output_dir = os.path.join(self.root, "split_src") + os.makedirs(output_dir, exist_ok=True) + profiles = load_emulator_profiles(self.emulators_dir) + generate_split_packs( + "test_existence", self.platforms_dir, self.db, self.bios_dir, + output_dir, emulators_dir=self.emulators_dir, emu_profiles=profiles, + source="platform", + ) + entries = os.listdir(output_dir) + platform_dirs = [e for e in entries if "_Platform_" in e and "Split" in e] + self.assertTrue(len(platform_dirs) > 0, f"No _Platform_ split dir in {entries}") + + def test_209_all_variants_generates_6_zips(self): + """All 6 source x required combinations produce unique ZIPs.""" + from packs.platformpack import generate_pack + + output_dir = os.path.join(self.root, "pack_allvar") + os.makedirs(output_dir, exist_ok=True) + profiles = load_emulator_profiles(self.emulators_dir) + variants = [ + ("full", False), ("full", True), + ("platform", False), ("platform", True), + ("truth", False), ("truth", True), + ] + for source, required_only in variants: + generate_pack( + "test_existence", self.platforms_dir, self.db, self.bios_dir, + output_dir, emu_profiles=profiles, emulators_dir=self.emulators_dir, + source=source, required_only=required_only, + ) + zips = [f for f in os.listdir(output_dir) if f.endswith(".zip")] + self.assertEqual(len(zips), 6, f"Expected 6 ZIPs, got {len(zips)}: {zips}") + self.assertEqual(len(set(zips)), 6) + + +class TestE2EHashResolution(E2EFixture): + """Declared archive bytes, strong hash resolution and zip member checks.""" + + def _make_hash_zip_fixture(self, tmpdir, declare_md5=True): + """Platform fixture with one ZIP file, optionally md5-declared.""" + import hashlib as hl + + plat_dir = os.path.join(tmpdir, "platforms") + bios_dir = os.path.join(tmpdir, "bios", "Arcade") + out_dir = os.path.join(tmpdir, "dist") + os.makedirs(plat_dir) + os.makedirs(bios_dir) + + zip_src = os.path.join(bios_dir, "testbios.zip") + with zipfile.ZipFile(zip_src, "w", zipfile.ZIP_DEFLATED) as zf: + info = zipfile.ZipInfo("rom.bin", date_time=(2020, 6, 15, 12, 0, 0)) + zf.writestr(info, b"rom_content_bytes") + from core.hashing import compute_hashes + + h = compute_hashes(zip_src) + + db = { + "files": { + h["sha1"]: { + "name": "testbios.zip", + "md5": h["md5"], + "sha1": h["sha1"], + "path": zip_src, + "paths": ["Arcade/testbios.zip"], + }, + }, + "indexes": { + "by_md5": {h["md5"]: h["sha1"]}, + "by_name": {"testbios.zip": [h["sha1"]]}, + "by_crc32": {}, + "by_path_suffix": {}, + }, + } + entry = {"name": "testbios.zip", "destination": "dc/testbios.zip"} + if declare_md5: + entry["md5"] = h["md5"] + config = { + "platform": "HashZipTest", + "verification_mode": "md5", + "base_destination": "bios", + "systems": {"arcade-sys": {"files": [entry]}}, + } + with open(os.path.join(plat_dir, "test_hashzip.yml"), "w") as fh: + yaml.dump(config, fh) + return plat_dir, os.path.join(tmpdir, "bios"), out_dir, db, h, hl + + def test_210_pack_copies_md5_declared_zip_byte_identical(self): + """md5-declared ZIPs are copied unchanged, never rebuilt.""" + import tempfile + + from packs.platformpack import generate_pack + + with tempfile.TemporaryDirectory() as tmpdir: + plat_dir, bios_root, out_dir, db, h, hl = self._make_hash_zip_fixture( + tmpdir, declare_md5=True + ) + zip_path = generate_pack( + "test_hashzip", plat_dir, db, bios_root, out_dir + ) + self.assertIsNotNone(zip_path) + with zipfile.ZipFile(zip_path) as zf: + data = zf.read("dc/testbios.zip") + self.assertEqual(hl.md5(data).hexdigest(), h["md5"]) + + def test_211_pack_keeps_zip_bytes_without_declared_hash(self): + """A ZIP with no declared hash keeps the collection's bytes, so it + hashes to what the install list publishes.""" + import io + import tempfile + + from packs.platformpack import generate_pack + + with tempfile.TemporaryDirectory() as tmpdir: + plat_dir, bios_root, out_dir, db, h, hl = self._make_hash_zip_fixture( + tmpdir, declare_md5=False + ) + zip_path = generate_pack( + "test_hashzip", plat_dir, db, bios_root, out_dir + ) + self.assertIsNotNone(zip_path) + with zipfile.ZipFile(zip_path) as zf: + data = zf.read("dc/testbios.zip") + self.assertEqual(hl.md5(data).hexdigest(), h["md5"]) + with zipfile.ZipFile(io.BytesIO(data)) as inner: + self.assertEqual(inner.read("rom.bin"), b"rom_content_bytes") + + def test_212_verify_pack_flags_native_md5_mismatch(self): + """Pack verification reproduces the native md5 check per member.""" + import tempfile + + from packs.platformcheck import verify_pack_against_platform + + with tempfile.TemporaryDirectory() as tmpdir: + plat_dir, bios_root, out_dir, db, h, hl = self._make_hash_zip_fixture( + tmpdir, declare_md5=True + ) + os.makedirs(out_dir) + bad_pack = os.path.join(out_dir, "HashZipTest_BIOS_Pack.zip") + with zipfile.ZipFile(bad_pack, "w") as zf: + zf.writestr("dc/testbios.zip", b"wrong bytes entirely") + result = verify_pack_against_platform( + bad_pack, "test_hashzip", plat_dir, db=None + ) + errors = result[3] + self.assertTrue( + any("md5" in e for e in errors), + f"expected md5 mismatch error, got: {errors}", + ) + + def test_213_verify_pack_passes_correct_member_hash(self): + """Pack verification passes when member bytes match declared md5.""" + import tempfile + + from packs.platformcheck import verify_pack_against_platform + + with tempfile.TemporaryDirectory() as tmpdir: + plat_dir, bios_root, out_dir, db, h, hl = self._make_hash_zip_fixture( + tmpdir, declare_md5=True + ) + os.makedirs(out_dir) + good_pack = os.path.join(out_dir, "HashZipTest_BIOS_Pack.zip") + src = os.path.join(bios_root, "Arcade", "testbios.zip") + with zipfile.ZipFile(good_pack, "w") as zf: + zf.write(src, "dc/testbios.zip") + result = verify_pack_against_platform( + good_pack, "test_hashzip", plat_dir, db=None + ) + self.assertEqual(result[3], [], f"unexpected errors: {result[3]}") + + def test_213b_absent_game_data_is_counted_apart(self): + """Game data the collection lacks is counted apart from the pack's + errors, while firmware the collection lacks stays one.""" + import tempfile + + from packs.platformpack import generate_pack + from packs.platformcheck import verify_pack_against_platform + + profiles = {"eng": {"emulator": "Eng", "type": "game", "cores": ["eng"], + "systems": ["arcade-sys"], + "files": [{"name": "data.pak", "category": "game_data"}, + {"name": "firmware.bin"}]}} + with tempfile.TemporaryDirectory() as tmpdir: + plat_dir, bios_root, out_dir, db, _h, _hl = self._make_hash_zip_fixture( + tmpdir, declare_md5=True + ) + config_path = os.path.join(plat_dir, "test_hashzip.yml") + with open(config_path) as fh: + config = yaml.safe_load(fh) + config["cores"] = ["eng"] + config["systems"]["arcade-sys"]["files"].append( + {"name": "data.pak", "destination": "dc/data.pak"} + ) + with open(config_path, "w") as fh: + yaml.dump(config, fh) + zip_path = generate_pack("test_hashzip", plat_dir, db, bios_root, out_dir, + emu_profiles=profiles) + result = verify_pack_against_platform( + zip_path, "test_hashzip", plat_dir, db=db, emu_profiles=profiles) + self.assertEqual(result[3], []) + self.assertEqual((result[4], result[5], result[9]), (2, 1, 1)) + + config["systems"]["arcade-sys"]["files"][-1]["name"] = "firmware.bin" + config["systems"]["arcade-sys"]["files"][-1]["destination"] = "dc/firmware.bin" + with open(os.path.join(plat_dir, "test_hashzip_fw.yml"), "w") as fh: + yaml.dump(config, fh) + result = verify_pack_against_platform( + zip_path, "test_hashzip_fw", plat_dir, db=db, emu_profiles=profiles) + self.assertEqual([e.rsplit("/", 1)[-1] for e in result[3]], ["firmware.bin"]) + self.assertTrue(result[3][0].startswith("baseline missing: ")) + self.assertEqual(result[9], 0) + + def test_216_resolve_by_sha256(self): + """resolve_local_file matches files by declared sha256.""" + import tempfile + + from resolve.localfile import resolve_local_file + + with tempfile.TemporaryDirectory() as tmpdir: + path = os.path.join(tmpdir, "SNES_dsp1.rom") + with open(path, "wb") as fh: + fh.write(b"dsp firmware bytes") + import hashlib as hl + + sha256 = hl.sha256(b"dsp firmware bytes").hexdigest() + db = { + "files": { + "sha1x": { + "name": "SNES_dsp1.rom", + "path": path, + "sha256": sha256, + }, + }, + "indexes": { + "by_md5": {}, + "by_name": {"SNES_dsp1.rom": ["sha1x"]}, + "by_sha256": {sha256: "sha1x"}, + "by_crc32": {}, + "by_path_suffix": {}, + }, + } + # Name differs, only sha256 identifies the content + entry = {"name": "dsp1.rom", "sha256": sha256} + local, status = resolve_local_file(entry, db) + self.assertEqual(local, path) + self.assertEqual(status, "sha256_exact") + # Multi-hash list also resolves + entry = {"name": "dsp1.rom", "sha256": f"{'0' * 64},{sha256}"} + local, status = resolve_local_file(entry, db) + self.assertEqual(local, path) + # Unknown sha256 falls through to not_found + entry = {"name": "dsp1.rom", "sha256": "f" * 64} + local, status = resolve_local_file(entry, db) + self.assertIsNone(local) + self.assertEqual(status, "not_found") + + def test_220_large_file_dotted_asset_fallback(self): + """Files with spaces resolve to GitHub's dotted asset name.""" + import tempfile + import urllib.error + + from model.largefiles import fetch_large_file + + attempts = [] + + class FakeResponse: + headers: dict = {} + + def __init__(self, payload): + self._payload = payload + + def read(self, _size=None): + data, self._payload = self._payload, b"" + return data + + def __enter__(self): + return self + + def __exit__(self, *_): + return False + + def fake_urlopen(req, timeout=None): + url = req.full_url if hasattr(req, "full_url") else str(req) + attempts.append(url) + if "MAME%200.174" in url: + raise urllib.error.HTTPError(url, 404, "Not Found", {}, None) + return FakeResponse(b"payload") + + original = largefiles.urllib.request.urlopen + largefiles.urllib.request.urlopen = fake_urlopen + try: + with tempfile.TemporaryDirectory() as tmpdir, mock.patch.dict( + os.environ, {"RETROBIOS_OFFLINE": ""} + ): + path = fetch_large_file( + "MAME 0.174 Arcade XML.dat", dest_dir=tmpdir + ) + self.assertIsNotNone(path) + with open(path, "rb") as fh: + self.assertEqual(fh.read(), b"payload") + finally: + largefiles.urllib.request.urlopen = original + + self.assertEqual(len(attempts), 2, attempts) + self.assertIn("MAME%200.174", attempts[0]) + self.assertIn("MAME.0.174.Arcade.XML.dat", attempts[1]) + + def test_219_batocera_stable_tag_selection(self): + """Stable tag picker takes the highest batocera-N(.M) tag.""" + from scripts.scraper.batocera_scraper import pick_stable_tag + + tags = [ + "uboot-rockpro64", "batocera-pre-br2-external", + "batocera-41", "batocera-42", "batocera-43", "batocera-43.1", + "master_20180518", + ] + self.assertEqual(pick_stable_tag(tags), "batocera-43.1") + self.assertEqual(pick_stable_tag(["batocera-9", "batocera-10"]), "batocera-10") + self.assertIsNone(pick_stable_tag(["uboot-x", "random"])) + + def test_218_resolve_by_crc32_and_size(self): + """crc-only profile entries resolve by crc32 confirmed by size.""" + import tempfile + import zlib + + from resolve.localfile import resolve_local_file + + with tempfile.TemporaryDirectory() as tmpdir: + data = b"exos rom bytes" * 100 + path = os.path.join(tmpdir, "exos21.rom") + with open(path, "wb") as fh: + fh.write(data) + crc = f"{zlib.crc32(data) & 0xffffffff:08x}" + db = { + "files": { + "sha1e": { + "name": "exos21.rom", + "path": path, + "size": len(data), + "crc32": crc, + }, + }, + "indexes": { + "by_md5": {}, + "by_name": {"exos21.rom": ["sha1e"]}, + "by_crc32": {crc: "sha1e"}, + "by_path_suffix": {}, + }, + } + # Different extension in the profile, crc32+size identify it + local, status = resolve_local_file( + {"name": "exos21.bin", "crc32": crc, "size": len(data)}, db + ) + self.assertEqual(local, path) + self.assertEqual(status, "crc32_exact") + # Wrong size rejects the crc match + local, status = resolve_local_file( + {"name": "exos21.bin", "crc32": crc, "size": 1}, db + ) + self.assertIsNone(local) + + def test_217_resolve_name_casefold_fallback(self): + """Name resolution falls back to a case-insensitive match.""" + import tempfile + + from resolve.localfile import resolve_local_file + + with tempfile.TemporaryDirectory() as tmpdir: + path = os.path.join(tmpdir, "VEC_Minestorm.vec") + with open(path, "wb") as fh: + fh.write(b"minestorm rom") + db = { + "files": {"sha1v": {"name": "VEC_Minestorm.vec", "path": path}}, + "indexes": { + "by_md5": {}, + "by_name": {"VEC_Minestorm.vec": ["sha1v"]}, + "by_crc32": {}, + "by_path_suffix": {}, + }, + } + # Upstream declares a different casing, no hash + local, status = resolve_local_file( + {"name": "VEC_MineStorm.vec"}, db + ) + self.assertEqual(local, path) + self.assertEqual(status, "name_exact") + + def test_217b_zipped_file_composite_needs_the_member(self): + """One member of another name has the zipped_file md5 as composite. + + Batocera looks the member up by name, so the archive is not proof of + the entry: a MAME rename leaves exactly that archive behind. + """ + import hashlib as hl + import tempfile + + from resolve.localfile import resolve_local_file + + rom = b"inner rom bytes" + rom_md5 = hl.md5(rom).hexdigest() + with tempfile.TemporaryDirectory() as tmpdir: + path = os.path.join(tmpdir, "foo.zip") + with zipfile.ZipFile(path, "w") as zf: + zf.writestr("renamed.bin", rom) + db = { + "files": {"sha1z": {"name": "foo.zip", "path": path, "md5": "f" * 32}}, + "indexes": { + "by_md5": {}, "by_name": {"foo.zip": ["sha1z"]}, + "by_crc32": {}, "by_path_suffix": {}, + }, + } + entry = {"name": "foo.zip", "zipped_file": "expected.bin", "md5": rom_md5} + self.assertNotEqual( + resolve_local_file(entry, db)[1], "md5_composite_exact" + ) + with zipfile.ZipFile(path, "w") as zf: + zf.writestr("expected.bin", rom) + self.assertEqual( + resolve_local_file(entry, db), (path, "md5_composite_exact") + ) + + def test_215_check_member_hash_inside_zip(self): + """zipped_file entries verify the ROM inside the ZIP, not the ZIP.""" + import hashlib as hl + import tempfile + + from packs.packhashes import _check_member_hash + + rom = b"inner rom bytes" + rom_md5 = hl.md5(rom).hexdigest() + with tempfile.TemporaryDirectory() as tmpdir: + pack = os.path.join(tmpdir, "pack.zip") + import io + + inner_buf = io.BytesIO() + with zipfile.ZipFile(inner_buf, "w") as inner: + inner.writestr("EPR-123.IC27", rom) + with zipfile.ZipFile(pack, "w") as zf: + zf.writestr("dc/game.zip", inner_buf.getvalue()) + with zipfile.ZipFile(pack) as zf: + # Case-insensitive inner match (Batocera casefold) + ok = _check_member_hash( + zf, + "dc/game.zip", + {"zipped_file": "epr-123.ic27", "md5": rom_md5}, + "md5", + ) + self.assertIsNone(ok) + bad = _check_member_hash( + zf, + "dc/game.zip", + {"zipped_file": "epr-123.ic27", "md5": "0" * 32}, + "md5", + ) + self.assertIsNotNone(bad) + + +class TestE2EMister(E2EFixture): + """The MiSTer BiosDB scraper, cross-reference filtering and compressed manifests.""" + + # -- MiSTer FPGA scraper (BiosDB) ------------------------------------- + + MISTER_DB = { + "db_id": "bios_db", + "timestamp": 1785183064, + "files": { + "games/3DO/boot.rom": { + "hash": "f47264dd47fe30f73ab3c010015c155b", + "size": 1048576, + "url": "https://archive.org/download/x/3DO.zip/boot.rom", + }, + "games/GameCom/boot.rom": { + "hash": "3f2178d717dd309ed7424d49ef92987f", + "size": 262144, + "url": "https://archive.org/download/x/GameCom.zip/boot.rom", + }, + }, + "archives": { + "neogeo_unibios": { + "archive_file": {"hash": "a" * 32, "size": 101498, "url": "http://x/u.zip"}, + "summary_inline": { + "files": { + "games/NEOGEO/uni-bios.rom": { + "hash": "4f0aeda8d2d145f596826b62d563c4ef", + "size": 131072, + } + } + }, + } + }, + } + + def _mister_scraper(self): + import json + + from scraper.misterfpga_scraper import Scraper + + scraper = Scraper(url="https://example.test/bios_db.json.zip") + scraper._raw_data = json.dumps(self.MISTER_DB) + return scraper + + def test_221_mister_parse_db_inlines_archive_entries(self): + """Archive-provided files carry the extracted member hash.""" + import json + + from scraper.misterfpga_scraper import parse_db + + entries = parse_db(json.dumps(self.MISTER_DB)) + self.assertIn("games/NEOGEO/uni-bios.rom", entries) + self.assertEqual( + entries["games/NEOGEO/uni-bios.rom"]["hash"], + "4f0aeda8d2d145f596826b62d563c4ef", + ) + self.assertEqual(len(entries), 3) + + def test_222_mister_validate_format_rejects_foreign_db(self): + """Only the bios_db database is accepted.""" + import json + + scraper = self._mister_scraper() + self.assertTrue(scraper.validate_format(json.dumps(self.MISTER_DB))) + self.assertFalse(scraper.validate_format("not json")) + self.assertFalse( + scraper.validate_format(json.dumps({"db_id": "distribution_mister", "files": {}})) + ) + broken = json.loads(json.dumps(self.MISTER_DB)) + broken["files"]["games/3DO/boot.rom"].pop("size") + self.assertFalse(scraper.validate_format(json.dumps(broken))) + + def test_223_mister_requirements_strip_games_prefix(self): + """Destinations are relative to base_destination games.""" + reqs = {r.destination: r for r in self._mister_scraper().fetch_requirements()} + self.assertIn("3DO/boot.rom", reqs) + self.assertEqual(reqs["3DO/boot.rom"].name, "boot.rom") + self.assertEqual(reqs["3DO/boot.rom"].system, "3do") + self.assertEqual(reqs["3DO/boot.rom"].native_id, "3DO") + self.assertEqual(reqs["3DO/boot.rom"].size, 1048576) + + def test_224_mister_platform_yaml_shape(self): + """The generated config declares md5 verification and no cores.""" + config = self._mister_scraper().generate_platform_yaml() + self.assertEqual(config["verification_mode"], "md5") + self.assertEqual(config["base_destination"], "games") + self.assertEqual(config["cores"], []) + self.assertEqual(config["version"], "2026-07-27") + systems = config["systems"] + self.assertEqual( + systems["3do"]["docs"], "https://github.com/MiSTer-devel/3DO_MiSTer" + ) + # No MiSTer-devel repository exists for the Game.com core + self.assertNotIn("docs", systems["tiger-game-com"]) + entry = systems["3do"]["files"][0] + self.assertTrue(entry["required"]) + self.assertEqual(entry["md5"], "f47264dd47fe30f73ab3c010015c155b") + + def test_225_mister_docs_targets_are_unique_per_system(self): + """Every mapped system resolves to a distinct retrobios system ID.""" + from scraper.misterfpga_scraper import SYSTEM_MAP + + folders = list(SYSTEM_MAP) + systems = [SYSTEM_MAP[f][0] for f in folders] + self.assertEqual(len(systems), len(set(systems))) + + + def test_226_cross_reference_platform_filter(self): + """--platform restricts declarations to that platform alone.""" + from packs.crossref import global_report_scope, platform_configs + + with tempfile.TemporaryDirectory() as tmpdir: + plat_dir = os.path.join(tmpdir, "platforms") + os.makedirs(plat_dir) + registry = { + "platforms": { + "alpha": {"config": "alpha.yml"}, + "beta": {"config": "beta.yml"}, + } + } + with open(os.path.join(plat_dir, "_registry.yml"), "w") as f: + yaml.dump(registry, f) + for name, fname in (("alpha", "a.bin"), ("beta", "b.bin")): + cfg = { + "platform": name, + "verification_mode": "md5", + "systems": {"shared-system": {"files": [{"name": fname}]}}, + } + with open(os.path.join(plat_dir, f"{name}.yml"), "w") as f: + yaml.dump(cfg, f) + + # Keyed by the normalized system ID, as profiles spell systems + # differently from platforms. + db = {"files": {}, "indexes": {}} + everything, _ = global_report_scope(platform_configs(plat_dir), db, {}) + self.assertEqual(everything["sharedsystem"], {"a.bin", "b.bin"}) + + only_alpha, _ = global_report_scope(platform_configs(plat_dir, ["alpha"]), db, {}) + self.assertEqual(only_alpha["sharedsystem"], {"a.bin"}) + + + def test_227_manifest_injected_compressed(self): + """The manifest is deflated whichever injection path runs.""" + import json as _json + + from packs.finalize import inject_manifest + + manifest = {"files": [{"path": f"f{i}.bin"} for i in range(200)]} + raw = _json.dumps(manifest, indent=2, ensure_ascii=False) + sizes = [] + with tempfile.TemporaryDirectory() as tmpdir: + for preexisting in (False, True): + path = os.path.join(tmpdir, f"pack{int(preexisting)}.zip") + with zipfile.ZipFile(path, "w", zipfile.ZIP_DEFLATED) as zf: + zf.writestr("bios.bin", b"x" * 4096) + if preexisting: + zf.writestr("manifest.json", "{}") + inject_manifest(path, manifest) + with zipfile.ZipFile(path) as zf: + info = zf.getinfo("manifest.json") + self.assertEqual(info.compress_type, zipfile.ZIP_DEFLATED) + self.assertEqual(_json.loads(zf.read("manifest.json")), manifest) + sizes.append(info.compress_size) + self.assertLess(sizes[0], len(raw)) + self.assertEqual(sizes[0], sizes[1]) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_e2e_region.py b/tests/test_e2e_region.py new file mode 100644 index 000000000..a11595af7 --- /dev/null +++ b/tests/test_e2e_region.py @@ -0,0 +1,972 @@ +"""End-to-end region filtering, pack narrowings and gap analysis.""" + +from __future__ import annotations + +import tests +from tests.sources import script_source +import os +import sys +import unittest +import zipfile +import yaml +from tests.e2esupport import E2EFixture + + +class TestE2ERegion(E2EFixture): + """Region filter, narrowing names and the reports that follow them.""" + + # --------------------------------------------------------------- + # Region filter + # --------------------------------------------------------------- + + def _region_profiles(self) -> dict: + return { + "rgncore": { + "emulator": "RegionCore", + "type": "libretro", + "cores": ["rgncore"], + "systems": ["region-console"], + "files": [ + {"name": "rgn_us.bin", "region": ["north-america"]}, + {"name": "rgn_jp.bin", "region": ["japan"]}, + {"name": "rgn_eu.bin", "region": ["europe"]}, + {"name": "rgn_world.bin", "region": ["world"]}, + {"name": "rgn_plain.bin"}, + ], + } + } + + def _create_region_fixtures(self) -> None: + names = ( + "rgn_us.bin", + "rgn_jp.bin", + "rgn_eu.bin", + "rgn_world.bin", + "rgn_plain.bin", + ) + for name in names: + self._make_file(name, name.encode()) + self.db = self._build_db() + config = { + "platform": "RegionPlat", + "version": "3.0", + "verification_mode": "existence", + "systems": { + "region-console": { + "files": [ + { + "name": n, + "destination": n, + "required": n + in ("rgn_us.bin", "rgn_jp.bin", "rgn_eu.bin"), + } + for n in names + ] + } + }, + } + with open( + os.path.join(self.platforms_dir, "regionplat.yml"), "w", encoding="utf-8" + ) as fh: + yaml.safe_dump(config, fh) + + def _region_pack(self, **kwargs) -> str: + from packs.platformpack import generate_pack + + self._create_region_fixtures() + out = generate_pack( + "regionplat", + self.platforms_dir, + self.db, + self.bios_dir, + self.root, + emu_profiles=self._region_profiles(), + **kwargs, + ) + self.assertIsNotNone(out) + return out + + @staticmethod + def _names_in(zip_path: str) -> set[str]: + with zipfile.ZipFile(zip_path) as zf: + return {os.path.basename(n) for n in zf.namelist()} + + def test_region_filter_drops_other_regions(self): + names = self._names_in(self._region_pack(regions=["north-america"])) + self.assertIn("rgn_us.bin", names) + self.assertNotIn("rgn_jp.bin", names) + self.assertNotIn("rgn_eu.bin", names) + + def test_region_priority_selects_second_choice(self): + names = self._names_in(self._region_pack(regions=["oceania", "europe"])) + self.assertIn("rgn_eu.bin", names) + self.assertNotIn("rgn_us.bin", names) + self.assertNotIn("rgn_jp.bin", names) + + def test_region_filter_uses_world_when_no_regional_match(self): + names = self._names_in(self._region_pack(regions=["oceania"])) + self.assertIn("rgn_world.bin", names) + for expected in ("rgn_us.bin", "rgn_jp.bin", "rgn_eu.bin"): + self.assertNotIn(expected, names) + + def test_region_filter_keeps_untagged_and_world(self): + names = self._names_in(self._region_pack(regions=["north-america"])) + self.assertIn("rgn_plain.bin", names) + self.assertIn("rgn_world.bin", names) + + def test_region_tag_in_pack_name(self): + out = self._region_pack(regions=["north-america", "japan"]) + self.assertIn("NorthAmerica_Japan", os.path.basename(out)) + + def test_no_region_argument_changes_nothing(self): + names = self._names_in(self._region_pack()) + for expected in ( + "rgn_us.bin", + "rgn_jp.bin", + "rgn_eu.bin", + "rgn_plain.bin", + "rgn_world.bin", + ): + self.assertIn(expected, names) + + def test_region_composes_with_required_only(self): + out = self._region_pack(regions=["north-america"], required_only=True) + names = self._names_in(out) + self.assertIn("rgn_us.bin", names) + self.assertNotIn("rgn_jp.bin", names) + self.assertNotIn("rgn_eu.bin", names) + self.assertIn("NorthAmerica", os.path.basename(out)) + self.assertIn("Required", os.path.basename(out)) + + def test_region_composes_with_source_platform(self): + names = self._names_in( + self._region_pack(regions=["north-america"], source="platform") + ) + self.assertIn("rgn_us.bin", names) + self.assertNotIn("rgn_jp.bin", names) + self.assertNotIn("rgn_eu.bin", names) + self.assertIn("rgn_world.bin", names) + self.assertIn("rgn_plain.bin", names) + + def test_region_composes_with_split(self): + from packs.platformpack import generate_split_packs + + self._create_region_fixtures() + paths = generate_split_packs( + "regionplat", + self.platforms_dir, + self.db, + self.bios_dir, + self.root, + emu_profiles=self._region_profiles(), + regions=["north-america"], + offline=True, + ) + self.assertTrue(paths) + for p in paths: + self.assertIn("NorthAmerica", os.path.basename(p)) + names = self._names_in(p) + self.assertNotIn("rgn_jp.bin", names) + self.assertNotIn("rgn_eu.bin", names) + + def test_region_composes_with_split_and_target(self): + from packs.platformpack import generate_split_packs + + self._create_region_fixtures() + paths = generate_split_packs( + "regionplat", + self.platforms_dir, + self.db, + self.bios_dir, + self.root, + emu_profiles=self._region_profiles(), + target_cores={"rgncore"}, + regions=["north-america"], + ) + self.assertTrue(paths) + for p in paths: + self.assertIn("NorthAmerica", os.path.basename(p)) + names = self._names_in(p) + self.assertNotIn("rgn_jp.bin", names) + self.assertNotIn("rgn_eu.bin", names) + self.assertTrue( + any("rgn_us.bin" in self._names_in(p) for p in paths), + "target filtering removed the whole system", + ) + + def test_region_composes_with_manifest(self): + from packs.manifest import generate_manifest + + self._create_region_fixtures() + registry_path = os.path.join(self.platforms_dir, "_registry.yml") + if not os.path.exists(registry_path): + with open(registry_path, "w", encoding="utf-8") as fh: + yaml.safe_dump({"platforms": {}}, fh) + manifest = generate_manifest( + "regionplat", + self.platforms_dir, + self.db, + self.bios_dir, + registry_path, + emu_profiles=self._region_profiles(), + regions=["north-america"], + ) + packed = {os.path.basename(f["dest"]) for f in manifest["files"]} + self.assertEqual(manifest["regions"], ["north-america"]) + self.assertIn("rgn_us.bin", packed) + self.assertNotIn("rgn_jp.bin", packed) + self.assertNotIn("rgn_eu.bin", packed) + + def test_manifest_without_region_keeps_every_variant(self): + from packs.manifest import generate_manifest + + self._create_region_fixtures() + registry_path = os.path.join(self.platforms_dir, "_registry.yml") + if not os.path.exists(registry_path): + with open(registry_path, "w", encoding="utf-8") as fh: + yaml.safe_dump({"platforms": {}}, fh) + manifest = generate_manifest( + "regionplat", + self.platforms_dir, + self.db, + self.bios_dir, + registry_path, + emu_profiles=self._region_profiles(), + offline=True, + ) + packed = {os.path.basename(f["dest"]) for f in manifest["files"]} + for expected in ("rgn_us.bin", "rgn_jp.bin", "rgn_eu.bin"): + self.assertIn(expected, packed) + + def test_region_composes_with_system_pack(self): + from packs.emulatorpack import generate_system_pack + + self._create_region_fixtures() + os.makedirs(self.emulators_dir, exist_ok=True) + with open( + os.path.join(self.emulators_dir, "rgncore.yml"), "w", encoding="utf-8" + ) as fh: + yaml.safe_dump(self._region_profiles()["rgncore"], fh) + out = generate_system_pack( + ["region-console"], + self.emulators_dir, + self.db, + self.bios_dir, + self.root, + regions=["north-america"], + ) + self.assertIsNotNone(out) + self.assertIn("NorthAmerica", os.path.basename(out)) + names = self._names_in(out) + self.assertIn("rgn_us.bin", names) + self.assertNotIn("rgn_jp.bin", names) + + def test_verify_platform_region_matches_the_pack(self): + from model.platforms import load_platform_config + from packs.coverage import verify_platform + + self._create_region_fixtures() + profiles = self._region_profiles() + config = load_platform_config("regionplat", self.platforms_dir) + + full = verify_platform(config, self.db, self.emulators_dir, profiles) + filtered = verify_platform( + config, + self.db, + self.emulators_dir, + profiles, + regions=["north-america"], + ) + checked = {d["name"] for d in filtered["details"]} + self.assertIn("rgn_us.bin", checked) + self.assertNotIn("rgn_jp.bin", checked) + self.assertNotIn("rgn_eu.bin", checked) + self.assertLess(len(filtered["details"]), len(full["details"])) + + packed = self._names_in(self._region_pack(regions=["north-america"])) + self.assertTrue(checked.issubset(packed), checked - packed) + + def test_verify_emulator_region_matches_the_pack(self): + from packs.emulatorpack import generate_emulator_pack + from packs.emulatorcheck import verify_emulator + + self._create_region_fixtures() + with open( + os.path.join(self.emulators_dir, "rgncore.yml"), "w", encoding="utf-8" + ) as fh: + yaml.safe_dump(self._region_profiles()["rgncore"], fh) + + full = verify_emulator(["rgncore"], self.emulators_dir, self.db) + filtered = verify_emulator( + ["rgncore"], self.emulators_dir, self.db, regions=["north-america"] + ) + checked = {d["name"] for d in filtered["details"]} + self.assertIn("rgn_us.bin", checked) + self.assertNotIn("rgn_jp.bin", checked) + self.assertLess(len(filtered["details"]), len(full["details"])) + + out = generate_emulator_pack( + ["rgncore"], + self.emulators_dir, + self.db, + self.bios_dir, + self.root, + regions=["north-america"], + ) + self.assertTrue(checked.issubset(self._names_in(out))) + + def test_every_narrowing_names_itself_and_says_so(self): + """A dimension that removes files must show in the pack name and in the + README. Both are built from pack_narrowings, so this holds for any new one.""" + from packs.readme import build_readme + from packs.naming import pack_narrowings + + dimensions = [ + {"source": "platform"}, + {"source": "truth"}, + {"regions": ["north-america"]}, + {"target_name": "switch"}, + {"one_per_slot": True}, + {"required_only": True}, + {"no_game_data": True}, + ] + for kwargs in dimensions: + applied = pack_narrowings( + kwargs.get("source", "full"), + kwargs.get("regions"), + kwargs.get("target_name"), + kwargs.get("one_per_slot", False), + kwargs.get("required_only", False), + no_game_data=kwargs.get("no_game_data", False), + ) + self.assertEqual(len(applied), 1, kwargs) + tag, label = applied[0] + self.assertTrue(tag.startswith("_") and len(tag) > 1, kwargs) + self.assertTrue(label.strip(), kwargs) + readme = build_readme("p", "P", "", 1, 1, narrowings=applied) + self.assertIn("PACK TYPE: Narrowed", readme) + self.assertIn(label, readme) + + def test_no_mode_swallows_a_narrowing_flag(self): + """Every mode either honours a narrowing flag or refuses it. + + Silently ignoring one is how --manifest-targets accepted --region and + wrote seven unfiltered manifests, and how --manifest accepted + --one-per-slot. A mode that cannot apply a flag must say so. + """ + import subprocess + + repo = os.path.join(os.path.dirname(__file__), "..") + matrix = [ + (["--manifest-targets"], ["--region", "us"], "refuse"), + (["--manifest-targets"], ["--one-per-slot"], "refuse"), + (["--platform", "retroarch", "--manifest"], ["--one-per-slot"], "refuse"), + (["--emulator", "duckstation"], ["--one-per-slot"], "refuse"), + (["--system", "sony-playstation"], ["--one-per-slot"], "refuse"), + (["--platform", "retroarch", "--system", "sony-playstation"], + ["--one-per-slot"], "refuse"), + (["--platform", "retroarch", "--from-md5", "d8f1"], ["--region", "us"], + "refuse"), + (["--platform", "retroarch", "--from-md5", "d8f1"], ["--one-per-slot"], + "refuse"), + # --verify-packs returns before the argument checks run, so it + # used to accept these and answer about the pack sitting in the + # output directory. --target is honoured instead of refused: the + # check narrows by it. + (["--platform", "retroarch", "--verify-packs"], ["--one-per-slot"], + "refuse"), + (["--platform", "retroarch", "--verify-packs"], ["--required-only"], + "refuse"), + (["--platform", "retroarch", "--verify-packs"], ["--source", "truth"], + "refuse"), + # Modes that read none of these: the flag reached the filename or + # nothing at all, never the selection. + (["--emulator", "duckstation"], ["--source", "truth"], "refuse"), + (["--system", "sony-playstation"], ["--source", "truth"], "refuse"), + (["--manifest-targets"], ["--target", "switch"], "refuse"), + (["--manifest-targets"], ["--required-only"], "refuse"), + (["--manifest-targets"], ["--source", "truth"], "refuse"), + (["--platform", "retroarch", "--from-md5", "d8f1"], + ["--target", "switch"], "refuse"), + (["--platform", "retroarch", "--from-md5", "d8f1"], + ["--required-only"], "refuse"), + (["--platform", "retroarch", "--from-md5", "d8f1"], + ["--source", "truth"], "refuse"), + (["--platform", "retroarch", "--manifest"], + ["--system", "sony-playstation"], "refuse"), + (["--platform", "retroarch", "--split"], + ["--system", "sony-playstation"], "refuse"), + # --all took the same filter and wrote twelve complete manifests. + (["--all", "--manifest"], ["--system", "sony-playstation"], "refuse"), + (["--all", "--split"], ["--system", "sony-playstation"], "refuse"), + # A pack built with --system is named after its systems, but the check + # looked for the full pack instead. + (["--platform", "retroarch", "--verify-packs"], + ["--system", "sony-playstation"], "refuse"), + # --all-variants builds its own six combinations: it overrode these + # and the single-pack modes never read it at all. + (["--platform", "retroarch", "--all-variants"], ["--source", "truth"], + "refuse"), + (["--platform", "retroarch", "--all-variants"], ["--required-only"], + "refuse"), + # The default value typed out is still the flag: compared with its + # default, `--source full` and `--group-by system` went through. + (["--platform", "retroarch", "--all-variants"], ["--source", "full"], + "refuse"), + (["--manifest-targets"], ["--source", "full"], "refuse"), + (["--emulator", "handy"], ["--source", "full"], "refuse"), + (["--platform", "retroarch", "--from-md5", "d8f1"], + ["--source", "full"], "refuse"), + (["--platform", "retroarch", "--offline"], ["--group-by", "system"], + "refuse"), + (["--platform", "retroarch", "--verify-packs"], ["--group-by", "system"], + "refuse"), + (["--emulator", "duckstation"], ["--all-variants"], "refuse"), + (["--system", "sony-playstation"], ["--all-variants"], "refuse"), + (["--emulator", "duckstation", "--verify-packs"], ["--all-variants"], + "refuse"), + (["--all", "--manifest", "--all-variants"], ["--verify-packs"], + "refuse"), + (["--all", "--all-variants", "--verify-packs"], ["--one-per-slot"], + "refuse"), + (["--all", "--all-variants", "--verify-packs"], ["--split"], + "refuse"), + # Every flag a quick mode does not read, from one table. + (["--platform", "retroarch", "--verify-packs"], ["--split"], "refuse"), + (["--platform", "retroarch", "--verify-packs"], ["--manifest"], "refuse"), + (["--platform", "retroarch", "--verify-packs"], ["--emulator", "handy"], + "refuse"), + (["--manifest-targets"], ["--platform", "batocera"], "refuse"), + (["--manifest-targets"], ["--system", "sony-playstation"], "refuse"), + (["--manifest-targets"], ["--all"], "refuse"), + (["--platform", "retroarch", "--from-md5", "d8f1"], ["--manifest"], + "refuse"), + (["--list-systems"], ["--region", "us"], "refuse"), + (["--list-emulators"], ["--target", "switch"], "refuse"), + # Only the platform path refreshes data directories. + (["--emulator", "dolphin"], ["--refresh-data"], "refuse"), + (["--system", "sony-playstation"], ["--refresh-data"], "refuse"), + (["--from-md5", "d8f1"], ["--refresh-data"], "refuse"), + (["--platform", "retroarch", "--offline"], ["--refresh-data"], "refuse"), + (["--emulator", "dolphin"], ["--no-refresh-data"], "refuse"), + (["--system", "sony-playstation"], ["--no-refresh-data"], "refuse"), + (["--platform", "retroarch", "--offline"], ["--no-refresh-data"], "refuse"), + (["--platform", "retroarch", "--refresh-data"], ["--no-refresh-data"], + "refuse"), + # Documented as adding core files, read by nothing. + (["--emulator", "handy"], ["--include-extras"], "refuse"), + (["--system", "atari-lynx"], ["--include-extras"], "refuse"), + # Game data is categorized against a platform's list and the + # cores it runs: the modes without a platform refuse it, and + # --all-variants builds its own fixed set. + (["--emulator", "handy"], ["--no-game-data"], "refuse"), + (["--system", "atari-lynx"], ["--no-game-data"], "refuse"), + (["--platform", "retroarch", "--from-md5", "d8f1"], ["--no-game-data"], + "refuse"), + (["--from-md5", "d8f1"], ["--no-game-data"], "refuse"), + (["--manifest-targets"], ["--no-game-data"], "refuse"), + (["--platform", "retroarch", "--all-variants"], ["--no-game-data"], + "refuse"), + (["--list-systems"], ["--no-game-data"], "refuse"), + (["--list"], ["--no-game-data"], "refuse"), + # --counts records the full platform packs the pipeline compares + # with verify: a mode that builds none refuses it. + (["--emulator", "handy"], ["--counts", "counts.json"], "refuse"), + (["--platform", "retroarch", "--manifest"], ["--counts", "counts.json"], "refuse"), + (["--platform", "retroarch", "--split"], ["--counts", "counts.json"], "refuse"), + (["--platform", "retroarch", "--system", "sony-playstation"], + ["--counts", "counts.json"], "refuse"), + (["--platform", "retroarch", "--from-md5", "d8f1"], ["--counts", "counts.json"], + "refuse"), + (["--platform", "retroarch", "--verify-packs"], ["--counts", "counts.json"], + "refuse"), + (["--list"], ["--counts", "counts.json"], "refuse"), + ] + for mode, flag, expected in matrix: + with self.subTest(mode=mode, flag=flag): + self.assertEqual(expected, "refuse") + result = subprocess.run( + [sys.executable, "scripts/generate_pack.py", *mode, *flag, + "--output-dir", os.path.join(self.root, "modecheck")], + capture_output=True, text=True, cwd=repo, timeout=120, + check=False, + ) + combined = result.stdout + result.stderr + self.assertNotEqual( + result.returncode, 0, + f"{' '.join(mode + flag)} was accepted and ignored:\n{combined}", + ) + self.assertIn("error:", combined) + # The refusal names a flag the command carries: "requires + # --platform or --all" answered --platform --system + # --one-per-slot, and the user could not tell what to drop. + message = combined[combined.index("error:"):].splitlines()[0] + passed = [arg for arg in mode + flag if arg.startswith("--")] + self.assertTrue( + any(arg in message for arg in passed), + f"{' '.join(mode + flag)}: {message}", + ) + demanded = message.partition(" requires ")[2].replace(",", " ").split() + self.assertFalse( + [arg for arg in passed if arg in demanded], + f"{' '.join(mode + flag)} asks for a flag it was given: {message}", + ) + + def test_conformance_narrows_by_target_like_it_does_by_region(self): + """A targeted pack is checked against the targeted expectation. + + --target narrowed the build and nothing else: the conformance stage + held every targeted pack to the platform's whole system list and + core set, so a correct build exited non-zero on hundreds of files it + was never asked to carry. Region was already passed to the check, and + target has to travel the same way, which is why the pack is checked + as a full pack. + """ + import inspect + + from packs import platformcheck + from packs.naming import pack_narrowings, pack_variant + + source = inspect.getsource(platformcheck.verify_pack_against_platform) + self.assertIn( + "target_cores", + inspect.signature(platformcheck.verify_pack_against_platform).parameters, + "the pack verifier takes no target, so it cannot narrow by one", + ) + self.assertIn( + "platform_scope_systems(config, emu_profiles, target_cores)", + source, + "the baseline expectation is not narrowed by the target, as the pack and verify narrow it", + ) + self.assertIn( + "target_cores=target_cores", + source, + "the core-extras expectation is not narrowed by the target", + ) + + # And the pack must not be skipped instead: skipping checks nothing. + for target in ("nintendo-switch", "switch", "rpi4"): + tag = pack_narrowings("full", None, target, False, False)[0][0] + self.assertEqual( + pack_variant(f"Platform_1.0{tag}_BIOS_Pack.zip"), ("full", False), + f"a pack built for {target} would be checked as a narrowed variant", + ) + + def test_standalone_mode_names_itself(self): + """--emulator --standalone ships a different file set, and without a tag it + overwrote the pack built without it.""" + from packs.naming import pack_narrowings + + applied = pack_narrowings("full", None, None, False, False, standalone=True) + self.assertEqual([tag for tag, _l in applied], ["_Standalone"]) + + def test_every_name_builder_uses_the_same_list(self): + """Four places name a pack or a manifest. None may assemble tags by + hand: that is how --one-per-slot reached --split unnamed.""" + source = script_source("generate_pack.py") + for hand_rolled in ( + 'req_tag = "_Required"', + 'source_tag = {"platform": "_Platform"', + 'req_suffix = "_required"', + 'slot_tag = "_OnePerSlot"', + # The --system rename kept the region tag alone, the custom pack + # took no tag at all, and the skip list retyped four of them. + '_Custom_BIOS_Pack.zip"', + '{rgn_tag}_BIOS_Pack.zip"', + '("_Platform_", "_Truth_"', + ): + self.assertNotIn(hand_rolled, source, hand_rolled) + self.assertGreaterEqual(source.count("pack_narrowings("), 8) + + def test_a_narrowed_system_pack_does_not_take_the_full_name(self): + """Every dimension has to show in the filename or two builds collide. + + --system X --required-only produced the same name as --system X and + overwrote it, because the rename kept only the region tag. + """ + import subprocess + + repo = os.path.join(os.path.dirname(__file__), "..") + names = {} + for label, extra in (("full", []), ("required", ["--required-only"])): + out = os.path.join(self.root, f"sysname_{label}") + proc = subprocess.run( + [sys.executable, "scripts/generate_pack.py", "--system", + "atari-lynx", "--offline", *extra, "--output-dir", out], + capture_output=True, text=True, cwd=repo, timeout=300, + check=False, + ) + self.assertEqual(proc.returncode, 0, proc.stdout + proc.stderr) + names[label] = sorted( + f for f in os.listdir(out) if f.endswith("_BIOS_Pack.zip") + ) + self.assertTrue(names["full"] and names["required"]) + self.assertNotEqual( + names["full"], names["required"], + "a required-only system pack took the name of the full one", + ) + + def test_a_platform_without_cores_has_no_truth_pack(self): + """MiSTer declares cores: []: its truth pack held nothing, passed + its check and exited 0 under a name claiming a content.""" + import subprocess + + repo = os.path.join(os.path.dirname(__file__), "..") + out = os.path.join(self.root, "truth_empty") + proc = subprocess.run( + [sys.executable, "scripts/generate_pack.py", "--platform", "misterfpga", + "--offline", "--source", "truth", "--output-dir", out], + capture_output=True, text=True, cwd=repo, timeout=300, + check=False, + ) + self.assertNotEqual(proc.returncode, 0) + self.assertIn("a truth pack would hold nothing", proc.stderr) + self.assertFalse( + [f for f in os.listdir(out) if f.endswith(".zip")] if os.path.isdir(out) else [] + ) + + def test_an_emulator_needing_no_file_succeeds_like_verify(self): + """Handy requires no file. --required-only removed the empty ZIP, + printed its path and exited 1, while verify reported 0/0 OK.""" + import subprocess + + repo = os.path.join(os.path.dirname(__file__), "..") + out = os.path.join(self.root, "no_file_needed") + proc = subprocess.run( + [sys.executable, "scripts/generate_pack.py", "--emulator", "handy", + "--required-only", "--offline", "--output-dir", out], + capture_output=True, text=True, cwd=repo, timeout=300, + check=False, + ) + self.assertEqual(proc.returncode, 0, proc.stdout + proc.stderr) + self.assertIn("no file needed, no pack written", proc.stdout) + self.assertNotIn(".zip", proc.stdout) + verify = subprocess.run( + [sys.executable, "scripts/verify.py", "--emulator", "handy", "--required-only"], + capture_output=True, text=True, cwd=repo, timeout=300, + check=False, + ) + self.assertEqual(verify.returncode, proc.returncode) + + def test_a_platform_without_cores_refuses_profile_narrowings(self): + """MiSTer and BizHawk declare cores: []. --region, --one-per-slot + and --no-game-data read the profiles, so their packs withdrew + nothing under a name and README that said otherwise.""" + import subprocess + + repo = os.path.join(os.path.dirname(__file__), "..") + out = os.path.join(self.root, "blind") + runs = [ + ["scripts/generate_pack.py", "--platform", "misterfpga", "--region", "us"], + ["scripts/generate_pack.py", "--platform", "misterfpga", "--one-per-slot"], + ["scripts/generate_pack.py", "--platform", "misterfpga", "--no-game-data"], + ["scripts/generate_pack.py", "--platform", "bizhawk", "--manifest", + "--region", "us"], + ["scripts/verify.py", "--platform", "bizhawk", "--region", "us"], + ] + for argv in runs: + extra = ["--offline", "--output-dir", out] if "generate_pack" in argv[0] else [] + with self.subTest(argv=argv): + proc = subprocess.run( + [sys.executable, *argv, *extra], + capture_output=True, text=True, cwd=repo, timeout=300, + check=False, + ) + self.assertEqual(proc.returncode, 1, proc.stdout + proc.stderr) + self.assertIn("runs no core a profile describes", proc.stderr) + self.assertFalse(os.listdir(out) if os.path.isdir(out) else []) + + def test_a_full_pack_is_not_announced_as_narrowed(self): + from packs.readme import build_readme + from packs.naming import pack_narrowings + + self.assertEqual(pack_narrowings("full", None, None, False, False), []) + self.assertNotIn( + "PACK TYPE: Narrowed", build_readme("p", "P", "", 1, 1) + ) + + def test_system_filter_is_announced_too(self): + from packs.readme import build_readme + + readme = build_readme( + "p", "P", "", 1, 1, system_filter=["sony-playstation"] + ) + self.assertIn("PACK TYPE: Narrowed", readme) + self.assertIn("sony-playstation", readme) + + def test_extras_group_under_their_system_not_a_shared_bucket(self): + """A core extra competes in its system's group: the chain from the + gap report (system, systems) to platform_region_groups, not a + dictionary built by hand. Without it every extra stood alone and + --region compared nothing.""" + import hashlib + + from packs.extraregions import platform_region_groups + + files, by_name = {}, {} + for name in ("core_us.bin", "core_jp.bin"): + payload = name.encode() + path = os.path.join(self.bios_dir, name) + with open(path, "wb") as handle: + handle.write(payload) + sha1 = hashlib.sha1(payload).hexdigest() + files[sha1] = {"path": path, "name": name, "size": len(payload), + "md5": hashlib.md5(payload).hexdigest()} + by_name[name] = [sha1] + db = {"files": files, "indexes": {"by_name": by_name, "by_md5": {}, + "by_crc32": {}, "by_path_suffix": {}}} + profiles = {"psxcore": { + "emulator": "PSX Core (Display Name)", "type": "libretro", + "systems": ["sony-playstation"], + "files": [{"name": "core_us.bin", "region": ["north-america"]}, + {"name": "core_jp.bin", "region": ["japan"]}], + }} + config = {"platform": "P", "cores": ["psxcore"], "base_destination": "system", + "systems": {"sony-playstation": {"files": [ + {"name": "declared.bin", "destination": "declared.bin"}]}}} + groups, _ = platform_region_groups( + config, config["systems"], self.emulators_dir, db, "system", profiles, + ) + self.assertEqual( + sorted(groups["sony-playstation"]), + [("core_jp.bin", "core_jp.bin"), ("core_us.bin", "core_us.bin"), + ("declared.bin", "declared.bin")], + ) + + def test_a_system_spelled_two_ways_is_one_group(self): + """RetroDECK files the Master System as sega-master-system, the + profiles as sega-mastersystem. Two groups reduced apart, and a + --region us pack kept the declared Japanese BIOS.""" + import hashlib + + from packs.extraregions import platform_region_groups + + files, by_name = {}, {} + for name in ("bios_U.sms", "bios_J.sms"): + payload = name.encode() + path = os.path.join(self.bios_dir, name) + with open(path, "wb") as handle: + handle.write(payload) + sha1 = hashlib.sha1(payload).hexdigest() + files[sha1] = {"path": path, "name": name, "size": len(payload), + "md5": hashlib.md5(payload).hexdigest()} + by_name[name] = [sha1] + db = {"files": files, "indexes": {"by_name": by_name, "by_md5": {}, + "by_crc32": {}, "by_path_suffix": {}}} + profiles = {"smscore": { + "emulator": "SMS Core", "type": "libretro", + "systems": ["sega-mastersystem"], + "files": [{"name": "bios_U.sms", "region": ["north-america"]}, + {"name": "bios_J.sms", "region": ["japan"]}], + }} + config = {"platform": "P", "cores": ["smscore"], "base_destination": "system", + "systems": {"sega-master-system": {"files": [ + {"name": "bios_J.sms", "destination": "bios/bios_J.sms"}]}}} + groups, _ = platform_region_groups( + config, config["systems"], self.emulators_dir, db, "system", profiles, + ) + self.assertNotIn("sega-mastersystem", groups) + self.assertEqual( + sorted(dest for dest, _ in groups["sega-master-system"]), + ["bios/bios_J.sms", "bios_J.sms", "bios_U.sms"], + ) + + def test_slot_narrowed_pack_gets_its_own_name(self): + names = { + os.path.basename(self._region_pack()), + os.path.basename(self._region_pack(one_per_slot=True)), + } + self.assertEqual(len(names), 2, names) + self.assertTrue(any("OnePerSlot" in n for n in names)) + + def test_verify_pack_return_matches_its_annotation(self): + import inspect + import typing + + from packs.platformpack import generate_pack + from packs.platformcheck import verify_pack_against_platform + + self._create_region_fixtures() + profiles = self._region_profiles() + out = generate_pack( + "regionplat", + self.platforms_dir, + self.db, + self.bios_dir, + self.root, + emu_profiles=profiles, + ) + result = verify_pack_against_platform( + out, "regionplat", self.platforms_dir, db=self.db, emu_profiles=profiles + ) + annotated = typing.get_args( + inspect.signature( + verify_pack_against_platform, eval_str=True + ).return_annotation + ) + self.assertEqual(len(result), len(annotated)) + + def test_narrowed_variants_are_checked_as_built(self): + from packs.naming import pack_variant + + for narrowed, variant in ( + ("EmuDeck_2.3.8_Required_BIOS_Pack.zip", ("full", True)), + ("EmuDeck_2.3.8_Platform_BIOS_Pack.zip", ("platform", False)), + ("EmuDeck_2.3.8_Truth_Required_BIOS_Pack.zip", ("truth", True)), + ("EmuDeck_2.3.8_NorthAmerica_Required_BIOS_Pack.zip", ("full", True)), + ): + self.assertEqual(pack_variant(narrowed), variant, narrowed) + + for full in ( + "EmuDeck_2.3.8_BIOS_Pack.zip", + "EmuDeck_2.3.8_NorthAmerica_BIOS_Pack.zip", + "RetroArch_v1.22.2_Switch_BIOS_Pack.zip", + ): + self.assertEqual(pack_variant(full), ("full", False), full) + + def test_target_tag_formats_hardware_names(self): + from packs.naming import _target_tag + + self.assertEqual(_target_tag("switch"), "Switch") + self.assertEqual(_target_tag("rpi4"), "Rpi4") + self.assertEqual(_target_tag("x86_64"), "X86 64".replace(" ", "")) + + def test_targeted_pack_does_not_overwrite_the_full_one(self): + names = { + os.path.basename(self._region_pack()), + os.path.basename(self._region_pack(target_name="switch")), + } + self.assertEqual(len(names), 2, names) + self.assertTrue(any("Switch" in n for n in names)) + + def test_target_and_region_tags_compose_in_the_name(self): + name = os.path.basename( + self._region_pack(regions=["north-america"], target_name="switch") + ) + self.assertIn("NorthAmerica", name) + self.assertIn("Switch", name) + + def test_readme_region_section_lists_fallback_systems(self): + from packs.readme import build_readme + + text = build_readme( + "regionplat", + "RegionPlat", + "", + 10, + 2, + regions=["north-america"], + fallback_systems=["nintendo-fds"], + ) + self.assertIn("PACK TYPE: Region Filtered", text) + self.assertIn("Region priority: North America", text) + self.assertIn("nintendo-fds", text) + self.assertIn("This pack was filtered", text) + self.assertNotIn("All are included", text) + + def test_readme_without_region_keeps_the_regional_note(self): + from packs.readme import build_readme + + text = build_readme("regionplat", "RegionPlat", "", 10, 2) + self.assertNotIn("PACK TYPE: Region Filtered", text) + self.assertIn("All are included", text) + + def test_verify_agrees_with_region_filtered_pack(self): + from packs.platformcheck import verify_pack_against_platform + + out = self._region_pack(regions=["north-america"]) + result = verify_pack_against_platform( + out, + "regionplat", + self.platforms_dir, + db=self.db, + emu_profiles=self._region_profiles(), + regions=["north-america"], + ) + ok, _checked, _present, errors = result[:4] + self.assertTrue(ok, errors) + + def test_verify_reports_the_gap_without_the_region_filter(self): + from packs.platformcheck import verify_pack_against_platform + + out = self._region_pack(regions=["north-america"]) + result = verify_pack_against_platform( + out, + "regionplat", + self.platforms_dir, + db=self.db, + emu_profiles=self._region_profiles(), + ) + ok, _checked, _present, errors = result[:4] + self.assertFalse(ok) + self.assertTrue(any("rgn_jp.bin" in e for e in errors), errors) + + def test_region_composes_with_source_truth(self): + names = self._names_in( + self._region_pack(regions=["north-america"], source="truth") + ) + self.assertIn("rgn_us.bin", names) + self.assertNotIn("rgn_jp.bin", names) + + +class TestE2EGapAnalysis(E2EFixture): + """Gap analysis resolves files the pack can already ship.""" + + # ---- gap analysis resolves files the pack can already ship ---- + + @staticmethod + def _gap_db(repo_name: str, sha1: str, crc32: str) -> dict: + return { + "files": {sha1: {"path": f"bios/{repo_name}", "size": 8192, "crc32": crc32}}, + "indexes": { + "by_name": {repo_name: [sha1]}, + "by_md5": {}, + "by_crc32": {crc32: sha1}, + "by_sha256": {}, + "by_path_suffix": {}, + }, + } + + def _gap_source(self, entry: dict, db: dict) -> str: + from packs.crossref import cross_reference + + report = cross_reference( + {"gapemu": {"emulator": "GapEmu", "systems": ["s"], "files": [entry]}}, + {"s": set()}, + db, + ) + return report["gapemu"]["gap_details"][0]["source"] + + def test_gap_analysis_resolves_by_alias(self): + """A file stored under an alias is in the repo, not a sourcing target.""" + db = self._gap_db("REPO_chip.rom", "a" * 40, "465c4e1c") + entry = {"name": "chip.rom", "aliases": ["REPO_chip.rom"], "required": True} + self.assertEqual(self._gap_source(entry, db), "bios") + + def test_gap_analysis_resolves_by_crc32(self): + """crc32 is the only hash some emulators declare.""" + db = self._gap_db("REPO_chip.rom", "a" * 40, "465c4e1c") + entry = {"name": "chip.rom", "crc32": "465c4e1c", "required": True} + self.assertEqual(self._gap_source(entry, db), "bios") + + def test_gap_analysis_reports_unknown_file_missing(self): + db = self._gap_db("REPO_chip.rom", "a" * 40, "465c4e1c") + entry = {"name": "chip.rom", "aliases": ["OTHER.rom"], "crc32": "deadbeef"} + self.assertEqual(self._gap_source(entry, db), "missing") + + def test_gap_analysis_resolves_renamed_mame_set(self): + """A renamed set is held under the name dedup kept, as verify reads it.""" + from model import database + + db = self._gap_db("v4bios.zip", "a" * 40, "465c4e1c") + original = database.get_mame_clone_map + database.get_mame_clone_map = lambda *_a: {"bctvidbs.zip": "v4bios.zip"} + try: + entry = {"name": "bctvidbs.zip", "required": True} + self.assertEqual(self._gap_source(entry, db), "bios") + finally: + database.get_mame_clone_map = original + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_e2e_resolution.py b/tests/test_e2e_resolution.py new file mode 100644 index 000000000..4d49603dd --- /dev/null +++ b/tests/test_e2e_resolution.py @@ -0,0 +1,729 @@ +"""End-to-end resolution, platform verification, cross-reference and validation checks.""" + +from __future__ import annotations + +import tests +import hashlib +import os +import tempfile +import unittest +from pathlib import Path +import yaml +from core.ziptools import build_zip_contents_index, check_inside_zip +from core.hashing import md5_composite +from resolve.grouping import group_identical_platforms +from model.profiles import load_emulator_profiles +from model.platforms import load_platform_config +from resolve.localfile import resolve_local_file +from resolve.cores import resolve_platform_cores +from resolve.validation import build_validation_index, check_file_validation +from packs.verdicts import Severity, Status +from packs.gaps import find_exclusion_notes, find_undeclared_files +from packs.coverage import verify_platform +from tests.e2esupport import E2EFixture + + +class TestE2EResolution(E2EFixture): + """Resolution, zip checks, platform verification, grouping and core resolution.""" + + def test_01_resolve_sha1(self): + entry = { + "name": "present_req.bin", + "sha1": self.files["present_req.bin"]["sha1"], + } + path, status = resolve_local_file(entry, self.db) + self.assertEqual(status, "sha1_exact") + self.assertIn("present_req.bin", path) + + def test_02_resolve_md5(self): + entry = { + "name": "correct_hash.bin", + "md5": self.files["correct_hash.bin"]["md5"], + } + path, status = resolve_local_file(entry, self.db) + self.assertEqual(status, "md5_exact") + + def test_03_resolve_name_no_md5(self): + entry = {"name": "no_md5.bin"} + path, status = resolve_local_file(entry, self.db) + self.assertEqual(status, "name_exact") + + def test_04_resolve_alias(self): + entry = {"name": "alias_alt.bin", "aliases": []} + path, status = resolve_local_file(entry, self.db) + self.assertEqual(status, "name_exact") + self.assertIn("alias_target.bin", path) + + def test_05_resolve_truncated_md5(self): + truncated = self.files["truncated.bin"]["md5"][:29] + entry = {"name": "truncated.bin", "md5": truncated} + path, status = resolve_local_file(entry, self.db) + self.assertEqual(status, "md5_exact") + + def test_06_resolve_not_found(self): + entry = {"name": "nonexistent.bin", "sha1": "0" * 40} + path, status = resolve_local_file(entry, self.db) + self.assertIsNone(path) + self.assertEqual(status, "not_found") + + def test_07_resolve_hash_mismatch(self): + entry = {"name": "wrong_hash.bin", "md5": "ffffffffffffffffffffffffffffffff"} + path, status = resolve_local_file(entry, self.db) + self.assertEqual(status, "hash_mismatch") + + def test_07b_resolve_unsourceable_ignores_homonym(self): + """An unsourceable entry takes content, never a file of the same name.""" + entry = { + "name": "wrong_hash.bin", + "md5": "ffffffffffffffffffffffffffffffff", + "unsourceable": "ships inside a paid application package", + } + path, status = resolve_local_file(entry, self.db) + self.assertIsNone(path) + self.assertEqual(status, "not_found") + + entry = {"name": "no_md5.bin", "unsourceable": "written per title"} + path, status = resolve_local_file(entry, self.db) + self.assertIsNone(path) + self.assertEqual(status, "not_found") + + # Collecting the real bytes still resolves it. + entry = { + "name": "present_req.bin", + "sha1": self.files["present_req.bin"]["sha1"], + "unsourceable": "ships inside a paid application package", + } + path, status = resolve_local_file(entry, self.db) + self.assertEqual(status, "sha1_exact") + self.assertIn("present_req.bin", path) + + def test_08_resolve_variants_deprioritized(self): + entry = {"name": "present_req.bin"} + path, status = resolve_local_file(entry, self.db) + self.assertNotIn(".variants", path) + + def test_09_resolve_zip_contents(self): + zc = build_zip_contents_index(self.db, Path(self.root)) + inner_md5 = self.files["good.zip"]["inner_md5s"]["inner.rom"] + entry = {"name": "good.zip", "md5": inner_md5, "zipped_file": "inner.rom"} + path, status = resolve_local_file(entry, self.db, zc) + # Should find via name match (hash_mismatch since container md5 != inner md5) + # then zip_contents would be fallback + self.assertIsNotNone(path) + + def test_10_md5_composite(self): + expected = hashlib.md5(b"AAAA" + b"BBBB").hexdigest() + actual = md5_composite(self.files["composite.zip"]["path"]) + self.assertEqual(actual, expected) + + def test_11_check_inside_zip_match(self): + inner_md5 = self.files["good.zip"]["inner_md5s"]["inner.rom"] + r = check_inside_zip(self.files["good.zip"]["path"], "inner.rom", inner_md5) + self.assertEqual(r, "ok") + + def test_12_check_inside_zip_mismatch(self): + r = check_inside_zip(self.files["bad_inner.zip"]["path"], "inner.rom", "wrong") + self.assertEqual(r, "untested") + + def test_20b_agnostic_core_fills_existence_slots(self): + """An agnostic core on the platform serves a missing slot, as the pack does.""" + config = load_platform_config("test_existence", self.platforms_dir) + result = verify_platform(config, self.db, self.emulators_dir) + c = result["severity_counts"] + self.assertEqual(c[Severity.OK], result["total_files"]) + + def test_13_check_inside_zip_not_found(self): + r = check_inside_zip(self.files["missing_inner.zip"]["path"], "nope.rom", "abc") + self.assertEqual(r, "not_in_zip") + + def test_14_check_inside_zip_casefold(self): + inner_md5 = self.files["good.zip"]["inner_md5s"]["inner.rom"] + r = check_inside_zip(self.files["good.zip"]["path"], "INNER.ROM", inner_md5) + self.assertEqual(r, "ok") + + def test_20_verify_existence_platform(self): + config = load_platform_config("test_existence", self.platforms_dir) + # Without the filename-agnostic core, which would serve the two + # missing slots under existence (test_20b covers that case). + profiles = { + k: v for k, v in load_emulator_profiles(self.emulators_dir).items() + if v.get("bios_mode") != "agnostic" + } + result = verify_platform(config, self.db, self.emulators_dir, emu_profiles=profiles) + c = result["severity_counts"] + total = result["total_files"] + # 2 present (1 req + 1 opt), 2 missing (1 req WARNING + 1 opt INFO) + self.assertEqual(c[Severity.OK], 2) + self.assertEqual(c[Severity.WARNING], 1) # required missing + self.assertEqual(c[Severity.INFO], 1) # optional missing + self.assertEqual(sum(c.values()), total) + + def test_21_verify_md5_platform(self): + config = load_platform_config("test_md5", self.platforms_dir) + result = verify_platform(config, self.db, self.emulators_dir) + c = result["severity_counts"] + total = result["total_files"] + self.assertEqual(sum(c.values()), total) + # At least some OK and some non-OK + self.assertGreater(c[Severity.OK], 0) + self.assertGreater(total, c[Severity.OK]) + + def test_22_verify_required_propagated(self): + config = load_platform_config("test_md5", self.platforms_dir) + result = verify_platform(config, self.db, self.emulators_dir) + for d in result["details"]: + self.assertIn("required", d) + + def test_23_verify_missing_required_is_critical(self): + config = load_platform_config("test_md5", self.platforms_dir) + result = verify_platform(config, self.db, self.emulators_dir) + c = result["severity_counts"] + self.assertGreater(c[Severity.CRITICAL], 0) + + def test_24_verify_missing_optional_is_warning(self): + config = load_platform_config("test_md5", self.platforms_dir) + result = verify_platform(config, self.db, self.emulators_dir) + c = result["severity_counts"] + self.assertGreater(c[Severity.WARNING], 0) + + def test_24b_a_held_group_member_makes_the_others_optional(self): + """RetroBat's group: one file held is enough (batocera-systems/Program.cs).""" + from model.platforms import _platform_config_cache + + with open(os.path.join(self.platforms_dir, "test_md5.yml")) as fh: + config = yaml.safe_load(fh) + held_md5 = next( + f["md5"] for f in config["systems"]["sys-renamed"]["files"] + ) + config["systems"] = { + "sys-group": {"files": [ + {"name": "correct_hash.bin", "destination": "g/held.bin", + "md5": held_md5, "required": True, "group": "one"}, + {"name": "absent_alt.bin", "destination": "g/absent_alt.bin", + "md5": "0" * 32, "required": True, "group": "one"}, + {"name": "absent_a.bin", "destination": "g/absent_a.bin", + "md5": "1" * 32, "required": True, "group": "none"}, + {"name": "absent_b.bin", "destination": "g/absent_b.bin", + "md5": "2" * 32, "required": True, "group": "none"}, + ]}, + } + with open(os.path.join(self.platforms_dir, "grouped_md5.yml"), "w") as fh: + yaml.dump(config, fh) + _platform_config_cache.clear() + result = verify_platform( + load_platform_config("grouped_md5", self.platforms_dir), self.db, self.emulators_dir + ) + by_name = {d["name"]: d for d in result["details"]} + self.assertEqual(by_name["correct_hash.bin"]["status"], Status.OK) + self.assertIs(by_name["absent_alt.bin"]["required"], False) + self.assertIs(by_name["absent_a.bin"]["required"], True) + self.assertIs(by_name["absent_b.bin"]["required"], True) + self.assertEqual(result["severity_counts"][Severity.CRITICAL], 2) + + def test_25_verify_sha1_platform(self): + config = load_platform_config("test_sha1", self.platforms_dir) + result = verify_platform(config, self.db, self.emulators_dir) + self.assertEqual(result["total_files"], 5) + self.assertEqual(result["verification_mode"], "sha1") + ok_count = result["severity_counts"][Severity.OK] + self.assertEqual(ok_count, 2) + + def test_26_sha1_mismatch_is_warning(self): + config = load_platform_config("test_sha1", self.platforms_dir) + result = verify_platform(config, self.db, self.emulators_dir) + by_name = {d["name"]: d for d in result["details"]} + self.assertEqual(by_name["wrong_hash.bin"]["status"], Status.UNTESTED) + + def test_27_sha1_missing_required_is_critical(self): + config = load_platform_config("test_sha1", self.platforms_dir) + result = verify_platform(config, self.db, self.emulators_dir) + c = result["severity_counts"] + self.assertGreater(c[Severity.CRITICAL], 0) + + def test_28_sha1_missing_optional_is_warning(self): + config = load_platform_config("test_sha1", self.platforms_dir) + result = verify_platform(config, self.db, self.emulators_dir) + c = result["severity_counts"] + self.assertGreater(c[Severity.WARNING], 0) + + def test_29_sha1_no_hash_is_existence_check(self): + config = load_platform_config("test_sha1", self.platforms_dir) + result = verify_platform(config, self.db, self.emulators_dir) + by_name = {d["name"]: d for d in result["details"]} + self.assertEqual(by_name["no_md5.bin"]["status"], Status.OK) + + def test_30_inheritance_inherits_systems(self): + config = load_platform_config("test_inherited", self.platforms_dir) + self.assertEqual(config["platform"], "TestInherited") + self.assertEqual(config["base_destination"], "BIOS") + self.assertIn("console-a", config["systems"]) + + def test_31_shared_groups_injected(self): + config = load_platform_config("test_md5", self.platforms_dir) + names = [f["name"] for f in config["systems"]["sys-md5"]["files"]] + self.assertIn("shared_file.rom", names) + + def test_40_cross_ref_finds_undeclared(self): + config = load_platform_config("test_existence", self.platforms_dir) + profiles = load_emulator_profiles(self.emulators_dir) + undeclared = find_undeclared_files( + config, self.emulators_dir, self.db, profiles + ) + names = {u["name"] for u in undeclared} + self.assertIn("undeclared_req.bin", names) + self.assertIn("undeclared_opt.bin", names) + + def test_41_cross_ref_skips_standalone(self): + config = load_platform_config("test_existence", self.platforms_dir) + profiles = load_emulator_profiles(self.emulators_dir) + undeclared = find_undeclared_files( + config, self.emulators_dir, self.db, profiles + ) + names = {u["name"] for u in undeclared} + self.assertNotIn("standalone_only.bin", names) + + def test_42_cross_ref_skips_alias_profiles(self): + profiles = load_emulator_profiles(self.emulators_dir) + self.assertNotIn("test_alias", profiles) + + def test_42b_profile_hash_fields_load_as_str(self): + """Unquoted digit-only hashes must load as strings, not YAML ints.""" + with tempfile.TemporaryDirectory() as tmp: + Path(tmp, "numcrc.yml").write_text( + "emulator: NumCRC\n" + "type: libretro\n" + "files:\n" + " - name: kernal.bin\n" + " crc32: 70295038\n" + " md5: [12345678901234567890123456789012]\n" + ) + profiles = load_emulator_profiles(tmp) + entry = profiles["numcrc"]["files"][0] + self.assertEqual(entry["crc32"], "70295038") + self.assertEqual(entry["md5"], ["12345678901234567890123456789012"]) + + def test_43_cross_ref_data_dir_does_not_suppress_files(self): + config = load_platform_config("test_md5", self.platforms_dir) + profiles = load_emulator_profiles(self.emulators_dir) + undeclared = find_undeclared_files( + config, self.emulators_dir, self.db, profiles + ) + names = {u["name"] for u in undeclared} + # dd_covered.bin is a file entry, not data_dir content: still undeclared + self.assertIn("dd_covered.bin", names) + + def test_44_cross_ref_skips_launchers(self): + config = load_platform_config("test_existence", self.platforms_dir) + profiles = load_emulator_profiles(self.emulators_dir) + undeclared = find_undeclared_files( + config, self.emulators_dir, self.db, profiles + ) + names = {u["name"] for u in undeclared} + # launcher_bios.bin from TestLauncher should NOT appear + self.assertNotIn("launcher_bios.bin", names) + + def test_45_hle_fallback_downgrades_severity(self): + """Missing file with hle_fallback=true ->INFO severity, not CRITICAL.""" + from packs.verdicts import Severity, compute_severity + + # required + missing + NO HLE = CRITICAL + sev = compute_severity("missing", True, "md5", hle_fallback=False) + self.assertEqual(sev, Severity.CRITICAL) + # required + missing + HLE = INFO + sev = compute_severity("missing", True, "md5", hle_fallback=True) + self.assertEqual(sev, Severity.INFO) + # required + missing + HLE + existence mode = INFO + sev = compute_severity("missing", True, "existence", hle_fallback=True) + self.assertEqual(sev, Severity.INFO) + + def test_46_hle_index_built_from_emulator_profiles(self): + """verify_platform reads hle_fallback from emulator profiles.""" + config = load_platform_config("test_existence", self.platforms_dir) + profiles = load_emulator_profiles(self.emulators_dir) + result = verify_platform(config, self.db, self.emulators_dir, profiles) + # present_req.bin has hle_fallback: true in TestHLE profile + for d in result["details"]: + if d["name"] == "present_req.bin": + self.assertTrue(d.get("hle_fallback", False)) + break + + def test_47_cross_ref_shows_hle_on_undeclared(self): + """Undeclared files include hle_fallback from emulator profile.""" + config = load_platform_config("test_existence", self.platforms_dir) + profiles = load_emulator_profiles(self.emulators_dir) + undeclared = find_undeclared_files( + config, self.emulators_dir, self.db, profiles + ) + hle_files = {u["name"] for u in undeclared if u.get("hle_fallback")} + self.assertIn("hle_missing.bin", hle_files) + + def test_50_platform_grouping_identical(self): + groups = group_identical_platforms( + ["test_existence", "test_inherited"], self.platforms_dir + ) + # With flat ZIPs, base_destination no longer separates groups + # Platforms with same files (regardless of base_dest) are grouped + self.assertEqual(len(groups), 1) + self.assertEqual(len(groups[0][0]), 2) + + def test_51_platform_grouping_same(self): + # Create two identical platforms + for name in ("dup_a", "dup_b"): + config = { + "platform": name, + "verification_mode": "existence", + "systems": { + "s": {"files": [{"name": "x.bin", "destination": "x.bin"}]} + }, + } + with open(os.path.join(self.platforms_dir, f"{name}.yml"), "w") as fh: + yaml.dump(config, fh) + groups = group_identical_platforms(["dup_a", "dup_b"], self.platforms_dir) + self.assertEqual(len(groups), 1) + self.assertEqual(len(groups[0][0]), 2) + + def test_52_platform_grouping_splits_on_cores(self): + """Same baseline, different emulators: the core files differ.""" + declared = { + "cores_all": "all_libretro", + "cores_all_too": "all_libretro", + "cores_listed": ["retroarch", "openmsx"], + } + for name, cores in declared.items(): + config = { + "platform": name, + "verification_mode": "existence", + "cores": cores, + "systems": { + "s": {"files": [{"name": "x.bin", "destination": "x.bin"}]} + }, + } + with open(os.path.join(self.platforms_dir, f"{name}.yml"), "w") as fh: + yaml.dump(config, fh) + groups = group_identical_platforms(list(declared), self.platforms_dir) + self.assertEqual( + sorted(sorted(group) for group, _rep in groups), + [["cores_all", "cores_all_too"], ["cores_listed"]], + ) + + def test_60_storage_external(self): + from resolve.packfiles import resolve_file + + entry = {"name": "large.pup", "storage": "external"} + path, status = resolve_file(entry, self.db, self.bios_dir) + self.assertIsNone(path) + self.assertEqual(status, "external") + + def test_61_storage_user_provided(self): + from resolve.packfiles import resolve_file + + entry = {"name": "user.bin", "storage": "user_provided"} + path, status = resolve_file(entry, self.db, self.bios_dir) + self.assertIsNone(path) + self.assertEqual(status, "user_provided") + + def test_resolve_cores_all_libretro(self): + """all_libretro resolves to all libretro-type profiles, excludes alias/standalone.""" + config = {"cores": "all_libretro", "systems": {"nes": {"files": []}}} + profiles = { + "fceumm": {"type": "libretro", "systems": ["nes"], "files": []}, + "dolphin_standalone": { + "type": "standalone", + "systems": ["gc"], + "files": [], + }, + "gambatte": {"type": "pure_libretro", "systems": ["gb"], "files": []}, + "mednafen_psx_hw": {"type": "alias", "alias_of": "beetle_psx", "files": []}, + } + result = resolve_platform_cores(config, profiles) + self.assertEqual(result, {"fceumm", "gambatte"}) + + def test_a_build_a_platform_compiles_is_reached_by_name(self): + """Recalbox compiles libretro/mame at 0.258 and 0.278, but the buildbot + RetroArch installs from does not, so all_libretro must not reach + them while a platform naming them does.""" + profiles = { + "mame": {"type": "standalone + libretro", "systems": ["arcade"], "files": []}, + "mame0278": {"type": "libretro", "built_by": ["recalbox"], + "cores": ["mame0278"], "systems": ["arcade"], "files": []}, + } + everyone = {"cores": "all_libretro", "systems": {}} + self.assertEqual(resolve_platform_cores(everyone, profiles), {"mame"}) + retroarch_plus = {"cores": ["retroarch"], "systems": {}} + self.assertEqual(resolve_platform_cores(retroarch_plus, profiles), {"mame"}) + recalbox = {"cores": ["mame0278"], "systems": {}} + self.assertEqual(resolve_platform_cores(recalbox, profiles), {"mame0278"}) + + def test_a_platform_s_own_libretro_build_comes_with_its_retroarch(self): + """ROCKNIX ships yabadabadoo with its RetroArch and names it nowhere + else: a list naming retroarch takes the libretro builds whose + built_by names that platform, and no other platform's.""" + profiles = { + "yabause": {"type": "libretro", "systems": ["saturn"], "files": []}, + "yabadabadoo": {"type": "libretro", "built_by": ["rocknix"], + "systems": ["saturn"], "files": []}, + } + rocknix = {"_key": "rocknix", "cores": ["retroarch"], "systems": {}} + self.assertEqual(resolve_platform_cores(rocknix, profiles), + {"yabause", "yabadabadoo"}) + other = {"_key": "batocera", "cores": ["retroarch"], "systems": {}} + self.assertEqual(resolve_platform_cores(other, profiles), {"yabause"}) + everyone = {"_key": "retroarch", "cores": "all_libretro", "systems": {}} + self.assertEqual(resolve_platform_cores(everyone, profiles), {"yabause"}) + + def test_resolve_cores_explicit_list(self): + """Explicit cores list matches against profile dict keys.""" + config = {"cores": ["fbneo", "opera"], "systems": {"arcade": {"files": []}}} + profiles = { + "fbneo": {"type": "pure_libretro", "systems": ["arcade"], "files": []}, + "opera": {"type": "libretro", "systems": ["3do"], "files": []}, + "mame": {"type": "libretro", "systems": ["arcade"], "files": []}, + } + result = resolve_platform_cores(config, profiles) + self.assertEqual(result, {"fbneo", "opera"}) + + def test_resolve_cores_fallback_systems(self): + """Missing cores: field falls back to system ID intersection.""" + config = {"systems": {"nes": {"files": []}}} + profiles = { + "fceumm": {"type": "libretro", "systems": ["nes"], "files": []}, + "dolphin": {"type": "libretro", "systems": ["gc"], "files": []}, + } + result = resolve_platform_cores(config, profiles) + self.assertEqual(result, {"fceumm"}) + + def test_resolve_cores_excludes_alias(self): + """Alias profiles never included even if name matches cores list.""" + config = {"cores": ["mednafen_psx_hw"], "systems": {}} + profiles = { + "mednafen_psx_hw": {"type": "alias", "alias_of": "beetle_psx", "files": []}, + } + result = resolve_platform_cores(config, profiles) + self.assertEqual(result, set()) + + def test_cross_reference_uses_core_resolution(self): + """Cross-reference matches by cores: field, not system intersection.""" + config = { + "cores": ["fbneo"], + "systems": {"arcade": {"files": [{"name": "neogeo.zip", "md5": "abc"}]}}, + } + profiles = { + "fbneo": { + "emulator": "FBNeo", + "systems": ["snk-neogeo-mvs"], + "type": "pure_libretro", + "files": [ + {"name": "neogeo.zip", "required": True}, + {"name": "neocdz.zip", "required": True}, + ], + }, + } + db = {"indexes": {"by_name": {"neocdz.zip": {"sha1": "x"}}}} + undeclared = find_undeclared_files(config, self.emulators_dir, db, profiles) + names = [u["name"] for u in undeclared] + self.assertIn("neocdz.zip", names) + self.assertNotIn("neogeo.zip", names) + + def test_exclusion_notes_uses_core_resolution(self): + """Exclusion notes match by cores: field, not system intersection.""" + config = {"cores": ["desmume2015"], "systems": {"nds": {"files": []}}} + profiles = { + "desmume2015": { + "emulator": "DeSmuME 2015", + "type": "frozen_snapshot", + "systems": ["nintendo-ds"], + "files": [], + "exclusion_note": "Frozen snapshot, code never loads BIOS", + }, + } + notes = find_exclusion_notes(config, self.emulators_dir, profiles) + emu_names = [n["emulator"] for n in notes] + self.assertIn("DeSmuME 2015", emu_names) + + +class TestE2EValidation(E2EFixture): + """The validation index and the checks it applies.""" + + def test_70_validation_index_built(self): + """Validation index extracts checks from emulator profiles.""" + profiles = load_emulator_profiles(self.emulators_dir) + index = build_validation_index(profiles) + self.assertIn("present_req.bin", index) + self.assertIn("size", index["present_req.bin"]["checks"]) + self.assertIn(16, {s for r in index["present_req.bin"]["rules"] for s in r["sizes"]}) + self.assertIn("correct_hash.bin", index) + self.assertIn("crc32", index["correct_hash.bin"]["checks"]) + + def test_71_validation_size_pass(self): + """File with correct size passes validation.""" + profiles = load_emulator_profiles(self.emulators_dir) + index = build_validation_index(profiles) + path = self.files["present_req.bin"]["path"] + reason = check_file_validation(path, "present_req.bin", index) + self.assertIsNone(reason) + + def test_72_validation_size_fail(self): + """File with wrong size fails validation.""" + profiles = load_emulator_profiles(self.emulators_dir) + index = build_validation_index(profiles) + path = self.files["present_opt.bin"]["path"] + result = check_file_validation(path, "present_opt.bin", index) + self.assertIsNotNone(result) + reason, emus = result + self.assertIn("size mismatch", reason) + self.assertIsInstance(emus, list) + + def test_73_validation_crc32_pass(self): + """File with correct CRC32 passes validation.""" + profiles = load_emulator_profiles(self.emulators_dir) + index = build_validation_index(profiles) + path = self.files["correct_hash.bin"]["path"] + reason = check_file_validation(path, "correct_hash.bin", index) + self.assertIsNone(reason) + + def test_74_validation_crc32_fail(self): + """File with wrong CRC32 fails validation.""" + profiles = load_emulator_profiles(self.emulators_dir) + index = build_validation_index(profiles) + path = self.files["no_md5.bin"]["path"] + result = check_file_validation(path, "no_md5.bin", index) + self.assertIsNotNone(result) + reason, emus = result + self.assertIn("crc32 mismatch", reason) + self.assertIsInstance(emus, list) + + def test_75_validation_applied_in_existence_mode(self): + """Existence mode reports discrepancy when validation fails, keeps OK.""" + config = load_platform_config("test_existence", self.platforms_dir) + profiles = load_emulator_profiles(self.emulators_dir) + result = verify_platform(config, self.db, self.emulators_dir, profiles) + # present_opt.bin exists but has wrong expected size - OK with discrepancy + for d in result["details"]: + if d["name"] == "present_opt.bin": + self.assertEqual(d["status"], Status.OK) + self.assertIn("size mismatch", d.get("discrepancy", "")) + break + else: + self.fail("present_opt.bin not found in details") + + def test_77_validation_crc32_leading_zero(self): + """CRC32 starting with '0' must not be truncated (lstrip regression).""" + profiles = load_emulator_profiles(self.emulators_dir) + index = build_validation_index(profiles) + path = self.files["leading_zero_crc.bin"]["path"] + reason = check_file_validation(path, "leading_zero_crc.bin", index) + self.assertIsNone(reason) + + def test_78_validation_multi_size_accepted(self): + """Multiple valid sizes from different profiles are collected as a set.""" + profiles = { + "emu_a": { + "type": "libretro", + "files": [ + {"name": "shared.bin", "validation": ["size"], "size": 512}, + ], + }, + "emu_b": { + "type": "libretro", + "files": [ + {"name": "shared.bin", "validation": ["size"], "size": 1024}, + ], + }, + } + index = build_validation_index(profiles) + self.assertEqual([r["sizes"] for r in index["shared.bin"]["rules"]], [{512}, {1024}]) + + def test_71b_validation_sizes_judged_per_entry(self): + """One core's exact size is never bounded by another core's minimum: + pooled, gsplus's 131072-byte Apple IIGS ROM fell under basiliskii's + min_size and was refused.""" + import tempfile + + profiles = { + "exact": {"type": "libretro", "files": [ + {"name": "ROM", "validation": ["size"], "size": [131072, 262144]}]}, + "ranged": {"type": "libretro", "files": [ + {"name": "ROM", "validation": ["size"], "min_size": 377670}]}, + } + index = build_validation_index(profiles) + with tempfile.TemporaryDirectory() as tmp: + path = os.path.join(tmp, "ROM") + with open(path, "wb") as f: + f.write(b"\0" * 131072) + self.assertIsNone(check_file_validation(path, "ROM", index)) + with open(path, "wb") as f: + f.write(b"\0" * 1000) + reason, emus = check_file_validation(path, "ROM", index) + self.assertIn("size", reason) + self.assertEqual(emus, ["exact", "ranged"]) + + def test_79_validation_md5_pass(self): + """File with correct MD5 passes validation.""" + profiles = load_emulator_profiles(self.emulators_dir) + index = build_validation_index(profiles) + path = self.files["correct_hash.bin"]["path"] + reason = check_file_validation(path, "correct_hash.bin", index) + self.assertIsNone(reason) + + def test_80_validation_md5_fail(self): + """File with wrong MD5 fails validation.""" + profiles = load_emulator_profiles(self.emulators_dir) + index = build_validation_index(profiles) + path = self.files["alias_target.bin"]["path"] + result = check_file_validation(path, "alias_target.bin", index) + self.assertIsNotNone(result) + reason, emus = result + self.assertIn("md5 mismatch", reason) + self.assertIsInstance(emus, list) + + def test_81_validation_index_has_md5_sha1(self): + """Validation index stores md5 and sha1 when declared.""" + profiles = load_emulator_profiles(self.emulators_dir) + index = build_validation_index(profiles) + self.assertIn("md5", index["correct_hash.bin"]["checks"]) + self.assertIn("sha1", index["correct_hash.bin"]["checks"]) + self.assertIsNotNone(index["correct_hash.bin"]["md5"]) + self.assertIsNotNone(index["correct_hash.bin"]["sha1"]) + + def test_82_validation_adler32_pass(self): + """File with correct adler32 passes validation.""" + profiles = load_emulator_profiles(self.emulators_dir) + index = build_validation_index(profiles) + path = self.files["present_req.bin"]["path"] + reason = check_file_validation(path, "present_req.bin", index) + self.assertIsNone(reason) + + def test_83_validation_min_max_size_pass(self): + """File within min/max size range passes validation.""" + profiles = load_emulator_profiles(self.emulators_dir) + index = build_validation_index(profiles) + path = self.files["present_req.bin"]["path"] + reason = check_file_validation(path, "present_req.bin", index) + self.assertIsNone(reason) + # Each entry keeps its own min/max + rules = index["present_req.bin"]["rules"] + self.assertIn((10, 100), {(r["min_size"], r["max_size"]) for r in rules}) + + def test_84_validation_crypto_tracked(self): + """Signature/crypto checks are tracked as non-reproducible.""" + profiles = load_emulator_profiles(self.emulators_dir) + index = build_validation_index(profiles) + # correct_hash.bin has [size, signature] + self.assertIn("signature", index["correct_hash.bin"]["crypto_only"]) + # Size check still applies despite signature being non-reproducible + path = self.files["correct_hash.bin"]["path"] + reason = check_file_validation(path, "correct_hash.bin", index) + self.assertIsNone(reason) # size=16 matches + + def test_76_validation_no_effect_when_no_field(self): + """Files without validation field are unaffected.""" + profiles = load_emulator_profiles(self.emulators_dir) + index = build_validation_index(profiles) + # wrong_hash.bin has no validation in any profile + path = self.files["wrong_hash.bin"]["path"] + reason = check_file_validation(path, "wrong_hash.bin", index) + self.assertIsNone(reason) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_e2e_search_sets.py b/tests/test_e2e_search_sets.py new file mode 100644 index 000000000..be881ba05 --- /dev/null +++ b/tests/test_e2e_search_sets.py @@ -0,0 +1,407 @@ +"""Standalone layouts, search lists and archive sets, end to end.""" + +from __future__ import annotations + +import tests +import contextlib +import hashlib +import io +import os +import shutil +import tempfile +import unittest +import zipfile +from pathlib import Path +import yaml +from model.profiles import load_emulator_profiles +from packs.verdicts import Severity +from packs.gaps import find_undeclared_files +from packs.emulatorcheck import verify_emulator + + +try: + import jsonschema +except ImportError: + jsonschema = None + + +HAS_JSONSCHEMA = jsonschema is not None + + +class StandaloneModeRequiresAStandaloneBuild(unittest.TestCase): + """A platform names its standalone emulators by its own names, which can + equal the key of a libretro-only profile (Recalbox and Batocera both + call their standalone ScummVM ``scummvm``). Laid out standalone, such a + profile loses every ``path:`` and drops its files at the root.""" + + def test_libretro_only_profile_keeps_its_layout(self): + from resolve.launches import PlatformLaunches + + libretro_only = {"type": "libretro", "cores": ["scummvm"]} + dual = {"type": "standalone + libretro", "cores": ["dolphin"]} + standalone = {"type": "standalone", "cores": ["xemu"]} + named = PlatformLaunches(standalone=frozenset({"scummvm", "dolphin", "xemu", "hatari"})) + self.assertFalse(named.runs_standalone("scummvm", libretro_only)) + self.assertTrue(named.runs_standalone("dolphin", dual)) + self.assertTrue(named.runs_standalone("xemu", standalone)) + self.assertTrue(named.runs_standalone("other-key", {"type": "standalone", "cores": ["hatari"]})) + self.assertFalse(PlatformLaunches().runs_standalone("dolphin", dual)) + self.assertFalse( + PlatformLaunches(standalone=frozenset({"pcsx2"})).runs_standalone("dolphin", dual) + ) + + +class OneOfASearchList(unittest.TestCase): + """Entries a core takes the first of are one need (``group:``). + + Yabause tries saturn_bios.bin, sega_101.bin, mpr-17933.bin and loads the + first it finds. Written as required on the first name only, verify and + the gap report called saturn_bios.bin a missing required file while + sega_101.bin was held, and a set held through an optional-looking name + passed for the wrong reason. Synthetic: set ``first`` holds only its + second member, set ``none`` holds nothing. + """ + + def setUp(self): + from model.profiles import emulator_profiles_cache + + emulator_profiles_cache.clear() + self.root = Path(tempfile.mkdtemp()) + self.addCleanup(shutil.rmtree, self.root, True) + previous = os.getcwd() + os.chdir(self.root) + self.addCleanup(os.chdir, previous) + self.db = {"files": {}, "indexes": {"by_md5": {}, "by_name": {}, + "by_crc32": {}, "by_path_suffix": {}}} + for name in ("second.bin", "third.bin", "plain.bin"): + data = name.encode() * 8 + rel = f"bios/Test/Console/{name}" + Path(rel).parent.mkdir(parents=True, exist_ok=True) + Path(rel).write_bytes(data) + sha1 = hashlib.sha1(data).hexdigest() + self.db["files"][sha1] = {"path": rel, "name": name, "size": len(data), + "md5": hashlib.md5(data).hexdigest(), "crc32": ""} + self.db["indexes"]["by_name"][name] = [sha1] + Path("emulators").mkdir() + Path("platforms").mkdir() + + def member(name: str, group: str, rank: int) -> dict: + return {"name": name, "system": "console-a", "group": group, + "priority": rank} + + raw = { + "emulator": "Seq", "type": "libretro", "cores": ["seq"], + "systems": ["console-a"], + "groups": {"first": {"required": True}, "none": {"required": True}}, + "files": [ + member("first.bin", "first", 1), + member("second.bin", "first", 2), + member("third.bin", "first", 3), + member("none_a.bin", "none", 1), + member("none_b.bin", "none", 2), + {"name": "plain.bin", "system": "console-a", "required": True}, + ], + } + Path("emulators/seq.yml").write_text(yaml.safe_dump(raw)) + self.raw = raw + # What every reader sees: the profile as load_emulator_profiles gives it. + self.profile = load_emulator_profiles("emulators")["seq"] + self.config = { + "platform": "Seqs", "verification_mode": "existence", + "base_destination": "system", "cores": ["seq"], + "systems": {"console-a": {"files": []}}, + } + + def _verify(self) -> dict: + return verify_emulator(["seq"], "emulators", self.db, platforms_dir="platforms") + + def test_one_member_held_leaves_no_missing_report_for_its_set(self): + result = self._verify() + reported = {d["name"]: d["status"] for d in result["details"]} + self.assertEqual(reported["second.bin"], "ok") + self.assertEqual(reported["third.bin"], "ok") + self.assertNotIn("first.bin", reported) + self.assertEqual( + sorted(d["name"] for d in result["set_members"]), + ["first.bin", "none_b.bin"], + ) + + def test_a_set_none_holds_is_one_gap(self): + result = self._verify() + missing = [d for d in result["details"] if d["status"] == "missing"] + self.assertEqual([d["name"] for d in missing], ["none_a.bin"]) + self.assertEqual(missing[0]["alternatives"], ["none_b.bin"]) + # Required and missing, judged as the core judges: one warning. + self.assertEqual(result["severity_counts"][Severity.WARNING], 1) + self.assertEqual(result["severity_counts"][Severity.INFO], 0) + self.assertEqual(result["status_counts"].get("missing"), 1) + self.assertEqual(result["total_files"], 4) + + def test_a_required_set_held_through_a_later_member_is_satisfied(self): + """second.bin used to read required: false beside a required + first.bin: the set is required and held, so nothing is critical + for it, and the strict exit names only the set nobody holds.""" + from packs.strictgate import emulator_strict_failure + + result = self._verify() + critical = [d["name"] for d in result["details"] + if d["status"] == "missing" and d["required"]] + self.assertEqual(critical, ["none_a.bin"]) + self.assertIn("1 required file(s) missing: none_a.bin", + emulator_strict_failure(result) or "") + + def test_pack_and_verify_agree(self): + from packs.emulatorpack import generate_emulator_pack + + result = self._verify() + out = io.StringIO() + with contextlib.redirect_stdout(out): + zip_path = generate_emulator_pack( + ["seq"], "emulators", self.db, "bios", "out", offline=True, + platforms_dir="platforms", + ) + with zipfile.ZipFile(zip_path) as zf: + packed = sorted(n for n in zf.namelist() if n != "README.txt") + self.assertEqual(packed, ["plain.bin", "second.bin", "third.bin"]) + self.assertEqual(result["severity_counts"]["ok"], len(packed)) + lines = out.getvalue().splitlines() + self.assertEqual( + [line.split(": ", 1)[1] for line in lines if line.strip().startswith("MISSING:")], + ["none_a.bin"], + ) + self.assertIn("3 files packed, 1 missing", out.getvalue()) + + def test_core_complement_reports_one_gap_per_set(self): + undeclared = find_undeclared_files( + self.config, "emulators", self.db, {"seq": self.profile} + ) + by_name = {u["name"]: u for u in undeclared} + self.assertEqual( + sorted(by_name), ["none_a.bin", "plain.bin", "second.bin", "third.bin"] + ) + self.assertTrue(by_name["second.bin"]["in_repo"]) + self.assertFalse(by_name["none_a.bin"]["in_repo"]) + self.assertEqual(by_name["none_a.bin"]["alternatives"], ["none_b.bin"]) + + def test_a_platform_declaration_speaks_for_the_set(self): + """The platform declares first.bin and reports it in its own check: + the core's other names are not gaps on top of it.""" + config = {**self.config, "systems": {"console-a": {"files": [ + {"name": "first.bin", "destination": "first.bin", "required": True}, + {"name": "none_b.bin", "destination": "none_b.bin", "required": True}, + ]}}} + undeclared = find_undeclared_files( + config, "emulators", self.db, {"seq": self.profile} + ) + self.assertEqual( + sorted(u["name"] for u in undeclared), ["plain.bin", "second.bin", "third.bin"] + ) + + def test_gap_report_counts_the_set_once(self): + from packs import crossref + + index = { + "by_name": self.db["indexes"]["by_name"], + "by_name_lower": {k.lower(): k for k in self.db["indexes"]["by_name"]}, + "by_path_suffix": {}, "by_md5": {}, "by_sha256": {}, "by_crc32": {}, + "data_names": set(), "all_declared": set(), "db_files": self.db["files"], + } + report: dict = {} + crossref._cross_reference_profile("seq", self.profile, {}, report, index) + gaps = {g["name"]: g for g in report["seq"]["gap_details"]} + self.assertEqual(sorted(gaps), ["none_a.bin", "plain.bin", "second.bin", "third.bin"]) + self.assertEqual(gaps["none_a.bin"]["alternatives"], ["none_b.bin"]) + self.assertEqual(report["seq"]["set_aside"]["other_versions"], 2) + + def test_truth_names_no_member_required_on_its_own(self): + from resolve.truth import _fold_into, _new_truth_entry + + entry = _new_truth_entry(dict(self.profile["files"][0]), "seq", None) + self.assertNotIn("required", entry) + self.assertEqual(entry["_required_by"], set()) + self.assertTrue(entry["one_of_required"]) + _fold_into(entry, {"name": "first.bin", "required": True}, "other") + self.assertTrue(entry["required"]) + self.assertEqual(entry["_required_by"], {"other"}) + + def test_ranks_order_one_set_and_never_two(self): + """px68k-sdl ranks its IPL list and its font list each from 1: + --one-per-slot keeps the first of each, not one file of the two.""" + from resolve.slot import build_slot_index, resolve_slot_drops + + profile = {"type": "standalone", "files": [ + {"name": "ipl_a.dat", "group": "ipl", "priority": 1}, + {"name": "ipl_b.dat", "group": "ipl", "priority": 2}, + {"name": "font_a.dat", "group": "font", "priority": 1}, + {"name": "font_b.dat", "group": "font", "priority": 2}, + ]} + index = build_slot_index({"x68": profile}) + groups = {"sharp-x68000": [(n, n) for n in + ("ipl_a.dat", "ipl_b.dat", "font_a.dat", "font_b.dat")]} + drops, undecidable = resolve_slot_drops(groups, index) + self.assertEqual(drops, {"ipl_b.dat", "font_b.dat"}) + self.assertEqual(undecidable, []) + + def test_an_archive_needs_one_member_of_a_set(self): + import zlib + + from resolve.archives import holds_required_members + + path = self.root / "set.zip" + with zipfile.ZipFile(path, "w") as zf: + zf.writestr("boot_b.ic94", b"B") + zf.writestr("eeprom.ic1", b"E") + crc = {n: f"{zlib.crc32(d):08x}" for n, d in (("a", b"A"), ("b", b"B"), ("e", b"E"))} + members = [ + {"crc32": crc["a"], "required": True, "group": "boot"}, + {"crc32": crc["b"], "required": True, "group": "boot"}, + {"crc32": crc["e"], "required": True}, + ] + self.assertTrue(holds_required_members(str(path), members)) + self.assertFalse(holds_required_members(str(path), members[:1] + members[2:])) + + @unittest.skipUnless(HAS_JSONSCHEMA, "validate_schemas needs jsonschema") + def test_schema_refuses_a_set_split_on_required(self): + from schemas.profilechecks import group_requirement_split + from core.paths import REPO_ROOT + + path = REPO_ROOT / "emulators" / "seq.yml" + own_value = {"groups": {"g": {"required": True}}, + "files": [{"name": "a", "group": "g", "required": False}, + {"name": "b", "group": "g"}]} + self.assertEqual(len(group_requirement_split(path, own_value)), 1) + undeclared_set = {"files": [{"name": "a", "group": "g"}]} + self.assertEqual(len(group_requirement_split(path, undeclared_set)), 1) + unused = {"groups": {"g": {"required": True}}, "files": [{"name": "a"}]} + self.assertEqual(len(group_requirement_split(path, unused)), 1) + self.assertEqual(group_requirement_split(path, self.raw), []) + + def test_a_shared_fallback_takes_its_requirement_from_its_sets(self): + """pom2 falls back on apple2e.rom for the //e it boots by default + and for the unenhanced //e it may be switched to. One value on the + file cannot say both: the sets carry it.""" + from model.alternatives import derive_member_requirements + + profile = {"groups": {"iie": {"required": True}, "iie-u": {"required": False}}, + "files": [{"name": "apple2e_unenh.rom", "group": "iie-u"}, + {"name": "apple2e.rom", "group": ["iie", "iie-u"]}]} + derive_member_requirements(profile) + self.assertEqual([f["required"] for f in profile["files"]], [False, True]) + + def test_required_only_keeps_one_held_member_per_required_set(self): + """second.bin and third.bin are both held: a --required-only pack + carries second.bin, the first the code reads among those held, and + verify reports the same single file.""" + from packs.emulatorpack import generate_emulator_pack + + result = verify_emulator(["seq"], "emulators", self.db, + platforms_dir="platforms", required_only=True) + held = sorted(d["name"] for d in result["details"] if d["status"] == "ok") + self.assertEqual(held, ["plain.bin", "second.bin"]) + with contextlib.redirect_stdout(io.StringIO()): + zip_path = generate_emulator_pack( + ["seq"], "emulators", self.db, "bios", "out", offline=True, + platforms_dir="platforms", required_only=True, + ) + with zipfile.ZipFile(zip_path) as zf: + packed = sorted(n for n in zf.namelist() if n != "README.txt") + self.assertEqual(packed, held) + + def test_required_only_core_files_keep_one_member(self): + from model.alternatives import core_file_spares + + undeclared = find_undeclared_files( + self.config, "emulators", self.db, {"seq": self.profile} + ) + spares = core_file_spares(undeclared) + kept = sorted(u["name"] for u in undeclared if id(u) not in spares) + self.assertEqual(kept, ["none_a.bin", "plain.bin", "second.bin"]) + + +class AnArchiveIsAMemberOfASet(unittest.TestCase): + """Kronos reads kronos/stvbios.zip, else stvbios.zip at the root: one + archive under two paths, a first-found pair. The archive unit and the + root copy settle as members of one set, and a --required-only pack + carries the first, while the members inside still settle the archive + by its contents.""" + + def _fixture(self, held: bool) -> dict: + import zlib + + from model.profiles import emulator_profiles_cache + + emulator_profiles_cache.clear() + root = Path(tempfile.mkdtemp()) + self.addCleanup(shutil.rmtree, root, True) + previous = os.getcwd() + os.chdir(root) + self.addCleanup(os.chdir, previous) + self.db: dict = {"files": {}, "indexes": {"by_md5": {}, "by_name": {}, + "by_crc32": {}, "by_path_suffix": {}}} + rom = b"STV" * 64 + if held: + rel = "bios/Sega/STV/set.zip" + Path(rel).parent.mkdir(parents=True) + with zipfile.ZipFile(rel, "w") as zf: + zf.writestr("epr.ic8", rom) + data = Path(rel).read_bytes() + sha1 = hashlib.sha1(data).hexdigest() + self.db["files"][sha1] = {"path": rel, "name": "set.zip", "size": len(data), + "md5": hashlib.md5(data).hexdigest(), "crc32": ""} + self.db["indexes"]["by_name"]["set.zip"] = [sha1] + Path("emulators").mkdir() + Path("platforms").mkdir() + Path("emulators/stv.yml").write_text(yaml.safe_dump({ + "emulator": "Stv", "type": "libretro", "cores": ["stv"], + "systems": ["sega-stv"], "archive_prefix": "stv", + "groups": {"stv-bios": {"required": True}}, + "files": [ + {"name": "set.zip", "system": "sega-stv", "group": "stv-bios"}, + {"name": "epr.ic8", "archive": "set.zip", "system": "sega-stv", + "required": True, "crc32": f"{zlib.crc32(rom):08x}"}, + ], + })) + return load_emulator_profiles("emulators")["stv"] + + def test_the_archive_and_its_root_copy_are_one_need(self): + self._fixture(held=False) + result = verify_emulator(["stv"], "emulators", self.db, platforms_dir="platforms") + missing = [d for d in result["details"] if d["status"] == "missing"] + self.assertEqual([d["destination"] for d in missing], ["stv/set.zip"]) + self.assertEqual(missing[0]["alternatives"], ["set.zip"]) + self.assertEqual(result["status_counts"].get("missing"), 1) + + def test_required_only_carries_the_archive_the_code_reads_first(self): + from packs.emulatorpack import generate_emulator_pack + + self._fixture(held=True) + full = verify_emulator(["stv"], "emulators", self.db, platforms_dir="platforms") + self.assertEqual( + sorted(d["destination"] for d in full["details"] if d["status"] == "ok"), + ["set.zip", "stv/set.zip"], + ) + result = verify_emulator(["stv"], "emulators", self.db, + platforms_dir="platforms", required_only=True) + held = sorted(d["destination"] for d in result["details"] if d["status"] == "ok") + self.assertEqual(held, ["stv/set.zip"]) + with contextlib.redirect_stdout(io.StringIO()): + zip_path = generate_emulator_pack( + ["stv"], "emulators", self.db, "bios", "out", offline=True, + platforms_dir="platforms", required_only=True, + ) + with zipfile.ZipFile(zip_path) as zf: + packed = sorted(n for n in zf.namelist() if n != "README.txt") + self.assertEqual(packed, held) + + def test_core_files_report_the_pair_once(self): + profile = self._fixture(held=False) + config = {"platform": "Stvs", "verification_mode": "existence", + "base_destination": "system", "cores": ["stv"], + "systems": {"sega-stv": {"files": []}}} + undeclared = find_undeclared_files(config, "emulators", self.db, {"stv": profile}) + self.assertEqual([u["name"] for u in undeclared], ["set.zip"]) + self.assertTrue(undeclared[0].get("archive")) + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_e2e_truth.py b/tests/test_e2e_truth.py new file mode 100644 index 000000000..a71dcfff7 --- /dev/null +++ b/tests/test_e2e_truth.py @@ -0,0 +1,977 @@ +"""End-to-end scraper parsing, archive cross-reference, truth generation and manifests.""" + +from __future__ import annotations + +import tests +import os +import unittest +import zipfile +import yaml +from model.profiles import load_emulator_profiles +from model.platforms import load_platform_config +from resolve.localfile import resolve_local_file +from resolve.truth import generate_platform_truth +from packs.gaps import find_undeclared_files +from tests.e2esupport import E2EFixture + + +class TestE2EBizHawkScraper(E2EFixture): + """The BizHawk FirmwareDatabase.cs parser.""" + + # BizHawk scraper tests + + def test_150_bizhawk_scraper_parse_firmware_and_option(self): + """Parse FirmwareAndOption() one-liner pattern.""" + from scraper.bizhawk_scraper import parse_firmware_database + + fragment = """ + FirmwareAndOption("DBEBD76A448447CB6E524AC3CB0FD19FC065D944", 256, "32X", "G", "32X_G_BIOS.BIN", "32x 68k BIOS"); + FirmwareAndOption("1E5B0B2441A4979B6966D942B20CC76C413B8C5E", 2048, "32X", "M", "32X_M_BIOS.BIN", "32x SH2 MASTER BIOS"); + """ + records, files = parse_firmware_database(fragment) + self.assertEqual(len(records), 2) + self.assertEqual(records[0]["system"], "32X") + self.assertEqual(records[0]["firmware_id"], "G") + self.assertEqual(records[0]["sha1"], "DBEBD76A448447CB6E524AC3CB0FD19FC065D944") + self.assertEqual(records[0]["name"], "32X_G_BIOS.BIN") + self.assertEqual(records[0]["size"], 256) + + def test_151_bizhawk_scraper_parse_variable_refs(self): + """Parse var = File() + Firmware() + Option() pattern.""" + from scraper.bizhawk_scraper import parse_firmware_database + + fragment = """ + var gbaNormal = File("300C20DF6731A33952DED8C436F7F186D25D3492", 16384, "GBA_bios.rom", "Bios (World)"); + Firmware("GBA", "Bios", "Bios"); + Option("GBA", "Bios", in gbaNormal, FirmwareOptionStatus.Ideal); + """ + records, files = parse_firmware_database(fragment) + self.assertEqual(len(records), 1) + self.assertEqual(records[0]["system"], "GBA") + self.assertEqual(records[0]["sha1"], "300C20DF6731A33952DED8C436F7F186D25D3492") + self.assertEqual(records[0]["name"], "GBA_bios.rom") + self.assertEqual(records[0]["status"], "Ideal") + + def test_152_bizhawk_scraper_skips_comments(self): + """Commented-out blocks (PS2) are skipped.""" + from scraper.bizhawk_scraper import parse_firmware_database + + fragment = """ + FirmwareAndOption("DBEBD76A448447CB6E524AC3CB0FD19FC065D944", 256, "32X", "G", "32X_G_BIOS.BIN", "32x 68k BIOS"); + /* + Firmware("PS2", "BIOS", "PS2 Bios"); + Option("PS2", "BIOS", File("FBD54BFC020AF34008B317DCB80B812DD29B3759", 4194304, "ps2.bin", "PS2 Bios")); + */ + """ + records, files = parse_firmware_database(fragment) + systems = {r["system"] for r in records} + self.assertNotIn("PS2", systems) + self.assertEqual(len(records), 1) + + def test_152b_bizhawk_scraper_skips_line_comments(self): + """FirmwareDatabase.cs 2.11.1 comments out two MSX options with //: + read as live, they were listed required.""" + from scraper.bizhawk_scraper import parse_firmware_database + + fragment = """ + FirmwareAndOption("DBEBD76A448447CB6E524AC3CB0FD19FC065D944", 256, "32X", "G", "32X_G_BIOS.BIN", "see http://x"); + //FirmwareAndOption("E998F0C441F4F1800EF44E42CD1659150206CF79", 32768, "MSX", "bios_pal", "MSX_8020-20bios.rom", "MSX"); + """ + records, _ = parse_firmware_database(fragment) + self.assertEqual([r["name"] for r in records], ["32X_G_BIOS.BIN"]) + + def test_153_bizhawk_scraper_arithmetic_size(self): + """Size expressions like 4 * 1024 * 1024 are evaluated.""" + from scraper.bizhawk_scraper import parse_firmware_database + + fragment = """ + FirmwareAndOption("BF861922DCB78C316360E3E742F4F70FF63C9BC3", 4 * 1024 * 1024, "N64DD", "IPL_JPN", "64DD_IPL.bin", "N64DD JPN IPL"); + """ + records, _ = parse_firmware_database(fragment) + self.assertEqual(records[0]["size"], 4194304) + + def test_154_bizhawk_scraper_dummy_hash(self): + """SHA1Checksum.Dummy entries get no sha1 field.""" + from scraper.bizhawk_scraper import parse_firmware_database + + fragment = """ + FirmwareAndOption(SHA1Checksum.Dummy, 0, "3DS", "aes_keys", "aes_keys.txt", "AES Keys"); + """ + records, _ = parse_firmware_database(fragment) + self.assertEqual(len(records), 1) + self.assertIsNone(records[0]["sha1"]) + + def test_155_bizhawk_scraper_multi_option_picks_ideal(self): + """When multiple options exist, Ideal is selected as canonical.""" + from scraper.bizhawk_scraper import parse_firmware_database + + fragment = """ + var ss_100_j = File("2B8CB4F87580683EB4D760E4ED210813D667F0A2", 524288, "SAT_1.00-(J).bin", "Bios v1.00 (J)"); + var ss_101_j = File("DF94C5B4D47EB3CC404D88B33A8FDA237EAF4720", 524288, "SAT_1.01-(J).bin", "Bios v1.01 (J)"); + Firmware("SAT", "J", "Bios (J)"); + Option("SAT", "J", in ss_100_j); + Option("SAT", "J", in ss_101_j, FirmwareOptionStatus.Ideal); + """ + records, _ = parse_firmware_database(fragment) + self.assertEqual(len(records), 1) + self.assertEqual(records[0]["sha1"], "DF94C5B4D47EB3CC404D88B33A8FDA237EAF4720") + self.assertEqual(records[0]["name"], "SAT_1.01-(J).bin") + + def test_156_bizhawk_scraper_is_bad_excluded(self): + """Files with isBad: true are not selected as canonical.""" + from scraper.bizhawk_scraper import parse_firmware_database + + fragment = """ + var good = File("AAAA", 100, "good.bin", "Good"); + var bad = File("BBBB", 100, "bad.bin", "Bad", isBad: true); + Firmware("TEST", "X", "Test"); + Option("TEST", "X", in bad); + Option("TEST", "X", in good, FirmwareOptionStatus.Ideal); + """ + records, _ = parse_firmware_database(fragment) + self.assertEqual(records[0]["name"], "good.bin") + + +class TestE2EPathConflicts(E2EFixture): + """File and directory naming collisions in a pack.""" + + def test_157_path_conflict_helpers(self): + """has_path_conflict detects file/directory naming collisions.""" + from packs.paths import has_path_conflict, register_path + + seen_files: set[str] = set() + seen_parents: set[str] = set() + + # Register system/SGB1.sfc as a file + register_path("system/SGB1.sfc", seen_files, seen_parents) + + # Adding system/SGB1.sfc/program.rom should conflict (parent is a file) + self.assertTrue( + has_path_conflict("system/SGB1.sfc/program.rom", seen_files, seen_parents) + ) + + # Adding system/other.bin should not conflict + self.assertFalse( + has_path_conflict("system/other.bin", seen_files, seen_parents) + ) + + # Reverse: register a nested path first, then check flat + seen_files2: set[str] = set() + seen_parents2: set[str] = set() + register_path("system/SGB2.sfc/program.rom", seen_files2, seen_parents2) + + # Adding system/SGB2.sfc as a file should conflict (it's a directory) + self.assertTrue( + has_path_conflict("system/SGB2.sfc", seen_files2, seen_parents2) + ) + + # Adding system/SGB2.sfc/boot.rom should not conflict (sibling in same dir) + self.assertFalse( + has_path_conflict("system/SGB2.sfc/boot.rom", seen_files2, seen_parents2) + ) + + def test_158_pack_skips_file_directory_conflict(self): + """Pack generation skips entries that conflict with existing paths.""" + from packs.platformpack import generate_pack + + output_dir = os.path.join(self.root, "pack_conflict") + os.makedirs(output_dir, exist_ok=True) + + # Platform declares SGB1.sfc as a flat file + config = { + "platform": "ConflictTest", + "verification_mode": "existence", + "base_destination": "system", + "systems": { + "test-sys": { + "files": [ + { + "name": "present_req.bin", + "destination": "present_req.bin", + "required": True, + }, + ], + }, + }, + } + with open(os.path.join(self.platforms_dir, "test_conflict.yml"), "w") as fh: + yaml.dump(config, fh) + + # Create an emulator profile with a nested path that conflicts + emu = { + "emulator": "ConflictCore", + "type": "libretro", + "systems": ["test-sys"], + "files": [ + {"name": "present_req.bin/nested.rom", "required": False}, + ], + } + with open(os.path.join(self.emulators_dir, "conflict_core.yml"), "w") as fh: + yaml.dump(emu, fh) + + zip_path = generate_pack( + "test_conflict", + self.platforms_dir, + self.db, + self.bios_dir, + output_dir, + emulators_dir=self.emulators_dir, + offline=True, + ) + self.assertIsNotNone(zip_path) + with zipfile.ZipFile(zip_path) as zf: + names = zf.namelist() + # Flat file should be present + self.assertTrue( + any("present_req.bin" in n and "/" + "nested" not in n for n in names) + ) + # Nested conflict should NOT be present + self.assertFalse(any("nested.rom" in n for n in names)) + + +class TestE2EArchiveCrossRef(E2EFixture): + """Archive cross-reference, descriptive names and data directory fallback.""" + + # --------------------------------------------------------------- + # Archive cross-reference and descriptive name tests + # --------------------------------------------------------------- + + def test_159_cross_ref_archive_in_repo(self): + """Archived files group by archive, in_repo=True when archive exists.""" + config = load_platform_config("test_existence", self.platforms_dir) + profiles = load_emulator_profiles(self.emulators_dir) + undeclared = find_undeclared_files( + config, self.emulators_dir, self.db, profiles + ) + # test_archive.zip should appear as a single grouped entry + archive_entries = [ + u for u in undeclared if u.get("archive") == "test_archive.zip" + ] + self.assertEqual(len(archive_entries), 1) + entry = archive_entries[0] + self.assertTrue(entry["in_repo"]) + self.assertEqual(entry["name"], "test_archive.zip") + self.assertEqual(entry["archive_file_count"], 2) + self.assertTrue(entry["required"]) # at least one file is required + + def test_160_cross_ref_archive_missing(self): + """Missing archive reported as single entry with in_repo=False.""" + config = load_platform_config("test_existence", self.platforms_dir) + profiles = load_emulator_profiles(self.emulators_dir) + undeclared = find_undeclared_files( + config, self.emulators_dir, self.db, profiles + ) + missing_entries = [ + u for u in undeclared if u.get("archive") == "missing_archive.zip" + ] + self.assertEqual(len(missing_entries), 1) + entry = missing_entries[0] + self.assertFalse(entry["in_repo"]) + self.assertEqual(entry["name"], "missing_archive.zip") + self.assertEqual(entry["archive_file_count"], 1) + + def test_161_cross_ref_archive_not_individual_roms(self): + """Individual ROM names from archived files should NOT appear as separate entries.""" + config = load_platform_config("test_existence", self.platforms_dir) + profiles = load_emulator_profiles(self.emulators_dir) + undeclared = find_undeclared_files( + config, self.emulators_dir, self.db, profiles + ) + names = {u["name"] for u in undeclared} + # Individual ROMs should NOT be in the undeclared list + self.assertNotIn("rom_a.bin", names) + self.assertNotIn("rom_b.bin", names) + self.assertNotIn("missing_rom.bin", names) + + def test_162_cross_ref_descriptive_name_resolved_by_path(self): + """Descriptive name with path: fallback resolves via path basename.""" + config = load_platform_config("test_existence", self.platforms_dir) + profiles = load_emulator_profiles(self.emulators_dir) + undeclared = find_undeclared_files( + config, self.emulators_dir, self.db, profiles + ) + desc_entries = { + u["name"]: u for u in undeclared if u["emulator"] == "TestDescriptive" + } + # "Descriptive BIOS Name" has path: "present_req.bin" which IS in by_name + self.assertIn("Descriptive BIOS Name", desc_entries) + self.assertTrue(desc_entries["Descriptive BIOS Name"]["in_repo"]) + # "Missing Descriptive" has path: "nonexistent_path.bin" which is NOT in by_name + self.assertIn("Missing Descriptive", desc_entries) + self.assertFalse(desc_entries["Missing Descriptive"]["in_repo"]) + + def test_163_cross_ref_archive_declared_by_platform_skipped(self): + """Archive files whose archive is declared by platform are skipped.""" + # Create a platform that declares test_archive.zip + config = { + "platform": "TestArchivePlatform", + "verification_mode": "existence", + "systems": { + "console-a": { + "files": [ + { + "name": "test_archive.zip", + "destination": "test_archive.zip", + "required": True, + }, + ], + }, + }, + } + with open( + os.path.join(self.platforms_dir, "test_archive_platform.yml"), "w" + ) as fh: + yaml.dump(config, fh) + config = load_platform_config("test_archive_platform", self.platforms_dir) + profiles = load_emulator_profiles(self.emulators_dir) + undeclared = find_undeclared_files( + config, self.emulators_dir, self.db, profiles + ) + # test_archive.zip is declared ->its archived ROMs should be skipped + archive_entries = [ + u for u in undeclared if u.get("archive") == "test_archive.zip" + ] + self.assertEqual(len(archive_entries), 0) + + def test_164_pack_extras_use_archive_name(self): + """Pack extras for archived files use archive name, not individual ROM.""" + from packs.extras import collect_emulator_extras + + config = load_platform_config("test_existence", self.platforms_dir) + profiles = load_emulator_profiles(self.emulators_dir) + extras = collect_emulator_extras( + config, + self.emulators_dir, + self.db, + set(), + "", + profiles, + ) + extra_names = {e["name"] for e in extras} + # Archive name should be present, not individual ROMs + self.assertIn("test_archive.zip", extra_names) + self.assertNotIn("rom_a.bin", extra_names) + self.assertNotIn("rom_b.bin", extra_names) + # Missing archive should NOT be in extras (in_repo=False) + self.assertNotIn("missing_archive.zip", extra_names) + + def test_165_pack_extras_multi_dest_cross_ref(self): + """Same file at different paths from two profiles produces both destinations.""" + from packs.extras import collect_emulator_extras + + config = load_platform_config("test_existence", self.platforms_dir) + profiles = load_emulator_profiles(self.emulators_dir) + extras = collect_emulator_extras( + config, + self.emulators_dir, + self.db, + set(), + "", + profiles, + ) + extra_dests = {e["destination"] for e in extras} + # Root destination (from test_emu or test_root_core, no path) + self.assertIn("present_req.bin", extra_dests) + # Subdirectory destination (from test_subdir_core) + self.assertIn("subcore/bios/present_req.bin", extra_dests) + + def test_166_pack_extras_multi_dest_platform_declared(self): + """Profile with path different from platform destination adds alternative.""" + from packs.extras import collect_emulator_extras + + config = load_platform_config("test_existence", self.platforms_dir) + profiles = load_emulator_profiles(self.emulators_dir) + # Simulate platform already having present_req.bin at root + seen = {"present_req.bin"} + extras = collect_emulator_extras( + config, + self.emulators_dir, + self.db, + seen, + "", + profiles, + ) + extra_dests = {e["destination"] for e in extras} + # Root is already in pack (in seen), should NOT be duplicated + self.assertNotIn("present_req.bin", extra_dests) + # Subdirectory destination should be added + self.assertIn("subcore/bios/present_req.bin", extra_dests) + + def test_167_resolve_local_file_data_dir_fallback(self): + """resolve_local_file finds files in data directories when not in bios/.""" + data_dir = os.path.join(self.root, "data", "test-data") + os.makedirs(data_dir, exist_ok=True) + data_file = os.path.join(data_dir, "data_only.bin") + with open(data_file, "wb") as f: + f.write(b"DATA_DIR_CONTENT") + + registry = {"test-data": {"local_cache": data_dir}} + + fe = {"name": "data_only.bin"} + path, status = resolve_local_file(fe, self.db, data_dir_registry=registry) + self.assertIsNotNone(path) + self.assertEqual(os.path.basename(path), "data_only.bin") + self.assertEqual(status, "data_dir") + + def test_167b_unsourceable_skips_data_dir_name_match(self): + """The cache walk matches on filename, so unsourceable has to skip it.""" + data_dir = os.path.join(self.root, "data", "other-core") + os.makedirs(data_dir, exist_ok=True) + with open(os.path.join(data_dir, "shared_name.dat"), "wb") as f: + f.write(b"ANOTHER CORE DEFINITIONS") + + registry = {"other-core": {"local_cache": data_dir}} + + fe = {"name": "shared_name.dat", "unsourceable": "ships inside the package"} + path, status = resolve_local_file(fe, self.db, data_dir_registry=registry) + self.assertIsNone(path) + self.assertEqual(status, "not_found") + + # A declared hash is content proof, so the cache still answers for it. + import hashlib + + digest = hashlib.sha1(b"ANOTHER CORE DEFINITIONS").hexdigest() + fe = { + "name": "shared_name.dat", + "sha1": digest, + "unsourceable": "ships inside the package", + } + path, status = resolve_local_file(fe, self.db, data_dir_registry=registry) + self.assertIsNotNone(path) + self.assertEqual(status, "data_dir_hash_exact") + + +class TestE2EGenerateTruth(E2EFixture): + """generate_platform_truth over the synthetic profiles.""" + + def test_168_generate_truth_basic(self): + """generate_platform_truth resolves cores and builds system truth.""" + import yaml as _yaml + + profile = { + "emulator": "TestCore", + "type": "libretro", + "systems": ["test-system"], + "cores": ["testcore"], + "files": [ + { + "name": "bios.bin", + "system": "test-system", + "required": True, + "sha1": "aabbccdd" * 5, + "md5": "11223344" * 4, + "size": 1024, + "path": "TestConsole/bios.bin", + "source_ref": "main.cpp:42", + }, + ], + } + profile_path = os.path.join(self.emulators_dir, "testcore.yml") + with open(profile_path, "w") as f: + _yaml.dump(profile, f) + + # Clear profile cache so fresh load picks up our file + from model.profiles import emulator_profiles_cache + + emulator_profiles_cache.clear() + + profiles = load_emulator_profiles(self.emulators_dir) + config = {"cores": ["testcore"]} + + result = generate_platform_truth( + "testplat", + config, + {}, + profiles, + db=None, + data_registry={}, + ) + + self.assertEqual(result["platform"], "testplat") + self.assertTrue(result["generated"]) + self.assertIn("test-system", result["systems"]) + sys_files = result["systems"]["test-system"]["files"] + self.assertEqual(len(sys_files), 1) + fe = sys_files[0] + self.assertEqual(fe["name"], "bios.bin") + self.assertTrue(fe["required"]) + self.assertEqual(fe["sha1"], "aabbccdd" * 5) + self.assertIn("testcore", fe["_cores"]) + self.assertIn("main.cpp:42", fe["_source_refs"]) + + def test_169_generate_truth_mode_filtering(self): + """generate_platform_truth excludes standalone-only files for all_libretro.""" + import yaml as _yaml + from model.profiles import emulator_profiles_cache + + profile = { + "emulator": "DualMode", + "type": "standalone + libretro", + "systems": ["test-system"], + "cores": ["dualmode"], + "files": [ + { + "name": "both.bin", + "system": "test-system", + "required": True, + "mode": "both", + "sha1": "aaaa", + }, + { + "name": "lr_only.bin", + "system": "test-system", + "required": True, + "mode": "libretro", + "sha1": "bbbb", + }, + { + "name": "sa_only.bin", + "system": "test-system", + "required": True, + "mode": "standalone", + "sha1": "cccc", + }, + {"name": "nomode.bin", "system": "test-system", "required": True, "sha1": "dddd"}, + ], + } + with open(os.path.join(self.emulators_dir, "dualmode.yml"), "w") as f: + _yaml.dump(profile, f) + + emulator_profiles_cache.clear() + profiles = load_emulator_profiles(self.emulators_dir) + config = {"cores": "all_libretro"} + + result = generate_platform_truth("testplat", config, {}, profiles, data_registry={}) + names = {fe["name"] for fe in result["systems"]["test-system"]["files"]} + + self.assertIn("both.bin", names) + self.assertIn("lr_only.bin", names) + self.assertIn("nomode.bin", names) + self.assertNotIn("sa_only.bin", names) + + def test_170_generate_truth_standalone_cores(self): + """generate_platform_truth uses standalone mode for standalone_cores.""" + import yaml as _yaml + from model.profiles import emulator_profiles_cache + + profile = { + "emulator": "DualCore", + "type": "standalone + libretro", + "systems": ["test-system"], + "cores": ["dualcore"], + "files": [ + { + "name": "lr_file.bin", + "system": "test-system", + "required": True, + "mode": "libretro", + "sha1": "aaaa", + }, + { + "name": "sa_file.bin", + "system": "test-system", + "required": True, + "mode": "standalone", + "sha1": "bbbb", + }, + ], + } + with open(os.path.join(self.emulators_dir, "dualcore.yml"), "w") as f: + _yaml.dump(profile, f) + + emulator_profiles_cache.clear() + profiles = load_emulator_profiles(self.emulators_dir) + config = { + "cores": ["dualcore"], + "standalone_cores": ["dualcore"], + } + + result = generate_platform_truth("testplat", config, {}, profiles, data_registry={}) + names = {fe["name"] for fe in result["systems"]["test-system"]["files"]} + + self.assertIn("sa_file.bin", names) + self.assertNotIn("lr_file.bin", names) + + def test_171_generate_truth_dedup_required_wins(self): + """Dedup merges cores and required=True wins over required=False.""" + import yaml as _yaml + from model.profiles import emulator_profiles_cache + + core_a = { + "emulator": "CoreA", + "type": "libretro", + "systems": ["test-system"], + "cores": ["core_a"], + "files": [ + { + "name": "shared.bin", + "system": "test-system", + "required": False, + "source_ref": "a.cpp:10", + "sha1": "aaaa", + }, + ], + } + core_b = { + "emulator": "CoreB", + "type": "libretro", + "systems": ["test-system"], + "cores": ["core_b"], + "files": [ + { + "name": "shared.bin", + "system": "test-system", + "required": True, + "source_ref": "b.cpp:20", + "sha1": "aaaa", + }, + ], + } + for name, data in [("core_a", core_a), ("core_b", core_b)]: + with open(os.path.join(self.emulators_dir, f"{name}.yml"), "w") as f: + _yaml.dump(data, f) + + emulator_profiles_cache.clear() + profiles = load_emulator_profiles(self.emulators_dir) + config = {"cores": ["core_a", "core_b"]} + + result = generate_platform_truth("testplat", config, {}, profiles, data_registry={}) + sys_files = result["systems"]["test-system"]["files"] + self.assertEqual(len(sys_files), 1) + + fe = sys_files[0] + self.assertEqual(fe["name"], "shared.bin") + self.assertTrue(fe["required"]) + self.assertIn("core_a", fe["_cores"]) + self.assertIn("core_b", fe["_cores"]) + self.assertIn("a.cpp:10", fe["_source_refs"]) + self.assertIn("b.cpp:20", fe["_source_refs"]) + + def test_172_generate_truth_coverage_metadata(self): + """Coverage tracks profiled vs unprofiled cores.""" + import yaml as _yaml + from model.profiles import emulator_profiles_cache + + profile = { + "emulator": "ProfiledCore", + "type": "libretro", + "systems": ["test-system"], + "cores": ["profiled_core"], + "files": [ + {"name": "fw.bin", "system": "test-system", "required": True}, + ], + } + with open(os.path.join(self.emulators_dir, "profiled_core.yml"), "w") as f: + _yaml.dump(profile, f) + + emulator_profiles_cache.clear() + profiles = load_emulator_profiles(self.emulators_dir) + config = {"cores": ["profiled_core", "unprofiled_core"]} + + result = generate_platform_truth("testplat", config, {}, profiles, data_registry={}) + cov = result["_coverage"] + + self.assertEqual(cov["cores_profiled"], 1) + self.assertNotIn( + "unprofiled_core", [name for name in profiles if name == "unprofiled_core"] + ) + # unprofiled_core has no profile YAML so resolve_platform_cores + # won't include it, so cores_resolved reflects only matched profiles + self.assertEqual(cov["cores_resolved"], 1) + self.assertNotIn("unprofiled_core", cov["cores_unprofiled"]) + + +class TestE2EManifest(E2EFixture): + """Install manifests and their agreement with the ZIP.""" + + def test_90_registry_install_metadata(self): + """Registry install section is accessible.""" + import yaml + + with open("platforms/_registry.yml") as f: + registry = yaml.safe_load(f) + for name in ( + "retroarch", + "batocera", + "emudeck", + "recalbox", + "retrobat", + "retrodeck", + "lakka", + "romm", + "bizhawk", + ): + plat = registry["platforms"][name] + self.assertIn("install", plat, f"{name} missing install section") + self.assertIn("detect", plat["install"]) + self.assertIsInstance(plat["install"]["detect"], list) + for hint in plat["install"]["detect"]: + self.assertIn("os", hint) + # EmuDeck has standalone_copies + self.assertIn( + "standalone_copies", + registry["platforms"]["emudeck"]["install"], + ) + + def test_91_manifest_required_only_drops_optional_files(self): + """A manifest named _required must hold only the required files. + + The filename carried the narrowing while the content did not, so + install.py fetched every optional file for a user who asked for the + required set, and --all-variants wrote three manifests that duplicated + their non-required twins. + """ + from packs.manifest import generate_manifest + + registry_path = os.path.join(self.platforms_dir, "_test_registry.yml") + with open(registry_path, "w") as fh: + yaml.dump({"platforms": {"test_existence": {"install": {}}}}, fh) + + def names(required_only): + manifest = generate_manifest( + "test_existence", + self.platforms_dir, + self.db, + self.bios_dir, + registry_path, + emulators_dir=self.emulators_dir, + offline=True, + required_only=required_only, + ) + return {entry["dest"] for entry in manifest["files"]} + + every = names(False) + required = names(True) + self.assertIn("present_req.bin", every) + self.assertIn("present_opt.bin", every) + self.assertIn("present_req.bin", required) + self.assertNotIn( + "present_opt.bin", + required, + "an optional file reached a manifest built with required_only", + ) + + def test_91_generate_manifest(self): + """generate_manifest returns valid manifest dict with expected fields.""" + from packs.manifest import generate_manifest + + # Create a minimal registry file for the test + registry_path = os.path.join(self.platforms_dir, "_test_registry.yml") + registry_data = { + "platforms": { + "test_existence": { + "install": { + "detect": [ + { + "os": "linux", + "method": "path_exists", + "path": "/test/bios", + } + ], + }, + }, + }, + } + with open(registry_path, "w") as fh: + yaml.dump(registry_data, fh) + + manifest = generate_manifest( + "test_existence", + self.platforms_dir, + self.db, + self.bios_dir, + registry_path, + emulators_dir=self.emulators_dir, + offline=True, + ) + + self.assertEqual(manifest["manifest_version"], 2) + self.assertEqual(manifest["regions"], []) + self.assertEqual(manifest["platform"], "test_existence") + self.assertEqual(manifest["display_name"], "TestExistence") + self.assertIn("generated", manifest) + self.assertIn("files", manifest) + self.assertIsInstance(manifest["files"], list) + self.assertEqual(manifest["total_files"], len(manifest["files"])) + self.assertEqual(manifest["total_omitted"], len(manifest["omitted_files"])) + self.assertGreater(len(manifest["files"]), 0) + self.assertEqual(manifest["base_destination"], "system") + self.assertEqual( + manifest["detect"], + registry_data["platforms"]["test_existence"]["install"]["detect"], + ) + + for f in manifest["files"]: + self.assertIn("dest", f) + self.assertIn("sha1", f) + self.assertIn("size", f) + self.assertIn("repo_path", f) + self.assertIn("cores", f) + self.assertIsInstance(f["size"], int) + self.assertGreater(len(f["sha1"]), 0) + + def test_91_manifest_version_is_the_platform_list_version(self): + """The manifest names the version of the list it was built from. + + It was the constant "1.0" for every platform, so the installer could + not tell which Batocera or Recalbox release a list described. Two + platforms of different versions show the value comes from each YAML. + A YAML without one, an inheriting child included, is refused rather + than written with a stand-in or its parent's version. + """ + from model.platforms import _platform_config_cache + from packs.manifest import generate_manifest + + registry_path = os.path.join(self.platforms_dir, "_test_registry_version.yml") + with open(registry_path, "w") as fh: + yaml.dump({"platforms": {}}, fh) + with open(os.path.join(self.platforms_dir, "test_md5.yml")) as fh: + config = yaml.safe_load(fh) + config["version"] = "41" + with open(os.path.join(self.platforms_dir, "versioned_md5.yml"), "w") as fh: + yaml.dump(config, fh) + del config["version"] + with open(os.path.join(self.platforms_dir, "unversioned.yml"), "w") as fh: + yaml.dump(config, fh) + _platform_config_cache.clear() + + def version_of(name: str) -> str: + return generate_manifest( + name, self.platforms_dir, self.db, self.bios_dir, registry_path, + emulators_dir=self.emulators_dir, offline=True, + )["version"] + + self.assertEqual(version_of("test_existence"), "9.1") + self.assertEqual(version_of("versioned_md5"), "41") + for name in ("unversioned", "test_inherited"): + with self.subTest(platform=name), \ + self.assertRaisesRegex(ValueError, "records no version"): + version_of(name) + with open(os.path.join(self.platforms_dir, "test_inherited.yml")) as fh: + child = yaml.safe_load(fh) + child["version"] = "2" + with open(os.path.join(self.platforms_dir, "test_inherited.yml"), "w") as fh: + yaml.dump(child, fh) + _platform_config_cache.clear() + self.assertEqual(version_of("test_inherited"), "2") + + def test_91b_manifest_hash_points_at_a_fetchable_file(self): + """A declared hash no local file carries must not blank repo_path. + + install.py builds its download URL from repo_path, so an upstream + hash that resolves to nothing leaves the file unfetchable. + """ + from packs.manifest import generate_manifest + + registry_path = os.path.join(self.platforms_dir, "_test_registry2.yml") + with open(registry_path, "w") as fh: + yaml.dump({"platforms": {"test_existence": {"install": {}}}}, fh) + + config_path = os.path.join(self.platforms_dir, "test_existence.yml") + with open(config_path) as fh: + config = yaml.safe_load(fh) + for system in config.get("systems", {}).values(): + for entry in system.get("files", []): + entry["sha1"] = "0" * 40 # upstream hash, absent from the repo + with open(config_path, "w") as fh: + yaml.dump(config, fh) + from model.platforms import _platform_config_cache + + _platform_config_cache.clear() + + manifest = generate_manifest( + "test_existence", + self.platforms_dir, + self.db, + self.bios_dir, + registry_path, + emulators_dir=self.emulators_dir, + offline=True, + ) + + self.assertGreater(len(manifest["files"]), 0) + self.assertGreater(len(manifest["omitted_files"]), 0) + self.assertTrue( + all( + entry["reason"] in {"hash_mismatch", "not_found"} + for entry in manifest["omitted_files"] + if entry["cores"] is None + ) + ) + for f in manifest["files"]: + if f.get("release_asset"): + continue + self.assertTrue( + f["repo_path"], + f"{f['dest']} has no repo_path, install.py cannot fetch it", + ) + self.assertNotEqual(f["sha1"], "0" * 40) + + def test_92_manifest_matches_zip(self): + """Manifest file destinations match ZIP contents (excluding metadata).""" + from packs.manifest import generate_manifest + from packs.platformpack import generate_pack + + registry_path = os.path.join(self.platforms_dir, "_test_registry.yml") + registry_data = { + "platforms": { + "test_existence": { + "install": {"detect": []}, + }, + }, + } + with open(registry_path, "w") as fh: + yaml.dump(registry_data, fh) + + # Generate ZIP + output_dir = os.path.join(self.root, "pack_manifest_cmp") + os.makedirs(output_dir, exist_ok=True) + zip_path = generate_pack( + "test_existence", + self.platforms_dir, + self.db, + self.bios_dir, + output_dir, + emulators_dir=self.emulators_dir, + offline=True, + ) + self.assertIsNotNone(zip_path) + + # Get ZIP file destinations (exclude metadata) + with zipfile.ZipFile(zip_path) as zf: + zip_names = { + n + for n in zf.namelist() + if not n.rsplit("/", 1)[-1].startswith(("INSTRUCTIONS_", "RENAMED_")) + and n != "manifest.json" + and n != "README.txt" + } + + # Generate manifest + manifest = generate_manifest( + "test_existence", + self.platforms_dir, + self.db, + self.bios_dir, + registry_path, + emulators_dir=self.emulators_dir, + offline=True, + ) + # Detect flat vs nested ZIP to build expected paths + base = manifest.get("base_destination", "") + is_flat = bool(base) and not any( + n.startswith(base + "/") for n in zip_names + ) + manifest_dests = set() + for f in manifest["files"]: + if base and not is_flat: + d = f"{base}/{f['dest']}" + else: + d = f["dest"] + manifest_dests.add(d) + + self.assertEqual(manifest_dests, zip_names) + + +if __name__ == "__main__": + unittest.main() diff --git a/wiki/adding-a-scraper.md b/wiki/adding-a-scraper.md index 4add2fd8b..a3c430ba9 100644 --- a/wiki/adding-a-scraper.md +++ b/wiki/adding-a-scraper.md @@ -518,11 +518,11 @@ the fields listed in [BiosRequirement fields](adding-a-platform.md#biosrequireme ### E2E tests -The project's test suite (`tests/test_e2e.py`) covers scraper integration at the +The `test_e2e_*` modules of the test suite cover scraper integration at the pipeline level. When adding a new scraper, verify that the full pipeline passes: ```bash -python -m unittest tests.test_e2e +python -m unittest tests.test_e2e_truth tests.test_e2e_pack_sources python scripts/pipeline.py --offline ``` diff --git a/wiki/architecture.md b/wiki/architecture.md index db8f3c100..483ef936e 100644 --- a/wiki/architecture.md +++ b/wiki/architecture.md @@ -515,9 +515,9 @@ subset: | File | Coverage | |------|----------| -| `test_e2e.py` | resolution, verification, packs, inheritance, targets, truth and exporters | +| `test_e2e_*.py` | resolution, verification, packs, inheritance, targets, truth and exporters | | `test_profile_sync.py`, `test_upstream.py` | source anchoring, forge parsing, revisions, cache and guarded writes | -| `test_install.py`, `test_audit_regressions.py` | automatic wrappers, manifest boundaries, pipeline exits, strong hashes and safe archives | +| `test_install.py`, `test_audit_*.py` | automatic wrappers, manifest boundaries, pipeline exits, strong hashes and safe archives | | `test_region.py` | region vocabulary, ranking, per-system grouping and repository conformance | | `test_site_exports.py`, `test_site_validation.py` | versioned exports, SQLite, metadata, accessibility structure and complete local-link graph | | parser/provenance modules | MAME, FBNeo, DAT import, merge and provenance joins | @@ -525,10 +525,10 @@ subset: ```bash python -m unittest discover -s tests -t . -v # full suite -python -m unittest tests.test_e2e -v # single module +python -m unittest tests.test_e2e_region -v # single module ``` -`test_e2e.py`, `test_install.py`, `test_provenance.py`, the parser tests, +`test_e2e_*.py`, `test_install.py`, `test_provenance.py`, the parser tests, `test_profile_sync.py` and `test_upstream.py` run on synthetic fixtures with no network and no real BIOS files. `test_pack_integrity.py`, `test_torrentzip.py` and `test_no_case_collisions.py` read the working tree and skip when the data they diff --git a/wiki/testing-guide.md b/wiki/testing-guide.md index 7118660aa..6eca6df66 100644 --- a/wiki/testing-guide.md +++ b/wiki/testing-guide.md @@ -35,7 +35,7 @@ python scripts/run_tests.py --jobs 1 # one at a time Run a single module, or several: ```bash -python -m unittest tests.test_e2e -v +python -m unittest tests.test_e2e_resolution -v python -m unittest tests.test_install tests.test_install_cores -v ``` @@ -62,7 +62,7 @@ Every module in `tests/`, by the area it guards. | Area | Fixtures | Modules | |------|----------|---------| -| Core regression suites | synthetic | `test_e2e`, `test_audit_regressions`, `test_tool_messages` | +| Core regression suites | synthetic | `test_e2e_resolution`, `test_e2e_emulator`, `test_e2e_pack_options`, `test_e2e_truth`, `test_e2e_diff_export`, `test_e2e_pack_sources`, `test_e2e_region`, `test_e2e_search_sets`, `test_audit_project`, `test_audit_docs`, `test_audit_site`, `test_audit_cli`, `test_audit_packs`, `test_audit_manifests`, `test_audit_resolution`, `test_audit_profiles`, `test_tool_messages` | | Import layers | the source of `scripts/` | `test_layers` | | File resolution and identity | synthetic + collection | `test_adler32_resolution`, `test_agnostic_scan`, `test_agnostic_scan_mode`, `test_agnostic_scope`, `test_agnostic_substitute`, `test_archive_build`, `test_archive_choice`, `test_archive_recipes`, `test_bios_companions`, `test_bundled_identity`, `test_casefold_cache`, `test_db_aliases`, `test_declared_names`, `test_derivations`, `test_directory_entries`, `test_extra_identity`, `test_foreign_tree`, `test_foreign_tree_names`, `test_frontend_digest`, `test_game_data_homonyms`, `test_hashing`, `test_held_record`, `test_identity`, `test_maker_folder_names`, `test_md5_pack_context`, `test_name_tiebreak`, `test_nec_filing`, `test_np2_fonts`, `test_owner_resolution`, `test_path_suffix`, `test_proven_name`, `test_resolution_evidence`, `test_sega_filing`, `test_shipped_content`, `test_switch_nca`, `test_twin_declaration_status`, `test_twin_declarations`, `test_validated_choice`, `test_variant_archives`, `test_variant_copies`, `test_variant_choice`, `test_variant_identity`, `test_zipped_member` | | Verification, cross-reference and profile checks | synthetic + profiles | `test_bios_layout`, `test_cache_independent_counts`, `test_case_insensitive_platforms`, `test_checks_have_values`, `test_content_checks`, `test_content_declarations`, `test_core_file_fills_declaration`, `test_core_size_refusal`, `test_cross_reference_sources`, `test_crypto_aes`, `test_crypto_unique_data`, `test_crypto_verify`, `test_data_only_refs`, `test_entry_categories`, `test_file_consumers`, `test_fileless_audit`, `test_flycast_layout`, `test_gap_settlement`, `test_hidden_extras`, `test_launcher_aliases`, `test_launcher_evidence`, `test_launcher_gaps`, `test_launcher_layer`, `test_launcher_paths`, `test_launcher_placement`, `test_native_mode`, `test_no_case_collisions`, `test_path_conflict_status`, `test_path_null_copies`, `test_profile_checks`, `test_profile_names`, `test_profile_paths`, `test_profile_repositories`, `test_romm_hash_rule`, `test_shared_groups`, `test_standalone_links`, `test_standalone_mode`, `test_undeclared_dedup`, `test_unplaced_extras`, `test_validation_scope`, `test_verify_all_dir`, `test_verify_data_dir_notice`, `test_verify_emulator_evidence`, `test_verify_listing`, `test_verify_pack_choice`, `test_verify_release_asset` | @@ -85,13 +85,15 @@ Every module in `tests/`, by the area it guards. ## Test architecture -### test_e2e.py +### test_e2e_*.py -The main regression suite. `TestE2E` exercises the resolution, verification, -pack generation and cross-reference logic, and `StandaloneModeRequiresAStandaloneBuild` -sits beside it for the per-emulator build mode. +The main regression suite, one module per subject. The `TestE2E*` classes +exercise the resolution, verification, pack generation and cross-reference +logic, and `test_e2e_search_sets` holds `StandaloneModeRequiresAStandaloneBuild` +for the per-emulator build mode beside the search-list and archive-set classes. -**Fixture pattern.** `setUp` creates a temporary directory tree with: +**Fixture pattern.** Every `TestE2E*` class inherits `E2EFixture` from +`tests/e2esupport.py`, whose `setUp` creates a temporary directory tree with: - Fake BIOS files (deterministic content for hash computation) - Platform YAML configs (existence mode, MD5 mode, inheritance, shared groups) @@ -253,7 +255,7 @@ A new module starts with `import tests` right after `from __future__ import annotations`. The package import is what keeps a run offline, puts its scratch under `tmp/` and gives it its own installer cache, however the module is started: `discover tests`, `python -m unittest -tests.test_e2e` or `python -m tests.test_e2e`. A test fails on any module +tests.test_e2e_resolution` or `python -m tests.test_e2e_resolution`. A test fails on any module without it. A fix comes with a test that fails without it. Write the test first, watch it