context_test.go 35 KB

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