context_test.go 19 KB

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