-
Notifications
You must be signed in to change notification settings - Fork 114
/
decode_slice_test.go
125 lines (117 loc) · 2.22 KB
/
decode_slice_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
package gojay
import (
"strings"
"testing"
"github.com/stretchr/testify/require"
)
type slicesTestObject struct {
sliceString []string
sliceInt []int
sliceFloat64 []float64
sliceBool []bool
}
func (s *slicesTestObject) UnmarshalJSONObject(dec *Decoder, k string) error {
switch k {
case "sliceString":
return dec.AddSliceString(&s.sliceString)
case "sliceInt":
return dec.AddSliceInt(&s.sliceInt)
case "sliceFloat64":
return dec.AddSliceFloat64(&s.sliceFloat64)
case "sliceBool":
return dec.AddSliceBool(&s.sliceBool)
}
return nil
}
func (s *slicesTestObject) NKeys() int {
return 4
}
func TestDecodeSlices(t *testing.T) {
testCases := []struct {
name string
json string
expectedResult slicesTestObject
err bool
}{
{
name: "basic slice string",
json: `{
"sliceString": ["foo","bar"]
}`,
expectedResult: slicesTestObject{
sliceString: []string{"foo", "bar"},
},
},
{
name: "basic slice bool",
json: `{
"sliceBool": [true,false]
}`,
expectedResult: slicesTestObject{
sliceBool: []bool{true, false},
},
},
{
name: "basic slice int",
json: `{
"sliceInt": [1,2,3]
}`,
expectedResult: slicesTestObject{
sliceInt: []int{1, 2, 3},
},
},
{
name: "basic slice float64",
json: `{
"sliceFloat64": [1.3,2.4,3.1]
}`,
expectedResult: slicesTestObject{
sliceFloat64: []float64{1.3, 2.4, 3.1},
},
},
{
name: "err slice float64",
json: `{
"sliceFloat64": [1.3",2.4,3.1]
}`,
err: true,
},
{
name: "err slice str",
json: `{
"sliceString": [",""]
}`,
err: true,
},
{
name: "err slice int",
json: `{
"sliceInt": [1t,2,3]
}`,
err: true,
},
{
name: "err slice bool",
json: `{
"sliceBool": [truo,false]
}`,
err: true,
},
}
for _, testCase := range testCases {
t.Run(
testCase.name,
func(t *testing.T) {
dec := BorrowDecoder(strings.NewReader(testCase.json))
var o slicesTestObject
err := dec.Decode(&o)
if testCase.err {
require.NotNil(t, err, "err should not be nil")
return
}
require.Nil(t, err, "err should be nil")
require.Equal(t, testCase.expectedResult, o)
},
)
}
}