-
Notifications
You must be signed in to change notification settings - Fork 13
/
json_test.go
2022 lines (1937 loc) · 45.6 KB
/
json_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
package jettison
import (
"bytes"
"context"
"crypto/rand"
"encoding/json"
"errors"
"fmt"
"math"
"math/big"
"net"
"reflect"
"regexp"
"strconv"
"sync"
"testing"
"time"
)
type (
jmr string
jmv []string
)
func (*jmr) MarshalJSON() ([]byte, error) { return []byte(`"XYZ"`), nil }
func (jmv) MarshalJSON() ([]byte, error) { return []byte(`"ZYX"`), nil }
type (
mapss struct {
M map[string]string
}
inner struct {
M map[string]string
}
outer struct {
M map[string]inner
}
z struct {
S []byte
}
y struct {
P float64 `json:"p,omitempty"`
Q uint64 `json:"q,omitempty"`
R uint8
}
x struct {
A *string `json:"a,string"`
B1 int64 `json:"b1,string"`
B2 uint16 `json:"b2"`
C *bool `json:"c,string"`
D float32
E1 *[]int
E2 []string
E3 []jmr
F1 [4]string
F2 [1]jmr
F3 *[1]jmr
G1 map[int]*string
G2 map[string]*map[string]string
G3 map[int]map[string]map[int]string
G4 map[string]mapss
G5 outer
G6 map[int]jmr
G7 map[int]*jmr
G8 map[int]bool `json:",omitempty"`
H1 jmr
H2 *jmr
H3 jmv
H4 *jmv
I time.Time
J time.Duration
K json.Number
L json.RawMessage
M1 interface{}
M2 interface{}
N struct{}
X *x
*y
z `json:"z"`
}
)
var (
s = "Loreum"
b = true
m = map[string]string{"b": "c"}
xx = x{
A: &s,
B1: -42,
B2: 42,
C: &b,
D: math.MaxFloat32,
E1: &[]int{1, 2, 3},
E2: []string{"x", "y", "z"},
E3: []jmr{"1"},
F1: [4]string{"a", "b", "c", "d"},
F2: [1]jmr{"1"},
F3: &[1]jmr{"1"},
G1: map[int]*string{2: &s, 3: new(string)},
G2: map[string]*map[string]string{"a": &m},
G3: map[int]map[string]map[int]string{1: {"a": {2: "b"}}},
G4: map[string]mapss{"1": {M: map[string]string{"2": "3"}}},
G5: outer{map[string]inner{"outer": {map[string]string{"key": "val"}}}},
G6: map[int]jmr{1: "jmr"},
G7: map[int]*jmr{1: new(jmr)},
G8: map[int]bool{},
H1: "jmp",
H2: nil,
H3: nil,
H4: nil,
I: time.Now(),
J: 3 * time.Minute,
K: "3.14",
L: []byte(`{ "a":"b" }`),
M1: uint32(255),
M2: &s,
X: &x{H1: "jmv"},
y: &y{R: math.MaxUint8},
z: z{S: []byte("Loreum")},
}
)
// marshalCompare compares the JSON encoding
// of v between Jettison and encoding/json.
func marshalCompare(t *testing.T, v interface{}, name string) {
jb1, err := Marshal(v)
if err != nil {
t.Fatal(err)
}
jb2, err := MarshalOpts(v)
if err != nil {
t.Fatal(err)
}
if !bytes.Equal(jb1, jb2) {
t.Error("non-equal outputs for Marshal and MarshalOpts")
}
jb3, err := Append([]byte(nil), v)
if err != nil {
t.Fatal(err)
}
if !bytes.Equal(jb1, jb3) {
t.Error("non-equal outputs for Marshal and Append")
}
sb, err := json.Marshal(v)
if err != nil {
t.Fatal(err)
}
t.Logf("standard: %s", string(sb))
t.Logf("jettison: %s", string(jb1))
if !bytes.Equal(jb1, sb) {
t.Errorf("%s: non-equal outputs", name)
}
}
func marshalCompareError(t *testing.T, v interface{}, name string) {
_, errj := Marshal(v)
if errj == nil {
t.Fatalf("expected non-nil error")
}
_, errs := json.Marshal(v)
if errs == nil {
t.Fatalf("expected non-nil error")
}
t.Logf("standard: %s", errs)
t.Logf("jettison: %s", errj)
if errs.Error() != errj.Error() {
t.Errorf("%s: non-equal outputs", name)
}
}
func TestAll(t *testing.T) {
marshalCompare(t, nil, "nil")
marshalCompare(t, xx, "non-pointer")
marshalCompare(t, &xx, "pointer")
}
func TestInvalidEncodeOpts(t *testing.T) {
for _, opt := range []Option{
TimeLayout(""),
DurationFormat(DurationFmt(-1)),
DurationFormat(DurationFmt(6)),
WithContext(nil), // nolint:staticcheck
} {
_, err1 := MarshalOpts(struct{}{}, opt)
_, err2 := AppendOpts([]byte(nil), struct{}{}, opt)
for _, err := range []error{err1, err2} {
if err != nil {
e, ok := err.(*InvalidOptionError)
if !ok {
t.Errorf("got %T, want InvalidOptionError", err)
}
if e.Error() == "" {
t.Errorf("expected non-empty error message")
}
} else {
t.Error("expected non-nil error")
}
}
}
}
// TestBasicTypes tests the marshaling of basic types.
func TestBasicTypes(t *testing.T) {
testdata := []interface{}{
true,
false,
"Loreum",
int8(math.MaxInt8),
int16(math.MaxInt16),
int32(math.MaxInt32),
int64(math.MaxInt64),
uint8(math.MaxUint8),
uint16(math.MaxUint16),
uint32(math.MaxUint32),
uint64(math.MaxUint64),
uintptr(0xBEEF),
(*bool)(nil),
(*int)(nil),
(*string)(nil),
}
for _, v := range testdata {
marshalCompare(t, v, "")
}
}
// TestCompositeTypes tests the marshaling of composite types.
func TestCompositeTypes(t *testing.T) {
var (
jmref = jmr("jmr")
jmval = jmv([]string{"a", "b", "c"})
)
testdata := []interface{}{
[]uint{},
[]int{1, 2, 3},
[]int(nil),
(*[]int)(nil),
[]string{"a", "b", "c"},
[2]bool{true, false},
(*[4]string)(nil),
map[string]int{"a": 1, "b": 2},
&map[int]string{1: "a", 2: "b"},
(map[string]int)(nil),
time.Now(),
3*time.Minute + 35*time.Second,
jmref,
&jmref,
jmval,
&jmval,
}
for _, v := range testdata {
marshalCompare(t, v, "")
}
}
// TestUnsupportedTypes tests that marshaling an
// unsupported type such as channel, complex, and
// function value returns an UnsupportedTypeError.
// The error message is compared with the one that
// is returned by json.Marshal.
func TestUnsupportedTypes(t *testing.T) {
testdata := []interface{}{
make(chan int),
func() {},
complex64(0),
complex128(0),
make([]chan int, 1),
[1]complex64{},
&[1]complex128{},
map[int]chan bool{1: make(chan bool)},
struct{ F func() }{func() {}},
&struct{ C complex64 }{0},
}
for _, v := range testdata {
marshalCompareError(t, v, "")
}
}
// TestInvalidFloatValues tests that encoding an
// invalid float value returns UnsupportedValueError.
func TestInvalidFloatValues(t *testing.T) {
for _, v := range []float64{
math.NaN(),
math.Inf(-1),
math.Inf(1),
} {
_, err := Marshal(v)
if err != nil {
if _, ok := err.(*UnsupportedValueError); !ok {
t.Errorf("got %T, want UnsupportedValueError", err)
}
} else {
t.Error("got nil, want non-nil error")
}
// Error message must be the same as
// the one of the standard library.
marshalCompareError(t, v, "")
}
}
// TestJSONNumber tests that a json.Number literal value
// can be marshaled, and that an error is returned if it
// isn't a valid number according to the JSON grammar.
func TestJSONNumber(t *testing.T) {
valid := []json.Number{
"42",
"-42",
"24.42",
"-666.66",
"3.14",
"-3.14",
"1e3",
"1E-6",
"1E+42",
// Special case to keep backward
// compatibility with Go1.5, that
// encodes the empty string as "0".
"",
}
for _, v := range valid {
marshalCompare(t, v, "valid")
}
invalid := []json.Number{
"1E+4.0",
"084",
"-03.14",
"-",
"invalid",
}
for _, v := range invalid {
marshalCompareError(t, v, "invalid")
}
}
func TestInvalidTime(t *testing.T) {
// Special case to test error when the year
// of the date is outside of range [0.9999].
// see golang.org/issue/4556#c15.
for _, tm := range []time.Time{
time.Date(-1, time.January, 1, 0, 0, 0, 0, time.UTC),
time.Date(10000, time.January, 1, 0, 0, 0, 0, time.UTC),
} {
_, err := Marshal(tm)
if err != nil {
want := "time: year outside of range [0,9999]"
if err.Error() != want {
t.Errorf("got %q, want %q", err.Error(), want)
}
} else {
t.Error("got nil, want non-nil error")
}
}
}
// TestRenamedByteSlice tests that a name type
// that represents a slice of bytes is marshaled
// the same way as a regular byte slice.
func TestRenamedByteSlice(t *testing.T) {
type (
b byte
b1 []byte
b2 []b
)
testdata := []interface{}{
b1("byte slice 1"),
b2("byte slice 2"),
}
for _, v := range testdata {
marshalCompare(t, v, "")
}
}
func TestByteSliceSizes(t *testing.T) {
makeSlice := func(size int) []byte {
b := make([]byte, size)
if _, err := rand.Read(b); err != nil {
t.Fatal(err)
}
return b
}
for _, v := range []interface{}{
makeSlice(0),
makeSlice(1024),
makeSlice(2048),
makeSlice(4096),
makeSlice(8192),
} {
marshalCompare(t, v, "")
}
}
// TestSortedSyncMap tests the marshaling
// of a sorted sync.Map value.
func TestSortedSyncMap(t *testing.T) {
var sm sync.Map
sm.Store(1, "one")
sm.Store("a", 42)
sm.Store("b", false)
sm.Store(mkvstrMarshaler("c"), -42)
sm.Store(mkrstrMarshaler("d"), true)
sm.Store(mkvintMarshaler(42), 1)
sm.Store(mkrintMarshaler(42), 2)
b, err := Marshal(&sm)
if err != nil {
t.Fatal(err)
}
want := `{"1":"one","42":2,"MKVINT":1,"a":42,"b":false,"c":-42,"d":true}`
if !bytes.Equal(b, []byte(want)) {
t.Errorf("got %#q, want %#q", b, want)
}
}
// TestUnsortedSyncMap tests the marshaling
// of an unsorted sync.Map value.
func TestUnsortedSyncMap(t *testing.T) {
// entries maps each interface k/v
// pair to the string representation
// of the key in payload.
entries := map[string]struct {
key interface{}
val interface{}
}{
"1": {1, "one"},
"a": {"a", 42},
"b": {"b", false},
"c": {mkvstrMarshaler("c"), -42},
"d": {mkrstrMarshaler("d"), true},
"MKVINT": {mkvintMarshaler(42), 1},
"42": {mkrintMarshaler(42), 2},
}
var sm sync.Map
for _, e := range entries {
sm.Store(e.key, e.val)
}
bts, err := MarshalOpts(&sm, UnsortedMap())
if err != nil {
t.Fatal(err)
}
m := make(map[string]interface{})
if err := json.Unmarshal(bts, &m); err != nil {
t.Fatal(err)
}
// Unmarshaled map must contain exactly the
// number of entries added to the sync map.
if g, w := len(m), len(entries); g != w {
t.Errorf("invalid lengths: got %d, want %d", g, w)
}
for k, v := range m {
// Compare the marshaled representation
// of each value to avoid false-positive
// between integer and float types.
b1, err1 := json.Marshal(v)
b2, err2 := json.Marshal(entries[k].val)
if err1 != nil {
t.Fatal(err)
}
if err2 != nil {
t.Fatal(err2)
}
if !bytes.Equal(b1, b2) {
t.Errorf("for key %s: got %v, want %v", k, b1, b2)
}
}
}
// TestInvalidSyncMapKeys tests that marshaling a
// sync.Map with unsupported key types returns an
// error.
func TestInvalidSyncMapKeys(t *testing.T) {
testInvalidSyncMapKeys(t, true)
testInvalidSyncMapKeys(t, false)
}
func testInvalidSyncMapKeys(t *testing.T, sorted bool) {
for _, f := range []func(sm *sync.Map){
func(sm *sync.Map) { sm.Store(false, nil) },
func(sm *sync.Map) { sm.Store(new(int), nil) },
func(sm *sync.Map) { sm.Store(nil, nil) },
} {
var (
sm sync.Map
err error
)
f(&sm) // add entries to sm
if sorted {
_, err = Marshal(&sm)
} else {
_, err = MarshalOpts(&sm, UnsortedMap())
}
if err == nil {
t.Error("expected a non-nil error")
}
}
}
// TestCompositeMapValue tests the marshaling
// of maps with composite values.
func TestCompositeMapValue(t *testing.T) {
type x struct {
A string `json:"a"`
B int `json:"b"`
C bool `json:"c"`
}
type y []uint32
for _, v := range []interface{}{
map[string]x{
"1": {A: "A", B: 42, C: true},
"2": {A: "A", B: 84, C: false},
},
map[string]y{
"3": {7, 8, 9},
"2": {4, 5, 6},
"1": nil,
},
map[string]*x{
"b": {A: "A", B: 128, C: true},
"a": nil,
"c": {},
},
map[string]interface{}{
"1": 42,
"2": "two",
"3": nil,
"4": (*int64)(nil),
"5": x{A: "A"},
"6": &x{A: "A", B: 256, C: true},
},
} {
marshalCompare(t, v, "")
}
}
type (
mkstr string
mkint int64
mkvstrMarshaler string
mkrstrMarshaler string
mkvintMarshaler uint64
mkrintMarshaler int
mkvcmpMarshaler struct{}
)
func (mkvstrMarshaler) MarshalText() ([]byte, error) { return []byte("MKVSTR"), nil }
func (*mkrstrMarshaler) MarshalText() ([]byte, error) { return []byte("MKRSTR"), nil }
func (mkvintMarshaler) MarshalText() ([]byte, error) { return []byte("MKVINT"), nil }
func (*mkrintMarshaler) MarshalText() ([]byte, error) { return []byte("MKRINT"), nil }
func (mkvcmpMarshaler) MarshalText() ([]byte, error) { return []byte("MKVCMP"), nil }
// TestMapKeyPrecedence tests that the precedence
// order of map key types is respected during marshaling.
func TestMapKeyPrecedence(t *testing.T) {
testdata := []interface{}{
map[mkstr]string{"K": "V"},
map[mkint]string{1: "V"},
map[mkvstrMarshaler]string{"K": "V"},
map[mkrstrMarshaler]string{"K": "V"},
map[mkvintMarshaler]string{42: "V"},
map[mkrintMarshaler]string{1: "one"},
map[mkvcmpMarshaler]string{{}: "V"},
}
for _, v := range testdata {
marshalCompare(t, v, "")
}
}
// TestJSONMarshaler tests that a type implementing the
// json.Marshaler interface is marshaled using the result
// of its MarshalJSON method call result.
// Because the types big.Int and time.Time also implements
// the encoding.TextMarshaler interface, the test ensures
// that MarshalJSON has priority.
func TestJSONMarshaler(t *testing.T) {
type x struct {
T1 time.Time `json:""`
T2 time.Time `json:",omitempty"`
T3 *time.Time `json:""`
T4 *time.Time `json:""` // nil
T5 *time.Time `json:",omitempty"` // nil
S1 bvjm `json:",omitempty"`
S2 bvjm `json:",omitempty"`
S3 bvjm `json:""`
S4 *bvjm `json:""`
S5 *bvjm `json:""` // nil
S6 *bvjm `json:",omitempty"` // nil
I1 big.Int `json:""`
I2 big.Int `json:",omitempty"`
I3 *big.Int `json:""`
I4 *big.Int `json:""` // nil
I5 *big.Int `json:",omitempty"` // nil
P1 brjm `json:",omitempty"`
P2 brjm `json:",omitempty"`
P3 brjm `json:""`
P4 *brjm `json:""`
P5 *brjm `json:""` // nil
P6 *brjm `json:",omitempty"` // nil
// NOTE
// time.Time = Non-pointer receiver of composite type.
// bvjm = Non-pointer receiver of basic type.
// big.Int = Pointer receiver of composite type.
// brjm = Pointer receiver of basic type.
}
var (
now = time.Now()
bval = bvjm("bval")
bref = brjm("bref")
xx = x{
T1: now,
T3: &now,
S1: "S1",
S4: &bval,
I1: *big.NewInt(math.MaxInt64),
I3: big.NewInt(math.MaxInt64),
P1: "P1",
P4: &bref,
}
)
marshalCompare(t, xx, "non-pointer")
marshalCompare(t, &xx, "pointer")
}
// TestTextMarshaler tests that a type implementing
// the encoding.TextMarshaler interface encodes to a
// quoted string of its MashalText method result.
func TestTextMarshaler(t *testing.T) {
type x struct {
S1 net.IP `json:""`
S2 net.IP `json:",omitempty"`
S3 *net.IP `json:""`
S4 *net.IP `json:""` // nil
S5 *net.IP `json:",omitempty"` // nil
I1 bvtm `json:",omitempty"`
I2 bvtm `json:",omitempty"`
I3 bvtm `json:""`
I4 *bvtm `json:""`
I5 *bvtm `json:""` // nil
I6 *bvtm `json:",omitempty"` // nil
F1 big.Float `json:""`
F2 big.Float `json:",omitempty"`
F3 *big.Float `json:""`
F4 *big.Float `json:""` // nil
F5 *big.Float `json:",omitempty"` // nil
P1 brtm `json:",omitempty"`
P2 brtm `json:",omitempty"`
P3 brtm `json:""`
P4 *brtm `json:""`
P5 *brtm `json:""` // nil
P6 *brtm `json:",omitempty"` // nil
// NOTE
// net.IP = Non-pointer receiver of composite type.
// bvtm = Non-pointer receiver of basic type.
// big.Float = Pointer receiver of composite type.
// brtm = Pointer receiver of basic type.
}
var (
bval = bvtm(42)
bref = brtm(42)
xx = x{
S1: net.IP{192, 168, 0, 1},
S3: &net.IP{127, 0, 0, 1},
I1: 42,
I4: &bval,
F1: *big.NewFloat(math.MaxFloat64),
F3: big.NewFloat(math.MaxFloat64),
P1: 42,
P4: &bref,
}
)
marshalCompare(t, xx, "non-pointer")
marshalCompare(t, &xx, "pointer")
}
type (
bvm string
brm string
cvm struct{}
crm struct{}
)
func (m bvm) AppendJSON(dst []byte) ([]byte, error) {
return append(dst, strconv.Quote(string(m))...), nil
}
func (m *brm) AppendJSON(dst []byte) ([]byte, error) {
return append(dst, strconv.Quote(string(*m))...), nil
}
func (m bvm) MarshalJSON() ([]byte, error) { return []byte(strconv.Quote(string(m))), nil }
func (m *brm) MarshalJSON() ([]byte, error) { return []byte(strconv.Quote(string(*m))), nil }
func (cvm) AppendJSON(dst []byte) ([]byte, error) { return append(dst, `"X"`...), nil }
func (cvm) MarshalJSON() ([]byte, error) { return []byte(`"X"`), nil }
func (*crm) AppendJSON(dst []byte) ([]byte, error) { return append(dst, `"Y"`...), nil }
func (*crm) MarshalJSON() ([]byte, error) { return []byte(`"Y"`), nil }
//nolint:dupl
func TestMarshaler(t *testing.T) {
type x struct {
S1 cvm `json:""`
S2 cvm `json:",omitempty"`
S3 *cvm `json:""`
S4 *cvm `json:""` // nil
S5 *cvm `json:",omitempty"` // nil
I1 bvm `json:",omitempty"`
I2 bvm `json:",omitempty"`
I3 bvm `json:""`
I4 *bvm `json:""`
I5 *bvm `json:""` // nil
I6 *bvm `json:",omitempty"` // nil
F1 crm `json:""`
F2 crm `json:",omitempty"`
F3 *crm `json:""`
F4 *crm `json:""` // nil
F5 *crm `json:",omitempty"` // nil
P1 brm `json:",omitempty"`
P2 brm `json:",omitempty"`
P3 brm `json:""`
P4 *brm `json:""`
P5 *brm `json:""` // nil
P6 *brm `json:",omitempty"` // nil
// NOTE
// cvm = Non-pointer receiver of composite type.
// bvm = Non-pointer receiver of basic type.
// crm = Pointer receiver of composite type.
// brm = Pointer receiver of basic type.
}
var (
bval = bvm("bval")
bref = brm("bref")
xx = x{
S1: cvm{},
S3: &cvm{},
I1: "I1",
I4: &bval,
F1: crm{},
F3: &crm{},
P1: "P1",
P4: &bref,
}
)
marshalCompare(t, xx, "non-pointer")
marshalCompare(t, &xx, "pointer")
}
type (
bvmctx string
brmctx string
cvmctx struct{}
crmctx struct{}
)
func (m bvmctx) AppendJSONContext(_ context.Context, dst []byte) ([]byte, error) {
return append(dst, strconv.Quote(string(m))...), nil
}
func (m bvmctx) MarshalJSON() ([]byte, error) {
return []byte(strconv.Quote(string(m))), nil
}
func (m *brmctx) AppendJSONContext(_ context.Context, dst []byte) ([]byte, error) {
return append(dst, strconv.Quote(string(*m))...), nil
}
func (m *brmctx) MarshalJSON() ([]byte, error) {
return []byte(strconv.Quote(string(*m))), nil
}
func (cvmctx) AppendJSONContext(_ context.Context, dst []byte) ([]byte, error) {
return append(dst, `"X"`...), nil
}
func (cvmctx) MarshalJSON() ([]byte, error) {
return []byte(`"X"`), nil
}
func (*crmctx) AppendJSONContext(_ context.Context, dst []byte) ([]byte, error) {
return append(dst, `"Y"`...), nil
}
func (*crmctx) MarshalJSON() ([]byte, error) {
return []byte(`"Y"`), nil
}
//nolint:dupl
func TestMarshalerCtx(t *testing.T) {
type x struct {
S1 cvmctx `json:""`
S2 cvmctx `json:",omitempty"`
S3 *cvmctx `json:""`
S4 *cvmctx `json:""` // nil
S5 *cvmctx `json:",omitempty"` // nil
I1 bvmctx `json:",omitempty"`
I2 bvmctx `json:",omitempty"`
I3 bvmctx `json:""`
I4 *bvmctx `json:""`
I5 *bvmctx `json:""` // nil
I6 *bvmctx `json:",omitempty"` // nil
F1 crmctx `json:""`
F2 crmctx `json:",omitempty"`
F3 *crmctx `json:""`
F4 *crmctx `json:""` // nil
F5 *crmctx `json:",omitempty"` // nil
P1 brmctx `json:",omitempty"`
P2 brmctx `json:",omitempty"`
P3 brmctx `json:""`
P4 *brmctx `json:""`
P5 *brmctx `json:""` // nil
P6 *brmctx `json:",omitempty"` // nil
// NOTE
// cvmctx = Non-pointer receiver of composite type.
// bvmctx = Non-pointer receiver of basic type.
// crmctx = Pointer receiver of composite type.
// brmctx = Pointer receiver of basic type.
}
var (
bval = bvmctx("bval")
bref = brmctx("bref")
xx = x{
S1: cvmctx{},
S3: &cvmctx{},
I1: "I1",
I4: &bval,
F1: crmctx{},
F3: &crmctx{},
P1: "P1",
P4: &bref,
}
)
marshalCompare(t, xx, "non-pointer")
marshalCompare(t, &xx, "pointer")
}
type (
niljetim string // jettison.Marshaler
nilmjctx string // jettison.MarshalerCtx
niljsonm string // json.Marshaler
niltextm string // encoding.TextMarshaler
)
// comboMarshaler combines the json.Marshaler
// and jettison.AppendMarshaler interfaces so
// that tests outputs can be compared.
type comboMarshaler interface {
AppendMarshaler
json.Marshaler
}
// comboMarshalerCtx combines the json.Marshaler
// and jettison.AppendMarshalerCtx interfaces so
// that tests outputs can be compared.
type comboMarshalerCtx interface {
AppendMarshalerCtx
json.Marshaler
}
func (*niljetim) MarshalJSON() ([]byte, error) { return []byte(`"W"`), nil }
func (*nilmjctx) MarshalJSON() ([]byte, error) { return []byte(`"X"`), nil }
func (*niljsonm) MarshalJSON() ([]byte, error) { return []byte(`"Y"`), nil }
func (*niltextm) MarshalText() ([]byte, error) { return []byte("Z"), nil }
func (*niljetim) AppendJSON(dst []byte) ([]byte, error) {
return append(dst, `"W"`...), nil
}
func (*nilmjctx) AppendJSONContext(_ context.Context, dst []byte) ([]byte, error) {
return append(dst, `"X"`...), nil
}
type (
errvjm struct{}
errrjm struct{}
errvtm struct{}
errrtm struct{}
errvm struct{}
errrm struct{}
errvmctx struct{}
errrmctx struct{}
)
var errMarshaler = errors.New("error")
func (errvjm) MarshalJSON() ([]byte, error) { return nil, errMarshaler }
func (*errrjm) MarshalJSON() ([]byte, error) { return nil, errMarshaler }
func (errvtm) MarshalText() ([]byte, error) { return nil, errMarshaler }
func (*errrtm) MarshalText() ([]byte, error) { return nil, errMarshaler }
func (errvm) AppendJSON(dst []byte) ([]byte, error) { return dst, errMarshaler }
func (*errrm) AppendJSON(dst []byte) ([]byte, error) { return dst, errMarshaler }
func (errvmctx) AppendJSONContext(_ context.Context, dst []byte) ([]byte, error) {
return dst, errMarshaler
}
func (*errrmctx) AppendJSONContext(_ context.Context, dst []byte) ([]byte, error) {
return dst, errMarshaler
}
// TestMarshalerError tests that a MarshalerError is
// returned when a MarshalText, MarshalJSON, WriteJSON
// or WriteJSONContext method returns an error.
func TestMarshalerError(t *testing.T) {
testdata := []interface{}{
errvjm{},
&errrjm{},
errvtm{},
&errrtm{},
errvm{},
&errrm{},
errvmctx{},
&errrmctx{},
}
for _, v := range testdata {
_, err := Marshal(v)
if err != nil {
me, ok := err.(*MarshalerError)
if !ok {
t.Fatalf("got %T, want MarshalerError", err)
}
typ := reflect.TypeOf(v)
if me.Type != typ {
t.Errorf("got %s, want %s", me.Type, typ)
}
if err := me.Unwrap(); err == nil {
t.Error("expected non-nil error")
}
if me.Error() == "" {
t.Error("expected non-empty error message")
}
} else {
t.Error("got nil, want non-nil error")
}
}
}
// TestStructFieldName tests that invalid struct
// field names are ignored during marshaling.
func TestStructFieldName(t *testing.T) {
//nolint:staticcheck
type x struct {
A string `json:" "` // valid, spaces
B string `json:"0123"` // valid, digits
C int `json:","` // invalid, comma
D int8 `json:"\\"` // invalid, backslash,
E int16 `json:"\""` // invalid, quotation mark
F int `json:"Вилиам"` // valid, UTF-8 runes
G bool `json:"<ben&jerry>"` // valid, HTML-escaped chars
Aβ int
}
marshalCompare(t, x{}, "")
}
// TestStructFieldOmitempty tests that the fields of
// a struct with the omitempty option are not encoded
// when they have the zero-value of their type.
func TestStructFieldOmitempty(t *testing.T) {
type x struct {
A string `json:",omitempty"`
B string `json:",omitempty"`
C *string `json:",omitempty"`
Ca *string `json:"a,omitempty"`
D *string `json:",omitempty"`
E bool `json:",omitempty"`
F int `json:",omitempty"`
F1 int8 `json:",omitempty"`
F2 int16 `json:",omitempty"`
F3 int32 `json:",omitempty"`
F4 int64 `json:",omitempty"`
G1 uint `json:",omitempty"`
G2 uint8 `json:",omitempty"`
G3 uint16 `json:",omitempty"`
G4 uint32 `json:",omitempty"`
G5 uint64 `json:",omitempty"`
G6 uintptr `json:",omitempty"`
H float32 `json:",omitempty"`
I float64 `json:",omitempty"`
J1 map[int]int `json:",omitempty"`
J2 map[int]int `json:",omitempty"`
J3 map[int]int `json:",omitempty"`
K1 []string `json:",omitempty"`
K2 []string `json:",omitempty"`
L1 [0]int `json:",omitempty"`
L2 [2]int `json:",omitempty"`
M1 interface{} `json:",omitempty"`
M2 interface{} `json:",omitempty"`
}
var (
s1 = "Loreum"
s2 = ""
xx = &x{
A: "A",
B: "",
C: &s1,
Ca: &s2,
D: nil,
J2: map[int]int{},
J3: map[int]int{1: 42},
K2: []string{"K2"},
M2: (*int)(nil),
}
)
marshalCompare(t, xx, "")
}