refactor: split profile_sync tests by subject

This commit is contained in:
Abdessamad Derraz committed 2026-11-24 07:36:56 +01:00
1 parent 5451bc5b91
commit b7632dbf45
11 files changed
+6988 -6751

No files matched your search

+91
View File
@@ -0,0 +1,91 @@
"""Fixtures shared by the profile_sync test modules."""
from __future__ import annotations
import tests
from unittest import mock
from profiling.reports import (
CitedSource,
EntryReport,
ProfileReport,
)
from profiling.anchoring import PartResult
from model.sourceref import RefPart
from core import upstream
from profiling import versionbasis
def _version_read_as_written(profile, cache_dir, offline, profiles=None, recompute=False):
"""bump_commit reads core_version again at the new pin. These fixtures
have no forge behind them, so the version reads as written here:
tests/test_version_basis.py holds the reading and the refusals."""
stated = versionbasis.declared(profile, "")
return [versionbasis.Reading("", "file", stated, stated, "fixture", versionbasis.MATCH)]
_VERSION_AS_WRITTEN = mock.patch.object(versionbasis, "check", _version_read_as_written)
def setUpModule():
_VERSION_AS_WRITTEN.start()
def tearDownModule():
_VERSION_AS_WRITTEN.stop()
def _sample_report():
shifted = PartResult(RefPart("a.c", 2, 4), "SHIFTED", None, 10, 12, [])
changed = PartResult(RefPart("b.c", 5, 5), "CHANGED", None, 7, 7, [])
return ProfileReport(
name="demo",
repo="o/n",
host="github.com",
pin="pinsha0000",
pin_origin="profiled_date 2026-03-29",
head="headsha000",
entries=[
EntryReport("f0.bin", "a.c:2-4", "SHIFTED", [shifted]),
EntryReport("f1.bin", "b.c:5", "CHANGED", [changed]),
],
counts={"SHIFTED": 1, "CHANGED": 1},
cited_sources=[
CitedSource(path, _SAMPLE_REPO, "pinsha0000", "headsha000")
for path in ("a.c", "b.c")
],
)
_SAMPLE_REPO = upstream.parse_repo("https://github.com/o/n")
SAMPLE = '''emulator: Test
source: "https://github.com/o/n"
profiled_date: "2026-03-29"
notes: >
A note mentioning profiled_date: "1999-01-01" inside prose.
files:
- name: "a.bin"
source_ref: "a.c:10-12"
- name: "b.bin"
source_ref: "b.c:5"
'''
PROSE_SAMPLE = '''emulator: Test
source: "https://github.com/o/n"
profiled_date: "2026-03-29"
source_commit: "pin"
notes: |
The loader appends dc/ to the system directory (a.c:10) and reads
both ranges (b.c:2,8-9) on boot.
files:
- name: "a.bin"
source_ref: "a.c:10-12"
'''
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+821
View File
@@ -0,0 +1,821 @@
"""Tests for the profile_sync command: selection, output modes, records, triage (no network)."""
from __future__ import annotations
import tests
import argparse
import contextlib
import io
import json
import os
import subprocess
import sys
import tempfile
import unittest
from pathlib import Path
from unittest import mock
import yaml
import profile_sync
from profiling import reports as profiling_reports
from profiling import run as profiling_run
from profiling import sourcepaths as profiling_sourcepaths
from profiling import worktree as profiling_worktree
from profiling import triage
from profiling import quota as profiling_quota
from profiling import selection as profiling_selection
from model import profiles as model_profiles
from profiling.reports import (
CitedSource,
EntryReport,
ProfileReport,
SkipKind,
fetch_plan,
format_report,
report_to_dict,
)
from profiling.anchoring import PartResult
from profiling.yamledit import (
YamlWriteError,
)
from profile_sync import build_parser
from profiling.selection import select_profiles
from model.sourceref import RefPart
from core import upstream
from core import forgehttp
from tests.profilesyncsupport import _SAMPLE_REPO, _sample_report
from tests.profilesyncsupport import setUpModule as setUpModule
from tests.profilesyncsupport import tearDownModule as tearDownModule
class TestFetchPlan(unittest.TestCase):
def test_only_entries_needing_review(self):
urls = fetch_plan(_sample_report())
self.assertEqual(len(urls), 1)
self.assertIn("b.c", urls[0])
def test_url_carries_head_revision(self):
self.assertIn("headsha000", fetch_plan(_sample_report())[0])
def test_url_uses_the_recorded_host(self):
report = _sample_report()
report.host = "codeberg.org"
self.assertIn("codeberg.org", fetch_plan(report)[0])
def test_empty_when_nothing_to_review(self):
report = _sample_report()
report.entries = [report.entries[0]]
report.counts = {"SHIFTED": 1}
self.assertEqual(fetch_plan(report), [])
PROFILES = {
"alpha": {
"emulator": "A",
"type": "libretro",
"systems": ["sony-playstation"],
"profiled_date": "2026-03-01",
},
"beta": {
"emulator": "B",
"type": "standalone",
"systems": ["nintendo-64"],
"profiled_date": "2026-08-01",
},
"gamma": {
"emulator": "C",
"type": "alias",
"systems": ["sony-playstation"],
"profiled_date": "2026-03-01",
},
}
def _args(**kwargs):
argv = []
for key, value in kwargs.items():
flag = "--" + key.replace("_", "-")
if value is True:
argv.append(flag)
elif isinstance(value, list):
for item in value:
argv.extend([flag, str(item)])
else:
argv.extend([flag, str(value)])
return build_parser().parse_args(argv)
class TestSelectProfiles(unittest.TestCase):
def test_single_emulator(self):
self.assertEqual(
list(select_profiles(PROFILES, _args(emulator="alpha"))), ["alpha"]
)
def test_emulator_repeats(self):
# A stored --emulator kept only the last of several.
self.assertEqual(
list(select_profiles(PROFILES, _args(emulator=["alpha", "beta", "alpha"]))),
["alpha", "beta"],
)
def test_all_excludes_aliases(self):
self.assertEqual(
sorted(select_profiles(PROFILES, _args(all=True))), ["alpha", "beta"]
)
def test_filter_by_system(self):
self.assertEqual(
list(
select_profiles(
PROFILES, _args(all=True, system="sony-playstation")
)
),
["alpha"],
)
def test_filter_by_type(self):
self.assertEqual(
list(select_profiles(PROFILES, _args(all=True, type="standalone"))),
["beta"],
)
def test_stale_before(self):
self.assertEqual(
list(
select_profiles(PROFILES, _args(all=True, stale_before="2026-06-01"))
),
["alpha"],
)
def test_limit(self):
self.assertEqual(len(select_profiles(PROFILES, _args(all=True, limit=1))), 1)
def test_unknown_emulator_raises(self):
with self.assertRaises(SystemExit):
select_profiles(PROFILES, _args(emulator="nope"))
class TestRateLimitEndsOneProfile(unittest.TestCase):
"""git.libretro.com answered 429 on cemu's tree and the pass over 647
profiles stopped with a traceback and no report at all."""
def test_the_pass_goes_on_and_fails(self):
from unittest import mock
def build(name, *_args, **_kwargs):
if name == "cemu":
raise forgehttp.RateLimitError(
"https://git.libretro.com/x: HTTP 429", "git.libretro.com"
)
return ProfileReport(name=name, counts={"CHANGED": 1})
out, err = io.StringIO(), io.StringIO()
saved = sys.argv
try:
sys.argv = ["profile_sync.py", "--all", "--json"]
with mock.patch.object(model_profiles, "load_emulator_profiles", return_value={}), \
mock.patch.object(profiling_selection, "select_profiles",
return_value={"cemu": {}, "after": {}}), \
mock.patch.object(profiling_quota, "check_quota"), \
mock.patch.object(profiling_run, "build_report", side_effect=build), \
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)
by_name = {r["name"]: r for r in json.loads(out.getvalue())}
self.assertEqual(by_name["cemu"]["skipped"], "rate limited: git.libretro.com")
self.assertEqual(by_name["after"]["needs_review"], 1)
class AWriteRefreshesTheSourcePaths(unittest.TestCase):
"""Each bump left website/src/data/source-paths.json behind its pins and
the site's freshness test red until someone ran site_sources by hand."""
def _args(self, **kw):
base = {
"dry_run": False, "offline": False,
"emulators_dir": str(profiling_sourcepaths.REPO_ROOT / "emulators"), "cache_dir": ".cache/upstream",
}
return argparse.Namespace(**{**base, **kw})
def test_only_a_real_online_write_refreshes(self):
from unittest import mock
from sitegen import sources
with mock.patch.object(sources, "build_source_paths", return_value=({}, [])) as built, \
mock.patch.dict(os.environ, {"RETROBIOS_OFFLINE": ""}), \
mock.patch.object(profiling_sourcepaths, "load_emulator_profiles", return_value={}), \
mock.patch.object(sources, "write_if_changed") as written, \
contextlib.redirect_stderr(io.StringIO()):
profiling_sourcepaths.refresh_source_paths(self._args(), set())
self.assertFalse(built.called)
profiling_sourcepaths.refresh_source_paths(self._args(dry_run=True), {"x"})
self.assertFalse(built.called)
profiling_sourcepaths.refresh_source_paths(self._args(), {"x"})
self.assertTrue(built.called and written.called)
def test_the_record_reads_the_pins_just_written(self):
# The loader caches by directory and the run had loaded the profiles
# before writing them: the record kept the pins it had replaced.
from unittest import mock
from model.profiles import emulator_profiles_cache
from sitegen import sources
with tempfile.TemporaryDirectory() as tmp:
profile = Path(tmp) / "p.yml"
profile.write_text('emulator: P\nsource_commit: "old"\n', encoding="utf-8")
emulator_profiles_cache.clear()
self.addCleanup(emulator_profiles_cache.clear)
model_profiles.load_emulator_profiles(tmp, skip_aliases=False)
profile.write_text('emulator: P\nsource_commit: "new"\n', encoding="utf-8")
with mock.patch.object(sources, "build_source_paths", return_value=({}, [])) as built, \
mock.patch.dict(os.environ, {"RETROBIOS_OFFLINE": ""}), \
mock.patch.object(profiling_sourcepaths, "REPO_ROOT", Path(tmp).parent), \
mock.patch.object(profiling_sourcepaths, "EMULATORS_DIR", Path(tmp).name), \
mock.patch.object(sources, "write_if_changed"), \
contextlib.redirect_stderr(io.StringIO()), \
contextlib.redirect_stdout(io.StringIO()):
profiling_sourcepaths.refresh_source_paths(self._args(emulators_dir=tmp), {"p"})
self.assertEqual(built.call_args[0][0]["p"]["source_commit"], "new")
def test_another_profile_tree_leaves_the_record_alone(self):
# Rebuilt from a one-profile copy, the record went from 701 trees to 1.
from unittest import mock
from sitegen import sources
with tempfile.TemporaryDirectory() as tmp, \
mock.patch.object(sources, "refresh_record") as refreshed, \
mock.patch.dict(os.environ, {"RETROBIOS_OFFLINE": ""}), \
contextlib.redirect_stderr(io.StringIO()) as err:
profiling_sourcepaths.refresh_source_paths(self._args(emulators_dir=tmp), {"p"})
self.assertFalse(refreshed.called)
self.assertIn(f"site_sources.py --fetch --emulators-dir {tmp}", err.getvalue())
def test_the_run_cache_and_the_record_path_are_passed(self):
from unittest import mock
from sitegen import sources
with mock.patch.object(sources, "refresh_record", return_value=({}, [])) as refreshed, \
mock.patch.dict(os.environ, {"RETROBIOS_OFFLINE": ""}), \
mock.patch.object(profiling_sourcepaths, "load_emulator_profiles", return_value={}), \
contextlib.redirect_stderr(io.StringIO()):
profiling_sourcepaths.refresh_source_paths(self._args(cache_dir="tmp/c"), {"x"})
self.assertEqual(refreshed.call_args.args[1], [Path("tmp/c")])
self.assertEqual(refreshed.call_args.kwargs["output"], sources.SOURCE_PATHS)
def test_the_record_waits_for_a_run_holding_the_repository(self):
"""profile_sync rewrote source-paths.json without the repository
hold site_sources takes, in the middle of a pipeline run."""
from unittest import mock
from core.artifacts import ArtifactLockBusy
from sitegen import sources
busy = mock.MagicMock()
busy.__enter__.side_effect = ArtifactLockBusy("another run is writing")
with mock.patch.object(sources, "repository_output_lock", return_value=busy) as lock, \
mock.patch.object(sources, "build_source_paths") as built, \
mock.patch.dict(os.environ, {"RETROBIOS_OFFLINE": ""}), \
mock.patch.object(profiling_sourcepaths, "load_emulator_profiles", return_value={}), \
contextlib.redirect_stderr(io.StringIO()) as err:
profiling_sourcepaths.refresh_source_paths(self._args(), {"x"})
lock.assert_called_once_with(str(sources.SOURCE_PATHS))
self.assertFalse(built.called)
self.assertIn("site_sources.py --fetch", err.getvalue())
class EveryWriterIsRecorded(unittest.TestCase):
"""--backfill-commits wrote a pin without saying so: the record of cited
source paths then lacked the tree that pin names."""
def test_a_backfilled_pin_is_a_write(self):
from unittest import mock
with tempfile.TemporaryDirectory() as tmp:
path = Path(tmp) / "p.yml"
path.write_text('emulator: P\nprofiled_date: "2026-01-01"\n', encoding="utf-8")
args = argparse.Namespace(
emulators_dir=tmp, backfill_commits=True, rebase_refs=False,
bump_commit=False, dry_run=False,
)
report = ProfileReport(name="p", entries=[], counts={}, pin="abcdef0")
written: set[str] = set()
with mock.patch.object(profiling_run, "_build_full_report", return_value=report), \
contextlib.redirect_stdout(io.StringIO()):
profiling_run.read_one_profile(
args, "p", yaml.safe_load(path.read_text()), [], set(), True, written,
)
self.assertIn('source_commit: "abcdef0"', path.read_text())
self.assertEqual(written, {"p"})
def test_a_write_put_back_is_not_recorded(self):
with tempfile.TemporaryDirectory() as tmp:
path = Path(tmp) / "p.yml"
path.write_text("emulator: P\n", encoding="utf-8")
written: set[str] = set()
with profiling_sourcepaths.record_write(path, "p", written):
path.write_text("emulator: Q\n", encoding="utf-8")
path.write_text("emulator: P\n", encoding="utf-8")
self.assertEqual(written, set())
with self.assertRaises(YamlWriteError), \
profiling_sourcepaths.record_write(path, "p", written):
path.write_text("emulator: Q\n", encoding="utf-8")
raise YamlWriteError("a later write refused")
self.assertEqual(written, {"p"})
class AnUnreadTreeKeepsItsRecord(unittest.TestCase):
"""site_sources --fetch, rate-limited by GitLab, dropped about twenty
trees it never read from source-paths.json."""
def test_unread_trees_carry_over(self):
from sitegen import sources
kept = sources.keep_unread(
{"a@1": ["x.c"]}, ["b@2", "c@3"], {"b@2": ["y.c"], "a@1": ["old.c"]}
)
# c@3 was never read: recorded empty, it confirms no path.
self.assertEqual(kept, {"a@1": ["x.c"], "b@2": ["y.c"], "c@3": []})
class FreshRefusesOffline(unittest.TestCase):
def test_the_pair_is_refused(self):
saved = sys.argv
try:
sys.argv = ["profile_sync.py", "--all", "--fresh", "--offline"]
with contextlib.redirect_stderr(io.StringIO()), self.assertRaises(SystemExit) as caught:
profile_sync.main()
finally:
sys.argv = saved
self.assertEqual(caught.exception.code, 1)
class TestOutputModesApplyTheirFlags(unittest.TestCase):
"""--changed-only narrows --json too. Extras are refused off the text report."""
def _main(self, *argv):
from unittest import mock
clean = ProfileReport(name="clean")
drift = ProfileReport(name="drift", counts={"CHANGED": 1})
reports = {"clean": clean, "drift": drift}
out, err = io.StringIO(), io.StringIO()
saved = sys.argv
try:
sys.argv = ["profile_sync.py", "--all", *argv]
with mock.patch.object(model_profiles, "load_emulator_profiles", return_value={}), \
mock.patch.object(profiling_selection, "select_profiles",
return_value={"clean": {}, "drift": {}}), \
mock.patch.object(profiling_quota, "check_quota"), \
mock.patch.object(profiling_run, "build_report",
side_effect=lambda name, *a, **k: reports[name]), \
contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):
try:
profile_sync.main()
code = 0
except SystemExit as exc:
code = exc.code
finally:
sys.argv = saved
return code, out.getvalue(), err.getvalue()
def test_changed_only_narrows_json(self):
code, out, _ = self._main("--changed-only", "--json")
self.assertEqual(code, 0)
self.assertEqual([r["name"] for r in json.loads(out)], ["drift"])
def test_strict_fails_on_refs_to_review(self):
"""A new profile whose refs miss their value used to pass CI green."""
code, out, _ = self._main("--changed-only", "--strict")
self.assertEqual(code, 1)
self.assertIn("drift", out)
def test_strict_passes_when_nothing_is_to_review(self):
from unittest import mock
with mock.patch.object(ProfileReport, "needs_review", return_value=0):
code, _, _ = self._main("--strict")
self.assertEqual(code, 0)
def test_strict_fails_on_prose_that_blocks_the_pin(self):
"""blastem read "0 to review" while its prose refused every bump."""
from unittest import mock
with tempfile.TemporaryDirectory() as tmp:
for name in ("clean", "drift"):
(Path(tmp) / f"{name}.yml").write_text("emulator: x\n")
stale = {"clean": ["read again: notes: a.c:5 (pin moved)"], "drift": []}
with mock.patch.object(
profiling_run, "realign_prose",
side_effect=lambda path, *a, **k: stale[path.stem],
):
code, out, _ = self._main(
"--changed-only", "--strict", "--emulators-dir", tmp,
)
self.assertEqual(code, 1)
self.assertIn("clean", out)
self.assertIn("prose under an older pin", out)
def test_diffs_are_refused_with_json(self):
code, _, err = self._main("--json", "--full-diff")
self.assertEqual(code, 1)
self.assertIn("--full-diff", err)
def test_markdown_carries_detection(self):
"""Detection lives on the report, and the markdown document embeds
each report's text: refusing the pair left the finding unwritten."""
from unittest import mock
def detect(profile, report, *_):
report.new_files = [
{"path": "a.c", "line": 3, "name": "new.rom", "since_pin": True}
]
report.new_hashes = [{"path": "a.c", "kind": "md5", "value": "0" * 32}]
with tempfile.TemporaryDirectory() as tmp, \
mock.patch.object(profiling_run, "_attach_detection", side_effect=detect):
code, _, err = self._main(
"--markdown", "--detect-new-files", "--watch-hashes", "--report-dir", tmp,
)
self.assertEqual(code, 0, err)
document = next(Path(tmp).glob("profile-sync-*.md")).read_text(encoding="utf-8")
self.assertIn(" new file: a.c:3 new.rom", document)
self.assertIn(f" new md5: a.c {'0' * 32}", document)
def test_rankings_refuse_detection(self):
code, _, err = self._main("--triage", "--detect-new-files")
self.assertEqual(code, 1)
self.assertIn("--detect-new-files", err)
def test_json_carries_detection(self):
"""check_freshness reads --json: a new upstream file or hash printed
only in the text report stayed a human reading."""
from unittest import mock
def detect(profile, report, *_):
report.new_files = [
{"path": "a.c", "line": 3, "name": "new.rom", "since_pin": True}
]
report.new_hashes = [{"path": "a.c", "kind": "md5", "value": "0" * 32}]
with mock.patch.object(profiling_run, "_attach_detection", side_effect=detect):
code, out, err = self._main("--json", "--detect-new-files", "--watch-hashes")
self.assertEqual(code, 0, err)
rows = json.loads(out)
self.assertEqual(rows[0]["new_files"][0]["name"], "new.rom")
self.assertTrue(rows[0]["new_files"][0]["since_pin"])
self.assertEqual(rows[0]["new_hashes"][0]["kind"], "md5")
def test_json_carries_the_version_check(self):
"""check_freshness asks for --json --check-version: refused, its
profile row read an empty report as unreadable on every run."""
code, out, err = self._main("--json", "--check-version")
self.assertEqual(code, 0, err)
rows = json.loads(out)
self.assertTrue(all("version" in row and "page_version" in row for row in rows))
def test_rankings_refuse_the_version_check(self):
code, _, err = self._main("--triage", "--check-version")
self.assertEqual(code, 1)
self.assertIn("--check-version", err)
def test_json_carries_the_ranking(self):
"""--json --triage printed the plain report: no score, no order."""
code, out, err = self._main("--json", "--triage")
self.assertEqual(code, 0, err)
rows = json.loads(out)
self.assertEqual([r["name"] for r in rows], ["drift", "clean"])
self.assertEqual([r["drift_score"] for r in rows], [30, 0])
self.assertIsNone(rows[0]["drift_refused"])
def test_the_ranking_as_json_carries_the_version_check(self):
code, out, err = self._main("--json", "--triage", "--check-version")
self.assertEqual(code, 0, err)
self.assertTrue(all("version" in row for row in json.loads(out)))
def test_two_outputs_are_refused(self):
for pair in (("--json", "--markdown"), ("--markdown", "--triage"),
("--json", "--fetch-plan"), ("--fetch-plan", "--triage")):
code, out, err = self._main(*pair)
self.assertEqual(code, 1, pair)
self.assertIn("separate outputs", err, pair)
self.assertEqual(out, "", pair)
def test_a_profile_the_forge_failed_is_listed_and_fails_the_run(self):
"""Dropped by --changed-only, a 502 read as nothing to review."""
from unittest import mock
def build(name, *args, **kwargs):
if name == "drift":
raise forgehttp.UpstreamError("https://x: HTTP 502")
return ProfileReport(name=name)
out = io.StringIO()
saved = sys.argv
try:
sys.argv = ["profile_sync.py", "--all", "--changed-only", "--json"]
with mock.patch.object(model_profiles, "load_emulator_profiles", return_value={}), \
mock.patch.object(profiling_selection, "select_profiles",
return_value={"clean": {}, "drift": {}}), \
mock.patch.object(profiling_quota, "check_quota"), \
mock.patch.object(profiling_run, "build_report", side_effect=build), \
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)
(row,) = json.loads(out.getvalue())
self.assertEqual(row["name"], "drift")
self.assertIn("upstream error", row["skipped"])
class TestEmulatorsDirStatus(unittest.TestCase):
"""git was asked from the current directory and its exit code ignored:
a profile tree in another repository, or in none, read as clean, and
--rebase-refs wrote over uncommitted profiles."""
def _git(self, *args: str, cwd: str) -> None:
subprocess.run(["git", *args], cwd=cwd, check=True, capture_output=True)
def test_a_tree_in_another_repository_answers_for_itself(self):
with tempfile.TemporaryDirectory() as root:
self._git("init", "-q", cwd=root)
Path(root, "a.yml").write_text("emulator: a\n")
self.assertTrue(profiling_worktree.emulators_dir_is_dirty(root))
def test_only_the_selected_profiles_count(self):
# A loop of --emulator X --rebase-refs refused every profile after
# the first one it wrote.
with tempfile.TemporaryDirectory() as root:
self._git("init", "-q", cwd=root)
Path(root, "a.yml").write_text("emulator: a\n")
Path(root, "b.yml").write_text("emulator: b\n")
self._git("add", "a.yml", "b.yml", cwd=root)
self._git("-c", "user.name=t", "-c", "user.email=t@t", "commit", "-qm", "p", cwd=root)
Path(root, "a.yml").write_text("emulator: a2\n")
self.assertTrue(profiling_worktree.emulators_dir_is_dirty(root, ["a"]))
self.assertFalse(profiling_worktree.emulators_dir_is_dirty(root, ["b"]))
def test_the_refusal_names_the_changed_profile(self):
"""One profile changed by another session among ~375 refused the
whole run without saying which."""
with tempfile.TemporaryDirectory() as root:
self._git("init", "-q", cwd=root)
for name in "abc":
Path(root, f"{name}.yml").write_text(f"emulator: {name}\n")
self._git("add", "a.yml", "b.yml", "c.yml", cwd=root)
self._git("-c", "user.name=t", "-c", "user.email=t@t", "commit", "-qm", "p", cwd=root)
Path(root, "b.yml").write_text("emulator: b2\n")
self.assertEqual(profiling_worktree.emulators_dir_is_dirty(root, ["a", "b", "c"]),
["b.yml"])
err = io.StringIO()
with contextlib.redirect_stderr(err), self.assertRaises(SystemExit):
profiling_worktree.refuse_dirty_tree(root, ["a", "b", "c"])
self.assertIn("b.yml has uncommitted changes", err.getvalue())
self.assertNotIn("a.yml", err.getvalue())
def test_a_tree_outside_any_repository_is_not_clean(self):
with tempfile.TemporaryDirectory() as root, mock.patch.dict(
os.environ, {"GIT_CEILING_DIRECTORIES": str(Path(root).parent)}
), self.assertRaises(RuntimeError):
profiling_worktree.emulators_dir_is_dirty(root)
class TestSelectionNamesWhatMatchedNothing(unittest.TestCase):
"""`--all --system atari-lynxx` printed nothing and exited 0, which read
as "no Lynx profile needs a re-read", and `--emulator handyy` offered no
suggestion."""
PROFILES = {
"handy": {"type": "libretro", "systems": ["atari-lynx"]},
"mednafen_lynx": {"type": "libretro", "systems": ["atari-lynx"]},
}
def _args(self, **values):
base = {"emulator": None, "changed": False, "added": False,
"system": None, "type_": None, "stale_before": None,
"limit": None}
return argparse.Namespace(**{**base, **values})
def test_a_misspelt_system_stops_and_suggests(self):
with self.assertRaises(SystemExit) as caught:
select_profiles(self.PROFILES, self._args(system="atari-lynxx"))
self.assertIn("atari-lynx", str(caught.exception.code))
def test_a_misspelt_emulator_suggests(self):
with self.assertRaises(SystemExit) as caught:
select_profiles(self.PROFILES, self._args(emulator="handyy"))
self.assertIn("Close matches: handy", str(caught.exception.code))
def test_a_matching_filter_selects(self):
selected = select_profiles(self.PROFILES, self._args(system="atari-lynx"))
self.assertEqual(sorted(selected), ["handy", "mednafen_lynx"])
def test_system_matches_as_the_listing_does(self):
"""verify.py --list-systems printed `saturn`, which selected 1 profile
of 11 because 10 declare sega-saturn."""
profiles = {
"a": {"type": "libretro", "systems": ["sega-saturn"]},
"b": {"type": "libretro", "systems": ["saturn"]},
}
for spelling in ("saturn", "sega-saturn"):
selected = select_profiles(profiles, self._args(system=spelling))
self.assertEqual(sorted(selected), ["a", "b"])
def test_the_hint_counts_what_the_listing_prints(self):
profiles = {
"a": {"type": "libretro", "systems": ["sega-saturn"]},
"b": {"type": "libretro", "systems": ["saturn"]},
"c": {"type": "libretro", "systems": ["atari-lynx"]},
}
with self.assertRaises(SystemExit) as caught:
select_profiles(profiles, self._args(system="nothing"))
self.assertIn("Known: atari-lynx, sega-saturn.", str(caught.exception.code))
class TheUnknownProfileHintCountsTheListing(unittest.TestCase):
"""profile_sync said "verify.py --list-emulators lists all 553" for a
listing of 530: the alias and test profiles it counted are not listed."""
def test_the_count_matches(self):
import subprocess
root = Path(__file__).resolve().parents[1]
hint = subprocess.run(
[sys.executable, "scripts/profile_sync.py", "--emulator", "no-such-profile"],
cwd=root, capture_output=True, text=True, timeout=120, check=False,
)
listing = subprocess.run(
[sys.executable, "scripts/verify.py", "--list-emulators"],
cwd=root, capture_output=True, text=True, timeout=120, check=False,
).stdout
count = len([line for line in listing.splitlines() if line.strip()])
self.assertIn(f"lists all {count}.", hint.stderr + hint.stdout)
class StrictRefusesAnUncheckableProfile(unittest.TestCase):
"""A new profile whose repository answered 404, or with no pin at all,
was skipped with empty counts and --strict passed it in CI."""
def test_defects_are_told_from_the_profiles_nature(self):
def report(kind):
return ProfileReport(name="p", entries=[], counts={}, skipped="any words",
skip_kind=kind)
self.assertTrue(report(SkipKind.UNANSWERED).uncheckable())
self.assertTrue(report(SkipKind.GONE).uncheckable())
self.assertTrue(report(SkipKind.GONE_CONTRADICTED).uncheckable())
self.assertFalse(report(SkipKind.UNSUPPORTED_HOST).uncheckable())
self.assertFalse(report(SkipKind.GONE_DECLARED).uncheckable())
self.assertFalse(report(SkipKind.NO_SOURCE_REF).uncheckable())
self.assertFalse(report(SkipKind.OFFLINE).uncheckable())
def test_a_forge_failing_this_time_is_unread_in_the_json_too(self):
"""profile_sync exited 1 on a forge answering 500 or 429 while its
JSON row carried no attention, so check_freshness --profiles showed
SKIPPED and exited 0."""
for kind in (SkipKind.UPSTREAM_ERROR, SkipKind.RATE_LIMITED):
report = ProfileReport(name="p", skipped="x", skip_kind=kind)
self.assertTrue(report.unreached())
self.assertEqual(
[(r.kind, r.level) for r in report.attention()],
[("unreached", profiling_reports.UNKNOWN_LEVEL)],
)
self.assertNotIn("skip_kind", report_to_dict(report))
self.assertFalse(ProfileReport(name="p", skipped="x",
skip_kind=SkipKind.OFFLINE).unreached())
class AnOnlinePassSaysWhereItIs(unittest.TestCase):
"""`--all --triage` online printed nothing for 15 minutes, and Ctrl-C
left no ranking at all, while --offline answered in three."""
def _main(self, *argv: str, stop_after: int | None = None):
calls: list[str] = []
def build(_args, name, _profile, _path, _failed):
if stop_after is not None and len(calls) == stop_after:
raise KeyboardInterrupt
calls.append(name)
return ProfileReport(name=name, entries=[], counts={})
out, err = io.StringIO(), io.StringIO()
saved = sys.argv
try:
sys.argv = ["profile_sync.py", "--all", "--triage", *argv]
with mock.patch.object(profiling_run, "_build_full_report", side_effect=build), \
mock.patch.object(profiling_quota, "check_quota"), \
contextlib.redirect_stdout(out), contextlib.redirect_stderr(err), \
self.assertRaises(SystemExit) as caught:
profile_sync.main()
raise SystemExit(0)
finally:
sys.argv = saved
return caught.exception.code, out.getvalue(), err.getvalue()
def test_ctrl_c_prints_the_ranking_of_what_was_read(self):
code, out, err = self._main("--offline", stop_after=3)
self.assertEqual(code, 130)
self.assertEqual(out.splitlines()[-1], "3 profiles, 0 with something to review")
self.assertIn("interrupted after 3 of", err)
def test_an_online_pass_names_its_size_and_the_offline_mode(self):
_code, _out, err = self._main("--limit", "2")
self.assertIn("reading 2 profiles against their forges", err)
self.assertIn("--offline answers from the cache alone", err)
def test_a_progress_line_at_each_interval(self):
clock = iter([0.0, 10.0, triage.PROGRESS_SECONDS + 1, 40.0])
err = io.StringIO()
with mock.patch.object(triage.time, "monotonic", lambda: next(clock)), \
contextlib.redirect_stderr(err):
progress = triage.Progress(9, "read", quiet=False)
for done, name in enumerate(("a", "b", "c")):
progress.step(done, name)
self.assertEqual(err.getvalue(), "read: 1 of 9, at b\n")
class TheTriageCountsWhatBlocksThePin(unittest.TestCase):
"""Prose written under an older pin refuses the recale and the bump, yet
the triage, --changed-only and --strict read "0 to review" on blastem,
xenia-edge and lindbergh-loader. And one stderr notice per profile put
254 lines above an unlabelled ranking."""
def _report(self, name: str, paths: int, stale: list[str] | None = None):
entries = [
EntryReport(f"f{i}", f"d/{i}.c:1", "ANCHORED", [
PartResult(RefPart(f"d/{i}.c", 1, 1, "1"), "ANCHORED",
None, None, None, [])
])
for i in range(paths)
]
return ProfileReport(
name=name, pin="p", head="h", entries=entries,
counts={"ANCHORED": paths}, stale_prose=stale,
cited_sources=[
CitedSource(f"d/{i}.c", _SAMPLE_REPO, "p", "h") for i in range(paths)
],
)
def test_stale_prose_is_review_work(self):
report = self._report("b", 1, ["read again: notes: a.c:5 (pin moved)"])
self.assertEqual(report.needs_review(), 1)
self.assertIn("prose under an older pin", format_report(report))
self.assertEqual(report_to_dict(report)["needs_review"], 1)
def test_the_ranking_is_labelled_and_the_sampling_said_once(self):
reports = [
self._report("clean", 7),
self._report("stuck", 7, ["read again: notes: a.c:5 (pin moved)"]),
]
selected = {r.name: {"source": "https://github.com/o/n"} for r in reports}
args = argparse.Namespace(cache_dir="unused", offline=True)
out, err = io.StringIO(), io.StringIO()
with mock.patch.object(triage, "check_version", return_value=None), \
mock.patch.object(upstream, "commits_touching",
return_value=0), \
contextlib.redirect_stdout(out), contextlib.redirect_stderr(err):
triage.print_triage(args, selected, reports)
lines = out.getvalue().splitlines()
self.assertIn("profile", lines[0])
self.assertIn("stuck", lines[1])
self.assertIn("1 to review, 1 prose under an older pin", lines[1])
self.assertIn("0 to review", lines[2])
self.assertEqual(lines[-1], "2 profiles, 1 with something to review")
self.assertEqual(len(err.getvalue().splitlines()), 1, err.getvalue())
def test_an_uncheckable_profile_ranks_first_and_counts(self):
"""simple64 and teknoparrot answered 404 and --strict failed on them,
while the triage put them at 0 under the clean profiles."""
gone = ProfileReport(
name="gone", pin="p", skipped="no declared repository answers (o/n)",
skip_kind=SkipKind.UNANSWERED,
)
reports = [self._report("clean", 1), gone]
selected = {r.name: {"source": "https://github.com/o/n"} for r in reports}
args = argparse.Namespace(cache_dir="unused", offline=True)
out = io.StringIO()
with mock.patch.object(triage, "check_version", return_value=None), \
mock.patch.object(upstream, "commits_touching",
return_value=0), \
contextlib.redirect_stdout(out), contextlib.redirect_stderr(io.StringIO()):
triage.print_triage(args, selected, reports)
lines = out.getvalue().splitlines()
self.assertIn("gone", lines[1])
self.assertEqual(lines[-1], "2 profiles, 1 with something to review")
if __name__ == "__main__":
unittest.main()
File diff suppressed because it is too large. Load diff
File diff suppressed because it is too large. Load diff
+552
View File
@@ -0,0 +1,552 @@
"""Tests for the repositories profile_sync reads: submodules, mirrors, forks, branches, roles (no network)."""
from __future__ import annotations
import tests
import contextlib
import io
import os
import subprocess
import tempfile
import unittest
from pathlib import Path
from unittest import mock
import profile_sync
from profiling import anchoring
from profiling import citations as profiling_citations
from profiling import realign
from profiling import reports as profiling_reports
from profiling import repos as profiling_repos
from profiling import resolver
from profiling import reportinputs
from profiling import worktree as profiling_worktree
from profiling import versions
from model import sourceref
from profiling.reports import (
ProfileReport,
format_report,
report_to_dict,
)
from profiling.selection import select_profiles
from tests.sources import script_source
from core import upstream
from core import forgehttp
from core import upstreamtree
from tests.profilesyncsupport import setUpModule as setUpModule
from tests.profilesyncsupport import tearDownModule as tearDownModule
class UpstreamVendoredAsASubmodule(unittest.TestCase):
"""libretro/TIC-80 builds nesbox/TIC-80 through its `core` submodule, and
tic80's upstream_commit is that submodule's commit. Compared to nesbox's
own HEAD it reported changes the shipped core never had, and a bump would
have moved upstream_commit past what libretro builds."""
def _views(self, links: dict) -> list:
from unittest import mock
repo_s, repo_u = object(), object()
views = [
profiling_repos.RepoView(repo_s, "src-pin", "src-head", "source_commit", "source"),
profiling_repos.RepoView(repo_u, "sub-old", "nesbox-tip", "upstream_commit", "upstream"),
]
with mock.patch.object(
upstreamtree, "list_gitlinks",
side_effect=lambda repo, sha, *a, **k: links.get(sha, {}),
):
return profiling_repos._follow_submodule(views, "cache", True)
def test_the_upstream_head_is_what_the_port_head_builds(self):
views = self._views({"src-pin": {"core": "sub-old"}, "src-head": {"core": "sub-new"}})
self.assertEqual(views[1].head, "sub-new")
self.assertEqual(views[0].head, "src-head")
def test_an_upstream_the_port_does_not_vendor_keeps_its_tip(self):
views = self._views({"src-pin": {"deps/zlib": "other"}, "src-head": {}})
self.assertEqual(views[1].head, "nesbox-tip")
def test_a_truncated_port_tree_is_not_read_as_no_submodule(self):
"""A partial listing kept nesbox's tip, the commit a bump must not
move upstream_commit to."""
views = [
profiling_repos.RepoView(object(), "src-pin", "src-head", "source_commit", "source"),
profiling_repos.RepoView(object(), "sub-old", "nesbox-tip", "upstream_commit", "upstream"),
]
with mock.patch.object(
upstreamtree, "list_gitlinks",
side_effect=forgehttp.TruncatedListingError("tree listing truncated"),
), self.assertRaises(forgehttp.TruncatedListingError):
profiling_repos._follow_submodule(views, "cache", True)
class TruncatedGitlinksInTheResolver(unittest.TestCase):
"""A read-only report goes on past a partial listing, and says so."""
def test_the_lost_tree_yields_no_link_and_the_next_is_read(self):
from types import SimpleNamespace
views = [SimpleNamespace(repo="a", pin="p1"), SimpleNamespace(repo="b", pin="p2")]
state = SimpleNamespace(views=views, cache_dir="c", offline=True, name="demo")
def links(repo, sha, *_args):
if repo == "a":
raise forgehttp.TruncatedListingError("a@p1: tree listing truncated")
return {"sub": "s"}
with mock.patch.object(upstreamtree, "list_gitlinks", side_effect=links), \
contextlib.redirect_stderr(io.StringIO()) as err:
found = [list(paths) for paths in resolver._Resolver.gitlinks_in_order(state)]
self.assertEqual(found, [[], ["sub"]])
self.assertIn("submodule paths unknown", err.getvalue())
class AMirrorOutlivesAGoneSource(unittest.TestCase):
"""yuzu's source answers 451. select_views stopped on it and never read
the source_mirror declared after it, so the profile stayed unchecked."""
def test_the_mirror_is_read_when_the_source_is_gone(self):
from unittest import mock
gone_repo = upstream.make_repo("github.com", "yuzu-emu-mirror", "yuzu")
mirror = upstream.make_repo("github.com", "fork", "yuzu")
def head(repo, cache_dir, offline=False, branch=None):
if repo == gone_repo:
raise forgehttp.GoneError("HTTP 451")
return "mirror-head"
profile = {
"source": "https://github.com/yuzu-emu-mirror/yuzu",
"source_mirror": "https://github.com/fork/yuzu",
"source_commit": "pin",
}
with mock.patch.object(upstream, "resolve_head", side_effect=head), \
mock.patch.object(profiling_repos, "resolve_pin", return_value=("pin", "source_commit")):
views = profiling_repos.select_views(profile, "cache", True)
self.assertEqual([(v.repo, v.field) for v in views], [(mirror, "source_mirror")])
def test_the_mirror_takes_the_gone_source_place_before_the_upstream(self):
"""Read last, the mirror ranked after a live upstream, while the
prose pass and the site read it in the source's place."""
from unittest import mock
gone_repo = upstream.make_repo("github.com", "gone", "emu")
mirror = upstream.make_repo("github.com", "fork", "emu")
live = upstream.make_repo("github.com", "up", "emu")
def head(repo, cache_dir, offline=False, branch=None):
if repo == gone_repo:
raise forgehttp.GoneError("HTTP 404")
return "tip"
profile = {
"source": "https://github.com/gone/emu",
"upstream": "https://github.com/up/emu",
"source_mirror": "https://github.com/fork/emu",
"source_commit": "pin",
"upstream_gone": "gone/emu answers 404",
}
with mock.patch.object(upstream, "resolve_head", side_effect=head), \
mock.patch.object(profiling_repos, "resolve_pin", return_value=("pin", "c")):
views = profiling_repos.select_views(profile, "cache", True)
self.assertEqual([(v.repo, v.field) for v in views],
[(mirror, "source_mirror"), (live, "upstream")])
def test_the_gone_source_is_still_asked(self):
"""A forge answering again contradicts upstream_gone, so it is asked."""
from unittest import mock
asked = []
def head(repo, cache_dir, offline=False, branch=None):
asked.append(repo.slug)
return "tip"
profile = {
"source": "https://github.com/gone/emu",
"source_mirror": "https://github.com/fork/emu",
"source_commit": "pin",
"upstream_gone": "gone/emu answers 404",
}
with mock.patch.object(upstream, "resolve_head", side_effect=head), \
mock.patch.object(profiling_repos, "resolve_pin", return_value=("pin", "c")):
views = profiling_repos.select_views(profile, "cache", True)
self.assertEqual(asked[0], "gone/emu")
self.assertEqual(views[0].field, "source")
class AHeldUpstreamStaysOnItsPin(unittest.TestCase):
"""aps3e vendors RPCS3 1f080485 and yaps2 PCSX2 342db515: a bump moved
upstream_commit to the upstream HEAD neither port carries."""
def test_the_upstream_view_is_read_at_its_pin(self):
views = [
profiling_repos.RepoView("fork", "p", "h", "source_commit", "source"),
profiling_repos.RepoView("up", "vendored", "tip", "upstream_commit", "upstream"),
]
held = profiling_repos._hold_upstream({"upstream_frozen": "vendored tree"}, views)
self.assertEqual((held[0].head, held[1].head), ("h", "vendored"))
self.assertEqual(profiling_repos._hold_upstream({}, views), views)
class RealignReadsThePathAsWritten(unittest.TestCase):
"""hatarib cites hatari/src/tos.c, a path of hatariB. When only
upstream_commit moved, realign stripped the hatari/ prefix, read
hatari/hatari's src/tos.c and proposed moving a correct citation."""
def test_an_unmoved_repository_carrying_the_path_keeps_it(self):
from unittest import mock
fork = upstream.make_repo("github.com", "b", "hatariB")
up = upstream.make_repo("github.com", "hatari", "hatari")
trees = {(fork, "fork-pin"): {"hatari/src/tos.c"},
(up, "old"): {"src/tos.c"}, (up, "new"): {"src/tos.c"}}
def fetch(repo, sha, path, *a, **k):
return ["line"] * 40 if path in trees.get((repo, sha), set()) else None
part = sourceref.RefPart("hatari/src/tos.c", 10, 10, "10")
with mock.patch.object(upstream, "fetch_file", side_effect=fetch), \
mock.patch.object(realign, "_resolve_at",
return_value=("found", ("src/tos.c", ["x"] * 40))):
result = realign._realign_part(
part, [(up, "old", "new")], "cache", True,
pinned=[(fork, "fork-pin"), (up, "new")],
)
self.assertIsNone(result)
class RealignGivesASharedPathToTheFirstRepository(unittest.TestCase):
"""freej2me-plus and hex007/freej2me both hold src/libretro/: with only
upstream_commit moved, the fork's citations were read in upstream."""
def test_the_source_declared_first_keeps_it(self):
from unittest import mock
fork = upstream.make_repo("github.com", "t", "freej2me-plus")
up = upstream.make_repo("github.com", "hex007", "freej2me")
part = sourceref.RefPart("src/libretro/freej2me_libretro.c", 39, 46, "39-46")
with mock.patch.object(
upstream, "fetch_file", return_value=["line"] * 99
), mock.patch.object(
realign, "_resolve_at", return_value=("found", (part.path, ["x"] * 99))
):
result = realign._realign_part(
part, [(up, "eb4ac87", "8b9bc8a")], "cache", True,
pinned=[(fork, "3933e75"), (up, "8b9bc8a")],
)
self.assertIsNone(result)
class RealignObeysTheRoleWord(unittest.TestCase):
"""retrodream cites `(upstream retro_host.c:196-198)` beside the fork's
retro_host.c. With both pins moved and both trees carrying the file,
realign read the upstream citation in the fork, declared first."""
def _realign(self, role):
from unittest import mock
fork = upstream.make_repo("github.com", "f", "retrodream")
up = upstream.make_repo("github.com", "o", "dreamcast")
body = [f"line {n}" for n in range(1, 41)]
trees = {
(fork, "f-old"): body, (fork, "f-new"): ["pad"] * 5 + body,
(up, "u-old"): body, (up, "u-new"): body,
}
def fetch(repo, sha, path, *a, **k):
return trees.get((repo, sha)) if path == "retro_host.c" else None
part = sourceref.RefPart("retro_host.c", 20, 22, "20-22", role)
with mock.patch.object(upstream, "fetch_file", side_effect=fetch):
return realign._realign_part(
part, [(fork, "f-old", "f-new"), (up, "u-old", "u-new")], "cache", True,
pinned=[(fork, "f-new"), (up, "u-new")],
declared={fork: ("source", ""), up: ("upstream", "")},
)
def test_an_upstream_part_is_read_in_upstream(self):
self.assertIsNone(self._realign("upstream"))
def test_a_part_naming_no_repository_stays_with_the_first_declared(self):
self.assertEqual(self._realign(""), ("ok", (25, 27)))
def test_attribution_and_realign_share_the_order(self):
"""The resolver and realign order repositories by one function."""
source = script_source("profile_sync.py")
self.assertEqual(source.count("def owner_order("), 1)
self.assertIn("owner_order(self.views", source)
self.assertIn("owner_order(pairs, part.role", source)
class UpstreamForkedByThePort(unittest.TestCase):
"""snes9x, kronos and np2kai pinned upstream_commit on the merge base of
upstream with the fork. Compared to upstream's own HEAD, a bump moved it
past anything the port carries."""
def _views(self, base, ancestry=None):
from unittest import mock
fork = upstream.make_repo("github.com", "f", "port")
self.up = upstream.make_repo("github.com", "o", "up")
self.fork = fork
views = [
profiling_repos.RepoView(fork, "src-pin", "src-head", "source_commit", "source"),
profiling_repos.RepoView(self.up, "old-base", "up-tip", "upstream_commit", "upstream"),
]
with mock.patch.object(
upstreamtree, "fork_base", return_value=base
) as asked, mock.patch.object(
upstreamtree, "ancestry", return_value=ancestry
):
followed = profiling_repos._follow_fork_base(views, "cache", True)
return followed, asked
def test_the_upstream_head_is_the_fork_base(self):
views, asked = self._views("new-base")
self.assertEqual(views[1].head, "new-base")
self.assertEqual(
asked.call_args.args[:4], (self.up, "up-tip", self.fork, "src-head")
)
def test_a_port_outside_the_network_keeps_the_tip(self):
views, _ = self._views(None)
self.assertEqual(views[1].head, "up-tip")
def test_a_pin_newer_than_the_base_keeps_the_tip(self):
"""melonds documents the Qt standalone from melonDS-emu/melonDS: its
upstream_commit is 825 commits past the merge base with the libretro
fork, and reading its refs at the 2021 base reported them CHANGED."""
views, _ = self._views("old-merge", ancestry=(825, 0))
self.assertEqual(views[1].head, "up-tip")
def test_a_pin_behind_the_base_follows_it(self):
views, _ = self._views("new-base", ancestry=(0, 12))
self.assertEqual(views[1].head, "new-base")
class TestTreeUrlIntoADirectory(unittest.TestCase):
"""`.../libretro-samples/tree/master/tests/cruzes` took the whole tail as
the branch. Nothing resolved and cruzes was skipped as having no pin."""
def test_candidates_are_prefixes_shortest_first(self):
self.assertEqual(
profiling_repos.branch_candidates(
"https://github.com/libretro/libretro-samples/tree/master/tests/cruzes"
),
["master", "master/tests", "master/tests/cruzes"],
)
self.assertEqual(profiling_repos.branch_candidates("https://github.com/o/r"), [])
def test_the_first_resolving_prefix_is_the_branch(self):
from unittest import mock
asked = []
def head(repo, cache, offline=False, branch=None):
asked.append(branch)
return "tipsha" if branch == "master" else None
profile = {"source": "https://github.com/libretro/libretro-samples/tree/master/tests/cruzes",
"source_commit": "pinsha"}
with mock.patch.object(upstream, "resolve_head", side_effect=head):
views = profiling_repos.select_views(profile, ".cache", True)
self.assertEqual([(v.pin, v.head) for v in views], [("pinsha", "tipsha")])
self.assertEqual(asked[0], "master")
class TestAnUnansweringRepository(unittest.TestCase):
"""pyxel declares source_commit, yet the skip read "no source_commit":
its repository answers 404. A declared upstream_gone was honoured only
when the forge raised GoneError, never on a plain non-answer."""
def _report(self, profile):
from unittest import mock
with mock.patch.object(reportinputs, "select_views", return_value=[]):
return resolver.build_report("p", profile, ".cache", True)
def test_a_declared_pin_names_the_repository(self):
report = self._report({"source": "https://github.com/o/r", "source_commit": "abc",
"files": [{"name": "a", "source_ref": "a.c:1"}]})
self.assertIn("no declared repository answers", report.skipped)
def test_a_declared_gone_upstream_is_honoured(self):
report = self._report({"source": "https://github.com/o/r", "source_commit": "abc",
"upstream_gone": "404 since 2026-10-18",
"files": [{"name": "a", "source_ref": "a.c:1"}]})
self.assertEqual(report.skipped, "upstream gone (declared): 404 since 2026-10-18")
class AnOffForgeProfileWatchesItsReleasePage(unittest.TestCase):
"""Profiles of projects outside any forge were skipped as an unsupported
host, and a new release of Altirra or mednafen went unseen."""
def test_the_page_version_is_read(self):
from unittest import mock
profile = {"emulator": "Altirra", "core_version": "4.40", "version_source": {
"url": "https://example.test/altirra", "pattern": r"Altirra (\d+\.\d+) released",
}}
with mock.patch.object(upstream, "fetch_page",
return_value="<p>Altirra 4.50 released</p>"):
self.assertEqual(versions.page_version(profile, "cache", False), ("4.50", None))
def test_an_unread_page_says_why(self):
"""A fetch error, an uncached page, a 404 and a pattern miss all
came back None, the error only printed: the JSON could not tell a
moved release page from a profile without one."""
from unittest import mock
profile = {"emulator": "Altirra", "version_source": {
"url": "https://example.test/altirra", "pattern": r"Altirra (\d+\.\d+) released",
}}
answers = [
(forgehttp.NotCachedError("cold"), "not cached offline"),
(None, "page absent"),
("<p>nothing here</p>", "pattern not found"),
(forgehttp.UpstreamError("HTTP 500"), "https://example.test/altirra: HTTP 500"),
]
for answer, reason in answers:
effect = {"side_effect": answer} if isinstance(answer, Exception) else {"return_value": answer}
with self.subTest(reason=reason), \
mock.patch.object(upstream, "fetch_page", **effect), \
mock.patch("sys.stderr") as stderr:
self.assertEqual(versions.page_version(profile, "cache", True), (None, reason))
stderr.write.assert_not_called()
def test_an_uncached_page_offline_is_not_an_absent_one(self):
with tempfile.TemporaryDirectory() as cache, self.assertRaises(forgehttp.NotCachedError):
upstream.fetch_page("https://example.invalid/never-cached", cache, True)
def test_the_reason_reaches_the_json_and_the_text(self):
report = ProfileReport(name="altirra", entries=[], counts={}, skipped="unsupported host: x",
declared_version="4.40", page_version_unread="page absent",
version_unread="tag ancestry unread: refused")
payload = report_to_dict(report)
self.assertEqual(payload["page_version_unread"], "page absent")
self.assertEqual(payload["version_unread"], "tag ancestry unread: refused")
text = format_report(report)
self.assertIn("announced unreadable (page absent)", text)
self.assertIn("tag ancestry unread: refused", text)
class ARecaleKeepsTheRepositoryWord(unittest.TestCase):
"""`stella src/a.c:120` says the lines are in the stella repository. The
path is read without the word, and a recale wrote it back without it."""
def test_the_word_stays_in_front_of_the_new_span(self):
from model.sourceref import split_source_ref
for raw, expected in (
("stella src/a.c:120-130", "stella src/a.c:140-150"),
("stella src/a.c:120 (the table)", "stella src/a.c:140-150 (the table)"),
("src/a.c:120", "src/a.c:140-150"),
):
with self.subTest(raw=raw):
p = split_source_ref(raw)[0]
part = sourceref.RefPart(
profiling_citations.strip_repo_word(p.path, {"stella"}), p.start, p.end, p.raw)
result = anchoring.PartResult(part, "SHIFTED", None, 140, 150, [], "")
self.assertEqual(profiling_reports.rendered_part(result), expected)
class TestBranchProfiles(unittest.TestCase):
"""--changed and --added name the profiles a branch brings, not by hand."""
def setUp(self):
self._tmp = tempfile.TemporaryDirectory()
self.addCleanup(self._tmp.cleanup)
self.root = Path(self._tmp.name)
self._cwd = os.getcwd()
self.addCleanup(os.chdir, self._cwd)
os.chdir(self.root)
env = {**os.environ, "GIT_AUTHOR_NAME": "t", "GIT_AUTHOR_EMAIL": "t@t",
"GIT_COMMITTER_NAME": "t", "GIT_COMMITTER_EMAIL": "t@t"}
self.env = env
self._git("init", "-q", "-b", "main")
(self.root / "emulators").mkdir()
(self.root / "emulators" / "kept.yml").write_text("a: 1\n")
(self.root / "emulators" / "edited.yml").write_text("a: 1\n")
self._git("add", "emulators")
self._git("commit", "-q", "--no-verify", "-m", "base")
self._git("checkout", "-q", "-b", "topic")
(self.root / "emulators" / "edited.yml").write_text("a: 2\n")
(self.root / "emulators" / "new.yml").write_text("a: 1\n")
self._git("add", "emulators")
self._git("commit", "-q", "--no-verify", "-m", "topic")
(self.root / "emulators" / "draft.yml").write_text("a: 1\n")
(self.root / "emulators" / "notes.txt").write_text("x\n")
def _git(self, *args):
subprocess.run(["git", *args], cwd=self.root, env=self.env, check=True)
def test_changed_takes_added_edited_and_uncommitted(self):
self.assertEqual(
profiling_worktree.branch_profiles("emulators", "main", added_only=False),
["draft", "edited", "new"],
)
def test_added_leaves_edited_profiles_out(self):
self.assertEqual(
profiling_worktree.branch_profiles("emulators", "main", added_only=True),
["draft", "new"],
)
def test_an_unfetched_base_says_to_fetch(self):
"""`--base upstream/main` with upstream added and never fetched
stopped on git's "Not a valid object name" and no next step."""
with self.assertRaises(SystemExit) as raised:
profiling_worktree.branch_profiles("emulators", "upstream/main", added_only=True)
self.assertIn("git fetch upstream", str(raised.exception))
def test_the_flag_selects_those_profiles(self):
args = profile_sync.build_parser().parse_args(["--changed", "--base", "main"])
profiles = {"kept": {}, "edited": {}, "new": {}, "draft": {}}
self.assertEqual(
list(select_profiles(profiles, args)),
["draft", "edited", "new"],
)
def test_a_fork_clone_compares_with_the_project(self):
"""origin is the fork, pushed: origin/main is HEAD, and the default
base found nothing to check while the PR's CI failed."""
base = subprocess.run(
["git", "rev-parse", "main"], cwd=self.root, capture_output=True,
text=True, check=True,
).stdout.strip()
self._git("remote", "add", "origin", "https://github.com/someone/retrobios")
self._git("remote", "add", "upstream", "https://github.com/Abdess/retrobios")
self._git("update-ref", "refs/remotes/origin/main", "HEAD")
self._git("update-ref", "refs/remotes/upstream/main", base)
args = profile_sync.build_parser().parse_args(["--changed"])
profiles = {"kept": {}, "edited": {}, "new": {}, "draft": {}}
self.assertEqual(
list(select_profiles(profiles, args)),
["draft", "edited", "new"],
)
class TestBranchCheckIsWired(unittest.TestCase):
"""CONTRIBUTING and CI name the branch's profiles through the flag."""
def test_contributing_and_ci_use_the_flags(self):
root = Path(__file__).resolve().parents[1]
from sitegen import readme
text = readme.generate_contributing()
self.assertIn("profile_sync.py --added --strict", text)
# The default base is fetched by the tool: a documented upstream
# remote failed every clone that had origin alone.
self.assertNotIn("--base upstream/main", text)
self.assertNotIn("remote add upstream", text)
self.assertNotIn("--emulator NAME --strict", text)
workflow = (root / ".github" / "workflows" / "validate.yml").read_text()
self.assertIn("profile_sync.py --added --base", workflow)
self.assertNotIn('--emulator "$name"', workflow)
if __name__ == "__main__":
unittest.main()
+425
View File
@@ -0,0 +1,425 @@
"""Tests for the profile_sync version check, new file detection and drift score (no network)."""
from __future__ import annotations
import tests
import tempfile
import unittest
from profiling import versions
from profiling.reports import (
ProfileReport,
)
from profiling.versions import VersionReport, check_version, version_warning
from profiling.detection import (
declared_hashes,
declared_names,
detect_new_files,
tree_diff,
unified_for_path,
watch_hashes,
)
from profiling.triage import drift_score
from core import upstream
from core import forgehttp
from core import upstreamtree
from profiling import versionbasis
from core.upstreamtree import CompareResult, FileChange
from tests.profilesyncsupport import setUpModule as setUpModule
from tests.profilesyncsupport import tearDownModule as tearDownModule
class TestCheckVersion(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
self.dir = self.tmp.name
self.repo = upstream.parse_repo("https://github.com/o/n")
self._orig = (
upstream.latest_release,
upstream.list_tags,
upstream.resolve_tag_commit,
upstream.tag_commit,
)
upstream.latest_release = (
lambda repo, cache, offline=False: upstream.Release(
"v3.1.2", "2026-06-14", False
)
)
upstream.list_tags = (
lambda repo, cache, offline=False: ["v3.1.2", "v3.0.0"]
)
upstream.resolve_tag_commit = (
lambda repo, tag, cache, offline=False: (
"tagsha" if tag == "v3.0.0" else None
)
)
upstream.tag_commit = upstream.resolve_tag_commit
def _check(self, declared, tag=None):
named = versionbasis.VersionTag("", declared, tag or declared, 0, self.repo, "source")
return check_version(named, self.dir, False)
def tearDown(self):
(
upstream.latest_release,
upstream.list_tags,
upstream.resolve_tag_commit,
upstream.tag_commit,
) = self._orig
self.tmp.cleanup()
def test_reports_declared_and_latest(self):
result = self._check("v3.0.0")
self.assertEqual(result.declared, "v3.0.0")
self.assertEqual(result.latest_release, "v3.1.2")
self.assertEqual(result.release_date, "2026-06-14")
def test_detects_declared_version_is_a_tag(self):
result = self._check("v3.0.0")
self.assertTrue(result.tag_matches_declared)
self.assertEqual(result.tag_commit, "tagsha")
def test_declared_version_not_a_tag(self):
result = self._check("5.2")
self.assertFalse(result.tag_matches_declared)
self.assertIsNone(result.tag_commit)
def test_none_without_core_version(self):
self.assertIsNone(self._check(""))
def test_warning_when_tag_commit_differs_from_pin(self):
result = self._check("v3.0.0")
self.assertIsNotNone(version_warning(result, "otherpin"))
def test_no_warning_when_tag_commit_matches_pin(self):
result = self._check("v3.0.0")
self.assertIsNone(version_warning(result, "tagsha"))
def test_warning_says_which_side_of_the_tag_the_pin_is(self):
# 52 warnings read alike: a build after its release and a pin older
# than the release it claims could not be told apart.
result = self._check("v3.0.0")
self.assertIn("4 commits after the tag", version_warning(result, "p", (4, 0)))
self.assertIn("core_version is later than the code",
version_warning(result, "p", (0, 9)))
self.assertIn("off the tag's history", version_warning(result, "p", (2, 3)))
def test_warning_names_a_release_the_pin_already_contains(self):
result = self._check("v3.0.0")
warning = version_warning(result, "tagsha", None, "v3.1.0")
self.assertIn("already contains release v3.1.0", warning)
class APassedReleaseIsNewerThanTheTag(unittest.TestCase):
"""pcsx2x6 declares tag v0.2.22 while its latest published release is
v0.2.20: the pin holds v0.2.20 without core_version being older."""
def test_a_release_older_than_the_declared_tag_is_not_passed(self):
from unittest import mock
version = versions.VersionReport(
"v0.2.22", "v0.2.22", "v0.2.20", "2026-07-25", True, "tag22"
)
with mock.patch.object(upstream, "tag_commit", return_value="rel20"), \
mock.patch.object(upstreamtree, "ancestry", return_value=(5, 0)):
self.assertIsNone(versions.latest_passed_release("repo", version, "pin", "c", True))
class ANewerReleaseThanTheTag(unittest.TestCase):
"""armsx2 sat on its 2.8 tag while 2.9 was out, and read as clean."""
def _newer(self, after_tag, after_pin):
from unittest import mock
version = versions.VersionReport("2.8", "2.9", "2.9", "2026-10-01", True, "tag28")
answers = iter([after_tag, after_pin])
with mock.patch.object(upstream, "tag_commit", return_value="rel29"), \
mock.patch.object(upstreamtree, "ancestry", side_effect=lambda *a, **k: next(answers)):
return versions.newer_release("repo", version, "tag28", "c", True)
def test_a_later_release_is_named(self):
self.assertEqual(self._newer((12, 0), (12, 0)), "2.9")
def test_an_older_or_unrelated_release_is_not(self):
self.assertIsNone(self._newer((0, 5), (0, 5)))
self.assertIsNone(self._newer((3, 4), (3, 4)))
class AProjectThatOnlyTags(unittest.TestCase):
"""eightyone sat on v1.2 and higan on 106 while v1.3 and v107 were tagged:
with no release published, nothing compared them."""
def test_a_version_tag_stands_in_for_the_missing_release(self):
version = versions.VersionReport("v1.2", "v1.3", None, None, True, "tag12")
self.assertEqual(versions.published_version(version), "v1.3")
for tag in ("v107", "1.1d", "v9.0-6", "2.55"):
version = versions.VersionReport("x", tag, None, None, False, None)
self.assertEqual(versions.published_version(version), tag)
def test_a_nightly_tag_does_not(self):
for tag in ("latest-nightly", "continuous", "nightly-20261001"):
version = versions.VersionReport("v1.2", tag, None, None, True, "t")
self.assertIsNone(versions.published_version(version))
def test_a_release_wins_over_a_newer_tag(self):
version = versions.VersionReport("1.0", "1.2", "1.1", "2026-01-01", True, "t")
self.assertEqual(versions.published_version(version), "1.1")
def test_a_newer_tag_is_named(self):
from unittest import mock
version = versions.VersionReport("v1.2", "v1.3", None, None, True, "tag12")
with mock.patch.object(upstream, "tag_commit", return_value="tag13"), \
mock.patch.object(upstreamtree, "ancestry", return_value=(7, 0)):
self.assertEqual(versions.newer_release("repo", version, "tag12", "c", True), "v1.3")
class APassedReleaseUnderAnUntaggedVersion(unittest.TestCase):
"""parallel-launcher declared 9.0.5, a name no tag carries, and its HEAD
already held release v9.0-6: the missing tag silenced the warning."""
def test_the_passed_release_is_named_without_a_declared_tag(self):
version = versions.VersionReport("9.0.5", "v9.0-6", "v9.0-6", "2026-08-08", False, None)
warning = version_warning(version, "head", None, "v9.0-6")
self.assertIn("already contains release v9.0-6", warning)
def test_only_a_higher_number_counts_without_a_tag(self):
from unittest import mock
cases = {("9.0.5", "v9.0-6"): "v9.0-6", ("1.61", "1.53"): None,
("v0.1-12070", "latest"): None, ("Git", "v2.7"): None, ("5.2", "v5.2"): None,
("v1", "v1.0"): None, ("0.83", "20120302"): None, ("0.160", "v1.4.1"): None,
("0.0.35", "v0.0.43"): "v0.0.43", ("106", "v107"): "v107", ("v1", "20170424"): None}
for (declared, release), expected in cases.items():
version = versions.VersionReport(declared, release, release, "d", False, None)
with self.subTest(declared=declared, release=release), \
mock.patch.object(upstream, "tag_commit", return_value="rel"), \
mock.patch.object(upstreamtree, "ancestry", return_value=(3, 0)):
self.assertEqual(versions.latest_passed_release("repo", version, "pin", "c", True), expected)
def test_no_tag_and_nothing_passed_stays_quiet(self):
version = versions.VersionReport("9.0.5", None, None, None, False, None)
self.assertIsNone(version_warning(version, "head"))
@tests.ONLINE
class TestAncestry(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
self.saved = forgehttp.http_json
def tearDown(self):
forgehttp.http_json = self.saved
self.tmp.cleanup()
def test_github_answers_both_directions_at_once(self):
calls = []
def answer(url):
calls.append(url)
return {"ahead_by": 3, "behind_by": 0}
forgehttp.http_json = answer
repo = upstream.parse_repo("https://github.com/o/n")
self.assertEqual(
upstreamtree.ancestry(repo, "tag", "pin", self.tmp.name), (3, 0)
)
self.assertEqual(len(calls), 1)
def test_gitlab_is_asked_both_ways(self):
def answer(url):
forward = "from=tag&to=pin" in url
return {"commits": [{}] * (0 if forward else 5)}
forgehttp.http_json = answer
repo = upstream.parse_repo("https://gitlab.com/o/n")
self.assertEqual(
upstreamtree.ancestry(repo, "tag", "pin", self.tmp.name), (0, 5)
)
HASH_PROFILE = {
"files": [
{
"name": "scph5500.bin",
"sha1": "B05DEF971D8EC59F346F2D9AC21FB742E3EB6917",
"aliases": ["SCPH-5500.bin"],
},
{"name": "gba_bios.bin", "md5": "a860e8c0b6d573d191e4ec7db1b1e4f6"},
]
}
class TestDeclared(unittest.TestCase):
def test_names_include_aliases_casefolded(self):
names = declared_names(HASH_PROFILE)
self.assertIn("scph5500.bin", names)
self.assertIn("scph-5500.bin", names)
def test_hashes_lowercased(self):
self.assertIn(
"b05def971d8ec59f346f2d9ac21fb742e3eb6917", declared_hashes(HASH_PROFILE)
)
class TestDetectNewFiles(unittest.TestCase):
def test_finds_undeclared_filename(self):
lines = ['load("scph5500.bin");', 'load("scph7001.bin");']
found, elided = detect_new_files(lines, declared_names(HASH_PROFILE))
self.assertEqual(found, [(2, "scph7001.bin")])
self.assertEqual(elided, 0)
def test_ignores_declared_alias(self):
found, _ = detect_new_files(
['open("SCPH-5500.bin")'], declared_names(HASH_PROFILE)
)
self.assertEqual(found, [])
def test_cap_reports_elided_count(self):
lines = [f'load("rom{i}.bin");' for i in range(40)]
found, elided = detect_new_files(lines, set(), cap=25)
self.assertEqual(len(found), 25)
self.assertEqual(elided, 15)
def test_source_file_extensions_are_not_matched(self):
found, _ = detect_new_files(['#include "driver.cpp"'], set())
self.assertEqual(found, [])
def test_a_printf_conversion_is_not_part_of_the_name(self):
# sdl2trs src/trs_options.c:864-866 builds "%slevel2.rom" and the
# report named slevel2.rom.
lines = [
'snprintf(romfile1, sizeof(romfile1), "%slevel2.rom", ROM_PATH);',
'snprintf(name, 64, "%02dcart.bin", slot);',
]
found, _ = detect_new_files(lines, set(), path="src/trs_options.c")
self.assertEqual(found, [(1, "level2.rom"), (2, "cart.bin")])
def test_a_quoted_name_with_spaces_is_read_whole(self):
# virtualjaguar libretro.c:5815-5816 opens "Jaguar CD BIOS.rom",
# reported as BIOS.rom. A sentence still yields the name it holds.
lines = [
'snprintf(path, n, "%s%c%s", dir, slash, "Jaguar CD BIOS.rom");',
'log("Please insert bios.bin first");',
'message(STATUS "Packing patches.zip")',
'#define ROM ".bin.hex.iii.rom"',
]
found, _ = detect_new_files(lines, set(), path="libretro.c")
self.assertEqual(
found,
[(1, "Jaguar CD BIOS.rom"), (2, "bios.bin"), (3, "patches.zip")],
)
def test_an_identifier_in_code_is_not_a_file(self):
# pcee2 reads config keys EE.bios and IOP.bios and a field psm_s.pal.
lines = [
"cfg.EE.bios = load(path);",
"if (psm_s.pal) {",
"// loads boot.rom from the system directory",
'open("ipl.rom");',
]
found, _ = detect_new_files(lines, set(), path="src/core/config.cpp")
self.assertEqual(found, [(3, "boot.rom"), (4, "ipl.rom")])
found, _ = detect_new_files(["Copy EE.bios here"], set(), path="README.md")
self.assertEqual(found, [(1, "EE.bios")])
class TestWatchHashes(unittest.TestCase):
def test_finds_new_sha1(self):
added = ['+ { "x.bin", "0123456789abcdef0123456789abcdef01234567" },']
found = watch_hashes(added, declared_hashes(HASH_PROFILE))
self.assertEqual(found[0][1], "0123456789abcdef0123456789abcdef01234567")
def test_ignores_declared_hash(self):
added = ["+ b05def971d8ec59f346f2d9ac21fb742e3eb6917"]
self.assertEqual(watch_hashes(added, declared_hashes(HASH_PROFILE)), [])
def test_crc32_needs_a_filename_on_the_line(self):
self.assertEqual(watch_hashes(["+ mask = 0xdeadbeef;"], set()), [])
found = watch_hashes(['+ { "a.rom", 0xdeadbeef }'], set())
self.assertEqual(found[0][1], "deadbeef")
class TestUnifiedForPath(unittest.TestCase):
def test_produces_a_hunk(self):
out = unified_for_path(["a", "b"], ["a", "c"], "f.c", 1)
self.assertIn("-b", out)
self.assertIn("+c", out)
self.assertIn("f.c", out)
def test_identical_files_produce_nothing(self):
self.assertEqual(unified_for_path(["a"], ["a"], "f.c", 3), "")
class TestTreeDiff(unittest.TestCase):
def test_filters_to_ref_directories(self):
result = CompareResult(
[
FileChange("added", "src/new.cpp", None),
FileChange("added", "docs/readme.md", None),
],
False,
)
self.assertEqual(tree_diff(result, {"src"}), ["added src/new.cpp"])
def test_rename_shows_both_paths(self):
result = CompareResult([FileChange("renamed", "src/b.c", "src/a.c")], False)
self.assertEqual(tree_diff(result, {"src"}), ["renamed src/a.c -> src/b.c"])
def test_repository_root_is_a_directory(self):
result = CompareResult(
[
FileChange("modified", "libretro.c", None),
FileChange("modified", "deps/lightning/lib/jit_arm.c", None),
],
False,
)
self.assertEqual(tree_diff(result, {""}), ["modified libretro.c"])
def test_empty_ref_dirs_show_everything(self):
result = CompareResult([FileChange("modified", "a/b.c", None)], False)
self.assertEqual(tree_diff(result, set()), ["modified a/b.c"])
def test_truncation_is_announced(self):
result = CompareResult([FileChange("added", "src/a.c", None)], True)
self.assertIn("truncated", "\n".join(tree_diff(result, {"src"})))
class TestDriftScore(unittest.TestCase):
def test_review_statuses_dominate(self):
heavy = ProfileReport(name="a", entries=[], counts={"GONE": 1})
light = ProfileReport(name="b", entries=[], counts={"SHIFTED": 20})
self.assertGreater(drift_score(heavy, [], 0), drift_score(light, [], 0))
def test_version_mismatch_adds_weight(self):
report = ProfileReport(name="a", entries=[], counts={})
stale = VersionReport("v1.0", "v2.0", "v2.0", "2026-06-01", False, None)
current = VersionReport("v2.0", "v2.0", "v2.0", "2026-06-01", True, None)
self.assertGreater(
drift_score(report, [stale], 0), drift_score(report, [current], 0)
)
def test_commit_count_is_a_light_signal(self):
report = ProfileReport(name="a", entries=[], counts={})
self.assertGreater(drift_score(report, [], 100), drift_score(report, [], 0))
def test_clean_profile_scores_zero(self):
report = ProfileReport(name="a", entries=[], counts={"ANCHORED": 5})
self.assertEqual(drift_score(report, [], 0), 0)
def test_a_pin_to_set_again_outranks_a_gone_ref(self):
"""pcem ranked last at 0 with "1 to review, 1 orphaned pin": its
upstream_commit had left every branch of a force-pushed repository."""
gone = ProfileReport(name="a", entries=[], counts={"GONE": 1})
orphaned = ProfileReport(name="pcem", entries=[], counts={},
orphaned=["upstream_commit 25b54e3f"])
moved = ProfileReport(name="m", entries=[], counts={},
moved_repos=["a/b answers as c/b"])
for report in (orphaned, moved):
with self.subTest(name=report.name):
self.assertGreater(drift_score(report, [], 0), drift_score(gone, [], 0))
if __name__ == "__main__":
unittest.main()
File diff suppressed because it is too large. Load diff
+2 -2
View File
@@ -516,7 +516,7 @@ subset:
| File | Coverage |
|------|----------|
| `test_e2e_*.py` | resolution, verification, packs, inheritance, targets, truth and exporters |
| `test_profile_sync.py`, `test_upstream.py` | source anchoring, forge parsing, revisions, cache and guarded writes |
| `test_profile_sync_*.py`, `test_upstream.py` | source anchoring, forge parsing, revisions, cache and guarded writes |
| `test_install_bootstrap.py`, `test_audit_*.py` | automatic wrappers, manifest boundaries, pipeline exits, strong hashes and safe archives |
| `test_region.py` | region vocabulary, ranking, per-system grouping and repository conformance |
| `test_site_exports.py`, `test_site_validation.py` | versioned exports, SQLite, metadata, accessibility structure and complete local-link graph |
@@ -529,7 +529,7 @@ python -m unittest tests.test_e2e_region -v # single module
```
`test_e2e_*.py`, `test_install_detection.py`, `test_provenance.py`, the parser tests,
`test_profile_sync.py` and `test_upstream.py` run on synthetic fixtures with no
`test_profile_sync_*.py` and `test_upstream.py` run on synthetic fixtures with no
network and no real BIOS files. `test_pack_integrity.py`, `test_torrentzip.py` and
`test_no_case_collisions.py` read the working tree and skip when the data they
need is absent. See the [testing guide](testing-guide.md) for the fixture
+5 -3
View File
@@ -80,7 +80,7 @@ Every module in `tests/`, by the area it guards.
| Automation runner, disk cleanup, asset sync and bit-flip repair | fake jobs, git repositories with a bare origin and session worktrees, a committed file with one bit flipped, canned CI runs in place of `gh` | `test_autorun` |
| Flat-tree migration | a flat system folder copied into a temporary tree, its plan said through the caller, and a failed copy named once by `migrate.py` | `test_bios_migrate` |
| Truth and native export | synthetic + cached originals | `test_export_counts`, `test_export_native_layer`, `test_export_report`, `test_exporters`, `test_truth_data_dir_readers`, `test_truth_diff`, `test_truth_layout` |
| Scrapers, upstream and provenance | inline sources, synthetic | `test_auto_fetch_lookup`, `test_batocera_md5_list`, `test_find_embedded`, `test_report_excerpt`, `test_check_freshness`, `test_cited_lines`, `test_contributing_text`, `test_coverage_cache`, `test_data_dir_refs`, `test_dataclass_defaults`, `test_dedup`, `test_doc_pages`, `test_doc_surfaces`, `test_elec_scrapers`, `test_fbneo_parser`, `test_find_pinned_revision`, `test_hash_merge`, `test_launchers`, `test_launchers_amberelec`, `test_launchers_emudeck`, `test_launchers_emuelec`, `test_launchers_knulli`, `test_launchers_recalbox`, `test_launchers_retrobat`, `test_launchers_retrodeck`, `test_launchers_retropie`, `test_launchers_rocknix`, `test_lines`, `test_listxml`, `test_mame_devices`, `test_mame_parser`, `test_mame_ref_audit`, `test_optional_dependencies`, `test_pin_build`, `test_profile_sync`, `test_prose_style`, `test_provenance`, `test_refresh_data_dirs`, `test_refresh_failures`, `test_refresh_stale`, `test_retired_files`, `test_retrodeck_component_md5`, `test_retrodeck_scraper_errors`, `test_romset_recipes`, `test_schema_semantic_gate`, `test_scraper_contract`, `test_scraper_dropped`, `test_scraper_network`, `test_site_agents`, `test_site_arcade_boards`, `test_site_availability`, `test_site_bootstrap`, `test_site_built_gate`, `test_site_components`, `test_site_console_folders`, `test_site_content_data`, `test_site_copy`, `test_site_cores`, `test_site_css`, `test_site_demo`, `test_site_density_cards`, `test_site_emulator_page`, `test_site_emulators`, `test_site_entry`, `test_site_entry_tables`, `test_site_exports`, `test_site_freshness`, `test_site_funnel`, `test_site_images`, `test_site_inputs`, `test_site_insights`, `test_site_integration`, `test_site_nav`, `test_site_page_text`, `test_site_picker`, `test_site_platform_density`, `test_site_platform_hashes`, `test_site_privacy`, `test_site_pronouns`, `test_site_reference`, `test_site_render`, `test_site_search`, `test_site_steps`, `test_site_system_links`, `test_site_system_names`, `test_site_system_sections`, `test_site_systems`, `test_site_validation`, `test_site_wanted`, `test_site_weight`, `test_site_wiki`, `test_site_write`, `test_source_ref_targets`, `test_text`, `test_upstream`, `test_upstream_index`, `test_validate_pr`, `test_validate_pr_flow`, `test_validate_pr_hashes`, `test_version_basis`, `test_workflow_paths` |
| Scrapers, upstream and provenance | inline sources, synthetic | `test_auto_fetch_lookup`, `test_batocera_md5_list`, `test_find_embedded`, `test_report_excerpt`, `test_check_freshness`, `test_cited_lines`, `test_contributing_text`, `test_coverage_cache`, `test_data_dir_refs`, `test_dataclass_defaults`, `test_dedup`, `test_doc_pages`, `test_doc_surfaces`, `test_elec_scrapers`, `test_fbneo_parser`, `test_find_pinned_revision`, `test_hash_merge`, `test_launchers`, `test_launchers_amberelec`, `test_launchers_emudeck`, `test_launchers_emuelec`, `test_launchers_knulli`, `test_launchers_recalbox`, `test_launchers_retrobat`, `test_launchers_retrodeck`, `test_launchers_retropie`, `test_launchers_rocknix`, `test_lines`, `test_listxml`, `test_mame_devices`, `test_mame_parser`, `test_mame_ref_audit`, `test_optional_dependencies`, `test_pin_build`, `test_profile_sync_anchoring`, `test_profile_sync_cli`, `test_profile_sync_prose`, `test_profile_sync_report`, `test_profile_sync_repositories`, `test_profile_sync_versions`, `test_profile_sync_writes`, `test_prose_style`, `test_provenance`, `test_refresh_data_dirs`, `test_refresh_failures`, `test_refresh_stale`, `test_retired_files`, `test_retrodeck_component_md5`, `test_retrodeck_scraper_errors`, `test_romset_recipes`, `test_schema_semantic_gate`, `test_scraper_contract`, `test_scraper_dropped`, `test_scraper_network`, `test_site_agents`, `test_site_arcade_boards`, `test_site_availability`, `test_site_bootstrap`, `test_site_built_gate`, `test_site_components`, `test_site_console_folders`, `test_site_content_data`, `test_site_copy`, `test_site_cores`, `test_site_css`, `test_site_demo`, `test_site_density_cards`, `test_site_emulator_page`, `test_site_emulators`, `test_site_entry`, `test_site_entry_tables`, `test_site_exports`, `test_site_freshness`, `test_site_funnel`, `test_site_images`, `test_site_inputs`, `test_site_insights`, `test_site_integration`, `test_site_nav`, `test_site_page_text`, `test_site_picker`, `test_site_platform_density`, `test_site_platform_hashes`, `test_site_privacy`, `test_site_pronouns`, `test_site_reference`, `test_site_render`, `test_site_search`, `test_site_steps`, `test_site_system_links`, `test_site_system_names`, `test_site_system_sections`, `test_site_systems`, `test_site_validation`, `test_site_wanted`, `test_site_weight`, `test_site_wiki`, `test_site_write`, `test_source_ref_targets`, `test_text`, `test_upstream`, `test_upstream_index`, `test_validate_pr`, `test_validate_pr_flow`, `test_validate_pr_hashes`, `test_version_basis`, `test_workflow_paths` |
| Games on the card | small DATs, listxml and setup sources, a fake fetcher, fixture install lists, and the committed data against its schemas | `test_arcade_parents`, `test_game_catalogs`, `test_game_headers`, `test_game_regions`, `test_games_index`, `test_romfolders_card`, `test_romfolders_es` |
## Test architecture
@@ -193,9 +193,11 @@ config-file key parsing in `test_install_config`, handhelds, boards and target
filtering in `test_install_devices`, manifest loading in
`test_install_platforms`, and destination resolution in `test_install_runs`.
**test_profile_sync.** Covers ref anchoring end to end: the six statuses,
**test_profile_sync_\*.** Cover ref anchoring end to end: the six statuses,
widening a one-line anchor until it is unique, refusing to rebase an ambiguous
one, following a rename, and the guarded YAML writes. Network access is
one, following a rename, and the guarded YAML writes. One module per subject:
`anchoring`, `report`, `writes`, `prose`, `versions`, `repositories` and `cli`,
with their shared fixtures in `tests/profilesyncsupport.py`. Network access is
replaced by an injected fetch function.
**test_upstream.** Covers forge URL parsing for GitHub, GitLab and Forgejo,