tree_test.go
This file
Path
tree_test.go
1,113 lines · 35.1 KiB · Go
Last changed by
fix(tree): panic in findCaseInsensitivePathRec with RedirectFixedPath (#4535)Varun Chawlabefore adoption472d086
History of this fileTake it
1// Copyright 2013 Julien Schmidt. All rights reserved.2// Use of this source code is governed by a BSD-style license that can be found3// at https://github.com/julienschmidt/httprouter/blob/master/LICENSE45package gin67import (8 "fmt"9 "reflect"10 "regexp"11 "strings"12 "testing"13)1415// Used as a workaround since we can't compare functions or their addresses16var fakeHandlerValue string1718func fakeHandler(val string) HandlersChain {19 return HandlersChain{func(c *Context) {20 fakeHandlerValue = val21 }}22}2324type testRequests []struct {25 path string26 nilHandler bool27 route string28 ps Params29}3031func getParams() *Params {32 ps := make(Params, 0, 20)33 return &ps34}3536func getSkippedNodes() *[]skippedNode {37 ps := make([]skippedNode, 0, 20)38 return &ps39}4041func checkRequests(t *testing.T, tree *node, requests testRequests, unescapes ...bool) {42 unescape := false43 if len(unescapes) >= 1 {44 unescape = unescapes[0]45 }4647 for _, request := range requests {48 value := tree.getValue(request.path, getParams(), getSkippedNodes(), unescape)4950 if value.handlers == nil {51 if !request.nilHandler {52 t.Errorf("handle mismatch for route '%s': Expected non-nil handle", request.path)53 }54 } else if request.nilHandler {55 t.Errorf("handle mismatch for route '%s': Expected nil handle", request.path)56 } else {57 value.handlers[0](nil)58 if fakeHandlerValue != request.route {59 t.Errorf("handle mismatch for route '%s': Wrong handle (%s != %s)", request.path, fakeHandlerValue, request.route)60 }61 }6263 if value.params != nil {64 if !reflect.DeepEqual(*value.params, request.ps) {65 t.Errorf("Params mismatch for route '%s'", request.path)66 }67 }6869 }70}7172func checkPriorities(t *testing.T, n *node) uint32 {73 var prio uint3274 for i := range n.children {75 prio += checkPriorities(t, n.children[i])76 }7778 if n.handlers != nil {79 prio++80 }8182 if n.priority != prio {83 t.Errorf(84 "priority mismatch for node '%s': is %d, should be %d",85 n.path, n.priority, prio,86 )87 }8889 return prio90}9192func TestCountParams(t *testing.T) {93 if countParams("/path/:param1/static/*catch-all") != 2 {94 t.Fail()95 }96 if countParams(strings.Repeat("/:param", 256)) != 256 {97 t.Fail()98 }99}100101func TestTreeAddAndGet(t *testing.T) {102 tree := &node{}103104 routes := [...]string{105 "/hi",106 "/contact",107 "/co",108 "/c",109 "/a",110 "/ab",111 "/doc/",112 "/doc/go_faq.html",113 "/doc/go1.html",114 "/α",115 "/β",116 }117 for _, route := range routes {118 tree.addRoute(route, fakeHandler(route))119 }120121 checkRequests(t, tree, testRequests{122 {"/a", false, "/a", nil},123 {"/", true, "", nil},124 {"/hi", false, "/hi", nil},125 {"/contact", false, "/contact", nil},126 {"/co", false, "/co", nil},127 {"/con", true, "", nil}, // key mismatch128 {"/cona", true, "", nil}, // key mismatch129 {"/no", true, "", nil}, // no matching child130 {"/ab", false, "/ab", nil},131 {"/α", false, "/α", nil},132 {"/β", false, "/β", nil},133 })134135 checkPriorities(t, tree)136}137138func TestTreeWildcard(t *testing.T) {139 tree := &node{}140141 routes := [...]string{142 "/",143 "/cmd/:tool/",144 "/cmd/:tool/:sub",145 "/cmd/whoami",146 "/cmd/whoami/root",147 "/cmd/whoami/root/",148 "/src/*filepath",149 "/search/",150 "/search/:query",151 "/search/gin-gonic",152 "/search/google",153 "/user_:name",154 "/user_:name/about",155 "/files/:dir/*filepath",156 "/doc/",157 "/doc/go_faq.html",158 "/doc/go1.html",159 "/info/:user/public",160 "/info/:user/project/:project",161 "/info/:user/project/golang",162 "/aa/*xx",163 "/ab/*xx",164 "/:cc",165 "/c1/:dd/e",166 "/c1/:dd/e1",167 "/:cc/cc",168 "/:cc/:dd/ee",169 "/:cc/:dd/:ee/ff",170 "/:cc/:dd/:ee/:ff/gg",171 "/:cc/:dd/:ee/:ff/:gg/hh",172 "/get/test/abc/",173 "/get/:param/abc/",174 "/something/:paramname/thirdthing",175 "/something/secondthing/test",176 "/get/abc",177 "/get/:param",178 "/get/abc/123abc",179 "/get/abc/:param",180 "/get/abc/123abc/xxx8",181 "/get/abc/123abc/:param",182 "/get/abc/123abc/xxx8/1234",183 "/get/abc/123abc/xxx8/:param",184 "/get/abc/123abc/xxx8/1234/ffas",185 "/get/abc/123abc/xxx8/1234/:param",186 "/get/abc/123abc/xxx8/1234/kkdd/12c",187 "/get/abc/123abc/xxx8/1234/kkdd/:param",188 "/get/abc/:param/test",189 "/get/abc/123abd/:param",190 "/get/abc/123abddd/:param",191 "/get/abc/123/:param",192 "/get/abc/123abg/:param",193 "/get/abc/123abf/:param",194 "/get/abc/123abfff/:param",195 "/get/abc/escaped_colon/test\\:param",196 }197 for _, route := range routes {198 tree.addRoute(route, fakeHandler(route))199 }200201 checkRequests(t, tree, testRequests{202 {"/", false, "/", nil},203 {"/cmd/test", true, "/cmd/:tool/", Params{Param{"tool", "test"}}},204 {"/cmd/test/", false, "/cmd/:tool/", Params{Param{"tool", "test"}}},205 {"/cmd/test/3", false, "/cmd/:tool/:sub", Params{Param{Key: "tool", Value: "test"}, Param{Key: "sub", Value: "3"}}},206 {"/cmd/who", true, "/cmd/:tool/", Params{Param{"tool", "who"}}},207 {"/cmd/who/", false, "/cmd/:tool/", Params{Param{"tool", "who"}}},208 {"/cmd/whoami", false, "/cmd/whoami", nil},209 {"/cmd/whoami/", true, "/cmd/whoami", nil},210 {"/cmd/whoami/r", false, "/cmd/:tool/:sub", Params{Param{Key: "tool", Value: "whoami"}, Param{Key: "sub", Value: "r"}}},211 {"/cmd/whoami/r/", true, "/cmd/:tool/:sub", Params{Param{Key: "tool", Value: "whoami"}, Param{Key: "sub", Value: "r"}}},212 {"/cmd/whoami/root", false, "/cmd/whoami/root", nil},213 {"/cmd/whoami/root/", false, "/cmd/whoami/root/", nil},214 {"/src/", false, "/src/*filepath", Params{Param{Key: "filepath", Value: "/"}}},215 {"/src/some/file.png", false, "/src/*filepath", Params{Param{Key: "filepath", Value: "/some/file.png"}}},216 {"/search/", false, "/search/", nil},217 {"/search/someth!ng+in+ünìcodé", false, "/search/:query", Params{Param{Key: "query", Value: "someth!ng+in+ünìcodé"}}},218 {"/search/someth!ng+in+ünìcodé/", true, "", Params{Param{Key: "query", Value: "someth!ng+in+ünìcodé"}}},219 {"/search/gin", false, "/search/:query", Params{Param{"query", "gin"}}},220 {"/search/gin-gonic", false, "/search/gin-gonic", nil},221 {"/search/google", false, "/search/google", nil},222 {"/user_gopher", false, "/user_:name", Params{Param{Key: "name", Value: "gopher"}}},223 {"/user_gopher/about", false, "/user_:name/about", Params{Param{Key: "name", Value: "gopher"}}},224 {"/files/js/inc/framework.js", false, "/files/:dir/*filepath", Params{Param{Key: "dir", Value: "js"}, Param{Key: "filepath", Value: "/inc/framework.js"}}},225 {"/info/gordon/public", false, "/info/:user/public", Params{Param{Key: "user", Value: "gordon"}}},226 {"/info/gordon/project/go", false, "/info/:user/project/:project", Params{Param{Key: "user", Value: "gordon"}, Param{Key: "project", Value: "go"}}},227 {"/info/gordon/project/golang", false, "/info/:user/project/golang", Params{Param{Key: "user", Value: "gordon"}}},228 {"/aa/aa", false, "/aa/*xx", Params{Param{Key: "xx", Value: "/aa"}}},229 {"/ab/ab", false, "/ab/*xx", Params{Param{Key: "xx", Value: "/ab"}}},230 {"/a", false, "/:cc", Params{Param{Key: "cc", Value: "a"}}},231 // * Error with argument being intercepted232 // new PR handle (/all /all/cc /a/cc)233 // fix PR: https://github.com/gin-gonic/gin/pull/2796234 {"/all", false, "/:cc", Params{Param{Key: "cc", Value: "all"}}},235 {"/d", false, "/:cc", Params{Param{Key: "cc", Value: "d"}}},236 {"/ad", false, "/:cc", Params{Param{Key: "cc", Value: "ad"}}},237 {"/dd", false, "/:cc", Params{Param{Key: "cc", Value: "dd"}}},238 {"/dddaa", false, "/:cc", Params{Param{Key: "cc", Value: "dddaa"}}},239 {"/aa", false, "/:cc", Params{Param{Key: "cc", Value: "aa"}}},240 {"/aaa", false, "/:cc", Params{Param{Key: "cc", Value: "aaa"}}},241 {"/aaa/cc", false, "/:cc/cc", Params{Param{Key: "cc", Value: "aaa"}}},242 {"/ab", false, "/:cc", Params{Param{Key: "cc", Value: "ab"}}},243 {"/abb", false, "/:cc", Params{Param{Key: "cc", Value: "abb"}}},244 {"/abb/cc", false, "/:cc/cc", Params{Param{Key: "cc", Value: "abb"}}},245 {"/allxxxx", false, "/:cc", Params{Param{Key: "cc", Value: "allxxxx"}}},246 {"/alldd", false, "/:cc", Params{Param{Key: "cc", Value: "alldd"}}},247 {"/all/cc", false, "/:cc/cc", Params{Param{Key: "cc", Value: "all"}}},248 {"/a/cc", false, "/:cc/cc", Params{Param{Key: "cc", Value: "a"}}},249 {"/c1/d/e", false, "/c1/:dd/e", Params{Param{Key: "dd", Value: "d"}}},250 {"/c1/d/e1", false, "/c1/:dd/e1", Params{Param{Key: "dd", Value: "d"}}},251 {"/c1/d/ee", false, "/:cc/:dd/ee", Params{Param{Key: "cc", Value: "c1"}, Param{Key: "dd", Value: "d"}}},252 {"/cc/cc", false, "/:cc/cc", Params{Param{Key: "cc", Value: "cc"}}},253 {"/ccc/cc", false, "/:cc/cc", Params{Param{Key: "cc", Value: "ccc"}}},254 {"/deedwjfs/cc", false, "/:cc/cc", Params{Param{Key: "cc", Value: "deedwjfs"}}},255 {"/acllcc/cc", false, "/:cc/cc", Params{Param{Key: "cc", Value: "acllcc"}}},256 {"/get/test/abc/", false, "/get/test/abc/", nil},257 {"/get/te/abc/", false, "/get/:param/abc/", Params{Param{Key: "param", Value: "te"}}},258 {"/get/testaa/abc/", false, "/get/:param/abc/", Params{Param{Key: "param", Value: "testaa"}}},259 {"/get/xx/abc/", false, "/get/:param/abc/", Params{Param{Key: "param", Value: "xx"}}},260 {"/get/tt/abc/", false, "/get/:param/abc/", Params{Param{Key: "param", Value: "tt"}}},261 {"/get/a/abc/", false, "/get/:param/abc/", Params{Param{Key: "param", Value: "a"}}},262 {"/get/t/abc/", false, "/get/:param/abc/", Params{Param{Key: "param", Value: "t"}}},263 {"/get/aa/abc/", false, "/get/:param/abc/", Params{Param{Key: "param", Value: "aa"}}},264 {"/get/abas/abc/", false, "/get/:param/abc/", Params{Param{Key: "param", Value: "abas"}}},265 {"/something/secondthing/test", false, "/something/secondthing/test", nil},266 {"/something/abcdad/thirdthing", false, "/something/:paramname/thirdthing", Params{Param{Key: "paramname", Value: "abcdad"}}},267 {"/something/secondthingaaaa/thirdthing", false, "/something/:paramname/thirdthing", Params{Param{Key: "paramname", Value: "secondthingaaaa"}}},268 {"/something/se/thirdthing", false, "/something/:paramname/thirdthing", Params{Param{Key: "paramname", Value: "se"}}},269 {"/something/s/thirdthing", false, "/something/:paramname/thirdthing", Params{Param{Key: "paramname", Value: "s"}}},270 {"/c/d/ee", false, "/:cc/:dd/ee", Params{Param{Key: "cc", Value: "c"}, Param{Key: "dd", Value: "d"}}},271 {"/c/d/e/ff", false, "/:cc/:dd/:ee/ff", Params{Param{Key: "cc", Value: "c"}, Param{Key: "dd", Value: "d"}, Param{Key: "ee", Value: "e"}}},272 {"/c/d/e/f/gg", false, "/:cc/:dd/:ee/:ff/gg", Params{Param{Key: "cc", Value: "c"}, Param{Key: "dd", Value: "d"}, Param{Key: "ee", Value: "e"}, Param{Key: "ff", Value: "f"}}},273 {"/c/d/e/f/g/hh", false, "/:cc/:dd/:ee/:ff/:gg/hh", Params{Param{Key: "cc", Value: "c"}, Param{Key: "dd", Value: "d"}, Param{Key: "ee", Value: "e"}, Param{Key: "ff", Value: "f"}, Param{Key: "gg", Value: "g"}}},274 {"/cc/dd/ee/ff/gg/hh", false, "/:cc/:dd/:ee/:ff/:gg/hh", Params{Param{Key: "cc", Value: "cc"}, Param{Key: "dd", Value: "dd"}, Param{Key: "ee", Value: "ee"}, Param{Key: "ff", Value: "ff"}, Param{Key: "gg", Value: "gg"}}},275 {"/get/abc", false, "/get/abc", nil},276 {"/get/a", false, "/get/:param", Params{Param{Key: "param", Value: "a"}}},277 {"/get/abz", false, "/get/:param", Params{Param{Key: "param", Value: "abz"}}},278 {"/get/12a", false, "/get/:param", Params{Param{Key: "param", Value: "12a"}}},279 {"/get/abcd", false, "/get/:param", Params{Param{Key: "param", Value: "abcd"}}},280 {"/get/abc/123abc", false, "/get/abc/123abc", nil},281 {"/get/abc/12", false, "/get/abc/:param", Params{Param{Key: "param", Value: "12"}}},282 {"/get/abc/123ab", false, "/get/abc/:param", Params{Param{Key: "param", Value: "123ab"}}},283 {"/get/abc/xyz", false, "/get/abc/:param", Params{Param{Key: "param", Value: "xyz"}}},284 {"/get/abc/123abcddxx", false, "/get/abc/:param", Params{Param{Key: "param", Value: "123abcddxx"}}},285 {"/get/abc/123abc/xxx8", false, "/get/abc/123abc/xxx8", nil},286 {"/get/abc/123abc/x", false, "/get/abc/123abc/:param", Params{Param{Key: "param", Value: "x"}}},287 {"/get/abc/123abc/xxx", false, "/get/abc/123abc/:param", Params{Param{Key: "param", Value: "xxx"}}},288 {"/get/abc/123abc/abc", false, "/get/abc/123abc/:param", Params{Param{Key: "param", Value: "abc"}}},289 {"/get/abc/123abc/xxx8xxas", false, "/get/abc/123abc/:param", Params{Param{Key: "param", Value: "xxx8xxas"}}},290 {"/get/abc/123abc/xxx8/1234", false, "/get/abc/123abc/xxx8/1234", nil},291 {"/get/abc/123abc/xxx8/1", false, "/get/abc/123abc/xxx8/:param", Params{Param{Key: "param", Value: "1"}}},292 {"/get/abc/123abc/xxx8/123", false, "/get/abc/123abc/xxx8/:param", Params{Param{Key: "param", Value: "123"}}},293 {"/get/abc/123abc/xxx8/78k", false, "/get/abc/123abc/xxx8/:param", Params{Param{Key: "param", Value: "78k"}}},294 {"/get/abc/123abc/xxx8/1234xxxd", false, "/get/abc/123abc/xxx8/:param", Params{Param{Key: "param", Value: "1234xxxd"}}},295 {"/get/abc/123abc/xxx8/1234/ffas", false, "/get/abc/123abc/xxx8/1234/ffas", nil},296 {"/get/abc/123abc/xxx8/1234/f", false, "/get/abc/123abc/xxx8/1234/:param", Params{Param{Key: "param", Value: "f"}}},297 {"/get/abc/123abc/xxx8/1234/ffa", false, "/get/abc/123abc/xxx8/1234/:param", Params{Param{Key: "param", Value: "ffa"}}},298 {"/get/abc/123abc/xxx8/1234/kka", false, "/get/abc/123abc/xxx8/1234/:param", Params{Param{Key: "param", Value: "kka"}}},299 {"/get/abc/123abc/xxx8/1234/ffas321", false, "/get/abc/123abc/xxx8/1234/:param", Params{Param{Key: "param", Value: "ffas321"}}},300 {"/get/abc/123abc/xxx8/1234/kkdd/12c", false, "/get/abc/123abc/xxx8/1234/kkdd/12c", nil},301 {"/get/abc/123abc/xxx8/1234/kkdd/1", false, "/get/abc/123abc/xxx8/1234/kkdd/:param", Params{Param{Key: "param", Value: "1"}}},302 {"/get/abc/123abc/xxx8/1234/kkdd/12", false, "/get/abc/123abc/xxx8/1234/kkdd/:param", Params{Param{Key: "param", Value: "12"}}},303 {"/get/abc/123abc/xxx8/1234/kkdd/12b", false, "/get/abc/123abc/xxx8/1234/kkdd/:param", Params{Param{Key: "param", Value: "12b"}}},304 {"/get/abc/123abc/xxx8/1234/kkdd/34", false, "/get/abc/123abc/xxx8/1234/kkdd/:param", Params{Param{Key: "param", Value: "34"}}},305 {"/get/abc/123abc/xxx8/1234/kkdd/12c2e3", false, "/get/abc/123abc/xxx8/1234/kkdd/:param", Params{Param{Key: "param", Value: "12c2e3"}}},306 {"/get/abc/12/test", false, "/get/abc/:param/test", Params{Param{Key: "param", Value: "12"}}},307 {"/get/abc/123abdd/test", false, "/get/abc/:param/test", Params{Param{Key: "param", Value: "123abdd"}}},308 {"/get/abc/123abdddf/test", false, "/get/abc/:param/test", Params{Param{Key: "param", Value: "123abdddf"}}},309 {"/get/abc/123ab/test", false, "/get/abc/:param/test", Params{Param{Key: "param", Value: "123ab"}}},310 {"/get/abc/123abgg/test", false, "/get/abc/:param/test", Params{Param{Key: "param", Value: "123abgg"}}},311 {"/get/abc/123abff/test", false, "/get/abc/:param/test", Params{Param{Key: "param", Value: "123abff"}}},312 {"/get/abc/123abffff/test", false, "/get/abc/:param/test", Params{Param{Key: "param", Value: "123abffff"}}},313 {"/get/abc/123abd/test", false, "/get/abc/123abd/:param", Params{Param{Key: "param", Value: "test"}}},314 {"/get/abc/123abddd/test", false, "/get/abc/123abddd/:param", Params{Param{Key: "param", Value: "test"}}},315 {"/get/abc/123/test22", false, "/get/abc/123/:param", Params{Param{Key: "param", Value: "test22"}}},316 {"/get/abc/123abg/test", false, "/get/abc/123abg/:param", Params{Param{Key: "param", Value: "test"}}},317 {"/get/abc/123abf/testss", false, "/get/abc/123abf/:param", Params{Param{Key: "param", Value: "testss"}}},318 {"/get/abc/123abfff/te", false, "/get/abc/123abfff/:param", Params{Param{Key: "param", Value: "te"}}},319 {"/get/abc/escaped_colon/test\\:param", false, "/get/abc/escaped_colon/test\\:param", nil},320 })321322 checkPriorities(t, tree)323}324325func TestUnescapeParameters(t *testing.T) {326 tree := &node{}327328 routes := [...]string{329 "/",330 "/cmd/:tool/:sub",331 "/cmd/:tool/",332 "/src/*filepath",333 "/search/:query",334 "/files/:dir/*filepath",335 "/info/:user/project/:project",336 "/info/:user",337 }338 for _, route := range routes {339 tree.addRoute(route, fakeHandler(route))340 }341342 unescape := true343 checkRequests(t, tree, testRequests{344 {"/", false, "/", nil},345 {"/cmd/test/", false, "/cmd/:tool/", Params{Param{Key: "tool", Value: "test"}}},346 {"/cmd/test", true, "", Params{Param{Key: "tool", Value: "test"}}},347 {"/src/some/file.png", false, "/src/*filepath", Params{Param{Key: "filepath", Value: "/some/file.png"}}},348 {"/src/some/file+test.png", false, "/src/*filepath", Params{Param{Key: "filepath", Value: "/some/file test.png"}}},349 {"/src/some/file++++%%%%test.png", false, "/src/*filepath", Params{Param{Key: "filepath", Value: "/some/file++++%%%%test.png"}}},350 {"/src/some/file%2Ftest.png", false, "/src/*filepath", Params{Param{Key: "filepath", Value: "/some/file/test.png"}}},351 {"/search/someth!ng+in+ünìcodé", false, "/search/:query", Params{Param{Key: "query", Value: "someth!ng in ünìcodé"}}},352 {"/info/gordon/project/go", false, "/info/:user/project/:project", Params{Param{Key: "user", Value: "gordon"}, Param{Key: "project", Value: "go"}}},353 {"/info/slash%2Fgordon", false, "/info/:user", Params{Param{Key: "user", Value: "slash/gordon"}}},354 {"/info/slash%2Fgordon/project/Project%20%231", false, "/info/:user/project/:project", Params{Param{Key: "user", Value: "slash/gordon"}, Param{Key: "project", Value: "Project #1"}}},355 {"/info/slash%%%%", false, "/info/:user", Params{Param{Key: "user", Value: "slash%%%%"}}},356 {"/info/slash%%%%2Fgordon/project/Project%%%%20%231", false, "/info/:user/project/:project", Params{Param{Key: "user", Value: "slash%%%%2Fgordon"}, Param{Key: "project", Value: "Project%%%%20%231"}}},357 }, unescape)358359 checkPriorities(t, tree)360}361362func catchPanic(testFunc func()) (recv any) {363 defer func() {364 recv = recover()365 }()366367 testFunc()368 return369}370371type testRoute struct {372 path string373 conflict bool374}375376func testRoutes(t *testing.T, routes []testRoute) {377 tree := &node{}378379 for _, route := range routes {380 recv := catchPanic(func() {381 tree.addRoute(route.path, nil)382 })383384 if route.conflict {385 if recv == nil {386 t.Errorf("no panic for conflicting route '%s'", route.path)387 }388 } else if recv != nil {389 t.Errorf("unexpected panic for route '%s': %v", route.path, recv)390 }391 }392}393394func TestTreeWildcardConflict(t *testing.T) {395 routes := []testRoute{396 {"/cmd/:tool/:sub", false},397 {"/cmd/vet", false},398 {"/foo/bar", false},399 {"/foo/:name", false},400 {"/foo/:names", true},401 {"/cmd/*path", true},402 {"/cmd/:badvar", true},403 {"/cmd/:tool/names", false},404 {"/cmd/:tool/:badsub/details", true},405 {"/src/*filepath", false},406 {"/src/:file", true},407 {"/src/static.json", true},408 {"/src/*filepathx", true},409 {"/src/", true},410 {"/src/foo/bar", true},411 {"/src1/", false},412 {"/src1/*filepath", true},413 {"/src2*filepath", true},414 {"/src2/*filepath", false},415 {"/search/:query", false},416 {"/search/valid", false},417 {"/user_:name", false},418 {"/user_x", false},419 {"/user_:name", false},420 {"/id:id", false},421 {"/id/:id", false},422 {"/static/*file", false},423 {"/static/", true},424 {"/escape/test\\:d1", false},425 {"/escape/test\\:d2", false},426 {"/escape/test:param", false},427 }428 testRoutes(t, routes)429}430431func TestCatchAllAfterSlash(t *testing.T) {432 routes := []testRoute{433 {"/non-leading-*catchall", true},434 }435 testRoutes(t, routes)436}437438func TestTreeChildConflict(t *testing.T) {439 routes := []testRoute{440 {"/cmd/vet", false},441 {"/cmd/:tool", false},442 {"/cmd/:tool/:sub", false},443 {"/cmd/:tool/misc", false},444 {"/cmd/:tool/:othersub", true},445 {"/src/AUTHORS", false},446 {"/src/*filepath", true},447 {"/user_x", false},448 {"/user_:name", false},449 {"/id/:id", false},450 {"/id:id", false},451 {"/:id", false},452 {"/*filepath", true},453 }454 testRoutes(t, routes)455}456457func TestTreeDuplicatePath(t *testing.T) {458 tree := &node{}459460 routes := [...]string{461 "/",462 "/doc/",463 "/src/*filepath",464 "/search/:query",465 "/user_:name",466 }467 for _, route := range routes {468 recv := catchPanic(func() {469 tree.addRoute(route, fakeHandler(route))470 })471 if recv != nil {472 t.Fatalf("panic inserting route '%s': %v", route, recv)473 }474475 // Add again476 recv = catchPanic(func() {477 tree.addRoute(route, nil)478 })479 if recv == nil {480 t.Fatalf("no panic while inserting duplicate route '%s", route)481 }482 }483484 // printChildren(tree, "")485486 checkRequests(t, tree, testRequests{487 {"/", false, "/", nil},488 {"/doc/", false, "/doc/", nil},489 {"/src/some/file.png", false, "/src/*filepath", Params{Param{"filepath", "/some/file.png"}}},490 {"/search/someth!ng+in+ünìcodé", false, "/search/:query", Params{Param{"query", "someth!ng+in+ünìcodé"}}},491 {"/user_gopher", false, "/user_:name", Params{Param{"name", "gopher"}}},492 })493}494495func TestEmptyWildcardName(t *testing.T) {496 tree := &node{}497498 routes := [...]string{499 "/user:",500 "/user:/",501 "/cmd/:/",502 "/src/*",503 }504 for _, route := range routes {505 recv := catchPanic(func() {506 tree.addRoute(route, nil)507 })508 if recv == nil {509 t.Fatalf("no panic while inserting route with empty wildcard name '%s", route)510 }511 }512}513514func TestTreeCatchAllConflict(t *testing.T) {515 routes := []testRoute{516 {"/src/*filepath/x", true},517 {"/src2/", false},518 {"/src2/*filepath/x", true},519 {"/src3/*filepath", false},520 {"/src3/*filepath/x", true},521 }522 testRoutes(t, routes)523}524525func TestTreeCatchAllConflictRoot(t *testing.T) {526 routes := []testRoute{527 {"/", false},528 {"/*filepath", true},529 }530 testRoutes(t, routes)531}532533func TestTreeCatchMaxParams(t *testing.T) {534 tree := &node{}535 route := "/cmd/*filepath"536 tree.addRoute(route, fakeHandler(route))537}538539func TestTreeDoubleWildcard(t *testing.T) {540 const panicMsg = "only one wildcard per path segment is allowed"541542 routes := [...]string{543 "/:foo:bar",544 "/:foo:bar/",545 "/:foo*bar",546 }547548 for _, route := range routes {549 tree := &node{}550 recv := catchPanic(func() {551 tree.addRoute(route, nil)552 })553554 if rs, ok := recv.(string); !ok || !strings.HasPrefix(rs, panicMsg) {555 t.Fatalf(`"Expected panic "%s" for route '%s', got "%v"`, panicMsg, route, recv)556 }557 }558}559560/*func TestTreeDuplicateWildcard(t *testing.T) {561 tree := &node{}562 routes := [...]string{563 "/:id/:name/:id",564 }565 for _, route := range routes {566 ...567 }568}*/569570func TestTreeTrailingSlashRedirect(t *testing.T) {571 tree := &node{}572573 routes := [...]string{574 "/hi",575 "/b/",576 "/search/:query",577 "/cmd/:tool/",578 "/src/*filepath",579 "/x",580 "/x/y",581 "/y/",582 "/y/z",583 "/0/:id",584 "/0/:id/1",585 "/1/:id/",586 "/1/:id/2",587 "/aa",588 "/a/",589 "/admin",590 "/admin/:category",591 "/admin/:category/:page",592 "/doc",593 "/doc/go_faq.html",594 "/doc/go1.html",595 "/no/a",596 "/no/b",597 "/api/:page/:name",598 "/api/hello/:name/bar/",599 "/api/bar/:name",600 "/api/baz/foo",601 "/api/baz/foo/bar",602 "/blog/:p",603 "/posts/:b/:c",604 "/posts/b/:c/d/",605 "/vendor/:x/*y",606 }607 for _, route := range routes {608 recv := catchPanic(func() {609 tree.addRoute(route, fakeHandler(route))610 })611 if recv != nil {612 t.Fatalf("panic inserting route '%s': %v", route, recv)613 }614 }615616 tsrRoutes := [...]string{617 "/hi/",618 "/b",619 "/search/gopher/",620 "/cmd/vet",621 "/src",622 "/x/",623 "/y",624 "/0/go/",625 "/1/go",626 "/a",627 "/admin/",628 "/admin/config/",629 "/admin/config/permissions/",630 "/doc/",631 "/admin/static/",632 "/admin/cfg/",633 "/admin/cfg/users/",634 "/api/hello/x/bar",635 "/api/baz/foo/",636 "/api/baz/bax/",637 "/api/bar/huh/",638 "/api/baz/foo/bar/",639 "/api/world/abc/",640 "/blog/pp/",641 "/posts/b/c/d",642 "/vendor/x",643 }644645 for _, route := range tsrRoutes {646 value := tree.getValue(route, nil, getSkippedNodes(), false)647 if value.handlers != nil {648 t.Fatalf("non-nil handler for TSR route '%s", route)649 } else if !value.tsr {650 t.Errorf("expected TSR recommendation for route '%s'", route)651 }652 }653654 noTsrRoutes := [...]string{655 "/",656 "/no",657 "/no/",658 "/_",659 "/_/",660 "/api",661 "/api/",662 "/api/hello/x/foo",663 "/api/baz/foo/bad",664 "/foo/p/p",665 }666 for _, route := range noTsrRoutes {667 value := tree.getValue(route, nil, getSkippedNodes(), false)668 if value.handlers != nil {669 t.Fatalf("non-nil handler for No-TSR route '%s", route)670 } else if value.tsr {671 t.Errorf("expected no TSR recommendation for route '%s'", route)672 }673 }674}675676func TestTreeRootTrailingSlashRedirect(t *testing.T) {677 tree := &node{}678679 recv := catchPanic(func() {680 tree.addRoute("/:test", fakeHandler("/:test"))681 })682 if recv != nil {683 t.Fatalf("panic inserting test route: %v", recv)684 }685686 value := tree.getValue("/", nil, getSkippedNodes(), false)687 if value.handlers != nil {688 t.Fatalf("non-nil handler")689 } else if value.tsr {690 t.Errorf("expected no TSR recommendation")691 }692}693694func TestRedirectTrailingSlash(t *testing.T) {695 data := []struct {696 path string697 }{698 {"/hello/:name"},699 {"/hello/:name/123"},700 {"/hello/:name/234"},701 }702703 node := &node{}704 for _, item := range data {705 node.addRoute(item.path, fakeHandler("test"))706 }707708 value := node.getValue("/hello/abx/", nil, getSkippedNodes(), false)709 if value.tsr != true {710 t.Fatalf("want true, is false")711 }712}713714func TestTreeFindCaseInsensitivePath(t *testing.T) {715 tree := &node{}716717 longPath := "/l" + strings.Repeat("o", 128) + "ng"718 lOngPath := "/l" + strings.Repeat("O", 128) + "ng/"719720 routes := [...]string{721 "/hi",722 "/b/",723 "/ABC/",724 "/search/:query",725 "/cmd/:tool/",726 "/src/*filepath",727 "/x",728 "/x/y",729 "/y/",730 "/y/z",731 "/0/:id",732 "/0/:id/1",733 "/1/:id/",734 "/1/:id/2",735 "/aa",736 "/a/",737 "/doc",738 "/doc/go_faq.html",739 "/doc/go1.html",740 "/doc/go/away",741 "/no/a",742 "/no/b",743 "/Π",744 "/u/apfêl/",745 "/u/äpfêl/",746 "/u/öpfêl",747 "/v/Äpfêl/",748 "/v/Öpfêl",749 "/w/♬", // 3 byte750 "/w/♭/", // 3 byte, last byte differs751 "/w/𠜎", // 4 byte752 "/w/𠜏/", // 4 byte753 longPath,754 }755756 for _, route := range routes {757 recv := catchPanic(func() {758 tree.addRoute(route, fakeHandler(route))759 })760 if recv != nil {761 t.Fatalf("panic inserting route '%s': %v", route, recv)762 }763 }764765 // Check out == in for all registered routes766 // With fixTrailingSlash = true767 for _, route := range routes {768 out, found := tree.findCaseInsensitivePath(route, true)769 if !found {770 t.Errorf("Route '%s' not found!", route)771 } else if string(out) != route {772 t.Errorf("Wrong result for route '%s': %s", route, string(out))773 }774 }775 // With fixTrailingSlash = false776 for _, route := range routes {777 out, found := tree.findCaseInsensitivePath(route, false)778 if !found {779 t.Errorf("Route '%s' not found!", route)780 } else if string(out) != route {781 t.Errorf("Wrong result for route '%s': %s", route, string(out))782 }783 }784785 tests := []struct {786 in string787 out string788 found bool789 slash bool790 }{791 {"/HI", "/hi", true, false},792 {"/HI/", "/hi", true, true},793 {"/B", "/b/", true, true},794 {"/B/", "/b/", true, false},795 {"/abc", "/ABC/", true, true},796 {"/abc/", "/ABC/", true, false},797 {"/aBc", "/ABC/", true, true},798 {"/aBc/", "/ABC/", true, false},799 {"/abC", "/ABC/", true, true},800 {"/abC/", "/ABC/", true, false},801 {"/SEARCH/QUERY", "/search/QUERY", true, false},802 {"/SEARCH/QUERY/", "/search/QUERY", true, true},803 {"/CMD/TOOL/", "/cmd/TOOL/", true, false},804 {"/CMD/TOOL", "/cmd/TOOL/", true, true},805 {"/SRC/FILE/PATH", "/src/FILE/PATH", true, false},806 {"/x/Y", "/x/y", true, false},807 {"/x/Y/", "/x/y", true, true},808 {"/X/y", "/x/y", true, false},809 {"/X/y/", "/x/y", true, true},810 {"/X/Y", "/x/y", true, false},811 {"/X/Y/", "/x/y", true, true},812 {"/Y/", "/y/", true, false},813 {"/Y", "/y/", true, true},814 {"/Y/z", "/y/z", true, false},815 {"/Y/z/", "/y/z", true, true},816 {"/Y/Z", "/y/z", true, false},817 {"/Y/Z/", "/y/z", true, true},818 {"/y/Z", "/y/z", true, false},819 {"/y/Z/", "/y/z", true, true},820 {"/Aa", "/aa", true, false},821 {"/Aa/", "/aa", true, true},822 {"/AA", "/aa", true, false},823 {"/AA/", "/aa", true, true},824 {"/aA", "/aa", true, false},825 {"/aA/", "/aa", true, true},826 {"/A/", "/a/", true, false},827 {"/A", "/a/", true, true},828 {"/DOC", "/doc", true, false},829 {"/DOC/", "/doc", true, true},830 {"/NO", "", false, true},831 {"/DOC/GO", "", false, true},832 {"/π", "/Π", true, false},833 {"/π/", "/Π", true, true},834 {"/u/ÄPFÊL/", "/u/äpfêl/", true, false},835 {"/u/ÄPFÊL", "/u/äpfêl/", true, true},836 {"/u/ÖPFÊL/", "/u/öpfêl", true, true},837 {"/u/ÖPFÊL", "/u/öpfêl", true, false},838 {"/v/äpfêL/", "/v/Äpfêl/", true, false},839 {"/v/äpfêL", "/v/Äpfêl/", true, true},840 {"/v/öpfêL/", "/v/Öpfêl", true, true},841 {"/v/öpfêL", "/v/Öpfêl", true, false},842 {"/w/♬/", "/w/♬", true, true},843 {"/w/♭", "/w/♭/", true, true},844 {"/w/𠜎/", "/w/𠜎", true, true},845 {"/w/𠜏", "/w/𠜏/", true, true},846 {lOngPath, longPath, true, true},847 }848 // With fixTrailingSlash = true849 for _, test := range tests {850 out, found := tree.findCaseInsensitivePath(test.in, true)851 if found != test.found || (found && (string(out) != test.out)) {852 t.Errorf("Wrong result for '%s': got %s, %t; want %s, %t",853 test.in, string(out), found, test.out, test.found)854 return855 }856 }857 // With fixTrailingSlash = false858 for _, test := range tests {859 out, found := tree.findCaseInsensitivePath(test.in, false)860 if test.slash {861 if found { // test needs a trailingSlash fix. It must not be found!862 t.Errorf("Found without fixTrailingSlash: %s; got %s", test.in, string(out))863 }864 } else {865 if found != test.found || (found && (string(out) != test.out)) {866 t.Errorf("Wrong result for '%s': got %s, %t; want %s, %t",867 test.in, string(out), found, test.out, test.found)868 return869 }870 }871 }872}873874func TestTreeInvalidNodeType(t *testing.T) {875 const panicMsg = "invalid node type"876877 tree := &node{}878 tree.addRoute("/", fakeHandler("/"))879 tree.addRoute("/:page", fakeHandler("/:page"))880881 // set invalid node type882 tree.children[0].nType = 42883884 // normal lookup885 recv := catchPanic(func() {886 tree.getValue("/test", nil, getSkippedNodes(), false)887 })888 if rs, ok := recv.(string); !ok || rs != panicMsg {889 t.Fatalf("Expected panic '"+panicMsg+"', got '%v'", recv)890 }891892 // case-insensitive lookup893 recv = catchPanic(func() {894 tree.findCaseInsensitivePath("/test", true)895 })896 if rs, ok := recv.(string); !ok || rs != panicMsg {897 t.Fatalf("Expected panic '"+panicMsg+"', got '%v'", recv)898 }899}900901func TestTreeInvalidParamsType(t *testing.T) {902 tree := &node{}903 // add a child with wildcard904 route := "/:path"905 tree.addRoute(route, fakeHandler(route))906907 // set invalid Params type908 params := make(Params, 0)909910 // try to trigger slice bounds out of range with capacity 0911 tree.getValue("/test", ¶ms, getSkippedNodes(), false)912}913914func TestTreeExpandParamsCapacity(t *testing.T) {915 data := []struct {916 path string917 }{918 {"/:path"},919 {"/*path"},920 }921922 for _, item := range data {923 tree := &node{}924 tree.addRoute(item.path, fakeHandler(item.path))925 params := make(Params, 0)926927 value := tree.getValue("/test", ¶ms, getSkippedNodes(), false)928929 if value.params == nil {930 t.Errorf("Expected %s params to be set, but they weren't", item.path)931 continue932 }933934 if len(*value.params) != 1 {935 t.Errorf("Wrong number of %s params: got %d, want %d",936 item.path, len(*value.params), 1)937 continue938 }939 }940}941942func TestTreeWildcardConflictEx(t *testing.T) {943 conflicts := [...]struct {944 route string945 segPath string946 existPath string947 existSegPath string948 }{949 {"/who/are/foo", "/foo", `/who/are/\*you`, `/\*you`},950 {"/who/are/foo/", "/foo/", `/who/are/\*you`, `/\*you`},951 {"/who/are/foo/bar", "/foo/bar", `/who/are/\*you`, `/\*you`},952 {"/con:nection", ":nection", `/con:tact`, `:tact`},953 }954955 for _, conflict := range conflicts {956 // I have to re-create a 'tree', because the 'tree' will be957 // in an inconsistent state when the loop recovers from the958 // panic which threw by 'addRoute' function.959 tree := &node{}960 routes := [...]string{961 "/con:tact",962 "/who/are/*you",963 "/who/foo/hello",964 }965966 for _, route := range routes {967 tree.addRoute(route, fakeHandler(route))968 }969970 recv := catchPanic(func() {971 tree.addRoute(conflict.route, fakeHandler(conflict.route))972 })973974 if !regexp.MustCompile(fmt.Sprintf("'%s' in new path .* conflicts with existing wildcard '%s' in existing prefix '%s'", conflict.segPath, conflict.existSegPath, conflict.existPath)).MatchString(fmt.Sprint(recv)) {975 t.Fatalf("invalid wildcard conflict error (%v)", recv)976 }977 }978}979980func TestTreeInvalidEscape(t *testing.T) {981 routes := map[string]bool{982 "/r1/r": true,983 "/r2/:r": true,984 "/r3/\\:r": true,985 }986 tree := &node{}987 for route, valid := range routes {988 recv := catchPanic(func() {989 tree.addRoute(route, fakeHandler(route))990 })991 if recv == nil != valid {992 t.Fatalf("%s should be %t but got %v", route, valid, recv)993 }994 }995}996997func TestWildcardInvalidSlash(t *testing.T) {998 const panicMsgPrefix = "no / before catch-all in path"9991000 routes := map[string]bool{1001 "/foo/bar": true,1002 "/foo/x*zy": false,1003 "/foo/b*r": false,1004 }10051006 for route, valid := range routes {1007 tree := &node{}1008 recv := catchPanic(func() {1009 tree.addRoute(route, nil)1010 })10111012 if recv == nil != valid {1013 t.Fatalf("%s should be %t but got %v", route, valid, recv)1014 }10151016 if rs, ok := recv.(string); recv != nil && (!ok || !strings.HasPrefix(rs, panicMsgPrefix)) {1017 t.Fatalf(`"Expected panic "%s" for route '%s', got "%v"`, panicMsgPrefix, route, recv)1018 }1019 }1020}10211022func TestTreeFindCaseInsensitivePathWithMultipleChildrenAndWildcard(t *testing.T) {1023 tree := &node{}10241025 // Setup routes that create a node with both static children and a wildcard child.1026 // This configuration previously caused a panic ("invalid node type") in1027 // findCaseInsensitivePathRec because it accessed children[0] instead of the1028 // wildcard child (which is always at the end of the children array).1029 // See: https://github.com/gin-gonic/gin/issues/29591030 routes := [...]string{1031 "/aa/aa",1032 "/:bb/aa",1033 }10341035 for _, route := range routes {1036 recv := catchPanic(func() {1037 tree.addRoute(route, fakeHandler(route))1038 })1039 if recv != nil {1040 t.Fatalf("panic inserting route '%s': %v", route, recv)1041 }1042 }10431044 // These lookups previously panicked with "invalid node type" because1045 // findCaseInsensitivePathRec picked children[0] (a static node) instead1046 // of the wildcard child at the end of the array.1047 out, found := tree.findCaseInsensitivePath("/aa", true)1048 if found {1049 t.Errorf("Expected no match for '/aa', but got: %s", string(out))1050 }10511052 out, found = tree.findCaseInsensitivePath("/aa/aa/aa/aa", true)1053 if found {1054 t.Errorf("Expected no match for '/aa/aa/aa/aa', but got: %s", string(out))1055 }10561057 // Case-insensitive lookup should match the static route /aa/aa1058 out, found = tree.findCaseInsensitivePath("/AA/AA", true)1059 if !found {1060 t.Error("Route '/AA/AA' not found via case-insensitive lookup")1061 } else if string(out) != "/aa/aa" {1062 t.Errorf("Wrong result for '/AA/AA': expected '/aa/aa', got: %s", string(out))1063 }1064}10651066func TestTreeFindCaseInsensitivePathWildcardParamAndStaticChild(t *testing.T) {1067 tree := &node{}10681069 // Another variant: param route + static route under same prefix1070 routes := [...]string{1071 "/prefix/:id",1072 "/prefix/xxx",1073 }10741075 for _, route := range routes {1076 recv := catchPanic(func() {1077 tree.addRoute(route, fakeHandler(route))1078 })1079 if recv != nil {1080 t.Fatalf("panic inserting route '%s': %v", route, recv)1081 }1082 }10831084 // Should NOT panic even for paths that don't match any route1085 out, found := tree.findCaseInsensitivePath("/prefix/a/b/c", true)1086 if found {1087 t.Errorf("Expected no match for '/prefix/a/b/c', but got: %s", string(out))1088 }10891090 // Exact match should still work1091 out, found = tree.findCaseInsensitivePath("/prefix/xxx", true)1092 if !found {1093 t.Error("Route '/prefix/xxx' not found")1094 } else if string(out) != "/prefix/xxx" {1095 t.Errorf("Wrong result for '/prefix/xxx': %s", string(out))1096 }10971098 // Case-insensitive match should work1099 out, found = tree.findCaseInsensitivePath("/PREFIX/XXX", true)1100 if !found {1101 t.Error("Route '/PREFIX/XXX' not found via case-insensitive lookup")1102 } else if string(out) != "/prefix/xxx" {1103 t.Errorf("Wrong result for '/PREFIX/XXX': expected '/prefix/xxx', got: %s", string(out))1104 }11051106 // Param route should still match1107 out, found = tree.findCaseInsensitivePath("/prefix/something", true)1108 if !found {1109 t.Error("Route '/prefix/something' not found via param match")1110 } else if string(out) != "/prefix/something" {1111 t.Errorf("Wrong result for '/prefix/something': %s", string(out))1112 }1113}