gunk-dev/the-valley

composed_test.go

source273a801b2353main's published tip history
7.8 KiB
1package composed
2
3import (
4 "bytes"
5 "errors"
6 "maps"
7 "os"
8 "os/exec"
9 "path/filepath"
10 "strings"
11 "testing"
12)
13
14// layerRepo is a scratch repository with one commit, whose tree holds the
15// files written into it.
16type layerRepo struct {
17 t *testing.T
18 dir string
19 tip string
20}
21
22func newLayerRepo(t *testing.T, files map[string]string) *layerRepo {
23 t.Helper()
24 if _, err := exec.LookPath("git"); err != nil {
25 if os.Getenv("VALLEY_TEST_TOOLS") == "required" {
26 t.Fatal("no git on PATH, and VALLEY_TEST_TOOLS=required")
27 }
28 t.Skip("no git to read a layer with; the composed-unit check provides one")
29 }
30 t.Setenv("HOME", t.TempDir())
31 t.Setenv("GIT_CONFIG_NOSYSTEM", "1")
32 r := &layerRepo{t: t, dir: t.TempDir()}
33 r.git("init", "--quiet", "--initial-branch=main")
34 files["README"] = "a repository\n"
35 for path, body := range files {
36 full := filepath.Join(r.dir, path)
37 if err := os.MkdirAll(filepath.Dir(full), 0o755); err != nil {
38 t.Fatal(err)
39 }
40 if err := os.WriteFile(full, []byte(body), 0o644); err != nil {
41 t.Fatal(err)
42 }
43 }
44 r.git("add", "--all")
45 r.git("-c", "user.name=t", "-c", "user.email=t@localhost", "commit", "--quiet", "-m", "layers")
46 r.tip = r.git("rev-parse", "HEAD")
47 return r
48}
49
50func (r *layerRepo) git(args ...string) string {
51 r.t.Helper()
52 cmd := exec.Command("git", args...)
53 cmd.Dir = r.dir
54 var out, errb bytes.Buffer
55 cmd.Stdout, cmd.Stderr = &out, &errb
56 if err := cmd.Run(); err != nil {
57 r.t.Fatalf("git %s: %v\n%s", strings.Join(args, " "), err, errb.String())
58 }
59 return strings.TrimSpace(out.String())
60}
61
62// lose removes the loose object that path names at the tip, so reading it
63// fails as a damaged repository's read does.
64func (r *layerRepo) lose(path string) {
65 r.t.Helper()
66 oid := r.git("rev-parse", r.tip+":"+path)
67 if err := os.Remove(filepath.Join(r.dir, ".git", "objects", oid[:2], oid[2:])); err != nil {
68 r.t.Fatal(err)
69 }
70}
71
72// project is Project of dir at the tip.
73func (r *layerRepo) project(dir string) (docs map[string]string, note string, err error) {
74 r.t.Helper()
75 path, note, done, err := Project(r.t.Context(), r.dir, r.tip, dir, "composed-test-")
76 defer done()
77 if err != nil {
78 if path != "" {
79 r.t.Errorf("a refusal resolved the layer to %s", path)
80 }
81 return nil, note, err
82 }
83 entries, err := os.ReadDir(path)
84 if err != nil {
85 r.t.Fatal(err)
86 }
87 docs = map[string]string{}
88 for _, e := range entries {
89 body, err := os.ReadFile(filepath.Join(path, e.Name()))
90 if err != nil {
91 r.t.Fatal(err)
92 }
93 docs[e.Name()] = string(body)
94 }
95 return docs, note, nil
96}
97
98const addsNothing = "package verification\n"
99
100// A project layer is the *.cue entries directly in its directory at the
101// tip, dotfiles among them. A
102// directory that is not there, or holds no *.cue, composes the floor
103// alone.
104func TestProjectReadsTheLayerAtTheTip(t *testing.T) {
105 r := newLayerRepo(t, map[string]string{
106 "policy/project/a.cue": "package verification // a\n",
107 "policy/project/.hidden.cue": "package verification // hidden\n",
108 "policy/project/notes.md": "not a document\n",
109 "policy/project/sub/b.cue": "package verification // nested\n",
110 "policy/dotted/.only.cue": "package verification // only\n",
111 "policy/prose/notes.md": "not a document\n",
112 })
113 for _, c := range []struct {
114 dir string
115 want map[string]string
116 alone bool
117 }{
118 {"policy/project", map[string]string{"a.cue": "package verification // a\n", ".hidden.cue": "package verification // hidden\n"}, false},
119 // Present, and the composer reads no document in it (layer), so
120 // composing it is refused.
121 {"policy/dotted", map[string]string{".only.cue": "package verification // only\n"}, false},
122 {"policy/missing", map[string]string{"adds-nothing.cue": addsNothing}, true},
123 {"policy/prose", map[string]string{"adds-nothing.cue": addsNothing}, true},
124 {"README", map[string]string{"adds-nothing.cue": addsNothing}, true},
125 } {
126 t.Run(c.dir, func(t *testing.T) {
127 docs, note, err := r.project(c.dir)
128 if err != nil {
129 t.Fatal(err)
130 }
131 if (note != "") != c.alone {
132 t.Errorf("the note reads %q", note)
133 }
134 if !maps.Equal(docs, c.want) {
135 t.Errorf("the layer holds %q, not %q", docs, c.want)
136 }
137 })
138 }
139}
140
141// A directory is named and never matched: policy/proj* is that directory,
142// and not policy/projX beside it.
143func TestProjectReadsADirectoryNamedLikeAPatternAsNamed(t *testing.T) {
144 r := newLayerRepo(t, map[string]string{
145 "policy/proj*/one.cue": "package verification // one\n",
146 "policy/projX/decoy.cue": "package verification // decoy\n",
147 ":(glob)p/decoy.cue": "package verification // magic\n",
148 "p/two.cue": "package verification // two\n",
149 })
150 docs, _, err := r.project("policy/proj*")
151 if err != nil || !maps.Equal(docs, map[string]string{"one.cue": "package verification // one\n"}) {
152 t.Errorf("policy/proj* read as %q, %v", docs, err)
153 }
154 // Pathspec magic is a name like any other.
155 docs, _, err = r.project(":(glob)p")
156 if err != nil || !maps.Equal(docs, map[string]string{"decoy.cue": "package verification // magic\n"}) {
157 t.Errorf(":(glob)p read as %q, %v", docs, err)
158 }
159}
160
161// A layer that cannot be read is refused, never composed as the floor
162// alone: a tip that names a missing object, a layer whose tree is gone, a
163// document whose blob is gone, and a *.cue entry that is a directory,
164// which reading it as a blob refuses.
165func TestProjectRefusesALayerThatCannotBeRead(t *testing.T) {
166 files := map[string]string{
167 "policy/project/a.cue": "package verification\n",
168 "policy/odd/x.cue/inner.cue": "package verification\n",
169 "policy/odd/y.cue": "package verification\n",
170 }
171 cases := []struct {
172 name, dir string
173 damage func(r *layerRepo)
174 }{
175 {"a missing tip", "policy/project", func(r *layerRepo) { r.tip = strings.Repeat("0", len(r.tip)-1) + "1" }},
176 {"the layer's tree lost", "policy/project", func(r *layerRepo) { r.lose("policy/project") }},
177 {"a document's blob lost", "policy/project", func(r *layerRepo) { r.lose("policy/project/a.cue") }},
178 {"a *.cue directory", "policy/odd", func(*layerRepo) {}},
179 }
180 for _, c := range cases {
181 t.Run(c.name, func(t *testing.T) {
182 r := newLayerRepo(t, maps.Clone(files))
183 c.damage(r)
184 docs, note, err := r.project(c.dir)
185 if err == nil {
186 t.Fatalf("an unreadable layer resolved to %q, %q", docs, note)
187 }
188 if note != "" {
189 t.Errorf("a refusal noted %q", note)
190 }
191 for _, want := range []string{c.dir, r.dir, r.tip} {
192 if !strings.Contains(err.Error(), want) {
193 t.Errorf("the refusal %q does not name %s", err, want)
194 }
195 }
196 })
197 }
198}
199
200// A floor that cannot be read is refused as what it is, and not as a floor
201// that is not there, which a reader may look for elsewhere (ErrNoFloor).
202func TestOpenTellsAnUnreadableFloorFromAnAbsentOne(t *testing.T) {
203 files := map[string]string{
204 "policy/instance/floor.cue": "package verification\n",
205 "policy/prose/notes.md": "not a document\n",
206 }
207 for _, c := range []struct {
208 dir string
209 lose string
210 noFloor bool
211 mentioned string
212 }{
213 {"policy/missing", "", true, "has no policy/missing/"},
214 {"policy/prose", "", true, "holds no *.cue in policy/prose/"},
215 {"policy/instance", "policy/instance", false, "reading policy/instance/"},
216 {"policy/instance", "policy/instance/floor.cue", false, "reading policy/instance/floor.cue"},
217 } {
218 t.Run(c.dir+" "+c.lose, func(t *testing.T) {
219 r := newLayerRepo(t, maps.Clone(files))
220 if c.lose != "" {
221 r.lose(c.lose)
222 }
223 dir, done, err := Floor{Repo: r.dir, Ref: "refs/heads/main", Dir: c.dir}.Open(t.Context(), "composed-test-")
224 defer done()
225 if err == nil {
226 t.Fatalf("the floor resolved to %s", dir)
227 }
228 if errors.Is(err, ErrNoFloor) != c.noFloor {
229 t.Errorf("the refusal %q is read as no floor: %v", err, !c.noFloor)
230 }
231 if !strings.Contains(err.Error(), c.mentioned) {
232 t.Errorf("the refusal %q does not say %q", err, c.mentioned)
233 }
234 })
235 }
236}