-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathbind_test.go
More file actions
1239 lines (1062 loc) · 31.8 KB
/
bind_test.go
File metadata and controls
1239 lines (1062 loc) · 31.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
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 wo
import (
"errors"
"mime/multipart"
"net/textproto"
"reflect"
"strconv"
"testing"
"time"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
// SimpleStruct represents a basic struct for binding tests
type SimpleStruct struct {
Name string `query:"name"`
Age int `query:"age"`
Email string `query:"email"`
}
// NestedStruct represents a struct with nested struct field
type NestedStruct struct {
User SimpleStruct `query:"user"`
Company string `query:"company"`
}
// PointerStruct represents a struct with pointer fields
type PointerStruct struct {
Name *string `query:"name"`
Age *int `query:"age"`
Active *bool `query:"active"`
Score *float64 `query:"score"`
}
// SliceStruct represents a struct with slice fields
type SliceStruct struct {
Tags []string `query:"tags"`
Numbers []int `query:"numbers"`
Floats []float64 `query:"floats"`
Booleans []bool `query:"booleans"`
}
// CustomUnmarshaler implements BindUnmarshaler
type CustomUnmarshaler struct {
Value time.Time
}
func (c *CustomUnmarshaler) UnmarshalParam(param string) error {
t, err := time.Parse(time.RFC3339, param)
if err != nil {
return err
}
c.Value = t
return nil
}
// CustomMultipleUnmarshaler implements BindMultipleUnmarshaler
type CustomMultipleUnmarshaler struct {
Values []string
}
func (c *CustomMultipleUnmarshaler) UnmarshalParams(params []string) error {
c.Values = params
return nil
}
// TextUnmarshaler implements encoding.TextUnmarshaler
type TextUnmarshaler struct {
Value string
}
func (t *TextUnmarshaler) UnmarshalText(text []byte) error {
t.Value = string(text)
return nil
}
// StructWithUnmarshalers combines different unmarshaler types
type StructWithUnmarshalers struct {
Custom CustomUnmarshaler `query:"custom"`
Multiple CustomMultipleUnmarshaler `query:"multiple"`
Text TextUnmarshaler `query:"text"`
Normal string `query:"normal"`
}
// StructWithFiles tests file binding
type StructWithFiles struct {
Document *multipart.FileHeader `form:"document"`
Images []*multipart.FileHeader `form:"images"`
Avatar *multipart.FileHeader `form:"avatar"`
Name string `form:"name"`
}
// AnonymousStructField tests anonymous struct field handling
type AnonymousStructField struct {
*SimpleStruct // No tag for anonymous embedded struct
Extra string `query:"extra"`
}
// TestBindData_SimpleStruct tests binding to a simple struct
func TestBindData_SimpleStruct(t *testing.T) {
tests := []struct {
name string
data map[string][]string
expected SimpleStruct
wantErr bool
}{
{
name: "valid binding",
data: map[string][]string{
"name": {"John Doe"},
"age": {"30"},
"email": {"john@example.com"},
},
expected: SimpleStruct{
Name: "John Doe",
Age: 30,
Email: "john@example.com",
},
wantErr: false,
},
{
name: "partial binding",
data: map[string][]string{
"name": {"Jane Doe"},
"age": {"25"},
},
expected: SimpleStruct{
Name: "Jane Doe",
Age: 25,
},
wantErr: false,
},
{
name: "empty data",
data: map[string][]string{},
expected: SimpleStruct{},
wantErr: false,
},
{
name: "invalid integer",
data: map[string][]string{
"name": {"Invalid"},
"age": {"not-a-number"},
},
expected: SimpleStruct{},
wantErr: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
var result SimpleStruct
err := BindData(&result, tt.data, "query", nil)
if tt.wantErr {
assert.Error(t, err)
} else {
assert.NoError(t, err)
assert.Equal(t, tt.expected, result)
}
})
}
}
// TestBindData_CaseInsensitive tests case-insensitive binding
func TestBindData_CaseInsensitive(t *testing.T) {
data := map[string][]string{
"NAME": {"John Doe"},
"Age": {"30"},
"EMAIL": {"john@example.com"},
}
var result SimpleStruct
err := BindData(&result, data, "query", nil)
assert.NoError(t, err)
assert.Equal(t, "John Doe", result.Name)
assert.Equal(t, 30, result.Age)
assert.Equal(t, "john@example.com", result.Email)
}
// TestBindData_PointerFields tests binding to pointer fields
func TestBindData_PointerFields(t *testing.T) {
tests := []struct {
name string
data map[string][]string
expected PointerStruct
}{
{
name: "valid pointers",
data: map[string][]string{
"name": {"John"},
"age": {"30"},
"active": {"true"},
"score": {"95.5"},
},
expected: PointerStruct{
Name: stringPtr("John"),
Age: intPtr(30),
Active: boolPtr(true),
Score: float64Ptr(95.5),
},
},
{
name: "empty values become zero values",
data: map[string][]string{
"name": {""},
"age": {""},
"active": {""},
"score": {""},
},
expected: PointerStruct{
Name: stringPtr(""),
Age: intPtr(0),
Active: boolPtr(false),
Score: float64Ptr(0.0),
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
var result PointerStruct
err := BindData(&result, tt.data, "query", nil)
assert.NoError(t, err)
if tt.expected.Name != nil {
require.NotNil(t, result.Name)
assert.Equal(t, *tt.expected.Name, *result.Name)
}
if tt.expected.Age != nil {
require.NotNil(t, result.Age)
assert.Equal(t, *tt.expected.Age, *result.Age)
}
if tt.expected.Active != nil {
require.NotNil(t, result.Active)
assert.Equal(t, *tt.expected.Active, *result.Active)
}
if tt.expected.Score != nil {
require.NotNil(t, result.Score)
assert.Equal(t, *tt.expected.Score, *result.Score)
}
})
}
}
// TestBindData_SliceFields tests binding to slice fields
func TestBindData_SliceFields(t *testing.T) {
data := map[string][]string{
"tags": {"go", "web", "framework"},
"numbers": {"1", "2", "3"},
"floats": {"1.1", "2.2", "3.3"},
"booleans": {"true", "false", "true"},
}
var result SliceStruct
err := BindData(&result, data, "query", nil)
assert.NoError(t, err)
assert.Equal(t, []string{"go", "web", "framework"}, result.Tags)
assert.Equal(t, []int{1, 2, 3}, result.Numbers)
assert.Equal(t, []float64{1.1, 2.2, 3.3}, result.Floats)
assert.Equal(t, []bool{true, false, true}, result.Booleans)
}
// TestBindData_NestedStruct tests binding to nested structs
func TestBindData_NestedStruct(t *testing.T) {
// Note: The binding implementation doesn't support dot notation like "user.name"
// It only binds to nested structs that have no explicit tag
data := map[string][]string{
"name": {"John Doe"},
"age": {"30"},
"email": {"john@example.com"},
"company": {"Acme Corp"},
}
var result NestedStruct
err := BindData(&result, data, "query", nil)
assert.NoError(t, err)
// Only the company field should be set because User has no explicit tag
assert.Equal(t, "", result.User.Name)
assert.Equal(t, 0, result.User.Age)
assert.Equal(t, "", result.User.Email)
assert.Equal(t, "Acme Corp", result.Company)
}
// TestBindData_CustomUnmarshaler tests custom unmarshaler implementations
func TestBindData_CustomUnmarshaler(t *testing.T) {
customTime := "2023-12-01T10:00:00Z"
multipleValues := []string{"value1", "value2", "value3"}
textValue := "hello world"
data := map[string][]string{
"custom": {customTime},
"multiple": multipleValues,
"text": {textValue},
"normal": {"normal value"},
}
var result StructWithUnmarshalers
err := BindData(&result, data, "query", nil)
assert.NoError(t, err)
// Test custom unmarshaler
parsedTime, err := time.Parse(time.RFC3339, customTime)
assert.NoError(t, err)
assert.Equal(t, parsedTime, result.Custom.Value)
// Test multiple unmarshaler
assert.Equal(t, multipleValues, result.Multiple.Values)
// Test text unmarshaler
assert.Equal(t, textValue, result.Text.Value)
// Test normal field
assert.Equal(t, "normal value", result.Normal)
}
// TestBindData_MapBinding tests binding to map types
func TestBindData_MapBinding(t *testing.T) {
t.Run("map[string]string", func(t *testing.T) {
data := map[string][]string{
"key1": {"value1"},
"key2": {"value2"},
}
var result map[string]string
err := BindData(&result, data, "query", nil)
assert.NoError(t, err)
assert.Equal(t, map[string]string{
"key1": "value1",
"key2": "value2",
}, result)
})
t.Run("map[string][]string", func(t *testing.T) {
data := map[string][]string{
"key1": {"value1", "value2"},
"key2": {"value3"},
}
var result map[string][]string
err := BindData(&result, data, "query", nil)
assert.NoError(t, err)
assert.Equal(t, data, result)
})
t.Run("map[string]interface{}", func(t *testing.T) {
data := map[string][]string{
"key1": {"value1"},
"key2": {"value2"},
}
var result map[string]interface{}
err := BindData(&result, data, "query", nil)
assert.NoError(t, err)
assert.Equal(t, map[string]interface{}{
"key1": "value1",
"key2": "value2",
}, result)
})
t.Run("unsupported map type", func(t *testing.T) {
data := map[string][]string{
"key1": {"value1"},
}
var result map[string]int
err := BindData(&result, data, "query", nil)
assert.NoError(t, err) // Should not error, just not bind
assert.Nil(t, result)
})
}
// TestBindData_FileBinding tests file binding functionality
func TestBindData_FileBinding(t *testing.T) {
// Create mock file headers
file1 := &multipart.FileHeader{
Filename: "document.pdf",
Header: make(textproto.MIMEHeader),
}
file1.Header.Set("Content-Type", "application/pdf")
file2 := &multipart.FileHeader{
Filename: "image.jpg",
Header: make(textproto.MIMEHeader),
}
file2.Header.Set("Content-Type", "image/jpeg")
file3 := &multipart.FileHeader{
Filename: "avatar.png",
Header: make(textproto.MIMEHeader),
}
file3.Header.Set("Content-Type", "image/png")
data := map[string][]string{
"name": {"John Doe"},
}
files := map[string][]*multipart.FileHeader{
"document": {file1},
"images": {file2, file3},
"avatar": {file3},
}
var result StructWithFiles
err := BindData(&result, data, "form", files)
assert.NoError(t, err)
assert.Equal(t, "John Doe", result.Name)
assert.Equal(t, file1, result.Document)
assert.Equal(t, []*multipart.FileHeader{file2, file3}, result.Images)
assert.Equal(t, file3, result.Avatar)
}
// TestBindData_FileBindingErrors tests file binding error cases
func TestBindData_FileBindingErrors(t *testing.T) {
t.Run("non-existent file field", func(t *testing.T) {
var result StructWithFiles
err := BindData(&result, map[string][]string{}, "form", map[string][]*multipart.FileHeader{})
assert.NoError(t, err)
assert.Nil(t, result.Document)
assert.Nil(t, result.Images)
assert.Nil(t, result.Avatar)
})
t.Run("binding to struct FileHeader (should error)", func(t *testing.T) {
type InvalidFileStruct struct {
File multipart.FileHeader `form:"file"` // Should be pointer
}
file := &multipart.FileHeader{
Filename: "test.txt",
}
files := map[string][]*multipart.FileHeader{
"file": {file},
}
var result InvalidFileStruct
err := BindData(&result, map[string][]string{}, "form", files)
assert.Error(t, err)
assert.Contains(t, err.Error(), "binding to multipart.FileHeader struct is not supported")
})
}
// TestBindData_AnonymousStruct tests anonymous struct field handling
func TestBindData_AnonymousStruct(t *testing.T) {
t.Run("valid anonymous struct without tags", func(t *testing.T) {
// Note: The anonymous struct field needs to be initialized first
data := map[string][]string{
"name": {"John Doe"},
"age": {"30"},
"email": {"john@example.com"},
"extra": {"some extra data"},
}
var result AnonymousStructField
result.SimpleStruct = &SimpleStruct{}
err := BindData(&result, data, "query", nil)
assert.NoError(t, err)
// The SimpleStruct fields should be bound because the anonymous field has no tag
assert.Equal(t, "John Doe", result.Name)
assert.Equal(t, 30, result.Age)
assert.Equal(t, "john@example.com", result.Email)
assert.Equal(t, "some extra data", result.Extra)
})
t.Run("anonymous struct with tags (should error)", func(t *testing.T) {
type AnonymousWithTags struct {
*SimpleStruct `query:"user"`
Extra string `query:"extra"`
}
data := map[string][]string{
"name": {"John"},
}
var result AnonymousWithTags
result.SimpleStruct = &SimpleStruct{}
err := BindData(&result, data, "query", nil)
assert.Error(t, err)
assert.Contains(t, err.Error(), "query/param/form tags are not allowed with anonymous struct field")
})
t.Run("nested struct without explicit tags", func(t *testing.T) {
// This shows how nested structs actually work - they bind when they have no explicit tag
type NestedStructNoTag struct {
Inner SimpleStruct
Extra string `query:"extra"`
}
data := map[string][]string{
"name": {"John Doe"},
"age": {"30"},
"email": {"john@example.com"},
"extra": {"some extra data"},
}
var result NestedStructNoTag
err := BindData(&result, data, "query", nil)
assert.NoError(t, err)
assert.Equal(t, "John Doe", result.Inner.Name)
assert.Equal(t, 30, result.Inner.Age)
assert.Equal(t, "john@example.com", result.Inner.Email)
assert.Equal(t, "some extra data", result.Extra)
})
}
// TestBindData_ErrorConditions tests various error conditions
func TestBindData_ErrorConditions(t *testing.T) {
t.Run("nil destination", func(t *testing.T) {
err := BindData(nil, map[string][]string{}, "query", nil)
assert.NoError(t, err) // Should not error, just return
})
t.Run("non-struct destination", func(t *testing.T) {
var result string
err := BindData(&result, map[string][]string{"key": {"value"}}, "form", nil)
assert.Error(t, err)
assert.Contains(t, err.Error(), "binding element must be a struct")
})
t.Run("param/query/header with non-struct (should not error)", func(t *testing.T) {
var result string
err := BindData(&result, map[string][]string{"key": {"value"}}, "query", nil)
assert.NoError(t, err) // Should not error for these tags
})
t.Run("unsupported field type", func(t *testing.T) {
type UnsupportedStruct struct {
Field chan int `query:"field"`
}
data := map[string][]string{
"field": {"value"},
}
var result UnsupportedStruct
err := BindData(&result, data, "query", nil)
assert.Error(t, err)
assert.Contains(t, err.Error(), "unknown type")
})
t.Run("unsettable field", func(t *testing.T) {
type UnsettableStruct struct {
unexported string `query:"unexported"`
}
data := map[string][]string{
"unexported": {"value"},
}
var result UnsettableStruct
err := BindData(&result, data, "query", nil)
assert.NoError(t, err) // Should not error, just skip unsettable field
assert.Empty(t, result.unexported)
})
}
// ErrorUnmarshaler is a type that always returns an error
type ErrorUnmarshaler struct{}
func (e *ErrorUnmarshaler) UnmarshalParam(param string) error {
return errors.New("custom unmarshal error")
}
// ErrorMultipleUnmarshaler is a type that always returns an error for multiple params
type ErrorMultipleUnmarshaler struct{}
func (e *ErrorMultipleUnmarshaler) UnmarshalParams(params []string) error {
return errors.New("custom multiple unmarshal error")
}
// ErrorTextUnmarshaler is a type that always returns an error for text unmarshaling
type ErrorTextUnmarshaler struct{}
func (e *ErrorTextUnmarshaler) UnmarshalText(text []byte) error {
return errors.New("custom text unmarshal error")
}
// TestBindData_CustomUnmarshalerErrors tests error cases for custom unmarshalers
func TestBindData_CustomUnmarshalerErrors(t *testing.T) {
t.Run("BindUnmarshaler error", func(t *testing.T) {
type TestStruct struct {
Field ErrorUnmarshaler `query:"field"`
}
data := map[string][]string{
"field": {"value"},
}
var result TestStruct
err := BindData(&result, data, "query", nil)
assert.Error(t, err)
assert.Contains(t, err.Error(), "custom unmarshal error")
})
t.Run("BindMultipleUnmarshaler error", func(t *testing.T) {
type TestStruct struct {
Field ErrorMultipleUnmarshaler `query:"field"`
}
data := map[string][]string{
"field": {"value1", "value2"},
}
var result TestStruct
err := BindData(&result, data, "query", nil)
assert.Error(t, err)
assert.Contains(t, err.Error(), "custom multiple unmarshal error")
})
t.Run("TextUnmarshaler error", func(t *testing.T) {
type TestStruct struct {
Field ErrorTextUnmarshaler `query:"field"`
}
data := map[string][]string{
"field": {"value"},
}
var result TestStruct
err := BindData(&result, data, "query", nil)
assert.Error(t, err)
assert.Contains(t, err.Error(), "custom text unmarshal error")
})
}
// TestBindData_NumericConversions tests numeric type conversions
func TestBindData_NumericConversions(t *testing.T) {
type NumericStruct struct {
Int int `query:"int"`
Int8 int8 `query:"int8"`
Int16 int16 `query:"int16"`
Int32 int32 `query:"int32"`
Int64 int64 `query:"int64"`
Uint uint `query:"uint"`
Uint8 uint8 `query:"uint8"`
Uint16 uint16 `query:"uint16"`
Uint32 uint32 `query:"uint32"`
Uint64 uint64 `query:"uint64"`
Float32 float32 `query:"float32"`
Float64 float64 `query:"float64"`
Bool bool `query:"bool"`
}
data := map[string][]string{
"int": {"-42"},
"int8": {"-128"},
"int16": {"-32768"},
"int32": {"-2147483648"},
"int64": {"-9223372036854775808"},
"uint": {"42"},
"uint8": {"255"},
"uint16": {"65535"},
"uint32": {"4294967295"},
"uint64": {"18446744073709551615"},
"float32": {"3.14"},
"float64": {"3.14159265359"},
"bool": {"true"},
}
var result NumericStruct
err := BindData(&result, data, "query", nil)
assert.NoError(t, err)
assert.Equal(t, -42, result.Int)
assert.Equal(t, int8(-128), result.Int8)
assert.Equal(t, int16(-32768), result.Int16)
assert.Equal(t, int32(-2147483648), result.Int32)
assert.Equal(t, int64(-9223372036854775808), result.Int64)
assert.Equal(t, uint(42), result.Uint)
assert.Equal(t, uint8(255), result.Uint8)
assert.Equal(t, uint16(65535), result.Uint16)
assert.Equal(t, uint32(4294967295), result.Uint32)
assert.Equal(t, uint64(18446744073709551615), result.Uint64)
assert.Equal(t, float32(3.14), result.Float32)
assert.Equal(t, float64(3.14159265359), result.Float64)
assert.True(t, result.Bool)
}
// TestIsFieldMultipartFile tests the isFieldMultipartFile function
func TestIsFieldMultipartFile(t *testing.T) {
tests := []struct {
name string
fieldType reflect.Type
expectedOK bool
expectedErr bool
}{
{
name: "FileHeader pointer",
fieldType: reflect.TypeOf(&multipart.FileHeader{}),
expectedOK: true,
expectedErr: false,
},
{
name: "FileHeader slice",
fieldType: reflect.TypeOf([]multipart.FileHeader(nil)),
expectedOK: true,
expectedErr: false,
},
{
name: "FileHeader pointer slice",
fieldType: reflect.TypeOf([]*multipart.FileHeader(nil)),
expectedOK: true,
expectedErr: false,
},
{
name: "FileHeader struct (should error)",
fieldType: reflect.TypeOf(multipart.FileHeader{}),
expectedOK: true,
expectedErr: true,
},
{
name: "unsupported type",
fieldType: reflect.TypeOf(""),
expectedOK: false,
expectedErr: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
ok, err := isFieldMultipartFile(tt.fieldType)
if tt.expectedErr {
assert.Error(t, err)
} else {
assert.NoError(t, err)
}
assert.Equal(t, tt.expectedOK, ok)
})
}
}
// TestSetMultipartFileHeaderTypes tests the setMultipartFileHeaderTypes function
func TestSetMultipartFileHeaderTypes(t *testing.T) {
file1 := &multipart.FileHeader{Filename: "file1.txt"}
file2 := &multipart.FileHeader{Filename: "file2.txt"}
files := map[string][]*multipart.FileHeader{
"files": {file1, file2},
}
t.Run("FileHeader pointer slice", func(t *testing.T) {
var headers []*multipart.FileHeader
field := reflect.ValueOf(&headers).Elem()
result := setMultipartFileHeaderTypes(field, "files", files)
assert.True(t, result)
assert.Equal(t, []*multipart.FileHeader{file1, file2}, headers)
})
t.Run("FileHeader slice", func(t *testing.T) {
var headers []multipart.FileHeader
field := reflect.ValueOf(&headers).Elem()
result := setMultipartFileHeaderTypes(field, "files", files)
assert.True(t, result)
assert.Len(t, headers, 2)
assert.Equal(t, "file1.txt", headers[0].Filename)
assert.Equal(t, "file2.txt", headers[1].Filename)
})
t.Run("FileHeader pointer", func(t *testing.T) {
var header *multipart.FileHeader
field := reflect.ValueOf(&header).Elem()
result := setMultipartFileHeaderTypes(field, "files", files)
assert.True(t, result)
assert.Equal(t, file1, header)
})
t.Run("unsupported type", func(t *testing.T) {
var s string
field := reflect.ValueOf(&s).Elem()
result := setMultipartFileHeaderTypes(field, "files", files)
assert.False(t, result)
})
t.Run("non-existent field", func(t *testing.T) {
var header *multipart.FileHeader
field := reflect.ValueOf(&header).Elem()
result := setMultipartFileHeaderTypes(field, "nonexistent", files)
assert.False(t, result)
})
}
// TestSetWithProperType tests the setWithProperType function
func TestSetWithProperType(t *testing.T) {
tests := []struct {
name string
valueKind reflect.Kind
value string
setupField func() reflect.Value
expectedErr bool
verify func(t *testing.T, field reflect.Value)
}{
{
name: "int",
valueKind: reflect.Int,
value: "42",
setupField: func() reflect.Value {
return reflect.New(reflect.TypeOf(0)).Elem()
},
expectedErr: false,
verify: func(t *testing.T, field reflect.Value) {
assert.Equal(t, int64(42), field.Int())
},
},
{
name: "string",
valueKind: reflect.String,
value: "hello",
setupField: func() reflect.Value {
return reflect.New(reflect.TypeOf("")).Elem()
},
expectedErr: false,
verify: func(t *testing.T, field reflect.Value) {
assert.Equal(t, "hello", field.String())
},
},
{
name: "bool",
valueKind: reflect.Bool,
value: "true",
setupField: func() reflect.Value {
return reflect.New(reflect.TypeOf(false)).Elem()
},
expectedErr: false,
verify: func(t *testing.T, field reflect.Value) {
assert.True(t, field.Bool())
},
},
{
name: "float64",
valueKind: reflect.Float64,
value: "3.14",
setupField: func() reflect.Value {
return reflect.New(reflect.TypeOf(0.0)).Elem()
},
expectedErr: false,
verify: func(t *testing.T, field reflect.Value) {
assert.Equal(t, 3.14, field.Float())
},
},
{
name: "pointer to int",
valueKind: reflect.Ptr,
value: "42",
setupField: func() reflect.Value {
// Create a pointer to int and return the pointer value
var intVar *int
return reflect.ValueOf(&intVar).Elem() // Get the pointer field itself
},
expectedErr: false,
verify: func(t *testing.T, field reflect.Value) {
// After calling setWithProperType, the pointer should be set to point to 42
if field.IsNil() {
t.Error("Expected field to be non-nil after setting")
} else {
assert.Equal(t, int64(42), field.Elem().Int())
}
},
},
{
name: "invalid int",
valueKind: reflect.Int,
value: "not-a-number",
setupField: func() reflect.Value {
return reflect.New(reflect.TypeOf(0)).Elem()
},
expectedErr: true,
verify: nil,
},
{
name: "unknown type",
valueKind: reflect.Chan,
value: "value",
setupField: func() reflect.Value {
ch := make(chan int)
return reflect.ValueOf(&ch).Elem()
},
expectedErr: true,
verify: nil,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
field := tt.setupField()
err := setWithProperType(tt.valueKind, tt.value, field)
if tt.expectedErr {
assert.Error(t, err)
} else {
assert.NoError(t, err)
if tt.verify != nil {
tt.verify(t, field)
}
}
})
}
}
// Helper functions for tests
func stringPtr(s string) *string {
return &s
}
func intPtr(i int) *int {
return &i
}
func boolPtr(b bool) *bool {
return &b
}
func float64Ptr(f float64) *float64 {
return &f
}
// TestUnmarshalInputToField tests the unmarshalInputToField function
func TestUnmarshalInputToField(t *testing.T) {
t.Run("BindUnmarshaler", func(t *testing.T) {
custom := &CustomUnmarshaler{}
field := reflect.ValueOf(custom)
testTime := "2023-12-01T10:00:00Z"
ok, err := unmarshalInputToField(reflect.Ptr, testTime, field)
assert.True(t, ok)
assert.NoError(t, err)
expectedTime, _ := time.Parse(time.RFC3339, testTime)
assert.Equal(t, expectedTime, custom.Value)
})
t.Run("TextUnmarshaler", func(t *testing.T) {
text := &TextUnmarshaler{}
field := reflect.ValueOf(text)
testValue := "hello world"
ok, err := unmarshalInputToField(reflect.Ptr, testValue, field)
assert.True(t, ok)
assert.NoError(t, err)
assert.Equal(t, testValue, text.Value)
})
t.Run("non-unmarshaler", func(t *testing.T) {
s := &struct{}{}
field := reflect.ValueOf(s)
ok, err := unmarshalInputToField(reflect.Ptr, "value", field)
assert.False(t, ok)
assert.NoError(t, err)
})
}
// TestUnmarshalInputsToField tests the unmarshalInputsToField function
func TestUnmarshalInputsToField(t *testing.T) {
t.Run("BindMultipleUnmarshaler", func(t *testing.T) {
multiple := &CustomMultipleUnmarshaler{}
field := reflect.ValueOf(multiple)
values := []string{"value1", "value2", "value3"}
ok, err := unmarshalInputsToField(reflect.Ptr, values, field)
assert.True(t, ok)
assert.NoError(t, err)
assert.Equal(t, values, multiple.Values)
})