Debian Codegraph @

kyaml/openapi/openapi_test.go

raw symbols SCIP
1 // Copyright 2019 The Kubernetes Authors.
2 // SPDX-License-Identifier: Apache-2.0
3
4 package openapi
5
6 import (
7 "fmt"
8 "os"
9 "sync"
10 "testing"
11
12 "github.com/google/go-cmp/cmp"
13 "github.com/stretchr/testify/assert"
14 "github.com/stretchr/testify/require"
15 "sigs.k8s.io/kustomize/kyaml/yaml"
16 )
17
18 func TestAddSchema(t *testing.T) {
19 // reset package vars
20 globalSchema = openapiData{}
21
22 err := AddSchema(additionalSchema)
23 if !assert.NoError(t, err) {
24 t.FailNow()
25 }
26 s, err := GetSchema(`{"$ref": "#/definitions/io.k8s.config.setters.replicas"}`, Schema())
27 if !assert.Greater(t, len(globalSchema.schema.Definitions), 200) {
28 t.FailNow()
29 }
30 if !assert.NoError(t, err) {
31 t.FailNow()
32 }
33 assert.Equal(t, `map[x-kustomize:map[setBy:Jane setter:map[name:replicas value:5]]]`,
34 fmt.Sprintf("%v", s.Schema.Extensions))
35 }
36
37 var additionalSchema = []byte(`
38 {
39 "definitions": {
40 "io.k8s.config.setters.replicas": {
41 "description": "replicas description.",
42 "type": "integer",
43 "x-kustomize": {"setBy":"Jane","setter": {"name":"replicas","value":"5"}}
44 }
45 },
46 "invalid": "field"
47 }
48 `)
49
50 func TestSchemaForResourceType(t *testing.T) {
51 // reset package vars
52 globalSchema = openapiData{}
53
54 s := SchemaForResourceType(
55 yaml.TypeMeta{APIVersion: "apps/v1", Kind: "Deployment"})
56 if !assert.NotNil(t, s) {
57 t.FailNow()
58 }
59
60 f := s.Field("spec")
61 if !assert.NotNil(t, f) {
62 t.FailNow()
63 }
64 if !assert.Equal(t, "DeploymentSpec is the specification of the desired behavior of the Deployment.",
65 f.Schema.Description) {
66 t.FailNow()
67 }
68
69 replicas := f.Field("replicas")
70 if !assert.NotNil(t, replicas) {
71 t.FailNow()
72 }
73 if !assert.Equal(t, "Number of desired pods. This is a pointer to distinguish between explicit zero and not specified. Defaults to 1.",
74 replicas.Schema.Description) {
75 t.FailNow()
76 }
77
78 temp := f.Field("template")
79 if !assert.NotNil(t, temp) {
80 t.FailNow()
81 }
82 if !assert.Equal(t, "PodTemplateSpec describes the data a pod should have when created from a template",
83 temp.Schema.Description) {
84 t.FailNow()
85 }
86
87 containers := temp.Field("spec").Field("containers").Elements()
88 if !assert.NotNil(t, containers) {
89 t.FailNow()
90 }
91
92 targetPort := containers.Field("ports").Elements().Field("containerPort")
93 if !assert.NotNil(t, targetPort) {
94 t.FailNow()
95 }
96 if !assert.Equal(t, "Number of port to expose on the pod's IP address. This must be a valid port number, 0 < x < 65536.",
97 targetPort.Schema.Description) {
98 t.FailNow()
99 }
100
101 arg := containers.Field("args").Elements()
102 if !assert.NotNil(t, arg) {
103 t.FailNow()
104 }
105 if !assert.Equal(t, "string", arg.Schema.Type[0]) {
106 t.FailNow()
107 }
108 }
109
110 func TestSchemaFromFile(t *testing.T) {
111 ResetOpenAPI()
112 inputyaml := `
113 openAPI:
114 definitions:
115 io.k8s.cli.setters.image-name:
116 x-k8s-cli:
117 setter:
118 name: image-name
119 value: "nginx"
120 `
121 f, err := os.CreateTemp("", "openapi-")
122 if !assert.NoError(t, err) {
123 t.FailNow()
124 }
125 if !assert.NoError(t, os.WriteFile(f.Name(), []byte(inputyaml), 0o600)) {
126 t.FailNow()
127 }
128
129 sc, err := SchemaFromFile(f.Name())
130 if !assert.NoError(t, err) {
131 t.FailNow()
132 }
133
134 s, err := GetSchema(`{"$ref": "#/definitions/io.k8s.cli.setters.image-name"}`, sc)
135
136 if !assert.NoError(t, err) {
137 t.FailNow()
138 }
139 if !assert.Greater(t, len(sc.Definitions), 0) {
140 t.FailNow()
141 }
142 assert.Equal(t, `map[x-k8s-cli:map[setter:map[name:image-name value:nginx]]]`,
143 fmt.Sprintf("%v", s.Schema.Extensions))
144 }
145
146 func TestPopulateDefsInOpenAPI_Substitution(t *testing.T) {
147 ResetOpenAPI()
148 inputyaml := `
149 openAPI:
150 definitions:
151 io.k8s.cli.setters.image-name:
152 x-k8s-cli:
153 setter:
154 name: image-name
155 value: "nginx"
156 io.k8s.cli.setters.image-tag:
157 x-k8s-cli:
158 setter:
159 name: image-tag
160 value: "1.8.1"
161 io.k8s.cli.substitutions.image:
162 x-k8s-cli:
163 substitution:
164 name: image
165 pattern: IMAGE_NAME:IMAGE_TAG
166 values:
167 - marker: "IMAGE_NAME"
168 ref: "#/definitions/io.k8s.cli.setters.image-name"
169 - marker: "IMAGE_TAG"
170 ref: "#/definitions/io.k8s.cli.setters.image-tag"
171 `
172
173 f, err := os.CreateTemp("", "openapi-")
174 if !assert.NoError(t, err) {
175 t.FailNow()
176 }
177 if !assert.NoError(t, os.WriteFile(f.Name(), []byte(inputyaml), 0o600)) {
178 t.FailNow()
179 }
180
181 sc, err := SchemaFromFile(f.Name())
182 if !assert.NoError(t, err) {
183 t.FailNow()
184 }
185
186 s, err := GetSchema(`{"$ref": "#/definitions/io.k8s.cli.substitutions.image"}`, sc)
187
188 if !assert.NoError(t, err) {
189 t.FailNow()
190 }
191 if !assert.Equal(t, len(sc.Definitions), 3) {
192 t.FailNow()
193 }
194
195 assert.Equal(t,
196 `map[x-k8s-cli:map[substitution:map[name:image pattern:IMAGE_NAME:IMAGE_TAG`+
197 ` values:[map[marker:IMAGE_NAME ref:#/definitions/io.k8s.cli.setters.image-name]`+
198 ` map[marker:IMAGE_TAG ref:#/definitions/io.k8s.cli.setters.image-tag]]]]]`,
199 fmt.Sprintf("%v", s.Schema.Extensions))
200 }
201
202 func TestAddSchemaFromFile_empty(t *testing.T) {
203 ResetOpenAPI()
204 inputyaml := `
205 kind: Example
206 `
207
208 f, err := os.CreateTemp("", "openapi-")
209 if !assert.NoError(t, err) {
210 t.FailNow()
211 }
212 if !assert.NoError(t, os.WriteFile(f.Name(), []byte(inputyaml), 0o600)) {
213 t.FailNow()
214 }
215
216 sc, err := SchemaFromFile(f.Name())
217 if !assert.NoError(t, err) {
218 t.FailNow()
219 }
220
221 if !assert.Nil(t, sc) {
222 t.FailNow()
223 }
224 }
225
226 func TestIsNamespaceScoped_builtin(t *testing.T) {
227 testCases := []struct {
228 name string
229 typeMeta yaml.TypeMeta
230 expectIsFound bool
231 expectIsNamespaced bool
232 }{
233 {
234 name: "namespacescoped resource",
235 typeMeta: yaml.TypeMeta{
236 APIVersion: "apps/v1",
237 Kind: "Deployment",
238 },
239 expectIsFound: true,
240 expectIsNamespaced: true,
241 },
242 {
243 name: "clusterscoped resource",
244 typeMeta: yaml.TypeMeta{
245 APIVersion: "v1",
246 Kind: "Namespace",
247 },
248 expectIsFound: true,
249 expectIsNamespaced: false,
250 },
251 {
252 name: "unknown resource",
253 typeMeta: yaml.TypeMeta{
254 APIVersion: "custom.io/v1",
255 Kind: "Custom",
256 },
257 expectIsFound: false,
258 },
259 }
260
261 for i := range testCases {
262 test := testCases[i]
263 t.Run(test.name, func(t *testing.T) {
264 ResetOpenAPI()
265 isNamespaceable, isFound := IsNamespaceScoped(test.typeMeta)
266
267 if !test.expectIsFound {
268 assert.False(t, isFound)
269 return
270 }
271 assert.True(t, isFound)
272 assert.Equal(t, test.expectIsNamespaced, isNamespaceable)
273 })
274 }
275 }
276
277 // TestIsNamespaceScopedPrecompute checks that the precomputed result meets the actual result
278 func TestIsNamespaceScopedPrecompute(t *testing.T) {
279 initSchema()
280 if diff := cmp.Diff(globalSchema.namespaceabilityByResourceType, precomputedIsNamespaceScoped); diff != "" {
281 t.Fatalf("%s", diff)
282 }
283 }
284
285 func TestIsNamespaceScoped_custom(t *testing.T) {
286 SuppressBuiltInSchemaUse()
287 err := AddSchema([]byte(`
288 {
289 "definitions": {},
290 "paths": {
291 "/apis/custom.io/v1/namespaces/{namespace}/customs/{name}": {
292 "get": {
293 "x-kubernetes-action": "get",
294 "x-kubernetes-group-version-kind": {
295 "group": "custom.io",
296 "kind": "Custom",
297 "version": "v1"
298 }
299 }
300 },
301 "/apis/custom.io/v1/clustercustoms": {
302 "get": {
303 "x-kubernetes-action": "get",
304 "x-kubernetes-group-version-kind": {
305 "group": "custom.io",
306 "kind": "ClusterCustom",
307 "version": "v1"
308 }
309 }
310 }
311 }
312 }
313 `))
314 require.NoError(t, err)
315
316 isNamespaceable, isFound := IsNamespaceScoped(yaml.TypeMeta{
317 APIVersion: "custom.io/v1",
318 Kind: "ClusterCustom",
319 })
320 assert.True(t, isFound)
321 assert.False(t, isNamespaceable)
322
323 isNamespaceable, isFound = IsNamespaceScoped(yaml.TypeMeta{
324 APIVersion: "custom.io/v1",
325 Kind: "Custom",
326 })
327 assert.True(t, isFound)
328 assert.True(t, isNamespaceable)
329 }
330
331 func TestCanSetAndResetSchemaConcurrently(t *testing.T) {
332 t.Run("SetSchema doesn't cause a data race when called concurrently", func(t *testing.T) {
333 set := func(wg *sync.WaitGroup) {
334 defer wg.Done()
335 err := SetSchema(
336 map[string]string{
337 "/apis/custom.io/v1": "true",
338 },
339 []byte(`
340 {
341 "definitions": {},
342 "paths": {
343 "/apis/custom.io/v1/namespaces/{namespace}/customs/{name}": {
344 "get": {
345 "x-kubernetes-action": "get",
346 "x-kubernetes-group-version-kind": {
347 "group": "custom.io",
348 "kind": "Custom",
349 "version": "v1"
350 }
351 }
352 },
353 "/apis/custom.io/v1/clustercustoms": {
354 "get": {
355 "x-kubernetes-action": "get",
356 "x-kubernetes-group-version-kind": {
357 "group": "custom.io",
358 "kind": "ClusterCustom",
359 "version": "v1"
360 }
361 }
362 }
363 }
364 }
365 `),
366 true,
367 )
368 require.NoError(t, err)
369 }
370
371 var wg sync.WaitGroup
372 require.NotPanics(t, func() {
373 for i := 0; i < 100; i++ {
374 wg.Add(1)
375 go set(&wg)
376 }
377 })
378 wg.Wait()
379 })
380
381 t.Run("ResetOpenAPI doesn't cause a data race when called concurrently", func(t *testing.T) {
382 reset := func(wg *sync.WaitGroup) {
383 defer wg.Done()
384 ResetOpenAPI()
385 }
386 var wg sync.WaitGroup
387 require.NotPanics(t, func() {
388 for i := 0; i < 100; i++ {
389 wg.Add(1)
390 go reset(&wg)
391 }
392 })
393 wg.Wait()
394 })
395 }