-
-
Notifications
You must be signed in to change notification settings - Fork 45
/
ctx_test.go
564 lines (459 loc) · 14.9 KB
/
ctx_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
package fuego
import (
"bytes"
"context"
"encoding/xml"
"errors"
"net/http/httptest"
"strings"
"testing"
"github.com/stretchr/testify/require"
)
func TestContext_PathParam(t *testing.T) {
t.Run("can read one path param", func(t *testing.T) {
s := NewServer()
Get(s, "/foo/{id}", func(c ContextNoBody) (ans, error) {
return ans{Ans: c.PathParam("id")}, nil
})
r := httptest.NewRequest("GET", "/foo/123", nil)
w := httptest.NewRecorder()
s.Mux.ServeHTTP(w, r)
require.Equal(t, crlf(`{"ans":"123"}`), w.Body.String())
})
t.Run("path param invalid", func(t *testing.T) {
s := NewServer()
Get(s, "/foo/", func(c ContextNoBody) (ans, error) {
return ans{Ans: c.PathParam("id")}, nil
})
r := httptest.NewRequest("GET", "/foo/", nil)
w := httptest.NewRecorder()
s.Mux.ServeHTTP(w, r)
require.Equal(t, crlf(`{"ans":""}`), w.Body.String())
})
}
func TestContext_QueryParam(t *testing.T) {
r := httptest.NewRequest("GET", "http://example.com/foo/123?id=456&other=hello&boo=true&name=jhon&name=doe", nil)
w := httptest.NewRecorder()
c := NewContext[any](w, r, readOptions{})
t.Run("string", func(t *testing.T) {
param := c.QueryParam("other")
require.NotEmpty(t, param)
require.Equal(t, "hello", param)
param = c.QueryParam("notfound")
require.Empty(t, param)
})
t.Run("int", func(t *testing.T) {
param := c.QueryParam("id")
require.NotEmpty(t, param)
require.Equal(t, "456", param)
paramInt := c.QueryParamInt("id")
require.Equal(t, 456, paramInt)
paramInt = c.QueryParamInt("notfound")
require.Equal(t, 0, paramInt)
paramInt = c.QueryParamInt("other")
require.Equal(t, 0, paramInt)
paramInt, err := c.QueryParamIntErr("id")
require.NoError(t, err)
require.Equal(t, 456, paramInt)
paramInt, err = c.QueryParamIntErr("notfound")
require.Error(t, err)
require.Equal(t, "param notfound not found", err.Error())
require.Equal(t, 0, paramInt)
paramInt, err = c.QueryParamIntErr("other")
require.Error(t, err)
require.Contains(t, err.Error(), "param other=hello is not of type int")
require.Equal(t, 0, paramInt)
})
t.Run("bool", func(t *testing.T) {
param := c.QueryParam("boo")
require.NotEmpty(t, param)
require.Equal(t, "true", param)
paramBool := c.QueryParamBool("boo")
require.Equal(t, true, paramBool)
paramBool = c.QueryParamBool("notfound")
require.Equal(t, false, paramBool)
paramBool, err := c.QueryParamBoolErr("boo")
require.NoError(t, err)
require.Equal(t, true, paramBool)
paramBool, err = c.QueryParamBoolErr("notfound")
require.Error(t, err)
require.Equal(t, false, paramBool)
paramBool, err = c.QueryParamBoolErr("other")
require.Error(t, err)
require.Equal(t, false, paramBool)
})
t.Run("slice", func(t *testing.T) {
name := c.QueryParamArr("name")
require.NotEmpty(t, name)
require.Equal(t, []string{"jhon", "doe"}, name)
notFound := c.QueryParamArr("notfound")
require.Empty(t, notFound)
})
}
func TestContext_QueryParams(t *testing.T) {
r := httptest.NewRequest("GET", "http://example.com/foo/123?id=456&other=hello", nil)
w := httptest.NewRecorder()
c := NewContext[any](w, r, readOptions{})
params := c.QueryParams()
require.NotEmpty(t, params)
require.Equal(t, params["id"], []string{"456"})
require.Equal(t, params["other"], []string{"hello"})
require.Empty(t, params["notfound"])
}
type testStruct struct {
XMLName xml.Name `xml:"TestStruct"`
Name string `json:"name" xml:"Name" yaml:"name"`
Age int `json:"age" xml:"Age" yaml:"age"`
}
type testStructInTransformer struct {
Name string `json:"name" validate:"required,min=3,max=20"`
Age int `json:"age" validate:"min=18"`
}
func (b *testStructInTransformer) InTransform(context.Context) error {
b.Name = "transformed " + b.Name
b.Age *= 2
return nil
}
type testStructInTransformerWithError struct {
Name string `json:"name" validate:"required,min=3,max=10"`
Age int `json:"age" validate:"min=18"`
}
func (b *testStructInTransformerWithError) InTransform(context.Context) error {
return errors.New("error")
}
func TestContext_Body(t *testing.T) {
t.Run("can read JSON body", func(t *testing.T) {
// Create new Reader
a := strings.NewReader(`{"name":"John","age":30}`)
// Test an http request
w := httptest.NewRecorder()
r := httptest.NewRequest("GET", "http://example.com/foo", a)
c := NewContext[testStruct](w, r, readOptions{})
body, err := c.Body()
require.NoError(t, err)
require.Equal(t, "John", body.Name)
require.Equal(t, 30, body.Age)
})
t.Run("can read JSON body with Content-Type application/json", func(t *testing.T) {
// Create new Reader
a := strings.NewReader(`{"name":"John","age":30}`)
// Test an http request
w := httptest.NewRecorder()
r := httptest.NewRequest("GET", "http://example.com/foo", a)
r.Header.Add("Content-Type", "application/json")
c := NewContext[testStruct](w, r, readOptions{})
body, err := c.Body()
require.NoError(t, err)
require.Equal(t, "John", body.Name)
require.Equal(t, 30, body.Age)
})
t.Run("can read JSON body twice", func(t *testing.T) {
a := strings.NewReader(`{"name":"John","age":30}`)
w := httptest.NewRecorder()
r := httptest.NewRequest("GET", "http://example.com/foo", a)
c := NewContext[testStruct](w, r, readOptions{})
body, err := c.Body()
require.NoError(t, err)
require.Equal(t, "John", body.Name)
require.Equal(t, 30, body.Age)
body, err = c.Body()
require.NoError(t, err)
require.Equal(t, "John", body.Name)
require.Equal(t, 30, body.Age)
})
t.Run("can read and validate valid JSON body", func(t *testing.T) {
type testStruct struct {
Name string `json:"name" validate:"required,min=3,max=10"`
Age int `json:"age" validate:"min=18"`
}
reqBody := strings.NewReader(`{"name":"John","age":30}`)
c := NewContext[testStruct](
httptest.NewRecorder(),
httptest.NewRequest("GET", "http://example.com/foo", reqBody),
readOptions{})
body, err := c.Body()
require.NoError(t, err)
require.Equal(t, "John", body.Name)
require.Equal(t, 30, body.Age)
})
t.Run("can read and validate invalid JSON body", func(t *testing.T) {
type testStruct struct {
Name string `json:"name" validate:"required,min=3,max=10"`
Age int `json:"age" validate:"min=18"`
}
reqBody := strings.NewReader(`{"name":"VeryLongName","age":12}`)
c := NewContext[testStruct](
httptest.NewRecorder(),
httptest.NewRequest("GET", "http://example.com/foo", reqBody),
readOptions{})
body, err := c.Body()
require.Error(t, err)
require.Equal(t, "VeryLongName", body.Name)
require.Equal(t, 12, body.Age)
})
t.Run("can transform JSON body with custom method", func(t *testing.T) {
reqBody := strings.NewReader(`{"name":"John","age":30}`)
c := NewContext[testStructInTransformer](
httptest.NewRecorder(),
httptest.NewRequest("GET", "http://example.com/foo", reqBody),
readOptions{})
body, err := c.Body()
require.NoError(t, err)
require.Equal(t, "transformed John", body.Name)
require.Equal(t, 60, body.Age)
})
t.Run("can transform JSON body with custom method returning error", func(t *testing.T) {
reqBody := strings.NewReader(`{"name":"John","age":30}`)
c := NewContext[testStructInTransformerWithError](
httptest.NewRecorder(),
httptest.NewRequest("GET", "http://example.com/foo", reqBody),
readOptions{})
body, err := c.Body()
require.Error(t, err)
require.Equal(t, "John", body.Name)
require.Equal(t, 30, body.Age)
})
t.Run("can read bytes", func(t *testing.T) {
// Create new Reader with pure bytes from an image
a := bytes.NewReader([]byte(`image`))
// Test an http request
w := httptest.NewRecorder()
r := httptest.NewRequest("GET", "http://example.com/foo", a)
r.Header.Add("Content-Type", "application/octet-stream")
c := NewContext[[]byte](w, r, readOptions{})
body, err := c.Body()
require.NoError(t, err)
require.Equal(t, []byte(`image`), body)
})
t.Run("cannot read bytes if expected type is different than bytes", func(t *testing.T) {
// Create new Reader with pure bytes from an image
a := bytes.NewReader([]byte(`image`))
// Test an http request
w := httptest.NewRecorder()
r := httptest.NewRequest("GET", "http://example.com/foo", a)
r.Header.Add("Content-Type", "application/octet-stream")
c := NewContext[*struct{}](w, r, readOptions{})
body, err := c.Body()
require.Error(t, err)
require.ErrorContains(t, err, "use []byte as the body type")
require.Equal(t, (*struct{})(nil), body)
})
t.Run("can read XML body", func(t *testing.T) {
a := bytes.NewReader([]byte(`
<TestStruct>
<Name>John</Name>
<Age>30</Age>
</TestStruct>
`))
// Test an http request
w := httptest.NewRecorder()
r := httptest.NewRequest("GET", "http://example.com/foo", a)
r.Header.Add("Content-Type", "application/xml")
c := NewContext[testStruct](w, r, readOptions{})
body, err := c.Body()
require.NoError(t, err)
require.Equal(t, "John", body.Name)
require.Equal(t, 30, body.Age)
})
t.Run("can read YAML body", func(t *testing.T) {
a := bytes.NewReader([]byte(`
name: John
age: 30
`))
// Test an http request
w := httptest.NewRecorder()
r := httptest.NewRequest("GET", "http://example.com/foo", a)
r.Header.Add("Content-Type", "application/x-yaml")
c := NewContext[testStruct](w, r, readOptions{})
body, err := c.Body()
require.NoError(t, err)
require.Equal(t, "John", body.Name)
require.Equal(t, 30, body.Age)
})
t.Run("unparsable because restricted to 1 byte", func(t *testing.T) {
reqBody := strings.NewReader(`{"name":"John","age":30}`)
c := NewContext[testStructInTransformerWithError](
httptest.NewRecorder(),
httptest.NewRequest("GET", "http://example.com/foo", reqBody),
readOptions{
MaxBodySize: 1,
})
body, err := c.Body()
require.Error(t, err)
require.Equal(t, "", body.Name)
require.Equal(t, 0, body.Age)
})
t.Run("can read string body", func(t *testing.T) {
// Create new Reader
a := strings.NewReader("Hello World")
// Test an http request
w := httptest.NewRecorder()
r := httptest.NewRequest("GET", "http://example.com/foo", a)
r.Header.Set("Content-Type", "text/plain")
c := NewContext[string](w, r, readOptions{})
_, err := c.Body()
require.NoError(t, err)
})
}
func FuzzContext_Body(f *testing.F) {
f.Add("Hello Fuzz")
f.Fuzz(func(t *testing.T, s string) {
// Create new Reader
a := strings.NewReader(s)
// Test an http request
w := httptest.NewRecorder()
r := httptest.NewRequest("GET", "http://example.com/foo", a)
r.Header.Set("Content-Type", "application/x-www-form-urlencoded")
c := NewContext[testStruct](w, r, readOptions{})
_, err := c.Body()
require.NoError(t, err)
})
}
func BenchmarkContext_Body(b *testing.B) {
b.Run("valid JSON body", func(b *testing.B) {
for i := range b.N {
reqBody := strings.NewReader(`{"name":"John","age":30}`)
c := NewContext[testStruct](
httptest.NewRecorder(),
httptest.NewRequest("GET", "http://example.com/foo", reqBody),
readOptions{})
_, err := c.Body()
if err != nil {
b.Fatal(err, "iteration", i)
}
}
})
// This test does make really sense because the body will not be accessed millions of times.
// It however does show that caching the body works.
// See [Body] for more information.
b.Run("valid JSON body cache", func(b *testing.B) {
reqBody := strings.NewReader(`{"name":"John","age":30}`)
c := NewContext[testStruct](
httptest.NewRecorder(),
httptest.NewRequest("GET", "http://example.com/foo", reqBody),
readOptions{})
for i := range b.N {
_, err := c.Body()
if err != nil {
b.Fatal(err, "iteration", i)
}
}
})
b.Run("invalid JSON body", func(b *testing.B) {
for range b.N {
reqBody := strings.NewReader(`{"name":"John","age":30}`)
c := NewContext[testStruct](
httptest.NewRecorder(),
httptest.NewRequest("GET", "http://example.com/foo", reqBody),
readOptions{})
_, err := c.Body()
if err != nil {
b.Fatal(err)
}
}
})
b.Run("string body", func(b *testing.B) {
for range b.N {
reqBody := strings.NewReader(`{"name":"John","age":30}`)
c := NewContext[testStruct](
httptest.NewRecorder(),
httptest.NewRequest("GET", "http://example.com/foo", reqBody),
readOptions{})
_, err := c.Body()
if err != nil {
b.Fatal(err)
}
}
})
}
func TestContext_MustBody(t *testing.T) {
t.Run("can read JSON body", func(t *testing.T) {
// Create new Reader
a := strings.NewReader(`{"name":"John","age":30}`)
// Test an http request
w := httptest.NewRecorder()
r := httptest.NewRequest("GET", "http://example.com/foo", a)
c := NewContext[testStruct](w, r, readOptions{})
body := c.MustBody()
require.Equal(t, "John", body.Name)
require.Equal(t, 30, body.Age)
})
t.Run("cannot read invalid JSON body", func(t *testing.T) {
type testStruct struct {
Name string `json:"name" validate:"required,min=3,max=10"`
Age int `json:"age" validate:"min=18"`
}
reqBody := strings.NewReader(`{"name":"VeryLongName","age":12}`)
c := NewContext[testStruct](
httptest.NewRecorder(),
httptest.NewRequest("GET", "http://example.com/foo", reqBody),
readOptions{})
require.Panics(t, func() {
c.MustBody()
})
})
}
func TestMainLang(t *testing.T) {
r := httptest.NewRequest("GET", "/", nil)
r.Header.Set("Accept-Language", "fr-CH, fr;q=0.9, en;q=0.8, de;q=0.7, *;q=0.5")
c := NewContext[any](httptest.NewRecorder(), r, readOptions{})
require.Equal(t, c.MainLang(), "fr")
require.Equal(t, c.MainLocale(), "fr-CH")
}
func TestContextNoBody_Body(t *testing.T) {
body := `{"name":"John","age":30}`
r := httptest.NewRequest("GET", "/", strings.NewReader(body))
ctx := ContextNoBody{
Req: r,
Res: httptest.NewRecorder(),
}
res, err := ctx.Body()
require.NoError(t, err)
require.Equal(t, any(map[string]any{
"name": "John",
"age": 30.0, // JSON numbers are float64
}), res)
}
func TestContextNoBody_MustBody(t *testing.T) {
t.Run("can read JSON body", func(t *testing.T) {
body := `{"name":"John","age":30}`
r := httptest.NewRequest("GET", "/", strings.NewReader(body))
ctx := ContextNoBody{
Req: r,
Res: httptest.NewRecorder(),
}
res := ctx.MustBody()
require.Equal(t, any(map[string]any{
"name": "John",
"age": 30.0, // JSON numbers are float64
}), res)
})
t.Run("cannot read invalid JSON body", func(t *testing.T) {
body := `{"name":"John","age":30`
r := httptest.NewRequest("GET", "/", strings.NewReader(body))
ctx := ContextNoBody{
Req: r,
Res: httptest.NewRecorder(),
}
require.Panics(t, func() {
ctx.MustBody()
})
})
}
func TestContextNoBody_Redirect(t *testing.T) {
s := NewServer()
Get(s, "/", func(c ContextNoBody) (any, error) {
return c.Redirect(301, "/foo")
})
Get(s, "/foo", func(c ContextNoBody) (ans, error) {
return ans{Ans: "foo"}, nil
})
t.Run("can redirect", func(t *testing.T) {
r := httptest.NewRequest("GET", "/", nil)
w := httptest.NewRecorder()
s.Mux.ServeHTTP(w, r)
require.Equal(t, 301, w.Code)
require.Equal(t, "/foo", w.Header().Get("Location"))
require.Equal(t, "<a href=\"/foo\">Moved Permanently</a>.\n\n", w.Body.String())
})
}