context_test.go 23 KB

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