refactor: public names for cross-module reads

This commit is contained in:
Abdessamad Derraz committed 2026-11-18 22:59:51 +01:00
1 parent f371790dc6
commit 3853ca2f1c
254 files changed
+2955 -2969

No files matched your search

+4 -4
View File
@@ -19,7 +19,7 @@ import tempfile
import unittest
from pathlib import Path
from model.profiles import load_emulator_profiles, _emulator_profiles_cache
from model.profiles import load_emulator_profiles, emulator_profiles_cache
from resolve.localfile import resolve_local_file
from packs import extras as packextras
@@ -87,10 +87,10 @@ class AgnosticScanStaysInItsTree(unittest.TestCase):
"base_destination": "",
"systems": {},
}
_emulator_profiles_cache.clear()
emulator_profiles_cache.clear()
def tearDown(self):
_emulator_profiles_cache.clear()
emulator_profiles_cache.clear()
self._tmp.cleanup()
def _write_profile(self, body: str):
@@ -98,7 +98,7 @@ class AgnosticScanStaysInItsTree(unittest.TestCase):
return load_emulator_profiles(str(self.root / "emulators"))
def _scan(self, profiles):
extras = packextras._collect_emulator_extras(
extras = packextras.collect_emulator_extras(
self.config, str(self.root / "emulators"), self.db, set(), "",
profiles,
)
+2 -2
View File
@@ -27,7 +27,7 @@ class ScanFollowsTheBuild(unittest.TestCase):
from model.database import load_database
from model.profiles import load_emulator_profiles
from model.platforms import load_platform_config
from packs.extras import _collect_emulator_extras
from packs.extras import collect_emulator_extras
profiles = load_emulator_profiles("emulators")
entry = next(
@@ -38,7 +38,7 @@ class ScanFollowsTheBuild(unittest.TestCase):
if entry is None or entry.get("mode") != "standalone":
self.skipTest("armsx2 no longer declares a standalone proverb.zip")
config = load_platform_config("retroarch")
extras = _collect_emulator_extras(
extras = collect_emulator_extras(
config, "emulators", load_database("database.json"), set(),
config.get("base_destination", ""), profiles,
)
+2 -2
View File
@@ -470,11 +470,11 @@ class ALooseEntryNamingItsArchive(unittest.TestCase):
import yaml
from model.profiles import _emulator_profiles_cache
from model.profiles import emulator_profiles_cache
from packs.emulatorpack import generate_emulator_pack
from packs.emulatorcheck import verify_emulator
_emulator_profiles_cache.clear()
emulator_profiles_cache.clear()
(REPO_ROOT / "tmp").mkdir(exist_ok=True)
root = Path(tempfile.mkdtemp(dir=REPO_ROOT / "tmp"))
self.addCleanup(shutil.rmtree, root, True)
+3 -3
View File
@@ -222,7 +222,7 @@ class ScratchFilesGetThePlainMode(unittest.TestCase):
from packs import finalize
pack = self.dir / "Pack.zip"
with archive._writing_pack(str(pack)) as zf:
with archive.writing_pack(str(pack)) as zf:
zf.writestr("a.bin", b"x")
self.assertEqual(self._mode(pack), 0o644)
os.chmod(pack, 0o600)
@@ -315,9 +315,9 @@ class ATerminatedBuildLeavesNoScratch(unittest.TestCase):
"import sys, time\n"
"sys.path.insert(0, 'scripts')\n"
"from core.cli import run_cli\n"
"from packs.archive import _writing_pack\n"
"from packs.archive import writing_pack\n"
"def main():\n"
" with _writing_pack(sys.argv[1]) as zf:\n"
" with writing_pack(sys.argv[1]) as zf:\n"
" zf.writestr('a.bin', b'x')\n"
" print('writing', flush=True)\n"
" time.sleep(60)\n"
+67 -67
View File
@@ -625,13 +625,13 @@ class APackIsSwappedInWhole(unittest.TestCase):
def test_a_failed_build_keeps_the_previous_pack(self):
import zipfile
from packs.archive import _writing_pack
from packs.archive import writing_pack
directory = self._dir()
pack = directory / "Pack.zip"
with zipfile.ZipFile(pack, "w") as zf:
zf.writestr("old.bin", b"complete")
with self.assertRaises(OSError), _writing_pack(str(pack)) as zf:
with self.assertRaises(OSError), writing_pack(str(pack)) as zf:
zf.writestr("new.bin", b"half")
raise OSError("disk full")
with zipfile.ZipFile(pack) as zf:
@@ -641,12 +641,12 @@ class APackIsSwappedInWhole(unittest.TestCase):
def test_a_finished_build_replaces_it(self):
import zipfile
from packs.archive import _writing_pack
from packs.archive import writing_pack
directory = self._dir()
pack = directory / "Pack.zip"
pack.write_bytes(b"stale")
with _writing_pack(str(pack)) as zf:
with writing_pack(str(pack)) as zf:
zf.writestr("new.bin", b"whole")
with zipfile.ZipFile(pack) as zf:
self.assertEqual(zf.namelist(), ["new.bin"])
@@ -823,7 +823,7 @@ class ADamagedArchiveIsNotPacked(unittest.TestCase):
def test_the_rebuild_refusal_reaches_the_run(self):
import zipfile
from packs.archive import DamagedArchiveError, _add_zip_to_pack
from packs.archive import DamagedArchiveError, add_zip_to_pack
with tempfile.TemporaryDirectory(dir=TMP_ROOT) as directory:
source = Path(directory) / "set.zip"
@@ -835,7 +835,7 @@ class ADamagedArchiveIsNotPacked(unittest.TestCase):
pack = Path(directory) / "pack.zip"
with zipfile.ZipFile(pack, "w") as target:
with self.assertRaises(DamagedArchiveError) as caught:
_add_zip_to_pack(str(source), "set.zip", target)
add_zip_to_pack(str(source), "set.zip", target)
self.assertNotIn("set.zip", target.namelist())
self.assertIsInstance(caught.exception, OSError)
self.assertIn("set.zip", str(caught.exception))
@@ -849,7 +849,7 @@ class APackedArchiveKeepsItsBytes(unittest.TestCase):
import hashlib
import zipfile
from packs.archive import _add_zip_to_pack
from packs.archive import add_zip_to_pack
with tempfile.TemporaryDirectory(dir=TMP_ROOT) as directory:
source = Path(directory) / "set.zip"
@@ -857,7 +857,7 @@ class APackedArchiveKeepsItsBytes(unittest.TestCase):
zf.writestr(zipfile.ZipInfo("rom.bin", (1999, 1, 2, 3, 4, 5)), b"rom" * 40)
pack = Path(directory) / "pack.zip"
with zipfile.ZipFile(pack, "w") as target:
_add_zip_to_pack(str(source), "set.zip", target)
add_zip_to_pack(str(source), "set.zip", target)
with zipfile.ZipFile(pack) as packed:
inner = packed.read("set.zip")
self.assertEqual(hashlib.sha1(inner).hexdigest(),
@@ -870,11 +870,11 @@ class PackReadmesSayWhatTheInstallerDoes(unittest.TestCase):
RetroArch README offered only `| sh`, which Windows cannot run."""
def _guide(self, platform: str) -> str:
from packs.readme import _build_readme
from packs.readme import build_readme
registry = yaml.safe_load((ROOT / "platforms" / "_registry.yml").read_text())
install = registry["platforms"][platform].get("install") or {}
text = _build_readme(platform, platform, "", 1, 1,
text = build_readme(platform, platform, "", 1, 1,
detect=install.get("detect", []),
standalone_copies=install.get("standalone_copies", []))
return text[text.index("INSTALLATION"):text.index("TROUBLESHOOTING")]
@@ -3351,30 +3351,30 @@ class APackNameFitsAFileName(unittest.TestCase):
before writing anything, while verify --system snes reported."""
def test_a_long_selection_is_bounded_and_told_apart(self):
from scripts.packs.naming import MAX_PACK_NAME_BYTES, _bounded_pack_name
from scripts.packs.naming import MAX_PACK_NAME_BYTES, bounded_pack_name
names = [f"Emulator_Number_{i}" for i in range(23)]
long_name = _bounded_pack_name(names, names, "_BIOS_Pack.zip")
long_name = bounded_pack_name(names, names, "_BIOS_Pack.zip")
self.assertLessEqual(len(long_name.encode()), MAX_PACK_NAME_BYTES)
self.assertTrue(long_name.startswith("Emulator_Number_0_and_22_more_"))
other = _bounded_pack_name(names, names[:-1] + ["x"], "_BIOS_Pack.zip")
other = bounded_pack_name(names, names[:-1] + ["x"], "_BIOS_Pack.zip")
self.assertNotEqual(long_name, other)
self.assertEqual(_bounded_pack_name(["A", "B"], ["a", "b"], ".zip"), "A_B.zip")
self.assertEqual(bounded_pack_name(["A", "B"], ["a", "b"], ".zip"), "A_B.zip")
def test_a_long_system_list_is_bounded(self):
"""Thirty systems joined made a 261-byte platform pack name."""
from scripts.packs.naming import MAX_SYSTEM_TAG_BYTES, _system_tag
from scripts.packs.naming import MAX_SYSTEM_TAG_BYTES, system_tag
systems = [f"vendor-console-number-{i}" for i in range(30)]
tag = _system_tag(systems)
tag = system_tag(systems)
self.assertLessEqual(len(tag.encode()), MAX_SYSTEM_TAG_BYTES + 1)
self.assertNotEqual(tag, _system_tag(systems[:-1] + ["other-console"]))
self.assertEqual(_system_tag(["sony-playstation"]), "_Playstation")
self.assertNotEqual(tag, system_tag(systems[:-1] + ["other-console"]))
self.assertEqual(system_tag(["sony-playstation"]), "_Playstation")
def test_two_systems_never_name_one_system(self):
"""sega-dreamcast,arcade and sega-dreamcast-arcade both wrote
RetroArch_..._Dreamcast_Arcade.zip, and the second replaced the first."""
from scripts.packs.naming import _system_tag
from scripts.packs.naming import system_tag
pairs = [
(["sega-dreamcast", "arcade"], ["sega-dreamcast-arcade"]),
@@ -3383,7 +3383,7 @@ class APackNameFitsAFileName(unittest.TestCase):
]
for two, one in pairs:
with self.subTest(two=two):
self.assertNotEqual(_system_tag(two), _system_tag(one))
self.assertNotEqual(system_tag(two), system_tag(one))
def test_two_hash_lists_get_two_names(self):
"""--from-md5 named its pack after the context only: a second list
@@ -3431,7 +3431,7 @@ class ARegionDroppedExtraBlocksNothing(unittest.TestCase):
config = {"case_insensitive_fs": True, "base_destination": ""}
def report(region_drops):
with mock.patch.object(packextras, "_collect_emulator_extras",
with mock.patch.object(packextras, "collect_emulator_extras",
return_value=extras), \
mock.patch.object(packextras, "resolve_local_file",
side_effect=lambda fe, *a, **k: (
@@ -3539,7 +3539,7 @@ class APinnedCoreFileTakesTheSlotFirst(unittest.TestCase):
with mock.patch("packs.gaps.find_undeclared_files", return_value=undeclared), \
mock.patch.object(packextras, "resolve_platform_cores",
return_value=set()) as cores:
extras = packextras._collect_emulator_extras(
extras = packextras.collect_emulator_extras(
config, "emulators", {"files": {}, "indexes": {}}, set(), "bios", {}
)
self.assertEqual([e["source_profile"] for e in extras][:1], ["solarus"])
@@ -3714,7 +3714,7 @@ class AnArchiveShipsWholeUnderARegion(unittest.TestCase):
def test_verify_filters_loose_files_only(self):
source = script_source("verify.py")
self.assertIn(
'if fe.get("archive")\n or _resolve_destination(fe, standalone) not in region_drops',
'if fe.get("archive")\n or resolve_destination(fe, standalone) not in region_drops',
source,
)
@@ -3972,7 +3972,7 @@ class ADataDirectoryIsWalkedOnce(unittest.TestCase):
resolution cost names x tree on every pack build."""
def test_two_lookups_share_one_walk_and_keep_its_order(self):
from resolve.datadirs import forget_data_dir_index, _resolve_in_data_dirs
from resolve.datadirs import forget_data_dir_index, resolve_in_data_dirs
with tempfile.TemporaryDirectory(dir=ROOT / "tmp") as tmp:
cache = Path(tmp) / "cache"
@@ -3991,9 +3991,9 @@ class ADataDirectoryIsWalkedOnce(unittest.TestCase):
return real_walk(top, *a, **k)
with mock.patch.object(os, "walk", counting_walk):
first, _ = _resolve_in_data_dirs(["font.bin"], registry,
first, _ = resolve_in_data_dirs(["font.bin"], registry,
lambda _p: "name_exact")
second, _ = _resolve_in_data_dirs(["other.bin"], registry,
second, _ = resolve_in_data_dirs(["other.bin"], registry,
lambda _p: "name_exact")
forget_data_dir_index()
self.assertEqual(len(walks), 1)
@@ -4223,7 +4223,7 @@ class TriageSurvivesAForgeRefusal(unittest.TestCase):
mock.patch.object(triage, "select_repo", lambda p: object()), \
contextlib.redirect_stdout(out), \
contextlib.redirect_stderr(io.StringIO()):
triage._print_triage(args, selected, reports)
triage.print_triage(args, selected, reports)
# A header row and a closing count frame the ranking.
lines = out.getvalue().splitlines()[1:-1]
self.assertEqual(len(lines), 2)
@@ -4315,7 +4315,7 @@ class ASameNamedMemberIsNotTheFile(unittest.TestCase):
(tmp / "bios").mkdir()
with zipfile.ZipFile(tmp / "bios" / "extras.zip", "w") as zf:
zf.writestr("files/other.ttf", b"MEMBER FONT")
names = crossref._build_supplemental_index(str(tmp / "data"), str(tmp / "bios"))
names = crossref.build_supplemental_index(str(tmp / "data"), str(tmp / "bios"))
locations = crossref._supplemental_locations(str(tmp / "data"), str(tmp / "bios"))
with mock.patch.object(crossref, "_supplemental_locations", lambda: locations):
for fname, data in (("font.ttf", b"DATA FONT"), ("other.ttf", b"MEMBER FONT")):
@@ -4481,7 +4481,7 @@ class EveryReadmeNamesItsFolder(unittest.TestCase):
/storage/system, the folder the registry and the installer use."""
def test_the_registry_folder_is_in_the_guide(self):
from scripts.packs.readme import _build_readme
from scripts.packs.readme import build_readme
registry = yaml.safe_load((ROOT / "platforms" / "_registry.yml").read_text())
for name, entry in registry["platforms"].items():
@@ -4489,10 +4489,10 @@ class EveryReadmeNamesItsFolder(unittest.TestCase):
if not folder:
continue
with self.subTest(platform=name):
text = _build_readme(name, name, "", 1, 1,
text = build_readme(name, name, "", 1, 1,
detect=[{"os": "linux", "bios_path": folder}])
self.assertIn(folder, text)
lakka = _build_readme("lakka", "Lakka", "", 1, 1)
lakka = build_readme("lakka", "Lakka", "", 1, 1)
self.assertNotIn("retroarch/system", lakka)
@@ -4799,8 +4799,8 @@ class VerifyPacksSaysWhatItExcluded(unittest.TestCase):
body = source[source.index("def _run_verify_packs"):]
body = body[:body.index("\ndef ")]
self.assertIn("bl_excluded, bl_absent) = result", body)
self.assertIn("_baseline_shortfall(bl_excluded, bl_absent)", body)
shortfall = source[source.index("def _baseline_shortfall"):]
self.assertIn("baseline_shortfall(bl_excluded, bl_absent)", body)
shortfall = source[source.index("def baseline_shortfall"):]
self.assertIn("unsafe excluded", shortfall[:shortfall.index("\ndef ")])
self.assertNotIn("errors[:5]", body)
self.assertNotRegex(body, r"result\[\d\]")
@@ -4839,11 +4839,11 @@ class AFileToSourceIsAFileNotAName(unittest.TestCase):
def test_rows_are_keyed_by_name_and_hash(self):
source = script_source("generate_site.py")
self.assertIn('key = (g["name"], g.get("identity") or f"emulator:{emu_name}")', source)
from scripts.packs.crossref import _first_hash
from scripts.packs.crossref import first_hash
self.assertEqual(_first_hash({"md5": ["AB", "cd"]}), "md5:ab")
self.assertEqual(_first_hash({"crc32": "1", "sha1": "F" * 40}), "sha1:" + "f" * 40)
self.assertEqual(_first_hash({}), "")
self.assertEqual(first_hash({"md5": ["AB", "cd"]}), "md5:ab")
self.assertEqual(first_hash({"crc32": "1", "sha1": "F" * 40}), "sha1:" + "f" * 40)
self.assertEqual(first_hash({}), "")
@@ -4867,7 +4867,7 @@ class AFileCardSaysAllItKnows(unittest.TestCase):
showed standalone_path, and gave no file an anchor to link to."""
def test_members_standalone_path_and_anchor(self):
from scripts.sitegen.emulatorcards import _render_emulator_file
from scripts.sitegen.emulatorcards import render_emulator_file
entry = {
"name": "neogeo.zip", "path": "neogeo.zip", "category": "bios_zip",
@@ -4875,7 +4875,7 @@ class AFileCardSaysAllItKnows(unittest.TestCase):
"contents": [{"name": f"m{i}.bin", "size": 1024, "crc32": f"{i:08x}"}
for i in range(12)],
}
text = "\n".join(_render_emulator_file(
text = "\n".join(render_emulator_file(
entry, {"files": [entry]}, None, [entry], lambda f: True, "file-neogeo-zip",
))
# The card is a heading with this id, linked by the heading's own
@@ -5374,7 +5374,7 @@ class BundledFilesAreNotToSource(unittest.TestCase):
entry = {"name": "n64.psh", "required": True, "in_repo": False,
"category": "bios", "in_pack": True, "bundled": True}
self.assertEqual(packs_report._core_required_missing([entry]), [])
self.assertEqual(packs_report.core_required_missing([entry]), [])
summary = verify._overall_summary(
[({"severity_counts": {}, "undeclared_files": [entry]}, ["ROCKNIX"])]
)
@@ -5473,12 +5473,12 @@ class AdlerValuesReadLikeTheDownloads(unittest.TestCase):
byte-swapped ROM, so the raw ea3734fe in files.csv matched neither."""
def test_values_and_the_swap_are_stated(self):
from scripts.sitegen.emulatorcards import _render_emulator_file
from scripts.sitegen.emulatorcards import render_emulator_file
entry = {"name": "dsp_rom.bin", "path": "dsp_rom.bin",
"known_hash_adler32": ["0x66f334fe", "0xE789B5A5"],
"adler32_byteswap": True}
text = "\n".join(_render_emulator_file(
text = "\n".join(render_emulator_file(
entry, {"files": [entry]}, None, [entry], lambda f: True, "file-dsp",
))
self.assertIn("`66f334fe`, `e789b5a5`", text)
@@ -5553,11 +5553,11 @@ class UnsourceableCardSaysWhy(unittest.TestCase):
and nothing else. The reason was only on the gaps page."""
def test_reason_and_link(self):
from scripts.sitegen.emulatorcards import _render_emulator_file
from scripts.sitegen.emulatorcards import render_emulator_file
entry = {"name": "nds_firmware_modified.bin", "path": "x.bin",
"unsourceable": "written by the firmware editor, so no dump of it exists"}
text = "\n".join(_render_emulator_file(
text = "\n".join(render_emulator_file(
entry, {"files": [entry]}, None, [entry], lambda f: False, "file-x",
))
self.assertIn("Not collected yet: written by the firmware editor", text)
@@ -5599,10 +5599,10 @@ class CollectionCardsSayWhereToGetTheFile(unittest.TestCase):
cards._RELEASE_ASSET_NAMES = None
self.addCleanup(setattr, cards, "_RELEASE_ASSET_NAMES", None)
self.assertEqual(
cards._fetch_url("bios/Sony/PlayStation/scph5501.bin"),
cards.fetch_url("bios/Sony/PlayStation/scph5501.bin"),
"https://raw.githubusercontent.com/Abdess/retrobios/main/bios/Sony/PlayStation/scph5501.bin",
)
self.assertTrue(cards._fetch_url("bios/Arcade/MAME/MAME 0.174 Arcade XML.dat").endswith(
self.assertTrue(cards.fetch_url("bios/Arcade/MAME/MAME 0.174 Arcade XML.dat").endswith(
"/releases/download/large-files/MAME.0.174.Arcade.XML.dat"
))
@@ -5615,12 +5615,12 @@ class CollectionCardsCarryFullHashes(unittest.TestCase):
def test_every_hash_in_full(self):
from scripts.packs.crossref import FileConsumers
from scripts.sitegen.cards import _system_file_card
from scripts.sitegen.cards import system_file_card
entry = {"name": "DUKE.RTS", "path": "bios/x/DUKE.RTS", "size": 10,
"sha1": "a" * 40, "md5": "9d29f9673bbdb56068acf7645c13749c",
"crc32": "504086c1", "sha256": "b" * 64}
text = "\n".join(_system_file_card(entry, FileConsumers({}, {})))
text = "\n".join(system_file_card(entry, FileConsumers({}, {})))
for value in (entry["sha1"], entry["md5"], entry["crc32"], entry["sha256"]):
self.assertIn(f'<dd class="rb-hash">{value}</dd>', text)
@@ -5631,9 +5631,9 @@ class AHeldRevisionLinksItsBuildFile(unittest.TestCase):
and the path a pinned link needs. 36 profiles carry one."""
def test_the_build_file_row(self):
from scripts.sitegen.emulatorcards import _build_rows
from scripts.sitegen.emulatorcards import build_rows
rows = _build_rows({"pin_frozen": "KNULLI builds this revision.", "pin_build": [{
rows = build_rows({"pin_frozen": "KNULLI builds this revision.", "pin_build": [{
"platform": "knulli", "repo": "https://github.com/knulli-cfw/knulli-linux",
"revision": "20260511", "path": "package/emulators/advanced_drastic/advanced_drastic.mk",
"variable": "ADVANCED_DRASTIC_VERSION", "value": "eaf41ab9"}]})
@@ -5643,10 +5643,10 @@ class AHeldRevisionLinksItsBuildFile(unittest.TestCase):
"at `20260511` sets `ADVANCED_DRASTIC_VERSION` |", rows)
def test_a_build_read_at_a_recorded_commit_links(self):
from scripts.sitegen.emulatorcards import _build_rows
from scripts.sitegen.emulatorcards import build_rows
pin = "46128cd252cdecae852a4d0bafa2aaf9d03ab563"
rows = _build_rows({"pin_build": [{
rows = build_rows({"pin_build": [{
"platform": "retropie", "repo": "https://github.com/RetroPie/RetroPie-Setup",
"revision": pin, "path": "scriptmodules/emulators/advmame-1.4.sh",
"variable": "rp_module_repo", "value": "x"}]})
@@ -5669,14 +5669,14 @@ class AVariantCardSaysWhatToSaveItAs(unittest.TestCase):
def test_the_name_to_save_it_under(self):
from scripts.packs.crossref import FileConsumers
from scripts.sitegen.cards import _system_file_card
from scripts.sitegen.cards import system_file_card
entry = {"name": "advision.zip", "size": 10, "sha1": "a" * 40,
"path": "bios/Entex/Adventure Vision/.variants/advision.zip.1c086064"}
text = "\n".join(_system_file_card(entry, FileConsumers({}, {})))
text = "\n".join(system_file_card(entry, FileConsumers({}, {})))
self.assertIn("Save as", text)
self.assertIn("advision.zip.1c086064", text)
plain = "\n".join(_system_file_card(
plain = "\n".join(system_file_card(
{**entry, "path": "bios/Entex/Adventure Vision/advision.zip"}, FileConsumers({}, {})))
self.assertNotIn("Save as", plain)
@@ -5717,7 +5717,7 @@ class EmulatorCardsLinkTheCopyAndTheSection(unittest.TestCase):
def test_copy_and_sections(self):
from types import SimpleNamespace
from scripts.sitegen.emulatorcards import _render_emulator_file
from scripts.sitegen.emulatorcards import render_emulator_file
sha1 = "ef9194ab4804aa0aa8540d846caf291b28331165"
consumers = SimpleNamespace(
@@ -5727,7 +5727,7 @@ class EmulatorCardsLinkTheCopyAndTheSection(unittest.TestCase):
platform_systems={sha1: {"batocera": {"nintendo-gamecube"}}},
)
entry = {"name": "IPL.bin", "path": "GC/USA/IPL.bin"}
text = "\n".join(_render_emulator_file(
text = "\n".join(render_emulator_file(
entry, {"files": [entry]}, consumers, [entry], lambda f: True, "file-ipl", "dolphin",
))
self.assertIn("../systems/nintendo.md#sha1-ef9194ab4804", text)
@@ -5801,9 +5801,9 @@ class SiteCodeSpansHoldTheirValue(unittest.TestCase):
was read as markup."""
def test_a_backtick_cannot_close_the_span(self):
from scripts.sitegen.render import _code
from scripts.sitegen.render import code_span
span = _code("a`<img src=x onerror=alert(1)>`")
span = code_span("a`<img src=x onerror=alert(1)>`")
self.assertEqual(span.count("`"), 2)
self.assertTrue(span.startswith("`") and span.endswith("`"))
@@ -5888,7 +5888,7 @@ class TheCollectionShipsADat(unittest.TestCase):
Batocera reads."""
sys.path.insert(0, str(ROOT / "scripts" / "scraper"))
from logiqx_parser import parse_logiqx
from scripts.sitegen.platformfiles import _platform_data_links
from scripts.sitegen.platformfiles import platform_data_links
from scripts.sitegen.structured import platform_dat
db = {"files": {"a" * 40: {"size": 4, "crc32": "8D8CB7E4", "md5": "1" * 32,
@@ -5907,7 +5907,7 @@ class TheCollectionShipsADat(unittest.TestCase):
("bios", "dolphin-emu\\Sys\\GC\\font.bin")})
self.assertEqual(roms[("bios", "dc\\naomi2.zip")].md5, "1" * 32)
self.assertEqual(roms[("bios", "dolphin-emu\\Sys\\GC\\font.bin")].md5, "3" * 32)
self.assertIn("[DAT](../downloads/dat/batocera.dat)", _platform_data_links("batocera"))
self.assertIn("[DAT](../downloads/dat/batocera.dat)", platform_data_links("batocera"))
@@ -7128,7 +7128,7 @@ class RequiredOnlyReachesDataDirectories(unittest.TestCase):
}
return [
dest
for _src, dest in datatrees._data_directory_members(
for _src, dest in datatrees.data_directory_members(
systems, registry, "retroarch", "", False, set(), set(), set(),
required_only=required_only,
)
@@ -7483,7 +7483,7 @@ class ExternalDownloadsFollowTheRunPolicy(unittest.TestCase):
def test_the_run_switch_is_inherited(self):
from resolve import packfiles as packresolve
saved = packresolve._OFFLINE
saved = packresolve.OFFLINE
packresolve.set_offline(True)
try:
with tempfile.TemporaryDirectory() as tmp, \
@@ -7891,14 +7891,14 @@ class EveryReaderOfACoreFileIsNamed(unittest.TestCase):
def test_a_held_file_out_of_reach_names_every_core_reading_it(self):
"""harm1.wad is a release asset: a checkout without it omits the file,
and the omission named gzdoom alone where lzdoom reads it too."""
from packs.manifestentry import _claim_cores
from packs.manifestentry import claim_cores
extra = {"source_profile": "gzdoom", "other_claims": [
{"source_profile": "uzdoom"}, {"source_profile": "lzdoom"}]}
self.assertEqual(_claim_cores(extra), ["gzdoom", "lzdoom", "uzdoom"])
self.assertEqual(claim_cores(extra), ["gzdoom", "lzdoom", "uzdoom"])
def test_a_missing_file_names_every_core_reading_it(self):
from packs.manifestentry import _record_absent
from packs.manifestentry import record_absent
omitted: dict[str, dict] = {}
@@ -7914,7 +7914,7 @@ class EveryReaderOfACoreFileIsNamed(unittest.TestCase):
omitted["SHARED.BIN"] = platform
absent.append({"name": "SHARED.BIN", "destination": "SHARED.BIN",
"source_profile": "raze"})
_record_absent(absent, {}, "", set(), False, set(), omitted, record)
record_absent(absent, {}, "", set(), False, set(), omitted, record)
self.assertEqual(omitted["NAPALM.GRP"]["cores"], ["eduke32", "raze"])
# A platform's own omission stays the platform's.
self.assertIsNone(omitted["SHARED.BIN"]["cores"])
+6 -6
View File
@@ -45,7 +45,7 @@ class ThePackReadmeNamesTheSpellingsItLeavesOut(unittest.TestCase):
def setUp(self):
from model.platforms import _platform_config_cache
from model.profiles import _emulator_profiles_cache
from model.profiles import emulator_profiles_cache
import generate_db
tmp = tempfile.TemporaryDirectory(dir=REPO_ROOT / "tmp")
self.addCleanup(tmp.cleanup)
@@ -74,9 +74,9 @@ class ThePackReadmeNamesTheSpellingsItLeavesOut(unittest.TestCase):
"files": [{"name": "bios.col", "required": True}],
}))
_platform_config_cache.clear()
_emulator_profiles_cache.clear()
emulator_profiles_cache.clear()
self.addCleanup(_platform_config_cache.clear)
self.addCleanup(_emulator_profiles_cache.clear)
self.addCleanup(emulator_profiles_cache.clear)
def _readme(self, systems: list[str]) -> str:
from model.platforms import _platform_config_cache
@@ -87,14 +87,14 @@ class ThePackReadmeNamesTheSpellingsItLeavesOut(unittest.TestCase):
}}}))
_platform_config_cache.clear()
texts: dict[str, str] = {}
real = platformpack._write_generated_member
real = platformpack.write_generated_member
def capture(zf, arcname, text):
texts[arcname] = text
return real(zf, arcname, text)
platformpack._write_generated_member = capture
self.addCleanup(setattr, platformpack, "_write_generated_member", real)
platformpack.write_generated_member = capture
self.addCleanup(setattr, platformpack, "write_generated_member", real)
with contextlib.redirect_stdout(io.StringIO()):
platformpack.generate_pack(
"p", "platforms", self.db, "bios", "", emulators_dir="emulators",
+1 -1
View File
@@ -400,7 +400,7 @@ class SiteNpmPins(unittest.TestCase):
name = url.split("registry.npmjs.org/", 1)[1].rsplit("/latest", 1)[0]
return {"version": latest[name]}
with mock.patch.object(cf, "SITE_PACKAGE", package), \
mock.patch.object(cf.upstream, "_http_json", side_effect=answer):
mock.patch.object(cf.upstream, "http_json", side_effect=answer):
rows = {f.subject: f for f in cf._npm_findings()}
self.assertEqual(rows["npm:astro"].status, cf.STALE)
self.assertEqual(rows["npm:astro"].remote, "7.4.7")
+6 -6
View File
@@ -19,12 +19,12 @@ import tempfile
import unittest
from pathlib import Path
from model.profiles import _emulator_profiles_cache, load_emulator_profiles
from model.profiles import emulator_profiles_cache, load_emulator_profiles
from resolve.content import content_fits, size_fits, _masked_sha1_verdict
from resolve.localfile import resolve_local_file
from packs import extras as packextras
from core.romdir import romdir_accepts, walk
from resolve.validation import _build_validation_index, check_file_validation
from resolve.validation import build_validation_index, check_file_validation
REPO_ROOT = Path(__file__).resolve().parent.parent
@@ -256,13 +256,13 @@ class ScannerVerifyManifestAgree(unittest.TestCase):
" - name: \"<bios>.nvm\"\n path: \"ps2/<bios>.nvm\"\n size: 1024\n"
" - name: \"<bios>.mec\"\n path: \"ps2/<bios>.mec\"\n size: 4\n"
)
_emulator_profiles_cache.clear()
emulator_profiles_cache.clear()
self.profiles = load_emulator_profiles(str(self.root / "emulators"))
self.config = {"platform": "Demo", "verification_mode": "existence",
"cores": ["demo", "anchor"], "base_destination": "", "systems": {}}
def tearDown(self):
_emulator_profiles_cache.clear()
emulator_profiles_cache.clear()
self._tmp.cleanup()
def accepted(self) -> set[str]:
@@ -279,7 +279,7 @@ class ScannerVerifyManifestAgree(unittest.TestCase):
"SCPH-70004.nvm", "246C.mec"})
def test_platform_pack_and_manifest_scan(self):
extras = packextras._collect_emulator_extras(
extras = packextras.collect_emulator_extras(
self.config, str(self.root / "emulators"), self.db, set(), "", self.profiles,
)
placed = {e["name"] for e in extras if e.get("source_profile") == "demo"}
@@ -296,7 +296,7 @@ class ScannerVerifyManifestAgree(unittest.TestCase):
self.assertEqual(names, self.accepted())
def test_resolver_name_step_and_validation_agree(self):
index = _build_validation_index(self.profiles_with_labels())
index = build_validation_index(self.profiles_with_labels())
for name in self.IMAGES:
path = str(self.root / "bios" / "PS2" / name)
entry_ = {"name": name, "found_by": "content", "validation": ["romdir"],
+1 -1
View File
@@ -175,7 +175,7 @@ class AmberelecCarriesTheMachines(unittest.TestCase):
trees = datatrees.core_data_trees(config, profiles, "amberelec", registry)
refs: dict = {}
members = dict(
(full, src) for src, full in datatrees._data_directory_members(
(full, src) for src, full in datatrees.data_directory_members(
config.get("systems", {}), registry, "amberelec",
config.get("base_destination", ""), False, set(), set(), set(),
refs_out=refs, core_trees=trees,
+12 -12
View File
@@ -24,7 +24,7 @@ from unittest import mock
import yaml
from model.profiles import _emulator_profiles_cache
from model.profiles import emulator_profiles_cache
from model.platforms import load_platform_config
from packs.platformpack import generate_pack
from packs.coverage import verify_platform
@@ -34,7 +34,7 @@ REPO_ROOT = Path(__file__).resolve().parents[1]
class ACoreFileFillsAFreeDeclaration(unittest.TestCase):
def setUp(self):
_emulator_profiles_cache.clear()
emulator_profiles_cache.clear()
(REPO_ROOT / "tmp").mkdir(exist_ok=True)
self.root = Path(tempfile.mkdtemp(dir=REPO_ROOT / "tmp"))
self.addCleanup(shutil.rmtree, self.root, True)
@@ -104,7 +104,7 @@ class AFileDeclaredUnderAnotherName(unittest.TestCase):
declarations, took ROM as declared and never counted it."""
def test_the_report_lists_what_the_builder_packs(self):
_emulator_profiles_cache.clear()
emulator_profiles_cache.clear()
root = Path(tempfile.mkdtemp(dir=REPO_ROOT / "tmp"))
self.addCleanup(shutil.rmtree, root, True)
bios = root / "bios" / "Apple" / "IIgs"
@@ -169,8 +169,8 @@ class AMissingDataDirectoryFailsTheRun(unittest.TestCase):
}))
db = {"files": {}, "indexes": {"by_md5": {}, "by_name": {}, "by_crc32": {},
"by_path_suffix": {}}}
datatrees._MISSING_DATA_DIRS.clear()
self.addCleanup(datatrees._MISSING_DATA_DIRS.clear)
datatrees.MISSING_DATA_DIRS.clear()
self.addCleanup(datatrees.MISSING_DATA_DIRS.clear)
with redirect_stdout(io.StringIO()):
platformpack.generate_pack(
"fakeplat", str(root / "platforms"), db, str(root / "bios"),
@@ -178,9 +178,9 @@ class AMissingDataDirectoryFailsTheRun(unittest.TestCase):
data_registry={"assets": {"local_cache": str(root / "absent")}},
offline=True,
)
self.assertEqual(datatrees._MISSING_DATA_DIRS, {"assets"})
self.assertEqual(datatrees.MISSING_DATA_DIRS, {"assets"})
# main() starts each run with no notices, so the run itself records it.
with mock.patch.object(gp, "_main", lambda held: datatrees._MISSING_DATA_DIRS.add("assets")), \
with mock.patch.object(gp, "_main", lambda held: datatrees.MISSING_DATA_DIRS.add("assets")), \
contextlib.redirect_stderr(io.StringIO()), \
self.assertRaises(SystemExit) as stop:
gp.main()
@@ -196,7 +196,7 @@ class AFileNobodyHoldsIsAnOmission(unittest.TestCase):
def test_the_manifest_names_it(self):
from packs.manifest import generate_manifest
_emulator_profiles_cache.clear()
emulator_profiles_cache.clear()
root = Path(tempfile.mkdtemp(dir=REPO_ROOT / "tmp"))
self.addCleanup(shutil.rmtree, root, True)
for folder in ("platforms", "emulators", "bios"):
@@ -237,7 +237,7 @@ class AMemberNameIsNotALooseFile(unittest.TestCase):
def test_verify_reads_undeclared_files_as_the_builder_does(self):
from packs import crossref
_emulator_profiles_cache.clear()
emulator_profiles_cache.clear()
root = Path(tempfile.mkdtemp(dir=REPO_ROOT / "tmp"))
self.addCleanup(shutil.rmtree, root, True)
(root / "platforms").mkdir()
@@ -255,7 +255,7 @@ class AMemberNameIsNotALooseFile(unittest.TestCase):
db = {"files": {}, "indexes": {"by_md5": {}, "by_name": {}, "by_crc32": {},
"by_path_suffix": {}}}
config = load_platform_config("fakeplat", str(root / "platforms"))
with mock.patch.object(crossref, "_build_supplemental_index",
with mock.patch.object(crossref, "build_supplemental_index",
lambda *a, **k: {"315-6146.bin"}):
result = verify_platform(config, db, str(root / "emulators"))
self.assertEqual(
@@ -271,7 +271,7 @@ class TwoDeclarationsOfOnePath(unittest.TestCase):
round, both must count the path once and met."""
def _run(self, first: str, second: str, spelling: str):
_emulator_profiles_cache.clear()
emulator_profiles_cache.clear()
root = Path(tempfile.mkdtemp(dir=REPO_ROOT / "tmp"))
self.addCleanup(shutil.rmtree, root, True)
bios = root / "bios" / "Maker" / "Console"
@@ -322,7 +322,7 @@ class ANamelessWhitelistEntry(unittest.TestCase):
missing in the pack and met in verify."""
def test_the_pack_counts_what_verify_counts(self):
_emulator_profiles_cache.clear()
emulator_profiles_cache.clear()
root = Path(tempfile.mkdtemp(dir=REPO_ROOT / "tmp"))
self.addCleanup(shutil.rmtree, root, True)
bios = root / "bios" / "Sony" / "PlayStation"
+4 -4
View File
@@ -22,7 +22,7 @@ from pathlib import Path
import yaml
from model.platforms import _platform_config_cache
from model.profiles import load_emulator_profiles, _emulator_profiles_cache
from model.profiles import load_emulator_profiles, emulator_profiles_cache
import generate_db
from packs import manifest as packs_manifest
from packs import platformpack
@@ -90,12 +90,12 @@ class _Collection(unittest.TestCase):
Path("emulators/sized.yml").write_text(SIZED)
Path("emulators/unsized.yml").write_text(UNSIZED)
_platform_config_cache.clear()
_emulator_profiles_cache.clear()
emulator_profiles_cache.clear()
self.profiles = load_emulator_profiles("emulators")
def tearDown(self):
_platform_config_cache.clear()
_emulator_profiles_cache.clear()
emulator_profiles_cache.clear()
os.chdir(self._cwd)
self._tmp.cleanup()
@@ -159,7 +159,7 @@ class SizeTheCoreRefuses(_Collection):
Path("emulators/sized.yml").write_text(
SIZED + " - name: ROM\n path: ROM\n size: 8\n validation: [size]\n"
)
_emulator_profiles_cache.clear()
emulator_profiles_cache.clear()
self.profiles = load_emulator_profiles("emulators")
self.assertTrue(self._report("sized")["in_repo"])
self.assertIn("ROM", self._pack_members())
+2 -2
View File
@@ -16,7 +16,7 @@ import tempfile
import unittest
from pathlib import Path
from packs.crossref import _build_supplemental_index, cross_reference, entry_source
from packs.crossref import build_supplemental_index, cross_reference, entry_source
from cross_reference import print_report
REPO_ROOT = Path(__file__).resolve().parent.parent
@@ -77,7 +77,7 @@ class GapReportSources(unittest.TestCase):
def test_a_directory_does_not_stand_for_a_file(self):
with tempfile.TemporaryDirectory(dir=REPO_ROOT / "tmp") as tmp:
(Path(tmp) / "bios" / "cpcemu" / "ROM").mkdir(parents=True)
names = _build_supplemental_index(str(Path(tmp) / "data"), str(Path(tmp) / "bios"))
names = build_supplemental_index(str(Path(tmp) / "data"), str(Path(tmp) / "bios"))
self.assertIsNone(entry_source({"name": "ROM"}, _index(data_names=names)))
directory = {"name": "ROM", "type": "directory"}
self.assertEqual(entry_source(directory, _index(data_names=names)), "data")
+5 -5
View File
@@ -55,12 +55,12 @@ def _rsa_sign(message: bytes) -> bytes:
def _ecdsa_sign(message: bytes) -> bytes:
g = (ec._Gx, ec._Gy)
r = ec._ec_mul(_ECC_NONCE, g)[0] % ec._N
g = (ec.Gx, ec.Gy)
r = ec.ec_mul(_ECC_NONCE, g)[0] % ec.N
digest = int.from_bytes(hashlib.sha256(message).digest(), "big")
if ec._N_BITLEN < 256:
digest >>= 256 - ec._N_BITLEN
s = (ec._modinv(_ECC_NONCE, ec._N) * (digest + r * _ECC_PRIVATE)) % ec._N
s = (ec._modinv(_ECC_NONCE, ec.N) * (digest + r * _ECC_PRIVATE)) % ec.N
return r.to_bytes(30, "big") + s.to_bytes(30, "big")
@@ -243,7 +243,7 @@ def _otp_plaintext(
body[0x24:0x44] = _ECC_PRIVATE.to_bytes(0x20, "big")
# Rebuild the certificate exactly as the verifier does, then sign it.
point = ec._ec_mul(_ECC_PRIVATE % ec._N, (ec._Gx, ec._Gy))
point = ec.ec_mul(_ECC_PRIVATE % ec.N, (ec.Gx, ec.Gy))
pub_xy = point[0].to_bytes(30, "big") + point[1].to_bytes(30, "big")
issuer = bytearray(0x40)
issuer_str = (
@@ -264,7 +264,7 @@ def _otp_plaintext(
def _root_public() -> bytes:
point = ec._ec_mul(_ECC_PRIVATE, (ec._Gx, ec._Gy))
point = ec.ec_mul(_ECC_PRIVATE, (ec.Gx, ec.Gy))
return point[0].to_bytes(30, "big") + point[1].to_bytes(30, "big")
+18 -18
View File
@@ -30,7 +30,7 @@ from core import sect233r1 as ec
class FieldArithmetic(unittest.TestCase):
"""GF(2^233) with the reduction polynomial t^233 + t^74 + 1."""
VALUES = (1, 2, 3, 0x1234567, ec._Gx, ec._Gy, (1 << 232) | 1)
VALUES = (1, 2, 3, 0x1234567, ec.Gx, ec.Gy, (1 << 232) | 1)
def test_reduction_keeps_the_degree_below_the_field_size(self):
for value in (1 << 300, (1 << 466) - 1, ec._F, ec._F << 5):
@@ -49,7 +49,7 @@ class FieldArithmetic(unittest.TestCase):
self.assertEqual(ec._gf_mul(a, b), ec._gf_mul(b, a))
def test_multiplication_is_associative(self):
a, b, c = ec._Gx, ec._Gy, 0x1234567
a, b, c = ec.Gx, ec.Gy, 0x1234567
self.assertEqual(
ec._gf_mul(ec._gf_mul(a, b), c), ec._gf_mul(a, ec._gf_mul(b, c))
)
@@ -79,44 +79,44 @@ class CurveParameters(unittest.TestCase):
return left == right
def test_the_generator_satisfies_the_curve_equation(self):
self.assertTrue(self._on_curve((ec._Gx, ec._Gy)))
self.assertTrue(self._on_curve((ec.Gx, ec.Gy)))
def test_multiplying_the_generator_by_the_group_order_gives_infinity(self):
"""The definitive check on the point arithmetic."""
self.assertIsNone(ec._ec_mul(ec._N, (ec._Gx, ec._Gy)))
self.assertIsNone(ec.ec_mul(ec.N, (ec.Gx, ec.Gy)))
def test_scalar_multiplication_agrees_with_repeated_addition(self):
g = (ec._Gx, ec._Gy)
g = (ec.Gx, ec.Gy)
accumulated = None
for k in range(1, 9):
accumulated = ec._ec_add(accumulated, g)
self.assertEqual(ec._ec_mul(k, g), accumulated, f"k={k}")
self.assertEqual(ec.ec_mul(k, g), accumulated, f"k={k}")
def test_doubling_agrees_with_adding_a_point_to_itself(self):
g = (ec._Gx, ec._Gy)
g = (ec.Gx, ec.Gy)
self.assertEqual(ec._ec_double(g), ec._ec_add(g, g))
def test_infinity_is_the_additive_identity(self):
g = (ec._Gx, ec._Gy)
g = (ec.Gx, ec.Gy)
self.assertEqual(ec._ec_add(g, None), g)
self.assertEqual(ec._ec_add(None, g), g)
self.assertIsNone(ec._ec_add(None, None))
self.assertIsNone(ec._ec_mul(0, g))
self.assertIsNone(ec.ec_mul(0, g))
def test_modular_inverse_round_trips(self):
for a in (1, 2, 3, 12345, ec._N - 1):
self.assertEqual((a * ec._modinv(a, ec._N)) % ec._N, 1)
for a in (1, 2, 3, 12345, ec.N - 1):
self.assertEqual((a * ec._modinv(a, ec.N)) % ec.N, 1)
def _sign(message: bytes, private: int, nonce: int) -> bytes:
"""ECDSA-SHA256 signing, so verification has something real to check."""
g = (ec._Gx, ec._Gy)
point = ec._ec_mul(nonce, g)
r = point[0] % ec._N
g = (ec.Gx, ec.Gy)
point = ec.ec_mul(nonce, g)
r = point[0] % ec.N
digest = int.from_bytes(hashlib.sha256(message).digest(), "big")
if ec._N_BITLEN < 256:
digest >>= 256 - ec._N_BITLEN
s = (ec._modinv(nonce, ec._N) * (digest + r * private)) % ec._N
s = (ec._modinv(nonce, ec.N) * (digest + r * private)) % ec.N
return r.to_bytes(30, "big") + s.to_bytes(30, "big")
@@ -127,7 +127,7 @@ class EcdsaVerification(unittest.TestCase):
@classmethod
def setUpClass(cls):
point = ec._ec_mul(cls.PRIVATE, (ec._Gx, ec._Gy))
point = ec.ec_mul(cls.PRIVATE, (ec.Gx, ec.Gy))
cls.public = point[0].to_bytes(30, "big") + point[1].to_bytes(30, "big")
cls.signature = _sign(cls.MESSAGE, cls.PRIVATE, cls.NONCE)
@@ -149,7 +149,7 @@ class EcdsaVerification(unittest.TestCase):
)
def test_another_public_key_is_rejected(self):
other = ec._ec_mul(self.PRIVATE + 1, (ec._Gx, ec._Gy))
other = ec.ec_mul(self.PRIVATE + 1, (ec.Gx, ec.Gy))
encoded = other[0].to_bytes(30, "big") + other[1].to_bytes(30, "big")
self.assertFalse(
ec.ecdsa_verify_sha256(self.MESSAGE, self.signature, encoded)
@@ -162,7 +162,7 @@ class EcdsaVerification(unittest.TestCase):
)
def test_out_of_range_scalars_are_rejected(self):
for bad in (b"\x00" * 30, ec._N.to_bytes(30, "big")):
for bad in (b"\x00" * 30, ec.N.to_bytes(30, "big")):
self.assertFalse(
ec.ecdsa_verify_sha256(self.MESSAGE, bad + self.signature[30:], self.public)
)
+3 -3
View File
@@ -287,9 +287,9 @@ class PathPriority(unittest.TestCase):
self.assertLess(primary, variant)
def test_protected_directories_are_recognised(self):
self.assertTrue(nodedup._in_nodedup_dir("bios/RPG Maker/x/font.png"))
self.assertTrue(nodedup._in_nodedup_dir("bios/ScummVM/x/monkey.tbl"))
self.assertFalse(nodedup._in_nodedup_dir("bios/Sony/PlayStation/scph.bin"))
self.assertTrue(nodedup.in_nodedup_dir("bios/RPG Maker/x/font.png"))
self.assertTrue(nodedup.in_nodedup_dir("bios/ScummVM/x/monkey.tbl"))
self.assertFalse(nodedup.in_nodedup_dir("bios/Sony/PlayStation/scph.bin"))
class TheNoDedupListIsPinned(unittest.TestCase):
+12 -12
View File
@@ -13,7 +13,7 @@ import zipfile
from pathlib import Path
from scripts.core.deterministic_zip import (
_FIXED_DATE_TIME,
FIXED_DATE_TIME,
rebuild_zip_deterministic,
verify_zip_determinism,
)
@@ -67,7 +67,7 @@ class TestRebuild(unittest.TestCase):
out, _ = self._rebuild()
with zipfile.ZipFile(out) as zf:
for info in zf.infolist():
self.assertEqual(info.date_time, _FIXED_DATE_TIME)
self.assertEqual(info.date_time, FIXED_DATE_TIME)
self.assertEqual(info.create_system, 0)
self.assertEqual(info.external_attr, 0o100644 << 16)
self.assertEqual(info.compress_type, zipfile.ZIP_DEFLATED)
@@ -278,7 +278,7 @@ class TestPackDeterminism(unittest.TestCase):
pack = self._build("out1")
with zipfile.ZipFile(pack) as zf:
dates = {i.date_time for i in zf.infolist()}
self.assertEqual(dates, {_FIXED_DATE_TIME})
self.assertEqual(dates, {FIXED_DATE_TIME})
def test_generated_members_carry_the_fixed_epoch(self):
pack = self._build("out1")
@@ -291,7 +291,7 @@ class TestPackDeterminism(unittest.TestCase):
]
self.assertTrue(generated, "pack should carry a generated README")
for info in generated:
self.assertEqual(info.date_time, _FIXED_DATE_TIME)
self.assertEqual(info.date_time, FIXED_DATE_TIME)
def _build_emulator(self, out_name: str) -> Path:
from scripts.packs.emulatorpack import generate_emulator_pack
@@ -313,14 +313,14 @@ class TestPackDeterminism(unittest.TestCase):
" system: test-sys\n"
" required: true\n"
)
from model.profiles import _emulator_profiles_cache
from model.profiles import emulator_profiles_cache
_emulator_profiles_cache.clear()
emulator_profiles_cache.clear()
path = generate_emulator_pack(
["detcore"], str(self.tmp / "emulators"), self.db, str(self.bios),
str(out), offline=True,
)
_emulator_profiles_cache.clear()
emulator_profiles_cache.clear()
self.assertIsNotNone(path)
return Path(path)
@@ -337,7 +337,7 @@ class TestPackDeterminism(unittest.TestCase):
def test_every_emulator_pack_member_carries_the_fixed_epoch(self):
pack = self._build_emulator("emu1")
with zipfile.ZipFile(pack) as zf:
self.assertEqual({i.date_time for i in zf.infolist()}, {_FIXED_DATE_TIME})
self.assertEqual({i.date_time for i in zf.infolist()}, {FIXED_DATE_TIME})
def test_an_executable_source_stays_executable(self):
"""Pinning the mode stripped the bit the RetroDECK pack needs.
@@ -393,7 +393,7 @@ class TestPackDeterminism(unittest.TestCase):
inject_manifest(str(pack), manifest)
with zipfile.ZipFile(pack) as zf:
info = zf.getinfo("manifest.json")
self.assertEqual(info.date_time, _FIXED_DATE_TIME)
self.assertEqual(info.date_time, FIXED_DATE_TIME)
@@ -421,7 +421,7 @@ class ManifestInjectionIsAtomic(unittest.TestCase):
zf.fp.flush()
raise KeyboardInterrupt
with mock.patch.object(finalize, "_write_generated_member", die), \
with mock.patch.object(finalize, "write_generated_member", die), \
self.assertRaises(KeyboardInterrupt):
finalize.inject_manifest(str(pack), {"files": ["x"] * 2000})
self.assertEqual(pack.read_bytes(), before)
@@ -437,14 +437,14 @@ class PackMemberCompression(unittest.TestCase):
the packs' size."""
def _pack(self, tmp: Path, name: str) -> Path:
from scripts.packs.archive import _add_pack_member
from scripts.packs.archive import add_pack_member
source = tmp / "member"
source.write_bytes(b"\x00" * 4096)
pack = tmp / name
with zipfile.ZipFile(pack, "w", zipfile.ZIP_DEFLATED) as zf:
for arcname in ("bios/a.zip", "bios/b.PNG", "bios/c.bin", "bios/d.pk3"):
_add_pack_member(zf, str(source), arcname)
add_pack_member(zf, str(source), arcname)
return pack
def test_compressed_formats_are_stored_and_the_rest_deflated(self):
+4 -4
View File
@@ -25,7 +25,7 @@ try:
import jsonschema
except ImportError:
jsonschema = None
from model.profiles import load_emulator_profiles, _emulator_profiles_cache
from model.profiles import load_emulator_profiles, emulator_profiles_cache
from resolve.directories import directory_members
import generate_db
from packs import emulatorpack
@@ -92,10 +92,10 @@ class DirectoryFixture(unittest.TestCase):
(self.platforms / "_registry.yml").write_text(
yaml.dump({"platforms": {"demo": {"config": "demo.yml"}}})
)
_emulator_profiles_cache.clear()
emulator_profiles_cache.clear()
def tearDown(self):
_emulator_profiles_cache.clear()
emulator_profiles_cache.clear()
self._tmp.cleanup()
def _add(self, relative: str, payload: bytes) -> None:
@@ -125,7 +125,7 @@ class DirectoryFixture(unittest.TestCase):
def _profiles(self, body: str = PROFILE) -> dict:
(self.emulators / "demo.yml").write_text(body)
_emulator_profiles_cache.clear()
emulator_profiles_cache.clear()
return load_emulator_profiles(str(self.emulators))
+1 -1
View File
@@ -479,7 +479,7 @@ class ValidationIndexScope(unittest.TestCase):
source = inspect.getsource(coverage.verify_platform)
self.assertRegex(source, r"plat_cores = resolve_platform_cores\(config, profiles\)")
self.assertIn("_build_validation_index(platform_profiles)", source)
self.assertIn("build_validation_index(platform_profiles)", source)
section = _section(_page("verification-modes.md"), "Validation index")
self.assertIn("resolve_platform_cores", section)
self.assertNotIn("reads all emulator profiles", section)
+86 -86
View File
@@ -43,7 +43,7 @@ from model.platforms import load_platform_config
from resolve.localfile import resolve_local_file
from resolve.cores import resolve_platform_cores
from resolve.truth import diff_platform_truth, generate_platform_truth
from resolve.validation import _build_validation_index, check_file_validation, filter_files_by_mode
from resolve.validation import build_validation_index, check_file_validation, filter_files_by_mode
from packs.verdicts import Severity, Status
from packs.gaps import find_exclusion_notes, find_undeclared_files
from packs.emulatorcheck import verify_emulator
@@ -76,9 +76,9 @@ class TestE2E(unittest.TestCase):
def setUp(self):
# Clear emulator profile cache to avoid stale data between tests
from model.profiles import _emulator_profiles_cache
from model.profiles import emulator_profiles_cache
_emulator_profiles_cache.clear()
emulator_profiles_cache.clear()
self.root = tempfile.mkdtemp()
self.bios_dir = os.path.join(self.root, "bios")
@@ -1263,7 +1263,7 @@ class TestE2E(unittest.TestCase):
def test_70_validation_index_built(self):
"""Validation index extracts checks from emulator profiles."""
profiles = load_emulator_profiles(self.emulators_dir)
index = _build_validation_index(profiles)
index = build_validation_index(profiles)
self.assertIn("present_req.bin", index)
self.assertIn("size", index["present_req.bin"]["checks"])
self.assertIn(16, index["present_req.bin"]["sizes"])
@@ -1273,7 +1273,7 @@ class TestE2E(unittest.TestCase):
def test_71_validation_size_pass(self):
"""File with correct size passes validation."""
profiles = load_emulator_profiles(self.emulators_dir)
index = _build_validation_index(profiles)
index = build_validation_index(profiles)
path = self.files["present_req.bin"]["path"]
reason = check_file_validation(path, "present_req.bin", index)
self.assertIsNone(reason)
@@ -1281,7 +1281,7 @@ class TestE2E(unittest.TestCase):
def test_72_validation_size_fail(self):
"""File with wrong size fails validation."""
profiles = load_emulator_profiles(self.emulators_dir)
index = _build_validation_index(profiles)
index = build_validation_index(profiles)
path = self.files["present_opt.bin"]["path"]
result = check_file_validation(path, "present_opt.bin", index)
self.assertIsNotNone(result)
@@ -1292,7 +1292,7 @@ class TestE2E(unittest.TestCase):
def test_73_validation_crc32_pass(self):
"""File with correct CRC32 passes validation."""
profiles = load_emulator_profiles(self.emulators_dir)
index = _build_validation_index(profiles)
index = build_validation_index(profiles)
path = self.files["correct_hash.bin"]["path"]
reason = check_file_validation(path, "correct_hash.bin", index)
self.assertIsNone(reason)
@@ -1300,7 +1300,7 @@ class TestE2E(unittest.TestCase):
def test_74_validation_crc32_fail(self):
"""File with wrong CRC32 fails validation."""
profiles = load_emulator_profiles(self.emulators_dir)
index = _build_validation_index(profiles)
index = build_validation_index(profiles)
path = self.files["no_md5.bin"]["path"]
result = check_file_validation(path, "no_md5.bin", index)
self.assertIsNotNone(result)
@@ -1325,7 +1325,7 @@ class TestE2E(unittest.TestCase):
def test_77_validation_crc32_leading_zero(self):
"""CRC32 starting with '0' must not be truncated (lstrip regression)."""
profiles = load_emulator_profiles(self.emulators_dir)
index = _build_validation_index(profiles)
index = build_validation_index(profiles)
path = self.files["leading_zero_crc.bin"]["path"]
reason = check_file_validation(path, "leading_zero_crc.bin", index)
self.assertIsNone(reason)
@@ -1346,13 +1346,13 @@ class TestE2E(unittest.TestCase):
],
},
}
index = _build_validation_index(profiles)
index = build_validation_index(profiles)
self.assertEqual(index["shared.bin"]["sizes"], {512, 1024})
def test_79_validation_md5_pass(self):
"""File with correct MD5 passes validation."""
profiles = load_emulator_profiles(self.emulators_dir)
index = _build_validation_index(profiles)
index = build_validation_index(profiles)
path = self.files["correct_hash.bin"]["path"]
reason = check_file_validation(path, "correct_hash.bin", index)
self.assertIsNone(reason)
@@ -1360,7 +1360,7 @@ class TestE2E(unittest.TestCase):
def test_80_validation_md5_fail(self):
"""File with wrong MD5 fails validation."""
profiles = load_emulator_profiles(self.emulators_dir)
index = _build_validation_index(profiles)
index = build_validation_index(profiles)
path = self.files["alias_target.bin"]["path"]
result = check_file_validation(path, "alias_target.bin", index)
self.assertIsNotNone(result)
@@ -1371,7 +1371,7 @@ class TestE2E(unittest.TestCase):
def test_81_validation_index_has_md5_sha1(self):
"""Validation index stores md5 and sha1 when declared."""
profiles = load_emulator_profiles(self.emulators_dir)
index = _build_validation_index(profiles)
index = build_validation_index(profiles)
self.assertIn("md5", index["correct_hash.bin"]["checks"])
self.assertIn("sha1", index["correct_hash.bin"]["checks"])
self.assertIsNotNone(index["correct_hash.bin"]["md5"])
@@ -1380,7 +1380,7 @@ class TestE2E(unittest.TestCase):
def test_82_validation_adler32_pass(self):
"""File with correct adler32 passes validation."""
profiles = load_emulator_profiles(self.emulators_dir)
index = _build_validation_index(profiles)
index = build_validation_index(profiles)
path = self.files["present_req.bin"]["path"]
reason = check_file_validation(path, "present_req.bin", index)
self.assertIsNone(reason)
@@ -1388,7 +1388,7 @@ class TestE2E(unittest.TestCase):
def test_83_validation_min_max_size_pass(self):
"""File within min/max size range passes validation."""
profiles = load_emulator_profiles(self.emulators_dir)
index = _build_validation_index(profiles)
index = build_validation_index(profiles)
path = self.files["present_req.bin"]["path"]
reason = check_file_validation(path, "present_req.bin", index)
self.assertIsNone(reason)
@@ -1399,7 +1399,7 @@ class TestE2E(unittest.TestCase):
def test_84_validation_crypto_tracked(self):
"""Signature/crypto checks are tracked as non-reproducible."""
profiles = load_emulator_profiles(self.emulators_dir)
index = _build_validation_index(profiles)
index = build_validation_index(profiles)
# correct_hash.bin has [size, signature]
self.assertIn("signature", index["correct_hash.bin"]["crypto_only"])
# Size check still applies despite signature being non-reproducible
@@ -1410,7 +1410,7 @@ class TestE2E(unittest.TestCase):
def test_76_validation_no_effect_when_no_field(self):
"""Files without validation field are unaffected."""
profiles = load_emulator_profiles(self.emulators_dir)
index = _build_validation_index(profiles)
index = build_validation_index(profiles)
# wrong_hash.bin has no validation in any profile
path = self.files["wrong_hash.bin"]["path"]
reason = check_file_validation(path, "wrong_hash.bin", index)
@@ -2063,7 +2063,7 @@ class TestE2E(unittest.TestCase):
def test_111_validation_index_per_emulator(self):
"""Validation index includes per-emulator detail for ground truth."""
profiles = load_emulator_profiles(self.emulators_dir)
index = _build_validation_index(profiles)
index = build_validation_index(profiles)
entry = index["present_req.bin"]
self.assertIn("per_emulator", entry)
pe = entry["per_emulator"]
@@ -2077,7 +2077,7 @@ class TestE2E(unittest.TestCase):
from resolve.validation import build_ground_truth
profiles = load_emulator_profiles(self.emulators_dir)
index = _build_validation_index(profiles)
index = build_validation_index(profiles)
gt = build_ground_truth("present_req.bin", index)
self.assertIsInstance(gt, list)
self.assertTrue(len(gt) >= 1)
@@ -2094,7 +2094,7 @@ class TestE2E(unittest.TestCase):
from resolve.validation import build_ground_truth
profiles = load_emulator_profiles(self.emulators_dir)
index = _build_validation_index(profiles)
index = build_validation_index(profiles)
gt = build_ground_truth("nonexistent.bin", index)
self.assertEqual(gt, [])
@@ -2431,12 +2431,12 @@ class TestE2E(unittest.TestCase):
self.assertFalse(any("present_opt.bin" in n for n in names))
def test_133_platform_system_filter_normalized(self):
"""_norm_system_id normalization matches with manufacturer prefix."""
from model.systems import _norm_system_id
"""norm_system_id normalization matches with manufacturer prefix."""
from model.systems import norm_system_id
self.assertEqual(
_norm_system_id("sony-playstation"),
_norm_system_id("playstation"),
norm_system_id("sony-playstation"),
norm_system_id("playstation"),
)
def test_134_list_systems_platform_context(self):
@@ -3069,38 +3069,38 @@ class TestE2E(unittest.TestCase):
self.assertEqual(records[0]["name"], "good.bin")
def test_157_path_conflict_helpers(self):
"""_has_path_conflict detects file/directory naming collisions."""
from packs.paths import _has_path_conflict, _register_path
"""has_path_conflict detects file/directory naming collisions."""
from packs.paths import has_path_conflict, register_path
seen_files: set[str] = set()
seen_parents: set[str] = set()
# Register system/SGB1.sfc as a file
_register_path("system/SGB1.sfc", seen_files, seen_parents)
register_path("system/SGB1.sfc", seen_files, seen_parents)
# Adding system/SGB1.sfc/program.rom should conflict (parent is a file)
self.assertTrue(
_has_path_conflict("system/SGB1.sfc/program.rom", seen_files, seen_parents)
has_path_conflict("system/SGB1.sfc/program.rom", seen_files, seen_parents)
)
# Adding system/other.bin should not conflict
self.assertFalse(
_has_path_conflict("system/other.bin", seen_files, seen_parents)
has_path_conflict("system/other.bin", seen_files, seen_parents)
)
# Reverse: register a nested path first, then check flat
seen_files2: set[str] = set()
seen_parents2: set[str] = set()
_register_path("system/SGB2.sfc/program.rom", seen_files2, seen_parents2)
register_path("system/SGB2.sfc/program.rom", seen_files2, seen_parents2)
# Adding system/SGB2.sfc as a file should conflict (it's a directory)
self.assertTrue(
_has_path_conflict("system/SGB2.sfc", seen_files2, seen_parents2)
has_path_conflict("system/SGB2.sfc", seen_files2, seen_parents2)
)
# Adding system/SGB2.sfc/boot.rom should not conflict (sibling in same dir)
self.assertFalse(
_has_path_conflict("system/SGB2.sfc/boot.rom", seen_files2, seen_parents2)
has_path_conflict("system/SGB2.sfc/boot.rom", seen_files2, seen_parents2)
)
def test_158_pack_skips_file_directory_conflict(self):
@@ -3264,11 +3264,11 @@ class TestE2E(unittest.TestCase):
def test_164_pack_extras_use_archive_name(self):
"""Pack extras for archived files use archive name, not individual ROM."""
from packs.extras import _collect_emulator_extras
from packs.extras import collect_emulator_extras
config = load_platform_config("test_existence", self.platforms_dir)
profiles = load_emulator_profiles(self.emulators_dir)
extras = _collect_emulator_extras(
extras = collect_emulator_extras(
config,
self.emulators_dir,
self.db,
@@ -3286,11 +3286,11 @@ class TestE2E(unittest.TestCase):
def test_165_pack_extras_multi_dest_cross_ref(self):
"""Same file at different paths from two profiles produces both destinations."""
from packs.extras import _collect_emulator_extras
from packs.extras import collect_emulator_extras
config = load_platform_config("test_existence", self.platforms_dir)
profiles = load_emulator_profiles(self.emulators_dir)
extras = _collect_emulator_extras(
extras = collect_emulator_extras(
config,
self.emulators_dir,
self.db,
@@ -3306,13 +3306,13 @@ class TestE2E(unittest.TestCase):
def test_166_pack_extras_multi_dest_platform_declared(self):
"""Profile with path different from platform destination adds alternative."""
from packs.extras import _collect_emulator_extras
from packs.extras import collect_emulator_extras
config = load_platform_config("test_existence", self.platforms_dir)
profiles = load_emulator_profiles(self.emulators_dir)
# Simulate platform already having present_req.bin at root
seen = {"present_req.bin"}
extras = _collect_emulator_extras(
extras = collect_emulator_extras(
config,
self.emulators_dir,
self.db,
@@ -3396,9 +3396,9 @@ class TestE2E(unittest.TestCase):
_yaml.dump(profile, f)
# Clear profile cache so fresh load picks up our file
from model.profiles import _emulator_profiles_cache
from model.profiles import emulator_profiles_cache
_emulator_profiles_cache.clear()
emulator_profiles_cache.clear()
profiles = load_emulator_profiles(self.emulators_dir)
config = {"cores": ["testcore"]}
@@ -3426,7 +3426,7 @@ class TestE2E(unittest.TestCase):
def test_169_generate_truth_mode_filtering(self):
"""generate_platform_truth excludes standalone-only files for all_libretro."""
import yaml as _yaml
from model.profiles import _emulator_profiles_cache
from model.profiles import emulator_profiles_cache
profile = {
"emulator": "DualMode",
@@ -3461,7 +3461,7 @@ class TestE2E(unittest.TestCase):
with open(os.path.join(self.emulators_dir, "dualmode.yml"), "w") as f:
_yaml.dump(profile, f)
_emulator_profiles_cache.clear()
emulator_profiles_cache.clear()
profiles = load_emulator_profiles(self.emulators_dir)
config = {"cores": "all_libretro"}
@@ -3476,7 +3476,7 @@ class TestE2E(unittest.TestCase):
def test_170_generate_truth_standalone_cores(self):
"""generate_platform_truth uses standalone mode for standalone_cores."""
import yaml as _yaml
from model.profiles import _emulator_profiles_cache
from model.profiles import emulator_profiles_cache
profile = {
"emulator": "DualCore",
@@ -3503,7 +3503,7 @@ class TestE2E(unittest.TestCase):
with open(os.path.join(self.emulators_dir, "dualcore.yml"), "w") as f:
_yaml.dump(profile, f)
_emulator_profiles_cache.clear()
emulator_profiles_cache.clear()
profiles = load_emulator_profiles(self.emulators_dir)
config = {
"cores": ["dualcore"],
@@ -3519,7 +3519,7 @@ class TestE2E(unittest.TestCase):
def test_171_generate_truth_dedup_required_wins(self):
"""Dedup merges cores and required=True wins over required=False."""
import yaml as _yaml
from model.profiles import _emulator_profiles_cache
from model.profiles import emulator_profiles_cache
core_a = {
"emulator": "CoreA",
@@ -3555,7 +3555,7 @@ class TestE2E(unittest.TestCase):
with open(os.path.join(self.emulators_dir, f"{name}.yml"), "w") as f:
_yaml.dump(data, f)
_emulator_profiles_cache.clear()
emulator_profiles_cache.clear()
profiles = load_emulator_profiles(self.emulators_dir)
config = {"cores": ["core_a", "core_b"]}
@@ -3574,7 +3574,7 @@ class TestE2E(unittest.TestCase):
def test_172_generate_truth_coverage_metadata(self):
"""Coverage tracks profiled vs unprofiled cores."""
import yaml as _yaml
from model.profiles import _emulator_profiles_cache
from model.profiles import emulator_profiles_cache
profile = {
"emulator": "ProfiledCore",
@@ -3588,7 +3588,7 @@ class TestE2E(unittest.TestCase):
with open(os.path.join(self.emulators_dir, "profiled_core.yml"), "w") as f:
_yaml.dump(profile, f)
_emulator_profiles_cache.clear()
emulator_profiles_cache.clear()
profiles = load_emulator_profiles(self.emulators_dir)
config = {"cores": ["profiled_core", "unprofiled_core"]}
@@ -4398,9 +4398,9 @@ class TestE2E(unittest.TestCase):
# No profile for core_b (unprofiled)
# Clear cache so the new profile is picked up
from model.profiles import _emulator_profiles_cache
from model.profiles import emulator_profiles_cache
_emulator_profiles_cache.clear()
emulator_profiles_cache.clear()
profiles = load_emulator_profiles(self.emulators_dir)
self.assertIn("core_a", profiles)
self.assertNotIn("core_b", profiles)
@@ -4652,11 +4652,11 @@ class TestE2E(unittest.TestCase):
def test_181_agnostic_extras_scan(self):
"""Agnostic profiles add all matching DB files as extras."""
from packs.extras import _collect_emulator_extras
from packs.extras import collect_emulator_extras
config = load_platform_config("test_existence", self.platforms_dir)
profiles = load_emulator_profiles(self.emulators_dir)
extras = _collect_emulator_extras(
extras = collect_emulator_extras(
config,
self.emulators_dir,
self.db,
@@ -4674,10 +4674,10 @@ class TestE2E(unittest.TestCase):
self.assertTrue(e.get("agnostic_scan", False))
def test_182_agnostic_rename_readme(self):
"""_build_agnostic_rename_readme generates correct text."""
from packs.readme import _build_agnostic_rename_readme
"""build_agnostic_rename_readme generates correct text."""
from packs.readme import build_agnostic_rename_readme
result = _build_agnostic_rename_readme(
result = build_agnostic_rename_readme(
"dsi_nand.bin",
"DSi_Nand_AUS.bin",
["DSi_Nand_EUR.bin", "DSi_Nand_USA.bin"],
@@ -5035,20 +5035,20 @@ struct BurnDriver BurnDrvneogeo = {
def test_201_collect_emulator_extras_include_all(self):
"""include_all=True passes through to find_undeclared_files."""
from packs.extras import _collect_emulator_extras
from packs.extras import collect_emulator_extras
config = self._load_config("test_existence")
profiles = load_emulator_profiles(self.emulators_dir)
base_dest = config.get("base_destination", "")
# Default call must succeed without TypeError
extras = _collect_emulator_extras(
extras = collect_emulator_extras(
config, self.emulators_dir, self.db, set(), base_dest, profiles
)
self.assertIsInstance(extras, list)
# include_all=True must be accepted and return a list
all_extras = _collect_emulator_extras(
all_extras = collect_emulator_extras(
config, self.emulators_dir, self.db, set(), base_dest, profiles,
include_all=True,
)
@@ -6125,9 +6125,9 @@ struct BurnDriver BurnDrvneogeo = {
def test_every_narrowing_names_itself_and_says_so(self):
"""A dimension that removes files must show in the pack name and in the
README. Both are built from _narrowings, so this holds for any new one."""
from packs.readme import _build_readme
from packs.naming import _narrowings
README. Both are built from pack_narrowings, so this holds for any new one."""
from packs.readme import build_readme
from packs.naming import pack_narrowings
dimensions = [
{"source": "platform"},
@@ -6139,7 +6139,7 @@ struct BurnDriver BurnDrvneogeo = {
{"no_game_data": True},
]
for kwargs in dimensions:
applied = _narrowings(
applied = pack_narrowings(
kwargs.get("source", "full"),
kwargs.get("regions"),
kwargs.get("target_name"),
@@ -6151,7 +6151,7 @@ struct BurnDriver BurnDrvneogeo = {
tag, label = applied[0]
self.assertTrue(tag.startswith("_") and len(tag) > 1, kwargs)
self.assertTrue(label.strip(), kwargs)
readme = _build_readme("p", "P", "", 1, 1, narrowings=applied)
readme = build_readme("p", "P", "", 1, 1, narrowings=applied)
self.assertIn("PACK TYPE: Narrowed", readme)
self.assertIn(label, readme)
@@ -6321,7 +6321,7 @@ struct BurnDriver BurnDrvneogeo = {
import inspect
from packs import integrity as packverify
from packs.naming import _narrows_contents, _narrowings
from packs.naming import narrows_contents, pack_narrowings
source = inspect.getsource(packverify.verify_pack_against_platform)
self.assertIn(
@@ -6342,18 +6342,18 @@ struct BurnDriver BurnDrvneogeo = {
# And the pack must not be skipped instead: skipping checks nothing.
for target in ("nintendo-switch", "switch", "rpi4"):
tag = _narrowings("full", None, target, False, False)[0][0]
tag = pack_narrowings("full", None, target, False, False)[0][0]
self.assertFalse(
_narrows_contents(f"Platform_1.0{tag}_BIOS_Pack.zip"),
narrows_contents(f"Platform_1.0{tag}_BIOS_Pack.zip"),
f"a pack built for {target} would skip conformance entirely",
)
def test_standalone_mode_names_itself(self):
"""--emulator --standalone ships a different file set, and without a tag it
overwrote the pack built without it."""
from packs.naming import _narrowings
from packs.naming import pack_narrowings
applied = _narrowings("full", None, None, False, False, standalone=True)
applied = pack_narrowings("full", None, None, False, False, standalone=True)
self.assertEqual([tag for tag, _l in applied], ["_Standalone"])
def test_every_name_builder_uses_the_same_list(self):
@@ -6372,7 +6372,7 @@ struct BurnDriver BurnDrvneogeo = {
'("_Platform_", "_Truth_"',
):
self.assertNotIn(hand_rolled, source, hand_rolled)
self.assertGreaterEqual(source.count("_narrowings("), 8)
self.assertGreaterEqual(source.count("pack_narrowings("), 8)
def test_a_narrowed_system_pack_does_not_take_the_full_name(self):
"""Every dimension has to show in the filename or two builds collide.
@@ -6473,18 +6473,18 @@ struct BurnDriver BurnDrvneogeo = {
self.assertFalse(os.listdir(out) if os.path.isdir(out) else [])
def test_a_full_pack_is_not_announced_as_narrowed(self):
from packs.readme import _build_readme
from packs.naming import _narrowings
from packs.readme import build_readme
from packs.naming import pack_narrowings
self.assertEqual(_narrowings("full", None, None, False, False), [])
self.assertEqual(pack_narrowings("full", None, None, False, False), [])
self.assertNotIn(
"PACK TYPE: Narrowed", _build_readme("p", "P", "", 1, 1)
"PACK TYPE: Narrowed", build_readme("p", "P", "", 1, 1)
)
def test_system_filter_is_announced_too(self):
from packs.readme import _build_readme
from packs.readme import build_readme
readme = _build_readme(
readme = build_readme(
"p", "P", "", 1, 1, system_filter=["sony-playstation"]
)
self.assertIn("PACK TYPE: Narrowed", readme)
@@ -6603,7 +6603,7 @@ struct BurnDriver BurnDrvneogeo = {
self.assertEqual(len(result), len(annotated))
def test_narrowed_variants_skip_conformance(self):
from packs.naming import _narrows_contents
from packs.naming import narrows_contents
for narrowed in (
"EmuDeck_2.3.8_Required_BIOS_Pack.zip",
@@ -6611,14 +6611,14 @@ struct BurnDriver BurnDrvneogeo = {
"EmuDeck_2.3.8_Truth_Required_BIOS_Pack.zip",
"EmuDeck_2.3.8_NorthAmerica_Required_BIOS_Pack.zip",
):
self.assertTrue(_narrows_contents(narrowed), narrowed)
self.assertTrue(narrows_contents(narrowed), narrowed)
for full in (
"EmuDeck_2.3.8_BIOS_Pack.zip",
"EmuDeck_2.3.8_NorthAmerica_BIOS_Pack.zip",
"RetroArch_v1.22.2_Switch_BIOS_Pack.zip",
):
self.assertFalse(_narrows_contents(full), full)
self.assertFalse(narrows_contents(full), full)
def test_target_tag_formats_hardware_names(self):
from packs.naming import _target_tag
@@ -6643,9 +6643,9 @@ struct BurnDriver BurnDrvneogeo = {
self.assertIn("Switch", name)
def test_readme_region_section_lists_fallback_systems(self):
from packs.readme import _build_readme
from packs.readme import build_readme
text = _build_readme(
text = build_readme(
"regionplat",
"RegionPlat",
"",
@@ -6661,9 +6661,9 @@ struct BurnDriver BurnDrvneogeo = {
self.assertNotIn("All are included", text)
def test_readme_without_region_keeps_the_regional_note(self):
from packs.readme import _build_readme
from packs.readme import build_readme
text = _build_readme("regionplat", "RegionPlat", "", 10, 2)
text = build_readme("regionplat", "RegionPlat", "", 10, 2)
self.assertNotIn("PACK TYPE: Region Filtered", text)
self.assertIn("All are included", text)
@@ -6794,9 +6794,9 @@ class OneOfASearchList(unittest.TestCase):
"""
def setUp(self):
from model.profiles import _emulator_profiles_cache
from model.profiles import emulator_profiles_cache
_emulator_profiles_cache.clear()
emulator_profiles_cache.clear()
repo = Path(__file__).resolve().parent.parent
(repo / "tmp").mkdir(exist_ok=True)
self.root = Path(tempfile.mkdtemp(dir=repo / "tmp"))
@@ -7060,9 +7060,9 @@ class AnArchiveIsAMemberOfASet(unittest.TestCase):
def _fixture(self, held: bool) -> dict:
import zlib
from model.profiles import _emulator_profiles_cache
from model.profiles import emulator_profiles_cache
_emulator_profiles_cache.clear()
emulator_profiles_cache.clear()
repo = Path(__file__).resolve().parent.parent
(repo / "tmp").mkdir(exist_ok=True)
root = Path(tempfile.mkdtemp(dir=repo / "tmp"))
+2 -2
View File
@@ -80,11 +80,11 @@ class APlaceholderIsAnsweredByEvidence(unittest.TestCase):
import yaml
from model.profiles import _emulator_profiles_cache
from model.profiles import emulator_profiles_cache
from packs.emulatorpack import generate_emulator_pack
from packs.emulatorcheck import verify_emulator
_emulator_profiles_cache.clear()
emulator_profiles_cache.clear()
(REPO_ROOT / "tmp").mkdir(exist_ok=True)
root = Path(tempfile.mkdtemp(dir=REPO_ROOT / "tmp"))
self.addCleanup(shutil.rmtree, root, True)
+2 -2
View File
@@ -97,9 +97,9 @@ class CorrectedFilesPage(unittest.TestCase):
for platform in ("recalbox", "retropie"):
self.assertIn(f'href="api/v1/exports/{platform}.json"', self.page)
source = script_source("generate_site.py")
publish = source[source.index("def _publish_manifests("):]
publish = source[source.index("def publish_manifests("):]
publish = publish[:publish.index("\ndef ")]
self.assertIn('(_REPO_ROOT / "exports").glob("*.json")', publish)
self.assertIn('(REPO_ROOT / "exports").glob("*.json")', publish)
self.assertIn('exports = api / "exports"', publish)
def test_several_files_link_to_their_directory(self):
+5 -5
View File
@@ -15,7 +15,7 @@ import unittest
from pathlib import Path
from model.profiles import PROFILE_IDENTITY_FIELDS
from packs.extras import _collect_emulator_extras
from packs.extras import collect_emulator_extras
from packs.gaps import find_undeclared_files
REPO_ROOT = Path(__file__).resolve().parents[1]
@@ -46,7 +46,7 @@ class IdentityTravels(unittest.TestCase):
"by_crc32": {"12345678": "s1"}},
}
report = find_undeclared_files(config, "emulators", db, emu_profiles={"np2kai": profile})
extras = _collect_emulator_extras(
extras = collect_emulator_extras(
config, "emulators", db, set(), "", {"np2kai": profile}, include_all=True
)
for label, item in (("report", report[0]), ("extra", extras[0])):
@@ -91,7 +91,7 @@ class UnsourceableIsNoCopy(unittest.TestCase):
"by_crc32": {"c1": "s1"},
"by_path_suffix": {"zc210/sf2/default.sf2": ["s1"]}},
}
extras = _collect_emulator_extras(config, "emulators", db, set(), "", profiles)
extras = collect_emulator_extras(config, "emulators", db, set(), "", profiles)
self.assertEqual(
[(e["source_profile"], e["destination"]) for e in extras],
[("zc210", "zc210/sf2/default.sf2")],
@@ -117,7 +117,7 @@ class BareNameIsADestination(unittest.TestCase):
"indexes": {"by_name": {"syscard1.pce": ["s1"]}, "by_md5": {"m1": "s1"},
"by_crc32": {"c1": "s1"}, "by_path_suffix": {}},
}
extras = _collect_emulator_extras(
extras = collect_emulator_extras(
config, "emulators", db, {"pcenginecd/syscard1.pce"}, "", profiles
)
self.assertIn("syscard1.pce", [e["destination"] for e in extras])
@@ -142,7 +142,7 @@ class ArchiveMembersStayInside(unittest.TestCase):
"indexes": {"by_name": {"msx.rom": ["s1"]}, "by_md5": {"m1": "s1"},
"by_crc32": {"c1": "s1"}, "by_path_suffix": {}},
}
extras = _collect_emulator_extras(config, "emulators", db, set(), "", profiles)
extras = collect_emulator_extras(config, "emulators", db, set(), "", profiles)
loose = [e for e in extras if e["destination"] == "msx.rom"]
self.assertEqual([e["source_profile"] for e in loose], ["zesarux"])
+1 -1
View File
@@ -27,7 +27,7 @@ class ThePinnedRevisionIsInTheHistory(unittest.TestCase):
def fetch(url, *_a, **_k):
return next(data for sha, data in blobs.items() if f"/{sha}/" in url)
with mock.patch.object(upstream, "_api", api), mock.patch.object(upstream, "_fetch", fetch):
with mock.patch.object(upstream, "cached_api", api), mock.patch.object(upstream, "fetch_body", fetch):
found = history.find_revision(
repo, "dists/engine-data/queen.tbl",
hashlib.md5(b"pinned").hexdigest(), "unused")
+3 -3
View File
@@ -107,10 +107,10 @@ class AReleaseNamedAfterTheTree(unittest.TestCase):
def test_only_whole_leading_words_name_the_tree(self):
"""dolphin-mmjr2 is not a release of dolphin-mmjr: mmjr2 is one word."""
from resolve.ownership import _owner_tokens
from resolve.ownership import owner_tokens
self.assertNotIn("dolphinmmjr", _owner_tokens({"source_profile": "dolphin-mmjr2"}))
self.assertIn("cxbxreloaded", _owner_tokens({"source_profile": "cxbx-reloaded-2023"}))
self.assertNotIn("dolphinmmjr", owner_tokens({"source_profile": "dolphin-mmjr2"}))
self.assertIn("cxbxreloaded", owner_tokens({"source_profile": "cxbx-reloaded-2023"}))
class AnotherMachinesRomIsNotServed(unittest.TestCase):
+2 -2
View File
@@ -224,7 +224,7 @@ class SecondPassKeepsIdentity(unittest.TestCase):
"""
def test_flag_and_hashes_reach_the_alternative_destination(self):
from packs.extras import _collect_emulator_extras
from packs.extras import collect_emulator_extras
sha = "a" * 40
md5 = "b" * 32
@@ -247,7 +247,7 @@ class SecondPassKeepsIdentity(unittest.TestCase):
{"name": "pak1.pk3", "path": "maintt/pak1.pk3", "sha1": "c" * 40},
],
}}
extras = {e["destination"]: e for e in _collect_emulator_extras(
extras = {e["destination"]: e for e in collect_emulator_extras(
config, "emulators", db, set(), "", profiles)}
# Unsourceable is settled, as in the first pass: no copy at all.
self.assertNotIn("mainta/pak1.pk3", extras)
+2 -2
View File
@@ -93,8 +93,8 @@ class TheSiteReadsAHashFieldTheResolversWay(unittest.TestCase):
("0xDEADBEEF", ["deadbeef"]), (12345678, ["12345678"]),
):
with self.subTest(raw=raw):
self.assertEqual(lookup._hash_values(raw), expected)
self.assertEqual(lookup._hash_values(raw), sorted(hashing.parse_hash_list(raw)))
self.assertEqual(lookup.sorted_hash_values(raw), expected)
self.assertEqual(lookup.sorted_hash_values(raw), sorted(hashing.parse_hash_list(raw)))
if __name__ == "__main__":
+1 -1
View File
@@ -193,7 +193,7 @@ class TheReplayResolvesAsTheBuilder(unittest.TestCase):
)
placed: set[str] = set()
with mock.patch.object(packextras, "_collect_emulator_extras", return_value=extras):
with mock.patch.object(packextras, "collect_emulator_extras", return_value=extras):
hidden = packextras.hidden_extras(
{"systems": {}}, "emulators", {"files": {}}, {}, {},
placed=placed, resolver=Resolver(),
+4 -4
View File
@@ -369,11 +369,11 @@ class APlatformOmissionKeepsItsClaim(unittest.TestCase):
from packs import manifestentry
held = {"cores": None}
self.assertTrue(manifestentry._claim_platform_omission(held, "melonds"))
self.assertTrue(manifestentry._claim_platform_omission(held, "melonds"))
self.assertTrue(manifestentry.claim_platform_omission(held, "melonds"))
self.assertTrue(manifestentry.claim_platform_omission(held, "melonds"))
self.assertEqual(held["alternatives"], [{"cores": ["melonds"]}])
self.assertFalse(manifestentry._claim_platform_omission({"cores": ["x"]}, "melonds"))
self.assertFalse(manifestentry._claim_platform_omission(None, "melonds"))
self.assertFalse(manifestentry.claim_platform_omission({"cores": ["x"]}, "melonds"))
self.assertFalse(manifestentry.claim_platform_omission(None, "melonds"))
def test_the_boundary_takes_only_core_names(self):
manifest = {"manifest_version": 2, "platform": "retroarch", "files": [],
+9 -9
View File
@@ -1053,7 +1053,7 @@ class AHeldFileTheInstallerCannotFetch(unittest.TestCase):
def setUp(self):
from model import profiles
from model.platforms import _platform_config_cache
from model.profiles import _emulator_profiles_cache
from model.profiles import emulator_profiles_cache
import generate_db
tmp = tempfile.TemporaryDirectory(dir=REPO_ROOT / "tmp")
self.addCleanup(tmp.cleanup)
@@ -1096,9 +1096,9 @@ class AHeldFileTheInstallerCannotFetch(unittest.TestCase):
"required": True},
]}))
_platform_config_cache.clear()
_emulator_profiles_cache.clear()
emulator_profiles_cache.clear()
self.addCleanup(_platform_config_cache.clear)
self.addCleanup(_emulator_profiles_cache.clear)
self.addCleanup(emulator_profiles_cache.clear)
self.profiles = profiles.load_emulator_profiles("emulators")
def _manifest(self, regions):
@@ -1134,7 +1134,7 @@ class AStandaloneLayoutBelowTheBiosFolder(unittest.TestCase):
def setUp(self):
from model import profiles
from model.platforms import _platform_config_cache
from model.profiles import _emulator_profiles_cache
from model.profiles import emulator_profiles_cache
import generate_db
tmp = tempfile.TemporaryDirectory(dir=REPO_ROOT / "tmp")
self.addCleanup(tmp.cleanup)
@@ -1179,9 +1179,9 @@ class AStandaloneLayoutBelowTheBiosFolder(unittest.TestCase):
for name in ("eu.bin", "jp.bin")
]}))
_platform_config_cache.clear()
_emulator_profiles_cache.clear()
emulator_profiles_cache.clear()
self.addCleanup(_platform_config_cache.clear)
self.addCleanup(_emulator_profiles_cache.clear)
self.addCleanup(emulator_profiles_cache.clear)
self.profiles = profiles.load_emulator_profiles("emulators")
def _manifest(self, regions):
@@ -1217,7 +1217,7 @@ class AnExtraBesideItsDeclarationBelowTheBiosFolder(unittest.TestCase):
def setUp(self):
from model import profiles
from model.platforms import _platform_config_cache
from model.profiles import _emulator_profiles_cache
from model.profiles import emulator_profiles_cache
import generate_db
tmp = tempfile.TemporaryDirectory(dir=REPO_ROOT / "tmp")
self.addCleanup(tmp.cleanup)
@@ -1268,9 +1268,9 @@ class AnExtraBesideItsDeclarationBelowTheBiosFolder(unittest.TestCase):
{"name": "us.bin", "path": "alt/us.bin", "system": "sys", "required": False},
]}))
_platform_config_cache.clear()
_emulator_profiles_cache.clear()
emulator_profiles_cache.clear()
self.addCleanup(_platform_config_cache.clear)
self.addCleanup(_emulator_profiles_cache.clear)
self.addCleanup(emulator_profiles_cache.clear)
self.profiles = profiles.load_emulator_profiles("emulators")
def _manifest(self, regions):
+2 -2
View File
@@ -30,7 +30,7 @@ import yaml
import verify
from packs import coverage
from packs import report as packs_report
from model.profiles import _emulator_profiles_cache, load_emulator_profiles
from model.profiles import emulator_profiles_cache, load_emulator_profiles
from model.platforms import load_platform_config
from cross_reference import LAUNCHER_READS_KEY, LAUNCHER_UNPROVEN_KEY, print_launcher_reads
from packs.crossref import launcher_file_names, launcher_reads_not_held
@@ -82,7 +82,7 @@ LAUNCHERS = [
class LauncherGapTest(unittest.TestCase):
def setUp(self) -> None:
_emulator_profiles_cache.clear()
emulator_profiles_cache.clear()
self.root = tempfile.mkdtemp()
self.bios_dir = os.path.join(self.root, "bios")
self.platforms_dir = os.path.join(self.root, "platforms")
+10 -10
View File
@@ -21,7 +21,7 @@ import zipfile
import yaml
from model.profiles import _emulator_profiles_cache, load_emulator_profiles
from model.profiles import emulator_profiles_cache, load_emulator_profiles
from model.platforms import load_platform_config
from resolve.launchers import LauncherLayer, launcher_places, suffixed_stem
from packs.gaps import find_undeclared_files
@@ -41,7 +41,7 @@ def _md5(data: bytes) -> str:
class LauncherLayerTest(unittest.TestCase):
def setUp(self) -> None:
_emulator_profiles_cache.clear()
emulator_profiles_cache.clear()
self.root = tempfile.mkdtemp()
self.bios_dir = os.path.join(self.root, "bios")
self.platforms_dir = os.path.join(self.root, "platforms")
@@ -198,7 +198,7 @@ class LauncherLayerTest(unittest.TestCase):
}
with open(os.path.join(self.emulators_dir, "fixemu.yml"), "w") as fh:
yaml.dump(profile, fh)
_emulator_profiles_cache.clear()
emulator_profiles_cache.clear()
self.profiles = load_emulator_profiles(self.emulators_dir)
added = [u["path"] for u in self._report() if u.get("launcher")]
self.assertNotIn("sub/fix.bin", added)
@@ -226,7 +226,7 @@ class LauncherLayerTest(unittest.TestCase):
yaml.dump(profile, fh)
self.config["launchers"][2]["names"] = ["v103.bin"]
self.config["launchers"][2]["search_dir"] = "/userdata/bios"
_emulator_profiles_cache.clear()
emulator_profiles_cache.clear()
self.profiles = load_emulator_profiles(self.emulators_dir)
report = {u["path"]: u for u in self._report()}
self.assertNotIn("flash.bin", report)
@@ -247,7 +247,7 @@ class LauncherLayerTest(unittest.TestCase):
with open(os.path.join(self.emulators_dir, "fixemu.yml"), "w") as fh:
yaml.dump(profile, fh)
self.config["launchers"][2]["names"] = ["plain.bin"]
_emulator_profiles_cache.clear()
emulator_profiles_cache.clear()
self.profiles = load_emulator_profiles(self.emulators_dir)
self.assertNotIn("core.bin", {u["name"] for u in self._report()})
self.assertNotIn("core.bin", self._pack_names())
@@ -266,7 +266,7 @@ class LauncherLayerTest(unittest.TestCase):
yaml.dump(profile, fh)
self.config["launchers"][2]["names"] = ["launcher.rom"]
self.config["launchers"][2]["passes_to"] = "command line -romslot"
_emulator_profiles_cache.clear()
emulator_profiles_cache.clear()
self.profiles = load_emulator_profiles(self.emulators_dir)
added = {u["path"]: u for u in self._report() if u.get("launcher")}
self.assertEqual(added["launcher.rom"]["launcher_of"], "core.bin")
@@ -283,7 +283,7 @@ class LauncherLayerTest(unittest.TestCase):
with open(os.path.join(self.emulators_dir, "fixemu.yml"), "w") as fh:
yaml.dump(profile, fh)
self.config["launchers"][2]["names"] = ["kick.A500.rom"]
_emulator_profiles_cache.clear()
emulator_profiles_cache.clear()
self.profiles = load_emulator_profiles(self.emulators_dir)
added = {u["path"]: u for u in self._report() if u.get("launcher")}
self.assertEqual(added["kick.A500.rom"]["md5"], _md5(CONTENT["core.bin"]))
@@ -302,7 +302,7 @@ class LauncherLayerTest(unittest.TestCase):
self.config["systems"]["test-sys"]["files"].append(
{"name": "core.bin", "destination": "core.bin", "required": True}
)
_emulator_profiles_cache.clear()
emulator_profiles_cache.clear()
self.profiles = load_emulator_profiles(self.emulators_dir)
added = {u["path"]: u for u in self._report() if u.get("launcher")}
self.assertEqual(added["kick.A500.rom"]["md5"], _md5(CONTENT["core.bin"]))
@@ -353,7 +353,7 @@ class LauncherLayerTest(unittest.TestCase):
"overrides": [],
"source_ref": "core-options.cfg:515",
})
_emulator_profiles_cache.clear()
emulator_profiles_cache.clear()
self.profiles = load_emulator_profiles(self.emulators_dir)
added = {u["path"]: u for u in self._report() if u.get("launcher")}
self.assertEqual(added["ps2/bios/scph10000.bin"]["md5"], _md5(older))
@@ -460,7 +460,7 @@ class LauncherLayerTest(unittest.TestCase):
self.assertIn("LauncherLayer(", inspect.getsource(packs_gaps.find_undeclared_files))
self.assertIn(".settle(", inspect.getsource(packs_gaps.find_undeclared_files))
self.assertIn(
"undeclared_report(", inspect.getsource(packextras._collect_emulator_extras)
"undeclared_report(", inspect.getsource(packextras.collect_emulator_extras)
)
self.assertIn(
"find_undeclared_files(", inspect.getsource(packextras.undeclared_report)
+6 -6
View File
@@ -23,7 +23,7 @@ from pathlib import Path
import yaml
from model.profiles import _emulator_profiles_cache, load_emulator_profiles
from model.profiles import emulator_profiles_cache, load_emulator_profiles
from model.platforms import load_platform_config
from resolve.standalone import platform_layouts, standalone_set
from packs.manifest import generate_manifest
@@ -46,7 +46,7 @@ LINK = {
class ALinkMovesTheDestination(unittest.TestCase):
def setUp(self) -> None:
_emulator_profiles_cache.clear()
emulator_profiles_cache.clear()
(REPO_ROOT / "tmp").mkdir(exist_ok=True)
self.root = Path(tempfile.mkdtemp(dir=REPO_ROOT / "tmp"))
self.addCleanup(shutil.rmtree, self.root, True)
@@ -161,7 +161,7 @@ class ALinkMovesTheDestination(unittest.TestCase):
"systems": ["commodore-amiga"],
"files": [{"name": "kick.rom", "path": "kick.rom", "required": False}],
}))
_emulator_profiles_cache.clear()
emulator_profiles_cache.clear()
manifest = self.manifest("linkplat")
(held,) = [f for f in manifest["files"] if f["dest"] == "kick.rom"]
self.assertEqual(held["cores"], ["other"])
@@ -175,7 +175,7 @@ class ALinkMovesTheDestination(unittest.TestCase):
for key in ("kick-1", "kick-2"):
(self.emulators / f"{key}.yml").write_text(
yaml.safe_dump({**data, "built_by": ["linkplat"]}))
_emulator_profiles_cache.clear()
emulator_profiles_cache.clear()
omitted = [o for o in self.manifest("linkplat")["omitted_files"]
if o["name"] == "kick.rom"]
self.assertEqual([(o["root"], o["cores"]) for o in omitted],
@@ -305,7 +305,7 @@ class AProgramRunFromItsFolder(unittest.TestCase):
"""
def setUp(self) -> None:
_emulator_profiles_cache.clear()
emulator_profiles_cache.clear()
(REPO_ROOT / "tmp").mkdir(exist_ok=True)
self.root = Path(tempfile.mkdtemp(dir=REPO_ROOT / "tmp"))
self.addCleanup(shutil.rmtree, self.root, True)
@@ -572,7 +572,7 @@ class ASettingSetsTheBiosFolder(unittest.TestCase):
"""
def setUp(self) -> None:
_emulator_profiles_cache.clear()
emulator_profiles_cache.clear()
(REPO_ROOT / "tmp").mkdir(exist_ok=True)
self.root = Path(tempfile.mkdtemp(dir=REPO_ROOT / "tmp"))
self.addCleanup(shutil.rmtree, self.root, True)
+6 -6
View File
@@ -15,7 +15,7 @@ import os
import unittest
from pathlib import Path
from packs.paths import _resolve_destination
from packs.paths import resolve_destination
from resolve.validation import outside_gap_scope, read_from_save_dir, read_from_system_dir
REPO_ROOT = Path(__file__).resolve().parents[1]
@@ -24,11 +24,11 @@ REPO_ROOT = Path(__file__).resolve().parents[1]
class PathIsTheDestination(unittest.TestCase):
def test_no_prefix_on_a_file(self):
entry = {"name": "ppge_atlas.zim", "path": "PPSSPP/ppge_atlas.zim"}
self.assertEqual(_resolve_destination(entry, False), "PPSSPP/ppge_atlas.zim")
self.assertEqual(resolve_destination(entry, False), "PPSSPP/ppge_atlas.zim")
dual = {"name": "IPL.bin", "path": "dolphin-emu/Sys/GC/USA/IPL.bin",
"standalone_path": "GC/USA/IPL.bin"}
self.assertEqual(_resolve_destination(dual, False), "dolphin-emu/Sys/GC/USA/IPL.bin")
self.assertEqual(_resolve_destination(dual, True), "GC/USA/IPL.bin")
self.assertEqual(resolve_destination(dual, False), "dolphin-emu/Sys/GC/USA/IPL.bin")
self.assertEqual(resolve_destination(dual, True), "GC/USA/IPL.bin")
class LoadFromPerBuild(unittest.TestCase):
@@ -63,10 +63,10 @@ class RetroArchCarriesDolphinWhereItReads(unittest.TestCase):
from model.database import load_database
from model.profiles import load_emulator_profiles
from model.platforms import load_platform_config
from packs.extras import _collect_emulator_extras
from packs.extras import collect_emulator_extras
config = load_platform_config("retroarch")
extras = _collect_emulator_extras(
extras = collect_emulator_extras(
config, "emulators", load_database("database.json"), set(),
config.get("base_destination", ""), load_emulator_profiles("emulators"),
)
+3 -3
View File
@@ -29,7 +29,7 @@ from model import cliargs, platforms
from resolve import cores, grouping, localfile
from model.database import load_database
from model.platforms import _platform_config_cache
from model.profiles import _emulator_profiles_cache, load_emulator_profiles
from model.profiles import emulator_profiles_cache, load_emulator_profiles
from model.registry import list_registered_platforms, load_data_dir_registry
from resolve.localfile import resolve_local_file
from resolve.ownership import BUCKET_FOLDERS, names_manufacturer
@@ -104,13 +104,13 @@ class _Collection(unittest.TestCase):
)
self.db = load_database("database.json")
_platform_config_cache.clear()
_emulator_profiles_cache.clear()
emulator_profiles_cache.clear()
self.config = platforms.load_platform_config("handheld", "platforms")
self.profiles = load_emulator_profiles("emulators")
def tearDown(self):
_platform_config_cache.clear()
_emulator_profiles_cache.clear()
emulator_profiles_cache.clear()
os.chdir(self._cwd)
self._tmp.cleanup()
+3 -3
View File
@@ -626,7 +626,7 @@ class APickReadsTheEntrySystems(unittest.TestCase):
self.assertTrue(entry_serves_systems({}, profile, ["snk-neogeo-mvs"]))
def test_the_gap_report_and_the_extras_carry_them(self):
from packs.extras import _collect_emulator_extras, _extra_system_ids
from packs.extras import collect_emulator_extras, extra_system_ids
from packs.gaps import find_undeclared_files
profile = {
@@ -643,10 +643,10 @@ class APickReadsTheEntrySystems(unittest.TestCase):
}
(gap,) = find_undeclared_files(config, "emulators", db, emu_profiles={"mame": profile})
self.assertEqual(gap["systems"], ["apple2gs", "coco"])
(extra,) = _collect_emulator_extras(
(extra,) = collect_emulator_extras(
config, "emulators", db, set(), "", {"mame": profile}, include_all=True
)
self.assertEqual(_extra_system_ids(extra), ["apple2gs", "coco"])
self.assertEqual(extra_system_ids(extra), ["apple2gs", "coco"])
def test_the_schema_and_the_profile_list(self):
try:
+1 -1
View File
@@ -66,7 +66,7 @@ class AnEntryWithoutSourceIsAnOmission(unittest.TestCase):
omitted[full_dest] = reason
with mock.patch.object(manifestentry, "compute_hashes", return_value=hashes):
manifestcores._manifest_core_entries(
manifestcores.manifest_core_entries(
[extra], {}, self.db, str(REPO_ROOT / "bios"), "", str(REPO_ROOT),
{}, True,
region_drops=set(), case_insensitive=False, seen_destinations=set(),
+3 -3
View File
@@ -75,7 +75,7 @@ class SystemAndEmulatorPacksKeepTheirNames(unittest.TestCase):
import yaml
from model.profiles import _emulator_profiles_cache
from model.profiles import emulator_profiles_cache
import generate_db
from packs import emulatorpack
@@ -99,7 +99,7 @@ class SystemAndEmulatorPacksKeepTheirNames(unittest.TestCase):
"systems": ["sega-triforce"],
"files": [{"name": "segaboot.gcm", "required": True}],
}))
_emulator_profiles_cache.clear()
emulator_profiles_cache.clear()
try:
emulator_pack = emulatorpack.generate_emulator_pack(
["triforce"], str(root / "emulators"), db, str(root / "bios"),
@@ -110,7 +110,7 @@ class SystemAndEmulatorPacksKeepTheirNames(unittest.TestCase):
str(root / "bios"), str(out), offline=True,
)
finally:
_emulator_profiles_cache.clear()
emulator_profiles_cache.clear()
self.assertNotEqual(Path(emulator_pack).name, Path(system_pack).name)
self.assertTrue(Path(emulator_pack).exists())
self.assertTrue(Path(system_pack).exists())
+2 -2
View File
@@ -169,9 +169,9 @@ class PackPlacesCoreFilesUnderTheTag(unittest.TestCase):
folder the platform hands it, and nowhere else."""
def setUp(self):
from model.profiles import _emulator_profiles_cache
from model.profiles import emulator_profiles_cache
_emulator_profiles_cache.clear()
emulator_profiles_cache.clear()
self.root = tempfile.mkdtemp(dir=REPO_ROOT / "tmp" / "tests")
self.bios = os.path.join(self.root, "bios")
self.platforms = os.path.join(self.root, "platforms")
+6 -6
View File
@@ -221,12 +221,12 @@ class GapAnalysisAgreesWithTheBuilder(unittest.TestCase):
return tmp, root, db
def _in_repo(self, mode: str) -> bool:
from model.profiles import _emulator_profiles_cache, load_emulator_profiles
from model.profiles import emulator_profiles_cache, load_emulator_profiles
from packs.gaps import find_undeclared_files
tmp, root, db = self._fixture()
try:
_emulator_profiles_cache.clear()
emulator_profiles_cache.clear()
profiles = load_emulator_profiles(str(root / "emulators"))
config = {
"platform": "Demo",
@@ -240,7 +240,7 @@ class GapAnalysisAgreesWithTheBuilder(unittest.TestCase):
entry = next(e for e in found if e["name"] == "collide.rom")
return bool(entry["in_repo"])
finally:
_emulator_profiles_cache.clear()
emulator_profiles_cache.clear()
tmp.cleanup()
def test_a_digest_mode_does_not_call_a_contradicted_copy_available(self):
@@ -367,7 +367,7 @@ class SkippingIsNotSettling(unittest.TestCase):
import hashlib
import tempfile
from model.profiles import _emulator_profiles_cache, load_emulator_profiles
from model.profiles import emulator_profiles_cache, load_emulator_profiles
from packs.gaps import find_undeclared_files
tmp = tempfile.TemporaryDirectory()
@@ -398,7 +398,7 @@ class SkippingIsNotSettling(unittest.TestCase):
"files:\n" + entry
)
try:
_emulator_profiles_cache.clear()
emulator_profiles_cache.clear()
profiles = load_emulator_profiles(str(root / "emulators"))
config = {
"platform": "Demo", "verification_mode": "existence",
@@ -409,7 +409,7 @@ class SkippingIsNotSettling(unittest.TestCase):
)
return {(u["emulator"], u["name"]) for u in found}
finally:
_emulator_profiles_cache.clear()
emulator_profiles_cache.clear()
tmp.cleanup()
def test_the_profile_that_needs_the_file_still_reports_it(self):
+3 -3
View File
@@ -29,7 +29,7 @@ from pathlib import Path
import yaml
from model.platforms import load_platform_config, _platform_config_cache
from model.profiles import _emulator_profiles_cache
from model.profiles import emulator_profiles_cache
import generate_db
from packs import archive as packs_archive
from packs import manifest as packs_manifest
@@ -107,13 +107,13 @@ class _Fixture(unittest.TestCase):
yaml.dump({"platforms": {"handheld": {"config": "handheld.yml"}}})
)
_platform_config_cache.clear()
_emulator_profiles_cache.clear()
emulator_profiles_cache.clear()
self.out = self.root / "dist"
self.out.mkdir()
def tearDown(self):
_platform_config_cache.clear()
_emulator_profiles_cache.clear()
emulator_profiles_cache.clear()
self._tmp.cleanup()
def pack(self, no_game_data: bool) -> tuple[str, set[str], str]:
+2 -2
View File
@@ -64,10 +64,10 @@ class ConformanceUsesTheRunDirectories(unittest.TestCase):
with mock.patch.object(packs_finalize, "list_registered_platforms", return_value=["fix"]), \
mock.patch.object(
packs_finalize, "_expected_pack_names",
packs_finalize, "expected_pack_names",
return_value={"fix": {"Fix_BIOS_Pack.zip"}},
), \
mock.patch.object(packs_finalize, "_pack_archives", return_value=["Fix_BIOS_Pack.zip"]), \
mock.patch.object(packs_finalize, "pack_archives", return_value=["Fix_BIOS_Pack.zip"]), \
mock.patch.object(
packs_finalize, "verify_pack",
return_value=(True, {"summary": {
+4 -4
View File
@@ -150,7 +150,7 @@ class NarrowedPacksAgainstTheirOwnList(unittest.TestCase):
def setUp(self):
from model.platforms import _platform_config_cache
from model.profiles import load_emulator_profiles, _emulator_profiles_cache
from model.profiles import load_emulator_profiles, emulator_profiles_cache
import generate_db
tmp = tempfile.TemporaryDirectory(dir=REPO_ROOT / "tmp")
self.addCleanup(tmp.cleanup)
@@ -185,9 +185,9 @@ class NarrowedPacksAgainstTheirOwnList(unittest.TestCase):
{"name": "extra.bin", "path": "extra.bin", "required": False},
]}), encoding="utf-8")
_platform_config_cache.clear()
_emulator_profiles_cache.clear()
emulator_profiles_cache.clear()
self.addCleanup(_platform_config_cache.clear)
self.addCleanup(_emulator_profiles_cache.clear)
self.addCleanup(emulator_profiles_cache.clear)
self.profiles = load_emulator_profiles("emulators")
def _build(self, source: str, required: bool) -> tuple[str, set[str]]:
@@ -221,7 +221,7 @@ class NarrowedPacksAgainstTheirOwnList(unittest.TestCase):
ok, _c, _p, errors, *_rest = self._check(zip_path, source, required)
self.assertTrue(ok, errors)
self.assertEqual(
naming._pack_variant(os.path.basename(zip_path)), (source, required)
naming.pack_variant(os.path.basename(zip_path)), (source, required)
)
def test_a_narrowed_pack_missing_a_required_file_fails(self):
+5 -5
View File
@@ -30,7 +30,7 @@ except ImportError:
jsonschema = None
from core.artifacts import ArtifactLockBusy, artifact_lock
from model.platforms import _platform_config_cache
from model.profiles import _emulator_profiles_cache, load_emulator_profiles
from model.profiles import emulator_profiles_cache, load_emulator_profiles
import generate_db
from packs import archive as packs_archive
from packs import datatrees
@@ -111,11 +111,11 @@ class PackCountFixture(unittest.TestCase):
yaml.dump({"platforms": {"demo": {"config": "demo.yml"}}})
)
(self.emulators / "demo.yml").write_text(PROFILE)
_emulator_profiles_cache.clear()
emulator_profiles_cache.clear()
self.profiles = load_emulator_profiles(str(self.emulators))
def tearDown(self):
_emulator_profiles_cache.clear()
emulator_profiles_cache.clear()
self._tmp.cleanup()
def _manifest(self) -> dict:
@@ -656,7 +656,7 @@ class CoreCopiesKeepTheirCategory(unittest.TestCase):
copies, game data, under core files."""
def test_a_copy_counts_as_its_entry_says(self):
from packs.extras import _collect_emulator_extras, hidden_extras
from packs.extras import collect_emulator_extras, hidden_extras
with tempfile.TemporaryDirectory(dir=REPO_ROOT / "tmp") as tmp:
held = Path(tmp) / "x.dat"
@@ -672,7 +672,7 @@ class CoreCopiesKeepTheirCategory(unittest.TestCase):
}}
db = {"files": {sha1: {"path": str(held), "name": "x.dat", "sha1": sha1}},
"indexes": {"by_name": {"x.dat": [sha1]}, "by_path_suffix": {}}}
(extra,) = _collect_emulator_extras(
(extra,) = collect_emulator_extras(
config, "emulators", db, {"x.dat"}, "", profiles
)
self.assertEqual(
+6 -6
View File
@@ -29,9 +29,9 @@ REPO_ROOT = Path(__file__).resolve().parents[1]
class _Fixture(unittest.TestCase):
def setUp(self) -> None:
from model.profiles import _emulator_profiles_cache
from model.profiles import emulator_profiles_cache
_emulator_profiles_cache.clear()
emulator_profiles_cache.clear()
(REPO_ROOT / "tmp").mkdir(exist_ok=True)
self.root = Path(tempfile.mkdtemp(dir=REPO_ROOT / "tmp"))
self.addCleanup(shutil.rmtree, self.root, True)
@@ -175,9 +175,9 @@ class EveryNarrowingIsCompared(unittest.TestCase):
import inspect
import pipeline
from packs.naming import _narrowings
from packs.naming import pack_narrowings
dimensions = set(inspect.signature(_narrowings).parameters)
dimensions = set(inspect.signature(pack_narrowings).parameters)
compared = set(pipeline.NARROWINGS_COMPARED)
exempt = set(pipeline.NARROWINGS_NOT_COMPARED)
self.assertFalse(compared & exempt)
@@ -192,10 +192,10 @@ class EveryNarrowingIsCompared(unittest.TestCase):
import inspect
import pipeline
from packs.naming import _narrowings
from packs.naming import pack_narrowings
from packs.emulatorpack import generate_emulator_pack
taken = (set(inspect.signature(_narrowings).parameters)
taken = (set(inspect.signature(pack_narrowings).parameters)
& set(inspect.signature(generate_emulator_pack).parameters))
self.assertEqual(taken, set(pipeline.EMULATOR_NARROWINGS_COMPARED))
profile = {"files": [{"name": "a.bin", "region": "japan"},
+3 -3
View File
@@ -15,7 +15,7 @@ import tempfile
import unittest
from pathlib import Path
from packs.naming import _name_part
from packs.naming import file_name_part
from packs.emulatorpack import generate_emulator_pack
REPO_ROOT = Path(__file__).resolve().parent.parent
@@ -23,8 +23,8 @@ REPO_ROOT = Path(__file__).resolve().parent.parent
class PackFileNames(unittest.TestCase):
def test_separators_and_reserved_characters_are_replaced(self):
self.assertEqual(_name_part("FinalBurn Neo (CPS-1/CPS-2)"), "FinalBurnNeo(CPS-1-CPS-2)")
self.assertEqual(_name_part('a\\b:c*d?"e<f>g|h', "_"), "a-b-c-d--e-f-g-h")
self.assertEqual(file_name_part("FinalBurn Neo (CPS-1/CPS-2)"), "FinalBurnNeo(CPS-1-CPS-2)")
self.assertEqual(file_name_part('a\\b:c*d?"e<f>g|h', "_"), "a-b-c-d--e-f-g-h")
def test_an_emulator_named_with_a_slash_writes_its_pack(self):
with tempfile.TemporaryDirectory(dir=REPO_ROOT / "tmp") as tmp:
+2 -2
View File
@@ -32,9 +32,9 @@ def _pack_path(platform_name: str) -> str | None:
"""Path of the platform's full pack, by the exact name the builder writes."""
if not os.path.isdir(DIST_DIR):
return None
from packs.naming import _expected_pack_names
from packs.naming import expected_pack_names
names = _expected_pack_names([platform_name], PLATFORMS_DIR, [], None)
names = expected_pack_names([platform_name], PLATFORMS_DIR, [], None)
for entry in sorted(names[platform_name]):
path = os.path.join(DIST_DIR, entry)
if os.path.isfile(path):
+6 -6
View File
@@ -16,7 +16,7 @@ from pathlib import Path
import yaml
from packs.readme import _build_readme
from packs.readme import build_readme
REPO_ROOT = Path(__file__).resolve().parents[1]
@@ -27,7 +27,7 @@ def _extract_lines(text: str) -> list[str]:
class GuidesPointAtTheReadPath(unittest.TestCase):
def test_retrodeck_is_extracted_at_its_root(self):
text = _build_readme("retrodeck", "RetroDECK", "", 1, 1)
text = build_readme("retrodeck", "RetroDECK", "", 1, 1)
for line in _extract_lines(text):
self.assertNotIn("retrodeck/bios", line)
@@ -37,7 +37,7 @@ class GuidesPointAtTheReadPath(unittest.TestCase):
detect = (data.get("install", {}) or {}).get("detect", [])
if not any(d.get("bios_path") for d in detect):
continue
text = _build_readme(name, name, "", 1, 1, detect=detect)
text = build_readme(name, name, "", 1, 1, detect=detect)
with self.subTest(platform=name):
self.assertFalse(
any("your BIOS directory" in line for line in _extract_lines(text))
@@ -51,7 +51,7 @@ class ACardOpenedOnAComputerShowsItsShareDrive(unittest.TestCase):
def test_the_card_steps_name_the_drive_folder(self):
for name in ("batocera", "recalbox"):
text = _build_readme(name, name, "", 1, 1)
text = build_readme(name, name, "", 1, 1)
card = text[text.index("Manual (SD card)"):]
card = card[:card.index("\n\n", card.index("1."))]
with self.subTest(platform=name):
@@ -74,7 +74,7 @@ def _registry() -> dict:
def _guide(name: str) -> str:
install = _registry()["platforms"][name].get("install") or {}
return _build_readme(name, name, "", 1, 1, detect=install.get("detect", []),
return build_readme(name, name, "", 1, 1, detect=install.get("detect", []),
standalone_copies=install.get("standalone_copies", []))
@@ -136,7 +136,7 @@ class GuidesInstallFromTheZipInHand(unittest.TestCase):
detect = (data.get("install", {}) or {}).get("detect", [])
if not detect:
continue
text = _build_readme(name, name, "", 1, 1, detect=detect)
text = build_readme(name, name, "", 1, 1, detect=detect)
if "Option A: Automatic" not in text:
continue
with self.subTest(platform=name):
+10 -10
View File
@@ -21,7 +21,7 @@ from pathlib import Path
import yaml
from model.platforms import load_platform_config, _platform_config_cache
from model.profiles import _emulator_profiles_cache
from model.profiles import emulator_profiles_cache
import generate_db
from packs import emulatorpack
from packs import platformpack
@@ -69,7 +69,7 @@ class ConflictingDeclarations(unittest.TestCase):
yaml.dump({"platforms": {"conflict": {"config": "conflict.yml"}}})
)
_platform_config_cache.clear()
_emulator_profiles_cache.clear()
emulator_profiles_cache.clear()
def tearDown(self):
_platform_config_cache.clear()
@@ -145,11 +145,11 @@ class AnExtraDoesNotPassAHashCheck(unittest.TestCase):
}
(self.emulators / "fxcore.yml").write_text(yaml.dump(profile))
_platform_config_cache.clear()
_emulator_profiles_cache.clear()
emulator_profiles_cache.clear()
def tearDown(self):
_platform_config_cache.clear()
_emulator_profiles_cache.clear()
emulator_profiles_cache.clear()
self._tmp.cleanup()
def test_the_declaration_stays_failed(self):
@@ -198,10 +198,10 @@ class TheEmulatorPackShipsWhatTheCoreAccepts(unittest.TestCase):
"max_size": 1048576, "validation": ["size"]}],
}
(self.emulators / "mac.yml").write_text(yaml.dump(profile))
_emulator_profiles_cache.clear()
emulator_profiles_cache.clear()
def tearDown(self):
_emulator_profiles_cache.clear()
emulator_profiles_cache.clear()
self._tmp.cleanup()
def test_the_refused_rom_is_named_not_shipped(self):
@@ -256,10 +256,10 @@ class AlternativesAgreeWithThePack(unittest.TestCase):
],
}
(self.emulators / "eng.yml").write_text(yaml.dump(profile))
_emulator_profiles_cache.clear()
emulator_profiles_cache.clear()
def tearDown(self):
_emulator_profiles_cache.clear()
emulator_profiles_cache.clear()
self._tmp.cleanup()
def test_verify_counts_what_the_pack_ships(self):
@@ -319,10 +319,10 @@ class AMaskedArchiveIsMissing(unittest.TestCase):
"files": [{"name": "y.bin", "archive": "pack.zip", "required": True,
"crc32": f"{__import__('zlib').crc32(b'y'):08x}"}],
}))
_emulator_profiles_cache.clear()
emulator_profiles_cache.clear()
def tearDown(self):
_emulator_profiles_cache.clear()
emulator_profiles_cache.clear()
self._tmp.cleanup()
def test_both_report_the_archive_missing(self):
+2 -2
View File
@@ -27,7 +27,7 @@ class NoPathNoCopy(unittest.TestCase):
from model.database import load_database
from model.profiles import load_emulator_profiles
from model.platforms import load_platform_config
from packs.extras import _collect_emulator_extras
from packs.extras import collect_emulator_extras
profiles = load_emulator_profiles("emulators")
nameless = {
@@ -36,7 +36,7 @@ class NoPathNoCopy(unittest.TestCase):
if isinstance(f, dict) and "path" in f and f["path"] is None
}
config = load_platform_config("retroarch")
extras = _collect_emulator_extras(
extras = collect_emulator_extras(
config, "emulators", load_database("database.json"), set(),
config.get("base_destination", ""), profiles,
)
+2 -2
View File
@@ -18,7 +18,7 @@ from pathlib import Path
import yaml
from resolve.validation import _build_validation_index, check_file_validation
from resolve.validation import build_validation_index, check_file_validation
REPO_ROOT = Path(__file__).resolve().parents[1]
@@ -37,7 +37,7 @@ class _Probe(unittest.TestCase):
def accepts(self, emulator: str, name: str, data: bytes, strict: bool = False) -> bool:
"""strict counts a check the code only warns about."""
index = _build_validation_index({emulator: _profile(emulator)})
index = build_validation_index({emulator: _profile(emulator)})
path = Path(self._tmp.name) / name
path.write_bytes(data)
return check_file_validation(
+47 -47
View File
@@ -859,7 +859,7 @@ class TestSymlinkTarget(unittest.TestCase):
class TestAnchorTokens(unittest.TestCase):
def test_archive_members_supply_the_content_values(self):
tokens = profiling_citations._anchor_tokens(
tokens = profiling_citations.anchor_tokens(
{"name": "esh.zip", "contents": [{"crc32": "c14f36b3"}]}
)
# The set name stays: a MAME ref cites the machine declaration, which
@@ -867,24 +867,24 @@ class TestAnchorTokens(unittest.TestCase):
self.assertEqual(tokens, ["c14f36b3", "esh"])
def test_a_hashless_archive_still_falls_back_to_its_stem(self):
tokens = profiling_citations._anchor_tokens(
tokens = profiling_citations.anchor_tokens(
{"name": "esh.zip", "contents": [{"name": "rom.u1"}]}
)
self.assertIn("esh", tokens)
def test_archive_stem_is_searched_too(self):
tokens = profiling_citations._anchor_tokens({"name": "stvbios.zip"})
tokens = profiling_citations.anchor_tokens({"name": "stvbios.zip"})
self.assertIn("stvbios.zip", tokens)
self.assertIn("stvbios", tokens)
def test_hashes_still_win(self):
tokens = profiling_citations._anchor_tokens(
tokens = profiling_citations.anchor_tokens(
{"name": "a.zip", "sha1": "AABB" * 10}
)
self.assertIn("aabb" * 10, tokens)
def test_very_short_stem_is_skipped(self):
self.assertNotIn("ab", profiling_citations._anchor_tokens({"name": "ab.zip"}))
self.assertNotIn("ab", profiling_citations.anchor_tokens({"name": "ab.zip"}))
class TestNudgeToDeclared(unittest.TestCase):
@@ -1285,8 +1285,8 @@ class TestBuildReport(unittest.TestCase):
upstream.list_tags,
upstream.resolve_tag_commit,
upstream.tag_commit,
upstream._http_json,
upstream._http_text,
upstream.http_json,
upstream.http_text,
upstream.list_gitlinks,
upstream.current_slug,
upstream.fork_base,
@@ -1315,8 +1315,8 @@ class TestBuildReport(unittest.TestCase):
def _no_network(url):
raise AssertionError(f"test reached the network: {url}")
upstream._http_json = _no_network
upstream._http_text = _no_network
upstream.http_json = _no_network
upstream.http_text = _no_network
upstream.list_tags = (
lambda repo, cache, offline=False: self.tags
)
@@ -1356,8 +1356,8 @@ class TestBuildReport(unittest.TestCase):
upstream.list_tags,
upstream.resolve_tag_commit,
upstream.tag_commit,
upstream._http_json,
upstream._http_text,
upstream.http_json,
upstream.http_text,
upstream.list_gitlinks,
upstream.current_slug,
upstream.fork_base,
@@ -2206,7 +2206,7 @@ class TestExtrasSurviveARefusingForge(unittest.TestCase):
profiling_run._attach_detection(self._args(), self._profile(), report)
buffer = io.StringIO()
with contextlib.redirect_stdout(buffer):
detection._print_extras(self._args(), self._profile(), report)
detection.print_extras(self._args(), self._profile(), report)
finally:
upstream.fetch_file = original
self.assertEqual(report.detection_skipped, "https://x/y: HTTP 403")
@@ -2731,7 +2731,7 @@ class TestWriteDryRun(unittest.TestCase):
with mock.patch.object(profiling_run, "_build_full_report", return_value=skipped), \
mock.patch.object(profiling_run, "realign_prose", side_effect=cold), \
contextlib.redirect_stderr(io.StringIO()) as err:
profiling_run._read_one(
profiling_run.read_one_profile(
self._args(rebase_refs=True), "p", yaml.safe_load(SAMPLE), reports, failed, True
)
self.assertEqual(reports, [skipped])
@@ -3145,7 +3145,7 @@ class TestDeliberatelyFrozenPin(TestBuildReport):
class TestProseSpacingIsNotADifference(unittest.TestCase):
"""A recale keeps the author's spacing, so the check has to allow for it.
_run_after_moves renders `a.c:228,1439-1443` while the writer leaves the
run_after_moves renders `a.c:228,1439-1443` while the writer leaves the
sentence as written, `a.c:228, 1439-1443`. Comparing the two literally
made the run look unwritten, so bump_commit refused for ever: mariani
was held back by three of them.
@@ -3153,20 +3153,20 @@ class TestProseSpacingIsNotADifference(unittest.TestCase):
def test_a_written_run_counts_as_written_whatever_the_spacing(self):
self.assertEqual(
profiling_citations._citation_key("src/Harddisk.cpp:228, 1439-1443"),
profiling_citations._citation_key("src/Harddisk.cpp:228,1439-1443"),
profiling_citations.citation_key("src/Harddisk.cpp:228, 1439-1443"),
profiling_citations.citation_key("src/Harddisk.cpp:228,1439-1443"),
)
def test_different_citations_still_differ(self):
self.assertNotEqual(
profiling_citations._citation_key("a.c:1, 2"),
profiling_citations._citation_key("a.c:1, 3"),
profiling_citations.citation_key("a.c:1, 2"),
profiling_citations.citation_key("a.c:1, 3"),
)
def test_a_path_change_still_differs(self):
self.assertNotEqual(
profiling_citations._citation_key("a.c:1"),
profiling_citations._citation_key("src/a.c:1"),
profiling_citations.citation_key("a.c:1"),
profiling_citations.citation_key("src/a.c:1"),
)
@@ -3660,7 +3660,7 @@ class APassedReleaseIsNewerThanTheTag(unittest.TestCase):
args = argparse.Namespace(cache_dir="c", offline=True)
with mock.patch.object(upstream, "tag_commit", return_value="rel20"), \
mock.patch.object(upstream, "ancestry", return_value=(5, 0)):
self.assertIsNone(versions._passed_release(args, "repo", version, "pin"))
self.assertIsNone(versions.latest_passed_release(args, "repo", version, "pin"))
class ANewerReleaseThanTheTag(unittest.TestCase):
@@ -3674,7 +3674,7 @@ class ANewerReleaseThanTheTag(unittest.TestCase):
answers = iter([after_tag, after_pin])
with mock.patch.object(upstream, "tag_commit", return_value="rel29"), \
mock.patch.object(upstream, "ancestry", side_effect=lambda *a, **k: next(answers)):
return versions._newer_release(args, "repo", version, "tag28")
return versions.newer_release(args, "repo", version, "tag28")
def test_a_later_release_is_named(self):
self.assertEqual(self._newer((12, 0), (12, 0)), "2.9")
@@ -3711,7 +3711,7 @@ class AProjectThatOnlyTags(unittest.TestCase):
args = argparse.Namespace(cache_dir="c", offline=True)
with mock.patch.object(upstream, "tag_commit", return_value="tag13"), \
mock.patch.object(upstream, "ancestry", return_value=(7, 0)):
self.assertEqual(versions._newer_release(args, "repo", version, "tag12"), "v1.3")
self.assertEqual(versions.newer_release(args, "repo", version, "tag12"), "v1.3")
class APassedReleaseUnderAnUntaggedVersion(unittest.TestCase):
@@ -3736,7 +3736,7 @@ class APassedReleaseUnderAnUntaggedVersion(unittest.TestCase):
with self.subTest(declared=declared, release=release), \
mock.patch.object(upstream, "tag_commit", return_value="rel"), \
mock.patch.object(upstream, "ancestry", return_value=(3, 0)):
self.assertEqual(versions._passed_release(args, "repo", version, "pin"), expected)
self.assertEqual(versions.latest_passed_release(args, "repo", version, "pin"), expected)
def test_no_tag_and_nothing_passed_stays_quiet(self):
version = versions.VersionReport("9.0.5", None, None, None, False, None)
@@ -3746,10 +3746,10 @@ class APassedReleaseUnderAnUntaggedVersion(unittest.TestCase):
class TestAncestry(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
self.saved = upstream._http_json
self.saved = upstream.http_json
def tearDown(self):
upstream._http_json = self.saved
upstream.http_json = self.saved
self.tmp.cleanup()
def test_github_answers_both_directions_at_once(self):
@@ -3759,7 +3759,7 @@ class TestAncestry(unittest.TestCase):
calls.append(url)
return {"ahead_by": 3, "behind_by": 0}
upstream._http_json = answer
upstream.http_json = answer
repo = upstream.parse_repo("https://github.com/o/n")
self.assertEqual(
upstream.ancestry(repo, "tag", "pin", self.tmp.name), (3, 0)
@@ -3771,7 +3771,7 @@ class TestAncestry(unittest.TestCase):
forward = "from=tag&to=pin" in url
return {"commits": [{}] * (0 if forward else 5)}
upstream._http_json = answer
upstream.http_json = answer
repo = upstream.parse_repo("https://gitlab.com/o/n")
self.assertEqual(
upstream.ancestry(repo, "tag", "pin", self.tmp.name), (0, 5)
@@ -4205,7 +4205,7 @@ class TestCollectCitations(unittest.TestCase):
def test_run_is_rendered_with_its_written_path(self):
parts = [RefPart("mupen64plus-video-rice/upstream/src/Config.cpp", 38, 38, "38")]
self.assertEqual(
proseedit._run_after_moves(parts, {0: (40, 40, None)}, "Config.cpp:38"),
proseedit.run_after_moves(parts, {0: (40, 40, None)}, "Config.cpp:38"),
"Config.cpp:40",
)
@@ -5160,15 +5160,15 @@ class AWriteRefreshesTheSourcePaths(unittest.TestCase):
mock.patch.object(profile_sync, "load_emulator_profiles", return_value={}), \
mock.patch("core.artifacts.write_if_changed") as written, \
contextlib.redirect_stderr(io.StringIO()):
profiling_run._WRITTEN.clear()
profiling_run.WRITTEN_PROFILES.clear()
profile_sync._refresh_source_paths(self._args())
self.assertFalse(built.called)
profiling_run._WRITTEN.add("x")
profiling_run.WRITTEN_PROFILES.add("x")
profile_sync._refresh_source_paths(self._args(dry_run=True))
self.assertFalse(built.called)
profile_sync._refresh_source_paths(self._args())
self.assertTrue(built.called and written.called)
profiling_run._WRITTEN.clear()
profiling_run.WRITTEN_PROFILES.clear()
def test_the_record_reads_the_pins_just_written(self):
@@ -5177,14 +5177,14 @@ class AWriteRefreshesTheSourcePaths(unittest.TestCase):
from unittest import mock
from model import profiles as model_profiles
from model.profiles import _emulator_profiles_cache
from model.profiles import emulator_profiles_cache
from sitegen import sources
with tempfile.TemporaryDirectory() as tmp:
profile = Path(tmp) / "p.yml"
profile.write_text('emulator: P\nsource_commit: "old"\n', encoding="utf-8")
_emulator_profiles_cache.clear()
self.addCleanup(_emulator_profiles_cache.clear)
emulator_profiles_cache.clear()
self.addCleanup(emulator_profiles_cache.clear)
model_profiles.load_emulator_profiles(tmp, skip_aliases=False)
profile.write_text('emulator: P\nsource_commit: "new"\n', encoding="utf-8")
with mock.patch.object(sources, "build_source_paths", return_value=({}, [])) as built, \
@@ -5192,8 +5192,8 @@ class AWriteRefreshesTheSourcePaths(unittest.TestCase):
mock.patch("core.artifacts.write_if_changed"), \
contextlib.redirect_stderr(io.StringIO()), \
contextlib.redirect_stdout(io.StringIO()):
profiling_run._WRITTEN.add("p")
self.addCleanup(profiling_run._WRITTEN.clear)
profiling_run.WRITTEN_PROFILES.add("p")
self.addCleanup(profiling_run.WRITTEN_PROFILES.clear)
profile_sync._refresh_source_paths(self._args(emulators_dir=tmp))
self.assertEqual(built.call_args[0][0]["p"]["source_commit"], "new")
@@ -5901,7 +5901,7 @@ class ARecaleKeepsTheRepositoryWord(unittest.TestCase):
part = sourceref.RefPart(
profiling_citations.strip_repo_word(p.path, {"stella"}), p.start, p.end, p.raw)
result = anchoring.PartResult(part, "SHIFTED", None, 140, 150, [], "")
self.assertEqual(profiling_reports._rendered_part(result), expected)
self.assertEqual(profiling_reports.rendered_part(result), expected)
class EachCitationNamesTheCodeThatAsks(unittest.TestCase):
@@ -6047,9 +6047,9 @@ class ARoleIsReadPerPart(unittest.TestCase):
self.assertEqual(prose[0].parts[0].repo, "alek/x")
def test_the_prose_grammar_keeps_the_role(self):
from model.sourceref import _prose_runs
from model.sourceref import prose_runs
runs = list(_prose_runs(
runs = list(prose_runs(
"# ref: source src/a.cpp:1656-1685, 1709-1738, upstream b.c:5"
))
roles = [(p.path, p.role) for run in runs for p in run[3]]
@@ -6060,7 +6060,7 @@ class ARoleIsReadPerPart(unittest.TestCase):
def test_an_abbreviated_location_reads_in_the_file_named_last(self):
"""devilutionx writes `Source/engine/assets.cpp:` then `(:507)` for
each loader, and its pin moved under five uncollected numbers."""
from model.sourceref import _prose_runs
from model.sourceref import prose_runs
text = (
"Load order is defined in Source/engine/assets.cpp:\n"
@@ -6071,7 +6071,7 @@ class ARoleIsReadPerPart(unittest.TestCase):
":44,65) and lightspark's (tools/errorgen:20).\n"
)
cited = [
(p.path, p.start, p.end) for run in _prose_runs(text) for p in run[3]
(p.path, p.start, p.end) for run in prose_runs(text) for p in run[3]
]
self.assertEqual(cited, [
("Source/engine/assets.cpp", 507, 507),
@@ -6086,9 +6086,9 @@ class ARoleIsReadPerPart(unittest.TestCase):
])
def test_an_abbreviated_location_needs_a_file_before_it(self):
from model.sourceref import _prose_runs
from model.sourceref import prose_runs
self.assertEqual(list(_prose_runs("read at boot (:507), devilutionx.mpq")), [])
self.assertEqual(list(prose_runs("read at boot (:507), devilutionx.mpq")), [])
class AnOnlinePassSaysWhereItIs(unittest.TestCase):
@@ -6134,7 +6134,7 @@ class AnOnlinePassSaysWhereItIs(unittest.TestCase):
err = io.StringIO()
with mock.patch.object(triage.time, "monotonic", lambda: next(clock)), \
contextlib.redirect_stderr(err):
progress = triage._Progress(9, "read", quiet=False)
progress = triage.Progress(9, "read", quiet=False)
for done, name in enumerate(("a", "b", "c")):
progress.step(done, name)
self.assertEqual(err.getvalue(), "read: 1 of 9, at b\n")
@@ -6177,7 +6177,7 @@ class TheTriageCountsWhatBlocksThePin(unittest.TestCase):
mock.patch.object(upstream, "commits_touching",
return_value=0), \
contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):
triage._print_triage(args, selected, reports)
triage.print_triage(args, selected, reports)
lines = out.getvalue().splitlines()
self.assertIn("profile", lines[0])
self.assertIn("stuck", lines[1])
@@ -6200,7 +6200,7 @@ class TheTriageCountsWhatBlocksThePin(unittest.TestCase):
mock.patch.object(upstream, "commits_touching",
return_value=0), \
contextlib.redirect_stdout(out), contextlib.redirect_stderr(io.StringIO()):
triage._print_triage(args, selected, reports)
triage.print_triage(args, selected, reports)
lines = out.getvalue().splitlines()
self.assertIn("gone", lines[1])
self.assertEqual(lines[-1], "2 profiles, 1 with something to review")
+3 -3
View File
@@ -151,13 +151,13 @@ class AnUnpinnedInstallerIsRefused(unittest.TestCase):
root = Path(name)
(root / "install.py").write_bytes(b"print('another')\n")
shutil.copyfile(REPO_ROOT / "install.sh", root / "install.sh")
original = pypi.ROOT
pypi.ROOT = root
original = pypi.REPO_ROOT
pypi.REPO_ROOT = root
try:
with self.assertRaises(ValueError):
pypi.installer_bytes()
finally:
pypi.ROOT = original
pypi.REPO_ROOT = original
def _python38() -> str | None:
+11 -11
View File
@@ -22,8 +22,8 @@ from unittest import mock
import refresh_data_dirs as rdd
from packs import datadirs
from model.registry import _load_versions
from packs.datatrees import _data_directory_members
from model.registry import load_versions
from packs.datatrees import data_directory_members
REPO_ROOT = Path(__file__).resolve().parents[1]
@@ -106,12 +106,12 @@ class RefreshConcurrency(unittest.TestCase):
lambda *a, **k: _Response(payload)), \
mock.patch.object(datadirs, "_get_remote_etag", return_value="e1"):
self.assertTrue(datadirs.refresh_entry("pak", entry, versions_path=self.versions))
self.assertEqual(_load_versions(self.versions)["pak"]["archive_size"],
self.assertEqual(load_versions(self.versions)["pak"]["archive_size"],
len(payload))
datadirs._record_version("pak", {"sha": "e1"}, self.versions)
(self.cache / "a.bin").write_bytes(b"kept")
self.assertFalse(datadirs.refresh_entry("pak", entry, versions_path=self.versions))
self.assertEqual(_load_versions(self.versions)["pak"],
self.assertEqual(load_versions(self.versions)["pak"],
{"sha": "e1", "archive_size": len(payload)})
self.assertEqual((self.cache / "a.bin").read_bytes(), b"kept")
@@ -188,7 +188,7 @@ class RefreshConcurrency(unittest.TestCase):
thread.start()
for thread in threads:
thread.join()
self.assertEqual(sorted(_load_versions(self.versions)), sorted(keys))
self.assertEqual(sorted(load_versions(self.versions)), sorted(keys))
class PackWalkHoldsTheCache(unittest.TestCase):
@@ -203,7 +203,7 @@ class PackWalkHoldsTheCache(unittest.TestCase):
(cache / "b.mkf").write_bytes(b"b")
systems = {"s": {"data_directories": [{"ref": "sdlpal", "destination": "sdlpal"}]}}
registry = {"sdlpal": {"local_cache": str(cache)}}
walk = _data_directory_members(systems, registry, "p", "", False, set(), set(), set())
walk = data_directory_members(systems, registry, "p", "", False, set(), set(), set())
next(walk)
with open(cache.with_name(".sdlpal.lock"), "a") as handle, self.assertRaises(
BlockingIOError
@@ -218,7 +218,7 @@ class EmulatorPackHoldsTheCache(unittest.TestCase):
def test_the_walk_holds_a_shared_lock(self):
import fcntl
from packs.datatrees import _pack_data_tree
from packs.datatrees import pack_data_tree
with tempfile.TemporaryDirectory(dir=REPO_ROOT / "tmp") as tmp:
cache = Path(tmp) / "data" / "scummvm"
@@ -236,8 +236,8 @@ class EmulatorPackHoldsTheCache(unittest.TestCase):
fcntl.flock(handle, fcntl.LOCK_UN)
held.append(False)
with mock.patch("packs.datatrees._add_pack_member", member):
_pack_data_tree(None, str(cache), "scummvm", set(), set(), set())
with mock.patch("packs.datatrees.add_pack_member", member):
pack_data_tree(None, str(cache), "scummvm", set(), set(), set())
self.assertEqual(held, [True])
@@ -304,7 +304,7 @@ class TheManifestCarriesTheArchiveSize(unittest.TestCase):
the installer announces as the tree's download."""
def test_recorded_size_is_written_and_an_unrecorded_one_left_out(self):
from packs.datatrees import _manifest_data_directories
from packs.datatrees import manifest_data_directories
(REPO_ROOT / "tmp").mkdir(exist_ok=True)
with tempfile.TemporaryDirectory(dir=REPO_ROOT / "tmp") as tmp:
@@ -319,7 +319,7 @@ class TheManifestCarriesTheArchiveSize(unittest.TestCase):
members = [(str(data / ref / "a.bin"), f"{ref}/a.bin") for ref in ("pak", "old")]
refs = {f"{ref}/a.bin": (ref, ("s",), ref, True) for ref in ("pak", "old")}
listed = {entry["ref"]: entry for entry in
_manifest_data_directories(members, refs, registry, "")}
manifest_data_directories(members, refs, registry, "")}
self.assertEqual(listed["pak"]["archive_size"], 21_360_579)
self.assertNotIn("archive_size", listed["old"])
self.assertNotIn("optional", listed["pak"])
+16 -16
View File
@@ -13,7 +13,7 @@ import unittest
from pathlib import Path
from model import profiles as model_profiles
from model.profiles import _emulator_profiles_cache
from model.profiles import emulator_profiles_cache
from model import region
from resolve import regions as resolve_regions
from packs.extras import emulator_region_drops
@@ -476,10 +476,10 @@ class TestFallbackGroups(unittest.TestCase):
)
def test_the_readme_names_a_slot_as_a_reader_does(self):
from packs.readme import _group_label
from packs.readme import group_label
self.assertEqual(_group_label("PicoDrive:variant:megacd"), "megacd (PicoDrive)")
self.assertEqual(_group_label("sega-mega-cd"), "sega-mega-cd")
self.assertEqual(group_label("PicoDrive:variant:megacd"), "megacd (PicoDrive)")
self.assertEqual(group_label("sega-mega-cd"), "sega-mega-cd")
def test_no_requested_regions_reports_nothing(self):
groups = {"fds": [("disksys.rom", "disksys.rom")]}
@@ -698,13 +698,13 @@ class TestReportAndBuilderNarrowTogether(unittest.TestCase):
def test_the_report_withdraws_what_the_builder_withdraws(self):
from model import profiles as model_profiles
from model.profiles import _emulator_profiles_cache
from model.profiles import emulator_profiles_cache
from packs import extras as packs_extras
from packs import coverage
tmp, root, db, config = self._fixture()
try:
_emulator_profiles_cache.clear()
emulator_profiles_cache.clear()
profiles = model_profiles.load_emulator_profiles(str(root / "emulators"))
groups, extra_dests = packs_extras.platform_region_groups(
config, config["systems"], str(root / "emulators"),
@@ -734,7 +734,7 @@ class TestReportAndBuilderNarrowTogether(unittest.TestCase):
"the report must withdraw exactly the builder's drop set",
)
finally:
_emulator_profiles_cache.clear()
emulator_profiles_cache.clear()
tmp.cleanup()
def test_a_missing_regional_core_file_is_withdrawn_too(self):
@@ -742,7 +742,7 @@ class TestReportAndBuilderNarrowTogether(unittest.TestCase):
missing core file was never grouped and stayed "required missing"
for a region the request excludes."""
from model import profiles as model_profiles
from model.profiles import _emulator_profiles_cache
from model.profiles import emulator_profiles_cache
from packs import coverage
tmp, root, db, config = self._fixture()
@@ -750,7 +750,7 @@ class TestReportAndBuilderNarrowTogether(unittest.TestCase):
jp = next(k for k, v in db["files"].items() if v["name"] == "jp.bin")
del db["files"][jp]
del db["indexes"]["by_name"]["jp.bin"]
_emulator_profiles_cache.clear()
emulator_profiles_cache.clear()
profiles = model_profiles.load_emulator_profiles(str(root / "emulators"))
plain = coverage.verify_platform(
config, db, str(root / "emulators"), profiles,
@@ -765,20 +765,20 @@ class TestReportAndBuilderNarrowTogether(unittest.TestCase):
{u["name"] for u in narrowed["undeclared_files"]}, {"us.bin"}
)
finally:
_emulator_profiles_cache.clear()
emulator_profiles_cache.clear()
tmp.cleanup()
def test_the_report_names_the_fallback_groups(self):
"""The pack README lists the systems kept whole because nothing
answers the request. verify said all OK and named none."""
from model import profiles as model_profiles
from model.profiles import _emulator_profiles_cache
from model.profiles import emulator_profiles_cache
from packs import coverage
from packs import report as packs_report
tmp, root, db, config = self._fixture()
try:
_emulator_profiles_cache.clear()
emulator_profiles_cache.clear()
profiles = model_profiles.load_emulator_profiles(str(root / "emulators"))
result = coverage.verify_platform(
config, db, str(root / "emulators"), profiles,
@@ -790,7 +790,7 @@ class TestReportAndBuilderNarrowTogether(unittest.TestCase):
packs_report.print_platform_result(result, ["Demo"])
self.assertIn("all kept (1): demo-system", out.getvalue())
finally:
_emulator_profiles_cache.clear()
emulator_profiles_cache.clear()
tmp.cleanup()
def test_one_grouping_pass_serves_both_sides(self):
@@ -1314,7 +1314,7 @@ class ARefusedRegionalFileHoldsNoSlot(unittest.TestCase):
from packs.emulatorpack import generate_emulator_pack
from packs.emulatorcheck import verify_emulator
_emulator_profiles_cache.clear()
emulator_profiles_cache.clear()
repo = Path(__file__).resolve().parents[1]
(repo / "tmp").mkdir(exist_ok=True)
root = Path(tempfile.mkdtemp(dir=repo / "tmp"))
@@ -1459,9 +1459,9 @@ class RegionWordsInAPackReadme(unittest.TestCase):
"""The pack README title-cased each slug: asia-ntsc read "Asia Ntsc"."""
def test_the_priority_line_reads_as_written(self):
from packs.readme import _build_readme
from packs.readme import build_readme
readme = _build_readme(
readme = build_readme(
"retroarch", "RetroArch", "system", 1, 1,
regions=region.parse_requested("us,asia-ntsc,jp"),
)
+2 -2
View File
@@ -93,13 +93,13 @@ class ADataDirectoryCopyIsHeld(unittest.TestCase):
def test_emulator_entry_from_a_data_tree(self):
from packs.extras import _emulator_ships
from resolve.validation import _build_validation_index
from resolve.validation import build_validation_index
profile = self.profiles["dolphin-mmjr2"]
entry = next(
fe for fe in profile["files"] if fe.get("name") == "nwc24msg.cfg"
)
index = _build_validation_index({"dolphin-mmjr2": profile})
index = build_validation_index({"dolphin-mmjr2": profile})
self.assertTrue(_emulator_ships(
entry, "dolphin-mmjr2", profile, self.db, index, {}, self.registry,
))
+1 -1
View File
@@ -262,7 +262,7 @@ class EverySurfaceSaysWhy(unittest.TestCase):
line = guidepage.no_zip_line("KNULLI")
self.assertEqual(line, "No ZIP for KNULLI. The command installs every file and checks it.")
with contextlib.chdir(REPO_ROOT):
block = guidepage._pack_buttons("knulli")
block = guidepage.pack_buttons("knulli")
guide = guidepage._guide_download(
"knulli", "KNULLI", guides.GUIDES["knulli"], None, "## Download")
self.assertIn(line, block)
+2 -2
View File
@@ -22,7 +22,7 @@ from pathlib import Path
import yaml
from model.platforms import _platform_config_cache
from model.profiles import _emulator_profiles_cache
from model.profiles import emulator_profiles_cache
import generate_db
from packs import manifest as packs_manifest
from packs import platformpack
@@ -72,7 +72,7 @@ class RequiredTwins(unittest.TestCase):
yaml.dump({"platforms": {"twins": {"config": "twins.yml"}}})
)
_platform_config_cache.clear()
_emulator_profiles_cache.clear()
emulator_profiles_cache.clear()
def tearDown(self):
_platform_config_cache.clear()
+6 -6
View File
@@ -34,7 +34,7 @@ import yaml
from packs.paths import (
EMULATOR_PACK_SAVE_FOLDER,
SaveLayout,
_resolve_destination,
resolve_destination,
save_destination,
save_layout,
)
@@ -86,10 +86,10 @@ class TheEntryNamesItsRoot(unittest.TestCase):
def test_an_emulator_pack_keeps_them_in_their_own_folder(self):
self.assertEqual(
_resolve_destination(self.ENTRY, False),
resolve_destination(self.ENTRY, False),
f"{EMULATOR_PACK_SAVE_FOLDER}/CoreX/sysdata/keys.txt",
)
self.assertEqual(_resolve_destination(self.ENTRY, True), "sysdata/keys.txt")
self.assertEqual(resolve_destination(self.ENTRY, True), "sysdata/keys.txt")
class ThePlatformNamesItsSaveDirectory(unittest.TestCase):
@@ -211,13 +211,13 @@ class _Fixture(unittest.TestCase):
OTHER_KEYS = b"PLATFORM KEYS"
def setUp(self) -> None:
from model.profiles import _emulator_profiles_cache
from model.profiles import emulator_profiles_cache
from model.platforms import _platform_config_cache
_emulator_profiles_cache.clear()
emulator_profiles_cache.clear()
_platform_config_cache.clear()
self.addCleanup(_platform_config_cache.clear)
self.addCleanup(_emulator_profiles_cache.clear)
self.addCleanup(emulator_profiles_cache.clear)
self.root = _scratch(self)
self.bios = self.root / "bios"
self.platforms = self.root / "platforms"
+9 -9
View File
@@ -934,7 +934,7 @@ class OneNativeIdOneSystem(unittest.TestCase):
FOLDS = {"fbneo", "pcenginecd"}
def test_scrapers_agree_on_every_shared_native_id(self):
from model.systems import _norm_system_id
from model.systems import norm_system_id
seen: dict[str, dict[str, str]] = {}
for path in sorted((REPO_ROOT / "scripts" / "scraper").glob("*_scraper.py")):
@@ -947,7 +947,7 @@ class OneNativeIdOneSystem(unittest.TestCase):
seen.setdefault(native.lower(), {})[path.stem] = slug
split = {
native: by for native, by in seen.items()
if native not in self.FOLDS and len({_norm_system_id(s) for s in by.values()}) > 1
if native not in self.FOLDS and len({norm_system_id(s) for s in by.values()}) > 1
}
self.assertEqual(split, {})
@@ -979,14 +979,14 @@ class OneNativeIdOneSystem(unittest.TestCase):
def test_every_platform_system_meets_a_profile_system(self):
import yaml
from model.systems import _norm_system_id
from model.systems import norm_system_id
from model.profiles import load_emulator_profiles
from model.platforms import load_platform_config
known = set()
for profile in load_emulator_profiles(str(REPO_ROOT / "emulators")).values():
known |= {_norm_system_id(s) for s in profile.get("systems") or []}
known |= {_norm_system_id(f["system"]) for f in profile.get("files") or []
known |= {norm_system_id(s) for s in profile.get("systems") or []}
known |= {norm_system_id(f["system"]) for f in profile.get("files") or []
if isinstance(f, dict) and f.get("system")}
registry = yaml.safe_load((REPO_ROOT / "platforms" / "_registry.yml").read_text())
for name in registry["platforms"]:
@@ -994,22 +994,22 @@ class OneNativeIdOneSystem(unittest.TestCase):
config = load_platform_config(name, str(REPO_ROOT / "platforms"))
allowed = self.UNMATCHED["*"] | self.UNMATCHED.get(name, set())
stray = {s for s in config.get("systems", {})
if _norm_system_id(s) not in known} - allowed
if norm_system_id(s) not in known} - allowed
self.assertEqual(stray, set())
def test_xroar_machines_reach_the_platforms_that_run_it(self):
import yaml
from model.systems import _norm_system_id
from model.systems import norm_system_id
xroar = yaml.safe_load((REPO_ROOT / "emulators" / "xroar.yml").read_text())
machines = {_norm_system_id(s) for s in xroar["systems"]}
machines = {norm_system_id(s) for s in xroar["systems"]}
for platform, wanted in (("retrodeck", {"coco", "dragon64"}),
("recalbox", {"coco", "dragon64"}),
("misterfpga", {"coco3"})):
with self.subTest(platform=platform):
data = yaml.safe_load((REPO_ROOT / "platforms" / f"{platform}.yml").read_text())
ids = {_norm_system_id(s) for s in data["systems"]}
ids = {norm_system_id(s) for s in data["systems"]}
self.assertEqual(wanted & ids & machines, wanted)
+1 -1
View File
@@ -68,7 +68,7 @@ STAYS_PLAIN = {
def _reset() -> None:
"""Back to the repository's sections and boards, none written."""
siterender._arcade_source[0] = None
systemnames._boards_built[0] = False
systemnames.boards_built[0] = False
systemnames._sections_installed[0] = False
siterender.reset_console_pages()
+6 -6
View File
@@ -16,8 +16,8 @@ from pathlib import Path
import yaml
from model.database import load_database
from sitegen.emulatorpage import _availability_check
from sitegen.emulatorcards import _file_badges
from sitegen.emulatorpage import availability_check
from sitegen.emulatorcards import file_badges
REPO_ROOT = Path(__file__).resolve().parent.parent
@@ -30,20 +30,20 @@ DB = {
class UnsourceableIsNotHeld(unittest.TestCase):
def test_a_homonym_does_not_stand_in(self):
available = _availability_check(DB, set())
available = availability_check(DB, set())
self.assertTrue(available({"name": "pak0.pk3"}))
self.assertFalse(available({"name": "pak0.pk3", "unsourceable": "retail data"}))
def test_a_release_asset_is_held_only_when_collected(self):
"""storage: large_file said "in repo" for kenji-nx's user-picked
firmware package, which the collection does not hold."""
available = _availability_check(DB, set())
available = availability_check(DB, set())
self.assertFalse(available({"name": "<firmware>.zip", "storage": "large_file"}))
self.assertTrue(available({"name": "pak0.pk3", "storage": "release"}))
def test_the_badge_says_why(self):
entry = {"name": "pak0.pk3", "unsourceable": "retail data"}
badges = " ".join(_file_badges(entry, False))
badges = " ".join(file_badges(entry, False))
self.assertIn("unsourceable", badges)
self.assertNotIn(">missing<", badges)
self.assertNotIn("in repo", badges)
@@ -52,7 +52,7 @@ class UnsourceableIsNotHeld(unittest.TestCase):
db_path = REPO_ROOT / "database.json"
if not db_path.exists():
self.skipTest("database.json is not built")
available = _availability_check(load_database(str(db_path)), set())
available = availability_check(load_database(str(db_path)), set())
shown_held = []
for path in sorted((REPO_ROOT / "emulators").glob("*.yml")):
document = yaml.safe_load(path.read_text(encoding="utf-8")) or {}
+2 -2
View File
@@ -261,10 +261,10 @@ class GeneratedSurfaces(unittest.TestCase):
from sitegen import consolecards
tail = " | sh -s -- --check"
self.assertEqual(consolecards._install_box_weight([f"curl -fsSL {INSTALL_SH}{tail}"]),
self.assertEqual(consolecards.install_box_weight([f"curl -fsSL {INSTALL_SH}{tail}"]),
len("curl -fsSL ") + 66 + len(tail) + 1)
line = f"&([scriptblock]::Create((irm {INSTALL_PS1}))) --check"
self.assertEqual(consolecards._install_box_weight([line]),
self.assertEqual(consolecards.install_box_weight([line]),
len(line) - len(INSTALL_PS1) + 67 + 1)
def test_the_readme_shows_the_short_form(self):
+1 -1
View File
@@ -213,7 +213,7 @@ class NavFromFrontMatter(unittest.TestCase):
def test_every_wiki_page_states_its_place(self):
for page in sorted(WIKI.glob("*.md")):
meta = decorate._front_matter(page.read_text(encoding="utf-8"))
meta = decorate.front_matter(page.read_text(encoding="utf-8"))
with self.subTest(page=page.name):
self.assertIn(meta.get("level"), sitegen_nav.TABS)
self.assertTrue(meta.get("nav") is False or isinstance(meta.get("order"), int))
+1 -1
View File
@@ -40,7 +40,7 @@ class SiteCoreCounts(unittest.TestCase):
}
for name, cov in coverages.items():
with self.subTest(page=name):
if platformpage._own_list_only(cov["config"]):
if platformpage.own_list_only(cov["config"]):
# cores: [] (MiSTer, BizHawk): no core table, the overview
# row points at the platform's own list instead.
self.assertNotIn(f"cross-reference-{name}", moved)
+8 -8
View File
@@ -105,7 +105,7 @@ def _card() -> dict:
class ASystemCardShowsTheAnswerFirst(unittest.TestCase):
def setUp(self) -> None:
self.lines = cards._system_file_card(_card(), _card_consumers(SHA1))
self.lines = cards.system_file_card(_card(), _card_consumers(SHA1))
self.text = "\n".join(self.lines)
self.fold = self.text[self.text.index("<details"):self.text.index("</details>")]
self.shown = self.text.replace(self.fold, "")
@@ -134,7 +134,7 @@ class ASystemCardShowsTheAnswerFirst(unittest.TestCase):
# The yardstick list a page is cut by holds every fact: the
# Starlight card holds each of its values.
with markup.using("mkdocs"):
yardstick = "\n".join(cards._system_file_card(_card(), _card_consumers(SHA1)))
yardstick = "\n".join(cards.system_file_card(_card(), _card_consumers(SHA1)))
for label, values in re.findall(r"(?m)^- ([^:]+): (.*)$", yardstick):
self.assertIn(f"<dt>{label}</dt>", self.text)
for value in re.findall(r"[0-9a-f]{8,64}|`[^`]+`", values):
@@ -152,7 +152,7 @@ class AnEmulatorCardFoldsItsHashes(unittest.TestCase):
"required": True, "note": "Read at boot.", "priority": 5,
"validation": ["md5"], "source_ref": "src/core/bios.cpp:47"}
profile = {"emulator": "DuckStation", "files": [entry], "systems": ["sony-playstation"]}
self.text = "\n".join(emulatorcards._render_emulator_file(
self.text = "\n".join(emulatorcards.render_emulator_file(
entry, profile, None, profile["files"], lambda _f: True, anchor="file-scph5501-bin"))
self.fold = self.text[self.text.index("<details"):self.text.index("</details>")]
self.shown = self.text.replace(self.fold, "")
@@ -176,7 +176,7 @@ class AnEmulatorCardFoldsItsHashes(unittest.TestCase):
def test_the_markdown_yardstick_is_unchanged(self) -> None:
with markup.using("mkdocs"):
entry = {"name": "a.bin", "md5": "b" * 32, "size": 4}
text = "\n".join(emulatorcards._render_emulator_file(
text = "\n".join(emulatorcards.render_emulator_file(
entry, {"files": [entry]}, None, [entry], lambda _f: True))
self.assertNotIn("<details", text)
self.assertIn("- MD5: ", text)
@@ -187,7 +187,7 @@ PAIRS = [("emudeck", "sony-psp"), ("retroarch", "sony-psp"), ("retrobat", "Neo G
class AnInstallBoxShowsOneCommand(unittest.TestCase):
def setUp(self) -> None:
self.text = "\n".join(install._console_install_block("PlayStation Portable", PAIRS))
self.text = "\n".join(install.console_install_block("PlayStation Portable", PAIRS))
def test_one_command_per_tab_for_the_setup_picked(self) -> None:
tabs = self.text[self.text.index("<Tabs"):self.text.index("</Tabs>")]
@@ -226,7 +226,7 @@ class AnInstallBoxShowsOneCommand(unittest.TestCase):
self.assertIn("https://<wbr>abdess.github.io", listed)
def test_one_setup_keeps_its_two_blocks(self) -> None:
text = "\n".join(install._console_install_block("PlayStation Portable", PAIRS[:1]))
text = "\n".join(install.console_install_block("PlayStation Portable", PAIRS[:1]))
self.assertNotIn("<select", text)
self.assertIn('```sh title="Terminal"', text)
self.assertIn('```powershell title="PowerShell"', text)
@@ -235,7 +235,7 @@ class AnInstallBoxShowsOneCommand(unittest.TestCase):
# The budgets that cut a system page are measured on this Markdown:
# a box that changed it would move cards to other pages.
with markup.using("mkdocs"):
text = "\n".join(install._console_install_block("PlayStation Portable", PAIRS))
text = "\n".join(install.console_install_block("PlayStation Portable", PAIRS))
self.assertNotIn("<select", text)
self.assertEqual(text.count("# RetroBat"), 2)
self.assertEqual(text.count("/i | sh"), 3)
@@ -256,7 +256,7 @@ class TheSetupListLooksLikeAList(unittest.TestCase):
# The arrow is defined for both themes.
self.assertEqual(len(re.findall(r"--rb-select-arrow:", css)), 2)
# The box's select sits in Markdown content, where the shared rule applies.
box = "\n".join(install._console_install_block("PlayStation Portable", PAIRS))
box = "\n".join(install.console_install_block("PlayStation Portable", PAIRS))
self.assertIn('<label class="rb-install-setup">Setup <select>', box)
def test_the_built_select_shows_the_arrow(self) -> None:
+2 -2
View File
@@ -137,11 +137,11 @@ class WhatASearchSnippetSays(unittest.TestCase):
saved = dict(descriptions.PAGE_DATA)
self.addCleanup(lambda: (descriptions.PAGE_DATA.clear(), descriptions.PAGE_DATA.update(saved)))
descriptions.PAGE_DATA[rel.as_posix()] = {}
text = descriptions._page_description("# Lutro\n", rel, "Lutro")
text = descriptions.page_description("# Lutro\n", rel, "Lutro")
self.assertNotIn("hashes", text)
self.assertIn("It needs no BIOS or firmware file.", text)
descriptions.PAGE_DATA[rel.as_posix()] = {"hasPart": [{"name": "a.bin"}]}
self.assertNotIn("needs no BIOS", descriptions._page_description("# Lutro\n", rel, "Lutro"))
self.assertNotIn("needs no BIOS", descriptions.page_description("# Lutro\n", rel, "Lutro"))
def test_a_long_paragraph_is_cut_at_a_word(self):
plain = ("files/?sha1= is the address that does not move: it opens the card "
+17 -17
View File
@@ -208,7 +208,7 @@ class TheSummaryLineIsProse(unittest.TestCase):
self.assertIn("By kind: 1,563 BIOS ZIPs and 2 game data.", text)
def test_category_badge_in_words(self):
badges = " ".join(emulatorcards._file_badges({"name": "a", "category": "game_data"}, True))
badges = " ".join(emulatorcards.file_badges({"name": "a", "category": "game_data"}, True))
self.assertIn(">game data</span>", badges)
@@ -217,7 +217,7 @@ class TheIndexNamesEmulatorsAndSystems(unittest.TestCase):
# Pages another test split off would send the console elsewhere.
siterender.reset_console_pages()
self.addCleanup(siterender.reset_console_pages)
saved = dict(siterender._system_page_map)
saved = dict(siterender.system_page_map)
self.addCleanup(siterender.set_system_page_map, saved)
siterender.set_system_page_map({"sony-playstation": ("sony", "PlayStation")})
page = emulatorsindex.generate_emulators_index({
@@ -276,14 +276,14 @@ class WhatTheAppShipsIsNoFileToGet(unittest.TestCase):
def test_the_badge(self):
font = next(f for f in self.profile["files"] if f["name"] == "Roboto-Regular.ttf")
badges = " ".join(emulatorcards._file_badges(font, False))
badges = " ".join(emulatorcards.file_badges(font, False))
self.assertIn(">comes with the app</span>", badges)
self.assertNotIn(">required</span>", badges)
self.assertNotIn(">missing</span>", badges)
# Narrowed to one build, the entry is that build's alone, as verify
# and the pack read it: EightyOne installs its ROMs, and the libretro
# core, which embeds them, reads no entry. Nothing to fetch.
dual = " ".join(emulatorcards._file_badges({"name": "a", "bundled": True, "mode": "standalone",
dual = " ".join(emulatorcards.file_badges({"name": "a", "bundled": True, "mode": "standalone",
"required": True}, False))
self.assertNotIn(">required</span>", dual)
self.assertNotIn(">missing</span>", dual)
@@ -364,11 +364,11 @@ class LongPagesFold(unittest.TestCase):
class DataDirectoryPagesStayOutOfSearch(unittest.TestCase):
def test_front_matter(self):
saved = dict(emulatorcards._DATA_MEMBERS), dict(emulatorpage._DATA_READERS)
self.addCleanup(lambda: (emulatorcards._DATA_MEMBERS.clear(), emulatorcards._DATA_MEMBERS.update(saved[0]),
emulatorpage._DATA_READERS.clear(), emulatorpage._DATA_READERS.update(saved[1])))
emulatorcards._DATA_MEMBERS["dolphin-sys"] = {"a.bin": {"sha1": "a" * 40, "size": 1}}
emulatorpage._DATA_READERS["dolphin-sys"] = [("dolphin-mmjr", "Dolphin MMJR"), ("dolphin", "Dolphin")]
saved = dict(emulatorcards.DATA_MEMBERS), dict(emulatorpage.DATA_READERS)
self.addCleanup(lambda: (emulatorcards.DATA_MEMBERS.clear(), emulatorcards.DATA_MEMBERS.update(saved[0]),
emulatorpage.DATA_READERS.clear(), emulatorpage.DATA_READERS.update(saved[1])))
emulatorcards.DATA_MEMBERS["dolphin-sys"] = {"a.bin": {"sha1": "a" * 40, "size": 1}}
emulatorpage.DATA_READERS["dolphin-sys"] = [("dolphin-mmjr", "Dolphin MMJR"), ("dolphin", "Dolphin")]
page = emulatorpage._data_tree_page("dolphin-sys", {}, [("data-dolphin-sys", ["a.bin"])], 0)
front = yaml.safe_load(page.split("---\n")[1])
self.assertEqual(front["search"], "exclude")
@@ -487,14 +487,14 @@ class PartsKnowWhereTheySit(unittest.TestCase):
ref = "x-sys"
members = {f"f{i:05d}": {"size": 1, "sha1": f"{i:040x}"}
for i in range(lookup.DATA_TREE_ROWS_PER_PAGE * 2 + 1)}
emulatorcards._DATA_MEMBERS[ref] = members
emulatorpage._DATA_READERS[ref] = [("x", "X")]
emulatorcards.DATA_MEMBERS[ref] = members
emulatorpage.DATA_READERS[ref] = [("x", "X")]
try:
pages = lookup.data_tree_pages(ref, members)
self.assertEqual(len(pages), 3)
middle = _front(emulatorpage._data_tree_page(ref, {}, pages, 1))
finally:
del emulatorcards._DATA_MEMBERS[ref], emulatorpage._DATA_READERS[ref]
del emulatorcards.DATA_MEMBERS[ref], emulatorpage.DATA_READERS[ref]
self.assertEqual(middle["parent"], {"label": "X", "link": "x.md"})
self.assertEqual(middle["prev"]["link"], f"{pages[0][0]}.md")
self.assertEqual(middle["next"]["link"], f"{pages[2][0]}.md")
@@ -694,7 +694,7 @@ class DataFolderPrinted(unittest.TestCase):
"standalone_path": "a"}), "a")
def test_the_metadata_card_has_a_row_per_system(self) -> None:
rows = emulatorcards._render_metadata_rows(_profile("cxbx-reloaded"))
rows = emulatorcards.render_metadata_rows(_profile("cxbx-reloaded"))
self.assertIn("| Data folder (Windows) | `%APPDATA%/Cxbx-Reloaded/` |", rows)
self.assertFalse(any("Data folder (Linux)" in row for row in rows))
@@ -742,22 +742,22 @@ class InstallBlockWhereItWorks(unittest.TestCase):
self.assertLessEqual(_tab_labels(_install_section(_built_page(name))), allowed)
def test_android_only_app_gets_no_desktop_command(self) -> None:
self.assertEqual(sitegen_install._install_block("mame4droid", _profile("mame4droid")), [])
self.assertEqual(sitegen_install.install_block("mame4droid", _profile("mame4droid")), [])
command, setups, oses = sitegen_install.emulator_install_route("cxbx-reloaded", _profile("cxbx-reloaded"))
self.assertEqual(oses, ("windows",))
def test_a_lone_app_is_named_with_the_setup_that_launches_it(self) -> None:
text = "\n".join(sitegen_install._install_block("ryujinx", _profile("ryujinx")))
text = "\n".join(sitegen_install.install_block("ryujinx", _profile("ryujinx")))
self.assertRegex(text, r"With [^:]*EmuDeck[^:]*: the installer finds")
self.assertNotIn("Android (Termux)", text)
self.assertNotIn("RetroArch", text)
def test_a_dual_app_says_what_the_command_fills(self) -> None:
text = "\n".join(sitegen_install._install_block("duckstation", _profile("duckstation")))
text = "\n".join(sitegen_install.install_block("duckstation", _profile("duckstation")))
self.assertIn("For DuckStation inside RetroArch, Batocera or another setup.", text)
def test_no_files_no_command(self) -> None:
self.assertEqual(sitegen_install._install_block("beetle_wswan", _profile("beetle_wswan")), [])
self.assertEqual(sitegen_install.install_block("beetle_wswan", _profile("beetle_wswan")), [])
def test_tabs_follow_the_keys_given(self) -> None:
tabs = "\n".join(sitegen_install.install_commands("--emulator x", oses=("linux", "steamdeck")))
+16 -16
View File
@@ -110,7 +110,7 @@ class TrustItemsSayWhereItWrites(unittest.TestCase):
class NextStepsIsAPlainList(unittest.TestCase):
def test_the_helpers(self):
block = "\n".join(sitegen_home._next_block(["[A](a.md)", "[B](b.md)"]))
block = "\n".join(sitegen_home.next_block(["[A](a.md)", "[B](b.md)"]))
self.assertEqual(block, "## Next steps\n\n- [A](a.md)\n- [B](b.md)\n")
self.assertIn("## Next steps", reference.reference_next())
self.assertNotIn(":::", reference.reference_next())
@@ -317,7 +317,7 @@ class CommandBlocks(unittest.TestCase):
self.assertGreaterEqual(len(commands), 3)
for group in commands:
self.assertIn("/i.ps1", group)
block = "\n".join(sitegen_install._console_install_block(
block = "\n".join(sitegen_install.console_install_block(
"PlayStation", [("batocera", "psx"), ("recalbox", "psx")]))
# Every setup's options in both forms: the list of every command,
# and the one command under the OS tabs.
@@ -342,9 +342,9 @@ class ContributingOpensOnTheAction(unittest.TestCase):
self.assertLess(body.index("## What happens next"), body.index("CI hashes"))
def test_description_is_a_sentence(self):
text = descriptions._page_description("", Path("contributing.md"), "Contributing")
text = descriptions.page_description("", Path("contributing.md"), "Contributing")
self.assertTrue(text.endswith("."))
fallback = descriptions._page_description(
fallback = descriptions.page_description(
"One file needs no clone and no local setup at all here:\n\n"
"A plain sentence that describes the page well enough.",
Path("other.md"), "Other")
@@ -464,7 +464,7 @@ class PackNamesItsVersion(unittest.TestCase):
record = releaserecord.load_record()
if not releaserecord.pack_for("batocera", record):
self.skipTest("release.json has no Batocera pack")
block = guidepage._pack_buttons("batocera")
block = guidepage.pack_buttons("batocera")
name = releaserecord.pack_name_for("batocera", record)
version = versions._pack_version(name, ["batocera"])
self.assertIn(f"Made for Batocera {version}. "
@@ -480,10 +480,10 @@ class PackNamesItsVersion(unittest.TestCase):
def test_a_version_with_an_underscore_is_read_whole(self):
"""AmberELEC's prerelease-20261019_1835 read as 1835, and the page
said the pack was built for another version."""
from packs.naming import _platform_pack_stem
from packs.naming import platform_pack_stem
version = load_platform_config("amberelec", "platforms")["version"]
name = _platform_pack_stem(["amberelec"], "amberelec", "platforms") + "_BIOS_Pack.zip"
name = platform_pack_stem(["amberelec"], "amberelec", "platforms") + "_BIOS_Pack.zip"
self.assertEqual(versions._pack_version(name, ["amberelec"]), version)
record = {"tag": "v2026.10.10", "packs": {name: {
"assets": [name], "platforms": ["amberelec"]}}}
@@ -732,12 +732,12 @@ class NoZipNoUnzipText(unittest.TestCase):
self.assertIn("`smb://recalbox/share`", how["macos"])
self.assertEqual(args["linux"], "--platform recalbox --dest /path/to/share/bios")
self.assertIn("`smb://recalbox/share`", how["linux"])
lines = guidepage._setup_routes("recalbox", "Recalbox")
lines = guidepage.setup_routes("recalbox", "Recalbox")
routes = "\n".join(lines[:lines.index("## On the device { #install }")])
for label in ("Windows", "macOS", "Linux"):
self.assertIn(f'label="{label}"', routes)
# The setup page sends a Mac or Linux reader to those tabs.
lines = guidepage._setup_routes("recalbox", "Recalbox", page_link=True)
lines = guidepage.setup_routes("recalbox", "Recalbox", page_link=True)
self.assertIn("[Mac or Linux](../get/recalbox.md#from-your-computer)", lines)
def test_the_network_route_needs_a_share_and_no_zip(self):
@@ -913,17 +913,17 @@ class GetPagesGiveTheSetupsOwnRoutes(unittest.TestCase):
def test_one_helper_writes_both_pages(self):
source = script_source("generate_site.py")
get_page = source.split("def generate_get_page", 1)[1].split("\ndef ", 1)[0]
guide = source.split("def _platform_guide", 1)[1].split("\ndef ", 1)[0]
guide = source.split("def platform_guide", 1)[1].split("\ndef ", 1)[0]
self.assertNotIn("install_commands(", get_page)
self.assertIn("_setup_routes(", get_page)
self.assertIn("_setup_routes(", guide)
self.assertIn("setup_routes(", get_page)
self.assertIn("setup_routes(", guide)
class CheckNeedsTheFiles(unittest.TestCase):
def test_the_pass_line_is_what_the_installer_prints_only_when_complete(self):
installer = (REPO_ROOT / "install.py").read_text(encoding="utf-8")
printed = re.search(r"`([^`]+)`", guidepage.check_pass_line())[1]
self.assertEqual(printed, sitegen_install._installer().EVERYTHING_IN_PLACE)
self.assertEqual(printed, sitegen_install.installer_module().EVERYTHING_IN_PLACE)
self.assertIn('print(f"\\n {EVERYTHING_IN_PLACE}")', installer)
self.assertNotIn("wrong hash", guidepage.check_pass_line())
@@ -1080,7 +1080,7 @@ class TheSiteSaysWhatTheInstallerShows(unittest.TestCase):
"c) choose systems, cores and regions")
def test_which_pack_describes_the_screen_in_the_installers_words(self):
installer = sitegen_install._installer()
installer = sitegen_install.installer_module()
text = _plain_page("which-pack.md")
for line in guidepage.first_screen_words():
self.assertIn(line, text)
@@ -1091,7 +1091,7 @@ class TheSiteSaysWhatTheInstallerShows(unittest.TestCase):
self.assertNotIn("press **c**", text)
def test_the_plan_rows_are_the_words_the_pages_use(self):
installer = sitegen_install._installer()
installer = sitegen_install.installer_module()
state = installer.TuiState(os_type="linux", home=Path("/home/me"))
state.stack = ["plan"]
state.check = {"files": 2, "present": 0, "missing": 2, "wrong_hash": 0, "need": 2,
@@ -1107,7 +1107,7 @@ class TheSiteSaysWhatTheInstallerShows(unittest.TestCase):
self.assertIn(installer.TUI_SYSTEMS_ROW, labels)
def test_the_readme_and_the_wiki_take_the_same_words(self):
installer = sitegen_install._installer()
installer = sitegen_install.installer_module()
readme = (REPO_ROOT / "README.md").read_text(encoding="utf-8")
self.assertIn(f"fewer under **{installer.TUI_SYSTEMS_ROW}**", readme)
self.assertNotIn("offers to install everything or to choose systems", readme)
+38 -38
View File
@@ -16,9 +16,9 @@ from pathlib import Path
import yaml
from sitegen.render import _admonition_body
from sitegen.descriptions import _browser_title
from sitegen.sources import _forge_sources, _source_ref_markdown
from sitegen.render import admonition_body
from sitegen.descriptions import page_browser_title
from sitegen.sources import _forge_sources, source_ref_markdown
from sitegen.decorate import decorate_markdown_pages
from sitegen.dataexports import generate_data_exports
@@ -143,7 +143,7 @@ class SiteReferenceContracts(unittest.TestCase):
@mock.patch("sitegen.sources.tree_holds", lambda *_args: True) # a path the record confirms
def test_source_references_are_revision_pinned_links(self):
_, _, profiles, _ = self._fixtures()
rendered = _source_ref_markdown(
rendered = source_ref_markdown(
profiles["testemu"], "src/firmware.cpp:10-12"
)
self.assertIn("/blob/" + "a" * 40 + "/src/firmware.cpp#L10-L12", rendered)
@@ -161,24 +161,24 @@ class SiteReferenceContracts(unittest.TestCase):
"upstream": "https://gitlab.com/vendor/example",
"upstream_commit": "b" * 40,
}
rendered = _source_ref_markdown(profile, "jg.c:213-214")
rendered = source_ref_markdown(profile, "jg.c:213-214")
self.assertEqual(rendered, "`jg.c:213-214`")
self.assertNotIn("http", rendered)
# A first segment equal to a repository's name proves nothing: PCSX2
# keeps its sources in pcsx2/, hatariB vendors Hatari in hatari/.
# Stripped, 470 links pointed at nothing or at another file.
prefixed = _source_ref_markdown(profile, "example/jg.c:213-214")
prefixed = source_ref_markdown(profile, "example/jg.c:213-214")
self.assertEqual(prefixed, "`example/jg.c:213-214`")
@mock.patch("sitegen.sources.tree_holds", lambda *_args: True) # a path the record confirms
def test_a_single_repository_links_the_path_as_written(self):
profile = {"source": "https://github.com/PCSX2/pcsx2", "source_commit": "c" * 40}
rendered = _source_ref_markdown(profile, "pcsx2/ImGui/FullscreenUI.cpp:755-759")
rendered = source_ref_markdown(profile, "pcsx2/ImGui/FullscreenUI.cpp:755-759")
self.assertIn("/blob/" + "c" * 40 + "/pcsx2/ImGui/FullscreenUI.cpp#L755-L759", rendered)
def test_preprocessor_tokens_cannot_become_page_headings(self):
rendered = _admonition_body("First paragraph.\n\n#if FEATURE\nEnabled")
rendered = admonition_body("First paragraph.\n\n#if FEATURE\nEnabled")
self.assertIn("\\#if FEATURE", rendered)
self.assertNotIn("\n #if FEATURE", rendered)
@@ -189,9 +189,9 @@ class SiteReferenceContracts(unittest.TestCase):
pages = {"systems/qemu.md": {}, "emulators/qemu.md": {"hasPart": [{"name": "a"}]}}
with mock.patch.dict(descriptions.PAGE_DATA, pages, clear=True):
self.assertEqual(_browser_title(Path("emulators/qemu.md"), "QEMU"),
self.assertEqual(page_browser_title(Path("emulators/qemu.md"), "QEMU"),
"QEMU emulator BIOS files")
self.assertEqual(_browser_title(Path("systems/qemu.md"), "QEMU"), "QEMU BIOS files")
self.assertEqual(page_browser_title(Path("systems/qemu.md"), "QEMU"), "QEMU BIOS files")
ACCEPTED = (
("md5", "c87a52c277f7952b41c639fc7bf0a43b"),
@@ -336,7 +336,7 @@ class APlatformPageSaysWhereEachFileGoes(unittest.TestCase):
declared = [{"name": "IPL.bin", "destination": f"dolphin-emu/Sys/GC/{r}/IPL.bin",
"sha1": str(i) * 40} for i, r in enumerate(regions)]
files = [{"name": "IPL.bin", "status": "ok"} for _ in regions]
lines = platformfiles._render_platform_systems(
lines = platformfiles.render_platform_systems(
{"nintendo-gamecube": files}, {("nintendo-gamecube", "IPL.bin"): declared}, {})
for region in regions:
# The folder: the name is before it in the row.
@@ -408,11 +408,11 @@ class EmulatorPagesPrintWholeHashes(unittest.TestCase):
whole found nothing."""
def test_full_and_split(self):
from sitegen.fields import _hash_spans
from sitegen.fields import hash_spans
sha1 = "0c3de403b524107809fa9308b730d60e8e41ba93"
self.assertIn(f">{sha1}</code>", _hash_spans(sha1))
both = _hash_spans(f"{'a' * 64}, {'b' * 64}")
self.assertIn(f">{sha1}</code>", hash_spans(sha1))
both = hash_spans(f"{'a' * 64}, {'b' * 64}")
self.assertIn(">" + "a" * 64 + "</code>", both)
self.assertIn(">" + "b" * 64 + "</code>", both)
self.assertNotIn("...", both)
@@ -461,7 +461,7 @@ class ASystemCardLandsOnThePlatformsSection(unittest.TestCase):
def test_section_and_destination(self):
import types
from sitegen.cards import _platform_links
from sitegen.cards import platform_links
consumers = types.SimpleNamespace(
platforms={"s": {"retrodeck"}},
@@ -469,7 +469,7 @@ class ASystemCardLandsOnThePlatformsSection(unittest.TestCase):
platform_destinations={"s": {"retrodeck": {"bios/scph5000.bin"}}},
)
self.assertEqual(
_platform_links("s", consumers),
platform_links("s", consumers),
["[RetroDECK](../platforms/retrodeck.md#sony-playstation): `bios/scph5000.bin`"],
)
@@ -588,8 +588,8 @@ class OnlyAPinnedProfileClaimsAPin(unittest.TestCase):
"emulators/redream.md": {},
}
with mock.patch.dict(descriptions.PAGE_DATA, pages, clear=True):
pinned = descriptions._page_description("", Path("emulators/pinned.md"), "P")
loose = descriptions._page_description("", Path("emulators/redream.md"), "R")
pinned = descriptions.page_description("", Path("emulators/pinned.md"), "P")
loose = descriptions.page_description("", Path("emulators/redream.md"), "R")
# A search snippet is level 0: the pin is on the page, not in it.
self.assertNotIn("source-pinned", pinned)
self.assertNotIn("source-pinned", loose)
@@ -722,13 +722,13 @@ class AHashFindsEveryPageThatNamesIt(unittest.TestCase):
members = {"dolphin-sys": {"ApprovedInis.json": {"sha1": sha1},
"Stale.json": {"sha1": "ef" * 20}}}
registry = {"dolphin-sys": {"local_cache": "data/dolphin-sys"}}
digests = lookup._data_member_digests(members, registry, Path(tmp))
digests = lookup.data_member_digests(members, registry, Path(tmp))
self.assertEqual(digests, {sha1: {
"sha1": sha1, "md5": hashlib.md5(body).hexdigest(),
"sha256": hashlib.sha256(body).hexdigest(),
"crc32": f"{zlib.crc32(body):08x}"}})
with mock.patch.object(lookup, "_data_member_digests", return_value=digests), \
mock.patch.object(structured, "_data_member_digests", return_value=digests):
with mock.patch.object(lookup, "data_member_digests", return_value=digests), \
mock.patch.object(structured, "data_member_digests", return_value=digests):
records = lookup.file_lookup_records(
{"files": {}}, {}, {}, [{"sha1": sha1, "url": "u"}],
{"dolphin-sys": {"ApprovedInis.json": {"sha1": sha1}}})
@@ -861,7 +861,7 @@ class AWantedDumpIsFoundByItsHash(unittest.TestCase):
self.assertIn('"wanted"', _json.dumps(schema))
self.assertIn("byLayer('wanted')", (root / "website" / "src" / "scripts" / "site.ts").read_text())
source = script_source("generate_site.py")
self.assertIn('model_retired.load(_REPO_ROOT / "retired.json"), wanted)', source)
self.assertIn('model_retired.load(REPO_ROOT / "retired.json"), wanted)', source)
class AMovedPartCardReachesItsPage(unittest.TestCase):
@@ -913,7 +913,7 @@ class AFileHasAnAddressByContent(unittest.TestCase):
self.assertIn("params.has('sha1')", script)
from packs.crossref import FileConsumers
card = "\n".join(cards._system_file_card(
card = "\n".join(cards.system_file_card(
{"name": "x.rom", "sha1": "ab" * 20, "size": 1}, FileConsumers({"files": {}}),
))
self.assertIn("/retrobios/files/?sha1=" + "ab" * 20, card)
@@ -1002,10 +1002,10 @@ class ACitationSaysWhoseCodeItIs(unittest.TestCase):
@mock.patch("sitegen.sources.tree_holds", lambda *_args: True) # a path the record confirms
def test_each_part_links_to_its_repository_with_its_label(self):
from sitegen.sources import _source_ref_markdown, requested_by
from sitegen.sources import source_ref_markdown, requested_by
ref = "source libretro.c:5, upstream emu/memory.c:46, 50-52"
text = _source_ref_markdown(self.PROFILE, ref)
text = source_ref_markdown(self.PROFILE, ref)
self.assertIn("libretro/a5200/blob/" + "a" * 40 + "/libretro.c#L5) (libretro glue)", text)
self.assertIn("alekmaul/a5200/blob/" + "b" * 40 + "/emu/memory.c#L50-L52) (upstream emulator)",
text)
@@ -1016,10 +1016,10 @@ class ACitationSaysWhoseCodeItIs(unittest.TestCase):
"upstream emulator")
def test_a_role_without_a_pin_links_nowhere_else(self):
from sitegen.sources import _source_ref_markdown
from sitegen.sources import source_ref_markdown
profile = {**self.PROFILE, "upstream_commit": ""}
self.assertEqual(_source_ref_markdown(profile, "upstream emu/memory.c:46"),
self.assertEqual(source_ref_markdown(profile, "upstream emu/memory.c:46"),
"`emu/memory.c:46` (upstream emulator)")
@@ -1028,10 +1028,10 @@ class EveryAcceptedHashIsItsOwnWord(unittest.TestCase):
search made one token of it and found none but the first."""
def test_a_list_is_split(self):
from sitegen.fields import _hash_spans
from sitegen.fields import hash_spans
md5s = ["96cf" + "0" * 28, "d5af" + "0" * 28]
text = _hash_spans(",".join(md5s))
text = hash_spans(",".join(md5s))
for md5 in md5s:
self.assertIn(f'<code class="rb-hash">{md5}</code>', text)
@@ -1078,9 +1078,9 @@ class ACardSaysWhyAFileIsLeftOut(unittest.TestCase):
could not tell why a RetroArch pack carried PPSSPP's assets."""
def test_the_build_and_the_platforms_are_named(self):
from sitegen.emulatorcards import _file_badges
from sitegen.emulatorcards import file_badges
badges = " ".join(_file_badges({"name": "a", "bundled": True, "mode": "standalone"}, True))
badges = " ".join(file_badges({"name": "a", "bundled": True, "mode": "standalone"}, True))
self.assertIn("installed with the standalone emulator", badges)
@@ -1089,13 +1089,13 @@ class AnEmulatorPageOffersItsInstall(unittest.TestCase):
install them together."""
def test_the_command_names_the_emulator(self):
from sitegen.install import _install_block
from sitegen.install import install_block
profile = yaml.safe_load((ROOT / "emulators" / "pcem.yml").read_text(encoding="utf-8"))
text = "\n".join(_install_block("pcem", profile))
text = "\n".join(install_block("pcem", profile))
self.assertIn("/i | sh -s -- --emulator pcem", text)
self.assertIn("/i.ps1))) --emulator pcem", text)
self.assertEqual(_install_block("x", {"type": "alias"}), [])
self.assertEqual(install_block("x", {"type": "alias"}), [])
def test_the_installer_takes_the_option(self):
source = (ROOT / "install.py").read_text(encoding="utf-8")
@@ -1112,12 +1112,12 @@ class NestedProfileBlocksRenderAsLists(unittest.TestCase):
import markdown
except ImportError:
self.skipTest("markdown is not installed")
from sitegen.render import _render_yaml_value
from sitegen.render import render_yaml_value
# The page opens the block with ???+ (pymdownx.details). An admonition
# nests its body by the same four spaces, and needs nothing CI lacks.
lines = ['!!! abstract "Analysis"', ""]
_render_yaml_value(lines, value, 4)
render_yaml_value(lines, value, 4)
return markdown.markdown("\n".join(lines), extensions=["admonition"])
def test_a_nested_mapping_is_a_nested_list(self):
@@ -1131,7 +1131,7 @@ class NestedProfileBlocksRenderAsLists(unittest.TestCase):
def test_platform_details_are_a_list(self):
from sitegen import fields
lines = fields._render_platform_details(
lines = fields.render_platform_details(
{"platform_details": {"megacd": {"root": "x"}, "note": "y"}}
)
try:
@@ -1194,7 +1194,7 @@ class TheOneLinerIsWhereUsersLand(unittest.TestCase):
from sitegen import cards
from sitegen import render as siterender
saved = dict(siterender._system_page_map)
saved = dict(siterender.system_page_map)
self.addCleanup(siterender.set_system_page_map, saved)
siterender.set_system_page_map({"sony-playstation": ("sony", "PlayStation"),
"nowhere": ("sony", "PlayStation")})
+2 -2
View File
@@ -47,7 +47,7 @@ def _docs_pages() -> list[Path]:
def _level(page: Path) -> str:
return str(decorate._front_matter(page.read_text(encoding="utf-8")).get("level") or "")
return str(decorate.front_matter(page.read_text(encoding="utf-8")).get("level") or "")
class FiveTabs(unittest.TestCase):
@@ -168,7 +168,7 @@ class SampleCoresLeaveTheNavigation(unittest.TestCase):
class EveryPageHasALevel(unittest.TestCase):
def test_wiki_sources_declare_one(self):
for page in sorted((REPO_ROOT / "wiki").glob("*.md")):
level = decorate._front_matter(page.read_text(encoding="utf-8")).get("level")
level = decorate.front_matter(page.read_text(encoding="utf-8")).get("level")
with self.subTest(page=page.name):
self.assertIn(level, decorate.LEVELS)
+3 -3
View File
@@ -161,9 +161,9 @@ class WhereEachSystemFindsItsFile(unittest.TestCase):
def test_the_generator_writes_them(self):
source = script_source("generate_site.py")
self.assertIn("sitehandheld.write_launchers(public, _REPO_ROOT)", source)
self.assertIn("sitehandheld.platform_block(platform_name, _REPO_ROOT)", source)
self.assertIn("sitehandheld.group_page(_REPO_ROOT)", source)
self.assertIn("sitehandheld.write_launchers(public, REPO_ROOT)", source)
self.assertIn("sitehandheld.platform_block(platform_name, REPO_ROOT)", source)
self.assertIn("sitehandheld.group_page(REPO_ROOT)", source)
if __name__ == "__main__":
+6 -6
View File
@@ -69,12 +69,12 @@ class TheGivenProfilesAndPlatforms(_Inputs):
def test_emulator_names_come_from_the_given_profiles(self) -> None:
self.use(emulators=self.emulators)
self.assertEqual(set(collection._profiles_on_disk()), {"fixturecore"})
self.assertEqual(platformfiles._emulator_named_link("fixturecore"),
self.assertEqual(set(collection.profiles_on_disk()), {"fixturecore"})
self.assertEqual(platformfiles.emulator_named_link("fixturecore"),
"[Fixture Core](emulators/fixturecore.md)")
def test_release_pack_does_not_depend_on_the_working_directory(self) -> None:
released = install._release_pack_platforms()
released = install.release_pack_platforms()
self.assertIn("retroarch", released)
here = os.getcwd()
os.chdir(REPO_ROOT / "scripts")
@@ -102,14 +102,14 @@ class TheCollectionDoesNotDependOnTheWorkingDirectory(unittest.TestCase):
db = json.loads((REPO_ROOT / "database.json").read_text(encoding="utf-8"))
here = sitecollection.collection_paths(db)
places = sitecollection._copy_places(db)
places = sitecollection.copy_places(db)
elsewhere = Path(tempfile.mkdtemp(dir=REPO_ROOT / "tmp" if (REPO_ROOT / "tmp").is_dir() else None))
self.addCleanup(shutil.rmtree, elsewhere)
cwd = os.getcwd()
os.chdir(elsewhere)
self.addCleanup(os.chdir, cwd)
self.assertEqual(sitecollection.collection_paths(db), here)
self.assertEqual(sitecollection._copy_places(db), places)
self.assertEqual(sitecollection.copy_places(db), places)
self.assertGreater(sum(map(len, here.values())), len(here))
def test_the_bios_folder_sits_beside_the_given_database(self) -> None:
@@ -161,7 +161,7 @@ class NoPageModuleReadsTheRepositoryInputs(unittest.TestCase):
source = ast.get_source_segment(
build,
next(n for n in ast.parse(build).body
if isinstance(n, ast.FunctionDef) and n.name == "_generate"))
if isinstance(n, ast.FunctionDef) and n.name == "generate_site"))
self.assertLess(source.index("siteinputs.use("), source.index("load_database("))
+6 -6
View File
@@ -40,12 +40,12 @@ def _profile(name: str) -> dict:
class DataTreeReaders(unittest.TestCase):
def test_read_by_names_the_emulators(self):
ref = "y-sys"
emulatorcards._DATA_MEMBERS[ref] = {"a.bin": {"size": 1, "sha1": "0" * 40}}
emulatorpage._DATA_READERS[ref] = [("dolphin", "Dolphin"), ("ishiiruka", "Ishiiruka")]
emulatorcards.DATA_MEMBERS[ref] = {"a.bin": {"size": 1, "sha1": "0" * 40}}
emulatorpage.DATA_READERS[ref] = [("dolphin", "Dolphin"), ("ishiiruka", "Ishiiruka")]
try:
page = emulatorpage._data_tree_page(ref, {}, [("y-sys", ["a.bin"])], 0)
finally:
del emulatorcards._DATA_MEMBERS[ref], emulatorpage._DATA_READERS[ref]
del emulatorcards.DATA_MEMBERS[ref], emulatorpage.DATA_READERS[ref]
self.assertIn("Read by [Dolphin](dolphin.md#data-directories) and "
"[Ishiiruka](ishiiruka.md#data-directories).", page)
self.assertNotIn("('dolphin'", page)
@@ -66,9 +66,9 @@ class EngineIntros(unittest.TestCase):
class SectionNames(unittest.TestCase):
def test_fba2012_is_headed_by_its_program(self):
self.assertEqual(startwith._section_label("Arcade", "fba2012"), "FB Alpha 2012")
self.assertEqual(startwith._section_label("Arcade", "Arcade"), startwith.OTHER_ARCADE_LABEL)
self.assertEqual(startwith._section_label("Sony", "PlayStation"), "PlayStation")
self.assertEqual(startwith.section_label("Arcade", "fba2012"), "FB Alpha 2012")
self.assertEqual(startwith.section_label("Arcade", "Arcade"), startwith.OTHER_ARCADE_LABEL)
self.assertEqual(startwith.section_label("Sony", "PlayStation"), "PlayStation")
self.assertEqual(collection.SECTION_LABELS[("Arcade", "fba2012")],
_profile("fbalpha2012")["emulator"])
+4 -4
View File
@@ -111,7 +111,7 @@ class NotFoundPage(unittest.TestCase):
terms={},
),
)
front = decorate._front_matter(text)
front = decorate.front_matter(text)
self.assertIs(front["tableOfContents"], False)
self.assertIs(front["prev"], False)
self.assertIs(front["next"], False)
@@ -221,7 +221,7 @@ class OneNextPerPage(unittest.TestCase):
def test_card_pages_turn_pagination_off(self):
for rel in ("systems/sony.md", "emulators/duckstation.md", "platforms/batocera.md"):
_target, text = sitestarlight.render_page(rel, "# T\n\nBody.\n", sitestarlight.PageMeta(level="explore", weight=None, browser_title="T", description="d", structured={}, terms={}))
front = decorate._front_matter(text)
front = decorate.front_matter(text)
with self.subTest(page=rel):
self.assertIs(front["prev"], False)
self.assertIs(front["next"], False)
@@ -230,12 +230,12 @@ class OneNextPerPage(unittest.TestCase):
body = ("# Troubleshooting\n\nText.\n\n## Next steps\n\n"
"- [Common questions](faq.md)\n- [Glossary](glossary.md)\n")
_target, text = sitestarlight.render_page("wiki/troubleshooting.md", body, sitestarlight.PageMeta(level="start", weight=None, browser_title="Troubleshooting", description="d", structured={}, terms={}))
front = decorate._front_matter(text)
front = decorate.front_matter(text)
self.assertEqual(front["next"], {"link": "/retrobios/wiki/faq/", "label": "Common questions"})
def test_a_page_without_next_steps_keeps_the_reading_order(self):
_target, text = sitestarlight.render_page("wiki/faq.md", "# FAQ\n\nText.\n", sitestarlight.PageMeta(level="start", weight=None, browser_title="FAQ", description="d", structured={}, terms={}))
self.assertNotIn("next", decorate._front_matter(text))
self.assertNotIn("next", decorate.front_matter(text))
class ReferenceGrouped(unittest.TestCase):
+3 -3
View File
@@ -120,10 +120,10 @@ class ARowPerFile(unittest.TestCase):
files = [{"name": "a.bin", "status": "ok"}, {"name": "b.bin", "status": "ok"}]
system = "nintendo-gamecube"
config = {(system, "a.bin"): [{"destination": "a.bin"}], (system, "b.bin"): [{}]}
text = "\n".join(platformfiles._render_platform_systems({system: files}, config, {}))
text = "\n".join(platformfiles.render_platform_systems({system: files}, config, {}))
self.assertIn('<div class="rb-files">', text)
config[(system, "b.bin")] = [{"destination": "sub/b.bin"}]
text = "\n".join(platformfiles._render_platform_systems({system: files}, config, {}))
text = "\n".join(platformfiles.render_platform_systems({system: files}, config, {}))
self.assertIn('<div class="rb-files rb-files-path">', text)
def test_status_words(self):
@@ -173,7 +173,7 @@ class ReferencesNameTheirRoleOnce(unittest.TestCase):
self.assertIn(f"**{word}**", platformfiles.ROLE_LEGEND)
def test_other_pages_keep_the_role_after_each_reference(self):
text = sources._source_ref_markdown(self.PROFILE, self.REFS)
text = sources.source_ref_markdown(self.PROFILE, self.REFS)
self.assertEqual(text.count("(emulator code, libretro port)"), 2)
self.assertIn("`src/c.c:4` (upstream emulator)", text)
+2 -2
View File
@@ -14,7 +14,7 @@ import unittest
from unittest import mock
from model import systemnames
from sitegen.platformfiles import _render_platform_systems
from sitegen.platformfiles import render_platform_systems
A, B, C = "a" * 32, "b" * 32, "c" * 32
@@ -37,7 +37,7 @@ class EachRowItsDeclaration(unittest.TestCase):
}
names = {"psx": "Sony PlayStation", "saturn": "Sega Saturn"}
with mock.patch.dict(systemnames.SYSTEM_NAMES, names):
text = "\n".join(_render_platform_systems(by_system, config_files, {}))
text = "\n".join(render_platform_systems(by_system, config_files, {}))
psx, saturn = text.split("saturn", 1)[0], text.split("saturn", 1)[1]
self.assertIn(A, psx)
self.assertNotIn(B, psx)
+21 -21
View File
@@ -72,7 +72,7 @@ from model import systemnames
from model.registry import list_registered_platforms, list_release_pack_platforms
from model.profiles import load_emulator_profiles
from model.platforms import load_platform_config
from resolve.reconcile import HASH_FIELDS, _hash_values
from resolve.reconcile import HASH_FIELDS, hash_values
from resolve.categories import EntryCategories
from sitegen.sources import launcher_ref_markdown, list_source
import check_platform_folder
@@ -89,10 +89,10 @@ DIST = REPO_ROOT / "website" / "dist"
def _accepted(profile_entry: dict) -> set[str]:
values = {v for f in HASH_FIELDS for v in _hash_values(profile_entry, f)}
values = {v for f in HASH_FIELDS for v in hash_values(profile_entry, f)}
for member in profile_entry.get("contents") or []:
if isinstance(member, dict):
values |= {v for f in HASH_FIELDS for v in _hash_values(member, f)}
values |= {v for f in HASH_FIELDS for v in hash_values(member, f)}
return values
@@ -123,11 +123,11 @@ class ReaderMatchedByHash(unittest.TestCase):
cats = EntryCategories(config, self.profiles)
for sys_id, system in (config.get("systems") or {}).items():
for entry in system.get("files") or []:
md5s = set(_hash_values(entry, "md5")) | set(_hash_values(entry, "alt_md5"))
md5s = set(hash_values(entry, "md5")) | set(hash_values(entry, "alt_md5"))
if not md5s:
continue
# The same dump, named by whichever hash both sides state.
declared = md5s | {v for f in HASH_FIELDS for v in _hash_values(entry, f)}
declared = md5s | {v for f in HASH_FIELDS for v in hash_values(entry, f)}
found = cats.explain(entry, entry.get("destination") or entry["name"], sys_id)
for reader in found.get("read_by", []):
if reader["emulator"] == "launcher":
@@ -239,7 +239,7 @@ class EachEntryNamesItsFile(unittest.TestCase):
rows = [[f'<details class="rb-file"><summary>f{n}.bin</summary>x<br>y</details>']
for n in range(4)]
# Three elements a row: two rows fit in a budget of seven.
runs = sitegen_parts._blocks_in_runs(rows, 7, platformfiles._element_weight)
runs = sitegen_parts.blocks_in_runs(rows, 7, platformfiles._element_weight)
self.assertEqual([len(run) for run in runs], [2, 2])
self.assertEqual(sum(runs, []), sum(rows, []))
@@ -406,7 +406,7 @@ class ExportsComplete(unittest.TestCase):
("missing", "game_data", ""))
def test_commit_and_wanted_list(self):
commit = dataexports._source_commit()
commit = dataexports.source_commit()
self.assertRegex(commit, r"^[0-9a-f]{40}$")
schema = json.loads((REPO_ROOT / "schemas" / "site-api-envelope.schema.json")
.read_text(encoding="utf-8"))
@@ -691,15 +691,15 @@ class EveryEnvelopeCarriesTheCommit(unittest.TestCase):
def test_the_writers_pass_it(self):
source = script_source("generate_site.py")
self.assertIn('str(db.get("generated_at") or _timestamp()), _source_commit(),\n )\n'
self.assertIn('str(db.get("generated_at") or data_timestamp()), source_commit(),\n )\n'
" clash", source)
block = source[source.index("public_profiles = {"):source.index("pages = emulator_pages(")]
self.assertIn("write_single_item(", block)
self.assertIn("_source_commit()", block)
self.assertIn("source_commit()", block)
def test_every_built_envelope_has_it(self):
_built(API / "catalog.json")
if not dataexports._source_commit():
if not dataexports.source_commit():
raise unittest.SkipTest("not a git checkout")
lacking = [
path.relative_to(API).as_posix() for path in sorted(API.rglob("*.json"))
@@ -729,7 +729,7 @@ class ManifestsArePublished(unittest.TestCase):
schema = json.loads((REPO_ROOT / "schemas" / "install-manifest.schema.json").read_text())
for field in ("dest", "repo_path", "release_asset", "cores"):
description = schema["$defs"]["file"]["properties"][field]["description"]
self.assertIn(f"| `{field}` | {render._escape_tags(description)} |", page)
self.assertIn(f"| `{field}` | {render.escape_tags(description)} |", page)
self.assertIn("## Platform manifests", page)
self.assertIn("**Licence:**", page)
self.assertIn("## Hosting, rate limits and caching", page)
@@ -834,21 +834,21 @@ class PlatformPagesLinkTheirSystemsAndEmulators(unittest.TestCase):
"""8.9: the overview named emulators as ids, none of 1,463 linked."""
def test_an_emulator_is_named_and_linked(self):
link = platformfiles._emulator_named_link("beetle_psx", "../")
link = platformfiles.emulator_named_link("beetle_psx", "../")
self.assertRegex(link, r"^\[[^\]]+\]\(\.\./emulators/beetle_psx\.md\)$")
self.assertNotEqual(link, "[beetle_psx](../emulators/beetle_psx.md)")
def test_the_overview_column_uses_it(self):
source = script_source("generate_site.py")
block = source[source.index("### Systems overview"):source.index("_render_platform_systems(by_system")]
self.assertIn("_emulator_named_link(e, \"../\")", block)
block = source[source.index("### Systems overview"):source.index("render_platform_systems(by_system")]
self.assertIn("emulator_named_link(e, \"../\")", block)
self.assertNotIn('", ".join(sys_emus[:3])', block)
def test_a_moved_list_opens_on_its_console_and_names_its_parent(self):
# Past PLATFORM_SECTION_BUDGET, so the list leaves for a page of its own.
files = [{"name": f"{'f' * 200}{i}.bin", "status": "ok"} for i in range(2000)]
moved: dict[str, str] = {}
platformfiles._render_platform_systems(
platformfiles.render_platform_systems(
{"sony-playstation": files}, {}, {}, ("retroarch", "RetroArch"), moved, {})
self.assertTrue(moved)
page = next(iter(moved.values()))
@@ -858,11 +858,11 @@ class PlatformPagesLinkTheirSystemsAndEmulators(unittest.TestCase):
def test_part_pages_of_gaps_and_cross_reference_name_their_parent(self):
moved: dict[str, str] = {}
sitegen_parts._list_pages("gaps-x", "T", "intro", [], [["| a |"]], moved,
sitegen_parts.list_pages("gaps-x", "T", "intro", [], [["| a |"]], moved,
parent=("What the packs do not hold", "/gaps/"))
self.assertIn('parent:\n label: "What the packs do not hold"\n link: "/gaps/"', moved["gaps-x"])
source = script_source("generate_site.py")
self.assertIn('_parent_front_matter(("Cores by platform", "/cross-reference/"))', source)
self.assertIn('parent_front_matter(("Cores by platform", "/cross-reference/"))', source)
self.assertIn('parent=("Dump provenance", "/provenance/")', source)
@@ -906,7 +906,7 @@ class SourceLinksGoWhereTheFileIs(unittest.TestCase):
original = sources._tree_paths
sources._tree_paths = lambda repo, pin: tree
try:
return sources._source_ref_markdown(
return sources.source_ref_markdown(
self.PROFILE, "src/emulator.cpp:234; src/core/loader/ncch.cpp:151-164")
finally:
sources._tree_paths = original
@@ -939,7 +939,7 @@ class SourceLinksGoWhereTheFileIs(unittest.TestCase):
if not isinstance(entry, dict) or not entry.get("source_ref"):
continue
for slug, pin, path in link.findall(
sources._source_ref_markdown(profile, entry["source_ref"])):
sources.source_ref_markdown(profile, entry["source_ref"])):
from core import upstream
repo = upstream.parse_repo(f"https://github.com/{slug}")
@@ -1120,7 +1120,7 @@ class SourceLinksOnlyWhereTheFileIs(unittest.TestCase):
def test_an_address_in_a_binary_reads_as_one(self):
profile = {"source": "https://github.com/o/r", "source_commit": "e" * 40}
text = sources._source_ref_markdown(
text = sources.source_ref_markdown(
profile, "Nesoid 2.5.0 libnes.so 0x455a4-0x45694 (setter), 0x8094-0x80ac")
self.assertEqual(text, "offset `0x455a4-0x45694` in `Nesoid 2.5.0 libnes.so` (setter), "
"offset `0x8094-0x80ac` in `Nesoid 2.5.0 libnes.so`")
@@ -1132,7 +1132,7 @@ class SourceLinksOnlyWhereTheFileIs(unittest.TestCase):
with mock.patch.object(sources, "_verified", return_value=record):
sources._tree_paths.cache_clear()
try:
text = sources._source_ref_markdown(profile, "src/a.c:5, src/b.c:7")
text = sources.source_ref_markdown(profile, "src/a.c:5, src/b.c:7")
finally:
sources._tree_paths.cache_clear()
self.assertIn("[`src/a.c:5`](https://github.com/o/r/blob/" + "e" * 40 + "/src/a.c#L5)", text)
+9 -9
View File
@@ -134,7 +134,7 @@ class StructuredBlocks(unittest.TestCase):
def render(self, profile: dict) -> str:
from sitegen import fields
return "\n".join(fields._render_structured_blocks(profile))
return "\n".join(fields.render_structured_blocks(profile))
@mock.patch("sitegen.sources.tree_holds", lambda *_args: True) # a path the record confirms
def test_a_source_ref_in_a_block_is_a_pinned_link(self):
@@ -310,7 +310,7 @@ class ForgesUpstreamDoesNotRead(unittest.TestCase):
profile = {"source": url, "source_commit": "f6c00044" + "0" * 32, **extra}
return (sources.revision_markdown(profile),
sources._source_ref_markdown(profile, ref))
sources.source_ref_markdown(profile, ref))
def test_bitbucket(self):
revision, ref = self.links("https://bitbucket.org/linuxwolf6/splitwolf",
@@ -382,7 +382,7 @@ class TheSearchLandsOnTheCard(unittest.TestCase):
for i in range(11)}
names = {sys_id: f"System {sys_id[-2:]}" for sys_id in by_system}
with mock.patch.dict(systemnames.SYSTEM_NAMES, names):
lines = platformfiles._render_platform_systems(by_system, {}, {})
lines = platformfiles.render_platform_systems(by_system, {}, {})
headings = [line for line in lines if line.startswith("### ")]
self.assertEqual(len(headings), 11)
self.assertTrue(headings[0].endswith("{ #system-00 }"))
@@ -393,7 +393,7 @@ class TheSearchLandsOnTheCard(unittest.TestCase):
from sitegen import emulatorcards
entry = {"name": "scph5501.bin", "required": True}
lines = emulatorcards._render_emulator_file(
lines = emulatorcards.render_emulator_file(
entry, {"files": [entry]}, None, [entry], lambda f: True, "file-scph5501-bin")
self.assertTrue(lines[2].startswith('<h3 id="file-scph5501-bin" class="rb-file-title"'))
self.assertIn("<code>scph5501.bin</code>", lines[2])
@@ -403,7 +403,7 @@ class TheSearchLandsOnTheCard(unittest.TestCase):
from packs.crossref import FileConsumers
entry = {"name": "a.bin", "sha1": "a" * 40, "md5": "b" * 32, "size": 3}
lines = cards._system_file_card(entry, FileConsumers({"files": {}}))
lines = cards.system_file_card(entry, FileConsumers({"files": {}}))
self.assertTrue(lines[2].startswith('<h3 id="sha1-aaaaaaaaaaaa" class="rb-file-title"'))
self.assertIn("<code>a.bin</code>", lines[2])
@@ -424,7 +424,7 @@ class TheSearchSkipsLinkLists(unittest.TestCase):
consumers.installed = {sha1: {"batocera": {"bios/a.bin"}}}
consumers.emulators = {sha1: {"duckstation"}}
entry = {"name": "a.bin", "sha1": sha1, "md5": "b" * 32, "size": 3}
lines = cards._system_file_card(entry, consumers)
lines = cards.system_file_card(entry, consumers)
self.assertIn("<code>a.bin</code>", lines[2])
text = "\n".join(lines)
searched, _sep, skipped = text.partition('<dl class="rb-facts" data-pagefind-ignore>')
@@ -440,7 +440,7 @@ class TheSearchSkipsLinkLists(unittest.TestCase):
from packs.crossref import FileConsumers
entry = {"name": "0.ogg", "sha1": "a" * 40, "size": 3}
lines = cards._system_file_card(
lines = cards.system_file_card(
entry, FileConsumers({"files": {}}), searchable=False)
self.assertIn("data-pagefind-ignore", lines[2])
self.assertNotIn("data-pagefind-weight", lines[2])
@@ -451,7 +451,7 @@ class TheSearchSkipsLinkLists(unittest.TestCase):
lines = ["- Path: `p`", "- SHA1: x", "- Source: `a.c:1`", "- Platforms: p",
"- Destination: `d`", "- Contents (1 members):", " - `m`",
"- Note"]
out = [line for line in cards._search_skipped_apart(lines) if line]
out = [line for line in cards.search_skipped_apart(lines) if line]
self.assertEqual(out, [
"- Path: `p`",
'<div class="rb-search-skip" data-pagefind-ignore>',
@@ -523,7 +523,7 @@ class AMemberIsReadInItsArchive(unittest.TestCase):
self.assertIn(shipped, credited)
self.assertFalse([p for p in credited if p.endswith("/sm1.sm1")])
sm1 = next(f for f in files if f["name"] == "sm1.sm1")
rows = "\n".join(emulatorcards._render_emulator_file(sm1, profile, consumers, files,
rows = "\n".join(emulatorcards.render_emulator_file(sm1, profile, consumers, files,
lambda _f: True, owner="fbneo"))
self.assertIn("Collection copy: member `sm1.sm1` of", rows)
self.assertIn(shipped, rows)
+16 -16
View File
@@ -230,10 +230,10 @@ class Descriptions(unittest.TestCase):
saved = dict(descriptions.PAGE_DATA)
self.addCleanup(lambda: (descriptions.PAGE_DATA.clear(), descriptions.PAGE_DATA.update(saved)))
descriptions.PAGE_DATA["emulators/duckstation.md"] = {"hasPart": [{"name": "scph5501.bin"}]}
self.assertEqual(descriptions._browser_title(Path("emulators/duckstation.md"), "DuckStation"),
self.assertEqual(descriptions.page_browser_title(Path("emulators/duckstation.md"), "DuckStation"),
"DuckStation BIOS files")
self.assertEqual(descriptions._browser_title(Path("systems/sega.md"), "Sega"), "Sega BIOS files")
self.assertEqual(descriptions._browser_title(Path("systems/sega-dreamcast.md"), "Sega: Dreamcast"),
self.assertEqual(descriptions.page_browser_title(Path("systems/sega.md"), "Sega"), "Sega BIOS files")
self.assertEqual(descriptions.page_browser_title(Path("systems/sega-dreamcast.md"), "Sega: Dreamcast"),
"Dreamcast BIOS files (Sega)")
def test_an_emulator_page_is_described_by_its_intro(self) -> None:
@@ -242,7 +242,7 @@ class Descriptions(unittest.TestCase):
descriptions.PAGE_DATA["emulators/duckstation.md"] = {"hasPart": [{"name": "scph5501.bin"}]}
body = ("# DuckStation\n\nDuckStation emulates Sony PlayStation. It picks the BIOS for "
"the game's region.\n\n<details>\n\nThe installer finds the platform.\n")
text = descriptions._page_description(body, Path("emulators/duckstation.md"), "DuckStation")
text = descriptions.page_description(body, Path("emulators/duckstation.md"), "DuckStation")
self.assertTrue(text.startswith("DuckStation emulates Sony PlayStation."))
self.assertNotIn("source-pinned", text)
@@ -255,9 +255,9 @@ class Descriptions(unittest.TestCase):
with open(REPO_ROOT / "emulators" / "daedalusx64.yml", encoding="utf-8") as handle:
structured.record_emulator_page("daedalusx64", yaml.safe_load(handle))
key = Path("emulators/daedalusx64.md")
self.assertEqual(descriptions._browser_title(key, "DaedalusX64"), "DaedalusX64 emulator")
self.assertEqual(descriptions.page_browser_title(key, "DaedalusX64"), "DaedalusX64 emulator")
body = "# DaedalusX64\n\nDaedalusX64 emulates Nintendo 64.\n"
self.assertEqual(descriptions._page_description(body, key, "DaedalusX64"),
self.assertEqual(descriptions.page_description(body, key, "DaedalusX64"),
"DaedalusX64 emulates Nintendo 64. Every file it reads comes with the app.")
def test_an_emulator_snippet_names_the_files_searched_for(self) -> None:
@@ -272,17 +272,17 @@ class Descriptions(unittest.TestCase):
key = Path("emulators/flycast.md")
body = ("# Flycast\n\nFlycast emulates Sega Dreamcast. It reads 10 files, 4 of them "
"required: without a required file it does not start games.\n")
text = descriptions._page_description(body, key, "Flycast")
text = descriptions.page_description(body, key, "Flycast")
self.assertTrue(text.startswith("Sega Dreamcast BIOS for Flycast: dc_boot.bin, "), text)
self.assertLessEqual(len(text), 155)
self.assertFalse(text.endswith("..."), text)
def test_a_switch_emulator_reads_keys(self) -> None:
self.assertEqual(emulatorcards._snippet_noun(["prod.keys", "dev.keys", "title.keys", "key_retail.bin"], 4, 4), "keys")
self.assertEqual(emulatorcards._snippet_noun(["prod.keys", "title.keys", "<firmware>.zip", "a.txt"], 3, 4),
self.assertEqual(emulatorcards.snippet_noun(["prod.keys", "dev.keys", "title.keys", "key_retail.bin"], 4, 4), "keys")
self.assertEqual(emulatorcards.snippet_noun(["prod.keys", "title.keys", "<firmware>.zip", "a.txt"], 3, 4),
"keys and firmware")
self.assertEqual(emulatorcards._snippet_noun(["gba_bios.bin", "gb_bios.bin"], 2, 2), "BIOS")
self.assertEqual(emulatorcards._snippet_noun(["oot.z64", "oot-mq.z64", "font.bin"], 1, 3), "files")
self.assertEqual(emulatorcards.snippet_noun(["gba_bios.bin", "gb_bios.bin"], 2, 2), "BIOS")
self.assertEqual(emulatorcards.snippet_noun(["oot.z64", "oot-mq.z64", "font.bin"], 1, 3), "files")
def test_an_any_name_snippet_says_what_to_do(self) -> None:
saved = dict(descriptions.PAGE_DATA)
@@ -291,7 +291,7 @@ class Descriptions(unittest.TestCase):
body = ("# AetherSX2\n\nAetherSX2 needs one Sony PlayStation 2 BIOS file, any region."
"\n\n1. Download [`ps2.bin`](../x/).\n2. Put it in this folder:\n")
self.assertEqual(
descriptions._page_description(body, Path("emulators/aethersx2.md"), "AetherSX2"),
descriptions.page_description(body, Path("emulators/aethersx2.md"), "AetherSX2"),
"AetherSX2 needs one Sony PlayStation 2 BIOS file, any region. Download one "
"from this page and put it in the folder it shows. Any file name works.")
@@ -311,24 +311,24 @@ class Descriptions(unittest.TestCase):
body = ("# ROCKNIX\n\nA system for handhelds. [ROCKNIX website](https://rocknix.org).\n\n"
"## On the device { #install }\n")
self.assertEqual(
descriptions._page_description(body, Path("platforms/rocknix.md"), "ROCKNIX"),
descriptions.page_description(body, Path("platforms/rocknix.md"), "ROCKNIX"),
"The BIOS files for ROCKNIX, the folder they go in and the command that installs "
"them. A system for handhelds.")
def test_a_console_page_is_described_by_its_start_line(self) -> None:
body = "# Sega: Dreamcast\n\nPart of Sega.\n\n**Start with**: `dc_boot.bin`, `dc_flash.bin`.\n"
text = descriptions._page_description(body, Path("systems/sega-dreamcast.md"), "Sega: Dreamcast")
text = descriptions.page_description(body, Path("systems/sega-dreamcast.md"), "Sega: Dreamcast")
self.assertEqual(text, "Dreamcast BIOS files (Sega). Start with dc_boot.bin, dc_flash.bin.")
def test_the_faq_is_described_by_its_questions(self) -> None:
body = ("# Common questions\n\n## Are BIOS files needed?\n\nYes.\n\n## Which one?\n\n"
"Run the command with --dry-run.\n\n## Zip or not?\n\nZip.\n")
text = descriptions._page_description(body, Path("wiki/faq.md"), "Common questions")
text = descriptions.page_description(body, Path("wiki/faq.md"), "Common questions")
self.assertTrue(text.startswith("Common questions: Are BIOS files needed?"))
def test_a_written_description_wins(self) -> None:
source = script_source("generate_site.py")
self.assertIn('authored.get("description") or _page_description(', source)
self.assertIn('authored.get("description") or page_description(', source)
def test_the_check_counts_templates(self) -> None:
pages = {}
+21 -21
View File
@@ -54,7 +54,7 @@ class LinksFollowContent(unittest.TestCase):
db = load_database("database.json")
config = load_platform_config("misterfpga")
names: dict = {}
for mfr, consoles in collection._group_by_manufacturer(db).items():
for mfr, consoles in collection.group_by_manufacturer(db).items():
for console, entries in consoles.items():
for entry in entries:
names.setdefault(entry["name"], set()).add((mfr, console))
@@ -74,17 +74,17 @@ class OtherSpellingsOfOneSystem(unittest.TestCase):
sega-megadrive, and 2,057 of 4,215 emulator system lines had no link."""
def test_a_platform_system_finds_its_emulators(self):
index = whichpack._build_emulator_file_index({
index = whichpack.build_emulator_file_index({
"genesis_plus_gx": {"systems": ["sega-megadrive"]},
"np2kai": {"systems": ["pc-98"]},
})
self.assertEqual(platformfiles._system_emulators("sega-mega-drive", index), ["genesis_plus_gx"])
self.assertEqual(platformfiles._system_emulators("nintendo-snes", index), [])
self.assertEqual(platformfiles.system_emulators("sega-mega-drive", index), ["genesis_plus_gx"])
self.assertEqual(platformfiles.system_emulators("nintendo-snes", index), [])
def _install(self, mapping: dict) -> None:
from sitegen import render as siterender
saved = dict(siterender._system_page_map)
saved = dict(siterender.system_page_map)
self.addCleanup(siterender.set_system_page_map, saved)
siterender.set_system_page_map(mapping)
@@ -92,10 +92,10 @@ class OtherSpellingsOfOneSystem(unittest.TestCase):
from sitegen import render as siterender
self._install({"sega-mega-drive": ("sega", "Mega Drive")})
self.assertEqual(siterender._page_by_norm("sega-megadrive"), ("sega", "Mega Drive"))
self.assertEqual(siterender.page_by_norm("sega-megadrive"), ("sega", "Mega Drive"))
self._install({"sega-mega-drive": ("sega", "Mega Drive"),
"megadrive": ("other", "Elsewhere")})
self.assertIsNone(siterender._page_by_norm("sega-megadrive"))
self.assertIsNone(siterender.page_by_norm("sega-megadrive"))
def test_a_table_of_the_same_size_replaces_the_other_spellings(self):
"""The index of other spellings was kept while the table kept its
@@ -103,15 +103,15 @@ class OtherSpellingsOfOneSystem(unittest.TestCase):
from sitegen import render as siterender
self._install({"sega-mega-drive": ("sega", "Mega Drive")})
self.assertEqual(siterender._page_by_norm("sega-megadrive"), ("sega", "Mega Drive"))
self.assertEqual(siterender.page_by_norm("sega-megadrive"), ("sega", "Mega Drive"))
self._install({"sega-mega-drive": ("other", "Elsewhere")})
self.assertEqual(siterender._page_by_norm("sega-megadrive"), ("other", "Elsewhere"))
self.assertEqual(siterender.page_by_norm("sega-megadrive"), ("other", "Elsewhere"))
def test_a_system_only_profiles_name_is_placed_by_their_files(self):
manufacturers = {"Commodore": {"PET": [{"name": "basic4.bin"}]}}
profiles = {"vice_xpet": {"systems": ["commodore-pet"],
"files": [{"name": "basic4.bin"}]}}
pages = places._system_pages_from_data(
pages = places.system_pages_from_data(
manufacturers, {}, {"files": {}, "indexes": {}}, profiles)
self.assertEqual(pages["commodore-pet"], ("commodore", "PET"))
@@ -136,7 +136,7 @@ class ACopyIsOnItsOwnFoldersPage(unittest.TestCase):
"Fairchild/Channel F/sl31253.bin": ["s"], "Channel F/sl31253.bin": ["s"],
}},
}
groups = collection._group_by_manufacturer(db)
groups = collection.group_by_manufacturer(db)
self.assertEqual(sorted(groups), ["Arcade", "Fairchild"])
self.assertEqual(list(groups["Fairchild"]), ["Channel F"])
# The copy is listed twice and counted once.
@@ -210,10 +210,10 @@ class ACopyFiledByEmulatorDoesNotMoveAMachine(unittest.TestCase):
with tempfile.TemporaryDirectory(dir=REPO_ROOT / "tmp") as tmp:
db = self._db(tmp)
manufacturers = collection._group_by_manufacturer(db)
manufacturers = collection.group_by_manufacturer(db)
config = {"systems": {"nintendo-nes": {"files": [
{"name": "FDS_disksys-nintendo.rom", "sha1": "d" * 40}]}}}
pages = places._system_pages_from_data(
pages = places.system_pages_from_data(
manufacturers, {"p": {"config": config}}, db)
self.assertEqual(pages["nintendo-nes"], ("nintendo", "NES"))
@@ -227,8 +227,8 @@ class ACopyFiledByEmulatorDoesNotMoveAMachine(unittest.TestCase):
from model.profiles import load_emulator_profiles
db = load_database("database.json")
manufacturers = collection._group_by_manufacturer(db)
pages = places._system_pages_from_data(
manufacturers = collection.group_by_manufacturer(db)
pages = places.system_pages_from_data(
manufacturers, {}, db, load_emulator_profiles("emulators", skip_aliases=False))
expected = {
"nintendo-nes": ("nintendo", "NES"),
@@ -248,7 +248,7 @@ class SystemEmulatorsWhenNoIdMatches(unittest.TestCase):
of both rows was empty on every platform page."""
def setUp(self):
self.index = whichpack._build_emulator_file_index({
self.index = whichpack.build_emulator_file_index({
"flycast": {"systems": ["sega-naomi"], "files": [{"name": "airlbios.zip"}]},
"fbneo": {"systems": ["arcade"], "files": [
{"name": "boot.bin", "archive": "bubsys.zip"}]},
@@ -257,18 +257,18 @@ class SystemEmulatorsWhenNoIdMatches(unittest.TestCase):
def test_a_file_the_system_lists_names_its_emulator(self):
self.assertEqual(
platformfiles._system_emulators("sega-dreamcast-arcade", self.index, [{"name": "airlbios.zip"}]),
platformfiles.system_emulators("sega-dreamcast-arcade", self.index, [{"name": "airlbios.zip"}]),
["flycast"],
)
def test_an_archive_member_is_not_a_file_by_that_name(self):
self.assertEqual(
platformfiles._system_emulators("sega-dreamcast", self.index, [{"name": "boot.bin"}]), []
platformfiles.system_emulators("sega-dreamcast", self.index, [{"name": "boot.bin"}]), []
)
def test_an_id_match_is_kept_alone(self):
self.assertEqual(
platformfiles._system_emulators("sega-megadrive", self.index, [{"name": "airlbios.zip"}]),
platformfiles.system_emulators("sega-megadrive", self.index, [{"name": "airlbios.zip"}]),
["genesis"],
)
@@ -295,7 +295,7 @@ class EverySystemLinkLandsOnItsSection(unittest.TestCase):
db = load_database(str(REPO_ROOT / "database.json"))
profiles = load_emulator_profiles(str(REPO_ROOT / "emulators"), skip_aliases=False)
systemnames.set_console_sections(collection._group_by_manufacturer(db), systemnames.program_names(profiles))
systemnames.set_console_sections(collection.group_by_manufacturer(db), systemnames.program_names(profiles))
platforms = REPO_ROOT / "platforms"
ids = {str(sid) for profile in profiles.values() for sid in profile.get("systems") or []}
for name in list_registered_platforms(str(platforms)):
@@ -331,7 +331,7 @@ class EverySystemLinkLandsOnItsSection(unittest.TestCase):
# The Arcade folder of sets no board claims is headed by
# what it holds, its id staying the folder's.
if slug == "arcade":
console = startwith._section_label("Arcade", console)
console = startwith.section_label("Arcade", console)
self.assertEqual(self.headings[page][match["anchor"]], console)
self.assertGreater(linked, 200)
+4 -4
View File
@@ -20,7 +20,7 @@ from model import systemnames
from model.registry import list_registered_platforms
from model.profiles import load_emulator_profiles
from model.platforms import load_platform_config
from model.collection import _group_by_manufacturer
from model.collection import group_by_manufacturer
REPO_ROOT = Path(__file__).resolve().parents[1]
@@ -44,7 +44,7 @@ class SystemNames(unittest.TestCase):
def setUpClass(cls) -> None:
with open(REPO_ROOT / "database.json", encoding="utf-8") as handle:
db = json.load(handle)
cls.manufacturers = _group_by_manufacturer(db)
cls.manufacturers = group_by_manufacturer(db)
cls.profiles = load_emulator_profiles(
str(REPO_ROOT / "emulators"), skip_aliases=False)
systemnames.set_console_sections(
@@ -86,7 +86,7 @@ class SystemNames(unittest.TestCase):
no platform or profile names is a leftover."""
shadowed = sorted(
sys_id for sys_id in systemnames.SYSTEM_NAMES
if systemnames._own_section(sys_id) is not None
if systemnames.own_section(sys_id) is not None
)
self.assertEqual(shadowed, [])
unused = sorted(set(systemnames.SYSTEM_NAMES) - self._all_ids())
@@ -125,7 +125,7 @@ class SectionsComeBeforeThePlan(unittest.TestCase):
from sitegen import build
tree = ast.parse(inspect.getsource(build._generate))
tree = ast.parse(inspect.getsource(build.generate_site))
lines = {}
for node in ast.walk(tree):
if isinstance(node, ast.Call) and isinstance(node.func, ast.Name):
+10 -10
View File
@@ -152,12 +152,12 @@ class SystemLinks(unittest.TestCase):
from model.registry import list_registered_platforms
from model.profiles import load_emulator_profiles
from model.platforms import load_platform_config
from model.collection import _group_by_manufacturer
from model.collection import group_by_manufacturer
from sitegen.systempages import arcade_board_sections
with open("database.json", encoding="utf-8") as handle:
db = json.load(handle)
cls.manufacturers = _group_by_manufacturer(db)
cls.manufacturers = group_by_manufacturer(db)
profiles = load_emulator_profiles("emulators", skip_aliases=False)
systemnames.set_console_sections(
cls.manufacturers, systemnames.program_names(profiles))
@@ -208,7 +208,7 @@ class SystemLinks(unittest.TestCase):
by_heading: dict[str, set[tuple[str, str]]] = {}
for mfr, consoles in self.manufacturers.items():
for console in consoles:
for name in {systemnames._heading_name(mfr, console), console}:
for name in {systemnames.heading_name(mfr, console), console}:
by_heading.setdefault(name.casefold(), set()).add((mfr, console))
missed = []
for sys_id in sorted(self.ids):
@@ -217,7 +217,7 @@ class SystemLinks(unittest.TestCase):
continue
mfr, console = next(iter(places))
if mfr == "Other" or (
mfr == "Arcade" and console.casefold() in systemnames._program_names
mfr == "Arcade" and console.casefold() in systemnames.known_program_names
):
continue
if siterender.system_section(sys_id) is None:
@@ -240,7 +240,7 @@ class SystemLinks(unittest.TestCase):
by_name.setdefault(systemnames.system_name(sys_id), set()).update(sections)
wrong = []
for sys_id, parent in sorted(systemnames.SYSTEM_PARENTS.items()):
if systemnames._own_section(sys_id) is not None:
if systemnames.own_section(sys_id) is not None:
continue
held = by_name.get(systemnames.system_name(sys_id))
if held is not None and parent not in held:
@@ -282,10 +282,10 @@ class SystemLinks(unittest.TestCase):
self.assertNotIn(sys_id, systemnames.SYSTEM_PARENTS)
def test_emulator_rows_link_the_variant(self) -> None:
from sitegen.emulatorcards import _named_system_link
from sitegen.emulatorcards import named_system_link
self.assertEqual(
_named_system_link("wonderswan-color", "../"),
named_system_link("wonderswan-color", "../"),
"[Bandai WonderSwan Color](../systems/bandai.md#wonderswan)")
@@ -327,11 +327,11 @@ class AnEntryListingSystemsIsFiledUnderEach(unittest.TestCase):
from model.profiles import entry_system_ids
entry = {"name": "ym2608.zip", "systems": ["arcade", "pc80"]}
self.assertEqual(consolecards._entry_systems("mame", entry), ["arcade", "pc80"])
self.assertEqual(consolecards.entry_systems("mame", entry), ["arcade", "pc80"])
self.assertEqual(
consolecards._entry_systems("mame", entry), entry_system_ids(entry, {"systems": []})
consolecards.entry_systems("mame", entry), entry_system_ids(entry, {"systems": []})
)
self.assertEqual(consolecards._entry_systems("mame", {"name": "a", "system": "pc80"}), ["pc80"])
self.assertEqual(consolecards.entry_systems("mame", {"name": "a", "system": "pc80"}), ["pc80"])
if __name__ == "__main__":
+56 -56
View File
@@ -109,7 +109,7 @@ class TheConsoleBiosComesFirst(unittest.TestCase):
}, platforms={"6" * 40: {"a", "b"}, "3" * 40: {"a", "b", "c"}})
def names(self) -> list[str]:
cards = consolecards._console_cards("Sony", self.files, self.consumers, set())
cards = consolecards.console_cards("Sony", self.files, self.consumers, set())
return [re.search(r"<code>(.*?)</code>", card[2])[1] for _v, card, _s in cards]
def test_required_then_priority_then_setups_then_name(self):
@@ -121,7 +121,7 @@ class TheConsoleBiosComesFirst(unittest.TestCase):
])
def test_a_console_cut_in_parts_goes_by_name(self):
cards = consolecards._console_cards("Sony", self.files, self.consumers, set(), by_name=True)
cards = consolecards.console_cards("Sony", self.files, self.consumers, set(), by_name=True)
names = [re.search(r"<code>(.*?)</code>", card[2])[1] for _v, card, _s in cards]
self.assertEqual(names, sorted(names, key=str.casefold))
@@ -136,7 +136,7 @@ class TheConsoleBiosComesFirst(unittest.TestCase):
})
def test_the_section_opens_on_the_bios_by_region(self):
lines = startwith._start_with(self.files, self.required_only())
lines = startwith.start_with(self.files, self.required_only())
self.assertEqual(lines[0], "**Start with** the BIOS for the region of the games:")
self.assertIn("- **North America**: [`scph5501.bin`](#sha1-444444444444)", lines)
self.assertIn("- **Japan**: [`scph5500.bin`](#sha1-555555555555)", lines)
@@ -146,7 +146,7 @@ class TheConsoleBiosComesFirst(unittest.TestCase):
def test_regions_needing_the_same_file_share_a_line(self):
consumers = _one_reader_each({"4" * 40: [
{"required": True, "region": ["north-america", "latin-america", "brazil"]}]})
lines = startwith._start_with([_sony_file("scph5501.bin", "4")], consumers)
lines = startwith.start_with([_sony_file("scph5501.bin", "4")], consumers)
# Brazil says nothing Latin America does not.
self.assertIn("- **North America, Latin America**: [`scph5501.bin`](#sha1-444444444444)", lines)
@@ -157,13 +157,13 @@ class TheConsoleBiosComesFirst(unittest.TestCase):
consumers = _one_reader_each({f["sha1"]: [{"required": True}] for f in files})
consumers.emulator_files = {"emu": [{"required": True}] * len(files)}
consumers.emulator_entries = {f["sha1"]: {"emu": i} for i, f in enumerate(files)}
self.assertEqual(startwith._start_with(files, consumers)[0],
self.assertEqual(startwith.start_with(files, consumers)[0],
"**Start with**: [`rom0.bin`](#sha1-aaaaaaaaaaaa), [`rom1.bin`](#sha1-bbbbbbbbbbbb), "
"[`rom2.bin`](#sha1-cccccccccccc) and 5 more files. "
"They come first below.")
def test_no_required_file_no_line(self):
self.assertEqual(startwith._start_with([_sony_file("a.bin", "a")], _one_reader_each({})), [])
self.assertEqual(startwith.start_with([_sony_file("a.bin", "a")], _one_reader_each({})), [])
def test_the_page_carries_the_line_under_the_console(self):
# Sega keeps its consoles as sections. Sony gives each a page.
@@ -178,7 +178,7 @@ class ThePermalinkIsAnIcon(unittest.TestCase):
search showed "scph5501.bin permalink" and screen readers read it."""
def test_no_word_and_out_of_the_search(self):
lines = sitegen_cards._system_file_card(_sony_file("scph5501.bin", "4"), FileConsumers({"files": {}}))
lines = sitegen_cards.system_file_card(_sony_file("scph5501.bin", "4"), FileConsumers({"files": {}}))
title = lines[2]
link = re.search(r'<a class="rb-permalink"[^>]*>(.*?)</a>', title)
self.assertNotIn("permalink", re.sub(r"<[^>]+>", "", title))
@@ -203,7 +203,7 @@ class TheCardGivesTheSizeInBytes(unittest.TestCase):
(2 * 1024 * 1024, "2 MB"), (2304, "2,304 B"), (10, "10 B")):
with self.subTest(size=size):
card = {**_sony_file("scph5501.bin", "4"), "size": size}
title = sitegen_cards._system_file_card(card, FileConsumers({"files": {}}))[2]
title = sitegen_cards.system_file_card(card, FileConsumers({"files": {}}))[2]
self.assertIn(f'<span class="rb-badge rb-badge-muted">{shown}</span>', title)
@@ -219,7 +219,7 @@ class TheCardLinesSayWhatTheyMean(unittest.TestCase):
platform_destinations={sha1: {"batocera": {"scph5501.bin"}}},
installed={sha1: {"retrobat": {"bios/scph5501.bin"}}},
)
self.lines = sitegen_cards._system_file_card(_sony_file("scph5501.bin", "4"), self.consumers)
self.lines = sitegen_cards.system_file_card(_sony_file("scph5501.bin", "4"), self.consumers)
def test_labels_and_display_names(self):
text = "\n".join(self.lines)
@@ -251,7 +251,7 @@ class TheCardLinesSayWhatTheyMean(unittest.TestCase):
self.assertIn("**Packed for its emulators by** names", page)
def test_a_file_nothing_reads_says_so(self):
title = sitegen_cards._system_file_card(_sony_file("GameIndex.yaml", "9"), FileConsumers({"files": {}}))[2]
title = sitegen_cards.system_file_card(_sony_file("GameIndex.yaml", "9"), FileConsumers({"files": {}}))[2]
self.assertIn(">No reader</span>", title)
self.assertNotIn("No reader", self.lines[2])
@@ -263,7 +263,7 @@ class FileFactsAreAGrid(unittest.TestCase):
entry = {**_sony_file("scph5501.bin", "4"), "crc32": "8d8cb7e4",
"provenance": {"redump": {"name": "ps-30a.bin"},
"tosec": {"name": "SCPH-5501 (1996).bin"}}}
lines = sitegen_cards._system_file_card(entry, FileConsumers({"files": {}}))
lines = sitegen_cards.system_file_card(entry, FileConsumers({"files": {}}))
text = "\n".join(lines)
# One value cell after each label, in the open list and in the fold.
facts = re.findall(r"<dt>[^<]*</dt><dd[^>]*>.*?</dd>", text)
@@ -279,7 +279,7 @@ class FileFactsAreAGrid(unittest.TestCase):
self.assertNotRegex(text, r"(?m)^- ")
def test_collection_path_keeps_its_chip(self):
text = "\n".join(sitegen_cards._system_file_card(_sony_file("a.bin", "a"), FileConsumers({"files": {}})))
text = "\n".join(sitegen_cards.system_file_card(_sony_file("a.bin", "a"), FileConsumers({"files": {}})))
self.assertIn("<dt>Collection path</dt><dd><code>bios/Sony/PlayStation/a.bin</code>", text)
@@ -289,15 +289,15 @@ class ConsoleHeadingsStartWithTheName(unittest.TestCase):
altogether."""
def test_no_icon_even_when_one_exists(self):
icon = siterender._icon_name("Sony", "PlayStation")
icon = siterender.console_icon_name("Sony", "PlayStation")
with mock.patch.dict(siterender._icon_available, {icon: True}):
self.assertEqual(startwith._console_heading("Sony", "PlayStation"),
self.assertEqual(startwith.console_heading("Sony", "PlayStation"),
"## PlayStation { #playstation }")
def test_no_icon_no_image(self):
icon = siterender._icon_name("Nobody", "Nothing")
icon = siterender.console_icon_name("Nobody", "Nothing")
with mock.patch.dict(siterender._icon_available, {icon: False}):
self.assertEqual(startwith._console_heading("Nobody", "Nothing"), "## Nothing { #nothing }")
self.assertEqual(startwith.console_heading("Nobody", "Nothing"), "## Nothing { #nothing }")
class TheSystemsIndexListsConsoles(unittest.TestCase):
@@ -424,29 +424,29 @@ class TheSectionStartsWithItsOwnConsole(unittest.TestCase):
})
def test_no_dsi_file_on_the_ds_line(self) -> None:
text = "\n".join(startwith._start_with(self.files, self.consumers, section=DS))
text = "\n".join(startwith.start_with(self.files, self.consumers, section=DS))
self.assertNotIn("dsi", text)
def test_a_console_its_emulators_run_without_says_so(self) -> None:
self.assertEqual(startwith._start_with(self.files, self.consumers, section=DS), [
self.assertEqual(startwith.start_with(self.files, self.consumers, section=DS), [
"**No file needed** with emu-a or emu-b. For full accuracy: "
"[`bios7.bin`](#sha1-777777777777), [`bios9.bin`](#sha1-999999999999).", ""])
def test_the_dsi_section_names_its_file(self) -> None:
lines = startwith._start_with(self.files, self.consumers, section=("Nintendo", "Nintendo DSi"))
lines = startwith.start_with(self.files, self.consumers, section=("Nintendo", "Nintendo DSi"))
self.assertEqual(lines, ["**Start with**: [`dsi_bios7.bin`](#sha1-dddddddddddd).", ""])
def test_more_than_three_emulators_are_counted(self) -> None:
hle = {"required": False, "hle_fallback": True, "system": "nintendo-ds"}
consumers = _consumers_with_db({"7" * 40: [(f"emu-{n}", hle) for n in "abcd"]})
self.assertEqual(startwith._start_with(self.files[:1], consumers, section=DS)[0],
self.assertEqual(startwith.start_with(self.files[:1], consumers, section=DS)[0],
"**No file needed**: none of its 4 emulators requires one. "
"For full accuracy: [`NDS_Bios7.bin`](#sha1-777777777777).")
def test_a_shipped_file_is_no_start(self) -> None:
consumers = _consumers_with_db({"7" * 40: [("emu-a", {"required": True, "bundled": True,
"system": "nintendo-ds"})]})
self.assertEqual(startwith._start_with(self.files[:1], consumers, section=DS), [])
self.assertEqual(startwith.start_with(self.files[:1], consumers, section=DS), [])
class TheNameSetupsWrite(unittest.TestCase):
@@ -457,13 +457,13 @@ class TheNameSetupsWrite(unittest.TestCase):
"system": "nintendo-gba"})]},
destinations={"a" * 40: {"p1": {"gba_bios.bin"}, "p2": {"bios/gba_bios.bin"},
"p3": {"GBA_bios.rom"}}})
self.assertEqual(startwith._start_with([f], consumers, section=("Nintendo", "Game Boy Advance")),
self.assertEqual(startwith.start_with([f], consumers, section=("Nintendo", "Game Boy Advance")),
["**Start with**: [`gba_bios.bin`](#sha1-aaaaaaaaaaaa).", ""])
def test_no_setup_then_the_emulators_name(self) -> None:
f = _file_at("x.rom", "b", "bios/Nintendo/Game Boy Advance/x.rom")
consumers = _consumers_with_db({"b" * 40: [("emu-a", {"name": "gba_bios.bin", "required": True})]})
self.assertEqual(consolecards._setup_name(f, consumers, [("emu-a", {"name": "gba_bios.bin"})]),
self.assertEqual(consolecards.setup_name(f, consumers, [("emu-a", {"name": "gba_bios.bin"})]),
"gba_bios.bin")
@@ -488,14 +488,14 @@ class ArcadeSetsAreNamedWhereverFiled(unittest.TestCase):
}, db_files=[self.aes, neogeo, mega_cd, shader])
def test_the_file_most_emulators_read_leads_and_the_arcade_set_is_linked(self) -> None:
lines = startwith._start_with([self.aes], self.consumers, section=("SNK", "Neo Geo"))
lines = startwith.start_with([self.aes], self.consumers, section=("SNK", "Neo Geo"))
link = f"[`neogeo.zip`](/retrobios/files/?sha1={'2' * 40})"
self.assertEqual(lines[0], f"**Start with** {link}. Keep it zipped. "
"mame0, mame1 and mame2 read it.")
self.assertIn("Geolith reads [`aes.zip`](#sha1-111111111111) instead.", lines)
def test_another_consoles_file_or_an_emulators_folder_is_left_out(self) -> None:
text = "\n".join(startwith._start_with([self.aes], self.consumers, section=("SNK", "Neo Geo")))
text = "\n".join(startwith.start_with([self.aes], self.consumers, section=("SNK", "Neo Geo")))
self.assertNotIn("bios_CD_U.bin", text)
self.assertNotIn("tfx.glsl", text)
@@ -506,14 +506,14 @@ class ArcadeSetsAreNamedWhereverFiled(unittest.TestCase):
"1" * 40: [("geolith", {"required": True})],
"5" * 40: [(f"emu{n}", {"required": True}) for n in range(3)],
})
cards = consolecards._console_cards("SNK", [one, many], consumers, set())
cards = consolecards.console_cards("SNK", [one, many], consumers, set())
self.assertIn("sp-s3.sp1", cards[0][1][2])
def test_a_long_list_names_the_first_files(self) -> None:
files = [_file_at(f"rom{i}.bin", "abcdefgh"[i], f"bios/SNK/Neo Geo/rom{i}.bin")
for i in range(8)]
consumers = _consumers_with_db({f["sha1"]: [("emu", {"required": True})] for f in files})
self.assertEqual(startwith._start_with(files, consumers, first_below=False)[0],
self.assertEqual(startwith.start_with(files, consumers, first_below=False)[0],
"**Start with**: [`rom0.bin`](#sha1-aaaaaaaaaaaa), [`rom1.bin`](#sha1-bbbbbbbbbbbb), "
"[`rom2.bin`](#sha1-cccccccccccc) and 5 more files.")
@@ -537,10 +537,10 @@ class CardsSayWhichReleaseTheSetMatches(unittest.TestCase):
def card(self) -> str:
f = {"name": "set.zip", "sha1": "e" * 40, "md5": "e" * 32, "size": 4,
"path": str(self.path)}
with mock.patch.object(sitegen_cards, "_romset_releases", return_value=self.releases), \
mock.patch.object(consolecards, "_romset_releases", return_value=self.releases), \
mock.patch.object(startwith, "_romset_releases", return_value=self.releases):
return "\n".join(sitegen_cards._system_file_card(f, _consumers_with_db({})))
with mock.patch.object(sitegen_cards, "romset_releases", return_value=self.releases), \
mock.patch.object(consolecards, "romset_releases", return_value=self.releases), \
mock.patch.object(startwith, "romset_releases", return_value=self.releases):
return "\n".join(sitegen_cards.system_file_card(f, _consumers_with_db({})))
def test_the_matching_releases_as_runs(self) -> None:
self.assertIn("<dt>Romset</dt><dd>Same contents as MAME 0.190 to 0.195, 0.220 and "
@@ -560,9 +560,9 @@ class CardsSayWhichReleaseTheSetMatches(unittest.TestCase):
def test_a_page_of_sets_links_the_version_answer(self) -> None:
f = {"name": "set.zip", "sha1": "e" * 40, "path": "bios/SNK/Neo Geo/set.zip"}
with mock.patch.object(sitegen_cards, "_romset_releases", return_value=self.releases), \
mock.patch.object(consolecards, "_romset_releases", return_value=self.releases), \
mock.patch.object(startwith, "_romset_releases", return_value=self.releases):
with mock.patch.object(sitegen_cards, "romset_releases", return_value=self.releases), \
mock.patch.object(consolecards, "romset_releases", return_value=self.releases), \
mock.patch.object(startwith, "romset_releases", return_value=self.releases):
page = systempages.generate_system_page("SNK", {"Neo Geo": [f]}, _consumers_with_db({}))
self.assertIn("MAME and FBNeo sets must match the emulator's version. [Which version "
f"each core reads]({sitegen_cards.ROMSET_FAQ}).", page)
@@ -657,8 +657,8 @@ class InstallBoxesCountTowardTheSummary(unittest.TestCase):
def install(console: str, _declared: list) -> list[str]:
return ["x" * box] if console == "Boxed" else []
with mock.patch.object(sitegen_install, "_console_install_block", side_effect=install), \
mock.patch.object(systempages, "_console_install_block", side_effect=install), \
with mock.patch.object(sitegen_install, "console_install_block", side_effect=install), \
mock.patch.object(systempages, "console_install_block", side_effect=install), \
mock.patch.object(consolecards, "SYSTEM_SUMMARY_HTML", 50_000), \
mock.patch.object(systempages, "SYSTEM_SUMMARY_HTML", 50_000):
return systempages.system_pages("Maker", self.consoles, _consumers_with_db({}), budget=30_000)
@@ -724,7 +724,7 @@ class AFileFewRequireIsNoStartFile(unittest.TestCase):
consumers = _consumers_by_system({"1" * 40: [
("emux_gb", {"name": "dmg_boot.bin", "required": True}),
("gambatte", optional), ("mgba", optional), ("sameboy", optional)]})
line = _unlinked(startwith._start_with([boot], consumers)[0])
line = _unlinked(startwith.start_with([boot], consumers)[0])
self.assertTrue(line.startswith("**No file needed** with "), line)
self.assertRegex(line, r"Only \S.* requires `dmg_boot.bin`\.$")
@@ -733,14 +733,14 @@ class AFileFewRequireIsNoStartFile(unittest.TestCase):
required = {"name": "scph5501.bin", "required": True}
consumers = _consumers_by_system({"2" * 40: [
("a", required), ("b", required), ("c", {"required": False, "hle_fallback": True})]})
self.assertEqual(_unlinked(startwith._start_with([bios], consumers)[0]), "**Start with**: `scph5501.bin`.")
self.assertEqual(_unlinked(startwith.start_with([bios], consumers)[0]), "**Start with**: `scph5501.bin`.")
def test_an_entry_read_for_a_system_with_no_section_is_dropped(self) -> None:
sample = _game_boy_file("ym2608_adpcm_rom.bin", "3", "bios/Nintendo/NES/ym2608_adpcm_rom.bin")
consumers = _consumers_by_system({"3" * 40: [
("fbneo", {"name": "ym2608_adpcm_rom.bin", "required": True,
"system": "no-such-system-anywhere"})]})
self.assertEqual(startwith._start_with([sample], consumers, section=("Nintendo", "NES")), [])
self.assertEqual(startwith.start_with([sample], consumers, section=("Nintendo", "NES")), [])
def test_the_home_usually_not_consoles_open_on_no_file_needed(self) -> None:
home = _built_page(DIST / "index.html")
@@ -782,11 +782,11 @@ class TheNeoGeoOpensOnItsSet(unittest.TestCase):
"5" * 40: [("ares", {"name": "neo-epo.sp1", "required": True,
"system": "snk-neogeo"})],
})
lines = [_unlinked(line) for line in startwith._start_with([neogeo, epo], consumers, section=("SNK", "Neo Geo"))]
lines = [_unlinked(line) for line in startwith.start_with([neogeo, epo], consumers, section=("SNK", "Neo Geo"))]
self.assertTrue(lines[0].startswith("**Start with** `neogeo.zip`. Keep it zipped. "))
self.assertIn("ares reads `neo-epo.sp1` instead.", lines)
cards = consolecards._console_cards("SNK", [epo, neogeo], consumers, set(),
start=startwith._start_order([neogeo, epo], consumers,
cards = consolecards.console_cards("SNK", [epo, neogeo], consumers, set(),
start=startwith.start_order([neogeo, epo], consumers,
("SNK", "Neo Geo")))
self.assertIn("neogeo.zip", cards[0][1][2])
@@ -794,7 +794,7 @@ class TheNeoGeoOpensOnItsSet(unittest.TestCase):
consumers = _consumers_by_system({}, systems={"a" * 40: {"retroarch": {"arcade"}}})
pairs = systempages._install_pairs([("batocera", "snk-neogeo")], "a" * 40, consumers)
self.assertIn(("retroarch", "arcade"), pairs)
block = "\n".join(sitegen_install._console_install_block("Neo Geo", pairs))
block = "\n".join(sitegen_install.console_install_block("Neo Geo", pairs))
self.assertIn("<li>RetroArch: <code", block)
self.assertIn("--platform retroarch --system arcade</code>", block)
@@ -852,7 +852,7 @@ class CardsNameEmulatorsByName(unittest.TestCase):
def test_no_built_card_link_reads_an_id(self) -> None:
if not (DIST / "systems").is_dir():
self.skipTest("site not built")
profiles = collection._profiles_on_disk()
profiles = collection.profiles_on_disk()
bad = set()
for page in (DIST / "systems").glob("*/index.html"):
for emulator, text in re.findall(
@@ -892,7 +892,7 @@ class PartPagesKnowWhereTheyAre(unittest.TestCase):
for i in range(10)]
consumers = _consumers_by_system({})
with sitegen.markup.using("mkdocs"):
one = sum(len(line) + 1 for line in sitegen_cards._system_file_card(files[0], consumers))
one = sum(len(line) + 1 for line in sitegen_cards.system_file_card(files[0], consumers))
pages = systempages.system_pages("Sony", {"PlayStation 2": files}, consumers, budget=one * 7)
parts = [stem for stem in pages if stem != "sony"]
self.assertEqual(len(parts), 2)
@@ -925,7 +925,7 @@ class ConsolesFieldNamesMachinesOnce(unittest.TestCase):
def test_no_emulator_folder_is_a_console(self) -> None:
for maker in ("Other", "Game Engines"):
page = systempages.system_pages(maker, {"dolphin": [_game_boy_file("a.bin", "a")]}, _consumers_by_system({}))
self.assertEqual(_consoles(page[collection._slug(maker)][0]), [], maker)
self.assertEqual(_consoles(page[collection.manufacturer_slug(maker)][0]), [], maker)
def test_a_console_with_its_own_page_is_left_to_it(self) -> None:
big = [_game_boy_file(f"r{i:02}.bin", "0123456789"[i], f"bios/Sega/Saturn/r{i:02}.bin")
@@ -933,7 +933,7 @@ class ConsolesFieldNamesMachinesOnce(unittest.TestCase):
small = [_game_boy_file("pico.bin", "p", "bios/Sega/Pico/pico.bin")]
consumers = _consumers_by_system({})
with sitegen.markup.using("mkdocs"):
one = sum(len(line) + 1 for line in sitegen_cards._system_file_card(big[0], consumers))
one = sum(len(line) + 1 for line in sitegen_cards.system_file_card(big[0], consumers))
# Sega splits by size. Every Sony console has a page whatever its size.
pages = systempages.system_pages("Sega", {"Saturn": big, "Pico": small},
consumers, budget=one * 12)
@@ -1040,7 +1040,7 @@ class AStartFileIsNoOnesExtra(unittest.TestCase):
"1" * 40: [(e, {"name": "naomi.zip", "required": True}) for e, _ in both + extra],
"2" * 40: both + extra,
})
self.assertEqual([_unlinked(line) for line in startwith._start_with([naomi, hod2], consumers)],
self.assertEqual([_unlinked(line) for line in startwith.start_with([naomi, hod2], consumers)],
["**Start with**: `naomi.zip`.", ""])
def test_the_naomi_page_opens_on_naomi_zip(self) -> None:
@@ -1052,7 +1052,7 @@ class AStartFileIsNoOnesExtra(unittest.TestCase):
"3" * 40: [(e, {"name": "bios7.bin", "required": True}) for e in ("a", "b")],
"4" * 40: [(e, {"name": "bios9.bin", "required": True}) for e in ("a", "b")],
})
self.assertEqual(_unlinked(startwith._start_with([bios7, bios9], consumers)[0]),
self.assertEqual(_unlinked(startwith.start_with([bios7, bios9], consumers)[0]),
"**Start with**: `bios7.bin`, `bios9.bin`.")
def test_some_files_each_is_not_every_file_for_one(self) -> None:
@@ -1064,7 +1064,7 @@ class AStartFileIsNoOnesExtra(unittest.TestCase):
reads["1" * 40].append(("bsnes", {"name": "chip1.rom", "required": True}))
reads["2" * 40].append(("jgenesis", {"name": "chip2.rom", "required": True}))
reads["3" * 40].append(("jgenesis", {"name": "chip3.rom", "required": True}))
line = startwith._start_with(files, _consumers(reads))[0]
line = startwith.start_with(files, _consumers(reads))[0]
self.assertIn("require some of these files: ", line)
@@ -1078,7 +1078,7 @@ class OtherNamesForOneSlotReadAsAlternatives(unittest.TestCase):
for e in ("mesen", "nestopia", "fceumm")],
"6" * 40: [("fbneo", {"name": "fdsbios.zip", "required": True})],
})
self.assertEqual(_unlinked(startwith._start_with([disk, fds], consumers)[0]),
self.assertEqual(_unlinked(startwith.start_with([disk, fds], consumers)[0]),
"**Start with**: `disksys.rom`. FinalBurn Neo reads `fdsbios.zip` instead.")
def test_a_card_read_under_another_name_says_both(self) -> None:
@@ -1088,7 +1088,7 @@ class OtherNamesForOneSlotReadAsAlternatives(unittest.TestCase):
"7" * 40: [("c", {"name": "short.rom", "required": True})],
})
self.assertIn("reads `long name (1986).bin` (as `short.rom`) instead.",
_unlinked(startwith._start_with([disk, card], consumers)[0]))
_unlinked(startwith.start_with([disk, card], consumers)[0]))
def test_a_regional_line_names_one_file_per_reader(self) -> None:
mega_cd = _system_page("sega").split("{ #mega-cd }", 1)[1].split("\n## ", 1)[0]
@@ -1239,9 +1239,9 @@ class OneLabelOnceOnABoardPage(unittest.TestCase):
"""6.7, 6.8, 6.9, 6.10: the words a board or part page repeats."""
def test_a_label_naming_files_installs_these_files(self) -> None:
block = "\n".join(sitegen_install._console_install_block("Other arcade files", [("mame", "arcade")]))
block = "\n".join(sitegen_install.console_install_block("Other arcade files", [("mame", "arcade")]))
self.assertIn("<summary>Install these files</summary>", block)
block = "\n".join(sitegen_install._console_install_block("Sega NAOMI", [("mame", "arcade")]))
block = "\n".join(sitegen_install.console_install_block("Sega NAOMI", [("mame", "arcade")]))
self.assertIn("<summary>Install the files of Sega NAOMI</summary>", block)
def test_a_board_page_has_no_heading_of_its_name(self) -> None:
@@ -1275,12 +1275,12 @@ class EachFileDownloadsFromItsCard(unittest.TestCase):
from packs.crossref import FileConsumers
f = _naomi_file("apple2-asoft-auto.rom", "3", "bios/Apple/Apple II/apple2-asoft-auto.rom")
title = next(line for line in sitegen_cards._system_file_card(f, FileConsumers({"files": {}}))
title = next(line for line in sitegen_cards.system_file_card(f, FileConsumers({"files": {}}))
if "rb-file-title" in line)
self.assertIn('class="rb-download" href="https://raw.githubusercontent.com/Abdess/'
'retrobios/main/bios/Apple/Apple%20II/apple2-asoft-auto.rom"', title)
self.assertIn('aria-label="Download apple2-asoft-auto.rom"', title)
facts = "\n".join(sitegen_cards._system_file_card(f, FileConsumers({"files": {}})))
facts = "\n".join(sitegen_cards.system_file_card(f, FileConsumers({"files": {}})))
self.assertNotIn("(download)", facts)
def test_a_start_name_leads_to_its_card(self) -> None:
+10 -10
View File
@@ -39,20 +39,20 @@ class ProsePlaceholders(unittest.TestCase):
"""A path written with angle brackets reaches the reader as written."""
def test_a_placeholder_is_text_not_a_tag(self):
from sitegen.render import _admonition_body, _escape_tags
from sitegen.render import admonition_body, escape_tags
self.assertEqual(
_escape_tags("gameProfiles/<title id>.ini under <system_dir>/Cemu"),
escape_tags("gameProfiles/<title id>.ini under <system_dir>/Cemu"),
"gameProfiles/&lt;title id>.ini under &lt;system_dir>/Cemu",
)
self.assertIn("&lt;title id>", _admonition_body("read <title id>.ini"))
self.assertIn("&lt;title id>", admonition_body("read <title id>.ini"))
def test_code_spans_and_links_are_left_alone(self):
from sitegen.render import _escape_tags
from sitegen.render import escape_tags
self.assertEqual(_escape_tags("`<system_dir>/x`"), "`<system_dir>/x`")
self.assertEqual(_escape_tags("see <https://example.org/a>"), "see <https://example.org/a>")
self.assertEqual(_escape_tags("size < 4096"), "size &lt; 4096")
self.assertEqual(escape_tags("`<system_dir>/x`"), "`<system_dir>/x`")
self.assertEqual(escape_tags("see <https://example.org/a>"), "see <https://example.org/a>")
self.assertEqual(escape_tags("size < 4096"), "size &lt; 4096")
class WikiSourceHeadings(unittest.TestCase):
@@ -94,7 +94,7 @@ class PlatformDetails(unittest.TestCase):
def test_lists_and_flags_read_as_prose(self):
from sitegen import fields
lines = fields._render_platform_details(
lines = fields.render_platform_details(
{"platform_details": {"megacd": {
"extensions_tried": [".bin", ".zip"],
"hle_available": False,
@@ -362,9 +362,9 @@ class TheSitemapIsAnnouncedWhereCrawlersLook(unittest.TestCase):
class TheHomeTitleSaysWhatTheSiteIs(unittest.TestCase):
def test_not_the_site_name_twice(self):
from sitegen.config import SITE_NAME
from sitegen.descriptions import _browser_title
from sitegen.descriptions import page_browser_title
title = _browser_title(Path("index.md"), SITE_NAME)
title = page_browser_title(Path("index.md"), SITE_NAME)
self.assertNotEqual(title, SITE_NAME)
self.assertIn("BIOS", title)
+1 -1
View File
@@ -121,7 +121,7 @@ class APlatformSystemOverItsBudgetMoves(unittest.TestCase):
budget = platformfiles.PLATFORM_SECTION_BUDGET
platformfiles.PLATFORM_SECTION_BUDGET = 5
try:
lines = platformfiles._render_platform_systems(
lines = platformfiles.render_platform_systems(
{"arcade": files}, config, {}, ("deck", "Deck"), moved)
finally:
platformfiles.PLATFORM_SECTION_BUDGET = budget
+15 -15
View File
@@ -31,15 +31,15 @@ FRONT = (
class Undecorate(unittest.TestCase):
def test_it_removes_front_matter_and_structured_data(self):
self.assertEqual(sitewrite._undecorated(FRONT + BODY), BODY)
self.assertEqual(sitewrite.undecorated(FRONT + BODY), BODY)
def test_a_plain_body_is_returned_unchanged(self):
self.assertEqual(sitewrite._undecorated(BODY), BODY)
self.assertEqual(sitewrite.undecorated(BODY), BODY)
def test_front_matter_this_build_did_not_write_is_left_alone(self):
"""A hand-maintained page with its own front matter is not ours."""
foreign = '---\ntitle: "Hand written"\n---\n\nBody.\n'
self.assertEqual(sitewrite._undecorated(foreign), foreign)
self.assertEqual(sitewrite.undecorated(foreign), foreign)
class TwoPassWriting(unittest.TestCase):
@@ -105,12 +105,12 @@ class Sweep(unittest.TestCase):
def _produce(self, *relatives: str) -> None:
for relative in relatives:
sitewrite._record(self.docs / relative)
sitewrite.record_written(self.docs / relative)
def test_it_removes_only_what_nothing_produced(self):
self._produce("emulators/kept.md", "emulators/nested/deep.md",
"platforms/kept.md")
removed = sitewrite._sweep_generated(self.docs, ["emulators", "platforms"])
removed = sitewrite.sweep_generated(self.docs, ["emulators", "platforms"])
self.assertEqual(removed, 1)
self.assertFalse((self.docs / "emulators/stale.md").exists())
self.assertTrue((self.docs / "emulators/kept.md").exists())
@@ -123,10 +123,10 @@ class Sweep(unittest.TestCase):
(self.docs / "platforms/kept.mdx").write_text("x")
(self.docs / "platforms/gone.mdx").write_text("x")
self._produce("platforms/kept.md")
sitewrite._sweep_generated(self.docs, ["platforms"])
sitewrite.sweep_generated(self.docs, ["platforms"])
(self.docs / "top.mdx").write_text("x")
sitewrite._record(self.docs / "top.md")
self.assertEqual(sitewrite._sweep_top_pages(self.docs), 0)
sitewrite.record_written(self.docs / "top.md")
self.assertEqual(sitewrite.sweep_top_pages(self.docs), 0)
self.assertTrue((self.docs / "platforms/kept.mdx").exists())
self.assertTrue((self.docs / "top.mdx").exists())
self.assertFalse((self.docs / "platforms/gone.mdx").exists())
@@ -134,22 +134,22 @@ class Sweep(unittest.TestCase):
def test_a_directory_outside_the_list_is_never_touched(self):
self._produce("emulators/kept.md", "emulators/nested/deep.md",
"emulators/stale.md")
sitewrite._sweep_generated(self.docs, ["emulators"])
sitewrite.sweep_generated(self.docs, ["emulators"])
self.assertTrue((self.docs / "untouched/manual.md").exists())
self.assertTrue((self.docs / "platforms/kept.md").exists())
def test_an_emptied_directory_is_pruned(self):
self._produce("emulators/kept.md", "emulators/stale.md")
sitewrite._sweep_generated(self.docs, ["emulators"])
sitewrite.sweep_generated(self.docs, ["emulators"])
self.assertFalse((self.docs / "emulators/nested").exists())
self.assertTrue((self.docs / "emulators").is_dir())
def test_a_missing_directory_is_not_an_error(self):
self.assertEqual(sitewrite._sweep_generated(self.docs, ["absent"]), 0)
self.assertEqual(sitewrite.sweep_generated(self.docs, ["absent"]), 0)
def test_producing_nothing_empties_the_generated_tree(self):
"""The wipe this replaced, reached only when the build produced nothing."""
removed = sitewrite._sweep_generated(self.docs, ["emulators"])
removed = sitewrite.sweep_generated(self.docs, ["emulators"])
self.assertEqual(removed, 3)
self.assertTrue((self.docs / "untouched/manual.md").exists())
@@ -161,12 +161,12 @@ class Sweep(unittest.TestCase):
removes it.
"""
self._produce("emulators/kept.md")
sitewrite._sweep_generated(self.docs, ["emulators"])
sitewrite.sweep_generated(self.docs, ["emulators"])
survivors = {p.name for p in (self.docs / "emulators").rglob("*")
if p.is_file()}
self.assertEqual(survivors, {"kept.md"})
(self.docs / "emulators" / "kept.md").write_text("y")
self.assertEqual(sitewrite._sweep_generated(self.docs, ["emulators"]), 0)
self.assertEqual(sitewrite.sweep_generated(self.docs, ["emulators"]), 0)
def test_a_root_page_nothing_produced_is_removed(self):
"""cross-reference-misterfpga.md outlived the table it held and kept
@@ -174,7 +174,7 @@ class Sweep(unittest.TestCase):
for name in ("cross-reference.md", "cross-reference-misterfpga.md", "which-pack.mdx"):
(self.docs / name).write_text("x")
self._produce("cross-reference.md", "which-pack.mdx")
self.assertEqual(sitewrite._sweep_top_pages(self.docs), 1)
self.assertEqual(sitewrite.sweep_top_pages(self.docs), 1)
self.assertFalse((self.docs / "cross-reference-misterfpga.md").exists())
self.assertTrue((self.docs / "cross-reference.md").exists())
self.assertTrue((self.docs / "which-pack.mdx").exists())
+3 -3
View File
@@ -475,7 +475,7 @@ class TheStrongestProofTakesAnUndeclaredPath(unittest.TestCase):
path, whatever the proof, and mame2015 received another revision."""
def test_a_held_hash_beats_a_bare_name_whatever_the_order(self):
from packs.extras import _collect_emulator_extras
from packs.extras import collect_emulator_extras
config = {
"platform": "P", "verification_mode": "existence",
@@ -488,7 +488,7 @@ class TheStrongestProofTakesAnUndeclaredPath(unittest.TestCase):
"zzz": {"emulator": "Zzz", "type": "libretro", "systems": ["console"],
"files": [{"name": "IPL.bin", "required": True, "md5": "n" * 32}]},
}
extras = _collect_emulator_extras(config, "", REGIONS_DB, set(), "", profiles)
extras = collect_emulator_extras(config, "", REGIONS_DB, set(), "", profiles)
winner = next(e for e in extras if e["destination"] == "IPL.bin")
self.assertEqual(winner["source_profile"], "zzz")
self.assertEqual({c["source_profile"] for c in winner["other_claims"]}, {"aaa"})
@@ -949,7 +949,7 @@ class SlotsJudgeWhatVerifyJudged(unittest.TestCase):
class ARecordIsFoundByItsPathOnce(unittest.TestCase):
"""_accepted_by_all walked all 19 000 records for every path asked."""
"""accepted_by_all walked all 19 000 records for every path asked."""
def test_the_files_are_walked_once(self):
from resolve import collisions as resolve_collisions
+3 -3
View File
@@ -44,7 +44,7 @@ class BinaryContinuationsAreNotLinked(unittest.TestCase):
original = sources._tree_paths
sources._tree_paths = lambda repo, pin: frozenset({"FPLoader.cpp"})
try:
return sources._source_ref_markdown(self.PROFILE, value)
return sources.source_ref_markdown(self.PROFILE, value)
finally:
sources._tree_paths = original
@@ -77,7 +77,7 @@ class ForgejoTreesArePaged(unittest.TestCase):
page = int(url.rsplit("&page=", 1)[1]) if "&page=" in url else 1
return {"tree": pages.get(page, []), "truncated": True, "total_count": 1002}
with mock.patch.object(upstream, "_api", side_effect=fake_api):
with mock.patch.object(upstream, "cached_api", side_effect=fake_api):
paths, truncated = upstream.list_tree(repo, "7" * 40, "unused")
self.assertFalse(truncated)
self.assertEqual(len(paths), 1001)
@@ -86,7 +86,7 @@ class ForgejoTreesArePaged(unittest.TestCase):
def test_a_github_truncation_stays_final(self):
repo = upstream.parse_repo("https://github.com/o/r")
payload = {"tree": [{"type": "blob", "path": "x"}], "truncated": True}
with mock.patch.object(upstream, "_api", return_value=payload) as api:
with mock.patch.object(upstream, "cached_api", return_value=payload) as api:
paths, truncated = upstream.list_tree(repo, "7" * 40, "unused")
self.assertTrue(truncated)
self.assertEqual(api.call_count, 1)
+3 -3
View File
@@ -231,7 +231,7 @@ class PartsAreNotTakenForPacks(SplitFixture):
"""A part holds half a platform by design: judged as a pack it fails."""
parts = packs_parts.split_pack(self.pack, limit=LIMIT)
self.assertEqual(
naming._pack_archives(str(self.dist)), [],
naming.pack_archives(str(self.dist)), [],
[p.name for p in parts],
)
@@ -242,11 +242,11 @@ class PartsAreNotTakenForPacks(SplitFixture):
for name in ("RetroBIOS.zip", "RetroBIOS-tools.zip", "RetroBIOS-batocera.zip"):
self._build(self.dist / name, {"RetroBIOS.sh": b"#!/bin/sh\n"})
before = {p.name: p.read_bytes() for p in self.dist.glob("RetroBIOS*.zip")}
self.assertEqual(naming._pack_archives(str(self.dist)), [self.pack.name])
self.assertEqual(naming.pack_archives(str(self.dist)), [self.pack.name])
# A --system platform pack carries its system after the suffix.
system = self.dist / "Demo_1.0_BIOS_Pack_Playstation.zip"
self._build(system, {"one.bin": b"1"})
self.assertEqual(naming._pack_archives(str(self.dist)),
self.assertEqual(naming.pack_archives(str(self.dist)),
sorted([self.pack.name, system.name]))
system.unlink()
with contextlib.redirect_stdout(io.StringIO()):
+8 -8
View File
@@ -14,7 +14,7 @@ import tests
import unittest
from pathlib import Path
from model.systems import SYSTEM_ALIASES, _norm_system_id
from model.systems import SYSTEM_ALIASES, norm_system_id
from model.profiles import load_emulator_profiles
from packs.extras import _names_content, _slug_for
@@ -64,26 +64,26 @@ class PlatformNamesReachTheProfileSystem(unittest.TestCase):
unmet = [
f"{name} -> {emulator}"
for name, emulator in self.PAIRS
if _norm_system_id(name)
not in {_norm_system_id(str(s)) for s in profiles[emulator].get("systems", [])}
if norm_system_id(name)
not in {norm_system_id(str(s)) for s in profiles[emulator].get("systems", [])}
]
self.assertEqual(unmet, [])
def test_both_spellings_normalize_alike(self):
for alias, canonical in SYSTEM_ALIASES.items():
with self.subTest(alias=alias):
self.assertEqual(_norm_system_id(alias), _norm_system_id(canonical))
self.assertEqual(norm_system_id(alias), norm_system_id(canonical))
def test_each_id_is_normalized_once(self):
"""A manifest run asked 1.7 million times for about a thousand ids,
1.5 seconds of prefix loops: the answer is kept per id."""
_norm_system_id.cache_clear()
norm_system_id.cache_clear()
for _ in range(3):
_norm_system_id("Nintendo_WiiU")
info = _norm_system_id.cache_info()
norm_system_id("Nintendo_WiiU")
info = norm_system_id.cache_info()
self.assertEqual((info.misses, info.hits), (1, 2))
self.assertEqual(
_norm_system_id("Nintendo_WiiU"), _norm_system_id.__wrapped__("Nintendo_WiiU")
norm_system_id("Nintendo_WiiU"), norm_system_id.__wrapped__("Nintendo_WiiU")
)
+8 -8
View File
@@ -24,7 +24,7 @@ from core.cli import suggest_names
from model.cliargs import list_system_ids
from model.database import load_database
from model.platforms import load_platform_config
from model.profiles import _emulator_profiles_cache, load_emulator_profiles, profiles_for_systems
from model.profiles import emulator_profiles_cache, load_emulator_profiles, profiles_for_systems
from packs import archive
from packs import emulatorpack
from packs import md5pack
@@ -44,9 +44,9 @@ class SpellingsAgree(unittest.TestCase):
def test_the_pack_name_normalizes_the_spelling(self):
self.assertEqual(
emulatorpack._system_display_name("atari_2600"), emulatorpack._system_display_name("atari-2600")
emulatorpack.system_display_name("atari_2600"), emulatorpack.system_display_name("atari-2600")
)
self.assertEqual(emulatorpack._system_display_name("msxturboR"), emulatorpack._system_display_name("msxturbor"))
self.assertEqual(emulatorpack.system_display_name("msxturboR"), emulatorpack.system_display_name("msxturbor"))
class TheListingCountsLikeTheSelection(unittest.TestCase):
@@ -73,8 +73,8 @@ class StandaloneNeedsAStandaloneBuild(unittest.TestCase):
Path(tmp, "emulators", "handy.yml").write_text(
"emulator: Handy\ntype: libretro\nsystems: [atari-lynx]\nfiles:\n - name: lynxboot.img\n"
)
_emulator_profiles_cache.clear()
self.addCleanup(_emulator_profiles_cache.clear)
emulator_profiles_cache.clear()
self.addCleanup(emulator_profiles_cache.clear)
db = {"files": {}, "indexes": {"by_md5": {}, "by_crc32": {}, "by_name": {}}}
result = md5pack.generate_md5_pack(
[("md5", "d8f1206299c48946e6ec5ef96d014eaa")], db, tmp, tmp,
@@ -393,7 +393,7 @@ class TheCopyKeepsTheCheckoutOutOfReach(unittest.TestCase):
checkout = scratch_checkout()
proc = subprocess.run(
[sys.executable, "-c", "import sys; sys.path.insert(0, 'scripts'); "
"from sitegen import config; print(config._REPO_ROOT)"],
"from core.paths import REPO_ROOT; print(REPO_ROOT)"],
capture_output=True, text=True, cwd=str(checkout), timeout=300, check=True,
)
self.assertEqual(Path(proc.stdout.strip()), checkout.resolve())
@@ -631,7 +631,7 @@ class ASystemPackHoldsThatSystem(unittest.TestCase):
import yaml
from packs.emulatorcheck import verify_system
_emulator_profiles_cache.clear()
emulator_profiles_cache.clear()
(REPO_ROOT / "tmp").mkdir(exist_ok=True)
root = Path(tempfile.mkdtemp(dir=REPO_ROOT / "tmp"))
self.addCleanup(shutil.rmtree, root, True)
@@ -685,7 +685,7 @@ class ATreeHoldsAPathForAnotherProfile(unittest.TestCase):
import yaml
from packs.emulatorcheck import verify_emulator
_emulator_profiles_cache.clear()
emulator_profiles_cache.clear()
(REPO_ROOT / "tmp").mkdir(exist_ok=True)
root = Path(tempfile.mkdtemp(dir=REPO_ROOT / "tmp"))
self.addCleanup(shutil.rmtree, root, True)
+2 -2
View File
@@ -120,14 +120,14 @@ class EachPlatformNamesTheTargetItsOwnWay(unittest.TestCase):
platforms_dir = str(REPO_ROOT / "platforms")
with contextlib.redirect_stdout(io.StringIO()):
expected = naming._expected_pack_names(
expected = naming.expected_pack_names(
["batocera", "recalbox"], platforms_dir, None, "rpi4"
)
self.assertTrue(any("_Bcm2711_" in name for name in expected["batocera"]))
self.assertTrue(any("_Rpi464_" in name for name in expected["recalbox"]))
for platform, tag in (("batocera", "bcm2711"), ("recalbox", "rpi4_64")):
self.assertEqual(
naming._platform_target(platform, "rpi4", platforms_dir), tag
naming.platform_target(platform, "rpi4", platforms_dir), tag
)
def test_no_naming_site_reads_the_typed_target(self):
+1 -1
View File
@@ -367,7 +367,7 @@ class DownloadedCoresReachTheirBoards(unittest.TestCase):
from packs import manifestcores
core_names = {"amiberry": [], "higan_sfc_balanced": ["nside_sfc_balanced"]}
boards = manifestcores._downloaded_cores(
boards = manifestcores.downloaded_cores(
self.config, self.profiles, core_names, str(REPO_ROOT / "platforms"))
self.assertEqual(set(boards), {"amiberry", "higan_sfc_balanced"})
self.assertIn("x86_64", boards["amiberry"])
+9 -9
View File
@@ -49,13 +49,13 @@ class ANameClaimsOnlyANarrowingThatHappened(unittest.TestCase):
on switch'."""
def test_a_platform_without_the_target_is_named_plainly(self):
from packs.naming import _narrowings, _platform_target
from packs.naming import pack_narrowings, platform_target
platforms = str(REPO_ROOT / "platforms")
self.assertIsNone(_platform_target("bizhawk", "switch", platforms))
self.assertEqual(_narrowings("full", None, None, False, False), [])
self.assertIsNone(platform_target("bizhawk", "switch", platforms))
self.assertEqual(pack_narrowings("full", None, None, False, False), [])
self.assertEqual(
_platform_target("retroarch", "nx", platforms), "nintendo-switch"
platform_target("retroarch", "nx", platforms), "nintendo-switch"
)
@@ -151,8 +151,8 @@ class ASplitBuildsOnlyTheTargetsSystems(unittest.TestCase):
with tempfile.TemporaryDirectory(dir=REPO_ROOT / "tmp") as out, \
mock.patch.object(platformpack, "generate_pack", record), \
mock.patch.object(platformpack, "_collect_emulator_extras", return_value=[]), \
mock.patch.object(manifest, "_collect_emulator_extras", return_value=[]):
mock.patch.object(platformpack, "collect_emulator_extras", return_value=[]), \
mock.patch.object(manifest, "collect_emulator_extras", return_value=[]):
packs_platformpack.generate_split_packs(
"retroarch", platforms, {"files": {}}, "bios", out,
emu_profiles=profiles,
@@ -215,12 +215,12 @@ class TheSplitDirectoryReadsThePackStem(unittest.TestCase):
mock.patch.object(naming, "load_platform_config", return_value=config), \
mock.patch.object(manifest, "load_platform_config", return_value=config), \
mock.patch.object(md5pack, "load_platform_config", return_value=config), \
mock.patch.object(packs_platformpack, "_collect_emulator_extras", return_value=[]), \
mock.patch.object(manifest, "_collect_emulator_extras", return_value=[]):
mock.patch.object(packs_platformpack, "collect_emulator_extras", return_value=[]), \
mock.patch.object(manifest, "collect_emulator_extras", return_value=[]):
packs_platformpack.generate_split_packs(
"foo", "platforms", {"files": {}}, "bios", out, emu_profiles={},
)
stem = naming._platform_pack_stem(["foo"], "foo", "platforms")
stem = naming.platform_pack_stem(["foo"], "foo", "platforms")
self.assertEqual(os.listdir(out), [f"{stem}_Split"])
self.assertEqual(stem, "Foo-_Bar_release-1.22")
+3 -3
View File
@@ -17,7 +17,7 @@ import tempfile
import unittest
from pathlib import Path
from model.profiles import _emulator_profiles_cache
from model.profiles import emulator_profiles_cache
import generate_db
from packs.coverage import verify_platform
@@ -45,10 +45,10 @@ class TwinDeclarations(unittest.TestCase):
self.db = {"files": files, "indexes": generate_db.build_indexes(files, {})}
self.emulators = Path(self._tmp.name) / "emulators"
self.emulators.mkdir()
_emulator_profiles_cache.clear()
emulator_profiles_cache.clear()
def tearDown(self):
_emulator_profiles_cache.clear()
emulator_profiles_cache.clear()
os.chdir(self._cwd)
self._tmp.cleanup()
+10 -10
View File
@@ -19,7 +19,7 @@ from pathlib import Path
import yaml
from model.platforms import _platform_config_cache, load_platform_config
from model.profiles import load_emulator_profiles, _emulator_profiles_cache
from model.profiles import load_emulator_profiles, emulator_profiles_cache
import generate_db
from packs import manifest as packs_manifest
from packs.extras import platform_region_groups
@@ -77,12 +77,12 @@ class SlugPlatform(unittest.TestCase):
)
(self.emulators / "dosbox.yml").write_text(PROFILE)
_platform_config_cache.clear()
_emulator_profiles_cache.clear()
emulator_profiles_cache.clear()
self.profiles = load_emulator_profiles("emulators")
def tearDown(self):
_platform_config_cache.clear()
_emulator_profiles_cache.clear()
emulator_profiles_cache.clear()
os.chdir(self._cwd)
self._tmp.cleanup()
@@ -139,7 +139,7 @@ class RegionKeysForEveryClaimant(unittest.TestCase):
f"emulator: {name}\ntype: libretro\nsystems: [sys]\ncores: [{name}]\n"
f"files:\n - name: jp.bin\n region: [japan]\n{extra}"
)
_emulator_profiles_cache.clear()
emulator_profiles_cache.clear()
profiles = load_emulator_profiles("emulators")
config = {"platform": "P", "version": "2.1", "verification_mode": "existence", "cores": ["one", "two"],
"systems": {"sys": {"files": []}}}
@@ -199,7 +199,7 @@ class FlatFirmwareFolder(unittest.TestCase):
)
Path("emulators/psx.yml").write_text(self.PROFILE)
_platform_config_cache.clear()
_emulator_profiles_cache.clear()
emulator_profiles_cache.clear()
profiles = load_emulator_profiles("emulators")
if report:
return verify_platform(
@@ -212,7 +212,7 @@ class FlatFirmwareFolder(unittest.TestCase):
)
finally:
_platform_config_cache.clear()
_emulator_profiles_cache.clear()
emulator_profiles_cache.clear()
os.chdir(previous)
def test_a_nested_file_is_omitted_with_its_reason(self):
@@ -269,8 +269,8 @@ class UserProvidedIsNeverTakenFromTheCollection(unittest.TestCase):
"emulator: Fake\ntype: libretro\nsystems: [psx]\ncores: [fake]\n"
"files:\n - name: scph5501.bin\n storage: user_provided\n"
)
_emulator_profiles_cache.clear()
self.addCleanup(_emulator_profiles_cache.clear)
emulator_profiles_cache.clear()
self.addCleanup(emulator_profiles_cache.clear)
result = verify_emulator(["fake"], "emulators", db)
statuses = [d["status"] for d in result["details"] if d["name"] == "scph5501.bin"]
self.assertEqual(statuses, [Status.MISSING])
@@ -300,8 +300,8 @@ class OnePathCountsOnce(unittest.TestCase):
f"emulator: {core}\ntype: libretro\nsystems: [amiga]\ncores: [{core}]\n"
f"files:\n - name: rom.key\n required: false\n{region}"
)
_emulator_profiles_cache.clear()
self.addCleanup(_emulator_profiles_cache.clear)
emulator_profiles_cache.clear()
self.addCleanup(emulator_profiles_cache.clear)
profiles = load_emulator_profiles("emulators")
config = {"platform": "P", "version": "2.1", "verification_mode": "existence", "cores": ["one", "two"],
"systems": {"amiga": {"files": []}}}
+59 -59
View File
@@ -261,31 +261,31 @@ class TestFetchRetry(unittest.TestCase):
def test_dropped_connection_is_retried_then_succeeds(self):
dropped = http.client.RemoteDisconnected("closed")
self._serve([dropped, b"payload"])
self.assertEqual(upstream._fetch("https://host/x"), b"payload")
self.assertEqual(upstream.fetch_body("https://host/x"), b"payload")
self.assertEqual(self.calls, 2)
self.assertEqual(len(self.slept), 1)
def test_retries_are_bounded(self):
self._serve([http.client.RemoteDisconnected("closed")])
with self.assertRaises(upstream.UpstreamError):
upstream._fetch("https://host/x")
upstream.fetch_body("https://host/x")
self.assertEqual(self.calls, upstream.RETRIES)
def test_server_error_is_retried(self):
self._serve([_http_error(503)])
with self.assertRaises(upstream.UpstreamError):
upstream._fetch("https://host/x")
upstream.fetch_body("https://host/x")
self.assertEqual(self.calls, upstream.RETRIES)
def test_forbidden_is_not_retried(self):
self._serve([_http_error(403)])
with self.assertRaises(upstream.UpstreamError):
upstream._fetch("https://host/x")
upstream.fetch_body("https://host/x")
self.assertEqual(self.calls, 1)
def test_missing_file_is_not_retried(self):
self._serve([_http_error(404)])
self.assertIsNone(upstream._fetch("https://host/x"))
self.assertIsNone(upstream.fetch_body("https://host/x"))
self.assertEqual(self.calls, 1)
@staticmethod
@@ -301,26 +301,26 @@ class TestFetchRetry(unittest.TestCase):
# git.libretro.com answered 429 on cemu's tree a few hundred
# requests into a pass, and the whole pass stopped.
self._serve([self._limited("7"), self._limited(), b"payload"])
self.assertEqual(upstream._fetch("https://host/x"), b"payload")
self.assertEqual(upstream.fetch_body("https://host/x"), b"payload")
self.assertEqual(self.slept, [7.0, upstream.RATE_LIMIT_WAITS[1]])
def test_lasting_rate_limit_mutes_the_host_only(self):
self._serve([self._limited()])
with self.assertRaises(upstream.RateLimitError) as caught:
upstream._fetch("https://host/x")
upstream.fetch_body("https://host/x")
self.assertEqual(caught.exception.host, "host")
self.assertEqual(self.calls, len(upstream.RATE_LIMIT_WAITS) + 1)
# The same host is not asked again, another one still is.
with self.assertRaises(upstream.RateLimitError):
upstream._fetch("https://host/y")
upstream.fetch_body("https://host/y")
self.assertEqual(self.calls, len(upstream.RATE_LIMIT_WAITS) + 1)
self._serve([b"other"])
self.assertEqual(upstream._fetch("https://other/x"), b"other")
self.assertEqual(upstream.fetch_body("https://other/x"), b"other")
def test_long_retry_after_is_not_waited(self):
self._serve([self._limited(str(int(upstream.RATE_LIMIT_WAIT_CAP) + 1))])
with self.assertRaises(upstream.RateLimitError):
upstream._fetch("https://host/x")
upstream.fetch_body("https://host/x")
self.assertEqual((self.calls, self.slept), (1, []))
def test_exhausted_github_quota_is_not_waited(self):
@@ -330,7 +330,7 @@ class TestFetchRetry(unittest.TestCase):
headers["X-RateLimit-Remaining"] = "0"
self._serve([_http_error(403, headers)])
with self.assertRaises(upstream.RateLimitError):
upstream._fetch("https://host/x")
upstream.fetch_body("https://host/x")
self.assertEqual((self.calls, self.slept), (1, []))
@@ -362,14 +362,14 @@ class TestGoneUpstream(unittest.TestCase):
def test_legal_takedown_is_gone_and_not_retried(self):
self._serve(_http_error(451))
with self.assertRaises(upstream.GoneError):
upstream._fetch("https://host/x")
upstream.fetch_body("https://host/x")
self.assertEqual(self.calls, 1)
self.assertEqual(self.slept, [])
def test_http_gone_is_gone(self):
self._serve(_http_error(410))
with self.assertRaises(upstream.GoneError):
upstream._fetch("https://host/x")
upstream.fetch_body("https://host/x")
self.assertEqual(self.calls, 1)
def test_unresolvable_host_is_gone_and_not_retried(self):
@@ -378,7 +378,7 @@ class TestGoneUpstream(unittest.TestCase):
))
with mock.patch.object(upstream, "_resolver_answers", return_value=True), \
self.assertRaises(upstream.GoneError):
upstream._fetch("https://host/x")
upstream.fetch_body("https://host/x")
self.assertEqual(self.calls, 1)
self.assertEqual(self.slept, [])
@@ -390,25 +390,25 @@ class TestGoneUpstream(unittest.TestCase):
self._serve(urllib.error.URLError(socket.gaierror(errno, "no")))
with mock.patch.object(upstream, "_resolver_answers", return_value=resolver), \
self.assertRaises(upstream.UpstreamError) as caught:
upstream._fetch("https://host/x")
upstream.fetch_body("https://host/x")
self.assertNotIsInstance(caught.exception, upstream.GoneError)
def test_a_gone_error_is_still_an_upstream_error(self):
self._serve(_http_error(451))
with self.assertRaises(upstream.UpstreamError):
upstream._fetch("https://host/x")
upstream.fetch_body("https://host/x")
def test_refused_request_is_not_gone(self):
"""403 is a forge refusing a request, which anti-bot filters do."""
self._serve(_http_error(403))
with self.assertRaises(upstream.UpstreamError) as caught:
upstream._fetch("https://host/x")
upstream.fetch_body("https://host/x")
self.assertNotIsInstance(caught.exception, upstream.GoneError)
def test_a_dropped_connection_is_not_gone(self):
self._serve(http.client.RemoteDisconnected("closed"))
with self.assertRaises(upstream.UpstreamError) as caught:
upstream._fetch("https://host/x")
upstream.fetch_body("https://host/x")
self.assertNotIsInstance(caught.exception, upstream.GoneError)
self.assertEqual(self.calls, upstream.RETRIES)
@@ -419,12 +419,12 @@ class TestCache(unittest.TestCase):
self.dir = self.tmp.name
self.repo = parse_repo("https://github.com/o/n")
self.calls: list[str] = []
self._orig = (upstream._http_text, upstream._http_json)
upstream._http_text = self._fake
upstream._http_json = _no_network
self._orig = (upstream.http_text, upstream.http_json)
upstream.http_text = self._fake
upstream.http_json = _no_network
def tearDown(self):
upstream._http_text, upstream._http_json = self._orig
upstream.http_text, upstream.http_json = self._orig
self.tmp.cleanup()
def _fake(self, url: str) -> str | None:
@@ -473,7 +473,7 @@ class TestCache(unittest.TestCase):
self.assertEqual(self.calls, [])
def test_missing_file_is_cached_as_absent(self):
upstream._http_text = lambda url: None
upstream.http_text = lambda url: None
self.assertIsNone(upstream.fetch_file(self.repo, "abc", "gone.c", self.dir))
self.assertIsNone(
upstream.fetch_file(self.repo, "abc", "gone.c", self.dir, offline=True)
@@ -505,12 +505,12 @@ class TestRevisions(unittest.TestCase):
self.repo = parse_repo("https://github.com/o/n")
self.responses: dict[str, object] = {}
self.calls: list[str] = []
self._orig = (upstream._http_json, upstream._http_text)
upstream._http_json = self._fake
upstream._http_text = _no_network
self._orig = (upstream.http_json, upstream.http_text)
upstream.http_json = self._fake
upstream.http_text = _no_network
def tearDown(self):
upstream._http_json, upstream._http_text = self._orig
upstream.http_json, upstream.http_text = self._orig
self.tmp.cleanup()
def _fake(self, url: str):
@@ -634,7 +634,7 @@ class TestRevisions(unittest.TestCase):
def boom(url: str):
raise upstream.RateLimitError("quota")
upstream._http_json = boom
upstream.http_json = boom
with self.assertRaises(upstream.RateLimitError):
upstream.resolve_head(self.repo, self.dir)
@@ -645,12 +645,12 @@ class TestCompare(unittest.TestCase):
self.dir = self.tmp.name
self.repo = parse_repo("https://github.com/o/n")
self.payload: object = None
self._orig = (upstream._http_json, upstream._http_text)
upstream._http_json = lambda url: self.payload
upstream._http_text = _no_network
self._orig = (upstream.http_json, upstream.http_text)
upstream.http_json = lambda url: self.payload
upstream.http_text = _no_network
def tearDown(self):
upstream._http_json, upstream._http_text = self._orig
upstream.http_json, upstream.http_text = self._orig
self.tmp.cleanup()
def test_list_directory_reads_one_tree(self):
@@ -667,7 +667,7 @@ class TestCompare(unittest.TestCase):
],
}
upstream._http_json = answer
upstream.http_json = answer
self.assertEqual(
upstream.list_directory(self.repo, "abc", "hash/", self.dir), ["a.xml", "b.xml"]
)
@@ -678,7 +678,7 @@ class TestCompare(unittest.TestCase):
["a.xml", "b.xml"],
)
self.assertEqual(len(seen), 1)
upstream._http_json = lambda url: {"truncated": True, "tree": []}
upstream.http_json = lambda url: {"truncated": True, "tree": []}
self.assertIsNone(upstream.list_directory(self.repo, "def", "hash", self.dir))
gitlab = parse_repo("https://gitlab.com/o/n")
self.assertIsNone(upstream.list_directory(gitlab, "abc", "hash", self.dir))
@@ -749,7 +749,7 @@ class TestCompare(unittest.TestCase):
return value
return listing
upstream._http_json = answer
upstream.http_json = answer
self.assertEqual(
upstream.commits_touching(self.repo, "a.c", "base", self.dir, head="tip"), 2
)
@@ -774,7 +774,7 @@ class TestCompare(unittest.TestCase):
return value
return list(listing)
upstream._http_json = answer
upstream.http_json = answer
self.assertEqual(upstream.commits_touching(self.repo, "a.c", "base", self.dir), 1)
for cached in (Path(self.dir) / "_api").glob("*.json"):
stale = _os.path.getmtime(cached) - upstream.MOVING_TTL - 1
@@ -793,7 +793,7 @@ class TestCompare(unittest.TestCase):
def answer(url):
return answers[-1]
upstream._http_json = answer
upstream.http_json = answer
self.assertIsNone(upstream.tag_commit(self.repo, "v2.0", self.dir))
for cached in (Path(self.dir) / "_api").glob("*.json"):
stale = _os.path.getmtime(cached) - upstream.MOVING_TTL - 1
@@ -813,7 +813,7 @@ class TestGitlabTree(unittest.TestCase):
self.dir = self.tmp.name
self.repo = upstream.parse_repo("https://gitlab.com/g/p")
self.pages: dict[int, object] = {}
self._orig = (upstream._http_json, upstream._http_text)
self._orig = (upstream.http_json, upstream.http_text)
def fake(url):
page = int(url.rsplit("page=", 1)[1])
@@ -822,10 +822,10 @@ class TestGitlabTree(unittest.TestCase):
raise upstream.UpstreamError(url)
return payload
upstream._http_json = fake
upstream.http_json = fake
def tearDown(self):
upstream._http_json, upstream._http_text = self._orig
upstream.http_json, upstream.http_text = self._orig
self.tmp.cleanup()
def _blobs(self, *names):
@@ -876,7 +876,7 @@ class TestGiteaCommitAt(unittest.TestCase):
self.tmp = tempfile.TemporaryDirectory()
self.addCleanup(self.tmp.cleanup)
self.urls: list[str] = []
original = upstream._http_json
original = upstream.http_json
def fake(url):
self.urls.append(url)
@@ -884,8 +884,8 @@ class TestGiteaCommitAt(unittest.TestCase):
page = int(url.rsplit("page=", 1)[1])
return self.PAGES.get(page, [])
upstream._http_json = fake
self.addCleanup(setattr, upstream, "_http_json", original)
upstream.http_json = fake
self.addCleanup(setattr, upstream, "http_json", original)
def test_the_first_commit_by_the_cutoff(self):
repo = parse_repo("https://codeberg.org/iyzsong/gam4980")
@@ -914,7 +914,7 @@ class TestCurrentSlug(unittest.TestCase):
},
}
with tempfile.TemporaryDirectory() as tmp, \
mock.patch.object(upstream, "_http_json", side_effect=answers.get):
mock.patch.object(upstream, "http_json", side_effect=answers.get):
github = parse_repo("https://github.com/AloysHF/NicaiEmu")
gitlab = parse_repo("https://gitlab.com/g/sub/p")
self.assertEqual(upstream.current_slug(github, tmp), "AloysHF/CoolbarEmu")
@@ -953,10 +953,10 @@ class TestNewestTag(unittest.TestCase):
class TestNamedTagCommit(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
self.saved = upstream._http_json
self.saved = upstream.http_json
def tearDown(self):
upstream._http_json = self.saved
upstream.http_json = self.saved
self.tmp.cleanup()
def test_gitlab_tag_is_asked_by_name(self):
@@ -966,7 +966,7 @@ class TestNamedTagCommit(unittest.TestCase):
asked.append(url)
return {"name": "1.2.35", "commit": {"id": "c74fc36"}}
upstream._http_json = answer
upstream.http_json = answer
repo = parse_repo("https://gitlab.com/jengun/sdltrs")
self.assertEqual(upstream.tag_commit(repo, "1.2.35", self.tmp.name), "c74fc36")
self.assertTrue(asked[0].endswith("/repository/tags/1.2.35"))
@@ -975,10 +975,10 @@ class TestNamedTagCommit(unittest.TestCase):
class TestForkBase(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
self.saved = upstream._http_json
self.saved = upstream.http_json
def tearDown(self):
upstream._http_json = self.saved
upstream.http_json = self.saved
self.tmp.cleanup()
def test_the_merge_base_github_names(self):
@@ -988,13 +988,13 @@ class TestForkBase(unittest.TestCase):
asked.append(url)
return {"merge_base_commit": {"sha": "base"}, "status": "diverged"}
upstream._http_json = answer
upstream.http_json = answer
up, fork = make_repo("github.com", "o", "up"), make_repo("github.com", "f", "port")
self.assertEqual(upstream.fork_base(up, "tip", fork, "head", self.tmp.name), "base")
self.assertTrue(asked[0].endswith("/repos/o/up/compare/tip...f:port:head"))
def test_no_network_is_none(self):
upstream._http_json = lambda url: None
upstream.http_json = lambda url: None
up, fork = make_repo("github.com", "o", "up"), make_repo("github.com", "f", "port")
self.assertIsNone(upstream.fork_base(up, "tip", fork, "head", self.tmp.name))
@@ -1029,41 +1029,41 @@ class TestGitlabDirectoryArchive(unittest.TestCase):
def test_files_land_in_the_cache_fetch_file_reads(self):
calls = []
with mock.patch.object(upstream, "_fetch", side_effect=lambda url: calls.append(url) or self.body):
with mock.patch.object(upstream, "fetch_body", side_effect=lambda url: calls.append(url) or self.body):
held = upstream.cache_gitlab_directory(self.repo, "abc", "sys", self.tmp.name)
self.assertEqual(held, {"sys/a/system.ini", "sys/b/system.ini"})
self.assertEqual(len(calls), 1)
self.assertIn("archive.tar.gz?sha=abc&path=sys", calls[0])
with mock.patch.object(upstream, "_http_text", side_effect=_no_network):
with mock.patch.object(upstream, "http_text", side_effect=_no_network):
lines = upstream.fetch_file(self.repo, "abc", "sys/b/system.ini", self.tmp.name, offline=True)
self.assertEqual(lines, ["[core.x]"])
def test_a_second_run_reads_the_index_offline(self):
with mock.patch.object(upstream, "_fetch", return_value=self.body):
with mock.patch.object(upstream, "fetch_body", return_value=self.body):
upstream.cache_gitlab_directory(self.repo, "abc", "sys", self.tmp.name)
with mock.patch.object(upstream, "_fetch", side_effect=_no_network):
with mock.patch.object(upstream, "fetch_body", side_effect=_no_network):
held = upstream.cache_gitlab_directory(self.repo, "abc", "sys", self.tmp.name, offline=True)
self.assertEqual(held, {"sys/a/system.ini", "sys/b/system.ini"})
def test_offline_without_index_knows_nothing(self):
with mock.patch.object(upstream, "_fetch", side_effect=_no_network):
with mock.patch.object(upstream, "fetch_body", side_effect=_no_network):
self.assertIsNone(upstream.cache_gitlab_directory(self.repo, "abc", "sys", self.tmp.name, offline=True))
def test_other_forges_are_left_to_per_file_reads(self):
github = parse_repo("https://github.com/o/r")
with mock.patch.object(upstream, "_fetch", side_effect=_no_network):
with mock.patch.object(upstream, "fetch_body", side_effect=_no_network):
self.assertIsNone(upstream.cache_gitlab_directory(github, "abc", "sys", self.tmp.name))
def test_a_refused_api_falls_back_to_git(self):
refused = upstream.RateLimitError("429", "gitlab.com")
with mock.patch.object(upstream, "_fetch", side_effect=refused), \
with mock.patch.object(upstream, "fetch_body", side_effect=refused), \
mock.patch.object(upstream, "_sparse_git_files", return_value={"sys/a/system.ini": "x"}) as git:
held = upstream.cache_gitlab_directory(self.repo, "abc", "sys", self.tmp.name)
self.assertEqual(held, {"sys/a/system.ini"})
git.assert_called_once()
def test_an_empty_archive_is_an_error_not_an_empty_directory(self):
with mock.patch.object(upstream, "_fetch", return_value=_tarball({"p/other/x": "y"})), \
with mock.patch.object(upstream, "fetch_body", return_value=_tarball({"p/other/x": "y"})), \
self.assertRaises(upstream.UpstreamError):
upstream.cache_gitlab_directory(self.repo, "abc", "sys", self.tmp.name)
+11 -11
View File
@@ -17,7 +17,7 @@ import tempfile
import unittest
from pathlib import Path
from resolve.validation import _build_validation_index, destination_owners, validated_choice
from resolve.validation import build_validation_index, destination_owners, validated_choice
REPO_ROOT = Path(__file__).resolve().parent.parent
@@ -44,7 +44,7 @@ class ValidatedChoice(unittest.TestCase):
"indexes": {"by_name": {}, "by_md5": {}},
}
db["indexes"]["by_name"]["ROM2.BIN"] = list(db["files"])
index = _build_validation_index({
index = build_validation_index({
"galaksija": {
"emulator": "galaksija",
"files": [{"name": "ROM2.BIN", "size": 4096, "validation": ["size"]}],
@@ -66,7 +66,7 @@ class ValidatedChoice(unittest.TestCase):
{"name": "cpc6128.rom", "path": "ep128emu/roms/cpc6128.rom"},
]},
}
index = _build_validation_index(profiles)
index = build_validation_index(profiles)
owners = destination_owners(profiles)
with tempfile.TemporaryDirectory(dir=REPO_ROOT / "tmp") as tmp:
rom = Path(tmp) / "cpc6128.rom"
@@ -106,7 +106,7 @@ class ValidatedChoice(unittest.TestCase):
for call in ast.walk(node)
)
}
self.assertLessEqual({"generate_pack", "_manifest_core_entries"}, resolvers)
self.assertLessEqual({"generate_pack", "manifest_core_entries"}, resolvers)
extras = ast.parse((REPO_ROOT / "scripts" / "packs" / "extras.py").read_text(encoding="utf-8"))
resolve = next(
node for node in ast.walk(extras)
@@ -166,7 +166,7 @@ class ManifestsServeWhatTheCoreAccepts(unittest.TestCase):
profiles = load_emulator_profiles(str(REPO_ROOT / "emulators"))
config = load_platform_config("retroarch", str(REPO_ROOT / "platforms"))
cores = {n: profiles[n] for n in _platform_cores(config, profiles)}
index = _build_validation_index(cores)
index = build_validation_index(cores)
owners = destination_owners(cores)
manifest = json.loads(manifest_path.read_text(encoding="utf-8"))
wrong = []
@@ -195,7 +195,7 @@ class EachReaderJudgesWithItsOwnRules(unittest.TestCase):
def test_rules_of_another_emulator_do_not_judge(self):
from resolve.validation import check_file_validation
index = _build_validation_index({
index = build_validation_index({
"azahar": {"files": [{"name": "otp.bin", "path": "sysdata/otp.bin",
"size": 256, "validation": ["size"]}]},
"cemu": {"files": [{"name": "otp.bin", "path": "Cemu/otp.bin",
@@ -210,7 +210,7 @@ class EachReaderJudgesWithItsOwnRules(unittest.TestCase):
def test_one_of_an_emulators_entries_is_enough(self):
from resolve.validation import check_file_validation
index = _build_validation_index({"raze": {"files": [
index = build_validation_index({"raze": {"files": [
{"name": "SW.GRP", "size": 100, "validation": ["size"]},
{"name": "SW.GRP", "size": 200, "validation": ["size"]},
]}})
@@ -239,7 +239,7 @@ class DolphinForksJudgeTheirOwnDspTable(unittest.TestCase):
expect = {"dolphin": "v04", "primehack": "v04", "dolphin-mmjr2": "v04",
"triforce": "v04", "dolphin-mmjr": "v031", "ishiiruka": "v031"}
for name, accepted in expect.items():
index = _build_validation_index({name: profiles[name]})
index = build_validation_index({name: profiles[name]})
with self.subTest(emulator=name):
for label, path in (("v04", self.FREE_V04), ("v031", self.FREE_V031)):
verdict = check_file_validation(
@@ -266,7 +266,7 @@ class AWarningRejectsNothing(unittest.TestCase):
sha1 = hashlib.sha1(f.read_bytes()).hexdigest()
db["files"][sha1] = {"path": str(f), "name": "OS12.rom", "size": f.stat().st_size}
db["indexes"]["by_name"]["OS12.rom"].append(sha1)
index = _build_validation_index({"beebem": {"files": [
index = build_validation_index({"beebem": {"files": [
{"name": "OS12.rom", "size": 16384, "validation": ["size"], "on_mismatch": "warn"},
]}})
return short, good, db, index
@@ -345,7 +345,7 @@ class AVersionTakenWithoutACheck(unittest.TestCase):
def test_the_unchecked_version_accepts_the_copy(self):
from resolve.validation import check_file_validation
index = _build_validation_index({"raze": self.RAZE})
index = build_validation_index({"raze": self.RAZE})
with tempfile.TemporaryDirectory(dir=REPO_ROOT / "tmp") as tmp:
self.assertIsNone(check_file_validation(
self._file(tmp), "BLOOD.RFF", index, emulators={"raze"}
@@ -364,7 +364,7 @@ class AVersionTakenWithoutACheck(unittest.TestCase):
from resolve.validation import check_file_validation
checked = {"files": self.RAZE["files"][:2]}
index = _build_validation_index({"raze": checked})
index = build_validation_index({"raze": checked})
with tempfile.TemporaryDirectory(dir=REPO_ROOT / "tmp") as tmp:
reason, emulators = check_file_validation(
self._file(tmp), "BLOOD.RFF", index, emulators={"raze"}
+8 -8
View File
@@ -20,7 +20,7 @@ REPO_ROOT = Path(__file__).resolve().parents[1]
class ValidationIndexScope(unittest.TestCase):
def test_no_index_over_every_profile(self):
pattern = re.compile(r"_build_validation_index\(\s*(emu_)?profiles\s*\)")
pattern = re.compile(r"build_validation_index\(\s*(emu_)?profiles\s*\)")
for name in ("verify.py", "generate_pack.py", "packs/integrity.py", "packs/extras.py"):
source = script_source(name)
with self.subTest(module=name):
@@ -34,11 +34,11 @@ class ValidationIndexScope(unittest.TestCase):
r"plat_cores = resolve_platform_cores\(config, profiles\)\s+"
r"platform_profiles = \{name: profiles\[name\] for name in plat_cores\}",
)
self.assertIn("validation_index = _build_validation_index(platform_profiles)", verify)
self.assertIn("validation_index = build_validation_index(platform_profiles)", verify)
self.assertRegex(
builder,
r"for name in resolve_platform_cores\(config, emu_profiles\)\s*\}\s*"
r"validation_index = _build_validation_index\(platform_profiles\)",
r"validation_index = build_validation_index\(platform_profiles\)",
)
@@ -60,7 +60,7 @@ class ContentFoundLabelsTakeTheirRegionSlot(unittest.TestCase):
import hashlib
import tempfile
from resolve.validation import _build_validation_index, check_file_validation
from resolve.validation import build_validation_index, check_file_validation
with tempfile.TemporaryDirectory() as tmp:
path = Path(tmp) / "scph1001.bin"
@@ -78,12 +78,12 @@ class ContentFoundLabelsTakeTheirRegionSlot(unittest.TestCase):
"validation": ["sha256"], "sha256": "b" * 64},
],
}
index = _build_validation_index({"rustation": profile})
index = build_validation_index({"rustation": profile})
self.assertIsNone(check_file_validation(str(path), "scph1001.bin", index))
# Another region is another slot.
self.assertIsNotNone(check_file_validation(str(path), "scph5500.bin", index))
# A core that opens the file by name rejects it.
index = _build_validation_index({"rustation": {**profile, "found_by": "name"}})
index = build_validation_index({"rustation": {**profile, "found_by": "name"}})
self.assertIsNotNone(check_file_validation(str(path), "scph1001.bin", index))
@@ -97,12 +97,12 @@ class GearcolecoWarnsOnAnUnknownRevision(unittest.TestCase):
import yaml
from resolve.validation import _build_validation_index, check_file_validation
from resolve.validation import build_validation_index, check_file_validation
profile = yaml.safe_load(
(REPO_ROOT / "emulators" / "gearcoleco.yml").read_text(encoding="utf-8")
)
index = _build_validation_index({"gearcoleco": profile})
index = build_validation_index({"gearcoleco": profile})
with tempfile.TemporaryDirectory() as tmp:
for name, size in (("colecovision.rom", 8192), ("eos.rom", 8192),
("writer.rom", 32768)):
+5 -5
View File
@@ -51,12 +51,12 @@ class FindValidatedVariant(unittest.TestCase):
"by_name": {"rom.bin": [s for s, e in self.files.items() if e["name"] == "rom.bin"]},
"by_md5": {e["md5"]: s for s, e in self.files.items()},
}}
from resolve.validation import _build_validation_index
from resolve.validation import build_validation_index
self.by_hash = _build_validation_index({"emu": {"files": [
self.by_hash = build_validation_index({"emu": {"files": [
{"name": "rom.bin", "validation": ["size", "sha1"], "size": 16,
"sha1": self.good_sha1}]}})
self.by_size = _build_validation_index({"emu": {"files": [
self.by_size = build_validation_index({"emu": {"files": [
{"name": "rom.bin", "validation": ["size"], "size": 16}]}})
def test_a_dump_held_under_another_name_is_found_by_the_emulator_hash(self):
@@ -95,7 +95,7 @@ _SEEDED = """
import hashlib, sys, tempfile
from pathlib import Path
sys.path.insert(0, sys.argv[1])
from resolve.validation import _build_validation_index, find_validated_variant
from resolve.validation import build_validation_index, find_validated_variant
root = Path(sys.argv[2])
paths = [root / f"ctrl_{i}.rom" for i in range(8)]
files = {}
@@ -105,7 +105,7 @@ for i, path in enumerate(paths):
files[hashlib.sha1(data).hexdigest()] = {"path": str(path), "name": path.name}
bad = root / "MT32_CONTROL.ROM"
bad.write_bytes(b"x" * 16)
index = _build_validation_index({"emu": {"files": [
index = build_validation_index({"emu": {"files": [
{"name": "MT32_CONTROL.ROM", "validation": ["sha1"], "sha1": sha1} for sha1 in files]}})
db = {"files": files, "indexes": {"by_name": {}}}
print(find_validated_variant({"name": "MT32_CONTROL.ROM"}, db, str(bad), index))
Loaded 100 of 254 files, more files were not shown because too many files have changed in this diff. Show more