From 382241fb1bf053e5e49c7fe9ca0e49f453c3b466 Mon Sep 17 00:00:00 2001 From: Abdessamad Derraz <3028866+Abdess@users.noreply.github.com> Date: Tue, 17 Nov 2026 07:21:12 +0100 Subject: [PATCH] refactor: split long test functions by stage --- tests/test_archive_recipes.py | 134 +++++++------ tests/test_install.py | 119 +++++++----- tests/test_install_tui.py | 33 +++- tests/test_pin_build.py | 32 ++-- tests/test_site_copy.py | 293 ++++++++++++++++------------- tests/test_site_system_sections.py | 96 ++++++---- tests/test_target_scrapers.py | 148 +++++++-------- 7 files changed, 481 insertions(+), 374 deletions(-) diff --git a/tests/test_archive_recipes.py b/tests/test_archive_recipes.py index 6d88d00ea..083fe9437 100644 --- a/tests/test_archive_recipes.py +++ b/tests/test_archive_recipes.py @@ -85,56 +85,86 @@ def _hashes(values: object) -> set[str]: return {str(value).strip().lower() for value in raw if str(value).strip()} +def _allowed_members() -> dict[str, set[str]]: + from common import load_emulator_profiles + from romset_recipes import load_dat_recipes + + allowed: dict[str, set[str]] = defaultdict(set) + for archive, per_label in load_dat_recipes(REPO_ROOT / "recipes").items(): + for recipe in per_label.values(): + allowed[archive.lower()] |= {crc for _name, crc in recipe} + profiles = load_emulator_profiles(str(REPO_ROOT / "emulators"), skip_aliases=False) + for profile in profiles.values(): + for entry in profile.get("files", []) or []: + crcs = { + str(member.get("crc32") or "").lower() + for member in entry.get("contents") or [] + } + crcs.discard("") + if not crcs: + continue + for name in [entry.get("name", "")] + list(entry.get("aliases") or []): + if name: + allowed[str(name).lower()] |= crcs + for name, devices in DEVICE_ROMS.items(): + for device in devices: + allowed[name] |= allowed.get(device, set()) + return allowed + + +def _platform_pins() -> tuple[set[str], dict[str, set[tuple[str, str]]]]: + from common import list_registered_platforms, load_platform_config + + pinned: set[str] = set() + zipped: dict[str, set[tuple[str, str]]] = defaultdict(set) + platforms_dir = str(REPO_ROOT / "platforms") + for platform in list_registered_platforms(platforms_dir): + config = load_platform_config(platform, platforms_dir) + for system in config.get("systems", {}).values(): + for entry in system.get("files", []) or []: + if entry.get("zipped_file"): + for md5 in _hashes(entry.get("md5")): + zipped[str(entry.get("name", "")).lower()].add( + (str(entry["zipped_file"]).casefold(), md5) + ) + continue + for key in ("md5", "sha1", "alt_md5"): + pinned |= _hashes(entry.get(key)) + return pinned, zipped + + +def _extra_members( + path: Path, name: str, allowed: set[str], zipped: set[tuple[str, str]] +) -> list[zipfile.ZipInfo] | None: + stem = name[:-4] + try: + with zipfile.ZipFile(path) as archive: + extra = [ + info for info in archive.infolist() + if not info.is_dir() + and f"{info.CRC:08x}" not in allowed + # a merged set keeps each clone in a folder of its name + and not ("/" in info.filename and info.filename.split("/")[0] != stem) + ] + return [ + info for info in extra + if (info.filename.casefold(), + hashlib.md5(archive.read(info)).hexdigest()) not in zipped + ] + except zipfile.BadZipFile: + return None + + class HeldArchivesMatchTheirRecipes(unittest.TestCase): def test_no_member_outside_every_recipe_of_the_name(self): bios = REPO_ROOT / "bios" if not bios.is_dir() or not (REPO_ROOT / "recipes").is_dir(): self.skipTest("bios/ or recipes/ is not present") - from common import ( - list_registered_platforms, - load_emulator_profiles, - load_platform_config, - variant_base_name, - ) + from common import variant_base_name from hashing import md5_composite_of - from romset_recipes import load_dat_recipes - allowed: dict[str, set[str]] = defaultdict(set) - for archive, per_label in load_dat_recipes(REPO_ROOT / "recipes").items(): - for recipe in per_label.values(): - allowed[archive.lower()] |= {crc for _name, crc in recipe} - profiles = load_emulator_profiles(str(REPO_ROOT / "emulators"), skip_aliases=False) - for profile in profiles.values(): - for entry in profile.get("files", []) or []: - crcs = { - str(member.get("crc32") or "").lower() - for member in entry.get("contents") or [] - } - crcs.discard("") - if not crcs: - continue - for name in [entry.get("name", "")] + list(entry.get("aliases") or []): - if name: - allowed[str(name).lower()] |= crcs - for name, devices in DEVICE_ROMS.items(): - for device in devices: - allowed[name] |= allowed.get(device, set()) - - pinned: set[str] = set() - zipped: dict[str, set[tuple[str, str]]] = defaultdict(set) - platforms_dir = str(REPO_ROOT / "platforms") - for platform in list_registered_platforms(platforms_dir): - config = load_platform_config(platform, platforms_dir) - for system in config.get("systems", {}).values(): - for entry in system.get("files", []) or []: - if entry.get("zipped_file"): - for md5 in _hashes(entry.get("md5")): - zipped[str(entry.get("name", "")).lower()].add( - (str(entry["zipped_file"]).casefold(), md5) - ) - continue - for key in ("md5", "sha1", "alt_md5"): - pinned |= _hashes(entry.get(key)) + allowed = _allowed_members() + pinned, zipped = _platform_pins() offenders = [] for path in sorted(bios.rglob("*")): @@ -143,22 +173,8 @@ class HeldArchivesMatchTheirRecipes(unittest.TestCase): continue if path.parent.name in NOT_ROMSETS: continue - stem = name[:-4] - try: - with zipfile.ZipFile(path) as archive: - extra = [ - info for info in archive.infolist() - if not info.is_dir() - and f"{info.CRC:08x}" not in allowed[name] - # a merged set keeps each clone in a folder of its name - and not ("/" in info.filename and info.filename.split("/")[0] != stem) - ] - extra = [ - info for info in extra - if (info.filename.casefold(), - hashlib.md5(archive.read(info)).hexdigest()) not in zipped[name] - ] - except zipfile.BadZipFile: + extra = _extra_members(path, name, allowed[name], zipped[name]) + if extra is None: continue if len(extra) < MIN_EXTRA or str(path.relative_to(REPO_ROOT)) in KEPT: continue diff --git a/tests/test_install.py b/tests/test_install.py index 305c26895..2f80a40b1 100644 --- a/tests/test_install.py +++ b/tests/test_install.py @@ -61,6 +61,52 @@ def _tempdir(test: unittest.TestCase) -> str: return path +def _parenthesized_withs(tokens: list) -> list[str]: + import tokenize + + found = [] + for i, tok in enumerate(tokens): + if tok.type == tokenize.NAME and tok.string == "with" and i + 1 < len(tokens): + if tokens[i + 1].string != "(": + continue + depth = 0 + for inner in tokens[i + 1:]: + if inner.string in "([{" and inner.type == tokenize.OP: + depth += 1 + elif inner.string in ")]}" and inner.type == tokenize.OP: + depth -= 1 + if depth == 0: + break + elif depth == 1 and inner.type == tokenize.NAME and inner.string == "as": + found.append(f"line {tok.start[0]}: parenthesized with") + break + return found + + +def _nested_fstrings(tokens: list) -> list[str]: + import tokenize + + found: list[str] = [] + fstring_start = getattr(tokenize, "FSTRING_START", None) + if fstring_start is None: + return found + stack = [] + for tok in tokens: + if tok.type == fstring_start: + if stack: + found.append(f"line {tok.start[0]}: f-string inside an f-string") + stack.append(tok.string[-1]) + elif tok.type == tokenize.FSTRING_END: + stack.pop() + elif stack and tok.type == tokenize.STRING and stack[-1] in tok.string: + found.append(f"line {tok.start[0]}: f-string reuses its quote") + elif stack and tok.type == tokenize.FSTRING_MIDDLE: + continue + elif stack and tok.type == tokenize.ERRORTOKEN and tok.string == "\\": + found.append(f"line {tok.start[0]}: backslash in an f-string field") + return found + + class TestShellUnquote(unittest.TestCase): def test_plain_value(self): self.assertEqual(install._shell_unquote("/userdata/bios"), "/userdata/bios") @@ -1670,39 +1716,8 @@ class InstallerStaysOnPython38AndTheStdlib(unittest.TestCase): import io import tokenize - found = [] tokens = list(tokenize.generate_tokens(io.StringIO(self.SOURCE).readline)) - for i, tok in enumerate(tokens): - if tok.type == tokenize.NAME and tok.string == "with" and i + 1 < len(tokens): - if tokens[i + 1].string != "(": - continue - depth = 0 - for inner in tokens[i + 1:]: - if inner.string in "([{" and inner.type == tokenize.OP: - depth += 1 - elif inner.string in ")]}" and inner.type == tokenize.OP: - depth -= 1 - if depth == 0: - break - elif depth == 1 and inner.type == tokenize.NAME and inner.string == "as": - found.append(f"line {tok.start[0]}: parenthesized with") - break - fstring_start = getattr(tokenize, "FSTRING_START", None) - if fstring_start is not None: - stack = [] - for tok in tokens: - if tok.type == fstring_start: - if stack: - found.append(f"line {tok.start[0]}: f-string inside an f-string") - stack.append(tok.string[-1]) - elif tok.type == tokenize.FSTRING_END: - stack.pop() - elif stack and tok.type == tokenize.STRING and stack[-1] in tok.string: - found.append(f"line {tok.start[0]}: f-string reuses its quote") - elif stack and tok.type == tokenize.FSTRING_MIDDLE: - continue - elif stack and tok.type == tokenize.ERRORTOKEN and tok.string == "\\": - found.append(f"line {tok.start[0]}: backslash in an f-string field") + found = _parenthesized_withs(tokens) + _nested_fstrings(tokens) self.assertEqual(found, []) def test_no_runtime_generic_builtin(self): @@ -2194,9 +2209,9 @@ class TestManualPlatformPrompt(unittest.TestCase): def test_quit_stops_like_ctrl_c(self): """`install.sh && retroarch` went on to start RetroArch with no BIOS after a q, which left with 0 where Ctrl+C leaves with 130.""" - with unittest.mock.patch("builtins.input", lambda _prompt="": "q"): - with self.assertRaises(SystemExit) as raised: - install._prompt_manual_platform("linux") + with unittest.mock.patch("builtins.input", lambda _prompt="": "q"), \ + self.assertRaises(SystemExit) as raised: + install._prompt_manual_platform("linux") self.assertEqual(raised.exception.code, install.QUIT_CODE) def test_quotes_around_a_typed_folder_are_dropped(self): @@ -2207,7 +2222,8 @@ class TestManualPlatformPrompt(unittest.TestCase): f' "{root}/My Card/bios" '): answers = iter(["1", typed]) with self.subTest(typed=typed), \ - unittest.mock.patch("builtins.input", lambda _prompt="": next(answers)), \ + unittest.mock.patch("builtins.input", + lambda _prompt="", answers=answers: next(answers)), \ contextlib.redirect_stdout(io.StringIO()): chosen = install._prompt_manual_platform("linux") self.assertEqual(chosen, [("retroarch", root / "My Card" / "bios")]) @@ -2217,7 +2233,8 @@ class TestManualPlatformPrompt(unittest.TestCase): answers = iter(["1", '"~/$RB_TEST_DIR/bios"']) with self.subTest(os_type=os_type), \ unittest.mock.patch.dict(os.environ, {"RB_TEST_DIR": "cards"}), \ - unittest.mock.patch("builtins.input", lambda _prompt="": next(answers)), \ + unittest.mock.patch("builtins.input", + lambda _prompt="", answers=answers: next(answers)), \ contextlib.redirect_stdout(io.StringIO()): chosen = install._prompt_manual_platform(os_type) self.assertEqual(chosen[0][1], Path.home() / "cards" / "bios") @@ -2313,6 +2330,7 @@ class TestLaunchboxDetectionPowershell(unittest.TestCase): capture_output=True, text=True, timeout=60, + check=False, ) finally: httpd.shutdown() @@ -2576,6 +2594,7 @@ class TestAvailablePlatforms(unittest.TestCase): capture_output=True, text=True, timeout=30, + check=False, ) self.assertEqual(proc.returncode, 0, proc.stdout + proc.stderr) self.assertTrue(marker.is_file(), "piped bootstrap did not download install.py") @@ -2693,7 +2712,7 @@ class TestAvailablePlatforms(unittest.TestCase): proc = subprocess.run( [shutil.which("sh"), str(root / "install.sh")], env={"PATH": f"{fake_bin}{os.pathsep}{tools}", "HOME": str(root)}, - capture_output=True, text=True, timeout=60, stdin=subprocess.DEVNULL) + capture_output=True, text=True, timeout=60, stdin=subprocess.DEVNULL, check=False) self.assertEqual(proc.returncode, 0, proc.stdout + proc.stderr) self.assertIn("ran True", proc.stdout) @@ -3174,7 +3193,7 @@ class TermuxStorageIsSetUpByTheBootstrap(unittest.TestCase): f"TERMUX_VERSION=0.118 /bin/sh {shlex.quote(str(root / 'install.sh'))}") proc = subprocess.run( [shutil.which("script"), "-qec", command, "/dev/null"], - capture_output=True, text=True, timeout=120, stdin=subprocess.DEVNULL) + capture_output=True, text=True, timeout=120, stdin=subprocess.DEVNULL, check=False) return proc, root def test_it_runs_once_then_the_installer(self): @@ -3209,7 +3228,7 @@ class APyLauncherWithoutARuntimeIsPassed(unittest.TestCase): proc = subprocess.run( [shutil.which("pwsh"), "-NoProfile", "-File", str(folder / "install.ps1")], env={**os.environ, "PATH": f"{fake_bin}{os.pathsep}/usr/bin/nonexistent"}, - capture_output=True, text=True, timeout=120, stdin=subprocess.DEVNULL) + capture_output=True, text=True, timeout=120, stdin=subprocess.DEVNULL, check=False) self.assertEqual(proc.returncode, 0, proc.stdout + proc.stderr) self.assertIn("installer ran", proc.stdout) @@ -3231,7 +3250,7 @@ class APowerShellDownloadThatNeverAnswersEnds(unittest.TestCase): ["pwsh", "-NoProfile", "-File", str(folder / "install.ps1"), "--check"], env={**os.environ, "RETROBIOS_INSTALL_URL": f"https://127.0.0.1:{port}/install.py"}, - capture_output=True, text=True, timeout=150, stdin=subprocess.DEVNULL) + capture_output=True, text=True, timeout=150, stdin=subprocess.DEVNULL, check=False) self.assertLess(time.monotonic() - started, 120) self.assertNotEqual(proc.returncode, 0) self.assertIn("could not be downloaded", " ".join((proc.stdout + proc.stderr).split())) @@ -3251,6 +3270,7 @@ class ThePowerShellWrapperPassesTheStatusOn(unittest.TestCase): proc = subprocess.run( ["pwsh", "-NoProfile", "-File", str(folder / "install.ps1")], capture_output=True, text=True, timeout=120, + check=False, ) self.assertEqual(proc.returncode, code, proc.stderr) self.assertNotIn("installer failed", proc.stdout + proc.stderr) @@ -3274,6 +3294,7 @@ class ThePowerShellWrapperPassesEveryArgument(unittest.TestCase): proc = subprocess.run( ["pwsh", "-NoProfile", "-File", str(folder / "install.ps1"), *args], capture_output=True, text=True, timeout=120, + check=False, ) self.assertEqual(proc.returncode, 0, proc.stderr) self.assertEqual(json.loads(proc.stdout), args) @@ -3707,7 +3728,7 @@ class ACardPreparedOnAComputerGetsItsBoard(unittest.TestCase): [sys.executable, "-c", code, str(REPO_ROOT), str(self.boot), "--platform", "batocera", "--dest", str(self.share), "--manifest", str(self.list), "--offline", "--check", "--events", *extra], - env=env, capture_output=True, text=True, timeout=120, stdin=subprocess.DEVNULL) + env=env, capture_output=True, text=True, timeout=120, stdin=subprocess.DEVNULL, check=False) events = [json.loads(line) for line in proc.stdout.splitlines() if line.startswith("{")] return proc.stdout + proc.stderr, events @@ -3795,7 +3816,7 @@ class APlatformWithoutTargetsSaysSoOffline(unittest.TestCase): [sys.executable, str(REPO_ROOT / "install.py"), "--platform", "misterfpga", "--dest", str(dest), "--target", "de10-nano", "--offline", "--no-input", "--dry-run", *extra], - capture_output=True, text=True, timeout=120, stdin=subprocess.DEVNULL) + capture_output=True, text=True, timeout=120, stdin=subprocess.DEVNULL, check=False) self.assertEqual(proc.returncode, 2, proc.stderr) self.assertIn("MiSTer FPGA has no hardware targets", proc.stderr) self.assertNotIn("targets/misterfpga.json", proc.stderr) @@ -3893,6 +3914,7 @@ class TheBoardTheSystemNamesIsTheTarget(unittest.TestCase): [sys.executable, str(REPO_ROOT / "install.py"), "--every-board", "--target", "bcm2711", "--platform", "batocera", "--dry-run"], capture_output=True, text=True, timeout=120, + check=False, ) self.assertEqual(result.returncode, 2) self.assertIn("--every-board", result.stderr) @@ -4837,7 +4859,10 @@ class WindowsSeenFromWsl(unittest.TestCase): self.assertEqual(os.environ["USERPROFILE"], str(self.root / "c" / "Users" / "me")) self.assertEqual(os.environ["APPDATA"], str(self.root / "c" / "Users" / "me" / "AppData" / "Roaming")) - self.assertEqual(os.environ["ProgramFiles"], "") + # ProgramFiles among them: cmd answered %ProgramFiles% unexpanded. + for name in sorted(set(install._WINDOWS_VARIABLES) - answers.keys()): + with self.subTest(variable=name): + self.assertEqual(os.environ[name], "") def test_a_steam_client_outside_program_files_is_found(self): @@ -5331,7 +5356,7 @@ class AnUnknownNameIsAnEvent(unittest.TestCase): [sys.executable, str(REPO_ROOT / "install.py"), "--dest", dest, "--check", "--events", "--no-input", *argv], env=env, capture_output=True, text=True, timeout=120, - stdin=subprocess.DEVNULL) + stdin=subprocess.DEVNULL, check=False) return proc.returncode, [json.loads(line) for line in proc.stdout.splitlines()] def test_each_refusal_says_why(self): @@ -5653,7 +5678,7 @@ class ThePowerShellOneLinerLeavesTheSessionAlone(unittest.TestCase): env = {**os.environ, "RETROBIOS_INSTALL_URL": "http://127.0.0.1/install.py"} env.pop("RETROBIOS_BOOTSTRAP", None) proc = subprocess.run(["pwsh", "-NoProfile", "-Command", script], cwd=REPO_ROOT, - env=env, capture_output=True, text=True, timeout=120) + env=env, capture_output=True, text=True, timeout=120, check=False) self.assertIn("must use HTTPS", proc.stderr) self.assertIn("EAP=Continue temporary=[] installer=[] bootstrap=[]", proc.stdout) @@ -7217,7 +7242,7 @@ class AStrippedPythonIsNamed(unittest.TestCase): return subprocess.run( [sys.executable, "-c", code, str(REPO_ROOT / "install.py"), *argv], env=env, capture_output=True, text=True, timeout=60, - stdin=subprocess.DEVNULL) + stdin=subprocess.DEVNULL, check=False) def test_a_missing_c_module_is_named(self): for hidden in ("zlib", "unicodedata"): diff --git a/tests/test_install_tui.py b/tests/test_install_tui.py index 7b44676a5..7555d886a 100644 --- a/tests/test_install_tui.py +++ b/tests/test_install_tui.py @@ -41,6 +41,8 @@ from pathlib import Path, PurePosixPath, PureWindowsPath from unittest import mock REPO_ROOT = Path(__file__).resolve().parent.parent +# install.py runs on 3.8, the scripts it is compared with need 3.9. +BUILDER_FLOOR = (3, 9) sys.path.insert(0, str(REPO_ROOT)) sys.path.insert(0, str(REPO_ROOT / "tests")) @@ -949,6 +951,13 @@ class Widgets(unittest.TestCase): def golden_states() -> dict: """One state per screen, filled as a run fills it.""" + states = _golden_setup_states() + states.update(_golden_plan_states()) + states.update(_golden_run_states()) + return states + + +def _golden_setup_states() -> dict: states = {} states["setup"] = fresh_state() states["setup"].notes = ["ES-DE found: its BIOS files go to each emulator, not to " @@ -985,6 +994,11 @@ def golden_states() -> dict: checking.platform, checking.dest, checking.stack = "retroarch", SYSTEM_DIR, ["checking"] checking.manifest, checking.started, checking.now = MANIFEST, 10.0, 14.2 states["checking"] = checking + return states + + +def _golden_plan_states() -> dict: + states = {} states["plan"] = checked_state() done = checked_state() done.check = {**CHECK, "present": 5, "missing": 0, "wrong_hash": 0, "bytes_needed": 0, @@ -1039,6 +1053,11 @@ def golden_states() -> dict: confirm.dry = {**CHECK, "files": 1, "present": 0, "missing": 1, "wrong_hash": 0, "bytes_needed": 16384, "not_installable": 0} states["confirm"] = confirm + return states + + +def _golden_run_states() -> dict: + states = {} installing = checked_state() installing.stack.append("installing") installing.run, installing.running = "install", True @@ -2509,7 +2528,7 @@ class WorkFolders(unittest.TestCase): self.addCleanup(signal.signal, number, previous) interrupt = signal.getsignal(signal.SIGINT) - def starting(*_args, **_kwargs): + def starting(*_args, number=number, **_kwargs): os.kill(os.getpid(), number) return fresh_state(), [("fetch", "retroarch")] @@ -2521,7 +2540,7 @@ class WorkFolders(unittest.TestCase): with mock.patch.object(install, "_TuiTerminal", self.Terminal), \ mock.patch.object(install.tempfile, "mkdtemp", return_value=str(work)), \ mock.patch.object(self.Terminal, "enter", - lambda _t: entered.append(True)), \ + lambda _t, entered=entered: entered.append(True)), \ mock.patch.object(install, "tui_start", side_effect=starting), \ mock.patch.object(install, "_open_local_sources"), \ mock.patch.object(install, "_tui_fetch") as fetch, \ @@ -7597,7 +7616,7 @@ class _CardFixtures: listing = self.root / f"{plat}.json" install_list = {"manifest_version": 2, "platform": plat, "files": files} listing.write_text(json.dumps(install_list)) - if sys.version_info < (3, 9): + if sys.version_info < BUILDER_FLOOR: # generate_pack.py's context managers need Python 3.9. return listing, None, {} sys.path.insert(0, str(REPO_ROOT / "scripts")) @@ -7725,7 +7744,7 @@ class _LineModeFindings(_CardFixtures): region=["us"]) self.assertEqual(code, 0, text) - @unittest.skipIf(sys.version_info < (3, 9), + @unittest.skipIf(sys.version_info < BUILDER_FLOOR, "generate_pack.py's context managers need Python 3.9") def test_a_pack_names_its_list_only_when_that_list_records_it(self): """A MinUI pack sent --core to install/minui.json, @@ -9225,7 +9244,7 @@ class PacksWordingAndDocs(unittest.TestCase): # a pack's own list records its systems. - @unittest.skipIf(sys.version_info < (3, 9), + @unittest.skipIf(sys.version_info < BUILDER_FLOOR, "generate_pack.py's context managers need Python 3.9") def test_a_pack_records_the_systems_of_its_files(self): sys.path.insert(0, str(REPO_ROOT / "scripts")) @@ -14673,7 +14692,7 @@ class ProvenCardsAndCounts(unittest.TestCase): # Root cause 6: the pages say what the installer shows. - @unittest.skipIf(sys.version_info < (3, 9), + @unittest.skipIf(sys.version_info < BUILDER_FLOOR, "the site generator needs Python 3.9") def test_which_pack_names_the_first_screen(self): """Which-pack said the command opens a screen @@ -16148,7 +16167,7 @@ class EmulatorChoiceMatchesTheEmulatorPack(unittest.TestCase): db_path = REPO_ROOT / "database.json" if not db_path.exists(): raise unittest.SkipTest("database.json is not built") - if sys.version_info < (3, 9): + if sys.version_info < BUILDER_FLOOR: # The builder's floor: install.py alone keeps 3.8. raise unittest.SkipTest("generate_pack.py needs Python 3.9 or newer") sys.path.insert(0, str(REPO_ROOT / "scripts")) diff --git a/tests/test_pin_build.py b/tests/test_pin_build.py index 6b27c186f..3a15fa91e 100644 --- a/tests/test_pin_build.py +++ b/tests/test_pin_build.py @@ -124,6 +124,15 @@ class HeldPinsReadTheirBuildFileAgain(unittest.TestCase): self.assertEqual(row.items, ["raine"]) +def _names_the_pin(value: str, profile: dict, source: str, pins: set, versions: set) -> bool: + if profile.get("pin_follows"): + # A build of the branch tip names the repository it + # clones, at no revision: RetroPie's advmame. + return value.split()[-1].rstrip("/").removesuffix(".git") == source + token = value.split()[-1].rsplit("/", 1)[-1].removesuffix(".tar.gz") + return value in pins or any(token in v or v in value for v in versions) + + class EveryBuildReferenceNamesThePin(unittest.TestCase): """Reads the repository: a pin_build value is what the platform builds, so it is the profile's source_commit or names its core_version, and the @@ -147,23 +156,20 @@ class EveryBuildReferenceNamesThePin(unittest.TestCase): source = str(profile.get("source") or "").rstrip("/").removesuffix(".git") - def names_it(value: str) -> bool: - if profile.get("pin_follows"): - # A build of the branch tip names the repository it - # clones, at no revision: RetroPie's advmame. - return value.split()[-1].rstrip("/").removesuffix(".git") == source - token = value.split()[-1].rsplit("/", 1)[-1].removesuffix(".tar.gz") - return value in pins or any(token in v or v in value for v in versions) - # A reference that only dates a config_reads entry names the build # the platform reads that file at, not this profile's pin. justifies_pin = profile.get("pin_frozen") or profile.get("pin_follows") - if justifies_pin and not any(names_it(str(r["value"])) for r in references): + if justifies_pin and not any( + _names_the_pin(str(r["value"]), profile, source, pins, versions) + for r in references + ): disagree.append(name) - for reference in references: - if not cf.pin_build_revision(reference, REPO_ROOT / "platforms"): - disagree.append(f"{name}: {reference['platform']} is not read from " - f"{reference['repo']}") + disagree.extend( + f"{name}: {reference['platform']} is not read from " + f"{reference['repo']}" + for reference in references + if not cf.pin_build_revision(reference, REPO_ROOT / "platforms") + ) self.assertEqual(disagree, []) diff --git a/tests/test_site_copy.py b/tests/test_site_copy.py index 9a316fab5..dfd08dac5 100644 --- a/tests/test_site_copy.py +++ b/tests/test_site_copy.py @@ -151,6 +151,164 @@ def guide_part(markdown: str) -> str: return markdown[: match.start()] if match else markdown +class _PageParser: + """The state parse() carries from one line to the next.""" + + def __init__(self) -> None: + self.page = Page() + self.seen_words = 0 + self.details = 0 # depth of collapsed blocks + self.tab = 0 # the tab of a group being read, 0 outside a group + self.fence: str | None = None + self.current: list[str] = [] + self.kind = "paragraph" + self.run = 0 + + def flush(self) -> None: + page = self.page + if self.current: + body = strip_inline(" ".join(self.current)) + if WORD.search(body): + kind = self.kind + term = page.blocks[-1].text.lower() if kind == "definition" and page.blocks else "" + block = Block(kind, body, self.details > 0, term, self.tab > 1) + page.blocks.append(block) + if (page.before_action is None and not block.collapsed + and not block.hidden and kind not in ("table", "heading")): + self.seen_words += count_words(body) + self.current = [] + if self.kind in ("item", "definition", "heading"): + self.kind = "paragraph" + + def act(self) -> None: + self.flush() + if self.page.before_action is None: + self.page.before_action = self.seen_words + + def end_run(self) -> None: + if self.run: + self.page.list_runs.append(self.run) + self.run = 0 + + def feed(self, raw: str) -> None: + line = raw.rstrip() + stripped = line.strip() + indent = len(line) - len(line.lstrip()) + if self.fence: + if stripped.startswith(self.fence): + self.fence = None + return + if self._markup(stripped): + return + if stripped.startswith("#"): + self._heading(stripped) + return + if stripped.startswith("|"): + self._table_row(stripped) + return + self._prose(stripped, indent) + + def _markup(self, stripped: str) -> bool: + """Fences, blank lines and HTML: True when the line is consumed.""" + if stripped.startswith(("```", "~~~")): + self.fence = stripped[:3] + if self.tab < 2: + self.act() + return True + if not stripped: + self.flush() + return True + if stripped.startswith("import ") and stripped.endswith(";"): + return True + if stripped.startswith(":::"): + self.flush() + return True + if self._container(stripped): + return True + if "rb-button" in stripped or "rb-tile" in stripped or stripped.startswith( + (" bool: + """Collapsed blocks and tab groups: True when the line is consumed.""" + if stripped.startswith(""): + self.flush() + self.details = max(0, self.details - 1) + return True + if stripped.startswith(""): + self.flush() + self.tab = 0 + return True + return False + + def _heading(self, stripped: str) -> None: + self.flush() + self.end_run() + self.kind = "heading" + self.current = [re.sub(r"\s*\{[^}]*\}\s*$", "", stripped.lstrip("#").strip())] + self.flush() + self.kind = "paragraph" + + def _table_row(self, stripped: str) -> None: + if self.kind != "table": + self.flush() + self.kind = "table" + if not re.fullmatch(r"\|[\s:|-]+\|?", stripped): + self.current.append(stripped.replace("|", " ")) + + def _prose(self, stripped: str, indent: int) -> None: + if self.kind == "table": + self.flush() + self.kind = "paragraph" + item = re.match(r"(?:[-*+]|\d+\.)\s+(.*)", stripped) + definition = re.match(r":\s+(.*)", stripped) + if item: + self.flush() + self.kind = "item" + self.run += 1 + self.current = [item.group(1)] + return + if definition: + self.flush() + page = self.page + if page.blocks and page.blocks[-1].kind == "paragraph": + page.blocks[-1].kind = "term" + self.kind = "definition" + self.current = [definition.group(1)] + return + if self.kind == "item" and indent == 0: + self.flush() + self.kind = "paragraph" + if self.kind == "paragraph": + self.end_run() + if not self.current and self.kind in ("item", "definition") and indent == 0: + self.kind = "paragraph" + self.current.append(stripped) + + def finish(self) -> Page: + self.flush() + if self.run: + self.page.list_runs.append(self.run) + return self.page + + def parse(markdown: str) -> Page: """Blocks of prose a reader sees, code and HTML left out. @@ -161,131 +319,10 @@ def parse(markdown: str) -> Page: text = guide_part(markdown) text = re.sub(r"", "", text, flags=re.S) text = re.sub(r"", "", text, flags=re.S) - page = Page() - seen_words = 0 - details = 0 # depth of collapsed blocks - tab = 0 # the tab of a group being read, 0 outside a group - fence: str | None = None - current: list[str] = [] - kind = "paragraph" - run = 0 - - def flush() -> None: - nonlocal current, seen_words, kind - if current: - body = strip_inline(" ".join(current)) - if WORD.search(body): - term = page.blocks[-1].text.lower() if kind == "definition" and page.blocks else "" - block = Block(kind, body, details > 0, term, tab > 1) - page.blocks.append(block) - if (page.before_action is None and not block.collapsed - and not block.hidden and kind not in ("table", "heading")): - seen_words += count_words(body) - current = [] - if kind in ("item", "definition", "heading"): - kind = "paragraph" - - def act() -> None: - flush() - if page.before_action is None: - page.before_action = seen_words - + parser = _PageParser() for raw in text.splitlines(): - line = raw.rstrip() - stripped = line.strip() - indent = len(line) - len(line.lstrip()) - if fence: - if stripped.startswith(fence): - fence = None - continue - if stripped.startswith(("```", "~~~")): - fence = stripped[:3] - if tab < 2: - act() - continue - if not stripped: - flush() - continue - if stripped.startswith("import ") and stripped.endswith(";"): - continue - if stripped.startswith(":::"): - flush() - continue - if stripped.startswith(""): - flush() - details = max(0, details - 1) - continue - if stripped.startswith(""): - flush() - tab = 0 - continue - if "rb-button" in stripped or "rb-tile" in stripped or stripped.startswith( - (" list[str]: @@ -298,9 +335,11 @@ def banned(block: Block, level: str) -> list[str]: return [] for sentence in split_sentences(text) or [text]: lower = sentence.lower() - for phrase in FILLER: - if re.search(rf"(? set[str]: return held +def _entries_by_system(platforms: list[dict], profiles: dict) -> dict[str, list[dict]]: + entries: dict[str, list[dict]] = {} + for config in platforms: + for sys_id, system in config.get("systems", {}).items(): + entries.setdefault(sys_id, []).extend(system.get("files") or []) + for profile in profiles.values(): + systems = [str(s) for s in profile.get("systems") or []] + for fe in profile.get("files") or []: + if not isinstance(fe, dict): + continue + owners = {str(fe["system"])} if fe.get("system") else set() + owners.update(str(s) for s in fe.get("systems") or []) + if not owners and len(systems) == 1: + owners = set(systems) + for owner in owners: + entries.setdefault(owner, []).append(fe) + return entries + + +def _held_sections( + ids: Iterable[str], entries: dict[str, list[dict]], board_sections: dict, db: dict +) -> dict[str, set[tuple[str, str]]]: + """Id -> the (manufacturer, console) sections holding its files.""" + from common import resolve_local_file + + # Where each content has a card. + places: dict[str, set[tuple[str, str, str]]] = {} + for mfr, consoles in board_sections.items(): + for console, files in consoles.items(): + for f in files: + places.setdefault(f["sha1"], set()).add((mfr, console, f["name"])) + by_path = {entry.get("path"): sha1 for sha1, entry in db["files"].items()} + held: dict[str, set[tuple[str, str]]] = {} + for sys_id in ids: + sections: set[tuple[str, str]] = set() + for fe in entries.get(sys_id, []): + if fe.get("category") == "bios_zip": + for sha1 in _archives_held(fe, db): + sections.update((m, c) for m, c, _ in places.get(sha1, set())) + continue + local, status = resolve_local_file(fe, db) + if not _accepts(fe, local, status): + continue + sha1 = by_path.get(local) + if sha1 is not None: + sections.update((m, c) for m, c, _ in places.get(sha1, set())) + if sections: + held[sys_id] = sections + return held + + @unittest.skipUnless((REPO_ROOT / "database.json").exists(), "database.json is not built") class SystemLinks(unittest.TestCase): @@ -101,7 +153,6 @@ class SystemLinks(unittest.TestCase): list_registered_platforms, load_emulator_profiles, load_platform_config, - resolve_local_file, ) from generate_site import _group_by_manufacturer, arcade_board_sections @@ -124,46 +175,9 @@ class SystemLinks(unittest.TestCase): ] cls.ids = siterender.system_ids(profiles, platforms) - entries: dict[str, list[dict]] = {} - for config in platforms: - for sys_id, system in config.get("systems", {}).items(): - entries.setdefault(sys_id, []).extend(system.get("files") or []) - for profile in profiles.values(): - systems = [str(s) for s in profile.get("systems") or []] - for fe in profile.get("files") or []: - if not isinstance(fe, dict): - continue - owners = {str(fe["system"])} if fe.get("system") else set() - owners.update(str(s) for s in fe.get("systems") or []) - if not owners and len(systems) == 1: - owners = set(systems) - for owner in owners: - entries.setdefault(owner, []).append(fe) - - # Where each content has a card. - places: dict[str, set[tuple[str, str, str]]] = {} - for mfr, consoles in cls.sections.items(): - for console, files in consoles.items(): - for f in files: - places.setdefault(f["sha1"], set()).add((mfr, console, f["name"])) - by_path = {entry.get("path"): sha1 for sha1, entry in db["files"].items()} - # Id -> the (manufacturer, console) sections holding its files. - cls.held: dict[str, set[tuple[str, str]]] = {} - for sys_id in cls.ids: - sections: set[tuple[str, str]] = set() - for fe in entries.get(sys_id, []): - if fe.get("category") == "bios_zip": - for sha1 in _archives_held(fe, db): - sections.update((m, c) for m, c, _ in places.get(sha1, set())) - continue - local, status = resolve_local_file(fe, db) - if not _accepts(fe, local, status): - continue - sha1 = by_path.get(local) - if sha1 is not None: - sections.update((m, c) for m, c, _ in places.get(sha1, set())) - if sections: - cls.held[sys_id] = sections + entries = _entries_by_system(platforms, profiles) + cls.held: dict[str, set[tuple[str, str]]] = _held_sections( + cls.ids, entries, cls.sections, db) finally: os.chdir(previous) diff --git a/tests/test_target_scrapers.py b/tests/test_target_scrapers.py index 3a7a203eb..9b74162f4 100644 --- a/tests/test_target_scrapers.py +++ b/tests/test_target_scrapers.py @@ -33,6 +33,57 @@ def _refuse(*_args, **_kwargs): raise urllib.error.HTTPError("https://api.github.com/x", 403, "rate limited", {}, None) +class _Body: + def __init__(self, body: str | bytes): + self.body = body.encode() if isinstance(body, str) else body + + def __enter__(self): + return self + + def __exit__(self, *exc): + return False + + def read(self): + return self.body + + +def _serve_batocera(boards: list[str], refuse_board: bool): + def urlopen(request, *_a, **_k): + url = request.full_url + if "/tags" in url: + return _Body(b'[{"name": "batocera-43"}]') + if "/contents/configs" in url: + return _Body(json.dumps([{"name": b} for b in boards]).encode()) + if "/contents/buildroot" in url: + return _Body(b'{"sha": "0123abc"}') + if url.endswith("x86_wow64.board"): + # Builds the 32-bit Wine package, not an image. + return _Body(b"BR2_PACKAGE_BATOCERA_TARGET_X86=y\n") + if url.endswith(".board"): + if refuse_board: + _refuse() + return _Body(b"BR2_PACKAGE_BATOCERA_TARGET_X86_64=y\n" + b"BR2_PACKAGE_BATOCERA_SYSTEM=y\n") + if "/git/trees/" in url: + return _Body(b'{"tree": [], "truncated": false}') + if url.endswith("retroarch.mk"): + return _Body(b"RETROARCH_CONF_OPTS = --enable-networking\n") + if url.startswith("https://raw.githubusercontent.com/") and url.count("/") == 6: + return _Body(b'source "$BR2_EXTERNAL_BATOCERA_PATH/' + b'package/batocera/core/batocera-system/Config.in"\n') + if url.endswith("Config.in"): + return _Body(b"config BR2_PACKAGE_BATOCERA_SYSTEM\n" + b"\tselect BR2_PACKAGE_MGBA\n\n" + b"config BR2_TARGET_BATOCERA_IMAGES\n\tstring \"x\"\n" + b"\tdefault \"x86_64\" if BR2_PACKAGE_BATOCERA_TARGET_X86_64\n") + return _Body( + b"gba:\n emulators:\n libretro:\n" + b" mgba: {requireAnyOf: [BR2_PACKAGE_MGBA]}\n" + ) + + return urlopen + + class FailedRequestsStopTheScrape(unittest.TestCase): def test_every_scraper_raises(self): for module in ( @@ -66,68 +117,18 @@ class FailedRequestsStopTheScrape(unittest.TestCase): def test_batocera_needs_its_boards(self): """No board listed, or one board unreadable, used to print a warning and write the targets file without those boards.""" - - class _Body: - def __init__(self, body: bytes): - self.body = body - - def __enter__(self): - return self - - def __exit__(self, *exc): - return False - - def read(self): - return self.body - - def serve(boards: list[str], refuse_board: bool): - def urlopen(request, *_a, **_k): - url = request.full_url - if "/tags" in url: - return _Body(b'[{"name": "batocera-43"}]') - if "/contents/configs" in url: - return _Body(json.dumps([{"name": b} for b in boards]).encode()) - if "/contents/buildroot" in url: - return _Body(b'{"sha": "0123abc"}') - if url.endswith("x86_wow64.board"): - # Builds the 32-bit Wine package, not an image. - return _Body(b"BR2_PACKAGE_BATOCERA_TARGET_X86=y\n") - if url.endswith(".board"): - if refuse_board: - _refuse() - return _Body(b"BR2_PACKAGE_BATOCERA_TARGET_X86_64=y\n" - b"BR2_PACKAGE_BATOCERA_SYSTEM=y\n") - if "/git/trees/" in url: - return _Body(b'{"tree": [], "truncated": false}') - if url.endswith("retroarch.mk"): - return _Body(b"RETROARCH_CONF_OPTS = --enable-networking\n") - if url.startswith("https://raw.githubusercontent.com/") and url.count("/") == 6: - return _Body(b'source "$BR2_EXTERNAL_BATOCERA_PATH/' - b'package/batocera/core/batocera-system/Config.in"\n') - if url.endswith("Config.in"): - return _Body(b"config BR2_PACKAGE_BATOCERA_SYSTEM\n" - b"\tselect BR2_PACKAGE_MGBA\n\n" - b"config BR2_TARGET_BATOCERA_IMAGES\n\tstring \"x\"\n" - b"\tdefault \"x86_64\" if BR2_PACKAGE_BATOCERA_TARGET_X86_64\n") - return _Body( - b"gba:\n emulators:\n libretro:\n" - b" mgba: {requireAnyOf: [BR2_PACKAGE_MGBA]}\n" - ) - - return urlopen - for boards, refuse_board in (([], False), (["batocera-x86_64.board"], True)): with self.subTest(boards=boards), mock.patch.object( batocera_targets_scraper.urllib.request, "urlopen", - serve(boards, refuse_board), + _serve_batocera(boards, refuse_board), ), self.assertRaises(RuntimeError): batocera_targets_scraper.Scraper().fetch_targets() with mock.patch.object( batocera_targets_scraper.urllib.request, "urlopen", - serve(["batocera-x86_64.board", "batocera-x86_wow64.board"], False), + _serve_batocera(["batocera-x86_64.board", "batocera-x86_wow64.board"], False), ): targets = batocera_targets_scraper.Scraper().fetch_targets()["targets"] self.assertEqual(targets["x86_64"]["cores"], ["mgba"]) @@ -434,41 +435,28 @@ class KnulliPerBoard(unittest.TestCase): raw = f"https://raw.githubusercontent.com/knulli-cfw/knulli-linux/{pin}/" api = "https://api.github.com/repos/knulli-cfw/knulli-linux/contents/" seen: list[str] = [] - - class _Body: - def __init__(self, body: str): - self.body = body.encode() - - def __enter__(self): - return self - - def __exit__(self, *exc): - return False - - def read(self): - return self.body + names = [p.removeprefix("configs/") for p in self.FILES if p.startswith("configs/")] + exact = { + f"{api}configs?ref={pin}": json.dumps([{"name": n} for n in names]), + f"{api}buildroot?ref={pin}": '{"sha": "c2d7985b"}', + f"{api}batocera?ref={pin}": '{"sha": "487014d9"}', + f"{raw}board/r16/retroarch.cfg": 'menu_show_core_updater = "false"\n', + f"{raw}package/retroarch/retroarch/retroarch.mk": + "RETROARCH_CONF_OPTS = --enable-networking\n", + ("https://raw.githubusercontent.com/batocera-linux/batocera.linux/" + "487014d9/package/batocera/emulators/ppsspp/Config.in"): + "config BR2_PACKAGE_PPSSPP\n\tselect BR2_PACKAGE_PPSSPP_ASSETS\n", + } def urlopen(request, *_a, **_k): url = request.full_url seen.append(url) - if url == f"{api}configs?ref={pin}": - names = [p.removeprefix("configs/") for p in self.FILES if p.startswith("configs/")] - return _Body(json.dumps([{"name": n} for n in names])) - if url == f"{api}buildroot?ref={pin}": - return _Body('{"sha": "c2d7985b"}') - if url == f"{api}batocera?ref={pin}": - return _Body('{"sha": "487014d9"}') + if url in exact: + return _Body(exact[url]) if "/git/trees/" in url: # A board config that hides the downloader leaves its URL. cfg = "board/r16/retroarch.cfg" if "knulli-linux" in url else "x" return _Body(json.dumps({"tree": [{"path": cfg}], "truncated": False})) - if url == f"{raw}board/r16/retroarch.cfg": - return _Body('menu_show_core_updater = "false"\n') - if url == f"{raw}package/retroarch/retroarch/retroarch.mk": - return _Body("RETROARCH_CONF_OPTS = --enable-networking\n") - if url == ("https://raw.githubusercontent.com/batocera-linux/batocera.linux/" - "487014d9/package/batocera/emulators/ppsspp/Config.in"): - return _Body("config BR2_PACKAGE_PPSSPP\n\tselect BR2_PACKAGE_PPSSPP_ASSETS\n") if url == f"{raw}package/utils/vtree/Config.in": raise urllib.error.HTTPError(url, 404, "Not Found", {}, None) if url.endswith("/c2d7985b/arch/Config.in.arm"): @@ -478,7 +466,7 @@ class KnulliPerBoard(unittest.TestCase): path = url.removeprefix(raw) if path in self.FILES: return _Body(self.FILES[path]) - _refuse() + return _refuse() with mock.patch.object(batocera_targets_scraper.urllib.request, "urlopen", urlopen): data = knulli_targets_scraper.Scraper().fetch_targets()