CI / test (push) Canceled after 0s
The migrator was fully synchronous — every HTTP round-trip and git op serialized over one blocking client, and a stalled git push could hang it forever. Overlap the independent phases and bound the slow / memory-heavy paths. - clients: ApiClient is now thread-safe (per-thread httpx.Client) so labels, milestones, Pass-B comments, and release assets overlap via parallel(); --concurrency sizes it (default 8). Pass A issue/PR creation stays serial — entities are created in source-number order so the number map resolves forward cross-references. - releases: stream assets through a spooled temp file instead of buffering each whole into memory; upload them concurrently. - reliability: per-op --git-timeout (was unbounded hangs), a circuit breaker that aborts on a degraded target, jittered retry backoff, and a bulk timeout for large asset transfers. - round-trips: set an issue's milestone in the create body; batch the deleted-branch PR-head git push and refs/pull/* pruning. - fix: raw_get_stream 4xx/5xx raised AttributeError (resp.read().text on bytes) instead of ApiError — now decodes. Wrap mirror git ops in try/finally so tokenized remote URLs are scrubbed even on timeout. - refactor: drop the typer dependency — the CLI is now stdlib argparse (same subcommands, flags, and env vars); remove dead code surfaced by a whole-repo audit (has_lfs, name_map, unused owner_repo param, stored-but-unread _base_url). - ci: enable the uv download cache. Tests cover parallel ordering, the circuit breaker, and the streamed 4xx path. CHANGELOG updated; the runtime dependency is now just httpx.
140 lines
4.6 KiB
Python
140 lines
4.6 KiB
Python
"""Tests for the API client (pagination + helpers) using a mock transport.
|
|
|
|
No network: httpx.MockTransport answers all requests deterministically.
|
|
"""
|
|
|
|
import httpx
|
|
import pytest
|
|
|
|
from codeberg_to_gitea_migrator.clients import ApiClient, ApiError, CircuitOpenError, parallel
|
|
|
|
|
|
def _client(handler) -> ApiClient:
|
|
return ApiClient("https://example.com", "tok", transport=httpx.MockTransport(handler))
|
|
|
|
|
|
def test_paged_follows_pages_until_short_batch() -> None:
|
|
pages = {
|
|
1: [{"id": i} for i in range(50)],
|
|
2: [{"id": i} for i in range(50, 70)], # < limit → stop
|
|
}
|
|
|
|
def handler(request: httpx.Request) -> httpx.Response:
|
|
page = int(request.url.params["page"])
|
|
return httpx.Response(200, json=pages.get(page, []))
|
|
|
|
with _client(handler) as c:
|
|
items = c.get_all("/repos/o/r/labels")
|
|
assert len(items) == 70
|
|
assert items[0]["id"] == 0
|
|
assert items[-1]["id"] == 69
|
|
|
|
|
|
def test_get_drops_none_params_and_stringifies_bools() -> None:
|
|
seen = {}
|
|
|
|
def handler(request: httpx.Request) -> httpx.Response:
|
|
seen["params"] = dict(request.url.params)
|
|
return httpx.Response(200, json={"ok": True})
|
|
|
|
with _client(handler) as c:
|
|
c.get("/repos/o/r", state=None, private=True, draft=False, name="x")
|
|
assert seen["params"] == {"private": "true", "draft": "false", "name": "x"}
|
|
|
|
|
|
def test_raises_on_4xx() -> None:
|
|
def handler(request: httpx.Request) -> httpx.Response:
|
|
return httpx.Response(404, text="not found")
|
|
|
|
with _client(handler) as c:
|
|
with pytest.raises(ApiError) as exc_info:
|
|
c.get("/repos/o/r/missing")
|
|
assert exc_info.value.status == 404
|
|
|
|
|
|
def test_post_sends_json_body() -> None:
|
|
seen = {}
|
|
|
|
def handler(request: httpx.Request) -> httpx.Response:
|
|
seen["body"] = request.read().decode()
|
|
return httpx.Response(201, json={"id": 7})
|
|
|
|
with _client(handler) as c:
|
|
result = c.post("/repos/o/r/issues", body={"title": "x"})
|
|
assert result == {"id": 7}
|
|
assert '"title":"x"' in seen["body"]
|
|
|
|
|
|
def test_raw_get_stream_returns_downloaded_bytes() -> None:
|
|
payload = b"binary-asset-bytes"
|
|
|
|
def handler(request: httpx.Request) -> httpx.Response:
|
|
return httpx.Response(200, content=payload)
|
|
|
|
with _client(handler) as c:
|
|
with c.raw_get_stream("/repos/o/r/releases/1/assets/9") as f:
|
|
assert f.read() == payload
|
|
|
|
|
|
def test_raw_get_stream_4xx_raises_apierror_not_attributeerror() -> None:
|
|
# Regression: the streamed 4xx path used resp.read().text on bytes, raising
|
|
# AttributeError instead of the intended ApiError on a missing/inaccessible
|
|
# asset.
|
|
def handler(request: httpx.Request) -> httpx.Response:
|
|
return httpx.Response(404, content=b"no such asset")
|
|
|
|
with _client(handler) as c:
|
|
with pytest.raises(ApiError) as exc_info:
|
|
with c.raw_get_stream("/repos/o/r/releases/1/assets/9"):
|
|
pass
|
|
assert exc_info.value.status == 404
|
|
|
|
|
|
def test_circuit_breaker_opens_then_aborts(monkeypatch) -> None:
|
|
monkeypatch.setattr("time.sleep", lambda _s: None) # no real backoff in the test
|
|
|
|
def handler(request: httpx.Request) -> httpx.Response:
|
|
return httpx.Response(503, text="down")
|
|
|
|
c = ApiClient(
|
|
"https://example.com",
|
|
"tok",
|
|
transport=httpx.MockTransport(handler),
|
|
max_retries=0,
|
|
fail_fast=3,
|
|
)
|
|
with c:
|
|
# First two 503s exhaust and return ApiError (counter < 3)...
|
|
for _ in range(2):
|
|
with pytest.raises(ApiError):
|
|
c.get("/x")
|
|
# ...the third consecutive failure trips the breaker.
|
|
with pytest.raises(CircuitOpenError):
|
|
c.get("/x")
|
|
# Now open → aborts immediately, without issuing a request.
|
|
with pytest.raises(CircuitOpenError):
|
|
c.get("/x")
|
|
|
|
|
|
def test_parallel_preserves_input_order() -> None:
|
|
def handler(request: httpx.Request) -> httpx.Response:
|
|
return httpx.Response(200, json={"id": int(request.url.params["x"])})
|
|
|
|
with _client(handler) as c:
|
|
items = list(range(12))
|
|
out = parallel(items, lambda i: c.get("/x", x=i)["id"], workers=4)
|
|
assert out == items
|
|
|
|
|
|
def test_parallel_serial_when_workers_one() -> None:
|
|
calls: list[int] = []
|
|
|
|
def handler(request: httpx.Request) -> httpx.Response:
|
|
calls.append(int(request.url.params["x"]))
|
|
return httpx.Response(200, json={"ok": True})
|
|
|
|
with _client(handler) as c:
|
|
parallel([3, 2, 1], lambda i: c.get("/x", x=i), workers=1)
|
|
# Serial path runs in input order; a thread pool would not guarantee it.
|
|
assert calls == [3, 2, 1]
|