context_test.go 13 KB

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