gunk-dev/the-valley

policy_test.go

source37f58f5c0dcfmain's published tip history
8.8 KiB
1package main
2
3// The policy bridge, where this program is coupled to two others: the
4// deriver's output, and the window a policy writes down. Both are pinned
5// here rather than assumed.
6
7import (
8 "os"
9 "path/filepath"
10 "reflect"
11 "strings"
12 "testing"
13 "time"
14)
15
16func TestDeriverOutputIsRead(t *testing.T) {
17 out := `abc1234..def5678: 3 changed path(s)
18policy: instance + policy
19classes matched: code, prose
20
21required checks:
22 code-build mandatory code
23 prose-format default prose, knowledge
24
25unclassified: 1 path(s) matched no class
26 odd.txt
27`
28 d, err := parseDerived(out)
29 if err != nil {
30 t.Fatal(err)
31 }
32 if !d.classes["code"] || !d.classes["prose"] || len(d.classes) != 2 {
33 t.Fatalf("classes = %v", d.classes)
34 }
35 if got := strings.Join(d.requires["prose-format"], "+"); got != "prose+knowledge" {
36 t.Fatalf("prose-format required by %q", got)
37 }
38 if got := strings.Join(d.requires["code-build"], "+"); got != "code" {
39 t.Fatalf("code-build required by %q", got)
40 }
41 if len(d.requires) != 2 {
42 t.Fatalf("required = %v", d.requires)
43 }
44}
45
46// The deriver ends its report with what each owed check costs. Those lines
47// group the owed checks and owe nothing, so a report carrying them reads as
48// exactly the report without them โ€” with an unclassified block between
49// the table and the summary, and with the summary straight after the table.
50func TestTheCostSummaryChangesNothingRead(t *testing.T) {
51 table := `abc1234..def5678: 2 changed path(s)
52policy: instance + policy
53classes matched: code, prose
54
55required checks:
56 code-build mandatory code
57 vm-test default code
58 prose-format default prose, knowledge
59`
60 unclassified := `
61unclassified: 1 path(s) matched no class
62 odd.txt
63`
64 summary := `
65quick: code-build, prose-format
66slow: vm-test
67`
68 for _, before := range []string{table, table + unclassified} {
69 want, err := parseDerived(before)
70 if err != nil {
71 t.Fatal(err)
72 }
73 if len(want.requires) != 3 || len(want.classes) != 2 {
74 t.Fatalf("the report without a summary reads as %+v", want)
75 }
76 got, err := parseDerived(before + summary)
77 if err != nil {
78 t.Fatal(err)
79 }
80 if !reflect.DeepEqual(got, want) {
81 t.Errorf("with the cost summary, the report reads as %+v, not %+v", got, want)
82 }
83 }
84}
85
86// A deriver that fails partway and still exits zero prints something that
87// is not a whole report. Read as one, each of these owes nothing, so each
88// is refused.
89func TestAPartialReportIsRefused(t *testing.T) {
90 for _, c := range []struct{ name, out string }{
91 {"a required-checks heading with no checks under it", `abc1234..def5678: 2 changed path(s)
92policy: instance + policy
93classes matched: code
94
95required checks:
96
97quick: none
98slow: none
99`},
100 {"a required-checks heading that ends the output", `abc1234..def5678: 2 changed path(s)
101policy: instance + policy
102classes matched: code
103
104required checks:
105`},
106 {"no required-checks section", `abc1234..def5678: 2 changed path(s)
107policy: instance + policy
108classes matched: code
109`},
110 {"no header", `policy: instance + policy
111classes matched: code
112
113required checks:
114 code-build mandatory code
115`},
116 {"nothing at all", ``},
117 {"changed paths and no class", `abc1234..def5678: 2 changed path(s)
118policy: instance + policy
119classes matched: none
120
121required checks: none
122`},
123 {"no changed paths and a class", `abc1234..def5678: 0 changed path(s)
124policy: instance + policy
125classes matched: code
126
127required checks:
128 code-build mandatory code
129`},
130 } {
131 if d, err := parseDerived(c.out); err == nil {
132 t.Errorf("%s: read as %+v", c.name, d)
133 }
134 }
135}
136
137// The report of a diff with nothing in it is still a whole report, and it
138// owes nothing.
139func TestAnEmptyDiffReadsAsOwingNothing(t *testing.T) {
140 d, err := parseDerived(`abc1234..abc1234: 0 changed path(s)
141policy: instance + policy
142classes matched: none
143
144required checks: none
145`)
146 if err != nil {
147 t.Fatal(err)
148 }
149 if d.paths != 0 || len(d.classes) != 0 || len(d.requires) != 0 {
150 t.Fatalf("an empty diff reads as %+v", d)
151 }
152}
153
154// A report of no changed paths is believed only when git agrees. The
155// stand-in deriver prints a whole, well-formed report of no changed paths โ€”
156// what a deriver whose diff failed silently would print โ€” and the
157// derivation is read over two commits with one tree, and refused over two
158// commits whose trees differ.
159func TestAReportOfNoChangedPathsIsCheckedAgainstGit(t *testing.T) {
160 repo := t.TempDir()
161 run := func(args ...string) string {
162 t.Helper()
163 out, err := git(repo, append([]string{"-c", "user.name=t", "-c", "user.email=t@localhost"}, args...)...)
164 if err != nil {
165 t.Fatal(err)
166 }
167 return strings.TrimSpace(out)
168 }
169 run("init", "--quiet")
170 run("commit", "--quiet", "--allow-empty", "-m", "one")
171 one := run("rev-parse", "HEAD")
172 run("commit", "--quiet", "--allow-empty", "-m", "the same tree")
173 same := run("rev-parse", "HEAD")
174 if err := os.WriteFile(filepath.Join(repo, "changed.txt"), []byte("x\n"), 0o644); err != nil {
175 t.Fatal(err)
176 }
177 run("add", "changed.txt")
178 run("commit", "--quiet", "-m", "a change")
179 changed := run("rev-parse", "HEAD")
180
181 deriver := filepath.Join(t.TempDir(), "valley")
182 report := `printf '%s\n' 'x..y: 0 changed path(s)' 'policy: a + b' 'classes matched: none' '' 'required checks: none'`
183 if err := os.WriteFile(deriver, []byte("#!/bin/sh\n"+report+"\n"), 0o755); err != nil {
184 t.Fatal(err)
185 }
186 p := policySource{valley: deriver}
187 tip := &worktree{dir: repo}
188 if _, err := p.derive(tip, one, same); err != nil {
189 t.Fatalf("an empty diff reported as empty was refused: %v", err)
190 }
191 if d, err := p.derive(tip, one, changed); err == nil {
192 t.Fatalf("a change reported as touching nothing was read as %+v", d)
193 }
194}
195
196func TestValidityWindowsAreReadAsThePolicyWritesThem(t *testing.T) {
197 for _, c := range []struct {
198 in string
199 want time.Duration
200 }{
201 {"", 0},
202 {"30s", 30 * time.Second},
203 {"15m", 15 * time.Minute},
204 {"6h", 6 * time.Hour},
205 {"2d", 48 * time.Hour},
206 } {
207 got, err := parseWindow(c.in)
208 if err != nil || got != c.want {
209 t.Errorf("parseWindow(%q) = %v, %v; want %v", c.in, got, err, c.want)
210 }
211 }
212}
213
214// Each layer's absence defaults in the safe direction of that layer's job,
215// and the two directions are opposite (dcr-f41f718). Both are pinned here,
216// because the value of the rule is that neither is the other.
217
218func TestATargetWithNoProjectLayerIsJudgedUnderTheFloorAlone(t *testing.T) {
219 tip := &worktree{dir: t.TempDir()}
220 p := policySource{projectDir: "policy/project"}
221 done, err := p.openProject(tip)
222 if err != nil {
223 t.Fatal(err)
224 }
225 defer done()
226 if p.note == "" {
227 t.Fatal("the pass said nothing about composing the floor alone")
228 }
229 // What the deriver and the composer are handed is a layer that adds
230 // nothing, not a directory that is not there.
231 docs, err := filepath.Glob(filepath.Join(p.project, "*.cue"))
232 if err != nil || len(docs) != 1 {
233 t.Fatalf("the resolved project layer holds %v (%v)", docs, err)
234 }
235 if body, err := os.ReadFile(docs[0]); err != nil || strings.TrimSpace(string(body)) != "package verification" {
236 t.Fatalf("the layer that adds nothing reads %q (%v)", body, err)
237 }
238 done()
239 if _, err := os.Stat(p.project); !os.IsNotExist(err) {
240 t.Fatalf("the pass left its scratch layer behind: %v", err)
241 }
242}
243
244func TestATargetsOwnProjectLayerIsUsedWhereItIs(t *testing.T) {
245 tip := &worktree{dir: t.TempDir()}
246 own := filepath.Join(tip.dir, "policy/project")
247 if err := os.MkdirAll(own, 0o755); err != nil {
248 t.Fatal(err)
249 }
250 if err := os.WriteFile(filepath.Join(own, "policy.cue"), []byte("package verification\n"), 0o644); err != nil {
251 t.Fatal(err)
252 }
253 p := policySource{projectDir: "policy/project"}
254 done, err := p.openProject(tip)
255 if err != nil {
256 t.Fatal(err)
257 }
258 defer done()
259 if p.project != own {
260 t.Fatalf("the project layer resolved to %s, not to %s", p.project, own)
261 }
262 if p.note != "" {
263 t.Fatalf("an ordinary composition said %q", p.note)
264 }
265}
266
267func TestAFloorThatIsNotThereIsRefused(t *testing.T) {
268 // The materialized source, which is the one a test can drive without a
269 // repository. The repository source refuses the same way, and the e2e
270 // observes it there.
271 _, done, err := instanceLayer{path: t.TempDir()}.open()
272 defer done()
273 if err == nil {
274 t.Fatal("a floor directory with no documents in it was accepted")
275 }
276 if !strings.Contains(err.Error(), floorless) {
277 t.Fatalf("the refusal reads %q", err)
278 }
279}
280
281func TestARefusalIsReadAsTheSentenceItIs(t *testing.T) {
282 // attest reports what it checked, then refuses, then elaborates. The
283 // sentence is the refusal; the elaboration is not.
284 out := `note /tmp/x.note
285text ok (411 bytes signed)
286attest: tree digest mismatch: the statement is about a different tree
287 recorded aaaa
288 found bbbb
289`
290 if got := refusalLine(out); got != "tree digest mismatch: the statement is about a different tree" {
291 t.Fatalf("refusalLine = %q", got)
292 }
293 if got := refusalLine("something with no prefix at all\n"); got != "something with no prefix at all" {
294 t.Fatalf("refusalLine fallback = %q", got)
295 }
296}