Debian Codegraph @

encode_test.go

raw symbols SCIP
1 package yaml_test
2
3 import (
4 "bytes"
5 "context"
6 "errors"
7 "fmt"
8 "math"
9 "net/netip"
10 "reflect"
11 "strconv"
12 "strings"
13 "testing"
14 "time"
15 "unsafe"
16
17 "github.com/goccy/go-yaml"
18 "github.com/goccy/go-yaml/ast"
19 "github.com/goccy/go-yaml/parser"
20 )
21
22 var zero = 0
23 var emptyStr = ""
24
25 type TestTextMarshaler string
26
27 func (t TestTextMarshaler) MarshalText() ([]byte, error) {
28 return []byte(t), nil
29 }
30
31 type TestTextUnmarshalerContainer struct {
32 V TestTextMarshaler
33 }
34
35 func TestEncoder(t *testing.T) {
36 tests := []struct {
37 source string
38 value interface{}
39 options []yaml.EncodeOption
40 }{
41 {
42 "null\n",
43 (*struct{})(nil),
44 nil,
45 },
46 {
47 "v: hi\n",
48 map[string]string{"v": "hi"},
49 nil,
50 },
51 {
52 "v: \"true\"\n",
53 map[string]string{"v": "true"},
54 nil,
55 },
56 {
57 "v: \"false\"\n",
58 map[string]string{"v": "false"},
59 nil,
60 },
61 {
62 "v: true\n",
63 map[string]interface{}{"v": true},
64 nil,
65 },
66 {
67 "v: false\n",
68 map[string]bool{"v": false},
69 nil,
70 },
71 {
72 "v: 10\n",
73 map[string]int{"v": 10},
74 nil,
75 },
76 {
77 "v: -10\n",
78 map[string]int{"v": -10},
79 nil,
80 },
81 {
82 "v: 4294967296\n",
83 map[string]int64{"v": int64(4294967296)},
84 nil,
85 },
86 {
87 "v: 0.1\n",
88 map[string]interface{}{"v": 0.1},
89 nil,
90 },
91 {
92 "v: 0.99\n",
93 map[string]float32{"v": 0.99},
94 nil,
95 },
96 {
97 "v: 1e-06\n",
98 map[string]float32{"v": 1e-06},
99 nil,
100 },
101 {
102 "v: 1e-06\n",
103 map[string]float64{"v": 0.000001},
104 nil,
105 },
106 {
107 "v: 0.123456789\n",
108 map[string]float64{"v": 0.123456789},
109 nil,
110 },
111 {
112 "v: -0.1\n",
113 map[string]float64{"v": -0.1},
114 nil,
115 },
116 {
117 "v: 1.0\n",
118 map[string]float64{"v": 1.0},
119 nil,
120 },
121 {
122 "v: 1e+06\n",
123 map[string]float64{"v": 1000000},
124 nil,
125 },
126 {
127 "v: 1e-06\n",
128 map[string]float64{"v": 0.000001},
129 nil,
130 },
131 {
132 "v: 1e-06\n",
133 map[string]float64{"v": 1e-06},
134 nil,
135 },
136 {
137 "v: .inf\n",
138 map[string]interface{}{"v": math.Inf(0)},
139 nil,
140 },
141 {
142 "v: -.inf\n",
143 map[string]interface{}{"v": math.Inf(-1)},
144 nil,
145 },
146 {
147 "v: .nan\n",
148 map[string]interface{}{"v": math.NaN()},
149 nil,
150 },
151 {
152 "v: null\n",
153 map[string]interface{}{"v": nil},
154 nil,
155 },
156 {
157 "v: \"\"\n",
158 map[string]string{"v": ""},
159 nil,
160 },
161 {
162 "v:\n- A\n- B\n",
163 map[string][]string{"v": {"A", "B"}},
164 nil,
165 },
166 {
167 "v:\n - A\n - B\n",
168 map[string][]string{"v": {"A", "B"}},
169 []yaml.EncodeOption{
170 yaml.IndentSequence(true),
171 },
172 },
173 {
174 "v:\n- A\n- B\n",
175 map[string][2]string{"v": {"A", "B"}},
176 nil,
177 },
178 {
179 "v:\n - A\n - B\n",
180 map[string][2]string{"v": {"A", "B"}},
181 []yaml.EncodeOption{
182 yaml.IndentSequence(true),
183 },
184 },
185 {
186 "a: \"-\"\n",
187 map[string]string{"a": "-"},
188 nil,
189 },
190 {
191 "123\n",
192 123,
193 nil,
194 },
195 {
196 "hello: world\n",
197 map[string]string{"hello": "world"},
198 nil,
199 },
200 {
201 "hello: |\n hello\n world\n",
202 map[string]string{"hello": "hello\nworld\n"},
203 nil,
204 },
205 {
206 "hello: |-\n hello\n world\n",
207 map[string]string{"hello": "hello\nworld"},
208 nil,
209 },
210 {
211 "hello: |+\n hello\n world\n\n",
212 map[string]string{"hello": "hello\nworld\n\n"},
213 nil,
214 },
215 {
216 "hello:\n hello: |\n hello\n world\n",
217 map[string]map[string]string{"hello": {"hello": "hello\nworld\n"}},
218 nil,
219 },
220 {
221 "hello: |\r hello\r world\n",
222 map[string]string{"hello": "hello\rworld\r"},
223 nil,
224 },
225 {
226 "hello: |\r\n hello\r\n world\n",
227 map[string]string{"hello": "hello\r\nworld\r\n"},
228 nil,
229 },
230 {
231 "v: |-\n username: hello\n password: hello123\n",
232 map[string]interface{}{"v": "username: hello\npassword: hello123"},
233 []yaml.EncodeOption{
234 yaml.UseLiteralStyleIfMultiline(true),
235 },
236 },
237 {
238 "v: |-\n # comment\n username: hello\n password: hello123\n",
239 map[string]interface{}{"v": "# comment\nusername: hello\npassword: hello123"},
240 []yaml.EncodeOption{
241 yaml.UseLiteralStyleIfMultiline(true),
242 },
243 },
244 {
245 "v: \"# comment\\nusername: hello\\npassword: hello123\"\n",
246 map[string]interface{}{"v": "# comment\nusername: hello\npassword: hello123"},
247 []yaml.EncodeOption{
248 yaml.UseLiteralStyleIfMultiline(false),
249 },
250 },
251 {
252 "v:\n- A\n- 1\n- B:\n - 2\n - 3\n",
253 map[string]interface{}{
254 "v": []interface{}{
255 "A",
256 1,
257 map[string][]int{
258 "B": {2, 3},
259 },
260 },
261 },
262 nil,
263 },
264 {
265 "v:\n - A\n - 1\n - B:\n - 2\n - 3\n - 2\n",
266 map[string]interface{}{
267 "v": []interface{}{
268 "A",
269 1,
270 map[string][]int{
271 "B": {2, 3},
272 },
273 2,
274 },
275 },
276 []yaml.EncodeOption{
277 yaml.IndentSequence(true),
278 },
279 },
280 {
281 "a:\n b: c\n",
282 map[string]interface{}{
283 "a": map[string]string{
284 "b": "c",
285 },
286 },
287 nil,
288 },
289 {
290 "t2: \"2018-01-09T10:40:47Z\"\nt4: \"2098-01-09T10:40:47Z\"\n",
291 map[string]string{
292 "t2": "2018-01-09T10:40:47Z",
293 "t4": "2098-01-09T10:40:47Z",
294 },
295 nil,
296 },
297 {
298 "a:\n b: c\n d: e\n",
299 map[string]interface{}{
300 "a": map[string]string{
301 "b": "c",
302 "d": "e",
303 },
304 },
305 nil,
306 },
307 {
308 "a: 3s\n",
309 map[string]string{
310 "a": "3s",
311 },
312 nil,
313 },
314 {
315 "a: <foo>\n",
316 map[string]string{"a": "<foo>"},
317 nil,
318 },
319 {
320 "a: \"1:1\"\n",
321 map[string]string{"a": "1:1"},
322 nil,
323 },
324 {
325 "a: 1.2.3.4\n",
326 map[string]string{"a": "1.2.3.4"},
327 nil,
328 },
329 {
330 "a: \"b: c\"\n",
331 map[string]string{"a": "b: c"},
332 nil,
333 },
334 {
335 "a: \"Hello #comment\"\n",
336 map[string]string{"a": "Hello #comment"},
337 nil,
338 },
339 {
340 "a: \" b\"\n",
341 map[string]string{"a": " b"},
342 nil,
343 },
344 {
345 "a: \"b \"\n",
346 map[string]string{"a": "b "},
347 nil,
348 },
349 {
350 "a: \" b \"\n",
351 map[string]string{"a": " b "},
352 nil,
353 },
354 {
355 "a: \"`b` c\"\n",
356 map[string]string{"a": "`b` c"},
357 nil,
358 },
359 {
360 "a: 100.5\n",
361 map[string]interface{}{
362 "a": 100.5,
363 },
364 nil,
365 },
366 {
367 "a: \"\\\\0\"\n",
368 map[string]string{"a": "\\0"},
369 nil,
370 },
371 {
372 "a: 1\nb: 2\nc: 3\nd: 4\nsub:\n e: 5\n",
373 map[string]interface{}{
374 "a": 1,
375 "b": 2,
376 "c": 3,
377 "d": 4,
378 "sub": map[string]int{
379 "e": 5,
380 },
381 },
382 nil,
383 },
384 {
385 "a: 1\nb: []\n",
386 struct {
387 A int
388 B []string
389 }{
390 1, ([]string)(nil),
391 },
392 nil,
393 },
394 {
395 "a: 1\nb: []\n",
396 struct {
397 A int
398 B []string
399 }{
400 1, []string{},
401 },
402 nil,
403 },
404 {
405 "a: {}\n",
406 struct {
407 A map[string]interface{}
408 }{
409 map[string]interface{}{},
410 },
411 nil,
412 },
413 {
414 "a: b\nc: d\n",
415 struct {
416 A string
417 C string `yaml:"c"`
418 }{
419 "b", "d",
420 },
421 nil,
422 },
423 {
424 "a: 1\n",
425 struct {
426 A int
427 B int `yaml:"-"`
428 }{
429 1, 0,
430 },
431 nil,
432 },
433 {
434 "a: \"\"\n",
435 struct {
436 A string
437 }{
438 "",
439 },
440 nil,
441 },
442 {
443 "a: null\n",
444 struct {
445 A *string
446 }{
447 nil,
448 },
449 nil,
450 },
451 {
452 "a: \"\"\n",
453 struct {
454 A *string
455 }{
456 &emptyStr,
457 },
458 nil,
459 },
460 {
461 "a: null\n",
462 struct {
463 A *int
464 }{
465 nil,
466 },
467 nil,
468 },
469 {
470 "a: 0\n",
471 struct {
472 A *int
473 }{
474 &zero,
475 },
476 nil,
477 },
478
479 // Omitempty flag.
480 {
481 "a: 1\n",
482 struct {
483 A int `yaml:"a,omitempty"`
484 B int `yaml:"b,omitempty"`
485 }{1, 0},
486 nil,
487 },
488 {
489 "{}\n",
490 struct {
491 A int `yaml:"a,omitempty"`
492 B int `yaml:"b,omitempty"`
493 }{0, 0},
494 nil,
495 },
496 {
497 "a:\n \"y\": \"\"\n",
498 struct {
499 A *struct {
500 X string `yaml:"x,omitempty"`
501 Y string
502 }
503 }{&struct {
504 X string `yaml:"x,omitempty"`
505 Y string
506 }{}},
507 nil,
508 },
509 {
510 "a: {}\n",
511 struct {
512 A *struct {
513 X string `yaml:"x,omitempty"`
514 Y string `yaml:"y,omitempty"`
515 }
516 }{&struct {
517 X string `yaml:"x,omitempty"`
518 Y string `yaml:"y,omitempty"`
519 }{}},
520 nil,
521 },
522 {
523 "a: {x: 1}\n",
524 struct {
525 A *struct{ X, y int } `yaml:"a,omitempty,flow"`
526 }{&struct{ X, y int }{1, 2}},
527 nil,
528 },
529 {
530 "{}\n",
531 struct {
532 A *struct{ X, y int } `yaml:"a,omitempty,flow"`
533 }{nil},
534 nil,
535 },
536 {
537 "a: {x: 0}\n",
538 struct {
539 A *struct{ X, y int } `yaml:"a,omitempty,flow"`
540 }{&struct{ X, y int }{}},
541 nil,
542 },
543 {
544 "a: {x: 1}\n",
545 struct {
546 A struct{ X, y int } `yaml:"a,omitempty,flow"`
547 }{struct{ X, y int }{1, 2}},
548 nil,
549 },
550 {
551 "{}\n",
552 struct {
553 A struct{ X, y int } `yaml:"a,omitempty,flow"`
554 }{struct{ X, y int }{0, 1}},
555 nil,
556 },
557 {
558 "a: 1.0\n",
559 struct {
560 A float64 `yaml:"a,omitempty"`
561 B float64 `yaml:"b,omitempty"`
562 }{1, 0},
563 nil,
564 },
565 {
566 "a: 1\n",
567 struct {
568 A int
569 B []string `yaml:"b,omitempty"`
570 }{
571 1, []string{},
572 },
573 nil,
574 },
575 // Highlighting differences of go-yaml omitempty vs std encoding/json
576 // omitempty. Encoding/json will emit the following fields: https://go.dev/play/p/VvNpdM0GD4d
577 {
578 "{}\n",
579 struct {
580 // This type has a custom IsZero method.
581 A netip.Addr `yaml:"a,omitempty"`
582 B struct{ X, y int } `yaml:"b,omitempty"`
583 }{},
584 nil,
585 },
586
587 // omitzero flag.
588 {
589 "a: 1\n",
590 struct {
591 A int `yaml:"a,omitzero"`
592 B int `yaml:"b,omitzero"`
593 }{1, 0},
594 nil,
595 },
596 {
597 "{}\n",
598 struct {
599 A int `yaml:"a,omitzero"`
600 B int `yaml:"b,omitzero"`
601 }{0, 0},
602 nil,
603 },
604 {
605 "a:\n \"y\": \"\"\n",
606 struct {
607 A *struct {
608 X string `yaml:"x,omitzero"`
609 Y string
610 }
611 }{&struct {
612 X string `yaml:"x,omitzero"`
613 Y string
614 }{}},
615 nil,
616 },
617 {
618 "a: {}\n",
619 struct {
620 A *struct {
621 X string `yaml:"x,omitzero"`
622 Y string `yaml:"y,omitzero"`
623 }
624 }{&struct {
625 X string `yaml:"x,omitzero"`
626 Y string `yaml:"y,omitzero"`
627 }{}},
628 nil,
629 },
630 {
631 "a: {x: 1}\n",
632 struct {
633 A *struct{ X, y int } `yaml:"a,omitzero,flow"`
634 }{&struct{ X, y int }{1, 2}},
635 nil,
636 },
637 {
638 "{}\n",
639 struct {
640 A *struct{ X, y int } `yaml:"a,omitzero,flow"`
641 }{nil},
642 nil,
643 },
644 {
645 "a: {x: 0}\n",
646 struct {
647 A *struct{ X, y int } `yaml:"a,omitzero,flow"`
648 }{&struct{ X, y int }{}},
649 nil,
650 },
651 {
652 "a: {x: 1}\n",
653 struct {
654 A struct{ X, y int } `yaml:"a,omitzero,flow"`
655 }{struct{ X, y int }{1, 2}},
656 nil,
657 },
658 {
659 "{}\n",
660 struct {
661 A struct{ X, y int } `yaml:"a,omitzero,flow"`
662 }{struct{ X, y int }{0, 1}},
663 nil,
664 },
665 {
666 "a: 1.0\n",
667 struct {
668 A float64 `yaml:"a,omitzero"`
669 B float64 `yaml:"b,omitzero"`
670 }{1, 0},
671 nil,
672 },
673 {
674 "a: 1\nb: []\n",
675 struct {
676 A int
677 B []string `yaml:"b,omitzero"`
678 }{
679 1, []string{},
680 },
681 nil,
682 },
683 {
684 "{}\n",
685 struct {
686 A netip.Addr `yaml:"a,omitzero"`
687 B struct{ X, y int } `yaml:"b,omitzero"`
688 }{},
689 nil,
690 },
691
692 // OmitEmpty global option.
693 {
694 "a: 1\n",
695 struct {
696 A int
697 B int `yaml:"b,omitempty"`
698 }{1, 0},
699 []yaml.EncodeOption{
700 yaml.OmitEmpty(),
701 },
702 },
703 {
704 "{}\n",
705 struct {
706 A int
707 B int `yaml:"b,omitempty"`
708 }{0, 0},
709 []yaml.EncodeOption{
710 yaml.OmitEmpty(),
711 },
712 },
713 {
714 "a: \"\"\nb: {}\n",
715 struct {
716 A netip.Addr `yaml:"a"`
717 B struct{ X, y int } `yaml:"b"`
718 }{},
719 []yaml.EncodeOption{
720 yaml.OmitEmpty(),
721 },
722 },
723
724 // OmitZero global option.
725 {
726 "a: 1\n",
727 struct {
728 A int
729 B int
730 }{1, 0},
731 []yaml.EncodeOption{
732 yaml.OmitZero(),
733 },
734 },
735 {
736 "{}\n",
737 struct {
738 A int
739 B int
740 }{0, 0},
741 []yaml.EncodeOption{
742 yaml.OmitZero(),
743 },
744 },
745 {
746 "{}\n",
747 struct {
748 A netip.Addr `yaml:"a"`
749 B struct{ X, y int } `yaml:"b"`
750 }{},
751 []yaml.EncodeOption{
752 yaml.OmitZero(),
753 },
754 },
755
756 // Flow flag.
757 {
758 "a: [1, 2]\n",
759 struct {
760 A []int `yaml:"a,flow"`
761 }{[]int{1, 2}},
762 nil,
763 },
764 {
765 "a: {b: c, d: e}\n",
766 &struct {
767 A map[string]string `yaml:"a,flow"`
768 }{map[string]string{"b": "c", "d": "e"}},
769 nil,
770 },
771 {
772 "a: {b: c, d: e}\n",
773 struct {
774 A struct {
775 B, D string
776 } `yaml:"a,flow"`
777 }{struct{ B, D string }{"c", "e"}},
778 nil,
779 },
780 // Quoting in flow mode
781 {
782 `a: [b, "c,d", e]` + "\n",
783 struct {
784 A []string `yaml:"a,flow"`
785 }{[]string{"b", "c,d", "e"}},
786 []yaml.EncodeOption{
787 yaml.UseSingleQuote(false),
788 },
789 },
790 {
791 `a: [b, "c]", d]` + "\n",
792 struct {
793 A []string `yaml:"a,flow"`
794 }{[]string{"b", "c]", "d"}},
795 []yaml.EncodeOption{
796 yaml.UseSingleQuote(false),
797 },
798 },
799 {
800 `a: [b, "c}", d]` + "\n",
801 struct {
802 A []string `yaml:"a,flow"`
803 }{[]string{"b", "c}", "d"}},
804 []yaml.EncodeOption{
805 yaml.UseSingleQuote(false),
806 },
807 },
808 {
809 `a: [b, "c\"", d]` + "\n",
810 struct {
811 A []string `yaml:"a,flow"`
812 }{[]string{"b", `c"`, "d"}},
813 []yaml.EncodeOption{
814 yaml.UseSingleQuote(false),
815 },
816 },
817 {
818 `a: [b, "c'", d]` + "\n",
819 struct {
820 A []string `yaml:"a,flow"`
821 }{[]string{"b", "c'", "d"}},
822 []yaml.EncodeOption{
823 yaml.UseSingleQuote(false),
824 },
825 },
826 // No quoting in non-flow mode
827 {
828 "a:\n- b\n- c,d\n- e\n",
829 struct {
830 A []string `yaml:"a"`
831 }{[]string{"b", "c,d", "e"}},
832 nil,
833 },
834 {
835 `a: [b, "c]", d]` + "\n",
836 struct {
837 A []string `yaml:"a,flow"`
838 }{[]string{"b", "c]", "d"}},
839 nil,
840 },
841 {
842 `a: [b, "c}", d]` + "\n",
843 struct {
844 A []string `yaml:"a,flow"`
845 }{[]string{"b", "c}", "d"}},
846 nil,
847 },
848 {
849 `a: [b, "c\"", d]` + "\n",
850 struct {
851 A []string `yaml:"a,flow"`
852 }{[]string{"b", `c"`, "d"}},
853 nil,
854 },
855 {
856 `a: [b, "c'", d]` + "\n",
857 struct {
858 A []string `yaml:"a,flow"`
859 }{[]string{"b", "c'", "d"}},
860 nil,
861 },
862
863 // Multi bytes
864 {
865 "v: あいうえお\nv2: かきくけこ\n",
866 map[string]string{"v": "あいうえお", "v2": "かきくけこ"},
867 nil,
868 },
869
870 // time value
871 {
872 "v: 0001-01-01T00:00:00Z\n",
873 map[string]time.Time{"v": {}},
874 nil,
875 },
876 {
877 "v: 0001-01-01T00:00:00Z\n",
878 map[string]*time.Time{"v": {}},
879 nil,
880 },
881 {
882 "v: null\n",
883 map[string]*time.Time{"v": nil},
884 nil,
885 },
886 {
887 "v: 30s\n",
888 map[string]time.Duration{"v": 30 * time.Second},
889 nil,
890 },
891 {
892 "v: 30s\n",
893 map[string]*time.Duration{"v": ptr(30 * time.Second)},
894 nil,
895 },
896 {
897 "v: null\n",
898 map[string]*time.Duration{"v": nil},
899 nil,
900 },
901 {
902 "v: test\n",
903 TestTextUnmarshalerContainer{V: "test"},
904 nil,
905 },
906 {
907 "v: \"1\"\n",
908 TestTextUnmarshalerContainer{V: "1"},
909 nil,
910 },
911 {
912 "v: \"#\"\n",
913 TestTextUnmarshalerContainer{V: "#"},
914 nil,
915 },
916 // Quote style
917 {
918 `v: '''a''b'` + "\n",
919 map[string]string{"v": `'a'b`},
920 []yaml.EncodeOption{
921 yaml.UseSingleQuote(true),
922 },
923 },
924 {
925 `v: "'a'b"` + "\n",
926 map[string]string{"v": `'a'b`},
927 []yaml.EncodeOption{
928 yaml.UseSingleQuote(false),
929 },
930 },
931 {
932 `a: '\.yaml'` + "\n",
933 map[string]string{"a": `\.yaml`},
934 []yaml.EncodeOption{
935 yaml.UseSingleQuote(true),
936 },
937 },
938 }
939 for _, test := range tests {
940 t.Run(test.source, func(t *testing.T) {
941 var buf bytes.Buffer
942 enc := yaml.NewEncoder(&buf, test.options...)
943 if err := enc.Encode(test.value); err != nil {
944 t.Fatalf("%+v", err)
945 }
946 if test.source != buf.String() {
947 t.Fatalf("expect = [%s], actual = [%s]", test.source, buf.String())
948 }
949 })
950 }
951 }
952
953 func TestEncodeStructIncludeMap(t *testing.T) {
954 type U struct {
955 M map[string]string
956 }
957 type T struct {
958 A U
959 }
960 bytes, err := yaml.Marshal(T{
961 A: U{
962 M: map[string]string{"x": "y"},
963 },
964 })
965 if err != nil {
966 t.Fatalf("%+v", err)
967 }
968 expect := "a:\n m:\n x: \"y\"\n"
969 actual := string(bytes)
970 if actual != expect {
971 t.Fatalf("unexpected output. expect:[%s] actual:[%s]", expect, actual)
972 }
973 }
974
975 func TestEncodeDefinedTypeKeyMap(t *testing.T) {
976 type K string
977 type U struct {
978 M map[K]string
979 }
980 bytes, err := yaml.Marshal(U{
981 M: map[K]string{K("x"): "y"},
982 })
983 if err != nil {
984 t.Fatalf("%+v", err)
985 }
986 expect := "m:\n x: \"y\"\n"
987 actual := string(bytes)
988 if actual != expect {
989 t.Fatalf("unexpected output. expect:[%s] actual:[%s]", expect, actual)
990 }
991 }
992
993 func TestEncodeWithAnchorAndAlias(t *testing.T) {
994 var buf bytes.Buffer
995 enc := yaml.NewEncoder(&buf)
996 type T struct {
997 A int
998 B string
999 }
1000 var v struct {
1001 A *T `yaml:"a,anchor=c"`
1002 B *T `yaml:"b,alias=c"`
1003 }
1004 v.A = &T{A: 1, B: "hello"}
1005 v.B = v.A
1006 if err := enc.Encode(v); err != nil {
1007 t.Fatalf("%+v", err)
1008 }
1009 expect := "a: &c\n a: 1\n b: hello\nb: *c\n"
1010 if expect != buf.String() {
1011 t.Fatalf("expect = [%s], actual = [%s]", expect, buf.String())
1012 }
1013 }
1014
1015 func TestEncodeWithAutoAlias(t *testing.T) {
1016 var buf bytes.Buffer
1017 enc := yaml.NewEncoder(&buf)
1018 type T struct {
1019 I int
1020 S string
1021 }
1022 var v struct {
1023 A *T `yaml:"a,anchor=a"`
1024 B *T `yaml:"b,anchor=b"`
1025 C *T `yaml:"c"`
1026 D *T `yaml:"d"`
1027 }
1028 v.A = &T{I: 1, S: "hello"}
1029 v.B = &T{I: 2, S: "world"}
1030 v.C = v.A
1031 v.D = v.B
1032 if err := enc.Encode(v); err != nil {
1033 t.Fatalf("%+v", err)
1034 }
1035 expect := `a: &a
1036 i: 1
1037 s: hello
1038 b: &b
1039 i: 2
1040 s: world
1041 c: *a
1042 d: *b
1043 `
1044 if expect != buf.String() {
1045 t.Fatalf("expect = [%s], actual = [%s]", expect, buf.String())
1046 }
1047 }
1048
1049 func TestEncodeWithImplicitAnchorAndAlias(t *testing.T) {
1050 var buf bytes.Buffer
1051 enc := yaml.NewEncoder(&buf)
1052 type T struct {
1053 I int
1054 S string
1055 }
1056 var v struct {
1057 A *T `yaml:"a,anchor"`
1058 B *T `yaml:"b,anchor"`
1059 C *T `yaml:"c"`
1060 D *T `yaml:"d"`
1061 }
1062 v.A = &T{I: 1, S: "hello"}
1063 v.B = &T{I: 2, S: "world"}
1064 v.C = v.A
1065 v.D = v.B
1066 if err := enc.Encode(v); err != nil {
1067 t.Fatalf("%+v", err)
1068 }
1069 expect := `a: &a
1070 i: 1
1071 s: hello
1072 b: &b
1073 i: 2
1074 s: world
1075 c: *a
1076 d: *b
1077 `
1078 if expect != buf.String() {
1079 t.Fatalf("expect = [%s], actual = [%s]", expect, buf.String())
1080 }
1081 }
1082
1083 func TestEncodeWithMerge(t *testing.T) {
1084 type Person struct {
1085 *Person `yaml:",omitempty,inline"`
1086 Name string `yaml:",omitempty"`
1087 Age int `yaml:",omitempty"`
1088 }
1089 defaultPerson := &Person{
1090 Name: "John Smith",
1091 Age: 20,
1092 }
1093 people := []*Person{
1094 {
1095 Person: defaultPerson,
1096 Name: "Ken",
1097 Age: 10,
1098 },
1099 {
1100 Person: defaultPerson,
1101 },
1102 }
1103 var doc struct {
1104 Default *Person `yaml:"default,anchor"`
1105 People []*Person `yaml:"people"`
1106 }
1107 doc.Default = defaultPerson
1108 doc.People = people
1109 var buf bytes.Buffer
1110 enc := yaml.NewEncoder(&buf)
1111 if err := enc.Encode(doc); err != nil {
1112 t.Fatalf("%+v", err)
1113 }
1114 expect := `default: &default
1115 name: John Smith
1116 age: 20
1117 people:
1118 - <<: *default
1119 name: Ken
1120 age: 10
1121 - <<: *default
1122 `
1123 if expect != buf.String() {
1124 t.Fatalf("expect = [%s], actual = [%s]", expect, buf.String())
1125 }
1126 }
1127
1128 func TestEncodeWithNestedYAML(t *testing.T) {
1129 // Represents objects containing stringified YAML, and special chars
1130 tests := []struct {
1131 value interface{}
1132 // If true, expects a different result between when using forced literal style or not
1133 expectDifferent bool
1134 }{
1135 {
1136 value: map[string]interface{}{"v": "# comment\nname: hello\npassword: hello123\nspecial: \":ghost:\"\ntext: |\n nested multiline!"},
1137 expectDifferent: true,
1138 },
1139 {
1140 value: map[string]interface{}{"v": "# comment\nusername: hello\npassword: hello123"},
1141 expectDifferent: true,
1142 },
1143 {
1144 value: map[string]interface{}{"v": "# comment\n"},
1145 expectDifferent: true,
1146 },
1147 }
1148
1149 for _, test := range tests {
1150 yamlBytesForced, err := yaml.MarshalWithOptions(test.value, yaml.UseLiteralStyleIfMultiline(true))
1151 if err != nil {
1152 t.Fatalf("%+v", err)
1153 }
1154
1155 // Convert it back for proper equality testing
1156 var unmarshaled interface{}
1157
1158 if err := yaml.Unmarshal(yamlBytesForced, &unmarshaled); err != nil {
1159 t.Fatalf("%+v", err)
1160 }
1161
1162 if !reflect.DeepEqual(test.value, unmarshaled) {
1163 t.Fatalf("expected %v(%T). but actual %v(%T)", test.value, test.value, unmarshaled, unmarshaled)
1164 }
1165
1166 if test.expectDifferent {
1167 yamlBytesNotForced, err := yaml.MarshalWithOptions(test.value)
1168 if err != nil {
1169 t.Fatalf("%+v", err)
1170 }
1171
1172 if string(yamlBytesForced) == string(yamlBytesNotForced) {
1173 t.Fatalf("expected different strings when force literal style is not enabled. forced: %s, not forced: %s", string(yamlBytesForced), string(yamlBytesNotForced))
1174 }
1175 }
1176 }
1177 }
1178
1179 func TestEncoder_Inline(t *testing.T) {
1180 type base struct {
1181 A int
1182 B string
1183 }
1184 var buf bytes.Buffer
1185 enc := yaml.NewEncoder(&buf)
1186 if err := enc.Encode(struct {
1187 *base `yaml:",inline"`
1188 C bool
1189 }{
1190 base: &base{
1191 A: 1,
1192 B: "hello",
1193 },
1194 C: true,
1195 }); err != nil {
1196 t.Fatalf("%+v", err)
1197 }
1198 expect := `
1199 a: 1
1200 b: hello
1201 c: true
1202 `
1203 actual := "\n" + buf.String()
1204 if expect != actual {
1205 t.Fatalf("inline marshal error: expect=[%s] actual=[%s]", expect, actual)
1206 }
1207 }
1208
1209 func TestEncoder_InlineAndConflictKey(t *testing.T) {
1210 type base struct {
1211 A int
1212 B string
1213 }
1214 var buf bytes.Buffer
1215 enc := yaml.NewEncoder(&buf)
1216 if err := enc.Encode(struct {
1217 *base `yaml:",inline"`
1218 A int // conflict
1219 C bool
1220 }{
1221 base: &base{
1222 A: 1,
1223 B: "hello",
1224 },
1225 A: 0, // default value
1226 C: true,
1227 }); err != nil {
1228 t.Fatalf("%+v", err)
1229 }
1230 expect := `
1231 b: hello
1232 a: 0
1233 c: true
1234 `
1235 actual := "\n" + buf.String()
1236 if expect != actual {
1237 t.Fatalf("inline marshal error: expect=[%s] actual=[%s]", expect, actual)
1238 }
1239 }
1240
1241 func TestEncoder_InlineNil(t *testing.T) {
1242 type base struct {
1243 A int
1244 B string
1245 }
1246 var buf bytes.Buffer
1247 enc := yaml.NewEncoder(&buf)
1248 if err := enc.Encode(struct {
1249 *base `yaml:",inline"`
1250 C bool
1251 }{
1252 C: true,
1253 }); err != nil {
1254 t.Fatalf("%+v", err)
1255 }
1256 expect := `
1257 c: true
1258 `
1259 actual := "\n" + buf.String()
1260 if expect != actual {
1261 t.Fatalf("inline marshal error: expect=[%s] actual=[%s]", expect, actual)
1262 }
1263 }
1264
1265 func TestEncoder_Flow(t *testing.T) {
1266 var buf bytes.Buffer
1267 enc := yaml.NewEncoder(&buf, yaml.Flow(true))
1268 var v struct {
1269 A int
1270 B string
1271 C struct {
1272 D int
1273 E string
1274 }
1275 F []int
1276 }
1277 v.A = 1
1278 v.B = "hello"
1279 v.C.D = 3
1280 v.C.E = "world"
1281 v.F = []int{1, 2}
1282 if err := enc.Encode(v); err != nil {
1283 t.Fatalf("%+v", err)
1284 }
1285 expect := `
1286 {a: 1, b: hello, c: {d: 3, e: world}, f: [1, 2]}
1287 `
1288 actual := "\n" + buf.String()
1289 if expect != actual {
1290 t.Fatalf("flow style marshal error: expect=[%s] actual=[%s]", expect, actual)
1291 }
1292 }
1293
1294 func TestEncoder_FlowRecursive(t *testing.T) {
1295 var v struct {
1296 M map[string][]int `yaml:",flow"`
1297 }
1298 v.M = map[string][]int{
1299 "test": {1, 2, 3},
1300 }
1301 var buf bytes.Buffer
1302 if err := yaml.NewEncoder(&buf).Encode(v); err != nil {
1303 t.Fatalf("%+v", err)
1304 }
1305 expect := `
1306 m: {test: [1, 2, 3]}
1307 `
1308 actual := "\n" + buf.String()
1309 if expect != actual {
1310 t.Fatalf("flow style marshal error: expect=[%s] actual=[%s]", expect, actual)
1311 }
1312 }
1313
1314 func TestEncoder_JSON(t *testing.T) {
1315 var buf bytes.Buffer
1316 enc := yaml.NewEncoder(&buf, yaml.JSON())
1317 type st struct {
1318 I int8
1319 S string
1320 F float32
1321 }
1322 if err := enc.Encode(struct {
1323 I int
1324 U uint
1325 S string
1326 F float64
1327 Struct *st
1328 Slice []int
1329 Map map[string]interface{}
1330 Time time.Time
1331 Duration time.Duration
1332 }{
1333 I: -10,
1334 U: 10,
1335 S: "hello",
1336 F: 3.14,
1337 Struct: &st{
1338 I: 2,
1339 S: "world",
1340 F: 1.23,
1341 },
1342 Slice: []int{1, 2, 3, 4, 5},
1343 Map: map[string]interface{}{
1344 "a": 1,
1345 "b": 1.23,
1346 "c": "json",
1347 },
1348 Time: time.Time{},
1349 Duration: 5 * time.Minute,
1350 }); err != nil {
1351 t.Fatalf("%+v", err)
1352 }
1353 expect := `
1354 {"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"}
1355 `
1356 actual := "\n" + buf.String()
1357 if expect != actual {
1358 t.Fatalf("JSON style marshal error: expect=[%s] actual=[%s]", expect, actual)
1359 }
1360 }
1361
1362 func TestEncoder_MarshalAnchor(t *testing.T) {
1363 type Host struct {
1364 Hostname string
1365 Username string
1366 Password string
1367 }
1368 type HostDecl struct {
1369 Host *Host `yaml:",anchor"`
1370 }
1371 type Queue struct {
1372 Name string `yaml:","`
1373 *Host
1374 }
1375 var doc struct {
1376 Hosts []*HostDecl `yaml:"hosts"`
1377 Queues []*Queue `yaml:"queues"`
1378 }
1379 host1 := &Host{
1380 Hostname: "host1.example.com",
1381 Username: "userA",
1382 Password: "pass1",
1383 }
1384 host2 := &Host{
1385 Hostname: "host2.example.com",
1386 Username: "userB",
1387 Password: "pass2",
1388 }
1389 doc.Hosts = []*HostDecl{
1390 {
1391 Host: host1,
1392 },
1393 {
1394 Host: host2,
1395 },
1396 }
1397 doc.Queues = []*Queue{
1398 {
1399 Name: "queue",
1400 Host: host1,
1401 }, {
1402 Name: "queue2",
1403 Host: host2,
1404 },
1405 }
1406 hostIdx := 1
1407 opt := yaml.MarshalAnchor(func(anchor *ast.AnchorNode, value interface{}) error {
1408 if _, ok := value.(*Host); ok {
1409 nameNode, _ := anchor.Name.(*ast.StringNode)
1410 nameNode.Value = fmt.Sprintf("host%d", hostIdx)
1411 hostIdx++
1412 }
1413 return nil
1414 })
1415
1416 var buf bytes.Buffer
1417 if err := yaml.NewEncoder(&buf, opt).Encode(doc); err != nil {
1418 t.Fatalf("%+v", err)
1419 }
1420 expect := `
1421 hosts:
1422 - host: &host1
1423 hostname: host1.example.com
1424 username: userA
1425 password: pass1
1426 - host: &host2
1427 hostname: host2.example.com
1428 username: userB
1429 password: pass2
1430 queues:
1431 - name: queue
1432 host: *host1
1433 - name: queue2
1434 host: *host2
1435 `
1436 if "\n"+buf.String() != expect {
1437 t.Fatalf("unexpected output. %s", buf.String())
1438 }
1439 }
1440
1441 type useJSONMarshalerTest struct{}
1442
1443 func (t useJSONMarshalerTest) MarshalJSON() ([]byte, error) {
1444 return []byte(`{"a":[1, 2, 3]}`), nil
1445 }
1446
1447 func TestEncoder_UseJSONMarshaler(t *testing.T) {
1448 got, err := yaml.MarshalWithOptions(useJSONMarshalerTest{}, yaml.UseJSONMarshaler())
1449 if err != nil {
1450 t.Fatal(err)
1451 }
1452 expected := `
1453 a:
1454 - 1
1455 - 2
1456 - 3
1457 `
1458 if expected != "\n"+string(got) {
1459 t.Fatalf("failed to use json marshaler. expected [%q] but got [%q]", expected, string(got))
1460 }
1461 }
1462
1463 func TestEncoder_CustomMarshaler(t *testing.T) {
1464 t.Run("override struct type", func(t *testing.T) {
1465 type T struct {
1466 Foo string `yaml:"foo"`
1467 }
1468 b, err := yaml.MarshalWithOptions(&T{Foo: "bar"}, yaml.CustomMarshaler[T](func(v T) ([]byte, error) {
1469 return []byte(`"override"`), nil
1470 }))
1471 if err != nil {
1472 t.Fatal(err)
1473 }
1474 if !bytes.Equal(b, []byte("\"override\"\n")) {
1475 t.Fatalf("failed to switch to custom marshaler. got: %q", b)
1476 }
1477 })
1478 t.Run("override bytes type", func(t *testing.T) {
1479 type T struct {
1480 Foo []byte `yaml:"foo"`
1481 }
1482 b, err := yaml.MarshalWithOptions(&T{Foo: []byte("bar")}, yaml.CustomMarshaler[[]byte](func(v []byte) ([]byte, error) {
1483 if !bytes.Equal(v, []byte("bar")) {
1484 t.Fatalf("failed to get src buffer: %q", v)
1485 }
1486 return []byte(`override`), nil
1487 }))
1488 if err != nil {
1489 t.Fatal(err)
1490 }
1491 if !bytes.Equal(b, []byte("foo: override\n")) {
1492 t.Fatalf("failed to switch to custom marshaler. got: %q", b)
1493 }
1494 })
1495 t.Run("override bytes type with context", func(t *testing.T) {
1496 type T struct {
1497 Foo []byte `yaml:"foo"`
1498 }
1499 ctx := context.WithValue(context.Background(), "plop", uint(42))
1500 b, err := yaml.MarshalContext(ctx, &T{Foo: []byte("bar")}, yaml.CustomMarshalerContext[[]byte](func(ctx context.Context, v []byte) ([]byte, error) {
1501 if !bytes.Equal(v, []byte("bar")) {
1502 t.Fatalf("failed to get src buffer: %q", v)
1503 }
1504 if ctx.Value("plop") != uint(42) {
1505 t.Fatalf("context value is not correct")
1506 }
1507 return []byte(`override`), nil
1508 }))
1509 if err != nil {
1510 t.Fatal(err)
1511 }
1512 if !bytes.Equal(b, []byte("foo: override\n")) {
1513 t.Fatalf("failed to switch to custom marshaler. got: %q", b)
1514 }
1515 })
1516 }
1517
1518 func TestEncoder_AutoInt(t *testing.T) {
1519 for _, test := range []struct {
1520 desc string
1521 input any
1522 expected string
1523 }{
1524 {
1525 desc: "int-convertible float64",
1526 input: map[string]float64{
1527 "key": 1.0,
1528 },
1529 expected: "key: 1\n",
1530 },
1531 {
1532 desc: "non int-convertible float64",
1533 input: map[string]float64{
1534 "key": 1.1,
1535 },
1536 expected: "key: 1.1\n",
1537 },
1538 {
1539 desc: "int-convertible float32",
1540 input: map[string]float32{
1541 "key": 1.0,
1542 },
1543 expected: "key: 1\n",
1544 },
1545 {
1546 desc: "non int-convertible float32",
1547 input: map[string]float32{
1548 "key": 1.1,
1549 },
1550 expected: "key: 1.1\n",
1551 },
1552 } {
1553 t.Run(test.desc, func(t *testing.T) {
1554 var buf bytes.Buffer
1555 enc := yaml.NewEncoder(&buf, yaml.AutoInt())
1556 if err := enc.Encode(test.input); err != nil {
1557 t.Fatalf("failed to encode: %s", err)
1558 }
1559 if actual := buf.String(); actual != test.expected {
1560 t.Errorf("expect:\n%s\nactual\n%s\n", test.expected, actual)
1561 }
1562 })
1563 }
1564 }
1565
1566 func TestEncoder_MultipleDocuments(t *testing.T) {
1567 var buf bytes.Buffer
1568 enc := yaml.NewEncoder(&buf)
1569 if err := enc.Encode(1); err != nil {
1570 t.Fatalf("failed to encode: %s", err)
1571 }
1572 if err := enc.Encode(2); err != nil {
1573 t.Fatalf("failed to encode: %s", err)
1574 }
1575 if actual, expect := buf.String(), "1\n---\n2\n"; actual != expect {
1576 t.Errorf("expect:\n%s\nactual\n%s\n", expect, actual)
1577 }
1578 }
1579
1580 func TestEncoder_UnmarshallableTypes(t *testing.T) {
1581 for _, test := range []struct {
1582 desc string
1583 input any
1584 expectedErr string
1585 }{
1586 {
1587 desc: "channel",
1588 input: make(chan int),
1589 expectedErr: "unknown value type chan int",
1590 },
1591 {
1592 desc: "function",
1593 input: func() {},
1594 expectedErr: "unknown value type func()",
1595 },
1596 {
1597 desc: "complex number",
1598 input: complex(10, 11),
1599 expectedErr: "unknown value type complex128",
1600 },
1601 {
1602 desc: "unsafe pointer",
1603 input: unsafe.Pointer(&struct{}{}),
1604 expectedErr: "unknown value type unsafe.Pointer",
1605 },
1606 {
1607 desc: "uintptr",
1608 input: uintptr(0x1234),
1609 expectedErr: "unknown value type uintptr",
1610 },
1611 {
1612 desc: "map with channel",
1613 input: map[string]any{"key": make(chan string)},
1614 expectedErr: "unknown value type chan string",
1615 },
1616 {
1617 desc: "nested map with func",
1618 input: map[string]any{
1619 "a": map[string]any{
1620 "b": func(_ string) {},
1621 },
1622 },
1623 expectedErr: "unknown value type func(string)",
1624 },
1625 {
1626 desc: "slice with channel",
1627 input: []any{make(chan bool)},
1628 expectedErr: "unknown value type chan bool",
1629 },
1630 {
1631 desc: "nested slice with complex number",
1632 input: []any{[]any{complex(10, 11)}},
1633 expectedErr: "unknown value type complex128",
1634 },
1635 {
1636 desc: "struct with unsafe pointer",
1637 input: struct {
1638 Field unsafe.Pointer `yaml:"field"`
1639 }{},
1640 expectedErr: "unknown value type unsafe.Pointer",
1641 },
1642 } {
1643 t.Run(test.desc, func(t *testing.T) {
1644 var buf bytes.Buffer
1645 err := yaml.NewEncoder(&buf).Encode(test.input)
1646 if err == nil {
1647 t.Errorf("expect error:\n%s\nbut got none\n", test.expectedErr)
1648 } else if err.Error() != test.expectedErr {
1649 t.Errorf("expect error:\n%s\nactual\n%s\n", test.expectedErr, err)
1650 }
1651 })
1652 }
1653 }
1654
1655 func ExampleMarshal_node() {
1656 type T struct {
1657 Text ast.Node `yaml:"text"`
1658 }
1659 stringNode, err := yaml.ValueToNode("node example")
1660 if err != nil {
1661 panic(err)
1662 }
1663 bytes, err := yaml.Marshal(T{Text: stringNode})
1664 if err != nil {
1665 panic(err)
1666 }
1667 fmt.Println(string(bytes))
1668 // OUTPUT:
1669 // text: node example
1670 }
1671
1672 func ExampleMarshal_explicitAnchorAlias() {
1673 type T struct {
1674 A int
1675 B string
1676 }
1677 var v struct {
1678 C *T `yaml:"c,anchor=x"`
1679 D *T `yaml:"d,alias=x"`
1680 }
1681 v.C = &T{A: 1, B: "hello"}
1682 v.D = v.C
1683 bytes, err := yaml.Marshal(v)
1684 if err != nil {
1685 panic(err)
1686 }
1687 fmt.Println(string(bytes))
1688 // OUTPUT:
1689 // c: &x
1690 // a: 1
1691 // b: hello
1692 // d: *x
1693 }
1694
1695 func ExampleMarshal_implicitAnchorAlias() {
1696 type T struct {
1697 I int
1698 S string
1699 }
1700 var v struct {
1701 A *T `yaml:"a,anchor"`
1702 B *T `yaml:"b,anchor"`
1703 C *T `yaml:"c"`
1704 D *T `yaml:"d"`
1705 }
1706 v.A = &T{I: 1, S: "hello"}
1707 v.B = &T{I: 2, S: "world"}
1708 v.C = v.A // C has same pointer address to A
1709 v.D = v.B // D has same pointer address to B
1710 bytes, err := yaml.Marshal(v)
1711 if err != nil {
1712 panic(err)
1713 }
1714 fmt.Println(string(bytes))
1715 // OUTPUT:
1716 // a: &a
1717 // i: 1
1718 // s: hello
1719 // b: &b
1720 // i: 2
1721 // s: world
1722 // c: *a
1723 // d: *b
1724 }
1725
1726 type tMarshal []string
1727
1728 func (t *tMarshal) MarshalYAML() ([]byte, error) {
1729 var buf bytes.Buffer
1730 buf.WriteString("tags:\n")
1731 for i, v := range *t {
1732 if i == 0 {
1733 fmt.Fprintf(&buf, "- %s\n", v)
1734 } else {
1735 fmt.Fprintf(&buf, " %s\n", v)
1736 }
1737 }
1738 return buf.Bytes(), nil
1739 }
1740 func Test_Marshaler(t *testing.T) {
1741 const expected = `- hello-world
1742 `
1743
1744 // sanity check
1745 var l []string
1746 if err := yaml.Unmarshal([]byte(expected), &l); err != nil {
1747 t.Fatalf("failed to parse string: %s", err)
1748 }
1749
1750 buf, err := yaml.Marshal(tMarshal{"hello-world"})
1751 if err != nil {
1752 t.Fatalf("failed to marshal: %s", err)
1753 }
1754
1755 if string(buf) != expected {
1756 t.Fatalf("expected '%s', got '%s'", expected, buf)
1757 }
1758
1759 t.Logf("%s", buf)
1760 }
1761
1762 type marshalContext struct{}
1763
1764 func (c *marshalContext) MarshalYAML(ctx context.Context) ([]byte, error) {
1765 v, ok := ctx.Value("k").(int)
1766 if !ok {
1767 return nil, errors.New("cannot get valid context")
1768 }
1769 if v != 1 {
1770 return nil, errors.New("cannot get valid context")
1771 }
1772 return []byte("1"), nil
1773 }
1774
1775 func Test_MarshalerContext(t *testing.T) {
1776 ctx := context.WithValue(context.Background(), "k", 1)
1777 bytes, err := yaml.MarshalContext(ctx, &marshalContext{})
1778 if err != nil {
1779 t.Fatalf("%+v", err)
1780 }
1781 if string(bytes) != "1\n" {
1782 t.Fatalf("failed marshal: %q", string(bytes))
1783 }
1784 }
1785
1786 type SlowMarshaler struct {
1787 A string
1788 B int
1789 }
1790 type FastMarshaler struct {
1791 A string
1792 B int
1793 }
1794 type TextMarshaler int64
1795 type TextMarshalerContainer struct {
1796 Field TextMarshaler `yaml:"field"`
1797 }
1798
1799 func (v SlowMarshaler) MarshalYAML() ([]byte, error) {
1800 var buf bytes.Buffer
1801 buf.WriteString("tags:\n")
1802 buf.WriteString("- slow-marshaler\n")
1803 buf.WriteString("a: " + v.A + "\n")
1804 buf.WriteString("b: " + strconv.FormatInt(int64(v.B), 10) + "\n")
1805 return buf.Bytes(), nil
1806 }
1807
1808 func (v FastMarshaler) MarshalYAML() (interface{}, error) {
1809 return yaml.MapSlice{
1810 {"tags", []string{"fast-marshaler"}},
1811 {"a", v.A},
1812 {"b", v.B},
1813 }, nil
1814 }
1815
1816 func (t TextMarshaler) MarshalText() ([]byte, error) {
1817 return []byte(strconv.FormatInt(int64(t), 8)), nil
1818 }
1819
1820 func ExampleMarshal() {
1821 var slow SlowMarshaler
1822 slow.A = "Hello slow poke"
1823 slow.B = 100
1824 buf, err := yaml.Marshal(slow)
1825 if err != nil {
1826 panic(err.Error())
1827 }
1828
1829 fmt.Println(string(buf))
1830
1831 var fast FastMarshaler
1832 fast.A = "Hello speed demon"
1833 fast.B = 100
1834 buf, err = yaml.Marshal(fast)
1835 if err != nil {
1836 panic(err.Error())
1837 }
1838
1839 fmt.Println(string(buf))
1840
1841 text := TextMarshalerContainer{
1842 Field: 11,
1843 }
1844 buf, err = yaml.Marshal(text)
1845 if err != nil {
1846 panic(err.Error())
1847 }
1848
1849 fmt.Println(string(buf))
1850 // OUTPUT:
1851 // tags:
1852 // - slow-marshaler
1853 // a: Hello slow poke
1854 // b: 100
1855 //
1856 // tags:
1857 // - fast-marshaler
1858 // a: Hello speed demon
1859 // b: 100
1860 //
1861 // field: "13"
1862 }
1863
1864 func TestIssue356(t *testing.T) {
1865 tests := map[string]struct {
1866 in string
1867 }{
1868 "content on first line": {
1869 in: `args:
1870 - |
1871
1872 key:
1873 nest1: something
1874 nest2:
1875 nest2a: b
1876 `,
1877 },
1878 "empty first line": {
1879 in: `args:
1880 - |
1881
1882 key:
1883 nest1: something
1884 nest2:
1885 nest2a: b
1886 `,
1887 },
1888 }
1889
1890 for name, test := range tests {
1891 t.Run(name, func(t *testing.T) {
1892 f, err := parser.ParseBytes([]byte(test.in), 0)
1893 if err != nil {
1894 t.Fatalf("parse: %v", err)
1895 }
1896 got := f.String()
1897 if test.in != got {
1898 t.Fatalf("failed to encode.\nexpected:\n%s\nbut got:\n%s\n", test.in, got)
1899 }
1900 })
1901 }
1902 }
1903
1904 func TestMarshalIndentWithMultipleText(t *testing.T) {
1905 tests := []struct {
1906 name string
1907 input map[string]interface{}
1908 indent yaml.EncodeOption
1909 want string
1910 }{
1911 {
1912 name: "depth1",
1913 input: map[string]interface{}{
1914 "key": []string{`line1
1915 line2
1916 line3`},
1917 },
1918 indent: yaml.Indent(2),
1919 want: `key:
1920 - |-
1921 line1
1922 line2
1923 line3
1924 `,
1925 },
1926 {
1927 name: "depth2",
1928 input: map[string]interface{}{
1929 "key": map[string]interface{}{
1930 "key2": []string{`line1
1931 line2
1932 line3`},
1933 },
1934 },
1935 indent: yaml.Indent(2),
1936 want: `key:
1937 key2:
1938 - |-
1939 line1
1940 line2
1941 line3
1942 `,
1943 },
1944 {
1945 name: "raw string new lines",
1946 input: map[string]interface{}{
1947 "key": "line1\nline2\nline3",
1948 },
1949 indent: yaml.Indent(4),
1950 want: `key: |-
1951 line1
1952 line2
1953 line3
1954 `,
1955 },
1956 }
1957
1958 for _, tt := range tests {
1959 t.Run(tt.name, func(t *testing.T) {
1960 b, err := yaml.MarshalWithOptions(tt.input, tt.indent)
1961 if err != nil {
1962 t.Fatalf("failed to marshal yaml: %v", err)
1963 }
1964 got := string(b)
1965 if tt.want != got {
1966 t.Fatalf("failed to encode.\nexpected:\n%s\nbut got:\n%s\n", tt.want, got)
1967 }
1968 })
1969 }
1970 }
1971
1972 type bytesMarshaler struct{}
1973
1974 func (b *bytesMarshaler) MarshalYAML() ([]byte, error) {
1975 return yaml.Marshal(map[string]interface{}{"d": "foo"})
1976 }
1977
1978 func TestBytesMarshaler(t *testing.T) {
1979 b, err := yaml.Marshal(map[string]interface{}{
1980 "a": map[string]interface{}{
1981 "b": map[string]interface{}{
1982 "c": &bytesMarshaler{},
1983 },
1984 },
1985 })
1986 if err != nil {
1987 t.Fatal(err)
1988 }
1989 expected := `
1990 a:
1991 b:
1992 c:
1993 d: foo
1994 `
1995 got := "\n" + string(b)
1996 if expected != got {
1997 t.Fatalf("failed to encode. expected %s but got %s", expected, got)
1998 }
1999 }
2000
2001 type customMapSliceOneItemMarshaler struct{}
2002
2003 func (m *customMapSliceOneItemMarshaler) MarshalYAML() ([]byte, error) {
2004 var v yaml.MapSlice
2005 v = append(v, yaml.MapItem{"a", "b"})
2006 return yaml.Marshal(v)
2007 }
2008
2009 type customMapSliceTwoItemMarshaler struct{}
2010
2011 func (m *customMapSliceTwoItemMarshaler) MarshalYAML() ([]byte, error) {
2012 var v yaml.MapSlice
2013 v = append(v, yaml.MapItem{"a", "b"})
2014 v = append(v, yaml.MapItem{"b", "c"})
2015 return yaml.Marshal(v)
2016 }
2017
2018 func TestCustomMapSliceMarshaler(t *testing.T) {
2019 type T struct {
2020 A *customMapSliceOneItemMarshaler `yaml:"a"`
2021 B *customMapSliceTwoItemMarshaler `yaml:"b"`
2022 }
2023 b, err := yaml.Marshal(&T{
2024 A: &customMapSliceOneItemMarshaler{},
2025 B: &customMapSliceTwoItemMarshaler{},
2026 })
2027 if err != nil {
2028 t.Fatal(err)
2029 }
2030 expected := `
2031 a:
2032 a: b
2033 b:
2034 a: b
2035 b: c
2036 `
2037 got := "\n" + string(b)
2038 if expected != got {
2039 t.Fatalf("failed to encode. expected %s but got %s", expected, got)
2040 }
2041 }
2042
2043 type Issue174 struct {
2044 K string
2045 V []int
2046 }
2047
2048 func (v Issue174) MarshalYAML() ([]byte, error) {
2049 return yaml.MarshalWithOptions(map[string][]int{v.K: v.V}, yaml.Flow(true))
2050 }
2051
2052 func TestIssue174(t *testing.T) {
2053 b, err := yaml.Marshal(Issue174{"00:00:00-23:59:59", []int{1, 2, 3}})
2054 if err != nil {
2055 t.Fatal(err)
2056 }
2057 got := strings.TrimSuffix(string(b), "\n")
2058 if got != `{"00:00:00-23:59:59": [1, 2, 3]}` {
2059 t.Fatalf("failed to encode: %q", got)
2060 }
2061 }
2062
2063 func TestIssue259(t *testing.T) {
2064 type AnchorValue struct {
2065 Foo uint64
2066 Bar string
2067 }
2068
2069 type Value struct {
2070 Baz string `yaml:"baz"`
2071 Value *AnchorValue `yaml:"value,anchor"`
2072 }
2073
2074 type Schema struct {
2075 Values []*Value
2076 }
2077
2078 schema := Schema{}
2079 anchorValue := AnchorValue{Foo: 3, Bar: "bar"}
2080 schema.Values = []*Value{
2081 {Baz: "xxx", Value: &anchorValue},
2082 {Baz: "yyy", Value: &anchorValue},
2083 {Baz: "zzz", Value: &anchorValue},
2084 }
2085 b, err := yaml.Marshal(schema)
2086 if err != nil {
2087 t.Fatal(err)
2088 }
2089 expected := `
2090 values:
2091 - baz: xxx
2092 value: &value
2093 foo: 3
2094 bar: bar
2095 - baz: yyy
2096 value: *value
2097 - baz: zzz
2098 value: *value
2099 `
2100 if strings.TrimPrefix(expected, "\n") != string(b) {
2101 t.Fatalf("failed to encode: got = %s", string(b))
2102 }
2103 }
2104
2105 func TestTagMarshalling(t *testing.T) {
2106 tests := []struct {
2107 name string
2108 input string
2109 }{
2110 {name: "scalar", input: "a: !mytag 1"},
2111 {name: "mapping", input: `
2112 a: !mytag
2113 b: 2`},
2114 {name: "sequence", input: `
2115 a: !mytag
2116 - 1
2117 - 2
2118 - 3`},
2119 {name: "anchor before tag", input: `
2120 a: &anc !mytag
2121 - 1
2122 - 2
2123 - 3`},
2124 {name: "flow mapping", input: "a: !mytag {b: 2}"},
2125 {name: "flow sequence", input: "a: !mytag [1, 2, 3]"},
2126 {name: "explicit type", input: "a: !!timestamp test"},
2127 }
2128
2129 for _, tt := range tests {
2130 t.Run(tt.name, func(t *testing.T) {
2131 res, _ := parser.ParseBytes([]byte(tt.input), 0)
2132 result, err := yaml.Marshal(res.Docs[0])
2133 if err != nil {
2134 t.Fatal(err)
2135 }
2136
2137 expected := strings.TrimSpace(tt.input)
2138 output := strings.TrimSpace(string(result))
2139 if expected != output {
2140 t.Fatalf("input is not equal to output.\n\nexpected:\n%v\n actual:\n%v", expected, output)
2141 }
2142 })
2143 }
2144 }
2145
2146 func ptr[T any](v T) *T {
2147 return &v
2148 }