tree_test.go 16 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655
  1. // Copyright 2013 Julien Schmidt. All rights reserved.
  2. // Use of this source code is governed by a BSD-style license that can be found
  3. // at https://github.com/julienschmidt/httprouter/blob/master/LICENSE
  4. package gin
  5. import (
  6. "reflect"
  7. "strings"
  8. "testing"
  9. )
  10. // Used as a workaround since we can't compare functions or their addressses
  11. var fakeHandlerValue string
  12. func fakeHandler(val string) HandlersChain {
  13. return HandlersChain{func(c *Context) {
  14. fakeHandlerValue = val
  15. }}
  16. }
  17. type testRequests []struct {
  18. path string
  19. nilHandler bool
  20. route string
  21. ps Params
  22. }
  23. func checkRequests(t *testing.T, tree *node, requests testRequests, unescapes ...bool) {
  24. unescape := false
  25. if len(unescapes) >= 1 {
  26. unescape = unescapes[0]
  27. }
  28. for _, request := range requests {
  29. handler, ps, _ := tree.getValue(request.path, nil, unescape)
  30. if handler == nil {
  31. if !request.nilHandler {
  32. t.Errorf("handle mismatch for route '%s': Expected non-nil handle", request.path)
  33. }
  34. } else if request.nilHandler {
  35. t.Errorf("handle mismatch for route '%s': Expected nil handle", request.path)
  36. } else {
  37. handler[0](nil)
  38. if fakeHandlerValue != request.route {
  39. t.Errorf("handle mismatch for route '%s': Wrong handle (%s != %s)", request.path, fakeHandlerValue, request.route)
  40. }
  41. }
  42. if !reflect.DeepEqual(ps, request.ps) {
  43. t.Errorf("Params mismatch for route '%s'", request.path)
  44. }
  45. }
  46. }
  47. func checkPriorities(t *testing.T, n *node) uint32 {
  48. var prio uint32
  49. for i := range n.children {
  50. prio += checkPriorities(t, n.children[i])
  51. }
  52. if n.handlers != nil {
  53. prio++
  54. }
  55. if n.priority != prio {
  56. t.Errorf(
  57. "priority mismatch for node '%s': is %d, should be %d",
  58. n.path, n.priority, prio,
  59. )
  60. }
  61. return prio
  62. }
  63. func checkMaxParams(t *testing.T, n *node) uint8 {
  64. var maxParams uint8
  65. for i := range n.children {
  66. params := checkMaxParams(t, n.children[i])
  67. if params > maxParams {
  68. maxParams = params
  69. }
  70. }
  71. if n.nType > root && !n.wildChild {
  72. maxParams++
  73. }
  74. if n.maxParams != maxParams {
  75. t.Errorf(
  76. "maxParams mismatch for node '%s': is %d, should be %d",
  77. n.path, n.maxParams, maxParams,
  78. )
  79. }
  80. return maxParams
  81. }
  82. func TestCountParams(t *testing.T) {
  83. if countParams("/path/:param1/static/*catch-all") != 2 {
  84. t.Fail()
  85. }
  86. if countParams(strings.Repeat("/:param", 256)) != 255 {
  87. t.Fail()
  88. }
  89. }
  90. func TestTreeAddAndGet(t *testing.T) {
  91. tree := &node{}
  92. routes := [...]string{
  93. "/hi",
  94. "/contact",
  95. "/co",
  96. "/c",
  97. "/a",
  98. "/ab",
  99. "/doc/",
  100. "/doc/go_faq.html",
  101. "/doc/go1.html",
  102. "/α",
  103. "/β",
  104. }
  105. for _, route := range routes {
  106. tree.addRoute(route, fakeHandler(route))
  107. }
  108. checkRequests(t, tree, testRequests{
  109. {"/a", false, "/a", nil},
  110. {"/", true, "", nil},
  111. {"/hi", false, "/hi", nil},
  112. {"/contact", false, "/contact", nil},
  113. {"/co", false, "/co", nil},
  114. {"/con", true, "", nil}, // key mismatch
  115. {"/cona", true, "", nil}, // key mismatch
  116. {"/no", true, "", nil}, // no matching child
  117. {"/ab", false, "/ab", nil},
  118. {"/α", false, "/α", nil},
  119. {"/β", false, "/β", nil},
  120. })
  121. checkPriorities(t, tree)
  122. checkMaxParams(t, tree)
  123. }
  124. func TestTreeWildcard(t *testing.T) {
  125. tree := &node{}
  126. routes := [...]string{
  127. "/",
  128. "/cmd/:tool/:sub",
  129. "/cmd/:tool/",
  130. "/src/*filepath",
  131. "/search/",
  132. "/search/:query",
  133. "/user_:name",
  134. "/user_:name/about",
  135. "/files/:dir/*filepath",
  136. "/doc/",
  137. "/doc/go_faq.html",
  138. "/doc/go1.html",
  139. "/info/:user/public",
  140. "/info/:user/project/:project",
  141. }
  142. for _, route := range routes {
  143. tree.addRoute(route, fakeHandler(route))
  144. }
  145. checkRequests(t, tree, testRequests{
  146. {"/", false, "/", nil},
  147. {"/cmd/test/", false, "/cmd/:tool/", Params{Param{"tool", "test"}}},
  148. {"/cmd/test", true, "", Params{Param{"tool", "test"}}},
  149. {"/cmd/test/3", false, "/cmd/:tool/:sub", Params{Param{"tool", "test"}, Param{"sub", "3"}}},
  150. {"/src/", false, "/src/*filepath", Params{Param{"filepath", "/"}}},
  151. {"/src/some/file.png", false, "/src/*filepath", Params{Param{"filepath", "/some/file.png"}}},
  152. {"/search/", false, "/search/", nil},
  153. {"/search/someth!ng+in+ünìcodé", false, "/search/:query", Params{Param{"query", "someth!ng+in+ünìcodé"}}},
  154. {"/search/someth!ng+in+ünìcodé/", true, "", Params{Param{"query", "someth!ng+in+ünìcodé"}}},
  155. {"/user_gopher", false, "/user_:name", Params{Param{"name", "gopher"}}},
  156. {"/user_gopher/about", false, "/user_:name/about", Params{Param{"name", "gopher"}}},
  157. {"/files/js/inc/framework.js", false, "/files/:dir/*filepath", Params{Param{"dir", "js"}, Param{"filepath", "/inc/framework.js"}}},
  158. {"/info/gordon/public", false, "/info/:user/public", Params{Param{"user", "gordon"}}},
  159. {"/info/gordon/project/go", false, "/info/:user/project/:project", Params{Param{"user", "gordon"}, Param{"project", "go"}}},
  160. })
  161. checkPriorities(t, tree)
  162. checkMaxParams(t, tree)
  163. }
  164. func TestUnescapeParameters(t *testing.T) {
  165. tree := &node{}
  166. routes := [...]string{
  167. "/",
  168. "/cmd/:tool/:sub",
  169. "/cmd/:tool/",
  170. "/src/*filepath",
  171. "/search/:query",
  172. "/files/:dir/*filepath",
  173. "/info/:user/project/:project",
  174. "/info/:user",
  175. }
  176. for _, route := range routes {
  177. tree.addRoute(route, fakeHandler(route))
  178. }
  179. unescape := true
  180. checkRequests(t, tree, testRequests{
  181. {"/", false, "/", nil},
  182. {"/cmd/test/", false, "/cmd/:tool/", Params{Param{"tool", "test"}}},
  183. {"/cmd/test", true, "", Params{Param{"tool", "test"}}},
  184. {"/src/some/file.png", false, "/src/*filepath", Params{Param{"filepath", "/some/file.png"}}},
  185. {"/src/some/file+test.png", false, "/src/*filepath", Params{Param{"filepath", "/some/file test.png"}}},
  186. {"/src/some/file++++%%%%test.png", false, "/src/*filepath", Params{Param{"filepath", "/some/file++++%%%%test.png"}}},
  187. {"/src/some/file%2Ftest.png", false, "/src/*filepath", Params{Param{"filepath", "/some/file/test.png"}}},
  188. {"/search/someth!ng+in+ünìcodé", false, "/search/:query", Params{Param{"query", "someth!ng in ünìcodé"}}},
  189. {"/info/gordon/project/go", false, "/info/:user/project/:project", Params{Param{"user", "gordon"}, Param{"project", "go"}}},
  190. {"/info/slash%2Fgordon", false, "/info/:user", Params{Param{"user", "slash/gordon"}}},
  191. {"/info/slash%2Fgordon/project/Project%20%231", false, "/info/:user/project/:project", Params{Param{"user", "slash/gordon"}, Param{"project", "Project #1"}}},
  192. {"/info/slash%%%%", false, "/info/:user", Params{Param{"user", "slash%%%%"}}},
  193. {"/info/slash%%%%2Fgordon/project/Project%%%%20%231", false, "/info/:user/project/:project", Params{Param{"user", "slash%%%%2Fgordon"}, Param{"project", "Project%%%%20%231"}}},
  194. }, unescape)
  195. checkPriorities(t, tree)
  196. checkMaxParams(t, tree)
  197. }
  198. func catchPanic(testFunc func()) (recv interface{}) {
  199. defer func() {
  200. recv = recover()
  201. }()
  202. testFunc()
  203. return
  204. }
  205. type testRoute struct {
  206. path string
  207. conflict bool
  208. }
  209. func testRoutes(t *testing.T, routes []testRoute) {
  210. tree := &node{}
  211. for _, route := range routes {
  212. recv := catchPanic(func() {
  213. tree.addRoute(route.path, nil)
  214. })
  215. if route.conflict {
  216. if recv == nil {
  217. t.Errorf("no panic for conflicting route '%s'", route.path)
  218. }
  219. } else if recv != nil {
  220. t.Errorf("unexpected panic for route '%s': %v", route.path, recv)
  221. }
  222. }
  223. }
  224. func TestTreeWildcardConflict(t *testing.T) {
  225. routes := []testRoute{
  226. {"/cmd/:tool/:sub", false},
  227. {"/cmd/vet", true},
  228. {"/src/*filepath", false},
  229. {"/src/*filepathx", true},
  230. {"/src/", true},
  231. {"/src1/", false},
  232. {"/src1/*filepath", true},
  233. {"/src2*filepath", true},
  234. {"/search/:query", false},
  235. {"/search/invalid", true},
  236. {"/user_:name", false},
  237. {"/user_x", true},
  238. {"/user_:name", false},
  239. {"/id:id", false},
  240. {"/id/:id", true},
  241. }
  242. testRoutes(t, routes)
  243. }
  244. func TestTreeChildConflict(t *testing.T) {
  245. routes := []testRoute{
  246. {"/cmd/vet", false},
  247. {"/cmd/:tool/:sub", true},
  248. {"/src/AUTHORS", false},
  249. {"/src/*filepath", true},
  250. {"/user_x", false},
  251. {"/user_:name", true},
  252. {"/id/:id", false},
  253. {"/id:id", true},
  254. {"/:id", true},
  255. {"/*filepath", true},
  256. }
  257. testRoutes(t, routes)
  258. }
  259. func TestTreeDupliatePath(t *testing.T) {
  260. tree := &node{}
  261. routes := [...]string{
  262. "/",
  263. "/doc/",
  264. "/src/*filepath",
  265. "/search/:query",
  266. "/user_:name",
  267. }
  268. for _, route := range routes {
  269. recv := catchPanic(func() {
  270. tree.addRoute(route, fakeHandler(route))
  271. })
  272. if recv != nil {
  273. t.Fatalf("panic inserting route '%s': %v", route, recv)
  274. }
  275. // Add again
  276. recv = catchPanic(func() {
  277. tree.addRoute(route, nil)
  278. })
  279. if recv == nil {
  280. t.Fatalf("no panic while inserting duplicate route '%s", route)
  281. }
  282. }
  283. checkRequests(t, tree, testRequests{
  284. {"/", false, "/", nil},
  285. {"/doc/", false, "/doc/", nil},
  286. {"/src/some/file.png", false, "/src/*filepath", Params{Param{"filepath", "/some/file.png"}}},
  287. {"/search/someth!ng+in+ünìcodé", false, "/search/:query", Params{Param{"query", "someth!ng+in+ünìcodé"}}},
  288. {"/user_gopher", false, "/user_:name", Params{Param{"name", "gopher"}}},
  289. })
  290. }
  291. func TestEmptyWildcardName(t *testing.T) {
  292. tree := &node{}
  293. routes := [...]string{
  294. "/user:",
  295. "/user:/",
  296. "/cmd/:/",
  297. "/src/*",
  298. }
  299. for _, route := range routes {
  300. recv := catchPanic(func() {
  301. tree.addRoute(route, nil)
  302. })
  303. if recv == nil {
  304. t.Fatalf("no panic while inserting route with empty wildcard name '%s", route)
  305. }
  306. }
  307. }
  308. func TestTreeCatchAllConflict(t *testing.T) {
  309. routes := []testRoute{
  310. {"/src/*filepath/x", true},
  311. {"/src2/", false},
  312. {"/src2/*filepath/x", true},
  313. }
  314. testRoutes(t, routes)
  315. }
  316. func TestTreeCatchAllConflictRoot(t *testing.T) {
  317. routes := []testRoute{
  318. {"/", false},
  319. {"/*filepath", true},
  320. }
  321. testRoutes(t, routes)
  322. }
  323. func TestTreeDoubleWildcard(t *testing.T) {
  324. const panicMsg = "only one wildcard per path segment is allowed"
  325. routes := [...]string{
  326. "/:foo:bar",
  327. "/:foo:bar/",
  328. "/:foo*bar",
  329. }
  330. for _, route := range routes {
  331. tree := &node{}
  332. recv := catchPanic(func() {
  333. tree.addRoute(route, nil)
  334. })
  335. if rs, ok := recv.(string); !ok || !strings.HasPrefix(rs, panicMsg) {
  336. t.Fatalf(`"Expected panic "%s" for route '%s', got "%v"`, panicMsg, route, recv)
  337. }
  338. }
  339. }
  340. /*func TestTreeDuplicateWildcard(t *testing.T) {
  341. tree := &node{}
  342. routes := [...]string{
  343. "/:id/:name/:id",
  344. }
  345. for _, route := range routes {
  346. ...
  347. }
  348. }*/
  349. func TestTreeTrailingSlashRedirect(t *testing.T) {
  350. tree := &node{}
  351. routes := [...]string{
  352. "/hi",
  353. "/b/",
  354. "/search/:query",
  355. "/cmd/:tool/",
  356. "/src/*filepath",
  357. "/x",
  358. "/x/y",
  359. "/y/",
  360. "/y/z",
  361. "/0/:id",
  362. "/0/:id/1",
  363. "/1/:id/",
  364. "/1/:id/2",
  365. "/aa",
  366. "/a/",
  367. "/admin",
  368. "/admin/:category",
  369. "/admin/:category/:page",
  370. "/doc",
  371. "/doc/go_faq.html",
  372. "/doc/go1.html",
  373. "/no/a",
  374. "/no/b",
  375. "/api/hello/:name",
  376. }
  377. for _, route := range routes {
  378. recv := catchPanic(func() {
  379. tree.addRoute(route, fakeHandler(route))
  380. })
  381. if recv != nil {
  382. t.Fatalf("panic inserting route '%s': %v", route, recv)
  383. }
  384. }
  385. tsrRoutes := [...]string{
  386. "/hi/",
  387. "/b",
  388. "/search/gopher/",
  389. "/cmd/vet",
  390. "/src",
  391. "/x/",
  392. "/y",
  393. "/0/go/",
  394. "/1/go",
  395. "/a",
  396. "/admin/",
  397. "/admin/config/",
  398. "/admin/config/permissions/",
  399. "/doc/",
  400. }
  401. for _, route := range tsrRoutes {
  402. handler, _, tsr := tree.getValue(route, nil, false)
  403. if handler != nil {
  404. t.Fatalf("non-nil handler for TSR route '%s", route)
  405. } else if !tsr {
  406. t.Errorf("expected TSR recommendation for route '%s'", route)
  407. }
  408. }
  409. noTsrRoutes := [...]string{
  410. "/",
  411. "/no",
  412. "/no/",
  413. "/_",
  414. "/_/",
  415. "/api/world/abc",
  416. }
  417. for _, route := range noTsrRoutes {
  418. handler, _, tsr := tree.getValue(route, nil, false)
  419. if handler != nil {
  420. t.Fatalf("non-nil handler for No-TSR route '%s", route)
  421. } else if tsr {
  422. t.Errorf("expected no TSR recommendation for route '%s'", route)
  423. }
  424. }
  425. }
  426. func TestTreeRootTrailingSlashRedirect(t *testing.T) {
  427. tree := &node{}
  428. recv := catchPanic(func() {
  429. tree.addRoute("/:test", fakeHandler("/:test"))
  430. })
  431. if recv != nil {
  432. t.Fatalf("panic inserting test route: %v", recv)
  433. }
  434. handler, _, tsr := tree.getValue("/", nil, false)
  435. if handler != nil {
  436. t.Fatalf("non-nil handler")
  437. } else if tsr {
  438. t.Errorf("expected no TSR recommendation")
  439. }
  440. }
  441. func TestTreeFindCaseInsensitivePath(t *testing.T) {
  442. tree := &node{}
  443. routes := [...]string{
  444. "/hi",
  445. "/b/",
  446. "/ABC/",
  447. "/search/:query",
  448. "/cmd/:tool/",
  449. "/src/*filepath",
  450. "/x",
  451. "/x/y",
  452. "/y/",
  453. "/y/z",
  454. "/0/:id",
  455. "/0/:id/1",
  456. "/1/:id/",
  457. "/1/:id/2",
  458. "/aa",
  459. "/a/",
  460. "/doc",
  461. "/doc/go_faq.html",
  462. "/doc/go1.html",
  463. "/doc/go/away",
  464. "/no/a",
  465. "/no/b",
  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. }
  474. }
  475. // Check out == in for all registered routes
  476. // With fixTrailingSlash = true
  477. for _, route := range routes {
  478. out, found := tree.findCaseInsensitivePath(route, true)
  479. if !found {
  480. t.Errorf("Route '%s' not found!", route)
  481. } else if string(out) != route {
  482. t.Errorf("Wrong result for route '%s': %s", route, string(out))
  483. }
  484. }
  485. // With fixTrailingSlash = false
  486. for _, route := range routes {
  487. out, found := tree.findCaseInsensitivePath(route, false)
  488. if !found {
  489. t.Errorf("Route '%s' not found!", route)
  490. } else if string(out) != route {
  491. t.Errorf("Wrong result for route '%s': %s", route, string(out))
  492. }
  493. }
  494. tests := []struct {
  495. in string
  496. out string
  497. found bool
  498. slash bool
  499. }{
  500. {"/HI", "/hi", true, false},
  501. {"/HI/", "/hi", true, true},
  502. {"/B", "/b/", true, true},
  503. {"/B/", "/b/", true, false},
  504. {"/abc", "/ABC/", true, true},
  505. {"/abc/", "/ABC/", true, false},
  506. {"/aBc", "/ABC/", true, true},
  507. {"/aBc/", "/ABC/", true, false},
  508. {"/abC", "/ABC/", true, true},
  509. {"/abC/", "/ABC/", true, false},
  510. {"/SEARCH/QUERY", "/search/QUERY", true, false},
  511. {"/SEARCH/QUERY/", "/search/QUERY", true, true},
  512. {"/CMD/TOOL/", "/cmd/TOOL/", true, false},
  513. {"/CMD/TOOL", "/cmd/TOOL/", true, true},
  514. {"/SRC/FILE/PATH", "/src/FILE/PATH", true, false},
  515. {"/x/Y", "/x/y", true, false},
  516. {"/x/Y/", "/x/y", true, true},
  517. {"/X/y", "/x/y", true, false},
  518. {"/X/y/", "/x/y", true, true},
  519. {"/X/Y", "/x/y", true, false},
  520. {"/X/Y/", "/x/y", true, true},
  521. {"/Y/", "/y/", true, false},
  522. {"/Y", "/y/", true, true},
  523. {"/Y/z", "/y/z", true, false},
  524. {"/Y/z/", "/y/z", true, true},
  525. {"/Y/Z", "/y/z", true, false},
  526. {"/Y/Z/", "/y/z", true, true},
  527. {"/y/Z", "/y/z", true, false},
  528. {"/y/Z/", "/y/z", true, true},
  529. {"/Aa", "/aa", true, false},
  530. {"/Aa/", "/aa", true, true},
  531. {"/AA", "/aa", true, false},
  532. {"/AA/", "/aa", true, true},
  533. {"/aA", "/aa", true, false},
  534. {"/aA/", "/aa", true, true},
  535. {"/A/", "/a/", true, false},
  536. {"/A", "/a/", true, true},
  537. {"/DOC", "/doc", true, false},
  538. {"/DOC/", "/doc", true, true},
  539. {"/NO", "", false, true},
  540. {"/DOC/GO", "", false, true},
  541. }
  542. // With fixTrailingSlash = true
  543. for _, test := range tests {
  544. out, found := tree.findCaseInsensitivePath(test.in, true)
  545. if found != test.found || (found && (string(out) != test.out)) {
  546. t.Errorf("Wrong result for '%s': got %s, %t; want %s, %t",
  547. test.in, string(out), found, test.out, test.found)
  548. return
  549. }
  550. }
  551. // With fixTrailingSlash = false
  552. for _, test := range tests {
  553. out, found := tree.findCaseInsensitivePath(test.in, false)
  554. if test.slash {
  555. if found { // test needs a trailingSlash fix. It must not be found!
  556. t.Errorf("Found without fixTrailingSlash: %s; got %s", test.in, string(out))
  557. }
  558. } else {
  559. if found != test.found || (found && (string(out) != test.out)) {
  560. t.Errorf("Wrong result for '%s': got %s, %t; want %s, %t",
  561. test.in, string(out), found, test.out, test.found)
  562. return
  563. }
  564. }
  565. }
  566. }
  567. func TestTreeInvalidNodeType(t *testing.T) {
  568. const panicMsg = "invalid node type"
  569. tree := &node{}
  570. tree.addRoute("/", fakeHandler("/"))
  571. tree.addRoute("/:page", fakeHandler("/:page"))
  572. // set invalid node type
  573. tree.children[0].nType = 42
  574. // normal lookup
  575. recv := catchPanic(func() {
  576. tree.getValue("/test", nil, false)
  577. })
  578. if rs, ok := recv.(string); !ok || rs != panicMsg {
  579. t.Fatalf("Expected panic '"+panicMsg+"', got '%v'", recv)
  580. }
  581. // case-insensitive lookup
  582. recv = catchPanic(func() {
  583. tree.findCaseInsensitivePath("/test", true)
  584. })
  585. if rs, ok := recv.(string); !ok || rs != panicMsg {
  586. t.Fatalf("Expected panic '"+panicMsg+"', got '%v'", recv)
  587. }
  588. }