context_test.go 18 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609
  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 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, 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))
  294. //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")
  295. }
  296. func TestContextRenderFile(t *testing.T) {
  297. c, w, _ := createTestContext()
  298. c.Request, _ = http.NewRequest("GET", "/", nil)
  299. c.File("./gin.go")
  300. assert.Equal(t, w.Code, 200)
  301. assert.Contains(t, w.Body.String(), "func New() *Engine {")
  302. assert.Equal(t, w.HeaderMap.Get("Content-Type"), "text/plain; charset=utf-8")
  303. }
  304. func TestContextHeaders(t *testing.T) {
  305. c, _, _ := createTestContext()
  306. c.Header("Content-Type", "text/plain")
  307. c.Header("X-Custom", "value")
  308. assert.Equal(t, c.Writer.Header().Get("Content-Type"), "text/plain")
  309. assert.Equal(t, c.Writer.Header().Get("X-Custom"), "value")
  310. c.Header("Content-Type", "text/html")
  311. c.Header("X-Custom", "")
  312. assert.Equal(t, c.Writer.Header().Get("Content-Type"), "text/html")
  313. _, exist := c.Writer.Header()["X-Custom"]
  314. assert.False(t, exist)
  315. }
  316. // TODO
  317. func TestContextRenderRedirectWithRelativePath(t *testing.T) {
  318. c, w, _ := createTestContext()
  319. c.Request, _ = http.NewRequest("POST", "http://example.com", nil)
  320. assert.Panics(t, func() { c.Redirect(299, "/new_path") })
  321. assert.Panics(t, func() { c.Redirect(309, "/new_path") })
  322. c.Redirect(302, "/path")
  323. c.Writer.WriteHeaderNow()
  324. assert.Equal(t, w.Code, 302)
  325. assert.Equal(t, w.Header().Get("Location"), "/path")
  326. }
  327. func TestContextRenderRedirectWithAbsolutePath(t *testing.T) {
  328. c, w, _ := createTestContext()
  329. c.Request, _ = http.NewRequest("POST", "http://example.com", nil)
  330. c.Redirect(302, "http://google.com")
  331. c.Writer.WriteHeaderNow()
  332. assert.Equal(t, w.Code, 302)
  333. assert.Equal(t, w.Header().Get("Location"), "http://google.com")
  334. }
  335. func TestContextNegotiationFormat(t *testing.T) {
  336. c, _, _ := createTestContext()
  337. c.Request, _ = http.NewRequest("POST", "", nil)
  338. assert.Panics(t, func() { c.NegotiateFormat() })
  339. assert.Equal(t, c.NegotiateFormat(MIMEJSON, MIMEXML), MIMEJSON)
  340. assert.Equal(t, c.NegotiateFormat(MIMEHTML, MIMEJSON), MIMEHTML)
  341. }
  342. func TestContextNegotiationFormatWithAccept(t *testing.T) {
  343. c, _, _ := createTestContext()
  344. c.Request, _ = http.NewRequest("POST", "/", nil)
  345. c.Request.Header.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
  346. assert.Equal(t, c.NegotiateFormat(MIMEJSON, MIMEXML), MIMEXML)
  347. assert.Equal(t, c.NegotiateFormat(MIMEXML, MIMEHTML), MIMEHTML)
  348. assert.Equal(t, c.NegotiateFormat(MIMEJSON), "")
  349. }
  350. func TestContextNegotiationFormatCustum(t *testing.T) {
  351. c, _, _ := createTestContext()
  352. c.Request, _ = http.NewRequest("POST", "/", nil)
  353. c.Request.Header.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
  354. c.Accepted = nil
  355. c.SetAccepted(MIMEJSON, MIMEXML)
  356. assert.Equal(t, c.NegotiateFormat(MIMEJSON, MIMEXML), MIMEJSON)
  357. assert.Equal(t, c.NegotiateFormat(MIMEXML, MIMEHTML), MIMEXML)
  358. assert.Equal(t, c.NegotiateFormat(MIMEJSON), MIMEJSON)
  359. }
  360. func TestContextIsAborted(t *testing.T) {
  361. c, _, _ := createTestContext()
  362. assert.False(t, c.IsAborted())
  363. c.Abort()
  364. assert.True(t, c.IsAborted())
  365. c.Next()
  366. assert.True(t, c.IsAborted())
  367. c.index++
  368. assert.True(t, c.IsAborted())
  369. }
  370. // TestContextData tests that the response can be written from `bytesting`
  371. // with specified MIME type
  372. func TestContextAbortWithStatus(t *testing.T) {
  373. c, w, _ := createTestContext()
  374. c.index = 4
  375. c.AbortWithStatus(401)
  376. c.Writer.WriteHeaderNow()
  377. assert.Equal(t, c.index, abortIndex)
  378. assert.Equal(t, c.Writer.Status(), 401)
  379. assert.Equal(t, w.Code, 401)
  380. assert.True(t, c.IsAborted())
  381. }
  382. func TestContextError(t *testing.T) {
  383. c, _, _ := createTestContext()
  384. assert.Empty(t, c.Errors)
  385. c.Error(errors.New("first error"))
  386. assert.Len(t, c.Errors, 1)
  387. assert.Equal(t, c.Errors.String(), "Error #01: first error\n")
  388. c.Error(&Error{
  389. Err: errors.New("second error"),
  390. Meta: "some data 2",
  391. Type: ErrorTypePublic,
  392. })
  393. assert.Len(t, c.Errors, 2)
  394. assert.Equal(t, c.Errors[0].Err, errors.New("first error"))
  395. assert.Nil(t, c.Errors[0].Meta)
  396. assert.Equal(t, c.Errors[0].Type, ErrorTypePrivate)
  397. assert.Equal(t, c.Errors[1].Err, errors.New("second error"))
  398. assert.Equal(t, c.Errors[1].Meta, "some data 2")
  399. assert.Equal(t, c.Errors[1].Type, ErrorTypePublic)
  400. assert.Equal(t, c.Errors.Last(), c.Errors[1])
  401. }
  402. func TestContextTypedError(t *testing.T) {
  403. c, _, _ := createTestContext()
  404. c.Error(errors.New("externo 0")).SetType(ErrorTypePublic)
  405. c.Error(errors.New("interno 0")).SetType(ErrorTypePrivate)
  406. for _, err := range c.Errors.ByType(ErrorTypePublic) {
  407. assert.Equal(t, err.Type, ErrorTypePublic)
  408. }
  409. for _, err := range c.Errors.ByType(ErrorTypePrivate) {
  410. assert.Equal(t, err.Type, ErrorTypePrivate)
  411. }
  412. assert.Equal(t, c.Errors.Errors(), []string{"externo 0", "interno 0"})
  413. }
  414. func TestContextAbortWithError(t *testing.T) {
  415. c, w, _ := createTestContext()
  416. c.AbortWithError(401, errors.New("bad input")).SetMeta("some input")
  417. c.Writer.WriteHeaderNow()
  418. assert.Equal(t, w.Code, 401)
  419. assert.Equal(t, c.index, abortIndex)
  420. assert.True(t, c.IsAborted())
  421. }
  422. func TestContextClientIP(t *testing.T) {
  423. c, _, _ := createTestContext()
  424. c.Request, _ = http.NewRequest("POST", "/", nil)
  425. c.Request.Header.Set("X-Real-IP", " 10.10.10.10 ")
  426. c.Request.Header.Set("X-Forwarded-For", " 20.20.20.20, 30.30.30.30")
  427. c.Request.RemoteAddr = " 40.40.40.40 "
  428. assert.Equal(t, c.ClientIP(), "10.10.10.10")
  429. c.Request.Header.Del("X-Real-IP")
  430. assert.Equal(t, c.ClientIP(), "20.20.20.20")
  431. c.Request.Header.Set("X-Forwarded-For", "30.30.30.30 ")
  432. assert.Equal(t, c.ClientIP(), "30.30.30.30")
  433. c.Request.Header.Del("X-Forwarded-For")
  434. assert.Equal(t, c.ClientIP(), "40.40.40.40")
  435. }
  436. func TestContextContentType(t *testing.T) {
  437. c, _, _ := createTestContext()
  438. c.Request, _ = http.NewRequest("POST", "/", nil)
  439. c.Request.Header.Set("Content-Type", "application/json; charset=utf-8")
  440. assert.Equal(t, c.ContentType(), "application/json")
  441. }
  442. func TestContextAutoBindJSON(t *testing.T) {
  443. c, _, _ := createTestContext()
  444. c.Request, _ = http.NewRequest("POST", "/", 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.NoError(t, c.Bind(&obj))
  451. assert.Equal(t, obj.Bar, "foo")
  452. assert.Equal(t, obj.Foo, "bar")
  453. assert.Empty(t, c.Errors)
  454. }
  455. func TestContextBindWithJSON(t *testing.T) {
  456. c, w, _ := createTestContext()
  457. c.Request, _ = http.NewRequest("POST", "/", bytes.NewBufferString("{\"foo\":\"bar\", \"bar\":\"foo\"}"))
  458. c.Request.Header.Add("Content-Type", MIMEXML) // set fake content-type
  459. var obj struct {
  460. Foo string `json:"foo"`
  461. Bar string `json:"bar"`
  462. }
  463. assert.NoError(t, c.BindJSON(&obj))
  464. assert.Equal(t, obj.Bar, "foo")
  465. assert.Equal(t, obj.Foo, "bar")
  466. assert.Equal(t, w.Body.Len(), 0)
  467. }
  468. func TestContextBadAutoBind(t *testing.T) {
  469. c, w, _ := createTestContext()
  470. c.Request, _ = http.NewRequest("POST", "http://example.com", bytes.NewBufferString("\"foo\":\"bar\", \"bar\":\"foo\"}"))
  471. c.Request.Header.Add("Content-Type", MIMEJSON)
  472. var obj struct {
  473. Foo string `json:"foo"`
  474. Bar string `json:"bar"`
  475. }
  476. assert.False(t, c.IsAborted())
  477. assert.Error(t, c.Bind(&obj))
  478. c.Writer.WriteHeaderNow()
  479. assert.Empty(t, obj.Bar)
  480. assert.Empty(t, obj.Foo)
  481. assert.Equal(t, w.Code, 400)
  482. assert.True(t, c.IsAborted())
  483. }
  484. func TestContextGolangContext(t *testing.T) {
  485. c, _, _ := createTestContext()
  486. c.Request, _ = http.NewRequest("POST", "/", bytes.NewBufferString("{\"foo\":\"bar\", \"bar\":\"foo\"}"))
  487. assert.NoError(t, c.Err())
  488. assert.Nil(t, c.Done())
  489. ti, ok := c.Deadline()
  490. assert.Equal(t, ti, time.Time{})
  491. assert.False(t, ok)
  492. assert.Equal(t, c.Value(0), c.Request)
  493. assert.Nil(t, c.Value("foo"))
  494. c.Set("foo", "bar")
  495. assert.Equal(t, c.Value("foo"), "bar")
  496. assert.Nil(t, c.Value(1))
  497. }