gunk-dev/the-valley

dashboard_github_test.go

source60ad80d5a5a5main's published tip history
5.9 KiB
1package cmd
2
3import (
4 "fmt"
5 "os"
6 "path/filepath"
7 "strconv"
8 "strings"
9 "testing"
10 "time"
11
12 tea "github.com/charmbracelet/bubbletea"
13 "github.com/charmbracelet/x/ansi"
14 "the-valley/flow/internal/config"
15 gh "the-valley/flow/internal/github"
16 "the-valley/flow/internal/run"
17)
18
19// fakeGHAPI puts a `gh` on PATH that logs each call, one line per call, and
20// answers `gh api` from files in its directory: graphql.json for GraphQL
21// (or the raw response in ratelimit, when present) and a zero behind_by for
22// compares.
23func fakeGHAPI(t *testing.T) string {
24 t.Helper()
25 dir := t.TempDir()
26 script := `#!/bin/sh
27d=$(dirname "$0")
28line=$(printf '%s' "$*" | tr '\n' ' ')
29printf '%s\n' "$line" >> "$d/calls.log"
30case "$line" in
31*graphql*)
32 if [ -f "$d/ratelimit" ]; then cat "$d/ratelimit"; exit 1; fi
33 printf 'HTTP/2.0 200 OK\r\n\r\n'; cat "$d/graphql.json" ;;
34*compare*) printf 'HTTP/2.0 200 OK\r\n\r\n{"behind_by": 0}' ;;
35*) echo "unexpected gh call: $line" >&2; exit 1 ;;
36esac
37`
38 if err := os.WriteFile(filepath.Join(dir, "gh"), []byte(script), 0o755); err != nil {
39 t.Fatal(err)
40 }
41 t.Setenv("PATH", dir+string(os.PathListSeparator)+os.Getenv("PATH"))
42 t.Setenv("HOME", t.TempDir())
43 return dir
44}
45
46// graphQLPRs is a PRSnapshots response for PRs 1..n of one repository; the
47// PRs in merged read MERGED, the others open with passing CI.
48func graphQLPRs(n int, merged ...int) string {
49 var prs []string
50 for i := 1; i <= n; i++ {
51 state := "OPEN"
52 for _, m := range merged {
53 if m == i {
54 state = "MERGED"
55 }
56 }
57 prs = append(prs, fmt.Sprintf(`"pr%d": {"state": %q, "isDraft": false, "mergeable": "MERGEABLE", "reviewDecision": null,
58"headRefOid": "head%d", "baseRef": {"target": {"oid": "base"}}, "labels": {"nodes": []},
59"commits": {"nodes": [{"commit": {"committedDate": "2026-11-01T00:00:00Z", "statusCheckRollup": {"state": "SUCCESS"}}}]},
60"author": {"__typename": "User", "login": "op"}, "reviews": {"nodes": []}, "comments": {"nodes": []}}`, i, state, i))
61 }
62 return `{"data": {"viewer": {"login": "op"}, "repository": {` + strings.Join(prs, ",") + `}}}`
63}
64
65// TestGHPollingCallBudget: the dashboard's GitHub polling costs one GraphQL
66// call per repository however many PRs it tracks, compares a PR's head with
67// its base only when they move, stops asking about a merged PR, and stops
68// polling while GitHub rate-limits it.
69func TestGHPollingCallBudget(t *testing.T) {
70 dir := fakeGHAPI(t)
71 write := func(name, content string) {
72 t.Helper()
73 if err := os.WriteFile(filepath.Join(dir, name), []byte(content), 0o644); err != nil {
74 t.Fatal(err)
75 }
76 }
77 calls := func() []string {
78 t.Helper()
79 data, _ := os.ReadFile(filepath.Join(dir, "calls.log"))
80 os.Remove(filepath.Join(dir, "calls.log"))
81 return strings.Fields(strings.ReplaceAll(strings.TrimSpace(string(data)), " ", "_"))
82 }
83 count := func(lines []string, what string) int {
84 n := 0
85 for _, l := range lines {
86 if strings.Contains(l, what) {
87 n++
88 }
89 }
90 return n
91 }
92 url := func(n int) string { return "https://github.com/acme/widget/pull/" + strconv.Itoa(n) }
93 tracked := func(n int) []*run.State {
94 var states []*run.State
95 for i := 1; i <= n; i++ {
96 u := url(i)
97 states = append(states, &run.State{ID: fmt.Sprintf("20261106-0000-%04d", i), Type: "launch", Prompt: fmt.Sprintf("pr %d", i),
98 PRURL: &u, PR: strPtr(strconv.Itoa(i)), CostUSD: float64Ptr(1), CreatedAt: time.Now().Format(time.RFC3339)})
99 }
100 return states
101 }
102
103 cfg := config.Config{TrustedReviewers: []string{"gemini-code-assist[bot]"}}
104 m := newDashboardModel(run.NewGitDirStore(t.TempDir()), cfg, gh.NewGHCLIClient(""))
105 m.tmuxDeps = testDashboardTmuxDeps()
106 poll := func() []string {
107 t.Helper()
108 m = send(m, m.fetchGHStatusCmd(m.states)())
109 return calls()
110 }
111
112 // Three open PRs and a merged one: one query, and a compare for each
113 // open PR, whose head and base are new.
114 m.states = tracked(4)
115 write("graphql.json", graphQLPRs(4, 4))
116 first := poll()
117 if g, c := count(first, "graphql"), count(first, "compare"); g != 1 || c != 3 {
118 t.Fatalf("first poll: %d GraphQL calls and %d compares, want 1 and 3:\n%s", g, c, strings.Join(first, "\n"))
119 }
120 if st := m.ghStatus[url(4)]; st == nil || st.State != "MERGED" {
121 t.Fatalf("PR 4 status = %+v, want MERGED", st)
122 }
123
124 // Nothing moved: one query, no compares, and the merged PR isn't in it.
125 steady := poll()
126 if len(steady) != 1 || count(steady, "graphql") != 1 {
127 t.Fatalf("steady poll of 3 open PRs: calls %v, want one GraphQL query", steady)
128 }
129 if strings.Contains(steady[0], "pr4:") {
130 t.Errorf("the merged PR is still asked about: %s", steady[0])
131 }
132 if st := m.ghStatus[url(4)]; st == nil || st.State != "MERGED" {
133 t.Errorf("PR 4 status after it left the query = %+v, want MERGED", st)
134 }
135
136 // Twice the open PRs cost the same once their heads are compared.
137 m.states = tracked(7)
138 write("graphql.json", graphQLPRs(7, 4))
139 poll()
140 if steady := poll(); len(steady) != 1 {
141 t.Errorf("steady poll of 6 open PRs: calls %v, want one GraphQL query", steady)
142 }
143
144 // A rate limit pauses polling until GitHub's reset, says so in the
145 // header, and leaves the statuses as they were.
146 reset := time.Now().Add(40 * time.Minute)
147 write("ratelimit", fmt.Sprintf("HTTP/2.0 200 OK\r\nX-Ratelimit-Remaining: 0\r\nX-Ratelimit-Reset: %d\r\n\r\n"+
148 `{"data": null, "errors": [{"type": "RATE_LIMITED", "message": "API rate limit exceeded"}]}`, reset.Unix()))
149 if limited := poll(); len(limited) != 1 {
150 t.Fatalf("rate-limited poll: calls %v, want the one refused query", limited)
151 }
152 if paused := poll(); len(paused) != 0 {
153 t.Errorf("polls while rate-limited: calls %v, want none", paused)
154 }
155 m = send(m, tea.WindowSizeMsg{Width: 200, Height: 30})
156 want := "GitHub rate-limited until " + time.Unix(reset.Unix(), 0).Format("15:04")
157 if view := ansi.Strip(m.View()); !strings.Contains(view, want) {
158 t.Errorf("header doesn't say %q:\n%s", want, view)
159 }
160 if st := m.ghStatus[url(1)]; st == nil || st.State != "OPEN" || st.CI != "passing" {
161 t.Errorf("PR 1 status after the rate limit = %+v, want its last reading", st)
162 }
163}