Files
kandev/apps/backend/internal/gitlab/pat_client_test.go
T
João Salavisa 68aeefa296 feat(gitlab): add GitLab integration with MR / discussions support (#861)
* feat(gitlab): add GitLab integration with MR / discussions support

Adds a GitLab integration parallel to the GitHub one: PAT and glab CLI auth,
self-managed host configuration, MR feedback (approvals + discussions +
pipelines), and discussion reply / resolve so agents can address review
comments. The pr skill detects the host from git remote and creates a real
GitLab merge request via glab or REST.

Closes #820

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* refactor(gitlab): address review feedback and tighten lint surface

- Add service_test.go covering ConfigureToken / ClearToken / ConfigureHost.
- Drop speculative MRWatch / TaskMR / ReviewWatch / IssueWatch / preset
  scaffolding that had no migrations or handlers behind it.
- Consolidate /approvals into one round-trip via fetchApprovals.
- Use http.DefaultClient in CheckHost (context already carries the deadline).
- Rename misleading id → configured in ConfigureToken.
- Introduce mrStateOpen constant so the lint goconst rule passes.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* fix(gitlab): address PR review feedback (CodeQL SSRF, races, atomicity)

- connectivity: parse host with url.Parse, validate http/https scheme,
  build probe URL via &url.URL{} so user-controlled host can't smuggle
  into the request — clears the CodeQL go/request-forgery alert.
- pat_client: guard cached username with sync.RWMutex; IsAuthenticated
  now propagates non-401/403 errors instead of masking transport
  failures; GetMRStatus skips pipelines query when HeadSHA / HeadBranch
  are both empty; parseNextLink drops cross-host links instead of
  returning bare absolute URLs that get() would double-prefix.
- service: findTokenSecret returns (bool, string, error) and all
  callers propagate the secrets.List error so a backend outage isn't
  mistaken for "token absent"; ConfigureHost persists to hostStore
  before mutating in-memory host + client + authMethod under one lock.
- repoclone: SSH clone URL falls back to ssh:// form when the host has
  a port (scp-style git@host:path can't carry one).
- gitlab/client_helpers: namespace fallback uses LastIndex("/") so
  subgroup paths (acme/team/squad/repo) are preserved.
- pr skill / plan doc: drop hardcoded --target-branch main, derive host
  from git remote instead of $CI_SERVER_URL, build curl payload with
  jq -n; fix /pipelines/:id/jobs → :pipeline_id typo.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* fix(gitlab): preserve host base path in CheckHost; broaden validation; test

- connectivity: extract validateHost so the parse / scheme / hostname /
  userinfo / opaque-URL checks each have a single home. Preserve the
  configured base path (TrimRight slash) so a host like
  https://gitlab.acme.corp/gitlab probes /gitlab/api/v4/version instead
  of dropping the prefix.
- connectivity_test: cover validateHost (default, https, http, trailing
  slash, subpath, missing scheme, ftp, empty host, userinfo) and
  CheckHost end-to-end (version endpoint, base-path preservation,
  scheme rejection, unreachable host).
- pr skill: drop the broken `glab repo view --json defaultBranch`
  branch — glab doesn't accept --json, so the lookup silently fell
  back to "main" every time. Fetch default_branch via the GitLab
  REST API directly using the PAT we already have.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* fix(gitlab): override filter defaults, refresh auth uncached, mock pipelines

- appendFilter: Del before re-Add so user-supplied filter keys actually
  override caller defaults (e.g. state=closed swaps the seeded state=opened
  instead of appending a second value GitLab silently ignored).
- IsAuthenticated: probe /user directly instead of routing through the
  username cache; a token revoked upstream now surfaces as not-connected
  immediately. Cache is opportunistically refreshed on success.
- MockClient.GetMRFeedback: include pipeline state in HasIssues, matching
  the real PATClient behavior so test flows can't miss a broken MR.
- pr skill: document `glab mr note create --reply <id>` for replies (bare
  `glab mr note` opens a new thread); fix host-extraction block to handle
  ssh://host:2222/team/repo.git without leaking the port into PROJECT.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* fix(gitlab): guard mock pipelines on empty MR head; preserve HTTPS port in pr skill

- MockClient.GetMRFeedback now mirrors PATClient: skip the pipelines
  fetch when HeadSHA and HeadBranch are both empty. The mock'\''s
  ListPipelines ignores its branch argument and returns every pipeline
  seeded under the project, so without this guard a brand-new MR would
  inherit a sibling MR'\''s failing pipeline and flip HasIssues to true.
  Tests cover both the empty-head and head-present cases.
- pr skill: derive HOST scheme-aware so https://host:8443 keeps the port
  (HTTPS API endpoint), ssh://host:2222 strips it (different transport),
  and scp-style git@host stays portless. Avoids silently re-routing
  self-managed API calls to the default 443.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* fix(gitlab): export SeedPipelines; mock GetMRStatus parity; drain bodies; test cache hit

- MockClient: add exported SeedPipelines(project, iid, []) alongside the
  other Seed* methods; mirror PATClient.GetMRStatus by populating
  PipelineState / jobs counts via summarizePipelines, guarded on a
  non-empty head ref. Brings mock parity with the real client so any
  future test seeding pipelines sees the same MRStatus shape.
- PATClient HTTP plumbing: drain resp.Body via io.Copy(io.Discard, ...)
  when result == nil in both getWithTotal and doWrite, so HTTP/1.1 can
  reuse the connection instead of opening a new TCP socket per call.
- TestPATClient_GetAuthenticatedUser: assert calls == 1 after the second
  GetAuthenticatedUser hit so the cache contract is actually verified
  (a non-caching implementation would have passed the prior version).

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* fix(gitlab): surface connection errors, align MR pipeline guards, fix mock seed key

- service.GetStatus now captures the IsAuthenticated error into a new
  Status.ConnectionError field (empty on healthy / 401-403, populated on
  network / 5xx / parse failures). Frontend GitLabStatus + settings page
  render a distinct "Unreachable" badge + alert so users don't delete a
  still-valid token during a transient GitLab outage.
- PATClient.GetMRFeedback now guards on HeadSHA || HeadBranch, matching
  GetMRStatus and MockClient.GetMRFeedback (which had been updated in an
  earlier round). The three call sites were inconsistent — a mock test
  with HeadBranch-but-no-SHA would pass while the real client silently
  dropped pipelines.
- MockClient.pipelines is now keyed by project alone (was
  map[mockMRKey][]Pipeline). SeedPipelines takes (project, []) so
  successive seeds for the same project deterministically overwrite,
  instead of leaving multiple entries that ListPipelines would resolve
  in Go's unspecified map-iteration order.
- Tests: TestService_GetStatus_{PopulatesConnectionErrorOn5xx,
  ClearsConnectionErrorOn401} cover the new error surface;
  TestMockClient_SeedPipelines_OverwritesByProject locks the key change.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* fix(gitlab): tighten validateHost; init Status scopes; close token-host race

- validateHost: drop the parsed.Opaque != "" branch — Go only sets
  Opaque for opaque URIs, which have an empty Host the prior check
  already rejects. Narrow the userinfo error to mention the actual
  user:password@host shape so the message matches what users see.
- service.GetStatus: initialize RequiredScopes: []string{} on the
  nil-client defensive branch so the JSON payload keeps the
  always-an-array contract declared on the TypeScript side. The branch
  is effectively unreachable (every Provide path returns at least a
  NoopClient) but the empty-slice fallback costs nothing.
- service.ConfigureToken: build the installed client inside the write
  lock using the up-to-date s.host instead of the pre-probe snapshot.
  A concurrent ConfigureHost between RUnlock and Lock used to leave
  s.client pointing at the prior host while s.host advertised the new
  one — every subsequent API call would silently target the wrong
  instance until the next reconfigure.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* fix(gitlab): drop MR-commit stats fields; rename AuthorName; log post-lock host

- MRCommitInfo: drop Additions / Deletions / FilesChanged. GitLab's
  /merge_requests/:iid/commits endpoint doesn't return a stats object,
  so those fields were always 0 — better to omit them than feed callers
  silently-wrong numbers. Rename AuthorUsername to AuthorName since the
  API returns a display name, not a login handle. Doc-comment records
  the per-commit endpoint to use if a future revision wants real stats.
- ListMRCommits: drop the Stats anonymous struct from the JSON decode
  target now that the destination fields are gone.
- service.ConfigureToken: capture installedHost inside the write lock
  and log that value. The previous log used the pre-validation host
  snapshot, so a concurrent ConfigureHost between snapshot and lock
  would leave the log entry referring to a stale value while the
  client itself was correctly built against the new host.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* fix(gitlab): encode subgroup paths; sentinel-route errors; mock approval parity

- pat_client.SearchGroupProjects now encodes the group path through a new
  groupRef helper that %2F-substitutes slashes (mirrors projectRef). Subgroup
  paths like "acme/team" used to land at /groups/acme/team/projects, which
  GitLab routed to the parent group only and returned 404 for. Subgroups now
  work end-to-end.
- service.ErrInvalidToken sentinel + controller errors.Is routing: token
  validation failures now wrap a package-level sentinel and the HTTP layer
  switches on it via errors.Is, replacing the fragile strings.Contains
  prefix check that would silently fall through to 500 if the message ever
  changed. Coverage: TestService_ConfigureToken_WrapsErrInvalidToken.
- MockClient gains seedable approvals: SeedApprovals(project, iid, list,
  required) backs a dedicated approvals + requiredApprovals map.
  ListMRApprovals, GetMRFeedback, and GetMRStatus all consume them so
  ApprovalState / ApprovalCount / RequiredApprovals match what the real
  PATClient.GetMRStatus computes. Coverage:
  TestMockClient_GetMRStatus_UsesSeededApprovals.
- ClearToken: same host-snapshot race ConfigureToken was fixed for last
  round — NewClient now runs under the write lock against s.host rather
  than a pre-acquired snapshot.
- CheckHost: drain resp.Body before close so http.DefaultClient's keep-alive
  pool can reuse the connection for the next probe.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* fix(gitlab): full-path projectRef round-trip; unlock during glab probe

- splitFullReference now returns (namespace, fullPath) where fullPath is
  the namespace-qualified project path ("group/sub/project") instead of
  the last segment alone. Callers can pass MR.ProjectPath straight to
  projectRef for round-trip API calls (GetMR, GetMRFeedback, etc.) —
  matches GitLab's own path_with_namespace convention. Existing test
  cases updated.
- ClearToken: build the fallback client OUTSIDE the write lock so
  NewClient's glab subprocess (bounded by glabAuthTimeout = 10s)
  doesn't freeze every concurrent GetStatus / GetMRFeedback /
  Client() RLock reader for the duration. Brief WLock now only wraps
  the field swap. Tradeoff with the concurrent-ConfigureHost race is
  documented in-code: narrow stale-host window vs. 10s of blocked
  readers, and the next reconfigure resolves it.
- New regression test TestPATClient_SearchGroupProjects_EncodesSubgroupSlash
  asserts the request URL is /groups/acme%2Fteam/projects so a future
  refactor that swapped groupRef back to a bare url.PathEscape would
  fail visibly instead of silently 404ing subgroup lookups.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* fix(gitlab): equality-guard ClearToken's client swap against ConfigureHost race

ClearToken builds the fallback client outside the write lock to avoid
blocking RLock readers for up to 10s while glab auth-probes. The
swap-only critical section now compares s.host against the pre-probe
snapshot before assigning — if a concurrent ConfigureHost moved the
host underneath us, we leave its (newer, correctly-targeted) client
alone instead of overwriting with our stale-host build.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* fix(web): add GitLab to the settings integrations sidebar

The /settings/integrations/gitlab page existed and the index card listed
GitLab alongside the other integrations, but the settings sidebar nav
(IntegrationsNavGroup) only listed GitHub / Jira / Linear / Slack. The
page was unreachable through the standard sidebar.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* feat(gitlab): task-MR topbar surface + DB-backed task↔MR store

Phase 1 of the GitLab UI build-out: brings the MR side of the task topbar
to parity with the existing GitHub PR button.

Backend
- gitlab_task_mrs table + Store wiring (UpsertTaskMR,
  ListTaskMRsByTask, ListTaskMRsByWorkspaceID, DeleteTaskMR), uniqued
  on (task_id, repository_id, project_path, mr_iid) for multi-repo.
- service.SyncTaskMR folds a live GetMRStatus probe into an upsert;
  ListTaskMRsByTask / ListTaskMRsByWorkspace expose the rows.
- Three HTTP endpoints: GET /workspaces/:id/task-mrs, GET
  /tasks/:taskID/mrs, POST /tasks/:taskID/mrs/sync.
- initGitLabService now takes a *db.Pool and constructs gitlab.Store.
  Failures non-fatal: integration keeps working without the table.

Frontend
- TaskMR type + listWorkspaceTaskMRs / listTaskMRs / syncTaskMR API.
- lib/state/slices/gitlab slice (taskMRs.byTaskId) wired through
  default-state, store.ts AppState, and slices/index exports.
- hooks/domains/gitlab/use-task-mr.ts: useWorkspaceMRs (fetch-on-
  workspace-switch) and useTaskMRs (per-task selector).
- components/gitlab/mr-topbar-button.tsx — single/multi MR variants,
  status icons mirroring pr-task-icon priority order.
- task-top-bar.tsx renders PRTopbarButton and MRTopbarButton side-by-
  side; each returns null when empty, so the union handles GitHub-only,
  GitLab-only, and multi-repo tasks without an explicit switch.
- kanban-board.tsx hydrates useWorkspaceMRs alongside useWorkspacePRs.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* feat(gitlab): add /gitlab page for browsing user MRs and issues

Adds the GitLab counterpart to /github so users can browse their own
merge requests and issues from inside kandev, parallel to the existing
GitHub "My GitHub" page.

Backend
- /api/v1/gitlab/user/mrs and /user/issues — paginated wrappers around
  the existing SearchMRsPaged / ListIssuesPaged client methods.
  paginationFromQuery clamps page/per_page the same way as the client.

Frontend
- /gitlab SSR page + client with MR/Issue tabs, scope filters
  (assigned / created / review-requested), and a free-text search box
  that falls back to raw GitLab query-string for power users.
- searchUserMRs / searchUserIssues API helpers + MR / Issue / *SearchPage
  types in lib/types/gitlab.
- useGitLabAvailable hook (probes /status + refreshes on window focus)
  feeds the integrations menu so the GitLab link only shows when a
  token is configured or auth is green.

Tests
- task-top-bar.test mocks the new MRTopbarButton so renders no longer
  pick up useAppStore without a StateProvider.
- integrations-menu.test wires the new useGitLabAvailable mock and
  gitlabReady prop into mockAvailability / getAvailableIntegrationLinks
  fixtures.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* fix(gitlab): stable empty array in useTaskMRs to avoid infinite re-render

useTaskMRs returned `state.taskMRs.byTaskId[taskId] ?? []` — that fresh
literal made the zustand selector produce a new reference on every
render when the task had no MRs, triggering an infinite re-render loop
in MRTopbarButton that crashed the task page with a Next.js client-side
exception.

The page never mounted session-chat, so Docker E2E tests that drive
`/t/:id` (slow-bootstrap progress, external-stop resume, environment
reset) all timed out waiting for the chat panel.

Mirror the GitHub side's `EMPTY_PRS` pattern: hoist a module-level
`EMPTY_MRS = []` and return it for the empty case.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* fix(gitlab): address PR review — cache header, in-flight cancel, tests

- Top-level `cache: "no-store"` in 5 sites (use-task-mr.ts, gitlab-api.ts,
  gitlab-page-client.tsx). The earlier `init: { cache: "no-store" }`
  placement was silently overwritten by fetchJson with undefined, so probes
  hit the browser cache instead.
- useWorkspaceMRs now invalidates in-flight responses and calls
  resetTaskMRs when the workspace becomes null, so the previous workspace's
  MRs don't linger after sign-out / workspace switch.
- Drop unpopulated UnresolvedThreads/DiscussionCount from TaskMR (model,
  schema, TS type). SyncTaskMR's source MRStatus never populated them and
  no surface reads them; the dropped columns are skipped via an explicit
  projection in store.go so existing dev DBs keep binding.
- Extract MRList/IssueList inline fetches in /gitlab into useGitLabUserMRs
  / useGitLabUserIssues — matches CLAUDE.md "never fetch in components".
- Tests for store (UpsertTaskMR, composite key, workspace-JOIN isolation,
  ordering, Delete), service (SyncTaskMR mock round-trip + field mapping +
  store-unset error, ListTaskMRsByWorkspace JOIN isolation, ListTaskMRsByTask),
  pat_client (ListIssuesPaged X-Total), gitlab-api (5 new fns), gitlab-slice
  (setTaskMR composite key), and the use-task-mr / use-user-search hooks.
- pr SKILL.md: skip note for steps 5–6 on GitLab remotes.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

* fix(gitlab): only wrap 401/403 probe errors as ErrInvalidToken

Network failures, 5xx, and DNS errors during `ConfigureToken` previously
surfaced to the user as HTTP 400 "invalid token: …" — during a GitLab
outage a user with a valid token might delete it assuming it was rejected.
Now only `*APIError` with 401/403 is mapped to `ErrInvalidToken`; other
errors propagate unwrapped so the controller routes them to "GitLab
unreachable" instead.

Co-Authored-By: Claude Opus 4.7 <noreply@anthropic.com>

---------

Co-authored-by: Kandev Agent <agent@kandev.dev>
Co-authored-by: Claude Opus 4.7 <noreply@anthropic.com>
2026-05-23 23:17:16 +01:00

538 lines
17 KiB
Go

package gitlab
import (
"context"
"encoding/json"
"errors"
"net/http"
"net/http/httptest"
"strconv"
"strings"
"testing"
"time"
)
// newTestServer wires a handler under /api/v4/* and returns the host URL.
func newTestServer(t *testing.T, handler http.Handler) (host string, teardown func()) {
t.Helper()
mux := http.NewServeMux()
mux.Handle("/api/v4/", http.StripPrefix("/api/v4", handler))
srv := httptest.NewServer(mux)
return srv.URL, srv.Close
}
func TestPATClient_GetAuthenticatedUser(t *testing.T) {
calls := 0
host, stop := newTestServer(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
calls++
if r.URL.Path != "/user" {
t.Errorf("path = %q, want /user", r.URL.Path)
}
if r.Header.Get("PRIVATE-TOKEN") != "tok" {
t.Errorf("PRIVATE-TOKEN header = %q, want tok", r.Header.Get("PRIVATE-TOKEN"))
}
_ = json.NewEncoder(w).Encode(map[string]any{"username": "alice"})
}))
defer stop()
c := NewPATClient(host, "tok")
user, err := c.GetAuthenticatedUser(context.Background())
if err != nil {
t.Fatalf("err = %v", err)
}
if user != "alice" {
t.Fatalf("user = %q, want alice", user)
}
// Cached on second call — the server must not be hit again. A non-
// caching implementation would still pass an err-only assertion, so
// the request counter is what actually proves the cache.
if _, err := c.GetAuthenticatedUser(context.Background()); err != nil {
t.Fatalf("cached call err = %v", err)
}
if calls != 1 {
t.Errorf("server called %d times, want 1 (second call must hit cache)", calls)
}
}
func TestPATClient_GetAuthenticatedUser_AuthFailure(t *testing.T) {
host, stop := newTestServer(t, http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusUnauthorized)
_, _ = w.Write([]byte(`{"message":"401 Unauthorized"}`))
}))
defer stop()
c := NewPATClient(host, "bad")
_, err := c.GetAuthenticatedUser(context.Background())
if err == nil {
t.Fatal("expected error")
}
var apiErr *APIError
if !errors.As(err, &apiErr) {
t.Fatalf("err = %v, want *APIError", err)
}
if apiErr.StatusCode != http.StatusUnauthorized {
t.Fatalf("status = %d, want 401", apiErr.StatusCode)
}
}
func TestPATClient_GetMR(t *testing.T) {
host, stop := newTestServer(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// EscapedPath preserves %2F; r.URL.Path is the decoded form.
if got, want := r.URL.EscapedPath(), "/projects/group%2Fproject/merge_requests/42"; got != want {
t.Errorf("escaped path = %q, want %q (URL-encoded slash)", got, want)
}
_ = json.NewEncoder(w).Encode(rawMR{
ID: 1, IID: 42, ProjectID: 7,
Title: "Add feature", State: "opened",
SourceBranch: "feat/x", TargetBranch: "main",
SHA: "abc123",
Author: rawUser{Username: "alice"},
References: struct {
Full string `json:"full"`
}{Full: "group/project!42"},
CreatedAt: time.Now(), UpdatedAt: time.Now(),
})
}))
defer stop()
c := NewPATClient(host, "tok")
mr, err := c.GetMR(context.Background(), "group/project", 42)
if err != nil {
t.Fatalf("err = %v", err)
}
if mr.IID != 42 {
t.Errorf("iid = %d, want 42", mr.IID)
}
if mr.State != "open" {
t.Errorf("state = %q, want open (normalized from opened)", mr.State)
}
if mr.HeadBranch != "feat/x" || mr.BaseBranch != "main" {
t.Errorf("branches = %q/%q, want feat/x/main", mr.HeadBranch, mr.BaseBranch)
}
if mr.AuthorUsername != "alice" {
t.Errorf("author = %q, want alice", mr.AuthorUsername)
}
}
func TestPATClient_FindMRByBranch_Empty(t *testing.T) {
host, stop := newTestServer(t, http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
_, _ = w.Write([]byte(`[]`))
}))
defer stop()
c := NewPATClient(host, "tok")
mr, err := c.FindMRByBranch(context.Background(), "g/p", "missing")
if err != nil {
t.Fatalf("err = %v", err)
}
if mr != nil {
t.Fatalf("mr = %+v, want nil", mr)
}
}
func TestPATClient_CreateMR_DraftPrefix(t *testing.T) {
var receivedBody map[string]any
host, stop := newTestServer(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
if r.Method != http.MethodPost {
t.Errorf("method = %s, want POST", r.Method)
}
_ = json.NewDecoder(r.Body).Decode(&receivedBody)
_ = json.NewEncoder(w).Encode(rawMR{IID: 7, Title: "Draft: feat", State: "opened"})
}))
defer stop()
c := NewPATClient(host, "tok")
mr, err := c.CreateMR(context.Background(), "g/p", "feat", "main", "feat", "body", true)
if err != nil {
t.Fatalf("err = %v", err)
}
if mr.IID != 7 {
t.Errorf("iid = %d, want 7", mr.IID)
}
if got, want := receivedBody["title"], "Draft: feat"; got != want {
t.Errorf("title sent = %v, want %q", got, want)
}
}
func TestPATClient_CreateMR_NoDoubleDraftPrefix(t *testing.T) {
var receivedBody map[string]any
host, stop := newTestServer(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
_ = json.NewDecoder(r.Body).Decode(&receivedBody)
_ = json.NewEncoder(w).Encode(rawMR{IID: 8, State: "opened"})
}))
defer stop()
c := NewPATClient(host, "tok")
if _, err := c.CreateMR(context.Background(), "g/p", "feat", "main", "Draft: already", "", true); err != nil {
t.Fatalf("err = %v", err)
}
if got := receivedBody["title"].(string); strings.Count(got, "Draft:") != 1 {
t.Errorf("title = %q, expected single Draft: prefix", got)
}
}
func TestPATClient_ResolveDiscussion_UsesPUT(t *testing.T) {
called := false
host, stop := newTestServer(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
called = true
if r.Method != http.MethodPut {
t.Errorf("method = %s, want PUT", r.Method)
}
if !strings.Contains(r.URL.RawQuery, "resolved=true") {
t.Errorf("query = %q, want resolved=true", r.URL.RawQuery)
}
w.WriteHeader(http.StatusOK)
}))
defer stop()
c := NewPATClient(host, "tok")
if err := c.ResolveMRDiscussion(context.Background(), "g/p", 1, "abc123"); err != nil {
t.Fatalf("err = %v", err)
}
if !called {
t.Fatal("server was not called")
}
}
func TestPATClient_ListMRDiscussions_ConvertsThread(t *testing.T) {
host, stop := newTestServer(t, http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
_, _ = w.Write([]byte(`[{
"id": "thread-1",
"notes": [
{"id":1,"body":"first","resolvable":true,"resolved":false,"author":{"username":"alice"},"created_at":"2026-05-01T00:00:00Z","updated_at":"2026-05-01T00:00:00Z"},
{"id":2,"body":"reply","author":{"username":"bob"},"created_at":"2026-05-02T00:00:00Z","updated_at":"2026-05-02T00:00:00Z"}
]
}]`))
}))
defer stop()
c := NewPATClient(host, "tok")
d, err := c.ListMRDiscussions(context.Background(), "g/p", 1, nil)
if err != nil {
t.Fatalf("err = %v", err)
}
if len(d) != 1 {
t.Fatalf("got %d discussions, want 1", len(d))
}
if !d[0].Resolvable {
t.Error("resolvable = false, want true (taken from first note)")
}
if d[0].Resolved {
t.Error("resolved = true, want false")
}
if len(d[0].Notes) != 2 {
t.Fatalf("notes = %d, want 2", len(d[0].Notes))
}
wantUpdate := time.Date(2026, 5, 2, 0, 0, 0, 0, time.UTC)
if !d[0].UpdatedAt.Equal(wantUpdate) {
t.Errorf("updated_at = %v, want %v (latest reply)", d[0].UpdatedAt, wantUpdate)
}
}
func TestPATClient_ListMRDiscussions_FiltersBySince(t *testing.T) {
host, stop := newTestServer(t, http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
_, _ = w.Write([]byte(`[
{"id":"old","notes":[{"id":1,"created_at":"2026-04-01T00:00:00Z","updated_at":"2026-04-01T00:00:00Z"}]},
{"id":"new","notes":[{"id":2,"created_at":"2026-05-15T00:00:00Z","updated_at":"2026-05-15T00:00:00Z"}]}
]`))
}))
defer stop()
since := time.Date(2026, 5, 1, 0, 0, 0, 0, time.UTC)
c := NewPATClient(host, "tok")
d, err := c.ListMRDiscussions(context.Background(), "g/p", 1, &since)
if err != nil {
t.Fatalf("err = %v", err)
}
if len(d) != 1 || d[0].ID != "new" {
t.Fatalf("got %#v, want only the 'new' discussion", d)
}
}
func TestPATClient_SearchMRsPaged_HonoursTotalHeader(t *testing.T) {
host, stop := newTestServer(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("X-Total", "153")
page, _ := strconv.Atoi(r.URL.Query().Get("page"))
if page == 1 {
_, _ = w.Write([]byte(`[{"iid":1,"state":"opened","author":{"username":"a"},"references":{"full":"g/p!1"}}]`))
return
}
_, _ = w.Write([]byte(`[]`))
}))
defer stop()
c := NewPATClient(host, "tok")
page, err := c.SearchMRsPaged(context.Background(), "", "", 1, 25)
if err != nil {
t.Fatalf("err = %v", err)
}
if page.TotalCount != 153 {
t.Errorf("total = %d, want 153", page.TotalCount)
}
if len(page.MRs) != 1 {
t.Errorf("mrs = %d, want 1", len(page.MRs))
}
}
func TestPATClient_ListIssuesPaged_HonoursTotalHeader(t *testing.T) {
host, stop := newTestServer(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// X-Total drives pagination; the body returns a small slice so the
// test verifies header + body wire up independently.
w.Header().Set("X-Total", "87")
if r.URL.Path != "/issues" {
// newTestServer strips the /api/v4 prefix before dispatch.
t.Errorf("path = %q, want /issues", r.URL.Path)
}
page, _ := strconv.Atoi(r.URL.Query().Get("page"))
perPage := r.URL.Query().Get("per_page")
if perPage != "20" {
t.Errorf("per_page = %q, want 20 — paging args must reach the server", perPage)
}
if page == 2 {
_, _ = w.Write([]byte(`[{"iid":42,"state":"opened","author":{"username":"alice"},"references":{"full":"g/p#42"}}]`))
return
}
_, _ = w.Write([]byte(`[]`))
}))
defer stop()
c := NewPATClient(host, "tok")
page, err := c.ListIssuesPaged(context.Background(), "", "", 2, 20)
if err != nil {
t.Fatalf("err = %v", err)
}
if page.TotalCount != 87 {
t.Errorf("total = %d, want 87 (X-Total header)", page.TotalCount)
}
if page.Page != 2 || page.PerPage != 20 {
t.Errorf("page/perPage = %d/%d, want 2/20 (echoed back)", page.Page, page.PerPage)
}
if len(page.Issues) != 1 || page.Issues[0].IID != 42 {
t.Errorf("issues = %+v, want one issue with IID 42", page.Issues)
}
}
func TestParseNextLink(t *testing.T) {
apiBase := "https://gitlab.example.com/api/v4"
cases := []struct {
name string
header string
want string
}{
{"empty", "", ""},
{"next", `<https://gitlab.example.com/api/v4/issues?page=2>; rel="next"`, "/issues?page=2"},
{"prev-only", `<https://gitlab.example.com/api/v4/issues?page=2>; rel="prev"`, ""},
{"next-then-last", `<https://gitlab.example.com/api/v4/issues?page=3>; rel="next", <https://gitlab.example.com/api/v4/issues?page=10>; rel="last"`, "/issues?page=3"},
// Cross-host or wrong-base URLs are dropped rather than returned
// raw — passing a bare absolute URL back to get() would double-
// prefix it with host + apiPathPrefix.
{"foreign-host-dropped", `<https://other.example.com/api/v4/issues?page=2>; rel="next"`, ""},
{"no-apibase-dropped", `</issues?page=2>; rel="next"`, ""},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
got := parseNextLink(tc.header, apiBase)
if got != tc.want {
t.Errorf("parseNextLink(%q) = %q, want %q", tc.header, got, tc.want)
}
})
}
}
func TestPATClient_IsAuthenticated_PropagatesNonAuthErrors(t *testing.T) {
host, stop := newTestServer(t, http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusInternalServerError)
_, _ = w.Write([]byte(`{"message":"boom"}`))
}))
defer stop()
c := NewPATClient(host, "tok")
ok, err := c.IsAuthenticated(context.Background())
if err == nil {
t.Fatal("expected error for 500 response (transport failure must not be reported as 'not authenticated')")
}
if ok {
t.Error("authenticated = true on 500, want false")
}
}
func TestPATClient_IsAuthenticated_401IsClean(t *testing.T) {
host, stop := newTestServer(t, http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusUnauthorized)
}))
defer stop()
c := NewPATClient(host, "bad")
ok, err := c.IsAuthenticated(context.Background())
if err != nil {
t.Errorf("err = %v, want nil for 401 (it's a clean 'not authenticated' signal)", err)
}
if ok {
t.Error("authenticated = true on 401, want false")
}
}
// Regression: if a token gets revoked upstream, IsAuthenticated must surface
// the failure even though the username was previously cached. The previous
// implementation called GetAuthenticatedUser, which short-circuited on the
// cache and made revoked tokens appear connected forever.
func TestPATClient_IsAuthenticated_DoesNotTrustStaleCache(t *testing.T) {
calls := 0
host, stop := newTestServer(t, http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) {
calls++
if calls == 1 {
_, _ = w.Write([]byte(`{"username":"alice"}`))
return
}
w.WriteHeader(http.StatusUnauthorized)
}))
defer stop()
c := NewPATClient(host, "tok")
// Warm the cache.
if _, err := c.GetAuthenticatedUser(context.Background()); err != nil {
t.Fatalf("warmup err = %v", err)
}
ok, err := c.IsAuthenticated(context.Background())
if err != nil {
t.Errorf("err = %v, want nil for 401", err)
}
if ok {
t.Error("authenticated = true after upstream revoked token, want false (cache must not mask revocation)")
}
}
// SearchGroupProjects must %2F-encode slashes in subgroup paths so the
// resulting URL is /groups/acme%2Fteam/projects, not /groups/acme/team/projects
// (which GitLab routes to the parent only and returns 404 for). Without this
// regression test a future refactor that switched groupRef back to a bare
// url.PathEscape would silently break subgroup lookups.
func TestPATClient_SearchGroupProjects_EncodesSubgroupSlash(t *testing.T) {
var receivedPath string
host, stop := newTestServer(t, http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// EscapedPath() preserves %2F; r.URL.Path is the decoded form.
receivedPath = r.URL.EscapedPath()
_, _ = w.Write([]byte(`[]`))
}))
defer stop()
c := NewPATClient(host, "tok")
if _, err := c.SearchGroupProjects(context.Background(), "acme/team", "", 5); err != nil {
t.Fatalf("err = %v", err)
}
// newTestServer mounts handlers under /api/v4/* via StripPrefix, so the
// handler sees the path without the /api/v4 prefix.
want := "/groups/acme%2Fteam/projects"
if receivedPath != want {
t.Errorf("escaped path = %q, want %q (subgroup slash must be %%2F-encoded)", receivedPath, want)
}
}
func TestNormalizeMRState(t *testing.T) {
cases := map[string]string{
"opened": "open",
"closed": "closed",
"merged": "merged",
"locked": "locked",
"": "",
}
for in, want := range cases {
if got := normalizeMRState(in); got != want {
t.Errorf("normalizeMRState(%q) = %q, want %q", in, got, want)
}
}
}
func TestSplitFullReference(t *testing.T) {
// projectPath is the full namespace-qualified path so callers can pass
// it straight to projectRef. namespace is everything before the final
// "/" — same shape as Project.Namespace.
cases := []struct {
in string
wantNamespace string
wantPath string
}{
{"group/project!42", "group", "group/project"},
{"group/sub/project!7", "group/sub", "group/sub/project"},
{"group/project#10", "group", "group/project"},
{"noslash", "", ""},
{"", "", ""},
}
for _, tc := range cases {
ns, p := splitFullReference(tc.in)
if ns != tc.wantNamespace || p != tc.wantPath {
t.Errorf("splitFullReference(%q) = (%q, %q), want (%q, %q)", tc.in, ns, p, tc.wantNamespace, tc.wantPath)
}
}
}
func TestSummarizePipelines(t *testing.T) {
cases := []struct {
name string
input []Pipeline
state string
expectsTotal bool
}{
{"empty", nil, "", false},
{"success", []Pipeline{{Status: "success", JobsTotal: 3, JobsPassing: 3}}, "success", true},
{"failed", []Pipeline{{Status: "failed"}}, "failure", false},
{"running", []Pipeline{{Status: "running"}}, "pending", false},
{"skipped-suppressed", []Pipeline{{Status: "skipped"}}, "", false},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
state, total, _ := summarizePipelines(tc.input)
if state != tc.state {
t.Errorf("state = %q, want %q", state, tc.state)
}
if tc.expectsTotal && total == 0 {
t.Error("expected jobs total > 0")
}
})
}
}
func TestSummarizeApprovals(t *testing.T) {
cases := []struct {
have, required int
want string
}{
{0, 0, ""},
{1, 0, "approved"},
{2, 2, "approved"},
{1, 2, "pending"},
{0, 1, "pending"},
}
for _, tc := range cases {
if got := summarizeApprovals(tc.have, tc.required); got != tc.want {
t.Errorf("summarizeApprovals(%d,%d) = %q, want %q", tc.have, tc.required, got, tc.want)
}
}
}
func TestCountDiffLines(t *testing.T) {
diff := "--- a/foo.go\n+++ b/foo.go\n@@ -1,3 +1,3 @@\n-old\n+new1\n+new2\n unchanged\n"
add, del := countDiffLines(diff)
if add != 2 {
t.Errorf("additions = %d, want 2", add)
}
if del != 1 {
t.Errorf("deletions = %d, want 1", del)
}
}
func TestClampSearchPage(t *testing.T) {
cases := []struct{ inP, inPP, wantP, wantPP int }{
{0, 0, 1, defaultPageSize},
{-3, 5, 1, 5},
{2, 250, 2, maxPageSize},
{5, 30, 5, 30},
}
for _, tc := range cases {
p, pp := clampSearchPage(tc.inP, tc.inPP)
if p != tc.wantP || pp != tc.wantPP {
t.Errorf("clamp(%d,%d) = (%d,%d), want (%d,%d)", tc.inP, tc.inPP, p, pp, tc.wantP, tc.wantPP)
}
}
}