context_test.go 9.8 KB

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