refactor: move recipes and acquisition to packages

This commit is contained in:
Abdessamad Derraz committed 2026-11-18 19:49:49 +01:00
1 parent 664776ae91
commit 0e4e5f450d
35 files changed
+2186 -2071

No files matched your search

+25 -23
View File
@@ -18,7 +18,9 @@ import zipfile
from pathlib import Path
from unittest import mock
import archive_build
from recipes import build as recipes_build
from recipes import capture as recipes_capture
from recipes import ledger
from core.torrentzip import build_torrentzip
ROOT = Path(__file__).resolve().parent.parent
@@ -41,8 +43,8 @@ class TheLedgerCoversTheCollection(unittest.TestCase):
def setUpClass(cls):
with (ROOT / "database.json").open(encoding="utf-8") as handle:
cls.db = json.load(handle)
cls.ledger = archive_build.load_ledger()
cls.archives = archive_build.database_archives(cls.db)
cls.ledger = ledger.load_ledger()
cls.archives = ledger.database_archives(cls.db)
def test_every_database_archive_has_a_recipe(self):
absent = sorted(set(self.archives) - set(self.ledger))
@@ -77,15 +79,15 @@ class TheLedgerCoversTheCollection(unittest.TestCase):
def test_every_member_is_held_in_the_collection(self):
"""The list printed here is the acquisition list: a member neither held
as a loose file nor inside any archive the database lists."""
missing = archive_build.missing_members(self.ledger, self.db)
missing = ledger.missing_members(self.ledger, self.db)
listing = "\n".join(
f" {m['archive']}: {m['member']} ({m['sha1']})" for m in missing
)
self.assertEqual(missing, [], f"members held nowhere:\n{listing}")
def test_the_file_is_written_the_one_way(self):
text = archive_build.ARCHIVES_FILE.read_text(encoding="utf-8")
self.assertEqual(text, archive_build.ledger_text(self.ledger))
text = ledger.ARCHIVES_FILE.read_text(encoding="utf-8")
self.assertEqual(text, ledger.ledger_text(self.ledger))
def test_recipes_describe_the_archives_on_disk(self):
"""Names in order, sizes and crc32 against each central directory."""
@@ -139,7 +141,7 @@ class Fixture(unittest.TestCase):
self.temp.cleanup()
def capture(self, **kwargs) -> dict[str, dict]:
records, failed = archive_build.capture(
records, failed = recipes_capture.capture(
self.db, kwargs.get("previous", {}), kwargs.get("index", {}),
kwargs.get("pins", {}), workers=1, log=lambda _line: None,
)
@@ -175,7 +177,7 @@ class Capture(Fixture):
self.assertEqual(exact["sources"], ["collection"])
def test_dat_agreement_and_pins_are_recorded(self):
key = archive_build.member_key(
key = recipes_capture.member_key(
[{"name": n, "crc32": c} for n, c in (
("a.rom", self._crc(ROM_A)), ("b.rom", self._crc(ROM_B)),
("c.rom", self._crc(ROM_C)),
@@ -197,8 +199,8 @@ 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"), \
self.assertRaises(archive_build.ZlibNgError):
with mock.patch.object(recipes_build, "zlib_ng_version", lambda: "2.2.4"), \
self.assertRaises(recipes_capture.ZlibNgError):
self.capture()
def test_composite_and_zipped_pins_name_no_container(self):
@@ -229,7 +231,7 @@ class Capture(Fixture):
f" - name: set.zip\n sha1: {'d' * 40}\n",
encoding="utf-8",
)
pins = archive_build.container_pins(str(platforms), str(emulators))
pins = recipes_capture.container_pins(str(platforms), str(emulators))
self.assertEqual(pins, {"a" * 32: {"platform:plain"}, "d" * 40: {"profile:core"}})
@staticmethod
@@ -248,11 +250,11 @@ class Build(Fixture):
os.chdir(self.root)
self.ledger = self.capture()
os.chdir(self._cwd)
self.atoms = archive_build.AtomIndex.from_collection(self.ledger, self.db, self.root)
self.atoms = recipes_build.AtomIndex.from_collection(self.ledger, self.db, self.root)
self.out = self.root / "out"
def build(self, path: str):
return archive_build.build_archive(self.ledger[path], self.atoms, self.out, self.root)
return recipes_build.build_archive(self.ledger[path], self.atoms, self.out, self.root)
def test_an_exact_recipe_rebuilds_the_bytes(self):
result = self.build("bios/set.zip")
@@ -279,14 +281,14 @@ class Build(Fixture):
record["members"] = record["members"] + [
{"name": "gone.rom", "size": 1, "crc32": "00000000", "sha1": "f" * 40}
]
result = archive_build.build_archive(record, self.atoms, self.out, self.root)
result = recipes_build.build_archive(record, self.atoms, self.out, self.root)
self.assertEqual(result.status, "impossible")
self.assertEqual([m["name"] for m in result.missing], ["gone.rom"])
self.assertFalse(self.out.exists())
def test_a_mismatch_is_never_promoted(self):
record = dict(self.ledger["bios/set.zip"], sha1="0" * 40)
result = archive_build.build_archive(record, self.atoms, self.out, self.root)
result = recipes_build.build_archive(record, self.atoms, self.out, self.root)
self.assertEqual(result.status, "failed")
self.assertIn("is not the recorded", result.detail)
self.assertEqual(list(self.out.rglob("*")), [], "no file, no scratch left")
@@ -295,37 +297,37 @@ class Build(Fixture):
record = dict(self.ledger["bios/other.zip"])
record["members"] = [dict(m) for m in record["members"]]
record["members"][0]["crc32"] = "00000000"
result = archive_build.build_archive(record, self.atoms, self.out, self.root)
result = recipes_build.build_archive(record, self.atoms, self.out, self.root)
self.assertEqual(result.status, "failed")
self.assertEqual(list(self.out.rglob("*")), [])
def test_zlib_ng_never_claims_exact(self):
with mock.patch.object(archive_build, "zlib_ng_version", lambda: "2.2.4"):
with mock.patch.object(recipes_build, "zlib_ng_version", lambda: "2.2.4"):
result = self.build("bios/set.zip")
self.assertEqual(result.status, "canonical")
self.assertIn("zlib-ng 2.2.4", result.detail)
def test_an_archive_is_named_by_path_or_by_name(self):
self.assertEqual(
[r["path"] for r in archive_build.select(self.ledger, "set.zip", self.root)],
[r["path"] for r in recipes_build.select(self.ledger, "set.zip", self.root)],
["bios/set.zip"],
)
self.assertEqual(
len(archive_build.select(self.ledger, str(self.exact_path), self.root)), 1
len(recipes_build.select(self.ledger, str(self.exact_path), self.root)), 1
)
self.assertEqual(archive_build.select(self.ledger, "none.zip", self.root), [])
self.assertEqual(recipes_build.select(self.ledger, "none.zip", self.root), [])
def test_missing_members_reads_the_committed_data(self):
self.assertEqual(archive_build.missing_members(self.ledger, self.db), [])
self.assertEqual(ledger.missing_members(self.ledger, self.db), [])
del self.db["files"][_sha1(self.exact_path.read_bytes())]
missing = archive_build.missing_members(self.ledger, self.db)
missing = ledger.missing_members(self.ledger, self.db)
self.assertEqual(
[(m["archive"], m["member"]) for m in missing], [("bios/set.zip", "c.rom")]
)
def test_the_command_reports_each_archive(self):
archives = self.root / "archives.json"
archives.write_text(archive_build.ledger_text(self.ledger), encoding="utf-8")
archives.write_text(ledger.ledger_text(self.ledger), encoding="utf-8")
db = self.root / "database.json"
db.write_text(json.dumps(self.db), encoding="utf-8")
run = subprocess.run(
+1 -1
View File
@@ -85,7 +85,7 @@ def _hashes(values: object) -> set[str]:
def _allowed_members() -> dict[str, set[str]]:
from model.profiles import load_emulator_profiles
from romset_recipes import load_dat_recipes
from recipes.romsets import load_dat_recipes
allowed: dict[str, set[str]] = defaultdict(set)
for archive, per_label in load_dat_recipes(REPO_ROOT / "recipes").items():
+32 -32
View File
@@ -922,17 +922,17 @@ class AutoFetchReadsListsAndPlacesWithoutClobbering(unittest.TestCase):
def test_a_hash_list_is_every_accepted_revision(self):
import hashlib
from scripts import auto_fetch
from scripts.acquire import fetch as acquire_fetch
data = b"second revision"
entry = {"sha1": ["0" * 40, hashlib.sha1(data).hexdigest()]}
self.assertTrue(auto_fetch.verify_content(data, entry))
self.assertTrue(acquire_fetch.verify_content(data, entry))
db = {"files": {hashlib.sha1(data).hexdigest(): {"path": "bios/x/n64.psh"}},
"indexes": {"by_md5": {}}}
self.assertEqual(auto_fetch.step1_crossref_db(entry, db), "bios/x/n64.psh")
self.assertEqual(acquire_fetch.step1_crossref_db(entry, db), "bios/x/n64.psh")
def test_the_whole_slug_picks_the_folder_and_nothing_is_overwritten(self):
from scripts import auto_fetch
from scripts.acquire import fetch as acquire_fetch
with tempfile.TemporaryDirectory(dir=TMP_ROOT) as directory:
bios = Path(directory)
@@ -940,7 +940,7 @@ class AutoFetchReadsListsAndPlacesWithoutClobbering(unittest.TestCase):
(bios / folder).mkdir(parents=True)
held = bios / "Nintendo" / "N64" / "n64.psh"
held.write_bytes(b"other revision")
placed = Path(auto_fetch.place_file(
placed = Path(acquire_fetch.place_file(
b"fetched", {"name": "n64.psh", "system": "nintendo-64"}, str(bios), {}
))
self.assertEqual(placed.parent.parent, bios / "Nintendo" / "N64")
@@ -4623,7 +4623,7 @@ class TheWantedPageCountsRomsetMembers(unittest.TestCase):
Wanted page asked for dumps the collection holds inside romsets."""
def test_members_are_read_unless_given(self):
from scripts import provenance_report
from scripts.acquire import provenance
calls = []
@@ -4631,9 +4631,9 @@ class TheWantedPageCountsRomsetMembers(unittest.TestCase):
calls.append(db)
return {}
with mock.patch.object(provenance_report, "archive_members", members):
provenance_report.build_report({"files": {}}, {})
provenance_report.build_report({"files": {}}, {}, {})
with mock.patch.object(provenance, "archive_members", members):
provenance.build_report({"files": {}}, {})
provenance.build_report({"files": {}}, {}, {})
self.assertEqual(len(calls), 1)
@@ -4644,7 +4644,7 @@ class AutoFetchAsksVerifyWhatIsMissing(unittest.TestCase):
file was ever one. 721 announced where verify saw none critical."""
def test_the_targets_are_verify_verdicts(self):
from scripts import auto_fetch
from scripts.acquire import fetch as acquire_fetch
from packs import coverage as packs_coverage
from packs import verdicts
@@ -4671,7 +4671,7 @@ class AutoFetchAsksVerifyWhatIsMissing(unittest.TestCase):
],
}
with mock.patch.object(packs_coverage, "verify_platform", lambda c, d: result):
names = [m["name"] for m in auto_fetch.find_missing(config, {})]
names = [m["name"] for m in acquire_fetch.find_missing(config, {})]
self.assertEqual(names, ["gone.bin", "bad.bin", "diabdat.mpq"])
@@ -6668,7 +6668,7 @@ class AnUnansweredSearchIsNotANotFound(unittest.TestCase):
def _fetch(self, error):
from unittest import mock
from scripts import auto_fetch
from scripts.acquire import fetch as acquire_fetch
def refuse(*_args, **_kwargs):
raise error
@@ -6676,9 +6676,9 @@ class AnUnansweredSearchIsNotANotFound(unittest.TestCase):
entry = {"name": "nowhere.bin", "system": "test-system", "sha1": "0" * 40}
db = {"files": {}, "indexes": {"by_md5": {}, "by_name": {}}}
with mock.patch("urllib.request.urlopen", refuse), \
mock.patch.object(auto_fetch, "step2_scan_branches", lambda e: None), \
mock.patch.object(acquire_fetch, "step2_scan_branches", lambda e: None), \
contextlib.redirect_stdout(io.StringIO()):
return auto_fetch.fetch_missing([entry], db, "bios")
return acquire_fetch.fetch_missing([entry], db, "bios")
def test_offline_is_not_searched(self):
import urllib.error
@@ -6705,21 +6705,21 @@ class AutoFetchProvesEveryHashItIsGiven(unittest.TestCase):
def test_a_sha256_proves_a_download(self):
import hashlib
from scripts import auto_fetch
from scripts.acquire import fetch as acquire_fetch
sha256 = {"sha256": hashlib.sha256(self.DATA).hexdigest()}
self.assertTrue(auto_fetch.verify_content(self.DATA, sha256))
self.assertFalse(auto_fetch.verify_content(b"other", sha256))
self.assertTrue(acquire_fetch.verify_content(self.DATA, sha256))
self.assertFalse(acquire_fetch.verify_content(b"other", sha256))
def test_every_declared_cryptographic_hash_must_match(self):
import hashlib
from scripts import auto_fetch
from scripts.acquire import fetch as acquire_fetch
both = {"sha256": hashlib.sha256(self.DATA).hexdigest(), "md5": "0" * 32}
self.assertFalse(auto_fetch.verify_content(self.DATA, both))
self.assertFalse(acquire_fetch.verify_content(self.DATA, both))
both["md5"] = hashlib.md5(self.DATA).hexdigest()
self.assertTrue(auto_fetch.verify_content(self.DATA, both))
self.assertTrue(acquire_fetch.verify_content(self.DATA, both))
def test_crc32_and_size_never_accept_a_download(self):
"""A crc32 can be forged: bytes a source crafts to it would land in
@@ -6728,44 +6728,44 @@ class AutoFetchProvesEveryHashItIsGiven(unittest.TestCase):
import zlib
from unittest import mock
from scripts import auto_fetch
from scripts.acquire import fetch as acquire_fetch
crc = {"name": "forged.bin", "system": "test-system",
"crc32": f"{zlib.crc32(self.DATA):08X}", "size": len(self.DATA)}
self.assertFalse(auto_fetch.verify_content(self.DATA, crc))
self.assertFalse(auto_fetch.verifiable(crc))
self.assertFalse(acquire_fetch.verify_content(self.DATA, crc))
self.assertFalse(acquire_fetch.verifiable(crc))
served = io.BytesIO(self.DATA)
with tempfile.TemporaryDirectory() as bios, \
mock.patch.object(urllib.request, "urlopen", lambda *a, **k: served), \
mock.patch.object(auto_fetch, "step2_scan_branches",
mock.patch.object(acquire_fetch, "step2_scan_branches",
lambda e: self.DATA), \
contextlib.redirect_stdout(io.StringIO()) as out:
result = auto_fetch.fetch_missing([crc], {"files": {}}, bios)
result = acquire_fetch.fetch_missing([crc], {"files": {}}, bios)
self.assertEqual(list(Path(bios).rglob("*")), [])
self.assertEqual(result["stats"]["found"], 0)
self.assertEqual(result["stats"]["unverifiable"], 1)
self.assertIn("declares no cryptographic hash", out.getvalue())
def test_a_held_sha256_is_found_in_the_database(self):
from scripts import auto_fetch
from scripts.acquire import fetch as acquire_fetch
db = {"files": {"s": {"path": "bios/x/dsi.bin", "size": 3}},
"indexes": {"by_sha256": {"f" * 64: "s"}}}
self.assertEqual(
auto_fetch.step1_crossref_db({"sha256": "F" * 64}, db), "bios/x/dsi.bin"
acquire_fetch.step1_crossref_db({"sha256": "F" * 64}, db), "bios/x/dsi.bin"
)
def test_an_entry_without_a_hash_is_not_searched(self):
from unittest import mock
from scripts import auto_fetch
from scripts.acquire import fetch as acquire_fetch
entry = {"name": "DICROM.ROM", "system": "fujitsu-fm7"}
out = io.StringIO()
with mock.patch.object(auto_fetch, "step2_scan_branches") as branches, \
with mock.patch.object(acquire_fetch, "step2_scan_branches") as branches, \
contextlib.redirect_stdout(out):
result = auto_fetch.fetch_missing([entry], {"files": {}}, "bios", dry_run=True)
result = acquire_fetch.fetch_missing([entry], {"files": {}}, "bios", dry_run=True)
branches.assert_not_called()
self.assertEqual(result["stats"]["unverifiable"], 1)
self.assertNotIn("Would search", out.getvalue())
@@ -7848,9 +7848,9 @@ class AutoFetchIssueBodyReadsAsWritten(unittest.TestCase):
"md5": "490f666e1afb15b7362b406ed1cea246"}
def test_full_hashes_and_no_template_phrasing(self):
from scripts import auto_fetch
from scripts.acquire import fetch as acquire_fetch
body = auto_fetch.generate_issue_body([self.ENTRY], "RetroArch")
body = acquire_fetch.generate_issue_body([self.ENTRY], "RetroArch")
self.assertIn(f"`{self.ENTRY['sha1']}`", body)
self.assertIn(f"`{self.ENTRY['md5']}`", body)
self.assertNotIn("...", body)
+13 -12
View File
@@ -16,6 +16,7 @@ from pathlib import Path
from unittest import mock
import auto_fetch
from acquire import fetch
PAYLOAD = b"keyboard mcu"
SHA1 = hashlib.sha1(PAYLOAD).hexdigest()
@@ -46,24 +47,24 @@ def _serving(payloads: dict[str, bytes]):
class SoftwareHeritageAnswersByContent(unittest.TestCase):
def test_the_bytes_it_serves_are_kept_when_the_hash_holds(self):
urlopen, asked = _serving({f"{auto_fetch.SOFTWARE_HERITAGE}/sha1:{SHA1}/raw/": PAYLOAD})
urlopen, asked = _serving({f"{fetch.SOFTWARE_HERITAGE}/sha1:{SHA1}/raw/": PAYLOAD})
with mock.patch.object(auto_fetch.urllib.request, "urlopen", urlopen):
data = auto_fetch.step3b_software_heritage({"name": "D8039HLC.rom", "sha1": SHA1})
data = fetch.step3b_software_heritage({"name": "D8039HLC.rom", "sha1": SHA1})
self.assertEqual(data, PAYLOAD)
self.assertEqual(asked, [f"{auto_fetch.SOFTWARE_HERITAGE}/sha1:{SHA1}/raw/"])
self.assertEqual(asked, [f"{fetch.SOFTWARE_HERITAGE}/sha1:{SHA1}/raw/"])
def test_other_bytes_under_the_hash_are_refused(self):
urlopen, _asked = _serving({auto_fetch.SOFTWARE_HERITAGE: b"something else"})
urlopen, _asked = _serving({fetch.SOFTWARE_HERITAGE: b"something else"})
with mock.patch.object(auto_fetch.urllib.request, "urlopen", urlopen):
data = auto_fetch.step3b_software_heritage({"name": "x", "sha1": SHA1})
data = fetch.step3b_software_heritage({"name": "x", "sha1": SHA1})
self.assertIsNone(data)
def test_an_absent_file_is_not_counted_as_a_source_that_did_not_answer(self):
urlopen, _asked = _serving({})
auto_fetch._UNANSWERED.clear()
fetch._UNANSWERED.clear()
with mock.patch.object(auto_fetch.urllib.request, "urlopen", urlopen):
self.assertIsNone(auto_fetch.step3b_software_heritage({"name": "x", "sha1": SHA1}))
self.assertEqual(auto_fetch._UNANSWERED, [])
self.assertIsNone(fetch.step3b_software_heritage({"name": "x", "sha1": SHA1}))
self.assertEqual(fetch._UNANSWERED, [])
class LookupBySha1(unittest.TestCase):
@@ -74,10 +75,10 @@ class LookupBySha1(unittest.TestCase):
self.addCleanup(os.chdir, self.cwd)
def test_a_found_file_goes_to_tmp_acquire_never_to_bios(self):
urlopen, _asked = _serving({f"{auto_fetch.SOFTWARE_HERITAGE}/sha1:{SHA1}/raw/": PAYLOAD})
urlopen, _asked = _serving({f"{fetch.SOFTWARE_HERITAGE}/sha1:{SHA1}/raw/": PAYLOAD})
with mock.patch.object(auto_fetch.urllib.request, "urlopen", urlopen), \
contextlib.redirect_stdout(io.StringIO()) as out:
code = auto_fetch.lookup_sha1s([SHA1.upper()], {"files": {}})
code = fetch.lookup_sha1s([SHA1.upper()], {"files": {}})
self.assertEqual(code, 0)
self.assertEqual((self.root / "tmp" / "acquire" / SHA1).read_bytes(), PAYLOAD)
self.assertFalse((self.root / "bios").exists())
@@ -88,7 +89,7 @@ class LookupBySha1(unittest.TestCase):
db = {"files": {SHA1: {"path": "bios/Commodore/Amiga/x.rom"}}}
with mock.patch.object(auto_fetch.urllib.request, "urlopen", urlopen), \
contextlib.redirect_stdout(io.StringIO()) as out:
code = auto_fetch.lookup_sha1s([SHA1], db)
code = fetch.lookup_sha1s([SHA1], db)
self.assertEqual((code, asked), (0, []))
self.assertIn("already held at bios/Commodore/Amiga/x.rom", out.getvalue())
@@ -97,7 +98,7 @@ class LookupBySha1(unittest.TestCase):
with mock.patch.object(auto_fetch.urllib.request, "urlopen", urlopen), \
contextlib.redirect_stdout(io.StringIO()) as out, \
contextlib.redirect_stderr(io.StringIO()) as err:
code = auto_fetch.lookup_sha1s([SHA1, "not-a-hash"], {"files": {}})
code = fetch.lookup_sha1s([SHA1, "not-a-hash"], {"files": {}})
self.assertEqual(code, 1)
self.assertIn(f"{SHA1}: not found", out.getvalue())
self.assertIn("not-a-hash: not a sha1", err.getvalue())
+2 -2
View File
@@ -18,7 +18,7 @@ import unittest.mock
import zlib
from pathlib import Path
import derivations
from acquire import derivations
REPO_ROOT = Path(__file__).resolve().parent.parent
@@ -153,7 +153,7 @@ class CombineMatchesZlib(unittest.TestCase):
import os
import zlib
from derivations import crc32_combine
from acquire.derivations import crc32_combine
for size in (1, 2, 3, 7, 100, 4096, 65537, 1000003):
with self.subTest(size=size):
+3 -3
View File
@@ -650,15 +650,15 @@ class ArchiveRecipesAreCountedFromTheRecipes(unittest.TestCase):
that file, never typed."""
def setUp(self) -> None:
import archive_build
from recipes import ledger
records = archive_build.load_ledger().values()
records = ledger.load_ledger().values()
self.counts = {
"total": len(records),
"exact": sum(r["rebuild"] == "exact" for r in records),
"canonical": sum(r["rebuild"] == "canonical" for r in records),
}
self.assertEqual(archive_build.rebuild_counts(), self.counts)
self.assertEqual(ledger.rebuild_counts(), self.counts)
self.assertEqual(self.counts["exact"] + self.counts["canonical"], self.counts["total"])
def test_the_readme_line(self) -> None:
+4 -3
View File
@@ -19,6 +19,7 @@ from pathlib import Path
from unittest import mock
import find_embedded
from acquire import embedded
ROM = bytes(random.Random(8039).randrange(256) for _ in range(2048))
CRC = zlib.crc32(ROM)
@@ -29,11 +30,11 @@ class RollingWindow(unittest.TestCase):
def test_every_offset_matches_a_direct_crc(self):
noise = random.Random(1).randbytes(5000)
data = noise[:777] + ROM + noise[777:3000] + ROM + noise[3000:]
self.assertEqual(find_embedded.offsets(data, CRC, len(ROM)), [777, 777 + 2048 + 2223])
self.assertEqual(embedded.offsets(data, CRC, len(ROM)), [777, 777 + 2048 + 2223])
def test_the_file_itself_and_a_short_file(self):
self.assertEqual(find_embedded.offsets(ROM, CRC, len(ROM)), [0])
self.assertEqual(find_embedded.offsets(ROM[:100], CRC, len(ROM)), [])
self.assertEqual(embedded.offsets(ROM, CRC, len(ROM)), [0])
self.assertEqual(embedded.offsets(ROM[:100], CRC, len(ROM)), [])
class Command(unittest.TestCase):
+3 -3
View File
@@ -12,7 +12,7 @@ import hashlib
import unittest
from unittest import mock
import find_pinned_revision
from acquire import history
from core import upstream
@@ -28,10 +28,10 @@ class ThePinnedRevisionIsInTheHistory(unittest.TestCase):
return next(data for sha, data in blobs.items() if f"/{sha}/" in url)
with mock.patch.object(upstream, "_api", api), mock.patch.object(upstream, "_fetch", fetch):
found = find_pinned_revision.find_revision(
found = history.find_revision(
repo, "dists/engine-data/queen.tbl",
hashlib.md5(b"pinned").hexdigest(), "unused")
missing = find_pinned_revision.find_revision(
missing = history.find_revision(
repo, "dists/engine-data/queen.tbl", "0" * 32, "unused")
self.assertEqual(found, ("c2", b"pinned"))
self.assertIsNone(missing)
+20 -20
View File
@@ -17,7 +17,7 @@ from scripts.model.dumpcatalog import (
write_provenance_snapshot,
)
from scripts.sitegen.provenance import generate_provenance_page
from scripts.provenance_report import build_report
from scripts.acquire.provenance import build_report
from scripts.scraper.dat_pack_importer import _bios_entries, import_pack
from scripts.scraper.logiqx_parser import parse_logiqx, validate_logiqx_format
from scripts.scraper.redump_dat_scraper import discover_bios_datfiles, parse_redump_dat
@@ -430,7 +430,7 @@ class HeldUnderAnAlias(unittest.TestCase):
}
def _needs(self, **fields):
from scripts.provenance_report import profile_needs
from scripts.acquire.provenance import profile_needs
entry = {"name": "KANJI2.ROM", "size": 131072, **fields}
return profile_needs({"emu": {"files": [entry]}}, self.DB)["by_name"]
@@ -555,7 +555,7 @@ class ArchiveMembersAreHeld(unittest.TestCase):
import hashlib
import zlib
from scripts.provenance_report import archive_members
from scripts.acquire.provenance import archive_members
data = b"bally" * 400
with tempfile.TemporaryDirectory() as tmp:
@@ -582,7 +582,7 @@ class OneDumpIsCountedOnce(unittest.TestCase):
the site's Wanted page published the larger number."""
def test_a_dump_in_several_dats_is_one_missing_entry(self):
from scripts import provenance_report
from scripts.acquire import provenance as acquire_provenance
rom = {"name": "DICROM.rom", "sha1": "a" * 40, "size": 32768}
held = {"name": "held.rom", "sha1": "b" * 40, "size": 16}
@@ -591,13 +591,13 @@ class OneDumpIsCountedOnce(unittest.TestCase):
{**rom, "dat": "FM-7 (Flux)"}, {**held, "dat": "FM-7 (Flux)"},
]}}
db = {"files": {"b" * 40: {"md5": "", "size": 16}}}
report = provenance_report.build_report(db, snapshots, {})
report = acquire_provenance.build_report(db, snapshots, {})
(entry,) = report["no-intro"]["missing"]
self.assertEqual(entry["dats"], ["FM-7 (Bitstream)", "FM-7 (Flux)"])
self.assertEqual(report["no-intro"]["matched"], 1)
self.assertEqual(provenance_report.distinct_missing(report), 1)
self.assertEqual(acquire_provenance.distinct_missing(report), 1)
twice = {"redump": report["no-intro"], "no-intro": report["no-intro"]}
self.assertEqual(provenance_report.distinct_missing(twice), 1)
self.assertEqual(acquire_provenance.distinct_missing(twice), 1)
class AMissingDumpNamesTheProfileItFills(unittest.TestCase):
@@ -613,7 +613,7 @@ class AMissingDumpNamesTheProfileItFills(unittest.TestCase):
}
def _report(self, db):
from scripts import provenance_report
from scripts.acquire import provenance as acquire_provenance
snapshots = {"no-intro": {"entries": [
{"dat": "FM-7", "name": "DICROM.rom", "sha1": "a" * 40, "size": 262144},
@@ -621,8 +621,8 @@ class AMissingDumpNamesTheProfileItFills(unittest.TestCase):
{"dat": "FM-7", "name": "Other Name.rom", "sha1": "c" * 40, "size": 8},
{"dat": "FM-7", "name": "unread.rom", "sha1": "d" * 40, "size": 8},
]}}
needs = provenance_report.profile_needs(self.PROFILES, db)
return provenance_report.build_report(db, snapshots, {}, {}, needs)
needs = acquire_provenance.profile_needs(self.PROFILES, db)
return acquire_provenance.build_report(db, snapshots, {}, {}, needs)
def test_a_dump_a_profile_reads_names_it(self):
db = {"files": {"b" * 40: {"name": "held.rom", "md5": "", "size": 16}}}
@@ -635,23 +635,23 @@ class AMissingDumpNamesTheProfileItFills(unittest.TestCase):
self.assertIsNone(missing["unread.rom"])
def test_a_size_outside_the_profile_range_fills_nothing(self):
from scripts import provenance_report
from scripts.acquire import provenance as acquire_provenance
needs = provenance_report.profile_needs(self.PROFILES, {"files": {}})
needs = acquire_provenance.profile_needs(self.PROFILES, {"files": {}})
small = {"name": "DICROM.rom", "size": 1024}
self.assertEqual(provenance_report.needs_filled(small, needs), [])
self.assertEqual(acquire_provenance.needs_filled(small, needs), [])
def test_a_need_the_collection_answers_is_not_one(self):
from scripts import provenance_report
from scripts.acquire import provenance as acquire_provenance
db = {"files": {"e" * 40: {"name": "dicrom.rom", "size": 262144}}}
needs = provenance_report.profile_needs(self.PROFILES, db)
needs = acquire_provenance.profile_needs(self.PROFILES, db)
self.assertNotIn("dicrom.rom", needs["by_name"])
def test_a_file_installed_with_the_emulator_is_not_a_need(self):
"""43 of 50 needs were bundled entries (samcoupe.rom, zesarux's
tk90x.rom), burying the six xm7 ROMs a maintainer has to find."""
from scripts import provenance_report
from scripts.acquire import provenance as acquire_provenance
profiles = {
"samcoupe": {"files": [{"name": "samcoupe.rom", "required": True,
@@ -659,7 +659,7 @@ class AMissingDumpNamesTheProfileItFills(unittest.TestCase):
"hcl": {"files": [{"name": "kanji.rom", "required": True, "bundled": True,
"not_bundled_on": ["batocera"], "sha1": "9" * 40}]},
}
needs = provenance_report.profile_needs(profiles, {"files": {}})
needs = acquire_provenance.profile_needs(profiles, {"files": {}})
self.assertNotIn(("sha1", "f" * 40), needs["by_hash"])
self.assertIn(("sha1", "9" * 40), needs["by_hash"])
@@ -695,7 +695,7 @@ class MissingDumpsNameTheirRomsets(unittest.TestCase):
spectrum.zip: the report said MISSING and nothing about where to look."""
def _index(self, entries: list[dict]) -> dict:
from scripts.provenance_report import romset_index
from scripts.acquire.provenance import romset_index
with tempfile.TemporaryDirectory() as tmp:
Path(tmp, "mame.json").write_text(
@@ -704,7 +704,7 @@ class MissingDumpsNameTheirRomsets(unittest.TestCase):
return romset_index(Path(tmp))
def test_versions_of_one_set_merge(self):
from scripts.provenance_report import romsets_holding
from scripts.acquire.provenance import romsets_holding
member = {"name": "1986es.rom", "size": 16384, "crc32": "aaaa0001", "sha1": "f9"}
index = self._index([
@@ -718,7 +718,7 @@ class MissingDumpsNameTheirRomsets(unittest.TestCase):
self.assertEqual(hits[0]["dats"], ["MAME mame0190", "MAME mame0220", "MAME mame0289"])
def test_a_disagreeing_sha1_is_not_the_dump(self):
from scripts.provenance_report import romsets_holding
from scripts.acquire.provenance import romsets_holding
member = {"name": "a.rom", "size": 8, "crc32": "00000001", "sha1": "aa"}
index = self._index([{"name": "set.zip", "members": [member], "dats": ["MAME mame0190"]}])
+5 -7
View File
@@ -13,13 +13,11 @@ import zipfile
import zlib
from pathlib import Path
from romset_recipes import (
AtomPool,
collect_recipes,
from recipes.pool import AtomPool
from recipes.romsets import collect_recipes, load_dat_recipes, merge_recipes
from recipes.identify import (
identify_archive,
identify_report,
load_dat_recipes,
merge_recipes,
missing_report,
reconstruct,
write_reconstructions,
@@ -717,7 +715,7 @@ class IdentificationReadsTheDirectoryFirst(unittest.TestCase):
def test_a_recipe_with_other_members_is_never_built(self):
from core.torrentzip import build_torrentzip
import romset_recipes
from recipes import identify
rom = b"rom bytes"
crc = format(zlib.crc32(rom), "08x")
@@ -739,7 +737,7 @@ class IdentificationReadsTheDirectoryFirst(unittest.TestCase):
return hashlib.md5(blob).hexdigest(), len(blob)
pool = Pool()
label = romset_recipes.identify_archive(
label = identify.identify_archive(
archive, {"other": [("b.rom", crc)], "match": [("a.rom", crc)]}, pool)
self.assertEqual(label, "match")
self.assertEqual(pool.built, [[("a.rom", crc)]])