refactor: keep shared test fixtures in helpers

Fifteen modules imported FakeRepository from test_install_selection, and
others read fixtures from test_install_app, test_install_offline,
test_install_games, test_launchers, test_prose_style, test_site_nav,
test_site_pronouns and test_site_copy. Those now live in installsupport,
gamessupport, launcherssupport, docpagessupport, sitepages and sitecopy,
and test_layers refuses an import of a test module.

sitereferencesupport and the DIST each site module defined merge into
sitepages, launchersretrobatsupport into launcherssupport, auditsupport
into the tests package (REPO_ROOT, HAS_JSONSCHEMA). test_launchers is the
Batocera module and becomes test_launchers_batocera. test_port becomes
test_handheld_port: its archive checks repeated test_handheld_scripts,
whose TheArchives now holds the port.json assertions.

The testing guide splits the row that held 113 modules, replaces the e2e
number ranges by a module table, gives package imports and scratch_dir in
How to add a test, lists every module that reads the working tree and
every helper module. Its guard moves to test_doc_pages_tools and checks
each module on one row once and each family on one row. The guide and
tools.md join the pages whose cited paths and options are looked up.
This commit is contained in:
Abdessamad Derraz committed 2026-11-24 10:10:15 +01:00
1 parent b2d4eee534
commit 74ba20ac10
73 files changed
+1718 -1585

No files matched your search

