routes_test.go 7.6 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282
  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. })
  113. w := performRequest(router, "GET", "/test/john/smith/is/super/great")
  114. assert.Equal(t, w.Code, 200)
  115. assert.Equal(t, name, "john")
  116. assert.Equal(t, lastName, "smith")
  117. assert.Equal(t, wild, "/is/super/great")
  118. }
  119. // TestHandleStaticFile - ensure the static file handles properly
  120. func TestRouteStaticFile(t *testing.T) {
  121. // SETUP file
  122. testRoot, _ := os.Getwd()
  123. f, err := ioutil.TempFile(testRoot, "")
  124. if err != nil {
  125. t.Error(err)
  126. }
  127. defer os.Remove(f.Name())
  128. f.WriteString("Gin Web Framework")
  129. f.Close()
  130. dir, filename := path.Split(f.Name())
  131. // SETUP gin
  132. router := New()
  133. router.Static("/using_static", dir)
  134. router.StaticFile("/result", f.Name())
  135. w := performRequest(router, "GET", "/using_static/"+filename)
  136. w2 := performRequest(router, "GET", "/result")
  137. assert.Equal(t, w, w2)
  138. assert.Equal(t, w.Code, 200)
  139. assert.Equal(t, w.Body.String(), "Gin Web Framework")
  140. assert.Equal(t, w.HeaderMap.Get("Content-Type"), "text/plain; charset=utf-8")
  141. w3 := performRequest(router, "HEAD", "/using_static/"+filename)
  142. w4 := performRequest(router, "HEAD", "/result")
  143. assert.Equal(t, w3, w4)
  144. assert.Equal(t, w3.Code, 200)
  145. }
  146. // TestHandleStaticDir - ensure the root/sub dir handles properly
  147. func TestRouteStaticListingDir(t *testing.T) {
  148. router := New()
  149. router.StaticFS("/", Dir("./", true))
  150. w := performRequest(router, "GET", "/")
  151. assert.Equal(t, w.Code, 200)
  152. assert.Contains(t, w.Body.String(), "gin.go")
  153. assert.Equal(t, w.HeaderMap.Get("Content-Type"), "text/html; charset=utf-8")
  154. }
  155. // TestHandleHeadToDir - ensure the root/sub dir handles properly
  156. func TestRouteStaticNoListing(t *testing.T) {
  157. router := New()
  158. router.Static("/", "./")
  159. w := performRequest(router, "GET", "/")
  160. assert.Equal(t, w.Code, 404)
  161. assert.NotContains(t, w.Body.String(), "gin.go")
  162. }
  163. func TestRouterMiddlewareAndStatic(t *testing.T) {
  164. router := New()
  165. static := router.Group("/", func(c *Context) {
  166. c.Writer.Header().Add("Last-Modified", "Mon, 02 Jan 2006 15:04:05 MST")
  167. c.Writer.Header().Add("Expires", "Mon, 02 Jan 2006 15:04:05 MST")
  168. c.Writer.Header().Add("X-GIN", "Gin Framework")
  169. })
  170. static.Static("/", "./")
  171. w := performRequest(router, "GET", "/gin.go")
  172. assert.Equal(t, w.Code, 200)
  173. assert.Contains(t, w.Body.String(), "package gin")
  174. assert.Equal(t, w.HeaderMap.Get("Content-Type"), "text/plain; charset=utf-8")
  175. assert.NotEqual(t, w.HeaderMap.Get("Last-Modified"), "Mon, 02 Jan 2006 15:04:05 MST")
  176. assert.Equal(t, w.HeaderMap.Get("Expires"), "Mon, 02 Jan 2006 15:04:05 MST")
  177. assert.Equal(t, w.HeaderMap.Get("x-GIN"), "Gin Framework")
  178. }
  179. func TestRouteNotAllowed(t *testing.T) {
  180. router := New()
  181. router.POST("/path", func(c *Context) {})
  182. w := performRequest(router, "GET", "/path")
  183. assert.Equal(t, w.Code, http.StatusMethodNotAllowed)
  184. router.NoMethod(func(c *Context) {
  185. c.String(http.StatusTeapot, "responseText")
  186. })
  187. w = performRequest(router, "GET", "/path")
  188. assert.Equal(t, w.Body.String(), "responseText")
  189. assert.Equal(t, w.Code, http.StatusTeapot)
  190. }
  191. func TestRouterNotFound(t *testing.T) {
  192. router := New()
  193. router.GET("/path", func(c *Context) {})
  194. router.GET("/dir/", func(c *Context) {})
  195. router.GET("/", func(c *Context) {})
  196. testRoutes := []struct {
  197. route string
  198. code int
  199. header string
  200. }{
  201. {"/path/", 301, "map[Location:[/path]]"}, // TSR -/
  202. {"/dir", 301, "map[Location:[/dir/]]"}, // TSR +/
  203. {"", 301, "map[Location:[/]]"}, // TSR +/
  204. {"/PATH", 301, "map[Location:[/path]]"}, // Fixed Case
  205. {"/DIR/", 301, "map[Location:[/dir/]]"}, // Fixed Case
  206. {"/PATH/", 301, "map[Location:[/path]]"}, // Fixed Case -/
  207. {"/DIR", 301, "map[Location:[/dir/]]"}, // Fixed Case +/
  208. {"/../path", 301, "map[Location:[/path]]"}, // CleanPath
  209. {"/nope", 404, ""}, // NotFound
  210. }
  211. for _, tr := range testRoutes {
  212. w := performRequest(router, "GET", tr.route)
  213. assert.Equal(t, w.Code, tr.code)
  214. if w.Code != 404 {
  215. assert.Equal(t, fmt.Sprint(w.Header()), tr.header)
  216. }
  217. }
  218. // Test custom not found handler
  219. var notFound bool
  220. router.NoRoute(func(c *Context) {
  221. c.AbortWithStatus(404)
  222. notFound = true
  223. })
  224. w := performRequest(router, "GET", "/nope")
  225. assert.Equal(t, w.Code, 404)
  226. assert.True(t, notFound)
  227. // Test other method than GET (want 307 instead of 301)
  228. router.PATCH("/path", func(c *Context) {})
  229. w = performRequest(router, "PATCH", "/path/")
  230. assert.Equal(t, w.Code, 307)
  231. assert.Equal(t, fmt.Sprint(w.Header()), "map[Location:[/path]]")
  232. // Test special case where no node for the prefix "/" exists
  233. router = New()
  234. router.GET("/a", func(c *Context) {})
  235. w = performRequest(router, "GET", "/")
  236. assert.Equal(t, w.Code, 404)
  237. }