-
Notifications
You must be signed in to change notification settings - Fork 678
Expand file tree
/
Copy pathcurly_test.go
More file actions
401 lines (352 loc) · 11.6 KB
/
Copy pathcurly_test.go
File metadata and controls
401 lines (352 loc) · 11.6 KB
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
package restful
import (
"io"
"net/http"
"regexp"
"sync"
"testing"
)
var requestPaths = []struct {
// url with path (1) is handled by service with root (2) and remainder has value final (3)
path, root string
}{
{"/", "/"},
{"/p", "/p"},
{"/p/x", "/p/{q}"},
{"/q/x", "/q"},
{"/p/x/", "/p/{q}"},
{"/p/x/y", "/p/{q}"},
{"/q/x/y", "/q"},
{"/z/q", "/{p}/q"},
{"/a/b/c/q", "/"},
}
// go test -v -test.run TestCurlyDetectWebService ...restful
func TestCurlyDetectWebService(t *testing.T) {
ws1 := new(WebService).Path("/")
ws2 := new(WebService).Path("/p")
ws3 := new(WebService).Path("/q")
ws4 := new(WebService).Path("/p/q")
ws5 := new(WebService).Path("/p/{q}")
ws7 := new(WebService).Path("/{p}/q")
var wss = []*WebService{ws1, ws2, ws3, ws4, ws5, ws7}
for _, each := range wss {
t.Logf("path=%s,toks=%v\n", each.pathExpr.Source, each.pathExpr.tokens)
}
router := CurlyRouter{}
ok := true
for i, fixture := range requestPaths {
requestTokens := tokenizePath(fixture.path)
who := router.detectWebService(requestTokens, wss)
if who != nil && who.RootPath() != fixture.root {
t.Logf("[line:%v] Unexpected dispatcher, expected:%v, actual:%v", i, fixture.root, who.RootPath())
ok = false
}
}
if !ok {
t.Fail()
}
}
var serviceDetects = []struct {
path string
found bool
root string
}{
{"/a/b", true, "/{p}/{q}/{r}"},
{"/p/q", true, "/p/q"},
{"/q/p", true, "/q"},
{"/", true, "/"},
{"/p/q/r", true, "/p/q"},
}
// go test -v -test.run Test_detectWebService ...restful
func Test_detectWebService(t *testing.T) {
router := CurlyRouter{}
ws1 := new(WebService).Path("/")
ws2 := new(WebService).Path("/p")
ws3 := new(WebService).Path("/q")
ws4 := new(WebService).Path("/p/q")
ws5 := new(WebService).Path("/p/{q}")
ws6 := new(WebService).Path("/p/{q}/")
ws7 := new(WebService).Path("/{p}/q")
ws8 := new(WebService).Path("/{p}/{q}/{r}")
var wss = []*WebService{ws8, ws7, ws6, ws5, ws4, ws3, ws2, ws1}
for _, fix := range serviceDetects {
requestPath := fix.path
requestTokens := tokenizePath(requestPath)
for _, ws := range wss {
serviceTokens := ws.pathExpr.tokens
matches, score := router.computeWebserviceScore(requestTokens, serviceTokens)
t.Logf("req=%s,toks:%v,ws=%s,toks:%v,score=%d,matches=%v", requestPath, requestTokens, ws.RootPath(), serviceTokens, score, matches)
}
best := router.detectWebService(requestTokens, wss)
if best != nil {
if fix.found {
t.Logf("best=%s", best.RootPath())
} else {
t.Fatalf("should have found:%s", fix.root)
}
}
}
}
func Test_detectWebServiceWithRegexPath(t *testing.T) {
router := CurlyRouter{}
holaWS := new(WebService).Path("/{:hola}")
helloWS := new(WebService).Path("/{:hello}")
var wss = []*WebService{holaWS, helloWS}
holaJuanInTokens := tokenizePath("/hola/juan")
selected := router.detectWebService(holaJuanInTokens, wss)
if selected != holaWS {
t.Fatalf("expected holaWS, got %v", selected.rootPath)
}
helloJuanInTokens := tokenizePath("/hello/juan")
selected = router.detectWebService(helloJuanInTokens, wss)
if selected != helloWS {
t.Fatalf("expected helloWS, got %v", selected.rootPath)
}
}
var routeMatchers = []struct {
route string
path string
matches bool
paramCount int
staticCount int
hasCustomVerb bool
}{
// route, request-path
{"/a", "/a", true, 0, 1, false},
{"/a", "/b", false, 0, 0, false},
{"/a", "/b", false, 0, 0, false},
{"/a/{b}/c/", "/a/2/c", true, 1, 2, false},
{"/{a}/{b}/{c}/", "/a/b", false, 0, 0, false},
{"/{x:*}", "/", false, 0, 0, false},
{"/{x:*}", "/a", true, 1, 0, false},
{"/{x:*}", "/a/b", true, 1, 0, false},
{"/a/{x:*}", "/a/b", true, 1, 1, false},
{"/a/{x:[A-Z][A-Z]}", "/a/ZX", true, 1, 1, false},
{"/basepath/{resource:*}", "/basepath/some/other/location/test.xml", true, 1, 1, false},
{"/resources:run", "/resources:run", true, 0, 2, true},
{"/resources:run", "/user:run", false, 0, 0, true},
{"/resources:run", "/resources", false, 0, 0, true},
{"/users/{userId:^prefix-}:start", "/users/prefix-}:startUserId", false, 0, 0, true},
{"/users/{userId:^prefix-}:start", "/users/prefix-userId:start", true, 1, 2, true},
}
// clear && go test -v -test.run Test_matchesRouteByPathTokens ...restful
func Test_matchesRouteByPathTokens(t *testing.T) {
router := CurlyRouter{}
for i, each := range routeMatchers {
routeToks := tokenizePath(each.route)
reqToks := tokenizePath(each.path)
matches, pCount, sCount := router.matchesRouteByPathTokens(routeToks, reqToks, each.hasCustomVerb)
if matches != each.matches {
t.Fatalf("[%d] unexpected matches outcome route:%s, path:%s, matches:%v", i, each.route, each.path, matches)
}
if pCount != each.paramCount {
t.Fatalf("[%d] unexpected paramCount got:%d want:%d ", i, pCount, each.paramCount)
}
if sCount != each.staticCount {
t.Fatalf("[%d] unexpected staticCount got:%d want:%d ", i, sCount, each.staticCount)
}
}
}
// clear && go test -v -test.run TestExtractParameters_Wildcard1 ...restful
func TestExtractParameters_Wildcard1(t *testing.T) {
params := doExtractParams("/fixed/{var:*}", 2, "/fixed/remainder", t)
if params["var"] != "remainder" {
t.Errorf("parameter mismatch var: %s", params["var"])
}
}
// clear && go test -v -test.run TestExtractParameters_Wildcard2 ...restful
func TestExtractParameters_Wildcard2(t *testing.T) {
params := doExtractParams("/fixed/{var:*}", 2, "/fixed/remain/der", t)
if params["var"] != "remain/der" {
t.Errorf("parameter mismatch var: %s", params["var"])
}
}
// clear && go test -v -test.run TestExtractParameters_Wildcard3 ...restful
func TestExtractParameters_Wildcard3(t *testing.T) {
params := doExtractParams("/static/{var:*}", 2, "/static/test/sub/hi.html", t)
if params["var"] != "test/sub/hi.html" {
t.Errorf("parameter mismatch var: %s", params["var"])
}
}
func TestExtractParameters_Wildcard4(t *testing.T) {
params := doExtractParams("/static/{var:*}/sub", 3, "/static/test/sub", t)
if params["var"] != "test/sub" {
t.Errorf("parameter mismatch var: %s", params["var"])
}
}
// clear && go test -v -test.run TestCurly_ISSUE_34 ...restful
func TestCurly_ISSUE_34(t *testing.T) {
ws1 := new(WebService).Path("/")
ws1.Route(ws1.GET("/{type}/{id}").To(curlyDummy))
ws1.Route(ws1.GET("/network/{id}").To(curlyDummy))
croutes := CurlyRouter{}.selectRoutes(ws1, tokenizePath("/network/12"))
if len(croutes) != 2 {
t.Fatal("expected 2 routes")
}
if got, want := croutes[0].route.Path, "/network/{id}"; got != want {
t.Errorf("got %v want %v", got, want)
}
}
// clear && go test -v -test.run TestCurly_ISSUE_34_2 ...restful
func TestCurly_ISSUE_34_2(t *testing.T) {
ws1 := new(WebService)
ws1.Route(ws1.GET("/network/{id}").To(curlyDummy))
ws1.Route(ws1.GET("/{type}/{id}").To(curlyDummy))
croutes := CurlyRouter{}.selectRoutes(ws1, tokenizePath("/network/12"))
if len(croutes) != 2 {
t.Fatal("expected 2 routes")
}
if got, want := croutes[0].route.Path, "/network/{id}"; got != want {
t.Errorf("got %v want %v", got, want)
}
}
// clear && go test -v -test.run TestCurly_JsonHtml ...restful
func TestCurly_JsonHtml(t *testing.T) {
ws1 := new(WebService)
ws1.Path("/")
ws1.Route(ws1.GET("/some.html").To(curlyDummy).Consumes("*/*").Produces("text/html"))
req, _ := http.NewRequest("GET", "/some.html", nil)
req.Header.Set("Accept", "application/json")
_, route, err := CurlyRouter{}.SelectRoute([]*WebService{ws1}, req)
if err == nil {
t.Error("error expected")
}
if route != nil {
t.Error("no route expected")
}
}
// go test -v -test.run TestCurly_ISSUE_137 ...restful
func TestCurly_ISSUE_137(t *testing.T) {
ws1 := new(WebService)
ws1.Route(ws1.GET("/hello").To(curlyDummy))
ws1.Path("/")
req, _ := http.NewRequest("GET", "/", nil)
_, route, _ := CurlyRouter{}.SelectRoute([]*WebService{ws1}, req)
t.Log(route)
if route != nil {
t.Error("no route expected")
}
}
// go test -v -test.run TestCurly_ISSUE_137_2 ...restful
func TestCurly_ISSUE_137_2(t *testing.T) {
ws1 := new(WebService)
ws1.Route(ws1.GET("/hello").To(curlyDummy))
ws1.Path("/")
req, _ := http.NewRequest("GET", "/hello/bob", nil)
_, route, _ := CurlyRouter{}.SelectRoute([]*WebService{ws1}, req)
t.Log(route)
if route != nil {
t.Errorf("no route expected, got %v", route)
}
}
func curlyDummy(req *Request, resp *Response) { io.WriteString(resp.ResponseWriter, "curlyDummy") }
func TestRegexCaching(t *testing.T) {
// Store original state and enable caching for this test
originalEnabled := pathTokenCacheEnabled
defer func() {
SetPathTokenCacheEnabled(originalEnabled)
}()
SetPathTokenCacheEnabled(true)
// Clear cache before test
regexCache = sync.Map{}
router := CurlyRouter{}
// Test with regex pattern
routeToken := "{id:[0-9]+}"
requestToken := "123"
// First call should cache the regex
matches1, _ := router.regularMatchesPathToken(routeToken, 3, requestToken)
if !matches1 {
t.Error("Expected first call to match")
}
// Verify cache contains the pattern
pattern := "[0-9]+"
_, found := regexCache.Load(pattern)
if !found {
t.Error("Expected pattern to be cached")
}
// Second call should use cached regex
matches2, _ := router.regularMatchesPathToken(routeToken, 3, requestToken)
if !matches2 {
t.Error("Expected second call to match using cache")
}
// Test with different pattern to ensure separate caching
routeToken2 := "{name:[a-z]+}"
requestToken2 := "john"
matches3, _ := router.regularMatchesPathToken(routeToken2, 5, requestToken2)
if !matches3 {
t.Error("Expected name pattern to match")
}
// Verify both patterns are cached
pattern2 := "[a-z]+"
_, found2 := regexCache.Load(pattern2)
if !found2 {
t.Error("Expected name pattern to be cached")
}
}
func TestRegexCacheDisabled(t *testing.T) {
// Store original state
originalEnabled := pathTokenCacheEnabled
defer func() {
SetPathTokenCacheEnabled(originalEnabled)
}()
// Clear cache before test
regexCache = sync.Map{}
// Disable caching
SetPathTokenCacheEnabled(false)
router := CurlyRouter{}
routeToken := "{id:[0-9]+}"
requestToken := "123"
// Call should work but not cache
matches, _ := router.regularMatchesPathToken(routeToken, 3, requestToken)
if !matches {
t.Error("Expected call to match")
}
// Verify pattern is not cached
pattern := "[0-9]+"
_, found := regexCache.Load(pattern)
if found {
t.Error("Expected pattern to not be cached when caching is disabled")
}
// Re-enable caching
SetPathTokenCacheEnabled(true)
// Now it should cache
matches2, _ := router.regularMatchesPathToken(routeToken, 3, requestToken)
if !matches2 {
t.Error("Expected call to match")
}
// Verify pattern is now cached
_, found2 := regexCache.Load(pattern)
if !found2 {
t.Error("Expected pattern to be cached when caching is re-enabled")
}
}
func TestRegexCachePanicSafety(t *testing.T) {
// Store original state
originalEnabled := pathTokenCacheEnabled
defer func() {
SetPathTokenCacheEnabled(originalEnabled)
regexCache = sync.Map{} // Clean up
}()
SetPathTokenCacheEnabled(true)
// Poison cache with wrong type
pattern := "[0-9]+"
regexCache.Store(pattern, "not a regex")
router := CurlyRouter{}
routeToken := "{id:[0-9]+}"
requestToken := "123"
// Should not panic, should handle invalid cache entry gracefully
matches, _ := router.regularMatchesPathToken(routeToken, 3, requestToken)
if !matches {
t.Error("Expected call to match even with corrupted cache")
}
// After the call, the invalid entry should be overwritten with valid regex
if cached, found := regexCache.Load(pattern); found {
if _, ok := cached.(*regexp.Regexp); ok {
// Success: cache entry is now a valid regex
} else {
t.Error("Expected invalid cache entry to be overwritten with valid regex")
}
} else {
t.Error("Expected valid regex to be cached")
}
}