Repository navigation
Expand file tree
/
Copy pathencoder_test.go
More file actions
1540 lines (1374 loc) Β· 40.9 KB
/
Copy pathencoder_test.go
File metadata and controls
1540 lines (1374 loc) Β· 40.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 schema
import (
"fmt"
"math"
"reflect"
"slices"
"strconv"
"strings"
"sync"
"testing"
"time"
)
type E1 struct {
F01 int `schema:"f01"`
F02 int `schema:"-"`
F03 string `schema:"f03"`
F04 string `schema:"f04,omitempty"`
F05 bool `schema:"f05"`
F06 bool `schema:"f06"`
F07 *string `schema:"f07"`
F08 *int8 `schema:"f08"`
F09 float64 `schema:"f09"`
F10 func() `schema:"f10"`
F11 inner
}
type inner struct {
F12 int
}
type SimpleStructForBenchmarkEncode struct {
A string `schema:"a"`
B int `schema:"b"`
C bool `schema:"c"`
D float64 `schema:"d"`
E struct {
F float64 `schema:"f"`
} `schema:"e"`
}
func TestFilled(t *testing.T) {
f07 := "seven"
var f08 int8 = 8
s := &E1{
F01: 1,
F02: 2,
F03: "three",
F04: "four",
F05: true,
F06: false,
F07: &f07,
F08: &f08,
F09: 1.618,
F10: func() {},
F11: inner{12},
}
vals := make(map[string][]string)
errs := NewEncoder().Encode(s, vals)
valExists(t, "f01", "1", vals)
valNotExists(t, "f02", vals)
valExists(t, "f03", "three", vals)
valExists(t, "f05", "true", vals)
valExists(t, "f06", "false", vals)
valExists(t, "f07", "seven", vals)
valExists(t, "f08", "8", vals)
valExists(t, "f09", "1.618000", vals)
valExists(t, "F12", "12", vals)
emptyErr := MultiError{}
if errs.Error() == emptyErr.Error() {
t.Errorf("Expected error got %v", errs)
}
}
type Aa int
type E3 struct {
F01 bool `schema:"f01"`
F02 float32 `schema:"f02"`
F03 float64 `schema:"f03"`
F04 int `schema:"f04"`
F05 int8 `schema:"f05"`
F06 int16 `schema:"f06"`
F07 int32 `schema:"f07"`
F08 int64 `schema:"f08"`
F09 string `schema:"f09"`
F10 uint `schema:"f10"`
F11 uint8 `schema:"f11"`
F12 uint16 `schema:"f12"`
F13 uint32 `schema:"f13"`
F14 uint64 `schema:"f14"`
F15 Aa `schema:"f15"`
}
// Test compatibility with default decoder types.
func TestCompat(t *testing.T) {
src := &E3{
F01: true,
F02: 4.2,
F03: 4.3,
F04: -42,
F05: -43,
F06: -44,
F07: -45,
F08: -46,
F09: "foo",
F10: 42,
F11: 43,
F12: 44,
F13: 45,
F14: 46,
F15: 1,
}
dst := &E3{}
vals := make(map[string][]string)
encoder := NewEncoder()
decoder := NewDecoder()
encoder.RegisterEncoder(src.F15, func(reflect.Value) string { return "1" })
decoder.RegisterConverter(src.F15, func(string) reflect.Value { return reflect.ValueOf(1) })
err := encoder.Encode(src, vals)
if err != nil {
t.Errorf("Encoder has non-nil error: %v", err)
}
err = decoder.Decode(dst, vals)
if err != nil {
t.Errorf("Decoder has non-nil error: %v", err)
}
if *src != *dst {
t.Errorf("Decoder-Encoder compatibility: expected %v, got %v\n", src, dst)
}
}
// Integer fields are routed to width-specific utils formatters; check each
// against strconv over its full, or boundary, range.
func TestEncodeIntegerWidths(t *testing.T) {
t.Parallel()
type sized struct {
I8 int8 `schema:"i8"`
I16 int16 `schema:"i16"`
I32 int32 `schema:"i32"`
I64 int64 `schema:"i64"`
I int `schema:"i"`
U8 uint8 `schema:"u8"`
U16 uint16 `schema:"u16"`
U32 uint32 `schema:"u32"`
U64 uint64 `schema:"u64"`
U uint `schema:"u"`
}
enc := NewEncoder()
check := func(s sized) {
t.Helper()
vals := make(map[string][]string)
if err := enc.Encode(&s, vals); err != nil {
t.Fatalf("Encode(%+v): %v", s, err)
}
for key, want := range map[string]string{
"i8": strconv.FormatInt(int64(s.I8), 10),
"i16": strconv.FormatInt(int64(s.I16), 10),
"i32": strconv.FormatInt(int64(s.I32), 10),
"i64": strconv.FormatInt(s.I64, 10),
"i": strconv.FormatInt(int64(s.I), 10),
"u8": strconv.FormatUint(uint64(s.U8), 10),
"u16": strconv.FormatUint(uint64(s.U16), 10),
"u32": strconv.FormatUint(uint64(s.U32), 10),
"u64": strconv.FormatUint(s.U64, 10),
"u": strconv.FormatUint(uint64(s.U), 10),
} {
if got := vals[key]; len(got) != 1 || got[0] != want {
t.Fatalf("%s of %+v = %v, want %q", key, s, got, want)
}
}
}
// The 8- and 16-bit widths are small enough to cover exhaustively.
for n := range 1 << 16 {
check(sized{
I8: int8(n), I16: int16(n), U8: uint8(n), U16: uint16(n),
I32: int32(n), I64: int64(n), I: n,
U32: uint32(n), U64: uint64(n), U: uint(n),
})
}
for _, n := range []int64{
math.MinInt32, math.MinInt32 + 1, -100, -99, -1, 0, 1, 99, 100,
math.MaxInt32 - 1, math.MaxInt32, math.MaxInt64, math.MinInt64,
} {
check(sized{
I32: int32(n), I64: n, I: int(n),
U32: uint32(n), U64: uint64(n), U: uint(n),
})
}
for _, n := range []uint64{
0, 1, 99, 100, math.MaxUint32 - 1, math.MaxUint32, math.MaxUint64,
} {
check(sized{U32: uint32(n), U64: n, U: uint(n)})
}
}
// encode skips reading a key back before writing it when the plan writes
// every key once. The shapes that break that β duplicate aliases, and nested
// structs whose keys land in the same map β must still accumulate values.
func TestEncodeRepeatedKeys(t *testing.T) {
t.Parallel()
type dup struct {
A string `schema:"same"`
B string `schema:"same"`
C int `schema:"same"`
}
vals := make(map[string][]string)
if err := NewEncoder().Encode(&dup{A: "a", B: "b", C: 7}, vals); err != nil {
t.Fatal(err)
}
if got := vals["same"]; len(got) != 3 || got[0] != "a" || got[1] != "b" || got[2] != "7" {
t.Fatalf("duplicate aliases lost values: %v", got)
}
// A nested struct is encoded into the same map without a prefix, so its
// key collides with the outer one.
type inner struct {
V string `schema:"shared"`
}
type outerVal struct {
Inner inner `schema:"inner"`
V string `schema:"shared"`
}
vals = make(map[string][]string)
if err := NewEncoder().Encode(&outerVal{Inner: inner{V: "in"}, V: "out"}, vals); err != nil {
t.Fatal(err)
}
if got := vals["shared"]; len(got) != 2 {
t.Fatalf("nested struct key collision lost values: %v", got)
}
// Same through a pointer to a struct, which recurses when non-nil and
// writes its own key when nil.
type outerPtr struct {
Inner *inner `schema:"shared"`
V string `schema:"shared"`
}
vals = make(map[string][]string)
if err := NewEncoder().Encode(&outerPtr{Inner: &inner{V: "in"}, V: "out"}, vals); err != nil {
t.Fatal(err)
}
if got := vals["shared"]; len(got) != 2 {
t.Fatalf("pointer struct key collision lost values: %v", got)
}
vals = make(map[string][]string)
if err := NewEncoder().Encode(&outerPtr{V: "out"}, vals); err != nil {
t.Fatal(err)
}
if got := vals["shared"]; len(got) != 2 {
t.Fatalf("nil pointer struct key collision lost values: %v", got)
}
// The flag itself: a flat struct with distinct names is the only shape
// the fast path may claim.
type flat struct {
A string `schema:"a"`
B int `schema:"b"`
}
enc := NewEncoder()
for _, tc := range []struct {
typ reflect.Type
want bool
}{
{reflect.TypeFor[flat](), true},
{reflect.TypeFor[dup](), false},
{reflect.TypeFor[outerVal](), false},
{reflect.TypeFor[outerPtr](), false},
} {
if got := enc.structInfo(tc.typ).freshKeys; got != tc.want {
t.Fatalf("%s: freshKeys=%v, want %v", tc.typ, got, tc.want)
}
}
}
// Now that the plan settles which applies, omitempty on a struct field must
// still honour an IsZero method, and still fall back to comparing fields.
func TestOmitEmptyStructFields(t *testing.T) {
t.Parallel()
type plain struct {
A int
B string
}
type S struct {
T time.Time `schema:"t,omitempty"`
P plain `schema:"p,omitempty"`
Keep time.Time `schema:"keep"`
After string `schema:"after"`
}
enc := NewEncoder()
enc.RegisterEncoder(time.Time{}, func(v reflect.Value) string {
tv, _ := reflect.TypeAssert[time.Time](v)
return tv.Format(time.RFC3339)
})
enc.RegisterEncoder(plain{}, func(v reflect.Value) string {
pv, _ := reflect.TypeAssert[plain](v)
return fmt.Sprintf("%d/%s", pv.A, pv.B)
})
// Zero values of both shapes are dropped; the field without omitempty and
// the one after them are not.
vals := make(map[string][]string)
if err := enc.Encode(&S{After: "x"}, vals); err != nil {
t.Fatal(err)
}
if _, ok := vals["t"]; ok {
t.Errorf("zero time.Time should be omitted: %v", vals["t"])
}
if _, ok := vals["p"]; ok {
t.Errorf("zero struct should be omitted: %v", vals["p"])
}
if got := vals["after"]; len(got) != 1 || got[0] != "x" {
t.Errorf("after = %v", got)
}
if len(vals["keep"]) != 1 {
t.Errorf("field without omitempty should be encoded: %v", vals["keep"])
}
// Non-zero values of both shapes are kept.
vals = make(map[string][]string)
src := S{T: time.Date(2025, 1, 1, 12, 0, 0, 0, time.UTC), P: plain{A: 1, B: "b"}}
if err := enc.Encode(&src, vals); err != nil {
t.Fatal(err)
}
if len(vals["t"]) != 1 {
t.Errorf("non-zero time.Time should be encoded: %v", vals["t"])
}
if got := vals["p"]; len(got) != 1 || got[0] != "1/b" {
t.Errorf("non-zero struct should be encoded: %v", got)
}
// A non-addressable source takes the same decisions.
vals = make(map[string][]string)
if err := enc.Encode(src, vals); err != nil {
t.Fatal(err)
}
if len(vals["t"]) != 1 || len(vals["p"]) != 1 {
t.Errorf("non-addressable source dropped values: %v", vals)
}
vals = make(map[string][]string)
if err := enc.Encode(S{After: "x"}, vals); err != nil {
t.Fatal(err)
}
if _, ok := vals["t"]; ok {
t.Errorf("non-addressable zero time.Time should be omitted: %v", vals["t"])
}
if _, ok := vals["p"]; ok {
t.Errorf("non-addressable zero struct should be omitted: %v", vals["p"])
}
}
func BenchmarkOmitEmptyStructEncode(b *testing.B) {
type S struct {
T time.Time `schema:"t,omitempty"`
A string `schema:"a"`
}
enc := NewEncoder()
enc.RegisterEncoder(time.Time{}, func(v reflect.Value) string {
tv, _ := reflect.TypeAssert[time.Time](v)
return tv.Format(time.RFC3339)
})
s := S{A: "x"}
b.ReportAllocs()
for b.Loop() {
vals := make(map[string][]string, 4)
if err := enc.Encode(&s, vals); err != nil {
b.Fatal(err)
}
}
}
func BenchmarkSizedIntegerEncode(b *testing.B) {
type sized struct {
I8 int8 `schema:"i8"`
I16 int16 `schema:"i16"`
I32 int32 `schema:"i32"`
U8 uint8 `schema:"u8"`
U16 uint16 `schema:"u16"`
U32 uint32 `schema:"u32"`
}
s := sized{I8: -12, I16: -1234, I32: -123456, U8: 12, U16: 1234, U32: 123456}
enc := NewEncoder()
b.ReportAllocs()
for b.Loop() {
vals := make(map[string][]string, 8)
if err := enc.Encode(&s, vals); err != nil {
b.Fatal(err)
}
}
}
func BenchmarkFloatFieldEncode(b *testing.B) {
type floats struct {
A float64 `schema:"a"`
B float32 `schema:"b"`
}
s := floats{A: 3.14159, B: 2.71828}
enc := NewEncoder()
b.ReportAllocs()
for b.Loop() {
vals := make(map[string][]string, 4)
if err := enc.Encode(&s, vals); err != nil {
b.Fatal(err)
}
}
}
func TestEmpty(t *testing.T) {
s := &E1{
F01: 1,
F02: 2,
F03: "three",
}
estr := "schema: encoder not found for <nil>"
vals := make(map[string][]string)
err := NewEncoder().Encode(s, vals)
if err.Error() != estr {
t.Errorf("Expected: %s, got %v", estr, err)
}
valExists(t, "f03", "three", vals)
valNotExists(t, "f04", vals)
}
func TestStruct(t *testing.T) {
estr := "schema: interface must be a struct"
vals := make(map[string][]string)
err := NewEncoder().Encode("hello world", vals)
if err.Error() != estr {
t.Errorf("Expected: %s, got %v", estr, err)
}
}
func TestSlices(t *testing.T) {
type oneAsWord int
ones := []oneAsWord{1, 2}
s1 := &struct {
ones []oneAsWord `schema:"ones"`
ints []int `schema:"ints"`
nonempty []int `schema:"nonempty"`
empty []int `schema:"empty,omitempty"`
}{ones, []int{1, 1}, []int{}, []int{}}
vals := make(map[string][]string)
encoder := NewEncoder()
encoder.RegisterEncoder(ones[0], func(v reflect.Value) string { return "one" })
err := encoder.Encode(s1, vals)
if err != nil {
t.Errorf("Encoder has non-nil error: %v", err)
}
valsExist(t, "ones", []string{"one", "one"}, vals)
valsExist(t, "ints", []string{"1", "1"}, vals)
valsExist(t, "nonempty", []string{}, vals)
valNotExists(t, "empty", vals)
}
func TestCompatSlices(t *testing.T) {
type oneAsWord int
type s1 struct {
Ones []oneAsWord `schema:"ones"`
Ints []int `schema:"ints"`
}
ones := []oneAsWord{1, 1}
src := &s1{ones, []int{1, 1}}
vals := make(map[string][]string)
dst := &s1{}
encoder := NewEncoder()
encoder.RegisterEncoder(ones[0], func(v reflect.Value) string { return "one" })
decoder := NewDecoder()
decoder.RegisterConverter(ones[0], func(s string) reflect.Value {
if s == "one" {
return reflect.ValueOf(1)
}
return reflect.ValueOf(2)
})
err := encoder.Encode(src, vals)
if err != nil {
t.Errorf("Encoder has non-nil error: %v", err)
}
err = decoder.Decode(dst, vals)
if err != nil {
t.Errorf("Dncoder has non-nil error: %v", err)
}
if len(src.Ints) != len(dst.Ints) || len(src.Ones) != len(dst.Ones) {
t.Fatalf("Expected %v, got %v", src, dst)
}
for i, v := range src.Ones {
if dst.Ones[i] != v {
t.Fatalf("Expected %v, got %v", v, dst.Ones[i])
}
}
for i, v := range src.Ints {
if dst.Ints[i] != v {
t.Fatalf("Expected %v, got %v", v, dst.Ints[i])
}
}
}
func TestRegisterEncoder(t *testing.T) {
type oneAsWord int
type twoAsWord int
type oneSliceAsWord []int
s1 := &struct {
oneAsWord
twoAsWord
oneSliceAsWord
}{1, 2, []int{1, 1}}
v1 := make(map[string][]string)
encoder := NewEncoder()
encoder.RegisterEncoder(s1.oneAsWord, func(v reflect.Value) string { return "one" })
encoder.RegisterEncoder(s1.twoAsWord, func(v reflect.Value) string { return "two" })
encoder.RegisterEncoder(s1.oneSliceAsWord, func(v reflect.Value) string { return "one" })
err := encoder.Encode(s1, v1)
if err != nil {
t.Errorf("Encoder has non-nil error: %v", err)
}
valExists(t, "oneAsWord", "one", v1)
valExists(t, "twoAsWord", "two", v1)
valExists(t, "oneSliceAsWord", "one", v1)
}
func TestEncoderOrder(t *testing.T) {
type builtinEncoderSimple int
type builtinEncoderSimpleOverridden int
type builtinEncoderSlice []int
type builtinEncoderSliceOverridden []int
type builtinEncoderStruct struct{ nr int }
type builtinEncoderStructOverridden struct{ nr int }
s1 := &struct {
builtinEncoderSimple `schema:"simple"`
builtinEncoderSimpleOverridden `schema:"simple_overridden"`
builtinEncoderSlice `schema:"slice"`
builtinEncoderSliceOverridden `schema:"slice_overridden"`
builtinEncoderStruct `schema:"struct"`
builtinEncoderStructOverridden `schema:"struct_overridden"`
}{
1,
1,
[]int{2},
[]int{2},
builtinEncoderStruct{3},
builtinEncoderStructOverridden{3},
}
v1 := make(map[string][]string)
encoder := NewEncoder()
encoder.RegisterEncoder(s1.builtinEncoderSimpleOverridden, func(v reflect.Value) string { return "one" })
encoder.RegisterEncoder(s1.builtinEncoderSliceOverridden, func(v reflect.Value) string { return "two" })
encoder.RegisterEncoder(s1.builtinEncoderStructOverridden, func(v reflect.Value) string { return "three" })
err := encoder.Encode(s1, v1)
if err != nil {
t.Errorf("Encoder has non-nil error: %v", err)
}
valExists(t, "simple", "1", v1)
valExists(t, "simple_overridden", "one", v1)
valExists(t, "slice", "2", v1)
valExists(t, "slice_overridden", "two", v1)
valExists(t, "nr", "3", v1)
valExists(t, "struct_overridden", "three", v1)
}
func valExists(t *testing.T, key string, expect string, result map[string][]string) {
valsExist(t, key, []string{expect}, result)
}
func valsExist(t *testing.T, key string, expect []string, result map[string][]string) {
vals, ok := result[key]
if !ok {
t.Fatalf("Key not found. Expected: %s", key)
}
if len(expect) != len(vals) {
t.Fatalf("Expected: %v, got: %v", expect, vals)
}
for i, v := range expect {
if vals[i] != v {
t.Fatalf("Unexpected value. Expected: %v, got %v", v, vals[i])
}
}
}
func valNotExists(t *testing.T, key string, result map[string][]string) {
if val, ok := result[key]; ok {
t.Error("Key not omitted. Expected: empty; got: " + val[0] + ".")
}
}
func valsLength(t *testing.T, expectedLength int, result map[string][]string) {
length := len(result)
if length != expectedLength {
t.Errorf("Expected length of %v, but got %v", expectedLength, length)
}
}
func noError(t *testing.T, err error) {
if err != nil {
t.Errorf("Unexpected error. Got %v", err)
}
}
type E4 struct {
ID string `json:"id"`
}
func TestEncoderSetAliasTag(t *testing.T) {
data := map[string][]string{}
s := E4{
ID: "foo",
}
encoder := NewEncoder()
encoder.SetAliasTag("json")
err := encoder.Encode(&s, data)
if err != nil {
t.Fatalf("Failed to encode: %v", err)
}
valExists(t, "id", "foo", data)
}
type E5 struct {
F01 int `schema:"f01,omitempty"`
F02 string `schema:"f02,omitempty"`
F03 *string `schema:"f03,omitempty"`
F04 *int8 `schema:"f04,omitempty"`
F05 float64 `schema:"f05,omitempty"`
F06 E5F06 `schema:"f06,omitempty"`
F07 E5F06 `schema:"f07,omitempty"`
F08 []string `schema:"f08,omitempty"`
F09 []string `schema:"f09,omitempty"`
}
type E5F06 struct {
F0601 string `schema:"f0601,omitempty"`
}
func TestEncoderWithOmitempty(t *testing.T) {
vals := map[string][]string{}
s := E5{
F02: "test",
F07: E5F06{
F0601: "test",
},
F09: []string{"test"},
}
encoder := NewEncoder()
err := encoder.Encode(&s, vals)
if err != nil {
t.Fatalf("Failed to encode: %v", err)
}
valNotExists(t, "f01", vals)
valExists(t, "f02", "test", vals)
valNotExists(t, "f03", vals)
valNotExists(t, "f04", vals)
valNotExists(t, "f05", vals)
valNotExists(t, "f06", vals)
valExists(t, "f0601", "test", vals)
valNotExists(t, "f08", vals)
valsExist(t, "f09", []string{"test"}, vals)
}
type E6 struct {
F01 *inner
F02 *inner
F03 *inner `schema:",omitempty"`
}
func TestStructPointer(t *testing.T) {
vals := map[string][]string{}
s := E6{
F01: &inner{2},
}
encoder := NewEncoder()
err := encoder.Encode(&s, vals)
if err != nil {
t.Fatalf("Failed to encode: %v", err)
}
valExists(t, "F12", "2", vals)
valExists(t, "F02", "null", vals)
valNotExists(t, "F03", vals)
}
func TestRegisterEncoderCustomArrayType(t *testing.T) {
type CustomInt []int
type S1 struct {
SomeInts CustomInt `schema:",omitempty"`
}
ss := []S1{
{},
{CustomInt{}},
{CustomInt{1, 2, 3}},
}
for s := range ss {
vals := map[string][]string{}
encoder := NewEncoder()
encoder.RegisterEncoder(CustomInt{}, func(value reflect.Value) string {
return fmt.Sprint(value.Interface())
})
err := encoder.Encode(ss[s], vals)
if err != nil {
t.Fatalf("Failed to encode: %v", err)
}
}
}
func TestRegisterEncoderStructIsZero(t *testing.T) {
type S1 struct {
SomeTime1 time.Time `schema:"tim1,omitempty"`
SomeTime2 time.Time `schema:"tim2,omitempty"`
}
ss := []*S1{
{
SomeTime1: time.Date(2020, 8, 4, 13, 30, 1, 0, time.UTC),
},
}
for s := range ss {
vals := map[string][]string{}
encoder := NewEncoder()
encoder.RegisterEncoder(time.Time{}, func(value reflect.Value) string {
tv, _ := reflect.TypeAssert[time.Time](value)
return tv.Format(time.RFC3339Nano)
})
err := encoder.Encode(ss[s], vals)
if err != nil {
t.Errorf("Encoder has non-nil error: %v", err)
}
ta, ok := vals["tim1"]
if !ok {
t.Error("expected tim1 to be present")
}
if len(ta) != 1 {
t.Error("expected tim1 to be present")
}
if ta[0] != "2020-08-04T13:30:01Z" {
t.Error("expected correct tim1 time")
}
_, ok = vals["tim2"]
if ok {
t.Error("expected tim1 not to be present")
}
}
}
func TestRegisterEncoderWithPtrType(t *testing.T) {
type CustomTime struct {
time time.Time
}
type S1 struct {
DateStart *CustomTime
DateEnd *CustomTime
Empty *CustomTime `schema:"empty,omitempty"`
}
ss := S1{
DateStart: &CustomTime{time: time.Now()},
DateEnd: nil,
}
encoder := NewEncoder()
encoder.RegisterEncoder(&CustomTime{}, func(value reflect.Value) string {
if value.IsNil() {
return ""
}
custom, _ := reflect.TypeAssert[*CustomTime](value)
return custom.time.String()
})
vals := map[string][]string{}
err := encoder.Encode(ss, vals)
noError(t, err)
valsLength(t, 2, vals)
valExists(t, "DateStart", ss.DateStart.time.String(), vals)
valExists(t, "DateEnd", "", vals)
}
func TestTimeDurationEncoding(t *testing.T) {
type DurationStruct struct {
Timeout time.Duration `schema:"timeout"`
}
vals := map[string][]string{}
testData := DurationStruct{
Timeout: 3 * time.Minute,
}
enc := NewEncoder()
enc.RegisterEncoder(time.Duration(0), func(v reflect.Value) string {
d, _ := reflect.TypeAssert[time.Duration](v)
return d.String() // "3m0s"
})
err := enc.Encode(&testData, vals)
if err != nil {
t.Fatalf("Failed to encode time.Duration: %v", err)
}
got, ok := vals["timeout"]
if !ok || len(got) < 1 {
t.Fatalf("Encoded map missing key 'timeout'")
}
if got[0] != (3 * time.Minute).String() {
t.Errorf("Expected %q, got %q", (3 * time.Minute).String(), got[0])
}
}
// Test for omitempty with zero time.Duration.
func TestTimeDurationOmitEmpty(t *testing.T) {
type DurationStruct struct {
Timeout time.Duration `schema:"timeout,omitempty"`
}
vals := map[string][]string{}
testData := DurationStruct{
Timeout: 0,
}
enc := NewEncoder()
enc.RegisterEncoder(time.Duration(0), func(v reflect.Value) string {
d, _ := reflect.TypeAssert[time.Duration](v)
return d.String()
})
err := enc.Encode(&testData, vals)
if err != nil {
t.Fatalf("Failed to encode time.Duration: %v", err)
}
// Should be omitted since 0 for time.Duration is "zero" and tagged as omitempty
if _, found := vals["timeout"]; found {
t.Errorf("Expected 'timeout' to be omitted, but it was present: %v", vals["timeout"])
}
}
func TestEncoderZeroAndNonZeroFields(t *testing.T) {
type ZeroTestStruct struct {
A string `schema:"a,omitempty"`
B int `schema:"b,omitempty"`
C float64 `schema:"c,omitempty"`
D bool `schema:"d,omitempty"`
E *int `schema:"e,omitempty"`
F *string `schema:"f,omitempty"`
G string `schema:"g"` // no omitempty
}
vals := map[string][]string{}
intVal := 42
strVal := "Hello"
s := ZeroTestStruct{
A: "",
B: 0,
C: 0.0,
D: false,
E: &intVal,
F: &strVal,
G: "MustEncode",
}
enc := NewEncoder()
err := enc.Encode(&s, vals)
if err != nil {
t.Fatalf("Encoding error: %v", err)
}
// Fields A, B, C, D are zero and should be omitted
if _, found := vals["a"]; found {
t.Errorf("Expected 'a' to be omitted for zero string")
}
if _, found := vals["b"]; found {
t.Errorf("Expected 'b' to be omitted for zero int")
}
if _, found := vals["c"]; found {
t.Errorf("Expected 'c' to be omitted for zero float")
}
if _, found := vals["d"]; found {
t.Errorf("Expected 'd' to be omitted for false bool")
}
// E is a pointer to an int, so it should appear
gotE, found := vals["e"]
if !found {
t.Error("Expected 'e' to be present")
} else if len(gotE) != 1 || gotE[0] != "42" {
t.Errorf("Expected '42', got %v", gotE)
}
// F is a pointer to string, so it should appear
gotF, found := vals["f"]
if !found {
t.Error("Expected 'f' to be present")
} else if len(gotF) != 1 || gotF[0] != "Hello" {
t.Errorf("Expected 'Hello', got %v", gotF)
}
// G has no omitempty tag and must be encoded
gotG, found := vals["g"]
if !found {
t.Error("Expected 'g' to be present")
} else if len(gotG) != 1 || gotG[0] != "MustEncode" {
t.Errorf("Expected 'MustEncode', got %v", gotG)
}
}
func BenchmarkSimpleStructEncode(b *testing.B) {
s := SimpleStructForBenchmarkEncode{
A: "abc",
B: 123,
C: true,
D: 3.14,
E: struct {
F float64 `schema:"f"`
}{F: 6.28},
}
enc := NewEncoder()
vals := map[string][]string{}
for b.Loop() {
_ = enc.Encode(&s, vals)
}
}
func BenchmarkSimpleStructEncodeParallel(b *testing.B) {
s := SimpleStructForBenchmarkEncode{
A: "abc",
B: 123,
C: true,
D: 3.14,
E: struct {
F float64 `schema:"f"`
}{F: 6.28},
}
enc := NewEncoder()
b.ResetTimer()
b.RunParallel(func(pb *testing.PB) {
vals := map[string][]string{}
for pb.Next() {
_ = enc.Encode(&s, vals)
}
})
}
type LargeStructForBenchmarkEncode struct {
F1 string `schema:"f1"`
F2 string `schema:"f2"`
F3 int `schema:"f3"`
F4 int `schema:"f4"`
F5 []string `schema:"f5"`
F6 []int `schema:"f6"`
F7 float64 `schema:"f7"`
F8 bool `schema:"f8"`
F9 struct {
N1 time.Time `schema:"n1"`
N2 string `schema:"n2"`
} `schema:"f9"`