package agent import ( "encoding/json" "errors" "fmt" "net/http" "net/http/httptest" "strconv" "strings" "sync" "sync/atomic" "testing" "time" ) func TestMergeGitHubCI(t *testing.T) { run := func(status, conclusion string) githubCheckRun { return githubCheckRun{Status: status, Conclusion: conclusion} } done := func(c string) githubCheckRun { return run("completed", c) } tests := []struct { name string status string count int runs []githubCheckRun want string }{ {"nothing", "pending", 0, nil, ""}, {"zero statuses report pending but mean none", "pending", 0, []githubCheckRun{done("success")}, "success"}, {"status failure wins over green checks", "failure", 2, []githubCheckRun{done("success")}, "failure"}, {"status error", "error", 1, nil, "error"}, {"check failure wins over green status", "success", 1, []githubCheckRun{done("success"), done("failure")}, "failure"}, {"check failure wins over running checks", "pending", 1, []githubCheckRun{run("in_progress", ""), done("timed_out")}, "failure"}, {"running check keeps it pending", "success", 1, []githubCheckRun{run("queued", "")}, "pending"}, {"pending status keeps it pending", "pending", 1, []githubCheckRun{done("success")}, "pending"}, {"skipped and neutral are not failures", "", 0, []githubCheckRun{done("skipped"), done("neutral")}, "success"}, {"cancelled is a failure", "", 0, []githubCheckRun{done("cancelled")}, "failure"}, {"status only", "success", 3, nil, "success"}, } for _, tt := range tests { if got := mergeGitHubCI(tt.status, tt.count, tt.runs); got != tt.want { t.Errorf("%s: mergeGitHubCI = %q, want %q", tt.name, got, tt.want) } } } func TestCountNonAgentActivity(t *testing.T) { item := func(login, state string) githubActivity { var a githubActivity a.User.Login, a.State = login, state return a } items := []githubActivity{ item("iuclabs-coder[bot]", ""), item("IUCLabs-Reviewer[bot]", "COMMENTED"), item("dependabot[bot]", ""), item("alice", "CHANGES_REQUESTED"), item("alice", "PENDING"), item("bob", ""), } if n := countNonAgentActivity(items, DefaultGitHubAgentLogins); n != 2 { t.Errorf("count = %d, want 2 (alice's review + bob; agents and drafts excluded)", n) } } func TestGitHubAgentLoginsEnv(t *testing.T) { t.Setenv("GITHUB_AGENT_LOGINS", "") if got := GitHubAgentLogins(); len(got) != 4 { t.Errorf("default = %v", got) } t.Setenv("GITHUB_AGENT_LOGINS", " a[bot], ,b ") if got := GitHubAgentLogins(); strings.Join(got, "|") != "a[bot]|b" { t.Errorf("env = %v", got) } } // fakeGitHubPR serves one PR whose state tests mutate between polls. type fakeGitHubPR struct { mu sync.Mutex pr string status string checks string issue []string review []string reviews []string authSeen []string reject string // a token the server answers 401 for rateLimit bool } func (f *fakeGitHubPR) set(fn func(*fakeGitHubPR)) { f.mu.Lock() defer f.mu.Unlock() fn(f) } func activity(logins ...string) []string { out := make([]string, len(logins)) for i, l := range logins { state := "" if strings.HasPrefix(l, "review:") { l, state = strings.TrimPrefix(l, "review:"), "CHANGES_REQUESTED" } out[i] = fmt.Sprintf(`{"user":{"login":%q},"state":%q}`, l, state) } return out } func (f *fakeGitHubPR) serve(t *testing.T) *httptest.Server { t.Helper() page := func(w http.ResponseWriter, r *http.Request, items []string) { p, _ := strconv.Atoi(r.URL.Query().Get("page")) if r.URL.Query().Get("per_page") != "100" || p < 1 { t.Errorf("%s: unpaged list request", r.URL) } lo, hi := min((p-1)*100, len(items)), min(p*100, len(items)) _, _ = w.Write([]byte("[" + strings.Join(items[lo:hi], ",") + "]")) } srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { f.mu.Lock() defer f.mu.Unlock() auth := r.Header.Get("Authorization") f.authSeen = append(f.authSeen, auth) if f.rateLimit { w.Header().Set("X-RateLimit-Remaining", "0") w.WriteHeader(http.StatusForbidden) _, _ = w.Write([]byte(`{"message":"API rate limit exceeded"}`)) return } if f.reject != "" && auth == "Bearer "+f.reject { w.WriteHeader(http.StatusUnauthorized) _, _ = w.Write([]byte(`{"message":"Bad credentials"}`)) return } switch r.URL.Path { case "/repos/IUCLabs/app/pulls/5": _, _ = w.Write([]byte(f.pr)) case "/repos/IUCLabs/app/commits/aaa/status", "/repos/IUCLabs/app/commits/bbb/status": _, _ = w.Write([]byte(f.status)) case "/repos/IUCLabs/app/commits/aaa/check-runs", "/repos/IUCLabs/app/commits/bbb/check-runs": _, _ = w.Write([]byte(f.checks)) case "/repos/IUCLabs/app/issues/5/comments": page(w, r, f.issue) case "/repos/IUCLabs/app/pulls/5/comments": page(w, r, f.review) case "/repos/IUCLabs/app/pulls/5/reviews": page(w, r, f.reviews) default: w.WriteHeader(http.StatusNotFound) _, _ = w.Write([]byte(`{"message":"Not Found"}`)) } })) t.Cleanup(srv.Close) return srv } func openPR(head string, mergeable string) string { return `{"state":"open","title":"t","merged":false,"mergeable":` + mergeable + `,"mergeable_state":"clean","html_url":"https://github.com/IUCLabs/app/pull/5","head":{"sha":"` + head + `"},"base":{"sha":"base1"}}` } var ghRef = PRRef{Forge: ForgeGitHub, Owner: "IUCLabs", Repo: "app", Number: 5} func newFakeGitHubClient(srv *httptest.Server) *GitHubClient { return &GitHubClient{APIURL: srv.URL, HTTP: srv.Client(), AgentLogins: DefaultGitHubAgentLogins} } func TestGitHubFetchState(t *testing.T) { humans := make([]string, 0, 101) for i := 0; i < 101; i++ { humans = append(humans, "carol") } f := &fakeGitHubPR{ pr: openPR("aaa", "null"), status: `{"state":"success","total_count":1}`, checks: `{"check_runs":[{"status":"completed","conclusion":"failure"}]}`, issue: activity(humans...), review: activity("iuclabs-coder[bot]", "alice"), reviews: activity("review:alice", "iuclabs-reviewer[bot]"), } st, err := newFakeGitHubClient(f.serve(t)).FetchState(ghRef, "unkin-agent") if err != nil { t.Fatal(err) } if st.State != "open" || st.HeadSHA != "aaa" || st.BaseSHA != "base1" || st.Mergeable != MergeUnknown || st.MergeableState != "clean" { t.Errorf("state = %+v", st) } if st.CIStatus != "failure" { t.Errorf("ci = %q, want failure from the check run", st.CIStatus) } if st.NonAgentComments != 103 { t.Errorf("non-agent = %d, want 103 (101 paged issue comments + review comment + review)", st.NonAgentComments) } for _, a := range f.authSeen { if a != "" { t.Errorf("anonymous client sent Authorization %q", a) } } b, _ := json.Marshal(st) if !strings.Contains(string(b), `"Forge":"github"`) || !strings.Contains(string(b), `"mergeable":null`) { t.Errorf("json = %s", b) } } func TestGitHubFetchStateErrors(t *testing.T) { f := &fakeGitHubPR{pr: openPR("aaa", "true"), status: `{"state":"pending","total_count":0}`, checks: `{"check_runs":[]}`} c := newFakeGitHubClient(f.serve(t)) gone := ghRef gone.Number = 6 if _, err := c.FetchState(gone, ""); !IsPRGone(err) { t.Errorf("missing PR err = %v, want PR gone", err) } f.set(func(f *fakeGitHubPR) { f.rateLimit = true }) _, err := c.FetchState(ghRef, "") if err == nil || IsAuthError(err) || !strings.Contains(err.Error(), "rate limited") { t.Errorf("rate limit err = %v, want a transient non-auth error", err) } f.set(func(f *fakeGitHubPR) { f.rateLimit = false }) c.Token = func() (string, error) { return "", errors.New("vault down") } if _, err := c.FetchState(ghRef, ""); err == nil || !strings.Contains(err.Error(), "vault down") { t.Errorf("token err = %v", err) } } func TestGitHubAnonymousRejectionIsNoCredential(t *testing.T) { srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(http.StatusUnauthorized) _, _ = w.Write([]byte(`{"message":"Requires authentication"}`)) })) defer srv.Close() _, err := newFakeGitHubClient(srv).FetchState(ghRef, "") if !IsNoCredential(err) { t.Errorf("err = %v, want ErrNoCredential", err) } if !strings.Contains(err.Error(), "github GET") { t.Errorf("err = %v, want it to name github", err) } } func TestGitHubReMintsRejectedToken(t *testing.T) { f := &fakeGitHubPR{pr: openPR("aaa", "true"), status: `{"state":"success","total_count":1}`, checks: `{"check_runs":[]}`, reject: "old"} c := newFakeGitHubClient(f.serve(t)) current := "old" refreshes := 0 c.Token = func() (string, error) { return current, nil } c.Refresh = func() (string, error) { refreshes++; current = "new"; return current, nil } if _, err := c.FetchState(ghRef, ""); err != nil { t.Fatal(err) } if refreshes != 1 { t.Errorf("refreshes = %d, want 1", refreshes) } if last := f.authSeen[len(f.authSeen)-1]; last != "Bearer new" { t.Errorf("last auth = %q", last) } f.set(func(f *fakeGitHubPR) { f.reject = "new" }) c.Refresh = func() (string, error) { return "new", nil } if _, err := c.FetchState(ghRef, ""); !IsAuthError(err) || IsNoCredential(err) { t.Errorf("err = %v, want an auth error after the re-mint is rejected too", err) } } func TestInstallationTokenReMintsNearExpiry(t *testing.T) { var mints atomic.Int32 srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { n := mints.Add(1) exp := time.Now().Add(2 * time.Minute).UTC().Format(time.RFC3339) w.WriteHeader(http.StatusCreated) _, _ = fmt.Fprintf(w, `{"token":"t%d","expires_at":%q}`, n, exp) })) defer srv.Close() a := &GitHubApp{AppID: "1", InstallationID: "777", Key: testKey, APIURL: srv.URL, HTTP: srv.Client()} for i := 1; i <= 2; i++ { if tok, err := a.InstallationToken(); err != nil || tok != "t"+strconv.Itoa(i) { t.Fatalf("call %d: token = %q, %v (a token inside the refresh margin must be re-minted)", i, tok, err) } } if tok, err := a.RefreshInstallationToken(); err != nil || tok != "t3" { t.Errorf("refresh = %q, %v", tok, err) } } // runGitHubWatch drives Watch through steps (one per tick) and returns the // result of the tick after the last step; it fails if the watch ends earlier. func runGitHubWatch(t *testing.T, f *fakeGitHubPR, steps ...func(*fakeGitHubPR)) WatchResult { t.Helper() c := newFakeGitHubClient(f.serve(t)) ticks := make(chan time.Time) type result struct { res WatchResult err error } done := make(chan result, 1) baseline := make(chan struct{}) go func() { res, err := Watch(c, []PRRef{ghRef}, "", ticks, func([]PRState) { close(baseline) }, nil) done <- result{res, err} }() select { case <-baseline: case r := <-done: t.Fatalf("watch ended at baseline: %+v, %v", r.res, r.err) } now := time.Now() for i, step := range steps { f.set(step) now = now.Add(time.Minute) select { case ticks <- now: case r := <-done: t.Fatalf("step %d: watch ended early: %+v, %v", i, r.res, r.err) } } close(ticks) r := <-done if r.err != nil { t.Fatal(r.err) } return r.res } func pendingPR() *fakeGitHubPR { return &fakeGitHubPR{ pr: openPR("aaa", "true"), status: `{"state":"pending","total_count":1}`, checks: `{"check_runs":[{"status":"in_progress"}]}`, } } // The agents' own pushes and comments and CI going green are silent; a human // changes-requested review alerts. func TestWatchGitHubHumanReviewAlerts(t *testing.T) { res := runGitHubWatch(t, pendingPR(), func(f *fakeGitHubPR) { f.pr = openPR("bbb", "null") f.issue = activity("iuclabs-coder[bot]", "github-actions[bot]") }, func(f *fakeGitHubPR) { f.status = `{"state":"success","total_count":1}` f.checks = `{"check_runs":[{"status":"completed","conclusion":"success"}]}` f.reviews = activity("iuclabs-reviewer[bot]") }, ) if !res.TimedOut { t.Fatalf("benign steps alerted: %+v", res) } res = runGitHubWatch(t, pendingPR(), func(f *fakeGitHubPR) { f.reviews = activity("iuclabs-reviewer[bot]", "review:alice") }, ) if res.Reason != "new comment from a non-agent user" || res.Ref != ghRef { t.Errorf("result = %+v, want the human review to alert", res) } } func TestWatchGitHubCheckRunFailureAlerts(t *testing.T) { res := runGitHubWatch(t, pendingPR(), func(f *fakeGitHubPR) { f.status = `{"state":"success","total_count":1}` f.checks = `{"check_runs":[{"status":"completed","conclusion":"success"},{"status":"completed","conclusion":"failure"}]}` }, ) if res.Reason != "CI failed (failure)" { t.Errorf("result = %+v, want a CI failure", res) } } func TestWatchGitHubMergeAlerts(t *testing.T) { res := runGitHubWatch(t, pendingPR(), func(f *fakeGitHubPR) { f.pr = strings.Replace(openPR("aaa", "null"), `"merged":false`, `"merged":true`, 1) }, ) if res.Reason != "PR merged" { t.Errorf("result = %+v, want merged", res) } }