mirror of
https://github.com/Abdess/retroarch_system.git
synced 2026-11-24 02:27:52 -06:00
chore: merge the test suite lint work
This commit is contained in:
commit
d7783cfbe4
61 files changed
+852
-584
No files matched your search
@@ -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"
|
||||
|
||||
@@ -85,56 +85,86 @@ def _hashes(values: object) -> set[str]:
|
||||
return {str(value).strip().lower() for value in raw if str(value).strip()}
|
||||
|
||||
|
||||
def _allowed_members() -> dict[str, set[str]]:
|
||||
from common import load_emulator_profiles
|
||||
from romset_recipes import load_dat_recipes
|
||||
|
||||
allowed: dict[str, set[str]] = defaultdict(set)
|
||||
for archive, per_label in load_dat_recipes(REPO_ROOT / "recipes").items():
|
||||
for recipe in per_label.values():
|
||||
allowed[archive.lower()] |= {crc for _name, crc in recipe}
|
||||
profiles = load_emulator_profiles(str(REPO_ROOT / "emulators"), skip_aliases=False)
|
||||
for profile in profiles.values():
|
||||
for entry in profile.get("files", []) or []:
|
||||
crcs = {
|
||||
str(member.get("crc32") or "").lower()
|
||||
for member in entry.get("contents") or []
|
||||
}
|
||||
crcs.discard("")
|
||||
if not crcs:
|
||||
continue
|
||||
for name in [entry.get("name", "")] + list(entry.get("aliases") or []):
|
||||
if name:
|
||||
allowed[str(name).lower()] |= crcs
|
||||
for name, devices in DEVICE_ROMS.items():
|
||||
for device in devices:
|
||||
allowed[name] |= allowed.get(device, set())
|
||||
return allowed
|
||||
|
||||
|
||||
def _platform_pins() -> tuple[set[str], dict[str, set[tuple[str, str]]]]:
|
||||
from common import list_registered_platforms, load_platform_config
|
||||
|
||||
pinned: set[str] = set()
|
||||
zipped: dict[str, set[tuple[str, str]]] = defaultdict(set)
|
||||
platforms_dir = str(REPO_ROOT / "platforms")
|
||||
for platform in list_registered_platforms(platforms_dir):
|
||||
config = load_platform_config(platform, platforms_dir)
|
||||
for system in config.get("systems", {}).values():
|
||||
for entry in system.get("files", []) or []:
|
||||
if entry.get("zipped_file"):
|
||||
for md5 in _hashes(entry.get("md5")):
|
||||
zipped[str(entry.get("name", "")).lower()].add(
|
||||
(str(entry["zipped_file"]).casefold(), md5)
|
||||
)
|
||||
continue
|
||||
for key in ("md5", "sha1", "alt_md5"):
|
||||
pinned |= _hashes(entry.get(key))
|
||||
return pinned, zipped
|
||||
|
||||
|
||||
def _extra_members(
|
||||
path: Path, name: str, allowed: set[str], zipped: set[tuple[str, str]]
|
||||
) -> list[zipfile.ZipInfo] | None:
|
||||
stem = name[:-4]
|
||||
try:
|
||||
with zipfile.ZipFile(path) as archive:
|
||||
extra = [
|
||||
info for info in archive.infolist()
|
||||
if not info.is_dir()
|
||||
and f"{info.CRC:08x}" not in allowed
|
||||
# a merged set keeps each clone in a folder of its name
|
||||
and not ("/" in info.filename and info.filename.split("/")[0] != stem)
|
||||
]
|
||||
return [
|
||||
info for info in extra
|
||||
if (info.filename.casefold(),
|
||||
hashlib.md5(archive.read(info)).hexdigest()) not in zipped
|
||||
]
|
||||
except zipfile.BadZipFile:
|
||||
return None
|
||||
|
||||
|
||||
class HeldArchivesMatchTheirRecipes(unittest.TestCase):
|
||||
def test_no_member_outside_every_recipe_of_the_name(self):
|
||||
bios = REPO_ROOT / "bios"
|
||||
if not bios.is_dir() or not (REPO_ROOT / "recipes").is_dir():
|
||||
self.skipTest("bios/ or recipes/ is not present")
|
||||
from common import (
|
||||
list_registered_platforms,
|
||||
load_emulator_profiles,
|
||||
load_platform_config,
|
||||
variant_base_name,
|
||||
)
|
||||
from common import variant_base_name
|
||||
from hashing import md5_composite_of
|
||||
from romset_recipes import load_dat_recipes
|
||||
|
||||
allowed: dict[str, set[str]] = defaultdict(set)
|
||||
for archive, per_label in load_dat_recipes(REPO_ROOT / "recipes").items():
|
||||
for recipe in per_label.values():
|
||||
allowed[archive.lower()] |= {crc for _name, crc in recipe}
|
||||
profiles = load_emulator_profiles(str(REPO_ROOT / "emulators"), skip_aliases=False)
|
||||
for profile in profiles.values():
|
||||
for entry in profile.get("files", []) or []:
|
||||
crcs = {
|
||||
str(member.get("crc32") or "").lower()
|
||||
for member in entry.get("contents") or []
|
||||
}
|
||||
crcs.discard("")
|
||||
if not crcs:
|
||||
continue
|
||||
for name in [entry.get("name", "")] + list(entry.get("aliases") or []):
|
||||
if name:
|
||||
allowed[str(name).lower()] |= crcs
|
||||
for name, devices in DEVICE_ROMS.items():
|
||||
for device in devices:
|
||||
allowed[name] |= allowed.get(device, set())
|
||||
|
||||
pinned: set[str] = set()
|
||||
zipped: dict[str, set[tuple[str, str]]] = defaultdict(set)
|
||||
platforms_dir = str(REPO_ROOT / "platforms")
|
||||
for platform in list_registered_platforms(platforms_dir):
|
||||
config = load_platform_config(platform, platforms_dir)
|
||||
for system in config.get("systems", {}).values():
|
||||
for entry in system.get("files", []) or []:
|
||||
if entry.get("zipped_file"):
|
||||
for md5 in _hashes(entry.get("md5")):
|
||||
zipped[str(entry.get("name", "")).lower()].add(
|
||||
(str(entry["zipped_file"]).casefold(), md5)
|
||||
)
|
||||
continue
|
||||
for key in ("md5", "sha1", "alt_md5"):
|
||||
pinned |= _hashes(entry.get(key))
|
||||
allowed = _allowed_members()
|
||||
pinned, zipped = _platform_pins()
|
||||
|
||||
offenders = []
|
||||
for path in sorted(bios.rglob("*")):
|
||||
@@ -143,22 +173,8 @@ class HeldArchivesMatchTheirRecipes(unittest.TestCase):
|
||||
continue
|
||||
if path.parent.name in NOT_ROMSETS:
|
||||
continue
|
||||
stem = name[:-4]
|
||||
try:
|
||||
with zipfile.ZipFile(path) as archive:
|
||||
extra = [
|
||||
info for info in archive.infolist()
|
||||
if not info.is_dir()
|
||||
and f"{info.CRC:08x}" not in allowed[name]
|
||||
# a merged set keeps each clone in a folder of its name
|
||||
and not ("/" in info.filename and info.filename.split("/")[0] != stem)
|
||||
]
|
||||
extra = [
|
||||
info for info in extra
|
||||
if (info.filename.casefold(),
|
||||
hashlib.md5(archive.read(info)).hexdigest()) not in zipped[name]
|
||||
]
|
||||
except zipfile.BadZipFile:
|
||||
extra = _extra_members(path, name, allowed[name], zipped[name])
|
||||
if extra is None:
|
||||
continue
|
||||
if len(extra) < MIN_EXTRA or str(path.relative_to(REPO_ROOT)) in KEPT:
|
||||
continue
|
||||
|
||||
+19
-14
@@ -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)
|
||||
|
||||
@@ -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):
|
||||
|
||||
@@ -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, [])
|
||||
|
||||
|
||||
|
||||
@@ -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}),
|
||||
|
||||
@@ -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 = """\
|
||||
|
||||
@@ -173,7 +173,7 @@ class AmberelecCarriesTheMachines(unittest.TestCase):
|
||||
(full, src) for src, full in builder._data_directory_members(
|
||||
config.get("systems", {}), registry, "amberelec",
|
||||
config.get("base_destination", ""), False, set(), set(), set(),
|
||||
refs, core_trees=trees,
|
||||
refs_out=refs, core_trees=trees,
|
||||
)
|
||||
)
|
||||
finally:
|
||||
@@ -204,7 +204,7 @@ class TheCountLineKeepsTreesOutOfTheBaseline(unittest.TestCase):
|
||||
"myminui", "platforms", db, "bios", "tmp", offline=True, record=record,
|
||||
data_registry=common.load_data_dir_registry("platforms"),
|
||||
)
|
||||
line = next(l for l in out.getvalue().splitlines() if "files packed" in l)
|
||||
line = next(entry for entry in out.getvalue().splitlines() if "files packed" in entry)
|
||||
self.assertIn("(0 baseline + ", line)
|
||||
if record.trees:
|
||||
self.assertIn(f"+ {len(record.trees)} in core data trees + ", line)
|
||||
|
||||
@@ -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, [])
|
||||
|
||||
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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
@@ -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)
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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)",
|
||||
|
||||
@@ -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:])
|
||||
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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(
|
||||
|
||||
+72
-47
@@ -61,6 +61,52 @@ def _tempdir(test: unittest.TestCase) -> str:
|
||||
return path
|
||||
|
||||
|
||||
def _parenthesized_withs(tokens: list) -> list[str]:
|
||||
import tokenize
|
||||
|
||||
found = []
|
||||
for i, tok in enumerate(tokens):
|
||||
if tok.type == tokenize.NAME and tok.string == "with" and i + 1 < len(tokens):
|
||||
if tokens[i + 1].string != "(":
|
||||
continue
|
||||
depth = 0
|
||||
for inner in tokens[i + 1:]:
|
||||
if inner.string in "([{" and inner.type == tokenize.OP:
|
||||
depth += 1
|
||||
elif inner.string in ")]}" and inner.type == tokenize.OP:
|
||||
depth -= 1
|
||||
if depth == 0:
|
||||
break
|
||||
elif depth == 1 and inner.type == tokenize.NAME and inner.string == "as":
|
||||
found.append(f"line {tok.start[0]}: parenthesized with")
|
||||
break
|
||||
return found
|
||||
|
||||
|
||||
def _nested_fstrings(tokens: list) -> list[str]:
|
||||
import tokenize
|
||||
|
||||
found: list[str] = []
|
||||
fstring_start = getattr(tokenize, "FSTRING_START", None)
|
||||
if fstring_start is None:
|
||||
return found
|
||||
stack = []
|
||||
for tok in tokens:
|
||||
if tok.type == fstring_start:
|
||||
if stack:
|
||||
found.append(f"line {tok.start[0]}: f-string inside an f-string")
|
||||
stack.append(tok.string[-1])
|
||||
elif tok.type == tokenize.FSTRING_END:
|
||||
stack.pop()
|
||||
elif stack and tok.type == tokenize.STRING and stack[-1] in tok.string:
|
||||
found.append(f"line {tok.start[0]}: f-string reuses its quote")
|
||||
elif stack and tok.type == tokenize.FSTRING_MIDDLE:
|
||||
continue
|
||||
elif stack and tok.type == tokenize.ERRORTOKEN and tok.string == "\\":
|
||||
found.append(f"line {tok.start[0]}: backslash in an f-string field")
|
||||
return found
|
||||
|
||||
|
||||
class TestShellUnquote(unittest.TestCase):
|
||||
def test_plain_value(self):
|
||||
self.assertEqual(install._shell_unquote("/userdata/bios"), "/userdata/bios")
|
||||
@@ -1670,39 +1716,8 @@ class InstallerStaysOnPython38AndTheStdlib(unittest.TestCase):
|
||||
import io
|
||||
import tokenize
|
||||
|
||||
found = []
|
||||
tokens = list(tokenize.generate_tokens(io.StringIO(self.SOURCE).readline))
|
||||
for i, tok in enumerate(tokens):
|
||||
if tok.type == tokenize.NAME and tok.string == "with" and i + 1 < len(tokens):
|
||||
if tokens[i + 1].string != "(":
|
||||
continue
|
||||
depth = 0
|
||||
for inner in tokens[i + 1:]:
|
||||
if inner.string in "([{" and inner.type == tokenize.OP:
|
||||
depth += 1
|
||||
elif inner.string in ")]}" and inner.type == tokenize.OP:
|
||||
depth -= 1
|
||||
if depth == 0:
|
||||
break
|
||||
elif depth == 1 and inner.type == tokenize.NAME and inner.string == "as":
|
||||
found.append(f"line {tok.start[0]}: parenthesized with")
|
||||
break
|
||||
fstring_start = getattr(tokenize, "FSTRING_START", None)
|
||||
if fstring_start is not None:
|
||||
stack = []
|
||||
for tok in tokens:
|
||||
if tok.type == fstring_start:
|
||||
if stack:
|
||||
found.append(f"line {tok.start[0]}: f-string inside an f-string")
|
||||
stack.append(tok.string[-1])
|
||||
elif tok.type == tokenize.FSTRING_END:
|
||||
stack.pop()
|
||||
elif stack and tok.type == tokenize.STRING and stack[-1] in tok.string:
|
||||
found.append(f"line {tok.start[0]}: f-string reuses its quote")
|
||||
elif stack and tok.type == tokenize.FSTRING_MIDDLE:
|
||||
continue
|
||||
elif stack and tok.type == tokenize.ERRORTOKEN and tok.string == "\\":
|
||||
found.append(f"line {tok.start[0]}: backslash in an f-string field")
|
||||
found = _parenthesized_withs(tokens) + _nested_fstrings(tokens)
|
||||
self.assertEqual(found, [])
|
||||
|
||||
def test_no_runtime_generic_builtin(self):
|
||||
@@ -2194,9 +2209,9 @@ class TestManualPlatformPrompt(unittest.TestCase):
|
||||
def test_quit_stops_like_ctrl_c(self):
|
||||
"""`install.sh && retroarch` went on to start RetroArch with no BIOS
|
||||
after a q, which left with 0 where Ctrl+C leaves with 130."""
|
||||
with unittest.mock.patch("builtins.input", lambda _prompt="": "q"):
|
||||
with self.assertRaises(SystemExit) as raised:
|
||||
install._prompt_manual_platform("linux")
|
||||
with unittest.mock.patch("builtins.input", lambda _prompt="": "q"), \
|
||||
self.assertRaises(SystemExit) as raised:
|
||||
install._prompt_manual_platform("linux")
|
||||
self.assertEqual(raised.exception.code, install.QUIT_CODE)
|
||||
|
||||
def test_quotes_around_a_typed_folder_are_dropped(self):
|
||||
@@ -2207,7 +2222,8 @@ class TestManualPlatformPrompt(unittest.TestCase):
|
||||
f' "{root}/My Card/bios" '):
|
||||
answers = iter(["1", typed])
|
||||
with self.subTest(typed=typed), \
|
||||
unittest.mock.patch("builtins.input", lambda _prompt="": next(answers)), \
|
||||
unittest.mock.patch("builtins.input",
|
||||
lambda _prompt="", answers=answers: next(answers)), \
|
||||
contextlib.redirect_stdout(io.StringIO()):
|
||||
chosen = install._prompt_manual_platform("linux")
|
||||
self.assertEqual(chosen, [("retroarch", root / "My Card" / "bios")])
|
||||
@@ -2217,7 +2233,8 @@ class TestManualPlatformPrompt(unittest.TestCase):
|
||||
answers = iter(["1", '"~/$RB_TEST_DIR/bios"'])
|
||||
with self.subTest(os_type=os_type), \
|
||||
unittest.mock.patch.dict(os.environ, {"RB_TEST_DIR": "cards"}), \
|
||||
unittest.mock.patch("builtins.input", lambda _prompt="": next(answers)), \
|
||||
unittest.mock.patch("builtins.input",
|
||||
lambda _prompt="", answers=answers: next(answers)), \
|
||||
contextlib.redirect_stdout(io.StringIO()):
|
||||
chosen = install._prompt_manual_platform(os_type)
|
||||
self.assertEqual(chosen[0][1], Path.home() / "cards" / "bios")
|
||||
@@ -2313,6 +2330,7 @@ class TestLaunchboxDetectionPowershell(unittest.TestCase):
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=60,
|
||||
check=False,
|
||||
)
|
||||
finally:
|
||||
httpd.shutdown()
|
||||
@@ -2576,6 +2594,7 @@ class TestAvailablePlatforms(unittest.TestCase):
|
||||
capture_output=True,
|
||||
text=True,
|
||||
timeout=30,
|
||||
check=False,
|
||||
)
|
||||
self.assertEqual(proc.returncode, 0, proc.stdout + proc.stderr)
|
||||
self.assertTrue(marker.is_file(), "piped bootstrap did not download install.py")
|
||||
@@ -2693,7 +2712,7 @@ class TestAvailablePlatforms(unittest.TestCase):
|
||||
proc = subprocess.run(
|
||||
[shutil.which("sh"), str(root / "install.sh")],
|
||||
env={"PATH": f"{fake_bin}{os.pathsep}{tools}", "HOME": str(root)},
|
||||
capture_output=True, text=True, timeout=60, stdin=subprocess.DEVNULL)
|
||||
capture_output=True, text=True, timeout=60, stdin=subprocess.DEVNULL, check=False)
|
||||
self.assertEqual(proc.returncode, 0, proc.stdout + proc.stderr)
|
||||
self.assertIn("ran True", proc.stdout)
|
||||
|
||||
@@ -3174,7 +3193,7 @@ class TermuxStorageIsSetUpByTheBootstrap(unittest.TestCase):
|
||||
f"TERMUX_VERSION=0.118 /bin/sh {shlex.quote(str(root / 'install.sh'))}")
|
||||
proc = subprocess.run(
|
||||
[shutil.which("script"), "-qec", command, "/dev/null"],
|
||||
capture_output=True, text=True, timeout=120, stdin=subprocess.DEVNULL)
|
||||
capture_output=True, text=True, timeout=120, stdin=subprocess.DEVNULL, check=False)
|
||||
return proc, root
|
||||
|
||||
def test_it_runs_once_then_the_installer(self):
|
||||
@@ -3209,7 +3228,7 @@ class APyLauncherWithoutARuntimeIsPassed(unittest.TestCase):
|
||||
proc = subprocess.run(
|
||||
[shutil.which("pwsh"), "-NoProfile", "-File", str(folder / "install.ps1")],
|
||||
env={**os.environ, "PATH": f"{fake_bin}{os.pathsep}/usr/bin/nonexistent"},
|
||||
capture_output=True, text=True, timeout=120, stdin=subprocess.DEVNULL)
|
||||
capture_output=True, text=True, timeout=120, stdin=subprocess.DEVNULL, check=False)
|
||||
self.assertEqual(proc.returncode, 0, proc.stdout + proc.stderr)
|
||||
self.assertIn("installer ran", proc.stdout)
|
||||
|
||||
@@ -3231,7 +3250,7 @@ class APowerShellDownloadThatNeverAnswersEnds(unittest.TestCase):
|
||||
["pwsh", "-NoProfile", "-File", str(folder / "install.ps1"), "--check"],
|
||||
env={**os.environ,
|
||||
"RETROBIOS_INSTALL_URL": f"https://127.0.0.1:{port}/install.py"},
|
||||
capture_output=True, text=True, timeout=150, stdin=subprocess.DEVNULL)
|
||||
capture_output=True, text=True, timeout=150, stdin=subprocess.DEVNULL, check=False)
|
||||
self.assertLess(time.monotonic() - started, 120)
|
||||
self.assertNotEqual(proc.returncode, 0)
|
||||
self.assertIn("could not be downloaded", " ".join((proc.stdout + proc.stderr).split()))
|
||||
@@ -3251,6 +3270,7 @@ class ThePowerShellWrapperPassesTheStatusOn(unittest.TestCase):
|
||||
proc = subprocess.run(
|
||||
["pwsh", "-NoProfile", "-File", str(folder / "install.ps1")],
|
||||
capture_output=True, text=True, timeout=120,
|
||||
check=False,
|
||||
)
|
||||
self.assertEqual(proc.returncode, code, proc.stderr)
|
||||
self.assertNotIn("installer failed", proc.stdout + proc.stderr)
|
||||
@@ -3274,6 +3294,7 @@ class ThePowerShellWrapperPassesEveryArgument(unittest.TestCase):
|
||||
proc = subprocess.run(
|
||||
["pwsh", "-NoProfile", "-File", str(folder / "install.ps1"), *args],
|
||||
capture_output=True, text=True, timeout=120,
|
||||
check=False,
|
||||
)
|
||||
self.assertEqual(proc.returncode, 0, proc.stderr)
|
||||
self.assertEqual(json.loads(proc.stdout), args)
|
||||
@@ -3707,7 +3728,7 @@ class ACardPreparedOnAComputerGetsItsBoard(unittest.TestCase):
|
||||
[sys.executable, "-c", code, str(REPO_ROOT), str(self.boot),
|
||||
"--platform", "batocera", "--dest", str(self.share), "--manifest",
|
||||
str(self.list), "--offline", "--check", "--events", *extra],
|
||||
env=env, capture_output=True, text=True, timeout=120, stdin=subprocess.DEVNULL)
|
||||
env=env, capture_output=True, text=True, timeout=120, stdin=subprocess.DEVNULL, check=False)
|
||||
events = [json.loads(line) for line in proc.stdout.splitlines()
|
||||
if line.startswith("{")]
|
||||
return proc.stdout + proc.stderr, events
|
||||
@@ -3795,7 +3816,7 @@ class APlatformWithoutTargetsSaysSoOffline(unittest.TestCase):
|
||||
[sys.executable, str(REPO_ROOT / "install.py"), "--platform", "misterfpga",
|
||||
"--dest", str(dest), "--target", "de10-nano", "--offline", "--no-input",
|
||||
"--dry-run", *extra],
|
||||
capture_output=True, text=True, timeout=120, stdin=subprocess.DEVNULL)
|
||||
capture_output=True, text=True, timeout=120, stdin=subprocess.DEVNULL, check=False)
|
||||
self.assertEqual(proc.returncode, 2, proc.stderr)
|
||||
self.assertIn("MiSTer FPGA has no hardware targets", proc.stderr)
|
||||
self.assertNotIn("targets/misterfpga.json", proc.stderr)
|
||||
@@ -3893,6 +3914,7 @@ class TheBoardTheSystemNamesIsTheTarget(unittest.TestCase):
|
||||
[sys.executable, str(REPO_ROOT / "install.py"), "--every-board",
|
||||
"--target", "bcm2711", "--platform", "batocera", "--dry-run"],
|
||||
capture_output=True, text=True, timeout=120,
|
||||
check=False,
|
||||
)
|
||||
self.assertEqual(result.returncode, 2)
|
||||
self.assertIn("--every-board", result.stderr)
|
||||
@@ -4837,7 +4859,10 @@ class WindowsSeenFromWsl(unittest.TestCase):
|
||||
self.assertEqual(os.environ["USERPROFILE"], str(self.root / "c" / "Users" / "me"))
|
||||
self.assertEqual(os.environ["APPDATA"],
|
||||
str(self.root / "c" / "Users" / "me" / "AppData" / "Roaming"))
|
||||
self.assertEqual(os.environ["ProgramFiles"], "")
|
||||
# ProgramFiles among them: cmd answered %ProgramFiles% unexpanded.
|
||||
for name in sorted(set(install._WINDOWS_VARIABLES) - answers.keys()):
|
||||
with self.subTest(variable=name):
|
||||
self.assertEqual(os.environ[name], "")
|
||||
|
||||
|
||||
def test_a_steam_client_outside_program_files_is_found(self):
|
||||
@@ -5331,7 +5356,7 @@ class AnUnknownNameIsAnEvent(unittest.TestCase):
|
||||
[sys.executable, str(REPO_ROOT / "install.py"), "--dest", dest,
|
||||
"--check", "--events", "--no-input", *argv],
|
||||
env=env, capture_output=True, text=True, timeout=120,
|
||||
stdin=subprocess.DEVNULL)
|
||||
stdin=subprocess.DEVNULL, check=False)
|
||||
return proc.returncode, [json.loads(line) for line in proc.stdout.splitlines()]
|
||||
|
||||
def test_each_refusal_says_why(self):
|
||||
@@ -5653,7 +5678,7 @@ class ThePowerShellOneLinerLeavesTheSessionAlone(unittest.TestCase):
|
||||
env = {**os.environ, "RETROBIOS_INSTALL_URL": "http://127.0.0.1/install.py"}
|
||||
env.pop("RETROBIOS_BOOTSTRAP", None)
|
||||
proc = subprocess.run(["pwsh", "-NoProfile", "-Command", script], cwd=REPO_ROOT,
|
||||
env=env, capture_output=True, text=True, timeout=120)
|
||||
env=env, capture_output=True, text=True, timeout=120, check=False)
|
||||
self.assertIn("must use HTTPS", proc.stderr)
|
||||
self.assertIn("EAP=Continue temporary=[] installer=[] bootstrap=[]", proc.stdout)
|
||||
|
||||
@@ -7217,7 +7242,7 @@ class AStrippedPythonIsNamed(unittest.TestCase):
|
||||
return subprocess.run(
|
||||
[sys.executable, "-c", code, str(REPO_ROOT / "install.py"), *argv],
|
||||
env=env, capture_output=True, text=True, timeout=60,
|
||||
stdin=subprocess.DEVNULL)
|
||||
stdin=subprocess.DEVNULL, check=False)
|
||||
|
||||
def test_a_missing_c_module_is_named(self):
|
||||
for hidden in ("zlib", "unicodedata"):
|
||||
|
||||
@@ -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())
|
||||
|
||||
@@ -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
|
||||
|
||||
|
||||
@@ -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):
|
||||
|
||||
@@ -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)
|
||||
|
||||
|
||||
|
||||
@@ -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")
|
||||
|
||||
@@ -41,6 +41,8 @@ from pathlib import Path, PurePosixPath, PureWindowsPath
|
||||
from unittest import mock
|
||||
|
||||
REPO_ROOT = Path(__file__).resolve().parent.parent
|
||||
# install.py runs on 3.8, the scripts it is compared with need 3.9.
|
||||
BUILDER_FLOOR = (3, 9)
|
||||
sys.path.insert(0, str(REPO_ROOT))
|
||||
sys.path.insert(0, str(REPO_ROOT / "tests"))
|
||||
|
||||
@@ -949,6 +951,13 @@ class Widgets(unittest.TestCase):
|
||||
|
||||
def golden_states() -> dict:
|
||||
"""One state per screen, filled as a run fills it."""
|
||||
states = _golden_setup_states()
|
||||
states.update(_golden_plan_states())
|
||||
states.update(_golden_run_states())
|
||||
return states
|
||||
|
||||
|
||||
def _golden_setup_states() -> dict:
|
||||
states = {}
|
||||
states["setup"] = fresh_state()
|
||||
states["setup"].notes = ["ES-DE found: its BIOS files go to each emulator, not to "
|
||||
@@ -985,6 +994,11 @@ def golden_states() -> dict:
|
||||
checking.platform, checking.dest, checking.stack = "retroarch", SYSTEM_DIR, ["checking"]
|
||||
checking.manifest, checking.started, checking.now = MANIFEST, 10.0, 14.2
|
||||
states["checking"] = checking
|
||||
return states
|
||||
|
||||
|
||||
def _golden_plan_states() -> dict:
|
||||
states = {}
|
||||
states["plan"] = checked_state()
|
||||
done = checked_state()
|
||||
done.check = {**CHECK, "present": 5, "missing": 0, "wrong_hash": 0, "bytes_needed": 0,
|
||||
@@ -1039,6 +1053,11 @@ def golden_states() -> dict:
|
||||
confirm.dry = {**CHECK, "files": 1, "present": 0, "missing": 1, "wrong_hash": 0,
|
||||
"bytes_needed": 16384, "not_installable": 0}
|
||||
states["confirm"] = confirm
|
||||
return states
|
||||
|
||||
|
||||
def _golden_run_states() -> dict:
|
||||
states = {}
|
||||
installing = checked_state()
|
||||
installing.stack.append("installing")
|
||||
installing.run, installing.running = "install", True
|
||||
@@ -2509,7 +2528,7 @@ class WorkFolders(unittest.TestCase):
|
||||
self.addCleanup(signal.signal, number, previous)
|
||||
interrupt = signal.getsignal(signal.SIGINT)
|
||||
|
||||
def starting(*_args, **_kwargs):
|
||||
def starting(*_args, number=number, **_kwargs):
|
||||
os.kill(os.getpid(), number)
|
||||
return fresh_state(), [("fetch", "retroarch")]
|
||||
|
||||
@@ -2521,7 +2540,7 @@ class WorkFolders(unittest.TestCase):
|
||||
with mock.patch.object(install, "_TuiTerminal", self.Terminal), \
|
||||
mock.patch.object(install.tempfile, "mkdtemp", return_value=str(work)), \
|
||||
mock.patch.object(self.Terminal, "enter",
|
||||
lambda _t: entered.append(True)), \
|
||||
lambda _t, entered=entered: entered.append(True)), \
|
||||
mock.patch.object(install, "tui_start", side_effect=starting), \
|
||||
mock.patch.object(install, "_open_local_sources"), \
|
||||
mock.patch.object(install, "_tui_fetch") as fetch, \
|
||||
@@ -7597,7 +7616,7 @@ class _CardFixtures:
|
||||
listing = self.root / f"{plat}.json"
|
||||
install_list = {"manifest_version": 2, "platform": plat, "files": files}
|
||||
listing.write_text(json.dumps(install_list))
|
||||
if sys.version_info < (3, 9):
|
||||
if sys.version_info < BUILDER_FLOOR:
|
||||
# generate_pack.py's context managers need Python 3.9.
|
||||
return listing, None, {}
|
||||
sys.path.insert(0, str(REPO_ROOT / "scripts"))
|
||||
@@ -7725,7 +7744,7 @@ class _LineModeFindings(_CardFixtures):
|
||||
region=["us"])
|
||||
self.assertEqual(code, 0, text)
|
||||
|
||||
@unittest.skipIf(sys.version_info < (3, 9),
|
||||
@unittest.skipIf(sys.version_info < BUILDER_FLOOR,
|
||||
"generate_pack.py's context managers need Python 3.9")
|
||||
def test_a_pack_names_its_list_only_when_that_list_records_it(self):
|
||||
"""A MinUI pack sent --core to install/minui.json,
|
||||
@@ -9225,7 +9244,7 @@ class PacksWordingAndDocs(unittest.TestCase):
|
||||
|
||||
# a pack's own list records its systems.
|
||||
|
||||
@unittest.skipIf(sys.version_info < (3, 9),
|
||||
@unittest.skipIf(sys.version_info < BUILDER_FLOOR,
|
||||
"generate_pack.py's context managers need Python 3.9")
|
||||
def test_a_pack_records_the_systems_of_its_files(self):
|
||||
sys.path.insert(0, str(REPO_ROOT / "scripts"))
|
||||
@@ -14673,7 +14692,7 @@ class ProvenCardsAndCounts(unittest.TestCase):
|
||||
|
||||
# Root cause 6: the pages say what the installer shows.
|
||||
|
||||
@unittest.skipIf(sys.version_info < (3, 9),
|
||||
@unittest.skipIf(sys.version_info < BUILDER_FLOOR,
|
||||
"the site generator needs Python 3.9")
|
||||
def test_which_pack_names_the_first_screen(self):
|
||||
"""Which-pack said the command opens a screen
|
||||
@@ -16148,7 +16167,7 @@ class EmulatorChoiceMatchesTheEmulatorPack(unittest.TestCase):
|
||||
db_path = REPO_ROOT / "database.json"
|
||||
if not db_path.exists():
|
||||
raise unittest.SkipTest("database.json is not built")
|
||||
if sys.version_info < (3, 9):
|
||||
if sys.version_info < BUILDER_FLOOR:
|
||||
# The builder's floor: install.py alone keeps 3.8.
|
||||
raise unittest.SkipTest("generate_pack.py needs Python 3.9 or newer")
|
||||
sys.path.insert(0, str(REPO_ROOT / "scripts"))
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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",
|
||||
|
||||
@@ -68,8 +68,11 @@ class AnEntryWithoutSourceIsAnOmission(unittest.TestCase):
|
||||
with mock.patch.object(gp, "compute_hashes", return_value=hashes):
|
||||
gp._manifest_core_entries(
|
||||
[extra], {}, self.db, str(REPO_ROOT / "bios"), "", str(REPO_ROOT),
|
||||
{}, True, set(), False, set(), set(), set(), files, {},
|
||||
record, pack_only, SelectionIndex.build({}, {}, {}, []),
|
||||
{}, True,
|
||||
region_drops=set(), case_insensitive=False, seen_destinations=set(),
|
||||
seen_lower=set(), seen_parents=set(), manifest_files=files,
|
||||
omitted_by_destination={}, record_omission=record,
|
||||
pack_only_sizes=pack_only, selection=SelectionIndex.build({}, {}, {}, []),
|
||||
)
|
||||
return files, omitted, pack_only
|
||||
|
||||
|
||||
@@ -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"] = {
|
||||
|
||||
@@ -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/")
|
||||
|
||||
@@ -9,10 +9,12 @@ from __future__ import annotations
|
||||
|
||||
import tests # noqa: F401 offline, scratch under tmp/, the suite's own cache
|
||||
|
||||
import ast
|
||||
import re
|
||||
import subprocess
|
||||
import sys
|
||||
import unittest
|
||||
from collections.abc import Iterator
|
||||
from pathlib import Path
|
||||
|
||||
REPO_ROOT = Path(__file__).resolve().parent.parent
|
||||
@@ -69,6 +71,47 @@ MAINTENANCE_TOOLS = {
|
||||
}
|
||||
|
||||
|
||||
def _is_type_checking(test: ast.expr) -> bool:
|
||||
if isinstance(test, ast.Name):
|
||||
return test.id == "TYPE_CHECKING"
|
||||
return (isinstance(test, ast.Attribute) and test.attr == "TYPE_CHECKING"
|
||||
and isinstance(test.value, ast.Name) and test.value.id == "typing")
|
||||
|
||||
|
||||
def _runtime_nodes(node: ast.AST) -> Iterator[ast.AST]:
|
||||
"""Every node that can run: the body of an `if TYPE_CHECKING:` never does."""
|
||||
yield node
|
||||
for child in ast.iter_child_nodes(node):
|
||||
if isinstance(child, ast.If) and _is_type_checking(child.test):
|
||||
for branch in child.orelse:
|
||||
yield from _runtime_nodes(branch)
|
||||
continue
|
||||
yield from _runtime_nodes(child)
|
||||
|
||||
|
||||
def _foreign_imports(source: str, file_name: str, local: set[str]) -> list[str]:
|
||||
"""The top-level packages a script imports at run time beyond the
|
||||
standard library, pyyaml and the repository's own modules."""
|
||||
allowed = {"yaml"}
|
||||
found = []
|
||||
for node in _runtime_nodes(ast.parse(source)):
|
||||
if isinstance(node, ast.Import):
|
||||
names = [a.name.split(".")[0] for a in node.names]
|
||||
elif isinstance(node, ast.ImportFrom) and node.level == 0 and node.module:
|
||||
names = [node.module.split(".")[0]]
|
||||
else:
|
||||
continue
|
||||
for name in names:
|
||||
if name in sys.stdlib_module_names or name in local or name in allowed:
|
||||
continue
|
||||
if name == "jsonschema" and file_name == "validate_schemas.py":
|
||||
continue
|
||||
if MAINTENANCE_TOOLS.get(file_name) == name:
|
||||
continue
|
||||
found.append(name)
|
||||
return found
|
||||
|
||||
|
||||
class ScriptsNeedOnlyPyyaml(unittest.TestCase):
|
||||
"""The build scripts need the standard library and pyyaml. jsonschema is
|
||||
validate_schemas.py's alone. CI installs jsonschema with its whole tree
|
||||
@@ -76,8 +119,6 @@ class ScriptsNeedOnlyPyyaml(unittest.TestCase):
|
||||
there and fail for a contributor following the documented setup."""
|
||||
|
||||
def test_no_script_imports_another_package(self):
|
||||
import ast
|
||||
|
||||
scripts = Path(__file__).resolve().parents[1] / "scripts"
|
||||
local = {p.stem for p in scripts.rglob("*.py")} | {
|
||||
p.name for p in scripts.iterdir() if p.is_dir()
|
||||
@@ -85,26 +126,35 @@ class ScriptsNeedOnlyPyyaml(unittest.TestCase):
|
||||
# install.py is the repository's own single file, stdlib only (its
|
||||
# tests hold it to that): generate_games_index reads its narrowing.
|
||||
local.add("install")
|
||||
allowed = {"yaml"}
|
||||
found = []
|
||||
for path in sorted(scripts.rglob("*.py")):
|
||||
for node in ast.walk(ast.parse(path.read_text(encoding="utf-8"))):
|
||||
if isinstance(node, ast.Import):
|
||||
names = [a.name.split(".")[0] for a in node.names]
|
||||
elif isinstance(node, ast.ImportFrom) and node.level == 0 and node.module:
|
||||
names = [node.module.split(".")[0]]
|
||||
else:
|
||||
continue
|
||||
for name in names:
|
||||
if name in sys.stdlib_module_names or name in local or name in allowed:
|
||||
continue
|
||||
if name == "jsonschema" and path.name == "validate_schemas.py":
|
||||
continue
|
||||
if MAINTENANCE_TOOLS.get(path.name) == name:
|
||||
continue
|
||||
found.append(f"{path.relative_to(scripts)}: {name}")
|
||||
found = [
|
||||
f"{path.relative_to(scripts)}: {name}"
|
||||
for path in sorted(scripts.rglob("*.py"))
|
||||
for name in _foreign_imports(path.read_text(encoding="utf-8"), path.name, local)
|
||||
]
|
||||
self.assertEqual(found, [])
|
||||
|
||||
def test_an_import_only_a_type_checker_runs_is_no_dependency(self):
|
||||
guarded = (
|
||||
"from typing import TYPE_CHECKING\n"
|
||||
"import typing\n"
|
||||
"if TYPE_CHECKING:\n"
|
||||
" from typing_extensions import Unpack\n"
|
||||
"if typing.TYPE_CHECKING:\n"
|
||||
" import typing_extensions\n"
|
||||
)
|
||||
self.assertEqual(_foreign_imports(guarded, "x.py", set()), [])
|
||||
self.assertEqual(_foreign_imports("import typing_extensions\n", "x.py", set()),
|
||||
["typing_extensions"])
|
||||
# The else branch of the guard runs: it stays a dependency.
|
||||
branch = (
|
||||
"from typing import TYPE_CHECKING\n"
|
||||
"if TYPE_CHECKING:\n"
|
||||
" pass\n"
|
||||
"else:\n"
|
||||
" import typing_extensions\n"
|
||||
)
|
||||
self.assertEqual(_foreign_imports(branch, "x.py", set()), ["typing_extensions"])
|
||||
|
||||
|
||||
class TheDownloaderRunsWithoutPyyaml(unittest.TestCase):
|
||||
"""download.py is the documented Windows downloader, "stdlib only". It
|
||||
|
||||
@@ -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):
|
||||
|
||||
@@ -34,7 +34,8 @@ class SlotPassReadsTheRegionGrouping(unittest.TestCase):
|
||||
config = load_platform_config("retroarch", "platforms")
|
||||
drops, _fallbacks, _undecided = gp._select_variants(
|
||||
config, config["systems"], "emulators", db,
|
||||
config.get("base_destination", ""), profiles, None, "full", None, True,
|
||||
config.get("base_destination", ""), profiles, None, "full",
|
||||
regions=None, one_per_slot=True,
|
||||
)
|
||||
names = {os.path.basename(d) for d in drops}
|
||||
for name in ("jp_mcd1_9111.bin", "eu_mcd1_9210.bin"):
|
||||
@@ -68,7 +69,7 @@ class VariantGroupSpansSystems(unittest.TestCase):
|
||||
drops, _fallbacks, _undecided = gp._select_variants(
|
||||
config, config["systems"], "emulators", db,
|
||||
config.get("base_destination", ""), profiles, None, "full",
|
||||
region_mod.parse_requested("us"), False,
|
||||
regions=region_mod.parse_requested("us"), one_per_slot=False,
|
||||
)
|
||||
names = {os.path.basename(d) for d in drops}
|
||||
for name in ("jp_mcd1_9111.bin", "eu_mcd2_9306.bin"):
|
||||
|
||||
@@ -92,6 +92,7 @@ class PackIntegrityTest(unittest.TestCase):
|
||||
capture_output=True,
|
||||
text=True,
|
||||
cwd=REPO_ROOT,
|
||||
check=False,
|
||||
)
|
||||
if result.returncode == 0:
|
||||
return
|
||||
|
||||
+19
-13
@@ -124,6 +124,15 @@ class HeldPinsReadTheirBuildFileAgain(unittest.TestCase):
|
||||
self.assertEqual(row.items, ["raine"])
|
||||
|
||||
|
||||
def _names_the_pin(value: str, profile: dict, source: str, pins: set, versions: set) -> bool:
|
||||
if profile.get("pin_follows"):
|
||||
# A build of the branch tip names the repository it
|
||||
# clones, at no revision: RetroPie's advmame.
|
||||
return value.split()[-1].rstrip("/").removesuffix(".git") == source
|
||||
token = value.split()[-1].rsplit("/", 1)[-1].removesuffix(".tar.gz")
|
||||
return value in pins or any(token in v or v in value for v in versions)
|
||||
|
||||
|
||||
class EveryBuildReferenceNamesThePin(unittest.TestCase):
|
||||
"""Reads the repository: a pin_build value is what the platform builds,
|
||||
so it is the profile's source_commit or names its core_version, and the
|
||||
@@ -147,23 +156,20 @@ class EveryBuildReferenceNamesThePin(unittest.TestCase):
|
||||
|
||||
source = str(profile.get("source") or "").rstrip("/").removesuffix(".git")
|
||||
|
||||
def names_it(value: str) -> bool:
|
||||
if profile.get("pin_follows"):
|
||||
# A build of the branch tip names the repository it
|
||||
# clones, at no revision: RetroPie's advmame.
|
||||
return value.split()[-1].rstrip("/").removesuffix(".git") == source
|
||||
token = value.split()[-1].rsplit("/", 1)[-1].removesuffix(".tar.gz")
|
||||
return value in pins or any(token in v or v in value for v in versions)
|
||||
|
||||
# A reference that only dates a config_reads entry names the build
|
||||
# the platform reads that file at, not this profile's pin.
|
||||
justifies_pin = profile.get("pin_frozen") or profile.get("pin_follows")
|
||||
if justifies_pin and not any(names_it(str(r["value"])) for r in references):
|
||||
if justifies_pin and not any(
|
||||
_names_the_pin(str(r["value"]), profile, source, pins, versions)
|
||||
for r in references
|
||||
):
|
||||
disagree.append(name)
|
||||
for reference in references:
|
||||
if not cf.pin_build_revision(reference, REPO_ROOT / "platforms"):
|
||||
disagree.append(f"{name}: {reference['platform']} is not read from "
|
||||
f"{reference['repo']}")
|
||||
disagree.extend(
|
||||
f"{name}: {reference['platform']} is not read from "
|
||||
f"{reference['repo']}"
|
||||
for reference in references
|
||||
if not cf.pin_build_revision(reference, REPO_ROOT / "platforms")
|
||||
)
|
||||
self.assertEqual(disagree, [])
|
||||
|
||||
|
||||
|
||||
@@ -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):
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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))
|
||||
|
||||
|
||||
|
||||
@@ -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):
|
||||
|
||||
@@ -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}
|
||||
|
||||
@@ -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 = (
|
||||
|
||||
@@ -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(
|
||||
|
||||
@@ -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/")
|
||||
|
||||
@@ -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")
|
||||
|
||||
|
||||
|
||||
+166
-127
@@ -151,6 +151,164 @@ def guide_part(markdown: str) -> str:
|
||||
return markdown[: match.start()] if match else markdown
|
||||
|
||||
|
||||
class _PageParser:
|
||||
"""The state parse() carries from one line to the next."""
|
||||
|
||||
def __init__(self) -> None:
|
||||
self.page = Page()
|
||||
self.seen_words = 0
|
||||
self.details = 0 # depth of collapsed blocks
|
||||
self.tab = 0 # the tab of a group being read, 0 outside a group
|
||||
self.fence: str | None = None
|
||||
self.current: list[str] = []
|
||||
self.kind = "paragraph"
|
||||
self.run = 0
|
||||
|
||||
def flush(self) -> None:
|
||||
page = self.page
|
||||
if self.current:
|
||||
body = strip_inline(" ".join(self.current))
|
||||
if WORD.search(body):
|
||||
kind = self.kind
|
||||
term = page.blocks[-1].text.lower() if kind == "definition" and page.blocks else ""
|
||||
block = Block(kind, body, self.details > 0, term, self.tab > 1)
|
||||
page.blocks.append(block)
|
||||
if (page.before_action is None and not block.collapsed
|
||||
and not block.hidden and kind not in ("table", "heading")):
|
||||
self.seen_words += count_words(body)
|
||||
self.current = []
|
||||
if self.kind in ("item", "definition", "heading"):
|
||||
self.kind = "paragraph"
|
||||
|
||||
def act(self) -> None:
|
||||
self.flush()
|
||||
if self.page.before_action is None:
|
||||
self.page.before_action = self.seen_words
|
||||
|
||||
def end_run(self) -> None:
|
||||
if self.run:
|
||||
self.page.list_runs.append(self.run)
|
||||
self.run = 0
|
||||
|
||||
def feed(self, raw: str) -> None:
|
||||
line = raw.rstrip()
|
||||
stripped = line.strip()
|
||||
indent = len(line) - len(line.lstrip())
|
||||
if self.fence:
|
||||
if stripped.startswith(self.fence):
|
||||
self.fence = None
|
||||
return
|
||||
if self._markup(stripped):
|
||||
return
|
||||
if stripped.startswith("#"):
|
||||
self._heading(stripped)
|
||||
return
|
||||
if stripped.startswith("|"):
|
||||
self._table_row(stripped)
|
||||
return
|
||||
self._prose(stripped, indent)
|
||||
|
||||
def _markup(self, stripped: str) -> bool:
|
||||
"""Fences, blank lines and HTML: True when the line is consumed."""
|
||||
if stripped.startswith(("```", "~~~")):
|
||||
self.fence = stripped[:3]
|
||||
if self.tab < 2:
|
||||
self.act()
|
||||
return True
|
||||
if not stripped:
|
||||
self.flush()
|
||||
return True
|
||||
if stripped.startswith("import ") and stripped.endswith(";"):
|
||||
return True
|
||||
if stripped.startswith(":::"):
|
||||
self.flush()
|
||||
return True
|
||||
if self._container(stripped):
|
||||
return True
|
||||
if "rb-button" in stripped or "rb-tile" in stripped or stripped.startswith(
|
||||
("<FilePicker", "<WantedFiles")):
|
||||
self.act()
|
||||
return True
|
||||
if re.match(r"</?(?!abbr\b|a\b|code\b|strong\b|em\b)[A-Za-z]", stripped):
|
||||
self.flush()
|
||||
return True
|
||||
return False
|
||||
|
||||
def _container(self, stripped: str) -> bool:
|
||||
"""Collapsed blocks and tab groups: True when the line is consumed."""
|
||||
if stripped.startswith("<details"):
|
||||
self.flush()
|
||||
self.details += 1
|
||||
return True
|
||||
if stripped.startswith("</details>"):
|
||||
self.flush()
|
||||
self.details = max(0, self.details - 1)
|
||||
return True
|
||||
if stripped.startswith("<Tabs"):
|
||||
self.flush()
|
||||
self.tab = 0
|
||||
return True
|
||||
if stripped.startswith("<TabItem"):
|
||||
self.flush()
|
||||
self.tab += 1
|
||||
return True
|
||||
if stripped.startswith("</Tabs>"):
|
||||
self.flush()
|
||||
self.tab = 0
|
||||
return True
|
||||
return False
|
||||
|
||||
def _heading(self, stripped: str) -> None:
|
||||
self.flush()
|
||||
self.end_run()
|
||||
self.kind = "heading"
|
||||
self.current = [re.sub(r"\s*\{[^}]*\}\s*$", "", stripped.lstrip("#").strip())]
|
||||
self.flush()
|
||||
self.kind = "paragraph"
|
||||
|
||||
def _table_row(self, stripped: str) -> None:
|
||||
if self.kind != "table":
|
||||
self.flush()
|
||||
self.kind = "table"
|
||||
if not re.fullmatch(r"\|[\s:|-]+\|?", stripped):
|
||||
self.current.append(stripped.replace("|", " "))
|
||||
|
||||
def _prose(self, stripped: str, indent: int) -> None:
|
||||
if self.kind == "table":
|
||||
self.flush()
|
||||
self.kind = "paragraph"
|
||||
item = re.match(r"(?:[-*+]|\d+\.)\s+(.*)", stripped)
|
||||
definition = re.match(r":\s+(.*)", stripped)
|
||||
if item:
|
||||
self.flush()
|
||||
self.kind = "item"
|
||||
self.run += 1
|
||||
self.current = [item.group(1)]
|
||||
return
|
||||
if definition:
|
||||
self.flush()
|
||||
page = self.page
|
||||
if page.blocks and page.blocks[-1].kind == "paragraph":
|
||||
page.blocks[-1].kind = "term"
|
||||
self.kind = "definition"
|
||||
self.current = [definition.group(1)]
|
||||
return
|
||||
if self.kind == "item" and indent == 0:
|
||||
self.flush()
|
||||
self.kind = "paragraph"
|
||||
if self.kind == "paragraph":
|
||||
self.end_run()
|
||||
if not self.current and self.kind in ("item", "definition") and indent == 0:
|
||||
self.kind = "paragraph"
|
||||
self.current.append(stripped)
|
||||
|
||||
def finish(self) -> Page:
|
||||
self.flush()
|
||||
if self.run:
|
||||
self.page.list_runs.append(self.run)
|
||||
return self.page
|
||||
|
||||
|
||||
def parse(markdown: str) -> Page:
|
||||
"""Blocks of prose a reader sees, code and HTML left out.
|
||||
|
||||
@@ -161,131 +319,10 @@ def parse(markdown: str) -> Page:
|
||||
text = guide_part(markdown)
|
||||
text = re.sub(r"<script.*?</script>", "", text, flags=re.S)
|
||||
text = re.sub(r"<!--.*?-->", "", text, flags=re.S)
|
||||
page = Page()
|
||||
seen_words = 0
|
||||
details = 0 # depth of collapsed blocks
|
||||
tab = 0 # the tab of a group being read, 0 outside a group
|
||||
fence: str | None = None
|
||||
current: list[str] = []
|
||||
kind = "paragraph"
|
||||
run = 0
|
||||
|
||||
def flush() -> None:
|
||||
nonlocal current, seen_words, kind
|
||||
if current:
|
||||
body = strip_inline(" ".join(current))
|
||||
if WORD.search(body):
|
||||
term = page.blocks[-1].text.lower() if kind == "definition" and page.blocks else ""
|
||||
block = Block(kind, body, details > 0, term, tab > 1)
|
||||
page.blocks.append(block)
|
||||
if (page.before_action is None and not block.collapsed
|
||||
and not block.hidden and kind not in ("table", "heading")):
|
||||
seen_words += count_words(body)
|
||||
current = []
|
||||
if kind in ("item", "definition", "heading"):
|
||||
kind = "paragraph"
|
||||
|
||||
def act() -> None:
|
||||
flush()
|
||||
if page.before_action is None:
|
||||
page.before_action = seen_words
|
||||
|
||||
parser = _PageParser()
|
||||
for raw in text.splitlines():
|
||||
line = raw.rstrip()
|
||||
stripped = line.strip()
|
||||
indent = len(line) - len(line.lstrip())
|
||||
if fence:
|
||||
if stripped.startswith(fence):
|
||||
fence = None
|
||||
continue
|
||||
if stripped.startswith(("```", "~~~")):
|
||||
fence = stripped[:3]
|
||||
if tab < 2:
|
||||
act()
|
||||
continue
|
||||
if not stripped:
|
||||
flush()
|
||||
continue
|
||||
if stripped.startswith("import ") and stripped.endswith(";"):
|
||||
continue
|
||||
if stripped.startswith(":::"):
|
||||
flush()
|
||||
continue
|
||||
if stripped.startswith("<details"):
|
||||
flush()
|
||||
details += 1
|
||||
continue
|
||||
if stripped.startswith("</details>"):
|
||||
flush()
|
||||
details = max(0, details - 1)
|
||||
continue
|
||||
if stripped.startswith("<Tabs"):
|
||||
flush()
|
||||
tab = 0
|
||||
continue
|
||||
if stripped.startswith("<TabItem"):
|
||||
flush()
|
||||
tab += 1
|
||||
continue
|
||||
if stripped.startswith("</Tabs>"):
|
||||
flush()
|
||||
tab = 0
|
||||
continue
|
||||
if "rb-button" in stripped or "rb-tile" in stripped or stripped.startswith(
|
||||
("<FilePicker", "<WantedFiles")):
|
||||
act()
|
||||
continue
|
||||
if re.match(r"</?(?!abbr\b|a\b|code\b|strong\b|em\b)[A-Za-z]", stripped):
|
||||
flush()
|
||||
continue
|
||||
if stripped.startswith("#"):
|
||||
flush()
|
||||
if run:
|
||||
page.list_runs.append(run)
|
||||
run = 0
|
||||
kind = "heading"
|
||||
current = [re.sub(r"\s*\{[^}]*\}\s*$", "", stripped.lstrip("#").strip())]
|
||||
flush()
|
||||
kind = "paragraph"
|
||||
continue
|
||||
if stripped.startswith("|"):
|
||||
if kind != "table":
|
||||
flush()
|
||||
kind = "table"
|
||||
if not re.fullmatch(r"\|[\s:|-]+\|?", stripped):
|
||||
current.append(stripped.replace("|", " "))
|
||||
continue
|
||||
if kind == "table":
|
||||
flush()
|
||||
kind = "paragraph"
|
||||
item = re.match(r"(?:[-*+]|\d+\.)\s+(.*)", stripped)
|
||||
definition = re.match(r":\s+(.*)", stripped)
|
||||
if item:
|
||||
flush()
|
||||
kind = "item"
|
||||
run += 1
|
||||
current = [item.group(1)]
|
||||
continue
|
||||
if definition:
|
||||
flush()
|
||||
if page.blocks and page.blocks[-1].kind == "paragraph":
|
||||
page.blocks[-1].kind = "term"
|
||||
kind = "definition"
|
||||
current = [definition.group(1)]
|
||||
continue
|
||||
if kind == "item" and indent == 0:
|
||||
flush()
|
||||
kind = "paragraph"
|
||||
if kind == "paragraph" and run:
|
||||
page.list_runs.append(run)
|
||||
run = 0
|
||||
if not current and kind in ("item", "definition") and indent == 0:
|
||||
kind = "paragraph"
|
||||
current.append(stripped)
|
||||
flush()
|
||||
if run:
|
||||
page.list_runs.append(run)
|
||||
return page
|
||||
parser.feed(raw)
|
||||
return parser.finish()
|
||||
|
||||
|
||||
def banned(block: Block, level: str) -> list[str]:
|
||||
@@ -298,9 +335,11 @@ def banned(block: Block, level: str) -> list[str]:
|
||||
return []
|
||||
for sentence in split_sentences(text) or [text]:
|
||||
lower = sentence.lower()
|
||||
for phrase in FILLER:
|
||||
if re.search(rf"(?<![\w-]){re.escape(phrase)}(?![\w-])", lower):
|
||||
found.append(phrase)
|
||||
found.extend(
|
||||
phrase
|
||||
for phrase in FILLER
|
||||
if re.search(rf"(?<![\w-]){re.escape(phrase)}(?![\w-])", lower)
|
||||
)
|
||||
terms = dict(JARGON)
|
||||
if level == "start":
|
||||
terms.update(START_ONLY)
|
||||
|
||||
@@ -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"))
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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):
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -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:
|
||||
|
||||
@@ -20,6 +20,7 @@ import json
|
||||
import os
|
||||
import sys
|
||||
import unittest
|
||||
from collections.abc import Iterable
|
||||
from pathlib import Path
|
||||
|
||||
REPO_ROOT = Path(__file__).resolve().parents[1]
|
||||
@@ -89,6 +90,57 @@ def _archives_held(fe: dict, db: dict) -> set[str]:
|
||||
return held
|
||||
|
||||
|
||||
def _entries_by_system(platforms: list[dict], profiles: dict) -> dict[str, list[dict]]:
|
||||
entries: dict[str, list[dict]] = {}
|
||||
for config in platforms:
|
||||
for sys_id, system in config.get("systems", {}).items():
|
||||
entries.setdefault(sys_id, []).extend(system.get("files") or [])
|
||||
for profile in profiles.values():
|
||||
systems = [str(s) for s in profile.get("systems") or []]
|
||||
for fe in profile.get("files") or []:
|
||||
if not isinstance(fe, dict):
|
||||
continue
|
||||
owners = {str(fe["system"])} if fe.get("system") else set()
|
||||
owners.update(str(s) for s in fe.get("systems") or [])
|
||||
if not owners and len(systems) == 1:
|
||||
owners = set(systems)
|
||||
for owner in owners:
|
||||
entries.setdefault(owner, []).append(fe)
|
||||
return entries
|
||||
|
||||
|
||||
def _held_sections(
|
||||
ids: Iterable[str], entries: dict[str, list[dict]], board_sections: dict, db: dict
|
||||
) -> dict[str, set[tuple[str, str]]]:
|
||||
"""Id -> the (manufacturer, console) sections holding its files."""
|
||||
from common import resolve_local_file
|
||||
|
||||
# Where each content has a card.
|
||||
places: dict[str, set[tuple[str, str, str]]] = {}
|
||||
for mfr, consoles in board_sections.items():
|
||||
for console, files in consoles.items():
|
||||
for f in files:
|
||||
places.setdefault(f["sha1"], set()).add((mfr, console, f["name"]))
|
||||
by_path = {entry.get("path"): sha1 for sha1, entry in db["files"].items()}
|
||||
held: dict[str, set[tuple[str, str]]] = {}
|
||||
for sys_id in ids:
|
||||
sections: set[tuple[str, str]] = set()
|
||||
for fe in entries.get(sys_id, []):
|
||||
if fe.get("category") == "bios_zip":
|
||||
for sha1 in _archives_held(fe, db):
|
||||
sections.update((m, c) for m, c, _ in places.get(sha1, set()))
|
||||
continue
|
||||
local, status = resolve_local_file(fe, db)
|
||||
if not _accepts(fe, local, status):
|
||||
continue
|
||||
sha1 = by_path.get(local)
|
||||
if sha1 is not None:
|
||||
sections.update((m, c) for m, c, _ in places.get(sha1, set()))
|
||||
if sections:
|
||||
held[sys_id] = sections
|
||||
return held
|
||||
|
||||
|
||||
@unittest.skipUnless((REPO_ROOT / "database.json").exists(), "database.json is not built")
|
||||
class SystemLinks(unittest.TestCase):
|
||||
|
||||
@@ -101,7 +153,6 @@ class SystemLinks(unittest.TestCase):
|
||||
list_registered_platforms,
|
||||
load_emulator_profiles,
|
||||
load_platform_config,
|
||||
resolve_local_file,
|
||||
)
|
||||
from generate_site import _group_by_manufacturer, arcade_board_sections
|
||||
|
||||
@@ -124,46 +175,9 @@ class SystemLinks(unittest.TestCase):
|
||||
]
|
||||
cls.ids = siterender.system_ids(profiles, platforms)
|
||||
|
||||
entries: dict[str, list[dict]] = {}
|
||||
for config in platforms:
|
||||
for sys_id, system in config.get("systems", {}).items():
|
||||
entries.setdefault(sys_id, []).extend(system.get("files") or [])
|
||||
for profile in profiles.values():
|
||||
systems = [str(s) for s in profile.get("systems") or []]
|
||||
for fe in profile.get("files") or []:
|
||||
if not isinstance(fe, dict):
|
||||
continue
|
||||
owners = {str(fe["system"])} if fe.get("system") else set()
|
||||
owners.update(str(s) for s in fe.get("systems") or [])
|
||||
if not owners and len(systems) == 1:
|
||||
owners = set(systems)
|
||||
for owner in owners:
|
||||
entries.setdefault(owner, []).append(fe)
|
||||
|
||||
# Where each content has a card.
|
||||
places: dict[str, set[tuple[str, str, str]]] = {}
|
||||
for mfr, consoles in cls.sections.items():
|
||||
for console, files in consoles.items():
|
||||
for f in files:
|
||||
places.setdefault(f["sha1"], set()).add((mfr, console, f["name"]))
|
||||
by_path = {entry.get("path"): sha1 for sha1, entry in db["files"].items()}
|
||||
# Id -> the (manufacturer, console) sections holding its files.
|
||||
cls.held: dict[str, set[tuple[str, str]]] = {}
|
||||
for sys_id in cls.ids:
|
||||
sections: set[tuple[str, str]] = set()
|
||||
for fe in entries.get(sys_id, []):
|
||||
if fe.get("category") == "bios_zip":
|
||||
for sha1 in _archives_held(fe, db):
|
||||
sections.update((m, c) for m, c, _ in places.get(sha1, set()))
|
||||
continue
|
||||
local, status = resolve_local_file(fe, db)
|
||||
if not _accepts(fe, local, status):
|
||||
continue
|
||||
sha1 = by_path.get(local)
|
||||
if sha1 is not None:
|
||||
sections.update((m, c) for m, c, _ in places.get(sha1, set()))
|
||||
if sections:
|
||||
cls.held[sys_id] = sections
|
||||
entries = _entries_by_system(platforms, profiles)
|
||||
cls.held: dict[str, set[tuple[str, str]]] = _held_sections(
|
||||
cls.ids, entries, cls.sections, db)
|
||||
finally:
|
||||
os.chdir(previous)
|
||||
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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())
|
||||
|
||||
@@ -33,6 +33,57 @@ def _refuse(*_args, **_kwargs):
|
||||
raise urllib.error.HTTPError("https://api.github.com/x", 403, "rate limited", {}, None)
|
||||
|
||||
|
||||
class _Body:
|
||||
def __init__(self, body: str | bytes):
|
||||
self.body = body.encode() if isinstance(body, str) else body
|
||||
|
||||
def __enter__(self):
|
||||
return self
|
||||
|
||||
def __exit__(self, *exc):
|
||||
return False
|
||||
|
||||
def read(self):
|
||||
return self.body
|
||||
|
||||
|
||||
def _serve_batocera(boards: list[str], refuse_board: bool):
|
||||
def urlopen(request, *_a, **_k):
|
||||
url = request.full_url
|
||||
if "/tags" in url:
|
||||
return _Body(b'[{"name": "batocera-43"}]')
|
||||
if "/contents/configs" in url:
|
||||
return _Body(json.dumps([{"name": b} for b in boards]).encode())
|
||||
if "/contents/buildroot" in url:
|
||||
return _Body(b'{"sha": "0123abc"}')
|
||||
if url.endswith("x86_wow64.board"):
|
||||
# Builds the 32-bit Wine package, not an image.
|
||||
return _Body(b"BR2_PACKAGE_BATOCERA_TARGET_X86=y\n")
|
||||
if url.endswith(".board"):
|
||||
if refuse_board:
|
||||
_refuse()
|
||||
return _Body(b"BR2_PACKAGE_BATOCERA_TARGET_X86_64=y\n"
|
||||
b"BR2_PACKAGE_BATOCERA_SYSTEM=y\n")
|
||||
if "/git/trees/" in url:
|
||||
return _Body(b'{"tree": [], "truncated": false}')
|
||||
if url.endswith("retroarch.mk"):
|
||||
return _Body(b"RETROARCH_CONF_OPTS = --enable-networking\n")
|
||||
if url.startswith("https://raw.githubusercontent.com/") and url.count("/") == 6:
|
||||
return _Body(b'source "$BR2_EXTERNAL_BATOCERA_PATH/'
|
||||
b'package/batocera/core/batocera-system/Config.in"\n')
|
||||
if url.endswith("Config.in"):
|
||||
return _Body(b"config BR2_PACKAGE_BATOCERA_SYSTEM\n"
|
||||
b"\tselect BR2_PACKAGE_MGBA\n\n"
|
||||
b"config BR2_TARGET_BATOCERA_IMAGES\n\tstring \"x\"\n"
|
||||
b"\tdefault \"x86_64\" if BR2_PACKAGE_BATOCERA_TARGET_X86_64\n")
|
||||
return _Body(
|
||||
b"gba:\n emulators:\n libretro:\n"
|
||||
b" mgba: {requireAnyOf: [BR2_PACKAGE_MGBA]}\n"
|
||||
)
|
||||
|
||||
return urlopen
|
||||
|
||||
|
||||
class FailedRequestsStopTheScrape(unittest.TestCase):
|
||||
def test_every_scraper_raises(self):
|
||||
for module in (
|
||||
@@ -66,68 +117,18 @@ class FailedRequestsStopTheScrape(unittest.TestCase):
|
||||
def test_batocera_needs_its_boards(self):
|
||||
"""No board listed, or one board unreadable, used to print a warning
|
||||
and write the targets file without those boards."""
|
||||
|
||||
class _Body:
|
||||
def __init__(self, body: bytes):
|
||||
self.body = body
|
||||
|
||||
def __enter__(self):
|
||||
return self
|
||||
|
||||
def __exit__(self, *exc):
|
||||
return False
|
||||
|
||||
def read(self):
|
||||
return self.body
|
||||
|
||||
def serve(boards: list[str], refuse_board: bool):
|
||||
def urlopen(request, *_a, **_k):
|
||||
url = request.full_url
|
||||
if "/tags" in url:
|
||||
return _Body(b'[{"name": "batocera-43"}]')
|
||||
if "/contents/configs" in url:
|
||||
return _Body(json.dumps([{"name": b} for b in boards]).encode())
|
||||
if "/contents/buildroot" in url:
|
||||
return _Body(b'{"sha": "0123abc"}')
|
||||
if url.endswith("x86_wow64.board"):
|
||||
# Builds the 32-bit Wine package, not an image.
|
||||
return _Body(b"BR2_PACKAGE_BATOCERA_TARGET_X86=y\n")
|
||||
if url.endswith(".board"):
|
||||
if refuse_board:
|
||||
_refuse()
|
||||
return _Body(b"BR2_PACKAGE_BATOCERA_TARGET_X86_64=y\n"
|
||||
b"BR2_PACKAGE_BATOCERA_SYSTEM=y\n")
|
||||
if "/git/trees/" in url:
|
||||
return _Body(b'{"tree": [], "truncated": false}')
|
||||
if url.endswith("retroarch.mk"):
|
||||
return _Body(b"RETROARCH_CONF_OPTS = --enable-networking\n")
|
||||
if url.startswith("https://raw.githubusercontent.com/") and url.count("/") == 6:
|
||||
return _Body(b'source "$BR2_EXTERNAL_BATOCERA_PATH/'
|
||||
b'package/batocera/core/batocera-system/Config.in"\n')
|
||||
if url.endswith("Config.in"):
|
||||
return _Body(b"config BR2_PACKAGE_BATOCERA_SYSTEM\n"
|
||||
b"\tselect BR2_PACKAGE_MGBA\n\n"
|
||||
b"config BR2_TARGET_BATOCERA_IMAGES\n\tstring \"x\"\n"
|
||||
b"\tdefault \"x86_64\" if BR2_PACKAGE_BATOCERA_TARGET_X86_64\n")
|
||||
return _Body(
|
||||
b"gba:\n emulators:\n libretro:\n"
|
||||
b" mgba: {requireAnyOf: [BR2_PACKAGE_MGBA]}\n"
|
||||
)
|
||||
|
||||
return urlopen
|
||||
|
||||
for boards, refuse_board in (([], False), (["batocera-x86_64.board"], True)):
|
||||
with self.subTest(boards=boards), mock.patch.object(
|
||||
batocera_targets_scraper.urllib.request,
|
||||
"urlopen",
|
||||
serve(boards, refuse_board),
|
||||
_serve_batocera(boards, refuse_board),
|
||||
), self.assertRaises(RuntimeError):
|
||||
batocera_targets_scraper.Scraper().fetch_targets()
|
||||
|
||||
with mock.patch.object(
|
||||
batocera_targets_scraper.urllib.request,
|
||||
"urlopen",
|
||||
serve(["batocera-x86_64.board", "batocera-x86_wow64.board"], False),
|
||||
_serve_batocera(["batocera-x86_64.board", "batocera-x86_wow64.board"], False),
|
||||
):
|
||||
targets = batocera_targets_scraper.Scraper().fetch_targets()["targets"]
|
||||
self.assertEqual(targets["x86_64"]["cores"], ["mgba"])
|
||||
@@ -434,41 +435,28 @@ class KnulliPerBoard(unittest.TestCase):
|
||||
raw = f"https://raw.githubusercontent.com/knulli-cfw/knulli-linux/{pin}/"
|
||||
api = "https://api.github.com/repos/knulli-cfw/knulli-linux/contents/"
|
||||
seen: list[str] = []
|
||||
|
||||
class _Body:
|
||||
def __init__(self, body: str):
|
||||
self.body = body.encode()
|
||||
|
||||
def __enter__(self):
|
||||
return self
|
||||
|
||||
def __exit__(self, *exc):
|
||||
return False
|
||||
|
||||
def read(self):
|
||||
return self.body
|
||||
names = [p.removeprefix("configs/") for p in self.FILES if p.startswith("configs/")]
|
||||
exact = {
|
||||
f"{api}configs?ref={pin}": json.dumps([{"name": n} for n in names]),
|
||||
f"{api}buildroot?ref={pin}": '{"sha": "c2d7985b"}',
|
||||
f"{api}batocera?ref={pin}": '{"sha": "487014d9"}',
|
||||
f"{raw}board/r16/retroarch.cfg": 'menu_show_core_updater = "false"\n',
|
||||
f"{raw}package/retroarch/retroarch/retroarch.mk":
|
||||
"RETROARCH_CONF_OPTS = --enable-networking\n",
|
||||
("https://raw.githubusercontent.com/batocera-linux/batocera.linux/"
|
||||
"487014d9/package/batocera/emulators/ppsspp/Config.in"):
|
||||
"config BR2_PACKAGE_PPSSPP\n\tselect BR2_PACKAGE_PPSSPP_ASSETS\n",
|
||||
}
|
||||
|
||||
def urlopen(request, *_a, **_k):
|
||||
url = request.full_url
|
||||
seen.append(url)
|
||||
if url == f"{api}configs?ref={pin}":
|
||||
names = [p.removeprefix("configs/") for p in self.FILES if p.startswith("configs/")]
|
||||
return _Body(json.dumps([{"name": n} for n in names]))
|
||||
if url == f"{api}buildroot?ref={pin}":
|
||||
return _Body('{"sha": "c2d7985b"}')
|
||||
if url == f"{api}batocera?ref={pin}":
|
||||
return _Body('{"sha": "487014d9"}')
|
||||
if url in exact:
|
||||
return _Body(exact[url])
|
||||
if "/git/trees/" in url:
|
||||
# A board config that hides the downloader leaves its URL.
|
||||
cfg = "board/r16/retroarch.cfg" if "knulli-linux" in url else "x"
|
||||
return _Body(json.dumps({"tree": [{"path": cfg}], "truncated": False}))
|
||||
if url == f"{raw}board/r16/retroarch.cfg":
|
||||
return _Body('menu_show_core_updater = "false"\n')
|
||||
if url == f"{raw}package/retroarch/retroarch/retroarch.mk":
|
||||
return _Body("RETROARCH_CONF_OPTS = --enable-networking\n")
|
||||
if url == ("https://raw.githubusercontent.com/batocera-linux/batocera.linux/"
|
||||
"487014d9/package/batocera/emulators/ppsspp/Config.in"):
|
||||
return _Body("config BR2_PACKAGE_PPSSPP\n\tselect BR2_PACKAGE_PPSSPP_ASSETS\n")
|
||||
if url == f"{raw}package/utils/vtree/Config.in":
|
||||
raise urllib.error.HTTPError(url, 404, "Not Found", {}, None)
|
||||
if url.endswith("/c2d7985b/arch/Config.in.arm"):
|
||||
@@ -478,7 +466,7 @@ class KnulliPerBoard(unittest.TestCase):
|
||||
path = url.removeprefix(raw)
|
||||
if path in self.FILES:
|
||||
return _Body(self.FILES[path])
|
||||
_refuse()
|
||||
return _refuse()
|
||||
|
||||
with mock.patch.object(batocera_targets_scraper.urllib.request, "urlopen", urlopen):
|
||||
data = knulli_targets_scraper.Scraper().fetch_targets()
|
||||
|
||||
@@ -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)
|
||||
|
||||
@@ -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__":
|
||||
|
||||
@@ -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"
|
||||
|
||||
@@ -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"])
|
||||
|
||||
@@ -63,7 +63,7 @@ def _pack_files(root: Path, emulators: Path, db: dict) -> set[str]:
|
||||
os.chdir(root)
|
||||
try:
|
||||
generate_pack.generate_emulator_pack(
|
||||
["demo"], str(emulators), db, "bios", "", False, {}, offline=True,
|
||||
["demo"], str(emulators), db, "bios", "", False, zip_contents={}, offline=True,
|
||||
record=record,
|
||||
)
|
||||
finally:
|
||||
|
||||
Reference in new issue
Block a user