chore: clear the ruff findings in tests

This commit is contained in:
Abdessamad Derraz committed 2026-11-17 07:21:28 +01:00
1 parent 382241fb1b
commit cc028fe7ee
49 files changed
+290 -183

No files matched your search

+3 -3
View File
@@ -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"
+19 -14
View File
@@ -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)
+8 -4
View File
@@ -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):
+55 -28
View File
@@ -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, [])
+2 -2
View File
@@ -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}),
+3 -2
View File
@@ -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 = """\
+5 -3
View File
@@ -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, [])
+3 -2
View File
@@ -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)
+6 -3
View File
@@ -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")
+36 -22
View File
@@ -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"(?<![\w-])(--[a-z][a-z0-9-]*)", command):
if f'"{option}"' not in source:
wrong.append(f"{name} {option}")
wrong.extend(
f"{name} {option}"
for option in re.findall(r"(?<![\w-])(--[a-z][a-z0-9-]*)", command)
if f'"{option}"' not in source
)
return sorted(set(wrong))
@@ -1324,6 +1332,7 @@ class CitedOptionsExist(unittest.TestCase):
proc = subprocess.run(
[*argv, *([sub] if sub else []), "--help"],
cwd=ROOT, capture_output=True, text=True, timeout=120,
check=False,
)
cls._helps[key] = proc.stdout if proc.returncode == 0 else ""
return cls._helps[key]
@@ -1520,9 +1529,11 @@ def stale_options(text: str, default: str | None) -> 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)
+7 -1
View File
@@ -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)
+11
View File
@@ -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)
+5 -1
View File
@@ -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)
+3 -2
View File
@@ -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)",
+1
View File
@@ -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:])
+7 -10
View File
@@ -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:
+1 -1
View File
@@ -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(
+9 -9
View File
@@ -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())
+6 -4
View File
@@ -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
+1 -1
View File
@@ -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):
+2 -1
View File
@@ -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)
+3 -3
View File
@@ -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")
+5 -4
View File
@@ -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)
+1
View File
@@ -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)
+3 -2
View File
@@ -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",
+1 -1
View File
@@ -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"] = {
+1
View File
@@ -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/")
+5 -5
View File
@@ -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):
+1
View File
@@ -92,6 +92,7 @@ class PackIntegrityTest(unittest.TestCase):
capture_output=True,
text=True,
cwd=REPO_ROOT,
check=False,
)
if result.returncode == 0:
return
+5 -3
View File
@@ -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):
+8 -6
View File
@@ -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)
+13 -7
View File
@@ -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))
+5 -5
View File
@@ -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):
+1
View File
@@ -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}
+3 -2
View File
@@ -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 = (
+2 -3
View File
@@ -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(
+1
View File
@@ -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/")
+5 -3
View File
@@ -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")
+1 -2
View File
@@ -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"))
+2 -2
View File
@@ -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)
+3 -3
View File
@@ -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):
+5 -3
View File
@@ -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:
+7 -5
View File
@@ -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'[^>]*>([^<]*)</\1>',
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'[^>]*>([^<]*)</\1>',
path.read_text(encoding="utf-8"))
if match[2].strip()
)
self.assertEqual(texts, [])
def test_a_setups_console_page_names_its_setup(self) -> None:
+1
View File
@@ -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)
+3 -1
View File
@@ -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())
+1
View File
@@ -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)
+9 -9
View File
@@ -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__":
+1 -1
View File
@@ -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"
+1
View File
@@ -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"])