context_test.go 21 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697
  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. func TestContextHeaders(t *testing.T) {
  364. c, _, _ := CreateTestContext()
  365. c.Header("Content-Type", "text/plain")
  366. c.Header("X-Custom", "value")
  367. assert.Equal(t, c.Writer.Header().Get("Content-Type"), "text/plain")
  368. assert.Equal(t, c.Writer.Header().Get("X-Custom"), "value")
  369. c.Header("Content-Type", "text/html")
  370. c.Header("X-Custom", "")
  371. assert.Equal(t, c.Writer.Header().Get("Content-Type"), "text/html")
  372. _, exist := c.Writer.Header()["X-Custom"]
  373. assert.False(t, exist)
  374. }
  375. // TODO
  376. func TestContextRenderRedirectWithRelativePath(t *testing.T) {
  377. c, w, _ := CreateTestContext()
  378. c.Request, _ = http.NewRequest("POST", "http://example.com", nil)
  379. assert.Panics(t, func() { c.Redirect(299, "/new_path") })
  380. assert.Panics(t, func() { c.Redirect(309, "/new_path") })
  381. c.Redirect(301, "/path")
  382. c.Writer.WriteHeaderNow()
  383. assert.Equal(t, w.Code, 301)
  384. assert.Equal(t, w.Header().Get("Location"), "/path")
  385. }
  386. func TestContextRenderRedirectWithAbsolutePath(t *testing.T) {
  387. c, w, _ := CreateTestContext()
  388. c.Request, _ = http.NewRequest("POST", "http://example.com", nil)
  389. c.Redirect(302, "http://google.com")
  390. c.Writer.WriteHeaderNow()
  391. assert.Equal(t, w.Code, 302)
  392. assert.Equal(t, w.Header().Get("Location"), "http://google.com")
  393. }
  394. func TestContextRenderRedirectWith201(t *testing.T) {
  395. c, w, _ := CreateTestContext()
  396. c.Request, _ = http.NewRequest("POST", "http://example.com", nil)
  397. c.Redirect(201, "/resource")
  398. c.Writer.WriteHeaderNow()
  399. assert.Equal(t, w.Code, 201)
  400. assert.Equal(t, w.Header().Get("Location"), "/resource")
  401. }
  402. func TestContextRenderRedirectAll(t *testing.T) {
  403. c, _, _ := CreateTestContext()
  404. c.Request, _ = http.NewRequest("POST", "http://example.com", nil)
  405. assert.Panics(t, func() { c.Redirect(200, "/resource") })
  406. assert.Panics(t, func() { c.Redirect(202, "/resource") })
  407. assert.Panics(t, func() { c.Redirect(299, "/resource") })
  408. assert.Panics(t, func() { c.Redirect(309, "/resource") })
  409. assert.NotPanics(t, func() { c.Redirect(300, "/resource") })
  410. assert.NotPanics(t, func() { c.Redirect(308, "/resource") })
  411. }
  412. func TestContextNegotiationFormat(t *testing.T) {
  413. c, _, _ := CreateTestContext()
  414. c.Request, _ = http.NewRequest("POST", "", nil)
  415. assert.Panics(t, func() { c.NegotiateFormat() })
  416. assert.Equal(t, c.NegotiateFormat(MIMEJSON, MIMEXML), MIMEJSON)
  417. assert.Equal(t, c.NegotiateFormat(MIMEHTML, MIMEJSON), MIMEHTML)
  418. }
  419. func TestContextNegotiationFormatWithAccept(t *testing.T) {
  420. c, _, _ := CreateTestContext()
  421. c.Request, _ = http.NewRequest("POST", "/", nil)
  422. c.Request.Header.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
  423. assert.Equal(t, c.NegotiateFormat(MIMEJSON, MIMEXML), MIMEXML)
  424. assert.Equal(t, c.NegotiateFormat(MIMEXML, MIMEHTML), MIMEHTML)
  425. assert.Equal(t, c.NegotiateFormat(MIMEJSON), "")
  426. }
  427. func TestContextNegotiationFormatCustum(t *testing.T) {
  428. c, _, _ := CreateTestContext()
  429. c.Request, _ = http.NewRequest("POST", "/", nil)
  430. c.Request.Header.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
  431. c.Accepted = nil
  432. c.SetAccepted(MIMEJSON, MIMEXML)
  433. assert.Equal(t, c.NegotiateFormat(MIMEJSON, MIMEXML), MIMEJSON)
  434. assert.Equal(t, c.NegotiateFormat(MIMEXML, MIMEHTML), MIMEXML)
  435. assert.Equal(t, c.NegotiateFormat(MIMEJSON), MIMEJSON)
  436. }
  437. func TestContextIsAborted(t *testing.T) {
  438. c, _, _ := CreateTestContext()
  439. assert.False(t, c.IsAborted())
  440. c.Abort()
  441. assert.True(t, c.IsAborted())
  442. c.Next()
  443. assert.True(t, c.IsAborted())
  444. c.index++
  445. assert.True(t, c.IsAborted())
  446. }
  447. // TestContextData tests that the response can be written from `bytesting`
  448. // with specified MIME type
  449. func TestContextAbortWithStatus(t *testing.T) {
  450. c, w, _ := CreateTestContext()
  451. c.index = 4
  452. c.AbortWithStatus(401)
  453. c.Writer.WriteHeaderNow()
  454. assert.Equal(t, c.index, abortIndex)
  455. assert.Equal(t, c.Writer.Status(), 401)
  456. assert.Equal(t, w.Code, 401)
  457. assert.True(t, c.IsAborted())
  458. }
  459. func TestContextError(t *testing.T) {
  460. c, _, _ := CreateTestContext()
  461. assert.Empty(t, c.Errors)
  462. c.Error(errors.New("first error"))
  463. assert.Len(t, c.Errors, 1)
  464. assert.Equal(t, c.Errors.String(), "Error #01: first error\n")
  465. c.Error(&Error{
  466. Err: errors.New("second error"),
  467. Meta: "some data 2",
  468. Type: ErrorTypePublic,
  469. })
  470. assert.Len(t, c.Errors, 2)
  471. assert.Equal(t, c.Errors[0].Err, errors.New("first error"))
  472. assert.Nil(t, c.Errors[0].Meta)
  473. assert.Equal(t, c.Errors[0].Type, ErrorTypePrivate)
  474. assert.Equal(t, c.Errors[1].Err, errors.New("second error"))
  475. assert.Equal(t, c.Errors[1].Meta, "some data 2")
  476. assert.Equal(t, c.Errors[1].Type, ErrorTypePublic)
  477. assert.Equal(t, c.Errors.Last(), c.Errors[1])
  478. }
  479. func TestContextTypedError(t *testing.T) {
  480. c, _, _ := CreateTestContext()
  481. c.Error(errors.New("externo 0")).SetType(ErrorTypePublic)
  482. c.Error(errors.New("interno 0")).SetType(ErrorTypePrivate)
  483. for _, err := range c.Errors.ByType(ErrorTypePublic) {
  484. assert.Equal(t, err.Type, ErrorTypePublic)
  485. }
  486. for _, err := range c.Errors.ByType(ErrorTypePrivate) {
  487. assert.Equal(t, err.Type, ErrorTypePrivate)
  488. }
  489. assert.Equal(t, c.Errors.Errors(), []string{"externo 0", "interno 0"})
  490. }
  491. func TestContextAbortWithError(t *testing.T) {
  492. c, w, _ := CreateTestContext()
  493. c.AbortWithError(401, errors.New("bad input")).SetMeta("some input")
  494. c.Writer.WriteHeaderNow()
  495. assert.Equal(t, w.Code, 401)
  496. assert.Equal(t, c.index, abortIndex)
  497. assert.True(t, c.IsAborted())
  498. }
  499. func TestContextClientIP(t *testing.T) {
  500. c, _, _ := CreateTestContext()
  501. c.Request, _ = http.NewRequest("POST", "/", nil)
  502. c.Request.Header.Set("X-Real-IP", " 10.10.10.10 ")
  503. c.Request.Header.Set("X-Forwarded-For", " 20.20.20.20, 30.30.30.30")
  504. c.Request.RemoteAddr = " 40.40.40.40:42123 "
  505. assert.Equal(t, c.ClientIP(), "10.10.10.10")
  506. c.Request.Header.Del("X-Real-IP")
  507. assert.Equal(t, c.ClientIP(), "20.20.20.20")
  508. c.Request.Header.Set("X-Forwarded-For", "30.30.30.30 ")
  509. assert.Equal(t, c.ClientIP(), "30.30.30.30")
  510. c.Request.Header.Del("X-Forwarded-For")
  511. assert.Equal(t, c.ClientIP(), "40.40.40.40")
  512. }
  513. func TestContextContentType(t *testing.T) {
  514. c, _, _ := CreateTestContext()
  515. c.Request, _ = http.NewRequest("POST", "/", nil)
  516. c.Request.Header.Set("Content-Type", "application/json; charset=utf-8")
  517. assert.Equal(t, c.ContentType(), "application/json")
  518. }
  519. func TestContextAutoBindJSON(t *testing.T) {
  520. c, _, _ := CreateTestContext()
  521. c.Request, _ = http.NewRequest("POST", "/", bytes.NewBufferString("{\"foo\":\"bar\", \"bar\":\"foo\"}"))
  522. c.Request.Header.Add("Content-Type", MIMEJSON)
  523. var obj struct {
  524. Foo string `json:"foo"`
  525. Bar string `json:"bar"`
  526. }
  527. assert.NoError(t, c.Bind(&obj))
  528. assert.Equal(t, obj.Bar, "foo")
  529. assert.Equal(t, obj.Foo, "bar")
  530. assert.Empty(t, c.Errors)
  531. }
  532. func TestContextBindWithJSON(t *testing.T) {
  533. c, w, _ := CreateTestContext()
  534. c.Request, _ = http.NewRequest("POST", "/", bytes.NewBufferString("{\"foo\":\"bar\", \"bar\":\"foo\"}"))
  535. c.Request.Header.Add("Content-Type", MIMEXML) // set fake content-type
  536. var obj struct {
  537. Foo string `json:"foo"`
  538. Bar string `json:"bar"`
  539. }
  540. assert.NoError(t, c.BindJSON(&obj))
  541. assert.Equal(t, obj.Bar, "foo")
  542. assert.Equal(t, obj.Foo, "bar")
  543. assert.Equal(t, w.Body.Len(), 0)
  544. }
  545. func TestContextBadAutoBind(t *testing.T) {
  546. c, w, _ := CreateTestContext()
  547. c.Request, _ = http.NewRequest("POST", "http://example.com", bytes.NewBufferString("\"foo\":\"bar\", \"bar\":\"foo\"}"))
  548. c.Request.Header.Add("Content-Type", MIMEJSON)
  549. var obj struct {
  550. Foo string `json:"foo"`
  551. Bar string `json:"bar"`
  552. }
  553. assert.False(t, c.IsAborted())
  554. assert.Error(t, c.Bind(&obj))
  555. c.Writer.WriteHeaderNow()
  556. assert.Empty(t, obj.Bar)
  557. assert.Empty(t, obj.Foo)
  558. assert.Equal(t, w.Code, 400)
  559. assert.True(t, c.IsAborted())
  560. }
  561. func TestContextGolangContext(t *testing.T) {
  562. c, _, _ := CreateTestContext()
  563. c.Request, _ = http.NewRequest("POST", "/", bytes.NewBufferString("{\"foo\":\"bar\", \"bar\":\"foo\"}"))
  564. assert.NoError(t, c.Err())
  565. assert.Nil(t, c.Done())
  566. ti, ok := c.Deadline()
  567. assert.Equal(t, ti, time.Time{})
  568. assert.False(t, ok)
  569. assert.Equal(t, c.Value(0), c.Request)
  570. assert.Nil(t, c.Value("foo"))
  571. c.Set("foo", "bar")
  572. assert.Equal(t, c.Value("foo"), "bar")
  573. assert.Nil(t, c.Value(1))
  574. }