Debian Codegraph @

api/krusty/accumulation_test.go

raw
1 // Copyright 2019 The Kubernetes Authors.
2 // SPDX-License-Identifier: Apache-2.0
3
4 package krusty_test
5
6 import (
7 "fmt"
8 "net/http"
9 "net/http/httptest"
10 "path/filepath"
11 "regexp"
12 "strings"
13 "testing"
14
15 "github.com/stretchr/testify/require"
16 . "sigs.k8s.io/kustomize/api/internal/target"
17 "sigs.k8s.io/kustomize/api/konfig"
18 "sigs.k8s.io/kustomize/api/krusty"
19 kusttest_test "sigs.k8s.io/kustomize/api/testutils/kusttest"
20 )
21
22 const validResource = `
23 apiVersion: v1
24 kind: Service
25 metadata:
26 name: myService
27 spec:
28 selector:
29 backend: bungie
30 ports:
31 - port: 7002
32 `
33
34 const invalidResource = `apiVersion: v1
35 kind: Service
36 metadata:
37 name: kapacitor
38 labels:
39 app.kubernetes.io/name: tick-kapacitor
40 spec:
41 selector:
42 app.kubernetes.io/name: tick-kapacitor
43 - name: http
44 port: 9092
45 protocol: TCP
46 type: ClusterIP`
47
48 func TestTargetMustHaveKustomizationFile(t *testing.T) {
49 th := kusttest_test.MakeHarness(t)
50 th.WriteF("service.yaml", `
51 apiVersion: v1
52 kind: Service
53 metadata:
54 name: aService
55 `)
56 th.WriteF("deeper/service.yaml", `
57 apiVersion: v1
58 kind: Service
59 metadata:
60 name: anotherService
61 `)
62 err := th.RunWithErr(".", th.MakeDefaultOptions())
63 if err == nil {
64 t.Fatalf("expected an error")
65 }
66 if !IsMissingKustomizationFileError(err) {
67 t.Fatalf("unexpected error: %q", err)
68 }
69 }
70
71 func TestTargetMustHaveOnlyOneKustomizationFile(t *testing.T) {
72 th := kusttest_test.MakeHarness(t)
73 for _, n := range konfig.RecognizedKustomizationFileNames() {
74 th.WriteF(filepath.Join(".", n), `
75 apiVersion: kustomize.config.k8s.io/v1beta1
76 kind: Kustomization
77 `)
78 }
79 err := th.RunWithErr(".", th.MakeDefaultOptions())
80 if err == nil {
81 t.Fatalf("expected an error")
82 }
83 if !strings.Contains(err.Error(), "Found multiple kustomization files") {
84 t.Fatalf("unexpected error: %q", err)
85 }
86 }
87
88 func TestBaseMustHaveKustomizationFile(t *testing.T) {
89 th := kusttest_test.MakeHarness(t)
90 th.WriteK(".", `
91 resources:
92 - base
93 `)
94 th.WriteF("base/service.yaml", validResource)
95 err := th.RunWithErr(".", th.MakeDefaultOptions())
96 if err == nil {
97 t.Fatalf("expected an error")
98 }
99 if !strings.Contains(err.Error(), "accumulating resources") {
100 t.Fatalf("unexpected error: %q", err)
101 }
102 }
103
104 func TestResourceNotFound(t *testing.T) {
105 th := kusttest_test.MakeHarness(t)
106 th.WriteK(".", `
107 resources:
108 - deployment.yaml
109 `)
110 err := th.RunWithErr(".", th.MakeDefaultOptions())
111 if err == nil {
112 t.Fatalf("expected an error")
113 }
114 if !strings.Contains(err.Error(), "accumulating resources") {
115 t.Fatalf("unexpected error: %q", err)
116 }
117 }
118
119 func TestResourceHasAnchor(t *testing.T) {
120 th := kusttest_test.MakeHarness(t)
121 th.WriteK(".", `
122 resources:
123 - ingress.yaml
124 `)
125 th.WriteF("ingress.yaml", `
126 apiVersion: networking.k8s.io/v1
127 kind: Ingress
128 metadata:
129 name: blog
130 spec:
131 tls:
132 - hosts:
133 - xyz.me
134 - www.xyz.me
135 secretName: cert-tls
136 rules:
137 - host: xyz.me
138 http: &xxx_rules
139 paths:
140 - path: /
141 pathType: Prefix
142 backend:
143 service:
144 name: service
145 port:
146 number: 80
147 - host: www.xyz.me
148 http: *xxx_rules
149 `)
150 m := th.Run(".", th.MakeDefaultOptions())
151 th.AssertActualEqualsExpected(m, `
152 apiVersion: networking.k8s.io/v1
153 kind: Ingress
154 metadata:
155 name: blog
156 spec:
157 rules:
158 - host: xyz.me
159 http:
160 paths:
161 - backend:
162 service:
163 name: service
164 port:
165 number: 80
166 path: /
167 pathType: Prefix
168 - host: www.xyz.me
169 http:
170 paths:
171 - backend:
172 service:
173 name: service
174 port:
175 number: 80
176 path: /
177 pathType: Prefix
178 tls:
179 - hosts:
180 - xyz.me
181 - www.xyz.me
182 secretName: cert-tls
183 `)
184 }
185
186 func TestAccumulateResourcesErrors(t *testing.T) {
187 type testcase struct {
188 name string
189 resource string
190 // resourceFunc generates a resource string using the URL to the local
191 // test server (optional).
192 resourceFunc func(string) string
193 // resourceServerSetup configures the local test server (optional).
194 resourceServerSetup func(*http.ServeMux)
195 isAbsolute bool
196 files map[string]string
197 // errFile, errDir are regex for the expected error message output
198 // when kustomize tries to accumulate resource as file and dir,
199 // respectively. The test substitutes occurrences of "%s" in the
200 // error strings with the absolute path where kustomize looks for it.
201 errFile, errDir string
202 }
203 populateAbsolutePaths := func(tc testcase, dir string) testcase {
204 filePaths := make(map[string]string, len(tc.files)+1)
205 for file, content := range tc.files {
206 filePaths[filepath.Join(dir, file)] = content
207 }
208 resourcePath := filepath.Join(dir, tc.resource)
209 if tc.isAbsolute {
210 tc.resource = resourcePath
211 }
212 filePaths[filepath.Join(dir, "kustomization.yaml")] = fmt.Sprintf(`
213 resources:
214 - %s
215 `, tc.resource)
216 tc.files = filePaths
217 regPath := regexp.QuoteMeta(resourcePath)
218 tc.errFile = strings.ReplaceAll(tc.errFile, "%s", regPath)
219 tc.errDir = strings.ReplaceAll(tc.errDir, "%s", regPath)
220 return tc
221 }
222 buildError := func(tc testcase) string {
223 const (
224 prefix = "accumulating resources"
225 filePrefixf = "accumulating resources from '%s'"
226 fileWrapperIfDirf = "accumulation err='%s'"
227 separator = ": "
228 )
229 parts := []string{
230 prefix,
231 strings.Join([]string{
232 fmt.Sprintf(filePrefixf, regexp.QuoteMeta(tc.resource)),
233 tc.errFile,
234 }, separator),
235 }
236 if tc.errDir != "" {
237 parts[1] = fmt.Sprintf(fileWrapperIfDirf, parts[1])
238 parts = append(parts, tc.errDir)
239 }
240 return strings.Join(parts, separator)
241 }
242 for _, test := range []testcase{
243 {
244 name: "remote file not considered repo",
245 resourceFunc: func(url string) string {
246 return fmt.Sprintf("%s/segments-too-few-to-be-repo", url)
247 },
248 resourceServerSetup: func(server *http.ServeMux) {
249 server.HandleFunc("/", func(out http.ResponseWriter, req *http.Request) {
250 out.WriteHeader(http.StatusNotFound)
251 })
252 },
253 // It's acceptable for the error output of a remote file-like
254 // resource to not indicate the resource's status as a
255 // local directory. Though it is possible for a remote file-like
256 // resource to be a local directory, it is very unlikely.
257 errFile: `HTTP Error: status code 404 \(Not Found\)\z`,
258 },
259 {
260 name: "remote file qualifies as repo",
261 resourceFunc: func(url string) string {
262 return fmt.Sprintf("%s/long/enough/to/have/org/and/repo", url)
263 },
264 resourceServerSetup: func(server *http.ServeMux) {
265 server.HandleFunc("/", func(out http.ResponseWriter, req *http.Request) {
266 out.WriteHeader(http.StatusInternalServerError)
267 })
268 },
269 // TODO(4788): This error message is technically wrong. Just
270 // because we fail to GET a resource does not mean the resource is
271 // not a remote file. We should return the GET status code as well.
272 errFile: "URL is a git repository",
273 errDir: `failed to run \S+/git fetch --depth=1 .+`,
274 },
275 {
276 name: "local file qualifies as repo",
277 // The .example top level domain is reserved for example purposes,
278 // see RFC 2606.
279 resource: "[email protected]/configs/base",
280 errFile: `evalsymlink failure on '%s' .+`,
281 errDir: `failed to run \S+/git fetch --depth=1 .+`,
282 },
283 {
284 name: "relative path does not exist",
285 resource: "file-or-directory",
286 errFile: `evalsymlink failure on '%s' .+`,
287 errDir: `must build at directory: not a valid directory: evalsymlink failure .+`,
288 },
289 {
290 name: "absolute path does not exist",
291 resource: "file-or-directory",
292 isAbsolute: true,
293 errFile: `evalsymlink failure on '%s' .+`,
294 errDir: `new root '%s' cannot be absolute`,
295 },
296 {
297 name: "relative file violates restrictions",
298 resource: "../base/resource.yaml",
299 files: map[string]string{
300 "../base/resource.yaml": validResource,
301 },
302 errFile: "security; file '%s' is not in or below .+",
303 // TODO(4348): Over-inclusion of directory error message when we
304 // know resource is file.
305 errDir: "must build at directory: '%s': file is not directory",
306 },
307 {
308 name: "absolute file violates restrictions",
309 resource: "../base/resource.yaml",
310 isAbsolute: true,
311 files: map[string]string{
312 "../base/resource.yaml": validResource,
313 },
314 errFile: "security; file '%s' is not in or below .+",
315 // TODO(4348): Over-inclusion of directory error message when we
316 // know resource is file.
317 errDir: `new root '%s' cannot be absolute`,
318 },
319 {
320 name: "malformed yaml yields an error",
321 resource: "service.yaml",
322 files: map[string]string{
323 "service.yaml": invalidResource,
324 },
325 errFile: "MalformedYAMLError",
326 },
327 } {
328 t.Run(test.name, func(t *testing.T) {
329 if test.resourceFunc != nil {
330 // Configure test server handler
331 handler := http.NewServeMux()
332 if test.resourceServerSetup != nil {
333 test.resourceServerSetup(handler)
334 }
335 // Start test server
336 svr := httptest.NewServer(handler)
337 defer svr.Close()
338 // Generate resource with test server address
339 test.resource = test.resourceFunc(svr.URL)
340 }
341
342 // Should use real file system to indicate that we are creating
343 // new temporary directories on disk when we attempt to fetch repos.
344 fs, tmpDir := kusttest_test.Setup(t)
345 root := tmpDir.Join("root")
346 require.NoError(t, fs.Mkdir(root))
347
348 test = populateAbsolutePaths(test, root)
349 for file, content := range test.files {
350 dir := filepath.Dir(file)
351 require.NoError(t, fs.MkdirAll(dir))
352 require.NoError(t, fs.WriteFile(file, []byte(content)))
353 }
354
355 b := krusty.MakeKustomizer(krusty.MakeDefaultOptions())
356 _, err := b.Run(fs, root)
357 require.Regexp(t, buildError(test), err.Error())
358 })
359 }
360 // TODO(annasong): add tests that check accumulateResources errors for
361 // - repos
362 // - local directories
363 }