refactor: testing from the beginning. a journey in 150k lines of tests to none
This commit is contained in:
651 files changed
-146443
No files matched your search
@@ -1,72 +0,0 @@
|
||||
package forge
|
||||
|
||||
import (
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestNewDispatchesByForgeType(t *testing.T) {
|
||||
// Gitea client construction makes a network call to /api/v1/version, so
|
||||
// its happy path is covered separately in TestNewGitea against a fake
|
||||
// server rather than here.
|
||||
tests := []struct {
|
||||
name string
|
||||
forgeType string
|
||||
wantErr bool
|
||||
}{
|
||||
{name: "github", forgeType: "github"},
|
||||
{name: "none", forgeType: "none"},
|
||||
{name: "off", forgeType: "off"},
|
||||
{name: "disabled", forgeType: "disabled"},
|
||||
{name: "empty defaults to noop", forgeType: ""},
|
||||
{name: "unsupported type errors", forgeType: "bitbucket", wantErr: true},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
f, err := New(tt.forgeType, "token", "", nil)
|
||||
if tt.wantErr {
|
||||
if err == nil {
|
||||
t.Fatalf("New(%q) error = nil, want error", tt.forgeType)
|
||||
}
|
||||
if f != nil {
|
||||
t.Fatalf("New(%q) forge = %v, want nil on error", tt.forgeType, f)
|
||||
}
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatalf("New(%q) error = %v, want nil", tt.forgeType, err)
|
||||
}
|
||||
if f == nil {
|
||||
t.Fatalf("New(%q) forge = nil, want non-nil", tt.forgeType)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewGitea(t *testing.T) {
|
||||
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
|
||||
if r.URL.Path == "/api/v1/version" {
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
_, _ = w.Write([]byte(`{"version":"1.21.0"}`))
|
||||
return
|
||||
}
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
}))
|
||||
defer srv.Close()
|
||||
|
||||
f, err := New("gitea", "token", srv.URL, nil)
|
||||
if err != nil {
|
||||
t.Fatalf("New(\"gitea\") error = %v, want nil", err)
|
||||
}
|
||||
if f == nil {
|
||||
t.Fatal("New(\"gitea\") forge = nil, want non-nil")
|
||||
}
|
||||
}
|
||||
|
||||
func TestNewGiteaUnreachableHost(t *testing.T) {
|
||||
if _, err := New("gitea", "token", "http://127.0.0.1:0", nil); err == nil {
|
||||
t.Fatal("New(\"gitea\") with unreachable host error = nil, want error")
|
||||
}
|
||||
}
|
||||
@@ -1,419 +0,0 @@
|
||||
package forge
|
||||
|
||||
import (
|
||||
"io"
|
||||
"net/http"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestGiteaAssignedIssuesExcludesPRs(t *testing.T) {
|
||||
c, mux := newTestGiteaClient(t)
|
||||
mux.HandleFunc("GET /api/v1/repos/o/r/issues", func(w http.ResponseWriter, r *http.Request) {
|
||||
if got := r.URL.Query().Get("assigned_by"); got != "archie-bot" {
|
||||
t.Errorf("assigned_by = %q", got)
|
||||
}
|
||||
writeJSON(t, w, []map[string]any{
|
||||
{"number": 1, "title": "real issue", "body": "b", "labels": []map[string]any{{"name": "bug"}}},
|
||||
{"number": 2, "title": "a pr", "pull_request": map[string]any{"url": "x"}},
|
||||
})
|
||||
})
|
||||
|
||||
issues, err := c.AssignedIssues(t.Context(), "o", "r", "archie-bot")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(issues) != 1 || issues[0].Number != 1 || issues[0].Title != "real issue" || len(issues[0].Labels) != 1 || issues[0].Labels[0] != "bug" {
|
||||
t.Fatalf("issues = %+v", issues)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGiteaIssuesWithLabelExcludesPRs(t *testing.T) {
|
||||
c, mux := newTestGiteaClient(t)
|
||||
mux.HandleFunc("GET /api/v1/repos/o/r/issues", func(w http.ResponseWriter, r *http.Request) {
|
||||
if got := r.URL.Query().Get("labels"); got != "widget" {
|
||||
t.Errorf("labels = %q", got)
|
||||
}
|
||||
writeJSON(t, w, []map[string]any{
|
||||
{"number": 3, "title": "labelled", "body": "b"},
|
||||
})
|
||||
})
|
||||
|
||||
issues, err := c.IssuesWithLabel(t.Context(), "o", "r", "widget")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(issues) != 1 || issues[0].Number != 3 {
|
||||
t.Fatalf("issues = %+v", issues)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGiteaAssignedIssuesError(t *testing.T) {
|
||||
c, mux := newTestGiteaClient(t)
|
||||
mux.HandleFunc("GET /api/v1/repos/o/r/issues", func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
})
|
||||
|
||||
if _, err := c.AssignedIssues(t.Context(), "o", "r", "archie-bot"); err == nil {
|
||||
t.Fatal("AssignedIssues() error = nil, want error")
|
||||
}
|
||||
}
|
||||
|
||||
func TestGiteaComment(t *testing.T) {
|
||||
c, mux := newTestGiteaClient(t)
|
||||
mux.HandleFunc("POST /api/v1/repos/o/r/issues/5/comments", func(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(t, w, map[string]any{"id": 42})
|
||||
})
|
||||
|
||||
id, err := c.Comment(t.Context(), "o", "r", 5, "hello")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if id != 42 {
|
||||
t.Fatalf("id = %d, want 42", id)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGiteaCreatePR(t *testing.T) {
|
||||
c, mux := newTestGiteaClient(t)
|
||||
mux.HandleFunc("POST /api/v1/repos/o/r/pulls", func(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(t, w, map[string]any{"number": 7})
|
||||
})
|
||||
|
||||
num, err := c.CreatePR(t.Context(), "o", "r", "title", "head", "base", "body")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if num != 7 {
|
||||
t.Fatalf("num = %d, want 7", num)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGiteaCreatePRError(t *testing.T) {
|
||||
c, mux := newTestGiteaClient(t)
|
||||
mux.HandleFunc("POST /api/v1/repos/o/r/pulls", func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusUnprocessableEntity)
|
||||
})
|
||||
|
||||
if _, err := c.CreatePR(t.Context(), "o", "r", "title", "head", "base", "body"); err == nil {
|
||||
t.Fatal("CreatePR() error = nil, want error")
|
||||
}
|
||||
}
|
||||
|
||||
func TestGiteaPRState(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
status int
|
||||
body map[string]any
|
||||
want string
|
||||
wantErr bool
|
||||
}{
|
||||
{name: "open", status: http.StatusOK, body: map[string]any{"number": 1, "state": "open", "merged": false}, want: "open"},
|
||||
{name: "merged", status: http.StatusOK, body: map[string]any{"number": 1, "state": "closed", "merged": true}, want: "merged"},
|
||||
{name: "not found treated as closed", status: http.StatusNotFound, body: map[string]any{"message": "not found"}, want: "closed"},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
c, mux := newTestGiteaClient(t)
|
||||
mux.HandleFunc("GET /api/v1/repos/o/r/pulls/1", func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(tt.status)
|
||||
if tt.body != nil {
|
||||
writeJSON(t, w, tt.body)
|
||||
}
|
||||
})
|
||||
|
||||
state, err := c.PRState(t.Context(), "o", "r", 1)
|
||||
if tt.wantErr {
|
||||
if err == nil {
|
||||
t.Fatal("PRState() error = nil, want error")
|
||||
}
|
||||
return
|
||||
}
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if state != tt.want {
|
||||
t.Fatalf("state = %q, want %q", state, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestGiteaGetPullRequest(t *testing.T) {
|
||||
c, mux := newTestGiteaClient(t)
|
||||
mux.HandleFunc("GET /api/v1/repos/o/r/pulls/7", func(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(t, w, map[string]any{
|
||||
"number": 7, "title": "Add widget", "body": "Why",
|
||||
"state": "open", "merged": false,
|
||||
"head": map[string]any{"ref": "feature/widget", "sha": "headsha"},
|
||||
"base": map[string]any{"ref": "main", "sha": "basesha"},
|
||||
})
|
||||
})
|
||||
|
||||
pr, err := c.GetPullRequest(t.Context(), "o", "r", 7)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
want := PullRequest{Number: 7, Title: "Add widget", Body: "Why", HeadRef: "feature/widget", BaseRef: "main", HeadSHA: "headsha", BaseSHA: "basesha", State: "open"}
|
||||
if pr != want {
|
||||
t.Fatalf("GetPullRequest = %+v, want %+v", pr, want)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGiteaGetPullRequestMissingHeadDoesNotPanic(t *testing.T) {
|
||||
c, mux := newTestGiteaClient(t)
|
||||
// Gitea returns head: null when a PR's head branch was deleted.
|
||||
mux.HandleFunc("GET /api/v1/repos/o/r/pulls/7", func(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(t, w, map[string]any{
|
||||
"number": 7, "title": "Add widget", "state": "closed", "merged": true,
|
||||
"head": nil, "base": nil,
|
||||
})
|
||||
})
|
||||
|
||||
if _, err := c.GetPullRequest(t.Context(), "o", "r", 7); err == nil {
|
||||
t.Fatal("GetPullRequest error = nil, want a missing-head/base error rather than a panic")
|
||||
}
|
||||
}
|
||||
|
||||
func TestGiteaCloseIssueWithComment(t *testing.T) {
|
||||
c, mux := newTestGiteaClient(t)
|
||||
var commented, closed bool
|
||||
mux.HandleFunc("POST /api/v1/repos/o/r/issues/9/comments", func(w http.ResponseWriter, r *http.Request) {
|
||||
commented = true
|
||||
writeJSON(t, w, map[string]any{"id": 1})
|
||||
})
|
||||
mux.HandleFunc("PATCH /api/v1/repos/o/r/issues/9", func(w http.ResponseWriter, r *http.Request) {
|
||||
closed = true
|
||||
writeJSON(t, w, map[string]any{"number": 9, "state": "closed"})
|
||||
})
|
||||
|
||||
if err := c.CloseIssue(t.Context(), "o", "r", 9, "final comment"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !commented || !closed {
|
||||
t.Fatalf("commented=%t closed=%t, want both true", commented, closed)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGiteaCloseIssueWithoutComment(t *testing.T) {
|
||||
c, mux := newTestGiteaClient(t)
|
||||
var commented bool
|
||||
mux.HandleFunc("POST /api/v1/repos/o/r/issues/9/comments", func(w http.ResponseWriter, r *http.Request) {
|
||||
commented = true
|
||||
})
|
||||
mux.HandleFunc("PATCH /api/v1/repos/o/r/issues/9", func(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(t, w, map[string]any{"number": 9, "state": "closed"})
|
||||
})
|
||||
|
||||
if err := c.CloseIssue(t.Context(), "o", "r", 9, ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if commented {
|
||||
t.Fatal("commented = true, want false when comment is empty")
|
||||
}
|
||||
}
|
||||
|
||||
func TestGiteaReact(t *testing.T) {
|
||||
c, mux := newTestGiteaClient(t)
|
||||
var got string
|
||||
mux.HandleFunc("POST /api/v1/repos/o/r/issues/1/reactions", func(w http.ResponseWriter, r *http.Request) {
|
||||
got = "called"
|
||||
writeJSON(t, w, map[string]any{"content": "+1"})
|
||||
})
|
||||
|
||||
if err := c.React(t.Context(), "o", "r", 1, "+1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got != "called" {
|
||||
t.Fatal("reaction endpoint was not called")
|
||||
}
|
||||
}
|
||||
|
||||
func TestGiteaAcceptInvitationsIsNoop(t *testing.T) {
|
||||
c, _ := newTestGiteaClient(t)
|
||||
if err := c.AcceptInvitations(t.Context()); err != nil {
|
||||
t.Fatalf("AcceptInvitations() = %v, want nil", err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGiteaVerifyPush(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
status int
|
||||
body map[string]any
|
||||
wantErr bool
|
||||
}{
|
||||
{name: "has push", status: http.StatusOK, body: map[string]any{"permissions": map[string]any{"push": true}}},
|
||||
{name: "no push", status: http.StatusOK, body: map[string]any{"permissions": map[string]any{"push": false}}, wantErr: true},
|
||||
{name: "not found", status: http.StatusNotFound, wantErr: true},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
c, mux := newTestGiteaClient(t)
|
||||
mux.HandleFunc("GET /api/v1/repos/o/r", func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(tt.status)
|
||||
if tt.body != nil {
|
||||
writeJSON(t, w, tt.body)
|
||||
}
|
||||
})
|
||||
|
||||
err := c.VerifyPush(t.Context(), "o", "r")
|
||||
if tt.wantErr && err == nil {
|
||||
t.Fatal("VerifyPush() error = nil, want error")
|
||||
}
|
||||
if !tt.wantErr && err != nil {
|
||||
t.Fatalf("VerifyPush() error = %v, want nil", err)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestGiteaLinkBranch(t *testing.T) {
|
||||
c, mux := newTestGiteaClient(t)
|
||||
mux.HandleFunc("POST /api/v1/repos/o/r/issues/3/refs", func(w http.ResponseWriter, r *http.Request) {
|
||||
if got := r.Header.Get("Authorization"); got != "token token" {
|
||||
t.Errorf("Authorization = %q", got)
|
||||
}
|
||||
w.WriteHeader(http.StatusOK)
|
||||
})
|
||||
|
||||
if err := c.LinkBranch(t.Context(), "o", "r", 3, "feature-branch"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGiteaLinkBranchError(t *testing.T) {
|
||||
c, mux := newTestGiteaClient(t)
|
||||
mux.HandleFunc("POST /api/v1/repos/o/r/issues/3/refs", func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
})
|
||||
|
||||
if err := c.LinkBranch(t.Context(), "o", "r", 3, "feature-branch"); err == nil {
|
||||
t.Fatal("LinkBranch() error = nil, want error")
|
||||
}
|
||||
}
|
||||
|
||||
func TestGiteaSetStateLabelSwapsLabels(t *testing.T) {
|
||||
c, mux := newTestGiteaClient(t)
|
||||
mux.HandleFunc("GET /api/v1/repos/o/r/issues/4", func(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(t, w, map[string]any{
|
||||
"number": 4,
|
||||
"labels": []map[string]any{
|
||||
{"id": 1, "name": "archie:queued"},
|
||||
{"id": 2, "name": "keep-me"},
|
||||
},
|
||||
})
|
||||
})
|
||||
var deletedID int64
|
||||
mux.HandleFunc("DELETE /api/v1/repos/o/r/issues/4/labels/1", func(w http.ResponseWriter, r *http.Request) {
|
||||
deletedID = 1
|
||||
w.WriteHeader(http.StatusOK)
|
||||
})
|
||||
mux.HandleFunc("GET /api/v1/repos/o/r/labels", func(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(t, w, []map[string]any{{"id": 9, "name": "archie:working"}})
|
||||
})
|
||||
var added []int64
|
||||
mux.HandleFunc("POST /api/v1/repos/o/r/issues/4/labels", func(w http.ResponseWriter, r *http.Request) {
|
||||
added = []int64{9}
|
||||
writeJSON(t, w, []map[string]any{{"id": 9, "name": "archie:working"}})
|
||||
})
|
||||
|
||||
known := []string{"archie:queued", "archie:working", "archie:waiting"}
|
||||
c.SetStateLabel(t.Context(), "o", "r", 4, "archie:working", known)
|
||||
|
||||
if deletedID != 1 {
|
||||
t.Errorf("deletedID = %d, want 1 (archie:queued removed)", deletedID)
|
||||
}
|
||||
if len(added) != 1 || added[0] != 9 {
|
||||
t.Errorf("added = %v, want [9]", added)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGiteaSetStateLabelAlreadyPresentIsNoop(t *testing.T) {
|
||||
c, mux := newTestGiteaClient(t)
|
||||
mux.HandleFunc("GET /api/v1/repos/o/r/issues/4", func(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(t, w, map[string]any{
|
||||
"number": 4,
|
||||
"labels": []map[string]any{{"id": 9, "name": "archie:working"}},
|
||||
})
|
||||
})
|
||||
called := false
|
||||
mux.HandleFunc("POST /api/v1/repos/o/r/issues/4/labels", func(w http.ResponseWriter, r *http.Request) {
|
||||
called = true
|
||||
})
|
||||
|
||||
c.SetStateLabel(t.Context(), "o", "r", 4, "archie:working", []string{"archie:working"})
|
||||
|
||||
if called {
|
||||
t.Fatal("AddIssueLabels was called, want no-op when label already present")
|
||||
}
|
||||
}
|
||||
|
||||
func TestGiteaSetStateLabelEmptyClearsAll(t *testing.T) {
|
||||
c, mux := newTestGiteaClient(t)
|
||||
mux.HandleFunc("GET /api/v1/repos/o/r/issues/4", func(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(t, w, map[string]any{
|
||||
"number": 4,
|
||||
"labels": []map[string]any{{"id": 1, "name": "archie:queued"}},
|
||||
})
|
||||
})
|
||||
deleted := false
|
||||
mux.HandleFunc("DELETE /api/v1/repos/o/r/issues/4/labels/1", func(w http.ResponseWriter, r *http.Request) {
|
||||
deleted = true
|
||||
w.WriteHeader(http.StatusOK)
|
||||
})
|
||||
added := false
|
||||
mux.HandleFunc("POST /api/v1/repos/o/r/issues/4/labels", func(w http.ResponseWriter, r *http.Request) {
|
||||
added = true
|
||||
})
|
||||
|
||||
c.SetStateLabel(t.Context(), "o", "r", 4, "", []string{"archie:queued"})
|
||||
|
||||
if !deleted {
|
||||
t.Error("deleted = false, want true (archie:queued removed)")
|
||||
}
|
||||
if added {
|
||||
t.Error("added = true, want false (empty label clears all)")
|
||||
}
|
||||
}
|
||||
|
||||
func TestLabelNamesGitea(t *testing.T) {
|
||||
names := labelNamesGitea(nil)
|
||||
if names != nil {
|
||||
t.Fatalf("labelNamesGitea(nil) = %v, want nil", names)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGiteaGetPullRequestDiff(t *testing.T) {
|
||||
c, mux := newTestGiteaClient(t)
|
||||
mux.HandleFunc("GET /api/v1/repos/o/r/pulls/7.diff", func(w http.ResponseWriter, r *http.Request) {
|
||||
_, _ = w.Write([]byte("diff --git a/f.go b/f.go\n+added\n"))
|
||||
})
|
||||
|
||||
diff, err := c.GetPullRequestDiff(t.Context(), "o", "r", 7)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if diff != "diff --git a/f.go b/f.go\n+added\n" {
|
||||
t.Fatalf("diff = %q", diff)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGiteaGetRepoArchive(t *testing.T) {
|
||||
c, mux := newTestGiteaClient(t)
|
||||
mux.HandleFunc("GET /api/v1/repos/o/r/archive/deadbeef.tar.gz", func(w http.ResponseWriter, r *http.Request) {
|
||||
_, _ = w.Write([]byte("fake-tar-bytes"))
|
||||
})
|
||||
|
||||
rc, err := c.GetRepoArchive(t.Context(), "o", "r", "deadbeef")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer rc.Close()
|
||||
body, err := io.ReadAll(rc)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if string(body) != "fake-tar-bytes" {
|
||||
t.Fatalf("archive body = %q", body)
|
||||
}
|
||||
}
|
||||
@@ -1,31 +0,0 @@
|
||||
package forge
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"code.gitea.io/sdk/gitea"
|
||||
)
|
||||
|
||||
// newTestGiteaClient wires a GiteaClient at a local httptest server so its
|
||||
// methods can be exercised without hitting a real Gitea instance. The
|
||||
// caller's mux handles every route except /api/v1/version, which this
|
||||
// registers so client construction (which probes it) succeeds.
|
||||
func newTestGiteaClient(t *testing.T) (*GiteaClient, *http.ServeMux) {
|
||||
t.Helper()
|
||||
mux := http.NewServeMux()
|
||||
mux.HandleFunc("GET /api/v1/version", func(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(t, w, map[string]string{"version": "1.21.0"})
|
||||
})
|
||||
srv := httptest.NewServer(mux)
|
||||
t.Cleanup(srv.Close)
|
||||
|
||||
cli, err := gitea.NewClient(srv.URL, gitea.SetToken("token"))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
return &GiteaClient{cli: cli, host: srv.URL, token: "token", log: slog.New(slog.DiscardHandler)}, mux
|
||||
}
|
||||
@@ -1,447 +0,0 @@
|
||||
package forge
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"io"
|
||||
"net/http"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func writeJSON(t *testing.T, w http.ResponseWriter, v any) {
|
||||
t.Helper()
|
||||
w.Header().Set("Content-Type", "application/json")
|
||||
if err := json.NewEncoder(w).Encode(v); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAssignedIssuesExcludesPRs(t *testing.T) {
|
||||
c, mux := newTestClient(t)
|
||||
mux.HandleFunc("GET /repos/o/r/issues", func(w http.ResponseWriter, r *http.Request) {
|
||||
if got := r.URL.Query().Get("assignee"); got != "archie-bot" {
|
||||
t.Errorf("assignee = %q", got)
|
||||
}
|
||||
writeJSON(t, w, []map[string]any{
|
||||
{"number": 1, "title": "real issue", "body": "b", "labels": []map[string]any{{"name": "bug"}}},
|
||||
{"number": 2, "title": "a pr", "pull_request": map[string]any{"url": "x"}},
|
||||
})
|
||||
})
|
||||
|
||||
issues, err := c.AssignedIssues(t.Context(), "o", "r", "archie-bot")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(issues) != 1 || issues[0].Number != 1 || issues[0].Title != "real issue" || len(issues[0].Labels) != 1 || issues[0].Labels[0] != "bug" {
|
||||
t.Fatalf("issues = %+v", issues)
|
||||
}
|
||||
}
|
||||
|
||||
func TestIssuesWithLabelExcludesPRs(t *testing.T) {
|
||||
c, mux := newTestClient(t)
|
||||
mux.HandleFunc("GET /repos/o/r/issues", func(w http.ResponseWriter, r *http.Request) {
|
||||
if got := r.URL.Query().Get("labels"); got != "widget" {
|
||||
t.Errorf("labels = %q", got)
|
||||
}
|
||||
writeJSON(t, w, []map[string]any{
|
||||
{"number": 3, "title": "labelled", "body": "b"},
|
||||
})
|
||||
})
|
||||
|
||||
issues, err := c.IssuesWithLabel(t.Context(), "o", "r", "widget")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(issues) != 1 || issues[0].Number != 3 {
|
||||
t.Fatalf("issues = %+v", issues)
|
||||
}
|
||||
}
|
||||
|
||||
func TestComment(t *testing.T) {
|
||||
c, mux := newTestClient(t)
|
||||
mux.HandleFunc("POST /repos/o/r/issues/5/comments", func(w http.ResponseWriter, r *http.Request) {
|
||||
var body map[string]string
|
||||
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if body["body"] != "hello" {
|
||||
t.Errorf("comment body = %q", body["body"])
|
||||
}
|
||||
writeJSON(t, w, map[string]any{"id": 42})
|
||||
})
|
||||
|
||||
id, err := c.Comment(t.Context(), "o", "r", 5, "hello")
|
||||
if err != nil || id != 42 {
|
||||
t.Fatalf("Comment = (%d, %v)", id, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCreatePR(t *testing.T) {
|
||||
c, mux := newTestClient(t)
|
||||
mux.HandleFunc("POST /repos/o/r/pulls", func(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(t, w, map[string]any{"number": 9})
|
||||
})
|
||||
|
||||
n, err := c.CreatePR(t.Context(), "o", "r", "title", "head", "base", "body")
|
||||
if err != nil || n != 9 {
|
||||
t.Fatalf("CreatePR = (%d, %v)", n, err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestPRState(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
json map[string]any
|
||||
want string
|
||||
}{
|
||||
{"merged", map[string]any{"merged": true, "state": "closed"}, "merged"},
|
||||
{"open", map[string]any{"merged": false, "state": "open"}, "open"},
|
||||
{"closed", map[string]any{"merged": false, "state": "closed"}, "closed"},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
c, mux := newTestClient(t)
|
||||
mux.HandleFunc("GET /repos/o/r/pulls/7", func(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(t, w, tt.json)
|
||||
})
|
||||
got, err := c.PRState(t.Context(), "o", "r", 7)
|
||||
if err != nil || got != tt.want {
|
||||
t.Fatalf("PRState = (%q, %v), want %q", got, err, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetPullRequest(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
json map[string]any
|
||||
want PullRequest
|
||||
}{
|
||||
{
|
||||
name: "open",
|
||||
json: map[string]any{
|
||||
"number": 7, "title": "Add widget", "body": "Why this matters",
|
||||
"state": "open", "merged": false,
|
||||
"head": map[string]any{"ref": "feature/widget", "sha": "headsha"},
|
||||
"base": map[string]any{"ref": "main", "sha": "basesha"},
|
||||
},
|
||||
want: PullRequest{Number: 7, Title: "Add widget", Body: "Why this matters", HeadRef: "feature/widget", BaseRef: "main", HeadSHA: "headsha", BaseSHA: "basesha", State: "open"},
|
||||
},
|
||||
{
|
||||
name: "merged",
|
||||
json: map[string]any{
|
||||
"number": 7, "title": "Add widget", "body": "",
|
||||
"state": "closed", "merged": true,
|
||||
"head": map[string]any{"ref": "feature/widget", "sha": "headsha"},
|
||||
"base": map[string]any{"ref": "main", "sha": "basesha"},
|
||||
},
|
||||
want: PullRequest{Number: 7, Title: "Add widget", HeadRef: "feature/widget", BaseRef: "main", HeadSHA: "headsha", BaseSHA: "basesha", State: "merged"},
|
||||
},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
c, mux := newTestClient(t)
|
||||
mux.HandleFunc("GET /repos/o/r/pulls/7", func(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(t, w, tt.json)
|
||||
})
|
||||
got, err := c.GetPullRequest(t.Context(), "o", "r", 7)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got != tt.want {
|
||||
t.Fatalf("GetPullRequest = %+v, want %+v", got, tt.want)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestCloseIssueWithComment(t *testing.T) {
|
||||
c, mux := newTestClient(t)
|
||||
var commented, edited bool
|
||||
mux.HandleFunc("POST /repos/o/r/issues/5/comments", func(w http.ResponseWriter, r *http.Request) {
|
||||
commented = true
|
||||
writeJSON(t, w, map[string]any{"id": 1})
|
||||
})
|
||||
mux.HandleFunc("PATCH /repos/o/r/issues/5", func(w http.ResponseWriter, r *http.Request) {
|
||||
edited = true
|
||||
var body map[string]string
|
||||
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if body["state"] != "closed" {
|
||||
t.Errorf("state = %q", body["state"])
|
||||
}
|
||||
writeJSON(t, w, map[string]any{"number": 5, "state": "closed"})
|
||||
})
|
||||
|
||||
if err := c.CloseIssue(t.Context(), "o", "r", 5, "won't do"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if !commented || !edited {
|
||||
t.Fatalf("commented=%v edited=%v", commented, edited)
|
||||
}
|
||||
}
|
||||
|
||||
func TestCloseIssueWithoutComment(t *testing.T) {
|
||||
c, mux := newTestClient(t)
|
||||
mux.HandleFunc("POST /repos/o/r/issues/5/comments", func(w http.ResponseWriter, r *http.Request) {
|
||||
t.Fatal("should not comment when comment is empty")
|
||||
})
|
||||
mux.HandleFunc("PATCH /repos/o/r/issues/5", func(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(t, w, map[string]any{"number": 5, "state": "closed"})
|
||||
})
|
||||
|
||||
if err := c.CloseIssue(t.Context(), "o", "r", 5, ""); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestReact(t *testing.T) {
|
||||
c, mux := newTestClient(t)
|
||||
mux.HandleFunc("POST /repos/o/r/issues/5/reactions", func(w http.ResponseWriter, r *http.Request) {
|
||||
var body map[string]string
|
||||
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if body["content"] != "+1" {
|
||||
t.Errorf("content = %q", body["content"])
|
||||
}
|
||||
writeJSON(t, w, map[string]any{"id": 1, "content": "+1"})
|
||||
})
|
||||
|
||||
if err := c.React(t.Context(), "o", "r", 5, "+1"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSetStateLabelSwapsLabels(t *testing.T) {
|
||||
c, mux := newTestClient(t)
|
||||
var removed, added, created []string
|
||||
|
||||
mux.HandleFunc("GET /repos/o/r/issues/5", func(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(t, w, map[string]any{
|
||||
"number": 5,
|
||||
"labels": []map[string]any{{"name": "archie:queued"}, {"name": "bug"}},
|
||||
})
|
||||
})
|
||||
mux.HandleFunc("DELETE /repos/o/r/issues/5/labels/archie:queued", func(w http.ResponseWriter, r *http.Request) {
|
||||
removed = append(removed, "archie:queued")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
})
|
||||
mux.HandleFunc("POST /repos/o/r/labels", func(w http.ResponseWriter, r *http.Request) {
|
||||
var body map[string]string
|
||||
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
created = append(created, body["name"])
|
||||
writeJSON(t, w, map[string]any{"name": body["name"], "color": body["color"]})
|
||||
})
|
||||
mux.HandleFunc("POST /repos/o/r/issues/5/labels", func(w http.ResponseWriter, r *http.Request) {
|
||||
var body []string
|
||||
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
added = append(added, body...)
|
||||
writeJSON(t, w, []map[string]any{})
|
||||
})
|
||||
|
||||
known := []string{"archie:queued", "archie:working", "archie:waiting", "archie:pr", "archie:parked"}
|
||||
c.SetStateLabel(t.Context(), "o", "r", 5, "archie:working", known)
|
||||
|
||||
if len(removed) != 1 || removed[0] != "archie:queued" {
|
||||
t.Fatalf("removed = %v", removed)
|
||||
}
|
||||
if len(created) != 1 || created[0] != "archie:working" {
|
||||
t.Fatalf("created = %v", created)
|
||||
}
|
||||
if len(added) != 1 || added[0] != "archie:working" {
|
||||
t.Fatalf("added = %v", added)
|
||||
}
|
||||
|
||||
// Second call for the same label reuses the ensured-labels cache and
|
||||
// skips label creation.
|
||||
mux.HandleFunc("GET /repos/o/r/issues/6", func(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(t, w, map[string]any{"number": 6, "labels": []map[string]any{}})
|
||||
})
|
||||
mux.HandleFunc("POST /repos/o/r/issues/6/labels", func(w http.ResponseWriter, r *http.Request) {
|
||||
var body []string
|
||||
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
added = append(added, body...)
|
||||
writeJSON(t, w, []map[string]any{})
|
||||
})
|
||||
c.SetStateLabel(t.Context(), "o", "r", 6, "archie:working", known)
|
||||
if len(created) != 1 {
|
||||
t.Fatalf("expected label creation to be cached, created = %v", created)
|
||||
}
|
||||
}
|
||||
|
||||
func TestSetStateLabelAlreadyPresentIsNoop(t *testing.T) {
|
||||
c, mux := newTestClient(t)
|
||||
mux.HandleFunc("GET /repos/o/r/issues/5", func(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(t, w, map[string]any{
|
||||
"number": 5,
|
||||
"labels": []map[string]any{{"name": "archie:working"}},
|
||||
})
|
||||
})
|
||||
mux.HandleFunc("POST /repos/o/r/issues/5/labels", func(w http.ResponseWriter, r *http.Request) {
|
||||
t.Fatal("should not add a label that's already present")
|
||||
})
|
||||
mux.HandleFunc("POST /repos/o/r/labels", func(w http.ResponseWriter, r *http.Request) {
|
||||
t.Fatal("should not create a label that's already present")
|
||||
})
|
||||
|
||||
c.SetStateLabel(t.Context(), "o", "r", 5, "archie:working", []string{"archie:working"})
|
||||
}
|
||||
|
||||
func TestSetStateLabelEmptyClearsAll(t *testing.T) {
|
||||
c, mux := newTestClient(t)
|
||||
var removed []string
|
||||
mux.HandleFunc("GET /repos/o/r/issues/5", func(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(t, w, map[string]any{
|
||||
"number": 5,
|
||||
"labels": []map[string]any{{"name": "archie:working"}},
|
||||
})
|
||||
})
|
||||
mux.HandleFunc("DELETE /repos/o/r/issues/5/labels/archie:working", func(w http.ResponseWriter, r *http.Request) {
|
||||
removed = append(removed, "archie:working")
|
||||
w.WriteHeader(http.StatusOK)
|
||||
})
|
||||
|
||||
c.SetStateLabel(t.Context(), "o", "r", 5, "", []string{"archie:working"})
|
||||
if len(removed) != 1 {
|
||||
t.Fatalf("removed = %v", removed)
|
||||
}
|
||||
}
|
||||
|
||||
func TestVerifyPush(t *testing.T) {
|
||||
t.Run("has push", func(t *testing.T) {
|
||||
c, mux := newTestClient(t)
|
||||
mux.HandleFunc("GET /repos/o/r", func(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(t, w, map[string]any{"permissions": map[string]bool{"push": true}})
|
||||
})
|
||||
if err := c.VerifyPush(t.Context(), "o", "r"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("no push", func(t *testing.T) {
|
||||
c, mux := newTestClient(t)
|
||||
mux.HandleFunc("GET /repos/o/r", func(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(t, w, map[string]any{"permissions": map[string]bool{"push": false}})
|
||||
})
|
||||
if err := c.VerifyPush(t.Context(), "o", "r"); err == nil {
|
||||
t.Fatal("expected error for missing push permission")
|
||||
}
|
||||
})
|
||||
|
||||
t.Run("api error", func(t *testing.T) {
|
||||
c, mux := newTestClient(t)
|
||||
mux.HandleFunc("GET /repos/o/r", func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
})
|
||||
if err := c.VerifyPush(t.Context(), "o", "r"); err == nil {
|
||||
t.Fatal("expected error for 404")
|
||||
}
|
||||
})
|
||||
}
|
||||
|
||||
func TestAcceptInvitations(t *testing.T) {
|
||||
c, mux := newTestClient(t)
|
||||
var accepted []string
|
||||
mux.HandleFunc("GET /user/repository_invitations", func(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(t, w, []map[string]any{
|
||||
{"id": 1, "repository": map[string]any{"full_name": "o/ok"}},
|
||||
{"id": 2, "repository": map[string]any{"full_name": "o/fails"}},
|
||||
})
|
||||
})
|
||||
mux.HandleFunc("PATCH /user/repository_invitations/1", func(w http.ResponseWriter, r *http.Request) {
|
||||
accepted = append(accepted, "1")
|
||||
w.WriteHeader(http.StatusNoContent)
|
||||
})
|
||||
mux.HandleFunc("PATCH /user/repository_invitations/2", func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
})
|
||||
|
||||
// A single failing invitation must not stop the others from being
|
||||
// processed or fail the whole call.
|
||||
if err := c.AcceptInvitations(t.Context()); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(accepted) != 1 || accepted[0] != "1" {
|
||||
t.Fatalf("accepted = %v", accepted)
|
||||
}
|
||||
}
|
||||
|
||||
func TestAcceptInvitationsListError(t *testing.T) {
|
||||
c, mux := newTestClient(t)
|
||||
mux.HandleFunc("GET /user/repository_invitations", func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusInternalServerError)
|
||||
})
|
||||
if err := c.AcceptInvitations(t.Context()); err == nil {
|
||||
t.Fatal("expected error")
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetPullRequestDiff(t *testing.T) {
|
||||
c, mux := newTestClient(t)
|
||||
mux.HandleFunc("GET /repos/o/r/pulls/7", func(w http.ResponseWriter, r *http.Request) {
|
||||
if got := r.Header.Get("Accept"); got == "" {
|
||||
t.Errorf("Accept header not set for a raw diff request")
|
||||
}
|
||||
_, _ = w.Write([]byte("diff --git a/f.go b/f.go\n+added\n"))
|
||||
})
|
||||
|
||||
diff, err := c.GetPullRequestDiff(t.Context(), "o", "r", 7)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if diff != "diff --git a/f.go b/f.go\n+added\n" {
|
||||
t.Fatalf("diff = %q", diff)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetRepoArchive(t *testing.T) {
|
||||
c, mux := newTestClient(t)
|
||||
mux.HandleFunc("GET /repos/o/r/tarball/deadbeef", func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Location", "http://"+r.Host+"/archive-blob/deadbeef.tar.gz")
|
||||
w.WriteHeader(http.StatusFound)
|
||||
})
|
||||
mux.HandleFunc("GET /archive-blob/deadbeef.tar.gz", func(w http.ResponseWriter, r *http.Request) {
|
||||
// Real GitHub archive links are unauthenticated storage URLs; assert
|
||||
// no forge token leaks onto this second request.
|
||||
if got := r.Header.Get("Authorization"); got != "" {
|
||||
t.Errorf("Authorization header present on the archive blob request: %q", got)
|
||||
}
|
||||
_, _ = w.Write([]byte("fake-tar-bytes"))
|
||||
})
|
||||
|
||||
rc, err := c.GetRepoArchive(t.Context(), "o", "r", "deadbeef")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
defer rc.Close()
|
||||
body, err := io.ReadAll(rc)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if string(body) != "fake-tar-bytes" {
|
||||
t.Fatalf("archive body = %q", body)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGetRepoArchiveNonOKStatus(t *testing.T) {
|
||||
c, mux := newTestClient(t)
|
||||
mux.HandleFunc("GET /repos/o/r/tarball/badref", func(w http.ResponseWriter, r *http.Request) {
|
||||
w.Header().Set("Location", "http://"+r.Host+"/archive-blob/badref.tar.gz")
|
||||
w.WriteHeader(http.StatusFound)
|
||||
})
|
||||
mux.HandleFunc("GET /archive-blob/badref.tar.gz", func(w http.ResponseWriter, r *http.Request) {
|
||||
w.WriteHeader(http.StatusNotFound)
|
||||
})
|
||||
|
||||
if _, err := c.GetRepoArchive(t.Context(), "o", "r", "badref"); err == nil {
|
||||
t.Fatal("want an error for a non-200 archive blob response")
|
||||
}
|
||||
}
|
||||
@@ -1,47 +0,0 @@
|
||||
package forge
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestNewConfiguresHost(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
host string
|
||||
wantBase string
|
||||
wantUpload string
|
||||
}{
|
||||
{
|
||||
name: "github.com",
|
||||
host: "https://github.com",
|
||||
wantBase: "https://api.github.com/",
|
||||
wantUpload: "https://uploads.github.com/",
|
||||
},
|
||||
{
|
||||
name: "enterprise",
|
||||
host: "https://git.example.com",
|
||||
wantBase: "https://git.example.com/api/v3/",
|
||||
wantUpload: "https://git.example.com/api/uploads/",
|
||||
},
|
||||
}
|
||||
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
f, err := New("github", "token", tt.host, slog.New(slog.DiscardHandler))
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
client, ok := f.(*GitHubClient)
|
||||
if !ok {
|
||||
t.Fatalf("f is %T, want *GitHubClient", f)
|
||||
}
|
||||
if got := client.gh.BaseURL.String(); got != tt.wantBase {
|
||||
t.Errorf("BaseURL = %q, want %q", got, tt.wantBase)
|
||||
}
|
||||
if got := client.gh.UploadURL.String(); got != tt.wantUpload {
|
||||
t.Errorf("UploadURL = %q, want %q", got, tt.wantUpload)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
@@ -1,66 +0,0 @@
|
||||
package forge
|
||||
|
||||
import (
|
||||
"context"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestNewNoopDefaultsLogger(t *testing.T) {
|
||||
f := NewNoop(nil)
|
||||
if f == nil {
|
||||
t.Fatal("NewNoop(nil) = nil, want non-nil Forge")
|
||||
}
|
||||
}
|
||||
|
||||
func TestNoopForgeIsAllZeroValue(t *testing.T) {
|
||||
ctx := context.Background()
|
||||
f := NewNoop(nil)
|
||||
|
||||
issues, err := f.AssignedIssues(ctx, "o", "r", "a")
|
||||
if issues != nil || err != nil {
|
||||
t.Errorf("AssignedIssues() = (%v, %v), want (nil, nil)", issues, err)
|
||||
}
|
||||
|
||||
issues, err = f.IssuesWithLabel(ctx, "o", "r", "label")
|
||||
if issues != nil || err != nil {
|
||||
t.Errorf("IssuesWithLabel() = (%v, %v), want (nil, nil)", issues, err)
|
||||
}
|
||||
|
||||
id, err := f.Comment(ctx, "o", "r", 1, "body")
|
||||
if id != 0 || err != nil {
|
||||
t.Errorf("Comment() = (%d, %v), want (0, nil)", id, err)
|
||||
}
|
||||
|
||||
if err := f.CloseIssue(ctx, "o", "r", 1, "comment"); err != nil {
|
||||
t.Errorf("CloseIssue() = %v, want nil", err)
|
||||
}
|
||||
|
||||
if err := f.React(ctx, "o", "r", 1, "+1"); err != nil {
|
||||
t.Errorf("React() = %v, want nil", err)
|
||||
}
|
||||
|
||||
// SetStateLabel has no return value; just confirm it does not panic.
|
||||
f.SetStateLabel(ctx, "o", "r", 1, "label", nil)
|
||||
|
||||
prNum, err := f.CreatePR(ctx, "o", "r", "title", "head", "base", "body")
|
||||
if prNum != 0 || err != nil {
|
||||
t.Errorf("CreatePR() = (%d, %v), want (0, nil)", prNum, err)
|
||||
}
|
||||
|
||||
state, err := f.PRState(ctx, "o", "r", 1)
|
||||
if state != "closed" || err != nil {
|
||||
t.Errorf("PRState() = (%q, %v), want (\"closed\", nil)", state, err)
|
||||
}
|
||||
|
||||
if err := f.AcceptInvitations(ctx); err != nil {
|
||||
t.Errorf("AcceptInvitations() = %v, want nil", err)
|
||||
}
|
||||
|
||||
if err := f.VerifyPush(ctx, "o", "r"); err != nil {
|
||||
t.Errorf("VerifyPush() = %v, want nil", err)
|
||||
}
|
||||
|
||||
if err := f.LinkBranch(ctx, "o", "r", 1, "branch"); err != nil {
|
||||
t.Errorf("LinkBranch() = %v, want nil", err)
|
||||
}
|
||||
}
|
||||
@@ -1,190 +0,0 @@
|
||||
package forge
|
||||
|
||||
import (
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestGitHubListReviews(t *testing.T) {
|
||||
c, mux := newTestClient(t)
|
||||
mux.HandleFunc("GET /repos/o/r/pulls/7/reviews", func(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(t, w, []map[string]any{
|
||||
{"id": 1, "state": "APPROVED", "user": map[string]any{"login": "alice"}},
|
||||
{"id": 2, "state": "CHANGES_REQUESTED", "user": map[string]any{"login": "bob"}},
|
||||
})
|
||||
})
|
||||
|
||||
reviews, err := c.ListReviews(t.Context(), "o", "r", 7, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(reviews) != 2 {
|
||||
t.Fatalf("reviews = %d, want 2", len(reviews))
|
||||
}
|
||||
if reviews[0].ID != 1 || reviews[0].Author != "alice" || reviews[0].State != ReviewStateApproved {
|
||||
t.Errorf("reviews[0] = %+v", reviews[0])
|
||||
}
|
||||
if reviews[1].State != ReviewStateRequestedChanges {
|
||||
t.Errorf("reviews[1].State = %q, want %q", reviews[1].State, ReviewStateRequestedChanges)
|
||||
}
|
||||
|
||||
// sinceID cursor excludes already-seen reviews.
|
||||
reviews, err = c.ListReviews(t.Context(), "o", "r", 7, 1)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(reviews) != 1 || reviews[0].ID != 2 {
|
||||
t.Fatalf("sinceID-filtered reviews = %+v, want only id 2", reviews)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGitHubListReviewComments(t *testing.T) {
|
||||
c, mux := newTestClient(t)
|
||||
mux.HandleFunc("GET /repos/o/r/pulls/7/comments", func(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(t, w, []map[string]any{
|
||||
{"id": 10, "body": "nil deref here", "path": "a.go", "original_line": 42, "in_reply_to_id": 5, "user": map[string]any{"login": "alice"}},
|
||||
})
|
||||
})
|
||||
|
||||
comments, err := c.ListReviewComments(t.Context(), "o", "r", 7, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(comments) != 1 {
|
||||
t.Fatalf("comments = %d, want 1", len(comments))
|
||||
}
|
||||
got := comments[0]
|
||||
if got.ID != 10 || got.Author != "alice" || got.Body != "nil deref here" ||
|
||||
got.Path != "a.go" || got.Line != 42 || got.InReplyTo != 5 {
|
||||
t.Errorf("comment = %+v", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGitHubReplyToReview(t *testing.T) {
|
||||
c, mux := newTestClient(t)
|
||||
var gotBody map[string]any
|
||||
mux.HandleFunc("POST /repos/o/r/pulls/7/comments", func(w http.ResponseWriter, r *http.Request) {
|
||||
if err := json.NewDecoder(r.Body).Decode(&gotBody); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
writeJSON(t, w, map[string]any{"id": 99})
|
||||
})
|
||||
|
||||
if err := c.ReplyToReview(t.Context(), "o", "r", 7, 42, "fixed"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if gotBody["body"] != "fixed" || gotBody["in_reply_to"] != float64(42) {
|
||||
t.Errorf("request body = %v, want body=fixed in_reply_to=42", gotBody)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGiteaListReviews(t *testing.T) {
|
||||
c, mux := newTestGiteaClient(t)
|
||||
mux.HandleFunc("GET /api/v1/repos/o/r/pulls/7/reviews", func(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(t, w, []map[string]any{
|
||||
{"id": 1, "state": "APPROVED", "user": map[string]any{"login": "alice"}},
|
||||
{"id": 2, "state": "REQUEST_CHANGES", "user": map[string]any{"login": "bob"}},
|
||||
})
|
||||
})
|
||||
|
||||
reviews, err := c.ListReviews(t.Context(), "o", "r", 7, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(reviews) != 2 {
|
||||
t.Fatalf("reviews = %d, want 2", len(reviews))
|
||||
}
|
||||
if reviews[0].State != ReviewStateApproved || reviews[0].Author != "alice" {
|
||||
t.Errorf("reviews[0] = %+v", reviews[0])
|
||||
}
|
||||
if reviews[1].State != ReviewStateRequestedChanges {
|
||||
t.Errorf("reviews[1].State = %q, want %q", reviews[1].State, ReviewStateRequestedChanges)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGiteaListReviewComments(t *testing.T) {
|
||||
c, mux := newTestGiteaClient(t)
|
||||
mux.HandleFunc("GET /api/v1/repos/o/r/pulls/7/reviews", func(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(t, w, []map[string]any{{"id": 3, "state": "COMMENT", "user": map[string]any{"login": "alice"}}})
|
||||
})
|
||||
mux.HandleFunc("GET /api/v1/repos/o/r/pulls/7/reviews/3/comments", func(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(t, w, []map[string]any{
|
||||
{"id": 20, "body": "race here", "path": "b.go", "position": 12, "user": map[string]any{"login": "bob"}},
|
||||
})
|
||||
})
|
||||
|
||||
comments, err := c.ListReviewComments(t.Context(), "o", "r", 7, 0)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(comments) != 1 {
|
||||
t.Fatalf("comments = %d, want 1", len(comments))
|
||||
}
|
||||
got := comments[0]
|
||||
if got.ID != 20 || got.Author != "bob" || got.Body != "race here" || got.Path != "b.go" || got.Line != 12 {
|
||||
t.Errorf("comment = %+v", got)
|
||||
}
|
||||
|
||||
// sinceID cursor excludes already-seen comments.
|
||||
comments, err = c.ListReviewComments(t.Context(), "o", "r", 7, 20)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if len(comments) != 0 {
|
||||
t.Fatalf("sinceID-filtered comments = %+v, want empty", comments)
|
||||
}
|
||||
}
|
||||
|
||||
// TestGiteaListReviewCommentsRejectsLineNumberPastInt pins the bound on the
|
||||
// forge's line number. Gitea reports position as a uint64; past the int range
|
||||
// the conversion wraps negative and reaches a reviewer as a line that cannot
|
||||
// exist.
|
||||
func TestGiteaListReviewCommentsRejectsLineNumberPastInt(t *testing.T) {
|
||||
c, mux := newTestGiteaClient(t)
|
||||
mux.HandleFunc("GET /api/v1/repos/o/r/pulls/7/reviews", func(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(t, w, []map[string]any{{"id": 3, "state": "COMMENT", "user": map[string]any{"login": "alice"}}})
|
||||
})
|
||||
mux.HandleFunc("GET /api/v1/repos/o/r/pulls/7/reviews/3/comments", func(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(t, w, []map[string]any{
|
||||
{"id": 20, "body": "x", "path": "b.go", "position": uint64(1) << 63, "user": map[string]any{"login": "bob"}},
|
||||
})
|
||||
})
|
||||
|
||||
if _, err := c.ListReviewComments(t.Context(), "o", "r", 7, 0); err == nil {
|
||||
t.Fatal("want an error for a line number that does not fit an int")
|
||||
}
|
||||
}
|
||||
|
||||
func TestGiteaReplyToReview(t *testing.T) {
|
||||
c, mux := newTestGiteaClient(t)
|
||||
var got map[string]any
|
||||
mux.HandleFunc("POST /api/v1/repos/o/r/pulls/7/comments/42/replies", func(w http.ResponseWriter, r *http.Request) {
|
||||
if err := json.NewDecoder(r.Body).Decode(&got); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
writeJSON(t, w, map[string]any{"id": 99})
|
||||
})
|
||||
|
||||
if err := c.ReplyToReview(t.Context(), "o", "r", 7, 42, "fixed"); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
if got["body"] != "fixed" {
|
||||
t.Errorf("request body = %v, want body=fixed", got)
|
||||
}
|
||||
}
|
||||
|
||||
func TestNormalizeReviewState(t *testing.T) {
|
||||
tests := map[string]string{
|
||||
"APPROVED": ReviewStateApproved,
|
||||
"CHANGES_REQUESTED": ReviewStateRequestedChanges,
|
||||
"COMMENTED": ReviewStateCommented,
|
||||
"DISMISSED": ReviewStateDismissed,
|
||||
"SOMETHING_NEW": "something_new",
|
||||
}
|
||||
for in, want := range tests {
|
||||
if got := normalizeReviewState(in); got != want {
|
||||
t.Errorf("normalizeReviewState(%q) = %q, want %q", in, got, want)
|
||||
}
|
||||
}
|
||||
}
|
||||
@@ -1,261 +0,0 @@
|
||||
package forge
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"strings"
|
||||
"testing"
|
||||
)
|
||||
|
||||
func TestGitHubCreateReviewComments(t *testing.T) {
|
||||
c, mux := newTestClient(t)
|
||||
// The head SHA is deliberately not "headsha": the comments are anchored to
|
||||
// the revision the forge reports for the pull request, never to a value the
|
||||
// caller supplied. The caller's reviewed revision gates the posting, it is
|
||||
// not the anchor itself.
|
||||
mux.HandleFunc("GET /repos/o/r/pulls/7", func(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(t, w, map[string]any{
|
||||
"number": 7, "title": "Add widget", "state": "open",
|
||||
"head": map[string]any{"ref": "feature/widget", "sha": "pulled-head-sha"},
|
||||
"base": map[string]any{"ref": "main", "sha": "basesha"},
|
||||
})
|
||||
})
|
||||
var got []map[string]any
|
||||
mux.HandleFunc("POST /repos/o/r/pulls/7/comments", func(w http.ResponseWriter, r *http.Request) {
|
||||
var body map[string]any
|
||||
if err := json.NewDecoder(r.Body).Decode(&body); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
got = append(got, body)
|
||||
writeJSON(t, w, map[string]any{"id": 1})
|
||||
})
|
||||
|
||||
comments := []InlineReviewComment{
|
||||
{Path: "a.go", Line: 12, Body: "nil deref"},
|
||||
{Path: "b.go", Line: 3, Body: "```suggestion\nfixed\n```"},
|
||||
}
|
||||
if err := c.CreateReviewComments(t.Context(), "o", "r", 7, "pulled-head-sha", comments); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
if len(got) != 2 {
|
||||
t.Fatalf("posted %d comments, want 2", len(got))
|
||||
}
|
||||
if got[0]["path"] != "a.go" || got[0]["line"] != float64(12) || got[0]["side"] != "RIGHT" {
|
||||
t.Errorf("comment[0] = %v, want path=a.go line=12 side=RIGHT", got[0])
|
||||
}
|
||||
if got[0]["commit_id"] != "pulled-head-sha" {
|
||||
t.Errorf("comment[0].commit_id = %v, want the head pull requests.Get reported", got[0]["commit_id"])
|
||||
}
|
||||
if got[1]["body"] != "```suggestion\nfixed\n```" {
|
||||
t.Errorf("comment[1].body = %v, want the suggestion block preserved", got[1]["body"])
|
||||
}
|
||||
}
|
||||
|
||||
// TestGitHubCreateReviewCommentsKeepsGoingAfterARefusal pins that one comment
|
||||
// GitHub will not accept -- a line outside the diff, a file the push renamed --
|
||||
// cannot silently drop the comments after it.
|
||||
func TestGitHubCreateReviewCommentsKeepsGoingAfterARefusal(t *testing.T) {
|
||||
c, mux := newTestClient(t)
|
||||
mux.HandleFunc("GET /repos/o/r/pulls/7", func(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(t, w, map[string]any{
|
||||
"number": 7, "state": "open",
|
||||
"head": map[string]any{"ref": "f", "sha": "headsha"},
|
||||
"base": map[string]any{"ref": "main", "sha": "basesha"},
|
||||
})
|
||||
})
|
||||
attempts := 0
|
||||
mux.HandleFunc("POST /repos/o/r/pulls/7/comments", func(w http.ResponseWriter, r *http.Request) {
|
||||
attempts++
|
||||
if attempts == 1 {
|
||||
w.WriteHeader(http.StatusUnprocessableEntity)
|
||||
return
|
||||
}
|
||||
writeJSON(t, w, map[string]any{"id": 2})
|
||||
})
|
||||
|
||||
err := c.CreateReviewComments(t.Context(), "o", "r", 7, "headsha", []InlineReviewComment{
|
||||
{Path: "a.go", Line: 1, Body: "refused"},
|
||||
{Path: "b.go", Line: 2, Body: "accepted"},
|
||||
})
|
||||
if err == nil {
|
||||
t.Error("CreateReviewComments error = nil, want the refused comment surfaced")
|
||||
}
|
||||
if attempts != 2 {
|
||||
t.Errorf("attempted %d comments, want 2: a refusal must not abandon the rest", attempts)
|
||||
}
|
||||
}
|
||||
|
||||
// TestGitHubCreateReviewCommentsRefusesAnEmptyHeadSHA guards the anchor itself.
|
||||
// An empty commit_id makes GitHub reject every comment with nothing that says
|
||||
// why, so it fails before the first request instead.
|
||||
func TestGitHubCreateReviewCommentsRefusesAnEmptyHeadSHA(t *testing.T) {
|
||||
c, mux := newTestClient(t)
|
||||
mux.HandleFunc("GET /repos/o/r/pulls/7", func(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(t, w, map[string]any{
|
||||
"number": 7, "state": "open",
|
||||
"head": map[string]any{"ref": "f"}, "base": map[string]any{"ref": "main", "sha": "basesha"},
|
||||
})
|
||||
})
|
||||
posted := false
|
||||
mux.HandleFunc("POST /repos/o/r/pulls/7/comments", func(w http.ResponseWriter, r *http.Request) {
|
||||
posted = true
|
||||
writeJSON(t, w, map[string]any{"id": 1})
|
||||
})
|
||||
|
||||
err := c.CreateReviewComments(t.Context(), "o", "r", 7, "reviewed-sha", []InlineReviewComment{{Path: "a.go", Line: 1, Body: "x"}})
|
||||
if err == nil {
|
||||
t.Fatal("CreateReviewComments error = nil, want a missing-head-sha error")
|
||||
}
|
||||
if posted {
|
||||
t.Error("a comment was posted despite no head sha to anchor it to")
|
||||
}
|
||||
}
|
||||
|
||||
// TestGitHubCreateReviewCommentsRefusesAMovedHead is the q9au drift guard. The
|
||||
// line numbers in a finding describe one revision; if the pull request's head
|
||||
// has moved since the review, GitHub anchors a line number against the CURRENT
|
||||
// file and attaches the comment to whatever now occupies that line rather than
|
||||
// failing. So the set is refused before the first comment is attempted, and the
|
||||
// PR body remains the record.
|
||||
func TestGitHubCreateReviewCommentsRefusesAMovedHead(t *testing.T) {
|
||||
c, mux := newTestClient(t)
|
||||
mux.HandleFunc("GET /repos/o/r/pulls/7", func(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(t, w, map[string]any{
|
||||
"number": 7, "state": "open",
|
||||
"head": map[string]any{"ref": "f", "sha": "moved-head-sha"},
|
||||
"base": map[string]any{"ref": "main", "sha": "basesha"},
|
||||
})
|
||||
})
|
||||
posted := false
|
||||
mux.HandleFunc("POST /repos/o/r/pulls/7/comments", func(w http.ResponseWriter, r *http.Request) {
|
||||
posted = true
|
||||
writeJSON(t, w, map[string]any{"id": 1})
|
||||
})
|
||||
|
||||
err := c.CreateReviewComments(t.Context(), "o", "r", 7, "reviewed-sha", []InlineReviewComment{{Path: "a.go", Line: 12, Body: "nil deref"}})
|
||||
if err == nil {
|
||||
t.Fatal("CreateReviewComments error = nil, want a refusal for a head that moved off the reviewed revision")
|
||||
}
|
||||
if !strings.Contains(err.Error(), "reviewed-sha") || !strings.Contains(err.Error(), "moved-head-sha") {
|
||||
t.Errorf("error = %v, want it to name both revisions so an operator can tell what moved", err)
|
||||
}
|
||||
if posted {
|
||||
t.Error("a comment was anchored to a revision its line numbers were not measured on")
|
||||
}
|
||||
}
|
||||
|
||||
func TestGiteaCreateReviewComments(t *testing.T) {
|
||||
c, mux := newTestGiteaClient(t)
|
||||
mux.HandleFunc("GET /api/v1/repos/o/r/pulls/7", func(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(t, w, map[string]any{
|
||||
"number": 7, "title": "Add widget", "state": "open", "merged": false,
|
||||
"head": map[string]any{"ref": "feature/widget", "sha": "pulled-head-sha"},
|
||||
"base": map[string]any{"ref": "main", "sha": "basesha"},
|
||||
})
|
||||
})
|
||||
var got map[string]any
|
||||
mux.HandleFunc("POST /api/v1/repos/o/r/pulls/7/reviews", func(w http.ResponseWriter, r *http.Request) {
|
||||
if err := json.NewDecoder(r.Body).Decode(&got); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
writeJSON(t, w, map[string]any{"id": 1})
|
||||
})
|
||||
|
||||
comments := []InlineReviewComment{
|
||||
{Path: "a.go", Line: 12, Body: "nil deref"},
|
||||
{Path: "b.go", Line: 3, Body: "race"},
|
||||
}
|
||||
if err := c.CreateReviewComments(t.Context(), "o", "r", 7, "pulled-head-sha", comments); err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
|
||||
// Gitea carries inline comments on one COMMENT-state review.
|
||||
if got["event"] != "COMMENT" || got["commit_id"] != "pulled-head-sha" {
|
||||
t.Errorf("review = %v, want event=COMMENT and the reported head sha", got)
|
||||
}
|
||||
posted, _ := got["comments"].([]any)
|
||||
if len(posted) != 2 {
|
||||
t.Fatalf("review carried %d comments, want 2", len(posted))
|
||||
}
|
||||
first, _ := posted[0].(map[string]any)
|
||||
if first["path"] != "a.go" || first["new_position"] != float64(12) {
|
||||
t.Errorf("comments[0] = %v, want path=a.go new_position=12", first)
|
||||
}
|
||||
}
|
||||
|
||||
func TestGiteaCreateReviewCommentsRefusesAnEmptyHeadSHA(t *testing.T) {
|
||||
c, mux := newTestGiteaClient(t)
|
||||
mux.HandleFunc("GET /api/v1/repos/o/r/pulls/7", func(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(t, w, map[string]any{
|
||||
"number": 7, "state": "open", "merged": false,
|
||||
"head": map[string]any{"ref": "f"}, "base": map[string]any{"ref": "main", "sha": "basesha"},
|
||||
})
|
||||
})
|
||||
reviewed := false
|
||||
mux.HandleFunc("POST /api/v1/repos/o/r/pulls/7/reviews", func(w http.ResponseWriter, r *http.Request) {
|
||||
reviewed = true
|
||||
writeJSON(t, w, map[string]any{"id": 1})
|
||||
})
|
||||
|
||||
err := c.CreateReviewComments(t.Context(), "o", "r", 7, "reviewed-sha", []InlineReviewComment{{Path: "a.go", Line: 1, Body: "x"}})
|
||||
if err == nil {
|
||||
t.Fatal("CreateReviewComments error = nil, want a missing-head-sha error")
|
||||
}
|
||||
if reviewed {
|
||||
t.Error("a review was submitted despite no head sha to anchor it to")
|
||||
}
|
||||
}
|
||||
|
||||
// TestGiteaCreateReviewCommentsRefusesAMovedHead is the Gitea half of the q9au
|
||||
// drift guard: the same refusal, reached before the review is submitted, because
|
||||
// Gitea's inline comments live on that one review and a wrong line is applied
|
||||
// with one click.
|
||||
func TestGiteaCreateReviewCommentsRefusesAMovedHead(t *testing.T) {
|
||||
c, mux := newTestGiteaClient(t)
|
||||
mux.HandleFunc("GET /api/v1/repos/o/r/pulls/7", func(w http.ResponseWriter, r *http.Request) {
|
||||
writeJSON(t, w, map[string]any{
|
||||
"number": 7, "state": "open", "merged": false,
|
||||
"head": map[string]any{"ref": "f", "sha": "moved-head-sha"},
|
||||
"base": map[string]any{"ref": "main", "sha": "basesha"},
|
||||
})
|
||||
})
|
||||
reviewed := false
|
||||
mux.HandleFunc("POST /api/v1/repos/o/r/pulls/7/reviews", func(w http.ResponseWriter, r *http.Request) {
|
||||
reviewed = true
|
||||
writeJSON(t, w, map[string]any{"id": 1})
|
||||
})
|
||||
|
||||
err := c.CreateReviewComments(t.Context(), "o", "r", 7, "reviewed-sha", []InlineReviewComment{{Path: "a.go", Line: 12, Body: "nil deref"}})
|
||||
if err == nil {
|
||||
t.Fatal("CreateReviewComments error = nil, want a refusal for a head that moved off the reviewed revision")
|
||||
}
|
||||
if reviewed {
|
||||
t.Error("a review was submitted against a revision its line numbers were not measured on")
|
||||
}
|
||||
}
|
||||
|
||||
// TestReviewCommentWriterIsOptional pins the degrade path the forgerpc server
|
||||
// relies on: a forge that cannot post inline comments must not satisfy the
|
||||
// interface, so the caller is told rather than handed a silent no-op.
|
||||
func TestReviewCommentWriterIsOptional(t *testing.T) {
|
||||
if _, ok := any(&NoopForge{}).(ReviewCommentWriter); ok {
|
||||
t.Error("NoopForge satisfies ReviewCommentWriter; the capability must be absent, not faked")
|
||||
}
|
||||
for _, c := range []any{&GitHubClient{}, &GiteaClient{}} {
|
||||
if _, ok := c.(ReviewCommentWriter); !ok {
|
||||
t.Errorf("%T does not satisfy ReviewCommentWriter", c)
|
||||
}
|
||||
}
|
||||
}
|
||||
|
||||
// Compile-time guard: the workflow stage reaches this through a Forger whose
|
||||
// signature carries the domain's own comment value, so the conversion is the
|
||||
// caller's. The interface carries the revision the caller MEASURED, never a
|
||||
// commit to anchor to: the anchor stays a per-forge detail (GitHub pins
|
||||
// commit_id, Gitea anchors the review), while the caller's revision is only ever
|
||||
// compared against the head the forge reads for itself.
|
||||
var _ = func(ctx context.Context, c ReviewCommentWriter) error {
|
||||
return c.CreateReviewComments(ctx, "o", "r", 1, "reviewed-sha", nil)
|
||||
}
|
||||
@@ -1,30 +0,0 @@
|
||||
package forge
|
||||
|
||||
import (
|
||||
"log/slog"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"net/url"
|
||||
"testing"
|
||||
|
||||
"github.com/google/go-github/v78/github"
|
||||
)
|
||||
|
||||
// newTestClient wires a GitHubClient at a local httptest server so its
|
||||
// methods can be exercised without hitting the real GitHub API.
|
||||
func newTestClient(t *testing.T) (*GitHubClient, *http.ServeMux) {
|
||||
t.Helper()
|
||||
mux := http.NewServeMux()
|
||||
srv := httptest.NewServer(mux)
|
||||
t.Cleanup(srv.Close)
|
||||
|
||||
gh := github.NewClient(nil)
|
||||
base, err := url.Parse(srv.URL + "/")
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
gh.BaseURL = base
|
||||
gh.UploadURL = base
|
||||
|
||||
return &GitHubClient{gh: gh, log: slog.New(slog.DiscardHandler)}, mux
|
||||
}
|
||||
@@ -1,201 +0,0 @@
|
||||
package webhook
|
||||
|
||||
import (
|
||||
"context"
|
||||
"encoding/json"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"testing"
|
||||
|
||||
"github.com/google/go-github/v78/github"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/workintake"
|
||||
)
|
||||
|
||||
// reviewEvent builds a signed pull_request_review delivery, GitHub's
|
||||
// low-latency path for "a human reacted to archie's PR" (decision 2).
|
||||
func reviewEvent(t *testing.T, action string, mutate func(*github.PullRequestReviewEvent)) *http.Request {
|
||||
t.Helper()
|
||||
ev := &github.PullRequestReviewEvent{
|
||||
Action: new(action),
|
||||
Review: &github.PullRequestReview{
|
||||
ID: new(int64(7)),
|
||||
State: new("requested_changes"),
|
||||
Body: new("please fix the loop"),
|
||||
User: &github.User{Login: new("alice")},
|
||||
},
|
||||
PullRequest: &github.PullRequest{Number: new(42)},
|
||||
Repo: &github.Repository{
|
||||
Name: new("widgets"),
|
||||
Owner: &github.User{Login: new("acme")},
|
||||
},
|
||||
}
|
||||
if mutate != nil {
|
||||
mutate(ev)
|
||||
}
|
||||
payload, err := json.Marshal(ev)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return signedRequest(t, testSecret, "pull_request_review", payload)
|
||||
}
|
||||
|
||||
func reviewCommentEvent(t *testing.T, action string, mutate func(*github.PullRequestReviewCommentEvent)) *http.Request {
|
||||
t.Helper()
|
||||
ev := &github.PullRequestReviewCommentEvent{
|
||||
Action: new(action),
|
||||
Comment: &github.PullRequestComment{
|
||||
ID: new(int64(11)),
|
||||
PullRequestReviewID: new(int64(7)),
|
||||
Body: new("also this"),
|
||||
Path: new("x.go"),
|
||||
Line: new(3),
|
||||
User: &github.User{Login: new("bob")},
|
||||
},
|
||||
PullRequest: &github.PullRequest{Number: new(42)},
|
||||
Repo: &github.Repository{
|
||||
Name: new("widgets"),
|
||||
Owner: &github.User{Login: new("acme")},
|
||||
},
|
||||
}
|
||||
if mutate != nil {
|
||||
mutate(ev)
|
||||
}
|
||||
payload, err := json.Marshal(ev)
|
||||
if err != nil {
|
||||
t.Fatal(err)
|
||||
}
|
||||
return signedRequest(t, testSecret, "pull_request_review_comment", payload)
|
||||
}
|
||||
|
||||
func serveReaction(t *testing.T, r *Receiver, req *http.Request) (*httptest.ResponseRecorder, []workintake.ReviewCommentEnvelope) {
|
||||
t.Helper()
|
||||
var published []workintake.ReviewCommentEnvelope
|
||||
r.reactionPublish = func(_ context.Context, e workintake.ReviewCommentEnvelope) error {
|
||||
published = append(published, e)
|
||||
return nil
|
||||
}
|
||||
rec := httptest.NewRecorder()
|
||||
r.ServeHTTP(rec, req)
|
||||
return rec, published
|
||||
}
|
||||
|
||||
func newReactionReceiver() *Receiver {
|
||||
return New(testSecret, "label", testLabel, testBot, nil, nil, nil)
|
||||
}
|
||||
|
||||
func TestReceiverPublishesASubmittedReviewAsAReaction(t *testing.T) {
|
||||
r := newReactionReceiver()
|
||||
rec, published := serveReaction(t, r, reviewEvent(t, "submitted", nil))
|
||||
|
||||
if rec.Code != http.StatusAccepted {
|
||||
t.Fatalf("status = %d, want 202", rec.Code)
|
||||
}
|
||||
if len(published) != 1 {
|
||||
t.Fatalf("published = %d, want 1", len(published))
|
||||
}
|
||||
e := published[0]
|
||||
if e.Kind != workintake.ReviewReactionReview || e.ReviewID != 7 || e.Owner != "acme" || e.Repo != "widgets" || e.PRNumber != 42 {
|
||||
t.Errorf("reaction = %+v, want review 7 on acme/widgets#42", e)
|
||||
}
|
||||
if e.State != "requested_changes" || e.Body != "please fix the loop" || e.Author != "alice" {
|
||||
t.Errorf("reaction content = %+v, want the review's own state/body/author", e)
|
||||
}
|
||||
// The idempotency key is kinded (decision 3): a review ID and a comment
|
||||
// ID come from independent forge sequences and must never collide.
|
||||
if e.IdempotencyKey() == "" {
|
||||
t.Error("reaction carried no idempotency key")
|
||||
}
|
||||
}
|
||||
|
||||
func TestReceiverPublishesACreatedCommentAsAReaction(t *testing.T) {
|
||||
r := newReactionReceiver()
|
||||
rec, published := serveReaction(t, r, reviewCommentEvent(t, "created", nil))
|
||||
|
||||
if rec.Code != http.StatusAccepted {
|
||||
t.Fatalf("status = %d, want 202", rec.Code)
|
||||
}
|
||||
if len(published) != 1 {
|
||||
t.Fatalf("published = %d, want 1", len(published))
|
||||
}
|
||||
e := published[0]
|
||||
if e.Kind != workintake.ReviewReactionComment || e.CommentID != 11 || e.ReviewID != 7 {
|
||||
t.Errorf("reaction = %+v, want comment 11 collected under review 7", e)
|
||||
}
|
||||
}
|
||||
|
||||
func TestReceiverIgnoresNonActionReviewActivity(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
kind string
|
||||
action string
|
||||
}{
|
||||
{"dismissed review", "review", "dismissed"},
|
||||
{"edited review", "review", "edited"},
|
||||
{"deleted review", "review", "deleted"},
|
||||
{"edited comment", "comment", "edited"},
|
||||
{"deleted comment", "comment", "deleted"},
|
||||
}
|
||||
for _, tt := range tests {
|
||||
t.Run(tt.name, func(t *testing.T) {
|
||||
r := newReactionReceiver()
|
||||
var req *http.Request
|
||||
if tt.kind == "review" {
|
||||
req = reviewEvent(t, tt.action, nil)
|
||||
} else {
|
||||
req = reviewCommentEvent(t, tt.action, nil)
|
||||
}
|
||||
rec, published := serveReaction(t, r, req)
|
||||
if rec.Code != http.StatusAccepted {
|
||||
t.Fatalf("status = %d, want 202", rec.Code)
|
||||
}
|
||||
if len(published) != 0 {
|
||||
t.Errorf("published %d reactions for action %q", len(published), tt.action)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestReceiverReactionWithoutTheCapabilityIsUntouched(t *testing.T) {
|
||||
// A receiver composed without the reaction publisher (nil) must not
|
||||
// panic or publish when a review event arrives: the reaction path is an
|
||||
// optional capability, the issue path is the receiver's core contract.
|
||||
r := New(testSecret, "label", testLabel, testBot, nil, nil, nil)
|
||||
rec := httptest.NewRecorder()
|
||||
r.ServeHTTP(rec, reviewEvent(t, "submitted", nil))
|
||||
if rec.Code != http.StatusAccepted {
|
||||
t.Fatalf("status = %d, want 202", rec.Code)
|
||||
}
|
||||
}
|
||||
|
||||
func TestReceiverRateLimitsReactionDeliveries(t *testing.T) {
|
||||
r := newReactionReceiver()
|
||||
// Drive the limiter to its per-window ceiling with one remote, then
|
||||
// assert the next reaction from that remote is refused with 429 while a
|
||||
// different remote still passes.
|
||||
remote := "10.0.0.1:1234"
|
||||
for i := range reactionRateLimit {
|
||||
req := reviewEvent(t, "submitted", nil)
|
||||
req.RemoteAddr = remote
|
||||
rec, _ := serveReaction(t, r, req)
|
||||
if rec.Code != http.StatusAccepted {
|
||||
t.Fatalf("delivery %d within the window: status = %d, want 202", i+1, rec.Code)
|
||||
}
|
||||
}
|
||||
req := reviewEvent(t, "submitted", nil)
|
||||
req.RemoteAddr = remote
|
||||
rec, published := serveReaction(t, r, req)
|
||||
if rec.Code != http.StatusTooManyRequests {
|
||||
t.Fatalf("over-limit status = %d, want 429", rec.Code)
|
||||
}
|
||||
if len(published) != 0 {
|
||||
t.Errorf("over-limit delivery published %d reactions", len(published))
|
||||
}
|
||||
|
||||
otherReq := reviewEvent(t, "submitted", nil)
|
||||
otherReq.RemoteAddr = "10.0.0.2:1234"
|
||||
rec, published = serveReaction(t, r, otherReq)
|
||||
if rec.Code != http.StatusAccepted || len(published) != 1 {
|
||||
t.Errorf("different remote blocked: status = %d, published = %d", rec.Code, len(published))
|
||||
}
|
||||
}
|
||||
@@ -1,388 +0,0 @@
|
||||
package webhook
|
||||
|
||||
import (
|
||||
"context"
|
||||
"crypto/hmac"
|
||||
"crypto/sha256"
|
||||
"encoding/hex"
|
||||
"encoding/json"
|
||||
"errors"
|
||||
"net/http"
|
||||
"net/http/httptest"
|
||||
"slices"
|
||||
"strings"
|
||||
"testing"
|
||||
|
||||
"github.com/google/go-github/v78/github"
|
||||
|
||||
"github.com/samcharles93/archie-core/internal/domain/workintake"
|
||||
)
|
||||
|
||||
const (
|
||||
testSecret = "test-secret"
|
||||
testBot = "archie-bot"
|
||||
testLabel = "archie"
|
||||
)
|
||||
|
||||
func issueEvent(t *testing.T, action string, mutate func(*github.IssuesEvent)) *github.IssuesEvent {
|
||||
t.Helper()
|
||||
ev := &github.IssuesEvent{
|
||||
Action: new(action),
|
||||
Issue: &github.Issue{
|
||||
Number: new(42),
|
||||
Title: new("Do the thing"),
|
||||
Body: new("please"),
|
||||
State: new("open"),
|
||||
},
|
||||
Repo: &github.Repository{
|
||||
Name: new("repo"),
|
||||
Owner: &github.User{Login: new("owner")},
|
||||
},
|
||||
}
|
||||
if mutate != nil {
|
||||
mutate(ev)
|
||||
}
|
||||
return ev
|
||||
}
|
||||
|
||||
func signedRequest(t *testing.T, secret, eventType string, payload []byte) *http.Request {
|
||||
t.Helper()
|
||||
req := httptest.NewRequestWithContext(t.Context(), http.MethodPost, "/webhook", strings.NewReader(string(payload)))
|
||||
req.Header.Set("X-GitHub-Event", eventType)
|
||||
if secret != "" {
|
||||
mac := hmac.New(sha256.New, []byte(secret))
|
||||
mac.Write(payload)
|
||||
req.Header.Set("X-Hub-Signature-256", "sha256="+hex.EncodeToString(mac.Sum(nil)))
|
||||
}
|
||||
return req
|
||||
}
|
||||
|
||||
func serve(t *testing.T, r *Receiver, req *http.Request) (*httptest.ResponseRecorder, []workintake.TaskEnvelope) {
|
||||
t.Helper()
|
||||
var published []workintake.TaskEnvelope
|
||||
r.publish = func(_ context.Context, task workintake.TaskEnvelope) error {
|
||||
published = append(published, task)
|
||||
return nil
|
||||
}
|
||||
rec := httptest.NewRecorder()
|
||||
r.ServeHTTP(rec, req)
|
||||
return rec, published
|
||||
}
|
||||
|
||||
func TestReceiverPublishesMatchingIssue(t *testing.T) {
|
||||
tests := []struct {
|
||||
name string
|
||||
trigger string
|
||||
cfgLabel string
|
||||
eventType string
|
||||
action string
|
||||
secret string
|
||||
mutate func(*github.IssuesEvent)
|
||||
wantStatus int
|
||||
wantPubl int
|
||||
}{
|
||||
{
|
||||
name: "labelled issue matches label trigger",
|
||||
trigger: "label",
|
||||
cfgLabel: testLabel,
|
||||
eventType: "issues",
|
||||
action: "labeled",
|
||||
secret: testSecret,
|
||||
mutate: func(ev *github.IssuesEvent) { ev.Issue.Labels = []*github.Label{{Name: new(testLabel)}} },
|
||||
wantStatus: http.StatusAccepted,
|
||||
wantPubl: 1,
|
||||
},
|
||||
{
|
||||
name: "assigned issue matches assignee trigger",
|
||||
trigger: "assignee",
|
||||
eventType: "issues",
|
||||
action: "assigned",
|
||||
secret: testSecret,
|
||||
mutate: func(ev *github.IssuesEvent) { ev.Issue.Assignees = []*github.User{{Login: new(testBot)}} },
|
||||
wantStatus: http.StatusAccepted,
|
||||
wantPubl: 1,
|
||||
},
|
||||
{
|
||||
name: "opened issue with label matches label trigger",
|
||||
trigger: "label",
|
||||
cfgLabel: testLabel,
|
||||
eventType: "issues",
|
||||
action: "opened",
|
||||
secret: testSecret,
|
||||
mutate: func(ev *github.IssuesEvent) { ev.Issue.Labels = []*github.Label{{Name: new(testLabel)}} },
|
||||
wantStatus: http.StatusAccepted,
|
||||
wantPubl: 1,
|
||||
},
|
||||
{
|
||||
name: "wrong label does not match",
|
||||
trigger: "label",
|
||||
cfgLabel: testLabel,
|
||||
eventType: "issues",
|
||||
action: "labeled",
|
||||
secret: testSecret,
|
||||
mutate: func(ev *github.IssuesEvent) { ev.Issue.Labels = []*github.Label{{Name: new("other")}} },
|
||||
wantStatus: http.StatusAccepted,
|
||||
wantPubl: 0,
|
||||
},
|
||||
{
|
||||
name: "invalid signature is rejected",
|
||||
trigger: "label",
|
||||
cfgLabel: testLabel,
|
||||
eventType: "issues",
|
||||
action: "labeled",
|
||||
secret: "wrong-secret",
|
||||
mutate: func(ev *github.IssuesEvent) { ev.Issue.Labels = []*github.Label{{Name: new(testLabel)}} },
|
||||
wantStatus: http.StatusUnauthorized,
|
||||
wantPubl: 0,
|
||||
},
|
||||
{
|
||||
name: "missing signature is rejected",
|
||||
trigger: "label",
|
||||
cfgLabel: testLabel,
|
||||
eventType: "issues",
|
||||
action: "labeled",
|
||||
secret: "",
|
||||
mutate: func(ev *github.IssuesEvent) { ev.Issue.Labels = []*github.Label{{Name: new(testLabel)}} },
|
||||
wantStatus: http.StatusUnauthorized,
|
||||
wantPubl: 0,
|
||||
},
|
||||
{
|
||||
name: "non-issue event is acknowledged and ignored",
|
||||
trigger: "label",
|
||||
cfgLabel: testLabel,
|
||||
eventType: "ping",
|
||||
action: "",
|
||||
secret: testSecret,
|
||||
wantStatus: http.StatusAccepted,
|
||||
wantPubl: 0,
|
||||
},
|
||||
{
|
||||
name: "pull request is ignored",
|
||||
trigger: "label",
|
||||
cfgLabel: testLabel,
|
||||
eventType: "issues",
|
||||
action: "labeled",
|
||||
secret: testSecret,
|
||||
mutate: func(ev *github.IssuesEvent) {
|
||||
ev.Issue.Labels = []*github.Label{{Name: new(testLabel)}}
|
||||
ev.Issue.PullRequestLinks = &github.PullRequestLinks{URL: new("https://api.github.com/repos/o/r/pulls/1")}
|
||||
},
|
||||
wantStatus: http.StatusAccepted,
|
||||
wantPubl: 0,
|
||||
},
|
||||
{
|
||||
name: "closed issue is ignored",
|
||||
trigger: "label",
|
||||
cfgLabel: testLabel,
|
||||
eventType: "issues",
|
||||
action: "labeled",
|
||||
secret: testSecret,
|
||||
mutate: func(ev *github.IssuesEvent) {
|
||||
ev.Issue.State = new("closed")
|
||||
ev.Issue.Labels = []*github.Label{{Name: new(testLabel)}}
|
||||
},
|
||||
wantStatus: http.StatusAccepted,
|
||||
wantPubl: 0,
|
||||
},
|
||||
{
|
||||
name: "unlabeled action never queues",
|
||||
trigger: "label",
|
||||
cfgLabel: testLabel,
|
||||
eventType: "issues",
|
||||
action: "unlabeled",
|
||||
secret: testSecret,
|
||||
mutate: func(ev *github.IssuesEvent) { ev.Issue.Labels = []*github.Label{{Name: new(testLabel)}} },
|
||||
wantStatus: http.StatusAccepted,
|
||||
wantPubl: 0,
|
||||
},
|
||||
}
|
||||
|
||||
for _, tc := range tests {
|
||||
t.Run(tc.name, func(t *testing.T) {
|
||||
ev := issueEvent(t, tc.action, tc.mutate)
|
||||
payload, err := json.Marshal(ev)
|
||||
if err != nil {
|
||||
t.Fatalf("marshal event: %v", err)
|
||||
}
|
||||
// The receiver always trusts testSecret; tc.secret is what the
|
||||
// request is signed with, so a case can sign with the wrong (or no)
|
||||
// secret to exercise rejection.
|
||||
r := New(testSecret, tc.trigger, tc.cfgLabel, testBot, nil, nil, nil)
|
||||
rec, published := serve(t, r, signedRequest(t, tc.secret, tc.eventType, payload))
|
||||
|
||||
if rec.Code != tc.wantStatus {
|
||||
t.Errorf("status = %d, want %d", rec.Code, tc.wantStatus)
|
||||
}
|
||||
if len(published) != tc.wantPubl {
|
||||
t.Errorf("published %d envelopes, want %d", len(published), tc.wantPubl)
|
||||
}
|
||||
})
|
||||
}
|
||||
}
|
||||
|
||||
func TestPublishedEnvelopeCarriesIssueIdentityAndKind(t *testing.T) {
|
||||
ev := issueEvent(t, "labeled", func(ev *github.IssuesEvent) {
|
||||
ev.Issue.Labels = []*github.Label{{Name: new(testLabel)}, {Name: new("bug")}}
|
||||
})
|
||||
payload, err := json.Marshal(ev)
|
||||
if err != nil {
|
||||
t.Fatalf("marshal event: %v", err)
|
||||
}
|
||||
r := New(testSecret, "label", testLabel, testBot, nil, nil, nil)
|
||||
_, published := serve(t, r, signedRequest(t, testSecret, "issues", payload))
|
||||
|
||||
if len(published) != 1 {
|
||||
t.Fatalf("published = %d, want 1", len(published))
|
||||
}
|
||||
task := published[0]
|
||||
if task.Owner != "owner" || task.Repo != "repo" || task.Number != 42 {
|
||||
t.Errorf("envelope identity = %s/%s#%d, want owner/repo#42", task.Owner, task.Repo, task.Number)
|
||||
}
|
||||
if task.Kind != workintake.KindBug {
|
||||
t.Errorf("envelope kind = %q, want %q", task.Kind, workintake.KindBug)
|
||||
}
|
||||
if !slices.Contains(task.Labels, testLabel) || !slices.Contains(task.Labels, "bug") {
|
||||
t.Errorf("envelope labels = %v, want to contain %q and %q", task.Labels, testLabel, "bug")
|
||||
}
|
||||
if task.IdempotencyKey() != "archie:default//owner/repo/42" {
|
||||
t.Errorf("idempotency key = %q, want archie:default//owner/repo/42", task.IdempotencyKey())
|
||||
}
|
||||
}
|
||||
|
||||
// TestReceiverStatusTracksAuthenticatedDeliveries pins the observability this
|
||||
// receiver needs for archie-core-7d5u.5: a wedged or non-delivering receiver
|
||||
// must not be indistinguishable from an idle repo. Deliveries counts every
|
||||
// authenticated, parseable delivery (proof GitHub is reaching the process at
|
||||
// all) independent of whether that delivery matched the dispatch predicate;
|
||||
// Publishes counts only what actually became work. An unauthenticated
|
||||
// request must not inflate either counter -- that would let anyone spamming
|
||||
// the endpoint with a bad signature manufacture a false "receiver is alive
|
||||
// and busy" signal.
|
||||
func TestReceiverStatusTracksAuthenticatedDeliveries(t *testing.T) {
|
||||
r := New(testSecret, "label", testLabel, testBot, nil, nil, nil)
|
||||
|
||||
before := r.Status()
|
||||
if before.Deliveries != 0 || before.Publishes != 0 {
|
||||
t.Fatalf("initial status = %+v, want zero counters", before)
|
||||
}
|
||||
if before.LastReceivedAt != nil {
|
||||
t.Fatalf("initial LastReceivedAt = %v, want nil", before.LastReceivedAt)
|
||||
}
|
||||
|
||||
// Invalid signature: not a real GitHub delivery, must not count.
|
||||
rejected := issueEvent(t, "labeled", func(ev *github.IssuesEvent) {
|
||||
ev.Issue.Labels = []*github.Label{{Name: new(testLabel)}}
|
||||
})
|
||||
rejectedPayload, err := json.Marshal(rejected)
|
||||
if err != nil {
|
||||
t.Fatalf("marshal event: %v", err)
|
||||
}
|
||||
serve(t, r, signedRequest(t, "wrong-secret", "issues", rejectedPayload))
|
||||
afterRejected := r.Status()
|
||||
if afterRejected.Deliveries != 0 {
|
||||
t.Fatalf("Deliveries after unauthenticated request = %d, want 0", afterRejected.Deliveries)
|
||||
}
|
||||
|
||||
// Authenticated but dispatch-ineligible: counts as a delivery (GitHub
|
||||
// really did reach the receiver), not as a publish.
|
||||
ineligible := issueEvent(t, "unlabeled", func(ev *github.IssuesEvent) {
|
||||
ev.Issue.Labels = []*github.Label{{Name: new(testLabel)}}
|
||||
})
|
||||
ineligiblePayload, err := json.Marshal(ineligible)
|
||||
if err != nil {
|
||||
t.Fatalf("marshal event: %v", err)
|
||||
}
|
||||
serve(t, r, signedRequest(t, testSecret, "issues", ineligiblePayload))
|
||||
afterIneligible := r.Status()
|
||||
if afterIneligible.Deliveries != 1 {
|
||||
t.Fatalf("Deliveries after ineligible authenticated request = %d, want 1", afterIneligible.Deliveries)
|
||||
}
|
||||
if afterIneligible.Publishes != 0 {
|
||||
t.Fatalf("Publishes after ineligible authenticated request = %d, want 0", afterIneligible.Publishes)
|
||||
}
|
||||
if afterIneligible.LastReceivedAt == nil {
|
||||
t.Fatal("LastReceivedAt after authenticated request = nil, want set")
|
||||
}
|
||||
|
||||
// Authenticated and dispatch-eligible: counts as both.
|
||||
matched := issueEvent(t, "labeled", func(ev *github.IssuesEvent) {
|
||||
ev.Issue.Labels = []*github.Label{{Name: new(testLabel)}}
|
||||
})
|
||||
matchedPayload, err := json.Marshal(matched)
|
||||
if err != nil {
|
||||
t.Fatalf("marshal event: %v", err)
|
||||
}
|
||||
serve(t, r, signedRequest(t, testSecret, "issues", matchedPayload))
|
||||
final := r.Status()
|
||||
if final.Deliveries != 2 {
|
||||
t.Fatalf("Deliveries = %d, want 2", final.Deliveries)
|
||||
}
|
||||
if final.Publishes != 1 {
|
||||
t.Fatalf("Publishes = %d, want 1", final.Publishes)
|
||||
}
|
||||
}
|
||||
|
||||
// TestReceiverStatusDoesNotCountFailedPublish pins that a Publisher error
|
||||
// still counts the delivery (GitHub really did reach the receiver, and the
|
||||
// payload really was dispatch-eligible) but must not count as a publish --
|
||||
// otherwise Status would report work that never actually reached the queue.
|
||||
func TestReceiverStatusDoesNotCountFailedPublish(t *testing.T) {
|
||||
r := New(testSecret, "label", testLabel, testBot, nil, nil, nil)
|
||||
r.publish = func(context.Context, workintake.TaskEnvelope) error {
|
||||
return errors.New("publish unavailable")
|
||||
}
|
||||
|
||||
ev := issueEvent(t, "labeled", func(ev *github.IssuesEvent) {
|
||||
ev.Issue.Labels = []*github.Label{{Name: new(testLabel)}}
|
||||
})
|
||||
payload, err := json.Marshal(ev)
|
||||
if err != nil {
|
||||
t.Fatalf("marshal event: %v", err)
|
||||
}
|
||||
rec := httptest.NewRecorder()
|
||||
r.ServeHTTP(rec, signedRequest(t, testSecret, "issues", payload))
|
||||
|
||||
if rec.Code != http.StatusInternalServerError {
|
||||
t.Fatalf("status = %d, want 500", rec.Code)
|
||||
}
|
||||
got := r.Status()
|
||||
if got.Deliveries != 1 {
|
||||
t.Errorf("Deliveries = %d, want 1", got.Deliveries)
|
||||
}
|
||||
if got.Publishes != 0 {
|
||||
t.Errorf("Publishes = %d, want 0 (publish failed)", got.Publishes)
|
||||
}
|
||||
}
|
||||
|
||||
// TestReceiverServesStatusOnGET proves the counters are reachable without a
|
||||
// separate health-check subsystem: any GET is answered with the JSON status
|
||||
// body, since GitHub only ever POSTs to this receiver.
|
||||
func TestReceiverServesStatusOnGET(t *testing.T) {
|
||||
r := New(testSecret, "label", testLabel, testBot, nil, nil, nil)
|
||||
ev := issueEvent(t, "labeled", func(ev *github.IssuesEvent) {
|
||||
ev.Issue.Labels = []*github.Label{{Name: new(testLabel)}}
|
||||
})
|
||||
payload, err := json.Marshal(ev)
|
||||
if err != nil {
|
||||
t.Fatalf("marshal event: %v", err)
|
||||
}
|
||||
serve(t, r, signedRequest(t, testSecret, "issues", payload))
|
||||
|
||||
req := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/", nil)
|
||||
rec := httptest.NewRecorder()
|
||||
r.ServeHTTP(rec, req)
|
||||
|
||||
if rec.Code != http.StatusOK {
|
||||
t.Fatalf("GET status = %d, want 200", rec.Code)
|
||||
}
|
||||
var got Status
|
||||
if err := json.Unmarshal(rec.Body.Bytes(), &got); err != nil {
|
||||
t.Fatalf("decode status body: %v (%s)", err, rec.Body.String())
|
||||
}
|
||||
if got.Deliveries != 1 || got.Publishes != 1 {
|
||||
t.Errorf("decoded status = %+v, want Deliveries=1 Publishes=1", got)
|
||||
}
|
||||
if got.LastReceivedAt == nil {
|
||||
t.Error("decoded status LastReceivedAt = nil, want set")
|
||||
}
|
||||
}
|
||||
Reference in new issue
Block a user