-
Notifications
You must be signed in to change notification settings - Fork 9
/
default_test.go
106 lines (87 loc) · 2.48 KB
/
default_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
93
94
95
96
97
98
99
100
101
102
103
104
105
106
// Copyright (c) 2024 The konf authors
// Use of this source code is governed by a MIT license found in the LICENSE file.
package konf_test
import (
"context"
"testing"
"github.com/nil-go/konf"
"github.com/nil-go/konf/internal/assert"
"github.com/nil-go/konf/provider/env"
)
func TestUnmarshal(t *testing.T) {
t.Parallel()
var config konf.Config
err := config.Load(mapLoader{"config": "string"})
assert.NoError(t, err)
konf.SetDefault(&config)
var v string
assert.NoError(t, konf.Unmarshal("config", &v))
assert.Equal(t, "string", v)
}
func TestGet(t *testing.T) {
t.Parallel()
var config konf.Config
err := config.Load(mapLoader{"config": "string"})
assert.NoError(t, err)
konf.SetDefault(&config)
assert.Equal(t, "string", konf.Get[string]("config"))
}
func TestGet_error(t *testing.T) {
buf := &buffer{}
config := konf.New(konf.WithLogHandler(logHandler(buf)))
err := config.Load(mapLoader{"config": "string"})
assert.NoError(t, err)
konf.SetDefault(config)
assert.True(t, !konf.Get[bool]("config"))
expected := `level=WARN msg="Could not read config, return empty value instead."` +
` path=config type=bool` +
` error="decode: cannot parse '' as bool: strconv.ParseBool: parsing \"string\": invalid syntax"` +
"\n"
assert.Equal(t, expected, buf.String())
}
func TestOnChange(t *testing.T) {
var config konf.Config
watcher := stringWatcher{key: "Config", value: make(chan string)}
err := config.Load(watcher)
assert.NoError(t, err)
konf.SetDefault(&config)
var value string
assert.NoError(t, config.Unmarshal("config", &value))
assert.Equal(t, "", value)
stopped := make(chan struct{})
ctx, cancel := context.WithCancel(context.Background())
defer func() {
cancel()
<-stopped
}()
go func() {
defer close(stopped)
assert.NoError(t, config.Watch(ctx))
}()
newValue := make(chan string)
konf.OnChange(func() {
var value string
assert.NoError(t, konf.Unmarshal("config", &value))
newValue <- value
}, "config")
watcher.change()
assert.Equal(t, "changed", <-newValue)
}
func TestExplain(t *testing.T) {
var config konf.Config
err := config.Load(env.New())
assert.NoError(t, err)
err = config.Load(mapLoader{
"config": map[string]any{"nest": "env"},
})
assert.NoError(t, err)
err = config.Load(mapLoader{
"config": map[string]any{"nest": "map"},
})
assert.NoError(t, err)
konf.SetDefault(&config)
assert.Equal(t, `config.nest has value[map] that is loaded by loader[map].
Here are other value(loader)s:
- env(map)
`, konf.Explain("config"))
}