routes_test.go 8.4 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309
  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 TestRouterGroupRouteOK(t *testing.T) {
  67. testRouteOK("GET", t)
  68. testRouteOK("POST", t)
  69. testRouteOK("PUT", t)
  70. testRouteOK("PATCH", t)
  71. testRouteOK("HEAD", t)
  72. testRouteOK("OPTIONS", t)
  73. testRouteOK("DELETE", t)
  74. testRouteOK("CONNECT", t)
  75. testRouteOK("TRACE", t)
  76. }
  77. // TestSingleRouteOK tests that POST route is correctly invoked.
  78. func TestRouteNotOK(t *testing.T) {
  79. testRouteNotOK("GET", t)
  80. testRouteNotOK("POST", t)
  81. testRouteNotOK("PUT", t)
  82. testRouteNotOK("PATCH", t)
  83. testRouteNotOK("HEAD", t)
  84. testRouteNotOK("OPTIONS", t)
  85. testRouteNotOK("DELETE", t)
  86. testRouteNotOK("CONNECT", t)
  87. testRouteNotOK("TRACE", t)
  88. }
  89. // TestSingleRouteOK tests that POST route is correctly invoked.
  90. func TestRouteNotOK2(t *testing.T) {
  91. testRouteNotOK2("GET", t)
  92. testRouteNotOK2("POST", t)
  93. testRouteNotOK2("PUT", t)
  94. testRouteNotOK2("PATCH", t)
  95. testRouteNotOK2("HEAD", t)
  96. testRouteNotOK2("OPTIONS", t)
  97. testRouteNotOK2("DELETE", t)
  98. testRouteNotOK2("CONNECT", t)
  99. testRouteNotOK2("TRACE", t)
  100. }
  101. // TestContextParamsGet tests that a parameter can be parsed from the URL.
  102. func TestRouteParamsByName(t *testing.T) {
  103. name := ""
  104. lastName := ""
  105. wild := ""
  106. router := New()
  107. router.GET("/test/:name/:last_name/*wild", func(c *Context) {
  108. name = c.Params.ByName("name")
  109. lastName = c.Params.ByName("last_name")
  110. var ok bool
  111. wild, ok = c.Params.Get("wild")
  112. assert.True(t, ok)
  113. assert.Equal(t, name, c.Param("name"))
  114. assert.Equal(t, name, c.Param("name"))
  115. assert.Equal(t, lastName, c.Param("last_name"))
  116. assert.Empty(t, c.Param("wtf"))
  117. assert.Empty(t, c.Params.ByName("wtf"))
  118. wtf, ok := c.Params.Get("wtf")
  119. assert.Empty(t, wtf)
  120. assert.False(t, ok)
  121. })
  122. w := performRequest(router, "GET", "/test/john/smith/is/super/great")
  123. assert.Equal(t, w.Code, 200)
  124. assert.Equal(t, name, "john")
  125. assert.Equal(t, lastName, "smith")
  126. assert.Equal(t, wild, "/is/super/great")
  127. }
  128. // TestHandleStaticFile - ensure the static file handles properly
  129. func TestRouteStaticFile(t *testing.T) {
  130. // SETUP file
  131. testRoot, _ := os.Getwd()
  132. f, err := ioutil.TempFile(testRoot, "")
  133. if err != nil {
  134. t.Error(err)
  135. }
  136. defer os.Remove(f.Name())
  137. f.WriteString("Gin Web Framework")
  138. f.Close()
  139. dir, filename := filepath.Split(f.Name())
  140. // SETUP gin
  141. router := New()
  142. router.Static("/using_static", dir)
  143. router.StaticFile("/result", f.Name())
  144. w := performRequest(router, "GET", "/using_static/"+filename)
  145. w2 := performRequest(router, "GET", "/result")
  146. assert.Equal(t, w, w2)
  147. assert.Equal(t, w.Code, 200)
  148. assert.Equal(t, w.Body.String(), "Gin Web Framework")
  149. assert.Equal(t, w.HeaderMap.Get("Content-Type"), "text/plain; charset=utf-8")
  150. w3 := performRequest(router, "HEAD", "/using_static/"+filename)
  151. w4 := performRequest(router, "HEAD", "/result")
  152. assert.Equal(t, w3, w4)
  153. assert.Equal(t, w3.Code, 200)
  154. }
  155. // TestHandleStaticDir - ensure the root/sub dir handles properly
  156. func TestRouteStaticListingDir(t *testing.T) {
  157. router := New()
  158. router.StaticFS("/", Dir("./", true))
  159. w := performRequest(router, "GET", "/")
  160. assert.Equal(t, w.Code, 200)
  161. assert.Contains(t, w.Body.String(), "gin.go")
  162. assert.Equal(t, w.HeaderMap.Get("Content-Type"), "text/html; charset=utf-8")
  163. }
  164. // TestHandleHeadToDir - ensure the root/sub dir handles properly
  165. func TestRouteStaticNoListing(t *testing.T) {
  166. router := New()
  167. router.Static("/", "./")
  168. w := performRequest(router, "GET", "/")
  169. assert.Equal(t, w.Code, 404)
  170. assert.NotContains(t, w.Body.String(), "gin.go")
  171. }
  172. func TestRouterMiddlewareAndStatic(t *testing.T) {
  173. router := New()
  174. static := router.Group("/", func(c *Context) {
  175. c.Writer.Header().Add("Last-Modified", "Mon, 02 Jan 2006 15:04:05 MST")
  176. c.Writer.Header().Add("Expires", "Mon, 02 Jan 2006 15:04:05 MST")
  177. c.Writer.Header().Add("X-GIN", "Gin Framework")
  178. })
  179. static.Static("/", "./")
  180. w := performRequest(router, "GET", "/gin.go")
  181. assert.Equal(t, w.Code, 200)
  182. assert.Contains(t, w.Body.String(), "package gin")
  183. assert.Equal(t, w.HeaderMap.Get("Content-Type"), "text/plain; charset=utf-8")
  184. assert.NotEqual(t, w.HeaderMap.Get("Last-Modified"), "Mon, 02 Jan 2006 15:04:05 MST")
  185. assert.Equal(t, w.HeaderMap.Get("Expires"), "Mon, 02 Jan 2006 15:04:05 MST")
  186. assert.Equal(t, w.HeaderMap.Get("x-GIN"), "Gin Framework")
  187. }
  188. func TestRouteNotAllowedEnabled(t *testing.T) {
  189. router := New()
  190. router.HandleMethodNotAllowed = true
  191. router.POST("/path", func(c *Context) {})
  192. w := performRequest(router, "GET", "/path")
  193. assert.Equal(t, w.Code, http.StatusMethodNotAllowed)
  194. router.NoMethod(func(c *Context) {
  195. c.String(http.StatusTeapot, "responseText")
  196. })
  197. w = performRequest(router, "GET", "/path")
  198. assert.Equal(t, w.Body.String(), "responseText")
  199. assert.Equal(t, w.Code, http.StatusTeapot)
  200. }
  201. func TestRouteNotAllowedDisabled(t *testing.T) {
  202. router := New()
  203. router.HandleMethodNotAllowed = false
  204. router.POST("/path", func(c *Context) {})
  205. w := performRequest(router, "GET", "/path")
  206. assert.Equal(t, w.Code, 404)
  207. router.NoMethod(func(c *Context) {
  208. c.String(http.StatusTeapot, "responseText")
  209. })
  210. w = performRequest(router, "GET", "/path")
  211. assert.Equal(t, w.Body.String(), "404 page not found")
  212. assert.Equal(t, w.Code, 404)
  213. }
  214. func TestRouterNotFound(t *testing.T) {
  215. router := New()
  216. router.RedirectFixedPath = true
  217. router.GET("/path", func(c *Context) {})
  218. router.GET("/dir/", func(c *Context) {})
  219. router.GET("/", func(c *Context) {})
  220. testRoutes := []struct {
  221. route string
  222. code int
  223. header string
  224. }{
  225. {"/path/", 301, "map[Location:[/path]]"}, // TSR -/
  226. {"/dir", 301, "map[Location:[/dir/]]"}, // TSR +/
  227. {"", 301, "map[Location:[/]]"}, // TSR +/
  228. {"/PATH", 301, "map[Location:[/path]]"}, // Fixed Case
  229. {"/DIR/", 301, "map[Location:[/dir/]]"}, // Fixed Case
  230. {"/PATH/", 301, "map[Location:[/path]]"}, // Fixed Case -/
  231. {"/DIR", 301, "map[Location:[/dir/]]"}, // Fixed Case +/
  232. {"/../path", 301, "map[Location:[/path]]"}, // CleanPath
  233. {"/nope", 404, ""}, // NotFound
  234. }
  235. for _, tr := range testRoutes {
  236. w := performRequest(router, "GET", tr.route)
  237. assert.Equal(t, w.Code, tr.code)
  238. if w.Code != 404 {
  239. assert.Equal(t, fmt.Sprint(w.Header()), tr.header)
  240. }
  241. }
  242. // Test custom not found handler
  243. var notFound bool
  244. router.NoRoute(func(c *Context) {
  245. c.AbortWithStatus(404)
  246. notFound = true
  247. })
  248. w := performRequest(router, "GET", "/nope")
  249. assert.Equal(t, w.Code, 404)
  250. assert.True(t, notFound)
  251. // Test other method than GET (want 307 instead of 301)
  252. router.PATCH("/path", func(c *Context) {})
  253. w = performRequest(router, "PATCH", "/path/")
  254. assert.Equal(t, w.Code, 307)
  255. assert.Equal(t, fmt.Sprint(w.Header()), "map[Location:[/path]]")
  256. // Test special case where no node for the prefix "/" exists
  257. router = New()
  258. router.GET("/a", func(c *Context) {})
  259. w = performRequest(router, "GET", "/")
  260. assert.Equal(t, w.Code, 404)
  261. }