gin_test.go 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378
  1. package gin
  2. import (
  3. "html/template"
  4. "io/ioutil"
  5. "net/http"
  6. "net/http/httptest"
  7. "os"
  8. "path"
  9. "strings"
  10. "testing"
  11. )
  12. // TestRouterGroupGETRouteOK tests that GET route is correctly invoked.
  13. func TestRouterGroupGETRouteOK(t *testing.T) {
  14. req, _ := http.NewRequest("GET", "/test", nil)
  15. w := httptest.NewRecorder()
  16. passed := false
  17. r := Default()
  18. r.GET("/test", func(c *Context) {
  19. passed = true
  20. })
  21. r.ServeHTTP(w, req)
  22. if passed == false {
  23. t.Errorf("GET route handler was not invoked.")
  24. }
  25. if w.Code != http.StatusOK {
  26. t.Errorf("Status code should be %v, was %d", http.StatusOK, w.Code)
  27. }
  28. }
  29. // TestRouterGroupGETNoRootExistsRouteOK tests that a GET requse to root is correctly
  30. // handled (404) when no root route exists.
  31. func TestRouterGroupGETNoRootExistsRouteOK(t *testing.T) {
  32. req, _ := http.NewRequest("GET", "/", nil)
  33. w := httptest.NewRecorder()
  34. r := Default()
  35. r.GET("/test", func(c *Context) {
  36. })
  37. r.ServeHTTP(w, req)
  38. if w.Code != http.StatusNotFound {
  39. // If this fails, it's because httprouter needs to be updated to at least f78f58a0db
  40. t.Errorf("Status code should be %v, was %d. Location: %s", http.StatusNotFound, w.Code, w.HeaderMap.Get("Location"))
  41. }
  42. }
  43. // TestRouterGroupPOSTRouteOK tests that POST route is correctly invoked.
  44. func TestRouterGroupPOSTRouteOK(t *testing.T) {
  45. req, _ := http.NewRequest("POST", "/test", nil)
  46. w := httptest.NewRecorder()
  47. passed := false
  48. r := Default()
  49. r.POST("/test", func(c *Context) {
  50. passed = true
  51. })
  52. r.ServeHTTP(w, req)
  53. if passed == false {
  54. t.Errorf("POST route handler was not invoked.")
  55. }
  56. if w.Code != http.StatusOK {
  57. t.Errorf("Status code should be %v, was %d", http.StatusOK, w.Code)
  58. }
  59. }
  60. // TestRouterGroupDELETERouteOK tests that DELETE route is correctly invoked.
  61. func TestRouterGroupDELETERouteOK(t *testing.T) {
  62. req, _ := http.NewRequest("DELETE", "/test", nil)
  63. w := httptest.NewRecorder()
  64. passed := false
  65. r := Default()
  66. r.DELETE("/test", func(c *Context) {
  67. passed = true
  68. })
  69. r.ServeHTTP(w, req)
  70. if passed == false {
  71. t.Errorf("DELETE route handler was not invoked.")
  72. }
  73. if w.Code != http.StatusOK {
  74. t.Errorf("Status code should be %v, was %d", http.StatusOK, w.Code)
  75. }
  76. }
  77. // TestRouterGroupPATCHRouteOK tests that PATCH route is correctly invoked.
  78. func TestRouterGroupPATCHRouteOK(t *testing.T) {
  79. req, _ := http.NewRequest("PATCH", "/test", nil)
  80. w := httptest.NewRecorder()
  81. passed := false
  82. r := Default()
  83. r.PATCH("/test", func(c *Context) {
  84. passed = true
  85. })
  86. r.ServeHTTP(w, req)
  87. if passed == false {
  88. t.Errorf("PATCH route handler was not invoked.")
  89. }
  90. if w.Code != http.StatusOK {
  91. t.Errorf("Status code should be %v, was %d", http.StatusOK, w.Code)
  92. }
  93. }
  94. // TestRouterGroupPUTRouteOK tests that PUT route is correctly invoked.
  95. func TestRouterGroupPUTRouteOK(t *testing.T) {
  96. req, _ := http.NewRequest("PUT", "/test", nil)
  97. w := httptest.NewRecorder()
  98. passed := false
  99. r := Default()
  100. r.PUT("/test", func(c *Context) {
  101. passed = true
  102. })
  103. r.ServeHTTP(w, req)
  104. if passed == false {
  105. t.Errorf("PUT route handler was not invoked.")
  106. }
  107. if w.Code != http.StatusOK {
  108. t.Errorf("Status code should be %v, was %d", http.StatusOK, w.Code)
  109. }
  110. }
  111. // TestRouterGroupOPTIONSRouteOK tests that OPTIONS route is correctly invoked.
  112. func TestRouterGroupOPTIONSRouteOK(t *testing.T) {
  113. req, _ := http.NewRequest("OPTIONS", "/test", nil)
  114. w := httptest.NewRecorder()
  115. passed := false
  116. r := Default()
  117. r.OPTIONS("/test", func(c *Context) {
  118. passed = true
  119. })
  120. r.ServeHTTP(w, req)
  121. if passed == false {
  122. t.Errorf("OPTIONS route handler was not invoked.")
  123. }
  124. if w.Code != http.StatusOK {
  125. t.Errorf("Status code should be %v, was %d", http.StatusOK, w.Code)
  126. }
  127. }
  128. // TestRouterGroupHEADRouteOK tests that HEAD route is correctly invoked.
  129. func TestRouterGroupHEADRouteOK(t *testing.T) {
  130. req, _ := http.NewRequest("HEAD", "/test", nil)
  131. w := httptest.NewRecorder()
  132. passed := false
  133. r := Default()
  134. r.HEAD("/test", func(c *Context) {
  135. passed = true
  136. })
  137. r.ServeHTTP(w, req)
  138. if passed == false {
  139. t.Errorf("HEAD route handler was not invoked.")
  140. }
  141. if w.Code != http.StatusOK {
  142. t.Errorf("Status code should be %v, was %d", http.StatusOK, w.Code)
  143. }
  144. }
  145. // TestRouterGroup404 tests that 404 is returned for a route that does not exist.
  146. func TestEngine404(t *testing.T) {
  147. req, _ := http.NewRequest("GET", "/", nil)
  148. w := httptest.NewRecorder()
  149. r := Default()
  150. r.ServeHTTP(w, req)
  151. if w.Code != http.StatusNotFound {
  152. t.Errorf("Response code should be %v, was %d", http.StatusNotFound, w.Code)
  153. }
  154. }
  155. // TestContextParamsGet tests that a parameter can be parsed from the URL.
  156. func TestContextParamsByName(t *testing.T) {
  157. req, _ := http.NewRequest("GET", "/test/alexandernyquist", nil)
  158. w := httptest.NewRecorder()
  159. name := ""
  160. r := Default()
  161. r.GET("/test/:name", func(c *Context) {
  162. name = c.Params.ByName("name")
  163. })
  164. r.ServeHTTP(w, req)
  165. if name != "alexandernyquist" {
  166. t.Errorf("Url parameter was not correctly parsed. Should be alexandernyquist, was %s.", name)
  167. }
  168. }
  169. // TestContextSetGet tests that a parameter is set correctly on the
  170. // current context and can be retrieved using Get.
  171. func TestContextSetGet(t *testing.T) {
  172. req, _ := http.NewRequest("GET", "/test", nil)
  173. w := httptest.NewRecorder()
  174. r := Default()
  175. r.GET("/test", func(c *Context) {
  176. // Key should be lazily created
  177. if c.Keys != nil {
  178. t.Error("Keys should be nil")
  179. }
  180. // Set
  181. c.Set("foo", "bar")
  182. if v := c.Get("foo"); v != "bar" {
  183. t.Errorf("Value should be bar, was %s", v)
  184. }
  185. })
  186. r.ServeHTTP(w, req)
  187. }
  188. // TestContextJSON tests that the response is serialized as JSON
  189. // and Content-Type is set to application/json
  190. func TestContextJSON(t *testing.T) {
  191. req, _ := http.NewRequest("GET", "/test", nil)
  192. w := httptest.NewRecorder()
  193. r := Default()
  194. r.GET("/test", func(c *Context) {
  195. c.JSON(200, H{"foo": "bar"})
  196. })
  197. r.ServeHTTP(w, req)
  198. if w.Body.String() != "{\"foo\":\"bar\"}\n" {
  199. t.Errorf("Response should be {\"foo\":\"bar\"}, was: %s", w.Body.String())
  200. }
  201. if w.HeaderMap.Get("Content-Type") != "application/json" {
  202. t.Errorf("Content-Type should be application/json, was %s", w.HeaderMap.Get("Content-Type"))
  203. }
  204. }
  205. // TestContextHTML tests that the response executes the templates
  206. // and responds with Content-Type set to text/html
  207. func TestContextHTML(t *testing.T) {
  208. req, _ := http.NewRequest("GET", "/test", nil)
  209. w := httptest.NewRecorder()
  210. r := Default()
  211. r.HTMLTemplates = template.Must(template.New("t").Parse(`Hello {{.Name}}`))
  212. type TestData struct{ Name string }
  213. r.GET("/test", func(c *Context) {
  214. c.HTML(200, "t", TestData{"alexandernyquist"})
  215. })
  216. r.ServeHTTP(w, req)
  217. if w.Body.String() != "Hello alexandernyquist" {
  218. t.Errorf("Response should be Hello alexandernyquist, was: %s", w.Body.String())
  219. }
  220. if w.HeaderMap.Get("Content-Type") != "text/html" {
  221. t.Errorf("Content-Type should be text/html, was %s", w.HeaderMap.Get("Content-Type"))
  222. }
  223. }
  224. // TestContextString tests that the response is returned
  225. // with Content-Type set to text/plain
  226. func TestContextString(t *testing.T) {
  227. req, _ := http.NewRequest("GET", "/test", nil)
  228. w := httptest.NewRecorder()
  229. r := Default()
  230. r.GET("/test", func(c *Context) {
  231. c.String(200, "test")
  232. })
  233. r.ServeHTTP(w, req)
  234. if w.Body.String() != "test" {
  235. t.Errorf("Response should be test, was: %s", w.Body.String())
  236. }
  237. if w.HeaderMap.Get("Content-Type") != "text/plain" {
  238. t.Errorf("Content-Type should be text/plain, was %s", w.HeaderMap.Get("Content-Type"))
  239. }
  240. }
  241. // TestHandleStaticFile - ensure the static file handles properly
  242. func TestHandleStaticFile(t *testing.T) {
  243. testRoot, _ := os.Getwd()
  244. f, err := ioutil.TempFile(testRoot, "")
  245. defer os.Remove(f.Name())
  246. if err != nil {
  247. t.Error(err)
  248. }
  249. filePath := path.Join("/", path.Base(f.Name()))
  250. req, _ := http.NewRequest("GET", filePath, nil)
  251. f.WriteString("Gin Web Framework")
  252. f.Close()
  253. w := httptest.NewRecorder()
  254. r := Default()
  255. r.ServeFiles("/*filepath", http.Dir("./"))
  256. r.ServeHTTP(w, req)
  257. if w.Code != 200 {
  258. t.Errorf("Response code should be Ok, was: %s", w.Code)
  259. }
  260. if w.Body.String() != "Gin Web Framework" {
  261. t.Errorf("Response should be test, was: %s", w.Body.String())
  262. }
  263. if w.HeaderMap.Get("Content-Type") != "text/plain; charset=utf-8" {
  264. t.Errorf("Content-Type should be text/plain, was %s", w.HeaderMap.Get("Content-Type"))
  265. }
  266. }
  267. // TestHandleStaticDir - ensure the root/sub dir handles properly
  268. func TestHandleStaticDir(t *testing.T) {
  269. req, _ := http.NewRequest("GET", "/", nil)
  270. w := httptest.NewRecorder()
  271. r := Default()
  272. r.ServeFiles("/*filepath", http.Dir("./"))
  273. r.ServeHTTP(w, req)
  274. if w.Code != 200 {
  275. t.Errorf("Response code should be Ok, was: %s", w.Code)
  276. }
  277. bodyAsString := w.Body.String()
  278. if len(bodyAsString) == 0 {
  279. t.Errorf("Got empty body instead of file tree")
  280. }
  281. if !strings.Contains(bodyAsString, "gin.go") {
  282. t.Errorf("Can't find:`gin.go` in file tree: %s", bodyAsString)
  283. }
  284. if w.HeaderMap.Get("Content-Type") != "text/html; charset=utf-8" {
  285. t.Errorf("Content-Type should be text/plain, was %s", w.HeaderMap.Get("Content-Type"))
  286. }
  287. }