Debian Codegraph @

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

raw
1 package yaml_test
2
3 import (
4 "bytes"
5 "context"
6 "fmt"
7 "math"
8 "reflect"
9 "strconv"
10 "testing"
11 "time"
12
13 "github.com/goccy/go-yaml"
14 "github.com/goccy/go-yaml/ast"
15 "github.com/goccy/go-yaml/parser"
16 )
17
18 var zero = 0
19 var emptyStr = ""
20
21 func TestEncoder(t *testing.T) {
22 tests := []struct {
23 source string
24 value interface{}
25 options []yaml.EncodeOption
26 }{
27 {
28 "null\n",
29 (*struct{})(nil),
30 nil,
31 },
32 {
33 "v: hi\n",
34 map[string]string{"v": "hi"},
35 nil,
36 },
37 {
38 "v: \"true\"\n",
39 map[string]string{"v": "true"},
40 nil,
41 },
42 {
43 "v: \"false\"\n",
44 map[string]string{"v": "false"},
45 nil,
46 },
47 {
48 "v: true\n",
49 map[string]interface{}{"v": true},
50 nil,
51 },
52 {
53 "v: false\n",
54 map[string]bool{"v": false},
55 nil,
56 },
57 {
58 "v: 10\n",
59 map[string]int{"v": 10},
60 nil,
61 },
62 {
63 "v: -10\n",
64 map[string]int{"v": -10},
65 nil,
66 },
67 {
68 "v: 4294967296\n",
69 map[string]int64{"v": int64(4294967296)},
70 nil,
71 },
72 {
73 "v: 0.1\n",
74 map[string]interface{}{"v": 0.1},
75 nil,
76 },
77 {
78 "v: 0.99\n",
79 map[string]float32{"v": 0.99},
80 nil,
81 },
82 {
83 "v: 1e-06\n",
84 map[string]float32{"v": 1e-06},
85 nil,
86 },
87 {
88 "v: 1e-06\n",
89 map[string]float64{"v": 0.000001},
90 nil,
91 },
92 {
93 "v: 0.123456789\n",
94 map[string]float64{"v": 0.123456789},
95 nil,
96 },
97 {
98 "v: -0.1\n",
99 map[string]float64{"v": -0.1},
100 nil,
101 },
102 {
103 "v: 1.0\n",
104 map[string]float64{"v": 1.0},
105 nil,
106 },
107 {
108 "v: 1e+06\n",
109 map[string]float64{"v": 1000000},
110 nil,
111 },
112 {
113 "v: 1e-06\n",
114 map[string]float64{"v": 0.000001},
115 nil,
116 },
117 {
118 "v: 1e-06\n",
119 map[string]float64{"v": 1e-06},
120 nil,
121 },
122 {
123 "v: .inf\n",
124 map[string]interface{}{"v": math.Inf(0)},
125 nil,
126 },
127 {
128 "v: -.inf\n",
129 map[string]interface{}{"v": math.Inf(-1)},
130 nil,
131 },
132 {
133 "v: .nan\n",
134 map[string]interface{}{"v": math.NaN()},
135 nil,
136 },
137 {
138 "v: null\n",
139 map[string]interface{}{"v": nil},
140 nil,
141 },
142 {
143 "v: \"\"\n",
144 map[string]string{"v": ""},
145 nil,
146 },
147 {
148 "v:\n- A\n- B\n",
149 map[string][]string{"v": {"A", "B"}},
150 nil,
151 },
152 {
153 "v:\n - A\n - B\n",
154 map[string][]string{"v": {"A", "B"}},
155 []yaml.EncodeOption{
156 yaml.IndentSequence(true),
157 },
158 },
159 {
160 "v:\n- A\n- B\n",
161 map[string][2]string{"v": {"A", "B"}},
162 nil,
163 },
164 {
165 "v:\n - A\n - B\n",
166 map[string][2]string{"v": {"A", "B"}},
167 []yaml.EncodeOption{
168 yaml.IndentSequence(true),
169 },
170 },
171 {
172 "a: -\n",
173 map[string]string{"a": "-"},
174 nil,
175 },
176 {
177 "123\n",
178 123,
179 nil,
180 },
181 {
182 "hello: world\n",
183 map[string]string{"hello": "world"},
184 nil,
185 },
186 {
187 "hello: |\n hello\n world\n",
188 map[string]string{"hello": "hello\nworld\n"},
189 nil,
190 },
191 {
192 "hello: |-\n hello\n world\n",
193 map[string]string{"hello": "hello\nworld"},
194 nil,
195 },
196 {
197 "hello: |+\n hello\n world\n\n",
198 map[string]string{"hello": "hello\nworld\n\n"},
199 nil,
200 },
201 {
202 "hello:\n hello: |\n hello\n world\n",
203 map[string]map[string]string{"hello": {"hello": "hello\nworld\n"}},
204 nil,
205 },
206 {
207 "hello: |\r hello\r world\n",
208 map[string]string{"hello": "hello\rworld\r"},
209 nil,
210 },
211 {
212 "hello: |\r\n hello\r\n world\n",
213 map[string]string{"hello": "hello\r\nworld\r\n"},
214 nil,
215 },
216 {
217 "v: |-\n username: hello\n password: hello123\n",
218 map[string]interface{}{"v": "username: hello\npassword: hello123"},
219 []yaml.EncodeOption{
220 yaml.UseLiteralStyleIfMultiline(true),
221 },
222 },
223 {
224 "v: |-\n # comment\n username: hello\n password: hello123\n",
225 map[string]interface{}{"v": "# comment\nusername: hello\npassword: hello123"},
226 []yaml.EncodeOption{
227 yaml.UseLiteralStyleIfMultiline(true),
228 },
229 },
230 {
231 "v: \"# comment\\nusername: hello\\npassword: hello123\"\n",
232 map[string]interface{}{"v": "# comment\nusername: hello\npassword: hello123"},
233 []yaml.EncodeOption{
234 yaml.UseLiteralStyleIfMultiline(false),
235 },
236 },
237 {
238 "v:\n- A\n- 1\n- B:\n - 2\n - 3\n",
239 map[string]interface{}{
240 "v": []interface{}{
241 "A",
242 1,
243 map[string][]int{
244 "B": {2, 3},
245 },
246 },
247 },
248 nil,
249 },
250 {
251 "v:\n - A\n - 1\n - B:\n - 2\n - 3\n - 2\n",
252 map[string]interface{}{
253 "v": []interface{}{
254 "A",
255 1,
256 map[string][]int{
257 "B": {2, 3},
258 },
259 2,
260 },
261 },
262 []yaml.EncodeOption{
263 yaml.IndentSequence(true),
264 },
265 },
266 {
267 "a:\n b: c\n",
268 map[string]interface{}{
269 "a": map[string]string{
270 "b": "c",
271 },
272 },
273 nil,
274 },
275 {
276 "t2: 2018-01-09T10:40:47Z\nt4: 2098-01-09T10:40:47Z\n",
277 map[string]string{
278 "t2": "2018-01-09T10:40:47Z",
279 "t4": "2098-01-09T10:40:47Z",
280 },
281 nil,
282 },
283 {
284 "a:\n b: c\n d: e\n",
285 map[string]interface{}{
286 "a": map[string]string{
287 "b": "c",
288 "d": "e",
289 },
290 },
291 nil,
292 },
293 {
294 "a: 3s\n",
295 map[string]string{
296 "a": "3s",
297 },
298 nil,
299 },
300 {
301 "a: <foo>\n",
302 map[string]string{"a": "<foo>"},
303 nil,
304 },
305 {
306 "a: \"1:1\"\n",
307 map[string]string{"a": "1:1"},
308 nil,
309 },
310 {
311 "a: 1.2.3.4\n",
312 map[string]string{"a": "1.2.3.4"},
313 nil,
314 },
315 {
316 "a: \"b: c\"\n",
317 map[string]string{"a": "b: c"},
318 nil,
319 },
320 {
321 "a: \"Hello #comment\"\n",
322 map[string]string{"a": "Hello #comment"},
323 nil,
324 },
325 {
326 "a: \" b\"\n",
327 map[string]string{"a": " b"},
328 nil,
329 },
330 {
331 "a: \"b \"\n",
332 map[string]string{"a": "b "},
333 nil,
334 },
335 {
336 "a: \" b \"\n",
337 map[string]string{"a": " b "},
338 nil,
339 },
340 {
341 "a: \"`b` c\"\n",
342 map[string]string{"a": "`b` c"},
343 nil,
344 },
345 {
346 "a: 100.5\n",
347 map[string]interface{}{
348 "a": 100.5,
349 },
350 nil,
351 },
352 {
353 "a: \"\\\\0\"\n",
354 map[string]string{"a": "\\0"},
355 nil,
356 },
357 {
358 "a: 1\nb: 2\nc: 3\nd: 4\nsub:\n e: 5\n",
359 map[string]interface{}{
360 "a": 1,
361 "b": 2,
362 "c": 3,
363 "d": 4,
364 "sub": map[string]int{
365 "e": 5,
366 },
367 },
368 nil,
369 },
370 {
371 "a: 1\nb: []\n",
372 struct {
373 A int
374 B []string
375 }{
376 1, ([]string)(nil),
377 },
378 nil,
379 },
380 {
381 "a: 1\nb: []\n",
382 struct {
383 A int
384 B []string
385 }{
386 1, []string{},
387 },
388 nil,
389 },
390 {
391 "a: {}\n",
392 struct {
393 A map[string]interface{}
394 }{
395 map[string]interface{}{},
396 },
397 nil,
398 },
399 {
400 "a: b\nc: d\n",
401 struct {
402 A string
403 C string `yaml:"c"`
404 }{
405 "b", "d",
406 },
407 nil,
408 },
409 {
410 "a: 1\n",
411 struct {
412 A int
413 B int `yaml:"-"`
414 }{
415 1, 0,
416 },
417 nil,
418 },
419 {
420 "a: \"\"\n",
421 struct {
422 A string
423 }{
424 "",
425 },
426 nil,
427 },
428 {
429 "a: null\n",
430 struct {
431 A *string
432 }{
433 nil,
434 },
435 nil,
436 },
437 {
438 "a: \"\"\n",
439 struct {
440 A *string
441 }{
442 &emptyStr,
443 },
444 nil,
445 },
446 {
447 "a: null\n",
448 struct {
449 A *int
450 }{
451 nil,
452 },
453 nil,
454 },
455 {
456 "a: 0\n",
457 struct {
458 A *int
459 }{
460 &zero,
461 },
462 nil,
463 },
464
465 // Conditional flag
466 {
467 "a: 1\n",
468 struct {
469 A int `yaml:"a,omitempty"`
470 B int `yaml:"b,omitempty"`
471 }{1, 0},
472 nil,
473 },
474 {
475 "{}\n",
476 struct {
477 A int `yaml:"a,omitempty"`
478 B int `yaml:"b,omitempty"`
479 }{0, 0},
480 nil,
481 },
482
483 {
484 "a:\n \"y\": \"\"\n",
485 struct {
486 A *struct {
487 X string `yaml:"x,omitempty"`
488 Y string
489 }
490 }{&struct {
491 X string `yaml:"x,omitempty"`
492 Y string
493 }{}},
494 nil,
495 },
496
497 {
498 "a: {}\n",
499 struct {
500 A *struct {
501 X string `yaml:"x,omitempty"`
502 Y string `yaml:"y,omitempty"`
503 }
504 }{&struct {
505 X string `yaml:"x,omitempty"`
506 Y string `yaml:"y,omitempty"`
507 }{}},
508 nil,
509 },
510
511 {
512 "a: {x: 1}\n",
513 struct {
514 A *struct{ X, y int } `yaml:"a,omitempty,flow"`
515 }{&struct{ X, y int }{1, 2}},
516 nil,
517 },
518
519 {
520 "{}\n",
521 struct {
522 A *struct{ X, y int } `yaml:"a,omitempty,flow"`
523 }{nil},
524 nil,
525 },
526
527 {
528 "a: {x: 0}\n",
529 struct {
530 A *struct{ X, y int } `yaml:"a,omitempty,flow"`
531 }{&struct{ X, y int }{}},
532 nil,
533 },
534
535 {
536 "a: {x: 1}\n",
537 struct {
538 A struct{ X, y int } `yaml:"a,omitempty,flow"`
539 }{struct{ X, y int }{1, 2}},
540 nil,
541 },
542 {
543 "{}\n",
544 struct {
545 A struct{ X, y int } `yaml:"a,omitempty,flow"`
546 }{struct{ X, y int }{0, 1}},
547 nil,
548 },
549 {
550 "a: 1.0\n",
551 struct {
552 A float64 `yaml:"a,omitempty"`
553 B float64 `yaml:"b,omitempty"`
554 }{1, 0},
555 nil,
556 },
557 {
558 "a: 1\n",
559 struct {
560 A int
561 B []string `yaml:"b,omitempty"`
562 }{
563 1, []string{},
564 },
565 nil,
566 },
567
568 // Flow flag
569 {
570 "a: [1, 2]\n",
571 struct {
572 A []int `yaml:"a,flow"`
573 }{[]int{1, 2}},
574 nil,
575 },
576 {
577 "a: {b: c, d: e}\n",
578 &struct {
579 A map[string]string `yaml:"a,flow"`
580 }{map[string]string{"b": "c", "d": "e"}},
581 nil,
582 },
583 {
584 "a: {b: c, d: e}\n",
585 struct {
586 A struct {
587 B, D string
588 } `yaml:"a,flow"`
589 }{struct{ B, D string }{"c", "e"}},
590 nil,
591 },
592 // Quoting in flow mode
593 {
594 `a: [b, "c,d", e]` + "\n",
595 struct {
596 A []string `yaml:"a,flow"`
597 }{[]string{"b", "c,d", "e"}},
598 []yaml.EncodeOption{
599 yaml.UseSingleQuote(false),
600 },
601 },
602 {
603 `a: [b, "c]", d]` + "\n",
604 struct {
605 A []string `yaml:"a,flow"`
606 }{[]string{"b", "c]", "d"}},
607 []yaml.EncodeOption{
608 yaml.UseSingleQuote(false),
609 },
610 },
611 {
612 `a: [b, "c}", d]` + "\n",
613 struct {
614 A []string `yaml:"a,flow"`
615 }{[]string{"b", "c}", "d"}},
616 []yaml.EncodeOption{
617 yaml.UseSingleQuote(false),
618 },
619 },
620 {
621 `a: [b, "c\"", d]` + "\n",
622 struct {
623 A []string `yaml:"a,flow"`
624 }{[]string{"b", `c"`, "d"}},
625 []yaml.EncodeOption{
626 yaml.UseSingleQuote(false),
627 },
628 },
629 {
630 `a: [b, "c'", d]` + "\n",
631 struct {
632 A []string `yaml:"a,flow"`
633 }{[]string{"b", "c'", "d"}},
634 []yaml.EncodeOption{
635 yaml.UseSingleQuote(false),
636 },
637 },
638 // No quoting in non-flow mode
639 {
640 "a:\n- b\n- c,d\n- e\n",
641 struct {
642 A []string `yaml:"a"`
643 }{[]string{"b", "c,d", "e"}},
644 nil,
645 },
646 {
647 `a: [b, "c]", d]` + "\n",
648 struct {
649 A []string `yaml:"a,flow"`
650 }{[]string{"b", "c]", "d"}},
651 nil,
652 },
653 {
654 `a: [b, "c}", d]` + "\n",
655 struct {
656 A []string `yaml:"a,flow"`
657 }{[]string{"b", "c}", "d"}},
658 nil,
659 },
660 {
661 `a: [b, "c\"", d]` + "\n",
662 struct {
663 A []string `yaml:"a,flow"`
664 }{[]string{"b", `c"`, "d"}},
665 nil,
666 },
667 {
668 `a: [b, "c'", d]` + "\n",
669 struct {
670 A []string `yaml:"a,flow"`
671 }{[]string{"b", "c'", "d"}},
672 nil,
673 },
674
675 // Multi bytes
676 {
677 "v: あいうえお\nv2: かきくけこ\n",
678 map[string]string{"v": "あいうえお", "v2": "かきくけこ"},
679 nil,
680 },
681
682 // time value
683 {
684 "v: 0001-01-01T00:00:00Z\n",
685 map[string]time.Time{"v": {}},
686 nil,
687 },
688 {
689 "v: 0001-01-01T00:00:00Z\n",
690 map[string]*time.Time{"v": {}},
691 nil,
692 },
693 {
694 "v: null\n",
695 map[string]*time.Time{"v": nil},
696 nil,
697 },
698 {
699 "v: 30s\n",
700 map[string]time.Duration{"v": 30 * time.Second},
701 nil,
702 },
703 // Quote style
704 {
705 `v: '\'a\'b'` + "\n",
706 map[string]string{"v": `'a'b`},
707 []yaml.EncodeOption{
708 yaml.UseSingleQuote(true),
709 },
710 },
711 {
712 `v: "'a'b"` + "\n",
713 map[string]string{"v": `'a'b`},
714 []yaml.EncodeOption{
715 yaml.UseSingleQuote(false),
716 },
717 },
718 }
719 for _, test := range tests {
720 var buf bytes.Buffer
721 enc := yaml.NewEncoder(&buf, test.options...)
722 if err := enc.Encode(test.value); err != nil {
723 t.Fatalf("%+v", err)
724 }
725 if test.source != buf.String() {
726 t.Fatalf("expect = [%s], actual = [%s]", test.source, buf.String())
727 }
728 }
729 }
730
731 func TestEncodeStructIncludeMap(t *testing.T) {
732 type U struct {
733 M map[string]string
734 }
735 type T struct {
736 A U
737 }
738 bytes, err := yaml.Marshal(T{
739 A: U{
740 M: map[string]string{"x": "y"},
741 },
742 })
743 if err != nil {
744 t.Fatalf("%+v", err)
745 }
746 expect := "a:\n m:\n x: \"y\"\n"
747 actual := string(bytes)
748 if actual != expect {
749 t.Fatalf("unexpected output. expect:[%s] actual:[%s]", expect, actual)
750 }
751 }
752
753 func TestEncodeDefinedTypeKeyMap(t *testing.T) {
754 type K string
755 type U struct {
756 M map[K]string
757 }
758 bytes, err := yaml.Marshal(U{
759 M: map[K]string{K("x"): "y"},
760 })
761 if err != nil {
762 t.Fatalf("%+v", err)
763 }
764 expect := "m:\n x: \"y\"\n"
765 actual := string(bytes)
766 if actual != expect {
767 t.Fatalf("unexpected output. expect:[%s] actual:[%s]", expect, actual)
768 }
769 }
770
771 func TestEncodeWithAnchorAndAlias(t *testing.T) {
772 var buf bytes.Buffer
773 enc := yaml.NewEncoder(&buf)
774 type T struct {
775 A int
776 B string
777 }
778 var v struct {
779 A *T `yaml:"a,anchor=c"`
780 B *T `yaml:"b,alias=c"`
781 }
782 v.A = &T{A: 1, B: "hello"}
783 v.B = v.A
784 if err := enc.Encode(v); err != nil {
785 t.Fatalf("%+v", err)
786 }
787 expect := "a: &c\n a: 1\n b: hello\nb: *c\n"
788 if expect != buf.String() {
789 t.Fatalf("expect = [%s], actual = [%s]", expect, buf.String())
790 }
791 }
792
793 func TestEncodeWithAutoAlias(t *testing.T) {
794 var buf bytes.Buffer
795 enc := yaml.NewEncoder(&buf)
796 type T struct {
797 I int
798 S string
799 }
800 var v struct {
801 A *T `yaml:"a,anchor=a"`
802 B *T `yaml:"b,anchor=b"`
803 C *T `yaml:"c,alias"`
804 D *T `yaml:"d,alias"`
805 }
806 v.A = &T{I: 1, S: "hello"}
807 v.B = &T{I: 2, S: "world"}
808 v.C = v.A
809 v.D = v.B
810 if err := enc.Encode(v); err != nil {
811 t.Fatalf("%+v", err)
812 }
813 expect := `a: &a
814 i: 1
815 s: hello
816 b: &b
817 i: 2
818 s: world
819 c: *a
820 d: *b
821 `
822 if expect != buf.String() {
823 t.Fatalf("expect = [%s], actual = [%s]", expect, buf.String())
824 }
825 }
826
827 func TestEncodeWithImplicitAnchorAndAlias(t *testing.T) {
828 var buf bytes.Buffer
829 enc := yaml.NewEncoder(&buf)
830 type T struct {
831 I int
832 S string
833 }
834 var v struct {
835 A *T `yaml:"a,anchor"`
836 B *T `yaml:"b,anchor"`
837 C *T `yaml:"c,alias"`
838 D *T `yaml:"d,alias"`
839 }
840 v.A = &T{I: 1, S: "hello"}
841 v.B = &T{I: 2, S: "world"}
842 v.C = v.A
843 v.D = v.B
844 if err := enc.Encode(v); err != nil {
845 t.Fatalf("%+v", err)
846 }
847 expect := `a: &a
848 i: 1
849 s: hello
850 b: &b
851 i: 2
852 s: world
853 c: *a
854 d: *b
855 `
856 if expect != buf.String() {
857 t.Fatalf("expect = [%s], actual = [%s]", expect, buf.String())
858 }
859 }
860
861 func TestEncodeWithMerge(t *testing.T) {
862 type Person struct {
863 *Person `yaml:",omitempty,inline,alias"`
864 Name string `yaml:",omitempty"`
865 Age int `yaml:",omitempty"`
866 }
867 defaultPerson := &Person{
868 Name: "John Smith",
869 Age: 20,
870 }
871 people := []*Person{
872 {
873 Person: defaultPerson,
874 Name: "Ken",
875 Age: 10,
876 },
877 {
878 Person: defaultPerson,
879 },
880 }
881 var doc struct {
882 Default *Person `yaml:"default,anchor"`
883 People []*Person `yaml:"people"`
884 }
885 doc.Default = defaultPerson
886 doc.People = people
887 var buf bytes.Buffer
888 enc := yaml.NewEncoder(&buf)
889 if err := enc.Encode(doc); err != nil {
890 t.Fatalf("%+v", err)
891 }
892 expect := `default: &default
893 name: John Smith
894 age: 20
895 people:
896 - <<: *default
897 name: Ken
898 age: 10
899 - <<: *default
900 `
901 if expect != buf.String() {
902 t.Fatalf("expect = [%s], actual = [%s]", expect, buf.String())
903 }
904 }
905
906 func TestEncodeWithNestedYAML(t *testing.T) {
907 // Represents objects containing stringified YAML, and special chars
908 tests := []struct {
909 value interface{}
910 // If true, expects a different result between when using forced literal style or not
911 expectDifferent bool
912 }{
913 {
914 value: map[string]interface{}{"v": "# comment\nname: hello\npassword: hello123\nspecial: \":ghost:\"\ntext: |\n nested multiline!"},
915 expectDifferent: true,
916 },
917 {
918 value: map[string]interface{}{"v": "# comment\nusername: hello\npassword: hello123"},
919 expectDifferent: true,
920 },
921 {
922 value: map[string]interface{}{"v": "# comment\n"},
923 expectDifferent: true,
924 },
925 {
926 value: map[string]interface{}{"v": "\n"},
927 },
928 }
929
930 for _, test := range tests {
931 yamlBytesForced, err := yaml.MarshalWithOptions(test.value, yaml.UseLiteralStyleIfMultiline(true))
932 if err != nil {
933 t.Fatalf("%+v", err)
934 }
935
936 // Convert it back for proper equality testing
937 var unmarshaled interface{}
938
939 if err := yaml.Unmarshal(yamlBytesForced, &unmarshaled); err != nil {
940 t.Fatalf("%+v", err)
941 }
942
943 if !reflect.DeepEqual(test.value, unmarshaled) {
944 t.Fatalf("expected %v(%T). but actual %v(%T)", test.value, test.value, unmarshaled, unmarshaled)
945 }
946
947 if test.expectDifferent {
948 yamlBytesNotForced, err := yaml.MarshalWithOptions(test.value)
949 if err != nil {
950 t.Fatalf("%+v", err)
951 }
952
953 if string(yamlBytesForced) == string(yamlBytesNotForced) {
954 t.Fatalf("expected different strings when force literal style is not enabled. forced: %s, not forced: %s", string(yamlBytesForced), string(yamlBytesNotForced))
955 }
956 }
957 }
958 }
959
960 func TestEncoder_Inline(t *testing.T) {
961 type base struct {
962 A int
963 B string
964 }
965 var buf bytes.Buffer
966 enc := yaml.NewEncoder(&buf)
967 if err := enc.Encode(struct {
968 *base `yaml:",inline"`
969 C bool
970 }{
971 base: &base{
972 A: 1,
973 B: "hello",
974 },
975 C: true,
976 }); err != nil {
977 t.Fatalf("%+v", err)
978 }
979 expect := `
980 a: 1
981 b: hello
982 c: true
983 `
984 actual := "\n" + buf.String()
985 if expect != actual {
986 t.Fatalf("inline marshal error: expect=[%s] actual=[%s]", expect, actual)
987 }
988 }
989
990 func TestEncoder_InlineAndConflictKey(t *testing.T) {
991 type base struct {
992 A int
993 B string
994 }
995 var buf bytes.Buffer
996 enc := yaml.NewEncoder(&buf)
997 if err := enc.Encode(struct {
998 *base `yaml:",inline"`
999 A int // conflict
1000 C bool
1001 }{
1002 base: &base{
1003 A: 1,
1004 B: "hello",
1005 },
1006 A: 0, // default value
1007 C: true,
1008 }); err != nil {
1009 t.Fatalf("%+v", err)
1010 }
1011 expect := `
1012 b: hello
1013 a: 0
1014 c: true
1015 `
1016 actual := "\n" + buf.String()
1017 if expect != actual {
1018 t.Fatalf("inline marshal error: expect=[%s] actual=[%s]", expect, actual)
1019 }
1020 }
1021
1022 func TestEncoder_InlineNil(t *testing.T) {
1023 type base struct {
1024 A int
1025 B string
1026 }
1027 var buf bytes.Buffer
1028 enc := yaml.NewEncoder(&buf)
1029 if err := enc.Encode(struct {
1030 *base `yaml:",inline"`
1031 C bool
1032 }{
1033 C: true,
1034 }); err != nil {
1035 t.Fatalf("%+v", err)
1036 }
1037 expect := `
1038 c: true
1039 `
1040 actual := "\n" + buf.String()
1041 if expect != actual {
1042 t.Fatalf("inline marshal error: expect=[%s] actual=[%s]", expect, actual)
1043 }
1044 }
1045
1046 func TestEncoder_Flow(t *testing.T) {
1047 var buf bytes.Buffer
1048 enc := yaml.NewEncoder(&buf, yaml.Flow(true))
1049 var v struct {
1050 A int
1051 B string
1052 C struct {
1053 D int
1054 E string
1055 }
1056 F []int
1057 }
1058 v.A = 1
1059 v.B = "hello"
1060 v.C.D = 3
1061 v.C.E = "world"
1062 v.F = []int{1, 2}
1063 if err := enc.Encode(v); err != nil {
1064 t.Fatalf("%+v", err)
1065 }
1066 expect := `
1067 {a: 1, b: hello, c: {d: 3, e: world}, f: [1, 2]}
1068 `
1069 actual := "\n" + buf.String()
1070 if expect != actual {
1071 t.Fatalf("flow style marshal error: expect=[%s] actual=[%s]", expect, actual)
1072 }
1073 }
1074
1075 func TestEncoder_FlowRecursive(t *testing.T) {
1076 var v struct {
1077 M map[string][]int `yaml:",flow"`
1078 }
1079 v.M = map[string][]int{
1080 "test": {1, 2, 3},
1081 }
1082 var buf bytes.Buffer
1083 if err := yaml.NewEncoder(&buf).Encode(v); err != nil {
1084 t.Fatalf("%+v", err)
1085 }
1086 expect := `
1087 m: {test: [1, 2, 3]}
1088 `
1089 actual := "\n" + buf.String()
1090 if expect != actual {
1091 t.Fatalf("flow style marshal error: expect=[%s] actual=[%s]", expect, actual)
1092 }
1093 }
1094
1095 func TestEncoder_JSON(t *testing.T) {
1096 var buf bytes.Buffer
1097 enc := yaml.NewEncoder(&buf, yaml.JSON())
1098 type st struct {
1099 I int8
1100 S string
1101 F float32
1102 }
1103 if err := enc.Encode(struct {
1104 I int
1105 U uint
1106 S string
1107 F float64
1108 Struct *st
1109 Slice []int
1110 Map map[string]interface{}
1111 Time time.Time
1112 Duration time.Duration
1113 }{
1114 I: -10,
1115 U: 10,
1116 S: "hello",
1117 F: 3.14,
1118 Struct: &st{
1119 I: 2,
1120 S: "world",
1121 F: 1.23,
1122 },
1123 Slice: []int{1, 2, 3, 4, 5},
1124 Map: map[string]interface{}{
1125 "a": 1,
1126 "b": 1.23,
1127 "c": "json",
1128 },
1129 Time: time.Time{},
1130 Duration: 5 * time.Minute,
1131 }); err != nil {
1132 t.Fatalf("%+v", err)
1133 }
1134 expect := `
1135 {"i": -10, "u": 10, "s": "hello", "f": 3.14, "struct": {"i": 2, "s": "world", "f": 1.23}, "slice": [1, 2, 3, 4, 5], "map": {"a": 1, "b": 1.23, "c": "json"}, "time": "0001-01-01T00:00:00Z", "duration": "5m0s"}
1136 `
1137 actual := "\n" + buf.String()
1138 if expect != actual {
1139 t.Fatalf("JSON style marshal error: expect=[%s] actual=[%s]", expect, actual)
1140 }
1141 }
1142
1143 func TestEncoder_MarshalAnchor(t *testing.T) {
1144 type Host struct {
1145 Hostname string
1146 Username string
1147 Password string
1148 }
1149 type HostDecl struct {
1150 Host *Host `yaml:",anchor"`
1151 }
1152 type Queue struct {
1153 Name string `yaml:","`
1154 *Host `yaml:",alias"`
1155 }
1156 var doc struct {
1157 Hosts []*HostDecl `yaml:"hosts"`
1158 Queues []*Queue `yaml:"queues"`
1159 }
1160 host1 := &Host{
1161 Hostname: "host1.example.com",
1162 Username: "userA",
1163 Password: "pass1",
1164 }
1165 host2 := &Host{
1166 Hostname: "host2.example.com",
1167 Username: "userB",
1168 Password: "pass2",
1169 }
1170 doc.Hosts = []*HostDecl{
1171 {
1172 Host: host1,
1173 },
1174 {
1175 Host: host2,
1176 },
1177 }
1178 doc.Queues = []*Queue{
1179 {
1180 Name: "queue",
1181 Host: host1,
1182 }, {
1183 Name: "queue2",
1184 Host: host2,
1185 },
1186 }
1187 hostIdx := 1
1188 opt := yaml.MarshalAnchor(func(anchor *ast.AnchorNode, value interface{}) error {
1189 if _, ok := value.(*Host); ok {
1190 nameNode, _ := anchor.Name.(*ast.StringNode)
1191 nameNode.Value = fmt.Sprintf("host%d", hostIdx)
1192 hostIdx++
1193 }
1194 return nil
1195 })
1196
1197 var buf bytes.Buffer
1198 if err := yaml.NewEncoder(&buf, opt).Encode(doc); err != nil {
1199 t.Fatalf("%+v", err)
1200 }
1201 expect := `
1202 hosts:
1203 - host: &host1
1204 hostname: host1.example.com
1205 username: userA
1206 password: pass1
1207 - host: &host2
1208 hostname: host2.example.com
1209 username: userB
1210 password: pass2
1211 queues:
1212 - name: queue
1213 host: *host1
1214 - name: queue2
1215 host: *host2
1216 `
1217 if "\n"+buf.String() != expect {
1218 t.Fatalf("unexpected output. %s", buf.String())
1219 }
1220 }
1221
1222 type useJSONMarshalerTest struct{}
1223
1224 func (t useJSONMarshalerTest) MarshalJSON() ([]byte, error) {
1225 return []byte(`{"a":[1, 2, 3]}`), nil
1226 }
1227
1228 func TestEncoder_UseJSONMarshaler(t *testing.T) {
1229 got, err := yaml.MarshalWithOptions(useJSONMarshalerTest{}, yaml.UseJSONMarshaler())
1230 if err != nil {
1231 t.Fatal(err)
1232 }
1233 expected := `
1234 a:
1235 - 1
1236 - 2
1237 - 3
1238 `
1239 if expected != "\n"+string(got) {
1240 t.Fatalf("failed to use json marshaler. expected [%q] but got [%q]", expected, string(got))
1241 }
1242 }
1243
1244 func TestEncoder_CustomMarshaler(t *testing.T) {
1245 t.Run("override struct type", func(t *testing.T) {
1246 type T struct {
1247 Foo string `yaml:"foo"`
1248 }
1249 b, err := yaml.MarshalWithOptions(&T{Foo: "bar"}, yaml.CustomMarshaler[T](func(v T) ([]byte, error) {
1250 return []byte(`"override"`), nil
1251 }))
1252 if err != nil {
1253 t.Fatal(err)
1254 }
1255 if !bytes.Equal(b, []byte("\"override\"\n")) {
1256 t.Fatalf("failed to switch to custom marshaler. got: %q", b)
1257 }
1258 })
1259 t.Run("override bytes type", func(t *testing.T) {
1260 type T struct {
1261 Foo []byte `yaml:"foo"`
1262 }
1263 b, err := yaml.MarshalWithOptions(&T{Foo: []byte("bar")}, yaml.CustomMarshaler[[]byte](func(v []byte) ([]byte, error) {
1264 if !bytes.Equal(v, []byte("bar")) {
1265 t.Fatalf("failed to get src buffer: %q", v)
1266 }
1267 return []byte(`override`), nil
1268 }))
1269 if err != nil {
1270 t.Fatal(err)
1271 }
1272 if !bytes.Equal(b, []byte("foo: override\n")) {
1273 t.Fatalf("failed to switch to custom marshaler. got: %q", b)
1274 }
1275 })
1276 }
1277
1278 func TestEncoder_MultipleDocuments(t *testing.T) {
1279 var buf bytes.Buffer
1280 enc := yaml.NewEncoder(&buf)
1281 if err := enc.Encode(1); err != nil {
1282 t.Fatalf("failed to encode: %s", err)
1283 }
1284 if err := enc.Encode(2); err != nil {
1285 t.Fatalf("failed to encode: %s", err)
1286 }
1287 if actual, expect := buf.String(), "1\n---\n2\n"; actual != expect {
1288 t.Errorf("expect:\n%s\nactual\n%s\n", expect, actual)
1289 }
1290 }
1291
1292 func Example_Marshal_Node() {
1293 type T struct {
1294 Text ast.Node `yaml:"text"`
1295 }
1296 stringNode, err := yaml.ValueToNode("node example")
1297 if err != nil {
1298 panic(err)
1299 }
1300 bytes, err := yaml.Marshal(T{Text: stringNode})
1301 if err != nil {
1302 panic(err)
1303 }
1304 fmt.Println(string(bytes))
1305 // OUTPUT:
1306 // text: node example
1307 }
1308
1309 func Example_Marshal_ExplicitAnchorAlias() {
1310 type T struct {
1311 A int
1312 B string
1313 }
1314 var v struct {
1315 C *T `yaml:"c,anchor=x"`
1316 D *T `yaml:"d,alias=x"`
1317 }
1318 v.C = &T{A: 1, B: "hello"}
1319 v.D = v.C
1320 bytes, err := yaml.Marshal(v)
1321 if err != nil {
1322 panic(err)
1323 }
1324 fmt.Println(string(bytes))
1325 // OUTPUT:
1326 // c: &x
1327 // a: 1
1328 // b: hello
1329 // d: *x
1330 }
1331
1332 func Example_Marshal_ImplicitAnchorAlias() {
1333 type T struct {
1334 I int
1335 S string
1336 }
1337 var v struct {
1338 A *T `yaml:"a,anchor"`
1339 B *T `yaml:"b,anchor"`
1340 C *T `yaml:"c,alias"`
1341 D *T `yaml:"d,alias"`
1342 }
1343 v.A = &T{I: 1, S: "hello"}
1344 v.B = &T{I: 2, S: "world"}
1345 v.C = v.A // C has same pointer address to A
1346 v.D = v.B // D has same pointer address to B
1347 bytes, err := yaml.Marshal(v)
1348 if err != nil {
1349 panic(err)
1350 }
1351 fmt.Println(string(bytes))
1352 // OUTPUT:
1353 // a: &a
1354 // i: 1
1355 // s: hello
1356 // b: &b
1357 // i: 2
1358 // s: world
1359 // c: *a
1360 // d: *b
1361 }
1362
1363 type tMarshal []string
1364
1365 func (t *tMarshal) MarshalYAML() ([]byte, error) {
1366 var buf bytes.Buffer
1367 buf.WriteString("tags:\n")
1368 for i, v := range *t {
1369 if i == 0 {
1370 fmt.Fprintf(&buf, "- %s\n", v)
1371 } else {
1372 fmt.Fprintf(&buf, " %s\n", v)
1373 }
1374 }
1375 return buf.Bytes(), nil
1376 }
1377 func Test_Marshaler(t *testing.T) {
1378 const expected = `- hello-world
1379 `
1380
1381 // sanity check
1382 var l []string
1383 if err := yaml.Unmarshal([]byte(expected), &l); err != nil {
1384 t.Fatalf("failed to parse string: %s", err)
1385 }
1386
1387 buf, err := yaml.Marshal(tMarshal{"hello-world"})
1388 if err != nil {
1389 t.Fatalf("failed to marshal: %s", err)
1390 }
1391
1392 if string(buf) != expected {
1393 t.Fatalf("expected '%s', got '%s'", expected, buf)
1394 }
1395
1396 t.Logf("%s", buf)
1397 }
1398
1399 type marshalContext struct{}
1400
1401 func (c *marshalContext) MarshalYAML(ctx context.Context) ([]byte, error) {
1402 v, ok := ctx.Value("k").(int)
1403 if !ok {
1404 return nil, fmt.Errorf("cannot get valid context")
1405 }
1406 if v != 1 {
1407 return nil, fmt.Errorf("cannot get valid context")
1408 }
1409 return []byte("1"), nil
1410 }
1411
1412 func Test_MarshalerContext(t *testing.T) {
1413 ctx := context.WithValue(context.Background(), "k", 1)
1414 bytes, err := yaml.MarshalContext(ctx, &marshalContext{})
1415 if err != nil {
1416 t.Fatalf("%+v", err)
1417 }
1418 if string(bytes) != "1\n" {
1419 t.Fatalf("failed marshal: %q", string(bytes))
1420 }
1421 }
1422
1423 type SlowMarshaler struct {
1424 A string
1425 B int
1426 }
1427 type FastMarshaler struct {
1428 A string
1429 B int
1430 }
1431 type TextMarshaler int64
1432 type TextMarshalerContainer struct {
1433 Field TextMarshaler `yaml:"field"`
1434 }
1435
1436 func (v SlowMarshaler) MarshalYAML() ([]byte, error) {
1437 var buf bytes.Buffer
1438 buf.WriteString("tags:\n")
1439 buf.WriteString("- slow-marshaler\n")
1440 buf.WriteString("a: " + v.A + "\n")
1441 buf.WriteString("b: " + strconv.FormatInt(int64(v.B), 10) + "\n")
1442 return buf.Bytes(), nil
1443 }
1444
1445 func (v FastMarshaler) MarshalYAML() (interface{}, error) {
1446 return yaml.MapSlice{
1447 {"tags", []string{"fast-marshaler"}},
1448 {"a", v.A},
1449 {"b", v.B},
1450 }, nil
1451 }
1452
1453 func (t TextMarshaler) MarshalText() ([]byte, error) {
1454 return []byte(strconv.FormatInt(int64(t), 8)), nil
1455 }
1456
1457 func Example_MarshalYAML() {
1458 var slow SlowMarshaler
1459 slow.A = "Hello slow poke"
1460 slow.B = 100
1461 buf, err := yaml.Marshal(slow)
1462 if err != nil {
1463 panic(err.Error())
1464 }
1465
1466 fmt.Println(string(buf))
1467
1468 var fast FastMarshaler
1469 fast.A = "Hello speed demon"
1470 fast.B = 100
1471 buf, err = yaml.Marshal(fast)
1472 if err != nil {
1473 panic(err.Error())
1474 }
1475
1476 fmt.Println(string(buf))
1477
1478 text := TextMarshalerContainer{
1479 Field: 11,
1480 }
1481 buf, err = yaml.Marshal(text)
1482 if err != nil {
1483 panic(err.Error())
1484 }
1485
1486 fmt.Println(string(buf))
1487 // OUTPUT:
1488 // tags:
1489 // - slow-marshaler
1490 // a: Hello slow poke
1491 // b: 100
1492 //
1493 // tags:
1494 // - fast-marshaler
1495 // a: Hello speed demon
1496 // b: 100
1497 //
1498 // field: 13
1499 }
1500
1501 func TestIssue356(t *testing.T) {
1502 tests := map[string]struct {
1503 in string
1504 }{
1505 "content on first line": {
1506 in: `args:
1507 - |
1508
1509 key:
1510 nest1: something
1511 nest2:
1512 nest2a: b
1513 `,
1514 },
1515 "empty first line": {
1516 in: `args:
1517 - |
1518
1519 key:
1520 nest1: something
1521 nest2:
1522 nest2a: b
1523 `,
1524 },
1525 }
1526
1527 for name, test := range tests {
1528 t.Run(name, func(t *testing.T) {
1529 f, err := parser.ParseBytes([]byte(test.in), 0)
1530 if err != nil {
1531 t.Fatalf("parse: %v", err)
1532 }
1533 got := f.String()
1534 if test.in != got {
1535 t.Fatalf("failed to encode.\nexpected:\n%s\nbut got:\n%s\n", test.in, got)
1536 }
1537 })
1538 }
1539 }
1540
1541 func TestMarshalIndentWithMultipleText(t *testing.T) {
1542 t.Run("depth1", func(t *testing.T) {
1543 b, err := yaml.MarshalWithOptions(map[string]interface{}{
1544 "key": []string{`line1
1545 line2
1546 line3`},
1547 }, yaml.Indent(2))
1548 if err != nil {
1549 t.Fatal(err)
1550 }
1551 got := string(b)
1552 expected := `key:
1553 - |-
1554 line1
1555 line2
1556 line3
1557 `
1558 if expected != got {
1559 t.Fatalf("failed to encode.\nexpected:\n%s\nbut got:\n%s\n", expected, got)
1560 }
1561 })
1562 t.Run("depth2", func(t *testing.T) {
1563 b, err := yaml.MarshalWithOptions(map[string]interface{}{
1564 "key": map[string]interface{}{
1565 "key2": []string{`line1
1566 line2
1567 line3`},
1568 },
1569 }, yaml.Indent(2))
1570 if err != nil {
1571 t.Fatal(err)
1572 }
1573 got := string(b)
1574 expected := `key:
1575 key2:
1576 - |-
1577 line1
1578 line2
1579 line3
1580 `
1581 if expected != got {
1582 t.Fatalf("failed to encode.\nexpected:\n%s\nbut got:\n%s\n", expected, got)
1583 }
1584 })
1585 }
1586
1587 type bytesMarshaler struct{}
1588
1589 func (b *bytesMarshaler) MarshalYAML() ([]byte, error) {
1590 return yaml.Marshal(map[string]interface{}{"d": "foo"})
1591 }
1592
1593 func TestBytesMarshaler(t *testing.T) {
1594 b, err := yaml.Marshal(map[string]interface{}{
1595 "a": map[string]interface{}{
1596 "b": map[string]interface{}{
1597 "c": &bytesMarshaler{},
1598 },
1599 },
1600 })
1601 if err != nil {
1602 t.Fatal(err)
1603 }
1604 expected := `
1605 a:
1606 b:
1607 c:
1608 d: foo
1609 `
1610 got := "\n" + string(b)
1611 if expected != got {
1612 t.Fatalf("failed to encode. expected %s but got %s", expected, got)
1613 }
1614 }
1615
1616 type customMapSliceOneItemMarshaler struct{}
1617
1618 func (m *customMapSliceOneItemMarshaler) MarshalYAML() ([]byte, error) {
1619 var v yaml.MapSlice
1620 v = append(v, yaml.MapItem{"a", "b"})
1621 return yaml.Marshal(v)
1622 }
1623
1624 type customMapSliceTwoItemMarshaler struct{}
1625
1626 func (m *customMapSliceTwoItemMarshaler) MarshalYAML() ([]byte, error) {
1627 var v yaml.MapSlice
1628 v = append(v, yaml.MapItem{"a", "b"})
1629 v = append(v, yaml.MapItem{"b", "c"})
1630 return yaml.Marshal(v)
1631 }
1632
1633 func TestCustomMapSliceMarshaler(t *testing.T) {
1634 type T struct {
1635 A *customMapSliceOneItemMarshaler `yaml:"a"`
1636 B *customMapSliceTwoItemMarshaler `yaml:"b"`
1637 }
1638 b, err := yaml.Marshal(&T{
1639 A: &customMapSliceOneItemMarshaler{},
1640 B: &customMapSliceTwoItemMarshaler{},
1641 })
1642 if err != nil {
1643 t.Fatal(err)
1644 }
1645 expected := `
1646 a:
1647 a: b
1648 b:
1649 a: b
1650 b: c
1651 `
1652 got := "\n" + string(b)
1653 if expected != got {
1654 t.Fatalf("failed to encode. expected %s but got %s", expected, got)
1655 }
1656 }