context_test.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741
  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(httptest.NewRecorder())
  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(httptest.NewRecorder())
  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(httptest.NewRecorder())
  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(httptest.NewRecorder())
  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(httptest.NewRecorder())
  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(httptest.NewRecorder())
  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(httptest.NewRecorder())
  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(httptest.NewRecorder())
  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(httptest.NewRecorder())
  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(httptest.NewRecorder())
  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. w := httptest.NewRecorder()
  270. c, _ := CreateTestContext(w)
  271. c.JSON(201, H{"foo": "bar"})
  272. assert.Equal(t, w.Code, 201)
  273. assert.Equal(t, w.Body.String(), "{\"foo\":\"bar\"}\n")
  274. assert.Equal(t, w.HeaderMap.Get("Content-Type"), "application/json; charset=utf-8")
  275. }
  276. // Tests that the response is serialized as JSON
  277. // we change the content-type before
  278. func TestContextRenderAPIJSON(t *testing.T) {
  279. w := httptest.NewRecorder()
  280. c, _ := CreateTestContext(w)
  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. w := httptest.NewRecorder()
  291. c, _ := CreateTestContext(w)
  292. c.IndentedJSON(201, H{"foo": "bar", "bar": "foo", "nested": H{"foo": "bar"}})
  293. assert.Equal(t, w.Code, 201)
  294. assert.Equal(t, w.Body.String(), "{\n \"bar\": \"foo\",\n \"foo\": \"bar\",\n \"nested\": {\n \"foo\": \"bar\"\n }\n}")
  295. assert.Equal(t, w.HeaderMap.Get("Content-Type"), "application/json; charset=utf-8")
  296. }
  297. // Tests that the response executes the templates
  298. // and responds with Content-Type set to text/html
  299. func TestContextRenderHTML(t *testing.T) {
  300. w := httptest.NewRecorder()
  301. c, router := CreateTestContext(w)
  302. templ := template.Must(template.New("t").Parse(`Hello {{.name}}`))
  303. router.SetHTMLTemplate(templ)
  304. c.HTML(201, "t", H{"name": "alexandernyquist"})
  305. assert.Equal(t, w.Code, 201)
  306. assert.Equal(t, w.Body.String(), "Hello alexandernyquist")
  307. assert.Equal(t, w.HeaderMap.Get("Content-Type"), "text/html; charset=utf-8")
  308. }
  309. // TestContextXML tests that the response is serialized as XML
  310. // and Content-Type is set to application/xml
  311. func TestContextRenderXML(t *testing.T) {
  312. w := httptest.NewRecorder()
  313. c, _ := CreateTestContext(w)
  314. c.XML(201, H{"foo": "bar"})
  315. assert.Equal(t, w.Code, 201)
  316. assert.Equal(t, w.Body.String(), "<map><foo>bar</foo></map>")
  317. assert.Equal(t, w.HeaderMap.Get("Content-Type"), "application/xml; charset=utf-8")
  318. }
  319. // TestContextString tests that the response is returned
  320. // with Content-Type set to text/plain
  321. func TestContextRenderString(t *testing.T) {
  322. w := httptest.NewRecorder()
  323. c, _ := CreateTestContext(w)
  324. c.String(201, "test %s %d", "string", 2)
  325. assert.Equal(t, w.Code, 201)
  326. assert.Equal(t, w.Body.String(), "test string 2")
  327. assert.Equal(t, w.HeaderMap.Get("Content-Type"), "text/plain; charset=utf-8")
  328. }
  329. // TestContextString tests that the response is returned
  330. // with Content-Type set to text/html
  331. func TestContextRenderHTMLString(t *testing.T) {
  332. w := httptest.NewRecorder()
  333. c, _ := CreateTestContext(w)
  334. c.Header("Content-Type", "text/html; charset=utf-8")
  335. c.String(201, "<html>%s %d</html>", "string", 3)
  336. assert.Equal(t, w.Code, 201)
  337. assert.Equal(t, w.Body.String(), "<html>string 3</html>")
  338. assert.Equal(t, w.HeaderMap.Get("Content-Type"), "text/html; charset=utf-8")
  339. }
  340. // TestContextData tests that the response can be written from `bytesting`
  341. // with specified MIME type
  342. func TestContextRenderData(t *testing.T) {
  343. w := httptest.NewRecorder()
  344. c, _ := CreateTestContext(w)
  345. c.Data(201, "text/csv", []byte(`foo,bar`))
  346. assert.Equal(t, w.Code, 201)
  347. assert.Equal(t, w.Body.String(), "foo,bar")
  348. assert.Equal(t, w.HeaderMap.Get("Content-Type"), "text/csv")
  349. }
  350. func TestContextRenderSSE(t *testing.T) {
  351. w := httptest.NewRecorder()
  352. c, _ := CreateTestContext(w)
  353. c.SSEvent("float", 1.5)
  354. c.Render(-1, sse.Event{
  355. Id: "123",
  356. Data: "text",
  357. })
  358. c.SSEvent("chat", H{
  359. "foo": "bar",
  360. "bar": "foo",
  361. })
  362. 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))
  363. }
  364. func TestContextRenderFile(t *testing.T) {
  365. w := httptest.NewRecorder()
  366. c, _ := CreateTestContext(w)
  367. c.Request, _ = http.NewRequest("GET", "/", nil)
  368. c.File("./gin.go")
  369. assert.Equal(t, w.Code, 200)
  370. assert.Contains(t, w.Body.String(), "func New() *Engine {")
  371. assert.Equal(t, w.HeaderMap.Get("Content-Type"), "text/plain; charset=utf-8")
  372. }
  373. // TestContextRenderYAML tests that the response is serialized as YAML
  374. // and Content-Type is set to application/x-yaml
  375. func TestContextRenderYAML(t *testing.T) {
  376. w := httptest.NewRecorder()
  377. c, _ := CreateTestContext(w)
  378. c.YAML(201, H{"foo": "bar"})
  379. assert.Equal(t, w.Code, 201)
  380. assert.Equal(t, w.Body.String(), "foo: bar\n")
  381. assert.Equal(t, w.HeaderMap.Get("Content-Type"), "application/x-yaml; charset=utf-8")
  382. }
  383. func TestContextHeaders(t *testing.T) {
  384. c, _ := CreateTestContext(httptest.NewRecorder())
  385. c.Header("Content-Type", "text/plain")
  386. c.Header("X-Custom", "value")
  387. assert.Equal(t, c.Writer.Header().Get("Content-Type"), "text/plain")
  388. assert.Equal(t, c.Writer.Header().Get("X-Custom"), "value")
  389. c.Header("Content-Type", "text/html")
  390. c.Header("X-Custom", "")
  391. assert.Equal(t, c.Writer.Header().Get("Content-Type"), "text/html")
  392. _, exist := c.Writer.Header()["X-Custom"]
  393. assert.False(t, exist)
  394. }
  395. // TODO
  396. func TestContextRenderRedirectWithRelativePath(t *testing.T) {
  397. w := httptest.NewRecorder()
  398. c, _ := CreateTestContext(w)
  399. c.Request, _ = http.NewRequest("POST", "http://example.com", nil)
  400. assert.Panics(t, func() { c.Redirect(299, "/new_path") })
  401. assert.Panics(t, func() { c.Redirect(309, "/new_path") })
  402. c.Redirect(301, "/path")
  403. c.Writer.WriteHeaderNow()
  404. assert.Equal(t, w.Code, 301)
  405. assert.Equal(t, w.Header().Get("Location"), "/path")
  406. }
  407. func TestContextRenderRedirectWithAbsolutePath(t *testing.T) {
  408. w := httptest.NewRecorder()
  409. c, _ := CreateTestContext(w)
  410. c.Request, _ = http.NewRequest("POST", "http://example.com", nil)
  411. c.Redirect(302, "http://google.com")
  412. c.Writer.WriteHeaderNow()
  413. assert.Equal(t, w.Code, 302)
  414. assert.Equal(t, w.Header().Get("Location"), "http://google.com")
  415. }
  416. func TestContextRenderRedirectWith201(t *testing.T) {
  417. w := httptest.NewRecorder()
  418. c, _ := CreateTestContext(w)
  419. c.Request, _ = http.NewRequest("POST", "http://example.com", nil)
  420. c.Redirect(201, "/resource")
  421. c.Writer.WriteHeaderNow()
  422. assert.Equal(t, w.Code, 201)
  423. assert.Equal(t, w.Header().Get("Location"), "/resource")
  424. }
  425. func TestContextRenderRedirectAll(t *testing.T) {
  426. c, _ := CreateTestContext(httptest.NewRecorder())
  427. c.Request, _ = http.NewRequest("POST", "http://example.com", nil)
  428. assert.Panics(t, func() { c.Redirect(200, "/resource") })
  429. assert.Panics(t, func() { c.Redirect(202, "/resource") })
  430. assert.Panics(t, func() { c.Redirect(299, "/resource") })
  431. assert.Panics(t, func() { c.Redirect(309, "/resource") })
  432. assert.NotPanics(t, func() { c.Redirect(300, "/resource") })
  433. assert.NotPanics(t, func() { c.Redirect(308, "/resource") })
  434. }
  435. func TestContextNegotiationFormat(t *testing.T) {
  436. c, _ := CreateTestContext(httptest.NewRecorder())
  437. c.Request, _ = http.NewRequest("POST", "", nil)
  438. assert.Panics(t, func() { c.NegotiateFormat() })
  439. assert.Equal(t, c.NegotiateFormat(MIMEJSON, MIMEXML), MIMEJSON)
  440. assert.Equal(t, c.NegotiateFormat(MIMEHTML, MIMEJSON), MIMEHTML)
  441. }
  442. func TestContextNegotiationFormatWithAccept(t *testing.T) {
  443. c, _ := CreateTestContext(httptest.NewRecorder())
  444. c.Request, _ = http.NewRequest("POST", "/", nil)
  445. c.Request.Header.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
  446. assert.Equal(t, c.NegotiateFormat(MIMEJSON, MIMEXML), MIMEXML)
  447. assert.Equal(t, c.NegotiateFormat(MIMEXML, MIMEHTML), MIMEHTML)
  448. assert.Equal(t, c.NegotiateFormat(MIMEJSON), "")
  449. }
  450. func TestContextNegotiationFormatCustum(t *testing.T) {
  451. c, _ := CreateTestContext(httptest.NewRecorder())
  452. c.Request, _ = http.NewRequest("POST", "/", nil)
  453. c.Request.Header.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
  454. c.Accepted = nil
  455. c.SetAccepted(MIMEJSON, MIMEXML)
  456. assert.Equal(t, c.NegotiateFormat(MIMEJSON, MIMEXML), MIMEJSON)
  457. assert.Equal(t, c.NegotiateFormat(MIMEXML, MIMEHTML), MIMEXML)
  458. assert.Equal(t, c.NegotiateFormat(MIMEJSON), MIMEJSON)
  459. }
  460. func TestContextIsAborted(t *testing.T) {
  461. c, _ := CreateTestContext(httptest.NewRecorder())
  462. assert.False(t, c.IsAborted())
  463. c.Abort()
  464. assert.True(t, c.IsAborted())
  465. c.Next()
  466. assert.True(t, c.IsAborted())
  467. c.index++
  468. assert.True(t, c.IsAborted())
  469. }
  470. // TestContextData tests that the response can be written from `bytesting`
  471. // with specified MIME type
  472. func TestContextAbortWithStatus(t *testing.T) {
  473. w := httptest.NewRecorder()
  474. c, _ := CreateTestContext(w)
  475. c.index = 4
  476. c.AbortWithStatus(401)
  477. assert.Equal(t, c.index, abortIndex)
  478. assert.Equal(t, c.Writer.Status(), 401)
  479. assert.Equal(t, w.Code, 401)
  480. assert.True(t, c.IsAborted())
  481. }
  482. func TestContextError(t *testing.T) {
  483. c, _ := CreateTestContext(httptest.NewRecorder())
  484. assert.Empty(t, c.Errors)
  485. c.Error(errors.New("first error"))
  486. assert.Len(t, c.Errors, 1)
  487. assert.Equal(t, c.Errors.String(), "Error #01: first error\n")
  488. c.Error(&Error{
  489. Err: errors.New("second error"),
  490. Meta: "some data 2",
  491. Type: ErrorTypePublic,
  492. })
  493. assert.Len(t, c.Errors, 2)
  494. assert.Equal(t, c.Errors[0].Err, errors.New("first error"))
  495. assert.Nil(t, c.Errors[0].Meta)
  496. assert.Equal(t, c.Errors[0].Type, ErrorTypePrivate)
  497. assert.Equal(t, c.Errors[1].Err, errors.New("second error"))
  498. assert.Equal(t, c.Errors[1].Meta, "some data 2")
  499. assert.Equal(t, c.Errors[1].Type, ErrorTypePublic)
  500. assert.Equal(t, c.Errors.Last(), c.Errors[1])
  501. }
  502. func TestContextTypedError(t *testing.T) {
  503. c, _ := CreateTestContext(httptest.NewRecorder())
  504. c.Error(errors.New("externo 0")).SetType(ErrorTypePublic)
  505. c.Error(errors.New("interno 0")).SetType(ErrorTypePrivate)
  506. for _, err := range c.Errors.ByType(ErrorTypePublic) {
  507. assert.Equal(t, err.Type, ErrorTypePublic)
  508. }
  509. for _, err := range c.Errors.ByType(ErrorTypePrivate) {
  510. assert.Equal(t, err.Type, ErrorTypePrivate)
  511. }
  512. assert.Equal(t, c.Errors.Errors(), []string{"externo 0", "interno 0"})
  513. }
  514. func TestContextAbortWithError(t *testing.T) {
  515. w := httptest.NewRecorder()
  516. c, _ := CreateTestContext(w)
  517. c.AbortWithError(401, errors.New("bad input")).SetMeta("some input")
  518. assert.Equal(t, w.Code, 401)
  519. assert.Equal(t, c.index, abortIndex)
  520. assert.True(t, c.IsAborted())
  521. }
  522. func TestContextClientIP(t *testing.T) {
  523. c, _ := CreateTestContext(httptest.NewRecorder())
  524. c.Request, _ = http.NewRequest("POST", "/", nil)
  525. c.Request.Header.Set("X-Real-IP", " 10.10.10.10 ")
  526. c.Request.Header.Set("X-Forwarded-For", " 20.20.20.20, 30.30.30.30")
  527. c.Request.RemoteAddr = " 40.40.40.40:42123 "
  528. assert.Equal(t, c.ClientIP(), "10.10.10.10")
  529. c.Request.Header.Del("X-Real-IP")
  530. assert.Equal(t, c.ClientIP(), "20.20.20.20")
  531. c.Request.Header.Set("X-Forwarded-For", "30.30.30.30 ")
  532. assert.Equal(t, c.ClientIP(), "30.30.30.30")
  533. c.Request.Header.Del("X-Forwarded-For")
  534. assert.Equal(t, c.ClientIP(), "40.40.40.40")
  535. }
  536. func TestContextContentType(t *testing.T) {
  537. c, _ := CreateTestContext(httptest.NewRecorder())
  538. c.Request, _ = http.NewRequest("POST", "/", nil)
  539. c.Request.Header.Set("Content-Type", "application/json; charset=utf-8")
  540. assert.Equal(t, c.ContentType(), "application/json")
  541. }
  542. func TestContextAutoBindJSON(t *testing.T) {
  543. c, _ := CreateTestContext(httptest.NewRecorder())
  544. c.Request, _ = http.NewRequest("POST", "/", bytes.NewBufferString("{\"foo\":\"bar\", \"bar\":\"foo\"}"))
  545. c.Request.Header.Add("Content-Type", MIMEJSON)
  546. var obj struct {
  547. Foo string `json:"foo"`
  548. Bar string `json:"bar"`
  549. }
  550. assert.NoError(t, c.Bind(&obj))
  551. assert.Equal(t, obj.Bar, "foo")
  552. assert.Equal(t, obj.Foo, "bar")
  553. assert.Empty(t, c.Errors)
  554. }
  555. func TestContextBindWithJSON(t *testing.T) {
  556. w := httptest.NewRecorder()
  557. c, _ := CreateTestContext(w)
  558. c.Request, _ = http.NewRequest("POST", "/", bytes.NewBufferString("{\"foo\":\"bar\", \"bar\":\"foo\"}"))
  559. c.Request.Header.Add("Content-Type", MIMEXML) // set fake content-type
  560. var obj struct {
  561. Foo string `json:"foo"`
  562. Bar string `json:"bar"`
  563. }
  564. assert.NoError(t, c.BindJSON(&obj))
  565. assert.Equal(t, obj.Bar, "foo")
  566. assert.Equal(t, obj.Foo, "bar")
  567. assert.Equal(t, w.Body.Len(), 0)
  568. }
  569. func TestContextBadAutoBind(t *testing.T) {
  570. w := httptest.NewRecorder()
  571. c, _ := CreateTestContext(w)
  572. c.Request, _ = http.NewRequest("POST", "http://example.com", bytes.NewBufferString("\"foo\":\"bar\", \"bar\":\"foo\"}"))
  573. c.Request.Header.Add("Content-Type", MIMEJSON)
  574. var obj struct {
  575. Foo string `json:"foo"`
  576. Bar string `json:"bar"`
  577. }
  578. assert.False(t, c.IsAborted())
  579. assert.Error(t, c.Bind(&obj))
  580. c.Writer.WriteHeaderNow()
  581. assert.Empty(t, obj.Bar)
  582. assert.Empty(t, obj.Foo)
  583. assert.Equal(t, w.Code, 400)
  584. assert.True(t, c.IsAborted())
  585. }
  586. func TestContextGolangContext(t *testing.T) {
  587. c, _ := CreateTestContext(httptest.NewRecorder())
  588. c.Request, _ = http.NewRequest("POST", "/", bytes.NewBufferString("{\"foo\":\"bar\", \"bar\":\"foo\"}"))
  589. assert.NoError(t, c.Err())
  590. assert.Nil(t, c.Done())
  591. ti, ok := c.Deadline()
  592. assert.Equal(t, ti, time.Time{})
  593. assert.False(t, ok)
  594. assert.Equal(t, c.Value(0), c.Request)
  595. assert.Nil(t, c.Value("foo"))
  596. c.Set("foo", "bar")
  597. assert.Equal(t, c.Value("foo"), "bar")
  598. assert.Nil(t, c.Value(1))
  599. }