context_test.go 11 KB

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