context_test.go 14 KB

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