context_test.go 33 KB

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