...
1 package yaml
2
3 import (
4 "testing"
5
6 "github.com/stretchr/testify/assert"
7 "github.com/stretchr/testify/require"
8 )
9
10
11 const original = `# key-value pair
12 key: value
13 list:
14 - item1
15 - item2
16 - item3
17 map:
18 key: value
19
20 # nested
21 # map
22 nested_map:
23 map:
24 key: value
25 list:
26 - item1
27 - item2
28 - item3
29 `
30
31
32 const encoded = `key: value
33 list:
34 - item1
35 - item2
36 - item3
37 map:
38 key: value
39 nested_map:
40 map:
41 key: value
42 list:
43 - item1
44 - item2
45 - item3
46 `
47
48
49
50
51
52 var decoded = map[string]any{
53 "key": "value",
54 "list": []any{
55 "item1",
56 "item2",
57 "item3",
58 },
59 "map": map[string]any{
60 "key": "value",
61 },
62 "nested_map": map[string]any{
63 "map": map[string]any{
64 "key": "value",
65 "list": []any{
66 "item1",
67 "item2",
68 "item3",
69 },
70 },
71 },
72 }
73
74
75 var data = map[string]any{
76 "key": "value",
77 "list": []any{
78 "item1",
79 "item2",
80 "item3",
81 },
82 "map": map[string]any{
83 "key": "value",
84 },
85 "nested_map": map[string]any{
86 "map": map[string]any{
87 "key": "value",
88 "list": []any{
89 "item1",
90 "item2",
91 "item3",
92 },
93 },
94 },
95 }
96
97 func TestCodec_Encode(t *testing.T) {
98 codec := Codec{}
99
100 b, err := codec.Encode(data)
101 require.NoError(t, err)
102
103 assert.Equal(t, encoded, string(b))
104 }
105
106 func TestCodec_Decode(t *testing.T) {
107 t.Run("OK", func(t *testing.T) {
108 codec := Codec{}
109
110 v := map[string]any{}
111
112 err := codec.Decode([]byte(original), v)
113 require.NoError(t, err)
114
115 assert.Equal(t, decoded, v)
116 })
117
118 t.Run("InvalidData", func(t *testing.T) {
119 codec := Codec{}
120
121 v := map[string]any{}
122
123 err := codec.Decode([]byte(`invalid data`), v)
124 require.Error(t, err)
125
126 t.Logf("decoding failed as expected: %s", err)
127 })
128 }
129
View as plain text