gunk-dev/the-valley

agree_test.go

source53bd156eeb1bmain's published tip history
29.0 KiB
1package derive
2
3import (
4 "bytes"
5 "fmt"
6 "math/rand/v2"
7 "os"
8 "os/exec"
9 "path/filepath"
10 "regexp"
11 "slices"
12 "sort"
13 "strings"
14 "testing"
15
16 "the-valley/composed"
17)
18
19// fixture is one policy both derivers are run under, and how many cases
20// are drawn for it.
21type fixture struct {
22 name string
23 instance, project []string
24 cases int
25}
26
27// fixtures are the policies this repository carries: its own project
28// layer, under the example floor and template own-policy composes it with
29// because the owning valley's floor is not in this tree; the scratch policy
30// policy-deriver drives; the worked example; the policy self-update's
31// smoke test ships; and each carry case cue-vet vets, as a floor under a
32// project that adds nothing.
33func fixtures(t *testing.T, r *rig) []fixture {
34 fs := []fixture{
35 {"own", []string{r.path("examples/policy/instance/floor-format.cue"), r.path("examples/policy/instance/template-docs.cue")}, r.glob(t, "policy/project/*.cue"), 16},
36 {"deriver", r.glob(t, "examples/policy/deriver/[ft]*.cue"), []string{r.path("examples/policy/deriver/project.cue")}, 30},
37 {"example", r.glob(t, "examples/policy/instance/*.cue"), r.glob(t, "examples/policy/project/*.cue"), 16},
38 {"smoke", r.glob(t, "examples/policy/smoke/instance/*.cue"), r.glob(t, "examples/policy/smoke/project/*.cue"), 10},
39 }
40 for _, f := range r.glob(t, "examples/policy/carry/*.cue") {
41 fs = append(fs, fixture{"carry-" + strings.TrimSuffix(filepath.Base(f), ".cue"), []string{f}, nil, 6})
42 }
43 return fs
44}
45
46// TestDeriversAgree runs both derivers over every fixture policy and cases
47// drawn from a fixed seed, and requires the same answer from each: the
48// same documents composed, the same changed paths in the same order, the
49// same classes, carry mode and unclassified paths, and the same required
50// checks with the same classes, pins, runners, attributes, commands and
51// costs. bin/valley is run under every locale (locales), and the fixtures'
52// layer directories are named in turn as each of namings names them.
53//
54// A case is a change from one base tree: files modified, added, deleted,
55// renamed and turned into symbolic links, at paths drawn from instances of
56// every glob the policy names, near misses of each, and names chosen to be
57// awkward. A newline in a path is the one thing no case holds, because
58// bin/valley splits such a path in two (TestKnownDivergences).
59func TestDeriversAgree(t *testing.T) {
60 r := newRig(t)
61 locs := r.locales(t)
62 for i, f := range fixtures(t, r) {
63 t.Run(f.name, func(t *testing.T) {
64 l := newLayersAt(t, namings[i%len(namings)], f.instance, f.project, nil)
65 m, err := r.read(l)
66 if err != nil {
67 t.Fatalf("the Go deriver cannot read the policy: %v", err)
68 }
69 rng := rand.New(rand.NewPCG(20261021, uint64(i)))
70 pool := pathPool(m, rng)
71 rp := newRepo(t, r)
72 base := baseTree(rng, pool)
73 baseCommit := rp.commit("", base)
74 heads := []string{baseCommit, rp.commit(baseCommit, tree{})}
75 for range f.cases {
76 heads = append(heads, rp.commit(baseCommit, change(rng, base, pool)))
77 }
78 for n, head := range heads {
79 t.Run(fmt.Sprintf("case-%02d", n), func(t *testing.T) {
80 t.Parallel()
81 res, err := r.derive(m, rp.dir, baseCommit, head)
82 if err != nil {
83 t.Fatalf("the Go deriver refused: %v", err)
84 }
85 for _, loc := range locs {
86 rep, err := r.valleyIn(t, loc, rp.dir, r.schema, l, baseCommit, head)
87 if err != nil {
88 t.Fatalf("bin/valley refused in %s: %v", loc.name, err)
89 }
90 if diffs := agree(rep, m, res); len(diffs) > 0 {
91 t.Errorf("the derivers disagree in %s over %q:\n %s", loc.name, res.Paths, strings.Join(diffs, "\n "))
92 }
93 }
94 })
95 }
96 })
97 }
98}
99
100// TestReplacementRefsChangeNothing holds both derivers to reading the
101// commits they are given, with replacement refs on in git's configuration
102// and a replacement standing the uncovered case's head in for another.
103func TestReplacementRefsChangeNothing(t *testing.T) {
104 r := newRig(t)
105 l := newLayers(t, r.glob(t, "examples/policy/deriver/[ft]*.cue"), []string{r.path("examples/policy/deriver/project.cue")}, nil)
106 m, err := r.read(l)
107 if err != nil {
108 t.Fatal(err)
109 }
110 rp := newRepo(t, r)
111 base := rp.commit("", tree{"Makefile": file("seed\n"), "src/one.rs": file("seed\n")})
112 uncovered := rp.commit(base, tree{"Makefile": file("edit\n"), "src/one.rs": file("seed\n")})
113 flat := rp.commit(base, tree{"Makefile": file("seed\n"), "src/one.rs": file("edit\n")})
114 rp.git(nil, "update-ref", "refs/replace/"+uncovered, flat)
115 on := "GIT_CONFIG_PARAMETERS='core.usereplacerefs'='true'"
116 if got := rp.gitEnv([]string{on}, nil, "diff", "--name-only", base, uncovered); got != "src/one.rs" {
117 t.Fatalf("the replacement did not take, so this case proves nothing: %q", got)
118 }
119 rep, err := r.valley(t, rp.dir, r.schema, l, base, uncovered, on)
120 if err != nil {
121 t.Fatal(err)
122 }
123 res, err := r.derive(m, rp.dir, base, uncovered, on)
124 if err != nil {
125 t.Fatal(err)
126 }
127 if diffs := agree(rep, m, res); len(diffs) > 0 {
128 t.Errorf("the derivers disagree:\n %s", strings.Join(diffs, "\n "))
129 }
130 if got := names(res); !sameSet(got, []string{"c-uncovered"}) {
131 t.Errorf("a replacement ref changed what is required: %q", got)
132 }
133}
134
135// TestLocaleChangesNothing holds both derivers to one answer in every
136// locale, for the paths a locale reads differently, and holds that answer
137// to bytes. A glob matches bytes: `?` is one byte, so `?.md` covers x.md
138// and not é.md, whose é is two, and `**` and `*` cover bytes that are not
139// UTF-8, which a UTF-8 locale's regular expressions match nothing of. Two
140// paths that differ in one such byte are two paths, which sort -u under
141// en_US.UTF-8 would merge.
142func TestLocaleChangesNothing(t *testing.T) {
143 r := newRig(t)
144 l := newLayers(t, r.glob(t, "examples/policy/deriver/[ft]*.cue"), []string{r.path("examples/policy/deriver/project.cue")},
145 map[string]string{"bytes.cue": "package verification\n" +
146 `project: classes: one: {paths: "?.md": true, requires: "c-notes": true}` + "\n" +
147 `project: classes: raw: {paths: "raw/**": true, requires: "c-nested": true}` + "\n"})
148 m, err := r.read(l)
149 if err != nil {
150 t.Fatal(err)
151 }
152 rp := newRepo(t, r)
153 base := rp.commit("", tree{"Makefile": file("seed\n")})
154 head := rp.commit(base, tree{
155 "Makefile": file("seed\n"), "x.md": file("x\n"), "\xc3\xa9.md": file("e\n"),
156 "raw/\xff.bin": file("ff\n"), "src/caf\xe9.rs": file("latin-1\n"),
157 "a\xffb": file("ff\n"), "a\xfeb": file("fe\n"),
158 })
159 res, err := r.derive(m, rp.dir, base, head)
160 if err != nil {
161 t.Fatal(err)
162 }
163 if want := []string{"deep", "flat", "one", "raw"}; !slices.Equal(res.Classes, want) {
164 t.Errorf("the Go deriver matched %q; bytes match %q", res.Classes, want)
165 }
166 if want := []string{"a\xfeb", "a\xffb", "\xc3\xa9.md"}; !slices.Equal(res.Unclassified, want) {
167 t.Errorf("the Go deriver left %q unclassified; bytes leave %q", res.Unclassified, want)
168 }
169 locs := r.locales(t)
170 if len(locs) < 2 {
171 t.Skip("no UTF-8 locale takes here, so this case proves nothing")
172 }
173 for _, loc := range locs {
174 rep, err := r.valleyIn(t, loc, rp.dir, r.schema, l, base, head)
175 if err != nil {
176 t.Fatalf("bin/valley refused in %s: %v", loc.name, err)
177 }
178 if diffs := agree(rep, m, res); len(diffs) > 0 {
179 t.Errorf("the derivers disagree in %s:\n %s", loc.name, strings.Join(diffs, "\n "))
180 }
181 }
182}
183
184// TestLayerDiscovery holds both derivers to reading a layer as bin/valley's
185// `"$dir"/*.cue` does. The directory is a name, so one named like a pattern
186// is read and the directories the pattern names are not. A name beginning
187// with a dot is not a document. And a layer whose first document is not a
188// file holds none, so both refuse it.
189func TestLayerDiscovery(t *testing.T) {
190 r := newRig(t)
191 floor := r.glob(t, "examples/policy/deriver/[ft]*.cue")
192 project := []string{r.path("examples/policy/deriver/project.cue")}
193 rp := newRepo(t, r)
194 base := rp.commit("", tree{"docs/a.md": file("seed\n")})
195 head := rp.commit(base, tree{"docs/a.md": file("edit\n"), "src/b.rs": file("new\n")})
196
197 for _, n := range namings {
198 t.Run(n.instance+" and "+n.project, func(t *testing.T) {
199 l := newLayersAt(t, n, floor, project, nil)
200 m, err := r.read(l)
201 if err != nil {
202 t.Fatalf("the Go deriver cannot read the policy: %v", err)
203 }
204 want := []string{r.schema, filepath.Join(l.instance, "floor.cue"), filepath.Join(l.instance, "template.cue"), filepath.Join(l.project, "project.cue")}
205 if !slices.Equal(m.Documents, want) {
206 t.Errorf("the Go deriver composed %q; the layers' documents are %q", m.Documents, want)
207 }
208 rep, err := r.valley(t, rp.dir, r.schema, l, base, head)
209 if err != nil {
210 t.Fatalf("bin/valley refused: %v", err)
211 }
212 res, err := r.derive(m, rp.dir, base, head)
213 if err != nil {
214 t.Fatal(err)
215 }
216 if diffs := agree(rep, m, res); len(diffs) > 0 {
217 t.Errorf("the derivers disagree:\n %s", strings.Join(diffs, "\n "))
218 }
219 })
220 }
221
222 refuse := func(t *testing.T, l layers) {
223 t.Helper()
224 if rep, err := r.valley(t, rp.dir, r.schema, l, base, head); err == nil || !strings.Contains(err.Error(), "no project policy layer") {
225 t.Errorf("bin/valley did not refuse the project layer: %v, %+v", err, rep)
226 }
227 if m, err := r.read(l); err == nil || !strings.Contains(err.Error(), "no policy layer at "+l.project) {
228 t.Errorf("the Go deriver did not refuse the project layer: %v, %q", err, m.Documents)
229 }
230 }
231 t.Run("a dotfile alone", func(t *testing.T) {
232 l := newLayers(t, floor, nil, map[string]string{".only.cue": "package verification\n"})
233 refuse(t, l)
234 })
235 t.Run("a directory first", func(t *testing.T) {
236 l := newLayers(t, floor, project, nil)
237 if err := os.Mkdir(filepath.Join(l.project, "a.cue"), 0o755); err != nil {
238 t.Fatal(err)
239 }
240 refuse(t, l)
241 })
242}
243
244// TestEveryDerivationGlobal holds the globals agree compares to the ones
245// bin/valley declares for its derivation, so a global added there is one
246// these tests compare.
247func TestEveryDerivationGlobal(t *testing.T) {
248 r := newRig(t)
249 script, err := os.ReadFile(r.script)
250 if err != nil {
251 t.Fatal(err)
252 }
253 declared := []string{"POLICY_LAYER"}
254 for _, m := range regexp.MustCompile(`(?m)^(?:declare -A )?((?:DERIVED|CHECK)_[A-Z_]+)=`).FindAllSubmatch(script, -1) {
255 declared = append(declared, string(m[1]))
256 }
257 var compared []string
258 for _, g := range derivation {
259 compared = append(compared, g.name)
260 }
261 if !sameSet(declared, compared) {
262 t.Errorf("bin/valley declares %q, and the tests compare %q", sortedSet(declared), sortedSet(compared))
263 }
264}
265
266// TestKnownDivergences records each place bin/valley's deriver is wrong
267// (bug bd-11e0e4d) and the Go deriver is not: what each one answers. When
268// bin/valley's answer changes, so must this test.
269func TestKnownDivergences(t *testing.T) {
270 r := newRig(t)
271 floor := r.glob(t, "examples/policy/deriver/[ft]*.cue")
272 project := []string{r.path("examples/policy/deriver/project.cue")}
273 rp := newRepo(t, r)
274 seed := tree{"docs/kept.md": file("seed\n"), "Makefile": file("seed\n")}
275 base := rp.commit("", seed)
276 with := func(path string) string {
277 files := tree{path: file("added\n")}
278 for p, e := range seed {
279 files[p] = e
280 }
281 return rp.commit(base, files)
282 }
283 bash := func(t *testing.T, l layers, head string) (*report, error) {
284 t.Helper()
285 return r.valley(t, rp.dir, r.schema, l, base, head)
286 }
287 gos := func(t *testing.T, l layers, head string) *Result {
288 t.Helper()
289 m, err := r.read(l)
290 if err != nil {
291 t.Fatalf("the Go deriver cannot read the policy: %v", err)
292 }
293 res, err := r.derive(m, rp.dir, base, head)
294 if err != nil {
295 t.Fatalf("the Go deriver refused: %v", err)
296 }
297 return res
298 }
299 requires := func(t *testing.T, who string, got, want []string) {
300 t.Helper()
301 if !sameSet(got, want) {
302 t.Errorf("%s requires %q, and this test records %q", who, got, want)
303 }
304 }
305 reportNames := func(rep *report) []string {
306 var out []string
307 for name := range rep.required {
308 out = append(out, name)
309 }
310 return out
311 }
312
313 // diff_paths prints each path on a line of its own, so a path holding a
314 // newline is read as two. src/a<newline>b.rs matches the flat and deep
315 // classes whole; its two halves match no class.
316 t.Run("a newline in a path", func(t *testing.T) {
317 l := newLayers(t, floor, project, nil)
318 head := with("src/a\nb.rs")
319 rep, err := bash(t, l, head)
320 if err != nil {
321 t.Fatal(err)
322 }
323 if rep.paths != 2 || !sameSet(rep.unclassified, []string{"src/a", "b.rs"}) {
324 t.Errorf("bin/valley read %d paths, %q unclassified; this test records 2, src/a and b.rs", rep.paths, rep.unclassified)
325 }
326 requires(t, "bin/valley", reportNames(rep), []string{"c-uncovered"})
327 res := gos(t, l, head)
328 if !sameSet(res.Paths, []string{"src/a\nb.rs"}) || len(res.Unclassified) != 0 {
329 t.Errorf("the Go deriver read %q, %q unclassified", res.Paths, res.Unclassified)
330 }
331 requires(t, "the Go deriver", names(res), []string{"c-deep", "c-flat"})
332 })
333
334 // The schema's cross-check reads the layers' composition, not `policy`,
335 // so a class added by refining `policy` may require a check nobody
336 // defines, and cue vet passes. bin/valley derives as usual until a change
337 // touches that class, and then fails on an unbound variable while it
338 // groups the checks by cost. The Go deriver refuses the policy.
339 t.Run("a class added at policy requires an undefined check", func(t *testing.T) {
340 l := newLayers(t, floor, project, map[string]string{"ghost.cue": "package verification\n" +
341 `policy: classes: sneaky: {paths: "sneak/**": true, requires: ghost: true}` + "\n"})
342 if _, err := r.read(l); err == nil || !strings.Contains(err.Error(), "class sneaky requires check ghost, which the composed policy does not define") {
343 t.Errorf("the Go deriver read the policy: %v", err)
344 }
345 _, err := bash(t, l, with("sneak/x"))
346 if err == nil || !strings.Contains(err.Error(), "unbound variable") {
347 t.Errorf("bin/valley did not fail on an unbound variable for a change touching the class: %v", err)
348 }
349 rep, err := bash(t, l, with("docs/new.md"))
350 if err != nil {
351 t.Fatalf("bin/valley refused a change outside the class: %v", err)
352 }
353 requires(t, "bin/valley", reportNames(rep), []string{"c-docs", "c-tmpl"})
354 })
355
356 // bin/valley renders the unclassified set's requirements as a class
357 // named unclassified, so a real class of that name shares them. Each
358 // requires the other's checks, and the class's requirement is pinned by
359 // probing the set. When both require one check, the render states it
360 // twice, and bin/valley refuses every derivation.
361 t.Run("a class named unclassified", func(t *testing.T) {
362 l := newLayers(t, floor, project, map[string]string{"odd.cue": "package verification\n" +
363 `project: classes: unclassified: {paths: "odd/**": true, requires: "c-notes": true}` + "\n"})
364 odd, uncovered := with("odd/x"), with("Makefile.new")
365
366 rep, err := bash(t, l, odd)
367 if err != nil {
368 t.Fatal(err)
369 }
370 requires(t, "bin/valley, for a path in the class,", reportNames(rep), []string{"c-notes", "c-uncovered"})
371 if pin := rep.required["c-notes"].pin; pin != "default" {
372 t.Errorf("bin/valley pins the class's c-notes %s; this test records default", pin)
373 }
374 res := gos(t, l, odd)
375 requires(t, "the Go deriver, for a path in the class,", names(res), []string{"c-notes"})
376 if q := res.Required[0]; q.Pin != composed.Mandatory || !sameSet(q.Classes, []string{"unclassified"}) || q.Unclassified {
377 t.Errorf("the Go deriver requires c-notes as %+v", q)
378 }
379
380 rep, err = bash(t, l, uncovered)
381 if err != nil {
382 t.Fatal(err)
383 }
384 requires(t, "bin/valley, for an uncovered path,", reportNames(rep), []string{"c-notes", "c-uncovered"})
385 res = gos(t, l, uncovered)
386 requires(t, "the Go deriver, for an uncovered path,", names(res), []string{"c-uncovered"})
387 if len(res.Classes) != 0 || !res.Required[0].Unclassified {
388 t.Errorf("the Go deriver matched %q and required %+v", res.Classes, res.Required)
389 }
390
391 shared := newLayers(t, floor, project, map[string]string{"odd.cue": "package verification\n" +
392 `project: classes: unclassified: {paths: "odd/**": true, requires: "c-uncovered": true}` + "\n"})
393 if _, err := bash(t, shared, odd); err == nil || !strings.Contains(err.Error(), "rendered 'requires unclassified c-uncovered' twice") {
394 t.Errorf("bin/valley did not refuse a class sharing the unclassified set's check: %v", err)
395 }
396 res = gos(t, shared, odd)
397 requires(t, "the Go deriver, for a class sharing the set's check,", names(res), []string{"c-uncovered"})
398 if q := res.Required[0]; !sameSet(q.Classes, []string{"unclassified"}) || q.Unclassified {
399 t.Errorf("the Go deriver requires c-uncovered as %+v", q)
400 }
401 })
402}
403
404// TestBothRefuse holds both derivers to refusing what neither may derive
405// from: a policy cue-vet rejects, and a schema older than either deriver,
406// with no cost or no carry modes to read. Read as a policy, either would
407// be one whose checks cost nothing or whose classes carry everywhere.
408func TestBothRefuse(t *testing.T) {
409 r := newRig(t)
410 rp := newRepo(t, r)
411 base := rp.commit("", tree{"src/one.rs": file("seed\n")})
412 head := rp.commit(base, tree{"src/one.rs": file("edit\n"), "a/b": file("new\n")})
413 refuse := func(t *testing.T, schema string, l layers) {
414 t.Helper()
415 if rep, err := r.valley(t, rp.dir, schema, l, base, head); err == nil {
416 t.Errorf("bin/valley derived %+v", rep)
417 }
418 if m, err := composed.Read(t.Context(), r.cue, schema, l.instance, l.project); err == nil {
419 t.Errorf("the Go deriver read %+v", m)
420 }
421 }
422 for _, f := range r.glob(t, "examples/policy/carry/rejected/*.cue") {
423 t.Run(filepath.Base(f), func(t *testing.T) { refuse(t, r.schema, newLayers(t, []string{f}, nil, nil)) })
424 }
425 deriver := newLayers(t, r.glob(t, "examples/policy/deriver/[ft]*.cue"), []string{r.path("examples/policy/deriver/project.cue")}, nil)
426 body, err := os.ReadFile(r.schema)
427 if err != nil {
428 t.Fatal(err)
429 }
430 for name, line := range map[string]string{"costless": "\tcost: *\"quick\" | \"slow\"\n", "modeless": "\n_mode: "} {
431 t.Run(name, func(t *testing.T) {
432 at := bytes.Index(body, []byte(line))
433 if at < 0 {
434 t.Fatalf("the schema has no %q, so this case proves nothing", line)
435 }
436 end := at + 1 + bytes.IndexByte(body[at+1:], '\n')
437 older := filepath.Join(t.TempDir(), "verification.cue")
438 if err := os.WriteFile(older, append(append([]byte{}, body[:at+1]...), body[end+1:]...), 0o644); err != nil {
439 t.Fatal(err)
440 }
441 refuse(t, older, deriver)
442 })
443 }
444}
445
446// TestGlobsAgree holds Match to bin/valley's glob_ere, run by bash in the
447// C locale that derive_required derives in, over every glob the fixture
448// policies name, globs drawn from the characters a glob or a regular
449// expression treats specially, and paths drawn for each.
450func TestGlobsAgree(t *testing.T) {
451 r := newRig(t)
452 rng := rand.New(rand.NewPCG(20261021, 1000))
453 globs := map[string]bool{"docs/": true, "docs//": true, "": true, "**": true, "a**b": true, "**/**/x": true}
454 for _, f := range fixtures(t, r) {
455 m, err := r.read(newLayers(t, f.instance, f.project, nil))
456 if err != nil {
457 t.Fatal(err)
458 }
459 for _, c := range m.Classes {
460 for _, g := range c.Paths {
461 globs[g] = true
462 }
463 }
464 }
465 pieces := []string{"a", "b", ".", "*", "?", "/", "**", "\\", "(", ")", "[", "]", "{", "}", "+", "^", "$", "|", "é", " ", "x"}
466 for range 150 {
467 var g strings.Builder
468 for range 1 + rng.IntN(6) {
469 g.WriteString(pieces[rng.IntN(len(pieces))])
470 }
471 globs[g.String()] = true
472 }
473 sorted := make([]string, 0, len(globs))
474 for g := range globs {
475 sorted = append(sorted, g)
476 }
477 sort.Strings(sorted)
478
479 chars := []string{"a", "b", "x", ".", "/", "é", "\xff", "\n", " ", "*", "?", "\\", "md", "("}
480 type pair struct{ glob, path string }
481 var pairs []pair
482 var input bytes.Buffer
483 var want strings.Builder
484 for _, g := range sorted {
485 fmt.Fprintf(&input, "G\x00%s\x00", g)
486 paths := map[string]bool{}
487 for range 8 {
488 paths[instance(g, rng)] = true
489 }
490 for range 24 {
491 var p strings.Builder
492 for range rng.IntN(9) {
493 p.WriteString(chars[rng.IntN(len(chars))])
494 }
495 paths[p.String()] = true
496 }
497 for _, p := range sortedKeys(paths) {
498 fmt.Fprintf(&input, "P\x00%s\x00", p)
499 pairs = append(pairs, pair{g, p})
500 if Match(g, p) {
501 want.WriteByte('0')
502 } else {
503 want.WriteByte('1')
504 }
505 }
506 }
507 program := r.functions(t, "segment_ere", "glob_ere") + `
508while IFS= read -r -d '' kind && IFS= read -r -d '' value; do
509 case "$kind" in
510 G) ere="$(glob_ere "$value")" ;;
511 P) if [[ $value =~ $ere ]]; then printf 0; else printf '%d' "$?"; fi ;;
512 esac
513done
514`
515 got := r.bash(t, program, input.Bytes())
516 if len(got) != len(pairs) {
517 t.Fatalf("glob_ere answered %d pairs of %d", len(got), len(pairs))
518 }
519 failed := 0
520 for i, p := range pairs {
521 if got[i] == want.String()[i] {
522 continue
523 }
524 if failed++; failed <= 10 {
525 t.Errorf("glob %q, path %q: glob_ere answers %c, Match %c (0 is a match)", p.glob, p.path, got[i], want.String()[i])
526 }
527 }
528 t.Logf("%d globs, %d pairs, %d disagree", len(sorted), len(pairs), failed)
529}
530
531// TestDiffReadersAgree holds Changed to bin/valley's diff_paths over the
532// output git diff -z --name-status could give, and over every cut of some
533// of it. Each must read the same paths in the same order, or both must
534// refuse. diff_paths writes a path on a line of its own, so where a path
535// holds a newline, its lines are the path split at each, and that is the
536// divergence this records. Changed also refuses two records git never
537// writes, which diff_paths reads: an unknown status, and an empty path.
538func TestDiffReadersAgree(t *testing.T) {
539 r := newRig(t)
540 rng := rand.New(rand.NewPCG(20261021, 2000))
541 statuses := []string{"A", "M", "D", "T", "R100", "R075", "C050"}
542 chars := []string{"a", "b/", "x.md", "é", "\xff", " ", "\t", "*", "\\", "-"}
543 pathOf := func(newline bool) string {
544 var p strings.Builder
545 for range 1 + rng.IntN(5) {
546 p.WriteString(chars[rng.IntN(len(chars))])
547 }
548 if newline {
549 p.WriteString("\nmore")
550 }
551 return p.String()
552 }
553 var streams [][]byte
554 for n := range 200 {
555 var s bytes.Buffer
556 for range 1 + rng.IntN(4) {
557 status := statuses[rng.IntN(len(statuses))]
558 fmt.Fprintf(&s, "%s\x00%s\x00", status, pathOf(n%10 == 0))
559 if status[0] == 'R' || status[0] == 'C' {
560 fmt.Fprintf(&s, "%s\x00", pathOf(false))
561 }
562 }
563 streams = append(streams, s.Bytes())
564 }
565 for _, s := range streams[:6] {
566 for cut := range len(s) {
567 streams = append(streams, s[:cut])
568 }
569 }
570 unwritten := [][]byte{[]byte("Z\x00a\x00"), []byte("M\x00\x00")}
571 streams = append(streams, unwritten...)
572
573 dir := t.TempDir()
574 for i, s := range streams {
575 if err := os.WriteFile(filepath.Join(dir, fmt.Sprintf("%05d.in", i)), s, 0o644); err != nil {
576 t.Fatal(err)
577 }
578 }
579 program := r.functions(t, "diff_paths") + `
580for f in "$1"/*.in; do
581 if diff_paths < "$f" > "${f%.in}.out"; then echo ok; else echo refused; fi
582done
583`
584 verdicts := strings.Fields(r.bash(t, program, nil, dir))
585 if len(verdicts) != len(streams) {
586 t.Fatalf("diff_paths read %d streams of %d", len(verdicts), len(streams))
587 }
588 agreed, divergent := 0, 0
589 for i, s := range streams {
590 paths, err := Changed(s)
591 out, rerr := os.ReadFile(filepath.Join(dir, fmt.Sprintf("%05d.out", i)))
592 if rerr != nil {
593 t.Fatal(rerr)
594 }
595 isUnwritten := i >= len(streams)-len(unwritten)
596 switch {
597 case isUnwritten:
598 if err == nil || verdicts[i] != "ok" {
599 t.Errorf("stream %q: Changed %v, diff_paths %s; this test records a refusal and a reading", s, err, verdicts[i])
600 }
601 divergent++
602 case (err == nil) != (verdicts[i] == "ok"):
603 t.Errorf("stream %q: Changed says %v, diff_paths %s", s, err, verdicts[i])
604 case err != nil:
605 agreed++
606 default:
607 lines := string(out)
608 want := ""
609 if len(paths) > 0 {
610 want = strings.Join(paths, "\n") + "\n"
611 }
612 if lines != want {
613 t.Errorf("stream %q: Changed read %q, diff_paths wrote %q", s, paths, lines)
614 }
615 if strings.Count(want, "\n") > len(paths) {
616 divergent++
617 } else {
618 agreed++
619 }
620 }
621 }
622 t.Logf("%d streams agree; %d hold a newline path or a record git never writes", agreed, divergent)
623}
624
625// functions are bin/valley's definitions of the named functions, to be run
626// on their own.
627func (r *rig) functions(t *testing.T, names ...string) string {
628 t.Helper()
629 script, err := os.ReadFile(r.script)
630 if err != nil {
631 t.Fatal(err)
632 }
633 var out strings.Builder
634 for _, name := range names {
635 start := bytes.Index(script, []byte("\n"+name+"() {\n"))
636 if start < 0 {
637 t.Fatalf("bin/valley defines no %s", name)
638 }
639 body := script[start+1:]
640 end := bytes.Index(body, []byte("\n}\n"))
641 out.Write(body[:end+3])
642 }
643 return out.String()
644}
645
646// bash runs a program with stdin, in the rig's environment, and returns
647// what it printed.
648func (r *rig) bash(t *testing.T, program string, stdin []byte, args ...string) string {
649 t.Helper()
650 cmd := exec.Command("bash", append([]string{"-c", program, "bash"}, args...)...)
651 cmd.Env = r.env
652 cmd.Stdin = bytes.NewReader(stdin)
653 var stdout, stderr bytes.Buffer
654 cmd.Stdout, cmd.Stderr = &stdout, &stderr
655 if err := cmd.Run(); err != nil {
656 t.Fatalf("bash: %v\n%s", err, stderr.String())
657 }
658 return stdout.String()
659}
660
661func sortedKeys(set map[string]bool) []string {
662 out := make([]string, 0, len(set))
663 for k := range set {
664 out = append(out, k)
665 }
666 sort.Strings(out)
667 return out
668}
669
670// instance is a path made from a glob, which mostly matches it: each `**`
671// segment made none, one or two segments, each `*` some bytes, and each `?`
672// one character. That character is two bytes when it is é, so `?` meets a
673// character that is not one byte. A `*` or a `?` is sometimes made a `/`,
674// which neither may match.
675func instance(glob string, rng *rand.Rand) string {
676 segs := strings.Split(glob, "/")
677 if segs[len(segs)-1] == "" {
678 segs = segs[:len(segs)-1]
679 }
680 stars := []string{"", "x", "x.y", "ü", "\xff", " ", "*", "q.md", "", "x", "x/y"}
681 ones := []string{"q", "é", "\xfe", "?", "q", "/"}
682 var out []string
683 for _, seg := range segs {
684 if seg == "**" {
685 out = append(out, []string{"d", "e.md", "ü"}[:rng.IntN(3)]...)
686 continue
687 }
688 var s strings.Builder
689 for i := 0; i < len(seg); i++ {
690 switch seg[i] {
691 case '*':
692 s.WriteString(stars[rng.IntN(len(stars))])
693 case '?':
694 s.WriteString(ones[rng.IntN(len(ones))])
695 default:
696 s.WriteByte(seg[i])
697 }
698 }
699 out = append(out, s.String())
700 }
701 return strings.Join(out, "/")
702}
703
704// awkward are names chosen for what a reader of paths might get wrong.
705var awkward = []string{
706 "README.md", "a b.md", "-dash.md", "naïve.md", "caf\xe9.md", "tab\there.md",
707 "quote\"d.md", "back\\slash.md", "star*.md", "q?.md", "[br].md", "{x}.md",
708 "deep/a/b/c/d/e.txt", ".hidden", "dir.md/inner", "\xff\xfe/x", "research/notes.txt",
709 "src/x.rs.bak", "docs", "bin/valley", "flake.nix", "nix/checks/derive-unit.sh",
710}
711
712// validPath reports whether git would hold p as a path.
713func validPath(p string) bool {
714 if p == "" || strings.ContainsAny(p, "\x00\n") {
715 return false
716 }
717 for _, seg := range strings.Split(p, "/") {
718 if seg == "" || seg == "." || seg == ".." || strings.EqualFold(seg, ".git") {
719 return false
720 }
721 }
722 return true
723}
724
725// pathPool is what a fixture's cases are drawn from: instances of every
726// glob the policy names, near misses of each, and the awkward names.
727func pathPool(m *composed.Model, rng *rand.Rand) []string {
728 set := map[string]bool{}
729 add := func(p string) {
730 if validPath(p) {
731 set[p] = true
732 }
733 }
734 classes := make([]string, 0, len(m.Classes))
735 for name := range m.Classes {
736 classes = append(classes, name)
737 }
738 sort.Strings(classes)
739 for _, name := range classes {
740 for _, g := range m.Classes[name].Paths {
741 for range 3 {
742 p := instance(g, rng)
743 add(p)
744 add("zz/" + p)
745 add(p + "x")
746 if i := strings.LastIndexByte(p, '/'); i > 0 {
747 add(p[:i] + "/zz" + p[i:])
748 }
749 }
750 }
751 }
752 for _, p := range awkward {
753 add(p)
754 }
755 return sortedKeys(set)
756}
757
758// fits reports whether p can join t: no path of t is a directory of p's,
759// and p is no directory of a path of t.
760func fits(t tree, p string) bool {
761 if _, ok := t[p]; ok {
762 return false
763 }
764 for q := range t {
765 if strings.HasPrefix(p, q+"/") || strings.HasPrefix(q, p+"/") {
766 return false
767 }
768 }
769 return true
770}
771
772// baseTree is about half the pool.
773func baseTree(rng *rand.Rand, pool []string) tree {
774 t := tree{}
775 for _, p := range pool {
776 if rng.IntN(2) == 0 && fits(t, p) {
777 t[p] = file("base " + p + "\n")
778 }
779 }
780 return t
781}
782
783// change is base with one to six changes made to it.
784func change(rng *rand.Rand, base tree, pool []string) tree {
785 t := tree{}
786 for p, e := range base {
787 t[p] = e
788 }
789 existing := func() string {
790 paths := make([]string, 0, len(t))
791 for p := range t {
792 paths = append(paths, p)
793 }
794 sort.Strings(paths)
795 if len(paths) == 0 {
796 return ""
797 }
798 return paths[rng.IntN(len(paths))]
799 }
800 fresh := func() string {
801 for range 20 {
802 if p := pool[rng.IntN(len(pool))]; fits(t, p) {
803 return p
804 }
805 }
806 return ""
807 }
808 for n := range 1 + rng.IntN(6) {
809 switch rng.IntN(5) {
810 case 0: // modify
811 if p := existing(); p != "" {
812 t[p] = file(fmt.Sprintf("edit %d of %s\n", n, p))
813 }
814 case 1: // delete
815 if p := existing(); p != "" {
816 delete(t, p)
817 }
818 case 2: // add
819 if p := fresh(); p != "" {
820 t[p] = file("added " + p + "\n")
821 }
822 case 3: // rename
823 if from := existing(); from != "" {
824 e := t[from]
825 delete(t, from)
826 if to := fresh(); to != "" {
827 t[to] = e
828 } else {
829 t[from] = e
830 }
831 }
832 case 4: // turn into a symbolic link
833 if p := existing(); p != "" {
834 t[p] = entry{mode: "120000", content: "target-of-" + p}
835 }
836 }
837 }
838 return t
839}