From 2208d16b218a2615943866d0e55bc8847b9416bb Mon Sep 17 00:00:00 2001 From: Abdessamad Derraz <3028866+Abdess@users.noreply.github.com> Date: Tue, 24 Nov 2026 06:35:47 +0100 Subject: [PATCH] refactor: split exporter tests by subject --- tests/exporterssupport.py | 95 + tests/test_exporters.py | 3155 ------------------------ tests/test_exporters_contract.py | 560 +++++ tests/test_exporters_fidelity.py | 383 +++ tests/test_exporters_lists.py | 859 +++++++ tests/test_exporters_reconciliation.py | 850 +++++++ tests/test_exporters_scripts.py | 506 ++++ wiki/adding-a-platform.md | 2 +- wiki/testing-guide.md | 2 +- 9 files changed, 3255 insertions(+), 3157 deletions(-) create mode 100644 tests/exporterssupport.py delete mode 100644 tests/test_exporters.py create mode 100644 tests/test_exporters_contract.py create mode 100644 tests/test_exporters_fidelity.py create mode 100644 tests/test_exporters_lists.py create mode 100644 tests/test_exporters_reconciliation.py create mode 100644 tests/test_exporters_scripts.py diff --git a/tests/exporterssupport.py b/tests/exporterssupport.py new file mode 100644 index 000000000..5fc39b91a --- /dev/null +++ b/tests/exporterssupport.py @@ -0,0 +1,95 @@ +"""Fixtures shared by the native exporter test modules.""" + +from __future__ import annotations + +import tests + +from pathlib import Path + +from resolve.reconcile import build_native_model + + +REPO_ROOT = Path(__file__).resolve().parent.parent + +UPSTREAM_CACHE = REPO_ROOT / ".cache" / "upstream-native" + + +TRUTH = { + "systems": { + "sony-playstation": { + "files": [ + { + "name": "scph5501.bin", + "path": "psx/scph5501.bin", + "md5": "490f666e1afb15b7362b406ed1cea246", + "size": 524288, + "required": True, + "_cores": ["duckstation"], + }, + { + "name": "scph7001.bin", + "path": "psx/scph7001.bin", + "md5": "1e68c231d0896b7eadcad1d7d8e76129", + "size": 524288, + "required": False, + "_cores": ["duckstation"], + }, + # Carries an md5 on purpose: without one it would be dropped + # for being incomplete, and the placeholder guard would never + # be the reason it stayed out. + { + "name": ".bin", + "path": "psx/PLACEHOLDER-MUST-NOT-SHIP.bin", + "md5": "00000000000000000000000000000000", + "size": 1, + "required": False, + "_cores": ["duckstation"], + }, + ], + }, + }, +} + +# The profiles that name the runners: beetle_psx answers to the buildbot's +# mednafen_psx, duckstation has a standalone build. +PROFILES = { + "beetle_psx": {"type": "libretro", "cores": ["mednafen_psx"]}, + "duckstation": {"type": "standalone + libretro"}, +} + +SCRAPED = { + # The cores the platform runs, by its own names: an addition is written + # with the runner that wants it. + "cores": ["atari800", "duckstation", "fuse", "melonds", "o2em", "picodrive", + "snes9x", "beetle_psx"], + "standalone_cores": ["duckstation"], + "systems": { + "sony-playstation": { + "native_id": "psx", + "files": [ + { + "name": "scph5501.bin", + "destination": "psx/scph5501.bin", + "native_system": "psx", + "native_name": "Sony PlayStation", + "md5": "deadbeefdeadbeefdeadbeefdeadbeef", + "core": "libretro/duckstation", + "required": True, + }, + { + "name": "unknown-to-truth.bin", + "destination": "psx/unknown-to-truth.bin", + "native_system": "psx", + "native_name": "Sony PlayStation", + "md5": "11111111111111111111111111111111", + "core": "libretro/duckstation", + "required": True, + }, + ], + }, + }, +} + + +def model(truth: dict = TRUTH, scraped: dict | None = SCRAPED): + return build_native_model(truth, scraped) diff --git a/tests/test_exporters.py b/tests/test_exporters.py deleted file mode 100644 index 1458be147..000000000 --- a/tests/test_exporters.py +++ /dev/null @@ -1,3155 +0,0 @@ -#!/usr/bin/env python3 -"""Native-format exporters. - -export_native.py rewrites each platform's own file, corrected: Recalbox's -es_bios.xml, Batocera's systems list, RetroDECK's manifests. The point is -that a maintainer can take the output and use it, so what matters is -whether the platform would still read it, and whether anything it already -declared went missing on the way through. - -The fidelity cases read the platforms' real files from the upstream cache -and skip when it has not been populated (python scripts/export_native.py ---all --fetch), because a test that needs the network is not a test. -""" - -from __future__ import annotations - -import tests - -import difflib -import io -import json -import os -import re -import subprocess -import sys -import tempfile -import unittest -import xml.etree.ElementTree as ET -import zipfile -from collections import OrderedDict -from pathlib import Path - -from model.registry import list_registered_platforms -from model.platforms import load_platform_config, native_layer -from model.profiles import load_emulator_profiles -from model.safeparse import parse_untrusted_xml -from exporter import discover_exporters -from exporter.base_exporter import BaseExporter -from exporter.originals import SOURCES_INDEX, collect_originals, fetch, pinned_base, source_key -from exporter.landed import landed_changes -from resolve.nativemodel import NativeFile, NativeSystem, Report -from resolve.reconcile import build_native_model - -REPO_ROOT = Path(__file__).resolve().parent.parent - -UPSTREAM_CACHE = REPO_ROOT / ".cache" / "upstream-native" - - -def _without_native_list() -> set[str]: - """Registered platforms whose code names no BIOS file to hand back.""" - import yaml - - registry = yaml.safe_load((REPO_ROOT / "platforms" / "_registry.yml").read_text()) - return { - name for name, entry in registry["platforms"].items() - if entry.get("native_list") == "none" - } - -TRUTH = { - "systems": { - "sony-playstation": { - "files": [ - { - "name": "scph5501.bin", - "path": "psx/scph5501.bin", - "md5": "490f666e1afb15b7362b406ed1cea246", - "size": 524288, - "required": True, - "_cores": ["duckstation"], - }, - { - "name": "scph7001.bin", - "path": "psx/scph7001.bin", - "md5": "1e68c231d0896b7eadcad1d7d8e76129", - "size": 524288, - "required": False, - "_cores": ["duckstation"], - }, - # Carries an md5 on purpose: without one it would be dropped - # for being incomplete, and the placeholder guard would never - # be the reason it stayed out. - { - "name": ".bin", - "path": "psx/PLACEHOLDER-MUST-NOT-SHIP.bin", - "md5": "00000000000000000000000000000000", - "size": 1, - "required": False, - "_cores": ["duckstation"], - }, - ], - }, - }, -} - -# The profiles that name the runners: beetle_psx answers to the buildbot's -# mednafen_psx, duckstation has a standalone build. -PROFILES = { - "beetle_psx": {"type": "libretro", "cores": ["mednafen_psx"]}, - "duckstation": {"type": "standalone + libretro"}, -} - -SCRAPED = { - # The cores the platform runs, by its own names: an addition is written - # with the runner that wants it. - "cores": ["atari800", "duckstation", "fuse", "melonds", "o2em", "picodrive", - "snes9x", "beetle_psx"], - "standalone_cores": ["duckstation"], - "systems": { - "sony-playstation": { - "native_id": "psx", - "files": [ - { - "name": "scph5501.bin", - "destination": "psx/scph5501.bin", - "native_system": "psx", - "native_name": "Sony PlayStation", - "md5": "deadbeefdeadbeefdeadbeefdeadbeef", - "core": "libretro/duckstation", - "required": True, - }, - { - "name": "unknown-to-truth.bin", - "destination": "psx/unknown-to-truth.bin", - "native_system": "psx", - "native_name": "Sony PlayStation", - "md5": "11111111111111111111111111111111", - "core": "libretro/duckstation", - "required": True, - }, - ], - }, - }, -} - - -def model(truth: dict = TRUTH, scraped: dict | None = SCRAPED): - return build_native_model(truth, scraped) - - -class Reconciliation(unittest.TestCase): - """The platform's file corrected, not replaced by ours.""" - - def test_a_bare_truth_name_is_not_a_path_suffix(self): - """fbneo's boot.bin has no path, while libretro's dc/boot.bin ends in - /boot.bin. The suffix paired them past the size guard and wrote the - 480-byte file's size and hashes over the 2 MB Dreamcast BIOS.""" - truth = {"systems": {"sega-dreamcast": {"files": [ - {"name": "boot.bin", "size": 480, "crc32": "f0774fc2"}]}}} - scraped = {"systems": {"sega-dreamcast": {"native_id": "dc", "files": [ - {"name": "boot.bin", "destination": "dc/boot.bin", "native_system": "dc", - "size": 2097152, "crc32": "89f2b1a1"}]}}} - systems, report = build_native_model(truth, scraped) - platform_entry = next( - fe for fe in systems["dc"].files if fe.destination == "dc/boot.bin" - ) - self.assertIsNone(platform_entry.truth) - self.assertEqual(report.hashes_corrected, []) - - def test_a_contradicted_hash_takes_no_platform_size(self): - """geolith's neocdz.zip md5 contradicts System.dat's: the export - wrote that md5 beside System.dat's 953078 bytes.""" - entry = NativeFile( - "neocdz.zip", "neocdz.zip", "neocd", - platform={"md5": "a" * 32, "size": 953078}, - truth={"md5": "b" * 32}, - ) - self.assertEqual((entry.hash("md5"), entry.size()), ("b" * 32, None)) - agreeing = NativeFile( - "neocdz.zip", "neocdz.zip", "neocd", - platform={"md5": "b" * 32, "size": 955352}, truth={"md5": "b" * 32}, - ) - self.assertEqual(agreeing.size(), 955352) - - def test_a_size_list_keeps_the_platform_size_it_accepts(self): - """geargrafx accepts syscard3.pce headerless or headered, and System.dat - states 262144 for the same dump. The list came first, stated no - single size, and the rom line went out with none.""" - both = NativeFile( - "syscard3.pce", "syscard3.pce", "pce", - platform={"md5": "c" * 32, "size": 262144}, - truth={"md5": "c" * 32, "size": [262144, 262656]}, - ) - self.assertEqual(both.size(), 262144) - refused = NativeFile( - "syscard3.pce", "syscard3.pce", "pce", - platform={"md5": "c" * 32, "size": 131072}, - truth={"md5": "c" * 32, "size": [262144, 262656]}, - ) - self.assertIsNone(refused.size()) - - def test_a_file_the_truth_says_nothing_about_is_kept(self): - systems, _ = model() - names = {fe.name for fe in systems["psx"].files} - self.assertIn("unknown-to-truth.bin", names) - - def test_the_truth_overrides_a_hash_the_platform_got_wrong(self): - systems, report = model() - entry = next(fe for fe in systems["psx"].files if fe.name == "scph5501.bin") - self.assertEqual(entry.hash("md5"), "490f666e1afb15b7362b406ed1cea246") - self.assertTrue(any("scph5501" in c for c in report.hashes_corrected)) - - def test_a_file_only_the_truth_knows_is_added(self): - systems, report = model() - names = {fe.name for fe in systems["psx"].files} - self.assertIn("scph7001.bin", names) - self.assertEqual(report.files_added, 1) - - def test_a_placeholder_is_never_added(self): - systems, _ = model() - names = {fe.name for fe in systems["psx"].files} - self.assertNotIn(".bin", names) - - def test_a_name_match_does_not_take_a_later_entrys_destination(self): - """dosbox-x's system.rom (alias bios.rom, no path) came before - np2kai's np2kai/bios.rom in the truth, took Batocera's - np2kai/BIOS.ROM by name and wrote an IBM PCjr md5 on it.""" - truth = {"systems": {"nec-pc-98": {"files": [ - {"name": "system.rom", "aliases": ["bios.rom"], "md5": "c" * 32}, - {"name": "bios.rom", "path": "np2kai/bios.rom"}, - ]}}} - scraped = {"systems": {"nec-pc-98": {"native_id": "pc98", "files": [ - {"name": "BIOS.ROM", "destination": "np2kai/BIOS.ROM", - "native_system": "pc98", "md5": "e" * 32}, - ]}}} - systems, report = build_native_model(truth, scraped) - entry = systems["pc98"].files[0] - self.assertEqual(entry.truth["path"], "np2kai/bios.rom") - self.assertEqual(entry.hash("md5"), "e" * 32) - self.assertEqual(report.hashes_corrected, []) - self.assertEqual(report.files_added, 0) - - def test_a_path_does_not_outrank_the_hash_another_line_carries(self): - """The truth's MSX.rom joins bluemsx's path and fmsx's md5. Paired by - path, fmsx's md5 replaced the blueMSX dump on Recalbox's - Machines/Shared Roms/MSX.rom line while fmsx's own line held it.""" - truth = {"systems": {"microsoft-msx": {"files": [ - {"name": "MSX.rom", "path": "Machines/Shared Roms/MSX.rom", - "md5": "a" * 32}, - ]}}} - scraped = {"systems": {"microsoft-msx": {"native_id": "msx", "files": [ - {"name": "MSX.rom", "destination": "Machines/Shared Roms/MSX.rom", - "native_system": "msx", "md5": "b" * 32}, - {"name": "MSX.ROM", "destination": "MSX.ROM", - "native_system": "msx", "md5": "a" * 32}, - ]}}} - systems, report = build_native_model(truth, scraped) - bluemsx, fmsx = systems["msx"].files - self.assertIsNone(bluemsx.truth) - self.assertEqual(bluemsx.hash("md5"), "b" * 32) - self.assertIs(fmsx.truth, truth["systems"]["microsoft-msx"]["files"][0]) - self.assertEqual(report.hashes_corrected, []) - - def test_a_name_the_core_opens_is_added_beside_its_content(self): - """fuse opens fuse/128-1.rom and fuse/128p-1.rom, one dump. Recalbox - declares only 128p-1.rom. Paired entry by entry, 128-1.rom took that - line by hash and was never added. A core that opens a name is not - served by the same bytes under another one.""" - truth = {"systems": {"sinclair-zx-spectrum": {"files": [ - {"name": "128p-1.rom", "path": "fuse/128p-1.rom", "md5": "d" * 32}, - {"name": "128-1.rom", "path": "fuse/128-1.rom", "md5": "d" * 32}, - ]}}} - scraped = {"systems": {"sinclair-zx-spectrum": {"native_id": "zx", "files": [ - {"name": "128p-1.rom", "destination": "fuse/128p-1.rom", - "native_system": "zx", "md5": "d" * 32}, - ]}}} - systems, report = build_native_model(truth, scraped) - own, added = systems["zx"].files - self.assertEqual(own.truth["name"], "128p-1.rom") - self.assertEqual(added.destination, "fuse/128-1.rom") - self.assertEqual(report.files_added, 1) - - def test_a_hash_the_code_does_not_check_corrects_nothing(self): - """dosbox checks MT32_CONTROL.ROM by sha1 and size. The truth accepts - System.dat's sha1 but carries the md5 and crc of another revision, - and the export wrote those beside System.dat's sha1: a record no - file satisfies, counted as a correction.""" - truth = {"systems": {"dos": {"files": [ - {"name": "MT32_CONTROL.ROM", "sha1": ["1" * 40, "2" * 40], - "md5": "a" * 32, "crc32": "aaaaaaaa", "size": 65536, - "validation": ["sha1", "size"]}, - ]}}} - scraped = {"systems": {"dos": {"native_id": "dos", "files": [ - {"name": "MT32_CONTROL.ROM", "destination": "MT32_CONTROL.ROM", - "native_system": "dos", "sha1": "2" * 40, "md5": "b" * 32, - "crc32": "bbbbbbbb", "size": 65536}, - ]}}} - systems, report = build_native_model(truth, scraped) - entry = systems["dos"].files[0] - self.assertEqual( - [entry.record_hash(f) for f in ("crc32", "md5", "sha1")], - ["bbbbbbbb", "b" * 32, "2" * 40], - ) - self.assertEqual(entry.hashes("md5"), ["b" * 32]) - self.assertEqual(report.hashes_corrected, []) - - def test_a_size_checked_file_keeps_the_dump_the_platform_names(self): - """pcsx_rearmed and DuckStation check scph1001.bin by size. The - truth's md5 is v4.1's, Batocera names v2.0: the export replaced it - and the frontend then refused the v2.0 the cores load. Nor is a - blank md5 filled with one revision the code does not require.""" - truth = {"systems": {"sony-playstation": {"files": [ - {"name": "scph1001.bin", "md5": "a" * 32, "size": 524288, - "validation": ["size"]}, - {"name": "scph5500.bin", "md5": "c" * 32, "size": 524288, - "validation": ["size"]}, - ]}}} - scraped = {"systems": {"sony-playstation": {"native_id": "psx", "files": [ - {"name": "scph1001.bin", "destination": "scph1001.bin", - "native_system": "psx", "md5": "b" * 32}, - {"name": "scph5500.bin", "destination": "scph5500.bin", - "native_system": "psx"}, - ]}}} - systems, report = build_native_model(truth, scraped) - v20, blank = systems["psx"].files - self.assertEqual(v20.hash("md5"), "b" * 32) - self.assertEqual(blank.hash("md5"), "") - self.assertEqual((report.hashes_corrected, blank.filled), ([], [])) - - def test_a_hash_beside_one_checked_value_still_corrects(self): - """A core that checks one crc32 pins one dump, and the md5 of that - dump is no less true: a platform md5 against it is corrected.""" - truth = {"systems": {"coco": {"files": [ - {"name": "bas12.rom", "crc32": "aaaaaaaa", "md5": "a" * 32, - "validation": ["crc32"]}, - ]}}} - scraped = {"systems": {"coco": {"native_id": "coco", "files": [ - {"name": "bas12.rom", "destination": "bas12.rom", - "native_system": "coco", "md5": "b" * 32}, - ]}}} - systems, report = build_native_model(truth, scraped) - self.assertEqual(systems["coco"].files[0].hash("md5"), "a" * 32) - self.assertEqual(report.hashes_corrected, ["coco/bas12.rom md5"]) - - def test_a_hash_the_cores_disagree_on_corrects_nothing(self): - """armsx2 and yaps2 declare different revisions of GameIndex.yaml. - The truth kept armsx2's, and the export wrote it over System.dat's - line for LRPS2 as a hash and size correction.""" - import contextlib - - from resolve import truth as truth_module - - entry = {"name": "GameIndex.yaml", "sha1": "1" * 40, "size": 2690355} - with contextlib.redirect_stderr(io.StringIO()): - truth_module._merge_hashes( - entry, {"name": "GameIndex.yaml", "sha1": "2" * 40}, "yaps2" - ) - self.assertEqual(entry["hash_conflict"], ["sha1"]) - truth = {"systems": {"sony-playstation-2": {"files": [entry]}}} - scraped = {"systems": {"sony-playstation-2": {"native_id": "ps2", "files": [ - {"name": "GameIndex.yaml", "destination": "pcsx2/resources/GameIndex.yaml", - "native_system": "ps2", "sha1": "3" * 40, "size": 1737799}, - ]}}} - systems, report = build_native_model(truth, scraped) - line = systems["ps2"].files[0] - self.assertEqual((line.hash("sha1"), line.size()), ("3" * 40, 1737799)) - self.assertEqual(report.hashes_corrected, []) - - def test_the_diff_names_no_mismatch_the_code_does_not_check(self): - from resolve.platformdiff import _diff_system - truth_sys = {"files": [{"name": "scph1001.bin", "md5": "a" * 32, - "validation": ["size"]}]} - scraped_sys = {"files": [{"name": "scph1001.bin", "md5": "b" * 32}]} - self.assertNotIn("hash_mismatch", _diff_system(truth_sys, scraped_sys)) - - def test_a_label_is_never_added(self): - """A name only a content-scanning core gives is no file to hold.""" - truth = {"systems": {"sony-playstation": {"files": [ - {"name": "scph1001_v20.bin", "md5": "a" * 32, - "_cores": ["duckstation"], "_named_by": []}, - {"name": "scph5903.bin", "md5": "c" * 32, - "_cores": ["beetle_psx"], "_named_by": ["beetle_psx"]}, - ]}}} - scraped = {"systems": {"sony-playstation": {"native_id": "psx", "files": [ - {"name": "scph5501.bin", "destination": "scph5501.bin", - "native_system": "psx", "md5": "d" * 32}]}}} - systems, report = build_native_model(truth, scraped) - self.assertEqual([fe.name for fe in systems["psx"].files], - ["scph5501.bin", "scph5903.bin"]) - self.assertEqual(report.files_added, 1) - - def test_a_label_pairs_by_content_only(self): - """DuckStation's and rustation's scph5000.bin labels carried another - dump's md5 and, paired by name, replaced System.dat's scph5000.bin.""" - truth = {"systems": {"sony-playstation": {"files": [ - {"name": "scph5000.bin", "md5": "a" * 32, - "_cores": ["duckstation"], "_named_by": []}, - {"name": "other_label.bin", "md5": "e" * 32, "sha256": "f" * 64, - "_cores": ["duckstation"], "_named_by": []}, - ]}}} - scraped = {"systems": {"sony-playstation": {"native_id": "psx", "files": [ - {"name": "scph5000.bin", "destination": "scph5000.bin", - "native_system": "psx", "md5": "b" * 32}, - {"name": "scph7001.bin", "destination": "scph7001.bin", - "native_system": "psx", "md5": "e" * 32}, - ]}}} - systems, report = build_native_model(truth, scraped) - scph5000, scph7001 = systems["psx"].files - self.assertIsNone(scph5000.truth) - self.assertEqual(scph7001.truth["name"], "other_label.bin") - self.assertEqual(report.hashes_corrected, []) - - def test_the_diff_names_no_missing_label(self): - from resolve.platformdiff import _diff_system - truth_sys = {"files": [{"name": "scph1001_v20.bin", "md5": "a" * 32, - "_cores": ["duckstation"], "_named_by": []}]} - self.assertNotIn("missing", _diff_system(truth_sys, {"files": []})) - - def test_a_bundled_truth_entry_is_never_added(self): - truth = {"systems": {"neogeo": {"files": [ - {"name": "gngeo_data.zip", "md5": "a" * 32, "bundled": True, - "_cores": ["gngeopi"], "_named_by": ["gngeopi"], "_brought_by": []}, - {"name": "neogeo.zip", "md5": "b" * 32, - "_cores": ["gngeopi"], "_named_by": ["gngeopi"], - "_brought_by": ["gngeopi:standalone"]}, - ]}}} - systems, report = build_native_model(truth, {"systems": {}}) - self.assertEqual([fe.name for fe in systems["neogeo"].files], ["neogeo.zip"]) - self.assertEqual(report.files_added, 1) - - def test_a_bundled_entry_the_platform_declares_is_kept(self): - truth = {"systems": {"neogeo": {"files": [ - {"name": "gngeo_data.zip", "md5": "a" * 32, "bundled": True, - "_cores": ["gngeopi"], "_named_by": ["gngeopi"], "_brought_by": []}]}}} - scraped = {"systems": {"neogeo": {"native_id": "neogeo", "files": [ - {"name": "gngeo_data.zip", "destination": "gngeo_data.zip", - "native_system": "neogeo", "md5": "c" * 32}]}}} - systems, _ = build_native_model(truth, scraped) - (kept,) = systems["neogeo"].files - self.assertIsNotNone(kept.truth) - - def test_the_runner_is_the_build_that_needs_the_file(self): - """ROCKNIX runs ARMSX2 standalone only, and the libretro build's - pcsx2/resources entries went out as armsx2-sa files.""" - truth = {"systems": {"sony-playstation-2": {"files": [ - {"name": "GameIndex.yaml", "md5": "a" * 32, - "_cores": ["armsx2"], "_named_by": ["armsx2"], - "_brought_by": ["armsx2:libretro"]}]}}} - scraped = {"cores": ["armsx2"], "standalone_cores": ["armsx2"], "systems": {}} - systems, _ = build_native_model(truth, scraped) - (added,) = systems["sony-playstation-2"].files - self.assertEqual(added.runners, [(False, "armsx2")]) - - def test_the_diff_names_no_missing_bundled_file(self): - from resolve.platformdiff import _diff_system - truth_sys = {"files": [{"name": "gngeo_data.zip", "md5": "a" * 32, "bundled": True, - "_cores": ["gngeopi"], "_named_by": ["gngeopi"], - "_brought_by": []}]} - self.assertNotIn("missing", _diff_system(truth_sys, {"files": []})) - - def test_the_diff_pairs_by_the_same_rule(self): - """diff_truth reads the same pairing, or it names a mismatch the - export does not correct.""" - from resolve.platformdiff import _diff_system - truth_sys = {"files": [ - {"name": "system.rom", "aliases": ["bios.rom"], "md5": "c" * 32}, - {"name": "bios.rom", "path": "np2kai/bios.rom"}, - ]} - scraped_sys = {"files": [ - {"name": "BIOS.ROM", "destination": "np2kai/BIOS.ROM", "md5": "e" * 32}, - ]} - self.assertNotIn("hash_mismatch", _diff_system(truth_sys, scraped_sys)) - - def test_systems_are_keyed_by_the_name_the_platform_uses(self): - systems, _ = model() - self.assertEqual(sorted(systems), ["psx"]) - - def test_the_platform_own_grouping_survives_a_collapsed_slug(self): - """Several native systems can share one of our slugs. - - Recalbox files pcengine, pcenginecd and supergrafx under one slug. - Grouping on the slug would publish one of the three and drop the - rest, which is how eleven Recalbox platforms went missing. - """ - scraped = { - "systems": { - "nec-pc-engine": { - "native_id": "pcengine", - "files": [ - { - "name": "syscard3.pce", - "destination": "pcengine/syscard3.pce", - "native_system": "pcengine", - "md5": "38179df8f4ac870017db21ebcbf53114", - }, - { - "name": "syscard3.pce", - "destination": "supergrafx/syscard3.pce", - "native_system": "supergrafx", - "md5": "38179df8f4ac870017db21ebcbf53114", - }, - ], - }, - }, - } - systems, _ = build_native_model({"systems": {}}, scraped) - self.assertEqual(sorted(systems), ["pcengine", "supergrafx"]) - - def test_a_container_md5_leaves_a_zipped_file_md5_alone(self): - """Batocera's checkInsideZip compares a zippedFile item's md5 with - the member's. A profile's container md5 was written in its place - and counted as a hash updated to the emulator source.""" - scraped = {"systems": {"pc6001": {"native_id": "pc6001", "files": [ - {"name": "pc6001.zip", "destination": "pc6001.zip", "md5": "1" * 32, - "zipped_file": "basicrom.60"}, - ]}}} - truth = {"systems": {"pc6001": {"files": [ - {"name": "pc6001.zip", "md5": "2" * 32}, - ]}}} - systems, report = build_native_model(truth, scraped) - entry = systems["pc6001"].files[0] - self.assertEqual(entry.corrections, []) - self.assertEqual(report.hashes_corrected, []) - self.assertEqual(entry.hashes("md5"), ["1" * 32]) - - def test_an_addition_joins_the_native_id_its_cores_read(self): - """RetroDECK's arcade spans mame and fbneo with no primary id. Every - addition went under fbneo, the first sorted, MAME device archives - included. One the cores do not settle is not written.""" - scraped = {"systems": {"arcade": {"files": [ - {"name": "neogeo.zip", "destination": "neogeo.zip", "native_system": "mame"}, - {"name": "pgm.zip", "destination": "pgm.zip", "native_system": "fbneo"}, - ]}}} - truth = {"systems": {"arcade": {"files": [ - {"name": "neogeo.zip", "_cores": ["mame"]}, - {"name": "pgm.zip", "_cores": ["fbneo"]}, - {"name": "a2autokbd.zip", "_cores": ["mame"]}, - {"name": "dkong.zip", "_cores": ["mame", "fbneo"]}, - ]}}} - systems, report = build_native_model(truth, scraped) - self.assertEqual( - [fe.name for fe in systems["mame"].files if fe.platform is None], - ["a2autokbd.zip"], - ) - self.assertFalse([fe for fe in systems["fbneo"].files if fe.platform is None]) - self.assertEqual(report.unattributed, ["arcade/dkong.zip"]) - - def test_an_entry_the_platform_declares_without_a_hash_is_still_written(self): - """Batocera and RetroBat both ship entries with an empty md5.""" - scraped = { - "systems": { - "nintendo-ds": { - "native_id": "nds", - "files": [ - { - "name": "firmware.bin", - "destination": "firmware.bin", - "native_system": "nds", - } - ], - } - } - } - systems, _ = build_native_model({"systems": {}}, scraped) - entry = systems["nds"].files[0] - self.assertTrue(_BaseRule().writable(entry, require="md5")) - - def test_no_format_drops_what_the_platform_already_declares(self): - """An export poorer than the file it corrects is not usable.""" - systems, _ = model() - for name, cls in discover_exporters().items(): - for system in systems.values(): - for entry in system.files: - if entry.platform is None: - continue - with self.subTest(platform=name, file=entry.name): - self.assertTrue(cls().writable(entry)) - - def test_an_addition_the_format_cannot_express_is_refused(self): - truth = { - "systems": { - "nintendo-ds": {"files": [{"name": "no-hash.bin", "required": True}]} - } - } - systems, _ = build_native_model(truth, None) - entry = systems["nintendo-ds"].files[0] - self.assertFalse(_BaseRule().writable(entry, require="md5")) - - -class _BaseRule(BaseExporter): - """A concrete exporter that keeps every rule of the base class.""" - - @staticmethod - def platform_name() -> str: - return "base" - - @staticmethod - def native_filename() -> str: - return "base" - - def render(self, systems, report, originals, scraped=None): - return {} - - def validate(self, systems, produced): - return [] - - -class ExporterRegistry(unittest.TestCase): - """Every registered platform has an exporter, and it declares itself.""" - - def test_every_exporter_declares_a_platform_and_a_filename(self): - for name, cls in discover_exporters().items(): - with self.subTest(platform=name): - self.assertTrue(cls.platform_name()) - self.assertTrue(cls.native_filename()) - self.assertTrue(issubclass(cls, BaseExporter)) - - def test_every_registered_platform_can_be_exported(self): - """A platform with no exporter is a platform we cannot hand back. - - The export is a correction we offer, not a release artefact: a - platform without a release pack is exported all the same. - """ - exporters = discover_exporters() - registered = set( - list_registered_platforms( - str(REPO_ROOT / "platforms") - ) - ) - self.assertEqual(registered - set(exporters) - _without_native_list(), set()) - - def test_a_run_over_a_platform_without_a_native_list_passes(self): - """export_native --all ran over MinUI, NextUI and MyMinUI and failed - the pipeline step for three platforms the registry says have nothing - to export. A platform with no exporter and no such mark still fails.""" - import contextlib - - from exporter import runner - - with tempfile.TemporaryDirectory() as directory: - platforms = Path(directory) - (platforms / "_registry.yml").write_text( - "platforms:\n cardonly:\n native_list: none\n unwritten: {}\n", - encoding="utf-8") - with contextlib.redirect_stdout(io.StringIO()) as out: - self.assertEqual(runner.run( - ["cardonly"], directory, directory, str(platforms), directory, False), 0) - self.assertEqual(runner.run( - ["unwritten"], directory, directory, str(platforms), directory, False), 1) - self.assertIn("SKIP cardonly: names no BIOS file of its own", out.getvalue()) - - def test_a_platform_without_a_native_list_declares_no_file(self): - """`native_list: none` says the platform's code names no BIOS file - (MinUI hands each core a folder and opens nothing in it). A platform - whose file declares one has a list to hand back.""" - for name in _without_native_list(): - config = load_platform_config(name, str(REPO_ROOT / "platforms")) - with self.subTest(platform=name): - self.assertNotIn(name, discover_exporters()) - self.assertFalse(any( - system.get("files") for system in (config.get("systems") or {}).values() - )) - - def test_no_exporter_is_registered_for_an_unregistered_platform(self): - """A dead exporter is one nobody will notice has stopped working.""" - exporters = set(discover_exporters()) - registered = set( - list_registered_platforms( - str(REPO_ROOT / "platforms") - ) - ) - self.assertEqual(exporters - registered, set()) - - def test_every_exporter_says_what_its_format_can_state(self): - """A correction to a field the file has no place for is not delivered.""" - for name, cls in discover_exporters().items(): - with self.subTest(platform=name): - carried = cls.carries() - self.assertTrue(carried) - self.assertTrue( - carried - <= {"size", "crc32", "md5", "sha1", "sha256", "required", "name"}, - f"{name} claims a field that is not one of ours: {carried}", - ) - - def test_only_a_format_with_the_field_claims_to_carry_it(self): - """Recalbox writes mandatory, while RetroBat's entries are md5 and file.""" - exporters = discover_exporters() - self.assertIn("required", exporters["recalbox"].carries()) - self.assertNotIn("required", exporters["retrobat"].carries()) - self.assertNotIn("required", exporters["retroarch"].carries()) - - def test_an_exporter_that_patches_code_says_it_needs_the_original(self): - """Regenerating a script from data alone drops the code around it.""" - for name in ("batocera", "rocknix", "emudeck", "retrodeck", "bizhawk", - "misterfpga", "knulli", "amberelec", "emuelec"): - with self.subTest(platform=name): - self.assertTrue(discover_exporters()[name].needs_original()) - - def test_every_exporter_with_an_original_needs_it(self): - """System.dat, RomM, Recalbox and RetroBat were rebuilt from our data - when their file was not cached: libretro's quoted names, Recalbox's - comments and its second zxspectrum block were lost, and the run - said OK.""" - for name, exporter in discover_exporters().items(): - if exporter.native_sources(): - with self.subTest(platform=name): - self.assertTrue(exporter.needs_original()) - - def test_an_export_without_its_original_writes_nothing(self): - from exporter.native import export_platform - - with tempfile.TemporaryDirectory() as tmp: - output = Path(tmp) / "out" - ok, messages = export_platform( - "retroarch", discover_exporters()["retroarch"], - REPO_ROOT / "dist" / "truth", output, - str(REPO_ROOT / "platforms"), Path(tmp) / "no-cache", False, - ) - if not (REPO_ROOT / "dist" / "truth" / "retroarch.yml").exists(): - self.skipTest("dist/truth not generated") - self.assertFalse(ok, messages) - self.assertFalse(output.exists()) - - -class SearchOrder(unittest.TestCase): - """A list is read in the order the code looks, best first.""" - - @staticmethod - def _entry(name, priority=None, position=0): - truth = {"name": name, "required": True, "md5": f"{position:032x}"} - if priority is not None: - truth["priority"] = priority - return NativeFile( - name=name, destination=name, native_system="psx", truth=truth - ) - - def test_the_declared_rank_orders_the_names(self): - exporter = discover_exporters()["retropie"]() - candidates = [ - self._entry("scph5502.bin", 5, 0), - self._entry("scph5501.bin", 2, 1), - self._entry("scph7001.bin", 10, 2), - ] - self.assertEqual( - exporter._in_search_order(candidates), - ["scph5501.bin", "scph5502.bin", "scph7001.bin"], - ) - - def test_without_a_rank_the_order_the_code_walks_is_kept(self): - """An undeclared order is the profile's own, not the alphabet.""" - exporter = discover_exporters()["retropie"]() - candidates = [ - self._entry("zzz.bin", None, 0), - self._entry("aaa.bin", None, 1), - ] - self.assertEqual( - exporter._in_search_order(candidates), ["zzz.bin", "aaa.bin"] - ) - - def test_a_ranked_file_is_read_before_an_unranked_one(self): - exporter = discover_exporters()["retropie"]() - candidates = [ - self._entry("unranked.bin", None, 0), - self._entry("ranked.bin", 9, 1), - ] - self.assertEqual( - exporter._in_search_order(candidates), ["ranked.bin", "unranked.bin"] - ) - - def test_a_region_the_help_already_fills_gets_no_alternative(self): - """PicoDrive loads the first file of each region's list. RetroPie - names one per region, but the export appended three more, which the - sentence reads as three more required files.""" - from resolve.nativemodel import NativeSystem - - def cd(name, region, rank): - return NativeFile(name=name, destination=name, native_system="segacd", truth={ - "name": name, "required": True, "md5": "0" * 32, "_cores": ["picodrive"], - "region": [region], "priority": rank}) - - files = [cd("us_scd2_9306.bin", "north-america", 1), - cd("us_scd1_9210.bin", "north-america", 3), - cd("eu_mcd2_9306.bin", "europe", 1), - cd("eu_mcd1_9210.bin", "europe", 3), - cd("jp_mcd2_921222.bin", "japan", 1), - cd("jp_mcd1_9112.bin", "japan", 2)] - script = ('rp_module_id="lr-picodrive"\nrp_module_help="The Sega CD requires the ' - 'BIOS files us_scd1_9210.bin, eu_mcd1_9210.bin copied to $biosdir"\n') - exporter = discover_exporters()["retropie"]( - {"picodrive": {"type": "libretro", "cores": ["picodrive"]}} - ) - # The cap is the longest list RetroPie writes: xm7 names thirteen. - longest = ('rp_module_id="xm7"\nrp_module_help="Copy bios files ' - + ", ".join(f"n{i}.rom" for i in range(12)) + ' and n12.rom to $biosdir"\n') - produced = exporter.render( - {"segacd": NativeSystem("segacd", files=files)}, None, - {"scriptmodules/libretrocores/lr-picodrive.sh": script, - "scriptmodules/emulators/xm7.sh": longest}, - )["scriptmodules/libretrocores/lr-picodrive.sh"] - self.assertIn("us_scd1_9210.bin, eu_mcd1_9210.bin and jp_mcd2_921222.bin copied", - produced) - self.assertNotIn("us_scd2_9306", produced) - self.assertNotIn("jp_mcd1_9112", produced) - - def test_a_file_joins_the_list_of_its_own_system(self): - """flycast's help names the Dreamcast BIOS, then the Naomi/Atomiswave - ones. naomi2.zip, an arcade archive, went into the Dreamcast list: - only the first BIOS clause was read.""" - from resolve.nativemodel import NativeSystem - - def entry(name, system): - return NativeFile(name=name, destination=f"dc/{name}", native_system=system, - truth={"name": name, "required": True, "md5": "0" * 32, - "_cores": ["flycast"], "_required_by": ["flycast"]}) - - dc, arcade = "Sega - Dreamcast", "Sega - Dreamcast-based Arcade" - systems = { - dc: NativeSystem(dc, files=[entry("dc_boot.bin", dc)]), - arcade: NativeSystem(arcade, files=[entry("naomi.zip", arcade), - entry("awbios.zip", arcade), - entry("naomi2.zip", arcade)]), - "other": NativeSystem("other", files=[entry("other.zip", "other")]), - } - script = ('rp_module_id="lr-flycast"\nrp_module_help="Copy the required Dreamcast ' - 'BIOS file dc_boot.bin to $biosdir/dc\\n\\nCopy the required ' - 'Naomi/Atomiswave BIOS files naomi.zip and awbios.zip to $biosdir/dc"\n') - longest = ('rp_module_id="xm7"\nrp_module_help="Copy bios files ' - + ", ".join(f"n{i}.rom" for i in range(12)) + ' and n12.rom to $biosdir"\n') - exporter = discover_exporters()["retropie"]( - {"flycast": {"type": "libretro", "cores": ["flycast"]}} - ) - written = exporter.render( - systems, None, - {"scriptmodules/libretrocores/lr-flycast.sh": script, - "scriptmodules/emulators/xm7.sh": longest}, - ) - produced = written["scriptmodules/libretrocores/lr-flycast.sh"] - self.assertIn("Dreamcast BIOS file dc_boot.bin to", produced) - self.assertIn("BIOS files naomi.zip, awbios.zip and naomi2.zip to", produced) - self.assertNotIn("other.zip", produced) - # Rewritten for naomi2.zip, other.zip left out: the summary said - # "Left as is" of a package in the diff. - outcome = exporter.outcome(systems, written) - self.assertIn("Updated in part: lr-flycast,", outcome) - self.assertNotIn("Left as is: lr-flycast", outcome) - - def test_cores_that_disagree_keep_the_best_rank(self): - """Nothing is dropped on the rank here, so the best one wins. - - slot.py voids the choice when cores disagree because it keeps one - file, while ordering keeps them all, and a file that is some core's first - choice belongs early. - """ - merged = {"name": "scph5501.bin", "priority": 2, "priority_conflict": True} - entry = NativeFile( - name="scph5501.bin", - destination="scph5501.bin", - native_system="psx", - truth=merged, - ) - self.assertEqual(entry.priority, 2) - - -class TwoAdditionsAtOnePath(unittest.TestCase): - """Two cores declaring two dumps of one file the platform lacks: both - were counted added while the render wrote one. Recalbox's md5 list takes - both, a System.dat name and a RetroDECK path hold one.""" - - A, B = "615a" + "0" * 28, "ef49" + "0" * 28 - - def _addition(self, md5: str, core: str, system: str = "dos") -> NativeFile: - return NativeFile( - name="MT32_CONTROL.ROM", destination="mt32/MT32_CONTROL.ROM", native_system=system, - truth={"name": "MT32_CONTROL.ROM", "path": "mt32/MT32_CONTROL.ROM", "md5": md5, - "crc32": md5[:8], "required": True, "_cores": [core]}, - runners=[(False, core)], - ) - - def _added(self, exporter, systems) -> list[str]: - return [c["name"] for c in landed_changes(exporter, systems).records - if c["kind"] == "added"] - - def test_recalbox_writes_both_md5_in_one_element(self): - systems = {"dos": NativeSystem("dos", files=[ - self._addition(self.A, "dosbox_pure"), self._addition(self.B, "dosbox_core")])} - exporter = discover_exporters()["recalbox"]() - produced = exporter.render(systems, Report(), {})["es_bios.xml"] - elements = [e for e in ET.fromstring(produced).iter("bios")] - self.assertEqual(len(elements), 1) - self.assertEqual(elements[0].get("md5").split(","), [self.A, self.B]) - self.assertEqual(elements[0].get("core"), "libretro/dosbox_pure,libretro/dosbox_core") - self.assertEqual(exporter.validate(systems, {"es_bios.xml": produced}), []) - self.assertEqual(len(self._added(exporter, systems)), 2) - - def test_system_dat_counts_the_line_it_wrote(self): - systems = {"DOS": NativeSystem("DOS", files=[ - self._addition(self.A, "dosbox_pure", "DOS"), - self._addition(self.B, "dosbox_core", "DOS")])} - exporter = discover_exporters()["retroarch"]() - original = 'clrmamepro (\n\tname "System"\n)\n\ngame (\n\tname "System"\n' \ - '\tcomment "System"\n\n\tcomment "DOS"\n\trom ( name a.bin size 1 crc 00000000 )\n)\n' - produced = exporter.render(systems, Report(), {"System.dat": original})["System.dat"] - self.assertEqual(produced.count("MT32_CONTROL.ROM"), 1) - self.assertEqual(len(self._added(exporter, systems)), 1) - - def test_retrodeck_counts_the_entry_it_appended(self): - theirs = NativeFile( - name="scph1001.bin", destination="scph1001.bin", native_system="psx", - platform={"name": "scph1001.bin", "md5": "1" * 32, "component": "duckstation"}) - - def addition(md5: str) -> NativeFile: - return NativeFile( - name="scph5501.bin", destination="scph5501.bin", native_system="psx", - truth={"name": "scph5501.bin", "md5": md5, "required": True, - "_cores": ["duckstation"]}, - runners=[(True, "duckstation")]) - - systems = {"psx": NativeSystem("psx", files=[theirs, addition(self.A), addition(self.B)])} - manifest = json.dumps({"duckstation": {"name": "DuckStation", "bios": [ - {"filename": "scph1001.bin", "md5": "1" * 32, "system": "psx"}]}}) - exporter = discover_exporters()["retrodeck"]() - produced = exporter.render(systems, Report(), {"duckstation/component_manifest.json": manifest}) - bios = json.loads(produced["duckstation/component_manifest.json"])["duckstation"]["bios"] - self.assertEqual([e["filename"] for e in bios], ["scph1001.bin", "scph5501.bin"]) - self.assertEqual(self._added(exporter, systems), ["scph5501.bin"]) - - -class AdditionOrder(unittest.TestCase): - """What we add is listed the way the code looks for it.""" - - TRUTH = { - "systems": { - "sony-playstation": { - "files": [ - { - "name": "third.bin", - "md5": "c" * 32, - "required": True, - "priority": 10, - }, - { - "name": "first.bin", - "md5": "a" * 32, - "required": True, - "priority": 1, - }, - {"name": "unranked.bin", "md5": "b" * 32, "required": True}, - ] - } - } - } - - def test_a_ranked_addition_is_named_before_a_later_one(self): - systems, _ = build_native_model(self.TRUTH, None) - names = [fe.name for fe in systems["sony-playstation"].files] - self.assertEqual(names, ["first.bin", "third.bin", "unranked.bin"]) - - def test_what_the_platform_wrote_keeps_its_place(self): - """Reordering their own entries would be churn, not a correction.""" - scraped = { - "systems": { - "sony-playstation": { - "native_id": "psx", - "files": [ - { - "name": "theirs-b.bin", - "destination": "theirs-b.bin", - "native_system": "psx", - "md5": "d" * 32, - }, - { - "name": "theirs-a.bin", - "destination": "theirs-a.bin", - "native_system": "psx", - "md5": "e" * 32, - }, - ], - } - } - } - systems, _ = build_native_model(self.TRUTH, scraped) - names = [fe.name for fe in systems["psx"].files] - self.assertEqual(names[:2], ["theirs-b.bin", "theirs-a.bin"]) - self.assertEqual(names[2], "first.bin") - - -class PinnedRevision(unittest.TestCase): - """The file we patch is the revision our transcription came from.""" - - def test_the_tag_the_scraper_pinned_wins_over_the_branch_tip(self): - wanted = {"batocera-systems": "https://example.invalid/master/batocera-systems"} - scraped = { - "source": "https://raw.githubusercontent.com/batocera-linux" - "/batocera.linux/batocera-43.1/package/batocera-systems" - } - self.assertEqual( - pinned_base(wanted, scraped), - "https://raw.githubusercontent.com/batocera-linux/batocera.linux" - "/batocera-43.1/package/", - ) - - def test_a_blob_page_is_read_as_raw(self): - """github.com/.../blob/... names a revision but serves HTML.""" - wanted = {"System.dat": "https://example.invalid/System.dat"} - scraped = { - "source": "https://github.com/libretro/libretro-database" - "/blob/master/dat/System.dat" - } - self.assertEqual( - pinned_base(wanted, scraped), - "https://raw.githubusercontent.com/libretro/libretro-database" - "/master/dat/", - ) - - def test_a_source_that_names_no_wanted_file_changes_nothing(self): - wanted = {"component_manifest.json": "https://example.invalid/x.json"} - scraped = {"source": "https://github.com/RetroDECK/components"} - self.assertEqual(pinned_base(wanted, scraped), "") - - def test_every_platform_that_records_its_source_pins_the_export(self): - """A scraped platform states the revision, and the export follows it.""" - exporters = discover_exporters() - for name in ("batocera", "recalbox", "bizhawk", "romm", "retroarch"): - with self.subTest(platform=name): - config = load_platform_config(name, str(REPO_ROOT / "platforms")) - base = pinned_base(dict(exporters[name].native_sources()), config) - self.assertTrue(base.startswith("https://"), base) - - def test_every_file_of_every_platform_is_read_at_the_pinned_revision(self): - """Checked on five platforms by their base only: ROCKNIX's second - file, RetroDECK's manifests and RetroPie's tarball were never - looked at, and a URL that fell back to a branch passed.""" - from exporter.originals import unpinned, wanted_sources - - for name, exporter_class in discover_exporters().items(): - with self.subTest(platform=name): - config = native_layer(load_platform_config(name, str(REPO_ROOT / "platforms"))) - systems, _ = build_native_model({}, config) - wanted = wanted_sources(exporter_class(), systems, config) - self.assertTrue(wanted) - self.assertEqual(unpinned(wanted, config), []) - - def test_a_file_read_off_the_pinned_revision_is_named(self): - from exporter.originals import unpinned - - pinned = {"source": "https://raw.githubusercontent.com/o/r/v1.0/list.txt"} - self.assertEqual(unpinned( - {"list.txt": "https://raw.githubusercontent.com/o/r/v1.0/list.txt"}, pinned), []) - moved = unpinned( - {"list.txt": "https://raw.githubusercontent.com/o/r/master/list.txt"}, pinned) - self.assertEqual(len(moved), 1) - self.assertIn("v1.0", moved[0]) - bare = unpinned( - {"x.json": "https://raw.githubusercontent.com/o/r/main/x.json"}, - {"source": "https://github.com/RetroDECK/components"}) - self.assertIn("names no revision", bare[0]) - - -class _OneFileExporter: - """An exporter reduced to what collect_originals reads.""" - - def __init__(self, url: str): - self._url = url - - def platform_name(self) -> str: - return "plat" - - def native_sources(self) -> dict[str, str]: - return {"list.txt": self._url} - - -class _ArchiveExporter(_OneFileExporter): - """One whose original is an archive it unpacks, as MiSTer's is.""" - - def native_sources(self) -> dict[str, str]: - return {"db.zip": self._url} - - @staticmethod - def unpack(raw: bytes) -> dict[str, str]: - with zipfile.ZipFile(io.BytesIO(raw)) as archive: - return {"db.json": archive.read("db.json").decode("utf-8")} - - -class CachedOriginal(unittest.TestCase): - """The cached original is the file the platform data was read from.""" - - def setUp(self): - self._tmp = tempfile.TemporaryDirectory() - self.addCleanup(self._tmp.cleanup) - self.root = Path(self._tmp.name) - self.cache = self.root / "cache" - self.index = self.cache / SOURCES_INDEX - - def _upstream(self, name: str, text: str) -> str: - path = self.root / name - path.write_text(text, encoding="utf-8") - return path.as_uri() - - def test_the_same_url_is_served_from_the_cache(self): - url = self._upstream("v1.txt", "one") - target = self.cache / "plat" / "list.txt" - self.assertEqual(fetch(url, target, self.index), b"one") - self._upstream("v1.txt", "moved") - self.assertEqual(fetch(url, target, self.index), b"one") - - def test_an_unreadable_index_serves_nothing(self): - """A truncated index read as empty: the cached batocera-41 file was - served for a 43.1 URL, and the next download erased every other - platform's recorded URL.""" - from exporter.originals import SourcesIndexUnreadable - - old = self._upstream("batocera-41.txt", "old") - target = self.cache / "plat" / "list.txt" - fetch(old, target, self.index) - self.index.write_text('{"plat/list.txt": "' + old + '",', encoding="utf-8") - new = self._upstream("batocera-43.txt", "new") - with self.assertRaises(SourcesIndexUnreadable) as caught: - fetch(new, target, self.index) - self.assertIn("--refresh-cache", str(caught.exception)) - self.assertTrue(self.index.read_text(encoding="utf-8").endswith(",")) - - def test_refresh_reads_a_branch_url_again(self): - """A branch URL keeps its name while the platform moves.""" - url = self._upstream("branch.txt", "one") - target = self.cache / "plat" / "list.txt" - fetch(url, target, self.index) - self._upstream("branch.txt", "two") - self.assertEqual(fetch(url, target, self.index, refresh=True), b"two") - self.assertEqual(target.read_bytes(), b"two") - - def test_a_new_pin_refetches_an_existing_file(self): - """Reading the file straight from disk served the old pin forever.""" - old = self._upstream("tag-1.txt", "one") - new = self._upstream("tag-2.txt", "two") - originals, missing = collect_originals( - _OneFileExporter(old), {}, self.cache, True - ) - self.assertEqual((originals, missing), ({"list.txt": "one"}, [])) - originals, missing = collect_originals( - _OneFileExporter(new), {}, self.cache, True - ) - self.assertEqual((originals, missing), ({"list.txt": "two"}, [])) - - def test_an_empty_or_html_original_fails_the_platform(self): - """A System.dat served as an HTML page with 200, or a 0-byte cache, - was parsed as a file with no entries: four exporters rebuilt it from - our data and reported OK.""" - for body in ("", " \n", "Too Many Requests", - "\n"): - with self.subTest(body=body): - url = self._upstream("served.txt", body) - originals, missing = collect_originals( - _OneFileExporter(url), {}, self.cache, True, refresh=True - ) - self.assertEqual(originals, {}) - self.assertEqual(len(missing), 1) - cached = self.cache / "plat" / "list.txt" - cached.parent.mkdir(parents=True, exist_ok=True) - cached.write_text(body, encoding="utf-8") - _, missing = collect_originals( - _OneFileExporter(url), {}, self.cache, False - ) - self.assertEqual(len(missing), 1) - cached.unlink() - - def test_offline_serves_what_is_cached_and_names_what_is_not(self): - url = self._upstream("v1.txt", "one") - _, missing = collect_originals(_OneFileExporter(url), {}, self.cache, False) - self.assertEqual(missing, [ - f"list.txt: not in {self.cache / 'plat'}; rerun with --fetch to download it" - ]) - collect_originals(_OneFileExporter(url), {}, self.cache, True) - originals, missing = collect_originals( - _OneFileExporter("file:///nowhere/else.txt"), {}, self.cache, False - ) - self.assertEqual((originals, missing), ({"list.txt": "one"}, [])) - - def test_the_bytes_are_written_under_the_index_lock(self): - """Written under two locks, two runs wanting two URLs for one path - could leave one's bytes beside the other's index entry.""" - import fcntl - from unittest import mock - - from exporter import originals - - url = self._upstream("v1.txt", "one") - target = self.cache / "plat" / "list.txt" - lock = self.index.with_name(f".{self.index.name}.lock") - held: list[bool] = [] - write = originals.write_bytes_atomic - - def probing(path, data): - with open(lock, "a") as handle: - try: - fcntl.flock(handle, fcntl.LOCK_EX | fcntl.LOCK_NB) - except BlockingIOError: - held.append(True) - else: - fcntl.flock(handle, fcntl.LOCK_UN) - held.append(False) - write(path, data) - - with mock.patch.object(originals, "write_bytes_atomic", probing): - fetch(url, target, self.index) - self.assertEqual(held, [True]) - - def test_an_unreadable_cached_archive_fails_its_platform_only(self): - """A cached bios_db.json.zip that was not a zip raised BadZipFile - out of run(): --all stopped and the next platforms were never - exported.""" - target = self.cache / "plat" / "db.zip" - target.parent.mkdir(parents=True) - target.write_bytes(b"not a zip") - originals, missing = collect_originals( - _ArchiveExporter("file:///nowhere/db.zip"), {}, self.cache, False - ) - self.assertEqual(originals, {}) - self.assertEqual(len(missing), 1) - self.assertIn("--refresh-cache", missing[0]) - - def test_a_download_that_is_not_the_archive_keeps_the_cache(self): - """fetch() cached any 200 reply, so an error page replaced a good - archive and was served on every later run.""" - good = self.root / "db.zip" - with zipfile.ZipFile(good, "w") as archive: - archive.writestr("db.json", "{}") - url = good.as_uri() - exporter = _ArchiveExporter(url) - collect_originals(exporter, {}, self.cache, True) - cached = (self.cache / "plat" / "db.zip").read_bytes() - good.write_bytes(b"error") - originals, missing = collect_originals(exporter, {}, self.cache, True, refresh=True) - self.assertEqual(originals, {}) - self.assertIn("--refresh-cache", missing[0]) - self.assertEqual((self.cache / "plat" / "db.zip").read_bytes(), cached) - - def test_an_incomplete_read_is_reported(self): - import http.client - from unittest import mock - - from exporter import originals as exporter_originals - - def cut(*_args, **_kwargs): - raise http.client.IncompleteRead(b"par") - - with mock.patch.object(exporter_originals, "fetch", cut): - originals, missing = collect_originals( - _OneFileExporter("https://example.invalid/list.txt"), {}, self.cache, True - ) - self.assertEqual((originals, len(missing)), ({}, 1)) - - def test_the_index_names_a_file_the_same_from_any_directory(self): - target = self.cache / "plat" / "list.txt" - self.assertEqual(source_key(target, self.index), "plat/list.txt") - relative = Path(os.path.relpath(target, Path.cwd())) - self.assertEqual(source_key(relative, self.index), "plat/list.txt") - - -class RecalboxExport(unittest.TestCase): - def _render(self): - systems, report = model() - exporter = discover_exporters()["recalbox"]() - return exporter, systems, exporter.render(systems, report, {}, None) - - def test_output_is_well_formed_xml_in_recalbox_shape(self): - _, _, produced = self._render() - root = ET.fromstring(produced["es_bios.xml"]) - self.assertEqual(root.tag, "biosList") - self.assertTrue(list(root.iter("system"))) - - def test_every_element_carries_what_the_schema_requires(self): - """es_bios.xsd makes path, md5 and core required on every bios.""" - _, _, produced = self._render() - root = ET.fromstring(produced["es_bios.xml"]) - for element in root.iter("bios"): - for attribute in ("path", "md5", "core"): - self.assertTrue(element.get(attribute), attribute) - - def test_mandatory_is_only_stated_when_it_is_false(self): - _, _, produced = self._render() - root = ET.fromstring(produced["es_bios.xml"]) - by_path = {e.get("path"): e for e in root.iter("bios")} - self.assertIsNone(by_path["psx/scph5501.bin"].get("mandatory")) - self.assertEqual(by_path["psx/scph7001.bin"].get("mandatory"), "false") - - def test_hash_match_mandatory_does_not_follow_mandatory(self): - """They are separate axes: Recalbox uses all four combinations.""" - _, _, produced = self._render() - root = ET.fromstring(produced["es_bios.xml"]) - optional = next( - e for e in root.iter("bios") if e.get("mandatory") == "false" - ) - self.assertIsNone(optional.get("hashMatchMandatory")) - - def test_the_export_passes_its_own_validator(self): - exporter, systems, produced = self._render() - self.assertEqual(exporter.validate(systems, produced), []) - - def test_an_addition_goes_where_the_core_reads_it(self): - """DuckStation reads scph5000.bin at the BIOS root, but the export wrote - psx/scph5000.bin, a path no core opens.""" - import copy - - truth = copy.deepcopy(TRUTH) - truth["systems"]["sony-playstation"]["files"].append({ - "name": "scph5000.bin", "md5": "57a06303dfa9cf9351222dfcbb4a29d9", - "size": 524288, "required": False, "_cores": ["duckstation"], - }) - systems, report = build_native_model(truth, SCRAPED) - produced = discover_exporters()["recalbox"]().render(systems, report, {}, None) - paths = {e.get("path") for e in ET.fromstring(produced["es_bios.xml"]).iter("bios")} - self.assertIn("scph5000.bin", paths) - self.assertNotIn("psx/scph5000.bin", paths) - - def test_two_blocks_of_one_platform_stay_two(self): - """Recalbox files Pentagon and Scorpion under zxspectrum, apart. - - Merged, the Scorpion ROMs sat under the Pentagon name and the BIOS - manager lost a section, and the line the maintainer commented out went - with the rewrite. - """ - old, new = "1" * 32, "2" * 32 - - def declared(name, label, md5): - return { - "name": name, "destination": f"fuse/{name}", - "native_system": "zxspectrum", "native_name": label, - "native_path": f"fuse/{name}", "md5": md5, - "core": "libretro/fuse", "required": False, - } - - pentagon = "Pentagon 128/512/1024 (ZX Spectrum clone)" - scorpion = "Scorpion 256K (ZX Spectrum clone)" - scraped = {"systems": {"sinclair-zxspectrum": { - "native_id": "zxspectrum", - "files": [ - declared("128p-0.rom", pentagon, "3" * 32), - declared("256s-0.rom", scorpion, old), - ], - }}} - truth = {"systems": {"sinclair-zxspectrum": {"files": [{ - "name": "256s-0.rom", "path": "fuse/256s-0.rom", "md5": new, - "required": False, "_cores": ["fuse"], - }]}}} - original = ( - '\n\n' - f' \n' - f' \n' - ' \n' - " \n" - f' \n' - f' \n' - " \n\n" - ) - systems, report = build_native_model(truth, scraped) - produced = discover_exporters()["recalbox"]().render( - systems, report, {"es_bios.xml": original}, None - )["es_bios.xml"] - self.assertIn('\n' + " \n" + f' \n' + f' \n' + " \n\n" + ) + systems, report = build_native_model(truth, scraped) + produced = discover_exporters()["recalbox"]().render( + systems, report, {"es_bios.xml": original}, None + )["es_bios.xml"] + self.assertIn('