Files
roboco/tests/unit/services/test_git_env_sync_fallback.py
96401f4c10 feat(forge): Phases 2+2.1+3 — Gitea + GitLab providers, per-call routing, local-merge fallback (#575)
* feat(forge): Phase 2 — Gitea provider, per-call routing, host registry

Gitea support lands behind the Phase-1 seam:

- GiteaProvider (services/forge/gitea.py): Gitea v1 transport addressed
  by instance host (api base from the project's git_url). Where Gitea's
  wire contract diverges from GitHub's, the provider adapts responses
  back into the shapes GitService already classifies (ShapedResponse):
  `token` auth scheme, duplicate-PR 409→422 with the "already exists"
  text GitService keys on, commit statuses reshaped into check_runs /
  workflow_runs envelopes, APPROVE→APPROVED review mapping, Do-keyed
  POST merge, merge-method repo keys, label-color '#' prefix,
  client-side head/base PR filtering. Deliberate postures per the spec:
  zero-workflows fail-open (statuses-free repo → no_ci_configured) and
  merge_branch as a shaped 501 (env-sync cascade lands on missing_ref;
  the shared local-git fallback is Phase-2.1).
- ForgeRouter (services/forge/router.py): GitService._forge now routes
  per call from RepoRef.host — every existing call site unchanged in
  shape. RepoRef gains an optional host; _parse_git_url returns the
  host-stamped ref and it is threaded through GitService/release
  executor instead of being rebuilt from strings (helpers re-signatured
  to take RepoRef).
- Host registry (services/forge/registry.py): in-memory host→provider
  map, self-healing — ProjectService.get/get_by_slug re-register on
  every read; provider_for resolves gitea projects by git_url host.
- Registration validation now accepts git_provider="gitea"; GitLab
  remains recognized-but-rejected. Panel: the read-only Forge badge
  becomes a real picker (Auto-detect / GitHub-GHE / Gitea / GitLab
  disabled).

Plain git (clone/fetch/push) needs no changes — the Basic-auth
extraheader works on Gitea unchanged. Gates: mypy 392 files, xenon A,
full unit suite 6356 green, integration suite 2257 green.

* feat(forge): live-Gitea contract suite + scheme support + slash-safe refs

Hardening from running the provider against a real dockerized Gitea
1.22.6 (the spec's Phase-2 contract suite, now committed as the
env-gated tests/e2e_smoke/test_gitea_live.py — self-seeding: creates its
own repo, pushes real commits, and drives PR open → duplicate reshape →
list/filter → diff → review → labels → commit-status CI reshapes →
squash merge → branch delete → release, plus a live verification of the
x-access-token Basic-auth git-CLI claim).

Two real findings fixed:
- Branch refs weren't URL-encoded — every RoboCo branch carries slashes
  (feature/backend/...), and Gitea's router 404s on the extra path
  segments. list_ci_runs + delete_branch_ref now quote the ref
  (regression-pinned in the unit suite).
- The API base hardcoded https; a LAN instance serving plain http is a
  real deployment shape. GiteaProvider gains a scheme (recorded per host
  by the registry from the project's git_url).

ShapedResponse moves to forge/shaping.py (shared by the upcoming GitLab
transport, which needs its text override for diff reassembly).

* feat(forge): Phase 3 GitLab provider + Phase 2.1 local-merge fallback

GitLabProvider (services/forge/gitlab.py): GitLab v4 transport addressed
by host+scheme, subgroup-safe (the MR project path packs into
RepoRef.owner, URL-encoded per call). Adapters translate MR semantics
into the GitHub shapes GitService classifies: iid→number,
source/target_branch→head/base with a merged bool, per-file diffs
reassembled into unified-diff text (ShapedResponse text override,
3-page cap), approve-vs-note review routing (GitLab has no
request-changes verb), pipelines/statuses reshaped into
workflow_runs/check_runs, merge-method repo-key mapping, duplicate-MR
409→422. Reviewer mirroring is skipped (needs numeric ids RoboCo
doesn't store); provisioning stays Phase 4. gitlab.com now auto-detects
at registration like github.com; self-hosted GitLab sets the provider
explicitly (panel picker enabled).

Phase 2.1: neither Gitea nor GitLab has GitHub's server-side merges
API — their merge_branch returns a shaped 501 and
GitService.sync_env_branch now runs the shared local-git fallback
(_local_merge_branch: throwaway clone → ancestor check → merge → push;
a conflict aborts with the remote untouched; same status vocabulary as
the merges-API path).

Also aligns the whole tree with the full gate's tests/-scoped mypy
(provider-test responder typing, e2e_smoke's stale owner/repo shapes).
Gates: mypy 1229 files clean, xenon A, unit suite 6393 green, forge
suites 85 green, panel typecheck/lint clean.

---------

Co-authored-by: Renn F <rennf93@users.noreply.github.com>
2026-07-19 08:12:34 +02:00

134 lines
4.2 KiB
Python

"""The env-sync local-git merge fallback (forge Phase 2.1): a provider's
shaped 501 routes sync_env_branch through a throwaway clone→merge→push, with
the same status vocabulary the merges-API path produces.
"""
from __future__ import annotations
from types import SimpleNamespace
from typing import TYPE_CHECKING, Any
from unittest.mock import AsyncMock, MagicMock
import pytest
import roboco.services.git as git_module
from roboco.services.git import GitService
if TYPE_CHECKING:
from pathlib import Path
def _bind(svc: GitService, name: str, value: object) -> None:
"""Stub without tripping mypy's method-assign check (test_git.py idiom)."""
setattr(svc, name, value)
def _service() -> GitService:
svc = GitService.__new__(GitService)
_bind(svc, "log", MagicMock())
return svc
def _result(returncode: int = 0, stdout: str = "") -> SimpleNamespace:
return SimpleNamespace(returncode=returncode, stdout=stdout, stderr="")
def _scripted_run_git(
outcomes: dict[str, SimpleNamespace],
) -> tuple[AsyncMock, list[str]]:
"""Route each _run_git call by its first meaningful arg; record verbs."""
verbs: list[str] = []
async def _run(_workspace: Path, args: list[str], **_kw: Any) -> SimpleNamespace:
verb = args[0] if args[0] != "merge-base" else "merge-base"
verbs.append(verb)
return outcomes.get(verb, _result())
return AsyncMock(side_effect=_run), verbs
@pytest.mark.asyncio
async def test_clean_merge_pushes_and_reports_sha() -> None:
svc = _service()
# merge-base non-zero = not an ancestor → real merge happens.
outcomes = {
"merge-base": _result(1),
"rev-parse": _result(0, "abc123\n"),
}
run, verbs = _scripted_run_git(outcomes)
_bind(svc, "_run_git", run)
status = await svc._local_merge_branch("https://g/x/y.git", "tok", "stag", "main")
assert status == {"status": "merged", "sha": "abc123"}
assert verbs[0] == "clone"
assert "merge" in verbs
assert "push" in verbs
@pytest.mark.asyncio
async def test_already_ancestor_short_circuits() -> None:
svc = _service()
run, verbs = _scripted_run_git({"merge-base": _result(0)})
_bind(svc, "_run_git", run)
status = await svc._local_merge_branch("https://g/x/y.git", "tok", "stag", "main")
assert status == {"status": "already_ancestor"}
assert "merge" not in verbs
assert "push" not in verbs
@pytest.mark.asyncio
async def test_merge_conflict_never_pushes() -> None:
svc = _service()
run, verbs = _scripted_run_git(
{"merge-base": _result(1), "merge": _result(1, "CONFLICT")}
)
_bind(svc, "_run_git", run)
status = await svc._local_merge_branch("https://g/x/y.git", "tok", "stag", "main")
assert status == {"status": "conflict"}
assert "push" not in verbs
@pytest.mark.asyncio
async def test_missing_branch_maps_to_missing_ref() -> None:
svc = _service()
run, _ = _scripted_run_git({"fetch": _result(128)})
_bind(svc, "_run_git", run)
status = await svc._local_merge_branch("https://g/x/y.git", "tok", "stag", "main")
assert status == {"status": "missing_ref"}
@pytest.mark.asyncio
async def test_sync_env_branch_routes_shaped_501_to_fallback(
monkeypatch: pytest.MonkeyPatch,
) -> None:
svc = _service()
_bind(svc, "session", MagicMock())
project = SimpleNamespace(git_url="https://gitea.example.com/a/b.git")
project_svc = MagicMock(get_by_slug=AsyncMock(return_value=project))
monkeypatch.setattr(git_module, "get_project_service", lambda _s: project_svc)
_bind(svc, "_token_for_project", AsyncMock(return_value="tok"))
_bind(svc, "_parse_git_url", MagicMock(return_value=MagicMock()))
forge = MagicMock(
merge_branch=AsyncMock(
return_value=SimpleNamespace(status_code=501, text="", json=dict)
)
)
monkeypatch.setattr(GitService, "_forge", property(lambda _self: forge))
fallback = AsyncMock(return_value={"status": "merged", "sha": "abc"})
_bind(svc, "_local_merge_branch", fallback)
status = await svc.sync_env_branch("proj", "stag", "main")
assert status == {"status": "merged", "sha": "abc"}
fallback.assert_awaited_once_with(
"https://gitea.example.com/a/b.git", "tok", "stag", "main"
)