context_test.go 31 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029
  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. "fmt"
  9. "html/template"
  10. "mime/multipart"
  11. "net/http"
  12. "net/http/httptest"
  13. "strings"
  14. "testing"
  15. "time"
  16. "github.com/stretchr/testify/assert"
  17. "golang.org/x/net/context"
  18. "gopkg.in/gin-contrib/sse.v0"
  19. )
  20. var _ context.Context = &Context{}
  21. // Unit tests TODO
  22. // func (c *Context) File(filepath string) {
  23. // func (c *Context) Negotiate(code int, config Negotiate) {
  24. // BAD case: func (c *Context) Render(code int, render render.Render, obj ...interface{}) {
  25. // test that information is not leaked when reusing Contexts (using the Pool)
  26. func createMultipartRequest() *http.Request {
  27. boundary := "--testboundary"
  28. body := new(bytes.Buffer)
  29. mw := multipart.NewWriter(body)
  30. defer mw.Close()
  31. must(mw.SetBoundary(boundary))
  32. must(mw.WriteField("foo", "bar"))
  33. must(mw.WriteField("bar", "10"))
  34. must(mw.WriteField("bar", "foo2"))
  35. must(mw.WriteField("array", "first"))
  36. must(mw.WriteField("array", "second"))
  37. must(mw.WriteField("id", ""))
  38. must(mw.WriteField("time_local", "31/12/2016 14:55"))
  39. must(mw.WriteField("time_utc", "31/12/2016 14:55"))
  40. req, err := http.NewRequest("POST", "/", body)
  41. must(err)
  42. req.Header.Set("Content-Type", MIMEMultipartPOSTForm+"; boundary="+boundary)
  43. return req
  44. }
  45. func must(err error) {
  46. if err != nil {
  47. panic(err.Error())
  48. }
  49. }
  50. func TestContextFormFile(t *testing.T) {
  51. buf := new(bytes.Buffer)
  52. mw := multipart.NewWriter(buf)
  53. w, err := mw.CreateFormFile("file", "test")
  54. if assert.NoError(t, err) {
  55. w.Write([]byte("test"))
  56. }
  57. mw.Close()
  58. c, _ := CreateTestContext(httptest.NewRecorder())
  59. c.Request, _ = http.NewRequest("POST", "/", buf)
  60. c.Request.Header.Set("Content-Type", mw.FormDataContentType())
  61. f, err := c.FormFile("file")
  62. if assert.NoError(t, err) {
  63. assert.Equal(t, "test", f.Filename)
  64. }
  65. }
  66. func TestContextMultipartForm(t *testing.T) {
  67. buf := new(bytes.Buffer)
  68. mw := multipart.NewWriter(buf)
  69. mw.WriteField("foo", "bar")
  70. mw.Close()
  71. c, _ := CreateTestContext(httptest.NewRecorder())
  72. c.Request, _ = http.NewRequest("POST", "/", buf)
  73. c.Request.Header.Set("Content-Type", mw.FormDataContentType())
  74. f, err := c.MultipartForm()
  75. if assert.NoError(t, err) {
  76. assert.NotNil(t, f)
  77. }
  78. }
  79. func TestContextReset(t *testing.T) {
  80. router := New()
  81. c := router.allocateContext()
  82. assert.Equal(t, c.engine, router)
  83. c.index = 2
  84. c.Writer = &responseWriter{ResponseWriter: httptest.NewRecorder()}
  85. c.Params = Params{Param{}}
  86. c.Error(errors.New("test"))
  87. c.Set("foo", "bar")
  88. c.reset()
  89. assert.False(t, c.IsAborted())
  90. assert.Nil(t, c.Keys)
  91. assert.Nil(t, c.Accepted)
  92. assert.Len(t, c.Errors, 0)
  93. assert.Empty(t, c.Errors.Errors())
  94. assert.Empty(t, c.Errors.ByType(ErrorTypeAny))
  95. assert.Len(t, c.Params, 0)
  96. assert.EqualValues(t, c.index, -1)
  97. assert.Equal(t, c.Writer.(*responseWriter), &c.writermem)
  98. }
  99. func TestContextHandlers(t *testing.T) {
  100. c, _ := CreateTestContext(httptest.NewRecorder())
  101. assert.Nil(t, c.handlers)
  102. assert.Nil(t, c.handlers.Last())
  103. c.handlers = HandlersChain{}
  104. assert.NotNil(t, c.handlers)
  105. assert.Nil(t, c.handlers.Last())
  106. f := func(c *Context) {}
  107. g := func(c *Context) {}
  108. c.handlers = HandlersChain{f}
  109. compareFunc(t, f, c.handlers.Last())
  110. c.handlers = HandlersChain{f, g}
  111. compareFunc(t, g, c.handlers.Last())
  112. }
  113. // TestContextSetGet tests that a parameter is set correctly on the
  114. // current context and can be retrieved using Get.
  115. func TestContextSetGet(t *testing.T) {
  116. c, _ := CreateTestContext(httptest.NewRecorder())
  117. c.Set("foo", "bar")
  118. value, err := c.Get("foo")
  119. assert.Equal(t, value, "bar")
  120. assert.True(t, err)
  121. value, err = c.Get("foo2")
  122. assert.Nil(t, value)
  123. assert.False(t, err)
  124. assert.Equal(t, c.MustGet("foo"), "bar")
  125. assert.Panics(t, func() { c.MustGet("no_exist") })
  126. }
  127. func TestContextSetGetValues(t *testing.T) {
  128. c, _ := CreateTestContext(httptest.NewRecorder())
  129. c.Set("string", "this is a string")
  130. c.Set("int32", int32(-42))
  131. c.Set("int64", int64(42424242424242))
  132. c.Set("uint64", uint64(42))
  133. c.Set("float32", float32(4.2))
  134. c.Set("float64", 4.2)
  135. var a interface{} = 1
  136. c.Set("intInterface", a)
  137. assert.Exactly(t, c.MustGet("string").(string), "this is a string")
  138. assert.Exactly(t, c.MustGet("int32").(int32), int32(-42))
  139. assert.Exactly(t, c.MustGet("int64").(int64), int64(42424242424242))
  140. assert.Exactly(t, c.MustGet("uint64").(uint64), uint64(42))
  141. assert.Exactly(t, c.MustGet("float32").(float32), float32(4.2))
  142. assert.Exactly(t, c.MustGet("float64").(float64), 4.2)
  143. assert.Exactly(t, c.MustGet("intInterface").(int), 1)
  144. }
  145. func TestContextCopy(t *testing.T) {
  146. c, _ := CreateTestContext(httptest.NewRecorder())
  147. c.index = 2
  148. c.Request, _ = http.NewRequest("POST", "/hola", nil)
  149. c.handlers = HandlersChain{func(c *Context) {}}
  150. c.Params = Params{Param{Key: "foo", Value: "bar"}}
  151. c.Set("foo", "bar")
  152. cp := c.Copy()
  153. assert.Nil(t, cp.handlers)
  154. assert.Nil(t, cp.writermem.ResponseWriter)
  155. assert.Equal(t, &cp.writermem, cp.Writer.(*responseWriter))
  156. assert.Equal(t, cp.Request, c.Request)
  157. assert.Equal(t, cp.index, abortIndex)
  158. assert.Equal(t, cp.Keys, c.Keys)
  159. assert.Equal(t, cp.engine, c.engine)
  160. assert.Equal(t, cp.Params, c.Params)
  161. }
  162. func TestContextHandlerName(t *testing.T) {
  163. c, _ := CreateTestContext(httptest.NewRecorder())
  164. c.handlers = HandlersChain{func(c *Context) {}, handlerNameTest}
  165. assert.Regexp(t, "^(.*/vendor/)?github.com/gin-gonic/gin.handlerNameTest$", c.HandlerName())
  166. }
  167. func handlerNameTest(c *Context) {
  168. }
  169. func TestContextQuery(t *testing.T) {
  170. c, _ := CreateTestContext(httptest.NewRecorder())
  171. c.Request, _ = http.NewRequest("GET", "http://example.com/?foo=bar&page=10&id=", nil)
  172. value, ok := c.GetQuery("foo")
  173. assert.True(t, ok)
  174. assert.Equal(t, value, "bar")
  175. assert.Equal(t, c.DefaultQuery("foo", "none"), "bar")
  176. assert.Equal(t, c.Query("foo"), "bar")
  177. value, ok = c.GetQuery("page")
  178. assert.True(t, ok)
  179. assert.Equal(t, value, "10")
  180. assert.Equal(t, c.DefaultQuery("page", "0"), "10")
  181. assert.Equal(t, c.Query("page"), "10")
  182. value, ok = c.GetQuery("id")
  183. assert.True(t, ok)
  184. assert.Empty(t, value)
  185. assert.Equal(t, c.DefaultQuery("id", "nada"), "")
  186. assert.Empty(t, c.Query("id"))
  187. value, ok = c.GetQuery("NoKey")
  188. assert.False(t, ok)
  189. assert.Empty(t, value)
  190. assert.Equal(t, c.DefaultQuery("NoKey", "nada"), "nada")
  191. assert.Empty(t, c.Query("NoKey"))
  192. // postform should not mess
  193. value, ok = c.GetPostForm("page")
  194. assert.False(t, ok)
  195. assert.Empty(t, value)
  196. assert.Empty(t, c.PostForm("foo"))
  197. }
  198. func TestContextQueryAndPostForm(t *testing.T) {
  199. c, _ := CreateTestContext(httptest.NewRecorder())
  200. body := bytes.NewBufferString("foo=bar&page=11&both=&foo=second")
  201. c.Request, _ = http.NewRequest("POST", "/?both=GET&id=main&id=omit&array[]=first&array[]=second", body)
  202. c.Request.Header.Add("Content-Type", MIMEPOSTForm)
  203. assert.Equal(t, c.DefaultPostForm("foo", "none"), "bar")
  204. assert.Equal(t, c.PostForm("foo"), "bar")
  205. assert.Empty(t, c.Query("foo"))
  206. value, ok := c.GetPostForm("page")
  207. assert.True(t, ok)
  208. assert.Equal(t, value, "11")
  209. assert.Equal(t, c.DefaultPostForm("page", "0"), "11")
  210. assert.Equal(t, c.PostForm("page"), "11")
  211. assert.Equal(t, c.Query("page"), "")
  212. value, ok = c.GetPostForm("both")
  213. assert.True(t, ok)
  214. assert.Empty(t, value)
  215. assert.Empty(t, c.PostForm("both"))
  216. assert.Equal(t, c.DefaultPostForm("both", "nothing"), "")
  217. assert.Equal(t, c.Query("both"), "GET")
  218. value, ok = c.GetQuery("id")
  219. assert.True(t, ok)
  220. assert.Equal(t, value, "main")
  221. assert.Equal(t, c.DefaultPostForm("id", "000"), "000")
  222. assert.Equal(t, c.Query("id"), "main")
  223. assert.Empty(t, c.PostForm("id"))
  224. value, ok = c.GetQuery("NoKey")
  225. assert.False(t, ok)
  226. assert.Empty(t, value)
  227. value, ok = c.GetPostForm("NoKey")
  228. assert.False(t, ok)
  229. assert.Empty(t, value)
  230. assert.Equal(t, c.DefaultPostForm("NoKey", "nada"), "nada")
  231. assert.Equal(t, c.DefaultQuery("NoKey", "nothing"), "nothing")
  232. assert.Empty(t, c.PostForm("NoKey"))
  233. assert.Empty(t, c.Query("NoKey"))
  234. var obj struct {
  235. Foo string `form:"foo"`
  236. ID string `form:"id"`
  237. Page int `form:"page"`
  238. Both string `form:"both"`
  239. Array []string `form:"array[]"`
  240. }
  241. assert.NoError(t, c.Bind(&obj))
  242. assert.Equal(t, obj.Foo, "bar")
  243. assert.Equal(t, obj.ID, "main")
  244. assert.Equal(t, obj.Page, 11)
  245. assert.Equal(t, obj.Both, "")
  246. assert.Equal(t, obj.Array, []string{"first", "second"})
  247. values, ok := c.GetQueryArray("array[]")
  248. assert.True(t, ok)
  249. assert.Equal(t, "first", values[0])
  250. assert.Equal(t, "second", values[1])
  251. values = c.QueryArray("array[]")
  252. assert.Equal(t, "first", values[0])
  253. assert.Equal(t, "second", values[1])
  254. values = c.QueryArray("nokey")
  255. assert.Equal(t, 0, len(values))
  256. values = c.QueryArray("both")
  257. assert.Equal(t, 1, len(values))
  258. assert.Equal(t, "GET", values[0])
  259. }
  260. func TestContextPostFormMultipart(t *testing.T) {
  261. c, _ := CreateTestContext(httptest.NewRecorder())
  262. c.Request = createMultipartRequest()
  263. var obj struct {
  264. Foo string `form:"foo"`
  265. Bar string `form:"bar"`
  266. BarAsInt int `form:"bar"`
  267. Array []string `form:"array"`
  268. ID string `form:"id"`
  269. TimeLocal time.Time `form:"time_local" time_format:"02/01/2006 15:04"`
  270. TimeUTC time.Time `form:"time_utc" time_format:"02/01/2006 15:04" time_utc:"1"`
  271. BlankTime time.Time `form:"blank_time" time_format:"02/01/2006 15:04"`
  272. }
  273. assert.NoError(t, c.Bind(&obj))
  274. assert.Equal(t, obj.Foo, "bar")
  275. assert.Equal(t, obj.Bar, "10")
  276. assert.Equal(t, obj.BarAsInt, 10)
  277. assert.Equal(t, obj.Array, []string{"first", "second"})
  278. assert.Equal(t, obj.ID, "")
  279. assert.Equal(t, obj.TimeLocal.Format("02/01/2006 15:04"), "31/12/2016 14:55")
  280. assert.Equal(t, obj.TimeLocal.Location(), time.Local)
  281. assert.Equal(t, obj.TimeUTC.Format("02/01/2006 15:04"), "31/12/2016 14:55")
  282. assert.Equal(t, obj.TimeUTC.Location(), time.UTC)
  283. assert.True(t, obj.BlankTime.IsZero())
  284. value, ok := c.GetQuery("foo")
  285. assert.False(t, ok)
  286. assert.Empty(t, value)
  287. assert.Empty(t, c.Query("bar"))
  288. assert.Equal(t, c.DefaultQuery("id", "nothing"), "nothing")
  289. value, ok = c.GetPostForm("foo")
  290. assert.True(t, ok)
  291. assert.Equal(t, value, "bar")
  292. assert.Equal(t, c.PostForm("foo"), "bar")
  293. value, ok = c.GetPostForm("array")
  294. assert.True(t, ok)
  295. assert.Equal(t, value, "first")
  296. assert.Equal(t, c.PostForm("array"), "first")
  297. assert.Equal(t, c.DefaultPostForm("bar", "nothing"), "10")
  298. value, ok = c.GetPostForm("id")
  299. assert.True(t, ok)
  300. assert.Empty(t, value)
  301. assert.Empty(t, c.PostForm("id"))
  302. assert.Empty(t, c.DefaultPostForm("id", "nothing"))
  303. value, ok = c.GetPostForm("nokey")
  304. assert.False(t, ok)
  305. assert.Empty(t, value)
  306. assert.Equal(t, c.DefaultPostForm("nokey", "nothing"), "nothing")
  307. values, ok := c.GetPostFormArray("array")
  308. assert.True(t, ok)
  309. assert.Equal(t, "first", values[0])
  310. assert.Equal(t, "second", values[1])
  311. values = c.PostFormArray("array")
  312. assert.Equal(t, "first", values[0])
  313. assert.Equal(t, "second", values[1])
  314. values = c.PostFormArray("nokey")
  315. assert.Equal(t, 0, len(values))
  316. values = c.PostFormArray("foo")
  317. assert.Equal(t, 1, len(values))
  318. assert.Equal(t, "bar", values[0])
  319. }
  320. func TestContextSetCookie(t *testing.T) {
  321. c, _ := CreateTestContext(httptest.NewRecorder())
  322. c.SetCookie("user", "gin", 1, "/", "localhost", true, true)
  323. assert.Equal(t, c.Writer.Header().Get("Set-Cookie"), "user=gin; Path=/; Domain=localhost; Max-Age=1; HttpOnly; Secure")
  324. }
  325. func TestContextGetCookie(t *testing.T) {
  326. c, _ := CreateTestContext(httptest.NewRecorder())
  327. c.Request, _ = http.NewRequest("GET", "/get", nil)
  328. c.Request.Header.Set("Cookie", "user=gin")
  329. cookie, _ := c.Cookie("user")
  330. assert.Equal(t, cookie, "gin")
  331. }
  332. func TestContextBodyAllowedForStatus(t *testing.T) {
  333. assert.Equal(t, false, bodyAllowedForStatus(102))
  334. assert.Equal(t, false, bodyAllowedForStatus(204))
  335. assert.Equal(t, false, bodyAllowedForStatus(304))
  336. assert.Equal(t, true, bodyAllowedForStatus(500))
  337. }
  338. type TestPanicRender struct {
  339. }
  340. func (*TestPanicRender) Render(http.ResponseWriter) error {
  341. return errors.New("TestPanicRender")
  342. }
  343. func (*TestPanicRender) WriteContentType(http.ResponseWriter) {}
  344. func TestContextRenderPanicIfErr(t *testing.T) {
  345. defer func() {
  346. r := recover()
  347. assert.Equal(t, "TestPanicRender", fmt.Sprint(r))
  348. }()
  349. w := httptest.NewRecorder()
  350. c, _ := CreateTestContext(w)
  351. c.Render(http.StatusOK, &TestPanicRender{})
  352. assert.Fail(t, "Panic not detected")
  353. }
  354. // Tests that the response is serialized as JSON
  355. // and Content-Type is set to application/json
  356. func TestContextRenderJSON(t *testing.T) {
  357. w := httptest.NewRecorder()
  358. c, _ := CreateTestContext(w)
  359. c.JSON(201, H{"foo": "bar"})
  360. assert.Equal(t, 201, w.Code)
  361. assert.Equal(t, "{\"foo\":\"bar\"}", w.Body.String())
  362. assert.Equal(t, "application/json; charset=utf-8", w.HeaderMap.Get("Content-Type"))
  363. }
  364. // Tests that no JSON is rendered if code is 204
  365. func TestContextRenderNoContentJSON(t *testing.T) {
  366. w := httptest.NewRecorder()
  367. c, _ := CreateTestContext(w)
  368. c.JSON(204, H{"foo": "bar"})
  369. assert.Equal(t, 204, w.Code)
  370. assert.Equal(t, "", w.Body.String())
  371. assert.Equal(t, "application/json; charset=utf-8", w.HeaderMap.Get("Content-Type"))
  372. }
  373. // Tests that the response is serialized as JSON
  374. // we change the content-type before
  375. func TestContextRenderAPIJSON(t *testing.T) {
  376. w := httptest.NewRecorder()
  377. c, _ := CreateTestContext(w)
  378. c.Header("Content-Type", "application/vnd.api+json")
  379. c.JSON(201, H{"foo": "bar"})
  380. assert.Equal(t, 201, w.Code)
  381. assert.Equal(t, "{\"foo\":\"bar\"}", w.Body.String())
  382. assert.Equal(t, "application/vnd.api+json", w.HeaderMap.Get("Content-Type"))
  383. }
  384. // Tests that no Custom JSON is rendered if code is 204
  385. func TestContextRenderNoContentAPIJSON(t *testing.T) {
  386. w := httptest.NewRecorder()
  387. c, _ := CreateTestContext(w)
  388. c.Header("Content-Type", "application/vnd.api+json")
  389. c.JSON(204, H{"foo": "bar"})
  390. assert.Equal(t, 204, w.Code)
  391. assert.Equal(t, "", w.Body.String())
  392. assert.Equal(t, w.HeaderMap.Get("Content-Type"), "application/vnd.api+json")
  393. }
  394. // Tests that the response is serialized as JSON
  395. // and Content-Type is set to application/json
  396. func TestContextRenderIndentedJSON(t *testing.T) {
  397. w := httptest.NewRecorder()
  398. c, _ := CreateTestContext(w)
  399. c.IndentedJSON(201, H{"foo": "bar", "bar": "foo", "nested": H{"foo": "bar"}})
  400. assert.Equal(t, w.Code, 201)
  401. assert.Equal(t, w.Body.String(), "{\n \"bar\": \"foo\",\n \"foo\": \"bar\",\n \"nested\": {\n \"foo\": \"bar\"\n }\n}")
  402. assert.Equal(t, w.HeaderMap.Get("Content-Type"), "application/json; charset=utf-8")
  403. }
  404. // Tests that no Custom JSON is rendered if code is 204
  405. func TestContextRenderNoContentIndentedJSON(t *testing.T) {
  406. w := httptest.NewRecorder()
  407. c, _ := CreateTestContext(w)
  408. c.IndentedJSON(204, H{"foo": "bar", "bar": "foo", "nested": H{"foo": "bar"}})
  409. assert.Equal(t, 204, w.Code)
  410. assert.Equal(t, "", w.Body.String())
  411. assert.Equal(t, w.HeaderMap.Get("Content-Type"), "application/json; charset=utf-8")
  412. }
  413. // Tests that the response executes the templates
  414. // and responds with Content-Type set to text/html
  415. func TestContextRenderHTML(t *testing.T) {
  416. w := httptest.NewRecorder()
  417. c, router := CreateTestContext(w)
  418. templ := template.Must(template.New("t").Parse(`Hello {{.name}}`))
  419. router.SetHTMLTemplate(templ)
  420. c.HTML(201, "t", H{"name": "alexandernyquist"})
  421. assert.Equal(t, w.Code, 201)
  422. assert.Equal(t, w.Body.String(), "Hello alexandernyquist")
  423. assert.Equal(t, w.HeaderMap.Get("Content-Type"), "text/html; charset=utf-8")
  424. }
  425. // Tests that no HTML is rendered if code is 204
  426. func TestContextRenderNoContentHTML(t *testing.T) {
  427. w := httptest.NewRecorder()
  428. c, router := CreateTestContext(w)
  429. templ := template.Must(template.New("t").Parse(`Hello {{.name}}`))
  430. router.SetHTMLTemplate(templ)
  431. c.HTML(204, "t", H{"name": "alexandernyquist"})
  432. assert.Equal(t, 204, w.Code)
  433. assert.Equal(t, "", w.Body.String())
  434. assert.Equal(t, w.HeaderMap.Get("Content-Type"), "text/html; charset=utf-8")
  435. }
  436. // TestContextXML tests that the response is serialized as XML
  437. // and Content-Type is set to application/xml
  438. func TestContextRenderXML(t *testing.T) {
  439. w := httptest.NewRecorder()
  440. c, _ := CreateTestContext(w)
  441. c.XML(201, H{"foo": "bar"})
  442. assert.Equal(t, w.Code, 201)
  443. assert.Equal(t, w.Body.String(), "<map><foo>bar</foo></map>")
  444. assert.Equal(t, w.HeaderMap.Get("Content-Type"), "application/xml; charset=utf-8")
  445. }
  446. // Tests that no XML is rendered if code is 204
  447. func TestContextRenderNoContentXML(t *testing.T) {
  448. w := httptest.NewRecorder()
  449. c, _ := CreateTestContext(w)
  450. c.XML(204, H{"foo": "bar"})
  451. assert.Equal(t, 204, w.Code)
  452. assert.Equal(t, "", w.Body.String())
  453. assert.Equal(t, w.HeaderMap.Get("Content-Type"), "application/xml; charset=utf-8")
  454. }
  455. // TestContextString tests that the response is returned
  456. // with Content-Type set to text/plain
  457. func TestContextRenderString(t *testing.T) {
  458. w := httptest.NewRecorder()
  459. c, _ := CreateTestContext(w)
  460. c.String(201, "test %s %d", "string", 2)
  461. assert.Equal(t, w.Code, 201)
  462. assert.Equal(t, w.Body.String(), "test string 2")
  463. assert.Equal(t, w.HeaderMap.Get("Content-Type"), "text/plain; charset=utf-8")
  464. }
  465. // Tests that no String is rendered if code is 204
  466. func TestContextRenderNoContentString(t *testing.T) {
  467. w := httptest.NewRecorder()
  468. c, _ := CreateTestContext(w)
  469. c.String(204, "test %s %d", "string", 2)
  470. assert.Equal(t, 204, w.Code)
  471. assert.Equal(t, "", w.Body.String())
  472. assert.Equal(t, w.HeaderMap.Get("Content-Type"), "text/plain; charset=utf-8")
  473. }
  474. // TestContextString tests that the response is returned
  475. // with Content-Type set to text/html
  476. func TestContextRenderHTMLString(t *testing.T) {
  477. w := httptest.NewRecorder()
  478. c, _ := CreateTestContext(w)
  479. c.Header("Content-Type", "text/html; charset=utf-8")
  480. c.String(201, "<html>%s %d</html>", "string", 3)
  481. assert.Equal(t, w.Code, 201)
  482. assert.Equal(t, w.Body.String(), "<html>string 3</html>")
  483. assert.Equal(t, w.HeaderMap.Get("Content-Type"), "text/html; charset=utf-8")
  484. }
  485. // Tests that no HTML String is rendered if code is 204
  486. func TestContextRenderNoContentHTMLString(t *testing.T) {
  487. w := httptest.NewRecorder()
  488. c, _ := CreateTestContext(w)
  489. c.Header("Content-Type", "text/html; charset=utf-8")
  490. c.String(204, "<html>%s %d</html>", "string", 3)
  491. assert.Equal(t, 204, w.Code)
  492. assert.Equal(t, "", w.Body.String())
  493. assert.Equal(t, w.HeaderMap.Get("Content-Type"), "text/html; charset=utf-8")
  494. }
  495. // TestContextData tests that the response can be written from `bytesting`
  496. // with specified MIME type
  497. func TestContextRenderData(t *testing.T) {
  498. w := httptest.NewRecorder()
  499. c, _ := CreateTestContext(w)
  500. c.Data(201, "text/csv", []byte(`foo,bar`))
  501. assert.Equal(t, w.Code, 201)
  502. assert.Equal(t, w.Body.String(), "foo,bar")
  503. assert.Equal(t, w.HeaderMap.Get("Content-Type"), "text/csv")
  504. }
  505. // Tests that no Custom Data is rendered if code is 204
  506. func TestContextRenderNoContentData(t *testing.T) {
  507. w := httptest.NewRecorder()
  508. c, _ := CreateTestContext(w)
  509. c.Data(204, "text/csv", []byte(`foo,bar`))
  510. assert.Equal(t, 204, w.Code)
  511. assert.Equal(t, "", w.Body.String())
  512. assert.Equal(t, w.HeaderMap.Get("Content-Type"), "text/csv")
  513. }
  514. func TestContextRenderSSE(t *testing.T) {
  515. w := httptest.NewRecorder()
  516. c, _ := CreateTestContext(w)
  517. c.SSEvent("float", 1.5)
  518. c.Render(-1, sse.Event{
  519. Id: "123",
  520. Data: "text",
  521. })
  522. c.SSEvent("chat", H{
  523. "foo": "bar",
  524. "bar": "foo",
  525. })
  526. 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))
  527. }
  528. func TestContextRenderFile(t *testing.T) {
  529. w := httptest.NewRecorder()
  530. c, _ := CreateTestContext(w)
  531. c.Request, _ = http.NewRequest("GET", "/", nil)
  532. c.File("./gin.go")
  533. assert.Equal(t, w.Code, 200)
  534. assert.Contains(t, w.Body.String(), "func New() *Engine {")
  535. assert.Equal(t, w.HeaderMap.Get("Content-Type"), "text/plain; charset=utf-8")
  536. }
  537. // TestContextRenderYAML tests that the response is serialized as YAML
  538. // and Content-Type is set to application/x-yaml
  539. func TestContextRenderYAML(t *testing.T) {
  540. w := httptest.NewRecorder()
  541. c, _ := CreateTestContext(w)
  542. c.YAML(201, H{"foo": "bar"})
  543. assert.Equal(t, w.Code, 201)
  544. assert.Equal(t, w.Body.String(), "foo: bar\n")
  545. assert.Equal(t, w.HeaderMap.Get("Content-Type"), "application/x-yaml; charset=utf-8")
  546. }
  547. func TestContextHeaders(t *testing.T) {
  548. c, _ := CreateTestContext(httptest.NewRecorder())
  549. c.Header("Content-Type", "text/plain")
  550. c.Header("X-Custom", "value")
  551. assert.Equal(t, c.Writer.Header().Get("Content-Type"), "text/plain")
  552. assert.Equal(t, c.Writer.Header().Get("X-Custom"), "value")
  553. c.Header("Content-Type", "text/html")
  554. c.Header("X-Custom", "")
  555. assert.Equal(t, c.Writer.Header().Get("Content-Type"), "text/html")
  556. _, exist := c.Writer.Header()["X-Custom"]
  557. assert.False(t, exist)
  558. }
  559. // TODO
  560. func TestContextRenderRedirectWithRelativePath(t *testing.T) {
  561. w := httptest.NewRecorder()
  562. c, _ := CreateTestContext(w)
  563. c.Request, _ = http.NewRequest("POST", "http://example.com", nil)
  564. assert.Panics(t, func() { c.Redirect(299, "/new_path") })
  565. assert.Panics(t, func() { c.Redirect(309, "/new_path") })
  566. c.Redirect(301, "/path")
  567. c.Writer.WriteHeaderNow()
  568. assert.Equal(t, w.Code, 301)
  569. assert.Equal(t, w.Header().Get("Location"), "/path")
  570. }
  571. func TestContextRenderRedirectWithAbsolutePath(t *testing.T) {
  572. w := httptest.NewRecorder()
  573. c, _ := CreateTestContext(w)
  574. c.Request, _ = http.NewRequest("POST", "http://example.com", nil)
  575. c.Redirect(302, "http://google.com")
  576. c.Writer.WriteHeaderNow()
  577. assert.Equal(t, w.Code, 302)
  578. assert.Equal(t, w.Header().Get("Location"), "http://google.com")
  579. }
  580. func TestContextRenderRedirectWith201(t *testing.T) {
  581. w := httptest.NewRecorder()
  582. c, _ := CreateTestContext(w)
  583. c.Request, _ = http.NewRequest("POST", "http://example.com", nil)
  584. c.Redirect(201, "/resource")
  585. c.Writer.WriteHeaderNow()
  586. assert.Equal(t, w.Code, 201)
  587. assert.Equal(t, w.Header().Get("Location"), "/resource")
  588. }
  589. func TestContextRenderRedirectAll(t *testing.T) {
  590. c, _ := CreateTestContext(httptest.NewRecorder())
  591. c.Request, _ = http.NewRequest("POST", "http://example.com", nil)
  592. assert.Panics(t, func() { c.Redirect(200, "/resource") })
  593. assert.Panics(t, func() { c.Redirect(202, "/resource") })
  594. assert.Panics(t, func() { c.Redirect(299, "/resource") })
  595. assert.Panics(t, func() { c.Redirect(309, "/resource") })
  596. assert.NotPanics(t, func() { c.Redirect(300, "/resource") })
  597. assert.NotPanics(t, func() { c.Redirect(308, "/resource") })
  598. }
  599. func TestContextNegotiationFormat(t *testing.T) {
  600. c, _ := CreateTestContext(httptest.NewRecorder())
  601. c.Request, _ = http.NewRequest("POST", "", nil)
  602. assert.Panics(t, func() { c.NegotiateFormat() })
  603. assert.Equal(t, c.NegotiateFormat(MIMEJSON, MIMEXML), MIMEJSON)
  604. assert.Equal(t, c.NegotiateFormat(MIMEHTML, MIMEJSON), MIMEHTML)
  605. }
  606. func TestContextNegotiationFormatWithAccept(t *testing.T) {
  607. c, _ := CreateTestContext(httptest.NewRecorder())
  608. c.Request, _ = http.NewRequest("POST", "/", nil)
  609. c.Request.Header.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
  610. assert.Equal(t, c.NegotiateFormat(MIMEJSON, MIMEXML), MIMEXML)
  611. assert.Equal(t, c.NegotiateFormat(MIMEXML, MIMEHTML), MIMEHTML)
  612. assert.Equal(t, c.NegotiateFormat(MIMEJSON), "")
  613. }
  614. func TestContextNegotiationFormatCustum(t *testing.T) {
  615. c, _ := CreateTestContext(httptest.NewRecorder())
  616. c.Request, _ = http.NewRequest("POST", "/", nil)
  617. c.Request.Header.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
  618. c.Accepted = nil
  619. c.SetAccepted(MIMEJSON, MIMEXML)
  620. assert.Equal(t, c.NegotiateFormat(MIMEJSON, MIMEXML), MIMEJSON)
  621. assert.Equal(t, c.NegotiateFormat(MIMEXML, MIMEHTML), MIMEXML)
  622. assert.Equal(t, c.NegotiateFormat(MIMEJSON), MIMEJSON)
  623. }
  624. func TestContextIsAborted(t *testing.T) {
  625. c, _ := CreateTestContext(httptest.NewRecorder())
  626. assert.False(t, c.IsAborted())
  627. c.Abort()
  628. assert.True(t, c.IsAborted())
  629. c.Next()
  630. assert.True(t, c.IsAborted())
  631. c.index++
  632. assert.True(t, c.IsAborted())
  633. }
  634. // TestContextData tests that the response can be written from `bytesting`
  635. // with specified MIME type
  636. func TestContextAbortWithStatus(t *testing.T) {
  637. w := httptest.NewRecorder()
  638. c, _ := CreateTestContext(w)
  639. c.index = 4
  640. c.AbortWithStatus(401)
  641. assert.Equal(t, c.index, abortIndex)
  642. assert.Equal(t, c.Writer.Status(), 401)
  643. assert.Equal(t, w.Code, 401)
  644. assert.True(t, c.IsAborted())
  645. }
  646. type testJSONAbortMsg struct {
  647. Foo string `json:"foo"`
  648. Bar string `json:"bar"`
  649. }
  650. func TestContextAbortWithStatusJSON(t *testing.T) {
  651. w := httptest.NewRecorder()
  652. c, _ := CreateTestContext(w)
  653. c.index = 4
  654. in := new(testJSONAbortMsg)
  655. in.Bar = "barValue"
  656. in.Foo = "fooValue"
  657. c.AbortWithStatusJSON(415, in)
  658. assert.Equal(t, c.index, abortIndex)
  659. assert.Equal(t, c.Writer.Status(), 415)
  660. assert.Equal(t, w.Code, 415)
  661. assert.True(t, c.IsAborted())
  662. contentType := w.Header().Get("Content-Type")
  663. assert.Equal(t, contentType, "application/json; charset=utf-8")
  664. buf := new(bytes.Buffer)
  665. buf.ReadFrom(w.Body)
  666. jsonStringBody := buf.String()
  667. assert.Equal(t, fmt.Sprint(`{"foo":"fooValue","bar":"barValue"}`), jsonStringBody)
  668. }
  669. func TestContextError(t *testing.T) {
  670. c, _ := CreateTestContext(httptest.NewRecorder())
  671. assert.Empty(t, c.Errors)
  672. c.Error(errors.New("first error"))
  673. assert.Len(t, c.Errors, 1)
  674. assert.Equal(t, c.Errors.String(), "Error #01: first error\n")
  675. c.Error(&Error{
  676. Err: errors.New("second error"),
  677. Meta: "some data 2",
  678. Type: ErrorTypePublic,
  679. })
  680. assert.Len(t, c.Errors, 2)
  681. assert.Equal(t, c.Errors[0].Err, errors.New("first error"))
  682. assert.Nil(t, c.Errors[0].Meta)
  683. assert.Equal(t, c.Errors[0].Type, ErrorTypePrivate)
  684. assert.Equal(t, c.Errors[1].Err, errors.New("second error"))
  685. assert.Equal(t, c.Errors[1].Meta, "some data 2")
  686. assert.Equal(t, c.Errors[1].Type, ErrorTypePublic)
  687. assert.Equal(t, c.Errors.Last(), c.Errors[1])
  688. }
  689. func TestContextTypedError(t *testing.T) {
  690. c, _ := CreateTestContext(httptest.NewRecorder())
  691. c.Error(errors.New("externo 0")).SetType(ErrorTypePublic)
  692. c.Error(errors.New("interno 0")).SetType(ErrorTypePrivate)
  693. for _, err := range c.Errors.ByType(ErrorTypePublic) {
  694. assert.Equal(t, err.Type, ErrorTypePublic)
  695. }
  696. for _, err := range c.Errors.ByType(ErrorTypePrivate) {
  697. assert.Equal(t, err.Type, ErrorTypePrivate)
  698. }
  699. assert.Equal(t, c.Errors.Errors(), []string{"externo 0", "interno 0"})
  700. }
  701. func TestContextAbortWithError(t *testing.T) {
  702. w := httptest.NewRecorder()
  703. c, _ := CreateTestContext(w)
  704. c.AbortWithError(401, errors.New("bad input")).SetMeta("some input")
  705. assert.Equal(t, w.Code, 401)
  706. assert.Equal(t, c.index, abortIndex)
  707. assert.True(t, c.IsAborted())
  708. }
  709. func TestContextClientIP(t *testing.T) {
  710. c, _ := CreateTestContext(httptest.NewRecorder())
  711. c.Request, _ = http.NewRequest("POST", "/", nil)
  712. c.Request.Header.Set("X-Real-IP", " 10.10.10.10 ")
  713. c.Request.Header.Set("X-Forwarded-For", " 20.20.20.20, 30.30.30.30")
  714. c.Request.Header.Set("X-Appengine-Remote-Addr", "50.50.50.50")
  715. c.Request.RemoteAddr = " 40.40.40.40:42123 "
  716. assert.Equal(t, "20.20.20.20", c.ClientIP())
  717. c.Request.Header.Del("X-Forwarded-For")
  718. assert.Equal(t, "10.10.10.10", c.ClientIP())
  719. c.Request.Header.Set("X-Forwarded-For", "30.30.30.30 ")
  720. assert.Equal(t, "30.30.30.30", c.ClientIP())
  721. c.Request.Header.Del("X-Forwarded-For")
  722. c.Request.Header.Del("X-Real-IP")
  723. c.engine.AppEngine = true
  724. assert.Equal(t, "50.50.50.50", c.ClientIP())
  725. c.Request.Header.Del("X-Appengine-Remote-Addr")
  726. assert.Equal(t, "40.40.40.40", c.ClientIP())
  727. // no port
  728. c.Request.RemoteAddr = "50.50.50.50"
  729. assert.Equal(t, "", c.ClientIP())
  730. }
  731. func TestContextContentType(t *testing.T) {
  732. c, _ := CreateTestContext(httptest.NewRecorder())
  733. c.Request, _ = http.NewRequest("POST", "/", nil)
  734. c.Request.Header.Set("Content-Type", "application/json; charset=utf-8")
  735. assert.Equal(t, c.ContentType(), "application/json")
  736. }
  737. func TestContextAutoBindJSON(t *testing.T) {
  738. c, _ := CreateTestContext(httptest.NewRecorder())
  739. c.Request, _ = http.NewRequest("POST", "/", bytes.NewBufferString("{\"foo\":\"bar\", \"bar\":\"foo\"}"))
  740. c.Request.Header.Add("Content-Type", MIMEJSON)
  741. var obj struct {
  742. Foo string `json:"foo"`
  743. Bar string `json:"bar"`
  744. }
  745. assert.NoError(t, c.Bind(&obj))
  746. assert.Equal(t, obj.Bar, "foo")
  747. assert.Equal(t, obj.Foo, "bar")
  748. assert.Empty(t, c.Errors)
  749. }
  750. func TestContextBindWithJSON(t *testing.T) {
  751. w := httptest.NewRecorder()
  752. c, _ := CreateTestContext(w)
  753. c.Request, _ = http.NewRequest("POST", "/", bytes.NewBufferString("{\"foo\":\"bar\", \"bar\":\"foo\"}"))
  754. c.Request.Header.Add("Content-Type", MIMEXML) // set fake content-type
  755. var obj struct {
  756. Foo string `json:"foo"`
  757. Bar string `json:"bar"`
  758. }
  759. assert.NoError(t, c.BindJSON(&obj))
  760. assert.Equal(t, obj.Bar, "foo")
  761. assert.Equal(t, obj.Foo, "bar")
  762. assert.Equal(t, w.Body.Len(), 0)
  763. }
  764. func TestContextBadAutoBind(t *testing.T) {
  765. w := httptest.NewRecorder()
  766. c, _ := CreateTestContext(w)
  767. c.Request, _ = http.NewRequest("POST", "http://example.com", bytes.NewBufferString("\"foo\":\"bar\", \"bar\":\"foo\"}"))
  768. c.Request.Header.Add("Content-Type", MIMEJSON)
  769. var obj struct {
  770. Foo string `json:"foo"`
  771. Bar string `json:"bar"`
  772. }
  773. assert.False(t, c.IsAborted())
  774. assert.Error(t, c.Bind(&obj))
  775. c.Writer.WriteHeaderNow()
  776. assert.Empty(t, obj.Bar)
  777. assert.Empty(t, obj.Foo)
  778. assert.Equal(t, w.Code, 400)
  779. assert.True(t, c.IsAborted())
  780. }
  781. func TestContextGolangContext(t *testing.T) {
  782. c, _ := CreateTestContext(httptest.NewRecorder())
  783. c.Request, _ = http.NewRequest("POST", "/", bytes.NewBufferString("{\"foo\":\"bar\", \"bar\":\"foo\"}"))
  784. assert.NoError(t, c.Err())
  785. assert.Nil(t, c.Done())
  786. ti, ok := c.Deadline()
  787. assert.Equal(t, ti, time.Time{})
  788. assert.False(t, ok)
  789. assert.Equal(t, c.Value(0), c.Request)
  790. assert.Nil(t, c.Value("foo"))
  791. c.Set("foo", "bar")
  792. assert.Equal(t, c.Value("foo"), "bar")
  793. assert.Nil(t, c.Value(1))
  794. }
  795. func TestWebsocketsRequired(t *testing.T) {
  796. // Example request from spec: https://tools.ietf.org/html/rfc6455#section-1.2
  797. c, _ := CreateTestContext(httptest.NewRecorder())
  798. c.Request, _ = http.NewRequest("GET", "/chat", nil)
  799. c.Request.Header.Set("Host", "server.example.com")
  800. c.Request.Header.Set("Upgrade", "websocket")
  801. c.Request.Header.Set("Connection", "Upgrade")
  802. c.Request.Header.Set("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==")
  803. c.Request.Header.Set("Origin", "http://example.com")
  804. c.Request.Header.Set("Sec-WebSocket-Protocol", "chat, superchat")
  805. c.Request.Header.Set("Sec-WebSocket-Version", "13")
  806. assert.True(t, c.IsWebsocket())
  807. // Normal request, no websocket required.
  808. c, _ = CreateTestContext(httptest.NewRecorder())
  809. c.Request, _ = http.NewRequest("GET", "/chat", nil)
  810. c.Request.Header.Set("Host", "server.example.com")
  811. assert.False(t, c.IsWebsocket())
  812. }
  813. func TestGetRequestHeaderValue(t *testing.T) {
  814. c, _ := CreateTestContext(httptest.NewRecorder())
  815. c.Request, _ = http.NewRequest("GET", "/chat", nil)
  816. c.Request.Header.Set("Gin-Version", "1.0.0")
  817. assert.Equal(t, "1.0.0", c.GetHeader("Gin-Version"))
  818. assert.Equal(t, "", c.GetHeader("Connection"))
  819. }
  820. func TestContextGetRawData(t *testing.T) {
  821. c, _ := CreateTestContext(httptest.NewRecorder())
  822. body := bytes.NewBufferString("Fetch binary post data")
  823. c.Request, _ = http.NewRequest("POST", "/", body)
  824. c.Request.Header.Add("Content-Type", MIMEPOSTForm)
  825. data, err := c.GetRawData()
  826. assert.Nil(t, err)
  827. assert.Equal(t, "Fetch binary post data", string(data))
  828. }