context_test.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447
  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. "github.com/gin-gonic/gin/binding"
  13. "github.com/stretchr/testify/assert"
  14. )
  15. // Unit tests TODO
  16. // func (c *Context) File(filepath string) {
  17. // func (c *Context) Negotiate(code int, config Negotiate) {
  18. // BAD case: func (c *Context) Render(code int, render render.Render, obj ...interface{}) {
  19. // test that information is not leaked when reusing Contexts (using the Pool)
  20. func createTestContext() (c *Context, w *httptest.ResponseRecorder, r *Engine) {
  21. w = httptest.NewRecorder()
  22. r = New()
  23. c = r.allocateContext()
  24. c.reset()
  25. c.writermem.reset(w)
  26. return
  27. }
  28. func TestContextReset(t *testing.T) {
  29. router := New()
  30. c := router.allocateContext()
  31. assert.Equal(t, c.Engine, router)
  32. c.index = 2
  33. c.Writer = &responseWriter{ResponseWriter: httptest.NewRecorder()}
  34. c.Params = Params{Param{}}
  35. c.Error(errors.New("test"), nil)
  36. c.Set("foo", "bar")
  37. c.reset()
  38. assert.False(t, c.IsAborted())
  39. assert.Nil(t, c.Keys)
  40. assert.Nil(t, c.Accepted)
  41. assert.Len(t, c.Errors, 0)
  42. assert.Empty(t, c.Errors.Errors())
  43. assert.Empty(t, c.Errors.ByType(ErrorTypeAny))
  44. assert.Len(t, c.Params, 0)
  45. assert.Equal(t, c.index, -1)
  46. assert.Equal(t, c.Writer.(*responseWriter), &c.writermem)
  47. }
  48. // TestContextSetGet tests that a parameter is set correctly on the
  49. // current context and can be retrieved using Get.
  50. func TestContextSetGet(t *testing.T) {
  51. c, _, _ := createTestContext()
  52. c.Set("foo", "bar")
  53. value, err := c.Get("foo")
  54. assert.Equal(t, value, "bar")
  55. assert.True(t, err)
  56. value, err = c.Get("foo2")
  57. assert.Nil(t, value)
  58. assert.False(t, err)
  59. assert.Equal(t, c.MustGet("foo"), "bar")
  60. assert.Panics(t, func() { c.MustGet("no_exist") })
  61. }
  62. func TestContextSetGetValues(t *testing.T) {
  63. c, _, _ := createTestContext()
  64. c.Set("string", "this is a string")
  65. c.Set("int32", int32(-42))
  66. c.Set("int64", int64(42424242424242))
  67. c.Set("uint64", uint64(42))
  68. c.Set("float32", float32(4.2))
  69. c.Set("float64", 4.2)
  70. var a interface{} = 1
  71. c.Set("intInterface", a)
  72. assert.Exactly(t, c.MustGet("string").(string), "this is a string")
  73. assert.Exactly(t, c.MustGet("int32").(int32), int32(-42))
  74. assert.Exactly(t, c.MustGet("int64").(int64), int64(42424242424242))
  75. assert.Exactly(t, c.MustGet("uint64").(uint64), uint64(42))
  76. assert.Exactly(t, c.MustGet("float32").(float32), float32(4.2))
  77. assert.Exactly(t, c.MustGet("float64").(float64), 4.2)
  78. assert.Exactly(t, c.MustGet("intInterface").(int), 1)
  79. }
  80. func TestContextCopy(t *testing.T) {
  81. c, _, _ := createTestContext()
  82. c.index = 2
  83. c.Request, _ = http.NewRequest("POST", "/hola", nil)
  84. c.handlers = HandlersChain{func(c *Context) {}}
  85. c.Params = Params{Param{Key: "foo", Value: "bar"}}
  86. c.Set("foo", "bar")
  87. cp := c.Copy()
  88. assert.Nil(t, cp.handlers)
  89. assert.Nil(t, cp.writermem.ResponseWriter)
  90. assert.Equal(t, &cp.writermem, cp.Writer.(*responseWriter))
  91. assert.Equal(t, cp.Request, c.Request)
  92. assert.Equal(t, cp.index, AbortIndex)
  93. assert.Equal(t, cp.Keys, c.Keys)
  94. assert.Equal(t, cp.Engine, c.Engine)
  95. assert.Equal(t, cp.Params, c.Params)
  96. }
  97. func TestContextFormParse(t *testing.T) {
  98. c, _, _ := createTestContext()
  99. c.Request, _ = http.NewRequest("GET", "http://example.com/?foo=bar&page=10", nil)
  100. assert.Equal(t, c.DefaultFormValue("foo", "none"), "bar")
  101. assert.Equal(t, c.FormValue("foo"), "bar")
  102. assert.Empty(t, c.PostFormValue("foo"))
  103. assert.Equal(t, c.DefaultFormValue("page", "0"), "10")
  104. assert.Equal(t, c.FormValue("page"), "10")
  105. assert.Empty(t, c.PostFormValue("page"))
  106. assert.Equal(t, c.DefaultFormValue("NoKey", "nada"), "nada")
  107. assert.Empty(t, c.FormValue("NoKey"))
  108. assert.Empty(t, c.PostFormValue("NoKey"))
  109. }
  110. func TestContextPostFormParse(t *testing.T) {
  111. c, _, _ := createTestContext()
  112. body := bytes.NewBufferString("foo=bar&page=11&both=POST")
  113. c.Request, _ = http.NewRequest("POST", "http://example.com/?both=GET&id=main", body)
  114. c.Request.Header.Add("Content-Type", MIMEPOSTForm)
  115. assert.Equal(t, c.DefaultPostFormValue("foo", "none"), "bar")
  116. assert.Equal(t, c.PostFormValue("foo"), "bar")
  117. assert.Equal(t, c.FormValue("foo"), "bar")
  118. assert.Equal(t, c.DefaultPostFormValue("page", "0"), "11")
  119. assert.Equal(t, c.PostFormValue("page"), "11")
  120. assert.Equal(t, c.FormValue("page"), "11")
  121. assert.Equal(t, c.PostFormValue("both"), "POST")
  122. assert.Equal(t, c.FormValue("both"), "POST")
  123. assert.Equal(t, c.FormValue("id"), "main")
  124. assert.Empty(t, c.PostFormValue("id"))
  125. assert.Equal(t, c.DefaultPostFormValue("NoKey", "nada"), "nada")
  126. assert.Empty(t, c.PostFormValue("NoKey"))
  127. assert.Empty(t, c.FormValue("NoKey"))
  128. }
  129. // Tests that the response is serialized as JSON
  130. // and Content-Type is set to application/json
  131. func TestContextRenderJSON(t *testing.T) {
  132. c, w, _ := createTestContext()
  133. c.JSON(201, H{"foo": "bar"})
  134. assert.Equal(t, w.Code, 201)
  135. assert.Equal(t, w.Body.String(), "{\"foo\":\"bar\"}\n")
  136. assert.Equal(t, w.HeaderMap.Get("Content-Type"), "application/json; charset=utf-8")
  137. }
  138. // Tests that the response is serialized as JSON
  139. // and Content-Type is set to application/json
  140. func TestContextRenderIndentedJSON(t *testing.T) {
  141. c, w, _ := createTestContext()
  142. c.IndentedJSON(201, H{"foo": "bar", "bar": "foo", "nested": H{"foo": "bar"}})
  143. assert.Equal(t, w.Code, 201)
  144. assert.Equal(t, w.Body.String(), "{\n \"bar\": \"foo\",\n \"foo\": \"bar\",\n \"nested\": {\n \"foo\": \"bar\"\n }\n}")
  145. assert.Equal(t, w.HeaderMap.Get("Content-Type"), "application/json; charset=utf-8")
  146. }
  147. // Tests that the response executes the templates
  148. // and responds with Content-Type set to text/html
  149. func TestContextRenderHTML(t *testing.T) {
  150. c, w, router := createTestContext()
  151. templ := template.Must(template.New("t").Parse(`Hello {{.name}}`))
  152. router.SetHTMLTemplate(templ)
  153. c.HTML(201, "t", H{"name": "alexandernyquist"})
  154. assert.Equal(t, w.Code, 201)
  155. assert.Equal(t, w.Body.String(), "Hello alexandernyquist")
  156. assert.Equal(t, w.HeaderMap.Get("Content-Type"), "text/html; charset=utf-8")
  157. }
  158. // TestContextXML tests that the response is serialized as XML
  159. // and Content-Type is set to application/xml
  160. func TestContextRenderXML(t *testing.T) {
  161. c, w, _ := createTestContext()
  162. c.XML(201, H{"foo": "bar"})
  163. assert.Equal(t, w.Code, 201)
  164. assert.Equal(t, w.Body.String(), "<map><foo>bar</foo></map>")
  165. assert.Equal(t, w.HeaderMap.Get("Content-Type"), "application/xml; charset=utf-8")
  166. }
  167. // TestContextString tests that the response is returned
  168. // with Content-Type set to text/plain
  169. func TestContextRenderString(t *testing.T) {
  170. c, w, _ := createTestContext()
  171. c.String(201, "test %s %d", "string", 2)
  172. assert.Equal(t, w.Code, 201)
  173. assert.Equal(t, w.Body.String(), "test string 2")
  174. assert.Equal(t, w.HeaderMap.Get("Content-Type"), "text/plain; charset=utf-8")
  175. }
  176. // TestContextString tests that the response is returned
  177. // with Content-Type set to text/html
  178. func TestContextRenderHTMLString(t *testing.T) {
  179. c, w, _ := createTestContext()
  180. c.Header("Content-Type", "text/html; charset=utf-8")
  181. c.String(201, "<html>%s %d</html>", "string", 3)
  182. assert.Equal(t, w.Code, 201)
  183. assert.Equal(t, w.Body.String(), "<html>string 3</html>")
  184. assert.Equal(t, w.HeaderMap.Get("Content-Type"), "text/html; charset=utf-8")
  185. }
  186. // TestContextData tests that the response can be written from `bytesting`
  187. // with specified MIME type
  188. func TestContextRenderData(t *testing.T) {
  189. c, w, _ := createTestContext()
  190. c.Data(201, "text/csv", []byte(`foo,bar`))
  191. assert.Equal(t, w.Code, 201)
  192. assert.Equal(t, w.Body.String(), "foo,bar")
  193. assert.Equal(t, w.HeaderMap.Get("Content-Type"), "text/csv")
  194. }
  195. func TestContextHeaders(t *testing.T) {
  196. c, _, _ := createTestContext()
  197. c.Header("Content-Type", "text/plain")
  198. c.Header("X-Custom", "value")
  199. assert.Equal(t, c.Writer.Header().Get("Content-Type"), "text/plain")
  200. assert.Equal(t, c.Writer.Header().Get("X-Custom"), "value")
  201. c.Header("Content-Type", "text/html")
  202. c.Header("X-Custom", "")
  203. assert.Equal(t, c.Writer.Header().Get("Content-Type"), "text/html")
  204. _, exist := c.Writer.Header()["X-Custom"]
  205. assert.False(t, exist)
  206. }
  207. // TODO
  208. func TestContextRenderRedirectWithRelativePath(t *testing.T) {
  209. c, w, _ := createTestContext()
  210. c.Request, _ = http.NewRequest("POST", "http://example.com", nil)
  211. assert.Panics(t, func() { c.Redirect(299, "/new_path") })
  212. assert.Panics(t, func() { c.Redirect(309, "/new_path") })
  213. c.Redirect(302, "/path")
  214. c.Writer.WriteHeaderNow()
  215. assert.Equal(t, w.Code, 302)
  216. assert.Equal(t, w.Header().Get("Location"), "/path")
  217. }
  218. func TestContextRenderRedirectWithAbsolutePath(t *testing.T) {
  219. c, w, _ := createTestContext()
  220. c.Request, _ = http.NewRequest("POST", "http://example.com", nil)
  221. c.Redirect(302, "http://google.com")
  222. c.Writer.WriteHeaderNow()
  223. assert.Equal(t, w.Code, 302)
  224. assert.Equal(t, w.Header().Get("Location"), "http://google.com")
  225. }
  226. func TestContextNegotiationFormat(t *testing.T) {
  227. c, _, _ := createTestContext()
  228. c.Request, _ = http.NewRequest("POST", "", nil)
  229. assert.Panics(t, func() { c.NegotiateFormat() })
  230. assert.Equal(t, c.NegotiateFormat(MIMEJSON, MIMEXML), MIMEJSON)
  231. assert.Equal(t, c.NegotiateFormat(MIMEHTML, MIMEJSON), MIMEHTML)
  232. }
  233. func TestContextNegotiationFormatWithAccept(t *testing.T) {
  234. c, _, _ := createTestContext()
  235. c.Request, _ = http.NewRequest("POST", "", nil)
  236. c.Request.Header.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
  237. assert.Equal(t, c.NegotiateFormat(MIMEJSON, MIMEXML), MIMEXML)
  238. assert.Equal(t, c.NegotiateFormat(MIMEXML, MIMEHTML), MIMEHTML)
  239. assert.Equal(t, c.NegotiateFormat(MIMEJSON), "")
  240. }
  241. func TestContextNegotiationFormatCustum(t *testing.T) {
  242. c, _, _ := createTestContext()
  243. c.Request, _ = http.NewRequest("POST", "", nil)
  244. c.Request.Header.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
  245. c.Accepted = nil
  246. c.SetAccepted(MIMEJSON, MIMEXML)
  247. assert.Equal(t, c.NegotiateFormat(MIMEJSON, MIMEXML), MIMEJSON)
  248. assert.Equal(t, c.NegotiateFormat(MIMEXML, MIMEHTML), MIMEXML)
  249. assert.Equal(t, c.NegotiateFormat(MIMEJSON), MIMEJSON)
  250. }
  251. // TestContextData tests that the response can be written from `bytesting`
  252. // with specified MIME type
  253. func TestContextAbortWithStatus(t *testing.T) {
  254. c, w, _ := createTestContext()
  255. c.index = 4
  256. c.AbortWithStatus(401)
  257. c.Writer.WriteHeaderNow()
  258. assert.Equal(t, c.index, AbortIndex)
  259. assert.Equal(t, c.Writer.Status(), 401)
  260. assert.Equal(t, w.Code, 401)
  261. assert.True(t, c.IsAborted())
  262. }
  263. func TestContextError(t *testing.T) {
  264. c, _, _ := createTestContext()
  265. assert.Nil(t, c.LastError())
  266. assert.Empty(t, c.Errors.String())
  267. c.Error(errors.New("first error"), "some data")
  268. assert.Equal(t, c.LastError().Error(), "first error")
  269. assert.Len(t, c.Errors, 1)
  270. assert.Equal(t, c.Errors.String(), "Error #01: first error\n Meta: some data\n")
  271. c.Error(errors.New("second error"), "some data 2")
  272. assert.Equal(t, c.LastError().Error(), "second error")
  273. assert.Len(t, c.Errors, 2)
  274. assert.Equal(t, c.Errors.String(), "Error #01: first error\n Meta: some data\n"+
  275. "Error #02: second error\n Meta: some data 2\n")
  276. assert.Equal(t, c.Errors[0].Error, errors.New("first error"))
  277. assert.Equal(t, c.Errors[0].Meta, "some data")
  278. assert.Equal(t, c.Errors[0].Flags, ErrorTypeExternal)
  279. assert.Equal(t, c.Errors[1].Error, errors.New("second error"))
  280. assert.Equal(t, c.Errors[1].Meta, "some data 2")
  281. assert.Equal(t, c.Errors[1].Flags, ErrorTypeExternal)
  282. }
  283. func TestContextTypedError(t *testing.T) {
  284. c, _, _ := createTestContext()
  285. c.ErrorTyped(errors.New("externo 0"), ErrorTypeExternal, nil)
  286. c.ErrorTyped(errors.New("externo 1"), ErrorTypeExternal, nil)
  287. c.ErrorTyped(errors.New("interno 0"), ErrorTypeInternal, nil)
  288. c.ErrorTyped(errors.New("externo 2"), ErrorTypeExternal, nil)
  289. c.ErrorTyped(errors.New("interno 1"), ErrorTypeInternal, nil)
  290. c.ErrorTyped(errors.New("interno 2"), ErrorTypeInternal, nil)
  291. for _, err := range c.Errors.ByType(ErrorTypeExternal) {
  292. assert.Equal(t, err.Flags, ErrorTypeExternal)
  293. }
  294. for _, err := range c.Errors.ByType(ErrorTypeInternal) {
  295. assert.Equal(t, err.Flags, ErrorTypeInternal)
  296. }
  297. assert.Equal(t, c.Errors.Errors(), []string{"externo 0", "externo 1", "interno 0", "externo 2", "interno 1", "interno 2"})
  298. }
  299. func TestContextFail(t *testing.T) {
  300. c, w, _ := createTestContext()
  301. c.Fail(401, errors.New("bad input"))
  302. c.Writer.WriteHeaderNow()
  303. assert.Equal(t, w.Code, 401)
  304. assert.Equal(t, c.LastError().Error(), "bad input")
  305. assert.Equal(t, c.index, AbortIndex)
  306. assert.True(t, c.IsAborted())
  307. }
  308. func TestContextClientIP(t *testing.T) {
  309. c, _, _ := createTestContext()
  310. c.Request, _ = http.NewRequest("POST", "", nil)
  311. c.Request.Header.Set("X-Real-IP", "10.10.10.10")
  312. c.Request.Header.Set("X-Forwarded-For", "20.20.20.20 , 30.30.30.30")
  313. c.Request.RemoteAddr = "40.40.40.40"
  314. assert.Equal(t, c.ClientIP(), "10.10.10.10")
  315. c.Request.Header.Del("X-Real-IP")
  316. assert.Equal(t, c.ClientIP(), "20.20.20.20")
  317. c.Request.Header.Del("X-Forwarded-For")
  318. assert.Equal(t, c.ClientIP(), "40.40.40.40")
  319. }
  320. func TestContextContentType(t *testing.T) {
  321. c, _, _ := createTestContext()
  322. c.Request, _ = http.NewRequest("POST", "", nil)
  323. c.Request.Header.Set("Content-Type", "application/json; charset=utf-8")
  324. assert.Equal(t, c.ContentType(), "application/json")
  325. }
  326. func TestContextAutoBind(t *testing.T) {
  327. c, w, _ := createTestContext()
  328. c.Request, _ = http.NewRequest("POST", "http://example.com", bytes.NewBufferString("{\"foo\":\"bar\", \"bar\":\"foo\"}"))
  329. c.Request.Header.Add("Content-Type", MIMEJSON)
  330. var obj struct {
  331. Foo string `json:"foo"`
  332. Bar string `json:"bar"`
  333. }
  334. assert.True(t, c.Bind(&obj))
  335. assert.Equal(t, obj.Bar, "foo")
  336. assert.Equal(t, obj.Foo, "bar")
  337. assert.Equal(t, w.Body.Len(), 0)
  338. }
  339. func TestContextBadAutoBind(t *testing.T) {
  340. c, w, _ := createTestContext()
  341. c.Request, _ = http.NewRequest("POST", "http://example.com", bytes.NewBufferString("\"foo\":\"bar\", \"bar\":\"foo\"}"))
  342. c.Request.Header.Add("Content-Type", MIMEJSON)
  343. var obj struct {
  344. Foo string `json:"foo"`
  345. Bar string `json:"bar"`
  346. }
  347. assert.False(t, c.IsAborted())
  348. assert.False(t, c.Bind(&obj))
  349. c.Writer.WriteHeaderNow()
  350. assert.Empty(t, obj.Bar)
  351. assert.Empty(t, obj.Foo)
  352. assert.Equal(t, w.Code, 400)
  353. assert.True(t, c.IsAborted())
  354. }
  355. func TestContextBindWith(t *testing.T) {
  356. c, w, _ := createTestContext()
  357. c.Request, _ = http.NewRequest("POST", "http://example.com", bytes.NewBufferString("{\"foo\":\"bar\", \"bar\":\"foo\"}"))
  358. c.Request.Header.Add("Content-Type", MIMEXML)
  359. var obj struct {
  360. Foo string `json:"foo"`
  361. Bar string `json:"bar"`
  362. }
  363. assert.True(t, c.BindWith(&obj, binding.JSON))
  364. assert.Equal(t, obj.Bar, "foo")
  365. assert.Equal(t, obj.Foo, "bar")
  366. assert.Equal(t, w.Body.Len(), 0)
  367. }