Debian Codegraph @

dependencies/pkg/mod/github.com/goccy/[email protected]/yaml_test.go

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