forked from mitchellh/mapstructure
-
Notifications
You must be signed in to change notification settings - Fork 41
Expand file tree
/
Copy pathdecode_hooks_test.go
More file actions
2174 lines (1990 loc) · 75.9 KB
/
decode_hooks_test.go
File metadata and controls
2174 lines (1990 loc) · 75.9 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 mapstructure
import (
"encoding/json"
"errors"
"fmt"
"math"
"math/big"
"net"
"net/netip"
"net/url"
"reflect"
"strings"
"testing"
"time"
)
type decodeHookTestSuite[F any, T any] struct {
fn DecodeHookFunc
ok []decodeHookTestCase[F, T]
fail []decodeHookFailureTestCase[F, T]
}
func (ts decodeHookTestSuite[F, T]) Run(t *testing.T) {
t.Run("OK", func(t *testing.T) {
t.Parallel()
for _, tc := range ts.ok {
tc := tc
t.Run("", func(t *testing.T) {
t.Parallel()
tc.Run(t, ts.fn)
})
}
})
t.Run("Fail", func(t *testing.T) {
t.Parallel()
for _, tc := range ts.fail {
tc := tc
t.Run("", func(t *testing.T) {
t.Parallel()
tc.Run(t, ts.fn)
})
}
})
t.Run("NoOp", func(t *testing.T) {
t.Parallel()
var zero F
actual, err := DecodeHookExec(ts.fn, reflect.ValueOf(zero), reflect.ValueOf(zero))
if err != nil {
t.Fatalf("unexpected error: %s", err)
}
if !reflect.DeepEqual(actual, zero) {
t.Fatalf("expected %[1]T(%#[1]v), got %[2]T(%#[2]v)", zero, actual)
}
})
}
type decodeHookTestCase[F any, T any] struct {
from F
expected T
}
func (tc decodeHookTestCase[F, T]) Run(t *testing.T, fn DecodeHookFunc) {
var to T
actual, err := DecodeHookExec(fn, reflect.ValueOf(tc.from), reflect.ValueOf(to))
if err != nil {
t.Fatalf("unexpected error: %s", err)
}
if !reflect.DeepEqual(actual, tc.expected) {
t.Fatalf("expected %[1]T(%#[1]v), got %[2]T(%#[2]v)", tc.expected, actual)
}
}
type decodeHookFailureTestCase[F any, T any] struct {
from F
}
func (tc decodeHookFailureTestCase[F, T]) Run(t *testing.T, fn DecodeHookFunc) {
var to T
_, err := DecodeHookExec(fn, reflect.ValueOf(tc.from), reflect.ValueOf(to))
if err == nil {
t.Fatalf("expected error, got none")
}
}
func TestComposeDecodeHookFunc(t *testing.T) {
f1 := func(
f reflect.Kind,
t reflect.Kind,
data any,
) (any, error) {
return data.(string) + "foo", nil
}
f2 := func(
f reflect.Kind,
t reflect.Kind,
data any,
) (any, error) {
return data.(string) + "bar", nil
}
f := ComposeDecodeHookFunc(f1, f2)
result, err := DecodeHookExec(
f, reflect.ValueOf(""), reflect.ValueOf([]byte("")))
if err != nil {
t.Fatalf("bad: %s", err)
}
if result.(string) != "foobar" {
t.Fatalf("bad: %#v", result)
}
}
func TestComposeDecodeHookFunc_err(t *testing.T) {
f1 := func(reflect.Kind, reflect.Kind, any) (any, error) {
return nil, errors.New("foo")
}
f2 := func(reflect.Kind, reflect.Kind, any) (any, error) {
panic("NOPE")
}
f := ComposeDecodeHookFunc(f1, f2)
_, err := DecodeHookExec(
f, reflect.ValueOf(""), reflect.ValueOf([]byte("")))
if err.Error() != "foo" {
t.Fatalf("bad: %s", err)
}
}
func TestComposeDecodeHookFunc_kinds(t *testing.T) {
var f2From reflect.Kind
f1 := func(
f reflect.Kind,
t reflect.Kind,
data any,
) (any, error) {
return int(42), nil
}
f2 := func(
f reflect.Kind,
t reflect.Kind,
data any,
) (any, error) {
f2From = f
return data, nil
}
f := ComposeDecodeHookFunc(f1, f2)
_, err := DecodeHookExec(
f, reflect.ValueOf(""), reflect.ValueOf([]byte("")))
if err != nil {
t.Fatalf("bad: %s", err)
}
if f2From != reflect.Int {
t.Fatalf("bad: %#v", f2From)
}
}
func TestOrComposeDecodeHookFunc(t *testing.T) {
f1 := func(
f reflect.Kind,
t reflect.Kind,
data any,
) (any, error) {
return data.(string) + "foo", nil
}
f2 := func(
f reflect.Kind,
t reflect.Kind,
data any,
) (any, error) {
return data.(string) + "bar", nil
}
f := OrComposeDecodeHookFunc(f1, f2)
result, err := DecodeHookExec(
f, reflect.ValueOf(""), reflect.ValueOf([]byte("")))
if err != nil {
t.Fatalf("bad: %s", err)
}
if result.(string) != "foo" {
t.Fatalf("bad: %#v", result)
}
}
func TestOrComposeDecodeHookFunc_correctValueIsLast(t *testing.T) {
f1 := func(
f reflect.Kind,
t reflect.Kind,
data any,
) (any, error) {
return nil, errors.New("f1 error")
}
f2 := func(
f reflect.Kind,
t reflect.Kind,
data any,
) (any, error) {
return nil, errors.New("f2 error")
}
f3 := func(
f reflect.Kind,
t reflect.Kind,
data any,
) (any, error) {
return data.(string) + "bar", nil
}
f := OrComposeDecodeHookFunc(f1, f2, f3)
result, err := DecodeHookExec(
f, reflect.ValueOf(""), reflect.ValueOf([]byte("")))
if err != nil {
t.Fatalf("bad: %s", err)
}
if result.(string) != "bar" {
t.Fatalf("bad: %#v", result)
}
}
func TestOrComposeDecodeHookFunc_err(t *testing.T) {
f1 := func(
f reflect.Kind,
t reflect.Kind,
data any,
) (any, error) {
return nil, errors.New("f1 error")
}
f2 := func(
f reflect.Kind,
t reflect.Kind,
data any,
) (any, error) {
return nil, errors.New("f2 error")
}
f := OrComposeDecodeHookFunc(f1, f2)
_, err := DecodeHookExec(
f, reflect.ValueOf(""), reflect.ValueOf([]byte("")))
if err == nil {
t.Fatalf("bad: should return an error")
}
if err.Error() != "f1 error\nf2 error\n" {
t.Fatalf("bad: %s", err)
}
}
func TestComposeDecodeHookFunc_safe_nofuncs(t *testing.T) {
f := ComposeDecodeHookFunc()
type myStruct2 struct {
MyInt int
}
type myStruct1 struct {
Blah map[string]myStruct2
}
src := &myStruct1{Blah: map[string]myStruct2{
"test": {
MyInt: 1,
},
}}
dst := &myStruct1{}
dConf := &DecoderConfig{
Result: dst,
ErrorUnused: true,
DecodeHook: f,
}
d, err := NewDecoder(dConf)
if err != nil {
t.Fatal(err)
}
err = d.Decode(src)
if err != nil {
t.Fatal(err)
}
}
func TestComposeDecodeHookFunc_ReflectValueHook(t *testing.T) {
reflectValueHook := func(
f reflect.Kind,
t reflect.Kind,
data any,
) (any, error) {
new := data.(string) + "foo"
return reflect.ValueOf(new), nil
}
stringHook := func(
f reflect.Kind,
t reflect.Kind,
data any,
) (any, error) {
return data.(string) + "bar", nil
}
f := ComposeDecodeHookFunc(reflectValueHook, stringHook)
result, err := DecodeHookExec(
f, reflect.ValueOf(""), reflect.ValueOf([]byte("")))
if err != nil {
t.Fatalf("bad: %s", err)
}
if result.(string) != "foobar" {
t.Fatalf("bad: %#v", result)
}
}
// TestComposeDecodeHookFunc_NilValue tests that ComposeDecodeHookFunc
// doesn't panic when a hook returns nil (issue #121).
func TestComposeDecodeHookFunc_NilValue(t *testing.T) {
hook := func(f reflect.Kind, t reflect.Kind, data any) (any, error) {
return data, nil
}
f := ComposeDecodeHookFunc(hook, hook)
// Test with nil input - this should not panic
result, err := DecodeHookExec(f, reflect.Value{}, reflect.ValueOf(""))
if err != nil {
t.Fatalf("unexpected error: %s", err)
}
if result != nil {
t.Fatalf("expected nil result, got: %#v", result)
}
}
// TestComposeDecodeHookFunc_DecodeNilRemain tests the specific scenario from issue #121
// where using ComposeDecodeHookFunc with DecodeNil and ,remain tag causes a panic.
func TestComposeDecodeHookFunc_DecodeNilRemain(t *testing.T) {
v := make(map[string]any)
v["m"] = nil
var result struct {
V map[string]any `mapstructure:",remain"`
}
hook := func(f reflect.Kind, t reflect.Kind, data any) (any, error) {
return data, nil
}
dec, err := NewDecoder(&DecoderConfig{
DecodeHook: ComposeDecodeHookFunc(hook, hook),
DecodeNil: true,
Result: &result,
})
if err != nil {
t.Fatalf("unexpected error creating decoder: %s", err)
}
// This should not panic
err = dec.Decode(&v)
if err != nil {
t.Fatalf("unexpected error decoding: %s", err)
}
}
func TestStringToSliceHookFunc(t *testing.T) {
// Test comma separator
commaSuite := decodeHookTestSuite[string, []string]{
fn: StringToSliceHookFunc(","),
ok: []decodeHookTestCase[string, []string]{
{"foo,bar,baz", []string{"foo", "bar", "baz"}}, // Basic comma separation
{"", []string{}}, // Empty string
{"single", []string{"single"}}, // Single element
{"one,two", []string{"one", "two"}}, // Two elements
{"foo, bar, baz", []string{"foo", " bar", " baz"}}, // Preserves spaces
{"foo,,bar", []string{"foo", "", "bar"}}, // Empty elements
{",foo,bar,", []string{"", "foo", "bar", ""}}, // Leading/trailing separators
{"foo,bar,baz,", []string{"foo", "bar", "baz", ""}}, // Trailing separator
{",foo", []string{"", "foo"}}, // Leading separator only
{"foo,", []string{"foo", ""}}, // Trailing separator only
{"a,b,c,d,e,f,g,h,i,j", []string{"a", "b", "c", "d", "e", "f", "g", "h", "i", "j"}}, // Many elements
},
fail: []decodeHookFailureTestCase[string, []string]{
// StringToSliceHookFunc doesn't have failure cases - it always succeeds
},
}
t.Run("CommaSeparator", commaSuite.Run)
// Test semicolon separator
semicolonSuite := decodeHookTestSuite[string, []string]{
fn: StringToSliceHookFunc(";"),
ok: []decodeHookTestCase[string, []string]{
{"foo;bar;baz", []string{"foo", "bar", "baz"}}, // Basic semicolon separation
{"", []string{}}, // Empty string
{"single", []string{"single"}}, // Single element
{"one;two", []string{"one", "two"}}, // Two elements
{"foo; bar; baz", []string{"foo", " bar", " baz"}}, // Preserves spaces
{"foo;;bar", []string{"foo", "", "bar"}}, // Empty elements
{";foo;bar;", []string{"", "foo", "bar", ""}}, // Leading/trailing separators
},
fail: []decodeHookFailureTestCase[string, []string]{},
}
t.Run("SemicolonSeparator", semicolonSuite.Run)
// Test pipe separator
pipeSuite := decodeHookTestSuite[string, []string]{
fn: StringToSliceHookFunc("|"),
ok: []decodeHookTestCase[string, []string]{
{"foo|bar|baz", []string{"foo", "bar", "baz"}}, // Basic pipe separation
{"", []string{}}, // Empty string
{"single", []string{"single"}}, // Single element
{"foo||bar", []string{"foo", "", "bar"}}, // Empty elements
},
fail: []decodeHookFailureTestCase[string, []string]{},
}
t.Run("PipeSeparator", pipeSuite.Run)
// Test space separator
spaceSuite := decodeHookTestSuite[string, []string]{
fn: StringToSliceHookFunc(" "),
ok: []decodeHookTestCase[string, []string]{
{"foo bar baz", []string{"foo", "bar", "baz"}}, // Basic space separation
{"", []string{}}, // Empty string
{"single", []string{"single"}}, // Single element
{"foo bar", []string{"foo", "", "bar"}}, // Double space creates empty element
},
fail: []decodeHookFailureTestCase[string, []string]{},
}
t.Run("SpaceSeparator", spaceSuite.Run)
// Test multi-character separator
multiCharSuite := decodeHookTestSuite[string, []string]{
fn: StringToSliceHookFunc("::"),
ok: []decodeHookTestCase[string, []string]{
{"foo::bar::baz", []string{"foo", "bar", "baz"}}, // Basic multi-char separation
{"", []string{}}, // Empty string
{"single", []string{"single"}}, // Single element
{"foo::::bar", []string{"foo", "", "bar"}}, // Double separator creates empty element
{"::foo::bar::", []string{"", "foo", "bar", ""}}, // Leading/trailing separators
},
fail: []decodeHookFailureTestCase[string, []string]{},
}
t.Run("MultiCharSeparator", multiCharSuite.Run)
// Test edge cases with custom logic for type conversion
t.Run("NonStringTypes", func(t *testing.T) {
f := StringToSliceHookFunc(",")
// Test that non-string types are passed through unchanged
sliceValue := reflect.ValueOf([]string{"42"})
actual, err := DecodeHookExec(f, sliceValue, sliceValue)
if err != nil {
t.Fatalf("unexpected error: %s", err)
}
if !reflect.DeepEqual(actual, []string{"42"}) {
t.Fatalf("expected %v, got %v", []string{"42"}, actual)
}
// Test byte slice passthrough
byteValue := reflect.ValueOf([]byte("42"))
actual, err = DecodeHookExec(f, byteValue, reflect.ValueOf([]byte{}))
if err != nil {
t.Fatalf("unexpected error: %s", err)
}
if !reflect.DeepEqual(actual, []byte("42")) {
t.Fatalf("expected %v, got %v", []byte("42"), actual)
}
// Test string to string passthrough
strValue := reflect.ValueOf("42")
actual, err = DecodeHookExec(f, strValue, strValue)
if err != nil {
t.Fatalf("unexpected error: %s", err)
}
if !reflect.DeepEqual(actual, "42") {
t.Fatalf("expected %v, got %v", "42", actual)
}
})
}
func TestStringToWeakSliceHookFunc(t *testing.T) {
f := StringToWeakSliceHookFunc(",")
strValue := reflect.ValueOf("42")
sliceValue := reflect.ValueOf([]string{"42"})
sliceValue2 := reflect.ValueOf([]byte("42"))
cases := []struct {
f, t reflect.Value
result any
err bool
}{
{sliceValue, sliceValue, []string{"42"}, false},
{sliceValue2, sliceValue2, []byte("42"), false},
{reflect.ValueOf([]byte("42")), reflect.ValueOf([]byte{}), []byte("42"), false},
{strValue, strValue, "42", false},
{
reflect.ValueOf("foo,bar,baz"),
sliceValue,
[]string{"foo", "bar", "baz"},
false,
},
{
reflect.ValueOf("foo,bar,baz"),
sliceValue2,
[]string{"foo", "bar", "baz"},
false,
},
{
reflect.ValueOf(""),
sliceValue,
[]string{},
false,
},
{
reflect.ValueOf(""),
sliceValue2,
[]string{},
false,
},
}
for i, tc := range cases {
actual, err := DecodeHookExec(f, tc.f, tc.t)
if tc.err != (err != nil) {
t.Fatalf("case %d: expected err %#v", i, tc.err)
}
if !reflect.DeepEqual(actual, tc.result) {
t.Fatalf(
"case %d: expected %#v, got %#v",
i, tc.result, actual)
}
}
}
func TestStringToTimeDurationHookFunc(t *testing.T) {
suite := decodeHookTestSuite[string, time.Duration]{
fn: StringToTimeDurationHookFunc(),
ok: []decodeHookTestCase[string, time.Duration]{
// Basic units
{"5s", 5 * time.Second}, // Seconds
{"10ms", 10 * time.Millisecond}, // Milliseconds
{"100us", 100 * time.Microsecond}, // Microseconds
{"1000ns", 1000 * time.Nanosecond}, // Nanoseconds
{"2m", 2 * time.Minute}, // Minutes
{"3h", 3 * time.Hour}, // Hours
{"24h", 24 * time.Hour}, // Day in hours
// Combinations
{"1h30m", time.Hour + 30*time.Minute}, // Hour and minutes
{"2h45m30s", 2*time.Hour + 45*time.Minute + 30*time.Second}, // Multiple units
{"1m30s", time.Minute + 30*time.Second}, // Minutes and seconds
{"500ms", 500 * time.Millisecond}, // Milliseconds only
{"1.5s", time.Second + 500*time.Millisecond}, // Fractional seconds
{"2.5h", 2*time.Hour + 30*time.Minute}, // Fractional hours
// Zero values
{"0s", 0}, // Zero seconds
{"0ms", 0}, // Zero milliseconds
{"0h", 0}, // Zero hours
{"0", 0}, // Just zero
// Negative durations
{"-5s", -5 * time.Second}, // Negative seconds
{"-1h30m", -(time.Hour + 30*time.Minute)}, // Negative combined
{"-100ms", -100 * time.Millisecond}, // Negative milliseconds
// Fractional values
{"0.5s", 500 * time.Millisecond}, // Half second
{"1.25m", time.Minute + 15*time.Second}, // Fractional minute
{"0.1h", 6 * time.Minute}, // Fractional hour
{"2.5ms", 2*time.Millisecond + 500*time.Microsecond}, // Fractional millisecond
// Large values
{"8760h", 8760 * time.Hour}, // 1 year in hours
{"525600m", 525600 * time.Minute}, // 1 year in minutes
{"1000000us", 1000000 * time.Microsecond}, // Large microseconds
// Additional valid cases
{".5s", 500 * time.Millisecond}, // Leading decimal is valid
{"5µs", 5 * time.Microsecond}, // Unicode micro symbol is valid
{"5.s", 5 * time.Second}, // Trailing decimal is valid
{"5s5m5s", 10*time.Second + 5*time.Minute}, // Duplicate units are valid
},
fail: []decodeHookFailureTestCase[string, time.Duration]{
{"5"}, // Missing unit
{"abc"}, // Invalid format
{""}, // Empty string
{"5x"}, // Invalid unit
{"5ss"}, // Double unit letters
{"5..5s"}, // Multiple decimal points
{"++5s"}, // Double plus sign
{"--5s"}, // Double minus sign
{" 5s "}, // Leading/trailing whitespace not handled
{"\t10ms\n"}, // Tab/newline whitespace not handled
{"\r1h\r"}, // Carriage return whitespace not handled
{"5s "}, // Trailing space after unit
{" 5 s"}, // Space before unit
{"5 s 10 m"}, // Spaces in combined duration
{"∞s"}, // Unicode infinity symbol
{"1y"}, // Unsupported unit (years)
{"1w"}, // Unsupported unit (weeks)
{"1d"}, // Unsupported unit (days)
},
}
// Test non-string and non-duration type passthrough
t.Run("Passthrough", func(t *testing.T) {
f := StringToTimeDurationHookFunc()
// Non-string type should pass through
intValue := reflect.ValueOf(42)
actual, err := DecodeHookExec(f, intValue, reflect.ValueOf(time.Duration(0)))
if err != nil {
t.Fatalf("unexpected error: %s", err)
}
if actual != 42 {
t.Fatalf("expected 42, got %v", actual)
}
// Non-duration target type should pass through
strValue := reflect.ValueOf("5s")
actual, err = DecodeHookExec(f, strValue, strValue)
if err != nil {
t.Fatalf("unexpected error: %s", err)
}
if actual != "5s" {
t.Fatalf("expected '5s', got %v", actual)
}
})
suite.Run(t)
}
func TestStringToTimeLocationHookFunc(t *testing.T) {
newYork, _ := time.LoadLocation("America/New_York")
london, _ := time.LoadLocation("Europe/London")
tehran, _ := time.LoadLocation("Asia/Tehran")
shanghai, _ := time.LoadLocation("Asia/Shanghai")
suite := decodeHookTestSuite[string, *time.Location]{
fn: StringToTimeLocationHookFunc(),
ok: []decodeHookTestCase[string, *time.Location]{
{"UTC", time.UTC},
{"Local", time.Local},
{"America/New_York", newYork},
{"Europe/London", london},
{"Asia/Tehran", tehran},
{"Asia/Shanghai", shanghai},
},
fail: []decodeHookFailureTestCase[string, *time.Location]{
{"UTC2"}, // Non-existent
{"5s"}, // Duration-like, not a zone
{"Europe\\London"}, // Invalid path separator
{"../etc/passwd"}, // Unsafe path
{"/etc/zoneinfo"}, // Absolute path (rejected by stdlib)
{"Asia\\Tehran"}, // Invalid Windows-style path
},
}
suite.Run(t)
}
func TestStringToURLHookFunc(t *testing.T) {
httpURL, _ := url.Parse("http://example.com")
httpsURL, _ := url.Parse("https://example.com")
ftpURL, _ := url.Parse("ftp://ftp.example.com")
fileURL, _ := url.Parse("file:///path/to/file")
complexURL, _ := url.Parse("https://user:pass@example.com:8080/path?query=value&foo=bar#fragment")
ipURL, _ := url.Parse("http://192.168.1.1:8080")
ipv6URL, _ := url.Parse("http://[::1]:8080")
emptyURL, _ := url.Parse("")
suite := decodeHookTestSuite[string, *url.URL]{
fn: StringToURLHookFunc(),
ok: []decodeHookTestCase[string, *url.URL]{
{"http://example.com", httpURL}, // Basic HTTP URL
{"https://example.com", httpsURL}, // HTTPS URL
{"ftp://ftp.example.com", ftpURL}, // FTP URL
{"file:///path/to/file", fileURL}, // File URL
{"https://user:pass@example.com:8080/path?query=value&foo=bar#fragment", complexURL}, // Complex URL with all components
{"http://192.168.1.1:8080", ipURL}, // IPv4 address with port
{"http://[::1]:8080", ipv6URL}, // IPv6 address with port
{"", emptyURL}, // Empty URL
// Additional valid cases that url.Parse accepts
{"http://", func() *url.URL { u, _ := url.Parse("http://"); return u }()}, // Scheme with empty host
{"http://example.com:99999", func() *url.URL { u, _ := url.Parse("http://example.com:99999"); return u }()}, // High port number
{"not a url at all", func() *url.URL { u, _ := url.Parse("not a url at all"); return u }()}, // Relative path (valid)
},
fail: []decodeHookFailureTestCase[string, *url.URL]{
{"http ://example.com"}, // Space in scheme
{"://invalid"}, // Missing scheme
{"http://[invalid:ipv6"}, // Malformed IPv6 bracket
},
}
suite.Run(t)
}
func TestStringToTimeHookFunc(t *testing.T) {
strValue := reflect.ValueOf("5")
timeValue := reflect.ValueOf(time.Time{})
cases := []struct {
f, t reflect.Value
layout string
result any
err bool
}{
{
reflect.ValueOf("2006-01-02T15:04:05Z"), timeValue, time.RFC3339,
time.Date(2006, 1, 2, 15, 4, 5, 0, time.UTC), false,
},
{strValue, timeValue, time.RFC3339, time.Time{}, true},
{strValue, strValue, time.RFC3339, "5", false},
}
for i, tc := range cases {
f := StringToTimeHookFunc(tc.layout)
actual, err := DecodeHookExec(f, tc.f, tc.t)
if tc.err != (err != nil) {
t.Fatalf("case %d: expected err %#v", i, tc.err)
}
if !reflect.DeepEqual(actual, tc.result) {
t.Fatalf(
"case %d: expected %#v, got %#v",
i, tc.result, actual)
}
}
}
func TestStringToIPHookFunc(t *testing.T) {
suite := decodeHookTestSuite[string, net.IP]{
fn: StringToIPHookFunc(),
ok: []decodeHookTestCase[string, net.IP]{
// IPv4 addresses
{"1.2.3.4", net.IPv4(0x01, 0x02, 0x03, 0x04)}, // Basic IPv4
{"192.168.1.1", net.IPv4(192, 168, 1, 1)}, // Private network address
{"0.0.0.0", net.IPv4(0, 0, 0, 0)}, // Zero address
{"255.255.255.255", net.IPv4(255, 255, 255, 255)}, // Broadcast address
{"127.0.0.1", net.IPv4(127, 0, 0, 1)}, // Localhost
{"10.0.0.1", net.IPv4(10, 0, 0, 1)}, // Private network
// IPv6 addresses
{"::1", net.ParseIP("::1")}, // IPv6 localhost
{"2001:db8::1", net.ParseIP("2001:db8::1")}, // Documentation address
{"fe80::1", net.ParseIP("fe80::1")}, // Link-local address
{"2001:0db8:85a3:0000:0000:8a2e:0370:7334", net.ParseIP("2001:0db8:85a3:0000:0000:8a2e:0370:7334")}, // Full IPv6 address
{"2001:db8:85a3::8a2e:370:7334", net.ParseIP("2001:db8:85a3::8a2e:370:7334")}, // Compressed IPv6
{"::", net.ParseIP("::")}, // IPv6 zero address
{"::ffff:192.0.2.1", net.ParseIP("::ffff:192.0.2.1")}, // IPv4-mapped IPv6
},
fail: []decodeHookFailureTestCase[string, net.IP]{
{"5"}, // Single number
{"256.1.1.1"}, // IPv4 octet too large
{"1.2.3"}, // Too few IPv4 octets
{"1.2.3.4.5"}, // Too many IPv4 octets
{"not.an.ip.address"}, // Non-numeric text
{""}, // Empty string
{"192.168.1.256"}, // Last octet too large
{"192.168.-1.1"}, // Negative octet
{"gggg::1"}, // Invalid hex in IPv6
{"2001:db8::1::2"}, // Double :: in IPv6
{"[::1]"}, // IPv6 with brackets (not raw IP)
{"192.168.1.1:8080"}, // IPv4 with port
},
}
suite.Run(t)
}
func TestStringToIPNetHookFunc(t *testing.T) {
strValue := reflect.ValueOf("5")
ipNetValue := reflect.ValueOf(net.IPNet{})
var nilNet *net.IPNet = nil
cases := []struct {
f, t reflect.Value
result any
err bool
}{
{
reflect.ValueOf("1.2.3.4/24"), ipNetValue,
&net.IPNet{
IP: net.IP{0x01, 0x02, 0x03, 0x00},
Mask: net.IPv4Mask(0xff, 0xff, 0xff, 0x00),
}, false,
},
{strValue, ipNetValue, nilNet, true},
{strValue, strValue, "5", false},
}
for i, tc := range cases {
f := StringToIPNetHookFunc()
actual, err := DecodeHookExec(f, tc.f, tc.t)
if tc.err != (err != nil) {
t.Fatalf("case %d: expected err %#v", i, tc.err)
}
if !reflect.DeepEqual(actual, tc.result) {
t.Fatalf(
"case %d: expected %#v, got %#v",
i, tc.result, actual)
}
}
}
func TestWeaklyTypedHook(t *testing.T) {
var f DecodeHookFunc = WeaklyTypedHook
strValue := reflect.ValueOf("")
cases := []struct {
f, t reflect.Value
result any
err bool
}{
// TO STRING
{
reflect.ValueOf(false),
strValue,
"0", // bool false converts to "0"
false,
},
{
reflect.ValueOf(true),
strValue,
"1", // bool true converts to "1"
false,
},
{
reflect.ValueOf(float32(7)),
strValue,
"7", // float32 converts to string
false,
},
{
reflect.ValueOf(int(7)),
strValue,
"7", // int converts to string
false,
},
{
reflect.ValueOf([]uint8("foo")),
strValue,
"foo", // byte slice converts to string
false,
},
{
reflect.ValueOf(uint(7)),
strValue,
"7", // uint converts to string
false,
},
}
for i, tc := range cases {
actual, err := DecodeHookExec(f, tc.f, tc.t)
if tc.err != (err != nil) {
t.Fatalf("case %d: expected err %#v", i, tc.err)
}
if !reflect.DeepEqual(actual, tc.result) {
t.Fatalf(
"case %d: expected %#v, got %#v",
i, tc.result, actual)
}
}
}
func TestStructToMapHookFuncTabled(t *testing.T) {
var f DecodeHookFunc = RecursiveStructToMapHookFunc()
type b struct {
TestKey string
}
type a struct {
Sub b
}
testStruct := a{
Sub: b{
TestKey: "testval",
},
}
testMap := map[string]any{
"Sub": map[string]any{
"TestKey": "testval",
},
}
cases := []struct {
name string
receiver any
input any
expected any
err bool
}{
{
"map receiver",
func() any {
var res map[string]any
return &res
}(),
testStruct,
&testMap,
false,
},
{
"interface receiver",
func() any {
var res any
return &res
}(),
testStruct,
func() any {
var exp any = testMap
return &exp
}(),
false,
},
{
"slice receiver errors",
func() any {
var res []string
return &res
}(),
testStruct,
new([]string),
true,
},
{
"slice to slice - no change",
func() any {
var res []string
return &res
}(),
[]string{"a", "b"},
&[]string{"a", "b"},
false,
},
{
"string to string - no change",
func() any {
var res string
return &res
}(),
"test",
func() *string {
s := "test"
return &s
}(),
false,
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
cfg := &DecoderConfig{
DecodeHook: f,
Result: tc.receiver,
}
d, err := NewDecoder(cfg)
if err != nil {
t.Fatalf("unexpected err %#v", err)
}
err = d.Decode(tc.input)
if tc.err != (err != nil) {
t.Fatalf("expected err %#v", err)
}
if !reflect.DeepEqual(tc.expected, tc.receiver) {
t.Fatalf("expected %#v, got %#v",
tc.expected, tc.receiver)
}