chore: merge main for the ruff config

This commit is contained in:
Abdessamad Derraz committed 2026-11-17 07:09:56 +01:00
commit 4e9f7673a2
186 files changed
+1001 -1058

No files matched your search

+2 -2
View File
@@ -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():
+2 -2
View File
@@ -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])
+3 -3
View File
@@ -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():
+17 -25
View File
@@ -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):
+6 -6
View File
@@ -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")
+25 -26
View File
@@ -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"},
+2 -2
View File
@@ -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",
+1 -1
View File
@@ -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"
+2 -2
View File
@@ -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))
+4 -4
View File
@@ -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": {},
+8 -8
View File
@@ -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")
+1 -1
View File
@@ -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
+2 -2
View File
@@ -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 = {
+2 -2
View File
@@ -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)
+1 -1
View File
@@ -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")
+1 -1
View File
@@ -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")
+1 -1
View File
@@ -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)
+4 -4
View File
@@ -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()
unittest.main()
+3 -3
View File
@@ -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()
+11 -11
View File
@@ -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"),
+6 -6
View File
@@ -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,
+2 -3
View File
@@ -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())
+4 -4
View File
@@ -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"):
+1 -1
View File
@@ -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"]
+3 -3
View File
@@ -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)
+2 -2
View File
@@ -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,
+24 -24
View File
@@ -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",
+3 -3
View File
@@ -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")
+9 -9
View File
@@ -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()
+30 -30
View File
@@ -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('<bios path="a" md5="1,2" />'),
_stated('<bios path="a" md5="2,1" />'))
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 = ' <bios path="kick.rom" md5="aa" core="libretro/puae" />'
mine = ' <bios path="kick.rom" md5="aa" core="libretro/puae" mandatory="false" />'
@@ -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)])
+1 -1
View File
@@ -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.
+2 -3
View File
@@ -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):
+2 -2
View File
@@ -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)
+4 -6
View File
@@ -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()
+1 -1
View File
@@ -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):
+53 -54
View File
@@ -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):
+1 -2
View File
@@ -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:
+2 -3
View File
@@ -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())
+6 -6
View File
@@ -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": [
+4 -5
View File
@@ -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")
+2 -2
View File
@@ -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
+1 -1
View File
@@ -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
+5 -5
View File
@@ -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)
+1 -1
View File
@@ -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
+5 -5
View File
@@ -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"]}]
+22 -25
View File
@@ -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("<!-- generated: card-markers -->"):
@@ -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))
+7 -7
View File
@@ -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
+4 -4
View File
@@ -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,
+4 -4
View File
@@ -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",
+3 -4
View File
@@ -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:
+1 -1
View File
@@ -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"]))
+2 -3
View File
@@ -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)
+5 -5
View File
@@ -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)
+1 -1
View File
@@ -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",
+2 -2
View File
@@ -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 = (
+4 -5
View File
@@ -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)
+1 -1
View File
@@ -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"]):
+1 -1
View File
@@ -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()
+2 -2
View File
@@ -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):
+3 -3
View File
@@ -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")
+28 -31
View File
@@ -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)
+5 -17
View File
@@ -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)]
+6 -6
View File
@@ -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,
+8 -9
View File
@@ -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:
+1 -1
View File
@@ -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(
+4 -4
View File
@@ -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:
+7 -7
View File
@@ -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,
+1 -1
View File
@@ -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)
+1 -1
View File
@@ -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"]},
+1 -1
View File
@@ -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},
+8 -8
View File
@@ -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)
+1 -1
View File
@@ -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
+34 -38
View File
@@ -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):
+4 -4
View File
@@ -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 = ('<html><body><main><h1 id="_top">Demo</h1><div class="sl-markdown-content">'
'<p>Run it <a href="/retrobios/x/">here</a>.</p>'
+1 -1
View File
@@ -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"]
+1 -1
View File
@@ -359,7 +359,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"></span>', sitemarkup._tile_mark("MyMinUI", ""))
component = _read(REPO_ROOT / "website" / "src" / "components" / "PageTitle.astro")
-1
View File
@@ -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
+5 -5
View File
@@ -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("<InstallDemo "), len(expected) - 1)
def test_the_site_serves_the_videos_not_the_gif(self):
import generate_site # noqa: PLC0415
import generate_site
expected = tuple(name for variant in make_demo.VARIANTS.values()
for name in variant.outputs if not name.endswith(".gif"))
@@ -261,7 +261,7 @@ class TheTwoPagesShowIt(unittest.TestCase):
def generate_site_assets() -> tuple[str, ...]:
import generate_site # noqa: PLC0415
import generate_site
return generate_site.DEMO_ASSETS
-1
View File
@@ -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"
+2 -2
View File
@@ -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")
+1 -1
View File
@@ -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)
+43 -43
View File
@@ -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]
+1 -2
View File
@@ -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}
+2 -2
View File
@@ -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)
+1 -1
View File
@@ -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)
+1 -1
View File
@@ -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/"
+6 -6
View File
@@ -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 "
+1 -1
View File
@@ -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*"))
+2 -4
View File
@@ -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 <br> breaks a line on screen only: a copy and textContent join across
+1 -1
View File
@@ -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)
+8 -8
View File
@@ -604,11 +604,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)
@@ -635,7 +635,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")
@@ -783,7 +783,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"}}}
@@ -914,7 +914,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, []
@@ -925,7 +925,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))
@@ -1025,7 +1025,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"]
@@ -1148,7 +1148,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
+2 -2
View File
@@ -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"])
+1 -1
View File
@@ -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": {}}))
+1 -2
View File
@@ -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.
+1 -2
View File
@@ -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(
+6 -6
View File
@@ -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():
+1 -1
View File
@@ -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",
+6 -6
View File
@@ -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")
+12 -12
View File
@@ -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"))
+24 -24
View File
@@ -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):
Loaded 100 of 186 files, more files were not shown because too many files have changed in this diff. Show more