-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathprefer_test.go
More file actions
717 lines (574 loc) · 16.8 KB
/
prefer_test.go
File metadata and controls
717 lines (574 loc) · 16.8 KB
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
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
package prefer
import (
"errors"
"os"
"path/filepath"
"strings"
"sync/atomic"
"testing"
"time"
"github.com/fsnotify/fsnotify"
)
func TestLoadCreatesNewConfiguration(t *testing.T) {
type Mock struct {
Name string `json:"name"`
Age int `json:"age"`
}
mock := Mock{}
configuration, err := Load("share/fixtures/example", &mock)
checkTestError(t, err)
file_path_index := strings.Index(configuration.Identifier, "share/fixtures/example.")
expected_index := len(configuration.Identifier) - 27
if file_path_index != expected_index {
t.Error("Loaded unexpected configuration file:", configuration.Identifier)
}
if mock.Name != "Bailey" || mock.Age != 30 {
t.Error("Got unexpected values from configuration file.")
}
}
func TestLoadReturnsErrorForFilesWhichDontExist(t *testing.T) {
type Mock struct {
Name string `json:"name"`
Age int `json:"age"`
}
mock := Mock{}
_, err := Load("this/is/a/fake/filename", &mock)
if err == nil {
t.Error("Expected an error but one was not returned.")
}
}
func TestWatchReturnsChannelForWatchingFileForUpdates(t *testing.T) {
type Mock struct {
Name string `json:"name"`
Age int `json:"age"`
}
mock := Mock{}
channel, err := Watch("share/fixtures/example", &mock)
checkTestError(t, err)
<-channel
if mock.Name != "Bailey" || mock.Age != 30 {
t.Error("Got unexpected values from configuration file.")
}
}
func TestWatchWithDoneCanBeStopped(t *testing.T) {
type Mock struct {
Name string `json:"name"`
}
// Create a temporary file
tmpDir := t.TempDir()
tmpFile := filepath.Join(tmpDir, "config.json")
initialContent := `{"name": "initial"}`
if err := os.WriteFile(tmpFile, []byte(initialContent), 0644); err != nil {
t.Fatal(err)
}
mock := Mock{}
done := make(chan struct{})
channel, err := WatchWithDone(tmpFile, &mock, done)
checkTestError(t, err)
// Wait for initial load
select {
case <-channel:
if mock.Name != "initial" {
t.Error("Expected initial name, got:", mock.Name)
}
case <-time.After(2 * time.Second):
t.Fatal("Timed out waiting for initial config")
}
// Stop watching
close(done)
// Give it time to clean up
time.Sleep(100 * time.Millisecond)
// Channel should be closed
select {
case _, ok := <-channel:
if ok {
t.Error("Expected channel to be closed")
}
case <-time.After(500 * time.Millisecond):
// Channel not closed yet, that's ok for this test
}
}
func TestWatchWithDoneDetectsFileChanges(t *testing.T) {
type Mock struct {
Name string `json:"name"`
}
// Create a temporary file
tmpDir := t.TempDir()
tmpFile := filepath.Join(tmpDir, "config.json")
initialContent := `{"name": "initial"}`
if err := os.WriteFile(tmpFile, []byte(initialContent), 0644); err != nil {
t.Fatal(err)
}
mock := Mock{}
done := make(chan struct{})
channel, err := WatchWithDone(tmpFile, &mock, done)
checkTestError(t, err)
// Wait for initial load
select {
case <-channel:
// Initial load complete
case <-time.After(2 * time.Second):
close(done)
t.Fatal("Timed out waiting for initial config")
}
if mock.Name != "initial" {
close(done)
t.Fatal("Expected initial name, got:", mock.Name)
}
// Give watcher time to set up
time.Sleep(100 * time.Millisecond)
// Update the file
newContent := `{"name": "updated"}`
if err := os.WriteFile(tmpFile, []byte(newContent), 0644); err != nil {
close(done)
t.Fatal(err)
}
// Wait for update notification
select {
case <-channel:
// Stop the watcher and wait for goroutine to exit (channel close)
close(done)
for range channel {
} // drain until closed
if mock.Name != "updated" {
t.Error("Expected updated name, got:", mock.Name)
}
case <-time.After(2 * time.Second):
close(done)
t.Error("Timed out waiting for config update")
}
}
func TestWatchWithDoneSkipsInvalidUpdates(t *testing.T) {
type Mock struct {
Name string `json:"name"`
}
// Create a temporary file
tmpDir := t.TempDir()
tmpFile := filepath.Join(tmpDir, "config.json")
initialContent := `{"name": "initial"}`
if err := os.WriteFile(tmpFile, []byte(initialContent), 0644); err != nil {
t.Fatal(err)
}
mock := Mock{}
done := make(chan struct{})
channel, err := WatchWithDone(tmpFile, &mock, done)
checkTestError(t, err)
// Wait for initial load
<-channel
// Give watcher time to set up
time.Sleep(100 * time.Millisecond)
// Write invalid JSON - should be skipped, not crash
if err := os.WriteFile(tmpFile, []byte(`{invalid json}`), 0644); err != nil {
close(done)
t.Fatal(err)
}
// Give it time to process
time.Sleep(200 * time.Millisecond)
// Write valid JSON again
if err := os.WriteFile(tmpFile, []byte(`{"name": "recovered"}`), 0644); err != nil {
close(done)
t.Fatal(err)
}
// Should receive the valid update
select {
case <-channel:
// Stop the watcher and wait for goroutine to exit (channel close)
close(done)
for range channel {
} // drain until closed
if mock.Name != "recovered" {
t.Error("Expected recovered name, got:", mock.Name)
}
case <-time.After(2 * time.Second):
close(done)
t.Error("Timed out waiting for recovered config")
}
}
func TestConfigurationWatch(t *testing.T) {
type Mock struct {
Name string `json:"name"`
}
// Create a temporary file
tmpDir := t.TempDir()
tmpFile := filepath.Join(tmpDir, "config.json")
initialContent := `{"name": "test"}`
if err := os.WriteFile(tmpFile, []byte(initialContent), 0644); err != nil {
t.Fatal(err)
}
mock := Mock{}
config := NewConfiguration(tmpFile)
channel := make(chan interface{}, 1)
// Test the Configuration.Watch method (which wraps WatchWithDone)
err := config.Watch(&mock, channel)
if err != nil {
t.Fatal("Unexpected error:", err)
}
// Wait for initial load
select {
case <-channel:
if mock.Name != "test" {
t.Error("Expected name to be 'test', got:", mock.Name)
}
case <-time.After(2 * time.Second):
t.Fatal("Timed out waiting for initial config")
}
}
func TestConfigurationReloadWithInvalidFile(t *testing.T) {
// Test Reload with a file that doesn't exist
config := NewConfiguration("nonexistent/file.json")
type Mock struct {
Name string `json:"name"`
}
mock := Mock{}
err := config.Reload(&mock)
if err == nil {
t.Error("Expected error for non-existent file")
}
}
func TestConfigurationReloadWithUnsupportedFormat(t *testing.T) {
// Create a temporary file with unsupported extension
tmpDir := t.TempDir()
tmpFile := filepath.Join(tmpDir, "config.unknown")
if err := os.WriteFile(tmpFile, []byte(`data`), 0644); err != nil {
t.Fatal(err)
}
config := NewConfiguration(tmpFile)
type Mock struct {
Name string
}
mock := Mock{}
err := config.Reload(&mock)
if err == nil {
t.Error("Expected error for unsupported format")
}
}
func TestWatchWithDoneReloadError(t *testing.T) {
// Test that WatchWithDone returns error when initial Reload fails
type Mock struct {
Name string `json:"name"`
}
mock := Mock{}
done := make(chan struct{})
defer close(done)
config := NewConfiguration("nonexistent/file.json")
channel := make(chan interface{}, 1)
err := config.WatchWithDone(&mock, channel, done)
if err == nil {
t.Error("Expected error for non-existent file")
}
}
func TestReloadWithEmptyIdentifier(t *testing.T) {
// Test Reload when NewLoader returns error (empty identifier)
config := NewConfiguration("")
type Mock struct {
Name string `json:"name"`
}
mock := Mock{}
err := config.Reload(&mock)
if err == nil {
t.Error("Expected error for empty identifier")
}
}
func TestWatchWithDoneNewLoaderError(t *testing.T) {
// Test WatchWithDone when NewLoader returns error (empty identifier)
type Mock struct {
Name string `json:"name"`
}
mock := Mock{}
done := make(chan struct{})
defer close(done)
config := NewConfiguration("")
channel := make(chan interface{}, 1)
err := config.WatchWithDone(&mock, channel, done)
if err == nil {
t.Error("Expected error for empty identifier")
}
}
func TestWatchWithDoneUpdateChannelClosed(t *testing.T) {
type Mock struct {
Name string `json:"name"`
}
// Create a temporary file
tmpDir := t.TempDir()
tmpFile := filepath.Join(tmpDir, "config.json")
if err := os.WriteFile(tmpFile, []byte(`{"name": "initial"}`), 0644); err != nil {
t.Fatal(err)
}
mock := Mock{}
done := make(chan struct{})
channel, err := WatchWithDone(tmpFile, &mock, done)
checkTestError(t, err)
// Wait for initial load
<-channel
// Close done to stop the watcher
close(done)
// Give time for goroutine to clean up
time.Sleep(200 * time.Millisecond)
// Channel should be closed
select {
case <-channel:
// Got a value or channel closed
case <-time.After(500 * time.Millisecond):
// Timeout is fine
}
}
func TestWatchWithDoneSkipsSerializerErrors(t *testing.T) {
type Mock struct {
Name string `json:"name"`
}
// Create a temporary file
tmpDir := t.TempDir()
tmpFile := filepath.Join(tmpDir, "config.json")
if err := os.WriteFile(tmpFile, []byte(`{"name": "initial"}`), 0644); err != nil {
t.Fatal(err)
}
mock := Mock{}
done := make(chan struct{})
defer close(done)
channel, err := WatchWithDone(tmpFile, &mock, done)
checkTestError(t, err)
// Wait for initial load
<-channel
// Give watcher time to set up
time.Sleep(100 * time.Millisecond)
// Rename file to an unsupported extension to trigger NewSerializer error
newFile := filepath.Join(tmpDir, "config.unsupported")
_ = os.Rename(tmpFile, newFile)
// Write to trigger a watch event (even though it won't be picked up properly)
_ = os.WriteFile(tmpFile, []byte(`{"name": "updated"}`), 0644)
time.Sleep(200 * time.Millisecond)
// The watcher should continue running without crashing
// Write valid JSON again
_ = os.WriteFile(tmpFile, []byte(`{"name": "recovered"}`), 0644)
// Should eventually receive an update
select {
case <-channel:
// Got an update, good
case <-time.After(2 * time.Second):
// Timeout is acceptable - the point is the watcher didn't crash
}
}
func TestWatchWithDoneWatcherError(t *testing.T) {
// Test WatchWithDone when WatchWithContext returns an error
type Mock struct {
Name string `json:"name"`
}
// Create a temporary file
tmpDir := t.TempDir()
tmpFile := filepath.Join(tmpDir, "config.json")
if err := os.WriteFile(tmpFile, []byte(`{"name": "initial"}`), 0644); err != nil {
t.Fatal(err)
}
// Save original newWatcher and restore after test
originalNewWatcher := getWatcher()
defer setWatcher(originalNewWatcher)
// Make newWatcher fail - this happens in WatchWithContext after Reload succeeds
setWatcher(func() (Watcher, error) {
return nil, errors.New("watcher error")
})
mock := Mock{}
done := make(chan struct{})
defer close(done)
config := NewConfiguration(tmpFile)
channel := make(chan interface{}, 1)
err := config.WatchWithDone(&mock, channel, done)
if err == nil {
t.Error("Expected error when WatchWithContext fails")
}
}
func TestWatchWithDoneLoadErrorDuringUpdate(t *testing.T) {
// Test that loader.Load() errors during watch updates are skipped (resilient)
type Mock struct {
Name string `json:"name"`
}
// Create a temporary file
tmpDir := t.TempDir()
tmpFile := filepath.Join(tmpDir, "config.json")
if err := os.WriteFile(tmpFile, []byte(`{"name": "initial"}`), 0644); err != nil {
t.Fatal(err)
}
mock := Mock{}
done := make(chan struct{})
defer close(done)
channel, err := WatchWithDone(tmpFile, &mock, done)
checkTestError(t, err)
// Wait for initial load
select {
case <-channel:
if mock.Name != "initial" {
t.Error("Expected initial name, got:", mock.Name)
}
case <-time.After(2 * time.Second):
t.Fatal("Timed out waiting for initial config")
}
// Give watcher time to set up
time.Sleep(100 * time.Millisecond)
// Delete the file - this will cause Load() to fail on next update
os.Remove(tmpFile)
// Create the file again to trigger a watcher event
// The Load will succeed now since the file exists again
if err := os.WriteFile(tmpFile, []byte(`{"name": "recovered"}`), 0644); err != nil {
t.Fatal(err)
}
// Should receive the recovered config
select {
case <-channel:
if mock.Name != "recovered" {
t.Error("Expected recovered name, got:", mock.Name)
}
case <-time.After(2 * time.Second):
// Timeout is acceptable - the watcher continues to work
}
}
// mockWatcherForPrefer is a test-specific mock for prefer_test.go
type mockWatcherForPrefer struct {
events chan fsnotify.Event
errors chan error
addErr error
closeCalls atomic.Int32
}
func (m *mockWatcherForPrefer) Add(name string) error { return m.addErr }
func (m *mockWatcherForPrefer) Close() error {
m.closeCalls.Add(1)
return nil
}
func (m *mockWatcherForPrefer) Events() <-chan fsnotify.Event { return m.events }
func (m *mockWatcherForPrefer) Errors() <-chan error { return m.errors }
func TestConfigurationWatchWithDoneUpdateChannelClosed(t *testing.T) {
// Test that the goroutine exits gracefully when update channel closes
type Mock struct {
Name string `json:"name"`
}
// Create a temporary file
tmpDir := t.TempDir()
tmpFile := filepath.Join(tmpDir, "config.json")
if err := os.WriteFile(tmpFile, []byte(`{"name": "initial"}`), 0644); err != nil {
t.Fatal(err)
}
// Save original newWatcher and restore after test
originalNewWatcher := getWatcher()
defer setWatcher(originalNewWatcher)
mock := &mockWatcherForPrefer{
events: make(chan fsnotify.Event, 10),
errors: make(chan error, 10),
}
setWatcher(func() (Watcher, error) {
return mock, nil
})
data := Mock{}
done := make(chan struct{})
config := NewConfiguration(tmpFile)
channel := make(chan interface{}, 1)
err := config.WatchWithDone(&data, channel, done)
checkTestError(t, err)
// Wait for initial notification
<-channel
// Close the mock events channel - this simulates watcher shutdown
close(mock.events)
// Give time for goroutine to exit
time.Sleep(100 * time.Millisecond)
// The output channel should be closed now
select {
case <-channel:
// Got a value or channel closed, as expected
case <-time.After(500 * time.Millisecond):
// Timeout - channel not closed, but that's acceptable
}
}
func TestConfigurationWatchWithDoneLoadError(t *testing.T) {
// Test that loader.Load() errors during update are skipped
type Mock struct {
Name string `json:"name"`
}
// Create a temporary file
tmpDir := t.TempDir()
tmpFile := filepath.Join(tmpDir, "config.json")
if err := os.WriteFile(tmpFile, []byte(`{"name": "initial"}`), 0644); err != nil {
t.Fatal(err)
}
// Save original newWatcher and restore after test
originalNewWatcher := getWatcher()
defer setWatcher(originalNewWatcher)
mock := &mockWatcherForPrefer{
events: make(chan fsnotify.Event, 10),
errors: make(chan error, 10),
}
setWatcher(func() (Watcher, error) {
return mock, nil
})
data := Mock{}
done := make(chan struct{})
defer close(done)
config := NewConfiguration(tmpFile)
channel := make(chan interface{}, 1)
err := config.WatchWithDone(&data, channel, done)
checkTestError(t, err)
// Wait for initial notification
<-channel
// Delete the file to cause Load() to fail
os.Remove(tmpFile)
// Send a write event - this will trigger Load() which will fail
mock.events <- fsnotify.Event{Name: tmpFile, Op: fsnotify.Write}
// Give time for the error path to execute
time.Sleep(100 * time.Millisecond)
// Recreate the file
if err := os.WriteFile(tmpFile, []byte(`{"name": "recovered"}`), 0644); err != nil {
t.Fatal(err)
}
// Send another event - this one should succeed
mock.events <- fsnotify.Event{Name: tmpFile, Op: fsnotify.Write}
// Should receive the recovered config
select {
case <-channel:
if data.Name != "recovered" {
t.Error("Expected recovered name, got:", data.Name)
}
case <-time.After(2 * time.Second):
t.Error("Timed out waiting for recovered config")
}
}
func TestLoadWithCustomLoader(t *testing.T) {
type Config struct {
Name string `json:"name"`
}
content := []byte(`{"name": "from memory"}`)
loader := NewMemoryLoader("config.json", content)
var config Config
_, err := Load("unused", &config, WithLoader(loader))
if err != nil {
t.Fatal("Unexpected error:", err)
}
if config.Name != "from memory" {
t.Error("Expected 'from memory', got:", config.Name)
}
}
func TestLoadWithCustomLoaderYAML(t *testing.T) {
type Config struct {
Database struct {
Host string `yaml:"host"`
Port int `yaml:"port"`
} `yaml:"database"`
}
content := []byte(`database:
host: localhost
port: 5432`)
loader := NewMemoryLoader("config.yaml", content)
var config Config
_, err := Load("unused", &config, WithLoader(loader))
if err != nil {
t.Fatal("Unexpected error:", err)
}
if config.Database.Host != "localhost" {
t.Error("Expected 'localhost', got:", config.Database.Host)
}
if config.Database.Port != 5432 {
t.Error("Expected 5432, got:", config.Database.Port)
}
}
func TestNewConfigurationWithOptions(t *testing.T) {
loader := NewMemoryLoader("test.json", []byte(`{}`))
config := NewConfiguration("test", WithLoader(loader))
if config.loader != loader {
t.Error("Expected custom loader to be set")
}
}