diff --git a/recipes/mame.json b/recipes/mame.json index 0d02d410e..f3a6b1b67 100644 --- a/recipes/mame.json +++ b/recipes/mame.json @@ -35743,13 +35743,13 @@ "sha1": "3f9a3d9940b36d4fee5eca9f1359c99d7ed545b9" }, { - "name": "f&m.expansion.3.1.e5", + "name": "f&m.expansion.3.1.e5", "size": 4096, "crc32": "818ca2ef", "sha1": "ea000097622e7fd472d53e7899e3c83773433045" }, { - "name": "f&m.expansion.3.2.e5", + "name": "f&m.expansion.3.2.e5", "size": 4096, "crc32": "0f0fc960", "sha1": "eb6b6e7bc9e761d13554482025d8cb5e260c0619" @@ -35790,13 +35790,13 @@ "sha1": "e80481054c6997a5f418d8a5872ac0110ae7b75a" }, { - "name": "f&m.basic.bin", + "name": "f&m.basic.bin", "size": 8192, "crc32": "22ab7b61", "sha1": "68b5770bca37b1ba94083f944086884e612b5a1b" }, { - "name": "f&m.eprom.board.1.1.bin", + "name": "f&m.eprom.board.1.1.bin", "size": 2048, "crc32": "a042a31a", "sha1": "13831a1350aa62a87988bfcc99c4b7db8ef1cf62" @@ -36107,7 +36107,7 @@ "description": "comx_prn", "members": [ { - "name": "f&m.printer.1.2.bin", + "name": "f&m.printer.1.2.bin", "size": 4096, "crc32": "2feb997d", "sha1": "ee9cb91042696c88ff5f2f44d2f702dc93369ba0" diff --git a/scripts/scraper/arcade_parent_importer.py b/scripts/scraper/arcade_parent_importer.py index 7c9a692dc..e0dcabf5a 100644 --- a/scripts/scraper/arcade_parent_importer.py +++ b/scripts/scraper/arcade_parent_importer.py @@ -45,7 +45,7 @@ import sys import urllib.parse import zipfile from collections import Counter -from collections.abc import Callable, Iterator +from collections.abc import Iterator from dataclasses import dataclass, field from pathlib import Path from typing import IO @@ -56,13 +56,11 @@ from model.profiles import load_emulator_profiles from core.cli import run_cli from core.hashing import compute_hashes from .base_scraper import download +from .listxml import Opener, attrs, iter_elements, open_listxml, rom_members from .romset_dat_importer import ( - LISTXML_CHUNK, MAME_LISTXML_URL, BlobMismatchError, _api_json, - _listxml_opener, - _machine_roms, fetch_pack, git_blob_sha, ) @@ -129,61 +127,26 @@ class SetEntry: source: str | None = None -_ELEMENT = re.compile(rb"<(machine|game)\b([^>]*)>") -_ATTR = re.compile(rb'([\w:-]+)="([^"]*)"') _DEVICE_REF = re.compile(rb']*\bname="([^"]+)"') _DISK = re.compile(rb"]*)>") -# Longer than any start tag the DATs write, shorter than any element. -_TAG_TAIL = 4096 - - -def _attrs(raw: bytes) -> dict[str, str]: - return {k.decode(): v.decode() for k, v in _ATTR.findall(raw)} def iter_sets(stream: IO[bytes]) -> Iterator[SetEntry]: - """Every machine or game element of a DAT or -listxml, streamed. - - Attributes come in any order (mame2003 writes ````), and the document is never held whole: the window - keeps only the element being closed. - """ - buffer = b"" - while True: - chunk = stream.read(LISTXML_CHUNK) - buffer += chunk - position = 0 - # Where the next read has to resume: the start of an element still - # open, else a tail long enough to hold a start tag cut in two. - keep_from = max(0, len(buffer) - _TAG_TAIL) - while True: - match = _ELEMENT.search(buffer, position) - if not match: - break - closing = b"" - end = buffer.find(closing, match.end()) - if end == -1: - keep_from = match.start() - break - attrs = _attrs(match.group(2)) - body = buffer[match.end() : end] - disks = [_attrs(d) for d in _DISK.findall(body)] - yield SetEntry( - name=attrs.get("name", ""), - romof=attrs.get("romof") or None, - isbios=attrs.get("isbios") == "yes", - isdevice=attrs.get("isdevice") == "yes", - runnable=attrs.get("runnable", "yes") != "no", - has_roms=bool(_machine_roms(body)), - disks=any(d.get("status") != "nodump" for d in disks), - devices=[d.decode() for d in _DEVICE_REF.findall(body)], - source=attrs.get("sourcefile"), - ) - position = end + len(closing) - keep_from = max(position, len(buffer) - _TAG_TAIL) - if not chunk: - return - buffer = buffer[keep_from:] + """Every machine or game element of a DAT or -listxml, streamed.""" + for element in iter_elements(stream, ("machine", "game")): + found, body = element.attrs, element.body + disks = [attrs(d) for d in _DISK.findall(body)] + yield SetEntry( + name=found.get("name", ""), + romof=found.get("romof") or None, + isbios=found.get("isbios") == "yes", + isdevice=found.get("isdevice") == "yes", + runnable=found.get("runnable", "yes") != "no", + has_roms=bool(rom_members(body)), + disks=any(d.get("status") != "nodump" for d in disks), + devices=[d.decode() for d in _DEVICE_REF.findall(body)], + source=found.get("sourcefile"), + ) def is_bios(entry: SetEntry, marker: str) -> bool: @@ -313,7 +276,7 @@ def _fbneo_driver_names(entries: list[SetEntry], names: dict[str, set[str]]) -> def fbneo_sets( - openers: list[Callable[[], IO[bytes]]], names: dict[str, set[str]] + openers: list[Opener], names: dict[str, set[str]] ) -> tuple[dict[str, SetEntry], dict[str, str]]: """Every set of FBNeo's DATs keyed by its driver, and the archive of each set whose driver name is not its archive name. @@ -1012,11 +975,11 @@ def _cached_repo_file(slug: str, commit: str, path: str, cache_dir: Path) -> tup return destination, git_blob_sha(destination.read_bytes()) -def _file_opener(path: Path) -> Callable[[], IO[bytes]]: +def _file_opener(path: Path) -> Opener: return lambda: path.open("rb") -def _xml_streams(path: Path) -> Iterator[Callable[[], IO[bytes]]]: +def _xml_streams(path: Path) -> Iterator[Opener]: """Openers for the XML documents a file holds: itself, or each XML or DAT member of a ZIP.""" if path.suffix.lower() != ".zip": @@ -1035,7 +998,7 @@ def _xml_streams(path: Path) -> Iterator[Callable[[], IO[bytes]]]: yield opener -def read_sets(openers: list[Callable[[], IO[bytes]]]) -> dict[str, SetEntry]: +def read_sets(openers: list[Opener]) -> dict[str, SetEntry]: """Every set of several documents. A set read twice keeps its first reading: FBNeo's Arcade and Neogeo DATs both carry the neogeo BIOS.""" sets: dict[str, SetEntry] = {} @@ -1059,7 +1022,7 @@ def import_profile( source_url = str(data.get("source") or "") kind = spec["kind"] source: dict[str, object] - openers: list[Callable[[], IO[bytes]]] + openers: list[Opener] if kind == "listxml": tag = "mame" + str(data["core_version"]).replace(".", "").zfill(4) if offline: @@ -1073,7 +1036,7 @@ def import_profile( "url": MAME_LISTXML_URL.format(tag=tag), "sha256": compute_hashes(pack, frozenset({"sha256"}), cache=False)["sha256"], } - index = build_index(read_sets([_listxml_opener(pack)]), spec["marker"]) + index = build_index(read_sets([lambda: open_listxml(pack)]), spec["marker"]) elif kind == "fbneo": if offline: folder = cache_dir / "fbneo-dats" diff --git a/scripts/scraper/listxml.py b/scripts/scraper/listxml.py new file mode 100644 index 000000000..2e163f3c4 --- /dev/null +++ b/scripts/scraper/listxml.py @@ -0,0 +1,120 @@ +"""Streaming reader for MAME -listxml documents and Logiqx DATs. + +The 0.289 listxml is 311 MB, so a document is read through a sliding window +and never held whole. romset_dat_importer, mame_devices and +arcade_parent_importer read elements, attributes and ROM members here. +""" + +from __future__ import annotations + +import html +import re +import zipfile +from collections.abc import Callable, Collection, Iterator +from contextlib import AbstractContextManager, contextmanager +from pathlib import Path +from typing import IO, NamedTuple + +LISTXML_CHUNK = 8 * 1024 * 1024 +# Longer than any start tag the documents write, shorter than any element. +_TAG_TAIL = 4096 + +_ATTR = re.compile(rb'([\w:-]+)="([^"]*)"') +_ROM = re.compile(rb"]*)>") + +Opener = Callable[[], AbstractContextManager[IO[bytes]]] + + +class Element(NamedTuple): + tag: str + attrs: dict[str, str] + body: bytes + + +def attrs(raw: bytes) -> dict[str, str]: + """Attributes of a start tag, entities decoded (``f&m.basic.bin``).""" + return { + key.decode(): html.unescape(value.decode()) + for key, value in _ATTR.findall(raw) + } + + +def iter_elements( + stream: IO[bytes], tags: Collection[str] = ("machine",), head: bytes = b"", +) -> Iterator[Element]: + """Every element named in *tags*, in document order. + + Attributes come in any order (mame2003 writes ````). The window keeps the element still open from its start + tag and grows until that element closes, whatever its size. *head* is + what the caller already read from *stream*. + """ + element = re.compile(rb"<(" + b"|".join(t.encode() for t in tags) + rb")\b([^>]*)>") + buffer = head + while True: + chunk = stream.read(LISTXML_CHUNK) + buffer += chunk + position = 0 + # Where the next read has to resume: the start of an element still + # open, else a tail long enough to hold a start tag cut in two. + keep_from = max(0, len(buffer) - _TAG_TAIL) + while match := element.search(buffer, position): + closing = b"" + end = buffer.find(closing, match.end()) + if end == -1: + keep_from = match.start() + break + yield Element( + match.group(1).decode(), attrs(match.group(2)), buffer[match.end() : end] + ) + position = end + len(closing) + keep_from = max(position, len(buffer) - _TAG_TAIL) + if not chunk: + return + buffer = buffer[keep_from:] + + +def rom_members( + body: bytes, dedupe: bool = False, extra: Collection[str] = (), +) -> list[dict]: + """Dumped ROMs of one element: name, size, crc32, sha1. + + A ROM without a crc is undumped and left out. *dedupe* keeps the first + ROM of each name, as the loader does. *extra* names attributes copied + when the ROM writes them. + """ + members: list[dict] = [] + seen: set[str] = set() + for match in _ROM.finditer(body): + found = attrs(match.group(1)) + name, crc = found.get("name", ""), found.get("crc", "").lower() + if not name or not crc or (dedupe and name in seen): + continue + seen.add(name) + try: + size = int(found.get("size", "0") or 0) + except ValueError: + size = 0 + member = {"name": name, "size": size, "crc32": crc, "sha1": found.get("sha1", "").lower()} + member.update((key, found[key]) for key in extra if key in found) + members.append(member) + return members + + +def xml_members(archive: zipfile.ZipFile) -> list[str]: + return [n for n in archive.namelist() if n.lower().endswith(".xml")] + + +@contextmanager +def open_listxml(path: Path) -> Iterator[IO[bytes]]: + """Byte stream over a -listxml document, plain or as MAME's release zip.""" + if path.suffix.lower() != ".zip": + with path.open("rb") as stream: + yield stream + return + with zipfile.ZipFile(path) as archive: + names = xml_members(archive) + if len(names) != 1: + raise ValueError(f"{path}: expected one .xml member, found {len(names)}") + with archive.open(names[0]) as stream: + yield stream diff --git a/scripts/scraper/mame_devices.py b/scripts/scraper/mame_devices.py index a8a2c7cf3..3ae7b8fd7 100644 --- a/scripts/scraper/mame_devices.py +++ b/scripts/scraper/mame_devices.py @@ -20,26 +20,19 @@ from __future__ import annotations import html import re -import zipfile -from collections.abc import Callable, Collection, Iterable, Iterator +from collections.abc import Callable, Collection, Iterable from concurrent.futures import ThreadPoolExecutor -from contextlib import contextmanager -from pathlib import Path from typing import IO, NamedTuple from model.safeparse import yaml_load from ._hash_merge import generated_start +from .listxml import LISTXML_CHUNK, attrs, iter_elements, rom_members from .mame_parser import _collect_rom_macros, _expand_macros, _parse_rom_entries -LISTXML_CHUNK = 8 * 1024 * 1024 - _BUILD = re.compile(rb']*)>') -_ATTR = re.compile(rb'(\w+)="([^"]*)"') _DESCRIPTION = re.compile(rb"(.*?)", re.S) _BIOSSET = re.compile(rb"]*)>") -_ROM = re.compile(rb"]*)>") _DEVICE_REF = re.compile(rb']*\bname="([^"]+)"') _SLOT_OPTION = re.compile(rb']*\bdevname="([^"]+)"') _SOFTWARE_LIST = re.compile(rb']*\bname="([^"]+)"') @@ -60,53 +53,21 @@ AMBIGUOUS = "ambiguous" NO_FILE = "no file" -def _attrs(raw: bytes) -> dict[str, str]: - return { - key.decode(): html.unescape(value.decode()) - for key, value in _ATTR.findall(raw) - } - - def _device_roms(body: bytes) -> list[dict]: """Dumped ROMs of one machine element, first of each name kept.""" bios_names = { - attrs.get("name", ""): attrs.get("description", "") - for attrs in map(_attrs, _BIOSSET.findall(body)) + found.get("name", ""): found.get("description", "") + for found in map(attrs, _BIOSSET.findall(body)) } - roms: dict[str, dict] = {} - for match in _ROM.finditer(body): - attrs = _attrs(match.group(1)) - name, crc = attrs.get("name", ""), attrs.get("crc", "").lower() - if not name or not crc or name in roms: - continue - rom: dict = { - "name": name, - "size": int(attrs.get("size", "0") or 0), - "crc32": crc, - "sha1": attrs.get("sha1", "").lower(), - } - if attrs.get("status") == "baddump": + roms: list[dict] = [] + for rom in rom_members(body, dedupe=True, extra=("status", "bios")): + if rom.pop("status", "") == "baddump": rom["bad_dump"] = True - description = bios_names.get(attrs.get("bios", ""), "") + description = bios_names.get(rom.pop("bios", ""), "") if description: rom["bios_description"] = description - roms[name] = rom - return list(roms.values()) - - -@contextmanager -def open_listxml(path: Path) -> Iterator[IO[bytes]]: - """Byte stream over a -listxml document, plain or as MAME's release zip.""" - if path.suffix.lower() != ".zip": - with path.open("rb") as stream: - yield stream - return - with zipfile.ZipFile(path) as archive: - names = [n for n in archive.namelist() if n.lower().endswith(".xml")] - if len(names) != 1: - raise ValueError(f"{path}: expected one .xml member, found {len(names)}") - with archive.open(names[0]) as stream: - yield stream + roms.append(rom) + return roms class MachineLinks(NamedTuple): @@ -144,48 +105,37 @@ def scan_release(stream: IO[bytes]) -> Release: configuration (2184-2198). device_t::searchpath puts the parent ROM device after the device itself (src/emu/device.cpp:140-152). """ - tag = "" + head = stream.read(LISTXML_CHUNK) + build = _BUILD.search(head) + tag = build.group(1).decode() if build else "" devices: dict[str, dict] = {} machines: dict[str, MachineLinks] = {} - buffer = b"" - while chunk := stream.read(LISTXML_CHUNK): - buffer += chunk - if not tag and (build := _BUILD.search(buffer)): - tag = build.group(1).decode() - position = 0 - while match := _MACHINE.search(buffer, position): - end = buffer.find(b"", match.end()) - if end == -1: - break - name = match.group(1).decode() - attrs = _attrs(match.group(2)) - body = buffer[match.end() : end] - isdevice = attrs.get("isdevice") == "yes" - romof = attrs.get("romof", "") - uses = { - ref.decode() - for ref in (*_DEVICE_REF.findall(body), *_SLOT_OPTION.findall(body)) - } - if isdevice and romof: - uses.add(romof) - uses.discard(name) - softlists = {found.decode() for found in _SOFTWARE_LIST.findall(body)} - machines[name] = MachineLinks( - romof, isdevice, tuple(sorted(uses)), tuple(sorted(softlists)), - attrs.get("sourcefile", ""), - ) - if isdevice: - roms = _device_roms(body) - if roms: - description = _DESCRIPTION.search(body) - devices[name] = { - "description": html.unescape(description.group(1).decode()) - if description else "", - "sourcefile": attrs.get("sourcefile", ""), - "roms": roms, - } - position = end + len(b"") - buffer = buffer[position:] if position else buffer[-(2 * LISTXML_CHUNK) :] + for element in iter_elements(stream, head=head): + name, found, body = element.attrs.get("name", ""), element.attrs, element.body + isdevice = found.get("isdevice") == "yes" + romof = found.get("romof", "") + uses = { + ref.decode() + for ref in (*_DEVICE_REF.findall(body), *_SLOT_OPTION.findall(body)) + } + if isdevice and romof: + uses.add(romof) + uses.discard(name) + softlists = {item.decode() for item in _SOFTWARE_LIST.findall(body)} + machines[name] = MachineLinks( + romof, isdevice, tuple(sorted(uses)), tuple(sorted(softlists)), + found.get("sourcefile", ""), + ) + if isdevice: + roms = _device_roms(body) + if roms: + description = _DESCRIPTION.search(body) + devices[name] = { + "description": html.unescape(description.group(1).decode()) + if description else "", + "sourcefile": found.get("sourcefile", ""), + "roms": roms, + } if not tag: raise ValueError("no header: not a MAME -listxml document") return Release(tag, devices, machines) diff --git a/scripts/scraper/mame_hash_scraper.py b/scripts/scraper/mame_hash_scraper.py index 6bdfe76b6..a3f59d345 100644 --- a/scripts/scraper/mame_hash_scraper.py +++ b/scripts/scraper/mame_hash_scraper.py @@ -49,12 +49,12 @@ from .mame_devices import ( floppy_drives, floppy_sample_systems, locate_sources, - open_listxml, platform_seeds, profile_seeds, scan_release, source_path, ) +from .listxml import open_listxml from .mame_parser import parse_mame_source_tree from core.paths import REPO_ROOT diff --git a/scripts/scraper/romset_dat_importer.py b/scripts/scraper/romset_dat_importer.py index e6276131a..4e089e349 100644 --- a/scripts/scraper/romset_dat_importer.py +++ b/scripts/scraper/romset_dat_importer.py @@ -48,6 +48,7 @@ from model.platforms import load_platform_config from core.cli import add_repo_inputs, run_cli from model.dumpcatalog import build_snapshot, load_provenance_snapshots, write_snapshot from .base_scraper import download, fetch_github_latest_version, github_json +from .listxml import Opener, iter_elements, open_listxml, rom_members, xml_members from .logiqx_parser import LogiqxDat, parse_logiqx MAX_MEMBER_SIZE = 200 * 1024 * 1024 @@ -243,87 +244,26 @@ def recipe_entries( return one_set_per_archive(entries) -_MACHINE = re.compile(rb']*)>') -_ROM = re.compile( - rb']*\bcrc="([0-9a-fA-F]+)")[^>]*>' -) -_ROM_ATTR = re.compile(rb'(\w+)="([^"]*)"') -_ROMOF = re.compile(r'romof="([^"]+)"') -LISTXML_CHUNK = 8 * 1024 * 1024 - - -def _machine_roms(blob: bytes) -> list[dict]: - """ROM members of one machine element, undumped ones dropped.""" - members: list[dict] = [] - for match in re.finditer(rb"]*)>", blob): - attrs = { - key.decode(): value.decode() - for key, value in _ROM_ATTR.findall(match.group(1)) - } - crc = attrs.get("crc", "").lower() - name = attrs.get("name", "") - if not name or not crc: - continue - try: - size = int(attrs.get("size", "0")) - except ValueError: - size = 0 - members.append( - { - "name": name, - "size": size, - "crc32": crc, - "sha1": attrs.get("sha1", "").lower(), - } - ) - return members - - def _scan_listxml( stream: IO[bytes], selector: Callable[[str], bool], targets: Targets | None = None, ) -> dict[str, tuple[str | None, list[dict]]]: """Stream a MAME -listxml document, keeping the machines *selector* wants - and those holding one of *targets*. - - The document is 311 MB for MAME 0.289, so it is never held whole: the - window keeps the element still open from its start tag, and grows until - that element closes, whatever its size. - """ + and those holding one of *targets*.""" found: dict[str, tuple[str | None, list[dict]]] = {} - buffer = b"" - while chunk := stream.read(LISTXML_CHUNK): - buffer += chunk - position = 0 - keep_from = None - while True: - match = _MACHINE.search(buffer, position) - if not match: - break - end = buffer.find(b"", match.end()) - if end == -1: - keep_from = match.start() - break - name = match.group(1).decode() - wanted = selector(name) - if wanted or targets: - roms = _machine_roms(buffer[match.end() : end]) - if wanted or holds_target(roms, targets): - parent = _ROMOF.search(match.group(2).decode()) - found[name] = (parent.group(1) if parent else None, roms) - position = end + len(b"") - if keep_from is None: - # No element open: only a start tag cut by the read can follow. - start = buffer.rfind(b" bool: - """Whether *pack* holds a MAME -listxml document rather than a DAT.""" + """Whether *pack* holds a MAME -listxml document rather than a DAT. + + A ZIP of several XML documents is a DAT collection.""" if pack.is_dir(): return False if pack.suffix.lower() == ".zip": with zipfile.ZipFile(pack) as archive: - names = [n for n in archive.namelist() if n.lower().endswith(".xml")] - if not names: + if len(xml_members(archive)) != 1: return False - with archive.open(names[0]) as handle: - return b" Callable[[], IO[bytes]]: - """A callable giving a fresh byte stream over the listxml document.""" - if pack.suffix.lower() == ".zip": - def opener() -> IO[bytes]: - archive = zipfile.ZipFile(pack) - name = next(n for n in archive.namelist() if n.lower().endswith(".xml")) - # The member keeps the archive alive: its shared file closes - # through the archive's own _fpclose. - return archive.open(name) - - return opener - return lambda: pack.open("rb") - - def _parser() -> argparse.ArgumentParser: parser = argparse.ArgumentParser(allow_abbrev=False, description=__doc__) parser.add_argument( @@ -656,7 +581,7 @@ def _selection(args: argparse.Namespace) -> _Selection: def _import_listxml(pack: Path, args: argparse.Namespace, output: str, chosen: _Selection) -> int: label = f"MAME {pack.stem.replace('lx', '')}" entries = listxml_entries( - _listxml_opener(pack), label, chosen.keep, chosen.targets, chosen.by_members + lambda: open_listxml(pack), label, chosen.keep, chosen.targets, chosen.by_members ) dats = {label: pack.stem} print(f" {label}: {len(entries)} sets retenus") diff --git a/tests/test_arcade_parents.py b/tests/test_arcade_parents.py index 7dc28e2a8..144128b14 100644 --- a/tests/test_arcade_parents.py +++ b/tests/test_arcade_parents.py @@ -12,6 +12,7 @@ import zipfile from pathlib import Path from scripts.scraper import arcade_parent_importer as api +from scripts.scraper import listxml ROOT = Path(__file__).resolve().parent.parent TMP_ROOT = ROOT / "tmp" / "tests" @@ -29,13 +30,13 @@ COMMIT = "a" * 40 def _sets(name: str, chunk: int | None = None) -> dict: data = (FIXTURES / name).read_bytes() - saved = api.LISTXML_CHUNK + saved = listxml.LISTXML_CHUNK if chunk: - api.LISTXML_CHUNK = chunk + listxml.LISTXML_CHUNK = chunk try: return api.read_sets([lambda: io.BytesIO(data)]) finally: - api.LISTXML_CHUNK = saved + listxml.LISTXML_CHUNK = saved class ListxmlIndex(unittest.TestCase): diff --git a/tests/test_listxml.py b/tests/test_listxml.py new file mode 100644 index 000000000..23ea8c440 --- /dev/null +++ b/tests/test_listxml.py @@ -0,0 +1,104 @@ +"""The streaming reader shared by the MAME listxml and DAT importers.""" + +from __future__ import annotations + +import tests + +import io +import tempfile +import unittest +import zipfile +from pathlib import Path + +from scripts.scraper import listxml +from scripts.scraper.listxml import attrs, iter_elements, open_listxml, rom_members + +DOCUMENT = b""" + +\t +\t\t +\t\t +\t\t +\t\t +\t +\t + +""" + + +class ElementsAreStreamed(unittest.TestCase): + def _read(self, tags: tuple[str, ...]) -> list[listxml.Element]: + return list(iter_elements(io.BytesIO(DOCUMENT), tags)) + + def test_every_named_element_in_order(self): + found = self._read(("machine", "game")) + self.assertEqual([(e.tag, e.attrs["name"]) for e in found], + [("machine", "comx_eb"), ("game", "neogeo")]) + self.assertEqual(found[1].attrs["runnable"], "no") + + def test_other_elements_are_skipped(self): + self.assertEqual([e.attrs["name"] for e in self._read(("machine",))], ["comx_eb"]) + + def test_any_window_reads_the_same_elements(self): + expected = self._read(("machine", "game")) + saved = listxml.LISTXML_CHUNK + try: + for window in (1, 5, 33): + listxml.LISTXML_CHUNK = window + self.assertEqual(self._read(("machine", "game")), expected, window) + finally: + listxml.LISTXML_CHUNK = saved + + def test_head_is_read_before_the_stream(self): + stream = io.BytesIO(DOCUMENT) + head = stream.read(60) + names = [e.attrs["name"] for e in iter_elements(stream, ("machine", "game"), head)] + self.assertEqual(names, ["comx_eb", "neogeo"]) + + +class AttributesAndMembers(unittest.TestCase): + def test_entities_are_decoded(self): + self.assertEqual(attrs(b' name="f&m" x:y=""q""'), + {"name": "f&m", "x:y": '"q"'}) + + def test_undumped_roms_are_left_out(self): + body = next(iter_elements(io.BytesIO(DOCUMENT))).body + self.assertEqual([m["name"] for m in rom_members(body)], + ["f&m.basic.bin", "dup.bin", "dup.bin"]) + + def test_dedupe_keeps_the_first_of_a_name(self): + body = next(iter_elements(io.BytesIO(DOCUMENT))).body + members = rom_members(body, dedupe=True, extra=("status",)) + self.assertEqual(members[0], {"name": "f&m.basic.bin", "size": 4096, + "crc32": "52cb44e2", "sha1": "ab"}) + self.assertEqual(members[1], {"name": "dup.bin", "size": 16, + "crc32": "00000001", "sha1": ""}) + self.assertEqual(len(members), 2) + + def test_an_unreadable_size_is_zero(self): + body = list(iter_elements(io.BytesIO(DOCUMENT), ("game",)))[0].body + self.assertEqual(rom_members(body)[0]["size"], 0) + + +class ReleaseArchive(unittest.TestCase): + def test_one_xml_member_is_opened(self): + with tempfile.TemporaryDirectory() as folder: + pack = Path(folder) / "mame0289lx.zip" + with zipfile.ZipFile(pack, "w") as archive: + archive.writestr("mame0289.xml", DOCUMENT) + with open_listxml(pack) as stream: + self.assertEqual(stream.read(), DOCUMENT) + + def test_an_archive_without_exactly_one_xml_is_refused(self): + with tempfile.TemporaryDirectory() as folder: + pack = Path(folder) / "pack.zip" + with zipfile.ZipFile(pack, "w") as archive: + archive.writestr("a.xml", DOCUMENT) + archive.writestr("b.xml", DOCUMENT) + with (self.assertRaisesRegex(ValueError, "expected one .xml member, found 2"), + open_listxml(pack)): + pass + + +if __name__ == "__main__": + unittest.main() diff --git a/tests/test_mame_devices.py b/tests/test_mame_devices.py index 89173edd3..29b5036eb 100644 --- a/tests/test_mame_devices.py +++ b/tests/test_mame_devices.py @@ -26,6 +26,7 @@ from scripts.scraper._hash_merge import ( merge_mame_profile, merge_mame_support, ) +from scripts.scraper.listxml import open_listxml from scripts.scraper.mame_devices import ( ABSENT, AMBIGUOUS, @@ -40,7 +41,6 @@ from scripts.scraper.mame_devices import ( floppy_drives, floppy_sample_systems, locate_sources, - open_listxml, platform_seeds, profile_seeds, scan_device_sets, diff --git a/tests/test_romset_recipes.py b/tests/test_romset_recipes.py index 2bb10b1ab..9e40ced08 100644 --- a/tests/test_romset_recipes.py +++ b/tests/test_romset_recipes.py @@ -407,19 +407,19 @@ class ListXmlRecipes(unittest.TestCase): def test_a_machine_larger_than_the_window_is_kept(self): """Each machine here spans several reads: the window grows until the element closes instead of cutting its start tag away.""" - from scripts.scraper import romset_dat_importer + from scripts.scraper import listxml expected = listxml_entries(self._opener(self._document()), "MAME 0.289", None) - saved = romset_dat_importer.LISTXML_CHUNK + saved = listxml.LISTXML_CHUNK try: for window in (1, 7, 16, 64): - romset_dat_importer.LISTXML_CHUNK = window + listxml.LISTXML_CHUNK = window entries = listxml_entries( self._opener(self._document()), "MAME 0.289", None ) self.assertEqual(entries, expected, window) finally: - romset_dat_importer.LISTXML_CHUNK = saved + listxml.LISTXML_CHUNK = saved self.assertEqual( [entry["name"] for entry in entries], ["childset.zip", "parentset.zip"] )