context_test.go 18 KB

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