context_test.go 10 KB

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