+7 -3
View File
@@ -13,6 +13,7 @@ temporary directory instead of naming the missing parent.
from __future__ import annotations
import importlib.util
import os
import shutil
import sys
@@ -27,10 +28,13 @@ os.environ.setdefault("RETROBIOS_OFFLINE", "1")
ONLINE = mock.patch.dict(os.environ, {"RETROBIOS_OFFLINE": ""})
# The modules under test import each other by bare name (common, verify), as
# the scripts do when run from scripts/, and install.py sits at the root.
_REPOSITORY = Path(__file__).resolve().parent.parent
for _path in (str(_REPOSITORY), str(_REPOSITORY / "scripts")):
REPO_ROOT = Path(__file__).resolve().parent.parent
for _path in (str(REPO_ROOT), str(REPO_ROOT / "scripts")):
if _path not in sys.path:
sys.path.insert(0, _path)
# jsonschema is a tooling dependency: the tests that validate a schema skip
# without it.
HAS_JSONSCHEMA = importlib.util.find_spec("jsonschema") is not None
# The installer reads the XDG base directories as RetroArch and the
# emulators do. The CI runner sets XDG_CONFIG_HOME to its own home, so tests
# that fake HOME found the runner's folders instead of theirs. A test that
@@ -48,7 +52,7 @@ os.environ.setdefault("RETROBIOS_PROBE_LOCK", str(_SCRATCH / "probe.lock"))
# The repository's own hold (database.json, install/, README.md) too: a
# pipeline run by one module no longer refuses another module's, nor the
# maintainer's real run beside the suite.
os.environ.setdefault("RETROBIOS_REPOSITORY_LOCK_DIR", str(_SCRATCH / "repository-lock"))
os.environ.setdefault("RETROBIOSREPO_ROOT_LOCK_DIR", str(_SCRATCH / "repository-lock"))
# A TemporaryDirectory() without dir= landed in /tmp, a 4 GB tmpfs here: once
# another run filled it, modules unrelated to any change failed with ENOSPC.
# The default is the repository's tmp/, for this process and its children.
-18
View File
@@ -1,18 +0,0 @@
"""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
+44
View File
@@ -6,8 +6,10 @@ import tests
from tests import mdsections
import functools
import io
import json
import re
import tokenize
from pathlib import Path
@@ -17,6 +19,12 @@ WIKI = ROOT / "wiki"
PUBLISHED = sorted(WIKI.glob("*.md")) + [ROOT / "README.md", ROOT / "CONTRIBUTING.md"]
# The marketing vocabulary the project refuses in published text.
MARKETING_WORDS = re.compile(
r"\b(comprehensive|robust|seamless(ly)?|leverag\w*|streamlin\w*|delv(e|ing))\b",
re.IGNORECASE,
)
def _page(name: str) -> str:
return (WIKI / name).read_text(encoding="utf-8")
@@ -44,3 +52,39 @@ def _registry() -> dict:
import yaml
return yaml.safe_load((ROOT / "platforms" / "_registry.yml").read_text(encoding="utf-8"))["platforms"]
def _python_prose(source: str) -> str:
"""Comments and docstrings of a module, one per line."""
parts: list[str] = []
previous = tokenize.INDENT
for token in tokenize.generate_tokens(io.StringIO(source).readline):
if token.type == tokenize.COMMENT or token.type == tokenize.STRING and previous in (
tokenize.INDENT, tokenize.NEWLINE, tokenize.NL, tokenize.DEDENT,
):
parts.append(token.string)
if token.type not in (tokenize.COMMENT, tokenize.NL):
previous = token.type
return "\n".join(parts)
# Words a heading keeps capitalized: names of platforms, systems and programs.
_HEADING_KEEP = set(["Batocera", "Recalbox", "Lakka", "Dolphin", "Redump", "Linux", "Windows", "Android", "Python", "Steam", "Deck", "macOS", "Termux", "Flatpak", "Switch", "Raspberry", "Pi", "Mega", "Drive", "Genesis", "Saturn", "Dreamcast", "Amiga", "Atari", "Sega", "Nintendo", "Sony", "Neo", "Geo", "Lynx", "Jaguar", "Commodore", "Apple", "Mac", "Spectrum", "Sinclair", "Amstrad", "MSX", "GameCube", "Wii", "Game", "Boy", "Advance", "Famicom", "Disk", "System", "Super", "Master", "PlayStation", "Vita", "Xbox", "Arcade", "English", "French", "Spanish", "I", "Lua", "Unity", "Qt", "Kodi", "Discord", "Pages", "Actions", "Docker", "Windows", "Mac", "Ubuntu", "Debian", "Arch", "SteamOS", "Chihiro", "NAOMI", "Triforce", "Lindbergh", "Model", "PinMAME", "ScummVM", "Dinothawr", "Cemu", "Citra", "Yuzu", "Ryujinx", "Mednafen", "Beetle", "Stella", "Hatari", "Caprice", "Vice", "Fuse", "Daphne", "Hypseus", "Singe", "Supermodel", "Flycast", "Redream", "DuckStation", "SwanStation", "Opera", "Gearsystem", "Picodrive", "Snes9x", "Nestopia", "Mesen", "Gambatte", "SameBoy", "mGBA", "melonDS", "DeSmuME", "Azahar", "Eden", "Sudachi", "Torzu", "Xemu", "Cxbx", "PCSX2", "AetherSX2", "NetherSX2", "ARMSX2", "RPCS3", "Vita3K", "Zinc", "Raine", "FBNeo", "FinalBurn", "Neo", "MAME", "Clrmamepro", "RomVault"])
def _sentence_case(title: str) -> str:
words = title.split(" ")
out = []
starts = True
for w in words:
core = w.strip("()[],:.")
if starts:
# The first word of a heading or of a clause after ":", "." or " - ".
head, sep, tail = core.partition("-")
if sep and re.fullmatch(r"[A-Z][a-z]+", tail) and tail not in _HEADING_KEEP:
w = w.replace(core, f"{head}-{tail.lower()}", 1)
elif re.fullmatch(r"[A-Z][a-z]+(-[A-Z]?[a-z]+)*", core) and core not in _HEADING_KEEP:
w = w.replace(core, core.lower(), 1)
out.append(w)
starts = w.endswith((":", ".")) or w == "-" or re.fullmatch(r"\d+[a-z]?\.?", w) is not None
return " ".join(out)
+300
View File
@@ -0,0 +1,300 @@
"""The games on a card the installer tests read: the games index, the BIOS list, disc and cartridge images, a card."""
from __future__ import annotations
import tests
import gzip
import hashlib
import json
import shutil
import tempfile
import zipfile
from pathlib import Path
from tests import loopback
MD_EU = b"md europe game " * 64
MD_JP = b"md japan game " * 64
MD_ZIPPED = b"md zipped usa game " * 64
GC_HEADER = 0x458
# Every file the fixture list carries: dest -> (size, regions, cores, systems).
FILES = {
"scph5500.bin": (512, ["japan"], None, ["sony-playstation"]),
"scph5501.bin": (512, ["north-america"], None, ["sony-playstation"]),
"scph5502.bin": (512, ["europe"], None, ["sony-playstation"]),
"bios_CD_E.bin": (128, ["europe"], None, ["sega-megacd"]),
"bios_CD_U.bin": (128, ["north-america"], None, ["sega-megacd"]),
"bios_CD_J.bin": (128, ["japan"], None, ["sega-megacd"]),
"cd_extra.bin": (16, None, ["picodrive"], None),
"md_eu.bin": (64, ["europe"], None, ["sega-megadrive"]),
"md_us.bin": (64, ["north-america"], None, ["sega-megadrive"]),
"md_jp.bin": (64, ["japan"], None, ["sega-megadrive"]),
"md_tmss.bin": (32, None, None, ["sega-megadrive"]),
"dolphin/GC/USA/IPL.bin": (256, ["north-america"], ["dolphin"], None),
"dolphin/GC/EUR/IPL.bin": (256, ["europe"], ["dolphin"], None),
"dolphin/GC/JAP/IPL.bin": (256, ["japan"], ["dolphin"], None),
"neogeo.zip": (300, None, None, ["snk-neogeo"]),
"fbneo/neogeo.zip": (300, None, ["fbneo"], None),
"fbneo/pgm.zip": (200, None, ["fbneo"], None),
"fbneo/msx.zip": (150, None, ["fbneo"], None),
"fbneo/samples/big.zip": (9000, None, ["fbneo"], None),
"gba_bios.bin": (100, None, None, ["nintendo-gba"]),
}
# The fallback sets: key -> (files, optional).
SETS = {
"sony-playstation|beetle_psx": (["scph5500.bin", "scph5501.bin", "scph5502.bin"], []),
"sega-megacd|picodrive": (["bios_CD_E.bin", "bios_CD_U.bin", "bios_CD_J.bin",
"cd_extra.bin"], ["cd_extra.bin"]),
"sega-megadrive|fixcore": (["md_eu.bin", "md_us.bin", "md_jp.bin", "md_tmss.bin"],
["md_tmss.bin"]),
"nintendo-gamecube|dolphin": (["dolphin/GC/USA/IPL.bin", "dolphin/GC/EUR/IPL.bin",
"dolphin/GC/JAP/IPL.bin"], []),
"arcade|fbneo": (["fbneo/samples/big.zip"], ["fbneo/samples/big.zip"]),
"msx|fbneo": (["fbneo/msx.zip"], []),
"nintendo-gba|mgba": (["gba_bios.bin"], ["gba_bios.bin"]),
"nintendo-gba|gpsp": (["gba_bios.bin"], []),
}
REGION_READER_MCD = {
"applies_to": {"extensions": [".cue", ".bin", ".iso"], "media": "cd"},
"decode": {"kind": "integer", "otherwise": ["north-america"],
"values": [{"regions": ["europe"], "value": 100},
{"regions": ["japan"], "value": 161}]},
"location": {"encoding": "u8", "length": 1, "offset": 523, "sector": 0},
"magic": {"bytes": "SEGADISCSYSTEM", "offset": 0, "sector": 0},
}
SYSTEMS = {
"sony-playstation": {
"identify": {"sources": [{"source": "redump", "dat": "PS"}], "regions": [["europe"]],
"games": [], "serials": {"SLES-00001": [0]}},
"headers": {"readers": {"psx-serial-prefix": {
"location": {"iso_file": "SYSTEM.CNF", "key": "BOOT", "take": "basename"},
"decode": {"kind": "prefix-nocase", "values": [
{"value": "sles", "regions": ["europe"]}], "otherwise": "unknown"}}},
"cores": {"beetle_psx": {"order": ["psx-serial-prefix"],
"otherwise": ["north-america"]}}},
"region_rules": {"beetle_psx": {"keep_all_regions": [
{"case": "psx-override-bios", "condition": "option", "keeps": "region-free-files"}]}},
},
"sega-megacd": {
"identify": {"sources": [{"source": "redump", "dat": "MCD"}], "regions": [],
"games": [], "serials": {}},
"headers": {"readers": {"mcd-security-code": REGION_READER_MCD},
"cores": {"picodrive": {"order": ["mcd-security-code"],
"otherwise": ["north-america"]}}},
"region_rules": {"picodrive": {"default_region": "north-america"}},
"extras": [{"system": "sega-megacd", "profile": "picodrive",
"trigger": {"every_game": True}, "files": ["cd_extra.bin"],
"required": True}],
},
"sega-megadrive": {
"identify": {"sources": [{"source": "no-intro", "dat": "MD"}],
"regions": [["europe"], ["japan"], ["north-america"]],
"games": sorted([[loopback.crc(MD_EU), len(MD_EU), 0, "Game (Europe)"],
[loopback.crc(MD_JP), len(MD_JP), 1, "Game (Japan)"],
[loopback.crc(MD_ZIPPED), len(MD_ZIPPED), 2, "Zipped (USA)"]]),
"serials": {}},
"headers": {"readers": {"md-country": {
"location": {"offset": 0x1F0, "length": 3, "encoding": "ascii"},
"decode": {"kind": "letters", "otherwise": "unknown", "values": [
{"value": "J", "regions": ["japan"]}, {"value": "E", "regions": ["europe"]},
{"value": "U", "regions": ["north-america"]}]}}},
"cores": {"fixcore": {"order": ["md-country"], "otherwise": "unknown"}}},
"region_rules": {"fixcore": {}},
},
"nintendo-gamecube": {
"identify": {"sources": [{"source": "redump", "dat": "GC"}],
"regions": [["europe", "north-america"], ["japan"]],
"games": [], "serials": {"GALE01": [0], "GJPN01": [1]}},
"headers": {"readers": {
"gc-game-id": {"location": {"container": "gamecube-disc", "disc_offset": 0,
"encoding": "ascii", "length": 6},
"decode": {"kind": "serial"}},
"gc-region": {"location": {"container": "gamecube-disc", "disc_offset": GC_HEADER,
"encoding": "u32be", "length": 4},
"decode": {"kind": "integer", "otherwise": "unknown", "values": [
{"value": 0, "regions": ["japan"]},
{"value": 1, "regions": ["north-america"]},
{"value": 2, "regions": ["europe"]}]}}},
"cores": {"dolphin": {"order": ["gc-region"], "otherwise": "unknown"}}},
"region_rules": {"dolphin": {"keep_all_regions": [
{"case": "gamecube-unknown-region", "condition": "disc"}]}},
},
"nintendo-gba": {},
}
ARCADE = {
"bios": {"neogeo": ["mslug", "mslug2"], "pgm": ["orlegend"], "nobios": ["lost"],
"msx": ["msx_1942"]},
"devices": {}, "chd": [], "missing_parents": {},
"no_bios": ["1942", "nes_1942", "pacman"], "bios_sets": ["msx", "neogeo", "nobios", "pgm"],
}
SETUP = {
"format_version": 1, "setup": "retroarch", "name": "Fixture", "platform": "retroarch",
"sources": {}, "roms_root": {"path": "/mnt/SDCARD/Roms", "from_bios": "../Roms"},
"case_sensitive": False,
"media": [{"name": "Imgs"}],
"folders": [
{"folder": "PS", "systems": ["sony-playstation"], "basis": "id",
"profile": "beetle_psx", "extensions": [".cue", ".bin", ".chd", ".m3u", ".iso"],
"fallback": ["sony-playstation|beetle_psx"], "source_ref": "x"},
{"folder": "SEGACD", "systems": ["sega-megacd"], "basis": "id",
"profile": "picodrive", "extensions": [".cue", ".iso", ".bin", ".chd", ".m3u"],
"fallback": ["sega-megacd|picodrive"], "source_ref": "x"},
{"folder": "MD", "systems": ["sega-megadrive"], "basis": "id", "profile": "fixcore",
"extensions": [".md", ".bin", ".zip", ".7z"],
"fallback": ["sega-megadrive|fixcore"], "source_ref": "x"},
{"folder": "GC", "systems": ["nintendo-gamecube"], "basis": "id",
"profile": "dolphin", "extensions": [".iso", ".rvz"],
"fallback": ["nintendo-gamecube|dolphin"], "source_ref": "x"},
{"folder": "FBNEO", "systems": ["arcade"], "basis": "id", "profile": "fbneo",
"arcade": "fbneo", "extensions": [".zip", ".7z"], "fallback": ["arcade|fbneo"],
"source_ref": "x"},
{"folder": "MSX", "systems": ["msx"], "basis": "id", "profile": "fbneo",
"arcade": "fbneo", "extensions": [".zip"], "fallback": ["msx|fbneo"],
"source_ref": "x"},
{"folder": "GBA", "systems": ["nintendo-gba"], "basis": "id", "profile": "mgba",
"extensions": [".gba"], "fallback": ["nintendo-gba|mgba"],
"board_defaults": {"rpi": {"core": "gpsp", "profile": "gpsp",
"fallback": ["nintendo-gba|gpsp"]}},
"source_ref": "x"},
{"folder": "PORTS", "systems": [], "basis": "unresolved", "source_ref": "x"},
],
}
def _dumps(doc: object) -> bytes:
return (json.dumps(doc, sort_keys=True, separators=(",", ":")) + "\n").encode()
def write_index(folder: Path, systems: dict | None = None, arcade: dict | None = None,
setup: dict | None = None, extra_sets: dict | None = None,
more_setups: dict | None = None) -> None:
"""install/games/ as the generator lays it out, every digest right."""
rows = sorted({(dest, FILES[dest][0], "bios") for files, _o in SETS.values()
for dest in files})
position = {row[0]: i for i, row in enumerate(rows)}
sets = {**SETS, **(extra_sets or {})}
fallback = {"format_version": 1, "platform": "retroarch", "files": [list(r) for r in rows],
"sets": {key: {"files": [position[d] for d in files],
"optional": [position[d] for d in optional],
"bytes": 0, "required_bytes": 0}
for key, (files, optional) in sets.items()}}
docs = {"setups": {"retroarch": setup or SETUP, **(more_setups or {})}, "fallback": {"retroarch": fallback},
"systems": {key: {"format_version": 1, "system": key, **value}
for key, value in (systems or SYSTEMS).items()},
"arcade": {"fbneo": {"profile": "fbneo", **(arcade or ARCADE)}}}
index: dict = {"format_version": 1, "data_version": "0" * 16, "licences": [],
"folders": {"ps": ["sony-playstation"], "psx": ["sony-playstation"],
"md": ["sega-megadrive"], "megadrive": ["sega-megadrive"]}}
for kind, items in docs.items():
index[kind] = {}
for key, doc in items.items():
data = _dumps(doc)
rel = f"{kind}/{key}.json"
(folder / kind).mkdir(parents=True, exist_ok=True)
(folder / rel).write_bytes(data)
index[kind][key] = {"file": rel, "size": len(data),
"gzip_size": len(gzip.compress(data)),
"sha256": hashlib.sha256(data).hexdigest()}
(folder / "index.json").write_bytes(_dumps(index))
def manifest() -> dict:
files = []
for dest, (size, regions, cores, systems) in FILES.items():
payload = dest.encode().ljust(size, b".")[:size]
entry = {"dest": dest, "size": size, "sha1": hashlib.sha1(payload).hexdigest(),
"sha256": hashlib.sha256(payload).hexdigest(),
"repo_path": f"bios/{dest.replace('/', '_')}", "cores": cores}
if systems:
entry["systems"] = systems
if regions:
entry.update(regions=regions)
files.append(entry)
return {"manifest_version": 2, "platform": "retroarch", "files": files,
"omitted_files": []}
def mcd_iso(code: int, magic: bool = True) -> bytes:
data = bytearray(2048 * 18)
if magic:
data[0:14] = b"SEGADISCSYSTEM"
data[523] = code
return bytes(data)
def gc_iso(game_id: bytes, region: int) -> bytes:
data = bytearray(0x500)
data[0:6] = game_id
data[GC_HEADER:GC_HEADER + 4] = region.to_bytes(4, "big")
return bytes(data)
def md_rom(content: bytes, country: bytes) -> bytes:
data = bytearray(content.ljust(0x200, b"\0"))
data[0x1F0:0x1F3] = country
return bytes(data)
def ps_iso(boot: str) -> bytes:
"""A 2048-byte ISO 9660 image whose root holds SYSTEM.CNF."""
sectors = [bytearray(2048) for _ in range(20)]
volume = sectors[16]
volume[0] = 1
volume[1:6] = b"CD001"
root = bytearray(34)
root[0] = 34
root[2:6] = (17).to_bytes(4, "little")
root[10:14] = (2048).to_bytes(4, "little")
volume[156:190] = root
name = b"SYSTEM.CNF;1"
record = bytearray(33 + len(name))
record[0] = len(record)
record[2:6] = (18).to_bytes(4, "little")
text = f"BOOT = cdrom:\\{boot};1\r\n".encode()
record[10:14] = len(text).to_bytes(4, "little")
record[32] = len(name)
record[33:] = name
sectors[17][0:len(record)] = record
sectors[18][0:len(text)] = text
return b"".join(bytes(s) for s in sectors)
class Card:
"""A card in tmp/: BIOS/ and Roms/ at its root, the games index beside
a saved file list."""
def __init__(self) -> None:
self.root = Path(tempfile.mkdtemp())
self.bios = self.root / "card" / "BIOS"
self.roms = self.root / "card" / "Roms"
self.bios.mkdir(parents=True)
self.roms.mkdir()
self.lists = self.root / "lists"
(self.lists / "games").mkdir(parents=True)
self.manifest_path = self.lists / "retroarch.json"
self.manifest_path.write_text(json.dumps(manifest()))
write_index(self.lists / "games")
self.cache = self.root / "cache"
def game(self, folder: str, name: str, data: bytes = b"game") -> Path:
path = self.roms / folder / name
path.parent.mkdir(parents=True, exist_ok=True)
path.write_bytes(data)
return path
def zipped(self, folder: str, name: str, member: str, data: bytes) -> Path:
path = self.roms / folder / name
path.parent.mkdir(parents=True, exist_ok=True)
with zipfile.ZipFile(path, "w") as archive:
archive.writestr(member, data)
return path
def close(self) -> None:
shutil.rmtree(self.root, ignore_errors=True)
+255 -1
View File
@@ -1,18 +1,24 @@
"""What the installer test modules share: install.py loaded once, loopback runs and served trees."""
"""What the installer test modules share: install.py loaded once, loopback runs, served trees, the fake repositories, cards and payloads."""
from __future__ import annotations
import tests
from tests import loopback
from tests import scratch_dir
import functools
import hashlib
import http.server
import importlib.util
import io
import json
import os
import shutil
import subprocess
import sys
import tempfile
import threading
import unittest
import zipfile
from pathlib import Path
REPO_ROOT = Path(__file__).resolve().parent.parent
@@ -118,3 +124,251 @@ class _SyntheticTree:
def _events(proc: subprocess.CompletedProcess) -> list[dict]:
"""The --events stream, every stdout line a JSON object."""
return [json.loads(line) for line in proc.stdout.splitlines()]
class FakeRepository:
"""A loopback copy of the repository: one manifest and its payloads."""
PAYLOADS = {
"scph5500.bin": (b"jp bios", ["sony-playstation"], ["japan"], None),
"scph5501.bin": (b"us bios", ["sony-playstation"], ["north-america"], None),
"gba_bios.bin": (b"gba bios", ["nintendo-gba"], None, None),
"pcsx/extra.bin": (b"pcsx", ["sony-playstation"], None, ["pcsx_rearmed"]),
"mgba/extra.bin": (b"mgba", ["nintendo-gba"], None, ["mgba"]),
}
def __init__(self, selection: bool = True):
self.selection = selection
def __enter__(self) -> FakeRepository:
self.root = Path(tempfile.mkdtemp())
(self.root / "install").mkdir()
(self.root / "bios").mkdir()
files = []
for name, (payload, systems, regions, cores) in self.PAYLOADS.items():
stored = name.replace("/", "_")
(self.root / "bios" / stored).write_bytes(payload)
entry = {
"dest": name,
"sha1": hashlib.sha1(payload).hexdigest(),
"sha256": hashlib.sha256(payload).hexdigest(),
"size": len(payload),
"repo_path": f"bios/{stored}",
"cores": cores,
}
if self.selection:
entry["systems"] = systems
if regions:
entry.update(regions=regions, region_system_groups=systems)
files.append(entry)
manifest = {"manifest_version": 2, "platform": "retroarch", "files": files}
(self.root / "install" / "retroarch.json").write_text(json.dumps(manifest))
handler = functools.partial(loopback.Quiet, directory=str(self.root))
self.httpd = http.server.ThreadingHTTPServer(("127.0.0.1", 0), handler)
threading.Thread(target=self.httpd.serve_forever, daemon=True).start()
self.dest = self.root / "dest"
return self
def __exit__(self, *exc) -> None:
self.httpd.shutdown()
self.httpd.server_close()
shutil.rmtree(self.root, ignore_errors=True)
def env(self) -> dict:
env = dict(os.environ)
env["RETROBIOS_BASE_URL"] = f"http://127.0.0.1:{self.httpd.server_address[1]}"
return env
def command(self, *options: str) -> list[str]:
return [sys.executable, str(REPO_ROOT / "install.py"), "--platform",
"retroarch", "--dest", str(self.dest), *options]
def run(self, *options: str) -> subprocess.CompletedProcess:
return subprocess.run(
self.command(*options), env=self.env(), capture_output=True,
text=True, timeout=60, check=False, stdin=subprocess.DEVNULL,
)
def installed(self) -> list[str]:
if not self.dest.exists():
return []
return sorted(
p.relative_to(self.dest).as_posix()
for p in self.dest.rglob("*") if p.is_file()
)
INDEX = REPO_ROOT / "install" / "launchers" / "index.json"
def make_card(root: Path, system: str) -> Path:
"""A card as each system leaves it, and the BIOS folder on it."""
bios = _card_files(root, system)
bios.mkdir(parents=True, exist_ok=True)
return bios
def _card_files(root: Path, system: str) -> Path:
root.mkdir(parents=True, exist_ok=True)
if system == "muOS":
(root / "MUOS" / "bios").mkdir(parents=True)
return root / "MUOS" / "bios"
if system == "KNULLI":
(root / "system").mkdir()
(root / "system" / "batocera.conf").write_text("system.hostname=KNULLI\n")
return root / "bios"
if system == "ROCKNIX":
(root / ".config" / "system" / "configs").mkdir(parents=True)
(root / ".config" / "system" / "configs" / "system.cfg").write_text(
"root.password=rocknix\n")
return root / "roms" / "bios"
if system == "Onion":
(root / ".tmp_update" / "onionVersion").mkdir(parents=True)
(root / ".tmp_update" / "onionVersion" / "version.txt").write_text("4.3.1\n")
return root / "BIOS"
if system == "spruceOS":
(root / "spruce").mkdir()
return root / "BIOS"
if system == "MinUI":
(root / ".system").mkdir()
(root / ".system" / "version.txt").write_text("MinUI-20250101\n")
return root
raise ValueError(system)
class AppRepository(FakeRepository):
"""The fake repository with the launcher list and every file it names,
and the BIOS lists of the systems whose cards are tried."""
def __enter__(self) -> AppRepository:
super().__enter__()
index = json.loads(INDEX.read_text(encoding="utf-8"))
(self.root / "install" / "launchers").mkdir()
(self.root / "install" / "launchers" / "index.json").write_text(json.dumps(index))
for launcher in index["launchers"].values():
for entry in launcher.get("files", launcher.get("members", [])):
if "repo_path" in entry:
target = self.root / entry["repo_path"]
target.parent.mkdir(parents=True, exist_ok=True)
shutil.copyfile(REPO_ROOT / entry["repo_path"], target)
base = json.loads((self.root / "install" / "retroarch.json").read_text())
for plat in ("knulli", "rocknix", "minui"):
(self.root / "install" / f"{plat}.json").write_text(
json.dumps({**base, "platform": plat}))
return self
def card(self, system: str) -> tuple[Path, Path]:
root = self.root / "cards" / system
return root, make_card(root, system)
def tamper(self, repo_path: str) -> None:
"""One byte changed, the size kept: only the hash tells."""
path = self.root / repo_path
data = bytearray(path.read_bytes())
data[-1] ^= 0x20
path.write_bytes(bytes(data))
def cli(self, *options: str, env: dict | None = None) -> subprocess.CompletedProcess:
return subprocess.run(
[sys.executable, str(REPO_ROOT / "install.py"), *options],
env={**self.env(), **(env or {})}, capture_output=True, text=True,
timeout=120, check=False, stdin=subprocess.DEVNULL)
US = b"us bios " * 64
JP = b"jp bios " * 64
EU = b"eu bios " * 64
GBA = b"gba bios" * 32
EXTRA = b"pcsx extra"
def _sha1(data: bytes) -> str:
return hashlib.sha1(data).hexdigest()
def _entry(dest: str, data: bytes, systems: list[str], **fields) -> dict:
return {
"dest": dest, "sha1": _sha1(data), "size": len(data),
"repo_path": f"bios/{dest.replace('/', '_')}", "cores": None,
"systems": systems, **fields,
}
def manifest() -> dict:
"""A small RetroArch list: two regions of one BIOS, a core file with a
second revision, a file in a subfolder."""
return {
"manifest_version": 2,
"platform": "retroarch",
"files": [
_entry("scph5501.bin", US, ["sony-playstation"], regions=["north-america"]),
_entry("scph5500.bin", JP, ["sony-playstation"], regions=["japan"]),
_entry("gba_bios.bin", GBA, ["nintendo-gba"]),
_entry("pcsx/extra.bin", EXTRA, ["sony-playstation"], cores=["pcsx_rearmed"],
alternatives=[{"sha1": _sha1(EU), "size": len(EU),
"repo_path": "bios/eu", "cores": ["beetle_psx"]},
{"sha1": _sha1(EXTRA), "size": len(EXTRA),
"repo_path": "bios/x", "cores": ["pcsx_rearmed"]}]),
],
"system_cores": {"sony-playstation": ["beetle_psx", "pcsx_rearmed"],
"nintendo-gba": ["mgba"]},
}
PAYLOAD = {"scph5501.bin": US, "scph5500.bin": JP, "gba_bios.bin": GBA,
"pcsx/extra.bin": EXTRA}
def _offline_env() -> dict:
"""An environment where any request the installer makes is refused."""
env = dict(os.environ)
env["RETROBIOS_BASE_URL"] = f"http://127.0.0.1:{loopback.closed_port()}"
env["HTTPS_PROXY"] = env["HTTP_PROXY"] = f"http://127.0.0.1:{loopback.closed_port()}"
return env
class Scratch(unittest.TestCase):
def setUp(self):
self.root = Path(tempfile.mkdtemp())
self.addCleanup(shutil.rmtree, self.root, True)
self.dest = self.root / "system"
self.list = self.root / "retroarch.json"
self.list.write_text(json.dumps(manifest()))
def run_installer(self, *options: str) -> subprocess.CompletedProcess:
return subprocess.run(
[sys.executable, str(REPO_ROOT / "install.py"), "--platform", "retroarch",
"--dest", str(self.dest), *options],
env=_offline_env(), capture_output=True, text=True, timeout=120,
check=False, stdin=subprocess.DEVNULL,
)
def place(self, relative: str, data: bytes) -> Path:
path = self.dest / relative
path.parent.mkdir(parents=True, exist_ok=True)
path.write_bytes(data)
return path
def check(self) -> str:
proc = self.run_installer("--check", "--manifest", str(self.list), "--verbose")
self.assertEqual(proc.returncode, 3, proc.stdout + proc.stderr)
return proc.stdout
def complete(self, *skip: str) -> None:
for name, data in PAYLOAD.items():
if name not in skip:
self.place(name, data)
def _pack(directory: Path, name: str, members: dict[str, bytes]) -> Path:
"""A pack as generate_pack writes one: the files and a manifest.json."""
listed = [{"path": path, "sha1": _sha1(data), "md5": hashlib.md5(data).hexdigest(),
"size": len(data), "status": "verified", "name": path.rsplit("/", 1)[-1]}
for path, data in members.items()]
path = directory / name
with zipfile.ZipFile(path, "w", zipfile.ZIP_DEFLATED) as archive:
for member, data in members.items():
archive.writestr(member, data)
archive.writestr("README.txt", b"read me\n")
archive.writestr("manifest.json", json.dumps({"files": listed}))
return path
+1 -1
View File
@@ -29,7 +29,7 @@ from scraper.recalbox_configgen import (
Configgen,
)
from tests.test_launchers import placed
from tests.launcherssupport import placed
# recalboxFiles.py:1-12, 173-174
-22
View File
@@ -1,22 +0,0 @@
"""Fixture readers shared by the RetroBat launcher test modules."""
from __future__ import annotations
import tests
import textwrap
from pathlib import Path
from scraper.retrobat_generators import GENERATORS
from scraper.csharp_source import Source
REPO_ROOT = Path(__file__).resolve().parent.parent
G = GENERATORS
def _sources(**texts: str) -> dict[str, Source]:
return {
path: Source(path, textwrap.dedent(text).lstrip("\n")) for path, text in texts.items()
}
+26
View File
@@ -0,0 +1,26 @@
"""Source texts the launcher test modules build: blocks placed at their lines, C# files by path."""
from __future__ import annotations
import tests
import textwrap
from scraper.csharp_source import Source
def placed(blocks: dict[int, str]) -> str:
"""Each block starting at its line, blank lines between."""
lines: list[str] = []
for start, block in sorted(blocks.items()):
if len(lines) >= start:
raise AssertionError(f"block at line {start} overlaps the previous one")
lines += [""] * (start - 1 - len(lines))
lines += block.splitlines()
return "\n".join(lines) + "\n"
def _sources(**texts: str) -> dict[str, Source]:
return {
path: Source(path, textwrap.dedent(text).lstrip("\n")) for path, text in texts.items()
}
+260
View File
@@ -0,0 +1,260 @@
"""The reader the copy budgets measure a generated page with."""
from __future__ import annotations
import tests
import re
from dataclasses import dataclass, field
from pathlib import Path
from tests import sitepages
# Level 0: the Start here pages, with their own ceiling on words.
START_PAGES = {
"index.md": 220,
"which-pack.md": 400,
"wiki/what-are-bios-files.md": 300,
"wiki/first-install.md": 400,
"wiki/troubleshooting.md": 300,
"wiki/faq.md": 450,
"wiki/glossary.md": 200,
}
WORD = re.compile(r"[A-Za-z0-9][A-Za-z0-9'._/\\:%~-]*")
SENTENCE_END = re.compile(r"(?<=[.!?])\s+(?=[A-Z`\"(*\[])")
@dataclass
class Block:
kind: str # paragraph, item, term, definition, heading, table
text: str
collapsed: bool = False
defines: str = ""
hidden: bool = False # in a tab other than the first: read instead of the first
@dataclass
class Page:
blocks: list[Block] = field(default_factory=list)
before_action: int | None = None
list_runs: list[int] = field(default_factory=list)
def prose(self) -> list[Block]:
return [b for b in self.blocks if b.kind in ("paragraph", "item", "term", "definition")]
def words(self) -> int:
return sum(count_words(b.text) for b in self.blocks if b.kind != "table" and not b.hidden)
def sentences(self) -> list[str]:
return [s for b in self.prose() for s in split_sentences(b.text)]
def strip_inline(text: str) -> str:
"""Link text kept, targets, attribute lists, images and markup dropped."""
text = re.sub(r"!\[[^\]]*\]\([^)]*\)(\{[^}]*\})?", "", text)
text = re.sub(r"\[([^\]]*)\]\([^)]*\)", r"\1", text)
text = re.sub(r"\{\s*[#.:][^}]*\}", "", text)
text = re.sub(r"<[^>]+>", "", text)
return text.replace("**", "").strip()
def count_words(text: str) -> int:
return len(WORD.findall(re.sub(r"`[^`]*`", "code", text)))
def split_sentences(text: str) -> list[str]:
return [s for s in SENTENCE_END.split(text.strip()) if WORD.search(s)]
def guide_part(markdown: str) -> str:
"""A page up to its Reference heading, without front matter."""
if markdown.startswith("---\n"):
markdown = markdown.split("\n---\n", 1)[1]
match = re.search(r"^## Reference\b", markdown, re.M)
return markdown[: match.start()] if match else markdown
class _PageParser:
"""The state parse() carries from one line to the next."""
def __init__(self) -> None:
self.page = Page()
self.seen_words = 0
self.details = 0 # depth of collapsed blocks
self.tab = 0 # the tab of a group being read, 0 outside a group
self.fence: str | None = None
self.current: list[str] = []
self.kind = "paragraph"
self.run = 0
def flush(self) -> None:
page = self.page
if self.current:
body = strip_inline(" ".join(self.current))
if WORD.search(body):
kind = self.kind
term = page.blocks[-1].text.lower() if kind == "definition" and page.blocks else ""
block = Block(kind, body, self.details > 0, term, self.tab > 1)
page.blocks.append(block)
if (page.before_action is None and not block.collapsed
and not block.hidden and kind not in ("table", "heading")):
self.seen_words += count_words(body)
self.current = []
if self.kind in ("item", "definition", "heading"):
self.kind = "paragraph"
def act(self) -> None:
self.flush()
if self.page.before_action is None:
self.page.before_action = self.seen_words
def end_run(self) -> None:
if self.run:
self.page.list_runs.append(self.run)
self.run = 0
def feed(self, raw: str) -> None:
line = raw.rstrip()
stripped = line.strip()
indent = len(line) - len(line.lstrip())
if self.fence:
if stripped.startswith(self.fence):
self.fence = None
return
if self._markup(stripped):
return
if stripped.startswith("#"):
self._heading(stripped)
return
if stripped.startswith("|"):
self._table_row(stripped)
return
self._prose(stripped, indent)
def _markup(self, stripped: str) -> bool:
"""Fences, blank lines and HTML: True when the line is consumed."""
if stripped.startswith(("```", "~~~")):
self.fence = stripped[:3]
if self.tab < 2:
self.act()
return True
if not stripped:
self.flush()
return True
if stripped.startswith("import ") and stripped.endswith(";"):
return True
if stripped.startswith(":::"):
self.flush()
return True
if self._container(stripped):
return True
if "rb-button" in stripped or "rb-tile" in stripped or stripped.startswith(
("<FilePicker", "<WantedFiles")):
self.act()
return True
if re.match(r"</?(?!abbr\b|a\b|code\b|strong\b|em\b)[A-Za-z]", stripped):
self.flush()
return True
return False
def _container(self, stripped: str) -> bool:
"""Collapsed blocks and tab groups: True when the line is consumed."""
if stripped.startswith("<details"):
self.flush()
self.details += 1
return True
if stripped.startswith("</details>"):
self.flush()
self.details = max(0, self.details - 1)
return True
if stripped.startswith("<Tabs"):
self.flush()
self.tab = 0
return True
if stripped.startswith("<TabItem"):
self.flush()
self.tab += 1
return True
if stripped.startswith("</Tabs>"):
self.flush()
self.tab = 0
return True
return False
def _heading(self, stripped: str) -> None:
self.flush()
self.end_run()
self.kind = "heading"
self.current = [re.sub(r"\s*\{[^}]*\}\s*$", "", stripped.lstrip("#").strip())]
self.flush()
self.kind = "paragraph"
def _table_row(self, stripped: str) -> None:
if self.kind != "table":
self.flush()
self.kind = "table"
if not re.fullmatch(r"\|[\s:|-]+\|?", stripped):
self.current.append(stripped.replace("|", " "))
def _prose(self, stripped: str, indent: int) -> None:
if self.kind == "table":
self.flush()
self.kind = "paragraph"
item = re.match(r"(?:[-*+]|\d+\.)\s+(.*)", stripped)
definition = re.match(r":\s+(.*)", stripped)
if item:
self.flush()
self.kind = "item"
self.run += 1
self.current = [item.group(1)]
return
if definition:
self.flush()
page = self.page
if page.blocks and page.blocks[-1].kind == "paragraph":
page.blocks[-1].kind = "term"
self.kind = "definition"
self.current = [definition.group(1)]
return
if self.kind == "item" and indent == 0:
self.flush()
self.kind = "paragraph"
if self.kind == "paragraph":
self.end_run()
if not self.current and self.kind in ("item", "definition") and indent == 0:
self.kind = "paragraph"
self.current.append(stripped)
def finish(self) -> Page:
self.flush()
if self.run:
self.page.list_runs.append(self.run)
return self.page
def parse(markdown: str) -> Page:
"""Blocks of prose a reader sees, code and HTML left out.
A collapsed block (<details>) counts, but not before the first action:
the reader opens it on purpose. Of a group of tabs the first is read and
the others only stand in for it.
"""
text = guide_part(markdown)
text = re.sub(r"<script.*?</script>", "", text, flags=re.S)
text = re.sub(r"<!--.*?-->", "", text, flags=re.S)
parser = _PageParser()
for raw in text.splitlines():
parser.feed(raw)
return parser.finish()
def _docs() -> Path:
return sitepages.require()
def _load(name: str) -> Page:
_docs()
return parse(sitepages.page(name).read_text(encoding="utf-8"))
+168 -1
View File
@@ -3,16 +3,39 @@
generate_site.py writes each page into the Starlight project's content
collection, as .md or as .mdx when it uses a component. A test names a
page by its docs path (``which-pack.md``) and gets whichever file holds it.
The built site, the public data, the navigation the generator writes and the
pronoun scanner are read here too.
"""
from __future__ import annotations
import tests
import html
import os
import re
import unittest
from pathlib import Path
REPO_ROOT = Path(__file__).resolve().parents[1]
from core import anchors as core_anchors
from model.platforms import load_platform_config
from model.registry import list_registered_platforms, load_platform_registry
from sitegen import emulatorsindex, nav as sitegen_nav, starlight as sitestarlight
from sitegen.guidedata import device_groups
REPO_ROOT = tests.REPO_ROOT
CONTENT = REPO_ROOT / "website" / "src" / "content" / "docs"
DIST = REPO_ROOT / "website" / "dist"
PUBLIC = REPO_ROOT / "website" / "public"
API = PUBLIC / "api" / "v1"
SITE = "https://abdess.github.io/retrobios/"
def built(path: Path) -> Path:
"""path, or a skip when the build that writes it has not run."""
if not path.exists():
raise unittest.SkipTest(f"{path.relative_to(REPO_ROOT)} not generated")
return path
def require() -> Path:
@@ -58,3 +81,147 @@ def generator_sources() -> list[Path]:
return sorted({*scripts.glob("site*.py"), scripts / "generate_site.py",
*(scripts / "sitegen").glob("*.py"), scripts / "model" / "guides.py",
scripts / "model" / "systemnames.py", scripts / "packs" / "readme.py"})
def _nav() -> list:
platforms = REPO_ROOT / "platforms"
registry = load_platform_registry(str(platforms))
coverages = {
key: {"platform": load_platform_config(key, str(platforms))["platform"]}
for key in list_registered_platforms(str(platforms))
}
manufacturers = {"Sony": {}, "Sega": {}, "ScummVM": {}}
profiles = {
"duckstation": {"emulator": "DuckStation", "systems": ["sony-playstation"]},
"dolphin": {"emulator": "Dolphin", "systems": ["nintendo-gamecube"]},
"mame": {"emulator": "MAME", "systems": ["arcade"]},
}
return sitegen_nav.generate_nav(coverages, manufacturers, profiles, registry)
def _targets(value: object) -> set[str]:
if isinstance(value, str):
return {value}
if isinstance(value, list):
return set().union(*(_targets(v) for v in value)) if value else set()
return set().union(*(_targets(v) for v in value.values()))
def _present(nav: list) -> set[str]:
return {t for t in _targets(nav) if not t.startswith("http")}
def _index_anchors(markdown: str) -> set[str]:
"""The heading ids a generated page carries once written."""
_title, title_id, body = sitestarlight.split_title(markdown)
return sitestarlight.heading_ids(sitestarlight.pin_heading_ids(body, title_id))
ANCHORS = {
"platforms/index.md": {core_anchors.toc_slug(label) for label, _ in device_groups().values()},
"systems/index.md": {"consoles-and-computers"},
"emulators/index.md": _index_anchors(emulatorsindex.generate_emulators_index({
"duckstation": {"emulator": "DuckStation", "systems": ["sony-playstation"]},
"dolphin": {"emulator": "Dolphin", "systems": ["nintendo-gamecube"]},
"mame": {"emulator": "MAME", "systems": ["arcade"]},
})),
}
PRONOUN = re.compile(
r"(?<![\w-])((?-i:I)|me|my|mine|myself|we|us|our|ours|ourselves"
r"|you|your|yours|yourself|yourselves)(?![\w-])",
re.I,
)
FENCED = re.compile(r"^[ \t]*(```|~~~).*?^[ \t]*\1[^\n]*$", re.S | re.M)
INLINE_CODE = re.compile(r"(`+)(?:(?!\n\n)[^`])*?\1")
HTML_COMMENT = re.compile(r"<!--.*?-->", re.S)
SCRIPT_STYLE = re.compile(r"<(script|style|pre|code)\b.*?</\1>", re.S | re.I)
TAG = re.compile(r"</?[A-Za-z][^<>]*>")
ENTITY = re.compile(r"&#(?:\d+|x[0-9a-fA-F]+);")
URL = re.compile(r"(?:https?|ftp|smb)://\S+|\bwww\.\S+")
LINK_TARGET = re.compile(r"\]\([^)\s]*(?:\s+\"[^\"]*\")?\)|^\[[^\]]+\]:\s*\S+.*$", re.M)
ANCHOR = re.compile(r"\{[^{}\n]*#[^{}\n]*\}")
PATHLIKE = re.compile(r"\S*[/\\]\S*")
# File names, domains and dotted initials: baserom.us.z64, delete.me, A.I.R.
DOTTED = re.compile(r"[\w-]+(?:\.[\w-]+)+\.?")
# A list of single letters or digits (D, F, I, P), or of lowercase option
# values in parentheses (euro, us, asia), names keys, not people.
LETTERS = re.compile(r"(?<!\w)[A-Z0-9](?:,\s?[A-Z0-9#@^](?!\w))+")
VALUES = re.compile(r"\((?:[a-z][\w-]*, )+[a-z][\w-]*\)")
LETTER_HEADING = re.compile(r"^#+ [A-Z]\s*$", re.M)
# Search keywords, written the way readers type a query. Pagefind matches
# them, the page never shows them.
TERMS = re.compile(r"^terms: .*$", re.M)
# A capitalised "US" names the country and its region code.
COUNTRY = re.compile(r"(?<![\w-])US(?![\w-])")
# Proper names that hold one of the words.
NAMES: dict[str, str] = {
r"I(?:'|''|&#x27;|&#39;)Max": "I'Max MACS, an arcade board maker",
r"My (?:Old)?Boy!": "My Boy! and My OldBoy!, Android emulators",
r"My Vision": "Nichibutsu My Vision, a console",
r"On My iPhone": "the Files app location on iOS",
r"Us vs Them": "a game title",
r"Aliens Ate My Railway|Fell Apart On Me": "OpenTTD music track titles",
r"\b(?:Model|Level|Series|Mk|MK|Ultima|Interface|Type) I\b(?!')":
"a roman numeral in a machine or game name (Model I, Ultima I)",
r"\bI(?= \([A-Z])": "a model letter, I (Palladium)",
r"Java ME": "Java ME, the mobile Java platform",
r"\bME(?=,? (?:and )?MA\b)": "FM Towns ME, a model name beside the MA (geartowns)",
r"laseractive us(?=:)": "the LaserActive region key of geargrafx's BIOS list",
}
# Program output quoted word for word. INSTALLER holds install.py's own
# messages, empty since the installer speaks without pronouns. SOURCE holds what an emulator prints, quoted in its
# profile from the emulator's code, which this project does not write.
INSTALLER: dict[str, str] = {}
SOURCE: dict[str, str] = {
"You do not have a ROM image installed for Model": "sdltrs message, emulators/sdl2trs.yml",
"You might not get sound because": "lindbergh-loader message, emulators/lindbergh-loader.yml",
'"Your Card"': "KEGS disk name, emulators/kegs.yml",
"How do I use SC3000": "MG.html question title, emulators/mastergear.yml",
"How do I use SF7000 disk images?": "MG.html question title, emulators/mastergear.yml",
"There is no version of MG for my Unix!": "MG.html question title, emulators/mastergear.yml",
"rename your own SFX dat file to this name": "Zelda Classic README, emulators/zc210.yml",
"Could not load ROM images! You must supply these.":
"hypseus message, emulators/hypseus-singe.yml",
"Please copy pak0.pk3 from the 'etmain' path of your":
"ET: Legacy message, emulators/etlegacy.yml",
'"keyconf.dat(us)"': "file name px68k ships, emulators/px68k-sdl.yml",
}
_SPACED = [
re.compile(r"\s+".join(map(re.escape, phrase.split())))
for phrase in (*INSTALLER, *SOURCE)
]
_NAMES = [re.compile(pattern) for pattern in NAMES]
def _blank(match: re.Match[str]) -> str:
return re.sub(r"[^\n]", " ", match[0])
def prose(text: str) -> str:
"""The text of a page with everything that is not prose blanked."""
for pattern in (HTML_COMMENT, SCRIPT_STYLE, TAG):
text = pattern.sub(_blank, text)
# &#95; and &#x27; spell a file name or a name: read them as characters.
text = ENTITY.sub(lambda m: html.unescape(m[0]), text)
for pattern in (
*_SPACED, FENCED, INLINE_CODE, LINK_TARGET, URL, ANCHOR, PATHLIKE,
TERMS, *_NAMES, DOTTED, LETTERS, VALUES, LETTER_HEADING, COUNTRY,
):
text = pattern.sub(_blank, text)
return text
def pronouns(text: str) -> list[tuple[int, str]]:
"""(line number, line) for each prose line holding a personal pronoun."""
lines = text.splitlines()
return [
(number, lines[number - 1].strip())
for number, line in enumerate(prose(text).splitlines(), 1)
if PRONOUN.search(line)
]
-27
View File
@@ -1,27 +0,0 @@
"""Paths and readers shared by the reference page test modules."""
from __future__ import annotations
import tests
import unittest
from pathlib import Path
REPO_ROOT = Path(__file__).resolve().parents[1]
DIST = REPO_ROOT / "website" / "dist"
PUBLIC = REPO_ROOT / "website" / "public"
API = PUBLIC / "api" / "v1"
SITE = "https://abdess.github.io/retrobios/"
def _built(path: Path) -> Path:
if not path.exists():
raise unittest.SkipTest(f"{path.relative_to(REPO_ROOT)} not generated")
return path
+39 -39
View File
@@ -18,7 +18,7 @@ from pathlib import Path
from unittest import mock
from scripts import pipeline
from orchestrate import checks, consistency, results, runner
from tests.auditsupport import ROOT
from tests import REPO_ROOT
class VerboseAppliesToJson(unittest.TestCase):
@@ -32,7 +32,7 @@ class VerboseAppliesToJson(unittest.TestCase):
completed = subprocess.run(
[sys.executable, "scripts/verify.py", *args, "--json"],
capture_output=True, text=True, cwd=ROOT, timeout=900, check=False,
capture_output=True, text=True, cwd=REPO_ROOT, timeout=900, check=False,
)
self.assertEqual(completed.returncode, 0, completed.stderr[-2000:])
return json.loads(completed.stdout)
@@ -70,7 +70,7 @@ class OnePlatformPerFlag(unittest.TestCase):
completed = subprocess.run(
[sys.executable, f"scripts/{script}", "--platform",
"bizhawk,misterfpga", *extra],
capture_output=True, text=True, cwd=ROOT, timeout=600, check=False,
capture_output=True, text=True, cwd=REPO_ROOT, timeout=600, check=False,
)
self.assertNotEqual(completed.returncode, 0)
self.assertIn("takes one platform", completed.stderr)
@@ -80,7 +80,7 @@ class OnePlatformPerFlag(unittest.TestCase):
from model.cliargs import require_platform
with self.assertRaises(SystemExit) as caught:
require_platform("batocra", str(ROOT / "platforms"))
require_platform("batocra", str(REPO_ROOT / "platforms"))
self.assertIn("batocera", str(caught.exception))
def test_a_file_that_is_no_platform_is_refused(self):
@@ -90,7 +90,7 @@ class OnePlatformPerFlag(unittest.TestCase):
for name in ("_shared", "_registry", "emulatorjs"):
with self.subTest(name=name), self.assertRaises(SystemExit) as caught:
require_platform(name, str(ROOT / "platforms"))
require_platform(name, str(REPO_ROOT / "platforms"))
self.assertIn("unknown platform", str(caught.exception))
@@ -330,7 +330,7 @@ class ACheckThatCannotAnswerDoesNotPass(unittest.TestCase):
named = subprocess.run(
[sys.executable, "scripts/generate_pack.py", "--platform",
"retroarch", "--verify-packs", "--output-dir", directory],
capture_output=True, text=True, cwd=str(ROOT), timeout=300,
capture_output=True, text=True, cwd=str(REPO_ROOT), timeout=300,
check=False,
)
self.assertNotEqual(
@@ -343,7 +343,7 @@ class ACheckThatCannotAnswerDoesNotPass(unittest.TestCase):
swept = subprocess.run(
[sys.executable, "scripts/generate_pack.py", "--all",
"--verify-packs", "--output-dir", directory],
capture_output=True, text=True, cwd=str(ROOT), timeout=300,
capture_output=True, text=True, cwd=str(REPO_ROOT), timeout=300,
check=False,
)
self.assertIn("SKIP (no pack in", swept.stdout)
@@ -374,7 +374,7 @@ class ACheckThatCannotAnswerDoesNotPass(unittest.TestCase):
import check_buildbot_system as cbs
from scraper import buildbot_system
registry = str(ROOT / "platforms" / "_data_dirs.yml")
registry = str(REPO_ROOT / "platforms" / "_data_dirs.yml")
tracked = buildbot_system.load_tracked_entries(registry)
self.assertTrue(tracked)
cases = {
@@ -400,7 +400,7 @@ class ACheckThatCannotAnswerDoesNotPass(unittest.TestCase):
from model.profiles import load_emulator_profiles
with self.assertRaisesRegex(InputMissing, "no emulator profile directory"):
load_emulator_profiles(str(ROOT / "no-such-emulator-dir"))
load_emulator_profiles(str(REPO_ROOT / "no-such-emulator-dir"))
class PipelineStepsSpeakAsTheyGo(unittest.TestCase):
@@ -463,7 +463,7 @@ class VerifyStrictAppliesInEveryMode(unittest.TestCase):
@classmethod
def setUpClass(cls):
if not (ROOT / "database.json").exists():
if not (REPO_ROOT / "database.json").exists():
raise unittest.SkipTest("database.json is not built")
cls.dir = Path(tempfile.mkdtemp())
(cls.dir / "fakeemu.yml").write_text(
@@ -478,7 +478,7 @@ class VerifyStrictAppliesInEveryMode(unittest.TestCase):
def run_verify(self, *flags: str) -> int:
return subprocess.run(
[sys.executable, "scripts/verify.py", *flags], cwd=ROOT,
[sys.executable, "scripts/verify.py", *flags], cwd=REPO_ROOT,
capture_output=True, text=True,
check=False,
).returncode
@@ -562,7 +562,7 @@ class EveryToolRefusesAFlagItWouldDrop(unittest.TestCase):
for argv in cases:
with self.subTest(script=script, argv=argv):
proc = subprocess.run(
[sys.executable, script, *argv], cwd=ROOT,
[sys.executable, script, *argv], cwd=REPO_ROOT,
capture_output=True, text=True, timeout=120,
check=False,
)
@@ -575,7 +575,7 @@ class AReaderThatLeavesEarlyIsNoCrash(unittest.TestCase):
def test_a_closed_pipe_ends_quietly(self):
proc = subprocess.Popen(
[sys.executable, "scripts/verify.py", "--list-emulators"], cwd=ROOT,
[sys.executable, "scripts/verify.py", "--list-emulators"], cwd=REPO_ROOT,
stdout=subprocess.PIPE, stderr=subprocess.PIPE,
)
# The listing fits a 64 KiB pipe: a child that wrote it all before
@@ -595,7 +595,7 @@ class AReaderThatLeavesEarlyIsNoCrash(unittest.TestCase):
def test_every_entry_point_goes_through_run_cli(self):
plain = re.compile(r'if __name__ == "__main__":\n (main\(\)|sys\.exit\(main\(\)\))')
found = [p.name for p in sorted((ROOT / "scripts").glob("*.py"))
found = [p.name for p in sorted((REPO_ROOT / "scripts").glob("*.py"))
if plain.search(p.read_text())]
self.assertEqual(found, [])
@@ -638,7 +638,7 @@ class TargetListsReadThePinnedRelease(unittest.TestCase):
def test_no_target_scraper_asks_for_the_latest_tag(self):
for name in ("batocera", "rocknix", "recalbox"):
source = (ROOT / "scripts" / "scraper" / "targets" / f"{name}_targets_scraper.py").read_text()
source = (REPO_ROOT / "scripts" / "scraper" / "targets" / f"{name}_targets_scraper.py").read_text()
with self.subTest(scraper=name):
# The Batocera scraper reads the pin of the platform it is
# instantiated for (KNULLI subclasses it).
@@ -649,7 +649,7 @@ class TargetListsReadThePinnedRelease(unittest.TestCase):
self.assertNotIn("fetch_stable_tag()", source)
self.assertNotIn("fetch_github_latest_version(", source)
# Lakka inherits its BIOS list and pins the release in its own version:.
source = (ROOT / "scripts" / "scraper" / "targets" / "lakka_targets_scraper.py").read_text()
source = (REPO_ROOT / "scripts" / "scraper" / "targets" / "lakka_targets_scraper.py").read_text()
self.assertIn("self.pinned_version(PLATFORM_NAME)", source)
self.assertNotIn("fetch_github_latest_version(", source)
@@ -717,7 +717,7 @@ class OneOutputFormPerRun(unittest.TestCase):
with self.subTest(script=script, argv=argv):
proc = subprocess.run(
[sys.executable, f"scripts/{script}", *argv], capture_output=True,
text=True, cwd=str(ROOT), timeout=120, check=False,
text=True, cwd=str(REPO_ROOT), timeout=120, check=False,
)
self.assertEqual(proc.returncode, 2, proc.stdout[-300:])
self.assertIn("not allowed with", proc.stderr)
@@ -731,7 +731,7 @@ class ATargetIsNamedWhenItRemovesTheCore(unittest.TestCase):
result = subprocess.run(
[sys.executable, "scripts/cross_reference.py", "--platform", "batocera",
"--target", "bcm2711", "--emulator", "dolphin"],
cwd=ROOT, capture_output=True, text=True, timeout=600,
cwd=REPO_ROOT, capture_output=True, text=True, timeout=600,
check=False,
)
self.assertEqual(result.returncode, 1)
@@ -748,7 +748,7 @@ class ANamedPackThatIsAbsentFails(unittest.TestCase):
result = subprocess.run(
[sys.executable, "scripts/generate_pack.py", "--platform", "retroarch",
"--verify-packs", "--output-dir", directory],
cwd=ROOT, capture_output=True, text=True, timeout=600,
cwd=REPO_ROOT, capture_output=True, text=True, timeout=600,
check=False,
)
self.assertEqual(result.returncode, 1)
@@ -762,7 +762,7 @@ class ANamedPackThatIsAbsentFails(unittest.TestCase):
result = subprocess.run(
[sys.executable, "scripts/generate_pack.py", "--all",
"--verify-packs", "--output-dir", directory],
cwd=ROOT, capture_output=True, text=True, timeout=600,
cwd=REPO_ROOT, capture_output=True, text=True, timeout=600,
check=False,
)
self.assertEqual(result.returncode, 1)
@@ -804,7 +804,7 @@ class AnAliasSelectsItsProfile(unittest.TestCase):
def test_verify_runs_the_alias(self):
result = subprocess.run(
[sys.executable, "scripts/verify.py", "--emulator", "mednafen_psx"],
cwd=ROOT, capture_output=True, text=True, timeout=300, check=False,
cwd=REPO_ROOT, capture_output=True, text=True, timeout=300, check=False,
)
self.assertEqual(result.returncode, 0, result.stderr)
self.assertIn("beetle_psx", result.stdout)
@@ -935,7 +935,7 @@ class VerifyPacksRefusesWhatItCannotDo(unittest.TestCase):
with self.subTest(args=extra), tempfile.TemporaryDirectory() as out:
result = subprocess.run(
[sys.executable, "scripts/generate_pack.py", *extra, "--output-dir", out],
cwd=ROOT, capture_output=True, text=True, timeout=300,
cwd=REPO_ROOT, capture_output=True, text=True, timeout=300,
check=False,
)
self.assertEqual(result.returncode, 2, result.stderr[-300:])
@@ -1013,11 +1013,11 @@ class AnUnknownTargetIsRefusedUnderAll(unittest.TestCase):
from scripts.model.targets import build_target_cores_cache
from scripts.model.registry import list_registered_platforms
platforms = list_registered_platforms(str(ROOT / "platforms"))
platforms = list_registered_platforms(str(REPO_ROOT / "platforms"))
with self.assertRaises(ValueError):
build_target_cores_cache(platforms, "swtich", str(ROOT / "platforms"), is_all=True)
build_target_cores_cache(platforms, "swtich", str(REPO_ROOT / "platforms"), is_all=True)
_cache, kept, _notes = build_target_cores_cache(
platforms, "switch", str(ROOT / "platforms"), is_all=True
platforms, "switch", str(REPO_ROOT / "platforms"), is_all=True
)
self.assertNotIn("bizhawk", kept)
self.assertIn("retroarch", kept)
@@ -1112,7 +1112,7 @@ class ThePipelineRunsTheSchemaCheckCIRuns(unittest.TestCase):
unquoted numeric core name passed it and failed CI on push."""
def test_the_ci_command_is_a_pipeline_step(self):
workflow = (ROOT / ".github" / "workflows" / "validate.yml").read_text(encoding="utf-8")
workflow = (REPO_ROOT / ".github" / "workflows" / "validate.yml").read_text(encoding="utf-8")
command = re.search(r"python (scripts/validate_schemas\.py[^\n]*)", workflow).group(1)
script, *flags = command.split()
source = script_source("pipeline.py")
@@ -1123,7 +1123,7 @@ class ThePipelineRunsTheSchemaCheckCIRuns(unittest.TestCase):
def test_the_site_is_rendered_as_the_deploy_renders_it(self):
"""The pipeline generated pages without rendering them: 20 pages with
duplicate ids passed it and failed the deploy."""
workflow = (ROOT / ".github" / "workflows" / "deploy-site.yml").read_text(encoding="utf-8")
workflow = (REPO_ROOT / ".github" / "workflows" / "deploy-site.yml").read_text(encoding="utf-8")
source = script_source("pipeline.py")
self.assertIn("npm run build --prefix website", workflow)
self.assertIn('["npm", "run", "build", "--prefix", "website"]', source)
@@ -1136,7 +1136,7 @@ class TheReleaseBuildsEveryServedPackInOneRun(unittest.TestCase):
the consistency check between verify and the pack never covered it."""
def test_the_pipeline_step_covers_every_platform(self):
page = (ROOT / "wiki" / "release-process.md").read_text(encoding="utf-8")
page = (REPO_ROOT / "wiki" / "release-process.md").read_text(encoding="utf-8")
self.assertIn("python scripts/pipeline.py\n", page)
self.assertNotIn("generate_pack.py --platform retropie", page)
@@ -1152,8 +1152,8 @@ class PlatformSystemTypoGetsTheClosestNames(unittest.TestCase):
with tempfile.TemporaryDirectory() as tmp, \
contextlib.redirect_stdout(out):
result = platformpack.generate_pack(
"retroarch", str(ROOT / "platforms"), {"files": {}, "indexes": {}},
str(ROOT / "bios"), tmp, emulators_dir=str(ROOT / "emulators"),
"retroarch", str(REPO_ROOT / "platforms"), {"files": {}, "indexes": {}},
str(REPO_ROOT / "bios"), tmp, emulators_dir=str(REPO_ROOT / "emulators"),
system_filter=["sony-playstaton"], offline=True,
)
self.assertIsNone(result)
@@ -1194,7 +1194,7 @@ class HashInputNamesWhatItAccepts(unittest.TestCase):
def test_a_sha256_finds_its_file(self):
from scripts.resolve.packfiles import sha1_for_hash
db = json.loads((ROOT / "database.json").read_text(encoding="utf-8"))
db = json.loads((REPO_ROOT / "database.json").read_text(encoding="utf-8"))
sha1, entry = next(
(k, e) for k, e in db["files"].items() if e.get("sha256")
)
@@ -1251,9 +1251,9 @@ class PipelineOutputDirIsTheOneItWrites(unittest.TestCase):
def test_the_default_is_the_root_dist_wherever_the_run_starts(self):
previous = os.getcwd()
self.addCleanup(os.chdir, previous)
os.chdir(ROOT / "scripts")
self.assertEqual(runner.pack_output_dir(None), str(ROOT / "dist"))
self.assertEqual(runner.pack_output_dir("out"), str(ROOT / "scripts" / "out"))
os.chdir(REPO_ROOT / "scripts")
self.assertEqual(runner.pack_output_dir(None), str(REPO_ROOT / "dist"))
self.assertEqual(runner.pack_output_dir("out"), str(REPO_ROOT / "scripts" / "out"))
def test_main_resolves_it_before_the_lock(self):
source = script_source("pipeline.py")
@@ -1279,7 +1279,7 @@ class ToolsRunFromAnyDirectory(unittest.TestCase):
for script in ("verify.py", "generate_pack.py"):
with self.subTest(script=script):
proc = self._run(
ROOT / "scripts", str(ROOT / "scripts" / script),
REPO_ROOT / "scripts", str(REPO_ROOT / "scripts" / script),
"--platform", "RetroArch", "--list-systems",
)
self.assertEqual(proc.returncode, 0, proc.stderr)
@@ -1289,7 +1289,7 @@ class ToolsRunFromAnyDirectory(unittest.TestCase):
def test_a_typed_path_is_read_from_where_it_was_typed(self):
with tempfile.TemporaryDirectory() as tmp:
proc = self._run(
Path(tmp), str(ROOT / "scripts" / "generate_pack.py"),
Path(tmp), str(REPO_ROOT / "scripts" / "generate_pack.py"),
"--manifest-targets", "--output-dir", "lists",
)
self.assertEqual(proc.returncode, 0, proc.stderr)
@@ -1306,7 +1306,7 @@ class ATargetTypoIsAnErrorInEveryTool(unittest.TestCase):
proc = subprocess.run(
[sys.executable, f"scripts/{script}", "--platform", "retroarch",
"--target", "swich"],
cwd=ROOT, capture_output=True, text=True, timeout=300,
cwd=REPO_ROOT, capture_output=True, text=True, timeout=300,
check=False,
)
output = proc.stdout + proc.stderr
@@ -1327,7 +1327,7 @@ class AnUnknownSystemIsRefusedBeforeAnyWork(unittest.TestCase):
proc = subprocess.run(
[sys.executable, "scripts/generate_pack.py", "--platform", "batocera",
"--system", "playstaton-nothing", "--output-dir", str(out)],
cwd=ROOT, capture_output=True, text=True, timeout=120,
cwd=REPO_ROOT, capture_output=True, text=True, timeout=120,
check=False,
)
self.assertEqual(proc.returncode, 2, proc.stdout + proc.stderr)
@@ -1345,7 +1345,7 @@ class AnUnknownSystemIsRefusedBeforeAnyWork(unittest.TestCase):
parser = argparse.ArgumentParser()
args = argparse.Namespace(
system="sony-playstation", platform="retroarch", all=False,
platforms_dir=str(ROOT / "platforms"), manifest=False,
platforms_dir=str(REPO_ROOT / "platforms"), manifest=False,
)
self.assertEqual(resolve_system_ids(args, parser), ["sony-playstation"])
+48 -48
View File
@@ -15,7 +15,7 @@ import unittest
from pathlib import Path
from unittest import mock
import yaml
from tests.auditsupport import ROOT
from tests import REPO_ROOT
class ReadmeRegressions(unittest.TestCase):
@@ -27,7 +27,7 @@ class ReadmeRegressions(unittest.TestCase):
"""
def _quick_install(self) -> str:
readme = (ROOT / "README.md").read_text(encoding="utf-8")
readme = (REPO_ROOT / "README.md").read_text(encoding="utf-8")
return readme.split("## Install in one line", 1)[1].split(
"## Or download a ZIP", 1
)[0]
@@ -45,16 +45,16 @@ class ReadmeRegressions(unittest.TestCase):
commit = "0" * 40
for name in sitebootstrap.SOURCES:
self.assertIn(sitebootstrap.installer_url(commit),
sitebootstrap.served_text(name, ROOT, commit))
sitebootstrap.served_text(name, REPO_ROOT, commit))
self.assertIn(
"https://raw.githubusercontent.com/Abdess/retrobios/main/install.py",
(ROOT / "install.sh").read_text(encoding="utf-8"),
(REPO_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")
parser_source = (REPO_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}")
@@ -64,13 +64,13 @@ class ReadmeRegressions(unittest.TestCase):
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"),
(REPO_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, (REPO_ROOT / page).read_text(encoding="utf-8"))
self.assertIn(
version, script_source("generate_readme.py")
)
@@ -87,7 +87,7 @@ class ReadmeRegressions(unittest.TestCase):
# 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,
cwd=REPO_ROOT, capture_output=True, text=True, timeout=60, check=False,
)
self.assertEqual(proc.returncode, 1)
self.assertIn("needs Python 3.9", proc.stderr)
@@ -104,7 +104,7 @@ class ReadmeRegressions(unittest.TestCase):
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,
cwd=REPO_ROOT, capture_output=True, text=True, timeout=60, check=False,
)
self.assertEqual(proc.returncode, 1)
self.assertNotIn("SyntaxError", proc.stderr)
@@ -138,7 +138,7 @@ class ReadmeRegressions(unittest.TestCase):
# 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,
cwd=REPO_ROOT, capture_output=True, text=True, timeout=60,
check=False,
)
self.assertEqual(proc.returncode, 1, proc.stderr)
@@ -155,7 +155,7 @@ class ReadmeRegressions(unittest.TestCase):
floor = re.search(
r"sys\.version_info < \((\d+), (\d+)\)",
(ROOT / "scripts" / "pipeline.py").read_text(encoding="utf-8"),
(REPO_ROOT / "scripts" / "pipeline.py").read_text(encoding="utf-8"),
)
name = f"python{floor.group(1)}.{floor.group(2)}"
interpreter = shutil.which(name)
@@ -180,7 +180,7 @@ class ReadmeRegressions(unittest.TestCase):
"print(json.dumps(failed))\n"
)
proc = subprocess.run(
[interpreter, "-I", "-c", check], cwd=ROOT, capture_output=True,
[interpreter, "-I", "-c", check], cwd=REPO_ROOT, capture_output=True,
text=True, timeout=600, check=False,
env={**os.environ, "RETROBIOS_OFFLINE": "1"},
)
@@ -209,7 +209,7 @@ class PackReadmesSayWhatTheInstallerDoes(unittest.TestCase):
def _guide(self, platform: str) -> str:
from packs.readme import build_readme
registry = yaml.safe_load((ROOT / "platforms" / "_registry.yml").read_text())
registry = yaml.safe_load((REPO_ROOT / "platforms" / "_registry.yml").read_text())
install = registry["platforms"][platform].get("install") or {}
text = build_readme(platform, platform, "", 1, 1,
detect=install.get("detect", []),
@@ -230,7 +230,7 @@ class PackReadmesSayWhatTheInstallerDoes(unittest.TestCase):
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:
with (REPO_ROOT / "platforms" / "_registry.yml").open(encoding="utf-8") as handle:
registry = yaml.safe_load(handle)
targets = {
target.rstrip("/").replace("$HOME", "~")
@@ -263,13 +263,13 @@ class FaqRegressions(unittest.TestCase):
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")
(REPO_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:
with (REPO_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):
@@ -279,8 +279,8 @@ class FaqRegressions(unittest.TestCase):
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")
profiles = load_emulator_profiles(str(REPO_ROOT / "emulators"), skip_aliases=False)
page = (REPO_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",
@@ -303,7 +303,7 @@ class FaqRegressions(unittest.TestCase):
"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")
text = (REPO_ROOT / "wiki" / page).read_text(encoding="utf-8")
for line in text.splitlines():
if "Adler-32" in line or "adler32" in line:
self.assertNotIn(
@@ -390,11 +390,11 @@ class CatalogRatioRegressions(unittest.TestCase):
from scripts.model.composition import compute_composition, count_catalog_matched
from scripts.model.database import load_database
database = ROOT / "database.json"
database = REPO_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")
readme = (REPO_ROOT / "README.md").read_text(encoding="utf-8")
match = re.search(
r"\*\*([\d,]+) of ([\d,]+) system files\*\* matched to", readme
)
@@ -454,7 +454,7 @@ class ContributorsSurviveAFailedRequest(unittest.TestCase):
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()
text = (REPO_ROOT / "README.md").read_text()
# Missing is the failure this guards, never a reason to skip.
self.assertIn("## Contributors", text)
self.assertGreater(
@@ -542,7 +542,7 @@ class EveryReadmeNamesItsFolder(unittest.TestCase):
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())
registry = yaml.safe_load((REPO_ROOT / "platforms" / "_registry.yml").read_text())
for name, entry in registry["platforms"].items():
folder = (entry.get("extract_to") or "").rstrip("/")
if not folder:
@@ -563,7 +563,7 @@ class TheToolsPageSaysWhatDedupDoes(unittest.TestCase):
from scripts.model import nodedup
line = next(
row for row in (ROOT / "wiki" / "tools.md").read_text().splitlines()
row for row in (REPO_ROOT / "wiki" / "tools.md").read_text().splitlines()
if row.startswith("| `dedup.py`")
)
self.assertNotIn(".variants", line)
@@ -578,7 +578,7 @@ class ThePipelineTableNamesEveryStep(unittest.TestCase):
labels = set(re.findall(
r'"(\d[a-z]?\d?)(?:/8)? [a-z]', script_source("pipeline.py")
))
doc = (ROOT / "wiki" / "tools.md").read_text()
doc = (REPO_ROOT / "wiki" / "tools.md").read_text()
documented = set(re.findall(r"^\| (\d[a-z]?\d?)(?:/8)? \|", doc, re.MULTILINE))
self.assertEqual(labels - documented, set())
@@ -588,10 +588,10 @@ class DocumentedHashLookupsFindTheirFile(unittest.TestCase):
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"))
db = json.loads((REPO_ROOT / "database.json").read_text(encoding="utf-8"))
by_md5 = db["indexes"]["by_md5"]
found = 0
for page in sorted((ROOT / "wiki").glob("*.md")):
for page in sorted((REPO_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
@@ -606,17 +606,17 @@ class ToolReferenceListsEveryModule(unittest.TestCase):
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")
text = (REPO_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")}
modules = {p.stem for p in (REPO_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")
p.stem for p in (REPO_ROOT / "scripts" / "scraper" / "targets").glob("*_targets_scraper.py")
}
self.assertEqual(self._rows("Target scrapers"), modules)
@@ -626,10 +626,10 @@ class ToolReferenceCountsMatchTheirArtifacts(unittest.TestCase):
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")
self.text = (REPO_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"))
store = json.loads((REPO_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(
@@ -654,7 +654,7 @@ class WikiProseHasNoTornSentence(unittest.TestCase):
"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")):
for page in sorted((REPO_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):
@@ -676,18 +676,18 @@ class EveryOptionIsDocumented(unittest.TestCase):
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,
cwd=str(REPO_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"]
for path in [*sorted((REPO_ROOT / "wiki").glob("*.md")),
REPO_ROOT / "README.md", REPO_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")))
for flag in set(option.findall((REPO_ROOT / name).read_text(encoding="utf-8")))
if not re.search(re.escape(flag) + r"(?![\w-])", docs)
)
self.assertEqual(undocumented, [])
@@ -703,7 +703,7 @@ class OfflineHelpSaysWhatItCuts(unittest.TestCase):
with self.subTest(script=script):
out = subprocess.run(
[sys.executable, f"scripts/{script}", "--help"],
capture_output=True, text=True, cwd=str(ROOT), check=True,
capture_output=True, text=True, cwd=str(REPO_ROOT), check=True,
).stdout
block = out.split("--offline", 2)[-1].split("\n --", 1)[0]
self.assertIn("release", " ".join(block.split()))
@@ -717,7 +717,7 @@ class PipelineDocstringNamesThePrintedSteps(unittest.TestCase):
def test_the_two_lists_hold_the_same_steps(self):
import ast
source = (ROOT / "scripts" / "pipeline.py").read_text(encoding="utf-8")
source = (REPO_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
@@ -736,7 +736,7 @@ class DocumentedExamplesHoldTogether(unittest.TestCase):
import fnmatch
import re
page = (ROOT / "wiki" / "release-process.md").read_text(encoding="utf-8")
page = (REPO_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",
@@ -748,7 +748,7 @@ class DocumentedExamplesHoldTogether(unittest.TestCase):
import re
# The annotated run moved from First install to the installer page.
page = (ROOT / "wiki" / "installer.md").read_text(encoding="utf-8")
page = (REPO_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.
@@ -770,9 +770,9 @@ class TheReadmeCountsSystemsAsListSystemsDoes(unittest.TestCase):
out = io.StringIO()
with redirect_stdout(out):
list_system_ids(str(ROOT / "emulators"))
list_system_ids(str(REPO_ROOT / "emulators"))
listed = len(out.getvalue().splitlines())
readme = (ROOT / "README.md").read_text(encoding="utf-8")
readme = (REPO_ROOT / "README.md").read_text(encoding="utf-8")
announced = int(re.search(r"\*\*(\d+) systems\*\*", readme).group(1))
self.assertEqual(announced, listed)
@@ -786,18 +786,18 @@ class DocsDescribeTheRegistriesTheyName(unittest.TestCase):
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"]
paths = sorted((REPO_ROOT / "wiki").glob("*.md"))
paths += [REPO_ROOT / "scripts" / "generate_readme.py", REPO_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()
offenders = [str(p.relative_to(REPO_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")
tools = (REPO_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.
@@ -817,7 +817,7 @@ class SkipPacksHelpSaysWhatRuns(unittest.TestCase):
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,
cwd=REPO_ROOT, capture_output=True, text=True, timeout=60, check=True,
)
text = " ".join(proc.stdout.split())
self.assertNotIn("Only regenerate DB and verify", text)
+22 -22
View File
@@ -18,7 +18,7 @@ import yaml
import install
from orchestrate import runner
from scripts.packs.targets import generate_target_manifests
from tests.auditsupport import HAS_JSONSCHEMA, ROOT
from tests import HAS_JSONSCHEMA, REPO_ROOT
class InstallerBoundaryRegressions(unittest.TestCase):
@@ -91,7 +91,7 @@ class InstallerBoundaryRegressions(unittest.TestCase):
from jsonschema import Draft202012Validator
schema = json.loads(
(ROOT / "schemas" / "target-manifest.schema.json").read_text(
(REPO_ROOT / "schemas" / "target-manifest.schema.json").read_text(
encoding="utf-8"
)
)
@@ -158,7 +158,7 @@ class InstallerBoundaryRegressions(unittest.TestCase):
from packs import scope
from schemas import packmanifests
install_list = json.loads((ROOT / "install" / "romm.json").read_text(encoding="utf-8"))
install_list = json.loads((REPO_ROOT / "install" / "romm.json").read_text(encoding="utf-8"))
targets = {"browser": None, "rpi4": {"cores": ["mgba"], "images": ["rpi4"]}}
document = {
"schema_version": 1, "version": 1,
@@ -226,10 +226,10 @@ class TargetManifestRegressions(unittest.TestCase):
generate_target_manifests(str(root / "absent"), str(root / "out"))
(root / "plat").mkdir()
run = subprocess.run(
[sys.executable, str(ROOT / "scripts" / "generate_pack.py"),
[sys.executable, str(REPO_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,
capture_output=True, text=True, cwd=REPO_ROOT, check=False,
)
self.assertEqual(run.returncode, 1, run.stderr)
self.assertIn("No targets directory at", run.stderr)
@@ -242,7 +242,7 @@ def _git_paths(*args: str, stdin: list[str] | None = None) -> set[str] | None:
result = subprocess.run(
["git", *args],
input="".join(f"{p}\0" for p in stdin or []),
capture_output=True, text=True, cwd=ROOT, check=False,
capture_output=True, text=True, cwd=REPO_ROOT, check=False,
)
except FileNotFoundError:
return None
@@ -264,18 +264,18 @@ class ManifestVersionIsThePlatformsOwn(unittest.TestCase):
def test_committed_manifests_state_their_platform_version(self):
from scripts.model.platforms import load_platform_config
manifests = sorted((ROOT / "install").glob("*.json"))
manifests = sorted((REPO_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"))
config = load_platform_config(data["platform"], str(REPO_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"
platforms = REPO_ROOT / "platforms"
children = {}
for path in sorted(platforms.glob("*.yml")):
raw = yaml.safe_load(path.read_text()) or {}
@@ -298,7 +298,7 @@ class ManifestVersionIsThePlatformsOwn(unittest.TestCase):
self.assertNotIn("version", load_platform_config("child", tmp))
def test_lakka_names_the_release_its_cores_are_read_at(self):
platforms = ROOT / "platforms"
platforms = REPO_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)
@@ -316,7 +316,7 @@ class EveryManifestEntryIsFetchable(unittest.TestCase):
"""
def test_committed_manifests_all_have_a_source(self):
manifests = sorted((ROOT / "install").glob("*.json"))
manifests = sorted((REPO_ROOT / "install").glob("*.json"))
self.assertTrue(manifests, "no install manifests to check")
for path in manifests:
with self.subTest(manifest=path.name):
@@ -332,7 +332,7 @@ class EveryManifestEntryIsFetchable(unittest.TestCase):
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")):
for path in sorted((REPO_ROOT / "install").glob("*.json")):
with self.subTest(manifest=path.name):
data = json.loads(path.read_text())
for entry in data.get("omitted_files", []):
@@ -341,7 +341,7 @@ class EveryManifestEntryIsFetchable(unittest.TestCase):
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")):
for path in sorted((REPO_ROOT / "install").glob("*.json")):
with self.subTest(manifest=path.name):
data = json.loads(path.read_text())
install._validate_manifest(data, data["platform"])
@@ -351,8 +351,8 @@ class EveryManifestEntryIsFetchable(unittest.TestCase):
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"))
for path in sorted((REPO_ROOT / "install").glob("*.json"))}
layouts = sorted((REPO_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")})
@@ -367,7 +367,7 @@ class EveryManifestEntryIsFetchable(unittest.TestCase):
def test_schema_and_installer_name_the_same_reasons(self):
schema = json.loads(
(ROOT / "schemas" / "install-manifest.schema.json").read_text()
(REPO_ROOT / "schemas" / "install-manifest.schema.json").read_text()
)
reasons = schema["properties"]["omitted_files"]["items"]["properties"][
"reason"
@@ -375,8 +375,8 @@ class EveryManifestEntryIsFetchable(unittest.TestCase):
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"))
paths = sorted((REPO_ROOT / "install").glob("*.json"))
paths += sorted((REPO_ROOT / "install" / "targets").glob("*.json"))
self.assertTrue(paths, "no install manifests to check")
return paths
@@ -389,7 +389,7 @@ class EveryManifestEntryIsFetchable(unittest.TestCase):
repo_path from raw.githubusercontent.com, so a stale one is a
download that can never succeed.
"""
database = ROOT / "database.json"
database = REPO_ROOT / "database.json"
if not database.is_file():
self.skipTest("database.json not generated")
files = json.loads(database.read_text(encoding="utf-8"))["files"]
@@ -463,7 +463,7 @@ class EveryManifestEntryIsFetchable(unittest.TestCase):
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"
database = REPO_ROOT / "database.json"
if not database.is_file():
self.skipTest("database.json not generated")
files = json.loads(database.read_text(encoding="utf-8"))["files"]
@@ -776,12 +776,12 @@ class InstallerJsonKindsNeverOverwriteEachOther(unittest.TestCase):
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")
before = (REPO_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,
cwd=REPO_ROOT, capture_output=True, text=True, timeout=600,
check=False,
)
return proc, before, target.read_text(encoding="utf-8")
+10 -10
View File
@@ -21,7 +21,7 @@ import yaml
from scripts.resolve import regionaudit, regions
from scripts.packs.extraregions import _emulator_region_group
from scripts.packs.platformcheck import verify_pack_against_platform
from tests.auditsupport import ROOT
from tests import REPO_ROOT
class APackIsSwappedInWhole(unittest.TestCase):
@@ -33,7 +33,7 @@ class APackIsSwappedInWhole(unittest.TestCase):
import shutil
import tempfile
(ROOT / "tmp").mkdir(exist_ok=True)
(REPO_ROOT / "tmp").mkdir(exist_ok=True)
directory = Path(tempfile.mkdtemp())
self.addCleanup(shutil.rmtree, directory, True)
return directory
@@ -84,8 +84,8 @@ class EverySharedGroupServesAPlatform(unittest.TestCase):
from model.registry import list_registered_platforms
from model.platforms import load_platform_config
platforms_dir = str(ROOT / "platforms")
with (ROOT / "platforms" / "_shared.yml").open(encoding="utf-8") as handle:
platforms_dir = str(REPO_ROOT / "platforms")
with (REPO_ROOT / "platforms" / "_shared.yml").open(encoding="utf-8") as handle:
groups = set((yaml.safe_load(handle) or {}).get("shared_groups") or {})
served = {
entry.get("shared_group")
@@ -205,7 +205,7 @@ class StandaloneCopiesComeFromTheProfiles(unittest.TestCase):
def test_the_published_retroarch_list_reaches_cemu(self):
import json
manifest = json.loads((ROOT / "install" / "retroarch.json").read_text())
manifest = json.loads((REPO_ROOT / "install" / "retroarch.json").read_text())
files = {copy["file"]: copy for copy in manifest["standalone_copies"]
if "file" in copy}
for name in ("Cemu/keys.txt", "Cemu/otp.bin", "Cemu/seeprom.bin"):
@@ -1058,7 +1058,7 @@ class ReportsHoldTheDataTrees(unittest.TestCase):
# check calls too (TheExportHoldsTheDataTrees in test_export_report).
for script in ("generate_readme.py", "generate_site.py", "slots.py",
"cross_reference.py"):
tree = ast.parse((ROOT / "scripts" / script).read_text(encoding="utf-8"))
tree = ast.parse((REPO_ROOT / "scripts" / script).read_text(encoding="utf-8"))
main = next(
node for node in tree.body
if isinstance(node, ast.FunctionDef) and node.name == "main"
@@ -1155,7 +1155,7 @@ class RequiredOnlyReachesDataDirectories(unittest.TestCase):
self.assertIn("data_refs, required_only=required_only,", source)
def test_the_overlays_are_declared_optional(self):
retroarch = yaml.safe_load((ROOT / "platforms" / "retroarch.yml").read_text())
retroarch = yaml.safe_load((REPO_ROOT / "platforms" / "retroarch.yml").read_text())
trees = retroarch["systems"]["mattel-intellivision"]["data_directories"]
self.assertEqual(trees, [
{"ref": "freeintv-overlays", "destination": "freeintv_overlays",
@@ -1168,7 +1168,7 @@ class RequiredOnlyReachesDataDirectories(unittest.TestCase):
emulator pack of the core itself left the overlays out."""
profiles = {
path.stem: yaml.safe_load(path.read_text(encoding="utf-8"))
for path in (ROOT / "emulators").glob("*.yml")
for path in (REPO_ROOT / "emulators").glob("*.yml")
}
def trees(profile: dict) -> dict:
@@ -1331,7 +1331,7 @@ class NoArchiveRepeatsAMemberName(unittest.TestCase):
warnings and Info-ZIP stops on an interactive replace? at extraction."""
def test_member_names_are_unique(self):
archives = sorted((ROOT / "bios").rglob("*.zip"))
archives = sorted((REPO_ROOT / "bios").rglob("*.zip"))
if not archives:
self.skipTest("no archive under bios/")
repeated = []
@@ -1342,7 +1342,7 @@ class NoArchiveRepeatsAMemberName(unittest.TestCase):
except (zipfile.BadZipFile, OSError):
continue
if len(names) != len(set(names)):
repeated.append(str(path.relative_to(ROOT)))
repeated.append(str(path.relative_to(REPO_ROOT)))
self.assertEqual(repeated, [])
+48 -48
View File
@@ -15,7 +15,7 @@ import unittest
from pathlib import Path
from unittest import mock
import yaml
from tests.auditsupport import HAS_JSONSCHEMA, ROOT
from tests import HAS_JSONSCHEMA, REPO_ROOT
class UnreachableCitationRegressions(unittest.TestCase):
@@ -59,7 +59,7 @@ class UnreachableCitationRegressions(unittest.TestCase):
from schemas import citations
errors = []
for path in sorted((ROOT / "emulators").glob("*.yml")):
for path in sorted((REPO_ROOT / "emulators").glob("*.yml")):
with path.open(encoding="utf-8") as handle:
errors.extend(
citations.unreachable_citations(path, yaml.safe_load(handle))
@@ -97,7 +97,7 @@ class DoubledCitationPaths(unittest.TestCase):
from schemas import citations
errors = []
for path in sorted((ROOT / "emulators").glob("*.yml")):
for path in sorted((REPO_ROOT / "emulators").glob("*.yml")):
errors.extend(citations.doubled_paths(path))
self.assertEqual(errors, [])
@@ -118,7 +118,7 @@ class KidVidTapesStayWithTheContent(unittest.TestCase):
read_from_system_dir,
)
profiles = load_emulator_profiles(str(ROOT / "emulators"))
profiles = load_emulator_profiles(str(REPO_ROOT / "emulators"))
for name in ("stella", "stella2014", "stella2023"):
tapes = [f for f in profiles[name]["files"]
if f["name"].lower().endswith(".wav")]
@@ -140,10 +140,10 @@ class GeneralUserGSReachesEveryCoreThatNamesIt(unittest.TestCase):
from model import profiles as model_profiles
from resolve import localfile
if not (ROOT / "database.json").exists():
if not (REPO_ROOT / "database.json").exists():
self.skipTest("database.json is not generated")
db = json.loads((ROOT / "database.json").read_text())
profiles = model_profiles.load_emulator_profiles(str(ROOT / "emulators"))
db = json.loads((REPO_ROOT / "database.json").read_text())
profiles = model_profiles.load_emulator_profiles(str(REPO_ROOT / "emulators"))
held = "bios/Other/GeneralUser GS/GeneralUser-GS.sf2"
for emulator, name in (("dosbox_pure", "DOSBOX.SF2"),
("dosbox-staging", "GeneralUser-GS.sf2"),
@@ -165,10 +165,10 @@ class APlatformPinDoesNotReplaceTheCoresRevision(unittest.TestCase):
from model import profiles as model_profiles
from resolve import localfile
if not (ROOT / "database.json").exists():
if not (REPO_ROOT / "database.json").exists():
self.skipTest("database.json is not generated")
db = json.loads((ROOT / "database.json").read_text())
profiles = model_profiles.load_emulator_profiles(str(ROOT / "emulators"))
db = json.loads((REPO_ROOT / "database.json").read_text())
profiles = model_profiles.load_emulator_profiles(str(REPO_ROOT / "emulators"))
for emulator, name, pinned in (("scummvm", "kyra.dat", "21a57f79886e46f410cfb50186ed8d77"),
("fbneo", "hiscore.dat", "37fc4e050b53a1ef2c2e7f3042553025")):
with self.subTest(emulator=emulator):
@@ -202,7 +202,7 @@ class ProseCitationsUseTheTrackedForm(unittest.TestCase):
def test_no_profile_writes_a_line_number_profile_sync_cannot_see(self):
found = [
f"{path.name}:{number}: {match.group(0)}"
for path in sorted((ROOT / "emulators").glob("*.yml"))
for path in sorted((REPO_ROOT / "emulators").glob("*.yml"))
for number, line in enumerate(path.read_text().splitlines(), 1)
for match in self.UNTRACKED.finditer(line)
]
@@ -259,9 +259,9 @@ class OpenMsxRomsSitInItsSystemroms(unittest.TestCase):
from scripts.model.platforms import load_platform_config
from scripts.resolve.standalone import platform_layouts, platform_launches
profiles = load_emulator_profiles(str(ROOT / "emulators"))
profiles = load_emulator_profiles(str(REPO_ROOT / "emulators"))
profile = profiles["openmsx"]
retrobat = yaml.safe_load((ROOT / "platforms" / "retrobat.yml").read_text())
retrobat = yaml.safe_load((REPO_ROOT / "platforms" / "retrobat.yml").read_text())
declared_dirs = {
fe["destination"].rsplit("/", 1)[0].lower()
for system in retrobat["systems"].values()
@@ -269,7 +269,7 @@ class OpenMsxRomsSitInItsSystemroms(unittest.TestCase):
if "systemroms" in fe.get("destination", "")
}
self.assertEqual(declared_dirs, {"openmsx/share/systemroms"})
config = load_platform_config("retrobat", str(ROOT / "platforms"))
config = load_platform_config("retrobat", str(REPO_ROOT / "platforms"))
((view, _standalone),) = platform_layouts("openmsx", profile, platform_launches(config, profiles))
placed = {f["name"]: f for f in view["files"]}
for entry in profile["files"]:
@@ -290,12 +290,12 @@ class EmuDeckRunsItsEmulatorsStandalone(unittest.TestCase):
from scripts.resolve.launches import PlatformLaunches
from scripts.model.profiles import load_emulator_profiles
config = load_platform_config("emudeck", str(ROOT / "platforms"))
config = load_platform_config("emudeck", str(REPO_ROOT / "platforms"))
self.assertEqual(
sorted(config["standalone_cores"]),
sorted(c for c in config["cores"] if c != "retroarch"),
)
profiles = load_emulator_profiles(str(ROOT / "emulators"))
profiles = load_emulator_profiles(str(REPO_ROOT / "emulators"))
standalone = PlatformLaunches(standalone=frozenset(config["standalone_cores"]))
for name in ("dolphin", "cemu", "armsx2", "supermodel"):
with self.subTest(emulator=name):
@@ -309,9 +309,9 @@ class EmuDeckRunsItsEmulatorsStandalone(unittest.TestCase):
from scripts.model.platforms import load_platform_config
from scripts.resolve.cores import resolve_platform_cores
config = load_platform_config("emudeck", str(ROOT / "platforms"))
config = load_platform_config("emudeck", str(REPO_ROOT / "platforms"))
self.assertIn("retroarch", config["cores"])
cores = resolve_platform_cores(config, load_emulator_profiles(str(ROOT / "emulators")))
cores = resolve_platform_cores(config, load_emulator_profiles(str(REPO_ROOT / "emulators")))
for name in ("np2kai", "neocd", "dolphin"):
with self.subTest(core=name):
self.assertIn(name, cores)
@@ -409,10 +409,10 @@ class BundledFilesAreNotToSource(unittest.TestCase):
from model.registry import list_registered_platforms
from model.profiles import load_emulator_profiles
known = set(list_registered_platforms(str(ROOT / "platforms")))
known = set(list_registered_platforms(str(REPO_ROOT / "platforms")))
unknown = sorted({
(name, platform)
for name, profile in load_emulator_profiles(str(ROOT / "emulators")).items()
for name, profile in load_emulator_profiles(str(REPO_ROOT / "emulators")).items()
for entry in (profile.get("files") or []) + (profile.get("data_directories") or [])
if isinstance(entry, dict)
for field in ("installed_on", "not_bundled_on")
@@ -436,7 +436,7 @@ class BundledFilesAreNotToSource(unittest.TestCase):
self.assertIn("installed=installed_data_refs_in(plan.platform_name", source)
def test_the_pack_builder_skips_it(self):
source = (ROOT / "scripts" / "packs" / "extras.py").read_text(encoding="utf-8")
source = (REPO_ROOT / "scripts" / "packs" / "extras.py").read_text(encoding="utf-8")
self.assertIn('if u.get("bundled"):', source)
@@ -478,7 +478,7 @@ const _EJS_NIGHTLY_CORES_MAP: Record<string, string[]> = {
def test_the_platform_file_carries_the_nightly_cores(self):
from model.platforms import load_platform_config
cores = set(load_platform_config("romm", str(ROOT / "platforms"))["cores"])
cores = set(load_platform_config("romm", str(REPO_ROOT / "platforms"))["cores"])
self.assertTrue({"azahar", "bsnes", "genesis_plus_gx_wide"} <= cores)
@@ -514,7 +514,7 @@ class RommNeoGeoFoldersGetTheirBios(unittest.TestCase):
self.assertEqual(_slug_for({"profile": "melonds"}, *args), "nds")
def test_the_platform_file_carries_it(self):
text = (ROOT / "platforms" / "romm.yml").read_text(encoding="utf-8")
text = (REPO_ROOT / "platforms" / "romm.yml").read_text(encoding="utf-8")
self.assertIn("destination: neogeoaes/neogeo.zip", text)
self.assertIn("destination: neogeomvs/neogeo.zip", text)
self.assertNotIn("neogeoaes/pgm.zip", text)
@@ -559,7 +559,7 @@ class AHashScanningCoreContradictsNoPlatform(unittest.TestCase):
from scripts.model.registry import list_registered_platforms
from scripts.model.profiles import load_emulator_profiles
root = ROOT
root = REPO_ROOT
if not (root / "database.json").exists():
self.skipTest("database.json is not built")
profiles = load_emulator_profiles(str(root / "emulators"))
@@ -582,7 +582,7 @@ class FsUaeKickstartIsFoundByContent(unittest.TestCase):
def test_the_kickstart_is_an_optional_label(self):
from scripts.resolve.entryscope import opens_by_name
profile = yaml.safe_load((ROOT / "emulators" / "fs-uae.yml").read_text(encoding="utf-8"))
profile = yaml.safe_load((REPO_ROOT / "emulators" / "fs-uae.yml").read_text(encoding="utf-8"))
entry = next(f for f in profile["files"] if f.get("sha1") == "891e9a547772fe0c6c19b610baf8bc4ea7fcb785")
self.assertFalse(opens_by_name(entry, profile, standalone=True))
self.assertFalse(entry.get("required"))
@@ -601,7 +601,7 @@ class NoProfileHashFromASecondarySource(unittest.TestCase):
def test_no_hashed_entry_names_a_secondary_source(self):
found = []
for path in sorted((ROOT / "emulators").glob("*.yml")):
for path in sorted((REPO_ROOT / "emulators").glob("*.yml")):
profile = yaml.safe_load(path.read_text(encoding="utf-8")) or {}
for entry in profile.get("files") or []:
if not isinstance(entry, dict):
@@ -621,7 +621,7 @@ class XeniosFollowsItsReleaseBranch(unittest.TestCase):
default branch, so the profile names no other branch."""
def test_the_profile_follows_the_branch_its_pin_is_on(self):
profile = yaml.safe_load((ROOT / "emulators" / "xenios.yml").read_text(encoding="utf-8"))
profile = yaml.safe_load((REPO_ROOT / "emulators" / "xenios.yml").read_text(encoding="utf-8"))
self.assertIn(profile.get("source_branch"), (None, "xenios"))
self.assertEqual(profile["source_commit"][:7], "cf7c7ee")
@@ -634,7 +634,7 @@ class PcemUpstreamPinIsTheLastSync(unittest.TestCase):
bump cannot move it to a HEAD the port never contained."""
def test_the_upstream_pin_is_held_at_the_last_sync(self):
profile = yaml.safe_load((ROOT / "emulators" / "pcem.yml").read_text(encoding="utf-8"))
profile = yaml.safe_load((REPO_ROOT / "emulators" / "pcem.yml").read_text(encoding="utf-8"))
self.assertEqual(profile["upstream_commit"], "10739b9618e388a5bf8c21e752f12b3952fa83e1")
self.assertTrue(profile.get("upstream_frozen"))
@@ -690,10 +690,10 @@ class AHashScanLabelNamesNoOtherDump(unittest.TestCase):
from scripts.model.profiles import load_emulator_profiles
if not (ROOT / "database.json").exists():
if not (REPO_ROOT / "database.json").exists():
self.skipTest("database.json is not built")
db = json.loads((ROOT / "database.json").read_text(encoding="utf-8"))
profiles = load_emulator_profiles(str(ROOT / "emulators"))
db = json.loads((REPO_ROOT / "database.json").read_text(encoding="utf-8"))
profiles = load_emulator_profiles(str(REPO_ROOT / "emulators"))
by_name: dict[str, list[tuple[str, dict]]] = {}
for emulator, profile in profiles.items():
for entry in profile.get("files") or []:
@@ -738,7 +738,7 @@ class ANoteOutsideTheSystemDirCarriesLoadFrom(unittest.TestCase):
def test_prose_and_load_from_agree(self):
offenders = []
for path in sorted((ROOT / "emulators").glob("*.yml")):
for path in sorted((REPO_ROOT / "emulators").glob("*.yml")):
profile = yaml.safe_load(path.read_text(encoding="utf-8")) or {}
if profile.get("type") != "libretro":
continue
@@ -756,11 +756,11 @@ class TheTreeKeepsStandaloneEntries(unittest.TestCase):
Batocera and RetroBat run standalone and no platform declares."""
def test_a_standalone_only_entry_is_reported(self):
if not (ROOT / "database.json").exists():
if not (REPO_ROOT / "database.json").exists():
self.skipTest("database.json is not built")
out = subprocess.run(
[sys.executable, "scripts/cross_reference.py", "--emulator", "eka2l1"],
cwd=ROOT, capture_output=True, text=True, timeout=600, check=True,
cwd=REPO_ROOT, capture_output=True, text=True, timeout=600, check=True,
).stdout
undeclared = re.search(r"(\d+) undeclared", out)
self.assertIsNotNone(undeclared, out[-500:])
@@ -851,9 +851,9 @@ class WhatOnlyAnInstallProvidesIsListed(unittest.TestCase):
from model.profiles import load_emulator_profiles
rows = bundledonly.bundled_only(
load_database(str(ROOT / "database.json")),
load_emulator_profiles(str(ROOT / "emulators")),
str(ROOT / "platforms"), ROOT / "install",
load_database(str(REPO_ROOT / "database.json")),
load_emulator_profiles(str(REPO_ROOT / "emulators")),
str(REPO_ROOT / "platforms"), REPO_ROOT / "install",
)
self.assertEqual([f"{r['path']} ({', '.join(r['emulators'])})" for r in rows], [],
"remove the copy: the emulator's own install provides it")
@@ -888,7 +888,7 @@ class AmigaCdDriversLiveInTheExtendedRom(unittest.TestCase):
def test_both_extended_roms_are_required_without_fallback(self):
profile = yaml.safe_load(
(ROOT / "emulators" / "winuae.yml").read_text(encoding="utf-8")
(REPO_ROOT / "emulators" / "winuae.yml").read_text(encoding="utf-8")
)
entries = {f["name"]: f for f in profile["files"]}
for name in ("amiga-ext-310-cd32.rom", "amiga-ext-130-cdtv.rom"):
@@ -906,7 +906,7 @@ class BizHawkListsEveryDsiNandSlot(unittest.TestCase):
def test_the_six_regional_nands_are_declared(self):
profile = yaml.safe_load(
(ROOT / "emulators" / "bizhawk.yml").read_text(encoding="utf-8")
(REPO_ROOT / "emulators" / "bizhawk.yml").read_text(encoding="utf-8")
)
entries = {f["name"]: f for f in profile["files"]}
for region_code in ("JPN", "EUR", "USA", "AUS", "CHN", "KOR"):
@@ -927,7 +927,7 @@ class HiganSuperGameBoyFolderIsFree(unittest.TestCase):
import yaml
file_names: set[str] = set()
for path in (ROOT / "emulators").glob("*.yml"):
for path in (REPO_ROOT / "emulators").glob("*.yml"):
document = yaml.safe_load(path.read_text(encoding="utf-8")) or {}
for entry in document.get("files") or []:
for name in [entry.get("name"), *(entry.get("aliases") or [])]:
@@ -937,7 +937,7 @@ class HiganSuperGameBoyFolderIsFree(unittest.TestCase):
file_names.add(str(entry["path"]).casefold())
for profile in ("higan_sfc", "higan_sfc_balanced"):
document = yaml.safe_load(
(ROOT / "emulators" / f"{profile}.yml").read_text(encoding="utf-8")
(REPO_ROOT / "emulators" / f"{profile}.yml").read_text(encoding="utf-8")
)
folders = {
str(entry["path"]).split("/", 1)[0]
@@ -960,10 +960,10 @@ class ProfileNotesDescribeTheCoreAlone(unittest.TestCase):
SHOUT = re.compile(r"\b(NOT|NEVER|ONLY|MUST|ALL|DIFFERENT)\b(?! FOUND)")
def test_no_profile_shouts_or_compares_with_another_profile(self):
names = {path.stem.casefold() for path in (ROOT / "emulators").glob("*.yml")}
names = {path.stem.casefold() for path in (REPO_ROOT / "emulators").glob("*.yml")}
names |= {name.replace("_", "-") for name in names}
found = []
for path in sorted((ROOT / "emulators").glob("*.yml")):
for path in sorted((REPO_ROOT / "emulators").glob("*.yml")):
text = path.read_text(encoding="utf-8")
for number, line in enumerate(text.splitlines(), 1):
if self.SHOUT.search(line):
@@ -991,7 +991,7 @@ class Ps2BiosImagesAreFoundByContent(unittest.TestCase):
from resolve.entryscope import opens_by_name
named = []
for path in sorted((ROOT / "emulators").glob("*.yml")):
for path in sorted((REPO_ROOT / "emulators").glob("*.yml")):
profile = yaml.safe_load(path.read_text(encoding="utf-8")) or {}
# Whatever the profile's own flags: TeknoParrot documents its
# pcsx2x6 component, whose scan is the same (BiosTools.cpp:268-291
@@ -1021,7 +1021,7 @@ class SynthRomsAreFoundByContent(unittest.TestCase):
from resolve.entryscope import opens_by_name
profile = yaml.safe_load(
(ROOT / "emulators" / "dosbox-staging.yml").read_text(encoding="utf-8")
(REPO_ROOT / "emulators" / "dosbox-staging.yml").read_text(encoding="utf-8")
)
named = [
entry["name"]
@@ -1042,7 +1042,7 @@ class Dev9FilesAreReadFromTheWorkingDirectory(unittest.TestCase):
import yaml
unset = []
for path in sorted((ROOT / "emulators").glob("*.yml")):
for path in sorted((REPO_ROOT / "emulators").glob("*.yml")):
profile = yaml.safe_load(path.read_text(encoding="utf-8")) or {}
unset.extend(
f"{path.stem}: {entry['name']}"
@@ -1067,7 +1067,7 @@ class OpenMsxSystemRomsAreFoundBySha1(unittest.TestCase):
from resolve.entryscope import opens_by_name
profile = yaml.safe_load((ROOT / "emulators" / "openmsx.yml").read_text())
profile = yaml.safe_load((REPO_ROOT / "emulators" / "openmsx.yml").read_text())
named = [
entry["name"] for entry in profile["files"]
if "share/systemroms/" in str(entry.get("path"))
@@ -1087,7 +1087,7 @@ class PrboomPlusCitesFullPaths(unittest.TestCase):
from scripts.model.sourceref import source_ref_values, split_source_ref
profile = yaml.safe_load((ROOT / "emulators" / "prboom-plus.yml").read_text(encoding="utf-8"))
profile = yaml.safe_load((REPO_ROOT / "emulators" / "prboom-plus.yml").read_text(encoding="utf-8"))
refs: list[str] = []
def walk(node):
+55 -55
View File
@@ -16,7 +16,7 @@ import unittest
from pathlib import Path
from unittest import mock
import yaml
from tests.auditsupport import HAS_JSONSCHEMA, ROOT, jsonschema
from tests import HAS_JSONSCHEMA, REPO_ROOT
class AModuleRunAloneHasItsScratchDirectory(unittest.TestCase):
@@ -29,7 +29,7 @@ class AModuleRunAloneHasItsScratchDirectory(unittest.TestCase):
clone = Path(directory)
(clone / "tests").mkdir()
(clone / "tests" / "__init__.py").write_bytes(
(ROOT / "tests" / "__init__.py").read_bytes()
(REPO_ROOT / "tests" / "__init__.py").read_bytes()
)
# The folder a module gets alone, not the one scripts/run_tests.py
# names for each module it runs beside others.
@@ -56,7 +56,7 @@ class EveryTestModuleImportsTheIsolation(unittest.TestCase):
def test_the_package_import_comes_before_any_other(self):
missing = []
for path in sorted((ROOT / "tests").glob("test_*.py")):
for path in sorted((REPO_ROOT / "tests").glob("test_*.py")):
body = ast.parse(path.read_text(encoding="utf-8")).body
imports = [
node for node in body
@@ -79,14 +79,14 @@ class EveryTestModuleImportsTheIsolation(unittest.TestCase):
"unittest.TestLoader().discover('tests', pattern='test_artifact_lock.py')\n"
"print(os.environ.get('RETROBIOS_OFFLINE'), tempfile.gettempdir(),"
" os.environ.get('RETROBIOS_CACHE'))\n"],
cwd=ROOT, env=env, capture_output=True, text=True, timeout=120,
cwd=REPO_ROOT, env=env, capture_output=True, text=True, timeout=120,
check=False,
)
self.assertEqual(proc.returncode, 0, proc.stderr)
offline, scratch, cache = proc.stdout.split()
self.assertEqual(offline, "1")
self.assertEqual(scratch, str(ROOT / "tmp" / "tests"))
self.assertEqual(cache, str(ROOT / "tmp" / "tests" / "cache"))
self.assertEqual(scratch, str(REPO_ROOT / "tmp" / "tests"))
self.assertEqual(cache, str(REPO_ROOT / "tmp" / "tests" / "cache"))
class ReleaseSigningRegressions(unittest.TestCase):
@@ -101,7 +101,7 @@ class ReleaseSigningRegressions(unittest.TestCase):
PRINCIPAL = "releases@retrobios"
def test_allowed_signers_names_one_usable_key(self):
path = ROOT / "allowed_signers"
path = REPO_ROOT / "allowed_signers"
self.assertTrue(path.exists(), "allowed_signers is the published trust root")
lines = [
line for line in path.read_text(encoding="utf-8").splitlines()
@@ -115,7 +115,7 @@ class ReleaseSigningRegressions(unittest.TestCase):
self.assertTrue(len(blob) > 40, "key material looks truncated")
def test_the_release_signs_the_list_and_ships_the_signature(self):
process = (ROOT / "wiki" / "release-process.md").read_text(encoding="utf-8")
process = (REPO_ROOT / "wiki" / "release-process.md").read_text(encoding="utf-8")
self.assertIn(
"ssh-keygen -Y sign", process, "the release no longer signs the list"
)
@@ -129,7 +129,7 @@ class ReleaseSigningRegressions(unittest.TestCase):
)
def test_the_documented_verification_matches_the_published_principal(self):
process = (ROOT / "wiki" / "release-process.md").read_text(encoding="utf-8")
process = (REPO_ROOT / "wiki" / "release-process.md").read_text(encoding="utf-8")
self.assertIn("ssh-keygen -Y verify", process)
self.assertIn(f"-I {self.PRINCIPAL}", process)
self.assertIn("allowed_signers", process)
@@ -145,7 +145,7 @@ class WorkflowRegressions(unittest.TestCase):
@staticmethod
def _workflow(name: str) -> dict:
with (ROOT / ".github" / "workflows" / name).open(encoding="utf-8") as f:
with (REPO_ROOT / ".github" / "workflows" / name).open(encoding="utf-8") as f:
document = yaml.safe_load(f)
# PyYAML resolves the bare `on:` key to the boolean True.
document["on"] = document.pop(True, document.get("on"))
@@ -244,7 +244,7 @@ class WorkflowRegressions(unittest.TestCase):
def test_no_workflow_relies_on_a_yaml_anchor(self):
"""The workflow parser reads no anchor, and PyYAML would hide the break."""
for path in sorted((ROOT / ".github" / "workflows").glob("*.yml")):
for path in sorted((REPO_ROOT / ".github" / "workflows").glob("*.yml")):
for number, line in enumerate(
path.read_text(encoding="utf-8").splitlines(), 1
):
@@ -264,7 +264,7 @@ class PatchesTargetWhatRuns(unittest.TestCase):
def test_no_test_creates_the_attribute_it_patches(self):
needle = "create" + "=True"
offenders = []
for path in sorted((ROOT / "tests").glob("test_*.py")):
for path in sorted((REPO_ROOT / "tests").glob("test_*.py")):
for number, line in enumerate(path.read_text(encoding="utf-8").splitlines(), 1):
code = line.split("#", 1)[0]
if needle in code:
@@ -282,7 +282,7 @@ class NoParserAcceptsAnAbbreviation(unittest.TestCase):
import ast
lax = []
for path in sorted([*(ROOT / "scripts").rglob("*.py"), ROOT / "install.py"]):
for path in sorted([*(REPO_ROOT / "scripts").rglob("*.py"), REPO_ROOT / "install.py"]):
for node in ast.walk(ast.parse(path.read_text(encoding="utf-8"))):
if not isinstance(node, ast.Call):
continue
@@ -295,7 +295,7 @@ class NoParserAcceptsAnAbbreviation(unittest.TestCase):
and isinstance(kw.value, ast.Constant) and kw.value.value is False
for kw in node.keywords
):
lax.append(f"{path.relative_to(ROOT)}:{node.lineno}")
lax.append(f"{path.relative_to(REPO_ROOT)}:{node.lineno}")
self.assertEqual(lax, [])
@@ -314,7 +314,7 @@ class SchemaFormatsAreChecked(unittest.TestCase):
def test_every_install_asks_for_the_extras(self):
for path in (".github/workflows/validate.yml", ".github/workflows/deploy-site.yml",
"pyproject.toml"):
text = (ROOT / path).read_text(encoding="utf-8")
text = (REPO_ROOT / path).read_text(encoding="utf-8")
with self.subTest(path=path):
self.assertNotRegex(text, r"jsonschema(?!\[format)[=>]")
@@ -328,7 +328,7 @@ class CheckoutCompletenessRegressions(unittest.TestCase):
"""
def _steps(self, workflow: str, job: str) -> list[dict]:
data = yaml.safe_load((ROOT / ".github" / "workflows" / workflow).read_text())
data = yaml.safe_load((REPO_ROOT / ".github" / "workflows" / workflow).read_text())
return data["jobs"][job]["steps"]
def _index(self, steps: list[dict], needle: str) -> int:
@@ -385,7 +385,7 @@ class CheckoutCompletenessRegressions(unittest.TestCase):
with self.assertRaises(FileNotFoundError):
gitignored_paths(missing)
proc = subprocess.run(
[sys.executable, str(ROOT / "scripts" / "restore_large_files.py"),
[sys.executable, str(REPO_ROOT / "scripts" / "restore_large_files.py"),
"--gitignore", missing, "--cache", directory],
capture_output=True, text=True, timeout=120,
check=False,
@@ -494,7 +494,7 @@ class CheckoutCompletenessRegressions(unittest.TestCase):
}}),
encoding="utf-8",
)
command = [sys.executable, str(ROOT / "scripts" / "restore_large_files.py")]
command = [sys.executable, str(REPO_ROOT / "scripts" / "restore_large_files.py")]
proc = subprocess.run(
[*command, "--cache", "cache"],
capture_output=True, text=True, cwd=str(root), timeout=120,
@@ -533,14 +533,14 @@ class PreservedBytesAreNeverNormalised(unittest.TestCase):
out = subprocess.run(
["git", "check-attr", "text", "--", path],
capture_output=True, text=True, cwd=ROOT,
capture_output=True, text=True, cwd=REPO_ROOT,
check=False,
).stdout
return out.rsplit(":", 1)[-1].strip()
def test_gitattributes_exists(self):
self.assertTrue(
(ROOT / ".gitattributes").is_file(),
(REPO_ROOT / ".gitattributes").is_file(),
"without it git guesses, and guesses wrong on Windows",
)
@@ -642,7 +642,7 @@ class AMissingDependencyStopsTheBuild(unittest.TestCase):
proc = subprocess.run(
[sys.executable, "-S", "scripts/generate_db.py", "--force",
"--bios-dir", "bios", "--output", str(output)],
cwd=ROOT, capture_output=True, text=True, timeout=600, check=False,
cwd=REPO_ROOT, capture_output=True, text=True, timeout=600, check=False,
)
self.assertNotEqual(proc.returncode, 0, proc.stdout)
self.assertIn("PyYAML required", proc.stderr)
@@ -655,7 +655,7 @@ class AMissingDependencyStopsTheBuild(unittest.TestCase):
with self.subTest(command=command[0]):
proc = subprocess.run(
[sys.executable, "-S", *command],
cwd=ROOT, capture_output=True, text=True, timeout=120, check=False,
cwd=REPO_ROOT, capture_output=True, text=True, timeout=120, check=False,
)
self.assertEqual(proc.returncode, 1, proc.stdout)
self.assertEqual(
@@ -664,10 +664,10 @@ class AMissingDependencyStopsTheBuild(unittest.TestCase):
def test_no_script_swallows_an_import_error(self):
offenders = []
for path in sorted((ROOT / "scripts").rglob("*.py")):
for path in sorted((REPO_ROOT / "scripts").rglob("*.py")):
tree = ast.parse(path.read_text(encoding="utf-8"))
offenders.extend(
f"{path.relative_to(ROOT)}:{node.lineno}"
f"{path.relative_to(REPO_ROOT)}:{node.lineno}"
for node in ast.walk(tree)
if (
isinstance(node, ast.ExceptHandler)
@@ -685,7 +685,7 @@ class TestsCleanUpTheirScratch(unittest.TestCase):
def test_every_class_that_makes_a_directory_removes_it(self):
offenders = []
for path in sorted((ROOT / "tests").glob("test_*.py")):
for path in sorted((REPO_ROOT / "tests").glob("test_*.py")):
source = path.read_text(encoding="utf-8")
for node in ast.parse(source).body:
if not isinstance(node, ast.ClassDef):
@@ -710,7 +710,7 @@ class DeclaredDependenciesMatchTheDocumentedWorkflows(unittest.TestCase):
def _pyproject() -> dict:
import tomllib
with (ROOT / "pyproject.toml").open("rb") as handle:
with (REPO_ROOT / "pyproject.toml").open("rb") as handle:
return tomllib.load(handle)
def test_every_package_ci_installs_is_declared(self):
@@ -723,7 +723,7 @@ class DeclaredDependenciesMatchTheDocumentedWorkflows(unittest.TestCase):
declared |= set(self._pyproject()["project"]["dependencies"])
installed: set[str] = set()
for workflow in ("validate.yml", "deploy-site.yml"):
body = (ROOT / ".github" / "workflows" / workflow).read_text(
body = (REPO_ROOT / ".github" / "workflows" / workflow).read_text(
encoding="utf-8"
)
for line in body.splitlines():
@@ -749,12 +749,12 @@ class TheAnnotationsAreChecked(unittest.TestCase):
type error, and CI runs mypy bare, so any new one fails."""
def test_ci_runs_mypy_without_a_baseline(self):
body = (ROOT / ".github" / "workflows" / "validate.yml").read_text(
body = (REPO_ROOT / ".github" / "workflows" / "validate.yml").read_text(
encoding="utf-8"
)
self.assertRegex(body, r"(?m)^\s+mypy$")
self.assertNotIn("mypy-baseline", body)
self.assertFalse((ROOT / "mypy-baseline.txt").exists())
self.assertFalse((REPO_ROOT / "mypy-baseline.txt").exists())
def test_the_code_reports_no_type_error(self):
try:
@@ -763,7 +763,7 @@ class TheAnnotationsAreChecked(unittest.TestCase):
self.skipTest("mypy is not installed (pip install -e '.[dev]')")
report = subprocess.run(
[sys.executable, "-m", "mypy"],
cwd=ROOT, capture_output=True, text=True, check=False,
cwd=REPO_ROOT, capture_output=True, text=True, check=False,
)
self.assertEqual(report.returncode, 0, report.stdout[-4000:])
@@ -789,13 +789,13 @@ class TheProjectInstallsWithPip(unittest.TestCase):
"dist.set_defaults()\n"
"print(sorted(dist.packages or []), sorted(dist.py_modules or []))\n"
)
done = subprocess.run([sys.executable, "-c", program], cwd=ROOT,
done = subprocess.run([sys.executable, "-c", program], cwd=REPO_ROOT,
capture_output=True, text=True, check=False)
self.assertEqual(done.returncode, 0, done.stderr[-2000:])
self.assertEqual(done.stdout.strip(), "[] []")
import tomllib
with (ROOT / "pyproject.toml").open("rb") as handle:
with (REPO_ROOT / "pyproject.toml").open("rb") as handle:
build = tomllib.load(handle)["build-system"]
self.assertEqual(build["build-backend"], "setuptools.build_meta")
@@ -809,7 +809,7 @@ class TestEntryPointsRunEveryClass(unittest.TestCase):
"""
def test_no_module_calls_main_before_its_last_class(self):
for path in sorted((ROOT / "tests").glob("test_*.py")):
for path in sorted((REPO_ROOT / "tests").glob("test_*.py")):
lines = path.read_text(encoding="utf-8").splitlines()
# Column zero only: the same text appears inside this very test as
# a string literal, and a substring search matched that instead.
@@ -845,7 +845,7 @@ class ScriptsImportThreeWays(unittest.TestCase):
return subprocess.run(
[sys.executable, *args],
capture_output=True, text=True, cwd=str(ROOT), timeout=300,
capture_output=True, text=True, cwd=str(REPO_ROOT), timeout=300,
check=False,
)
@@ -873,7 +873,7 @@ class NoHandlerSwallowsEverything(unittest.TestCase):
import ast
offenders = []
for path in [*sorted((ROOT / "scripts").rglob("*.py")), ROOT / "install.py"]:
for path in [*sorted((REPO_ROOT / "scripts").rglob("*.py")), REPO_ROOT / "install.py"]:
tree = ast.parse(path.read_text(encoding="utf-8"))
for node in ast.walk(tree):
if not isinstance(node, ast.ExceptHandler):
@@ -883,7 +883,7 @@ class NoHandlerSwallowsEverything(unittest.TestCase):
and node.type.id in ("Exception", "BaseException")
)
if broad and all(isinstance(stmt, ast.Pass) for stmt in node.body):
offenders.append(f"{path.relative_to(ROOT)}:{node.lineno}")
offenders.append(f"{path.relative_to(REPO_ROOT)}:{node.lineno}")
self.assertEqual(offenders, [])
@@ -913,7 +913,7 @@ class ModuleConstantsDeclaredOnce(unittest.TestCase):
def test_no_module_assigns_the_same_constant_twice(self):
offenders = {}
for path in sorted(ROOT.glob("scripts/**/*.py")) + [ROOT / "install.py"]:
for path in sorted(REPO_ROOT.glob("scripts/**/*.py")) + [REPO_ROOT / "install.py"]:
again = self._redeclared(path)
if again:
offenders[path.name] = again
@@ -940,9 +940,9 @@ class OnlyTheSchemaValidatorNeedsJsonschema(unittest.TestCase):
def test_no_other_module_imports_it(self):
offenders = [
str(path.relative_to(ROOT))
for path in sorted(ROOT.glob("scripts/**/*.py")) + [ROOT / "install.py"]
if path.parent != ROOT / "scripts" / "schemas"
str(path.relative_to(REPO_ROOT))
for path in sorted(REPO_ROOT.glob("scripts/**/*.py")) + [REPO_ROOT / "install.py"]
if path.parent != REPO_ROOT / "scripts" / "schemas"
and self._imports_jsonschema(path.read_text())
]
self.assertEqual(offenders, [])
@@ -973,7 +973,7 @@ class NoSourceWarnsWhenCompiled(unittest.TestCase):
def test_every_script_compiles_clean(self):
import warnings
sources = [ROOT / "install.py", *sorted((ROOT / "scripts").rglob("*.py"))]
sources = [REPO_ROOT / "install.py", *sorted((REPO_ROOT / "scripts").rglob("*.py"))]
for path in sources:
with self.subTest(path=path.name), warnings.catch_warnings():
warnings.simplefilter("error", SyntaxWarning)
@@ -994,7 +994,7 @@ class TestsRunOffline(unittest.TestCase):
listed = subprocess.run(
["git", "grep", "-n", "unittest discover", "--", ":!tests"],
capture_output=True, text=True, cwd=ROOT, check=False,
capture_output=True, text=True, cwd=REPO_ROOT, check=False,
).stdout.splitlines()
self.assertTrue(listed)
self.assertEqual([line for line in listed if "-t ." not in line], [])
@@ -1008,7 +1008,7 @@ class MessagesSeparateWithAColon(unittest.TestCase):
def test_no_message_uses_a_dash_separator(self):
found = []
for path in [ROOT / "install.py", *sorted((ROOT / "scripts").rglob("*.py"))]:
for path in [REPO_ROOT / "install.py", *sorted((REPO_ROOT / "scripts").rglob("*.py"))]:
for number, line in enumerate(path.read_text().splitlines(), 1):
if self.PATTERN.search(line):
found.append(f"{path.name}:{number}: {line.strip()}")
@@ -1023,14 +1023,14 @@ class TheIssueFormListsEveryPlatform(unittest.TestCase):
from scripts.model.platforms import load_platform_config
form = yaml.safe_load(
(ROOT / ".github" / "ISSUE_TEMPLATE" / "missing-bios.yml").read_text()
(REPO_ROOT / ".github" / "ISSUE_TEMPLATE" / "missing-bios.yml").read_text()
)
options = next(
item["attributes"]["options"] for item in form["body"]
if item.get("id") == "platform"
)
for name in list_registered_platforms(str(ROOT / "platforms")):
display = load_platform_config(name, str(ROOT / "platforms"))["platform"]
for name in list_registered_platforms(str(REPO_ROOT / "platforms")):
display = load_platform_config(name, str(REPO_ROOT / "platforms"))["platform"]
self.assertIn(display, options)
@@ -1040,7 +1040,7 @@ class TheTestJobHasTheDataTrees(unittest.TestCase):
def test_the_trees_are_fetched_before_the_suite(self):
steps = yaml.safe_load(
(ROOT / ".github" / "workflows" / "validate.yml").read_text()
(REPO_ROOT / ".github" / "workflows" / "validate.yml").read_text()
)["jobs"]["run-tests"]["steps"]
runs = [step.get("run", "") for step in steps]
fetch = next(i for i, run in enumerate(runs) if "refresh_data_dirs.py" in run)
@@ -1055,7 +1055,7 @@ class GeneratedArtifactsMeetTheirSchemas(unittest.TestCase):
@unittest.skipUnless(HAS_JSONSCHEMA, "needs jsonschema")
def test_the_full_schema_check_passes(self):
proc = subprocess.run(
[sys.executable, "scripts/validate_schemas.py"], cwd=ROOT,
[sys.executable, "scripts/validate_schemas.py"], cwd=REPO_ROOT,
capture_output=True, text=True, timeout=600,
check=False,
)
@@ -1088,12 +1088,12 @@ class SignaturesCarryTheirTypes(unittest.TestCase):
return found
def test_the_count_only_goes_down(self):
paths = [ROOT / "install.py", *sorted((ROOT / "scripts").rglob("*.py"))]
paths = [REPO_ROOT / "install.py", *sorted((REPO_ROOT / "scripts").rglob("*.py"))]
missing = [m for path in paths for m in self._missing(path)]
self.assertLessEqual(len(missing), self.CEILING, missing[:20])
for name in self.COMPLETE:
with self.subTest(module=name):
self.assertEqual(self._missing(ROOT / "scripts" / name), [])
self.assertEqual(self._missing(REPO_ROOT / "scripts" / name), [])
class TheApiSchemaHoldsTheFieldsItPromises(unittest.TestCase):
@@ -1106,7 +1106,7 @@ class TheApiSchemaHoldsTheFieldsItPromises(unittest.TestCase):
import jsonschema
except ImportError:
self.skipTest("jsonschema is tooling only")
schema = json.loads((ROOT / "schemas" / "site-api-envelope.schema.json").read_text())
schema = json.loads((REPO_ROOT / "schemas" / "site-api-envelope.schema.json").read_text())
envelope = {"schema_version": 1, "generated_at": "2026-10-20T00:00:00Z",
"kind": "file-locations", "count": 1,
"items": [{"sha1": "a" * 40, "url": "https://x/y"}]}
@@ -1132,13 +1132,13 @@ class CommentsSayWhy(unittest.TestCase):
"""Three scripts were read, and 22 labels stood in 13 others."""
tracked = subprocess.run(
["git", "ls-files", "--", "scripts/*.py", "scripts/**/*.py", "install.py"],
cwd=ROOT, capture_output=True, text=True, check=True,
cwd=REPO_ROOT, capture_output=True, text=True, check=True,
).stdout.split()
self.assertIn("install.py", tracked)
self.assertIn("scripts/scraper/mame_parser.py", tracked)
found = []
for name in sorted(set(tracked)):
lines = (ROOT / name).read_text(encoding="utf-8").splitlines()
lines = (REPO_ROOT / name).read_text(encoding="utf-8").splitlines()
for index, line in enumerate(lines):
if not self.LABEL.match(line) or self.REASON.search(line):
continue
@@ -1177,7 +1177,7 @@ class TupleAnnotationsMatchTheirReturns(unittest.TestCase):
stack.extend(ast.iter_child_nodes(node))
def test_a_fixed_tuple_annotation_counts_its_returned_values(self):
sources = sorted((ROOT / "scripts").rglob("*.py")) + [ROOT / "install.py"]
sources = sorted((REPO_ROOT / "scripts").rglob("*.py")) + [REPO_ROOT / "install.py"]
mismatched = []
for path in sources:
for fn in ast.walk(ast.parse(path.read_text(encoding="utf-8"))):
@@ -1196,7 +1196,7 @@ class TupleAnnotationsMatchTheirReturns(unittest.TestCase):
and not any(isinstance(e, ast.Starred) for e in value.elts)
and len(value.elts) != len(declared)):
mismatched.append(
f"{path.relative_to(ROOT)}:{ret.lineno} "
f"{path.relative_to(REPO_ROOT)}:{ret.lineno} "
f"{len(value.elts)} returned, {len(declared)} declared"
)
self.assertEqual(mismatched, [])
+10 -10
View File
@@ -20,7 +20,7 @@ from unittest import mock
from packs import verdicts
from scripts.resolve.localfile import resolve_local_file
from scripts.core.ziptools import safe_extract_zip
from tests.auditsupport import ROOT
from tests import REPO_ROOT
class AutoFetchReadsListsAndPlacesWithoutClobbering(unittest.TestCase):
@@ -348,14 +348,14 @@ class AnotherEmulatorsTreeProvesNothing(unittest.TestCase):
from scripts.model.platforms import load_platform_config
from scripts.model.targets import load_target_config
if not (ROOT / "database.json").exists():
if not (REPO_ROOT / "database.json").exists():
self.skipTest("database.json is not generated")
db = load_database(str(ROOT / "database.json"))
config = load_platform_config("retroarch", str(ROOT / "platforms"))
profiles = load_emulator_profiles(str(ROOT / "emulators"))
cores = set(load_target_config("retroarch", "x86_64", str(ROOT / "platforms")))
db = load_database(str(REPO_ROOT / "database.json"))
config = load_platform_config("retroarch", str(REPO_ROOT / "platforms"))
profiles = load_emulator_profiles(str(REPO_ROOT / "emulators"))
cores = set(load_target_config("retroarch", "x86_64", str(REPO_ROOT / "platforms")))
overrides = slots.pack_overrides(
config, profiles, db, None, load_data_dir_registry(str(ROOT / "platforms")),
config, profiles, db, None, load_data_dir_registry(str(REPO_ROOT / "platforms")),
target_cores=cores,
)
self.assertFalse([d for d, p in overrides.items() if "/armsx2/" in p])
@@ -614,9 +614,9 @@ class HashMergeBackupsAreNotSources(unittest.TestCase):
def test_the_backup_suffix_is_written_once(self):
offenders = [
str(path.relative_to(ROOT))
for path in sorted(ROOT.glob("scripts/**/*.py"))
if path.relative_to(ROOT).as_posix() != "scripts/model/profiles.py"
str(path.relative_to(REPO_ROOT))
for path in sorted(REPO_ROOT.glob("scripts/**/*.py"))
if path.relative_to(REPO_ROOT).as_posix() != "scripts/model/profiles.py"
and '".old.yml"' in path.read_text()
]
self.assertEqual(offenders, [])
+5 -5
View File
@@ -11,7 +11,7 @@ import sys
import unittest
from pathlib import Path
from unittest import mock
from tests.auditsupport import ROOT
from tests import REPO_ROOT
class TheSiteCountsSlotsNotVersions(unittest.TestCase):
@@ -230,7 +230,7 @@ class GapsPageCountsOneWay(unittest.TestCase):
from scripts.sitegen.gaps import _verify_tally
from model.platforms import load_platform_config
config = load_platform_config("amberelec", str(ROOT / "platforms"))
config = load_platform_config("amberelec", str(REPO_ROOT / "platforms"))
details, wanted = [], []
for system, data in (config.get("systems") or {}).items():
for entry in data.get("files") or []:
@@ -488,7 +488,7 @@ class SitemapDatesComeFromThePage(unittest.TestCase):
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")
config = (REPO_ROOT / "website" / "astro.config.mjs").read_text(encoding="utf-8")
self.assertIn("lastmod.json", config)
self.assertIn("serialize(item)", config)
@@ -558,7 +558,7 @@ class TheCollectionShipsADat(unittest.TestCase):
converter from files.csv."""
def test_round_trip_through_the_logiqx_parser(self):
sys.path.insert(0, str(ROOT / "scripts" / "scraper"))
sys.path.insert(0, str(REPO_ROOT / "scripts" / "scraper"))
from logiqx_parser import parse_logiqx
from scripts.sitegen.structured import collection_dat
@@ -581,7 +581,7 @@ class TheCollectionShipsADat(unittest.TestCase):
"""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"))
sys.path.insert(0, str(REPO_ROOT / "scripts" / "scraper"))
from logiqx_parser import parse_logiqx
from scripts.sitegen.platformfiles import platform_data_links
from scripts.sitegen.structured import platform_dat
+1 -2
View File
@@ -9,8 +9,7 @@ from tests.sources import script_source
import re
import unittest
from tests.test_prose_style import _python_prose, _sentence_case
from tests.docpagessupport import PUBLISHED, ROOT, WIKI
from tests.docpagessupport import PUBLISHED, ROOT, WIKI, _python_prose, _sentence_case
class PublishedHeadings(unittest.TestCase):
+74 -10
View File
@@ -16,7 +16,9 @@ import sys
import unittest
from pathlib import Path
from tests.docpagessupport import PUBLISHED, ROOT, WIKI, _page, _registry, _schema, _section
from tests.docpagessupport import (
MARKETING_WORDS, PUBLISHED, ROOT, WIKI, _page, _registry, _schema, _section,
)
class TestSkeletonReadsTheResultShape(unittest.TestCase):
@@ -181,17 +183,20 @@ class ScratchFilesGoToRepoTmp(unittest.TestCase):
CONTRIBUTOR_PAGES = (
"profiling.md", "adding-a-platform.md", "adding-a-scraper.md", "architecture.md",
"verification-modes.md", "reference-terms.md", "glossary.md", "legal.md", "index.md",
"what-are-bios-files.md", "community-tools.md",
"what-are-bios-files.md", "community-tools.md", "testing-guide.md", "tools.md",
)
REPO_DIRS = (
"scripts/", "platforms/", "emulators/", "schemas/", "tests/", "wiki/", "install/",
"provenance/", "recipes/", "exports/", "measurements/", "website/", "automation/",
"ports/", "docs_assets/", "docs/",
"ports/", "docs_assets/", "docs/", "campaign/",
)
PLACEHOLDER = re.compile(r"[<>*{}]|myplatform|\bNAME\b|\.\.\.")
# Folders the site build writes, ignored by git and absent from a fresh clone.
BUILT = ("website/src/content/docs", "website/dist")
def _schema_keys(schema: object, keys: set[str]) -> set[str]:
if isinstance(schema, dict):
@@ -220,7 +225,7 @@ def missing_repo_paths(text: str) -> list[str]:
continue
path = re.sub(r":[\d,-]+$", "", token).rstrip(".,")
if path.startswith(REPO_DIRS) and not PLACEHOLDER.search(path):
if not (ROOT / path).exists():
if not (ROOT / path).exists() and not path.startswith(BUILT):
missing.append(path)
elif re.fullmatch(r"test_\w+\.py", path) and not (ROOT / "tests" / path).exists():
missing.append(path)
@@ -236,10 +241,14 @@ def _script_source(line: str) -> tuple[str, str] | None:
match = re.search(r"python3? -m (scripts\.scraper\.[\w.]+)", line)
if match:
module = match.group(1)
path = ROOT / (module.replace(".", "/") + ".py")
source = path.read_text(encoding="utf-8") if path.is_file() else ""
path = ROOT / module.replace(".", "/")
# A package runs its __main__ and reads its options across its modules.
files = sorted(path.glob("*.py")) if path.is_dir() else [path.with_suffix(".py")]
source = "".join(f.read_text(encoding="utf-8") for f in files if f.is_file())
if "scraper_cli" in source or "myplatform" in module:
source += (ROOT / "scripts/scraper/base_scraper.py").read_text(encoding="utf-8")
if "target_cli" in source:
source += (ROOT / "scripts/scraper/targets/__init__.py").read_text(encoding="utf-8")
return module, source
return None
@@ -258,7 +267,9 @@ def unknown_commands(text: str) -> list[str]:
wrong.extend(
f"{name} {option}"
for option in re.findall(r"(?<![\w-])(--[a-z][a-z0-9-]*)", command)
if f'"{option}"' not in source and option not in declared_options(source)
# argparse adds --help to every parser.
if option != "--help"
and f'"{option}"' not in source and option not in declared_options(source)
)
return sorted(set(wrong))
@@ -611,10 +622,8 @@ class LandingAChangeNamesTheCommitRules(unittest.TestCase):
section = self._landing()
words = re.search(r"\\b\((.*?)\)", commitrules.REFUSED_WORDS.pattern).group(1)
from tests.test_prose_style import NoMarketingVocabulary
for word in words.replace("|", " ").split():
if NoMarketingVocabulary.WORDS.search(word):
if MARKETING_WORDS.search(word):
# Named by "the marketing vocabulary above": spelled out,
# the page would fail that test.
continue
@@ -648,5 +657,60 @@ class LandingAChangeNamesTheCommitRules(unittest.TestCase):
self.assertEqual(accepted.returncode, 0, accepted.stderr)
# Families of test modules: a family is one subject split by size, so it sits
# on one row of the guide's table.
TEST_FAMILIES = ("test_site_", "test_install_", "test_tui_", "test_profile_sync_",
"test_launchers_", "test_e2e_", "test_audit_")
# A skip that names repository data: the test reads the working tree.
WORKING_TREE_SKIP = re.compile(
r"(?:skipTest|SkipTest|skipUnless|skipIf)\(.*(?:database\.json|bios/|romset|no pack found|dist/)"
)
class TheTestingGuideNamesEveryModule(unittest.TestCase):
"""The guide described 18 modules of 144, and a contributor touching
slots.py or the downloader found no module named for it. Later one row
held 113 modules, the site, the doc pages, profile_sync and the launcher
extractors together, and a family was split across rows."""
TESTS = ROOT / "tests"
def _rows(self) -> list[list[str]]:
section = _section(_page("testing-guide.md"), "Modules at a glance")
return [re.findall(r"`(test_\w+)`", line.split("|")[3])
for line in section.splitlines()
if line.startswith("| ") and line.count("|") >= 4 and "`test_" in line]
def test_each_module_is_on_one_row_once(self):
named = [name for row in self._rows() for name in row]
modules = sorted(path.stem for path in self.TESTS.glob("test_*.py"))
self.assertEqual(sorted(set(modules) - set(named)), [], "not in the table")
self.assertEqual(sorted(set(named) - set(modules)), [], "no such module")
self.assertEqual(sorted({n for n in named if named.count(n) > 1}), [], "named twice")
def test_each_family_sits_on_one_row(self):
rows = self._rows()
for prefix in TEST_FAMILIES:
with self.subTest(family=prefix):
holding = [i for i, row in enumerate(rows) if any(n.startswith(prefix) for n in row)]
self.assertEqual(len(holding), 1, f"{prefix} on rows {holding}")
def test_every_helper_module_is_in_the_helpers_table(self):
section = _section(_page("testing-guide.md"), "Shared helpers")
named = set(re.findall(r"^\| `(\w+)` \|", section, re.M))
helpers = {path.stem for path in self.TESTS.glob("*.py") if not path.stem.startswith("test_")}
helpers |= {path.parent.name for path in self.TESTS.glob("*/__init__.py")}
self.assertEqual(sorted(helpers - named), [], "not in the table")
self.assertEqual(sorted(named - helpers), [], "no such module")
def test_every_module_reading_the_working_tree_is_listed(self):
section = _section(_page("testing-guide.md"), "Tests that read the working tree")
reading = sorted(path.stem for path in self.TESTS.glob("test_*.py")
if WORKING_TREE_SKIP.search(path.read_text(encoding="utf-8")))
self.assertIn("test_archive_build", reading)
self.assertEqual([name for name in reading if f"`{name}`" not in section], [])
if __name__ == "__main__":
unittest.main()
@@ -1,11 +1,11 @@
"""The PortMaster port: its archive, its event reader and its fallback screens.
"""The PortMaster port: its dialog commands, its event reader and its fallback screens.
The screens are driven here with PortMasterDialog's functions replaced by
stubs that record each command and answer from a script, and with a fake
install.py that writes canned --events streams. What a device adds (pugwash
drawing, the pad, mount, the network) is not exercised. The full-screen
route of the port is in test_handheld_portmaster, the other launchers in
test_handheld_frontends.
test_handheld_frontends, the archives in test_handheld_scripts.
"""
from __future__ import annotations
@@ -22,11 +22,9 @@ import shutil
import subprocess
import sys
import unittest
import zipfile
from pathlib import Path
from installer_build import port as installer_build_port
from installer_build.pins import pinned_sha256
REPO_ROOT = Path(__file__).resolve().parent.parent
PORT = REPO_ROOT / "ports" / "RetroBIOS"
@@ -42,7 +40,7 @@ _spec.loader.exec_module(rbevents)
SCRIPTS = [PORT / "RetroBIOS.sh", PORT / "retrobios" / "screens.txt"]
class EveryScriptParses(unittest.TestCase):
class DialogCommands(unittest.TestCase):
def test_only_dialog_functions_the_oldest_releases_have(self):
"""PortMaster 2024.02.26 and 8.5.23 define these in PortMasterDialog.txt,
and have no funcs.txt: pm_message and the rest would be undefined."""
@@ -69,43 +67,6 @@ class EveryScriptParses(unittest.TestCase):
self.assertEqual(set(inits), {"no-check"})
class ThePortArchive(unittest.TestCase):
def setUp(self):
self.out = scratch_dir(self)
def _build(self, name: str = "RetroBIOS.zip") -> Path:
return installer_build_port.build_port(self.out / name)
def test_layout_portmaster_installs(self):
"""One launch script at the top, one folder holding port.json: what
harbourmaster's captain.check_port accepts without a warning."""
with zipfile.ZipFile(self._build()) as zf:
names = zf.namelist()
port = json.loads(zf.read("retrobios/port.json"))
mode = zf.getinfo("RetroBIOS.sh").external_attr >> 16
self.assertEqual(names, sorted(names))
self.assertEqual([n for n in names if "/" not in n], ["RetroBIOS.sh"])
self.assertEqual({n.split("/")[0] for n in names if "/" in n}, {"retrobios"})
self.assertEqual([n for n in names if n.endswith(".sh")], ["RetroBIOS.sh"])
for member in ("retrobios/install.py", "retrobios/rbevents.py",
"retrobios/screens.txt", "retrobios/tui.txt",
"retrobios/retrobios.gptk", "retrobios/gameinfo.xml",
"retrobios/retrobios.md", "retrobios/licenses/LICENSE-retrobios.txt"):
self.assertIn(member, names)
self.assertEqual(port["version"], 4)
self.assertEqual(port["name"], "retrobios.zip")
self.assertEqual(port["items"], ["RetroBIOS.sh", "retrobios"])
self.assertEqual(port["attr"]["genres"], ["other"])
self.assertTrue(mode & 0o111, "the launch script is executable")
def test_bundled_installer_is_the_pinned_one(self):
with zipfile.ZipFile(self._build()) as zf:
bundled = hashlib.sha256(zf.read("retrobios/install.py")).hexdigest()
self.assertEqual(bundled, pinned_sha256("install.sh"))
install_sh = (REPO_ROOT / "install.sh").read_text(encoding="utf-8")
self.assertIn(f'DEFAULT_INSTALL_SHA256="{bundled}"', install_sh)
class LauncherIndex(unittest.TestCase):
"""install/launchers/index.json, which --add-app reads, lists the members of
the archives built from the same tree, each with its size and hash."""
+14
View File
@@ -208,6 +208,20 @@ class TheArchives(unittest.TestCase):
self.assertEqual(top, [])
self.assertIn("RetroBIOS/retrobios.gptk", names)
def test_the_port_describes_itself_to_portmaster(self):
"""port.json and the files harbourmaster's captain.check_port and the
PortMaster listing read, beside the launch script."""
name = port.PORT_ZIP
with zipfile.ZipFile(port.build_archive(name, self.out / name)) as zf:
names = zf.namelist()
described = json.loads(zf.read("retrobios/port.json"))
for member in ("retrobios/screens.txt", "retrobios/gameinfo.xml", "retrobios/retrobios.md"):
self.assertIn(member, names)
self.assertEqual(described["version"], 4)
self.assertEqual(described["name"], "retrobios.zip")
self.assertEqual(described["items"], ["RetroBIOS.sh", "retrobios"])
self.assertEqual(described["attr"]["genres"], ["other"])
def test_the_muos_icon_is_the_glyph_its_header_names(self):
"""muOS reads glyph/<ICON>.png in the application's folder, and the
muxapp named an icon it did not carry."""
+1 -79
View File
@@ -14,9 +14,7 @@ from tests import scratch_dir
import hashlib
import io
import json
import shutil
import stat
import subprocess
import sys
import unittest
import zipfile
@@ -24,92 +22,16 @@ from pathlib import Path
from unittest import mock
import install
from tests.test_install_selection import FakeRepository
from tests.installsupport import INDEX, AppRepository, FakeRepository, make_card
REPO_ROOT = Path(__file__).resolve().parent.parent
INDEX = REPO_ROOT / "install" / "launchers" / "index.json"
def make_card(root: Path, system: str) -> Path:
"""A card as each system leaves it, and the BIOS folder on it."""
bios = _card_files(root, system)
bios.mkdir(parents=True, exist_ok=True)
return bios
def _card_files(root: Path, system: str) -> Path:
root.mkdir(parents=True, exist_ok=True)
if system == "muOS":
(root / "MUOS" / "bios").mkdir(parents=True)
return root / "MUOS" / "bios"
if system == "KNULLI":
(root / "system").mkdir()
(root / "system" / "batocera.conf").write_text("system.hostname=KNULLI\n")
return root / "bios"
if system == "ROCKNIX":
(root / ".config" / "system" / "configs").mkdir(parents=True)
(root / ".config" / "system" / "configs" / "system.cfg").write_text(
"root.password=rocknix\n")
return root / "roms" / "bios"
if system == "Onion":
(root / ".tmp_update" / "onionVersion").mkdir(parents=True)
(root / ".tmp_update" / "onionVersion" / "version.txt").write_text("4.3.1\n")
return root / "BIOS"
if system == "spruceOS":
(root / "spruce").mkdir()
return root / "BIOS"
if system == "MinUI":
(root / ".system").mkdir()
(root / ".system" / "version.txt").write_text("MinUI-20250101\n")
return root
raise ValueError(system)
# The file list each card's system gets.
CARD_PLATFORMS = {"muOS": "retroarch", "KNULLI": "knulli", "ROCKNIX": "rocknix",
"Onion": "retroarch", "spruceOS": "retroarch", "MinUI": "minui"}
class AppRepository(FakeRepository):
"""The fake repository with the launcher list and every file it names,
and the BIOS lists of the systems whose cards are tried."""
def __enter__(self) -> AppRepository:
super().__enter__()
index = json.loads(INDEX.read_text(encoding="utf-8"))
(self.root / "install" / "launchers").mkdir()
(self.root / "install" / "launchers" / "index.json").write_text(json.dumps(index))
for launcher in index["launchers"].values():
for entry in launcher.get("files", launcher.get("members", [])):
if "repo_path" in entry:
target = self.root / entry["repo_path"]
target.parent.mkdir(parents=True, exist_ok=True)
shutil.copyfile(REPO_ROOT / entry["repo_path"], target)
base = json.loads((self.root / "install" / "retroarch.json").read_text())
for plat in ("knulli", "rocknix", "minui"):
(self.root / "install" / f"{plat}.json").write_text(
json.dumps({**base, "platform": plat}))
return self
def card(self, system: str) -> tuple[Path, Path]:
root = self.root / "cards" / system
return root, make_card(root, system)
def tamper(self, repo_path: str) -> None:
"""One byte changed, the size kept: only the hash tells."""
path = self.root / repo_path
data = bytearray(path.read_bytes())
data[-1] ^= 0x20
path.write_bytes(bytes(data))
def cli(self, *options: str, env: dict | None = None) -> subprocess.CompletedProcess:
return subprocess.run(
[sys.executable, str(REPO_ROOT / "install.py"), *options],
env={**self.env(), **(env or {})}, capture_output=True, text=True,
timeout=120, check=False, stdin=subprocess.DEVNULL)
class Placement(unittest.TestCase):
def test_each_card_and_where_its_app_goes(self):
root = scratch_dir(self)
+1 -1
View File
@@ -23,7 +23,7 @@ from pathlib import Path
from unittest import mock
import install
from tests.test_install_selection import FakeRepository
from tests.installsupport import FakeRepository
REPO_ROOT = Path(__file__).resolve().parent.parent
+2 -2
View File
@@ -239,7 +239,7 @@ class DataDirectoriesAreInstalled(unittest.TestCase):
self.assertEqual(sorted(p.name for p in (bios / "dolphin-emu").iterdir()), ["Sys"])
def test_the_run_ends_on_the_archive_bytes_too(self):
from tests.test_install_selection import FakeRepository
from tests.installsupport import FakeRepository
member = os.urandom(300_000)
with FakeRepository() as repo:
@@ -262,7 +262,7 @@ class DataDirectoriesAreInstalled(unittest.TestCase):
def test_the_plan_announces_the_archive_not_the_tree(self):
"""yaps2's tarball is 21.2 MB for a 6.5 MB tree, Cemu's 21.4 MB for
9.9 KB: the plan announced the tree, and the run downloaded far more."""
from tests.test_install_selection import FakeRepository
from tests.installsupport import FakeRepository
member = b"profile"
archive_size = 21_360_579
+1 -1
View File
@@ -28,7 +28,7 @@ from pathlib import Path
from unittest import mock
import install
from tests.test_install_selection import FakeRepository
from tests.installsupport import FakeRepository
REPO_ROOT = Path(__file__).resolve().parent.parent
+1 -1
View File
@@ -18,7 +18,7 @@ from pathlib import Path
from unittest import mock
import install
from tests.test_install_selection import FakeRepository
from tests.installsupport import FakeRepository
REPO_ROOT = Path(__file__).resolve().parent.parent
+2 -3
View File
@@ -31,10 +31,9 @@ from pathlib import Path
from unittest import mock
import install
from tests.test_install_offline import (
EXTRA, GBA, JP, PAYLOAD, US, Scratch, _entry, _offline_env,
from tests.installsupport import (
EXTRA, GBA, JP, PAYLOAD, US, FakeRepository, Scratch, _entry, _offline_env,
)
from tests.test_install_selection import FakeRepository
REPO_ROOT = Path(__file__).resolve().parent.parent
+15 -287
View File
@@ -12,7 +12,6 @@ import tests
from tests import loopback
import contextlib
import gzip
import hashlib
import io
import json
@@ -23,301 +22,30 @@ import sys
import tempfile
import unittest
import urllib.error
import zipfile
from pathlib import Path
from unittest import mock
import install
from tests.gamessupport import (
Card,
FILES,
MD_EU,
MD_JP,
MD_ZIPPED,
SETUP,
SYSTEMS,
gc_iso,
manifest,
mcd_iso,
md_rom,
ps_iso,
write_index,
)
REPO_ROOT = Path(__file__).resolve().parent.parent
MD_EU = b"md europe game " * 64
MD_JP = b"md japan game " * 64
MD_ZIPPED = b"md zipped usa game " * 64
GC_HEADER = 0x458
# Every file the fixture list carries: dest -> (size, regions, cores, systems).
FILES = {
"scph5500.bin": (512, ["japan"], None, ["sony-playstation"]),
"scph5501.bin": (512, ["north-america"], None, ["sony-playstation"]),
"scph5502.bin": (512, ["europe"], None, ["sony-playstation"]),
"bios_CD_E.bin": (128, ["europe"], None, ["sega-megacd"]),
"bios_CD_U.bin": (128, ["north-america"], None, ["sega-megacd"]),
"bios_CD_J.bin": (128, ["japan"], None, ["sega-megacd"]),
"cd_extra.bin": (16, None, ["picodrive"], None),
"md_eu.bin": (64, ["europe"], None, ["sega-megadrive"]),
"md_us.bin": (64, ["north-america"], None, ["sega-megadrive"]),
"md_jp.bin": (64, ["japan"], None, ["sega-megadrive"]),
"md_tmss.bin": (32, None, None, ["sega-megadrive"]),
"dolphin/GC/USA/IPL.bin": (256, ["north-america"], ["dolphin"], None),
"dolphin/GC/EUR/IPL.bin": (256, ["europe"], ["dolphin"], None),
"dolphin/GC/JAP/IPL.bin": (256, ["japan"], ["dolphin"], None),
"neogeo.zip": (300, None, None, ["snk-neogeo"]),
"fbneo/neogeo.zip": (300, None, ["fbneo"], None),
"fbneo/pgm.zip": (200, None, ["fbneo"], None),
"fbneo/msx.zip": (150, None, ["fbneo"], None),
"fbneo/samples/big.zip": (9000, None, ["fbneo"], None),
"gba_bios.bin": (100, None, None, ["nintendo-gba"]),
}
# The fallback sets: key -> (files, optional).
SETS = {
"sony-playstation|beetle_psx": (["scph5500.bin", "scph5501.bin", "scph5502.bin"], []),
"sega-megacd|picodrive": (["bios_CD_E.bin", "bios_CD_U.bin", "bios_CD_J.bin",
"cd_extra.bin"], ["cd_extra.bin"]),
"sega-megadrive|fixcore": (["md_eu.bin", "md_us.bin", "md_jp.bin", "md_tmss.bin"],
["md_tmss.bin"]),
"nintendo-gamecube|dolphin": (["dolphin/GC/USA/IPL.bin", "dolphin/GC/EUR/IPL.bin",
"dolphin/GC/JAP/IPL.bin"], []),
"arcade|fbneo": (["fbneo/samples/big.zip"], ["fbneo/samples/big.zip"]),
"msx|fbneo": (["fbneo/msx.zip"], []),
"nintendo-gba|mgba": (["gba_bios.bin"], ["gba_bios.bin"]),
"nintendo-gba|gpsp": (["gba_bios.bin"], []),
}
REGION_READER_MCD = {
"applies_to": {"extensions": [".cue", ".bin", ".iso"], "media": "cd"},
"decode": {"kind": "integer", "otherwise": ["north-america"],
"values": [{"regions": ["europe"], "value": 100},
{"regions": ["japan"], "value": 161}]},
"location": {"encoding": "u8", "length": 1, "offset": 523, "sector": 0},
"magic": {"bytes": "SEGADISCSYSTEM", "offset": 0, "sector": 0},
}
SYSTEMS = {
"sony-playstation": {
"identify": {"sources": [{"source": "redump", "dat": "PS"}], "regions": [["europe"]],
"games": [], "serials": {"SLES-00001": [0]}},
"headers": {"readers": {"psx-serial-prefix": {
"location": {"iso_file": "SYSTEM.CNF", "key": "BOOT", "take": "basename"},
"decode": {"kind": "prefix-nocase", "values": [
{"value": "sles", "regions": ["europe"]}], "otherwise": "unknown"}}},
"cores": {"beetle_psx": {"order": ["psx-serial-prefix"],
"otherwise": ["north-america"]}}},
"region_rules": {"beetle_psx": {"keep_all_regions": [
{"case": "psx-override-bios", "condition": "option", "keeps": "region-free-files"}]}},
},
"sega-megacd": {
"identify": {"sources": [{"source": "redump", "dat": "MCD"}], "regions": [],
"games": [], "serials": {}},
"headers": {"readers": {"mcd-security-code": REGION_READER_MCD},
"cores": {"picodrive": {"order": ["mcd-security-code"],
"otherwise": ["north-america"]}}},
"region_rules": {"picodrive": {"default_region": "north-america"}},
"extras": [{"system": "sega-megacd", "profile": "picodrive",
"trigger": {"every_game": True}, "files": ["cd_extra.bin"],
"required": True}],
},
"sega-megadrive": {
"identify": {"sources": [{"source": "no-intro", "dat": "MD"}],
"regions": [["europe"], ["japan"], ["north-america"]],
"games": sorted([[loopback.crc(MD_EU), len(MD_EU), 0, "Game (Europe)"],
[loopback.crc(MD_JP), len(MD_JP), 1, "Game (Japan)"],
[loopback.crc(MD_ZIPPED), len(MD_ZIPPED), 2, "Zipped (USA)"]]),
"serials": {}},
"headers": {"readers": {"md-country": {
"location": {"offset": 0x1F0, "length": 3, "encoding": "ascii"},
"decode": {"kind": "letters", "otherwise": "unknown", "values": [
{"value": "J", "regions": ["japan"]}, {"value": "E", "regions": ["europe"]},
{"value": "U", "regions": ["north-america"]}]}}},
"cores": {"fixcore": {"order": ["md-country"], "otherwise": "unknown"}}},
"region_rules": {"fixcore": {}},
},
"nintendo-gamecube": {
"identify": {"sources": [{"source": "redump", "dat": "GC"}],
"regions": [["europe", "north-america"], ["japan"]],
"games": [], "serials": {"GALE01": [0], "GJPN01": [1]}},
"headers": {"readers": {
"gc-game-id": {"location": {"container": "gamecube-disc", "disc_offset": 0,
"encoding": "ascii", "length": 6},
"decode": {"kind": "serial"}},
"gc-region": {"location": {"container": "gamecube-disc", "disc_offset": GC_HEADER,
"encoding": "u32be", "length": 4},
"decode": {"kind": "integer", "otherwise": "unknown", "values": [
{"value": 0, "regions": ["japan"]},
{"value": 1, "regions": ["north-america"]},
{"value": 2, "regions": ["europe"]}]}}},
"cores": {"dolphin": {"order": ["gc-region"], "otherwise": "unknown"}}},
"region_rules": {"dolphin": {"keep_all_regions": [
{"case": "gamecube-unknown-region", "condition": "disc"}]}},
},
"nintendo-gba": {},
}
ARCADE = {
"bios": {"neogeo": ["mslug", "mslug2"], "pgm": ["orlegend"], "nobios": ["lost"],
"msx": ["msx_1942"]},
"devices": {}, "chd": [], "missing_parents": {},
"no_bios": ["1942", "nes_1942", "pacman"], "bios_sets": ["msx", "neogeo", "nobios", "pgm"],
}
SETUP = {
"format_version": 1, "setup": "retroarch", "name": "Fixture", "platform": "retroarch",
"sources": {}, "roms_root": {"path": "/mnt/SDCARD/Roms", "from_bios": "../Roms"},
"case_sensitive": False,
"media": [{"name": "Imgs"}],
"folders": [
{"folder": "PS", "systems": ["sony-playstation"], "basis": "id",
"profile": "beetle_psx", "extensions": [".cue", ".bin", ".chd", ".m3u", ".iso"],
"fallback": ["sony-playstation|beetle_psx"], "source_ref": "x"},
{"folder": "SEGACD", "systems": ["sega-megacd"], "basis": "id",
"profile": "picodrive", "extensions": [".cue", ".iso", ".bin", ".chd", ".m3u"],
"fallback": ["sega-megacd|picodrive"], "source_ref": "x"},
{"folder": "MD", "systems": ["sega-megadrive"], "basis": "id", "profile": "fixcore",
"extensions": [".md", ".bin", ".zip", ".7z"],
"fallback": ["sega-megadrive|fixcore"], "source_ref": "x"},
{"folder": "GC", "systems": ["nintendo-gamecube"], "basis": "id",
"profile": "dolphin", "extensions": [".iso", ".rvz"],
"fallback": ["nintendo-gamecube|dolphin"], "source_ref": "x"},
{"folder": "FBNEO", "systems": ["arcade"], "basis": "id", "profile": "fbneo",
"arcade": "fbneo", "extensions": [".zip", ".7z"], "fallback": ["arcade|fbneo"],
"source_ref": "x"},
{"folder": "MSX", "systems": ["msx"], "basis": "id", "profile": "fbneo",
"arcade": "fbneo", "extensions": [".zip"], "fallback": ["msx|fbneo"],
"source_ref": "x"},
{"folder": "GBA", "systems": ["nintendo-gba"], "basis": "id", "profile": "mgba",
"extensions": [".gba"], "fallback": ["nintendo-gba|mgba"],
"board_defaults": {"rpi": {"core": "gpsp", "profile": "gpsp",
"fallback": ["nintendo-gba|gpsp"]}},
"source_ref": "x"},
{"folder": "PORTS", "systems": [], "basis": "unresolved", "source_ref": "x"},
],
}
def _dumps(doc: object) -> bytes:
return (json.dumps(doc, sort_keys=True, separators=(",", ":")) + "\n").encode()
def write_index(folder: Path, systems: dict | None = None, arcade: dict | None = None,
setup: dict | None = None, extra_sets: dict | None = None,
more_setups: dict | None = None) -> None:
"""install/games/ as the generator lays it out, every digest right."""
rows = sorted({(dest, FILES[dest][0], "bios") for files, _o in SETS.values()
for dest in files})
position = {row[0]: i for i, row in enumerate(rows)}
sets = {**SETS, **(extra_sets or {})}
fallback = {"format_version": 1, "platform": "retroarch", "files": [list(r) for r in rows],
"sets": {key: {"files": [position[d] for d in files],
"optional": [position[d] for d in optional],
"bytes": 0, "required_bytes": 0}
for key, (files, optional) in sets.items()}}
docs = {"setups": {"retroarch": setup or SETUP, **(more_setups or {})}, "fallback": {"retroarch": fallback},
"systems": {key: {"format_version": 1, "system": key, **value}
for key, value in (systems or SYSTEMS).items()},
"arcade": {"fbneo": {"profile": "fbneo", **(arcade or ARCADE)}}}
index: dict = {"format_version": 1, "data_version": "0" * 16, "licences": [],
"folders": {"ps": ["sony-playstation"], "psx": ["sony-playstation"],
"md": ["sega-megadrive"], "megadrive": ["sega-megadrive"]}}
for kind, items in docs.items():
index[kind] = {}
for key, doc in items.items():
data = _dumps(doc)
rel = f"{kind}/{key}.json"
(folder / kind).mkdir(parents=True, exist_ok=True)
(folder / rel).write_bytes(data)
index[kind][key] = {"file": rel, "size": len(data),
"gzip_size": len(gzip.compress(data)),
"sha256": hashlib.sha256(data).hexdigest()}
(folder / "index.json").write_bytes(_dumps(index))
def manifest() -> dict:
files = []
for dest, (size, regions, cores, systems) in FILES.items():
payload = dest.encode().ljust(size, b".")[:size]
entry = {"dest": dest, "size": size, "sha1": hashlib.sha1(payload).hexdigest(),
"sha256": hashlib.sha256(payload).hexdigest(),
"repo_path": f"bios/{dest.replace('/', '_')}", "cores": cores}
if systems:
entry["systems"] = systems
if regions:
entry.update(regions=regions)
files.append(entry)
return {"manifest_version": 2, "platform": "retroarch", "files": files,
"omitted_files": []}
def mcd_iso(code: int, magic: bool = True) -> bytes:
data = bytearray(2048 * 18)
if magic:
data[0:14] = b"SEGADISCSYSTEM"
data[523] = code
return bytes(data)
def gc_iso(game_id: bytes, region: int) -> bytes:
data = bytearray(0x500)
data[0:6] = game_id
data[GC_HEADER:GC_HEADER + 4] = region.to_bytes(4, "big")
return bytes(data)
def md_rom(content: bytes, country: bytes) -> bytes:
data = bytearray(content.ljust(0x200, b"\0"))
data[0x1F0:0x1F3] = country
return bytes(data)
def ps_iso(boot: str) -> bytes:
"""A 2048-byte ISO 9660 image whose root holds SYSTEM.CNF."""
sectors = [bytearray(2048) for _ in range(20)]
volume = sectors[16]
volume[0] = 1
volume[1:6] = b"CD001"
root = bytearray(34)
root[0] = 34
root[2:6] = (17).to_bytes(4, "little")
root[10:14] = (2048).to_bytes(4, "little")
volume[156:190] = root
name = b"SYSTEM.CNF;1"
record = bytearray(33 + len(name))
record[0] = len(record)
record[2:6] = (18).to_bytes(4, "little")
text = f"BOOT = cdrom:\\{boot};1\r\n".encode()
record[10:14] = len(text).to_bytes(4, "little")
record[32] = len(name)
record[33:] = name
sectors[17][0:len(record)] = record
sectors[18][0:len(text)] = text
return b"".join(bytes(s) for s in sectors)
class Card:
"""A card in tmp/: BIOS/ and Roms/ at its root, the games index beside
a saved file list."""
def __init__(self) -> None:
self.root = Path(tempfile.mkdtemp())
self.bios = self.root / "card" / "BIOS"
self.roms = self.root / "card" / "Roms"
self.bios.mkdir(parents=True)
self.roms.mkdir()
self.lists = self.root / "lists"
(self.lists / "games").mkdir(parents=True)
self.manifest_path = self.lists / "retroarch.json"
self.manifest_path.write_text(json.dumps(manifest()))
write_index(self.lists / "games")
self.cache = self.root / "cache"
def game(self, folder: str, name: str, data: bytes = b"game") -> Path:
path = self.roms / folder / name
path.parent.mkdir(parents=True, exist_ok=True)
path.write_bytes(data)
return path
def zipped(self, folder: str, name: str, member: str, data: bytes) -> Path:
path = self.roms / folder / name
path.parent.mkdir(parents=True, exist_ok=True)
with zipfile.ZipFile(path, "w") as archive:
archive.writestr(member, data)
return path
def close(self) -> None:
shutil.rmtree(self.root, ignore_errors=True)
class GamesTestCase(unittest.TestCase):
def setUp(self) -> None:
self.card = Card()
+6 -6
View File
@@ -28,7 +28,7 @@ import unittest
from pathlib import Path
import install
from tests import test_install_games as games
from tests.gamessupport import SETUP, manifest, write_index
from tests.tuisupport import DOWN, UP, Pty, pty, pyte
REPO_ROOT = Path(__file__).resolve().parent.parent
@@ -143,13 +143,13 @@ class Repository:
self.site = self.root / "site"
(self.site / "install" / "games").mkdir(parents=True)
(self.site / "bios").mkdir()
self.listed = games.manifest()
self.listed = manifest()
self.write_list()
muos = dict(games.SETUP, setup="muos", name="muOS",
muos = dict(SETUP, setup="muos", name="muOS",
roms_root={"path": "/mnt/mmc/ROMS", "from_bios": "../../ROMS"})
retroarch = dict(games.SETUP, roms_root={"path": None, "from_bios": None})
games.write_index(self.site / "install" / "games", setup=retroarch,
more_setups={"muos": muos})
retroarch = dict(SETUP, roms_root={"path": None, "from_bios": None})
write_index(self.site / "install" / "games", setup=retroarch,
more_setups={"muos": muos})
base = loopback.serve(test, self.site)
self.home = self.root / "home"
self.home.mkdir()
+5 -107
View File
@@ -13,7 +13,6 @@ import tests
from tests import loopback
import contextlib
import hashlib
import io
import json
import os
@@ -28,100 +27,15 @@ import zipfile
from pathlib import Path
import install
from tests.test_install_selection import FakeRepository
from tests.installsupport import (
EU, EXTRA, GBA, JP, PAYLOAD, US, FakeRepository, Scratch, _entry, _offline_env, _pack,
_sha1, manifest,
)
# The screen tests run under 3.8 and import this module for its payloads. The
# build scripts stop below 3.9 (core.cli), so their modules load only above
# that floor.
if sys.version_info >= (3, 9):
from packs import parts as packs_parts
from packs import parts as packs_parts
REPO_ROOT = Path(__file__).resolve().parent.parent
US = b"us bios " * 64
JP = b"jp bios " * 64
EU = b"eu bios " * 64
GBA = b"gba bios" * 32
EXTRA = b"pcsx extra"
def _sha1(data: bytes) -> str:
return hashlib.sha1(data).hexdigest()
def _entry(dest: str, data: bytes, systems: list[str], **fields) -> dict:
return {
"dest": dest, "sha1": _sha1(data), "size": len(data),
"repo_path": f"bios/{dest.replace('/', '_')}", "cores": None,
"systems": systems, **fields,
}
def manifest() -> dict:
"""A small RetroArch list: two regions of one BIOS, a core file with a
second revision, a file in a subfolder."""
return {
"manifest_version": 2,
"platform": "retroarch",
"files": [
_entry("scph5501.bin", US, ["sony-playstation"], regions=["north-america"]),
_entry("scph5500.bin", JP, ["sony-playstation"], regions=["japan"]),
_entry("gba_bios.bin", GBA, ["nintendo-gba"]),
_entry("pcsx/extra.bin", EXTRA, ["sony-playstation"], cores=["pcsx_rearmed"],
alternatives=[{"sha1": _sha1(EU), "size": len(EU),
"repo_path": "bios/eu", "cores": ["beetle_psx"]},
{"sha1": _sha1(EXTRA), "size": len(EXTRA),
"repo_path": "bios/x", "cores": ["pcsx_rearmed"]}]),
],
"system_cores": {"sony-playstation": ["beetle_psx", "pcsx_rearmed"],
"nintendo-gba": ["mgba"]},
}
PAYLOAD = {"scph5501.bin": US, "scph5500.bin": JP, "gba_bios.bin": GBA,
"pcsx/extra.bin": EXTRA}
def _offline_env() -> dict:
"""An environment where any request the installer makes is refused."""
env = dict(os.environ)
env["RETROBIOS_BASE_URL"] = f"http://127.0.0.1:{loopback.closed_port()}"
env["HTTPS_PROXY"] = env["HTTP_PROXY"] = f"http://127.0.0.1:{loopback.closed_port()}"
return env
class Scratch(unittest.TestCase):
def setUp(self):
self.root = Path(tempfile.mkdtemp())
self.addCleanup(shutil.rmtree, self.root, True)
self.dest = self.root / "system"
self.list = self.root / "retroarch.json"
self.list.write_text(json.dumps(manifest()))
def run_installer(self, *options: str) -> subprocess.CompletedProcess:
return subprocess.run(
[sys.executable, str(REPO_ROOT / "install.py"), "--platform", "retroarch",
"--dest", str(self.dest), *options],
env=_offline_env(), capture_output=True, text=True, timeout=120,
check=False, stdin=subprocess.DEVNULL,
)
def place(self, relative: str, data: bytes) -> Path:
path = self.dest / relative
path.parent.mkdir(parents=True, exist_ok=True)
path.write_bytes(data)
return path
def check(self) -> str:
proc = self.run_installer("--check", "--manifest", str(self.list), "--verbose")
self.assertEqual(proc.returncode, 3, proc.stdout + proc.stderr)
return proc.stdout
def complete(self, *skip: str) -> None:
for name, data in PAYLOAD.items():
if name not in skip:
self.place(name, data)
class CheckNamesWhyAFileIsRefused(Scratch):
def test_another_region_is_named(self):
@@ -311,20 +225,6 @@ class ArchivesInTheBiosFolder(Scratch):
self.assertLess(elapsed, 30, f"{elapsed:.1f} s")
def _pack(directory: Path, name: str, members: dict[str, bytes]) -> Path:
"""A pack as generate_pack writes one: the files and a manifest.json."""
listed = [{"path": path, "sha1": _sha1(data), "md5": hashlib.md5(data).hexdigest(),
"size": len(data), "status": "verified", "name": path.rsplit("/", 1)[-1]}
for path, data in members.items()]
path = directory / name
with zipfile.ZipFile(path, "w", zipfile.ZIP_DEFLATED) as archive:
for member, data in members.items():
archive.writestr(member, data)
archive.writestr("README.txt", b"read me\n")
archive.writestr("manifest.json", json.dumps({"files": listed}))
return path
BIG = {f"dir{n}/file{n}.bin": loopback.noise(str(n), 2048) for n in range(4)}
@@ -875,7 +775,6 @@ class ADryRunOpensOnItsTotals(Scratch):
self.assertTrue(any("sys00/file0.bin" in line for line in plan))
class OfflineLeavesFilesMissing(Scratch):
"""The files --offline leaves out at a
terminal were counted with a "no" to the size question. Once one file
@@ -1155,7 +1054,6 @@ class OfflineAndPackLeaveOut(Scratch):
self.assertIn("Enter) install what is found in", out.getvalue())
class LocalFilesSayWhyTheyCannotBeUsed(unittest.TestCase):
"""An oversized layout beside --manifest was "not valid: Expecting
value", and an unreadable target list read as absent, so the offline
+1 -1
View File
@@ -26,7 +26,7 @@ from pathlib import Path
from unittest import mock
import install
from tests.test_install_selection import FakeRepository
from tests.installsupport import FakeRepository
REPO_ROOT = Path(__file__).resolve().parent.parent
+2 -2
View File
@@ -217,7 +217,7 @@ class TheDataTreesCountInTheFreeSpace(unittest.TestCase):
files the first installed."""
from types import SimpleNamespace
from tests.test_install_selection import FakeRepository
from tests.installsupport import FakeRepository
member = os.urandom(4096)
results = []
@@ -594,7 +594,7 @@ class ACheckThatFindsFilesMissingIsNoFailure(unittest.TestCase):
BIOS folder to complete from a tool that never ran."""
def test_missing_is_3_and_a_failure_stays_1(self):
from tests.test_install_selection import FakeRepository
from tests.installsupport import FakeRepository
with FakeRepository() as repo:
missing = repo.run("--no-input", "--check")
+2 -83
View File
@@ -14,9 +14,6 @@ from tests import loopback
from tests.sources import script_source
import contextlib
import functools
import hashlib
import http.server
import importlib.util
import io
import json
@@ -26,19 +23,13 @@ import shlex
import shutil
import subprocess
import sys
import tempfile
import threading
import unittest
from unittest import mock
from pathlib import Path
from model import region
# The screen tests run under 3.8 and import this module for its fakes. The
# build scripts stop below 3.9 (core.cli), so their modules load only above
# that floor.
if sys.version_info >= (3, 9):
from resolve import regions as resolve_regions
from resolve import regions as resolve_regions
from tests.installsupport import FakeRepository
REPO_ROOT = Path(__file__).resolve().parent.parent
@@ -517,78 +508,6 @@ class TheBoundaryChecksTheNewFields(unittest.TestCase):
install._validate_manifest(manifest, "retroarch")
class FakeRepository:
"""A loopback copy of the repository: one manifest and its payloads."""
PAYLOADS = {
"scph5500.bin": (b"jp bios", ["sony-playstation"], ["japan"], None),
"scph5501.bin": (b"us bios", ["sony-playstation"], ["north-america"], None),
"gba_bios.bin": (b"gba bios", ["nintendo-gba"], None, None),
"pcsx/extra.bin": (b"pcsx", ["sony-playstation"], None, ["pcsx_rearmed"]),
"mgba/extra.bin": (b"mgba", ["nintendo-gba"], None, ["mgba"]),
}
def __init__(self, selection: bool = True):
self.selection = selection
def __enter__(self) -> FakeRepository:
self.root = Path(tempfile.mkdtemp())
(self.root / "install").mkdir()
(self.root / "bios").mkdir()
files = []
for name, (payload, systems, regions, cores) in self.PAYLOADS.items():
stored = name.replace("/", "_")
(self.root / "bios" / stored).write_bytes(payload)
entry = {
"dest": name,
"sha1": hashlib.sha1(payload).hexdigest(),
"sha256": hashlib.sha256(payload).hexdigest(),
"size": len(payload),
"repo_path": f"bios/{stored}",
"cores": cores,
}
if self.selection:
entry["systems"] = systems
if regions:
entry.update(regions=regions, region_system_groups=systems)
files.append(entry)
manifest = {"manifest_version": 2, "platform": "retroarch", "files": files}
(self.root / "install" / "retroarch.json").write_text(json.dumps(manifest))
handler = functools.partial(loopback.Quiet, directory=str(self.root))
self.httpd = http.server.ThreadingHTTPServer(("127.0.0.1", 0), handler)
threading.Thread(target=self.httpd.serve_forever, daemon=True).start()
self.dest = self.root / "dest"
return self
def __exit__(self, *exc) -> None:
self.httpd.shutdown()
self.httpd.server_close()
shutil.rmtree(self.root, ignore_errors=True)
def env(self) -> dict:
env = dict(os.environ)
env["RETROBIOS_BASE_URL"] = f"http://127.0.0.1:{self.httpd.server_address[1]}"
return env
def command(self, *options: str) -> list[str]:
return [sys.executable, str(REPO_ROOT / "install.py"), "--platform",
"retroarch", "--dest", str(self.dest), *options]
def run(self, *options: str) -> subprocess.CompletedProcess:
return subprocess.run(
self.command(*options), env=self.env(), capture_output=True,
text=True, timeout=60, check=False, stdin=subprocess.DEVNULL,
)
def installed(self) -> list[str]:
if not self.dest.exists():
return []
return sorted(
p.relative_to(self.dest).as_posix()
for p in self.dest.rglob("*") if p.is_file()
)
class TheOneLinerNarrows(unittest.TestCase):
def test_options_install_only_the_choice(self):
with FakeRepository() as repo:
@@ -28,6 +28,7 @@ from scraper.batocera_launchers import (
from scraper.batocera_searches import duckstation, hatari
from scraper.batocera_config_writes import lexaloffle
from scraper.retropie_scripts import Launcher as PackageLauncher
from tests.launcherssupport import placed
REPO_ROOT = Path(__file__).resolve().parent.parent
@@ -302,17 +303,6 @@ class LexaloffleGenerator(Generator):
return 4/3'''
def placed(blocks: dict[int, str]) -> str:
"""Each block starting at its line, blank lines between."""
lines: list[str] = []
for start, block in sorted(blocks.items()):
if len(lines) >= start:
raise AssertionError(f"block at line {start} overlaps the previous one")
lines += [""] * (start - 1 - len(lines))
lines += block.splitlines()
return "\n".join(lines) + "\n"
def configgen(files: dict[str, str]) -> Configgen:
tree = {PATHS_MODULE: PATHS, IMPORTER: IMPORTER_TEXT, **files}
return Configgen(tree.__getitem__)
+39 -39
View File
@@ -22,12 +22,12 @@ from scraper.retrobat_config_files import (
ares,
mesen,
)
from scraper.retrobat_generators import GUARDED_WRITES, guarded_writes_in
from scraper.retrobat_generators import GENERATORS, GUARDED_WRITES, guarded_writes_in
from scraper.retrobat_playstation import duckstation, psx_cascades
from scraper.retrobat_render import _option_path_in
from scraper.csharp_source import LauncherPatternMissing, Source, render_concat
from model.sourcerevision import required_revision
from tests.launchersretrobatsupport import G, _sources
from tests.launcherssupport import _sources
ARES = """
@@ -347,9 +347,9 @@ REASSIGNED = """
def _psx_sources() -> dict[str, Source]:
return _sources(
**{
f"{G}/Mednafen.Generator.cs": MEDNAFEN,
f"{G}/Bizhawk.Generator.cs": MEDNAFEN.replace("mednafen_psx", "bizhawk_psx"),
f"{G}/LibRetro.CoreOptions.cs": LIBRETRO_PSX,
f"{GENERATORS}/Mednafen.Generator.cs": MEDNAFEN,
f"{GENERATORS}/Bizhawk.Generator.cs": MEDNAFEN.replace("mednafen_psx", "bizhawk_psx"),
f"{GENERATORS}/LibRetro.CoreOptions.cs": LIBRETRO_PSX,
}
)
@@ -360,7 +360,7 @@ def revision_of(url: str) -> str:
class NamesInLauncherOrder(unittest.TestCase):
def test_ares_fallback_chain_keeps_its_order(self):
[record] = ares(_sources(**{f"{G}/Ares.Generator.cs": ARES}))
[record] = ares(_sources(**{f"{GENERATORS}/Ares.Generator.cs": ARES}))
self.assertEqual(
record["names"],
[
@@ -374,10 +374,10 @@ class NamesInLauncherOrder(unittest.TestCase):
self.assertEqual(
record["passes_to"], "settings.bml LaserActiveSEGAPAC/Firmware/BIOS.Japan (first found)"
)
self.assertEqual(record["source_ref"], f"{G}/Ares.Generator.cs:7-14")
self.assertEqual(record["source_ref"], f"{GENERATORS}/Ares.Generator.cs:7-14")
def test_mesen_copy_names_source_and_renamed_target(self):
[record] = mesen(_sources(**{f"{G}/Mesen.Generator.cs": MESEN}))
[record] = mesen(_sources(**{f"{GENERATORS}/Mesen.Generator.cs": MESEN}))
self.assertEqual(record["names"], ["colecovision.rom"])
self.assertEqual(record["kind"], "copies")
self.assertIn("<mesen>/Firmware/bios.col", record["passes_to"])
@@ -385,10 +385,10 @@ class NamesInLauncherOrder(unittest.TestCase):
record["fails_when_missing"],
"ApplicationException 'Colecovision firmware is missing (colecovision.rom)'",
)
self.assertEqual(record["source_ref"], f"{G}/Mesen.Generator.cs:1-13")
self.assertEqual(record["source_ref"], f"{GENERATORS}/Mesen.Generator.cs:1-13")
def test_amiberry_identical_lists_are_one_record(self):
records = amiberry(_sources(**{f"{G}/Amiberry.Generator.cs": AMIBERRY}))
records = amiberry(_sources(**{f"{GENERATORS}/Amiberry.Generator.cs": AMIBERRY}))
records = [r for r in records if r["kind"] == "names_searched"]
self.assertEqual(
[r["names"] for r in records],
@@ -399,7 +399,7 @@ class NamesInLauncherOrder(unittest.TestCase):
)
self.assertEqual(records[0]["search_dir"], "bios, bios/amiga, bios/Amiga")
self.assertEqual(
records[0]["source_ref"], f"{G}/Amiberry.Generator.cs:3-5, 8-10, 15-17, 23-27"
records[0]["source_ref"], f"{GENERATORS}/Amiberry.Generator.cs:3-5, 8-10, 15-17, 23-27"
)
self.assertEqual(
records[1]["passes_to"],
@@ -407,20 +407,20 @@ class NamesInLauncherOrder(unittest.TestCase):
)
def test_amiberry_folders_are_below_its_emulator_folder(self):
records = amiberry(_sources(**{f"{G}/Amiberry.Generator.cs": AMIBERRY}))
records = amiberry(_sources(**{f"{GENERATORS}/Amiberry.Generator.cs": AMIBERRY}))
folders = [r for r in records if r["kind"] == "passes_path"]
self.assertEqual(
[(r["search_dir"], r["passes_to"], r["source_ref"]) for r in folders],
[
('<AppConfig.GetFullPath("amiberry")>/ROMs', "written: rom_path in amiberry.conf",
f"{G}/Amiberry.Generator.cs:31, 37-41"),
f"{GENERATORS}/Amiberry.Generator.cs:31, 37-41"),
('<AppConfig.GetFullPath("amiberry")>/WHDBoot',
"written: whdboot_path in amiberry.conf", f"{G}/Amiberry.Generator.cs:31, 40-41"),
"written: whdboot_path in amiberry.conf", f"{GENERATORS}/Amiberry.Generator.cs:31, 40-41"),
],
)
def test_amiberry_copies_each_kickstart_into_its_roms_folder(self):
records = amiberry(_sources(**{f"{G}/Amiberry.Generator.cs": AMIBERRY}))
records = amiberry(_sources(**{f"{GENERATORS}/Amiberry.Generator.cs": AMIBERRY}))
copies = [r for r in records if r["kind"] == "copies"]
self.assertEqual(
[(r["names"], r["passes_to"], r["depends_on_option"]) for r in copies],
@@ -438,13 +438,13 @@ class NamesInLauncherOrder(unittest.TestCase):
self.assertEqual(copies[0]["search_dir"], "bios, bios/amiga, bios/Amiga")
self.assertEqual(
copies[0]["source_ref"],
f"{G}/Amiberry.Generator.cs:3-5, 8-10, 15, 23-27, 31, 37-39, 52-59",
f"{GENERATORS}/Amiberry.Generator.cs:3-5, 8-10, 15, 23-27, 31, 37-39, 52-59",
)
def test_amiberry_copy_without_its_staleness_test_raises(self):
broken = AMIBERRY.replace(" || dst.LastWriteTimeUtc < src.LastWriteTimeUtc", "")
with self.assertRaises(LauncherPatternMissing):
amiberry(_sources(**{f"{G}/Amiberry.Generator.cs": broken}))
amiberry(_sources(**{f"{GENERATORS}/Amiberry.Generator.cs": broken}))
def test_psx_cascade_splits_searched_from_fallback(self):
records = psx_cascades(_psx_sources())
@@ -454,17 +454,17 @@ class NamesInLauncherOrder(unittest.TestCase):
self.assertEqual(fallback["names"], ["scph5502.bin", "scph5500.bin"])
self.assertEqual(fallback["kind"], "fixed_name")
self.assertEqual(fallback["fails_when_missing"], "names written without an existence check")
self.assertEqual(searched["source_ref"], f"{G}/Mednafen.Generator.cs:1-21")
self.assertEqual(searched["source_ref"], f"{GENERATORS}/Mednafen.Generator.cs:1-21")
def test_libretro_cascade_takes_the_core_from_its_guard(self):
records = psx_cascades(_psx_sources())
[beetle] = [r for r in records if r["build"] == "libretro"]
self.assertEqual(beetle["emulator"], "mednafen_psx_hw")
self.assertEqual(beetle["names"], ["psxonpsp660.bin"])
self.assertEqual(beetle["source_ref"], f"{G}/LibRetro.CoreOptions.cs:3-12")
self.assertEqual(beetle["source_ref"], f"{GENERATORS}/LibRetro.CoreOptions.cs:3-12")
def test_openmsx_one_record_per_machine(self):
records = openmsx(_sources(**{f"{G}/OpenMSX.Generator.cs": OPENMSX}))
records = openmsx(_sources(**{f"{GENERATORS}/OpenMSX.Generator.cs": OPENMSX}))
self.assertEqual(
[(r["passes_to"], r["names"]) for r in records],
[
@@ -475,37 +475,37 @@ class NamesInLauncherOrder(unittest.TestCase):
)
self.assertEqual(records[0]["search_dir"], "bios/openmsx/share/systemroms")
self.assertFalse(records[0]["case_insensitive"])
self.assertEqual(records[1]["source_ref"], f"{G}/OpenMSX.Generator.cs:1-4, 10")
self.assertEqual(records[1]["source_ref"], f"{GENERATORS}/OpenMSX.Generator.cs:1-4, 10")
def test_openmsx_home_is_handed_as_a_directory(self):
# OPENMSX_HOME is the user directory openMSX reads share/systemroms below.
records = openmsx(_sources(**{f"{G}/OpenMSX.Generator.cs": OPENMSX}))
records = openmsx(_sources(**{f"{GENERATORS}/OpenMSX.Generator.cs": OPENMSX}))
home = records[-1]
self.assertEqual(home["kind"], "passes_path")
self.assertEqual(home["search_dir"], "bios/openmsx")
self.assertEqual(home["source_ref"], f"{G}/OpenMSX.Generator.cs:13-14")
self.assertEqual(home["source_ref"], f"{GENERATORS}/OpenMSX.Generator.cs:13-14")
def test_duckstation_reads_the_standalone_feature_not_the_core(self):
search, option = duckstation(
_sources(**{f"{G}/Duckstation.Generator.cs": DUCKSTATION, retrobat_generators.FEATURES: FEATURES})
_sources(**{f"{GENERATORS}/Duckstation.Generator.cs": DUCKSTATION, retrobat_generators.FEATURES: FEATURES})
)
self.assertEqual(search["kind"], "passes_path")
self.assertEqual(search["names"], [])
self.assertEqual(option["names"], ["psxonpsp660.bin", "scph5501.bin"])
self.assertEqual(option["passes_to"], "settings.ini [BIOS] PathNTSCJ = PathPAL = <value>")
self.assertEqual(
option["source_ref"], f"{G}/Duckstation.Generator.cs:3-7, {retrobat_generators.FEATURES}:12-15"
option["source_ref"], f"{GENERATORS}/Duckstation.Generator.cs:3-7, {retrobat_generators.FEATURES}:12-15"
)
def test_hatari_default_and_option(self):
fixed, option, emutos, newer = hatari(
_sources(**{f"{G}/Hatari.Generator.cs": HATARI, retrobat_generators.FEATURES: HATARI_FEATURES})
_sources(**{f"{GENERATORS}/Hatari.Generator.cs": HATARI, retrobat_generators.FEATURES: HATARI_FEATURES})
)
message = "ApplicationException 'Missing TOS file <tosName> in 'bios' folder.'"
self.assertEqual(fixed["names"], ["tos.img"])
self.assertEqual(fixed["search_dir"], "bios")
self.assertEqual(fixed["fails_when_missing"], f"bios/hatari/tos/emutos.img instead, else {message}")
self.assertEqual(fixed["source_ref"], f"{G}/Hatari.Generator.cs:1-3, 13-14, 27")
self.assertEqual(fixed["source_ref"], f"{GENERATORS}/Hatari.Generator.cs:1-3, 13-14, 27")
self.assertEqual(option["names"], ["tos206.img", "tos102.img"])
self.assertEqual(option["search_dir"], "bios/hatari/tos")
self.assertEqual(option["fails_when_missing"], message)
@@ -515,7 +515,7 @@ class NamesInLauncherOrder(unittest.TestCase):
self.assertEqual(newer["names"], ["tos104.img", "tos206.img", "emutos.img"])
def _one(text: str, emulator: str, path: str = f"{G}/X.Generator.cs") -> list[dict]:
def _one(text: str, emulator: str, path: str = f"{GENERATORS}/X.Generator.cs") -> list[dict]:
return guarded_writes_in(_sources(**{path: text})[path], emulator)
@@ -532,7 +532,7 @@ class GuardedConfigWrites(unittest.TestCase):
"32XM68KBIOS not written"),
],
)
self.assertEqual(fixed[0]["source_ref"], f"{G}/X.Generator.cs:14-16")
self.assertEqual(fixed[0]["source_ref"], f"{GENERATORS}/X.Generator.cs:14-16")
self.assertTrue(all(r["search_dir"] == "bios" and r["case_insensitive"] for r in fixed))
self.assertNotIn("depends_on_option", fixed[0])
@@ -540,7 +540,7 @@ class GuardedConfigWrites(unittest.TestCase):
(folder,) = [r for r in _one(KEGA, "kega-fusion") if r["kind"] == "passes_path"]
self.assertEqual(folder["names"], [])
self.assertEqual(folder["passes_to"], "Fusion.ini GenesisBIOS = bios")
self.assertEqual(folder["source_ref"], f"{G}/X.Generator.cs:7, 11")
self.assertEqual(folder["source_ref"], f"{GENERATORS}/X.Generator.cs:7, 11")
def test_early_return_and_enclosing_if_are_conditions(self):
(record,) = _one(JGENESIS, "jgenesis")
@@ -551,7 +551,7 @@ class GuardedConfigWrites(unittest.TestCase):
self.assertEqual(
record["passes_to"], "jgenesis-config.toml [sega_cd] bios_path, only if the file exists"
)
self.assertEqual(record["source_ref"], f"{G}/X.Generator.cs:12-13, 17, 21-22")
self.assertEqual(record["source_ref"], f"{GENERATORS}/X.Generator.cs:12-13, 17, 21-22")
def test_option_switch_is_named(self):
(record,) = _one(MELONDS, "melonds")
@@ -573,8 +573,8 @@ class GuardedConfigWrites(unittest.TestCase):
_one(looped, "kega-fusion")
def test_pinned_kega_fusion_generator_is_read(self):
self.assertIn(f"{G}/KegaFusion.Generator.cs", rl.SOURCE_FILES)
self.assertEqual(GUARDED_WRITES[f"{G}/KegaFusion.Generator.cs"], "kega-fusion")
self.assertIn(f"{GENERATORS}/KegaFusion.Generator.cs", rl.SOURCE_FILES)
self.assertEqual(GUARDED_WRITES[f"{GENERATORS}/KegaFusion.Generator.cs"], "kega-fusion")
SATURN_FEATURES = """
@@ -717,7 +717,7 @@ def _feature_sources(path: str, text: str, features: str) -> dict[str, Source]:
class OptionReplacesThePath(unittest.TestCase):
def test_kronos_default_then_option_without_hle(self):
path = f"{G}/Kronos.Generator.cs"
path = f"{GENERATORS}/Kronos.Generator.cs"
sources = _feature_sources(path, KRONOS, SATURN_FEATURES)
fixed, option = _option_path_in(sources[path], sources[retrobat_generators.FEATURES], "kronos")
self.assertEqual(fixed["names"], ["saturn_bios.bin"])
@@ -731,7 +731,7 @@ class OptionReplacesThePath(unittest.TestCase):
self.assertEqual(option["source_ref"], f"{path}:7-15, {retrobat_generators.FEATURES}:3-7")
def test_ymir_writes_without_a_check_and_passes_the_folder(self):
path = f"{G}/Ymir.Generator.cs"
path = f"{GENERATORS}/Ymir.Generator.cs"
sources = _feature_sources(path, YMIR, SATURN_FEATURES)
fixed, option, folder = _option_path_in(sources[path], sources[retrobat_generators.FEATURES], "ymir")
self.assertEqual(
@@ -744,7 +744,7 @@ class OptionReplacesThePath(unittest.TestCase):
)
def test_kronos_falls_back_to_the_regional_bios(self):
path = f"{G}/Kronos.Generator.cs"
path = f"{GENERATORS}/Kronos.Generator.cs"
sources = _feature_sources(path, KRONOS_FALLBACK, SATURN_FEATURES)
fixed, option, fallback = _option_path_in(
sources[path], sources[retrobat_generators.FEATURES], "kronos"
@@ -768,7 +768,7 @@ class OptionReplacesThePath(unittest.TestCase):
self.assertEqual(fallback["source_ref"], f"{path}:15-19")
def test_ymir_writes_a_forced_bios_under_its_flag(self):
path = f"{G}/Ymir.Generator.cs"
path = f"{GENERATORS}/Ymir.Generator.cs"
sources = _feature_sources(path, YMIR_OVERRIDE, SATURN_FEATURES)
option, ipl, cdb = _option_path_in(sources[path], sources[retrobat_generators.FEATURES], "ymir")
self.assertEqual(
@@ -784,7 +784,7 @@ class OptionReplacesThePath(unittest.TestCase):
self.assertEqual(cdb["source_ref"], f"{path}:15-19")
def test_ssf_has_no_default_name(self):
path = f"{G}/SSF.Generator.cs"
path = f"{GENERATORS}/SSF.Generator.cs"
sources = _feature_sources(path, SSF, SATURN_FEATURES)
[option] = _option_path_in(sources[path], sources[retrobat_generators.FEATURES], "ssf")
self.assertEqual(option["names"], ["sega_101.bin"])
@@ -804,7 +804,7 @@ class AbsentConstructStopsTheScrape(unittest.TestCase):
def test_chain_without_fallback_is_not_a_search(self):
single = ARES.split(" if (!File.Exists(bios_japan))")[0] + " }\n"
with self.assertRaises(LauncherPatternMissing):
ares(_sources(**{f"{G}/Ares.Generator.cs": single}))
ares(_sources(**{f"{GENERATORS}/Ares.Generator.cs": single}))
def test_missing_source_file_is_named(self):
with self.assertRaises(LauncherPatternMissing) as caught:
+32 -31
View File
@@ -22,10 +22,11 @@ from scraper.retrobat_config_files import (
desmume,
)
from scraper.retrobat_config_folders import eka2l1, tsugaru, dosbox_copies
from scraper.retrobat_generators import GENERATORS
from scraper.retrobat_render import render
from scraper.retrobat_xbox import CXBX_DATA_FOLDER, cxbx, xemu_saves
from scraper.csharp_source import LauncherPatternMissing, Source
from tests.launchersretrobatsupport import G, _sources
from tests.launcherssupport import _sources
DESMUME = """
@@ -386,7 +387,7 @@ XROAR = """
class FilesNeededTogether(unittest.TestCase):
def test_desmume_pair_and_firmware_override(self):
pair, firmware = desmume(_sources(**{f"{G}/Desmume.Generator.cs": DESMUME}))
pair, firmware = desmume(_sources(**{f"{GENERATORS}/Desmume.Generator.cs": DESMUME}))
self.assertEqual(pair["names"], ["bios7.bin", "bios9.bin"])
self.assertEqual(
pair["passes_to"],
@@ -402,7 +403,7 @@ class FilesNeededTogether(unittest.TestCase):
def test_melonds_dsi_files_and_nand_region(self):
fixed, region = melonds_dsi(
_sources(**{f"{G}/MelonDS.Generator.cs": MELONDS_DSI, retrobat_generators.FEATURES: MELONDS_FEATURES})
_sources(**{f"{GENERATORS}/MelonDS.Generator.cs": MELONDS_DSI, retrobat_generators.FEATURES: MELONDS_FEATURES})
)
self.assertEqual(fixed["names"], ["dsi_bios9.bin", "dsi_nand.bin"])
self.assertEqual(fixed["passes_to"], "melonDS.toml [DSi] BIOS9Path, NANDPath")
@@ -419,7 +420,7 @@ class FilesNeededTogether(unittest.TestCase):
self.assertEqual(region["fails_when_missing"], "falls back to dsi_nand.bin")
def test_jzintv_flags_in_command_line_order(self):
both, ecs = jzintv(_sources(**{f"{G}/Jzintv.Generator.cs": JZINTV}))
both, ecs = jzintv(_sources(**{f"{GENERATORS}/Jzintv.Generator.cs": JZINTV}))
self.assertEqual(both["names"], ["exec.bin", "grom.bin"])
self.assertEqual(both["passes_to"], "command line -e <bios>/exec.bin -g <bios>/grom.bin")
self.assertEqual(ecs["names"], ["ecs.bin"])
@@ -535,17 +536,17 @@ CXBX = """
class XboxFilesTheLauncherWrites(unittest.TestCase):
def test_xemu_keeps_its_eeprom_and_disk_below_saves(self):
records = xemu_saves(_sources(**{f"{G}/Xemu.Generator.cs": XEMU_SAVES}))
records = xemu_saves(_sources(**{f"{GENERATORS}/Xemu.Generator.cs": XEMU_SAVES}))
self.assertEqual(
[(r["emulator"], r["kind"], r["names"], r["search_dir"], r["source_ref"])
for r in records],
[
("xemu", "fixed_name", ["eeprom.bin", "xbox_hdd.qcow2"], "saves/<system>",
f"{G}/Xemu.Generator.cs:3-19, 27-29"),
f"{GENERATORS}/Xemu.Generator.cs:3-19, 27-29"),
("xemu, xemu-chihiro", "copies", ["chihiro_eeprom.bin"], "saves/chihiro",
f"{G}/Xemu.Generator.cs:3, 40-51"),
f"{GENERATORS}/Xemu.Generator.cs:3, 40-51"),
("xemu, xemu-chihiro", "fixed_name", ["chihiro_snapshots.qcow2"], "saves/chihiro",
f"{G}/Xemu.Generator.cs:3, 34-37"),
f"{GENERATORS}/Xemu.Generator.cs:3, 34-37"),
],
)
self.assertIn("eeprom_path, hdd_path", records[0]["passes_to"])
@@ -553,23 +554,23 @@ class XboxFilesTheLauncherWrites(unittest.TestCase):
records[0]["depends_on_option"])
def test_cxbx_runs_from_its_folder_and_gets_the_eeprom_there(self):
records = cxbx(_sources(**{f"{G}/Cxbx.Generator.cs": CXBX}))
records = cxbx(_sources(**{f"{GENERATORS}/Cxbx.Generator.cs": CXBX}))
self.assertEqual(
[(r["emulator"], r["kind"], r["names"], r["search_dir"], r["source_ref"])
for r in records],
[
("chihiro", "passes_path", [], '<AppConfig.GetFullPath("chihiro")>',
f"{G}/Cxbx.Generator.cs:19-21, 31"),
f"{GENERATORS}/Cxbx.Generator.cs:19-21, 31"),
("chihiro-gun", "passes_path", [], '<AppConfig.GetFullPath("chihiro-ds")>',
f"{G}/Cxbx.Generator.cs:23-25, 31"),
f"{GENERATORS}/Cxbx.Generator.cs:23-25, 31"),
("cxbx-reloaded", "passes_path", [], '<AppConfig.GetFullPath("cxbx-reloaded")>',
f"{G}/Cxbx.Generator.cs:27-31"),
f"{GENERATORS}/Cxbx.Generator.cs:27-31"),
("chihiro, chihiro-gun, cxbx-reloaded", "fixed_name", ["xbox-iso-vfs.exe"],
"<emulatorLauncher folder>", f"{G}/Cxbx.Generator.cs:3-7"),
"<emulatorLauncher folder>", f"{GENERATORS}/Cxbx.Generator.cs:3-7"),
("chihiro, chihiro-gun, cxbx-reloaded", "fixed_name", ["dokan2.dll"],
"%DokanLibrary2%", f"{G}/Cxbx.Generator.cs:3-4, 8-13"),
"%DokanLibrary2%", f"{GENERATORS}/Cxbx.Generator.cs:3-4, 8-13"),
("cxbx-reloaded", "fixed_name", ["EEPROM.bin"],
'<AppConfig.GetFullPath("cxbx-reloaded")>', f"{G}/Cxbx.Generator.cs:34-41"),
'<AppConfig.GetFullPath("cxbx-reloaded")>', f"{GENERATORS}/Cxbx.Generator.cs:34-41"),
],
)
self.assertTrue(all(r["passes_to"].startswith(CXBX_DATA_FOLDER) for r in records[:3]))
@@ -579,7 +580,7 @@ class XboxFilesTheLauncherWrites(unittest.TestCase):
class HelpersAndCopies(unittest.TestCase):
def test_blastem_one_record_per_helper_call(self):
records = blastem(_sources(**{f"{G}/Blastem.Generator.cs": BLASTEM}))
records = blastem(_sources(**{f"{GENERATORS}/Blastem.Generator.cs": BLASTEM}))
self.assertEqual(
[(r["names"], r["passes_to"]) for r in records],
[
@@ -590,10 +591,10 @@ class HelpersAndCopies(unittest.TestCase):
),
],
)
self.assertEqual(records[0]["source_ref"], f"{G}/Blastem.Generator.cs:9-10, 14-21")
self.assertEqual(records[0]["source_ref"], f"{GENERATORS}/Blastem.Generator.cs:9-10, 14-21")
def test_dolphin_unchecked_write_and_segaboot_candidates(self):
gba, segaboot = dolphin(_sources(**{f"{G}/Dolphin.Generator.cs": DOLPHIN}))
gba, segaboot = dolphin(_sources(**{f"{GENERATORS}/Dolphin.Generator.cs": DOLPHIN}))
self.assertEqual(gba["names"], ["gba_bios.bin"])
self.assertEqual(
gba["passes_to"],
@@ -608,7 +609,7 @@ class HelpersAndCopies(unittest.TestCase):
def test_dosbox_copies_grouped_by_target_folder(self):
sources = _sources(
**{f"{G}/DosBoxPure.Generator.cs": DOSBOX, f"{G}/DosBoxStaging.Generator.cs": DOSBOX}
**{f"{GENERATORS}/DosBoxPure.Generator.cs": DOSBOX, f"{GENERATORS}/DosBoxStaging.Generator.cs": DOSBOX}
)
records = dosbox_copies(sources)
self.assertEqual(
@@ -630,7 +631,7 @@ class HelpersAndCopies(unittest.TestCase):
self.assertEqual(records[0]["depends_on_option"], "the target does not exist")
def test_tsugaru_folder_chain(self):
[record] = tsugaru(_sources(**{f"{G}/Tsugaru.Generator.cs": TSUGARU}))
[record] = tsugaru(_sources(**{f"{GENERATORS}/Tsugaru.Generator.cs": TSUGARU}))
self.assertEqual(record["names"], ["FMT_SYS.ROM"])
self.assertEqual(
record["search_dir"], "bios/fmtowns, then bios/fmtownsux, then <emulator>/roms"
@@ -640,15 +641,15 @@ class HelpersAndCopies(unittest.TestCase):
)
def test_commented_code_is_not_read(self):
[record] = eka2l1(_sources(**{f"{G}/Eka2l1.Generator.cs": EKA2L1}))
[record] = eka2l1(_sources(**{f"{GENERATORS}/Eka2l1.Generator.cs": EKA2L1}))
self.assertEqual(record["passes_to"], "config.yml data-storage = bios/eka2l1/data")
def test_bizhawk_gb_one_slot_per_system(self):
records = bizhawk_gb(
_sources(
**{
f"{G}/Bizhawk.CoreOptions.cs": BIZHAWK_GB,
f"{G}/Bizhawk.Generator.cs": BIZHAWK_CONFIG,
f"{GENERATORS}/Bizhawk.CoreOptions.cs": BIZHAWK_GB,
f"{GENERATORS}/Bizhawk.Generator.cs": BIZHAWK_CONFIG,
}
)
)
@@ -669,9 +670,9 @@ class HelpersAndCopies(unittest.TestCase):
class FolderArguments(unittest.TestCase):
def test_mess_folders_shared_with_the_libretro_core(self):
sources = _sources(**{f"{G}/MessSystem.cs": MESS, f"{G}/Mame64.Generator.cs": MAME64})
sources = _sources(**{f"{GENERATORS}/MessSystem.cs": MESS, f"{GENERATORS}/Mame64.Generator.cs": MAME64})
records = mame(sources)
mess = [r for r in records if r["source_ref"].startswith(f"{G}/MessSystem.cs")]
mess = [r for r in records if r["source_ref"].startswith(f"{GENERATORS}/MessSystem.cs")]
self.assertEqual(
[(r["emulator"], r["passes_to"]) for r in mess],
[
@@ -688,8 +689,8 @@ class FolderArguments(unittest.TestCase):
self.assertNotIn("depends_on_option", mess[4])
def test_mame64_ternary_folder(self):
sources = _sources(**{f"{G}/MessSystem.cs": MESS, f"{G}/Mame64.Generator.cs": MAME64})
own = [r for r in mame(sources) if r["source_ref"].startswith(f"{G}/Mame64")]
sources = _sources(**{f"{GENERATORS}/MessSystem.cs": MESS, f"{GENERATORS}/Mame64.Generator.cs": MAME64})
own = [r for r in mame(sources) if r["source_ref"].startswith(f"{GENERATORS}/Mame64")]
self.assertEqual(own[0]["passes_to"], "command line -rp bios;<rom directory>")
self.assertEqual(
own[1]["search_dir"], "bios/hbmame/samples when hbmame, else bios/mame/samples"
@@ -698,7 +699,7 @@ class FolderArguments(unittest.TestCase):
def test_xroar_reassigned_folder_and_config_line(self):
# romPath is bios/dragon, rewritten to bios/coco for the coco system.
default, coco, config = xroar(_sources(**{
f"{G}/Xroar.Generator.cs": XROAR, retrobat_generators.FEATURES: XROAR_FEATURES,
f"{GENERATORS}/Xroar.Generator.cs": XROAR, retrobat_generators.FEATURES: XROAR_FEATURES,
}))
self.assertEqual(
(default["search_dir"], default["passes_to"], default.get("systems")),
@@ -757,12 +758,12 @@ PICO8 = """
class ProgramsRunFromEmulatorFolders(unittest.TestCase):
def test_pico8_runs_its_binary_from_its_emulator_folder(self):
(record,) = pico8(_sources(**{f"{G}/Pico8.Generator.cs": PICO8}))
(record,) = pico8(_sources(**{f"{GENERATORS}/Pico8.Generator.cs": PICO8}))
self.assertEqual(
(record["emulator"], record["kind"], record["names"], record["search_dir"],
record["passes_to"], record["source_ref"]),
("pico8", "fixed_name", ["pico8.exe"], '<AppConfig.GetFullPath("pico8")>', "exec",
f"{G}/Pico8.Generator.cs:3-7, 11-12"),
f"{GENERATORS}/Pico8.Generator.cs:3-7, 11-12"),
)
@@ -774,7 +775,7 @@ class EveryBiosReferenceIsRead(unittest.TestCase):
" }\n"
)
with self.assertRaises(LauncherPatternMissing) as caught:
eka2l1(_sources(**{f"{G}/Eka2l1.Generator.cs": extra}))
eka2l1(_sources(**{f"{GENERATORS}/Eka2l1.Generator.cs": extra}))
self.assertIn("bios reference at line", str(caught.exception))
def test_semicolon_inside_a_string_does_not_end_the_value(self):
+31
View File
@@ -371,6 +371,37 @@ class ModuleNames(unittest.TestCase):
self.assertEqual(found, [])
class TestModulesImportNoTestModule(unittest.TestCase):
"""FakeRepository lived in test_install_selection and fifteen modules
imported it from there: a module imported for a fixture loads its test
classes too, and a shared fixture belongs in a helper module."""
@staticmethod
def imported_test_modules(source: str) -> list[str]:
found = []
for node in ast.walk(ast.parse(source)):
if isinstance(node, ast.ImportFrom) and node.module:
names = [node.module] + [f"{node.module}.{a.name}" for a in node.names]
elif isinstance(node, ast.Import):
names = [a.name for a in node.names]
else:
continue
found += [name for name in names if name.startswith("tests.test_")][:1]
return found
def test_no_test_module_is_imported(self):
folder = Path(__file__).resolve().parent
found = [f"{path.name}: {name}" for path in sorted(folder.rglob("*.py"))
for name in self.imported_test_modules(path.read_text(encoding="utf-8"))]
self.assertEqual(found, [], "move what it shares into a helper module")
def test_both_forms_are_found(self):
self.assertEqual(self.imported_test_modules("from tests.test_x import y\n"), ["tests.test_x"])
self.assertEqual(self.imported_test_modules("import tests.test_x\n"), ["tests.test_x"])
self.assertEqual(self.imported_test_modules("from tests import test_x\n"), ["tests.test_x"])
self.assertEqual(self.imported_test_modules("from tests.sitepages import x\n"), [])
CODE_CEILING = 800
TEST_CEILING = 1500
+6 -44
View File
@@ -10,15 +10,15 @@ from __future__ import annotations
import tests
import io
import re
import subprocess
import tokenize
import unittest
from pathlib import Path
import yaml
from tests.docpagessupport import MARKETING_WORDS, _python_prose, _sentence_case
ROOT = Path(__file__).resolve().parent.parent
GLYPHS = re.compile(
@@ -67,20 +67,6 @@ def _semicolons(text: str) -> list[str]:
]
def _python_prose(source: str) -> str:
"""Comments and docstrings of a module, one per line."""
parts: list[str] = []
previous = tokenize.INDENT
for token in tokenize.generate_tokens(io.StringIO(source).readline):
if token.type == tokenize.COMMENT or token.type == tokenize.STRING and previous in (
tokenize.INDENT, tokenize.NEWLINE, tokenize.NL, tokenize.DEDENT,
):
parts.append(token.string)
if token.type not in (tokenize.COMMENT, tokenize.NL):
previous = token.type
return "\n".join(parts)
class _TagTolerantLoader(yaml.SafeLoader):
"""mkdocs.yml names Python callables with !!python/name tags."""
@@ -113,28 +99,6 @@ def _yaml_prose(text: str) -> str:
return "\n".join(parts)
# Words a heading keeps capitalized: names of platforms, systems and programs.
_HEADING_KEEP = set(["Batocera", "Recalbox", "Lakka", "Dolphin", "Redump", "Linux", "Windows", "Android", "Python", "Steam", "Deck", "macOS", "Termux", "Flatpak", "Switch", "Raspberry", "Pi", "Mega", "Drive", "Genesis", "Saturn", "Dreamcast", "Amiga", "Atari", "Sega", "Nintendo", "Sony", "Neo", "Geo", "Lynx", "Jaguar", "Commodore", "Apple", "Mac", "Spectrum", "Sinclair", "Amstrad", "MSX", "GameCube", "Wii", "Game", "Boy", "Advance", "Famicom", "Disk", "System", "Super", "Master", "PlayStation", "Vita", "Xbox", "Arcade", "English", "French", "Spanish", "I", "Lua", "Unity", "Qt", "Kodi", "Discord", "Pages", "Actions", "Docker", "Windows", "Mac", "Ubuntu", "Debian", "Arch", "SteamOS", "Chihiro", "NAOMI", "Triforce", "Lindbergh", "Model", "PinMAME", "ScummVM", "Dinothawr", "Cemu", "Citra", "Yuzu", "Ryujinx", "Mednafen", "Beetle", "Stella", "Hatari", "Caprice", "Vice", "Fuse", "Daphne", "Hypseus", "Singe", "Supermodel", "Flycast", "Redream", "DuckStation", "SwanStation", "Opera", "Gearsystem", "Picodrive", "Snes9x", "Nestopia", "Mesen", "Gambatte", "SameBoy", "mGBA", "melonDS", "DeSmuME", "Azahar", "Eden", "Sudachi", "Torzu", "Xemu", "Cxbx", "PCSX2", "AetherSX2", "NetherSX2", "ARMSX2", "RPCS3", "Vita3K", "Zinc", "Raine", "FBNeo", "FinalBurn", "Neo", "MAME", "Clrmamepro", "RomVault"])
def _sentence_case(title: str) -> str:
words = title.split(" ")
out = []
starts = True
for w in words:
core = w.strip("()[],:.")
if starts:
# The first word of a heading or of a clause after ":", "." or " - ".
head, sep, tail = core.partition("-")
if sep and re.fullmatch(r"[A-Z][a-z]+", tail) and tail not in _HEADING_KEEP:
w = w.replace(core, f"{head}-{tail.lower()}", 1)
elif re.fullmatch(r"[A-Z][a-z]+(-[A-Z]?[a-z]+)*", core) and core not in _HEADING_KEEP:
w = w.replace(core, core.lower(), 1)
out.append(w)
starts = w.endswith((":", ".")) or w == "-" or re.fullmatch(r"\d+[a-z]?\.?", w) is not None
return " ".join(out)
class NoGeneratedTypography(unittest.TestCase):
def test_no_dash_arrow_ellipsis_or_banner_glyphs(self):
offenders = []
@@ -161,16 +125,14 @@ class NoMarketingVocabulary(unittest.TestCase):
"""The project bans these words in published text, and nothing checked
it: "streamlined interface" reached the site's platform table."""
WORDS = re.compile(
r"\b(comprehensive|robust|seamless(ly)?|leverag\w*|streamlin\w*|delv(e|ing))\b",
re.IGNORECASE,
)
WORDS = MARKETING_WORDS
def test_no_tracked_text_uses_them(self):
offenders = []
for path in _tracked():
# This file and the commit rules have to name the words they refuse.
if path.name in {"test_prose_style.py", "commit_rules.py", "commitrules.py"}:
# The list, this file and the commit rules have to name the words they refuse.
if path.name in {"docpagessupport.py", "test_prose_style.py", "commit_rules.py",
"commitrules.py"}:
continue
text = path.read_text(encoding="utf-8", errors="replace")
for number, line in enumerate(text.splitlines(), 1):
+1 -1
View File
@@ -6,6 +6,7 @@ the fewest files the games need, and every address they give must exist.
from __future__ import annotations
import tests
from tests.sitepages import DIST
import re
import unittest
@@ -15,7 +16,6 @@ from sitegen import agents as siteagents
REPO_ROOT = Path(__file__).resolve().parent.parent
DIST = REPO_ROOT / "website" / "dist"
TOOLS = REPO_ROOT / "website" / "src" / "scripts" / "agent-tools.ts"
FOOTER = REPO_ROOT / "website" / "src" / "components" / "Footer.astro"
CONFIG = REPO_ROOT / "website" / "astro.config.mjs"
+1 -1
View File
@@ -16,6 +16,7 @@ Skips when the site is not built.
from __future__ import annotations
import tests
from tests.sitepages import DIST
import json
import re
@@ -27,7 +28,6 @@ import yaml
REPO_ROOT = Path(__file__).resolve().parents[1]
DIST = REPO_ROOT / "website" / "dist"
DOCS = REPO_ROOT / "website" / "src" / "content" / "docs"
SIDEBAR = REPO_ROOT / "website" / "src" / "generated" / "sidebar.json"
BASE = "/retrobios/"
+1 -4
View File
@@ -20,6 +20,7 @@ from __future__ import annotations
import tests
from tests.sources import script_source
from tests.sitepages import DIST
import json
import re
@@ -35,12 +36,8 @@ import sys
from model.registry import list_release_pack_platforms
REPO_ROOT = Path(__file__).resolve().parents[1]
REPO_ROOT = Path(__file__).resolve().parents[1]
WEBSITE = REPO_ROOT / "website"
DIST = WEBSITE / "dist"
COMPONENTS = WEBSITE / "src" / "components"
SITE_TS = WEBSITE / "src" / "scripts" / "site.ts"
HASHES_TS = WEBSITE / "src" / "scripts" / "hashes.ts"
+10 -247
View File
@@ -18,23 +18,22 @@ import re
import statistics
import sys
import unittest
from dataclasses import dataclass, field
from pathlib import Path
from tests import sitepages
from tests.sitecopy import (
Block,
Page,
START_PAGES,
_docs,
_load,
count_words,
parse,
split_sentences,
)
DOCS = sitepages.CONTENT
# Level 0: the Start here pages, with their own ceiling on words.
START_PAGES = {
"index.md": 220,
"which-pack.md": 400,
"wiki/what-are-bios-files.md": 300,
"wiki/first-install.md": 400,
"wiki/troubleshooting.md": 300,
"wiki/faq.md": 450,
"wiki/glossary.md": 200,
}
# Reference pages written for anyone, held to the Start here budgets.
START_LEVEL_PAGES = {
"wiki/measurements.md": 300,
@@ -95,233 +94,6 @@ START_ONLY = {"pack": None, "packs": None, "platform": None, "platforms": None}
# A word glossed in place: "X, a ...", "X (a ...", "called X".
GENERIC_GLOSS = r"(?:{w}\*{{0,2}}, an? |{w}\*{{0,2}} \(an? |called \*{{0,2}}{w})"
WORD = re.compile(r"[A-Za-z0-9][A-Za-z0-9'._/\\:%~-]*")
SENTENCE_END = re.compile(r"(?<=[.!?])\s+(?=[A-Z`\"(*\[])")
@dataclass
class Block:
kind: str # paragraph, item, term, definition, heading, table
text: str
collapsed: bool = False
defines: str = ""
hidden: bool = False # in a tab other than the first: read instead of the first
@dataclass
class Page:
blocks: list[Block] = field(default_factory=list)
before_action: int | None = None
list_runs: list[int] = field(default_factory=list)
def prose(self) -> list[Block]:
return [b for b in self.blocks if b.kind in ("paragraph", "item", "term", "definition")]
def words(self) -> int:
return sum(count_words(b.text) for b in self.blocks if b.kind != "table" and not b.hidden)
def sentences(self) -> list[str]:
return [s for b in self.prose() for s in split_sentences(b.text)]
def strip_inline(text: str) -> str:
"""Link text kept, targets, attribute lists, images and markup dropped."""
text = re.sub(r"!\[[^\]]*\]\([^)]*\)(\{[^}]*\})?", "", text)
text = re.sub(r"\[([^\]]*)\]\([^)]*\)", r"\1", text)
text = re.sub(r"\{\s*[#.:][^}]*\}", "", text)
text = re.sub(r"<[^>]+>", "", text)
return text.replace("**", "").strip()
def count_words(text: str) -> int:
return len(WORD.findall(re.sub(r"`[^`]*`", "code", text)))
def split_sentences(text: str) -> list[str]:
return [s for s in SENTENCE_END.split(text.strip()) if WORD.search(s)]
def guide_part(markdown: str) -> str:
"""A page up to its Reference heading, without front matter."""
if markdown.startswith("---\n"):
markdown = markdown.split("\n---\n", 1)[1]
match = re.search(r"^## Reference\b", markdown, re.M)
return markdown[: match.start()] if match else markdown
class _PageParser:
"""The state parse() carries from one line to the next."""
def __init__(self) -> None:
self.page = Page()
self.seen_words = 0
self.details = 0 # depth of collapsed blocks
self.tab = 0 # the tab of a group being read, 0 outside a group
self.fence: str | None = None
self.current: list[str] = []
self.kind = "paragraph"
self.run = 0
def flush(self) -> None:
page = self.page
if self.current:
body = strip_inline(" ".join(self.current))
if WORD.search(body):
kind = self.kind
term = page.blocks[-1].text.lower() if kind == "definition" and page.blocks else ""
block = Block(kind, body, self.details > 0, term, self.tab > 1)
page.blocks.append(block)
if (page.before_action is None and not block.collapsed
and not block.hidden and kind not in ("table", "heading")):
self.seen_words += count_words(body)
self.current = []
if self.kind in ("item", "definition", "heading"):
self.kind = "paragraph"
def act(self) -> None:
self.flush()
if self.page.before_action is None:
self.page.before_action = self.seen_words
def end_run(self) -> None:
if self.run:
self.page.list_runs.append(self.run)
self.run = 0
def feed(self, raw: str) -> None:
line = raw.rstrip()
stripped = line.strip()
indent = len(line) - len(line.lstrip())
if self.fence:
if stripped.startswith(self.fence):
self.fence = None
return
if self._markup(stripped):
return
if stripped.startswith("#"):
self._heading(stripped)
return
if stripped.startswith("|"):
self._table_row(stripped)
return
self._prose(stripped, indent)
def _markup(self, stripped: str) -> bool:
"""Fences, blank lines and HTML: True when the line is consumed."""
if stripped.startswith(("```", "~~~")):
self.fence = stripped[:3]
if self.tab < 2:
self.act()
return True
if not stripped:
self.flush()
return True
if stripped.startswith("import ") and stripped.endswith(";"):
return True
if stripped.startswith(":::"):
self.flush()
return True
if self._container(stripped):
return True
if "rb-button" in stripped or "rb-tile" in stripped or stripped.startswith(
("<FilePicker", "<WantedFiles")):
self.act()
return True
if re.match(r"</?(?!abbr\b|a\b|code\b|strong\b|em\b)[A-Za-z]", stripped):
self.flush()
return True
return False
def _container(self, stripped: str) -> bool:
"""Collapsed blocks and tab groups: True when the line is consumed."""
if stripped.startswith("<details"):
self.flush()
self.details += 1
return True
if stripped.startswith("</details>"):
self.flush()
self.details = max(0, self.details - 1)
return True
if stripped.startswith("<Tabs"):
self.flush()
self.tab = 0
return True
if stripped.startswith("<TabItem"):
self.flush()
self.tab += 1
return True
if stripped.startswith("</Tabs>"):
self.flush()
self.tab = 0
return True
return False
def _heading(self, stripped: str) -> None:
self.flush()
self.end_run()
self.kind = "heading"
self.current = [re.sub(r"\s*\{[^}]*\}\s*$", "", stripped.lstrip("#").strip())]
self.flush()
self.kind = "paragraph"
def _table_row(self, stripped: str) -> None:
if self.kind != "table":
self.flush()
self.kind = "table"
if not re.fullmatch(r"\|[\s:|-]+\|?", stripped):
self.current.append(stripped.replace("|", " "))
def _prose(self, stripped: str, indent: int) -> None:
if self.kind == "table":
self.flush()
self.kind = "paragraph"
item = re.match(r"(?:[-*+]|\d+\.)\s+(.*)", stripped)
definition = re.match(r":\s+(.*)", stripped)
if item:
self.flush()
self.kind = "item"
self.run += 1
self.current = [item.group(1)]
return
if definition:
self.flush()
page = self.page
if page.blocks and page.blocks[-1].kind == "paragraph":
page.blocks[-1].kind = "term"
self.kind = "definition"
self.current = [definition.group(1)]
return
if self.kind == "item" and indent == 0:
self.flush()
self.kind = "paragraph"
if self.kind == "paragraph":
self.end_run()
if not self.current and self.kind in ("item", "definition") and indent == 0:
self.kind = "paragraph"
self.current.append(stripped)
def finish(self) -> Page:
self.flush()
if self.run:
self.page.list_runs.append(self.run)
return self.page
def parse(markdown: str) -> Page:
"""Blocks of prose a reader sees, code and HTML left out.
A collapsed block (<details>) counts, but not before the first action:
the reader opens it on purpose. Of a group of tabs the first is read and
the others only stand in for it.
"""
text = guide_part(markdown)
text = re.sub(r"<script.*?</script>", "", text, flags=re.S)
text = re.sub(r"<!--.*?-->", "", text, flags=re.S)
parser = _PageParser()
for raw in text.splitlines():
parser.feed(raw)
return parser.finish()
def banned(block: Block, level: str) -> list[str]:
"""Filler, and jargon met without its meaning beside it."""
@@ -380,15 +152,6 @@ def held_pages(docs: Path) -> list[tuple[str, str, int]]:
if sitepages.page(name).is_file()]
def _docs() -> Path:
return sitepages.require()
def _load(name: str) -> Page:
_docs()
return parse(sitepages.page(name).read_text(encoding="utf-8"))
class CopyBudgets(unittest.TestCase):
def test_sentences_stay_short(self):
for name, level, _ceiling in held_pages(_docs()):
+1 -1
View File
@@ -13,6 +13,7 @@ from __future__ import annotations
import tests
from tests.sources import script_source
from tests.sitepages import DIST
import json
import re
@@ -29,7 +30,6 @@ ROOT = Path(__file__).resolve().parent.parent
DEMO = ROOT / "docs_assets" / "demo"
COMPONENT = ROOT / "website" / "src" / "components" / "InstallDemo.astro"
DIST = ROOT / "website" / "dist"
def _all_facts() -> dict:
+1 -1
View File
@@ -11,6 +11,7 @@ sits in closed folds, every fact still on the page.
from __future__ import annotations
import tests
from tests.sitepages import DIST
import re
import types
@@ -25,7 +26,6 @@ from sitegen import markup
REPO_ROOT = Path(__file__).resolve().parents[1]
DIST = REPO_ROOT / "website" / "dist"
SITE_TS = REPO_ROOT / "website" / "src" / "scripts" / "site.ts"
SHA1 = "30a33f3651f8e1b0967a5dfe6ff714baebcce41a"
+1 -1
View File
@@ -29,6 +29,7 @@ from __future__ import annotations
import tests
from tests import sitepages
from tests.sitepages import DIST
import re
import unittest
@@ -237,7 +238,6 @@ class TheIndexNamesEmulatorsAndSystems(unittest.TestCase):
self.assertNotIn("sony-playstation |", row)
DIST = REPO_ROOT / "website" / "dist"
def _emulator_page(name: str, profile: dict | None = None) -> str:
+1 -1
View File
@@ -11,6 +11,7 @@ every name and hash back.
from __future__ import annotations
import tests
from tests.sitepages import DIST
import re
import unittest
@@ -28,7 +29,6 @@ from sitegen import validate
REPO_ROOT = Path(__file__).resolve().parents[1]
EMPTY_DB = {"files": {}, "indexes": {"by_name": {}}}
DIST = REPO_ROOT / "website" / "dist"
def _archive(i: int, members: int = 3, **fields: object) -> dict:
+1 -1
View File
@@ -11,6 +11,7 @@ from __future__ import annotations
import tests
from tests import mdsections
from tests.sitepages import DIST
import glob
import json
@@ -33,7 +34,6 @@ from model import collection
REPO_ROOT = Path(__file__).resolve().parents[1]
DIST = REPO_ROOT / "website" / "dist"
def _profile(name: str) -> dict:
+2 -44
View File
@@ -41,56 +41,15 @@ from sitegen import parts
from sitegen import starlight as sitestarlight
from sitegen import sidebartopics
from core import anchors as core_anchors
from model.registry import list_registered_platforms, load_platform_registry
from model.platforms import load_platform_config
from model.registry import list_registered_platforms
from sitegen.guidedata import device_groups
from tests.sitepages import ANCHORS, DIST, _index_anchors, _nav, _present
REPO_ROOT = Path(__file__).resolve().parents[1]
DIST = REPO_ROOT / "website" / "dist"
ROUTE = REPO_ROOT / "website" / "src" / "routeData.ts"
TAB_ROOTS = {"/retrobios/", "/retrobios/platforms/", "/retrobios/explore/",
"/retrobios/wiki/", "/retrobios/contributing/"}
def _nav() -> list:
platforms = REPO_ROOT / "platforms"
registry = load_platform_registry(str(platforms))
coverages = {
key: {"platform": load_platform_config(key, str(platforms))["platform"]}
for key in list_registered_platforms(str(platforms))
}
manufacturers = {"Sony": {}, "Sega": {}, "ScummVM": {}}
profiles = {
"duckstation": {"emulator": "DuckStation", "systems": ["sony-playstation"]},
"dolphin": {"emulator": "Dolphin", "systems": ["nintendo-gamecube"]},
"mame": {"emulator": "MAME", "systems": ["arcade"]},
}
return sitegen_nav.generate_nav(coverages, manufacturers, profiles, registry)
def _targets(value: object) -> set[str]:
if isinstance(value, str):
return {value}
if isinstance(value, list):
return set().union(*(_targets(v) for v in value)) if value else set()
return set().union(*(_targets(v) for v in value.values()))
def _present(nav: list) -> set[str]:
return {t for t in _targets(nav) if not t.startswith("http")}
def _index_anchors(markdown: str) -> set[str]:
"""The heading ids a generated page carries once written."""
_title, title_id, body = sitestarlight.split_title(markdown)
return sitestarlight.heading_ids(sitestarlight.pin_heading_ids(body, title_id))
ANCHORS = {
"platforms/index.md": {core_anchors.toc_slug(label) for label, _ in device_groups().values()},
"systems/index.md": {"consoles-and-computers"},
"emulators/index.md": _index_anchors(emulatorsindex.generate_emulators_index({
"duckstation": {"emulator": "DuckStation", "systems": ["sony-playstation"]},
"dolphin": {"emulator": "Dolphin", "systems": ["nintendo-gamecube"]},
"mame": {"emulator": "MAME", "systems": ["arcade"]},
})),
}
class NotFoundPage(unittest.TestCase):
@@ -364,7 +323,6 @@ class PlatformShareCards(unittest.TestCase):
self.assertFalse(any(tag.get("attrs", {}).get("property") == "og:title" for tag in plain))
# The built site
+1 -1
View File
@@ -13,6 +13,7 @@ styles, and hold the page to one reading of each thing it says.
from __future__ import annotations
import tests
from tests.sitepages import DIST
import json
import re
@@ -31,7 +32,6 @@ ROOT = Path(__file__).resolve().parent.parent
WEBSITE = ROOT / "website"
DOCS = WEBSITE / "src" / "content" / "docs"
DIST = WEBSITE / "dist"
PLUGIN = WEBSITE / "src" / "plugins" / "rehype-stack-tables.mjs"
SATTERI = WEBSITE / "node_modules" / "satteri" / "dist" / "index.js"
+1 -100
View File
@@ -11,8 +11,6 @@ from __future__ import annotations
import tests
import html
import re
import subprocess
import sys
import unittest
@@ -20,108 +18,11 @@ from functools import cache
from pathlib import Path
from tests.scratchtree import scratch_checkout
from tests.sitepages import INSTALLER, NAMES, SOURCE, pronouns
ROOT = Path(__file__).resolve().parent.parent
DOCS = Path("website") / "src" / "content" / "docs"
PRONOUN = re.compile(
r"(?<![\w-])((?-i:I)|me|my|mine|myself|we|us|our|ours|ourselves"
r"|you|your|yours|yourself|yourselves)(?![\w-])",
re.I,
)
FENCED = re.compile(r"^[ \t]*(```|~~~).*?^[ \t]*\1[^\n]*$", re.S | re.M)
INLINE_CODE = re.compile(r"(`+)(?:(?!\n\n)[^`])*?\1")
HTML_COMMENT = re.compile(r"<!--.*?-->", re.S)
SCRIPT_STYLE = re.compile(r"<(script|style|pre|code)\b.*?</\1>", re.S | re.I)
TAG = re.compile(r"</?[A-Za-z][^<>]*>")
ENTITY = re.compile(r"&#(?:\d+|x[0-9a-fA-F]+);")
URL = re.compile(r"(?:https?|ftp|smb)://\S+|\bwww\.\S+")
LINK_TARGET = re.compile(r"\]\([^)\s]*(?:\s+\"[^\"]*\")?\)|^\[[^\]]+\]:\s*\S+.*$", re.M)
ANCHOR = re.compile(r"\{[^{}\n]*#[^{}\n]*\}")
PATHLIKE = re.compile(r"\S*[/\\]\S*")
# File names, domains and dotted initials: baserom.us.z64, delete.me, A.I.R.
DOTTED = re.compile(r"[\w-]+(?:\.[\w-]+)+\.?")
# A list of single letters or digits (D, F, I, P), or of lowercase option
# values in parentheses (euro, us, asia), names keys, not people.
LETTERS = re.compile(r"(?<!\w)[A-Z0-9](?:,\s?[A-Z0-9#@^](?!\w))+")
VALUES = re.compile(r"\((?:[a-z][\w-]*, )+[a-z][\w-]*\)")
LETTER_HEADING = re.compile(r"^#+ [A-Z]\s*$", re.M)
# Search keywords, written the way readers type a query. Pagefind matches
# them, the page never shows them.
TERMS = re.compile(r"^terms: .*$", re.M)
# A capitalised "US" names the country and its region code.
COUNTRY = re.compile(r"(?<![\w-])US(?![\w-])")
# Proper names that hold one of the words.
NAMES: dict[str, str] = {
r"I(?:'|''|&#x27;|&#39;)Max": "I'Max MACS, an arcade board maker",
r"My (?:Old)?Boy!": "My Boy! and My OldBoy!, Android emulators",
r"My Vision": "Nichibutsu My Vision, a console",
r"On My iPhone": "the Files app location on iOS",
r"Us vs Them": "a game title",
r"Aliens Ate My Railway|Fell Apart On Me": "OpenTTD music track titles",
r"\b(?:Model|Level|Series|Mk|MK|Ultima|Interface|Type) I\b(?!')":
"a roman numeral in a machine or game name (Model I, Ultima I)",
r"\bI(?= \([A-Z])": "a model letter, I (Palladium)",
r"Java ME": "Java ME, the mobile Java platform",
r"\bME(?=,? (?:and )?MA\b)": "FM Towns ME, a model name beside the MA (geartowns)",
r"laseractive us(?=:)": "the LaserActive region key of geargrafx's BIOS list",
}
# Program output quoted word for word. INSTALLER holds install.py's own
# messages, empty since the installer speaks without pronouns. SOURCE holds what an emulator prints, quoted in its
# profile from the emulator's code, which this project does not write.
INSTALLER: dict[str, str] = {}
SOURCE: dict[str, str] = {
"You do not have a ROM image installed for Model": "sdltrs message, emulators/sdl2trs.yml",
"You might not get sound because": "lindbergh-loader message, emulators/lindbergh-loader.yml",
'"Your Card"': "KEGS disk name, emulators/kegs.yml",
"How do I use SC3000": "MG.html question title, emulators/mastergear.yml",
"How do I use SF7000 disk images?": "MG.html question title, emulators/mastergear.yml",
"There is no version of MG for my Unix!": "MG.html question title, emulators/mastergear.yml",
"rename your own SFX dat file to this name": "Zelda Classic README, emulators/zc210.yml",
"Could not load ROM images! You must supply these.":
"hypseus message, emulators/hypseus-singe.yml",
"Please copy pak0.pk3 from the 'etmain' path of your":
"ET: Legacy message, emulators/etlegacy.yml",
'"keyconf.dat(us)"': "file name px68k ships, emulators/px68k-sdl.yml",
}
_SPACED = [
re.compile(r"\s+".join(map(re.escape, phrase.split())))
for phrase in (*INSTALLER, *SOURCE)
]
_NAMES = [re.compile(pattern) for pattern in NAMES]
def _blank(match: re.Match[str]) -> str:
return re.sub(r"[^\n]", " ", match[0])
def prose(text: str) -> str:
"""The text of a page with everything that is not prose blanked."""
for pattern in (HTML_COMMENT, SCRIPT_STYLE, TAG):
text = pattern.sub(_blank, text)
# &#95; and &#x27; spell a file name or a name: read them as characters.
text = ENTITY.sub(lambda m: html.unescape(m[0]), text)
for pattern in (
*_SPACED, FENCED, INLINE_CODE, LINK_TARGET, URL, ANCHOR, PATHLIKE,
TERMS, *_NAMES, DOTTED, LETTERS, VALUES, LETTER_HEADING, COUNTRY,
):
text = pattern.sub(_blank, text)
return text
def pronouns(text: str) -> list[tuple[int, str]]:
"""(line number, line) for each prose line holding a personal pronoun."""
lines = text.splitlines()
return [
(number, lines[number - 1].strip())
for number, line in enumerate(prose(text).splitlines(), 1)
if PRONOUN.search(line)
]
def _hits(paths: list[Path], root: Path = ROOT) -> list[str]:
return [
+16 -16
View File
@@ -44,7 +44,7 @@ from model.registry import list_release_pack_platforms
from model import releaserecord
from acquire.provenance import build_report
from model.dumpcatalog import load_provenance_snapshots
from tests.sitereferencesupport import API, DIST, PUBLIC, REPO_ROOT, SITE, _built
from tests.sitepages import API, DIST, PUBLIC, REPO_ROOT, SITE, built
class ExportsComplete(unittest.TestCase):
@@ -134,11 +134,11 @@ class TheExportsKeepWhatACheckNeeds(unittest.TestCase):
self.assertIn(field, exportrows.ENTRY_EXPORT_FIELDS)
def test_the_built_csv_has_the_column(self):
text = _built(PUBLIC / "downloads" / "platform-files.csv").read_text(encoding="utf-8")
text = built(PUBLIC / "downloads" / "platform-files.csv").read_text(encoding="utf-8")
rows = list(csv.DictReader(io.StringIO(text)))
batocera = [row for row in rows if row["platform_id"] == "batocera"]
self.assertGreater(sum(1 for row in batocera if row["zipped_file"]), 300)
with sqlite3.connect(_built(PUBLIC / "downloads" / "retrobios.sqlite")) as db:
with sqlite3.connect(built(PUBLIC / "downloads" / "retrobios.sqlite")) as db:
count = db.execute("SELECT count(*) FROM platform_files "
"WHERE platform_id = 'batocera' AND zipped_file != ''").fetchone()[0]
license_row = db.execute("SELECT value FROM metadata WHERE key = 'license'").fetchone()
@@ -184,7 +184,7 @@ class TheContractsValidate(unittest.TestCase):
self.assertEqual(schema.get("$id"), f"{SITE}api/v1/schemas/{path.name}")
def test_every_schema_is_published(self):
published = {p.name for p in _built(API / "schemas").glob("*.json")}
published = {p.name for p in built(API / "schemas").glob("*.json")}
self.assertEqual(published, {p.name for p in (REPO_ROOT / "schemas").glob("*.schema.json")})
def test_the_built_api_validates(self):
@@ -196,7 +196,7 @@ class TheContractsValidate(unittest.TestCase):
schemas = {p.name: json.loads(p.read_text()) for p in (REPO_ROOT / "schemas").glob("*.json")}
envelope = Draft202012Validator(schemas["site-api-envelope.schema.json"])
platform = Draft202012Validator(schemas["platform.schema.json"])
document = json.loads(_built(API / "platforms.json").read_text())
document = json.loads(built(API / "platforms.json").read_text())
self.assertEqual(list(envelope.iter_errors(document)), [])
for item in document["items"]:
with self.subTest(platform=item["id"]):
@@ -213,8 +213,8 @@ class TheIndexSaysWhatTheCatalogLists(unittest.TestCase):
in none of its 80 items."""
def test_the_description_matches_the_items(self):
index = json.loads(_built(API / "index.json").read_text())
catalog = json.loads(_built(API / "catalog.json").read_text())
index = json.loads(built(API / "index.json").read_text())
catalog = json.loads(built(API / "catalog.json").read_text())
described = next(i["description"] for i in index["items"] if i["url"] == "catalog.json")
self.assertNotIn("Every published file", described)
listed = {item["url"].split("/", 1)[0] for item in catalog["items"]}
@@ -237,7 +237,7 @@ class EveryEnvelopeCarriesTheCommit(unittest.TestCase):
self.assertIn("source_commit()", block)
def test_every_built_envelope_has_it(self):
_built(API / "catalog.json")
built(API / "catalog.json")
if not exportrows.source_commit():
raise unittest.SkipTest("not a git checkout")
lacking = [
@@ -253,7 +253,7 @@ class ManifestsArePublished(unittest.TestCase):
"""8.2: the manifest a pack installs, byte for byte, in the catalog."""
def test_each_manifest_is_the_repository_file(self):
catalog = json.loads(_built(API / "catalog.json").read_text())
catalog = json.loads(built(API / "catalog.json").read_text())
listed = {item["url"]: item for item in catalog["items"]}
for source in sorted((REPO_ROOT / "install").glob("*.json")):
with self.subTest(manifest=source.name):
@@ -298,7 +298,7 @@ class AnIdLeadsToItsData(unittest.TestCase):
def test_the_built_index_resolves_ids_to_sections(self):
items = {item["id"]: item for item in
json.loads(_built(API / "systems.json").read_text())["items"]}
json.loads(built(API / "systems.json").read_text())["items"]}
color = items["wonderswan-color"]
self.assertEqual(color["name"], "Bandai WonderSwan Color")
self.assertTrue(color["url"].startswith("/retrobios/systems/bandai/"), color["url"])
@@ -328,7 +328,7 @@ class ManifestFieldsAreComplete(unittest.TestCase):
self.assertIn(f"| `{key}` |", page)
def test_no_link_carries_an_escaped_bracket(self):
html = _built(DIST / "data" / "index.html").read_text(encoding="utf-8")
html = built(DIST / "data" / "index.html").read_text(encoding="utf-8")
self.assertNotRegex(html, r'href="[^"]*&amp;lt;')
self.assertNotRegex(html, r'href="[^"]*&lt;')
@@ -337,7 +337,7 @@ class EverySystemIdWithFilesHasAPage(unittest.TestCase):
"""8.5: tyrian, scummvm, dos and 25 more had files and a null url."""
def test_built_index(self):
items = json.loads(_built(API / "systems.json").read_text())["items"]
items = json.loads(built(API / "systems.json").read_text())["items"]
orphans = [item["id"] for item in items if item["sha1"] and not item["url"]]
self.assertEqual(orphans, [])
@@ -388,7 +388,7 @@ class OneAnswerOnReleasePacks(unittest.TestCase):
def test_api_release_pack_set_equals_the_registry(self):
found = set()
for path in _built(API / "platforms").glob("*.json"):
for path in built(API / "platforms").glob("*.json"):
item = json.loads(path.read_text())["items"][0]
if item["registry"].get("release_pack"):
found.add(item["id"])
@@ -403,7 +403,7 @@ class OneAnswerOnReleasePacks(unittest.TestCase):
self.assertLessEqual(served, _released())
def test_the_built_picker_file(self):
written = json.loads(_built(GENERATED / "release-advertised.json").read_text())
written = json.loads(built(GENERATED / "release-advertised.json").read_text())
self.assertEqual(written, releaserecord.load_advertised())
@@ -461,7 +461,7 @@ class TheDataPageListsWhatIsServed(unittest.TestCase):
self.assertIn(f"- [`{path.name}`](api/v1/schemas/{path.name}): ", page)
def test_target_lists_are_published_and_catalogued(self):
catalog = json.loads(_built(API / "catalog.json").read_text())
catalog = json.loads(built(API / "catalog.json").read_text())
listed = {item["url"] for item in catalog["items"]}
for source in (REPO_ROOT / "install" / "targets").glob("*.json"):
self.assertIn(f"targets/{source.name}", listed)
@@ -483,7 +483,7 @@ class SystemItemsCarryTheirApi(unittest.TestCase):
"""8.7."""
def test_each_api_address_is_served(self):
items = json.loads(_built(API / "systems.json").read_text())["items"]
items = json.loads(built(API / "systems.json").read_text())["items"]
playstation = next(i for i in items if i["id"] == "sony-playstation")
self.assertEqual(playstation["api"], "/retrobios/api/v1/systems/sony.json")
for item in items:
+7 -7
View File
@@ -30,7 +30,7 @@ from sitegen import cards
from sitegen import datapage
from sitegen import lookup
import check_platform_folder
from tests.sitereferencesupport import API, PUBLIC, REPO_ROOT, SITE, _built
from tests.sitepages import API, PUBLIC, REPO_ROOT, SITE, built
def _verify_status(entry: dict, path: Path, mode: str) -> str:
@@ -96,7 +96,7 @@ class AFolderCheckAgreesWithTheVerifier(unittest.TestCase):
"""A check driven by platform-files.csv, with zipped_file, gives the
verifier's verdict on every Batocera entry of a folder filled from
the collection."""
text = _built(PUBLIC / "downloads" / "platform-files.csv").read_text(encoding="utf-8")
text = built(PUBLIC / "downloads" / "platform-files.csv").read_text(encoding="utf-8")
rows = [row for row in csv.DictReader(io.StringIO(text)) if row["platform_id"] == "batocera"]
with tempfile.TemporaryDirectory() as tmp:
root = Path(tmp)
@@ -113,7 +113,7 @@ class AFolderCheckAgreesWithTheVerifier(unittest.TestCase):
if len(held) < 100:
raise unittest.SkipTest("the collection files are not in this checkout")
# The verifier reads the platform's own entries, the check the CSV.
contract = json.loads(_built(API / "platforms" / "batocera.json").read_text())[
contract = json.loads(built(API / "platforms" / "batocera.json").read_text())[
"items"][0]["contract"]
declared = [entry for _sys, system in sorted(contract["systems"].items())
for entry in system.get("files") or []]
@@ -187,12 +187,12 @@ class LookupUrlsResolve(unittest.TestCase):
self.assertEqual(by_layer[layer]["system_name"], expected)
def test_built_shards_carry_the_name(self):
shard = json.loads(_built(API / "lookup" / "05.json").read_text())
shard = json.loads(built(API / "lookup" / "05.json").read_text())
record = next(r for r in shard["items"] if r["value"].startswith("0555c6fae890"))
self.assertEqual(record["system_name"], "Sony PlayStation")
def test_built_records_land_on_built_pages(self):
shard = json.loads(_built(API / "lookup" / "05.json").read_text())
shard = json.loads(built(API / "lookup" / "05.json").read_text())
dist = REPO_ROOT / "website" / "dist"
for record in shard["items"][:200]:
with self.subTest(url=record["url"]):
@@ -243,7 +243,7 @@ class LookupRecordsUnderEveryHash(unittest.TestCase):
db = json.loads((REPO_ROOT / "database.json").read_text(encoding="utf-8"))
sha1 = "0555c6fae8906f3f09baf5988f00e55f88e9f30b"
entry = db["files"][sha1]
_built(API / "lookup")
built(API / "lookup")
answers = []
for algorithm in ("sha1", "md5", "crc32", "sha256"):
value = str(entry[algorithm]).lower()
@@ -344,7 +344,7 @@ class LookupCountsEmulatorsLikeTheCard(unittest.TestCase):
def test_scph5501_names_the_cards_eleven(self):
sha1 = "0555c6fae8906f3f09baf5988f00e55f88e9f30b"
shard = json.loads(_built(API / "lookup" / f"{sha1[:2]}.json").read_text())
shard = json.loads(built(API / "lookup" / f"{sha1[:2]}.json").read_text())
owners = {r["owner"] for r in shard["items"]
if r["value"] == sha1 and r["layer"] == "emulator"}
self.assertGreaterEqual(len(owners), 11)
+5 -5
View File
@@ -62,7 +62,7 @@ from sitegen import sources
from core import upstream
from core import forgehttp
from packs.verdicts import Severity, blocking_missing, compute_severity
from tests.sitereferencesupport import DIST, REPO_ROOT, _built
from tests.sitepages import DIST, REPO_ROOT, built
PLATFORMS = str(REPO_ROOT / "platforms")
@@ -586,7 +586,7 @@ class SourceLinksOnlyWhereTheFileIs(unittest.TestCase):
def test_every_rendered_link_is_recorded(self):
record = json.loads(sources.SOURCE_PATHS.read_text(encoding="utf-8"))
pages = sorted(_built(DOCS / "emulators").rglob("*.md*")) + sorted(DOCS.glob("gaps*.md*"))
pages = sorted(built(DOCS / "emulators").rglob("*.md*")) + sorted(DOCS.glob("gaps*.md*"))
from model import measurements as mr
# A Tested block links a record line and its data file in this
@@ -644,7 +644,7 @@ class TheReferencePagesAnswerTheirWords(unittest.TestCase):
"(`native_list: none`). An empty list does not mean nothing is needed.", page)
def test_overview_ids_and_counts_are_not_indexed(self):
html = _built(DIST / "platforms" / "batocera" / "index.html").read_text(encoding="utf-8")
html = built(DIST / "platforms" / "batocera" / "index.html").read_text(encoding="utf-8")
self.assertRegex(html, r"<small data-pagefind-ignore(=\"true\")?>sony-playstation</small>")
self.assertRegex(html, r"<span data-pagefind-ignore(=\"true\")?>\d+/\d+</span>")
@@ -660,7 +660,7 @@ class NoEmptyCoreTable(unittest.TestCase):
self.assertIn(platformpage.OWN_LIST_ONLY, page)
def test_built_pages(self):
_built(DOCS / "cross-reference.md")
built(DOCS / "cross-reference.md")
for name in ("misterfpga", "bizhawk"):
self.assertFalse((DOCS / f"cross-reference-{name}.md").exists())
page = sitepages.page(f"platforms/{name}.md").read_text(encoding="utf-8")
@@ -674,7 +674,7 @@ class FilesToSourceOnAPhone(unittest.TestCase):
"""8.12: 601 rows on one page, no way to give a file."""
def test_parts_of_a_hundred_rows_each_with_an_upload(self):
_built(DOCS / "gaps-files-to-source.md")
built(DOCS / "gaps-files-to-source.md")
parts = sorted(DOCS.glob("gaps-files-to-source*.md"))
self.assertGreater(len(parts), 1)
for part in parts:
+1 -2
View File
@@ -42,7 +42,7 @@ from sitegen import sidebartopics
from sitegen import validate
from model.registry import list_registered_platforms
from model.profiles import load_emulator_profiles
from tests.test_site_nav import ANCHORS, _nav, _present
from tests.sitepages import ANCHORS, DIST, _nav, _present
REPO_ROOT = Path(__file__).resolve().parents[1]
@@ -50,7 +50,6 @@ REPO_ROOT = Path(__file__).resolve().parents[1]
TOOLS = REPO_ROOT / "website" / "tools"
WORKFLOW = REPO_ROOT / ".github" / "workflows" / "deploy-site.yml"
DOCS = REPO_ROOT / "website" / "src" / "content" / "docs"
DIST = REPO_ROOT / "website" / "dist"
def _front(text: str) -> dict:
+1 -1
View File
@@ -10,6 +10,7 @@ and the words never disagree. And it draws in the theme's colours.
from __future__ import annotations
import tests
from tests.sitepages import DIST
import re
import unittest
@@ -23,7 +24,6 @@ from sitegen.guidedata import terminals
ROOT = Path(__file__).resolve().parent.parent
SVG = "{http://www.w3.org/2000/svg}"
DIST = ROOT / "website" / "dist"
class EachDrawingNamesItsSteps(unittest.TestCase):
+1 -1
View File
@@ -31,6 +31,7 @@ three times before the first file.
from __future__ import annotations
import tests
from tests.sitepages import DIST
import re
import tempfile
@@ -63,7 +64,6 @@ from core.anchors import toc_slug
REPO_ROOT = Path(__file__).resolve().parents[1]
DIST = REPO_ROOT / "website" / "dist"
def _sony_file(name: str, char: str, path: str = "") -> dict:
-15
View File
@@ -320,21 +320,6 @@ class EveryTestDependencyIsInstalledInCi(unittest.TestCase):
class TheTestingGuideNamesEveryModule(unittest.TestCase):
"""The guide described 18 modules of 144, and a contributor touching
slots.py or the downloader found no module named for it."""
def test_every_module_is_in_the_table(self):
root = Path(__file__).resolve().parents[1]
guide = (root / "wiki" / "testing-guide.md").read_text(encoding="utf-8")
missing = sorted(
path.stem for path in (root / "tests").glob("test_*.py")
if f"`{path.stem}`" not in guide
)
self.assertEqual(missing, [])
class TheSitemapIsAnnouncedWhereCrawlersLook(unittest.TestCase):
"""robots.txt was published as /retrobios/robots.txt, which no crawler
reads (RFC 9309 reads the host root): the sitemap it announced was
+1 -1
View File
@@ -32,7 +32,7 @@ from sitegen import wanted as sitewanted
from resolve import review, reviewhashes, sendable
import yaml
from model.database import load_database
from tests.test_site_pronouns import pronouns
from tests.sitepages import pronouns
REPO_ROOT = Path(__file__).resolve().parent.parent
+2 -3
View File
@@ -695,14 +695,13 @@ class StartPagesStayInBudget(unittest.TestCase):
"""The built pages: the new answers fit the level 0 ceilings."""
def test_ceilings(self):
from tests import test_site_copy
from tests.sitecopy import START_PAGES, _load
sitepages.require()
for name in ("wiki/faq.md", "wiki/troubleshooting.md", "wiki/first-install.md",
"wiki/what-are-bios-files.md"):
with self.subTest(page=name):
self.assertLessEqual(test_site_copy._load(name).words(),
test_site_copy.START_PAGES[name])
self.assertLessEqual(_load(name).words(), START_PAGES[name])
ARCADE_ANCHOR = "technical-faq.md#which-mame-version-do-the-arcade-bios-sets-match"
+1 -1
View File
@@ -21,7 +21,7 @@ from pathlib import Path
from unittest import mock
import install
from tests.test_install_app import make_card
from tests.installsupport import make_card
from tests.netguard import module_guard
from tests.tuisupport import (
_args, BUILDER_FLOOR, _CardFixtures, CHECK, checked_state, ChoiceRuns, ChoiceScreens, _Decided,
+1 -2
View File
@@ -18,8 +18,7 @@ from pathlib import Path, PurePosixPath, PureWindowsPath
from unittest import mock
import install
from tests.test_install_app import make_card
from tests.test_install_selection import FakeRepository
from tests.installsupport import FakeRepository, make_card
from tests.netguard import module_guard
from tests.tuisupport import (
_args, checked_state, ChoiceRuns, ChoiceScreens, DriveRuns, fresh_state, games_part, HOME,
+1 -2
View File
@@ -17,8 +17,7 @@ from pathlib import Path, PureWindowsPath
from unittest import mock
import install
from tests.test_install_app import make_card
from tests.test_install_selection import FakeRepository
from tests.installsupport import FakeRepository, make_card
from tests.netguard import module_guard
from tests.tuisupport import (
_args, CHECK, checked_state, FILES, found, fresh_state, HOME, in_full, install_run, Key, listed,
+1 -1
View File
@@ -19,7 +19,7 @@ from pathlib import Path
from unittest import mock
import install
from tests.test_install_app import make_card
from tests.installsupport import make_card
from tests.netguard import module_guard
from tests.tuisupport import (
_args, CHECK, checked_state, FILES, found, fresh_state, HOME, in_full, install_run,
+2 -2
View File
@@ -17,7 +17,7 @@ from pathlib import Path
from unittest import mock
import install
from tests.test_install_app import make_card
from tests.installsupport import make_card
from tests.netguard import module_guard
from tests.tuisupport import (
_args, BUILDER_FLOOR, _CardFixtures, checked_state, _Decided, engine_events, fresh_state, HOME,
@@ -739,7 +739,7 @@ class LineModeAndScreenDecideAlike(_LineModeFindings, _OutsideTextFindings,
def test_a_pack_gets_the_menu_and_its_folder_named(self):
"""No menu and no folder before the copy, the pack's list
recording no system."""
from tests.test_install_offline import _pack, PAYLOAD
from tests.installsupport import _pack, PAYLOAD
downloads = self.root / "downloads"
downloads.mkdir()
+1 -1
View File
@@ -15,7 +15,7 @@ from pathlib import Path
from unittest import mock
import install
from tests.test_install_app import make_card
from tests.installsupport import make_card
from tests.netguard import module_guard
from tests.tuisupport import (
_args, _CardFixtures, CHECK, checked_state, drawn, FILES, fresh_state, _game_state, GOLDEN,
+7 -8
View File
@@ -24,8 +24,7 @@ from pathlib import Path
from unittest import mock
import install
from tests.test_install_app import make_card
from tests.test_install_selection import FakeRepository
from tests.installsupport import FakeRepository, make_card
from tests.netguard import module_guard
from tests.tuisupport import (
_args, BUILDER_FLOOR, CHECK, checked_state, DriveRuns, engine_events, FILES, fresh_state,
@@ -112,7 +111,7 @@ class PacksWordingAndDocs(unittest.TestCase):
self.assertIn("systems", schema["properties"]["files"]["items"]["properties"])
def pack(self, systems: bool) -> Path:
from tests.test_install_offline import GBA, US
from tests.installsupport import GBA, US
members = {"scph5501.bin": US, "gba_bios.bin": GBA}
listed = [{"path": path, "sha1": hashlib.sha1(data).hexdigest(),
@@ -161,7 +160,7 @@ class PacksWordingAndDocs(unittest.TestCase):
def test_a_pack_cannot_write_escapes_through_its_system_names(self):
"""The titles and ids a pack
records reached print() raw in the systems list."""
from tests.test_install_offline import GBA, US
from tests.installsupport import GBA, US
members = {"scph5501.bin": US, "gba_bios.bin": GBA}
listed = [{"path": path, "sha1": hashlib.sha1(data).hexdigest(), "size": len(data),
@@ -1072,15 +1071,15 @@ class GamesEndToEnd(unittest.TestCase):
"""The real --tui on a card with games, against a loopback repository."""
def test_the_plan_opens_on_the_games_and_installs_only_them(self):
from tests import test_install_games as games
from tests.gamessupport import Card, manifest, mcd_iso
card = games.Card()
card = Card()
self.addCleanup(card.close)
card.game("SEGACD", "sonic.iso", games.mcd_iso(100))
card.game("SEGACD", "sonic.iso", mcd_iso(100))
root = card.root / "repo"
(root / "install").mkdir(parents=True)
shutil.copytree(card.lists / "games", root / "install" / "games")
listed = games.manifest()
listed = manifest()
(root / "bios").mkdir()
for entry in listed["files"]:
payload = entry["dest"].encode().ljust(entry["size"], b".")[:entry["size"]]
+1 -5
View File
@@ -23,7 +23,7 @@ from pathlib import Path
from unittest import mock
import install
from tests.test_install_selection import FakeRepository
from tests.installsupport import AppRepository, FakeRepository, make_card
from tests.netguard import module_guard
from tests.tuisupport import (
DOWN, fresh_state, HOME, Pty, pty, pyte, REPO_ROOT, RIGHT, SaveDirectoryRepository, sgr,
@@ -116,8 +116,6 @@ class EndToEnd(unittest.TestCase):
def card_repo(self, system: str) -> tuple[Path, Path]:
from tests.test_install_app import AppRepository, make_card
repo = self.repo(AppRepository)
root = repo.root / "card"
return root, make_card(root, system)
@@ -1132,8 +1130,6 @@ class TapsOnAPtySeeFirst(unittest.TestCase):
term.close()
def test_the_game_data_row_keeps_the_ticks_to_the_install(self):
from tests.test_tui_pty import GameDataRepository
repo = self.repo(GameDataRepository)
term = self.start()
term.wait("> Install")
+3 -4
View File
@@ -19,8 +19,7 @@ from pathlib import Path
from unittest import mock
import install
from tests.test_install_app import make_card
from tests.test_install_selection import FakeRepository
from tests.installsupport import FakeRepository, make_card
from tests.netguard import module_guard
from tests.tuisupport import (
_args, CHECK, checked_state, _Decided, FILES, found, fresh_state, HOME, in_full,
@@ -989,7 +988,7 @@ class ScreenRowsAndFilters(unittest.TestCase):
"""Cannot create, then end 2 and nothing else."""
import subprocess
from tests.test_install_offline import PAYLOAD, _offline_env, _pack
from tests.installsupport import PAYLOAD, _offline_env, _pack
if os.name == "nt" or os.geteuid() == 0:
self.skipTest("a folder that refuses writes is POSIX, and root writes anyway")
@@ -1018,7 +1017,7 @@ class ScreenRowsAndFilters(unittest.TestCase):
be created gave it a summary."""
import subprocess
from tests.test_install_offline import PAYLOAD, _offline_env, _pack
from tests.installsupport import PAYLOAD, _offline_env, _pack
pack = _pack(self.root, "RetroArch_v1_BIOS_Pack.zip", PAYLOAD)
argv = ["install.py", "--platform", "retroarch", "--dest", str(self.root / "system"),
+3 -6
View File
@@ -35,8 +35,7 @@ from pathlib import Path
from unittest import mock
import install
from tests.test_install_app import make_card
from tests.test_install_selection import FakeRepository
from tests.installsupport import FakeRepository, make_card
REPO_ROOT = Path(__file__).resolve().parent.parent
@@ -805,8 +804,6 @@ class SaveDirectoryRepository(FakeRepository):
def _app_card(test: unittest.TestCase, system: str) -> tuple[Path, Path]:
"""A card of system in the repository's tmp/, its root and BIOS folder."""
from tests.test_install_app import make_card
root = Path(tempfile.mkdtemp())
test.addCleanup(shutil.rmtree, root, True)
return root / "card", make_card(root / "card", system)
@@ -1006,7 +1003,7 @@ class _CardFixtures:
regions: bool = True) -> tuple[Path, Path, dict]:
"""A list of plat's shape (the MinUI family records cores and regions,
no system), the pack built from it and the files' payloads."""
from tests.test_install_offline import GBA, JP, US
from tests.installsupport import GBA, JP, US
payloads = {"Bios/MGBA/gba_bios.bin": (GBA, "nintendo-gba", "mgba", None),
"Bios/PS/scph5501.bin": (US, "sony-playstation", "pcsx_rearmed",
@@ -1113,7 +1110,7 @@ class _OutsideTextFindings:
return out.getvalue() + err.getvalue() + events.getvalue()
def test_a_pack_member_path_is_refused(self):
from tests.test_install_offline import _pack, GBA
from tests.installsupport import _pack, GBA
pack = _pack(self.root, "RetroArch_v1_BIOS_Pack.zip", {f"x{self.OSC}.bin": GBA})
text = self.run_install(_args(platform="retroarch", dest=self.dest,