gunk-dev/the-valley

pr_test.go

sourceb8e46aa6aaccmain's published tip history
11.9 KiB
1package review
2
3import (
4 "context"
5 "encoding/json"
6 "errors"
7 "fmt"
8 "os"
9 "os/exec"
10 "path/filepath"
11 "strings"
12 "testing"
13 "time"
14
15 "the-valley/flow/internal/backend"
16)
17
18// gitDiffFixture returns a real `git diff`: app.go (40 lines) edited at lines 5 and 35, new.go added, old.go deleted.
19func gitDiffFixture(t *testing.T) string {
20 t.Helper()
21 dir := t.TempDir()
22 git := func(args ...string) string {
23 cmd := exec.Command("git", append([]string{"-c", "user.name=t", "-c", "user.email=t@t", "-c", "commit.gpgsign=false"}, args...)...)
24 cmd.Dir = dir
25 out, err := cmd.CombinedOutput()
26 if err != nil {
27 t.Fatalf("git %v: %v\n%s", args, err, out)
28 }
29 return string(out)
30 }
31 write := func(name, content string) {
32 if err := os.WriteFile(filepath.Join(dir, name), []byte(content), 0o644); err != nil {
33 t.Fatal(err)
34 }
35 }
36 var lines []string
37 for i := 1; i <= 40; i++ {
38 lines = append(lines, fmt.Sprintf("line %d", i))
39 }
40 git("init", "-q")
41 write("app.go", strings.Join(lines, "\n")+"\n")
42 write("old.go", "package old\n")
43 git("add", "-A")
44 git("commit", "-q", "-m", "base")
45
46 lines[4], lines[34] = "changed 5", "changed 35"
47 write("app.go", strings.Join(lines, "\n")+"\n")
48 write("new.go", "package app\n\nfunc New() {}\n")
49 if err := os.Remove(filepath.Join(dir, "old.go")); err != nil {
50 t.Fatal(err)
51 }
52 git("add", "-A")
53 return git("diff", "--cached")
54}
55
56func TestBuildPRReviewInlinesOnlyDiffLines(t *testing.T) {
57 result := &ReviewResult{
58 Verdict: "Does what it says.",
59 Summary: "six findings",
60 Findings: []Finding{
61 {Severity: "high", File: "app.go", Line: 5, Description: "added line"},
62 {Severity: "low", File: "app.go", Line: 8, Description: "context line in hunk"},
63 {Severity: "medium", File: "app.go", Line: 20, Description: "outside every hunk"},
64 {Severity: "low", File: "./new.go", Line: 3, Description: "new file"},
65 {Severity: "low", File: "old.go", Line: 1, Description: "deleted file"},
66 {Severity: "low", Description: "general concern"},
67 },
68 }
69 m := Marker{Backend: "codex", SHA: "abc123"}
70 req := buildPRReview(result, DiffLines(gitDiffFixture(t)), m)
71
72 if req.Event != "COMMENT" || req.CommitID != "abc123" {
73 t.Errorf("event/commit = %q/%q, want COMMENT/abc123", req.Event, req.CommitID)
74 }
75 var inline []string
76 for _, c := range req.Comments {
77 if c.Side != "RIGHT" {
78 t.Errorf("comment side = %q, want RIGHT", c.Side)
79 }
80 inline = append(inline, fmt.Sprintf("%s:%d", c.Path, c.Line))
81 }
82 if got, want := strings.Join(inline, " "), "app.go:5 app.go:8 new.go:3"; got != want {
83 t.Errorf("inline comments = %s, want %s", got, want)
84 }
85 for _, want := range []string{"outside every hunk", "`app.go:20`", "deleted file", "general concern", "Does what it says.", "not an approval"} {
86 if !strings.Contains(req.Body, want) {
87 t.Errorf("body missing %q:\n%s", want, req.Body)
88 }
89 }
90 if strings.Contains(req.Body, "added line") {
91 t.Error("inlined finding must not be repeated in the body")
92 }
93 if got, ok := ParseMarker(req.Body); !ok || got != m {
94 t.Errorf("ParseMarker(body) = %+v, %v; want %+v", got, ok, m)
95 }
96}
97
98func TestParseMarker(t *testing.T) {
99 m := Marker{Backend: "agy", Model: "gemini-3-pro", SHA: "d139283"}
100 flowMarker := fmt.Sprintf("%s backend=%s model=%s sha=%s -->", FlowCrossReviewMarker, m.Backend, m.Model, m.SHA)
101
102 if got, ok := ParseMarker("verdict\n\n" + m.String() + "\n"); !ok || got != m {
103 t.Errorf("legacy round trip = %+v, %v; want %+v", got, ok, m)
104 }
105 if got, ok := ParseMarker("verdict\n\n" + flowMarker + "\n"); !ok || got != m {
106 t.Errorf("new round trip = %+v, %v; want %+v", got, ok, m)
107 }
108 if got, ok := ParseMarker(m.String() + "\n" + flowMarker); !ok || got != m {
109 t.Errorf("both markers = %+v, %v; want %+v", got, ok, m)
110 }
111 if !HasCrossReviewMarker(m.String()) || !HasCrossReviewMarker(flowMarker) || HasCrossReviewMarker("LGTM") {
112 t.Error("HasCrossReviewMarker must accept both spellings and reject plain text")
113 }
114 if _, ok := ParseMarker("plain review " + CrossReviewMarker); ok {
115 t.Error("unterminated legacy marker must not parse")
116 }
117 if _, ok := ParseMarker("plain review " + FlowCrossReviewMarker); ok {
118 t.Error("unterminated new marker must not parse")
119 }
120 if _, ok := ParseMarker("LGTM"); ok {
121 t.Error("body without marker must not parse")
122 }
123}
124
125const fakeSHA = "d139283518cdbd801aa20a97868da29a2417178e"
126
127// fakePR installs a fake gh serving PR o/r#7 (recording the posted review) and a fake codex that checks it runs read-only in an empty dir.
128// Review bodies prefixed "drive-by:" come from another login. FAKE_CODEX_HOLD makes codex wait for $FAKE_DIR/release; $FAKE_DIR/{reviews,pr}-after.json, if present, replace the served JSON while codex runs.
129func fakePR(t *testing.T, reviews []string) string {
130 t.Helper()
131 dir := t.TempDir()
132 write := func(name, content string, mode os.FileMode) {
133 if err := os.WriteFile(filepath.Join(dir, name), []byte(content), mode); err != nil {
134 t.Fatal(err)
135 }
136 }
137 write("reviews.json", reviewsJSON(reviews), 0o644)
138 write("pr.json", `{"title":"Add greeting","body":"Adds New().","head":{"sha":"`+fakeSHA+`"}}`, 0o644)
139 write("diff", gitDiffFixture(t), 0o644)
140 write("gh", `#!/bin/sh
141case "$1 $2" in
142"pr diff") cat "$FAKE_DIR/diff" ;;
143"api repos/o/r/pulls/7") cat "$FAKE_DIR/pr.json" ;;
144"api user") echo operator ;;
145"api repos/o/r/pulls/7/reviews?per_page=100") cat "$FAKE_DIR/reviews.json" ;;
146"api repos/o/r/pulls/7/reviews") cat > "$FAKE_DIR/posted.json"; echo '{"html_url":"https://github.com/o/r/pull/7#pullrequestreview-1"}' ;;
147*) echo "unexpected gh $*" >&2; exit 1 ;;
148esac
149`, 0o755)
150 write("codex", `#!/bin/sh
151out=; sandbox=; isolated=; skipgit=
152while [ $# -gt 0 ]; do
153 case "$1" in
154 --output-last-message) shift; out=$1 ;;
155 --sandbox) shift; sandbox=$1 ;;
156 --ignore-user-config) isolated=yes ;;
157 --skip-git-repo-check) skipgit=yes ;;
158 esac
159 shift
160done
161[ "$sandbox" = read-only ] && [ "$isolated" = yes ] && [ "$skipgit" = yes ] || exit 3
162[ -z "$(ls -A .)" ] || exit 4
163cat > "$FAKE_DIR/prompt"
164if [ -n "$FAKE_CODEX_HOLD" ]; then
165 i=0; while [ ! -e "$FAKE_DIR/release" ] && [ $i -lt 200 ]; do sleep 0.05; i=$((i+1)); done
166fi
167for f in reviews pr; do [ -e "$FAKE_DIR/$f-after.json" ] && cp "$FAKE_DIR/$f-after.json" "$FAKE_DIR/$f.json"; done
168printf '%s' '{"verdict":"Matches intent.","findings":[{"severity":"high","file":"app.go","line":5,"description":"inline one"},{"severity":"low","file":"app.go","line":20,"description":"folded one"}],"summary":"two issues"}' > "$out"
169`, 0o755)
170 t.Setenv("FAKE_DIR", dir)
171 t.Setenv("PATH", dir+string(os.PathListSeparator)+os.Getenv("PATH"))
172 return dir
173}
174
175func reviewsJSON(bodies []string) string {
176 reviews := []map[string]any{}
177 for _, b := range bodies {
178 login := "operator"
179 if rest, ok := strings.CutPrefix(b, "drive-by:"); ok {
180 login, b = "drive-by", rest
181 }
182 reviews = append(reviews, map[string]any{"body": b, "user": map[string]string{"login": login}})
183 }
184 data, _ := json.Marshal(reviews)
185 return string(data)
186}
187
188func postOpts(t *testing.T) PROptions {
189 return PROptions{Backend: backend.Codex, Post: true, LockDir: t.TempDir()}
190}
191
192func TestRunPRReview(t *testing.T) {
193 other := Marker{Backend: "codex", SHA: "0000000"}.String()
194 flowOther := fmt.Sprintf("%s backend=codex model= sha=0000000 -->", FlowCrossReviewMarker)
195 flowSameHead := fmt.Sprintf("%s backend=codex model= sha=%s -->", FlowCrossReviewMarker, fakeSHA)
196 tests := []struct {
197 name string
198 reviews []string
199 wantErr error
200 }{
201 {name: "posts one COMMENT review", reviews: []string{"LGTM", other}},
202 {name: "review carrying both markers counts once", reviews: []string{other + "\n" + flowOther}},
203 {name: "ignores markers copied by other users", reviews: []string{other, "drive-by:" + other, "drive-by:" + Marker{Backend: "codex", SHA: fakeSHA}.String(), "drive-by:" + flowSameHead}},
204 {name: "same backend already reviewed head", reviews: []string{Marker{Backend: "codex", SHA: fakeSHA}.String()}, wantErr: ErrAlreadyReviewed},
205 {name: "same backend already reviewed head (flow marker)", reviews: []string{flowSameHead}, wantErr: ErrAlreadyReviewed},
206 {name: "round limit", reviews: []string{other, Marker{Backend: "agy", SHA: "1111111"}.String()}, wantErr: ErrMaxRounds},
207 {name: "round limit across both marker spellings", reviews: []string{other, fmt.Sprintf("%s backend=agy model= sha=1111111 -->", FlowCrossReviewMarker)}, wantErr: ErrMaxRounds},
208 }
209 for _, tt := range tests {
210 t.Run(tt.name, func(t *testing.T) {
211 dir := fakePR(t, tt.reviews)
212 result, err := RunPRReview(context.Background(), "o/r", "7", postOpts(t))
213 if tt.wantErr != nil {
214 if !errors.Is(err, tt.wantErr) {
215 t.Fatalf("err = %v, want %v", err, tt.wantErr)
216 }
217 if _, statErr := os.Stat(filepath.Join(dir, "prompt")); statErr == nil {
218 t.Error("reviewer ran although posting was refused")
219 }
220 return
221 }
222 if err != nil {
223 t.Fatal(err)
224 }
225 if result.Verdict != "Matches intent." || result.ReviewURL == "" {
226 t.Errorf("result = %+v", result)
227 }
228 prompt, _ := os.ReadFile(filepath.Join(dir, "prompt"))
229 for _, want := range []string{"Pull request title: Add greeting", "Adds New().", "+changed 5", `"verdict"`} {
230 if !strings.Contains(string(prompt), want) {
231 t.Errorf("prompt missing %q", want)
232 }
233 }
234 data, err := os.ReadFile(filepath.Join(dir, "posted.json"))
235 if err != nil {
236 t.Fatal(err)
237 }
238 var posted reviewRequest
239 if err := json.Unmarshal(data, &posted); err != nil {
240 t.Fatal(err)
241 }
242 if posted.Event != "COMMENT" || posted.CommitID != fakeSHA || len(posted.Comments) != 1 || posted.Comments[0].Line != 5 {
243 t.Errorf("posted = %+v", posted)
244 }
245 if !strings.Contains(posted.Body, "folded one") || !strings.Contains(posted.Body, CrossReviewMarker) {
246 t.Errorf("posted body = %q", posted.Body)
247 }
248 })
249 }
250}
251
252// State changes while the model runs: the pre-post re-check must refuse, keeping the findings.
253func TestRunPRReviewRechecksBeforePost(t *testing.T) {
254 for name, tt := range map[string]struct {
255 file, content string
256 wantErr error
257 }{
258 "another session posted for this head": {"reviews-after.json", reviewsJSON([]string{Marker{Backend: "codex", SHA: fakeSHA}.String()}), ErrAlreadyReviewed},
259 "head moved": {"pr-after.json", `{"title":"Add greeting","head":{"sha":"feedface"}}`, ErrHeadMoved},
260 } {
261 t.Run(name, func(t *testing.T) {
262 dir := fakePR(t, nil)
263 if err := os.WriteFile(filepath.Join(dir, tt.file), []byte(tt.content), 0o644); err != nil {
264 t.Fatal(err)
265 }
266 result, err := RunPRReview(context.Background(), "o/r", "7", postOpts(t))
267 if !errors.Is(err, tt.wantErr) {
268 t.Fatalf("err = %v, want %v", err, tt.wantErr)
269 }
270 if result == nil || result.Verdict != "Matches intent." {
271 t.Errorf("refused post must still return the review: %+v", result)
272 }
273 if _, err := os.Stat(filepath.Join(dir, "posted.json")); err == nil {
274 t.Error("posted despite the re-check failing")
275 }
276 })
277 }
278}
279
280func TestRunPRReviewLock(t *testing.T) {
281 dir := fakePR(t, nil)
282 t.Setenv("FAKE_CODEX_HOLD", "1")
283 opts := postOpts(t)
284
285 first := make(chan error, 1)
286 go func() {
287 _, err := RunPRReview(context.Background(), "o/r", "7", opts)
288 first <- err
289 }()
290 for deadline := time.Now().Add(10 * time.Second); ; time.Sleep(20 * time.Millisecond) { // first run is inside the model call
291 if _, err := os.Stat(filepath.Join(dir, "prompt")); err == nil {
292 break
293 }
294 if time.Now().After(deadline) {
295 t.Fatal("first review never reached the model")
296 }
297 }
298
299 second := make(chan error, 1)
300 go func() {
301 _, err := RunPRReview(context.Background(), "o/r", "7", opts)
302 second <- err
303 }()
304 if err := <-second; !errors.Is(err, ErrLocked) {
305 t.Fatalf("concurrent run: err = %v, want ErrLocked", err)
306 }
307
308 if err := os.WriteFile(filepath.Join(dir, "release"), nil, 0o644); err != nil {
309 t.Fatal(err)
310 }
311 if err := <-first; err != nil {
312 t.Fatalf("first run: %v", err)
313 }
314 if _, err := os.Stat(filepath.Join(dir, "posted.json")); err != nil {
315 t.Error("lock holder did not post")
316 }
317 unlock, err := lockPR(opts.LockDir, "o/r", "7")
318 if err != nil {
319 t.Fatalf("lock not released: %v", err)
320 }
321 unlock()
322}