gunk-dev/the-valley

pending_test.go

source6bf8ca46b311main's published tip history
14.2 KiB
1package main
2
3import (
4 "bytes"
5 "fmt"
6 "os"
7 "os/exec"
8 "path/filepath"
9 "regexp"
10 "strings"
11 "testing"
12)
13
14// pending fits its text to 80 columns when stdout is no terminal: a long
15// title is cut short with …, and a branch or a handle is printed whole,
16// even where the line it is on cannot fit. A stack of branches four deep
17// is listed at one indentation, so its deepest entry has the room its
18// second has. Nothing it prints is an escape code.
19func TestPendingFitsEightyColumnsAndKeepsNamesWhole(t *testing.T) {
20 dir := t.TempDir()
21 t.Setenv("HOME", dir)
22 t.Setenv("XDG_CONFIG_HOME", filepath.Join(dir, "config"))
23 t.Setenv("GIT_CONFIG_NOSYSTEM", "1")
24 t.Setenv("VALLEY_KNOWN_SIGNERS", "")
25 origin, work := filepath.Join(dir, "origin.git"), filepath.Join(dir, "work")
26 sh := func(args ...string) {
27 t.Helper()
28 cmd := exec.Command("git", args...)
29 cmd.Dir = work
30 if out, err := cmd.CombinedOutput(); err != nil {
31 t.Fatalf("git %s: %v\n%s", strings.Join(args, " "), err, out)
32 }
33 }
34 if out, err := exec.Command("git", "init", "--quiet", "--bare", "--initial-branch=main", origin).CombinedOutput(); err != nil {
35 t.Fatalf("git init: %v\n%s", err, out)
36 }
37 if out, err := exec.Command("git", "clone", "--quiet", origin, work).CombinedOutput(); err != nil {
38 t.Fatalf("git clone: %v\n%s", err, out)
39 }
40 sh("config", "user.name", "a committer whose name is so long that the line it is on has to cut it short")
41 sh("config", "user.email", "committer@localhost")
42 sh("config", "valley.principal", "alice")
43 sh("checkout", "--quiet", "-b", "main")
44 sh("commit", "--quiet", "--allow-empty", "-m", "base")
45 sh("push", "--quiet", "origin", "main")
46
47 long := "a-branch-whose-name-runs-on-well-past-the-eightieth-column-of-any-terminal-it-is-shown-in"
48 title := "a subject that says far more than one line has room for, " + strings.Repeat("and then some more ", 4)
49 sh("checkout", "--quiet", "-b", long, "main")
50 sh("commit", "--quiet", "--allow-empty", "-m", title+"on the long branch")
51 sh("push", "--quiet", "origin", long)
52 sh("checkout", "--quiet", "-b", "short", "main")
53 sh("commit", "--quiet", "--allow-empty", "-m", title)
54 sh("push", "--quiet", "origin", "short")
55 from := "main"
56 for _, layer := range []string{"1", "2", "3", "4"} {
57 sh("checkout", "--quiet", "-b", "layer-"+layer, from)
58 sh("commit", "--quiet", "--allow-empty", "-m", "layer "+layer+": "+title)
59 sh("push", "--quiet", "origin", "layer-"+layer)
60 from = "layer-" + layer
61 }
62
63 t.Chdir(work)
64 var stdout, stderr bytes.Buffer
65 if code := run([]string{"ready", "--change", strings.Repeat("q", 32), "short"}, &stdout, &stderr, os.Exit); code != 0 {
66 t.Fatalf("ready: %s", stderr.String())
67 }
68 stdout.Reset()
69 if code := run([]string{"pending", "--branches"}, &stdout, &stderr, os.Exit); code != 0 {
70 t.Fatalf("pending: %s", stderr.String())
71 }
72 out := stdout.String()
73 if strings.Contains(out, "\x1b") {
74 t.Errorf("pending printed an escape code to no terminal:\n%s", out)
75 }
76 if !strings.Contains(out, "\n"+long+"\n") {
77 t.Errorf("the long branch is not whole, on a line of its own:\n%s", out)
78 }
79 if !strings.Contains(out, "\n 1 qqqq v1") {
80 t.Errorf("the change is not named by its whole handle and version:\n%s", out)
81 }
82 cut := 0
83 for _, line := range strings.Split(strings.TrimSuffix(out, "\n"), "\n") {
84 if strings.Contains(line, long) {
85 continue
86 }
87 if columns(line) > 80 {
88 t.Errorf("a line is %d columns wide: %q", columns(line), line)
89 }
90 if strings.HasPrefix(strings.TrimLeft(line, " "), "a subject that says") {
91 if columns(line) != 80 || !strings.HasSuffix(line, "…") {
92 t.Errorf("a long title is not cut to 80 columns with …: %q", line)
93 }
94 cut++
95 }
96 if strings.HasPrefix(line, "layer-4 ") && !strings.HasSuffix(line, "…") {
97 t.Errorf("the author is not cut short to keep the line within 80 columns: %q", line)
98 }
99 }
100 lines := strings.Split(out, "\n")
101 for layer, lead := range map[string]string{"4": " ", "3": " │ ", "2": " │ ", "1": " "} {
102 listed := false
103 for _, line := range lines {
104 if strings.HasPrefix(line, lead+"layer "+layer+": ") {
105 listed = true
106 if columns(line) != 80 || !strings.HasSuffix(line, "…") {
107 t.Errorf("layer %s's title is not cut to 80 columns with …: %q", layer, line)
108 }
109 }
110 }
111 if !listed {
112 t.Errorf("layer %s's title is not at %q:\n%s", layer, lead, out)
113 }
114 }
115 if !strings.Contains(out, "\n approving it lands the 3 below too\n") || strings.Contains(out, "on layer-") {
116 t.Errorf("the stack four deep is not one list, each layer on the next:\n%s", out)
117 }
118 if cut != 2 {
119 t.Errorf("%d titles were cut short, where the change's and the branch's should be:\n%s", cut, out)
120 }
121}
122
123// fit cuts by columns, not bytes: a wide character takes two, and a
124// combining mark none.
125func TestFitCountsColumns(t *testing.T) {
126 for _, c := range []struct {
127 s string
128 n int
129 want string
130 }{
131 {"short", 10, "short"},
132 {"exactly ten", 11, "exactly ten"},
133 {"one word too many", 12, "one word to…"},
134 {"漢字漢字漢字", 7, "漢字漢…"},
135 {"café au lait", 5, "café au lait"[:6] + "…"},
136 } {
137 if got := fit(c.s, c.n); got != c.want || columns(got) > c.n {
138 t.Errorf("fit(%q, %d) = %q, %d columns; want %q", c.s, c.n, got, columns(got), c.want)
139 }
140 }
141}
142
143// toolsOnPath puts on PATH, for the test, a shim for each tool named that
144// logs each start to the file it returns and runs the real tool. It
145// skips the test when a tool is missing, unless VALLEY_TEST_TOOLS is
146// required.
147func toolsOnPath(t *testing.T, dir string, tools ...string) (starts string) {
148 t.Helper()
149 bin, starts := filepath.Join(dir, "bin"), filepath.Join(dir, "starts")
150 if err := os.MkdirAll(bin, 0o755); err != nil {
151 t.Fatal(err)
152 }
153 for _, tool := range tools {
154 real, err := exec.LookPath(tool)
155 if err != nil {
156 if os.Getenv("VALLEY_TEST_TOOLS") == "required" {
157 t.Fatalf("no %s on PATH, and VALLEY_TEST_TOOLS=required", tool)
158 }
159 t.Skipf("no %s to run; the nix check provides one", tool)
160 }
161 shim := fmt.Sprintf("#!/bin/sh\necho %s >> '%s'\nexec '%s' \"$@\"\n", tool, starts, real)
162 if err := os.WriteFile(filepath.Join(bin, tool), []byte(shim), 0o755); err != nil {
163 t.Fatal(err)
164 }
165 }
166 t.Setenv("PATH", bin+string(os.PathListSeparator)+os.Getenv("PATH"))
167 return starts
168}
169
170// testSchema is the verification schema, read from the package's
171// directory before a test changes to another.
172var testSchema, _ = filepath.Abs(filepath.Join("..", "schema", "verification.cue"))
173
174// policyProject is a repository at root with its own origin, whose floor
175// has one class requiring checks c-1 to c-<checks> of every path under
176// src/, made the current directory. head pushes a branch off main that
177// adds src/<branch> and readies it as the change id.
178func policyProject(t *testing.T, root string, checks int) (sh func(...string), head func(branch, id string)) {
179 t.Helper()
180 t.Setenv("HOME", root)
181 t.Setenv("XDG_CONFIG_HOME", filepath.Join(root, "config"))
182 t.Setenv("GIT_CONFIG_NOSYSTEM", "1")
183 t.Setenv("VALLEY_KNOWN_SIGNERS", "")
184 t.Setenv("VALLEY_VERIFICATION_SCHEMA", testSchema)
185 origin, work := filepath.Join(root, "origin.git"), filepath.Join(root, "work")
186 sh = func(args ...string) {
187 t.Helper()
188 cmd := exec.Command("git", args...)
189 cmd.Dir = work
190 if out, err := cmd.CombinedOutput(); err != nil {
191 t.Fatalf("git %s: %v\n%s", strings.Join(args, " "), err, out)
192 }
193 }
194 if out, err := exec.Command("git", "init", "--quiet", "--bare", "--initial-branch=main", origin).CombinedOutput(); err != nil {
195 t.Fatalf("git init: %v\n%s", err, out)
196 }
197 if out, err := exec.Command("git", "clone", "--quiet", origin, work).CombinedOutput(); err != nil {
198 t.Fatalf("git clone: %v\n%s", err, out)
199 }
200 sh("config", "user.name", "operator")
201 sh("config", "user.email", "operator@example.org")
202 sh("config", "valley.principal", "operator")
203 sh("checkout", "--quiet", "-b", "main")
204 var floor strings.Builder
205 floor.WriteString("package verification\nfloor: {\n")
206 for i := 1; i <= checks; i++ {
207 fmt.Fprintf(&floor, "\tchecks: \"c-%d\": {runner: \"nix\", attribute: \"c-%d\"}\n", i, i)
208 fmt.Fprintf(&floor, "\tclasses: src: {paths: \"src/**\": true, requires: \"c-%d\": true}\n", i)
209 }
210 floor.WriteString("\tunclassified: \"c-1\": true\n}\n")
211 if err := os.MkdirAll(filepath.Join(work, "policy", "instance"), 0o755); err != nil {
212 t.Fatal(err)
213 }
214 if err := os.WriteFile(filepath.Join(work, "policy", "instance", "floor.cue"), []byte(floor.String()), 0o644); err != nil {
215 t.Fatal(err)
216 }
217 sh("add", ".")
218 sh("commit", "--quiet", "-m", "base")
219 sh("push", "--quiet", "origin", "main")
220 t.Chdir(work)
221 head = func(branch, id string) {
222 t.Helper()
223 sh("checkout", "--quiet", "-b", branch, "main")
224 if err := os.MkdirAll(filepath.Join(work, "src"), 0o755); err != nil {
225 t.Fatal(err)
226 }
227 if err := os.WriteFile(filepath.Join(work, "src", branch), []byte(branch+"\n"), 0o644); err != nil {
228 t.Fatal(err)
229 }
230 sh("add", ".")
231 sh("commit", "--quiet", "-m", branch)
232 sh("push", "--quiet", "origin", branch)
233 var stdout, stderr bytes.Buffer
234 if code := run([]string{"ready", "--change", id, branch}, &stdout, &stderr, os.Exit); code != 0 {
235 t.Fatalf("ready: %s", stderr.String())
236 }
237 }
238 return sh, head
239}
240
241// runCounted runs valley with args, and returns what it printed and how
242// many processes the shims on PATH logged, by tool, and in all under "".
243func runCounted(t *testing.T, starts string, args ...string) (string, map[string]int) {
244 t.Helper()
245 os.Remove(starts)
246 var stdout, stderr bytes.Buffer
247 if code := run(args, &stdout, &stderr, os.Exit); code != 0 {
248 t.Fatalf("%s: %s", strings.Join(args, " "), stderr.String())
249 }
250 log, _ := os.ReadFile(starts)
251 started := map[string]int{}
252 for _, tool := range strings.Fields(string(log)) {
253 started[tool]++
254 started[""]++
255 }
256 return stdout.String(), started
257}
258
259// pending reads the policy at main's tip once for a project, and asks cue
260// no requirement's pin: the cue processes it starts, with --checks or
261// without, are as many for a class requiring nine checks and four ready
262// heads as for one requiring three and one head.
263func TestPendingStartsCueOncePerProject(t *testing.T) {
264 dir := t.TempDir()
265 starts := toolsOnPath(t, dir, "cue")
266
267 // project lists a project whose class requires checks c-1 to
268 // c-<checks>, with heads ready changes touching it. It returns what
269 // each listing printed and how many cue processes it started.
270 project := func(checks, heads int) (printed map[string]string, started map[string]int) {
271 t.Helper()
272 _, head := policyProject(t, filepath.Join(dir, fmt.Sprintf("%d-%d", checks, heads)), checks)
273 for i := 1; i <= heads; i++ {
274 head(fmt.Sprintf("head-%d", i), strings.Repeat(string(rune('p'+i)), 32))
275 }
276 printed, started = map[string]string{}, map[string]int{}
277 for _, args := range [][]string{{"pending"}, {"pending", "--checks"}} {
278 listing := strings.Join(args, " ")
279 out, n := runCounted(t, starts, args...)
280 printed[listing], started[listing] = out, n["cue"]
281 }
282 return printed, started
283 }
284
285 _, small := project(3, 1)
286 out, large := project(9, 4)
287 if want := "requires 9 quick checks, 0 slow"; strings.Count(out["pending --checks"], want) != 4 {
288 t.Fatalf("pending --checks does not say %q of each of four heads:\n%s", want, out["pending --checks"])
289 }
290 for listing, n := range small {
291 if n == 0 || large[listing] != n {
292 t.Errorf("%s started %d cue processes for three checks and one head, and %d for nine and four heads", listing, n, large[listing])
293 }
294 }
295}
296
297// pending --checks reads a draft's checks only when --drafts lists the
298// drafts. A listing starts attest only to read checks, once for each head
299// to digest its tree. Without --drafts, two drafts start no attest, add
300// nothing to what --checks starts, and change no row; with it, each
301// draft's tree is digested and its block shows its checks.
302func TestPendingReadsDraftChecksOnlyWhenListed(t *testing.T) {
303 dir := t.TempDir()
304 starts := toolsOnPath(t, dir, "git", "cue")
305 // attest logs its start as the shims do and answers with one digest:
306 // when origin holds no evidence, a listing asks it only to digest each
307 // head's tree, and the digest decides nothing.
308 stand := fmt.Sprintf("#!/bin/sh\necho attest >> '%s'\necho valley-tree-v1:0123\n", starts)
309 if err := os.WriteFile(filepath.Join(dir, "bin", "attest"), []byte(stand), 0o755); err != nil {
310 t.Fatal(err)
311 }
312 _, head := policyProject(t, filepath.Join(dir, "project"), 2)
313 head("ready-1", strings.Repeat("p", 32))
314 // listing is pending with args and --checks: what it printed, its ages
315 // left out, since a row's age ticks, the attest processes it started,
316 // and how many processes --checks added.
317 ages := regexp.MustCompile(`(?m) +[0-9]+[smhd]$`)
318 listing := func(args ...string) (out string, attest, added int) {
319 t.Helper()
320 _, without := runCounted(t, starts, append([]string{"pending"}, args...)...)
321 out, with := runCounted(t, starts, append([]string{"pending", "--checks"}, args...)...)
322 return ages.ReplaceAllString(out, ""), with["attest"], with[""] - without[""]
323 }
324 before, attest, added := listing()
325 if attest != 1 {
326 t.Fatalf("pending --checks started attest %d times for one ready head", attest)
327 }
328 for _, id := range []string{"q", "r"} {
329 head("draft-"+id, strings.Repeat(id, 32))
330 var stdout, stderr bytes.Buffer
331 if code := run([]string{"unready", strings.Repeat(id, 32)}, &stdout, &stderr, os.Exit); code != 0 {
332 t.Fatalf("unready: %s", stderr.String())
333 }
334 }
335 after, drafted, addedNow := listing()
336 if drafted != attest || addedNow != added {
337 t.Errorf("with two drafts not listed, pending --checks started attest %d times, not %d, and --checks added %d processes, not %d",
338 drafted, attest, addedNow, added)
339 }
340 if want := before + "\n2 drafts · valley pending --drafts\n"; after != want {
341 t.Errorf("pending --checks printed, with two drafts:\n%s\nand with none:\n%s", after, before)
342 }
343 out, listed, _ := listing("--drafts")
344 if listed != attest+2 {
345 t.Errorf("pending --drafts --checks started attest %d times for one ready head and two drafts", listed)
346 }
347 for _, d := range []string{"qqqq v1 on draft-q 2 checks pending", "rrrr v1 on draft-r 2 checks pending"} {
348 if !strings.Contains(out, "\n"+d) {
349 t.Errorf("pending --drafts --checks does not open a block with %q:\n%s", d, out)
350 }
351 }
352 if n := strings.Count(out, "\n checks: 2 pending\n"); n != 2 {
353 t.Errorf("pending --drafts --checks gives %d drafts their checks line, not 2:\n%s", n, out)
354 }
355}