-
Notifications
You must be signed in to change notification settings - Fork 24
/
Copy pathdata_test.go
executable file
·548 lines (508 loc) · 12.2 KB
/
data_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
// Copyright 2015 Alex Browne. All rights reserved.
// Use of this source code is governed by the MIT
// license, which can be found in the LICENSE file.
package forms
import (
"bytes"
"fmt"
"io"
"io/ioutil"
"mime/multipart"
"net/http"
"net/url"
"os"
"reflect"
"strings"
"testing"
)
func TestGet(t *testing.T) {
data := newData()
data.Values = map[string][]string{
"name": []string{"bob", "bill"},
"profession": []string{"plumber"},
}
table := []struct {
key string
expected string
}{
{
key: "name",
expected: "bob",
},
{
key: "profession",
expected: "plumber",
},
{
key: "favoriteColor",
expected: "",
},
}
for _, test := range table {
got := data.Get(test.key)
if got != test.expected {
t.Errorf("%s was incorrect. Expected %s, but got %s.\n", test.key, test.expected, got)
}
}
}
func TestGetInt(t *testing.T) {
data := newData()
data.Values = map[string][]string{
"age": []string{"25", "33"},
"weight": []string{"155"},
}
table := []struct {
key string
expected int
}{
{
key: "age",
expected: 25,
},
{
key: "weight",
expected: 155,
},
{
key: "height",
expected: 0,
},
}
for _, test := range table {
got := data.GetInt(test.key)
if got != test.expected {
t.Errorf("%s was incorrect. Expected %d, but got %d.\n", test.key, test.expected, got)
}
}
}
func TestGetFloat(t *testing.T) {
data := newData()
data.Values = map[string][]string{
"age": []string{"25.7", "33"},
"weight": []string{"42"},
}
table := []struct {
key string
expected float64
}{
{
key: "age",
expected: 25.7,
},
{
key: "weight",
expected: 42.0,
},
{
key: "height",
expected: 0.0,
},
}
for _, test := range table {
got := data.GetFloat(test.key)
if got != test.expected {
t.Errorf("%s was incorrect. Expected %f, but got %f.\n", test.key, test.expected, got)
}
}
}
func TestGetBool(t *testing.T) {
data := newData()
data.Values = map[string][]string{
"retired": []string{"true", "false"},
"leftHanded": []string{"0"},
"collegeGraduate": []string{"1"},
}
table := []struct {
key string
expected bool
}{
{
key: "retired",
expected: true,
},
{
key: "leftHanded",
expected: false,
},
{
key: "collegeGraduate",
expected: true,
},
{
key: "sagittarius",
expected: false,
},
}
for _, test := range table {
got := data.GetBool(test.key)
if got != test.expected {
t.Errorf("%s was incorrect. Expected %t, but got %t.\n", test.key, test.expected, got)
}
}
}
func TestBytes(t *testing.T) {
data := newData()
data.Values = map[string][]string{
"name": []string{"bob", "bill"},
"profession": []string{"plumber"},
}
table := []struct {
key string
expected []byte
}{
{
key: "name",
expected: []byte("bob"),
},
{
key: "profession",
expected: []byte("plumber"),
},
{
key: "favoriteColor",
expected: []byte(""),
},
}
for _, test := range table {
got := data.GetBytes(test.key)
if len(got) == 0 && len(test.expected) == 0 {
// do nothing
// reflect.DeepEqual doesn't like when both lengths are zero, but it should pass.
} else if !reflect.DeepEqual(got, test.expected) {
t.Errorf("%s was incorrect. Expected %v, but got %v.\n", test.key, test.expected, got)
}
}
}
func TestCreateFromMap(t *testing.T) {
m := map[string]string{
"name": "bob",
"age": "25",
"favoriteColor": "fuchsia",
}
data := CreateFromMap(m)
table := []struct {
key string
expected string
}{
{
key: "name",
expected: "bob",
},
{
key: "age",
expected: "25",
},
{
key: "dreamJob",
expected: "",
},
}
for _, test := range table {
got := data.Get(test.key)
if got != test.expected {
t.Errorf("%s was incorrect. Expected %s, but got %s.\n", test.key, test.expected, got)
}
}
}
func TestGetStringsSplit(t *testing.T) {
data := newData()
data.Values = map[string][]string{
"children": []string{"martha,bill,jane", "adam,julia"},
"favoriteColors": []string{"blue%20green%20fuchsia"},
}
table := []struct {
key string
delim string
expecteds []string
}{
{
key: "children",
delim: ",",
expecteds: []string{"martha", "bill", "jane"},
},
{
key: "favoriteColors",
delim: "%20",
expecteds: []string{"blue", "green", "fuchsia"},
},
{
key: "height",
delim: "-",
expecteds: []string{},
},
}
for _, test := range table {
gots := data.GetStringsSplit(test.key, test.delim)
if len(gots) == 0 && len(test.expecteds) == 0 {
// do nothing
// reflect.DeepEqual doesn't like when both lengths are zero, but it should pass.
} else if !reflect.DeepEqual(gots, test.expecteds) {
t.Errorf("%s was incorrect. Expected %v, but got %v.\n", test.key, test.expecteds, gots)
}
}
}
func TestParseUrlEncoded(t *testing.T) {
// Construct a urlencoded form request
// Add some simple key-value params to the form
fieldData := map[string]string{
"name": "Bob",
"age": "25",
"favoriteNumber": "99.99",
"leftHanded": "true",
}
values := url.Values{}
for fieldname, value := range fieldData {
values.Add(fieldname, value)
}
req, err := http.NewRequest("POST", "/", strings.NewReader(values.Encode()))
if err != nil {
t.Error(err)
}
req.Header.Add("Content-Type", "application/x-www-form-urlencoded")
// Parse the request
d, err := Parse(req)
if err != nil {
t.Error(err)
}
testBasicFormFields(t, d)
}
func TestParseMultipart(t *testing.T) {
// Construct a multipart request
body := bytes.NewBuffer([]byte{})
form := multipart.NewWriter(body)
// Add some simple key-value params to the form
fieldData := map[string]string{
"name": "Bob",
"age": "25",
"favoriteNumber": "99.99",
"leftHanded": "true",
}
for fieldname, value := range fieldData {
if err := form.WriteField(fieldname, value); err != nil {
panic(err)
}
}
// Add a file to the form
testFile, err := os.Open("test_file.txt")
if err != nil {
t.Error(err)
}
defer testFile.Close()
fileWriter, err := form.CreateFormFile("file", "test_file.txt")
if err != nil {
panic(err)
}
if _, err := io.Copy(fileWriter, testFile); err != nil {
panic(err)
}
// Close the form to finish writing
if err := form.Close(); err != nil {
panic(err)
}
req, err := http.NewRequest("POST", "/", body)
if err != nil {
t.Error(err)
}
req.Header.Add("Content-Type", "multipart/form-data; boundary="+form.Boundary())
// Parse the request
d, err := Parse(req)
if err != nil {
t.Error(err)
}
testBasicFormFields(t, d)
// Next test that the file was parsed correctly
if !d.FileExists("file") {
t.Error("Expected FileExists() to return true but it returned false.")
}
header := d.GetFile("file")
if header == nil {
t.Error("Exected GetFile() to return a *multipart.FileHeader but got nil.")
}
if header.Filename != "test_file.txt" {
t.Errorf(`Expected header.Filename to equal "test_file.txt" but got %s`, header.Filename)
}
file, err := header.Open()
if err != nil {
t.Error(err)
}
gotBytes, err := ioutil.ReadAll(file)
if err != nil {
t.Error(err)
}
if string(gotBytes) != "Hello!" {
t.Errorf(`Expected file contents when read directly to be "Hello!" but got %s`, string(gotBytes))
}
gotBytes, err = d.GetFileBytes("file")
if err != nil {
t.Error(err)
}
if string(gotBytes) != "Hello!" {
t.Errorf(`Expected GetFileBytes("file") to return "Hello!" but got %s`, string(gotBytes))
}
}
// Used for testing multipart and urlencoded form data, since both tests expect the same data
// to be present.
func testBasicFormFields(t *testing.T, d *Data) {
// use a table for testing
fields := []struct {
key string
got interface{}
expected interface{}
}{
{
key: "name",
got: d.Get("name"),
expected: "Bob",
},
{
key: "age",
got: d.GetInt("age"),
expected: 25,
},
{
key: "favoriteNumber",
got: d.GetFloat("favoriteNumber"),
expected: 99.99,
},
{
key: "leftHanded",
got: d.GetBool("leftHanded"),
expected: true,
},
}
for _, test := range fields {
if !reflect.DeepEqual(test.got, test.expected) {
t.Errorf("%s was incorrect. Expected %v, but got %v.\n", test.key, test.expected, test.got)
}
}
}
type jsonData struct {
Name string `json:"name"`
Age int `json:"age"`
Cool bool `json:"cool"`
Aptitude string `json:"aptitude"`
Location map[string]float64 `json:"location"`
Things []string `json:"things"`
}
func TestParseJSON(t *testing.T) {
// Construct and parse a json request
input := `{
"name": "bob",
"age": 25,
"cool": true,
"aptitude": null,
"location": {"latitude": 123.456, "longitude": 948.123},
"things": ["a", "b", "c"]
}`
body := bytes.NewBuffer([]byte(input))
req, err := http.NewRequest("POST", "/", body)
if err != nil {
t.Error(err)
}
req.Header.Set("Content-Type", "application/json")
d, err := Parse(req)
if err != nil {
t.Error(err)
}
// use a table for testing
table := []struct {
key string
got interface{}
expected interface{}
}{
{
key: "name",
got: d.Get("name"),
expected: "bob",
},
{
key: "age",
got: d.GetFloat("age"),
expected: 25.0,
},
{
key: "cool",
got: d.GetBool("cool"),
expected: true,
},
{
key: "aptitude",
got: d.Get("aptitude"),
expected: "",
},
}
for _, test := range table {
if !reflect.DeepEqual(test.got, test.expected) {
t.Errorf("%s was incorrect. Expected %v, but got %v.\n", test.key, test.expected, test.got)
}
}
// Test unmarshaling the entire body to a data structure.
expected := jsonData{
Name: "bob",
Age: 25,
Cool: true,
Aptitude: "",
Location: map[string]float64{"latitude": 123.456, "longitude": 948.123},
Things: []string{"a", "b", "c"},
}
var got jsonData
if err := d.BindJSON(&got); err != nil {
t.Error(err)
} else if !reflect.DeepEqual(got, expected) {
t.Errorf("Result of BindJSON was incorrect. Expected %+v, but got %+v.\n", expected, got)
}
// Test unmarshaling into data structures separately
// For maps, both the GetMapFromJSON method and the GetAndUnmarshalJSON method
expectedMap := map[string]interface{}{"latitude": 123.456, "longitude": 948.123}
if got, err := d.GetMapFromJSON("location"); err != nil {
t.Error(err)
} else if !reflect.DeepEqual(got, expectedMap) {
t.Errorf("location was incorrect. Expected %v, but got %v.\n", expectedMap, got)
}
gotMap := map[string]interface{}{}
if err := d.GetAndUnmarshalJSON("location", &gotMap); err != nil {
t.Error(err)
} else if !reflect.DeepEqual(gotMap, expectedMap) {
t.Errorf("location was incorrect. Expected %v, but got %v.\n", expectedMap, gotMap)
}
// For slices, both the GetSliceFromJSON method and the GetAndUnmarshalJSON method
expectedSlice := []interface{}{"a", "b", "c"}
if got, err := d.GetSliceFromJSON("things"); err != nil {
t.Error(err)
} else if !reflect.DeepEqual(got, expectedSlice) {
t.Errorf("things was incorrect. Expected %v, but got %v.\n", expectedSlice, got)
}
gotSlice := []interface{}{}
if err := d.GetAndUnmarshalJSON("things", &gotSlice); err != nil {
t.Error(err)
} else if !reflect.DeepEqual(gotSlice, expectedSlice) {
t.Errorf("things was incorrect. Expected %v, but got %v.\n", expectedSlice, gotSlice)
}
}
func ExampleParse() {
// Construct a request object for example purposes only.
// Typically you would be using this inside a http.HandlerFunc,
// not constructing your own request.
req, _ := http.NewRequest("GET", "/", nil)
values := url.Values{}
values.Add("name", "Bob")
values.Add("age", "25")
values.Add("retired", "false")
req.PostForm = values
req.Header.Set("Content-Type", "form-urlencoded")
// Parse the form data.
data, err := Parse(req)
if err != nil {
panic(err)
}
name := data.Get("name")
age := data.GetInt("age")
retired := data.GetBool("retired")
if retired {
fmt.Printf("%s is %d years old and he has retired.", name, age)
} else {
fmt.Printf("%s is %d years old and not yet retired.", name, age)
}
// Output:
// Bob is 25 years old and not yet retired.
}