-
-
Notifications
You must be signed in to change notification settings - Fork 5
/
parse_test.go
288 lines (248 loc) · 7.9 KB
/
parse_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
package queryparam_test
import (
"errors"
"fmt"
"github.com/tomwright/queryparam/v4"
"math"
"net/url"
"reflect"
"testing"
"time"
)
var urlValues = url.Values{}
var urlValuesNameAge = url.Values{
"name": []string{"tom"},
"age": []string{"26"},
}
// ExampleParse creates a dummy http request and parses the data into a struct
func ExampleParse() {
urlValues := url.Values{}
urlValues.Set("name", "Tom")
urlValues.Set("names", "Tom,Jim,Frank") // list of names separated by ,
urlValues.Set("dash-names", "Tom-Jim-Frank") // list of names separated by -
urlValues.Set("age", "123")
urlValues.Set("age32", "123")
urlValues.Set("age64", "123")
urlValues.Set("float32", "123.45")
urlValues.Set("float64", "123.45")
urlValues.Set("created-at", "2019-02-05T13:32:02Z")
urlValues.Set("bool-false", "false")
urlValues.Set("bool-true", "true")
urlValues.Set("bool-empty", "") // param set but no value means
urlValues.Set("present-empty", "") // param set but no value
urlValues.Set("present", "this is here")
requestData := struct {
Name string `queryparam:"name"`
Names []string `queryparam:"names"`
DashNames []string `queryparam:"dash-names" queryparamdelim:"-"`
Age int `queryparam:"age"`
Age32 int32 `queryparam:"age32"`
Age64 int64 `queryparam:"age64"`
Float32 float32 `queryparam:"float32"`
Float64 float64 `queryparam:"float64"`
CreatedAt time.Time `queryparam:"created-at"`
UpdatedAt time.Time `queryparam:"updated-at"`
BoolFalse bool `queryparam:"bool-false"`
BoolTrue bool `queryparam:"bool-true"`
BoolEmpty bool `queryparam:"bool-empty"`
PresentEmpty queryparam.Present `queryparam:"present-empty"`
Present queryparam.Present `queryparam:"present"`
NotPresent queryparam.Present `queryparam:"not-present"`
}{}
if err := queryparam.Parse(urlValues, &requestData); err != nil {
panic(err)
}
fmt.Printf("name: %s\n", requestData.Name)
fmt.Printf("names: %v\n", requestData.Names)
fmt.Printf("dash names: %v\n", requestData.DashNames)
fmt.Printf("age: %d\n", requestData.Age)
fmt.Printf("age32: %d\n", requestData.Age32)
fmt.Printf("age64: %d\n", requestData.Age64)
fmt.Printf("float32: %f\n", math.Round(float64(requestData.Float32))) // rounded to avoid floating point precision issues
fmt.Printf("float64: %f\n", math.Round(requestData.Float64)) // rounded to avoid floating point precision issues
fmt.Printf("created at: %s\n", requestData.CreatedAt.Format(time.RFC3339))
fmt.Printf("updated at: %s\n", requestData.UpdatedAt.Format(time.RFC3339))
fmt.Printf("bool false: %v\n", requestData.BoolFalse)
fmt.Printf("bool true: %v\n", requestData.BoolTrue)
fmt.Printf("bool empty: %v\n", requestData.BoolEmpty)
fmt.Printf("present empty: %v\n", requestData.PresentEmpty)
fmt.Printf("present: %v\n", requestData.Present)
fmt.Printf("not present: %v\n", requestData.NotPresent)
// Output:
// name: Tom
// names: [Tom Jim Frank]
// dash names: [Tom Jim Frank]
// age: 123
// age32: 123
// age64: 123
// float32: 123.000000
// float64: 123.000000
// created at: 2019-02-05T13:32:02Z
// updated at: 0001-01-01T00:00:00Z
// bool false: false
// bool true: true
// bool empty: false
// present empty: false
// present: true
// not present: false
}
func TestParse_FieldWithNoTagIsNotUsed(t *testing.T) {
t.Parallel()
req := &struct {
Name string ``
}{}
if err := queryparam.Parse(urlValues, req); err != nil {
t.Errorf("unexpected error: %v", err)
}
if exp, got := "", req.Name; exp != got {
t.Errorf("unexpected name. expected `%v`, got `%v`", exp, got)
}
}
func TestParse_InvalidURLValues(t *testing.T) {
t.Parallel()
req := &struct{}{}
err := queryparam.Parse(nil, req)
if exp, got := queryparam.ErrInvalidURLValues, err; exp != got {
t.Errorf("unexpected error. expected `%v`, got `%v`", exp, got)
}
}
func TestParse_NonPointerTarget(t *testing.T) {
t.Parallel()
req := struct{}{}
err := queryparam.Parse(urlValues, req)
if exp, got := queryparam.ErrNonPointerTarget, err; exp != got {
t.Errorf("unexpected error. expected `%v`, got `%v`", exp, got)
}
}
func TestParse_ParserUnhandledFieldType(t *testing.T) {
t.Parallel()
req := &struct {
Age struct{} `queryparam:"age"`
}{}
err := queryparam.Parse(urlValuesNameAge, req)
if !errors.Is(err, queryparam.ErrUnhandledFieldType) {
t.Errorf("unexpected error: %v", err)
}
}
func TestParse_SetterUnhandledFieldType(t *testing.T) {
t.Parallel()
req := &struct {
Age int `queryparam:"age"`
}{}
p := &queryparam.Parser{
Tag: "queryparam",
DelimiterTag: "queryparamdelim",
Delimiter: ",",
ValueParsers: queryparam.DefaultValueParsers(),
ValueSetters: map[reflect.Type]queryparam.ValueSetter{},
}
err := p.Parse(urlValuesNameAge, req)
if !errors.Is(err, queryparam.ErrUnhandledFieldType) {
t.Errorf("unexpected error: %v", err)
}
}
func TestParse_ValueParserErrorReturned(t *testing.T) {
t.Parallel()
tmpErr := errors.New("something bad happened")
p := &queryparam.Parser{
Tag: "queryparam",
DelimiterTag: "queryparamdelim",
Delimiter: ",",
ValueParsers: queryparam.DefaultValueParsers(),
ValueSetters: map[reflect.Type]queryparam.ValueSetter{
reflect.TypeOf(""): func(value reflect.Value, target reflect.Value) error {
return tmpErr
},
},
}
req := &struct {
Name string `queryparam:"name"`
}{}
err := p.Parse(urlValuesNameAge, req)
if !errors.Is(err, tmpErr) {
t.Errorf("unexpected error: %v", err)
}
}
func TestParse_EmptyTag(t *testing.T) {
t.Parallel()
req := &struct {
Name string `queryparam:""`
}{}
err := queryparam.Parse(urlValuesNameAge, req)
if !errors.Is(err, queryparam.ErrInvalidTag) {
t.Errorf("unexpected error: %v", err)
}
}
func TestParse_ValueSetterErrorReturned(t *testing.T) {
t.Parallel()
tmpErr := errors.New("something bad happened")
p := &queryparam.Parser{
Tag: "queryparam",
DelimiterTag: "queryparamdelim",
Delimiter: ",",
ValueParsers: map[reflect.Type]queryparam.ValueParser{
reflect.TypeOf(""): func(value string, delimiter string) (reflect.Value, error) {
return reflect.ValueOf(""), tmpErr
},
},
}
req := &struct {
Name string `queryparam:"name"`
}{}
err := p.Parse(urlValuesNameAge, req)
if !errors.Is(err, tmpErr) {
t.Errorf("unexpected error: %v", err)
}
}
func BenchmarkParse(b *testing.B) {
b.ResetTimer()
for i := 0; i < b.N; i++ {
data := struct {
Name string `queryparam:"name"`
NameList []string `queryparam:"name-list"`
NameListDash []string `queryparam:"name-list" queryparamdelim:"-"`
Age int `queryparam:"age"`
}{}
err := queryparam.Parse(urlValuesNameAge, &data)
if err != nil {
b.FailNow()
}
}
b.StopTimer()
b.ReportAllocs()
}
func TestErrInvalidParameterValue_Unwrap(t *testing.T) {
tmpErr := errors.New("something bad")
e := &queryparam.ErrInvalidParameterValue{
Err: tmpErr,
Parameter: "Name",
Field: "name",
Value: "asd",
Type: reflect.TypeOf(""),
}
exp := "invalid parameter value for field name (string) from parameter Name (asd): something bad"
if got := e.Error(); exp != got {
t.Errorf("expected `%s`, got `%s`", exp, got)
}
if !errors.Is(e, tmpErr) {
t.Error("expected is to return true")
}
}
func TestCannotSetValue_Unwrap(t *testing.T) {
tmpErr := errors.New("something bad")
e := &queryparam.ErrCannotSetValue{
Err: tmpErr,
Parameter: "Name",
Field: "name",
Value: "asd",
Type: reflect.TypeOf(""),
ParsedValue: reflect.ValueOf("asd"),
}
exp := "cannot set value for field name (string) from parameter Name (asd - asd): something bad"
if got := e.Error(); exp != got {
t.Errorf("expected `%s`, got `%s`", exp, got)
}
if !errors.Is(e, tmpErr) {
t.Error("expected is to return true")
}
}