"""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]