context_test.go 11 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442
  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. "bytes"
  7. "errors"
  8. "html/template"
  9. "net/http"
  10. "net/http/httptest"
  11. "testing"
  12. )
  13. // TestContextParamsGet tests that a parameter can be parsed from the URL.
  14. func TestContextParamsByName(t *testing.T) {
  15. req, _ := http.NewRequest("GET", "/test/alexandernyquist", nil)
  16. w := httptest.NewRecorder()
  17. name := ""
  18. r := New()
  19. r.GET("/test/:name", func(c *Context) {
  20. name = c.Params.ByName("name")
  21. })
  22. r.ServeHTTP(w, req)
  23. if name != "alexandernyquist" {
  24. t.Errorf("Url parameter was not correctly parsed. Should be alexandernyquist, was %s.", name)
  25. }
  26. }
  27. // TestContextSetGet tests that a parameter is set correctly on the
  28. // current context and can be retrieved using Get.
  29. func TestContextSetGet(t *testing.T) {
  30. req, _ := http.NewRequest("GET", "/test", nil)
  31. w := httptest.NewRecorder()
  32. r := New()
  33. r.GET("/test", func(c *Context) {
  34. // Key should be lazily created
  35. if c.Keys != nil {
  36. t.Error("Keys should be nil")
  37. }
  38. // Set
  39. c.Set("foo", "bar")
  40. v, err := c.Get("foo")
  41. if err != nil {
  42. t.Errorf("Error on exist key")
  43. }
  44. if v != "bar" {
  45. t.Errorf("Value should be bar, was %s", v)
  46. }
  47. })
  48. r.ServeHTTP(w, req)
  49. }
  50. // TestContextJSON tests that the response is serialized as JSON
  51. // and Content-Type is set to application/json
  52. func TestContextJSON(t *testing.T) {
  53. req, _ := http.NewRequest("GET", "/test", nil)
  54. w := httptest.NewRecorder()
  55. r := New()
  56. r.GET("/test", func(c *Context) {
  57. c.JSON(200, H{"foo": "bar"})
  58. })
  59. r.ServeHTTP(w, req)
  60. if w.Body.String() != "{\"foo\":\"bar\"}\n" {
  61. t.Errorf("Response should be {\"foo\":\"bar\"}, was: %s", w.Body.String())
  62. }
  63. if w.HeaderMap.Get("Content-Type") != "application/json; charset=utf-8" {
  64. t.Errorf("Content-Type should be application/json, was %s", w.HeaderMap.Get("Content-Type"))
  65. }
  66. }
  67. // TestContextHTML tests that the response executes the templates
  68. // and responds with Content-Type set to text/html
  69. func TestContextHTML(t *testing.T) {
  70. req, _ := http.NewRequest("GET", "/test", nil)
  71. w := httptest.NewRecorder()
  72. r := New()
  73. templ, _ := template.New("t").Parse(`Hello {{.Name}}`)
  74. r.SetHTMLTemplate(templ)
  75. type TestData struct{ Name string }
  76. r.GET("/test", func(c *Context) {
  77. c.HTML(200, "t", TestData{"alexandernyquist"})
  78. })
  79. r.ServeHTTP(w, req)
  80. if w.Body.String() != "Hello alexandernyquist" {
  81. t.Errorf("Response should be Hello alexandernyquist, was: %s", w.Body.String())
  82. }
  83. if w.HeaderMap.Get("Content-Type") != "text/html; charset=utf-8" {
  84. t.Errorf("Content-Type should be text/html, was %s", w.HeaderMap.Get("Content-Type"))
  85. }
  86. }
  87. // TestContextString tests that the response is returned
  88. // with Content-Type set to text/plain
  89. func TestContextString(t *testing.T) {
  90. req, _ := http.NewRequest("GET", "/test", nil)
  91. w := httptest.NewRecorder()
  92. r := New()
  93. r.GET("/test", func(c *Context) {
  94. c.String(200, "test")
  95. })
  96. r.ServeHTTP(w, req)
  97. if w.Body.String() != "test" {
  98. t.Errorf("Response should be test, was: %s", w.Body.String())
  99. }
  100. if w.HeaderMap.Get("Content-Type") != "text/plain; charset=utf-8" {
  101. t.Errorf("Content-Type should be text/plain, was %s", w.HeaderMap.Get("Content-Type"))
  102. }
  103. }
  104. // TestContextXML tests that the response is serialized as XML
  105. // and Content-Type is set to application/xml
  106. func TestContextXML(t *testing.T) {
  107. req, _ := http.NewRequest("GET", "/test", nil)
  108. w := httptest.NewRecorder()
  109. r := New()
  110. r.GET("/test", func(c *Context) {
  111. c.XML(200, H{"foo": "bar"})
  112. })
  113. r.ServeHTTP(w, req)
  114. if w.Body.String() != "<map><foo>bar</foo></map>" {
  115. t.Errorf("Response should be <map><foo>bar</foo></map>, was: %s", w.Body.String())
  116. }
  117. if w.HeaderMap.Get("Content-Type") != "application/xml; charset=utf-8" {
  118. t.Errorf("Content-Type should be application/xml, was %s", w.HeaderMap.Get("Content-Type"))
  119. }
  120. }
  121. // TestContextData tests that the response can be written from `bytesting`
  122. // with specified MIME type
  123. func TestContextData(t *testing.T) {
  124. req, _ := http.NewRequest("GET", "/test/csv", nil)
  125. w := httptest.NewRecorder()
  126. r := New()
  127. r.GET("/test/csv", func(c *Context) {
  128. c.Data(200, "text/csv", []byte(`foo,bar`))
  129. })
  130. r.ServeHTTP(w, req)
  131. if w.Body.String() != "foo,bar" {
  132. t.Errorf("Response should be foo&bar, was: %s", w.Body.String())
  133. }
  134. if w.HeaderMap.Get("Content-Type") != "text/csv" {
  135. t.Errorf("Content-Type should be text/csv, was %s", w.HeaderMap.Get("Content-Type"))
  136. }
  137. }
  138. func TestContextFile(t *testing.T) {
  139. req, _ := http.NewRequest("GET", "/test/file", nil)
  140. w := httptest.NewRecorder()
  141. r := New()
  142. r.GET("/test/file", func(c *Context) {
  143. c.File("./gin.go")
  144. })
  145. r.ServeHTTP(w, req)
  146. bodyAsString := w.Body.String()
  147. if len(bodyAsString) == 0 {
  148. t.Errorf("Got empty body instead of file data")
  149. }
  150. if w.HeaderMap.Get("Content-Type") != "text/plain; charset=utf-8" {
  151. t.Errorf("Content-Type should be text/plain; charset=utf-8, was %s", w.HeaderMap.Get("Content-Type"))
  152. }
  153. }
  154. // TestHandlerFunc - ensure that custom middleware works properly
  155. func TestHandlerFunc(t *testing.T) {
  156. req, _ := http.NewRequest("GET", "/", nil)
  157. w := httptest.NewRecorder()
  158. r := New()
  159. var stepsPassed int = 0
  160. r.Use(func(context *Context) {
  161. stepsPassed += 1
  162. context.Next()
  163. stepsPassed += 1
  164. })
  165. r.ServeHTTP(w, req)
  166. if w.Code != 404 {
  167. t.Errorf("Response code should be Not found, was: %s", w.Code)
  168. }
  169. if stepsPassed != 2 {
  170. t.Errorf("Falied to switch context in handler function: %s", stepsPassed)
  171. }
  172. }
  173. // TestBadAbortHandlersChain - ensure that Abort after switch context will not interrupt pending handlers
  174. func TestBadAbortHandlersChain(t *testing.T) {
  175. // SETUP
  176. var stepsPassed int = 0
  177. r := New()
  178. r.Use(func(c *Context) {
  179. stepsPassed += 1
  180. c.Next()
  181. stepsPassed += 1
  182. // after check and abort
  183. c.AbortWithStatus(409)
  184. })
  185. r.Use(func(c *Context) {
  186. stepsPassed += 1
  187. c.Next()
  188. stepsPassed += 1
  189. c.AbortWithStatus(403)
  190. })
  191. // RUN
  192. w := PerformRequest(r, "GET", "/")
  193. // TEST
  194. if w.Code != 409 {
  195. t.Errorf("Response code should be Forbiden, was: %d", w.Code)
  196. }
  197. if stepsPassed != 4 {
  198. t.Errorf("Falied to switch context in handler function: %d", stepsPassed)
  199. }
  200. }
  201. // TestAbortHandlersChain - ensure that Abort interrupt used middlewares in fifo order
  202. func TestAbortHandlersChain(t *testing.T) {
  203. // SETUP
  204. var stepsPassed int = 0
  205. r := New()
  206. r.Use(func(context *Context) {
  207. stepsPassed += 1
  208. context.AbortWithStatus(409)
  209. })
  210. r.Use(func(context *Context) {
  211. stepsPassed += 1
  212. context.Next()
  213. stepsPassed += 1
  214. })
  215. // RUN
  216. w := PerformRequest(r, "GET", "/")
  217. // TEST
  218. if w.Code != 409 {
  219. t.Errorf("Response code should be Conflict, was: %d", w.Code)
  220. }
  221. if stepsPassed != 1 {
  222. t.Errorf("Falied to switch context in handler function: %d", stepsPassed)
  223. }
  224. }
  225. // TestFailHandlersChain - ensure that Fail interrupt used middlewares in fifo order as
  226. // as well as Abort
  227. func TestFailHandlersChain(t *testing.T) {
  228. // SETUP
  229. var stepsPassed int = 0
  230. r := New()
  231. r.Use(func(context *Context) {
  232. stepsPassed += 1
  233. context.Fail(500, errors.New("foo"))
  234. })
  235. r.Use(func(context *Context) {
  236. stepsPassed += 1
  237. context.Next()
  238. stepsPassed += 1
  239. })
  240. // RUN
  241. w := PerformRequest(r, "GET", "/")
  242. // TEST
  243. if w.Code != 500 {
  244. t.Errorf("Response code should be Server error, was: %d", w.Code)
  245. }
  246. if stepsPassed != 1 {
  247. t.Errorf("Falied to switch context in handler function: %d", stepsPassed)
  248. }
  249. }
  250. func TestBindingJSON(t *testing.T) {
  251. body := bytes.NewBuffer([]byte("{\"foo\":\"bar\"}"))
  252. r := New()
  253. r.POST("/binding/json", func(c *Context) {
  254. var body struct {
  255. Foo string `json:"foo"`
  256. }
  257. if c.Bind(&body) {
  258. c.JSON(200, H{"parsed": body.Foo})
  259. }
  260. })
  261. req, _ := http.NewRequest("POST", "/binding/json", body)
  262. req.Header.Set("Content-Type", "application/json")
  263. w := httptest.NewRecorder()
  264. r.ServeHTTP(w, req)
  265. if w.Code != 200 {
  266. t.Errorf("Response code should be Ok, was: %s", w.Code)
  267. }
  268. if w.Body.String() != "{\"parsed\":\"bar\"}\n" {
  269. t.Errorf("Response should be {\"parsed\":\"bar\"}, was: %s", w.Body.String())
  270. }
  271. if w.HeaderMap.Get("Content-Type") != "application/json; charset=utf-8" {
  272. t.Errorf("Content-Type should be application/json, was %s", w.HeaderMap.Get("Content-Type"))
  273. }
  274. }
  275. func TestBindingJSONEncoding(t *testing.T) {
  276. body := bytes.NewBuffer([]byte("{\"foo\":\"嘉\"}"))
  277. r := New()
  278. r.POST("/binding/json", func(c *Context) {
  279. var body struct {
  280. Foo string `json:"foo"`
  281. }
  282. if c.Bind(&body) {
  283. c.JSON(200, H{"parsed": body.Foo})
  284. }
  285. })
  286. req, _ := http.NewRequest("POST", "/binding/json", body)
  287. req.Header.Set("Content-Type", "application/json; charset=utf-8")
  288. w := httptest.NewRecorder()
  289. r.ServeHTTP(w, req)
  290. if w.Code != 200 {
  291. t.Errorf("Response code should be Ok, was: %s", w.Code)
  292. }
  293. if w.Body.String() != "{\"parsed\":\"嘉\"}\n" {
  294. t.Errorf("Response should be {\"parsed\":\"嘉\"}, was: %s", w.Body.String())
  295. }
  296. if w.HeaderMap.Get("Content-Type") != "application/json; charset=utf-8" {
  297. t.Errorf("Content-Type should be application/json, was %s", w.HeaderMap.Get("Content-Type"))
  298. }
  299. }
  300. func TestBindingJSONNoContentType(t *testing.T) {
  301. body := bytes.NewBuffer([]byte("{\"foo\":\"bar\"}"))
  302. r := New()
  303. r.POST("/binding/json", func(c *Context) {
  304. var body struct {
  305. Foo string `json:"foo"`
  306. }
  307. if c.Bind(&body) {
  308. c.JSON(200, H{"parsed": body.Foo})
  309. }
  310. })
  311. req, _ := http.NewRequest("POST", "/binding/json", body)
  312. w := httptest.NewRecorder()
  313. r.ServeHTTP(w, req)
  314. if w.Code != 400 {
  315. t.Errorf("Response code should be Bad request, was: %s", w.Code)
  316. }
  317. if w.Body.String() == "{\"parsed\":\"bar\"}\n" {
  318. t.Errorf("Response should not be {\"parsed\":\"bar\"}, was: %s", w.Body.String())
  319. }
  320. if w.HeaderMap.Get("Content-Type") == "application/json" {
  321. t.Errorf("Content-Type should not be application/json, was %s", w.HeaderMap.Get("Content-Type"))
  322. }
  323. }
  324. func TestBindingJSONMalformed(t *testing.T) {
  325. body := bytes.NewBuffer([]byte("\"foo\":\"bar\"\n"))
  326. r := New()
  327. r.POST("/binding/json", func(c *Context) {
  328. var body struct {
  329. Foo string `json:"foo"`
  330. }
  331. if c.Bind(&body) {
  332. c.JSON(200, H{"parsed": body.Foo})
  333. }
  334. })
  335. req, _ := http.NewRequest("POST", "/binding/json", body)
  336. req.Header.Set("Content-Type", "application/json")
  337. w := httptest.NewRecorder()
  338. r.ServeHTTP(w, req)
  339. if w.Code != 400 {
  340. t.Errorf("Response code should be Bad request, was: %s", w.Code)
  341. }
  342. if w.Body.String() == "{\"parsed\":\"bar\"}\n" {
  343. t.Errorf("Response should not be {\"parsed\":\"bar\"}, was: %s", w.Body.String())
  344. }
  345. if w.HeaderMap.Get("Content-Type") == "application/json" {
  346. t.Errorf("Content-Type should not be application/json, was %s", w.HeaderMap.Get("Content-Type"))
  347. }
  348. }