Debian Codegraph @

yaml_test.go

raw symbols SCIP
1 // Copyright 2011-2019 Canonical Ltd
2 // Copyright 2025 The go-yaml Project Contributors
3 // SPDX-License-Identifier: Apache-2.0
4
5 // Tests for YAML marshal/unmarshal functionality, including struct tags,
6 // type conversions, anchors/aliases, and edge cases.
7
8 package yaml_test
9
10 import (
11 "bytes"
12 "encoding"
13 "encoding/json"
14 "errors"
15 "fmt"
16 "io"
17 "math"
18 "net"
19 "os"
20 "reflect"
21 "strconv"
22 "strings"
23 "testing"
24 "time"
25
26 "go.yaml.in/yaml/v4"
27 "go.yaml.in/yaml/v4/internal/libyaml"
28 "go.yaml.in/yaml/v4/internal/testutil/assert"
29 "go.yaml.in/yaml/v4/internal/testutil/datatest"
30 )
31
32 // negativeZero represents -0.0 for YAML test cases
33 // this is needed because Go constants cannot express -0.0
34 // https://staticcheck.dev/docs/checks/#SA4026
35 var negativeZero = math.Copysign(0.0, -1.0)
36
37 var unmarshalIntTest = 123
38
39 // archSafeInt returns v as int if it fits in the architecture's int type,
40 // otherwise returns int64.
41 func archSafeInt(v int64) any {
42 if strconv.IntSize == 64 || math.MinInt32 <= v && v <= math.MaxInt32 {
43 return int(v) // int is safe
44 }
45
46 // on 32-bit systems, and v overflows int, we need to return an int64
47 return v
48 }
49
50 // Named struct types for data-driven tests
51 type (
52 testStructHello struct{ Hello string }
53 testStructA_Int struct{ A int }
54 testStructA_Float64 struct{ A float64 }
55 testStructA_Uint struct{ A uint }
56 testStructA_Bool struct{ A bool }
57 testStructA_IntSlice struct{ A []int }
58 testStructA_IntArray2 struct{ A [2]int }
59 testStructA_MapStringString struct{ A map[string]string }
60 testStructA_MapStringStringPtr struct{ A *map[string]string }
61 testStructB_Int struct{ B int }
62 nestedStructB struct{ B string }
63 testStructA_NestedB struct{ A nestedStructB }
64 testStructA_NestedBPtr struct{ A *nestedStructB }
65 testStructABCD_Int struct{ A, B, C, D int }
66 testStructB_IntSlice struct{ B []int }
67 testStructA_IntSliceEmpty struct{ A []int }
68 testStructA_String struct{ A string }
69 testStructEmpty struct{}
70 )
71
72 // Types with yaml struct tags
73 type (
74 testStructB_Int_TagA struct {
75 B int `yaml:"a"`
76 }
77 testStructAB_Int_BIgnored struct {
78 A int
79 B int `yaml:"-"`
80 }
81 testStructA_Int_InlineB struct {
82 A int
83 C inlineB `yaml:",inline"`
84 }
85 testStructA_Int_InlineBPtr struct {
86 A int
87 C *inlineB `yaml:",inline"`
88 }
89 testStructA_Int_InlineDPtr struct {
90 A int
91 C *inlineD `yaml:",inline"`
92 }
93 testStructA_Int_InlineMapStringInt struct {
94 A int
95 C map[string]int `yaml:",inline"`
96 }
97 )
98
99 // simpleTextUnmarshaler is a simple type implementing [encoding.TextUnmarshaler]
100 // for testing TextUnmarshaler validation.
101 type simpleTextUnmarshaler struct {
102 Value string
103 }
104
105 func (s *simpleTextUnmarshaler) UnmarshalText(text []byte) error {
106 s.Value = string(text)
107 return nil
108 }
109
110 // Test types for TextUnmarshaler validation
111 type (
112 testStructA_TextUnmarshaler struct {
113 A simpleTextUnmarshaler
114 }
115 testStructA_TextUnmarshalerPtr struct {
116 A *simpleTextUnmarshaler
117 }
118 testStructA_TextUnmarshalerPtrPtr struct {
119 A **simpleTextUnmarshaler
120 }
121 testStructAB_TextUnmarshaler struct {
122 A simpleTextUnmarshaler
123 B simpleTextUnmarshaler
124 }
125 )
126
127 type textUnmarshalerWithYAMLUnmarshaler []string
128
129 var _ interface {
130 encoding.TextUnmarshaler
131 yaml.Unmarshaler
132 } = &textUnmarshalerWithYAMLUnmarshaler{}
133
134 func (ty *textUnmarshalerWithYAMLUnmarshaler) UnmarshalText(text []byte) error {
135 panic("UnmarshalText called on type with UnmarshalYAML")
136 }
137
138 func (ty *textUnmarshalerWithYAMLUnmarshaler) UnmarshalYAML(node *yaml.Node) error {
139 return node.Decode((*[]string)(ty))
140 }
141
142 func TestTextUnmarshalerWithYAMLUnmarshaler(t *testing.T) {
143 var target textUnmarshalerWithYAMLUnmarshaler
144 const input = `[foo, bar]`
145
146 // NOTE: also verified with [yaml.Unmarshal] — no shortcut bypasses
147 // Constructor since PR #310, so this is a regression test for
148 // [libyaml.Constructor.Construct] via both paths.
149 err := yaml.NewDecoder(strings.NewReader(input)).Decode(&target)
150
151 assert.NoError(t, err)
152 assert.DeepEqual(t, textUnmarshalerWithYAMLUnmarshaler{"foo", "bar"}, target)
153 }
154
155 // Type and value registries for data-driven tests
156 var (
157 decodeTypes = datatest.NewTypeRegistry()
158 decodeValues = datatest.NewValueRegistry()
159 )
160
161 func init() {
162 // Register basic map types
163 decodeTypes.RegisterFactory("map[string]string", func() any {
164 return make(map[string]string)
165 })
166 decodeTypes.RegisterFactory("map[string]any", func() any {
167 return make(map[string]any)
168 })
169 decodeTypes.RegisterFactory("map[string]int64", func() any {
170 return make(map[string]int64)
171 })
172 decodeTypes.RegisterFactory("map[string]float64", func() any {
173 return make(map[string]float64)
174 })
175 decodeTypes.RegisterFactory("map[string][]byte", func() any {
176 return make(map[string][]byte)
177 })
178 decodeTypes.RegisterFactory("map[any]any", func() any {
179 return make(map[any]any)
180 })
181
182 // Register slice types
183 decodeTypes.RegisterFactory("[]string", func() any {
184 return []string{}
185 })
186 decodeTypes.RegisterFactory("[]int", func() any {
187 return []int{}
188 })
189 decodeTypes.RegisterFactory("[]any", func() any {
190 return []any{}
191 })
192
193 // Register primitive types
194 decodeTypes.RegisterFactory("string", func() any {
195 return ""
196 })
197
198 // Register map types with slice values
199 decodeTypes.RegisterFactory("map[string][]string", func() any {
200 return make(map[string][]string)
201 })
202 decodeTypes.RegisterFactory("map[string][]int", func() any {
203 return make(map[string][]int)
204 })
205
206 // Register additional map types
207 decodeTypes.RegisterFactory("map[string]bool", func() any {
208 return make(map[string]bool)
209 })
210 decodeTypes.RegisterFactory("map[string]int", func() any {
211 return make(map[string]int)
212 })
213 decodeTypes.RegisterFactory("map[any]string", func() any {
214 return make(map[any]string)
215 })
216 decodeTypes.RegisterFactory("map[string]uint", func() any {
217 return make(map[string]uint)
218 })
219 decodeTypes.RegisterFactory("map[string]uint64", func() any {
220 return make(map[string]uint64)
221 })
222 decodeTypes.RegisterFactory("map[string]int32", func() any {
223 return make(map[string]int32)
224 })
225 decodeTypes.RegisterFactory("map[string]int8", func() any {
226 return make(map[string]int8)
227 })
228 decodeTypes.RegisterFactory("map[string]float32", func() any {
229 return make(map[string]float32)
230 })
231
232 // Register struct types
233 decodeTypes.Register("testStructHello", testStructHello{})
234 decodeTypes.Register("testStructA_Int", testStructA_Int{})
235 decodeTypes.Register("testStructA_Float64", testStructA_Float64{})
236 decodeTypes.Register("testStructA_Uint", testStructA_Uint{})
237 decodeTypes.Register("testStructA_Bool", testStructA_Bool{})
238 decodeTypes.Register("testStructA_IntSlice", testStructA_IntSlice{})
239 decodeTypes.Register("testStructA_IntArray2", testStructA_IntArray2{})
240 decodeTypes.Register("testStructA_MapStringString", testStructA_MapStringString{})
241 decodeTypes.Register("testStructA_MapStringStringPtr", testStructA_MapStringStringPtr{})
242 decodeTypes.Register("testStructB_Int", testStructB_Int{})
243 decodeTypes.Register("testStructA_NestedB", testStructA_NestedB{})
244 decodeTypes.Register("testStructA_NestedBPtr", testStructA_NestedBPtr{})
245 decodeTypes.Register("testStructABCD_Int", testStructABCD_Int{})
246 decodeTypes.Register("testStructB_IntSlice", testStructB_IntSlice{})
247 decodeTypes.Register("testStructA_IntSliceEmpty", testStructA_IntSliceEmpty{})
248 decodeTypes.Register("testStructA_String", testStructA_String{})
249 decodeTypes.Register("testStructEmpty", testStructEmpty{})
250
251 // Register struct types with yaml tags
252 decodeTypes.Register("testStructB_Int_TagA", testStructB_Int_TagA{})
253 decodeTypes.Register("testStructAB_Int_BIgnored", testStructAB_Int_BIgnored{})
254 decodeTypes.Register("testStructA_Int_InlineB", testStructA_Int_InlineB{})
255 decodeTypes.Register("testStructA_Int_InlineBPtr", testStructA_Int_InlineBPtr{})
256 decodeTypes.Register("testStructA_Int_InlineDPtr", testStructA_Int_InlineDPtr{})
257 decodeTypes.Register("testStructA_Int_InlineMapStringInt", testStructA_Int_InlineMapStringInt{})
258
259 // Register TextUnmarshaler test types
260 decodeTypes.Register("testStructA_TextUnmarshaler", testStructA_TextUnmarshaler{})
261 decodeTypes.Register("testStructA_TextUnmarshalerPtr", testStructA_TextUnmarshalerPtr{})
262 decodeTypes.Register("testStructA_TextUnmarshalerPtrPtr", testStructA_TextUnmarshalerPtrPtr{})
263 decodeTypes.Register("testStructAB_TextUnmarshaler", testStructAB_TextUnmarshaler{})
264
265 // Register math constants
266 decodeValues.Register("+Inf", math.Inf(+1))
267 decodeValues.Register("-Inf", math.Inf(-1))
268 decodeValues.Register("NaN", math.NaN())
269 decodeValues.Register("-0", negativeZero)
270
271 // Register math limit constants
272 decodeValues.Register("MaxInt32", int(math.MaxInt32))
273 decodeValues.Register("MinInt32", int(math.MinInt32))
274 decodeValues.Register("MaxInt64", int64(math.MaxInt64))
275 decodeValues.Register("MinInt64", int64(math.MinInt64))
276 decodeValues.Register("MaxUint32", uint(math.MaxUint32))
277 decodeValues.Register("MaxUint64", uint64(math.MaxUint64))
278 decodeValues.Register("MaxFloat32", math.MaxFloat32)
279 decodeValues.Register("MaxFloat64", math.MaxFloat64)
280 decodeValues.Register("SmallestNonzeroFloat32", math.SmallestNonzeroFloat32)
281 decodeValues.Register("SmallestNonzeroFloat64", math.SmallestNonzeroFloat64)
282 }
283
284 var unmarshalTests = []struct {
285 data string
286 value any
287 }{
288 {
289 "",
290 (*struct{})(nil),
291 },
292 {
293 "{}", &struct{}{},
294 },
295
296 // Simple values.
297 {
298 "123",
299 &unmarshalIntTest,
300 },
301 {
302 "-0",
303 negativeZero,
304 },
305 {
306 "\"\\t\\n\"\n",
307 "\t\n",
308 },
309
310 // Cross-architecture numeric tests
311 {
312 "bin: -0b1000000000000000000000000000000000000000000000000000000000000000",
313 map[string]any{"bin": archSafeInt(math.MinInt64)},
314 },
315 {
316 // When unmarshaling into map[string]int64, values that overflow int64
317 // cannot be decoded and result in an empty map.
318 "int_overflow: 9223372036854775808", // math.MaxInt64 + 1
319 map[string]int64{},
320 },
321
322 // Structs and type conversions.
323 {
324 "a: 'null'",
325 &struct{ A *unmarshalerType }{&unmarshalerType{"null"}},
326 },
327
328 // Anchors and aliases.
329 {
330 "a: &x 1\nb: &y 2\nc: *x\nd: *y\n",
331 &struct{ A, B, C, D int }{1, 2, 1, 2},
332 },
333 {
334 "a: &a {c: 1}\nb: *a",
335 &struct {
336 A, B struct {
337 C int
338 }
339 }{struct{ C int }{1}, struct{ C int }{1}},
340 },
341 {
342 "a: &a [1, 2]\nb: *a",
343 &struct{ B []int }{[]int{1, 2}},
344 },
345 {
346 "a: &a.b1.c [1, 2]\nb: *a.b1.c",
347 &struct{ B []int }{[]int{1, 2}},
348 },
349
350 // Bug https://github.com/yaml/go-yaml/issues/109
351 // Bug #1133337
352 {
353 "foo: ''",
354 map[string]*string{"foo": new(string)},
355 },
356 {
357 "foo: null",
358 map[string]*string{"foo": nil},
359 },
360
361 // Support for ~
362 {
363 "foo: ~",
364 map[string]*string{"foo": nil},
365 },
366
367 // Ignored field
368 {
369 "a: 1\nb: 2\n",
370 &struct {
371 A int
372 B int `yaml:"-"`
373 }{1, 0},
374 },
375
376 // Bug #1191981
377 {
378 "" +
379 "%YAML 1.1\n" +
380 "--- !!str\n" +
381 `"Generic line break (no glyph)\n\` + "\n" +
382 ` Generic line break (glyphed)\n\` + "\n" +
383 ` Line separator\u2028\` + "\n" +
384 ` Paragraph separator\u2029"` + "\n",
385 "" +
386 "Generic line break (no glyph)\n" +
387 "Generic line break (glyphed)\n" +
388 "Line separator\u2028Paragraph separator\u2029",
389 },
390
391 // Duration
392 {
393 "a: 3s",
394 map[string]time.Duration{"a": 3 * time.Second},
395 },
396 // Zero duration as a string.
397 {
398 "a: '0'",
399 map[string]time.Duration{"a": 0},
400 },
401 // Zero duration as an int.
402 {
403 "a: 0",
404 map[string]time.Duration{"a": 0},
405 },
406
407 // Binary data.
408 {
409 "a: !!binary gIGC\n",
410 map[string]string{"a": "\x80\x81\x82"},
411 },
412 {
413 "a: !!binary |\n " + strings.Repeat("kJCQ", 17) + "kJ\n CQ\n",
414 map[string]string{"a": strings.Repeat("\x90", 54)},
415 },
416 {
417 "a: !!binary |\n " + strings.Repeat("A", 70) + "\n ==\n",
418 map[string]string{"a": strings.Repeat("\x00", 52)},
419 },
420
421 // Scalar to string conversions.
422 // Float to string (regression test for constructFloat missing reflect.String case).
423 {
424 "a: 55.7351",
425 map[string]string{"a": "55.7351"},
426 },
427 {
428 "a: -3.14159",
429 map[string]string{"a": "-3.14159"},
430 },
431 {
432 "a: 1.23e10",
433 map[string]string{"a": "1.23e10"},
434 },
435 {
436 "a: .inf",
437 map[string]string{"a": ".inf"},
438 },
439 {
440 "a: -.inf",
441 map[string]string{"a": "-.inf"},
442 },
443 {
444 "a: .nan",
445 map[string]string{"a": ".nan"},
446 },
447 // Int to string (verify existing constructInt string case).
448 {
449 "a: 42",
450 map[string]string{"a": "42"},
451 },
452 {
453 "a: -100",
454 map[string]string{"a": "-100"},
455 },
456 {
457 "a: 0x1A",
458 map[string]string{"a": "0x1A"},
459 },
460 {
461 "a: 0o755",
462 map[string]string{"a": "0o755"},
463 },
464 // Bool to string (verify existing constructBool string case).
465 {
466 "a: true",
467 map[string]string{"a": "true"},
468 },
469 {
470 "a: false",
471 map[string]string{"a": "false"},
472 },
473
474 // Issue #39.
475 {
476 "a:\n b:\n c: d\n",
477 map[string]struct{ B any }{"a": {map[string]any{"c": "d"}}},
478 },
479
480 // Custom map type.
481 {
482 "a: {b: c}",
483 M{"a": M{"b": "c"}},
484 },
485
486 // Support encoding.TextUnmarshaler.
487 {
488 "a: 1.2.3.4\n",
489 map[string]textUnmarshaler{"a": {S: "1.2.3.4"}},
490 },
491 {
492 "a: 2015-02-24T18:19:39Z\n",
493 map[string]textUnmarshaler{"a": {"2015-02-24T18:19:39Z"}},
494 },
495
496 // Timestamps
497 {
498 // Date only.
499 "a: 2015-01-01\n",
500 map[string]time.Time{"a": time.Date(2015, 1, 1, 0, 0, 0, 0, time.UTC)},
501 },
502 {
503 // RFC3339
504 "a: 2015-02-24T18:19:39.12Z\n",
505 map[string]time.Time{"a": time.Date(2015, 2, 24, 18, 19, 39, .12e9, time.UTC)},
506 },
507 {
508 // RFC3339 with short dates.
509 "a: 2015-2-3T3:4:5Z",
510 map[string]time.Time{"a": time.Date(2015, 2, 3, 3, 4, 5, 0, time.UTC)},
511 },
512 {
513 // ISO8601 lower case t
514 "a: 2015-02-24t18:19:39Z\n",
515 map[string]time.Time{"a": time.Date(2015, 2, 24, 18, 19, 39, 0, time.UTC)},
516 },
517 {
518 // space separate, no time zone
519 "a: 2015-02-24 18:19:39\n",
520 map[string]time.Time{"a": time.Date(2015, 2, 24, 18, 19, 39, 0, time.UTC)},
521 },
522 // Some cases not currently handled. Uncomment these when
523 // the code is fixed.
524 // {
525 // // space separated with time zone
526 // "a: 2001-12-14 21:59:43.10 -5",
527 // map[string]any{"a": time.Date(2001, 12, 14, 21, 59, 43, .1e9, time.UTC)},
528 // },
529 // {
530 // // arbitrary whitespace between fields
531 // "a: 2001-12-14 \t\t \t21:59:43.10 \t Z",
532 // map[string]any{"a": time.Date(2001, 12, 14, 21, 59, 43, .1e9, time.UTC)},
533 // },
534 {
535 // explicit string tag
536 "a: !!str 2015-01-01",
537 map[string]any{"a": "2015-01-01"},
538 },
539 {
540 // explicit timestamp tag on quoted string
541 "a: !!timestamp \"2015-01-01\"",
542 map[string]time.Time{"a": time.Date(2015, 1, 1, 0, 0, 0, 0, time.UTC)},
543 },
544 {
545 // explicit timestamp tag on unquoted string
546 "a: !!timestamp 2015-01-01",
547 map[string]time.Time{"a": time.Date(2015, 1, 1, 0, 0, 0, 0, time.UTC)},
548 },
549 {
550 // explicit timestamp tag into interface.
551 "a: !!timestamp \"2015-01-01\"",
552 map[string]any{"a": time.Date(2015, 1, 1, 0, 0, 0, 0, time.UTC)},
553 },
554 {
555 // implicit timestamp tag into interface.
556 "a: 2015-01-01",
557 map[string]any{"a": time.Date(2015, 1, 1, 0, 0, 0, 0, time.UTC)},
558 },
559
560 // UTF-16-LE
561 {
562 "\xff\xfe\xf1\x00o\x00\xf1\x00o\x00:\x00 \x00v\x00e\x00r\x00y\x00 \x00y\x00e\x00s\x00\n\x00",
563 M{"ñoño": "very yes"},
564 },
565 // UTF-16-LE with surrogate.
566 {
567 "\xff\xfe\xf1\x00o\x00\xf1\x00o\x00:\x00 \x00v\x00e\x00r\x00y\x00 \x00y\x00e\x00s\x00 \x00=\xd8\xd4\xdf\n\x00",
568 M{"ñoño": "very yes 🟔"},
569 },
570
571 // UTF-16-BE
572 {
573 "\xfe\xff\x00\xf1\x00o\x00\xf1\x00o\x00:\x00 \x00v\x00e\x00r\x00y\x00 \x00y\x00e\x00s\x00\n",
574 M{"ñoño": "very yes"},
575 },
576 // UTF-16-BE with surrogate.
577 {
578 "\xfe\xff\x00\xf1\x00o\x00\xf1\x00o\x00:\x00 \x00v\x00e\x00r\x00y\x00 \x00y\x00e\x00s\x00 \xd8=\xdf\xd4\x00\n",
579 M{"ñoño": "very yes 🟔"},
580 },
581
582 // Comment scan exhausting the input buffer (issue #469).
583 {
584 "true\n#" + strings.Repeat(" ", 512*3),
585 "true",
586 },
587 {
588 "true #" + strings.Repeat(" ", 512*3),
589 "true",
590 },
591 {
592 `---
593 foo:
594 ? complex key
595 : complex value
596 ba?r: a?bc
597 `,
598 map[string]any{
599 "foo": map[string]any{"complex key": "complex value"},
600 "ba?r": "a?bc",
601 },
602 },
603
604 // issue https://github.com/yaml/go-yaml/issues/157
605 {
606 `foo: abc
607 bar: def`,
608 struct {
609 F string `yaml:"foo"` // the correct tag, because it has `yaml` prefix
610 B string `bar` //nolint:govet // the incorrect tag, but supported
611 }{
612 F: "abc",
613 B: "def", // value should be set using whole tag as a name, see issue: <https://github.com/yaml/go-yaml/issues/157>
614 },
615 },
616 }
617
618 type M map[string]any
619
620 type inlineB struct {
621 B int
622 inlineC `yaml:",inline"`
623 }
624
625 type inlineC struct {
626 C int
627 }
628
629 type inlineD struct {
630 C *inlineC `yaml:",inline"`
631 D int
632 }
633
634 func TestUnmarshal(t *testing.T) {
635 for i, item := range unmarshalTests {
636 t.Run(fmt.Sprintf("test %d: %q", i, item.data), func(t *testing.T) {
637 typ := reflect.ValueOf(item.value).Type()
638 value := reflect.New(typ)
639 err := yaml.Unmarshal([]byte(item.data), value.Interface())
640 if _, ok := err.(*yaml.LoadErrors); !ok {
641 assert.NoError(t, err)
642 }
643 assert.DeepEqualf(t, item.value, value.Elem().Interface(), "error: %v", err)
644 })
645 }
646 }
647
648 func TestDecodeFromYAML(t *testing.T) {
649 datatest.RunTestCases(t, func() ([]map[string]any, error) {
650 return datatest.LoadTestCasesFromFile("testdata/decode.yaml", libyaml.LoadAny)
651 }, map[string]datatest.TestHandler{
652 "decode": runDecodeTest,
653 })
654 }
655
656 func runDecodeTest(t *testing.T, tc map[string]any) {
657 t.Helper()
658
659 // Get test inputs
660 yamlData, ok := tc["yaml"].(string)
661 if !ok {
662 t.Fatal("yaml field must be string")
663 }
664
665 // Note: "type" field in YAML is renamed to "output_type" during normalization
666 // to avoid conflict with the test type ("decode")
667 typeName, ok := tc["output_type"].(string)
668 if !ok {
669 t.Fatal("output_type field must be string")
670 }
671
672 want := tc["want"]
673
674 // Create target from type registry
675 target, err := decodeTypes.NewPointerInstance(typeName)
676 if err != nil {
677 t.Fatalf("failed to create instance of type %s: %v", typeName, err)
678 }
679
680 // Unmarshal
681 err = yaml.Unmarshal([]byte(yamlData), target)
682
683 // Get the actual value (dereference pointer)
684 actual := reflect.ValueOf(target).Elem().Interface()
685
686 // Resolve constants in want
687 wantResolved := decodeValues.Resolve(want)
688
689 // Handle construct errors - if error occurred, check if want is empty/nil
690 if err != nil {
691 // For LoadErrors, values that can't be converted are skipped
692 if _, ok := err.(*yaml.LoadErrors); !ok {
693 t.Fatalf("unmarshal failed with unexpected error: %v", err)
694 }
695 // LoadErrors is expected for invalid conversions - compare with want
696 }
697
698 // Compare by marshaling both to YAML and comparing the output
699 // This handles type differences (e.g., int vs float with same value)
700 actualYAML, err := yaml.Marshal(actual)
701 if err != nil {
702 t.Fatalf("failed to marshal actual: %v", err)
703 }
704
705 wantYAML, err := yaml.Marshal(wantResolved)
706 if err != nil {
707 t.Fatalf("failed to marshal want: %v", err)
708 }
709
710 // Compare the YAML representations
711 if string(actualYAML) != string(wantYAML) {
712 t.Fatalf("YAML mismatch:\nGot:\n%s\nWant:\n%s", actualYAML, wantYAML)
713 }
714 }
715
716 func TestUnmarshalFullTimestamp(t *testing.T) {
717 // Full timestamp in same format as encoded. This is confirmed to be
718 // properly decoded by Python as a timestamp as well.
719 str := "2015-02-24T18:19:39.123456789-03:00"
720 var tm any
721 err := yaml.Unmarshal([]byte(str), &tm)
722 assert.NoError(t, err)
723 expectedTime := time.Date(2015, 2, 24, 18, 19, 39, 123456789, tm.(time.Time).Location())
724 assert.DeepEqual(t, expectedTime, tm)
725 assert.DeepEqual(t, time.Date(2015, 2, 24, 21, 19, 39, 123456789, time.UTC), tm.(time.Time).In(time.UTC))
726 }
727
728 func TestDecoderSingleDocument(t *testing.T) {
729 // Test that Decoder.Decode works as expected on
730 // all the unmarshal tests.
731 for i, item := range unmarshalTests {
732 t.Run(fmt.Sprintf("test %d: %q", i, item.data), func(t *testing.T) {
733 if item.data == "" {
734 // Behavior differs when there's no YAML.
735 return
736 }
737 typ := reflect.ValueOf(item.value).Type()
738 value := reflect.New(typ)
739 err := yaml.NewDecoder(strings.NewReader(item.data)).Decode(value.Interface())
740 if _, ok := err.(*yaml.LoadErrors); !ok {
741 assert.NoError(t, err)
742 }
743 assert.DeepEqual(t, item.value, value.Elem().Interface())
744 })
745 }
746 }
747
748 var decoderTests = []struct {
749 data string
750 values []any
751 }{{
752 "",
753 nil,
754 }, {
755 "a: b",
756 []any{
757 map[string]any{"a": "b"},
758 },
759 }, {
760 "---\na: b\n...\n",
761 []any{
762 map[string]any{"a": "b"},
763 },
764 }, {
765 "---\n'hello'\n...\n---\ngoodbye\n...\n",
766 []any{
767 "hello",
768 "goodbye",
769 },
770 }}
771
772 func TestDecoder(t *testing.T) {
773 for i, item := range decoderTests {
774 t.Run(fmt.Sprintf("test %d: %q", i, item.data), func(t *testing.T) {
775 var values []any
776 dec := yaml.NewDecoder(strings.NewReader(item.data))
777 for {
778 var value any
779 err := dec.Decode(&value)
780 if err == io.EOF {
781 break
782 }
783 assert.NoError(t, err)
784 values = append(values, value)
785 }
786 assert.DeepEqual(t, item.values, values)
787 })
788 }
789 }
790
791 func TestUnmarshalZeroDocumentStreams(t *testing.T) {
792 inputs := []string{
793 "",
794 " \n\n",
795 "# comment\n",
796 "# head\n\n# after blank\n",
797 }
798
799 for _, input := range inputs {
800 t.Run(fmt.Sprintf("%q", input), func(t *testing.T) {
801 target := struct {
802 A string `yaml:"a"`
803 }{A: "keep"}
804 err := yaml.Unmarshal([]byte(input), &target)
805 assert.NoError(t, err)
806 assert.Equal(t, "keep", target.A)
807
808 m := map[string]any{"keep": "yes"}
809 err = yaml.Unmarshal([]byte(input), &m)
810 assert.NoError(t, err)
811 assert.DeepEqual(t, map[string]any{"keep": "yes"}, m)
812
813 node := yaml.Node{
814 Kind: yaml.ScalarNode,
815 Tag: "!!str",
816 Value: "keep",
817 }
818 err = yaml.Unmarshal([]byte(input), &node)
819 assert.NoError(t, err)
820 assert.Equal(t, yaml.ScalarNode, node.Kind)
821 assert.Equal(t, "!!str", node.Tag)
822 assert.Equal(t, "keep", node.Value)
823 assert.Equal(t, "", node.HeadComment)
824 })
825 }
826 }
827
828 func TestDecoderZeroDocumentStreams(t *testing.T) {
829 inputs := []string{
830 "",
831 " \n\n",
832 "# comment\n",
833 "# head\n\n# after blank\n",
834 }
835
836 for _, input := range inputs {
837 t.Run(fmt.Sprintf("%q", input), func(t *testing.T) {
838 value := any("keep")
839 err := yaml.NewDecoder(strings.NewReader(input)).Decode(&value)
840 assert.ErrorIs(t, err, io.EOF)
841 assert.Equal(t, "keep", value)
842 })
843 }
844 }
845
846 type errReader struct{}
847
848 func (errReader) Read([]byte) (int, error) {
849 return 0, errors.New("some read error")
850 }
851
852 func TestDecoderReadError(t *testing.T) {
853 err := yaml.NewDecoder(errReader{}).Decode(&struct{}{})
854 assert.ErrorMatches(t, `go-yaml load error in reader at <unknown position>: input error: some read error`, err)
855 }
856
857 func TestUnmarshalNaN(t *testing.T) {
858 value := map[string]any{}
859 err := yaml.Unmarshal([]byte("notanum: .NaN"), &value)
860 assert.NoError(t, err)
861 assert.True(t, math.IsNaN(value["notanum"].(float64)))
862 }
863
864 func TestUnmarshalDurationInt(t *testing.T) {
865 // Don't accept plain ints as durations as it's unclear (issue #200).
866 var d time.Duration
867 err := yaml.Unmarshal([]byte("123"), &d)
868 assert.ErrorMatches(t, "yaml: construct errors: line 1: cannot construct !!int `123` into time.Duration", err)
869 }
870
871 func TestUnmarshalErrorsFromYAML(t *testing.T) {
872 datatest.RunTestCases(t, func() ([]map[string]any, error) {
873 return datatest.LoadTestCasesFromFile("testdata/unmarshal_errors.yaml", libyaml.LoadAny)
874 }, map[string]datatest.TestHandler{
875 "unmarshal-error": runUnmarshalErrorTest,
876 })
877 }
878
879 func runUnmarshalErrorTest(t *testing.T, tc map[string]any) {
880 t.Helper()
881
882 yamlInput := datatest.RequireString(t, tc, "yaml")
883 expectedError := datatest.RequireString(t, tc, "want")
884
885 var target any
886 // If a type is specified, use it; otherwise default to any
887 if typeName, ok := tc["output_type"].(string); ok {
888 var err error
889 target, err = decodeTypes.NewPointerInstance(typeName)
890 if err != nil {
891 t.Fatalf("failed to create instance of type %s: %v", typeName, err)
892 }
893 } else {
894 var value any
895 target = &value
896 }
897
898 err := yaml.Unmarshal([]byte(yamlInput), target)
899 if err == nil {
900 t.Fatalf("got nil; want error %q - Partial unmarshal: %#v", expectedError, target)
901 }
902 assert.Equalf(t, expectedError, err.Error(), "Partial unmarshal: %#v", target)
903 }
904
905 func TestDecoderErrors(t *testing.T) {
906 datatest.RunTestCases(t, func() ([]map[string]any, error) {
907 return datatest.LoadTestCasesFromFile("testdata/unmarshal_errors.yaml", libyaml.LoadAny)
908 }, map[string]datatest.TestHandler{
909 "unmarshal-error": func(t *testing.T, tc map[string]any) {
910 t.Helper()
911 yamlInput := datatest.RequireString(t, tc, "yaml")
912 expectedError := datatest.RequireString(t, tc, "want")
913
914 var target any
915 // If a type is specified, use it; otherwise default to any
916 if typeName, ok := tc["output_type"].(string); ok {
917 var err error
918 target, err = decodeTypes.NewPointerInstance(typeName)
919 if err != nil {
920 t.Fatalf("failed to create instance of type %s: %v", typeName, err)
921 }
922 } else {
923 var value any
924 target = &value
925 }
926
927 err := yaml.NewDecoder(strings.NewReader(yamlInput)).Decode(target)
928 if err == nil {
929 t.Fatalf("got nil; want error %q - Partial decode: %#v", expectedError, target)
930 }
931 assert.Equalf(t, expectedError, err.Error(), "Partial decode: %#v", target)
932 },
933 })
934 }
935
936 func TestParserErrorUnmarshal(t *testing.T) {
937 var v struct {
938 A, B int
939 }
940 data := "a: 1\n=\nb: 2"
941 err := yaml.Unmarshal([]byte(data), &v)
942 var asErr *libyaml.LoadError
943 assert.ErrorAs(t, err, &asErr)
944 expectedErr := &libyaml.LoadError{
945 Stage: libyaml.ScannerStage,
946 ContextMark: libyaml.Mark{
947 Index: 5,
948 Line: 2,
949 Column: 1,
950 },
951 ContextMsg: "while scanning a simple key",
952
953 Mark: libyaml.Mark{
954 Index: 7,
955 Line: 3,
956 Column: 1,
957 },
958 Message: "could not find expected ':'",
959 }
960 assert.DeepEqual(t, expectedErr, asErr)
961 }
962
963 func TestParserErrorDecoder(t *testing.T) {
964 var v any
965 data := "value: -"
966 err := yaml.NewDecoder(strings.NewReader(data)).Decode(&v)
967 var asErr *libyaml.LoadError
968 assert.ErrorAs(t, err, &asErr)
969 expectedErr := &libyaml.LoadError{
970 Stage: libyaml.ScannerStage,
971 Mark: libyaml.Mark{
972 Index: 7,
973 Line: 1,
974 Column: 8,
975 },
976 Message: "block sequence entries are not allowed in this context",
977 }
978 assert.DeepEqual(t, expectedErr, asErr)
979 }
980
981 var unmarshalerTests = []struct {
982 data, tag string
983 value any
984 }{
985 {"_: {hi: there}", "!!map", map[string]any{"hi": "there"}},
986 {"_: [1,A]", "!!seq", []any{1, "A"}},
987 {"_: 10", "!!int", 10},
988 {"_: null", "!!null", nil},
989 {`_: BAR!`, "!!str", "BAR!"},
990 {`_: "BAR!"`, "!!str", "BAR!"},
991 {"_: !!foo 'BAR!'", "!!foo", "BAR!"},
992 {`_: ""`, "!!str", ""},
993 }
994
995 var unmarshalerResult = map[int]error{}
996
997 type unmarshalerType struct {
998 value any
999 }
1000
1001 func (o *unmarshalerType) UnmarshalYAML(value *yaml.Node) error {
1002 if err := value.Load(&o.value); err != nil {
1003 return err
1004 }
1005 if i, ok := o.value.(int); ok {
1006 if result, ok := unmarshalerResult[i]; ok {
1007 return result
1008 }
1009 }
1010 return nil
1011 }
1012
1013 type unmarshalerPointer struct {
1014 Field *unmarshalerType `yaml:"_"`
1015 }
1016
1017 type unmarshalerInlined struct {
1018 Field *unmarshalerType `yaml:"_"`
1019 Inlined unmarshalerType `yaml:",inline"`
1020 }
1021
1022 type unmarshalerInlinedTwice struct {
1023 InlinedTwice unmarshalerInlined `yaml:",inline"`
1024 }
1025
1026 type legacyUnmarshalerType struct {
1027 value any
1028 }
1029
1030 func (o *legacyUnmarshalerType) UnmarshalYAML(unmarshal func(v any) error) error {
1031 if err := unmarshal(&o.value); err != nil {
1032 return err
1033 }
1034 if i, ok := o.value.(int); ok {
1035 if result, ok := unmarshalerResult[i]; ok {
1036 return result
1037 }
1038 }
1039 return nil
1040 }
1041
1042 type legacyUnmarshalerPointer struct {
1043 Field *legacyUnmarshalerType `yaml:"_"`
1044 }
1045
1046 type legacyUnmarshalerValue struct {
1047 Field legacyUnmarshalerType `yaml:"_"`
1048 }
1049
1050 func TestUnmarshalerPointerField(t *testing.T) {
1051 for _, item := range unmarshalerTests {
1052 obj := &unmarshalerPointer{}
1053 err := yaml.Unmarshal([]byte(item.data), obj)
1054 assert.NoError(t, err)
1055 if item.value == nil {
1056 assert.IsNil(t, obj.Field)
1057 } else {
1058 assert.NotNilf(t, obj.Field, "Pointer not initialized (%#v)", item.value)
1059 assert.DeepEqual(t, item.value, obj.Field.value)
1060 }
1061 }
1062 for _, item := range unmarshalerTests {
1063 obj := &legacyUnmarshalerPointer{}
1064 err := yaml.Unmarshal([]byte(item.data), obj)
1065 assert.NoError(t, err)
1066 if item.value == nil {
1067 assert.IsNil(t, obj.Field)
1068 } else {
1069 assert.NotNilf(t, obj.Field, "Pointer not initialized (%#v)", item.value)
1070 assert.DeepEqual(t, item.value, obj.Field.value)
1071 }
1072 }
1073 }
1074
1075 func TestUnmarshalerValueField(t *testing.T) {
1076 for _, item := range unmarshalerTests {
1077 obj := &legacyUnmarshalerValue{}
1078 err := yaml.Unmarshal([]byte(item.data), obj)
1079 assert.NoError(t, err)
1080 assert.NotNilf(t, obj.Field, "Pointer not initialized (%#v)", item.value)
1081 assert.DeepEqual(t, item.value, obj.Field.value)
1082 }
1083 }
1084
1085 func TestUnmarshalerInlinedField(t *testing.T) {
1086 obj := &unmarshalerInlined{}
1087 err := yaml.Unmarshal([]byte("_: a\ninlined: b\n"), obj)
1088 assert.NoError(t, err)
1089 assert.DeepEqual(t, &unmarshalerType{"a"}, obj.Field)
1090 assert.DeepEqual(t, unmarshalerType{map[string]any{"_": "a", "inlined": "b"}}, obj.Inlined)
1091
1092 twc := &unmarshalerInlinedTwice{}
1093 err = yaml.Unmarshal([]byte("_: a\ninlined: b\n"), twc)
1094 assert.NoError(t, err)
1095 assert.DeepEqual(t, &unmarshalerType{"a"}, twc.InlinedTwice.Field)
1096 assert.DeepEqual(t, unmarshalerType{map[string]any{"_": "a", "inlined": "b"}}, twc.InlinedTwice.Inlined)
1097 }
1098
1099 func TestUnmarshalerWholeDocument(t *testing.T) {
1100 obj := &legacyUnmarshalerType{}
1101 err := yaml.Unmarshal([]byte(unmarshalerTests[0].data), obj)
1102 assert.NoError(t, err)
1103 value, ok := obj.value.(map[string]any)
1104 assert.Truef(t, ok, "value: %#v", obj.value)
1105 assert.DeepEqual(t, unmarshalerTests[0].value, value["_"])
1106 }
1107
1108 func TestUnmarshalerWholeDocumentModern(t *testing.T) {
1109 obj := &unmarshalerType{}
1110 err := yaml.Unmarshal([]byte(unmarshalerTests[0].data), obj)
1111 assert.NoError(t, err)
1112 value, ok := obj.value.(map[string]any)
1113 assert.Truef(t, ok, "value: %#v", obj.value)
1114 assert.DeepEqual(t, unmarshalerTests[0].value, value["_"])
1115 }
1116
1117 func TestUnmarshalerWholeDocumentNull(t *testing.T) {
1118 obj := &unmarshalerType{}
1119 err := yaml.Unmarshal([]byte("null"), obj)
1120 assert.NoError(t, err)
1121 assert.DeepEqual(t, unmarshalerType{}, *obj)
1122 }
1123
1124 func TestUnmarshalerLoadErrors(t *testing.T) {
1125 unmarshalerResult[2] = &yaml.LoadErrors{Errors: []*yaml.LoadError{{Stage: yaml.ConstructorStage, Message: "foo", Mark: yaml.Mark{Line: 1, Column: 1}}}}
1126 unmarshalerResult[4] = &yaml.LoadErrors{Errors: []*yaml.LoadError{{Stage: yaml.ConstructorStage, Message: "bar", Mark: yaml.Mark{Line: 1, Column: 1}}}}
1127 defer func() {
1128 delete(unmarshalerResult, 2)
1129 delete(unmarshalerResult, 4)
1130 }()
1131
1132 type T struct {
1133 Before int
1134 After int
1135 M map[string]*unmarshalerType
1136 }
1137 var v T
1138 data := `{before: A, m: {abc: 1, def: 2, ghi: 3, jkl: 4}, after: B}`
1139 err := yaml.Unmarshal([]byte(data), &v)
1140 expectedError := "" +
1141 "yaml: construct errors: " +
1142 "line 1: cannot construct !!str `A` into int; " +
1143 "line 1: foo; " +
1144 "line 1: bar; " +
1145 "line 1: cannot construct !!str `B` into int"
1146 assert.ErrorMatches(t, expectedError, err)
1147 assert.NotNil(t, v.M["abc"])
1148 assert.IsNil(t, v.M["def"])
1149 assert.NotNil(t, v.M["ghi"])
1150 assert.IsNil(t, v.M["jkl"])
1151
1152 assert.Equal(t, 1, v.M["abc"].value)
1153 assert.Equal(t, 3, v.M["ghi"].value)
1154 }
1155
1156 func TestLegacyUnmarshalerLoadErrors(t *testing.T) {
1157 unmarshalerResult[2] = &yaml.LoadErrors{Errors: []*yaml.LoadError{{Stage: yaml.ConstructorStage, Message: "foo", Mark: yaml.Mark{Line: 1, Column: 1}}}}
1158 unmarshalerResult[4] = &yaml.LoadErrors{Errors: []*yaml.LoadError{{Stage: yaml.ConstructorStage, Message: "bar", Mark: yaml.Mark{Line: 1, Column: 1}}}}
1159 defer func() {
1160 delete(unmarshalerResult, 2)
1161 delete(unmarshalerResult, 4)
1162 }()
1163
1164 type T struct {
1165 Before int
1166 After int
1167 M map[string]*legacyUnmarshalerType
1168 }
1169 var v T
1170 data := `{before: A, m: {abc: 1, def: 2, ghi: 3, jkl: 4}, after: B}`
1171 err := yaml.Unmarshal([]byte(data), &v)
1172 expectedError := "" +
1173 "yaml: construct errors: " +
1174 "line 1: cannot construct !!str `A` into int; " +
1175 "line 1: foo; " +
1176 "line 1: bar; " +
1177 "line 1: cannot construct !!str `B` into int"
1178 assert.ErrorMatches(t, expectedError, err)
1179
1180 assert.NotNil(t, v.M["abc"])
1181 assert.IsNil(t, v.M["def"])
1182 assert.NotNil(t, v.M["ghi"])
1183 assert.IsNil(t, v.M["jkl"])
1184
1185 assert.Equal(t, 1, v.M["abc"].value)
1186 assert.Equal(t, 3, v.M["ghi"].value)
1187 }
1188
1189 func TestLoadErrors_Unwrapping(t *testing.T) {
1190 errSentinel := errors.New("foo")
1191 errSentinel2 := errors.New("bar")
1192
1193 errUnmarshal := yaml.NewLoadError(yaml.ConstructorStage, "foo", yaml.Mark{Line: 1, Column: 2}, errSentinel)
1194 errUnmarshal2 := yaml.NewLoadError(yaml.ConstructorStage, "bar", yaml.Mark{Line: 2, Column: 2}, errSentinel2)
1195
1196 // Simulate a LoadErrors
1197 err := &yaml.LoadErrors{
1198 Errors: []*yaml.LoadError{
1199 errUnmarshal,
1200 errUnmarshal2,
1201 },
1202 }
1203
1204 var errTarget *yaml.LoadError
1205 // check we can unwrap an error
1206 assert.ErrorAs(t, err, &errTarget)
1207
1208 // check we got the first error
1209 assert.ErrorIs(t, errTarget, errUnmarshal)
1210
1211 // check we can unwrap any sentinel error wrapped in any UnmarshalError
1212 assert.ErrorIs(t, err, errSentinel)
1213 assert.ErrorIs(t, err, errSentinel2)
1214
1215 var errTargetLegacy *yaml.TypeError
1216 // check we can unwrap to legacy TypeError
1217 assert.ErrorAs(t, err, &errTargetLegacy)
1218 }
1219
1220 func TestLoadErrors_Unwrapping_Failures(t *testing.T) {
1221 errSentinel := errors.New("foo")
1222
1223 errUnmarshal := yaml.NewLoadError(yaml.ConstructorStage, "foo", yaml.Mark{Line: 1, Column: 2}, errSentinel)
1224 errUnmarshal2 := yaml.NewLoadError(yaml.ConstructorStage, "bar", yaml.Mark{Line: 2, Column: 2}, errors.New("bar"))
1225
1226 // Simulate a LoadErrors
1227 err := &yaml.LoadErrors{
1228 Errors: []*yaml.LoadError{
1229 errUnmarshal,
1230 errUnmarshal2,
1231 },
1232 }
1233
1234 var errTarget *yaml.LoadError
1235 // check we can unwrap an error
1236 assert.ErrorAs(t, err, &errTarget)
1237
1238 // check we got the first error
1239 assert.ErrorIs(t, errTarget, errUnmarshal)
1240
1241 // check we can still unwrap the error wrapped in UnmarshalError
1242 assert.ErrorIs(t, errTarget, errSentinel)
1243 }
1244
1245 type proxyTypeError struct{}
1246
1247 func (v *proxyTypeError) UnmarshalYAML(node *yaml.Node) error {
1248 var s string
1249 var a int32
1250 var b int64
1251 if err := node.Load(&s); err != nil {
1252 panic(err)
1253 }
1254 if s == "a" {
1255 if err := node.Load(&b); err == nil {
1256 panic("should have failed")
1257 }
1258 return node.Load(&a)
1259 }
1260 if err := node.Load(&a); err == nil {
1261 panic("should have failed")
1262 }
1263 return node.Load(&b)
1264 }
1265
1266 func TestUnmarshalerLoadErrorsProxying(t *testing.T) {
1267 type T struct {
1268 Before int
1269 After int
1270 M map[string]*proxyTypeError
1271 }
1272 var v T
1273 data := `{before: A, m: {abc: a, def: b}, after: B}`
1274 err := yaml.Unmarshal([]byte(data), &v)
1275 expectedError := "" +
1276 "yaml: construct errors: " +
1277 "line 1: cannot construct !!str `A` into int; " +
1278 "line 1: cannot construct !!str `a` into int32; " +
1279 "line 1: cannot construct !!str `b` into int64; " +
1280 "line 1: cannot construct !!str `B` into int"
1281 assert.ErrorMatches(t, expectedError, err)
1282 }
1283
1284 type legacyProxyTypeError struct{}
1285
1286 func (v *legacyProxyTypeError) UnmarshalYAML(unmarshal func(any) error) error {
1287 var s string
1288 var a int32
1289 var b int64
1290 if err := unmarshal(&s); err != nil {
1291 panic(err)
1292 }
1293 if s == "a" {
1294 if err := unmarshal(&b); err == nil {
1295 panic("should have failed")
1296 }
1297 return unmarshal(&a)
1298 }
1299 if err := unmarshal(&a); err == nil {
1300 panic("should have failed")
1301 }
1302 return unmarshal(&b)
1303 }
1304
1305 func TestLegacyUnmarshalerLoadErrorsProxying(t *testing.T) {
1306 type T struct {
1307 Before int
1308 After int
1309 M map[string]*legacyProxyTypeError
1310 }
1311 var v T
1312 data := `{before: A, m: {abc: a, def: b}, after: B}`
1313 err := yaml.Unmarshal([]byte(data), &v)
1314 expectedError := "" +
1315 "yaml: construct errors: " +
1316 "line 1: cannot construct !!str `A` into int; " +
1317 "line 1: cannot construct !!str `a` into int32; " +
1318 "line 1: cannot construct !!str `b` into int64; " +
1319 "line 1: cannot construct !!str `B` into int"
1320 assert.ErrorMatches(t, expectedError, err)
1321 }
1322
1323 var errFailing = errors.New("failingErr")
1324
1325 type failingUnmarshaler struct{}
1326
1327 func (ft *failingUnmarshaler) UnmarshalYAML(node *yaml.Node) error {
1328 return errFailing
1329 }
1330
1331 func TestUnmarshalerError(t *testing.T) {
1332 data := `{foo: 123, bar: {}, spam: "test"}`
1333 dst := struct {
1334 Foo int
1335 Bar *failingUnmarshaler
1336 Spam string
1337 }{}
1338 err := yaml.Unmarshal([]byte(data), &dst)
1339 expectedErr := &yaml.LoadErrors{
1340 Errors: []*yaml.LoadError{
1341 yaml.NewLoadError(yaml.ConstructorStage, errFailing.Error(), yaml.Mark{Line: 1, Column: 17}, errFailing),
1342 },
1343 }
1344 assert.DeepEqual(t, expectedErr, err)
1345 // whatever could be unmarshaled must be unmarshaled
1346 assert.Equal(t, 123, dst.Foo)
1347 assert.DeepEqual(t, &failingUnmarshaler{}, dst.Bar)
1348 assert.Equal(t, "test", dst.Spam)
1349 }
1350
1351 type legacyFailingUnmarshaler struct{}
1352
1353 func (ft *legacyFailingUnmarshaler) UnmarshalYAML(unmarshal func(any) error) error {
1354 return errFailing
1355 }
1356
1357 func TestLegacyUnmarshalerError(t *testing.T) {
1358 data := `{foo: 123, bar: {}, spam: "test"}`
1359 dst := struct {
1360 Foo int
1361 Bar *legacyFailingUnmarshaler
1362 Spam string
1363 }{}
1364 err := yaml.Unmarshal([]byte(data), &dst)
1365 expectedErr := &yaml.LoadErrors{
1366 Errors: []*yaml.LoadError{
1367 yaml.NewLoadError(yaml.ConstructorStage, errFailing.Error(), yaml.Mark{Line: 1, Column: 17}, errFailing),
1368 },
1369 }
1370 assert.DeepEqual(t, expectedErr, err)
1371 // whatever could be unmarshaled must be unmarshaled
1372 assert.Equal(t, 123, dst.Foo)
1373 assert.DeepEqual(t, &legacyFailingUnmarshaler{}, dst.Bar)
1374 assert.Equal(t, "test", dst.Spam)
1375 }
1376
1377 type failingTextUnmarshaler struct{}
1378
1379 var _ encoding.TextUnmarshaler = &failingTextUnmarshaler{}
1380
1381 func (ft *failingTextUnmarshaler) UnmarshalText(b []byte) error {
1382 return errFailing
1383 }
1384
1385 func TestTextUnmarshalerError(t *testing.T) {
1386 data := `{foo: 123, bar: "456", spam: "test"}`
1387 dst := struct {
1388 Foo int
1389 Bar *failingTextUnmarshaler
1390 Spam string
1391 }{}
1392 err := yaml.Unmarshal([]byte(data), &dst)
1393 expectedErr := &yaml.LoadErrors{
1394 Errors: []*yaml.LoadError{
1395 yaml.NewLoadError(yaml.ConstructorStage, errFailing.Error(), yaml.Mark{Line: 1, Column: 17}, errFailing),
1396 },
1397 }
1398 assert.DeepEqual(t, expectedErr, err)
1399 // whatever could be unmarshaled must be unmarshaled
1400 assert.Equal(t, 123, dst.Foo)
1401 assert.DeepEqual(t, &failingTextUnmarshaler{}, dst.Bar)
1402 assert.Equal(t, "test", dst.Spam)
1403 }
1404
1405 func TestUnmarshalError_Unwrapping(t *testing.T) {
1406 errSentinel := errors.New("foo")
1407 errUnmarshal := yaml.NewLoadError(yaml.ConstructorStage, "foo", yaml.Mark{Line: 1, Column: 2}, errSentinel)
1408 assert.ErrorIs(t, errUnmarshal, errSentinel)
1409 }
1410
1411 func TestTextUnmarshalerNonScalar(t *testing.T) {
1412 dst := struct {
1413 A textUnmarshaler
1414 }{}
1415 inputs := []string{
1416 `a: {}`,
1417 `a: []`,
1418 }
1419
1420 for _, input := range inputs {
1421 err := yaml.Unmarshal([]byte(input), &dst)
1422 t.Logf("%s -> err=%v", input, err)
1423 var target *yaml.LoadErrors
1424 if !errors.As(err, &target) {
1425 t.Errorf("expected yaml.TypeError, got %v", err)
1426 }
1427 }
1428 }
1429
1430 type sliceUnmarshaler []int
1431
1432 func (su *sliceUnmarshaler) UnmarshalYAML(node *yaml.Node) error {
1433 var slice []int
1434 err := node.Load(&slice)
1435 if err == nil {
1436 *su = slice
1437 return nil
1438 }
1439
1440 var intVal int
1441 err = node.Load(&intVal)
1442 if err == nil {
1443 *su = []int{intVal}
1444 return nil
1445 }
1446
1447 return err
1448 }
1449
1450 func TestUnmarshalerRetry(t *testing.T) {
1451 var su sliceUnmarshaler
1452 err := yaml.Unmarshal([]byte("[1, 2, 3]"), &su)
1453 assert.NoError(t, err)
1454 assert.DeepEqual(t, sliceUnmarshaler([]int{1, 2, 3}), su)
1455
1456 err = yaml.Unmarshal([]byte("1"), &su)
1457 assert.NoError(t, err)
1458 assert.DeepEqual(t, sliceUnmarshaler([]int{1}), su)
1459 }
1460
1461 type legacySliceUnmarshaler []int
1462
1463 func (su *legacySliceUnmarshaler) UnmarshalYAML(unmarshal func(any) error) error {
1464 var slice []int
1465 err := unmarshal(&slice)
1466 if err == nil {
1467 *su = slice
1468 return nil
1469 }
1470
1471 var intVal int
1472 err = unmarshal(&intVal)
1473 if err == nil {
1474 *su = []int{intVal}
1475 return nil
1476 }
1477
1478 return err
1479 }
1480
1481 func TestLegacyUnmarshalerRetry(t *testing.T) {
1482 var su legacySliceUnmarshaler
1483 err := yaml.Unmarshal([]byte("[1, 2, 3]"), &su)
1484 assert.NoError(t, err)
1485 assert.DeepEqual(t, legacySliceUnmarshaler([]int{1, 2, 3}), su)
1486
1487 err = yaml.Unmarshal([]byte("1"), &su)
1488 assert.NoError(t, err)
1489 assert.DeepEqual(t, legacySliceUnmarshaler([]int{1}), su)
1490 }
1491
1492 // nodeKindRecorder records the Kind of the node passed to UnmarshalYAML
1493 type nodeKindRecorder struct {
1494 Kind libyaml.Kind
1495 Data any
1496 }
1497
1498 func (n *nodeKindRecorder) UnmarshalYAML(node *yaml.Node) error {
1499 n.Kind = node.Kind
1500 return node.Decode(&n.Data)
1501 }
1502
1503 // TestUnmarshalerNodeKind verifies that custom unmarshalers receive the
1504 // correct node kind (SequenceNode, ScalarNode, MappingNode) rather than
1505 // DocumentNode. This is a regression test for issue #274.
1506 func TestUnmarshalerNodeKind(t *testing.T) {
1507 tests := []struct {
1508 name string
1509 input string
1510 wantKind libyaml.Kind
1511 wantData any
1512 }{
1513 {
1514 name: "sequence",
1515 input: "[1, 2, 3]",
1516 wantKind: libyaml.SequenceNode,
1517 wantData: []any{1, 2, 3},
1518 },
1519 {
1520 name: "mapping",
1521 input: "foo: bar",
1522 wantKind: libyaml.MappingNode,
1523 wantData: map[string]any{"foo": "bar"},
1524 },
1525 {
1526 name: "scalar",
1527 input: "hello",
1528 wantKind: libyaml.ScalarNode,
1529 wantData: "hello",
1530 },
1531 }
1532
1533 for _, tt := range tests {
1534 t.Run(tt.name, func(t *testing.T) {
1535 var recorder nodeKindRecorder
1536 err := yaml.Unmarshal([]byte(tt.input), &recorder)
1537 assert.NoError(t, err)
1538 assert.Equal(t, tt.wantKind, recorder.Kind)
1539 assert.DeepEqual(t, tt.wantData, recorder.Data)
1540 })
1541 }
1542 }
1543
1544 // From http://yaml.org/type/merge.html
1545 var mergeTests = `
1546 anchors:
1547 list:
1548 - &CENTER { "x": 1, "y": 2 }
1549 - &LEFT { "x": 0, "y": 2 }
1550 - &BIG { "r": 10 }
1551 - &SMALL { "r": 1 }
1552
1553 # All the following maps are equal:
1554
1555 plain:
1556 # Explicit keys
1557 "x": 1
1558 "y": 2
1559 "r": 10
1560 label: center/big
1561
1562 mergeOne:
1563 # Merge one map
1564 << : *CENTER
1565 "r": 10
1566 label: center/big
1567
1568 mergeMultiple:
1569 # Merge multiple maps
1570 << : [ *CENTER, *BIG ]
1571 label: center/big
1572
1573 override:
1574 # Override
1575 << : [ *BIG, *LEFT, *SMALL ]
1576 "x": 1
1577 label: center/big
1578
1579 shortTag:
1580 # Explicit short merge tag
1581 !!merge "<<" : [ *CENTER, *BIG ]
1582 label: center/big
1583
1584 longTag:
1585 # Explicit merge long tag
1586 !<tag:yaml.org,2002:merge> "<<" : [ *CENTER, *BIG ]
1587 label: center/big
1588
1589 inlineMap:
1590 # Inlined map
1591 << : {"x": 1, "y": 2, "r": 10}
1592 label: center/big
1593
1594 inlineSequenceMap:
1595 # Inlined map in sequence
1596 << : [ *CENTER, {"r": 10} ]
1597 label: center/big
1598 `
1599
1600 func TestMerge(t *testing.T) {
1601 want := map[string]any{
1602 "x": 1,
1603 "y": 2,
1604 "r": 10,
1605 "label": "center/big",
1606 }
1607
1608 wantStringMap := make(map[string]any)
1609 for k, v := range want {
1610 wantStringMap[fmt.Sprintf("%v", k)] = v
1611 }
1612
1613 var m map[any]any
1614 err := yaml.Unmarshal([]byte(mergeTests), &m)
1615 assert.NoError(t, err)
1616 for name, test := range m {
1617 if name == "anchors" {
1618 continue
1619 }
1620 if name == "plain" {
1621 assert.DeepEqualf(t, wantStringMap, test, "test %q failed", name)
1622 continue
1623 }
1624 assert.DeepEqualf(t, want, test, "test %q failed", name)
1625 }
1626 }
1627
1628 func TestMergeStruct(t *testing.T) {
1629 type Data struct {
1630 X, Y, R int
1631 Label string
1632 }
1633 want := Data{1, 2, 10, "center/big"}
1634
1635 var m map[string]Data
1636 err := yaml.Unmarshal([]byte(mergeTests), &m)
1637 assert.NoError(t, err)
1638 for name, test := range m {
1639 if name == "anchors" {
1640 continue
1641 }
1642 assert.DeepEqualf(t, want, test, "test %q failed", name)
1643 }
1644 }
1645
1646 var mergeTestsNested = `
1647 mergeouter1: &mergeouter1
1648 d: 40
1649 e: 50
1650
1651 mergeouter2: &mergeouter2
1652 e: 5
1653 f: 6
1654 g: 70
1655
1656 mergeinner1: &mergeinner1
1657 <<: *mergeouter1
1658 inner:
1659 a: 1
1660 b: 2
1661
1662 mergeinner2: &mergeinner2
1663 <<: *mergeouter2
1664 inner:
1665 a: -1
1666 b: -2
1667
1668 outer:
1669 <<: [*mergeinner1, *mergeinner2]
1670 f: 60
1671 inner:
1672 a: 10
1673 `
1674
1675 func TestMergeNestedStruct(t *testing.T) {
1676 // Issue #818: Merging used to just unmarshal twice on the target
1677 // value, which worked for maps as these were replaced by the new map,
1678 // but not on struct values as these are preserved. This resulted in
1679 // the nested data from the merged map to be mixed up with the data
1680 // from the map being merged into.
1681 //
1682 // This test also prevents two potential bugs from showing up:
1683 //
1684 // 1) A simple implementation might just zero out the nested value
1685 // before unmarshaling the second time, but this would clobber previous
1686 // data that is usually respected ({C: 30} below).
1687 //
1688 // 2) A simple implementation might attempt to handle the key skipping
1689 // directly by iterating over the merging map without recursion, but
1690 // there are more complex cases that require recursion.
1691 //
1692 // Quick summary of the fields:
1693 //
1694 // - A must come from outer and not overridden
1695 // - B must not be set as its in the ignored merge
1696 // - C should still be set as it's preset in the value
1697 // - D should be set from the recursive merge
1698 // - E should be set from the first recursive merge, ignored on the second
1699 // - F should be set in the inlined map from outer, ignored later
1700 // - G should be set in the inlined map from the second recursive merge
1701 //
1702
1703 type Inner struct {
1704 A, B, C int
1705 }
1706 type Outer struct {
1707 D, E int
1708 Inner Inner
1709 Inline map[string]int `yaml:",inline"`
1710 }
1711 type Data struct {
1712 Outer Outer
1713 }
1714
1715 test := Data{Outer{0, 0, Inner{C: 30}, nil}}
1716 want := Data{Outer{40, 50, Inner{A: 10, C: 30}, map[string]int{"f": 60, "g": 70}}}
1717
1718 err := yaml.Unmarshal([]byte(mergeTestsNested), &test)
1719 assert.NoError(t, err)
1720 assert.DeepEqual(t, want, test)
1721
1722 // Repeat test with a map.
1723
1724 var testm map[string]any
1725 wantm := map[string]any{
1726 "f": 60,
1727 "inner": map[string]any{
1728 "a": 10,
1729 },
1730 "d": 40,
1731 "e": 50,
1732 "g": 70,
1733 }
1734 err = yaml.Unmarshal([]byte(mergeTestsNested), &testm)
1735 assert.NoError(t, err)
1736 assert.DeepEqual(t, wantm, testm["outer"])
1737 }
1738
1739 var unmarshalNullTests = []struct {
1740 input string
1741 pristine, expected func() any
1742 }{{
1743 "null",
1744 func() any { var v any = "v"; return &v },
1745 func() any { var v any = nil; return &v },
1746 }, {
1747 "null",
1748 func() any { s := "s"; return &s },
1749 func() any { s := "s"; return &s },
1750 }, {
1751 "null",
1752 func() any { s := "s"; sptr := &s; return &sptr },
1753 func() any { var sptr *string; return &sptr },
1754 }, {
1755 "null",
1756 func() any { i := 1; return &i },
1757 func() any { i := 1; return &i },
1758 }, {
1759 "null",
1760 func() any { i := 1; iptr := &i; return &iptr },
1761 func() any { var iptr *int; return &iptr },
1762 }, {
1763 "null",
1764 func() any { m := map[string]int{"s": 1}; return &m },
1765 func() any { var m map[string]int; return &m },
1766 }, {
1767 "null",
1768 func() any { m := map[string]int{"s": 1}; return m },
1769 func() any { m := map[string]int{"s": 1}; return m },
1770 }, {
1771 "s2: null\ns3: null",
1772 func() any { m := map[string]int{"s1": 1, "s2": 2}; return m },
1773 func() any { m := map[string]int{"s1": 1, "s2": 2, "s3": 0}; return m },
1774 }, {
1775 "s2: null\ns3: null",
1776 func() any { m := map[string]any{"s1": 1, "s2": 2}; return m },
1777 func() any { m := map[string]any{"s1": 1, "s2": nil, "s3": nil}; return m },
1778 }}
1779
1780 func TestUnmarshalNull(t *testing.T) {
1781 for _, test := range unmarshalNullTests {
1782 pristine := test.pristine()
1783 expected := test.expected()
1784 err := yaml.Unmarshal([]byte(test.input), pristine)
1785 assert.NoError(t, err)
1786 assert.DeepEqual(t, expected, pristine)
1787 }
1788 }
1789
1790 func TestUnmarshalPreservesData(t *testing.T) {
1791 var v struct {
1792 A, B int
1793 C int `yaml:"-"`
1794 }
1795 v.A = 42
1796 v.C = 88
1797 err := yaml.Unmarshal([]byte("---"), &v)
1798 assert.NoError(t, err)
1799 assert.Equal(t, 42, v.A)
1800 assert.Equal(t, 0, v.B)
1801 assert.Equal(t, 88, v.C)
1802
1803 err = yaml.Unmarshal([]byte("b: 21\nc: 99"), &v)
1804 assert.NoError(t, err)
1805 assert.Equal(t, 42, v.A)
1806 assert.Equal(t, 21, v.B)
1807 assert.Equal(t, 88, v.C)
1808 }
1809
1810 func TestUnmarshalSliceOnPreset(t *testing.T) {
1811 // Issue #48.
1812 v := struct{ A []int }{[]int{1}}
1813 err := yaml.Unmarshal([]byte("a: [2]"), &v)
1814 assert.NoError(t, err)
1815 assert.DeepEqual(t, []int{2}, v.A)
1816 }
1817
1818 var unmarshalStrictTests = []struct {
1819 known bool
1820 unique bool
1821 data string
1822 value any
1823 error string
1824 }{{
1825 known: true,
1826 data: "a: 1\nc: 2\n",
1827 value: struct{ A, B int }{A: 1},
1828 error: `yaml: construct errors: line 2: field c not found in type struct { A int; B int }`,
1829 }, {
1830 unique: true,
1831 data: "a: 1\nb: 2\na: 3\n",
1832 value: struct{ A, B int }{A: 3, B: 2},
1833 error: `yaml: construct errors: line 3: mapping key "a" already defined at line 1`,
1834 }, {
1835 unique: true,
1836 data: "c: 3\na: 1\nb: 2\nc: 4\n",
1837 value: struct {
1838 A int
1839 inlineB `yaml:",inline"`
1840 }{
1841 A: 1,
1842 inlineB: inlineB{
1843 B: 2,
1844 inlineC: inlineC{
1845 C: 4,
1846 },
1847 },
1848 },
1849 error: `yaml: construct errors: line 4: mapping key "c" already defined at line 1`,
1850 }, {
1851 unique: true,
1852 data: "c: 0\na: 1\nb: 2\nc: 1\n",
1853 value: struct {
1854 A int
1855 inlineB `yaml:",inline"`
1856 }{
1857 A: 1,
1858 inlineB: inlineB{
1859 B: 2,
1860 inlineC: inlineC{
1861 C: 1,
1862 },
1863 },
1864 },
1865 error: `yaml: construct errors: line 4: mapping key "c" already defined at line 1`,
1866 }, {
1867 unique: true,
1868 data: "c: 1\na: 1\nb: 2\nc: 3\n",
1869 value: struct {
1870 A int
1871 M map[string]any `yaml:",inline"`
1872 }{
1873 A: 1,
1874 M: map[string]any{
1875 "b": 2,
1876 "c": 3,
1877 },
1878 },
1879 error: `yaml: construct errors: line 4: mapping key "c" already defined at line 1`,
1880 }, {
1881 unique: true,
1882 data: "a: 1\n9: 2\nnull: 3\n9: 4",
1883 value: map[any]any{
1884 "a": 1,
1885 nil: 3,
1886 9: 4,
1887 },
1888 error: `yaml: construct errors: line 4: mapping key "9" already defined at line 2`,
1889 }}
1890
1891 func TestUnmarshalKnownFields(t *testing.T) {
1892 for i, item := range unmarshalStrictTests {
1893 t.Logf("test %d: %q", i, item.data)
1894 // First test that normal Unmarshal unmarshals to the expected value.
1895 if !item.unique {
1896 typ := reflect.ValueOf(item.value).Type()
1897 value := reflect.New(typ)
1898 err := yaml.Unmarshal([]byte(item.data), value.Interface())
1899 assert.NoError(t, err)
1900 assert.DeepEqual(t, item.value, value.Elem().Interface())
1901 }
1902
1903 // Then test that it fails on the same thing with KnownFields on.
1904 typ := reflect.ValueOf(item.value).Type()
1905 value := reflect.New(typ)
1906 dec := yaml.NewDecoder(bytes.NewBufferString(item.data))
1907 dec.KnownFields(item.known)
1908 err := dec.Decode(value.Interface())
1909 assert.ErrorMatches(t, item.error, err)
1910 }
1911 }
1912
1913 type textUnmarshaler struct {
1914 S string
1915 }
1916
1917 func (t *textUnmarshaler) UnmarshalText(s []byte) error {
1918 t.S = string(s)
1919 return nil
1920 }
1921
1922 func TestFuzzCrashersFromYAML(t *testing.T) {
1923 datatest.RunTestCases(t, func() ([]map[string]any, error) {
1924 return datatest.LoadTestCasesFromFile("testdata/fuzz_crashers.yaml", libyaml.LoadAny)
1925 }, map[string]datatest.TestHandler{
1926 "fuzz-crasher": runFuzzCrasherTest,
1927 })
1928 }
1929
1930 func runFuzzCrasherTest(t *testing.T, tc map[string]any) {
1931 t.Helper()
1932
1933 yamlInput := datatest.RequireString(t, tc, "yaml")
1934
1935 // Just unmarshal and ensure it doesn't crash
1936 var v any
1937 _ = yaml.Unmarshal([]byte(yamlInput), &v)
1938 }
1939
1940 func TestIssue117(t *testing.T) {
1941 data := []byte(`
1942 a:
1943 <<:
1944 -
1945 ?
1946 -
1947 `)
1948
1949 x := map[string]any{}
1950 err := yaml.Unmarshal(data, &x)
1951 if err == nil {
1952 t.Errorf("expected error, got none")
1953 }
1954 }
1955
1956 func TestParserErrorUnknownAnchorPosition(t *testing.T) {
1957 tests := []struct {
1958 data string
1959 line int
1960 column int
1961 }{
1962 {"*x", 1, 1},
1963 {"a: *x", 1, 4},
1964 {"a:\n b: *x", 2, 6},
1965 }
1966
1967 for _, test := range tests {
1968 var n yaml.Node
1969 err := yaml.Unmarshal([]byte(test.data), &n)
1970 asErr := new(libyaml.LoadError)
1971 assert.ErrorAs(t, err, &asErr)
1972 expected := &libyaml.LoadError{
1973 Stage: libyaml.ComposerStage,
1974 Message: "unknown anchor 'x' referenced",
1975 Mark: libyaml.Mark{
1976 Line: test.line,
1977 Column: test.column,
1978 },
1979 }
1980 assert.DeepEqual(t, expected, asErr)
1981 }
1982 }
1983
1984 var marshalIntTest = 123
1985
1986 var (
1987 encodeTypeRegistry = datatest.NewTypeRegistry()
1988 encodeValueRegistry = datatest.NewValueRegistry()
1989 )
1990
1991 func init() {
1992 // Register basic types
1993 encodeTypeRegistry.Register("string", "")
1994
1995 // Register map types
1996 encodeTypeRegistry.Register("map[string]string", map[string]string{})
1997 encodeTypeRegistry.Register("map[string]any", map[string]any{})
1998 encodeTypeRegistry.Register("map[string]uint", map[string]uint{})
1999 encodeTypeRegistry.Register("map[string]int64", map[string]int64{})
2000 encodeTypeRegistry.Register("map[string]uint64", map[string]uint64{})
2001 encodeTypeRegistry.Register("map[string][]string", map[string][]string{})
2002 encodeTypeRegistry.Register("map[string][]any", map[string][]any{})
2003 encodeTypeRegistry.Register("map[string][]map[string]any", map[string][]map[string]any{})
2004
2005 // Register struct types
2006 encodeTypeRegistry.Register("testStructHello", testStructHello{})
2007 encodeTypeRegistry.Register("testStructA_Int", testStructA_Int{})
2008 encodeTypeRegistry.Register("testStructA_Float64", testStructA_Float64{})
2009 encodeTypeRegistry.Register("testStructA_Bool", testStructA_Bool{})
2010 encodeTypeRegistry.Register("testStructA_String", testStructA_String{})
2011 encodeTypeRegistry.Register("testStructA_IntSlice", testStructA_IntSlice{})
2012 encodeTypeRegistry.Register("testStructA_IntArray2", testStructA_IntArray2{})
2013 encodeTypeRegistry.Register("testStructA_NestedB", testStructA_NestedB{})
2014 encodeTypeRegistry.Register("testStructA_NestedBPtr", testStructA_NestedBPtr{})
2015 encodeTypeRegistry.Register("testStructEmpty", testStructEmpty{})
2016
2017 // Register struct types with yaml tags
2018 encodeTypeRegistry.Register("testStructB_Int_TagA", testStructB_Int_TagA{})
2019
2020 // Register value constants
2021 encodeValueRegistry.Register("+Inf", math.Inf(+1))
2022 encodeValueRegistry.Register("-Inf", math.Inf(-1))
2023 encodeValueRegistry.Register("NaN", math.NaN())
2024 encodeValueRegistry.Register("-0", negativeZero)
2025 }
2026
2027 var marshalTests = []struct {
2028 value any
2029 data string
2030 }{
2031 {
2032 (*marshalerType)(nil),
2033 "null\n",
2034 },
2035
2036 // Simple values.
2037 {
2038 &marshalIntTest,
2039 "123\n",
2040 },
2041 {
2042 negativeZero,
2043 "-0\n",
2044 },
2045 {
2046 "\t\n",
2047 "\"\\t\\n\"\n",
2048 },
2049
2050 // Conditional flag
2051 {
2052 &struct {
2053 A int `yaml:"a,omitempty"`
2054 B int `yaml:"b,omitempty"`
2055 }{1, 0},
2056 "a: 1\n",
2057 },
2058 {
2059 &struct {
2060 A int `yaml:"a,omitempty"`
2061 B int `yaml:"b,omitempty"`
2062 }{0, 0},
2063 "{}\n",
2064 },
2065 {
2066 &struct {
2067 A *struct{ X, y int } `yaml:"a,omitempty,flow"`
2068 }{&struct{ X, y int }{1, 2}},
2069 "a: {x: 1}\n",
2070 },
2071 {
2072 &struct {
2073 A *struct{ X, y int } `yaml:"a,omitempty,flow"`
2074 }{nil},
2075 "{}\n",
2076 },
2077 {
2078 &struct {
2079 A *struct{ X, y int } `yaml:"a,omitempty,flow"`
2080 }{&struct{ X, y int }{}},
2081 "a: {x: 0}\n",
2082 },
2083 {
2084 &struct {
2085 A struct{ X, y int } `yaml:"a,omitempty,flow"`
2086 }{struct{ X, y int }{1, 2}},
2087 "a: {x: 1}\n",
2088 },
2089 {
2090 &struct {
2091 A struct{ X, y int } `yaml:"a,omitempty,flow"`
2092 }{struct{ X, y int }{0, 1}},
2093 "{}\n",
2094 },
2095 {
2096 &struct {
2097 A float64 `yaml:"a,omitempty"`
2098 B float64 `yaml:"b,omitempty"`
2099 }{1, 0},
2100 "a: 1\n",
2101 },
2102 {
2103 &struct {
2104 T1 time.Time `yaml:"t1,omitempty"`
2105 T2 time.Time `yaml:"t2,omitempty"`
2106 T3 *time.Time `yaml:"t3,omitempty"`
2107 T4 *time.Time `yaml:"t4,omitempty"`
2108 }{
2109 T2: time.Date(2018, 1, 9, 10, 40, 47, 0, time.UTC),
2110 T4: newTime(time.Date(2098, 1, 9, 10, 40, 47, 0, time.UTC)),
2111 },
2112 "t2: 2018-01-09T10:40:47Z\nt4: 2098-01-09T10:40:47Z\n",
2113 },
2114 // Nil interface that implements Marshaler.
2115 {
2116 map[string]yaml.Marshaler{
2117 "a": nil,
2118 },
2119 "a: null\n",
2120 },
2121
2122 // Flow flag
2123 {
2124 &struct {
2125 A []int `yaml:"a,flow"`
2126 }{[]int{1, 2}},
2127 "a: [1, 2]\n",
2128 },
2129 {
2130 &struct {
2131 A map[string]string `yaml:"a,flow"`
2132 }{map[string]string{"b": "c", "d": "e"}},
2133 "a: {b: c, d: e}\n",
2134 },
2135 {
2136 &struct {
2137 A struct {
2138 B, D string
2139 } `yaml:"a,flow"`
2140 }{struct{ B, D string }{"c", "e"}},
2141 "a: {b: c, d: e}\n",
2142 },
2143 {
2144 &struct {
2145 A string `yaml:"a,flow"`
2146 }{"b\nc"},
2147 "a: \"b\\nc\"\n",
2148 },
2149
2150 // Unexported field
2151 {
2152 &struct {
2153 u int
2154 A int
2155 }{0, 1},
2156 "a: 1\n",
2157 },
2158
2159 // Ignored field
2160 {
2161 &struct {
2162 A int
2163 B int `yaml:"-"`
2164 }{1, 2},
2165 "a: 1\n",
2166 },
2167
2168 // Struct inlining
2169 {
2170 &struct {
2171 A int
2172 C inlineB `yaml:",inline"`
2173 }{1, inlineB{2, inlineC{3}}},
2174 "a: 1\nb: 2\nc: 3\n",
2175 },
2176 // Struct inlining as a pointer
2177 {
2178 &struct {
2179 A int
2180 C *inlineB `yaml:",inline"`
2181 }{1, &inlineB{2, inlineC{3}}},
2182 "a: 1\nb: 2\nc: 3\n",
2183 },
2184 {
2185 &struct {
2186 A int
2187 C *inlineB `yaml:",inline"`
2188 }{1, nil},
2189 "a: 1\n",
2190 },
2191 {
2192 &struct {
2193 A int
2194 D *inlineD `yaml:",inline"`
2195 }{1, &inlineD{&inlineC{3}, 4}},
2196 "a: 1\nc: 3\nd: 4\n",
2197 },
2198
2199 // Map inlining
2200 {
2201 &struct {
2202 A int
2203 C map[string]int `yaml:",inline"`
2204 }{1, map[string]int{"b": 2, "c": 3}},
2205 "a: 1\nb: 2\nc: 3\n",
2206 },
2207
2208 // Duration
2209 {
2210 map[string]time.Duration{"a": 3 * time.Second},
2211 "a: 3s\n",
2212 },
2213
2214 // Binary data.
2215 {
2216 map[string]string{"a": "\x80\x81\x82"},
2217 "a: !!binary gIGC\n",
2218 },
2219 {
2220 map[string]string{"a": strings.Repeat("\x90", 54)},
2221 "a: !!binary |\n " + strings.Repeat("kJCQ", 17) + "kJ\n CQ\n",
2222 },
2223
2224 // Support encoding.TextMarshaler.
2225 {
2226 map[string]net.IP{"a": net.IPv4(1, 2, 3, 4)},
2227 "a: 1.2.3.4\n",
2228 },
2229 // time.Time gets a timestamp tag.
2230 {
2231 map[string]time.Time{"a": time.Date(2015, 2, 24, 18, 19, 39, 0, time.UTC)},
2232 "a: 2015-02-24T18:19:39Z\n",
2233 },
2234 {
2235 map[string]*time.Time{"a": newTime(time.Date(2015, 2, 24, 18, 19, 39, 0, time.UTC))},
2236 "a: 2015-02-24T18:19:39Z\n",
2237 },
2238 {
2239 // This is confirmed to be properly decoded in Python (libyaml) without a timestamp tag.
2240 map[string]time.Time{"a": time.Date(2015, 2, 24, 18, 19, 39, 123456789, time.FixedZone("FOO", -3*60*60))},
2241 "a: 2015-02-24T18:19:39.123456789-03:00\n",
2242 },
2243
2244 // Ensure MarshalYAML also gets called on the result of MarshalYAML itself.
2245 {
2246 &marshalerType{marshalerType{true}},
2247 "true\n",
2248 },
2249 {
2250 &marshalerType{&marshalerType{true}},
2251 "true\n",
2252 },
2253
2254 // yaml.Node
2255 {
2256 &struct {
2257 Value yaml.Node
2258 }{
2259 yaml.Node{
2260 Kind: yaml.ScalarNode,
2261 Tag: "!!str",
2262 Value: "foo",
2263 Style: yaml.SingleQuotedStyle,
2264 },
2265 },
2266 "value: 'foo'\n",
2267 },
2268 {
2269 yaml.Node{
2270 Kind: yaml.ScalarNode,
2271 Tag: "!!str",
2272 Value: "foo",
2273 Style: yaml.SingleQuotedStyle,
2274 },
2275 "'foo'\n",
2276 },
2277
2278 // Enforced tagging with shorthand notation (issue #616).
2279 {
2280 &struct {
2281 Value yaml.Node
2282 }{
2283 yaml.Node{
2284 Kind: yaml.ScalarNode,
2285 Style: yaml.TaggedStyle,
2286 Value: "foo",
2287 Tag: "!!str",
2288 },
2289 },
2290 "value: !!str foo\n",
2291 },
2292 {
2293 &struct {
2294 Value yaml.Node
2295 }{
2296 yaml.Node{
2297 Kind: yaml.MappingNode,
2298 Style: yaml.TaggedStyle,
2299 Tag: "!!map",
2300 },
2301 },
2302 "value: !!map {}\n",
2303 },
2304 {
2305 &struct {
2306 Value yaml.Node
2307 }{
2308 yaml.Node{
2309 Kind: yaml.SequenceNode,
2310 Style: yaml.TaggedStyle,
2311 Tag: "!!seq",
2312 },
2313 },
2314 "value: !!seq []\n",
2315 },
2316 // bug: question mark in value
2317 {
2318 map[string]any{
2319 "foo": map[string]any{"bar": "a?bc"},
2320 },
2321 "foo:\n bar: a?bc\n",
2322 },
2323
2324 // issue https://github.com/yaml/go-yaml/issues/157
2325 {
2326 struct {
2327 F string `yaml:"foo"` // the correct tag, because it has `yaml` prefix
2328 B string `bar` //nolint:govet // the incorrect tag, but supported
2329 }{
2330 F: "abc",
2331 B: "def", // value should be set using whole tag as a name, see issue: <https://github.com/yaml/go-yaml/issues/157>
2332 },
2333 "foo: abc\nbar: def\n",
2334 },
2335 }
2336
2337 func TestMarshal(t *testing.T) {
2338 defer os.Setenv("TZ", os.Getenv("TZ"))
2339 os.Setenv("TZ", "UTC")
2340 for i, item := range marshalTests {
2341 t.Run(fmt.Sprintf("test %d: %q", i, item.data), func(t *testing.T) {
2342 data, err := yaml.Marshal(item.value)
2343 assert.NoError(t, err)
2344 assert.Equal(t, item.data, string(data))
2345 })
2346 }
2347 }
2348
2349 func TestEncodeToYAML(t *testing.T) {
2350 datatest.RunTestCases(t, func() ([]map[string]any, error) {
2351 return datatest.LoadTestCasesFromFile("testdata/encode.yaml", libyaml.LoadAny)
2352 }, map[string]datatest.TestHandler{
2353 "encode": runEncodeTest,
2354 "encode-opts": runEncodeOptsTest,
2355 })
2356 }
2357
2358 func runEncodeTest(t *testing.T, tc map[string]any) {
2359 t.Helper()
2360
2361 // Get type and create instance
2362 // Note: "type" field in YAML is renamed to "output_type" during normalization
2363 // to avoid conflict with the test type ("encode")
2364 typeName, ok := tc["output_type"].(string)
2365 if !ok {
2366 t.Fatalf("output_type must be a string")
2367 }
2368 data := tc["data"]
2369
2370 // Create pointer target of the specified type (for addressability)
2371 targetPtr, err := encodeTypeRegistry.NewPointerInstance(typeName)
2372 if err != nil {
2373 t.Fatalf("Failed to create instance of type %s: %v", typeName, err)
2374 }
2375
2376 // Resolve value constants (like +Inf, -Inf, NaN, -0)
2377 resolvedData := encodeValueRegistry.Resolve(data)
2378
2379 // Unmarshal the data into the target to populate it
2380 dataBytes, err := yaml.Marshal(resolvedData)
2381 if err != nil {
2382 t.Fatalf("Failed to marshal data: %v", err)
2383 }
2384
2385 err = yaml.Unmarshal(dataBytes, targetPtr)
2386 if err != nil {
2387 t.Fatalf("Failed to unmarshal data into target: %v", err)
2388 }
2389
2390 // Marshal the target back to YAML
2391 output, err := yaml.Marshal(targetPtr)
2392 if err != nil {
2393 t.Fatalf("Marshal failed: %v", err)
2394 }
2395
2396 // Compare with expected output
2397 want, ok := tc["want"].(string)
2398 if !ok {
2399 t.Fatalf("want must be a string")
2400 }
2401 assert.Equal(t, want, string(output))
2402 }
2403
2404 func runEncodeOptsTest(t *testing.T, tc map[string]any) {
2405 t.Helper()
2406
2407 // Get type and create instance
2408 // Note: "type" field in YAML is renamed to "output_type" during normalization
2409 // to avoid conflict with the test type ("encode-opts")
2410 typeName, ok := tc["output_type"].(string)
2411 if !ok {
2412 t.Fatalf("output_type must be a string")
2413 }
2414 data := tc["data"]
2415
2416 // Parse options
2417 var opts []yaml.Option
2418 if optsRaw, exists := tc["opts"]; exists {
2419 optsMap, ok := optsRaw.(map[string]any)
2420 if !ok {
2421 t.Fatalf("opts must be a map, got %T", optsRaw)
2422 }
2423 if rqRaw, exists := optsMap["required-quotes"]; exists {
2424 rq, ok := rqRaw.(string)
2425 if !ok {
2426 t.Fatalf("required-quotes must be a string, got %T", rqRaw)
2427 }
2428 switch rq {
2429 case "single":
2430 opts = append(opts, yaml.WithQuotePreference(yaml.QuoteSingle))
2431 case "double":
2432 opts = append(opts, yaml.WithQuotePreference(yaml.QuoteDouble))
2433 case "legacy":
2434 opts = append(opts, yaml.WithQuotePreference(yaml.QuoteLegacy))
2435 default:
2436 t.Fatalf("Unknown required-quotes value: %s", rq)
2437 }
2438 }
2439 }
2440
2441 // Create pointer target of the specified type (for addressability)
2442 targetPtr, err := encodeTypeRegistry.NewPointerInstance(typeName)
2443 if err != nil {
2444 t.Fatalf("Failed to create instance of type %s: %v", typeName, err)
2445 }
2446
2447 // Resolve value constants (like +Inf, -Inf, NaN, -0)
2448 resolvedData := encodeValueRegistry.Resolve(data)
2449
2450 // Unmarshal the data into the target to populate it
2451 dataBytes, err := yaml.Marshal(resolvedData)
2452 if err != nil {
2453 t.Fatalf("Failed to marshal data: %v", err)
2454 }
2455
2456 err = yaml.Unmarshal(dataBytes, targetPtr)
2457 if err != nil {
2458 t.Fatalf("Failed to unmarshal data into target: %v", err)
2459 }
2460
2461 // Dump the target to YAML with options
2462 output, err := yaml.Dump(targetPtr, opts...)
2463 if err != nil {
2464 t.Fatalf("Dump failed: %v", err)
2465 }
2466
2467 // Compare with expected output
2468 want, ok := tc["want"].(string)
2469 if !ok {
2470 t.Fatalf("want must be a string")
2471 }
2472 assert.Equal(t, want, string(output))
2473 }
2474
2475 func TestEncoderSingleDocument(t *testing.T) {
2476 for i, item := range marshalTests {
2477 t.Run(fmt.Sprintf("test %d. %q", i, item.data), func(t *testing.T) {
2478 var buf bytes.Buffer
2479 enc := yaml.NewEncoder(&buf)
2480 err := enc.Encode(item.value)
2481 assert.NoError(t, err)
2482 err = enc.Close()
2483 assert.NoError(t, err)
2484 assert.Equal(t, item.data, buf.String())
2485 })
2486 }
2487 }
2488
2489 func TestEncoderMultipleDocuments(t *testing.T) {
2490 var buf bytes.Buffer
2491 enc := yaml.NewEncoder(&buf)
2492 err := enc.Encode(map[string]string{"a": "b"})
2493 assert.NoError(t, err)
2494 err = enc.Encode(map[string]string{"c": "d"})
2495 assert.NoError(t, err)
2496 err = enc.Close()
2497 assert.NoError(t, err)
2498 assert.Equal(t, "a: b\n---\nc: d\n", buf.String())
2499 }
2500
2501 func TestEncoderWriteError(t *testing.T) {
2502 enc := yaml.NewEncoder(errorWriter{})
2503 err := enc.Encode(map[string]string{"a": "b"})
2504 assert.ErrorMatches(t, `go-yaml dump error in writer: some write error`, err)
2505 var dumpErr *yaml.DumpError
2506 assert.True(t, errors.As(err, &dumpErr))
2507 assert.Equal(t, yaml.WriterStage, dumpErr.Stage)
2508 }
2509
2510 type errorWriter struct{}
2511
2512 func (errorWriter) Write([]byte) (int, error) {
2513 return 0, fmt.Errorf("some write error")
2514 }
2515
2516 var marshalErrorTests = []struct {
2517 value any
2518 error string
2519 stage yaml.Stage
2520 }{{
2521 value: &struct {
2522 B int
2523 inlineB `yaml:",inline"`
2524 }{1, inlineB{2, inlineC{3}}},
2525 //nolint:dupword // struct is duplicated here as the first one is the struct and the second is the name of the inline struct
2526 error: `go-yaml dump error in representer: duplicated key 'b' in struct struct \{ B int; .*`,
2527 stage: yaml.RepresenterStage,
2528 }, {
2529 value: &struct {
2530 A int
2531 B map[string]int `yaml:",inline"`
2532 }{1, map[string]int{"a": 2}},
2533 error: `go-yaml dump error in representer: cannot have key "a" in inlined map: conflicts with struct field`,
2534 stage: yaml.RepresenterStage,
2535 }}
2536
2537 func TestMarshalErrors(t *testing.T) {
2538 for _, item := range marshalErrorTests {
2539 t.Run(item.error, func(t *testing.T) {
2540 _, err := yaml.Marshal(item.value)
2541 assert.ErrorMatches(t, item.error, err)
2542 var dumpErr *yaml.DumpError
2543 assert.True(t, errors.As(err, &dumpErr))
2544 assert.Equal(t, item.stage, dumpErr.Stage)
2545 })
2546 }
2547 }
2548
2549 func TestMarshalTypeCache(t *testing.T) {
2550 var data []byte
2551 var err error
2552 func() {
2553 type T struct{ A int }
2554 data, err = yaml.Marshal(&T{})
2555 assert.NoError(t, err)
2556 }()
2557 func() {
2558 type T struct{ B int }
2559 data, err = yaml.Marshal(&T{})
2560 assert.NoError(t, err)
2561 }()
2562 assert.Equal(t, "b: 0\n", string(data))
2563 }
2564
2565 var marshalerTests = []struct {
2566 data string
2567 value any
2568 }{
2569 {"_:\n hi: there\n", map[any]any{"hi": "there"}},
2570 {"_:\n - 1\n - A\n", []any{1, "A"}},
2571 {"_: 10\n", 10},
2572 {"_: null\n", nil},
2573 {"_: BAR!\n", "BAR!"},
2574 }
2575
2576 type marshalerType struct {
2577 value any
2578 }
2579
2580 func (o marshalerType) MarshalText() ([]byte, error) {
2581 panic("MarshalText called on type with MarshalYAML")
2582 }
2583
2584 func (o marshalerType) MarshalYAML() (any, error) {
2585 return o.value, nil
2586 }
2587
2588 type marshalerValue struct {
2589 Field marshalerType `yaml:"_"`
2590 }
2591
2592 func TestMarshaler(t *testing.T) {
2593 for _, item := range marshalerTests {
2594 t.Run(item.data, func(t *testing.T) {
2595 obj := &marshalerValue{}
2596 obj.Field.value = item.value
2597 data, err := yaml.Marshal(obj)
2598 assert.NoError(t, err)
2599 assert.Equal(t, item.data, string(data))
2600 })
2601 }
2602 }
2603
2604 func TestMarshalerWholeDocument(t *testing.T) {
2605 obj := &marshalerType{}
2606 obj.value = map[string]string{"hello": "world!"}
2607 data, err := yaml.Marshal(obj)
2608 assert.NoError(t, err)
2609 assert.Equal(t, "hello: world!\n", string(data))
2610 }
2611
2612 type failingMarshaler struct{}
2613
2614 func (ft *failingMarshaler) MarshalYAML() (any, error) {
2615 return nil, errFailing
2616 }
2617
2618 func TestMarshalerError(t *testing.T) {
2619 _, err := yaml.Marshal(&failingMarshaler{})
2620 assert.ErrorIs(t, err, errFailing)
2621 }
2622
2623 func TestSetIndent(t *testing.T) {
2624 var buf bytes.Buffer
2625 enc := yaml.NewEncoder(&buf)
2626 enc.SetIndent(8)
2627 err := enc.Encode(map[string]any{"a": map[string]any{"b": map[string]string{"c": "d"}}})
2628 assert.NoError(t, err)
2629 err = enc.Close()
2630 assert.NoError(t, err)
2631 assert.Equal(t, "a:\n b:\n c: d\n", buf.String())
2632 }
2633
2634 func TestSortedOutput(t *testing.T) {
2635 order := []any{
2636 false,
2637 true,
2638 1,
2639 uint(1),
2640 1.0,
2641 1.1,
2642 1.2,
2643 2,
2644 uint(2),
2645 2.0,
2646 2.1,
2647 "",
2648 ".1",
2649 ".2",
2650 ".a",
2651 "1",
2652 "2",
2653 "a!10",
2654 "a/0001",
2655 "a/002",
2656 "a/3",
2657 "a/10",
2658 "a/11",
2659 "a/0012",
2660 "a/100",
2661 "a~10",
2662 "ab/1",
2663 "b/1",
2664 "b/01",
2665 "b/2",
2666 "b/02",
2667 "b/3",
2668 "b/03",
2669 "b1",
2670 "b01",
2671 "b3",
2672 "c2.10",
2673 "c10.2",
2674 "d1",
2675 "d7",
2676 "d7abc",
2677 "d12",
2678 "d12a",
2679 "e2b",
2680 "e4b",
2681 "e21a",
2682 }
2683 m := make(map[any]int)
2684 for _, k := range order {
2685 m[k] = 1
2686 }
2687 data, err := yaml.Marshal(m)
2688 assert.NoError(t, err)
2689 out := "\n" + string(data)
2690 last := 0
2691 for i, k := range order {
2692 repr := fmt.Sprint(k)
2693 if s, ok := k.(string); ok {
2694 if _, err = strconv.ParseFloat(repr, 32); s == "" || err == nil {
2695 repr = `"` + repr + `"`
2696 }
2697 }
2698 index := strings.Index(out, "\n"+repr+":")
2699 if index == -1 {
2700 t.Fatalf("%#v is not in the output: %#v", k, out)
2701 }
2702 if index < last {
2703 t.Fatalf("%#v was generated before %#v: %q", k, order[i-1], out)
2704 }
2705 last = index
2706 }
2707 }
2708
2709 func newTime(t time.Time) *time.Time {
2710 return &t
2711 }
2712
2713 func TestCompactSeqIndentDefault(t *testing.T) {
2714 var buf bytes.Buffer
2715 enc := yaml.NewEncoder(&buf)
2716 enc.CompactSeqIndent()
2717 err := enc.Encode(map[string]any{"a": []string{"b", "c"}})
2718 assert.NoError(t, err)
2719 err = enc.Close()
2720 assert.NoError(t, err)
2721 // The default indent is 4, so these sequence elements get 2 indents as before
2722 assert.Equal(t, `a:
2723 - b
2724 - c
2725 `, buf.String())
2726 }
2727
2728 func TestCompactSequenceWithSetIndent(t *testing.T) {
2729 var buf bytes.Buffer
2730 enc := yaml.NewEncoder(&buf)
2731 enc.CompactSeqIndent()
2732 enc.SetIndent(2)
2733 err := enc.Encode(map[string]any{"a": []string{"b", "c"}})
2734 assert.NoError(t, err)
2735 err = enc.Close()
2736 assert.NoError(t, err)
2737 // The sequence indent is 2, so these sequence elements don't get indented at all
2738 assert.Equal(t, `a:
2739 - b
2740 - c
2741 `, buf.String())
2742 }
2743
2744 type (
2745 normal string
2746 compact string
2747 )
2748
2749 // newlinePlusNormalToNewlinePlusCompact maps the normal encoding (prefixed with a newline)
2750 // to the compact encoding (prefixed with a newline), for test cases in marshalTests
2751 var newlinePlusNormalToNewlinePlusCompact = map[normal]compact{
2752 normal(`
2753 v:
2754 - A
2755 - B
2756 `): compact(`
2757 v:
2758 - A
2759 - B
2760 `),
2761
2762 normal(`
2763 v:
2764 - A
2765 - |-
2766 B
2767 C
2768 `): compact(`
2769 v:
2770 - A
2771 - |-
2772 B
2773 C
2774 `),
2775
2776 normal(`
2777 v:
2778 - A
2779 - 1
2780 - B:
2781 - 2
2782 - 3
2783 `): compact(`
2784 v:
2785 - A
2786 - 1
2787 - B:
2788 - 2
2789 - 3
2790 `),
2791
2792 normal(`
2793 a:
2794 - 1
2795 - 2
2796 `): compact(`
2797 a:
2798 - 1
2799 - 2
2800 `),
2801
2802 normal(`
2803 a:
2804 b:
2805 - c: 1
2806 d: 2
2807 `): compact(`
2808 a:
2809 b:
2810 - c: 1
2811 d: 2
2812 `),
2813 }
2814
2815 func TestEncoderCompactIndents(t *testing.T) {
2816 for i, item := range marshalTests {
2817 t.Run(fmt.Sprintf("test %d. %q", i, item.data), func(t *testing.T) {
2818 var buf bytes.Buffer
2819 enc := yaml.NewEncoder(&buf)
2820 enc.CompactSeqIndent()
2821 err := enc.Encode(item.value)
2822 assert.NoError(t, err)
2823 err = enc.Close()
2824 assert.NoError(t, err)
2825
2826 // Default to expecting the item data
2827 expected := item.data
2828 // If there's a different compact representation, use that
2829 if c, ok := newlinePlusNormalToNewlinePlusCompact[normal("\n"+item.data)]; ok {
2830 expected = string(c[1:])
2831 }
2832
2833 assert.Equal(t, expected, buf.String())
2834 })
2835 }
2836 }
2837
2838 func TestNewLinePreserved(t *testing.T) {
2839 obj := &marshalerValue{}
2840 obj.Field.value = "a:\n b:\n c: d\n"
2841 data, err := yaml.Marshal(obj)
2842 assert.NoError(t, err)
2843 assert.Equal(t, "_: |\n a:\n b:\n c: d\n", string(data))
2844
2845 obj.Field.value = "\na:\n b:\n c: d\n"
2846 data, err = yaml.Marshal(obj)
2847 assert.NoError(t, err)
2848 // the newline at the start of the file should be preserved
2849 assert.Equal(t, "_: |\n\n a:\n b:\n c: d\n", string(data))
2850 }
2851
2852 // Scalar style tests for complex whitespace (tabs and Unicode)
2853 // These tests are kept in Go because they involve whitespace characters
2854 // that are difficult to represent accurately in YAML test data files.
2855
2856 func TestScalarStyleWithTabs(t *testing.T) {
2857 testCases := []struct {
2858 input string
2859 expected string
2860 desc string
2861 }{
2862 {
2863 "\t\n",
2864 "\"\\t\\n\"\n",
2865 "Tab + newline",
2866 },
2867 {
2868 "\t",
2869 "\"\\t\"\n",
2870 "Just tab",
2871 },
2872 {
2873 "hello\tworld",
2874 "\"hello\\tworld\"\n",
2875 "Text with tab",
2876 },
2877 {
2878 "\tThis starts with tab\nand is long enough\nfor literal style",
2879 "|-\n \tThis starts with tab\n and is long enough\n for literal style\n",
2880 "Multiline starting with tab",
2881 },
2882 {
2883 "\tB\n\tC\n",
2884 "|\n \tB\n \tC\n",
2885 "Tab B newline tab C newline",
2886 },
2887 {
2888 "\ta\n",
2889 "|\n \ta\n",
2890 "Tab + char + newline",
2891 },
2892 {
2893 "\thello\n",
2894 "|\n \thello\n",
2895 "Tab + text + newline",
2896 },
2897 {
2898 "\t\nhello",
2899 "|-\n \t\n hello\n",
2900 "Tab + newline + text",
2901 },
2902 }
2903
2904 for i, testCase := range testCases {
2905 t.Run(fmt.Sprintf("test_%d_%s", i, testCase.desc), func(t *testing.T) {
2906 data, err := yaml.Marshal(testCase.input)
2907 assert.NoError(t, err)
2908 assert.Equal(t, testCase.expected, string(data))
2909 })
2910 }
2911 }
2912
2913 func TestUnicodeWhitespaceHandling(t *testing.T) {
2914 // Test cases for Unicode whitespace characters that should be properly handled
2915 // by the shouldUseLiteralStyle function using unicode.IsSpace()
2916 testCases := []struct {
2917 input string
2918 expected string
2919 desc string
2920 }{
2921 // Unicode whitespace characters
2922 {
2923 "hello\u00A0\n", // non-breaking space
2924 "|\n hello\u00A0\n",
2925 "Non-breaking space with content",
2926 },
2927 {
2928 "\u00A0\n", // non-breaking space
2929 "\"\u00A0\\n\"\n",
2930 "Non-breaking space only",
2931 },
2932 {
2933 "hello\u2000\n", // en quad
2934 "|\n hello\u2000\n",
2935 "En quad with content",
2936 },
2937 {
2938 "\u2000\n", // en quad
2939 "\"\u2000\\n\"\n",
2940 "En quad only",
2941 },
2942 {
2943 "hello\u2001\n", // em quad
2944 "|\n hello\u2001\n",
2945 "Em quad with content",
2946 },
2947 {
2948 "\u2001\n", // em quad
2949 "\"\u2001\\n\"\n",
2950 "Em quad only",
2951 },
2952 {
2953 "hello\u2002\n", // en space
2954 "|\n hello\u2002\n",
2955 "En space with content",
2956 },
2957 {
2958 "\u2002\n", // en space
2959 "\"\u2002\\n\"\n",
2960 "En space only",
2961 },
2962 {
2963 "hello\u2003\n", // em space
2964 "|\n hello\u2003\n",
2965 "Em space with content",
2966 },
2967 {
2968 "\u2003\n", // em space
2969 "\"\u2003\\n\"\n",
2970 "Em space only",
2971 },
2972 {
2973 "hello\u2004\n", // three-per-em space
2974 "|\n hello\u2004\n",
2975 "Three-per-em space with content",
2976 },
2977 {
2978 "\u2004\n", // three-per-em space
2979 "\"\u2004\\n\"\n",
2980 "Three-per-em space only",
2981 },
2982 {
2983 "hello\u2005\n", // four-per-em space
2984 "|\n hello\u2005\n",
2985 "Four-per-em space with content",
2986 },
2987 {
2988 "\u2005\n", // four-per-em space
2989 "\"\u2005\\n\"\n",
2990 "Four-per-em space only",
2991 },
2992 {
2993 "hello\u2006\n", // six-per-em space
2994 "|\n hello\u2006\n",
2995 "Six-per-em space with content",
2996 },
2997 {
2998 "\u2006\n", // six-per-em space
2999 "\"\u2006\\n\"\n",
3000 "Six-per-em space only",
3001 },
3002 {
3003 "hello\u2007\n", // figure space
3004 "|\n hello\u2007\n",
3005 "Figure space with content",
3006 },
3007 {
3008 "\u2007\n", // figure space
3009 "\"\u2007\\n\"\n",
3010 "Figure space only",
3011 },
3012 {
3013 "hello\u2008\n", // punctuation space
3014 "|\n hello\u2008\n",
3015 "Punctuation space with content",
3016 },
3017 {
3018 "\u2008\n", // punctuation space
3019 "\"\u2008\\n\"\n",
3020 "Punctuation space only",
3021 },
3022 {
3023 "hello\u2009\n", // thin space
3024 "|\n hello\u2009\n",
3025 "Thin space with content",
3026 },
3027 {
3028 "\u2009\n", // thin space
3029 "\"\u2009\\n\"\n",
3030 "Thin space only",
3031 },
3032 {
3033 "hello\u200A\n", // hair space
3034 "|\n hello\u200A\n",
3035 "Hair space with content",
3036 },
3037 {
3038 "\u200A\n", // hair space
3039 "\"\u200A\\n\"\n",
3040 "Hair space only",
3041 },
3042 // Other Unicode whitespace
3043 {
3044 "hello\u2028\n", // line separator
3045 "|+\n hello\u2028\n",
3046 "Line separator with content",
3047 },
3048 {
3049 "\u2028\n", // line separator
3050 "\"\\L\\n\"\n",
3051 "Line separator only",
3052 },
3053 {
3054 "hello\u2029\n", // paragraph separator
3055 "|+\n hello\u2029\n",
3056 "Paragraph separator with content",
3057 },
3058 {
3059 "\u2029\n", // paragraph separator
3060 "\"\\P\\n\"\n",
3061 "Paragraph separator only",
3062 },
3063 {
3064 "hello\u205F\n", // medium mathematical space
3065 "|\n hello\u205F\n",
3066 "Medium mathematical space with content",
3067 },
3068 {
3069 "\u205F\n", // medium mathematical space
3070 "\"\u205F\\n\"\n",
3071 "Medium mathematical space only",
3072 },
3073 {
3074 "hello\u3000\n", // ideographic space
3075 "|\n hello\u3000\n",
3076 "Ideographic space with content",
3077 },
3078 {
3079 "\u3000\n", // ideographic space
3080 "\"\u3000\\n\"\n",
3081 "Ideographic space only",
3082 },
3083 // Mixed Unicode whitespace
3084 {
3085 "hello\u00A0\u2000\u2001\n", // mixed Unicode spaces
3086 "|\n hello\u00A0\u2000\u2001\n",
3087 "Mixed Unicode spaces with content",
3088 },
3089 {
3090 "\u00A0\u2000\u2001\n", // mixed Unicode spaces
3091 "\"\u00A0\u2000\u2001\\n\"\n",
3092 "Mixed Unicode spaces only",
3093 },
3094 // Unicode whitespace with ASCII whitespace
3095 {
3096 "hello \u00A0\t\n", // ASCII + Unicode spaces
3097 "|\n hello \u00A0\t\n",
3098 "ASCII + Unicode spaces with content",
3099 },
3100 {
3101 " \u00A0\t\n", // ASCII + Unicode spaces
3102 "\" \u00A0\\t\\n\"\n",
3103 "ASCII + Unicode spaces only",
3104 },
3105 }
3106
3107 for i, testCase := range testCases {
3108 t.Run(fmt.Sprintf("test_%d_%s", i, testCase.desc), func(t *testing.T) {
3109 data, err := yaml.Marshal(testCase.input)
3110 assert.NoError(t, err)
3111 assert.Equal(t, testCase.expected, string(data))
3112 })
3113 }
3114 }
3115
3116 func TestOptsYAML(t *testing.T) {
3117 tests := []struct {
3118 name string
3119 yamlStr string
3120 expectErr bool
3121 errMatch string
3122 }{
3123 {
3124 name: "valid options",
3125 yamlStr: "indent: 4\nknown-fields: true",
3126 expectErr: false,
3127 },
3128 {
3129 name: "typo in field name",
3130 yamlStr: "knnown-fields: true",
3131 expectErr: true,
3132 errMatch: "knnown-fields not found",
3133 },
3134 {
3135 name: "another typo",
3136 yamlStr: "indnt: 2",
3137 expectErr: true,
3138 errMatch: "indnt not found",
3139 },
3140 {
3141 name: "multiple options with one typo",
3142 yamlStr: "indent: 2\nunicoode: true",
3143 expectErr: true,
3144 errMatch: "unicoode not found",
3145 },
3146 {
3147 name: "all valid options",
3148 yamlStr: `
3149 indent: 2
3150 compact-seq-indent: true
3151 line-width: 80
3152 unicode: true
3153 canonical: false
3154 line-break: ln
3155 explicit-start: true
3156 explicit-end: false
3157 flow-simple-coll: true
3158 known-fields: true
3159 single-document: true
3160 unique-keys: true
3161 `,
3162 expectErr: false,
3163 },
3164 }
3165
3166 for _, tt := range tests {
3167 t.Run(tt.name, func(t *testing.T) {
3168 opt, err := yaml.OptsYAML(tt.yamlStr)
3169 if tt.expectErr {
3170 if err == nil {
3171 t.Fatalf("expected error but got none")
3172 }
3173 if tt.errMatch != "" && !strings.Contains(err.Error(), tt.errMatch) {
3174 t.Errorf("expected error to contain %q, got: %v", tt.errMatch, err)
3175 }
3176 } else {
3177 if err != nil {
3178 t.Fatalf("unexpected error: %v", err)
3179 }
3180 if opt == nil {
3181 t.Fatal("expected non-nil option")
3182 }
3183 }
3184 })
3185 }
3186 }
3187
3188 // FuzzEncodeFromJSON checks that any JSON encoded value can also be encoded as YAML... and decoded.
3189 func FuzzEncodeFromJSON(f *testing.F) {
3190 // Load seed corpus from testdata YAML file
3191 cases, err := datatest.LoadTestCasesFromFile("testdata/fuzz_json_roundtrip.yaml", libyaml.LoadAny)
3192 if err != nil {
3193 f.Fatalf("Failed to load seed corpus: %v", err)
3194 }
3195
3196 // Add each seed to the fuzz corpus
3197 for _, tc := range cases {
3198 if jsonInput, ok := datatest.GetString(tc, "json"); ok {
3199 f.Add(jsonInput)
3200 }
3201 }
3202
3203 f.Fuzz(func(t *testing.T, s string) {
3204 var v any
3205 if err := json.Unmarshal([]byte(s), &v); err != nil {
3206 t.Skipf("not valid JSON %q", s)
3207 }
3208
3209 t.Logf("JSON %q", s)
3210 t.Logf("Go %q <%[1]x>", v)
3211
3212 // Encode as YAML
3213 b, err := yaml.Marshal(v)
3214 if err != nil {
3215 t.Error(err)
3216 }
3217 t.Logf("YAML %q <%[1]x>", b)
3218
3219 // Decode as YAML
3220 var v2 any
3221 if err := yaml.Unmarshal(b, &v2); err != nil {
3222 t.Error(err)
3223 }
3224
3225 t.Logf("Go %q <%[1]x>", v2)
3226
3227 b2, err := yaml.Marshal(v2)
3228 if err != nil {
3229 t.Error(err)
3230 }
3231 t.Logf("YAML %q <%[1]x>", b2)
3232
3233 if !bytes.Equal(b, b2) {
3234 t.Errorf("Marshal->Unmarshal->Marshal mismatch:\n- expected: %q\n- got: %q", b, b2)
3235 }
3236 })
3237 }
3238
3239 func TestPlugins(t *testing.T) {
3240 datatest.RunTestCases(t, func() ([]map[string]any, error) {
3241 return datatest.LoadTestCasesFromFile("testdata/plugin.yaml", libyaml.LoadAny)
3242 }, map[string]datatest.TestHandler{
3243 "plugin-pass": runPluginTest,
3244 "plugin-error": runPluginTest,
3245 })
3246 }
3247
3248 func runPluginTest(t *testing.T, tc map[string]any) {
3249 t.Helper()
3250
3251 // Build YAML string from plugin config for OptsYAML
3252 pluginCfg := tc["plugin"]
3253 pluginYAML, err := yaml.Dump(map[string]any{"plugin": pluginCfg})
3254 if err != nil {
3255 t.Fatalf("Failed to marshal plugin config: %v", err)
3256 }
3257
3258 opts, err := yaml.OptsYAML(string(pluginYAML))
3259 if err != nil {
3260 t.Fatalf("OptsYAML failed: %v", err)
3261 }
3262
3263 // Generate data from spec
3264 data, err := datatest.GenerateData(tc["data"])
3265 if err != nil {
3266 t.Fatalf("Failed to generate data: %v", err)
3267 }
3268
3269 // Load with plugin options
3270 var result any
3271 err = yaml.Load(data, &result, opts)
3272
3273 // Check result
3274 expectedError := ""
3275 if wantVal, hasWant := tc["want"]; hasWant {
3276 if s, ok := wantVal.(string); ok {
3277 expectedError = s
3278 }
3279 }
3280
3281 if expectedError != "" {
3282 if err == nil {
3283 t.Fatalf("expected error %q, got nil", expectedError)
3284 }
3285 assert.Equal(t, expectedError, err.Error())
3286 return
3287 }
3288 assert.NoError(t, err)
3289 }
3290
3291 func TestLimit(t *testing.T) {
3292 datatest.RunTestCases(t, func() ([]map[string]any, error) {
3293 return datatest.LoadTestCasesFromFile("testdata/limit.yaml", libyaml.LoadAny)
3294 }, map[string]datatest.TestHandler{
3295 "limit": runLimitTest,
3296 "limit-error": runLimitTest,
3297 "limit-pass": runLimitTest,
3298 })
3299 }
3300
3301 func runLimitTest(t *testing.T, tc map[string]any) {
3302 t.Helper()
3303
3304 // Generate data from spec
3305 dataSpec := tc["data"]
3306 data, err := datatest.GenerateData(dataSpec)
3307 if err != nil {
3308 t.Fatalf("Failed to generate data: %v", err)
3309 }
3310
3311 // Get expected error if any (for limit-error tests)
3312 // For limit-pass tests, want might be a map describing expected structure
3313 expectedError := ""
3314 if wantVal, hasWant := tc["want"]; hasWant {
3315 switch v := wantVal.(type) {
3316 case string:
3317 expectedError = v
3318 case map[string]any:
3319 // Future: could validate structure here
3320 // For now, just ignore (treated as success case)
3321 default:
3322 t.Fatalf("want field must be a string or map, got %T", wantVal)
3323 }
3324 }
3325
3326 // Run unmarshal
3327 var v any
3328 err = yaml.Unmarshal(data, &v)
3329 if expectedError != "" {
3330 if err == nil {
3331 t.Fatalf("expected error %q, got nil", expectedError)
3332 }
3333 assert.ErrorMatches(t, expectedError, err)
3334 return
3335 }
3336 assert.NoError(t, err)
3337 }
3338
3339 // Keep benchmark using hardcoded data for performance consistency
3340 var limitTests = []struct {
3341 name string
3342 data []byte
3343 error string
3344 }{
3345 {
3346 name: "1000kb of maps with 100 aliases",
3347 data: []byte(`{a: &a [{a}` + strings.Repeat(`,{a}`, 1000*1024/4-100) + `], b: &b [*a` + strings.Repeat(`,*a`, 99) + `]}`),
3348 error: "yaml: document contains excessive aliasing",
3349 },
3350 {
3351 name: "1000kb of deeply nested slices",
3352 data: []byte(strings.Repeat(`[`, 1000*1024)),
3353 error: "yaml: while increasing flow level at line 1, column 10001: exceeded max depth of 10000",
3354 },
3355 {
3356 name: "1000kb of deeply nested maps",
3357 data: []byte("x: " + strings.Repeat(`{`, 1000*1024)),
3358 error: "yaml: while increasing flow level at line 1, column 10004: exceeded max depth of 10000",
3359 },
3360 {
3361 name: "1000kb of deeply nested indents",
3362 data: []byte(strings.Repeat(`- `, 1000*1024)),
3363 error: "yaml: while increasing indent level at line 1: line 1, column 20001: exceeded max depth of 10000",
3364 },
3365 {
3366 name: "1000kb of 1000-indent lines",
3367 data: []byte(strings.Repeat(strings.Repeat(`- `, 1000)+"\n", 1024/2)),
3368 },
3369 {name: "1kb of maps", data: []byte(`a: &a [{a}` + strings.Repeat(`,{a}`, 1*1024/4-1) + `]`)},
3370 {name: "10kb of maps", data: []byte(`a: &a [{a}` + strings.Repeat(`,{a}`, 10*1024/4-1) + `]`)},
3371 {name: "100kb of maps", data: []byte(`a: &a [{a}` + strings.Repeat(`,{a}`, 100*1024/4-1) + `]`)},
3372 {name: "1000kb of maps", data: []byte(`a: &a [{a}` + strings.Repeat(`,{a}`, 1000*1024/4-1) + `]`)},
3373 {name: "1000kb slice nested at max-depth", data: []byte(strings.Repeat(`[`, 10000) + `1` + strings.Repeat(`,1`, 1000*1024/2-20000-1) + strings.Repeat(`]`, 10000))},
3374 {name: "1000kb slice nested in maps at max-depth", data: []byte("{a,b:\n" + strings.Repeat(" {a,b:", 10000-2) + ` [1` + strings.Repeat(",1", 1000*1024/2-6*10000-1) + `]` + strings.Repeat(`}`, 10000-1))},
3375 {name: "1000kb of 10000-nested lines", data: []byte(strings.Repeat(`- `+strings.Repeat(`[`, 10000)+strings.Repeat(`]`, 10000)+"\n", 1000*1024/20000))},
3376 }
3377
3378 func BenchmarkLimit(b *testing.B) {
3379 for _, tc := range limitTests {
3380 tc := tc
3381 b.Run(tc.name, func(b *testing.B) {
3382 for i := 0; i < b.N; i++ {
3383 var v any
3384 err := yaml.Unmarshal(tc.data, &v)
3385 if tc.error != "" {
3386 assert.ErrorMatches(b, tc.error, err)
3387 continue
3388 }
3389 assert.NoError(b, err)
3390 }
3391 })
3392 }
3393 }
3394
3395 func TestParserGetEvents(t *testing.T) {
3396 datatest.RunTestCases(t, func() ([]map[string]any, error) {
3397 return datatest.LoadTestCasesFromFile("testdata/parser_events.yaml", libyaml.LoadAny)
3398 }, map[string]datatest.TestHandler{
3399 "parser-events": runParserEventsTest,
3400 })
3401 }
3402
3403 func runParserEventsTest(t *testing.T, tc map[string]any) {
3404 t.Helper()
3405
3406 // Extract test data
3407 yamlInput := datatest.RequireString(t, tc, "yaml")
3408 want := datatest.RequireString(t, tc, "want")
3409
3410 // Run test
3411 events, err := libyaml.ParserGetEvents([]byte(yamlInput))
3412 if err != nil {
3413 t.Fatalf("ParserGetEvents error: %v", err)
3414 }
3415
3416 // Trim trailing newline from want (YAML literal blocks add one)
3417 want = datatest.TrimTrailingNewline(want)
3418
3419 assert.Equal(t, want, events)
3420 }