-
Notifications
You must be signed in to change notification settings - Fork 0
/
mapper_test.go
83 lines (65 loc) · 1.72 KB
/
mapper_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
package confmap_test
import (
"testing"
"github.com/memlib/confmap"
)
func equals(t *testing.T, expect, actual any) {
if expect != actual {
t.Errorf(`expects "%+v"(%T), actual "%+v"(%T)`, expect, expect, actual, actual)
}
}
func Test_MapEnvs(t *testing.T) {
type mappingObj struct {
Field0 string `mapstructure:"field_0"`
Field1 string `mapstructure:"field_1"`
}
t.Run("success", func(t *testing.T) {
var obj mappingObj
t.Setenv("PRFX_FIELD_0", "val0")
t.Setenv("PRFX_FIELD_1", "val1")
if err := confmap.MapEnvs("prfx", &obj); err != nil {
t.Errorf("error = %v", err)
}
equals(t, "val0", obj.Field0)
equals(t, "val1", obj.Field1)
})
t.Run("success generics", func(t *testing.T) {
var obj *mappingObj
t.Setenv("PRFX_FIELD_0", "val0")
t.Setenv("PRFX_FIELD_1", "val1")
obj, err := confmap.MapEnvsTyped[mappingObj]("prfx")
if err != nil {
t.Errorf("error = %v", err)
}
equals(t, "val0", obj.Field0)
equals(t, "val1", obj.Field1)
})
t.Run("success_single", func(t *testing.T) {
var obj mappingObj
t.Setenv("PRFX_FIELD_0", "val0")
if err := confmap.MapEnvs("prfx", &obj); err != nil {
t.Errorf("error = %v", err)
}
equals(t, "val0", obj.Field0)
equals(t, "", obj.Field1)
})
}
type testObjWithDefaults struct {
Field0 string `mapstructure:"field_0"`
Field1 string `mapstructure:"field_1"`
}
func (d testObjWithDefaults) DefaultEnvs() map[string]any {
return map[string]any{
"field_0": "def_val0",
"field_1": "def_val1",
}
}
func TestDefaults(t *testing.T) {
var obj testObjWithDefaults
t.Setenv("PRFX_FIELD_0", "val0")
if err := confmap.MapEnvs("prfx", &obj); err != nil {
t.Errorf("error = %v", err)
}
equals(t, "val0", obj.Field0)
equals(t, "def_val1", obj.Field1)
}