context_test.go 30 KB

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