forked from dimfeld/httptreemux
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathcontext_test.go
468 lines (397 loc) · 12.4 KB
/
context_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
// +build go1.7
package httptreemux
import (
"context"
"fmt"
"net/http"
"net/http/httptest"
"reflect"
"testing"
)
type IContextGroup interface {
GET(path string, handler http.HandlerFunc)
POST(path string, handler http.HandlerFunc)
PUT(path string, handler http.HandlerFunc)
PATCH(path string, handler http.HandlerFunc)
DELETE(path string, handler http.HandlerFunc)
HEAD(path string, handler http.HandlerFunc)
OPTIONS(path string, handler http.HandlerFunc)
NewContextGroup(path string) *ContextGroup
NewGroup(path string) *ContextGroup
}
func TestContextParams(t *testing.T) {
m := &contextData{
params: map[string]string{"id": "123"},
route: "",
}
ctx := context.WithValue(context.Background(), contextDataKey, m)
params := ContextParams(ctx)
if params == nil {
t.Errorf("expected '%#v', but got '%#v'", m, params)
}
if v := params["id"]; v != "123" {
t.Errorf("expected '%s', but got '%#v'", m.params["id"], params["id"])
}
}
func TestContextRoute(t *testing.T) {
tests := []struct {
name,
expectedRoute string
}{
{
name: "basic",
expectedRoute: "/base/path",
},
{
name: "params",
expectedRoute: "/base/path/:id/items/:itemid",
},
{
name: "catch-all",
expectedRoute: "/base/*path",
},
{
name: "empty",
expectedRoute: "",
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
cd := &contextData{}
if len(test.expectedRoute) > 0 {
cd.route = test.expectedRoute
}
ctx := context.WithValue(context.Background(), contextDataKey, cd)
gotRoute := ContextRoute(ctx)
if test.expectedRoute != gotRoute {
t.Errorf("ContextRoute didn't return the desired route\nexpected %s\ngot: %s", test.expectedRoute, gotRoute)
}
})
}
}
func TestContextData(t *testing.T) {
p := &contextData{
route: "route/path",
params: map[string]string{"id": "123"},
}
ctx := context.WithValue(context.Background(), contextDataKey, p)
ctxData := ContextData(ctx)
pathValue := ctxData.Route()
if pathValue != p.route {
t.Errorf("expected '%s', but got '%s'", p, pathValue)
}
params := ctxData.Params()
if v := params["id"]; v != "123" {
t.Errorf("expected '%s', but got '%#v'", p.params["id"], params["id"])
}
}
func TestContextDataWithEmptyParams(t *testing.T) {
p := &contextData{
route: "route/path",
params: nil,
}
ctx := context.WithValue(context.Background(), contextDataKey, p)
params := ContextData(ctx).Params()
if params == nil {
t.Errorf("ContextData.Params should never return nil")
}
}
func TestContextGroupMethods(t *testing.T) {
for _, scenario := range scenarios {
t.Run(scenario.description, func(t *testing.T) {
testContextGroupMethods(t, scenario.RequestCreator, true, false)
testContextGroupMethods(t, scenario.RequestCreator, false, false)
testContextGroupMethods(t, scenario.RequestCreator, true, true)
testContextGroupMethods(t, scenario.RequestCreator, false, true)
})
}
}
func testContextGroupMethods(t *testing.T, reqGen RequestCreator, headCanUseGet bool, useContextRouter bool) {
t.Run(fmt.Sprintf("headCanUseGet %v, useContextRouter %v", headCanUseGet, useContextRouter), func(t *testing.T) {
var result string
makeHandler := func(method, expectedRoutePath string, hasParam bool) http.HandlerFunc {
return func(w http.ResponseWriter, r *http.Request) {
result = method
// Test Legacy Accessor
var v string
v, ok := ContextParams(r.Context())["param"]
if hasParam && !ok {
t.Error("missing key 'param' in context from ContextParams")
}
ctxData := ContextData(r.Context())
if ctxData == nil {
t.Fatal("context did not contain ContextData")
}
v, ok = ctxData.Params()["param"]
if hasParam && !ok {
t.Error("missing key 'param' in context from ContextData")
}
routePath := ctxData.Route()
if routePath != expectedRoutePath {
t.Errorf("Expected context to have route path '%s', saw %s", expectedRoutePath, routePath)
}
if headCanUseGet && (method == "GET" || v == "HEAD") {
return
}
if hasParam && v != method {
t.Errorf("invalid key 'param' in context; expected '%s' but got '%s'", method, v)
}
}
}
var router http.Handler
var rootGroup IContextGroup
if useContextRouter {
root := NewContextMux()
root.HeadCanUseGet = headCanUseGet
t.Log(root.TreeMux.HeadCanUseGet)
router = root
rootGroup = root
} else {
root := New()
root.HeadCanUseGet = headCanUseGet
router = root
rootGroup = root.UsingContext()
}
cg := rootGroup.NewGroup("/base").NewGroup("/user")
cg.GET("/:param", makeHandler("GET", cg.group.path+"/:param", true))
cg.POST("/:param", makeHandler("POST", cg.group.path+"/:param", true))
cg.PATCH("/PATCH", makeHandler("PATCH", cg.group.path+"/PATCH", false))
cg.PUT("/:param", makeHandler("PUT", cg.group.path+"/:param", true))
cg.Handler("DELETE", "/:param", http.HandlerFunc(makeHandler("DELETE", cg.group.path+"/:param", true)))
testMethod := func(method, expect string) {
result = ""
w := httptest.NewRecorder()
r, _ := reqGen(method, "/base/user/"+method, nil)
router.ServeHTTP(w, r)
if expect == "" && w.Code != http.StatusMethodNotAllowed {
t.Errorf("Method %s not expected to match but saw code %d", method, w.Code)
}
if result != expect {
t.Errorf("Method %s got result %s", method, result)
}
}
testMethod("GET", "GET")
testMethod("POST", "POST")
testMethod("PATCH", "PATCH")
testMethod("PUT", "PUT")
testMethod("DELETE", "DELETE")
if headCanUseGet {
t.Log("Test implicit HEAD with HeadCanUseGet = true")
testMethod("HEAD", "GET")
} else {
t.Log("Test implicit HEAD with HeadCanUseGet = false")
testMethod("HEAD", "")
}
cg.HEAD("/:param", makeHandler("HEAD", cg.group.path+"/:param", true))
testMethod("HEAD", "HEAD")
})
}
func TestNewContextGroup(t *testing.T) {
router := New()
group := router.NewGroup("/api")
group.GET("/v1", func(w http.ResponseWriter, r *http.Request, params map[string]string) {
w.Write([]byte(`200 OK GET /api/v1`))
})
group.UsingContext().GET("/v2", func(w http.ResponseWriter, r *http.Request) {
w.Write([]byte(`200 OK GET /api/v2`))
})
tests := []struct {
uri, expected string
}{
{"/api/v1", "200 OK GET /api/v1"},
{"/api/v2", "200 OK GET /api/v2"},
}
for _, tc := range tests {
r, err := http.NewRequest("GET", tc.uri, nil)
if err != nil {
t.Fatal(err)
}
w := httptest.NewRecorder()
router.ServeHTTP(w, r)
if w.Code != http.StatusOK {
t.Errorf("GET %s: expected %d, but got %d", tc.uri, http.StatusOK, w.Code)
}
if got := w.Body.String(); got != tc.expected {
t.Errorf("GET %s : expected %q, but got %q", tc.uri, tc.expected, got)
}
}
}
type ContextGroupHandler struct{}
// adhere to the http.Handler interface
func (f ContextGroupHandler) ServeHTTP(w http.ResponseWriter, r *http.Request) {
switch r.Method {
case "GET":
w.Write([]byte(`200 OK GET /api/v1`))
default:
http.Error(w, "Method Not Allowed", http.StatusMethodNotAllowed)
return
}
}
func TestNewContextGroupHandler(t *testing.T) {
router := New()
group := router.NewGroup("/api")
group.UsingContext().Handler("GET", "/v1", ContextGroupHandler{})
tests := []struct {
uri, expected string
}{
{"/api/v1", "200 OK GET /api/v1"},
}
for _, tc := range tests {
r, err := http.NewRequest("GET", tc.uri, nil)
if err != nil {
t.Fatal(err)
}
w := httptest.NewRecorder()
router.ServeHTTP(w, r)
if w.Code != http.StatusOK {
t.Errorf("GET %s: expected %d, but got %d", tc.uri, http.StatusOK, w.Code)
}
if got := w.Body.String(); got != tc.expected {
t.Errorf("GET %s : expected %q, but got %q", tc.uri, tc.expected, got)
}
}
}
func TestDefaultContext(t *testing.T) {
router := New()
ctx := context.WithValue(context.Background(), "abc", "def")
expectContext := false
router.GET("/abc", func(w http.ResponseWriter, r *http.Request, params map[string]string) {
contextValue := r.Context().Value("abc")
if expectContext {
x, ok := contextValue.(string)
if !ok || x != "def" {
t.Errorf("Unexpected context key value: %+v", contextValue)
}
} else {
if contextValue != nil {
t.Errorf("Expected blank context but key had value %+v", contextValue)
}
}
})
r, err := http.NewRequest("GET", "/abc", nil)
if err != nil {
t.Fatal(err)
}
w := httptest.NewRecorder()
t.Log("Testing without DefaultContext")
router.ServeHTTP(w, r)
router.DefaultContext = ctx
expectContext = true
w = httptest.NewRecorder()
t.Log("Testing with DefaultContext")
router.ServeHTTP(w, r)
}
func TestContextMuxSimple(t *testing.T) {
router := NewContextMux()
ctx := context.WithValue(context.Background(), "abc", "def")
expectContext := false
router.GET("/abc", func(w http.ResponseWriter, r *http.Request) {
contextValue := r.Context().Value("abc")
if expectContext {
x, ok := contextValue.(string)
if !ok || x != "def" {
t.Errorf("Unexpected context key value: %+v", contextValue)
}
} else {
if contextValue != nil {
t.Errorf("Expected blank context but key had value %+v", contextValue)
}
}
})
r, err := http.NewRequest("GET", "/abc", nil)
if err != nil {
t.Fatal(err)
}
w := httptest.NewRecorder()
t.Log("Testing without DefaultContext")
router.ServeHTTP(w, r)
router.DefaultContext = ctx
expectContext = true
w = httptest.NewRecorder()
t.Log("Testing with DefaultContext")
router.ServeHTTP(w, r)
}
func TestAddDataToContext(t *testing.T) {
expectedRoute := "/expected/route"
expectedParams := map[string]string{
"test": "expected",
}
ctx := AddRouteDataToContext(context.Background(), &contextData{
route: expectedRoute,
params: expectedParams,
})
if gotData, ok := ctx.Value(contextDataKey).(*contextData); ok && gotData != nil {
if gotData.route != expectedRoute {
t.Errorf("Did not retrieve the desired route. Expected: %s; Got: %s", expectedRoute, gotData.route)
}
if !reflect.DeepEqual(expectedParams, gotData.params) {
t.Errorf("Did not retrieve the desired parameters. Expected: %#v; Got: %#v", expectedParams, gotData.params)
}
} else {
t.Error("failed to retrieve context data")
}
}
func TestAddParamsToContext(t *testing.T) {
expectedParams := map[string]string{
"test": "expected",
}
ctx := AddParamsToContext(context.Background(), expectedParams)
if gotData, ok := ctx.Value(contextDataKey).(*contextData); ok && gotData != nil {
if !reflect.DeepEqual(expectedParams, gotData.params) {
t.Errorf("Did not retrieve the desired parameters. Expected: %#v; Got: %#v", expectedParams, gotData.params)
}
} else {
t.Error("failed to retrieve context data")
}
}
func TestAddRouteToContext(t *testing.T) {
expectedRoute := "/expected/route"
ctx := AddRouteToContext(context.Background(), expectedRoute)
if gotData, ok := ctx.Value(contextDataKey).(*contextData); ok && gotData != nil {
if gotData.route != expectedRoute {
t.Errorf("Did not retrieve the desired route. Expected: %s; Got: %s", expectedRoute, gotData.route)
}
} else {
t.Error("failed to retrieve context data")
}
}
func TestContextDataWithMiddleware(t *testing.T) {
wantRoute := "/foo/:id/bar"
wantParams := map[string]string{
"id": "15",
}
validateRequestAndParams := func(request *http.Request, params map[string]string, location string) {
data := ContextData(request.Context())
if data == nil {
t.Fatalf("ContextData returned nil in %s", location)
}
if data.Route() != wantRoute {
t.Errorf("Unexpected route in %s. Got %s", location, data.Route())
}
if !reflect.DeepEqual(data.Params(), wantParams) {
t.Errorf("Unexpected context params in %s. Got %+v", location, data.Params())
}
if !reflect.DeepEqual(params, wantParams) {
t.Errorf("Unexpected handler params in %s. Got %+v", location, params)
}
}
router := NewContextMux()
router.Use(func(next HandlerFunc) HandlerFunc {
return func(writer http.ResponseWriter, request *http.Request, m map[string]string) {
t.Log("Testing Middleware")
validateRequestAndParams(request, m, "middleware")
next(writer, request, m)
}
})
router.GET(wantRoute, func(writer http.ResponseWriter, request *http.Request) {
t.Log("Testing handler")
validateRequestAndParams(request, ContextParams(request.Context()), "handler")
writer.WriteHeader(http.StatusOK)
})
w := httptest.NewRecorder()
r, _ := http.NewRequest(http.MethodGet, "/foo/15/bar", nil)
router.ServeHTTP(w, r)
if w.Code != http.StatusOK {
t.Fatalf("unexpected status code. got %d", w.Code)
}
}