gin_test.go 9.3 KB

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