diff --git a/tests/test_archive_build.py b/tests/test_archive_build.py index 935b94a66..9d79a2a45 100644 --- a/tests/test_archive_build.py +++ b/tests/test_archive_build.py @@ -198,9 +198,9 @@ class Capture(Fixture): self.assertEqual(records["bios/set.zip"]["members"][0]["sha1"], "kept") def test_zlib_ng_refuses_to_capture(self): - with mock.patch.object(archive_build, "zlib_ng_version", lambda: "2.2.4"): - with self.assertRaises(archive_build.ZlibNgError): - self.capture() + with mock.patch.object(archive_build, "zlib_ng_version", lambda: "2.2.4"), \ + self.assertRaises(archive_build.ZlibNgError): + self.capture() def test_composite_and_zipped_pins_name_no_container(self): platforms = self.root / "platforms" diff --git a/tests/test_artifact_lock.py b/tests/test_artifact_lock.py index ba3e2d2a6..aec1ec691 100644 --- a/tests/test_artifact_lock.py +++ b/tests/test_artifact_lock.py @@ -54,9 +54,10 @@ class ArtifactLockTest(unittest.TestCase): pass def test_writer_excludes_reader(self): - with artifact_lock(self.dir), self.assertRaises(ArtifactLockBusy): - with artifact_lock(self.dir, exclusive=False): - pass + with artifact_lock(self.dir), \ + self.assertRaises(ArtifactLockBusy), \ + 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): @@ -121,6 +122,7 @@ class PackLockCliTest(unittest.TestCase): text=True, cwd=str(scratch_checkout()), timeout=300, + check=False, ) def test_generate_pack_refuses_locked_output(self): @@ -162,6 +164,7 @@ class PackLockCliTest(unittest.TestCase): [sys.executable, "scripts/generate_pack.py", "--platform", "misterfpga", "--platforms-dir", str(platforms), "--output-dir", str(output)], capture_output=True, text=True, cwd=str(REPO_ROOT), timeout=120, + check=False, ) except subprocess.TimeoutExpired: self.fail("generate_pack waited on the data tree instead of refusing") @@ -240,6 +243,7 @@ class PipelineHoldsItsFixedOutputs(unittest.TestCase): [sys.executable, "scripts/pipeline.py", "--offline", "--skip-docs", "--output-dir", scratch], capture_output=True, text=True, cwd=str(checkout), timeout=120, + check=False, ) self.assertEqual(proc.returncode, 1, proc.stdout + proc.stderr) self.assertIn("another run is writing database.json", proc.stderr) @@ -260,21 +264,21 @@ class TheSuiteTakesTheRepositoryHoldInItsScratch(unittest.TestCase): scratch = Path(tempfile.mkdtemp(dir=REPO_ROOT / "tmp")) self.addCleanup(shutil.rmtree, scratch, True) moved = scratch / "repository-lock" - with mock.patch.dict(os.environ, {artifacts.REPOSITORY_LOCK_ENV: str(moved)}): - with artifacts.hold_repository_outputs(str(REPO_ROOT)): - key = str(REPO_ROOT.resolve()).strip(os.sep).replace(os.sep, "__") - self.assertTrue((moved / key / ".lock").is_file()) - # Held there: a second hold in the same tree is refused. - with self.assertRaises(artifacts.ArtifactLockBusy): - with artifacts.hold_repository_outputs(str(REPO_ROOT)): - pass + with mock.patch.dict(os.environ, {artifacts.REPOSITORY_LOCK_ENV: str(moved)}), \ + artifacts.hold_repository_outputs(str(REPO_ROOT)): + key = str(REPO_ROOT.resolve()).strip(os.sep).replace(os.sep, "__") + self.assertTrue((moved / key / ".lock").is_file()) + # Held there: a second hold in the same tree is refused. + with self.assertRaises(artifacts.ArtifactLockBusy), \ + artifacts.hold_repository_outputs(str(REPO_ROOT)): + pass def test_another_directory_keeps_its_own_lock(self): out = Path(tempfile.mkdtemp(dir=REPO_ROOT / "tmp")) self.addCleanup(shutil.rmtree, out, True) - with mock.patch.dict(os.environ, {artifacts.REPOSITORY_LOCK_ENV: str(out / "x")}): - with artifacts.artifact_lock(str(out)): - self.assertTrue((out / ".lock").is_file()) + with mock.patch.dict(os.environ, {artifacts.REPOSITORY_LOCK_ENV: str(out / "x")}), \ + artifacts.artifact_lock(str(out)): + self.assertTrue((out / ".lock").is_file()) self.assertFalse((out / "x").exists()) def test_the_suite_sets_it(self): @@ -401,6 +405,7 @@ class SiteGenerationHoldsDocs(unittest.TestCase): result = subprocess.run( [sys.executable, "scripts/generate_site.py", "--docs-dir", docs], cwd=scratch_checkout(), capture_output=True, text=True, timeout=600, + check=False, ) self.assertEqual(result.returncode, 1, result.stdout + result.stderr) self.assertIn("in use by another run", result.stderr) diff --git a/tests/test_atomic_artifacts.py b/tests/test_atomic_artifacts.py index fa771b4a4..3d0904290 100644 --- a/tests/test_atomic_artifacts.py +++ b/tests/test_atomic_artifacts.py @@ -100,10 +100,14 @@ class EveryWriterGoesThroughIt(unittest.TestCase): for top in tree.body: if path.name == "generate_installer_doc.py" and getattr(top, "name", "") in sandbox: continue - for node in ast.walk(top): - if (isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute) - and node.func.attr in ("write_text", "write_bytes")): - offenders.append(f"{path.name}:{node.lineno}") + offenders.extend( + f"{path.name}:{node.lineno}" + for node in ast.walk(top) + if ( + isinstance(node, ast.Call) and isinstance(node.func, ast.Attribute) + and node.func.attr in ("write_text", "write_bytes") + ) + ) self.assertEqual(offenders, []) def test_the_text_is_utf8_whatever_the_locale(self): diff --git a/tests/test_audit_regressions.py b/tests/test_audit_regressions.py index 249175027..9eec9145e 100644 --- a/tests/test_audit_regressions.py +++ b/tests/test_audit_regressions.py @@ -30,11 +30,8 @@ except ImportError: else: HAS_JSONSCHEMA = True -ROOT = Path(__file__).resolve().parent.parent -TMP_ROOT = ROOT / "tmp" / "tests" -TMP_ROOT.mkdir(parents=True, exist_ok=True) -sys.path.insert(0, str(ROOT)) -sys.path.insert(0, str(ROOT / "scripts")) +sys.path.insert(0, str(Path(__file__).resolve().parent.parent)) +sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "scripts")) import install from scripts import pipeline, region, region_audit @@ -45,6 +42,10 @@ from scripts.generate_pack import ( verify_pack_against_platform, ) +ROOT = Path(__file__).resolve().parent.parent +TMP_ROOT = ROOT / "tmp" / "tests" +TMP_ROOT.mkdir(parents=True, exist_ok=True) + class ReadmeRegressions(unittest.TestCase): """The README advertises commands, and these must stay executable. @@ -1283,7 +1284,7 @@ class PipelineRegressions(unittest.TestCase): "2a2 refresh FBNeo hashes", ): with self.subTest(failed_label=failed_label): - def fake_run(_command, label): + def fake_run(_command, label, failed_label=failed_label): return label != failed_label, "RetroArch: 1/1 OK\n" argv = ["pipeline.py", "--skip-packs", "--skip-docs"] @@ -2227,7 +2228,7 @@ class CheckoutCompletenessRegressions(unittest.TestCase): for position, step in enumerate(steps): if needle in step.get("name", "") or needle in str(step.get("run", "")): return position - self.fail(f"no step matching {needle!r}") + raise self.failureException(f"no step matching {needle!r}") def test_site_deploy_completes_the_checkout_before_generating(self): steps = self._steps("deploy-site.yml", "build") @@ -2281,6 +2282,7 @@ class CheckoutCompletenessRegressions(unittest.TestCase): [sys.executable, str(ROOT / "scripts" / "restore_large_files.py"), "--gitignore", missing, "--cache", directory], capture_output=True, text=True, timeout=120, + check=False, ) self.assertEqual(proc.returncode, 2, proc.stdout + proc.stderr) self.assertIn("lists the release assets", proc.stderr) @@ -2868,6 +2870,7 @@ class PreservedBytesAreNeverNormalised(unittest.TestCase): out = subprocess.run( ["git", "check-attr", "text", "--", path], capture_output=True, text=True, cwd=ROOT, + check=False, ).stdout return out.rsplit(":", 1)[-1].strip() @@ -2984,14 +2987,16 @@ class AMissingDependencyStopsTheBuild(unittest.TestCase): offenders = [] for path in sorted((ROOT / "scripts").rglob("*.py")): tree = ast.parse(path.read_text(encoding="utf-8")) - for node in ast.walk(tree): + offenders.extend( + f"{path.relative_to(ROOT)}:{node.lineno}" + for node in ast.walk(tree) if ( isinstance(node, ast.ExceptHandler) and isinstance(node.type, ast.Name) and node.type.id in ("ImportError", "ModuleNotFoundError") and all(isinstance(stmt, ast.Pass) for stmt in node.body) - ): - offenders.append(f"{path.relative_to(ROOT)}:{node.lineno}") + ) + ) self.assertEqual(offenders, []) @@ -3168,6 +3173,7 @@ class ACheckThatCannotAnswerDoesNotPass(unittest.TestCase): [sys.executable, "scripts/generate_pack.py", "--platform", "retroarch", "--verify-packs", "--output-dir", directory], capture_output=True, text=True, cwd=str(ROOT), timeout=300, + check=False, ) self.assertNotEqual( named.returncode, 0, @@ -3180,6 +3186,7 @@ class ACheckThatCannotAnswerDoesNotPass(unittest.TestCase): [sys.executable, "scripts/generate_pack.py", "--all", "--verify-packs", "--output-dir", directory], capture_output=True, text=True, cwd=str(ROOT), timeout=300, + check=False, ) self.assertIn("SKIP (no pack in", swept.stdout) self.assertNotEqual(swept.returncode, 0, swept.stdout + swept.stderr) @@ -3285,6 +3292,7 @@ class ScriptsImportThreeWays(unittest.TestCase): return subprocess.run( [sys.executable, *args], capture_output=True, text=True, cwd=str(ROOT), timeout=300, + check=False, ) def test_imported_as_a_package(self): @@ -3761,9 +3769,9 @@ class TheDatabaseCacheIsWrittenWhole(unittest.TestCase): with tempfile.TemporaryDirectory(dir=TMP_ROOT) as directory: path = os.path.join(directory, "cache", "db_cache.json") generate_db.save_cache(path, {"a": 1}) - with mock.patch.object(json, "dumps", side_effect=TypeError("miscomputed")): - with self.assertRaises(TypeError): - generate_db.save_cache(path, {"a": 2}) + with mock.patch.object(json, "dumps", side_effect=TypeError("miscomputed")), \ + self.assertRaises(TypeError): + generate_db.save_cache(path, {"a": 2}) self.assertEqual(generate_db.load_cache(path), {"a": 1}) self.assertEqual(os.listdir(os.path.dirname(path)), ["db_cache.json"]) @@ -4240,7 +4248,7 @@ class TriageSurvivesAForgeRefusal(unittest.TestCase): # A header row and a closing count frame the ranking. lines = out.getvalue().splitlines()[1:-1] self.assertEqual(len(lines), 2) - self.assertTrue(any("eden" in l and "unreachable" in l for l in lines)) + self.assertTrue(any("eden" in line and "unreachable" in line for line in lines)) class VerifyStrictAppliesInEveryMode(unittest.TestCase): @@ -4266,6 +4274,7 @@ class VerifyStrictAppliesInEveryMode(unittest.TestCase): return subprocess.run( [sys.executable, "scripts/verify.py", *flags], cwd=ROOT, capture_output=True, text=True, + check=False, ).returncode def test_emulator_and_system_modes_fail_on_a_missing_required_file(self): @@ -4608,6 +4617,7 @@ class EveryToolRefusesAFlagItWouldDrop(unittest.TestCase): proc = subprocess.run( [sys.executable, script, *argv], cwd=ROOT, capture_output=True, text=True, timeout=120, + check=False, ) self.assertEqual(proc.returncode, 2, proc.stdout + proc.stderr) @@ -4746,8 +4756,8 @@ class TheToolsPageSaysWhatDedupDoes(unittest.TestCase): from scripts import dedup line = next( - l for l in (ROOT / "wiki" / "tools.md").read_text().splitlines() - if l.startswith("| `dedup.py`") + row for row in (ROOT / "wiki" / "tools.md").read_text().splitlines() + if row.startswith("| `dedup.py`") ) self.assertNotIn(".variants", line) for name in dedup.NODEDUP_DIRS: @@ -4868,6 +4878,7 @@ class GeneratedArtifactsMeetTheirSchemas(unittest.TestCase): proc = subprocess.run( [sys.executable, "scripts/validate_schemas.py"], cwd=ROOT, capture_output=True, text=True, timeout=600, + check=False, ) self.assertEqual(proc.returncode, 0, proc.stdout + proc.stderr) @@ -6139,6 +6150,7 @@ class ATargetIsNamedWhenItRemovesTheCore(unittest.TestCase): [sys.executable, "scripts/cross_reference.py", "--platform", "batocera", "--target", "bcm2711", "--emulator", "dolphin"], cwd=ROOT, capture_output=True, text=True, timeout=600, + check=False, ) self.assertEqual(result.returncode, 1) self.assertIn("bcm2711 target", result.stderr) @@ -6156,6 +6168,7 @@ class ANamedPackThatIsAbsentFails(unittest.TestCase): [sys.executable, "scripts/generate_pack.py", "--platform", "retroarch", "--verify-packs", "--output-dir", directory], cwd=ROOT, capture_output=True, text=True, timeout=600, + check=False, ) self.assertEqual(result.returncode, 1) self.assertIn("retroarch: FAIL (no pack in", result.stdout) @@ -6169,6 +6182,7 @@ class ANamedPackThatIsAbsentFails(unittest.TestCase): [sys.executable, "scripts/generate_pack.py", "--all", "--verify-packs", "--output-dir", directory], cwd=ROOT, capture_output=True, text=True, timeout=600, + check=False, ) self.assertEqual(result.returncode, 1) self.assertIn("no pack to verify", result.stderr) @@ -6343,6 +6357,7 @@ class VerifyPacksRefusesWhatItCannotDo(unittest.TestCase): result = subprocess.run( [sys.executable, "scripts/generate_pack.py", *extra, "--output-dir", out], cwd=ROOT, capture_output=True, text=True, timeout=300, + check=False, ) self.assertEqual(result.returncode, 2, result.stderr[-300:]) self.assertIn("--verify-packs", result.stderr) @@ -6857,7 +6872,7 @@ class DocsDescribeTheRegistriesTheyName(unittest.TestCase): def test_the_dedup_list_is_named_whole_or_by_its_constant(self): from dedup import NODEDUP_DIRS tools = (ROOT / "wiki" / "tools.md").read_text(encoding="utf-8") - line = next(l for l in tools.splitlines() if "NODEDUP_DIRS" in l) + line = next(entry for entry in tools.splitlines() if "NODEDUP_DIRS" in entry) # Compared as list items: `mame` was missing while the substring # test found it in `_mame_clones.json` on the same line. listed = line.split("`NODEDUP_DIRS`", 1)[1].split(":", 1)[1].rstrip(" |") @@ -7193,6 +7208,7 @@ class InstallerJsonKindsNeverOverwriteEachOther(unittest.TestCase): [sys.executable, "scripts/generate_pack.py", *flags, "--offline", "--output-dir", tmp], cwd=ROOT, capture_output=True, text=True, timeout=600, + check=False, ) return proc, before, target.read_text(encoding="utf-8") @@ -7334,6 +7350,7 @@ class ToolsRunFromAnyDirectory(unittest.TestCase): return subprocess.run( [sys.executable, *argv], cwd=cwd, capture_output=True, text=True, timeout=600, + check=False, ) def test_listing_works_from_scripts(self): @@ -7528,6 +7545,7 @@ class ATargetTypoIsAnErrorInEveryTool(unittest.TestCase): [sys.executable, f"scripts/{script}", "--platform", "retroarch", "--target", "swich"], cwd=ROOT, capture_output=True, text=True, timeout=300, + check=False, ) output = proc.stdout + proc.stderr self.assertNotEqual(proc.returncode, 0) @@ -7548,6 +7566,7 @@ class AnUnknownSystemIsRefusedBeforeAnyWork(unittest.TestCase): [sys.executable, "scripts/generate_pack.py", "--platform", "batocera", "--system", "playstaton-nothing", "--output-dir", str(out)], cwd=ROOT, capture_output=True, text=True, timeout=120, + check=False, ) self.assertEqual(proc.returncode, 2, proc.stdout + proc.stderr) self.assertIn( @@ -7651,9 +7670,11 @@ class ProfileNotesDescribeTheCoreAlone(unittest.TestCase): for number, line in enumerate(text.splitlines(), 1): if self.SHOUT.search(line): found.append(f"{path.stem}:{number}") - for match in re.finditer(r"\bunlike (?:the )?([\w+-]+)", line, re.I): - if match.group(1).casefold() in names: - found.append(f"{path.stem}:{number}") + found.extend( + f"{path.stem}:{number}" + for match in re.finditer(r"\bunlike (?:the )?([\w+-]+)", line, re.I) + if match.group(1).casefold() in names + ) self.assertEqual(found, []) @@ -7677,13 +7698,15 @@ class Ps2BiosImagesAreFoundByContent(unittest.TestCase): # Whatever the profile's own flags: TeknoParrot documents its # pcsx2x6 component, whose scan is the same (BiosTools.cpp:268-291 # at 583f0e90), and carries no agnostic flag. - for entry in profile.get("files") or []: + named.extend( + f"{path.stem}: {entry['name']}" + for entry in profile.get("files") or [] if ( entry.get("min_size") in (2097152, 4194304) and entry.get("max_size") == 8388608 and opens_by_name(entry, profile) - ): - named.append(f"{path.stem}: {entry['name']}") + ) + ) self.assertEqual(named, []) @@ -7723,11 +7746,15 @@ class Dev9FilesAreReadFromTheWorkingDirectory(unittest.TestCase): unset = [] for path in sorted((ROOT / "emulators").glob("*.yml")): profile = yaml.safe_load(path.read_text(encoding="utf-8")) or {} - for entry in profile.get("files") or []: - if entry.get("name") in ("eeprom.dat", "flash.dat") and "DEV9" in str( - entry.get("source_ref") - ) and entry.get("load_from") != "working_directory": - unset.append(f"{path.stem}: {entry['name']}") + unset.extend( + f"{path.stem}: {entry['name']}" + for entry in profile.get("files") or [] + if ( + entry.get("name") in ("eeprom.dat", "flash.dat") + and "DEV9" in str(entry.get("source_ref")) + and entry.get("load_from") != "working_directory" + ) + ) self.assertEqual(unset, []) diff --git a/tests/test_autorun.py b/tests/test_autorun.py index 2cdbd4d5a..7d0515ead 100644 --- a/tests/test_autorun.py +++ b/tests/test_autorun.py @@ -512,7 +512,7 @@ class Commits(Origin): with contextlib.redirect_stdout(io.StringIO()): self.assertEqual(ar.run_job(ctx, "n"), (ar.OK, "dry run")) lines = ar.describe(ctx.jobs["n"], ctx) - would = sorted(l.split("would commit ")[1] for l in lines if "would commit" in l) + would = sorted(line.split("would commit ")[1] for line in lines if "would commit" in line) self.assertEqual(would, ["database.json", "install/b.json"]) self.assertEqual(run_git(wt, "diff", "--cached", "--name-only"), "") self.assertFalse(ctx.state_path.exists()) @@ -620,7 +620,7 @@ class Push(Origin): class RunnerPush(Origin): def _ctx(self, value: int, push: bool) -> ar.Context: - write = "open('database.json', 'w').write('{\"n\": %d}')" % value + write = f"open('database.json', 'w').write('{{\"n\": {value:d}}}')" jobs = {"n": {"min_free_gb": 0, "steps": [[PY, "-c", write]], "commits": [ {"subject": "chore: regenerate collection records", "paths": ["database.json"]}]}} return ar.Context(repo=self.repo, jobs=ar.parse_jobs({"jobs": jobs}), diff --git a/tests/test_campaign.py b/tests/test_campaign.py index f1f41b7cb..512d44365 100644 --- a/tests/test_campaign.py +++ b/tests/test_campaign.py @@ -29,14 +29,15 @@ from types import MappingProxyType import yaml -REPO_ROOT = Path(__file__).resolve().parent.parent -sys.path.insert(0, str(REPO_ROOT / "scripts")) +sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "scripts")) import campaign import campaign_profiles import campaign_rules as rules import measurement_records as mr +REPO_ROOT = Path(__file__).resolve().parent.parent + TMP = REPO_ROOT / "tmp" / "tests" PROFILE = """\ diff --git a/tests/test_core_file_fills_declaration.py b/tests/test_core_file_fills_declaration.py index 499f67dd2..52f281334 100644 --- a/tests/test_core_file_fills_declaration.py +++ b/tests/test_core_file_fills_declaration.py @@ -370,13 +370,15 @@ class TheManifestResolvesLikeThePack(unittest.TestCase): for fn in ast.walk(ast.parse(source)): if not isinstance(fn, ast.FunctionDef) or fn.name == "generate_md5_pack": continue - for node in ast.walk(fn): + missing.extend( + f"{fn.name}:{node.lineno}" + for node in ast.walk(fn) if ( isinstance(node, ast.Call) and getattr(node.func, "id", None) == "resolve_file" and "data_dir_registry" not in {k.arg for k in node.keywords} - ): - missing.append(f"{fn.name}:{node.lineno}") + ) + ) self.assertEqual(missing, []) diff --git a/tests/test_core_probe.py b/tests/test_core_probe.py index de09f6af1..19a05d7d7 100644 --- a/tests/test_core_probe.py +++ b/tests/test_core_probe.py @@ -25,12 +25,13 @@ import unittest.mock from pathlib import Path from typing import ClassVar -REPO_ROOT = Path(__file__).resolve().parent.parent -sys.path.insert(0, str(REPO_ROOT / "scripts")) +sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "scripts")) import core_probe import measurement_records +REPO_ROOT = Path(__file__).resolve().parent.parent + STRACE_SAMPLE = """\ 4242 openat(AT_FDCWD, "/sys/bios/card.bin", O_RDONLY) = 5 4242 openat(AT_FDCWD, "/sys/bios/missing.bin", O_RDONLY) = -1 ENOENT (No such file or directory) diff --git a/tests/test_directory_entries.py b/tests/test_directory_entries.py index 93b737253..7c86113ff 100644 --- a/tests/test_directory_entries.py +++ b/tests/test_directory_entries.py @@ -353,9 +353,11 @@ class ProfileContract(unittest.TestCase): offenders = [] for path in sorted((REPO_ROOT / "emulators").glob("*.yml")): document = yaml.safe_load(path.read_text(encoding="utf-8")) or {} - for entry in document.get("files") or []: - if self._errors_for_directory_rules(entry): - offenders.append(f"{path.name}: {entry.get('name')}") + offenders.extend( + f"{path.name}: {entry.get('name')}" + for entry in document.get("files") or [] + if self._errors_for_directory_rules(entry) + ) self.assertEqual(offenders, []) @staticmethod @@ -402,6 +404,7 @@ class CollectionScanAndIgnoreRules(unittest.TestCase): listed = subprocess.run( ["git", "ls-files", "--others", "--ignored", "--exclude-standard", "bios"], cwd=REPO_ROOT, capture_output=True, text=True, + check=False, ) if listed.returncode != 0: self.skipTest("not a git checkout") diff --git a/tests/test_doc_pages.py b/tests/test_doc_pages.py index dea19f7cb..72caa8d1c 100644 --- a/tests/test_doc_pages.py +++ b/tests/test_doc_pages.py @@ -47,9 +47,11 @@ def _section(text: str, heading: str) -> str: def _table_rows(text: str) -> list[list[str]]: rows = [] - for line in text.splitlines(): - if line.startswith("|") and not re.match(r"\|\s*-", line): - rows.append([cell.strip() for cell in line.strip().strip("|").split(" | ")]) + rows.extend( + [cell.strip() for cell in line.strip().strip("|").split(" | ")] + for line in text.splitlines() + if line.startswith("|") and not re.match(r"\|\s*-", line) + ) return rows[1:] @@ -321,9 +323,11 @@ class PublishedHeadings(unittest.TestCase): offenders = [] for page in (ROOT / "README.md", ROOT / "CONTRIBUTING.md"): text = FENCED.sub("", page.read_text(encoding="utf-8")) - for title in re.findall(r"(?m)^#{1,4} (.+)$", text): - if _sentence_case(title) != title: - offenders.append(f"{page.name}: {title}") + offenders.extend( + f"{page.name}: {title}" + for title in re.findall(r"(?m)^#{1,4} (.+)$", text) + if _sentence_case(title) != title + ) self.assertEqual(offenders, [], "\n".join(offenders)) @@ -388,9 +392,11 @@ class DocstringsWithoutInsistence(unittest.TestCase): offenders = [] paths = sorted((ROOT / "scripts").rglob("*.py")) + [ROOT / "install.py"] for path in paths: - for line in _python_prose(path.read_text(encoding="utf-8")).splitlines(): - if self.TICS.search(line): - offenders.append(f"{path.relative_to(ROOT)}: {line.strip()[:80]}") + offenders.extend( + f"{path.relative_to(ROOT)}: {line.strip()[:80]}" + for line in _python_prose(path.read_text(encoding="utf-8")).splitlines() + if self.TICS.search(line) + ) self.assertEqual(offenders, [], "\n".join(offenders)) @@ -1026,9 +1032,11 @@ def unknown_commands(text: str) -> list[str]: if not source: wrong.append(name) continue - for option in re.findall(r"(? list[str]: if not part or part.lstrip().startswith(FOREIGN_COMMANDS): continue program = _owner(part) or default - for option in OPTION.findall(part): - if program is None or not has(program, option): - stale.append(f"{option} ({program}): {part.strip()}") + stale.extend( + f"{option} ({program}): {part.strip()}" + for option in OPTION.findall(part) + if program is None or not has(program, option) + ) for paragraph in re.split(r"\n\s*\n", _prose(text)): named = {m.group(1) for m in SCRIPT.finditer(paragraph)} - {"install.sh", "install.ps1"} owners = named | page_scripts | ({default} if default else set()) @@ -1531,9 +1542,11 @@ def stale_options(text: str, default: str | None) -> list[str]: continue own = _owner(span) candidates = {own} if own else owners - for option in OPTION.findall(span): - if not any(has(program, option) for program in candidates): - stale.append(f"{option} ({', '.join(sorted(candidates))}): {span}") + stale.extend( + f"{option} ({', '.join(sorted(candidates))}): {span}" + for option in OPTION.findall(span) + if not any(has(program, option) for program in candidates) + ) return stale @@ -1891,8 +1904,9 @@ class SkipFlagsNameTheSteps(unittest.TestCase): for node in ast.walk(ast.parse(source)): if (isinstance(node, ast.Call) and getattr(node.func, "attr", "") == "add_argument" and node.args and isinstance(node.args[0], ast.Constant)): - helps.update({node.args[0].value: ast.literal_eval(kw.value) - for kw in node.keywords if kw.arg == "help"}) + for kw in node.keywords: + if kw.arg == "help": + helps[node.args[0].value] = ast.literal_eval(kw.value) for flag in ("--skip-packs", "--skip-docs"): steps = set() for row in table.splitlines(): @@ -2094,10 +2108,10 @@ class LandingAChangeNamesTheCommitRules(unittest.TestCase): message = clone / "MSG" message.write_text("fix: address review 3 notes\n", encoding="utf-8") refused = subprocess.run([str(clone / ".git" / "hooks" / "commit-msg"), "MSG"], - cwd=clone, capture_output=True, text=True) + cwd=clone, capture_output=True, text=True, check=False) message.write_text("fix: say what the change does\n", encoding="utf-8") accepted = subprocess.run([str(clone / ".git" / "hooks" / "commit-msg"), "MSG"], - cwd=clone, capture_output=True, text=True) + cwd=clone, capture_output=True, text=True, check=False) self.assertEqual(refused.returncode, 1, refused.stderr) self.assertIn("which review asked for it", refused.stderr) self.assertEqual(accepted.returncode, 0, accepted.stderr) diff --git a/tests/test_download.py b/tests/test_download.py index 98b06a1e2..c63643278 100644 --- a/tests/test_download.py +++ b/tests/test_download.py @@ -478,6 +478,7 @@ class TestDownloadPython(DownloaderCase): capture_output=True, text=True, timeout=120, + check=False, ) if expect_success: self.assertEqual(proc.returncode, 0, proc.stdout + proc.stderr) @@ -513,6 +514,7 @@ class TestDownloadPython(DownloaderCase): capture_output=True, text=True, timeout=60, + check=False, ) self.assertNotEqual(proc.returncode, 0, proc.stdout + proc.stderr) @@ -525,6 +527,7 @@ class TestDownloadPython(DownloaderCase): capture_output=True, text=True, timeout=60, + check=False, ) self.assertNotEqual(proc.returncode, 0) self.assertIn("RETROBIOS_API", proc.stderr) @@ -541,6 +544,7 @@ class TestDownloadShell(DownloaderCase): capture_output=True, text=True, timeout=120, + check=False, ) if expect_success: self.assertEqual(proc.returncode, 0, proc.stdout + proc.stderr) @@ -597,6 +601,7 @@ class TestDownloadShell(DownloaderCase): proc = subprocess.run( ["bash", str(SHELL), self.platform, str(self.dest)], env=env, capture_output=True, text=True, timeout=120, + check=False, ) self.assertNotEqual(proc.returncode, 0) self.assertEqual(installed.read_bytes(), b"valid") @@ -625,7 +630,8 @@ class TestDownloadShell(DownloaderCase): ) time.sleep(0.5) second = subprocess.run( - command, env=env, capture_output=True, text=True, timeout=120 + command, env=env, capture_output=True, text=True, timeout=120, + check=False, ) out, err = first.communicate(timeout=120) self.assertEqual(first.returncode, 0, out + err) diff --git a/tests/test_e2e.py b/tests/test_e2e.py index 065642dcb..781c592cf 100644 --- a/tests/test_e2e.py +++ b/tests/test_e2e.py @@ -2884,6 +2884,7 @@ class TestE2E(unittest.TestCase): ["python", "scripts/generate_pack.py", "--emulator", "test", "--split"], capture_output=True, text=True, + check=False, ) self.assertNotEqual(result.returncode, 0) self.assertIn("error", result.stderr.lower()) @@ -2902,6 +2903,7 @@ class TestE2E(unittest.TestCase): ], capture_output=True, text=True, + check=False, ) self.assertNotEqual(result.returncode, 0) @@ -2920,6 +2922,7 @@ class TestE2E(unittest.TestCase): ], capture_output=True, text=True, + check=False, ) self.assertNotEqual(result.returncode, 0) @@ -2938,6 +2941,7 @@ class TestE2E(unittest.TestCase): ], capture_output=True, text=True, + check=False, ) self.assertNotEqual(result.returncode, 0) @@ -6293,10 +6297,12 @@ struct BurnDriver BurnDrvneogeo = { ] for mode, flag, expected in matrix: with self.subTest(mode=mode, flag=flag): + self.assertEqual(expected, "refuse") result = subprocess.run( [sys.executable, "scripts/generate_pack.py", *mode, *flag, "--output-dir", os.path.join(self.root, "modecheck")], capture_output=True, text=True, cwd=repo, timeout=120, + check=False, ) combined = result.stdout + result.stderr self.assertNotEqual( @@ -6405,6 +6411,7 @@ struct BurnDriver BurnDrvneogeo = { [sys.executable, "scripts/generate_pack.py", "--system", "atari-lynx", "--offline", *extra, "--output-dir", out], capture_output=True, text=True, cwd=repo, timeout=300, + check=False, ) self.assertEqual(proc.returncode, 0, proc.stdout + proc.stderr) names[label] = sorted( @@ -6427,6 +6434,7 @@ struct BurnDriver BurnDrvneogeo = { [sys.executable, "scripts/generate_pack.py", "--platform", "misterfpga", "--offline", "--source", "truth", "--output-dir", out], capture_output=True, text=True, cwd=repo, timeout=300, + check=False, ) self.assertNotEqual(proc.returncode, 0) self.assertIn("a truth pack would hold nothing", proc.stderr) @@ -6445,6 +6453,7 @@ struct BurnDriver BurnDrvneogeo = { [sys.executable, "scripts/generate_pack.py", "--emulator", "handy", "--required-only", "--offline", "--output-dir", out], capture_output=True, text=True, cwd=repo, timeout=300, + check=False, ) self.assertEqual(proc.returncode, 0, proc.stdout + proc.stderr) self.assertIn("no file needed, no pack written", proc.stdout) @@ -6452,6 +6461,7 @@ struct BurnDriver BurnDrvneogeo = { verify = subprocess.run( [sys.executable, "scripts/verify.py", "--emulator", "handy", "--required-only"], capture_output=True, text=True, cwd=repo, timeout=300, + check=False, ) self.assertEqual(verify.returncode, proc.returncode) @@ -6477,6 +6487,7 @@ struct BurnDriver BurnDrvneogeo = { proc = subprocess.run( [sys.executable, *argv, *extra], capture_output=True, text=True, cwd=repo, timeout=300, + check=False, ) self.assertEqual(proc.returncode, 1, proc.stdout + proc.stderr) self.assertIn("runs no core a profile describes", proc.stderr) diff --git a/tests/test_exporters.py b/tests/test_exporters.py index ae1c6589b..4bb1cc614 100644 --- a/tests/test_exporters.py +++ b/tests/test_exporters.py @@ -2603,6 +2603,7 @@ class UpstreamFidelity(unittest.TestCase): capture_output=True, text=True, timeout=120, + check=False, ) self.assertEqual(result.returncode, 0, result.stderr) self.assertTrue(result.stdout.strip()) @@ -2625,6 +2626,7 @@ class UpstreamFidelity(unittest.TestCase): capture_output=True, text=True, timeout=120, + check=False, ) self.assertEqual(result.returncode, 0, result.stderr) @@ -2639,7 +2641,8 @@ class UpstreamFidelity(unittest.TestCase): script = Path(tmp) / "checkBIOS.sh" script.write_text(produced["checkBIOS.sh"], encoding="utf-8") result = subprocess.run( - ["bash", "-n", str(script)], capture_output=True, text=True, timeout=60 + ["bash", "-n", str(script)], capture_output=True, text=True, timeout=60, + check=False, ) self.assertEqual(result.returncode, 0, result.stderr) @@ -2759,6 +2762,7 @@ class UpstreamFidelity(unittest.TestCase): capture_output=True, text=True, timeout=60, + check=False, ) with self.subTest(module=relative): self.assertEqual(result.returncode, 0, result.stderr) diff --git a/tests/test_fileless_audit.py b/tests/test_fileless_audit.py index 0c6cc7c04..62ba75023 100644 --- a/tests/test_fileless_audit.py +++ b/tests/test_fileless_audit.py @@ -16,11 +16,12 @@ import unittest from pathlib import Path from unittest import mock -ROOT = Path(__file__).resolve().parent.parent -sys.path.insert(0, str(ROOT / "scripts")) +sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "scripts")) import fileless_audit +ROOT = Path(__file__).resolve().parent.parent + ASKS = [ "static void init(void)", diff --git a/tests/test_games_index.py b/tests/test_games_index.py index a6b93b938..374f8e221 100644 --- a/tests/test_games_index.py +++ b/tests/test_games_index.py @@ -230,6 +230,7 @@ class CommittedData(unittest.TestCase): result = subprocess.run( [sys.executable, "scripts/generate_games_index.py", "--check", "--quiet"], cwd=ROOT, capture_output=True, text=True, + check=False, ) self.assertEqual(result.returncode, 0, result.stderr[-2000:]) diff --git a/tests/test_handheld_launchers.py b/tests/test_handheld_launchers.py index 4ea88c20b..b8201acf3 100644 --- a/tests/test_handheld_launchers.py +++ b/tests/test_handheld_launchers.py @@ -12,6 +12,7 @@ from __future__ import annotations import tests # noqa: F401 offline, scratch under tmp/, the suite's own cache +import contextlib import hashlib import importlib.util import json @@ -87,7 +88,7 @@ def read_gptk(path: Path) -> dict[str, list[str]]: mapping: dict[str, list[str]] = {} for line in path.read_text(encoding="utf-8").splitlines(): line = line.strip() - if not line or line.startswith("#") or line.startswith("["): + if not line or line.startswith(("#", "[")): continue key, sep, value = line.partition(" = ") assert sep, line @@ -359,9 +360,9 @@ class TheArchives(unittest.TestCase): self.assertEqual(labels["retroarch"], "RetroArch") expected = "".join(f"{p}\t{label}\n" for p, label in sorted(labels.items())) for name, (_script, folder) in self.LAYOUT.items(): - with self.subTest(archive=name): - with zipfile.ZipFile(build_port.build_archive(name, self.out / name)) as zf: - self.assertEqual(zf.read(f"{folder}/packs.txt").decode(), expected) + with self.subTest(archive=name), \ + zipfile.ZipFile(build_port.build_archive(name, self.out / name)) as zf: + self.assertEqual(zf.read(f"{folder}/packs.txt").decode(), expected) def test_an_unpinned_installer_is_refused(self): root = _tempdir(self) @@ -818,10 +819,8 @@ class Device: for name in ("mapper.pid", "ui.pid", "engine.pid"): path = self.state / name if path.exists(): - try: + with contextlib.suppress(ProcessLookupError, ValueError): os.kill(int(path.read_text()), signal.SIGKILL) - except (ProcessLookupError, ValueError): - pass def _left(self) -> list[int]: """The processes a run on this device started that still run: each @@ -881,10 +880,8 @@ class Device: pid = int((self.state / "mapper.pid").read_text()) stopped = (self.state / "mapper.stopped").exists() if not stopped: - try: + with contextlib.suppress(ProcessLookupError): os.kill(pid, signal.SIGKILL) - except ProcessLookupError: - pass self.test.assertTrue(stopped, "gptokeyb was left running") def assert_mapper_gone(self) -> None: diff --git a/tests/test_hidden_extras.py b/tests/test_hidden_extras.py index 452c3205c..bd4f8ff59 100644 --- a/tests/test_hidden_extras.py +++ b/tests/test_hidden_extras.py @@ -109,7 +109,7 @@ class TheReportSaysSo(unittest.TestCase): for u in self.results[platform]["undeclared_files"]: if u.get("emulator") == emulator and (u.get("path") or u.get("name")) == path: return u - self.skipTest(f"{emulator} {path} is not in the cross-reference") + raise unittest.SkipTest(f"{emulator} {path} is not in the cross-reference") def _listed(self, emulator: str, path: str, platform: str) -> bool: return any( diff --git a/tests/test_install_experience.py b/tests/test_install_experience.py index aaf65c0ab..3f0a6adc8 100644 --- a/tests/test_install_experience.py +++ b/tests/test_install_experience.py @@ -648,7 +648,7 @@ class ADetectedFolderUnderAClosedOne(unittest.TestCase): os.chmod(lock, 0o000) try: runs = {name: subprocess.run(command + extra, env=env, capture_output=True, - text=True, timeout=60, stdin=subprocess.DEVNULL) + text=True, timeout=60, stdin=subprocess.DEVNULL, check=False) for name, extra in (("check", ["--check"]), ("install", []))} kinds = install.tell_apart([("retroarch", lock / "system", "RetroArch"), ("retroarch", repo.dest, "RetroArch")]) @@ -684,7 +684,7 @@ class AHomeThisUserCannotOpen(unittest.TestCase): [sys.executable, str(REPO_ROOT / "install.py"), "--check", "--no-input", "--verbose", *extra], env=env, capture_output=True, text=True, timeout=60, - stdin=subprocess.DEVNULL) + stdin=subprocess.DEVNULL, check=False) finally: os.chmod(home, 0o755) for name, proc in runs.items(): @@ -710,7 +710,7 @@ class AHomeThisUserCannotOpen(unittest.TestCase): [sys.executable, str(REPO_ROOT / "install.py"), "--check", "--no-input", "--platform", "retroarch"], env=env, capture_output=True, text=True, timeout=60, - stdin=subprocess.DEVNULL) + stdin=subprocess.DEVNULL, check=False) finally: os.chmod(home, 0o755) self.assertEqual(proc.returncode, 1, proc.stdout + proc.stderr) @@ -809,7 +809,7 @@ class TheFrontendsOwnFolderClosed(unittest.TestCase): [sys.executable, str(REPO_ROOT / "install.py"), "--platform", "retroarch", "--dry-run", "--no-input"], env=env, capture_output=True, text=True, timeout=60, - stdin=subprocess.DEVNULL) + stdin=subprocess.DEVNULL, check=False) finally: os.chmod(flatpak, 0o755) self.assertNotIn("Traceback", proc.stderr) @@ -877,7 +877,7 @@ class APartlyClosedHome(unittest.TestCase): [sys.executable, str(REPO_ROOT / "install.py"), "--check", "--no-input", "--verbose", *extra], env=env, capture_output=True, text=True, timeout=60, - stdin=subprocess.DEVNULL) + stdin=subprocess.DEVNULL, check=False) finally: os.chmod(closed, 0o755) refusal = (f"Could not look for setups: this user cannot open {closed} " @@ -942,7 +942,7 @@ class AnUnreadableRetroArchConfigIsSaid(unittest.TestCase): [sys.executable, str(REPO_ROOT / "install.py"), "--check", "--no-input", "--events"], env=env, capture_output=True, text=True, timeout=60, - stdin=subprocess.DEVNULL) + stdin=subprocess.DEVNULL, check=False) finally: os.chmod(cfg, 0o644) self.assertNotIn("Traceback", proc.stderr) @@ -1251,7 +1251,7 @@ class NotFoundWithAClosedFolder(unittest.TestCase): [sys.executable, str(REPO_ROOT / "install.py"), "--platform", platform, "--dry-run", "--no-input", "--events"], env=env, capture_output=True, text=True, timeout=60, - stdin=subprocess.DEVNULL) + stdin=subprocess.DEVNULL, check=False) finally: os.chmod(closed, 0o755) events = [json.loads(line) for line in proc.stdout.splitlines()] @@ -1329,7 +1329,7 @@ class ADetectedClosedFolderSaysWhereItCameFrom(unittest.TestCase): proc = subprocess.run( [sys.executable, str(REPO_ROOT / "install.py"), "--check", "--no-input"], env=env, capture_output=True, text=True, timeout=60, - stdin=subprocess.DEVNULL) + stdin=subprocess.DEVNULL, check=False) finally: os.chmod(lock, 0o755) self.cfg = cfg @@ -1373,7 +1373,7 @@ class OfflineWithNothingFound(unittest.TestCase): [sys.executable, str(REPO_ROOT / "install.py"), "--offline", "--check", "--no-input"], env=env, capture_output=True, text=True, timeout=60, - stdin=subprocess.DEVNULL) + stdin=subprocess.DEVNULL, check=False) said = proc.stdout + proc.stderr self.assertEqual(proc.returncode, 1, said) self.assertNotIn("emudeck", said.lower()) diff --git a/tests/test_install_expert.py b/tests/test_install_expert.py index 419e56b3c..a69dcdc63 100644 --- a/tests/test_install_expert.py +++ b/tests/test_install_expert.py @@ -25,6 +25,8 @@ import unittest from pathlib import Path REPO_ROOT = Path(__file__).resolve().parent.parent +# install.py runs on 3.8, the scripts it is compared with need 3.9. +BUILDER_FLOOR = (3, 9) sys.path.insert(0, str(REPO_ROOT / "scripts")) _spec = importlib.util.spec_from_file_location("install", REPO_ROOT / "install.py") @@ -44,7 +46,7 @@ class RealListParity(unittest.TestCase): db_path = REPO_ROOT / "database.json" if not db_path.exists(): raise unittest.SkipTest("database.json is not built") - if sys.version_info < (3, 9): + if sys.version_info < BUILDER_FLOOR: # The builder's floor: install.py alone keeps 3.8. raise unittest.SkipTest("generate_pack.py needs Python 3.9 or newer") import generate_pack as gp @@ -261,7 +263,7 @@ class TheSlotRuleIsTheBuilders(unittest.TestCase): _copy("b.bin", b"b", slot=_slot(_claims(px68k=2), groups=("x68000",)))] self.assertEqual(self.drops(entries), set()) - @unittest.skipIf(sys.version_info < (3, 9), "slot.py needs Python 3.9 or newer") + @unittest.skipIf(sys.version_info < BUILDER_FLOOR, "slot.py needs Python 3.9 or newer") def test_random_slots_against_the_builder(self): import random @@ -293,7 +295,7 @@ class TheSlotRuleIsTheBuilders(unittest.TestCase): for name in entries] self.assertEqual(self.drops(listed, reach), expected) - @unittest.skipIf(sys.version_info < (3, 9), "slot.py needs Python 3.9 or newer") + @unittest.skipIf(sys.version_info < BUILDER_FLOOR, "slot.py needs Python 3.9 or newer") def test_a_destination_two_groups_name_apart(self): """One destination a platform declares under one name and a core under another: each group looks its own name up, as the builder @@ -583,7 +585,7 @@ class ExpertRuns(Lists): self.assertEqual(proc.returncode, 1, proc.stdout + proc.stderr) self.assertIn("which --source truth needs", proc.stderr) - @unittest.skipIf(sys.version_info < (3, 9), "validate_schemas.py needs Python 3.9 or newer") + @unittest.skipIf(sys.version_info < BUILDER_FLOOR, "validate_schemas.py needs Python 3.9 or newer") def test_the_schema_check_reads_a_null_truth_list(self): from unittest import mock diff --git a/tests/test_install_filesystems.py b/tests/test_install_filesystems.py index 8392dc2e4..9f6adf31c 100644 --- a/tests/test_install_filesystems.py +++ b/tests/test_install_filesystems.py @@ -38,7 +38,7 @@ class AndroidMediaScanner(unittest.TestCase): proc = subprocess.run(self.repo.command("--yes", "--no-input", *options), env={**self.repo.env(), "RETROBIOS_OS": os_name}, capture_output=True, text=True, timeout=60, - stdin=subprocess.DEVNULL) + stdin=subprocess.DEVNULL, check=False) return self.repo, proc def test_an_android_install_writes_one(self): diff --git a/tests/test_install_pack.py b/tests/test_install_pack.py index 8bfffc8b6..817ed53ab 100644 --- a/tests/test_install_pack.py +++ b/tests/test_install_pack.py @@ -10,6 +10,7 @@ from __future__ import annotations import tests # noqa: F401 offline, scratch under tmp/, the suite's own cache +import argparse import functools import hashlib import http.server @@ -632,7 +633,7 @@ class PartSizes(unittest.TestCase): for text in ("big", "1K", "-5M"): with self.subTest(text=text), \ mock.patch("sys.stderr", io.StringIO()), \ - self.assertRaises(Exception): + self.assertRaises(argparse.ArgumentTypeError): install.parse_part_size(text) diff --git a/tests/test_install_selection.py b/tests/test_install_selection.py index 3f34215b4..551e8d6b8 100644 --- a/tests/test_install_selection.py +++ b/tests/test_install_selection.py @@ -379,10 +379,8 @@ class DecliningTheSizePointsAtTheChoice(unittest.TestCase): mock.patch.object(install, "_is_terminal", return_value=True), \ mock.patch("builtins.input", lambda _prompt="": next(replies)), \ contextlib.redirect_stdout(out): - try: + with contextlib.suppress(SystemExit): install.main() - except SystemExit: - pass self.assertEqual(repo.installed(), []) return out.getvalue() @@ -1561,6 +1559,7 @@ class AnUnknownNativeNameIsRefusedBeforeAnyWork(unittest.TestCase): [sys.executable, f"scripts/{script}", "--platform", "batocera", "--system", "psxx", "--db", missing, *extra], cwd=REPO_ROOT, capture_output=True, text=True, timeout=300, + check=False, ) self.assertEqual(proc.returncode, 2, proc.stdout + proc.stderr) self.assertIn("unknown system psxx. Close matches: psx.", proc.stderr) @@ -1572,6 +1571,7 @@ class AnUnknownNativeNameIsRefusedBeforeAnyWork(unittest.TestCase): [sys.executable, "scripts/verify.py", "--platform", "batocera", "--system", "psx", "--json"], cwd=REPO_ROOT, capture_output=True, text=True, timeout=600, + check=False, ) if "database" in proc.stderr and proc.returncode: self.skipTest("database.json is not built") diff --git a/tests/test_large_file_cache.py b/tests/test_large_file_cache.py index 80656f21e..c78e79e98 100644 --- a/tests/test_large_file_cache.py +++ b/tests/test_large_file_cache.py @@ -23,12 +23,13 @@ import urllib.error from pathlib import Path from unittest import mock -REPO_ROOT = Path(__file__).resolve().parent.parent -sys.path.insert(0, str(REPO_ROOT / "scripts")) +sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "scripts")) -import common # noqa: E402 +import common import largefiles -import check_release_assets # noqa: E402 +import check_release_assets + +REPO_ROOT = Path(__file__).resolve().parent.parent PAYLOAD_A = b"A" * (256 * 1024) PAYLOAD_B = b"B" * (256 * 1024) diff --git a/tests/test_launcher_gaps.py b/tests/test_launcher_gaps.py index 77e16d58f..3e698b321 100644 --- a/tests/test_launcher_gaps.py +++ b/tests/test_launcher_gaps.py @@ -273,6 +273,7 @@ class LauncherGapTest(unittest.TestCase): "--platforms-dir", self.platforms_dir, "--emulators-dir", self.emulators_dir, "--db", str(db_path), "--json"], cwd=ROOT, capture_output=True, text=True, timeout=300, + check=False, ) self.assertEqual(result.returncode, 0, result.stderr) report = json.loads(result.stdout) diff --git a/tests/test_mame_ref_audit.py b/tests/test_mame_ref_audit.py index 7f6113739..210381ab8 100644 --- a/tests/test_mame_ref_audit.py +++ b/tests/test_mame_ref_audit.py @@ -14,12 +14,13 @@ import tempfile import unittest from pathlib import Path -ROOT = Path(__file__).resolve().parent.parent -sys.path.insert(0, str(ROOT / "scripts")) +sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "scripts")) import mame_ref_audit from mame_ref_audit import declares +ROOT = Path(__file__).resolve().parent.parent + DRIVER = [ "// a driver file", diff --git a/tests/test_measurements.py b/tests/test_measurements.py index c3f7ac589..61fb94f04 100644 --- a/tests/test_measurements.py +++ b/tests/test_measurements.py @@ -84,7 +84,7 @@ def full_record(emulator: str, subject: str, when: str, kind: str = "check", } if kind == "check": groups: dict[str, list[str]] = {} - for variant, value in zip(variants, values): + for variant, _value in zip(variants, values): key = json.dumps(variant["repetitions"][0]["observables"][observable], sort_keys=True) groups.setdefault(key, []).append(variant["label"]) record["check"] = { diff --git a/tests/test_no_case_collisions.py b/tests/test_no_case_collisions.py index a724cfca2..027b4df1b 100644 --- a/tests/test_no_case_collisions.py +++ b/tests/test_no_case_collisions.py @@ -42,6 +42,7 @@ class TestNoCaseCollisions(unittest.TestCase): listed = subprocess.run( ["git", "ls-files", "-z", "--", "bios"], cwd=REPO_ROOT, capture_output=True, text=True, + check=False, ) if listed.returncode != 0 or not listed.stdout: self.skipTest("not a git checkout with bios/") diff --git a/tests/test_pack_failures.py b/tests/test_pack_failures.py index 3296c9edc..d335377c7 100644 --- a/tests/test_pack_failures.py +++ b/tests/test_pack_failures.py @@ -47,11 +47,11 @@ class FailedPlatformFailsTheRun(unittest.TestCase): def test_pack_mode(self): with mock.patch.object(gp, "generate_pack", _boom), \ - mock.patch.object(gp, "verify_and_finalize_packs", return_value=True): - with self.assertRaises(SystemExit) as ctx: - gp._run_platform_packs( - self._args(), [(["retropie"], "retropie")], {}, {}, {}, {}, {}, None - ) + mock.patch.object(gp, "verify_and_finalize_packs", return_value=True), \ + self.assertRaises(SystemExit) as ctx: + gp._run_platform_packs( + self._args(), [(["retropie"], "retropie")], {}, {}, {}, {}, {}, None + ) self.assertEqual(ctx.exception.code, 1) def test_manifest_mode(self): diff --git a/tests/test_pack_integrity.py b/tests/test_pack_integrity.py index a7e7c704e..0fa857329 100644 --- a/tests/test_pack_integrity.py +++ b/tests/test_pack_integrity.py @@ -92,6 +92,7 @@ class PackIntegrityTest(unittest.TestCase): capture_output=True, text=True, cwd=REPO_ROOT, + check=False, ) if result.returncode == 0: return diff --git a/tests/test_profile_paths.py b/tests/test_profile_paths.py index eea16aea9..fd19be8f4 100644 --- a/tests/test_profile_paths.py +++ b/tests/test_profile_paths.py @@ -59,9 +59,11 @@ class StandaloneDestinations(unittest.TestCase): if not isinstance(entry, dict): continue dest = _destination(entry) - for folder in FRONTEND_FOLDERS: - if dest.startswith(folder) and folder not in allowed: - wrong.append(f"{name}: {entry.get('name')} at {dest}") + wrong.extend( + f"{name}: {entry.get('name')} at {dest}" + for folder in FRONTEND_FOLDERS + if dest.startswith(folder) and folder not in allowed + ) self.assertEqual(wrong, []) def test_every_allowed_folder_is_read(self): diff --git a/tests/test_profile_sync.py b/tests/test_profile_sync.py index cb6a005a2..cd2cde195 100644 --- a/tests/test_profile_sync.py +++ b/tests/test_profile_sync.py @@ -5099,9 +5099,10 @@ class TestRateLimitEndsOneProfile(unittest.TestCase): return_value={"cemu": {}, "after": {}}), \ mock.patch.object(profile_sync, "_check_quota"), \ mock.patch.object(profile_sync, "build_report", side_effect=build), \ - contextlib.redirect_stdout(out), contextlib.redirect_stderr(err): - with self.assertRaises(SystemExit) as caught: - profile_sync.main() + contextlib.redirect_stdout(out), \ + contextlib.redirect_stderr(err), \ + self.assertRaises(SystemExit) as caught: + profile_sync.main() finally: sys.argv = saved self.assertEqual(caught.exception.code, 1) @@ -5316,9 +5317,10 @@ class TestOutputModesApplyTheirFlags(unittest.TestCase): return_value={"clean": {}, "drift": {}}), \ mock.patch.object(profile_sync, "_check_quota"), \ mock.patch.object(profile_sync, "build_report", side_effect=build), \ - contextlib.redirect_stdout(out), contextlib.redirect_stderr(io.StringIO()): - with self.assertRaises(SystemExit) as caught: - profile_sync.main() + contextlib.redirect_stdout(out), \ + contextlib.redirect_stderr(io.StringIO()), \ + self.assertRaises(SystemExit) as caught: + profile_sync.main() finally: sys.argv = saved self.assertEqual(caught.exception.code, 1) diff --git a/tests/test_prose_style.py b/tests/test_prose_style.py index b31e1dc36..715580712 100644 --- a/tests/test_prose_style.py +++ b/tests/test_prose_style.py @@ -368,8 +368,10 @@ class NoClauseSemicolons(unittest.TestCase): offenders = [] for path in files: text = path.read_text(encoding="utf-8") - for line in _semicolons(extract(text)): - offenders.append(f"{path.relative_to(ROOT)}: {line[:100]}") + offenders.extend( + f"{path.relative_to(ROOT)}: {line[:100]}" + for line in _semicolons(extract(text)) + ) self.assertEqual(offenders, [], "\n".join(offenders[:40])) def test_markdown(self): @@ -405,9 +407,11 @@ class NoClauseSemicolons(unittest.TestCase): offenders = [] for page in sorted((ROOT / "wiki").glob("*.md")): text = FENCED.sub("", page.read_text(encoding="utf-8")) - for title in re.findall(r"(?m)^#{1,4} (.+)$", text): - if _sentence_case(title) != title: - offenders.append(f"{page.name}: {title}") + offenders.extend( + f"{page.name}: {title}" + for title in re.findall(r"(?m)^#{1,4} (.+)$", text) + if _sentence_case(title) != title + ) self.assertEqual(offenders, [], "\n".join(offenders)) def test_yaml_prose_and_comments(self): @@ -441,8 +445,10 @@ class NoClauseSemicolons(unittest.TestCase): offenders = [] for path in sorted((ROOT / "schemas").glob("*.json")): text = path.read_text(encoding="utf-8") - for line in _semicolons(text) + GLYPHS.findall(text): - offenders.append(f"{path.relative_to(ROOT)}: {line[:100]}") + offenders.extend( + f"{path.relative_to(ROOT)}: {line[:100]}" + for line in _semicolons(text) + GLYPHS.findall(text) + ) self.assertEqual(offenders, [], "\n".join(offenders)) diff --git a/tests/test_region.py b/tests/test_region.py index bb3303d4a..280ed9675 100644 --- a/tests/test_region.py +++ b/tests/test_region.py @@ -571,11 +571,11 @@ class TestProfileConformance(unittest.TestCase): f"{os.path.basename(path)}: {f.get('name')} not a list" ) continue - for value in raw: - if value not in region.REGIONS: - offenders.append( - f"{os.path.basename(path)}: {f.get('name')} -> {value!r}" - ) + offenders.extend( + f"{os.path.basename(path)}: {f.get('name')} -> {value!r}" + for value in raw + if value not in region.REGIONS + ) self.assertEqual(offenders, [], "\n".join(offenders)) def test_index_builds_over_every_repo_profile(self): diff --git a/tests/test_release_packs.py b/tests/test_release_packs.py index 87a8cb5b0..16b4c5ef8 100644 --- a/tests/test_release_packs.py +++ b/tests/test_release_packs.py @@ -209,6 +209,7 @@ class APlatformWithoutAPackFailsNoCheck(unittest.TestCase): [sys.executable, "scripts/generate_pack.py", "--all", "--verify-packs", "--output-dir", directory], capture_output=True, text=True, cwd=REPO_ROOT, timeout=600, + check=False, ) swept = {line.split(":")[0].strip() for line in proc.stdout.splitlines() if "SKIP (no pack in" in line} diff --git a/tests/test_romfolders_es.py b/tests/test_romfolders_es.py index bb75a8576..b2b3abb99 100644 --- a/tests/test_romfolders_es.py +++ b/tests/test_romfolders_es.py @@ -16,8 +16,7 @@ import sys import unittest from pathlib import Path -ROOT = Path(__file__).resolve().parent.parent -sys.path.insert(0, str(ROOT / "scripts")) +sys.path.insert(0, str(Path(__file__).resolve().parent.parent / "scripts")) from romfolders import setup_paths, split_refs from scraper.romfolders import ( @@ -30,6 +29,8 @@ from scraper.romfolders import ( from scraper.romfolders.__main__ import dump_setup from scraper.romfolders.es import _module_valid +ROOT = Path(__file__).resolve().parent.parent + FIXTURES = ROOT / "tests" / "fixtures" / "romfolders" / "es" ROMFOLDERS = ROOT / "platforms" / "romfolders" ES_SETUPS = ( diff --git a/tests/test_shipped_content.py b/tests/test_shipped_content.py index 1e368df9a..860edc874 100644 --- a/tests/test_shipped_content.py +++ b/tests/test_shipped_content.py @@ -17,6 +17,7 @@ from __future__ import annotations import tests # noqa: F401 offline, scratch under tmp/, the suite's own cache +import contextlib import hashlib import json import os @@ -116,10 +117,8 @@ class ShippedFilesSatisfyTheirDeclaration(unittest.TestCase): # md5_composite computes and what the resolver matches on. # A variant carries its hash after the extension # (cdimono1.zip.e6714b3d), so the name is not the test. - try: + with contextlib.suppress(zipfile.BadZipFile, OSError): digests["md5"].append(common.md5_composite(str(blob_path))) - except (zipfile.BadZipFile, OSError): - pass # A declared MD5 can be shorter than 32 characters: compare by prefix. satisfied = any( all( diff --git a/tests/test_site_console_folders.py b/tests/test_site_console_folders.py index 9d3a895ce..8a207d6e7 100644 --- a/tests/test_site_console_folders.py +++ b/tests/test_site_console_folders.py @@ -47,6 +47,7 @@ class OneFolderPerConsole(unittest.TestCase): listed = subprocess.run( ["git", "ls-files", "-z", "--", "bios"], cwd=REPO_ROOT, capture_output=True, text=True, + check=False, ) if listed.returncode != 0 or not listed.stdout: self.skipTest("not a git checkout with bios/") diff --git a/tests/test_site_content_data.py b/tests/test_site_content_data.py index 8345a0a54..0f0b684e2 100644 --- a/tests/test_site_content_data.py +++ b/tests/test_site_content_data.py @@ -135,9 +135,11 @@ class NoPlatformProseInScripts(unittest.TestCase): scripts = REPO_ROOT / "scripts" for path in [scripts / name for name in _RENDERERS] + sorted(scripts.glob("site*.py")): for number, line in enumerate(path.read_text(encoding="utf-8").splitlines(), 1): - for match in _PLATFORM_BRANCH.finditer(line): - if (match.group(1) or match.group(2)) in platforms: - found.append(f"{path.name}:{number}: {line.strip()}") + found.extend( + f"{path.name}:{number}: {line.strip()}" + for match in _PLATFORM_BRANCH.finditer(line) + if (match.group(1) or match.group(2)) in platforms + ) self.assertEqual(found, [], "a guide field says what one platform needs") diff --git a/tests/test_site_entry.py b/tests/test_site_entry.py index 1fbfb1a1a..e4ecde35a 100644 --- a/tests/test_site_entry.py +++ b/tests/test_site_entry.py @@ -767,8 +767,7 @@ class EveryHandheldRowSaysWhere(unittest.TestCase): text = _plain_page(HANDHELDS.path) for system in HANDHELDS.systems: row = next(line for line in text.splitlines() - if line.startswith(f"| {system.name} |") - or line.startswith(f"| {system.name}, ")) + if line.startswith((f"| {system.name} |", f"| {system.name}, "))) with self.subTest(system=system.name): self.assertEqual(generate_site.LINUX_ONLY_HINT in row, system.linux_only) self.assertTrue(any(s.linux_only for s in HANDHELDS.systems if s.name == "ArchR")) diff --git a/tests/test_site_exports.py b/tests/test_site_exports.py index df9562bce..45ee451e7 100644 --- a/tests/test_site_exports.py +++ b/tests/test_site_exports.py @@ -390,8 +390,8 @@ class AFlaggedDumpIsNotVerified(unittest.TestCase): "tosec": {"name": "Sony PlayStation BIOS (v2.2)(Sony)(JP)[b].bin"}, "redump": {"name": "SCPH-5000 BIOS v2.2"}, }, "../") - tosec = next(l for l in lines if "TOSEC" in l) - redump = next(l for l in lines if "Redump" in l) + tosec = next(line for line in lines if "TOSEC" in line) + redump = next(line for line in lines if "Redump" in line) self.assertIn("rb-badge-warning", tosec) self.assertIn("bad dump", tosec) self.assertIn("(JP)[b].bin", tosec) diff --git a/tests/test_site_handheld.py b/tests/test_site_handheld.py index 42ef85b2d..bf06f3bfa 100644 --- a/tests/test_site_handheld.py +++ b/tests/test_site_handheld.py @@ -68,9 +68,9 @@ class TheSiteServesTheLaunchers(unittest.TestCase): """build_port refuses an install.py the bootstraps do not pin: served, that launcher would refuse its own installer.""" with mock.patch.dict(sitehandheld._built, clear=True), \ - mock.patch.object(build_port, "pinned_installer_sha256", return_value="0" * 64): - with self.assertRaisesRegex(ValueError, "re-pin the bootstraps"): - sitehandheld.write_launchers(self.tmp / "public", REPO_ROOT) + mock.patch.object(build_port, "pinned_installer_sha256", return_value="0" * 64), \ + self.assertRaisesRegex(ValueError, "re-pin the bootstraps"): + sitehandheld.write_launchers(self.tmp / "public", REPO_ROOT) self.assertFalse(list((self.tmp / "public").rglob("RetroBIOS*"))) def test_every_archive_is_on_a_page_with_its_link_and_hash(self): diff --git a/tests/test_site_inputs.py b/tests/test_site_inputs.py index 0d08a5226..d262070bc 100644 --- a/tests/test_site_inputs.py +++ b/tests/test_site_inputs.py @@ -144,9 +144,11 @@ class NoPageModuleReadsTheRepositoryInputs(unittest.TestCase): "load_platform_config", "load_platform_registry", "load_emulator_profiles", "list_registered_platforms", "load_database", "extract_notes", "load_data_dir_registry"): - for arg in node.args: - if isinstance(arg, ast.Constant) and arg.value in self.INPUTS: - found.append(f"{module}:{node.lineno}") + found.extend( + f"{module}:{node.lineno}" + for arg in node.args + if isinstance(arg, ast.Constant) and arg.value in self.INPUTS + ) self.assertEqual(found, []) def test_generate_installs_the_inputs_first(self) -> None: diff --git a/tests/test_site_nav.py b/tests/test_site_nav.py index cda3ad846..a2e9f2816 100644 --- a/tests/test_site_nav.py +++ b/tests/test_site_nav.py @@ -657,11 +657,13 @@ class BuiltSearchAndCrumbs(unittest.TestCase): for path in (DIST / "systems").rglob("index.html"): # The search fields are attributes on empty spans. The title # meta reads the visible h1. - for match in re.finditer(r'<(\w+)[^>]*data-pagefind-meta="(?:files|aliases|devices|consoles|terms):' - r'[^>]*>([^<]*)', - path.read_text(encoding="utf-8")): - if match[2].strip(): - texts.append(str(path.relative_to(DIST))) + texts.extend( + str(path.relative_to(DIST)) + for match in re.finditer(r'<(\w+)[^>]*data-pagefind-meta="(?:files|aliases|devices|consoles|terms):' + r'[^>]*>([^<]*)', + path.read_text(encoding="utf-8")) + if match[2].strip() + ) self.assertEqual(texts, []) def test_a_setups_console_page_names_its_setup(self) -> None: diff --git a/tests/test_system_pack_parity.py b/tests/test_system_pack_parity.py index 289c3fe7e..7bdad8fb4 100644 --- a/tests/test_system_pack_parity.py +++ b/tests/test_system_pack_parity.py @@ -28,6 +28,7 @@ def _run(*argv: str) -> str: result = subprocess.run( [sys.executable, *argv], cwd=REPO_ROOT, capture_output=True, text=True, timeout=1800, + check=False, ) if result.returncode != 0: raise AssertionError(result.stdout + result.stderr) diff --git a/tests/test_system_selection.py b/tests/test_system_selection.py index 08af24ae4..4ffff0d77 100644 --- a/tests/test_system_selection.py +++ b/tests/test_system_selection.py @@ -266,7 +266,7 @@ class AMissingBiosDirIsRefused(unittest.TestCase): def _scripts_taking(flag: str) -> list[Path]: - pattern = re.compile(r'add_argument\(\s*"%s"' % re.escape(flag)) + pattern = re.compile(rf'add_argument\(\s*"{re.escape(flag)}"') return [ path for path in sorted((REPO_ROOT / "scripts").glob("*.py")) + sorted((REPO_ROOT / "scripts" / "scraper").glob("*.py")) @@ -734,12 +734,14 @@ class ListingsKeepTheirColumns(unittest.TestCase): listing = subprocess.run( [sys.executable, "scripts/generate_pack.py", "--platform", "retroarch", "--list-systems"], cwd=REPO_ROOT, capture_output=True, text=True, timeout=300, + check=False, ).stdout.splitlines() starts = {line.index("[") for line in listing if "[" in line} self.assertEqual(len(starts), 1, listing[:5]) emulators = subprocess.run( [sys.executable, "scripts/verify.py", "--list-emulators"], cwd=REPO_ROOT, capture_output=True, text=True, timeout=300, + check=False, ).stdout.splitlines() ends = {line.index("]") + 1 for line in emulators if "]" in line} tails = {len(line) - len(line[line.index("]") + 1:].lstrip()) diff --git a/tests/test_tool_messages.py b/tests/test_tool_messages.py index 21601cd10..c3f3f8f14 100644 --- a/tests/test_tool_messages.py +++ b/tests/test_tool_messages.py @@ -58,6 +58,7 @@ class ABuildbotNameSelectsItsProfile(unittest.TestCase): return subprocess.run( [sys.executable, "scripts/cross_reference.py", "--emulator", name], cwd=REPO_ROOT, capture_output=True, text=True, timeout=600, + check=False, ) by_core, by_profile = report("pcfx"), report("beetle_pcfx") self.assertEqual(by_core.returncode, 0, by_core.stderr) diff --git a/tests/test_upstream.py b/tests/test_upstream.py index 1b11229a2..ae7e444f1 100644 --- a/tests/test_upstream.py +++ b/tests/test_upstream.py @@ -379,9 +379,9 @@ class TestGoneUpstream(unittest.TestCase): self._serve(urllib.error.URLError( socket.gaierror(socket.EAI_NONAME, "Name or service not known") )) - with mock.patch.object(upstream, "_resolver_answers", return_value=True): - with self.assertRaises(upstream.GoneError): - upstream._fetch("https://host/x") + with mock.patch.object(upstream, "_resolver_answers", return_value=True), \ + self.assertRaises(upstream.GoneError): + upstream._fetch("https://host/x") self.assertEqual(self.calls, 1) self.assertEqual(self.slept, []) @@ -391,9 +391,9 @@ class TestGoneUpstream(unittest.TestCase): for errno, resolver in ((socket.EAI_NONAME, False), (socket.EAI_AGAIN, True)): with self.subTest(errno=errno, resolver=resolver): self._serve(urllib.error.URLError(socket.gaierror(errno, "no"))) - with mock.patch.object(upstream, "_resolver_answers", return_value=resolver): - with self.assertRaises(upstream.UpstreamError) as caught: - upstream._fetch("https://host/x") + with mock.patch.object(upstream, "_resolver_answers", return_value=resolver), \ + self.assertRaises(upstream.UpstreamError) as caught: + upstream._fetch("https://host/x") self.assertNotIsInstance(caught.exception, upstream.GoneError) def test_a_gone_error_is_still_an_upstream_error(self): @@ -1066,9 +1066,9 @@ class TestGitlabDirectoryArchive(unittest.TestCase): git.assert_called_once() def test_an_empty_archive_is_an_error_not_an_empty_directory(self): - with mock.patch.object(upstream, "_fetch", return_value=_tarball({"p/other/x": "y"})): - with self.assertRaises(upstream.UpstreamError): - upstream.cache_gitlab_directory(self.repo, "abc", "sys", self.tmp.name) + with mock.patch.object(upstream, "_fetch", return_value=_tarball({"p/other/x": "y"})), \ + self.assertRaises(upstream.UpstreamError): + upstream.cache_gitlab_directory(self.repo, "abc", "sys", self.tmp.name) if __name__ == "__main__": diff --git a/tests/test_validate_pr.py b/tests/test_validate_pr.py index b43cb8c4e..a4f2f5592 100644 --- a/tests/test_validate_pr.py +++ b/tests/test_validate_pr.py @@ -192,7 +192,7 @@ class ADeclaredFileBesideItsHeldNameIsAVariant(_Fixture): left the copy to land on the held file of that name.""" def test_place_copies_it_beside_the_held_name(self): - import hashlib # noqa: PLC0415 + import hashlib data = b"declared revision" emulators = self.tmp / "emulators" diff --git a/tests/test_verify_all_dir.py b/tests/test_verify_all_dir.py index cc2b325ee..815816cd7 100644 --- a/tests/test_verify_all_dir.py +++ b/tests/test_verify_all_dir.py @@ -35,6 +35,7 @@ class AllReadsTheGivenDirectory(unittest.TestCase): [sys.executable, "scripts/verify.py", "--all", "--platforms-dir", str(plat), "--json"], cwd=REPO_ROOT, capture_output=True, text=True, + check=False, ) self.assertEqual(run.returncode, 0, run.stderr[-2000:]) self.assertEqual(list(json.loads(run.stdout)), ["solo"])