context_test.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607
  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. "mime/multipart"
  10. "net/http"
  11. "net/http/httptest"
  12. "testing"
  13. "time"
  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 createMultipartRequest() *http.Request {
  31. boundary := "--testboundary"
  32. body := new(bytes.Buffer)
  33. mw := multipart.NewWriter(body)
  34. defer mw.Close()
  35. must(mw.SetBoundary(boundary))
  36. must(mw.WriteField("foo", "bar"))
  37. must(mw.WriteField("bar", "foo"))
  38. must(mw.WriteField("bar", "foo2"))
  39. must(mw.WriteField("array", "first"))
  40. must(mw.WriteField("array", "second"))
  41. req, err := http.NewRequest("POST", "/", body)
  42. must(err)
  43. req.Header.Set("Content-Type", MIMEMultipartPOSTForm+"; boundary="+boundary)
  44. return req
  45. }
  46. func must(err error) {
  47. if err != nil {
  48. panic(err.Error())
  49. }
  50. }
  51. func TestContextReset(t *testing.T) {
  52. router := New()
  53. c := router.allocateContext()
  54. assert.Equal(t, c.engine, router)
  55. c.index = 2
  56. c.Writer = &responseWriter{ResponseWriter: httptest.NewRecorder()}
  57. c.Params = Params{Param{}}
  58. c.Error(errors.New("test"))
  59. c.Set("foo", "bar")
  60. c.reset()
  61. assert.False(t, c.IsAborted())
  62. assert.Nil(t, c.Keys)
  63. assert.Nil(t, c.Accepted)
  64. assert.Len(t, c.Errors, 0)
  65. assert.Empty(t, c.Errors.Errors())
  66. assert.Empty(t, c.Errors.ByType(ErrorTypeAny))
  67. assert.Len(t, c.Params, 0)
  68. assert.EqualValues(t, c.index, -1)
  69. assert.Equal(t, c.Writer.(*responseWriter), &c.writermem)
  70. }
  71. func TestContextHandlers(t *testing.T) {
  72. c, _, _ := createTestContext()
  73. assert.Nil(t, c.handlers)
  74. assert.Nil(t, c.handlers.Last())
  75. c.handlers = HandlersChain{}
  76. assert.NotNil(t, c.handlers)
  77. assert.Nil(t, c.handlers.Last())
  78. f := func(c *Context) {}
  79. g := func(c *Context) {}
  80. c.handlers = HandlersChain{f}
  81. compareFunc(t, f, c.handlers.Last())
  82. c.handlers = HandlersChain{f, g}
  83. compareFunc(t, g, c.handlers.Last())
  84. }
  85. // TestContextSetGet tests that a parameter is set correctly on the
  86. // current context and can be retrieved using Get.
  87. func TestContextSetGet(t *testing.T) {
  88. c, _, _ := createTestContext()
  89. c.Set("foo", "bar")
  90. value, err := c.Get("foo")
  91. assert.Equal(t, value, "bar")
  92. assert.True(t, err)
  93. value, err = c.Get("foo2")
  94. assert.Nil(t, value)
  95. assert.False(t, err)
  96. assert.Equal(t, c.MustGet("foo"), "bar")
  97. assert.Panics(t, func() { c.MustGet("no_exist") })
  98. }
  99. func TestContextSetGetValues(t *testing.T) {
  100. c, _, _ := createTestContext()
  101. c.Set("string", "this is a string")
  102. c.Set("int32", int32(-42))
  103. c.Set("int64", int64(42424242424242))
  104. c.Set("uint64", uint64(42))
  105. c.Set("float32", float32(4.2))
  106. c.Set("float64", 4.2)
  107. var a interface{} = 1
  108. c.Set("intInterface", a)
  109. assert.Exactly(t, c.MustGet("string").(string), "this is a string")
  110. assert.Exactly(t, c.MustGet("int32").(int32), int32(-42))
  111. assert.Exactly(t, c.MustGet("int64").(int64), int64(42424242424242))
  112. assert.Exactly(t, c.MustGet("uint64").(uint64), uint64(42))
  113. assert.Exactly(t, c.MustGet("float32").(float32), float32(4.2))
  114. assert.Exactly(t, c.MustGet("float64").(float64), 4.2)
  115. assert.Exactly(t, c.MustGet("intInterface").(int), 1)
  116. }
  117. func TestContextCopy(t *testing.T) {
  118. c, _, _ := createTestContext()
  119. c.index = 2
  120. c.Request, _ = http.NewRequest("POST", "/hola", nil)
  121. c.handlers = HandlersChain{func(c *Context) {}}
  122. c.Params = Params{Param{Key: "foo", Value: "bar"}}
  123. c.Set("foo", "bar")
  124. cp := c.Copy()
  125. assert.Nil(t, cp.handlers)
  126. assert.Nil(t, cp.writermem.ResponseWriter)
  127. assert.Equal(t, &cp.writermem, cp.Writer.(*responseWriter))
  128. assert.Equal(t, cp.Request, c.Request)
  129. assert.Equal(t, cp.index, abortIndex)
  130. assert.Equal(t, cp.Keys, c.Keys)
  131. assert.Equal(t, cp.engine, c.engine)
  132. assert.Equal(t, cp.Params, c.Params)
  133. }
  134. func TestContextHandlerName(t *testing.T) {
  135. c, _, _ := createTestContext()
  136. c.handlers = HandlersChain{func(c *Context) {}, handlerNameTest}
  137. assert.Regexp(t, "^(.*/vendor/)?github.com/gin-gonic/gin.handlerNameTest$", c.HandlerName())
  138. }
  139. func handlerNameTest(c *Context) {
  140. }
  141. func TestContextQuery(t *testing.T) {
  142. c, _, _ := createTestContext()
  143. c.Request, _ = http.NewRequest("GET", "http://example.com/?foo=bar&page=10", nil)
  144. assert.Equal(t, c.DefaultQuery("foo", "none"), "bar")
  145. assert.Equal(t, c.Query("foo"), "bar")
  146. assert.Empty(t, c.PostForm("foo"))
  147. assert.Equal(t, c.DefaultQuery("page", "0"), "10")
  148. assert.Equal(t, c.Query("page"), "10")
  149. assert.Empty(t, c.PostForm("page"))
  150. assert.Equal(t, c.DefaultQuery("NoKey", "nada"), "nada")
  151. assert.Empty(t, c.Query("NoKey"))
  152. assert.Empty(t, c.PostForm("NoKey"))
  153. }
  154. func TestContextQueryAndPostForm(t *testing.T) {
  155. c, _, _ := createTestContext()
  156. body := bytes.NewBufferString("foo=bar&page=11&both=POST&foo=second")
  157. c.Request, _ = http.NewRequest("POST", "/?both=GET&id=main&id=omit&array[]=first&array[]=second", body)
  158. c.Request.Header.Add("Content-Type", MIMEPOSTForm)
  159. assert.Equal(t, c.DefaultPostForm("foo", "none"), "bar")
  160. assert.Equal(t, c.PostForm("foo"), "bar")
  161. assert.Empty(t, c.Query("foo"))
  162. assert.Equal(t, c.DefaultPostForm("page", "0"), "11")
  163. assert.Equal(t, c.PostForm("page"), "11")
  164. assert.Equal(t, c.Query("page"), "")
  165. assert.Equal(t, c.PostForm("both"), "POST")
  166. assert.Equal(t, c.Query("both"), "GET")
  167. assert.Equal(t, c.DefaultPostForm("id", "000"), "000")
  168. assert.Equal(t, c.Query("id"), "main")
  169. assert.Empty(t, c.PostForm("id"))
  170. assert.Equal(t, c.DefaultPostForm("NoKey", "nada"), "nada")
  171. assert.Empty(t, c.PostForm("NoKey"))
  172. assert.Empty(t, c.Query("NoKey"))
  173. var obj struct {
  174. Foo string `form:"foo"`
  175. ID string `form:"id"`
  176. Page string `form:"page"`
  177. Both string `form:"both"`
  178. Array []string `form:"array[]"`
  179. }
  180. assert.NoError(t, c.Bind(&obj))
  181. assert.Equal(t, obj.Foo, "bar")
  182. assert.Equal(t, obj.ID, "main")
  183. assert.Equal(t, obj.Page, "11")
  184. assert.Equal(t, obj.Both, "POST")
  185. assert.Equal(t, obj.Array, []string{"first", "second"})
  186. }
  187. func TestContextPostFormMultipart(t *testing.T) {
  188. c, _, _ := createTestContext()
  189. c.Request = createMultipartRequest()
  190. var obj struct {
  191. Foo string `form:"foo"`
  192. Bar string `form:"bar"`
  193. Array []string `form:"array"`
  194. }
  195. assert.NoError(t, c.Bind(&obj))
  196. assert.Equal(t, obj.Bar, "foo")
  197. assert.Equal(t, obj.Foo, "bar")
  198. assert.Equal(t, obj.Array, []string{"first", "second"})
  199. assert.Empty(t, c.Query("foo"))
  200. assert.Empty(t, c.Query("bar"))
  201. assert.Equal(t, c.PostForm("foo"), "bar")
  202. assert.Equal(t, c.PostForm("array"), "first")
  203. assert.Equal(t, c.PostForm("bar"), "foo")
  204. }
  205. // Tests that the response is serialized as JSON
  206. // and Content-Type is set to application/json
  207. func TestContextRenderJSON(t *testing.T) {
  208. c, w, _ := createTestContext()
  209. c.JSON(201, H{"foo": "bar"})
  210. assert.Equal(t, w.Code, 201)
  211. assert.Equal(t, w.Body.String(), "{\"foo\":\"bar\"}\n")
  212. assert.Equal(t, w.HeaderMap.Get("Content-Type"), "application/json; charset=utf-8")
  213. }
  214. // Tests that the response is serialized as JSON
  215. // we change the content-type before
  216. func TestContextRenderAPIJSON(t *testing.T) {
  217. c, w, _ := createTestContext()
  218. c.Header("Content-Type", "application/vnd.api+json")
  219. c.JSON(201, H{"foo": "bar"})
  220. assert.Equal(t, w.Code, 201)
  221. assert.Equal(t, w.Body.String(), "{\"foo\":\"bar\"}\n")
  222. assert.Equal(t, w.HeaderMap.Get("Content-Type"), "application/vnd.api+json")
  223. }
  224. // Tests that the response is serialized as JSON
  225. // and Content-Type is set to application/json
  226. func TestContextRenderIndentedJSON(t *testing.T) {
  227. c, w, _ := createTestContext()
  228. c.IndentedJSON(201, H{"foo": "bar", "bar": "foo", "nested": H{"foo": "bar"}})
  229. assert.Equal(t, w.Code, 201)
  230. assert.Equal(t, w.Body.String(), "{\n \"bar\": \"foo\",\n \"foo\": \"bar\",\n \"nested\": {\n \"foo\": \"bar\"\n }\n}")
  231. assert.Equal(t, w.HeaderMap.Get("Content-Type"), "application/json; charset=utf-8")
  232. }
  233. // Tests that the response executes the templates
  234. // and responds with Content-Type set to text/html
  235. func TestContextRenderHTML(t *testing.T) {
  236. c, w, router := createTestContext()
  237. templ := template.Must(template.New("t").Parse(`Hello {{.name}}`))
  238. router.SetHTMLTemplate(templ)
  239. c.HTML(201, "t", H{"name": "alexandernyquist"})
  240. assert.Equal(t, w.Code, 201)
  241. assert.Equal(t, w.Body.String(), "Hello alexandernyquist")
  242. assert.Equal(t, w.HeaderMap.Get("Content-Type"), "text/html; charset=utf-8")
  243. }
  244. // TestContextXML tests that the response is serialized as XML
  245. // and Content-Type is set to application/xml
  246. func TestContextRenderXML(t *testing.T) {
  247. c, w, _ := createTestContext()
  248. c.XML(201, H{"foo": "bar"})
  249. assert.Equal(t, w.Code, 201)
  250. assert.Equal(t, w.Body.String(), "<map><foo>bar</foo></map>")
  251. assert.Equal(t, w.HeaderMap.Get("Content-Type"), "application/xml; charset=utf-8")
  252. }
  253. // TestContextString tests that the response is returned
  254. // with Content-Type set to text/plain
  255. func TestContextRenderString(t *testing.T) {
  256. c, w, _ := createTestContext()
  257. c.String(201, "test %s %d", "string", 2)
  258. assert.Equal(t, w.Code, 201)
  259. assert.Equal(t, w.Body.String(), "test string 2")
  260. assert.Equal(t, w.HeaderMap.Get("Content-Type"), "text/plain; charset=utf-8")
  261. }
  262. // TestContextString tests that the response is returned
  263. // with Content-Type set to text/html
  264. func TestContextRenderHTMLString(t *testing.T) {
  265. c, w, _ := createTestContext()
  266. c.Header("Content-Type", "text/html; charset=utf-8")
  267. c.String(201, "<html>%s %d</html>", "string", 3)
  268. assert.Equal(t, w.Code, 201)
  269. assert.Equal(t, w.Body.String(), "<html>string 3</html>")
  270. assert.Equal(t, w.HeaderMap.Get("Content-Type"), "text/html; charset=utf-8")
  271. }
  272. // TestContextData tests that the response can be written from `bytesting`
  273. // with specified MIME type
  274. func TestContextRenderData(t *testing.T) {
  275. c, w, _ := createTestContext()
  276. c.Data(201, "text/csv", []byte(`foo,bar`))
  277. assert.Equal(t, w.Code, 201)
  278. assert.Equal(t, w.Body.String(), "foo,bar")
  279. assert.Equal(t, w.HeaderMap.Get("Content-Type"), "text/csv")
  280. }
  281. func TestContextRenderSSE(t *testing.T) {
  282. c, w, _ := createTestContext()
  283. c.SSEvent("float", 1.5)
  284. c.Render(-1, sse.Event{
  285. Id: "123",
  286. Data: "text",
  287. })
  288. c.SSEvent("chat", H{
  289. "foo": "bar",
  290. "bar": "foo",
  291. })
  292. 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")
  293. }
  294. func TestContextRenderFile(t *testing.T) {
  295. c, w, _ := createTestContext()
  296. c.Request, _ = http.NewRequest("GET", "/", nil)
  297. c.File("./gin.go")
  298. assert.Equal(t, w.Code, 200)
  299. assert.Contains(t, w.Body.String(), "func New() *Engine {")
  300. assert.Equal(t, w.HeaderMap.Get("Content-Type"), "text/plain; charset=utf-8")
  301. }
  302. func TestContextHeaders(t *testing.T) {
  303. c, _, _ := createTestContext()
  304. c.Header("Content-Type", "text/plain")
  305. c.Header("X-Custom", "value")
  306. assert.Equal(t, c.Writer.Header().Get("Content-Type"), "text/plain")
  307. assert.Equal(t, c.Writer.Header().Get("X-Custom"), "value")
  308. c.Header("Content-Type", "text/html")
  309. c.Header("X-Custom", "")
  310. assert.Equal(t, c.Writer.Header().Get("Content-Type"), "text/html")
  311. _, exist := c.Writer.Header()["X-Custom"]
  312. assert.False(t, exist)
  313. }
  314. // TODO
  315. func TestContextRenderRedirectWithRelativePath(t *testing.T) {
  316. c, w, _ := createTestContext()
  317. c.Request, _ = http.NewRequest("POST", "http://example.com", nil)
  318. assert.Panics(t, func() { c.Redirect(299, "/new_path") })
  319. assert.Panics(t, func() { c.Redirect(309, "/new_path") })
  320. c.Redirect(302, "/path")
  321. c.Writer.WriteHeaderNow()
  322. assert.Equal(t, w.Code, 302)
  323. assert.Equal(t, w.Header().Get("Location"), "/path")
  324. }
  325. func TestContextRenderRedirectWithAbsolutePath(t *testing.T) {
  326. c, w, _ := createTestContext()
  327. c.Request, _ = http.NewRequest("POST", "http://example.com", nil)
  328. c.Redirect(302, "http://google.com")
  329. c.Writer.WriteHeaderNow()
  330. assert.Equal(t, w.Code, 302)
  331. assert.Equal(t, w.Header().Get("Location"), "http://google.com")
  332. }
  333. func TestContextNegotiationFormat(t *testing.T) {
  334. c, _, _ := createTestContext()
  335. c.Request, _ = http.NewRequest("POST", "", nil)
  336. assert.Panics(t, func() { c.NegotiateFormat() })
  337. assert.Equal(t, c.NegotiateFormat(MIMEJSON, MIMEXML), MIMEJSON)
  338. assert.Equal(t, c.NegotiateFormat(MIMEHTML, MIMEJSON), MIMEHTML)
  339. }
  340. func TestContextNegotiationFormatWithAccept(t *testing.T) {
  341. c, _, _ := createTestContext()
  342. c.Request, _ = http.NewRequest("POST", "/", nil)
  343. c.Request.Header.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
  344. assert.Equal(t, c.NegotiateFormat(MIMEJSON, MIMEXML), MIMEXML)
  345. assert.Equal(t, c.NegotiateFormat(MIMEXML, MIMEHTML), MIMEHTML)
  346. assert.Equal(t, c.NegotiateFormat(MIMEJSON), "")
  347. }
  348. func TestContextNegotiationFormatCustum(t *testing.T) {
  349. c, _, _ := createTestContext()
  350. c.Request, _ = http.NewRequest("POST", "/", nil)
  351. c.Request.Header.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
  352. c.Accepted = nil
  353. c.SetAccepted(MIMEJSON, MIMEXML)
  354. assert.Equal(t, c.NegotiateFormat(MIMEJSON, MIMEXML), MIMEJSON)
  355. assert.Equal(t, c.NegotiateFormat(MIMEXML, MIMEHTML), MIMEXML)
  356. assert.Equal(t, c.NegotiateFormat(MIMEJSON), MIMEJSON)
  357. }
  358. func TestContextIsAborted(t *testing.T) {
  359. c, _, _ := createTestContext()
  360. assert.False(t, c.IsAborted())
  361. c.Abort()
  362. assert.True(t, c.IsAborted())
  363. c.Next()
  364. assert.True(t, c.IsAborted())
  365. c.index++
  366. assert.True(t, c.IsAborted())
  367. }
  368. // TestContextData tests that the response can be written from `bytesting`
  369. // with specified MIME type
  370. func TestContextAbortWithStatus(t *testing.T) {
  371. c, w, _ := createTestContext()
  372. c.index = 4
  373. c.AbortWithStatus(401)
  374. c.Writer.WriteHeaderNow()
  375. assert.Equal(t, c.index, abortIndex)
  376. assert.Equal(t, c.Writer.Status(), 401)
  377. assert.Equal(t, w.Code, 401)
  378. assert.True(t, c.IsAborted())
  379. }
  380. func TestContextError(t *testing.T) {
  381. c, _, _ := createTestContext()
  382. assert.Empty(t, c.Errors)
  383. c.Error(errors.New("first error"))
  384. assert.Len(t, c.Errors, 1)
  385. assert.Equal(t, c.Errors.String(), "Error #01: first error\n")
  386. c.Error(&Error{
  387. Err: errors.New("second error"),
  388. Meta: "some data 2",
  389. Type: ErrorTypePublic,
  390. })
  391. assert.Len(t, c.Errors, 2)
  392. assert.Equal(t, c.Errors[0].Err, errors.New("first error"))
  393. assert.Nil(t, c.Errors[0].Meta)
  394. assert.Equal(t, c.Errors[0].Type, ErrorTypePrivate)
  395. assert.Equal(t, c.Errors[1].Err, errors.New("second error"))
  396. assert.Equal(t, c.Errors[1].Meta, "some data 2")
  397. assert.Equal(t, c.Errors[1].Type, ErrorTypePublic)
  398. assert.Equal(t, c.Errors.Last(), c.Errors[1])
  399. }
  400. func TestContextTypedError(t *testing.T) {
  401. c, _, _ := createTestContext()
  402. c.Error(errors.New("externo 0")).SetType(ErrorTypePublic)
  403. c.Error(errors.New("interno 0")).SetType(ErrorTypePrivate)
  404. for _, err := range c.Errors.ByType(ErrorTypePublic) {
  405. assert.Equal(t, err.Type, ErrorTypePublic)
  406. }
  407. for _, err := range c.Errors.ByType(ErrorTypePrivate) {
  408. assert.Equal(t, err.Type, ErrorTypePrivate)
  409. }
  410. assert.Equal(t, c.Errors.Errors(), []string{"externo 0", "interno 0"})
  411. }
  412. func TestContextAbortWithError(t *testing.T) {
  413. c, w, _ := createTestContext()
  414. c.AbortWithError(401, errors.New("bad input")).SetMeta("some input")
  415. c.Writer.WriteHeaderNow()
  416. assert.Equal(t, w.Code, 401)
  417. assert.Equal(t, c.index, abortIndex)
  418. assert.True(t, c.IsAborted())
  419. }
  420. func TestContextClientIP(t *testing.T) {
  421. c, _, _ := createTestContext()
  422. c.Request, _ = http.NewRequest("POST", "/", nil)
  423. c.Request.Header.Set("X-Real-IP", " 10.10.10.10 ")
  424. c.Request.Header.Set("X-Forwarded-For", " 20.20.20.20, 30.30.30.30")
  425. c.Request.RemoteAddr = " 40.40.40.40 "
  426. assert.Equal(t, c.ClientIP(), "10.10.10.10")
  427. c.Request.Header.Del("X-Real-IP")
  428. assert.Equal(t, c.ClientIP(), "20.20.20.20")
  429. c.Request.Header.Set("X-Forwarded-For", "30.30.30.30 ")
  430. assert.Equal(t, c.ClientIP(), "30.30.30.30")
  431. c.Request.Header.Del("X-Forwarded-For")
  432. assert.Equal(t, c.ClientIP(), "40.40.40.40")
  433. }
  434. func TestContextContentType(t *testing.T) {
  435. c, _, _ := createTestContext()
  436. c.Request, _ = http.NewRequest("POST", "/", nil)
  437. c.Request.Header.Set("Content-Type", "application/json; charset=utf-8")
  438. assert.Equal(t, c.ContentType(), "application/json")
  439. }
  440. func TestContextAutoBindJSON(t *testing.T) {
  441. c, _, _ := createTestContext()
  442. c.Request, _ = http.NewRequest("POST", "/", bytes.NewBufferString("{\"foo\":\"bar\", \"bar\":\"foo\"}"))
  443. c.Request.Header.Add("Content-Type", MIMEJSON)
  444. var obj struct {
  445. Foo string `json:"foo"`
  446. Bar string `json:"bar"`
  447. }
  448. assert.NoError(t, c.Bind(&obj))
  449. assert.Equal(t, obj.Bar, "foo")
  450. assert.Equal(t, obj.Foo, "bar")
  451. assert.Empty(t, c.Errors)
  452. }
  453. func TestContextBindWithJSON(t *testing.T) {
  454. c, w, _ := createTestContext()
  455. c.Request, _ = http.NewRequest("POST", "/", bytes.NewBufferString("{\"foo\":\"bar\", \"bar\":\"foo\"}"))
  456. c.Request.Header.Add("Content-Type", MIMEXML) // set fake content-type
  457. var obj struct {
  458. Foo string `json:"foo"`
  459. Bar string `json:"bar"`
  460. }
  461. assert.NoError(t, c.BindJSON(&obj))
  462. assert.Equal(t, obj.Bar, "foo")
  463. assert.Equal(t, obj.Foo, "bar")
  464. assert.Equal(t, w.Body.Len(), 0)
  465. }
  466. func TestContextBadAutoBind(t *testing.T) {
  467. c, w, _ := createTestContext()
  468. c.Request, _ = http.NewRequest("POST", "http://example.com", bytes.NewBufferString("\"foo\":\"bar\", \"bar\":\"foo\"}"))
  469. c.Request.Header.Add("Content-Type", MIMEJSON)
  470. var obj struct {
  471. Foo string `json:"foo"`
  472. Bar string `json:"bar"`
  473. }
  474. assert.False(t, c.IsAborted())
  475. assert.Error(t, c.Bind(&obj))
  476. c.Writer.WriteHeaderNow()
  477. assert.Empty(t, obj.Bar)
  478. assert.Empty(t, obj.Foo)
  479. assert.Equal(t, w.Code, 400)
  480. assert.True(t, c.IsAborted())
  481. }
  482. func TestContextGolangContext(t *testing.T) {
  483. c, _, _ := createTestContext()
  484. c.Request, _ = http.NewRequest("POST", "/", bytes.NewBufferString("{\"foo\":\"bar\", \"bar\":\"foo\"}"))
  485. assert.NoError(t, c.Err())
  486. assert.Nil(t, c.Done())
  487. ti, ok := c.Deadline()
  488. assert.Equal(t, ti, time.Time{})
  489. assert.False(t, ok)
  490. assert.Equal(t, c.Value(0), c.Request)
  491. assert.Nil(t, c.Value("foo"))
  492. c.Set("foo", "bar")
  493. assert.Equal(t, c.Value("foo"), "bar")
  494. assert.Nil(t, c.Value(1))
  495. }