-
Notifications
You must be signed in to change notification settings - Fork 9
/
watch_test.go
375 lines (305 loc) · 8.18 KB
/
watch_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
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
// 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 (
"bytes"
"context"
"errors"
"fmt"
"log/slog"
"sync"
"sync/atomic"
"testing"
"time"
"github.com/nil-go/konf"
"github.com/nil-go/konf/internal/assert"
)
func TestOnChange_nil(*testing.T) {
var config konf.Config
config.OnChange(nil) // It should not block
}
func TestConfig_Watch(t *testing.T) {
t.Parallel()
var config konf.Config
watcher := stringWatcher{key: "Config", value: make(chan string)}
err := config.Load(watcher)
assert.NoError(t, err)
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)
config.OnChange(func(config *konf.Config) {
var value string
assert.NoError(t, config.Unmarshal("config", &value))
newValue <- value
}, "config")
watcher.change()
assert.Equal(t, "changed", <-newValue)
}
func TestConfig_Watch_race(t *testing.T) {
t.Parallel()
var config konf.Config
watcher := stringWatcher{key: "Config", value: make(chan string)}
err := config.Load(watcher)
assert.NoError(t, err)
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() {
select {
case <-ctx.Done():
return
default:
var v string
_ = config.Unmarshal("config", &v)
}
}()
go func() {
defer close(stopped)
assert.NoError(t, config.Watch(ctx))
}()
newValue := make(chan string)
config.OnChange(func(config *konf.Config) {
var value string
assert.NoError(t, config.Unmarshal("config", &value))
newValue <- value
}, "config")
watcher.change()
assert.Equal(t, "changed", <-newValue)
}
func TestConfig_Watch_onchange_block(t *testing.T) {
t.Parallel()
buf := &buffer{}
config := konf.New(konf.WithLogHandler(logHandler(buf)))
watcher := stringWatcher{key: "Config", value: make(chan string)}
err := config.Load(watcher)
assert.NoError(t, err)
config.OnChange(func(*konf.Config) {
time.Sleep(time.Second)
})
ctx, cancel := context.WithTimeout(context.Background(), 10*time.Millisecond)
defer cancel()
go func() {
assert.NoError(t, config.Watch(ctx))
}()
watcher.change()
<-ctx.Done()
time.Sleep(10 * time.Millisecond) // Wait for log to be written
expected := `level=INFO msg="Configuration has been changed." loader=stringWatcher
level=WARN msg="Configuration has not been fully applied to onChanges in one minute. Please check if the onChanges is blocking or takes too long to complete."
`
assert.Equal(t, expected, buf.String())
}
func TestConfig_Watch_twice(t *testing.T) {
t.Parallel()
buf := &buffer{}
config := konf.New(konf.WithLogHandler(logHandler(buf)))
assert.NoError(t, config.Load(stringWatcher{key: "Config", value: make(chan string)}))
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))
}()
time.Sleep(100 * time.Millisecond) // Wait for watch to start
assert.NoError(t, config.Watch(ctx))
expected := "level=WARN msg=\"Config has been watched, call Watch more than once has no effects.\"\n"
assert.Equal(t, expected, buf.String())
}
func TestConfig_Watch_with_later_load(t *testing.T) {
t.Parallel()
config := konf.New()
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))
}()
time.Sleep(100 * time.Millisecond) // Wait for watch to start
watcher := stringWatcher{key: "Config", value: make(chan string)}
assert.NoError(t, config.Load(watcher))
newValue := make(chan string)
config.OnChange(func(config *konf.Config) {
var value string
assert.NoError(t, config.Unmarshal("config", &value))
newValue <- value
}, "config")
watcher.change()
assert.Equal(t, "changed", <-newValue)
}
func TestConfig_Watch_status(t *testing.T) {
t.Parallel()
var err atomic.Pointer[error]
buf := &buffer{}
config := konf.New(
konf.WithLogHandler(logHandler(buf)),
konf.WithOnStatus(func(loader konf.Loader, _ bool, e error) {
assert.Equal(t, "status", fmt.Sprintf("%s", loader))
err.Store(&e)
}),
)
assert.NoError(t, config.Load(&statusWatcher{}))
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))
}()
time.Sleep(100 * time.Millisecond) // Wait for watch to start
expected := "level=WARN msg=\"Error when loading configuration.\" loader=status error=\"watch error\"\n"
assert.Equal(t, expected, buf.String())
assert.EqualError(t, *err.Load(), "watch error")
}
func TestConfig_Watch_panic(t *testing.T) {
t.Parallel()
testcases := []struct {
description string
call func(*konf.Config)
err string
}{
{
description: "watch",
call: func(config *konf.Config) {
assert.NoError(t, config.Watch(nil)) //nolint:staticcheck
},
err: "cannot create context from nil parent",
},
}
for _, testcase := range testcases {
t.Run(testcase.description, func(t *testing.T) {
t.Parallel()
defer func() {
assert.Equal(t, testcase.err, recover().(string))
}()
var config konf.Config
assert.NoError(t, config.Load(stringWatcher{key: "Config", value: make(chan string)}))
testcase.call(&config)
t.Fail()
})
}
}
type stringWatcher struct {
key string
value chan string
}
func (m stringWatcher) Load() (map[string]any, error) {
return map[string]any{m.key: ""}, nil
}
func (m stringWatcher) Watch(ctx context.Context, fn func(map[string]any)) error {
for {
select {
case values := <-m.value:
fn(map[string]any{m.key: values})
case <-ctx.Done():
return nil
}
}
}
func (m stringWatcher) change() {
m.value <- "changed"
}
func (m stringWatcher) String() string {
return "stringWatcher"
}
func TestConfig_Watch_error(t *testing.T) {
t.Parallel()
var config konf.Config
err := config.Load(errorWatcher{})
assert.NoError(t, err)
ctx, cancel := context.WithCancel(context.Background())
defer cancel()
assert.EqualError(t, config.Watch(ctx), "watch configuration change on error: watch error")
}
type errorWatcher struct{}
func (errorWatcher) Load() (map[string]any, error) {
return nil, nil //nolint:nilnil
}
func (errorWatcher) Watch(context.Context, func(map[string]any)) error {
return errors.New("watch error")
}
func (errorWatcher) String() string {
return "error"
}
type statusWatcher struct {
onStatus func(bool, error)
}
func (*statusWatcher) Load() (map[string]any, error) {
return nil, nil //nolint:nilnil
}
func (s *statusWatcher) Watch(context.Context, func(map[string]any)) error {
s.onStatus(false, errors.New("watch error"))
return nil
}
func (s *statusWatcher) Status(onStatus func(bool, error)) {
s.onStatus = onStatus
}
func (*statusWatcher) String() string {
return "status"
}
func logHandler(buf *buffer) *slog.TextHandler {
return slog.NewTextHandler(buf, &slog.HandlerOptions{
ReplaceAttr: func(groups []string, attr slog.Attr) slog.Attr {
if len(groups) == 0 && attr.Key == slog.TimeKey {
return slog.Attr{}
}
return attr
},
})
}
type buffer struct {
b bytes.Buffer
m sync.RWMutex
}
func (b *buffer) Read(p []byte) (int, error) {
b.m.RLock()
defer b.m.RUnlock()
return b.b.Read(p)
}
func (b *buffer) Write(p []byte) (int, error) {
b.m.Lock()
defer b.m.Unlock()
return b.b.Write(p)
}
func (b *buffer) String() string {
b.m.RLock()
defer b.m.RUnlock()
return b.b.String()
}
func TestConfig_error(t *testing.T) {
t.Parallel()
var config konf.Config
err := config.Load(errorLoader{})
assert.EqualError(t, err, "load configuration: load error")
}
type errorLoader struct{}
func (errorLoader) Load() (map[string]any, error) {
return nil, errors.New("load error")
}