"""Phase tests through the Migration seam — no network. Two ``httpx.MockTransport``-backed clients feed a :class:`Migration`, then a phase is called. Tests assert external behaviour — the paths and bodies the target client received, and the resulting number-map state — never phase internals, so they survive an internal refactor of a phase. """ from __future__ import annotations import json import httpx from codeberg_to_gitea_migrator.clients import ApiClient from codeberg_to_gitea_migrator.issues import ( migrate_issues_and_prs, migrate_labels, migrate_milestones, ) from codeberg_to_gitea_migrator.migration import Migration from codeberg_to_gitea_migrator.releases import migrate_releases # -- shared mock-transport harness ---------------------------------------- def _client(handler, base: str = "https://src.example") -> ApiClient: return ApiClient(base, "tok", transport=httpx.MockTransport(handler)) def _wire_path(req: httpx.Request) -> str: """Repo-scoped path the wire saw, minus the client's ``/api/v1`` root. Phase tests assert repo-scoped paths (so an owner↔name transposition fails) without coupling to the client's api-root prefix. """ return req.url.path.removeprefix("/api/v1") def _src(routes: dict[str, object]) -> ApiClient: """Source client serving canned payloads keyed by exact repo-scoped path. A ``bytes`` route is returned as raw content (for streamed asset downloads); anything else is returned as JSON (lists/dicts). Unknown paths → empty list. """ def h(req: httpx.Request) -> httpx.Response: payload = routes.get(_wire_path(req), []) if isinstance(payload, (bytes, bytearray)): return httpx.Response(200, content=payload) return httpx.Response(200, json=payload) return _client(h, base="https://codeberg.org") def _recording_target(overrides: dict | None = None) -> tuple[ApiClient, list[dict]]: """Target client that records every write and returns canned created objects. ``overrides`` maps ``(method, path)`` → ``(status, json)`` for special cases (e.g. a 409 on PR merge). Recorded entries are ``{method, path, body}`` with repo-scoped paths. Creation POSTs return ascending ids/numbers. """ overrides = overrides or {} recorded: list[dict] = [] counters = {"number": 100, "id": 1000} def h(req: httpx.Request) -> httpx.Response: method, path = req.method, _wire_path(req) raw = req.read() try: body: object = json.loads(raw or "null") except ValueError: # multipart asset upload — not JSON body = {"_raw": raw.decode("utf-8", "replace")} recorded.append({"method": method, "path": path, "body": body}) if (method, path) in overrides: status, payload = overrides[(method, path)] return httpx.Response(status, json=payload) if method == "POST" and path in ("/repos/o/r/issues", "/repos/o/r/pulls"): counters["number"] += 1 return httpx.Response(201, json={"number": counters["number"]}) if method == "POST" and path in ( "/repos/o/r/labels", "/repos/o/r/milestones", "/repos/o/r/releases", ): counters["id"] += 1 return httpx.Response(201, json={"id": counters["id"]}) return httpx.Response(200, json={}) return _client(h, base="https://git.babylondreams.de"), recorded def _find(recorded: list[dict], method: str, path: str) -> list[dict]: return [r for r in recorded if r["method"] == method and r["path"] == path] def test_migration_path_and_rewrite_bind_identity_without_io() -> None: src = _client(lambda r: httpx.Response(200, json={}), base="https://codeberg.org") tgt = _client(lambda r: httpx.Response(200, json={}), base="https://git.babylondreams.de") m = Migration(src, tgt, "AlexKucera", "helm") assert m.path() == "/repos/AlexKucera/helm" assert m.path("/issues/5/comments") == "/repos/AlexKucera/helm/issues/5/comments" # rewrite sources the web roots from the bound clients + the bound number map m.numbers.add(289, 2) assert m.rewrite("Fixes #289") == "Fixes #2" assert m.rewrite(None) is None # a fresh migration starts with an empty number map (frozen field, mutable value) fresh = Migration(src, tgt, "o", "r") assert len(fresh.numbers) == 0 # -- labels / milestones ------------------------------------------------ def test_migrate_labels_maps_ids_and_posts_bodies() -> None: labels = [ { "id": 1, "name": "bug", "color": "#cc0000", "description": "defect", "exclusive": False, "is_archived": False, } ] src = _client(lambda r: httpx.Response(200, json=labels), base="https://codeberg.org") recorded: list[tuple[str, str, dict]] = [] def tgt_h(req: httpx.Request) -> httpx.Response: recorded.append((req.method, _wire_path(req), json.loads(req.read() or "null"))) return httpx.Response(201, json={"id": 101}) tgt = _client(tgt_h, base="https://git.babylondreams.de") m = Migration(src, tgt, "o", "r") out = migrate_labels(m, concurrency=1) assert out == {1: 101} assert len(recorded) == 1 method, path, body = recorded[0] assert (method, path) == ("POST", "/repos/o/r/labels") assert body == { "name": "bug", "color": "#cc0000", "description": "defect", "exclusive": False, "is_archived": False, } def test_migrate_milestones_maps_ids_and_passes_due_on() -> None: milestones = [ { "id": 5, "title": "v1", "description": "first", "state": "open", "due_on": "2026-12-31T00:00:00Z", } ] src = _client(lambda r: httpx.Response(200, json=milestones), base="https://codeberg.org") recorded: list[tuple[str, str, dict]] = [] def tgt_h(req: httpx.Request) -> httpx.Response: recorded.append((req.method, _wire_path(req), json.loads(req.read() or "null"))) return httpx.Response(201, json={"id": 51}) tgt = _client(tgt_h, base="https://git.babylondreams.de") m = Migration(src, tgt, "o", "r") out = migrate_milestones(m, concurrency=1) assert out == {5: 51} method, path, body = recorded[0] assert (method, path) == ("POST", "/repos/o/r/milestones") assert body == { "title": "v1", "description": "first", "state": "open", "due_on": "2026-12-31T00:00:00Z", } # -- issues + PRs (two-pass) -------------------------------------------- def test_migrate_issues_and_prs_two_pass_rewrites_refs_and_maps_numbers() -> None: # Source #1 (issue, body refs forward #2) and #2 (open PR); #1 has a comment. src = _src( { "/repos/o/r/issues": [ {"number": 1, "title": "first", "body": "depends on #2", "state": "open"} ], "/repos/o/r/pulls": [ { "number": 2, "title": "second", "body": "", "state": "open", "merged": False, "base": {"ref": "main"}, "head": {"ref": "feature"}, } ], "/repos/o/r/issues/1/comments": [{"body": "also see #2"}], } ) tgt, recorded = _recording_target() m = Migration(src, tgt, "o", "r") migrate_issues_and_prs(m, {}, {}, concurrency=1) # number map built in source-number order during Pass A assert len(m.numbers) == 2 assert m.numbers.get(1) == 101 assert m.numbers.get(2) == 102 # Pass B rewrites #2 → #102 in the issue body and streams the rewritten comment issue_patch = _find(recorded, "PATCH", "/repos/o/r/issues/101") assert any(r["body"]["body"] == "depends on #102" for r in issue_patch) comment_posts = _find(recorded, "POST", "/repos/o/r/issues/101/comments") assert comment_posts and comment_posts[0]["body"]["body"] == "also see #102" def test_migrate_issues_and_prs_sets_closed_state_in_pass_a() -> None: src = _src( { "/repos/o/r/issues": [ {"number": 1, "title": "closed one", "body": "", "state": "closed"} ], "/repos/o/r/pulls": [], "/repos/o/r/issues/1/comments": [], } ) tgt, recorded = _recording_target() m = Migration(src, tgt, "o", "r") migrate_issues_and_prs(m, {}, {}, concurrency=1) # a closed source issue → a state=closed PATCH on the target issue state_patches = [ r for r in _find(recorded, "PATCH", "/repos/o/r/issues/101") if r["body"] == {"state": "closed"} ] assert state_patches def test_migrate_issues_and_prs_merged_pr_attempts_merge_and_tolerates_conflict() -> None: src = _src( { "/repos/o/r/issues": [], "/repos/o/r/pulls": [ { "number": 1, "title": "merged", "body": "", "state": "closed", "merged": True, "base": {"ref": "main"}, "head": {"ref": "feature"}, } ], "/repos/o/r/issues/1/comments": [], } ) # Gitea 409s a historical merge (already in base) — best-effort must tolerate it. tgt, recorded = _recording_target( overrides={("POST", "/repos/o/r/pulls/101/merge"): (409, {"message": "conflict"})} ) m = Migration(src, tgt, "o", "r") migrate_issues_and_prs(m, {}, {}, concurrency=1) # must not raise # the merge was attempted (recorded before the 409 raised), and #1 still mapped assert _find(recorded, "POST", "/repos/o/r/pulls/101/merge") assert m.numbers.get(1) == 101 def test_migrate_issues_and_prs_deleted_branch_head_falls_back_to_pr_ref() -> None: src = _src( { "/repos/o/r/issues": [], "/repos/o/r/pulls": [ { "number": 1, "title": "gone head", "body": "", "state": "open", "merged": False, "base": {"ref": "main"}, "head": {"ref": "refs/pull/1/head"}, } ], "/repos/o/r/issues/1/comments": [], } ) tgt, recorded = _recording_target() m = Migration(src, tgt, "o", "r") migrate_issues_and_prs(m, {}, {}, concurrency=1) pr_creates = _find(recorded, "POST", "/repos/o/r/pulls") assert pr_creates and pr_creates[0]["body"]["head"] == "_pr/1" def test_migrate_issues_and_prs_attaches_mapped_labels_and_pr_milestone() -> None: # an issue carrying a source label, and a PR carrying a milestone — both # per-phase maps (produced by the prior phases) are threaded through the # phase interface, not bound on the handle. src = _src( { "/repos/o/r/issues": [ { "number": 1, "title": "with-label", "body": "", "state": "open", "labels": [{"id": 7, "name": "bug"}], } ], "/repos/o/r/pulls": [ { "number": 2, "title": "with-ms", "body": "", "state": "open", "merged": False, "milestone": {"id": 3}, "base": {"ref": "main"}, "head": {"ref": "feature"}, } ], "/repos/o/r/issues/1/comments": [], } ) tgt, recorded = _recording_target() m = Migration(src, tgt, "o", "r") migrate_issues_and_prs(m, {7: 77}, {3: 33}, concurrency=1) # the source label id 7 is mapped to the target id 77 and attached to issue 101 label_posts = _find(recorded, "POST", "/repos/o/r/issues/101/labels") assert label_posts and label_posts[0]["body"] == {"labels": [77]} # a PR can't carry its milestone in the create body, so it takes a follow-up PATCH pr_ms_patches = [ r for r in _find(recorded, "PATCH", "/repos/o/r/issues/102") if r["body"] == {"milestone": 33} ] assert pr_ms_patches # -- releases (+ assets) ------------------------------------------------ def test_migrate_releases_recreates_rewrites_body_and_reuploads_assets() -> None: src = _src( { "/repos/o/r/releases": [ { "id": 1, "tag_name": "v1", "name": "v1", "body": "see #5", "draft": False, "prerelease": False, "target_commitish": "main", "created_at": "2026-01-01T00:00:00Z", "assets": [{"id": 9, "name": "bin.tar.gz"}], }, { "id": 2, "tag_name": "v0-d", "name": "draft", "body": "", "draft": True, "assets": [], }, ], "/repos/o/r/releases/1/assets/9": b"asset-bytes", } ) tgt, recorded = _recording_target() m = Migration(src, tgt, "o", "r") m.numbers.add(5, 50) # rewrite "see #5" → "see #50" count = migrate_releases(m, concurrency=1) assert count == 1 # the draft is skipped rel_posts = _find(recorded, "POST", "/repos/o/r/releases") assert len(rel_posts) == 1 assert rel_posts[0]["body"]["body"] == "see #50" assert rel_posts[0]["body"]["tag_name"] == "v1" assert rel_posts[0]["body"]["prerelease"] is False # the asset is re-uploaded under the new release id (1001 from the counter) assert _find(recorded, "POST", "/repos/o/r/releases/1001/assets") def test_migrate_releases_404_endpoint_skips_cleanly() -> None: def src_h(req: httpx.Request) -> httpx.Response: return httpx.Response(404, text="releases disabled") src = _client(src_h, base="https://codeberg.org") tgt, recorded = _recording_target() m = Migration(src, tgt, "o", "r") assert migrate_releases(m, concurrency=1) == 0 assert recorded == []