Debian Codegraph @

yaml_test.go

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