fix(github): copy the watch handed to the initial-check goroutine (#2492)

This commit is contained in:
João Salavisa
2026-08-10 18:04:52 +02:00
committed by GitHub
parent a6a26911b7
commit f6fc6b3c72
14 changed files with 5431 additions and 8 deletions
@@ -0,0 +1,667 @@
package github
import (
"context"
"encoding/json"
"net/http"
"net/http/httptest"
"testing"
"time"
"github.com/gin-gonic/gin"
)
// controllerReadStub overrides the read methods the list/search endpoints use.
// The embedded *stubClient supplies no-op defaults for the rest of Client.
type controllerReadStub struct {
*stubClient
orgs []GitHubOrg
orgsErr error
orgRepos []GitHubRepo
orgReposErr error
branches []RepoBranch
branchesErr error
prPage *PRSearchPage
prPageErr error
issuePage *IssueSearchPage
issueErr error
feedback *PRFeedback
feedbackErr error
prStatus *PRStatus
statusErr error
}
func newControllerReadStub() *controllerReadStub {
return &controllerReadStub{stubClient: &stubClient{}}
}
func (s *controllerReadStub) ListUserOrgs(context.Context) ([]GitHubOrg, error) {
return s.orgs, s.orgsErr
}
func (s *controllerReadStub) SearchOrgRepos(context.Context, string, string, int) ([]GitHubRepo, error) {
return s.orgRepos, s.orgReposErr
}
func (s *controllerReadStub) ListRepoBranches(context.Context, string, string) ([]RepoBranch, error) {
return s.branches, s.branchesErr
}
func (s *controllerReadStub) SearchPRsPaged(
context.Context, string, string, int, int,
) (*PRSearchPage, error) {
if s.prPageErr != nil {
return nil, s.prPageErr
}
if s.prPage != nil {
return s.prPage, nil
}
return &PRSearchPage{PRs: []*PR{}}, nil
}
func (s *controllerReadStub) ListIssuesPaged(
context.Context, string, string, int, int,
) (*IssueSearchPage, error) {
if s.issueErr != nil {
return nil, s.issueErr
}
if s.issuePage != nil {
return s.issuePage, nil
}
return &IssueSearchPage{Issues: []*Issue{}}, nil
}
func (s *controllerReadStub) GetPRFeedback(
context.Context, string, string, int,
) (*PRFeedback, error) {
return s.feedback, s.feedbackErr
}
func (s *controllerReadStub) GetPRStatus(context.Context, string, string, int) (*PRStatus, error) {
return s.prStatus, s.statusErr
}
// doControllerRequest issues a request through the wired router and returns the
// recorder so callers can assert both status and decoded body.
func doControllerRequest(router http.Handler, method, target string) *httptest.ResponseRecorder {
request := httptest.NewRequest(method, target, nil)
response := httptest.NewRecorder()
router.ServeHTTP(response, request)
return response
}
// decodeControllerBody decodes a JSON response body into out.
func decodeControllerBody(t *testing.T, response *httptest.ResponseRecorder, out any) {
t.Helper()
if err := json.Unmarshal(response.Body.Bytes(), out); err != nil {
t.Fatalf("decode body %q: %v", response.Body.String(), err)
}
}
// The authenticated user is prepended as a pseudo-org so the picker can offer
// personal repositories alongside real organizations.
func TestController_ListUserOrgs(t *testing.T) {
client := newControllerReadStub()
client.orgs = []GitHubOrg{{Login: "acme", AvatarURL: "https://avatars/acme"}}
router, _ := setupControllerTest(client)
response := doControllerRequest(router, http.MethodGet, "/api/v1/github/orgs")
if response.Code != http.StatusOK {
t.Fatalf("status = %d, want 200; body = %s", response.Code, response.Body)
}
var body struct {
Orgs []GitHubOrg `json:"orgs"`
}
decodeControllerBody(t, response, &body)
if len(body.Orgs) != 2 {
t.Fatalf("orgs = %#v, want the pseudo-org plus acme", body.Orgs)
}
if body.Orgs[0] != (GitHubOrg{Login: "test-user"}) {
t.Errorf("orgs[0] = %#v, want the authenticated user first", body.Orgs[0])
}
if body.Orgs[1] != (GitHubOrg{Login: "acme", AvatarURL: "https://avatars/acme"}) {
t.Errorf("orgs[1] = %#v", body.Orgs[1])
}
}
func TestController_ListUserOrgs_UpstreamFailureIs500(t *testing.T) {
client := newControllerReadStub()
client.orgsErr = &GitHubAPIError{StatusCode: http.StatusUnauthorized, Endpoint: "/user/orgs"}
router, _ := setupControllerTest(client)
response := doControllerRequest(router, http.MethodGet, "/api/v1/github/orgs")
if response.Code != http.StatusInternalServerError {
t.Fatalf("status = %d, want 500; body = %s", response.Code, response.Body)
}
var body struct {
Error string `json:"error"`
}
decodeControllerBody(t, response, &body)
if body.Error == "" {
t.Error("error body is empty, want the upstream message surfaced")
}
}
func TestController_SearchRepos(t *testing.T) {
client := newControllerReadStub()
client.orgRepos = []GitHubRepo{
{FullName: "acme/widget", Owner: "acme", Name: "widget", DefaultBranch: "main"},
}
router, _ := setupControllerTest(client)
response := doControllerRequest(router, http.MethodGet, "/api/v1/github/repos/search?org=acme&q=wid")
if response.Code != http.StatusOK {
t.Fatalf("status = %d, want 200; body = %s", response.Code, response.Body)
}
var body struct {
Repos []GitHubRepo `json:"repos"`
}
decodeControllerBody(t, response, &body)
if len(body.Repos) != 1 || body.Repos[0].FullName != "acme/widget" {
t.Fatalf("repos = %#v", body.Repos)
}
if body.Repos[0].DefaultBranch != "main" {
t.Errorf("default_branch = %q, want main", body.Repos[0].DefaultBranch)
}
}
func TestController_SearchRepos_OrgIsRequired(t *testing.T) {
router, _ := setupControllerTest(newControllerReadStub())
response := doControllerRequest(router, http.MethodGet, "/api/v1/github/repos/search?q=wid")
if response.Code != http.StatusBadRequest {
t.Fatalf("status = %d, want 400; body = %s", response.Code, response.Body)
}
var body struct {
Error string `json:"error"`
}
decodeControllerBody(t, response, &body)
if body.Error != "org query parameter required" {
t.Errorf("error = %q", body.Error)
}
}
func TestController_SearchRepos_UpstreamFailureIs500(t *testing.T) {
client := newControllerReadStub()
client.orgReposErr = &GitHubAPIError{StatusCode: http.StatusForbidden, Endpoint: "/search/repositories"}
router, _ := setupControllerTest(client)
response := doControllerRequest(router, http.MethodGet, "/api/v1/github/repos/search?org=acme")
if response.Code != http.StatusInternalServerError {
t.Fatalf("status = %d, want 500; body = %s", response.Code, response.Body)
}
}
func TestController_ListRepoBranches(t *testing.T) {
client := newControllerReadStub()
client.branches = []RepoBranch{{Name: "main"}, {Name: "release/1.0"}}
router, _ := setupControllerTest(client)
response := doControllerRequest(router, http.MethodGet, "/api/v1/github/repos/acme/widget/branches")
if response.Code != http.StatusOK {
t.Fatalf("status = %d, want 200; body = %s", response.Code, response.Body)
}
var body struct {
Branches []RepoBranch `json:"branches"`
}
decodeControllerBody(t, response, &body)
if len(body.Branches) != 2 || body.Branches[0].Name != "main" ||
body.Branches[1].Name != "release/1.0" {
t.Fatalf("branches = %#v", body.Branches)
}
}
// Upstream status codes must survive to the client so the UI can re-prompt for
// auth on a 401 rather than showing an opaque 500.
func TestController_ListRepoBranches_PreservesUpstreamStatus(t *testing.T) {
cases := []struct {
upstream int
want int
}{
{http.StatusNotFound, http.StatusNotFound},
{http.StatusUnauthorized, http.StatusUnauthorized},
{http.StatusForbidden, http.StatusForbidden},
{http.StatusBadGateway, http.StatusInternalServerError},
}
for _, tc := range cases {
t.Run(http.StatusText(tc.upstream), func(t *testing.T) {
client := newControllerReadStub()
client.branchesErr = &GitHubAPIError{
StatusCode: tc.upstream, Endpoint: "/repos/acme/widget/branches", Body: "upstream said no",
}
router, _ := setupControllerTest(client)
response := doControllerRequest(
router, http.MethodGet, "/api/v1/github/repos/acme/widget/branches",
)
if response.Code != tc.want {
t.Fatalf("status = %d, want %d; body = %s", response.Code, tc.want, response.Body)
}
})
}
}
// GitHub not being configured is its own contract: a 503 carrying a stable
// code the frontend switches on.
func TestController_ListRepoBranches_NotConfiguredIs503WithCode(t *testing.T) {
router, _ := setupControllerTest(nil)
response := doControllerRequest(router, http.MethodGet, "/api/v1/github/repos/acme/widget/branches")
if response.Code != http.StatusServiceUnavailable {
t.Fatalf("status = %d, want 503; body = %s", response.Code, response.Body)
}
var body struct {
Code string `json:"code"`
Error string `json:"error"`
}
decodeControllerBody(t, response, &body)
if body.Code != "github_not_configured" {
t.Errorf("code = %q, want github_not_configured", body.Code)
}
if body.Error == "" {
t.Error("error message is empty, want the remediation hint")
}
}
func TestController_SearchUserPRs(t *testing.T) {
client := newControllerReadStub()
client.prPage = &PRSearchPage{
PRs: []*PR{{Number: 7, Title: "Fix auth", State: "open"}},
TotalCount: 1,
}
router, _ := setupControllerTest(client)
response := doControllerRequest(
router, http.MethodGet, "/api/v1/github/user/prs?filter=is:open&page=2&per_page=25",
)
if response.Code != http.StatusOK {
t.Fatalf("status = %d, want 200; body = %s", response.Code, response.Body)
}
var page PRSearchPage
decodeControllerBody(t, response, &page)
if len(page.PRs) != 1 || page.PRs[0].Number != 7 || page.PRs[0].Title != "Fix auth" {
t.Fatalf("prs = %#v", page.PRs)
}
if page.Page != 2 || page.PerPage != 25 {
t.Errorf("page/per_page = (%d, %d), want (2, 25)", page.Page, page.PerPage)
}
}
// A nil PR slice must serialize as [] rather than null so the frontend can map
// over the result without a guard.
func TestController_SearchUserPRs_NilResultSerializesAsEmptyArray(t *testing.T) {
client := newControllerReadStub()
client.prPage = &PRSearchPage{PRs: nil, TotalCount: 0}
router, _ := setupControllerTest(client)
response := doControllerRequest(router, http.MethodGet, "/api/v1/github/user/prs")
if response.Code != http.StatusOK {
t.Fatalf("status = %d, want 200; body = %s", response.Code, response.Body)
}
var raw map[string]json.RawMessage
decodeControllerBody(t, response, &raw)
if string(raw["prs"]) != "[]" {
t.Errorf("prs = %s, want []", raw["prs"])
}
}
func TestController_SearchUserIssues(t *testing.T) {
client := newControllerReadStub()
client.issuePage = &IssueSearchPage{
Issues: []*Issue{{Number: 3, Title: "Broken login", State: "open"}},
TotalCount: 1,
}
router, _ := setupControllerTest(client)
response := doControllerRequest(router, http.MethodGet, "/api/v1/github/user/issues?query=is:issue")
if response.Code != http.StatusOK {
t.Fatalf("status = %d, want 200; body = %s", response.Code, response.Body)
}
var page IssueSearchPage
decodeControllerBody(t, response, &page)
if len(page.Issues) != 1 || page.Issues[0].Number != 3 || page.Issues[0].Title != "Broken login" {
t.Fatalf("issues = %#v", page.Issues)
}
// Defaults apply when the caller sends no pagination params.
if page.Page != 1 || page.PerPage != 50 {
t.Errorf("page/per_page = (%d, %d), want the (1, 50) defaults", page.Page, page.PerPage)
}
}
func TestController_SearchUserIssues_NilResultSerializesAsEmptyArray(t *testing.T) {
client := newControllerReadStub()
client.issuePage = &IssueSearchPage{Issues: nil}
router, _ := setupControllerTest(client)
response := doControllerRequest(router, http.MethodGet, "/api/v1/github/user/issues")
if response.Code != http.StatusOK {
t.Fatalf("status = %d, want 200; body = %s", response.Code, response.Body)
}
var raw map[string]json.RawMessage
decodeControllerBody(t, response, &raw)
if string(raw["issues"]) != "[]" {
t.Errorf("issues = %s, want []", raw["issues"])
}
}
// Both search endpoints route their failures through handleSearchError, which
// forwards the recognised upstream statuses and collapses everything else.
func TestController_SearchEndpoints_MapUpstreamStatuses(t *testing.T) {
cases := []struct {
upstream int
want int
}{
{http.StatusNotFound, http.StatusNotFound},
{http.StatusUnauthorized, http.StatusUnauthorized},
{http.StatusForbidden, http.StatusForbidden},
{http.StatusTeapot, http.StatusInternalServerError},
}
for _, tc := range cases {
t.Run(http.StatusText(tc.upstream), func(t *testing.T) {
apiErr := &GitHubAPIError{StatusCode: tc.upstream, Endpoint: "/search/issues"}
client := newControllerReadStub()
client.prPageErr = apiErr
client.issueErr = apiErr
router, _ := setupControllerTest(client)
for _, path := range []string{"/api/v1/github/user/prs", "/api/v1/github/user/issues"} {
response := doControllerRequest(router, http.MethodGet, path)
if response.Code != tc.want {
t.Errorf("%s status = %d, want %d; body = %s",
path, response.Code, tc.want, response.Body)
}
}
})
}
}
func TestController_SearchEndpoints_NotConfiguredIs503WithCode(t *testing.T) {
router, _ := setupControllerTest(nil)
for _, path := range []string{"/api/v1/github/user/prs", "/api/v1/github/user/issues"} {
response := doControllerRequest(router, http.MethodGet, path)
if response.Code != http.StatusServiceUnavailable {
t.Errorf("%s status = %d, want 503; body = %s", path, response.Code, response.Body)
continue
}
var body struct {
Code string `json:"code"`
}
decodeControllerBody(t, response, &body)
if body.Code != "github_not_configured" {
t.Errorf("%s code = %q, want github_not_configured", path, body.Code)
}
}
}
func TestController_GetPRFeedback(t *testing.T) {
client := newControllerReadStub()
client.feedback = &PRFeedback{
PR: &PR{Number: 42, Title: "Add widgets", State: "open"},
Reviews: []PRReview{{ID: 1, Author: "alice", State: "APPROVED"}},
Comments: []PRComment{},
Checks: []CheckRun{{Name: "unit", Status: "completed", Conclusion: "failure"}},
HasIssues: true,
}
router, _ := setupControllerTest(client)
response := doControllerRequest(router, http.MethodGet, "/api/v1/github/prs/acme/widget/42")
if response.Code != http.StatusOK {
t.Fatalf("status = %d, want 200; body = %s", response.Code, response.Body)
}
var body PRFeedback
decodeControllerBody(t, response, &body)
if body.PR == nil || body.PR.Number != 42 || body.PR.Title != "Add widgets" {
t.Fatalf("PR = %#v", body.PR)
}
if len(body.Reviews) != 1 || body.Reviews[0].Author != "alice" {
t.Errorf("reviews = %#v", body.Reviews)
}
if len(body.Checks) != 1 || body.Checks[0].Conclusion != "failure" {
t.Errorf("checks = %#v", body.Checks)
}
if !body.HasIssues {
t.Error("has_issues = false, want true")
}
}
func TestController_GetPRFeedback_RejectsANonNumericPRNumber(t *testing.T) {
router, _ := setupControllerTest(newControllerReadStub())
response := doControllerRequest(router, http.MethodGet, "/api/v1/github/prs/acme/widget/abc")
if response.Code != http.StatusBadRequest {
t.Fatalf("status = %d, want 400; body = %s", response.Code, response.Body)
}
var body struct {
Error string `json:"error"`
}
decodeControllerBody(t, response, &body)
if body.Error != "invalid PR number" {
t.Errorf("error = %q", body.Error)
}
}
func TestController_GetPRFeedback_UpstreamFailureIs500(t *testing.T) {
client := newControllerReadStub()
client.feedbackErr = &GitHubAPIError{StatusCode: http.StatusNotFound, Endpoint: "/repos/acme/widget/pulls/42"}
router, _ := setupControllerTest(client)
response := doControllerRequest(router, http.MethodGet, "/api/v1/github/prs/acme/widget/42")
if response.Code != http.StatusInternalServerError {
t.Fatalf("status = %d, want 500; body = %s", response.Code, response.Body)
}
}
func TestController_GetPRStatus(t *testing.T) {
client := newControllerReadStub()
client.prStatus = &PRStatus{
PR: &PR{Number: 42, State: "open"},
ReviewState: computedReviewStateApproved,
ChecksState: "failure",
MergeableState: "blocked",
ReviewCount: 2,
ChecksTotal: 3,
ChecksPassing: 2,
ChecksPopulated: true,
}
router, _ := setupControllerTest(client)
response := doControllerRequest(router, http.MethodGet, "/api/v1/github/prs/acme/widget/42/status")
if response.Code != http.StatusOK {
t.Fatalf("status = %d, want 200; body = %s", response.Code, response.Body)
}
var body PRStatus
decodeControllerBody(t, response, &body)
if body.PR == nil || body.PR.Number != 42 {
t.Fatalf("PR = %#v", body.PR)
}
if body.ReviewState != computedReviewStateApproved || body.ChecksState != "failure" {
t.Errorf("states = (%q, %q)", body.ReviewState, body.ChecksState)
}
if body.MergeableState != "blocked" || body.ReviewCount != 2 {
t.Errorf("mergeable/review count = (%q, %d)", body.MergeableState, body.ReviewCount)
}
if body.ChecksTotal != 3 || body.ChecksPassing != 2 || !body.ChecksPopulated {
t.Errorf("checks = %d/%d populated=%v", body.ChecksPassing, body.ChecksTotal, body.ChecksPopulated)
}
}
func TestController_GetPRStatus_RejectsANonNumericPRNumber(t *testing.T) {
router, _ := setupControllerTest(newControllerReadStub())
response := doControllerRequest(router, http.MethodGet, "/api/v1/github/prs/acme/widget/xyz/status")
if response.Code != http.StatusBadRequest {
t.Fatalf("status = %d, want 400; body = %s", response.Code, response.Body)
}
}
// httpGetPRStatus goes through handleSearchError, so unlike the feedback
// endpoint it forwards the recognised upstream statuses.
func TestController_GetPRStatus_PreservesUpstreamStatus(t *testing.T) {
client := newControllerReadStub()
client.statusErr = &GitHubAPIError{
StatusCode: http.StatusNotFound, Endpoint: "/repos/acme/widget/pulls/42",
}
router, _ := setupControllerTest(client)
response := doControllerRequest(router, http.MethodGet, "/api/v1/github/prs/acme/widget/42/status")
if response.Code != http.StatusNotFound {
t.Fatalf("status = %d, want 404; body = %s", response.Code, response.Body)
}
}
func TestController_GetStats_RejectsMalformedDates(t *testing.T) {
cases := []struct {
name string
target string
want string
}{
{
"bad start_date", "/api/v1/github/stats?start_date=01-02-2026",
"invalid start_date format, expected YYYY-MM-DD",
},
{
"bad end_date", "/api/v1/github/stats?start_date=2026-01-01&end_date=nope",
"invalid end_date format, expected YYYY-MM-DD",
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
router, _ := setupControllerTest(newControllerReadStub())
response := doControllerRequest(router, http.MethodGet, tc.target)
if response.Code != http.StatusBadRequest {
t.Fatalf("status = %d, want 400; body = %s", response.Code, response.Body)
}
var body struct {
Error string `json:"error"`
}
decodeControllerBody(t, response, &body)
if body.Error != tc.want {
t.Errorf("error = %q, want %q", body.Error, tc.want)
}
})
}
}
func TestController_GetWorkspaceSettings_RequiresAWorkspace(t *testing.T) {
router, _ := setupControllerTest(newControllerReadStub())
request := httptest.NewRequest(http.MethodGet, "/api/v1/github/workspace-settings", nil)
request.Header.Set("X-Test-Omit-Workspace", "1")
response := httptest.NewRecorder()
router.ServeHTTP(response, request)
if response.Code != http.StatusBadRequest {
t.Fatalf("status = %d, want 400; body = %s", response.Code, response.Body)
}
var body struct {
Error string `json:"error"`
}
decodeControllerBody(t, response, &body)
if body.Error != "workspace_id query parameter required" {
t.Errorf("error = %q", body.Error)
}
}
// Both auth endpoints route a missing workspace through writeGitHubAuthError,
// so they owe the caller the 400 + github_workspace_required contract the
// frontend switches on — not just "some failure".
func TestController_ClearToken_RequiresAWorkspace(t *testing.T) {
router, _ := setupControllerTest(newControllerReadStub())
request := httptest.NewRequest(http.MethodDelete, "/api/v1/github/token", nil)
request.Header.Set("X-Test-Omit-Workspace", "1")
response := httptest.NewRecorder()
router.ServeHTTP(response, request)
assertWorkspaceRequiredResponse(t, response)
}
func TestController_GetStatus_RequiresAWorkspace(t *testing.T) {
router, _ := setupControllerTest(newControllerReadStub())
request := httptest.NewRequest(http.MethodGet, "/api/v1/github/status", nil)
request.Header.Set("X-Test-Omit-Workspace", "1")
response := httptest.NewRecorder()
router.ServeHTTP(response, request)
assertWorkspaceRequiredResponse(t, response)
}
func assertWorkspaceRequiredResponse(t *testing.T, response *httptest.ResponseRecorder) {
t.Helper()
if response.Code != http.StatusBadRequest {
t.Fatalf("status = %d, want 400; body = %s", response.Code, response.Body)
}
var body struct {
Code string `json:"code"`
Error string `json:"error"`
}
decodeControllerBody(t, response, &body)
if body.Code != "github_workspace_required" {
t.Errorf("code = %q, want github_workspace_required", body.Code)
}
if body.Error == "" {
t.Error("error message is empty")
}
}
// Guard the pagination defaults independently of any one endpoint: page floors
// at 1 and per_page falls back to 50, so a malformed query can never ask GitHub
// for page 0 or an empty page.
func TestParsePaginationQuery(t *testing.T) {
cases := []struct {
name string
query string
wantPage int
wantPerPage int
}{
{"defaults", "", 1, 50},
{"explicit values", "?page=3&per_page=25", 3, 25},
{"zero page floors to 1", "?page=0&per_page=25", 1, 25},
{"negative page floors to 1", "?page=-4&per_page=25", 1, 25},
{"zero per_page falls back", "?page=2&per_page=0", 2, 50},
{"negative per_page falls back", "?page=2&per_page=-1", 2, 50},
{"non-numeric values fall back", "?page=abc&per_page=xyz", 1, 50},
// The 100 cap lives in clampSearchPage, not here.
{"large per_page passes through", "?page=1&per_page=5000", 1, 5000},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
ctx := newPaginationGinContext(t, tc.query)
page, perPage := parsePaginationQuery(ctx)
if page != tc.wantPage || perPage != tc.wantPerPage {
t.Errorf("parsePaginationQuery(%q) = (%d, %d), want (%d, %d)",
tc.query, page, perPage, tc.wantPage, tc.wantPerPage)
}
})
}
}
func TestController_ListUserOrgs_ContextCancellationPropagates(t *testing.T) {
client := newControllerReadStub()
client.orgsErr = context.Canceled
router, _ := setupControllerTest(client)
response := doControllerRequest(router, http.MethodGet, "/api/v1/github/orgs")
if response.Code != http.StatusInternalServerError {
t.Fatalf("status = %d, want 500; body = %s", response.Code, response.Body)
}
}
func TestController_SearchRepos_HonoursTheRequestDeadline(t *testing.T) {
client := newControllerReadStub()
client.orgReposErr = context.DeadlineExceeded
router, _ := setupControllerTest(client)
request := httptest.NewRequest(http.MethodGet, "/api/v1/github/repos/search?org=acme", nil)
ctx, cancel := context.WithTimeout(request.Context(), time.Millisecond)
defer cancel()
request = request.WithContext(ctx)
response := httptest.NewRecorder()
router.ServeHTTP(response, request)
if response.Code != http.StatusInternalServerError {
t.Fatalf("status = %d, want 500; body = %s", response.Code, response.Body)
}
}
// newPaginationGinContext builds a bare gin context carrying only the query
// string, so parsePaginationQuery can be exercised without a route.
func newPaginationGinContext(t *testing.T, query string) *gin.Context {
t.Helper()
ctx, _ := gin.CreateTestContext(httptest.NewRecorder())
ctx.Request = httptest.NewRequest(http.MethodGet, "/search"+query, nil)
return ctx
}
@@ -247,6 +247,18 @@ func (r staticPromptResolver) ResolvePromptContent(context.Context, string, stri
}
func setupControllerStoreTest(t *testing.T) (*gin.Engine, *Store) {
t.Helper()
svc, store := setupWatchServiceTest(t)
ctrl := NewController(svc, newControllerTestLogger())
router := gin.New()
useControllerTestWorkspace(router)
ctrl.RegisterHTTPRoutes(router)
return router, store
}
// setupWatchServiceTest builds a Service backed by a real SQLite store and the
// stub client, with the ws-1 workspace connected so watch checks resolve.
func setupWatchServiceTest(t *testing.T) (*Service, *Store) {
t.Helper()
gin.SetMode(gin.TestMode)
tmp := t.TempDir()
@@ -289,11 +301,7 @@ func setupControllerStoreTest(t *testing.T) (*gin.Engine, *Store) {
return svc.client, AuthMethodPAT, nil
})
svc.SetPromptResolver(staticPromptResolver{content: "resolved default prompt"})
ctrl := NewController(svc, log)
router := gin.New()
useControllerTestWorkspace(router)
ctrl.RegisterHTTPRoutes(router)
return router, store
return svc, store
}
func TestCredentialBrokerReadinessUsesExactResolveRoute(t *testing.T) {
@@ -0,0 +1,722 @@
package github
import (
"bytes"
"context"
"encoding/json"
"fmt"
"net/http"
"net/http/httptest"
"strings"
"testing"
)
// doControllerJSON issues a request carrying a JSON body (marshalled from
// payload, or sent verbatim when payload is a string) and returns the recorder.
func doControllerJSON(
t *testing.T, router http.Handler, method, target string, payload any,
) *httptest.ResponseRecorder {
t.Helper()
request := httptest.NewRequest(method, target, bytes.NewReader(marshalPayload(t, payload)))
request.Header.Set("Content-Type", "application/json")
response := httptest.NewRecorder()
router.ServeHTTP(response, request)
return response
}
func TestController_ListTaskPRs_RequiresAWorkspaceOrTaskIDs(t *testing.T) {
router, _ := setupControllerStoreTest(t)
request := httptest.NewRequest(http.MethodGet, "/api/v1/github/task-prs", nil)
request.Header.Set("X-Test-Omit-Workspace", "1")
response := httptest.NewRecorder()
router.ServeHTTP(response, request)
if response.Code != http.StatusBadRequest {
t.Fatalf("status = %d, want 400; body = %s", response.Code, response.Body)
}
var body struct {
Error string `json:"error"`
}
decodeControllerBody(t, response, &body)
if body.Error != "workspace_id or task_ids query parameter required" {
t.Errorf("error = %q", body.Error)
}
}
func TestController_ListTaskPRs_WorkspaceScoped(t *testing.T) {
router, store := setupControllerStoreTest(t)
seedControllerTaskPR(t, store, "task-1", 7)
response := doControllerRequest(router, http.MethodGet, "/api/v1/github/task-prs?workspace_id=ws-1")
if response.Code != http.StatusOK {
t.Fatalf("status = %d, want 200; body = %s", response.Code, response.Body)
}
var body struct {
TaskPRs map[string][]TaskPR `json:"task_prs"`
}
decodeControllerBody(t, response, &body)
if len(body.TaskPRs) != 1 || len(body.TaskPRs["task-1"]) != 1 {
t.Fatalf("task_prs = %#v, want one association keyed by task-1", body.TaskPRs)
}
got := body.TaskPRs["task-1"][0]
if got.TaskID != "task-1" || got.PRNumber != 7 || got.Owner != "acme" || got.Repo != "widget" {
t.Errorf("task PR = %#v", got)
}
if got.WorkspaceID != "ws-1" || got.State != "open" || got.BaseBranch != "main" {
t.Errorf("task PR = %#v", got)
}
}
// The legacy task_ids form filters by explicit IDs rather than by workspace.
func TestController_ListTaskPRs_LegacyTaskIDsFilter(t *testing.T) {
router, store := setupControllerStoreTest(t)
seedControllerTaskPR(t, store, "task-1", 7)
seedControllerTaskPR(t, store, "task-2", 8)
request := httptest.NewRequest(http.MethodGet, "/api/v1/github/task-prs?task_ids=task-2", nil)
request.Header.Set("X-Test-Omit-Workspace", "1")
response := httptest.NewRecorder()
router.ServeHTTP(response, request)
if response.Code != http.StatusOK {
t.Fatalf("status = %d, want 200; body = %s", response.Code, response.Body)
}
var body struct {
TaskPRs map[string][]TaskPR `json:"task_prs"`
}
decodeControllerBody(t, response, &body)
if len(body.TaskPRs) != 1 {
t.Fatalf("task_prs = %#v, want only the requested task-2", body.TaskPRs)
}
rows := body.TaskPRs["task-2"]
if len(rows) != 1 || rows[0].PRNumber != 8 {
t.Fatalf("task-2 rows = %#v, want PR 8", rows)
}
}
func TestController_GetTaskPR(t *testing.T) {
router, store := setupControllerStoreTest(t)
seedControllerTaskPR(t, store, "task-1", 7)
response := doControllerRequest(router, http.MethodGet, "/api/v1/github/task-prs/task-1")
if response.Code != http.StatusOK {
t.Fatalf("status = %d, want 200; body = %s", response.Code, response.Body)
}
var got TaskPR
decodeControllerBody(t, response, &got)
if got.TaskID != "task-1" || got.PRNumber != 7 {
t.Errorf("task PR = %#v", got)
}
}
// No association is a 204 with no body, not a 404 — the panel treats an empty
// response as "this task has no PR yet".
func TestController_GetTaskPR_MissingAssociationIsNoContent(t *testing.T) {
router, _ := setupControllerStoreTest(t)
response := doControllerRequest(router, http.MethodGet, "/api/v1/github/task-prs/task-unknown")
if response.Code != http.StatusNoContent {
t.Fatalf("status = %d, want 204; body = %s", response.Code, response.Body)
}
if response.Body.Len() != 0 {
t.Errorf("body = %q, want empty", response.Body.String())
}
}
func TestController_CreateTaskPR_Validation(t *testing.T) {
cases := []struct {
name string
payload any
want string
}{
{"malformed JSON", "{not json", "invalid payload"},
{
"missing workspace_id",
map[string]string{"task_id": "task-1", "pr_url": "https://github.com/acme/widget/pull/7"},
"workspace_id, task_id and pr_url are required",
},
{
"missing task_id",
map[string]string{"workspace_id": "ws-1", "pr_url": "https://github.com/acme/widget/pull/7"},
"workspace_id, task_id and pr_url are required",
},
{
"missing pr_url",
map[string]string{"workspace_id": "ws-1", "task_id": "task-1"},
"workspace_id, task_id and pr_url are required",
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
router, _ := setupControllerStoreTest(t)
response := doControllerJSON(t, router, http.MethodPost, "/api/v1/github/task-prs", tc.payload)
if response.Code != http.StatusBadRequest {
t.Fatalf("status = %d, want 400; body = %s", response.Code, response.Body)
}
var body struct {
Error string `json:"error"`
}
decodeControllerBody(t, response, &body)
if body.Error != tc.want {
t.Errorf("error = %q, want %q", body.Error, tc.want)
}
})
}
}
// A URL that is not a PR link is the caller's fault, so it maps to 400 rather
// than collapsing into the generic 500.
func TestController_CreateTaskPR_InvalidPRURLIs400(t *testing.T) {
router, _ := setupControllerStoreTest(t)
response := doControllerJSON(t, router, http.MethodPost, "/api/v1/github/task-prs", map[string]string{
"workspace_id": "ws-1",
"task_id": "task-1",
"pr_url": "https://example.com/not-a-pr",
})
if response.Code != http.StatusBadRequest {
t.Fatalf("status = %d, want 400; body = %s", response.Code, response.Body)
}
}
func TestController_ActionPresets(t *testing.T) {
router, _ := setupControllerStoreTest(t)
t.Run("defaults are returned when nothing is stored", func(t *testing.T) {
response := doControllerRequest(
router, http.MethodGet, "/api/v1/github/action-presets?workspace_id=ws-1",
)
if response.Code != http.StatusOK {
t.Fatalf("status = %d, want 200; body = %s", response.Code, response.Body)
}
var presets ActionPresets
decodeControllerBody(t, response, &presets)
if presets.WorkspaceID != "ws-1" {
t.Errorf("workspace_id = %q", presets.WorkspaceID)
}
if len(presets.PR) != len(DefaultPRActionPresets()) {
t.Errorf("pr presets = %d, want the %d built-ins",
len(presets.PR), len(DefaultPRActionPresets()))
}
if len(presets.Issue) == 0 {
t.Error("issue presets are empty, want the built-ins")
}
})
t.Run("update then read back", func(t *testing.T) {
custom := []ActionPreset{{
ID: "triage", Label: "Triage", Hint: "sort it", Icon: "list",
PromptTemplate: "Triage {{url}}",
}}
response := doControllerJSON(t, router, http.MethodPut, "/api/v1/github/action-presets",
UpdateActionPresetsRequest{WorkspaceID: "ws-1", PR: &custom})
if response.Code != http.StatusOK {
t.Fatalf("update status = %d, want 200; body = %s", response.Code, response.Body)
}
var updated ActionPresets
decodeControllerBody(t, response, &updated)
if len(updated.PR) != 1 || updated.PR[0].ID != "triage" || updated.PR[0].Label != "Triage" {
t.Fatalf("pr presets = %#v", updated.PR)
}
// Issue presets were not supplied, so they must be left untouched.
if len(updated.Issue) == 0 {
t.Error("issue presets were cleared, want them unchanged")
}
readBack := doControllerRequest(
router, http.MethodGet, "/api/v1/github/action-presets?workspace_id=ws-1",
)
var stored ActionPresets
decodeControllerBody(t, readBack, &stored)
if len(stored.PR) != 1 || stored.PR[0].ID != "triage" {
t.Fatalf("stored pr presets = %#v, want the update persisted", stored.PR)
}
})
t.Run("reset restores the built-ins", func(t *testing.T) {
response := doControllerJSON(t, router, http.MethodPost,
"/api/v1/github/action-presets/reset?workspace_id=ws-1", nil)
if response.Code != http.StatusOK {
t.Fatalf("reset status = %d, want 200; body = %s", response.Code, response.Body)
}
var presets ActionPresets
decodeControllerBody(t, response, &presets)
if len(presets.PR) != len(DefaultPRActionPresets()) {
t.Fatalf("pr presets = %d, want the built-ins back", len(presets.PR))
}
})
}
func TestController_ActionPresets_Validation(t *testing.T) {
router, _ := setupControllerStoreTest(t)
cases := []struct {
name string
method string
target string
payload any
want string
}{
{
"get without a workspace", http.MethodGet, "/api/v1/github/action-presets", nil,
"workspace_id query parameter required",
},
{
"reset without a workspace", http.MethodPost, "/api/v1/github/action-presets/reset", nil,
"workspace_id query parameter required",
},
{
"update with malformed JSON", http.MethodPut, "/api/v1/github/action-presets", "{nope",
"invalid payload",
},
{
"update without a workspace", http.MethodPut, "/api/v1/github/action-presets",
map[string]any{}, "workspace_id is required",
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
request := httptest.NewRequest(tc.method, tc.target, bytes.NewReader(marshalPayload(t, tc.payload)))
request.Header.Set("Content-Type", "application/json")
request.Header.Set("X-Test-Omit-Workspace", "1")
response := httptest.NewRecorder()
router.ServeHTTP(response, request)
if response.Code != http.StatusBadRequest {
t.Fatalf("status = %d, want 400; body = %s", response.Code, response.Body)
}
var body struct {
Error string `json:"error"`
}
decodeControllerBody(t, response, &body)
if body.Error != tc.want {
t.Errorf("error = %q, want %q", body.Error, tc.want)
}
})
}
}
func TestController_IssueWatchCRUD(t *testing.T) {
router, _ := setupControllerStoreTest(t)
created := doControllerJSON(t, router, http.MethodPost, "/api/v1/github/watches/issue",
CreateIssueWatchRequest{
WorkspaceID: "ws-1",
WorkflowID: "wf-1",
WorkflowStepID: "step-1",
Repos: []RepoFilter{{Owner: "acme", Name: "widget"}},
Prompt: "fix it",
Labels: []string{"bug"},
CustomQuery: "is:open",
PollIntervalSeconds: 300,
})
if created.Code != http.StatusCreated {
t.Fatalf("create status = %d, want 201; body = %s", created.Code, created.Body)
}
var watch IssueWatch
decodeControllerBody(t, created, &watch)
if watch.ID == "" {
t.Fatal("created watch has no ID")
}
if watch.WorkspaceID != "ws-1" || watch.Prompt != "fix it" || watch.CustomQuery != "is:open" {
t.Errorf("created watch = %#v", watch)
}
if len(watch.Repos) != 1 || watch.Repos[0].Owner != "acme" || watch.Repos[0].Name != "widget" {
t.Errorf("created repos = %#v", watch.Repos)
}
if watch.PollIntervalSeconds != 300 {
t.Errorf("poll interval = %d, want 300", watch.PollIntervalSeconds)
}
t.Run("list returns the stored watch", func(t *testing.T) {
response := doControllerRequest(
router, http.MethodGet, "/api/v1/github/watches/issue?workspace_id=ws-1",
)
if response.Code != http.StatusOK {
t.Fatalf("status = %d, want 200; body = %s", response.Code, response.Body)
}
var body struct {
Watches []IssueWatch `json:"watches"`
}
decodeControllerBody(t, response, &body)
if len(body.Watches) != 1 || body.Watches[0].ID != watch.ID {
t.Fatalf("watches = %#v, want the seeded watch", body.Watches)
}
got := body.Watches[0]
if got.Prompt != "fix it" || got.CustomQuery != "is:open" || !got.Enabled {
t.Errorf("watch = %#v", got)
}
if len(got.Repos) != 1 || got.Repos[0].Owner != "acme" || got.Repos[0].Name != "widget" {
t.Errorf("repos = %#v", got.Repos)
}
if got.PollIntervalSeconds != 300 {
t.Errorf("poll interval = %d, want 300", got.PollIntervalSeconds)
}
})
t.Run("update mutates only the supplied fields", func(t *testing.T) {
newPrompt := "handle it"
disabled := false
response := doControllerJSON(t, router, http.MethodPut,
"/api/v1/github/watches/issue/"+watch.ID+"?workspace_id=ws-1",
UpdateIssueWatchRequest{Prompt: &newPrompt, Enabled: &disabled})
if response.Code != http.StatusOK {
t.Fatalf("update status = %d, want 200; body = %s", response.Code, response.Body)
}
var updated IssueWatch
decodeControllerBody(t, response, &updated)
if updated.Prompt != "handle it" {
t.Errorf("prompt = %q, want the update applied", updated.Prompt)
}
if updated.Enabled {
t.Error("enabled = true, want the update applied")
}
if updated.CustomQuery != "is:open" {
t.Errorf("custom_query = %q, want it left untouched", updated.CustomQuery)
}
if len(updated.Repos) != 1 || updated.Repos[0].Owner != "acme" {
t.Errorf("repos = %#v, want them left untouched", updated.Repos)
}
})
t.Run("delete removes the watch", func(t *testing.T) {
response := doControllerJSON(t, router, http.MethodDelete,
"/api/v1/github/watches/issue/"+watch.ID+"?workspace_id=ws-1", nil)
if response.Code != http.StatusOK {
t.Fatalf("delete status = %d, want 200; body = %s", response.Code, response.Body)
}
var body struct {
Deleted bool `json:"deleted"`
}
decodeControllerBody(t, response, &body)
if !body.Deleted {
t.Error("deleted = false, want true")
}
list := doControllerRequest(router, http.MethodGet, "/api/v1/github/watches/issue?workspace_id=ws-1")
if strings.Contains(list.Body.String(), watch.ID) {
t.Errorf("watch %s still listed after delete: %s", watch.ID, list.Body)
}
})
}
func TestController_IssueWatch_MalformedPayloadIs400(t *testing.T) {
router, _ := setupControllerStoreTest(t)
response := doControllerJSON(t, router, http.MethodPost, "/api/v1/github/watches/issue", "{nope")
if response.Code != http.StatusBadRequest {
t.Fatalf("status = %d, want 400; body = %s", response.Code, response.Body)
}
var body struct {
Error string `json:"error"`
}
decodeControllerBody(t, response, &body)
if body.Error != "invalid payload" {
t.Errorf("error = %q", body.Error)
}
}
func TestController_CreateReviewWatch(t *testing.T) {
router, _ := setupControllerStoreTest(t)
response := doControllerJSON(t, router, http.MethodPost, "/api/v1/github/watches/review",
CreateReviewWatchRequest{
WorkspaceID: "ws-1",
WorkflowID: "wf-1",
WorkflowStepID: "step-1",
Repos: []RepoFilter{{Owner: "acme", Name: "widget"}},
})
if response.Code != http.StatusCreated {
t.Fatalf("status = %d, want 201; body = %s", response.Code, response.Body)
}
var watch ReviewWatch
decodeControllerBody(t, response, &watch)
if watch.ID == "" {
t.Fatal("created watch has no ID")
}
if watch.WorkspaceID != "ws-1" || watch.WorkflowID != "wf-1" {
t.Errorf("created watch = %#v", watch)
}
if len(watch.Repos) != 1 || watch.Repos[0].Owner != "acme" || watch.Repos[0].Name != "widget" {
t.Errorf("created repos = %#v", watch.Repos)
}
}
func TestController_CreateReviewWatch_MalformedPayloadIs400(t *testing.T) {
router, _ := setupControllerStoreTest(t)
response := doControllerJSON(t, router, http.MethodPost, "/api/v1/github/watches/review", "{nope")
if response.Code != http.StatusBadRequest {
t.Fatalf("status = %d, want 400; body = %s", response.Code, response.Body)
}
}
// The trigger-all endpoints are workspace-scoped sweeps; without a workspace
// they would fan out across every workspace, so they refuse.
func TestController_TriggerAllChecks_RequireAWorkspace(t *testing.T) {
router, _ := setupControllerStoreTest(t)
for _, target := range []string{
"/api/v1/github/watches/review/trigger-all",
"/api/v1/github/watches/issue/trigger-all",
} {
t.Run(target, func(t *testing.T) {
request := httptest.NewRequest(http.MethodPost, target, nil)
request.Header.Set("X-Test-Omit-Workspace", "1")
response := httptest.NewRecorder()
router.ServeHTTP(response, request)
if response.Code != http.StatusBadRequest {
t.Fatalf("status = %d, want 400; body = %s", response.Code, response.Body)
}
var body struct {
Error string `json:"error"`
}
decodeControllerBody(t, response, &body)
if body.Error != "workspace_id query parameter required" {
t.Errorf("error = %q", body.Error)
}
})
}
}
func TestController_TriggerAllChecks_ReportNothingFoundOnAnEmptyWorkspace(t *testing.T) {
router, _ := setupControllerStoreTest(t)
cases := []struct {
target string
countAt string
}{
{"/api/v1/github/watches/review/trigger-all?workspace_id=ws-1", "new_prs_found"},
{"/api/v1/github/watches/issue/trigger-all?workspace_id=ws-1", "new_issues_found"},
}
for _, tc := range cases {
t.Run(tc.countAt, func(t *testing.T) {
response := doControllerJSON(t, router, http.MethodPost, tc.target, nil)
if response.Code != http.StatusOK {
t.Fatalf("status = %d, want 200; body = %s", response.Code, response.Body)
}
var body map[string]int
decodeControllerBody(t, response, &body)
count, ok := body[tc.countAt]
if !ok {
t.Fatalf("body = %s, want a %q field", response.Body, tc.countAt)
}
if count != 0 {
t.Errorf("%s = %d, want 0 with no watches configured", tc.countAt, count)
}
})
}
}
func TestController_CleanupEndpoints(t *testing.T) {
router, _ := setupControllerStoreTest(t)
for _, target := range []string{
"/api/v1/github/cleanup/review-tasks?workspace_id=ws-1",
"/api/v1/github/cleanup/issue-tasks?workspace_id=ws-1",
// No workspace_id takes the cleanup-everything branch.
"/api/v1/github/cleanup/review-tasks",
"/api/v1/github/cleanup/issue-tasks",
} {
t.Run(target, func(t *testing.T) {
request := httptest.NewRequest(http.MethodPost, target, nil)
request.Header.Set("X-Test-Omit-Workspace", "1")
response := httptest.NewRecorder()
router.ServeHTTP(response, request)
if response.Code != http.StatusOK {
t.Fatalf("status = %d, want 200; body = %s", response.Code, response.Body)
}
var body struct {
Deleted int `json:"deleted"`
}
decodeControllerBody(t, response, &body)
if body.Deleted != 0 {
t.Errorf("deleted = %d, want 0 with nothing to clean up", body.Deleted)
}
})
}
}
func TestController_WorkspaceSettings_UpdateAndRead(t *testing.T) {
router, _ := setupControllerStoreTest(t)
mode := RepoScopeModeOrgs
orgs := []string{"acme"}
updated := doControllerJSON(t, router, http.MethodPut, "/api/v1/github/workspace-settings",
UpdateWorkspaceSettingsRequest{WorkspaceID: "ws-1", RepoScopeMode: &mode, RepoScopeOrgs: &orgs})
if updated.Code != http.StatusOK {
t.Fatalf("update status = %d, want 200; body = %s", updated.Code, updated.Body)
}
var settings WorkspaceSettings
decodeControllerBody(t, updated, &settings)
if settings.RepoScopeMode != RepoScopeModeOrgs {
t.Errorf("repo_scope_mode = %q, want orgs", settings.RepoScopeMode)
}
if len(settings.RepoScopeOrgs) != 1 || settings.RepoScopeOrgs[0] != "acme" {
t.Errorf("repo_scope_orgs = %#v", settings.RepoScopeOrgs)
}
readBack := doControllerRequest(
router, http.MethodGet, "/api/v1/github/workspace-settings?workspace_id=ws-1",
)
if readBack.Code != http.StatusOK {
t.Fatalf("read status = %d, want 200; body = %s", readBack.Code, readBack.Body)
}
var stored WorkspaceSettings
decodeControllerBody(t, readBack, &stored)
if stored.RepoScopeMode != RepoScopeModeOrgs || len(stored.RepoScopeOrgs) != 1 {
t.Fatalf("stored settings = %#v, want the update persisted", stored)
}
}
func TestController_WorkspaceSettings_RejectsAnInvalidScopeMode(t *testing.T) {
router, _ := setupControllerStoreTest(t)
mode := "not-a-mode"
response := doControllerJSON(t, router, http.MethodPut, "/api/v1/github/workspace-settings",
UpdateWorkspaceSettingsRequest{WorkspaceID: "ws-1", RepoScopeMode: &mode})
if response.Code != http.StatusBadRequest {
t.Fatalf("status = %d, want 400; body = %s", response.Code, response.Body)
}
}
func TestController_WorkspaceSettings_MalformedPayloadIs400(t *testing.T) {
router, _ := setupControllerStoreTest(t)
response := doControllerJSON(t, router, http.MethodPut, "/api/v1/github/workspace-settings", "{nope")
if response.Code != http.StatusBadRequest {
t.Fatalf("status = %d, want 400; body = %s", response.Code, response.Body)
}
var body struct {
Error string `json:"error"`
}
decodeControllerBody(t, response, &body)
if body.Error != "invalid payload" {
t.Errorf("error = %q", body.Error)
}
}
func TestController_CopyWorkspaceSettings_Validation(t *testing.T) {
router, _ := setupControllerStoreTest(t)
cases := []struct {
name string
target string
payload any
omitWS bool
wantErrMsg string
}{
{
"missing source workspace", "/api/v1/github/workspace-settings/copy",
map[string]string{"targetWorkspaceId": "ws-2"}, true,
"workspace_id query parameter required",
},
{
"malformed payload", "/api/v1/github/workspace-settings/copy?workspace_id=ws-1",
"{nope", false, "invalid payload",
},
{
"missing target", "/api/v1/github/workspace-settings/copy?workspace_id=ws-1",
map[string]string{}, false, "targetWorkspaceId required",
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
request := httptest.NewRequest(
http.MethodPost, tc.target, bytes.NewReader(marshalPayload(t, tc.payload)),
)
request.Header.Set("Content-Type", "application/json")
if tc.omitWS {
request.Header.Set("X-Test-Omit-Workspace", "1")
}
response := httptest.NewRecorder()
router.ServeHTTP(response, request)
if response.Code != http.StatusBadRequest {
t.Fatalf("status = %d, want 400; body = %s", response.Code, response.Body)
}
var body struct {
Error string `json:"error"`
}
decodeControllerBody(t, response, &body)
if body.Error != tc.wantErrMsg {
t.Errorf("error = %q, want %q", body.Error, tc.wantErrMsg)
}
})
}
}
// Copying a workspace onto itself is rejected rather than silently no-oping.
func TestController_CopyWorkspaceSettings_RejectsTheSameWorkspace(t *testing.T) {
router, _ := setupControllerStoreTest(t)
response := doControllerJSON(t, router, http.MethodPost,
"/api/v1/github/workspace-settings/copy?workspace_id=ws-1",
map[string]string{"targetWorkspaceId": "ws-1"})
if response.Code != http.StatusBadRequest {
t.Fatalf("status = %d, want 400; body = %s", response.Code, response.Body)
}
}
func TestController_ConfigureToken_Validation(t *testing.T) {
router, _ := setupControllerStoreTest(t)
t.Run("missing workspace", func(t *testing.T) {
request := httptest.NewRequest(http.MethodPost, "/api/v1/github/token",
strings.NewReader(`{"token":"ghp_x"}`))
request.Header.Set("Content-Type", "application/json")
request.Header.Set("X-Test-Omit-Workspace", "1")
response := httptest.NewRecorder()
router.ServeHTTP(response, request)
if response.Code == http.StatusOK {
t.Fatalf("status = %d, want a failure; body = %s", response.Code, response.Body)
}
})
t.Run("malformed payload", func(t *testing.T) {
response := doControllerJSON(t, router, http.MethodPost,
"/api/v1/github/token?workspace_id=ws-1", "{nope")
if response.Code != http.StatusBadRequest {
t.Fatalf("status = %d, want 400; body = %s", response.Code, response.Body)
}
var body struct {
Error string `json:"error"`
}
decodeControllerBody(t, response, &body)
if body.Error != "invalid payload: token is required" {
t.Errorf("error = %q", body.Error)
}
})
}
// marshalPayload encodes a test payload, passing strings through verbatim so a
// case can send deliberately malformed JSON.
func marshalPayload(t *testing.T, payload any) []byte {
t.Helper()
switch typed := payload.(type) {
case nil:
return nil
case string:
return []byte(typed)
default:
encoded, err := json.Marshal(typed)
if err != nil {
t.Fatalf("marshal payload: %v", err)
}
return encoded
}
}
// seedControllerTaskPR persists one task→PR association in the ws-1 workspace,
// along with the task row the workspace-scoped listing joins against.
func seedControllerTaskPR(t *testing.T, store *Store, taskID string, prNumber int) *TaskPR {
t.Helper()
if _, err := store.db.Exec(
`INSERT INTO tasks (id, workspace_id, title) VALUES (?, 'ws-1', ?)`, taskID, taskID,
); err != nil {
t.Fatalf("seed task row: %v", err)
}
tp := &TaskPR{
WorkspaceID: "ws-1",
TaskID: taskID,
Owner: "acme",
Repo: "widget",
PRNumber: prNumber,
PRURL: fmt.Sprintf("https://github.com/acme/widget/pull/%d", prNumber),
PRTitle: fmt.Sprintf("PR %d", prNumber),
HeadBranch: fmt.Sprintf("feature-%d", prNumber),
BaseBranch: "main",
AuthorLogin: "octocat",
State: "open",
}
if err := store.CreateTaskPR(context.Background(), tp); err != nil {
t.Fatalf("seed task PR: %v", err)
}
return tp
}
@@ -0,0 +1,787 @@
package github
import (
"context"
"encoding/json"
"errors"
"net/http"
"strings"
"testing"
"time"
)
func TestGHClient_SearchOrgRepos(t *testing.T) {
cases := []struct {
name string
query string
limit int
wantQ string
wantP string
}{
{"no free-text query", "", 30, "q=org:acme", "per_page=30"},
{"with free-text query", "widget", 30, "q=org:acme widget", "per_page=30"},
{"limit clamps to the cap", "", 900, "q=org:acme", "per_page=100"},
{"zero limit takes the default", "", 0, "q=org:acme", "per_page=20"},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
calls := newFakeGH(t, ghResponse{
Prefix: "api search/repositories",
Stdout: `[{"full_name":"acme/widget","owner":{"login":"acme"},"name":"widget",
"private":true,"default_branch":"main","description":"w",
"pushed_at":"2026-06-01T00:00:00Z"}]`,
})
repos, err := NewGHClient().SearchOrgRepos(context.Background(), "acme", tc.query, tc.limit)
if err != nil {
t.Fatalf("SearchOrgRepos: %v", err)
}
argv := calls(t)[0]
if !containsPair(argv, "-f", tc.wantQ) || !containsPair(argv, "-f", tc.wantP) {
t.Errorf("argv = %q, want -f %q and -f %q", argv, tc.wantQ, tc.wantP)
}
if !containsPair(argv, "--jq", ".items") {
t.Errorf("argv = %q, want --jq .items to unwrap the search envelope", argv)
}
if len(repos) != 1 {
t.Fatalf("repos = %#v, want one", repos)
}
got := repos[0]
if got.FullName != "acme/widget" || got.Owner != "acme" || got.Name != "widget" {
t.Errorf("identity = %#v", got)
}
if !got.Private || got.DefaultBranch != "main" || got.Description != "w" {
t.Errorf("attributes = %#v", got)
}
if got.PushedAt == nil || !got.PushedAt.Equal(time.Date(2026, 6, 1, 0, 0, 0, 0, time.UTC)) {
t.Errorf("pushed_at = %v", got.PushedAt)
}
})
}
}
func TestGHClient_SearchOrgRepos_Error(t *testing.T) {
newFakeGH(t, ghResponse{Prefix: "api search/repositories", Stderr: "boom", Exit: 1})
repos, err := NewGHClient().SearchOrgRepos(context.Background(), "acme", "", 10)
if repos != nil {
t.Errorf("repos = %#v, want nil", repos)
}
if err == nil || !strings.Contains(err.Error(), "search org repos") {
t.Fatalf("err = %v, want a wrapped search-org-repos error", err)
}
}
func TestGHClient_ListUserRepos_ResolvesTheLoginFirst(t *testing.T) {
calls := newFakeGH(t,
ghResponse{Prefix: "api user -q", Stdout: "octocat\n"},
ghResponse{
Prefix: "api search/repositories",
Stdout: `[{"full_name":"octocat/demo","owner":{"login":"octocat"},"name":"demo",
"default_branch":"main","description":"Public demo"}]`,
},
)
repos, err := NewGHClient().ListUserRepos(context.Background(), "language:go", 50)
if err != nil {
t.Fatalf("ListUserRepos: %v", err)
}
recorded := calls(t)
assertGHArgv(t, recorded, 0, []string{"api", "user", "-q", ".login"})
if !containsPair(recorded[1], "-f", "q=user:octocat language:go") {
t.Errorf("argv = %q, want the resolved login folded into the q qualifier", recorded[1])
}
if len(repos) != 1 || repos[0].FullName != "octocat/demo" {
t.Fatalf("repos = %#v", repos)
}
if repos[0].DefaultBranch != "main" || repos[0].Description != "Public demo" {
t.Errorf("repo = %#v", repos[0])
}
}
func TestGHClient_ListUserRepos_AuthFailureSkipsTheSearch(t *testing.T) {
calls := newFakeGH(t, ghResponse{Prefix: "api user -q", Stderr: "HTTP 401", Exit: 1})
repos, err := NewGHClient().ListUserRepos(context.Background(), "", 20)
if repos != nil {
t.Errorf("repos = %#v, want nil", repos)
}
if err == nil || !strings.Contains(err.Error(), "list user repos") {
t.Fatalf("err = %v, want a wrapped list-user-repos error", err)
}
if len(calls(t)) != 1 {
t.Errorf("gh calls = %d, want 1 — the repo search must not run after auth fails", len(calls(t)))
}
}
func TestGHClient_ListAccessibleRepos(t *testing.T) {
calls := newFakeGH(t, ghResponse{
Prefix: "api /user/repos",
Stdout: `[
{"full_name":"acme/widget","owner":{"login":"acme"},"name":"widget"},
{"full_name":"acme/gadget","owner":{"login":"acme"},"name":"gadget"}
]`,
})
repos, err := NewGHClient().ListAccessibleRepos(context.Background(), "WIDGET", 5000)
if err != nil {
t.Fatalf("ListAccessibleRepos: %v", err)
}
assertGHArgv(t, calls(t), 0, []string{
"api", "/user/repos?affiliation=owner,collaborator,organization_member&sort=pushed&per_page=100",
})
if len(repos) != 1 || repos[0].FullName != "acme/widget" {
t.Fatalf("repos = %#v, want the case-insensitive full_name match only", repos)
}
}
func TestGHClient_ListAccessibleRepos_Errors(t *testing.T) {
t.Run("command failure", func(t *testing.T) {
newFakeGH(t, ghResponse{Prefix: "api /user/repos", Stderr: "boom", Exit: 1})
repos, err := NewGHClient().ListAccessibleRepos(context.Background(), "", 20)
if repos != nil {
t.Errorf("repos = %#v, want nil", repos)
}
if err == nil || !strings.Contains(err.Error(), "list accessible repos") {
t.Fatalf("err = %v, want a wrapped error", err)
}
})
t.Run("unparseable output", func(t *testing.T) {
newFakeGH(t, ghResponse{Prefix: "api /user/repos", Stdout: "nope"})
_, err := NewGHClient().ListAccessibleRepos(context.Background(), "", 20)
if err == nil || !strings.Contains(err.Error(), "parse search repos") {
t.Fatalf("err = %v, want a parse failure", err)
}
})
}
// The reviews endpoint carries both an `author` (GraphQL shape) and a `user`
// (REST shape); `user` wins because only it also carries the avatar.
func TestGHClient_ListPRReviews_PrefersTheRESTUserOverAuthor(t *testing.T) {
calls := newFakeGH(t, ghResponse{
Prefix: "api repos/",
Stdout: `[
{"id":1,"state":"APPROVED","body":"lgtm","submitted_at":"2026-01-05T10:00:00Z",
"author":{"login":"stale-author"},
"user":{"login":"alice","avatar_url":"https://avatars/alice"}},
{"id":2,"state":"COMMENTED","body":"note","submitted_at":"2026-01-06T10:00:00Z",
"author":{"login":"bob"}}
]`,
})
reviews, err := NewGHClient().ListPRReviews(context.Background(), "acme", "widget", 42)
if err != nil {
t.Fatalf("ListPRReviews: %v", err)
}
assertGHArgv(t, calls(t), 0, []string{
"api", "repos/acme/widget/pulls/42/reviews", "--paginate",
})
if len(reviews) != 2 {
t.Fatalf("reviews = %#v, want 2", reviews)
}
want := PRReview{
ID: 1, Author: "alice", AuthorAvatar: "https://avatars/alice",
State: "APPROVED", Body: "lgtm",
CreatedAt: time.Date(2026, 1, 5, 10, 0, 0, 0, time.UTC),
}
if reviews[0] != want {
t.Errorf("reviews[0] = %#v, want %#v", reviews[0], want)
}
// With no `user` block the author falls back to the GraphQL login and
// there is no avatar to carry.
if reviews[1].Author != "bob" || reviews[1].AuthorAvatar != "" {
t.Errorf("reviews[1] = %#v, want the author fallback with no avatar", reviews[1])
}
}
func TestGHClient_ListPRReviews_Errors(t *testing.T) {
t.Run("command failure", func(t *testing.T) {
newFakeGH(t, ghResponse{Prefix: "api repos/", Stderr: "boom", Exit: 1})
_, err := NewGHClient().ListPRReviews(context.Background(), "acme", "widget", 42)
if err == nil || !strings.Contains(err.Error(), "list PR reviews") {
t.Fatalf("err = %v, want a wrapped error", err)
}
})
t.Run("unparseable output", func(t *testing.T) {
newFakeGH(t, ghResponse{Prefix: "api repos/", Stdout: "nope"})
_, err := NewGHClient().ListPRReviews(context.Background(), "acme", "widget", 42)
if err == nil || !strings.Contains(err.Error(), "parse reviews") {
t.Fatalf("err = %v, want a parse failure", err)
}
})
}
func TestGHClient_ListPRComments_MergesBothEndpointsInTimeOrder(t *testing.T) {
calls := newFakeGH(t,
ghResponse{
Prefix: "api repos/acme/widget/pulls/42/comments",
Stdout: `[{"id":20,"path":"main.go","line":7,"side":"RIGHT","body":"inline note",
"created_at":"2026-01-05T12:00:00Z","updated_at":"2026-01-05T12:30:00Z",
"in_reply_to_id":19,"user":{"login":"alice","avatar_url":"https://a","type":"User"}}]`,
},
ghResponse{
Prefix: "api repos/acme/widget/issues/42/comments",
Stdout: `[{"id":10,"body":"conversation note","created_at":"2026-01-05T09:00:00Z",
"updated_at":"2026-01-05T09:00:00Z",
"user":{"login":"dependabot","avatar_url":"https://d","type":"Bot"}}]`,
},
)
comments, err := NewGHClient().ListPRComments(context.Background(), "acme", "widget", 42, nil)
if err != nil {
t.Fatalf("ListPRComments: %v", err)
}
recorded := calls(t)
assertGHArgv(t, recorded, 0, []string{"api", "repos/acme/widget/pulls/42/comments", "--paginate"})
assertGHArgv(t, recorded, 1, []string{"api", "repos/acme/widget/issues/42/comments", "--paginate"})
if len(comments) != 2 {
t.Fatalf("comments = %#v, want 2", comments)
}
if comments[0].ID != 10 || comments[0].CommentType != commentTypeIssue || !comments[0].AuthorIsBot {
t.Errorf("comments[0] = %#v, want the older bot-authored issue comment first", comments[0])
}
second := comments[1]
if second.ID != 20 || second.CommentType != commentTypeReview || second.AuthorIsBot {
t.Errorf("comments[1] = %#v", second)
}
if second.Path != "main.go" || second.Line != 7 || second.Side != "RIGHT" {
t.Errorf("comments[1] location = %#v", second)
}
if second.InReplyTo == nil || *second.InReplyTo != 19 {
t.Errorf("in_reply_to = %v, want 19", second.InReplyTo)
}
}
func TestGHClient_ListPRComments_AppendsSinceToBothEndpoints(t *testing.T) {
calls := newFakeGH(t, ghResponse{Prefix: "api repos/", Stdout: `[]`})
since := time.Date(2026, 1, 2, 3, 4, 5, 0, time.UTC)
if _, err := NewGHClient().ListPRComments(context.Background(), "acme", "widget", 42, &since); err != nil {
t.Fatalf("ListPRComments: %v", err)
}
recorded := calls(t)
if len(recorded) != 2 {
t.Fatalf("gh calls = %d, want 2", len(recorded))
}
wantSuffix := "?since=" + "2026-01-02T03%3A04%3A05Z"
for i, argv := range recorded {
if !strings.HasSuffix(argv[1], wantSuffix) {
t.Errorf("argv[%d] endpoint = %q, want the escaped since suffix %q", i, argv[1], wantSuffix)
}
}
}
func TestGHClient_ListPRComments_Errors(t *testing.T) {
t.Run("review leg failure", func(t *testing.T) {
newFakeGH(t, ghResponse{Prefix: "api repos/acme/widget/pulls/", Stderr: "boom", Exit: 1})
_, err := NewGHClient().ListPRComments(context.Background(), "acme", "widget", 42, nil)
if err == nil || !strings.Contains(err.Error(), "list PR comments") {
t.Fatalf("err = %v, want a wrapped review-comments error", err)
}
})
t.Run("issue leg failure", func(t *testing.T) {
newFakeGH(t,
ghResponse{Prefix: "api repos/acme/widget/pulls/", Stdout: `[]`},
ghResponse{Prefix: "api repos/acme/widget/issues/", Stderr: "boom", Exit: 1},
)
_, err := NewGHClient().ListPRComments(context.Background(), "acme", "widget", 42, nil)
if err == nil || !strings.Contains(err.Error(), "list issue comments") {
t.Fatalf("err = %v, want a wrapped issue-comments error", err)
}
})
t.Run("unparseable review comments", func(t *testing.T) {
newFakeGH(t, ghResponse{Prefix: "api repos/acme/widget/pulls/", Stdout: "nope"})
_, err := NewGHClient().ListPRComments(context.Background(), "acme", "widget", 42, nil)
if err == nil || !strings.Contains(err.Error(), "parse comments") {
t.Fatalf("err = %v, want a parse failure", err)
}
})
t.Run("unparseable issue comments", func(t *testing.T) {
newFakeGH(t,
ghResponse{Prefix: "api repos/acme/widget/pulls/", Stdout: `[]`},
ghResponse{Prefix: "api repos/acme/widget/issues/", Stdout: "nope"},
)
_, err := NewGHClient().ListPRComments(context.Background(), "acme", "widget", 42, nil)
if err == nil || !strings.Contains(err.Error(), "parse issue comments") {
t.Fatalf("err = %v, want a parse failure", err)
}
})
}
func TestAppendSinceQuery(t *testing.T) {
const endpoint = "repos/o/r/pulls/1/comments"
if got := appendSinceQuery(endpoint, nil); got != endpoint {
t.Errorf("appendSinceQuery(nil) = %q, want the endpoint unchanged", got)
}
since := time.Date(2026, 1, 2, 3, 4, 5, 0, time.UTC)
want := endpoint + "?since=2026-01-02T03%3A04%3A05Z"
if got := appendSinceQuery(endpoint, &since); got != want {
t.Errorf("appendSinceQuery = %q, want %q", got, want)
}
}
// A 404 means "no protection rule" and a 403 means "no rule we can see"
// (the token lacks Administration: Read). Both must be cached as HasRule=false
// without an error so the poller stops re-asking.
func TestGHClient_FetchBranchProtection(t *testing.T) {
cases := []struct {
name string
resp ghResponse
wantHasRule bool
wantRequired int
wantErr bool
}{
{
name: "rule with a required approval count",
resp: ghResponse{
Prefix: "api repos/",
Stdout: `{"required_pull_request_reviews":{"required_approving_review_count":2}}`,
},
wantHasRule: true, wantRequired: 2,
},
{
name: "rule without a review requirement",
resp: ghResponse{Prefix: "api repos/", Stdout: `{"required_pull_request_reviews":null}`},
wantHasRule: true,
},
{
name: "404 maps to no rule",
resp: ghResponse{Prefix: "api repos/", Stderr: "gh: HTTP 404: Not Found", Exit: 1},
},
{
name: "403 maps to no rule",
resp: ghResponse{Prefix: "api repos/", Stderr: "gh: HTTP 403: Forbidden", Exit: 1},
},
{
name: "500 propagates",
resp: ghResponse{Prefix: "api repos/", Stderr: "gh: HTTP 500: server error", Exit: 1},
wantErr: true,
},
{
name: "unparseable payload propagates",
resp: ghResponse{Prefix: "api repos/", Stdout: "nope"},
wantErr: true,
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
calls := newFakeGH(t, tc.resp)
got, err := NewGHClient().FetchBranchProtection(context.Background(), "acme", "widget", "main")
if tc.wantErr {
if err == nil {
t.Fatalf("err = nil, want an error; protection = %#v", got)
}
return
}
if err != nil {
t.Fatalf("FetchBranchProtection: %v", err)
}
assertGHArgv(t, calls(t), 0, []string{
"api", "repos/acme/widget/branches/main/protection",
})
if got.HasRule != tc.wantHasRule {
t.Errorf("HasRule = %v, want %v", got.HasRule, tc.wantHasRule)
}
if got.RequiredApprovingReviewCount != tc.wantRequired {
t.Errorf("required count = %d, want %d",
got.RequiredApprovingReviewCount, tc.wantRequired)
}
})
}
}
func TestGHClient_ListPRFiles(t *testing.T) {
calls := newFakeGH(t, ghResponse{
Prefix: "api repos/",
Stdout: `[
{"filename":"main.go","status":"modified","additions":4,"deletions":1,
"patch":"@@ -1 +1 @@\n-old\n+new"},
{"filename":"new.go","previous_filename":"old.go","status":"renamed"}
]`,
})
files, err := NewGHClient().ListPRFiles(context.Background(), "acme", "widget", 42)
if err != nil {
t.Fatalf("ListPRFiles: %v", err)
}
assertGHArgv(t, calls(t), 0, []string{"api", "repos/acme/widget/pulls/42/files", "--paginate"})
if len(files) != 2 {
t.Fatalf("files = %#v, want 2", files)
}
if files[0].Filename != "main.go" || files[0].Additions != 4 || files[0].Deletions != 1 {
t.Errorf("files[0] = %#v", files[0])
}
if !strings.Contains(files[0].Patch, "+new") {
t.Errorf("files[0] patch = %q, want the hunk preserved", files[0].Patch)
}
if files[1].OldPath != "old.go" || files[1].Status != "renamed" {
t.Errorf("files[1] = %#v, want the rename source preserved", files[1])
}
}
func TestGHClient_ListPRFiles_Errors(t *testing.T) {
t.Run("command failure", func(t *testing.T) {
newFakeGH(t, ghResponse{Prefix: "api repos/", Stderr: "boom", Exit: 1})
files, err := NewGHClient().ListPRFiles(context.Background(), "acme", "widget", 42)
if files != nil {
t.Errorf("files = %#v, want nil", files)
}
if err == nil || !strings.Contains(err.Error(), "list PR files") {
t.Fatalf("err = %v, want a wrapped error", err)
}
})
t.Run("unparseable output", func(t *testing.T) {
newFakeGH(t, ghResponse{Prefix: "api repos/", Stdout: "nope"})
_, err := NewGHClient().ListPRFiles(context.Background(), "acme", "widget", 42)
if err == nil || !strings.Contains(err.Error(), "parse PR files") {
t.Fatalf("err = %v, want a parse failure", err)
}
})
}
func TestGHClient_ListPRCommits(t *testing.T) {
calls := newFakeGH(t, ghResponse{
Prefix: "api repos/",
Stdout: `[
{"sha":"aaa","commit":{"message":"feat: add thing\n\nlong body",
"author":{"date":"2026-01-07T10:00:00Z"}},"author":{"login":"alice"}},
{"sha":"bbb","commit":{"message":"fix: typo","author":{"date":"2026-01-08T10:00:00Z"}}}
]`,
})
commits, err := NewGHClient().ListPRCommits(context.Background(), "acme", "widget", 42)
if err != nil {
t.Fatalf("ListPRCommits: %v", err)
}
assertGHArgv(t, calls(t), 0, []string{"api", "repos/acme/widget/pulls/42/commits", "--paginate"})
if len(commits) != 2 {
t.Fatalf("commits = %#v, want 2", commits)
}
if commits[0].SHA != "aaa" || commits[0].AuthorLogin != "alice" {
t.Errorf("commits[0] = %#v", commits[0])
}
if commits[0].Message != "feat: add thing" {
t.Errorf("commits[0] message = %q, want only the subject line", commits[0].Message)
}
if commits[0].AuthorDate != "2026-01-07T10:00:00Z" || commits[0].StatsAvailable {
t.Errorf("commits[0] = %#v, want the raw date and no stats", commits[0])
}
if commits[1].AuthorLogin != "" {
t.Errorf("commits[1] author = %q, want empty for an unmatched account", commits[1].AuthorLogin)
}
}
func TestGHClient_ListPRCommits_Errors(t *testing.T) {
t.Run("command failure", func(t *testing.T) {
newFakeGH(t, ghResponse{Prefix: "api repos/", Stderr: "boom", Exit: 1})
_, err := NewGHClient().ListPRCommits(context.Background(), "acme", "widget", 42)
if err == nil || !strings.Contains(err.Error(), "list PR commits") {
t.Fatalf("err = %v, want a wrapped error", err)
}
})
t.Run("unparseable output", func(t *testing.T) {
newFakeGH(t, ghResponse{Prefix: "api repos/", Stdout: "nope"})
_, err := NewGHClient().ListPRCommits(context.Background(), "acme", "widget", 42)
if err == nil || !strings.Contains(err.Error(), "parse PR commits") {
t.Fatalf("err = %v, want a parse failure", err)
}
})
}
func TestGHClient_GetPRCommitDetail_RejectsANonSHA(t *testing.T) {
calls := newFakeGH(t, ghResponse{Prefix: "api repos/", Stdout: `[]`})
_, err := NewGHClient().GetPRCommitDetail(context.Background(), "acme", "widget", "not-a-sha")
if err == nil || !strings.Contains(err.Error(), "invalid commit SHA") {
t.Fatalf("err = %v, want the SHA validation to reject it", err)
}
if len(calls(t)) != 0 {
t.Errorf("gh calls = %d, want 0 — validation must run before exec", len(calls(t)))
}
}
func TestGHClient_SubmitReview(t *testing.T) {
t.Run("approve without a body omits the body field", func(t *testing.T) {
calls := newFakeGH(t, ghResponse{Prefix: "api repos/", Stdout: `{}`})
if err := NewGHClient().SubmitReview(
context.Background(), "acme", "widget", 42, "APPROVE", "",
); err != nil {
t.Fatalf("SubmitReview: %v", err)
}
assertGHArgv(t, calls(t), 0, []string{
"api", "repos/acme/widget/pulls/42/reviews", "-X", "POST", "-f", "event=APPROVE",
})
})
t.Run("request changes carries the body", func(t *testing.T) {
calls := newFakeGH(t, ghResponse{Prefix: "api repos/", Stdout: `{}`})
if err := NewGHClient().SubmitReview(
context.Background(), "acme", "widget", 42, "REQUEST_CHANGES", "please fix",
); err != nil {
t.Fatalf("SubmitReview: %v", err)
}
assertGHArgv(t, calls(t), 0, []string{
"api", "repos/acme/widget/pulls/42/reviews", "-X", "POST",
"-f", "event=REQUEST_CHANGES", "-f", "body=please fix",
})
})
t.Run("failure names the PR", func(t *testing.T) {
newFakeGH(t, ghResponse{Prefix: "api repos/", Stderr: "HTTP 422", Exit: 1})
err := NewGHClient().SubmitReview(context.Background(), "acme", "widget", 42, "APPROVE", "")
if err == nil || !strings.Contains(err.Error(), "submit review on PR #42") {
t.Fatalf("err = %v, want the PR named in the wrap", err)
}
})
}
func TestGHClient_MergePR(t *testing.T) {
t.Run("sends the merge method", func(t *testing.T) {
calls := newFakeGH(t, ghResponse{Prefix: "api repos/", Stdout: `{"merged":true}`})
if err := NewGHClient().MergePR(context.Background(), "acme", "widget", 42, "squash"); err != nil {
t.Fatalf("MergePR: %v", err)
}
assertGHArgv(t, calls(t), 0, []string{
"api", "repos/acme/widget/pulls/42/merge", "-X", "PUT", "-f", "merge_method=squash",
})
})
t.Run("omits the merge method when unset", func(t *testing.T) {
calls := newFakeGH(t, ghResponse{Prefix: "api repos/", Stdout: `{"merged":true}`})
if err := NewGHClient().MergePR(context.Background(), "acme", "widget", 42, ""); err != nil {
t.Fatalf("MergePR: %v", err)
}
assertGHArgv(t, calls(t), 0, []string{
"api", "repos/acme/widget/pulls/42/merge", "-X", "PUT",
})
})
}
// The gh path must surface merge rejections as *GitHubAPIError so httpMergePR
// can translate them the same way it does for the PAT client.
func TestGHClient_MergePR_StatusIsRecoverable(t *testing.T) {
cases := []struct {
stderr string
want int
}{
{"gh: HTTP 405: Method Not Allowed", http.StatusMethodNotAllowed},
{"gh: HTTP 409: Conflict", http.StatusConflict},
{"gh: HTTP 404: Not Found", http.StatusNotFound},
{"gh: HTTP 403: Forbidden", http.StatusForbidden},
}
for _, tc := range cases {
t.Run(http.StatusText(tc.want), func(t *testing.T) {
newFakeGH(t, ghResponse{Prefix: "api repos/", Stderr: tc.stderr, Exit: 1})
err := NewGHClient().MergePR(context.Background(), "acme", "widget", 42, "merge")
var apiErr *GitHubAPIError
if !errors.As(err, &apiErr) {
t.Fatalf("err = %v, want a *GitHubAPIError", err)
}
if apiErr.StatusCode != tc.want {
t.Errorf("status = %d, want %d", apiErr.StatusCode, tc.want)
}
if apiErr.Endpoint != "repos/acme/widget/pulls/42/merge" {
t.Errorf("endpoint = %q", apiErr.Endpoint)
}
})
}
}
func TestGHClient_MergePR_UnmappedStatusFallsBackToAPlainWrap(t *testing.T) {
newFakeGH(t, ghResponse{Prefix: "api repos/", Stderr: "gh: HTTP 500: server error", Exit: 1})
err := NewGHClient().MergePR(context.Background(), "acme", "widget", 42, "merge")
if err == nil || !strings.Contains(err.Error(), "merge PR #42") {
t.Fatalf("err = %v, want a plain wrap naming the PR", err)
}
var apiErr *GitHubAPIError
if errors.As(err, &apiErr) {
t.Errorf("a 500 must not become *GitHubAPIError, got %#v", apiErr)
}
}
func TestGHClient_GetRepoMergeMethods(t *testing.T) {
cases := []struct {
name string
body string
want RepoMergeMethods
}{
{
"all allowed",
`{"allow_merge_commit":true,"allow_squash_merge":true,"allow_rebase_merge":true}`,
RepoMergeMethods{Merge: true, Squash: true, Rebase: true},
},
{
"rebase only",
`{"allow_merge_commit":false,"allow_squash_merge":false,"allow_rebase_merge":true}`,
RepoMergeMethods{Rebase: true},
},
{"omitted fields read as disallowed", `{"full_name":"acme/widget"}`, RepoMergeMethods{}},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
calls := newFakeGH(t, ghResponse{Prefix: "api repos/", Stdout: tc.body})
got, err := NewGHClient().GetRepoMergeMethods(context.Background(), "acme", "widget")
if err != nil {
t.Fatalf("GetRepoMergeMethods: %v", err)
}
assertGHArgv(t, calls(t), 0, []string{"api", "repos/acme/widget"})
if got != tc.want {
t.Errorf("methods = %#v, want %#v", got, tc.want)
}
})
}
}
func TestGHClient_GetRepoMergeMethods_Errors(t *testing.T) {
t.Run("command failure", func(t *testing.T) {
newFakeGH(t, ghResponse{Prefix: "api repos/", Stderr: "boom", Exit: 1})
_, err := NewGHClient().GetRepoMergeMethods(context.Background(), "acme", "widget")
if err == nil || !strings.Contains(err.Error(), "get repo merge methods") {
t.Fatalf("err = %v, want a wrapped error", err)
}
})
t.Run("unparseable output", func(t *testing.T) {
newFakeGH(t, ghResponse{Prefix: "api repos/", Stdout: "nope"})
_, err := NewGHClient().GetRepoMergeMethods(context.Background(), "acme", "widget")
if err == nil || !strings.Contains(err.Error(), "parse repo") {
t.Fatalf("err = %v, want a parse failure", err)
}
})
}
// ListRepoBranches reads a --jq-projected newline stream rather than JSON, so
// blank lines and stray whitespace must be dropped.
func TestGHClient_ListRepoBranches(t *testing.T) {
calls := newFakeGH(t, ghResponse{
Prefix: "api repos/",
Stdout: "main\n develop \n\nrelease/1.0\n\n",
})
branches, err := NewGHClient().ListRepoBranches(context.Background(), "acme", "widget")
if err != nil {
t.Fatalf("ListRepoBranches: %v", err)
}
assertGHArgv(t, calls(t), 0, []string{
"api", "repos/acme/widget/branches", "-X", "GET",
"-f", "per_page=100", "--paginate", "--jq", ".[].name",
})
want := []string{"main", "develop", "release/1.0"}
if len(branches) != len(want) {
t.Fatalf("branches = %#v, want %v", branches, want)
}
for i, name := range want {
if branches[i].Name != name {
t.Errorf("branches[%d] = %q, want %q", i, branches[i].Name, name)
}
}
}
func TestGHClient_ListRepoBranches_Error(t *testing.T) {
newFakeGH(t, ghResponse{Prefix: "api repos/", Stderr: "boom", Exit: 1})
branches, err := NewGHClient().ListRepoBranches(context.Background(), "acme", "widget")
if branches != nil {
t.Errorf("branches = %#v, want nil", branches)
}
if err == nil || !strings.Contains(err.Error(), "list repo branches") {
t.Fatalf("err = %v, want a wrapped error", err)
}
}
func TestGHClient_CreateGist_PipesThePayloadOnStdin(t *testing.T) {
calls := newFakeGH(t, ghResponse{
Prefix: "api gists",
Stdout: `{"id":"abc123","html_url":"https://gist.github.com/abc123",
"created_at":"2026-07-01T12:00:00Z"}`,
})
resp, err := NewGHClient().CreateGist(context.Background(), CreateGistInput{
Description: "kandev share",
Public: false,
Files: map[string]GistFile{"README.md": {Content: "# hello"}},
})
if err != nil {
t.Fatalf("CreateGist: %v", err)
}
assertGHArgv(t, calls(t), 0, []string{
"api", "gists", "-X", "POST", "-H", "Accept: " + githubAccept, "--input", "-",
})
if resp.ID != "abc123" || resp.HTMLURL != "https://gist.github.com/abc123" {
t.Errorf("response = %#v", resp)
}
if !resp.CreatedAt.Equal(time.Date(2026, 7, 1, 12, 0, 0, 0, time.UTC)) {
t.Errorf("created_at = %v", resp.CreatedAt)
}
var payload struct {
Description string `json:"description"`
Public bool `json:"public"`
Files map[string]map[string]string `json:"files"`
}
stdin := ghStdin(t)
if err := json.Unmarshal([]byte(stdin), &payload); err != nil {
t.Fatalf("decode piped payload %q: %v", stdin, err)
}
if payload.Description != "kandev share" || payload.Public {
t.Errorf("payload meta = %#v", payload)
}
if payload.Files["README.md"]["content"] != "# hello" {
t.Errorf("payload files = %#v", payload.Files)
}
}
func TestGHClient_CreateGist_Errors(t *testing.T) {
t.Run("command failure", func(t *testing.T) {
newFakeGH(t, ghResponse{Prefix: "api gists", Stderr: "HTTP 401", Exit: 1})
resp, err := NewGHClient().CreateGist(context.Background(), CreateGistInput{})
if resp != nil {
t.Errorf("resp = %#v, want nil", resp)
}
if err == nil || !strings.Contains(err.Error(), "create gist") {
t.Fatalf("err = %v, want a wrapped create-gist error", err)
}
})
t.Run("unparseable output", func(t *testing.T) {
newFakeGH(t, ghResponse{Prefix: "api gists", Stdout: "nope"})
_, err := NewGHClient().CreateGist(context.Background(), CreateGistInput{})
if err == nil || !strings.Contains(err.Error(), "decode gist response") {
t.Fatalf("err = %v, want a decode failure", err)
}
})
}
func TestGHClient_DeleteGist(t *testing.T) {
t.Run("deletes by id", func(t *testing.T) {
calls := newFakeGH(t, ghResponse{Prefix: "api gists/", Stdout: ""})
if err := NewGHClient().DeleteGist(context.Background(), "abc123"); err != nil {
t.Fatalf("DeleteGist: %v", err)
}
assertGHArgv(t, calls(t), 0, []string{"api", "gists/abc123", "-X", "DELETE"})
})
t.Run("empty id never execs gh", func(t *testing.T) {
calls := newFakeGH(t, ghResponse{Prefix: "api gists/", Stdout: ""})
if err := NewGHClient().DeleteGist(context.Background(), ""); err == nil {
t.Fatal("expected an error for an empty gist id")
}
if len(calls(t)) != 0 {
t.Errorf("gh calls = %d, want 0", len(calls(t)))
}
})
// share.IsAlreadyGone matches the typed 404 to treat an already-revoked
// gist as a soft success — every gh 404 spelling must be recognised.
t.Run("404 spellings all become a typed error", func(t *testing.T) {
for _, stderr := range []string{"HTTP 404: Not Found", "404 Not Found", "status: 404"} {
t.Run(stderr, func(t *testing.T) {
newFakeGH(t, ghResponse{Prefix: "api gists/", Stderr: stderr, Exit: 1})
err := NewGHClient().DeleteGist(context.Background(), "gone")
var apiErr *GitHubAPIError
if !errors.As(err, &apiErr) || apiErr.StatusCode != http.StatusNotFound {
t.Fatalf("err = %v, want a *GitHubAPIError with 404", err)
}
if apiErr.Endpoint != "/gists/gone" {
t.Errorf("endpoint = %q, want /gists/gone", apiErr.Endpoint)
}
})
}
})
t.Run("other failures stay untyped", func(t *testing.T) {
newFakeGH(t, ghResponse{Prefix: "api gists/", Stderr: "HTTP 500", Exit: 1})
err := NewGHClient().DeleteGist(context.Background(), "abc123")
if err == nil || !strings.Contains(err.Error(), "delete gist abc123") {
t.Fatalf("err = %v, want a wrapped delete-gist error", err)
}
var apiErr *GitHubAPIError
if errors.As(err, &apiErr) {
t.Errorf("a 500 must not become *GitHubAPIError, got %#v", apiErr)
}
})
}
@@ -0,0 +1,132 @@
package github
import (
"os"
"path/filepath"
"strconv"
"strings"
"testing"
)
// ghResponse is one dispatch arm of the fake `gh` binary. Prefix is a literal
// string matched against the start of the joined argv ("$*"); the first arm
// that matches wins, so order the arms most-specific first.
type ghResponse struct {
Prefix string
Stdout string
Stderr string
Exit int
}
// ghInvocations returns the exact argv of every fake-gh call, in order.
type ghInvocations func(t *testing.T) [][]string
// newFakeGH installs a fake `gh` on PATH that logs each invocation's argv
// verbatim (one argument per line, so quoting and spacing survive) and replies
// from the given dispatch arms. An invocation matching no arm exits non-zero
// with a loud stderr, so a test that quietly changes the command it issues
// fails rather than silently reading a default payload.
//
// t.Setenv is used for PATH, so tests calling this must not be parallel.
func newFakeGH(t *testing.T, responses ...ghResponse) ghInvocations {
t.Helper()
binDir := t.TempDir()
logPath := filepath.Join(t.TempDir(), "gh-argv.log")
var script strings.Builder
script.WriteString("#!/bin/sh\n")
script.WriteString(`{ for a in "$@"; do printf '%s\n' "$a"; done; printf '%s\n' '--END--'; } >> "$GH_ARGS_LOG"` + "\n")
// gh reads its request body from stdin for `--input -`. Commands launched
// without a stdin pipe see an immediate EOF here, so this is safe for all
// invocations.
script.WriteString(`cat >> "$GH_STDIN_LOG"` + "\n")
script.WriteString(`case "$*" in` + "\n")
for _, r := range responses {
// The literal half is single-quoted so a pattern containing spaces or
// slashes parses (dash rejects an unquoted multi-word case pattern);
// the trailing * stays outside the quotes so it still globs.
script.WriteString(" " + shellQuote(r.Prefix) + "*)\n")
if r.Stdout != "" {
script.WriteString(" printf '%s' " + shellQuote(r.Stdout) + "\n")
}
if r.Stderr != "" {
script.WriteString(" printf '%s' " + shellQuote(r.Stderr) + " >&2\n")
}
script.WriteString(" exit " + strconv.Itoa(r.Exit) + " ;;\n")
}
script.WriteString(" *)\n")
script.WriteString(` printf 'fake gh: no dispatch arm for: %s\n' "$*" >&2` + "\n")
script.WriteString(" exit 97 ;;\n")
script.WriteString("esac\n")
if err := os.WriteFile(filepath.Join(binDir, "gh"), []byte(script.String()), 0o755); err != nil {
t.Fatalf("write fake gh: %v", err)
}
t.Setenv("PATH", binDir+string(os.PathListSeparator)+os.Getenv("PATH"))
t.Setenv("GH_ARGS_LOG", logPath)
t.Setenv("GH_STDIN_LOG", filepath.Join(filepath.Dir(logPath), "gh-stdin.log"))
return func(t *testing.T) [][]string {
t.Helper()
return readGHInvocations(t, logPath)
}
}
// ghStdin returns everything the fake gh read on stdin across all invocations.
func ghStdin(t *testing.T) string {
t.Helper()
raw, err := os.ReadFile(os.Getenv("GH_STDIN_LOG"))
if os.IsNotExist(err) {
return ""
}
if err != nil {
t.Fatalf("read gh stdin log: %v", err)
}
return string(raw)
}
// readGHInvocations parses the argv log written by the fake gh script.
func readGHInvocations(t *testing.T, logPath string) [][]string {
t.Helper()
raw, err := os.ReadFile(logPath)
if os.IsNotExist(err) {
return nil
}
if err != nil {
t.Fatalf("read gh argv log: %v", err)
}
var calls [][]string
current := []string{}
for _, line := range strings.Split(strings.TrimSuffix(string(raw), "\n"), "\n") {
if line == "--END--" {
calls = append(calls, current)
current = []string{}
continue
}
current = append(current, line)
}
return calls
}
// shellQuote wraps s in single quotes for POSIX sh, escaping any embedded
// single quote via the close-quote / literal-quote / reopen-quote idiom.
func shellQuote(s string) string {
return "'" + strings.ReplaceAll(s, "'", `'\''`) + "'"
}
// assertGHArgv fails unless the recorded invocation matches want exactly.
func assertGHArgv(t *testing.T, calls [][]string, index int, want []string) {
t.Helper()
if index >= len(calls) {
t.Fatalf("gh invocation %d missing; recorded %d call(s): %v", index, len(calls), calls)
}
got := calls[index]
if len(got) != len(want) {
t.Fatalf("gh argv[%d] = %q, want %q", index, got, want)
}
for i := range want {
if got[i] != want[i] {
t.Fatalf("gh argv[%d][%d] = %q, want %q\nfull argv = %q", index, i, got[i], want[i], got)
}
}
}
@@ -0,0 +1,659 @@
package github
import (
"context"
"errors"
"net/http"
"strings"
"testing"
"time"
)
func TestGHClient_GetIssue(t *testing.T) {
calls := newFakeGH(t, ghResponse{
Prefix: "issue view",
Stdout: `{"number":5,"title":"Broken login","url":"https://github.com/acme/widget/issues/5",
"state":"CLOSED","body":"steps","createdAt":"2026-03-01T08:00:00Z",
"updatedAt":"2026-03-02T08:00:00Z","closedAt":"2026-03-03T08:00:00Z",
"author":{"login":"carol"},"labels":[{"name":"bug"},{"name":"p1"}],
"assignees":[{"login":"dave"}]}`,
})
issue, err := NewGHClient().GetIssue(context.Background(), "acme", "widget", 5)
if err != nil {
t.Fatalf("GetIssue: %v", err)
}
assertGHArgv(t, calls(t), 0, []string{
"issue", "view", "5", "--repo", "acme/widget",
"--json", "number,title,url,state,body,author,labels,assignees,createdAt,updatedAt,closedAt",
})
if issue.Number != 5 || issue.Title != "Broken login" || issue.Body != "steps" {
t.Errorf("scalars = %#v", issue)
}
if issue.URL != "https://github.com/acme/widget/issues/5" || issue.HTMLURL != issue.URL {
t.Errorf("URL/HTMLURL = (%q, %q)", issue.URL, issue.HTMLURL)
}
if issue.State != "closed" {
t.Errorf("state = %q, want lowercased closed", issue.State)
}
if issue.AuthorLogin != "carol" || issue.RepoOwner != "acme" || issue.RepoName != "widget" {
t.Errorf("author/repo = (%q, %q, %q)", issue.AuthorLogin, issue.RepoOwner, issue.RepoName)
}
if strings.Join(issue.Labels, ",") != "bug,p1" || strings.Join(issue.Assignees, ",") != "dave" {
t.Errorf("labels/assignees = (%v, %v)", issue.Labels, issue.Assignees)
}
if !issue.CreatedAt.Equal(time.Date(2026, 3, 1, 8, 0, 0, 0, time.UTC)) {
t.Errorf("created_at = %v", issue.CreatedAt)
}
if !issue.UpdatedAt.Equal(time.Date(2026, 3, 2, 8, 0, 0, 0, time.UTC)) {
t.Errorf("updated_at = %v", issue.UpdatedAt)
}
wantClosed := time.Date(2026, 3, 3, 8, 0, 0, 0, time.UTC)
if issue.ClosedAt == nil || !issue.ClosedAt.Equal(wantClosed) {
t.Errorf("closed_at = %v, want %v", issue.ClosedAt, wantClosed)
}
}
// The gh CLI emits "" (not null) for an open issue's closedAt.
func TestGHClient_GetIssue_EmptyClosedAtDecodesToNil(t *testing.T) {
newFakeGH(t, ghResponse{
Prefix: "issue view",
Stdout: `{"number":6,"state":"OPEN","closedAt":"","author":{"login":"carol"}}`,
})
issue, err := NewGHClient().GetIssue(context.Background(), "acme", "widget", 6)
if err != nil {
t.Fatalf("GetIssue: %v", err)
}
if issue.ClosedAt != nil {
t.Errorf("closed_at = %v, want nil", issue.ClosedAt)
}
}
func TestGHClient_GetIssue_NotFoundBecomesTypedError(t *testing.T) {
newFakeGH(t, ghResponse{
Prefix: "issue view",
Stderr: "gh: HTTP 404: Not Found",
Exit: 1,
})
issue, err := NewGHClient().GetIssue(context.Background(), "acme", "widget", 404)
if issue != nil {
t.Errorf("issue = %#v, want nil", issue)
}
var apiErr *GitHubAPIError
if !errors.As(err, &apiErr) || apiErr.StatusCode != http.StatusNotFound {
t.Fatalf("err = %v, want a *GitHubAPIError with 404", err)
}
if apiErr.Endpoint != "/repos/acme/widget/issues/404" {
t.Errorf("endpoint = %q", apiErr.Endpoint)
}
}
func TestGHClient_GetIssue_OtherFailureIsWrapped(t *testing.T) {
newFakeGH(t, ghResponse{Prefix: "issue view", Stderr: "HTTP 500: server error", Exit: 1})
_, err := NewGHClient().GetIssue(context.Background(), "acme", "widget", 6)
if err == nil || !strings.Contains(err.Error(), "get issue #6") {
t.Fatalf("err = %v, want a wrapped get-issue error", err)
}
var apiErr *GitHubAPIError
if errors.As(err, &apiErr) {
t.Errorf("a 500 must not be promoted to *GitHubAPIError, got %#v", apiErr)
}
}
func TestGHClient_GetPR_NotFoundBecomesTypedError(t *testing.T) {
newFakeGH(t, ghResponse{Prefix: "pr view", Stderr: "gh: HTTP 404: Not Found", Exit: 1})
pr, err := NewGHClient().GetPR(context.Background(), "acme", "widget", 7)
if pr != nil {
t.Errorf("pr = %#v, want nil", pr)
}
var apiErr *GitHubAPIError
if !errors.As(err, &apiErr) || apiErr.StatusCode != http.StatusNotFound {
t.Fatalf("err = %v, want a *GitHubAPIError with 404", err)
}
if apiErr.Endpoint != "/repos/acme/widget/pulls/7" {
t.Errorf("endpoint = %q", apiErr.Endpoint)
}
}
func TestGHClient_GetPR_UnparseableOutput(t *testing.T) {
newFakeGH(t, ghResponse{Prefix: "pr view", Stdout: "not json"})
if _, err := NewGHClient().GetPR(context.Background(), "acme", "widget", 7); err == nil ||
!strings.Contains(err.Error(), "parse PR response") {
t.Fatalf("err = %v, want a parse failure", err)
}
}
func TestGHClient_FindPRByBranch(t *testing.T) {
calls := newFakeGH(t, ghResponse{
Prefix: "pr list",
Stdout: `[{"number":12,"title":"fork PR","url":"https://github.com/acme/widget/pull/12",
"state":"OPEN","headRefName":"feature","headRefOid":"abc123","baseRefName":"main",
"author":{"login":"alice"},"isDraft":false,"mergeable":"MERGEABLE",
"mergeStateStatus":"CLEAN","additions":3,"deletions":1,
"createdAt":"2026-01-01T00:00:00Z","updatedAt":"2026-01-02T00:00:00Z"}]`,
})
pr, err := NewGHClient().FindPRByBranch(context.Background(), "acme", "widget", "feature")
if err != nil {
t.Fatalf("FindPRByBranch: %v", err)
}
assertGHArgv(t, calls(t), 0, []string{
"pr", "list", "--repo", "acme/widget", "--head", "feature", "--state", "open",
"--json", "number,title,url,state,headRefName,headRefOid,baseRefName,author,isDraft," +
"mergeable,mergeStateStatus,additions,deletions,createdAt,updatedAt",
"--limit", "1",
})
if pr == nil {
t.Fatal("pr = nil, want the single listed PR")
}
if pr.Number != 12 || pr.HeadBranch != "feature" || pr.HeadSHA != "abc123" {
t.Errorf("pr = %#v", pr)
}
if pr.BaseBranch != "main" || pr.AuthorLogin != "alice" || pr.State != "open" {
t.Errorf("pr = %#v", pr)
}
if !pr.Mergeable || pr.MergeableState != "clean" {
t.Errorf("mergeable = (%v, %q)", pr.Mergeable, pr.MergeableState)
}
if pr.RepoOwner != "acme" || pr.RepoName != "widget" {
t.Errorf("repo = (%q, %q)", pr.RepoOwner, pr.RepoName)
}
}
func TestGHClient_FindPRByBranch_NoMatchReturnsNilWithoutError(t *testing.T) {
newFakeGH(t, ghResponse{Prefix: "pr list", Stdout: `[]`})
pr, err := NewGHClient().FindPRByBranch(context.Background(), "acme", "widget", "feature")
if err != nil {
t.Fatalf("FindPRByBranch: %v", err)
}
if pr != nil {
t.Errorf("pr = %#v, want nil for an empty list", pr)
}
}
func TestGHClient_FindPRByBranch_Errors(t *testing.T) {
t.Run("command failure names the branch", func(t *testing.T) {
newFakeGH(t, ghResponse{Prefix: "pr list", Stderr: "boom", Exit: 1})
_, err := NewGHClient().FindPRByBranch(context.Background(), "acme", "widget", "feature")
if err == nil || !strings.Contains(err.Error(), `find PR by branch "feature"`) {
t.Fatalf("err = %v, want the branch named in the wrap", err)
}
})
t.Run("unparseable output", func(t *testing.T) {
newFakeGH(t, ghResponse{Prefix: "pr list", Stdout: "{"})
_, err := NewGHClient().FindPRByBranch(context.Background(), "acme", "widget", "feature")
if err == nil || !strings.Contains(err.Error(), "parse PR list") {
t.Fatalf("err = %v, want a parse failure", err)
}
})
}
func TestGHClient_ListAuthoredPRs(t *testing.T) {
calls := newFakeGH(t, ghResponse{
Prefix: "pr list",
Stdout: `[{"number":1,"title":"first","state":"OPEN","headRefName":"a","baseRefName":"main",
"author":{"login":"me"}},
{"number":2,"title":"second","state":"OPEN","headRefName":"b","baseRefName":"main",
"author":{"login":"me"}}]`,
})
prs, err := NewGHClient().ListAuthoredPRs(context.Background(), "acme", "widget")
if err != nil {
t.Fatalf("ListAuthoredPRs: %v", err)
}
argv := calls(t)[0]
// The @me author filter is what scopes this to the signed-in account;
// without it the call silently lists the whole repo.
if !containsPair(argv, "--author", "@me") {
t.Errorf("argv = %q, want --author @me", argv)
}
if !containsPair(argv, "--state", "open") || !containsPair(argv, "--repo", "acme/widget") {
t.Errorf("argv = %q, want --state open and --repo acme/widget", argv)
}
if len(prs) != 2 || prs[0].Number != 1 || prs[1].Number != 2 {
t.Fatalf("prs = %#v", prs)
}
if prs[0].RepoOwner != "acme" || prs[0].RepoName != "widget" {
t.Errorf("repo = (%q, %q)", prs[0].RepoOwner, prs[0].RepoName)
}
}
func TestGHClient_ListAuthoredPRs_Errors(t *testing.T) {
t.Run("command failure", func(t *testing.T) {
newFakeGH(t, ghResponse{Prefix: "pr list", Stderr: "boom", Exit: 1})
prs, err := NewGHClient().ListAuthoredPRs(context.Background(), "acme", "widget")
if prs != nil {
t.Errorf("prs = %#v, want nil", prs)
}
if err == nil || !strings.Contains(err.Error(), "list authored PRs") {
t.Fatalf("err = %v, want a wrapped list-authored error", err)
}
})
t.Run("unparseable output", func(t *testing.T) {
newFakeGH(t, ghResponse{Prefix: "pr list", Stdout: "["})
_, err := NewGHClient().ListAuthoredPRs(context.Background(), "acme", "widget")
if err == nil || !strings.Contains(err.Error(), "parse PR list") {
t.Fatalf("err = %v, want a parse failure", err)
}
})
}
func TestGHClient_ListReviewRequestedPRs(t *testing.T) {
calls := newFakeGH(t, ghResponse{
Prefix: "api search/issues",
Stdout: `[{"id":501,"node_id":"PR_a","number":3,"title":"Review me",
"html_url":"https://github.com/acme/web/pull/3","state":"closed","draft":true,
"created_at":"2026-04-01T00:00:00Z","updated_at":"2026-04-02T00:00:00Z",
"repository_url":"https://api.github.com/repos/acme/web","user":{"login":"erin"},
"pull_request":{"merged_at":"2026-04-03T00:00:00Z"}}]`,
})
prs, err := NewGHClient().ListReviewRequestedPRs(context.Background(), ReviewScopeUser, "repo:acme/web", "")
if err != nil {
t.Fatalf("ListReviewRequestedPRs: %v", err)
}
assertGHArgv(t, calls(t), 0, []string{
"api", "search/issues", "-X", "GET",
"-f", "q=type:pr state:open user-review-requested:@me -is:draft repo:acme/web",
"-f", "per_page=50", "--jq", ".items",
})
if len(prs) != 1 {
t.Fatalf("prs = %#v, want one", prs)
}
pr := prs[0]
if pr.ID != 501 || pr.NodeID != "PR_a" || pr.Number != 3 || pr.Title != "Review me" {
t.Errorf("identity = %#v", pr)
}
if pr.State != prStateMerged {
t.Errorf("state = %q, want merged — merged_at promotes a closed search hit", pr.State)
}
if pr.RepoOwner != "acme" || pr.RepoName != "web" || pr.AuthorLogin != "erin" || !pr.Draft {
t.Errorf("pr = %#v", pr)
}
}
func TestGHClient_ListReviewRequestedPRs_CustomQueryIsUsedVerbatim(t *testing.T) {
calls := newFakeGH(t, ghResponse{Prefix: "api search/issues", Stdout: `[]`})
if _, err := NewGHClient().ListReviewRequestedPRs(
context.Background(), ReviewScopeUser, "ignored", "is:pr author:me",
); err != nil {
t.Fatalf("ListReviewRequestedPRs: %v", err)
}
if !containsPair(calls(t)[0], "-f", "q=is:pr author:me") {
t.Errorf("argv = %q, want the custom query passed through untouched", calls(t)[0])
}
}
func TestGHClient_ListReviewRequestedPRs_Errors(t *testing.T) {
t.Run("command failure", func(t *testing.T) {
newFakeGH(t, ghResponse{Prefix: "api search/issues", Stderr: "boom", Exit: 1})
_, err := NewGHClient().ListReviewRequestedPRs(context.Background(), "", "", "")
if err == nil || !strings.Contains(err.Error(), "list review-requested PRs") {
t.Fatalf("err = %v, want a wrapped error", err)
}
})
t.Run("unparseable output", func(t *testing.T) {
newFakeGH(t, ghResponse{Prefix: "api search/issues", Stdout: "nope"})
_, err := NewGHClient().ListReviewRequestedPRs(context.Background(), "", "", "")
if err == nil || !strings.Contains(err.Error(), "parse search results") {
t.Fatalf("err = %v, want a parse failure", err)
}
})
}
func TestGHClient_SearchPRsPaged(t *testing.T) {
calls := newFakeGH(t, ghResponse{
Prefix: "api search/issues",
Stdout: `{"total_count":42,"items":[{"id":1,"number":1,"title":"one","state":"open",
"repository_url":"https://api.github.com/repos/o/r","pull_request":{}}]}`,
})
page, err := NewGHClient().SearchPRsPaged(context.Background(), "is:open", "", 2, 25)
if err != nil {
t.Fatalf("SearchPRsPaged: %v", err)
}
assertGHArgv(t, calls(t), 0, []string{
"api", "search/issues", "-X", "GET",
"-f", "q=type:pr is:open", "-f", "per_page=25", "-f", "page=2",
})
if page.TotalCount != 42 || page.Page != 2 || page.PerPage != 25 {
t.Errorf("page meta = (%d, %d, %d), want (42, 2, 25)", page.TotalCount, page.Page, page.PerPage)
}
if len(page.PRs) != 1 || page.PRs[0].Number != 1 {
t.Errorf("prs = %#v", page.PRs)
}
}
func TestGHClient_SearchPRs_UsesTheDefaultFirstPage(t *testing.T) {
calls := newFakeGH(t, ghResponse{
Prefix: "api search/issues",
Stdout: `{"total_count":0,"items":[]}`,
})
prs, err := NewGHClient().SearchPRs(context.Background(), "", "")
if err != nil {
t.Fatalf("SearchPRs: %v", err)
}
if len(prs) != 0 {
t.Errorf("prs = %#v, want empty", prs)
}
argv := calls(t)[0]
if !containsPair(argv, "-f", "per_page=50") || !containsPair(argv, "-f", "page=1") {
t.Errorf("argv = %q, want the default page 1 of 50", argv)
}
}
func TestGHClient_SearchPRsPaged_Errors(t *testing.T) {
t.Run("command failure", func(t *testing.T) {
newFakeGH(t, ghResponse{Prefix: "api search/issues", Stderr: "boom", Exit: 1})
_, err := NewGHClient().SearchPRsPaged(context.Background(), "", "", 1, 10)
if err == nil || !strings.Contains(err.Error(), "search PRs") {
t.Fatalf("err = %v, want a wrapped search error", err)
}
})
t.Run("unparseable envelope", func(t *testing.T) {
newFakeGH(t, ghResponse{Prefix: "api search/issues", Stdout: "nope"})
_, err := NewGHClient().SearchPRsPaged(context.Background(), "", "", 1, 10)
if err == nil || !strings.Contains(err.Error(), "parse PR search response") {
t.Fatalf("err = %v, want an envelope parse failure", err)
}
})
t.Run("unparseable items", func(t *testing.T) {
newFakeGH(t, ghResponse{Prefix: "api search/issues", Stdout: `{"total_count":1,"items":{}}`})
_, err := NewGHClient().SearchPRsPaged(context.Background(), "", "", 1, 10)
if err == nil || !strings.Contains(err.Error(), "parse search results") {
t.Fatalf("err = %v, want an items parse failure", err)
}
})
}
func TestGHClient_ListIssuesPaged_DropsPullRequests(t *testing.T) {
calls := newFakeGH(t, ghResponse{
Prefix: "api search/issues",
Stdout: `{"total_count":3,"items":[
{"id":10,"node_id":"I_a","number":10,"title":"a real issue","body":"details",
"html_url":"https://github.com/o/r/issues/10","state":"open",
"created_at":"2026-05-01T00:00:00Z","updated_at":"2026-05-02T00:00:00Z",
"repository_url":"https://api.github.com/repos/o/r","user":{"login":"frank"},
"labels":[{"name":"bug"}],"assignees":[{"login":"grace"}]},
{"id":11,"number":11,"title":"a PR","state":"open",
"repository_url":"https://api.github.com/repos/o/r","pull_request":{"url":"u"}}]}`,
})
page, err := NewGHClient().ListIssuesPaged(context.Background(), "label:bug", "", 1, 20)
if err != nil {
t.Fatalf("ListIssuesPaged: %v", err)
}
if !containsPair(calls(t)[0], "-f", "q=type:issue label:bug") {
t.Errorf("argv = %q, want the injected type:issue qualifier", calls(t)[0])
}
if len(page.Issues) != 1 {
t.Fatalf("issues = %#v, want the pull_request item dropped", page.Issues)
}
got := page.Issues[0]
if got.ID != 10 || got.NodeID != "I_a" || got.Number != 10 || got.Title != "a real issue" {
t.Errorf("issue = %#v", got)
}
if got.Body != "details" || got.RepoOwner != "o" || got.RepoName != "r" {
t.Errorf("issue = %#v", got)
}
if strings.Join(got.Labels, ",") != "bug" || strings.Join(got.Assignees, ",") != "grace" {
t.Errorf("labels/assignees = (%v, %v)", got.Labels, got.Assignees)
}
if page.TotalCount != 3 || page.Page != 1 || page.PerPage != 20 {
t.Errorf("page meta = (%d, %d, %d)", page.TotalCount, page.Page, page.PerPage)
}
}
func TestGHClient_ListIssues_UsesTheDefaultFirstPage(t *testing.T) {
calls := newFakeGH(t, ghResponse{
Prefix: "api search/issues",
Stdout: `{"total_count":0,"items":[]}`,
})
issues, err := NewGHClient().ListIssues(context.Background(), "", "")
if err != nil {
t.Fatalf("ListIssues: %v", err)
}
if len(issues) != 0 {
t.Errorf("issues = %#v, want empty", issues)
}
argv := calls(t)[0]
if !containsPair(argv, "-f", "per_page=50") || !containsPair(argv, "-f", "page=1") {
t.Errorf("argv = %q, want the default page 1 of 50", argv)
}
}
func TestGHClient_ListIssuesPaged_Errors(t *testing.T) {
t.Run("command failure", func(t *testing.T) {
newFakeGH(t, ghResponse{Prefix: "api search/issues", Stderr: "boom", Exit: 1})
_, err := NewGHClient().ListIssuesPaged(context.Background(), "", "", 1, 10)
if err == nil || !strings.Contains(err.Error(), "list issues") {
t.Fatalf("err = %v, want a wrapped list-issues error", err)
}
})
t.Run("unparseable output", func(t *testing.T) {
newFakeGH(t, ghResponse{Prefix: "api search/issues", Stdout: "nope"})
_, err := NewGHClient().ListIssuesPaged(context.Background(), "", "", 1, 10)
if err == nil || !strings.Contains(err.Error(), "parse issue search response") {
t.Fatalf("err = %v, want a parse failure", err)
}
})
}
func TestGHClient_GetIssueState(t *testing.T) {
calls := newFakeGH(t, ghResponse{Prefix: "api repos/", Stdout: "closed\n"})
state, err := NewGHClient().GetIssueState(context.Background(), "acme", "widget", 7)
if err != nil {
t.Fatalf("GetIssueState: %v", err)
}
assertGHArgv(t, calls(t), 0, []string{
"api", "repos/acme/widget/issues/7", "--jq", ".state",
})
if state != "closed" {
t.Errorf("state = %q, want the trimmed closed", state)
}
}
func TestGHClient_GetIssueState_Error(t *testing.T) {
newFakeGH(t, ghResponse{Prefix: "api repos/", Stderr: "boom", Exit: 1})
state, err := NewGHClient().GetIssueState(context.Background(), "acme", "widget", 7)
if state != "" {
t.Errorf("state = %q, want empty", state)
}
if err == nil || !strings.Contains(err.Error(), "get issue state") {
t.Fatalf("err = %v, want a wrapped error", err)
}
}
func TestGHClient_HasRepositoryAccess(t *testing.T) {
t.Run("readable repo", func(t *testing.T) {
calls := newFakeGH(t, ghResponse{Prefix: "api /repos/", Stdout: "acme/widget\n"})
ok, err := NewGHClient().HasRepositoryAccess(context.Background(), "acme", "widget")
if err != nil {
t.Fatalf("HasRepositoryAccess: %v", err)
}
if !ok {
t.Error("access = false, want true")
}
assertGHArgv(t, calls(t), 0, []string{"api", "/repos/acme/widget", "--jq", ".full_name"})
})
t.Run("blank output means no access", func(t *testing.T) {
newFakeGH(t, ghResponse{Prefix: "api /repos/", Stdout: "\n"})
ok, err := NewGHClient().HasRepositoryAccess(context.Background(), "acme", "widget")
if err != nil {
t.Fatalf("HasRepositoryAccess: %v", err)
}
if ok {
t.Error("access = true, want false for empty output")
}
})
t.Run("command failure propagates", func(t *testing.T) {
newFakeGH(t, ghResponse{Prefix: "api /repos/", Stderr: "HTTP 404", Exit: 1})
ok, err := NewGHClient().HasRepositoryAccess(context.Background(), "acme", "widget")
if ok {
t.Error("access = true, want false on error")
}
if err == nil {
t.Fatal("expected the gh failure to propagate")
}
})
}
func TestGHClient_ListUserOrgs(t *testing.T) {
calls := newFakeGH(t, ghResponse{
Prefix: "api user/orgs",
Stdout: `[{"login":"acme","avatar_url":"https://avatars/acme"},{"login":"other"}]`,
})
orgs, err := NewGHClient().ListUserOrgs(context.Background())
if err != nil {
t.Fatalf("ListUserOrgs: %v", err)
}
assertGHArgv(t, calls(t), 0, []string{"api", "user/orgs", "--paginate"})
if len(orgs) != 2 {
t.Fatalf("orgs = %#v, want 2", orgs)
}
if orgs[0] != (GitHubOrg{Login: "acme", AvatarURL: "https://avatars/acme"}) {
t.Errorf("orgs[0] = %#v", orgs[0])
}
if orgs[1] != (GitHubOrg{Login: "other"}) {
t.Errorf("orgs[1] = %#v", orgs[1])
}
}
func TestGHClient_ListUserOrgs_Errors(t *testing.T) {
t.Run("command failure", func(t *testing.T) {
newFakeGH(t, ghResponse{Prefix: "api user/orgs", Stderr: "boom", Exit: 1})
orgs, err := NewGHClient().ListUserOrgs(context.Background())
if orgs != nil {
t.Errorf("orgs = %#v, want nil", orgs)
}
if err == nil || !strings.Contains(err.Error(), "list user orgs") {
t.Fatalf("err = %v, want a wrapped error", err)
}
})
t.Run("unparseable output", func(t *testing.T) {
newFakeGH(t, ghResponse{Prefix: "api user/orgs", Stdout: "nope"})
_, err := NewGHClient().ListUserOrgs(context.Background())
if err == nil || !strings.Contains(err.Error(), "parse orgs") {
t.Fatalf("err = %v, want a parse failure", err)
}
})
}
// containsPair reports whether argv holds `flag` immediately followed by value.
func containsPair(argv []string, flag, value string) bool {
for i := 0; i < len(argv)-1; i++ {
if argv[i] == flag && argv[i+1] == value {
return true
}
}
return false
}
func TestGHClient_SearchPRs_PropagatesTheUnderlyingFailure(t *testing.T) {
newFakeGH(t, ghResponse{Prefix: "api search/issues", Stderr: "boom", Exit: 1})
prs, err := NewGHClient().SearchPRs(context.Background(), "", "")
if prs != nil {
t.Errorf("prs = %#v, want nil", prs)
}
if err == nil || !strings.Contains(err.Error(), "search PRs") {
t.Fatalf("err = %v, want the paged error surfaced unchanged", err)
}
}
func TestGHClient_ListIssues_PropagatesTheUnderlyingFailure(t *testing.T) {
newFakeGH(t, ghResponse{Prefix: "api search/issues", Stderr: "boom", Exit: 1})
issues, err := NewGHClient().ListIssues(context.Background(), "", "")
if issues != nil {
t.Errorf("issues = %#v, want nil", issues)
}
if err == nil || !strings.Contains(err.Error(), "list issues") {
t.Fatalf("err = %v, want the paged error surfaced unchanged", err)
}
}
func TestGHClient_GetPRCommitDetail_Errors(t *testing.T) {
const sha = "2222222222222222222222222222222222222222"
t.Run("command failure", func(t *testing.T) {
newFakeGH(t, ghResponse{Prefix: "api repos/", Stderr: "boom", Exit: 1})
_, err := NewGHClient().GetPRCommitDetail(context.Background(), "acme", "widget", sha)
if err == nil || !strings.Contains(err.Error(), "get PR commit detail") {
t.Fatalf("err = %v, want a wrapped error", err)
}
})
t.Run("unparseable output", func(t *testing.T) {
newFakeGH(t, ghResponse{Prefix: "api repos/", Stdout: "nope"})
_, err := NewGHClient().GetPRCommitDetail(context.Background(), "acme", "widget", sha)
if err == nil || !strings.Contains(err.Error(), "parse PR commit detail") {
t.Fatalf("err = %v, want a parse failure", err)
}
})
}
func TestGHClient_RequestReviewers_FailureNamesThePR(t *testing.T) {
newFakeGH(t, ghResponse{Prefix: "api repos/", Stderr: "HTTP 422", Exit: 1})
err := NewGHClient().RequestReviewers(context.Background(), "acme", "widget", 42, []string{"octocat"})
if err == nil || !strings.Contains(err.Error(), "request reviewers on PR #42") {
t.Fatalf("err = %v, want the PR named in the wrap", err)
}
}
// gh pr view exposes the head repository under several shapes. nameWithOwner
// backfills a missing owner/name, and httpsUrl is the fallback when cloneUrl
// is absent — without them a fork PR loses the remote it must be pushed to.
func TestConvertGHPR_HeadRepositoryFallbacks(t *testing.T) {
t.Run("nameWithOwner backfills a missing owner and name", func(t *testing.T) {
raw := &ghPR{Number: 1, State: "OPEN"}
raw.HeadRepository.NameWithOwner = "contributor/widget-fork"
raw.HeadRepository.HTTPSURL = "https://github.com/contributor/widget-fork.git"
pr := convertGHPR(raw, "acme", "widget")
if pr.HeadRepoOwner != "contributor" || pr.HeadRepoName != "widget-fork" {
t.Errorf("head repo = (%q, %q), want it split out of nameWithOwner",
pr.HeadRepoOwner, pr.HeadRepoName)
}
if pr.HeadRepoCloneURL != "https://github.com/contributor/widget-fork.git" {
t.Errorf("clone url = %q, want the httpsUrl fallback", pr.HeadRepoCloneURL)
}
})
t.Run("explicit fields win over nameWithOwner", func(t *testing.T) {
raw := &ghPR{Number: 1, State: "OPEN"}
raw.HeadRepositoryOwner.Login = "real-owner"
raw.HeadRepository.Name = "real-name"
raw.HeadRepository.NameWithOwner = "stale/stale-name"
raw.HeadRepository.CloneURL = "https://github.com/real-owner/real-name.git"
raw.HeadRepository.HTTPSURL = "https://ignored"
pr := convertGHPR(raw, "acme", "widget")
if pr.HeadRepoOwner != "real-owner" || pr.HeadRepoName != "real-name" {
t.Errorf("head repo = (%q, %q)", pr.HeadRepoOwner, pr.HeadRepoName)
}
if pr.HeadRepoCloneURL != "https://github.com/real-owner/real-name.git" {
t.Errorf("clone url = %q, want cloneUrl to win", pr.HeadRepoCloneURL)
}
})
// gh pr view never returns baseRepository, so the --repo arguments are the
// only trusted target identity and the base default branch stays unknown.
t.Run("the base repo comes from the caller, not the payload", func(t *testing.T) {
pr := convertGHPR(&ghPR{Number: 1, State: "OPEN", BaseRefName: "release/2.0"}, "acme", "widget")
if pr.BaseRepoOwner != "acme" || pr.BaseRepoName != "widget" {
t.Errorf("base repo = (%q, %q), want the caller's acme/widget", pr.BaseRepoOwner, pr.BaseRepoName)
}
if pr.BaseDefaultBranch != "" {
t.Errorf("base default branch = %q, want empty — the base ref is not the default branch",
pr.BaseDefaultBranch)
}
})
}
func TestConvertGHRequestedReviewers_SkipsAnEmptyTeam(t *testing.T) {
got := convertGHRequestedReviewers([]ghRequestedReviewer{
{TypeName: "Team"},
{TypeName: "User", Login: "alice"},
})
if len(got) != 1 {
t.Fatalf("reviewers = %#v, want the nameless team dropped", got)
}
if got[0] != (RequestedReviewer{Login: "alice", Type: reviewerTypeUser}) {
t.Errorf("reviewers[0] = %#v", got[0])
}
}
@@ -0,0 +1,619 @@
package github
import (
"context"
"encoding/base64"
"errors"
"net/http"
"strconv"
"strings"
"testing"
"time"
)
func TestGHClient_IsAuthenticated(t *testing.T) {
t.Run("gh auth status succeeds", func(t *testing.T) {
calls := newFakeGH(t, ghResponse{Prefix: "auth status", Stdout: "Logged in to github.com\n"})
ok, err := NewGHClient().IsAuthenticated(context.Background())
if err != nil {
t.Fatalf("IsAuthenticated: %v", err)
}
if !ok {
t.Error("authenticated = false, want true")
}
assertGHArgv(t, calls(t), 0, []string{"auth", "status", "--hostname", "github.com"})
})
// Any non-zero exit is "not authenticated" — the message text is
// locale-dependent, so it is deliberately not parsed.
t.Run("a non-zero exit reports false without an error", func(t *testing.T) {
newFakeGH(t, ghResponse{Prefix: "auth status", Stderr: "You are not logged in", Exit: 1})
ok, err := NewGHClient().IsAuthenticated(context.Background())
if err != nil {
t.Fatalf("a plain auth failure must not surface an error, got %v", err)
}
if ok {
t.Error("authenticated = true, want false")
}
})
// Cancellation must stay distinguishable from "not authenticated" so
// callers don't treat a shutdown as a lost login.
t.Run("cancellation propagates", func(t *testing.T) {
newFakeGH(t, ghResponse{Prefix: "auth status", Stdout: "ok"})
ctx, cancel := context.WithCancel(context.Background())
cancel()
ok, err := NewGHClient().IsAuthenticated(ctx)
if ok {
t.Error("authenticated = true, want false")
}
if !errors.Is(err, context.Canceled) {
t.Fatalf("err = %v, want it to unwrap to context.Canceled", err)
}
})
}
func TestGHClient_RunAuthDiagnostics(t *testing.T) {
t.Run("success captures stdout when stderr is empty", func(t *testing.T) {
calls := newFakeGH(t, ghResponse{Prefix: "auth status", Stdout: "Logged in as octocat"})
got := NewGHClient().RunAuthDiagnostics(context.Background())
assertGHArgv(t, calls(t), 0, []string{"auth", "status", "--hostname", "github.com"})
if got.Command != "gh auth status --hostname github.com" {
t.Errorf("command = %q", got.Command)
}
if got.Output != "Logged in as octocat" {
t.Errorf("output = %q, want the stdout text", got.Output)
}
if got.ExitCode != 0 {
t.Errorf("exit code = %d, want 0", got.ExitCode)
}
})
// gh writes its auth report to stderr, so stderr wins when both are set.
t.Run("stderr is preferred over stdout", func(t *testing.T) {
newFakeGH(t, ghResponse{
Prefix: "auth status", Stdout: "ignored", Stderr: "You are not logged into any hosts", Exit: 1,
})
got := NewGHClient().RunAuthDiagnostics(context.Background())
if got.Output != "You are not logged into any hosts" {
t.Errorf("output = %q, want the stderr text", got.Output)
}
if got.ExitCode != 1 {
t.Errorf("exit code = %d, want 1", got.ExitCode)
}
})
// A silent non-zero exit would otherwise render as a blank diagnostics
// panel, so the underlying error is surfaced as the output.
t.Run("a silent failure surfaces the underlying error", func(t *testing.T) {
newFakeGH(t, ghResponse{Prefix: "auth status", Exit: 3})
got := NewGHClient().RunAuthDiagnostics(context.Background())
if got.ExitCode != 3 {
t.Errorf("exit code = %d, want 3", got.ExitCode)
}
if !strings.Contains(got.Output, "gh auth status did not run") {
t.Errorf("output = %q, want the did-not-run explanation", got.Output)
}
})
t.Run("a cancelled context reports the context error too", func(t *testing.T) {
newFakeGH(t, ghResponse{Prefix: "auth status", Stdout: "ok"})
ctx, cancel := context.WithCancel(context.Background())
cancel()
got := NewGHClient().RunAuthDiagnostics(ctx)
if got.ExitCode != -1 {
t.Errorf("exit code = %d, want -1 for a non-exec failure", got.ExitCode)
}
if !strings.Contains(got.Output, "context:") {
t.Errorf("output = %q, want the context cause included", got.Output)
}
})
}
func TestGHClient_FetchRateLimit(t *testing.T) {
t.Run("no tracker is a no-op that never execs gh", func(t *testing.T) {
calls := newFakeGH(t, ghResponse{Prefix: "api rate_limit", Stdout: `{}`})
if err := NewGHClient().FetchRateLimit(context.Background()); err != nil {
t.Fatalf("FetchRateLimit: %v", err)
}
if len(calls(t)) != 0 {
t.Errorf("gh calls = %d, want 0 without a tracker", len(calls(t)))
}
})
t.Run("seeds every reported bucket", func(t *testing.T) {
reset := time.Now().Add(30 * time.Minute).UTC().Truncate(time.Second)
calls := newFakeGH(t, ghResponse{
Prefix: "api rate_limit",
Stdout: `{"resources":{
"core":{"limit":5000,"remaining":4990,"reset":` + strconv.FormatInt(reset.Unix(), 10) + `},
"graphql":{"limit":5000,"remaining":4000,"reset":` + strconv.FormatInt(reset.Unix(), 10) + `},
"search":{"limit":30,"remaining":29,"reset":` + strconv.FormatInt(reset.Unix(), 10) + `}}}`,
})
tracker := NewRateTracker(nil, nil)
if err := NewGHClient().WithRateTracker(tracker).FetchRateLimit(context.Background()); err != nil {
t.Fatalf("FetchRateLimit: %v", err)
}
assertGHArgv(t, calls(t), 0, []string{"api", "rate_limit"})
for _, want := range []struct {
resource Resource
limit int
remaining int
}{
{ResourceCore, 5000, 4990},
{ResourceGraphQL, 5000, 4000},
{ResourceSearch, 30, 29},
} {
snap, ok := tracker.Snapshot(want.resource)
if !ok {
t.Errorf("%s: no snapshot recorded", want.resource)
continue
}
if snap.Limit != want.limit || snap.Remaining != want.remaining {
t.Errorf("%s = %d/%d, want %d/%d",
want.resource, snap.Remaining, snap.Limit, want.remaining, want.limit)
}
if !snap.ResetAt.Equal(reset) {
t.Errorf("%s reset = %v, want %v", want.resource, snap.ResetAt, reset)
}
}
})
// An all-zero bucket means gh reported nothing for that resource; recording
// it would falsely present the bucket as exhausted.
t.Run("all-zero buckets are skipped", func(t *testing.T) {
newFakeGH(t, ghResponse{
Prefix: "api rate_limit",
Stdout: `{"resources":{"core":{"limit":5000,"remaining":10,"reset":1893456000},
"graphql":{"limit":0,"remaining":0,"reset":0},
"search":{"limit":0,"remaining":0,"reset":0}}}`,
})
tracker := NewRateTracker(nil, nil)
if err := NewGHClient().WithRateTracker(tracker).FetchRateLimit(context.Background()); err != nil {
t.Fatalf("FetchRateLimit: %v", err)
}
if _, ok := tracker.Snapshot(ResourceCore); !ok {
t.Error("core snapshot missing")
}
if _, ok := tracker.Snapshot(ResourceGraphQL); ok {
t.Error("graphql snapshot recorded, want the all-zero bucket skipped")
}
if _, ok := tracker.Snapshot(ResourceSearch); ok {
t.Error("search snapshot recorded, want the all-zero bucket skipped")
}
})
t.Run("command failure", func(t *testing.T) {
newFakeGH(t, ghResponse{Prefix: "api rate_limit", Stderr: "boom", Exit: 1})
err := NewGHClient().WithRateTracker(NewRateTracker(nil, nil)).FetchRateLimit(context.Background())
if err == nil || !strings.Contains(err.Error(), "fetch rate limit") {
t.Fatalf("err = %v, want a wrapped fetch error", err)
}
})
t.Run("unparseable output", func(t *testing.T) {
newFakeGH(t, ghResponse{Prefix: "api rate_limit", Stdout: "nope"})
err := NewGHClient().WithRateTracker(NewRateTracker(nil, nil)).FetchRateLimit(context.Background())
if err == nil || !strings.Contains(err.Error(), "parse rate_limit response") {
t.Fatalf("err = %v, want a parse failure", err)
}
})
}
func TestGHClient_ListCheckRuns_Errors(t *testing.T) {
t.Run("check-runs command failure", func(t *testing.T) {
newFakeGH(t, ghResponse{Prefix: "api --paginate", Stderr: "boom", Exit: 1})
_, err := NewGHClient().ListCheckRuns(context.Background(), "acme", "widget", "sha")
if err == nil || !strings.Contains(err.Error(), "list check runs") {
t.Fatalf("err = %v, want a wrapped check-runs error", err)
}
})
t.Run("undecodable check-run stream", func(t *testing.T) {
newFakeGH(t, ghResponse{Prefix: "api --paginate", Stdout: `{"name":"unit"`})
_, err := NewGHClient().ListCheckRuns(context.Background(), "acme", "widget", "sha")
if err == nil || !strings.Contains(err.Error(), "parse check runs") {
t.Fatalf("err = %v, want a check-run decode failure", err)
}
})
t.Run("status command failure", func(t *testing.T) {
newFakeGH(t,
ghResponse{Prefix: "api --paginate", Stdout: ""},
ghResponse{Prefix: "api repos/", Stderr: "boom", Exit: 1},
)
_, err := NewGHClient().ListCheckRuns(context.Background(), "acme", "widget", "sha")
if err == nil || !strings.Contains(err.Error(), "list status contexts") {
t.Fatalf("err = %v, want a wrapped status error", err)
}
})
t.Run("unparseable status contexts", func(t *testing.T) {
newFakeGH(t,
ghResponse{Prefix: "api --paginate", Stdout: ""},
ghResponse{Prefix: "api repos/", Stdout: "nope"},
)
_, err := NewGHClient().ListCheckRuns(context.Background(), "acme", "widget", "sha")
if err == nil || !strings.Contains(err.Error(), "parse status contexts") {
t.Fatalf("err = %v, want a status parse failure", err)
}
})
}
// A commit status context and a check run sharing a name collapse into one
// entry, with the check run winning.
func TestGHClient_ListCheckRuns_MergesStatusContexts(t *testing.T) {
newFakeGH(t,
ghResponse{
Prefix: "api --paginate",
Stdout: `{"name":"unit","status":"completed","conclusion":"success","html_url":"https://ci/unit"}`,
},
ghResponse{
Prefix: "api repos/",
Stdout: `[{"context":"unit","state":"failure","target_url":"https://legacy/unit"},
{"context":"legacy-only","state":"success","target_url":"https://legacy/other",
"description":"all good"}]`,
},
)
checks, err := NewGHClient().ListCheckRuns(context.Background(), "acme", "widget", "sha")
if err != nil {
t.Fatalf("ListCheckRuns: %v", err)
}
if len(checks) != 2 {
t.Fatalf("checks = %#v, want the duplicate name merged into 2 entries", checks)
}
byName := map[string]CheckRun{}
for _, c := range checks {
byName[c.Name] = c
}
unit, ok := byName["unit"]
if !ok {
t.Fatal("unit check missing")
}
if unit.Source != checkSourceCheckRun || unit.Conclusion != "success" {
t.Errorf("unit = %#v, want the check-run entry to win over the status context", unit)
}
legacy, ok := byName["legacy-only"]
if !ok {
t.Fatal("legacy-only check missing")
}
if legacy.Source != checkSourceStatusContext || legacy.Conclusion != checkStatusSuccess {
t.Errorf("legacy-only = %#v", legacy)
}
if legacy.Output != "all good" {
t.Errorf("legacy-only output = %q, want the status description", legacy.Output)
}
}
func TestGHClient_GetPRStatus(t *testing.T) {
newFakeGH(t, ghPRStatusResponses()...)
status, err := NewGHClient().GetPRStatus(context.Background(), "acme", "widget", 42)
if err != nil {
t.Fatalf("GetPRStatus: %v", err)
}
if status.PR == nil || status.PR.Number != 42 {
t.Fatalf("PR = %#v", status.PR)
}
if status.ReviewState != computedReviewStateApproved || status.ReviewCount != 1 {
t.Errorf("review = (%q, %d), want (approved, 1)", status.ReviewState, status.ReviewCount)
}
if status.ChecksState != "failure" {
t.Errorf("checks state = %q, want failure", status.ChecksState)
}
if status.ChecksTotal != 2 || status.ChecksPassing != 1 {
t.Errorf("checks = %d/%d, want 1/2", status.ChecksPassing, status.ChecksTotal)
}
if !status.ChecksPopulated || !status.ReviewCountsPopulated {
t.Error("the gh REST path counted checks and reviews; both flags must be set")
}
if status.UnresolvedReviewThreadsPopulated {
t.Error("UnresolvedReviewThreadsPopulated must stay false — no threads were fetched")
}
}
func TestGHClient_GetPRFeedback(t *testing.T) {
responses := append(ghPRStatusResponses(),
ghResponse{
Prefix: "api repos/acme/widget/pulls/42/comments",
Stdout: `[{"id":20,"body":"inline","created_at":"2026-01-05T12:00:00Z",
"user":{"login":"alice","type":"User"}}]`,
},
ghResponse{Prefix: "api repos/acme/widget/issues/42/comments", Stdout: `[]`},
)
newFakeGH(t, responses...)
feedback, err := NewGHClient().GetPRFeedback(context.Background(), "acme", "widget", 42)
if err != nil {
t.Fatalf("GetPRFeedback: %v", err)
}
if feedback.PR == nil || feedback.PR.Number != 42 {
t.Fatalf("PR = %#v", feedback.PR)
}
if len(feedback.Reviews) != 1 || len(feedback.Checks) != 2 {
t.Errorf("reviews/checks = (%d, %d), want (1, 2)", len(feedback.Reviews), len(feedback.Checks))
}
if len(feedback.Comments) != 1 || feedback.Comments[0].ID != 20 {
t.Errorf("comments = %#v", feedback.Comments)
}
if !feedback.HasIssues {
t.Error("HasIssues = false, want true — one check concluded failure")
}
}
// ghPRStatusResponses is the dispatch set the PR status rollup needs: the PR
// itself, its reviews, its paginated check runs, and its commit statuses.
// The comment endpoints are matched before the bare `api repos/` arm, so
// callers appending them must place them ahead of nothing — the ordering here
// already puts the specific pulls/issues comment paths first when appended.
func ghPRStatusResponses() []ghResponse {
return []ghResponse{
{
Prefix: "pr view",
Stdout: `{"number":42,"state":"OPEN","mergeStateStatus":"BLOCKED",
"headRefName":"feature","headRefOid":"headsha","baseRefName":"main",
"author":{"login":"bob"}}`,
},
{
Prefix: "api --paginate",
Stdout: `{"name":"unit","status":"completed","conclusion":"success","html_url":"https://ci/unit"}
{"name":"lint","status":"completed","conclusion":"failure","html_url":"https://ci/lint"}`,
},
{
Prefix: "api repos/acme/widget/pulls/42/reviews",
Stdout: `[{"id":1,"state":"APPROVED","submitted_at":"2026-01-05T10:00:00Z",
"user":{"login":"alice"}}]`,
},
{Prefix: "api repos/acme/widget/commits", Stdout: `[]`},
}
}
func TestGHClient_ListRepoDirectory(t *testing.T) {
calls := newFakeGH(t, ghResponse{
Prefix: "api repos/",
Stdout: `[{"name":"spec.md","path":"docs/spec.md","type":"file","sha":"aaa","size":128},
{"name":"images","path":"docs/images","type":"dir","sha":"bbb"}]`,
})
entries, err := NewGHClient().ListRepoDirectory(context.Background(), "acme", "widget", "docs", "main")
if err != nil {
t.Fatalf("ListRepoDirectory: %v", err)
}
assertGHArgv(t, calls(t), 0, []string{
"api", "repos/acme/widget/contents/docs", "-X", "GET", "-f", "ref=main",
})
want := []RepoContentEntry{
{Name: "spec.md", Path: "docs/spec.md", Type: RepoContentTypeFile, SHA: "aaa", Size: 128},
{Name: "images", Path: "docs/images", Type: RepoContentTypeDir, SHA: "bbb"},
}
if len(entries) != len(want) {
t.Fatalf("entries = %#v, want %#v", entries, want)
}
for i := range want {
if entries[i] != want[i] {
t.Errorf("entries[%d] = %#v, want %#v", i, entries[i], want[i])
}
}
}
func TestGHClient_ListRepoDirectory_RootOmitsPathAndRef(t *testing.T) {
calls := newFakeGH(t, ghResponse{Prefix: "api repos/", Stdout: `[]`})
if _, err := NewGHClient().ListRepoDirectory(context.Background(), "acme", "widget", "", ""); err != nil {
t.Fatalf("ListRepoDirectory: %v", err)
}
assertGHArgv(t, calls(t), 0, []string{"api", "repos/acme/widget/contents", "-X", "GET"})
}
func TestGHClient_ListRepoDirectory_Errors(t *testing.T) {
t.Run("404 becomes a typed error", func(t *testing.T) {
newFakeGH(t, ghResponse{Prefix: "api repos/", Stderr: "gh: HTTP 404: Not Found", Exit: 1})
entries, err := NewGHClient().ListRepoDirectory(context.Background(), "acme", "widget", "nope", "")
if entries != nil {
t.Errorf("entries = %#v, want nil", entries)
}
var apiErr *GitHubAPIError
if !errors.As(err, &apiErr) || apiErr.StatusCode != http.StatusNotFound {
t.Fatalf("err = %v, want a *GitHubAPIError with 404", err)
}
if apiErr.Endpoint != "repos/acme/widget/contents/nope" {
t.Errorf("endpoint = %q", apiErr.Endpoint)
}
})
t.Run("other failures stay untyped", func(t *testing.T) {
newFakeGH(t, ghResponse{Prefix: "api repos/", Stderr: "HTTP 500", Exit: 1})
_, err := NewGHClient().ListRepoDirectory(context.Background(), "acme", "widget", "docs", "")
if err == nil || !strings.Contains(err.Error(), "list repo directory") {
t.Fatalf("err = %v, want a wrapped error", err)
}
})
t.Run("unparseable output", func(t *testing.T) {
newFakeGH(t, ghResponse{Prefix: "api repos/", Stdout: "nope"})
_, err := NewGHClient().ListRepoDirectory(context.Background(), "acme", "widget", "docs", "")
if err == nil || !strings.Contains(err.Error(), "list repo directory: decode") {
t.Fatalf("err = %v, want a decode failure", err)
}
})
}
func TestGHClient_GetRepoFileContent(t *testing.T) {
content := "package main\n"
encoded := base64.StdEncoding.EncodeToString([]byte(content))
// GitHub wraps base64 at 60 chars; `\n` here is the JSON escape, so the
// decoded field really carries an embedded newline that must be stripped.
wrapped := encoded[:6] + `\n` + encoded[6:]
calls := newFakeGH(t, ghResponse{
Prefix: "api repos/",
Stdout: `{"type":"file","encoding":"base64","content":"` + wrapped + `"}`,
})
got, err := NewGHClient().GetRepoFileContent(context.Background(), "acme", "widget", "cmd/main.go", "abc")
if err != nil {
t.Fatalf("GetRepoFileContent: %v", err)
}
assertGHArgv(t, calls(t), 0, []string{
"api", "repos/acme/widget/contents/cmd/main.go", "-X", "GET", "-f", "ref=abc",
})
if string(got) != content {
t.Errorf("content = %q, want %q", got, content)
}
}
func TestGHClient_GetRepoFileContent_Errors(t *testing.T) {
t.Run("404 becomes a typed error", func(t *testing.T) {
newFakeGH(t, ghResponse{Prefix: "api repos/", Stderr: "gh: HTTP 404: Not Found", Exit: 1})
_, err := NewGHClient().GetRepoFileContent(context.Background(), "acme", "widget", "gone.txt", "")
var apiErr *GitHubAPIError
if !errors.As(err, &apiErr) || apiErr.StatusCode != http.StatusNotFound {
t.Fatalf("err = %v, want a *GitHubAPIError with 404", err)
}
if apiErr.Endpoint != "repos/acme/widget/contents/gone.txt" {
t.Errorf("endpoint = %q", apiErr.Endpoint)
}
})
t.Run("other failures stay untyped", func(t *testing.T) {
newFakeGH(t, ghResponse{Prefix: "api repos/", Stderr: "HTTP 500", Exit: 1})
_, err := NewGHClient().GetRepoFileContent(context.Background(), "acme", "widget", "x", "")
if err == nil || !strings.Contains(err.Error(), "get repo file content") {
t.Fatalf("err = %v, want a wrapped error", err)
}
})
t.Run("unparseable output", func(t *testing.T) {
newFakeGH(t, ghResponse{Prefix: "api repos/", Stdout: "nope"})
_, err := NewGHClient().GetRepoFileContent(context.Background(), "acme", "widget", "x", "")
if err == nil || !strings.Contains(err.Error(), "get repo file content: decode") {
t.Fatalf("err = %v, want a decode failure", err)
}
})
t.Run("unsupported encoding", func(t *testing.T) {
newFakeGH(t, ghResponse{
Prefix: "api repos/", Stdout: `{"type":"file","encoding":"none","content":""}`,
})
_, err := NewGHClient().GetRepoFileContent(context.Background(), "acme", "widget", "x", "")
if err == nil || !strings.Contains(err.Error(), `unsupported encoding "none"`) {
t.Fatalf("err = %v, want the encoding named", err)
}
})
t.Run("undecodable base64", func(t *testing.T) {
newFakeGH(t, ghResponse{
Prefix: "api repos/", Stdout: `{"type":"file","encoding":"base64","content":"!!!"}`,
})
_, err := NewGHClient().GetRepoFileContent(context.Background(), "acme", "widget", "x", "")
if err == nil || !strings.Contains(err.Error(), "decode base64") {
t.Fatalf("err = %v, want a base64 failure", err)
}
})
}
// The exec budget starts only after the throttle slot is acquired, and is
// capped at ghCLITimeout — a caller deadline further out must not extend it.
func TestResolveGHExecTimeout(t *testing.T) {
t.Run("no deadline takes the full budget", func(t *testing.T) {
if got := resolveGHExecTimeout(context.Background()); got != ghCLITimeout {
t.Errorf("timeout = %v, want %v", got, ghCLITimeout)
}
})
t.Run("a nearer deadline wins", func(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), 2*time.Second)
defer cancel()
got := resolveGHExecTimeout(ctx)
if got > 2*time.Second || got <= 0 {
t.Errorf("timeout = %v, want just under 2s", got)
}
})
t.Run("a further deadline is capped", func(t *testing.T) {
ctx, cancel := context.WithTimeout(context.Background(), time.Hour)
defer cancel()
if got := resolveGHExecTimeout(ctx); got != ghCLITimeout {
t.Errorf("timeout = %v, want it capped at %v", got, ghCLITimeout)
}
})
}
func TestFirstArg(t *testing.T) {
cases := []struct {
name string
args []string
want string
}{
{"nil", nil, "<no-args>"},
{"empty", []string{}, "<no-args>"},
{"single", []string{"api"}, "api"},
{"multiple", []string{"pr", "view", "1"}, "pr"},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
if got := firstArg(tc.args); got != tc.want {
t.Errorf("firstArg(%v) = %q, want %q", tc.args, got, tc.want)
}
})
}
}
func TestConvertGHIssue(t *testing.T) {
raw := &ghIssue{
Number: 11,
Title: "Crash on start",
URL: "https://github.com/acme/widget/issues/11",
State: "CLOSED",
Body: "stack trace",
CreatedAt: time.Date(2026, 2, 1, 0, 0, 0, 0, time.UTC),
UpdatedAt: time.Date(2026, 2, 2, 0, 0, 0, 0, time.UTC),
ClosedAt: "2026-02-03T00:00:00Z",
}
raw.Author.Login = "erin"
raw.Labels = []struct {
Name string `json:"name"`
}{{Name: "bug"}, {Name: "regression"}}
raw.Assignees = []struct {
Login string `json:"login"`
}{{Login: "frank"}}
issue := convertGHIssue(raw, "acme", "widget")
if issue.Number != 11 || issue.Title != "Crash on start" || issue.Body != "stack trace" {
t.Errorf("scalars = %#v", issue)
}
if issue.URL != raw.URL || issue.HTMLURL != raw.URL {
t.Errorf("URL/HTMLURL = (%q, %q), want both %q", issue.URL, issue.HTMLURL, raw.URL)
}
if issue.State != "closed" {
t.Errorf("state = %q, want lowercased", issue.State)
}
if issue.AuthorLogin != "erin" || issue.RepoOwner != "acme" || issue.RepoName != "widget" {
t.Errorf("author/repo = (%q, %q, %q)", issue.AuthorLogin, issue.RepoOwner, issue.RepoName)
}
if strings.Join(issue.Labels, ",") != "bug,regression" {
t.Errorf("labels = %v", issue.Labels)
}
if strings.Join(issue.Assignees, ",") != "frank" {
t.Errorf("assignees = %v", issue.Assignees)
}
if !issue.CreatedAt.Equal(raw.CreatedAt) || !issue.UpdatedAt.Equal(raw.UpdatedAt) {
t.Errorf("timestamps = (%v, %v)", issue.CreatedAt, issue.UpdatedAt)
}
wantClosed := time.Date(2026, 2, 3, 0, 0, 0, 0, time.UTC)
if issue.ClosedAt == nil || !issue.ClosedAt.Equal(wantClosed) {
t.Errorf("closed_at = %v, want %v", issue.ClosedAt, wantClosed)
}
}
func TestGHClient_ParsePRList(t *testing.T) {
t.Run("stamps the repo identity onto every row", func(t *testing.T) {
prs, err := (&GHClient{}).parsePRList(
`[{"number":1,"state":"OPEN","author":{"login":"a"}},
{"number":2,"state":"CLOSED","mergedAt":"2026-01-01T00:00:00Z","author":{"login":"b"}}]`,
"acme", "widget",
)
if err != nil {
t.Fatalf("parsePRList: %v", err)
}
if len(prs) != 2 {
t.Fatalf("prs = %#v, want 2", prs)
}
for i, pr := range prs {
if pr.RepoOwner != "acme" || pr.RepoName != "widget" {
t.Errorf("prs[%d] repo = (%q, %q)", i, pr.RepoOwner, pr.RepoName)
}
}
if prs[0].State != "open" {
t.Errorf("prs[0] state = %q, want open", prs[0].State)
}
if prs[1].State != prStateMerged {
t.Errorf("prs[1] state = %q, want merged", prs[1].State)
}
})
t.Run("unparseable input", func(t *testing.T) {
if _, err := (&GHClient{}).parsePRList("nope", "o", "r"); err == nil ||
!strings.Contains(err.Error(), "parse PR list") {
t.Fatalf("err = %v, want a parse failure", err)
}
})
}
@@ -0,0 +1,399 @@
package github
import (
"context"
"encoding/base64"
"errors"
"net/http"
"strings"
"testing"
"time"
)
func TestPATClient_ListRepoDirectory(t *testing.T) {
c, requests := newRecordingPATServer(t, map[string]string{
"/repos/acme/widget/contents/docs/specs": `[
{"name":"spec.md","path":"docs/specs/spec.md","type":"file","sha":"aaa","size":128},
{"name":"images","path":"docs/specs/images","type":"dir","sha":"bbb","size":0}
]`,
})
entries, err := c.ListRepoDirectory(context.Background(), "acme", "widget", "docs/specs", "main")
if err != nil {
t.Fatalf("ListRepoDirectory: %v", err)
}
want := []RepoContentEntry{
{Name: "spec.md", Path: "docs/specs/spec.md", Type: RepoContentTypeFile, SHA: "aaa", Size: 128},
{Name: "images", Path: "docs/specs/images", Type: RepoContentTypeDir, SHA: "bbb"},
}
if len(entries) != len(want) {
t.Fatalf("entries = %#v, want %#v", entries, want)
}
for i := range want {
if entries[i] != want[i] {
t.Errorf("entries[%d] = %#v, want %#v", i, entries[i], want[i])
}
}
if got := parseQueryValues(t, (*requests)[0].Query).Get("ref"); got != "main" {
t.Errorf("ref = %q, want main", got)
}
}
func TestPATClient_ListRepoDirectory_RootOmitsThePathSegment(t *testing.T) {
c, requests := newRecordingPATServer(t, map[string]string{
"/repos/acme/widget/contents": `[]`,
})
if _, err := c.ListRepoDirectory(context.Background(), "acme", "widget", "", ""); err != nil {
t.Fatalf("ListRepoDirectory: %v", err)
}
if (*requests)[0].Path != "/repos/acme/widget/contents" {
t.Errorf("path = %q, want the bare contents endpoint", (*requests)[0].Path)
}
if (*requests)[0].Query != "" {
t.Errorf("query = %q, want no ref parameter", (*requests)[0].Query)
}
}
func TestPATClient_ListRepoDirectory_MissingDirectoryIsTyped(t *testing.T) {
c, _ := newRecordingPATServer(t, nil)
entries, err := c.ListRepoDirectory(context.Background(), "acme", "widget", "nope", "main")
if entries != nil {
t.Errorf("entries = %#v, want nil", entries)
}
var apiErr *GitHubAPIError
if !errors.As(err, &apiErr) || apiErr.StatusCode != http.StatusNotFound {
t.Fatalf("err = %v, want an unwrappable *GitHubAPIError with 404", err)
}
if !strings.Contains(err.Error(), "list repo directory") {
t.Errorf("err = %v, want the wrap to name the operation", err)
}
}
func TestPATClient_GetRepoFileContent(t *testing.T) {
content := "package main\n\nfunc main() {}\n"
// GitHub wraps base64 content at 60 characters; the decoder must strip
// those newlines before decoding. `\n` here is the two-character JSON
// escape, so the decoded string really does carry an embedded newline.
encoded := base64.StdEncoding.EncodeToString([]byte(content))
wrapped := encoded[:8] + `\n` + encoded[8:]
c, requests := newRecordingPATServer(t, map[string]string{
"/repos/acme/widget/contents/cmd/main.go": `{"type":"file","encoding":"base64","content":"` + wrapped + `"}`,
})
got, err := c.GetRepoFileContent(context.Background(), "acme", "widget", "cmd/main.go", "abc123")
if err != nil {
t.Fatalf("GetRepoFileContent: %v", err)
}
if string(got) != content {
t.Errorf("content = %q, want %q", got, content)
}
if got := parseQueryValues(t, (*requests)[0].Query).Get("ref"); got != "abc123" {
t.Errorf("ref = %q, want abc123", got)
}
}
func TestPATClient_GetRepoFileContent_RejectsUnsupportedEncoding(t *testing.T) {
c, _ := newRecordingPATServer(t, map[string]string{
"/repos/acme/widget/contents/big.bin": `{"type":"file","encoding":"none","content":""}`,
})
got, err := c.GetRepoFileContent(context.Background(), "acme", "widget", "big.bin", "")
if got != nil {
t.Errorf("content = %q, want nil", got)
}
if err == nil || !strings.Contains(err.Error(), `unsupported encoding "none"`) {
t.Fatalf("err = %v, want it to name the unsupported encoding", err)
}
}
func TestPATClient_GetRepoFileContent_RejectsUndecodableBase64(t *testing.T) {
c, _ := newRecordingPATServer(t, map[string]string{
"/repos/acme/widget/contents/x": `{"type":"file","encoding":"base64","content":"!!!not base64!!!"}`,
})
if _, err := c.GetRepoFileContent(context.Background(), "acme", "widget", "x", ""); err == nil ||
!strings.Contains(err.Error(), "decode base64") {
t.Fatalf("err = %v, want a base64 decode failure", err)
}
}
func TestPATClient_GetRepoFileContent_MissingFileIsTyped(t *testing.T) {
c, _ := newRecordingPATServer(t, nil)
_, err := c.GetRepoFileContent(context.Background(), "acme", "widget", "gone.txt", "")
var apiErr *GitHubAPIError
if !errors.As(err, &apiErr) || apiErr.StatusCode != http.StatusNotFound {
t.Fatalf("err = %v, want an unwrappable *GitHubAPIError with 404", err)
}
}
func TestPATClient_GetPRStatus_RollsUpReviewsAndChecks(t *testing.T) {
routes := prStatusRoutes()
routes["/repos/acme/widget/pulls/42/reviews"] = `[
{"id":1,"state":"APPROVED","submitted_at":"2026-01-05T10:00:00Z","user":{"login":"alice"}},
{"id":2,"state":"APPROVED","submitted_at":"2026-01-06T10:00:00Z","user":{"login":"bob"}}
]`
c, _ := newRecordingPATServer(t, routes)
status, err := c.GetPRStatus(context.Background(), "acme", "widget", 42)
if err != nil {
t.Fatalf("GetPRStatus: %v", err)
}
if status.PR == nil || status.PR.Number != 42 {
t.Fatalf("PR = %#v", status.PR)
}
if status.ReviewState != computedReviewStateApproved {
t.Errorf("review state = %q, want approved", status.ReviewState)
}
if status.ReviewCount != 2 {
t.Errorf("review count = %d, want 2 distinct approving reviewers", status.ReviewCount)
}
if status.PendingReviewCount != 0 {
t.Errorf("pending review count = %d, want 0", status.PendingReviewCount)
}
if status.ChecksState != "failure" {
t.Errorf("checks state = %q, want failure", status.ChecksState)
}
if status.ChecksTotal != 2 || status.ChecksPassing != 1 {
t.Errorf("checks = %d/%d, want 1/2", status.ChecksPassing, status.ChecksTotal)
}
if status.MergeableState != "blocked" {
t.Errorf("mergeable state = %q, want blocked", status.MergeableState)
}
if !status.ChecksPopulated || !status.ReviewCountsPopulated {
t.Error("the REST path counted checks and reviews; both Populated flags must be set")
}
// The REST path never fetches review threads, so it must not claim to
// have counted them — SyncTaskPR relies on that to preserve the GraphQL value.
if status.UnresolvedReviewThreadsPopulated {
t.Error("UnresolvedReviewThreadsPopulated must stay false on the REST path")
}
}
// ReviewState and ReviewCount deliberately answer different questions, and an
// approver who later leaves a plain comment is where they diverge:
// ReviewState takes each author's strictly-latest review (COMMENTED, so the
// PR is no longer "all approved"), while ReviewCount ignores non-binding
// states so the popover still renders "Approved (1)".
func TestPATClient_GetPRStatus_LaterCommentFromAnApprover(t *testing.T) {
routes := prStatusRoutes()
routes["/repos/acme/widget/pulls/42/reviews"] = `[
{"id":1,"state":"APPROVED","submitted_at":"2026-01-05T10:00:00Z","user":{"login":"alice"}},
{"id":2,"state":"COMMENTED","submitted_at":"2026-01-06T10:00:00Z","user":{"login":"alice"}}
]`
c, _ := newRecordingPATServer(t, routes)
status, err := c.GetPRStatus(context.Background(), "acme", "widget", 42)
if err != nil {
t.Fatalf("GetPRStatus: %v", err)
}
if status.ReviewState != computedReviewStatePending {
t.Errorf("review state = %q, want pending", status.ReviewState)
}
if status.ReviewCount != 1 {
t.Errorf("review count = %d, want 1 — a later comment must not drop the approval", status.ReviewCount)
}
if status.PendingReviewCount != 1 {
t.Errorf("pending review count = %d, want 1", status.PendingReviewCount)
}
}
// A requested-but-not-yet-submitted reviewer is the pending signal that wins
// over any derived-from-reviews count.
func TestPATClient_GetPRStatus_RequestedReviewersDrivePendingCount(t *testing.T) {
routes := prStatusRoutes()
routes["/repos/acme/widget/pulls/42"] = `{"number":42,"state":"open","mergeable_state":"BLOCKED",
"requested_reviewers":[{"login":"carol"},{"login":"dave"}],
"user":{"login":"bob"},"head":{"ref":"feature","sha":"headsha"},"base":{"ref":"main"}}`
routes["/repos/acme/widget/pulls/42/reviews"] = `[]`
c, _ := newRecordingPATServer(t, routes)
status, err := c.GetPRStatus(context.Background(), "acme", "widget", 42)
if err != nil {
t.Fatalf("GetPRStatus: %v", err)
}
if status.PendingReviewCount != 2 {
t.Errorf("pending review count = %d, want 2 requested reviewers", status.PendingReviewCount)
}
if status.ReviewState != computedReviewStatePending {
t.Errorf("review state = %q, want pending", status.ReviewState)
}
if status.ReviewCount != 0 {
t.Errorf("review count = %d, want 0 — nobody has approved yet", status.ReviewCount)
}
}
func TestPATClient_GetPRFeedback_AggregatesReviewsCommentsAndChecks(t *testing.T) {
routes := prStatusRoutes()
routes["/repos/acme/widget/pulls/42/comments"] = `[{"id":20,"body":"inline",
"created_at":"2026-01-05T12:00:00Z","user":{"login":"alice","type":"User"}}]`
routes["/repos/acme/widget/issues/42/comments"] = `[]`
c, _ := newRecordingPATServer(t, routes)
feedback, err := c.GetPRFeedback(context.Background(), "acme", "widget", 42)
if err != nil {
t.Fatalf("GetPRFeedback: %v", err)
}
if feedback.PR == nil || feedback.PR.Number != 42 {
t.Fatalf("PR = %#v", feedback.PR)
}
if len(feedback.Reviews) != 2 || len(feedback.Checks) != 2 {
t.Errorf("reviews/checks = (%d, %d), want (2, 2)", len(feedback.Reviews), len(feedback.Checks))
}
if len(feedback.Comments) != 1 || feedback.Comments[0].ID != 20 {
t.Errorf("comments = %#v", feedback.Comments)
}
// A failing check alone is enough to flag the PR as needing attention.
if !feedback.HasIssues {
t.Error("HasIssues = false, want true — one check concluded failure")
}
}
func TestPATClient_GetPRFeedback_PropagatesAFailedLeg(t *testing.T) {
routes := prStatusRoutes()
// Drop the check-runs route so that leg 404s while the others succeed.
delete(routes, "/repos/acme/widget/commits/headsha/check-runs")
routes["/repos/acme/widget/pulls/42/comments"] = `[]`
routes["/repos/acme/widget/issues/42/comments"] = `[]`
c, _ := newRecordingPATServer(t, routes)
feedback, err := c.GetPRFeedback(context.Background(), "acme", "widget", 42)
if err == nil {
t.Fatal("expected the failing check-runs leg to abort the aggregate")
}
if feedback != nil {
t.Errorf("feedback = %#v, want nil", feedback)
}
}
// prStatusRoutes is the four-endpoint fixture the PR status/feedback rollups
// read: the PR, its reviews, its check runs, and its commit status contexts.
func prStatusRoutes() map[string]string {
return map[string]string{
"/repos/acme/widget/pulls/42": `{"number":42,"state":"open","mergeable_state":"BLOCKED",
"user":{"login":"bob"},"head":{"ref":"feature","sha":"headsha"},"base":{"ref":"main"}}`,
"/repos/acme/widget/pulls/42/reviews": `[
{"id":1,"state":"APPROVED","submitted_at":"2026-01-05T10:00:00Z","user":{"login":"alice"}},
{"id":2,"state":"COMMENTED","submitted_at":"2026-01-06T10:00:00Z","user":{"login":"alice"}}
]`,
"/repos/acme/widget/commits/headsha/check-runs": `{"check_runs":[
{"name":"unit","status":"completed","conclusion":"success","html_url":"https://ci/unit"},
{"name":"lint","status":"completed","conclusion":"failure","html_url":"https://ci/lint"}
]}`,
"/repos/acme/widget/commits/headsha/status": `{"statuses":[]}`,
}
}
func TestPATClient_ContextCancellationSurfaces(t *testing.T) {
c, requests := newRecordingPATServer(t, map[string]string{"/user": `{"login":"octocat"}`})
ctx, cancel := context.WithCancel(context.Background())
cancel()
_, err := c.GetAuthenticatedUser(ctx)
if err == nil {
t.Fatal("expected an error from a cancelled context")
}
if !errors.Is(err, context.Canceled) {
t.Fatalf("err = %v, want it to unwrap to context.Canceled", err)
}
if len(*requests) != 0 {
t.Errorf("requests = %d, want 0 — a cancelled context must not reach the server", len(*requests))
}
}
func TestParseNextLink(t *testing.T) {
cases := []struct {
name string
header string
want string
}{
{"empty header", "", ""},
{
"next link is stripped down to path and query",
`<` + githubAPIBase + `/repos/o/r/branches?per_page=100&page=2>; rel="next"`,
"/repos/o/r/branches?per_page=100&page=2",
},
{
"next is picked out of a multi-rel header",
`<` + githubAPIBase + `/x?page=2>; rel="next", <` + githubAPIBase + `/x?page=9>; rel="last"`,
"/x?page=2",
},
{
"a last-only header has no next page",
`<` + githubAPIBase + `/x?page=9>; rel="last"`,
"",
},
{
"an absolute URL off another host is returned verbatim",
`<https://ghe.example.com/api/v3/x?page=2>; rel="next"`,
"https://ghe.example.com/api/v3/x?page=2",
},
{"malformed brackets are skipped", `https://api.github.com/x?page=2; rel="next"`, ""},
{"reversed brackets are skipped", `>` + githubAPIBase + `/x<; rel="next"`, ""},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
if got := parseNextLink(tc.header); got != tc.want {
t.Errorf("parseNextLink(%q) = %q, want %q", tc.header, got, tc.want)
}
})
}
}
func TestFilterReposByQuery(t *testing.T) {
repos := []GitHubRepo{
{FullName: "acme/Widget"},
{FullName: "acme/gadget"},
{FullName: "other/widget-tools"},
}
t.Run("empty query returns the input unchanged", func(t *testing.T) {
got := filterReposByQuery(repos, "")
if len(got) != 3 {
t.Fatalf("repos = %#v, want all three", got)
}
})
t.Run("match is case-insensitive over full_name", func(t *testing.T) {
got := filterReposByQuery(repos, "WIDGET")
if len(got) != 2 {
t.Fatalf("repos = %#v, want acme/Widget and other/widget-tools", got)
}
if got[0].FullName != "acme/Widget" || got[1].FullName != "other/widget-tools" {
t.Errorf("repos = %#v", got)
}
})
t.Run("no match yields an empty, non-nil slice", func(t *testing.T) {
got := filterReposByQuery(repos, "nothing")
if got == nil || len(got) != 0 {
t.Fatalf("repos = %#v, want an empty slice", got)
}
})
}
func TestConvertRepoListItems(t *testing.T) {
pushed := time.Date(2026, 5, 4, 3, 2, 1, 0, time.UTC)
items := []repoListItem{
{
FullName: "acme/widget", Name: "widget", Private: true,
DefaultBranch: "trunk", Description: "a widget", PushedAt: pushed,
},
{FullName: "acme/quiet", Name: "quiet"},
}
items[0].Owner.Login = "acme"
items[1].Owner.Login = "acme"
got := convertRepoListItems(items)
if len(got) != 2 {
t.Fatalf("repos = %d, want 2", len(got))
}
if got[0].FullName != "acme/widget" || got[0].Owner != "acme" || got[0].Name != "widget" {
t.Errorf("repos[0] identity = %#v", got[0])
}
if !got[0].Private || got[0].DefaultBranch != "trunk" || got[0].Description != "a widget" {
t.Errorf("repos[0] attributes = %#v", got[0])
}
if got[0].PushedAt == nil || !got[0].PushedAt.Equal(pushed) {
t.Errorf("repos[0] pushed_at = %v, want %v", got[0].PushedAt, pushed)
}
// A zero pushed_at must stay nil so `omitempty` drops it instead of
// serializing "0001-01-01T00:00:00Z".
if got[1].PushedAt != nil {
t.Errorf("repos[1] pushed_at = %v, want nil", got[1].PushedAt)
}
}
@@ -0,0 +1,674 @@
package github
import (
"context"
"errors"
"net/http"
"strconv"
"strings"
"testing"
"time"
)
func TestPATClient_SetsAuthAndVersionHeadersOnGET(t *testing.T) {
c, requests := newRecordingPATServer(t, map[string]string{"/user": `{"login":"octocat"}`})
if _, err := c.GetAuthenticatedUser(context.Background()); err != nil {
t.Fatalf("GetAuthenticatedUser: %v", err)
}
if len(*requests) != 1 {
t.Fatalf("requests = %d, want 1", len(*requests))
}
got := (*requests)[0]
if got.Method != http.MethodGet {
t.Errorf("method = %q, want GET", got.Method)
}
if got.Header.Get("Authorization") != "token test-token" {
t.Errorf("Authorization = %q, want %q", got.Header.Get("Authorization"), "token test-token")
}
if got.Header.Get("Accept") != githubAccept {
t.Errorf("Accept = %q, want %q", got.Header.Get("Accept"), githubAccept)
}
if got.Header.Get("X-GitHub-Api-Version") != githubAPIVersion {
t.Errorf("X-GitHub-Api-Version = %q, want %q", got.Header.Get("X-GitHub-Api-Version"), githubAPIVersion)
}
}
func TestPATClient_GetAuthenticatedUser_CachesLogin(t *testing.T) {
c, requests := newRecordingPATServer(t, map[string]string{"/user": `{"login":"octocat"}`})
first, err := c.GetAuthenticatedUser(context.Background())
if err != nil {
t.Fatalf("first call: %v", err)
}
second, err := c.GetAuthenticatedUser(context.Background())
if err != nil {
t.Fatalf("second call: %v", err)
}
if first != "octocat" || second != "octocat" {
t.Fatalf("logins = (%q, %q), want both octocat", first, second)
}
if len(*requests) != 1 {
t.Fatalf("requests = %d, want 1 (second call must hit the cache)", len(*requests))
}
}
func TestPATClient_IsAuthenticated(t *testing.T) {
t.Run("valid token", func(t *testing.T) {
c, _ := newRecordingPATServer(t, map[string]string{"/user": `{"login":"octocat"}`})
ok, err := c.IsAuthenticated(context.Background())
if err != nil {
t.Fatalf("IsAuthenticated: %v", err)
}
if !ok {
t.Error("authenticated = false, want true")
}
})
t.Run("rejected token reports false without an error", func(t *testing.T) {
// No /user route → 404 → GetAuthenticatedUser errors, which
// IsAuthenticated must translate into (false, nil).
c, _ := newRecordingPATServer(t, nil)
ok, err := c.IsAuthenticated(context.Background())
if err != nil {
t.Fatalf("IsAuthenticated must swallow the auth failure, got %v", err)
}
if ok {
t.Error("authenticated = true, want false")
}
})
}
func TestPATClient_HasRepositoryAccess(t *testing.T) {
t.Run("repo readable", func(t *testing.T) {
c, requests := newRecordingPATServer(t, map[string]string{
"/repos/acme/widget": `{"full_name":"acme/widget"}`,
})
ok, err := c.HasRepositoryAccess(context.Background(), "acme", "widget")
if err != nil {
t.Fatalf("HasRepositoryAccess: %v", err)
}
if !ok {
t.Error("access = false, want true")
}
if (*requests)[0].Path != "/repos/acme/widget" {
t.Errorf("path = %q, want /repos/acme/widget", (*requests)[0].Path)
}
})
t.Run("empty full_name reports no access", func(t *testing.T) {
c, _ := newRecordingPATServer(t, map[string]string{"/repos/acme/widget": `{}`})
ok, err := c.HasRepositoryAccess(context.Background(), "acme", "widget")
if err != nil {
t.Fatalf("HasRepositoryAccess: %v", err)
}
if ok {
t.Error("access = true, want false when full_name is absent")
}
})
t.Run("404 surfaces a typed API error", func(t *testing.T) {
c, _ := newRecordingPATServer(t, nil)
ok, err := c.HasRepositoryAccess(context.Background(), "acme", "widget")
if ok {
t.Error("access = true, want false on error")
}
var apiErr *GitHubAPIError
if !errors.As(err, &apiErr) || apiErr.StatusCode != http.StatusNotFound {
t.Fatalf("err = %v, want *GitHubAPIError with 404", err)
}
})
}
func TestPATClient_GetPR_DecodesEveryField(t *testing.T) {
c, requests := newRecordingPATServer(t, map[string]string{
"/repos/acme/widget/pulls/42": `{
"number":42,"title":"Add widgets","html_url":"https://github.com/acme/widget/pull/42",
"body":"the body","state":"open","draft":true,"mergeable":true,"mergeable_state":"CLEAN",
"additions":12,"deletions":3,
"created_at":"2026-01-01T10:00:00Z","updated_at":"2026-01-02T11:00:00Z",
"merged_at":null,"closed_at":null,"maintainer_can_modify":true,
"requested_reviewers":[{"login":"alice"}],
"requested_teams":[{"slug":"platform","name":"Platform Team"}],
"user":{"login":"bob"},
"head":{"ref":"feature","sha":"abc123","repo":{"id":77,"name":"widget-fork","full_name":"contributor/widget-fork","clone_url":"https://github.com/contributor/widget-fork.git"}},
"base":{"ref":"main","repo":{"id":11,"name":"widget","full_name":"acme/widget","default_branch":"trunk"}}
}`,
})
pr, err := c.GetPR(context.Background(), "acme", "widget", 42)
if err != nil {
t.Fatalf("GetPR: %v", err)
}
if (*requests)[0].Path != "/repos/acme/widget/pulls/42" {
t.Errorf("path = %q, want /repos/acme/widget/pulls/42", (*requests)[0].Path)
}
assertPRScalars(t, pr)
assertPRRepositories(t, pr)
if len(pr.RequestedReviewers) != 2 {
t.Fatalf("requested reviewers = %#v, want user + team", pr.RequestedReviewers)
}
if pr.RequestedReviewers[0] != (RequestedReviewer{Login: "alice", Type: reviewerTypeUser}) {
t.Errorf("reviewer[0] = %#v", pr.RequestedReviewers[0])
}
if pr.RequestedReviewers[1] != (RequestedReviewer{Login: "platform", Type: reviewerTypeTeam}) {
t.Errorf("reviewer[1] = %#v", pr.RequestedReviewers[1])
}
if pr.MergedAt != nil || pr.ClosedAt != nil {
t.Errorf("MergedAt = %v, ClosedAt = %v, want both nil", pr.MergedAt, pr.ClosedAt)
}
}
func assertPRScalars(t *testing.T, pr *PR) {
t.Helper()
if pr.Number != 42 || pr.Title != "Add widgets" {
t.Errorf("number/title = (%d, %q)", pr.Number, pr.Title)
}
if pr.HTMLURL != "https://github.com/acme/widget/pull/42" {
t.Errorf("html_url = %q", pr.HTMLURL)
}
if pr.Body != "the body" || pr.State != "open" {
t.Errorf("body/state = (%q, %q)", pr.Body, pr.State)
}
if !pr.Draft || !pr.Mergeable || !pr.MaintainerCanModify {
t.Errorf("draft=%v mergeable=%v maintainerCanModify=%v, want all true",
pr.Draft, pr.Mergeable, pr.MaintainerCanModify)
}
if pr.MergeableState != "clean" {
t.Errorf("mergeable_state = %q, want lowercased clean", pr.MergeableState)
}
if pr.Additions != 12 || pr.Deletions != 3 {
t.Errorf("additions/deletions = (%d, %d), want (12, 3)", pr.Additions, pr.Deletions)
}
if pr.HeadBranch != "feature" || pr.HeadSHA != "abc123" || pr.BaseBranch != "main" {
t.Errorf("head/base = (%q, %q, %q)", pr.HeadBranch, pr.HeadSHA, pr.BaseBranch)
}
if pr.AuthorLogin != "bob" || pr.RepoOwner != "acme" || pr.RepoName != "widget" {
t.Errorf("author/repo = (%q, %q, %q)", pr.AuthorLogin, pr.RepoOwner, pr.RepoName)
}
if !pr.CreatedAt.Equal(time.Date(2026, 1, 1, 10, 0, 0, 0, time.UTC)) {
t.Errorf("created_at = %v", pr.CreatedAt)
}
if !pr.UpdatedAt.Equal(time.Date(2026, 1, 2, 11, 0, 0, 0, time.UTC)) {
t.Errorf("updated_at = %v", pr.UpdatedAt)
}
}
// assertPRRepositories pins the nested head.repo / base.repo decode, which
// only happens through patPR's custom UnmarshalJSON.
func assertPRRepositories(t *testing.T, pr *PR) {
t.Helper()
if pr.HeadRepoID != 77 || pr.HeadRepoOwner != "contributor" || pr.HeadRepoName != "widget-fork" {
t.Errorf("head repo = (%d, %q, %q), want (77, contributor, widget-fork)",
pr.HeadRepoID, pr.HeadRepoOwner, pr.HeadRepoName)
}
if pr.HeadRepoCloneURL != "https://github.com/contributor/widget-fork.git" {
t.Errorf("head clone url = %q", pr.HeadRepoCloneURL)
}
if pr.BaseRepoID != 11 || pr.BaseRepoOwner != "acme" || pr.BaseRepoName != "widget" {
t.Errorf("base repo = (%d, %q, %q), want (11, acme, widget)",
pr.BaseRepoID, pr.BaseRepoOwner, pr.BaseRepoName)
}
if pr.BaseDefaultBranch != "trunk" {
t.Errorf("base default branch = %q, want trunk", pr.BaseDefaultBranch)
}
}
func TestPATClient_GetPR_MergedStateAndTimestamps(t *testing.T) {
c, _ := newRecordingPATServer(t, map[string]string{
"/repos/acme/widget/pulls/9": `{"number":9,"state":"closed",
"merged_at":"2026-02-03T09:00:00Z","closed_at":"2026-02-03T09:00:00Z",
"user":{"login":"bob"},"head":{"ref":"f"},"base":{"ref":"main"}}`,
})
pr, err := c.GetPR(context.Background(), "acme", "widget", 9)
if err != nil {
t.Fatalf("GetPR: %v", err)
}
if pr.State != prStateMerged {
t.Errorf("state = %q, want merged (merged_at promotes closed → merged)", pr.State)
}
want := time.Date(2026, 2, 3, 9, 0, 0, 0, time.UTC)
if pr.MergedAt == nil || !pr.MergedAt.Equal(want) {
t.Errorf("merged_at = %v, want %v", pr.MergedAt, want)
}
if pr.ClosedAt == nil || !pr.ClosedAt.Equal(want) {
t.Errorf("closed_at = %v, want %v", pr.ClosedAt, want)
}
// No head.repo / base.repo in the payload: the identity fields stay zero.
if pr.HeadRepoID != 0 || pr.BaseRepoID != 0 || pr.BaseDefaultBranch != "" {
t.Errorf("expected zero repo identity, got head=%d base=%d branch=%q",
pr.HeadRepoID, pr.BaseRepoID, pr.BaseDefaultBranch)
}
}
func TestPATClient_GetPR_ErrorIsWrappedWithNumber(t *testing.T) {
c, _ := newRecordingPATServer(t, nil)
pr, err := c.GetPR(context.Background(), "acme", "widget", 42)
if pr != nil {
t.Errorf("pr = %#v, want nil on error", pr)
}
if err == nil || !strings.Contains(err.Error(), "get PR #42") {
t.Fatalf("err = %v, want it to name PR #42", err)
}
var apiErr *GitHubAPIError
if !errors.As(err, &apiErr) || apiErr.StatusCode != http.StatusNotFound {
t.Fatalf("err = %v, want an unwrappable *GitHubAPIError with 404", err)
}
}
func TestPATClient_GetIssue_DecodesEveryField(t *testing.T) {
c, requests := newRecordingPATServer(t, map[string]string{
"/repos/acme/widget/issues/5": `{
"number":5,"title":"Broken login","html_url":"https://github.com/acme/widget/issues/5",
"body":"steps to repro","state":"CLOSED",
"created_at":"2026-03-01T08:00:00Z","updated_at":"2026-03-02T08:00:00Z",
"closed_at":"2026-03-03T08:00:00Z",
"user":{"login":"carol"},
"labels":[{"name":"bug"},{"name":"p1"}],
"assignees":[{"login":"dave"}]
}`,
})
issue, err := c.GetIssue(context.Background(), "acme", "widget", 5)
if err != nil {
t.Fatalf("GetIssue: %v", err)
}
if (*requests)[0].Path != "/repos/acme/widget/issues/5" {
t.Errorf("path = %q, want /repos/acme/widget/issues/5", (*requests)[0].Path)
}
if issue.Number != 5 || issue.Title != "Broken login" || issue.Body != "steps to repro" {
t.Errorf("issue scalars = %#v", issue)
}
if issue.URL != "https://github.com/acme/widget/issues/5" || issue.HTMLURL != issue.URL {
t.Errorf("URL/HTMLURL = (%q, %q), want both the html_url", issue.URL, issue.HTMLURL)
}
if issue.State != "closed" {
t.Errorf("state = %q, want lowercased closed", issue.State)
}
if issue.AuthorLogin != "carol" || issue.RepoOwner != "acme" || issue.RepoName != "widget" {
t.Errorf("author/repo = (%q, %q, %q)", issue.AuthorLogin, issue.RepoOwner, issue.RepoName)
}
if strings.Join(issue.Labels, ",") != "bug,p1" {
t.Errorf("labels = %v, want [bug p1]", issue.Labels)
}
if strings.Join(issue.Assignees, ",") != "dave" {
t.Errorf("assignees = %v, want [dave]", issue.Assignees)
}
if !issue.CreatedAt.Equal(time.Date(2026, 3, 1, 8, 0, 0, 0, time.UTC)) {
t.Errorf("created_at = %v", issue.CreatedAt)
}
if !issue.UpdatedAt.Equal(time.Date(2026, 3, 2, 8, 0, 0, 0, time.UTC)) {
t.Errorf("updated_at = %v", issue.UpdatedAt)
}
wantClosed := time.Date(2026, 3, 3, 8, 0, 0, 0, time.UTC)
if issue.ClosedAt == nil || !issue.ClosedAt.Equal(wantClosed) {
t.Errorf("closed_at = %v, want %v", issue.ClosedAt, wantClosed)
}
}
func TestPATClient_GetIssue_OpenIssueHasNilClosedAt(t *testing.T) {
c, _ := newRecordingPATServer(t, map[string]string{
"/repos/acme/widget/issues/6": `{"number":6,"state":"open","closed_at":null,"user":{"login":"carol"}}`,
})
issue, err := c.GetIssue(context.Background(), "acme", "widget", 6)
if err != nil {
t.Fatalf("GetIssue: %v", err)
}
if issue.ClosedAt != nil {
t.Errorf("closed_at = %v, want nil for an open issue", issue.ClosedAt)
}
if len(issue.Labels) != 0 || len(issue.Assignees) != 0 {
t.Errorf("labels/assignees = (%v, %v), want empty", issue.Labels, issue.Assignees)
}
}
func TestPATClient_GetIssue_ErrorIsWrappedWithNumber(t *testing.T) {
c, _ := newRecordingPATServer(t, nil)
if _, err := c.GetIssue(context.Background(), "acme", "widget", 6); err == nil ||
!strings.Contains(err.Error(), "get issue #6") {
t.Fatalf("err = %v, want it to name issue #6", err)
}
}
func TestPATClient_GetIssueState(t *testing.T) {
c, requests := newRecordingPATServer(t, map[string]string{
"/repos/acme/widget/issues/7": `{"state":"closed","number":7}`,
})
state, err := c.GetIssueState(context.Background(), "acme", "widget", 7)
if err != nil {
t.Fatalf("GetIssueState: %v", err)
}
if state != "closed" {
t.Errorf("state = %q, want closed", state)
}
if (*requests)[0].Path != "/repos/acme/widget/issues/7" {
t.Errorf("path = %q", (*requests)[0].Path)
}
}
func TestPATClient_GetIssueState_Error(t *testing.T) {
c, _ := newRecordingPATServer(t, nil)
state, err := c.GetIssueState(context.Background(), "acme", "widget", 7)
if state != "" {
t.Errorf("state = %q, want empty on error", state)
}
if err == nil || !strings.Contains(err.Error(), "get issue state") {
t.Fatalf("err = %v, want a wrapped get-issue-state error", err)
}
}
func TestPATClient_ListAuthoredPRs_KeepsOnlyTheAuthenticatedUsersPRs(t *testing.T) {
c, requests := newRecordingPATServer(t, map[string]string{
"/user": `{"login":"octocat"}`,
"/repos/acme/widget/pulls": `[
{"number":1,"title":"mine","state":"open","user":{"login":"octocat"},"head":{"ref":"a"},"base":{"ref":"main"}},
{"number":2,"title":"theirs","state":"open","user":{"login":"someone-else"},"head":{"ref":"b"},"base":{"ref":"main"}},
{"number":3,"title":"mine too","state":"open","user":{"login":"octocat"},"head":{"ref":"c"},"base":{"ref":"main"}}
]`,
})
prs, err := c.ListAuthoredPRs(context.Background(), "acme", "widget")
if err != nil {
t.Fatalf("ListAuthoredPRs: %v", err)
}
if len(prs) != 2 {
t.Fatalf("prs = %d, want 2 (the other author must be filtered out)", len(prs))
}
if prs[0].Number != 1 || prs[1].Number != 3 {
t.Errorf("numbers = (%d, %d), want (1, 3)", prs[0].Number, prs[1].Number)
}
if prs[0].RepoOwner != "acme" || prs[0].RepoName != "widget" {
t.Errorf("repo = (%q, %q), want acme/widget", prs[0].RepoOwner, prs[0].RepoName)
}
listQuery := (*requests)[1].Query
if !strings.Contains(listQuery, "state=open") || !strings.Contains(listQuery, "per_page=100") {
t.Errorf("query = %q, want state=open and per_page=100", listQuery)
}
}
func TestPATClient_ListAuthoredPRs_PropagatesAuthFailure(t *testing.T) {
c, requests := newRecordingPATServer(t, nil)
prs, err := c.ListAuthoredPRs(context.Background(), "acme", "widget")
if err == nil {
t.Fatal("expected an error when /user fails")
}
if prs != nil {
t.Errorf("prs = %v, want nil", prs)
}
if len(*requests) != 1 {
t.Errorf("requests = %d, want 1 — the PR list must not run after auth fails", len(*requests))
}
}
func TestPATClient_ListReviewRequestedPRs_BuildsScopedQuery(t *testing.T) {
c, requests := newRecordingPATServer(t, map[string]string{
"/search/issues": `{"items":[{"id":501,"node_id":"PR_a","number":3,"title":"Review me",
"html_url":"https://github.com/acme/web/pull/3","state":"closed","draft":true,
"created_at":"2026-04-01T00:00:00Z","updated_at":"2026-04-02T00:00:00Z",
"repository_url":"https://api.github.com/repos/acme/web",
"user":{"login":"erin"},"pull_request":{"merged_at":"2026-04-03T00:00:00Z"}}]}`,
})
prs, err := c.ListReviewRequestedPRs(context.Background(), ReviewScopeUser, "repo:acme/web", "")
if err != nil {
t.Fatalf("ListReviewRequestedPRs: %v", err)
}
query := (*requests)[0].Query
for _, want := range []string{"user-review-requested", "per_page=50", "repo%3Aacme%2Fweb"} {
if !strings.Contains(query, want) {
t.Errorf("query = %q, want it to contain %q", query, want)
}
}
if len(prs) != 1 {
t.Fatalf("prs = %d, want 1", len(prs))
}
pr := prs[0]
if pr.ID != 501 || pr.NodeID != "PR_a" || pr.Number != 3 || pr.Title != "Review me" {
t.Errorf("identity = %#v", pr)
}
if pr.State != prStateMerged {
t.Errorf("state = %q, want merged — a non-empty pull_request.merged_at promotes closed", pr.State)
}
if pr.AuthorLogin != "erin" || !pr.Draft {
t.Errorf("author/draft = (%q, %v)", pr.AuthorLogin, pr.Draft)
}
if pr.RepoOwner != "acme" || pr.RepoName != "web" {
t.Errorf("repo = (%q, %q), want acme/web parsed from repository_url", pr.RepoOwner, pr.RepoName)
}
if pr.MergedAt == nil || !pr.MergedAt.Equal(time.Date(2026, 4, 3, 0, 0, 0, 0, time.UTC)) {
t.Errorf("merged_at = %v", pr.MergedAt)
}
}
func TestPATClient_ListReviewRequestedPRs_Error(t *testing.T) {
c, _ := newRecordingPATServer(t, nil)
if _, err := c.ListReviewRequestedPRs(context.Background(), "", "", ""); err == nil ||
!strings.Contains(err.Error(), "search review-requested") {
t.Fatalf("err = %v, want a wrapped search error", err)
}
}
func TestPATClient_SearchPRs_UsesFirstPageOfFifty(t *testing.T) {
c, requests := newRecordingPATServer(t, map[string]string{
"/search/issues": `{"total_count":2,"items":[
{"id":1,"number":1,"title":"one","state":"open","repository_url":"https://api.github.com/repos/o/r","pull_request":{}},
{"id":2,"number":2,"title":"two","state":"open","repository_url":"https://api.github.com/repos/o/r","pull_request":{}}
]}`,
})
prs, err := c.SearchPRs(context.Background(), "is:open", "")
if err != nil {
t.Fatalf("SearchPRs: %v", err)
}
if len(prs) != 2 || prs[0].Number != 1 || prs[1].Number != 2 {
t.Fatalf("prs = %#v", prs)
}
query := (*requests)[0].Query
if !strings.Contains(query, "per_page=50") || !strings.Contains(query, "page=1") {
t.Errorf("query = %q, want per_page=50 and page=1", query)
}
if !strings.Contains(query, "type%3Apr") {
t.Errorf("query = %q, want the injected type:pr qualifier", query)
}
}
func TestPATClient_SearchPRsPaged_ClampsPageAndPerPage(t *testing.T) {
cases := []struct {
name string
page, perPage int
wantPage, wantPerPage int
}{
{"zero page floors to 1", 0, 25, 1, 25},
{"negative page floors to 1", -3, 25, 1, 25},
{"zero per_page defaults to 50", 2, 0, 2, 50},
{"per_page above cap clamps to 100", 2, 500, 2, 100},
{"in-range values pass through", 3, 30, 3, 30},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
c, requests := newRecordingPATServer(t, map[string]string{
"/search/issues": `{"total_count":7,"items":[]}`,
})
page, err := c.SearchPRsPaged(context.Background(), "", "", tc.page, tc.perPage)
if err != nil {
t.Fatalf("SearchPRsPaged: %v", err)
}
if page.Page != tc.wantPage || page.PerPage != tc.wantPerPage {
t.Errorf("page/per_page = (%d, %d), want (%d, %d)",
page.Page, page.PerPage, tc.wantPage, tc.wantPerPage)
}
if page.TotalCount != 7 {
t.Errorf("total_count = %d, want 7", page.TotalCount)
}
if len(page.PRs) != 0 {
t.Errorf("prs = %#v, want empty", page.PRs)
}
gotQuery := (*requests)[0].Query
for _, want := range []string{
"page=" + strconv.Itoa(tc.wantPage), "per_page=" + strconv.Itoa(tc.wantPerPage),
} {
if !strings.Contains(gotQuery, want) {
t.Errorf("query = %q, want %q", gotQuery, want)
}
}
})
}
}
func TestPATClient_ListIssuesPaged_DropsPullRequestsFromSearchResults(t *testing.T) {
c, requests := newRecordingPATServer(t, map[string]string{
"/search/issues": `{"total_count":3,"items":[
{"id":10,"node_id":"I_a","number":10,"title":"a real issue","body":"details",
"html_url":"https://github.com/o/r/issues/10","state":"open",
"created_at":"2026-05-01T00:00:00Z","updated_at":"2026-05-02T00:00:00Z",
"repository_url":"https://api.github.com/repos/o/r","user":{"login":"frank"},
"labels":[{"name":"bug"}],"assignees":[{"login":"grace"}]},
{"id":11,"number":11,"title":"a PR in disguise","state":"open",
"repository_url":"https://api.github.com/repos/o/r","pull_request":{"url":"https://api/pulls/11"}}
]}`,
})
page, err := c.ListIssuesPaged(context.Background(), "", "", 1, 20)
if err != nil {
t.Fatalf("ListIssuesPaged: %v", err)
}
if len(page.Issues) != 1 {
t.Fatalf("issues = %d, want 1 — the pull_request item must be dropped", len(page.Issues))
}
got := page.Issues[0]
if got.ID != 10 || got.NodeID != "I_a" || got.Number != 10 {
t.Errorf("identity = %#v", got)
}
if got.Title != "a real issue" || got.Body != "details" || got.State != "open" {
t.Errorf("scalars = %#v", got)
}
if got.RepoOwner != "o" || got.RepoName != "r" || got.AuthorLogin != "frank" {
t.Errorf("repo/author = (%q, %q, %q)", got.RepoOwner, got.RepoName, got.AuthorLogin)
}
if strings.Join(got.Labels, ",") != "bug" || strings.Join(got.Assignees, ",") != "grace" {
t.Errorf("labels/assignees = (%v, %v)", got.Labels, got.Assignees)
}
// TotalCount is reported verbatim by GitHub — it is NOT the filtered length.
if page.TotalCount != 3 || page.Page != 1 || page.PerPage != 20 {
t.Errorf("page meta = (%d, %d, %d), want (3, 1, 20)", page.TotalCount, page.Page, page.PerPage)
}
if !strings.Contains((*requests)[0].Query, "type%3Aissue") {
t.Errorf("query = %q, want the injected type:issue qualifier", (*requests)[0].Query)
}
}
func TestPATClient_ListIssues_DelegatesToFirstPage(t *testing.T) {
c, requests := newRecordingPATServer(t, map[string]string{
"/search/issues": `{"total_count":1,"items":[{"id":1,"number":1,"title":"x",
"repository_url":"https://api.github.com/repos/o/r"}]}`,
})
issues, err := c.ListIssues(context.Background(), "", "is:open label:bug")
if err != nil {
t.Fatalf("ListIssues: %v", err)
}
if len(issues) != 1 || issues[0].Number != 1 {
t.Fatalf("issues = %#v", issues)
}
query := (*requests)[0].Query
if !strings.Contains(query, "per_page=50") || !strings.Contains(query, "page=1") {
t.Errorf("query = %q, want the default first page of 50", query)
}
}
func TestPATClient_ListIssuesPaged_Error(t *testing.T) {
c, _ := newRecordingPATServer(t, nil)
if _, err := c.ListIssuesPaged(context.Background(), "", "", 1, 10); err == nil ||
!strings.Contains(err.Error(), "search issues") {
t.Fatalf("err = %v, want a wrapped search-issues error", err)
}
}
func TestPATClient_ListUserOrgs(t *testing.T) {
c, requests := newRecordingPATServer(t, map[string]string{
"/user/orgs": `[{"login":"acme","avatar_url":"https://avatars/acme"},{"login":"other","avatar_url":""}]`,
})
orgs, err := c.ListUserOrgs(context.Background())
if err != nil {
t.Fatalf("ListUserOrgs: %v", err)
}
if len(orgs) != 2 {
t.Fatalf("orgs = %d, want 2", len(orgs))
}
if orgs[0] != (GitHubOrg{Login: "acme", AvatarURL: "https://avatars/acme"}) {
t.Errorf("orgs[0] = %#v", orgs[0])
}
if orgs[1] != (GitHubOrg{Login: "other"}) {
t.Errorf("orgs[1] = %#v", orgs[1])
}
if !strings.Contains((*requests)[0].Query, "per_page=100") {
t.Errorf("query = %q, want per_page=100", (*requests)[0].Query)
}
}
func TestPATClient_ListUserOrgs_Error(t *testing.T) {
c, _ := newRecordingPATServer(t, nil)
orgs, err := c.ListUserOrgs(context.Background())
if orgs != nil {
t.Errorf("orgs = %v, want nil", orgs)
}
if err == nil || !strings.Contains(err.Error(), "list user orgs") {
t.Fatalf("err = %v, want a wrapped list-user-orgs error", err)
}
}
func TestPATClient_SearchOrgRepos(t *testing.T) {
cases := []struct {
name string
query string
limit int
wantQ string
wantP string
}{
{"no free-text query", "", 30, "org:acme", "30"},
{"with free-text query", "widget", 30, "org:acme widget", "30"},
{"limit clamps to the cap", "", 900, "org:acme", "100"},
{"zero limit takes the default", "", 0, "org:acme", "20"},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
c, requests := newRecordingPATServer(t, map[string]string{
"/search/repositories": `{"items":[{"full_name":"acme/widget","owner":{"login":"acme"},
"name":"widget","private":true,"default_branch":"main","description":"w",
"pushed_at":"2026-06-01T00:00:00Z"}]}`,
})
repos, err := c.SearchOrgRepos(context.Background(), "acme", tc.query, tc.limit)
if err != nil {
t.Fatalf("SearchOrgRepos: %v", err)
}
if len(repos) != 1 {
t.Fatalf("repos = %d, want 1", len(repos))
}
got := repos[0]
if got.FullName != "acme/widget" || got.Owner != "acme" || got.Name != "widget" {
t.Errorf("identity = %#v", got)
}
if !got.Private || got.DefaultBranch != "main" || got.Description != "w" {
t.Errorf("attributes = %#v", got)
}
if got.PushedAt == nil || !got.PushedAt.Equal(time.Date(2026, 6, 1, 0, 0, 0, 0, time.UTC)) {
t.Errorf("pushed_at = %v", got.PushedAt)
}
values := parseQueryValues(t, (*requests)[0].Query)
if values.Get("q") != tc.wantQ {
t.Errorf("q = %q, want %q", values.Get("q"), tc.wantQ)
}
if values.Get("per_page") != tc.wantP {
t.Errorf("per_page = %q, want %q", values.Get("per_page"), tc.wantP)
}
})
}
}
func TestPATClient_SearchOrgRepos_Error(t *testing.T) {
c, _ := newRecordingPATServer(t, nil)
repos, err := c.SearchOrgRepos(context.Background(), "acme", "", 10)
if repos != nil {
t.Errorf("repos = %v, want nil", repos)
}
if err == nil || !strings.Contains(err.Error(), "search org repos") {
t.Fatalf("err = %v, want a wrapped search-org-repos error", err)
}
}
@@ -0,0 +1,118 @@
package github
import (
"io"
"net/http"
"net/http/httptest"
"net/url"
"strconv"
"sync"
"testing"
)
// patRequest records what a PATClient actually put on the wire so a test can
// assert method, path, query, headers and body rather than only the decoded
// result.
type patRequest struct {
Method string
Path string
Query string
Header http.Header
Body string
}
// newRecordingPATServer serves the given path→body map and records every
// request. Any path outside the map returns 404 with a JSON body, which the
// PATClient decode helpers surface as *GitHubAPIError.
func newRecordingPATServer(t *testing.T, routes map[string]string) (*PATClient, *[]patRequest) {
t.Helper()
return newRecordingPATServerFunc(t, func(r *http.Request) (int, string) {
body, ok := routes[r.URL.Path]
if !ok {
return http.StatusNotFound, `{"message":"Not Found"}`
}
return http.StatusOK, body
})
}
// newRecordingPATServerFunc is the general form: respond decides the status
// and body per request, and every request is still recorded. Assertions run in
// the calling goroutine off the returned slice — a handler goroutine must
// never call t.Fatal.
func newRecordingPATServerFunc(
t *testing.T, respond func(*http.Request) (int, string),
) (*PATClient, *[]patRequest) {
t.Helper()
var recorded []patRequest
// GetPRFeedback fans its three upstream reads out concurrently, so the
// recording slice is written from several handler goroutines at once.
var mu sync.Mutex
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
body, _ := io.ReadAll(r.Body)
mu.Lock()
recorded = append(recorded, patRequest{
Method: r.Method,
Path: r.URL.Path,
Query: r.URL.RawQuery,
Header: r.Header.Clone(),
Body: string(body),
})
mu.Unlock()
status, respBody := respond(r)
w.WriteHeader(status)
_, _ = w.Write([]byte(respBody))
}))
t.Cleanup(srv.Close)
return newPATClientPointingAt(t, srv.URL), &recorded
}
// newLinkPaginatedPATServer serves `pages` in order from a single endpoint,
// advertising the next page through a GitHub-shaped `Link: <...>; rel="next"`
// header on every response but the last. It exercises getPaginated's
// follow-the-link loop.
func newLinkPaginatedPATServer(
t *testing.T, path string, pages []string,
) (*PATClient, *[]patRequest) {
t.Helper()
var recorded []patRequest
served := 0
// getPaginated follows Link headers strictly in order — request N+1 is only
// sent after N's response is fully read — so these handler goroutines never
// overlap today. The mutex mirrors newRecordingPATServer and keeps that from
// becoming a silent race if a future test drives this server concurrently.
var mu sync.Mutex
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
mu.Lock()
recorded = append(recorded, patRequest{
Method: r.Method, Path: r.URL.Path, Query: r.URL.RawQuery, Header: r.Header.Clone(),
})
index := served
if r.URL.Path == path && served < len(pages) {
served++
}
mu.Unlock()
if r.URL.Path != path || index >= len(pages) {
w.WriteHeader(http.StatusNotFound)
_, _ = w.Write([]byte(`{"message":"Not Found"}`))
return
}
if index < len(pages)-1 {
next := githubAPIBase + path + "?per_page=100&page=" + strconv.Itoa(index+2)
w.Header().Set("Link", "<"+next+`>; rel="next"`)
}
_, _ = w.Write([]byte(pages[index]))
}))
t.Cleanup(srv.Close)
return newPATClientPointingAt(t, srv.URL), &recorded
}
// parseQueryValues decodes a raw query string, failing the test on malformed
// input so callers can assert on individual parameters.
func parseQueryValues(t *testing.T, rawQuery string) url.Values {
t.Helper()
values, err := url.ParseQuery(rawQuery)
if err != nil {
t.Fatalf("parse query %q: %v", rawQuery, err)
}
return values
}
@@ -0,0 +1,529 @@
package github
import (
"context"
"encoding/json"
"errors"
"net/http"
"strings"
"testing"
"time"
)
func TestPATClient_SubmitReview_SendsEventAndOptionalBody(t *testing.T) {
cases := []struct {
name string
event string
body string
wantJSON map[string]string
}{
{"approve without a body", "APPROVE", "", map[string]string{"event": "APPROVE"}},
{
"request changes with a body", "REQUEST_CHANGES", "please fix",
map[string]string{"event": "REQUEST_CHANGES", "body": "please fix"},
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
c, requests := newRecordingPATServerFunc(t, func(*http.Request) (int, string) {
return http.StatusOK, `{}`
})
if err := c.SubmitReview(context.Background(), "acme", "widget", 42, tc.event, tc.body); err != nil {
t.Fatalf("SubmitReview: %v", err)
}
got := (*requests)[0]
if got.Method != http.MethodPost {
t.Errorf("method = %q, want POST", got.Method)
}
if got.Path != "/repos/acme/widget/pulls/42/reviews" {
t.Errorf("path = %q", got.Path)
}
if got.Header.Get("Content-Type") != "application/json" {
t.Errorf("content-type = %q, want application/json", got.Header.Get("Content-Type"))
}
var payload map[string]string
if err := json.Unmarshal([]byte(got.Body), &payload); err != nil {
t.Fatalf("decode request body %q: %v", got.Body, err)
}
if len(payload) != len(tc.wantJSON) {
t.Fatalf("payload = %#v, want %#v", payload, tc.wantJSON)
}
for k, v := range tc.wantJSON {
if payload[k] != v {
t.Errorf("payload[%q] = %q, want %q", k, payload[k], v)
}
}
})
}
}
func TestPATClient_SubmitReview_ErrorIncludesStatusAndBody(t *testing.T) {
c, _ := newRecordingPATServerFunc(t, func(*http.Request) (int, string) {
return http.StatusUnprocessableEntity, `{"message":"Can not approve your own pull request"}`
})
err := c.SubmitReview(context.Background(), "acme", "widget", 42, "APPROVE", "")
if err == nil {
t.Fatal("expected an error from 422")
}
if !strings.Contains(err.Error(), "422") || !strings.Contains(err.Error(), "own pull request") {
t.Errorf("err = %v, want the status and upstream body surfaced", err)
}
}
func TestPATClient_MergePR(t *testing.T) {
t.Run("sends the merge method", func(t *testing.T) {
c, requests := newRecordingPATServerFunc(t, func(*http.Request) (int, string) {
return http.StatusOK, `{"merged":true}`
})
if err := c.MergePR(context.Background(), "acme", "widget", 42, "squash"); err != nil {
t.Fatalf("MergePR: %v", err)
}
got := (*requests)[0]
if got.Method != http.MethodPut {
t.Errorf("method = %q, want PUT", got.Method)
}
if got.Path != "/repos/acme/widget/pulls/42/merge" {
t.Errorf("path = %q", got.Path)
}
if got.Body != `{"merge_method":"squash"}` {
t.Errorf("body = %q, want the merge_method payload", got.Body)
}
})
t.Run("omits the merge method when unset", func(t *testing.T) {
c, requests := newRecordingPATServerFunc(t, func(*http.Request) (int, string) {
return http.StatusOK, `{"merged":true}`
})
if err := c.MergePR(context.Background(), "acme", "widget", 42, ""); err != nil {
t.Fatalf("MergePR: %v", err)
}
if (*requests)[0].Body != `{}` {
t.Errorf("body = %q, want an empty object so GitHub picks its default",
(*requests)[0].Body)
}
})
}
// A merge rejection must stay recoverable as *GitHubAPIError so the HTTP
// layer can map 405 (not mergeable) and 409 (conflict) onto a 409 response.
func TestPATClient_MergePR_StatusIsRecoverable(t *testing.T) {
for _, status := range []int{http.StatusMethodNotAllowed, http.StatusConflict} {
t.Run(http.StatusText(status), func(t *testing.T) {
c, _ := newRecordingPATServerFunc(t, func(*http.Request) (int, string) {
return status, `{"message":"Pull Request is not mergeable"}`
})
err := c.MergePR(context.Background(), "acme", "widget", 42, "merge")
var apiErr *GitHubAPIError
if !errors.As(err, &apiErr) {
t.Fatalf("err = %v, want a *GitHubAPIError", err)
}
if apiErr.StatusCode != status {
t.Errorf("status = %d, want %d", apiErr.StatusCode, status)
}
if apiErr.Endpoint != "/repos/acme/widget/pulls/42/merge" {
t.Errorf("endpoint = %q", apiErr.Endpoint)
}
if !strings.Contains(apiErr.Body, "not mergeable") {
t.Errorf("body = %q, want the upstream message", apiErr.Body)
}
})
}
}
func TestPATClient_CreateGist(t *testing.T) {
c, requests := newRecordingPATServerFunc(t, func(*http.Request) (int, string) {
return http.StatusCreated, `{"id":"abc123","html_url":"https://gist.github.com/abc123",
"created_at":"2026-07-01T12:00:00Z"}`
})
resp, err := c.CreateGist(context.Background(), CreateGistInput{
Description: "kandev share",
Public: false,
Files: map[string]GistFile{"README.md": {Content: "# hello"}},
})
if err != nil {
t.Fatalf("CreateGist: %v", err)
}
if resp.ID != "abc123" || resp.HTMLURL != "https://gist.github.com/abc123" {
t.Errorf("response = %#v", resp)
}
if !resp.CreatedAt.Equal(time.Date(2026, 7, 1, 12, 0, 0, 0, time.UTC)) {
t.Errorf("created_at = %v", resp.CreatedAt)
}
got := (*requests)[0]
if got.Method != http.MethodPost || got.Path != "/gists" {
t.Errorf("request = %s %s, want POST /gists", got.Method, got.Path)
}
var payload struct {
Description string `json:"description"`
Public bool `json:"public"`
Files map[string]map[string]string `json:"files"`
}
if err := json.Unmarshal([]byte(got.Body), &payload); err != nil {
t.Fatalf("decode payload %q: %v", got.Body, err)
}
if payload.Description != "kandev share" || payload.Public {
t.Errorf("payload meta = %#v", payload)
}
if payload.Files["README.md"]["content"] != "# hello" {
t.Errorf("payload files = %#v", payload.Files)
}
}
func TestPATClient_CreateGist_ErrorIsTyped(t *testing.T) {
c, _ := newRecordingPATServerFunc(t, func(*http.Request) (int, string) {
return http.StatusUnauthorized, `{"message":"Bad credentials"}`
})
resp, err := c.CreateGist(context.Background(), CreateGistInput{Files: map[string]GistFile{}})
if resp != nil {
t.Errorf("resp = %#v, want nil", resp)
}
var apiErr *GitHubAPIError
if !errors.As(err, &apiErr) || apiErr.StatusCode != http.StatusUnauthorized {
t.Fatalf("err = %v, want a *GitHubAPIError with 401", err)
}
}
func TestPATClient_DeleteGist(t *testing.T) {
t.Run("deletes by id", func(t *testing.T) {
c, requests := newRecordingPATServerFunc(t, func(*http.Request) (int, string) {
return http.StatusNoContent, ""
})
if err := c.DeleteGist(context.Background(), "abc123"); err != nil {
t.Fatalf("DeleteGist: %v", err)
}
got := (*requests)[0]
if got.Method != http.MethodDelete || got.Path != "/gists/abc123" {
t.Errorf("request = %s %s, want DELETE /gists/abc123", got.Method, got.Path)
}
if got.Header.Get("Authorization") != "token test-token" {
t.Errorf("DELETE must still carry auth, got %q", got.Header.Get("Authorization"))
}
})
t.Run("empty id never reaches the network", func(t *testing.T) {
c, requests := newRecordingPATServerFunc(t, func(*http.Request) (int, string) {
return http.StatusNoContent, ""
})
if err := c.DeleteGist(context.Background(), ""); err == nil {
t.Fatal("expected an error for an empty gist id")
}
if len(*requests) != 0 {
t.Errorf("requests = %d, want 0", len(*requests))
}
})
// share.IsAlreadyGone matches on the typed 404 to treat an already-revoked
// gist as a soft success rather than a 502.
t.Run("404 stays recoverable as a typed error", func(t *testing.T) {
c, _ := newRecordingPATServerFunc(t, func(*http.Request) (int, string) {
return http.StatusNotFound, `{"message":"Not Found"}`
})
err := c.DeleteGist(context.Background(), "gone")
var apiErr *GitHubAPIError
if !errors.As(err, &apiErr) || apiErr.StatusCode != http.StatusNotFound {
t.Fatalf("err = %v, want a *GitHubAPIError with 404", err)
}
if apiErr.Endpoint != "/gists/gone" {
t.Errorf("endpoint = %q, want /gists/gone", apiErr.Endpoint)
}
})
}
func TestPATClient_ListPRReviews(t *testing.T) {
c, requests := newRecordingPATServer(t, map[string]string{
"/repos/acme/widget/pulls/42/reviews": `[
{"id":1,"state":"APPROVED","body":"lgtm","submitted_at":"2026-01-05T10:00:00Z",
"user":{"login":"alice","avatar_url":"https://avatars/alice"}},
{"id":2,"state":"CHANGES_REQUESTED","body":"nope","submitted_at":"2026-01-06T10:00:00Z",
"user":{"login":"bob","avatar_url":""}}
]`,
})
reviews, err := c.ListPRReviews(context.Background(), "acme", "widget", 42)
if err != nil {
t.Fatalf("ListPRReviews: %v", err)
}
if len(reviews) != 2 {
t.Fatalf("reviews = %d, want 2", len(reviews))
}
want := PRReview{
ID: 1, Author: "alice", AuthorAvatar: "https://avatars/alice",
State: "APPROVED", Body: "lgtm",
CreatedAt: time.Date(2026, 1, 5, 10, 0, 0, 0, time.UTC),
}
if reviews[0] != want {
t.Errorf("reviews[0] = %#v, want %#v", reviews[0], want)
}
if reviews[1].ID != 2 || reviews[1].Author != "bob" || reviews[1].State != "CHANGES_REQUESTED" {
t.Errorf("reviews[1] = %#v", reviews[1])
}
if (*requests)[0].Path != "/repos/acme/widget/pulls/42/reviews" {
t.Errorf("path = %q", (*requests)[0].Path)
}
}
func TestPATClient_ListPRComments_MergesReviewAndIssueCommentsInTimeOrder(t *testing.T) {
c, requests := newRecordingPATServer(t, map[string]string{
"/repos/acme/widget/pulls/42/comments": `[
{"id":20,"path":"main.go","line":7,"side":"RIGHT","body":"inline note",
"created_at":"2026-01-05T12:00:00Z","updated_at":"2026-01-05T12:30:00Z",
"in_reply_to_id":19,"user":{"login":"alice","avatar_url":"https://a","type":"User"}}
]`,
"/repos/acme/widget/issues/42/comments": `[
{"id":10,"body":"conversation note","created_at":"2026-01-05T09:00:00Z",
"updated_at":"2026-01-05T09:00:00Z","user":{"login":"dependabot","avatar_url":"https://d","type":"Bot"}}
]`,
})
comments, err := c.ListPRComments(context.Background(), "acme", "widget", 42, nil)
if err != nil {
t.Fatalf("ListPRComments: %v", err)
}
if len(comments) != 2 {
t.Fatalf("comments = %d, want 2", len(comments))
}
// The issue comment is older, so it must sort first.
first, second := comments[0], comments[1]
if first.ID != 10 || first.CommentType != commentTypeIssue {
t.Errorf("comments[0] = %#v, want the older issue comment", first)
}
if !first.AuthorIsBot {
t.Error("a Bot-typed user must set AuthorIsBot")
}
if second.ID != 20 || second.CommentType != commentTypeReview {
t.Errorf("comments[1] = %#v, want the review comment", second)
}
if second.Path != "main.go" || second.Line != 7 || second.Side != "RIGHT" {
t.Errorf("review comment location = %#v", second)
}
if second.InReplyTo == nil || *second.InReplyTo != 19 {
t.Errorf("in_reply_to = %v, want 19", second.InReplyTo)
}
if second.AuthorIsBot {
t.Error("a User-typed author must not set AuthorIsBot")
}
for _, req := range *requests {
if !strings.Contains(req.Query, "per_page=100") {
t.Errorf("%s query = %q, want per_page=100", req.Path, req.Query)
}
if strings.Contains(req.Query, "since=") {
t.Errorf("%s query = %q, want no since when the caller passed nil", req.Path, req.Query)
}
}
}
func TestPATClient_ListPRComments_AppendsSinceToBothEndpoints(t *testing.T) {
c, requests := newRecordingPATServer(t, map[string]string{
"/repos/acme/widget/pulls/42/comments": `[]`,
"/repos/acme/widget/issues/42/comments": `[]`,
})
since := time.Date(2026, 1, 2, 3, 4, 5, 0, time.UTC)
if _, err := c.ListPRComments(context.Background(), "acme", "widget", 42, &since); err != nil {
t.Fatalf("ListPRComments: %v", err)
}
if len(*requests) != 2 {
t.Fatalf("requests = %d, want 2", len(*requests))
}
for _, req := range *requests {
if got := parseQueryValues(t, req.Query).Get("since"); got != "2026-01-02T03:04:05Z" {
t.Errorf("%s since = %q, want the RFC3339 timestamp", req.Path, got)
}
}
}
// The issue-comment leg runs after the review leg; its failure must abort the
// whole call rather than silently returning a half-populated list.
func TestPATClient_ListPRComments_IssueLegFailureAborts(t *testing.T) {
c, _ := newRecordingPATServer(t, map[string]string{
"/repos/acme/widget/pulls/42/comments": `[]`,
})
comments, err := c.ListPRComments(context.Background(), "acme", "widget", 42, nil)
if err == nil {
t.Fatal("expected an error when the issue-comments call fails")
}
if comments != nil {
t.Errorf("comments = %#v, want nil", comments)
}
}
func TestPATClient_ListPRFiles(t *testing.T) {
c, requests := newRecordingPATServer(t, map[string]string{
"/repos/acme/widget/pulls/42/files": `[
{"filename":"main.go","status":"modified","additions":4,"deletions":1,"patch":"@@ -1 +1 @@\n-old\n+new"},
{"filename":"new.go","previous_filename":"old.go","status":"renamed","additions":0,"deletions":0}
]`,
})
files, err := c.ListPRFiles(context.Background(), "acme", "widget", 42)
if err != nil {
t.Fatalf("ListPRFiles: %v", err)
}
if len(files) != 2 {
t.Fatalf("files = %d, want 2", len(files))
}
if files[0].Filename != "main.go" || files[0].Status != "modified" {
t.Errorf("files[0] identity = %#v", files[0])
}
if files[0].Additions != 4 || files[0].Deletions != 1 {
t.Errorf("files[0] stats = (%d, %d), want (4, 1)", files[0].Additions, files[0].Deletions)
}
if !strings.Contains(files[0].Patch, "+new") {
t.Errorf("files[0] patch = %q, want the hunk body preserved", files[0].Patch)
}
if files[1].OldPath != "old.go" || files[1].Status != "renamed" {
t.Errorf("files[1] = %#v, want the rename source preserved", files[1])
}
if !strings.Contains((*requests)[0].Query, "per_page=100") {
t.Errorf("query = %q, want per_page=100", (*requests)[0].Query)
}
}
func TestPATClient_ListPRFiles_Error(t *testing.T) {
c, _ := newRecordingPATServer(t, nil)
files, err := c.ListPRFiles(context.Background(), "acme", "widget", 42)
if files != nil {
t.Errorf("files = %#v, want nil", files)
}
if err == nil || !strings.Contains(err.Error(), "list PR files") {
t.Fatalf("err = %v, want a wrapped list-PR-files error", err)
}
}
func TestPATClient_ListPRCommits(t *testing.T) {
c, requests := newRecordingPATServer(t, map[string]string{
"/repos/acme/widget/pulls/42/commits": `[
{"sha":"aaa","commit":{"message":"feat: add thing\n\nlong body","author":{"date":"2026-01-07T10:00:00Z"}},
"author":{"login":"alice"}},
{"sha":"bbb","commit":{"message":"fix: typo","author":{"date":"2026-01-08T10:00:00Z"}}}
]`,
})
commits, err := c.ListPRCommits(context.Background(), "acme", "widget", 42)
if err != nil {
t.Fatalf("ListPRCommits: %v", err)
}
if len(commits) != 2 {
t.Fatalf("commits = %d, want 2", len(commits))
}
if commits[0].SHA != "aaa" || commits[0].AuthorLogin != "alice" {
t.Errorf("commits[0] identity = %#v", commits[0])
}
if commits[0].Message != "feat: add thing" {
t.Errorf("commits[0] message = %q, want only the subject line", commits[0].Message)
}
if commits[0].AuthorDate != "2026-01-07T10:00:00Z" {
t.Errorf("commits[0] author date = %q", commits[0].AuthorDate)
}
if commits[0].StatsAvailable {
t.Error("the PR-commits list carries no per-commit stats; StatsAvailable must stay false")
}
// A commit with no matched GitHub account decodes with an empty login.
if commits[1].AuthorLogin != "" || commits[1].Message != "fix: typo" {
t.Errorf("commits[1] = %#v", commits[1])
}
if !strings.Contains((*requests)[0].Query, "per_page=100") {
t.Errorf("query = %q, want per_page=100", (*requests)[0].Query)
}
}
func TestPATClient_ListPRCommits_Error(t *testing.T) {
c, _ := newRecordingPATServer(t, nil)
if _, err := c.ListPRCommits(context.Background(), "acme", "widget", 42); err == nil ||
!strings.Contains(err.Error(), "list PR commits") {
t.Fatalf("err = %v, want a wrapped list-PR-commits error", err)
}
}
func TestPATClient_ListRepoBranches_FollowsLinkHeaderPages(t *testing.T) {
c, requests := newLinkPaginatedPATServer(t, "/repos/acme/widget/branches", []string{
`[{"name":"main"},{"name":"develop"}]`,
`[{"name":"release/1.0"}]`,
})
branches, err := c.ListRepoBranches(context.Background(), "acme", "widget")
if err != nil {
t.Fatalf("ListRepoBranches: %v", err)
}
want := []string{"main", "develop", "release/1.0"}
if len(branches) != len(want) {
t.Fatalf("branches = %#v, want %v", branches, want)
}
for i, name := range want {
if branches[i].Name != name {
t.Errorf("branches[%d] = %q, want %q", i, branches[i].Name, name)
}
}
if len(*requests) != 2 {
t.Fatalf("requests = %d, want 2 pages", len(*requests))
}
if !strings.Contains((*requests)[0].Query, "per_page=100") {
t.Errorf("first query = %q, want per_page=100", (*requests)[0].Query)
}
}
func TestPATClient_ListRepoBranches_Error(t *testing.T) {
c, _ := newRecordingPATServer(t, nil)
branches, err := c.ListRepoBranches(context.Background(), "acme", "widget")
if branches != nil {
t.Errorf("branches = %#v, want nil", branches)
}
if err == nil || !strings.Contains(err.Error(), "list repo branches") {
t.Fatalf("err = %v, want a wrapped list-repo-branches error", err)
}
}
// Missing allow_* fields must read as false: a permission-gated repo response
// that omits them would otherwise let the caller pick a disallowed method and
// take a 405 from the merge endpoint.
func TestPATClient_GetRepoMergeMethods(t *testing.T) {
cases := []struct {
name string
body string
want RepoMergeMethods
}{
{
"all allowed",
`{"allow_merge_commit":true,"allow_squash_merge":true,"allow_rebase_merge":true}`,
RepoMergeMethods{Merge: true, Squash: true, Rebase: true},
},
{
"squash only",
`{"allow_merge_commit":false,"allow_squash_merge":true,"allow_rebase_merge":false}`,
RepoMergeMethods{Squash: true},
},
{
"omitted fields read as disallowed",
`{"full_name":"acme/widget"}`,
RepoMergeMethods{},
},
{
"explicit nulls read as disallowed",
`{"allow_merge_commit":null,"allow_squash_merge":null,"allow_rebase_merge":null}`,
RepoMergeMethods{},
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
c, requests := newRecordingPATServer(t, map[string]string{"/repos/acme/widget": tc.body})
got, err := c.GetRepoMergeMethods(context.Background(), "acme", "widget")
if err != nil {
t.Fatalf("GetRepoMergeMethods: %v", err)
}
if got != tc.want {
t.Errorf("methods = %#v, want %#v", got, tc.want)
}
if (*requests)[0].Path != "/repos/acme/widget" {
t.Errorf("path = %q", (*requests)[0].Path)
}
})
}
}
func TestPATClient_GetRepoMergeMethods_Error(t *testing.T) {
c, _ := newRecordingPATServer(t, nil)
got, err := c.GetRepoMergeMethods(context.Background(), "acme", "widget")
if got != (RepoMergeMethods{}) {
t.Errorf("methods = %#v, want the zero value on error", got)
}
if err == nil || !strings.Contains(err.Error(), "get repo merge methods") {
t.Fatalf("err = %v, want a wrapped merge-methods error", err)
}
}
@@ -75,7 +75,12 @@ func (s *Service) createIssueWatch(ctx context.Context, req *CreateIssueWatchReq
if err := s.store.CreateIssueWatch(ctx, iw); err != nil {
return nil, fmt.Errorf("create issue watch: %w", err)
}
go s.initialIssueCheck(context.Background(), iw)
// Poll in the background off a *copy*: the watch we return is JSON-encoded
// by the caller while the check writes LastPolledAt, and sharing the pointer
// races on that field. The goroutine persists its own timestamp, and the
// returned watch has legitimately not been polled yet.
initial := *iw
go s.initialIssueCheck(context.Background(), &initial)
return iw, nil
}
@@ -86,8 +86,13 @@ func (s *Service) createReviewWatch(
return nil, fmt.Errorf("create review watch: %w", err)
}
// Trigger initial poll in background so the watch starts working immediately
go s.initialReviewCheck(context.Background(), rw)
// Trigger initial poll in background so the watch starts working
// immediately. It runs off a *copy*: the watch we return is JSON-encoded by
// the caller while the check writes LastPolledAt, and sharing the pointer
// races on that field. The goroutine persists its own timestamp, and the
// returned watch has legitimately not been polled yet.
initial := *rw
go s.initialReviewCheck(context.Background(), &initial)
return rw, nil
}
@@ -0,0 +1,99 @@
package github
import (
"context"
"testing"
"time"
)
// Creating a watch kicks off an initial poll in the background, and that poll
// stamps LastPolledAt. The watch handed back to the caller is JSON-encoded by
// the HTTP/WS layer, so the goroutine must work on its own copy — otherwise the
// encoder reads LastPolledAt while the poll writes it (a real data race), and
// the caller sees a "last polled" time for a watch it just created.
//
// Both tests below wait for the goroutine to persist its timestamp, then assert
// the returned struct was left alone. That is deterministic: sharing the
// pointer again makes them fail on every run, not just under -race.
func TestCreateIssueWatch_InitialCheckDoesNotMutateTheReturnedWatch(t *testing.T) {
svc, store := setupWatchServiceTest(t)
ctx := context.Background()
watch, err := svc.CreateIssueWatch(ctx, &CreateIssueWatchRequest{
WorkspaceID: "ws-1",
Repos: []RepoFilter{{Owner: "acme", Name: "widget"}},
Prompt: "fix it",
})
if err != nil {
t.Fatalf("create issue watch: %v", err)
}
waitForIssueWatchPolled(t, store, watch.ID)
if watch.LastPolledAt != nil {
t.Errorf("returned watch has LastPolledAt = %v, want it untouched by the "+
"background check", watch.LastPolledAt)
}
}
func TestCreateReviewWatch_InitialCheckDoesNotMutateTheReturnedWatch(t *testing.T) {
svc, store := setupWatchServiceTest(t)
ctx := context.Background()
watch, err := svc.CreateReviewWatch(ctx, &CreateReviewWatchRequest{
WorkspaceID: "ws-1",
Repos: []RepoFilter{{Owner: "acme", Name: "widget"}},
})
if err != nil {
t.Fatalf("create review watch: %v", err)
}
waitForReviewWatchPolled(t, store, watch.ID)
if watch.LastPolledAt != nil {
t.Errorf("returned watch has LastPolledAt = %v, want it untouched by the "+
"background check", watch.LastPolledAt)
}
}
// waitForIssueWatchPolled blocks until the background check has persisted a
// LastPolledAt for the watch. Real subprocess-free goroutine work, so a short
// polling wait rather than synctest (which cannot advance a real DB write).
func waitForIssueWatchPolled(t *testing.T, store *Store, id string) {
t.Helper()
waitForWatchPolled(t, func() (bool, error) {
stored, err := store.GetIssueWatch(context.Background(), id)
if err != nil || stored == nil {
return false, err
}
return stored.LastPolledAt != nil, nil
})
}
func waitForReviewWatchPolled(t *testing.T, store *Store, id string) {
t.Helper()
waitForWatchPolled(t, func() (bool, error) {
stored, err := store.GetReviewWatch(context.Background(), id)
if err != nil || stored == nil {
return false, err
}
return stored.LastPolledAt != nil, nil
})
}
func waitForWatchPolled(t *testing.T, polled func() (bool, error)) {
t.Helper()
deadline := time.Now().Add(5 * time.Second)
for {
done, err := polled()
if err != nil {
t.Fatalf("read watch: %v", err)
}
if done {
return
}
if time.Now().After(deadline) {
t.Fatal("initial check never recorded LastPolledAt")
}
time.Sleep(5 * time.Millisecond)
}
}