mirror of
https://github.com/Abdess/retroarch_system.git
synced 2026-11-24 18:47:53 -06:00
refactor: route network access through upstream
Branch heads (scrapers, FBNeo import, data directories) resolve through core.upstream.resolve_head, with cache_dir=None to keep nothing under .cache/upstream. Streaming downloads (large files, external pack files, data directory archives, scraper downloads, standalone probe) go through one core.upstream.download: scratch then rename, size cap, retries of a cut stream, a 5xx or a rate limit. The shared rate limit wait reads GoatCounter's X-Rate-Limit-Reset, so site insights, download.py, indexnow and the contributor list use the same retrying client. list_gitlinks raises TruncatedListingError on a partial tree, read from one tree walk shared with list_tree (Forgejo paging included). The Recalbox configs/ listing is paged with the shared page cap.
This commit is contained in:
1 parent
526d7f09c7
commit
8a8fa71fbc
25 files changed
+708
-266
No files matched your search
@@ -17,6 +17,7 @@ import subprocess
|
||||
import sys
|
||||
import tempfile
|
||||
import unittest
|
||||
import urllib.error
|
||||
import zipfile
|
||||
import zlib
|
||||
from pathlib import Path
|
||||
@@ -3409,6 +3410,27 @@ class ContributorsSurviveAFailedRequest(unittest.TestCase):
|
||||
"the section is present but empty",
|
||||
)
|
||||
|
||||
def test_the_contributor_list_is_not_asked_offline(self):
|
||||
from sitegen import readme
|
||||
|
||||
with mock.patch.dict(os.environ, {"RETROBIOS_OFFLINE": "1"}), \
|
||||
mock.patch.object(readme.upstream, "fetch_body",
|
||||
side_effect=AssertionError("network")):
|
||||
self.assertEqual(readme.fetch_contributors(), [])
|
||||
|
||||
def test_contributors_are_read_through_the_retrying_client(self):
|
||||
from sitegen import readme
|
||||
|
||||
answer = json.dumps([
|
||||
{"login": "someone", "type": "User"},
|
||||
{"login": "dependabot[bot]", "type": "Bot"},
|
||||
{"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:
|
||||
self.assertEqual([c["login"] for c in readme.fetch_contributors()], ["someone"])
|
||||
self.assertIn("/contributors", fetch.call_args.args[0])
|
||||
|
||||
|
||||
class APackNameFitsAFileName(unittest.TestCase):
|
||||
"""--system snes joined 23 emulator names and died on ENAMETOOLONG
|
||||
@@ -7578,6 +7600,7 @@ class ExternalDownloadsFollowTheRunPolicy(unittest.TestCase):
|
||||
|
||||
def _response(self, body: bytes):
|
||||
stream = io.BytesIO(body)
|
||||
stream.headers = {}
|
||||
response = mock.MagicMock()
|
||||
response.__enter__.return_value = stream
|
||||
response.__exit__.return_value = False
|
||||
@@ -7587,7 +7610,7 @@ class ExternalDownloadsFollowTheRunPolicy(unittest.TestCase):
|
||||
from resolve import packfiles as packresolve
|
||||
|
||||
with tempfile.TemporaryDirectory() as tmp, \
|
||||
mock.patch.object(packresolve.urllib.request, "urlopen") as urlopen, \
|
||||
mock.patch("urllib.request.urlopen") as urlopen, \
|
||||
contextlib.redirect_stdout(io.StringIO()):
|
||||
ok = packresolve.download_external(self.ENTRY, f"{tmp}/x", offline=True)
|
||||
self.assertFalse(ok)
|
||||
@@ -7600,7 +7623,7 @@ class ExternalDownloadsFollowTheRunPolicy(unittest.TestCase):
|
||||
packresolve.set_offline(True)
|
||||
try:
|
||||
with tempfile.TemporaryDirectory() as tmp, \
|
||||
mock.patch.object(packresolve.urllib.request, "urlopen") as urlopen, \
|
||||
mock.patch("urllib.request.urlopen") as urlopen, \
|
||||
contextlib.redirect_stdout(io.StringIO()):
|
||||
self.assertFalse(packresolve.download_external(self.ENTRY, f"{tmp}/x"))
|
||||
urlopen.assert_not_called()
|
||||
@@ -7612,12 +7635,12 @@ class ExternalDownloadsFollowTheRunPolicy(unittest.TestCase):
|
||||
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
target = Path(tmp) / "x"
|
||||
with mock.patch.object(packresolve.urllib.request, "urlopen",
|
||||
with mock.patch("urllib.request.urlopen",
|
||||
return_value=self._response(b"payload")):
|
||||
self.assertTrue(packresolve.download_external(self.ENTRY, str(target), offline=False))
|
||||
self.assertEqual(target.read_bytes(), b"payload")
|
||||
target.unlink()
|
||||
with mock.patch.object(packresolve.urllib.request, "urlopen",
|
||||
with mock.patch("urllib.request.urlopen",
|
||||
return_value=self._response(b"other")), \
|
||||
contextlib.redirect_stdout(io.StringIO()):
|
||||
self.assertFalse(packresolve.download_external(self.ENTRY, str(target), offline=False))
|
||||
@@ -7636,6 +7659,21 @@ class ExternalDownloadsFollowTheRunPolicy(unittest.TestCase):
|
||||
entry = {**self.ENTRY, "sha1": sha1}
|
||||
self.assertTrue(packresolve.download_external(entry, f"{tmp}/x", offline=False))
|
||||
|
||||
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 resolve import packfiles as packresolve
|
||||
|
||||
refusal = urllib.error.HTTPError(self.ENTRY["source_url"], 503, "busy", {}, None)
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
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):
|
||||
self.assertTrue(packresolve.download_external(self.ENTRY, str(target), offline=False))
|
||||
self.assertEqual(target.read_bytes(), b"payload")
|
||||
self.assertEqual(os.listdir(tmp), ["x"])
|
||||
|
||||
def test_scratch_files_stay_in_the_repository(self):
|
||||
source = script_source("generate_pack.py")
|
||||
self.assertNotIn("def download_external", source)
|
||||
|
||||
@@ -720,6 +720,36 @@ class AProgressBarOnlyOnATerminal(unittest.TestCase):
|
||||
self.assertNotIn("\r", out.getvalue())
|
||||
self.assertEqual(out.getvalue().count("\n"), 1)
|
||||
|
||||
def test_a_cut_stream_is_fetched_again_from_the_start(self):
|
||||
"""One reset midway through a 2 GiB part failed the whole download."""
|
||||
import http.client
|
||||
|
||||
from core import upstream
|
||||
|
||||
class Body(io.BytesIO):
|
||||
headers = {"Content-Length": "6"}
|
||||
|
||||
def __enter__(self):
|
||||
return self
|
||||
|
||||
def __exit__(self, *exc):
|
||||
return False
|
||||
|
||||
class Cut(Body):
|
||||
def read(self, size: int = -1) -> bytes:
|
||||
raise http.client.IncompleteRead(b"pa")
|
||||
|
||||
answers = [Cut(b""), Body(b"packed")]
|
||||
with tempfile.TemporaryDirectory() as directory, \
|
||||
mock.patch.object(download.urllib.request, "urlopen",
|
||||
lambda *a, **k: answers.pop(0)), \
|
||||
mock.patch.object(upstream, "_sleep", lambda _s: None), \
|
||||
contextlib.redirect_stdout(io.StringIO()):
|
||||
target = Path(directory) / "a.zip"
|
||||
download.download_file("https://example.com/a.zip", target, 6, "a.zip ")
|
||||
self.assertEqual(target.read_bytes(), b"packed")
|
||||
self.assertEqual(answers, [])
|
||||
|
||||
|
||||
class TheShellDownloaderSendsTheToken(unittest.TestCase):
|
||||
"""download.py sent GITHUB_TOKEN to the API and download.sh did not, so
|
||||
|
||||
@@ -37,6 +37,9 @@ PAYLOAD_B = b"B" * (256 * 1024)
|
||||
# the CI test job sets RETROBIOS_OFFLINE to keep every other test off the
|
||||
# network, so it is cleared here.
|
||||
_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)
|
||||
|
||||
# The names these tests fetch, registered as .gitignore registers an asset:
|
||||
# a bare name no registered path carries is never asked of the release.
|
||||
@@ -58,15 +61,19 @@ def _test_registry(case: unittest.TestCase) -> None:
|
||||
|
||||
def setUpModule():
|
||||
_ONLINE.start()
|
||||
_NO_PAUSE.start()
|
||||
|
||||
|
||||
def tearDownModule():
|
||||
_NO_PAUSE.stop()
|
||||
_ONLINE.stop()
|
||||
|
||||
|
||||
class _SlowResponse(io.BytesIO):
|
||||
"""Serve a payload in chunks, yielding between them."""
|
||||
|
||||
headers: dict[str, str] = {}
|
||||
|
||||
def __init__(self, data: bytes, barrier: threading.Barrier | None = None):
|
||||
super().__init__(data)
|
||||
self._barrier = barrier
|
||||
@@ -629,16 +636,18 @@ class ReleaseAssetNames(unittest.TestCase):
|
||||
largefiles.fetch_large_file(
|
||||
self.RTCW, dest_dir=cache, registered=self.REGISTERED
|
||||
)
|
||||
# A refused connection is retried: each asset is asked
|
||||
# more than once, and only the assets asked matter here.
|
||||
self.assertEqual(
|
||||
requested,
|
||||
[largefiles.urllib.parse.quote(expected[self.RTCW])],
|
||||
set(requested),
|
||||
{largefiles.urllib.parse.quote(expected[self.RTCW])},
|
||||
)
|
||||
requested.clear()
|
||||
largefiles.fetch_large_file(
|
||||
"pak0.pk3", dest_dir=cache, registered=self.REGISTERED
|
||||
)
|
||||
self.assertEqual(
|
||||
sorted(requested),
|
||||
sorted(set(requested)),
|
||||
sorted(
|
||||
largefiles.urllib.parse.quote(expected[p])
|
||||
for p in (self.ET, self.RTCW)
|
||||
@@ -667,6 +676,8 @@ class ReleaseAssetNames(unittest.TestCase):
|
||||
class _StalledResponse(io.BytesIO):
|
||||
"""Serves one chunk, then the stream stalls."""
|
||||
|
||||
headers: dict[str, str] = {}
|
||||
|
||||
def __init__(self):
|
||||
super().__init__(PAYLOAD_A)
|
||||
self._served = False
|
||||
@@ -702,6 +713,24 @@ class DownloadFailuresAndRevisions(unittest.TestCase):
|
||||
self.assertIsNone(result)
|
||||
self.assertEqual(os.listdir(self.dir), [])
|
||||
|
||||
def test_a_transient_server_error_is_retried(self):
|
||||
"""One 503 from the release CDN dropped the asset from the build."""
|
||||
answers: list = [urllib.error.HTTPError("u", 503, "busy", {}, None), _SlowResponse(PAYLOAD_A)]
|
||||
|
||||
def urlopen(*_args, **_kwargs):
|
||||
answer = answers.pop(0)
|
||||
if isinstance(answer, Exception):
|
||||
raise answer
|
||||
return answer
|
||||
|
||||
largefiles.urllib.request.urlopen = urlopen
|
||||
result = largefiles.fetch_large_file(
|
||||
"big.bin", self.dir, expected_md5=hashlib.md5(PAYLOAD_A).hexdigest(),
|
||||
registered=TEST_REGISTERED,
|
||||
)
|
||||
self.assertIsNotNone(result)
|
||||
self.assertEqual(answers, [])
|
||||
|
||||
def test_another_revision_is_kept_not_evicted(self):
|
||||
cached = Path(self.dir, "PS3UPDAT.PUP")
|
||||
cached.write_bytes(PAYLOAD_A)
|
||||
|
||||
@@ -5579,6 +5579,40 @@ class UpstreamVendoredAsASubmodule(unittest.TestCase):
|
||||
views = self._views({"src-pin": {"deps/zlib": "other"}, "src-head": {}})
|
||||
self.assertEqual(views[1].head, "nesbox-tip")
|
||||
|
||||
def test_a_truncated_port_tree_is_not_read_as_no_submodule(self):
|
||||
"""A partial listing kept nesbox's tip, the commit a bump must not
|
||||
move upstream_commit to."""
|
||||
views = [
|
||||
profiling_repos.RepoView(object(), "src-pin", "src-head", "source_commit", "source"),
|
||||
profiling_repos.RepoView(object(), "sub-old", "nesbox-tip", "upstream_commit", "upstream"),
|
||||
]
|
||||
with mock.patch.object(
|
||||
upstream, "list_gitlinks",
|
||||
side_effect=upstream.TruncatedListingError("tree listing truncated"),
|
||||
), self.assertRaises(upstream.TruncatedListingError):
|
||||
profiling_repos._follow_submodule(views, "cache", True)
|
||||
|
||||
|
||||
class TruncatedGitlinksInTheResolver(unittest.TestCase):
|
||||
"""A read-only report goes on past a partial listing, and says so."""
|
||||
|
||||
def test_the_lost_tree_yields_no_link_and_the_next_is_read(self):
|
||||
from types import SimpleNamespace
|
||||
|
||||
views = [SimpleNamespace(repo="a", pin="p1"), SimpleNamespace(repo="b", pin="p2")]
|
||||
state = SimpleNamespace(views=views, cache_dir="c", offline=True, name="demo")
|
||||
|
||||
def links(repo, sha, *_args):
|
||||
if repo == "a":
|
||||
raise upstream.TruncatedListingError("a@p1: tree listing truncated")
|
||||
return {"sub": "s"}
|
||||
|
||||
with mock.patch.object(upstream, "list_gitlinks", side_effect=links), \
|
||||
contextlib.redirect_stderr(io.StringIO()) as err:
|
||||
found = [list(paths) for paths in resolver._Resolver.gitlinks_in_order(state)]
|
||||
self.assertEqual(found, [[], ["sub"]])
|
||||
self.assertIn("submodule paths unknown", err.getvalue())
|
||||
|
||||
|
||||
class AMirrorOutlivesAGoneSource(unittest.TestCase):
|
||||
"""yuzu's source answers 451. select_views stopped on it and never read
|
||||
|
||||
@@ -38,6 +38,8 @@ def _zip_bytes(files: dict[str, bytes]) -> bytes:
|
||||
|
||||
|
||||
class _Response(io.BytesIO):
|
||||
headers: dict[str, str] = {}
|
||||
|
||||
def __enter__(self):
|
||||
return self
|
||||
|
||||
@@ -466,6 +468,17 @@ class TheRemoteCommitComesFromTheForgeClient(unittest.TestCase):
|
||||
self.assertEqual((sha, len(seen)), ("b" * 40, 2))
|
||||
self.assertEqual(seen[0].get_header("Authorization"), "Bearer SECRET")
|
||||
|
||||
def test_the_answer_is_not_cached(self):
|
||||
from core import upstream
|
||||
|
||||
with mock.patch.object(upstream, "write_cache") as write:
|
||||
sha, _seen = self._resolve(
|
||||
"https://github.com/o/n/archive/{version}.tar.gz", "master",
|
||||
[[{"sha": "c" * 40}]],
|
||||
)
|
||||
self.assertEqual(sha, "c" * 40)
|
||||
write.assert_not_called()
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -28,11 +28,16 @@ class _Response(io.BytesIO):
|
||||
return False
|
||||
|
||||
|
||||
def _is_head(url):
|
||||
# core.upstream.resolve_head lists one commit from the branch.
|
||||
return "/commits?per_page=1" in url
|
||||
|
||||
|
||||
def _opener(failure):
|
||||
def urlopen(req, timeout=0):
|
||||
url = req.full_url
|
||||
if "/commits/" in url:
|
||||
return _Response(json.dumps({"sha": "a" * 40}).encode())
|
||||
if _is_head(url):
|
||||
return _Response(json.dumps([{"sha": "a" * 40}]).encode())
|
||||
if "api.github.com" in url:
|
||||
return _Response(json.dumps(TREE).encode())
|
||||
if "pcsx2" in url and failure is not None:
|
||||
@@ -71,10 +76,27 @@ class ManifestErrors(unittest.TestCase):
|
||||
|
||||
with mock.patch("urllib.request.urlopen", recording):
|
||||
Scraper()._fetch_remote_manifests()
|
||||
reads = [url for url in seen if "/commits/" not in url]
|
||||
reads = [url for url in seen if not _is_head(url)]
|
||||
self.assertTrue(reads)
|
||||
self.assertTrue(all("a" * 40 in url for url in reads), reads)
|
||||
|
||||
def test_the_head_is_read_without_a_cache_write(self):
|
||||
"""The branch head is asked of the forge each scrape and never
|
||||
written to the profile cache under .cache/upstream."""
|
||||
seen = []
|
||||
opener = _opener(None)
|
||||
|
||||
def recording(req, timeout=0):
|
||||
seen.append(req.full_url)
|
||||
return opener(req, timeout)
|
||||
|
||||
with mock.patch("urllib.request.urlopen", recording), \
|
||||
mock.patch("core.upstream.write_cache") as write:
|
||||
scraper = Scraper()
|
||||
self.assertEqual(scraper.revision, "a" * 40)
|
||||
self.assertTrue(any(_is_head(url) for url in seen), seen)
|
||||
write.assert_not_called()
|
||||
|
||||
def test_a_truncated_tree_stops_the_scrape(self):
|
||||
TREE["truncated"] = True
|
||||
self.addCleanup(TREE.pop, "truncated")
|
||||
|
||||
@@ -906,10 +906,12 @@ class FbneoFetchReadsOneRevision(unittest.TestCase):
|
||||
def tearDown(self):
|
||||
self._tmp.cleanup()
|
||||
|
||||
def _head(self, repo: str, branch: str | None = None) -> str:
|
||||
self.calls.append(f"{repo}@{branch}")
|
||||
return "c0ffee"
|
||||
|
||||
def _api(self, url: str) -> object:
|
||||
self.calls.append(url)
|
||||
if "/commits/" in url:
|
||||
return {"sha": "c0ffee"}
|
||||
return [{
|
||||
"type": "file", "name": "Demo.dat",
|
||||
"sha": git_blob_sha(FBNEO_DAT),
|
||||
@@ -927,6 +929,7 @@ class FbneoFetchReadsOneRevision(unittest.TestCase):
|
||||
from scripts.scraper import base_scraper
|
||||
|
||||
with mock.patch.object(self.importer, "_api_json", self._api), \
|
||||
mock.patch.object(self.importer, "fetch_branch_head", self._head), \
|
||||
mock.patch.object(base_scraper, "download", self._download):
|
||||
yield
|
||||
|
||||
@@ -941,11 +944,16 @@ class FbneoFetchReadsOneRevision(unittest.TestCase):
|
||||
target, blobs = self.importer.fetch_pack("fbneo", "v1.0.0.02", self.dir)
|
||||
self.assertEqual(
|
||||
self.calls,
|
||||
[f"{self.importer.FBNEO_API}/commits/v1.0.0.02",
|
||||
["libretro/FBNeo@v1.0.0.02",
|
||||
f"{self.importer.FBNEO_API}/contents/dats?ref=c0ffee"],
|
||||
)
|
||||
self.assertEqual(list(blobs), ["Demo.dat"])
|
||||
|
||||
def test_latest_reads_the_default_branch(self):
|
||||
with self._patched():
|
||||
self.importer.fetch_pack("fbneo", "latest", self.dir)
|
||||
self.assertEqual(self.calls[0], "libretro/FBNeo@None")
|
||||
|
||||
def test_a_revision_import_is_labelled_and_leaves_the_tip_blobs(self):
|
||||
import contextlib
|
||||
import io
|
||||
|
||||
@@ -271,11 +271,40 @@ class AnEmptyRecalboxListingStopsTheTargets(unittest.TestCase):
|
||||
|
||||
scraper = targets.Scraper()
|
||||
with mock.patch.object(scraper, "pinned_revision", lambda _name: "10.1.1"), \
|
||||
mock.patch.object(targets, "fetch_bytes", fetch), \
|
||||
mock.patch.object(recalbox_scraper, "fetch_bytes", fetch), \
|
||||
self.assertRaisesRegex(RuntimeError, "no Recalbox system"):
|
||||
scraper.fetch_targets()
|
||||
|
||||
def test_the_configs_listing_is_read_past_its_first_page(self):
|
||||
"""configs/ was asked for one page of 100 entries: a defconfig past
|
||||
it was a board the targets never listed."""
|
||||
import json
|
||||
from scraper import recalbox_scraper
|
||||
|
||||
asked: list[str] = []
|
||||
|
||||
def fetch(url, data=None, headers=None):
|
||||
asked.append(url)
|
||||
page = int(url.rsplit("page=", 1)[1])
|
||||
if page == 1:
|
||||
return json.dumps([{"name": f"other{i}"} for i in range(100)]).encode()
|
||||
return b'[{"name": "recalbox-rpi5_64_defconfig"}]'
|
||||
|
||||
with mock.patch.object(recalbox_scraper, "fetch_bytes", fetch):
|
||||
names = [item["name"] for item in recalbox_scraper.tree_listing("configs", "10.1.1")]
|
||||
self.assertEqual(len(names), 101)
|
||||
self.assertIn("recalbox-rpi5_64_defconfig", names)
|
||||
self.assertTrue(all("path=configs" in url for url in asked))
|
||||
|
||||
def test_a_listing_past_the_page_cap_raises(self):
|
||||
import json
|
||||
from scraper import recalbox_scraper
|
||||
|
||||
full = json.dumps([{"name": "x"}] * 100).encode()
|
||||
with mock.patch.object(recalbox_scraper, "fetch_bytes", lambda *a, **k: full), \
|
||||
self.assertRaisesRegex(RuntimeError, "page cap"):
|
||||
recalbox_scraper.tree_listing("configs", "10.1.1")
|
||||
|
||||
|
||||
class EveryNamedScraperExists(unittest.TestCase):
|
||||
"""The registry named lakka_targets, a scraper no file defines: a refresh
|
||||
@@ -787,7 +816,11 @@ class UnreadableReleaseStopsTheScrape(unittest.TestCase):
|
||||
return False
|
||||
|
||||
def answer(request, timeout=None):
|
||||
return Answer(json.dumps({"sha": sha}).encode())
|
||||
# A branch head is the first entry of the commit listing
|
||||
# (core.upstream.resolve_head), a release lookup one object.
|
||||
commit = {"sha": sha}
|
||||
listing = "/commits?" in request.full_url
|
||||
return Answer(json.dumps([commit] if listing else commit).encode())
|
||||
|
||||
branch_read = [s for s in self._registry_scrapers() if s not in self.TAG_PINNED]
|
||||
self.assertGreater(len(branch_read), 8)
|
||||
|
||||
@@ -291,7 +291,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.time, "sleep") as sleep, \
|
||||
mock.patch.object(insights.upstream, "_sleep") as sleep, \
|
||||
mock.patch.object(insights.upstream, "_exhausted_hosts", set()), \
|
||||
self.assertRaisesRegex(SystemExit, "2356 s"):
|
||||
insights._get_json("https://retrobios.goatcounter.com/api/v0/stats/hits")
|
||||
sleep.assert_not_called()
|
||||
@@ -304,10 +305,38 @@ 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.time, "sleep") as sleep:
|
||||
mock.patch.object(insights.upstream, "_sleep") as sleep:
|
||||
self.assertEqual(insights._get_json("https://x/api"), {"ok": 1})
|
||||
sleep.assert_called_once_with(2)
|
||||
|
||||
def test_a_server_error_is_asked_again(self) -> None:
|
||||
"""A 502 from GoatCounter ended the run on the first try."""
|
||||
refusal = urllib.error.HTTPError("https://x/api", 502, "Bad Gateway", email.message.Message(),
|
||||
io.BytesIO(b""))
|
||||
answer = mock.MagicMock()
|
||||
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"):
|
||||
self.assertEqual(insights._get_json("https://x/api"), {"ok": 1})
|
||||
|
||||
def test_github_headers_come_from_the_forge_helper(self) -> None:
|
||||
seen: list[dict[str, str]] = []
|
||||
|
||||
def get_json(url: str, headers: dict[str, str] | None = None, body: dict | None = None):
|
||||
seen.append(dict(headers or {}))
|
||||
return [] if "releases" in url else {}
|
||||
|
||||
with mock.patch.object(insights, "github_token", return_value="SECRET"), \
|
||||
mock.patch("core.github.github_token", return_value="SECRET"), \
|
||||
mock.patch.object(insights, "_get_json", get_json):
|
||||
insights.fetch_github()
|
||||
self.assertTrue(seen)
|
||||
for headers in seen:
|
||||
self.assertEqual(headers["Authorization"], "Bearer SECRET")
|
||||
self.assertEqual(headers["Accept"], "application/vnd.github+json")
|
||||
self.assertEqual(headers["User-Agent"], insights.USER_AGENT)
|
||||
|
||||
|
||||
if __name__ == "__main__":
|
||||
unittest.main()
|
||||
@@ -334,6 +334,62 @@ class TestFetchRetry(unittest.TestCase):
|
||||
upstream.fetch_body("https://host/x")
|
||||
self.assertEqual((self.calls, self.slept), (1, []))
|
||||
|
||||
def test_goatcounter_reset_header_is_waited_with_a_second_more(self):
|
||||
import email.message
|
||||
|
||||
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(self.slept, [4.0])
|
||||
|
||||
def test_download_retries_a_cut_stream_and_writes_whole(self):
|
||||
class Cut:
|
||||
def read(self, size: int = -1) -> bytes:
|
||||
raise http.client.IncompleteRead(b"par")
|
||||
|
||||
outcomes: list = [Cut(), _Body(b"payload")]
|
||||
|
||||
def opener(req, timeout=None):
|
||||
body = outcomes.pop(0)
|
||||
body.headers = {"Content-Disposition": "attachment"}
|
||||
return contextlib.nullcontext(body)
|
||||
|
||||
urllib.request.urlopen = opener
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
target = Path(tmp) / "file.bin"
|
||||
served = upstream.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"])
|
||||
self.assertEqual(len(self.slept), 1)
|
||||
|
||||
def test_download_refused_by_its_check_writes_nothing(self):
|
||||
def opener(req, timeout=None):
|
||||
body = _Body(b"payload")
|
||||
body.headers = {}
|
||||
return contextlib.nullcontext(body)
|
||||
|
||||
urllib.request.urlopen = opener
|
||||
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.assertEqual(target.read_bytes(), b"old")
|
||||
self.assertEqual(os.listdir(tmp), ["file.bin"])
|
||||
|
||||
def test_download_past_the_cap_raises_and_leaves_nothing(self):
|
||||
def opener(req, timeout=None):
|
||||
body = _Body(b"x" * 10)
|
||||
body.headers = {}
|
||||
return contextlib.nullcontext(body)
|
||||
|
||||
urllib.request.urlopen = opener
|
||||
with tempfile.TemporaryDirectory() as tmp:
|
||||
with self.assertRaises(ValueError):
|
||||
upstream.download("https://host/f", Path(tmp) / "f", max_bytes=4)
|
||||
self.assertEqual(os.listdir(tmp), [])
|
||||
|
||||
def test_exhausted_github_quota_is_not_waited(self):
|
||||
import email.message
|
||||
|
||||
@@ -535,6 +591,17 @@ class TestRevisions(unittest.TestCase):
|
||||
self.responses["/commits"] = [{"sha": "deadbeef"}]
|
||||
self.assertEqual(upstream.resolve_head(self.repo, self.dir), "deadbeef")
|
||||
|
||||
def test_resolve_head_without_a_cache_keeps_nothing(self):
|
||||
"""A scraper's branch head is asked each time and never cached."""
|
||||
self.responses["/commits"] = [{"sha": "f00d"}]
|
||||
self.assertEqual(upstream.resolve_head(self.repo, None, branch="main"), "f00d")
|
||||
self.assertEqual(upstream.resolve_head(self.repo, None, branch="main"), "f00d")
|
||||
self.assertEqual(len(self.calls), 2)
|
||||
self.assertIn("sha=main", self.calls[0])
|
||||
self.assertEqual(os.listdir(self.dir), [])
|
||||
with self.assertRaises(upstream.NotCachedError):
|
||||
upstream.resolve_head(self.repo, None, offline=True)
|
||||
|
||||
def test_resolve_head_gitlab_uses_id(self):
|
||||
repo = parse_repo("https://gitlab.com/g/p")
|
||||
self.responses["/repository/commits"] = [{"id": "cafe"}]
|
||||
@@ -869,6 +936,19 @@ class TestGitlabTree(unittest.TestCase):
|
||||
self.assertEqual(len(paths), upstream.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)]
|
||||
)
|
||||
self.pages[2] = None
|
||||
with self.assertRaises(upstream.TruncatedListingError):
|
||||
upstream.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})
|
||||
|
||||
|
||||
class TestGiteaCommitAt(unittest.TestCase):
|
||||
"""Gitea and Forgejo ignore `until` and answer with the tip: the date
|
||||
|
||||
Reference in new issue
Block a user