context_test.go 12 KB

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