routes_test.go 7.8 KB

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