gunk-dev/the-valley

pr_test.go

source672eff5ffaecmain's published tip history
10.6 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 if got, ok := ParseMarker("verdict\n\n" + m.String() + "\n"); !ok || got != m {
101 t.Errorf("round trip = %+v, %v; want %+v", got, ok, m)
102 }
103 if _, ok := ParseMarker("plain review " + CrossReviewMarker); ok {
104 t.Error("unterminated marker must not parse")
105 }
106 if _, ok := ParseMarker("LGTM"); ok {
107 t.Error("body without marker must not parse")
108 }
109}
110
111const fakeSHA = "d139283518cdbd801aa20a97868da29a2417178e"
112
113// 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.
114// 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.
115func fakePR(t *testing.T, reviews []string) string {
116 t.Helper()
117 dir := t.TempDir()
118 write := func(name, content string, mode os.FileMode) {
119 if err := os.WriteFile(filepath.Join(dir, name), []byte(content), mode); err != nil {
120 t.Fatal(err)
121 }
122 }
123 write("reviews.json", reviewsJSON(reviews), 0o644)
124 write("pr.json", `{"title":"Add greeting","body":"Adds New().","head":{"sha":"`+fakeSHA+`"}}`, 0o644)
125 write("diff", gitDiffFixture(t), 0o644)
126 write("gh", `#!/bin/sh
127case "$1 $2" in
128"pr diff") cat "$FAKE_DIR/diff" ;;
129"api repos/o/r/pulls/7") cat "$FAKE_DIR/pr.json" ;;
130"api user") echo operator ;;
131"api repos/o/r/pulls/7/reviews?per_page=100") cat "$FAKE_DIR/reviews.json" ;;
132"api repos/o/r/pulls/7/reviews") cat > "$FAKE_DIR/posted.json"; echo '{"html_url":"https://github.com/o/r/pull/7#pullrequestreview-1"}' ;;
133*) echo "unexpected gh $*" >&2; exit 1 ;;
134esac
135`, 0o755)
136 write("codex", `#!/bin/sh
137out=; sandbox=; isolated=; skipgit=
138while [ $# -gt 0 ]; do
139 case "$1" in
140 --output-last-message) shift; out=$1 ;;
141 --sandbox) shift; sandbox=$1 ;;
142 --ignore-user-config) isolated=yes ;;
143 --skip-git-repo-check) skipgit=yes ;;
144 esac
145 shift
146done
147[ "$sandbox" = read-only ] && [ "$isolated" = yes ] && [ "$skipgit" = yes ] || exit 3
148[ -z "$(ls -A .)" ] || exit 4
149cat > "$FAKE_DIR/prompt"
150if [ -n "$FAKE_CODEX_HOLD" ]; then
151 i=0; while [ ! -e "$FAKE_DIR/release" ] && [ $i -lt 200 ]; do sleep 0.05; i=$((i+1)); done
152fi
153for f in reviews pr; do [ -e "$FAKE_DIR/$f-after.json" ] && cp "$FAKE_DIR/$f-after.json" "$FAKE_DIR/$f.json"; done
154printf '%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"
155`, 0o755)
156 t.Setenv("FAKE_DIR", dir)
157 t.Setenv("PATH", dir+string(os.PathListSeparator)+os.Getenv("PATH"))
158 return dir
159}
160
161func reviewsJSON(bodies []string) string {
162 reviews := []map[string]any{}
163 for _, b := range bodies {
164 login := "operator"
165 if rest, ok := strings.CutPrefix(b, "drive-by:"); ok {
166 login, b = "drive-by", rest
167 }
168 reviews = append(reviews, map[string]any{"body": b, "user": map[string]string{"login": login}})
169 }
170 data, _ := json.Marshal(reviews)
171 return string(data)
172}
173
174func postOpts(t *testing.T) PROptions {
175 return PROptions{Backend: backend.Codex, Post: true, LockDir: t.TempDir()}
176}
177
178func TestRunPRReview(t *testing.T) {
179 other := Marker{Backend: "codex", SHA: "0000000"}.String()
180 tests := []struct {
181 name string
182 reviews []string
183 wantErr error
184 }{
185 {name: "posts one COMMENT review", reviews: []string{"LGTM", other}},
186 {name: "ignores markers copied by other users", reviews: []string{other, "drive-by:" + other, "drive-by:" + Marker{Backend: "codex", SHA: fakeSHA}.String()}},
187 {name: "same backend already reviewed head", reviews: []string{Marker{Backend: "codex", SHA: fakeSHA}.String()}, wantErr: ErrAlreadyReviewed},
188 {name: "round limit", reviews: []string{other, Marker{Backend: "agy", SHA: "1111111"}.String()}, wantErr: ErrMaxRounds},
189 }
190 for _, tt := range tests {
191 t.Run(tt.name, func(t *testing.T) {
192 dir := fakePR(t, tt.reviews)
193 result, err := RunPRReview(context.Background(), "o/r", "7", postOpts(t))
194 if tt.wantErr != nil {
195 if !errors.Is(err, tt.wantErr) {
196 t.Fatalf("err = %v, want %v", err, tt.wantErr)
197 }
198 if _, statErr := os.Stat(filepath.Join(dir, "prompt")); statErr == nil {
199 t.Error("reviewer ran although posting was refused")
200 }
201 return
202 }
203 if err != nil {
204 t.Fatal(err)
205 }
206 if result.Verdict != "Matches intent." || result.ReviewURL == "" {
207 t.Errorf("result = %+v", result)
208 }
209 prompt, _ := os.ReadFile(filepath.Join(dir, "prompt"))
210 for _, want := range []string{"Pull request title: Add greeting", "Adds New().", "+changed 5", `"verdict"`} {
211 if !strings.Contains(string(prompt), want) {
212 t.Errorf("prompt missing %q", want)
213 }
214 }
215 data, err := os.ReadFile(filepath.Join(dir, "posted.json"))
216 if err != nil {
217 t.Fatal(err)
218 }
219 var posted reviewRequest
220 if err := json.Unmarshal(data, &posted); err != nil {
221 t.Fatal(err)
222 }
223 if posted.Event != "COMMENT" || posted.CommitID != fakeSHA || len(posted.Comments) != 1 || posted.Comments[0].Line != 5 {
224 t.Errorf("posted = %+v", posted)
225 }
226 if !strings.Contains(posted.Body, "folded one") || !strings.Contains(posted.Body, CrossReviewMarker) {
227 t.Errorf("posted body = %q", posted.Body)
228 }
229 })
230 }
231}
232
233// State changes while the model runs: the pre-post re-check must refuse, keeping the findings.
234func TestRunPRReviewRechecksBeforePost(t *testing.T) {
235 for name, tt := range map[string]struct {
236 file, content string
237 wantErr error
238 }{
239 "another session posted for this head": {"reviews-after.json", reviewsJSON([]string{Marker{Backend: "codex", SHA: fakeSHA}.String()}), ErrAlreadyReviewed},
240 "head moved": {"pr-after.json", `{"title":"Add greeting","head":{"sha":"feedface"}}`, ErrHeadMoved},
241 } {
242 t.Run(name, func(t *testing.T) {
243 dir := fakePR(t, nil)
244 if err := os.WriteFile(filepath.Join(dir, tt.file), []byte(tt.content), 0o644); err != nil {
245 t.Fatal(err)
246 }
247 result, err := RunPRReview(context.Background(), "o/r", "7", postOpts(t))
248 if !errors.Is(err, tt.wantErr) {
249 t.Fatalf("err = %v, want %v", err, tt.wantErr)
250 }
251 if result == nil || result.Verdict != "Matches intent." {
252 t.Errorf("refused post must still return the review: %+v", result)
253 }
254 if _, err := os.Stat(filepath.Join(dir, "posted.json")); err == nil {
255 t.Error("posted despite the re-check failing")
256 }
257 })
258 }
259}
260
261func TestRunPRReviewLock(t *testing.T) {
262 dir := fakePR(t, nil)
263 t.Setenv("FAKE_CODEX_HOLD", "1")
264 opts := postOpts(t)
265
266 first := make(chan error, 1)
267 go func() {
268 _, err := RunPRReview(context.Background(), "o/r", "7", opts)
269 first <- err
270 }()
271 for deadline := time.Now().Add(10 * time.Second); ; time.Sleep(20 * time.Millisecond) { // first run is inside the model call
272 if _, err := os.Stat(filepath.Join(dir, "prompt")); err == nil {
273 break
274 }
275 if time.Now().After(deadline) {
276 t.Fatal("first review never reached the model")
277 }
278 }
279
280 second := make(chan error, 1)
281 go func() {
282 _, err := RunPRReview(context.Background(), "o/r", "7", opts)
283 second <- err
284 }()
285 if err := <-second; !errors.Is(err, ErrLocked) {
286 t.Fatalf("concurrent run: err = %v, want ErrLocked", err)
287 }
288
289 if err := os.WriteFile(filepath.Join(dir, "release"), nil, 0o644); err != nil {
290 t.Fatal(err)
291 }
292 if err := <-first; err != nil {
293 t.Fatalf("first run: %v", err)
294 }
295 if _, err := os.Stat(filepath.Join(dir, "posted.json")); err != nil {
296 t.Error("lock holder did not post")
297 }
298 unlock, err := lockPR(opts.LockDir, "o/r", "7")
299 if err != nil {
300 t.Fatalf("lock not released: %v", err)
301 }
302 unlock()
303}