gin_test.go 9.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365
  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. "html/template"
  8. "io/ioutil"
  9. "net/http"
  10. "reflect"
  11. "testing"
  12. "time"
  13. "github.com/stretchr/testify/assert"
  14. )
  15. func formatAsDate(t time.Time) string {
  16. year, month, day := t.Date()
  17. return fmt.Sprintf("%d/%02d/%02d", year, month, day)
  18. }
  19. func setupHTMLFiles(t *testing.T) func() {
  20. go func() {
  21. SetMode(TestMode)
  22. router := New()
  23. router.Delims("{[{", "}]}")
  24. router.SetFuncMap(template.FuncMap{
  25. "formatAsDate": formatAsDate,
  26. })
  27. router.LoadHTMLFiles("./fixtures/basic/hello.tmpl", "./fixtures/basic/raw.tmpl")
  28. router.GET("/test", func(c *Context) {
  29. c.HTML(http.StatusOK, "hello.tmpl", map[string]string{"name": "world"})
  30. })
  31. router.GET("/raw", func(c *Context) {
  32. c.HTML(http.StatusOK, "raw.tmpl", map[string]interface{}{
  33. "now": time.Date(2017, 07, 01, 0, 0, 0, 0, time.UTC),
  34. })
  35. })
  36. router.Run(":8888")
  37. }()
  38. t.Log("waiting 1 second for server startup")
  39. time.Sleep(1 * time.Second)
  40. return func() {}
  41. }
  42. func setupHTMLGlob(t *testing.T) func() {
  43. go func() {
  44. SetMode(DebugMode)
  45. router := New()
  46. router.Delims("{[{", "}]}")
  47. router.SetFuncMap(template.FuncMap{
  48. "formatAsDate": formatAsDate,
  49. })
  50. router.LoadHTMLGlob("./fixtures/basic/*")
  51. router.GET("/test", func(c *Context) {
  52. c.HTML(http.StatusOK, "hello.tmpl", map[string]string{"name": "world"})
  53. })
  54. router.GET("/raw", func(c *Context) {
  55. c.HTML(http.StatusOK, "raw.tmpl", map[string]interface{}{
  56. "now": time.Date(2017, 07, 01, 0, 0, 0, 0, time.UTC),
  57. })
  58. })
  59. router.Run(":8888")
  60. }()
  61. t.Log("waiting 1 second for server startup")
  62. time.Sleep(1 * time.Second)
  63. return func() {}
  64. }
  65. //TODO
  66. func TestLoadHTMLGlob(t *testing.T) {
  67. td := setupHTMLGlob(t)
  68. res, err := http.Get("http://127.0.0.1:8888/test")
  69. if err != nil {
  70. fmt.Println(err)
  71. }
  72. resp, _ := ioutil.ReadAll(res.Body)
  73. assert.Equal(t, "<h1>Hello world</h1>", string(resp[:]))
  74. td()
  75. }
  76. func TestLoadHTMLGlobFromFuncMap(t *testing.T) {
  77. time.Now()
  78. td := setupHTMLGlob(t)
  79. res, err := http.Get("http://127.0.0.1:8888/raw")
  80. if err != nil {
  81. fmt.Println(err)
  82. }
  83. resp, _ := ioutil.ReadAll(res.Body)
  84. assert.Equal(t, "Date: 2017/07/01\n", string(resp[:]))
  85. td()
  86. }
  87. // func (engine *Engine) LoadHTMLFiles(files ...string) {
  88. // func (engine *Engine) RunTLS(addr string, cert string, key string) error {
  89. func init() {
  90. SetMode(TestMode)
  91. }
  92. func TestCreateEngine(t *testing.T) {
  93. router := New()
  94. assert.Equal(t, "/", router.basePath)
  95. assert.Equal(t, router.engine, router)
  96. assert.Empty(t, router.Handlers)
  97. }
  98. // func TestLoadHTMLDebugMode(t *testing.T) {
  99. // router := New()
  100. // SetMode(DebugMode)
  101. // router.LoadHTMLGlob("*.testtmpl")
  102. // r := router.HTMLRender.(render.HTMLDebug)
  103. // assert.Empty(t, r.Files)
  104. // assert.Equal(t, r.Glob, "*.testtmpl")
  105. //
  106. // router.LoadHTMLFiles("index.html.testtmpl", "login.html.testtmpl")
  107. // r = router.HTMLRender.(render.HTMLDebug)
  108. // assert.Empty(t, r.Glob)
  109. // assert.Equal(t, r.Files, []string{"index.html", "login.html"})
  110. // SetMode(TestMode)
  111. // }
  112. func TestLoadHTMLFiles(t *testing.T) {
  113. td := setupHTMLFiles(t)
  114. res, err := http.Get("http://127.0.0.1:8888/test")
  115. if err != nil {
  116. fmt.Println(err)
  117. }
  118. resp, _ := ioutil.ReadAll(res.Body)
  119. assert.Equal(t, "<h1>Hello world</h1>", string(resp[:]))
  120. td()
  121. }
  122. func TestLoadHTMLFilesFuncMap(t *testing.T) {
  123. time.Now()
  124. td := setupHTMLFiles(t)
  125. res, err := http.Get("http://127.0.0.1:8888/raw")
  126. if err != nil {
  127. fmt.Println(err)
  128. }
  129. resp, _ := ioutil.ReadAll(res.Body)
  130. assert.Equal(t, "Date: 2017/07/01\n", string(resp[:]))
  131. td()
  132. }
  133. func TestLoadHTMLReleaseMode(t *testing.T) {
  134. }
  135. func TestAddRoute(t *testing.T) {
  136. router := New()
  137. router.addRoute("GET", "/", HandlersChain{func(_ *Context) {}})
  138. assert.Len(t, router.trees, 1)
  139. assert.NotNil(t, router.trees.get("GET"))
  140. assert.Nil(t, router.trees.get("POST"))
  141. router.addRoute("POST", "/", HandlersChain{func(_ *Context) {}})
  142. assert.Len(t, router.trees, 2)
  143. assert.NotNil(t, router.trees.get("GET"))
  144. assert.NotNil(t, router.trees.get("POST"))
  145. router.addRoute("POST", "/post", HandlersChain{func(_ *Context) {}})
  146. assert.Len(t, router.trees, 2)
  147. }
  148. func TestAddRouteFails(t *testing.T) {
  149. router := New()
  150. assert.Panics(t, func() { router.addRoute("", "/", HandlersChain{func(_ *Context) {}}) })
  151. assert.Panics(t, func() { router.addRoute("GET", "a", HandlersChain{func(_ *Context) {}}) })
  152. assert.Panics(t, func() { router.addRoute("GET", "/", HandlersChain{}) })
  153. router.addRoute("POST", "/post", HandlersChain{func(_ *Context) {}})
  154. assert.Panics(t, func() {
  155. router.addRoute("POST", "/post", HandlersChain{func(_ *Context) {}})
  156. })
  157. }
  158. func TestCreateDefaultRouter(t *testing.T) {
  159. router := Default()
  160. assert.Len(t, router.Handlers, 2)
  161. }
  162. func TestNoRouteWithoutGlobalHandlers(t *testing.T) {
  163. var middleware0 HandlerFunc = func(c *Context) {}
  164. var middleware1 HandlerFunc = func(c *Context) {}
  165. router := New()
  166. router.NoRoute(middleware0)
  167. assert.Nil(t, router.Handlers)
  168. assert.Len(t, router.noRoute, 1)
  169. assert.Len(t, router.allNoRoute, 1)
  170. compareFunc(t, router.noRoute[0], middleware0)
  171. compareFunc(t, router.allNoRoute[0], middleware0)
  172. router.NoRoute(middleware1, middleware0)
  173. assert.Len(t, router.noRoute, 2)
  174. assert.Len(t, router.allNoRoute, 2)
  175. compareFunc(t, router.noRoute[0], middleware1)
  176. compareFunc(t, router.allNoRoute[0], middleware1)
  177. compareFunc(t, router.noRoute[1], middleware0)
  178. compareFunc(t, router.allNoRoute[1], middleware0)
  179. }
  180. func TestNoRouteWithGlobalHandlers(t *testing.T) {
  181. var middleware0 HandlerFunc = func(c *Context) {}
  182. var middleware1 HandlerFunc = func(c *Context) {}
  183. var middleware2 HandlerFunc = func(c *Context) {}
  184. router := New()
  185. router.Use(middleware2)
  186. router.NoRoute(middleware0)
  187. assert.Len(t, router.allNoRoute, 2)
  188. assert.Len(t, router.Handlers, 1)
  189. assert.Len(t, router.noRoute, 1)
  190. compareFunc(t, router.Handlers[0], middleware2)
  191. compareFunc(t, router.noRoute[0], middleware0)
  192. compareFunc(t, router.allNoRoute[0], middleware2)
  193. compareFunc(t, router.allNoRoute[1], middleware0)
  194. router.Use(middleware1)
  195. assert.Len(t, router.allNoRoute, 3)
  196. assert.Len(t, router.Handlers, 2)
  197. assert.Len(t, router.noRoute, 1)
  198. compareFunc(t, router.Handlers[0], middleware2)
  199. compareFunc(t, router.Handlers[1], middleware1)
  200. compareFunc(t, router.noRoute[0], middleware0)
  201. compareFunc(t, router.allNoRoute[0], middleware2)
  202. compareFunc(t, router.allNoRoute[1], middleware1)
  203. compareFunc(t, router.allNoRoute[2], middleware0)
  204. }
  205. func TestNoMethodWithoutGlobalHandlers(t *testing.T) {
  206. var middleware0 HandlerFunc = func(c *Context) {}
  207. var middleware1 HandlerFunc = func(c *Context) {}
  208. router := New()
  209. router.NoMethod(middleware0)
  210. assert.Empty(t, router.Handlers)
  211. assert.Len(t, router.noMethod, 1)
  212. assert.Len(t, router.allNoMethod, 1)
  213. compareFunc(t, router.noMethod[0], middleware0)
  214. compareFunc(t, router.allNoMethod[0], middleware0)
  215. router.NoMethod(middleware1, middleware0)
  216. assert.Len(t, router.noMethod, 2)
  217. assert.Len(t, router.allNoMethod, 2)
  218. compareFunc(t, router.noMethod[0], middleware1)
  219. compareFunc(t, router.allNoMethod[0], middleware1)
  220. compareFunc(t, router.noMethod[1], middleware0)
  221. compareFunc(t, router.allNoMethod[1], middleware0)
  222. }
  223. func TestRebuild404Handlers(t *testing.T) {
  224. }
  225. func TestNoMethodWithGlobalHandlers(t *testing.T) {
  226. var middleware0 HandlerFunc = func(c *Context) {}
  227. var middleware1 HandlerFunc = func(c *Context) {}
  228. var middleware2 HandlerFunc = func(c *Context) {}
  229. router := New()
  230. router.Use(middleware2)
  231. router.NoMethod(middleware0)
  232. assert.Len(t, router.allNoMethod, 2)
  233. assert.Len(t, router.Handlers, 1)
  234. assert.Len(t, router.noMethod, 1)
  235. compareFunc(t, router.Handlers[0], middleware2)
  236. compareFunc(t, router.noMethod[0], middleware0)
  237. compareFunc(t, router.allNoMethod[0], middleware2)
  238. compareFunc(t, router.allNoMethod[1], middleware0)
  239. router.Use(middleware1)
  240. assert.Len(t, router.allNoMethod, 3)
  241. assert.Len(t, router.Handlers, 2)
  242. assert.Len(t, router.noMethod, 1)
  243. compareFunc(t, router.Handlers[0], middleware2)
  244. compareFunc(t, router.Handlers[1], middleware1)
  245. compareFunc(t, router.noMethod[0], middleware0)
  246. compareFunc(t, router.allNoMethod[0], middleware2)
  247. compareFunc(t, router.allNoMethod[1], middleware1)
  248. compareFunc(t, router.allNoMethod[2], middleware0)
  249. }
  250. func compareFunc(t *testing.T, a, b interface{}) {
  251. sf1 := reflect.ValueOf(a)
  252. sf2 := reflect.ValueOf(b)
  253. if sf1.Pointer() != sf2.Pointer() {
  254. t.Error("different functions")
  255. }
  256. }
  257. func TestListOfRoutes(t *testing.T) {
  258. router := New()
  259. router.GET("/favicon.ico", handlerTest1)
  260. router.GET("/", handlerTest1)
  261. group := router.Group("/users")
  262. {
  263. group.GET("/", handlerTest2)
  264. group.GET("/:id", handlerTest1)
  265. group.POST("/:id", handlerTest2)
  266. }
  267. router.Static("/static", ".")
  268. list := router.Routes()
  269. assert.Len(t, list, 7)
  270. assertRoutePresent(t, list, RouteInfo{
  271. Method: "GET",
  272. Path: "/favicon.ico",
  273. Handler: "^(.*/vendor/)?github.com/gin-gonic/gin.handlerTest1$",
  274. })
  275. assertRoutePresent(t, list, RouteInfo{
  276. Method: "GET",
  277. Path: "/",
  278. Handler: "^(.*/vendor/)?github.com/gin-gonic/gin.handlerTest1$",
  279. })
  280. assertRoutePresent(t, list, RouteInfo{
  281. Method: "GET",
  282. Path: "/users/",
  283. Handler: "^(.*/vendor/)?github.com/gin-gonic/gin.handlerTest2$",
  284. })
  285. assertRoutePresent(t, list, RouteInfo{
  286. Method: "GET",
  287. Path: "/users/:id",
  288. Handler: "^(.*/vendor/)?github.com/gin-gonic/gin.handlerTest1$",
  289. })
  290. assertRoutePresent(t, list, RouteInfo{
  291. Method: "POST",
  292. Path: "/users/:id",
  293. Handler: "^(.*/vendor/)?github.com/gin-gonic/gin.handlerTest2$",
  294. })
  295. }
  296. func assertRoutePresent(t *testing.T, gotRoutes RoutesInfo, wantRoute RouteInfo) {
  297. for _, gotRoute := range gotRoutes {
  298. if gotRoute.Path == wantRoute.Path && gotRoute.Method == wantRoute.Method {
  299. assert.Regexp(t, wantRoute.Handler, gotRoute.Handler)
  300. return
  301. }
  302. }
  303. t.Errorf("route not found: %v", wantRoute)
  304. }
  305. func handlerTest1(c *Context) {}
  306. func handlerTest2(c *Context) {}