context_test.go 19 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634
  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.Regexp(t, "^(.*/vendor/)?github.com/gin-gonic/gin.handlerNameTest$", c.HandlerName())
  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. func TestContextSetCookie(t *testing.T) {
  199. c, _, _ := CreateTestContext()
  200. c.SetCookie("user", "gin", 1, "/", "localhost", true, true)
  201. assert.Equal(t, c.Writer.Header().Get("Set-Cookie"), "user=gin; Path=/; Domain=localhost; Max-Age=1; HttpOnly; Secure")
  202. }
  203. func TestContextGetCookie(t *testing.T) {
  204. c, _, _ := CreateTestContext()
  205. c.Request, _ = http.NewRequest("GET", "/get", nil)
  206. c.Request.Header.Set("Cookie", "user=gin")
  207. cookie, _ := c.Cookie("user")
  208. assert.Equal(t, cookie, "gin")
  209. }
  210. // Tests that the response is serialized as JSON
  211. // and Content-Type is set to application/json
  212. func TestContextRenderJSON(t *testing.T) {
  213. c, w, _ := CreateTestContext()
  214. c.JSON(201, H{"foo": "bar"})
  215. assert.Equal(t, w.Code, 201)
  216. assert.Equal(t, w.Body.String(), "{\"foo\":\"bar\"}\n")
  217. assert.Equal(t, w.HeaderMap.Get("Content-Type"), "application/json; charset=utf-8")
  218. }
  219. // Tests that the response is serialized as JSON
  220. // we change the content-type before
  221. func TestContextRenderAPIJSON(t *testing.T) {
  222. c, w, _ := CreateTestContext()
  223. c.Header("Content-Type", "application/vnd.api+json")
  224. c.JSON(201, H{"foo": "bar"})
  225. assert.Equal(t, w.Code, 201)
  226. assert.Equal(t, w.Body.String(), "{\"foo\":\"bar\"}\n")
  227. assert.Equal(t, w.HeaderMap.Get("Content-Type"), "application/vnd.api+json")
  228. }
  229. // Tests that the response is serialized as JSON
  230. // and Content-Type is set to application/json
  231. func TestContextRenderIndentedJSON(t *testing.T) {
  232. c, w, _ := CreateTestContext()
  233. c.IndentedJSON(201, H{"foo": "bar", "bar": "foo", "nested": H{"foo": "bar"}})
  234. assert.Equal(t, w.Code, 201)
  235. assert.Equal(t, w.Body.String(), "{\n \"bar\": \"foo\",\n \"foo\": \"bar\",\n \"nested\": {\n \"foo\": \"bar\"\n }\n}")
  236. assert.Equal(t, w.HeaderMap.Get("Content-Type"), "application/json; charset=utf-8")
  237. }
  238. // Tests that the response executes the templates
  239. // and responds with Content-Type set to text/html
  240. func TestContextRenderHTML(t *testing.T) {
  241. c, w, router := CreateTestContext()
  242. templ := template.Must(template.New("t").Parse(`Hello {{.name}}`))
  243. router.SetHTMLTemplate(templ)
  244. c.HTML(201, "t", H{"name": "alexandernyquist"})
  245. assert.Equal(t, w.Code, 201)
  246. assert.Equal(t, w.Body.String(), "Hello alexandernyquist")
  247. assert.Equal(t, w.HeaderMap.Get("Content-Type"), "text/html; charset=utf-8")
  248. }
  249. // TestContextXML tests that the response is serialized as XML
  250. // and Content-Type is set to application/xml
  251. func TestContextRenderXML(t *testing.T) {
  252. c, w, _ := CreateTestContext()
  253. c.XML(201, H{"foo": "bar"})
  254. assert.Equal(t, w.Code, 201)
  255. assert.Equal(t, w.Body.String(), "<map><foo>bar</foo></map>")
  256. assert.Equal(t, w.HeaderMap.Get("Content-Type"), "application/xml; charset=utf-8")
  257. }
  258. // TestContextString tests that the response is returned
  259. // with Content-Type set to text/plain
  260. func TestContextRenderString(t *testing.T) {
  261. c, w, _ := CreateTestContext()
  262. c.String(201, "test %s %d", "string", 2)
  263. assert.Equal(t, w.Code, 201)
  264. assert.Equal(t, w.Body.String(), "test string 2")
  265. assert.Equal(t, w.HeaderMap.Get("Content-Type"), "text/plain; charset=utf-8")
  266. }
  267. // TestContextString tests that the response is returned
  268. // with Content-Type set to text/html
  269. func TestContextRenderHTMLString(t *testing.T) {
  270. c, w, _ := CreateTestContext()
  271. c.Header("Content-Type", "text/html; charset=utf-8")
  272. c.String(201, "<html>%s %d</html>", "string", 3)
  273. assert.Equal(t, w.Code, 201)
  274. assert.Equal(t, w.Body.String(), "<html>string 3</html>")
  275. assert.Equal(t, w.HeaderMap.Get("Content-Type"), "text/html; charset=utf-8")
  276. }
  277. // TestContextData tests that the response can be written from `bytesting`
  278. // with specified MIME type
  279. func TestContextRenderData(t *testing.T) {
  280. c, w, _ := CreateTestContext()
  281. c.Data(201, "text/csv", []byte(`foo,bar`))
  282. assert.Equal(t, w.Code, 201)
  283. assert.Equal(t, w.Body.String(), "foo,bar")
  284. assert.Equal(t, w.HeaderMap.Get("Content-Type"), "text/csv")
  285. }
  286. func TestContextRenderSSE(t *testing.T) {
  287. c, w, _ := CreateTestContext()
  288. c.SSEvent("float", 1.5)
  289. c.Render(-1, sse.Event{
  290. Id: "123",
  291. Data: "text",
  292. })
  293. c.SSEvent("chat", H{
  294. "foo": "bar",
  295. "bar": "foo",
  296. })
  297. 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))
  298. }
  299. func TestContextRenderFile(t *testing.T) {
  300. c, w, _ := CreateTestContext()
  301. c.Request, _ = http.NewRequest("GET", "/", nil)
  302. c.File("./gin.go")
  303. assert.Equal(t, w.Code, 200)
  304. assert.Contains(t, w.Body.String(), "func New() *Engine {")
  305. assert.Equal(t, w.HeaderMap.Get("Content-Type"), "text/plain; charset=utf-8")
  306. }
  307. func TestContextHeaders(t *testing.T) {
  308. c, _, _ := CreateTestContext()
  309. c.Header("Content-Type", "text/plain")
  310. c.Header("X-Custom", "value")
  311. assert.Equal(t, c.Writer.Header().Get("Content-Type"), "text/plain")
  312. assert.Equal(t, c.Writer.Header().Get("X-Custom"), "value")
  313. c.Header("Content-Type", "text/html")
  314. c.Header("X-Custom", "")
  315. assert.Equal(t, c.Writer.Header().Get("Content-Type"), "text/html")
  316. _, exist := c.Writer.Header()["X-Custom"]
  317. assert.False(t, exist)
  318. }
  319. // TODO
  320. func TestContextRenderRedirectWithRelativePath(t *testing.T) {
  321. c, w, _ := CreateTestContext()
  322. c.Request, _ = http.NewRequest("POST", "http://example.com", nil)
  323. assert.Panics(t, func() { c.Redirect(299, "/new_path") })
  324. assert.Panics(t, func() { c.Redirect(309, "/new_path") })
  325. c.Redirect(301, "/path")
  326. c.Writer.WriteHeaderNow()
  327. assert.Equal(t, w.Code, 301)
  328. assert.Equal(t, w.Header().Get("Location"), "/path")
  329. }
  330. func TestContextRenderRedirectWithAbsolutePath(t *testing.T) {
  331. c, w, _ := CreateTestContext()
  332. c.Request, _ = http.NewRequest("POST", "http://example.com", nil)
  333. c.Redirect(302, "http://google.com")
  334. c.Writer.WriteHeaderNow()
  335. assert.Equal(t, w.Code, 302)
  336. assert.Equal(t, w.Header().Get("Location"), "http://google.com")
  337. }
  338. func TestContextRenderRedirectWith201(t *testing.T) {
  339. c, w, _ := CreateTestContext()
  340. c.Request, _ = http.NewRequest("POST", "http://example.com", nil)
  341. c.Redirect(201, "/resource")
  342. c.Writer.WriteHeaderNow()
  343. assert.Equal(t, w.Code, 201)
  344. assert.Equal(t, w.Header().Get("Location"), "/resource")
  345. }
  346. func TestContextRenderRedirectAll(t *testing.T) {
  347. c, _, _ := CreateTestContext()
  348. c.Request, _ = http.NewRequest("POST", "http://example.com", nil)
  349. assert.Panics(t, func() { c.Redirect(200, "/resource") })
  350. assert.Panics(t, func() { c.Redirect(202, "/resource") })
  351. assert.Panics(t, func() { c.Redirect(299, "/resource") })
  352. assert.Panics(t, func() { c.Redirect(309, "/resource") })
  353. assert.NotPanics(t, func() { c.Redirect(300, "/resource") })
  354. assert.NotPanics(t, func() { c.Redirect(308, "/resource") })
  355. }
  356. func TestContextNegotiationFormat(t *testing.T) {
  357. c, _, _ := CreateTestContext()
  358. c.Request, _ = http.NewRequest("POST", "", nil)
  359. assert.Panics(t, func() { c.NegotiateFormat() })
  360. assert.Equal(t, c.NegotiateFormat(MIMEJSON, MIMEXML), MIMEJSON)
  361. assert.Equal(t, c.NegotiateFormat(MIMEHTML, MIMEJSON), MIMEHTML)
  362. }
  363. func TestContextNegotiationFormatWithAccept(t *testing.T) {
  364. c, _, _ := CreateTestContext()
  365. c.Request, _ = http.NewRequest("POST", "/", nil)
  366. c.Request.Header.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
  367. assert.Equal(t, c.NegotiateFormat(MIMEJSON, MIMEXML), MIMEXML)
  368. assert.Equal(t, c.NegotiateFormat(MIMEXML, MIMEHTML), MIMEHTML)
  369. assert.Equal(t, c.NegotiateFormat(MIMEJSON), "")
  370. }
  371. func TestContextNegotiationFormatCustum(t *testing.T) {
  372. c, _, _ := CreateTestContext()
  373. c.Request, _ = http.NewRequest("POST", "/", nil)
  374. c.Request.Header.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
  375. c.Accepted = nil
  376. c.SetAccepted(MIMEJSON, MIMEXML)
  377. assert.Equal(t, c.NegotiateFormat(MIMEJSON, MIMEXML), MIMEJSON)
  378. assert.Equal(t, c.NegotiateFormat(MIMEXML, MIMEHTML), MIMEXML)
  379. assert.Equal(t, c.NegotiateFormat(MIMEJSON), MIMEJSON)
  380. }
  381. func TestContextIsAborted(t *testing.T) {
  382. c, _, _ := CreateTestContext()
  383. assert.False(t, c.IsAborted())
  384. c.Abort()
  385. assert.True(t, c.IsAborted())
  386. c.Next()
  387. assert.True(t, c.IsAborted())
  388. c.index++
  389. assert.True(t, c.IsAborted())
  390. }
  391. // TestContextData tests that the response can be written from `bytesting`
  392. // with specified MIME type
  393. func TestContextAbortWithStatus(t *testing.T) {
  394. c, w, _ := CreateTestContext()
  395. c.index = 4
  396. c.AbortWithStatus(401)
  397. c.Writer.WriteHeaderNow()
  398. assert.Equal(t, c.index, abortIndex)
  399. assert.Equal(t, c.Writer.Status(), 401)
  400. assert.Equal(t, w.Code, 401)
  401. assert.True(t, c.IsAborted())
  402. }
  403. func TestContextError(t *testing.T) {
  404. c, _, _ := CreateTestContext()
  405. assert.Empty(t, c.Errors)
  406. c.Error(errors.New("first error"))
  407. assert.Len(t, c.Errors, 1)
  408. assert.Equal(t, c.Errors.String(), "Error #01: first error\n")
  409. c.Error(&Error{
  410. Err: errors.New("second error"),
  411. Meta: "some data 2",
  412. Type: ErrorTypePublic,
  413. })
  414. assert.Len(t, c.Errors, 2)
  415. assert.Equal(t, c.Errors[0].Err, errors.New("first error"))
  416. assert.Nil(t, c.Errors[0].Meta)
  417. assert.Equal(t, c.Errors[0].Type, ErrorTypePrivate)
  418. assert.Equal(t, c.Errors[1].Err, errors.New("second error"))
  419. assert.Equal(t, c.Errors[1].Meta, "some data 2")
  420. assert.Equal(t, c.Errors[1].Type, ErrorTypePublic)
  421. assert.Equal(t, c.Errors.Last(), c.Errors[1])
  422. }
  423. func TestContextTypedError(t *testing.T) {
  424. c, _, _ := CreateTestContext()
  425. c.Error(errors.New("externo 0")).SetType(ErrorTypePublic)
  426. c.Error(errors.New("interno 0")).SetType(ErrorTypePrivate)
  427. for _, err := range c.Errors.ByType(ErrorTypePublic) {
  428. assert.Equal(t, err.Type, ErrorTypePublic)
  429. }
  430. for _, err := range c.Errors.ByType(ErrorTypePrivate) {
  431. assert.Equal(t, err.Type, ErrorTypePrivate)
  432. }
  433. assert.Equal(t, c.Errors.Errors(), []string{"externo 0", "interno 0"})
  434. }
  435. func TestContextAbortWithError(t *testing.T) {
  436. c, w, _ := CreateTestContext()
  437. c.AbortWithError(401, errors.New("bad input")).SetMeta("some input")
  438. c.Writer.WriteHeaderNow()
  439. assert.Equal(t, w.Code, 401)
  440. assert.Equal(t, c.index, abortIndex)
  441. assert.True(t, c.IsAborted())
  442. }
  443. func TestContextClientIP(t *testing.T) {
  444. c, _, _ := CreateTestContext()
  445. c.Request, _ = http.NewRequest("POST", "/", nil)
  446. c.Request.Header.Set("X-Real-IP", " 10.10.10.10 ")
  447. c.Request.Header.Set("X-Forwarded-For", " 20.20.20.20, 30.30.30.30")
  448. c.Request.RemoteAddr = " 40.40.40.40:42123 "
  449. assert.Equal(t, c.ClientIP(), "10.10.10.10")
  450. c.Request.Header.Del("X-Real-IP")
  451. assert.Equal(t, c.ClientIP(), "20.20.20.20")
  452. c.Request.Header.Set("X-Forwarded-For", "30.30.30.30 ")
  453. assert.Equal(t, c.ClientIP(), "30.30.30.30")
  454. c.Request.Header.Del("X-Forwarded-For")
  455. assert.Equal(t, c.ClientIP(), "40.40.40.40")
  456. }
  457. func TestContextContentType(t *testing.T) {
  458. c, _, _ := CreateTestContext()
  459. c.Request, _ = http.NewRequest("POST", "/", nil)
  460. c.Request.Header.Set("Content-Type", "application/json; charset=utf-8")
  461. assert.Equal(t, c.ContentType(), "application/json")
  462. }
  463. func TestContextAutoBindJSON(t *testing.T) {
  464. c, _, _ := CreateTestContext()
  465. c.Request, _ = http.NewRequest("POST", "/", bytes.NewBufferString("{\"foo\":\"bar\", \"bar\":\"foo\"}"))
  466. c.Request.Header.Add("Content-Type", MIMEJSON)
  467. var obj struct {
  468. Foo string `json:"foo"`
  469. Bar string `json:"bar"`
  470. }
  471. assert.NoError(t, c.Bind(&obj))
  472. assert.Equal(t, obj.Bar, "foo")
  473. assert.Equal(t, obj.Foo, "bar")
  474. assert.Empty(t, c.Errors)
  475. }
  476. func TestContextBindWithJSON(t *testing.T) {
  477. c, w, _ := CreateTestContext()
  478. c.Request, _ = http.NewRequest("POST", "/", bytes.NewBufferString("{\"foo\":\"bar\", \"bar\":\"foo\"}"))
  479. c.Request.Header.Add("Content-Type", MIMEXML) // set fake content-type
  480. var obj struct {
  481. Foo string `json:"foo"`
  482. Bar string `json:"bar"`
  483. }
  484. assert.NoError(t, c.BindJSON(&obj))
  485. assert.Equal(t, obj.Bar, "foo")
  486. assert.Equal(t, obj.Foo, "bar")
  487. assert.Equal(t, w.Body.Len(), 0)
  488. }
  489. func TestContextBadAutoBind(t *testing.T) {
  490. c, w, _ := CreateTestContext()
  491. c.Request, _ = http.NewRequest("POST", "http://example.com", bytes.NewBufferString("\"foo\":\"bar\", \"bar\":\"foo\"}"))
  492. c.Request.Header.Add("Content-Type", MIMEJSON)
  493. var obj struct {
  494. Foo string `json:"foo"`
  495. Bar string `json:"bar"`
  496. }
  497. assert.False(t, c.IsAborted())
  498. assert.Error(t, c.Bind(&obj))
  499. c.Writer.WriteHeaderNow()
  500. assert.Empty(t, obj.Bar)
  501. assert.Empty(t, obj.Foo)
  502. assert.Equal(t, w.Code, 400)
  503. assert.True(t, c.IsAborted())
  504. }
  505. func TestContextGolangContext(t *testing.T) {
  506. c, _, _ := CreateTestContext()
  507. c.Request, _ = http.NewRequest("POST", "/", bytes.NewBufferString("{\"foo\":\"bar\", \"bar\":\"foo\"}"))
  508. assert.NoError(t, c.Err())
  509. assert.Nil(t, c.Done())
  510. ti, ok := c.Deadline()
  511. assert.Equal(t, ti, time.Time{})
  512. assert.False(t, ok)
  513. assert.Equal(t, c.Value(0), c.Request)
  514. assert.Nil(t, c.Value("foo"))
  515. c.Set("foo", "bar")
  516. assert.Equal(t, c.Value("foo"), "bar")
  517. assert.Nil(t, c.Value(1))
  518. }