-
Notifications
You must be signed in to change notification settings - Fork 69
Expand file tree
/
Copy pathcommon_test.go
More file actions
409 lines (382 loc) · 12.3 KB
/
common_test.go
File metadata and controls
409 lines (382 loc) · 12.3 KB
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
//
// Copyright (c) 2019-2026 Red Hat, Inc.
// Licensed under the Apache License, Version 2.0 (the "License");
// you may not use this file except in compliance with the License.
// You may obtain a copy of the License at
//
// http://www.apache.org/licenses/LICENSE-2.0
//
// Unless required by applicable law or agreed to in writing, software
// distributed under the License is distributed on an "AS IS" BASIS,
// WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
// See the License for the specific language governing permissions and
// limitations under the License.
//
package automount
import (
"fmt"
"os"
"path/filepath"
"strings"
"testing"
"github.com/google/go-cmp/cmp"
"github.com/google/go-cmp/cmp/cmpopts"
"github.com/stretchr/testify/assert"
corev1 "k8s.io/api/core/v1"
"sigs.k8s.io/controller-runtime/pkg/client"
"sigs.k8s.io/controller-runtime/pkg/client/fake"
"sigs.k8s.io/yaml"
"github.com/devfile/devworkspace-operator/apis/controller/v1alpha1"
"github.com/devfile/devworkspace-operator/pkg/common"
"github.com/devfile/devworkspace-operator/pkg/provision/sync"
)
type mountedVolumeType int
const (
devWorkspaceVolume mountedVolumeType = iota
secretVolumeType
configMapVolumeType
)
const (
testContainerName = "testContainer"
testNamespace = "test-namespace"
)
type testCase struct {
Name string `json:"name"`
Input struct {
// Secrets, Configmaps, and PVCs are necessary for deserialization from a testcase
Secrets []corev1.Secret `json:"secrets"`
ConfigMaps []corev1.ConfigMap `json:"configmaps"`
PVCs []corev1.PersistentVolumeClaim `json:"pvcs"`
// allObjects contains all Secrets, Configmaps, and PVCs defined above, for convenience
allObjects []client.Object
} `json:"input"`
Output struct {
// List of volumes expected in the resulting podAdditions; if the name of any volume
// starts with '/', the name will be overwritten to common.AutoMountProjectedVolumeName(name)
Volumes []corev1.Volume `json:"volumes"`
// List of volumeMounts expected in the resulting podAdditions; if the name of any volumeMount
// starts with '/', the name will be overwritten to common.AutoMountProjectedVolumeName(name)
VolumeMounts []corev1.VolumeMount `json:"volumeMounts"`
EnvFrom []corev1.EnvFromSource `json:"envFrom"`
ErrRegexp *string `json:"errRegexp"`
} `json:"output"`
TestPath string
}
var testDiffOpts = cmp.Options{
cmpopts.SortSlices(func(a, b corev1.Volume) bool {
return a.Name < b.Name
}),
cmpopts.SortSlices(func(a, b corev1.VolumeMount) bool {
if a.Name == b.Name {
return a.MountPath < b.MountPath
}
return a.Name < b.Name
}),
cmpopts.SortSlices(func(a, b corev1.EnvFromSource) bool {
switch {
case a.ConfigMapRef != nil && b.ConfigMapRef != nil:
return a.ConfigMapRef.Name < b.ConfigMapRef.Name
case a.ConfigMapRef != nil && b.ConfigMapRef == nil:
return true
case a.ConfigMapRef == nil && b.ConfigMapRef != nil:
return false
default:
return a.SecretRef.Name < b.SecretRef.Name
}
}),
cmpopts.SortSlices(func(a, b corev1.VolumeProjection) bool {
switch {
case a.ConfigMap != nil && b.ConfigMap != nil:
return a.ConfigMap.Name < b.ConfigMap.Name
case a.ConfigMap == nil && b.ConfigMap != nil:
return true
case a.ConfigMap != nil && b.ConfigMap == nil:
return false
default:
return a.Secret.Name < b.Secret.Name
}
}),
}
func TestProvisionAutomountResourcesInto(t *testing.T) {
tests := loadAllTestCasesOrPanic(t, "testdata")
testContainer := corev1.Container{
Name: "test-container",
Image: "test-image",
}
testPodAdditions := &v1alpha1.PodAdditions{
Containers: []corev1.Container{testContainer},
InitContainers: []corev1.Container{testContainer},
}
for _, tt := range tests {
t.Run(fmt.Sprintf("%s (%s)", tt.Name, tt.TestPath), func(t *testing.T) {
podAdditions := testPodAdditions.DeepCopy()
testAPI := sync.ClusterAPI{
Client: fake.NewClientBuilder().WithObjects(tt.Input.allObjects...).Build(),
}
// Note: this test does not allow for returning AutoMountError with isFatal: false (i.e. no retrying)
// and so is not suitable for testing automount features that provision cluster resources (yet)
err := ProvisionAutoMountResourcesInto(podAdditions, testAPI, testNamespace, false)
if tt.Output.ErrRegexp != nil {
if !assert.Error(t, err, "Expected an error but got none") {
return
}
assert.Regexp(t, *tt.Output.ErrRegexp, err.Error(), "Expected error messages to match")
} else {
if !assert.NoError(t, err, "Unexpected error") {
return
}
assert.Truef(t, cmp.Equal(tt.Output.Volumes, podAdditions.Volumes, testDiffOpts),
"Volumes should match expected output:\n%s",
cmp.Diff(tt.Output.Volumes, podAdditions.Volumes, testDiffOpts))
for _, container := range podAdditions.Containers {
assert.Truef(t, cmp.Equal(tt.Output.VolumeMounts, container.VolumeMounts, testDiffOpts),
"Container VolumeMounts should match expected output:\n%s",
cmp.Diff(tt.Output.VolumeMounts, container.VolumeMounts, testDiffOpts))
assert.Truef(t, cmp.Equal(tt.Output.EnvFrom, container.EnvFrom, testDiffOpts),
"Container EnvFrom should match expected output:\n%s",
cmp.Diff(tt.Output.EnvFrom, container.EnvFrom, testDiffOpts))
}
for _, container := range podAdditions.InitContainers {
assert.Truef(t, cmp.Equal(tt.Output.VolumeMounts, container.VolumeMounts, testDiffOpts),
"Container VolumeMounts should match expected output:\n%s",
cmp.Diff(tt.Output.VolumeMounts, container.VolumeMounts, testDiffOpts))
assert.Truef(t, cmp.Equal(tt.Output.EnvFrom, container.EnvFrom, testDiffOpts),
"Container EnvFrom should match expected output:\n%s",
cmp.Diff(tt.Output.EnvFrom, container.EnvFrom, testDiffOpts))
}
}
})
}
}
func TestCheckAutoMountVolumesForCollision(t *testing.T) {
type volumeDesc struct {
name string
mountPath string
volumeType mountedVolumeType
}
tests := []struct {
name string
basePodAdditions []volumeDesc
automountPodAdditions []volumeDesc
errRegexp string
}{
{
name: "Does not error when mounts are valid",
basePodAdditions: []volumeDesc{
{
name: "baseVolume",
mountPath: "basePath",
volumeType: configMapVolumeType,
},
},
automountPodAdditions: []volumeDesc{
{
name: "automountConfigMap",
mountPath: "/configmap/mount",
volumeType: configMapVolumeType,
},
{
name: "automountSecret",
mountPath: "/secret/mount",
volumeType: secretVolumeType,
},
},
},
{
name: "Detects volume name collision",
basePodAdditions: []volumeDesc{
{
name: "baseVolume",
mountPath: "basePath",
volumeType: devWorkspaceVolume,
},
},
automountPodAdditions: []volumeDesc{
{
name: "baseVolume",
mountPath: "/configmap/mount",
volumeType: configMapVolumeType,
},
},
errRegexp: "DevWorkspace volume 'baseVolume' conflicts with automounted volume from configmap 'baseVolume'",
},
{
name: "Detects mountPath collision with DevWorkspace",
basePodAdditions: []volumeDesc{
{
name: "baseVolume",
mountPath: "/collision/path",
volumeType: devWorkspaceVolume,
},
},
automountPodAdditions: []volumeDesc{
{
name: "testVolume",
mountPath: "/collision/path",
volumeType: secretVolumeType,
},
},
errRegexp: fmt.Sprintf("DevWorkspace volume 'baseVolume' in container %s has same mountpath as auto-mounted volume from secret 'testVolume'", testContainerName),
},
{
name: "Detects mountPath collision in automounted volumes",
automountPodAdditions: []volumeDesc{
{
name: "testVolume1",
mountPath: "/test/mount",
volumeType: secretVolumeType,
},
{
name: "testVolume2",
mountPath: "/test/mount",
volumeType: configMapVolumeType,
},
},
errRegexp: "auto-mounted volumes from configmap 'testVolume2' and secret 'testVolume1' have the same mount path",
},
}
convertDescToVolume := func(desc volumeDesc) (*corev1.Volume, *corev1.VolumeMount, *corev1.Container) {
switch desc.volumeType {
case secretVolumeType:
volume := &corev1.Volume{
Name: desc.name,
VolumeSource: corev1.VolumeSource{
Secret: &corev1.SecretVolumeSource{
SecretName: desc.name,
},
},
}
volumeMount := &corev1.VolumeMount{
Name: desc.name,
MountPath: desc.mountPath,
}
return volume, volumeMount, nil
case configMapVolumeType:
volume := &corev1.Volume{
Name: desc.name,
VolumeSource: corev1.VolumeSource{
ConfigMap: &corev1.ConfigMapVolumeSource{
LocalObjectReference: corev1.LocalObjectReference{
Name: desc.name,
},
},
},
}
volumeMount := &corev1.VolumeMount{
Name: desc.name,
MountPath: desc.mountPath,
}
return volume, volumeMount, nil
case devWorkspaceVolume:
volume := &corev1.Volume{
Name: desc.name,
}
container := &corev1.Container{
Name: testContainerName,
VolumeMounts: []corev1.VolumeMount{
{
Name: desc.name,
MountPath: desc.mountPath,
},
},
}
return volume, nil, container
}
return nil, nil, nil
}
convertToPodAddition := func(descs ...volumeDesc) *v1alpha1.PodAdditions {
pa := &v1alpha1.PodAdditions{}
for _, desc := range descs {
volume, volumeMount, container := convertDescToVolume(desc)
if volume != nil {
pa.Volumes = append(pa.Volumes, *volume)
}
if volumeMount != nil {
pa.VolumeMounts = append(pa.VolumeMounts, *volumeMount)
}
if container != nil {
pa.Containers = append(pa.Containers, *container)
}
}
return pa
}
convertToAutomountResources := func(descs ...volumeDesc) *Resources {
resources := &Resources{}
for _, desc := range descs {
volume, volumeMount, _ := convertDescToVolume(desc)
if volume != nil {
resources.Volumes = append(resources.Volumes, *volume)
}
if volumeMount != nil {
resources.VolumeMounts = append(resources.VolumeMounts, *volumeMount)
}
}
return resources
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
base := convertToPodAddition(tt.basePodAdditions...)
autoMount := convertToAutomountResources(tt.automountPodAdditions...)
outErr := checkAutomountVolumesForCollision(base, autoMount)
if tt.errRegexp == "" {
assert.Nil(t, outErr, "Expected no error but got %s", outErr)
} else {
assert.NotNil(t, outErr, "Expected error but got nil")
assert.Regexp(t, tt.errRegexp, outErr, "Error message should match regexp %s", tt.errRegexp)
}
})
}
}
func loadAllTestCasesOrPanic(t *testing.T, fromDir string) []testCase {
files, err := os.ReadDir(fromDir)
if err != nil {
t.Fatal(err)
}
var tests []testCase
for _, file := range files {
if file.IsDir() {
tests = append(tests, loadAllTestCasesOrPanic(t, filepath.Join(fromDir, file.Name()))...)
} else {
tests = append(tests, loadTestCaseOrPanic(t, filepath.Join(fromDir, file.Name())))
}
}
return tests
}
func loadTestCaseOrPanic(t *testing.T, testPath string) testCase {
bytes, err := os.ReadFile(testPath)
if err != nil {
t.Fatal(err)
}
var test testCase
if err := yaml.Unmarshal(bytes, &test); err != nil {
t.Fatal(err)
}
// Go doesn't allow conversion to interfaces (e.g. client.Object) for elements of slices,
// so we have to add one at a time
for idx := range test.Input.ConfigMaps {
test.Input.allObjects = append(test.Input.allObjects, &test.Input.ConfigMaps[idx])
}
for idx := range test.Input.Secrets {
test.Input.allObjects = append(test.Input.allObjects, &test.Input.Secrets[idx])
}
for idx := range test.Input.PVCs {
test.Input.allObjects = append(test.Input.allObjects, &test.Input.PVCs[idx])
}
// Overwrite namespace for convenience
for _, obj := range test.Input.allObjects {
obj.SetNamespace(testNamespace)
}
// Overwrite volume and volumeMount names for projected volumes
for idx, vol := range test.Output.Volumes {
if strings.HasPrefix(vol.Name, "/") {
test.Output.Volumes[idx].Name = common.AutoMountProjectedVolumeName(vol.Name)
}
}
for idx, vm := range test.Output.VolumeMounts {
if strings.HasPrefix(vm.Name, "/") {
test.Output.VolumeMounts[idx].Name = common.AutoMountProjectedVolumeName(vm.Name)
}
}
test.TestPath = testPath
return test
}