context_test.go 9.9 KB

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