gunk-dev/the-valley

agree_test.go

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