forked from revel/revel
-
Notifications
You must be signed in to change notification settings - Fork 2
/
router_test.go
482 lines (431 loc) · 11.7 KB
/
router_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
// Copyright (c) 2012-2016 The Revel Framework Authors, All rights reserved.
// Revel Framework source code and usage is governed by a MIT style
// license that can be found in the LICENSE file.
package revel
import (
"fmt"
"net/http"
"net/url"
"strings"
"testing"
)
// Data-driven tests that check that a given routes-file line translates into
// the expected Route object.
var routeTestCases = map[string]*Route{
"get / Application.Index": {
Method: "GET",
Path: "/",
Action: "Application.Index",
FixedParams: []string{},
},
"post /app/:id Application.SaveApp": {
Method: "POST",
Path: "/app/:id",
Action: "Application.SaveApp",
FixedParams: []string{},
},
"get /app/ Application.List": {
Method: "GET",
Path: "/app/",
Action: "Application.List",
FixedParams: []string{},
},
`get /app/:appId/ Application.Show`: {
Method: "GET",
Path: `/app/:appId/`,
Action: "Application.Show",
FixedParams: []string{},
},
`get /app-wild/*appId/ Application.WildShow`: {
Method: "GET",
Path: `/app-wild/*appId/`,
Action: "Application.WildShow",
FixedParams: []string{},
},
`GET /public/:filepath Static.Serve("public")`: {
Method: "GET",
Path: "/public/:filepath",
Action: "Static.Serve",
FixedParams: []string{
"public",
},
},
`GET /javascript/:filepath Static.Serve("public/js")`: {
Method: "GET",
Path: "/javascript/:filepath",
Action: "Static.Serve",
FixedParams: []string{
"public",
},
},
"* /apps/:id/:action Application.:action": {
Method: "*",
Path: "/apps/:id/:action",
Action: "Application.:action",
FixedParams: []string{},
},
"* /:controller/:action :controller.:action": {
Method: "*",
Path: "/:controller/:action",
Action: ":controller.:action",
FixedParams: []string{},
},
`GET / Application.Index("Test", "Test2")`: {
Method: "GET",
Path: "/",
Action: "Application.Index",
FixedParams: []string{
"Test",
"Test2",
},
},
}
// Run the test cases above.
func TestComputeRoute(t *testing.T) {
for routeLine, expected := range routeTestCases {
method, path, action, fixedArgs, found := parseRouteLine(routeLine)
if !found {
t.Error("Failed to parse route line:", routeLine)
continue
}
actual := NewRoute(appModule, method, path, action, fixedArgs, "", 0)
eq(t, "Method", actual.Method, expected.Method)
eq(t, "Path", actual.Path, expected.Path)
eq(t, "Action", actual.Action, expected.Action)
if t.Failed() {
t.Fatal("Failed on route:", routeLine)
}
}
}
// Router Tests
const TestRoutes = `
# This is a comment
GET / Application.Index
GET /test/ Application.Index("Test", "Test2")
GET /app/:id/ Application.Show
GET /app-wild/*id/ Application.WildShow
POST /app/:id Application.Save
PATCH /app/:id/ Application.Update
GET /javascript/:filepath App\Static.Serve("public/js")
GET /public/*filepath Static.Serve("public")
* /:controller/:action :controller.:action
GET /favicon.ico 404
`
var routeMatchTestCases = map[*http.Request]*RouteMatch{
&http.Request{
Method: "GET",
URL: &url.URL{Path: "/"},
}: {
ControllerName: "application",
MethodName: "Index",
FixedParams: []string{},
Params: map[string][]string{},
},
&http.Request{
Method: "GET",
URL: &url.URL{Path: "/test/"},
}: {
ControllerName: "application",
MethodName: "Index",
FixedParams: []string{"Test", "Test2"},
Params: map[string][]string{},
},
&http.Request{
Method: "GET",
URL: &url.URL{Path: "/app/123"},
}: {
ControllerName: "application",
MethodName: "Show",
FixedParams: []string{},
Params: map[string][]string{"id": {"123"}},
},
&http.Request{
Method: "PATCH",
URL: &url.URL{Path: "/app/123"},
}: {
ControllerName: "application",
MethodName: "Update",
FixedParams: []string{},
Params: map[string][]string{"id": {"123"}},
},
&http.Request{
Method: "POST",
URL: &url.URL{Path: "/app/123"},
}: {
ControllerName: "application",
MethodName: "Save",
FixedParams: []string{},
Params: map[string][]string{"id": {"123"}},
},
&http.Request{
Method: "GET",
URL: &url.URL{Path: "/app/123/"},
}: {
ControllerName: "application",
MethodName: "Show",
FixedParams: []string{},
Params: map[string][]string{"id": {"123"}},
},
&http.Request{
Method: "GET",
URL: &url.URL{Path: "/public/css/style.css"},
}: {
ControllerName: "static",
MethodName: "Serve",
FixedParams: []string{"public"},
Params: map[string][]string{"filepath": {"css/style.css"}},
},
&http.Request{
Method: "GET",
URL: &url.URL{Path: "/javascript/sessvars.js"},
}: {
ControllerName: "static",
MethodName: "Serve",
FixedParams: []string{"public/js"},
Params: map[string][]string{"filepath": {"sessvars.js"}},
},
&http.Request{
Method: "GET",
URL: &url.URL{Path: "/Implicit/Route"},
}: {
ControllerName: "implicit",
MethodName: "Route",
FixedParams: []string{},
Params: map[string][]string{
"METHOD": {"GET"},
"controller": {"Implicit"},
"action": {"Route"},
},
},
&http.Request{
Method: "GET",
URL: &url.URL{Path: "/favicon.ico"},
}: {
ControllerName: "",
MethodName: "",
Action: "404",
FixedParams: []string{},
Params: map[string][]string{},
},
&http.Request{
Method: "POST",
URL: &url.URL{Path: "/app/123"},
Header: http.Header{"X-Http-Method-Override": []string{"PATCH"}},
}: {
ControllerName: "application",
MethodName: "Update",
FixedParams: []string{},
Params: map[string][]string{"id": {"123"}},
},
&http.Request{
Method: "GET",
URL: &url.URL{Path: "/app/123"},
Header: http.Header{"X-Http-Method-Override": []string{"PATCH"}},
}: {
ControllerName: "application",
MethodName: "Show",
FixedParams: []string{},
Params: map[string][]string{"id": {"123"}},
},
}
func TestRouteMatches(t *testing.T) {
initControllers()
BasePath = "/BasePath"
router := NewRouter("")
router.Routes, _ = parseRoutes(appModule, "", "", TestRoutes, false)
if err := router.updateTree(); err != nil {
t.Errorf("updateTree failed: %s", err)
}
for req, expected := range routeMatchTestCases {
t.Log("Routing:", req.Method, req.URL)
actual := router.Route(req)
if !eq(t, "Found route", actual != nil, expected != nil) {
continue
}
if expected.ControllerName != "" {
eq(t, "ControllerName", actual.ControllerName, appModule.Namespace()+expected.ControllerName)
} else {
eq(t, "ControllerName", actual.ControllerName, expected.ControllerName)
}
eq(t, "MethodName", actual.MethodName, strings.ToLower(expected.MethodName))
eq(t, "len(Params)", len(actual.Params), len(expected.Params))
for key, actualValue := range actual.Params {
eq(t, "Params "+key, actualValue[0], expected.Params[key][0])
}
eq(t, "len(FixedParams)", len(actual.FixedParams), len(expected.FixedParams))
for i, actualValue := range actual.FixedParams {
eq(t, "FixedParams", actualValue, expected.FixedParams[i])
}
}
}
// Reverse Routing
type ReverseRouteArgs struct {
action string
args map[string]string
}
var reverseRoutingTestCases = map[*ReverseRouteArgs]*ActionDefinition{
&ReverseRouteArgs{
action: "Application.Index",
args: map[string]string{},
}: {
URL: "/",
Method: "GET",
Star: false,
Action: "Application.Index",
},
&ReverseRouteArgs{
action: "Application.Show",
args: map[string]string{"id": "123"},
}: {
URL: "/app/123/",
Method: "GET",
Star: false,
Action: "Application.Show",
},
&ReverseRouteArgs{
action: "Implicit.Route",
args: map[string]string{},
}: {
URL: "/implicit/route",
Method: "GET",
Star: true,
Action: "Implicit.Route",
},
&ReverseRouteArgs{
action: "Application.Save",
args: map[string]string{"id": "123", "c": "http://continue"},
}: {
URL: "/app/123?c=http%3A%2F%2Fcontinue",
Method: "POST",
Star: false,
Action: "Application.Save",
},
&ReverseRouteArgs{
action: "Application.WildShow",
args: map[string]string{"id": "123"},
}: {
URL: "/app-wild/123/",
Method: "GET",
Star: false,
Action: "Application.WildShow",
},
}
type testController struct {
*Controller
}
func initControllers() {
registerControllers()
}
func TestReverseRouting(t *testing.T) {
initControllers()
router := NewRouter("")
router.Routes, _ = parseRoutes(appModule, "", "", TestRoutes, false)
for routeArgs, expected := range reverseRoutingTestCases {
actual := router.Reverse(routeArgs.action, routeArgs.args)
if !eq(t, fmt.Sprintf("Found route %s %s", routeArgs.action, actual), actual != nil, expected != nil) {
continue
}
eq(t, "Url", actual.URL, expected.URL)
eq(t, "Method", actual.Method, expected.Method)
eq(t, "Star", actual.Star, expected.Star)
eq(t, "Action", actual.Action, expected.Action)
}
}
func BenchmarkRouter(b *testing.B) {
router := NewRouter("")
router.Routes, _ = parseRoutes(nil, "", "", TestRoutes, false)
if err := router.updateTree(); err != nil {
b.Errorf("updateTree failed: %s", err)
}
b.ResetTimer()
for i := 0; i < b.N/len(routeMatchTestCases); i++ {
for req := range routeMatchTestCases {
r := router.Route(req)
if r == nil {
b.Errorf("Request not found: %s", req.URL.Path)
}
}
}
}
// The benchmark from github.com/ant0ine/go-urlrouter
func BenchmarkLargeRouter(b *testing.B) {
router := NewRouter("")
routePaths := []string{
"/",
"/signin",
"/signout",
"/profile",
"/settings",
"/upload/*file",
}
for i := 0; i < 10; i++ {
for j := 0; j < 5; j++ {
routePaths = append(routePaths, fmt.Sprintf("/resource%d/:id/property%d", i, j))
}
routePaths = append(routePaths, fmt.Sprintf("/resource%d/:id", i))
routePaths = append(routePaths, fmt.Sprintf("/resource%d", i))
}
routePaths = append(routePaths, "/:any")
for _, p := range routePaths {
router.Routes = append(router.Routes,
NewRoute(appModule, "GET", p, "Controller.Action", "", "", 0))
}
if err := router.updateTree(); err != nil {
b.Errorf("updateTree failed: %s", err)
}
requestUrls := []string{
"http://example.org/",
"http://example.org/resource9/123",
"http://example.org/resource9/123/property1",
"http://example.org/doesnotexist",
}
var reqs []*http.Request
for _, url := range requestUrls {
req, _ := http.NewRequest("GET", url, nil)
reqs = append(reqs, req)
}
b.ResetTimer()
for i := 0; i < b.N/len(reqs); i++ {
for _, req := range reqs {
route := router.Route(req)
if route == nil {
b.Errorf("Failed to route: %s", req.URL.Path)
}
}
}
}
func BenchmarkRouterFilter(b *testing.B) {
startFakeBookingApp()
controllers := []*Controller{
{Request: NewRequest(showRequest)},
{Request: NewRequest(staticRequest)},
}
for _, c := range controllers {
c.Params = &Params{}
ParseParams(c.Params, c.Request)
}
b.ResetTimer()
for i := 0; i < b.N/len(controllers); i++ {
for _, c := range controllers {
RouterFilter(c, NilChain)
}
}
}
func TestOverrideMethodFilter(t *testing.T) {
req, _ := http.NewRequest("POST", "/hotels/3", strings.NewReader("_method=put"))
req.Header.Set("Content-Type", "application/x-www-form-urlencoded; param=value")
c := Controller{
Request: NewRequest(req),
}
if HTTPMethodOverride(&c, NilChain); c.Request.Request.Method != "PUT" {
t.Errorf("Expected to override current method '%s' in route, found '%s' instead", "", c.Request.Request.Method)
}
}
// Helpers
func eq(t *testing.T, name string, a, b interface{}) bool {
if a != b {
t.Error(name, ": (actual)", a, " != ", b, "(expected)")
return false
}
return true
}