context_test.go 21 KB

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