gunk-dev/the-valley

derive_test.go

source8c40ee5f164cmain's published tip history
19.0 KiB
1package derive
2
3import (
4 "bytes"
5 "fmt"
6 "math/rand/v2"
7 "os"
8 "path/filepath"
9 "reflect"
10 "slices"
11 "sort"
12 "strings"
13 "testing"
14
15 "the-valley/composed"
16)
17
18// fixture is one policy the deriver is run under, and how many cases are
19// drawn for it.
20type fixture struct {
21 name string
22 instance, project []string
23 cases int
24}
25
26// fixtures are the policies this repository carries: its own project
27// layer, under the example floor and template own-policy composes it with
28// because the owning valley's floor is not in this tree; the scratch policy
29// policy-deriver drives; the worked example; the policy self-update's
30// smoke test ships; and each carry case cue-vet vets, as a floor under a
31// project that adds nothing.
32func fixtures(t *testing.T, r *rig) []fixture {
33 fs := []fixture{
34 {"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},
35 {"deriver", r.glob(t, "examples/policy/deriver/[ft]*.cue"), []string{r.path("examples/policy/deriver/project.cue")}, 30},
36 {"example", r.glob(t, "examples/policy/instance/*.cue"), r.glob(t, "examples/policy/project/*.cue"), 16},
37 {"smoke", r.glob(t, "examples/policy/smoke/instance/*.cue"), r.glob(t, "examples/policy/smoke/project/*.cue"), 10},
38 }
39 for _, f := range r.glob(t, "examples/policy/carry/*.cue") {
40 fs = append(fs, fixture{"carry-" + strings.TrimSuffix(filepath.Base(f), ".cue"), []string{f}, nil, 6})
41 }
42 return fs
43}
44
45// deriverLayers is the scratch policy of examples/policy/deriver, whose
46// floor is one glob boundary per class, with extra documents beside the
47// project's.
48func (r *rig) deriverLayers(t *testing.T, extra map[string]string) layers {
49 t.Helper()
50 return newLayers(t, r.glob(t, "examples/policy/deriver/[ft]*.cue"), []string{r.path("examples/policy/deriver/project.cue")}, extra)
51}
52
53// TestDrawnChanges derives every fixture policy over changes drawn from a
54// fixed seed, and holds each answer to what the test knows of the change
55// and the policy: the changed paths are those whose entry differs between
56// the two trees; a path is unclassified when no glob of any class matches
57// it; the classes are those a path matches; and the required checks are
58// what those classes require, with what the unclassified set requires when
59// a path is unclassified, each as the policy defines it. The fixtures'
60// layer directories are named in turn as each of namings names them.
61//
62// A case is a change from one base tree: files modified, added, deleted,
63// renamed and turned into symbolic links, at paths drawn from instances of
64// every glob the policy names, near misses of each, and names chosen to be
65// awkward. The change that keeps the base tree and the one that deletes it
66// are cases too.
67func TestDrawnChanges(t *testing.T) {
68 r := newRig(t)
69 for i, f := range fixtures(t, r) {
70 t.Run(f.name, func(t *testing.T) {
71 m, err := r.read(newLayersAt(t, namings[i%len(namings)], f.instance, f.project, nil))
72 if err != nil {
73 t.Fatalf("the policy does not read: %v", err)
74 }
75 rng := rand.New(rand.NewPCG(20261021, uint64(i)))
76 pool := pathPool(m, rng)
77 rp := newRepo(t, r)
78 base := baseTree(rng, pool)
79 baseCommit := rp.commit("", base)
80 heads := []tree{base, {}}
81 for range f.cases {
82 heads = append(heads, change(rng, base, pool))
83 }
84 for n, head := range heads {
85 res, err := r.derive(m, rp.dir, baseCommit, rp.commit(baseCommit, head))
86 if err != nil {
87 t.Fatalf("case %d: the deriver refused: %v", n, err)
88 }
89 for _, miss := range misses(m, base, head, res) {
90 t.Errorf("case %d: %s", n, miss)
91 }
92 }
93 })
94 }
95}
96
97// misses are the ways res differs from what the policy m requires of the
98// change from base to head.
99func misses(m *composed.Model, base, head tree, res *Result) []string {
100 var out []string
101 differ := func(what string, got, want []string) {
102 if !slices.Equal(got, want) {
103 out = append(out, fmt.Sprintf("%s are %q, not %q", what, got, want))
104 }
105 }
106 changed := map[string]bool{}
107 for p, e := range base {
108 if head[p] != e {
109 changed[p] = true
110 }
111 }
112 for p := range head {
113 if _, ok := base[p]; !ok {
114 changed[p] = true
115 }
116 }
117 paths := sortedKeys(changed)
118 differ("the paths", res.Paths, paths)
119
120 matched, required := map[string]bool{}, map[string]bool{}
121 var unclassified []string
122 for _, p := range paths {
123 covered := false
124 for name, c := range m.Classes {
125 if slices.ContainsFunc(c.Paths, func(g string) bool { return Match(g, p) }) {
126 matched[name], covered = true, true
127 for k := range c.Requires {
128 required[k] = true
129 }
130 }
131 }
132 if !covered {
133 unclassified = append(unclassified, p)
134 for k := range m.Unclassified {
135 required[k] = true
136 }
137 }
138 }
139 differ("the unclassified paths", res.Unclassified, unclassified)
140 differ("the classes", res.Classes, sortedKeys(matched))
141 differ("the required checks", names(res), sortedKeys(required))
142 for _, q := range res.Required {
143 if !reflect.DeepEqual(q.Check, m.Checks[q.Name]) {
144 out = append(out, fmt.Sprintf("%s is required as %+v, and the policy defines %+v", q.Name, q.Check, m.Checks[q.Name]))
145 }
146 }
147 return out
148}
149
150// TestReplacementRefsChangeNothing holds the deriver to reading the
151// commits it is given, with replacement refs on in git's configuration
152// and a replacement standing the uncovered case's head in for another.
153func TestReplacementRefsChangeNothing(t *testing.T) {
154 r := newRig(t)
155 m, err := r.read(r.deriverLayers(t, nil))
156 if err != nil {
157 t.Fatal(err)
158 }
159 rp := newRepo(t, r)
160 base := rp.commit("", tree{"Makefile": file("seed\n"), "src/one.rs": file("seed\n")})
161 uncovered := rp.commit(base, tree{"Makefile": file("edit\n"), "src/one.rs": file("seed\n")})
162 flat := rp.commit(base, tree{"Makefile": file("seed\n"), "src/one.rs": file("edit\n")})
163 rp.git(nil, "update-ref", "refs/replace/"+uncovered, flat)
164 on := "GIT_CONFIG_PARAMETERS='core.usereplacerefs'='true'"
165 if got := rp.gitEnv([]string{on}, nil, "diff", "--name-only", base, uncovered); got != "src/one.rs" {
166 t.Fatalf("the replacement did not take, so this case proves nothing: %q", got)
167 }
168 res, err := r.derive(m, rp.dir, base, uncovered, on)
169 if err != nil {
170 t.Fatal(err)
171 }
172 if got := names(res); !slices.Equal(got, []string{"c-uncovered"}) {
173 t.Errorf("a replacement ref changed what is required: %q", got)
174 }
175}
176
177// TestPathsAreBytes holds the deriver to matching bytes. `?` is one byte,
178// so `?.md` covers x.md and not é.md, whose é is two, and `**` and `*`
179// cover bytes that are not UTF-8. Two paths that differ in one such byte
180// are two paths.
181func TestPathsAreBytes(t *testing.T) {
182 r := newRig(t)
183 m, err := r.read(r.deriverLayers(t, map[string]string{"bytes.cue": "package verification\n" +
184 `project: classes: one: {paths: "?.md": true, requires: "c-notes": true}` + "\n" +
185 `project: classes: raw: {paths: "raw/**": true, requires: "c-nested": true}` + "\n"}))
186 if err != nil {
187 t.Fatal(err)
188 }
189 rp := newRepo(t, r)
190 base := rp.commit("", tree{"Makefile": file("seed\n")})
191 head := rp.commit(base, tree{
192 "Makefile": file("seed\n"), "x.md": file("x\n"), "\xc3\xa9.md": file("e\n"),
193 "raw/\xff.bin": file("ff\n"), "src/caf\xe9.rs": file("latin-1\n"),
194 "a\xffb": file("ff\n"), "a\xfeb": file("fe\n"),
195 })
196 res, err := r.derive(m, rp.dir, base, head)
197 if err != nil {
198 t.Fatal(err)
199 }
200 if want := []string{"deep", "flat", "one", "raw"}; !slices.Equal(res.Classes, want) {
201 t.Errorf("the deriver matched %q; bytes match %q", res.Classes, want)
202 }
203 if want := []string{"a\xfeb", "a\xffb", "\xc3\xa9.md"}; !slices.Equal(res.Unclassified, want) {
204 t.Errorf("the deriver left %q unclassified; bytes leave %q", res.Unclassified, want)
205 }
206}
207
208// TestLayerDiscovery holds composed.Read to reading a layer as the *.cue
209// documents in its directory. The directory is a name, so one named like a
210// pattern is read and the directories the pattern names are not. A name
211// beginning with a dot is not a document. And a layer whose first document
212// is not a file holds none, so it is refused.
213func TestLayerDiscovery(t *testing.T) {
214 r := newRig(t)
215 floor := r.glob(t, "examples/policy/deriver/[ft]*.cue")
216 project := []string{r.path("examples/policy/deriver/project.cue")}
217 for _, n := range namings {
218 t.Run(n.instance+" and "+n.project, func(t *testing.T) {
219 l := newLayersAt(t, n, floor, project, nil)
220 m, err := r.read(l)
221 if err != nil {
222 t.Fatalf("the policy does not read: %v", err)
223 }
224 want := []string{r.schema, filepath.Join(l.instance, "floor.cue"), filepath.Join(l.instance, "template.cue"), filepath.Join(l.project, "project.cue")}
225 if !slices.Equal(m.Documents, want) {
226 t.Errorf("composed %q; the layers' documents are %q", m.Documents, want)
227 }
228 })
229 }
230
231 refuse := func(t *testing.T, l layers) {
232 t.Helper()
233 if m, err := r.read(l); err == nil || !strings.Contains(err.Error(), "no policy layer at "+l.project) {
234 t.Errorf("the project layer was not refused: %v, %q", err, m.Documents)
235 }
236 }
237 t.Run("a dotfile alone", func(t *testing.T) {
238 refuse(t, newLayers(t, floor, nil, map[string]string{".only.cue": "package verification\n"}))
239 })
240 t.Run("a directory first", func(t *testing.T) {
241 l := newLayers(t, floor, project, nil)
242 if err := os.Mkdir(filepath.Join(l.project, "a.cue"), 0o755); err != nil {
243 t.Fatal(err)
244 }
245 refuse(t, l)
246 })
247}
248
249// edgeRepo is a scratch repository with one base commit, and with makes a
250// head that adds path to it.
251func edgeRepo(t *testing.T, r *rig) (rp *repo, base string, with func(path string) string) {
252 t.Helper()
253 seed := tree{"docs/kept.md": file("seed\n"), "Makefile": file("seed\n")}
254 rp = newRepo(t, r)
255 base = rp.commit("", seed)
256 return rp, base, func(path string) string {
257 files := tree{path: file("added\n")}
258 for p, e := range seed {
259 files[p] = e
260 }
261 return rp.commit(base, files)
262 }
263}
264
265// TestANewlineInAPathIsOnePath holds Diff and Derive to reading a path
266// that holds a newline whole. src/a<newline>b.rs matches the flat and deep
267// classes; a reader splitting it at the newline would find two paths that
268// match no class.
269func TestANewlineInAPathIsOnePath(t *testing.T) {
270 r := newRig(t)
271 m, err := r.read(r.deriverLayers(t, nil))
272 if err != nil {
273 t.Fatal(err)
274 }
275 rp, base, with := edgeRepo(t, r)
276 res, err := r.derive(m, rp.dir, base, with("src/a\nb.rs"))
277 if err != nil {
278 t.Fatal(err)
279 }
280 if !slices.Equal(res.Paths, []string{"src/a\nb.rs"}) || len(res.Unclassified) != 0 {
281 t.Errorf("the deriver read %q, %q unclassified", res.Paths, res.Unclassified)
282 }
283 if got := names(res); !slices.Equal(got, []string{"c-deep", "c-flat"}) {
284 t.Errorf("the deriver requires %q", got)
285 }
286}
287
288// TestAClassAddedAtPolicyRequiringAnUndefinedCheckIsRefused holds
289// composed.Read to refusing a class, added by refining `policy`, that
290// requires a check the composed policy does not define. The schema's
291// cross-check reads the layers' composition, not `policy`, so cue vet
292// passes such a policy, and the reader is what refuses a requirement that
293// nothing could run.
294func TestAClassAddedAtPolicyRequiringAnUndefinedCheckIsRefused(t *testing.T) {
295 r := newRig(t)
296 l := r.deriverLayers(t, map[string]string{"ghost.cue": "package verification\n" +
297 `policy: classes: sneaky: {paths: "sneak/**": true, requires: ghost: true}` + "\n"})
298 if _, err := r.read(l); err == nil || !strings.Contains(err.Error(), "class sneaky requires check ghost, which the composed policy does not define") {
299 t.Errorf("the policy was read: %v", err)
300 }
301}
302
303// TestAClassNamedUnclassifiedIsKeptApart holds composed.Read and Derive to
304// keeping a class named unclassified apart from the unclassified set: a
305// path in the class requires the class's checks, a path no class covers
306// requires the set's, and a check both require is required of each for
307// its own reason.
308func TestAClassNamedUnclassifiedIsKeptApart(t *testing.T) {
309 r := newRig(t)
310 rp, base, with := edgeRepo(t, r)
311 odd, uncovered := with("odd/x"), with("Makefile.new")
312 derive := func(t *testing.T, requires, head string) *Result {
313 t.Helper()
314 m, err := r.read(r.deriverLayers(t, map[string]string{"odd.cue": "package verification\n" +
315 `project: classes: unclassified: {paths: "odd/**": true, requires: "` + requires + `": true}` + "\n"}))
316 if err != nil {
317 t.Fatal(err)
318 }
319 res, err := r.derive(m, rp.dir, base, head)
320 if err != nil {
321 t.Fatal(err)
322 }
323 return res
324 }
325
326 res := derive(t, "c-notes", odd)
327 if len(res.Required) != 1 || res.Required[0].Name != "c-notes" {
328 t.Fatalf("a path in the class requires %q", names(res))
329 }
330 if q := res.Required[0]; q.Pin != composed.Mandatory || !slices.Equal(q.Classes, []string{"unclassified"}) || q.Unclassified {
331 t.Errorf("a path in the class requires c-notes as %+v", q)
332 }
333
334 res = derive(t, "c-notes", uncovered)
335 if len(res.Required) != 1 || res.Required[0].Name != "c-uncovered" {
336 t.Fatalf("an uncovered path requires %q", names(res))
337 }
338 if len(res.Classes) != 0 || !res.Required[0].Unclassified {
339 t.Errorf("an uncovered path matched %q and required %+v", res.Classes, res.Required)
340 }
341
342 res = derive(t, "c-uncovered", odd)
343 if len(res.Required) != 1 || res.Required[0].Name != "c-uncovered" {
344 t.Fatalf("a class sharing the set's check requires %q", names(res))
345 }
346 if q := res.Required[0]; !slices.Equal(q.Classes, []string{"unclassified"}) || q.Unclassified {
347 t.Errorf("a class sharing the set's check requires c-uncovered as %+v", q)
348 }
349}
350
351// TestRejectedPoliciesAndOlderSchemasAreRefused holds composed.Read to
352// refusing what the deriver may not derive from: a policy cue-vet rejects,
353// and a schema older than the deriver, with no cost or no carry modes to
354// read. Read as a policy, either would be one whose checks cost nothing or
355// whose classes carry everywhere.
356func TestRejectedPoliciesAndOlderSchemasAreRefused(t *testing.T) {
357 r := newRig(t)
358 refuse := func(t *testing.T, schema string, l layers) {
359 t.Helper()
360 if m, err := composed.Read(t.Context(), r.cue, schema, l.instance, l.project); err == nil {
361 t.Errorf("the policy was read: %+v", m)
362 }
363 }
364 for _, f := range r.glob(t, "examples/policy/carry/rejected/*.cue") {
365 t.Run(filepath.Base(f), func(t *testing.T) { refuse(t, r.schema, newLayers(t, []string{f}, nil, nil)) })
366 }
367 body, err := os.ReadFile(r.schema)
368 if err != nil {
369 t.Fatal(err)
370 }
371 for name, line := range map[string]string{"costless": "\tcost: *\"quick\" | \"slow\"\n", "modeless": "\n_mode: "} {
372 t.Run(name, func(t *testing.T) {
373 at := bytes.Index(body, []byte(line))
374 if at < 0 {
375 t.Fatalf("the schema has no %q, so this case proves nothing", line)
376 }
377 end := at + 1 + bytes.IndexByte(body[at+1:], '\n')
378 older := filepath.Join(t.TempDir(), "verification.cue")
379 if err := os.WriteFile(older, append(append([]byte{}, body[:at+1]...), body[end+1:]...), 0o644); err != nil {
380 t.Fatal(err)
381 }
382 refuse(t, older, r.deriverLayers(t, nil))
383 })
384 }
385}
386
387func sortedKeys(set map[string]bool) []string {
388 out := make([]string, 0, len(set))
389 for k := range set {
390 out = append(out, k)
391 }
392 sort.Strings(out)
393 return out
394}
395
396// instance is a path made from a glob, which mostly matches it: each `**`
397// segment made none, one or two segments, each `*` some bytes, and each `?`
398// one character. That character is two bytes when it is é, so `?` meets a
399// character that is not one byte. A `*` or a `?` is sometimes made a `/`,
400// which neither may match.
401func instance(glob string, rng *rand.Rand) string {
402 segs := strings.Split(glob, "/")
403 if segs[len(segs)-1] == "" {
404 segs = segs[:len(segs)-1]
405 }
406 stars := []string{"", "x", "x.y", "ü", "\xff", " ", "*", "q.md", "", "x", "x/y"}
407 ones := []string{"q", "é", "\xfe", "?", "q", "/"}
408 var out []string
409 for _, seg := range segs {
410 if seg == "**" {
411 out = append(out, []string{"d", "e.md", "ü"}[:rng.IntN(3)]...)
412 continue
413 }
414 var s strings.Builder
415 for i := 0; i < len(seg); i++ {
416 switch seg[i] {
417 case '*':
418 s.WriteString(stars[rng.IntN(len(stars))])
419 case '?':
420 s.WriteString(ones[rng.IntN(len(ones))])
421 default:
422 s.WriteByte(seg[i])
423 }
424 }
425 out = append(out, s.String())
426 }
427 return strings.Join(out, "/")
428}
429
430// awkward are names chosen for what a reader of paths might get wrong.
431var awkward = []string{
432 "README.md", "a b.md", "-dash.md", "naïve.md", "caf\xe9.md", "tab\there.md",
433 "quote\"d.md", "back\\slash.md", "star*.md", "q?.md", "[br].md", "{x}.md",
434 "deep/a/b/c/d/e.txt", ".hidden", "dir.md/inner", "\xff\xfe/x", "research/notes.txt",
435 "src/x.rs.bak", "docs", "bin/valley", "flake.nix", "nix/checks/derive-unit.sh",
436}
437
438// validPath reports whether git would hold p as a path.
439func validPath(p string) bool {
440 if p == "" || strings.ContainsAny(p, "\x00\n") {
441 return false
442 }
443 for _, seg := range strings.Split(p, "/") {
444 if seg == "" || seg == "." || seg == ".." || strings.EqualFold(seg, ".git") {
445 return false
446 }
447 }
448 return true
449}
450
451// pathPool is what a fixture's cases are drawn from: instances of every
452// glob the policy names, near misses of each, and the awkward names.
453func pathPool(m *composed.Model, rng *rand.Rand) []string {
454 set := map[string]bool{}
455 add := func(p string) {
456 if validPath(p) {
457 set[p] = true
458 }
459 }
460 classes := make([]string, 0, len(m.Classes))
461 for name := range m.Classes {
462 classes = append(classes, name)
463 }
464 sort.Strings(classes)
465 for _, name := range classes {
466 for _, g := range m.Classes[name].Paths {
467 for range 3 {
468 p := instance(g, rng)
469 add(p)
470 add("zz/" + p)
471 add(p + "x")
472 if i := strings.LastIndexByte(p, '/'); i > 0 {
473 add(p[:i] + "/zz" + p[i:])
474 }
475 }
476 }
477 }
478 for _, p := range awkward {
479 add(p)
480 }
481 return sortedKeys(set)
482}
483
484// fits reports whether p can join t: no path of t is a directory of p's,
485// and p is no directory of a path of t.
486func fits(t tree, p string) bool {
487 if _, ok := t[p]; ok {
488 return false
489 }
490 for q := range t {
491 if strings.HasPrefix(p, q+"/") || strings.HasPrefix(q, p+"/") {
492 return false
493 }
494 }
495 return true
496}
497
498// baseTree is about half the pool.
499func baseTree(rng *rand.Rand, pool []string) tree {
500 t := tree{}
501 for _, p := range pool {
502 if rng.IntN(2) == 0 && fits(t, p) {
503 t[p] = file("base " + p + "\n")
504 }
505 }
506 return t
507}
508
509// change is base with one to six changes made to it.
510func change(rng *rand.Rand, base tree, pool []string) tree {
511 t := tree{}
512 for p, e := range base {
513 t[p] = e
514 }
515 existing := func() string {
516 paths := make([]string, 0, len(t))
517 for p := range t {
518 paths = append(paths, p)
519 }
520 sort.Strings(paths)
521 if len(paths) == 0 {
522 return ""
523 }
524 return paths[rng.IntN(len(paths))]
525 }
526 fresh := func() string {
527 for range 20 {
528 if p := pool[rng.IntN(len(pool))]; fits(t, p) {
529 return p
530 }
531 }
532 return ""
533 }
534 for n := range 1 + rng.IntN(6) {
535 switch rng.IntN(5) {
536 case 0: // modify
537 if p := existing(); p != "" {
538 t[p] = file(fmt.Sprintf("edit %d of %s\n", n, p))
539 }
540 case 1: // delete
541 if p := existing(); p != "" {
542 delete(t, p)
543 }
544 case 2: // add
545 if p := fresh(); p != "" {
546 t[p] = file("added " + p + "\n")
547 }
548 case 3: // rename
549 if from := existing(); from != "" {
550 e := t[from]
551 delete(t, from)
552 if to := fresh(); to != "" {
553 t[to] = e
554 } else {
555 t[from] = e
556 }
557 }
558 case 4: // turn into a symbolic link
559 if p := existing(); p != "" {
560 t[p] = entry{mode: "120000", content: "target-of-" + p}
561 }
562 }
563 }
564 return t
565}