Debian Codegraph @

tests/koanf_test.go

raw
1 package koanf_test
2
3 import (
4 encjson "encoding/json"
5 "errors"
6 "flag"
7 "fmt"
8 "log"
9 "maps"
10 "os"
11 "path/filepath"
12 "regexp"
13 "strconv"
14 "strings"
15 "sync"
16 "sync/atomic"
17 "testing"
18 "time"
19
20 "github.com/fsnotify/fsnotify"
21 "github.com/knadh/koanf/parsers/dotenv"
22 "github.com/knadh/koanf/parsers/hcl"
23 "github.com/knadh/koanf/parsers/hjson"
24 "github.com/knadh/koanf/parsers/json"
25 "github.com/knadh/koanf/parsers/toml"
26 "github.com/knadh/koanf/parsers/yaml"
27 "github.com/knadh/koanf/providers/basicflag"
28 "github.com/knadh/koanf/providers/confmap"
29 "github.com/knadh/koanf/providers/env/v2"
30 "github.com/knadh/koanf/providers/file"
31 "github.com/knadh/koanf/providers/posflag"
32 "github.com/knadh/koanf/providers/rawbytes"
33 "github.com/knadh/koanf/v2"
34 "github.com/spf13/pflag"
35 "github.com/stretchr/testify/assert"
36 "github.com/stretchr/testify/require"
37 )
38
39 const (
40 delim = "."
41
42 mockDir = "../mock"
43 mockJSON = mockDir + "/mock.json"
44 mockYAML = mockDir + "/mock.yml"
45 mockTOML = mockDir + "/mock.toml"
46 mockHCL = mockDir + "/mock.hcl"
47 mockProp = mockDir + "/mock.prop"
48 mockDotEnv = mockDir + "/mock.env"
49 mockHJSON = mockDir + "/mock.hjson"
50 )
51
52 // Ordered list of fields in the 'flat' test confs.
53 var flatTestKeys = []string{
54 "COMMENT",
55 "MORE",
56 "MiXeD",
57 "UPPER",
58 "empty",
59 "lower",
60 "quotedSpecial",
61 }
62
63 var flatTestKeyMap = map[string][]string{
64 "COMMENT": {"COMMENT"},
65 "MORE": {"MORE"},
66 "MiXeD": {"MiXeD"},
67 "UPPER": {"UPPER"},
68 "empty": {"empty"},
69 "lower": {"lower"},
70 "quotedSpecial": {"quotedSpecial"},
71 }
72
73 var flatTestAll = `COMMENT -> AFTER
74 MORE -> vars
75 MiXeD -> CaSe
76 UPPER -> CASE
77 empty ->
78 lower -> case
79 quotedSpecial -> j18120734xn2&*@#*&R#d1j23d*(*)`
80
81 // Ordered list of fields in the test confs.
82 var testKeys = []string{
83 "bools",
84 "duration",
85 "empty",
86 "intbools",
87 "negative_int",
88 "orphan",
89 "parent1.boolmap.notok3",
90 "parent1.boolmap.ok1",
91 "parent1.boolmap.ok2",
92 "parent1.child1.empty",
93 "parent1.child1.grandchild1.ids",
94 "parent1.child1.grandchild1.on",
95 "parent1.child1.name",
96 "parent1.child1.type",
97 "parent1.floatmap.key1",
98 "parent1.floatmap.key2",
99 "parent1.floatmap.key3",
100 "parent1.id",
101 "parent1.intmap.key1",
102 "parent1.intmap.key2",
103 "parent1.intmap.key3",
104 "parent1.name",
105 "parent1.strmap.key1",
106 "parent1.strmap.key2",
107 "parent1.strmap.key3",
108 "parent1.strsmap.key1",
109 "parent1.strsmap.key2",
110 "parent2.child2.empty",
111 "parent2.child2.grandchild2.ids",
112 "parent2.child2.grandchild2.on",
113 "parent2.child2.name",
114 "parent2.id",
115 "parent2.name",
116 "strbool",
117 "strbools",
118 "time",
119 "type",
120 }
121
122 var testKeyMap = map[string][]string{
123 "bools": {"bools"},
124 "duration": {"duration"},
125 "empty": {"empty"},
126 "intbools": {"intbools"},
127 "negative_int": {"negative_int"},
128 "orphan": {"orphan"},
129 "parent1": {"parent1"},
130 "parent1.boolmap": {"parent1", "boolmap"},
131 "parent1.boolmap.notok3": {"parent1", "boolmap", "notok3"},
132 "parent1.boolmap.ok1": {"parent1", "boolmap", "ok1"},
133 "parent1.boolmap.ok2": {"parent1", "boolmap", "ok2"},
134 "parent1.child1": {"parent1", "child1"},
135 "parent1.child1.empty": {"parent1", "child1", "empty"},
136 "parent1.child1.grandchild1": {"parent1", "child1", "grandchild1"},
137 "parent1.child1.grandchild1.ids": {"parent1", "child1", "grandchild1", "ids"},
138 "parent1.child1.grandchild1.on": {"parent1", "child1", "grandchild1", "on"},
139 "parent1.child1.name": {"parent1", "child1", "name"},
140 "parent1.child1.type": {"parent1", "child1", "type"},
141 "parent1.floatmap": {"parent1", "floatmap"},
142 "parent1.floatmap.key1": {"parent1", "floatmap", "key1"},
143 "parent1.floatmap.key2": {"parent1", "floatmap", "key2"},
144 "parent1.floatmap.key3": {"parent1", "floatmap", "key3"},
145 "parent1.id": {"parent1", "id"},
146 "parent1.intmap": {"parent1", "intmap"},
147 "parent1.intmap.key1": {"parent1", "intmap", "key1"},
148 "parent1.intmap.key2": {"parent1", "intmap", "key2"},
149 "parent1.intmap.key3": {"parent1", "intmap", "key3"},
150 "parent1.name": {"parent1", "name"},
151 "parent1.strmap": {"parent1", "strmap"},
152 "parent1.strmap.key1": {"parent1", "strmap", "key1"},
153 "parent1.strmap.key2": {"parent1", "strmap", "key2"},
154 "parent1.strmap.key3": {"parent1", "strmap", "key3"},
155 "parent1.strsmap": {"parent1", "strsmap"},
156 "parent1.strsmap.key1": {"parent1", "strsmap", "key1"},
157 "parent1.strsmap.key2": {"parent1", "strsmap", "key2"},
158 "parent2": {"parent2"},
159 "parent2.child2": {"parent2", "child2"},
160 "parent2.child2.empty": {"parent2", "child2", "empty"},
161 "parent2.child2.grandchild2": {"parent2", "child2", "grandchild2"},
162 "parent2.child2.grandchild2.ids": {"parent2", "child2", "grandchild2", "ids"},
163 "parent2.child2.grandchild2.on": {"parent2", "child2", "grandchild2", "on"},
164 "parent2.child2.name": {"parent2", "child2", "name"},
165 "parent2.id": {"parent2", "id"},
166 "parent2.name": {"parent2", "name"},
167 "strbool": {"strbool"},
168 "strbools": {"strbools"},
169 "time": {"time"},
170 "type": {"type"},
171 }
172
173 // `parent1.child1.type` and `type` are excluded as their
174 // values vary between files.
175 var testAll = `bools -> [true false true]
176 duration -> 3s
177 empty -> map[]
178 intbools -> [1 0 1]
179 negative_int -> -1234
180 orphan -> [red blue orange]
181 parent1.boolmap.notok3 -> false
182 parent1.boolmap.ok1 -> true
183 parent1.boolmap.ok2 -> true
184 parent1.child1.empty -> map[]
185 parent1.child1.grandchild1.ids -> [1 2 3]
186 parent1.child1.grandchild1.on -> true
187 parent1.child1.name -> child1
188 parent1.floatmap.key1 -> 1.1
189 parent1.floatmap.key2 -> 1.2
190 parent1.floatmap.key3 -> 1.3
191 parent1.id -> 1234
192 parent1.intmap.key1 -> 1
193 parent1.intmap.key2 -> 1
194 parent1.intmap.key3 -> 1
195 parent1.name -> parent1
196 parent1.strmap.key1 -> val1
197 parent1.strmap.key2 -> val2
198 parent1.strmap.key3 -> val3
199 parent1.strsmap.key1 -> [val1 val2 val3]
200 parent1.strsmap.key2 -> [val4 val5]
201 parent2.child2.empty -> map[]
202 parent2.child2.grandchild2.ids -> [4 5 6]
203 parent2.child2.grandchild2.on -> true
204 parent2.child2.name -> child2
205 parent2.id -> 5678
206 parent2.name -> parent2
207 strbool -> 1
208 strbools -> [1 t f]
209 time -> 2019-01-01`
210
211 var testParent2 = `child2.empty -> map[]
212 child2.grandchild2.ids -> [4 5 6]
213 child2.grandchild2.on -> true
214 child2.name -> child2
215 id -> 5678
216 name -> parent2`
217
218 type parentStruct struct {
219 Name string `koanf:"name"`
220 ID int `koanf:"id"`
221 Child1 childStruct `koanf:"child1"`
222 }
223 type childStruct struct {
224 Name string `koanf:"name"`
225 Type string `koanf:"type"`
226 Empty map[string]string `koanf:"empty"`
227 Grandchild1 grandchildStruct `koanf:"grandchild1"`
228 }
229 type grandchildStruct struct {
230 Ids []int `koanf:"ids"`
231 On bool `koanf:"on"`
232 }
233 type testStruct struct {
234 Type string `koanf:"type"`
235 Empty map[string]string `koanf:"empty"`
236 Parent1 parentStruct `koanf:"parent1"`
237 }
238
239 type testStructFlat struct {
240 Type string `koanf:"type"`
241 Empty map[string]string `koanf:"empty"`
242 Parent1Name string `koanf:"parent1.name"`
243 Parent1ID int `koanf:"parent1.id"`
244 Parent1Child1Name string `koanf:"parent1.child1.name"`
245 Parent1Child1Type string `koanf:"parent1.child1.type"`
246 Parent1Child1Empty map[string]string `koanf:"parent1.child1.empty"`
247 Parent1Child1Grandchild1IDs []int `koanf:"parent1.child1.grandchild1.ids"`
248 Parent1Child1Grandchild1On bool `koanf:"parent1.child1.grandchild1.on"`
249 }
250
251 type customText int
252
253 func (c *customText) UnmarshalText(text []byte) error {
254 s := strings.ToLower(string(text))
255
256 switch {
257 case strings.HasSuffix(s, "mb"):
258 s = strings.TrimSuffix(s, "mb")
259 default:
260 s = "0"
261 }
262
263 v, err := strconv.ParseFloat(s, 64)
264 if err != nil {
265 return err
266 }
267 *c = customText(v)
268 return nil
269 }
270
271 type Case struct {
272 koanf *koanf.Koanf
273 file string
274 parser koanf.Parser
275 typeName string
276 }
277
278 // 'Flat' Case instances to be used in multiple tests. These will not be
279 // mutated.
280 var flatCases = []Case{
281 {koanf: koanf.New(delim), file: mockDotEnv, parser: dotenv.Parser(), typeName: "dotenv"},
282 }
283
284 // Case instances to be used in multiple tests. These will not be mutated.
285 var cases = []Case{
286 {koanf: koanf.New(delim), file: mockJSON, parser: json.Parser(), typeName: "json"},
287 {koanf: koanf.New(delim), file: mockYAML, parser: yaml.Parser(), typeName: "yml"},
288 {koanf: koanf.New(delim), file: mockTOML, parser: toml.Parser(), typeName: "toml"},
289 {koanf: koanf.New(delim), file: mockHCL, parser: hcl.Parser(true), typeName: "hcl"},
290 {koanf: koanf.New(delim), file: mockHJSON, parser: hjson.Parser(), typeName: "hjson"},
291 }
292
293 func init() {
294 // Preload 4 Koanf instances with their providers and config.
295 if err := cases[0].koanf.Load(file.Provider(cases[0].file), json.Parser()); err != nil {
296 log.Fatalf("error loading config file: %v", err)
297 }
298 if err := cases[1].koanf.Load(file.Provider(cases[1].file), yaml.Parser()); err != nil {
299 log.Fatalf("error loading config file: %v", err)
300 }
301 if err := cases[2].koanf.Load(file.Provider(cases[2].file), toml.Parser()); err != nil {
302 log.Fatalf("error loading config file: %v", err)
303 }
304 if err := cases[3].koanf.Load(file.Provider(cases[3].file), hcl.Parser(true)); err != nil {
305 log.Fatalf("error loading config file: %v", err)
306 }
307 if err := cases[4].koanf.Load(file.Provider(cases[4].file), hjson.Parser()); err != nil {
308 log.Fatalf("error loading config file: %v", err)
309 }
310
311 // Preload 1 'flat' Koanf instances with their providers and config.
312 if err := flatCases[0].koanf.Load(file.Provider(flatCases[0].file), dotenv.Parser()); err != nil {
313 log.Fatalf("error loading config file: %v", err)
314 }
315 }
316
317 func BenchmarkLoadFile(b *testing.B) {
318 k := koanf.New(delim)
319
320 // Don't use TOML here because it distorts memory benchmarks due to high memory use
321 providers := []*file.File{file.Provider(mockJSON), file.Provider(mockYAML)}
322 parsers := []koanf.Parser{json.Parser(), yaml.Parser()}
323
324 b.ResetTimer()
325 for n := 0; n < b.N; n++ {
326 if err := k.Load(providers[n%2], parsers[n%2]); err != nil {
327 b.Fatalf("Unexpected error: %+v", k)
328 }
329 }
330 }
331
332 func TestLoadFile(t *testing.T) {
333 // Load a non-existent file.
334 _, err := file.Provider("does-not-exist").ReadBytes()
335 assert.NotNil(t, err, "no error for non-existent file")
336
337 // Load a valid file.
338 _, err = file.Provider(mockJSON).ReadBytes()
339 assert.Nil(t, err, "error loading file")
340 }
341
342 func TestLoadFlatFileAllKeys(t *testing.T) {
343 assert := assert.New(t)
344 re, _ := regexp.Compile("(.+?)?type \\-> (.*)\n")
345 for _, c := range flatCases {
346 // Check against testKeys.
347 assert.Equal(flatTestKeys, c.koanf.Keys(), fmt.Sprintf("loaded keys mismatch: %v", c.typeName))
348
349 // Check against keyMap.
350 assert.EqualValues(flatTestKeyMap, c.koanf.KeyMap(), "keymap doesn't match")
351
352 // Replace the "type" fields that varies across different files
353 // to do a complete key -> value map match with testAll.
354 s := strings.TrimSpace(re.ReplaceAllString(c.koanf.Sprint(), ""))
355 assert.Equal(flatTestAll, s, fmt.Sprintf("key -> value list mismatch: %v", c.typeName))
356 }
357 }
358
359 func TestLoadFileAllKeys(t *testing.T) {
360 assert := assert.New(t)
361 re, _ := regexp.Compile("(.+?)?type \\-> (.*)\n")
362 for _, c := range cases {
363 // Check against testKeys.
364 assert.Equal(testKeys, c.koanf.Keys(), fmt.Sprintf("loaded keys mismatch: %v", c.typeName))
365
366 // Check against keyMap.
367 assert.EqualValues(testKeyMap, c.koanf.KeyMap(), "keymap doesn't match")
368
369 // Replace the "type" fields that varies across different files
370 // to do a complete key -> value map match with testAll.
371 s := strings.TrimSpace(re.ReplaceAllString(c.koanf.Sprint(), ""))
372 assert.Equal(testAll, s, fmt.Sprintf("key -> value list mismatch: %v", c.typeName))
373 }
374 }
375
376 func TestDelim(t *testing.T) {
377 k1 := koanf.New(".")
378 assert.Equal(t, k1.Delim(), ".")
379
380 k2 := koanf.New("/")
381 assert.Equal(t, k2.Delim(), "/")
382 }
383
384 func TestLoadMergeYamlJson(t *testing.T) {
385 var (
386 assert = assert.New(t)
387 k = koanf.New(delim)
388 )
389
390 assert.NoError(k.Load(file.Provider(mockYAML), yaml.Parser()),
391 "error loading file")
392 // loading json after yaml causes the intbools to be loaded as []float64
393 assert.NoError(k.Load(file.Provider(mockJSON), yaml.Parser()),
394 "error loading file")
395
396 // checking that there is no issues with expecting it to be an []int64
397 v := k.Int64s("intbools")
398 assert.Len(v, 3)
399
400 defer func() {
401 if err := recover(); err != nil {
402 assert.Failf("panic", "received panic: %v", err)
403 }
404 }()
405
406 v2 := k.MustInt64s("intbools")
407 assert.Len(v2, 3)
408 }
409
410 func TestLoadMergeJsonYaml(t *testing.T) {
411 var (
412 assert = assert.New(t)
413 k = koanf.New(delim)
414 )
415
416 assert.NoError(k.Load(file.Provider(mockJSON), yaml.Parser()),
417 "error loading file")
418 // loading yaml after json causes the intbools to be loaded as []int after json loaded it with []float64
419 assert.NoError(k.Load(file.Provider(mockYAML), yaml.Parser()),
420 "error loading file")
421
422 // checking that there is no issues with expecting it to be an []float64
423 v := k.Float64s("intbools")
424 assert.Len(v, 3)
425
426 defer func() {
427 if err := recover(); err != nil {
428 assert.Failf("panic", "received panic: %v", err)
429 }
430 }()
431
432 v2 := k.MustFloat64s("intbools")
433 assert.Len(v2, 3)
434 }
435
436 func TestWatchFile(t *testing.T) {
437 var (
438 assert = assert.New(t)
439 k = koanf.New(delim)
440 )
441
442 // Create a tmp config file.
443 tmpDir, _ := os.MkdirTemp("", "koanf_*") // TODO: replace with t.TempDir() as of go v1.15
444 tmpFile := filepath.Join(tmpDir, "koanf_mock")
445 err := os.WriteFile(tmpFile, []byte(`{"parent": {"name": "name1"}}`), 0600)
446 require.NoError(t, err, "error creating temp config file: %v", err)
447
448 // Load the new config and watch it for changes.
449 f := file.Provider(tmpFile)
450 k.Load(f, json.Parser())
451
452 // Watch for changes.
453 changedC := make(chan string, 1)
454 var wg sync.WaitGroup
455 wg.Add(1) // our assurance that cb is called max once
456 f.Watch(func(event any, err error) {
457 // The File watcher always returns a nil `event`, which can
458 // be ignored.
459 if err != nil {
460 // TODO: replace make with of Error Wrapping-Scheme and assert.ErrorIs() checks as of go v1.13
461 assert.Condition(func() bool {
462 return strings.Contains(err.Error(), "was removed")
463 }, "received unexpected error. err: %s", err)
464 return
465 }
466 require.NotNil(t, event, "event is nil")
467 assert.True(event.(fsnotify.Event).Has(fsnotify.Write))
468 // Reload the config.
469 k.Load(f, json.Parser())
470 changedC <- k.String("parent.name")
471 wg.Done()
472 })
473
474 // Wait a second and change the file.
475 time.Sleep(1 * time.Second)
476 os.WriteFile(tmpFile, []byte(`{"parent": {"name": "name2"}}`), 0600)
477 if waitTimeout(&wg, time.Second*10) {
478 assert.Fail("timeout waiting for file watch trigger")
479 } else {
480 assert.Condition(func() bool {
481 return strings.Compare(<-changedC, "name2") == 0
482 }, "file watch reload didn't change config")
483 }
484 }
485
486 func TestWatchFileSymlink(t *testing.T) {
487 var (
488 assert = assert.New(t)
489 k = koanf.New(delim)
490 )
491 tmpDir, _ := os.MkdirTemp("", "koanf_*") // TODO: replace with t.TempDir() as of go v1.15
492
493 // Create a symlink.
494 symPath := filepath.Join(tmpDir, "koanf_test_symlink")
495 symPath2 := filepath.Join(tmpDir, "koanf_test_symlink2")
496
497 wd, err := os.Getwd()
498 assert.NoError(err, "error getting working dir")
499
500 jsonFile := filepath.Join(wd, mockJSON)
501 yamlFile := filepath.Join(wd, mockYAML)
502
503 // Create a symlink to the JSON file which will be swapped out later.
504 assert.NoError(os.Symlink(jsonFile, symPath), "error creating symlink")
505 assert.NoError(os.Symlink(yamlFile, symPath2), "error creating symlink2")
506
507 // Load the symlink (to the JSON) file.
508 f := file.Provider(symPath)
509 k.Load(f, json.Parser())
510
511 // Watch for changes.
512 changedC := make(chan string, 1)
513 var wg sync.WaitGroup
514 wg.Add(1) // our assurance that cb is called max once
515 f.Watch(func(event any, err error) {
516 // The File watcher always returns a nil `event`, which can
517 // be ignored.
518 if err != nil {
519 // TODO: make use of Error Wrapping-Scheme and assert.ErrorIs() checks as of go v1.13
520 assert.Condition(func() bool {
521 return strings.Contains(err.Error(), "no such file or directory")
522 }, "received unexpected error. err: %s", err)
523 return
524 }
525 // Reload the config.
526 k.Load(f, yaml.Parser())
527 changedC <- k.String("type")
528 wg.Done()
529 })
530
531 // Wait a second and swap the symlink target from the JSON file to the YAML file.
532 // Create a temp symlink to the YAML file and rename the old symlink to the new
533 // symlink. We do this to avoid removing the symlink and triggering a REMOVE event.
534 time.Sleep(1 * time.Second)
535 assert.NoError(os.Rename(symPath2, symPath), "error swapping symlink to another file type")
536 if waitTimeout(&wg, time.Second*10) {
537 assert.Fail("timeout waiting for file watch trigger")
538 } else {
539 assert.Condition(func() bool {
540 return strings.Compare(<-changedC, "yml") == 0
541 }, "symlink watch reload didn't change config")
542 }
543 }
544
545 func TestWatchFileDirectorySymlink(t *testing.T) {
546 var (
547 assert = assert.New(t)
548 k = koanf.New(delim)
549 )
550 tmpDir := t.TempDir()
551
552 baseDir := filepath.Join(tmpDir, "base_dir")
553 baseDir2 := filepath.Join(tmpDir, "base_dir2")
554
555 err := os.Mkdir(baseDir, 0700)
556 assert.NoError(err, "error creating base dir")
557
558 err = os.Mkdir(baseDir2, 0700)
559 assert.NoError(err, "error creating base dir 2")
560
561 wd, err := os.Getwd()
562 assert.NoError(err, "error getting working dir")
563
564 jsonFile := filepath.Join(wd, mockJSON)
565 yamlFile := filepath.Join(wd, mockYAML)
566
567 jsonData, err := os.ReadFile(jsonFile)
568 assert.NoError(err, "error reading JSON file")
569
570 err = os.WriteFile(filepath.Join(baseDir, "config"), jsonData, 0600)
571 assert.NoError(err, "error writing JSON file to base dir")
572
573 yamlData, err := os.ReadFile(yamlFile)
574 assert.NoError(err, "error reading YAML file")
575
576 err = os.WriteFile(filepath.Join(baseDir2, "config"), yamlData, 0600)
577 assert.NoError(err, "error writing YAML file to base dir 2")
578
579 // Create a symlink.
580 symDir := filepath.Join(tmpDir, "koanf_test_symlink")
581 symDir2 := filepath.Join(tmpDir, "koanf_test_symlink2")
582 symPath := filepath.Join(tmpDir, "config")
583
584 // Create a symlink to the JSON file which will be swapped out later.
585 assert.NoError(os.Symlink(baseDir, symDir), "error creating symlink dir")
586 assert.NoError(os.Symlink(baseDir2, symDir2), "error creating symlink dir2")
587 assert.NoError(os.Symlink(filepath.Join(symDir, "config"), symPath), "error creating symlink")
588
589 // Load the symlink (to the JSON) file.
590 f := file.Provider(symPath)
591 k.Load(f, json.Parser())
592
593 // Watch for changes.
594 changedC := make(chan string, 1)
595 var wg sync.WaitGroup
596 wg.Add(1) // our assurance that cb is called max once
597 f.Watch(func(event any, err error) {
598 // The File watcher always returns a nil `event`, which can
599 // be ignored.
600 if err != nil {
601 // TODO: make use of Error Wrapping-Scheme and assert.ErrorIs() checks as of go v1.13
602 assert.Condition(func() bool {
603 return strings.Contains(err.Error(), "no such file or directory")
604 }, "received unexpected error. err: %s", err)
605 return
606 }
607 // Reload the config.
608 k.Load(f, yaml.Parser())
609 changedC <- k.String("type")
610 wg.Done()
611 })
612
613 // Wait a second and swap the symlink target from the JSON file to the YAML file.
614 // Create a temp symlink to the YAML file and rename the old symlink to the new
615 // symlink. We do this to avoid removing the symlink and triggering a REMOVE event.
616 time.Sleep(1 * time.Second)
617 assert.NoError(os.Rename(symDir2, symDir), "error swapping symlink dir to another symlink dir")
618
619 if waitTimeout(&wg, time.Second*10) {
620 assert.Fail("timeout waiting for file watch trigger")
621 } else {
622 assert.Condition(func() bool {
623 return strings.Compare(<-changedC, "yml") == 0
624 }, "symlink watch reload didn't change config")
625 }
626 }
627
628 func TestUnwatchFile(t *testing.T) {
629 var (
630 assert = assert.New(t)
631 k = koanf.New(delim)
632 )
633
634 // Create a tmp config file.
635 tmpDir := t.TempDir()
636 tmpFile := filepath.Join(tmpDir, "koanf_mock")
637 require.NoError(t, os.WriteFile(tmpFile, []byte(`{"parent": {"name": "name1"}}`), 0600))
638
639 // Load the new config file.
640 f := file.Provider(tmpFile)
641 k.Load(f, json.Parser())
642
643 // Watch.
644 var reloaded int32
645 f.Watch(func(event any, err error) {
646 atomic.StoreInt32(&reloaded, 1)
647 assert.NoError(err)
648 })
649
650 // Change the file and check whether the watch triggered.
651 time.Sleep(100 * time.Millisecond)
652 os.WriteFile(tmpFile, []byte(`{"parent": {"name": "name2"}}`), 0600)
653 time.Sleep(100 * time.Millisecond)
654 assert.True(atomic.LoadInt32(&reloaded) == 1, "watched file didn't reload")
655
656 // Unwatch the file and verify that the watch didn't trigger.
657 assert.NoError(f.Unwatch())
658 atomic.StoreInt32(&reloaded, 0)
659 time.Sleep(100 * time.Millisecond)
660 os.WriteFile(tmpFile, []byte(`{"parent": {"name": "name3"}}`), 0600)
661 time.Sleep(100 * time.Millisecond)
662 assert.False(atomic.LoadInt32(&reloaded) == 1, "unwatched file reloaded")
663
664 // Re-watch and check again.
665 atomic.StoreInt32(&reloaded, 0)
666 f.Watch(func(event any, err error) {
667 atomic.StoreInt32(&reloaded, 1)
668 assert.NoError(err)
669 })
670 os.WriteFile(tmpFile, []byte(`{"parent": {"name": "name4"}}`), 0600)
671 time.Sleep(100 * time.Millisecond)
672 assert.True(atomic.LoadInt32(&reloaded) == 1, "watched file didn't reload")
673
674 f.Unwatch()
675 }
676
677 func TestLoadMerge(t *testing.T) {
678 var (
679 assert = assert.New(t)
680 // Load several types into a fresh Koanf instance.
681 k = koanf.New(delim)
682 )
683 for _, c := range cases {
684 assert.Nil(k.Load(file.Provider(c.file), c.parser),
685 fmt.Sprintf("error loading: %v", c.file))
686
687 // Check against testKeys.
688 assert.Equal(testKeys, k.Keys(), fmt.Sprintf("loaded keys don't match in: %v", c.file))
689
690 // The 'type' fields in different file types have different values.
691 // As each subsequent file is loaded, the previous value should be overridden.
692 assert.Equal(c.typeName, k.String("type"), "types don't match")
693 assert.Equal(c.typeName, k.String("parent1.child1.type"), "types don't match")
694 }
695
696 // Load env provider and override value.
697 t.Setenv("PREFIX_PARENT1.CHILD1.TYPE", "env")
698
699 err := k.Load(env.Provider(".", env.Opt{
700 Prefix: "PREFIX_",
701 TransformFunc: func(k, v string) (string, any) {
702 return strings.ReplaceAll(strings.ToLower(k), "prefix_", ""), v
703 },
704 }), nil)
705
706 assert.Nil(err, "error loading env")
707 assert.Equal("env", k.String("parent1.child1.type"), "types don't match")
708
709 // Test the env provider than can mutate the value to upper case
710 err = k.Load(env.Provider(".", env.Opt{
711 Prefix: "PREFIX_",
712 TransformFunc: func(k string, v string) (string, any) {
713 return strings.ReplaceAll(strings.ToLower(k), "prefix_", ""), strings.ToUpper(v)
714 },
715 }), nil)
716
717 assert.Nil(err, "error loading env with value")
718 assert.Equal("ENV", k.String("parent1.child1.type"), "types don't match")
719
720 // Override with the confmap provider.
721 k.Load(confmap.Provider(map[string]any{
722 "parent1.child1.type": "confmap",
723 "type": "confmap",
724 }, "."), nil)
725 assert.Equal("confmap", k.String("parent1.child1.type"), "types don't match")
726 assert.Equal("confmap", k.String("type"), "types don't match")
727
728 // Override with the rawbytes provider.
729 assert.Nil(k.Load(rawbytes.Provider([]byte(`{"type": "rawbytes", "parent1": {"child1": {"type": "rawbytes"}}}`)), json.Parser()),
730 "error loading raw bytes")
731 assert.Equal("rawbytes", k.String("parent1.child1.type"), "types don't match")
732 assert.Equal("rawbytes", k.String("type"), "types don't match")
733 }
734
735 func TestFlags(t *testing.T) {
736 var (
737 assert = assert.New(t)
738 def = koanf.New(delim)
739 )
740 assert.Nil(def.Load(file.Provider(mockJSON), json.Parser()), "error loading file")
741
742 // Override with the posflag provider.
743 f := pflag.NewFlagSet("test", pflag.ContinueOnError)
744
745 // Key that exists in the loaded conf. Should overwrite with Set().
746 f.String("parent1.child1.type", "flag", "")
747 f.Set("parent1.child1.type", "flag")
748 f.StringSlice("stringslice", []string{"a", "b", "c"}, "")
749 f.IntSlice("intslice", []int{1, 2, 3}, "")
750
751 // Key that doesn't exist in the loaded file conf. Should merge the default value.
752 f.String("flagkey", "flag", "")
753
754 // Key that exists in the loaded conf but no Set(). Default value shouldn't be merged.
755 f.String("parent1.name", "flag", "")
756
757 // Initialize the provider with the Koanf instance passed where default values
758 // will merge if the keys are not present in the conf map.
759 {
760 k := def.Copy()
761 assert.Nil(k.Load(posflag.Provider(f, ".", k), nil), "error loading posflag")
762 assert.Equal("flag", k.String("parent1.child1.type"), "types don't match")
763 assert.Equal("flag", k.String("flagkey"), "value doesn't match")
764 assert.NotEqual("flag", k.String("parent1.name"), "value doesn't match")
765 assert.Equal([]string{"a", "b", "c"}, k.Strings("stringslice"), "value doesn't match")
766 assert.Equal([]int{1, 2, 3}, k.Ints("intslice"), "value doesn't match")
767 }
768
769 // Test the posflag provider can mutate the value to upper case
770 {
771 k := def.Copy()
772 assert.Nil(k.Load(posflag.ProviderWithValue(f, ".", nil, func(k string, v string) (string, any) {
773 return strings.Replace(strings.ToLower(k), "prefix_", "", -1), strings.ToUpper(v)
774 }), nil), "error loading posflag")
775 assert.Equal("FLAG", k.String("parent1.child1.type"), "types don't match")
776 }
777
778 // Test without passing the Koanf instance where default values will not merge.
779 {
780 k := def.Copy()
781 assert.Nil(k.Load(posflag.Provider(f, ".", nil), nil), "error loading posflag")
782 assert.Equal("flag", k.String("parent1.child1.type"), "types don't match")
783 assert.Equal("", k.String("flagkey"), "value doesn't match")
784 assert.NotEqual("", k.String("parent1.name"), "value doesn't match")
785 }
786
787 // Override with the basicflag provider.
788 {
789 k := def.Copy()
790 bf := flag.NewFlagSet("test", flag.ContinueOnError)
791 bf.String("parent1.child1.type", "flag", "")
792 bf.String("parent2.child2.name", "override-default", "")
793 bf.Set("parent1.child1.type", "basicflag")
794 assert.Nil(k.Load(basicflag.Provider(bf, "."), nil), "error loading basicflag")
795 assert.Equal("basicflag", k.String("parent1.child1.type"), "types don't match")
796 assert.Equal("override-default", k.String("parent2.child2.name"), "basicflag default value override failed")
797 }
798
799 // No default-value override behaviour.
800 {
801 k := def.Copy()
802 bf := flag.NewFlagSet("test", flag.ContinueOnError)
803 bf.String("parent1.child1.name", "override-default", "")
804 bf.String("parent2.child2.name", "override-default", "")
805 bf.Set("parent2.child2.name", "custom")
806 assert.Nil(k.Load(basicflag.Provider(bf, ".", &basicflag.Opt{KeyMap: def}), nil), "error loading basicflag")
807 assert.Equal("child1", k.String("parent1.child1.name"), "basicflag default overwrote")
808 assert.Equal("custom", k.String("parent2.child2.name"), "basicflag set failed")
809 }
810
811 // Override with the basicflag provider.
812 {
813 k := def.Copy()
814 bf := flag.NewFlagSet("test", flag.ContinueOnError)
815 bf.String("parent1.child1.type", "flag", "")
816 bf.String("parent2.child2.name", "override-default", "")
817 bf.Set("parent1.child1.type", "basicflag")
818 assert.Nil(k.Load(basicflag.ProviderWithValue(bf, ".", nil), nil), "error loading basicflag")
819 assert.Equal("basicflag", k.String("parent1.child1.type"), "types don't match")
820 assert.Equal("override-default", k.String("parent2.child2.name"), "basicflag default value override failed")
821 }
822
823 // No default-value override behaviour.
824 {
825 k := def.Copy()
826 bf := flag.NewFlagSet("test", flag.ContinueOnError)
827 bf.String("parent1.child1.name", "override-default", "")
828 bf.String("parent2.child2.name", "override-default", "")
829 bf.Set("parent2.child2.name", "custom")
830 assert.Nil(k.Load(basicflag.ProviderWithValue(bf, ".", nil, def), nil), "error loading basicflag")
831 assert.Equal("child1", k.String("parent1.child1.name"), "basicflag default overwrote")
832 assert.Equal("custom", k.String("parent2.child2.name"), "basicflag set failed")
833 }
834
835 // Override with the basicflag provider.
836 {
837 k := def.Copy()
838 bf := flag.NewFlagSet("test", flag.ContinueOnError)
839 bf.String("parent1.child1.type", "flag", "")
840 bf.Set("parent1.child1.type", "basicflag")
841 assert.Nil(k.Load(basicflag.Provider(bf, "."), nil), "error loading basicflag")
842 assert.Equal("basicflag", k.String("parent1.child1.type"), "types don't match")
843 }
844
845 // Test the basicflag provider can mutate the value to upper case
846 {
847 k := def.Copy()
848 bf := flag.NewFlagSet("test", flag.ContinueOnError)
849 bf.String("parent1.child1.type", "flag", "")
850 bf.Set("parent1.child1.type", "basicflag")
851 assert.Nil(k.Load(basicflag.ProviderWithValue(bf, ".", func(k string, v string) (string, any) {
852 return strings.Replace(strings.ToLower(k), "prefix_", "", -1), strings.ToUpper(v)
853 }), nil), "error loading basicflag")
854 assert.Equal("BASICFLAG", k.String("parent1.child1.type"), "types don't match")
855 }
856 }
857
858 func TestConfMapValues(t *testing.T) {
859 var (
860 assert = assert.New(t)
861 k = koanf.New(delim)
862 )
863 assert.Nil(k.Load(file.Provider(mockJSON), json.Parser()), "error loading file")
864 var (
865 c1 = k.All()
866 ra1 = k.Raw()
867 r1 = k.Cut("parent2").Raw()
868 )
869
870 k = koanf.New(delim)
871 assert.Nil(k.Load(file.Provider(mockJSON), json.Parser()), "error loading file")
872 var (
873 c2 = k.All()
874 ra2 = k.Raw()
875 r2 = k.Cut("parent2").Raw()
876 )
877
878 assert.EqualValues(c1, c2, "conf map mismatch")
879 assert.EqualValues(ra1, ra2, "conf map mismatch")
880 assert.EqualValues(r1, r2, "conf map mismatch")
881 }
882
883 func TestCutCopy(t *testing.T) {
884 // Instance 1.
885 var (
886 assert = assert.New(t)
887 k1 = koanf.New(delim)
888 )
889 assert.Nil(k1.Load(file.Provider(mockJSON), json.Parser()),
890 "error loading file")
891 var (
892 cp1 = k1.Copy()
893 cut1 = k1.Cut("")
894 cutp1 = k1.Cut("parent2")
895 )
896
897 // Instance 2.
898 k2 := koanf.New(delim)
899 assert.Nil(k2.Load(file.Provider(mockJSON), json.Parser()),
900 "error loading file")
901 var (
902 cp2 = k2.Copy()
903 cut2 = k2.Cut("")
904 cutp2 = k2.Cut("parent2")
905 )
906
907 assert.EqualValues(cp1.All(), cp2.All(), "conf map mismatch")
908 assert.EqualValues(cut1.All(), cut2.All(), "conf map mismatch")
909 assert.EqualValues(cutp1.All(), cutp2.All(), "conf map mismatch")
910 assert.Equal(testParent2, strings.TrimSpace(cutp1.Sprint()), "conf map mismatch")
911 assert.Equal(strings.TrimSpace(cutp1.Sprint()), strings.TrimSpace(cutp2.Sprint()), "conf map mismatch")
912
913 // Cut a single field with no children. Should return empty conf maps.
914 assert.Equal(k1.Cut("type").Keys(), k2.Cut("type").Keys(), "single field cut mismatch")
915 assert.Equal(k1.Cut("xxxx").Keys(), k2.Cut("xxxx").Keys(), "single field cut mismatch")
916 assert.Equal(len(k1.Cut("type").Raw()), 0, "non-map cut returned items")
917 }
918
919 func TestWithMergeFunc(t *testing.T) {
920 var (
921 assert = assert.New(t)
922 k = koanf.New(delim)
923 )
924
925 assert.NoError(k.Load(rawbytes.Provider([]byte(`{"foo":"bar"}`)), json.Parser()))
926 assert.NoError(k.Load(rawbytes.Provider([]byte(`{"baz":"bar"}`)), json.Parser(), koanf.WithMergeFunc(func(a, b map[string]any) error {
927 // No merge
928 return nil
929 })))
930
931 assert.Equal(map[string]any{
932 "foo": "bar",
933 }, k.All(), "expects the result of the first load only")
934
935 err := errors.New("stub")
936 assert.ErrorIs(k.Load(rawbytes.Provider([]byte(`{"baz":"bar"}`)), json.Parser(), koanf.WithMergeFunc(func(a, b map[string]any) error {
937 return err
938 })), err, "expects the error thrown by WithMergeFunc")
939 }
940
941 func TestWithMergeFuncGetNoDeadlock(t *testing.T) {
942 k := koanf.New(delim)
943
944 require.NoError(t, k.Load(rawbytes.Provider([]byte(`{"key":"old"}`)), json.Parser()))
945
946 done := make(chan struct{})
947 go func() {
948 defer close(done)
949 err := k.Load(rawbytes.Provider([]byte(`{"key":"new"}`)), json.Parser(), koanf.WithMergeFunc(func(src, dest map[string]any) error {
950 // Calling a typed getter inside the merge func must not deadlock.
951 _ = k.String("key")
952 maps.Copy(dest, src)
953 return nil
954 }))
955 require.NoError(t, err)
956 }()
957
958 select {
959 case <-done:
960 case <-time.After(5 * time.Second):
961 t.Fatal("deadlock: merge func calling GetString blocked for 5s")
962 }
963
964 assert.New(t).Equal("new", k.String("key"))
965 }
966
967 func TestMerge(t *testing.T) {
968 var (
969 assert = assert.New(t)
970 k = koanf.New(delim)
971 )
972 assert.Nil(k.Load(file.Provider(mockJSON), json.Parser()),
973 "error loading file")
974
975 // Make two different cuts that'll have different confmaps.
976 var (
977 cut1 = k.Cut("parent1")
978 cut2 = k.Cut("parent2")
979 )
980 assert.NotEqual(cut1.All(), cut2.All(), "different cuts incorrectly match")
981 assert.NotEqual(cut1.Sprint(), cut2.Sprint(), "different cuts incorrectly match")
982
983 // Create an empty Koanf instance.
984 k2 := koanf.New(delim)
985
986 // Merge cut1 into it and check if they match.
987 k2.Merge(cut1)
988 assert.Equal(cut1.All(), k2.All(), "conf map mismatch")
989 }
990
991 func TestRaw_YamlTypes(t *testing.T) {
992 var (
993 assert = assert.New(t)
994 k = koanf.New(delim)
995 )
996
997 assert.Nil(k.Load(file.Provider(mockYAML), yaml.Parser()),
998 "error loading file")
999 raw := k.Raw()
1000
1001 i, ok := raw["intbools"]
1002 assert.True(ok, "ints key does not exist in the map")
1003
1004 arr, ok := i.([]any)
1005 assert.True(ok, "arr slice is not array of integers")
1006
1007 for _, integer := range arr {
1008 if _, ok := integer.(int); !ok {
1009 assert.Failf("failure", "%v not an integer but %T", integer, integer)
1010 }
1011 }
1012 }
1013
1014 func TestRaw_JsonTypes(t *testing.T) {
1015 var (
1016 assert = assert.New(t)
1017 k = koanf.New(delim)
1018 )
1019
1020 assert.Nil(k.Load(file.Provider(mockJSON), json.Parser()),
1021 "error loading file")
1022 raw := k.Raw()
1023
1024 i, ok := raw["intbools"]
1025 assert.True(ok, "ints key does not exist in the map")
1026
1027 arr, ok := i.([]any)
1028 assert.True(ok, "arr slice is not array of integers")
1029
1030 for _, integer := range arr {
1031 if _, ok := integer.(float64); !ok {
1032 assert.Failf("failure", "%v not an integer but %T", integer, integer)
1033 }
1034 }
1035 }
1036
1037 func TestMergeStrictError(t *testing.T) {
1038 assert := assert.New(t)
1039
1040 ks := koanf.NewWithConf(koanf.Conf{
1041 Delim: delim,
1042 StrictMerge: true,
1043 })
1044
1045 assert.Nil(ks.Load(confmap.Provider(map[string]any{
1046 "parent2": map[string]any{
1047 "child2": map[string]any{
1048 "grandchild2": map[string]any{
1049 "ids": 123,
1050 },
1051 },
1052 },
1053 }, delim), nil))
1054
1055 err := ks.Load(file.Provider(mockYAML), yaml.Parser())
1056 assert.Error(err)
1057 assert.True(strings.HasPrefix(err.Error(), "incorrect types at key parent2.child2.grandchild2"))
1058 }
1059
1060 func TestMergeAt(t *testing.T) {
1061 var (
1062 assert = assert.New(t)
1063 k = koanf.New(delim)
1064 )
1065 assert.Nil(k.Load(file.Provider(mockYAML), yaml.Parser()),
1066 "error loading file")
1067
1068 // Get expected koanf, and root data
1069 var (
1070 expected = k.Cut("parent2")
1071 rootData = map[string]any{
1072 "name": k.String("parent2.name"),
1073 "id": k.Int("parent2.id"),
1074 }
1075 )
1076
1077 // Get nested test data to merge at path
1078 child2 := koanf.New(delim)
1079 assert.Nil(child2.Load(confmap.Provider(map[string]any{
1080 "name": k.String("parent2.child2.name"),
1081 "empty": k.Get("parent2.child2.empty"),
1082 }, delim), nil))
1083 grandChild := k.Cut("parent2.child2.grandchild2")
1084
1085 // Create test koanf
1086 ordered := koanf.New(delim)
1087 assert.Nil(ordered.Load(confmap.Provider(rootData, delim), nil))
1088
1089 // Merge at path in order, first child2, then child2.grandchild2
1090 ordered.MergeAt(child2, "child2")
1091 ordered.MergeAt(grandChild, "child2.grandchild2")
1092 assert.Equal(expected.Get(""), ordered.Get(""), "conf map mismatch")
1093
1094 // Create test koanf
1095 reversed := koanf.New(delim)
1096 assert.Nil(reversed.Load(confmap.Provider(rootData, delim), nil))
1097
1098 // Merge at path in reverse order, first child2.grandchild2, then child2
1099 reversed.MergeAt(grandChild, "child2.grandchild2")
1100 reversed.MergeAt(child2, "child2")
1101 assert.Equal(expected.Get(""), reversed.Get(""), "conf map mismatch")
1102 }
1103
1104 func TestSet(t *testing.T) {
1105 var (
1106 assert = assert.New(t)
1107 k = koanf.New(delim)
1108 )
1109 assert.Nil(k.Load(file.Provider(mockYAML), yaml.Parser()),
1110 "error loading file")
1111
1112 assert.Nil(k.Set("parent1.name", "new"))
1113 assert.Equal(k.String("parent1.name"), "new")
1114
1115 assert.Nil(k.Set("parent1.child1.name", 123))
1116 assert.Equal(k.Int("parent1.child1.name"), 123)
1117
1118 assert.Nil(k.Set("parent1.child1.grandchild1.ids", []int{5}))
1119 assert.Equal(k.Ints("parent1.child1.grandchild1.ids"), []int{5})
1120
1121 assert.Nil(k.Set("parent1.child1.grandchild1", 123))
1122 assert.Equal(k.Int("parent1.child1.grandchild1"), 123)
1123 assert.Equal(k.Int("parent1.child1.grandchild1.ids"), 0)
1124
1125 assert.Nil(k.Set("parent1.child1.grandchild1", map[string]any{"name": "new"}))
1126 assert.Equal(k.Get("parent1.child1.grandchild1"), map[string]any{"name": "new"})
1127 }
1128
1129 func TestUnmarshal(t *testing.T) {
1130 assert := assert.New(t)
1131
1132 // Expected unmarshalled structure.
1133 real := testStruct{
1134 Type: "json",
1135 Empty: make(map[string]string),
1136 Parent1: parentStruct{
1137 Name: "parent1",
1138 ID: 1234,
1139 Child1: childStruct{
1140 Name: "child1",
1141 Type: "json",
1142 Empty: make(map[string]string),
1143 Grandchild1: grandchildStruct{
1144 Ids: []int{1, 2, 3},
1145 On: true,
1146 },
1147 },
1148 },
1149 }
1150
1151 // Unmarshal and check all parsers.
1152 for _, c := range cases {
1153 var (
1154 k = koanf.New(delim)
1155 ts testStruct
1156 )
1157 assert.Nil(k.Load(file.Provider(c.file), c.parser),
1158 fmt.Sprintf("error loading: %v", c.file))
1159 assert.Nil(k.Unmarshal("", &ts), "unmarshal failed")
1160 real.Type = c.typeName
1161 real.Parent1.Child1.Type = c.typeName
1162 assert.Equal(real, ts, "unmarshalled structs don't match")
1163
1164 // Unmarshal with config.
1165 ts = testStruct{}
1166 assert.Nil(k.UnmarshalWithConf("", &ts, koanf.UnmarshalConf{Tag: "koanf"}), "unmarshal failed")
1167 real.Type = c.typeName
1168 real.Parent1.Child1.Type = c.typeName
1169 assert.Equal(real, ts, "unmarshalled structs don't match")
1170 }
1171 }
1172
1173 func TestUnmarshalFlat(t *testing.T) {
1174 assert := assert.New(t)
1175
1176 // Expected unmarshalled structure.
1177 real := testStructFlat{
1178 Type: "json",
1179 Empty: make(map[string]string),
1180 Parent1Name: "parent1",
1181 Parent1ID: 1234,
1182 Parent1Child1Name: "child1",
1183 Parent1Child1Type: "json",
1184 Parent1Child1Empty: make(map[string]string),
1185 Parent1Child1Grandchild1IDs: []int{1, 2, 3},
1186 Parent1Child1Grandchild1On: true,
1187 }
1188
1189 // Unmarshal and check all parsers.
1190 for _, c := range cases {
1191 k := koanf.New(delim)
1192 assert.Nil(k.Load(file.Provider(c.file), c.parser),
1193 fmt.Sprintf("error loading: %v", c.file))
1194 ts := testStructFlat{}
1195 assert.Nil(k.UnmarshalWithConf("", &ts, koanf.UnmarshalConf{Tag: "koanf", FlatPaths: true}), "unmarshal failed")
1196 real.Type = c.typeName
1197 real.Parent1Child1Type = c.typeName
1198 assert.Equal(real, ts, "unmarshalled structs don't match")
1199 }
1200 }
1201
1202 func TestUnmarshalCustomText(t *testing.T) {
1203 test := struct {
1204 V1 customText `koanf:"v1"`
1205 V2 string `koanf:"v2"`
1206 V3 customText `koanf:"v3"`
1207 }{}
1208
1209 // Test custom unmarshalling of strings via mapstructure's UnmarshalText()
1210 // methods. customText is an int type that strips of the `mb` suffix and parses
1211 // the rest into a number.
1212
1213 k := koanf.New(delim)
1214 err := k.Load(rawbytes.Provider([]byte(`{"v1": "42mb", "v2": "42mb"}`)), json.Parser())
1215 assert.NoError(t, err)
1216
1217 k.Unmarshal("", &test)
1218 assert.Equal(t, int(test.V1), 42)
1219 assert.Equal(t, test.V2, "42mb")
1220 assert.Equal(t, int(test.V3), 0)
1221 }
1222
1223 func TestMarshal(t *testing.T) {
1224 assert := assert.New(t)
1225
1226 for _, c := range cases {
1227 // HCL does not support marshalling.
1228 if c.typeName == "hcl" {
1229 continue
1230 }
1231
1232 // Load config.
1233 k := koanf.New(delim)
1234 assert.NoError(k.Load(file.Provider(c.file), c.parser),
1235 fmt.Sprintf("error loading: %v", c.file))
1236
1237 // Serialize / marshal into raw bytes using the parser.
1238 b, err := k.Marshal(c.parser)
1239 assert.NoError(err, "error marshalling")
1240
1241 // Reload raw serialize bytes into a new koanf instance.
1242 k = koanf.New(delim)
1243 assert.NoError(k.Load(rawbytes.Provider(b), c.parser),
1244 fmt.Sprintf("error loading: %v", c.file))
1245
1246 // Check if values are intact.
1247 assert.Equal(float64(1234), c.koanf.MustFloat64("parent1.id"))
1248 assert.Equal([]string{"red", "blue", "orange"}, c.koanf.MustStrings("orphan"))
1249 assert.Equal([]int64{1, 2, 3}, c.koanf.MustInt64s("parent1.child1.grandchild1.ids"))
1250 }
1251 }
1252
1253 func TestGetExists(t *testing.T) {
1254 assert := assert.New(t)
1255
1256 type exCase struct {
1257 path string
1258 exists bool
1259 }
1260 exCases := []exCase{
1261 {"xxxxx", false},
1262 {"parent1.child2", false},
1263 {"child1", false},
1264 {"child2", false},
1265 {"type", true},
1266 {"parent1", true},
1267 {"parent2", true},
1268 {"parent1.name", true},
1269 {"parent2.name", true},
1270 {"parent1.child1", true},
1271 {"parent2.child2", true},
1272 {"parent1.child1.grandchild1", true},
1273 {"parent1.child1.grandchild1.on", true},
1274 {"parent2.child2.grandchild2.on", true},
1275 }
1276 for _, c := range exCases {
1277 assert.Equal(c.exists, cases[0].koanf.Exists(c.path),
1278 fmt.Sprintf("path resolution failed: %s", c.path))
1279 assert.Equal(c.exists, cases[0].koanf.Get(c.path) != nil,
1280 fmt.Sprintf("path resolution failed: %s", c.path))
1281 }
1282 }
1283
1284 func TestSlices(t *testing.T) {
1285 assert := assert.New(t)
1286
1287 // Load a slice of confmaps [{}, {}].
1288 var mp map[string]any
1289 err := encjson.Unmarshal([]byte(`{
1290 "parent": [
1291 {"value": 1, "sub": {"value": "1"}},
1292 {"value": 2, "sub": {"value": "2"}}
1293 ],
1294 "another": "123"
1295 }`), &mp)
1296 assert.NoError(err, "error marshalling test payload")
1297 k := koanf.New(delim)
1298 assert.NoError(k.Load(confmap.Provider(mp, "."), nil))
1299
1300 assert.Empty(k.Slices("x"))
1301 assert.Empty(k.Slices("parent.value"))
1302 assert.Empty(k.Slices("parent.value.sub"))
1303
1304 slices := k.Slices("parent")
1305 assert.NotNil(slices, "got nil slice of confmap")
1306 assert.NotEmpty(slices, "got empty confmap slice")
1307
1308 for i, s := range slices {
1309 assert.Equal(s.Int("value"), i+1)
1310 assert.Equal(s.String("sub.value"), fmt.Sprintf("%d", i+1))
1311 }
1312 }
1313
1314 func TestGetTypes(t *testing.T) {
1315 assert := assert.New(t)
1316 for _, c := range cases {
1317 assert.Equal(nil, c.koanf.Get("xxx"))
1318 assert.Equal(make(map[string]any), c.koanf.Get("empty"))
1319
1320 // Int.
1321 assert.Equal(int64(0), c.koanf.Int64("xxxx"))
1322 assert.Equal(int64(1234), c.koanf.Int64("parent1.id"))
1323
1324 assert.Equal(int(0), c.koanf.Int("xxxx"))
1325 assert.Equal(int(1234), c.koanf.Int("parent1.id"))
1326
1327 assert.Equal([]int64{}, c.koanf.Int64s("xxxx"))
1328 assert.Equal([]int64{1, 2, 3}, c.koanf.Int64s("parent1.child1.grandchild1.ids"))
1329
1330 assert.Equal(map[string]int64{"key1": 1, "key2": 1, "key3": 1}, c.koanf.Int64Map("parent1.intmap"))
1331 assert.Equal(map[string]int64{}, c.koanf.Int64Map("parent1.boolmap"))
1332 assert.Equal(map[string]int64{}, c.koanf.Int64Map("xxxx"))
1333 assert.Equal(map[string]int64{"key1": 1, "key2": 1, "key3": 1}, c.koanf.Int64Map("parent1.floatmap"))
1334
1335 assert.Equal([]int{1, 2, 3}, c.koanf.Ints("parent1.child1.grandchild1.ids"))
1336 assert.Equal([]int{}, c.koanf.Ints("xxxx"))
1337
1338 assert.Equal(map[string]int{"key1": 1, "key2": 1, "key3": 1}, c.koanf.IntMap("parent1.intmap"))
1339 assert.Equal(map[string]int{}, c.koanf.IntMap("parent1.boolmap"))
1340 assert.Equal(map[string]int{}, c.koanf.IntMap("xxxx"))
1341
1342 // Float.
1343 assert.Equal(float64(0), c.koanf.Float64("xxx"))
1344 assert.Equal(float64(1234), c.koanf.Float64("parent1.id"))
1345
1346 assert.Equal([]float64{}, c.koanf.Float64s("xxxx"))
1347 assert.Equal([]float64{1, 2, 3}, c.koanf.Float64s("parent1.child1.grandchild1.ids"))
1348
1349 assert.Equal(map[string]float64{"key1": 1, "key2": 1, "key3": 1}, c.koanf.Float64Map("parent1.intmap"))
1350 assert.Equal(map[string]float64{"key1": 1.1, "key2": 1.2, "key3": 1.3}, c.koanf.Float64Map("parent1.floatmap"))
1351 assert.Equal(map[string]float64{}, c.koanf.Float64Map("parent1.boolmap"))
1352 assert.Equal(map[string]float64{}, c.koanf.Float64Map("xxxx"))
1353
1354 // String and bytes.
1355 assert.Equal([]byte{}, c.koanf.Bytes("xxxx"))
1356 assert.Equal([]byte("parent1"), c.koanf.Bytes("parent1.name"))
1357
1358 assert.Equal("", c.koanf.String("xxxx"))
1359 assert.Equal("parent1", c.koanf.String("parent1.name"))
1360
1361 assert.Equal([]string{}, c.koanf.Strings("xxxx"))
1362 assert.Equal([]string{"red", "blue", "orange"}, c.koanf.Strings("orphan"))
1363
1364 assert.Equal(map[string]string{"key1": "val1", "key2": "val2", "key3": "val3"}, c.koanf.StringMap("parent1.strmap"))
1365 assert.Equal(map[string][]string{"key1": {"val1", "val2", "val3"}, "key2": {"val4", "val5"}}, c.koanf.StringsMap("parent1.strsmap"))
1366 assert.Equal(map[string]string{}, c.koanf.StringMap("xxxx"))
1367 assert.Equal(map[string]string{}, c.koanf.StringMap("parent1.intmap"))
1368
1369 // Bools.
1370 assert.Equal(false, c.koanf.Bool("xxxx"))
1371 assert.Equal(false, c.koanf.Bool("type"))
1372 assert.Equal(true, c.koanf.Bool("parent1.child1.grandchild1.on"))
1373 assert.Equal(true, c.koanf.Bool("strbool"))
1374
1375 assert.Equal([]bool{}, c.koanf.Bools("xxxx"))
1376 assert.Equal([]bool{true, false, true}, c.koanf.Bools("bools"))
1377 assert.Equal([]bool{true, false, true}, c.koanf.Bools("intbools"))
1378 assert.Equal([]bool{true, true, false}, c.koanf.Bools("strbools"))
1379
1380 assert.Equal(map[string]bool{"ok1": true, "ok2": true, "notok3": false}, c.koanf.BoolMap("parent1.boolmap"))
1381 assert.Equal(map[string]bool{"key1": true, "key2": true, "key3": true}, c.koanf.BoolMap("parent1.intmap"))
1382 assert.Equal(map[string]bool{}, c.koanf.BoolMap("xxxx"))
1383
1384 // Others.
1385 assert.Equal(time.Duration(1234), c.koanf.Duration("parent1.id"))
1386 assert.Equal(time.Duration(0), c.koanf.Duration("xxxx"))
1387 assert.Equal(time.Second*3, c.koanf.Duration("duration"))
1388
1389 assert.Equal(time.Time{}, c.koanf.Time("xxxx", "2006-01-02"))
1390 assert.Equal(time.Date(2019, 1, 1, 0, 0, 0, 0, time.UTC), c.koanf.Time("time", "2006-01-02"))
1391
1392 assert.Equal([]string{}, c.koanf.MapKeys("xxxx"), "map keys mismatch")
1393 assert.Equal([]string{"bools", "duration", "empty", "intbools", "negative_int", "orphan", "parent1", "parent2", "strbool", "strbools", "time", "type"},
1394 c.koanf.MapKeys(""), "map keys mismatch")
1395 assert.Equal([]string{"key1", "key2", "key3"}, c.koanf.MapKeys("parent1.strmap"), "map keys mismatch")
1396
1397 // Attempt to parse int=1234 as a Unix timestamp.
1398 assert.Equal(time.Date(1970, 1, 1, 0, 20, 34, 0, time.UTC), c.koanf.Time("parent1.id", "").UTC())
1399 }
1400 }
1401
1402 func TestMustGetTypes(t *testing.T) {
1403 assert := assert.New(t)
1404 for _, c := range cases {
1405 // Int.
1406 assert.Panics(func() { c.koanf.MustInt64("xxxx") })
1407 assert.Equal(int64(1234), c.koanf.MustInt64("parent1.id"))
1408 assert.Equal(int64(-1234), c.koanf.MustInt64("negative_int"))
1409
1410 assert.Panics(func() { c.koanf.MustInt("xxxx") })
1411 assert.Equal(int(1234), c.koanf.MustInt("parent1.id"))
1412 assert.Equal(int(-1234), c.koanf.MustInt("negative_int"))
1413
1414 assert.Panics(func() { c.koanf.MustInt64s("xxxx") })
1415 assert.Equal([]int64{1, 2, 3}, c.koanf.MustInt64s("parent1.child1.grandchild1.ids"))
1416
1417 assert.Panics(func() { c.koanf.MustInt64Map("xxxx") })
1418 assert.Equal(map[string]int64{"key1": 1, "key2": 1, "key3": 1}, c.koanf.MustInt64Map("parent1.intmap"))
1419
1420 assert.Panics(func() { c.koanf.MustInt64Map("parent1.boolmap") })
1421 assert.Equal(map[string]int64{"key1": 1, "key2": 1, "key3": 1}, c.koanf.MustInt64Map("parent1.floatmap"))
1422
1423 assert.Panics(func() { c.koanf.MustInts("xxxx") })
1424 assert.Equal([]int{1, 2, 3}, c.koanf.MustInts("parent1.child1.grandchild1.ids"))
1425
1426 assert.Panics(func() { c.koanf.MustIntMap("xxxx") })
1427 assert.Panics(func() { c.koanf.MustIntMap("parent1.boolmap") })
1428 assert.Equal(map[string]int{"key1": 1, "key2": 1, "key3": 1}, c.koanf.MustIntMap("parent1.intmap"))
1429
1430 // Float.
1431 assert.Panics(func() { c.koanf.MustInts("xxxx") })
1432 assert.Equal(float64(1234), c.koanf.MustFloat64("parent1.id"))
1433
1434 assert.Panics(func() { c.koanf.MustFloat64s("xxxx") })
1435 assert.Equal([]float64{1, 2, 3}, c.koanf.MustFloat64s("parent1.child1.grandchild1.ids"))
1436
1437 assert.Panics(func() { c.koanf.MustFloat64Map("xxxx") })
1438 assert.Panics(func() { c.koanf.MustFloat64Map("parent1.boolmap") })
1439 assert.Equal(map[string]float64{"key1": 1.1, "key2": 1.2, "key3": 1.3}, c.koanf.MustFloat64Map("parent1.floatmap"))
1440 assert.Equal(map[string]float64{"key1": 1, "key2": 1, "key3": 1}, c.koanf.MustFloat64Map("parent1.intmap"))
1441
1442 // String and bytes.
1443 assert.Panics(func() { c.koanf.MustBytes("xxxx") })
1444 assert.Equal([]byte("parent1"), c.koanf.MustBytes("parent1.name"))
1445
1446 assert.Panics(func() { c.koanf.MustString("xxxx") })
1447 assert.Equal("parent1", c.koanf.MustString("parent1.name"))
1448
1449 assert.Panics(func() { c.koanf.MustStrings("xxxx") })
1450 assert.Equal([]string{"red", "blue", "orange"}, c.koanf.MustStrings("orphan"))
1451
1452 assert.Panics(func() { c.koanf.MustStringMap("xxxx") })
1453 assert.Panics(func() { c.koanf.MustStringMap("parent1.intmap") })
1454 assert.Equal(map[string]string{"key1": "val1", "key2": "val2", "key3": "val3"}, c.koanf.MustStringMap("parent1.strmap"))
1455 assert.Equal(map[string][]string{"key1": {"val1", "val2", "val3"}, "key2": {"val4", "val5"}}, c.koanf.MustStringsMap("parent1.strsmap"))
1456
1457 // // Bools.
1458 assert.Panics(func() { c.koanf.MustBools("xxxx") })
1459 assert.Equal([]bool{true, false, true}, c.koanf.MustBools("bools"))
1460 assert.Equal([]bool{true, false, true}, c.koanf.MustBools("intbools"))
1461 assert.Equal([]bool{true, true, false}, c.koanf.MustBools("strbools"))
1462
1463 assert.Panics(func() { c.koanf.MustBoolMap("xxxx") })
1464 assert.Equal(map[string]bool{"ok1": true, "ok2": true, "notok3": false}, c.koanf.MustBoolMap("parent1.boolmap"))
1465 assert.Equal(map[string]bool{"key1": true, "key2": true, "key3": true}, c.koanf.MustBoolMap("parent1.intmap"))
1466
1467 // Others.
1468 assert.Panics(func() { c.koanf.MustDuration("xxxx") })
1469 assert.Equal(time.Duration(1234), c.koanf.MustDuration("parent1.id"))
1470 assert.Equal(time.Second*3, c.koanf.MustDuration("duration"))
1471 assert.Equal(time.Duration(-1234), c.koanf.MustDuration("negative_int"))
1472
1473 assert.Panics(func() { c.koanf.MustTime("xxxx", "2006-01-02") })
1474 assert.Equal(time.Date(2019, 1, 1, 0, 0, 0, 0, time.UTC), c.koanf.MustTime("time", "2006-01-02"))
1475
1476 // // Attempt to parse int=1234 as a Unix timestamp.
1477 assert.Panics(func() { c.koanf.MustTime("time", "2006") })
1478 assert.Equal(time.Date(1970, 1, 1, 0, 20, 34, 0, time.UTC), c.koanf.MustTime("parent1.id", "").UTC())
1479 }
1480 }
1481
1482 func TestDelete(t *testing.T) {
1483 assert := assert.New(t)
1484 for _, c := range cases {
1485 c.koanf.Delete("parent2.child2.grandchild2")
1486 assert.Equal(false, c.koanf.Exists("parent2.child2.grandchild2.on"))
1487 assert.Equal(false, c.koanf.Exists("parent2.child2.grandchild2.ids.5"))
1488 assert.Equal(true, c.koanf.Exists("parent2.child2.name"))
1489
1490 c.koanf.Delete("")
1491 assert.Equal(false, c.koanf.Exists("duration"))
1492 assert.Equal(false, c.koanf.Exists("empty"))
1493 }
1494 }
1495
1496 func TestGetStringsMap(t *testing.T) {
1497 assert := assert.New(t)
1498
1499 k := koanf.New(delim)
1500
1501 k.Load(confmap.Provider(map[string]any{
1502 "str": map[string]string{
1503 "k1": "value",
1504 },
1505 "strs": map[string][]string{
1506 "k1": {"value"},
1507 },
1508 "iface": map[string]any{
1509 "k2": "value",
1510 },
1511 "ifaces": map[string][]any{
1512 "k2": {"value"},
1513 },
1514 "ifaces2": map[string]any{
1515 "k2": []any{"value"},
1516 },
1517 "ifaces3": map[string]any{
1518 "k2": []string{"value"},
1519 },
1520 }, "."), nil)
1521 assert.Equal(map[string]string{"k1": "value"}, k.StringMap("str"), "types don't match")
1522 assert.Equal(map[string]string{"k2": "value"}, k.StringMap("iface"), "types don't match")
1523 assert.Equal(map[string][]string{"k1": {"value"}}, k.StringsMap("strs"), "types don't match")
1524 assert.Equal(map[string][]string{"k2": {"value"}}, k.StringsMap("ifaces"), "types don't match")
1525 assert.Equal(map[string][]string{"k2": {"value"}}, k.StringsMap("ifaces2"), "types don't match")
1526 assert.Equal(map[string][]string{"k2": {"value"}}, k.StringsMap("ifaces3"), "types don't match")
1527 }
1528
1529 // waitTimeout waits for the waitgroup for the specified max timeout.
1530 // Returns true if waiting timed out.
1531 func waitTimeout(wg *sync.WaitGroup, timeout time.Duration) bool {
1532 c := make(chan struct{})
1533 go func() {
1534 defer close(c)
1535 wg.Wait()
1536 }()
1537 select {
1538 case <-c:
1539 return false // completed normally
1540 case <-time.After(timeout):
1541 return true // timed out
1542 }
1543 }
1544
1545 // TestFileWatcherRaceCondition reproduces Issue #305
1546 // File watcher reloading config while reader goroutine accesses values
1547 // This test verifies our thread safety fix prevents empty string reads
1548 func TestFileWatcherRaceCondition(t *testing.T) {
1549 if testing.Short() {
1550 t.Skip("skipping race condition test in short mode")
1551 }
1552
1553 // Create temp config file
1554 tmpDir, err := os.MkdirTemp("", "koanf_race_*")
1555 if err != nil {
1556 t.Fatal(err)
1557 }
1558 defer os.RemoveAll(tmpDir)
1559
1560 tmpFile := filepath.Join(tmpDir, "config.yaml")
1561 writeConfig := func(value string) {
1562 content := fmt.Sprintf("rpc: %q\n", value)
1563 os.WriteFile(tmpFile, []byte(content), 0600)
1564 }
1565
1566 // Initial config
1567 writeConfig("initial")
1568
1569 k := koanf.New(".")
1570 provider := file.Provider(tmpFile)
1571 err = k.Load(provider, yaml.Parser())
1572 if err != nil {
1573 t.Fatal(err)
1574 }
1575
1576 // Setup file watcher that reloads the SAME koanf instance
1577 // This tests our internal thread safety, not user pattern issues
1578 var reloadCount int64
1579 provider.Watch(func(event any, err error) {
1580 if err != nil {
1581 t.Logf("watch error: %v", err)
1582 return
1583 }
1584
1585 // Reload into the same koanf instance - this tests our thread safety
1586 err = k.Load(provider, yaml.Parser())
1587 if err != nil {
1588 t.Logf("reload error: %v", err)
1589 }
1590 // Use atomic to avoid race in test counters
1591 atomic.AddInt64(&reloadCount, 1)
1592 })
1593
1594 // Start reader goroutine that continuously reads the config
1595 done := make(chan struct{})
1596 var emptyCount, totalReads int64
1597
1598 go func() {
1599 for {
1600 select {
1601 case <-done:
1602 return
1603 default:
1604 value := k.String("rpc")
1605 reads := atomic.AddInt64(&totalReads, 1)
1606 if value == "" {
1607 atomic.AddInt64(&emptyCount, 1)
1608 // With proper thread safety, this should never happen
1609 t.Errorf("Got empty string on read #%d", reads)
1610 }
1611 time.Sleep(time.Microsecond) // Small delay to allow interleaving
1612 }
1613 }
1614 }()
1615
1616 // Trigger multiple file changes to increase chance of race
1617 for i := 0; i < 5; i++ {
1618 time.Sleep(20 * time.Millisecond)
1619 writeConfig(fmt.Sprintf("value-%d", i))
1620 }
1621
1622 // Wait for file watching to settle
1623 time.Sleep(100 * time.Millisecond)
1624 close(done)
1625
1626 finalReads := atomic.LoadInt64(&totalReads)
1627 finalEmpties := atomic.LoadInt64(&emptyCount)
1628 finalReloads := atomic.LoadInt64(&reloadCount)
1629
1630 t.Logf("Total reads: %d, Empty reads: %d, Reloads: %d", finalReads, finalEmpties, finalReloads)
1631 if finalEmpties > 0 {
1632 t.Errorf("Thread safety issue: got %d empty reads out of %d total reads", finalEmpties, finalReads)
1633 }
1634 }
1635
1636 // TestConcurrentLoadRaceCondition reproduces Issue #335
1637 // Multiple goroutines calling k.Load() simultaneously
1638 // This test should fail with "concurrent map writes" panic
1639 func TestConcurrentLoadRaceCondition(t *testing.T) {
1640 if testing.Short() {
1641 t.Skip("skipping race condition test in short mode")
1642 }
1643
1644 k := koanf.New(".")
1645
1646 // Number of concurrent goroutines
1647 numGoroutines := 10
1648 numLoadsPerGoroutine := 10
1649
1650 var wg sync.WaitGroup
1651
1652 // Channel to collect any panics
1653 panics := make(chan any, numGoroutines)
1654
1655 for i := 0; i < numGoroutines; i++ {
1656 wg.Add(1)
1657 go func(id int) {
1658 defer wg.Done()
1659 defer func() {
1660 if r := recover(); r != nil {
1661 panics <- r
1662 }
1663 }()
1664
1665 for j := 0; j < numLoadsPerGoroutine; j++ {
1666 // Create different configs to load
1667 config := map[string]any{
1668 fmt.Sprintf("key_%d_%d", id, j): fmt.Sprintf("value_%d_%d", id, j),
1669 "common": fmt.Sprintf("common_%d_%d", id, j),
1670 }
1671
1672 // This should trigger concurrent map writes
1673 err := k.Load(confmap.Provider(config, "."), nil)
1674 if err != nil {
1675 t.Errorf("Load failed: %v", err)
1676 }
1677
1678 // Small delay to increase chance of race
1679 time.Sleep(time.Microsecond)
1680 }
1681 }(i)
1682 }
1683
1684 wg.Wait()
1685 close(panics)
1686
1687 // Check if we got any panics (which indicates the race condition)
1688 panicCount := 0
1689 for p := range panics {
1690 panicCount++
1691 t.Logf("Concurrent Load panic: %v", p)
1692 }
1693
1694 if panicCount > 0 {
1695 t.Errorf("Race condition detected: got %d panics from concurrent Load operations", panicCount)
1696 }
1697 }
1698
1699 // TestConcurrentReadWriteMix tests mixed concurrent reads and writes
1700 // This should expose various race conditions with inconsistent reads
1701 func TestConcurrentReadWriteMix(t *testing.T) {
1702 if testing.Short() {
1703 t.Skip("skipping race condition test in short mode")
1704 }
1705
1706 k := koanf.New(".")
1707
1708 // Initialize with some data
1709 k.Load(confmap.Provider(map[string]any{
1710 "test.key": "initial",
1711 "counter": 0,
1712 }, "."), nil)
1713
1714 done := make(chan struct{})
1715 var wg sync.WaitGroup
1716
1717 // Start multiple reader goroutines
1718 for i := 0; i < 5; i++ {
1719 wg.Add(1)
1720 go func(readerID int) {
1721 defer wg.Done()
1722 readCount := 0
1723 for {
1724 select {
1725 case <-done:
1726 t.Logf("Reader %d: performed %d reads", readerID, readCount)
1727 return
1728 default:
1729 // Mix different types of reads
1730 _ = k.String("test.key")
1731 _ = k.Int("counter")
1732 _ = k.Keys()
1733 _ = k.All()
1734 readCount++
1735 time.Sleep(time.Microsecond)
1736 }
1737 }
1738 }(i)
1739 }
1740
1741 // Start multiple writer goroutines
1742 for i := 0; i < 3; i++ {
1743 wg.Add(1)
1744 go func(writerID int) {
1745 defer wg.Done()
1746 writeCount := 0
1747 for {
1748 select {
1749 case <-done:
1750 t.Logf("Writer %d: performed %d writes", writerID, writeCount)
1751 return
1752 default:
1753 // Mix different types of writes
1754 config := map[string]any{
1755 "test.key": fmt.Sprintf("writer-%d-count-%d", writerID, writeCount),
1756 "counter": writeCount,
1757 fmt.Sprintf("dynamic.key.%d", writeCount): writerID,
1758 }
1759 k.Load(confmap.Provider(config, "."), nil)
1760 writeCount++
1761 time.Sleep(time.Microsecond)
1762 }
1763 }
1764 }(i)
1765 }
1766
1767 // Let the race run for a short time
1768 time.Sleep(50 * time.Millisecond)
1769 close(done)
1770 wg.Wait()
1771
1772 t.Log("Concurrent read/write test completed - check for race detector warnings")
1773 }
1774
1775 // TestConcurrentEdgeCases tests concurrent access to edge case methods
1776 func TestConcurrentEdgeCases(t *testing.T) {
1777 if testing.Short() {
1778 t.Skip("skipping race condition test in short mode")
1779 }
1780
1781 k := koanf.New(".")
1782 k.Load(confmap.Provider(map[string]any{
1783 "parent": map[string]any{
1784 "child": "value",
1785 },
1786 "list": []any{"a", "b", "c"},
1787 }, "."), nil)
1788
1789 done := make(chan struct{})
1790 var wg sync.WaitGroup
1791
1792 // Test concurrent Cut operations
1793 wg.Add(1)
1794 go func() {
1795 defer wg.Done()
1796 for {
1797 select {
1798 case <-done:
1799 return
1800 default:
1801 _ = k.Cut("parent")
1802 time.Sleep(time.Microsecond)
1803 }
1804 }
1805 }()
1806
1807 // Test concurrent Copy operations
1808 wg.Add(1)
1809 go func() {
1810 defer wg.Done()
1811 for {
1812 select {
1813 case <-done:
1814 return
1815 default:
1816 _ = k.Copy()
1817 time.Sleep(time.Microsecond)
1818 }
1819 }
1820 }()
1821
1822 // Test concurrent MapKeys access
1823 wg.Add(1)
1824 go func() {
1825 defer wg.Done()
1826 for {
1827 select {
1828 case <-done:
1829 return
1830 default:
1831 _ = k.MapKeys("parent")
1832 time.Sleep(time.Microsecond)
1833 }
1834 }
1835 }()
1836
1837 // Test concurrent modifications
1838 wg.Add(1)
1839 go func() {
1840 defer wg.Done()
1841 count := 0
1842 for {
1843 select {
1844 case <-done:
1845 return
1846 default:
1847 k.Set(fmt.Sprintf("dynamic.%d", count), count)
1848 count++
1849 time.Sleep(time.Microsecond)
1850 }
1851 }
1852 }()
1853
1854 time.Sleep(30 * time.Millisecond)
1855 close(done)
1856 wg.Wait()
1857
1858 t.Log("Concurrent edge cases test completed - check for race detector warnings")
1859 }
1860
1861 // TestNoDeadlock verifies that our locking patterns don't cause deadlocks
1862 // Tests concurrent reads and writes with various method combinations
1863 func TestNoDeadlock(t *testing.T) {
1864 if testing.Short() {
1865 t.Skip("skipping deadlock test in short mode")
1866 }
1867
1868 k := koanf.New(".")
1869 k.Load(confmap.Provider(map[string]any{
1870 "parent": map[string]any{
1871 "child": "value",
1872 "count": 42,
1873 },
1874 "list": []any{"a", "b", "c"},
1875 }, "."), nil)
1876
1877 // Test duration
1878 testDuration := 500 * time.Millisecond
1879
1880 var wg sync.WaitGroup
1881 done := make(chan struct{})
1882
1883 // Start multiple reader goroutines with different read patterns
1884 for i := 0; i < 3; i++ {
1885 wg.Add(1)
1886 go func(id int) {
1887 defer wg.Done()
1888 readCount := 0
1889 for {
1890 select {
1891 case <-done:
1892 t.Logf("Reader %d completed %d operations", id, readCount)
1893 return
1894 default:
1895 // Mix different read operations
1896 _ = k.Get("parent.child")
1897 _ = k.Keys()
1898 _ = k.All()
1899 _ = k.Raw()
1900 _ = k.Exists("parent")
1901 _ = k.Sprint() // This internally uses RLock and avoids calling Keys()
1902 _ = k.KeyMap()
1903 _ = k.MapKeys("parent")
1904
1905 // Test methods that call other locked methods
1906 _ = k.Cut("parent") // Calls Get()
1907 _ = k.Copy() // Calls Cut() → Get()
1908
1909 readCount++
1910 if readCount%100 == 0 {
1911 time.Sleep(time.Microsecond)
1912 }
1913 }
1914 }
1915 }(i)
1916 }
1917
1918 // Start writer goroutines with different write patterns
1919 for i := 0; i < 2; i++ {
1920 wg.Add(1)
1921 go func(id int) {
1922 defer wg.Done()
1923 writeCount := 0
1924 for {
1925 select {
1926 case <-done:
1927 t.Logf("Writer %d completed %d operations", id, writeCount)
1928 return
1929 default:
1930 // Mix different write operations
1931 k.Set(fmt.Sprintf("writer_%d.key", id), writeCount)
1932 k.Delete("nonexistent") // Should be safe
1933
1934 // Load new data
1935 newData := map[string]any{
1936 fmt.Sprintf("load_%d", writeCount): id,
1937 "nested": map[string]any{
1938 "value": writeCount,
1939 },
1940 }
1941 k.Load(confmap.Provider(newData, "."), nil)
1942
1943 // Merge operations
1944 other := koanf.New(".")
1945 other.Set("merge_key", writeCount)
1946 k.Merge(other)
1947
1948 writeCount++
1949 if writeCount%50 == 0 {
1950 time.Sleep(time.Microsecond)
1951 }
1952 }
1953 }
1954 }(i)
1955 }
1956
1957 // Run the test for specified duration
1958 time.Sleep(testDuration)
1959 close(done)
1960
1961 // Use a timeout to detect deadlocks
1962 waitChan := make(chan struct{})
1963 go func() {
1964 wg.Wait()
1965 close(waitChan)
1966 }()
1967
1968 select {
1969 case <-waitChan:
1970 t.Log("Deadlock test completed successfully - no deadlocks detected")
1971 case <-time.After(5 * time.Second):
1972 t.Fatal("DEADLOCK DETECTED: Goroutines did not complete within timeout")
1973 }
1974 }
1975
1976 // TestFileProviderConcurrency specifically tests the file provider's synchronization
1977 // under heavy concurrent load to catch any races in Watch/Unwatch
1978 func TestFileProviderConcurrency(t *testing.T) {
1979 if testing.Short() {
1980 t.Skip("skipping file provider concurrency test in short mode")
1981 }
1982
1983 // Create temp config file
1984 tmpDir := t.TempDir()
1985 tmpFile := filepath.Join(tmpDir, "config.json")
1986 initialData := []byte(`{"test": "value"}`)
1987 err := os.WriteFile(tmpFile, initialData, 0600)
1988 if err != nil {
1989 t.Fatal(err)
1990 }
1991
1992 var wg sync.WaitGroup
1993 done := make(chan struct{})
1994
1995 // Stress test: multiple goroutines rapidly watch/unwatch the same file
1996 for i := 0; i < 5; i++ {
1997 wg.Add(1)
1998 go func(id int) {
1999 defer wg.Done()
2000
2001 for {
2002 select {
2003 case <-done:
2004 return
2005 default:
2006 // Create new file provider for each iteration
2007 f := file.Provider(tmpFile)
2008
2009 // Try to watch
2010 var watchErr error
2011 watchErr = f.Watch(func(event any, err error) {
2012 // Simple callback that doesn't do much
2013 _ = event
2014 _ = err
2015 })
2016
2017 // Sometimes watch will fail if another goroutine is already watching
2018 if watchErr == nil {
2019 // If watch succeeded, unwatch after a short delay
2020 time.Sleep(time.Millisecond)
2021 unwatchErr := f.Unwatch()
2022 if unwatchErr != nil {
2023 // Log but don't fail - this can happen during cleanup
2024 t.Logf("Unwatch error (normal during stress test): %v", unwatchErr)
2025 }
2026 } else if watchErr.Error() != "file is already being watched" {
2027 // Unexpected error
2028 t.Errorf("Unexpected watch error: %v", watchErr)
2029 }
2030
2031 // Small delay to prevent tight loop
2032 time.Sleep(time.Microsecond)
2033 }
2034 }
2035 }(i)
2036 }
2037
2038 // Also test concurrent file modifications while watching
2039 wg.Add(1)
2040 go func() {
2041 defer wg.Done()
2042 counter := 0
2043
2044 for {
2045 select {
2046 case <-done:
2047 return
2048 default:
2049 // Write new data to trigger file events
2050 newData := fmt.Sprintf(`{"test": "value", "counter": %d}`, counter)
2051 os.WriteFile(tmpFile, []byte(newData), 0600)
2052 counter++
2053 time.Sleep(5 * time.Millisecond)
2054 }
2055 }
2056 }()
2057
2058 // Let the stress test run for 200ms
2059 time.Sleep(200 * time.Millisecond)
2060 close(done)
2061
2062 // Wait with timeout to detect deadlocks
2063 waitChan := make(chan struct{})
2064 go func() {
2065 wg.Wait()
2066 close(waitChan)
2067 }()
2068
2069 select {
2070 case <-waitChan:
2071 t.Log("File provider concurrency test completed successfully")
2072 case <-time.After(5 * time.Second):
2073 t.Fatal("FILE PROVIDER DEADLOCK: Goroutines did not complete within timeout")
2074 }
2075 }
2076
2077 // TestGetNilPointer tests Get()'ing nil pointers.
2078 func TestGetNilPointer(t *testing.T) {
2079 assert := assert.New(t)
2080 k := koanf.New(".")
2081
2082 type test struct {
2083 Name string
2084 }
2085 var nt *test
2086 assert.Nil(k.Set("key", nt))
2087 assert.True(k.Exists("key"))
2088 got := k.Get("key")
2089 assert.Nil(got)
2090 _, ok := got.(*test)
2091 assert.True(ok, "expected type *test, got %T", got)
2092
2093 // Test nil value.
2094 assert.Nil(k.Set("val", nil))
2095 assert.Nil(k.Get("val"))
2096
2097 // Test slice.
2098 var s *[]string
2099 assert.Nil(k.Set("slice", s))
2100 gotSlice := k.Get("slice")
2101 assert.Nil(gotSlice)
2102 _, ok = gotSlice.(*[]string)
2103 assert.True(ok, "expected type *[]string, got %T", gotSlice)
2104 }