mirror of
https://github.com/Abdess/retroarch_system.git
synced 2026-12-02 22:38:54 -06:00
refactor: split e2e and audit suites by subject
test_e2e.py (7,245 lines) becomes eight test_e2e_* modules whose TestE2E* classes inherit the shared scenario from tests/e2esupport.py. test_audit_regressions.py (8,391 lines) becomes eight test_audit_* modules, its constants in tests/auditsupport.py. Test bodies move verbatim and every test id keeps its method name.
This commit is contained in:
1 parent
6dd9970fb6
commit
623ef5cabe
25 files changed
+15966
-15652
No files matched your search
@@ -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")
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
@@ -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
|
||||
@@ -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)
|
||||
File diff suppressed because it is too large.
Load diff
@@ -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"(?<![\w-])--[a-z][a-z-]+", quick_install))
|
||||
parser_source = (ROOT / "install.py").read_text(encoding="utf-8")
|
||||
supported = set(re.findall(r'add_argument\(\s*"(--[a-z][a-z-]+)"', parser_source))
|
||||
unknown = advertised - supported
|
||||
self.assertEqual(unknown, set(), f"README advertises unknown flags: {unknown}")
|
||||
|
||||
def test_the_build_version_is_the_one_the_pipeline_requires(self):
|
||||
""""Python 3 + pyyaml" sent a 3.8 user to a SyntaxError in
|
||||
generate_pack, and a 3.10 one through six steps to fail at step 7."""
|
||||
floor = re.search(
|
||||
r"sys\.version_info < \((\d+), (\d+)\)",
|
||||
(ROOT / "scripts" / "pipeline.py").read_text(encoding="utf-8"),
|
||||
)
|
||||
self.assertIsNotNone(floor, "pipeline.py checks no interpreter version")
|
||||
version = f"Python {floor.group(1)}.{floor.group(2)}"
|
||||
for page in ("README.md", "wiki/tools.md", "wiki/testing-guide.md"):
|
||||
with self.subTest(page=page):
|
||||
self.assertIn(version, (ROOT / page).read_text(encoding="utf-8"))
|
||||
self.assertIn(
|
||||
version, script_source("generate_readme.py")
|
||||
)
|
||||
|
||||
def test_an_older_interpreter_is_refused_before_the_first_step(self):
|
||||
import shutil
|
||||
|
||||
python38 = shutil.which("python3.8")
|
||||
if python38 is None:
|
||||
if os.environ.get("CI"):
|
||||
self.fail("CI must provide python3.8")
|
||||
self.skipTest("no python3.8 on PATH")
|
||||
# --help: without the guard the run must stop at argparse, not
|
||||
# rebuild database.json under an interpreter missing pyyaml.
|
||||
proc = subprocess.run(
|
||||
[python38, "-I", "scripts/pipeline.py", "--help"],
|
||||
cwd=ROOT, capture_output=True, text=True, timeout=60, check=False,
|
||||
)
|
||||
self.assertEqual(proc.returncode, 1)
|
||||
self.assertIn("needs Python 3.9", proc.stderr)
|
||||
|
||||
def test_the_readme_build_command_names_the_floor(self):
|
||||
"""The README's first command is generate_pack.py. Under 3.8 it
|
||||
stopped on a raw SyntaxError at a parenthesized `with`."""
|
||||
import shutil
|
||||
|
||||
python38 = shutil.which("python3.8")
|
||||
if python38 is None:
|
||||
if os.environ.get("CI"):
|
||||
self.fail("CI must provide python3.8")
|
||||
self.skipTest("no python3.8 on PATH")
|
||||
proc = subprocess.run(
|
||||
[python38, "-I", "scripts/generate_pack.py", "--help"],
|
||||
cwd=ROOT, capture_output=True, text=True, timeout=60, check=False,
|
||||
)
|
||||
self.assertEqual(proc.returncode, 1)
|
||||
self.assertNotIn("SyntaxError", proc.stderr)
|
||||
self.assertIn("generate_pack.py needs Python 3.9", proc.stderr)
|
||||
|
||||
def test_every_script_names_the_floor_under_an_older_interpreter(self):
|
||||
"""Only generate_pack.py and pipeline.py checked the version. verify.py,
|
||||
slots.py, validate_pr.py and cross_reference.py started under 3.8 and
|
||||
stopped halfway on a str.removeprefix AttributeError."""
|
||||
import shutil
|
||||
|
||||
python38 = shutil.which("python3.8")
|
||||
if python38 is None:
|
||||
if os.environ.get("CI"):
|
||||
self.fail("CI must provide python3.8")
|
||||
self.skipTest("no python3.8 on PATH")
|
||||
commands = (
|
||||
["verify.py", "--emulator", "handy"],
|
||||
["verify.py", "--platform", "batocera"],
|
||||
["validate_pr.py", "--json", "README.md"],
|
||||
["cross_reference.py", "--emulator", "handy"],
|
||||
["slots.py"],
|
||||
["identity.py"],
|
||||
["generate_site.py", "--help"],
|
||||
["campaign.py", "--help"],
|
||||
["region_check.py", "--help"],
|
||||
)
|
||||
for command in commands:
|
||||
with self.subTest(command=" ".join(command)):
|
||||
# -E -s rather than -I: -I drops the script's folder from
|
||||
# sys.path, so the imports would fail before any check.
|
||||
proc = subprocess.run(
|
||||
[python38, "-E", "-s", f"scripts/{command[0]}", *command[1:]],
|
||||
cwd=ROOT, capture_output=True, text=True, timeout=60,
|
||||
check=False,
|
||||
)
|
||||
self.assertEqual(proc.returncode, 1, proc.stderr)
|
||||
self.assertNotIn("Traceback", proc.stderr)
|
||||
self.assertIn(f"{command[0]} needs Python 3.9", proc.stderr)
|
||||
|
||||
def test_the_floor_interpreter_imports_every_script(self):
|
||||
"""Every module under scripts/ is loaded by a real interpreter of the
|
||||
floor version, as the installer's 3.8 floor is proven by running it.
|
||||
Compiling only checks the grammar: a module-level alias such as
|
||||
`tuple[int, int | None]` compiles under 3.9 and raises TypeError
|
||||
when the module loads."""
|
||||
import shutil
|
||||
|
||||
floor = re.search(
|
||||
r"sys\.version_info < \((\d+), (\d+)\)",
|
||||
(ROOT / "scripts" / "pipeline.py").read_text(encoding="utf-8"),
|
||||
)
|
||||
name = f"python{floor.group(1)}.{floor.group(2)}"
|
||||
interpreter = shutil.which(name)
|
||||
if interpreter is None:
|
||||
if os.environ.get("CI"):
|
||||
self.fail(f"CI must provide {name}")
|
||||
self.skipTest(f"no {name} on PATH")
|
||||
check = (
|
||||
"import importlib, json, pathlib, sys\n"
|
||||
"sys.path.insert(0, '.')\n"
|
||||
"failed = {}\n"
|
||||
"for p in sorted(pathlib.Path('scripts').rglob('*.py')):\n"
|
||||
" if '__pycache__' in p.parts:\n"
|
||||
" continue\n"
|
||||
" parts = p.with_suffix('').parts\n"
|
||||
" if parts[-1] == '__init__':\n"
|
||||
" parts = parts[:-1]\n"
|
||||
" try:\n"
|
||||
" importlib.import_module('.'.join(parts))\n"
|
||||
" except BaseException as e:\n"
|
||||
" failed[str(p)] = [type(e).__name__, getattr(e, 'name', None), str(e)]\n"
|
||||
"print(json.dumps(failed))\n"
|
||||
)
|
||||
proc = subprocess.run(
|
||||
[interpreter, "-I", "-c", check], cwd=ROOT, capture_output=True,
|
||||
text=True, timeout=600, check=False,
|
||||
env={**os.environ, "RETROBIOS_OFFLINE": "1"},
|
||||
)
|
||||
self.assertEqual(proc.returncode, 0, proc.stdout + proc.stderr)
|
||||
failed = json.loads(proc.stdout.strip().splitlines()[-1])
|
||||
# pyyaml for every build script, jsonschema for validate_schemas:
|
||||
# without them the floor interpreter cannot load the modules, which
|
||||
# proves nothing either way.
|
||||
absent = sorted({
|
||||
err[1] for err in failed.values()
|
||||
if err[0] == "ModuleNotFoundError" and err[1] in ("yaml", "jsonschema")
|
||||
})
|
||||
if absent:
|
||||
message = f"{name} lacks {', '.join(absent)}"
|
||||
if os.environ.get("CI"):
|
||||
self.fail(message)
|
||||
self.skipTest(message)
|
||||
self.assertEqual(failed, {})
|
||||
|
||||
|
||||
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 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 href="https://github.com/a"><img src="x" alt="a"></a>\n'
|
||||
'<a href="https://github.com/b"><img src="y" alt="b"></a>\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 href="https://github.com/'), 0,
|
||||
"the section is present but empty",
|
||||
)
|
||||
|
||||
def test_a_failed_request_republishes_the_kept_block(self):
|
||||
from sitegen.readme import render_readme
|
||||
from tests.readmeinputs import readme_inputs
|
||||
|
||||
kept = ["## Contributors", "", '<a href="https://github.com/a"><img src="x" alt="a"></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\n<a href="https://github.com/someone"><img src="https://a/x"'
|
||||
' width="50" alt="someone" title="someone"></a>\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()
|
||||
@@ -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/<platform>.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 <platform>.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()
|
||||
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
File diff suppressed because it is too large.
Load diff
@@ -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('<h3 id="file-neogeo-zip" class="rb-file-title"', text)
|
||||
self.assertIn("Standalone path: `Firmware/neogeo.zip`", text)
|
||||
self.assertIn("`m11.bin`", text)
|
||||
self.assertIn("CRC32 `0000000b`", text)
|
||||
self.assertNotIn("more", text)
|
||||
|
||||
|
||||
class EmulatorPagesStateTheirDataForMachines(unittest.TestCase):
|
||||
"""Every emulator page's JSON-LD differed only by name and url."""
|
||||
|
||||
def test_source_pin_date_and_files(self):
|
||||
from scripts.sitegen.structured import emulator_structured_data
|
||||
|
||||
data = emulator_structured_data({
|
||||
"emulator": "DuckStation", "source": "https://github.com/stenzek/duckstation",
|
||||
"source_commit": "4122fed9", "core_version": "v0.1-12070",
|
||||
"profiled_date": "2026-03-23",
|
||||
"files": [{"name": "scph5501.bin", "md5": "490F666E", "sha1": ["a" * 40]},
|
||||
{"name": "free.bin"}],
|
||||
})
|
||||
self.assertEqual(data["about"]["codeRepository"], "https://github.com/stenzek/duckstation")
|
||||
# The release the profile describes, never the pin.
|
||||
self.assertEqual(data["about"]["version"], "v0.1-12070")
|
||||
self.assertNotIn("description", data["about"])
|
||||
self.assertEqual(data["dateModified"], "2026-03-23")
|
||||
self.assertEqual(data["hasPart"][0]["identifier"], ["sha1:" + "a" * 40, "md5:490f666e"])
|
||||
self.assertNotIn("identifier", data["hasPart"][1])
|
||||
|
||||
def test_every_repository_with_its_own_release(self):
|
||||
"""xemu's libretro build lives in another repository. Each source
|
||||
repository states the release of its build, a version holding a
|
||||
commit id states none, and a port's upstream is another code base."""
|
||||
from scripts.sitegen.structured import emulator_structured_data
|
||||
|
||||
data = emulator_structured_data({
|
||||
"emulator": "MesenCE",
|
||||
"source": {"standalone": "https://github.com/nesdev-org/MesenCE",
|
||||
"libretro": "https://github.com/libretro/MesenCE"},
|
||||
"source_commit": {"standalone": "f9b14039", "libretro": "d9804db7"},
|
||||
"core_version": {"standalone": "2.2.1", "libretro": "2.0.0"},
|
||||
"upstream": "https://github.com/SourMesen/Mesen2", "upstream_commit": "aa11",
|
||||
})
|
||||
self.assertEqual(
|
||||
[(a["codeRepository"].rsplit("/", 1)[1], a.get("version")) for a in data["about"]],
|
||||
[("MesenCE", "2.2.1"), ("MesenCE", "2.0.0"), ("Mesen2", None)])
|
||||
xemu = emulator_structured_data({
|
||||
"emulator": "xemu",
|
||||
"source": {"standalone": "https://github.com/xemu-project/xemu",
|
||||
"libretro": "https://github.com/LibretroAdmin/xemu-libretro"},
|
||||
"core_version": {"standalone": "0.8.139-2-g25e1ee2fd5",
|
||||
"libretro": "libretro-experimental"},
|
||||
})
|
||||
self.assertEqual([a.get("version") for a in xemu["about"]], [None, None])
|
||||
|
||||
|
||||
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</span>', 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('<span id="acknowledged-gaps"></span>', 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'<dd class="rb-hash">{value}</dd>', 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'<h3 id="(file-[^"]+)" class="rb-file-title"', page)
|
||||
|
||||
def test_inserting_a_version_keeps_the_others(self):
|
||||
a = {"name": "DUKE3D.GRP", "path": "DUKE3D.GRP", "crc32": "bbc9ce44"}
|
||||
b = {"name": "DUKE3D.GRP", "path": "DUKE3D.GRP", "crc32": "aa4f6a40"}
|
||||
c = {"name": "DUKE3D.GRP", "path": "DUKE3D.GRP", "crc32": "982afe4a"}
|
||||
before = self._anchors([a, b])
|
||||
after = self._anchors([c, a, b])
|
||||
self.assertTrue(set(before) <= set(after))
|
||||
|
||||
def test_same_size_versions_are_told_by_description(self):
|
||||
v1 = {"name": "AUDIO.ABS", "path": "AUDIO.ABS", "size": 6904, "description": "v1.12"}
|
||||
v2 = {"name": "AUDIO.ABS", "path": "AUDIO.ABS", "size": 6904, "description": "v1.13"}
|
||||
self.assertEqual(self._anchors([v1, v2]),
|
||||
["file-audio-abs-6904b-v1-12", "file-audio-abs-6904b-v1-13"])
|
||||
|
||||
|
||||
class SitemapDatesComeFromThePage(unittest.TestCase):
|
||||
"""All 664 sitemap URLs carried the build date: eduke32, re-read on
|
||||
2026-10-04, was announced as changed on the day of every build."""
|
||||
|
||||
def test_the_page_date_or_none_reaches_the_sitemap(self):
|
||||
import tempfile
|
||||
|
||||
from sitegen import decorate
|
||||
from sitegen.pageregistry import PageRegistry
|
||||
|
||||
pages = PageRegistry(page_data={"emulators/dated.md": {"dateModified": "2026-10-04"}})
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
docs = Path(tmp)
|
||||
(docs / "emulators").mkdir()
|
||||
(docs / "emulators" / "dated.md").write_text("# Dated\n\nA page with its own date.\n")
|
||||
(docs / "emulators" / "undated.md").write_text("# Undated\n\nA page with no date.\n")
|
||||
lastmod = decorate.decorate_markdown_pages(docs, pages)
|
||||
self.assertEqual(lastmod, {"/retrobios/emulators/dated/": "2026-10-04"})
|
||||
# The sitemap reads that map, and leaves every other page undated.
|
||||
config = (ROOT / "website" / "astro.config.mjs").read_text(encoding="utf-8")
|
||||
self.assertIn("lastmod.json", config)
|
||||
self.assertIn("serialize(item)", config)
|
||||
|
||||
|
||||
class SiteCodeSpansHoldTheirValue(unittest.TestCase):
|
||||
"""Values from profiles, platform files and file names went into code
|
||||
spans as they were: a backtick in one closed the span and what followed
|
||||
was read as markup."""
|
||||
|
||||
def test_a_backtick_cannot_close_the_span(self):
|
||||
from scripts.sitegen.render import code_span
|
||||
|
||||
span = code_span("a`<img src=x onerror=alert(1)>`")
|
||||
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()
|
||||
-7245
File diff suppressed because it is too large.
Load diff
@@ -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("<biosList", content)
|
||||
self.assertIn('platform="psx"', content)
|
||||
self.assertIn("fullname=", content)
|
||||
self.assertIn("scph5501.bin", content)
|
||||
# mandatory="true" is the default, not emitted (matching Recalbox format)
|
||||
self.assertNotIn('mandatory="false"', content)
|
||||
self.assertIn('core="libretro/c"', content)
|
||||
self.assertEqual(exp.validate(systems, produced), [])
|
||||
|
||||
def test_181_retrobat_exporter_round_trip(self):
|
||||
"""RetroBat exporter produces valid JSON."""
|
||||
import json as _json
|
||||
|
||||
from exporter.retrobat_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 = {
|
||||
"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)
|
||||
data = _json.loads(produced["batocera-systems.json"])
|
||||
self.assertIn("psx", data)
|
||||
self.assertTrue(
|
||||
any("scph5501" in bf["file"] for bf in data["psx"]["biosFiles"])
|
||||
)
|
||||
self.assertEqual(exp.validate(systems, produced), [])
|
||||
|
||||
def test_182_exporter_discovery(self):
|
||||
"""All exporters are discovered by the plugin system."""
|
||||
from exporter import discover_exporters
|
||||
|
||||
exporters = discover_exporters()
|
||||
self.assertIn("retroarch", exporters)
|
||||
self.assertIn("batocera", exporters)
|
||||
self.assertIn("recalbox", exporters)
|
||||
self.assertIn("retrobat", exporters)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -0,0 +1,671 @@
|
||||
"""End-to-end emulator mode verification and hardware target filtering."""
|
||||
|
||||
from __future__ import annotations
|
||||
|
||||
import tests
|
||||
import contextlib
|
||||
import hashlib
|
||||
import io
|
||||
import os
|
||||
import unittest
|
||||
import zipfile
|
||||
import yaml
|
||||
from core.ziptools import safe_extract_zip
|
||||
from core.hashing import compute_hashes, parse_hash_list
|
||||
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.entryscope import filter_files_by_mode
|
||||
from packs.verdicts import Severity, Status
|
||||
from packs.gaps import find_undeclared_files
|
||||
from packs.emulatorcheck import verify_emulator
|
||||
from tests.e2esupport import E2EFixture
|
||||
|
||||
|
||||
class TestE2EEmulatorMode(E2EFixture):
|
||||
"""verify --emulator and --system, build modes and path hints."""
|
||||
|
||||
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)
|
||||
|
||||
|
||||
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()
|
||||
File diff suppressed because it is too large.
Load diff
@@ -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()
|
||||
@@ -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()
|
||||
@@ -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()
|
||||
@@ -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()
|
||||
@@ -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()
|
||||
@@ -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
|
||||
```
|
||||
|
||||
|
||||
@@ -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
|
||||
|
||||
+10
-8
@@ -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
|
||||
|
||||
Reference in new issue
Block a user