routes_test.go 7.3 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268
  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"
  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. var methodRoute string
  53. if method == "POST" {
  54. methodRoute = "GET"
  55. } else {
  56. methodRoute = "POST"
  57. }
  58. router.Handle(methodRoute, "/test", func(c *Context) {
  59. passed = true
  60. })
  61. w := performRequest(router, method, "/test")
  62. assert.False(t, passed)
  63. assert.Equal(t, w.Code, http.StatusMethodNotAllowed)
  64. }
  65. func TestRouterGroupRouteOK(t *testing.T) {
  66. testRouteOK("POST", t)
  67. testRouteOK("DELETE", t)
  68. testRouteOK("PATCH", t)
  69. testRouteOK("PUT", t)
  70. testRouteOK("OPTIONS", t)
  71. testRouteOK("HEAD", t)
  72. }
  73. // TestSingleRouteOK tests that POST route is correctly invoked.
  74. func TestRouteNotOK(t *testing.T) {
  75. testRouteNotOK("POST", t)
  76. testRouteNotOK("DELETE", t)
  77. testRouteNotOK("PATCH", t)
  78. testRouteNotOK("PUT", t)
  79. testRouteNotOK("OPTIONS", t)
  80. testRouteNotOK("HEAD", t)
  81. }
  82. // TestSingleRouteOK tests that POST route is correctly invoked.
  83. func TestRouteNotOK2(t *testing.T) {
  84. testRouteNotOK2("POST", t)
  85. testRouteNotOK2("DELETE", t)
  86. testRouteNotOK2("PATCH", t)
  87. testRouteNotOK2("PUT", t)
  88. testRouteNotOK2("OPTIONS", t)
  89. testRouteNotOK2("HEAD", t)
  90. }
  91. // TestContextParamsGet tests that a parameter can be parsed from the URL.
  92. func TestRouteParamsByName(t *testing.T) {
  93. name := ""
  94. lastName := ""
  95. wild := ""
  96. router := New()
  97. router.GET("/test/:name/:last_name/*wild", func(c *Context) {
  98. name = c.Params.ByName("name")
  99. lastName = c.Params.ByName("last_name")
  100. wild = c.Params.ByName("wild")
  101. assert.Equal(t, name, c.ParamValue("name"))
  102. assert.Equal(t, lastName, c.ParamValue("last_name"))
  103. assert.Equal(t, name, c.DefaultParamValue("name", "nothing"))
  104. assert.Equal(t, lastName, c.DefaultParamValue("last_name", "nothing"))
  105. assert.Equal(t, c.DefaultParamValue("noKey", "default"), "default")
  106. })
  107. w := performRequest(router, "GET", "/test/john/smith/is/super/great")
  108. assert.Equal(t, w.Code, 200)
  109. assert.Equal(t, name, "john")
  110. assert.Equal(t, lastName, "smith")
  111. assert.Equal(t, wild, "/is/super/great")
  112. }
  113. // TestHandleStaticFile - ensure the static file handles properly
  114. func TestRouteStaticFile(t *testing.T) {
  115. // SETUP file
  116. testRoot, _ := os.Getwd()
  117. f, err := ioutil.TempFile(testRoot, "")
  118. if err != nil {
  119. t.Error(err)
  120. }
  121. defer os.Remove(f.Name())
  122. filePath := path.Join("/", path.Base(f.Name()))
  123. f.WriteString("Gin Web Framework")
  124. f.Close()
  125. // SETUP gin
  126. router := New()
  127. router.Static("./", testRoot)
  128. w := performRequest(router, "GET", filePath)
  129. assert.Equal(t, w.Code, 200)
  130. assert.Equal(t, w.Body.String(), "Gin Web Framework")
  131. assert.Equal(t, w.HeaderMap.Get("Content-Type"), "text/plain; charset=utf-8")
  132. }
  133. // TestHandleStaticDir - ensure the root/sub dir handles properly
  134. func TestRouteStaticDir(t *testing.T) {
  135. router := New()
  136. router.Static("/", "./")
  137. w := performRequest(router, "GET", "/")
  138. assert.Equal(t, w.Code, 200)
  139. assert.Contains(t, w.Body.String(), "gin.go")
  140. assert.Equal(t, w.HeaderMap.Get("Content-Type"), "text/html; charset=utf-8")
  141. }
  142. // TestHandleHeadToDir - ensure the root/sub dir handles properly
  143. func TestRouteHeadToDir(t *testing.T) {
  144. router := New()
  145. router.Static("/", "./")
  146. w := performRequest(router, "HEAD", "/")
  147. assert.Equal(t, w.Code, 200)
  148. assert.Contains(t, w.Body.String(), "gin.go")
  149. assert.Equal(t, w.HeaderMap.Get("Content-Type"), "text/html; charset=utf-8")
  150. }
  151. func TestRouterMiddlewareAndStatic(t *testing.T) {
  152. router := New()
  153. static := router.Group("/", func(c *Context) {
  154. c.Writer.Header().Add("Last-Modified", "Mon, 02 Jan 2006 15:04:05 MST")
  155. c.Writer.Header().Add("Expires", "Mon, 02 Jan 2006 15:04:05 MST")
  156. c.Writer.Header().Add("X-GIN", "Gin Framework")
  157. })
  158. static.Static("/", "./")
  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. assert.NotEqual(t, w.HeaderMap.Get("Last-Modified"), "Mon, 02 Jan 2006 15:04:05 MST")
  164. assert.Equal(t, w.HeaderMap.Get("Expires"), "Mon, 02 Jan 2006 15:04:05 MST")
  165. assert.Equal(t, w.HeaderMap.Get("x-GIN"), "Gin Framework")
  166. }
  167. func TestRouteNotAllowed(t *testing.T) {
  168. router := New()
  169. router.POST("/path", func(c *Context) {})
  170. w := performRequest(router, "GET", "/path")
  171. assert.Equal(t, w.Code, http.StatusMethodNotAllowed)
  172. router.NoMethod(func(c *Context) {
  173. c.String(http.StatusTeapot, "responseText")
  174. })
  175. w = performRequest(router, "GET", "/path")
  176. assert.Equal(t, w.Body.String(), "responseText")
  177. assert.Equal(t, w.Code, http.StatusTeapot)
  178. }
  179. func TestRouterNotFound(t *testing.T) {
  180. router := New()
  181. router.GET("/path", func(c *Context) {})
  182. router.GET("/dir/", func(c *Context) {})
  183. router.GET("/", func(c *Context) {})
  184. testRoutes := []struct {
  185. route string
  186. code int
  187. header string
  188. }{
  189. {"/path/", 301, "map[Location:[/path]]"}, // TSR -/
  190. {"/dir", 301, "map[Location:[/dir/]]"}, // TSR +/
  191. {"", 301, "map[Location:[/]]"}, // TSR +/
  192. {"/PATH", 301, "map[Location:[/path]]"}, // Fixed Case
  193. {"/DIR/", 301, "map[Location:[/dir/]]"}, // Fixed Case
  194. {"/PATH/", 301, "map[Location:[/path]]"}, // Fixed Case -/
  195. {"/DIR", 301, "map[Location:[/dir/]]"}, // Fixed Case +/
  196. {"/../path", 301, "map[Location:[/path]]"}, // CleanPath
  197. {"/nope", 404, ""}, // NotFound
  198. }
  199. for _, tr := range testRoutes {
  200. w := performRequest(router, "GET", tr.route)
  201. assert.Equal(t, w.Code, tr.code)
  202. if w.Code != 404 {
  203. assert.Equal(t, fmt.Sprint(w.Header()), tr.header)
  204. }
  205. }
  206. // Test custom not found handler
  207. var notFound bool
  208. router.NoRoute(func(c *Context) {
  209. c.AbortWithStatus(404)
  210. notFound = true
  211. })
  212. w := performRequest(router, "GET", "/nope")
  213. assert.Equal(t, w.Code, 404)
  214. assert.True(t, notFound)
  215. // Test other method than GET (want 307 instead of 301)
  216. router.PATCH("/path", func(c *Context) {})
  217. w = performRequest(router, "PATCH", "/path/")
  218. assert.Equal(t, w.Code, 307)
  219. assert.Equal(t, fmt.Sprint(w.Header()), "map[Location:[/path]]")
  220. // Test special case where no node for the prefix "/" exists
  221. router = New()
  222. router.GET("/a", func(c *Context) {})
  223. w = performRequest(router, "GET", "/")
  224. assert.Equal(t, w.Code, 404)
  225. }