From 4eacb6ff39ed2a4660ba83b27ce283963e5d6179 Mon Sep 17 00:00:00 2001 From: Abdessamad Derraz <3028866+Abdess@users.noreply.github.com> Date: Tue, 17 Nov 2026 07:07:48 +0100 Subject: [PATCH] chore: lint scripts and tests with ruff pyproject.toml now carries the ruff rule set: pyflakes, the B rules, simplify, perf, pyupgrade, complexity and size limits. This commit applies the fixes that change no behavior and the small defects the first run named: - tests/test_install.py used argparse without importing it - three loops rebound the outer `profile` with each layout (packextras, slots, verify); the loop variable is now `layout` - profile_sync loops shadowed dataclasses.field - generate_readme and packextras computed values nothing read - stale noqa markers for rules the project does not enforce Complexity, size and the remaining findings are handled next. --- install.ps1 | 2 +- install.py | 36 +++--- install.sh | 2 +- install/launchers/index.json | 16 +-- pyproject.toml | 33 ++++++ scripts/archive_build.py | 10 +- scripts/auto_fetch.py | 4 +- scripts/autorun.py | 2 +- scripts/build_port.py | 6 +- scripts/bundled_only.py | 2 +- scripts/check_buildbot_system.py | 5 +- scripts/check_freshness.py | 40 +++---- scripts/common.py | 47 ++++---- scripts/core_probe.py | 18 +-- scripts/cross_reference.py | 6 +- scripts/derivations.py | 4 +- scripts/export_native.py | 2 +- scripts/exporter/batocera_exporter.py | 4 +- scripts/exporter/candidates.py | 5 +- scripts/exporter/romm_exporter.py | 2 +- scripts/find_pinned_revision.py | 2 +- scripts/game_rules.py | 2 +- scripts/generate_games_index.py | 4 +- scripts/generate_installer_doc.py | 16 +-- scripts/generate_pack.py | 8 +- scripts/generate_readme.py | 14 +-- scripts/generate_site.py | 73 ++++++------ scripts/identity.py | 4 +- scripts/indexnow.py | 2 +- scripts/largefiles.py | 15 ++- scripts/launchers.py | 22 ++-- scripts/list_platforms.py | 2 +- scripts/make_demo.py | 2 +- scripts/packextras.py | 14 +-- scripts/packverify.py | 2 +- scripts/pipeline.py | 42 +++---- scripts/profile_sync.py | 36 +++--- scripts/provenance_report.py | 4 +- scripts/refresh_data_dirs.py | 28 +++-- scripts/refresh_stale.py | 2 +- scripts/region.py | 2 +- scripts/region_audit.py | 2 +- scripts/region_check.py | 14 +-- scripts/retired_files.py | 2 +- scripts/romset_recipes.py | 6 +- scripts/scraper/batocera_launchers.py | 6 +- scripts/scraper/configgen_launchers.py | 4 +- scripts/scraper/coreinfo_scraper.py | 4 +- scripts/scraper/emudeck_scraper.py | 6 +- scripts/scraper/game_dat_importer.py | 1 - scripts/scraper/knulli_scraper.py | 4 +- scripts/scraper/retrobat_launchers.py | 2 +- scripts/scraper/retrodeck_scraper.py | 2 +- scripts/scraper/retropie_launchers.py | 2 +- scripts/scraper/romfolders/__main__.py | 4 +- scripts/scraper/targets/__init__.py | 4 +- .../targets/retropie_targets_scraper.py | 2 +- .../targets/rocknix_targets_scraper.py | 2 +- scripts/sect233r1.py | 2 +- scripts/site_markdown.py | 2 +- scripts/sitecollection.py | 8 +- scripts/sitediagrams.py | 18 +-- scripts/sitemeasurements.py | 4 +- scripts/sitesources.py | 6 +- scripts/sitesteps.py | 2 +- scripts/slot.py | 2 +- scripts/slots.py | 16 +-- scripts/standalone_probe.py | 2 +- scripts/upstream.py | 4 +- scripts/validate_schemas.py | 10 +- scripts/validate_site.py | 8 +- scripts/validation.py | 1 - scripts/verify.py | 28 ++--- scripts/ziptools.py | 4 +- tests/test_adler32_resolution.py | 4 +- tests/test_archive_choice.py | 4 +- tests/test_archive_recipes.py | 6 +- tests/test_artifact_lock.py | 42 +++---- tests/test_atomic_artifacts.py | 12 +- tests/test_audit_regressions.py | 51 ++++----- tests/test_autorun.py | 4 +- tests/test_batocera_md5_list.py | 2 +- tests/test_cache_independent_counts.py | 4 +- tests/test_casefold_cache.py | 8 +- tests/test_check_freshness.py | 16 +-- tests/test_check_release.py | 2 +- tests/test_content_declarations.py | 4 +- tests/test_core_probe.py | 4 +- tests/test_crypto_unique_data.py | 2 +- tests/test_crypto_verify.py | 2 +- tests/test_declared_names.py | 2 +- tests/test_dedup.py | 8 +- tests/test_directory_entries.py | 6 +- tests/test_doc_pages.py | 22 ++-- tests/test_doc_surfaces.py | 12 +- tests/test_download.py | 5 +- tests/test_e2e.py | 8 +- tests/test_emuelec_targets.py | 2 +- tests/test_emulator_pack_counts.py | 6 +- tests/test_entry_categories.py | 4 +- tests/test_export_counts.py | 48 ++++---- tests/test_export_native_layer.py | 6 +- tests/test_export_report.py | 18 +-- tests/test_exporters.py | 60 +++++----- tests/test_extract_targets.py | 2 +- tests/test_fileless_audit.py | 5 +- tests/test_handheld_launchers.py | 4 +- tests/test_hash_merge.py | 10 +- tests/test_identity.py | 2 +- tests/test_install.py | 107 +++++++++--------- tests/test_install_app.py | 3 +- tests/test_install_cores.py | 5 +- tests/test_install_experience.py | 12 +- tests/test_install_expert.py | 9 +- tests/test_install_games.py | 4 +- tests/test_install_journeys.py | 2 +- tests/test_install_offline.py | 10 +- tests/test_install_pack.py | 2 +- tests/test_install_selection.py | 10 +- tests/test_install_tui.py | 47 ++++---- tests/test_launcher_evidence.py | 14 +-- tests/test_launcher_gaps.py | 8 +- tests/test_launcher_layer.py | 8 +- tests/test_launchers_retrobat.py | 7 +- tests/test_launchers_retropie.py | 2 +- tests/test_mame_devices.py | 5 +- tests/test_measurements.py | 10 +- tests/test_name_tiebreak.py | 2 +- tests/test_optional_dependencies.py | 4 +- tests/test_pack_failures.py | 9 +- tests/test_pack_file_names.py | 2 +- tests/test_pack_member_identity.py | 2 +- tests/test_path_suffix.py | 4 +- tests/test_port.py | 6 +- tests/test_profile_sync.py | 59 +++++----- tests/test_prose_style.py | 22 +--- tests/test_provenance.py | 12 +- tests/test_refresh_data_dirs.py | 17 ++- tests/test_refresh_failures.py | 2 +- tests/test_refresh_stale.py | 8 +- tests/test_region.py | 14 +-- tests/test_region_platform_index.py | 2 +- tests/test_region_required_only.py | 2 +- tests/test_retired_files.py | 2 +- tests/test_romset_recipes.py | 16 +-- tests/test_save_root.py | 2 +- tests/test_scraper_contract.py | 72 ++++++------ tests/test_site_agents.py | 8 +- tests/test_site_bootstrap.py | 2 +- tests/test_site_components.py | 2 +- tests/test_site_copy.py | 1 - tests/test_site_demo.py | 10 +- tests/test_site_density_cards.py | 1 - tests/test_site_emulators.py | 4 +- tests/test_site_entry.py | 2 +- tests/test_site_exports.py | 86 +++++++------- tests/test_site_funnel.py | 3 +- tests/test_site_handheld.py | 4 +- tests/test_site_images.py | 2 +- tests/test_site_insights.py | 2 +- tests/test_site_integration.py | 12 +- tests/test_site_nav.py | 2 +- tests/test_site_page_text.py | 6 +- tests/test_site_picker.py | 2 +- tests/test_site_reference.py | 16 +-- tests/test_site_system_sections.py | 4 +- tests/test_site_systems.py | 2 +- tests/test_site_validation.py | 3 +- tests/test_site_weight.py | 3 +- tests/test_slots.py | 12 +- tests/test_system_pack_extras.py | 2 +- tests/test_system_selection.py | 12 +- tests/test_target_names.py | 24 ++-- tests/test_target_scrapers.py | 48 ++++---- tests/test_target_verify.py | 7 +- tests/test_tool_messages.py | 20 ++-- tests/test_truth_layout.py | 6 +- tests/test_upstream.py | 4 +- tests/test_validate_pr.py | 20 ++-- tests/test_validate_pr_flow.py | 2 +- tests/test_validated_choice.py | 24 ++-- tests/test_verify_listing.py | 38 +++---- tests/test_version_basis.py | 4 +- tests/test_which_pack.py | 4 +- tests/test_workflow_paths.py | 4 +- tests/test_zipped_member.py | 4 +- 186 files changed, 1001 insertions(+), 1058 deletions(-) diff --git a/install.ps1 b/install.ps1 index 93b44ad56..1aa4fabb6 100644 --- a/install.ps1 +++ b/install.ps1 @@ -16,7 +16,7 @@ # and Invoke-WebRequest throws on a cut transfer before the hash is read: # the site's build rewrites this line there (scripts/sitebootstrap.py). $mismatchAdvice = "The download was most likely cut short: try again. Within minutes of an update of this project the two files can come from caches of different ages. Waiting five minutes settles that." - $defaultInstallSha256 = "4b8e2e8e5343dbf75f6c9b089993cce3b7f64ad1e7a5a6c91993a07ec9674bc6" + $defaultInstallSha256 = "5ff90f40cfcdab22fd1056f9a40ea2193541155eaf4c1ab48c8d16ac1f230c44" # The pin above refuses any changed byte: this cap only stops a body that # cannot be the installer (a sign-in portal's page) before it is hashed. $maximumInstallerBytes = 8MB diff --git a/install.py b/install.py index e3f48ed39..f83580005 100644 --- a/install.py +++ b/install.py @@ -353,7 +353,7 @@ def _enable_ansi() -> bool: if os.name != "nt": return True try: - import ctypes # noqa: PLC0415 + import ctypes kernel32 = ctypes.windll.kernel32 # type: ignore[attr-defined] handle = kernel32.GetStdHandle(-11) @@ -2857,7 +2857,7 @@ def _read_registry(key: str, value: str) -> str | None: """A string value of the Windows registry, read natively or, under WSL, through reg.exe. None when the key, the value or the means is missing.""" if os.name == "nt": - import winreg # noqa: PLC0415 + import winreg hive, _, subkey = key.partition("\\") roots = {"HKCU": winreg.HKEY_CURRENT_USER, "HKLM": winreg.HKEY_LOCAL_MACHINE} @@ -3476,7 +3476,7 @@ def did_you_mean( by the letters and digits of a typed name, the names it stands for here, suggested instead of the close ones. """ - import difflib # noqa: PLC0415 + import difflib by_key: dict[str, str] = {} for name in known: @@ -4624,7 +4624,7 @@ _RAW_ERRORS = threading.Event() def _default_ca_present() -> bool: """Whether the certificates this Python reads by default exist.""" - import ssl # noqa: PLC0415 + import ssl paths = ssl.get_default_verify_paths() for value in (os.environ.get("SSL_CERT_FILE"), paths.cafile, paths.openssl_cafile): @@ -5221,7 +5221,7 @@ def canonical_region(raw: str) -> str: key = raw.strip().lower() key = REGION_ALIASES.get(key, key) if key not in REGIONS: - import difflib # noqa: PLC0415 + import difflib close = difflib.get_close_matches(key, [*REGION_ALIASES, *REGIONS], n=3, cutoff=0.5) hint = f" Close matches: {', '.join(close)}." if close else "" @@ -10150,7 +10150,7 @@ def standalone_plan( RetroArch had no tree to copy from. The first list that holds a name for a folder serves it. """ - from fnmatch import fnmatch # noqa: PLC0415 + from fnmatch import fnmatch plan: dict[Path, dict[str, dict]] = {} for manifest in manifests: @@ -10674,7 +10674,7 @@ def _drive_not_removable(mount: Path) -> bool: False where it says nothing.""" if os.name == "nt": try: - import ctypes # noqa: PLC0415 + import ctypes kind = ctypes.windll.kernel32.GetDriveTypeW(str(mount)) # type: ignore[attr-defined] except (AttributeError, OSError): return False @@ -14463,7 +14463,7 @@ def fat32_drive(folder: Path) -> bool: probe = probe.parent if os.name == "nt": try: - import ctypes # noqa: PLC0415 + import ctypes root = ctypes.create_unicode_buffer(261) kind = ctypes.create_unicode_buffer(261) kernel = ctypes.windll.kernel32 # type: ignore[attr-defined] @@ -21766,7 +21766,7 @@ def tui_blocker( return (f"the terminal is {cols}x{rows}, smaller than " f"{TUI_MIN_COLS}x{TUI_MIN_ROWS}") if os.name == "nt": - import importlib # noqa: PLC0415 + import importlib try: importlib.import_module("msvcrt") @@ -21776,7 +21776,7 @@ def tui_blocker( return "this console does not draw escape sequences (Windows 10 or later does)" return "" try: - import termios # noqa: PLC0415 + import termios except ImportError: return "this Python has no termios to read keys" try: @@ -25002,7 +25002,7 @@ def _tui_key(state: TuiState, key: TuiKey) -> list[tuple]: step = 1 if focus == 0 else -1 order = list(range(focus, -1, -1) if step < 0 else range(focus, len(rows))) if wrap and moved: - order += range(last, focus, -1) if step < 0 else range(0, focus) + order += range(last, focus, -1) if step < 0 else range(focus) focus = next((index for index in order if rows[index].action != "heading"), max(0, min(state.focus.get(screen, 0), last))) state.focus[screen] = focus @@ -28963,7 +28963,7 @@ class _TuiTerminal: def enter(self) -> None: if os.name != "nt": - import termios # noqa: PLC0415 + import termios # Entered again after a stop, the mode to go back to stays the # one found the first time. @@ -28993,7 +28993,7 @@ class _TuiTerminal: self.write(_SCREEN_OFF) finally: if self.saved is not None: - import termios # noqa: PLC0415 + import termios saved, self.saved = self.saved, None termios.tcsetattr(self.fd, termios.TCSADRAIN, saved) @@ -29036,7 +29036,7 @@ class _TuiTerminal: if self.ended: time.sleep(timeout) return [] - import select # noqa: PLC0415 + import select if not select.select([self.fd], [], [], timeout)[0]: # A paste whose end never came, after a second of silence. @@ -29063,7 +29063,7 @@ class _TuiTerminal: return self.decoder.feed(self.input.decode(data)) def _console_keys(self, timeout: float) -> list[TuiKey]: - import msvcrt # noqa: PLC0415 + import msvcrt end = time.monotonic() + timeout keys: list[TuiKey] = [] @@ -29497,7 +29497,7 @@ def run_tui(args: argparse.Namespace) -> int: if terminating["signal"] and state.screen == "result": # The result is printed in the terminal on the way out. state.exit_code = state.code if state.code is not None else 1 - except Exception as exc: # noqa: BLE001 + except Exception as exc: if flags["term"] or _closed_terminal(exc, terminal): # The window closed under a screen that was changing, or the # SIGCONT that comes with its SIGHUP put the screen back: the @@ -29587,7 +29587,7 @@ def _terminal_gone(terminal: _TuiTerminal) -> bool: error is taken as it reads.""" if os.name == "nt": return True - import termios # noqa: PLC0415 + import termios try: termios.tcgetattr(terminal.fd) @@ -29642,7 +29642,7 @@ def _tui_cleanup( """Stop the child, put the terminal and the signal handlers back: what failed.""" failures: tuple = (OSError, ValueError) if os.name != "nt": - import termios # noqa: PLC0415 + import termios failures += (termios.error,) problems: list[str] = [] diff --git a/install.sh b/install.sh index b6979ddfe..604ab4f14 100755 --- a/install.sh +++ b/install.sh @@ -23,7 +23,7 @@ DEFAULT_INSTALL_URL="https://raw.githubusercontent.com/Abdess/retrobios/main/ins # curl or wget stop on a cut transfer before the hash is read: the site's # build rewrites this line there (scripts/sitebootstrap.py). MISMATCH_ADVICE="The download was most likely cut short: try again. Within minutes of an update of this project the two files can come from caches of different ages. Waiting five minutes settles that." -DEFAULT_INSTALL_SHA256="4b8e2e8e5343dbf75f6c9b089993cce3b7f64ad1e7a5a6c91993a07ec9674bc6" +DEFAULT_INSTALL_SHA256="5ff90f40cfcdab22fd1056f9a40ea2193541155eaf4c1ab48c8d16ac1f230c44" # The pin above refuses any changed byte: this cap only stops a body that # cannot be the installer (a sign-in portal's page) before it is hashed. MAX_INSTALLER_BYTES=8388608 diff --git a/install/launchers/index.json b/install/launchers/index.json index 889cdff73..2b8f5014e 100644 --- a/install/launchers/index.json +++ b/install/launchers/index.json @@ -27,8 +27,8 @@ { "dest": "roms/ports/retrobios/install.py", "repo_path": "install.py", - "size": 1384488, - "sha256": "4b8e2e8e5343dbf75f6c9b089993cce3b7f64ad1e7a5a6c91993a07ec9674bc6", + "size": 1384197, + "sha256": "5ff90f40cfcdab22fd1056f9a40ea2193541155eaf4c1ab48c8d16ac1f230c44", "executable": false }, { @@ -71,8 +71,8 @@ "muos": { "archive": { "dest": "ARCHIVE/RetroBIOS.muxapp", - "size": 1438113, - "sha256": "388342648dc84cadfae52e4c550349a30016bbd9a880d946749e96fc593dd9fb" + "size": 1437822, + "sha256": "c82fdd8134e2579f5fcff020a3b1b97135bb73ee8893b4aaa892022b31792021" }, "members": [ { @@ -92,8 +92,8 @@ { "name": "RetroBIOS/install.py", "repo_path": "install.py", - "size": 1384488, - "sha256": "4b8e2e8e5343dbf75f6c9b089993cce3b7f64ad1e7a5a6c91993a07ec9674bc6", + "size": 1384197, + "sha256": "5ff90f40cfcdab22fd1056f9a40ea2193541155eaf4c1ab48c8d16ac1f230c44", "executable": false }, { @@ -166,8 +166,8 @@ { "dest": ".config/modules/retrobios/install.py", "repo_path": "install.py", - "size": 1384488, - "sha256": "4b8e2e8e5343dbf75f6c9b089993cce3b7f64ad1e7a5a6c91993a07ec9674bc6", + "size": 1384197, + "sha256": "5ff90f40cfcdab22fd1056f9a40ea2193541155eaf4c1ab48c8d16ac1f230c44", "executable": false }, { diff --git a/pyproject.toml b/pyproject.toml index 0f112b541..0053ce36f 100644 --- a/pyproject.toml +++ b/pyproject.toml @@ -76,3 +76,36 @@ cache_dir = "tmp/mypy_cache" baseline_path = "mypy-baseline.txt" ignore_categories = ["note"] sort_baseline = true + +# CI runs this rule set over every Python file (validate.yml, pr_checks.py). +# C901 and the PLR limits hold function size: a function past them is split +# by stage, not exempted. +[tool.ruff] +target-version = "py39" +line-length = 120 +extend-exclude = ["bios", "tmp", "website", ".cache", "dist", "data"] + +[tool.ruff.lint] +select = ["E", "F", "W", "B", "C90", "SIM", "PERF", "UP", "RET", "PIE", "PLR09", "PLW1510", "RUF100"] +ignore = [ + "E501", # long lines are wrapped by hand where it reads better + "UP006", "UP007", "UP035", "UP045", # install.py keeps 3.8 spellings + "SIM300", # an ALL_CAPS name is not always a constant (_SYSTEM_ROOT) + "SIM108", # a ternary is not always clearer than an if block + "PERF203", # try in a loop is the per-item error report + "RET504", "RET505", "RET506", "RET508", +] + +[tool.ruff.lint.mccabe] +max-complexity = 15 + +[tool.ruff.lint.pylint] +max-branches = 15 +max-statements = 60 +max-args = 8 +max-returns = 10 + +[tool.ruff.lint.per-file-ignores] +"install.py" = ["UP"] +# Shell fixtures inside string literals keep the tabs the real files have. +"tests/test_launchers_*.py" = ["E101"] diff --git a/scripts/archive_build.py b/scripts/archive_build.py index ac22efd07..bedaf3635 100644 --- a/scripts/archive_build.py +++ b/scripts/archive_build.py @@ -46,7 +46,7 @@ from typing import BinaryIO sys.path.insert(0, str(Path(__file__).resolve().parent)) from torrentzip import Source as Readable -from torrentzip import write_torrentzip, zlib_ng_version # noqa: E402 +from torrentzip import write_torrentzip, zlib_ng_version REPO_ROOT = Path(__file__).resolve().parent.parent ARCHIVES_FILE = REPO_ROOT / "recipes" / "archives.json" @@ -105,7 +105,7 @@ def ledger_text(records: dict[str, dict]) -> str: def write_ledger(records: dict[str, dict], path: Path = ARCHIVES_FILE) -> bool: - from artifacts import write_if_changed # noqa: PLC0415 + from artifacts import write_if_changed path.parent.mkdir(parents=True, exist_ok=True) return write_if_changed(str(path), ledger_text(records)) @@ -236,7 +236,7 @@ def container_pins(platforms_dir: str, emulators_dir: str) -> dict[str, set[str] archive md5 is the composite of its members (``zip_digest: composite``, Bios.cpp:64-68): neither pins the container bytes. """ - from common import ( # noqa: PLC0415 + from common import ( list_registered_platforms, load_emulator_profiles, load_platform_config, @@ -269,8 +269,8 @@ def recipe_index(emulators_dir: str, recipes_dir: str) -> dict[MemberList, set[s Matching on the member list, not the archive name, credits a DAT that knows the set under another name (``aga.zip`` is MAME's ``isa_aga``). """ - from common import load_emulator_profiles # noqa: PLC0415 - from romset_recipes import collect_recipes, load_dat_recipes # noqa: PLC0415 + from common import load_emulator_profiles + from romset_recipes import collect_recipes, load_dat_recipes index: dict[MemberList, set[str]] = defaultdict(set) profiles = load_emulator_profiles(emulators_dir, skip_aliases=False) diff --git a/scripts/auto_fetch.py b/scripts/auto_fetch.py index aed1bfe6a..2b3d25f2b 100644 --- a/scripts/auto_fetch.py +++ b/scripts/auto_fetch.py @@ -86,8 +86,8 @@ def find_missing(config: dict, db: dict) -> list[dict]: checks them inside the zip and holds them, and saw none of the files the cores need that no platform lists. """ - from nativemode import reads_file_contents # noqa: PLC0415 - from verify import Status, verify_platform # noqa: PLC0415 + from nativemode import reads_file_contents + from verify import Status, verify_platform result = verify_platform(config, db) hashed = reads_file_contents(config.get("verification_mode", "existence")) diff --git a/scripts/autorun.py b/scripts/autorun.py index db8a9aec3..9935aebae 100644 --- a/scripts/autorun.py +++ b/scripts/autorun.py @@ -191,7 +191,7 @@ class Context: def check_subject(subject: str, body: str = "") -> list[str]: """What the repository's commit rules refuse in this message, checked when the job list loads instead of two hours into the job.""" - from commit_rules import problems # noqa: PLC0415 + from commit_rules import problems return problems(f"{subject}\n\n{body}" if body else subject) diff --git a/scripts/build_port.py b/scripts/build_port.py index b09b5b07d..144579c3c 100644 --- a/scripts/build_port.py +++ b/scripts/build_port.py @@ -141,12 +141,12 @@ def release_pack_labels(root: Path = REPO_ROOT) -> dict[str, str]: refuses a pack whose name does not spell the platform, so a platform outside these groups has no pack to copy, whatever its file list. """ - from common import ( # noqa: PLC0415 + from common import ( group_identical_platforms, list_release_pack_platforms, load_platform_config, ) - from generate_pack import _name_part, _platform_pack_stem # noqa: PLC0415 + from generate_pack import _name_part, _platform_pack_stem platforms_dir = str(root / "platforms") pool = list_release_pack_platforms(platforms_dir) @@ -178,7 +178,7 @@ def build_archive(name: str, output: Path, root: Path = REPO_ROOT) -> Path: ) # The packs' member writer: imported here, as it loads the whole # pack builder, which a caller reading ARCHIVES does not need. - from generate_pack import _add_pack_member # noqa: PLC0415 + from generate_pack import _add_pack_member members = archive_members(name, root) output.parent.mkdir(parents=True, exist_ok=True) diff --git a/scripts/bundled_only.py b/scripts/bundled_only.py index 74831cdb4..46d860d6a 100644 --- a/scripts/bundled_only.py +++ b/scripts/bundled_only.py @@ -119,7 +119,7 @@ def main() -> int: parser.add_argument("--json", action="store_true", help="print the list as JSON") parser.add_argument("--strict", action="store_true", help="exit 1 while a file is listed") args = parser.parse_args() - from common import work_from_repo_root # noqa: PLC0415 + from common import work_from_repo_root work_from_repo_root(args, parser, ["db", "emulators_dir", "platforms_dir", "install_dir"]) diff --git a/scripts/check_buildbot_system.py b/scripts/check_buildbot_system.py index f81f47c2f..d630bafbc 100644 --- a/scripts/check_buildbot_system.py +++ b/scripts/check_buildbot_system.py @@ -13,6 +13,7 @@ Usage: from __future__ import annotations import argparse +import importlib.util import json import logging import os @@ -51,9 +52,7 @@ def load_tracked_entries( Returns {decoded_zip_name: (key, source_url)}. """ - try: - import yaml - except ImportError: + if importlib.util.find_spec("yaml") is None: print("Error: PyYAML required", file=sys.stderr) sys.exit(1) with open(registry_path) as f: diff --git a/scripts/check_freshness.py b/scripts/check_freshness.py index ae0e27596..dd44d4cc7 100644 --- a/scripts/check_freshness.py +++ b/scripts/check_freshness.py @@ -49,11 +49,11 @@ from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parent)) sys.path.insert(0, str(Path(__file__).resolve().parents[1])) -import export_native # noqa: E402 -import pin_installer # noqa: E402 -import refresh_data_dirs # noqa: E402 -import upstream # noqa: E402 -from common import ( # noqa: E402 +import export_native +import pin_installer +import refresh_data_dirs +import upstream +from common import ( InputMissing, apply_target_overrides, list_registered_platforms, @@ -65,11 +65,11 @@ from common import ( # noqa: E402 write_text_atomic, yaml_load, ) -from exporter import discover_exporters # noqa: E402 -from exporter.baseline import build_native_model # noqa: E402 -from scripts.scraper import game_dat_importer # noqa: E402 -from scripts.scraper.redump_dat_scraper import fetch_snapshot # noqa: E402 -from scripts.scraper.targets import discover_target_scrapers # noqa: E402 +from exporter import discover_exporters +from exporter.baseline import build_native_model +from scripts.scraper import game_dat_importer +from scripts.scraper.redump_dat_scraper import fetch_snapshot +from scripts.scraper.targets import discover_target_scrapers REPO_ROOT = Path(__file__).resolve().parents[1] CORE_INFO_REPO = "https://github.com/libretro/libretro-core-info" @@ -876,7 +876,7 @@ def core_info_blobs(cache_dir: str, offline: bool) -> dict[str, str] | None: repo = upstream.parse_repo(CORE_INFO_REPO) if repo is None: return None - payload = upstream._api( # noqa: SLF001 + payload = upstream._api( f"{repo.api_base}/repos/{repo.slug}/contents?per_page=100", cache_dir, offline, @@ -1046,7 +1046,7 @@ def _check_buildbot_system() -> Finding: The registry entries are refreshed above. An asset published since, or one the buildbot no longer serves, is only seen by reading its .index. """ - import check_buildbot_system # noqa: PLC0415 + import check_buildbot_system with contextlib.redirect_stdout(io.StringIO()): report = check_buildbot_system.check( @@ -1094,7 +1094,7 @@ def _game_catalogs(source: str) -> list[dict]: def _no_intro_asset_date(cache_dir: str, offline: bool) -> str: """The day the mirror last rebuilt its No-Intro pack, empty if unlisted.""" repo = upstream.parse_repo(NO_INTRO_MIRROR) - payload = upstream._api( # noqa: SLF001 + payload = upstream._api( f"{repo.api_base}/repos/{repo.slug}/releases/tags/{NO_INTRO_RELEASE}", cache_dir, offline, @@ -1146,8 +1146,8 @@ def redump_datfile_version(code: str) -> str: request = urllib.request.Request(url, method="HEAD", headers={"User-Agent": "retrobios/1.0"}) with urllib.request.urlopen(request, timeout=60) as response: disposition = response.headers.get("Content-Disposition", "") - named = game_dat_importer._DISPOSITION.search(disposition) # noqa: SLF001 - match = game_dat_importer._REDUMP_FILE.match(named["file"]) if named else None # noqa: SLF001 + named = game_dat_importer._DISPOSITION.search(disposition) + match = game_dat_importer._REDUMP_FILE.match(named["file"]) if named else None if not match: raise ValueError(f"{url} names no datfile") return f"{match['date']} {match['time']}" @@ -1225,7 +1225,7 @@ def _check_tosec(offline: bool) -> Finding: if offline: return Finding("catalogs", "tosec", SKIPPED, local=imported, detail="offline") try: - html = upstream._http_text(TOSEC_DOWNLOADS) # noqa: SLF001 + html = upstream._http_text(TOSEC_DOWNLOADS) except upstream.UpstreamError as exc: return Finding("catalogs", "tosec", UNKNOWN, local=imported, detail=str(exc)) latest = tosec_latest_pack(html or "") @@ -1297,7 +1297,7 @@ def _check_fbneo(cache_dir: str, offline: bool) -> Finding: if offline: return Finding("catalogs", "fbneo recipes", SKIPPED, local=imported, detail="offline") repo = upstream.parse_repo(FBNEO_REPO) - listing = upstream._api( # noqa: SLF001 + listing = upstream._api( f"{repo.api_base}/repos/{repo.slug}/contents/dats", cache_dir, offline, @@ -1386,7 +1386,7 @@ def specifier_allows(spec: str, version: str) -> bool: def pypi_latest(name: str) -> str | None: - payload = upstream._http_json(PYPI_URL.format(name=name)) # noqa: SLF001 + payload = upstream._http_json(PYPI_URL.format(name=name)) if not isinstance(payload, dict): return None info = payload.get("info") or {} @@ -1403,7 +1403,7 @@ def parse_npm_pins(text: str) -> dict[str, str]: def npm_latest(name: str) -> str | None: - payload = upstream._http_json(NPM_URL.format(name=name)) # noqa: SLF001 + payload = upstream._http_json(NPM_URL.format(name=name)) if not isinstance(payload, dict): return None return str(payload.get("version") or "") or None @@ -1518,7 +1518,7 @@ def check_source_paths(profiles: dict) -> Finding: or a pinned tree the record lacks, means a pin moved or a profile was added and `sitesources.py --fetch` was not run after it. Every tree a run tries is recorded, read or not, so a lacking one was never tried.""" - import sitesources # noqa: PLC0415 + import sitesources pinned = { sitesources.tree_key(repo, pin) diff --git a/scripts/common.py b/scripts/common.py index 62bcc6613..2cacada9a 100644 --- a/scripts/common.py +++ b/scripts/common.py @@ -12,6 +12,7 @@ from collections import Counter import argparse import filecmp import hashlib +import importlib.util import functools import json import os @@ -106,7 +107,7 @@ def load_database(db_path: str) -> dict: except FileNotFoundError: # A mistyped --db beside the real database was told to rescan the # whole collection into a second file under the typo. - import difflib # noqa: PLC0415 + import difflib typed = Path(db_path) close = difflib.get_close_matches( @@ -235,8 +236,8 @@ def adler32_of(path: str, byteswap: bool = False) -> str: Dolphin swaps every 16-bit word of its DSP ROMs before hashing them (Common::swap16 in DSPLLE.cpp:LoadDSPRom). """ - import struct # noqa: PLC0415 - import zlib # noqa: PLC0415 + import struct + import zlib with open(path, "rb") as f: data = f.read() @@ -335,7 +336,7 @@ def declared_content_checks(file_entry: dict) -> set[str]: @functools.lru_cache(maxsize=4096) def _romdir_verdict(path: str, size: int, mtime_ns: int, spec: str) -> bool: - from romdir import romdir_accepts # noqa: PLC0415 + from romdir import romdir_accepts with open(path, "rb") as f: data = f.read() @@ -722,8 +723,8 @@ SHORT_LIST = 12 @functools.lru_cache(maxsize=1) def _gh_cli_token() -> str: """What `gh auth token` prints, or "" when gh is absent or logged out.""" - import logging # noqa: PLC0415 - import subprocess # noqa: PLC0415 + import logging + import subprocess log = logging.getLogger(__name__) try: @@ -775,7 +776,7 @@ def suggest_names( `listed` is how many entries the listing shows when `available` also holds aliases of them. """ - import difflib # noqa: PLC0415 + import difflib total = len(available) if listed is None else listed close = sorted({m for name in typed @@ -845,7 +846,7 @@ def require_platform(name: str, platforms_dir: str = "platforms") -> None: ) if os.path.exists(os.path.join(platforms_dir, f"{name}.yml")): return - import difflib # noqa: PLC0415 + import difflib known = list_registered_platforms(platforms_dir) close = difflib.get_close_matches(name, known, n=1) @@ -2485,9 +2486,7 @@ def load_emulator_profiles( } _emulator_profiles_cache[cache_key] = profiles return profiles - try: - import yaml - except ImportError: + if importlib.util.find_spec("yaml") is None: # Every consumer reads {} as "this repo documents no emulator", which # is what a broken install looks like from the outside: zero coverage, # no gap, nothing to fix. @@ -3003,7 +3002,7 @@ def standalone_set(config: dict) -> set[str]: for core in entry.get("cores") or [] } if names - {n for n in names if n.startswith(CORE_DIR_PREFIX)}: - from launchers import executed_files, handed_directories # noqa: PLC0415 + from launchers import executed_files, handed_directories handed = handed_directories(config) # The record's position travels too: a search list is read in order. @@ -3023,7 +3022,7 @@ def standalone_set(config: dict) -> set[str]: if f.get("name") } # The machines a record offers under its systems, by normalized id. - from launchers import native_systems # noqa: PLC0415 + from launchers import native_systems natives = native_systems(config) names |= { @@ -3059,7 +3058,7 @@ def merged_standalone_set(configs: Iterable[dict]) -> set[str]: def _handed(standalone_cores: Iterable[str]) -> list: """The directories a standalone set carries, as launchers built them.""" - from launchers import HandedDirectory # noqa: PLC0415 + from launchers import HandedDirectory found = [] for tag in standalone_cores: @@ -3103,7 +3102,7 @@ def entry_launch_systems(entry: dict, index: Mapping[str, set[str]]) -> frozense def _executed(standalone_cores: Iterable[str]) -> list: """The files a standalone set's launchers execute, as launchers read them.""" - from launchers import ExecutedFile # noqa: PLC0415 + from launchers import ExecutedFile found = [] for tag in standalone_cores: @@ -3198,7 +3197,7 @@ def standalone_destination( layout = standalone_layout_path(entry, profile) if layout is None or not bindings: return None - from launchers import bound_path # noqa: PLC0415 + from launchers import bound_path return bound_path(layout, bindings) @@ -3211,7 +3210,7 @@ def standalone_bindings_for( ``systems`` are those the entry is launched for (entry_launch_systems). """ - from launchers import directory_handles, pool_folders, standalone_bindings # noqa: PLC0415 + from launchers import directory_handles, pool_folders, standalone_bindings declared = directory_handles(profile) pools = pool_folders(profile) @@ -3332,7 +3331,7 @@ def _build_layouts( # The layout folders a search setting stands for (standalone_pools): # bound, the launcher passes the setting and the default is not read. - from launchers import pool_folders as _pool_folders # noqa: PLC0415 + from launchers import pool_folders as _pool_folders pool_folders = {v.strip("/") for v in _pool_folders(profile).values()} - {""} @@ -3428,7 +3427,7 @@ def _branch_holds(branch: str, board: str) -> bool: variable, _, pattern = branch.strip().partition(" ") if variable != "DEVICE" or not pattern.strip(): return True - import fnmatch # noqa: PLC0415 + import fnmatch return any( fnmatch.fnmatchcase(board.upper(), p.strip().upper()) for p in pattern.split("|") @@ -3539,7 +3538,7 @@ def content_folder_tags(config: dict) -> set[str]: boards = content_folder_boards(config) target = config.get(TARGET_KEY) pairs = {pair for pair, on in boards.items() if not target or on is None or target in on} - from launchers import _roms_place # noqa: PLC0415 + from launchers import _roms_place def place(folder: str) -> list: return list(_roms_place(config, folder) or ()) @@ -3712,7 +3711,7 @@ def content_layout( # path with stand for these: libretro MAME hands MAME # /mame/bios unless the content's command line names # another (retro_init.cpp Set_Path_Option, execute_game_cmd). - from launchers import pool_folders # noqa: PLC0415 + from launchers import pool_folders pools = set(pool_folders({"standalone_pools": view.get("libretro_pools")}).values()) for f in files: @@ -4279,7 +4278,7 @@ SYSTEM_ALIASES: dict[str, str] = { } -@functools.lru_cache(maxsize=None) +@functools.cache def _norm_system_id(sid: str) -> str: """Normalize system ID for cross-platform matching. @@ -4605,7 +4604,7 @@ def declared_root(config: dict) -> str: list also names folders beside the BIOS one states it as core_destination: EmuELEC's ports/ entries are a quarter of its list. """ - if config.get("base_destination", None) != "": + if config.get("base_destination") != "": return "" if config.get("core_destination"): return str(config["core_destination"]) @@ -4820,7 +4819,7 @@ def build_target_cores_cache( def _unknown_target_message(target: str, platforms: list[str], platforms_dir: str) -> str: """A target no platform has, with the closest names any of them knows.""" - import difflib # noqa: PLC0415 + import difflib targets_dir = os.path.join(platforms_dir, "targets") owners: dict[str, list[str]] = {} diff --git a/scripts/core_probe.py b/scripts/core_probe.py index 3af6fbdfe..e7a9dfb1b 100644 --- a/scripts/core_probe.py +++ b/scripts/core_probe.py @@ -1455,7 +1455,7 @@ def load_oracle(path: Path | None) -> tuple[dict, dict | None]: """The oracle file's data and its identity, or nothing without a file.""" if path is None or not path.is_file(): return {}, None - import yaml # noqa: PLC0415 + import yaml data = yaml.safe_load(path.read_text(encoding="utf-8")) or {} try: @@ -1469,7 +1469,7 @@ def default_emulator(core_file: Path, library_name: str | None) -> str: """The profile whose cores: names the .so, else the library name as a slug.""" stem = core_file.name.split(".")[0].removesuffix("_libretro") sys.path.insert(0, str(ROOT / "scripts")) - from common import load_emulator_profiles # noqa: PLC0415 + from common import load_emulator_profiles owners = sorted(key for key, profile in load_emulator_profiles(str(ROOT / "emulators")).items() if stem == key or stem in (profile.get("cores") or [])) @@ -1485,7 +1485,7 @@ def default_emulator(core_file: Path, library_name: str | None) -> str: def default_subject(record: dict) -> str: """A slug shared by the reruns of one test: a check by its claim and method, a run or bench by its inputs.""" - from measurement_records import canonical, sha256_hex, slugify # noqa: PLC0415 + from measurement_records import canonical, sha256_hex, slugify check = record.get("check") if check: @@ -1501,7 +1501,7 @@ def default_subject(record: dict) -> str: def write_record(directory: Path, full: dict) -> tuple[Path, dict]: """Append the record, with its id, to its emulator's .jsonl. Returns the file and the record as written.""" - from measurement_records import line_text, parse_lines, records_path, seal # noqa: PLC0415 + from measurement_records import line_text, parse_lines, records_path, seal sealed = seal(full) lines = directory / records_path(sealed["emulator"]) @@ -1546,7 +1546,7 @@ def _probe(args: argparse.Namespace) -> int: shutil.rmtree(work, ignore_errors=True) load_after = load_average() first = variants[0]["repetitions"][0] - from measurement_records import RECORD_VERSION # noqa: PLC0415 + from measurement_records import RECORD_VERSION record: dict = { "record_version": RECORD_VERSION, @@ -1622,7 +1622,7 @@ def rejudged(record: dict, data: dict, identity: dict | None, now: str) -> dict record's. The verdicts, their evidence, bios_used and inputs.oracle are computed again, and judged_at and judged_by say when and by what. """ - import copy # noqa: PLC0415 + import copy # Another probe (standalone_probe, pack_probe) judges with its own rules. if record.get("record_version", 0) < 4 or record["frontend"].get("script") != "scripts/core_probe.py": @@ -1656,8 +1656,8 @@ def rejudged(record: dict, data: dict, identity: dict | None, now: str) -> dict return out -def RECORD_VERSION_NOW() -> int: # noqa: N802 - from measurement_records import RECORD_VERSION # noqa: PLC0415 +def RECORD_VERSION_NOW() -> int: + from measurement_records import RECORD_VERSION return RECORD_VERSION @@ -1665,7 +1665,7 @@ def RECORD_VERSION_NOW() -> int: # noqa: N802 def rejudge_records(args: argparse.Namespace) -> int: """Append, for each live record whose judgement the oracle now gives otherwise, the record judged again, superseding it.""" - from measurement_records import line_text, live, read_records, records_path, seal # noqa: PLC0415 + from measurement_records import line_text, live, read_records, records_path, seal root = Path(args.record) data, identity = load_oracle(Path(args.oracle) if args.oracle else DEFAULT_ORACLE) diff --git a/scripts/cross_reference.py b/scripts/cross_reference.py index 580bacd39..40991523c 100644 --- a/scripts/cross_reference.py +++ b/scripts/cross_reference.py @@ -1187,9 +1187,7 @@ class _NameHolder: base = name.rsplit("/", 1)[-1] found: tuple[str, bool] | None = None stem = suffixed_stem(base) - if base in self.by_name or any(map(self._entry_held, self.exact.get(base, []))): - found = (base, True) - elif stem is not None and any(map(self._entry_held, self.exact.get(stem, []))): + if base in self.by_name or any(map(self._entry_held, self.exact.get(base, []))) or stem is not None and any(map(self._entry_held, self.exact.get(stem, []))): found = (base, True) else: path, _status = resolve_local_file( @@ -1554,7 +1552,7 @@ def main() -> None: "--list-emulators", action="store_true", help="List available emulators" ) args = parser.parse_args() - from common import work_from_repo_root # noqa: PLC0415 + from common import work_from_repo_root work_from_repo_root(args, parser, ["emulators_dir", "platforms_dir", "db"]) if args.list_emulators: diff --git a/scripts/derivations.py b/scripts/derivations.py index 5be365963..4840c104e 100644 --- a/scripts/derivations.py +++ b/scripts/derivations.py @@ -82,7 +82,7 @@ def crc32_combine(crc1: int, crc2: int, len2: int) -> int: return _gf2_times(_shift_operator(len2), crc1) ^ crc2 -@functools.lru_cache(maxsize=None) +@functools.cache def _byte_shift(power: int) -> tuple[int, ...]: """The operator for 2**power zero bytes appended, as zlib squares it: three squarings of the one-bit operator give one byte, and each power @@ -95,7 +95,7 @@ def _byte_shift(power: int) -> tuple[int, ...]: return tuple(operator) -@functools.lru_cache(maxsize=None) +@functools.cache def _shift_operator(len2: int) -> tuple[int, ...]: """The linear map zlib applies to crc(A) for len2 bytes appended. diff --git a/scripts/export_native.py b/scripts/export_native.py index 032ceb345..8b9266bc8 100644 --- a/scripts/export_native.py +++ b/scripts/export_native.py @@ -395,7 +395,7 @@ class StaleTruth(ValueError): """The truth file no longer describes the profiles it was built from.""" -@functools.lru_cache(maxsize=None) +@functools.cache def _truth_sources(platforms_dir: str) -> tuple[dict, dict, dict | None]: """Registry, profiles and database, as generate_truth reads them.""" registry_path = Path(platforms_dir) / "_registry.yml" diff --git a/scripts/exporter/batocera_exporter.py b/scripts/exporter/batocera_exporter.py index bbf9e9de2..58bebd922 100644 --- a/scripts/exporter/batocera_exporter.py +++ b/scripts/exporter/batocera_exporter.py @@ -421,13 +421,13 @@ class Exporter(BaseExporter): continue key = _note_key(line) if not key[0]: - if 0 <= hash_at and "[" in line[:hash_at]: + if hash_at >= 0 and "[" in line[:hash_at]: pending.append(line[hash_at:].strip()) continue if pending: leading[key] = pending pending = [] - if 0 <= hash_at and hash_at > line.index(key[0]): + if hash_at >= 0 and hash_at > line.index(key[0]): trailing[key] = line[hash_at:].rstrip() return trailing, leading diff --git a/scripts/exporter/candidates.py b/scripts/exporter/candidates.py index 579ee3b4a..a388c0256 100644 --- a/scripts/exporter/candidates.py +++ b/scripts/exporter/candidates.py @@ -46,10 +46,7 @@ def _declared_hashes(entry: dict) -> dict[str, set[str]]: def _accepts(accepted: set[str], declared: dict[str, set[str]]) -> bool: """True when the hashes a profile entry accepts, the members of its archive included, hold one the platform entry declares.""" - for values in declared.values(): - if values & accepted: - return True - return False + return any(values & accepted for values in declared.values()) def _contradicts(profile_entry: dict, declared: dict[str, set[str]]) -> bool: diff --git a/scripts/exporter/romm_exporter.py b/scripts/exporter/romm_exporter.py index 69faa0edd..fb8acf801 100644 --- a/scripts/exporter/romm_exporter.py +++ b/scripts/exporter/romm_exporter.py @@ -89,7 +89,7 @@ class Exporter(BaseExporter): and self._known_platform(fe.native_system) ) - def writable(self, fe: NativeFile, require: str = "") -> bool: # noqa: ARG002 + def writable(self, fe: NativeFile, require: str = "") -> bool: """What RomM already ships stays. The conditions gate additions. An entry of theirs that could never verify is still theirs, and the diff --git a/scripts/find_pinned_revision.py b/scripts/find_pinned_revision.py index 42f1aa402..5aac2ee2c 100644 --- a/scripts/find_pinned_revision.py +++ b/scripts/find_pinned_revision.py @@ -21,7 +21,7 @@ import urllib.parse from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parent)) -import upstream # noqa: E402 +import upstream # Commits listed per page and the most pages walked: a data file older than # 2 000 commits on its own path is not one a platform list still pins. diff --git a/scripts/game_rules.py b/scripts/game_rules.py index d9512ba34..5cee18b39 100644 --- a/scripts/game_rules.py +++ b/scripts/game_rules.py @@ -247,7 +247,7 @@ def main() -> int: help="profiles the rules are checked against (default emulators)") parser.add_argument("--json", action="store_true", help="print the summary as JSON") args = parser.parse_args() - from common import work_from_repo_root # noqa: PLC0415 + from common import work_from_repo_root work_from_repo_root(args, parser, ["regions", "extras", "headers", "emulators_dir"]) diff --git a/scripts/generate_games_index.py b/scripts/generate_games_index.py index 0d867577e..0b99a5220 100644 --- a/scripts/generate_games_index.py +++ b/scripts/generate_games_index.py @@ -45,7 +45,6 @@ if str(ROOT) not in sys.path: sys.path.insert(0, str(ROOT)) from common import ( # noqa: E402 - list_registered_platforms, load_emulator_profiles, load_platform_config, native_layer, @@ -584,8 +583,9 @@ def folder_systems(setups: dict[str, dict]) -> dict[str, list[str]]: return {name: sorted(systems) for name, systems in sorted(names.items())} -def render(output: Path = OUTPUT, inputs: Inputs = Inputs()) -> tuple[dict[Path, str], dict]: +def render(output: Path = OUTPUT, inputs: Inputs | None = None) -> tuple[dict[Path, str], dict]: """Every published file's text, keyed by its path, and the coverage.""" + inputs = inputs or Inputs() resolver = SystemResolver.from_repo(inputs.emulators, inputs.platforms) profiles = Profiles(load_emulator_profiles(inputs.emulators), resolver) arcade = build_arcade(inputs.games / "arcade") diff --git a/scripts/generate_installer_doc.py b/scripts/generate_installer_doc.py index 1880a9d4c..71622ebd0 100644 --- a/scripts/generate_installer_doc.py +++ b/scripts/generate_installer_doc.py @@ -232,8 +232,8 @@ def line_menu() -> str: prints it for the RetroArch list (install/retroarch.json): the very function line mode runs, its questions answered here. The page carried a copy typed by hand, whose keys and counts drifted from the installer.""" - import io # noqa: PLC0415 - from unittest import mock # noqa: PLC0415 + import io + from unittest import mock manifest = json.loads((ROOT / "install" / "retroarch.json").read_text(encoding="utf-8")) files = [*manifest["files"], *(manifest.get("case_variants") or [])] @@ -284,7 +284,7 @@ class _ListHandler(http.server.SimpleHTTPRequestHandler): def __init__(self, *args: object, **kwargs: object) -> None: super().__init__(*args, directory=str(ROOT), **kwargs) - def do_GET(self) -> None: # noqa: N802 + def do_GET(self) -> None: if not re.fullmatch(r"/install/[a-z0-9_-]+\.json", self.path): self.send_error(404) return @@ -317,7 +317,7 @@ SMALL_LIST = { def write_small_list(path: Path) -> None: - import hashlib # noqa: PLC0415 + import hashlib files = [] for dest, (data, systems, regions, cores) in SMALL_LIST.items(): @@ -339,9 +339,9 @@ def _child(spec: dict) -> int: data tree of a landed run reports its bytes written without fetching them, and a held run finds every file and tree in place. The counts, sizes and words are the installer's own.""" - import concurrent.futures # noqa: PLC0415 - import socket # noqa: PLC0415 - from unittest import mock # noqa: PLC0415 + import concurrent.futures + import socket + from unittest import mock real_connect = socket.create_connection @@ -382,7 +382,7 @@ def _child(spec: dict) -> int: patches += [ mock.patch.object(_install, "detect_platforms", lambda _os: [(spec["platform"], Path(spec["card"]))]), - mock.patch.object(_install, "_mounted_cards", lambda: []), + mock.patch.object(_install, "_mounted_cards", list), ] if spec.get("landed"): patches.append(mock.patch.object(_install, "_download_one", landed)) diff --git a/scripts/generate_pack.py b/scripts/generate_pack.py index 0f2233d34..be2a224f4 100644 --- a/scripts/generate_pack.py +++ b/scripts/generate_pack.py @@ -3997,7 +3997,7 @@ def _main(held: contextlib.ExitStack) -> None: # Manifest generation (JSON inventory for install.py) -@functools.lru_cache(maxsize=None) +@functools.cache def _registered(repo_root: str) -> frozenset[str]: """The paths a repository's .gitignore registers as release assets, read by the parser the fetcher and the release check use, once per root.""" @@ -4149,7 +4149,7 @@ def _profile_copies( the emulator, else the shortest path. DuckStation's ps2_scph50006.bin sits at the BIOS root and under pcsx2/bios/ for the libretro PS2 cores. """ - from fnmatch import fnmatch # noqa: PLC0415 + from fnmatch import fnmatch taken: list[tuple[str, str, str, bool]] = [] for copy in declared: @@ -5704,7 +5704,7 @@ def _offered_boards( pairs = content_folder_boards(config) if all(on is None for on in pairs.values()): return {} - from launchers import _roms_place # noqa: PLC0415 + from launchers import _roms_place by_key: dict[str, set[str]] = {} for name, claimants in upstream_profile_index(profiles).items(): @@ -6240,7 +6240,7 @@ from packextras import ( # noqa: E402,F401 ) -from packreadme import ( # noqa: E402,F401 +from packreadme import ( # noqa: E402 _build_readme, _build_agnostic_rename_readme, save_place, diff --git a/scripts/generate_readme.py b/scripts/generate_readme.py index 8b1a88a99..1f670018c 100644 --- a/scripts/generate_readme.py +++ b/scripts/generate_readme.py @@ -37,7 +37,6 @@ from common import ( unique_emulator_profiles, write_if_changed, ) -from nativemode import check_label import archive_build import release_record from siteguides import PACKAGE_COMMAND, install_command @@ -50,7 +49,7 @@ from verify import verify_platform def _installer_words() -> object: """install.py read as a module, for the words its screen shows: the README named a line menu the one-liner never opens.""" - import importlib.util # noqa: PLC0415 + import importlib.util spec = importlib.util.spec_from_file_location( "install", Path(__file__).resolve().parent.parent / "install.py") @@ -591,7 +590,6 @@ def archive_line(counts: dict[str, int]) -> str: def generate_readme(db: dict, platforms_dir: str, db_path: str = "database.json") -> str: total_files = db.get("total_files", 0) - total_size = db.get("total_size", 0) ts = datetime.now(timezone.utc).strftime("%Y-%m-%dT%H:%M:%SZ") platform_names = list_registered_platforms(platforms_dir) @@ -616,16 +614,6 @@ def generate_readme(db: dict, platforms_dir: str, db_path: str = "database.json" / len(profile_files)) if profile_files else 0) closed_count = sum(1 for prof in profiles.values() if str(prof.get("upstream") or "").startswith("closed")) - comp = compute_composition(db) - missing_total = len(set().union(*(c["missing_names"] for c in coverages.values()))) - # The entries marked `unsourceable:` are never served by name, so a - # homonym cannot take their place: retail game data, per-user keys, slots - # the user fills. Each stays an acquisition target with its reason, and - # is counted apart from the files still to be found. - unsourceable_total = len( - set().union(*(c["unsourceable_names"] for c in coverages.values())) - ) - acquirable_total = missing_total - unsourceable_total system_ids = system_index(profiles) diff --git a/scripts/generate_site.py b/scripts/generate_site.py index 017124bf2..c2f8235a0 100644 --- a/scripts/generate_site.py +++ b/scripts/generate_site.py @@ -38,7 +38,7 @@ from pathlib import Path from typing import TypeVar sys.path.insert(0, os.path.dirname(__file__)) -from sitecollection import ( # noqa: E402 +from sitecollection import ( _copy_places, _group_by_manufacturer, _profiles_in, _profiles_on_disk, _slug, collection_paths, ) @@ -77,7 +77,6 @@ from nativemode import check_label, digest_algorithm, reads_file_contents yaml = require_yaml() from generate_readme import ( - compute_coverage, platform_coverages, NO_PACK, asset_links, @@ -86,7 +85,6 @@ from generate_readme import ( demo_facts, download_links, extract_notes, - extract_targets, release_totals, ) from provenance_report import build_report, distinct_missing, profile_needs @@ -109,8 +107,6 @@ from siteguides import ( Guide, HandheldGuide, HandheldSystem, - FENCE_TITLES, - INSTALL_BASE, INSTALL_PS1, INSTALL_SH, PACKAGE_COMMAND, @@ -118,7 +114,6 @@ from siteguides import ( TRUST_ITEMS, detected_systems as _detected_systems, fence, - folder_list, install_command, setup_count, platform_args, @@ -624,7 +619,7 @@ def _pack_version(pack_name: str, platforms: list[str]) -> str: Read past the platform part the builder writes, not at the last underscore: AmberELEC_prerelease-20261019_1835 read as 1835. """ - from generate_pack import platform_pack_prefix # noqa: PLC0415 + from generate_pack import platform_pack_prefix stem = pack_name.removesuffix("_BIOS_Pack.zip") prefix = platform_pack_prefix( @@ -1079,7 +1074,7 @@ def _release_pack_platforms() -> frozenset[str]: return _release_packs_in(str(siteinputs.current().platforms)) -@functools.lru_cache(maxsize=None) +@functools.cache def _release_packs_in(platforms_dir: str) -> frozenset[str]: return frozenset(list_release_pack_platforms(platforms_dir)) @@ -2807,7 +2802,7 @@ def platform_dat(manifest: dict, db: dict, member_digests: dict[str, dict[str, s def _logiqx(name: str, description: str, games: dict[str, list[dict]], generated_at: str) -> str: """Games of roms as a Logiqx datafile, each rom's `_rom` its name.""" - import xml.etree.ElementTree as ET # noqa: PLC0415 + import xml.etree.ElementTree as ET root = ET.Element("datafile") header = ET.SubElement(root, "header") @@ -3258,7 +3253,7 @@ def _front_matter(markdown: str) -> dict: return data if isinstance(data, dict) else {} -@functools.lru_cache(maxsize=None) +@functools.cache def _sha1_by_prefix(db_path: str) -> dict[str, str]: return {sha1[:12]: sha1 for sha1 in load_database(db_path)["files"]} @@ -3581,7 +3576,7 @@ def _collection_sha1_by_path() -> dict[str, str]: return _sha1_by_path_in(str(siteinputs.current().db)) -@functools.lru_cache(maxsize=None) +@functools.cache def _sha1_by_path_in(db_path: str) -> dict[str, str]: with open(db_path, encoding="utf-8") as handle: files = json.load(handle).get("files", {}) @@ -3724,7 +3719,7 @@ def _copy_hash(algorithm: str, value: str | list) -> str: """A declared hash cut to SHORT_HASH characters on a button that copies it whole. A list of accepted values (Recalbox) copies its first. Outside a form a button submits nothing, so it carries no type.""" - from hashing import parse_hash_list # noqa: PLC0415 + from hashing import parse_hash_list values = parse_hash_list(value) if not values: @@ -4123,7 +4118,7 @@ def _profiles_by_core_name() -> dict[str, list[str]]: return _core_names_in(str(siteinputs.current().emulators)) -@functools.lru_cache(maxsize=None) +@functools.cache def _profiles_with_page(emulators_dir: str) -> frozenset[str]: """The profiles the site writes a page for: no alias, no test core.""" profiles = _profiles_in(emulators_dir, skip_aliases=True) @@ -4132,7 +4127,7 @@ def _profiles_with_page(emulators_dir: str) -> frozenset[str]: ) -@functools.lru_cache(maxsize=None) +@functools.cache def _core_names_in(emulators_dir: str) -> dict[str, list[str]]: profiles = _profiles_in(emulators_dir, skip_aliases=True) with_page = _profiles_with_page(emulators_dir) @@ -5060,8 +5055,8 @@ def _data_member_digests( whose copy in the tree's local cache has the sha1 the manifest records. The manifests carry sha1 alone: the MD5 of Dolphin's ApprovedInis.json found nothing although the pack ships it.""" - from common import load_data_dir_registry # noqa: PLC0415 - from hashing import compute_hashes # noqa: PLC0415 + from common import load_data_dir_registry + from hashing import compute_hashes if data_registry is None: data_registry = load_data_dir_registry(str(siteinputs.current().platforms)) @@ -5356,7 +5351,7 @@ def _console_display(manufacturer: str, console: str) -> str: """A console section's name as the reader looks for it: the heading system_name gives its id, or the folder alone under a program's top (Other, Arcade), where "Other mame" would name nothing.""" - from siterender import _PROGRAM_TOPS, _heading_name # noqa: PLC0415 + from siterender import _PROGRAM_TOPS, _heading_name return console if manufacturer in _PROGRAM_TOPS else _heading_name(manufacturer, console) @@ -5838,7 +5833,7 @@ def _fetch_url(path: str) -> str: large-files release asset when .gitignore keeps it out of git.""" global _RELEASE_ASSET_NAMES if _RELEASE_ASSET_NAMES is None: - from largefiles import ( # noqa: PLC0415 + from largefiles import ( LARGE_FILES_RELEASE, asset_names, load_registered_paths, @@ -6484,7 +6479,7 @@ def system_install_choices(coverages: dict) -> dict[str, dict[str, list[tuple[st platform's install manifest records is offered: --system refuses any other name. """ - from siterender import _page_by_norm # noqa: PLC0415 + from siterender import _page_by_norm choices: dict[str, dict[str, list[tuple[str, str]]]] = {} for name, cov in sorted(coverages.items()): @@ -6652,7 +6647,7 @@ def _region_order() -> dict[str, int]: for every region is a region-free stand-in for the BIOS of each one: the PlayStation section opened on psxonpsp660.bin, which one emulator requires among the BIOS it accepts, above the scph files most read.""" - from region import REGION_TREE, WORLD # noqa: PLC0415 + from region import REGION_TREE, WORLD ordered = [] for parent, members in REGION_TREE.items(): @@ -6692,7 +6687,7 @@ _SECTION_ENTRIES: dict[int, tuple[object, dict[tuple[str, str], list]]] = {} def _entries_by_section(consumers: FileConsumers) -> dict[tuple[str, str], list]: """Each console section with the (sha1, emulator, entry, system) whose system leads to it, read once per build.""" - from siterender import system_section # noqa: PLC0415 + from siterender import system_section cached = _SECTION_ENTRIES.get(id(consumers)) if cached is not None and cached[0] is consumers: @@ -6858,7 +6853,7 @@ def _start_groups( the Mega CD BIOS for its Genesis), and one under Other is a single emulator's, its shaders and fonts. A file the emulator ships with is no file to fetch.""" - from siterender import _heading_name, _manufacturer_slug, system_name, system_section # noqa: PLC0415 + from siterender import _heading_name, _manufacturer_slug, system_name, system_section here = (_manufacturer_slug(section[0]), section[1]) if section else None held = {str(f.get("sha1", "")) for f in files} @@ -7175,7 +7170,7 @@ def _group_start(group: _StartGroup, first_below: bool) -> list[tuple[str, str]] that run without it. The Game Boy opened on dmg_boot.bin, which Emux GB alone of 13 requires, under a home page that says the Game Boy needs no BIOS.""" - from region import _PARENT # noqa: PLC0415 + from region import _PARENT def listed(names: list[str], below: bool = first_below) -> str: if len(names) <= START_WITH_NAMES: @@ -7411,7 +7406,7 @@ def arcade_board_sections( folders. Each board is recorded (siterender.record_board_section) before any page links one, and a system's install commands follow its link to the board's section. Call after reset_console_pages().""" - from siterender import ( # noqa: PLC0415 + from siterender import ( arcade_board, arcade_boards, archive_machine, @@ -7507,7 +7502,7 @@ def arcade_board_sections( def _boards_line(manufacturer: str, console: str) -> list[str]: """The line of a section whose board sets went to the boards' pages: the Dreamcast folder holds NAOMI's and Atomiswave's.""" - from siterender import arcade_boards # noqa: PLC0415 + from siterender import arcade_boards boards = _BOARDS_FROM.get((manufacturer, console)) if not boards: @@ -7558,7 +7553,7 @@ def _part_weight() -> float: return SEARCH_WEIGHT.get("part", DEMOTED_WEIGHT) -@functools.lru_cache(maxsize=None) +@functools.cache def _manifest_systems(platform: str) -> frozenset[str]: """The system ids a platform's install manifest records: --system refuses any other.""" @@ -7610,7 +7605,7 @@ def system_pages( (siterender.record_console_pages). An arcade board has a page of its own, systems/arcade-/, under a heading of that id. """ - from siterender import board_slug # noqa: PLC0415 + from siterender import board_slug slug = _slug(manufacturer) installs = installs or {} @@ -7889,7 +7884,7 @@ def _named_system_link(sys_id: str, prefix: str = "") -> str: The emulator pages printed the id ("sony-playstation") where every other page says "Sony PlayStation". The id stays in the address only. """ - from siterender import system_section # noqa: PLC0415 + from siterender import system_section name = system_name(sys_id).replace("[", r"\[").replace("]", r"\]") section = system_section(sys_id) @@ -7920,7 +7915,7 @@ def _region_words(value: object, most: int = 0) -> str: """A region: value in words. ``most`` caps the regions named, the rest counted: one Saturn BIOS serves seven.""" raw = value if isinstance(value, list) else [value] if value else [] - from region import label # noqa: PLC0415 + from region import label words = [_REGION_WORDS.get(str(r)) or label(str(r)) for r in raw] if most and len(words) > most: @@ -8064,7 +8059,7 @@ def comes_with_app(f: dict) -> bool: narrowed by ``mode`` is that build's alone: the other build reads its own entry, or nothing. """ - from validation import installed_with_emulator # noqa: PLC0415 + from validation import installed_with_emulator return installed_with_emulator(f) @@ -8254,7 +8249,7 @@ def _build_file_links(pin_build: list[dict]) -> list[str]: """Each platform build file that holds the revision, linked at the commit it was read at when the source record holds it. The prose of pin_frozen named the file as plain text.""" - from sitesources import _browse_repo, _source_permalink, tree_holds # noqa: PLC0415 + from sitesources import _browse_repo, tree_holds links = [] for build in pin_build: @@ -8611,7 +8606,7 @@ def _more_words(lines: list[str]) -> list[str]: def _short_hash_line(f: dict) -> str: """The entry's strongest declared hash, cut to SHORT_HASH characters, with a copy button for the whole value. "" when it declares none.""" - from hashing import parse_hash_list # noqa: PLC0415 + from hashing import parse_hash_list for field, label in (("sha1", "SHA1"), ("md5", "MD5"), ("sha256", "SHA256"), ("crc32", "CRC32")): values = parse_hash_list(f.get(field) or "") @@ -8984,7 +8979,7 @@ def install_commands(args: str = "", indent: str = "", def _installer() -> object: """install.py, read as a module: the names `--emulator` accepts are its own (`emulator_names`).""" - import importlib.util # noqa: PLC0415 + import importlib.util spec = importlib.util.spec_from_file_location("install", _REPO_ROOT / "install.py") module = importlib.util.module_from_spec(spec) @@ -9549,7 +9544,7 @@ def _hash_spans(value: str | list, copy: bool = False) -> str: that only a profile declares were out of reach of the site search: it indexes text, and a pasted sha1 matched nothing. """ - from hashing import parse_hash_list # noqa: PLC0415 + from hashing import parse_hash_list return ", ".join( markup.hash_value(v, copy) for v in parse_hash_list(value) @@ -10607,7 +10602,7 @@ def _declared_hashes(config: dict, detail: dict) -> dict[str, list[str]]: and named neither: the reader could not look for the dump RetroDECK asks for, nor report the difference. """ - from hashing import parse_hash_list # noqa: PLC0415 + from hashing import parse_hash_list system = (config.get("systems") or {}).get(detail.get("system", "")) or {} for entry in system.get("files") or []: @@ -10947,8 +10942,8 @@ def reading_platforms(emu_name: str, profile: dict, name: str, """Of the platforms running an emulator (name -> config), those whose build of it reads the entry: BlastEm's cdbios.bin is read by the standalone build only, and RetroBat hands that build other names.""" - from common import platform_layouts, standalone_set # noqa: PLC0415 - from validation import filter_files_by_mode, unread_on # noqa: PLC0415 + from common import platform_layouts, standalone_set + from validation import filter_files_by_mode, unread_on return { platform for platform, config in configs.items() @@ -12629,7 +12624,7 @@ def _generate(args: argparse.Namespace) -> None: _system_pages_from_data(manufacturers, coverages, db, profiles) ) print(f" {len(_system_page_map)} system IDs mapped to pages") - from siterender import link_coverage, system_ids # noqa: PLC0415 + from siterender import link_coverage, system_ids print("Generating system pages...") @@ -12936,7 +12931,7 @@ def _generate(args: argparse.Namespace) -> None: print(f"Removed {stale} page(s) nothing produced this run") -from sitediagrams import local_images, prepare_page, unresolved_images # noqa: E402,F401 +from sitediagrams import local_images, prepare_page, unresolved_images # noqa: E402 from sitewrite import ( # noqa: E402,F401 _produced, _record, diff --git a/scripts/identity.py b/scripts/identity.py index 15679a950..e801c8262 100644 --- a/scripts/identity.py +++ b/scripts/identity.py @@ -132,10 +132,10 @@ def main() -> int: "--strict", action="store_true", help="exit non-zero when any is found" ) args = parser.parse_args() - from common import work_from_repo_root # noqa: PLC0415 + from common import work_from_repo_root work_from_repo_root(args, parser, ["bios_dir"]) - from common import require_directory # noqa: PLC0415 + from common import require_directory require_directory(args.bios_dir) diff --git a/scripts/indexnow.py b/scripts/indexnow.py index 6d62939ac..0ac638617 100644 --- a/scripts/indexnow.py +++ b/scripts/indexnow.py @@ -27,7 +27,7 @@ import urllib.request from pathlib import Path sys.path.insert(0, os.path.dirname(__file__)) -from siteagents import INDEXNOW_FILE, INDEXNOW_KEY, SITE # noqa: E402 +from siteagents import INDEXNOW_FILE, INDEXNOW_KEY, SITE HOST = "abdess.github.io" # What one IndexNow request accepts. diff --git a/scripts/largefiles.py b/scripts/largefiles.py index dc87bc666..686391c6e 100644 --- a/scripts/largefiles.py +++ b/scripts/largefiles.py @@ -213,13 +213,12 @@ def _fetch_asset( for candidate, url in _asset_urls(name): try: req = urllib.request.Request(url, headers={"User-Agent": "retrobios/1.0"}) - with urllib.request.urlopen(req, timeout=300) as resp: - with open(tmp_path, "wb") as f: - while True: - chunk = resp.read(65536) - if not chunk: - break - f.write(chunk) + with urllib.request.urlopen(req, timeout=300) as resp, open(tmp_path, "wb") as f: + while True: + chunk = resp.read(65536) + if not chunk: + break + f.write(chunk) downloaded = True break except (urllib.error.URLError, OSError, http.client.HTTPException) as exc: @@ -384,7 +383,7 @@ def _served_digests() -> dict[str, str]: f"{LARGE_FILES_RELEASE}" ) headers = {"User-Agent": "retrobios/1.0", "Accept": "application/vnd.github+json"} - from common import github_token # noqa: PLC0415 (common imports this module) + from common import github_token token = github_token() if token: diff --git a/scripts/launchers.py b/scripts/launchers.py index 806c32804..78b92f676 100644 --- a/scripts/launchers.py +++ b/scripts/launchers.py @@ -284,7 +284,7 @@ def config_target(record: dict) -> tuple[str, list[str]]: if "." not in head or head.startswith("<"): # The file is the one the record installs, named by its path or, # when a variable spells the path, by the config file it cites. - from scraper.shell_launchers import config_ref, is_feature_ref, ref_path # noqa: PLC0415 + from scraper.shell_launchers import config_ref, is_feature_ref, ref_path installed = str((record.get("installs") or {}).get("path") or "").rsplit("/", 1)[-1] cited = [ @@ -392,7 +392,7 @@ def _file_matches(read_file: str, file: str, record: dict) -> bool: any file the launcher passes), a path, or the flag the launcher passes it with (amiberry's -f). """ - from fnmatch import fnmatch # noqa: PLC0415 + from fnmatch import fnmatch spelled = read_file.rsplit("/", 1)[-1].casefold() if file and fnmatch(file.casefold(), spelled): @@ -449,7 +449,7 @@ def config_evidence( values a menu offers: it goes in ``choices_from``, beside the code that writes the choice, and such a record needs (c) and (d) too. """ - from scraper.shell_launchers import config_ref, is_feature_ref # noqa: PLC0415 + from scraper.shell_launchers import config_ref, is_feature_ref cited = config_ref(str(record.get("source_ref") or "")) choices = str(record.get("choices_from") or "") @@ -503,13 +503,13 @@ _DEFAULT_PROFILES: dict[str, dict] | None = None def _profiles_or_repo(profiles: Mapping[str, dict] | None) -> Mapping[str, dict]: """The profiles given, else this repository's, read once.""" - global _DEFAULT_PROFILES # noqa: PLW0603 + global _DEFAULT_PROFILES if profiles is not None: return profiles if _DEFAULT_PROFILES is None: - from pathlib import Path # noqa: PLC0415 + from pathlib import Path - from common import load_emulator_profiles # noqa: PLC0415 + from common import load_emulator_profiles _DEFAULT_PROFILES = load_emulator_profiles( str(Path(__file__).resolve().parent.parent / "emulators") @@ -518,7 +518,7 @@ def _profiles_or_repo(profiles: Mapping[str, dict] | None) -> Mapping[str, dict] def _cites_config(record: dict) -> bool: - from scraper.shell_launchers import config_ref # noqa: PLC0415 + from scraper.shell_launchers import config_ref return bool(record.get("choices_from")) or bool(config_ref(str(record.get("source_ref") or ""))) @@ -887,7 +887,7 @@ def _roms_place(config: dict, path: str | None) -> Place | None: platform installs above its BIOS folder (AmberELEC), else the roms tree.""" if path is None: return None - from common import ROMS_ROOT, outer_layout # noqa: PLC0415 + from common import ROMS_ROOT, outer_layout layout = outer_layout(config, ROMS_ROOT) or {} if "install_prefix" in layout: @@ -903,7 +903,7 @@ def folder_in_configs(directory: str, config: dict) -> str | None: (``configs_root.path``): Batocera's /userdata/system/configs, where its generators start shadPS4 from configs/shadps4. """ - from common import CONFIGS_ROOT # noqa: PLC0415 + from common import CONFIGS_ROOT return folder_in_root(directory, config, CONFIGS_ROOT) @@ -915,7 +915,7 @@ def folder_in_roms(directory: str, config: dict) -> str | None: (``roms_root.path``): ROCKNIX's /storage/roms, which holds its BIOS folder and the folders its launchers run programs from. """ - from common import ROMS_ROOT, outer_layout # noqa: PLC0415 + from common import ROMS_ROOT, outer_layout spelled = directory.strip().rstrip("/") for variable in ROMS_ROOT_VARIABLES: @@ -929,7 +929,7 @@ def folder_in_roms(directory: str, config: dict) -> str | None: def folder_in_root(directory: str, config: dict, root: str) -> str | None: """A directory relative to an outer root's path, None outside it.""" - from common import outer_layout # noqa: PLC0415 + from common import outer_layout roms = str((outer_layout(config, root) or {}).get("path") or "").rstrip("/") directory = directory.strip().rstrip("/") diff --git a/scripts/list_platforms.py b/scripts/list_platforms.py index 88fa39319..e4ec3232a 100644 --- a/scripts/list_platforms.py +++ b/scripts/list_platforms.py @@ -27,7 +27,7 @@ def list_platforms() -> list[str]: def main() -> None: parser = argparse.ArgumentParser(allow_abbrev=False, description="List available platforms") args = parser.parse_args() - from common import work_from_repo_root # noqa: PLC0415 + from common import work_from_repo_root work_from_repo_root(args, parser, []) diff --git a/scripts/make_demo.py b/scripts/make_demo.py index 53b9f222c..5684f4cc5 100644 --- a/scripts/make_demo.py +++ b/scripts/make_demo.py @@ -198,7 +198,7 @@ def build_card(card: Path) -> None: class QuietHandler(http.server.SimpleHTTPRequestHandler): - def log_message(self, format: str, *args: object) -> None: # noqa: A002 + def log_message(self, format: str, *args: object) -> None: pass diff --git a/scripts/packextras.py b/scripts/packextras.py index 3d469bb2a..e713b229e 100644 --- a/scripts/packextras.py +++ b/scripts/packextras.py @@ -1324,10 +1324,6 @@ def _collect_emulator_extras( extras_prefix = placement.prefix is_slug_based = placement.slug_based - # Use strict YAML names (no DB alias enrichment) so that files known - # under an alias still get packed at the emulator's expected path. - yaml_names = platform_declarations(config, db, enrich=False) - if undeclared is None: undeclared = undeclared_report( config, emulators_dir, db, emu_profiles, target_cores, include_all @@ -1454,8 +1450,8 @@ def _collect_emulator_extras( continue if emu_name not in relevant: continue - for profile, is_standalone in platform_layouts(emu_name, profile, standalone_set): - for f in profile.get("files", []): + for layout, is_standalone in platform_layouts(emu_name, profile, standalone_set): + for f in layout.get("files", []): fname = f.get("name", "") if not fname: continue @@ -1524,17 +1520,17 @@ def _collect_emulator_extras( "destination": dest, "required": f.get("required", False), "hle_fallback": f.get("hle_fallback", False), - "source_emulator": profile.get("emulator", emu_name), + "source_emulator": layout.get("emulator", emu_name), "source_profile": emu_name, # The key the gap report gives the same entry. "source_name": fname, "source_path": raw, "category": f.get("category", "bios"), "source_system": f.get("system"), - "source_systems": entry_system_ids(f, profile), + "source_systems": entry_system_ids(f, layout), "region": f.get("region"), "selection_slot": f.get("selection_slot"), - **set_fields(f, profile), + **set_fields(f, layout), } # The same identity the first pass carries: without it the copy # resolves on its name alone and a same-named file of another diff --git a/scripts/packverify.py b/scripts/packverify.py index 0d49c3f4f..e42ab4c32 100644 --- a/scripts/packverify.py +++ b/scripts/packverify.py @@ -40,7 +40,7 @@ import zipfile from collections.abc import Callable -@functools.lru_cache(maxsize=None) +@functools.cache def _file_sha1(path: str) -> str: """SHA-1 of a cached data-directory file, read once per run.""" digest = hashlib.sha1() diff --git a/scripts/pipeline.py b/scripts/pipeline.py index 6b8b91a62..35040f87f 100644 --- a/scripts/pipeline.py +++ b/scripts/pipeline.py @@ -331,7 +331,7 @@ def _match_key(label: str) -> set[str]: def release_pack_keys(platforms_dir: str = "platforms") -> set[str]: """Comparable identities of the platforms --all builds a pack for: their registry ids and display names, normalized as _match_key does.""" - from common import list_release_pack_platforms, load_platform_config # noqa: PLC0415 + from common import list_release_pack_platforms, load_platform_config keys: set[str] = set() for name in list_release_pack_platforms(platforms_dir): @@ -446,9 +446,9 @@ def _tree_members( platform: str, platforms_dir: str, emulators_dir: str = "emulators", ) -> dict[str, int]: """Archive path -> size of every file the platform's data trees can add.""" - import generate_pack # noqa: PLC0415 - from common import load_emulator_profiles, load_platform_config # noqa: PLC0415 - from packpaths import _flat # noqa: PLC0415 + import generate_pack + from common import load_emulator_profiles, load_platform_config + from packpaths import _flat config = load_platform_config(platform, platforms_dir) base_dest = config.get("base_destination", "") @@ -488,8 +488,8 @@ def check_pack_destinations( set aside when its path and size are the cached file's and verify does not credit the path. """ - import json # noqa: PLC0415 - import zipfile # noqa: PLC0415 + import json + import zipfile print(f"\n--- {step_title(STEP_LABELS['consistency'])}, destinations ---") try: @@ -542,7 +542,7 @@ def emulator_variants(profiles: list[dict], full: bool) -> list[tuple[str, dict] sampled as check_narrowed_packs samples them unless *full*. A profile without a regional file has nothing --region could withdraw. """ - import region as region_mod # noqa: PLC0415 + import region as region_mod regions = sorted({ r for profile in profiles for fe in profile.get("files") or [] @@ -568,10 +568,10 @@ def check_emulator_packs( required-only rules are written twice, once per side, and only this comparison holds them together. No archive is written and no file read. """ - import generate_pack # noqa: PLC0415 - import packresolve # noqa: PLC0415 - import verify # noqa: PLC0415 - from common import ( # noqa: PLC0415 + import generate_pack + import packresolve + import verify + from common import ( ProfileSelectionError, _norm_system_id, build_zip_contents_index, @@ -690,8 +690,8 @@ def narrowed_variants( target, every system, --no-game-data and --required-only. Without *full*, regions, targets and systems are sampled (_matrix_coverage). """ - import region as region_mod # noqa: PLC0415 - from common import list_available_targets # noqa: PLC0415 + import region as region_mod + from common import list_available_targets regions = sorted({ r for entry in region_mod.platform_region_index(config, profiles).values() @@ -739,10 +739,10 @@ def check_narrowed_packs( compares every value. NARROWINGS_NOT_COMPARED says why --source and --one-per-slot are not compared. """ - import generate_pack # noqa: PLC0415 - import packresolve # noqa: PLC0415 - import verify # noqa: PLC0415 - from common import ( # noqa: PLC0415 + import generate_pack + import packresolve + import verify + from common import ( build_zip_contents_index, group_identical_platforms, list_registered_platforms, @@ -851,9 +851,9 @@ def check_split_packs( RetroBat's 21 openmsx/ twins of openMSX/ files. Offline, as every comparison of this step. """ - import generate_pack # noqa: PLC0415 - import packresolve # noqa: PLC0415 - from common import ( # noqa: PLC0415 + import generate_pack + import packresolve + from common import ( build_zip_contents_index, group_identical_platforms, list_registered_platforms, @@ -993,7 +993,7 @@ def _refuse_offline_export_without_originals( """ if not (args.offline and args.with_export): return - from exporter import discover_exporters # noqa: PLC0415 + from exporter import discover_exporters lacking = sorted( name for name, exporter in discover_exporters().items() diff --git a/scripts/profile_sync.py b/scripts/profile_sync.py index ef71dc549..06a50e567 100644 --- a/scripts/profile_sync.py +++ b/scripts/profile_sync.py @@ -162,8 +162,8 @@ def entry_hashes(entry: dict) -> list[str]: for source in (entry, *members): if not isinstance(source, dict): continue - for field in HASH_FIELDS: - for v in parse_hash_list(source.get(field)): + for field_name in HASH_FIELDS: + for v in parse_hash_list(source.get(field_name)): if v not in tokens: tokens.append(v) return tokens @@ -463,11 +463,11 @@ def collect_citations(document: dict, text: str | None = None) -> list[Citation] if (repo := upstream.parse_repo(url)) is not None ) citations: list[Citation] = [] - for kind, field, holder, key, value in _walk_document(document): + for kind, field_name, holder, key, value in _walk_document(document): if kind == "ref": for label, ref in source_ref_values(value): citations.append(Citation( - field=field, kind="ref", ref=ref, entry=holder, + field=field_name, kind="ref", ref=ref, entry=holder, holder=holder, key=key, label=label, )) if isinstance(value, str): @@ -475,7 +475,7 @@ def collect_citations(document: dict, text: str | None = None) -> list[Citation] ref_prose_text(value), known ): citations.append(Citation( - field=field, kind="prose", ref=run, holder=holder, + field=field_name, kind="prose", ref=run, holder=holder, key=key, line=line, path_span=path_span, spans=spans, parts=parts, wrapped=bool(joined_at), joined_at=joined_at, )) @@ -484,7 +484,7 @@ def collect_citations(document: dict, text: str | None = None) -> list[Citation] value, known ): citations.append(Citation( - field=field, kind="prose", ref=run, holder=holder, key=key, + field=field_name, kind="prose", ref=run, holder=holder, key=key, line=line, path_span=path_span, spans=spans, parts=parts, wrapped=bool(joined_at), joined_at=joined_at, )) @@ -1108,8 +1108,8 @@ def select_repo(profile: dict) -> upstream.Repo | None: A source keyed by build mode with no upstream (uzdoom) names its repositories only in the dict, which a plain string read never parses. """ - for field in ("source", "upstream"): - repo = upstream.parse_repo(str(profile.get(field) or "")) + for field_name in ("source", "upstream"): + repo = upstream.parse_repo(str(profile.get(field_name) or "")) if repo is not None: return repo for _, _, url in declared_repositories(profile): @@ -1160,7 +1160,7 @@ def select_views( # A port living on a branch of a fork is absent from the default tip, so # the branch it was read from is followed when the profile names one. declared = str(profile.get("source_branch") or "") or None - for field, mode, url in declared_repositories(profile): + for field_name, mode, url in declared_repositories(profile): repo = upstream.parse_repo(url) if repo is None or (repo.host, repo.slug) in seen: continue @@ -1168,7 +1168,7 @@ def select_views( # its pin is source_commit. It read `source_mirror_commit`, a field # no profile carries, and fell back to profiled_date, which a bump # never moves (eden judged from f6e76860 while pinned on d16735f5). - pin_field = "source" if field == "source_mirror" else field + pin_field = "source" if field_name == "source_mirror" else field_name branch = declared if pin_field == "source" else None head = None try: @@ -1206,7 +1206,7 @@ def select_views( if relation and relation[0] == 0 and relation[1] > 0: head = upstream.resolve_head(repo, cache_dir, offline, branch, fresh=True) or head seen.add((repo.host, repo.slug)) - views.append(RepoView(repo, pin, head, origin, field, mode)) + views.append(RepoView(repo, pin, head, origin, field_name, mode)) if gone and not views: raise upstream.GoneError(f"{profile.get('emulator', '?')}: every declared repository is gone") views = _follow_fork_base(_follow_submodule(views, cache_dir, offline), cache_dir, offline) @@ -1311,12 +1311,12 @@ def declared_repositories(profile: dict) -> list[tuple[str, str, str]]: a declared repository still answers. """ urls: list[tuple[str, str, str]] = [] - for field in ("source", "upstream", "source_mirror"): - value = profile.get(field) + for field_name in ("source", "upstream", "source_mirror"): + value = profile.get(field_name) if isinstance(value, dict): - urls.extend((field, str(k), str(v)) for k, v in value.items() if v) + urls.extend((field_name, str(k), str(v)) for k, v in value.items() if v) elif value: - urls.append((field, "", str(value))) + urls.append((field_name, "", str(value))) return urls @@ -5520,9 +5520,9 @@ def _refresh_source_paths(args: argparse.Namespace) -> None: """ if not _WRITTEN or args.dry_run or args.offline or os.environ.get("RETROBIOS_OFFLINE"): return - import common # noqa: PLC0415 - import sitesources # noqa: PLC0415 - from common import write_if_changed # noqa: PLC0415 + import common + import sitesources + from common import write_if_changed # The run loaded the profiles before writing them, and the loader caches # by directory: read again, the record described the pins just replaced diff --git a/scripts/provenance_report.py b/scripts/provenance_report.py index 16ec2f5f8..8eba45d91 100644 --- a/scripts/provenance_report.py +++ b/scripts/provenance_report.py @@ -384,7 +384,7 @@ def main() -> int: "(the pipeline writes derivable.json)", ) args = parser.parse_args() - from common import work_from_repo_root # noqa: PLC0415 + from common import work_from_repo_root work_from_repo_root(args, parser, ["db", "provenance_dir", "emulators_dir", "write_derivable"]) if args.write_derivable and not args.derive: @@ -400,7 +400,7 @@ def main() -> int: report = build_report(db, snapshots, archive_members(db), needs=needs) derived: dict[str, dict] = {} if args.derive: - from derivations import derivable # noqa: PLC0415 + from derivations import derivable derived = derivable((e for d in report.values() for e in d["missing"]), db) for data in report.values(): diff --git a/scripts/refresh_data_dirs.py b/scripts/refresh_data_dirs.py index 575b73917..eb3655a0c 100644 --- a/scripts/refresh_data_dirs.py +++ b/scripts/refresh_data_dirs.py @@ -303,13 +303,12 @@ def _download_and_extract( log.info("downloading %s", source_url) req = urllib.request.Request(source_url, headers={"User-Agent": USER_AGENT}) - with urllib.request.urlopen(req, timeout=DOWNLOAD_TIMEOUT) as resp: - with open(tarball_path, "wb") as f: - while True: - chunk = resp.read(65536) - if not chunk: - break - f.write(chunk) + with urllib.request.urlopen(req, timeout=DOWNLOAD_TIMEOUT) as resp, open(tarball_path, "wb") as f: + while True: + chunk = resp.read(65536) + if not chunk: + break + f.write(chunk) if measured is not None: measured(tarball_path.stat().st_size) @@ -385,13 +384,12 @@ def _download_and_extract_zip( log.info("downloading %s", source_url) req = urllib.request.Request(source_url, headers={"User-Agent": USER_AGENT}) - with urllib.request.urlopen(req, timeout=DOWNLOAD_TIMEOUT) as resp: - with open(zip_path, "wb") as f: - while True: - chunk = resp.read(65536) - if not chunk: - break - f.write(chunk) + with urllib.request.urlopen(req, timeout=DOWNLOAD_TIMEOUT) as resp, open(zip_path, "wb") as f: + while True: + chunk = resp.read(65536) + if not chunk: + break + f.write(chunk) if measured is not None: measured(zip_path.stat().st_size) @@ -652,7 +650,7 @@ def refresh_all( ) if any(results.values()): # A cache the resolver indexed in this process has changed under it. - from common import forget_data_dir_index # noqa: PLC0415 + from common import forget_data_dir_index forget_data_dir_index() return results diff --git a/scripts/refresh_stale.py b/scripts/refresh_stale.py index c4c4fe37e..2007e6109 100755 --- a/scripts/refresh_stale.py +++ b/scripts/refresh_stale.py @@ -461,7 +461,7 @@ def _github_token_env() -> dict[str, str]: emudeck and retropie target scrapers hit the GitHub API. Without a token the unauthenticated rate limit (60/h) is burnt within a few platforms. """ - from common import github_token # noqa: PLC0415 + from common import github_token env = os.environ.copy() token = github_token() diff --git a/scripts/region.py b/scripts/region.py index 2d0a69552..0fa9fcfda 100644 --- a/scripts/region.py +++ b/scripts/region.py @@ -125,7 +125,7 @@ def unknown_region_message(raw: str, aliases: dict[str, str], regions: frozenset `unknown region: 'uss'` left the user to read the source for `us`. """ - import difflib # noqa: PLC0415 + import difflib spelled = raw.strip() close = difflib.get_close_matches(spelled.lower(), [*aliases, *regions], n=3, cutoff=0.5) diff --git a/scripts/region_audit.py b/scripts/region_audit.py index 731e0d2a8..ab147cfa4 100644 --- a/scripts/region_audit.py +++ b/scripts/region_audit.py @@ -201,7 +201,7 @@ def main() -> int: ) parser.add_argument("--json", action="store_true", help="Machine-readable output") args = parser.parse_args() - from common import work_from_repo_root # noqa: PLC0415 + from common import work_from_repo_root work_from_repo_root(args, parser, ["db", "emulators_dir"]) diff --git a/scripts/region_check.py b/scripts/region_check.py index 6fa9a9019..b33bbf77e 100644 --- a/scripts/region_check.py +++ b/scripts/region_check.py @@ -46,7 +46,7 @@ if sys.version_info < (3, 9): sys.path.insert(0, str(Path(__file__).resolve().parent)) -import yaml # noqa: E402 +import yaml ROOT = Path(__file__).resolve().parent.parent CONTENT_FILE = ROOT / "tests" / "campaign" / "content.yml" @@ -254,7 +254,7 @@ def content_file(item: dict, content_dir: Path) -> Path: def nightly_core(core: str) -> tuple[Path, str]: """The buildbot nightly of a core, downloaded once, and its URL.""" - import zipfile # noqa: PLC0415 + import zipfile url = NIGHTLY.format(core=core) target = CORES / f"{core}_libretro.so" @@ -277,7 +277,7 @@ def nightly_core(core: str) -> tuple[Path, str]: def pack_files(emulator: str, region: str, work: Path) -> dict[str, Path]: """The files generate_pack puts in the emulator's pack for one region, extracted, by their path in the pack.""" - from ziptools import safe_extract_zip # noqa: PLC0415 + from ziptools import safe_extract_zip out_dir = work / "pack" subprocess.run([sys.executable, str(ROOT / "scripts" / "generate_pack.py"), "--emulator", emulator, @@ -293,7 +293,7 @@ def pack_files(emulator: str, region: str, work: Path) -> dict[str, Path]: def local_resolver() -> Callable[[dict], Path | None]: - from common import load_database, resolve_local_file # noqa: PLC0415 + from common import load_database, resolve_local_file db = load_database(str(ROOT / "database.json")) @@ -329,7 +329,7 @@ def probe_when_idle(argv: list[str], max_wait: float, def run(args: argparse.Namespace) -> int: - from common import load_emulator_profiles # noqa: PLC0415 + from common import load_emulator_profiles profile = load_emulator_profiles(str(ROOT / "emulators"))[args.emulator] entries = region_entries(profile, args.system) @@ -373,8 +373,8 @@ def collect(root: Path = ROOT, stored_records: list | None = None) -> list[dict] """Every region outcome the records under measurements/ hold. A game listed under several systems (sega-megacd and mega-cd) is judged under the one whose profile ran it.""" - from common import load_emulator_profiles # noqa: PLC0415 - from measurement_records import live, read_records # noqa: PLC0415 + from common import load_emulator_profiles + from measurement_records import live, read_records content: dict[str, list[tuple[str, dict]]] = {} for system, items in load_content(root / "tests" / "campaign" / "content.yml").items(): diff --git a/scripts/retired_files.py b/scripts/retired_files.py index 7a2d3642d..f9f1d3da1 100644 --- a/scripts/retired_files.py +++ b/scripts/retired_files.py @@ -25,7 +25,7 @@ import sys from pathlib import Path sys.path.insert(0, str(Path(__file__).parent)) -from common import run_cli, write_if_changed # noqa: E402 +from common import run_cli, write_if_changed REPO_ROOT = Path(__file__).resolve().parents[1] RETIRED_FILE = REPO_ROOT / "retired.json" diff --git a/scripts/romset_recipes.py b/scripts/romset_recipes.py index 75a56dd80..c8dcb5cb5 100644 --- a/scripts/romset_recipes.py +++ b/scripts/romset_recipes.py @@ -210,7 +210,7 @@ class AtomPool: """Write the digest cache back, when this run learned anything.""" if self._digest_cache is None or not self._digests_changed: return - from artifacts import write_text_atomic # noqa: PLC0415 + from artifacts import write_text_atomic self._digest_cache.parent.mkdir(parents=True, exist_ok=True) write_text_atomic( @@ -481,7 +481,7 @@ def print_missing(gap: dict) -> None: def run_capture(args: argparse.Namespace, db: dict) -> int: """Write recipes/archives.json for every archive the database lists.""" - import archive_build # noqa: PLC0415 + import archive_build try: records, failed = archive_build.capture( @@ -512,7 +512,7 @@ def run_capture(args: argparse.Namespace, db: dict) -> int: def run_build(args: argparse.Namespace, db: dict) -> int: """Build one archive, or all of them, from the members the collection holds.""" - import archive_build # noqa: PLC0415 + import archive_build if not args.output_dir: print("ERROR: --build and --build-all need --output-dir", file=sys.stderr) diff --git a/scripts/scraper/batocera_launchers.py b/scripts/scraper/batocera_launchers.py index 3a14cdc22..b336287c3 100644 --- a/scripts/scraper/batocera_launchers.py +++ b/scripts/scraper/batocera_launchers.py @@ -104,7 +104,7 @@ def configs_root(cg: Configgen) -> dict[str, str]: starts an emulator from (shadPS4's configs/shadps4), with the lines that build it and BIOS. """ - import posixpath # noqa: PLC0415 + import posixpath src = cg.source(f"{cg.generators.rsplit('/', 1)[0]}/batoceraPaths.py") if "CONFIGS" not in cg.paths: @@ -1128,9 +1128,9 @@ def search_paths(cg: Configgen) -> list[Launcher]: """Every /userdata/bios path a generator's command line names, read as KNULLI's generic reader reads its fork of the same generator.""" try: - from .knulli_launchers import GenericSites, bios_sites # noqa: PLC0415 + from .knulli_launchers import GenericSites, bios_sites except ImportError: - from knulli_launchers import GenericSites, bios_sites # type: ignore[no-redef] # noqa: PLC0415 + from knulli_launchers import GenericSites, bios_sites # type: ignore[no-redef] # A boot disk image the command line names (the Macintosh's # /userdata/bios/.img) is a file, no search path. return [ diff --git a/scripts/scraper/configgen_launchers.py b/scripts/scraper/configgen_launchers.py index 4f6d05442..0b6fa6067 100644 --- a/scripts/scraper/configgen_launchers.py +++ b/scripts/scraper/configgen_launchers.py @@ -188,9 +188,7 @@ def _calls(scope: ast.AST, attr: str | None = None, name: str | None = None) -> if not isinstance(node, ast.Call): continue func = node.func - if attr is not None and isinstance(func, ast.Attribute) and func.attr == attr: - found.append(node) - elif name is not None and isinstance(func, ast.Name) and func.id == name: + if attr is not None and isinstance(func, ast.Attribute) and func.attr == attr or name is not None and isinstance(func, ast.Name) and func.id == name: found.append(node) return sorted(found, key=lambda call: (call.lineno, call.col_offset)) diff --git a/scripts/scraper/coreinfo_scraper.py b/scripts/scraper/coreinfo_scraper.py index 40c35db76..d7bc1a499 100644 --- a/scripts/scraper/coreinfo_scraper.py +++ b/scripts/scraper/coreinfo_scraper.py @@ -335,9 +335,7 @@ def main() -> None: found = 0 missing = [] for r in reqs: - if r.name in db["indexes"]["by_name"]: - found += 1 - elif r.md5 and r.md5 in db["indexes"]["by_md5"]: + if r.name in db["indexes"]["by_name"] or r.md5 and r.md5 in db["indexes"]["by_md5"]: found += 1 else: missing.append(r) diff --git a/scripts/scraper/emudeck_scraper.py b/scripts/scraper/emudeck_scraper.py index d4fadacf0..aabb91611 100644 --- a/scripts/scraper/emudeck_scraper.py +++ b/scripts/scraper/emudeck_scraper.py @@ -335,19 +335,19 @@ class Scraper(BaseScraper): bios_col = "" for key in row: if key and "bios" in key.lower(): - bios_col = self._clean_markdown((row[key] or "")) + bios_col = self._clean_markdown(row[key] or "") break if not bios_col or bios_col.lower() in ("not required", ""): continue folder_col = "" for key in row: if key and "folder" in key.lower(): - folder_col = self._clean_markdown((row[key] or "")) + folder_col = self._clean_markdown(row[key] or "") break system_col = "" for key in row: if key and "system" in key.lower(): - system_col = self._clean_markdown((row[key] or "")) + system_col = self._clean_markdown(row[key] or "") break slug = None for part in re.split(r"[`\s/]+", folder_col): diff --git a/scripts/scraper/game_dat_importer.py b/scripts/scraper/game_dat_importer.py index 0d6d4afb1..ecff9f160 100644 --- a/scripts/scraper/game_dat_importer.py +++ b/scripts/scraper/game_dat_importer.py @@ -26,7 +26,6 @@ from __future__ import annotations import argparse import gzip -import io import json import re import sys diff --git a/scripts/scraper/knulli_scraper.py b/scripts/scraper/knulli_scraper.py index 6ec04da61..afdd18e4b 100644 --- a/scripts/scraper/knulli_scraper.py +++ b/scripts/scraper/knulli_scraper.py @@ -94,9 +94,9 @@ class Scraper(BaseScraper): def submodule_revision(self) -> str: """The batocera.linux commit KNULLI's batocera submodule pins at the tag.""" - import json # noqa: PLC0415 + import json - from .base_scraper import github_headers # noqa: PLC0415 + from .base_scraper import github_headers url = _SUBMODULE.format(path=BATOCERA_SUBMODULE, ref=self.tag) req = urllib.request.Request(url, headers=github_headers()) diff --git a/scripts/scraper/retrobat_launchers.py b/scripts/scraper/retrobat_launchers.py index a443f83c3..e2541fb50 100644 --- a/scripts/scraper/retrobat_launchers.py +++ b/scripts/scraper/retrobat_launchers.py @@ -572,7 +572,7 @@ def hatari_libretro(sources: dict[str, Source]) -> list[Record]: guard = src.find(r'if \(core != "hatarib"\)', "hatarib guard") method = src.enclosing(guard.start()) tos_img = src.find( - rf'string (\w+) = Path\.Combine\((\w+), "([^"]+)"\);', "hatarib tos.img path", + r'string (\w+) = Path\.Combine\((\w+), "([^"]+)"\);', "hatarib tos.img path", method[0], method[1], ) own = src.find( diff --git a/scripts/scraper/retrodeck_scraper.py b/scripts/scraper/retrodeck_scraper.py index a1e6ffe75..7b1bd3b14 100644 --- a/scripts/scraper/retrodeck_scraper.py +++ b/scripts/scraper/retrodeck_scraper.py @@ -310,7 +310,7 @@ class Scraper(BaseScraper): def _fetch_remote_manifests(self) -> list[tuple[str, dict]]: """Fetch component manifests via GitHub API.""" - from common import github_token # noqa: PLC0415 + from common import github_token token = github_token() headers = {"User-Agent": "retrobios-scraper/1.0"} diff --git a/scripts/scraper/retropie_launchers.py b/scripts/scraper/retropie_launchers.py index ceb3eee99..544eb1adb 100644 --- a/scripts/scraper/retropie_launchers.py +++ b/scripts/scraper/retropie_launchers.py @@ -483,7 +483,7 @@ LIST_SEPARATORS = {"advmame": ":", "advmame-0.94": ":", "advmame-1.4": ":"} DEFAULT_LIST_SEPARATOR = ";" -def _search_list_in_roms(event: "Event", separator: str = DEFAULT_LIST_SEPARATOR) -> bool: +def _search_list_in_roms(event: Event, separator: str = DEFAULT_LIST_SEPARATOR) -> bool: """An iniSet whose value is a list of folders below the roms root. One folder alone is where a program writes (cfg_directory, nvram_directory diff --git a/scripts/scraper/romfolders/__main__.py b/scripts/scraper/romfolders/__main__.py index ef197a8ac..ad62ce559 100644 --- a/scripts/scraper/romfolders/__main__.py +++ b/scripts/scraper/romfolders/__main__.py @@ -14,8 +14,8 @@ from pathlib import Path import yaml from . import Fetcher, SourceError, load_sources, scrape_setup -from upstream import UpstreamError # noqa: E402 (the package puts scripts/ on sys.path) -from artifacts import write_text_atomic # noqa: E402 +from upstream import UpstreamError +from artifacts import write_text_atomic from ..base_scraper import _PlatformDumper DEFAULT_DIR = Path("platforms") / "romfolders" diff --git a/scripts/scraper/targets/__init__.py b/scripts/scraper/targets/__init__.py index 08381331f..f72d7ecb3 100644 --- a/scripts/scraper/targets/__init__.py +++ b/scripts/scraper/targets/__init__.py @@ -57,8 +57,8 @@ class BaseTargetScraper(ABC): """Write target data to YAML file.""" try: import yaml - except ImportError: - raise ImportError("PyYAML required: pip install pyyaml") + except ImportError as exc: + raise ImportError("PyYAML required: pip install pyyaml") from exc from common import write_text_atomic write_text_atomic( diff --git a/scripts/scraper/targets/retropie_targets_scraper.py b/scripts/scraper/targets/retropie_targets_scraper.py index a16bc46d0..12d2b8112 100644 --- a/scripts/scraper/targets/retropie_targets_scraper.py +++ b/scripts/scraper/targets/retropie_targets_scraper.py @@ -68,7 +68,7 @@ _MODULE_FLAGS_RE = re.compile(r'rp_module_flags\s*=\s*["\']([^"\']*)["\']') def _fetch(url: str, accept: str = "text/plain") -> str: headers = {"User-Agent": "retrobios-scraper/1.0", "Accept": accept} - from common import github_token # noqa: PLC0415 + from common import github_token token = github_token() if token and "api.github.com" in url: diff --git a/scripts/scraper/targets/rocknix_targets_scraper.py b/scripts/scraper/targets/rocknix_targets_scraper.py index e9b5f7dd3..86cd8cf81 100644 --- a/scripts/scraper/targets/rocknix_targets_scraper.py +++ b/scripts/scraper/targets/rocknix_targets_scraper.py @@ -214,7 +214,7 @@ class Scraper(BaseTargetScraper): return fetch_bytes(f"{RAW_BASE.format(tag=self.tag)}/{path}").decode("utf-8") def _devices(self) -> list[str]: - import json # noqa: PLC0415 + import json listing = json.loads(fetch_bytes( f"{GITHUB_API}/{DEVICES_DIR}?ref={self.tag}", headers=github_headers() diff --git a/scripts/sect233r1.py b/scripts/sect233r1.py index 3a92cfe00..258077641 100644 --- a/scripts/sect233r1.py +++ b/scripts/sect233r1.py @@ -226,7 +226,7 @@ def ecdsa_verify_sha256( h = hashlib.sha256(message).digest() e = int.from_bytes(h, "big") # Truncate to bit length of n - if 256 > _N_BITLEN: + if _N_BITLEN < 256: e >>= 256 - _N_BITLEN # w = s^(-1) mod n diff --git a/scripts/site_markdown.py b/scripts/site_markdown.py index 6ce944994..86a9f2985 100644 --- a/scripts/site_markdown.py +++ b/scripts/site_markdown.py @@ -37,7 +37,7 @@ from html.parser import HTMLParser from pathlib import Path sys.path.insert(0, os.path.dirname(__file__)) -from common import run_cli # noqa: E402 +from common import run_cli SITE = "https://abdess.github.io" BASE = "/retrobios/" diff --git a/scripts/sitecollection.py b/scripts/sitecollection.py index bdb154dec..daea42e9c 100644 --- a/scripts/sitecollection.py +++ b/scripts/sitecollection.py @@ -13,8 +13,8 @@ import os import sys sys.path.insert(0, os.path.dirname(__file__)) -import siteinputs # noqa: E402 -from common import GAME_DATA_TOPS, load_emulator_profiles # noqa: E402 +import siteinputs +from common import GAME_DATA_TOPS, load_emulator_profiles def _copy_places(db: dict) -> dict[str, set[tuple[str, str, str]]]: @@ -94,7 +94,7 @@ def _engine_sections(manufacturers: dict[str, dict[str, list]]) -> dict[str, dic top joins that top, and a folder named by a profile key is headed with the engine's name (SECTION_LABELS), its address unchanged. """ - from siterender import _PROGRAM_TOPS, SECTION_LABELS, record_card_move # noqa: PLC0415 + from siterender import _PROGRAM_TOPS, SECTION_LABELS, record_card_move profiles = {key: profile for key, profile in _profiles_on_disk().items() if profile.get("type") != "alias" and profile.get("role") != "test"} @@ -164,6 +164,6 @@ def _profiles_on_disk() -> dict[str, dict]: return _profiles_in(str(siteinputs.current().emulators), skip_aliases=False) -@functools.lru_cache(maxsize=None) +@functools.cache def _profiles_in(emulators_dir: str, skip_aliases: bool) -> dict[str, dict]: return load_emulator_profiles(emulators_dir, skip_aliases=skip_aliases) diff --git a/scripts/sitediagrams.py b/scripts/sitediagrams.py index 20fa6f057..c33fa6933 100644 --- a/scripts/sitediagrams.py +++ b/scripts/sitediagrams.py @@ -35,7 +35,7 @@ import urllib.parse from collections import Counter from collections.abc import Callable from dataclasses import dataclass, field -from functools import lru_cache +from functools import cache from pathlib import Path from xml.sax.saxutils import escape @@ -415,7 +415,7 @@ def registry() -> dict: return _registry_in(str(siteinputs.current().platforms)) -@lru_cache(maxsize=None) +@cache def _registry_in(platforms_dir: str) -> dict: import yaml @@ -429,7 +429,7 @@ def setups() -> tuple[str, ...]: return _setups_in(str(siteinputs.current().platforms)) -@lru_cache(maxsize=None) +@cache def _setups_in(platforms_dir: str) -> tuple[str, ...]: from common import list_registered_platforms @@ -449,7 +449,7 @@ def platform_modes() -> dict[str, tuple[str, str, str | None]]: return _platform_modes_in(str(siteinputs.current().platforms)) -@lru_cache(maxsize=None) +@cache def _platform_modes_in(platforms_dir: str) -> dict[str, tuple[str, str, str | None]]: from common import load_platform_config @@ -478,7 +478,7 @@ def emulator_names() -> dict[str, str]: return _emulator_names_in(str(siteinputs.current().emulators)) -@lru_cache(maxsize=None) +@cache def _emulator_names_in(emulators_dir: str) -> dict[str, str]: import yaml @@ -562,7 +562,7 @@ def _mode_summary() -> str: MINUI_EXAMPLES = (("Sony PlayStation", "PS"), ("Game Boy Advance", "GBA"), ("Sega Genesis", "MD")) -@lru_cache(maxsize=None) +@cache def minui_files() -> dict[str, list[str]]: manifest = json.loads((ROOT / "install" / "minui.json").read_text(encoding="utf-8")) by_tag: dict[str, list[str]] = {} @@ -747,7 +747,7 @@ def _figures() -> dict[str, Figure]: } -@lru_cache(maxsize=None) +@cache def figures() -> dict[str, Figure]: return _figures() @@ -818,7 +818,7 @@ IMAGE_LINK = re.compile(r"(!\[[^\]\n]*\]\()(https?://[^)\s]+)(\))") IMG_SRC = re.compile(r'(]*?\bsrc=")(https?://[^"]+)(")') -@lru_cache(maxsize=None) +@cache def local_images() -> dict[str, str]: """Remote URL -> path under the site root, from the two source manifests.""" mapping: dict[str, str] = {} @@ -928,7 +928,7 @@ def _string(node: ast.expr, constants: dict[str, str]) -> str: raise ValueError(f"install.py: an option help that is not a string: {ast.unparse(node)}") -@lru_cache(maxsize=None) +@cache def installer_options() -> tuple[tuple[str, str], ...]: """(usage, help) for each option of install.py, in the order --help lists them.""" tree = ast.parse((ROOT / "install.py").read_text(encoding="utf-8")) diff --git a/scripts/sitemeasurements.py b/scripts/sitemeasurements.py index e7a71a05c..dfa03af49 100644 --- a/scripts/sitemeasurements.py +++ b/scripts/sitemeasurements.py @@ -137,7 +137,7 @@ def opened(record: dict) -> str | None: def load_observations(path: Path) -> dict[str, dict]: """Each record id or subject an observation covers, with its issue number and words.""" - import yaml # noqa: PLC0415 + import yaml if not path.is_file(): return {} @@ -430,7 +430,7 @@ class Built: def load_profiles(emulators_dir: Path) -> dict: - from common import load_emulator_profiles # noqa: PLC0415 + from common import load_emulator_profiles return load_emulator_profiles(str(emulators_dir), skip_aliases=False) diff --git a/scripts/sitesources.py b/scripts/sitesources.py index a5cdbbccc..cf4b39ec5 100644 --- a/scripts/sitesources.py +++ b/scripts/sitesources.py @@ -173,7 +173,7 @@ def tree_key(repo: upstream.Repo, pin: str) -> str: return f"{repo.host}/{repo.slug}@{pin}" -@functools.lru_cache(maxsize=None) +@functools.cache def _verified() -> dict[str, frozenset[str]]: """The committed record, empty when it has not been written.""" try: @@ -183,7 +183,7 @@ def _verified() -> dict[str, frozenset[str]]: return {key: frozenset(paths) for key, paths in data.items()} -@functools.lru_cache(maxsize=None) +@functools.cache def _tree_paths(repo: upstream.Repo, pin: str) -> frozenset[str]: """The cited paths of a repository at a revision that its tree holds.""" return _verified().get(tree_key(repo, pin), frozenset()) @@ -767,7 +767,7 @@ def main() -> int: if not args.fetch and not any(path.is_dir() for path in cache_dirs): print(f"Error: no tree cache at {', '.join(map(str, cache_dirs))}", file=sys.stderr) return 1 - from common import ( # noqa: PLC0415 + from common import ( load_emulator_profiles, repository_output_lock, write_if_changed, diff --git a/scripts/sitesteps.py b/scripts/sitesteps.py index f79f437c5..20921a716 100644 --- a/scripts/sitesteps.py +++ b/scripts/sitesteps.py @@ -265,7 +265,7 @@ def steps_figure(tab: str) -> list[str]: def tab_demo(tab: str) -> list[str]: """The recording a tab shows, as generate_site writes the component.""" - from generate_site import install_demo # noqa: PLC0415 + from generate_site import install_demo variant = demo_variant(tab) return install_demo(variant, tab) if variant else [] diff --git a/scripts/slot.py b/scripts/slot.py index 3d7b81ff0..68ce93cd5 100644 --- a/scripts/slot.py +++ b/scripts/slot.py @@ -53,7 +53,7 @@ def platform_slot_claims( config: dict, profiles: dict, target_cores: set[str] | None = None ) -> dict[str, dict[str, dict]]: """What each emulator a platform runs declares at each key, unmerged.""" - from common import resolve_platform_cores # noqa: PLC0415 + from common import resolve_platform_cores cores = resolve_platform_cores(config, profiles, target_cores=target_cores) return slot_claims({n: profiles[n] for n in cores if n in profiles}) diff --git a/scripts/slots.py b/scripts/slots.py index 5297eadb0..07b1c2d93 100644 --- a/scripts/slots.py +++ b/scripts/slots.py @@ -201,7 +201,7 @@ def profile_claims( standalone_cores = standalone_cores or set() placement = None if config is not None: - from packextras import ExtraPlacement # noqa: PLC0415 + from packextras import ExtraPlacement placement = ExtraPlacement(config, base_dest, profiles) claims: list[Claim] = [] @@ -212,14 +212,14 @@ def profile_claims( # carries its scan candidates, never its named entries. if profile.get("bios_mode") == "agnostic": continue - for profile, is_standalone in platform_layouts(emu_name, profile, standalone_cores): + for layout, is_standalone in platform_layouts(emu_name, profile, standalone_cores): claims.extend( _archive_claims( - emu_name, profile, is_standalone, db, base_dest, placement, + emu_name, layout, is_standalone, db, base_dest, placement, zip_contents, data_dir_registry, ) ) - for entry in profile.get("files") or []: + for entry in layout.get("files") or []: if not isinstance(entry, dict): continue # The same rule as the gap report and the builder: an entry the @@ -249,7 +249,7 @@ def profile_claims( { "profile": emu_name, "system": entry.get("system"), - "systems": entry_system_ids(entry, profile), + "systems": entry_system_ids(entry, layout), }, dest, ) @@ -259,7 +259,7 @@ def profile_claims( # The owner's own copy is the one the builder ships. local, status = resolve_local_file( { - **with_archive_members(entry, profile.get("files") or []), + **with_archive_members(entry, layout.get("files") or []), "source_profile": emu_name, }, db, @@ -269,7 +269,7 @@ def profile_claims( ) if status == "name_exact" and _size_the_code_reads(entry, local): status = SIZE_EXACT - accepts = tuple(content_alternatives(entry, profile)) + accepts = tuple(content_alternatives(entry, layout)) claims.append( Claim( origin="profile", @@ -1038,7 +1038,7 @@ def main() -> int: "without it the run reports them and exits 0", ) args = parser.parse_args() - from common import work_from_repo_root # noqa: PLC0415 + from common import work_from_repo_root work_from_repo_root(args, parser, ["db", "platforms_dir", "emulators_dir"]) diff --git a/scripts/standalone_probe.py b/scripts/standalone_probe.py index 3f5d7d941..cbf6a35a9 100644 --- a/scripts/standalone_probe.py +++ b/scripts/standalone_probe.py @@ -230,7 +230,7 @@ def parse_xwd(data: bytes) -> tuple[int, int, bytes]: # -------------------------------------------------------------------------- def github_releases(repo: str) -> list[dict]: - from scraper.base_scraper import github_headers # noqa: PLC0415 + from scraper.base_scraper import github_headers request = urllib.request.Request(f"https://api.github.com/repos/{repo}/releases", headers=github_headers()) diff --git a/scripts/upstream.py b/scripts/upstream.py index e514e980e..a37604cad 100644 --- a/scripts/upstream.py +++ b/scripts/upstream.py @@ -230,7 +230,7 @@ def _headers(url: str, accept_json: bool = False) -> dict[str, str]: if accept_json: headers["Accept"] = "application/json" if urllib.parse.urlsplit(url).netloc in GITHUB_HOSTS: - from common import github_token # noqa: PLC0415 + from common import github_token # GITHUB_TOKEN, else the one gh is logged in with. token = github_token() @@ -667,7 +667,7 @@ def _github_graphql( GraphQL refuses anonymous calls, so an untokened run keeps the REST answer it already had. """ - from common import github_token # noqa: PLC0415 + from common import github_token body = json.dumps({"query": query, "variables": variables}, sort_keys=True) target = Path(cache_dir) / "_api" / f"{hashlib.sha256(body.encode()).hexdigest()}.json" diff --git a/scripts/validate_schemas.py b/scripts/validate_schemas.py index 687e9d40d..60fff9a8f 100644 --- a/scripts/validate_schemas.py +++ b/scripts/validate_schemas.py @@ -116,7 +116,7 @@ def _config_records_without_evidence(path: Path, document: object) -> list[str]: """ if not isinstance(document, dict): return [] - from scraper.shell_launchers import config_ref, is_feature_ref # noqa: PLC0415 + from scraper.shell_launchers import config_ref, is_feature_ref out: list[str] = [] for index, record in enumerate(document.get("launchers") or []): @@ -213,9 +213,7 @@ def _group_requirement_split(path: Path, document: object) -> list[str]: _CODE_SUFFIXES = frozenset( - "c cc cpp cxx c++ h hh hpp hxx inc inl ipp m mm mjs cjs js jsx ts tsx py cs java kt " - "go rs lua pas pp asm s sh bash zsh ps1 bat cmd vbs swift d zig nim qml qc rb pl php " - "scala ml hs dart vue ino z80 smali".split() + ["c", "cc", "cpp", "cxx", "c++", "h", "hh", "hpp", "hxx", "inc", "inl", "ipp", "m", "mm", "mjs", "cjs", "js", "jsx", "ts", "tsx", "py", "cs", "java", "kt", "go", "rs", "lua", "pas", "pp", "asm", "s", "sh", "bash", "zsh", "ps1", "bat", "cmd", "vbs", "swift", "d", "zig", "nim", "qml", "qc", "rb", "pl", "php", "scala", "ml", "hs", "dart", "vue", "ino", "z80", "smali"] ) _CODE_FILE = re.compile(r"(?<=[\w+-])\.([A-Za-z0-9+]+)\b") # A compiled image: a part that names one has to say where in it the file @@ -788,7 +786,7 @@ def _semantic_standalone_checks(path: Path, layouts: object) -> list[str]: def _event_schema_errors() -> list[str]: """install-events.schema.json is EVENT_KEYS written out, and a valid schema.""" - import generate_event_schema # noqa: PLC0415 + import generate_event_schema path = ROOT / "schemas" / generate_event_schema.OUTPUT.name label = path.relative_to(ROOT).as_posix() @@ -828,7 +826,7 @@ def _format_errors() -> list[str]: def _measurement_errors(root: Path | None = None) -> list[str]: """Every record line under measurements/, against its schema and the rules measurement_records.read_records applies.""" - import measurement_records as mr # noqa: PLC0415 + import measurement_records as mr root = root or ROOT validator = _validator("core-probe-record.schema.json") diff --git a/scripts/validate_site.py b/scripts/validate_site.py index 8826c971b..f8f5ab097 100644 --- a/scripts/validate_site.py +++ b/scripts/validate_site.py @@ -403,9 +403,9 @@ def _check_get_pages( recorded tag, and one without links none and gives the command. """ sys.path.insert(0, str(Path(__file__).resolve().parent)) - import release_record # noqa: PLC0415 - from siteguides import INSTALL_SH # noqa: PLC0415 - from common import list_registered_platforms, list_release_pack_platforms # noqa: PLC0415 + import release_record + from siteguides import INSTALL_SH + from common import list_registered_platforms, list_release_pack_platforms if not (platforms_dir / "_registry.yml").is_file(): return [f"no platform registry in {platforms_dir}"] @@ -499,7 +499,7 @@ def main() -> None: help="stop listing after this many errors (default: %(default)s)", ) args = parser.parse_args() - from common import require_directory # noqa: PLC0415 + from common import require_directory require_directory(str(args.platforms_dir), "--platforms-dir") diff --git a/scripts/validation.py b/scripts/validation.py index e0e3aa668..34920be01 100644 --- a/scripts/validation.py +++ b/scripts/validation.py @@ -23,7 +23,6 @@ from common import ( name_match_size_ok, sanitize_pack_path, shape_fits, - size_fits, ) from hashing import md5_composite, parse_hash_list, parse_md5_list from nativemode import SIZE_AND_ANY_HASH, digest_algorithm, hash_mismatch_excludes_file diff --git a/scripts/verify.py b/scripts/verify.py index 9cb11b855..2520e4f73 100644 --- a/scripts/verify.py +++ b/scripts/verify.py @@ -572,10 +572,10 @@ def find_undeclared_files( # (ARMSX2's arcade/proverb.zip once ROCKNIX binds bios/armsx2). agnostic = profile.get("bios_mode") == "agnostic" - for profile, is_standalone in platform_layouts(emu_name, profile, standalone_set): + for layout, is_standalone in platform_layouts(emu_name, profile, standalone_set): for f in expand_directory_entries( - profile.get("files", []), db, is_standalone + layout.get("files", []), db, is_standalone ): if agnostic and not f.get("unplaced"): continue @@ -613,7 +613,7 @@ def find_undeclared_files( # Below the save directory each core is handed a folder # of its own: two cores reading hiscore.dat there read # two files. - ("save", core_save_folder(profile)) if save_root + ("save", core_save_folder(layout)) if save_root else (f["root"],) if f.get("root") in OUTER_ROOTS # In the emulator's own folder: no other core reads it. else ("emulator", emu_name) if f.get("unplaced") else None, @@ -662,8 +662,8 @@ def find_undeclared_files( ) archive_entries[archive_key] = { "profile": emu_name, - "emulator": profile.get("emulator", emu_name), - "systems": entry_system_ids(f, profile), + "emulator": layout.get("emulator", emu_name), + "systems": entry_system_ids(f, layout), "system": f.get("system"), "region": f.get("region"), "selection_slot": f.get("selection_slot"), @@ -680,14 +680,14 @@ def find_undeclared_files( "expected": {}, "archive_file_count": 0, "archive_required_count": 0, - "members": archive_members(archive, profile.get("files", [])), + "members": archive_members(archive, layout.get("files", [])), } if f.get("system_dir"): archive_entries[archive_key]["system_dir"] = f["system_dir"] # The archive's own declaration names its sets: an # archive is a member like a loose file. - own = archive_entry(archive, profile.get("files", [])) - archive_entries[archive_key].update(set_fields(own, profile)) + own = archive_entry(archive, layout.get("files", [])) + archive_entries[archive_key].update(set_fields(own, layout)) set_records.append(( set_keys((emu_name, is_standalone), own), own, in_repo, (archive_entries[archive_key], None), @@ -761,15 +761,15 @@ def find_undeclared_files( # ROM is not Basilisk II's ROM. _lp, _st = resolve_local_file(owned, db, dest_hint=dest) if core_size_refusal( - f, _lp, same_slot_entries(profile.get("files"), fname, dest) + f, _lp, same_slot_entries(layout.get("files"), fname, dest) ): in_repo = False checks = _parse_validation(f.get("validation")) entry = { "profile": emu_name, - "emulator": profile.get("emulator", emu_name), - "systems": entry_system_ids(f, profile), + "emulator": layout.get("emulator", emu_name), + "systems": entry_system_ids(f, layout), "system": f.get("system"), "region": f.get("region"), "selection_slot": f.get("selection_slot"), @@ -782,7 +782,7 @@ def find_undeclared_files( "in_repo": in_repo, "note": f.get("note", ""), "checks": sorted(checks) if checks else [], - **set_fields(f, profile), + **set_fields(f, layout), "source_ref": f.get("source_ref"), "expected": _build_expected(f, checks), **_identity_of(f), @@ -793,12 +793,12 @@ def find_undeclared_files( entry["contents"] = f["contents"] if save_root: entry["root"] = "save" - folder = core_save_folder(profile) + folder = core_save_folder(layout) if folder is not None: entry["core_folder"] = folder elif f.get("system_dir"): entry["system_dir"] = f["system_dir"] - members = with_archive_members(f, profile.get("files", [])).get("members") + members = with_archive_members(f, layout.get("files", [])).get("members") if members: entry["members"] = members if f.get("layout_path"): diff --git a/scripts/ziptools.py b/scripts/ziptools.py index e8ad8bdfb..4fcf14e06 100644 --- a/scripts/ziptools.py +++ b/scripts/ziptools.py @@ -121,7 +121,7 @@ MAX_HASHED_MEMBER = 512 * 1024 * 1024 def _read_member_cache(path: str) -> dict[str, list[list]]: - import json # noqa: PLC0415 + import json try: with open(path, encoding="utf-8") as fh: @@ -135,7 +135,7 @@ def _read_member_cache(path: str) -> dict[str, list[list]]: def _write_member_cache(path: str, data: dict[str, list[list]]) -> None: - import json # noqa: PLC0415 + import json os.makedirs(os.path.dirname(path), exist_ok=True) fd, scratch = tempfile.mkstemp(dir=os.path.dirname(path), suffix=".tmp") diff --git a/tests/test_adler32_resolution.py b/tests/test_adler32_resolution.py index c90aba144..83483eb4c 100644 --- a/tests/test_adler32_resolution.py +++ b/tests/test_adler32_resolution.py @@ -119,7 +119,7 @@ class TheTwoRomsFormAPairTheCodeTakes(unittest.TestCase): class DolphinGetsAPairItTakes(unittest.TestCase): def test_each_dolphin_dsp_rom_resolves_to_an_accepted_dump(self): - from common import load_emulator_profiles # noqa: PLC0415 + from common import load_emulator_profiles database = REPO_ROOT / "database.json" if not database.exists(): @@ -139,7 +139,7 @@ class DolphinGetsAPairItTakes(unittest.TestCase): def test_every_paired_profile_resolves_a_pair_its_code_takes(self): - from common import load_emulator_profiles # noqa: PLC0415 + from common import load_emulator_profiles database = REPO_ROOT / "database.json" if not database.exists(): diff --git a/tests/test_archive_choice.py b/tests/test_archive_choice.py index 65cc92ddb..549cc5678 100644 --- a/tests/test_archive_choice.py +++ b/tests/test_archive_choice.py @@ -70,9 +70,9 @@ class OneWinnerRuleForEveryReader(unittest.TestCase): won in the report and lost in the pack. The rule takes no registry.""" def test_the_rule_reads_no_data_directory(self): - import inspect # noqa: PLC0415 + import inspect - import generate_pack # noqa: PLC0415 + import generate_pack parameters = inspect.signature(generate_pack._preferred_entries).parameters self.assertFalse([name for name in parameters if "registry" in name]) diff --git a/tests/test_archive_recipes.py b/tests/test_archive_recipes.py index f2f04f517..6d88d00ea 100644 --- a/tests/test_archive_recipes.py +++ b/tests/test_archive_recipes.py @@ -90,14 +90,14 @@ class HeldArchivesMatchTheirRecipes(unittest.TestCase): 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 ( # noqa: PLC0415 + from common import ( list_registered_platforms, load_emulator_profiles, load_platform_config, variant_base_name, ) - from hashing import md5_composite_of # noqa: PLC0415 - from romset_recipes import load_dat_recipes # noqa: PLC0415 + 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(): diff --git a/tests/test_artifact_lock.py b/tests/test_artifact_lock.py index bf32ab5a3..ba3e2d2a6 100644 --- a/tests/test_artifact_lock.py +++ b/tests/test_artifact_lock.py @@ -50,32 +50,27 @@ class ArtifactLockTest(unittest.TestCase): self.dir = _tempdir(self) def test_writer_excludes_writer(self): - with artifact_lock(self.dir): - with self.assertRaises(ArtifactLockBusy): - with artifact_lock(self.dir): - pass + with artifact_lock(self.dir), self.assertRaises(ArtifactLockBusy), artifact_lock(self.dir): + pass def test_writer_excludes_reader(self): - with artifact_lock(self.dir): - with self.assertRaises(ArtifactLockBusy): - with artifact_lock(self.dir, exclusive=False): - pass - - def test_readers_share(self): - with artifact_lock(self.dir, exclusive=False): + with artifact_lock(self.dir), self.assertRaises(ArtifactLockBusy): with artifact_lock(self.dir, exclusive=False): pass + def test_readers_share(self): + with artifact_lock(self.dir, exclusive=False), artifact_lock(self.dir, exclusive=False): + pass + def test_a_reader_never_creates_the_directory(self): """A mistyped --output-dir given to --verify-packs or release_record was created holding a .lock, and the next run with the same typo no longer said the path did not exist.""" - from common import ArtifactDirectoryMissing # noqa: PLC0415 + from common import ArtifactDirectoryMissing missing = os.path.join(self.dir, "sub", "dsit") - with self.assertRaises(ArtifactDirectoryMissing): - with artifact_lock(missing, exclusive=False): - pass + with self.assertRaises(ArtifactDirectoryMissing), artifact_lock(missing, exclusive=False): + pass self.assertFalse(os.path.exists(os.path.join(self.dir, "sub"))) def test_split_refuses_a_missing_target_before_locking(self): @@ -95,17 +90,15 @@ class ArtifactLockTest(unittest.TestCase): pass def test_lock_is_released_on_error(self): - with self.assertRaises(ValueError): - with artifact_lock(self.dir): - raise ValueError("boom") + with self.assertRaises(ValueError), artifact_lock(self.dir): + raise ValueError("boom") with artifact_lock(self.dir): pass def test_separate_directories_do_not_contend(self): other = _tempdir(self) - with artifact_lock(self.dir): - with artifact_lock(other): - pass + with artifact_lock(self.dir), artifact_lock(other): + pass def test_lock_survives_a_missing_directory(self): missing = os.path.join(self.dir, "not-created-yet") @@ -149,7 +142,7 @@ class PackLockCliTest(unittest.TestCase): """The refresh waits for every run holding a data tree, and a pipeline holds them all for its whole run: probed after the refresh, a second build sat silent for hours instead of being refused.""" - from refresh_data_dirs import cache_lock # noqa: PLC0415 + from refresh_data_dirs import cache_lock platforms = Path(self.dir) / "platforms" platforms.mkdir() @@ -254,9 +247,8 @@ class PipelineHoldsItsFixedOutputs(unittest.TestCase): def test_two_holds_of_the_repository_exclude_each_other(self): with hold_repository_outputs(str(REPO_ROOT)), \ - self.assertRaises(ArtifactLockBusy): - with hold_repository_outputs(str(REPO_ROOT)): - pass + self.assertRaises(ArtifactLockBusy), hold_repository_outputs(str(REPO_ROOT)): + pass class TheSuiteTakesTheRepositoryHoldInItsScratch(unittest.TestCase): diff --git a/tests/test_atomic_artifacts.py b/tests/test_atomic_artifacts.py index 51c652114..fa771b4a4 100644 --- a/tests/test_atomic_artifacts.py +++ b/tests/test_atomic_artifacts.py @@ -180,7 +180,7 @@ class ScratchFilesGetThePlainMode(unittest.TestCase): def test_threads_reading_the_mode_leave_the_umask_alone(self): """mame_devices fetches on eight threads and every cache write reads the umask: unguarded, two readers interleaved and left it at 0.""" - import threading # noqa: PLC0415 + import threading interval = sys.getswitchinterval() sys.setswitchinterval(1e-6) @@ -210,9 +210,9 @@ class ScratchFilesGetThePlainMode(unittest.TestCase): self.assertEqual(offenders, []) def test_packs_and_their_manifest(self): - import zipfile # noqa: PLC0415 + import zipfile - import generate_pack # noqa: PLC0415 + import generate_pack pack = self.dir / "Pack.zip" with generate_pack._writing_pack(str(pack)) as zf: @@ -230,7 +230,7 @@ class ScratchFilesGetThePlainMode(unittest.TestCase): copy_file_atomic is the one exception: copy2 gives the scratch the source file's own mode. """ - import ast # noqa: PLC0415 + import ast def name_of(node: ast.AST) -> str | None: return node.id if isinstance(node, ast.Name) else None @@ -317,8 +317,8 @@ class ATerminatedBuildLeavesNoScratch(unittest.TestCase): ) def test_sigterm_removes_the_partial_pack(self): - import signal # noqa: PLC0415 - import subprocess # noqa: PLC0415 + import signal + import subprocess if not hasattr(signal, "SIGTERM") or os.name != "posix": self.skipTest("POSIX signals") diff --git a/tests/test_audit_regressions.py b/tests/test_audit_regressions.py index 0f9ac840e..249175027 100644 --- a/tests/test_audit_regressions.py +++ b/tests/test_audit_regressions.py @@ -104,7 +104,7 @@ class ReadmeRegressions(unittest.TestCase): ) def test_an_older_interpreter_is_refused_before_the_first_step(self): - import shutil # noqa: PLC0415 + import shutil python38 = shutil.which("python3.8") if python38 is None: @@ -123,7 +123,7 @@ class ReadmeRegressions(unittest.TestCase): def test_the_readme_build_command_names_the_floor(self): """The README's first command is generate_pack.py. Under 3.8 it stopped on a raw SyntaxError at a parenthesized `with`.""" - import shutil # noqa: PLC0415 + import shutil python38 = shutil.which("python3.8") if python38 is None: @@ -142,7 +142,7 @@ class ReadmeRegressions(unittest.TestCase): """Only generate_pack.py and pipeline.py checked the version. verify.py, slots.py, validate_pr.py and cross_reference.py started under 3.8 and stopped halfway on a str.removeprefix AttributeError.""" - import shutil # noqa: PLC0415 + import shutil python38 = shutil.which("python3.8") if python38 is None: @@ -179,7 +179,7 @@ class ReadmeRegressions(unittest.TestCase): Compiling only checks the grammar: a module-level alias such as `tuple[int, int | None]` compiles under 3.9 and raises TypeError when the module loads.""" - import shutil # noqa: PLC0415 + import shutil floor = re.search( r"sys\.version_info < \((\d+), (\d+)\)", @@ -633,10 +633,9 @@ class APackIsSwappedInWhole(unittest.TestCase): pack = directory / "Pack.zip" with zipfile.ZipFile(pack, "w") as zf: zf.writestr("old.bin", b"complete") - with self.assertRaises(OSError): - with _writing_pack(str(pack)) as zf: - zf.writestr("new.bin", b"half") - raise OSError("disk full") + 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: self.assertEqual(zf.namelist(), ["old.bin"]) self.assertEqual(sorted(p.name for p in directory.iterdir()), ["Pack.zip"]) @@ -1004,8 +1003,8 @@ class FaqRegressions(unittest.TestCase): # and FinalBurn Neo 1.0.0.2, versions no source at the pins states, # and the test holding them to the profiles kept the errors in step. sys.path.insert(0, str(ROOT / "scripts")) - import generate_site # noqa: PLC0415 - from common import load_emulator_profiles # noqa: PLC0415 + import generate_site + from common import load_emulator_profiles profiles = load_emulator_profiles(str(ROOT / "emulators"), skip_aliases=False) page = (ROOT / "wiki" / "technical-faq.md").read_text(encoding="utf-8") @@ -1138,7 +1137,7 @@ class PipelineRegressions(unittest.TestCase): def test_integrity_checks_the_variants_step_4_built(self): """Step 6 ran --verify-packs without --all-variants: the five narrowed packs were never opened and an empty _Platform passed.""" - import argparse # noqa: PLC0415 + import argparse def command(**flags) -> list[str]: base = {"output_dir": "dist", "target": None, "all_variants": False} @@ -1331,7 +1330,7 @@ class SchemaFormatsAreChecked(unittest.TestCase): @unittest.skipUnless(HAS_JSONSCHEMA, "validating a schema needs jsonschema") def test_a_missing_checker_is_named(self): - import validate_schemas # noqa: PLC0415 + import validate_schemas empty = mock.Mock(checkers={}) with mock.patch.object(validate_schemas, "FormatChecker", return_value=empty): @@ -1878,7 +1877,7 @@ class RegionRegressions(unittest.TestCase): def test_region_audit_resolves_the_way_the_pack_does(self): """A private resolver read sha1, md5 and a lone name: an entry identified by its path (Dolphin's three IPL.bin) was never checked.""" - import hashlib # noqa: PLC0415 + import hashlib with tempfile.TemporaryDirectory(dir=TMP_ROOT) as directory: previous = os.getcwd() @@ -1893,7 +1892,7 @@ class RegionRegressions(unittest.TestCase): files[sha1] = {"path": rel, "name": "IPL.bin", "size": len(payload), "sha1": sha1, "md5": hashlib.md5(payload).hexdigest(), "sha256": hashlib.sha256(payload).hexdigest(), "crc32": "00000001"} - from scripts import generate_db # noqa: PLC0415 + from scripts import generate_db db = {"files": files, "indexes": generate_db.build_indexes(files, {})} by_md5 = {e["md5"]: s for s, e in files.items()} @@ -3128,7 +3127,7 @@ class TheProjectInstallsWithPip(unittest.TestCase): discovery found scripts/ and tests/ and refused to build.""" def test_setuptools_discovers_nothing_to_package(self): - import importlib.util # noqa: PLC0415 + import importlib.util if importlib.util.find_spec("setuptools") is None: # The dev extra and CI install it: skipped there, the guard held @@ -3147,7 +3146,7 @@ class TheProjectInstallsWithPip(unittest.TestCase): capture_output=True, text=True, check=False) self.assertEqual(done.returncode, 0, done.stderr[-2000:]) self.assertEqual(done.stdout.strip(), "[] []") - import tomllib # noqa: PLC0415 + import tomllib with (ROOT / "pyproject.toml").open("rb") as handle: build = tomllib.load(handle)["build-system"] @@ -3212,7 +3211,7 @@ class ACheckThatCannotAnswerDoesNotPass(unittest.TestCase): """Every HEAD unanswered printed "16 unknown" and exited 0, so the online pipeline printed check_buildbot OK.""" sys.path.insert(0, str(ROOT / "scripts")) - import check_buildbot_system as cbs # noqa: PLC0415 + import check_buildbot_system as cbs registry = str(ROOT / "platforms" / "_data_dirs.yml") tracked = cbs.load_tracked_entries(registry) @@ -3899,7 +3898,7 @@ class AnUnreadableArchiveIsSaidOutLoud(unittest.TestCase): truncated archive read as a missing dump (not_found) or a wrong one.""" def test_the_resolver_names_the_archive(self): - import common # noqa: PLC0415 + import common with tempfile.TemporaryDirectory(dir=ROOT / "tmp") as tmp: broken = Path(tmp) / "neogeo.zip" @@ -3922,7 +3921,7 @@ class GeneralUserGSReachesEveryCoreThatNamesIt(unittest.TestCase): shipped no General MIDI bank.""" def test_each_name_resolves_to_the_one_file(self): - import common # noqa: PLC0415 + import common if not (ROOT / "database.json").exists(): self.skipTest("database.json is not generated") @@ -3946,7 +3945,7 @@ class APlatformPinDoesNotReplaceTheCoresRevision(unittest.TestCase): files to cores built against newer ones.""" def test_the_profile_revision_serves_the_core(self): - import common # noqa: PLC0415 + import common if not (ROOT / "database.json").exists(): self.skipTest("database.json is not generated") @@ -3987,7 +3986,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): - import common # noqa: PLC0415 + import common with tempfile.TemporaryDirectory(dir=ROOT / "tmp") as tmp: cache = Path(tmp) / "cache" @@ -4022,7 +4021,7 @@ class ADuplicateYamlKeyIsRefused(unittest.TestCase): target_source keys for Recalbox and nothing noticed.""" def test_the_loader_names_the_repeated_key(self): - from safeparse import yaml_load # noqa: PLC0415 + from safeparse import yaml_load with self.assertRaises(yaml.constructor.ConstructorError) as caught: yaml_load("platform: x\ntarget_source: a\ntarget_source: b\n") @@ -4229,7 +4228,7 @@ class TriageSurvivesAForgeRefusal(unittest.TestCase): def check_version(profile, *_args): if "eden" in profile["source"]: raise profile_sync.upstream.UpstreamError("HTTP 403") - return None + return args = SimpleNamespace(cache_dir="", offline=True) out = io.StringIO() @@ -4289,7 +4288,7 @@ class OpenMsxRomsSitInItsSystemroms(unittest.TestCase): them there.""" def test_every_entry_is_under_share_systemroms(self): - from scripts.common import ( # noqa: PLC0415 + from scripts.common import ( load_emulator_profiles, load_platform_config, platform_layouts, @@ -4720,7 +4719,7 @@ class AReaderThatLeavesEarlyIsNoCrash(unittest.TestCase): # the close below never met the broken pipe and exited 0. A 4 KiB # pipe keeps it writing when the reader leaves. try: - import fcntl # noqa: PLC0415 + import fcntl fcntl.fcntl(proc.stdout.fileno(), fcntl.F_SETPIPE_SZ, 4096) except (ImportError, AttributeError, OSError): @@ -5670,7 +5669,7 @@ class AHeldRevisionLinksItsBuildFile(unittest.TestCase): f"RetroPie-Setup/blob/{pin}/scriptmodules/emulators/advmame-1.4.sh)", rows[0]) def test_the_record_holds_the_build_files(self): - import sitesources # noqa: PLC0415 + import sitesources files = sitesources.build_files({"pin_build": [ {"repo": "https://github.com/o/r", "revision": "a" * 40, "path": "p.mk"}, diff --git a/tests/test_autorun.py b/tests/test_autorun.py index 1600b99d1..2cdbd4d5a 100644 --- a/tests/test_autorun.py +++ b/tests/test_autorun.py @@ -959,7 +959,7 @@ class SubjectsFollowTheRepositoryRules(unittest.TestCase): calls: a copy in the hook alone let CI check only the shape.""" def test_the_runner_reads_the_tracked_rules(self): - import commit_rules # noqa: PLC0415 + import commit_rules for subject in ("chore: fix the broken manifests", "update things", "chore: " + "a" * 60): with self.subTest(subject=subject): @@ -970,7 +970,7 @@ class SubjectsFollowTheRepositoryRules(unittest.TestCase): def test_review_numbers_are_refused(self): """47 pushed subjects pointed at a numbered private review, which no clone can follow. The subject says what the change does.""" - import commit_rules # noqa: PLC0415 + import commit_rules for subject in ("chore: audit 24 and 17 cases, host kept out", "fix: polish the screens audit 11 named", diff --git a/tests/test_batocera_md5_list.py b/tests/test_batocera_md5_list.py index de98a6c71..e274b223a 100644 --- a/tests/test_batocera_md5_list.py +++ b/tests/test_batocera_md5_list.py @@ -391,7 +391,7 @@ class SeveralAcceptedMd5BecomeAList(unittest.TestCase): """Run the produced script: either listed md5 passes, another fails.""" produced, _, _, _ = self._export([dict(self.CORRECTED, md5=[C, SECOND])], LISTING) namespace: dict = {"__name__": "batocera_systems"} - exec(compile(produced, "batocera-systems", "exec"), namespace) # noqa: S102 + exec(compile(produced, "batocera-systems", "exec"), namespace) item = namespace["systems"]["psx"]["biosFiles"][0] self.assertEqual(item["md5"], [C, SECOND]) scratch = REPO_ROOT / "tmp" diff --git a/tests/test_cache_independent_counts.py b/tests/test_cache_independent_counts.py index 62def66ae..c3d7189f3 100644 --- a/tests/test_cache_independent_counts.py +++ b/tests/test_cache_independent_counts.py @@ -23,14 +23,14 @@ sys.path.insert(0, str(REPO_ROOT / "scripts")) class DeclaredFilesResolveWithoutDataCaches(unittest.TestCase): def test_no_platform_entry_rests_on_a_data_directory_cache(self): - from common import ( # noqa: PLC0415 + from common import ( build_zip_contents_index, list_registered_platforms, load_data_dir_registry, load_database, load_platform_config, ) - from packresolve import resolve_declaration # noqa: PLC0415 + from packresolve import resolve_declaration platforms_dir = REPO_ROOT / "platforms" registry = load_data_dir_registry(str(platforms_dir)) diff --git a/tests/test_casefold_cache.py b/tests/test_casefold_cache.py index 3e6d50631..95cc6f67b 100644 --- a/tests/test_casefold_cache.py +++ b/tests/test_casefold_cache.py @@ -34,8 +34,8 @@ class APrimaryUnderAnotherCasing(unittest.TestCase): platform pins, in the same directory.""" def setUp(self): - import shutil # noqa: PLC0415 - import tempfile # noqa: PLC0415 + import shutil + import tempfile self.root = Path(tempfile.mkdtemp(dir=REPO_ROOT / "tmp")) self.addCleanup(shutil.rmtree, self.root, True) @@ -43,7 +43,7 @@ class APrimaryUnderAnotherCasing(unittest.TestCase): self.by_name: dict = {} def _put(self, relative: str, data: bytes, indexed_as: str | None = None) -> None: - import hashlib # noqa: PLC0415 + import hashlib path = self.root / relative path.parent.mkdir(parents=True, exist_ok=True) @@ -56,7 +56,7 @@ class APrimaryUnderAnotherCasing(unittest.TestCase): self.by_name.setdefault(name, []).append(sha1) def _resolve(self, name: str) -> str: - from common import _casefold_index_cache, resolve_local_file # noqa: PLC0415 + from common import _casefold_index_cache, resolve_local_file _casefold_index_cache.clear() db = {"files": self.files, "indexes": {"by_name": self.by_name, "by_md5": {}, diff --git a/tests/test_check_freshness.py b/tests/test_check_freshness.py index 7cdd8dede..ae0deb730 100644 --- a/tests/test_check_freshness.py +++ b/tests/test_check_freshness.py @@ -324,7 +324,7 @@ class CoreResolutionTests(unittest.TestCase): def test_record_errors_are_one_line(self): """A mistyped core and an empty offline cache ended on a traceback.""" - import subprocess # noqa: PLC0415 + import subprocess with tempfile.TemporaryDirectory() as tmp: proc = subprocess.run( @@ -574,7 +574,7 @@ class ProfileSummaryTests(unittest.TestCase): def test_profile_sync_accepts_the_command_it_is_given(self): """--json with the detection flags was refused, so --profiles read an empty stdout and reported "unreadable report" on every run.""" - import profile_sync # noqa: PLC0415 + import profile_sync captured = [] @@ -653,8 +653,8 @@ class RepositoryWiringTests(unittest.TestCase): def test_a_target_of_every_declared_core_does_not_age(self): """RetroBat, RetroDECK and RomM name one target that runs every core they declare. With nothing hand-kept, there is no date to watch.""" - import tempfile # noqa: PLC0415 - from pathlib import Path as _Path # noqa: PLC0415 + import tempfile + from pathlib import Path as _Path with tempfile.TemporaryDirectory(dir=REPO_ROOT / "tmp") as tmp: targets = _Path(tmp) / "targets" @@ -668,8 +668,8 @@ class RepositoryWiringTests(unittest.TestCase): def test_a_scraped_target_offline_is_skipped_not_ok(self): """Offline, scraped target lists were labelled static and counted OK without any comparison, so a list 400 days old read as current.""" - import tempfile # noqa: PLC0415 - from pathlib import Path as _Path # noqa: PLC0415 + import tempfile + from pathlib import Path as _Path scraped = sorted(cf._target_scrapers()) self.assertTrue(scraped) @@ -702,7 +702,7 @@ class RepositoryWiringTests(unittest.TestCase): class RepeatedDestinations(unittest.TestCase): def test_a_change_to_an_earlier_declaration_is_seen(self): - from check_freshness import diff_platform # noqa: PLC0415 + from check_freshness import diff_platform def platform(first_md5: str) -> dict: return {"systems": {"pce": {"files": [ @@ -716,7 +716,7 @@ class RepeatedDestinations(unittest.TestCase): class PinsWithExtras(unittest.TestCase): def test_an_extras_bracket_keeps_its_pin(self): - from check_freshness import parse_pip_pins # noqa: PLC0415 + from check_freshness import parse_pip_pins pins = parse_pip_pins(' run: pip install pyyaml "jsonschema[format-nongpl]==4.26.0"') self.assertEqual(pins["jsonschema"], "==4.26.0") diff --git a/tests/test_check_release.py b/tests/test_check_release.py index 8555eaf39..700338e87 100644 --- a/tests/test_check_release.py +++ b/tests/test_check_release.py @@ -15,7 +15,7 @@ from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "scripts")) -import build_port # noqa: E402 +import build_port from check_release import SIGNATURE, SUMS, Asset, compare_release, parse_sums A = "a" * 64 diff --git a/tests/test_content_declarations.py b/tests/test_content_declarations.py index 21440435c..ae2401d96 100644 --- a/tests/test_content_declarations.py +++ b/tests/test_content_declarations.py @@ -16,8 +16,8 @@ import unittest sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "scripts")) -from common import platform_declared_contents # noqa: E402 -from validation import declaration_settles # noqa: E402 +from common import platform_declared_contents +from validation import declaration_settles SHA1 = "70cdf57469a208528f78a14275837352e90e20f1" DB = { diff --git a/tests/test_core_probe.py b/tests/test_core_probe.py index 1c866ffc7..de09f6af1 100644 --- a/tests/test_core_probe.py +++ b/tests/test_core_probe.py @@ -798,7 +798,7 @@ class TheInterpreterIsInTheSandbox(unittest.TestCase): crashed on the runner.""" def test_each_link_to_the_interpreter_is_bound(self): - from unittest import mock # noqa: PLC0415 + from unittest import mock with tempfile.TemporaryDirectory() as tmp: root = Path(tmp) @@ -826,7 +826,7 @@ class TheInterpreterIsInTheSandbox(unittest.TestCase): def test_a_link_in_a_shared_folder_binds_only_itself(self): """~/.local/bin/python3 must not expose ~/.local: only the link file and the proven Python prefix behind it are bound.""" - from unittest import mock # noqa: PLC0415 + from unittest import mock with tempfile.TemporaryDirectory() as tmp: root = Path(tmp) diff --git a/tests/test_crypto_unique_data.py b/tests/test_crypto_unique_data.py index a7428f68f..2124e00a2 100644 --- a/tests/test_crypto_unique_data.py +++ b/tests/test_crypto_unique_data.py @@ -62,7 +62,7 @@ def _ecdsa_sign(message: bytes) -> bytes: 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 256 > ec._N_BITLEN: + if ec._N_BITLEN < 256: digest >>= 256 - ec._N_BITLEN s = (ec._modinv(_ECC_NONCE, ec._N) * (digest + r * _ECC_PRIVATE)) % ec._N return r.to_bytes(30, "big") + s.to_bytes(30, "big") diff --git a/tests/test_crypto_verify.py b/tests/test_crypto_verify.py index a6f160bdd..a52dd03b6 100644 --- a/tests/test_crypto_verify.py +++ b/tests/test_crypto_verify.py @@ -118,7 +118,7 @@ def _sign(message: bytes, private: int, nonce: int) -> bytes: point = ec._ec_mul(nonce, g) r = point[0] % ec._N digest = int.from_bytes(hashlib.sha256(message).digest(), "big") - if 256 > ec._N_BITLEN: + if ec._N_BITLEN < 256: digest >>= 256 - ec._N_BITLEN s = (ec._modinv(nonce, ec._N) * (digest + r * private)) % ec._N return r.to_bytes(30, "big") + s.to_bytes(30, "big") diff --git a/tests/test_declared_names.py b/tests/test_declared_names.py index 630c60aa3..76ff4c236 100644 --- a/tests/test_declared_names.py +++ b/tests/test_declared_names.py @@ -30,7 +30,7 @@ class FlatDeclaredSet(unittest.TestCase): another that no alias joins: per system the ids never meet. nintendo-sgb and nintendo-super-game-boy were such a pair until SYSTEM_ALIASES joined them.""" - import tempfile # noqa: PLC0415 + import tempfile with tempfile.TemporaryDirectory(dir=REPO_ROOT / "tmp") as tmp: platforms = Path(tmp) diff --git a/tests/test_dedup.py b/tests/test_dedup.py index 0b6d31790..81e1f2d1e 100644 --- a/tests/test_dedup.py +++ b/tests/test_dedup.py @@ -302,7 +302,7 @@ class TheNoDedupListIsPinned(unittest.TestCase): three machines again, with the suite green.""" def test_every_tree_read_by_path_stays_undeduplicated(self): - from scripts.dedup import NODEDUP_DIRS # noqa: PLC0415 + from scripts.dedup import NODEDUP_DIRS expected = { "RPG Maker", "ScummVM", "tzdata", "c64-emu", "PinMAME", "BBK", @@ -350,7 +350,7 @@ class CloneChainsCollapse(unittest.TestCase): pointed at a file that no longer existed.""" def test_clones_follow_to_the_canonical_that_exists(self): - import dedup # noqa: PLC0415 + import dedup chain = { "cpu20.zip": {"clones": ["cpu21.zip"], "sha1": "a", "total_copies": 1}, @@ -362,7 +362,7 @@ class CloneChainsCollapse(unittest.TestCase): }) def test_a_loop_is_refused(self): - import dedup # noqa: PLC0415 + import dedup loop = {"a.zip": {"clones": ["b.zip"]}, "b.zip": {"clones": ["a.zip"]}} with self.assertRaises(ValueError): @@ -370,4 +370,4 @@ class CloneChainsCollapse(unittest.TestCase): if __name__ == "__main__": - unittest.main() \ No newline at end of file + unittest.main() diff --git a/tests/test_directory_entries.py b/tests/test_directory_entries.py index 3bd952006..93b737253 100644 --- a/tests/test_directory_entries.py +++ b/tests/test_directory_entries.py @@ -236,7 +236,7 @@ class PackCarriesADirectory(DirectoryFixture): self.assertEqual( archive.read("rtp/2000/Backdrop/a.png"), b"backdrop" ) - self.assertTrue(self.EXPECTED <= names, sorted(names)) + self.assertTrue(names >= self.EXPECTED, sorted(names)) self.assertFalse([n for n in names if ".variants" in n]) def test_the_install_manifest_lists_the_tree(self): @@ -248,7 +248,7 @@ class PackCarriesADirectory(DirectoryFixture): offline=True, ) dests = {entry["dest"] for entry in manifest["files"]} - self.assertTrue(self.EXPECTED <= dests, sorted(dests)) + self.assertTrue(dests >= self.EXPECTED, sorted(dests)) json.dumps(manifest) def test_the_gap_report_is_computed_once_per_build(self): @@ -291,7 +291,7 @@ class PackCarriesADirectory(DirectoryFixture): ) with zipfile.ZipFile(zip_path) as archive: names = set(archive.namelist()) - self.assertTrue(self.EXPECTED <= names, sorted(names)) + self.assertTrue(names >= self.EXPECTED, sorted(names)) def test_verify_counts_what_the_emulator_pack_ships(self): self._profiles() diff --git a/tests/test_doc_pages.py b/tests/test_doc_pages.py index cacea5f66..dea19f7cb 100644 --- a/tests/test_doc_pages.py +++ b/tests/test_doc_pages.py @@ -1318,7 +1318,7 @@ class CitedOptionsExist(unittest.TestCase): def help_text(cls, target: str, module: bool, sub: str = "") -> str: key = (target, sub) if key not in cls._helps: - import subprocess # noqa: PLC0415 + import subprocess argv = [sys.executable, *(["-m", target] if module else [target])] proc = subprocess.run( @@ -1376,7 +1376,7 @@ class PipelineStepsMatchTheRun(unittest.TestCase): @staticmethod def labels() -> list[str]: - import pipeline # noqa: PLC0415 + import pipeline return [pipeline.step_number(key) for key in pipeline.STEP_LABELS] @@ -1739,7 +1739,7 @@ class ArchitectureStatesTheArbitration(unittest.TestCase): checks the content: RetroBat's ATARIOSB.ROM.""" def test_the_page_says_what_arbitrate_decides(self): - import slots # noqa: PLC0415 + import slots page = (WIKI / "architecture.md").read_text(encoding="utf-8") self.assertNotIn("the profile takes precedence for pack generation", page) @@ -1795,9 +1795,9 @@ class ReportExcerptIsTheRun(unittest.TestCase): naming one, and never showed the line that names it.""" def test_every_quoted_line_is_printed(self): - import subprocess # noqa: PLC0415 + import subprocess - from restore_large_files import gitignored_paths # noqa: PLC0415 + from restore_large_files import gitignored_paths # The excerpt is a run over the whole collection. A checkout without # the release assets (the PR workflow restores none) prints other @@ -1915,7 +1915,7 @@ class TheInstallerSamplesTravelWithTheManifests(unittest.TestCase): place for the samples the gate's pipeline rewrites.""" def test_the_pages_and_the_nightly_carry_them(self): - import autorun # noqa: PLC0415 + import autorun guide = (WIKI / "testing-guide.md").read_text(encoding="utf-8") for name in ("wiki/installer.md", "derivable.json", "generate_installer_doc.py"): @@ -1940,7 +1940,7 @@ class TheRemovalProofsAreTheExportersOwn(unittest.TestCase): "data_directory": "a data directory"} def test_the_page_names_each_proof_in_order(self): - from exporter.candidates import _PROOF_ORDER # noqa: PLC0415 + from exporter.candidates import _PROOF_ORDER page = (WIKI / "tools.md").read_text(encoding="utf-8") start = page.index("No entry the platform declares is removed.") @@ -1969,10 +1969,10 @@ class NoTextClaimsAScheduledScrape(unittest.TestCase): `schedule:`.""" def test_no_text_ties_the_registry_to_automation(self): - import generate_pack # noqa: PLC0415 - import generate_readme # noqa: PLC0415 - import generate_site # noqa: PLC0415 - import list_platforms # noqa: PLC0415 + import generate_pack + import generate_readme + import generate_site + import list_platforms texts = { "adding-a-platform.md": (WIKI / "adding-a-platform.md").read_text(encoding="utf-8"), diff --git a/tests/test_doc_surfaces.py b/tests/test_doc_surfaces.py index 4cc026e7e..90ef35ad8 100644 --- a/tests/test_doc_surfaces.py +++ b/tests/test_doc_surfaces.py @@ -85,9 +85,9 @@ class TheDownloadTablesFollowTheRegistry(unittest.TestCase): now: the row of each platform names every system it is detected on.""" def test_every_detected_system_lists_the_platform(self): - import yaml # noqa: PLC0415 + import yaml - from common import load_platform_config # noqa: PLC0415 + from common import load_platform_config registry = yaml.safe_load(_read("platforms/_registry.yml")) page = _which_pack() @@ -431,7 +431,7 @@ class PagesOpenOnTheirContent(unittest.TestCase): before saying anything about a pack.""" def test_no_paragraph_announces_its_page(self): - import generate_site # noqa: PLC0415 + import generate_site text = generate_site.generate_which_pack() announcing = [ @@ -648,7 +648,7 @@ class ArchiveRecipesAreCountedFromTheRecipes(unittest.TestCase): that file, never typed.""" def setUp(self) -> None: - import archive_build # noqa: PLC0415 + import archive_build records = archive_build.load_ledger().values() self.counts = { @@ -660,7 +660,7 @@ class ArchiveRecipesAreCountedFromTheRecipes(unittest.TestCase): self.assertEqual(self.counts["exact"] + self.counts["canonical"], self.counts["total"]) def test_the_readme_line(self) -> None: - from generate_readme import archive_line # noqa: PLC0415 + from generate_readme import archive_line line = archive_line(self.counts) self.assertIn(line, _read("README.md").splitlines()) @@ -670,7 +670,7 @@ class ArchiveRecipesAreCountedFromTheRecipes(unittest.TestCase): self.assertIn(f"({SITE_URL}wiki/archive-recipes/)", line) def test_the_page_counts(self) -> None: - import generate_site # noqa: PLC0415 + import generate_site page = _read("wiki/archive-recipes.md") self.assertEqual(generate_site.with_archive_counts(page, self.counts), page, diff --git a/tests/test_download.py b/tests/test_download.py index 8923a2134..98b06a1e2 100644 --- a/tests/test_download.py +++ b/tests/test_download.py @@ -102,9 +102,8 @@ class TestPackGrouping(unittest.TestCase): def test_info_on_an_unknown_platform_fails(self): """--info printed "not found" and exited 0.""" release = _release(["EmuDeck_2.3.8_BIOS_Pack.zip"]) - with contextlib.redirect_stdout(io.StringIO()) as out: - with self.assertRaises(SystemExit) as caught: - download.show_info("emudek", release) + with contextlib.redirect_stdout(io.StringIO()) as out, self.assertRaises(SystemExit) as caught: + download.show_info("emudek", release) self.assertEqual(caught.exception.code, 1) self.assertIn("EmuDeck", out.getvalue()) diff --git a/tests/test_e2e.py b/tests/test_e2e.py index 9c8379233..065642dcb 100644 --- a/tests/test_e2e.py +++ b/tests/test_e2e.py @@ -6504,9 +6504,9 @@ struct BurnDriver BurnDrvneogeo = { gap report (system, systems) to platform_region_groups, not a dictionary built by hand. Without it every extra stood alone and --region compared nothing.""" - import hashlib # noqa: PLC0415 + import hashlib - from packextras import platform_region_groups # noqa: PLC0415 + from packextras import platform_region_groups files, by_name = {}, {} for name in ("core_us.bin", "core_jp.bin"): @@ -6542,9 +6542,9 @@ struct BurnDriver BurnDrvneogeo = { """RetroDECK files the Master System as sega-master-system, the profiles as sega-mastersystem. Two groups reduced apart, and a --region us pack kept the declared Japanese BIOS.""" - import hashlib # noqa: PLC0415 + import hashlib - from packextras import platform_region_groups # noqa: PLC0415 + from packextras import platform_region_groups files, by_name = {}, {} for name in ("bios_U.sms", "bios_J.sms"): diff --git a/tests/test_emuelec_targets.py b/tests/test_emuelec_targets.py index 77e8b2ec1..2a7fc147b 100644 --- a/tests/test_emuelec_targets.py +++ b/tests/test_emuelec_targets.py @@ -250,7 +250,7 @@ class TheFrontendOffersWhatTheDeviceKeeps(unittest.TestCase): class TheCommittedListFollowsTheRules(unittest.TestCase): def test_the_handhelds_list_no_core_they_do_not_build(self): - import yaml # noqa: PLC0415 + import yaml targets = yaml.safe_load((REPO_ROOT / "platforms" / "targets" / "emuelec.yml") .read_text(encoding="utf-8"))["targets"] diff --git a/tests/test_emulator_pack_counts.py b/tests/test_emulator_pack_counts.py index 654ff5c20..bf05abee1 100644 --- a/tests/test_emulator_pack_counts.py +++ b/tests/test_emulator_pack_counts.py @@ -81,9 +81,9 @@ class APlaceholderIsAnsweredByEvidence(unittest.TestCase): import yaml sys.path.insert(0, str(REPO_ROOT / "scripts")) - from common import _emulator_profiles_cache # noqa: PLC0415 - from generate_pack import generate_emulator_pack # noqa: PLC0415 - from verify import verify_emulator # noqa: PLC0415 + from common import _emulator_profiles_cache + from generate_pack import generate_emulator_pack + from verify import verify_emulator _emulator_profiles_cache.clear() (REPO_ROOT / "tmp").mkdir(exist_ok=True) diff --git a/tests/test_entry_categories.py b/tests/test_entry_categories.py index 6da8ef2b7..38e782ddb 100644 --- a/tests/test_entry_categories.py +++ b/tests/test_entry_categories.py @@ -14,8 +14,8 @@ from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "scripts")) -import verify # noqa: E402 -from exporter.candidates import ( # noqa: E402 +import verify +from exporter.candidates import ( BIOS, GAME_DATA, UNREAD, diff --git a/tests/test_export_counts.py b/tests/test_export_counts.py index 75a6e8907..3f78e2e68 100644 --- a/tests/test_export_counts.py +++ b/tests/test_export_counts.py @@ -63,7 +63,7 @@ class RetroDeckWritesWhatItCounts(unittest.TestCase): def test_an_appended_revision_is_not_counted_corrected(self): # 64DD_IPL.bin declared twice (A, B), truth C: the render keeps both # and appends C, and the summary said "1 hashes corrected". - from export_native import landed_changes # noqa: PLC0415 + from export_native import landed_changes appended: set = set() merged = RetroDeck._merge( @@ -212,7 +212,7 @@ class RetroBatCountsOneAdditionPerPath(unittest.TestCase): added: 78 additions announced for 75 items written.""" def test_an_addition_at_a_held_path_does_not_land(self): - from export_native import landed_changes # noqa: PLC0415 + from export_native import landed_changes theirs = NativeFile("scph1001.bin", "scph1001.bin", "psx", platform={"md5": A}, truth={"md5": A}) @@ -399,7 +399,7 @@ class MisterCountsWhatItWrites(unittest.TestCase): # The truth took the entry on a size contradiction and has no md5: # the render kept MiSTer's hash, wrote the new size, and the summary # announced the hash cleared. - from export_native import landed_changes # noqa: PLC0415 + from export_native import landed_changes fe = NativeFile("boot.rom", "NES/boot.rom", "nes", platform={"md5": A, "size": 100}, @@ -417,7 +417,7 @@ class MisterCountsWhatItWrites(unittest.TestCase): class OneMd5FormatsAddWhole(unittest.TestCase): def test_an_addition_with_several_md5_is_refused(self): - from exporter.batocera_exporter import Exporter as Batocera # noqa: PLC0415 + from exporter.batocera_exporter import Exporter as Batocera several = NativeFile("boot.bin", "boot.bin", "dc", truth={"md5": [A, B, C]}, runners=[(False, "flycast")]) @@ -430,7 +430,7 @@ class OneMd5FormatsAddWhole(unittest.TestCase): def test_retrobat_refuses_it_too(self): # RetroBat's batocera-systems.json holds one md5 per entry: the # addition was written with the first and counted added. - from exporter.retrobat_exporter import Exporter as RetroBat # noqa: PLC0415 + from exporter.retrobat_exporter import Exporter as RetroBat several = NativeFile("boot.bin", "boot.bin", "dc", truth={"md5": [A, B, C]}) single = NativeFile("boot2.bin", "boot2.bin", "dc", truth={"md5": A}) @@ -454,7 +454,7 @@ class BizHawkKeepsItsOwnHashes(unittest.TestCase): class SystemDatKeepsItsQuoting(unittest.TestCase): def test_a_name_the_original_quotes_stays_quoted(self): - from exporter.systemdat_exporter import _quote # noqa: PLC0415 + from exporter.systemdat_exporter import _quote quoted = frozenset({"dolphin-emu/Sys/GC/USA/IPL.bin"}) self.assertEqual(_quote("dolphin-emu/Sys/GC/USA/IPL.bin", quoted), @@ -547,7 +547,7 @@ class RommKeepsItsOwnKeys(unittest.TestCase): """known_bios_files.json writes PLUTONIA.WAD's sha1 with a leading space, which RomM compares as stored and never matches. The export wrote it stripped and the summary named no change for it.""" - from export_native import landed_changes # noqa: PLC0415 + from export_native import landed_changes sha1 = "8" * 40 fe = NativeFile("PLUTONIA.WAD", "doom/PLUTONIA.WAD", "doom", @@ -563,7 +563,7 @@ class RommKeepsItsOwnKeys(unittest.TestCase): def test_the_shared_helper_reads_every_exporter_the_same_way(self): """RomM's writable is per instance, but the base helper bound fe as self.""" - from exporter import discover_exporters # noqa: PLC0415 + from exporter import discover_exporters theirs = NativeFile("boot.bin", "dc/boot.bin", "dc", platform={"size": 2097152, "md5": A, "core": "libretro/flycast"}) @@ -609,7 +609,7 @@ class RommWritesOneEntryPerKey(unittest.TestCase): first in RomM's dict and both were counted landed.""" def test_the_second_addition_under_a_key_is_not_writable(self): - from exporter.romm_exporter import Exporter as Romm # noqa: PLC0415 + from exporter.romm_exporter import Exporter as Romm first = NativeFile("basic.rom", "Acorn/basic.rom", "acpc", truth={"size": 16384, "md5": A}) @@ -839,7 +839,7 @@ class RetroDeckCorrectsOnlyWhatItCarries(unittest.TestCase): def test_paths_and_description_stay_the_maintainers(self): """neogeo.zip lost its four search directories to a path that does not exist, and 26 descriptions were rewritten.""" - from collections import OrderedDict # noqa: PLC0415 + from collections import OrderedDict existing = [{"filename": "neogeo.zip", "system": "neogeo", "md5": A, "paths": ["$roms_path/neogeo", "$roms_path/fbneo", "$bios_path"], @@ -854,7 +854,7 @@ class RetroDeckCorrectsOnlyWhatItCarries(unittest.TestCase): def test_a_hash_no_revision_shares_is_appended(self): """IPL.n64 declared twice, both contradicted: counted corrected, written nowhere.""" - from collections import OrderedDict # noqa: PLC0415 + from collections import OrderedDict existing = [{"filename": "IPL.n64", "system": "n64dd", "md5": A}, {"filename": "IPL.n64", "system": "n64dd", "md5": B}] @@ -868,7 +868,7 @@ class BatoceraKeepsTheRunnerKeys(unittest.TestCase): """checkBios skips a BIOS whose emulator or core is not installed. Rewritten without the keys, vectrex's MAME BIOS was wanted by every build.""" - from exporter.batocera_exporter import Exporter as Batocera # noqa: PLC0415 + from exporter.batocera_exporter import Exporter as Batocera fe = NativeFile("bios.bin", "bios.bin", "vectrex", platform={"md5": A}, truth={"md5": B}, corrections=["md5"]) @@ -901,7 +901,7 @@ class SummaryCountsWhatTheTruthRewrites(unittest.TestCase): ) def test_a_format_with_the_fields_counts_them(self): - from export_native import landed_changes # noqa: PLC0415 + from export_native import landed_changes entry = self._entry() changes = landed_changes(SystemDat(), {"neocd": NativeSystem("neocd", files=[entry])}) @@ -910,8 +910,8 @@ class SummaryCountsWhatTheTruthRewrites(unittest.TestCase): self.assertEqual(changes.applied, ["neocd/neocdz.zip sha1"]) def test_a_format_without_them_does_not(self): - from export_native import landed_changes # noqa: PLC0415 - from exporter.batocera_exporter import Exporter as Batocera # noqa: PLC0415 + from export_native import landed_changes + from exporter.batocera_exporter import Exporter as Batocera entry = self._entry() changes = landed_changes(Batocera(), {"neocd": NativeSystem("neocd", files=[entry])}) @@ -929,7 +929,7 @@ class AStaleTruthIsRefused(unittest.TestCase): import shutil import tempfile - import export_native # noqa: PLC0415 + import export_native root = Path(__file__).resolve().parents[1] truth_dir = Path(tempfile.mkdtemp(dir=root / "tmp")) @@ -954,7 +954,7 @@ class ACorruptOriginalIsRefused(unittest.TestCase): self.assertIn("does not parse", str(caught.exception)) def test_retrobat_refuses_it(self): - from exporter.retrobat_exporter import Exporter as RetroBat # noqa: PLC0415 + from exporter.retrobat_exporter import Exporter as RetroBat fe = NativeFile("bios.bin", "bios.bin", "nes", platform={"md5": A}) exporter = RetroBat() @@ -978,8 +978,8 @@ class TheSummaryCountsWhatTheFileCarries(unittest.TestCase): ) def test_romm_drops_the_hashes_it_counts_cleared(self): - from export_native import landed_changes # noqa: PLC0415 - from exporter.baseline import Report # noqa: PLC0415 + from export_native import landed_changes + from exporter.baseline import Report fe = self._contradicted() systems = {"psx": NativeSystem("psx", files=[fe])} @@ -996,7 +996,7 @@ class TheSummaryCountsWhatTheFileCarries(unittest.TestCase): self.assertEqual(sorted(cleared), ["psx/scph5501.bin crc32", "psx/scph5501.bin sha1"]) def test_a_fill_no_record_holds_is_not_counted(self): - from export_native import landed_changes # noqa: PLC0415 + from export_native import landed_changes fe = NativeFile( "scph5501.bin", "scph5501.bin", "psx", @@ -1018,7 +1018,7 @@ class TheSummaryCountsWhatTheFileCarries(unittest.TestCase): self.assertNotIn("md5", merged[0]) def test_recalbox_counts_nothing_on_an_element_it_keeps(self): - from export_native import landed_changes # noqa: PLC0415 + from export_native import landed_changes fe = NativeFile( "scph5501.bin", "scph5501.bin", "psx", @@ -1035,7 +1035,7 @@ class BatoceraEntriesParseAsWritten(unittest.TestCase): gate and runner keys lost. The text was also run through exec.""" def test_a_trailing_comment_and_no_execution(self): - from exporter.batocera_exporter import Exporter as Batocera # noqa: PLC0415 + from exporter.batocera_exporter import Exporter as Batocera entry = Batocera._parse_entry([ '"gba": { "name": "GBA", "emulator": "libretro", "biosFiles": [', @@ -1069,7 +1069,7 @@ class AnExtendedListIsReported(unittest.TestCase): nothing. Only Batocera named the list it writes.""" def _records(self, exporter): - from export_native import landed_changes # noqa: PLC0415 + from export_native import landed_changes platform = {"name": "f.bin", "md5": A, "core": "libretro/mesen"} fe = NativeFile("f.bin", "f.bin", "s", platform=platform, @@ -1087,7 +1087,7 @@ class AnExtendedListIsReported(unittest.TestCase): ) def test_an_unchanged_value_reports_nothing(self): - from export_native import landed_changes # noqa: PLC0415 + from export_native import landed_changes for exporter in (RetroDeck(), Recalbox()): fe = NativeFile("f.bin", "f.bin", "s", diff --git a/tests/test_export_native_layer.py b/tests/test_export_native_layer.py index 7c9446218..902ea5d78 100644 --- a/tests/test_export_native_layer.py +++ b/tests/test_export_native_layer.py @@ -75,8 +75,8 @@ class TheTruthDiffReadsTheSameLayer(unittest.TestCase): """ def test_a_curated_file_is_missing_from_the_platform(self): - import json # noqa: PLC0415 - import subprocess # noqa: PLC0415 + import json + import subprocess with tempfile.TemporaryDirectory(dir=str(REPO_ROOT / "tmp")) as tmp: root = Path(tmp) @@ -110,7 +110,7 @@ class TheTruthDiffReadsTheSameLayer(unittest.TestCase): def test_every_truth_diff_caller_reads_the_native_layer(self): """The site's platform-vs-source table answers the same question.""" - import re # noqa: PLC0415 + import re for path in sorted((REPO_ROOT / "scripts").glob("*.py")): text = path.read_text(encoding="utf-8") diff --git a/tests/test_export_report.py b/tests/test_export_report.py index da01affd0..776410ee8 100644 --- a/tests/test_export_report.py +++ b/tests/test_export_report.py @@ -17,8 +17,8 @@ from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "scripts")) -import export_native # noqa: E402 -from siteexports import generate_exports_page, load_export_reports # noqa: E402 +import export_native +from siteexports import generate_exports_page, load_export_reports ROOT = Path(__file__).resolve().parent.parent @@ -179,10 +179,10 @@ class TheRunReportStatesWhatTheFileCarries(unittest.TestCase): JUDGING = ("their", "corrected", "wrong", "drift", "left out", "never seen") def test_summary_and_messages(self): - import json # noqa: PLC0415 - from unittest import mock # noqa: PLC0415 + import json + from unittest import mock - from exporter.base_exporter import BaseExporter # noqa: PLC0415 + from exporter.base_exporter import BaseExporter class Plain(BaseExporter): @staticmethod @@ -252,7 +252,7 @@ class TheRunReportStatesWhatTheFileCarries(unittest.TestCase): self.assertNotIn(word, name) def test_the_committed_reports_use_the_same_names(self): - import json # noqa: PLC0415 + import json for path in sorted((ROOT / "exports").glob("*.json")): report = json.loads(path.read_text(encoding="utf-8")) @@ -587,7 +587,7 @@ class ADestinationDeclaredTwiceIsNamed(unittest.TestCase): COCO = b"\x02" * 8194 def setUp(self): - import hashlib # noqa: PLC0415 + import hashlib self._tmp = tempfile.TemporaryDirectory(dir=ROOT / "tmp") root = Path(self._tmp.name) @@ -634,7 +634,7 @@ class ADestinationDeclaredTwiceIsNamed(unittest.TestCase): self._tmp.cleanup() def _doubled(self) -> list[dict]: - from exporter.doubled import doubled_destinations # noqa: PLC0415 + from exporter.doubled import doubled_destinations return doubled_destinations(self.scraped, self.profiles, self.db) @@ -656,7 +656,7 @@ class ADestinationDeclaredTwiceIsNamed(unittest.TestCase): self.assertEqual(coco["readers"], []) def test_the_platform_entries_are_left_as_written(self): - import copy # noqa: PLC0415 + import copy before = copy.deepcopy(self.scraped) self._doubled() diff --git a/tests/test_exporters.py b/tests/test_exporters.py index 985b0c1d6..ae1c6589b 100644 --- a/tests/test_exporters.py +++ b/tests/test_exporters.py @@ -61,7 +61,7 @@ UPSTREAM_CACHE = REPO_ROOT / ".cache" / "upstream-native" def _without_native_list() -> set[str]: """Registered platforms whose code names no BIOS file to hand back.""" - import yaml # noqa: PLC0415 + import yaml registry = yaml.safe_load((REPO_ROOT / "platforms" / "_registry.yml").read_text()) return { @@ -341,9 +341,9 @@ class Reconciliation(unittest.TestCase): """armsx2 and yaps2 declare different revisions of GameIndex.yaml. The truth kept armsx2's, and the export wrote it over System.dat's line for LRPS2 as a hash and size correction.""" - import contextlib # noqa: PLC0415 + import contextlib - import truth as truth_module # noqa: PLC0415 + import truth as truth_module entry = {"name": "GameIndex.yaml", "sha1": "1" * 40, "size": 2690355} with contextlib.redirect_stderr(io.StringIO()): @@ -685,7 +685,7 @@ class ExporterRegistry(unittest.TestCase): self.assertTrue(exporter.needs_original()) def test_an_export_without_its_original_writes_nothing(self): - import export_native # noqa: PLC0415 + import export_native with tempfile.TemporaryDirectory(dir=REPO_ROOT / "tmp") as tmp: output = Path(tmp) / "out" @@ -749,7 +749,7 @@ class SearchOrder(unittest.TestCase): """PicoDrive loads the first file of each region's list. RetroPie names one per region, but the export appended three more, which the sentence reads as three more required files.""" - from exporter.baseline import NativeSystem # noqa: PLC0415 + from exporter.baseline import NativeSystem def cd(name, region, rank): return NativeFile(name=name, destination=name, native_system="segacd", truth={ @@ -782,7 +782,7 @@ class SearchOrder(unittest.TestCase): """flycast's help names the Dreamcast BIOS, then the Naomi/Atomiswave ones. naomi2.zip, an arcade archive, went into the Dreamcast list: only the first BIOS clause was read.""" - from exporter.baseline import NativeSystem # noqa: PLC0415 + from exporter.baseline import NativeSystem def entry(name, system): return NativeFile(name=name, destination=f"dc/{name}", native_system=system, @@ -1004,7 +1004,7 @@ class PinnedRevision(unittest.TestCase): """Checked on five platforms by their base only: ROCKNIX's second file, RetroDECK's manifests and RetroPie's tarball were never looked at, and a URL that fell back to a branch passed.""" - import export_native # noqa: PLC0415 + import export_native for name, exporter_class in discover_exporters().items(): with self.subTest(platform=name): @@ -1015,7 +1015,7 @@ class PinnedRevision(unittest.TestCase): self.assertEqual(export_native.unpinned(wanted, config), []) def test_a_file_read_off_the_pinned_revision_is_named(self): - import export_native # noqa: PLC0415 + import export_native pinned = {"source": "https://raw.githubusercontent.com/o/r/v1.0/list.txt"} self.assertEqual(export_native.unpinned( @@ -1152,10 +1152,10 @@ class CachedOriginal(unittest.TestCase): def test_the_bytes_are_written_under_the_index_lock(self): """Written under two locks, two runs wanting two URLs for one path could leave one's bytes beside the other's index entry.""" - import fcntl # noqa: PLC0415 - from unittest import mock # noqa: PLC0415 + import fcntl + from unittest import mock - import export_native # noqa: PLC0415 + import export_native url = self._upstream("v1.txt", "one") target = self.cache / "plat" / "list.txt" @@ -1209,10 +1209,10 @@ class CachedOriginal(unittest.TestCase): self.assertEqual((self.cache / "plat" / "db.zip").read_bytes(), cached) def test_an_incomplete_read_is_reported(self): - import http.client # noqa: PLC0415 - from unittest import mock # noqa: PLC0415 + import http.client + from unittest import mock - import export_native # noqa: PLC0415 + import export_native def cut(*_args, **_kwargs): raise http.client.IncompleteRead(b"par") @@ -1273,7 +1273,7 @@ class RecalboxExport(unittest.TestCase): def test_an_addition_goes_where_the_core_reads_it(self): """DuckStation reads scph5000.bin at the BIOS root, but the export wrote psx/scph5000.bin, a path no core opens.""" - import copy # noqa: PLC0415 + import copy truth = copy.deepcopy(TRUTH) truth["systems"]["sony-playstation"]["files"].append({ @@ -1548,7 +1548,7 @@ class AnExportLeavesNoStaleFile(unittest.TestCase): holding the six files of the first run.""" def test_files_this_run_does_not_write_are_removed(self): - import export_native # noqa: PLC0415 + import export_native with tempfile.TemporaryDirectory() as tmp: root = Path(tmp) / "retropie" @@ -1576,9 +1576,9 @@ class AnExportIsWrittenAsItsBytes(unittest.TestCase): place, and dropped the mode: rocknix-systems is 100755 upstream.""" def test_bytes_mode_and_atomicity(self): - import stat # noqa: PLC0415 + import stat - import export_native # noqa: PLC0415 + import export_native with tempfile.TemporaryDirectory(dir=REPO_ROOT / "tmp") as tmp: root = Path(tmp) @@ -1604,7 +1604,7 @@ class AnExportWithoutTruthIsRefused(unittest.TestCase): uncorrected, said OK, and replaced the corrected export in exports/.""" def test_nothing_is_written_and_the_run_fails(self): - import export_native # noqa: PLC0415 + import export_native exporter = discover_exporters()["batocera"] with tempfile.TemporaryDirectory(dir=REPO_ROOT / "tmp") as tmp: @@ -1629,9 +1629,9 @@ class AnInvalidExportIsNotWritten(unittest.TestCase): code said so.""" def test_the_published_file_stays(self): - from unittest import mock # noqa: PLC0415 + from unittest import mock - import export_native # noqa: PLC0415 + import export_native if not (UPSTREAM_CACHE / "romm").exists(): self.skipTest("upstream cache not populated") @@ -1841,7 +1841,7 @@ class RommSizeIsNeverNone(unittest.TestCase): def test_an_entry_the_truth_takes_without_a_size_stays_whole(self): """RomM compares the size before any hash: the new md5 beside the old size never verified, and the report said the size was removed.""" - from export_native import landed_changes # noqa: PLC0415 + from export_native import landed_changes exporter, systems, _, data = self._export(524288) self.assertEqual( @@ -1920,13 +1920,13 @@ class RecalboxPatchesAttributesNotElements(unittest.TestCase): self.assertEqual(produced["es_bios.xml"], original) def test_a_reordered_md5_list_states_the_same(self): - from exporter.recalbox_exporter import _stated # noqa: PLC0415 + from exporter.recalbox_exporter import _stated self.assertEqual(_stated(''), _stated('')) def test_one_attribute_changes_in_place(self): - from exporter.recalbox_exporter import patch_element # noqa: PLC0415 + from exporter.recalbox_exporter import patch_element kept = ' ' mine = ' ' @@ -1956,7 +1956,7 @@ class RetrobatListComesBackAsWritten(unittest.TestCase): self.assertEqual(produced["batocera-systems.json"], original) def test_an_added_system_takes_the_same_separator(self): - from exporter.retrobat_exporter import keep_blank_lines # noqa: PLC0415 + from exporter.retrobat_exporter import keep_blank_lines original = '{\n "a": {},\n\n "b": {}\n}\n' produced = '{\n "a": {},\n "b": {},\n "c": {}\n}\n' @@ -1988,7 +1988,7 @@ class MisterDatabaseComesBackAsWritten(unittest.TestCase): def test_a_rebuilt_archive_keeps_the_member_as_mister_writes_it(self): raw, _ = self._render({"systems": {}}) - from exporter.misterfpga_exporter import rebuild_archive # noqa: PLC0415 + from exporter.misterfpga_exporter import rebuild_archive rebuilt = rebuild_archive(raw, "bios_db.json", '{"changed": true}') with zipfile.ZipFile(io.BytesIO(raw)) as before, \ @@ -2001,7 +2001,7 @@ class MisterDatabaseComesBackAsWritten(unittest.TestCase): ) def test_bytes_are_written_untouched(self): - import export_native # noqa: PLC0415 + import export_native with tempfile.TemporaryDirectory(dir=REPO_ROOT / "tmp") as tmp: export_native._write_produced(Path(tmp), {"a.zip": b"PK\x03\x04\xff"}, {}) @@ -2011,7 +2011,7 @@ class MisterDatabaseComesBackAsWritten(unittest.TestCase): """The Downloader checks each entry by size (fetch_file_worker.py:127): the old size beside the new hash described no file, and the report announced a size removal the database did not carry.""" - from export_native import landed_changes # noqa: PLC0415 + from export_native import landed_changes database = {"db_id": "bios_db", "files": { "games/X/boot.rom": {"hash": "a" * 32, "size": 100, "url": "u"}, @@ -2112,14 +2112,14 @@ class RetrodeckManifestsComeBackAsWritten(unittest.TestCase): self.assertEqual(text, originals[path]) def test_no_md5_key_is_made_up(self): - from exporter.retrodeck_exporter import Exporter # noqa: PLC0415 + from exporter.retrodeck_exporter import Exporter mine = OrderedDict([("filename", "bios.bin"), ("system", "xbox"), ("required", "Yes")]) (merged,) = Exporter._merge([OrderedDict(mine)], [OrderedDict(mine)]) self.assertNotIn("md5", merged) def test_a_single_bios_object_stays_an_object(self): - from exporter.retrodeck_exporter import Exporter # noqa: PLC0415 + from exporter.retrodeck_exporter import Exporter theirs = OrderedDict([("filename", "ppge_atlas.zim"), ("system", "psp"), ("md5", "a" * 32)]) diff --git a/tests/test_extract_targets.py b/tests/test_extract_targets.py index 59c8022f8..1995c4526 100644 --- a/tests/test_extract_targets.py +++ b/tests/test_extract_targets.py @@ -70,7 +70,7 @@ class ThePackGuideNamesTheInstallerDefault(unittest.TestCase): if rule["os"] == "windows" and rule["method"] == "path_exists" ) sys.path.insert(0, str(REPO_ROOT / "scripts")) - from siteguides import pack_manual # noqa: PLC0415 + from siteguides import pack_manual # The pack guide text is data (platforms/_guides.yml): read what the # pack README prints, not the source of the script that prints it. diff --git a/tests/test_fileless_audit.py b/tests/test_fileless_audit.py index 8409bb19c..0c6cc7c04 100644 --- a/tests/test_fileless_audit.py +++ b/tests/test_fileless_audit.py @@ -132,9 +132,8 @@ class TestCommandLine(unittest.TestCase): with mock.patch.object(sys, "argv", ["fileless_audit.py", *argv, "--emulators-dir", self.tmp.name]), \ mock.patch.object(fileless_audit, "audit", side_effect=fake), \ - mock.patch("sys.stderr"), mock.patch("sys.stdout"): - with self.assertRaises(SystemExit) as caught: - fileless_audit.main() + mock.patch("sys.stderr"), mock.patch("sys.stdout"), self.assertRaises(SystemExit) as caught: + fileless_audit.main() return caught.exception.code, read def test_all_reads_only_the_profiles_nobody_answered(self): diff --git a/tests/test_handheld_launchers.py b/tests/test_handheld_launchers.py index b69af08f7..4ea88c20b 100644 --- a/tests/test_handheld_launchers.py +++ b/tests/test_handheld_launchers.py @@ -705,7 +705,7 @@ class Device: test.addCleanup(os.close, master) test.addCleanup(os.close, slave) termios.tcsetattr(slave, termios.TCSANOW, termios.tcgetattr(slave)) - import fcntl # noqa: PLC0415 + import fcntl # Wide enough that no path in a message is folded. fcntl.ioctl(slave, termios.TIOCSWINSZ, struct.pack("HHHH", 50, 250, 0, 0)) self.master, self.slave = master, slave @@ -1570,7 +1570,7 @@ class TheBatoceraPort(unittest.TestCase): device.tool("xterm", FAKE_TERMAPP + "") socket_dir = device.root / "x11" socket_dir.mkdir() - import socket as _socket # noqa: PLC0415 + import socket as _socket sock = _socket.socket(_socket.AF_UNIX) sock.bind(str(socket_dir / "X0")) self.addCleanup(sock.close) diff --git a/tests/test_hash_merge.py b/tests/test_hash_merge.py index 22e63b710..83ee6a100 100644 --- a/tests/test_hash_merge.py +++ b/tests/test_hash_merge.py @@ -817,13 +817,11 @@ class AnUnreadableCloneStopsTheScrape(unittest.TestCase): from scripts.scraper import mame_hash_scraper as scraper failing = subprocess.CalledProcessError(128, ["git", "rev-parse", "HEAD"]) - with mock.patch.object(scraper, "_run_git", side_effect=failing): - with self.assertRaises(RuntimeError): - scraper._get_commit() + with mock.patch.object(scraper, "_run_git", side_effect=failing), self.assertRaises(RuntimeError): + scraper._get_commit() empty = subprocess.CompletedProcess(["git"], 0, stdout="\n", stderr="") - with mock.patch.object(scraper, "_run_git", return_value=empty): - with self.assertRaises(RuntimeError): - scraper._get_commit() + with mock.patch.object(scraper, "_run_git", return_value=empty), self.assertRaises(RuntimeError): + scraper._get_commit() diff --git a/tests/test_identity.py b/tests/test_identity.py index fce2c7ca9..598e3ac37 100644 --- a/tests/test_identity.py +++ b/tests/test_identity.py @@ -12,7 +12,7 @@ from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "scripts")) -import identity # noqa: E402 +import identity class TestCrossVendorDuplicates(unittest.TestCase): diff --git a/tests/test_install.py b/tests/test_install.py index a396d9485..305c26895 100644 --- a/tests/test_install.py +++ b/tests/test_install.py @@ -3,6 +3,7 @@ from __future__ import annotations import tests # noqa: F401 offline, scratch under tmp/, the suite's own cache +import argparse import contextlib import functools import hashlib @@ -429,7 +430,7 @@ class TheDataTreesCountInTheFreeSpace(unittest.TestCase): files the first installed.""" from types import SimpleNamespace - from test_install_selection import FakeRepository # noqa: PLC0415 + from test_install_selection import FakeRepository member = os.urandom(4096) results = [] @@ -1290,7 +1291,7 @@ class DetectionFollowsTheRegistry(unittest.TestCase): installer never read it: such a home detected nothing.""" def test_the_table_is_the_registry(self): - import yaml # noqa: PLC0415 + import yaml registry = yaml.safe_load( (Path(__file__).resolve().parents[1] / "platforms" / "_registry.yml").read_text() @@ -1308,7 +1309,7 @@ class DetectionFollowsTheRegistry(unittest.TestCase): Recalbox version file were detected by the installer and absent from every manifest's `detect`, and ROCKNIX was declared another way. A changed bios_path in the registry reached no installer.""" - import yaml # noqa: PLC0415 + import yaml registry = yaml.safe_load( (Path(__file__).resolve().parents[1] / "platforms" / "_registry.yml").read_text() @@ -1338,7 +1339,7 @@ class DetectionFollowsTheRegistry(unittest.TestCase): RetroDECK folder, but the installer also read Snap, the older macOS file, C:\\RetroArch, Program Files, ES-DE, Steam and RetroDECK's own config. A manifest reader saw a subset of what the installer does.""" - import yaml # noqa: PLC0415 + import yaml registry = yaml.safe_load( (Path(__file__).resolve().parents[1] / "platforms" / "_registry.yml").read_text() @@ -1370,12 +1371,12 @@ class DetectionFollowsTheRegistry(unittest.TestCase): def record(os_type: str): def probe(path, *_args, **_kwargs): read.add((os_type, str(Path(str(path).replace("\\", "/"))))) - return None + return return probe with unittest.mock.patch.dict(os.environ, env), \ - unittest.mock.patch.object(install, "_detect_embedded", lambda: []), \ - unittest.mock.patch.object(install, "_detect_android", lambda: []): + unittest.mock.patch.object(install, "_detect_embedded", list), \ + unittest.mock.patch.object(install, "_detect_android", list): for os_type in ("linux", "darwin", "windows"): with unittest.mock.patch.object( install, "_parse_retroarch_system_dir", record(os_type) @@ -1449,7 +1450,7 @@ class DetectionFollowsTheRegistry(unittest.TestCase): self.assertFalse((home / ".config" / "BizHawk").exists()) def test_the_executable_table_is_the_registry(self): - import yaml # noqa: PLC0415 + import yaml registry = yaml.safe_load( (Path(__file__).resolve().parents[1] / "platforms" / "_registry.yml").read_text() @@ -1557,13 +1558,13 @@ class InstallerStaysOnPython38AndTheStdlib(unittest.TestCase): SOURCE = (REPO_ROOT / "install.py").read_text(encoding="utf-8") def test_the_grammar_is_python_38(self): - import ast # noqa: PLC0415 + import ast ast.parse(self.SOURCE, filename="install.py", feature_version=(3, 8)) def test_every_import_is_standard_library(self): - import ast # noqa: PLC0415 - import sys # noqa: PLC0415 + import ast + import sys tree = ast.parse(self.SOURCE) imported = set() @@ -1585,8 +1586,8 @@ class InstallerStaysOnPython38AndTheStdlib(unittest.TestCase): def test_a_python_38_interpreter_compiles_and_imports_it(self): """ast.parse(feature_version=(3, 8)) on 3.12 accepts parenthesized context managers and PEP 701 f-strings: only a 3.8 interpreter says.""" - import shutil # noqa: PLC0415 - import subprocess # noqa: PLC0415 + import shutil + import subprocess python38 = shutil.which("python3.8") if python38 is None: @@ -1611,8 +1612,8 @@ class InstallerStaysOnPython38AndTheStdlib(unittest.TestCase): the repository's own manifests served over loopback. CI installs the interpreter, so there it may not skip. """ - import shutil # noqa: PLC0415 - import subprocess # noqa: PLC0415 + import shutil + import subprocess python38 = shutil.which("python3.8") if python38 is None: @@ -1666,8 +1667,8 @@ class InstallerStaysOnPython38AndTheStdlib(unittest.TestCase): def test_no_syntax_a_312_parser_lets_through(self): """Parenthesized context managers (3.9) and f-strings reusing their own quote or a backslash inside a replacement field (3.12).""" - import io # noqa: PLC0415 - import tokenize # noqa: PLC0415 + import io + import tokenize found = [] tokens = list(tokenize.generate_tokens(io.StringIO(self.SOURCE).readline)) @@ -1706,7 +1707,7 @@ class InstallerStaysOnPython38AndTheStdlib(unittest.TestCase): def test_no_runtime_generic_builtin(self): """dict[str, Path] outside an annotation runs on 3.9 and later only.""" - import ast # noqa: PLC0415 + import ast tree = ast.parse(self.SOURCE) annotations = set() @@ -1731,7 +1732,7 @@ class InstallerStaysOnPython38AndTheStdlib(unittest.TestCase): """ruff --select F in py38 mode is the installer's lint gate, and an unread `appdata` in _os_default_dests made it exit 1. The suite has no ruff, so the rule is read from the syntax tree.""" - import ast # noqa: PLC0415 + import ast tree = ast.parse((Path(__file__).resolve().parents[1] / "install.py").read_text()) unread = [] @@ -2509,7 +2510,7 @@ class TestAvailablePlatforms(unittest.TestCase): """Every edit to install.py meant a sha256sum pasted by hand into two files with two syntaxes, and the failing test named no command.""" sys.path.insert(0, str(REPO_ROOT / "scripts")) - import pin_installer # noqa: PLC0415 + import pin_installer with tempfile.TemporaryDirectory(dir=REPO_ROOT / "tmp" / "tests") as directory: root = Path(directory) @@ -2835,9 +2836,8 @@ class FileListsAreRetried(unittest.TestCase): with unittest.mock.patch.object(install.urllib.request, "urlopen", side_effect=failures), \ unittest.mock.patch.object(install.time, "sleep"), \ - contextlib.redirect_stderr(err): - with self.assertRaises(SystemExit) as caught: - install.fetch_manifest("retroarch") + contextlib.redirect_stderr(err), self.assertRaises(SystemExit) as caught: + install.fetch_manifest("retroarch") self.assertEqual(caught.exception.code, 1) self.assertIn("HTTPS_PROXY", err.getvalue()) self.assertIn(f"after {install.MAX_RETRIES} attempts", err.getvalue()) @@ -2874,9 +2874,8 @@ class ASilentServerIsBounded(unittest.TestCase): unittest.mock.patch.object(install, "_retry_delay", return_value=0), \ unittest.mock.patch.object(install, "MANIFEST_URL", f"http://127.0.0.1:{port}/{{platform}}.json"), \ - contextlib.redirect_stderr(err): - with self.assertRaises(SystemExit): - install.fetch_manifest("retroarch") + contextlib.redirect_stderr(err), self.assertRaises(SystemExit): + install.fetch_manifest("retroarch") elapsed = time.monotonic() - start self.assertLess(elapsed, 5) self.assertEqual(len(held), install.STALLED_ATTEMPTS) @@ -3649,7 +3648,7 @@ class AndroidEmulatorsOutOfReachAreSaid(unittest.TestCase): (data / "com.flycast.emulator").mkdir() (storage / "Android/data/com.flycast.emulator/files/data").mkdir(parents=True) self.assertEqual(self._lines(make), []) - import yaml # noqa: PLC0415 + import yaml registry = yaml.safe_load((REPO_ROOT / "platforms" / "_registry.yml").read_text()) copies = {entry.get("file"): entry for entry in registry["_standalone_copies"]} @@ -3899,7 +3898,7 @@ class TheBoardTheSystemNamesIsTheTarget(unittest.TestCase): self.assertIn("--every-board", result.stderr) def test_the_sources_name_our_target_lists(self): - import yaml # noqa: PLC0415 + import yaml for platform in install._BOARD_SOURCES: with self.subTest(platform=platform): @@ -3934,7 +3933,7 @@ class StandaloneCopiesReachFlatpakInstalls(unittest.TestCase): EMU_DATA_DIR), not azahar.""" def test_flatpak_and_native_directories(self): - import yaml # noqa: PLC0415 + import yaml registry = yaml.safe_load((REPO_ROOT / "platforms" / "_registry.yml").read_text()) linux = { @@ -4297,7 +4296,7 @@ class DataDirectoriesAreInstalled(unittest.TestCase): self.assertEqual(sorted(p.name for p in (bios / "dolphin-emu").iterdir()), ["Sys"]) def test_the_run_ends_on_the_archive_bytes_too(self): - from test_install_selection import FakeRepository # noqa: PLC0415 + from test_install_selection import FakeRepository member = os.urandom(300_000) with FakeRepository() as repo: @@ -4320,7 +4319,7 @@ class DataDirectoriesAreInstalled(unittest.TestCase): def test_the_plan_announces_the_archive_not_the_tree(self): """yaps2's tarball is 21.2 MB for a 6.5 MB tree, Cemu's 21.4 MB for 9.9 KB: the plan announced the tree, and the run downloaded far more.""" - from test_install_selection import FakeRepository # noqa: PLC0415 + from test_install_selection import FakeRepository member = b"profile" archive_size = 21_360_579 @@ -4569,8 +4568,8 @@ class ACheckNamesWhatTheCollectionLacks(unittest.TestCase): unnamed for a user asking why Caesar III would not start.""" def test_recalbox_caesar3(self): - import shutil # noqa: PLC0415 - import subprocess # noqa: PLC0415 + import shutil + import subprocess manifest = json.loads((REPO_ROOT / "install" / "recalbox.json").read_text()) lacking = sorted( @@ -4613,7 +4612,7 @@ class ARefusedStandaloneCopyIsNamed(unittest.TestCase): the BIOS folder and gave no advice.""" def test_the_file_and_its_folder_reach_the_summary(self): - import contextlib # noqa: PLC0415 + import contextlib if os.name == "nt" or os.geteuid() == 0: self.skipTest("a read-only folder needs POSIX modes and a non-root user") @@ -4711,7 +4710,7 @@ class ACheckThatFindsFilesMissingIsNoFailure(unittest.TestCase): BIOS folder to complete from a tool that never ran.""" def test_missing_is_3_and_a_failure_stays_1(self): - from test_install_selection import FakeRepository # noqa: PLC0415 + from test_install_selection import FakeRepository with FakeRepository() as repo: missing = repo.run("--no-input", "--check") @@ -4735,7 +4734,7 @@ class OneEmulatorsFilesInOneCommand(unittest.TestCase): } def test_only_its_files_and_its_systems(self): - import contextlib # noqa: PLC0415 + import contextlib files = [ {"dest": "pcem/ibmpc.bin", "cores": ["pcem"], "systems": ["ibm-pc"]}, @@ -4749,7 +4748,7 @@ class OneEmulatorsFilesInOneCommand(unittest.TestCase): self.assertEqual(sorted(e["dest"] for e in kept), ["ibm.rom", "pcem/ibmpc.bin"]) def test_an_unknown_name_is_refused(self): - import contextlib # noqa: PLC0415 + import contextlib with contextlib.redirect_stderr(io.StringIO()), self.assertRaises(SystemExit): install._narrow_to_emulators(["nope"], self.MANIFEST, "retroarch", [], []) @@ -5085,9 +5084,9 @@ class TheInstallerSaysWhatItFound(unittest.TestCase): the file list was fetched ended on a socket traceback.""" def setUp(self): - import functools # noqa: PLC0415 - import http.server # noqa: PLC0415 - import shutil # noqa: PLC0415 + import functools + import http.server + import shutil handler = functools.partial( http.server.SimpleHTTPRequestHandler, directory=str(REPO_ROOT) @@ -5149,8 +5148,8 @@ class TheInstallerSaysWhatItFound(unittest.TestCase): self.assertGreater(error, banner, proc.stdout) def test_ctrl_c_before_the_downloads_is_a_stop(self): - import signal # noqa: PLC0415 - import socket # noqa: PLC0415 + import signal + import socket silent = socket.socket() silent.bind(("127.0.0.1", 0)) @@ -5162,7 +5161,7 @@ class TheInstallerSaysWhatItFound(unittest.TestCase): "--dest", str(self.home / "s")], cwd=REPO_ROOT, env=env, stdout=subprocess.PIPE, stderr=subprocess.PIPE, text=True, ) - import time # noqa: PLC0415 + import time time.sleep(3) proc.send_signal(signal.SIGINT) @@ -5674,8 +5673,8 @@ class AQuestionLeftWithCtrlDOrCtrlCIsAStop(unittest.TestCase): @unittest.skipIf(os.name == "nt", "needs a pseudo-terminal") def test_ctrl_d_at_the_platform_question_exits_130(self): - import pty # noqa: PLC0415 - import time # noqa: PLC0415 + import pty + import time home = Path(_tempdir(self)) master, slave = pty.openpty() @@ -6105,7 +6104,7 @@ class StandaloneEmulatorsWithoutAPlatformAreServed(unittest.TestCase, _LoopbackR self.assertIn("scph5501.bin", names) # Every image the DuckStation profile places in its bios folder, # its PS2 and OpenBIOS images included, and nothing else. - import yaml # noqa: PLC0415 + import yaml profile = yaml.safe_load((REPO_ROOT / "emulators" / "duckstation.yml").read_text()) named = {PurePosixPath(entry["standalone_path"]).name @@ -6265,7 +6264,7 @@ class RetroBatIsFoundWhereItSaysItIs(unittest.TestCase): RetroBat.exe writes its folder to the registry on every start.""" def test_the_table_is_the_registry(self): - import yaml # noqa: PLC0415 + import yaml registry = yaml.safe_load((REPO_ROOT / "platforms" / "_registry.yml").read_text()) rules = { @@ -7051,7 +7050,7 @@ class EventsDescribeTheRun(unittest.TestCase, _SyntheticTree): def test_a_run_is_valid_against_the_published_schema(self): try: - from jsonschema import Draft202012Validator # noqa: PLC0415 + from jsonschema import Draft202012Validator except ImportError: self.skipTest("jsonschema is not installed") schema = json.loads(EVENT_SCHEMA_PATH.read_text(encoding="utf-8")) @@ -7075,7 +7074,7 @@ class TheEventSchemaFileIsEventKeys(unittest.TestCase): def _generator(self): sys.path.insert(0, str(REPO_ROOT / "scripts")) - import generate_event_schema # noqa: PLC0415 + import generate_event_schema return generate_event_schema @@ -7123,7 +7122,7 @@ class TheInstallerPageIsWrittenFromTheCode(unittest.TestCase): def setUp(self): sys.path.insert(0, str(REPO_ROOT / "scripts")) - import generate_installer_doc # noqa: PLC0415 + import generate_installer_doc self.generator = generate_installer_doc self.scratch = Path(_tempdir(self)) / "installer.md" @@ -7247,7 +7246,7 @@ class NetworkFailuresInPlainWords(unittest.TestCase): return install.network_words(urllib.error.URLError(reason), **kwargs) def test_the_common_failures(self): - import ssl # noqa: PLC0415 + import ssl cases = ( (socket.gaierror(-2, "Name or service not known"), "no internet connection"), @@ -7273,8 +7272,8 @@ class NetworkFailuresInPlainWords(unittest.TestCase): def test_a_clock_in_the_past_is_named(self): """A handheld with no clock battery boots in 1980, and every certificate then reads as not yet valid.""" - import datetime # noqa: PLC0415 - import ssl # noqa: PLC0415 + import datetime + import ssl error = ssl.SSLCertVerificationError(1, "certificate is not yet valid") with unittest.mock.patch.object(install, "_ca_bundle_found", return_value=True): @@ -7286,7 +7285,7 @@ class NetworkFailuresInPlainWords(unittest.TestCase): self.assertEqual(code, "network") def test_no_certificate_list_names_ssl_cert_file(self): - import ssl # noqa: PLC0415 + import ssl error = ssl.SSLCertVerificationError(1, "unable to get local issuer certificate") with unittest.mock.patch.object(install, "_ca_bundle_found", return_value=False): diff --git a/tests/test_install_app.py b/tests/test_install_app.py index 34a4e499d..2f30ec4ac 100644 --- a/tests/test_install_app.py +++ b/tests/test_install_app.py @@ -13,7 +13,6 @@ import tests # noqa: F401 offline, scratch under tmp/, the suite's own cache import hashlib import io import json -import os import shutil import stat import subprocess @@ -218,7 +217,7 @@ class TheList(unittest.TestCase): if "repo_path" in entry else entry["content"].encode()) for entry in launcher["members"]] data = install.app_archive(members) - import build_port # noqa: PLC0415 + import build_port built = _tempdir(self) / build_port.MUOS_APP build_port.build_archive(build_port.MUOS_APP, built) with zipfile.ZipFile(built) as release, zipfile.ZipFile(io.BytesIO(data)) as ours: diff --git a/tests/test_install_cores.py b/tests/test_install_cores.py index ae45ab1af..9082430a2 100644 --- a/tests/test_install_cores.py +++ b/tests/test_install_cores.py @@ -560,9 +560,8 @@ class AnUnknownTargetStopsTheRunFirst(unittest.TestCase): mock.patch.object(sys, "argv", ["install.py", "--target", "steamos", "--list-systems", "--no-input"]), \ contextlib.redirect_stdout(io.StringIO()), \ - contextlib.redirect_stderr(io.StringIO()) as err: - with self.assertRaises(SystemExit) as stop: - install.main() + contextlib.redirect_stderr(io.StringIO()) as err, self.assertRaises(SystemExit) as stop: + install.main() self.assertEqual(stop.exception.code, 2) self.assertIn("unknown target 'steamos' for RetroArch", err.getvalue()) self.assertIn("Nothing was installed", err.getvalue()) diff --git a/tests/test_install_experience.py b/tests/test_install_experience.py index 6ffcbb1b0..aaf65c0ab 100644 --- a/tests/test_install_experience.py +++ b/tests/test_install_experience.py @@ -41,10 +41,10 @@ class _RangeHandler(http.server.BaseHTTPRequestHandler): ranges: list[str] = [] fail_first: list[int] = [] - def log_message(self, *args) -> None: # noqa: D102 + def log_message(self, *args) -> None: pass - def do_GET(self) -> None: # noqa: N802, D102 + def do_GET(self) -> None: if self.fail_first: code = self.fail_first.pop(0) self.send_response(code) @@ -441,10 +441,10 @@ class _HeldHandler(http.server.BaseHTTPRequestHandler): manifest = b"" release = threading.Event() - def log_message(self, *args) -> None: # noqa: D102 + def log_message(self, *args) -> None: pass - def do_GET(self) -> None: # noqa: N802, D102 + def do_GET(self) -> None: if self.path.endswith(".json"): body = self.manifest else: @@ -465,8 +465,8 @@ class AStoppedRunCountsWhatLanded(unittest.TestCase): @unittest.skipIf(os.name == "nt", "SIGINT is sent the POSIX way") def test_only_the_written_file_is_counted(self): - import signal # noqa: PLC0415 - import time # noqa: PLC0415 + import signal + import time files = {name: name.encode() * 64 for name in ("first.bin", "second.bin", "third.bin")} manifest = {"manifest_version": 2, "platform": "retroarch", "files": [ diff --git a/tests/test_install_expert.py b/tests/test_install_expert.py index 791717329..419e56b3c 100644 --- a/tests/test_install_expert.py +++ b/tests/test_install_expert.py @@ -559,11 +559,10 @@ class ExpertRuns(Lists): install._validate_manifest(good, "retroarch") for broken in ([["../x.bin", LAYOUTS["standalone_layouts"]["duckstation"][0][1]]], [["ds/x.bin", "0" * 40]]): - with self.subTest(layout=broken): - with self.assertRaises(ValueError): - install._check_standalone_layouts( - {**LAYOUTS, "standalone_layouts": {"duckstation": broken}}, - LIST, "retroarch") + with self.subTest(layout=broken), self.assertRaises(ValueError): + install._check_standalone_layouts( + {**LAYOUTS, "standalone_layouts": {"duckstation": broken}}, + LIST, "retroarch") with self.assertRaises(ValueError): install._check_standalone_layouts({**LAYOUTS, "standalone_layouts": {}}, LIST, "retroarch") diff --git a/tests/test_install_games.py b/tests/test_install_games.py index cf45f3059..3711c3929 100644 --- a/tests/test_install_games.py +++ b/tests/test_install_games.py @@ -544,7 +544,7 @@ class KeepEveryRegionCases(unittest.TestCase): # The installer's own jobs (Python 3.8 with pyte alone) import this # module for its card builders, and install.py needs no pyyaml. try: - import yaml # noqa: PLC0415 + import yaml except ImportError as exc: raise unittest.SkipTest("pyyaml reads games/regions.yml") from exc with open(REPO_ROOT / "games" / "regions.yml", encoding="utf-8") as handle: @@ -1015,7 +1015,7 @@ class DataTreesFollowTheGamesCores(unittest.TestCase): class _Quiet(http.server.SimpleHTTPRequestHandler): - def log_message(self, format, *args): # noqa: A002 - stdlib signature + def log_message(self, format, *args): return diff --git a/tests/test_install_journeys.py b/tests/test_install_journeys.py index 3e0fa7351..d48e0cb30 100644 --- a/tests/test_install_journeys.py +++ b/tests/test_install_journeys.py @@ -123,7 +123,7 @@ _WITH_CARDS = ( class _Quiet(http.server.SimpleHTTPRequestHandler): - def log_message(self, format, *args): # noqa: A002 - stdlib signature + def log_message(self, format, *args): return diff --git a/tests/test_install_offline.py b/tests/test_install_offline.py index 5994f1a4d..9e4a83486 100644 --- a/tests/test_install_offline.py +++ b/tests/test_install_offline.py @@ -436,7 +436,7 @@ class ABoardWithoutTheNetwork(Scratch): def test_the_builder_writes_both_into_the_pack_list(self): sys.path.insert(0, str(REPO_ROOT / "scripts")) - import generate_pack # noqa: PLC0415 + import generate_pack install_list = manifest() board_file = REPO_ROOT / "platforms" / "targets" / "batocera.yml" @@ -725,7 +725,7 @@ class OfflineMakesNoRequest(Scratch): learn its platform, since nothing said "make no request".""" def _served(self, *options: str, env: dict | None = None): - import test_install_selection # noqa: PLC0415 + import test_install_selection hits: list[str] = [] with FakeRepository() as repo, unittest.mock.patch.object( @@ -818,13 +818,13 @@ class ANetworkThatDroppedFailsFast(unittest.TestCase): self.assertLessEqual(install.MAX_RETRIES * install.CONNECT_TIMEOUT + waited, 15) def test_a_slow_answer_on_an_open_connection_still_arrives(self): - import http.server # noqa: PLC0415 - import threading # noqa: PLC0415 + import http.server + import threading delay = install.CONNECT_TIMEOUT + 1 class Slow(http.server.BaseHTTPRequestHandler): - def do_GET(self): # noqa: N802 - stdlib name + def do_GET(self): time.sleep(delay) body = b'{"ok": true}' self.send_response(200) diff --git a/tests/test_install_pack.py b/tests/test_install_pack.py index e77b068a9..8bfffc8b6 100644 --- a/tests/test_install_pack.py +++ b/tests/test_install_pack.py @@ -62,7 +62,7 @@ BIG = {f"arcade/set{n}.zip": (_noise(str(n), 24 * 1024), ["arcade"], None, None) class _Quiet(http.server.SimpleHTTPRequestHandler): - def log_message(self, format, *args): # noqa: A002 - stdlib signature + def log_message(self, format, *args): return diff --git a/tests/test_install_selection.py b/tests/test_install_selection.py index 8c329645d..3f34215b4 100644 --- a/tests/test_install_selection.py +++ b/tests/test_install_selection.py @@ -515,7 +515,7 @@ class TheBoundaryChecksTheNewFields(unittest.TestCase): class _QuietHandler(http.server.SimpleHTTPRequestHandler): - def log_message(self, format, *args): # noqa: A002 - stdlib signature + def log_message(self, format, *args): return @@ -743,7 +743,7 @@ class TheOneLinerNarrows(unittest.TestCase): @unittest.skipIf(os.name == "nt", "a pseudo-terminal is a POSIX one") def test_ctrl_d_at_the_first_question_has_nothing_to_carry_on(self): - import pty # noqa: PLC0415 + import pty with FakeRepository() as repo: home = repo.root / "home" @@ -1358,8 +1358,8 @@ class ThePlatformsOwnSystemNamesAreAccepted(unittest.TestCase): file records psx as the native_system of sony-playstation.""" def test_the_names_come_from_the_platform_file(self): - from common import load_platform_config # noqa: PLC0415 - from common import platform_system_names # noqa: PLC0415 + from common import load_platform_config + from common import platform_system_names config = load_platform_config("batocera", str(REPO_ROOT / "platforms")) names = platform_system_names(config, list(config["systems"])) @@ -1378,7 +1378,7 @@ class ThePlatformsOwnSystemNamesAreAccepted(unittest.TestCase): def test_every_listed_system_gets_the_title_the_site_prints(self): sys.path.insert(0, str(REPO_ROOT / "scripts")) - from generate_pack import system_titles # noqa: PLC0415 + from generate_pack import system_titles files = [{"dest": "a.bin", "systems": ["sony-playstation", "nintendo-gba"]}] omitted = [{"dest": "b.bin", "systems": ["3do"]}] diff --git a/tests/test_install_tui.py b/tests/test_install_tui.py index 0b8efcc51..7b44676a5 100644 --- a/tests/test_install_tui.py +++ b/tests/test_install_tui.py @@ -4996,7 +4996,7 @@ class Pty: class _SlowHandler(_QuietHandler): """Serves each file after a pause, so a test can stop a download midway.""" - def do_GET(self) -> None: # noqa: N802, D102 + def do_GET(self) -> None: if self.path.startswith("/bios/"): time.sleep(0.6) super().do_GET() @@ -5056,7 +5056,7 @@ class SaveDirectoryRepository(FakeRepository): def _app_card(test: unittest.TestCase, system: str) -> tuple[Path, Path]: """A card of system in the repository's tmp/, its root and BIOS folder.""" - from test_install_app import make_card # noqa: PLC0415 + from test_install_app import make_card (REPO_ROOT / "tmp").mkdir(exist_ok=True) root = Path(tempfile.mkdtemp(dir=REPO_ROOT / "tmp")) @@ -5238,7 +5238,7 @@ class EndToEnd(unittest.TestCase): def card_repo(self, system: str) -> tuple[Path, Path]: - from test_install_app import AppRepository, make_card # noqa: PLC0415 + from test_install_app import AppRepository, make_card repo = self.repo(AppRepository) root = repo.root / "card" @@ -7113,9 +7113,7 @@ class OneCardReading(unittest.TestCase): for before, after in zip(body, body[1:]): count = blank_before(after) with self.subTest(line=after.lineno): - if isinstance(after, definitions): - self.assertEqual(count, 2) - elif isinstance(before, definitions): + if isinstance(after, definitions) or isinstance(before, definitions): self.assertEqual(count, 2) def test_a_refusal_is_said_once_and_another_card_names_its_remedy(self): @@ -7381,7 +7379,7 @@ class WhatEachScreenOffers(unittest.TestCase): def menu(_plat, files, *_rest, **_named): menus.append([entry["dest"] for entry in files]) - return None + return with SaveDirectoryRepository() as repo: argv = ["install.py", "--platform", "retroarch", "--dest", str(repo.dest), @@ -7581,7 +7579,7 @@ class _CardFixtures: regions: bool = True) -> tuple[Path, Path, dict]: """A list of plat's shape (the MinUI family records cores and regions, no system), the pack built from it and the files' payloads.""" - from test_install_offline import GBA, JP, US # noqa: PLC0415 + from test_install_offline import GBA, JP, US payloads = {"Bios/MGBA/gba_bios.bin": (GBA, "nintendo-gba", "mgba", None), "Bios/PS/scph5501.bin": (US, "sony-playstation", "pcsx_rearmed", @@ -7604,7 +7602,7 @@ class _CardFixtures: return listing, None, {} sys.path.insert(0, str(REPO_ROOT / "scripts")) self.addCleanup(sys.path.remove, str(REPO_ROOT / "scripts")) - import generate_pack # noqa: PLC0415 + import generate_pack pack_list = {"files": [{"path": dest, "sha1": entry["sha1"], "size": entry["size"]} for dest, entry in zip(payloads, files)]} @@ -7846,7 +7844,7 @@ class _OutsideTextFindings: return out.getvalue() + err.getvalue() + events.getvalue() def test_a_pack_member_path_is_refused(self): - from test_install_offline import _pack, GBA # noqa: PLC0415 + from test_install_offline import _pack, GBA pack = _pack(self.root, "RetroArch_v1_BIOS_Pack.zip", {f"x{self.OSC}.bin": GBA}) text = self.run_install(_args(platform="retroarch", dest=self.dest, @@ -8356,7 +8354,7 @@ class LineModeAndScreenDecideAlike(_LineModeFindings, _OutsideTextFindings, with mock.patch.object(install, "_ask", side_effect=["2", "q"]), \ contextlib.redirect_stdout(io.StringIO()) as out, \ self.assertRaises(SystemExit): - install._prompt_platform_choice([("retroarch", self.here)], other=lambda: []) + install._prompt_platform_choice([("retroarch", self.here)], other=list) self.assertIn("Type 1, o for another setup or folder, or q to quit.", out.getvalue()) self.assertNotIn("1 to 1", out.getvalue()) @@ -9232,7 +9230,7 @@ class PacksWordingAndDocs(unittest.TestCase): def test_a_pack_records_the_systems_of_its_files(self): sys.path.insert(0, str(REPO_ROOT / "scripts")) self.addCleanup(sys.path.remove, str(REPO_ROOT / "scripts")) - import generate_pack # noqa: PLC0415 + import generate_pack install_list = {"files": [{"dest": "a.bin", "systems": ["3do"]}, {"dest": "b/c.bin", "systems": []}], @@ -9249,7 +9247,7 @@ class PacksWordingAndDocs(unittest.TestCase): self.assertIn("systems", schema["properties"]["files"]["items"]["properties"]) def pack(self, systems: bool) -> Path: - from test_install_offline import GBA, US # noqa: PLC0415 + from test_install_offline import GBA, US members = {"scph5501.bin": US, "gba_bios.bin": GBA} listed = [{"path": path, "sha1": hashlib.sha1(data).hexdigest(), @@ -9298,7 +9296,7 @@ class PacksWordingAndDocs(unittest.TestCase): def test_a_pack_cannot_write_escapes_through_its_system_names(self): """The titles and ids a pack records reached print() raw in the systems list.""" - from test_install_offline import GBA, US # noqa: PLC0415 + from test_install_offline import GBA, US members = {"scph5501.bin": US, "gba_bios.bin": GBA} listed = [{"path": path, "sha1": hashlib.sha1(data).hexdigest(), "size": len(data), @@ -9955,7 +9953,7 @@ class LineModeDecisions(unittest.TestCase): patcher, asked = self.ask("") with patcher, contextlib.redirect_stdout(io.StringIO()) as out: chosen = install._prompt_platform_choice( - found, labels={("retroarch", here): "RetroArch"}, other=lambda: []) + found, labels={("retroarch", here): "RetroArch"}, other=list) self.assertEqual(chosen, found) self.assertEqual(asked, ["> [Enter for RetroArch] "]) self.assertIn("o) another setup or folder", out.getvalue()) @@ -10281,7 +10279,7 @@ class ScreenRowsAndFilters(unittest.TestCase): def test_a_folder_that_cannot_be_created_ends_on_an_error_and_a_summary(self): """Cannot create, then end 2 and nothing else.""" - import subprocess # noqa: PLC0415 + import subprocess from test_install_offline import PAYLOAD, _offline_env, _pack @@ -10604,7 +10602,7 @@ class CardNamesAndHelp(_CardFixtures, unittest.TestCase): is a row, about.info among them.""" sys.path.insert(0, str(REPO_ROOT / "scripts")) self.addCleanup(sys.path.remove, str(REPO_ROOT / "scripts")) - import generate_installer_doc # noqa: PLC0415 + import generate_installer_doc page = (REPO_ROOT / "wiki" / "installer.md").read_text(encoding="utf-8") block = page[page.index(""): @@ -10910,7 +10908,7 @@ class MouseOnEveryScreen(unittest.TestCase): @staticmethod def twin(state: install.TuiState) -> install.TuiState: - import copy # noqa: PLC0415 + import copy return copy.deepcopy(state) @@ -12830,7 +12828,7 @@ class TapsOnAPtySeeFirst(unittest.TestCase): term.close() def test_the_game_data_row_keeps_the_ticks_to_the_install(self): - from test_install_tui import GameDataRepository # noqa: PLC0415 + from test_install_tui import GameDataRepository repo = self.repo(GameDataRepository) term = self.start() @@ -14682,7 +14680,7 @@ class ProvenCardsAndCounts(unittest.TestCase): where Install and Choose systems are, the second screen.""" sys.path.insert(0, str(REPO_ROOT / "scripts")) self.addCleanup(sys.path.remove, str(REPO_ROOT / "scripts")) - import generate_site # noqa: PLC0415 + import generate_site words = " ".join(generate_site.first_screen_words()) found, nothing = fresh_state(), install.TuiState(os_type="linux", home=HOME) @@ -15096,7 +15094,7 @@ class CoresListAndFolderFailures(unittest.TestCase): def test_no_connection_leaves_the_loopback_nor_a_card_comes_in(self): """261 connections to GitHub left this module, and tests failed with an AmberELEC card in the reader.""" - import socket # noqa: PLC0415 + import socket log = Path(os.environ["RETROBIOS_TEST_NETLOG"]) before = log.read_text(encoding="utf-8") @@ -15261,7 +15259,7 @@ class GamesEndToEnd(unittest.TestCase): """The real --tui on a card with games, against a loopback repository.""" def test_the_plan_opens_on_the_games_and_installs_only_them(self): - import test_install_games as games # noqa: PLC0415 + import test_install_games as games card = games.Card() self.addCleanup(card.close) @@ -16290,9 +16288,8 @@ class DeviceAndEmulatorReview(unittest.TestCase): opened.append(archive) return archive - with mock.patch.object(install.zipfile, "ZipFile", side_effect=tracked): - with self.assertRaises(ValueError): - install.PackSource([notpack]) + with mock.patch.object(install.zipfile, "ZipFile", side_effect=tracked), self.assertRaises(ValueError): + install.PackSource([notpack]) self.assertTrue(opened) self.assertTrue(all(archive.fp is None for archive in opened)) diff --git a/tests/test_launcher_evidence.py b/tests/test_launcher_evidence.py index 57659fc80..8c1aca155 100644 --- a/tests/test_launcher_evidence.py +++ b/tests/test_launcher_evidence.py @@ -15,10 +15,10 @@ from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "scripts")) -import yaml # noqa: E402 +import yaml -from common import load_platform_config # noqa: E402 -from launchers import ( # noqa: E402 +from common import load_platform_config +from launchers import ( bound_launchers, config_evidence, config_target, @@ -26,9 +26,9 @@ from launchers import ( # noqa: E402 launcher_places, launcher_unproven, ) -from profile_sync import _check_build_refs, shipped_build_holders # noqa: E402 -from scraper.retrobat_launchers import _choices_apart # noqa: E402 -from scraper.shell_launchers import ( # noqa: E402 +from profile_sync import _check_build_refs, shipped_build_holders +from scraper.retrobat_launchers import _choices_apart +from scraper.shell_launchers import ( LauncherPatternMissing, Script, config_placement, @@ -41,7 +41,7 @@ REPO_ROOT = Path(__file__).resolve().parents[1] def schema_checks(test: unittest.TestCase): """validate_schemas, or a skip: it needs jsonschema, the build does not.""" try: - import validate_schemas # noqa: PLC0415 + import validate_schemas except ImportError as exc: test.skipTest(f"validate_schemas needs jsonschema: {exc}") return validate_schemas diff --git a/tests/test_launcher_gaps.py b/tests/test_launcher_gaps.py index a2e8bdbc1..77e16d58f 100644 --- a/tests/test_launcher_gaps.py +++ b/tests/test_launcher_gaps.py @@ -27,11 +27,11 @@ from unittest import mock sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "scripts")) -import yaml # noqa: E402 +import yaml -import verify # noqa: E402 -from common import _emulator_profiles_cache, load_emulator_profiles, load_platform_config # noqa: E402 -from cross_reference import ( # noqa: E402 +import verify +from common import _emulator_profiles_cache, load_emulator_profiles, load_platform_config +from cross_reference import ( LAUNCHER_READS_KEY, LAUNCHER_UNPROVEN_KEY, launcher_file_names, diff --git a/tests/test_launcher_layer.py b/tests/test_launcher_layer.py index 7f37fef6b..9034ec4ca 100644 --- a/tests/test_launcher_layer.py +++ b/tests/test_launcher_layer.py @@ -21,11 +21,11 @@ import zipfile sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "scripts")) -import yaml # noqa: E402 +import yaml -from common import _emulator_profiles_cache, load_emulator_profiles, load_platform_config # noqa: E402 -from launchers import LauncherLayer, launcher_places, suffixed_stem # noqa: E402 -from verify import find_undeclared_files, verify_platform # noqa: E402 +from common import _emulator_profiles_cache, load_emulator_profiles, load_platform_config +from launchers import LauncherLayer, launcher_places, suffixed_stem +from verify import find_undeclared_files, verify_platform CONTENT = { "b.bin": b"REGION_B_IMAGE", diff --git a/tests/test_launchers_retrobat.py b/tests/test_launchers_retrobat.py index 58dd8430e..c1be16844 100644 --- a/tests/test_launchers_retrobat.py +++ b/tests/test_launchers_retrobat.py @@ -1551,9 +1551,8 @@ class AbsentConstructStopsTheScrape(unittest.TestCase): def test_each_extractor_raises_on_an_empty_source(self): empty = {path: rl.Source(path, "") for path in rl.SOURCE_FILES} for extractor in rl.EXTRACTORS: - with self.subTest(extractor=extractor.__name__): - with self.assertRaises(rl.LauncherPatternMissing): - extractor(empty) + with self.subTest(extractor=extractor.__name__), self.assertRaises(rl.LauncherPatternMissing): + extractor(empty) def test_chain_without_fallback_is_not_a_search(self): single = ARES.split(" if (!File.Exists(bios_japan))")[0] + " }\n" @@ -1581,7 +1580,7 @@ class Helpers(unittest.TestCase): self.assertEqual(src.lines(*src.block_at(0)), (2, 4)) def test_a_rescrape_reads_the_pinned_commit(self): - from scraper import retrobat_scraper as rs # noqa: PLC0415 + from scraper import retrobat_scraper as rs pin = "ca486005f598551600d04a33b3156a5d764368d6" with tempfile.TemporaryDirectory(dir=REPO_ROOT / "tmp") as scratch: diff --git a/tests/test_launchers_retropie.py b/tests/test_launchers_retropie.py index d035724f3..fa1b74150 100644 --- a/tests/test_launchers_retropie.py +++ b/tests/test_launchers_retropie.py @@ -536,7 +536,7 @@ class PlatformRecords(unittest.TestCase): def test_one_package_record_per_core(self): packages = [r["package"] for r in self.config["launchers"] if r["kind"] == "package"] self.assertEqual(len(packages), len(set(packages))) - from scraper.retropie_scraper import core_name # noqa: PLC0415 + from scraper.retropie_scraper import core_name self.assertEqual({core_name(p) for p in packages}, set(self.config["cores"])) diff --git a/tests/test_mame_devices.py b/tests/test_mame_devices.py index 05aa8f36e..5965f4050 100644 --- a/tests/test_mame_devices.py +++ b/tests/test_mame_devices.py @@ -1014,9 +1014,8 @@ class Cli(unittest.TestCase): from unittest import mock with mock.patch.object(sys, "argv", ["x", "--devices"]), \ - mock.patch("sys.stderr", new=io.StringIO()): - with self.assertRaises(SystemExit) as raised: - main() + mock.patch("sys.stderr", new=io.StringIO()), self.assertRaises(SystemExit) as raised: + main() self.assertEqual(raised.exception.code, 2) diff --git a/tests/test_measurements.py b/tests/test_measurements.py index 099d18807..c3f7ac589 100644 --- a/tests/test_measurements.py +++ b/tests/test_measurements.py @@ -252,7 +252,7 @@ class ReadAndIndex(Workspace): self.assertEqual(sm.result_of(full_record("alpha", "c", "2026-10-06T10:00:00+00:00"))[0], "differs") def test_a_boot_on_the_built_in_bios_is_named_so(self) -> None: - import core_probe # noqa: PLC0415 + import core_probe record = full_record("alpha", "region-x-game-others", "2026-10-28T10:00:00+00:00", kind="run", observable="frame_hashes") @@ -343,7 +343,7 @@ class ReadAndIndex(Workspace): from jsonschema import Draft202012Validator except ImportError: self.skipTest("jsonschema is not installed") - import validate_schemas # noqa: PLC0415 + import validate_schemas self.assertEqual(validate_schemas._measurement_errors(self.tree), []) lines = self.tree / mr.records_path("beta") @@ -377,7 +377,7 @@ class ReadAndIndex(Workspace): from jsonschema import Draft202012Validator # noqa: F401 except ImportError: self.skipTest("jsonschema is not installed") - import validate_schemas # noqa: PLC0415 + import validate_schemas lines = self.tree / mr.records_path("beta") record = json.loads(lines.read_text()) @@ -653,8 +653,8 @@ class SitePages(unittest.TestCase): class Freshness(unittest.TestCase): def test_no_measurements_area(self) -> None: - import check_freshness # noqa: PLC0415 - import refresh_stale # noqa: PLC0415 + import check_freshness + import refresh_stale self.assertNotIn("measurements", check_freshness.AREAS) self.assertNotIn("measurements", refresh_stale.AUTO_AREAS) diff --git a/tests/test_name_tiebreak.py b/tests/test_name_tiebreak.py index 9270a30c2..347a8cb93 100644 --- a/tests/test_name_tiebreak.py +++ b/tests/test_name_tiebreak.py @@ -38,7 +38,7 @@ class DeclaredSizeOrders(unittest.TestCase): class OwnerOutranksSharedTree(unittest.TestCase): def test_the_owners_copy_beats_two_matching_segments(self): """armsx2's fxaa.fx lost to NetherSX2's under shaders/common/.""" - from common import _by_affinity # noqa: PLC0415 + from common import _by_affinity paths = [ "bios/Other/nethersx2/assets/shaders/common/fxaa.fx", diff --git a/tests/test_optional_dependencies.py b/tests/test_optional_dependencies.py index 15bba8b3f..be912f07f 100644 --- a/tests/test_optional_dependencies.py +++ b/tests/test_optional_dependencies.py @@ -76,7 +76,7 @@ class ScriptsNeedOnlyPyyaml(unittest.TestCase): there and fail for a contributor following the documented setup.""" def test_no_script_imports_another_package(self): - import ast # noqa: PLC0415 + import ast scripts = Path(__file__).resolve().parents[1] / "scripts" local = {p.stem for p in scripts.rglob("*.py")} | { @@ -112,7 +112,7 @@ class TheDownloaderRunsWithoutPyyaml(unittest.TestCase): import, every CI job (which installs pyyaml) would stay green.""" def test_help_runs_with_yaml_unimportable(self): - import subprocess # noqa: PLC0415 + import subprocess root = Path(__file__).resolve().parents[1] code = ( diff --git a/tests/test_pack_failures.py b/tests/test_pack_failures.py index 9ec1e7d1d..3296c9edc 100644 --- a/tests/test_pack_failures.py +++ b/tests/test_pack_failures.py @@ -55,11 +55,10 @@ class FailedPlatformFailsTheRun(unittest.TestCase): self.assertEqual(ctx.exception.code, 1) def test_manifest_mode(self): - with mock.patch.object(gp, "generate_manifest", _boom): - with self.assertRaises(SystemExit) as ctx: - gp._run_manifest_mode( - self._args(), [(["retropie"], "retropie")], {}, {}, {}, {} - ) + with mock.patch.object(gp, "generate_manifest", _boom), self.assertRaises(SystemExit) as ctx: + gp._run_manifest_mode( + self._args(), [(["retropie"], "retropie")], {}, {}, {}, {} + ) self.assertEqual(ctx.exception.code, 1) diff --git a/tests/test_pack_file_names.py b/tests/test_pack_file_names.py index cf5c4de43..78f5ac048 100644 --- a/tests/test_pack_file_names.py +++ b/tests/test_pack_file_names.py @@ -54,7 +54,7 @@ class SystemPackLeavesTheEmulatorPack(unittest.TestCase): """--system built under the emulator pack's name and renamed it away.""" def test_both_packs_stay(self): - import subprocess # noqa: PLC0415 + import subprocess with tempfile.TemporaryDirectory(dir=REPO_ROOT / "tmp") as tmp: for mode in (["--emulator", "emuscv"], ["--system", "scv"]): diff --git a/tests/test_pack_member_identity.py b/tests/test_pack_member_identity.py index 5eeb7d64b..9cc0fc826 100644 --- a/tests/test_pack_member_identity.py +++ b/tests/test_pack_member_identity.py @@ -94,7 +94,7 @@ class OneComparisonOfArchiveMembers(unittest.TestCase): import zipfile sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "scripts")) - from packverify import _same_members # noqa: PLC0415 + from packverify import _same_members def archive(members: dict) -> bytes: buffer = io.BytesIO() diff --git a/tests/test_path_suffix.py b/tests/test_path_suffix.py index 62ee65d56..7b8e40b1b 100644 --- a/tests/test_path_suffix.py +++ b/tests/test_path_suffix.py @@ -13,8 +13,8 @@ from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "scripts")) -from common import resolve_local_file # noqa: E402 -from generate_db import _path_suffixes # noqa: E402 +from common import resolve_local_file +from generate_db import _path_suffixes class TestPathSuffixes(unittest.TestCase): diff --git a/tests/test_port.py b/tests/test_port.py index 9685b00d2..c137525f5 100644 --- a/tests/test_port.py +++ b/tests/test_port.py @@ -118,7 +118,7 @@ class LauncherIndex(unittest.TestCase): the archives built from the same tree, each with its size and hash.""" def test_the_committed_list_is_current(self): - import generate_launcher_index # noqa: PLC0415 + import generate_launcher_index text = generate_launcher_index.render(generate_launcher_index.build_index()) self.assertEqual( @@ -134,7 +134,7 @@ class LauncherIndex(unittest.TestCase): self.assertIn("scripts/generate_launcher_index.py", section) def test_every_member_of_the_archives_is_listed(self): - import generate_launcher_index # noqa: PLC0415 + import generate_launcher_index index = json.loads(generate_launcher_index.OUTPUT.read_text(encoding="utf-8")) places = {place.key: place for place in install.APP_PLACES.values()} @@ -152,7 +152,7 @@ class LauncherIndex(unittest.TestCase): self.assertEqual(hashlib.sha256(data).hexdigest(), entry["sha256"]) def test_the_list_refuses_an_installer_the_bootstraps_do_not_pin(self): - import generate_launcher_index # noqa: PLC0415 + import generate_launcher_index root = _tempdir(self) shutil.copyfile(REPO_ROOT / "install.py", root / "install.py") diff --git a/tests/test_profile_sync.py b/tests/test_profile_sync.py index b021764a4..cb6a005a2 100644 --- a/tests/test_profile_sync.py +++ b/tests/test_profile_sync.py @@ -311,9 +311,8 @@ class TestSourceMirror(unittest.TestCase): "source_commit": "87b176a", "upstream_commit": "07021f0", } - with tempfile.TemporaryDirectory() as cache: - with self.assertRaises(profile_sync.upstream.NotCachedError): - profile_sync.select_views(profile, cache, True) + with tempfile.TemporaryDirectory() as cache, self.assertRaises(profile_sync.upstream.NotCachedError): + profile_sync.select_views(profile, cache, True) def test_a_profile_without_a_mirror_is_unchanged(self): profile = {"source": "https://github.com/o/port"} @@ -2640,7 +2639,7 @@ class TestWriteDryRun(unittest.TestCase): # untracked file, where outside one it answers nothing at all. subprocess.run(["git", "init", "-q"], cwd=self.dir, check=True) # The cited files gained nothing since the pin in these fixtures. - from unittest import mock # noqa: PLC0415 + from unittest import mock def nothing_gained(args, profile, report): report.new_files, report.new_hashes = [], [] @@ -2657,7 +2656,7 @@ class TestWriteDryRun(unittest.TestCase): def test_a_file_gained_since_the_pin_holds_the_bump(self): # mame2003_plus's zn.c gained two G-NET BIOS sets around refs that # only shifted. - from unittest import mock # noqa: PLC0415 + from unittest import mock def gained(args, profile, report): report.new_files = [{"path": "zn.c", "name": "coh3002t.zip", "since_pin": True}] @@ -2704,7 +2703,7 @@ class TestWriteDryRun(unittest.TestCase): """The bumped profile was promoted before the prose under its new pin was read. Offline, an uncached cited file raised NotCachedError past the restore and the profile kept a pin the guard would refuse.""" - from unittest import mock # noqa: PLC0415 + from unittest import mock before = self.path.read_bytes() cold = profile_sync.upstream.NotCachedError("x.c not cached") @@ -3042,7 +3041,7 @@ class TestDeliberatelyFrozenPin(TestBuildReport): # reicast is the commit Recalbox's reicast.mk builds, 789 commits # behind master. Compared to HEAD it showed eight refs to review that # nobody could act on. - from common import load_emulator_profiles # noqa: PLC0415 + from common import load_emulator_profiles root = Path(__file__).resolve().parents[1] / "emulators" profiles = load_emulator_profiles(str(root)) @@ -3062,7 +3061,7 @@ class TestDeliberatelyFrozenPin(TestBuildReport): # RetroPie builds ppsspp-1.5.4 as PPSSPPSDL alone: the frozen build # is the standalone half of a project that also ships a core. builds_differ = {("duckstation-legacy", "duckstation"), ("ppsspp-1.5.4", "ppsspp")} - from common import load_emulator_profiles # noqa: PLC0415 + from common import load_emulator_profiles root = Path(__file__).resolve().parents[1] / "emulators" profiles = load_emulator_profiles(str(root)) @@ -3626,7 +3625,7 @@ class APassedReleaseIsNewerThanTheTag(unittest.TestCase): v0.2.20: the pin holds v0.2.20 without core_version being older.""" def test_a_release_older_than_the_declared_tag_is_not_passed(self): - from unittest import mock # noqa: PLC0415 + from unittest import mock version = profile_sync.VersionReport( "v0.2.22", "v0.2.22", "v0.2.20", "2026-07-25", True, "tag22" @@ -3641,7 +3640,7 @@ class ANewerReleaseThanTheTag(unittest.TestCase): """armsx2 sat on its 2.8 tag while 2.9 was out, and read as clean.""" def _newer(self, after_tag, after_pin): - from unittest import mock # noqa: PLC0415 + from unittest import mock version = profile_sync.VersionReport("2.8", "2.9", "2.9", "2026-10-01", True, "tag28") args = argparse.Namespace(cache_dir="c", offline=True) @@ -3679,7 +3678,7 @@ class AProjectThatOnlyTags(unittest.TestCase): self.assertEqual(profile_sync.published_version(version), "1.1") def test_a_newer_tag_is_named(self): - from unittest import mock # noqa: PLC0415 + from unittest import mock version = profile_sync.VersionReport("v1.2", "v1.3", None, None, True, "tag12") args = argparse.Namespace(cache_dir="c", offline=True) @@ -3698,7 +3697,7 @@ class APassedReleaseUnderAnUntaggedVersion(unittest.TestCase): self.assertIn("already contains release v9.0-6", warning) def test_only_a_higher_number_counts_without_a_tag(self): - from unittest import mock # noqa: PLC0415 + from unittest import mock args = argparse.Namespace(cache_dir="c", offline=True) cases = {("9.0.5", "v9.0-6"): "v9.0-6", ("1.61", "1.53"): None, @@ -5120,9 +5119,9 @@ class AWriteRefreshesTheSourcePaths(unittest.TestCase): return argparse.Namespace(**{**base, **kw}) def test_only_a_real_online_write_refreshes(self): - from unittest import mock # noqa: PLC0415 + from unittest import mock - import sitesources # noqa: PLC0415 + import sitesources with mock.patch.object(sitesources, "build_source_paths", return_value=({}, [])) as built, \ mock.patch.dict(os.environ, {"RETROBIOS_OFFLINE": ""}), \ @@ -5143,10 +5142,10 @@ class AWriteRefreshesTheSourcePaths(unittest.TestCase): def test_the_record_reads_the_pins_just_written(self): # The loader caches by directory and the run had loaded the profiles # before writing them: the record kept the pins it had replaced. - from unittest import mock # noqa: PLC0415 + from unittest import mock - import common # noqa: PLC0415 - import sitesources # noqa: PLC0415 + import common + import sitesources with tempfile.TemporaryDirectory() as tmp: profile = Path(tmp) / "p.yml" @@ -5170,7 +5169,7 @@ class AnUnreadTreeKeepsItsRecord(unittest.TestCase): trees it never read from source-paths.json.""" def test_unread_trees_carry_over(self): - import sitesources # noqa: PLC0415 + import sitesources kept = sitesources.keep_unread( {"a@1": ["x.c"]}, ["b@2", "c@3"], {"b@2": ["y.c"], "a@1": ["old.c"]} @@ -5379,9 +5378,8 @@ class TestRealignFlagMatrix(unittest.TestCase): saved = sys.argv try: sys.argv = argv - with contextlib.redirect_stderr(stderr): - with self.assertRaises(SystemExit) as caught: - profile_sync.main() + with contextlib.redirect_stderr(stderr), self.assertRaises(SystemExit) as caught: + profile_sync.main() finally: sys.argv = saved return caught.exception.code, stderr.getvalue() @@ -5491,9 +5489,8 @@ class TestEmulatorsDirStatus(unittest.TestCase): def test_a_tree_outside_any_repository_is_not_clean(self): with tempfile.TemporaryDirectory() as root, mock.patch.dict( os.environ, {"GIT_CEILING_DIRECTORIES": str(Path(root).parent)} - ): - with self.assertRaises(RuntimeError): - profile_sync.emulators_dir_is_dirty(root) + ), self.assertRaises(RuntimeError): + profile_sync.emulators_dir_is_dirty(root) class UpstreamVendoredAsASubmodule(unittest.TestCase): @@ -5503,7 +5500,7 @@ class UpstreamVendoredAsASubmodule(unittest.TestCase): have moved upstream_commit past what libretro builds.""" def _views(self, links: dict) -> list: - from unittest import mock # noqa: PLC0415 + from unittest import mock repo_s, repo_u = object(), object() views = [ @@ -5531,7 +5528,7 @@ class AMirrorOutlivesAGoneSource(unittest.TestCase): the source_mirror declared after it, so the profile stayed unchecked.""" def test_the_mirror_is_read_when_the_source_is_gone(self): - from unittest import mock # noqa: PLC0415 + from unittest import mock gone_repo = profile_sync.upstream.make_repo("github.com", "yuzu-emu-mirror", "yuzu") mirror = profile_sync.upstream.make_repo("github.com", "fork", "yuzu") @@ -5572,7 +5569,7 @@ class RealignReadsThePathAsWritten(unittest.TestCase): hatari/hatari's src/tos.c and proposed moving a correct citation.""" def test_an_unmoved_repository_carrying_the_path_keeps_it(self): - from unittest import mock # noqa: PLC0415 + from unittest import mock fork = profile_sync.upstream.make_repo("github.com", "b", "hatariB") up = profile_sync.upstream.make_repo("github.com", "hatari", "hatari") @@ -5598,7 +5595,7 @@ class RealignGivesASharedPathToTheFirstRepository(unittest.TestCase): upstream_commit moved, the fork's citations were read in upstream.""" def test_the_source_declared_first_keeps_it(self): - from unittest import mock # noqa: PLC0415 + from unittest import mock fork = profile_sync.upstream.make_repo("github.com", "t", "freej2me-plus") up = profile_sync.upstream.make_repo("github.com", "hex007", "freej2me") @@ -5621,7 +5618,7 @@ class UpstreamForkedByThePort(unittest.TestCase): past anything the port carries.""" def _views(self, base, ancestry=None): - from unittest import mock # noqa: PLC0415 + from unittest import mock fork = profile_sync.upstream.make_repo("github.com", "f", "port") self.up = profile_sync.upstream.make_repo("github.com", "o", "up") @@ -5804,7 +5801,7 @@ class TheUnknownProfileHintCountsTheListing(unittest.TestCase): listing of 530: the alias and test profiles it counted are not listed.""" def test_the_count_matches(self): - import subprocess # noqa: PLC0415 + import subprocess root = Path(__file__).resolve().parents[1] hint = subprocess.run( @@ -6257,7 +6254,7 @@ class TestBranchCheckIsWired(unittest.TestCase): def test_contributing_and_ci_use_the_flags(self): root = Path(__file__).resolve().parents[1] sys.path.insert(0, str(root / "scripts")) - import generate_readme # noqa: PLC0415 + import generate_readme text = generate_readme.generate_contributing() self.assertIn("profile_sync.py --added --strict", text) diff --git a/tests/test_prose_style.py b/tests/test_prose_style.py index ac533c382..b31e1dc36 100644 --- a/tests/test_prose_style.py +++ b/tests/test_prose_style.py @@ -11,7 +11,6 @@ from __future__ import annotations import tests # noqa: F401 offline, scratch under tmp/, the suite's own cache import io -import os import re import subprocess import tokenize @@ -73,9 +72,7 @@ def _python_prose(source: str) -> str: parts: list[str] = [] previous = tokenize.INDENT for token in tokenize.generate_tokens(io.StringIO(source).readline): - if token.type == tokenize.COMMENT: - parts.append(token.string) - elif token.type == tokenize.STRING and previous in ( + if token.type == tokenize.COMMENT or token.type == tokenize.STRING and previous in ( tokenize.INDENT, tokenize.NEWLINE, tokenize.NL, tokenize.DEDENT, ): parts.append(token.string) @@ -117,16 +114,7 @@ def _yaml_prose(text: str) -> str: # Words a heading keeps capitalized: names of platforms, systems and programs. -_HEADING_KEEP = set("""Batocera Recalbox Lakka Dolphin Redump Linux Windows Android Python Steam Deck -macOS Termux Flatpak Switch Raspberry Pi Mega Drive Genesis Saturn Dreamcast Amiga Atari Sega -Nintendo Sony Neo Geo Lynx Jaguar Commodore Apple Mac Spectrum Sinclair Amstrad MSX GameCube Wii -Game Boy Advance Famicom Disk System Super Master PlayStation Vita Xbox Arcade English French -Spanish I Lua Unity Qt Kodi Discord Pages Actions Docker Windows Mac Ubuntu Debian Arch -SteamOS Chihiro NAOMI Triforce Lindbergh Model PinMAME ScummVM Dinothawr Cemu Citra Yuzu Ryujinx -Mednafen Beetle Stella Hatari Caprice Vice Fuse Daphne Hypseus Singe Supermodel Flycast Redream -DuckStation SwanStation Opera Gearsystem Picodrive Snes9x Nestopia Mesen Gambatte SameBoy -mGBA melonDS DeSmuME Azahar Eden Sudachi Torzu Xemu Cxbx PCSX2 AetherSX2 NetherSX2 ARMSX2 -RPCS3 Vita3K Zinc Raine FBNeo FinalBurn Neo MAME Clrmamepro RomVault""".split()) +_HEADING_KEEP = set(["Batocera", "Recalbox", "Lakka", "Dolphin", "Redump", "Linux", "Windows", "Android", "Python", "Steam", "Deck", "macOS", "Termux", "Flatpak", "Switch", "Raspberry", "Pi", "Mega", "Drive", "Genesis", "Saturn", "Dreamcast", "Amiga", "Atari", "Sega", "Nintendo", "Sony", "Neo", "Geo", "Lynx", "Jaguar", "Commodore", "Apple", "Mac", "Spectrum", "Sinclair", "Amstrad", "MSX", "GameCube", "Wii", "Game", "Boy", "Advance", "Famicom", "Disk", "System", "Super", "Master", "PlayStation", "Vita", "Xbox", "Arcade", "English", "French", "Spanish", "I", "Lua", "Unity", "Qt", "Kodi", "Discord", "Pages", "Actions", "Docker", "Windows", "Mac", "Ubuntu", "Debian", "Arch", "SteamOS", "Chihiro", "NAOMI", "Triforce", "Lindbergh", "Model", "PinMAME", "ScummVM", "Dinothawr", "Cemu", "Citra", "Yuzu", "Ryujinx", "Mednafen", "Beetle", "Stella", "Hatari", "Caprice", "Vice", "Fuse", "Daphne", "Hypseus", "Singe", "Supermodel", "Flycast", "Redream", "DuckStation", "SwanStation", "Opera", "Gearsystem", "Picodrive", "Snes9x", "Nestopia", "Mesen", "Gambatte", "SameBoy", "mGBA", "melonDS", "DeSmuME", "Azahar", "Eden", "Sudachi", "Torzu", "Xemu", "Cxbx", "PCSX2", "AetherSX2", "NetherSX2", "ARMSX2", "RPCS3", "Vita3K", "Zinc", "Raine", "FBNeo", "FinalBurn", "Neo", "MAME", "Clrmamepro", "RomVault"]) def _sentence_case(title: str) -> str: @@ -462,12 +450,12 @@ class GeneratedSiteProse(unittest.TestCase): """The site pages carry strings no tracked file shows verbatim.""" def test_generated_pages(self): - import sys # noqa: PLC0415 + import sys sys.path.insert(0, str(ROOT / "scripts")) - from generate_site import LOCAL_NOTE_DIRS # noqa: PLC0415 + from generate_site import LOCAL_NOTE_DIRS - from tests import sitepages # noqa: PLC0415 + from tests import sitepages pages = [p for p in sitepages.pages() if not set(p.relative_to(sitepages.CONTENT).parts[:-1]) & set(LOCAL_NOTE_DIRS)] diff --git a/tests/test_provenance.py b/tests/test_provenance.py index 4dd467c74..51b72b677 100644 --- a/tests/test_provenance.py +++ b/tests/test_provenance.py @@ -582,7 +582,7 @@ class OneDumpIsCountedOnce(unittest.TestCase): the site's Wanted page published the larger number.""" def test_a_dump_in_several_dats_is_one_missing_entry(self): - from scripts import provenance_report # noqa: PLC0415 + from scripts import provenance_report rom = {"name": "DICROM.rom", "sha1": "a" * 40, "size": 32768} held = {"name": "held.rom", "sha1": "b" * 40, "size": 16} @@ -613,7 +613,7 @@ class AMissingDumpNamesTheProfileItFills(unittest.TestCase): } def _report(self, db): - from scripts import provenance_report # noqa: PLC0415 + from scripts import provenance_report snapshots = {"no-intro": {"entries": [ {"dat": "FM-7", "name": "DICROM.rom", "sha1": "a" * 40, "size": 262144}, @@ -635,14 +635,14 @@ class AMissingDumpNamesTheProfileItFills(unittest.TestCase): self.assertIsNone(missing["unread.rom"]) def test_a_size_outside_the_profile_range_fills_nothing(self): - from scripts import provenance_report # noqa: PLC0415 + from scripts import provenance_report needs = provenance_report.profile_needs(self.PROFILES, {"files": {}}) small = {"name": "DICROM.rom", "size": 1024} self.assertEqual(provenance_report.needs_filled(small, needs), []) def test_a_need_the_collection_answers_is_not_one(self): - from scripts import provenance_report # noqa: PLC0415 + from scripts import provenance_report db = {"files": {"e" * 40: {"name": "dicrom.rom", "size": 262144}}} needs = provenance_report.profile_needs(self.PROFILES, db) @@ -651,7 +651,7 @@ class AMissingDumpNamesTheProfileItFills(unittest.TestCase): def test_a_file_installed_with_the_emulator_is_not_a_need(self): """43 of 50 needs were bundled entries (samcoupe.rom, zesarux's tk90x.rom), burying the six xm7 ROMs a maintainer has to find.""" - from scripts import provenance_report # noqa: PLC0415 + from scripts import provenance_report profiles = { "samcoupe": {"files": [{"name": "samcoupe.rom", "required": True, @@ -669,7 +669,7 @@ class TheWantedPageAsksOnlyForWhatCannotBeMade(unittest.TestCase): already produces (a Kickstart's odd bytes, a character ROM's halves).""" def test_a_derivable_dump_moves_out_of_the_wanted_list(self): - from scripts import generate_site # noqa: PLC0415 + from scripts import generate_site report = {"tosec": { "imported_at": "2026-01-01", "dats": {}, "total": 2, "matched": 0, diff --git a/tests/test_refresh_data_dirs.py b/tests/test_refresh_data_dirs.py index 963a7e1fb..701c30287 100644 --- a/tests/test_refresh_data_dirs.py +++ b/tests/test_refresh_data_dirs.py @@ -119,7 +119,7 @@ class RefreshConcurrency(unittest.TestCase): """A pipeline reads every tree for its whole run. A build beside it waited on the exclusive lock before asking the remote, which would have answered that nothing changed.""" - import fcntl # noqa: PLC0415 + import fcntl self.cache.mkdir(parents=True) rdd._record_version("pak", {"sha": "e1", "archive_size": 1}, self.versions) @@ -143,7 +143,7 @@ class RefreshConcurrency(unittest.TestCase): def test_a_waiting_refresh_names_the_lock_and_the_way_around(self): """"waiting for data/dolphin-sys: another run holds it" named neither the lock nor its holder, and the build waited unbounded.""" - import fcntl # noqa: PLC0415 + import fcntl self.cache.mkdir(parents=True) lock_path = self.cache.with_name(".pak.lock") @@ -172,9 +172,8 @@ class RefreshConcurrency(unittest.TestCase): def test_version_file_is_never_left_truncated(self): Path(self.versions).parent.mkdir(parents=True) Path(self.versions).write_text(json.dumps({"keep": {"sha": "1"}})) - with mock.patch.object(rdd.json, "dump", side_effect=OSError("disk full")): - with self.assertRaises(OSError): - rdd._save_versions({"keep": {"sha": "2"}}, self.versions) + with mock.patch.object(rdd.json, "dump", side_effect=OSError("disk full")), self.assertRaises(OSError): + rdd._save_versions({"keep": {"sha": "2"}}, self.versions) self.assertEqual(json.loads(Path(self.versions).read_text()), {"keep": {"sha": "1"}}) def test_concurrent_writers_keep_each_other(self): @@ -194,7 +193,7 @@ class RefreshConcurrency(unittest.TestCase): class PackWalkHoldsTheCache(unittest.TestCase): def test_a_refresh_waits_for_the_walk(self): - import fcntl # noqa: PLC0415 + import fcntl with tempfile.TemporaryDirectory(dir=REPO_ROOT / "tmp") as tmp: @@ -217,9 +216,9 @@ class PackWalkHoldsTheCache(unittest.TestCase): class EmulatorPackHoldsTheCache(unittest.TestCase): def test_the_walk_holds_a_shared_lock(self): - import fcntl # noqa: PLC0415 + import fcntl - from generate_pack import _pack_data_tree # noqa: PLC0415 + from generate_pack import _pack_data_tree with tempfile.TemporaryDirectory(dir=REPO_ROOT / "tmp") as tmp: cache = Path(tmp) / "data" / "scummvm" @@ -305,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 generate_pack import _manifest_data_directories # noqa: PLC0415 + from generate_pack import _manifest_data_directories (REPO_ROOT / "tmp").mkdir(exist_ok=True) with tempfile.TemporaryDirectory(dir=REPO_ROOT / "tmp") as tmp: diff --git a/tests/test_refresh_failures.py b/tests/test_refresh_failures.py index 7e2942913..2d0dd6ffc 100644 --- a/tests/test_refresh_failures.py +++ b/tests/test_refresh_failures.py @@ -267,7 +267,7 @@ class AKeyMustServeThePlatform(unittest.TestCase): dolphin-sys was refreshed for RomM, which never reads it.""" def test_a_key_outside_the_platform_is_refused(self): - import subprocess # noqa: PLC0415 + import subprocess root = Path(__file__).resolve().parents[1] refused = subprocess.run( diff --git a/tests/test_refresh_stale.py b/tests/test_refresh_stale.py index 8ab9ca66e..032be84e9 100644 --- a/tests/test_refresh_stale.py +++ b/tests/test_refresh_stale.py @@ -257,8 +257,8 @@ class SavedFindings(unittest.TestCase): def test_dry_run_json_prints_the_plan_as_json(self): """--dry-run --json printed the text plan, and a caller parsing it as JSON failed on the first line.""" - import json # noqa: PLC0415 - import subprocess # noqa: PLC0415 + import json + import subprocess with tempfile.TemporaryDirectory(dir=REPO_ROOT / "tmp" / "tests") as directory: path = Path(directory) / "freshness.json" @@ -280,7 +280,7 @@ class SavedFindings(unittest.TestCase): """romfolders was added to check_freshness and not here: its rows were dropped from a saved report without a word, and --only romfolders was refused.""" - import check_freshness # noqa: PLC0415 + import check_freshness self.assertEqual(set(check_freshness.AREAS), set(rs.AUTO_AREAS + rs.MANUAL_AREAS)) jobs, surfaced, _ = rs.plan_jobs([finding("romfolders", "muos")], REGISTRY, {}) @@ -302,7 +302,7 @@ class AFailedCheckIsNamed(unittest.TestCase): def _run(self, raises: Exception | None = None, **result): proc = subprocess.CompletedProcess([], **result) if result else None with mock.patch.object(rs.subprocess, "run", side_effect=raises, return_value=proc): - return rs._run_check_freshness(("coreinfo",), []) # noqa: SLF001 + return rs._run_check_freshness(("coreinfo",), []) def test_a_crash_shows_its_stderr(self): with self.assertRaises(RuntimeError) as raised: diff --git a/tests/test_region.py b/tests/test_region.py index 01a43f094..bb3303d4a 100644 --- a/tests/test_region.py +++ b/tests/test_region.py @@ -13,9 +13,9 @@ from pathlib import Path sys.path.insert(0, os.path.join(os.path.dirname(__file__), "..", "scripts")) -import common # noqa: E402 -import region # noqa: E402 -from packextras import emulator_region_drops # noqa: E402 +import common +import region +from packextras import emulator_region_drops class TestVocabulary(unittest.TestCase): @@ -1009,9 +1009,9 @@ class EmulatorModeKeepsAHeldFile(unittest.TestCase): shipped no PlayStation BIOS.""" def test_a_missing_match_does_not_withdraw_the_held_file(self): - import hashlib # noqa: PLC0415 - import shutil # noqa: PLC0415 - import tempfile # noqa: PLC0415 + import hashlib + import shutil + import tempfile root = Path(tempfile.mkdtemp(dir=Path(__file__).resolve().parents[1] / "tmp")) self.addCleanup(shutil.rmtree, root, True) @@ -1458,7 +1458,7 @@ 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 packreadme import _build_readme # noqa: PLC0415 + from packreadme import _build_readme readme = _build_readme( "retroarch", "RetroArch", "system", 1, 1, diff --git a/tests/test_region_platform_index.py b/tests/test_region_platform_index.py index 12d206dd3..63278078d 100644 --- a/tests/test_region_platform_index.py +++ b/tests/test_region_platform_index.py @@ -58,7 +58,7 @@ class OnlyThePlatformsCoresRankASlot(unittest.TestCase): } def test_a_foreign_rank_orders_nothing(self): - import slot as slot_mod # noqa: PLC0415 + import slot as slot_mod config = {"cores": ["beetle_psx"], "systems": {"sony-playstation": {"files": []}}} index = slot_mod.platform_slot_index(config, self.PROFILES) diff --git a/tests/test_region_required_only.py b/tests/test_region_required_only.py index b3a2cfdef..471d43d96 100644 --- a/tests/test_region_required_only.py +++ b/tests/test_region_required_only.py @@ -49,7 +49,7 @@ class EmulatorModeToo(unittest.TestCase): the optional US cards won the group, then --required-only removed them.""" def test_the_required_card_survives(self): - from packextras import emulator_region_drops # noqa: PLC0415 + from packextras import emulator_region_drops profile = {"systems": ["nec-pc-engine"], "files": [ {"name": "syscard3.pce", "required": True, "region": ["japan"]}, diff --git a/tests/test_retired_files.py b/tests/test_retired_files.py index fee66c0ab..e37ed1f4e 100644 --- a/tests/test_retired_files.py +++ b/tests/test_retired_files.py @@ -70,7 +70,7 @@ class WhatLeftIsRecorded(unittest.TestCase): class TheLookupAnswersForIt(unittest.TestCase): def test_records_lead_to_the_card_in_its_place(self): - import generate_site # noqa: PLC0415 + import generate_site retired = {OLD: {"name": "a2diskiing.zip", "path": "bios/Arcade/Arcade/a2diskiing.zip", "crc32": "292ef826", "left": "2026-10-22", "successor": "ee" * 20}, diff --git a/tests/test_romset_recipes.py b/tests/test_romset_recipes.py index 0d8d2d1c2..c929185dd 100644 --- a/tests/test_romset_recipes.py +++ b/tests/test_romset_recipes.py @@ -687,10 +687,10 @@ class TheMissingReportNamesItsTargets(unittest.TestCase): only in --json.""" def test_every_target_is_named(self): - import contextlib # noqa: PLC0415 - import io # noqa: PLC0415 + import contextlib + import io - import romset_recipes # noqa: PLC0415 + import romset_recipes gap = { "constructible": [], @@ -715,9 +715,9 @@ class IdentificationReadsTheDirectoryFirst(unittest.TestCase): whose members could never match.""" def test_a_recipe_with_other_members_is_never_built(self): - from torrentzip import build_torrentzip # noqa: PLC0415 + from torrentzip import build_torrentzip - import romset_recipes # noqa: PLC0415 + import romset_recipes rom = b"rom bytes" crc = format(zlib.crc32(rom), "08x") @@ -733,7 +733,7 @@ class IdentificationReadsTheDirectoryFirst(unittest.TestCase): return build_torrentzip([(name, rom) for name, _crc in recipe]) def digest(self, recipe): - import hashlib # noqa: PLC0415 + import hashlib blob = self.build(recipe) return hashlib.md5(blob).hexdigest(), len(blob) @@ -776,9 +776,9 @@ class WriteRunsTheReportItWrites(unittest.TestCase): --write saves come from the missing-pins report, which did not run.""" def test_write_implies_missing(self): - import argparse # noqa: PLC0415 + import argparse - import romset_recipes # noqa: PLC0415 + import romset_recipes args = argparse.Namespace(identify=True, missing=False, write=True) romset_recipes._resolve_modes(args) diff --git a/tests/test_save_root.py b/tests/test_save_root.py index 67a2a42d1..6647fee06 100644 --- a/tests/test_save_root.py +++ b/tests/test_save_root.py @@ -715,7 +715,7 @@ class _Repository: class _Quiet(http.server.SimpleHTTPRequestHandler): - def log_message(self, *args) -> None: # noqa: D102 + def log_message(self, *args) -> None: pass diff --git a/tests/test_scraper_contract.py b/tests/test_scraper_contract.py index 7b588ede3..a5c6e38a3 100644 --- a/tests/test_scraper_contract.py +++ b/tests/test_scraper_contract.py @@ -134,8 +134,8 @@ class RateLimitedForge(unittest.TestCase): @staticmethod def _limited(retry_after: str | None): - import email.message # noqa: PLC0415 - import io # noqa: PLC0415 + import email.message + import io headers = email.message.Message() if retry_after is not None: @@ -143,9 +143,9 @@ class RateLimitedForge(unittest.TestCase): return urllib.error.HTTPError("u", 429, "Too Many Requests", headers, io.BytesIO()) def test_a_rate_limit_is_waited_out(self): - import io # noqa: PLC0415 + import io - from scraper.base_scraper import fetch_bytes # noqa: PLC0415 + from scraper.base_scraper import fetch_bytes waits: list[float] = [] answers = [self._limited("7"), self._limited(None), io.BytesIO(b"ok")] @@ -161,22 +161,20 @@ class RateLimitedForge(unittest.TestCase): self.assertEqual(waits, [7.0, 4.0]) def test_a_lasting_limit_or_a_missing_file_fails(self): - from scraper.base_scraper import fetch_bytes # noqa: PLC0415 + from scraper.base_scraper import fetch_bytes def limited(_request, timeout): raise self._limited(None) - with mock.patch("urllib.request.urlopen", limited): - with self.assertRaises(ConnectionError): - fetch_bytes("https://x", attempts=3, sleep=lambda _s: None) + with mock.patch("urllib.request.urlopen", limited), self.assertRaises(ConnectionError): + fetch_bytes("https://x", attempts=3, sleep=lambda _s: None) def gone(_request, timeout): raise urllib.error.HTTPError("u", 404, "Not Found", None, None) waits: list[float] = [] - with mock.patch("urllib.request.urlopen", gone): - with self.assertRaises(ConnectionError): - fetch_bytes("https://x", sleep=waits.append) + with mock.patch("urllib.request.urlopen", gone), self.assertRaises(ConnectionError): + fetch_bytes("https://x", sleep=waits.append) self.assertEqual(waits, []) @@ -185,9 +183,9 @@ class RecalboxReadsItsSystemsInBatches(unittest.TestCase): scrape past its half-hour timeout.""" def test_one_query_per_fifty_systems(self): - import json as _json # noqa: PLC0415 + import json as _json - from scraper import recalbox_scraper # noqa: PLC0415 + from scraper import recalbox_scraper systems = [f"sys{i:03}" for i in range(120)] queries: list[list[str]] = [] @@ -217,7 +215,7 @@ class EveryNamedScraperExists(unittest.TestCase): of stale targets would have failed on its import.""" def test_registry_scrapers_are_modules(self): - import yaml # noqa: PLC0415 + import yaml registry = yaml.safe_load((REPO_ROOT / "platforms" / "_registry.yml").read_text()) scraper_dir = REPO_ROOT / "scripts" / "scraper" @@ -664,7 +662,7 @@ class UnreadableReleaseStopsTheScrape(unittest.TestCase): def _registry_scrapers() -> list[str]: """Every platform scraper the registry names: a hand-written list left rocknix, retrodeck, minui, nextui and myminui unchecked.""" - import yaml # noqa: PLC0415 + import yaml registry = yaml.safe_load((REPO_ROOT / "platforms" / "_registry.yml").read_text()) return sorted({entry["scraper"] for entry in registry["platforms"].values() @@ -766,7 +764,7 @@ class UnreadableReleaseStopsTheScrape(unittest.TestCase): def test_a_core_info_file_the_forge_refuses_raises(self): """Read as empty, the core left the result and --compare-db counted none of its firmware missing.""" - from scraper import coreinfo_scraper # noqa: PLC0415 + from scraper import coreinfo_scraper scraper = coreinfo_scraper.Scraper() with mock.patch.object( @@ -802,7 +800,7 @@ class EveryGitHubApiCallerSendsTheToken(unittest.TestCase): def test_each_function_building_an_api_request_reads_the_token(self): """Per module, one call of github_headers anywhere covered them all: fetch_github_latest_tag sent no token beside a helper that did.""" - import ast # noqa: PLC0415 + import ast scripts = Path(__file__).resolve().parent.parent / "scripts" silent = [] @@ -829,7 +827,7 @@ class EveryGitHubApiCallerSendsTheToken(unittest.TestCase): self.assertEqual(silent, []) def test_the_tag_helper_sends_the_token_and_raises(self): - from scraper import base_scraper # noqa: PLC0415 + from scraper import base_scraper seen = {} @@ -936,7 +934,7 @@ class OneNativeIdOneSystem(unittest.TestCase): FOLDS = {"fbneo", "pcenginecd"} def test_scrapers_agree_on_every_shared_native_id(self): - from common import _norm_system_id # noqa: PLC0415 + from common import _norm_system_id seen: dict[str, dict[str, str]] = {} for path in sorted((REPO_ROOT / "scripts" / "scraper").glob("*_scraper.py")): @@ -956,9 +954,9 @@ class OneNativeIdOneSystem(unittest.TestCase): def test_retrobat_files_its_systems_as_batocera_does(self): """RetroBat kept psx, nds and atari800: no profile system met them, so no core extra joined them and --system found nothing.""" - import yaml # noqa: PLC0415 + import yaml - from scraper import batocera_scraper, retrobat_scraper # noqa: PLC0415 + from scraper import batocera_scraper, retrobat_scraper for native, slug in batocera_scraper.SYSTEM_SLUG_MAP.items(): self.assertEqual(retrobat_scraper.SYSTEM_SLUG_MAP[native], slug) @@ -979,9 +977,9 @@ class OneNativeIdOneSystem(unittest.TestCase): } def test_every_platform_system_meets_a_profile_system(self): - import yaml # noqa: PLC0415 + import yaml - from common import ( # noqa: PLC0415 + from common import ( _norm_system_id, load_emulator_profiles, load_platform_config, @@ -1002,9 +1000,9 @@ class OneNativeIdOneSystem(unittest.TestCase): self.assertEqual(stray, set()) def test_xroar_machines_reach_the_platforms_that_run_it(self): - import yaml # noqa: PLC0415 + import yaml - from common import _norm_system_id # noqa: PLC0415 + from common 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"]} @@ -1025,13 +1023,13 @@ class HashScraperRefusesAnEmptyRead(unittest.TestCase): """ def _fresh(self, sets: dict) -> dict: - from datetime import datetime, timezone # noqa: PLC0415 + from datetime import datetime, timezone return {"fetched_at": datetime.now(timezone.utc).isoformat(), "commit": "abc", "bios_sets": sets} def test_mame_raises_and_writes_no_cache(self): - from scraper import mame_hash_scraper as m # noqa: PLC0415 + from scraper import mame_hash_scraper as m with tempfile.TemporaryDirectory() as tmp: cache = Path(tmp) / "mame-hashes.json" @@ -1040,19 +1038,18 @@ class HashScraperRefusesAnEmptyRead(unittest.TestCase): mock.patch.object(m, "_sparse_clone"), \ mock.patch.object(m, "_cleanup"), \ mock.patch.object(m, "_get_commit", return_value="abc"), \ - mock.patch.object(m, "parse_mame_source_tree", return_value={}): - with self.assertRaises(RuntimeError): - m._fetch_hashes(force=True) + mock.patch.object(m, "parse_mame_source_tree", return_value={}), self.assertRaises(RuntimeError): + m._fetch_hashes(force=True) self.assertFalse(cache.exists()) def test_mame_does_not_serve_an_empty_cache(self): - from scraper import mame_hash_scraper as m # noqa: PLC0415 + from scraper import mame_hash_scraper as m self.assertTrue(m._is_stale(self._fresh({}))) self.assertFalse(m._is_stale(self._fresh({"neogeo": {}}))) def test_fbneo_raises_and_writes_no_cache(self): - from scraper import fbneo_hash_scraper as f # noqa: PLC0415 + from scraper import fbneo_hash_scraper as f with tempfile.TemporaryDirectory() as tmp: cache = Path(tmp) / "fbneo-hashes.json" @@ -1060,13 +1057,12 @@ class HashScraperRefusesAnEmptyRead(unittest.TestCase): mock.patch.object(f, "_sparse_clone"), \ mock.patch.object(f, "_cleanup"), \ mock.patch.object(f, "_extract_version", return_value=("v1.0.0.03", "abc")), \ - mock.patch.object(f, "parse_fbneo_source_tree", return_value={}): - with self.assertRaises(RuntimeError): - f.fetch_and_cache(force=True) + mock.patch.object(f, "parse_fbneo_source_tree", return_value={}), self.assertRaises(RuntimeError): + f.fetch_and_cache(force=True) self.assertFalse(cache.exists()) def test_fbneo_does_not_serve_an_empty_cache(self): - from scraper import fbneo_hash_scraper as f # noqa: PLC0415 + from scraper import fbneo_hash_scraper as f with tempfile.TemporaryDirectory() as tmp: cache = Path(tmp) / "fbneo-hashes.json" @@ -1083,7 +1079,7 @@ class EmptyScrapeWritesNothing(unittest.TestCase): the committed platform file stays as it was.""" def _run(self, scraper_class, output: Path) -> int: - from scraper.base_scraper import scraper_cli # noqa: PLC0415 + from scraper.base_scraper import scraper_cli argv = ["scraper", "-o", str(output)] with mock.patch.object(sys, "argv", argv), \ @@ -1131,7 +1127,7 @@ class EmptyScrapeWritesNothing(unittest.TestCase): archive = RetroPiePackageList._archive( {"scriptmodules/supplementary/autostart.sh": 'rp_module_id="autostart"\n'} ) - from scraper.retropie_scraper import Scraper # noqa: PLC0415 + from scraper.retropie_scraper import Scraper scraper = Scraper(url="https://codeload.github.com/RetroPie/RetroPie-Setup/tar.gz/" + "0" * 40) with self.assertRaises(ValueError): diff --git a/tests/test_site_agents.py b/tests/test_site_agents.py index dbbbf4eb2..1dc4fbe21 100644 --- a/tests/test_site_agents.py +++ b/tests/test_site_agents.py @@ -56,7 +56,7 @@ class TheGuideDrivesTheInstaller(unittest.TestCase): fact is held to install.py, so the guide cannot drift from it.""" def setUp(self) -> None: - import generate_installer_doc # noqa: PLC0415 + import generate_installer_doc self.doc = generate_installer_doc self.text = siteagents.llms_txt([("retroarch", "RetroArch")]) @@ -72,7 +72,7 @@ class TheGuideDrivesTheInstaller(unittest.TestCase): self.assertEqual(listed, in_table) def test_the_event_schema_is_the_installers(self) -> None: - import json # noqa: PLC0415 + import json self.assertEqual(siteagents.EVENT_SCHEMA, self.doc._install.EVENT_SCHEMA) schema = json.loads((REPO_ROOT / "schemas" / "install-events.schema.json").read_text(encoding="utf-8")) @@ -104,7 +104,7 @@ class TheSkillIsAnAgentSkill(unittest.TestCase): plain Markdown entry): the setup steps are published as one.""" def test_front_matter_then_instructions(self) -> None: - import yaml # noqa: PLC0415 + import yaml text = siteagents.skill_md() head, _, body = text.removeprefix("---\n").partition("\n---\n") @@ -147,7 +147,7 @@ class EveryPageHasAMarkdownCopy(unittest.TestCase): self.assertIn("markdownCopies,", config) def test_a_page_keeps_its_commands_under_their_system(self) -> None: - import site_markdown # noqa: PLC0415 + import site_markdown html = ('

Demo

' '

Run it here.

' diff --git a/tests/test_site_bootstrap.py b/tests/test_site_bootstrap.py index b4ed3814d..18f6b8d4e 100644 --- a/tests/test_site_bootstrap.py +++ b/tests/test_site_bootstrap.py @@ -132,7 +132,7 @@ class ServedCopies(unittest.TestCase): sitebootstrap.served_text(name, root, self.commit) def test_deploy_site_checks_the_copies_before_it_publishes(self): - import yaml # noqa: PLC0415 + import yaml steps = yaml.safe_load((REPO_ROOT / ".github/workflows/deploy-site.yml").read_text( encoding="utf-8"))["jobs"]["build"]["steps"] diff --git a/tests/test_site_components.py b/tests/test_site_components.py index e89ddceb6..fadffdc57 100644 --- a/tests/test_site_components.py +++ b/tests/test_site_components.py @@ -326,7 +326,7 @@ class TitleLogoOnAPlate(unittest.TestCase): def test_a_setup_with_no_logo_gets_its_initials(self): # Every setup has a logo today: the fallback is read where it is # written, the tile's and the title's. - import sitemarkup # noqa: PLC0415 + import sitemarkup self.assertIn('data-initials="MM" aria-hidden="true">', sitemarkup._tile_mark("MyMinUI", "")) component = _read(REPO_ROOT / "website" / "src" / "components" / "PageTitle.astro") diff --git a/tests/test_site_copy.py b/tests/test_site_copy.py index 999a4503b..066a52b8c 100644 --- a/tests/test_site_copy.py +++ b/tests/test_site_copy.py @@ -14,7 +14,6 @@ from __future__ import annotations import tests # noqa: F401 offline, scratch under tmp/, the suite's own cache -import os import re import statistics import sys diff --git a/tests/test_site_demo.py b/tests/test_site_demo.py index 5ee81e0f5..2184dc3dc 100644 --- a/tests/test_site_demo.py +++ b/tests/test_site_demo.py @@ -118,7 +118,7 @@ class TheTapeAndTheDriverAgree(unittest.TestCase): self.assertEqual(variant.mount, "/roms") def test_the_command_typed_is_the_one_the_pages_give(self): - from siteguides import install_command # noqa: PLC0415 + from siteguides import install_command self.assertIn(f'Type "{install_command("sh", "--for-games")}"\n', self.tape) @@ -194,7 +194,7 @@ def _tab_bodies(markdown: str) -> dict[str, str]: class TheTwoPagesShowIt(unittest.TestCase): def test_home_shows_the_terminal_recording(self): - import generate_site # noqa: PLC0415 + import generate_site tag = generate_site.install_demo()[0] self.assertIn(f'description="{generate_readme.demo_description()}"', tag) @@ -204,7 +204,7 @@ class TheTwoPagesShowIt(unittest.TestCase): self.assertIn("*install_demo(),", body) def test_each_tab_of_get_your_files_shows_its_variant(self): - import generate_site # noqa: PLC0415 + import generate_site tabs = _tab_bodies(generate_site.generate_which_pack()) expected = {"Windows": None, "macOS": "default", "Linux": "default", @@ -226,7 +226,7 @@ class TheTwoPagesShowIt(unittest.TestCase): self.assertEqual(page.count(" tuple[str, ...]: - import generate_site # noqa: PLC0415 + import generate_site return generate_site.DEMO_ASSETS diff --git a/tests/test_site_density_cards.py b/tests/test_site_density_cards.py index 969f429b4..cf8ebfea6 100644 --- a/tests/test_site_density_cards.py +++ b/tests/test_site_density_cards.py @@ -24,7 +24,6 @@ sys.path.insert(0, str(REPO_ROOT / "scripts")) import generate_site as gs # noqa: E402 import sitemarkup as markup # noqa: E402 -from cross_reference import FileConsumers # noqa: E402 DIST = REPO_ROOT / "website" / "dist" SITE_TS = REPO_ROOT / "website" / "src" / "scripts" / "site.ts" diff --git a/tests/test_site_emulators.py b/tests/test_site_emulators.py index d62af8b64..daa07519e 100644 --- a/tests/test_site_emulators.py +++ b/tests/test_site_emulators.py @@ -57,7 +57,7 @@ def _profile(name: str) -> dict: member's required from its groups (DuckStation's ps-bios), which the raw YAML no longer writes on the files.""" if not _LOADED: - from common import load_emulator_profiles # noqa: PLC0415 + from common import load_emulator_profiles _LOADED.update(load_emulator_profiles(str(REPO_ROOT / "emulators"), skip_aliases=False)) return _LOADED[name] @@ -809,7 +809,7 @@ class AnEmulatorPageNamesItsSetups(unittest.TestCase): self.assertEqual(gs.emulator_setups(coverages, profiles)["handy"], ["a", "b"]) def test_the_page_names_them(self): - from tests import sitepages # noqa: PLC0415 + from tests import sitepages sitepages.require() text = sitepages.page("emulators/handy.md").read_text(encoding="utf-8") diff --git a/tests/test_site_entry.py b/tests/test_site_entry.py index a3da33bc1..1fbfb1a1a 100644 --- a/tests/test_site_entry.py +++ b/tests/test_site_entry.py @@ -1107,7 +1107,7 @@ class TheSiteSaysWhatTheInstallerShows(unittest.TestCase): self.assertNotIn("offers to install everything or to choose systems", readme) source = (REPO_ROOT / "scripts" / "generate_readme.py").read_text(encoding="utf-8") self.assertIn("_installer_words().TUI_SYSTEMS_ROW", source) - import generate_installer_doc # noqa: PLC0415 + import generate_installer_doc page = (REPO_ROOT / "wiki" / "installer.md").read_text(encoding="utf-8") self.assertIn(generate_installer_doc.line_menu(), page) diff --git a/tests/test_site_exports.py b/tests/test_site_exports.py index bce8a24f3..df9562bce 100644 --- a/tests/test_site_exports.py +++ b/tests/test_site_exports.py @@ -187,9 +187,9 @@ class SiteReferenceContracts(unittest.TestCase): self.assertNotIn("\n #if FEATURE", rendered) def test_browser_titles_distinguish_emulators_from_system_pages(self): - from unittest import mock # noqa: PLC0415 + from unittest import mock - import generate_site # noqa: PLC0415 + import generate_site pages = {"systems/qemu.md": {}, "emulators/qemu.md": {"hasPart": [{"name": "a"}]}} with mock.patch.dict(generate_site.PAGE_DATA, pages, clear=True): @@ -214,7 +214,7 @@ class SiteReferenceContracts(unittest.TestCase): # Every reference resolves against the catalog's own URL, as an # RFC 3986 client resolves it: the url was relative to the site root # and the schema to api/v1/, so neither base resolved both. - import urllib.parse # noqa: PLC0415 + import urllib.parse site = "https://example.org/site/" base = site + "api/v1/catalog.json" @@ -309,7 +309,7 @@ class AnEmulatorPageNamesItsRevision(unittest.TestCase): refers to sat in the YAML alone, for 178 profiles.""" def test_each_repository_links_its_pinned_commit(self): - import generate_site # noqa: PLC0415 + import generate_site profile = { "emulator": "Caprice32", "type": "libretro", @@ -334,7 +334,7 @@ class APlatformPageSaysWhereEachFileGoes(unittest.TestCase): goes to GC/USA, GC/EUR or GC/JAP.""" def test_same_named_files_show_their_destinations(self): - import generate_site # noqa: PLC0415 + import generate_site regions = ("USA", "EUR", "JAP") declared = [{"name": "IPL.bin", "destination": f"dolphin-emu/Sys/GC/{r}/IPL.bin", @@ -354,9 +354,9 @@ class AVariantShowsWhoPinsIt(unittest.TestCase): Batocera and RetroBat pin named no platform.""" def test_the_variant_card_names_its_readers(self): - import types # noqa: PLC0415 + import types - import generate_site # noqa: PLC0415 + import generate_site primary = {"name": "advision.zip", "path": "bios/Entex/Adventure Vision/advision.zip", "sha1": "a" * 40, "md5": "b" * 32, "size": 3000} @@ -542,7 +542,7 @@ class AVersionPerBuildReadsAsVersions(unittest.TestCase): """MesenCE's page showed {'standalone': '2.2.1', 'libretro': '2.0.0'}.""" def test_each_build_is_named(self): - from generate_site import generate_emulator_page # noqa: PLC0415 + from generate_site import generate_emulator_page page = generate_emulator_page( "mesence", @@ -560,7 +560,7 @@ class EmulatorPartsCarryTheirIdentity(unittest.TestCase): no part the url of its card.""" def test_identifiers_members_and_url(self): - from generate_site import emulator_file_anchors, emulator_structured_data # noqa: PLC0415 + from generate_site import emulator_file_anchors, emulator_structured_data files = [ {"name": "BS-X.bin", "sha256": "aa,bb"}, @@ -582,9 +582,9 @@ class OnlyAPinnedProfileClaimsAPin(unittest.TestCase): """Redream, with no revision at all, was described as source-pinned.""" def test_the_description_follows_the_pin(self): - from unittest import mock # noqa: PLC0415 + from unittest import mock - import generate_site # noqa: PLC0415 + import generate_site pages = { "emulators/pinned.md": {"about": {"version": "a" * 40}}, @@ -603,7 +603,7 @@ class ADataDirectorySaysWhatItIs(unittest.TestCase): @mock.patch("sitesources.tree_holds", lambda *_args: True) # a path the record confirms def test_description_origin_mode_and_source(self): - from generate_site import generate_emulator_page # noqa: PLC0415 + from generate_site import generate_emulator_page profile = { "emulator": "Cemu", "type": "standalone + libretro", "systems": [], @@ -627,7 +627,7 @@ class APlatformPageNamesTheFileItTranscribes(unittest.TestCase): batocera-systems revision every md5 on it comes from.""" def test_pinned_and_moving_sources(self): - import generate_site # noqa: PLC0415 + import generate_site def page(source: str) -> str: cov = {"platform": "P", "config": {"source": source, "systems": {}}, @@ -650,10 +650,10 @@ class APerCoreDocumentValidates(unittest.TestCase): def test_shape(self): try: - import jsonschema # noqa: PLC0415 + import jsonschema except ImportError: self.skipTest("jsonschema is not installed") - import yaml # noqa: PLC0415 + import yaml root = Path(__file__).resolve().parents[1] source = (root / "scripts" / "generate_site.py").read_text(encoding="utf-8") @@ -679,10 +679,10 @@ class AHashFindsEveryPageThatNamesIt(unittest.TestCase): and 335 of its 337 zipped_file entries were unreachable that way.""" import json as _json - import generate_site # noqa: PLC0415 - from common import load_platform_config # noqa: PLC0415 - from cross_reference import FileConsumers # noqa: PLC0415 - from ziptools import build_zip_contents_index # noqa: PLC0415 + import generate_site + from common import load_platform_config + from cross_reference import FileConsumers + from ziptools import build_zip_contents_index root = Path(__file__).resolve().parents[1] db = _json.loads((root / "database.json").read_text(encoding="utf-8")) @@ -712,7 +712,7 @@ class AHashFindsEveryPageThatNamesIt(unittest.TestCase): import tempfile import zlib - import generate_site # noqa: PLC0415 + import generate_site body = b"approved inis\n" sha1 = hashlib.sha1(body).hexdigest() @@ -740,7 +740,7 @@ class AHashFindsEveryPageThatNamesIt(unittest.TestCase): import json as _json import tempfile - import generate_site # noqa: PLC0415 + import generate_site sha1 = "ab" * 20 md5 = "490f666e1afb15b7362b406ed1cea246" @@ -794,9 +794,9 @@ class AnArchiveMemberIsFoundByItsCrc(unittest.TestCase): 33,403.""" def test_each_member_is_a_record_leading_to_its_archive(self): - import zipfile # noqa: PLC0415 + import zipfile - import generate_site # noqa: PLC0415 + import generate_site with tempfile.TemporaryDirectory(dir=Path(__file__).resolve().parents[1] / "tmp") as tmp: root = Path(tmp) @@ -810,7 +810,7 @@ class AnArchiveMemberIsFoundByItsCrc(unittest.TestCase): plain = generate_site._archive_member_records( {"name": "a.bin", "path": "bios/a.bin"}, "cd" * 20, "/retrobios/y/", root) self.assertEqual(plain, []) - import zlib # noqa: PLC0415 + import zlib self.assertEqual(records, [ {"value": f"{zlib.crc32(b'rom'):08x}", "algorithm": "crc32", "layer": "archive-member", @@ -820,9 +820,9 @@ class AnArchiveMemberIsFoundByItsCrc(unittest.TestCase): ]) def test_the_lookup_and_the_schema_carry_the_layer(self): - import json as _json # noqa: PLC0415 + import json as _json - import generate_site # noqa: PLC0415 + import generate_site source = Path(generate_site.__file__).read_text(encoding="utf-8") self.assertIn("records += _archive_member_records(entry, sha1, item[\"url\"])", source) @@ -840,7 +840,7 @@ class AWantedDumpIsFoundByItsHash(unittest.TestCase): the site knows has it.""" def test_each_hash_of_a_wanted_row_is_a_record(self): - import generate_site # noqa: PLC0415 + import generate_site row = {"catalog": "redump", "dat": "Sony - PlayStation 2 - BIOS Images", "name": "ps2-dvd-212k.bin", "description": "", "size": "4194304", @@ -856,9 +856,9 @@ class AWantedDumpIsFoundByItsHash(unittest.TestCase): ]) def test_the_schema_and_the_page_carry_the_layer(self): - import json as _json # noqa: PLC0415 + import json as _json - import generate_site # noqa: PLC0415 + import generate_site root = Path(__file__).resolve().parents[1] schema = _json.loads((root / "schemas" / "site-api-envelope.schema.json").read_text()) @@ -875,9 +875,9 @@ class AMovedPartCardReachesItsPage(unittest.TestCase): site.js redirected only sha1- ids.""" def test_a_part_page_sends_a_missing_card_to_the_emulator_page(self): - import re as _re # noqa: PLC0415 + import re as _re - import generate_site # noqa: PLC0415 + import generate_site script = (Path(__file__).resolve().parents[1] / "website" / "src" / "scripts" / "site.ts").read_text(encoding="utf-8") @@ -899,7 +899,7 @@ class AFileHasAnAddressByContent(unittest.TestCase): was not.""" def test_index_page_and_resolver(self): - import generate_site # noqa: PLC0415 + import generate_site db = {"files": { "ab" * 20: {"path": "bios/Roland/mt32-roms/mt32_control.rom"}, @@ -914,7 +914,7 @@ class AFileHasAnAddressByContent(unittest.TestCase): / "site.ts").read_text() self.assertIn("api/v1/lookup/", script) self.assertIn("params.has('sha1')", script) - from cross_reference import FileConsumers # noqa: PLC0415 + from cross_reference import FileConsumers card = "\n".join(generate_site._system_file_card( {"name": "x.rom", "sha1": "ab" * 20, "size": 1}, FileConsumers({"files": {}}), @@ -1159,7 +1159,7 @@ class TheOneLinerIsWhereUsersLand(unittest.TestCase): options, and the platform and system pages offered only ZIP parts.""" def test_download_page(self): - import generate_site # noqa: PLC0415 + import generate_site page = generate_site.generate_which_pack() self.assertIn("Android (Termux", page) @@ -1167,8 +1167,8 @@ class TheOneLinerIsWhereUsersLand(unittest.TestCase): self.assertIn("--platform retroarch --dest", page) def test_platform_and_system_pages(self): - import generate_site # noqa: PLC0415 - from cross_reference import FileConsumers # noqa: PLC0415 + import generate_site + from cross_reference import FileConsumers cov = {"platform": "Batocera", "mode": "md5", "present": 0, "total": 0, "verified": 0, "missing": 0, "details": [], "config": {"systems": {}}} @@ -1193,8 +1193,8 @@ class TheOneLinerIsWhereUsersLand(unittest.TestCase): self.assertIn("--platform batocera --system msx1", page) def test_a_system_is_offered_only_where_the_manifest_records_it(self): - import generate_site # noqa: PLC0415 - import siterender # noqa: PLC0415 + import generate_site + import siterender saved = dict(siterender._system_page_map) self.addCleanup(siterender.set_system_page_map, saved) @@ -1210,7 +1210,7 @@ class TheGapPageOpensOnCounts(unittest.TestCase): for 5,437 of 5,438 files and "Missing 0", above a table of red cells.""" def test_every_count_is_said(self): - import generate_site # noqa: PLC0415 + import generate_site text = generate_site._platform_lists_sentence(5438, 5437, 1, 0) self.assertIn("Of the 5,438 files", text) @@ -1231,7 +1231,7 @@ class WhichPackDescribesNoPlatformByOpinion(unittest.TestCase): def test_no_ranking_words(self): import re - import generate_site # noqa: PLC0415 + import generate_site page = generate_site.generate_which_pack() rows = [line for line in page.splitlines() if line.startswith("| ")] @@ -1250,8 +1250,8 @@ class EveryPageLinksItsOwnData(unittest.TestCase): it. A system page linked nothing either.""" def test_platform_and_system_documents(self): - import generate_site # noqa: PLC0415 - from cross_reference import FileConsumers # noqa: PLC0415 + import generate_site + from cross_reference import FileConsumers cov = {"platform": "Batocera", "mode": "md5", "present": 0, "total": 0, "verified": 0, "missing": 0, "details": [], "config": {"systems": {}}} @@ -1273,7 +1273,7 @@ class EveryPageLinksItsOwnData(unittest.TestCase): document = json.loads(path.read_text()) self.assertEqual(document["count"], 1) try: - import jsonschema # noqa: PLC0415 + import jsonschema except ImportError: return root = Path(__file__).resolve().parents[1] diff --git a/tests/test_site_funnel.py b/tests/test_site_funnel.py index 80a38ba87..3ebef94c9 100644 --- a/tests/test_site_funnel.py +++ b/tests/test_site_funnel.py @@ -10,7 +10,6 @@ from __future__ import annotations import tests # noqa: F401 offline, scratch under tmp/, the suite's own cache import contextlib -import os import re import sys import tempfile @@ -213,7 +212,7 @@ class DeepLinksCarryALabel(unittest.TestCase): ANSWERS = ("/retrobios/wiki/technical-faq/#which-mame-version-do-the-arcade-bios-sets-match",) def test_start_and_setup_pages(self): - import sitestarlight # noqa: PLC0415 + import sitestarlight pages = _docs_pages() levels = {page: _level(page) for page in pages} diff --git a/tests/test_site_handheld.py b/tests/test_site_handheld.py index ae81d0cd6..42ef85b2d 100644 --- a/tests/test_site_handheld.py +++ b/tests/test_site_handheld.py @@ -33,7 +33,7 @@ PLATFORMS = str(REPO_ROOT / "platforms") def _pages() -> dict[str, str]: """Every page that carries a launcher, by site path.""" - import generate_site # noqa: PLC0415 + import generate_site with contextlib.chdir(REPO_ROOT): pages = {f"get/{key}.md": generate_site.generate_get_page(key) @@ -105,7 +105,7 @@ class WhereEachSystemFindsItsFile(unittest.TestCase): def test_the_group_page_sits_with_the_handheld_guide(self): """It shares the guide's name, so the sidebar files it with it, and the guide a muOS or ArkOS owner lands on links it.""" - import generate_site # noqa: PLC0415 + import generate_site guide = generate_site.HANDHELD_GUIDE self.assertEqual(sitehandheld.GROUP_PAGE, guide.page) diff --git a/tests/test_site_images.py b/tests/test_site_images.py index ee0cb5355..a0f54a8c9 100644 --- a/tests/test_site_images.py +++ b/tests/test_site_images.py @@ -202,7 +202,7 @@ class SharingCards(unittest.TestCase): ET.fromstring(sitediagrams.og_card_svg(section, mark)) def test_the_template_names_every_section(self): - import sitestarlight # noqa: PLC0415 + import sitestarlight named = {sitestarlight.og_section("index.md", "")} | { sitestarlight.og_section("wiki/page.md", level) diff --git a/tests/test_site_insights.py b/tests/test_site_insights.py index ac0fe71c8..66285710b 100644 --- a/tests/test_site_insights.py +++ b/tests/test_site_insights.py @@ -10,7 +10,7 @@ from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "scripts")) -import site_insights as si # noqa: E402 +import site_insights as si PAGE = "https://abdess.github.io/retrobios/emulators/mgba/" diff --git a/tests/test_site_integration.py b/tests/test_site_integration.py index 589ca9fc7..d49486354 100644 --- a/tests/test_site_integration.py +++ b/tests/test_site_integration.py @@ -88,7 +88,7 @@ class PlatformLogos(unittest.TestCase): self.assertTrue(self.registry["minui"]["logo_flip"]) def test_every_logo_copy_has_a_registry_or_tile_logo(self): - from siteguides import GROUP_TILES # noqa: PLC0415 + from siteguides import GROUP_TILES tiles = {re.sub(r"[^a-z0-9]+", "-", tile.name.lower()).strip("-"): tile.logo for group in GROUP_TILES.values() for tile in group} @@ -120,7 +120,7 @@ class NodeCompileCache(unittest.TestCase): class SourcePathsFreshness(unittest.TestCase): def test_the_committed_record_is_current(self): - from common import load_emulator_profiles # noqa: PLC0415 + from common import load_emulator_profiles profiles = load_emulator_profiles(str(REPO_ROOT / "emulators"), skip_aliases=False) finding = check_freshness.check_source_paths(profiles) @@ -129,7 +129,7 @@ class SourcePathsFreshness(unittest.TestCase): def test_a_recorded_build_file_tree_is_pinned(self): """The record holds the platform trees pin_build reads at a commit, and the check called them orphaned.""" - import sitesources # noqa: PLC0415 + import sitesources pin = "a" * 40 profile = {"pin_build": [{"repo": "https://github.com/o/r", "revision": pin, @@ -152,7 +152,7 @@ class SourcePathsFreshness(unittest.TestCase): """fbneo moved to two new pins while fbneo_cps12 kept the old ones: no recorded tree was orphaned, so the check said OK and 174 citations stayed unlinked.""" - import sitesources # noqa: PLC0415 + import sitesources profile = _profile("geolith") trees = [sitesources.tree_key(r, p) for r, p in sitesources.profile_trees(profile)] @@ -170,7 +170,7 @@ class SourcePathsFreshness(unittest.TestCase): self.assertIn("1 pinned trees not recorded", finding.detail) def test_a_tree_read_with_no_cited_path_is_recorded(self): - import sitesources # noqa: PLC0415 + import sitesources profile = {"source": "https://github.com/o/r", "source_commit": "e" * 40, "files": [{"source_ref": "src/a.c:5"}]} @@ -227,7 +227,7 @@ class FaqInstallsFromWhatYouHold(unittest.TestCase): def test_the_cards_the_interface_finds(self): """Each system the SD card answer names is one install.py tells by its card: a release file (_CARD_RULES) or a card rule.""" - import install # noqa: PLC0415 + import install section = " ".join(self._section("Fill an SD card from a computer?").split()) self.assertIn("The interface finds a muOS, Onion, spruceOS, MinUI, KNULLI, ROCKNIX, Lakka " diff --git a/tests/test_site_nav.py b/tests/test_site_nav.py index fe4b6fefb..cda3ad846 100644 --- a/tests/test_site_nav.py +++ b/tests/test_site_nav.py @@ -475,7 +475,7 @@ def _moved_platform_pages() -> list[Path]: return [] # A guide page sits beside the setups (platforms/linux-handhelds) without # being a list moved off one of them. - from siteguides import HANDHELD_GUIDE # noqa: PLC0415 + from siteguides import HANDHELD_GUIDE guides = {Path(HANDHELD_GUIDE.path).stem} if HANDHELD_GUIDE else set() return [path for path in sorted(folder.glob("*.md*")) diff --git a/tests/test_site_page_text.py b/tests/test_site_page_text.py index 0e3f20e1b..e7f0d3bb9 100644 --- a/tests/test_site_page_text.py +++ b/tests/test_site_page_text.py @@ -44,10 +44,8 @@ PAGES = ("which-pack", "wiki/first-install", "wiki/architecture", "wiki/what-are "wiki/installer", "platforms/retrodeck", "provenance-no-intro", "explore", "index") BLOCKS = frozenset( - "address article aside blockquote caption dd details dialog div dl dt fieldset figcaption " - "figure footer form h1 h2 h3 h4 h5 h6 header hr li main nav ol option p pre section select " - "summary table tbody td tfoot th thead tr ul".split()) -VOID = frozenset("area base br col embed hr img input link meta source track wbr".split()) + ["address", "article", "aside", "blockquote", "caption", "dd", "details", "dialog", "div", "dl", "dt", "fieldset", "figcaption", "figure", "footer", "form", "h1", "h2", "h3", "h4", "h5", "h6", "header", "hr", "li", "main", "nav", "ol", "option", "p", "pre", "section", "select", "summary", "table", "tbody", "td", "tfoot", "th", "thead", "tr", "ul"]) +VOID = frozenset(["area", "base", "br", "col", "embed", "hr", "img", "input", "link", "meta", "source", "track", "wbr"]) # What the stylesheet lays out as its own box beside the text before it: # the markup has to space it, a reader without the stylesheet sees no box. # A
breaks a line on screen only: a copy and textContent join across diff --git a/tests/test_site_picker.py b/tests/test_site_picker.py index d725f57df..1f733d118 100644 --- a/tests/test_site_picker.py +++ b/tests/test_site_picker.py @@ -40,7 +40,7 @@ def picked(data: dict, chosen: set[str]) -> list[str]: class PickerMatchesInstaller(unittest.TestCase): def setUp(self): - import sitestarlight # noqa: PLC0415 + import sitestarlight self.folder = tempfile.TemporaryDirectory(dir=REPO_ROOT / "tmp" if (REPO_ROOT / "tmp").is_dir() else None) self.out = Path(self.folder.name) diff --git a/tests/test_site_reference.py b/tests/test_site_reference.py index ee73024c0..4089072fd 100644 --- a/tests/test_site_reference.py +++ b/tests/test_site_reference.py @@ -603,11 +603,11 @@ class TheContractsValidate(unittest.TestCase): def test_every_contract_validates_against_the_platform_schema(self): try: - from jsonschema import Draft202012Validator # noqa: PLC0415 + from jsonschema import Draft202012Validator except ImportError: self.skipTest("jsonschema is a tooling dependency") - from common import list_registered_platforms, load_platform_config # noqa: PLC0415 + from common import list_registered_platforms, load_platform_config schema = json.loads((REPO_ROOT / "schemas" / "platform.schema.json").read_text()) validator = Draft202012Validator(schema) @@ -634,7 +634,7 @@ class TheContractsValidate(unittest.TestCase): def test_the_built_api_validates(self): try: - from jsonschema import Draft202012Validator # noqa: PLC0415 + from jsonschema import Draft202012Validator except ImportError: self.skipTest("jsonschema is a tooling dependency") @@ -782,7 +782,7 @@ class LookupUrlsResolve(unittest.TestCase): def test_each_record_names_its_system_as_the_pages_do(self): """Find a file opens on "a BIOS file for Sony PlayStation": the name comes from system_name, never built in the browser.""" - from siterender import system_name # noqa: PLC0415 + from siterender import system_name db = {"files": {"ab" * 20: {"path": "bios/Sony/PlayStation/scph5501.bin", "name": "scph5501.bin", "md5": "490f666e1afb15b7362b406ed1cea246"}}} @@ -913,7 +913,7 @@ class SourceLinksGoWhereTheFileIs(unittest.TestCase): tree of its repository holds.""" if not sitesources.TREE_CACHE.is_dir(): raise unittest.SkipTest("no cached tree listings") - from common import load_emulator_profiles # noqa: PLC0415 + from common import load_emulator_profiles link = re.compile(r"\(https://github\.com/([^/]+/[^/]+)/blob/([0-9a-f]{40})/([^#)]+)") checked, wrong = 0, [] @@ -924,7 +924,7 @@ class SourceLinksGoWhereTheFileIs(unittest.TestCase): continue for slug, pin, path in link.findall( sitesources._source_ref_markdown(profile, entry["source_ref"])): - import upstream # noqa: PLC0415 + import upstream repo = upstream.parse_repo(f"https://github.com/{slug}") held = sitesources.tree_holds(repo, pin, urllib.parse.unquote(path)) @@ -1024,7 +1024,7 @@ class TheFolderCheckReadsEmuDecksWhitelist(unittest.TestCase): (api / "emudeck.json").write_text(json.dumps({"items": [{"contract": contract}]})) found = check_platform_folder.check("emudeck", root, api.as_uri() + "/") # The verifier's verdict on the matching entry, file by file. - from verify import verify_entry_md5 # noqa: PLC0415 + from verify import verify_entry_md5 verdicts = {name: verify_entry_md5(contract["systems"]["sony-playstation"]["files"][0], str(root / name))["status"] @@ -1147,7 +1147,7 @@ class SourceLinksOnlyWhereTheFileIs(unittest.TestCase): def test_every_rendered_link_is_recorded(self): record = json.loads(sitesources.SOURCE_PATHS.read_text(encoding="utf-8")) pages = sorted(_built(DOCS / "emulators").rglob("*.md*")) + sorted(DOCS.glob("gaps*.md*")) - import measurement_records # noqa: PLC0415 + import measurement_records # A Tested block links a record line and its data file in this # repository. The records are append-only, so a file a permalink diff --git a/tests/test_site_system_sections.py b/tests/test_site_system_sections.py index 35db064ed..3d1cbe1e2 100644 --- a/tests/test_site_system_sections.py +++ b/tests/test_site_system_sections.py @@ -310,8 +310,8 @@ class AnEntryListingSystemsIsFiledUnderEach(unittest.TestCase): under neither Arcade nor NEC PC-88, and kept on pages it does not serve.""" def test_the_site_reads_the_common_rule(self): - import generate_site as gs # noqa: PLC0415 - from common import entry_system_ids # noqa: PLC0415 + import generate_site as gs + from common import entry_system_ids entry = {"name": "ym2608.zip", "systems": ["arcade", "pc80"]} self.assertEqual(gs._entry_systems("mame", entry), ["arcade", "pc80"]) diff --git a/tests/test_site_systems.py b/tests/test_site_systems.py index db73dacbb..26e20f2c5 100644 --- a/tests/test_site_systems.py +++ b/tests/test_site_systems.py @@ -1258,7 +1258,7 @@ class EachFileDownloadsFromItsCard(unittest.TestCase): fourth of a card's facts.""" def test_the_card_title_holds_the_download(self) -> None: - from cross_reference import FileConsumers # noqa: PLC0415 + from cross_reference import FileConsumers f = _naomi_file("apple2-asoft-auto.rom", "3", "bios/Apple/Apple II/apple2-asoft-auto.rom") title = next(line for line in gs._system_file_card(f, FileConsumers({"files": {}})) diff --git a/tests/test_site_validation.py b/tests/test_site_validation.py index b33ffbf7a..92e3f70bd 100644 --- a/tests/test_site_validation.py +++ b/tests/test_site_validation.py @@ -5,7 +5,6 @@ from __future__ import annotations import tests # noqa: F401 offline, scratch under tmp/, the suite's own cache import json -import os import re import sys import tempfile @@ -376,7 +375,7 @@ class PlatformPagesPrintTheDeclaredCrc32(unittest.TestCase): only its sha1 and md5, so the crc a clrmamepro user pastes found nothing.""" def test_the_rendered_page(self): - from tests import sitepages # noqa: PLC0415 + from tests import sitepages sitepages.require() # The page and the systems moved to pages of their own. diff --git a/tests/test_site_weight.py b/tests/test_site_weight.py index 64ae626b0..2ad5e635c 100644 --- a/tests/test_site_weight.py +++ b/tests/test_site_weight.py @@ -14,7 +14,6 @@ import tests # noqa: F401 offline, scratch under tmp/, the suite's own cache import sys import unittest from pathlib import Path -from types import SimpleNamespace REPO_ROOT = Path(__file__).resolve().parent.parent sys.path.insert(0, str(REPO_ROOT / "scripts")) @@ -155,7 +154,7 @@ class TheTableOfContentsOfACardPageStopsAtLevelTwo(unittest.TestCase): @staticmethod @staticmethod def _contents(rel: str, sections: int): - import yaml # noqa: PLC0415 + import yaml body = "# T\n\n" + "".join(f"## S{i}\n\n### card\n\n" for i in range(sections)) _target, text = sitestarlight.finalize_page( diff --git a/tests/test_slots.py b/tests/test_slots.py index dea3aa25e..45f5ea70b 100644 --- a/tests/test_slots.py +++ b/tests/test_slots.py @@ -14,8 +14,8 @@ from pathlib import Path sys.path.insert(0, str(Path(__file__).resolve().parents[1] / "scripts")) -import slots # noqa: E402 -from slots import Claim, Conflict, arbitrate, format_decision # noqa: E402 +import slots +from slots import Claim, Conflict, arbitrate, format_decision def _db(entries: dict[str, dict]) -> dict: @@ -601,7 +601,7 @@ class TestSelfContradictingDestinations(unittest.TestCase): ) def test_the_database_and_the_arbiter_read_one_rule(self): - import generate_db # noqa: PLC0415 + import generate_db variant = Path("bios/M/C/.variants/aes.zip") self.assertEqual(generate_db._canonical_name(variant), "aes.zip") @@ -951,7 +951,7 @@ class ARecordIsFoundByItsPathOnce(unittest.TestCase): """_accepted_by_all walked all 19 000 records for every path asked.""" def test_the_files_are_walked_once(self): - import slots # noqa: PLC0415 + import slots class Counted(dict): walks = 0 @@ -1000,7 +1000,7 @@ class ACopierHeaderIsNotAnotherImage(unittest.TestCase): the core reads it as the 6d9a73ef image its profile lists.""" def test_headered_file_satisfies_the_profile(self): - import zlib # noqa: PLC0415 + import zlib image = b"S" * 1024 with tempfile.TemporaryDirectory() as tmp: @@ -1036,7 +1036,7 @@ class TheSlotsSummaryClosesTheRun(unittest.TestCase): which it never does.""" def test_order_and_help(self): - import subprocess # noqa: PLC0415 + import subprocess root = Path(__file__).resolve().parents[1] if not (root / "database.json").exists(): diff --git a/tests/test_system_pack_extras.py b/tests/test_system_pack_extras.py index 069844ee0..c9cc3b5d0 100644 --- a/tests/test_system_pack_extras.py +++ b/tests/test_system_pack_extras.py @@ -33,7 +33,7 @@ class SystemExtras(unittest.TestCase): """One extra stands per destination and the other cores' claims ride on it. Their systems are the file's systems too: narrowed to one of them, pack and installer both keep the file the core reads.""" - from manifestselect import SelectionIndex # noqa: PLC0415 + from manifestselect import SelectionIndex extras = [{ "name": "floppy.wav", "destination": "mame/samples/floppy.wav", diff --git a/tests/test_system_selection.py b/tests/test_system_selection.py index 96c5ab1ec..08af24ae4 100644 --- a/tests/test_system_selection.py +++ b/tests/test_system_selection.py @@ -46,8 +46,8 @@ class SpellingsAgree(unittest.TestCase): class TheListingCountsLikeTheSelection(unittest.TestCase): def test_one_system_is_listed_once_with_every_profile(self): - import contextlib # noqa: PLC0415 - import io # noqa: PLC0415 + import contextlib + import io out = io.StringIO() with contextlib.redirect_stdout(out): @@ -135,7 +135,7 @@ class AMistypedPlatformIsNamed(unittest.TestCase): def test_the_names_the_site_prints_are_accepted(self): """`--platform RetroArch` and `--platform "MiSTer FPGA"` were refused by verify and generate_pack while install.py took them.""" - from common import platform_arg # noqa: PLC0415 + from common import platform_arg previous = os.getcwd() os.chdir(REPO_ROOT) @@ -576,9 +576,9 @@ class EmulatorVerifyReadsNoArchiveItDoesNotNeed(unittest.TestCase): the 24 seconds of a run.""" def test_the_member_index_is_not_built(self): - from unittest import mock # noqa: PLC0415 + from unittest import mock - import verify # noqa: PLC0415 + import verify if not (REPO_ROOT / "database.json").exists(): self.skipTest("database.json is not generated") @@ -595,7 +595,7 @@ class CoverageWithoutProfilesMatchesTheCli(unittest.TestCase): a neocdz.zip discrepancy the pack and the CLI do not have.""" def test_omitting_profiles_gives_the_same_report(self): - import verify # noqa: PLC0415 + import verify if not (REPO_ROOT / "database.json").exists(): self.skipTest("database.json is not generated") diff --git a/tests/test_target_names.py b/tests/test_target_names.py index c3939fdde..2b9a2408a 100644 --- a/tests/test_target_names.py +++ b/tests/test_target_names.py @@ -28,9 +28,9 @@ class EveryBuildbotCoreIsNamed(unittest.TestCase): their libretro build from all_libretro.""" def test_retroarch_names_every_buildbot_core(self): - import yaml # noqa: PLC0415 + import yaml - from common import ( # noqa: PLC0415 + from common import ( load_emulator_profiles, load_platform_config, load_target_config, @@ -73,7 +73,7 @@ class AliasesResolveToOneName(unittest.TestCase): def test_linux_on_arm_and_32_bit_x86_is_a_target(self): """The buildbot's linux/aarch64 (232 cores) and linux/x86 builds were not scraped: --target refused RetroArch on Raspberry Pi OS 64-bit.""" - import yaml # noqa: PLC0415 + import yaml platforms = str(REPO_ROOT / "platforms") targets = yaml.safe_load((REPO_ROOT / "platforms" / "targets" / "retroarch.yml") @@ -116,10 +116,10 @@ class EachPlatformNamesTheTargetItsOwnWay(unittest.TestCase): answered SKIP for a pack the --all build had written.""" def test_the_all_run_and_the_platform_run_agree(self): - import contextlib # noqa: PLC0415 - import io # noqa: PLC0415 + import contextlib + import io - import generate_pack # noqa: PLC0415 + import generate_pack platforms_dir = str(REPO_ROOT / "platforms") with contextlib.redirect_stdout(io.StringIO()): @@ -145,7 +145,7 @@ class OneTruthModelPerTarget(unittest.TestCase): rebuilt the same slug by hand to find it.""" def test_aliases_share_a_directory(self): - from common import truth_target_dir # noqa: PLC0415 + from common import truth_target_dir platforms = str(REPO_ROOT / "platforms") dirs = { @@ -174,7 +174,7 @@ class TheListingCountsWhatTheFilterUses(unittest.TestCase): filters on 187 once _overrides.yml removes machine variants and launchers.""" def test_every_listed_count_is_the_filtered_set(self): - from common import list_available_targets, load_target_config # noqa: PLC0415 + from common import list_available_targets, load_target_config platforms = str(REPO_ROOT / "platforms") checked = 0 @@ -195,11 +195,11 @@ class ASingleTargetFiltersNothing(unittest.TestCase): from a pack the user had only asked to name.""" def test_the_only_target_resolves_every_declared_core(self): - import glob # noqa: PLC0415 + import glob - import yaml # noqa: PLC0415 + import yaml - from common import ( # noqa: PLC0415 + from common import ( load_emulator_profiles, load_platform_config, load_target_config, @@ -234,7 +234,7 @@ class PublishedListsAreNotNarrowed(unittest.TestCase): self.assertNotIn('manifest_cmd.extend(["--target"', pipeline) def test_every_install_list_is_a_whole_platform(self): - import json # noqa: PLC0415 + import json for path in sorted((REPO_ROOT / "install").glob("*.json")): data = json.loads(path.read_text(encoding="utf-8")) diff --git a/tests/test_target_scrapers.py b/tests/test_target_scrapers.py index 0a1bc8848..3a7a203eb 100644 --- a/tests/test_target_scrapers.py +++ b/tests/test_target_scrapers.py @@ -164,7 +164,7 @@ class BatoceraKconfig(unittest.TestCase): ) def active(self, board: set[str]) -> frozenset[str]: - from scraper.targets.batocera_targets_scraper import ( # noqa: PLC0415 + from scraper.targets.batocera_targets_scraper import ( _active_symbols, _parse_meta_flags, _parse_owned_selects, @@ -208,7 +208,7 @@ class BatoceraDerivedFlags(unittest.TestCase): ) def active(self, board: set[str]) -> frozenset[str]: - from scraper.targets.batocera_targets_scraper import ( # noqa: PLC0415 + from scraper.targets.batocera_targets_scraper import ( _active_symbols, _parse_meta_flags, _parse_owned_selects, @@ -221,7 +221,7 @@ class BatoceraDerivedFlags(unittest.TestCase): ) def test_a_continued_condition_keeps_its_later_lines(self): - from scraper.targets.batocera_targets_scraper import ( # noqa: PLC0415 + from scraper.targets.batocera_targets_scraper import ( _parse_meta_flags, ) @@ -254,7 +254,7 @@ class CoreDownloaderReach(unittest.TestCase): those runs any core of the buildbot list, an aarch64 one none.""" def test_each_architecture_reads_its_buildbot_list(self): - from scraper.targets.batocera_targets_scraper import buildbot_target # noqa: PLC0415 + from scraper.targets.batocera_targets_scraper import buildbot_target self.assertEqual(buildbot_target({"BR2_x86_64"}), "linux-x86_64") self.assertEqual(buildbot_target({"BR2_arm", "BR2_ARM_CPU_ARMV7A"}), "linux-armhf") @@ -263,7 +263,7 @@ class CoreDownloaderReach(unittest.TestCase): self.assertIsNone(buildbot_target({"BR2_aarch64"})) def test_a_build_or_a_blank_url_turns_it_off(self): - from scraper.targets.batocera_targets_scraper import downloader_disabled # noqa: PLC0415 + from scraper.targets.batocera_targets_scraper import downloader_disabled self.assertIsNone(downloader_disabled("--enable-networking", { "a/retroarch.cfg": 'menu_show_core_updater = "false"\n'})) @@ -272,7 +272,7 @@ class CoreDownloaderReach(unittest.TestCase): downloader_disabled("", {"a/retroarch.cfg": 'core_updater_buildbot_cores_url = ""\n'}) def test_a_board_that_downloads_gets_the_buildbot_list(self): - from common import load_target_config # noqa: PLC0415 + from common import load_target_config root = str(REPO_ROOT / "platforms") x86 = set(load_target_config("retroarch", "linux-x86_64", root) or ()) @@ -283,9 +283,9 @@ class CoreDownloaderReach(unittest.TestCase): self.assertLessEqual(armhf, set(load_target_config("knulli", "r16", root) or ())) def test_the_platform_names_what_its_boards_install(self): - import yaml # noqa: PLC0415 + import yaml - from common import load_target_config # noqa: PLC0415 + from common import load_target_config root = str(REPO_ROOT / "platforms") for platform in ("batocera", "knulli"): @@ -307,9 +307,9 @@ class CoreDownloaderReach(unittest.TestCase): """Batocera runs amiberry standalone, and its x86_64 boards fetch amiberry_libretro: removing every name the image builds lost the libretro core to the name it shares with the standalone package.""" - from common import DUAL_MODE_PREFIX, resolve_platform_cores, standalone_set # noqa: PLC0415 - from scraper.batocera_scraper import installable_cores # noqa: PLC0415 - from scraper.targets.batocera_targets_scraper import BuildSelection # noqa: PLC0415 + from common import DUAL_MODE_PREFIX, resolve_platform_cores, standalone_set + from scraper.batocera_scraper import installable_cores + from scraper.targets.batocera_targets_scraper import BuildSelection selection = BuildSelection( targets={"x86_64": {"architecture": "x86_64", "cores": [], @@ -341,7 +341,7 @@ class DownloadedCoresReachTheirBoards(unittest.TestCase): @classmethod def setUpClass(cls): - from common import load_emulator_profiles, load_platform_config # noqa: PLC0415 + from common import load_emulator_profiles, load_platform_config cls.profiles = load_emulator_profiles(str(REPO_ROOT / "emulators")) cls.config = load_platform_config("batocera", str(REPO_ROOT / "platforms")) @@ -350,7 +350,7 @@ class DownloadedCoresReachTheirBoards(unittest.TestCase): """Batocera lists higan_sfc_balanced and nside_sfc_balanced, and the buildbot offers the second: reading the first alone dropped the core from x86_64.""" - from common import load_target_config, resolve_platform_cores # noqa: PLC0415 + from common import load_target_config, resolve_platform_cores root = str(REPO_ROOT / "platforms") x86 = load_target_config("batocera", "x86_64", root) @@ -361,7 +361,7 @@ class DownloadedCoresReachTheirBoards(unittest.TestCase): self.assertIn("amiberry-7.1.1-332", resolved) def test_the_list_names_the_boards_of_each_downloaded_core(self): - import generate_pack # noqa: PLC0415 + import generate_pack core_names = {"amiberry": [], "higan_sfc_balanced": ["nside_sfc_balanced"]} boards = generate_pack._downloaded_cores( @@ -428,7 +428,7 @@ class KnulliPerBoard(unittest.TestCase): } def test_each_board_gets_its_own_cores(self): - from scripts.scraper.targets import knulli_targets_scraper # noqa: PLC0415 + from scripts.scraper.targets import knulli_targets_scraper pin = knulli_targets_scraper.Scraper.pinned_revision("knulli") raw = f"https://raw.githubusercontent.com/knulli-cfw/knulli-linux/{pin}/" @@ -533,7 +533,7 @@ class RocknixPerDevice(unittest.TestCase): ) def test_each_device_gets_its_own_cores(self): - from scraper.targets.rocknix_targets_scraper import parse_device_cores # noqa: PLC0415 + from scraper.targets.rocknix_targets_scraper import parse_device_cores libretro, standalone = parse_device_cores(self.PACKAGE_MK, "H700", "aarch64", True) self.assertTrue({"gpsp-lr", "duckstation-lr", "beetle-psx-lr", "81-lr", @@ -549,7 +549,7 @@ class RocknixPerDevice(unittest.TestCase): def test_a_package_names_the_cores_it_installs(self): """vice-lr builds ten EMUTYPEs: read as the package name, vice_x64 and its siblings reached no ROCKNIX device.""" - from scraper.targets.rocknix_targets_scraper import installed_cores # noqa: PLC0415 + from scraper.targets.rocknix_targets_scraper import installed_cores vice = ("makeinstall_target() {\n mkdir -p ${INSTALL}/usr/lib/libretro\n" " cp -a built/vice_x128_libretro.so ${INSTALL}/usr/lib/libretro\n" @@ -581,15 +581,15 @@ class RocknixPerDevice(unittest.TestCase): """vice-standalone answers to vice-sa only, as scummvm-standalone to scummvm-sa: stripped to vice, every targeted pack left them out while the untargeted one, read from the platform scraper, kept them.""" - from scraper.rocknix_scraper import standalone_emulators # noqa: PLC0415 - from scraper.targets.rocknix_targets_scraper import parse_device_cores # noqa: PLC0415 + from scraper.rocknix_scraper import standalone_emulators + from scraper.targets.rocknix_targets_scraper import parse_device_cores _, standalone = parse_device_cores(self.PACKAGE_MK, "SM8550", "aarch64", False) names = set(standalone_emulators(standalone)) self.assertTrue({"aethersx2-sa", "aethersx2", "dolphin-sa", "dolphin"} <= names) def test_a_metapackage_names_the_cores_it_installs(self): - from scraper.targets.rocknix_targets_scraper import metapackage_cores # noqa: PLC0415 + from scraper.targets.rocknix_targets_scraper import metapackage_cores self.assertEqual(metapackage_cores(self.IDTECH, "aarch64"), ["ecwolf-lr", "prboom-lr"]) self.assertEqual(metapackage_cores(self.IDTECH, "x86_64"), @@ -611,8 +611,8 @@ class RecalboxPerBoard(unittest.TestCase): ) def test_a_board_gets_the_cores_its_defconfig_builds(self): - from scraper.recalbox_scraper import board_cores # noqa: PLC0415 - from scraper.targets.recalbox_targets_scraper import ( # noqa: PLC0415 + from scraper.recalbox_scraper import board_cores + from scraper.targets.recalbox_targets_scraper import ( defconfig_arch, enabled_packages, ) @@ -630,7 +630,7 @@ class RecalboxPerBoard(unittest.TestCase): self.assertEqual(defconfig_arch("BR2_aarch64=y\n"), "aarch64") def test_board_sections_read_key_by_key_as_romfs_does(self): - from scraper.recalbox_scraper import board_cores # noqa: PLC0415 + from scraper.recalbox_scraper import board_cores ini = ( "[core.0]\npackage = BR2_PACKAGE_LIBRETRO_GAMBATTE\nemulator = \"libretro\"\n" @@ -820,7 +820,7 @@ class HashScrapersRefuseAnUnknownVersion(unittest.TestCase): and cached it for a day, while the pipeline step still read OK.""" def test_mame_raises(self): - from scripts.scraper import mame_hash_scraper # noqa: PLC0415 + from scripts.scraper import mame_hash_scraper with mock.patch.object(mame_hash_scraper.urllib.request, "urlopen", _refuse), \ self.assertRaises(RuntimeError): diff --git a/tests/test_target_verify.py b/tests/test_target_verify.py index 586c9c7dc..6ca012fcf 100644 --- a/tests/test_target_verify.py +++ b/tests/test_target_verify.py @@ -32,9 +32,8 @@ class CheckReadsTheTargetLikeTheBuild(unittest.TestCase): # Left out of a targeted --all run rather than built unfiltered, and # a run where no platform has the target is refused. with tempfile.TemporaryDirectory() as platforms, \ - contextlib.redirect_stdout(io.StringIO()): - with self.assertRaises(ValueError): - build_target_cores_cache(["recalbox"], "x86_64", platforms, is_all=True) + contextlib.redirect_stdout(io.StringIO()), self.assertRaises(ValueError): + build_target_cores_cache(["recalbox"], "x86_64", platforms, is_all=True) # The build never packs such a platform under the target, so the # check refuses it too instead of reading the full pack. with self.assertRaises(FileNotFoundError): @@ -148,7 +147,7 @@ class ASplitBuildsOnlyTheTargetsSystems(unittest.TestCase): def record(*_a, **kw): if kw.get("system_filter"): asked.append(kw["system_filter"]) - return None + return with tempfile.TemporaryDirectory(dir=REPO_ROOT / "tmp") as out, \ mock.patch.object(generate_pack, "generate_pack", record), \ diff --git a/tests/test_tool_messages.py b/tests/test_tool_messages.py index 394e84cae..21601cd10 100644 --- a/tests/test_tool_messages.py +++ b/tests/test_tool_messages.py @@ -585,7 +585,7 @@ class OneSpellingPerOption(unittest.TestCase): OTHER_MEANING = {("migrate.py", "--target")} def test_every_script_takes_the_short_forms(self): - import ast # noqa: PLC0415 + import ast missing = [] for path in sorted((REPO_ROOT / "scripts").rglob("*.py")): @@ -606,7 +606,7 @@ class OneSpellingPerOption(unittest.TestCase): def test_one_long_name_per_option(self): """arcade_parent_importer took --database where every other script takes --db, and refused `--db database.json`.""" - import ast # noqa: PLC0415 + import ast renamed = {"--database": "--db"} found = [] @@ -646,14 +646,14 @@ class ThePipelineCountsItsRealSteps(unittest.TestCase): the log never printed.""" def test_every_recorded_step_has_a_label(self): - import re # noqa: PLC0415 + import re source = (REPO_ROOT / "scripts" / "pipeline.py").read_text(encoding="utf-8") keys = set(re.findall(r'results\["(\w+)"\] =', source)) self.assertEqual(keys - set(pipeline.STEP_LABELS), set()) def test_a_label_written_out_is_one_of_the_list(self): - import re # noqa: PLC0415 + import re source = (REPO_ROOT / "scripts" / "pipeline.py").read_text(encoding="utf-8") written = re.findall(r'run\([^()]*?, "([^"]+)"\)', source) @@ -666,7 +666,7 @@ class ThePipelineCountsItsRealSteps(unittest.TestCase): def test_no_title_counts_eight_steps(self): """Three print() headers of step 5 still read "5/8" beside the computed "5 consistency check [20/24]".""" - import re # noqa: PLC0415 + import re source = (REPO_ROOT / "scripts" / "pipeline.py").read_text(encoding="utf-8") self.assertEqual(re.findall(r'"[^"\n]*---[^"\n]*\b\d+[a-z]?/\d+\b[^"\n]*"', source), []) @@ -866,9 +866,9 @@ class TheGitHubTokenComesFromGh(unittest.TestCase): run.assert_not_called() def test_every_api_caller_reads_it(self): - import profile_sync # noqa: PLC0415 - import upstream # noqa: PLC0415 - from scraper import base_scraper # noqa: PLC0415 + import profile_sync + import upstream + from scraper import base_scraper with self._gh(): self.assertEqual( @@ -884,7 +884,7 @@ class TheGitHubTokenComesFromGh(unittest.TestCase): profile_sync._check_quota(606, offline=False) def test_another_forge_never_triggers_gh(self): - import upstream # noqa: PLC0415 + import upstream with self._gh() as run: headers = upstream._headers("https://gitlab.com/api/v4/projects/1") @@ -901,7 +901,7 @@ class CitedCommandsRunWhenPasted(unittest.TestCase): CITED = re.compile(r"(?:^|run |with |then |, )([a-z_]+\.py) --[a-z]") def test_no_message_cites_a_bare_script(self): - import ast # noqa: PLC0415 + import ast offenders = [] for path in sorted((REPO_ROOT / "scripts").rglob("*.py")): diff --git a/tests/test_truth_layout.py b/tests/test_truth_layout.py index d319b42f6..31f076c8e 100644 --- a/tests/test_truth_layout.py +++ b/tests/test_truth_layout.py @@ -206,8 +206,8 @@ class DiffAndExportShareOneMismatchRule(unittest.TestCase): ) def test_the_diff_names_what_the_export_corrects(self): - from exporter.baseline import build_native_model # noqa: PLC0415 - from truth import diff_platform_truth # noqa: PLC0415 + from exporter.baseline import build_native_model + from truth import diff_platform_truth for t_hashes, p_hashes in self.CASES: with self.subTest(truth=t_hashes, platform=p_hashes): @@ -327,7 +327,7 @@ class ASizeOutsideARangeIsAnotherFile(unittest.TestCase): def test_two_cores_do_not_merge_across_a_declared_range(self): """bk's 24 KB BASIC10.ROM and oricutron's basic10.rom (max_size 16384) merged into one entry, which took the Oric md5.""" - from truth import _merge_file_into_system # noqa: PLC0415 + from truth import _merge_file_into_system system: dict = {} _merge_file_into_system(system, {"name": "BASIC10.ROM", "size": 24576, diff --git a/tests/test_upstream.py b/tests/test_upstream.py index 9132905be..1b11229a2 100644 --- a/tests/test_upstream.py +++ b/tests/test_upstream.py @@ -293,7 +293,7 @@ class TestFetchRetry(unittest.TestCase): @staticmethod def _limited(retry_after: str | None = None) -> urllib.error.HTTPError: - import email.message # noqa: PLC0415 + import email.message headers = email.message.Message() if retry_after is not None: @@ -327,7 +327,7 @@ class TestFetchRetry(unittest.TestCase): self.assertEqual((self.calls, self.slept), (1, [])) def test_exhausted_github_quota_is_not_waited(self): - import email.message # noqa: PLC0415 + import email.message headers = email.message.Message() headers["X-RateLimit-Remaining"] = "0" diff --git a/tests/test_validate_pr.py b/tests/test_validate_pr.py index 1a0fb66f4..7bb463c82 100644 --- a/tests/test_validate_pr.py +++ b/tests/test_validate_pr.py @@ -123,7 +123,7 @@ class AFileOnlyACoreReadsIsKnown(_Fixture): config - needs manual review".""" def test_the_profiles_that_declare_the_hash_are_named(self): - import hashlib # noqa: PLC0415 + import hashlib emulators = self.tmp / "emulators" emulators.mkdir() @@ -143,7 +143,7 @@ class AFileOnlyACoreReadsIsKnown(_Fixture): def test_a_missing_file_is_told_the_folder_of_its_system(self): """The folder came from platform lists only: a file only a profile declares, absent from the collection, got the generic advice.""" - import hashlib # noqa: PLC0415 + import hashlib held, missing = b"held rom", b"missing rom" emulators = self.tmp / "emulators" @@ -294,8 +294,8 @@ class HashRecognition(_Fixture): def test_a_zip_of_bios_files_is_read_member_by_member(self): """A card's BIOS folder zipped to upload it was hashed as one file, and its contributor was asked where that dump came from.""" - import hashlib # noqa: PLC0415 - import zipfile # noqa: PLC0415 + import hashlib + import zipfile held, declared = b"HELD BIOS", b"DECLARED BIOS" with zipfile.ZipFile(self.tmp / "mybios.zip", "w") as archive: @@ -490,7 +490,7 @@ class ThePlatformsOwnCheckDecides(_Fixture): return validate_pr.load_platform_hashes(str(platforms)) def _zip(self) -> str: - import zipfile # noqa: PLC0415 + import zipfile path = self.tmp / "contrib" / "set.zip" path.parent.mkdir() @@ -502,7 +502,7 @@ class ThePlatformsOwnCheckDecides(_Fixture): return validate_pr.validate_file(path, None, known).to_markdown() def test_a_member_pinned_by_zipped_file(self): - import hashlib # noqa: PLC0415 + import hashlib md5 = hashlib.md5(b"ROM").hexdigest() known = self._platforms( @@ -513,7 +513,7 @@ class ThePlatformsOwnCheckDecides(_Fixture): self.assertNotIn(".variants/", markdown) def test_a_member_digest(self): - from hashing import md5_composite # noqa: PLC0415 + from hashing import md5_composite path = self._zip() known = self._platforms( @@ -522,7 +522,7 @@ class ThePlatformsOwnCheckDecides(_Fixture): self.assertIn("Accepted by the platform's own check: p", self._verdict(path, known)) def test_a_sha256(self): - import hashlib # noqa: PLC0415 + import hashlib path = self._zip() digest = hashlib.sha256((self.tmp / path).read_bytes()).hexdigest() @@ -550,7 +550,7 @@ class FlagsAreAppliedOrRefused(unittest.TestCase): beside --markdown printed JSON and dropped the markdown.""" def _run(self, *argv: str): - import subprocess # noqa: PLC0415 + import subprocess return subprocess.run( [sys.executable, "scripts/validate_pr.py", *argv], cwd=REPO_ROOT, @@ -570,7 +570,7 @@ class FlagsAreAppliedOrRefused(unittest.TestCase): def test_a_failed_file_is_not_reported_new(self): """A path that does not exist came out as "outcome": "new", and a reader listing new contributions announced a BIOS nobody sent.""" - import json # noqa: PLC0415 + import json result = self._run("--json", "bios/nope.bin") report = json.loads(result.stdout) diff --git a/tests/test_validate_pr_flow.py b/tests/test_validate_pr_flow.py index d76259158..fb1d8e3b9 100644 --- a/tests/test_validate_pr_flow.py +++ b/tests/test_validate_pr_flow.py @@ -120,7 +120,7 @@ class OversizedFileAdvice(unittest.TestCase): def test_the_issue_form_is_filled_and_nothing_points_to_the_pr(self): """The link opened an empty form, and the same report said to put the file in the pull request and under bios/.""" - import urllib.parse # noqa: PLC0415 + import urllib.parse path = self.tmp / "big.bin" path.write_bytes(b"x" * 8) diff --git a/tests/test_validated_choice.py b/tests/test_validated_choice.py index 58df7e6a2..26bda65e5 100644 --- a/tests/test_validated_choice.py +++ b/tests/test_validated_choice.py @@ -157,11 +157,11 @@ class ManifestsServeWhatTheCoreAccepts(unittest.TestCase): Nintendo's dump, which Dolphin's check accepts, sat in .variants/.""" def test_no_served_core_file_fails_its_check_beside_a_passing_variant(self): - import json # noqa: PLC0415 + import json - from common import load_emulator_profiles, load_platform_config # noqa: PLC0415 - from generate_pack import _platform_cores # noqa: PLC0415 - from validation import check_file_validation # noqa: PLC0415 + from common import load_emulator_profiles, load_platform_config + from generate_pack import _platform_cores + from validation import check_file_validation manifest_path = REPO_ROOT / "install" / "retroarch.json" if not (REPO_ROOT / "database.json").is_file() or not manifest_path.is_file(): @@ -197,7 +197,7 @@ class EachReaderJudgesWithItsOwnRules(unittest.TestCase): Wii U otp.bin, and the variant search gave Cemu the 3DS file.""" def test_rules_of_another_emulator_do_not_judge(self): - from validation import check_file_validation # noqa: PLC0415 + from validation import check_file_validation index = _build_validation_index({ "azahar": {"files": [{"name": "otp.bin", "path": "sysdata/otp.bin", @@ -212,7 +212,7 @@ class EachReaderJudgesWithItsOwnRules(unittest.TestCase): self.assertIsNotNone(check_file_validation(str(wiiu), "otp.bin", index, tmp, {"azahar"})) def test_one_of_an_emulators_entries_is_enough(self): - from validation import check_file_validation # noqa: PLC0415 + from validation import check_file_validation index = _build_validation_index({"raze": {"files": [ {"name": "SW.GRP", "size": 100, "validation": ["size"]}, @@ -234,8 +234,8 @@ class DolphinForksJudgeTheirOwnDspTable(unittest.TestCase): FREE_V031 = REPO_ROOT / "bios" / "Nintendo" / "GameCube" / "Sys" / "GC" / "dsp_rom.bin" def test_each_fork_accepts_its_own_free_rom(self): - from common import load_emulator_profiles # noqa: PLC0415 - from validation import check_file_validation # noqa: PLC0415 + from common import load_emulator_profiles + from validation import check_file_validation if not self.FREE_V04.is_file() or not self.FREE_V031.is_file(): self.skipTest("free DSP ROMs not present") @@ -292,7 +292,7 @@ class AWarningRejectsNothing(unittest.TestCase): self.assertEqual((chosen, disagreement), (str(good), None)) def test_the_merged_view_rejects_nothing_for_it(self): - from validation import check_file_validation # noqa: PLC0415 + from validation import check_file_validation with tempfile.TemporaryDirectory(dir=REPO_ROOT / "tmp") as tmp: short, _good, _db, index = self._setup(tmp, held_good=False) @@ -347,7 +347,7 @@ class AVersionTakenWithoutACheck(unittest.TestCase): return str(path) def test_the_unchecked_version_accepts_the_copy(self): - from validation import check_file_validation # noqa: PLC0415 + from validation import check_file_validation index = _build_validation_index({"raze": self.RAZE}) with tempfile.TemporaryDirectory(dir=REPO_ROOT / "tmp") as tmp: @@ -356,7 +356,7 @@ class AVersionTakenWithoutACheck(unittest.TestCase): )) def test_the_pack_reads_it_as_an_alternative(self): - import generate_pack # noqa: PLC0415 + import generate_pack fe = {"name": "BLOOD.RFF", "source_profile": "raze", "source_path": "BLOOD.RFF"} with tempfile.TemporaryDirectory(dir=REPO_ROOT / "tmp") as tmp: @@ -365,7 +365,7 @@ class AVersionTakenWithoutACheck(unittest.TestCase): )) def test_a_refusal_names_every_accepted_size(self): - from validation import check_file_validation # noqa: PLC0415 + from validation import check_file_validation checked = {"files": self.RAZE["files"][:2]} index = _build_validation_index({"raze": checked}) diff --git a/tests/test_verify_listing.py b/tests/test_verify_listing.py index 5d6a208f9..19f42d1bc 100644 --- a/tests/test_verify_listing.py +++ b/tests/test_verify_listing.py @@ -58,7 +58,7 @@ class VerifyRefusesWhatAModeDoesNotRead(unittest.TestCase): def test_emulator_mode_reads_the_given_platforms_dir(self): sys.path.insert(0, str(REPO_ROOT / "scripts")) - import verify # noqa: PLC0415 + import verify seen: list[str] = [] @@ -91,7 +91,7 @@ class VerifyAppliesWhatItAccepts(unittest.TestCase): class EmulatorPackReadsThePlatformsDir(unittest.TestCase): def test_the_registry_comes_from_the_given_dir(self): sys.path.insert(0, str(REPO_ROOT / "scripts")) - import generate_pack # noqa: PLC0415 + import generate_pack seen: list[str] = [] @@ -116,11 +116,11 @@ class EmulatorPackReadsThePlatformsDir(unittest.TestCase): class CoreArchivesAreCounted(unittest.TestCase): def test_a_missing_required_bios_zip_is_printed(self): - import contextlib # noqa: PLC0415 - import io # noqa: PLC0415 + import contextlib + import io sys.path.insert(0, str(REPO_ROOT / "scripts")) - import verify # noqa: PLC0415 + import verify result = {"undeclared_files": [ {"name": "neogeo.zip", "category": "bios_zip", "required": True, @@ -136,10 +136,10 @@ class CoreArchivesAreCounted(unittest.TestCase): class ExistenceReportsWhatThePackReports(unittest.TestCase): def test_a_contradicted_hash_is_a_discrepancy(self): """30 RetroArch entries printed DISCREPANCY in the pack, nothing in verify.""" - import tempfile # noqa: PLC0415 + import tempfile sys.path.insert(0, str(REPO_ROOT / "scripts")) - import verify # noqa: PLC0415 + import verify with tempfile.TemporaryDirectory(dir=REPO_ROOT / "tmp") as tmp: path = Path(tmp) / "aes.zip" @@ -155,7 +155,7 @@ class ExistenceReportsWhatThePackReports(unittest.TestCase): """RetroArch, Lakka and RetroPie pages showed no "Served by" line: existence mode returned no path, where the hash modes return one.""" sys.path.insert(0, str(REPO_ROOT / "scripts")) - import verify # noqa: PLC0415 + import verify found = verify.verify_entry_existence({"name": "a.bin"}, "bios/X/Y/a.bin") self.assertEqual(found["path"], "bios/X/Y/a.bin") @@ -199,7 +199,7 @@ class EveryGapCountedIsNamed(unittest.TestCase): import io sys.path.insert(0, str(REPO_ROOT / "scripts")) - import verify # noqa: PLC0415 + import verify result = {"undeclared_files": [ {"name": "opt.rom", "emulator": "core", "required": False, "in_repo": False}, @@ -226,7 +226,7 @@ class BundledGameDataIsNotMissing(unittest.TestCase): import io sys.path.insert(0, str(REPO_ROOT / "scripts")) - import verify # noqa: PLC0415 + import verify result = {"undeclared_files": [ {"name": "abuse.lsp", "emulator": "Abuse", "required": True, @@ -248,11 +248,11 @@ class TheBundledLineSaysWhatItLeavesOut(unittest.TestCase): the required firmware, and nothing said 140 more existed.""" def test_the_hidden_names_are_counted(self): - import contextlib # noqa: PLC0415 - import io # noqa: PLC0415 + import contextlib + import io sys.path.insert(0, str(REPO_ROOT / "scripts")) - import verify # noqa: PLC0415 + import verify result = {"undeclared_files": [ {"name": name, "emulator": "e", "required": required, "in_repo": False, @@ -284,11 +284,11 @@ class TheCheckLineSaysWhatItIs(unittest.TestCase): '[size]' line, nine of them in verify --all.""" def test_the_checks_read_as_the_verbose_line(self): - import contextlib # noqa: PLC0415 - import io # noqa: PLC0415 + import contextlib + import io sys.path.insert(0, str(REPO_ROOT / "scripts")) - import verify # noqa: PLC0415 + import verify entry = {"name": "FBASIC30.ROM", "emulator": "XM7", "checks": ["size"]} with contextlib.redirect_stdout(io.StringIO()) as out: @@ -306,11 +306,11 @@ class CoreCopiesWithoutAGapEntryAreCounted(unittest.TestCase): count.""" def test_the_packed_count_is_printed(self): - import contextlib # noqa: PLC0415 - import io # noqa: PLC0415 + import contextlib + import io sys.path.insert(0, str(REPO_ROOT / "scripts")) - import verify # noqa: PLC0415 + import verify for packed, expected in (({"bios": 6, "game_data": 0}, "Core files: 6 in pack"), ({"bios": 0, "game_data": 3}, "Game data: 3 in pack")): diff --git a/tests/test_version_basis.py b/tests/test_version_basis.py index 55e1bb9af..00ff87a6f 100644 --- a/tests/test_version_basis.py +++ b/tests/test_version_basis.py @@ -132,7 +132,7 @@ class ReadsTheRecordedSourceOffline(unittest.TestCase): return int(exc.code or 0) return 0 - import common # noqa: PLC0415 + import common common._emulator_profiles_cache.clear() self.assertEqual(run(), 0) @@ -304,7 +304,7 @@ class TheWriterKeepsTheDocument(unittest.TestCase): class TheSchemaRefusesPlaceholders(unittest.TestCase): def setUp(self): try: - import jsonschema # noqa: PLC0415 + import jsonschema except ImportError: self.skipTest("jsonschema is not installed") schema = json.loads((ROOT / "schemas" / "emulator.schema.json").read_text()) diff --git a/tests/test_which_pack.py b/tests/test_which_pack.py index 6fd282a40..ed83509df 100644 --- a/tests/test_which_pack.py +++ b/tests/test_which_pack.py @@ -30,8 +30,8 @@ class WhichPackRows(unittest.TestCase): def test_platform_rows_name_their_own_pack(self): """A row links its own get/ page, never another setup's and never a release asset: the asset URL dies with its tag.""" - import generate_site # noqa: PLC0415 - import release_record # noqa: PLC0415 + import generate_site + import release_record record = release_record.load_advertised() page = generate_site.generate_which_pack() diff --git a/tests/test_workflow_paths.py b/tests/test_workflow_paths.py index 069954f3e..b3b9daeda 100644 --- a/tests/test_workflow_paths.py +++ b/tests/test_workflow_paths.py @@ -199,7 +199,7 @@ class DocumentedSteps(unittest.TestCase): def test_the_profiling_reference_names_every_profile_field(self): """built_by, source_branch, bios_mode, standalone_path and on_mismatch change what the tools do and no page named them.""" - import json # noqa: PLC0415 + import json schema = json.loads((REPO_ROOT / "schemas/emulator.schema.json").read_text(encoding="utf-8")) item = schema["properties"]["files"]["items"] @@ -277,7 +277,7 @@ class DocumentedSteps(unittest.TestCase): """The page listed pyyaml and mkdocs and left out jsonschema: a maintainer following it could not run the contract check.""" sys.path.insert(0, str(SCRIPTS)) - from check_freshness import parse_pip_pins # noqa: PLC0415 + from check_freshness import parse_pip_pins workflow = (REPO_ROOT / ".github/workflows/deploy-site.yml").read_text(encoding="utf-8") page = (REPO_ROOT / "wiki/release-process.md").read_text(encoding="utf-8") diff --git a/tests/test_zipped_member.py b/tests/test_zipped_member.py index cc369fbd0..9f7c144e8 100644 --- a/tests/test_zipped_member.py +++ b/tests/test_zipped_member.py @@ -65,9 +65,9 @@ class TheMemberIndexIsCachedByContent(unittest.TestCase): archive members again, about 23 s a step.""" def test_a_second_process_reads_the_cache(self): - from unittest import mock # noqa: PLC0415 + from unittest import mock - import ziptools # noqa: PLC0415 + import ziptools with tempfile.TemporaryDirectory(dir=REPO_ROOT / "tmp") as tmp: archive = Path(tmp) / "set.zip"