-
-
Notifications
You must be signed in to change notification settings - Fork 255
/
env_test.go
2308 lines (1928 loc) · 60.2 KB
/
env_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
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
// editorconfig-checker-disable-file
package env
import (
"encoding/base64"
"encoding/json"
"errors"
"fmt"
"net/http"
"net/url"
"os"
"path/filepath"
"reflect"
"runtime"
"strconv"
"strings"
"testing"
"time"
)
type unmarshaler struct {
time.Duration
}
// TextUnmarshaler implements encoding.TextUnmarshaler.
func (d *unmarshaler) UnmarshalText(data []byte) (err error) {
if len(data) != 0 {
d.Duration, err = time.ParseDuration(string(data))
} else {
d.Duration = 0
}
return err
}
// nolint: maligned
type Config struct {
String string `env:"STRING"`
StringPtr *string `env:"STRING"`
Strings []string `env:"STRINGS"`
StringPtrs []*string `env:"STRINGS"`
Bool bool `env:"BOOL"`
BoolPtr *bool `env:"BOOL"`
Bools []bool `env:"BOOLS"`
BoolPtrs []*bool `env:"BOOLS"`
Int int `env:"INT"`
IntPtr *int `env:"INT"`
Ints []int `env:"INTS"`
IntPtrs []*int `env:"INTS"`
Int8 int8 `env:"INT8"`
Int8Ptr *int8 `env:"INT8"`
Int8s []int8 `env:"INT8S"`
Int8Ptrs []*int8 `env:"INT8S"`
Int16 int16 `env:"INT16"`
Int16Ptr *int16 `env:"INT16"`
Int16s []int16 `env:"INT16S"`
Int16Ptrs []*int16 `env:"INT16S"`
Int32 int32 `env:"INT32"`
Int32Ptr *int32 `env:"INT32"`
Int32s []int32 `env:"INT32S"`
Int32Ptrs []*int32 `env:"INT32S"`
Int64 int64 `env:"INT64"`
Int64Ptr *int64 `env:"INT64"`
Int64s []int64 `env:"INT64S"`
Int64Ptrs []*int64 `env:"INT64S"`
Uint uint `env:"UINT"`
UintPtr *uint `env:"UINT"`
Uints []uint `env:"UINTS"`
UintPtrs []*uint `env:"UINTS"`
Uint8 uint8 `env:"UINT8"`
Uint8Ptr *uint8 `env:"UINT8"`
Uint8s []uint8 `env:"UINT8S"`
Uint8Ptrs []*uint8 `env:"UINT8S"`
Uint16 uint16 `env:"UINT16"`
Uint16Ptr *uint16 `env:"UINT16"`
Uint16s []uint16 `env:"UINT16S"`
Uint16Ptrs []*uint16 `env:"UINT16S"`
Uint32 uint32 `env:"UINT32"`
Uint32Ptr *uint32 `env:"UINT32"`
Uint32s []uint32 `env:"UINT32S"`
Uint32Ptrs []*uint32 `env:"UINT32S"`
Uint64 uint64 `env:"UINT64"`
Uint64Ptr *uint64 `env:"UINT64"`
Uint64s []uint64 `env:"UINT64S"`
Uint64Ptrs []*uint64 `env:"UINT64S"`
Float32 float32 `env:"FLOAT32"`
Float32Ptr *float32 `env:"FLOAT32"`
Float32s []float32 `env:"FLOAT32S"`
Float32Ptrs []*float32 `env:"FLOAT32S"`
Float64 float64 `env:"FLOAT64"`
Float64Ptr *float64 `env:"FLOAT64"`
Float64s []float64 `env:"FLOAT64S"`
Float64Ptrs []*float64 `env:"FLOAT64S"`
Duration time.Duration `env:"DURATION"`
Durations []time.Duration `env:"DURATIONS"`
DurationPtr *time.Duration `env:"DURATION"`
DurationPtrs []*time.Duration `env:"DURATIONS"`
Location time.Location `env:"LOCATION"`
Locations []time.Location `env:"LOCATIONS"`
LocationPtr *time.Location `env:"LOCATION"`
LocationPtrs []*time.Location `env:"LOCATIONS"`
Unmarshaler unmarshaler `env:"UNMARSHALER"`
UnmarshalerPtr *unmarshaler `env:"UNMARSHALER"`
Unmarshalers []unmarshaler `env:"UNMARSHALERS"`
UnmarshalerPtrs []*unmarshaler `env:"UNMARSHALERS"`
URL url.URL `env:"URL"`
URLPtr *url.URL `env:"URL"`
URLs []url.URL `env:"URLS"`
URLPtrs []*url.URL `env:"URLS"`
StringWithDefault string `env:"DATABASE_URL" envDefault:"postgres://localhost:5432/db"`
CustomSeparator []string `env:"SEPSTRINGS" envSeparator:":"`
NonDefined struct {
String string `env:"NONDEFINED_STR"`
}
NestedNonDefined struct {
NonDefined struct {
String string `env:"STR"`
} `envPrefix:"NONDEFINED_"`
} `envPrefix:"PRF_"`
NotAnEnv string
unexported string `env:"FOO"`
}
type ParentStruct struct {
InnerStruct *InnerStruct `env:",init"`
NilInnerStruct *InnerStruct
unexported *InnerStruct
Ignored *http.Client
}
type InnerStruct struct {
Inner string `env:"innervar"`
Number uint `env:"innernum"`
}
type ForNestedStruct struct {
NestedStruct
}
type NestedStruct struct {
NestedVar string `env:"nestedvar"`
}
func TestIssue245(t *testing.T) {
t.Setenv("NAME_NOT_SET", "")
type user struct {
Name string `env:"NAME_NOT_SET" envDefault:"abcd"`
}
cfg := user{}
isNoErr(t, Parse(&cfg))
isEqual(t, cfg.Name, "abcd")
}
func TestParsesEnv(t *testing.T) {
tos := func(v interface{}) string {
return fmt.Sprintf("%v", v)
}
toss := func(v ...interface{}) string {
ss := []string{}
for _, s := range v {
ss = append(ss, tos(s))
}
return strings.Join(ss, ",")
}
str1 := "str1"
str2 := "str2"
t.Setenv("STRING", str1)
t.Setenv("STRINGS", toss(str1, str2))
bool1 := true
bool2 := false
t.Setenv("BOOL", tos(bool1))
t.Setenv("BOOLS", toss(bool1, bool2))
int1 := -1
int2 := 2
t.Setenv("INT", tos(int1))
t.Setenv("INTS", toss(int1, int2))
var int81 int8 = -2
var int82 int8 = 5
t.Setenv("INT8", tos(int81))
t.Setenv("INT8S", toss(int81, int82))
var int161 int16 = -24
var int162 int16 = 15
t.Setenv("INT16", tos(int161))
t.Setenv("INT16S", toss(int161, int162))
var int321 int32 = -14
var int322 int32 = 154
t.Setenv("INT32", tos(int321))
t.Setenv("INT32S", toss(int321, int322))
var int641 int64 = -12
var int642 int64 = 150
t.Setenv("INT64", tos(int641))
t.Setenv("INT64S", toss(int641, int642))
var uint1 uint = 1
var uint2 uint = 2
t.Setenv("UINT", tos(uint1))
t.Setenv("UINTS", toss(uint1, uint2))
var uint81 uint8 = 15
var uint82 uint8 = 51
t.Setenv("UINT8", tos(uint81))
t.Setenv("UINT8S", toss(uint81, uint82))
var uint161 uint16 = 532
var uint162 uint16 = 123
t.Setenv("UINT16", tos(uint161))
t.Setenv("UINT16S", toss(uint161, uint162))
var uint321 uint32 = 93
var uint322 uint32 = 14
t.Setenv("UINT32", tos(uint321))
t.Setenv("UINT32S", toss(uint321, uint322))
var uint641 uint64 = 5
var uint642 uint64 = 43
t.Setenv("UINT64", tos(uint641))
t.Setenv("UINT64S", toss(uint641, uint642))
var float321 float32 = 9.3
var float322 float32 = 1.1
t.Setenv("FLOAT32", tos(float321))
t.Setenv("FLOAT32S", toss(float321, float322))
float641 := 1.53
float642 := 0.5
t.Setenv("FLOAT64", tos(float641))
t.Setenv("FLOAT64S", toss(float641, float642))
duration1 := time.Second
duration2 := time.Second * 4
t.Setenv("DURATION", tos(duration1))
t.Setenv("DURATIONS", toss(duration1, duration2))
location1 := time.UTC
location2, errLoadLocation := time.LoadLocation("Europe/Berlin")
isNoErr(t, errLoadLocation)
t.Setenv("LOCATION", tos(location1))
t.Setenv("LOCATIONS", toss(location1, location2))
unmarshaler1 := unmarshaler{time.Minute}
unmarshaler2 := unmarshaler{time.Millisecond * 1232}
t.Setenv("UNMARSHALER", tos(unmarshaler1.Duration))
t.Setenv("UNMARSHALERS", toss(unmarshaler1.Duration, unmarshaler2.Duration))
url1 := "https://goreleaser.com"
url2 := "https://caarlos0.dev"
t.Setenv("URL", tos(url1))
t.Setenv("URLS", toss(url1, url2))
t.Setenv("SEPSTRINGS", str1+":"+str2)
nonDefinedStr := "nonDefinedStr"
t.Setenv("NONDEFINED_STR", nonDefinedStr)
t.Setenv("PRF_NONDEFINED_STR", nonDefinedStr)
cfg := Config{}
isNoErr(t, Parse(&cfg))
isEqual(t, str1, cfg.String)
isEqual(t, &str1, cfg.StringPtr)
isEqual(t, str1, cfg.Strings[0])
isEqual(t, str2, cfg.Strings[1])
isEqual(t, &str1, cfg.StringPtrs[0])
isEqual(t, &str2, cfg.StringPtrs[1])
isEqual(t, bool1, cfg.Bool)
isEqual(t, &bool1, cfg.BoolPtr)
isEqual(t, bool1, cfg.Bools[0])
isEqual(t, bool2, cfg.Bools[1])
isEqual(t, &bool1, cfg.BoolPtrs[0])
isEqual(t, &bool2, cfg.BoolPtrs[1])
isEqual(t, int1, cfg.Int)
isEqual(t, &int1, cfg.IntPtr)
isEqual(t, int1, cfg.Ints[0])
isEqual(t, int2, cfg.Ints[1])
isEqual(t, &int1, cfg.IntPtrs[0])
isEqual(t, &int2, cfg.IntPtrs[1])
isEqual(t, int81, cfg.Int8)
isEqual(t, &int81, cfg.Int8Ptr)
isEqual(t, int81, cfg.Int8s[0])
isEqual(t, int82, cfg.Int8s[1])
isEqual(t, &int81, cfg.Int8Ptrs[0])
isEqual(t, &int82, cfg.Int8Ptrs[1])
isEqual(t, int161, cfg.Int16)
isEqual(t, &int161, cfg.Int16Ptr)
isEqual(t, int161, cfg.Int16s[0])
isEqual(t, int162, cfg.Int16s[1])
isEqual(t, &int161, cfg.Int16Ptrs[0])
isEqual(t, &int162, cfg.Int16Ptrs[1])
isEqual(t, int321, cfg.Int32)
isEqual(t, &int321, cfg.Int32Ptr)
isEqual(t, int321, cfg.Int32s[0])
isEqual(t, int322, cfg.Int32s[1])
isEqual(t, &int321, cfg.Int32Ptrs[0])
isEqual(t, &int322, cfg.Int32Ptrs[1])
isEqual(t, int641, cfg.Int64)
isEqual(t, &int641, cfg.Int64Ptr)
isEqual(t, int641, cfg.Int64s[0])
isEqual(t, int642, cfg.Int64s[1])
isEqual(t, &int641, cfg.Int64Ptrs[0])
isEqual(t, &int642, cfg.Int64Ptrs[1])
isEqual(t, uint1, cfg.Uint)
isEqual(t, &uint1, cfg.UintPtr)
isEqual(t, uint1, cfg.Uints[0])
isEqual(t, uint2, cfg.Uints[1])
isEqual(t, &uint1, cfg.UintPtrs[0])
isEqual(t, &uint2, cfg.UintPtrs[1])
isEqual(t, uint81, cfg.Uint8)
isEqual(t, &uint81, cfg.Uint8Ptr)
isEqual(t, uint81, cfg.Uint8s[0])
isEqual(t, uint82, cfg.Uint8s[1])
isEqual(t, &uint81, cfg.Uint8Ptrs[0])
isEqual(t, &uint82, cfg.Uint8Ptrs[1])
isEqual(t, uint161, cfg.Uint16)
isEqual(t, &uint161, cfg.Uint16Ptr)
isEqual(t, uint161, cfg.Uint16s[0])
isEqual(t, uint162, cfg.Uint16s[1])
isEqual(t, &uint161, cfg.Uint16Ptrs[0])
isEqual(t, &uint162, cfg.Uint16Ptrs[1])
isEqual(t, uint321, cfg.Uint32)
isEqual(t, &uint321, cfg.Uint32Ptr)
isEqual(t, uint321, cfg.Uint32s[0])
isEqual(t, uint322, cfg.Uint32s[1])
isEqual(t, &uint321, cfg.Uint32Ptrs[0])
isEqual(t, &uint322, cfg.Uint32Ptrs[1])
isEqual(t, uint641, cfg.Uint64)
isEqual(t, &uint641, cfg.Uint64Ptr)
isEqual(t, uint641, cfg.Uint64s[0])
isEqual(t, uint642, cfg.Uint64s[1])
isEqual(t, &uint641, cfg.Uint64Ptrs[0])
isEqual(t, &uint642, cfg.Uint64Ptrs[1])
isEqual(t, float321, cfg.Float32)
isEqual(t, &float321, cfg.Float32Ptr)
isEqual(t, float321, cfg.Float32s[0])
isEqual(t, float322, cfg.Float32s[1])
isEqual(t, &float321, cfg.Float32Ptrs[0])
isEqual(t, float641, cfg.Float64)
isEqual(t, &float641, cfg.Float64Ptr)
isEqual(t, float641, cfg.Float64s[0])
isEqual(t, float642, cfg.Float64s[1])
isEqual(t, &float641, cfg.Float64Ptrs[0])
isEqual(t, &float642, cfg.Float64Ptrs[1])
isEqual(t, duration1, cfg.Duration)
isEqual(t, &duration1, cfg.DurationPtr)
isEqual(t, duration1, cfg.Durations[0])
isEqual(t, duration2, cfg.Durations[1])
isEqual(t, &duration1, cfg.DurationPtrs[0])
isEqual(t, &duration2, cfg.DurationPtrs[1])
isEqual(t, *location1, cfg.Location)
isEqual(t, location1, cfg.LocationPtr)
isEqual(t, *location1, cfg.Locations[0])
isEqual(t, *location2, cfg.Locations[1])
isEqual(t, location1, cfg.LocationPtrs[0])
isEqual(t, location2, cfg.LocationPtrs[1])
isEqual(t, unmarshaler1, cfg.Unmarshaler)
isEqual(t, &unmarshaler1, cfg.UnmarshalerPtr)
isEqual(t, unmarshaler1, cfg.Unmarshalers[0])
isEqual(t, unmarshaler2, cfg.Unmarshalers[1])
isEqual(t, &unmarshaler1, cfg.UnmarshalerPtrs[0])
isEqual(t, &unmarshaler2, cfg.UnmarshalerPtrs[1])
isEqual(t, url1, cfg.URL.String())
isEqual(t, url1, cfg.URLPtr.String())
isEqual(t, url1, cfg.URLs[0].String())
isEqual(t, url2, cfg.URLs[1].String())
isEqual(t, url1, cfg.URLPtrs[0].String())
isEqual(t, url2, cfg.URLPtrs[1].String())
isEqual(t, "postgres://localhost:5432/db", cfg.StringWithDefault)
isEqual(t, nonDefinedStr, cfg.NonDefined.String)
isEqual(t, nonDefinedStr, cfg.NestedNonDefined.NonDefined.String)
isEqual(t, str1, cfg.CustomSeparator[0])
isEqual(t, str2, cfg.CustomSeparator[1])
isEqual(t, cfg.NotAnEnv, "")
isEqual(t, cfg.unexported, "")
}
func TestParsesEnv_Map(t *testing.T) {
type config struct {
MapStringString map[string]string `env:"MAP_STRING_STRING" envSeparator:","`
MapStringInt64 map[string]int64 `env:"MAP_STRING_INT64"`
MapStringBool map[string]bool `env:"MAP_STRING_BOOL" envSeparator:";"`
CustomSeparatorMapStringString map[string]string `env:"CUSTOM_SEPARATOR_MAP_STRING_STRING" envSeparator:"," envKeyValSeparator:"|"`
}
mss := map[string]string{
"k1": "v1",
"k2": "v2",
}
t.Setenv("MAP_STRING_STRING", "k1:v1,k2:v2")
msi := map[string]int64{
"k1": 1,
"k2": 2,
}
t.Setenv("MAP_STRING_INT64", "k1:1,k2:2")
msb := map[string]bool{
"k1": true,
"k2": false,
}
t.Setenv("MAP_STRING_BOOL", "k1:true;k2:false")
withCustomSeparator := map[string]string{
"k1": "v1",
"k2": "v2",
}
t.Setenv("CUSTOM_SEPARATOR_MAP_STRING_STRING", "k1|v1,k2|v2")
var cfg config
isNoErr(t, Parse(&cfg))
isEqual(t, mss, cfg.MapStringString)
isEqual(t, msi, cfg.MapStringInt64)
isEqual(t, msb, cfg.MapStringBool)
isEqual(t, withCustomSeparator, cfg.CustomSeparatorMapStringString)
}
func TestParsesEnvInvalidMap(t *testing.T) {
type config struct {
MapStringString map[string]string `env:"MAP_STRING_STRING" envSeparator:","`
}
t.Setenv("MAP_STRING_STRING", "k1,k2:v2")
var cfg config
err := Parse(&cfg)
isTrue(t, errors.Is(err, ParseError{}))
}
func TestParseCustomMapType(t *testing.T) {
type custommap map[string]bool
type config struct {
SecretKey custommap `env:"SECRET_KEY"`
}
t.Setenv("SECRET_KEY", "somesecretkey:1")
var cfg config
isNoErr(t, ParseWithOptions(&cfg, Options{FuncMap: map[reflect.Type]ParserFunc{
reflect.TypeOf(custommap{}): func(_ string) (interface{}, error) {
return custommap(map[string]bool{}), nil
},
}}))
}
func TestParseMapCustomKeyType(t *testing.T) {
type CustomKey string
type config struct {
SecretKey map[CustomKey]bool `env:"SECRET"`
}
t.Setenv("SECRET", "somesecretkey:1")
var cfg config
isNoErr(t, ParseWithOptions(&cfg, Options{FuncMap: map[reflect.Type]ParserFunc{
reflect.TypeOf(CustomKey("")): func(value string) (interface{}, error) {
return CustomKey(value), nil
},
}}))
}
func TestParseMapCustomKeyNoParser(t *testing.T) {
type CustomKey struct{}
type config struct {
SecretKey map[CustomKey]bool `env:"SECRET"`
}
t.Setenv("SECRET", "somesecretkey:1")
var cfg config
err := Parse(&cfg)
isTrue(t, errors.Is(err, NoParserError{}))
}
func TestParseMapCustomValueNoParser(t *testing.T) {
type Customval struct{}
type config struct {
SecretKey map[string]Customval `env:"SECRET"`
}
t.Setenv("SECRET", "somesecretkey:1")
var cfg config
err := Parse(&cfg)
isTrue(t, errors.Is(err, NoParserError{}))
}
func TestParseMapCustomKeyTypeError(t *testing.T) {
type CustomKey string
type config struct {
SecretKey map[CustomKey]bool `env:"SECRET"`
}
t.Setenv("SECRET", "somesecretkey:1")
var cfg config
err := ParseWithOptions(&cfg, Options{FuncMap: map[reflect.Type]ParserFunc{
reflect.TypeOf(CustomKey("")): func(_ string) (interface{}, error) {
return nil, fmt.Errorf("custom error")
},
}})
isTrue(t, errors.Is(err, ParseError{}))
}
func TestParseMapCustomValueTypeError(t *testing.T) {
type Customval string
type config struct {
SecretKey map[string]Customval `env:"SECRET"`
}
t.Setenv("SECRET", "somesecretkey:1")
var cfg config
err := ParseWithOptions(&cfg, Options{FuncMap: map[reflect.Type]ParserFunc{
reflect.TypeOf(Customval("")): func(_ string) (interface{}, error) {
return nil, fmt.Errorf("custom error")
},
}})
isTrue(t, errors.Is(err, ParseError{}))
}
func TestSetenvAndTagOptsChain(t *testing.T) {
type config struct {
Key1 string `mytag:"KEY1,required"`
Key2 int `mytag:"KEY2,required"`
}
envs := map[string]string{
"KEY1": "VALUE1",
"KEY2": "3",
}
cfg := config{}
isNoErr(t, ParseWithOptions(&cfg, Options{TagName: "mytag", Environment: envs}))
isEqual(t, "VALUE1", cfg.Key1)
isEqual(t, 3, cfg.Key2)
}
func TestJSONTag(t *testing.T) {
type config struct {
Key1 string `json:"KEY1"`
Key2 int `json:"KEY2"`
}
t.Setenv("KEY1", "VALUE7")
t.Setenv("KEY2", "5")
cfg := config{}
isNoErr(t, ParseWithOptions(&cfg, Options{TagName: "json"}))
isEqual(t, "VALUE7", cfg.Key1)
isEqual(t, 5, cfg.Key2)
}
func TestParsesEnvInner(t *testing.T) {
t.Setenv("innervar", "someinnervalue")
t.Setenv("innernum", "8")
cfg := ParentStruct{
InnerStruct: &InnerStruct{},
unexported: &InnerStruct{},
}
isNoErr(t, Parse(&cfg))
isEqual(t, "someinnervalue", cfg.InnerStruct.Inner)
isEqual(t, uint(8), cfg.InnerStruct.Number)
}
func TestParsesEnvInner_WhenInnerStructPointerIsNil(t *testing.T) {
t.Setenv("innervar", "someinnervalue")
t.Setenv("innernum", "8")
cfg := ParentStruct{}
isNoErr(t, Parse(&cfg))
isEqual(t, "someinnervalue", cfg.InnerStruct.Inner)
isEqual(t, uint(8), cfg.InnerStruct.Number)
}
func TestParsesEnvInnerFails(t *testing.T) {
type config struct {
Foo struct {
Number int `env:"NUMBER"`
}
}
t.Setenv("NUMBER", "not-a-number")
err := Parse(&config{})
isErrorWithMessage(t, err, `env: parse error on field "Number" of type "int": strconv.ParseInt: parsing "not-a-number": invalid syntax`)
isTrue(t, errors.Is(err, ParseError{}))
}
func TestParsesEnvInnerFailsMultipleErrors(t *testing.T) {
type config struct {
Foo struct {
Name string `env:"NAME,required"`
Number int `env:"NUMBER"`
Bar struct {
Age int `env:"AGE,required"`
}
}
}
t.Setenv("NUMBER", "not-a-number")
err := Parse(&config{})
isErrorWithMessage(t, err, `env: required environment variable "NAME" is not set; parse error on field "Number" of type "int": strconv.ParseInt: parsing "not-a-number": invalid syntax; required environment variable "AGE" is not set`)
isTrue(t, errors.Is(err, ParseError{}))
isTrue(t, errors.Is(err, VarIsNotSetError{}))
isTrue(t, errors.Is(err, VarIsNotSetError{}))
}
func TestParsesEnvInnerNil(t *testing.T) {
t.Setenv("innervar", "someinnervalue")
cfg := ParentStruct{}
isNoErr(t, Parse(&cfg))
}
func TestParsesEnvInnerInvalid(t *testing.T) {
t.Setenv("innernum", "-547")
cfg := ParentStruct{
InnerStruct: &InnerStruct{},
}
err := Parse(&cfg)
isErrorWithMessage(t, err, `env: parse error on field "Number" of type "uint": strconv.ParseUint: parsing "-547": invalid syntax`)
isTrue(t, errors.Is(err, ParseError{}))
}
func TestParsesEnvNested(t *testing.T) {
t.Setenv("nestedvar", "somenestedvalue")
var cfg ForNestedStruct
isNoErr(t, Parse(&cfg))
isEqual(t, "somenestedvalue", cfg.NestedVar)
}
func TestEmptyVars(t *testing.T) {
cfg := Config{}
isNoErr(t, Parse(&cfg))
isEqual(t, "", cfg.String)
isEqual(t, false, cfg.Bool)
isEqual(t, 0, cfg.Int)
isEqual(t, uint(0), cfg.Uint)
isEqual(t, uint64(0), cfg.Uint64)
isEqual(t, int64(0), cfg.Int64)
isEqual(t, 0, len(cfg.Strings))
isEqual(t, 0, len(cfg.CustomSeparator))
isEqual(t, 0, len(cfg.Ints))
isEqual(t, 0, len(cfg.Bools))
}
func TestPassAnInvalidPtr(t *testing.T) {
var thisShouldBreak int
err := Parse(&thisShouldBreak)
isErrorWithMessage(t, err, "env: expected a pointer to a Struct")
isTrue(t, errors.Is(err, NotStructPtrError{}))
}
func TestPassReference(t *testing.T) {
cfg := Config{}
err := Parse(cfg)
isErrorWithMessage(t, err, "env: expected a pointer to a Struct")
isTrue(t, errors.Is(err, NotStructPtrError{}))
}
func TestInvalidBool(t *testing.T) {
t.Setenv("BOOL", "should-be-a-bool")
err := Parse(&Config{})
isErrorWithMessage(t, err, `env: parse error on field "Bool" of type "bool": strconv.ParseBool: parsing "should-be-a-bool": invalid syntax; parse error on field "BoolPtr" of type "*bool": strconv.ParseBool: parsing "should-be-a-bool": invalid syntax`)
isTrue(t, errors.Is(err, ParseError{}))
}
func TestInvalidInt(t *testing.T) {
t.Setenv("INT", "should-be-an-int")
err := Parse(&Config{})
isErrorWithMessage(t, err, `env: parse error on field "Int" of type "int": strconv.ParseInt: parsing "should-be-an-int": invalid syntax; parse error on field "IntPtr" of type "*int": strconv.ParseInt: parsing "should-be-an-int": invalid syntax`)
isTrue(t, errors.Is(err, ParseError{}))
}
func TestInvalidUint(t *testing.T) {
t.Setenv("UINT", "-44")
err := Parse(&Config{})
isErrorWithMessage(t, err, `env: parse error on field "Uint" of type "uint": strconv.ParseUint: parsing "-44": invalid syntax; parse error on field "UintPtr" of type "*uint": strconv.ParseUint: parsing "-44": invalid syntax`)
isTrue(t, errors.Is(err, ParseError{}))
}
func TestInvalidFloat32(t *testing.T) {
t.Setenv("FLOAT32", "AAA")
err := Parse(&Config{})
isErrorWithMessage(t, err, `env: parse error on field "Float32" of type "float32": strconv.ParseFloat: parsing "AAA": invalid syntax; parse error on field "Float32Ptr" of type "*float32": strconv.ParseFloat: parsing "AAA": invalid syntax`)
isTrue(t, errors.Is(err, ParseError{}))
}
func TestInvalidFloat64(t *testing.T) {
t.Setenv("FLOAT64", "AAA")
err := Parse(&Config{})
isErrorWithMessage(t, err, `env: parse error on field "Float64" of type "float64": strconv.ParseFloat: parsing "AAA": invalid syntax; parse error on field "Float64Ptr" of type "*float64": strconv.ParseFloat: parsing "AAA": invalid syntax`)
isTrue(t, errors.Is(err, ParseError{}))
}
func TestInvalidUint64(t *testing.T) {
t.Setenv("UINT64", "AAA")
err := Parse(&Config{})
isErrorWithMessage(t, err, `env: parse error on field "Uint64" of type "uint64": strconv.ParseUint: parsing "AAA": invalid syntax; parse error on field "Uint64Ptr" of type "*uint64": strconv.ParseUint: parsing "AAA": invalid syntax`)
isTrue(t, errors.Is(err, ParseError{}))
}
func TestInvalidInt64(t *testing.T) {
t.Setenv("INT64", "AAA")
err := Parse(&Config{})
isErrorWithMessage(t, err, `env: parse error on field "Int64" of type "int64": strconv.ParseInt: parsing "AAA": invalid syntax; parse error on field "Int64Ptr" of type "*int64": strconv.ParseInt: parsing "AAA": invalid syntax`)
isTrue(t, errors.Is(err, ParseError{}))
}
func TestInvalidInt64Slice(t *testing.T) {
t.Setenv("BADINTS", "A,2,3")
type config struct {
BadFloats []int64 `env:"BADINTS"`
}
err := Parse(&config{})
isErrorWithMessage(t, err, `env: parse error on field "BadFloats" of type "[]int64": strconv.ParseInt: parsing "A": invalid syntax`)
isTrue(t, errors.Is(err, ParseError{}))
}
func TestInvalidUInt64Slice(t *testing.T) {
t.Setenv("BADINTS", "A,2,3")
type config struct {
BadFloats []uint64 `env:"BADINTS"`
}
err := Parse(&config{})
isErrorWithMessage(t, err, `env: parse error on field "BadFloats" of type "[]uint64": strconv.ParseUint: parsing "A": invalid syntax`)
isTrue(t, errors.Is(err, ParseError{}))
}
func TestInvalidFloat32Slice(t *testing.T) {
t.Setenv("BADFLOATS", "A,2.0,3.0")
type config struct {
BadFloats []float32 `env:"BADFLOATS"`
}
err := Parse(&config{})
isErrorWithMessage(t, err, `env: parse error on field "BadFloats" of type "[]float32": strconv.ParseFloat: parsing "A": invalid syntax`)
isTrue(t, errors.Is(err, ParseError{}))
}
func TestInvalidFloat64Slice(t *testing.T) {
t.Setenv("BADFLOATS", "A,2.0,3.0")
type config struct {
BadFloats []float64 `env:"BADFLOATS"`
}
err := Parse(&config{})
isErrorWithMessage(t, err, `env: parse error on field "BadFloats" of type "[]float64": strconv.ParseFloat: parsing "A": invalid syntax`)
isTrue(t, errors.Is(err, ParseError{}))
}
func TestInvalidBoolsSlice(t *testing.T) {
t.Setenv("BADBOOLS", "t,f,TRUE,faaaalse")
type config struct {
BadBools []bool `env:"BADBOOLS"`
}
err := Parse(&config{})
isErrorWithMessage(t, err, `env: parse error on field "BadBools" of type "[]bool": strconv.ParseBool: parsing "faaaalse": invalid syntax`)
isTrue(t, errors.Is(err, ParseError{}))
}
func TestInvalidDuration(t *testing.T) {
t.Setenv("DURATION", "should-be-a-valid-duration")
err := Parse(&Config{})
isErrorWithMessage(t, err, `env: parse error on field "Duration" of type "time.Duration": unable to parse duration: time: invalid duration "should-be-a-valid-duration"; parse error on field "DurationPtr" of type "*time.Duration": unable to parse duration: time: invalid duration "should-be-a-valid-duration"`)
isTrue(t, errors.Is(err, ParseError{}))
}
func TestInvalidDurations(t *testing.T) {
t.Setenv("DURATIONS", "1s,contains-an-invalid-duration,3s")
err := Parse(&Config{})
isErrorWithMessage(t, err, `env: parse error on field "Durations" of type "[]time.Duration": unable to parse duration: time: invalid duration "contains-an-invalid-duration"; parse error on field "DurationPtrs" of type "[]*time.Duration": unable to parse duration: time: invalid duration "contains-an-invalid-duration"`)
isTrue(t, errors.Is(err, ParseError{}))
}
func TestInvalidLocation(t *testing.T) {
t.Setenv("LOCATION", "should-be-a-valid-location")
err := Parse(&Config{})
isErrorWithMessage(t, err, `env: parse error on field "Location" of type "time.Location": unable to parse location: unknown time zone should-be-a-valid-location; parse error on field "LocationPtr" of type "*time.Location": unable to parse location: unknown time zone should-be-a-valid-location`)
isTrue(t, errors.Is(err, ParseError{}))
}
func TestInvalidLocations(t *testing.T) {
t.Setenv("LOCATIONS", "should-be-a-valid-location,UTC,Europe/Berlin")
err := Parse(&Config{})
isErrorWithMessage(t, err, `env: parse error on field "Locations" of type "[]time.Location": unable to parse location: unknown time zone should-be-a-valid-location; parse error on field "LocationPtrs" of type "[]*time.Location": unable to parse location: unknown time zone should-be-a-valid-location`)
isTrue(t, errors.Is(err, ParseError{}))
}
func TestParseStructWithoutEnvTag(t *testing.T) {
cfg := Config{}
isNoErr(t, Parse(&cfg))
isEqual(t, cfg.NotAnEnv, "")
}
func TestParseStructWithInvalidFieldKind(t *testing.T) {
type config struct {
WontWorkByte byte `env:"BLAH"`
}
t.Setenv("BLAH", "a")
err := Parse(&config{})
isErrorWithMessage(t, err, `env: parse error on field "WontWorkByte" of type "uint8": strconv.ParseUint: parsing "a": invalid syntax`)
isTrue(t, errors.Is(err, ParseError{}))
}
func TestUnsupportedSliceType(t *testing.T) {
type config struct {
WontWork []map[int]int `env:"WONTWORK"`
}
t.Setenv("WONTWORK", "1,2,3")
err := Parse(&config{})
isErrorWithMessage(t, err, `env: no parser found for field "WontWork" of type "[]map[int]int"`)
isTrue(t, errors.Is(err, NoParserError{}))
}
func TestBadSeparator(t *testing.T) {
type config struct {
WontWork []int `env:"WONTWORK" envSeparator:":"`
}
t.Setenv("WONTWORK", "1,2,3,4")
err := Parse(&config{})
isErrorWithMessage(t, err, `env: parse error on field "WontWork" of type "[]int": strconv.ParseInt: parsing "1,2,3,4": invalid syntax`)
isTrue(t, errors.Is(err, ParseError{}))
}
func TestNoErrorRequiredSet(t *testing.T) {
type config struct {
IsRequired string `env:"IS_REQUIRED,required"`
}
cfg := &config{}
t.Setenv("IS_REQUIRED", "")
isNoErr(t, Parse(cfg))
isEqual(t, "", cfg.IsRequired)
}
func TestHook(t *testing.T) {
type config struct {
Something string `env:"SOMETHING" envDefault:"important"`
Another string `env:"ANOTHER"`
Nope string
Inner struct{} `envPrefix:"FOO_"`
}
cfg := &config{}
t.Setenv("ANOTHER", "1")
type onSetArgs struct {
tag string
key interface{}
isDefault bool
}
var onSetCalled []onSetArgs
isNoErr(t, ParseWithOptions(cfg, Options{
OnSet: func(tag string, value interface{}, isDefault bool) {
onSetCalled = append(onSetCalled, onSetArgs{tag, value, isDefault})
},
}))
isEqual(t, "important", cfg.Something)
isEqual(t, "1", cfg.Another)
isEqual(t, 2, len(onSetCalled))
isEqual(t, onSetArgs{"SOMETHING", "important", true}, onSetCalled[0])
isEqual(t, onSetArgs{"ANOTHER", "1", false}, onSetCalled[1])
}
func TestErrorRequiredWithDefault(t *testing.T) {
type config struct {
IsRequired string `env:"IS_REQUIRED,required" envDefault:"important"`
}
cfg := &config{}
t.Setenv("IS_REQUIRED", "")
isNoErr(t, Parse(cfg))
isEqual(t, "important", cfg.IsRequired)
}
func TestErrorRequiredNotSet(t *testing.T) {
type config struct {
IsRequired string `env:"IS_REQUIRED,required"`
}
err := Parse(&config{})
isErrorWithMessage(t, err, `env: required environment variable "IS_REQUIRED" is not set`)
isTrue(t, errors.Is(err, VarIsNotSetError{}))
}
func TestNoErrorNotEmptySet(t *testing.T) {
t.Setenv("IS_REQUIRED", "1")
type config struct {
IsRequired string `env:"IS_REQUIRED,notEmpty"`
}
isNoErr(t, Parse(&config{}))
}
func TestNoErrorRequiredAndNotEmptySet(t *testing.T) {
t.Setenv("IS_REQUIRED", "1")
type config struct {
IsRequired string `env:"IS_REQUIRED,required,notEmpty"`
}
isNoErr(t, Parse(&config{}))
}
func TestErrorNotEmptySet(t *testing.T) {
t.Setenv("IS_REQUIRED", "")
type config struct {
IsRequired string `env:"IS_REQUIRED,notEmpty"`
}
err := Parse(&config{})
isErrorWithMessage(t, err, `env: environment variable "IS_REQUIRED" should not be empty`)
isTrue(t, errors.Is(err, EmptyVarError{}))
}
func TestErrorRequiredAndNotEmptySet(t *testing.T) {
t.Setenv("IS_REQUIRED", "")
type config struct {
IsRequired string `env:"IS_REQUIRED,notEmpty,required"`
}
err := Parse(&config{})
isErrorWithMessage(t, err, `env: environment variable "IS_REQUIRED" should not be empty`)
isTrue(t, errors.Is(err, EmptyVarError{}))
}
func TestErrorRequiredNotSetWithDefault(t *testing.T) {
type config struct {
IsRequired string `env:"IS_REQUIRED,required" envDefault:"important"`
}
cfg := &config{}
isNoErr(t, Parse(cfg))
isEqual(t, "important", cfg.IsRequired)
}
func TestParseExpandOption(t *testing.T) {
type config struct {
Host string `env:"HOST" envDefault:"localhost"`
Port int `env:"PORT,expand" envDefault:"3000"`
SecretKey string `env:"SECRET_KEY,expand"`
ExpandKey string `env:"EXPAND_KEY"`
CompoundKey string `env:"HOST_PORT,expand" envDefault:"${HOST}:${PORT}"`
Default string `env:"DEFAULT,expand" envDefault:"def1"`
}
t.Setenv("HOST", "localhost")
t.Setenv("PORT", "3000")
t.Setenv("EXPAND_KEY", "qwerty12345")
t.Setenv("SECRET_KEY", "${EXPAND_KEY}")
cfg := config{}