context_test.go 18 KB

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