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