A second tbd_ship for the same change no longer errors on "branch exists": CreateBranch conflict is tolerated, and if a PR is already open for the head, CreatePullRequest's conflict/validation error resolves it via ListPullRequests (matching head.ref). Identical file content on the branch skips the write, so a resume produces no redundant empty-diff commit. Then the same CI gate runs and merges if now green — so "poll or re-invoke" (the #40 UX) actually works. Test: TestTBDShip_Resume_ExistingBranchAndPR (branch+PR exist, content unchanged → no write, merges when green). First-call paths unchanged. Co-Authored-By: Claude Opus 4.8 (1M context) <noreply@anthropic.com>
212 lines
9.5 KiB
Go
212 lines
9.5 KiB
Go
package tools_test
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"strings"
|
|
"sync/atomic"
|
|
"testing"
|
|
|
|
"git.d-ma.be/mathias/gitea-mcp/internal/allowlist"
|
|
"git.d-ma.be/mathias/gitea-mcp/internal/gitea"
|
|
"git.d-ma.be/mathias/gitea-mcp/internal/tools"
|
|
"github.com/stretchr/testify/assert"
|
|
"github.com/stretchr/testify/require"
|
|
)
|
|
|
|
// shipFake serves the whole tbd_ship flow; runsJSON is the workflow_runs array
|
|
// for the head commit, letting each test drive the CI gate.
|
|
func shipFake(t *testing.T, runsJSON string, merged, deleted *atomic.Bool) *httptest.Server {
|
|
t.Helper()
|
|
return shipFakeOpts(t, runsJSON, 0, http.StatusOK, merged, deleted)
|
|
}
|
|
|
|
// shipFakeOpts adds protection (requiredApprovals>0 → protected) and a merge
|
|
// status code, so tests can drive the review-protected and conflict paths.
|
|
func shipFakeOpts(t *testing.T, runsJSON string, requiredApprovals, mergeStatus int, merged, deleted *atomic.Bool) *httptest.Server {
|
|
t.Helper()
|
|
return httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
p := r.URL.Path
|
|
w.Header().Set("Content-Type", "application/json")
|
|
switch {
|
|
case r.Method == http.MethodGet && strings.Contains(p, "/branch_protections/"):
|
|
if requiredApprovals > 0 {
|
|
_, _ = w.Write([]byte(`{"required_approvals":` + itoa(requiredApprovals) + `}`))
|
|
return
|
|
}
|
|
w.WriteHeader(http.StatusNotFound) // unprotected
|
|
_, _ = w.Write([]byte(`{"message":"not found"}`))
|
|
case r.Method == http.MethodPost && strings.HasSuffix(p, "/branches"):
|
|
w.WriteHeader(http.StatusCreated)
|
|
_, _ = w.Write([]byte(`{"name":"tbd/x","commit":{"id":"abc"}}`))
|
|
case r.Method == http.MethodGet && strings.Contains(p, "/contents/"):
|
|
w.WriteHeader(http.StatusNotFound) // new file
|
|
_, _ = w.Write([]byte(`{"message":"not found"}`))
|
|
case (r.Method == http.MethodPost || r.Method == http.MethodPut) && strings.Contains(p, "/contents/"):
|
|
w.WriteHeader(http.StatusCreated)
|
|
_, _ = w.Write([]byte(`{"content":{"path":"x","sha":"s"},"commit":{"sha":"c"}}`))
|
|
case r.Method == http.MethodPost && strings.HasSuffix(p, "/pulls"):
|
|
w.WriteHeader(http.StatusCreated)
|
|
_, _ = w.Write([]byte(`{"number":7,"title":"t","html_url":"http://x/pulls/7","state":"open","head":{"ref":"tbd/x","sha":"abc"},"base":{"ref":"main"}}`))
|
|
case r.Method == http.MethodGet && strings.Contains(p, "/actions/runs"):
|
|
_, _ = w.Write([]byte(`{"total_count":0,"workflow_runs":` + runsJSON + `}`))
|
|
case r.Method == http.MethodPost && strings.HasSuffix(p, "/pulls/7/merge"):
|
|
merged.Store(true)
|
|
w.WriteHeader(mergeStatus)
|
|
_, _ = w.Write([]byte(`{}`))
|
|
case r.Method == http.MethodDelete && strings.Contains(p, "/branches/"):
|
|
deleted.Store(true)
|
|
w.WriteHeader(http.StatusOK)
|
|
_, _ = w.Write([]byte(`{}`))
|
|
default:
|
|
t.Errorf("unexpected request: %s %s", r.Method, p)
|
|
w.WriteHeader(http.StatusNotFound)
|
|
}
|
|
}))
|
|
}
|
|
|
|
func callShip(t *testing.T, srvURL, args string) map[string]any {
|
|
t.Helper()
|
|
tool := tools.NewTBDShip(gitea.NewClient(srvURL, "tok"), allowlist.New([]string{"mathias"}))
|
|
out, err := tool.Call(context.Background(), json.RawMessage(args))
|
|
require.NoError(t, err)
|
|
var res map[string]any
|
|
require.NoError(t, json.Unmarshal(out, &res))
|
|
return res
|
|
}
|
|
|
|
// Green CI + unprotected base → squash-merge + branch deleted.
|
|
func TestTBDShip_GreenCI_Merges(t *testing.T) {
|
|
var merged, deleted atomic.Bool
|
|
srv := shipFake(t, `[{"id":1,"status":"completed","conclusion":"success","head_sha":"abc"}]`, &merged, &deleted)
|
|
defer srv.Close()
|
|
|
|
res := callShip(t, srv.URL, `{"owner":"mathias","repo":"myrepo","path":"docs/x.md","content":"hi","message":"add x"}`)
|
|
|
|
assert.Equal(t, true, res["merged"])
|
|
assert.Equal(t, "success", res["ci_status"])
|
|
assert.Equal(t, float64(7), res["pr_number"])
|
|
assert.True(t, merged.Load(), "merge endpoint must be called")
|
|
assert.True(t, deleted.Load(), "branch must be deleted after merge")
|
|
}
|
|
|
|
// No CI runs for the head commit → fail closed: PR opened, NOT merged.
|
|
func TestTBDShip_NoCI_FailsClosed(t *testing.T) {
|
|
var merged, deleted atomic.Bool
|
|
srv := shipFake(t, `[]`, &merged, &deleted)
|
|
defer srv.Close()
|
|
|
|
res := callShip(t, srv.URL, `{"owner":"mathias","repo":"myrepo","path":"docs/x.md","content":"hi","message":"add x"}`)
|
|
|
|
assert.Equal(t, false, res["merged"])
|
|
assert.Equal(t, "none", res["ci_status"])
|
|
assert.NotEmpty(t, res["reason"])
|
|
assert.False(t, merged.Load(), "merge must NOT be called when there is no CI")
|
|
assert.Equal(t, float64(7), res["pr_number"], "PR is still opened for manual merge")
|
|
}
|
|
|
|
// Red CI → fail closed.
|
|
func TestTBDShip_RedCI_FailsClosed(t *testing.T) {
|
|
var merged, deleted atomic.Bool
|
|
srv := shipFake(t, `[{"id":1,"status":"completed","conclusion":"failure","head_sha":"abc"}]`, &merged, &deleted)
|
|
defer srv.Close()
|
|
|
|
res := callShip(t, srv.URL, `{"owner":"mathias","repo":"myrepo","path":"docs/x.md","content":"hi","message":"add x"}`)
|
|
|
|
assert.Equal(t, false, res["merged"])
|
|
assert.Equal(t, "failed", res["ci_status"])
|
|
assert.False(t, merged.Load(), "merge must NOT be called when CI is red")
|
|
}
|
|
|
|
func itoa(n int) string { b, _ := json.Marshal(n); return string(b) }
|
|
|
|
// Green CI but the base branch requires review → fail closed (no auto-merge).
|
|
func TestTBDShip_ReviewProtected_FailsClosed(t *testing.T) {
|
|
var merged, deleted atomic.Bool
|
|
srv := shipFakeOpts(t, `[{"id":1,"status":"completed","conclusion":"success","head_sha":"abc"}]`, 1, http.StatusOK, &merged, &deleted)
|
|
defer srv.Close()
|
|
|
|
res := callShip(t, srv.URL, `{"owner":"mathias","repo":"myrepo","path":"docs/x.md","content":"hi","message":"add x"}`)
|
|
|
|
assert.Equal(t, false, res["merged"])
|
|
assert.NotEmpty(t, res["reason"])
|
|
assert.Contains(t, res["reason"], "review")
|
|
assert.False(t, merged.Load(), "must NOT merge a review-protected base")
|
|
}
|
|
|
|
// Green CI but the merge is unclean (409) → fail closed, PR left open.
|
|
func TestTBDShip_MergeConflict_FailsClosed(t *testing.T) {
|
|
var merged, deleted atomic.Bool
|
|
srv := shipFakeOpts(t, `[{"id":1,"status":"completed","conclusion":"success","head_sha":"abc"}]`, 0, http.StatusConflict, &merged, &deleted)
|
|
defer srv.Close()
|
|
|
|
res := callShip(t, srv.URL, `{"owner":"mathias","repo":"myrepo","path":"docs/x.md","content":"hi","message":"add x"}`)
|
|
|
|
assert.Equal(t, false, res["merged"])
|
|
assert.NotEmpty(t, res["reason"])
|
|
assert.True(t, merged.Load(), "merge is attempted")
|
|
assert.False(t, deleted.Load(), "branch is NOT deleted on a failed merge")
|
|
}
|
|
|
|
// Re-invoking with the same change must resume the existing branch/PR (not
|
|
// error on "branch exists"), skip the redundant write when content is
|
|
// unchanged, and merge once CI is green (#48).
|
|
func TestTBDShip_Resume_ExistingBranchAndPR(t *testing.T) {
|
|
var merged, deleted, wrote atomic.Bool
|
|
branch := "tbd/resume-me"
|
|
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
|
p := r.URL.Path
|
|
w.Header().Set("Content-Type", "application/json")
|
|
switch {
|
|
case r.Method == http.MethodGet && strings.Contains(p, "/branch_protections/"):
|
|
w.WriteHeader(http.StatusNotFound)
|
|
_, _ = w.Write([]byte(`{"message":"not found"}`))
|
|
case r.Method == http.MethodPost && strings.HasSuffix(p, "/branches"):
|
|
w.WriteHeader(http.StatusConflict) // branch already exists
|
|
_, _ = w.Write([]byte(`{"message":"branch already exists"}`))
|
|
case r.Method == http.MethodGet && strings.Contains(p, "/contents/"):
|
|
// existing file with identical content ("hi") → write should be skipped
|
|
w.WriteHeader(http.StatusOK)
|
|
_, _ = w.Write([]byte(`{"path":"docs/x.md","sha":"s","content":"aGk=","encoding":"base64"}`))
|
|
case (r.Method == http.MethodPost || r.Method == http.MethodPut) && strings.Contains(p, "/contents/"):
|
|
wrote.Store(true)
|
|
w.WriteHeader(http.StatusCreated)
|
|
_, _ = w.Write([]byte(`{"content":{"path":"x","sha":"s2"},"commit":{"sha":"c"}}`))
|
|
case r.Method == http.MethodPost && strings.HasSuffix(p, "/pulls"):
|
|
w.WriteHeader(http.StatusConflict) // PR already exists for this head
|
|
_, _ = w.Write([]byte(`{"message":"pull request already exists"}`))
|
|
case r.Method == http.MethodGet && strings.HasSuffix(p, "/pulls"):
|
|
_, _ = w.Write([]byte(`[{"number":7,"html_url":"http://x/pulls/7","state":"open","head":{"ref":"` + branch + `","sha":"abc"},"base":{"ref":"main"}}]`))
|
|
case r.Method == http.MethodGet && strings.Contains(p, "/actions/runs"):
|
|
_, _ = w.Write([]byte(`{"total_count":1,"workflow_runs":[{"id":1,"status":"completed","conclusion":"success","head_sha":"abc"}]}`))
|
|
case r.Method == http.MethodPost && strings.HasSuffix(p, "/pulls/7/merge"):
|
|
merged.Store(true)
|
|
w.WriteHeader(http.StatusOK)
|
|
_, _ = w.Write([]byte(`{}`))
|
|
case r.Method == http.MethodDelete && strings.Contains(p, "/branches/"):
|
|
deleted.Store(true)
|
|
w.WriteHeader(http.StatusOK)
|
|
_, _ = w.Write([]byte(`{}`))
|
|
default:
|
|
t.Errorf("unexpected request: %s %s", r.Method, p)
|
|
w.WriteHeader(http.StatusNotFound)
|
|
}
|
|
}))
|
|
defer srv.Close()
|
|
|
|
res := callShip(t, srv.URL, `{"owner":"mathias","repo":"myrepo","path":"docs/x.md","content":"hi","message":"add x","branch":"`+branch+`"}`)
|
|
|
|
assert.Equal(t, true, res["merged"], "resume must merge when CI is green")
|
|
assert.Equal(t, float64(7), res["pr_number"], "must reuse the existing PR #7")
|
|
assert.False(t, wrote.Load(), "identical content must not trigger a redundant write")
|
|
assert.True(t, merged.Load())
|
|
}
|
|
|
|
func TestTBDShip_AllowlistRejects(t *testing.T) {
|
|
tool := tools.NewTBDShip(gitea.NewClient("http://unused", ""), allowlist.New([]string{"mathias"}))
|
|
_, err := tool.Call(context.Background(), json.RawMessage(`{"owner":"evil","repo":"r","path":"p","content":"c","message":"m"}`))
|
|
require.Error(t, err)
|
|
}
|