context_test.go 35 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179
  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 TestContextGetString(t *testing.T) {
  146. c, _ := CreateTestContext(httptest.NewRecorder())
  147. c.Set("string", "this is a string")
  148. assert.Equal(t, "this is a string", c.GetString("string"))
  149. }
  150. func TestContextSetGetBool(t *testing.T) {
  151. c, _ := CreateTestContext(httptest.NewRecorder())
  152. c.Set("bool", true)
  153. assert.Equal(t, true, c.GetBool("bool"))
  154. }
  155. func TestContextGetInt(t *testing.T) {
  156. c, _ := CreateTestContext(httptest.NewRecorder())
  157. c.Set("int", 1)
  158. assert.Equal(t, 1, c.GetInt("int"))
  159. }
  160. func TestContextGetInt64(t *testing.T) {
  161. c, _ := CreateTestContext(httptest.NewRecorder())
  162. c.Set("int64", int64(42424242424242))
  163. assert.Equal(t, int64(42424242424242), c.GetInt64("int64"))
  164. }
  165. func TestContextGetFloat64(t *testing.T) {
  166. c, _ := CreateTestContext(httptest.NewRecorder())
  167. c.Set("float64", 4.2)
  168. assert.Equal(t, 4.2, c.GetFloat64("float64"))
  169. }
  170. func TestContextGetTime(t *testing.T) {
  171. c, _ := CreateTestContext(httptest.NewRecorder())
  172. t1, _ := time.Parse("1/2/2006 15:04:05", "01/01/2017 12:00:00")
  173. c.Set("time", t1)
  174. assert.Equal(t, t1, c.GetTime("time"))
  175. }
  176. func TestContextGetDuration(t *testing.T) {
  177. c, _ := CreateTestContext(httptest.NewRecorder())
  178. c.Set("duration", time.Second)
  179. assert.Equal(t, time.Second, c.GetDuration("duration"))
  180. }
  181. func TestContextGetStringSlice(t *testing.T) {
  182. c, _ := CreateTestContext(httptest.NewRecorder())
  183. c.Set("slice", []string{"foo"})
  184. assert.Equal(t, []string{"foo"}, c.GetStringSlice("slice"))
  185. }
  186. func TestContextGetStringMap(t *testing.T) {
  187. c, _ := CreateTestContext(httptest.NewRecorder())
  188. var m = make(map[string]interface{})
  189. m["foo"] = 1
  190. c.Set("map", m)
  191. assert.Equal(t, m, c.GetStringMap("map"))
  192. assert.Equal(t, 1, c.GetStringMap("map")["foo"])
  193. }
  194. func TestContextGetStringMapString(t *testing.T) {
  195. c, _ := CreateTestContext(httptest.NewRecorder())
  196. var m = make(map[string]string)
  197. m["foo"] = "bar"
  198. c.Set("map", m)
  199. assert.Equal(t, m, c.GetStringMapString("map"))
  200. assert.Equal(t, "bar", c.GetStringMapString("map")["foo"])
  201. }
  202. func TestContextGetStringMapStringSlice(t *testing.T) {
  203. c, _ := CreateTestContext(httptest.NewRecorder())
  204. var m = make(map[string][]string)
  205. m["foo"] = []string{"foo"}
  206. c.Set("map", m)
  207. assert.Equal(t, m, c.GetStringMapStringSlice("map"))
  208. assert.Equal(t, []string{"foo"}, c.GetStringMapStringSlice("map")["foo"])
  209. }
  210. func TestContextCopy(t *testing.T) {
  211. c, _ := CreateTestContext(httptest.NewRecorder())
  212. c.index = 2
  213. c.Request, _ = http.NewRequest("POST", "/hola", nil)
  214. c.handlers = HandlersChain{func(c *Context) {}}
  215. c.Params = Params{Param{Key: "foo", Value: "bar"}}
  216. c.Set("foo", "bar")
  217. cp := c.Copy()
  218. assert.Nil(t, cp.handlers)
  219. assert.Nil(t, cp.writermem.ResponseWriter)
  220. assert.Equal(t, &cp.writermem, cp.Writer.(*responseWriter))
  221. assert.Equal(t, cp.Request, c.Request)
  222. assert.Equal(t, cp.index, abortIndex)
  223. assert.Equal(t, cp.Keys, c.Keys)
  224. assert.Equal(t, cp.engine, c.engine)
  225. assert.Equal(t, cp.Params, c.Params)
  226. }
  227. func TestContextHandlerName(t *testing.T) {
  228. c, _ := CreateTestContext(httptest.NewRecorder())
  229. c.handlers = HandlersChain{func(c *Context) {}, handlerNameTest}
  230. assert.Regexp(t, "^(.*/vendor/)?github.com/gin-gonic/gin.handlerNameTest$", c.HandlerName())
  231. }
  232. func handlerNameTest(c *Context) {
  233. }
  234. func TestContextQuery(t *testing.T) {
  235. c, _ := CreateTestContext(httptest.NewRecorder())
  236. c.Request, _ = http.NewRequest("GET", "http://example.com/?foo=bar&page=10&id=", nil)
  237. value, ok := c.GetQuery("foo")
  238. assert.True(t, ok)
  239. assert.Equal(t, value, "bar")
  240. assert.Equal(t, c.DefaultQuery("foo", "none"), "bar")
  241. assert.Equal(t, c.Query("foo"), "bar")
  242. value, ok = c.GetQuery("page")
  243. assert.True(t, ok)
  244. assert.Equal(t, value, "10")
  245. assert.Equal(t, c.DefaultQuery("page", "0"), "10")
  246. assert.Equal(t, c.Query("page"), "10")
  247. value, ok = c.GetQuery("id")
  248. assert.True(t, ok)
  249. assert.Empty(t, value)
  250. assert.Equal(t, c.DefaultQuery("id", "nada"), "")
  251. assert.Empty(t, c.Query("id"))
  252. value, ok = c.GetQuery("NoKey")
  253. assert.False(t, ok)
  254. assert.Empty(t, value)
  255. assert.Equal(t, c.DefaultQuery("NoKey", "nada"), "nada")
  256. assert.Empty(t, c.Query("NoKey"))
  257. // postform should not mess
  258. value, ok = c.GetPostForm("page")
  259. assert.False(t, ok)
  260. assert.Empty(t, value)
  261. assert.Empty(t, c.PostForm("foo"))
  262. }
  263. func TestContextQueryAndPostForm(t *testing.T) {
  264. c, _ := CreateTestContext(httptest.NewRecorder())
  265. body := bytes.NewBufferString("foo=bar&page=11&both=&foo=second")
  266. c.Request, _ = http.NewRequest("POST", "/?both=GET&id=main&id=omit&array[]=first&array[]=second", body)
  267. c.Request.Header.Add("Content-Type", MIMEPOSTForm)
  268. assert.Equal(t, c.DefaultPostForm("foo", "none"), "bar")
  269. assert.Equal(t, c.PostForm("foo"), "bar")
  270. assert.Empty(t, c.Query("foo"))
  271. value, ok := c.GetPostForm("page")
  272. assert.True(t, ok)
  273. assert.Equal(t, value, "11")
  274. assert.Equal(t, c.DefaultPostForm("page", "0"), "11")
  275. assert.Equal(t, c.PostForm("page"), "11")
  276. assert.Equal(t, c.Query("page"), "")
  277. value, ok = c.GetPostForm("both")
  278. assert.True(t, ok)
  279. assert.Empty(t, value)
  280. assert.Empty(t, c.PostForm("both"))
  281. assert.Equal(t, c.DefaultPostForm("both", "nothing"), "")
  282. assert.Equal(t, c.Query("both"), "GET")
  283. value, ok = c.GetQuery("id")
  284. assert.True(t, ok)
  285. assert.Equal(t, value, "main")
  286. assert.Equal(t, c.DefaultPostForm("id", "000"), "000")
  287. assert.Equal(t, c.Query("id"), "main")
  288. assert.Empty(t, c.PostForm("id"))
  289. value, ok = c.GetQuery("NoKey")
  290. assert.False(t, ok)
  291. assert.Empty(t, value)
  292. value, ok = c.GetPostForm("NoKey")
  293. assert.False(t, ok)
  294. assert.Empty(t, value)
  295. assert.Equal(t, c.DefaultPostForm("NoKey", "nada"), "nada")
  296. assert.Equal(t, c.DefaultQuery("NoKey", "nothing"), "nothing")
  297. assert.Empty(t, c.PostForm("NoKey"))
  298. assert.Empty(t, c.Query("NoKey"))
  299. var obj struct {
  300. Foo string `form:"foo"`
  301. ID string `form:"id"`
  302. Page int `form:"page"`
  303. Both string `form:"both"`
  304. Array []string `form:"array[]"`
  305. }
  306. assert.NoError(t, c.Bind(&obj))
  307. assert.Equal(t, obj.Foo, "bar")
  308. assert.Equal(t, obj.ID, "main")
  309. assert.Equal(t, obj.Page, 11)
  310. assert.Equal(t, obj.Both, "")
  311. assert.Equal(t, obj.Array, []string{"first", "second"})
  312. values, ok := c.GetQueryArray("array[]")
  313. assert.True(t, ok)
  314. assert.Equal(t, "first", values[0])
  315. assert.Equal(t, "second", values[1])
  316. values = c.QueryArray("array[]")
  317. assert.Equal(t, "first", values[0])
  318. assert.Equal(t, "second", values[1])
  319. values = c.QueryArray("nokey")
  320. assert.Equal(t, 0, len(values))
  321. values = c.QueryArray("both")
  322. assert.Equal(t, 1, len(values))
  323. assert.Equal(t, "GET", values[0])
  324. }
  325. func TestContextPostFormMultipart(t *testing.T) {
  326. c, _ := CreateTestContext(httptest.NewRecorder())
  327. c.Request = createMultipartRequest()
  328. var obj struct {
  329. Foo string `form:"foo"`
  330. Bar string `form:"bar"`
  331. BarAsInt int `form:"bar"`
  332. Array []string `form:"array"`
  333. ID string `form:"id"`
  334. TimeLocal time.Time `form:"time_local" time_format:"02/01/2006 15:04"`
  335. TimeUTC time.Time `form:"time_utc" time_format:"02/01/2006 15:04" time_utc:"1"`
  336. BlankTime time.Time `form:"blank_time" time_format:"02/01/2006 15:04"`
  337. }
  338. assert.NoError(t, c.Bind(&obj))
  339. assert.Equal(t, obj.Foo, "bar")
  340. assert.Equal(t, obj.Bar, "10")
  341. assert.Equal(t, obj.BarAsInt, 10)
  342. assert.Equal(t, obj.Array, []string{"first", "second"})
  343. assert.Equal(t, obj.ID, "")
  344. assert.Equal(t, obj.TimeLocal.Format("02/01/2006 15:04"), "31/12/2016 14:55")
  345. assert.Equal(t, obj.TimeLocal.Location(), time.Local)
  346. assert.Equal(t, obj.TimeUTC.Format("02/01/2006 15:04"), "31/12/2016 14:55")
  347. assert.Equal(t, obj.TimeUTC.Location(), time.UTC)
  348. assert.True(t, obj.BlankTime.IsZero())
  349. value, ok := c.GetQuery("foo")
  350. assert.False(t, ok)
  351. assert.Empty(t, value)
  352. assert.Empty(t, c.Query("bar"))
  353. assert.Equal(t, c.DefaultQuery("id", "nothing"), "nothing")
  354. value, ok = c.GetPostForm("foo")
  355. assert.True(t, ok)
  356. assert.Equal(t, value, "bar")
  357. assert.Equal(t, c.PostForm("foo"), "bar")
  358. value, ok = c.GetPostForm("array")
  359. assert.True(t, ok)
  360. assert.Equal(t, value, "first")
  361. assert.Equal(t, c.PostForm("array"), "first")
  362. assert.Equal(t, c.DefaultPostForm("bar", "nothing"), "10")
  363. value, ok = c.GetPostForm("id")
  364. assert.True(t, ok)
  365. assert.Empty(t, value)
  366. assert.Empty(t, c.PostForm("id"))
  367. assert.Empty(t, c.DefaultPostForm("id", "nothing"))
  368. value, ok = c.GetPostForm("nokey")
  369. assert.False(t, ok)
  370. assert.Empty(t, value)
  371. assert.Equal(t, c.DefaultPostForm("nokey", "nothing"), "nothing")
  372. values, ok := c.GetPostFormArray("array")
  373. assert.True(t, ok)
  374. assert.Equal(t, "first", values[0])
  375. assert.Equal(t, "second", values[1])
  376. values = c.PostFormArray("array")
  377. assert.Equal(t, "first", values[0])
  378. assert.Equal(t, "second", values[1])
  379. values = c.PostFormArray("nokey")
  380. assert.Equal(t, 0, len(values))
  381. values = c.PostFormArray("foo")
  382. assert.Equal(t, 1, len(values))
  383. assert.Equal(t, "bar", values[0])
  384. }
  385. func TestContextSetCookie(t *testing.T) {
  386. c, _ := CreateTestContext(httptest.NewRecorder())
  387. c.SetCookie("user", "gin", 1, "/", "localhost", true, true)
  388. assert.Equal(t, c.Writer.Header().Get("Set-Cookie"), "user=gin; Path=/; Domain=localhost; Max-Age=1; HttpOnly; Secure")
  389. }
  390. func TestContextSetCookiePathEmpty(t *testing.T) {
  391. c, _ := CreateTestContext(httptest.NewRecorder())
  392. c.SetCookie("user", "gin", 1, "", "localhost", true, true)
  393. assert.Equal(t, c.Writer.Header().Get("Set-Cookie"), "user=gin; Path=/; Domain=localhost; Max-Age=1; HttpOnly; Secure")
  394. }
  395. func TestContextGetCookie(t *testing.T) {
  396. c, _ := CreateTestContext(httptest.NewRecorder())
  397. c.Request, _ = http.NewRequest("GET", "/get", nil)
  398. c.Request.Header.Set("Cookie", "user=gin")
  399. cookie, _ := c.Cookie("user")
  400. assert.Equal(t, cookie, "gin")
  401. _, err := c.Cookie("nokey")
  402. assert.Error(t, err)
  403. }
  404. func TestContextBodyAllowedForStatus(t *testing.T) {
  405. assert.Equal(t, false, bodyAllowedForStatus(102))
  406. assert.Equal(t, false, bodyAllowedForStatus(204))
  407. assert.Equal(t, false, bodyAllowedForStatus(304))
  408. assert.Equal(t, true, bodyAllowedForStatus(500))
  409. }
  410. type TestPanicRender struct {
  411. }
  412. func (*TestPanicRender) Render(http.ResponseWriter) error {
  413. return errors.New("TestPanicRender")
  414. }
  415. func (*TestPanicRender) WriteContentType(http.ResponseWriter) {}
  416. func TestContextRenderPanicIfErr(t *testing.T) {
  417. defer func() {
  418. r := recover()
  419. assert.Equal(t, "TestPanicRender", fmt.Sprint(r))
  420. }()
  421. w := httptest.NewRecorder()
  422. c, _ := CreateTestContext(w)
  423. c.Render(http.StatusOK, &TestPanicRender{})
  424. assert.Fail(t, "Panic not detected")
  425. }
  426. // Tests that the response is serialized as JSON
  427. // and Content-Type is set to application/json
  428. func TestContextRenderJSON(t *testing.T) {
  429. w := httptest.NewRecorder()
  430. c, _ := CreateTestContext(w)
  431. c.JSON(201, H{"foo": "bar"})
  432. assert.Equal(t, 201, w.Code)
  433. assert.Equal(t, "{\"foo\":\"bar\"}", w.Body.String())
  434. assert.Equal(t, "application/json; charset=utf-8", w.HeaderMap.Get("Content-Type"))
  435. }
  436. // Tests that no JSON is rendered if code is 204
  437. func TestContextRenderNoContentJSON(t *testing.T) {
  438. w := httptest.NewRecorder()
  439. c, _ := CreateTestContext(w)
  440. c.JSON(204, H{"foo": "bar"})
  441. assert.Equal(t, 204, w.Code)
  442. assert.Equal(t, "", w.Body.String())
  443. assert.Equal(t, "application/json; charset=utf-8", w.HeaderMap.Get("Content-Type"))
  444. }
  445. // Tests that the response is serialized as JSON
  446. // we change the content-type before
  447. func TestContextRenderAPIJSON(t *testing.T) {
  448. w := httptest.NewRecorder()
  449. c, _ := CreateTestContext(w)
  450. c.Header("Content-Type", "application/vnd.api+json")
  451. c.JSON(201, H{"foo": "bar"})
  452. assert.Equal(t, 201, w.Code)
  453. assert.Equal(t, "{\"foo\":\"bar\"}", w.Body.String())
  454. assert.Equal(t, "application/vnd.api+json", w.HeaderMap.Get("Content-Type"))
  455. }
  456. // Tests that no Custom JSON is rendered if code is 204
  457. func TestContextRenderNoContentAPIJSON(t *testing.T) {
  458. w := httptest.NewRecorder()
  459. c, _ := CreateTestContext(w)
  460. c.Header("Content-Type", "application/vnd.api+json")
  461. c.JSON(204, H{"foo": "bar"})
  462. assert.Equal(t, 204, w.Code)
  463. assert.Equal(t, "", w.Body.String())
  464. assert.Equal(t, w.HeaderMap.Get("Content-Type"), "application/vnd.api+json")
  465. }
  466. // Tests that the response is serialized as JSON
  467. // and Content-Type is set to application/json
  468. func TestContextRenderIndentedJSON(t *testing.T) {
  469. w := httptest.NewRecorder()
  470. c, _ := CreateTestContext(w)
  471. c.IndentedJSON(201, H{"foo": "bar", "bar": "foo", "nested": H{"foo": "bar"}})
  472. assert.Equal(t, w.Code, 201)
  473. assert.Equal(t, w.Body.String(), "{\n \"bar\": \"foo\",\n \"foo\": \"bar\",\n \"nested\": {\n \"foo\": \"bar\"\n }\n}")
  474. assert.Equal(t, w.HeaderMap.Get("Content-Type"), "application/json; charset=utf-8")
  475. }
  476. // Tests that no Custom JSON is rendered if code is 204
  477. func TestContextRenderNoContentIndentedJSON(t *testing.T) {
  478. w := httptest.NewRecorder()
  479. c, _ := CreateTestContext(w)
  480. c.IndentedJSON(204, H{"foo": "bar", "bar": "foo", "nested": H{"foo": "bar"}})
  481. assert.Equal(t, 204, w.Code)
  482. assert.Equal(t, "", w.Body.String())
  483. assert.Equal(t, w.HeaderMap.Get("Content-Type"), "application/json; charset=utf-8")
  484. }
  485. // Tests that the response executes the templates
  486. // and responds with Content-Type set to text/html
  487. func TestContextRenderHTML(t *testing.T) {
  488. w := httptest.NewRecorder()
  489. c, router := CreateTestContext(w)
  490. templ := template.Must(template.New("t").Parse(`Hello {{.name}}`))
  491. router.SetHTMLTemplate(templ)
  492. c.HTML(201, "t", H{"name": "alexandernyquist"})
  493. assert.Equal(t, w.Code, 201)
  494. assert.Equal(t, w.Body.String(), "Hello alexandernyquist")
  495. assert.Equal(t, w.HeaderMap.Get("Content-Type"), "text/html; charset=utf-8")
  496. }
  497. // Tests that no HTML is rendered if code is 204
  498. func TestContextRenderNoContentHTML(t *testing.T) {
  499. w := httptest.NewRecorder()
  500. c, router := CreateTestContext(w)
  501. templ := template.Must(template.New("t").Parse(`Hello {{.name}}`))
  502. router.SetHTMLTemplate(templ)
  503. c.HTML(204, "t", H{"name": "alexandernyquist"})
  504. assert.Equal(t, 204, w.Code)
  505. assert.Equal(t, "", w.Body.String())
  506. assert.Equal(t, w.HeaderMap.Get("Content-Type"), "text/html; charset=utf-8")
  507. }
  508. // TestContextXML tests that the response is serialized as XML
  509. // and Content-Type is set to application/xml
  510. func TestContextRenderXML(t *testing.T) {
  511. w := httptest.NewRecorder()
  512. c, _ := CreateTestContext(w)
  513. c.XML(201, H{"foo": "bar"})
  514. assert.Equal(t, w.Code, 201)
  515. assert.Equal(t, w.Body.String(), "<map><foo>bar</foo></map>")
  516. assert.Equal(t, w.HeaderMap.Get("Content-Type"), "application/xml; charset=utf-8")
  517. }
  518. // Tests that no XML is rendered if code is 204
  519. func TestContextRenderNoContentXML(t *testing.T) {
  520. w := httptest.NewRecorder()
  521. c, _ := CreateTestContext(w)
  522. c.XML(204, H{"foo": "bar"})
  523. assert.Equal(t, 204, w.Code)
  524. assert.Equal(t, "", w.Body.String())
  525. assert.Equal(t, w.HeaderMap.Get("Content-Type"), "application/xml; charset=utf-8")
  526. }
  527. // TestContextString tests that the response is returned
  528. // with Content-Type set to text/plain
  529. func TestContextRenderString(t *testing.T) {
  530. w := httptest.NewRecorder()
  531. c, _ := CreateTestContext(w)
  532. c.String(201, "test %s %d", "string", 2)
  533. assert.Equal(t, w.Code, 201)
  534. assert.Equal(t, w.Body.String(), "test string 2")
  535. assert.Equal(t, w.HeaderMap.Get("Content-Type"), "text/plain; charset=utf-8")
  536. }
  537. // Tests that no String is rendered if code is 204
  538. func TestContextRenderNoContentString(t *testing.T) {
  539. w := httptest.NewRecorder()
  540. c, _ := CreateTestContext(w)
  541. c.String(204, "test %s %d", "string", 2)
  542. assert.Equal(t, 204, w.Code)
  543. assert.Equal(t, "", w.Body.String())
  544. assert.Equal(t, w.HeaderMap.Get("Content-Type"), "text/plain; charset=utf-8")
  545. }
  546. // TestContextString tests that the response is returned
  547. // with Content-Type set to text/html
  548. func TestContextRenderHTMLString(t *testing.T) {
  549. w := httptest.NewRecorder()
  550. c, _ := CreateTestContext(w)
  551. c.Header("Content-Type", "text/html; charset=utf-8")
  552. c.String(201, "<html>%s %d</html>", "string", 3)
  553. assert.Equal(t, w.Code, 201)
  554. assert.Equal(t, w.Body.String(), "<html>string 3</html>")
  555. assert.Equal(t, w.HeaderMap.Get("Content-Type"), "text/html; charset=utf-8")
  556. }
  557. // Tests that no HTML String is rendered if code is 204
  558. func TestContextRenderNoContentHTMLString(t *testing.T) {
  559. w := httptest.NewRecorder()
  560. c, _ := CreateTestContext(w)
  561. c.Header("Content-Type", "text/html; charset=utf-8")
  562. c.String(204, "<html>%s %d</html>", "string", 3)
  563. assert.Equal(t, 204, w.Code)
  564. assert.Equal(t, "", w.Body.String())
  565. assert.Equal(t, w.HeaderMap.Get("Content-Type"), "text/html; charset=utf-8")
  566. }
  567. // TestContextData tests that the response can be written from `bytesting`
  568. // with specified MIME type
  569. func TestContextRenderData(t *testing.T) {
  570. w := httptest.NewRecorder()
  571. c, _ := CreateTestContext(w)
  572. c.Data(201, "text/csv", []byte(`foo,bar`))
  573. assert.Equal(t, w.Code, 201)
  574. assert.Equal(t, w.Body.String(), "foo,bar")
  575. assert.Equal(t, w.HeaderMap.Get("Content-Type"), "text/csv")
  576. }
  577. // Tests that no Custom Data is rendered if code is 204
  578. func TestContextRenderNoContentData(t *testing.T) {
  579. w := httptest.NewRecorder()
  580. c, _ := CreateTestContext(w)
  581. c.Data(204, "text/csv", []byte(`foo,bar`))
  582. assert.Equal(t, 204, w.Code)
  583. assert.Equal(t, "", w.Body.String())
  584. assert.Equal(t, w.HeaderMap.Get("Content-Type"), "text/csv")
  585. }
  586. func TestContextRenderSSE(t *testing.T) {
  587. w := httptest.NewRecorder()
  588. c, _ := CreateTestContext(w)
  589. c.SSEvent("float", 1.5)
  590. c.Render(-1, sse.Event{
  591. Id: "123",
  592. Data: "text",
  593. })
  594. c.SSEvent("chat", H{
  595. "foo": "bar",
  596. "bar": "foo",
  597. })
  598. 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))
  599. }
  600. func TestContextRenderFile(t *testing.T) {
  601. w := httptest.NewRecorder()
  602. c, _ := CreateTestContext(w)
  603. c.Request, _ = http.NewRequest("GET", "/", nil)
  604. c.File("./gin.go")
  605. assert.Equal(t, w.Code, 200)
  606. assert.Contains(t, w.Body.String(), "func New() *Engine {")
  607. assert.Equal(t, w.HeaderMap.Get("Content-Type"), "text/plain; charset=utf-8")
  608. }
  609. // TestContextRenderYAML tests that the response is serialized as YAML
  610. // and Content-Type is set to application/x-yaml
  611. func TestContextRenderYAML(t *testing.T) {
  612. w := httptest.NewRecorder()
  613. c, _ := CreateTestContext(w)
  614. c.YAML(201, H{"foo": "bar"})
  615. assert.Equal(t, w.Code, 201)
  616. assert.Equal(t, w.Body.String(), "foo: bar\n")
  617. assert.Equal(t, w.HeaderMap.Get("Content-Type"), "application/x-yaml; charset=utf-8")
  618. }
  619. func TestContextHeaders(t *testing.T) {
  620. c, _ := CreateTestContext(httptest.NewRecorder())
  621. c.Header("Content-Type", "text/plain")
  622. c.Header("X-Custom", "value")
  623. assert.Equal(t, c.Writer.Header().Get("Content-Type"), "text/plain")
  624. assert.Equal(t, c.Writer.Header().Get("X-Custom"), "value")
  625. c.Header("Content-Type", "text/html")
  626. c.Header("X-Custom", "")
  627. assert.Equal(t, c.Writer.Header().Get("Content-Type"), "text/html")
  628. _, exist := c.Writer.Header()["X-Custom"]
  629. assert.False(t, exist)
  630. }
  631. // TODO
  632. func TestContextRenderRedirectWithRelativePath(t *testing.T) {
  633. w := httptest.NewRecorder()
  634. c, _ := CreateTestContext(w)
  635. c.Request, _ = http.NewRequest("POST", "http://example.com", nil)
  636. assert.Panics(t, func() { c.Redirect(299, "/new_path") })
  637. assert.Panics(t, func() { c.Redirect(309, "/new_path") })
  638. c.Redirect(301, "/path")
  639. c.Writer.WriteHeaderNow()
  640. assert.Equal(t, w.Code, 301)
  641. assert.Equal(t, w.Header().Get("Location"), "/path")
  642. }
  643. func TestContextRenderRedirectWithAbsolutePath(t *testing.T) {
  644. w := httptest.NewRecorder()
  645. c, _ := CreateTestContext(w)
  646. c.Request, _ = http.NewRequest("POST", "http://example.com", nil)
  647. c.Redirect(302, "http://google.com")
  648. c.Writer.WriteHeaderNow()
  649. assert.Equal(t, w.Code, 302)
  650. assert.Equal(t, w.Header().Get("Location"), "http://google.com")
  651. }
  652. func TestContextRenderRedirectWith201(t *testing.T) {
  653. w := httptest.NewRecorder()
  654. c, _ := CreateTestContext(w)
  655. c.Request, _ = http.NewRequest("POST", "http://example.com", nil)
  656. c.Redirect(201, "/resource")
  657. c.Writer.WriteHeaderNow()
  658. assert.Equal(t, w.Code, 201)
  659. assert.Equal(t, w.Header().Get("Location"), "/resource")
  660. }
  661. func TestContextRenderRedirectAll(t *testing.T) {
  662. c, _ := CreateTestContext(httptest.NewRecorder())
  663. c.Request, _ = http.NewRequest("POST", "http://example.com", nil)
  664. assert.Panics(t, func() { c.Redirect(200, "/resource") })
  665. assert.Panics(t, func() { c.Redirect(202, "/resource") })
  666. assert.Panics(t, func() { c.Redirect(299, "/resource") })
  667. assert.Panics(t, func() { c.Redirect(309, "/resource") })
  668. assert.NotPanics(t, func() { c.Redirect(300, "/resource") })
  669. assert.NotPanics(t, func() { c.Redirect(308, "/resource") })
  670. }
  671. func TestContextNegotiationWithJSON(t *testing.T) {
  672. w := httptest.NewRecorder()
  673. c, _ := CreateTestContext(w)
  674. c.Request, _ = http.NewRequest("POST", "", nil)
  675. c.Negotiate(200, Negotiate{
  676. Offered: []string{MIMEJSON, MIMEXML},
  677. Data: H{"foo": "bar"},
  678. })
  679. assert.Equal(t, 200, w.Code)
  680. assert.Equal(t, "{\"foo\":\"bar\"}", w.Body.String())
  681. assert.Equal(t, "application/json; charset=utf-8", w.HeaderMap.Get("Content-Type"))
  682. }
  683. func TestContextNegotiationWithXML(t *testing.T) {
  684. w := httptest.NewRecorder()
  685. c, _ := CreateTestContext(w)
  686. c.Request, _ = http.NewRequest("POST", "", nil)
  687. c.Negotiate(200, Negotiate{
  688. Offered: []string{MIMEXML, MIMEJSON},
  689. Data: H{"foo": "bar"},
  690. })
  691. assert.Equal(t, 200, w.Code)
  692. assert.Equal(t, "<map><foo>bar</foo></map>", w.Body.String())
  693. assert.Equal(t, "application/xml; charset=utf-8", w.HeaderMap.Get("Content-Type"))
  694. }
  695. func TestContextNegotiationWithHTML(t *testing.T) {
  696. w := httptest.NewRecorder()
  697. c, router := CreateTestContext(w)
  698. c.Request, _ = http.NewRequest("POST", "", nil)
  699. templ := template.Must(template.New("t").Parse(`Hello {{.name}}`))
  700. router.SetHTMLTemplate(templ)
  701. c.Negotiate(200, Negotiate{
  702. Offered: []string{MIMEHTML},
  703. Data: H{"name": "gin"},
  704. HTMLName: "t",
  705. })
  706. assert.Equal(t, 200, w.Code)
  707. assert.Equal(t, "Hello gin", w.Body.String())
  708. assert.Equal(t, "text/html; charset=utf-8", w.HeaderMap.Get("Content-Type"))
  709. }
  710. func TestContextNegotiationNotSupport(t *testing.T) {
  711. w := httptest.NewRecorder()
  712. c, _ := CreateTestContext(w)
  713. c.Request, _ = http.NewRequest("POST", "", nil)
  714. c.Negotiate(200, Negotiate{
  715. Offered: []string{MIMEPOSTForm},
  716. })
  717. assert.Equal(t, 406, w.Code)
  718. assert.Equal(t, c.index, abortIndex)
  719. assert.True(t, c.IsAborted())
  720. }
  721. func TestContextNegotiationFormat(t *testing.T) {
  722. c, _ := CreateTestContext(httptest.NewRecorder())
  723. c.Request, _ = http.NewRequest("POST", "", nil)
  724. assert.Panics(t, func() { c.NegotiateFormat() })
  725. assert.Equal(t, c.NegotiateFormat(MIMEJSON, MIMEXML), MIMEJSON)
  726. assert.Equal(t, c.NegotiateFormat(MIMEHTML, MIMEJSON), MIMEHTML)
  727. }
  728. func TestContextNegotiationFormatWithAccept(t *testing.T) {
  729. c, _ := CreateTestContext(httptest.NewRecorder())
  730. c.Request, _ = http.NewRequest("POST", "/", nil)
  731. c.Request.Header.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
  732. assert.Equal(t, c.NegotiateFormat(MIMEJSON, MIMEXML), MIMEXML)
  733. assert.Equal(t, c.NegotiateFormat(MIMEXML, MIMEHTML), MIMEHTML)
  734. assert.Equal(t, c.NegotiateFormat(MIMEJSON), "")
  735. }
  736. func TestContextNegotiationFormatCustum(t *testing.T) {
  737. c, _ := CreateTestContext(httptest.NewRecorder())
  738. c.Request, _ = http.NewRequest("POST", "/", nil)
  739. c.Request.Header.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
  740. c.Accepted = nil
  741. c.SetAccepted(MIMEJSON, MIMEXML)
  742. assert.Equal(t, c.NegotiateFormat(MIMEJSON, MIMEXML), MIMEJSON)
  743. assert.Equal(t, c.NegotiateFormat(MIMEXML, MIMEHTML), MIMEXML)
  744. assert.Equal(t, c.NegotiateFormat(MIMEJSON), MIMEJSON)
  745. }
  746. func TestContextIsAborted(t *testing.T) {
  747. c, _ := CreateTestContext(httptest.NewRecorder())
  748. assert.False(t, c.IsAborted())
  749. c.Abort()
  750. assert.True(t, c.IsAborted())
  751. c.Next()
  752. assert.True(t, c.IsAborted())
  753. c.index++
  754. assert.True(t, c.IsAborted())
  755. }
  756. // TestContextData tests that the response can be written from `bytesting`
  757. // with specified MIME type
  758. func TestContextAbortWithStatus(t *testing.T) {
  759. w := httptest.NewRecorder()
  760. c, _ := CreateTestContext(w)
  761. c.index = 4
  762. c.AbortWithStatus(401)
  763. assert.Equal(t, c.index, abortIndex)
  764. assert.Equal(t, c.Writer.Status(), 401)
  765. assert.Equal(t, w.Code, 401)
  766. assert.True(t, c.IsAborted())
  767. }
  768. type testJSONAbortMsg struct {
  769. Foo string `json:"foo"`
  770. Bar string `json:"bar"`
  771. }
  772. func TestContextAbortWithStatusJSON(t *testing.T) {
  773. w := httptest.NewRecorder()
  774. c, _ := CreateTestContext(w)
  775. c.index = 4
  776. in := new(testJSONAbortMsg)
  777. in.Bar = "barValue"
  778. in.Foo = "fooValue"
  779. c.AbortWithStatusJSON(415, in)
  780. assert.Equal(t, c.index, abortIndex)
  781. assert.Equal(t, c.Writer.Status(), 415)
  782. assert.Equal(t, w.Code, 415)
  783. assert.True(t, c.IsAborted())
  784. contentType := w.Header().Get("Content-Type")
  785. assert.Equal(t, contentType, "application/json; charset=utf-8")
  786. buf := new(bytes.Buffer)
  787. buf.ReadFrom(w.Body)
  788. jsonStringBody := buf.String()
  789. assert.Equal(t, fmt.Sprint(`{"foo":"fooValue","bar":"barValue"}`), jsonStringBody)
  790. }
  791. func TestContextError(t *testing.T) {
  792. c, _ := CreateTestContext(httptest.NewRecorder())
  793. assert.Empty(t, c.Errors)
  794. c.Error(errors.New("first error"))
  795. assert.Len(t, c.Errors, 1)
  796. assert.Equal(t, c.Errors.String(), "Error #01: first error\n")
  797. c.Error(&Error{
  798. Err: errors.New("second error"),
  799. Meta: "some data 2",
  800. Type: ErrorTypePublic,
  801. })
  802. assert.Len(t, c.Errors, 2)
  803. assert.Equal(t, c.Errors[0].Err, errors.New("first error"))
  804. assert.Nil(t, c.Errors[0].Meta)
  805. assert.Equal(t, c.Errors[0].Type, ErrorTypePrivate)
  806. assert.Equal(t, c.Errors[1].Err, errors.New("second error"))
  807. assert.Equal(t, c.Errors[1].Meta, "some data 2")
  808. assert.Equal(t, c.Errors[1].Type, ErrorTypePublic)
  809. assert.Equal(t, c.Errors.Last(), c.Errors[1])
  810. }
  811. func TestContextTypedError(t *testing.T) {
  812. c, _ := CreateTestContext(httptest.NewRecorder())
  813. c.Error(errors.New("externo 0")).SetType(ErrorTypePublic)
  814. c.Error(errors.New("interno 0")).SetType(ErrorTypePrivate)
  815. for _, err := range c.Errors.ByType(ErrorTypePublic) {
  816. assert.Equal(t, err.Type, ErrorTypePublic)
  817. }
  818. for _, err := range c.Errors.ByType(ErrorTypePrivate) {
  819. assert.Equal(t, err.Type, ErrorTypePrivate)
  820. }
  821. assert.Equal(t, c.Errors.Errors(), []string{"externo 0", "interno 0"})
  822. }
  823. func TestContextAbortWithError(t *testing.T) {
  824. w := httptest.NewRecorder()
  825. c, _ := CreateTestContext(w)
  826. c.AbortWithError(401, errors.New("bad input")).SetMeta("some input")
  827. assert.Equal(t, w.Code, 401)
  828. assert.Equal(t, c.index, abortIndex)
  829. assert.True(t, c.IsAborted())
  830. }
  831. func TestContextClientIP(t *testing.T) {
  832. c, _ := CreateTestContext(httptest.NewRecorder())
  833. c.Request, _ = http.NewRequest("POST", "/", nil)
  834. c.Request.Header.Set("X-Real-IP", " 10.10.10.10 ")
  835. c.Request.Header.Set("X-Forwarded-For", " 20.20.20.20, 30.30.30.30")
  836. c.Request.Header.Set("X-Appengine-Remote-Addr", "50.50.50.50")
  837. c.Request.RemoteAddr = " 40.40.40.40:42123 "
  838. assert.Equal(t, "20.20.20.20", c.ClientIP())
  839. c.Request.Header.Del("X-Forwarded-For")
  840. assert.Equal(t, "10.10.10.10", c.ClientIP())
  841. c.Request.Header.Set("X-Forwarded-For", "30.30.30.30 ")
  842. assert.Equal(t, "30.30.30.30", c.ClientIP())
  843. c.Request.Header.Del("X-Forwarded-For")
  844. c.Request.Header.Del("X-Real-IP")
  845. c.engine.AppEngine = true
  846. assert.Equal(t, "50.50.50.50", c.ClientIP())
  847. c.Request.Header.Del("X-Appengine-Remote-Addr")
  848. assert.Equal(t, "40.40.40.40", c.ClientIP())
  849. // no port
  850. c.Request.RemoteAddr = "50.50.50.50"
  851. assert.Equal(t, "", c.ClientIP())
  852. }
  853. func TestContextContentType(t *testing.T) {
  854. c, _ := CreateTestContext(httptest.NewRecorder())
  855. c.Request, _ = http.NewRequest("POST", "/", nil)
  856. c.Request.Header.Set("Content-Type", "application/json; charset=utf-8")
  857. assert.Equal(t, c.ContentType(), "application/json")
  858. }
  859. func TestContextAutoBindJSON(t *testing.T) {
  860. c, _ := CreateTestContext(httptest.NewRecorder())
  861. c.Request, _ = http.NewRequest("POST", "/", bytes.NewBufferString("{\"foo\":\"bar\", \"bar\":\"foo\"}"))
  862. c.Request.Header.Add("Content-Type", MIMEJSON)
  863. var obj struct {
  864. Foo string `json:"foo"`
  865. Bar string `json:"bar"`
  866. }
  867. assert.NoError(t, c.Bind(&obj))
  868. assert.Equal(t, obj.Bar, "foo")
  869. assert.Equal(t, obj.Foo, "bar")
  870. assert.Empty(t, c.Errors)
  871. }
  872. func TestContextBindWithJSON(t *testing.T) {
  873. w := httptest.NewRecorder()
  874. c, _ := CreateTestContext(w)
  875. c.Request, _ = http.NewRequest("POST", "/", bytes.NewBufferString("{\"foo\":\"bar\", \"bar\":\"foo\"}"))
  876. c.Request.Header.Add("Content-Type", MIMEXML) // set fake content-type
  877. var obj struct {
  878. Foo string `json:"foo"`
  879. Bar string `json:"bar"`
  880. }
  881. assert.NoError(t, c.BindJSON(&obj))
  882. assert.Equal(t, obj.Bar, "foo")
  883. assert.Equal(t, obj.Foo, "bar")
  884. assert.Equal(t, w.Body.Len(), 0)
  885. }
  886. func TestContextBadAutoBind(t *testing.T) {
  887. w := httptest.NewRecorder()
  888. c, _ := CreateTestContext(w)
  889. c.Request, _ = http.NewRequest("POST", "http://example.com", bytes.NewBufferString("\"foo\":\"bar\", \"bar\":\"foo\"}"))
  890. c.Request.Header.Add("Content-Type", MIMEJSON)
  891. var obj struct {
  892. Foo string `json:"foo"`
  893. Bar string `json:"bar"`
  894. }
  895. assert.False(t, c.IsAborted())
  896. assert.Error(t, c.Bind(&obj))
  897. c.Writer.WriteHeaderNow()
  898. assert.Empty(t, obj.Bar)
  899. assert.Empty(t, obj.Foo)
  900. assert.Equal(t, w.Code, 400)
  901. assert.True(t, c.IsAborted())
  902. }
  903. func TestContextGolangContext(t *testing.T) {
  904. c, _ := CreateTestContext(httptest.NewRecorder())
  905. c.Request, _ = http.NewRequest("POST", "/", bytes.NewBufferString("{\"foo\":\"bar\", \"bar\":\"foo\"}"))
  906. assert.NoError(t, c.Err())
  907. assert.Nil(t, c.Done())
  908. ti, ok := c.Deadline()
  909. assert.Equal(t, ti, time.Time{})
  910. assert.False(t, ok)
  911. assert.Equal(t, c.Value(0), c.Request)
  912. assert.Nil(t, c.Value("foo"))
  913. c.Set("foo", "bar")
  914. assert.Equal(t, c.Value("foo"), "bar")
  915. assert.Nil(t, c.Value(1))
  916. }
  917. func TestWebsocketsRequired(t *testing.T) {
  918. // Example request from spec: https://tools.ietf.org/html/rfc6455#section-1.2
  919. c, _ := CreateTestContext(httptest.NewRecorder())
  920. c.Request, _ = http.NewRequest("GET", "/chat", nil)
  921. c.Request.Header.Set("Host", "server.example.com")
  922. c.Request.Header.Set("Upgrade", "websocket")
  923. c.Request.Header.Set("Connection", "Upgrade")
  924. c.Request.Header.Set("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==")
  925. c.Request.Header.Set("Origin", "http://example.com")
  926. c.Request.Header.Set("Sec-WebSocket-Protocol", "chat, superchat")
  927. c.Request.Header.Set("Sec-WebSocket-Version", "13")
  928. assert.True(t, c.IsWebsocket())
  929. // Normal request, no websocket required.
  930. c, _ = CreateTestContext(httptest.NewRecorder())
  931. c.Request, _ = http.NewRequest("GET", "/chat", nil)
  932. c.Request.Header.Set("Host", "server.example.com")
  933. assert.False(t, c.IsWebsocket())
  934. }
  935. func TestGetRequestHeaderValue(t *testing.T) {
  936. c, _ := CreateTestContext(httptest.NewRecorder())
  937. c.Request, _ = http.NewRequest("GET", "/chat", nil)
  938. c.Request.Header.Set("Gin-Version", "1.0.0")
  939. assert.Equal(t, "1.0.0", c.GetHeader("Gin-Version"))
  940. assert.Equal(t, "", c.GetHeader("Connection"))
  941. }
  942. func TestContextGetRawData(t *testing.T) {
  943. c, _ := CreateTestContext(httptest.NewRecorder())
  944. body := bytes.NewBufferString("Fetch binary post data")
  945. c.Request, _ = http.NewRequest("POST", "/", body)
  946. c.Request.Header.Add("Content-Type", MIMEPOSTForm)
  947. data, err := c.GetRawData()
  948. assert.Nil(t, err)
  949. assert.Equal(t, "Fetch binary post data", string(data))
  950. }