Debian Codegraph @

yaml_test.go

raw ◀ ▶
2 Debian patches touch this file
1 /*
2 Copyright 2021 The Kubernetes Authors.
3
4 Licensed under the Apache License, Version 2.0 (the "License");
5 you may not use this file except in compliance with the License.
6 You may obtain a copy of the License at
7
8 http://www.apache.org/licenses/LICENSE-2.0
9
10 Unless required by applicable law or agreed to in writing, software
11 distributed under the License is distributed on an "AS IS" BASIS,
12 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
13 See the License for the specific language governing permissions and
14 limitations under the License.
15 */
16
17 package yaml
18
19 import (
20 "bytes"
21 "encoding/json"
22 "fmt"
23 "math"
24 "reflect"
•25 "slices"
26 "sort"
27 "strconv"
28 "testing"
29
30 "github.com/google/go-cmp/cmp"
31 yamlv2 "go.yaml.in/yaml/v2"
32 yamlv3 "go.yaml.in/yaml/v3"
33 )
34
35 /* Test helper functions */
36
37 func strPtr(str string) *string {
38 return &str
39 }
40
•41 // newIntPtr returns a pointer to a new int or int64 based on architecture.
42 // On 64-bit platforms, it returns *int to test unsized int behavior.
43 // On 32-bit platforms, it returns *int64 to test the large value that doesn't fit in 32-bit int.
44 func newIntPtr() interface{} {
45 if strconv.IntSize == 64 {
46 return new(int)
47 }
48 return new(int64)
49 }
50
51 // expectedIntValue returns the expected decoded value for architecture-specific int tests.
52 // On 64-bit platforms, it returns the value as int.
53 // On 32-bit platforms, it returns the value as int64 since the large value doesn't fit in 32-bit int.
54 func expectedIntValue(value int64) interface{} {
55 if strconv.IntSize == 64 {
56 return int(value)
57 }
58 return value
59 }
60
61 type errorType int
62
63 const (
64 noErrorsType errorType = 0
65 fatalErrorsType errorType = 1 << iota
66 )
67
68 type unmarshalTestCase struct {
69 encoded []byte
70 decodeInto interface{}
71 decoded interface{}
72 err errorType
73 }
74
75 type testUnmarshalFunc = func(yamlBytes []byte, obj interface{}) error
76
77 var (
78 funcUnmarshal testUnmarshalFunc = func(yamlBytes []byte, obj interface{}) error {
79 return Unmarshal(yamlBytes, obj)
80 }
81
82 funcUnmarshalStrict testUnmarshalFunc = func(yamlBytes []byte, obj interface{}) error {
83 return UnmarshalStrict(yamlBytes, obj)
84 }
85 )
86
87 func testUnmarshal(t *testing.T, f testUnmarshalFunc, tests map[string]unmarshalTestCase) {
88 for testName, test := range tests {
89 t.Run(testName, func(t *testing.T) {
90 typ := reflect.TypeOf(test.decodeInto)
91 if typ.Kind() != reflect.Ptr {
92 t.Errorf("unmarshalTest.ptr %T is not a pointer type", test.decodeInto)
93 }
94
95 value := reflect.New(typ.Elem())
96
97 if !reflect.DeepEqual(test.decodeInto, value.Interface()) {
98 // There's no reason for ptr to point to non-zero data,
99 // as we decode into new(right-type), so the data is
100 // discarded.
101 // This can easily mean tests that silently don't test
102 // what they should. To test decoding into existing
103 // data, see TestPrefilled.
104 t.Errorf("unmarshalTest.ptr %#v is not a pointer to a zero value", test.decodeInto)
105 }
106
107 err := f(test.encoded, value.Interface())
108 if err != nil && test.err == noErrorsType {
109 t.Errorf("error unmarshaling YAML: %v", err)
110 }
111 if err == nil && test.err&fatalErrorsType != 0 {
112 t.Errorf("expected a fatal error, but no fatal error was returned, yaml: `%s`", test.encoded)
113 }
114
115 if test.err&fatalErrorsType != 0 {
116 // Don't check output if error is fatal
117 return
118 }
119
120 if !reflect.DeepEqual(value.Elem().Interface(), test.decoded) {
121 t.Errorf("unmarshal YAML was unsuccessful, expected: %+#v, got: %+#v", test.decoded, value.Elem().Interface())
122 }
123 })
124 }
125 }
126
127 type yamlToJSONTestcase struct {
128 yaml string
129 json string
•130 // jsonAllow provides allowed alternate JSON representations.
131 // For the json v1->v2 transition, this is used to tolerate changes
132 // in how malformed input in munged.
133 jsonAllow []string
134 // By default we test that reversing the output == input. But if there is a
135 // difference in the reversed output, you can optionally specify it here.
136 yamlReverseOverwrite *string
137 err errorType
138 }
139
140 type testYAMLToJSONFunc = func(yamlBytes []byte) ([]byte, error)
141
142 var (
143 funcYAMLToJSON testYAMLToJSONFunc = func(yamlBytes []byte) ([]byte, error) {
144 return YAMLToJSON(yamlBytes)
145 }
146
147 funcYAMLToJSONStrict testYAMLToJSONFunc = func(yamlBytes []byte) ([]byte, error) {
148 return YAMLToJSONStrict(yamlBytes)
149 }
150 )
151
152 func testYAMLToJSON(t *testing.T, f testYAMLToJSONFunc, tests map[string]yamlToJSONTestcase) {
153 for testName, test := range tests {
154 t.Run(fmt.Sprintf("%s_YAMLToJSON", testName), func(t *testing.T) {
155 // Convert Yaml to Json
156 jsonBytes, err := f([]byte(test.yaml))
157 if err != nil && test.err == noErrorsType {
158 t.Errorf("Failed to convert YAML to JSON, yamlv2: `%s`, err: %v", test.yaml, err)
159 }
160 if err == nil && test.err&fatalErrorsType != 0 {
161 t.Errorf("expected a fatal error, but no fatal error was returned, yaml: `%s`", test.yaml)
162 }
163
164 if test.err&fatalErrorsType != 0 {
165 // Don't check output if error is fatal
166 return
167 }
168
169 // Check it against the expected output.
•170 if got := string(jsonBytes); got != test.json && !slices.Contains(test.jsonAllow, got) {
171 t.Errorf("Failed to convert YAML to JSON, yaml: `%s`, expected json `%s`, got `%s`", test.yaml, test.json, got)
172 }
173 })
174
175 t.Run(fmt.Sprintf("%s_JSONToYAML", testName), func(t *testing.T) {
176 // Convert JSON to YAML
177 yamlBytes, err := JSONToYAML([]byte(test.json))
178 if err != nil {
179 t.Errorf("Failed to convert JSON to YAML, json: `%s`, err: %v", test.json, err)
180 }
181
182 // Set the string that we will compare the reversed output to.
183 correctYamlString := test.yaml
184
185 // If a special reverse string was specified, use that instead.
186 if test.yamlReverseOverwrite != nil {
187 correctYamlString = *test.yamlReverseOverwrite
188 }
189
190 // Check it against the expected output.
191 if string(yamlBytes) != correctYamlString {
192 t.Errorf("Failed to convert JSON to YAML, json: `%s`, expected yaml `%s`, got `%s`", test.json, correctYamlString, string(yamlBytes))
193 }
194 })
195 }
196 }
197
198 /* Start tests */
199
200 type MarshalTest struct {
201 A string
202 B int64
203 // Would like to test float64, but it's not supported in go-yaml.
204 // (See https://github.com/go-yaml/yaml/issues/83.)
205 C float32
206 }
207
208 func TestMarshal(t *testing.T) {
209 f32String := strconv.FormatFloat(math.MaxFloat32, 'g', -1, 32)
210 s := MarshalTest{"a", math.MaxInt64, math.MaxFloat32}
•211 e := []byte(fmt.Sprintf("A: a\nB: %d\nC: %s\n", int64(math.MaxInt64), f32String))
212
213 y, err := Marshal(s)
214 if err != nil {
215 t.Errorf("error marshaling YAML: %v", err)
216 }
217
218 if !reflect.DeepEqual(y, e) {
219 t.Errorf("marshal YAML was unsuccessful, expected: %#v, got: %#v",
220 string(e), string(y))
221 }
222 }
223
224 type UnmarshalUntaggedStruct struct {
225 A string
226 True string
227 }
228
229 type UnmarshalTaggedStruct struct {
230 AUpper string `json:"A"`
231 ALower string `json:"a"`
232 TrueUpper string `json:"True"`
233 TrueLower string `json:"true"`
234 YesUpper string `json:"Yes"`
235 YesLower string `json:"yes"`
236 Int3 string `json:"3"`
237 IntBig1 string `json:"9007199254740993"` // 2^53 + 1
238 IntBig2 string `json:"1000000000000000000000000000000000000"`
239 IntBig2Scientific string `json:"1e+36"`
240 Float3dot3 string `json:"3.3"`
241 }
242
243 type UnmarshalStruct struct {
244 A string `json:"a"`
245 B *string `json:"b"`
246 C string `json:"c"`
247 }
248
249 type UnmarshalStringMap struct {
250 A map[string]string `json:"a"`
251 }
252
253 type UnmarshalNestedStruct struct {
254 A UnmarshalStruct `json:"a"`
255 }
256
257 type UnmarshalSlice struct {
258 A []UnmarshalStruct `json:"a"`
259 }
260
261 type UnmarshalEmbedStruct struct {
262 UnmarshalStruct
263 B string `json:"b"`
264 }
265
266 type UnmarshalEmbedStructPointer struct {
267 *UnmarshalStruct
268 B string `json:"b"`
269 }
270
271 type UnmarshalEmbedRecursiveStruct struct {
272 *UnmarshalEmbedRecursiveStruct `json:"a"`
273 B string `json:"b"`
274 }
275
276 func TestUnmarshal(t *testing.T) {
277 tests := map[string]unmarshalTestCase{
278 // casematched / non-casematched untagged keys
279 "untagged casematched string key": {
280 encoded: []byte("A: test"),
281 decodeInto: new(UnmarshalUntaggedStruct),
282 decoded: UnmarshalUntaggedStruct{A: "test"},
283 },
284 "untagged non-casematched string key": {
285 encoded: []byte("a: test"),
286 decodeInto: new(UnmarshalUntaggedStruct),
287 decoded: UnmarshalUntaggedStruct{A: "test"},
288 },
289 "untagged casematched boolean key": {
290 encoded: []byte("True: test"),
291 decodeInto: new(UnmarshalUntaggedStruct),
292 decoded: UnmarshalUntaggedStruct{True: "test"},
293 },
294 "untagged non-casematched boolean key": {
295 encoded: []byte("true: test"),
296 decodeInto: new(UnmarshalUntaggedStruct),
297 decoded: UnmarshalUntaggedStruct{True: "test"},
298 },
299
300 // casematched / non-casematched tagged keys
301 "tagged casematched string key": {
302 encoded: []byte("A: test"),
303 decodeInto: new(UnmarshalTaggedStruct),
304 decoded: UnmarshalTaggedStruct{AUpper: "test"},
305 },
306 "tagged non-casematched string key": {
307 encoded: []byte("a: test"),
308 decodeInto: new(UnmarshalTaggedStruct),
309 decoded: UnmarshalTaggedStruct{ALower: "test"},
310 },
311 "tagged casematched boolean key": {
312 encoded: []byte("True: test"),
313 decodeInto: new(UnmarshalTaggedStruct),
314 decoded: UnmarshalTaggedStruct{TrueLower: "test"},
315 },
316 "tagged non-casematched boolean key": {
317 encoded: []byte("true: test"),
318 decodeInto: new(UnmarshalTaggedStruct),
319 decoded: UnmarshalTaggedStruct{TrueLower: "test"},
320 },
321 "tagged casematched boolean key (yes)": {
322 encoded: []byte("Yes: test"),
323 decodeInto: new(UnmarshalTaggedStruct),
324 decoded: UnmarshalTaggedStruct{TrueLower: "test"},
325 },
326 "tagged non-casematched boolean key (yes)": {
327 encoded: []byte("yes: test"),
328 decodeInto: new(UnmarshalTaggedStruct),
329 decoded: UnmarshalTaggedStruct{TrueLower: "test"},
330 },
331 "tagged integer key": {
332 encoded: []byte("3: test"),
333 decodeInto: new(UnmarshalTaggedStruct),
334 decoded: UnmarshalTaggedStruct{Int3: "test"},
335 },
336 "tagged big integer key 2^53 + 1": {
337 encoded: []byte("9007199254740993: test"),
338 decodeInto: new(UnmarshalTaggedStruct),
339 decoded: UnmarshalTaggedStruct{IntBig1: "test"},
340 },
341 "tagged big integer key 1000000000000000000000000000000000000": {
342 encoded: []byte("1000000000000000000000000000000000000: test"),
343 decodeInto: new(UnmarshalTaggedStruct),
344 decoded: UnmarshalTaggedStruct{IntBig2Scientific: "test"},
345 },
346 "tagged float key": {
347 encoded: []byte("3.3: test"),
348 decodeInto: new(UnmarshalTaggedStruct),
349 decoded: UnmarshalTaggedStruct{Float3dot3: "test"},
350 },
351
352 // decode into string field
353 "string value into string field": {
354 encoded: []byte("a: test"),
355 decodeInto: new(UnmarshalStruct),
356 decoded: UnmarshalStruct{A: "test"},
357 },
358 "integer value into string field": {
359 encoded: []byte("a: 1"),
360 decodeInto: new(UnmarshalStruct),
361 decoded: UnmarshalStruct{A: "1"},
362 },
363 "boolean value into string field": {
364 encoded: []byte("a: true"),
365 decodeInto: new(UnmarshalStruct),
366 decoded: UnmarshalStruct{A: "true"},
367 },
368 "boolean value (no) into string field": {
369 encoded: []byte("a: no"),
370 decodeInto: new(UnmarshalStruct),
371 decoded: UnmarshalStruct{A: "false"},
372 },
373
374 // decode into complex fields
375 "decode into nested struct": {
376 encoded: []byte("a:\n a: 1"),
377 decodeInto: new(UnmarshalNestedStruct),
378 decoded: UnmarshalNestedStruct{UnmarshalStruct{A: "1"}},
379 },
380 "decode into slice": {
381 encoded: []byte("a:\n - a: abc\n b: def\n - a: 123"),
382 decodeInto: new(UnmarshalSlice),
383 decoded: UnmarshalSlice{[]UnmarshalStruct{{A: "abc", B: strPtr("def")}, {A: "123"}}},
384 },
385 "decode into string map": {
386 encoded: []byte("a:\n b: 1"),
387 decodeInto: new(UnmarshalStringMap),
388 decoded: UnmarshalStringMap{map[string]string{"b": "1"}},
389 },
390 "decode into struct pointer map": {
391 encoded: []byte("a:\n a: TestA\nb:\n a: TestB\n b: TestC"),
392 decodeInto: new(map[string]*UnmarshalStruct),
393 decoded: map[string]*UnmarshalStruct{
394 "a": {A: "TestA"},
395 "b": {A: "TestB", B: strPtr("TestC")},
396 },
397 },
398
399 // decoding into string map
400 "string map: decode string key": {
401 encoded: []byte("a:"),
402 decodeInto: new(map[string]struct{}),
403 decoded: map[string]struct{}{
404 "a": {},
405 },
406 },
407 "string map: decode boolean key": {
408 encoded: []byte("True:"),
409 decodeInto: new(map[string]struct{}),
410 decoded: map[string]struct{}{
411 "true": {},
412 },
413 },
414 "string map: decode boolean key (yes)": {
415 encoded: []byte("Yes:"),
416 decodeInto: new(map[string]struct{}),
417 decoded: map[string]struct{}{
418 "true": {},
419 },
420 },
421 "string map: decode integer key": {
422 encoded: []byte("44:"),
423 decodeInto: new(map[string]struct{}),
424 decoded: map[string]struct{}{
425 "44": {},
426 },
427 },
428 "string map: decode float key": {
429 encoded: []byte("444.444:"),
430 decodeInto: new(map[string]struct{}),
431 decoded: map[string]struct{}{
432 "444.444": {},
433 },
434 },
435
436 // decoding integers
•437 "decode 2^53 + 1 into int64": {
438 encoded: []byte("9007199254740993"),
439 decodeInto: new(int64),
440 decoded: int64(9007199254740993),
441 },
442 "decode 2^53 + 1 into int (architecture-specific)": {
443 encoded: []byte("9007199254740993"),
•444 decodeInto: newIntPtr(),
445 decoded: expectedIntValue(9007199254740993),
446 },
447 "decode 2^53 + 1 into interface": {
448 encoded: []byte("9007199254740993"),
449 decodeInto: new(interface{}),
450 decoded: 9.007199254740992e+15,
451 },
452
453 // decode into interface
454 "float into interface": {
455 encoded: []byte("3.0"),
456 decodeInto: new(interface{}),
457 decoded: float64(3),
458 },
459 "integer into interface": {
460 encoded: []byte("3"),
461 decodeInto: new(interface{}),
462 decoded: float64(3),
463 },
464 "empty vs empty string into interface": {
465 encoded: []byte("a: \"\"\nb: \n"),
466 decodeInto: new(interface{}),
467 decoded: map[string]interface{}{
468 "a": "",
469 "b": nil,
470 },
471 },
472
473 // duplicate (non-casematched) keys (NOTE: this is very non-ideal behaviour!)
474 "decode duplicate (non-casematched) into nested struct 1": {
475 encoded: []byte("a:\n a: 1\n b: 1\n c: test\n\nA:\n a: 2"),
476 decodeInto: new(UnmarshalNestedStruct),
477 decoded: UnmarshalNestedStruct{A: UnmarshalStruct{A: "1", B: strPtr("1"), C: "test"}},
478 },
479 "decode duplicate (non-casematched) into nested struct 2": {
480 encoded: []byte("A:\n a: 1\n b: 1\n c: test\na:\n a: 2"),
481 decodeInto: new(UnmarshalNestedStruct),
482 decoded: UnmarshalNestedStruct{A: UnmarshalStruct{A: "2", B: strPtr("1"), C: "test"}},
483 },
484 "decode duplicate (non-casematched) into nested slice 1": {
485 encoded: []byte("a:\n - a: abc\n b: def\nA:\n - a: 123"),
486 decodeInto: new(UnmarshalSlice),
487 decoded: UnmarshalSlice{[]UnmarshalStruct{{A: "abc", B: strPtr("def")}}},
488 },
489 "decode duplicate (non-casematched) into nested slice 2": {
490 encoded: []byte("A:\n - a: abc\n b: def\na:\n - a: 123"),
491 decodeInto: new(UnmarshalSlice),
492 decoded: UnmarshalSlice{[]UnmarshalStruct{{A: "123", B: strPtr("def")}}},
493 },
494 "decode duplicate (non-casematched) into nested string map 1": {
495 encoded: []byte("a:\n b: 1\nA:\n c: 1"),
496 decodeInto: new(UnmarshalStringMap),
497 decoded: UnmarshalStringMap{map[string]string{"b": "1", "c": "1"}},
498 },
499 "decode duplicate (non-casematched) into nested string map 2": {
500 encoded: []byte("A:\n b: 1\na:\n c: 1"),
501 decodeInto: new(UnmarshalStringMap),
502 decoded: UnmarshalStringMap{map[string]string{"b": "1", "c": "1"}},
503 },
504 "decode duplicate (non-casematched) into string map": {
505 encoded: []byte("a: test\nb: test\nA: test2"),
506 decodeInto: new(map[string]string),
507 decoded: map[string]string{
508 "a": "test",
509 "A": "test2",
510 "b": "test",
511 },
512 },
513
514 // decoding embeded structs
515 "decode embeded struct": {
516 encoded: []byte("a: testA\nb: testB"),
517 decodeInto: new(UnmarshalEmbedStruct),
518 decoded: UnmarshalEmbedStruct{
519 UnmarshalStruct: UnmarshalStruct{
520 A: "testA",
521 },
522 B: "testB",
523 },
524 },
525 "decode embeded structpointer": {
526 encoded: []byte("a: testA\nb: testB"),
527 decodeInto: new(UnmarshalEmbedStructPointer),
528 decoded: UnmarshalEmbedStructPointer{
529 UnmarshalStruct: &UnmarshalStruct{
530 A: "testA",
531 },
532 B: "testB",
533 },
534 },
535 "decode recursive embeded structpointer": {
536 encoded: []byte("b: testB\na:\n b: testA"),
537 decodeInto: new(UnmarshalEmbedRecursiveStruct),
538 decoded: UnmarshalEmbedRecursiveStruct{
539 UnmarshalEmbedRecursiveStruct: &UnmarshalEmbedRecursiveStruct{
540 B: "testA",
541 },
542 B: "testB",
543 },
544 },
545
546 // BUG: type info gets lost (#58)
547 "decode embeded struct and cast integer to string": {
548 encoded: []byte("a: 11\nb: testB"),
549 decodeInto: new(UnmarshalEmbedStruct),
550 decoded: UnmarshalEmbedStruct{
551 UnmarshalStruct: UnmarshalStruct{
552 A: "11",
553 },
554 B: "testB",
555 },
556 err: fatalErrorsType,
557 },
558 "decode embeded structpointer and cast integer to string": {
559 encoded: []byte("a: 11\nb: testB"),
560 decodeInto: new(UnmarshalEmbedStructPointer),
561 decoded: UnmarshalEmbedStructPointer{
562 UnmarshalStruct: &UnmarshalStruct{
563 A: "11",
564 },
565 B: "testB",
566 },
567 err: fatalErrorsType,
568 },
569
570 // decoding into incompatible type
571 "decode into stringmap with incompatible type": {
572 encoded: []byte("a:\n a:\n a: 3"),
573 decodeInto: new(UnmarshalStringMap),
574 err: fatalErrorsType,
575 },
576 }
577
578 t.Run("Unmarshal", func(t *testing.T) {
579 testUnmarshal(t, funcUnmarshal, tests)
580 })
581
582 t.Run("UnmarshalStrict", func(t *testing.T) {
583 testUnmarshal(t, funcUnmarshalStrict, tests)
584 })
585 }
586
587 func TestUnmarshalStrictFails(t *testing.T) {
588 tests := map[string]unmarshalTestCase{
589 // decoding with duplicate values
590 "decode into struct pointer map with duplicate string value": {
591 encoded: []byte("a:\n a: TestA\n b: ID-A\n b: ID-1"),
592 decodeInto: new(map[string]*UnmarshalStruct),
593 decoded: map[string]*UnmarshalStruct{
594 "a": {A: "TestA", B: strPtr("ID-1")},
595 },
596 },
597 "decode into string field with duplicate boolean value": {
598 encoded: []byte("a: true\na: false"),
599 decodeInto: new(UnmarshalStruct),
600 decoded: UnmarshalStruct{A: "false"},
601 },
602 "decode into slice with duplicate string-boolean value": {
603 encoded: []byte("a:\n- b: abc\n a: 32\n b: 123"),
604 decodeInto: new(UnmarshalSlice),
605 decoded: UnmarshalSlice{[]UnmarshalStruct{{A: "32", B: strPtr("123")}}},
606 },
607
608 // decoding with unknown fields
609 "decode into struct with unknown field": {
610 encoded: []byte("a: TestB\nb: ID-B\nunknown: Some-Value"),
611 decodeInto: new(UnmarshalStruct),
612 decoded: UnmarshalStruct{A: "TestB", B: strPtr("ID-B")},
613 },
614
615 // decoding with duplicate complex values
616 "decode duplicate into nested struct": {
617 encoded: []byte("a:\n a: 1\na:\n a: 2"),
618 decodeInto: new(UnmarshalNestedStruct),
619 decoded: UnmarshalNestedStruct{A: UnmarshalStruct{A: "2"}},
620 },
621 "decode duplicate into nested slice": {
622 encoded: []byte("a:\n - a: abc\n b: def\na:\n - a: 123"),
623 decodeInto: new(UnmarshalSlice),
624 decoded: UnmarshalSlice{[]UnmarshalStruct{{A: "123"}}},
625 },
626 "decode duplicate into nested string map": {
627 encoded: []byte("a:\n b: 1\na:\n c: 1"),
628 decodeInto: new(UnmarshalStringMap),
629 decoded: UnmarshalStringMap{map[string]string{"c": "1"}},
630 },
631 "decode duplicate into string map": {
632 encoded: []byte("a: test\nb: test\na: test2"),
633 decodeInto: new(map[string]string),
634 decoded: map[string]string{
635 "a": "test2",
636 "b": "test",
637 },
638 },
639 }
640
641 t.Run("Unmarshal", func(t *testing.T) {
642 testUnmarshal(t, funcUnmarshal, tests)
643 })
644
645 t.Run("UnmarshalStrict", func(t *testing.T) {
646 failTests := map[string]unmarshalTestCase{}
647 for name, test := range tests {
648 test.err = fatalErrorsType
649 failTests[name] = test
650 }
651 testUnmarshal(t, funcUnmarshalStrict, failTests)
652 })
653 }
654
655 func TestYAMLToJSON(t *testing.T) {
656 tests := map[string]yamlToJSONTestcase{
657 "string value": {
658 yaml: "t: a\n",
659 json: `{"t":"a"}`,
660 },
661 "null value": {
662 yaml: "t: null\n",
663 json: `{"t":null}`,
664 },
665 "boolean value": {
666 yaml: "t: True\n",
667 json: `{"t":true}`,
668 yamlReverseOverwrite: strPtr("t: true\n"),
669 },
670 "boolean value (no)": {
671 yaml: "t: no\n",
672 json: `{"t":false}`,
673 yamlReverseOverwrite: strPtr("t: false\n"),
674 },
675 "integer value (2^53 + 1)": {
676 yaml: "t: 9007199254740993\n",
677 json: `{"t":9007199254740993}`,
678 yamlReverseOverwrite: strPtr("t: 9007199254740993\n"),
679 },
680 "integer value (1000000000000000000000000000000000000)": {
681 yaml: "t: 1000000000000000000000000000000000000\n",
682 json: `{"t":1e+36}`,
683 yamlReverseOverwrite: strPtr("t: 1e+36\n"),
684 },
685 "line-wrapped string value": {
686 yaml: "t: this is very long line with spaces and it must be longer than 80 so we will repeat\n that it must be longer that 80\n",
687 json: `{"t":"this is very long line with spaces and it must be longer than 80 so we will repeat that it must be longer that 80"}`,
688 },
689 "empty yaml value": {
690 yaml: "t: ",
691 json: `{"t":null}`,
692 yamlReverseOverwrite: strPtr("t: null\n"),
693 },
694 "boolean key": {
695 yaml: "True: a",
696 json: `{"true":"a"}`,
697 yamlReverseOverwrite: strPtr("\"true\": a\n"),
698 },
699 "boolean key (no)": {
700 yaml: "no: a",
701 json: `{"false":"a"}`,
702 yamlReverseOverwrite: strPtr("\"false\": a\n"),
703 },
704 "integer key": {
705 yaml: "1: a",
706 json: `{"1":"a"}`,
707 yamlReverseOverwrite: strPtr("\"1\": a\n"),
708 },
709 "float key": {
710 yaml: "1.2: a",
711 json: `{"1.2":"a"}`,
712 yamlReverseOverwrite: strPtr("\"1.2\": a\n"),
713 },
714 "large integer key": {
715 yaml: "1000000000000000000000000000000000000: a",
716 json: `{"1e+36":"a"}`,
717 yamlReverseOverwrite: strPtr("\"1e+36\": a\n"),
718 },
719 "large integer key (scientific notation)": {
720 yaml: "1e+36: a",
721 json: `{"1e+36":"a"}`,
722 yamlReverseOverwrite: strPtr("\"1e+36\": a\n"),
723 },
724 "string key (large integer as string)": {
725 yaml: "\"1e+36\": a\n",
726 json: `{"1e+36":"a"}`,
727 },
728 "string key (float as string)": {
729 yaml: "\"1.2\": a\n",
730 json: `{"1.2":"a"}`,
731 },
732 "array": {
733 yaml: "- t: a\n",
734 json: `[{"t":"a"}]`,
735 },
736 "nested struct array": {
737 yaml: "- t: a\n- t:\n b: 1\n c: 2\n",
738 json: `[{"t":"a"},{"t":{"b":1,"c":2}}]`,
739 },
740 "nested struct array (json notation)": {
741 yaml: `[{t: a}, {t: {b: 1, c: 2}}]`,
742 json: `[{"t":"a"},{"t":{"b":1,"c":2}}]`,
743 yamlReverseOverwrite: strPtr("- t: a\n- t:\n b: 1\n c: 2\n"),
744 },
745 "empty struct value": {
746 yaml: "- t: ",
747 json: `[{"t":null}]`,
748 yamlReverseOverwrite: strPtr("- t: null\n"),
749 },
750 "null struct value": {
751 yaml: "- t: null\n",
752 json: `[{"t":null}]`,
753 },
754 "binary data": {
•755 yaml: "a: !!binary gIGC",
756 json: `{"a":"\ufffd\ufffd\ufffd"}`,
757 // Go json/v2 emits U+FFFD as raw UTF-8 bytes rather than the \ufffd escape.
758 jsonAllow: []string{"{\"a\":\"\ufffd\ufffd\ufffd\"}"},
759 yamlReverseOverwrite: strPtr("a: \ufffd\ufffd\ufffd\n"),
760 },
761
762 // Cases that should produce errors.
763 "~ key": {
764 yaml: "~: a",
765 json: `{"null":"a"}`,
766 yamlReverseOverwrite: strPtr("\"null\": a\n"),
767 err: fatalErrorsType,
768 },
769 "null key": {
770 yaml: "null: a",
771 json: `{"null":"a"}`,
772 yamlReverseOverwrite: strPtr("\"null\": a\n"),
773 err: fatalErrorsType,
774 },
775 }
776
777 t.Run("YAMLToJSON", func(t *testing.T) {
778 testYAMLToJSON(t, funcYAMLToJSON, tests)
779 })
780
781 t.Run("YAMLToJSONStrict", func(t *testing.T) {
782 testYAMLToJSON(t, funcYAMLToJSONStrict, tests)
783 })
784 }
785
786 func TestYAMLToJSONStrictFails(t *testing.T) {
787 tests := map[string]yamlToJSONTestcase{
788 // expect YAMLtoJSON to pass on duplicate field names
789 "duplicate struct value": {
790 yaml: "foo: bar\nfoo: baz\n",
791 json: `{"foo":"baz"}`,
792 yamlReverseOverwrite: strPtr("foo: baz\n"),
793 },
794 }
795
796 t.Run("YAMLToJSON", func(t *testing.T) {
797 testYAMLToJSON(t, funcYAMLToJSON, tests)
798 })
799
800 t.Run("YAMLToJSONStrict", func(t *testing.T) {
801 failTests := map[string]yamlToJSONTestcase{}
802 for name, test := range tests {
803 test.err = fatalErrorsType
804 failTests[name] = test
805 }
806 testYAMLToJSON(t, funcYAMLToJSONStrict, failTests)
807 })
808 }
809
810 func TestJSONObjectToYAMLObject(t *testing.T) {
811 const bigUint64 = ((uint64(1) << 63) + 500) / 1000 * 1000
812 intOrInt64 := func(i64 int64) interface{} {
813 if i := int(i64); i64 == int64(i) {
814 return i
815 }
816 return i64
817 }
818
819 tests := []struct {
820 name string
821 input map[string]interface{}
822 expected yamlv2.MapSlice
823 }{
824 {name: "nil", expected: yamlv2.MapSlice(nil)},
825 {name: "empty", input: map[string]interface{}{}, expected: yamlv2.MapSlice(nil)},
826 {
827 name: "values",
828 input: map[string]interface{}{
829 "nil slice": []interface{}(nil),
830 "nil map": map[string]interface{}(nil),
831 "empty slice": []interface{}{},
832 "empty map": map[string]interface{}{},
833 "bool": true,
834 "float64": float64(42.1),
835 "fractionless": float64(42),
836 "int": int(42),
837 "int64": int64(42),
838 "int64 big": float64(math.Pow(2, 62)),
839 "negative int64 big": -float64(math.Pow(2, 62)),
840 "map": map[string]interface{}{"foo": "bar"},
841 "slice": []interface{}{"foo", "bar"},
842 "string": string("foo"),
843 "uint64 big": bigUint64,
844 },
845 expected: yamlv2.MapSlice{
846 {Key: "nil slice"},
847 {Key: "nil map"},
848 {Key: "empty slice", Value: []interface{}{}},
849 {Key: "empty map", Value: yamlv2.MapSlice(nil)},
850 {Key: "bool", Value: true},
851 {Key: "float64", Value: float64(42.1)},
852 {Key: "fractionless", Value: int(42)},
853 {Key: "int", Value: int(42)},
854 {Key: "int64", Value: int(42)},
855 {Key: "int64 big", Value: intOrInt64(int64(1) << 62)},
856 {Key: "negative int64 big", Value: intOrInt64(-(1 << 62))},
857 {Key: "map", Value: yamlv2.MapSlice{{Key: "foo", Value: "bar"}}},
858 {Key: "slice", Value: []interface{}{"foo", "bar"}},
859 {Key: "string", Value: string("foo")},
860 {Key: "uint64 big", Value: bigUint64},
861 },
862 },
863 }
864 for _, tt := range tests {
865 t.Run(tt.name, func(t *testing.T) {
866 got := JSONObjectToYAMLObject(tt.input)
867 sortMapSlicesInPlace(tt.expected)
868 sortMapSlicesInPlace(got)
869 if !reflect.DeepEqual(tt.expected, got) {
870 t.Errorf("jsonToYAML() returned unexpected results (-want+got):\n%v", cmp.Diff(tt.expected, got))
871 }
872
873 jsonBytes, err := json.Marshal(tt.input)
874 if err != nil {
875 t.Fatalf("unexpected json.Marshal error: %v", err)
876 }
877 var gotByRoundtrip yamlv2.MapSlice
878 if err := yamlv2.Unmarshal(jsonBytes, &gotByRoundtrip); err != nil {
879 t.Fatalf("unexpected yaml.Unmarshal error: %v", err)
880 }
881
882 // yamlv2.Unmarshal loses precision, it's rounding to the 4th last digit.
883 // Replicate this here in the test, but don't change the type.
884 for i := range got {
885 switch got[i].Key {
886 case "int64 big", "uint64 big", "negative int64 big":
887 switch v := got[i].Value.(type) {
888 case int64:
889 d := int64(500)
890 if v < 0 {
891 d = -500
892 }
893 got[i].Value = int64((v+d)/1000) * 1000
894 case uint64:
895 got[i].Value = uint64((v+500)/1000) * 1000
896 case int:
897 d := int(500)
898 if v < 0 {
899 d = -500
900 }
901 got[i].Value = int((v+d)/1000) * 1000
902 default:
903 t.Fatalf("unexpected type for key %s: %v:%T", got[i].Key, v, v)
904 }
905 }
906 }
907
908 if !reflect.DeepEqual(got, gotByRoundtrip) {
909 t.Errorf("yaml.Unmarshal(json.Marshal(tt.input)) returned unexpected results (-want+got):\n%v", cmp.Diff(got, gotByRoundtrip))
910 t.Errorf("json: %s", string(jsonBytes))
911 }
912 })
913 }
914 }
915
916 func sortMapSlicesInPlace(x interface{}) {
917 switch x := x.(type) {
918 case []interface{}:
919 for i := range x {
920 sortMapSlicesInPlace(x[i])
921 }
922 case yamlv2.MapSlice:
923 sort.Slice(x, func(a, b int) bool {
924 return x[a].Key.(string) < x[b].Key.(string)
925 })
926 }
927 }
928
929 func TestPatchedYamlV3AndUpstream(t *testing.T) {
930 input := `group: apps
931 apiVersion: v1
932 kind: Deployment
933 metadata:
934 name: deploy1
935 spec:
936 template:
937 spec:
938 containers:
939 - image: nginx:1.7.9
940 name: nginx-tagged
941 - image: nginx:latest
942 name: nginx-latest
943 - image: foobar:1
944 name: replaced-with-digest
945 - image: postgres:1.8.0
946 name: postgresdb
947 initContainers:
948 - image: nginx
949 name: nginx-notag
950 - image: nginx@sha256:111111111111111111
951 name: nginx-sha256
952 - image: alpine:1.8.0
953 name: init-alpine
954 `
955
956 var v3Map map[string]interface{}
957 var v2Map map[string]interface{}
958
959 // unmarshal the input into the two maps
960 if err := yamlv3.Unmarshal([]byte(input), &v3Map); err != nil {
961 t.Fatal(err)
962 }
963 if err := yamlv2.Unmarshal([]byte(input), &v2Map); err != nil {
964 t.Fatal(err)
965 }
966
967 // marshal using non-default settings from the yaml v3 fork
968 var buf bytes.Buffer
969 enc := yamlv3.NewEncoder(&buf)
970 enc.CompactSeqIndent()
971 enc.SetIndent(2)
972 err := enc.Encode(v3Map)
973 v3output := buf.String()
974
975 // marshal using the yaml v2 fork
976 v2output, err := yamlv2.Marshal(v2Map)
977 if err != nil {
978 t.Fatal(err)
979 }
980 if v3output != string(v2output) {
981 t.Fatalf("expected\n%s\ngot\n%s", string(v2output), v3output)
982 }
983 }
984
985 func TestUnmarshalWithTags(t *testing.T) {
986 type WithTaggedField struct {
987 Field string `json:"field"`
988 }
989
990 t.Run("Known tagged field", func(t *testing.T) {
991 y := []byte(`field: "hello"`)
992 v := WithTaggedField{}
993 if err := Unmarshal(y, &v, DisallowUnknownFields); err != nil {
994 t.Errorf("unexpected error: %v", err)
995 }
996 if v.Field != "hello" {
997 t.Errorf("v.Field=%v, want 'hello'", v.Field)
998 }
999
1000 })
1001 t.Run("With unknown tagged field", func(t *testing.T) {
1002 y := []byte(`unknown: "hello"`)
1003 v := WithTaggedField{}
1004 err := Unmarshal(y, &v, DisallowUnknownFields)
1005 if err == nil {
1006 t.Errorf("want error because of unknown field, got <nil>: v=%#v", v)
1007 }
1008 })
1009
1010 }
1011
1012 func exampleUnknown() {
1013 type WithTaggedField struct {
1014 Field string `json:"field"`
1015 }
1016 y := []byte(`unknown: "hello"`)
1017 v := WithTaggedField{}
1018 fmt.Printf("%v\n", Unmarshal(y, &v, DisallowUnknownFields))
1019 // Ouptut:
1020 // unmarshaling JSON: while decoding JSON: json: unknown field "unknown"
1021 }