context_test.go 15 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494
  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. "time"
  13. "github.com/gin-gonic/gin/binding"
  14. "github.com/manucorporat/sse"
  15. "github.com/stretchr/testify/assert"
  16. )
  17. // Unit tests TODO
  18. // func (c *Context) File(filepath string) {
  19. // func (c *Context) Negotiate(code int, config Negotiate) {
  20. // BAD case: func (c *Context) Render(code int, render render.Render, obj ...interface{}) {
  21. // test that information is not leaked when reusing Contexts (using the Pool)
  22. func createTestContext() (c *Context, w *httptest.ResponseRecorder, r *Engine) {
  23. w = httptest.NewRecorder()
  24. r = New()
  25. c = r.allocateContext()
  26. c.reset()
  27. c.writermem.reset(w)
  28. return
  29. }
  30. func TestContextReset(t *testing.T) {
  31. router := New()
  32. c := router.allocateContext()
  33. assert.Equal(t, c.engine, router)
  34. c.index = 2
  35. c.Writer = &responseWriter{ResponseWriter: httptest.NewRecorder()}
  36. c.Params = Params{Param{}}
  37. c.Error(errors.New("test"))
  38. c.Set("foo", "bar")
  39. c.reset()
  40. assert.False(t, c.IsAborted())
  41. assert.Nil(t, c.Keys)
  42. assert.Nil(t, c.Accepted)
  43. assert.Len(t, c.Errors, 0)
  44. assert.Empty(t, c.Errors.Errors())
  45. assert.Empty(t, c.Errors.ByType(ErrorTypeAny))
  46. assert.Len(t, c.Params, 0)
  47. assert.Equal(t, c.index, -1)
  48. assert.Equal(t, c.Writer.(*responseWriter), &c.writermem)
  49. }
  50. // TestContextSetGet tests that a parameter is set correctly on the
  51. // current context and can be retrieved using Get.
  52. func TestContextSetGet(t *testing.T) {
  53. c, _, _ := createTestContext()
  54. c.Set("foo", "bar")
  55. value, err := c.Get("foo")
  56. assert.Equal(t, value, "bar")
  57. assert.True(t, err)
  58. value, err = c.Get("foo2")
  59. assert.Nil(t, value)
  60. assert.False(t, err)
  61. assert.Equal(t, c.MustGet("foo"), "bar")
  62. assert.Panics(t, func() { c.MustGet("no_exist") })
  63. }
  64. func TestContextSetGetValues(t *testing.T) {
  65. c, _, _ := createTestContext()
  66. c.Set("string", "this is a string")
  67. c.Set("int32", int32(-42))
  68. c.Set("int64", int64(42424242424242))
  69. c.Set("uint64", uint64(42))
  70. c.Set("float32", float32(4.2))
  71. c.Set("float64", 4.2)
  72. var a interface{} = 1
  73. c.Set("intInterface", a)
  74. assert.Exactly(t, c.MustGet("string").(string), "this is a string")
  75. assert.Exactly(t, c.MustGet("int32").(int32), int32(-42))
  76. assert.Exactly(t, c.MustGet("int64").(int64), int64(42424242424242))
  77. assert.Exactly(t, c.MustGet("uint64").(uint64), uint64(42))
  78. assert.Exactly(t, c.MustGet("float32").(float32), float32(4.2))
  79. assert.Exactly(t, c.MustGet("float64").(float64), 4.2)
  80. assert.Exactly(t, c.MustGet("intInterface").(int), 1)
  81. }
  82. func TestContextCopy(t *testing.T) {
  83. c, _, _ := createTestContext()
  84. c.index = 2
  85. c.Request, _ = http.NewRequest("POST", "/hola", nil)
  86. c.handlers = HandlersChain{func(c *Context) {}}
  87. c.Params = Params{Param{Key: "foo", Value: "bar"}}
  88. c.Set("foo", "bar")
  89. cp := c.Copy()
  90. assert.Nil(t, cp.handlers)
  91. assert.Nil(t, cp.writermem.ResponseWriter)
  92. assert.Equal(t, &cp.writermem, cp.Writer.(*responseWriter))
  93. assert.Equal(t, cp.Request, c.Request)
  94. assert.Equal(t, cp.index, AbortIndex)
  95. assert.Equal(t, cp.Keys, c.Keys)
  96. assert.Equal(t, cp.engine, c.engine)
  97. assert.Equal(t, cp.Params, c.Params)
  98. }
  99. func TestContextFormParse(t *testing.T) {
  100. c, _, _ := createTestContext()
  101. c.Request, _ = http.NewRequest("GET", "http://example.com/?foo=bar&page=10", nil)
  102. assert.Equal(t, c.DefaultFormValue("foo", "none"), "bar")
  103. assert.Equal(t, c.FormValue("foo"), "bar")
  104. assert.Empty(t, c.PostFormValue("foo"))
  105. assert.Equal(t, c.DefaultFormValue("page", "0"), "10")
  106. assert.Equal(t, c.FormValue("page"), "10")
  107. assert.Empty(t, c.PostFormValue("page"))
  108. assert.Equal(t, c.DefaultFormValue("NoKey", "nada"), "nada")
  109. assert.Empty(t, c.FormValue("NoKey"))
  110. assert.Empty(t, c.PostFormValue("NoKey"))
  111. }
  112. func TestContextPostFormParse(t *testing.T) {
  113. c, _, _ := createTestContext()
  114. body := bytes.NewBufferString("foo=bar&page=11&both=POST")
  115. c.Request, _ = http.NewRequest("POST", "/?both=GET&id=main", body)
  116. c.Request.Header.Add("Content-Type", MIMEPOSTForm)
  117. assert.Equal(t, c.DefaultPostFormValue("foo", "none"), "bar")
  118. assert.Equal(t, c.PostFormValue("foo"), "bar")
  119. assert.Empty(t, c.FormValue("foo"))
  120. assert.Equal(t, c.DefaultPostForm("page", "0"), "11")
  121. assert.Equal(t, c.PostForm("page"), "11")
  122. assert.Equal(t, c.InputQuery("page"), "")
  123. assert.Equal(t, c.PostFormValue("both"), "POST")
  124. assert.Equal(t, c.FormValue("both"), "GET")
  125. assert.Equal(t, c.FormValue("id"), "main")
  126. assert.Empty(t, c.PostFormValue("id"))
  127. assert.Equal(t, c.DefaultPostFormValue("NoKey", "nada"), "nada")
  128. assert.Empty(t, c.PostFormValue("NoKey"))
  129. assert.Empty(t, c.FormValue("NoKey"))
  130. c.Param("page")
  131. c.Query("page")
  132. c.PostForm("page")
  133. }
  134. // Tests that the response is serialized as JSON
  135. // and Content-Type is set to application/json
  136. func TestContextRenderJSON(t *testing.T) {
  137. c, w, _ := createTestContext()
  138. c.JSON(201, H{"foo": "bar"})
  139. assert.Equal(t, w.Code, 201)
  140. assert.Equal(t, w.Body.String(), "{\"foo\":\"bar\"}\n")
  141. assert.Equal(t, w.HeaderMap.Get("Content-Type"), "application/json; charset=utf-8")
  142. }
  143. // Tests that the response is serialized as JSON
  144. // and Content-Type is set to application/json
  145. func TestContextRenderIndentedJSON(t *testing.T) {
  146. c, w, _ := createTestContext()
  147. c.IndentedJSON(201, H{"foo": "bar", "bar": "foo", "nested": H{"foo": "bar"}})
  148. assert.Equal(t, w.Code, 201)
  149. assert.Equal(t, w.Body.String(), "{\n \"bar\": \"foo\",\n \"foo\": \"bar\",\n \"nested\": {\n \"foo\": \"bar\"\n }\n}")
  150. assert.Equal(t, w.HeaderMap.Get("Content-Type"), "application/json; charset=utf-8")
  151. }
  152. // Tests that the response executes the templates
  153. // and responds with Content-Type set to text/html
  154. func TestContextRenderHTML(t *testing.T) {
  155. c, w, router := createTestContext()
  156. templ := template.Must(template.New("t").Parse(`Hello {{.name}}`))
  157. router.SetHTMLTemplate(templ)
  158. c.HTML(201, "t", H{"name": "alexandernyquist"})
  159. assert.Equal(t, w.Code, 201)
  160. assert.Equal(t, w.Body.String(), "Hello alexandernyquist")
  161. assert.Equal(t, w.HeaderMap.Get("Content-Type"), "text/html; charset=utf-8")
  162. }
  163. // TestContextXML tests that the response is serialized as XML
  164. // and Content-Type is set to application/xml
  165. func TestContextRenderXML(t *testing.T) {
  166. c, w, _ := createTestContext()
  167. c.XML(201, H{"foo": "bar"})
  168. assert.Equal(t, w.Code, 201)
  169. assert.Equal(t, w.Body.String(), "<map><foo>bar</foo></map>")
  170. assert.Equal(t, w.HeaderMap.Get("Content-Type"), "application/xml; charset=utf-8")
  171. }
  172. // TestContextString tests that the response is returned
  173. // with Content-Type set to text/plain
  174. func TestContextRenderString(t *testing.T) {
  175. c, w, _ := createTestContext()
  176. c.String(201, "test %s %d", "string", 2)
  177. assert.Equal(t, w.Code, 201)
  178. assert.Equal(t, w.Body.String(), "test string 2")
  179. assert.Equal(t, w.HeaderMap.Get("Content-Type"), "text/plain; charset=utf-8")
  180. }
  181. // TestContextString tests that the response is returned
  182. // with Content-Type set to text/html
  183. func TestContextRenderHTMLString(t *testing.T) {
  184. c, w, _ := createTestContext()
  185. c.Header("Content-Type", "text/html; charset=utf-8")
  186. c.String(201, "<html>%s %d</html>", "string", 3)
  187. assert.Equal(t, w.Code, 201)
  188. assert.Equal(t, w.Body.String(), "<html>string 3</html>")
  189. assert.Equal(t, w.HeaderMap.Get("Content-Type"), "text/html; charset=utf-8")
  190. }
  191. // TestContextData tests that the response can be written from `bytesting`
  192. // with specified MIME type
  193. func TestContextRenderData(t *testing.T) {
  194. c, w, _ := createTestContext()
  195. c.Data(201, "text/csv", []byte(`foo,bar`))
  196. assert.Equal(t, w.Code, 201)
  197. assert.Equal(t, w.Body.String(), "foo,bar")
  198. assert.Equal(t, w.HeaderMap.Get("Content-Type"), "text/csv")
  199. }
  200. func TestContextRenderSSE(t *testing.T) {
  201. c, w, _ := createTestContext()
  202. c.SSEvent("float", 1.5)
  203. c.Render(-1, sse.Event{
  204. Id: "123",
  205. Data: "text",
  206. })
  207. c.SSEvent("chat", H{
  208. "foo": "bar",
  209. "bar": "foo",
  210. })
  211. assert.Equal(t, w.Body.String(), "event: float\ndata: 1.5\n\nid: 123\ndata: text\n\nevent: chat\ndata: {\"bar\":\"foo\",\"foo\":\"bar\"}\n\n")
  212. }
  213. func TestContextRenderFile(t *testing.T) {
  214. c, w, _ := createTestContext()
  215. c.Request, _ = http.NewRequest("GET", "/", nil)
  216. c.File("./gin.go")
  217. assert.Equal(t, w.Code, 200)
  218. assert.Contains(t, w.Body.String(), "func New() *Engine {")
  219. assert.Equal(t, w.HeaderMap.Get("Content-Type"), "text/plain; charset=utf-8")
  220. }
  221. func TestContextHeaders(t *testing.T) {
  222. c, _, _ := createTestContext()
  223. c.Header("Content-Type", "text/plain")
  224. c.Header("X-Custom", "value")
  225. assert.Equal(t, c.Writer.Header().Get("Content-Type"), "text/plain")
  226. assert.Equal(t, c.Writer.Header().Get("X-Custom"), "value")
  227. c.Header("Content-Type", "text/html")
  228. c.Header("X-Custom", "")
  229. assert.Equal(t, c.Writer.Header().Get("Content-Type"), "text/html")
  230. _, exist := c.Writer.Header()["X-Custom"]
  231. assert.False(t, exist)
  232. }
  233. // TODO
  234. func TestContextRenderRedirectWithRelativePath(t *testing.T) {
  235. c, w, _ := createTestContext()
  236. c.Request, _ = http.NewRequest("POST", "http://example.com", nil)
  237. assert.Panics(t, func() { c.Redirect(299, "/new_path") })
  238. assert.Panics(t, func() { c.Redirect(309, "/new_path") })
  239. c.Redirect(302, "/path")
  240. c.Writer.WriteHeaderNow()
  241. assert.Equal(t, w.Code, 302)
  242. assert.Equal(t, w.Header().Get("Location"), "/path")
  243. }
  244. func TestContextRenderRedirectWithAbsolutePath(t *testing.T) {
  245. c, w, _ := createTestContext()
  246. c.Request, _ = http.NewRequest("POST", "http://example.com", nil)
  247. c.Redirect(302, "http://google.com")
  248. c.Writer.WriteHeaderNow()
  249. assert.Equal(t, w.Code, 302)
  250. assert.Equal(t, w.Header().Get("Location"), "http://google.com")
  251. }
  252. func TestContextNegotiationFormat(t *testing.T) {
  253. c, _, _ := createTestContext()
  254. c.Request, _ = http.NewRequest("POST", "", nil)
  255. assert.Panics(t, func() { c.NegotiateFormat() })
  256. assert.Equal(t, c.NegotiateFormat(MIMEJSON, MIMEXML), MIMEJSON)
  257. assert.Equal(t, c.NegotiateFormat(MIMEHTML, MIMEJSON), MIMEHTML)
  258. }
  259. func TestContextNegotiationFormatWithAccept(t *testing.T) {
  260. c, _, _ := createTestContext()
  261. c.Request, _ = http.NewRequest("POST", "/", nil)
  262. c.Request.Header.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
  263. assert.Equal(t, c.NegotiateFormat(MIMEJSON, MIMEXML), MIMEXML)
  264. assert.Equal(t, c.NegotiateFormat(MIMEXML, MIMEHTML), MIMEHTML)
  265. assert.Equal(t, c.NegotiateFormat(MIMEJSON), "")
  266. }
  267. func TestContextNegotiationFormatCustum(t *testing.T) {
  268. c, _, _ := createTestContext()
  269. c.Request, _ = http.NewRequest("POST", "/", nil)
  270. c.Request.Header.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
  271. c.Accepted = nil
  272. c.SetAccepted(MIMEJSON, MIMEXML)
  273. assert.Equal(t, c.NegotiateFormat(MIMEJSON, MIMEXML), MIMEJSON)
  274. assert.Equal(t, c.NegotiateFormat(MIMEXML, MIMEHTML), MIMEXML)
  275. assert.Equal(t, c.NegotiateFormat(MIMEJSON), MIMEJSON)
  276. }
  277. // TestContextData tests that the response can be written from `bytesting`
  278. // with specified MIME type
  279. func TestContextAbortWithStatus(t *testing.T) {
  280. c, w, _ := createTestContext()
  281. c.index = 4
  282. c.AbortWithStatus(401)
  283. c.Writer.WriteHeaderNow()
  284. assert.Equal(t, c.index, AbortIndex)
  285. assert.Equal(t, c.Writer.Status(), 401)
  286. assert.Equal(t, w.Code, 401)
  287. assert.True(t, c.IsAborted())
  288. }
  289. func TestContextError(t *testing.T) {
  290. c, _, _ := createTestContext()
  291. assert.Empty(t, c.Errors)
  292. c.Error(errors.New("first error"))
  293. assert.Len(t, c.Errors, 1)
  294. assert.Equal(t, c.Errors.String(), "Error #01: first error\n")
  295. c.Error(&Error{
  296. Err: errors.New("second error"),
  297. Meta: "some data 2",
  298. Type: ErrorTypePublic,
  299. })
  300. assert.Len(t, c.Errors, 2)
  301. assert.Equal(t, c.Errors[0].Err, errors.New("first error"))
  302. assert.Nil(t, c.Errors[0].Meta)
  303. assert.Equal(t, c.Errors[0].Type, ErrorTypePrivate)
  304. assert.Equal(t, c.Errors[1].Err, errors.New("second error"))
  305. assert.Equal(t, c.Errors[1].Meta, "some data 2")
  306. assert.Equal(t, c.Errors[1].Type, ErrorTypePublic)
  307. assert.Equal(t, c.Errors.Last(), c.Errors[1])
  308. }
  309. func TestContextTypedError(t *testing.T) {
  310. c, _, _ := createTestContext()
  311. c.Error(errors.New("externo 0")).SetType(ErrorTypePublic)
  312. c.Error(errors.New("interno 0")).SetType(ErrorTypePrivate)
  313. for _, err := range c.Errors.ByType(ErrorTypePublic) {
  314. assert.Equal(t, err.Type, ErrorTypePublic)
  315. }
  316. for _, err := range c.Errors.ByType(ErrorTypePrivate) {
  317. assert.Equal(t, err.Type, ErrorTypePrivate)
  318. }
  319. assert.Equal(t, c.Errors.Errors(), []string{"externo 0", "interno 0"})
  320. }
  321. func TestContextAbortWithError(t *testing.T) {
  322. c, w, _ := createTestContext()
  323. c.AbortWithError(401, errors.New("bad input")).SetMeta("some input")
  324. c.Writer.WriteHeaderNow()
  325. assert.Equal(t, w.Code, 401)
  326. assert.Equal(t, c.index, AbortIndex)
  327. assert.True(t, c.IsAborted())
  328. }
  329. func TestContextClientIP(t *testing.T) {
  330. c, _, _ := createTestContext()
  331. c.Request, _ = http.NewRequest("POST", "/", nil)
  332. c.Request.Header.Set("X-Real-IP", " 10.10.10.10 ")
  333. c.Request.Header.Set("X-Forwarded-For", " 20.20.20.20 , 30.30.30.30")
  334. c.Request.RemoteAddr = " 40.40.40.40 "
  335. assert.Equal(t, c.ClientIP(), "10.10.10.10")
  336. c.Request.Header.Del("X-Real-IP")
  337. assert.Equal(t, c.ClientIP(), "20.20.20.20")
  338. c.Request.Header.Set("X-Forwarded-For", "30.30.30.30")
  339. assert.Equal(t, c.ClientIP(), "30.30.30.30")
  340. c.Request.Header.Del("X-Forwarded-For")
  341. assert.Equal(t, c.ClientIP(), "40.40.40.40")
  342. }
  343. func TestContextContentType(t *testing.T) {
  344. c, _, _ := createTestContext()
  345. c.Request, _ = http.NewRequest("POST", "/", nil)
  346. c.Request.Header.Set("Content-Type", "application/json; charset=utf-8")
  347. assert.Equal(t, c.ContentType(), "application/json")
  348. }
  349. func TestContextAutoBind(t *testing.T) {
  350. c, w, _ := createTestContext()
  351. c.Request, _ = http.NewRequest("POST", "/", bytes.NewBufferString("{\"foo\":\"bar\", \"bar\":\"foo\"}"))
  352. c.Request.Header.Add("Content-Type", MIMEJSON)
  353. var obj struct {
  354. Foo string `json:"foo"`
  355. Bar string `json:"bar"`
  356. }
  357. assert.NoError(t, c.Bind(&obj))
  358. assert.Equal(t, obj.Bar, "foo")
  359. assert.Equal(t, obj.Foo, "bar")
  360. assert.Equal(t, w.Body.Len(), 0)
  361. }
  362. func TestContextBadAutoBind(t *testing.T) {
  363. c, w, _ := createTestContext()
  364. c.Request, _ = http.NewRequest("POST", "http://example.com", bytes.NewBufferString("\"foo\":\"bar\", \"bar\":\"foo\"}"))
  365. c.Request.Header.Add("Content-Type", MIMEJSON)
  366. var obj struct {
  367. Foo string `json:"foo"`
  368. Bar string `json:"bar"`
  369. }
  370. assert.False(t, c.IsAborted())
  371. assert.Error(t, c.Bind(&obj))
  372. c.Writer.WriteHeaderNow()
  373. assert.Empty(t, obj.Bar)
  374. assert.Empty(t, obj.Foo)
  375. assert.Equal(t, w.Code, 400)
  376. assert.True(t, c.IsAborted())
  377. }
  378. func TestContextBindWith(t *testing.T) {
  379. c, w, _ := createTestContext()
  380. c.Request, _ = http.NewRequest("POST", "/", bytes.NewBufferString("{\"foo\":\"bar\", \"bar\":\"foo\"}"))
  381. c.Request.Header.Add("Content-Type", MIMEXML)
  382. var obj struct {
  383. Foo string `json:"foo"`
  384. Bar string `json:"bar"`
  385. }
  386. assert.NoError(t, c.BindWith(&obj, binding.JSON))
  387. assert.Equal(t, obj.Bar, "foo")
  388. assert.Equal(t, obj.Foo, "bar")
  389. assert.Equal(t, w.Body.Len(), 0)
  390. }
  391. func TestContextGolangContext(t *testing.T) {
  392. c, _, _ := createTestContext()
  393. c.Request, _ = http.NewRequest("POST", "/", bytes.NewBufferString("{\"foo\":\"bar\", \"bar\":\"foo\"}"))
  394. assert.NoError(t, c.Err())
  395. assert.Nil(t, c.Done())
  396. ti, ok := c.Deadline()
  397. assert.Equal(t, ti, time.Time{})
  398. assert.False(t, ok)
  399. assert.Equal(t, c.Value(0), c.Request)
  400. assert.Nil(t, c.Value("foo"))
  401. c.Set("foo", "bar")
  402. assert.Equal(t, c.Value("foo"), "bar")
  403. assert.Nil(t, c.Value(1))
  404. }