context_test.go 21 KB

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