context_test.go 25 KB

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