-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathloader_test.go
More file actions
2392 lines (2022 loc) · 60.2 KB
/
loader_test.go
File metadata and controls
2392 lines (2022 loc) · 60.2 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
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package rigging
import (
"context"
"fmt"
"reflect"
"strings"
"testing"
"time"
)
// TestNewLoader verifies that NewLoader creates a loader with correct defaults.
func TestNewLoader(t *testing.T) {
loader := NewLoader[struct{}]()
if loader == nil {
t.Fatal("NewLoader returned nil")
}
if loader.sources == nil {
t.Error("sources slice should be initialized")
}
if loader.validators == nil {
t.Error("validators slice should be initialized")
}
if loader.transformers == nil {
t.Error("transformers slice should be initialized")
}
if !loader.strict {
t.Error("strict mode should be enabled by default")
}
if len(loader.sources) != 0 {
t.Errorf("expected 0 sources, got %d", len(loader.sources))
}
if len(loader.validators) != 0 {
t.Errorf("expected 0 validators, got %d", len(loader.validators))
}
if len(loader.transformers) != 0 {
t.Errorf("expected 0 transformers, got %d", len(loader.transformers))
}
}
// TestWithSource verifies that WithSource adds sources and returns the loader for chaining.
func TestWithSource(t *testing.T) {
loader := NewLoader[struct{}]()
mockSource1 := &mockSource{name: "source1"}
mockSource2 := &mockSource{name: "source2"}
// Test fluent API
result := loader.WithSource(mockSource1)
if result != loader {
t.Error("WithSource should return the same loader instance for chaining")
}
if len(loader.sources) != 1 {
t.Fatalf("expected 1 source, got %d", len(loader.sources))
}
// Add second source
loader.WithSource(mockSource2)
if len(loader.sources) != 2 {
t.Fatalf("expected 2 sources, got %d", len(loader.sources))
}
// Verify order is preserved
if loader.sources[0] != mockSource1 {
t.Error("first source should be mockSource1")
}
if loader.sources[1] != mockSource2 {
t.Error("second source should be mockSource2")
}
}
// TestWithValidator verifies that WithValidator adds validators and returns the loader for chaining.
func TestWithValidator(t *testing.T) {
loader := NewLoader[struct{}]()
validator1 := ValidatorFunc[struct{}](func(ctx context.Context, cfg *struct{}) error {
return nil
})
validator2 := ValidatorFunc[struct{}](func(ctx context.Context, cfg *struct{}) error {
return nil
})
// Test fluent API
result := loader.WithValidator(validator1)
if result != loader {
t.Error("WithValidator should return the same loader instance for chaining")
}
if len(loader.validators) != 1 {
t.Fatalf("expected 1 validator, got %d", len(loader.validators))
}
// Add second validator
loader.WithValidator(validator2)
if len(loader.validators) != 2 {
t.Fatalf("expected 2 validators, got %d", len(loader.validators))
}
}
// TestWithTransformer verifies that WithTransformer adds transformers and returns the loader for chaining.
func TestWithTransformer(t *testing.T) {
loader := NewLoader[struct{}]()
transformer1 := TransformerFunc[struct{}](func(ctx context.Context, cfg *struct{}) error { return nil })
transformer2 := TransformerFunc[struct{}](func(ctx context.Context, cfg *struct{}) error { return nil })
result := loader.WithTransformer(transformer1)
if result != loader {
t.Error("WithTransformer should return the same loader instance for chaining")
}
if len(loader.transformers) != 1 {
t.Fatalf("expected 1 transformer, got %d", len(loader.transformers))
}
loader.WithTransformer(transformer2)
if len(loader.transformers) != 2 {
t.Fatalf("expected 2 transformers, got %d", len(loader.transformers))
}
}
// TestWithTransformerFunc verifies that WithTransformerFunc wraps and adds a transformer and returns the loader for chaining.
func TestWithTransformerFunc(t *testing.T) {
type Config struct {
Value string
}
loader := NewLoader[Config]()
called := false
result := loader.WithTransformerFunc(func(ctx context.Context, cfg *Config) error {
called = true
cfg.Value = "normalized"
return nil
})
if result != loader {
t.Error("WithTransformerFunc should return the same loader instance for chaining")
}
if len(loader.transformers) != 1 {
t.Fatalf("expected 1 transformer, got %d", len(loader.transformers))
}
cfg := &Config{}
if err := loader.transformers[0].Transform(context.Background(), cfg); err != nil {
t.Fatalf("unexpected error calling wrapped transformer: %v", err)
}
if !called {
t.Fatal("expected wrapped transformer function to be called")
}
if cfg.Value != "normalized" {
t.Fatalf("expected transformer to mutate cfg.Value to %q, got %q", "normalized", cfg.Value)
}
}
// TestStrict verifies that Strict method sets the strict flag and returns the loader for chaining.
func TestStrict(t *testing.T) {
loader := NewLoader[struct{}]()
// Default should be true
if !loader.strict {
t.Error("strict should be true by default")
}
// Test setting to false
result := loader.Strict(false)
if result != loader {
t.Error("Strict should return the same loader instance for chaining")
}
if loader.strict {
t.Error("strict should be false after Strict(false)")
}
// Test setting back to true
loader.Strict(true)
if !loader.strict {
t.Error("strict should be true after Strict(true)")
}
}
// TestFluentAPI verifies that all methods can be chained together.
func TestFluentAPI(t *testing.T) {
mockSource := &mockSource{name: "test"}
validator := ValidatorFunc[struct{}](func(ctx context.Context, cfg *struct{}) error {
return nil
})
loader := NewLoader[struct{}]().
WithSource(mockSource).
WithValidator(validator).
Strict(false)
if len(loader.sources) != 1 {
t.Errorf("expected 1 source, got %d", len(loader.sources))
}
if len(loader.validators) != 1 {
t.Errorf("expected 1 validator, got %d", len(loader.validators))
}
if loader.strict {
t.Error("strict should be false")
}
}
// mockSource is a test helper that implements the Source interface.
type mockSource struct {
name string
data map[string]any
err error
}
func (m *mockSource) Load(ctx context.Context) (map[string]any, error) {
if m.err != nil {
return nil, m.err
}
if m.data == nil {
return make(map[string]any), nil
}
return m.data, nil
}
func (m *mockSource) Watch(ctx context.Context) (<-chan ChangeEvent, error) {
return nil, ErrWatchNotSupported
}
func (m *mockSource) Name() string {
if m.name != "" {
return m.name
}
return "mock"
}
// TestLoad_SingleSource verifies that Load works with a single source.
func TestLoad_SingleSource(t *testing.T) {
type Config struct {
Host string `conf:"required"`
Port int `conf:"default:8080"`
}
source := &mockSource{
data: map[string]any{
"host": "localhost",
},
}
loader := NewLoader[Config]().WithSource(source)
cfg, err := loader.Load(context.Background())
if err != nil {
t.Fatalf("Load failed: %v", err)
}
if cfg.Host != "localhost" {
t.Errorf("expected Host=localhost, got %s", cfg.Host)
}
if cfg.Port != 8080 {
t.Errorf("expected Port=8080 (default), got %d", cfg.Port)
}
}
// TestLoad_MultipleSources verifies that later sources override earlier ones.
func TestLoad_MultipleSources(t *testing.T) {
type Config struct {
Host string
Port int
}
source1 := &mockSource{
data: map[string]any{
"host": "localhost",
"port": 8080,
},
}
source2 := &mockSource{
data: map[string]any{
"port": 9090, // Override port
},
}
loader := NewLoader[Config]().
WithSource(source1).
WithSource(source2)
cfg, err := loader.Load(context.Background())
if err != nil {
t.Fatalf("Load failed: %v", err)
}
if cfg.Host != "localhost" {
t.Errorf("expected Host=localhost, got %s", cfg.Host)
}
if cfg.Port != 9090 {
t.Errorf("expected Port=9090 (overridden), got %d", cfg.Port)
}
}
// TestLoad_ValidationError verifies that validation errors are returned.
func TestLoad_ValidationError(t *testing.T) {
type Config struct {
Host string `conf:"required"`
Port int `conf:"min:1024,max:65535"`
}
source := &mockSource{
data: map[string]any{
"port": 80, // Below minimum
},
}
loader := NewLoader[Config]().WithSource(source)
cfg, err := loader.Load(context.Background())
if err == nil {
t.Fatal("expected validation error, got nil")
}
valErr, ok := err.(*ValidationError)
if !ok {
t.Fatalf("expected *ValidationError, got %T", err)
}
if len(valErr.FieldErrors) != 2 {
t.Logf("Field errors:")
for _, fe := range valErr.FieldErrors {
t.Logf(" - %s: %s (%s)", fe.FieldPath, fe.Code, fe.Message)
}
t.Fatalf("expected 2 field errors, got %d", len(valErr.FieldErrors))
}
// Check for required error
foundRequired := false
foundMin := false
for _, fe := range valErr.FieldErrors {
if fe.FieldPath == "Host" && fe.Code == ErrCodeRequired {
foundRequired = true
}
if fe.FieldPath == "Port" && fe.Code == ErrCodeMin {
foundMin = true
}
}
if !foundRequired {
t.Error("expected required error for Host field")
}
if !foundMin {
t.Error("expected min error for Port field")
}
if cfg != nil {
t.Error("cfg should be nil when validation fails")
}
}
func TestLoad_RequiredAllowsProvidedZeroValues(t *testing.T) {
type Config struct {
Enabled bool `conf:"required"`
Port int `conf:"required"`
Note string `conf:"required"`
}
source := &mockSource{
data: map[string]any{
"enabled": false,
"port": 0,
"note": "",
},
}
loader := NewLoader[Config]().WithSource(source)
cfg, err := loader.Load(context.Background())
if err != nil {
t.Fatalf("Load failed: %v", err)
}
if cfg == nil {
t.Fatal("expected non-nil config")
}
if cfg.Enabled != false {
t.Errorf("expected Enabled=false, got %v", cfg.Enabled)
}
if cfg.Port != 0 {
t.Errorf("expected Port=0, got %d", cfg.Port)
}
if cfg.Note != "" {
t.Errorf("expected Note empty string, got %q", cfg.Note)
}
}
func TestLoad_RequiredPresentZeroStillValidatesOtherConstraints(t *testing.T) {
type Config struct {
Port int `conf:"required,min:1"`
Mode string `conf:"required,oneof:prod,staging"`
}
source := &mockSource{
data: map[string]any{
"port": 0,
"mode": "",
},
}
loader := NewLoader[Config]().WithSource(source)
cfg, err := loader.Load(context.Background())
if err == nil {
t.Fatal("expected validation error, got nil")
}
valErr, ok := err.(*ValidationError)
if !ok {
t.Fatalf("expected *ValidationError, got %T", err)
}
foundMin := false
foundOneOf := false
foundRequired := false
for _, fe := range valErr.FieldErrors {
if fe.FieldPath == "Port" && fe.Code == ErrCodeMin {
foundMin = true
}
if fe.FieldPath == "Mode" && fe.Code == ErrCodeOneOf {
foundOneOf = true
}
if fe.Code == ErrCodeRequired {
foundRequired = true
}
}
if !foundMin {
t.Error("expected min error for Port field")
}
if !foundOneOf {
t.Error("expected oneof error for Mode field")
}
if foundRequired {
t.Error("did not expect required errors when fields are present")
}
if cfg != nil {
t.Error("cfg should be nil when validation fails")
}
}
func TestLoad_RequiredProvidedButInvalidTypeDoesNotAlsoReturnRequired(t *testing.T) {
type Config struct {
Port int `conf:"required"`
}
source := &mockSource{
data: map[string]any{
"port": "not-a-number",
},
}
loader := NewLoader[Config]().WithSource(source)
cfg, err := loader.Load(context.Background())
if err == nil {
t.Fatal("expected validation error, got nil")
}
valErr, ok := err.(*ValidationError)
if !ok {
t.Fatalf("expected *ValidationError, got %T", err)
}
foundInvalidType := false
foundRequired := false
for _, fe := range valErr.FieldErrors {
if fe.FieldPath == "Port" && fe.Code == ErrCodeInvalidType {
foundInvalidType = true
}
if fe.FieldPath == "Port" && fe.Code == ErrCodeRequired {
foundRequired = true
}
}
if !foundInvalidType {
t.Error("expected invalid type error for Port field")
}
if foundRequired {
t.Error("did not expect required error when key is present")
}
if cfg != nil {
t.Error("cfg should be nil when validation fails")
}
}
func TestLoad_PresentZeroValuesValidateConstraintsWithoutRequired(t *testing.T) {
type Config struct {
Port int `conf:"min:1"`
Mode string `conf:"oneof:prod,staging"`
}
t.Run("present zero values still validate", func(t *testing.T) {
source := &mockSource{
data: map[string]any{
"port": 0,
"mode": "",
},
}
loader := NewLoader[Config]().WithSource(source)
cfg, err := loader.Load(context.Background())
if err == nil {
t.Fatal("expected validation error, got nil")
}
valErr, ok := err.(*ValidationError)
if !ok {
t.Fatalf("expected *ValidationError, got %T", err)
}
foundMin := false
foundOneOf := false
foundRequired := false
for _, fe := range valErr.FieldErrors {
if fe.FieldPath == "Port" && fe.Code == ErrCodeMin {
foundMin = true
}
if fe.FieldPath == "Mode" && fe.Code == ErrCodeOneOf {
foundOneOf = true
}
if fe.Code == ErrCodeRequired {
foundRequired = true
}
}
if !foundMin {
t.Error("expected min error for Port field")
}
if !foundOneOf {
t.Error("expected oneof error for Mode field")
}
if foundRequired {
t.Error("did not expect required errors for non-required fields")
}
if cfg != nil {
t.Error("cfg should be nil when validation fails")
}
})
t.Run("absent optional fields skip constraints", func(t *testing.T) {
source := &mockSource{
data: map[string]any{},
}
loader := NewLoader[Config]().WithSource(source)
cfg, err := loader.Load(context.Background())
if err != nil {
t.Fatalf("unexpected error for absent optional fields: %v", err)
}
if cfg == nil {
t.Fatal("expected non-nil config")
}
})
}
func TestLoad_TransformerRunsBeforeTagValidation(t *testing.T) {
type Config struct {
Environment string `conf:"required,oneof:prod,staging"`
}
source := &mockSource{
data: map[string]any{
"environment": " PROD ",
},
}
var validatorSaw string
loader := NewLoader[Config]().
WithSource(source).
WithTransformer(TransformerFunc[Config](func(ctx context.Context, cfg *Config) error {
cfg.Environment = strings.ToLower(strings.TrimSpace(cfg.Environment))
return nil
})).
WithValidator(ValidatorFunc[Config](func(ctx context.Context, cfg *Config) error {
validatorSaw = cfg.Environment
return nil
}))
cfg, err := loader.Load(context.Background())
if err != nil {
t.Fatalf("Load failed: %v", err)
}
if cfg == nil {
t.Fatal("expected non-nil config")
}
if cfg.Environment != "prod" {
t.Fatalf("expected transformed environment=prod, got %q", cfg.Environment)
}
if validatorSaw != "prod" {
t.Fatalf("expected validator to see transformed value, got %q", validatorSaw)
}
}
func TestLoad_TransformerReturnsValidationError(t *testing.T) {
type Config struct {
Name string
}
source := &mockSource{
data: map[string]any{
"name": "alice",
},
}
loader := NewLoader[Config]().
WithSource(source).
WithTransformer(TransformerFunc[Config](func(ctx context.Context, cfg *Config) error {
return &ValidationError{
FieldErrors: []FieldError{{
FieldPath: "Name",
Code: "transformer_error",
Message: "name rejected by transformer",
}},
}
}))
cfg, err := loader.Load(context.Background())
if err == nil {
t.Fatal("expected validation error from transformer")
}
if cfg != nil {
t.Error("cfg should be nil when transformer returns validation error")
}
valErr, ok := err.(*ValidationError)
if !ok {
t.Fatalf("expected *ValidationError, got %T", err)
}
if len(valErr.FieldErrors) != 1 {
t.Fatalf("expected 1 field error, got %d", len(valErr.FieldErrors))
}
fe := valErr.FieldErrors[0]
if fe.FieldPath != "Name" {
t.Errorf("expected FieldPath=Name, got %q", fe.FieldPath)
}
if fe.Code != "transformer_error" {
t.Errorf("expected Code=transformer_error, got %q", fe.Code)
}
}
func TestLoad_TransformerReturnsGenericError(t *testing.T) {
type Config struct {
Name string
}
source := &mockSource{
data: map[string]any{
"name": "alice",
},
}
loader := NewLoader[Config]().
WithSource(source).
WithTransformer(TransformerFunc[Config](func(ctx context.Context, cfg *Config) error {
return fmt.Errorf("transformer boom")
}))
cfg, err := loader.Load(context.Background())
if err == nil {
t.Fatal("expected error from transformer")
}
if cfg != nil {
t.Error("cfg should be nil when transformer returns generic error")
}
if _, ok := err.(*ValidationError); ok {
t.Fatalf("expected non-validation error, got *ValidationError: %v", err)
}
if !strings.Contains(err.Error(), "transformer 0 failed") {
t.Fatalf("expected wrapped transformer index in error, got %q", err.Error())
}
if !strings.Contains(err.Error(), "transformer boom") {
t.Fatalf("expected original transformer error in message, got %q", err.Error())
}
}
// TestLoad_CustomValidator verifies that custom validators are executed.
func TestLoad_CustomValidator(t *testing.T) {
type Config struct {
Env string
Host string
}
source := &mockSource{
data: map[string]any{
"env": "prod",
"host": "localhost",
},
}
validator := ValidatorFunc[Config](func(ctx context.Context, cfg *Config) error {
if cfg.Env == "prod" && cfg.Host == "localhost" {
return &ValidationError{
FieldErrors: []FieldError{{
FieldPath: "Host",
Code: "invalid_prod_host",
Message: "production cannot use localhost",
}},
}
}
return nil
})
loader := NewLoader[Config]().
WithSource(source).
WithValidator(validator)
cfg, err := loader.Load(context.Background())
if err == nil {
t.Fatal("expected validation error from custom validator")
}
valErr, ok := err.(*ValidationError)
if !ok {
t.Fatalf("expected *ValidationError, got %T", err)
}
if len(valErr.FieldErrors) != 1 {
t.Fatalf("expected 1 field error, got %d", len(valErr.FieldErrors))
}
if valErr.FieldErrors[0].Code != "invalid_prod_host" {
t.Errorf("expected code=invalid_prod_host, got %s", valErr.FieldErrors[0].Code)
}
if cfg != nil {
t.Error("cfg should be nil when validation fails")
}
}
// TestLoad_StrictMode verifies that strict mode detects unknown keys.
func TestLoad_StrictMode(t *testing.T) {
type Config struct {
Host string
Port int
}
source := &mockSource{
data: map[string]any{
"host": "localhost",
"port": 8080,
"unknown": "value", // Unknown key
},
}
// Test with strict mode enabled (default)
loader := NewLoader[Config]().WithSource(source)
cfg, err := loader.Load(context.Background())
if err == nil {
t.Fatal("expected error for unknown key in strict mode")
}
if cfg != nil {
t.Error("cfg should be nil when strict mode fails")
}
// Verify it's a ValidationError with unknown_key code
valErr, ok := err.(*ValidationError)
if !ok {
t.Fatalf("expected ValidationError, got %T", err)
}
if len(valErr.FieldErrors) != 1 {
t.Fatalf("expected 1 field error, got %d", len(valErr.FieldErrors))
}
if valErr.FieldErrors[0].Code != ErrCodeUnknownKey {
t.Errorf("expected code %q, got %q", ErrCodeUnknownKey, valErr.FieldErrors[0].Code)
}
if valErr.FieldErrors[0].FieldPath != "unknown" {
t.Errorf("expected FieldPath %q, got %q", "unknown", valErr.FieldErrors[0].FieldPath)
}
// Test with strict mode disabled
loader = NewLoader[Config]().WithSource(source).Strict(false)
cfg, err = loader.Load(context.Background())
if err != nil {
t.Fatalf("Load failed with strict=false: %v", err)
}
if cfg.Host != "localhost" {
t.Errorf("expected Host=localhost, got %s", cfg.Host)
}
}
// TestLoad_Provenance verifies that provenance is stored for loaded config.
func TestLoad_Provenance(t *testing.T) {
type Config struct {
Host string `conf:"secret"`
Port int
Password string `conf:"secret"`
}
source := &mockSource{
data: map[string]any{
"host": "localhost",
"port": 8080,
"password": "secret123",
},
}
loader := NewLoader[Config]().WithSource(source)
cfg, err := loader.Load(context.Background())
if err != nil {
t.Fatalf("Load failed: %v", err)
}
// Get provenance
prov, ok := GetProvenance(cfg)
if !ok {
t.Fatal("provenance not found for config")
}
if len(prov.Fields) != 3 {
t.Fatalf("expected 3 provenance fields, got %d", len(prov.Fields))
}
// Check that secret fields are marked
secretCount := 0
for _, field := range prov.Fields {
if field.Secret {
secretCount++
}
}
if secretCount != 2 {
t.Errorf("expected 2 secret fields, got %d", secretCount)
}
}
func TestLoadWithProvenance(t *testing.T) {
type Config struct {
Host string
Password string `conf:"secret"`
}
source := &mockSource{
data: map[string]any{
"host": "localhost",
"password": "secret123",
},
}
loader := NewLoader[Config]().WithSource(source)
cfg, prov, err := loader.LoadWithProvenance(context.Background())
if err != nil {
t.Fatalf("LoadWithProvenance failed: %v", err)
}
if cfg.Host != "localhost" {
t.Errorf("expected Host=localhost, got %s", cfg.Host)
}
if cfg.Password != "secret123" {
t.Errorf("expected Password=secret123, got %s", cfg.Password)
}
if prov == nil {
t.Fatal("expected provenance to be returned")
}
if len(prov.Fields) != 2 {
t.Fatalf("expected 2 provenance fields, got %d", len(prov.Fields))
}
// LoadWithProvenance should not populate the global provenance store.
if _, ok := GetProvenance(cfg); ok {
t.Fatal("expected no global provenance entry for LoadWithProvenance")
}
}
// TestLoad_NestedStruct verifies that nested structs are bound correctly.
func TestLoad_NestedStruct(t *testing.T) {
type Database struct {
Host string
Port int
}
type Config struct {
Database Database `conf:"prefix:db"`
}
source := &mockSource{
data: map[string]any{
"db.host": "localhost",
"db.port": 5432,
},
}
loader := NewLoader[Config]().WithSource(source)
cfg, err := loader.Load(context.Background())
if err != nil {
t.Fatalf("Load failed: %v", err)
}
if cfg.Database.Host != "localhost" {
t.Errorf("expected Database.Host=localhost, got %s", cfg.Database.Host)
}
if cfg.Database.Port != 5432 {
t.Errorf("expected Database.Port=5432, got %d", cfg.Database.Port)
}
}
func TestLoad_NestedCollections(t *testing.T) {
type ClickHouseConfig struct {
Host string
Port int
}
type Config struct {
ClickhouseList []ClickHouseConfig
ClickhouseMap map[string]ClickHouseConfig
}
t.Run("binds slice and direct map values", func(t *testing.T) {
source := &mockSource{
data: map[string]any{
"clickhouse_list": []any{
map[string]any{"host": "ch1", "port": 9000},
map[string]any{"host": "ch2", "port": 9001},
},
"clickhouse_map": map[string]any{
"primary": map[string]any{"host": "ch1", "port": 9000},
"replica": map[string]any{"host": "ch2", "port": 9001},
"analytics": map[string]any{"host": "ch3", "port": 9002},
},
},
}
cfg, err := NewLoader[Config]().WithSource(source).Load(context.Background())
if err != nil {
t.Fatalf("Load failed: %v", err)
}
wantList := []ClickHouseConfig{
{Host: "ch1", Port: 9000},
{Host: "ch2", Port: 9001},
}
if !reflect.DeepEqual(cfg.ClickhouseList, wantList) {
t.Errorf("ClickhouseList = %#v, want %#v", cfg.ClickhouseList, wantList)
}
wantMap := map[string]ClickHouseConfig{
"primary": {Host: "ch1", Port: 9000},
"replica": {Host: "ch2", Port: 9001},
"analytics": {Host: "ch3", Port: 9002},
}
if !reflect.DeepEqual(cfg.ClickhouseMap, wantMap) {
t.Errorf("ClickhouseMap = %#v, want %#v", cfg.ClickhouseMap, wantMap)
}
})
t.Run("binds flattened dotted keys into map values in strict mode", func(t *testing.T) {
source := &mockSource{
data: map[string]any{
"clickhouse_map.primary.host": "ch1",
"clickhouse_map.primary.port": 9000,
"clickhouse_map.replica.host": "ch2",
"clickhouse_map.replica.port": 9001,
"clickhouse_map.analytics.host": "ch3",
"clickhouse_map.analytics.port": 9002,
},
}
cfg, err := NewLoader[Config]().WithSource(source).Load(context.Background())
if err != nil {
t.Fatalf("Load failed: %v", err)
}
wantMap := map[string]ClickHouseConfig{
"primary": {Host: "ch1", Port: 9000},
"replica": {Host: "ch2", Port: 9001},
"analytics": {Host: "ch3", Port: 9002},
}
if !reflect.DeepEqual(cfg.ClickhouseMap, wantMap) {
t.Errorf("ClickhouseMap = %#v, want %#v", cfg.ClickhouseMap, wantMap)
}
})
t.Run("strict mode rejects unknown nested key in flattened map value", func(t *testing.T) {
source := &mockSource{
data: map[string]any{
"clickhouse_map.primary.host": "ch1",
"clickhouse_map.primary.port": 9000,
"clickhouse_map.primary.unknown": "bad",