"""The git-mirror procedure's ordering invariants. Driven through a recording fake of the GitRunner exec callable (no git binary, no network). The fake records command intent only — ``auth.url``, never ``auth.token`` — so the procedure's correctness (its command *sequence* and which forge each step authenticates against) is locked without a credential ever reaching a fixture. """ from __future__ import annotations import subprocess from codeberg_to_gitea_migrator.git import GitError from codeberg_to_gitea_migrator.mirror import mirror_repo SRC_URL = "https://codeberg.org/o/r.git" TGT_URL = "https://git.babylondreams.de/o/r.git" def _ok(stdout: str = "") -> subprocess.CompletedProcess: return subprocess.CompletedProcess(args=[], returncode=0, stdout=stdout, stderr="") class FakeExec: """Recording exec: (cmd, stdin, auth_url). Synthesizes for-each-ref output.""" def __init__( self, *, pull_heads: dict[int, str] | None = None, lfs: bool = True, target_exists: bool = False, ): self._pull = dict(pull_heads or {}) self._lfs = lfs self._target_exists = target_exists self.calls: list[tuple[tuple[str, ...], str | None, str | None]] = [] def __call__(self, cmd, *, timeout, stdin, auth): self.calls.append((tuple(cmd), stdin, auth.url if auth else None)) if "for-each-ref" in cmd: if "--format=%(refname) %(objectname)" in cmd: # pull-head capture out = "\n".join(f"refs/pull/{n}/head {s}" for n, s in sorted(self._pull.items())) return _ok(out) return _ok("\n".join(f"refs/pull/{n}/head" for n in sorted(self._pull))) # prune list if "lfs" in cmd and "version" in cmd: if not self._lfs: raise GitError("no git-lfs") return _ok() if "remote" in cmd and "add" in cmd and "target" in cmd and self._target_exists: raise GitError("remote target already exists") return _ok() def cmds(self) -> list[tuple[str, ...]]: return [c for c, _, _ in self.calls] def auth_for(self, *tokens: str) -> str | None: # Exact-token match: a needle must be a whole argv element, so a test's # tmp_path (which embeds the test name — test_puSHes / test_reFETCH) # can't masquerade as the `push`/`fetch` subcommand. return next(au for cmd, _, au in self.calls if all(t in cmd for t in tokens)) def auth_for_substring(self, needle: str) -> str | None: return next(au for cmd, _, au in self.calls if any(needle in t for t in cmd)) def _index(cmds, *tokens) -> int: for i, c in enumerate(cmds): if all(t in c for t in tokens): # exact argv-token membership return i raise AssertionError(f"no call with tokens {tokens}; got {cmds}") def _index_sub(cmds, needle: str) -> int: for i, c in enumerate(cmds): if any(needle in t for t in c): # substring within one argv token return i raise AssertionError(f"no call with substring {needle}; got {cmds}") # --- ordering invariants (story #7) --- def test_ordering_capture_before_prune_before_mirror_before_prhead(tmp_path): fake = FakeExec(pull_heads={1: "aaa", 2: "bbb"}) mirror_repo(SRC_URL, TGT_URL, "stok", "ttok", tmp_path / "w", git_exec=fake) cmds = fake.cmds() i_capture = _index(cmds, "--format=%(refname) %(objectname)") # pull-head capture i_prune = _index(cmds, "update-ref") # the actual prune (batched delete) i_mirror = _index(cmds, "push", "--mirror") i_prhead = _index_sub(cmds, "refs/heads/_pr") # refspec token: :refs/heads/_pr/ assert i_capture < i_prune < i_mirror < i_prhead def test_report_shape_unchanged(tmp_path): fake = FakeExec(pull_heads={1: "aaa", 2: "bbb"}) report = mirror_repo(SRC_URL, TGT_URL, "stok", "ttok", tmp_path / "w", git_exec=fake) assert report["lfs_pushed"] is True assert report["pr_head_branches"] == 2 assert report["bare"].endswith("r.git") def test_no_pull_heads_skips_pr_head_push_and_prune(tmp_path): fake = FakeExec(pull_heads={}) mirror_repo(SRC_URL, TGT_URL, "s", "t", tmp_path / "w", git_exec=fake) cmds = fake.cmds() assert not any(any("refs/heads/_pr" in t for t in c) for c in cmds) assert not any("update-ref" in c for c in cmds) # nothing to prune # --- auth wiring (story #9): fetch=source, push=target, local ref ops=none --- def test_clone_and_fetch_authenticate_as_source(tmp_path): fake = FakeExec() mirror_repo(SRC_URL, TGT_URL, "stok", "ttok", tmp_path / "w", git_exec=fake) assert fake.auth_for("clone", "--mirror") == SRC_URL def test_pushes_authenticate_as_target(tmp_path): fake = FakeExec(pull_heads={1: "aaa"}) mirror_repo(SRC_URL, TGT_URL, "stok", "ttok", tmp_path / "w", git_exec=fake) assert fake.auth_for("push", "--mirror") == TGT_URL assert fake.auth_for_substring("refs/heads/_pr") == TGT_URL def test_local_ref_ops_carry_no_auth(tmp_path): fake = FakeExec(pull_heads={1: "aaa"}) mirror_repo(SRC_URL, TGT_URL, "stok", "ttok", tmp_path / "w", git_exec=fake) # update-ref is a local op; remote set-url/add write a token-free URL. assert fake.auth_for("update-ref") is None assert fake.auth_for("remote", "add", "target") is None def test_refetch_path_authenticates_fetch_as_source(tmp_path): (tmp_path / "w" / "r.git").mkdir(parents=True) # bare exists → re-fetch, not clone fake = FakeExec() mirror_repo(SRC_URL, TGT_URL, "stok", "ttok", tmp_path / "w", git_exec=fake) cmds = fake.cmds() assert not any("clone" in c for c in cmds) assert fake.auth_for("fetch") == SRC_URL def test_lfs_target_remote_is_idempotent_on_rerun(tmp_path): # The bare mirror persists on disk across runs, so on a re-run `remote add # target` fails (already registered). The procedure must fall back to # set-url and stay green — observable behaviour unchanged (spec #9). (tmp_path / "w" / "r.git").mkdir(parents=True) # bare exists → re-fetch path fake = FakeExec(target_exists=True) report = mirror_repo(SRC_URL, TGT_URL, "stok", "ttok", tmp_path / "w", git_exec=fake) cmds = fake.cmds() assert any("remote" in c and "add" in c and "target" in c for c in cmds) assert any("remote" in c and "set-url" in c and "target" in c for c in cmds) assert report["lfs_pushed"] is True # --- LFS: probe gates fetch+push; missing binary skips gracefully (story #4) --- def test_missing_git_lfs_skips_lfs_ops(tmp_path): fake = FakeExec(pull_heads={1: "aaa"}, lfs=False) report = mirror_repo(SRC_URL, TGT_URL, "s", "t", tmp_path / "w", git_exec=fake) lfs_calls = [c for c in fake.cmds() if "lfs" in c] assert lfs_calls == [("git", "lfs", "version")] # probe only; no fetch/push assert report["lfs_pushed"] is False def test_lfs_fetch_authenticates_as_source_push_as_target(tmp_path): fake = FakeExec(pull_heads={1: "aaa"}) mirror_repo(SRC_URL, TGT_URL, "stok", "ttok", tmp_path / "w", git_exec=fake) assert fake.auth_for("lfs", "fetch") == SRC_URL assert fake.auth_for("lfs", "push") == TGT_URL