forked from cnabio/cnab-go
-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbundle_test.go
More file actions
682 lines (598 loc) · 17.3 KB
/
bundle_test.go
File metadata and controls
682 lines (598 loc) · 17.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
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
package bundle
import (
"bytes"
"io/ioutil"
"testing"
"github.com/cnabio/cnab-go/bundle/definition"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
yaml "gopkg.in/yaml.v2"
)
func TestReadTopLevelProperties(t *testing.T) {
json := `{
"schemaVersion": "v1.0.0-WD",
"name": "foo",
"version": "1.0",
"images": {},
"credentials": {},
"custom": {}
}`
bundle, err := Unmarshal([]byte(json))
if err != nil {
t.Fatal(err)
}
assert.Equal(t, "v1.0.0-WD", bundle.SchemaVersion)
if bundle.Name != "foo" {
t.Errorf("Expected name 'foo', got '%s'", bundle.Name)
}
if bundle.Version != "1.0" {
t.Errorf("Expected version '1.0', got '%s'", bundle.Version)
}
if len(bundle.Images) != 0 {
t.Errorf("Expected no images, got %d", len(bundle.Images))
}
if len(bundle.Credentials) != 0 {
t.Errorf("Expected no credentials, got %d", len(bundle.Credentials))
}
if len(bundle.Custom) != 0 {
t.Errorf("Expected no custom extensions, got %d", len(bundle.Custom))
}
}
func TestReadImageProperties(t *testing.T) {
data, err := ioutil.ReadFile("../testdata/bundles/foo.json")
if err != nil {
t.Errorf("cannot read bundle file: %v", err)
}
bundle, err := Unmarshal(data)
if err != nil {
t.Fatal(err)
}
if len(bundle.Images) != 2 {
t.Errorf("Expected 2 images, got %d", len(bundle.Images))
}
image1 := bundle.Images["image1"]
if image1.Description != "image1" {
t.Errorf("Expected description 'image1', got '%s'", image1.Description)
}
if image1.Image != "urn:image1uri" {
t.Errorf("Expected Image 'urn:image1uri', got '%s'", image1.Image)
}
}
func TestReadCredentialProperties(t *testing.T) {
data, err := ioutil.ReadFile("../testdata/bundles/foo.json")
if err != nil {
t.Errorf("cannot read bundle file: %v", err)
}
bundle, err := Unmarshal(data)
if err != nil {
t.Fatal(err)
}
if len(bundle.Credentials) != 3 {
t.Errorf("Expected 3 credentials, got %d", len(bundle.Credentials))
}
f := bundle.Credentials["foo"]
if f.Path != "pfoo" {
t.Errorf("Expected path 'pfoo', got '%s'", f.Path)
}
if f.EnvironmentVariable != "" {
t.Errorf("Expected env '', got '%s'", f.EnvironmentVariable)
}
b := bundle.Credentials["bar"]
if b.Path != "" {
t.Errorf("Expected path '', got '%s'", b.Path)
}
if b.EnvironmentVariable != "ebar" {
t.Errorf("Expected env 'ebar', got '%s'", b.EnvironmentVariable)
}
q := bundle.Credentials["quux"]
if q.Path != "pquux" {
t.Errorf("Expected path 'pquux', got '%s'", q.Path)
}
if q.EnvironmentVariable != "equux" {
t.Errorf("Expected env 'equux', got '%s'", q.EnvironmentVariable)
}
}
func TestValuesOrDefaults(t *testing.T) {
is := assert.New(t)
vals := map[string]interface{}{
"port": 8080,
"host": "localhost",
"enabled": true,
}
b := &Bundle{
Definitions: map[string]*definition.Schema{
"portType": {
Type: "integer",
Default: 1234,
},
"hostType": {
Type: "string",
Default: "locahost.localdomain",
},
"replicaCountType": {
Type: "integer",
Default: 3,
},
"enabledType": {
Type: "boolean",
Default: false,
},
},
Parameters: map[string]Parameter{
"port": {
Definition: "portType",
},
"host": {
Definition: "hostType",
},
"enabled": {
Definition: "enabledType",
},
"replicaCount": {
Definition: "replicaCountType",
},
},
}
vod, err := ValuesOrDefaults(vals, b)
is.NoError(err)
is.True(vod["enabled"].(bool))
is.Equal(vod["host"].(string), "localhost")
is.Equal(vod["port"].(int), 8080)
is.Equal(vod["replicaCount"].(int), 3)
// This should err out because of type problem
vals["replicaCount"] = "banana"
_, err = ValuesOrDefaults(vals, b)
is.Error(err)
// Check for panic when zero value Bundle is passed
_, err = ValuesOrDefaults(vals, &Bundle{})
is.NoError(err)
}
func TestValuesOrDefaults_NoParameter(t *testing.T) {
is := assert.New(t)
vals := map[string]interface{}{}
b := &Bundle{}
vod, err := ValuesOrDefaults(vals, b)
is.NoError(err)
is.Len(vod, 0)
}
func TestValuesOrDefaults_Required(t *testing.T) {
is := assert.New(t)
vals := map[string]interface{}{
"enabled": true,
}
b := &Bundle{
Definitions: map[string]*definition.Schema{
"minType": {
Type: "integer",
},
"enabledType": {
Type: "boolean",
Default: false,
},
},
Parameters: map[string]Parameter{
"minimum": {
Definition: "minType",
Required: true,
},
"enabled": {
Definition: "enabledType",
},
},
}
_, err := ValuesOrDefaults(vals, b)
is.Error(err)
// It is unclear what the outcome should be when the user supplies
// empty values on purpose. For now, we will assume those meet the
// minimum definition of "required", and that other rules will
// correct for empty values.
//
// Example: It makes perfect sense for a user to specify --set minimum=0
// and in so doing meet the requirement that a value be specified.
vals["minimum"] = 0
res, err := ValuesOrDefaults(vals, b)
is.NoError(err)
is.Equal(0, res["minimum"])
}
func TestValidateVersionTag(t *testing.T) {
is := assert.New(t)
img := InvocationImage{BaseImage{}}
b := Bundle{
Version: "latest",
SchemaVersion: "99.98",
InvocationImages: []InvocationImage{img},
}
err := b.Validate()
is.EqualError(err, "'latest' is not a valid bundle version")
}
func TestValidateSchemaVersion(t *testing.T) {
is := assert.New(t)
img := InvocationImage{BaseImage{}}
b := Bundle{
Version: "0.1.0",
SchemaVersion: "99.98",
InvocationImages: []InvocationImage{img},
}
err := b.Validate()
is.Nil(err, "valid bundle schema failed to validate")
}
func TestValidateSchemaVersionWithPrefix(t *testing.T) {
is := assert.New(t)
img := InvocationImage{BaseImage{}}
b := Bundle{
Version: "0.1.0",
SchemaVersion: "v99.98",
InvocationImages: []InvocationImage{img},
}
err := b.Validate()
is.Nil(err, "valid bundle schema failed to validate")
}
func TestValidateMissingSchemaVersion(t *testing.T) {
is := assert.New(t)
img := InvocationImage{BaseImage{}}
b := Bundle{
Version: "0.1.0",
InvocationImages: []InvocationImage{img},
}
err := b.Validate()
is.EqualError(err, "invalid bundle schema version \"\": Invalid Semantic Version")
}
func TestValidateInvalidSchemaVersion(t *testing.T) {
is := assert.New(t)
img := InvocationImage{BaseImage{}}
b := Bundle{
Version: "0.1.0",
SchemaVersion: ".1",
InvocationImages: []InvocationImage{img},
}
err := b.Validate()
is.EqualError(err, "invalid bundle schema version \".1\": Invalid Semantic Version")
}
func TestValidateBundle_RequiresInvocationImage(t *testing.T) {
b := Bundle{
Name: "bar",
SchemaVersion: "99.98",
Version: "0.1.0",
}
err := b.Validate()
if err == nil {
t.Fatal("Validate should have failed because the bundle has no invocation images")
}
b.InvocationImages = append(b.InvocationImages, InvocationImage{})
err = b.Validate()
if err != nil {
t.Fatal(err)
}
}
func TestValidateRequiredExtensions(t *testing.T) {
is := assert.New(t)
img := InvocationImage{BaseImage{}}
b := Bundle{
Version: "0.1.0",
SchemaVersion: "99.98",
InvocationImages: []InvocationImage{img},
RequiredExtensions: []string{
"my.custom.extension",
},
}
// Verify the error when a required extension is not present in custom
err := b.Validate()
is.EqualError(err, "required extension 'my.custom.extension' is not defined in the Custom section of the bundle")
// Add corresponding entry in custom
b.Custom = map[string]interface{}{
"my.custom.extension": true,
}
err = b.Validate()
is.NoError(err)
// Add duplicate required extension
b.RequiredExtensions = append(b.RequiredExtensions, "my.custom.extension")
err = b.Validate()
is.EqualError(err, "required extension 'my.custom.extension' is already declared")
}
func TestReadCustomAndRequiredExtensions(t *testing.T) {
data, err := ioutil.ReadFile("../testdata/bundles/foo.json")
if err != nil {
t.Errorf("cannot read bundle file: %v", err)
}
bundle, err := Unmarshal(data)
if err != nil {
t.Fatal(err)
}
if len(bundle.Custom) != 2 {
t.Errorf("Expected 2 custom extensions, got %d", len(bundle.Custom))
}
duffleExtI, ok := bundle.Custom["com.example.duffle-bag"]
if !ok {
t.Fatal("Expected the com.example.duffle-bag extension")
}
duffleExt, ok := duffleExtI.(map[string]interface{})
if !ok {
t.Fatalf("Expected the com.example.duffle-bag to be of type map[string]interface{} but got %T ", duffleExtI)
}
assert.Equal(t, "PNG", duffleExt["iconType"])
assert.Equal(t, "https://example.com/icon.png", duffleExt["icon"])
backupExtI, ok := bundle.Custom["com.example.backup-preferences"]
if !ok {
t.Fatal("Expected the com.example.backup-preferences extension")
}
backupExt, ok := backupExtI.(map[string]interface{})
if !ok {
t.Fatalf("Expected the com.example.backup-preferences to be of type map[string]interface{} but got %T ", backupExtI)
}
assert.Equal(t, true, backupExt["enabled"])
assert.Equal(t, "daily", backupExt["frequency"])
if len(bundle.RequiredExtensions) != 1 {
t.Errorf("Expected 1 required extension, got %d", len(bundle.RequiredExtensions))
}
assert.Equal(t, "com.example.duffle-bag", bundle.RequiredExtensions[0])
}
func TestOutputs_Marshall(t *testing.T) {
bundleJSON := `
{
"outputs":{
"clientCert":{
"contentEncoding":"base64",
"contentMediaType":"application/x-x509-user-cert",
"path":"/cnab/app/outputs/clientCert",
"definition":"clientCert"
},
"hostName":{
"applyTo":[
"install"
],
"description":"the hostname produced installing the bundle",
"path":"/cnab/app/outputs/hostname",
"definition":"hostType"
},
"port":{
"path":"/cnab/app/outputs/port",
"definition":"portType"
}
}
}`
bundle, err := Unmarshal([]byte(bundleJSON))
assert.NoError(t, err, "should have unmarshalled the bundle")
require.NotNil(t, bundle.Outputs, "test must fail, not outputs found")
assert.Equal(t, 3, len(bundle.Outputs))
clientCert, ok := bundle.Outputs["clientCert"]
require.True(t, ok, "expected clientCert to exist as an output")
assert.Equal(t, "clientCert", clientCert.Definition)
assert.Equal(t, "/cnab/app/outputs/clientCert", clientCert.Path, "clientCert path was not the expected value")
hostName, ok := bundle.Outputs["hostName"]
require.True(t, ok, "expected hostname to exist as an output")
assert.Equal(t, "hostType", hostName.Definition)
assert.Equal(t, "/cnab/app/outputs/hostname", hostName.Path, "hostName path was not the expected value")
port, ok := bundle.Outputs["port"]
require.True(t, ok, "expected port to exist as an output")
assert.Equal(t, "portType", port.Definition)
assert.Equal(t, "/cnab/app/outputs/port", port.Path, "port path was not the expected value")
}
var exampleCred = Credential{
Description: "a password",
Location: Location{
EnvironmentVariable: "PASSWORD",
Path: "/cnab/app/path",
},
}
var exampleBundle = &Bundle{
SchemaVersion: "v1.0.0-WD",
Name: "testBundle",
Description: "something",
Version: "1.0",
License: "MIT License",
Credentials: map[string]Credential{
"password": exampleCred,
},
Images: map[string]Image{
"server": {
BaseImage: BaseImage{
Image: "nginx:1.0",
ImageType: "docker",
},
Description: "complicated",
},
},
InvocationImages: []InvocationImage{
{
BaseImage: BaseImage{
Image: "cnabio/invocation-image:1.0",
ImageType: "docker",
Labels: map[string]string{
"os": "Linux",
},
},
},
},
Definitions: map[string]*definition.Schema{
"portType": {
Type: "integer",
Default: 1234,
},
"hostType": {
Type: "string",
Default: "locahost.localdomain",
},
"replicaCountType": {
Type: "integer",
Default: 3,
},
"enabledType": {
Type: "boolean",
Default: false,
},
"clientCert": {
Type: "string",
ContentEncoding: "base64",
},
"productKeyType": {
Type: "string",
},
},
Parameters: map[string]Parameter{
"port": {
Definition: "portType",
Destination: &Location{
EnvironmentVariable: "PORT",
Path: "/path/to/port",
},
Required: true,
},
"host": {
Definition: "hostType",
Destination: &Location{
EnvironmentVariable: "HOST",
},
Required: true,
},
"enabled": {
Definition: "enabledType",
Destination: &Location{
EnvironmentVariable: "ENABLED",
},
},
"replicaCount": {
Definition: "replicaCountType",
Destination: &Location{
EnvironmentVariable: "REPLICA_COUNT",
},
},
"productKey": {
Definition: "productKeyType",
Destination: &Location{
EnvironmentVariable: "PRODUCT_KEY",
},
},
},
Outputs: map[string]Output{
"clientCert": {
Path: "/cnab/app/outputs/blah",
Definition: "clientCert",
},
},
}
func TestBundleMarshallAllThings(t *testing.T) {
expectedJSON, err := ioutil.ReadFile("../testdata/bundles/canonical-bundle.json")
require.NoError(t, err, "couldn't read test data")
var buf bytes.Buffer
_, err = exampleBundle.WriteTo(&buf)
require.NoError(t, err, "test requires output")
assert.Equal(t, string(expectedJSON), buf.String(), "output should match expected canonical json")
}
func TestBundleYamlRoundtrip(t *testing.T) {
bytes, err := yaml.Marshal(exampleBundle)
require.NoError(t, err, "should have been able to yaml.Marshal bundle")
expectedYAML, err := ioutil.ReadFile("../testdata/bundles/bundle.yaml")
require.NoError(t, err, "couldn't read test data")
assert.Equal(t, string(expectedYAML), string(bytes), "marshaled bytes should match expected yaml representation")
var roundTripBun Bundle
err = yaml.UnmarshalStrict(bytes, &roundTripBun)
require.NoError(t, err, "should have been able to yaml.UnmarshalStrict bundle")
assert.Equal(t, exampleBundle, &roundTripBun, "after a roundtrip yaml marshal/unmarshal, the bundle does not match expected")
}
func TestValidateABundleAndParams(t *testing.T) {
bun, err := ioutil.ReadFile("../testdata/bundles/foo.json")
require.NoError(t, err, "couldn't read test bundle")
bundle, err := Unmarshal(bun)
require.NoError(t, err, "the bundle should have been valid")
def, ok := bundle.Definitions["complexThing"]
require.True(t, ok, "test failed because definition not found")
testData := struct {
Port int `json:"port"`
Host string `json:"hostName"`
}{
Host: "validhost",
Port: 8080,
}
valErrors, err := def.Validate(testData)
assert.NoError(t, err, "validation should not have resulted in an error")
assert.Empty(t, valErrors, "validation should have been successful")
testData2 := struct {
Host string `json:"hostName"`
}{
Host: "validhost",
}
valErrors, err = def.Validate(testData2)
assert.NoError(t, err, "validation should not have encountered an error")
assert.NotEmpty(t, valErrors, "validation should not have been successful")
testData3 := struct {
Port int `json:"port"`
Host string `json:"hostName"`
}{
Host: "validhost",
Port: 80,
}
valErrors, err = def.Validate(testData3)
assert.NoError(t, err, "should not have encountered an error with the validator")
assert.NotEmpty(t, valErrors, "validation should not have been successful")
}
func TestBundle_RoundTrip(t *testing.T) {
testCases := []struct {
name string
testFile string
}{
{name: "EmptyJson", testFile: "testdata/empty.json"},
{name: "MinimalJson", testFile: "testdata/minimal.json"},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
wantData, err := ioutil.ReadFile(tc.testFile)
if err != nil {
t.Fatal(err)
}
bun, err := Unmarshal(wantData)
if err != nil {
t.Fatal(err)
}
output := &bytes.Buffer{}
_, err = bun.WriteTo(output)
require.NoError(t, err, "writing the bundle to json failed")
gotData := output.String()
assert.Equal(t, string(wantData), gotData)
})
}
}
func TestDigestPresent(t *testing.T) {
bun, err := ioutil.ReadFile("../testdata/bundles/digest.json")
require.NoError(t, err, "couldn't read test bundle")
bundle, err := Unmarshal(bun)
require.NoError(t, err, "the bundle should have been valid")
require.Equal(t, 1, len(bundle.InvocationImages), "there should be one invocation image in the bundle")
assert.Equal(t,
"sha256:decafbad71b4175951f29eb96035604c8cc372c99affa2e6d05cde6e8e20cc9a",
bundle.InvocationImages[0].Digest,
)
image, ok := bundle.Images["my-microservice"]
require.True(t, ok, "there should been an image named my-microservice in the bundle")
assert.Equal(
t,
"sha256:beefcacef6c04336a17761db2004813982abe0e87ab727a376c291e09391ea61",
image.Digest,
)
}
func TestImageDeepCopy(t *testing.T) {
origImg := Image{
Description: "my image",
BaseImage: BaseImage{
Image: "alpine",
ImageType: "docker",
Labels: map[string]string{
"origLabel": "origLabelValue",
},
Digest: "abc1234",
Size: 2,
},
}
newImg := origImg.DeepCopy()
newImg.Description = "my new image"
newImg.Image = "debian"
newImg.Labels["origLabel"] = "newLabelValue"
newImg.Digest = "123abcd"
assert.Equal(t, "my image", origImg.Description)
assert.Equal(t, "alpine", origImg.Image)
assert.Equal(t, map[string]string{"origLabel": "origLabelValue"}, origImg.Labels)
assert.Equal(t, "abc1234", origImg.Digest)
assert.Equal(t, "my new image", newImg.Description)
assert.Equal(t, "debian", newImg.Image)
assert.Equal(t, map[string]string{"origLabel": "newLabelValue"}, newImg.Labels)
assert.Equal(t, "123abcd", newImg.Digest)
}