Debian Codegraph @

testdata/yaml_test.go

raw symbols SCIP
1 package yaml_test
2
3 import (
4 "bytes"
5 "context"
6 "errors"
7 "strings"
8 "testing"
9
10 "github.com/google/go-cmp/cmp"
11
12 "github.com/goccy/go-yaml"
13 "github.com/goccy/go-yaml/ast"
14 )
15
16 func TestMarshal(t *testing.T) {
17 var v struct {
18 A int
19 B string
20 }
21 v.A = 1
22 v.B = "hello"
23 bytes, err := yaml.Marshal(v)
24 if err != nil {
25 t.Fatalf("%+v", err)
26 }
27 if string(bytes) != "a: 1\nb: hello\n" {
28 t.Fatal("failed to marshal")
29 }
30 }
31
32 func TestUnmarshal(t *testing.T) {
33 yml := `
34 %YAML 1.2
35 ---
36 a: 1
37 b: c
38 `
39 var v struct {
40 A int
41 B string
42 }
43 if err := yaml.Unmarshal([]byte(yml), &v); err != nil {
44 t.Fatalf("%+v", err)
45 }
46 }
47
48 type marshalTest struct{}
49
50 func (t *marshalTest) MarshalYAML() ([]byte, error) {
51 return yaml.Marshal(yaml.MapSlice{
52 {
53 "a", 1,
54 },
55 {
56 "b", "hello",
57 },
58 {
59 "c", true,
60 },
61 {
62 "d", map[string]string{"x": "y"},
63 },
64 })
65 }
66
67 type marshalTest2 struct{}
68
69 func (t *marshalTest2) MarshalYAML() (interface{}, error) {
70 return yaml.MapSlice{
71 {
72 "a", 2,
73 },
74 {
75 "b", "world",
76 },
77 {
78 "c", true,
79 },
80 }, nil
81 }
82
83 func TestMarshalYAML(t *testing.T) {
84 var v struct {
85 A *marshalTest
86 B *marshalTest2
87 }
88 v.A = &marshalTest{}
89 v.B = &marshalTest2{}
90 bytes, err := yaml.Marshal(v)
91 if err != nil {
92 t.Fatalf("failed to Marshal: %+v", err)
93 }
94 expect := `
95 a:
96 a: 1
97 b: hello
98 c: true
99 d:
100 x: "y"
101 b:
102 a: 2
103 b: world
104 c: true
105 `
106 actual := "\n" + string(bytes)
107 if expect != actual {
108 t.Fatalf("failed to MarshalYAML expect:[%s], actual:[%s]", expect, actual)
109 }
110 }
111
112 type unmarshalTest struct {
113 a int
114 b string
115 c bool
116 }
117
118 func (t *unmarshalTest) UnmarshalYAML(b []byte) error {
119 if t.a != 0 {
120 return errors.New("unexpected field value to a")
121 }
122 if t.b != "" {
123 return errors.New("unexpected field value to b")
124 }
125 if t.c {
126 return errors.New("unexpected field value to c")
127 }
128 var v struct {
129 A int
130 B string
131 C bool
132 }
133 if err := yaml.Unmarshal(b, &v); err != nil {
134 return err
135 }
136 t.a = v.A
137 t.b = v.B
138 t.c = v.C
139 return nil
140 }
141
142 type unmarshalTest2 struct {
143 a int
144 b string
145 c bool
146 }
147
148 func (t *unmarshalTest2) UnmarshalYAML(unmarshal func(interface{}) error) error {
149 var v struct {
150 A int
151 B string
152 C bool
153 }
154 if t.a != 0 {
155 return errors.New("unexpected field value to a")
156 }
157 if t.b != "" {
158 return errors.New("unexpected field value to b")
159 }
160 if t.c {
161 return errors.New("unexpected field value to c")
162 }
163 if err := unmarshal(&v); err != nil {
164 return err
165 }
166 t.a = v.A
167 t.b = v.B
168 t.c = v.C
169 return nil
170 }
171
172 func TestUnmarshalYAML(t *testing.T) {
173 yml := `
174 a:
175 a: 1
176 b: hello
177 c: true
178 b:
179 a: 2
180 b: world
181 c: true
182 `
183 var v struct {
184 A *unmarshalTest
185 B *unmarshalTest2
186 }
187 if err := yaml.Unmarshal([]byte(yml), &v); err != nil {
188 t.Fatalf("failed to Unmarshal: %+v", err)
189 }
190 if v.A == nil {
191 t.Fatal("failed to UnmarshalYAML")
192 }
193 if v.A.a != 1 {
194 t.Fatal("failed to UnmarshalYAML")
195 }
196 if v.A.b != "hello" {
197 t.Fatal("failed to UnmarshalYAML")
198 }
199 if !v.A.c {
200 t.Fatal("failed to UnmarshalYAML")
201 }
202 if v.B == nil {
203 t.Fatal("failed to UnmarshalYAML")
204 }
205 if v.B.a != 2 {
206 t.Fatal("failed to UnmarshalYAML")
207 }
208 if v.B.b != "world" {
209 t.Fatal("failed to UnmarshalYAML")
210 }
211 if !v.B.c {
212 t.Fatal("failed to UnmarshalYAML")
213 }
214 }
215
216 type ObjectMap map[string]*Object
217 type ObjectDecl struct {
218 Name string `yaml:"-"`
219 *Object `yaml:",inline,anchor"`
220 }
221
222 func (m ObjectMap) MarshalYAML() (interface{}, error) {
223 newMap := map[string]*ObjectDecl{}
224 for k, v := range m {
225 newMap[k] = &ObjectDecl{Name: k, Object: v}
226 }
227 return newMap, nil
228 }
229
230 type rootObject struct {
231 Single ObjectMap `yaml:"single"`
232 Collection map[string][]*Object `yaml:"collection"`
233 }
234
235 type Object struct {
236 *Object `yaml:",omitempty,inline,alias"`
237 MapValue map[string]interface{} `yaml:",omitempty,inline"`
238 }
239
240 func TestInlineAnchorAndAlias(t *testing.T) {
241 yml := `---
242 single:
243 default: &default
244 id: 1
245 name: john
246 user_1: &user_1
247 id: 1
248 name: ken
249 user_2: &user_2
250 <<: *default
251 id: 2
252 collection:
253 defaults:
254 - *default
255 - <<: *default
256 - <<: *default
257 id: 2
258 users:
259 - <<: *user_1
260 - <<: *user_2
261 - <<: *user_1
262 id: 3
263 - <<: *user_1
264 id: 4
265 - <<: *user_1
266 id: 5
267 `
268 var v rootObject
269 if err := yaml.Unmarshal([]byte(yml), &v); err != nil {
270 t.Fatal(err)
271 }
272 opt := yaml.MarshalAnchor(func(anchor *ast.AnchorNode, value interface{}) error {
273 if o, ok := value.(*ObjectDecl); ok {
274 return anchor.SetName(o.Name)
275 }
276 return nil
277 })
278 var buf bytes.Buffer
279 if err := yaml.NewEncoder(&buf, opt).Encode(v); err != nil {
280 t.Fatalf("%+v", err)
281 }
282 actual := "---\n" + buf.String()
283 if yml != actual {
284 t.Fatalf("failed to marshal: expected:[%s] actual:[%s]", yml, actual)
285 }
286 }
287
288 func TestMapSlice_Map(t *testing.T) {
289 yml := `
290 a: b
291 c: d
292 `
293 var v yaml.MapSlice
294 if err := yaml.Unmarshal([]byte(yml), &v); err != nil {
295 t.Fatal(err)
296 }
297 m := v.ToMap()
298 if len(m) != 2 {
299 t.Fatal("failed to convert MapSlice to map")
300 }
301 if m["a"] != "b" {
302 t.Fatal("failed to convert MapSlice to map")
303 }
304 if m["c"] != "d" {
305 t.Fatal("failed to convert MapSlice to map")
306 }
307 }
308
309 func TestMarshalWithModifiedAnchorAlias(t *testing.T) {
310 yml := `
311 a: &a 1
312 b: *a
313 `
314 var v struct {
315 A *int `yaml:"a,anchor"`
316 B *int `yaml:"b"`
317 }
318 if err := yaml.Unmarshal([]byte(yml), &v); err != nil {
319 t.Fatal(err)
320 }
321 node, err := yaml.ValueToNode(v)
322 if err != nil {
323 t.Fatal(err)
324 }
325 anchors := ast.Filter(ast.AnchorType, node)
326 if len(anchors) != 1 {
327 t.Fatal("failed to filter node")
328 }
329 anchor, _ := anchors[0].(*ast.AnchorNode)
330 if err := anchor.SetName("b"); err != nil {
331 t.Fatal(err)
332 }
333 aliases := ast.Filter(ast.AliasType, node)
334 if len(anchors) != 1 {
335 t.Fatal("failed to filter node")
336 }
337 alias, _ := aliases[0].(*ast.AliasNode)
338 if err := alias.SetName("b"); err != nil {
339 t.Fatal(err)
340 }
341
342 expected := `
343 a: &b 1
344 b: *b`
345
346 actual := "\n" + node.String()
347 if expected != actual {
348 t.Fatalf("failed to marshal: expected:[%q] but got [%q]", expected, actual)
349 }
350 }
351
352 func Test_YAMLToJSON(t *testing.T) {
353 yml := `
354 foo:
355 bar:
356 - a
357 - b
358 - c
359 a: 1
360 `
361 actual, err := yaml.YAMLToJSON([]byte(yml))
362 if err != nil {
363 t.Fatal(err)
364 }
365 expected := `{"foo": {"bar": ["a", "b", "c"]}, "a": 1}`
366 if expected+"\n" != string(actual) {
367 t.Fatalf("failed to convert yaml to json: expected [%q] but got [%q]", expected, actual)
368 }
369 }
370
371 func Test_JSONToYAML(t *testing.T) {
372 json := `{"foo": {"bar": ["a", "b", "c"]}, "a": 1}`
373 expected := `
374 foo:
375 bar:
376 - a
377 - b
378 - c
379 a: 1
380 `
381 actual, err := yaml.JSONToYAML([]byte(json))
382 if err != nil {
383 t.Fatal(err)
384 }
385 if expected != "\n"+string(actual) {
386 t.Fatalf("failed to convert json to yaml: expected [%q] but got [%q]", expected, actual)
387 }
388 }
389
390 func Test_WithCommentOption(t *testing.T) {
391 t.Run("line comment", func(t *testing.T) {
392 v := struct {
393 Foo string `yaml:"foo"`
394 Bar map[string]interface{} `yaml:"bar"`
395 Baz struct {
396 X int `yaml:"x"`
397 } `yaml:"baz"`
398 }{
399 Foo: "aaa",
400 Bar: map[string]interface{}{"bbb": "ccc"},
401 Baz: struct {
402 X int `yaml:"x"`
403 }{X: 10},
404 }
405 b, err := yaml.MarshalWithOptions(v, yaml.WithComment(
406 yaml.CommentMap{
407 "$.foo": []*yaml.Comment{yaml.LineComment("foo comment")},
408 "$.bar": []*yaml.Comment{yaml.LineComment("bar comment")},
409 "$.bar.bbb": []*yaml.Comment{yaml.LineComment("bbb comment")},
410 "$.baz.x": []*yaml.Comment{yaml.LineComment("x comment")},
411 },
412 ))
413 if err != nil {
414 t.Fatal(err)
415 }
416 expected := `
417 foo: aaa #foo comment
418 bar: #bar comment
419 bbb: ccc #bbb comment
420 baz:
421 x: 10 #x comment
422 `
423 actual := "\n" + string(b)
424 if expected != actual {
425 t.Fatalf("expected:%s but got %s", expected, actual)
426 }
427 })
428 t.Run("line comment2", func(t *testing.T) {
429 v := struct {
430 Foo map[string]interface{} `yaml:"foo"`
431 }{
432 Foo: map[string]interface{}{
433 "bar": map[string]interface{}{
434 "baz": true,
435 },
436 },
437 }
438 b, err := yaml.MarshalWithOptions(v, yaml.WithComment(
439 yaml.CommentMap{
440 "$.foo.bar": []*yaml.Comment{yaml.HeadComment(" bar head comment"), yaml.LineComment(" bar line comment")},
441 "$.foo.bar.baz": []*yaml.Comment{yaml.LineComment(" baz line comment")},
442 },
443 ))
444 if err != nil {
445 t.Fatal(err)
446 }
447 expected := `
448 foo:
449 # bar head comment
450 bar: # bar line comment
451 baz: true # baz line comment
452 `
453 actual := "\n" + string(b)
454 if expected != actual {
455 t.Fatalf("expected:%s but got %s", expected, actual)
456 }
457 })
458 t.Run("single head comment", func(t *testing.T) {
459 v := struct {
460 Foo string `yaml:"foo"`
461 Bar map[string]interface{} `yaml:"bar"`
462 Baz struct {
463 X int `yaml:"x"`
464 } `yaml:"baz"`
465 }{
466 Foo: "aaa",
467 Bar: map[string]interface{}{"bbb": "ccc"},
468 Baz: struct {
469 X int `yaml:"x"`
470 }{X: 10},
471 }
472
473 b, err := yaml.MarshalWithOptions(v, yaml.WithComment(
474 yaml.CommentMap{
475 "$.foo": []*yaml.Comment{yaml.HeadComment("foo comment")},
476 "$.bar": []*yaml.Comment{yaml.HeadComment("bar comment")},
477 "$.bar.bbb": []*yaml.Comment{yaml.HeadComment("bbb comment")},
478 "$.baz.x": []*yaml.Comment{yaml.HeadComment("x comment")},
479 },
480 ))
481 if err != nil {
482 t.Fatal(err)
483 }
484 expected := `
485 #foo comment
486 foo: aaa
487 #bar comment
488 bar:
489 #bbb comment
490 bbb: ccc
491 baz:
492 #x comment
493 x: 10
494 `
495 actual := "\n" + string(b)
496 if expected != actual {
497 t.Fatalf("expected:%s but got %s", expected, actual)
498 }
499 })
500
501 t.Run("multiple head comment", func(t *testing.T) {
502 v := struct {
503 Foo string `yaml:"foo"`
504 Bar map[string]interface{} `yaml:"bar"`
505 Baz struct {
506 X int `yaml:"x"`
507 } `yaml:"baz"`
508 }{
509 Foo: "aaa",
510 Bar: map[string]interface{}{"bbb": "ccc"},
511 Baz: struct {
512 X int `yaml:"x"`
513 }{X: 10},
514 }
515
516 b, err := yaml.MarshalWithOptions(v, yaml.WithComment(
517 yaml.CommentMap{
518 "$.foo": []*yaml.Comment{
519 yaml.HeadComment(
520 "foo comment",
521 "foo comment2",
522 ),
523 },
524 "$.bar": []*yaml.Comment{
525 yaml.HeadComment(
526 "bar comment",
527 "bar comment2",
528 ),
529 },
530 "$.bar.bbb": []*yaml.Comment{
531 yaml.HeadComment(
532 "bbb comment",
533 "bbb comment2",
534 ),
535 },
536 "$.baz.x": []*yaml.Comment{
537 yaml.HeadComment(
538 "x comment",
539 "x comment2",
540 ),
541 },
542 },
543 ))
544 if err != nil {
545 t.Fatal(err)
546 }
547 expected := `
548 #foo comment
549 #foo comment2
550 foo: aaa
551 #bar comment
552 #bar comment2
553 bar:
554 #bbb comment
555 #bbb comment2
556 bbb: ccc
557 baz:
558 #x comment
559 #x comment2
560 x: 10
561 `
562 actual := "\n" + string(b)
563 if expected != actual {
564 t.Fatalf("expected:%s but got %s", expected, actual)
565 }
566 })
567 t.Run("foot comment", func(t *testing.T) {
568 v := struct {
569 Bar map[string]interface{} `yaml:"bar"`
570 Baz []int `yaml:"baz"`
571 }{
572 Bar: map[string]interface{}{"bbb": "ccc"},
573 Baz: []int{1, 2},
574 }
575
576 b, err := yaml.MarshalWithOptions(v, yaml.IndentSequence(true), yaml.WithComment(
577 yaml.CommentMap{
578 "$.bar.bbb": []*yaml.Comment{yaml.FootComment("ccc: ddd")},
579 "$.baz[1]": []*yaml.Comment{yaml.FootComment("- 3")},
580 "$.baz": []*yaml.Comment{yaml.FootComment(" foot comment", "foot comment2")},
581 },
582 ))
583 if err != nil {
584 t.Fatal(err)
585 }
586 expected := `
587 bar:
588 bbb: ccc
589 #ccc: ddd
590 baz:
591 - 1
592 - 2
593 #- 3
594 # foot comment
595 #foot comment2
596 `
597 actual := "\n" + string(b)
598 if expected != actual {
599 t.Fatalf("expected:%s but got %s", expected, actual)
600 }
601 })
602
603 t.Run("combination", func(t *testing.T) {
604 v := struct {
605 Foo map[string]interface{} `yaml:"foo"`
606 O map[string]interface{} `yaml:"o"`
607 T map[string]bool `yaml:"t"`
608 Bar map[string]interface{} `yaml:"bar"`
609 Baz []int `yaml:"baz"`
610 Hoge map[string]interface{} `yaml:"hoge"`
611 }{
612 Foo: map[string]interface{}{
613 "a": map[string]interface{}{
614 "b": map[string]interface{}{
615 "c": "d",
616 },
617 },
618 },
619 O: map[string]interface{}{
620 "p": map[string]interface{}{
621 "q": map[string]interface{}{
622 "r": "s",
623 },
624 },
625 },
626 T: map[string]bool{
627 "u": true,
628 },
629 Bar: map[string]interface{}{"bbb": "ccc"},
630 Baz: []int{1, 2},
631 Hoge: map[string]interface{}{
632 "moga": true,
633 },
634 }
635
636 b, err := yaml.MarshalWithOptions(v, yaml.IndentSequence(true), yaml.WithComment(
637 yaml.CommentMap{
638 "$.foo": []*yaml.Comment{
639 yaml.HeadComment(" foo head comment", " foo head comment2"),
640 yaml.LineComment(" foo line comment"),
641 },
642 "$.foo.a": []*yaml.Comment{
643 yaml.HeadComment(" a head comment"),
644 yaml.LineComment(" a line comment"),
645 },
646 "$.foo.a.b": []*yaml.Comment{
647 yaml.HeadComment(" b head comment"),
648 yaml.LineComment(" b line comment"),
649 },
650 "$.foo.a.b.c": []*yaml.Comment{
651 yaml.LineComment(" c line comment"),
652 },
653 "$.o": []*yaml.Comment{
654 yaml.LineComment(" o line comment"),
655 },
656 "$.o.p": []*yaml.Comment{
657 yaml.HeadComment(" p head comment", " p head comment2"),
658 yaml.LineComment(" p line comment"),
659 },
660 "$.o.p.q": []*yaml.Comment{
661 yaml.HeadComment(" q head comment", " q head comment2"),
662 yaml.LineComment(" q line comment"),
663 },
664 "$.o.p.q.r": []*yaml.Comment{
665 yaml.LineComment(" r line comment"),
666 },
667 "$.t.u": []*yaml.Comment{
668 yaml.LineComment(" u line comment"),
669 },
670 "$.bar": []*yaml.Comment{
671 yaml.HeadComment(" bar head comment"),
672 yaml.LineComment(" bar line comment"),
673 },
674 "$.bar.bbb": []*yaml.Comment{
675 yaml.HeadComment(" bbb head comment"),
676 yaml.LineComment(" bbb line comment"),
677 yaml.FootComment(" bbb foot comment"),
678 },
679 "$.baz[0]": []*yaml.Comment{
680 yaml.HeadComment(" sequence head comment"),
681 yaml.LineComment(" sequence line comment"),
682 },
683 "$.baz[1]": []*yaml.Comment{
684 yaml.HeadComment(" sequence head comment2"),
685 yaml.LineComment(" sequence line comment2"),
686 yaml.FootComment(" sequence foot comment"),
687 },
688 "$.baz": []*yaml.Comment{
689 yaml.HeadComment(" baz head comment", " baz head comment2"),
690 yaml.LineComment(" baz line comment"),
691 yaml.FootComment(" baz foot comment"),
692 },
693 "$.hoge.moga": []*yaml.Comment{
694 yaml.LineComment(" moga line comment"),
695 yaml.FootComment(" moga foot comment"),
696 },
697 },
698 ))
699 if err != nil {
700 t.Fatal(err)
701 }
702 expected := `
703 # foo head comment
704 # foo head comment2
705 foo: # foo line comment
706 # a head comment
707 a: # a line comment
708 # b head comment
709 b: # b line comment
710 c: d # c line comment
711 o: # o line comment
712 # p head comment
713 # p head comment2
714 p: # p line comment
715 # q head comment
716 # q head comment2
717 q: # q line comment
718 r: s # r line comment
719 t:
720 u: true # u line comment
721 # bar head comment
722 bar: # bar line comment
723 # bbb head comment
724 bbb: ccc # bbb line comment
725 # bbb foot comment
726 # baz head comment
727 # baz head comment2
728 baz: # baz line comment
729 # sequence head comment
730 - 1 # sequence line comment
731 # sequence head comment2
732 - 2 # sequence line comment2
733 # sequence foot comment
734 # baz foot comment
735 hoge:
736 moga: true # moga line comment
737 # moga foot comment
738 `
739 actual := "\n" + string(b)
740 if expected != actual {
741 t.Fatalf("expected:%s but got %s", expected, actual)
742 }
743 })
744
745 }
746
747 func Test_CommentToMapOption(t *testing.T) {
748 type testCase struct {
749 name string
750 yml string
751 options []yaml.DecodeOption
752 expected []struct {
753 path string
754 comments []*yaml.Comment
755 }
756 }
757
758 tests := []testCase{
759 {
760 name: "line comment",
761 yml: `
762 foo: aaa #foo comment
763 bar: #bar comment
764 bbb: ccc #bbb comment
765 baz:
766 x: 10 #x comment
767 `,
768 expected: []struct {
769 path string
770 comments []*yaml.Comment
771 }{
772 {"$.foo", []*yaml.Comment{yaml.LineComment("foo comment")}},
773 {"$.bar", []*yaml.Comment{yaml.LineComment("bar comment")}},
774 {"$.bar.bbb", []*yaml.Comment{yaml.LineComment("bbb comment")}},
775 {"$.baz.x", []*yaml.Comment{yaml.LineComment("x comment")}},
776 },
777 },
778 {
779 name: "line comment2",
780 yml: `
781 foo:
782 bar: baz # comment`,
783 expected: []struct {
784 path string
785 comments []*yaml.Comment
786 }{
787 {"$.foo.bar", []*yaml.Comment{yaml.LineComment(" comment")}},
788 },
789 },
790 {
791 name: "single head comment",
792 yml: `
793 #foo comment
794 foo: aaa
795 #bar comment
796 bar:
797 #bbb comment
798 bbb: ccc
799 baz:
800 #x comment
801 x: 10
802 `,
803 expected: []struct {
804 path string
805 comments []*yaml.Comment
806 }{
807 {"$.foo", []*yaml.Comment{yaml.HeadComment("foo comment")}},
808 {"$.bar", []*yaml.Comment{yaml.HeadComment("bar comment")}},
809 {"$.bar.bbb", []*yaml.Comment{yaml.HeadComment("bbb comment")}},
810 {"$.baz.x", []*yaml.Comment{yaml.HeadComment("x comment")}},
811 },
812 },
813 {
814 name: "single head comment ordered map",
815 yml: `
816 #first comment
817 first: value
818 #second comment
819 second:
820 #third comment
821 third: value
822 #forth comment
823 forth: value
824 #fifth comment
825 fifth:
826 #sixth comment
827 sixth: value
828 #seventh comment
829 seventh: value
830 `,
831 expected: []struct {
832 path string
833 comments []*yaml.Comment
834 }{
835 {"$.first", []*yaml.Comment{yaml.HeadComment("first comment")}},
836 {"$.second", []*yaml.Comment{yaml.HeadComment("second comment")}},
837 {"$.second.third", []*yaml.Comment{yaml.HeadComment("third comment")}},
838 {"$.second.forth", []*yaml.Comment{yaml.HeadComment("forth comment")}},
839 {"$.fifth", []*yaml.Comment{yaml.HeadComment("fifth comment")}},
840 {"$.fifth.sixth", []*yaml.Comment{yaml.HeadComment("sixth comment")}},
841 {"$.fifth.seventh", []*yaml.Comment{yaml.HeadComment("seventh comment")}},
842 },
843 options: []yaml.DecodeOption{yaml.UseOrderedMap()},
844 },
845 {
846 name: "multiple head comments",
847 yml: `
848 #foo comment
849 #foo comment2
850 foo: aaa
851 #bar comment
852 #bar comment2
853 bar:
854 #bbb comment
855 #bbb comment2
856 bbb: ccc
857 baz:
858 #x comment
859 #x comment2
860 x: 10
861 `,
862 expected: []struct {
863 path string
864 comments []*yaml.Comment
865 }{
866 {"$.foo", []*yaml.Comment{yaml.HeadComment("foo comment", "foo comment2")}},
867 {"$.bar", []*yaml.Comment{yaml.HeadComment("bar comment", "bar comment2")}},
868 {"$.bar.bbb", []*yaml.Comment{yaml.HeadComment("bbb comment", "bbb comment2")}},
869 {"$.baz.x", []*yaml.Comment{yaml.HeadComment("x comment", "x comment2")}},
870 },
871 },
872 {
873 name: "foot comment",
874 yml: `
875 bar:
876 bbb: ccc
877 #ccc: ddd
878 baz:
879 - 1
880 - 2
881 #- 3
882 # foot comment
883 #foot comment2
884 `,
885 expected: []struct {
886 path string
887 comments []*yaml.Comment
888 }{
889 {"$.bar.bbb", []*yaml.Comment{yaml.FootComment("ccc: ddd")}},
890 {"$.baz[1]", []*yaml.Comment{yaml.FootComment("- 3")}},
891 {"$.baz", []*yaml.Comment{yaml.FootComment(" foot comment", "foot comment2")}},
892 },
893 },
894 {
895 name: "combination",
896 yml: `
897 # foo head comment
898 # foo head comment2
899 foo: # foo line comment
900 # a head comment
901 a: # a line comment
902 # b head comment
903 b: # b line comment
904 c: d # c line comment
905 o: # o line comment
906 # p head comment
907 # p head comment2
908 p: # p line comment
909 # q head comment
910 # q head comment2
911 q: # q line comment
912 r: s # r line comment
913 t:
914 u: true # u line comment
915 # bar head comment
916 bar: # bar line comment
917 # bbb head comment
918 bbb: ccc # bbb line comment
919 # bbb foot comment
920 # baz head comment
921 # baz head comment2
922 baz: # baz line comment
923 # sequence head comment
924 - 1 # sequence line comment
925 # sequence head comment2
926 - 2 # sequence line comment2
927 # sequence foot comment
928 hoge:
929 moga: true # moga line comment
930 # moga foot comment
931 # hoge foot comment
932 `,
933 expected: []struct {
934 path string
935 comments []*yaml.Comment
936 }{
937 {"$.foo", []*yaml.Comment{yaml.HeadComment(" foo head comment", " foo head comment2"), yaml.LineComment(" foo line comment")}},
938 {"$.foo.a", []*yaml.Comment{yaml.HeadComment(" a head comment"), yaml.LineComment(" a line comment")}},
939 {"$.foo.a.b", []*yaml.Comment{yaml.HeadComment(" b head comment"), yaml.LineComment(" b line comment")}},
940 {"$.foo.a.b.c", []*yaml.Comment{yaml.LineComment(" c line comment")}},
941 {"$.o", []*yaml.Comment{yaml.LineComment(" o line comment")}},
942 {"$.o.p", []*yaml.Comment{yaml.HeadComment(" p head comment", " p head comment2"), yaml.LineComment(" p line comment")}},
943 {"$.o.p.q", []*yaml.Comment{yaml.HeadComment(" q head comment", " q head comment2"), yaml.LineComment(" q line comment")}},
944 {"$.o.p.q.r", []*yaml.Comment{yaml.LineComment(" r line comment")}},
945 {"$.t.u", []*yaml.Comment{yaml.LineComment(" u line comment")}},
946 {"$.bar", []*yaml.Comment{yaml.HeadComment(" bar head comment"), yaml.LineComment(" bar line comment")}},
947 {"$.bar.bbb", []*yaml.Comment{yaml.HeadComment(" bbb head comment"), yaml.LineComment(" bbb line comment"), yaml.FootComment(" bbb foot comment")}},
948 {"$.baz[0]", []*yaml.Comment{yaml.HeadComment(" sequence head comment"), yaml.LineComment(" sequence line comment")}},
949 {"$.baz[1]", []*yaml.Comment{yaml.HeadComment(" sequence head comment2"), yaml.LineComment(" sequence line comment2"), yaml.FootComment(" sequence foot comment")}},
950 {"$.baz", []*yaml.Comment{yaml.HeadComment(" baz head comment", " baz head comment2"), yaml.LineComment(" baz line comment")}},
951 {"$.hoge", []*yaml.Comment{yaml.FootComment(" hoge foot comment")}},
952 {"$.hoge.moga", []*yaml.Comment{yaml.LineComment(" moga line comment"), yaml.FootComment(" moga foot comment")}},
953 },
954 },
955 }
956
957 for _, tc := range tests {
958 t.Run(tc.name, func(t *testing.T) {
959 cm := yaml.CommentMap{}
960 opts := []yaml.DecodeOption{yaml.CommentToMap(cm)}
961 opts = append(opts, tc.options...)
962
963 var v interface{}
964 if err := yaml.UnmarshalWithOptions([]byte(tc.yml), &v, opts...); err != nil {
965 t.Fatal(err)
966 }
967
968 if len(cm) != len(tc.expected) {
969 t.Fatalf("comment size does not match: got: %d, expected: %d", len(cm), len(tc.expected))
970 }
971 for _, exp := range tc.expected {
972 comments := cm[exp.path]
973 if comments == nil {
974 t.Fatalf("failed to get path %s", exp.path)
975 }
976 if diff := cmp.Diff(exp.comments, comments); diff != "" {
977 t.Errorf("(-got, +want)\n%s", diff)
978 }
979 }
980 })
981 }
982 }
983
984 func TestCommentMapRoundTrip(t *testing.T) {
985 // test that an unmarshal and marshal round trip retains comments.
986 // if expect is empty, the test will use the input as the expected result.
987 tests := []struct {
988 name string
989 source string
990 expect string
991 encodeOptions []yaml.EncodeOption
992 }{
993 {
994 name: "simple map",
995 source: `
996 # head
997 a: 1 # line
998 # foot
999 `,
1000 },
1001 {
1002 name: "nesting",
1003 source: `
1004 - 1 # one
1005 - foo:
1006 a: b
1007 # c comment
1008 c: d # d comment
1009 "e#f": g # g comment
1010 h.i: j # j comment
1011 "k.#l": m # m comment
1012 `,
1013 },
1014 {
1015 name: "single quotes",
1016 source: `'a#b': c # c comment`,
1017 encodeOptions: []yaml.EncodeOption{yaml.UseSingleQuote(true)},
1018 },
1019 {
1020 name: "single quotes added in encode",
1021 source: `a#b: c # c comment`,
1022 encodeOptions: []yaml.EncodeOption{yaml.UseSingleQuote(true)},
1023 expect: `'a#b': c # c comment`,
1024 },
1025 {
1026 name: "double quotes quotes transformed to single quotes",
1027 source: `"a#b": c # c comment`,
1028 encodeOptions: []yaml.EncodeOption{yaml.UseSingleQuote(true)},
1029 expect: `'a#b': c # c comment`,
1030 },
1031 {
1032 name: "single quotes quotes transformed to double quotes",
1033 source: `'a#b': c # c comment`,
1034 expect: `"a#b": c # c comment`,
1035 },
1036 {
1037 name: "single quotes removed",
1038 source: `'a': b # b comment`,
1039 expect: `a: b # b comment`,
1040 },
1041 {
1042 name: "double quotes removed",
1043 source: `"a": b # b comment`,
1044 expect: `a: b # b comment`,
1045 },
1046 }
1047 for _, test := range tests {
1048 t.Run(test.name, func(t *testing.T) {
1049 var val any
1050 cm := yaml.CommentMap{}
1051 source := strings.TrimSpace(test.source)
1052 if err := yaml.UnmarshalWithOptions([]byte(source), &val, yaml.CommentToMap(cm)); err != nil {
1053 t.Fatalf("%+v", err)
1054 }
1055 marshaled, err := yaml.MarshalWithOptions(val, append(test.encodeOptions, yaml.WithComment(cm))...)
1056 if err != nil {
1057 t.Fatalf("%+v", err)
1058 }
1059 got := strings.TrimSpace(string(marshaled))
1060 expect := strings.TrimSpace(test.expect)
1061 if expect == "" {
1062 expect = source
1063 }
1064 if got != expect {
1065 t.Fatalf("expected:\n%s\ngot:\n%s\n", expect, got)
1066 }
1067 })
1068
1069 }
1070 }
1071
1072 func TestRegisterCustomMarshaler(t *testing.T) {
1073 type T struct {
1074 Foo []byte `yaml:"foo"`
1075 }
1076 yaml.RegisterCustomMarshaler[T](func(_ T) ([]byte, error) {
1077 return []byte(`"override"`), nil
1078 })
1079 b, err := yaml.Marshal(&T{Foo: []byte("bar")})
1080 if err != nil {
1081 t.Fatal(err)
1082 }
1083 if !bytes.Equal(b, []byte("\"override\"\n")) {
1084 t.Fatalf("failed to register custom marshaler. got: %q", b)
1085 }
1086 }
1087
1088 func TestRegisterCustomMarshalerContext(t *testing.T) {
1089 type T struct {
1090 Foo []byte `yaml:"foo"`
1091 }
1092 yaml.RegisterCustomMarshalerContext[T](func(ctx context.Context, _ T) ([]byte, error) {
1093 if ctx.Value("plop") != uint(42) {
1094 t.Fatalf("context value is not correct")
1095 }
1096 return []byte(`"override"`), nil
1097 })
1098 ctx := context.WithValue(context.Background(), "plop", uint(42))
1099 b, err := yaml.MarshalContext(ctx, &T{Foo: []byte("bar")})
1100 if err != nil {
1101 t.Fatal(err)
1102 }
1103 if !bytes.Equal(b, []byte("\"override\"\n")) {
1104 t.Fatalf("failed to register custom marshaler. got: %q", b)
1105 }
1106 }
1107
1108 func TestRegisterCustomUnmarshaler(t *testing.T) {
1109 type T struct {
1110 Foo []byte `yaml:"foo"`
1111 }
1112 yaml.RegisterCustomUnmarshaler[T](func(v *T, _ []byte) error {
1113 v.Foo = []byte("override")
1114 return nil
1115 })
1116 var v T
1117 if err := yaml.Unmarshal([]byte(`"foo": "bar"`), &v); err != nil {
1118 t.Fatal(err)
1119 }
1120 if !bytes.Equal(v.Foo, []byte("override")) {
1121 t.Fatalf("failed to decode. got %q", v.Foo)
1122 }
1123 }
1124
1125 func TestRegisterCustomUnmarshalerContext(t *testing.T) {
1126 type T struct {
1127 Foo []byte `yaml:"foo"`
1128 }
1129 yaml.RegisterCustomUnmarshalerContext[T](func(ctx context.Context, v *T, _ []byte) error {
1130 if ctx.Value("plop") != uint(42) {
1131 t.Fatalf("context value is not correct")
1132 }
1133 v.Foo = []byte("override")
1134 return nil
1135 })
1136 var v T
1137 ctx := context.WithValue(context.Background(), "plop", uint(42))
1138 if err := yaml.UnmarshalContext(ctx, []byte(`"foo": "bar"`), &v); err != nil {
1139 t.Fatal(err)
1140 }
1141 if !bytes.Equal(v.Foo, []byte("override")) {
1142 t.Fatalf("failed to decode. got %q", v.Foo)
1143 }
1144 }