context_test.go 23 KB

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