-
Notifications
You must be signed in to change notification settings - Fork 0
/
types_test.go
92 lines (70 loc) · 2.14 KB
/
types_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
package example
import (
"fmt"
"strings"
"testing"
"github.com/knadh/koanf/parsers/yaml"
"github.com/knadh/koanf/providers/confmap"
"github.com/knadh/koanf/providers/env"
"github.com/knadh/koanf/providers/file"
"github.com/knadh/koanf/v2"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func TestLoadConfig(t *testing.T) {
testCases := []struct {
name string
value string
}{
{
"ArrayOfMaps",
"[map[example:456 extra:4]]",
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
t.Setenv("EXAMPLE_VALUES", tc.value)
t.Run("Straight", func(t *testing.T) {
config := &Configuration{}
require.NoError(t, loadConfig("EXAMPLE_", "example.yml", config))
assert.Len(t, config.Values, 1)
})
t.Run("ViaMap", func(t *testing.T) {
configmap := map[string]any{}
require.NoError(t, loadConfig("EXAMPLE_", "example.yml", &configmap))
assert.Equal(t, map[string]any{"values": []map[string]any{{"example": "456", "extra": 4}}}, configmap)
assert.NotEqual(t, map[string]any{"values": "[map[example:456 extra:4]]"}, configmap)
config, err := mapToConfig(configmap)
require.NoError(t, err)
assert.Len(t, config.Values, 1)
})
})
}
}
func loadConfig(envPrefix, path string, o any) (err error) {
k := koanf.New(".")
if err = k.Load(file.Provider(path), yaml.Parser()); err != nil {
return fmt.Errorf("error loading file: %w", err)
}
if err = k.Load(env.Provider(envPrefix, ".", func(s string) string {
return strings.Replace(strings.ToLower(
strings.TrimPrefix(s, envPrefix)), "_", ".", -1)
}), nil); err != nil {
return fmt.Errorf("error loading env: %w", err)
}
if err = k.Unmarshal("", o); err != nil {
return fmt.Errorf("error unmarshalling: %w", err)
}
return nil
}
func mapToConfig(o map[string]any) (config *Configuration, err error) {
k := koanf.New(".")
if err = k.Load(confmap.Provider(o, "."), nil); err != nil {
return nil, fmt.Errorf("error loading map: %w", err)
}
config = &Configuration{}
if err = k.Unmarshal("", config); err != nil {
return nil, fmt.Errorf("error unmarshalling: %w", err)
}
return config, nil
}