From 74fcdd2bc5876971dc26659790d82683b7946f6a Mon Sep 17 00:00:00 2001 From: Abdessamad Derraz <3028866+Abdess@users.noreply.github.com> Date: Sat, 21 Nov 2026 08:46:51 +0100 Subject: [PATCH] refactor: read archive members in one place core.ziptools.zip_members lists the name, size and crc32 of each member once per archive revision. The site lookup and cards, the gap report, the pack check, the romset importer, the recipe identification and build, provenance, derivations and the atom pool read it instead of opening each archive again. Each reader also tested a .zip suffix and skipped the .variants/ copies (x.zip.1a2b3c4d): the site lookup listed no member of a copy, the gap report's member index never saw one, the pack check never compared a copy's members, and the pack builders copied a copy without its CRC test. They now use is_archive_path. The inner ROM index of the resolver reads copies too, and a copy answers only for a member no primary holds. --- scripts/acquire/derivations.py | 15 ++-- scripts/acquire/provenance.py | 11 +-- scripts/core/ziptools.py | 73 ++++++++++------- scripts/packs/crossref.py | 18 +++-- scripts/packs/emulatorpack.py | 4 +- scripts/packs/integrity.py | 17 ++-- scripts/packs/platformpack.py | 7 +- scripts/resolve/packfiles.py | 4 +- scripts/romrecipes/build.py | 10 +-- scripts/romrecipes/identify.py | 11 +-- scripts/romrecipes/pool.py | 10 +-- scripts/scraper/romset_dat_importer.py | 12 +-- scripts/sitegen/cards.py | 5 +- scripts/sitegen/lookup.py | 13 ++-- tests/test_variant_archives.py | 104 +++++++++++++++++++++++++ wiki/testing-guide.md | 2 +- 16 files changed, 213 insertions(+), 103 deletions(-) create mode 100644 tests/test_variant_archives.py diff --git a/scripts/acquire/derivations.py b/scripts/acquire/derivations.py index 83a83ea35..fa9adb3b3 100644 --- a/scripts/acquire/derivations.py +++ b/scripts/acquire/derivations.py @@ -18,7 +18,7 @@ import zipfile from collections import defaultdict from collections.abc import Callable, Iterable, Sequence -from core.ziptools import is_archive_path +from core.ziptools import is_archive_path, zip_members # A held file larger than this is not read: no chip image is near it. MAX_SOURCE_SIZE = 64 * 1024 * 1024 @@ -158,18 +158,17 @@ def _held_sources(db: dict) -> list[dict]: if not is_archive_path(path): continue try: - with zipfile.ZipFile(path) as zf: - infos = [i for i in zf.infolist() if not i.is_dir()] + members = zip_members(path) except (OSError, zipfile.BadZipFile): continue sources.extend( { - "path": f"{path}/{info.filename}", "archive": path, - "member": info.filename, "size": info.file_size, - "crc32": f"{info.CRC:08x}", "group": path, + "path": f"{path}/{member.name}", "archive": path, + "member": member.name, "size": member.size, + "crc32": member.crc32, "group": path, } - for info in infos - if 0 < info.file_size <= MAX_SOURCE_SIZE + for member in members + if 0 < member.size <= MAX_SOURCE_SIZE ) return sources diff --git a/scripts/acquire/provenance.py b/scripts/acquire/provenance.py index aed681bbe..2b107509f 100644 --- a/scripts/acquire/provenance.py +++ b/scripts/acquire/provenance.py @@ -11,7 +11,7 @@ from pathlib import Path from core.hashing import parse_hash_list from core.paths import REPO_ROOT -from core.ziptools import is_archive_path +from core.ziptools import is_archive_path, zip_members from resolve.content import size_fits @@ -136,12 +136,9 @@ def archive_members(db: dict) -> dict[tuple[str, int], list[tuple[str, str]]]: if not is_archive_path(path) or not os.path.exists(path): continue try: - with zipfile.ZipFile(path) as archive: - for info in archive.infolist(): - if info.is_dir(): - continue - key = (f"{info.CRC:08x}", info.file_size) - members.setdefault(key, []).append((path, info.filename)) + for member in zip_members(path): + key = (member.crc32, member.size) + members.setdefault(key, []).append((path, member.name)) except (zipfile.BadZipFile, OSError) as exc: print(f" WARNING: {path}: {exc}", file=sys.stderr) return members diff --git a/scripts/core/ziptools.py b/scripts/core/ziptools.py index e90ccc7dd..e196b53b5 100644 --- a/scripts/core/ziptools.py +++ b/scripts/core/ziptools.py @@ -91,46 +91,51 @@ def _read_member_md5(source: str | io.BytesIO, folded: str, hashed: bool) -> str return "error" -@functools.lru_cache(maxsize=4096) -def _member_crcs(path: str, mtime: float) -> frozenset[str] | None: - try: - with zipfile.ZipFile(path) as archive: - return frozenset( - format(info.CRC, "08x") for info in archive.infolist() if not info.is_dir() - ) - except (zipfile.BadZipFile, OSError): - return None +@dataclass(frozen=True) +class ZipMember: + """One file of an archive, as its central directory lists it.""" + + name: str + size: int + crc32: str -@functools.lru_cache(maxsize=4096) -def _member_names(path: str, mtime: float) -> frozenset[str]: - try: - with zipfile.ZipFile(path) as archive: - return frozenset( - info.filename.rsplit("/", 1)[-1].casefold() - for info in archive.infolist() if not info.is_dir() - ) - except (zipfile.BadZipFile, OSError): - return frozenset() +@functools.lru_cache(maxsize=8192) +def _members(path: str, size: int, mtime_ns: int) -> tuple[ZipMember, ...]: + with zipfile.ZipFile(path) as archive: + return tuple( + ZipMember(info.filename, info.file_size, format(info.CRC, "08x")) + for info in archive.infolist() if not info.is_dir() + ) + + +def zip_members(path: str | os.PathLike[str]) -> tuple[ZipMember, ...]: + """Each file member of an archive, in directory order, read once. + + Keyed by the archive's size and mtime, so a rewritten archive is read + again. Raises OSError or zipfile.BadZipFile for a file that is no + readable archive, so each caller reports it in its own words. + """ + info = os.stat(path) + return _members(os.fspath(path), info.st_size, info.st_mtime_ns) def zip_member_names(path: str) -> frozenset[str]: """Casefolded base name of each member, read from the central directory.""" try: - mtime = os.path.getmtime(path) - except OSError: + members = zip_members(path) + except (zipfile.BadZipFile, OSError): return frozenset() - return _member_names(path, mtime) + return frozenset(m.name.rsplit("/", 1)[-1].casefold() for m in members) def readable_zip_member_crcs(path: str) -> frozenset[str] | None: """CRC-32 of each member, read from the central directory, None when the file is no readable archive.""" try: - mtime = os.path.getmtime(path) - except OSError: + return frozenset(m.crc32 for m in zip_members(path)) + except (zipfile.BadZipFile, OSError): return None - return _member_crcs(path, mtime) def zip_member_crcs(path: str) -> frozenset[str]: @@ -202,11 +207,17 @@ def build_zip_contents_index( """ global _zip_contents_cache + # Primaries first, then the .variants/ copies (x.zip.1a2b3c4d): a copy + # answers only for a member no primary holds. zip_entries: list[tuple[str, str]] = [] + variant_entries: list[tuple[str, str]] = [] for sha1, entry in db.get("files", {}).items(): path = entry["path"] - if path.endswith(".zip") and os.path.exists(path): - zip_entries.append((path, sha1)) + if is_archive_path(path) and os.path.exists(path): + primary = path.lower().endswith(".zip") + (zip_entries if primary else variant_entries).append((path, sha1)) + primaries = len(zip_entries) + zip_entries += variant_entries # The bound and the sha1 each path carries are part of the answer: a # second call with a smaller bound got members the first one admitted, @@ -221,7 +232,7 @@ def build_zip_contents_index( cached = _read_member_cache(cache_path) if cache_path else {} added = False index: dict[str, str] = {} - for path, sha1 in zip_entries: + for position, (path, sha1) in enumerate(zip_entries): members = cached.get(sha1) if members is None: members = _members_md5(path) @@ -230,8 +241,12 @@ def build_zip_contents_index( cached[sha1] = members added = True for md5, size in members: - if md5 is not None and size <= max_entry_size: + if md5 is None or size > max_entry_size: + continue + if position < primaries: index[md5] = sha1 + else: + index.setdefault(md5, sha1) if added and cache_path: _write_member_cache(cache_path, cached) diff --git a/scripts/packs/crossref.py b/scripts/packs/crossref.py index cb336a0e1..30200af0a 100644 --- a/scripts/packs/crossref.py +++ b/scripts/packs/crossref.py @@ -14,6 +14,7 @@ from typing import TYPE_CHECKING, TypedDict from core.hashing import parse_hash_list, stream_hashes from core.paths import BIOS_DIR, PLATFORMS_DIR, REPO_ROOT +from core.ziptools import is_archive_path, zip_members from model.alternatives import set_keys, set_requirements, settle_sets from model.database import get_mame_clone_map, sha1_at from model.profiles import lists_files @@ -158,10 +159,14 @@ def _zip_members(bios_root: str | Path) -> list[tuple[str, list[str]]]: return _zip_members_cache[key] found: list[tuple[str, list[str]]] = [] root = Path(bios_root) - for zpath in root.rglob("*.zip") if root.is_dir() else (): + # .variants/ copies (x.zip.1a2b3c4d) are archives too. + archives = sorted( + p for p in (root.rglob("*") if root.is_dir() else ()) + if is_archive_path(p.name) and p.is_file() + ) + for zpath in archives: try: - with zipfile.ZipFile(zpath) as zf: - members = [m for m in zf.namelist() if not m.endswith("/")] + members = [member.name for member in zip_members(zpath)] except (zipfile.BadZipFile, OSError) as exc: print(f" WARNING: unreadable archive {zpath}: {exc}", file=sys.stderr) continue @@ -345,10 +350,13 @@ def _content_matches(location: tuple[str, str], declared: dict[str, set[str]]) - """Whether the file or member at *location* carries a declared hash.""" path, member = location try: + if member and set(declared) == {"crc32"}: + return any( + held.name == member and held.crc32 in declared["crc32"] + for held in zip_members(path) + ) if member: with zipfile.ZipFile(path) as zf: - if set(declared) == {"crc32"}: - return f"{zf.getinfo(member).CRC:08x}" in declared["crc32"] data = zf.read(member) else: data = Path(path).read_bytes() diff --git a/scripts/packs/emulatorpack.py b/scripts/packs/emulatorpack.py index 1a9f130e4..3f5d12d5c 100644 --- a/scripts/packs/emulatorpack.py +++ b/scripts/packs/emulatorpack.py @@ -15,7 +15,7 @@ from typing import TYPE_CHECKING, TypedDict from core.options import reject_unknown from core.paths import REPO_ROOT -from core.ziptools import build_zip_contents_index +from core.ziptools import build_zip_contents_index, is_archive_path from model.alternatives import settle_sets, slot_set_keys from model.profiles import ( ProfileSelectionError, @@ -119,7 +119,7 @@ class _EmulatorPackBuild: def _add(self, local_path: str, dest: str, fe: dict | None) -> None: """Write a loose file or an archive at dest and count it.""" - if fe is not None and local_path.endswith(".zip"): + if fe is not None and is_archive_path(local_path): add_zip_to_pack(local_path, dest, self.zf, fe) else: add_pack_member(self.zf, local_path, dest) diff --git a/scripts/packs/integrity.py b/scripts/packs/integrity.py index 15cdd2117..a390e8950 100644 --- a/scripts/packs/integrity.py +++ b/scripts/packs/integrity.py @@ -12,7 +12,7 @@ from typing import TYPE_CHECKING, TypedDict from core.artifacts import build_timestamp from packs.paths import MEDIA_MARKER, has_path_conflict -from core.ziptools import build_zip_contents_index, is_archive_path +from core.ziptools import build_zip_contents_index, is_archive_path, zip_members from core.ziptools import safe_member_parts from resolve.nativemode import digest_algorithm, platform_mode from resolve.validation import ( @@ -106,10 +106,6 @@ def _settle_untracked( return "untracked", file_name -def _member_crcs(archive: zipfile.ZipFile) -> dict[str, int]: - return {i.filename: i.CRC for i in archive.infolist() if not i.is_dir()} - - def _same_members(pack: zipfile.ZipFile, name: str, source: str) -> bool: """Whether a ZIP inside the pack holds the members of a ZIP on disk. @@ -118,9 +114,12 @@ def _same_members(pack: zipfile.ZipFile, name: str, source: str) -> bool: each carried their own copy. """ try: - with zipfile.ZipFile(io.BytesIO(pack.read(name))) as packed, \ - zipfile.ZipFile(source) as held: - return _member_crcs(packed) == _member_crcs(held) + held = {member.name: member.crc32 for member in zip_members(source)} + with zipfile.ZipFile(io.BytesIO(pack.read(name))) as packed: + return held == { + info.filename: format(info.CRC, "08x") + for info in packed.infolist() if not info.is_dir() + } except (zipfile.BadZipFile, OSError): return False @@ -622,7 +621,7 @@ def _same_content(zf: zipfile.ZipFile, member: str, local: str) -> bool: with open(local, "rb") as handle: if zf.read(member) == handle.read(): return True - return local.lower().endswith(".zip") and _same_members(zf, member, local) + return is_archive_path(local) and _same_members(zf, member, local) class PlatformCheckOptions(TypedDict, total=False): diff --git a/scripts/packs/platformpack.py b/scripts/packs/platformpack.py index a423fb97d..fcf3f7e5b 100644 --- a/scripts/packs/platformpack.py +++ b/scripts/packs/platformpack.py @@ -15,6 +15,7 @@ from model.registry import load_platform_registry from core.hashing import compute_hashes from core.options import reject_unknown from core.paths import EMULATORS_DIR, declared_destination, sanitize_pack_path +from core.ziptools import is_archive_path from model.alternatives import core_file_spares from model.declarations import OUTER_ROOTS, declared_root from model.platforms import load_platform_config @@ -778,9 +779,9 @@ class _PlatformPackBuild: extract = file_entry.get("extract", False) flat_dest = self._flat(full_dest) - if extract and local_path.endswith(".zip"): + if extract and is_archive_path(local_path): extract_zip_to_archive(local_path, flat_dest, self.zf) - elif local_path.endswith(".zip"): + elif is_archive_path(local_path): add_zip_to_pack(local_path, flat_dest, self.zf, file_entry) else: add_pack_member(self.zf, local_path, flat_dest) @@ -876,7 +877,7 @@ class _PlatformPackBuild: within = plan.opts.within if within is not None and not same_bytes(local_path, within.get(flat_dest)): return - if local_path.endswith(".zip"): + if is_archive_path(local_path): add_zip_to_pack(local_path, flat_dest, self.zf, fe) else: add_pack_member(self.zf, local_path, flat_dest) diff --git a/scripts/resolve/packfiles.py b/scripts/resolve/packfiles.py index 24a670b75..4a2a6a86d 100644 --- a/scripts/resolve/packfiles.py +++ b/scripts/resolve/packfiles.py @@ -21,7 +21,7 @@ from core.hashing import declared_hash_lists, file_digest from resolve.content import declared_hash_verdict from resolve.localfile import resolution_is_hash_exact, resolve_local_file from core.paths import REPO_ROOT, declared_destination -from core.ziptools import readable_zip_member_crcs +from core.ziptools import is_archive_path, readable_zip_member_crcs from resolve.validation import inner_rom_check # CLI-wide network policy. Public helpers can override it explicitly, while # every CLI mode inherits --offline (including large-file release fallback). @@ -425,7 +425,7 @@ def _archive_choice( # that answers one of them (adam_fdc.zip: a one-member MAME set # answered first, the eight-member set sat beside it). def accepted(path: str | None) -> int: - if not path or not path.endswith(".zip"): + if not path or not is_archive_path(path): return -1 return sum(inner_rom_check(fe, path) == "ok" for fe in members) diff --git a/scripts/romrecipes/build.py b/scripts/romrecipes/build.py index ba5fe0c81..48f5b1ae4 100644 --- a/scripts/romrecipes/build.py +++ b/scripts/romrecipes/build.py @@ -3,14 +3,13 @@ from __future__ import annotations import os -import zipfile from dataclasses import dataclass, field from pathlib import Path from core.hashing import compute_hashes from core.paths import REPO_ROOT from core.torrentzip import write_torrentzip, zlib_ng_version -from core.ziptools import is_archive_path +from core.ziptools import is_archive_path, zip_members from romrecipes.members import member_sha1, member_opener @@ -74,12 +73,9 @@ class BuildResult: def _members_match(built: Path, members: list[dict]) -> str: """Empty when *built* holds exactly *members*, else what differs.""" expected = sorted((m["name"], m["size"], m["crc32"], m["sha1"]) for m in members) - with zipfile.ZipFile(built) as archive: - names = [info.filename for info in archive.infolist() if not info.is_dir()] - sizes = {info.filename: info.file_size for info in archive.infolist()} - crcs = {info.filename: f"{info.CRC:08x}" for info in archive.infolist()} held = sorted( - (name, sizes[name], crcs[name], member_sha1(built, name)) for name in names + (member.name, member.size, member.crc32, member_sha1(built, member.name)) + for member in zip_members(built) ) if held == expected: return "" diff --git a/scripts/romrecipes/identify.py b/scripts/romrecipes/identify.py index 055556b0d..13fe4fc5e 100644 --- a/scripts/romrecipes/identify.py +++ b/scripts/romrecipes/identify.py @@ -9,6 +9,7 @@ from collections import defaultdict from pathlib import Path from core.torrentzip import is_torrentzip +from core.ziptools import zip_members from romrecipes.pins import container_entries from romrecipes.pool import AtomPool from romrecipes.romsets import Recipe @@ -39,11 +40,7 @@ def identify_archive( def _member_list(path: Path) -> list[tuple[str, str]] | None: """Sorted (name, crc32) of an archive's members, from its directory.""" try: - with zipfile.ZipFile(path) as archive: - return sorted( - (info.filename, format(info.CRC, "08x")) - for info in archive.infolist() if not info.is_dir() - ) + return sorted((member.name, member.crc32) for member in zip_members(path)) except (zipfile.BadZipFile, OSError) as exc: print(f" UNREADABLE: {path}: {exc}", file=sys.stderr) return None @@ -84,10 +81,10 @@ def _is_archive(path: Path) -> bool: ROM, not an archive. Recipes only describe archives. """ try: - with zipfile.ZipFile(path): - return True + zip_members(path) except (OSError, zipfile.BadZipFile): return False + return True def _local_paths(archive: str, db: dict) -> list[Path]: diff --git a/scripts/romrecipes/pool.py b/scripts/romrecipes/pool.py index f84a22ee7..c80e744e7 100644 --- a/scripts/romrecipes/pool.py +++ b/scripts/romrecipes/pool.py @@ -10,7 +10,7 @@ from pathlib import Path from core.paths import REPO_ROOT from core.torrentzip import build_torrentzip -from core.ziptools import is_archive_path +from core.ziptools import is_archive_path, zip_members from romrecipes.romsets import Recipe @@ -42,12 +42,8 @@ class AtomPool: archives = (p for p in bios_dir.rglob("*") if is_archive_path(p.name) and p.is_file()) for archive in sorted(archives, key=lambda p: (".variants" in p.parts, p)): try: - with zipfile.ZipFile(archive) as handle: - for info in handle.infolist(): - if not info.is_dir(): - self._index.setdefault( - f"{info.CRC:08x}", (archive, info.filename) - ) + for member in zip_members(archive): + self._index.setdefault(member.crc32, (archive, member.name)) except (OSError, zipfile.BadZipFile) as exc: self.unreadable.append(f"{archive}: {exc}") # Loose ROMs, by the crc32 the database already computed: nmk004.zip diff --git a/scripts/scraper/romset_dat_importer.py b/scripts/scraper/romset_dat_importer.py index 0ba4e11c0..af4d2233c 100644 --- a/scripts/scraper/romset_dat_importer.py +++ b/scripts/scraper/romset_dat_importer.py @@ -40,6 +40,7 @@ from datetime import datetime, timezone from pathlib import Path from typing import IO +from core.ziptools import is_archive_path, zip_members from model.registry import list_registered_platforms from model.profiles import load_emulator_profiles from model.platforms import load_platform_config @@ -116,14 +117,13 @@ def collection_archives(db: dict) -> tuple[set[str], ByMembers]: for entry in db.get("files", {}).values(): path = Path(entry.get("path", "")) name = variant_base_name(path.name) - if not name.lower().endswith(".zip") or not path.is_file(): + if not is_archive_path(path.name) or not path.is_file(): continue try: - with zipfile.ZipFile(path) as archive: - held = [ - {"name": info.filename, "crc32": f"{info.CRC:08x}"} - for info in archive.infolist() if not info.is_dir() - ] + held = [ + {"name": member.name, "crc32": member.crc32} + for member in zip_members(path) + ] except (OSError, zipfile.BadZipFile) as exc: print(f" UNREADABLE: {path}: {exc}", file=sys.stderr) continue diff --git a/scripts/sitegen/cards.py b/scripts/sitegen/cards.py index 55247fc58..695547146 100644 --- a/scripts/sitegen/cards.py +++ b/scripts/sitegen/cards.py @@ -17,6 +17,7 @@ from packs.crossref import FileConsumers from romrecipes.romsets import dat_snapshots, usable_recipe from sitegen import markup, wanted as sitewanted from core.paths import REPO_ROOT +from core.ziptools import zip_members from model.mamerelease import tag_version from sitegen.fields import search_excluded from sitegen.install import manifest_systems, platform_display @@ -377,9 +378,7 @@ def _romset_line(f: dict) -> str: if not recipes or not path.is_file(): return "" try: - with zipfile.ZipFile(path) as archive: - held = tuple(sorted((info.filename, f"{info.CRC:08x}") - for info in archive.infolist() if not info.is_dir())) + held = tuple(sorted((member.name, member.crc32) for member in zip_members(path))) except (OSError, zipfile.BadZipFile) as exc: print(f" WARNING: {path}: {exc}", file=sys.stderr) return "" diff --git a/scripts/sitegen/lookup.py b/scripts/sitegen/lookup.py index 0237a3237..e8cf9feea 100644 --- a/scripts/sitegen/lookup.py +++ b/scripts/sitegen/lookup.py @@ -19,6 +19,7 @@ from packs.crossref import FileConsumers from sitegen.cards import PROVENANCE_LABELS, emulator_card_anchor, emulator_file_anchors from sitegen.config import SITE_URL from core.paths import REPO_ROOT +from core.ziptools import is_archive_path, zip_members from sitegen.render import card_anchor, code_span, slugify_anchor, card_page, emulator_card_page from sitegen.write import write_if_changed @@ -326,19 +327,17 @@ def _archive_member_records(entry: dict, sha1: str, url: str, no record. The record leads to the archive's card and names it. """ path = root / str(entry.get("path", "")) - if path.suffix.lower() != ".zip" or not path.is_file(): + if not is_archive_path(path.name) or not path.is_file(): return [] try: - with zipfile.ZipFile(path) as archive: - members = [(info.filename, info.CRC) for info in archive.infolist() - if not info.is_dir()] + members = zip_members(path) except (OSError, zipfile.BadZipFile) as exc: print(f" WARNING: {path}: members unreadable ({exc})", file=sys.stderr) return [] - return [{"value": f"{crc:08x}", "algorithm": "crc32", "layer": "archive-member", - "name": member.rsplit("/", 1)[-1], "archive": str(entry.get("name", "")), + return [{"value": member.crc32, "algorithm": "crc32", "layer": "archive-member", + "name": member.name.rsplit("/", 1)[-1], "archive": str(entry.get("name", "")), "sha1": sha1, "url": url} - for member, crc in members] + for member in members] def _collection_lookup_records( diff --git a/tests/test_variant_archives.py b/tests/test_variant_archives.py new file mode 100644 index 000000000..493a3cff4 --- /dev/null +++ b/tests/test_variant_archives.py @@ -0,0 +1,104 @@ +"""Every reader of collection archives sees the .variants/ copies. + +A copy kept as ``x.zip.1a2b3c4d`` is an archive, and the members it alone +holds are held: the site lookup, the gap report's member index, the inner +ROM index of the resolver and the pack check each tested a ``.zip`` suffix +and skipped them. All of them read members through core.ziptools. +""" + +from __future__ import annotations + +import tests + +import io +import tempfile +import unittest +import zipfile +from pathlib import Path + +from core.ziptools import build_zip_contents_index, zip_members +from packs.crossref import _zip_members +from packs.integrity import _same_content +from sitegen.cards import _release_name +from sitegen.lookup import _archive_member_records + + +def _write_zip(path: Path, members: dict[str, bytes]) -> Path: + path.parent.mkdir(parents=True, exist_ok=True) + with zipfile.ZipFile(path, "w") as zf: + for name, data in members.items(): + zf.writestr(name, data) + return path + + +class VariantArchives(unittest.TestCase): + def setUp(self): + tmp = tempfile.TemporaryDirectory() + self.addCleanup(tmp.cleanup) + self.root = Path(tmp.name) + self.primary = _write_zip(self.root / "bios" / "set.zip", {"a.rom": b"a" * 16}) + self.variant = _write_zip( + self.root / "bios" / ".variants" / "set.zip.1a2b3c4d", + {"a.rom": b"a" * 16, "only.rom": b"v" * 16}, + ) + + def test_members_come_from_the_central_directory(self): + with zipfile.ZipFile(self.variant, "a") as zf: + zf.writestr("dir/", b"") + members = zip_members(self.variant) + self.assertEqual([m.name for m in members], ["a.rom", "only.rom"]) + self.assertEqual(members[1].size, 16) + self.assertEqual(len(members[1].crc32), 8) + garbage = self.root / "bad.zip" + garbage.write_bytes(b"not an archive") + with self.assertRaises(zipfile.BadZipFile): + zip_members(garbage) + + def test_the_gap_report_lists_the_members_of_a_copy(self): + found = dict(_zip_members(self.root / "bios")) + self.assertEqual(found[str(self.variant)], ["a.rom", "only.rom"]) + + def test_a_copy_answers_only_for_what_no_primary_holds(self): + import hashlib + + db = {"files": { + "p": {"path": str(self.primary)}, + "v": {"path": str(self.variant)}, + }} + index = build_zip_contents_index(db, cache_path=None) + self.assertEqual(index[hashlib.md5(b"a" * 16).hexdigest()], "p") + self.assertEqual(index[hashlib.md5(b"v" * 16).hexdigest()], "v") + + def test_the_site_lookup_records_the_members_of_a_copy(self): + entry = {"path": str(self.variant.relative_to(self.root)), "name": "set.zip"} + records = _archive_member_records(entry, "v", "/files/", root=self.root) + self.assertEqual(sorted(r["name"] for r in records), ["a.rom", "only.rom"]) + + def test_the_pack_check_compares_members_with_a_copy(self): + packed = io.BytesIO() + with zipfile.ZipFile(packed, "w") as zf: + zf.writestr("set.zip", _rebuilt(self.variant)) + with zipfile.ZipFile(packed) as zf: + self.assertTrue(_same_content(zf, "set.zip", str(self.variant))) + + +def _rebuilt(source: Path) -> bytes: + """The same members written again, so the bytes differ.""" + out = io.BytesIO() + with zipfile.ZipFile(source) as src, \ + zipfile.ZipFile(out, "w", zipfile.ZIP_DEFLATED) as dst: + for info in src.infolist(): + dst.writestr(info.filename, src.read(info)) + return out.getvalue() + + +class MameReleaseNames(unittest.TestCase): + def test_a_mame_label_reads_as_its_version(self): + self.assertEqual(_release_name("mame", "MAME mame0220", {}), "0.220") + self.assertEqual(_release_name("mame", "MAME master", {}), "MAME master") + self.assertEqual(_release_name("fbneo", "FBNeo x", {"FBNeo x": "1.0.0.03"}), + "1.0.0.03") + + +if __name__ == "__main__": + unittest.main() diff --git a/wiki/testing-guide.md b/wiki/testing-guide.md index 0cb76ffd7..ca217e63c 100644 --- a/wiki/testing-guide.md +++ b/wiki/testing-guide.md @@ -63,7 +63,7 @@ Every module in `tests/`, by the area it guards. |------|----------|---------| | Core regression suites | synthetic | `test_e2e`, `test_audit_regressions`, `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_choice`, `test_variant_identity`, `test_zipped_member` | +| 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_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` | | Packs and manifests | synthetic + real packs | `test_artifact_lock`, `test_atomic_artifacts`, `test_batocera_cores`, `test_core_data_trees`, `test_deterministic_zip`, `test_emulator_pack_counts`, `test_finalize_pack_names`, `test_large_file_cache`, `test_libretro_layout`, `test_manifest_entry`, `test_minui_platform`, `test_no_game_data`, `test_pack_conformance_dirs`, `test_pack_core_extras`, `test_pack_counts`, `test_pack_destinations`, `test_pack_failures`, `test_pack_file_names`, `test_pack_grouping`, `test_pack_integrity`, `test_pack_member_identity`, `test_pack_readme`, `test_platform_inheritance`, `test_platform_keys`, `test_release_packs`, `test_required_only_archives`, `test_required_only_twins`, `test_save_root`, `test_split_extras`, `test_split_names`, `test_split_pack`, `test_system_pack_extras`, `test_system_pack_parity`, `test_torrentzip`, `test_which_pack` | | Slots and regions | synthetic + profiles | `test_region`, `test_region_agnostic_scan`, `test_region_groups`, `test_region_held`, `test_region_platform_index`, `test_region_required_only`, `test_slot`, `test_slots`, `test_slots_shipped_file` |