refactor: split core.upstream by subject

HTTP to the forges moves to core.forgehttp, comparisons, trees and
clone history to core.upstreamtree. core.upstream keeps repositories,
the cache and revisions.
This commit is contained in:
Abdessamad Derraz committed 2026-11-24 06:20:52 +01:00
1 parent ce92eff0aa
commit 263a64c0e0
65 files changed
+1417 -1337

No files matched your search

+8 -8
View File
@@ -3543,7 +3543,7 @@ class ContributorsSurviveAFailedRequest(unittest.TestCase):
from sitegen import readme
with mock.patch.dict(os.environ, {"RETROBIOS_OFFLINE": "1"}), \
mock.patch.object(readme.upstream, "fetch_body",
mock.patch.object(readme.forgehttp, "fetch_body",
side_effect=AssertionError("network")):
self.assertEqual(readme.fetch_contributors(), [])
@@ -3556,7 +3556,7 @@ class ContributorsSurviveAFailedRequest(unittest.TestCase):
{"login": readme.REPO.split("/")[0], "type": "User"},
]).encode()
with mock.patch.dict(os.environ, {"RETROBIOS_OFFLINE": ""}), \
mock.patch.object(readme.upstream, "fetch_body", return_value=answer) as fetch:
mock.patch.object(readme.forgehttp, "fetch_body", return_value=answer) as fetch:
self.assertEqual([c["login"] for c in readme.fetch_contributors()], ["someone"])
self.assertIn("/contributors", fetch.call_args.args[0])
@@ -4502,7 +4502,7 @@ class TriageSurvivesAForgeRefusal(unittest.TestCase):
def check_version(named, *_args):
if "eden" in named.repo.slug:
raise triage.upstream.UpstreamError("HTTP 403")
raise triage.forgehttp.UpstreamError("HTTP 403")
return
args = SimpleNamespace(cache_dir="", offline=True)
@@ -7015,7 +7015,7 @@ 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(acquire_fetch.upstream, "_sleep", lambda _s: None), \
mock.patch.object(acquire_fetch.forgehttp, "_sleep", lambda _s: None), \
mock.patch.object(acquire_fetch, "step2_scan_branches", lambda e: None):
return acquire_fetch.fetch_missing([entry], db, "bios")
@@ -7857,7 +7857,7 @@ class ExternalDownloadsFollowTheRunPolicy(unittest.TestCase):
def test_each_failure_names_its_own_cause(self):
"""Four causes came back as one False, reported as a download failure."""
from core import upstream
from core import forgehttp
from resolve import packfiles as packresolve
outcome = packresolve.ExternalOutcome
@@ -7868,7 +7868,7 @@ class ExternalDownloadsFollowTheRunPolicy(unittest.TestCase):
offline = packresolve.download_external(self.ENTRY, f"{tmp}/x", offline=True)
with mock.patch("urllib.request.urlopen",
side_effect=urllib.error.URLError("refused")), \
mock.patch.object(upstream, "_sleep", lambda _s: None):
mock.patch.object(forgehttp, "_sleep", lambda _s: None):
failed = packresolve.download_external(self.ENTRY, f"{tmp}/x", offline=False)
self.assertIs(no_hash.outcome, outcome.NO_HASH)
self.assertIs(offline.outcome, outcome.OFFLINE)
@@ -7934,7 +7934,7 @@ class ExternalDownloadsFollowTheRunPolicy(unittest.TestCase):
def test_a_transient_failure_is_retried_and_no_scratch_remains(self):
"""One 503 failed the external file for the whole build."""
from core import upstream
from core import forgehttp
from resolve import packfiles as packresolve
refusal = urllib.error.HTTPError(self.ENTRY["source_url"], 503, "busy", {}, None)
@@ -7942,7 +7942,7 @@ class ExternalDownloadsFollowTheRunPolicy(unittest.TestCase):
target = Path(tmp) / "x"
with mock.patch("urllib.request.urlopen",
side_effect=[refusal, self._response(b"payload")]), \
mock.patch.object(upstream, "_sleep", lambda _s: None):
mock.patch.object(forgehttp, "_sleep", lambda _s: None):
self.assertTrue(
packresolve.download_external(self.ENTRY, str(target), offline=False).fetched)
self.assertEqual(target.read_bytes(), b"payload")
+16 -16
View File
@@ -48,20 +48,20 @@ 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"{fetch.SOFTWARE_HERITAGE}/sha1:{SHA1}/raw/": PAYLOAD})
with mock.patch.object(fetch.upstream.urllib.request, "urlopen", urlopen):
with mock.patch.object(fetch.forgehttp.urllib.request, "urlopen", urlopen):
data = fetch.step3b_software_heritage({"name": "D8039HLC.rom", "sha1": SHA1}, [])
self.assertEqual(data, PAYLOAD)
self.assertEqual(asked, [f"{fetch.SOFTWARE_HERITAGE}/sha1:{SHA1}/raw/"])
def test_other_bytes_under_the_hash_are_refused(self):
urlopen, _asked = _serving({fetch.SOFTWARE_HERITAGE: b"something else"})
with mock.patch.object(fetch.upstream.urllib.request, "urlopen", urlopen):
with mock.patch.object(fetch.forgehttp.urllib.request, "urlopen", urlopen):
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({})
with mock.patch.object(fetch.upstream.urllib.request, "urlopen", urlopen):
with mock.patch.object(fetch.forgehttp.urllib.request, "urlopen", urlopen):
found = fetch.search({"name": "x", "sha1": SHA1}, fetch.SHA1_SOURCES)
self.assertEqual(found, fetch.SearchResult(None, None, ()))
@@ -76,7 +76,7 @@ class LookupBySha1(unittest.TestCase):
def test_a_found_file_goes_to_tmp_acquire_never_to_bios(self):
urlopen, _asked = _serving({f"{fetch.SOFTWARE_HERITAGE}/sha1:{SHA1}/raw/": PAYLOAD})
with mock.patch.object(fetch.upstream.urllib.request, "urlopen", urlopen):
with mock.patch.object(fetch.forgehttp.urllib.request, "urlopen", urlopen):
[record] = fetch.lookup_sha1s([SHA1.upper()], {"files": {}},
acquire_dir=self.acquire)
self.assertEqual((record.outcome, record.source), ("found", "software_heritage"))
@@ -92,7 +92,7 @@ class LookupBySha1(unittest.TestCase):
def test_a_held_file_is_named_and_not_fetched(self):
urlopen, asked = _serving({})
db = {"files": {SHA1: {"path": "bios/Commodore/Amiga/x.rom"}}}
with mock.patch.object(fetch.upstream.urllib.request, "urlopen", urlopen), \
with mock.patch.object(fetch.forgehttp.urllib.request, "urlopen", urlopen), \
contextlib.redirect_stdout(io.StringIO()) as out:
code = fetchtext.report_lookups([SHA1], db, acquire_dir=self.acquire)
self.assertEqual((code, asked), (0, []))
@@ -100,7 +100,7 @@ class LookupBySha1(unittest.TestCase):
def test_nothing_found_and_a_malformed_hash_end_with_one(self):
urlopen, _asked = _serving({})
with mock.patch.object(fetch.upstream.urllib.request, "urlopen", urlopen), \
with mock.patch.object(fetch.forgehttp.urllib.request, "urlopen", urlopen), \
contextlib.redirect_stdout(io.StringIO()) as out, \
contextlib.redirect_stderr(io.StringIO()) as err:
code = fetchtext.report_lookups([SHA1, "not-a-hash"], {"files": {}},
@@ -139,13 +139,13 @@ class AStalledOrLimitedSourceIsNoAnswer(unittest.TestCase):
A 429 from Software Heritage was recorded unanswered at once."""
def setUp(self):
from core import upstream
from core import forgehttp
patcher = mock.patch.object(upstream, "_sleep", lambda _s: None)
patcher = mock.patch.object(forgehttp, "_sleep", lambda _s: None)
patcher.start()
self.addCleanup(patcher.stop)
upstream._exhausted_hosts.clear()
self.addCleanup(upstream._exhausted_hosts.clear)
forgehttp._exhausted_hosts.clear()
self.addCleanup(forgehttp._exhausted_hosts.clear)
def test_a_stalled_read_is_recorded_and_the_search_goes_on(self):
class _Stalled(_Answer):
@@ -156,7 +156,7 @@ class AStalledOrLimitedSourceIsNoAnswer(unittest.TestCase):
return _Stalled()
unanswered: list[str] = []
with mock.patch.object(fetch.upstream.urllib.request, "urlopen", urlopen):
with mock.patch.object(fetch.forgehttp.urllib.request, "urlopen", urlopen):
self.assertIsNone(fetch.step3_search_public_repos(
{"name": "x.bin", "sha1": SHA1}, unanswered))
self.assertEqual(len(unanswered), len(fetch.PUBLIC_REPOS))
@@ -170,7 +170,7 @@ class AStalledOrLimitedSourceIsNoAnswer(unittest.TestCase):
raise answer
return _Answer(answer)
with mock.patch.object(fetch.upstream.urllib.request, "urlopen", urlopen):
with mock.patch.object(fetch.forgehttp.urllib.request, "urlopen", urlopen):
found = fetch.search({"name": "x", "sha1": SHA1}, fetch.SHA1_SOURCES)
self.assertEqual(found, fetch.SearchResult(PAYLOAD, "software_heritage", ()))
@@ -184,7 +184,7 @@ class AStalledOrLimitedSourceIsNoAnswer(unittest.TestCase):
return _Answer(b"0" * 64)
with mock.patch.object(fetch, "MAX_DOWNLOAD", 32), \
mock.patch.object(fetch.upstream.urllib.request, "urlopen", urlopen):
mock.patch.object(fetch.forgehttp.urllib.request, "urlopen", urlopen):
data = fetch.step3_search_public_repos(
{"name": "x.bin", "destination": "sub/x.bin", "sha1": SHA1}, [])
self.assertEqual(data, PAYLOAD)
@@ -212,7 +212,7 @@ class ArchiveOrgAnswersByHash(unittest.TestCase):
def test_the_member_is_found_by_its_sha1_whatever_its_name(self):
urlopen, asked = self._archive()
with mock.patch.object(fetch.upstream.urllib.request, "urlopen", urlopen):
with mock.patch.object(fetch.forgehttp.urllib.request, "urlopen", urlopen):
data = fetch.step4_search_archive_org(
{"name": "scph1001.bin", "sha1": SHA1.upper()}, [])
self.assertEqual(data, PAYLOAD)
@@ -220,7 +220,7 @@ class ArchiveOrgAnswersByHash(unittest.TestCase):
def test_the_platform_search_and_the_sha1_search_agree(self):
urlopen, _asked = self._archive()
with mock.patch.object(fetch.upstream.urllib.request, "urlopen", urlopen):
with mock.patch.object(fetch.forgehttp.urllib.request, "urlopen", urlopen):
by_platform = fetch.step4_search_archive_org(
{"name": "scph1001.bin", "sha1": SHA1}, [])
by_sha1 = fetch.archive_org_by_sha1(SHA1, [])
@@ -228,7 +228,7 @@ class ArchiveOrgAnswersByHash(unittest.TestCase):
def test_a_declared_md5_still_has_to_hold(self):
urlopen, _asked = self._archive()
with mock.patch.object(fetch.upstream.urllib.request, "urlopen", urlopen):
with mock.patch.object(fetch.forgehttp.urllib.request, "urlopen", urlopen):
data = fetch.step4_search_archive_org(
{"name": "scph1001.bin", "sha1": SHA1, "md5": "f" * 32}, [])
self.assertIsNone(data)
+4 -2
View File
@@ -20,6 +20,8 @@ from unittest import mock
from pathlib import Path
from core import upstream
from core import forgehttp
from core import upstreamtree
from core.cli import InputMissing
from exporter.native import ExportResult
from exporter.originals import SOURCES_INDEX
@@ -468,7 +470,7 @@ class SiteNpmPins(unittest.TestCase):
name = url.split("registry.npmjs.org/", 1)[1].rsplit("/latest", 1)[0]
return {"version": latest[name]}
with mock.patch("freshness.ci.SITE_PACKAGE", package), \
mock.patch.object(upstream, "http_json", side_effect=answer):
mock.patch.object(forgehttp, "http_json", side_effect=answer):
rows = {f.subject: f for f in _npm_findings()}
self.assertEqual(rows["npm:astro"].status, STALE)
self.assertEqual(rows["npm:astro"].remote, "7.4.7")
@@ -546,7 +548,7 @@ class RomFolderPins(unittest.TestCase):
with mock.patch.object(upstream, "commit_date", return_value="2026-10-01T00:00:00"), \
mock.patch.object(upstream, "latest_release", return_value=None), \
mock.patch.object(upstream, "resolve_head", side_effect=lambda repo, _c: heads.get(repo.slug)), \
mock.patch.object(upstream, "ancestry", return_value=(5, 0)):
mock.patch.object(upstreamtree, "ancestry", return_value=(5, 0)):
rows = {f.subject: f for f in check_romfolders(root, "", False)}
self.assertEqual(rows["card"].status, OK)
self.assertEqual((rows["card:dist"].status, rows["card:dist"].detail),
+2 -1
View File
@@ -14,6 +14,7 @@ import unittest
from pathlib import Path
from core import upstream
from core import forgehttp
from model.safeparse import yaml_load
ROOT = Path(__file__).resolve().parents[1]
@@ -47,7 +48,7 @@ class CitedLinesHoldTheirCode(unittest.TestCase):
lines = upstream.fetch_file(
repo, str(document["source_commit"]), path, str(CACHE), True
)
except upstream.NotCachedError:
except forgehttp.NotCachedError:
self.skipTest(f"{path} is not in the upstream cache")
self.assertIsNotNone(lines)
self.assertIn(text, lines[line - 1])
+4 -4
View File
@@ -886,7 +886,7 @@ class AProgressBarOnlyOnATerminal(unittest.TestCase):
"""One reset midway through a 2 GiB part failed the whole download."""
import http.client
from core import upstream
from core import forgehttp
class Body(io.BytesIO):
headers = {"Content-Length": "6"}
@@ -905,7 +905,7 @@ class AProgressBarOnlyOnATerminal(unittest.TestCase):
with tempfile.TemporaryDirectory() as directory, \
mock.patch.object(transfer.urllib.request, "urlopen",
lambda *a, **k: answers.pop(0)), \
mock.patch.object(upstream, "_sleep", lambda _s: None), \
mock.patch.object(forgehttp, "_sleep", lambda _s: None), \
contextlib.redirect_stdout(io.StringIO()):
target = Path(directory) / "a.zip"
transfer.download_file("https://example.com/a.zip", target, 6)
@@ -942,14 +942,14 @@ class ATransferFailureIsADownloadError(unittest.TestCase):
)
def test_a_transport_failure_raises(self):
from core import upstream
from core import forgehttp
def refuse(*_a, **_k):
raise ConnectionResetError("reset by peer")
with tempfile.TemporaryDirectory() as directory, \
mock.patch.object(transfer.urllib.request, "urlopen", refuse), \
mock.patch.object(upstream, "_sleep", lambda _s: None), \
mock.patch.object(forgehttp, "_sleep", lambda _s: None), \
self.assertRaises(DownloadError) as raised:
transfer.download_file("https://example.com/a.zip", Path(directory) / "a.zip", 20)
self.assertEqual(
+4 -3
View File
@@ -17,6 +17,7 @@ from pathlib import Path
from unittest import mock
import fileless_audit
from core import forgehttp
from profiling import fileless
ROOT = Path(__file__).resolve().parent.parent
@@ -147,7 +148,7 @@ class TestCommandLine(unittest.TestCase):
def test_an_unreachable_source_fails_the_run(self):
def unreachable(name):
raise fileless.upstream.UpstreamError("HTTP 403")
raise forgehttp.UpstreamError("HTTP 403")
code, _ = self._main("open", audit=unreachable)
self.assertEqual(code, 1)
@@ -173,7 +174,7 @@ class TestCorpusIsAnswered(unittest.TestCase):
# A cold path is unread here, not absent.
try:
lines = fetch(*args, **kwargs)
except fileless.upstream.NotCachedError:
except forgehttp.NotCachedError:
return None
if lines is not None:
read.append(args[2])
@@ -190,7 +191,7 @@ class TestCorpusIsAnswered(unittest.TestCase):
hits = fileless.audit(
path.stem, str(ROOT / "emulators"), str(cache), True
)
except fileless.upstream.NotCachedError:
except forgehttp.NotCachedError:
# A cold branch tip is unread too, not a branch gone.
continue
if hits:
+2 -1
View File
@@ -14,6 +14,7 @@ from unittest import mock
from acquire import history
from core import upstream
from core import forgehttp
class ThePinnedRevisionIsInTheHistory(unittest.TestCase):
@@ -27,7 +28,7 @@ class ThePinnedRevisionIsInTheHistory(unittest.TestCase):
def fetch(url, *_a, **_k):
return next(data for sha, data in blobs.items() if f"/{sha}/" in url)
with mock.patch.object(upstream, "cached_api", api), mock.patch.object(upstream, "fetch_body", fetch):
with mock.patch.object(upstream, "cached_api", api), mock.patch.object(forgehttp, "fetch_body", fetch):
found = history.find_revision(
repo, "dists/engine-data/queen.tbl",
hashlib.md5(b"pinned").hexdigest(), "unused")
+6 -6
View File
@@ -40,7 +40,7 @@ PAYLOAD_B = b"B" * (256 * 1024)
_ONLINE = mock.patch.dict(os.environ, {"RETROBIOS_OFFLINE": ""})
# core.upstream retries a failed transfer after a pause: the pauses are
# skipped, the retries are not.
_NO_PAUSE = mock.patch.object(largefiles.upstream, "_sleep", lambda _s: None)
_NO_PAUSE = mock.patch.object(largefiles.forgehttp, "_sleep", lambda _s: None)
# The names these tests fetch, registered as .gitignore registers an asset:
# a bare name no registered path carries is never asked of the release.
@@ -343,8 +343,8 @@ class TheOfflineSwitchHoldsEverywhere(unittest.TestCase):
under RETROBIOS_OFFLINE it listed the release and HEADed the asset."""
with tempfile.TemporaryDirectory() as tmp, mock.patch.dict(
os.environ, {"RETROBIOS_OFFLINE": "1"}
), mock.patch.object(largefiles.upstream, "fetch_body") as fetch_body, \
mock.patch.object(largefiles.upstream, "open_retrying") as head:
), mock.patch.object(largefiles.forgehttp, "fetch_body") as fetch_body, \
mock.patch.object(largefiles.forgehttp, "open_retrying") as head:
Path(tmp, "asset.bin").write_bytes(PAYLOAD_A)
self.assertIsNone(largefiles.fetch_large_file(
"asset.bin", dest_dir=tmp,
@@ -960,10 +960,10 @@ class AFailedReleaseListingIsAskedAgain(unittest.TestCase):
run, and every asset fell back to its Content-Length."""
def test_the_listing_is_read_again_after_a_failure(self):
from core import upstream
from core import forgehttp
release = {"assets": [{"name": "a.zip", "digest": "sha256:ABC"}]}
answers = [upstream.UpstreamError("reset"), json.dumps(release).encode()]
answers = [forgehttp.UpstreamError("reset"), json.dumps(release).encode()]
def fetch_body(*_args, **_kwargs):
answer = answers.pop(0)
@@ -972,7 +972,7 @@ class AFailedReleaseListingIsAskedAgain(unittest.TestCase):
return answer
with mock.patch.object(largefiles, "_digests_cache", None), \
mock.patch.object(upstream, "fetch_body", fetch_body):
mock.patch.object(forgehttp, "fetch_body", fetch_body):
self.assertEqual(largefiles._served_digests(), {})
self.assertEqual(largefiles._served_digests(), {"a.zip": "abc"})
+2 -1
View File
@@ -13,6 +13,7 @@ import tempfile
import unittest
from pathlib import Path
from core import forgehttp
from profiling import mamerefs
from profiling.mamerefs import declares
@@ -121,7 +122,7 @@ class TestCorpusStaysCorrect(unittest.TestCase):
findings, agreed, _ = mamerefs.audit(
name, str(ROOT / "emulators"), str(cache), True
)
except mamerefs.upstream.NotCachedError as exc:
except forgehttp.NotCachedError as exc:
# A cache that holds some drivers and not others is as
# cold as an empty one for this profile.
self.skipTest(f"{name}: {exc}")
+4 -2
View File
@@ -16,6 +16,8 @@ from pathlib import Path
from unittest import mock
from core import upstream
from core import forgehttp
from core import upstreamtree
from freshness.findings import OK, SKIPPED, STALE
from freshness.pinbuilds import build_variable, check_pin_builds, pin_build_revision
@@ -104,14 +106,14 @@ class HeldPinsReadTheirBuildFileAgain(unittest.TestCase):
profiles = {"amiberry": {"pin_frozen": "x", "pin_build": [ref]}}
with mock.patch.object(upstream, "fetch_file", side_effect=fetch), \
mock.patch.object(upstream, "list_gitlinks", return_value={"batocera": "c" * 40}):
mock.patch.object(upstreamtree, "list_gitlinks", return_value={"batocera": "c" * 40}):
(row,) = check_pin_builds(profiles, self.platforms, "cache", False)
self.assertEqual(row.status, OK, row.detail)
def test_offline_and_uncached_is_skipped(self):
self._platform("10.2")
profiles = {"mame0278": {"pin_frozen": "x", "pin_build": [self.REF]}}
cold = upstream.NotCachedError("not cached")
cold = forgehttp.NotCachedError("not cached")
with mock.patch.object(upstream, "fetch_file", side_effect=cold):
(row,) = check_pin_builds(profiles, self.platforms, "cache", True)
self.assertEqual(row.status, SKIPPED)
+84 -82
View File
@@ -76,8 +76,10 @@ from profiling.rebase import Recale, rebase_refs
from profiling.repos import select_repo
from model.sourceref import RefPart, parse_source_ref, split_source_ref
from core import upstream
from core import forgehttp
from core import upstreamtree
from profiling import versionbasis
from core.upstream import CompareResult, FileChange
from core.upstreamtree import CompareResult, FileChange
def _version_read_as_written(profile, cache_dir, offline, profiles=None, recompute=False):
@@ -325,7 +327,7 @@ class TestSourceMirror(unittest.TestCase):
"source_commit": "87b176a",
"upstream_commit": "07021f0",
}
with tempfile.TemporaryDirectory() as cache, self.assertRaises(upstream.NotCachedError):
with tempfile.TemporaryDirectory() as cache, self.assertRaises(forgehttp.NotCachedError):
profiling_repos.select_views(profile, cache, True)
def test_a_profile_without_a_mirror_is_unchanged(self):
@@ -1291,22 +1293,22 @@ class TestBuildReport(unittest.TestCase):
upstream.fetch_file,
upstream.resolve_head,
upstream.resolve_commit_at,
upstream.compare,
upstream.list_tree,
upstreamtree.compare,
upstreamtree.list_tree,
upstream.list_tags,
upstream.resolve_tag_commit,
upstream.tag_commit,
upstream.http_json,
upstream.http_text,
upstream.list_gitlinks,
forgehttp.http_json,
forgehttp.http_text,
upstreamtree.list_gitlinks,
upstream.current_slug,
upstream.fork_base,
upstream.ancestry,
upstreamtree.fork_base,
upstreamtree.ancestry,
)
# Pin and tip are unrelated shas in these fixtures: no ancestry.
upstream.ancestry = lambda *a, **k: None
upstreamtree.ancestry = lambda *a, **k: None
self.fork_bases: dict[str, str] = {}
upstream.fork_base = (
upstreamtree.fork_base = (
lambda repo, sha, fork, fork_sha, cache_dir, offline=False:
self.fork_bases.get(fork_sha)
)
@@ -1318,7 +1320,7 @@ class TestBuildReport(unittest.TestCase):
)
self.tags: list[str] = []
self.gitlinks: dict[str, dict[str, str]] = {}
upstream.list_gitlinks = (
upstreamtree.list_gitlinks = (
lambda repo, sha, cache_dir, offline=False: self.gitlinks.get(sha, {})
)
self.tag_commits: dict[str, str] = {}
@@ -1326,8 +1328,8 @@ class TestBuildReport(unittest.TestCase):
def _no_network(url):
raise AssertionError(f"test reached the network: {url}")
upstream.http_json = _no_network
upstream.http_text = _no_network
forgehttp.http_json = _no_network
forgehttp.http_text = _no_network
upstream.list_tags = (
lambda repo, cache, offline=False: self.tags
)
@@ -1337,7 +1339,7 @@ class TestBuildReport(unittest.TestCase):
upstream.tag_commit = (
lambda repo, tag, cache, offline=False: self.tag_commits.get(tag)
)
upstream.list_tree = (
upstreamtree.list_tree = (
lambda repo, sha, cache_dir, offline=False: (
sorted({path for _, path in self.files}), False
)
@@ -1353,7 +1355,7 @@ class TestBuildReport(unittest.TestCase):
upstream.resolve_commit_at = (
lambda repo, date, cache_dir, offline=False, branch=None: "pinsha"
)
upstream.compare = (
upstreamtree.compare = (
lambda repo, base, head, cache_dir, offline=False: CompareResult([], False)
)
@@ -1362,17 +1364,17 @@ class TestBuildReport(unittest.TestCase):
upstream.fetch_file,
upstream.resolve_head,
upstream.resolve_commit_at,
upstream.compare,
upstream.list_tree,
upstreamtree.compare,
upstreamtree.list_tree,
upstream.list_tags,
upstream.resolve_tag_commit,
upstream.tag_commit,
upstream.http_json,
upstream.http_text,
upstream.list_gitlinks,
forgehttp.http_json,
forgehttp.http_text,
upstreamtree.list_gitlinks,
upstream.current_slug,
upstream.fork_base,
upstream.ancestry,
upstreamtree.fork_base,
upstreamtree.ancestry,
) = self._orig
self.tmp.cleanup()
@@ -1410,7 +1412,7 @@ class TestBuildReport(unittest.TestCase):
"""git.eden-emu.dev answers 403 to scripts: the muted repository's
citations read "absent at HEAD" for files that exist."""
def refuse(repo, sha, path, cache_dir, offline=False):
raise upstream.UpstreamError(f"{path}: HTTP 403")
raise forgehttp.UpstreamError(f"{path}: HTTP 403")
upstream.fetch_file = refuse
with contextlib.redirect_stderr(io.StringIO()):
@@ -1423,7 +1425,7 @@ class TestBuildReport(unittest.TestCase):
"""git.eden-emu.dev truncates the HEAD tree: fs_paths.h, cited bare,
was reported GONE though it lives under src/common/fs/."""
self.files[("pinsha", "fs_paths.h")] = ["x", "hit"]
upstream.list_tree = (
upstreamtree.list_tree = (
lambda repo, sha, cache_dir, offline=False: (["other.c"], True)
)
with contextlib.redirect_stderr(io.StringIO()):
@@ -1789,7 +1791,7 @@ class TestBuildReport(unittest.TestCase):
upstream.resolve_head = (
lambda repo, cache, offline=False, branch=None: heads[repo.slug]
)
upstream.list_tree = (
upstreamtree.list_tree = (
lambda repo, sha, cache_dir, offline=False: (
sorted(path for revision, path in self.files if revision == sha), False
)
@@ -1836,7 +1838,7 @@ class TestBuildReport(unittest.TestCase):
# the forge's orphaned objects, and every ref read ANCHORED.
self.files[("pinsha", "a.c")] = ["x", "hit"]
self.files[("headsha", "a.c")] = ["x", "hit"]
upstream.compare = (
upstreamtree.compare = (
lambda repo, base, head, cache_dir, offline=False: CompareResult([], False, True)
)
report = build_report("test", self._profile(["a.c:2"]), self.dir)
@@ -1848,7 +1850,7 @@ class TestBuildReport(unittest.TestCase):
self.files[("pinsha", "a.c")] = ["x", "hit"]
self.files[("headsha", "a.c")] = ["x", "hit"]
self.tag_commits = {"v1.6.0": "pinsha"}
upstream.compare = (
upstreamtree.compare = (
lambda repo, base, head, cache_dir, offline=False: CompareResult([], False, True)
)
report = build_report("test", self._versioned("1.6.0"), self.dir)
@@ -1882,7 +1884,7 @@ class TestBuildReport(unittest.TestCase):
lambda repo, cache, offline=False, branch=None: heads[repo.slug]
)
# A tag off the tracked branch is not an orphaned pin.
upstream.compare = (
upstreamtree.compare = (
lambda repo, base, head, cache_dir, offline=False: CompareResult(
[], False, repo.slug == "o/up"
)
@@ -1986,7 +1988,7 @@ class TestDeclaredDeadUpstream(TestBuildReport):
def test_a_declared_death_is_reported_as_declared(self):
def boom(*a, **k):
raise upstream.GoneError("https://h/x: HTTP 451")
raise forgehttp.GoneError("https://h/x: HTTP 451")
upstream.resolve_head = boom
report = build_report(
@@ -2000,7 +2002,7 @@ class TestDeclaredDeadUpstream(TestBuildReport):
def test_any_refusal_of_a_declared_dead_forge_agrees(self):
# citron's taken domain now resolves and fails TLS.
def tls(*a, **k):
raise upstream.UpstreamError("TLSV1_UNRECOGNIZED_NAME")
raise forgehttp.UpstreamError("TLSV1_UNRECOGNIZED_NAME")
upstream.resolve_head = tls
report = build_report("test", self._profile_with("domain taken"), self.dir)
@@ -2018,10 +2020,10 @@ class TestDeclaredDeadUpstream(TestBuildReport):
def test_an_undeclared_death_is_unchanged(self):
def boom(*a, **k):
raise upstream.GoneError("https://h/x: HTTP 451")
raise forgehttp.GoneError("https://h/x: HTTP 451")
upstream.resolve_head = boom
with self.assertRaises(upstream.GoneError):
with self.assertRaises(forgehttp.GoneError):
build_report("test", self._profile(["a.c:1"]), self.dir)
@@ -2087,7 +2089,7 @@ class TestBareNameResolvedAtThePin(TestBuildReport):
def list_tree(repo, sha, cache_dir, offline=False):
return sorted({path for rev, path in self.files if rev == sha}), False
upstream.list_tree = list_tree
upstreamtree.list_tree = list_tree
def test_a_bare_name_follows_the_file_that_moved_after_the_pin(self):
self._tree_per_revision()
@@ -2170,7 +2172,7 @@ class TestRunResilience(unittest.TestCase):
def flaky(repo, date, cache_dir, offline=False, branch=None):
self.seen.append(repo.slug)
if repo.slug == "o/bad":
raise upstream.UpstreamError("HTTP 401")
raise forgehttp.UpstreamError("HTTP 401")
return "pinsha"
upstream.resolve_commit_at = flaky
@@ -2186,12 +2188,12 @@ class TestRunResilience(unittest.TestCase):
"profiled_date": "2026-03-29",
"files": [{"name": "a.bin", "source_ref": "a.c:1"}],
}
with self.assertRaises(upstream.UpstreamError):
with self.assertRaises(forgehttp.UpstreamError):
build_report("bad", profile, self.tmp.name)
def test_rate_limit_still_propagates(self):
def limited(repo, date, cache_dir, offline=False, branch=None):
raise upstream.RateLimitError("HTTP 403")
raise forgehttp.RateLimitError("HTTP 403")
upstream.resolve_commit_at = limited
profile = {
@@ -2200,7 +2202,7 @@ class TestRunResilience(unittest.TestCase):
"profiled_date": "2026-03-29",
"files": [{"name": "a.bin", "source_ref": "a.c:1"}],
}
with self.assertRaises(upstream.RateLimitError):
with self.assertRaises(forgehttp.RateLimitError):
build_report("x", profile, self.tmp.name)
@@ -2240,7 +2242,7 @@ class TestExtrasSurviveARefusingForge(unittest.TestCase):
original = upstream.fetch_file
def refuse(*_args, **_kwargs):
raise upstream.UpstreamError("https://x/y: HTTP 403")
raise forgehttp.UpstreamError("https://x/y: HTTP 403")
upstream.fetch_file = refuse
try:
@@ -2279,11 +2281,11 @@ class TestExtrasSurviveARefusingForge(unittest.TestCase):
original = upstream.fetch_file
def quota(*_args, **_kwargs):
raise upstream.RateLimitError("quota")
raise forgehttp.RateLimitError("quota")
upstream.fetch_file = quota
try:
with self.assertRaises(upstream.RateLimitError):
with self.assertRaises(forgehttp.RateLimitError):
profiling_run._attach_detection(
self._profile(), _sample_report(), "x", False, True, False
)
@@ -2814,9 +2816,9 @@ class TestWriteDryRun(unittest.TestCase):
from unittest import mock
before = self.path.read_bytes()
cold = upstream.NotCachedError("x.c not cached")
cold = forgehttp.NotCachedError("x.c not cached")
with mock.patch.object(profiling_run, "realign_prose", side_effect=[[], cold]), \
self.assertRaises(upstream.NotCachedError):
self.assertRaises(forgehttp.NotCachedError):
self._run(self._args(rebase_refs=True, dry_run=False), self._shifted())
self.assertEqual(self.path.read_bytes(), before)
@@ -2828,7 +2830,7 @@ class TestWriteDryRun(unittest.TestCase):
before = self.path.read_bytes()
skipped = ProfileReport(name="p", entries=[], counts={}, skipped="offline: not cached",
skip_kind=SkipKind.OFFLINE)
cold = upstream.NotCachedError("o/n@pin:a.c is not in the offline cache")
cold = forgehttp.NotCachedError("o/n@pin:a.c is not in the offline cache")
reports: list[ProfileReport] = []
failed: set[str] = set()
with mock.patch.object(profiling_run, "_build_full_report", return_value=skipped), \
@@ -3787,7 +3789,7 @@ class APassedReleaseIsNewerThanTheTag(unittest.TestCase):
"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(upstream, "ancestry", return_value=(5, 0)):
mock.patch.object(upstreamtree, "ancestry", return_value=(5, 0)):
self.assertIsNone(versions.latest_passed_release("repo", version, "pin", "c", True))
@@ -3800,7 +3802,7 @@ class ANewerReleaseThanTheTag(unittest.TestCase):
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(upstream, "ancestry", side_effect=lambda *a, **k: next(answers)):
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):
@@ -3836,7 +3838,7 @@ class AProjectThatOnlyTags(unittest.TestCase):
version = versions.VersionReport("v1.2", "v1.3", None, None, True, "tag12")
with mock.patch.object(upstream, "tag_commit", return_value="tag13"), \
mock.patch.object(upstream, "ancestry", return_value=(7, 0)):
mock.patch.object(upstreamtree, "ancestry", return_value=(7, 0)):
self.assertEqual(versions.newer_release("repo", version, "tag12", "c", True), "v1.3")
@@ -3860,7 +3862,7 @@ class APassedReleaseUnderAnUntaggedVersion(unittest.TestCase):
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(upstream, "ancestry", return_value=(3, 0)):
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):
@@ -3872,10 +3874,10 @@ class APassedReleaseUnderAnUntaggedVersion(unittest.TestCase):
class TestAncestry(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
self.saved = upstream.http_json
self.saved = forgehttp.http_json
def tearDown(self):
upstream.http_json = self.saved
forgehttp.http_json = self.saved
self.tmp.cleanup()
def test_github_answers_both_directions_at_once(self):
@@ -3885,10 +3887,10 @@ class TestAncestry(unittest.TestCase):
calls.append(url)
return {"ahead_by": 3, "behind_by": 0}
upstream.http_json = answer
forgehttp.http_json = answer
repo = upstream.parse_repo("https://github.com/o/n")
self.assertEqual(
upstream.ancestry(repo, "tag", "pin", self.tmp.name), (3, 0)
upstreamtree.ancestry(repo, "tag", "pin", self.tmp.name), (3, 0)
)
self.assertEqual(len(calls), 1)
@@ -3897,10 +3899,10 @@ class TestAncestry(unittest.TestCase):
forward = "from=tag&to=pin" in url
return {"commits": [{}] * (0 if forward else 5)}
upstream.http_json = answer
forgehttp.http_json = answer
repo = upstream.parse_repo("https://gitlab.com/o/n")
self.assertEqual(
upstream.ancestry(repo, "tag", "pin", self.tmp.name), (0, 5)
upstreamtree.ancestry(repo, "tag", "pin", self.tmp.name), (0, 5)
)
@@ -4316,10 +4318,10 @@ class TestCollectCitations(unittest.TestCase):
with mock.patch.object(upstream, "fetch_file", side_effect=fetch), \
mock.patch.object(
upstream, "list_gitlinks",
upstreamtree, "list_gitlinks",
return_value={"Q3E/src/main/jni/xash3d/xash3d-fwgs": "s1"},
):
target = upstream.through_gitlink(
target = upstreamtree.through_gitlink(
port, "p1",
"Q3E/src/main/jni/xash3d/xash3d-fwgs/filesystem/filesystem.c", "c",
)
@@ -4868,14 +4870,14 @@ class TestRealignProse(unittest.TestCase):
self.files: dict[tuple[str, str], list[str]] = {}
self._orig = (
upstream.fetch_file,
upstream.list_tree,
upstreamtree.list_tree,
)
upstream.fetch_file = (
lambda repo, sha, path, cache_dir, offline=False: self.files.get(
(sha, path)
)
)
upstream.list_tree = (
upstreamtree.list_tree = (
lambda repo, sha, cache_dir, offline=False: (
sorted({p for _, p in self.files}), False
)
@@ -4884,7 +4886,7 @@ class TestRealignProse(unittest.TestCase):
def tearDown(self):
(
upstream.fetch_file,
upstream.list_tree,
upstreamtree.list_tree,
) = self._orig
self.tmp.cleanup()
@@ -5190,7 +5192,7 @@ class TestRealignProse(unittest.TestCase):
base = PROSE_SAMPLE.replace("(a.c:10)", "(deep.c:10)")
self._commit(base.replace('"pin"', '"oldpin"'), "profile")
self.path.write_text(base, encoding="utf-8")
upstream.list_tree = (
upstreamtree.list_tree = (
lambda repo, sha, cache_dir, offline=False: ([], True)
)
self.files[("oldpin", "b.c")] = list("pqrstuvwx")
@@ -5242,7 +5244,7 @@ class TestRateLimitEndsOneProfile(unittest.TestCase):
def build(name, *_args, **_kwargs):
if name == "cemu":
raise upstream.RateLimitError(
raise forgehttp.RateLimitError(
"https://git.libretro.com/x: HTTP 429", "git.libretro.com"
)
return ProfileReport(name=name, counts={"CHANGED": 1})
@@ -5593,7 +5595,7 @@ class TestOutputModesApplyTheirFlags(unittest.TestCase):
def build(name, *args, **kwargs):
if name == "drift":
raise upstream.UpstreamError("https://x: HTTP 502")
raise forgehttp.UpstreamError("https://x: HTTP 502")
return ProfileReport(name=name)
out = io.StringIO()
@@ -5798,7 +5800,7 @@ class UpstreamVendoredAsASubmodule(unittest.TestCase):
profiling_repos.RepoView(repo_u, "sub-old", "nesbox-tip", "upstream_commit", "upstream"),
]
with mock.patch.object(
upstream, "list_gitlinks",
upstreamtree, "list_gitlinks",
side_effect=lambda repo, sha, *a, **k: links.get(sha, {}),
):
return profiling_repos._follow_submodule(views, "cache", True)
@@ -5820,9 +5822,9 @@ class UpstreamVendoredAsASubmodule(unittest.TestCase):
profiling_repos.RepoView(object(), "sub-old", "nesbox-tip", "upstream_commit", "upstream"),
]
with mock.patch.object(
upstream, "list_gitlinks",
side_effect=upstream.TruncatedListingError("tree listing truncated"),
), self.assertRaises(upstream.TruncatedListingError):
upstreamtree, "list_gitlinks",
side_effect=forgehttp.TruncatedListingError("tree listing truncated"),
), self.assertRaises(forgehttp.TruncatedListingError):
profiling_repos._follow_submodule(views, "cache", True)
@@ -5837,10 +5839,10 @@ class TruncatedGitlinksInTheResolver(unittest.TestCase):
def links(repo, sha, *_args):
if repo == "a":
raise upstream.TruncatedListingError("a@p1: tree listing truncated")
raise forgehttp.TruncatedListingError("a@p1: tree listing truncated")
return {"sub": "s"}
with mock.patch.object(upstream, "list_gitlinks", side_effect=links), \
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"]])
@@ -5859,7 +5861,7 @@ class AMirrorOutlivesAGoneSource(unittest.TestCase):
def head(repo, cache_dir, offline=False, branch=None):
if repo == gone_repo:
raise upstream.GoneError("HTTP 451")
raise forgehttp.GoneError("HTTP 451")
return "mirror-head"
profile = {
@@ -5883,7 +5885,7 @@ class AMirrorOutlivesAGoneSource(unittest.TestCase):
def head(repo, cache_dir, offline=False, branch=None):
if repo == gone_repo:
raise upstream.GoneError("HTTP 404")
raise forgehttp.GoneError("HTTP 404")
return "tip"
profile = {
@@ -6042,9 +6044,9 @@ class UpstreamForkedByThePort(unittest.TestCase):
profiling_repos.RepoView(self.up, "old-base", "up-tip", "upstream_commit", "upstream"),
]
with mock.patch.object(
upstream, "fork_base", return_value=base
upstreamtree, "fork_base", return_value=base
) as asked, mock.patch.object(
upstream, "ancestry", return_value=ancestry
upstreamtree, "ancestry", return_value=ancestry
):
followed = profiling_repos._follow_fork_base(views, "cache", True)
return followed, asked
@@ -6077,7 +6079,7 @@ class ACachedTipOlderThanThePin(TestBuildReport):
77d80d7, its ancestor: a bump would have moved the pin backwards."""
def test_the_tip_is_asked_again(self):
upstream.ancestry = lambda *a, **k: (0, 3)
upstreamtree.ancestry = lambda *a, **k: (0, 3)
upstream.resolve_head = (
lambda repo, cache_dir, offline=False, branch=None, fresh=False:
"newtip" if fresh else "staletip"
@@ -6095,10 +6097,10 @@ class OfflineCacheMissIsNotGone(TestBuildReport):
def test_an_uncached_file_is_not_reported_gone(self):
def cold(repo, sha, path, cache_dir, offline=False):
raise upstream.NotCachedError(f"{path} not cached")
raise forgehttp.NotCachedError(f"{path} not cached")
upstream.fetch_file = cold
with self.assertRaises(upstream.NotCachedError):
with self.assertRaises(forgehttp.NotCachedError):
build_report("test", self._profile(["a.c:2"]), self.dir, offline=True)
@@ -6287,10 +6289,10 @@ class AnOffForgeProfileWatchesItsReleasePage(unittest.TestCase):
"url": "https://example.test/altirra", "pattern": r"Altirra (\d+\.\d+) released",
}}
answers = [
(upstream.NotCachedError("cold"), "not cached offline"),
(forgehttp.NotCachedError("cold"), "not cached offline"),
(None, "page absent"),
("<p>nothing here</p>", "pattern not found"),
(upstream.UpstreamError("HTTP 500"), "https://example.test/altirra: HTTP 500"),
(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}
@@ -6301,7 +6303,7 @@ class AnOffForgeProfileWatchesItsReleasePage(unittest.TestCase):
stderr.write.assert_not_called()
def test_an_uncached_page_offline_is_not_an_absent_one(self):
with tempfile.TemporaryDirectory() as cache, self.assertRaises(upstream.NotCachedError):
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):
@@ -6366,7 +6368,7 @@ class EachCitationNamesTheCodeThatAsks(unittest.TestCase):
lambda repo, sha, path, cache_dir, offline=False:
trees.get(repo.slug, {}).get(path)
)
upstream.list_tree = (
upstreamtree.list_tree = (
lambda repo, sha, cache_dir, offline=False: (sorted(trees[repo.slug]), False)
)
upstream.resolve_head = (
@@ -6414,7 +6416,7 @@ class ARoleIsReadPerPart(unittest.TestCase):
lambda repo, sha, path, cache_dir, offline=False:
trees.get((repo.slug, sha), {}).get(path)
)
upstream.list_tree = (
upstreamtree.list_tree = (
lambda repo, sha, cache_dir, offline=False:
(sorted(trees.get((repo.slug, sha), {})), False)
)
@@ -6422,9 +6424,9 @@ class ARoleIsReadPerPart(unittest.TestCase):
lambda repo, cache_dir, offline=False, branch=None:
"heads" if repo.owner == "libretro" else "pinu"
)
upstream.compare = (
upstreamtree.compare = (
lambda repo, base, head, cache_dir, offline=False:
upstream.CompareResult([], False)
upstreamtree.CompareResult([], False)
)
text = (
'emulator: T\n'
+2 -1
View File
@@ -451,6 +451,7 @@ class TheRemoteCommitComesFromTheForgeClient(unittest.TestCase):
def _resolve(self, url: str, version: str, answers: list) -> tuple[str | None, list]:
from core import upstream
from core import forgehttp
seen: list = []
@@ -464,7 +465,7 @@ class TheRemoteCommitComesFromTheForgeClient(unittest.TestCase):
(REPO_ROOT / "tmp").mkdir(exist_ok=True)
with tempfile.TemporaryDirectory(dir=REPO_ROOT / "tmp") as tmp, \
mock.patch.object(upstream, "CACHE_DIR", tmp), \
mock.patch.object(upstream, "_sleep", lambda _s: None), \
mock.patch.object(forgehttp, "_sleep", lambda _s: None), \
mock.patch.dict("os.environ", {"GITHUB_TOKEN": "SECRET"}), \
mock.patch("urllib.request.urlopen", urlopen):
return datadirs.get_remote_sha(url, version), seen
+2 -1
View File
@@ -298,9 +298,10 @@ class CachedDirectory(unittest.TestCase):
from unittest import mock
from core import upstream
from core import upstreamtree
fetcher = Fetcher({"os": {"repo": "https://gitlab.com/g/p", "commit": "0" * 40}})
with mock.patch.object(upstream, "cache_gitlab_directory", return_value={"sys/a/system.ini"}):
with mock.patch.object(upstreamtree, "cache_gitlab_directory", return_value={"sys/a/system.ini"}):
fetcher.cache_directory("os", "sys/")
with mock.patch.object(upstream, "fetch_file", side_effect=AssertionError("network")):
self.assertIsNone(fetcher.optional_text("os", "sys/b/system.ini"))
+7 -7
View File
@@ -159,19 +159,19 @@ class RateLimitedForge(unittest.TestCase):
return urllib.error.HTTPError("u", 429, "Too Many Requests", headers, io.BytesIO())
def setUp(self):
from core import upstream
from core import forgehttp
self.waits: list[float] = []
patcher = mock.patch.object(upstream, "_sleep", self.waits.append)
patcher = mock.patch.object(forgehttp, "_sleep", self.waits.append)
patcher.start()
self.addCleanup(patcher.stop)
upstream._exhausted_hosts.clear()
self.addCleanup(upstream._exhausted_hosts.clear)
forgehttp._exhausted_hosts.clear()
self.addCleanup(forgehttp._exhausted_hosts.clear)
def test_a_rate_limit_is_waited_out(self):
import io
from core import upstream
from core import forgehttp
from scraper.base_scraper import fetch_bytes
answers = [self._limited("7"), self._limited(None), io.BytesIO(b"ok")]
@@ -184,7 +184,7 @@ class RateLimitedForge(unittest.TestCase):
with mock.patch("urllib.request.urlopen", urlopen):
self.assertEqual(fetch_bytes("https://x"), b"ok")
self.assertEqual(self.waits, [7.0, upstream.RATE_LIMIT_WAITS[1]])
self.assertEqual(self.waits, [7.0, forgehttp.RATE_LIMIT_WAITS[1]])
def test_a_lasting_limit_or_a_missing_file_fails(self):
from scraper.base_scraper import FetchError, fetch_bytes
@@ -987,7 +987,7 @@ class EveryGitHubApiCallerSendsTheToken(unittest.TestCase):
# arcade_parent_importer names API URLs and sends them through
# dat_fetch.api_json, which holds the token, and the
# scrapers through base_scraper.github_json, the rest through
# core.upstream.fetch_body or forge_headers.
# core.forgehttp.fetch_body or forge_headers.
and ("Request(" in source or "urlopen(" in source or path.suffix == ".sh")
and "GITHUB_TOKEN" not in source
and "github_headers(" not in source
+1 -1
View File
@@ -276,7 +276,7 @@ class OneImplementationPerJob(unittest.TestCase):
for needle in needles
if needle in path.read_text(encoding="utf-8")
]
# The ETag HEAD probe is core.upstream.remote_etag. MinUI reads
# The ETag HEAD probe is core.forgehttp.remote_etag. MinUI reads
# through a fetch its tests replace, and hands the answer to
# tree_entries.
self.assertEqual(found, ["minui_scraper.py: ?recursive=1"])
+4 -4
View File
@@ -292,8 +292,8 @@ class GoatCounterExport(unittest.TestCase):
refusal = urllib.error.HTTPError("https://retrobios.goatcounter.com/api/v0/stats/hits", 429,
"Too Many Requests", headers, io.BytesIO(b""))
with mock.patch.object(insights.urllib.request, "urlopen", side_effect=refusal), \
mock.patch.object(insights.upstream, "_sleep") as sleep, \
mock.patch.object(insights.upstream, "_exhausted_hosts", set()), \
mock.patch.object(insights.forgehttp, "_sleep") as sleep, \
mock.patch.object(insights.forgehttp, "_exhausted_hosts", set()), \
self.assertRaisesRegex(insights.SourceUnavailable, "2356 s") as caught:
insights._get_json("https://retrobios.goatcounter.com/api/v0/stats/hits")
sleep.assert_not_called()
@@ -307,7 +307,7 @@ class GoatCounterExport(unittest.TestCase):
answer.__enter__.return_value.status = 200
answer.__enter__.return_value.read.return_value = json.dumps({"ok": 1}).encode()
with mock.patch.object(insights.urllib.request, "urlopen", side_effect=[refusal, answer]), \
mock.patch.object(insights.upstream, "_sleep") as sleep:
mock.patch.object(insights.forgehttp, "_sleep") as sleep:
self.assertEqual(insights._get_json("https://x/api"), {"ok": 1})
sleep.assert_called_once_with(2)
@@ -319,7 +319,7 @@ class GoatCounterExport(unittest.TestCase):
answer.__enter__.return_value.status = 200
answer.__enter__.return_value.read.return_value = json.dumps({"ok": 1}).encode()
with mock.patch.object(insights.urllib.request, "urlopen", side_effect=[refusal, answer]), \
mock.patch.object(insights.upstream, "_sleep"):
mock.patch.object(insights.forgehttp, "_sleep"):
self.assertEqual(insights._get_json("https://x/api"), {"ok": 1})
def test_github_headers_come_from_the_forge_helper(self) -> None:
+3 -2
View File
@@ -86,6 +86,7 @@ import core
from sitegen import sources
from model import releaserecord
from core import upstream
from core import forgehttp
from packs.verdicts import Severity, blocking_missing, compute_severity
from acquire.provenance import build_report
from model.dumpcatalog import load_provenance_snapshots
@@ -1189,8 +1190,8 @@ class SourceLinksOnlyWhereTheFileIs(unittest.TestCase):
profile = {"source": "https://github.com/o/r", "source_commit": "e" * 40,
"files": [{"source_ref": "src/a.c:5"}]}
with mock.patch.object(sources, "_cached_tree", return_value=None), \
mock.patch.object(core.upstream, "list_directory",
side_effect=upstream.UpstreamError("HTTP 404")):
mock.patch.object(core.upstreamtree, "list_directory",
side_effect=forgehttp.UpstreamError("HTTP 404")):
held, unread = sources.build_source_paths({"p": profile}, [TMP])
self.assertEqual(held, {})
self.assertEqual(unread, ["github.com/o/r@" + "e" * 40])
+3 -2
View File
@@ -21,6 +21,7 @@ from unittest import mock
from model import sourceref
from sitegen import sources
from core import upstream
from core import upstreamtree
from model.profiles import load_emulator_profiles
from model.sourceref import ref_role, source_ref_values, split_source_ref
@@ -78,7 +79,7 @@ class ForgejoTreesArePaged(unittest.TestCase):
return {"tree": pages.get(page, []), "truncated": True, "total_count": 1002}
with mock.patch.object(upstream, "cached_api", side_effect=fake_api):
paths, truncated = upstream.list_tree(repo, "7" * 40, "unused")
paths, truncated = upstreamtree.list_tree(repo, "7" * 40, "unused")
self.assertFalse(truncated)
self.assertEqual(len(paths), 1001)
self.assertIn("src/Ryujinx.HLE/FileSystem/VirtualFileSystem.cs", paths)
@@ -87,7 +88,7 @@ class ForgejoTreesArePaged(unittest.TestCase):
repo = upstream.parse_repo("https://github.com/o/r")
payload = {"tree": [{"type": "blob", "path": "x"}], "truncated": True}
with mock.patch.object(upstream, "cached_api", return_value=payload) as api:
paths, truncated = upstream.list_tree(repo, "7" * 40, "unused")
paths, truncated = upstreamtree.list_tree(repo, "7" * 40, "unused")
self.assertTrue(truncated)
self.assertEqual(api.call_count, 1)
+4 -4
View File
@@ -974,13 +974,13 @@ class TheGitHubTokenComesFromGh(unittest.TestCase):
run.assert_not_called()
def test_every_api_caller_reads_it(self):
from core import upstream
from core import forgehttp
from profiling.quota import check_quota
from scraper import base_scraper
with self._gh():
self.assertEqual(
upstream.forge_headers("https://api.github.com/repos/o/n")["Authorization"],
forgehttp.forge_headers("https://api.github.com/repos/o/n")["Authorization"],
"Bearer gho_fromgh",
)
os.environ.pop("GITHUB_TOKEN")
@@ -992,10 +992,10 @@ class TheGitHubTokenComesFromGh(unittest.TestCase):
check_quota(606, offline=False)
def test_another_forge_never_triggers_gh(self):
from core import upstream
from core import forgehttp
with self._gh() as run:
headers = upstream.forge_headers("https://gitlab.com/api/v4/projects/1")
headers = forgehttp.forge_headers("https://gitlab.com/api/v4/projects/1")
self.assertNotIn("Authorization", headers)
run.assert_not_called()
+170 -168
View File
@@ -17,6 +17,8 @@ import urllib.request
from pathlib import Path
from core import upstream
from core import forgehttp
from core import upstreamtree
from core.upstream import make_repo, parse_repo, raw_url
@@ -169,43 +171,43 @@ class TestTokenScope(unittest.TestCase):
os.environ["GITHUB_TOKEN"] = self._orig
def test_sent_to_github_api(self):
h = upstream.forge_headers("https://api.github.com/repos/o/n/commits")
h = forgehttp.forge_headers("https://api.github.com/repos/o/n/commits")
self.assertEqual(h["Authorization"], "Bearer gho_secret")
def test_sent_to_github_raw(self):
h = upstream.forge_headers("https://raw.githubusercontent.com/o/n/sha/a.c")
h = forgehttp.forge_headers("https://raw.githubusercontent.com/o/n/sha/a.c")
self.assertIn("Authorization", h)
def test_withheld_from_codeberg(self):
h = upstream.forge_headers("https://codeberg.org/api/v1/repos/o/n/commits")
h = forgehttp.forge_headers("https://codeberg.org/api/v1/repos/o/n/commits")
self.assertNotIn("Authorization", h)
def test_withheld_from_gitlab(self):
h = upstream.forge_headers("https://gitlab.com/api/v4/projects/x/repository/commits")
h = forgehttp.forge_headers("https://gitlab.com/api/v4/projects/x/repository/commits")
self.assertNotIn("Authorization", h)
def test_withheld_from_forgejo_instances(self):
for host in ("git.citron-emu.org", "git.eden-emu.dev", "git.ryujinx.app"):
h = upstream.forge_headers(f"https://{host}/api/v1/repos/o/n/commits")
h = forgehttp.forge_headers(f"https://{host}/api/v1/repos/o/n/commits")
self.assertNotIn("Authorization", h, host)
def test_withheld_from_a_lookalike_host(self):
h = upstream.forge_headers("https://github.com.evil.example/repos/o/n")
h = forgehttp.forge_headers("https://github.com.evil.example/repos/o/n")
self.assertNotIn("Authorization", h)
def test_withheld_from_a_url_that_only_names_the_api(self):
h = upstream.forge_headers("https://evil.example/x?next=https://api.github.com/")
h = forgehttp.forge_headers("https://evil.example/x?next=https://api.github.com/")
self.assertNotIn("Authorization", h)
def test_withheld_from_the_web_host(self):
# A release download on github.com redirects to asset storage, and
# urllib carries the header across the redirect.
h = upstream.forge_headers("https://github.com/o/n/releases/download/v1/a.zip")
h = forgehttp.forge_headers("https://github.com/o/n/releases/download/v1/a.zip")
self.assertNotIn("Authorization", h)
def test_absent_token_adds_no_header(self):
os.environ.pop("GITHUB_TOKEN", None)
h = upstream.forge_headers("https://api.github.com/repos/o/n")
h = forgehttp.forge_headers("https://api.github.com/repos/o/n")
self.assertNotIn("Authorization", h)
@@ -214,34 +216,34 @@ class TestHttpFailure(unittest.TestCase):
def test_429_is_a_rate_limit(self):
self.assertIsInstance(
upstream._http_failure("u", _http_error(429)), upstream.RateLimitError
forgehttp._http_failure("u", _http_error(429)), forgehttp.RateLimitError
)
def test_429_names_the_wait_the_forge_asks_for(self):
failure = upstream._http_failure("u", _http_error(429, {"Retry-After": "1833"}))
failure = forgehttp._http_failure("u", _http_error(429, {"Retry-After": "1833"}))
self.assertIn("retry after 1833 s", str(failure))
def test_403_with_exhausted_quota_is_a_rate_limit(self):
exc = _http_error(403, {"X-RateLimit-Remaining": "0"})
self.assertIsInstance(
upstream._http_failure("u", exc), upstream.RateLimitError
forgehttp._http_failure("u", exc), forgehttp.RateLimitError
)
def test_403_with_quota_left_is_not(self):
exc = _http_error(403, {"X-RateLimit-Remaining": "4970"})
failure = upstream._http_failure("u", exc)
self.assertIsInstance(failure, upstream.UpstreamError)
self.assertNotIsInstance(failure, upstream.RateLimitError)
failure = forgehttp._http_failure("u", exc)
self.assertIsInstance(failure, forgehttp.UpstreamError)
self.assertNotIsInstance(failure, forgehttp.RateLimitError)
def test_bare_403_from_a_forge_is_not_a_rate_limit(self):
failure = upstream._http_failure("u", _http_error(403))
self.assertIsInstance(failure, upstream.UpstreamError)
self.assertNotIsInstance(failure, upstream.RateLimitError)
failure = forgehttp._http_failure("u", _http_error(403))
self.assertIsInstance(failure, forgehttp.UpstreamError)
self.assertNotIsInstance(failure, forgehttp.RateLimitError)
def test_525_is_a_plain_upstream_error(self):
failure = upstream._http_failure("u", _http_error(525))
self.assertIsInstance(failure, upstream.UpstreamError)
self.assertNotIsInstance(failure, upstream.RateLimitError)
failure = forgehttp._http_failure("u", _http_error(525))
self.assertIsInstance(failure, forgehttp.UpstreamError)
self.assertNotIsInstance(failure, forgehttp.RateLimitError)
@tests.ONLINE
@@ -249,14 +251,14 @@ class TestFetchRetry(unittest.TestCase):
"""Transient network failures are retried, definitive answers are not."""
def setUp(self):
self._orig = (urllib.request.urlopen, upstream._sleep)
self._orig = (urllib.request.urlopen, forgehttp._sleep)
self.slept: list[float] = []
upstream._sleep = self.slept.append
upstream._exhausted_hosts.clear()
forgehttp._sleep = self.slept.append
forgehttp._exhausted_hosts.clear()
def tearDown(self):
urllib.request.urlopen, upstream._sleep = self._orig
upstream._exhausted_hosts.clear()
urllib.request.urlopen, forgehttp._sleep = self._orig
forgehttp._exhausted_hosts.clear()
def _serve(self, outcomes):
self.calls = 0
@@ -273,31 +275,31 @@ class TestFetchRetry(unittest.TestCase):
def test_dropped_connection_is_retried_then_succeeds(self):
dropped = http.client.RemoteDisconnected("closed")
self._serve([dropped, b"payload"])
self.assertEqual(upstream.fetch_body("https://host/x"), b"payload")
self.assertEqual(forgehttp.fetch_body("https://host/x"), b"payload")
self.assertEqual(self.calls, 2)
self.assertEqual(len(self.slept), 1)
def test_retries_are_bounded(self):
self._serve([http.client.RemoteDisconnected("closed")])
with self.assertRaises(upstream.UpstreamError):
upstream.fetch_body("https://host/x")
self.assertEqual(self.calls, upstream.RETRIES)
with self.assertRaises(forgehttp.UpstreamError):
forgehttp.fetch_body("https://host/x")
self.assertEqual(self.calls, forgehttp.RETRIES)
def test_server_error_is_retried(self):
self._serve([_http_error(503)])
with self.assertRaises(upstream.UpstreamError):
upstream.fetch_body("https://host/x")
self.assertEqual(self.calls, upstream.RETRIES)
with self.assertRaises(forgehttp.UpstreamError):
forgehttp.fetch_body("https://host/x")
self.assertEqual(self.calls, forgehttp.RETRIES)
def test_forbidden_is_not_retried(self):
self._serve([_http_error(403)])
with self.assertRaises(upstream.UpstreamError):
upstream.fetch_body("https://host/x")
with self.assertRaises(forgehttp.UpstreamError):
forgehttp.fetch_body("https://host/x")
self.assertEqual(self.calls, 1)
def test_missing_file_is_not_retried(self):
self._serve([_http_error(404)])
self.assertIsNone(upstream.fetch_body("https://host/x"))
self.assertIsNone(forgehttp.fetch_body("https://host/x"))
self.assertEqual(self.calls, 1)
@staticmethod
@@ -313,26 +315,26 @@ class TestFetchRetry(unittest.TestCase):
# git.libretro.com answered 429 on cemu's tree a few hundred
# requests into a pass, and the whole pass stopped.
self._serve([self._limited("7"), self._limited(), b"payload"])
self.assertEqual(upstream.fetch_body("https://host/x"), b"payload")
self.assertEqual(self.slept, [7.0, upstream.RATE_LIMIT_WAITS[1]])
self.assertEqual(forgehttp.fetch_body("https://host/x"), b"payload")
self.assertEqual(self.slept, [7.0, forgehttp.RATE_LIMIT_WAITS[1]])
def test_lasting_rate_limit_mutes_the_host_only(self):
self._serve([self._limited()])
with self.assertRaises(upstream.RateLimitError) as caught:
upstream.fetch_body("https://host/x")
with self.assertRaises(forgehttp.RateLimitError) as caught:
forgehttp.fetch_body("https://host/x")
self.assertEqual(caught.exception.host, "host")
self.assertEqual(self.calls, len(upstream.RATE_LIMIT_WAITS) + 1)
self.assertEqual(self.calls, len(forgehttp.RATE_LIMIT_WAITS) + 1)
# The same host is not asked again, another one still is.
with self.assertRaises(upstream.RateLimitError):
upstream.fetch_body("https://host/y")
self.assertEqual(self.calls, len(upstream.RATE_LIMIT_WAITS) + 1)
with self.assertRaises(forgehttp.RateLimitError):
forgehttp.fetch_body("https://host/y")
self.assertEqual(self.calls, len(forgehttp.RATE_LIMIT_WAITS) + 1)
self._serve([b"other"])
self.assertEqual(upstream.fetch_body("https://other/x"), b"other")
self.assertEqual(forgehttp.fetch_body("https://other/x"), b"other")
def test_long_retry_after_is_not_waited(self):
self._serve([self._limited(str(int(upstream.RATE_LIMIT_WAIT_CAP) + 1))])
with self.assertRaises(upstream.RateLimitError):
upstream.fetch_body("https://host/x")
self._serve([self._limited(str(int(forgehttp.RATE_LIMIT_WAIT_CAP) + 1))])
with self.assertRaises(forgehttp.RateLimitError):
forgehttp.fetch_body("https://host/x")
self.assertEqual((self.calls, self.slept), (1, []))
def test_goatcounter_reset_header_is_waited_with_a_second_more(self):
@@ -341,7 +343,7 @@ class TestFetchRetry(unittest.TestCase):
headers = email.message.Message()
headers["X-Rate-Limit-Reset"] = "3"
self._serve([_http_error(429, headers), b"payload"])
self.assertEqual(upstream.fetch_body("https://host/x"), b"payload")
self.assertEqual(forgehttp.fetch_body("https://host/x"), b"payload")
self.assertEqual(self.slept, [4.0])
def test_download_retries_a_cut_stream_and_writes_whole(self):
@@ -359,7 +361,7 @@ class TestFetchRetry(unittest.TestCase):
urllib.request.urlopen = opener
with tempfile.TemporaryDirectory() as tmp:
target = Path(tmp) / "file.bin"
served = upstream.download("https://host/file.bin", target)
served = forgehttp.download("https://host/file.bin", target)
self.assertEqual(target.read_bytes(), b"payload")
self.assertEqual(served["Content-Disposition"], "attachment")
self.assertEqual(os.listdir(tmp), ["file.bin"])
@@ -375,7 +377,7 @@ class TestFetchRetry(unittest.TestCase):
with tempfile.TemporaryDirectory() as tmp:
target = Path(tmp) / "file.bin"
target.write_bytes(b"old")
self.assertIsNone(upstream.download("https://host/f", target, accept=lambda _p: False))
self.assertIsNone(forgehttp.download("https://host/f", target, accept=lambda _p: False))
self.assertEqual(target.read_bytes(), b"old")
self.assertEqual(os.listdir(tmp), ["file.bin"])
@@ -388,7 +390,7 @@ class TestFetchRetry(unittest.TestCase):
urllib.request.urlopen = opener
with tempfile.TemporaryDirectory() as tmp:
with self.assertRaises(ValueError):
upstream.download("https://host/f", Path(tmp) / "f", max_bytes=4)
forgehttp.download("https://host/f", Path(tmp) / "f", max_bytes=4)
self.assertEqual(os.listdir(tmp), [])
def test_exhausted_github_quota_is_not_waited(self):
@@ -397,8 +399,8 @@ class TestFetchRetry(unittest.TestCase):
headers = email.message.Message()
headers["X-RateLimit-Remaining"] = "0"
self._serve([_http_error(403, headers)])
with self.assertRaises(upstream.RateLimitError):
upstream.fetch_body("https://host/x")
with self.assertRaises(forgehttp.RateLimitError):
forgehttp.fetch_body("https://host/x")
self.assertEqual((self.calls, self.slept), (1, []))
@@ -413,13 +415,13 @@ class TestGoneUpstream(unittest.TestCase):
"""
def setUp(self):
self._orig = (urllib.request.urlopen, upstream._sleep)
self._orig = (urllib.request.urlopen, forgehttp._sleep)
self.slept: list[float] = []
upstream._sleep = self.slept.append
forgehttp._sleep = self.slept.append
self.calls = 0
def tearDown(self):
urllib.request.urlopen, upstream._sleep = self._orig
urllib.request.urlopen, forgehttp._sleep = self._orig
def _serve(self, outcome):
def opener(req, timeout=None):
@@ -430,24 +432,24 @@ class TestGoneUpstream(unittest.TestCase):
def test_legal_takedown_is_gone_and_not_retried(self):
self._serve(_http_error(451))
with self.assertRaises(upstream.GoneError):
upstream.fetch_body("https://host/x")
with self.assertRaises(forgehttp.GoneError):
forgehttp.fetch_body("https://host/x")
self.assertEqual(self.calls, 1)
self.assertEqual(self.slept, [])
def test_http_gone_is_gone(self):
self._serve(_http_error(410))
with self.assertRaises(upstream.GoneError):
upstream.fetch_body("https://host/x")
with self.assertRaises(forgehttp.GoneError):
forgehttp.fetch_body("https://host/x")
self.assertEqual(self.calls, 1)
def test_unresolvable_host_is_gone_and_not_retried(self):
self._serve(urllib.error.URLError(
socket.gaierror(socket.EAI_NONAME, "Name or service not known")
))
with mock.patch.object(upstream, "_resolver_answers", return_value=True), \
self.assertRaises(upstream.GoneError):
upstream.fetch_body("https://host/x")
with mock.patch.object(forgehttp, "_resolver_answers", return_value=True), \
self.assertRaises(forgehttp.GoneError):
forgehttp.fetch_body("https://host/x")
self.assertEqual(self.calls, 1)
self.assertEqual(self.slept, [])
@@ -457,29 +459,29 @@ class TestGoneUpstream(unittest.TestCase):
for errno, resolver in ((socket.EAI_NONAME, False), (socket.EAI_AGAIN, True)):
with self.subTest(errno=errno, resolver=resolver):
self._serve(urllib.error.URLError(socket.gaierror(errno, "no")))
with mock.patch.object(upstream, "_resolver_answers", return_value=resolver), \
self.assertRaises(upstream.UpstreamError) as caught:
upstream.fetch_body("https://host/x")
self.assertNotIsInstance(caught.exception, upstream.GoneError)
with mock.patch.object(forgehttp, "_resolver_answers", return_value=resolver), \
self.assertRaises(forgehttp.UpstreamError) as caught:
forgehttp.fetch_body("https://host/x")
self.assertNotIsInstance(caught.exception, forgehttp.GoneError)
def test_a_gone_error_is_still_an_upstream_error(self):
self._serve(_http_error(451))
with self.assertRaises(upstream.UpstreamError):
upstream.fetch_body("https://host/x")
with self.assertRaises(forgehttp.UpstreamError):
forgehttp.fetch_body("https://host/x")
def test_refused_request_is_not_gone(self):
"""403 is a forge refusing a request, which anti-bot filters do."""
self._serve(_http_error(403))
with self.assertRaises(upstream.UpstreamError) as caught:
upstream.fetch_body("https://host/x")
self.assertNotIsInstance(caught.exception, upstream.GoneError)
with self.assertRaises(forgehttp.UpstreamError) as caught:
forgehttp.fetch_body("https://host/x")
self.assertNotIsInstance(caught.exception, forgehttp.GoneError)
def test_a_dropped_connection_is_not_gone(self):
self._serve(http.client.RemoteDisconnected("closed"))
with self.assertRaises(upstream.UpstreamError) as caught:
upstream.fetch_body("https://host/x")
self.assertNotIsInstance(caught.exception, upstream.GoneError)
self.assertEqual(self.calls, upstream.RETRIES)
with self.assertRaises(forgehttp.UpstreamError) as caught:
forgehttp.fetch_body("https://host/x")
self.assertNotIsInstance(caught.exception, forgehttp.GoneError)
self.assertEqual(self.calls, forgehttp.RETRIES)
@@ -501,10 +503,10 @@ class TheOfflineSwitchHoldsAtTheGateway(unittest.TestCase):
def test_no_request_goes_out(self):
with mock.patch.object(urllib.request, "urlopen", side_effect=_no_network) as urlopen:
with self.assertRaises(upstream.OfflineError):
upstream.fetch_body("https://api.github.com/rate_limit", accept_json=True)
with self.assertRaises(upstream.NotCachedError):
upstream.download("https://host/x", tests.scratch_dir(self) / "x")
with self.assertRaises(forgehttp.OfflineError):
forgehttp.fetch_body("https://api.github.com/rate_limit", accept_json=True)
with self.assertRaises(forgehttp.NotCachedError):
forgehttp.download("https://host/x", tests.scratch_dir(self) / "x")
urlopen.assert_not_called()
def test_a_file_address_is_read_offline(self):
@@ -513,14 +515,14 @@ class TheOfflineSwitchHoldsAtTheGateway(unittest.TestCase):
open_retrying."""
held = tests.scratch_dir(self) / "held.txt"
held.write_bytes(b"local")
self.assertEqual(upstream.fetch_body(held.as_uri()), b"local")
self.assertEqual(forgehttp.fetch_body(held.as_uri()), b"local")
def test_the_cache_answers_as_an_offline_run(self):
cache = str(tests.scratch_dir(self))
with mock.patch.object(upstream, "http_json", side_effect=_no_network), \
mock.patch.object(upstream, "http_text", side_effect=_no_network):
with mock.patch.object(forgehttp, "http_json", side_effect=_no_network), \
mock.patch.object(forgehttp, "http_text", side_effect=_no_network):
self.assertIsNone(upstream.cached_api("https://api.github.com/x", cache, False))
with self.assertRaises(upstream.NotCachedError):
with self.assertRaises(forgehttp.NotCachedError):
upstream.fetch_file(parse_repo("https://github.com/o/n"), "abc", "a.c", cache)
@@ -531,12 +533,12 @@ class TestCache(unittest.TestCase):
self.dir = self.tmp.name
self.repo = parse_repo("https://github.com/o/n")
self.calls: list[str] = []
self._orig = (upstream.http_text, upstream.http_json)
upstream.http_text = self._fake
upstream.http_json = _no_network
self._orig = (forgehttp.http_text, forgehttp.http_json)
forgehttp.http_text = self._fake
forgehttp.http_json = _no_network
def tearDown(self):
upstream.http_text, upstream.http_json = self._orig
forgehttp.http_text, forgehttp.http_json = self._orig
self.tmp.cleanup()
def _fake(self, url: str) -> str | None:
@@ -562,7 +564,7 @@ class TestCache(unittest.TestCase):
def test_offline_miss_is_not_absence(self):
# Returning None made profile_sync report an existing file as GONE.
with self.assertRaises(upstream.NotCachedError):
with self.assertRaises(forgehttp.NotCachedError):
upstream.fetch_file(self.repo, "abc", "a.c", self.dir, offline=True)
self.assertEqual(self.calls, [])
@@ -585,7 +587,7 @@ class TestCache(unittest.TestCase):
self.assertEqual(self.calls, [])
def test_missing_file_is_cached_as_absent(self):
upstream.http_text = lambda url: None
forgehttp.http_text = lambda url: None
self.assertIsNone(upstream.fetch_file(self.repo, "abc", "gone.c", self.dir))
self.assertIsNone(
upstream.fetch_file(self.repo, "abc", "gone.c", self.dir, offline=True)
@@ -618,12 +620,12 @@ class TestRevisions(unittest.TestCase):
self.repo = parse_repo("https://github.com/o/n")
self.responses: dict[str, object] = {}
self.calls: list[str] = []
self._orig = (upstream.http_json, upstream.http_text)
upstream.http_json = self._fake
upstream.http_text = _no_network
self._orig = (forgehttp.http_json, forgehttp.http_text)
forgehttp.http_json = self._fake
forgehttp.http_text = _no_network
def tearDown(self):
upstream.http_json, upstream.http_text = self._orig
forgehttp.http_json, forgehttp.http_text = self._orig
self.tmp.cleanup()
def _fake(self, url: str):
@@ -645,7 +647,7 @@ class TestRevisions(unittest.TestCase):
self.assertEqual(len(self.calls), 2)
self.assertIn("sha=main", self.calls[0])
self.assertEqual(os.listdir(self.dir), [])
with self.assertRaises(upstream.NotCachedError):
with self.assertRaises(forgehttp.NotCachedError):
upstream.resolve_head(self.repo, None, offline=True)
def test_resolve_head_gitlab_uses_id(self):
@@ -663,9 +665,9 @@ class TestRevisions(unittest.TestCase):
def test_an_uncached_tip_offline_is_unknown_not_absent(self):
"""xenios-jp/XeniOS was dropped offline, its preview tip never
cached, and its citations were judged against the other repository."""
with self.assertRaises(upstream.NotCachedError):
with self.assertRaises(forgehttp.NotCachedError):
upstream.resolve_head(self.repo, self.dir, offline=True, branch="preview")
with self.assertRaises(upstream.NotCachedError):
with self.assertRaises(forgehttp.NotCachedError):
upstream.resolve_commit_at(self.repo, "2026-03-29", self.dir, offline=True)
self.assertEqual(self.calls, [])
@@ -756,10 +758,10 @@ class TestRevisions(unittest.TestCase):
def test_rate_limit_propagates(self):
def boom(url: str):
raise upstream.RateLimitError("quota")
raise forgehttp.RateLimitError("quota")
upstream.http_json = boom
with self.assertRaises(upstream.RateLimitError):
forgehttp.http_json = boom
with self.assertRaises(forgehttp.RateLimitError):
upstream.resolve_head(self.repo, self.dir)
@@ -770,12 +772,12 @@ class TestCompare(unittest.TestCase):
self.dir = self.tmp.name
self.repo = parse_repo("https://github.com/o/n")
self.payload: object = None
self._orig = (upstream.http_json, upstream.http_text)
upstream.http_json = lambda url: self.payload
upstream.http_text = _no_network
self._orig = (forgehttp.http_json, forgehttp.http_text)
forgehttp.http_json = lambda url: self.payload
forgehttp.http_text = _no_network
def tearDown(self):
upstream.http_json, upstream.http_text = self._orig
forgehttp.http_json, forgehttp.http_text = self._orig
self.tmp.cleanup()
def test_list_directory_reads_one_tree(self):
@@ -792,21 +794,21 @@ class TestCompare(unittest.TestCase):
],
}
upstream.http_json = answer
forgehttp.http_json = answer
self.assertEqual(
upstream.list_directory(self.repo, "abc", "hash/", self.dir), ["a.xml", "b.xml"]
upstreamtree.list_directory(self.repo, "abc", "hash/", self.dir), ["a.xml", "b.xml"]
)
self.assertTrue(seen[0].endswith("/repos/o/n/git/trees/abc:hash"))
# Cached: offline, the same answer without a request.
self.assertEqual(
upstream.list_directory(self.repo, "abc", "hash", self.dir, offline=True),
upstreamtree.list_directory(self.repo, "abc", "hash", self.dir, offline=True),
["a.xml", "b.xml"],
)
self.assertEqual(len(seen), 1)
upstream.http_json = lambda url: {"truncated": True, "tree": []}
self.assertIsNone(upstream.list_directory(self.repo, "def", "hash", self.dir))
forgehttp.http_json = lambda url: {"truncated": True, "tree": []}
self.assertIsNone(upstreamtree.list_directory(self.repo, "def", "hash", self.dir))
gitlab = parse_repo("https://gitlab.com/o/n")
self.assertIsNone(upstream.list_directory(gitlab, "abc", "hash", self.dir))
self.assertIsNone(upstreamtree.list_directory(gitlab, "abc", "hash", self.dir))
def test_renamed_file_carries_previous_path(self):
self.payload = {
@@ -819,14 +821,14 @@ class TestCompare(unittest.TestCase):
{"status": "modified", "filename": "a.c"},
]
}
result = upstream.compare(self.repo, "a", "b", self.dir)
result = upstreamtree.compare(self.repo, "a", "b", self.dir)
self.assertFalse(result.truncated)
self.assertEqual(upstream.find_renamed(result, "old.cpp"), "src/new.cpp")
self.assertEqual(upstreamtree.find_renamed(result, "old.cpp"), "src/new.cpp")
def test_no_rename_returns_none(self):
self.payload = {"files": [{"status": "modified", "filename": "a.c"}]}
result = upstream.compare(self.repo, "a", "b", self.dir)
self.assertIsNone(upstream.find_renamed(result, "old.cpp"))
result = upstreamtree.compare(self.repo, "a", "b", self.dir)
self.assertIsNone(upstreamtree.find_renamed(result, "old.cpp"))
def test_truncated_at_github_cap(self):
self.payload = {
@@ -834,11 +836,11 @@ class TestCompare(unittest.TestCase):
{"status": "modified", "filename": f"f{i}.c"} for i in range(300)
]
}
self.assertTrue(upstream.compare(self.repo, "a", "b", self.dir).truncated)
self.assertTrue(upstreamtree.compare(self.repo, "a", "b", self.dir).truncated)
def test_missing_comparison_is_empty_and_truncated(self):
self.payload = None
result = upstream.compare(self.repo, "a", "b", self.dir)
result = upstreamtree.compare(self.repo, "a", "b", self.dir)
self.assertEqual(result.files, [])
self.assertTrue(result.truncated)
@@ -855,8 +857,8 @@ class TestCompare(unittest.TestCase):
}
]
}
result = upstream.compare(repo, "a", "b", self.dir)
self.assertEqual(upstream.find_renamed(result, "old.c"), "new.c")
result = upstreamtree.compare(repo, "a", "b", self.dir)
self.assertEqual(upstreamtree.find_renamed(result, "old.c"), "new.c")
def test_commits_touching_counts_the_commits_after_the_pin(self):
"""Listing from the pin counted its history: freeintv's pin on HEAD
@@ -874,7 +876,7 @@ class TestCompare(unittest.TestCase):
return value
return listing
upstream.http_json = answer
forgehttp.http_json = answer
self.assertEqual(
upstream.commits_touching(self.repo, "a.c", "base", self.dir, head="tip"), 2
)
@@ -899,7 +901,7 @@ class TestCompare(unittest.TestCase):
return value
return list(listing)
upstream.http_json = answer
forgehttp.http_json = answer
self.assertEqual(upstream.commits_touching(self.repo, "a.c", "base", self.dir), 1)
for cached in (Path(self.dir) / "_api").glob("*.json"):
stale = _os.path.getmtime(cached) - upstream.MOVING_TTL - 1
@@ -918,7 +920,7 @@ class TestCompare(unittest.TestCase):
def answer(url):
return answers[-1]
upstream.http_json = answer
forgehttp.http_json = answer
self.assertIsNone(upstream.tag_commit(self.repo, "v2.0", self.dir))
for cached in (Path(self.dir) / "_api").glob("*.json"):
stale = _os.path.getmtime(cached) - upstream.MOVING_TTL - 1
@@ -939,19 +941,19 @@ class TestGitlabTree(unittest.TestCase):
self.dir = self.tmp.name
self.repo = upstream.parse_repo("https://gitlab.com/g/p")
self.pages: dict[int, object] = {}
self._orig = (upstream.http_json, upstream.http_text)
self._orig = (forgehttp.http_json, forgehttp.http_text)
def fake(url):
page = int(url.rsplit("page=", 1)[1])
payload = self.pages.get(page)
if payload == "boom":
raise upstream.UpstreamError(url)
raise forgehttp.UpstreamError(url)
return payload
upstream.http_json = fake
forgehttp.http_json = fake
def tearDown(self):
upstream.http_json, upstream.http_text = self._orig
forgehttp.http_json, forgehttp.http_text = self._orig
self.tmp.cleanup()
def _blobs(self, *names):
@@ -961,41 +963,41 @@ class TestGitlabTree(unittest.TestCase):
self.pages[1] = self._blobs("src/a.c", "src/b.c") + [
{"type": "tree", "path": "src"}
]
paths, truncated = upstream.list_tree(self.repo, "sha", self.dir)
paths, truncated = upstreamtree.list_tree(self.repo, "sha", self.dir)
self.assertEqual(paths, ["src/a.c", "src/b.c"])
self.assertFalse(truncated)
def test_pages_accumulate_until_a_short_one(self):
self.pages[1] = self._blobs(
*[f"f{i}.c" for i in range(upstream.TREE_PAGE_SIZE)]
*[f"f{i}.c" for i in range(upstreamtree.TREE_PAGE_SIZE)]
)
self.pages[2] = self._blobs("last.c")
paths, truncated = upstream.list_tree(self.repo, "sha", self.dir)
self.assertEqual(len(paths), upstream.TREE_PAGE_SIZE + 1)
paths, truncated = upstreamtree.list_tree(self.repo, "sha", self.dir)
self.assertEqual(len(paths), upstreamtree.TREE_PAGE_SIZE + 1)
self.assertIn("last.c", paths)
self.assertFalse(truncated)
def test_unreadable_page_reports_truncation(self):
self.pages[1] = self._blobs(
*[f"f{i}.c" for i in range(upstream.TREE_PAGE_SIZE)]
*[f"f{i}.c" for i in range(upstreamtree.TREE_PAGE_SIZE)]
)
self.pages[2] = None
paths, truncated = upstream.list_tree(self.repo, "sha", self.dir)
self.assertEqual(len(paths), upstream.TREE_PAGE_SIZE)
paths, truncated = upstreamtree.list_tree(self.repo, "sha", self.dir)
self.assertEqual(len(paths), upstreamtree.TREE_PAGE_SIZE)
self.assertTrue(truncated)
def test_gitlinks_of_a_truncated_listing_raise(self):
"""A lost page read as "no submodule there"."""
self.pages[1] = [{"type": "commit", "path": "core", "id": "c" * 40}] + self._blobs(
*[f"f{i}.c" for i in range(upstream.TREE_PAGE_SIZE - 1)]
*[f"f{i}.c" for i in range(upstreamtree.TREE_PAGE_SIZE - 1)]
)
self.pages[2] = None
with self.assertRaises(upstream.TruncatedListingError):
upstream.list_gitlinks(self.repo, "sha", self.dir)
with self.assertRaises(forgehttp.TruncatedListingError):
upstreamtree.list_gitlinks(self.repo, "sha", self.dir)
def test_gitlinks_of_a_whole_listing(self):
self.pages[1] = [{"type": "commit", "path": "core", "id": "c" * 40}]
self.assertEqual(upstream.list_gitlinks(self.repo, "sha", self.dir), {"core": "c" * 40})
self.assertEqual(upstreamtree.list_gitlinks(self.repo, "sha", self.dir), {"core": "c" * 40})
@tests.ONLINE
@@ -1016,7 +1018,7 @@ class TestGiteaCommitAt(unittest.TestCase):
self.tmp = tempfile.TemporaryDirectory()
self.addCleanup(self.tmp.cleanup)
self.urls: list[str] = []
original = upstream.http_json
original = forgehttp.http_json
def fake(url):
self.urls.append(url)
@@ -1024,8 +1026,8 @@ class TestGiteaCommitAt(unittest.TestCase):
page = int(url.rsplit("page=", 1)[1])
return self.PAGES.get(page, [])
upstream.http_json = fake
self.addCleanup(setattr, upstream, "http_json", original)
forgehttp.http_json = fake
self.addCleanup(setattr, forgehttp, "http_json", original)
def test_the_first_commit_by_the_cutoff(self):
repo = parse_repo("https://codeberg.org/iyzsong/gam4980")
@@ -1055,7 +1057,7 @@ class TestCurrentSlug(unittest.TestCase):
},
}
with tempfile.TemporaryDirectory() as tmp, \
mock.patch.object(upstream, "http_json", side_effect=answers.get):
mock.patch.object(forgehttp, "http_json", side_effect=answers.get):
github = parse_repo("https://github.com/AloysHF/NicaiEmu")
gitlab = parse_repo("https://gitlab.com/g/sub/p")
self.assertEqual(upstream.current_slug(github, tmp), "AloysHF/CoolbarEmu")
@@ -1095,10 +1097,10 @@ class TestNewestTag(unittest.TestCase):
class TestNamedTagCommit(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
self.saved = upstream.http_json
self.saved = forgehttp.http_json
def tearDown(self):
upstream.http_json = self.saved
forgehttp.http_json = self.saved
self.tmp.cleanup()
def test_gitlab_tag_is_asked_by_name(self):
@@ -1108,7 +1110,7 @@ class TestNamedTagCommit(unittest.TestCase):
asked.append(url)
return {"name": "1.2.35", "commit": {"id": "c74fc36"}}
upstream.http_json = answer
forgehttp.http_json = answer
repo = parse_repo("https://gitlab.com/jengun/sdltrs")
self.assertEqual(upstream.tag_commit(repo, "1.2.35", self.tmp.name), "c74fc36")
self.assertTrue(asked[0].endswith("/repository/tags/1.2.35"))
@@ -1118,10 +1120,10 @@ class TestNamedTagCommit(unittest.TestCase):
class TestForkBase(unittest.TestCase):
def setUp(self):
self.tmp = tempfile.TemporaryDirectory()
self.saved = upstream.http_json
self.saved = forgehttp.http_json
def tearDown(self):
upstream.http_json = self.saved
forgehttp.http_json = self.saved
self.tmp.cleanup()
def test_the_merge_base_github_names(self):
@@ -1131,15 +1133,15 @@ class TestForkBase(unittest.TestCase):
asked.append(url)
return {"merge_base_commit": {"sha": "base"}, "status": "diverged"}
upstream.http_json = answer
forgehttp.http_json = answer
up, fork = make_repo("github.com", "o", "up"), make_repo("github.com", "f", "port")
self.assertEqual(upstream.fork_base(up, "tip", fork, "head", self.tmp.name), "base")
self.assertEqual(upstreamtree.fork_base(up, "tip", fork, "head", self.tmp.name), "base")
self.assertTrue(asked[0].endswith("/repos/o/up/compare/tip...f:port:head"))
def test_no_network_is_none(self):
upstream.http_json = lambda url: None
forgehttp.http_json = lambda url: None
up, fork = make_repo("github.com", "o", "up"), make_repo("github.com", "f", "port")
self.assertIsNone(upstream.fork_base(up, "tip", fork, "head", self.tmp.name))
self.assertIsNone(upstreamtree.fork_base(up, "tip", fork, "head", self.tmp.name))
def _tarball(files: dict[str, str]) -> bytes:
@@ -1173,43 +1175,43 @@ class TestGitlabDirectoryArchive(unittest.TestCase):
def test_files_land_in_the_cache_fetch_file_reads(self):
calls = []
with mock.patch.object(upstream, "fetch_body", side_effect=lambda url: calls.append(url) or self.body):
held = upstream.cache_gitlab_directory(self.repo, "abc", "sys", self.tmp.name)
with mock.patch.object(forgehttp, "fetch_body", side_effect=lambda url: calls.append(url) or self.body):
held = upstreamtree.cache_gitlab_directory(self.repo, "abc", "sys", self.tmp.name)
self.assertEqual(held, {"sys/a/system.ini", "sys/b/system.ini"})
self.assertEqual(len(calls), 1)
self.assertIn("archive.tar.gz?sha=abc&path=sys", calls[0])
with mock.patch.object(upstream, "http_text", side_effect=_no_network):
with mock.patch.object(forgehttp, "http_text", side_effect=_no_network):
lines = upstream.fetch_file(self.repo, "abc", "sys/b/system.ini", self.tmp.name, offline=True)
self.assertEqual(lines, ["[core.x]"])
def test_a_second_run_reads_the_index_offline(self):
with mock.patch.object(upstream, "fetch_body", return_value=self.body):
upstream.cache_gitlab_directory(self.repo, "abc", "sys", self.tmp.name)
with mock.patch.object(upstream, "fetch_body", side_effect=_no_network):
held = upstream.cache_gitlab_directory(self.repo, "abc", "sys", self.tmp.name, offline=True)
with mock.patch.object(forgehttp, "fetch_body", return_value=self.body):
upstreamtree.cache_gitlab_directory(self.repo, "abc", "sys", self.tmp.name)
with mock.patch.object(forgehttp, "fetch_body", side_effect=_no_network):
held = upstreamtree.cache_gitlab_directory(self.repo, "abc", "sys", self.tmp.name, offline=True)
self.assertEqual(held, {"sys/a/system.ini", "sys/b/system.ini"})
def test_offline_without_index_knows_nothing(self):
with mock.patch.object(upstream, "fetch_body", side_effect=_no_network):
self.assertIsNone(upstream.cache_gitlab_directory(self.repo, "abc", "sys", self.tmp.name, offline=True))
with mock.patch.object(forgehttp, "fetch_body", side_effect=_no_network):
self.assertIsNone(upstreamtree.cache_gitlab_directory(self.repo, "abc", "sys", self.tmp.name, offline=True))
def test_other_forges_are_left_to_per_file_reads(self):
github = parse_repo("https://github.com/o/r")
with mock.patch.object(upstream, "fetch_body", side_effect=_no_network):
self.assertIsNone(upstream.cache_gitlab_directory(github, "abc", "sys", self.tmp.name))
with mock.patch.object(forgehttp, "fetch_body", side_effect=_no_network):
self.assertIsNone(upstreamtree.cache_gitlab_directory(github, "abc", "sys", self.tmp.name))
def test_a_refused_api_falls_back_to_git(self):
refused = upstream.RateLimitError("429", "gitlab.com")
with mock.patch.object(upstream, "fetch_body", side_effect=refused), \
mock.patch.object(upstream, "_sparse_git_files", return_value={"sys/a/system.ini": "x"}) as git:
held = upstream.cache_gitlab_directory(self.repo, "abc", "sys", self.tmp.name)
refused = forgehttp.RateLimitError("429", "gitlab.com")
with mock.patch.object(forgehttp, "fetch_body", side_effect=refused), \
mock.patch.object(upstreamtree, "_sparse_git_files", return_value={"sys/a/system.ini": "x"}) as git:
held = upstreamtree.cache_gitlab_directory(self.repo, "abc", "sys", self.tmp.name)
self.assertEqual(held, {"sys/a/system.ini"})
git.assert_called_once()
def test_an_empty_archive_is_an_error_not_an_empty_directory(self):
with mock.patch.object(upstream, "fetch_body", return_value=_tarball({"p/other/x": "y"})), \
self.assertRaises(upstream.UpstreamError):
upstream.cache_gitlab_directory(self.repo, "abc", "sys", self.tmp.name)
with mock.patch.object(forgehttp, "fetch_body", return_value=_tarball({"p/other/x": "y"})), \
self.assertRaises(forgehttp.UpstreamError):
upstreamtree.cache_gitlab_directory(self.repo, "abc", "sys", self.tmp.name)
if __name__ == "__main__":
+3 -2
View File
@@ -27,6 +27,7 @@ import profile_sync
from profiling import resolver
from profiling import yamledit
from core import upstream
from core import upstreamtree
from profiling import versionbasis
from model.profilerepos import pin_field
from model.profiles import load_emulator_profiles
@@ -293,7 +294,7 @@ class TheVersionRepositoryIsTheBasisRepository(unittest.TestCase):
with mock.patch.object(upstream, "latest_release", return_value=None), \
mock.patch.object(upstream, "newest_tag", return_value=None), \
mock.patch.object(upstream, "tag_commit", side_effect=tag_commit), \
mock.patch.object(upstream, "ancestry", return_value=(3, 0)) as ancestry:
mock.patch.object(upstreamtree, "ancestry", return_value=(3, 0)) as ancestry:
profiling_run._attach_version(args, dict(self.PROFILE, core_version="v1"), report)
self.assertEqual(set(asked), {"o/up"})
self.assertEqual(report.version.tag_commit, "uptag")
@@ -334,7 +335,7 @@ class TheTagCoreVersionNames(unittest.TestCase):
return_value=upstream.Release("2.10.0", "2026-11-01", False)), \
mock.patch.object(upstream, "newest_tag", return_value="2.10.0"), \
mock.patch.object(upstream, "tag_commit", side_effect=tag_commit), \
mock.patch.object(upstream, "ancestry", side_effect=ancestry):
mock.patch.object(upstreamtree, "ancestry", side_effect=ancestry):
profiling_run._attach_version(args, profile, report)
return report, asked