Debian Codegraph @

confmap/internal/mapstructure/encoder_test.go

raw
1 // Copyright The OpenTelemetry Authors
2 // SPDX-License-Identifier: Apache-2.0
3
4 package mapstructure
5
6 import (
7 "encoding"
8 "errors"
9 "reflect"
10 "strings"
11 "testing"
12
13 "github.com/go-viper/mapstructure/v2"
14 "github.com/stretchr/testify/require"
15 )
16
17 type TestComplexStruct struct {
18 Skipped TestEmptyStruct `mapstructure:",squash"`
19 Nested TestSimpleStruct `mapstructure:",squash"`
20 Slice []TestSimpleStruct `mapstructure:"slice,omitempty"`
21 Pointer *TestSimpleStruct `mapstructure:"ptr"`
22 Map map[string]TestSimpleStruct `mapstructure:"map,omitempty"`
23 Remain map[string]any `mapstructure:",remain"`
24 TranslatedYaml TestYamlStruct `mapstructure:"translated"`
25 SquashedYaml TestYamlStruct `mapstructure:",squash"`
26 PointerTranslatedYaml *TestPtrToYamlStruct `mapstructure:"translated_ptr"`
27 PointerSquashedYaml *TestPtrToYamlStruct `mapstructure:",squash"`
28 Interface encoding.TextMarshaler
29 }
30
31 type TestSimpleStruct struct {
32 Value string `mapstructure:"value"`
33 skipped string
34 err error
35 }
36
37 type TestEmptyStruct struct {
38 Value string `mapstructure:"-"`
39 }
40
41 type TestYamlStruct struct {
42 YamlValue string `yaml:"yaml_value"`
43 YamlOmitEmpty string `yaml:"yaml_omit,omitempty"`
44 YamlInline TestYamlSimpleStruct `yaml:",inline"`
45 }
46
47 type TestPtrToYamlStruct struct {
48 YamlValue string `yaml:"yaml_value_ptr"`
49 YamlOmitEmpty string `yaml:"yaml_omit_ptr,omitempty"`
50 YamlInline *TestYamlPtrToSimpleStruct `yaml:",inline"`
51 }
52
53 type TestYamlSimpleStruct struct {
54 Inline string `yaml:"yaml_inline"`
55 }
56
57 type TestYamlPtrToSimpleStruct struct {
58 InlinePtr string `yaml:"yaml_inline_ptr"`
59 }
60
61 type TestID string
62
63 func (tID TestID) MarshalText() (text []byte, err error) {
64 out := string(tID)
65 if out == "error" {
66 return nil, errors.New("parsing error")
67 }
68 if !strings.HasSuffix(out, "_") {
69 out += "_"
70 }
71 return []byte(out), nil
72 }
73
74 type TestStringLike string
75
76 func TestEncode(t *testing.T) {
77 enc := New(&EncoderConfig{
78 EncodeHook: mapstructure.ComposeDecodeHookFunc(
79 YamlMarshalerHookFunc(),
80 TextMarshalerHookFunc(),
81 ),
82 })
83 testCases := map[string]struct {
84 input any
85 want any
86 }{
87 "WithString": {
88 input: "test",
89 want: "test",
90 },
91 "WithTextMarshaler": {
92 input: TestID("type"),
93 want: "type_",
94 },
95 "MapWithTextMarshalerKey": {
96 input: map[TestID]TestSimpleStruct{
97 TestID("type"): {Value: "value"},
98 },
99 want: map[string]any{
100 "type_": map[string]any{"value": "value"},
101 },
102 },
103 "MapWithoutTextMarshalerKey": {
104 input: map[TestStringLike]TestSimpleStruct{
105 TestStringLike("key"): {Value: "value"},
106 },
107 want: map[string]any{
108 "key": map[string]any{"value": "value"},
109 },
110 },
111 "WithSlice": {
112 input: []TestID{
113 TestID("nop"),
114 TestID("type_"),
115 },
116 want: []any{"nop_", "type_"},
117 },
118 "WithSimpleStruct": {
119 input: TestSimpleStruct{Value: "test", skipped: "skipped"},
120 want: map[string]any{
121 "value": "test",
122 },
123 },
124 "WithComplexStruct": {
125 input: &TestComplexStruct{
126 Skipped: TestEmptyStruct{
127 Value: "omitted",
128 },
129 Nested: TestSimpleStruct{
130 Value: "nested",
131 },
132 Slice: []TestSimpleStruct{
133 {Value: "slice"},
134 },
135 Map: map[string]TestSimpleStruct{
136 "Key": {Value: "map"},
137 },
138 Pointer: &TestSimpleStruct{
139 Value: "pointer",
140 },
141 Remain: map[string]any{
142 "remain1": 23,
143 "remain2": "value",
144 },
145 Interface: TestID("value"),
146 TranslatedYaml: TestYamlStruct{
147 YamlValue: "foo_translated",
148 YamlOmitEmpty: "",
149 YamlInline: TestYamlSimpleStruct{
150 Inline: "bar_translated",
151 },
152 },
153 SquashedYaml: TestYamlStruct{
154 YamlValue: "foo_squashed",
155 YamlOmitEmpty: "",
156 YamlInline: TestYamlSimpleStruct{
157 Inline: "bar_squashed",
158 },
159 },
160 PointerTranslatedYaml: &TestPtrToYamlStruct{
161 YamlValue: "foo_translated_ptr",
162 YamlOmitEmpty: "",
163 YamlInline: &TestYamlPtrToSimpleStruct{
164 InlinePtr: "bar_translated_ptr",
165 },
166 },
167 PointerSquashedYaml: &TestPtrToYamlStruct{
168 YamlValue: "foo_squashed_ptr",
169 YamlOmitEmpty: "",
170 YamlInline: &TestYamlPtrToSimpleStruct{
171 InlinePtr: "bar_squashed_ptr",
172 },
173 },
174 },
175 want: map[string]any{
176 "value": "nested",
177 "slice": []any{map[string]any{"value": "slice"}},
178 "map": map[string]any{
179 "Key": map[string]any{"value": "map"},
180 },
181 "ptr": map[string]any{"value": "pointer"},
182 "interface": "value_",
183 "yaml_value": "foo_squashed",
184 "yaml_inline": "bar_squashed",
185 "translated": map[string]any{
186 "yaml_value": "foo_translated",
187 "yaml_inline": "bar_translated",
188 },
189 "yaml_value_ptr": "foo_squashed_ptr",
190 "yaml_inline_ptr": "bar_squashed_ptr",
191 "translated_ptr": map[string]any{
192 "yaml_value_ptr": "foo_translated_ptr",
193 "yaml_inline_ptr": "bar_translated_ptr",
194 },
195 "remain1": 23,
196 "remain2": "value",
197 },
198 },
199 }
200 for name, testCase := range testCases {
201 t.Run(name, func(t *testing.T) {
202 got, err := enc.Encode(testCase.input)
203 require.NoError(t, err)
204 require.Equal(t, testCase.want, got)
205 })
206 }
207 // without the TextMarshalerHookFunc
208 enc.config.EncodeHook = nil
209 testCase := TestID("test")
210 got, err := enc.Encode(testCase)
211 require.NoError(t, err)
212 require.Equal(t, testCase, got)
213 }
214
215 func TestGetTagInfo(t *testing.T) {
216 testCases := []struct {
217 name string
218 field reflect.StructField
219 wantName string
220 wantOmit bool
221 wantSquash bool
222 }{
223 {
224 name: "WithoutTags",
225 field: reflect.StructField{
226 Name: "Test",
227 },
228 wantName: "test",
229 },
230 {
231 name: "WithoutMapStructureTag",
232 field: reflect.StructField{
233 Tag: `yaml:"hello,inline"`,
234 Name: "YAML",
235 },
236 wantName: "yaml",
237 },
238 {
239 name: "WithRename",
240 field: reflect.StructField{
241 Tag: `mapstructure:"hello"`,
242 Name: "Test",
243 },
244 wantName: "hello",
245 },
246 {
247 name: "WithOmitEmpty",
248 field: reflect.StructField{
249 Tag: `mapstructure:"hello,omitempty"`,
250 Name: "Test",
251 },
252 wantName: "hello",
253 wantOmit: true,
254 },
255 {
256 name: "WithSquash",
257 field: reflect.StructField{
258 Tag: `mapstructure:",squash"`,
259 Name: "Test",
260 },
261 wantSquash: true,
262 },
263 {
264 name: "WithRemain",
265 field: reflect.StructField{
266 Tag: `mapstructure:",remain"`,
267 Name: "Test",
268 },
269 wantSquash: true,
270 },
271 }
272 for _, tt := range testCases {
273 t.Run(tt.name, func(t *testing.T) {
274 got := getTagInfo(tt.field)
275 require.Equal(t, tt.wantName, got.name)
276 require.Equal(t, tt.wantOmit, got.omitEmpty)
277 require.Equal(t, tt.wantSquash, got.squash)
278 })
279 }
280 }
281
282 func TestEncodeValueError(t *testing.T) {
283 enc := New(nil)
284 testValue := reflect.ValueOf("")
285 testCases := []struct {
286 encodeFn func(value reflect.Value) (any, error)
287 wantErr error
288 }{
289 {encodeFn: enc.encodeMap, wantErr: &reflect.ValueError{Method: "encodeMap", Kind: reflect.String}},
290 {encodeFn: enc.encodeStruct, wantErr: &reflect.ValueError{Method: "encodeStruct", Kind: reflect.String}},
291 {encodeFn: enc.encodeSlice, wantErr: &reflect.ValueError{Method: "encodeSlice", Kind: reflect.String}},
292 }
293 for _, tt := range testCases {
294 got, err := tt.encodeFn(testValue)
295 require.Error(t, err)
296 require.Equal(t, tt.wantErr, err)
297 require.Nil(t, got)
298 }
299 }
300
301 func TestEncodeNonStringEncodedKey(t *testing.T) {
302 enc := New(nil)
303 testCase := []struct {
304 Test map[string]any
305 }{
306 {
307 Test: map[string]any{
308 "test": map[TestEmptyStruct]TestSimpleStruct{
309 {Value: "key"}: {Value: "value"},
310 },
311 },
312 },
313 }
314 got, err := enc.Encode(testCase)
315 require.Error(t, err)
316 require.ErrorIs(t, err, errNonStringEncodedKey)
317 require.Nil(t, got)
318 }
319
320 func TestDuplicateKey(t *testing.T) {
321 enc := New(&EncoderConfig{
322 EncodeHook: TextMarshalerHookFunc(),
323 })
324 testCase := map[TestID]string{
325 "test": "value",
326 "test_": "other value",
327 }
328 got, err := enc.Encode(testCase)
329 require.Error(t, err)
330 require.Nil(t, got)
331 }
332
333 func TestTextMarshalerError(t *testing.T) {
334 enc := New(&EncoderConfig{
335 EncodeHook: TextMarshalerHookFunc(),
336 })
337 testCase := map[TestID]string{
338 "error": "value",
339 }
340 got, err := enc.Encode(testCase)
341 require.Error(t, err)
342 require.Nil(t, got)
343 }
344
345 func TestEncodeStruct(t *testing.T) {
346 enc := New(&EncoderConfig{
347 EncodeHook: testHookFunc(),
348 })
349 testCase := TestSimpleStruct{
350 Value: "original",
351 skipped: "final",
352 }
353 got, err := enc.Encode(testCase)
354 require.NoError(t, err)
355 require.Equal(t, "final", got)
356 }
357
358 func TestEncodeStructError(t *testing.T) {
359 enc := New(&EncoderConfig{
360 EncodeHook: testHookFunc(),
361 })
362 wantErr := errors.New("test")
363 testCase := map[TestSimpleStruct]string{
364 {err: wantErr}: "value",
365 }
366 got, err := enc.Encode(testCase)
367 require.Error(t, err)
368 require.ErrorIs(t, err, wantErr)
369 require.Nil(t, got)
370 }
371
372 func TestEncodeNil(t *testing.T) {
373 enc := New(nil)
374 got, err := enc.Encode(nil)
375 require.NoError(t, err)
376 require.Nil(t, got)
377 }
378
379 func testHookFunc() mapstructure.DecodeHookFuncValue {
380 return func(from, _ reflect.Value) (any, error) {
381 if from.Kind() != reflect.Struct {
382 return from.Interface(), nil
383 }
384
385 got, ok := from.Interface().(TestSimpleStruct)
386 if !ok {
387 return from.Interface(), nil
388 }
389 if got.err != nil {
390 return nil, got.err
391 }
392 return got.skipped, nil
393 }
394 }