context_test.go 17 KB

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