gunk-dev/the-valley

checks_test.go

source9ea588cfdefamain's published tip history
7.6 KiB
1package main
2
3import (
4 "bytes"
5 "encoding/base64"
6 "encoding/json"
7 "os"
8 "os/exec"
9 "path/filepath"
10 "reflect"
11 "strings"
12 "testing"
13)
14
15// checksRepo is a repository with a base and a head commit, and a policy
16// beside it, for the checks verb's tests.
17type checksRepo struct {
18 schema, instance, project, base, head string
19}
20
21func newChecksRepo(t *testing.T) *checksRepo {
22 t.Helper()
23 if _, err := exec.LookPath("cue"); err != nil {
24 if os.Getenv("VALLEY_TEST_TOOLS") == "required" {
25 t.Fatal("no cue on PATH, and VALLEY_TEST_TOOLS=required")
26 }
27 t.Skip("no cue to compose a policy with; the nix check provides one")
28 }
29 schema, err := filepath.Abs(filepath.Join("..", "schema", "verification.cue"))
30 if err != nil {
31 t.Fatal(err)
32 }
33 dir := t.TempDir()
34 t.Setenv("HOME", dir)
35 t.Setenv("GIT_CONFIG_NOSYSTEM", "1")
36 r := &checksRepo{schema: schema, instance: filepath.Join(dir, "instance"), project: filepath.Join(dir, "project")}
37 write := func(path, body string) {
38 t.Helper()
39 if err := os.MkdirAll(filepath.Dir(path), 0o755); err != nil {
40 t.Fatal(err)
41 }
42 if err := os.WriteFile(path, []byte(body), 0o644); err != nil {
43 t.Fatal(err)
44 }
45 }
46 write(filepath.Join(r.instance, "floor.cue"), `package verification
47floor: {
48 checks: "c-docs": {runner: "nix", attribute: "c-docs"}
49 checks: "c-live": {runner: "command", command: "probe --live", validity: "1h", cost: "slow"}
50 classes: docs: {paths: "docs/**": true, requires: "c-docs": true}
51 classes: run: {paths: "run/**": true, requires: "c-live": true, carry: exact: true}
52 unclassified: "c-docs": true
53}
54`)
55 write(filepath.Join(r.project, "policy.cue"), "package verification\n")
56 work := filepath.Join(dir, "work")
57 git := func(args ...string) string {
58 t.Helper()
59 cmd := exec.Command("git", args...)
60 cmd.Dir = work
61 out, err := cmd.CombinedOutput()
62 if err != nil {
63 t.Fatalf("git %s: %v\n%s", strings.Join(args, " "), err, out)
64 }
65 return strings.TrimSpace(string(out))
66 }
67 if err := os.Mkdir(work, 0o755); err != nil {
68 t.Fatal(err)
69 }
70 git("init", "--quiet", "--initial-branch=main")
71 git("config", "user.name", "checks-test")
72 git("config", "user.email", "checks-test@localhost")
73 write(filepath.Join(work, "docs", "a.md"), "base\n")
74 git("add", "-A")
75 git("commit", "--quiet", "-m", "base")
76 r.base = git("rev-parse", "HEAD")
77 write(filepath.Join(work, "run", "caf\xe9.sh"), "new\n")
78 write(filepath.Join(work, "docs", "new\nline.md"), "new\n")
79 write(filepath.Join(work, "Makefile"), "new\n")
80 git("add", "-A")
81 git("commit", "--quiet", "-m", "head")
82 r.head = git("rev-parse", "HEAD")
83 t.Chdir(work)
84 return r
85}
86
87func (r *checksRepo) checks(args ...string) (stdout, stderr string, code int) {
88 var out, errb bytes.Buffer
89 code = run(append([]string{"checks"}, args...), &out, &errb)
90 return out.String(), errb.String(), code
91}
92
93// TestChecksPrintsTheDerivation holds the valley-checks/v1 document to the
94// derivation: every path as git gave it, a path that is not UTF-8 in
95// base64, and each required check with its classes, pin, cost and how it
96// is run.
97func TestChecksPrintsTheDerivation(t *testing.T) {
98 r := newChecksRepo(t)
99 out, stderr, code := r.checks("--schema", r.schema, "--instance", r.instance, "--project="+r.project, r.base, "HEAD")
100 if code != 0 {
101 t.Fatalf("checks exited %d: %s", code, stderr)
102 }
103 type path struct {
104 Path *string `json:"path"`
105 Base64 *string `json:"base64"`
106 }
107 var doc struct {
108 Schema string `json:"schema"`
109 Base string `json:"base"`
110 Head string `json:"head"`
111 PolicyDigest string `json:"policy_digest"`
112 Paths []path `json:"paths"`
113 Classes []string
114 UnclassifiedPaths []path `json:"unclassified_paths"`
115 Carry string
116 Required []map[string]any
117 Follows []map[string]any
118 }
119 dec := json.NewDecoder(strings.NewReader(out))
120 dec.DisallowUnknownFields()
121 if err := dec.Decode(&doc); err != nil {
122 t.Fatalf("the document does not read: %v\n%s", err, out)
123 }
124 bytesOf := func(ps []path) []string {
125 var got []string
126 for _, p := range ps {
127 switch {
128 case p.Path != nil && p.Base64 == nil:
129 got = append(got, *p.Path)
130 case p.Base64 != nil && p.Path == nil:
131 b, err := base64.StdEncoding.Strict().DecodeString(*p.Base64)
132 if err != nil {
133 t.Fatal(err)
134 }
135 got = append(got, string(b))
136 default:
137 t.Errorf("a path is %+v, not one of path and base64", p)
138 }
139 }
140 return got
141 }
142 if doc.Schema != "valley-checks/v1" || doc.Base != r.base || doc.Head != r.head || len(doc.PolicyDigest) != 64 {
143 t.Errorf("schema %q, base %q, head %q, digest %q", doc.Schema, doc.Base, doc.Head, doc.PolicyDigest)
144 }
145 if got, want := bytesOf(doc.Paths), []string{"Makefile", "docs/new\nline.md", "run/caf\xe9.sh"}; !reflect.DeepEqual(got, want) {
146 t.Errorf("paths = %q", got)
147 }
148 if !strings.Contains(out, `"base64": "`+base64.StdEncoding.EncodeToString([]byte("run/caf\xe9.sh"))+`"`) {
149 t.Error("the path that is not UTF-8 is not in base64")
150 }
151 if got := bytesOf(doc.UnclassifiedPaths); !reflect.DeepEqual(got, []string{"Makefile"}) {
152 t.Errorf("unclassified paths = %q", got)
153 }
154 if !reflect.DeepEqual(doc.Classes, []string{"docs", "run"}) || doc.Carry != "exact" {
155 t.Errorf("classes %q, carry %q", doc.Classes, doc.Carry)
156 }
157 want := []map[string]any{
158 {"name": "c-docs", "classes": []any{"docs"}, "unclassified": true, "pin": "mandatory", "cost": "quick", "runner": "nix", "attribute": "c-docs"},
159 {"name": "c-live", "classes": []any{"run"}, "unclassified": false, "pin": "mandatory", "cost": "slow", "runner": "command", "command": "probe --live", "validity": "1h"},
160 }
161 if !reflect.DeepEqual(doc.Required, want) {
162 t.Errorf("required = %v", doc.Required)
163 }
164
165 // The same two commits with nothing between them require nothing, and
166 // every list is still a list.
167 out, _, code = r.checks("--schema", r.schema, "--instance", r.instance, "--project", r.project, r.head, r.head)
168 for _, field := range []string{`"paths": []`, `"classes": []`, `"unclassified_paths": []`, `"required": []`, `"follows": []`, `"carry": "same-paths"`} {
169 if code != 0 || !strings.Contains(out, field) {
170 t.Errorf("an empty change's document has no %s:\n%s", field, out)
171 }
172 }
173}
174
175// TestChecksPrintsNothingWhenItFails holds the verb to printing nothing on
176// stdout when it derives nothing, and to saying why.
177func TestChecksPrintsNothingWhenItFails(t *testing.T) {
178 r := newChecksRepo(t)
179 broken := t.TempDir()
180 if err := os.WriteFile(filepath.Join(broken, "policy.cue"), []byte("package verification\nproject: classes: x: requires: nothing: true\n"), 0o644); err != nil {
181 t.Fatal(err)
182 }
183 for _, c := range []struct {
184 name string
185 args []string
186 says string
187 }{
188 {"no project layer named", []string{"--instance", r.instance, r.base, r.head}, "usage: valley-go checks"},
189 {"one commit", []string{"--instance", r.instance, "--project", r.project, r.head}, "usage: valley-go checks"},
190 {"an unknown option", []string{"--names", "--instance", r.instance, "--project", r.project, r.base, r.head}, "usage: valley-go checks"},
191 {"no such base", []string{"--instance", r.instance, "--project", r.project, "nowhere", r.head}, "no such commit: nowhere"},
192 {"a layer that does not compose", []string{"--instance", r.instance, "--project", broken, r.base, r.head}, "do not compose"},
193 {"no schema there", []string{"--schema", filepath.Join(broken, "none.cue"), "--instance", r.instance, "--project", r.project, r.base, r.head}, "no policy schema at"},
194 } {
195 args := c.args
196 if !strings.HasPrefix(c.name, "no schema") {
197 args = append([]string{"--schema", r.schema}, args...)
198 }
199 out, stderr, code := r.checks(args...)
200 if code == 0 || out != "" || !strings.Contains(stderr, c.says) {
201 t.Errorf("%s: exit %d, stdout %q, stderr %q", c.name, code, out, stderr)
202 }
203 }
204}