gunk-dev/the-valley

review_test.go

source30e24c82839bmain's published tip history
7.4 KiB
1package main
2
3import (
4 "bytes"
5 "os"
6 "os/exec"
7 "os/signal"
8 "path/filepath"
9 "runtime"
10 "strings"
11 "sync"
12 "syscall"
13 "testing"
14)
15
16// A review's outcome on real repositories: a plain branch, topic, on a
17// scratch origin, reviewed off a terminal with its answers read from a
18// file or a pipe. [a]pprove's attempt is given at its Go boundary, since
19// attempting needs the attest helper.
20type reviewRepo struct {
21 t *testing.T
22 dir, work, tmp string
23 head string // topic's head
24 stdout *watched
25 stderr bytes.Buffer
26 ended chan stepOutcome // what the step's end path was given
27 endStatus int
28}
29
30func newReviewRepo(t *testing.T) *reviewRepo {
31 dir := t.TempDir()
32 r := &reviewRepo{t: t, dir: dir, work: filepath.Join(dir, "work"), tmp: filepath.Join(dir, "tmp"),
33 stdout: &watched{}, ended: make(chan stepOutcome, 1)}
34 t.Setenv("HOME", dir)
35 t.Setenv("XDG_CONFIG_HOME", filepath.Join(dir, "config"))
36 t.Setenv("XDG_STATE_HOME", filepath.Join(dir, "state"))
37 t.Setenv("GIT_CONFIG_NOSYSTEM", "1")
38 t.Setenv("VALLEY_KNOWN_SIGNERS", "")
39 t.Setenv("VALLEY_INTEGRATOR_SIGNER", "")
40 t.Setenv("TMPDIR", r.tmp)
41 if err := os.Mkdir(r.tmp, 0o755); err != nil {
42 t.Fatal(err)
43 }
44 origin := filepath.Join(dir, "origin.git")
45 for _, args := range [][]string{{"init", "--quiet", "--bare", "--initial-branch=main", origin}, {"clone", "--quiet", origin, r.work}} {
46 if out, err := exec.Command("git", args...).CombinedOutput(); err != nil {
47 t.Fatalf("git %s: %v\n%s", args[0], err, out)
48 }
49 }
50 r.git("config", "user.name", "review-test")
51 r.git("config", "user.email", "review-test@localhost")
52 r.git("checkout", "--quiet", "-b", "main")
53 r.git("commit", "--quiet", "--allow-empty", "-m", "base")
54 r.git("push", "--quiet", "origin", "main")
55 r.git("checkout", "--quiet", "-b", "topic")
56 if err := os.WriteFile(filepath.Join(r.work, "readme.md"), []byte("a readme\n"), 0o644); err != nil {
57 t.Fatal(err)
58 }
59 r.git("add", "readme.md")
60 r.git("commit", "--quiet", "-m", "a readme")
61 r.git("push", "--quiet", "origin", "topic")
62 r.git("checkout", "--quiet", "main")
63 r.head = r.git("rev-parse", "topic")
64 return r
65}
66
67func (r *reviewRepo) git(args ...string) string {
68 r.t.Helper()
69 cmd := exec.Command("git", args...)
70 cmd.Dir = r.work
71 out, err := cmd.CombinedOutput()
72 if err != nil {
73 r.t.Fatalf("git %s: %v\n%s", strings.Join(args, " "), err, out)
74 }
75 return strings.TrimSpace(string(out))
76}
77
78// review is a review of topic, from stdin, with attempt as [a]pprove's
79// attempt, and the test's catch of SIGINT and SIGTERM as the caller's.
80// The step's end path keeps what it was given and leaves the goroutine it
81// was called on, as it would leave the process.
82func (r *reviewRepo) review(stdin *os.File, attempt func(*approval)) *review {
83 g := git{env: gitEnvironment(os.Environ()), stderr: &r.stderr, dir: r.work}
84 interrupts := make(chan os.Signal, 1)
85 signal.Notify(interrupts, os.Interrupt, syscall.SIGTERM)
86 r.t.Cleanup(func() { signal.Stop(interrupts) })
87 rv := newReview(reviewStep{g: g, stdin: stdin, stdout: r.stdout, stderr: &r.stderr,
88 signers: &signerSource{g: g, stderr: &r.stderr}, interrupts: interrupts,
89 end: func(status int, o stepOutcome) {
90 r.endStatus = status
91 r.ended <- o
92 runtime.Goexit()
93 }})
94 rv.attempt = attempt
95 return rv
96}
97
98// answers is a file holding the answers given.
99func (r *reviewRepo) answers(text string) *os.File {
100 r.t.Helper()
101 path := filepath.Join(r.dir, "answers")
102 if err := os.WriteFile(path, []byte(text), 0o644); err != nil {
103 r.t.Fatal(err)
104 }
105 f, err := os.Open(path)
106 if err != nil {
107 r.t.Fatal(err)
108 }
109 r.t.Cleanup(func() { f.Close() })
110 return f
111}
112
113// leftBehind fails the test when the review left anything in its TMPDIR.
114func (r *reviewRepo) leftBehind() {
115 r.t.Helper()
116 if left, _ := os.ReadDir(r.tmp); len(left) > 0 {
117 r.t.Errorf("the review left %s in its TMPDIR", left[0].Name())
118 }
119}
120
121// watched is a review's stdout, which says when it first shows a text.
122type watched struct {
123 mu sync.Mutex
124 b bytes.Buffer
125 want string
126 seen chan struct{}
127}
128
129func (w *watched) Write(p []byte) (int, error) {
130 w.mu.Lock()
131 defer w.mu.Unlock()
132 n, err := w.b.Write(p)
133 if w.seen != nil && strings.Contains(w.b.String(), w.want) {
134 close(w.seen)
135 w.seen = nil
136 }
137 return n, err
138}
139
140// shows is closed once the output shows text.
141func (w *watched) shows(text string) <-chan struct{} {
142 w.mu.Lock()
143 defer w.mu.Unlock()
144 w.want, w.seen = text, make(chan struct{})
145 return w.seen
146}
147
148func (w *watched) String() string {
149 w.mu.Lock()
150 defer w.mu.Unlock()
151 return w.b.String()
152}
153
154// An approval of a plain branch ends the review approved, with the head
155// review showed and bound the attempt to, and no record's ID, handle or
156// version.
157func TestReviewApprovedAtTheHeadShown(t *testing.T) {
158 r := newReviewRepo(t)
159 o := r.review(r.answers("a\n"), func(a *approval) {
160 if a.bound != r.head || a.branch != "topic" || a.id != "" {
161 t.Errorf("the attempt was bound to %q on %q, change %q, not to topic at %s", a.bound, a.branch, a.id, r.head)
162 }
163 a.ended(nil)
164 }).review("topic")
165 if want := (stepOutcome{kind: "approved", head: r.head}); o != want {
166 t.Fatalf("the review ended %+v, not %+v\n%s%s", o, want, r.stdout, r.stderr.String())
167 }
168 r.leftBehind()
169}
170
171// An attempt whose checks failed, and one whose request's state could not
172// be established after the push, are refusals: the prompt comes back, and
173// a review then skipped ends refused, with status 0.
174func TestReviewRefusedAfterTheAttempt(t *testing.T) {
175 for name, fail := range map[string]func(*approval){
176 "checks failed": func(a *approval) { a.failedAt = a.bound; a.ended(errRefused) },
177 "unknown": func(a *approval) { a.ended(errUnknown) },
178 } {
179 t.Run(name, func(t *testing.T) {
180 r := newReviewRepo(t)
181 o := r.review(r.answers("a\ns\n"), fail).review("topic")
182 if o != (stepOutcome{kind: "refused"}) {
183 t.Fatalf("the review ended %+v, not refused\n%s%s", o, r.stdout, r.stderr.String())
184 }
185 if !strings.Contains(r.stdout.String(), "skipped topic; nothing done") {
186 t.Fatalf("the prompt did not come back to be skipped:\n%s", r.stdout)
187 }
188 r.leftBehind()
189 })
190 }
191}
192
193// An attempt a signal interrupts ends the review through the step's end
194// path, interrupted with status 130, once the review has cleaned up.
195func TestReviewInterruptedDuringTheAttempt(t *testing.T) {
196 r := newReviewRepo(t)
197 rv := r.review(r.answers("a\n"), func(a *approval) { a.interrupt() })
198 go rv.review("topic")
199 if o := <-r.ended; o.kind != "interrupted" || r.endStatus != interruptedStatus {
200 t.Fatalf("the review ended %+v with %d, not interrupted with 130", o, r.endStatus)
201 }
202 r.leftBehind()
203}
204
205// SIGTERM at the prompt ends the review through the step's end path,
206// interrupted with status 130, and an input that ends then is not read as
207// another ending.
208func TestReviewInterruptedAtThePrompt(t *testing.T) {
209 r := newReviewRepo(t)
210 in, out, err := os.Pipe()
211 if err != nil {
212 t.Fatal(err)
213 }
214 defer in.Close()
215 prompt := r.stdout.shows("[s]kip")
216 rv := r.review(in, func(*approval) { t.Error("the review attempted an approval") })
217 reviewed := make(chan struct{})
218 go func() {
219 defer close(reviewed)
220 rv.review("topic")
221 }()
222 <-prompt
223 if err := syscall.Kill(os.Getpid(), syscall.SIGTERM); err != nil {
224 t.Fatal(err)
225 }
226 if o := <-r.ended; o.kind != "interrupted" || r.endStatus != interruptedStatus {
227 t.Fatalf("the review ended %+v with %d, not interrupted with 130", o, r.endStatus)
228 }
229 out.Close()
230 <-reviewed
231 r.leftBehind()
232}