routes_test.go 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328
  1. // Copyright 2014 Manu Martinez-Almeida. All rights reserved.
  2. // Use of this source code is governed by a MIT style
  3. // license that can be found in the LICENSE file.
  4. package gin
  5. import (
  6. "fmt"
  7. "io/ioutil"
  8. "net/http"
  9. "net/http/httptest"
  10. "os"
  11. "path/filepath"
  12. "testing"
  13. "github.com/stretchr/testify/assert"
  14. )
  15. func performRequest(r http.Handler, method, path string) *httptest.ResponseRecorder {
  16. req, _ := http.NewRequest(method, path, nil)
  17. w := httptest.NewRecorder()
  18. r.ServeHTTP(w, req)
  19. return w
  20. }
  21. func testRouteOK(method string, t *testing.T) {
  22. passed := false
  23. passedAny := false
  24. r := New()
  25. r.Any("/test2", func(c *Context) {
  26. passedAny = true
  27. })
  28. r.Handle(method, "/test", func(c *Context) {
  29. passed = true
  30. })
  31. w := performRequest(r, method, "/test")
  32. assert.True(t, passed)
  33. assert.Equal(t, w.Code, http.StatusOK)
  34. performRequest(r, method, "/test2")
  35. assert.True(t, passedAny)
  36. }
  37. // TestSingleRouteOK tests that POST route is correctly invoked.
  38. func testRouteNotOK(method string, t *testing.T) {
  39. passed := false
  40. router := New()
  41. router.Handle(method, "/test_2", func(c *Context) {
  42. passed = true
  43. })
  44. w := performRequest(router, method, "/test")
  45. assert.False(t, passed)
  46. assert.Equal(t, w.Code, http.StatusNotFound)
  47. }
  48. // TestSingleRouteOK tests that POST route is correctly invoked.
  49. func testRouteNotOK2(method string, t *testing.T) {
  50. passed := false
  51. router := New()
  52. router.HandleMethodNotAllowed = true
  53. var methodRoute string
  54. if method == "POST" {
  55. methodRoute = "GET"
  56. } else {
  57. methodRoute = "POST"
  58. }
  59. router.Handle(methodRoute, "/test", func(c *Context) {
  60. passed = true
  61. })
  62. w := performRequest(router, method, "/test")
  63. assert.False(t, passed)
  64. assert.Equal(t, w.Code, http.StatusMethodNotAllowed)
  65. }
  66. func TestRouterMethod(t *testing.T) {
  67. router := New()
  68. router.PUT("/hey2", func(c *Context) {
  69. c.String(200, "sup2")
  70. })
  71. router.PUT("/hey", func(c *Context) {
  72. c.String(200, "called")
  73. })
  74. router.PUT("/hey3", func(c *Context) {
  75. c.String(200, "sup3")
  76. })
  77. w := performRequest(router, "PUT", "/hey")
  78. assert.Equal(t, w.Code, 200)
  79. assert.Equal(t, w.Body.String(), "called")
  80. }
  81. func TestRouterGroupRouteOK(t *testing.T) {
  82. testRouteOK("GET", t)
  83. testRouteOK("POST", t)
  84. testRouteOK("PUT", t)
  85. testRouteOK("PATCH", t)
  86. testRouteOK("HEAD", t)
  87. testRouteOK("OPTIONS", t)
  88. testRouteOK("DELETE", t)
  89. testRouteOK("CONNECT", t)
  90. testRouteOK("TRACE", t)
  91. }
  92. // TestSingleRouteOK tests that POST route is correctly invoked.
  93. func TestRouteNotOK(t *testing.T) {
  94. testRouteNotOK("GET", t)
  95. testRouteNotOK("POST", t)
  96. testRouteNotOK("PUT", t)
  97. testRouteNotOK("PATCH", t)
  98. testRouteNotOK("HEAD", t)
  99. testRouteNotOK("OPTIONS", t)
  100. testRouteNotOK("DELETE", t)
  101. testRouteNotOK("CONNECT", t)
  102. testRouteNotOK("TRACE", t)
  103. }
  104. // TestSingleRouteOK tests that POST route is correctly invoked.
  105. func TestRouteNotOK2(t *testing.T) {
  106. testRouteNotOK2("GET", t)
  107. testRouteNotOK2("POST", t)
  108. testRouteNotOK2("PUT", t)
  109. testRouteNotOK2("PATCH", t)
  110. testRouteNotOK2("HEAD", t)
  111. testRouteNotOK2("OPTIONS", t)
  112. testRouteNotOK2("DELETE", t)
  113. testRouteNotOK2("CONNECT", t)
  114. testRouteNotOK2("TRACE", t)
  115. }
  116. // TestContextParamsGet tests that a parameter can be parsed from the URL.
  117. func TestRouteParamsByName(t *testing.T) {
  118. name := ""
  119. lastName := ""
  120. wild := ""
  121. router := New()
  122. router.GET("/test/:name/:last_name/*wild", func(c *Context) {
  123. name = c.Params.ByName("name")
  124. lastName = c.Params.ByName("last_name")
  125. var ok bool
  126. wild, ok = c.Params.Get("wild")
  127. assert.True(t, ok)
  128. assert.Equal(t, name, c.Param("name"))
  129. assert.Equal(t, name, c.Param("name"))
  130. assert.Equal(t, lastName, c.Param("last_name"))
  131. assert.Empty(t, c.Param("wtf"))
  132. assert.Empty(t, c.Params.ByName("wtf"))
  133. wtf, ok := c.Params.Get("wtf")
  134. assert.Empty(t, wtf)
  135. assert.False(t, ok)
  136. })
  137. w := performRequest(router, "GET", "/test/john/smith/is/super/great")
  138. assert.Equal(t, w.Code, 200)
  139. assert.Equal(t, name, "john")
  140. assert.Equal(t, lastName, "smith")
  141. assert.Equal(t, wild, "/is/super/great")
  142. }
  143. // TestHandleStaticFile - ensure the static file handles properly
  144. func TestRouteStaticFile(t *testing.T) {
  145. // SETUP file
  146. testRoot, _ := os.Getwd()
  147. f, err := ioutil.TempFile(testRoot, "")
  148. if err != nil {
  149. t.Error(err)
  150. }
  151. defer os.Remove(f.Name())
  152. f.WriteString("Gin Web Framework")
  153. f.Close()
  154. dir, filename := filepath.Split(f.Name())
  155. // SETUP gin
  156. router := New()
  157. router.Static("/using_static", dir)
  158. router.StaticFile("/result", f.Name())
  159. w := performRequest(router, "GET", "/using_static/"+filename)
  160. w2 := performRequest(router, "GET", "/result")
  161. assert.Equal(t, w, w2)
  162. assert.Equal(t, w.Code, 200)
  163. assert.Equal(t, w.Body.String(), "Gin Web Framework")
  164. assert.Equal(t, w.HeaderMap.Get("Content-Type"), "text/plain; charset=utf-8")
  165. w3 := performRequest(router, "HEAD", "/using_static/"+filename)
  166. w4 := performRequest(router, "HEAD", "/result")
  167. assert.Equal(t, w3, w4)
  168. assert.Equal(t, w3.Code, 200)
  169. }
  170. // TestHandleStaticDir - ensure the root/sub dir handles properly
  171. func TestRouteStaticListingDir(t *testing.T) {
  172. router := New()
  173. router.StaticFS("/", Dir("./", true))
  174. w := performRequest(router, "GET", "/")
  175. assert.Equal(t, w.Code, 200)
  176. assert.Contains(t, w.Body.String(), "gin.go")
  177. assert.Equal(t, w.HeaderMap.Get("Content-Type"), "text/html; charset=utf-8")
  178. }
  179. // TestHandleHeadToDir - ensure the root/sub dir handles properly
  180. func TestRouteStaticNoListing(t *testing.T) {
  181. router := New()
  182. router.Static("/", "./")
  183. w := performRequest(router, "GET", "/")
  184. assert.Equal(t, w.Code, 404)
  185. assert.NotContains(t, w.Body.String(), "gin.go")
  186. }
  187. func TestRouterMiddlewareAndStatic(t *testing.T) {
  188. router := New()
  189. static := router.Group("/", func(c *Context) {
  190. c.Writer.Header().Add("Last-Modified", "Mon, 02 Jan 2006 15:04:05 MST")
  191. c.Writer.Header().Add("Expires", "Mon, 02 Jan 2006 15:04:05 MST")
  192. c.Writer.Header().Add("X-GIN", "Gin Framework")
  193. })
  194. static.Static("/", "./")
  195. w := performRequest(router, "GET", "/gin.go")
  196. assert.Equal(t, w.Code, 200)
  197. assert.Contains(t, w.Body.String(), "package gin")
  198. assert.Equal(t, w.HeaderMap.Get("Content-Type"), "text/plain; charset=utf-8")
  199. assert.NotEqual(t, w.HeaderMap.Get("Last-Modified"), "Mon, 02 Jan 2006 15:04:05 MST")
  200. assert.Equal(t, w.HeaderMap.Get("Expires"), "Mon, 02 Jan 2006 15:04:05 MST")
  201. assert.Equal(t, w.HeaderMap.Get("x-GIN"), "Gin Framework")
  202. }
  203. func TestRouteNotAllowedEnabled(t *testing.T) {
  204. router := New()
  205. router.HandleMethodNotAllowed = true
  206. router.POST("/path", func(c *Context) {})
  207. w := performRequest(router, "GET", "/path")
  208. assert.Equal(t, w.Code, http.StatusMethodNotAllowed)
  209. router.NoMethod(func(c *Context) {
  210. c.String(http.StatusTeapot, "responseText")
  211. })
  212. w = performRequest(router, "GET", "/path")
  213. assert.Equal(t, w.Body.String(), "responseText")
  214. assert.Equal(t, w.Code, http.StatusTeapot)
  215. }
  216. func TestRouteNotAllowedDisabled(t *testing.T) {
  217. router := New()
  218. router.HandleMethodNotAllowed = false
  219. router.POST("/path", func(c *Context) {})
  220. w := performRequest(router, "GET", "/path")
  221. assert.Equal(t, w.Code, 404)
  222. router.NoMethod(func(c *Context) {
  223. c.String(http.StatusTeapot, "responseText")
  224. })
  225. w = performRequest(router, "GET", "/path")
  226. assert.Equal(t, w.Body.String(), "404 page not found")
  227. assert.Equal(t, w.Code, 404)
  228. }
  229. func TestRouterNotFound(t *testing.T) {
  230. router := New()
  231. router.RedirectFixedPath = true
  232. router.GET("/path", func(c *Context) {})
  233. router.GET("/dir/", func(c *Context) {})
  234. router.GET("/", func(c *Context) {})
  235. testRoutes := []struct {
  236. route string
  237. code int
  238. header string
  239. }{
  240. {"/path/", 301, "map[Location:[/path]]"}, // TSR -/
  241. {"/dir", 301, "map[Location:[/dir/]]"}, // TSR +/
  242. {"", 301, "map[Location:[/]]"}, // TSR +/
  243. {"/PATH", 301, "map[Location:[/path]]"}, // Fixed Case
  244. {"/DIR/", 301, "map[Location:[/dir/]]"}, // Fixed Case
  245. {"/PATH/", 301, "map[Location:[/path]]"}, // Fixed Case -/
  246. {"/DIR", 301, "map[Location:[/dir/]]"}, // Fixed Case +/
  247. {"/../path", 301, "map[Location:[/path]]"}, // CleanPath
  248. {"/nope", 404, ""}, // NotFound
  249. }
  250. for _, tr := range testRoutes {
  251. w := performRequest(router, "GET", tr.route)
  252. assert.Equal(t, w.Code, tr.code)
  253. if w.Code != 404 {
  254. assert.Equal(t, fmt.Sprint(w.Header()), tr.header)
  255. }
  256. }
  257. // Test custom not found handler
  258. var notFound bool
  259. router.NoRoute(func(c *Context) {
  260. c.AbortWithStatus(404)
  261. notFound = true
  262. })
  263. w := performRequest(router, "GET", "/nope")
  264. assert.Equal(t, w.Code, 404)
  265. assert.True(t, notFound)
  266. // Test other method than GET (want 307 instead of 301)
  267. router.PATCH("/path", func(c *Context) {})
  268. w = performRequest(router, "PATCH", "/path/")
  269. assert.Equal(t, w.Code, 307)
  270. assert.Equal(t, fmt.Sprint(w.Header()), "map[Location:[/path]]")
  271. // Test special case where no node for the prefix "/" exists
  272. router = New()
  273. router.GET("/a", func(c *Context) {})
  274. w = performRequest(router, "GET", "/")
  275. assert.Equal(t, w.Code, 404)
  276. }