context_test.go 50 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667686970717273747576777879808182838485868788899091929394959697989910010110210310410510610710810911011111211311411511611711811912012112212312412512612712812913013113213313413513613713813914014114214314414514614714814915015115215315415515615715815916016116216316416516616716816917017117217317417517617717817918018118218318418518618718818919019119219319419519619719819920020120220320420520620720820921021121221321421521621721821922022122222322422522622722822923023123223323423523623723823924024124224324424524624724824925025125225325425525625725825926026126226326426526626726826927027127227327427527627727827928028128228328428528628728828929029129229329429529629729829930030130230330430530630730830931031131231331431531631731831932032132232332432532632732832933033133233333433533633733833934034134234334434534634734834935035135235335435535635735835936036136236336436536636736836937037137237337437537637737837938038138238338438538638738838939039139239339439539639739839940040140240340440540640740840941041141241341441541641741841942042142242342442542642742842943043143243343443543643743843944044144244344444544644744844945045145245345445545645745845946046146246346446546646746846947047147247347447547647747847948048148248348448548648748848949049149249349449549649749849950050150250350450550650750850951051151251351451551651751851952052152252352452552652752852953053153253353453553653753853954054154254354454554654754854955055155255355455555655755855956056156256356456556656756856957057157257357457557657757857958058158258358458558658758858959059159259359459559659759859960060160260360460560660760860961061161261361461561661761861962062162262362462562662762862963063163263363463563663763863964064164264364464564664764864965065165265365465565665765865966066166266366466566666766866967067167267367467567667767867968068168268368468568668768868969069169269369469569669769869970070170270370470570670770870971071171271371471571671771871972072172272372472572672772872973073173273373473573673773873974074174274374474574674774874975075175275375475575675775875976076176276376476576676776876977077177277377477577677777877978078178278378478578678778878979079179279379479579679779879980080180280380480580680780880981081181281381481581681781881982082182282382482582682782882983083183283383483583683783883984084184284384484584684784884985085185285385485585685785885986086186286386486586686786886987087187287387487587687787887988088188288388488588688788888989089189289389489589689789889990090190290390490590690790890991091191291391491591691791891992092192292392492592692792892993093193293393493593693793893994094194294394494594694794894995095195295395495595695795895996096196296396496596696796896997097197297397497597697797897998098198298398498598698798898999099199299399499599699799899910001001100210031004100510061007100810091010101110121013101410151016101710181019102010211022102310241025102610271028102910301031103210331034103510361037103810391040104110421043104410451046104710481049105010511052105310541055105610571058105910601061106210631064106510661067106810691070107110721073107410751076107710781079108010811082108310841085108610871088108910901091109210931094109510961097109810991100110111021103110411051106110711081109111011111112111311141115111611171118111911201121112211231124112511261127112811291130113111321133113411351136113711381139114011411142114311441145114611471148114911501151115211531154115511561157115811591160116111621163116411651166116711681169117011711172117311741175117611771178117911801181118211831184118511861187118811891190119111921193119411951196119711981199120012011202120312041205120612071208120912101211121212131214121512161217121812191220122112221223122412251226122712281229123012311232123312341235123612371238123912401241124212431244124512461247124812491250125112521253125412551256125712581259126012611262126312641265126612671268126912701271127212731274127512761277127812791280128112821283128412851286128712881289129012911292129312941295129612971298129913001301130213031304130513061307130813091310131113121313131413151316131713181319132013211322132313241325132613271328132913301331133213331334133513361337133813391340134113421343134413451346134713481349135013511352135313541355135613571358135913601361136213631364136513661367136813691370137113721373137413751376137713781379138013811382138313841385138613871388138913901391139213931394139513961397139813991400140114021403140414051406140714081409141014111412141314141415141614171418141914201421142214231424142514261427142814291430143114321433143414351436143714381439144014411442144314441445144614471448144914501451145214531454145514561457145814591460146114621463146414651466146714681469147014711472147314741475147614771478147914801481148214831484148514861487148814891490149114921493149414951496149714981499150015011502150315041505150615071508150915101511151215131514151515161517151815191520152115221523152415251526152715281529153015311532153315341535153615371538153915401541154215431544154515461547154815491550155115521553155415551556155715581559156015611562156315641565156615671568156915701571157215731574157515761577157815791580158115821583158415851586158715881589159015911592159315941595159615971598159916001601160216031604160516061607160816091610161116121613161416151616161716181619162016211622162316241625162616271628162916301631163216331634163516361637163816391640164116421643164416451646164716481649165016511652165316541655165616571658165916601661166216631664166516661667166816691670167116721673167416751676167716781679168016811682168316841685168616871688
  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. "io"
  11. "mime/multipart"
  12. "net/http"
  13. "net/http/httptest"
  14. "reflect"
  15. "strings"
  16. "testing"
  17. "time"
  18. "github.com/gin-contrib/sse"
  19. "github.com/gin-gonic/gin/binding"
  20. "github.com/golang/protobuf/proto"
  21. "github.com/stretchr/testify/assert"
  22. "golang.org/x/net/context"
  23. testdata "github.com/gin-gonic/gin/testdata/protoexample"
  24. )
  25. var _ context.Context = &Context{}
  26. // Unit tests TODO
  27. // func (c *Context) File(filepath string) {
  28. // func (c *Context) Negotiate(code int, config Negotiate) {
  29. // BAD case: func (c *Context) Render(code int, render render.Render, obj ...interface{}) {
  30. // test that information is not leaked when reusing Contexts (using the Pool)
  31. func createMultipartRequest() *http.Request {
  32. boundary := "--testboundary"
  33. body := new(bytes.Buffer)
  34. mw := multipart.NewWriter(body)
  35. defer mw.Close()
  36. must(mw.SetBoundary(boundary))
  37. must(mw.WriteField("foo", "bar"))
  38. must(mw.WriteField("bar", "10"))
  39. must(mw.WriteField("bar", "foo2"))
  40. must(mw.WriteField("array", "first"))
  41. must(mw.WriteField("array", "second"))
  42. must(mw.WriteField("id", ""))
  43. must(mw.WriteField("time_local", "31/12/2016 14:55"))
  44. must(mw.WriteField("time_utc", "31/12/2016 14:55"))
  45. must(mw.WriteField("time_location", "31/12/2016 14:55"))
  46. must(mw.WriteField("names[a]", "thinkerou"))
  47. must(mw.WriteField("names[b]", "tianou"))
  48. req, err := http.NewRequest("POST", "/", body)
  49. must(err)
  50. req.Header.Set("Content-Type", MIMEMultipartPOSTForm+"; boundary="+boundary)
  51. return req
  52. }
  53. func must(err error) {
  54. if err != nil {
  55. panic(err.Error())
  56. }
  57. }
  58. func TestContextFormFile(t *testing.T) {
  59. buf := new(bytes.Buffer)
  60. mw := multipart.NewWriter(buf)
  61. w, err := mw.CreateFormFile("file", "test")
  62. if assert.NoError(t, err) {
  63. w.Write([]byte("test"))
  64. }
  65. mw.Close()
  66. c, _ := CreateTestContext(httptest.NewRecorder())
  67. c.Request, _ = http.NewRequest("POST", "/", buf)
  68. c.Request.Header.Set("Content-Type", mw.FormDataContentType())
  69. f, err := c.FormFile("file")
  70. if assert.NoError(t, err) {
  71. assert.Equal(t, "test", f.Filename)
  72. }
  73. assert.NoError(t, c.SaveUploadedFile(f, "test"))
  74. }
  75. func TestContextMultipartForm(t *testing.T) {
  76. buf := new(bytes.Buffer)
  77. mw := multipart.NewWriter(buf)
  78. mw.WriteField("foo", "bar")
  79. w, err := mw.CreateFormFile("file", "test")
  80. if assert.NoError(t, err) {
  81. w.Write([]byte("test"))
  82. }
  83. mw.Close()
  84. c, _ := CreateTestContext(httptest.NewRecorder())
  85. c.Request, _ = http.NewRequest("POST", "/", buf)
  86. c.Request.Header.Set("Content-Type", mw.FormDataContentType())
  87. f, err := c.MultipartForm()
  88. if assert.NoError(t, err) {
  89. assert.NotNil(t, f)
  90. }
  91. assert.NoError(t, c.SaveUploadedFile(f.File["file"][0], "test"))
  92. }
  93. func TestSaveUploadedOpenFailed(t *testing.T) {
  94. buf := new(bytes.Buffer)
  95. mw := multipart.NewWriter(buf)
  96. mw.Close()
  97. c, _ := CreateTestContext(httptest.NewRecorder())
  98. c.Request, _ = http.NewRequest("POST", "/", buf)
  99. c.Request.Header.Set("Content-Type", mw.FormDataContentType())
  100. f := &multipart.FileHeader{
  101. Filename: "file",
  102. }
  103. assert.Error(t, c.SaveUploadedFile(f, "test"))
  104. }
  105. func TestSaveUploadedCreateFailed(t *testing.T) {
  106. buf := new(bytes.Buffer)
  107. mw := multipart.NewWriter(buf)
  108. w, err := mw.CreateFormFile("file", "test")
  109. if assert.NoError(t, err) {
  110. w.Write([]byte("test"))
  111. }
  112. mw.Close()
  113. c, _ := CreateTestContext(httptest.NewRecorder())
  114. c.Request, _ = http.NewRequest("POST", "/", buf)
  115. c.Request.Header.Set("Content-Type", mw.FormDataContentType())
  116. f, err := c.FormFile("file")
  117. if assert.NoError(t, err) {
  118. assert.Equal(t, "test", f.Filename)
  119. }
  120. assert.Error(t, c.SaveUploadedFile(f, "/"))
  121. }
  122. func TestContextReset(t *testing.T) {
  123. router := New()
  124. c := router.allocateContext()
  125. assert.Equal(t, c.engine, router)
  126. c.index = 2
  127. c.Writer = &responseWriter{ResponseWriter: httptest.NewRecorder()}
  128. c.Params = Params{Param{}}
  129. c.Error(errors.New("test"))
  130. c.Set("foo", "bar")
  131. c.reset()
  132. assert.False(t, c.IsAborted())
  133. assert.Nil(t, c.Keys)
  134. assert.Nil(t, c.Accepted)
  135. assert.Len(t, c.Errors, 0)
  136. assert.Empty(t, c.Errors.Errors())
  137. assert.Empty(t, c.Errors.ByType(ErrorTypeAny))
  138. assert.Len(t, c.Params, 0)
  139. assert.EqualValues(t, c.index, -1)
  140. assert.Equal(t, c.Writer.(*responseWriter), &c.writermem)
  141. }
  142. func TestContextHandlers(t *testing.T) {
  143. c, _ := CreateTestContext(httptest.NewRecorder())
  144. assert.Nil(t, c.handlers)
  145. assert.Nil(t, c.handlers.Last())
  146. c.handlers = HandlersChain{}
  147. assert.NotNil(t, c.handlers)
  148. assert.Nil(t, c.handlers.Last())
  149. f := func(c *Context) {}
  150. g := func(c *Context) {}
  151. c.handlers = HandlersChain{f}
  152. compareFunc(t, f, c.handlers.Last())
  153. c.handlers = HandlersChain{f, g}
  154. compareFunc(t, g, c.handlers.Last())
  155. }
  156. // TestContextSetGet tests that a parameter is set correctly on the
  157. // current context and can be retrieved using Get.
  158. func TestContextSetGet(t *testing.T) {
  159. c, _ := CreateTestContext(httptest.NewRecorder())
  160. c.Set("foo", "bar")
  161. value, err := c.Get("foo")
  162. assert.Equal(t, "bar", value)
  163. assert.True(t, err)
  164. value, err = c.Get("foo2")
  165. assert.Nil(t, value)
  166. assert.False(t, err)
  167. assert.Equal(t, "bar", c.MustGet("foo"))
  168. assert.Panics(t, func() { c.MustGet("no_exist") })
  169. }
  170. func TestContextSetGetValues(t *testing.T) {
  171. c, _ := CreateTestContext(httptest.NewRecorder())
  172. c.Set("string", "this is a string")
  173. c.Set("int32", int32(-42))
  174. c.Set("int64", int64(42424242424242))
  175. c.Set("uint64", uint64(42))
  176. c.Set("float32", float32(4.2))
  177. c.Set("float64", 4.2)
  178. var a interface{} = 1
  179. c.Set("intInterface", a)
  180. assert.Exactly(t, c.MustGet("string").(string), "this is a string")
  181. assert.Exactly(t, c.MustGet("int32").(int32), int32(-42))
  182. assert.Exactly(t, c.MustGet("int64").(int64), int64(42424242424242))
  183. assert.Exactly(t, c.MustGet("uint64").(uint64), uint64(42))
  184. assert.Exactly(t, c.MustGet("float32").(float32), float32(4.2))
  185. assert.Exactly(t, c.MustGet("float64").(float64), 4.2)
  186. assert.Exactly(t, c.MustGet("intInterface").(int), 1)
  187. }
  188. func TestContextGetString(t *testing.T) {
  189. c, _ := CreateTestContext(httptest.NewRecorder())
  190. c.Set("string", "this is a string")
  191. assert.Equal(t, "this is a string", c.GetString("string"))
  192. }
  193. func TestContextSetGetBool(t *testing.T) {
  194. c, _ := CreateTestContext(httptest.NewRecorder())
  195. c.Set("bool", true)
  196. assert.True(t, c.GetBool("bool"))
  197. }
  198. func TestContextGetInt(t *testing.T) {
  199. c, _ := CreateTestContext(httptest.NewRecorder())
  200. c.Set("int", 1)
  201. assert.Equal(t, 1, c.GetInt("int"))
  202. }
  203. func TestContextGetInt64(t *testing.T) {
  204. c, _ := CreateTestContext(httptest.NewRecorder())
  205. c.Set("int64", int64(42424242424242))
  206. assert.Equal(t, int64(42424242424242), c.GetInt64("int64"))
  207. }
  208. func TestContextGetFloat64(t *testing.T) {
  209. c, _ := CreateTestContext(httptest.NewRecorder())
  210. c.Set("float64", 4.2)
  211. assert.Equal(t, 4.2, c.GetFloat64("float64"))
  212. }
  213. func TestContextGetTime(t *testing.T) {
  214. c, _ := CreateTestContext(httptest.NewRecorder())
  215. t1, _ := time.Parse("1/2/2006 15:04:05", "01/01/2017 12:00:00")
  216. c.Set("time", t1)
  217. assert.Equal(t, t1, c.GetTime("time"))
  218. }
  219. func TestContextGetDuration(t *testing.T) {
  220. c, _ := CreateTestContext(httptest.NewRecorder())
  221. c.Set("duration", time.Second)
  222. assert.Equal(t, time.Second, c.GetDuration("duration"))
  223. }
  224. func TestContextGetStringSlice(t *testing.T) {
  225. c, _ := CreateTestContext(httptest.NewRecorder())
  226. c.Set("slice", []string{"foo"})
  227. assert.Equal(t, []string{"foo"}, c.GetStringSlice("slice"))
  228. }
  229. func TestContextGetStringMap(t *testing.T) {
  230. c, _ := CreateTestContext(httptest.NewRecorder())
  231. var m = make(map[string]interface{})
  232. m["foo"] = 1
  233. c.Set("map", m)
  234. assert.Equal(t, m, c.GetStringMap("map"))
  235. assert.Equal(t, 1, c.GetStringMap("map")["foo"])
  236. }
  237. func TestContextGetStringMapString(t *testing.T) {
  238. c, _ := CreateTestContext(httptest.NewRecorder())
  239. var m = make(map[string]string)
  240. m["foo"] = "bar"
  241. c.Set("map", m)
  242. assert.Equal(t, m, c.GetStringMapString("map"))
  243. assert.Equal(t, "bar", c.GetStringMapString("map")["foo"])
  244. }
  245. func TestContextGetStringMapStringSlice(t *testing.T) {
  246. c, _ := CreateTestContext(httptest.NewRecorder())
  247. var m = make(map[string][]string)
  248. m["foo"] = []string{"foo"}
  249. c.Set("map", m)
  250. assert.Equal(t, m, c.GetStringMapStringSlice("map"))
  251. assert.Equal(t, []string{"foo"}, c.GetStringMapStringSlice("map")["foo"])
  252. }
  253. func TestContextCopy(t *testing.T) {
  254. c, _ := CreateTestContext(httptest.NewRecorder())
  255. c.index = 2
  256. c.Request, _ = http.NewRequest("POST", "/hola", nil)
  257. c.handlers = HandlersChain{func(c *Context) {}}
  258. c.Params = Params{Param{Key: "foo", Value: "bar"}}
  259. c.Set("foo", "bar")
  260. cp := c.Copy()
  261. assert.Nil(t, cp.handlers)
  262. assert.Nil(t, cp.writermem.ResponseWriter)
  263. assert.Equal(t, &cp.writermem, cp.Writer.(*responseWriter))
  264. assert.Equal(t, cp.Request, c.Request)
  265. assert.Equal(t, cp.index, abortIndex)
  266. assert.Equal(t, cp.Keys, c.Keys)
  267. assert.Equal(t, cp.engine, c.engine)
  268. assert.Equal(t, cp.Params, c.Params)
  269. }
  270. func TestContextHandlerName(t *testing.T) {
  271. c, _ := CreateTestContext(httptest.NewRecorder())
  272. c.handlers = HandlersChain{func(c *Context) {}, handlerNameTest}
  273. assert.Regexp(t, "^(.*/vendor/)?github.com/gin-gonic/gin.handlerNameTest$", c.HandlerName())
  274. }
  275. func handlerNameTest(c *Context) {
  276. }
  277. var handlerTest HandlerFunc = func(c *Context) {
  278. }
  279. func TestContextHandler(t *testing.T) {
  280. c, _ := CreateTestContext(httptest.NewRecorder())
  281. c.handlers = HandlersChain{func(c *Context) {}, handlerTest}
  282. assert.Equal(t, reflect.ValueOf(handlerTest).Pointer(), reflect.ValueOf(c.Handler()).Pointer())
  283. }
  284. func TestContextQuery(t *testing.T) {
  285. c, _ := CreateTestContext(httptest.NewRecorder())
  286. c.Request, _ = http.NewRequest("GET", "http://example.com/?foo=bar&page=10&id=", nil)
  287. value, ok := c.GetQuery("foo")
  288. assert.True(t, ok)
  289. assert.Equal(t, "bar", value)
  290. assert.Equal(t, "bar", c.DefaultQuery("foo", "none"))
  291. assert.Equal(t, "bar", c.Query("foo"))
  292. value, ok = c.GetQuery("page")
  293. assert.True(t, ok)
  294. assert.Equal(t, "10", value)
  295. assert.Equal(t, "10", c.DefaultQuery("page", "0"))
  296. assert.Equal(t, "10", c.Query("page"))
  297. value, ok = c.GetQuery("id")
  298. assert.True(t, ok)
  299. assert.Empty(t, value)
  300. assert.Empty(t, c.DefaultQuery("id", "nada"))
  301. assert.Empty(t, c.Query("id"))
  302. value, ok = c.GetQuery("NoKey")
  303. assert.False(t, ok)
  304. assert.Empty(t, value)
  305. assert.Equal(t, "nada", c.DefaultQuery("NoKey", "nada"))
  306. assert.Empty(t, c.Query("NoKey"))
  307. // postform should not mess
  308. value, ok = c.GetPostForm("page")
  309. assert.False(t, ok)
  310. assert.Empty(t, value)
  311. assert.Empty(t, c.PostForm("foo"))
  312. }
  313. func TestContextQueryAndPostForm(t *testing.T) {
  314. c, _ := CreateTestContext(httptest.NewRecorder())
  315. body := bytes.NewBufferString("foo=bar&page=11&both=&foo=second")
  316. c.Request, _ = http.NewRequest("POST",
  317. "/?both=GET&id=main&id=omit&array[]=first&array[]=second&ids[a]=hi&ids[b]=3.14", body)
  318. c.Request.Header.Add("Content-Type", MIMEPOSTForm)
  319. assert.Equal(t, "bar", c.DefaultPostForm("foo", "none"))
  320. assert.Equal(t, "bar", c.PostForm("foo"))
  321. assert.Empty(t, c.Query("foo"))
  322. value, ok := c.GetPostForm("page")
  323. assert.True(t, ok)
  324. assert.Equal(t, "11", value)
  325. assert.Equal(t, "11", c.DefaultPostForm("page", "0"))
  326. assert.Equal(t, "11", c.PostForm("page"))
  327. assert.Empty(t, c.Query("page"))
  328. value, ok = c.GetPostForm("both")
  329. assert.True(t, ok)
  330. assert.Empty(t, value)
  331. assert.Empty(t, c.PostForm("both"))
  332. assert.Empty(t, c.DefaultPostForm("both", "nothing"))
  333. assert.Equal(t, "GET", c.Query("both"), "GET")
  334. value, ok = c.GetQuery("id")
  335. assert.True(t, ok)
  336. assert.Equal(t, "main", value)
  337. assert.Equal(t, "000", c.DefaultPostForm("id", "000"))
  338. assert.Equal(t, "main", c.Query("id"))
  339. assert.Empty(t, c.PostForm("id"))
  340. value, ok = c.GetQuery("NoKey")
  341. assert.False(t, ok)
  342. assert.Empty(t, value)
  343. value, ok = c.GetPostForm("NoKey")
  344. assert.False(t, ok)
  345. assert.Empty(t, value)
  346. assert.Equal(t, "nada", c.DefaultPostForm("NoKey", "nada"))
  347. assert.Equal(t, "nothing", c.DefaultQuery("NoKey", "nothing"))
  348. assert.Empty(t, c.PostForm("NoKey"))
  349. assert.Empty(t, c.Query("NoKey"))
  350. var obj struct {
  351. Foo string `form:"foo"`
  352. ID string `form:"id"`
  353. Page int `form:"page"`
  354. Both string `form:"both"`
  355. Array []string `form:"array[]"`
  356. }
  357. assert.NoError(t, c.Bind(&obj))
  358. assert.Equal(t, "bar", obj.Foo, "bar")
  359. assert.Equal(t, "main", obj.ID, "main")
  360. assert.Equal(t, 11, obj.Page, 11)
  361. assert.Empty(t, obj.Both)
  362. assert.Equal(t, []string{"first", "second"}, obj.Array)
  363. values, ok := c.GetQueryArray("array[]")
  364. assert.True(t, ok)
  365. assert.Equal(t, "first", values[0])
  366. assert.Equal(t, "second", values[1])
  367. values = c.QueryArray("array[]")
  368. assert.Equal(t, "first", values[0])
  369. assert.Equal(t, "second", values[1])
  370. values = c.QueryArray("nokey")
  371. assert.Equal(t, 0, len(values))
  372. values = c.QueryArray("both")
  373. assert.Equal(t, 1, len(values))
  374. assert.Equal(t, "GET", values[0])
  375. dicts, ok := c.GetQueryMap("ids")
  376. assert.True(t, ok)
  377. assert.Equal(t, "hi", dicts["a"])
  378. assert.Equal(t, "3.14", dicts["b"])
  379. dicts, ok = c.GetQueryMap("nokey")
  380. assert.False(t, ok)
  381. assert.Equal(t, 0, len(dicts))
  382. dicts, ok = c.GetQueryMap("both")
  383. assert.False(t, ok)
  384. assert.Equal(t, 0, len(dicts))
  385. dicts, ok = c.GetQueryMap("array")
  386. assert.False(t, ok)
  387. assert.Equal(t, 0, len(dicts))
  388. dicts = c.QueryMap("ids")
  389. assert.Equal(t, "hi", dicts["a"])
  390. assert.Equal(t, "3.14", dicts["b"])
  391. dicts = c.QueryMap("nokey")
  392. assert.Equal(t, 0, len(dicts))
  393. }
  394. func TestContextPostFormMultipart(t *testing.T) {
  395. c, _ := CreateTestContext(httptest.NewRecorder())
  396. c.Request = createMultipartRequest()
  397. var obj struct {
  398. Foo string `form:"foo"`
  399. Bar string `form:"bar"`
  400. BarAsInt int `form:"bar"`
  401. Array []string `form:"array"`
  402. ID string `form:"id"`
  403. TimeLocal time.Time `form:"time_local" time_format:"02/01/2006 15:04"`
  404. TimeUTC time.Time `form:"time_utc" time_format:"02/01/2006 15:04" time_utc:"1"`
  405. TimeLocation time.Time `form:"time_location" time_format:"02/01/2006 15:04" time_location:"Asia/Tokyo"`
  406. BlankTime time.Time `form:"blank_time" time_format:"02/01/2006 15:04"`
  407. }
  408. assert.NoError(t, c.Bind(&obj))
  409. assert.Equal(t, "bar", obj.Foo)
  410. assert.Equal(t, "10", obj.Bar)
  411. assert.Equal(t, 10, obj.BarAsInt)
  412. assert.Equal(t, []string{"first", "second"}, obj.Array)
  413. assert.Empty(t, obj.ID)
  414. assert.Equal(t, "31/12/2016 14:55", obj.TimeLocal.Format("02/01/2006 15:04"))
  415. assert.Equal(t, time.Local, obj.TimeLocal.Location())
  416. assert.Equal(t, "31/12/2016 14:55", obj.TimeUTC.Format("02/01/2006 15:04"))
  417. assert.Equal(t, time.UTC, obj.TimeUTC.Location())
  418. loc, _ := time.LoadLocation("Asia/Tokyo")
  419. assert.Equal(t, "31/12/2016 14:55", obj.TimeLocation.Format("02/01/2006 15:04"))
  420. assert.Equal(t, loc, obj.TimeLocation.Location())
  421. assert.True(t, obj.BlankTime.IsZero())
  422. value, ok := c.GetQuery("foo")
  423. assert.False(t, ok)
  424. assert.Empty(t, value)
  425. assert.Empty(t, c.Query("bar"))
  426. assert.Equal(t, "nothing", c.DefaultQuery("id", "nothing"))
  427. value, ok = c.GetPostForm("foo")
  428. assert.True(t, ok)
  429. assert.Equal(t, "bar", value)
  430. assert.Equal(t, "bar", c.PostForm("foo"))
  431. value, ok = c.GetPostForm("array")
  432. assert.True(t, ok)
  433. assert.Equal(t, "first", value)
  434. assert.Equal(t, "first", c.PostForm("array"))
  435. assert.Equal(t, "10", c.DefaultPostForm("bar", "nothing"))
  436. value, ok = c.GetPostForm("id")
  437. assert.True(t, ok)
  438. assert.Empty(t, value)
  439. assert.Empty(t, c.PostForm("id"))
  440. assert.Empty(t, c.DefaultPostForm("id", "nothing"))
  441. value, ok = c.GetPostForm("nokey")
  442. assert.False(t, ok)
  443. assert.Empty(t, value)
  444. assert.Equal(t, "nothing", c.DefaultPostForm("nokey", "nothing"))
  445. values, ok := c.GetPostFormArray("array")
  446. assert.True(t, ok)
  447. assert.Equal(t, "first", values[0])
  448. assert.Equal(t, "second", values[1])
  449. values = c.PostFormArray("array")
  450. assert.Equal(t, "first", values[0])
  451. assert.Equal(t, "second", values[1])
  452. values = c.PostFormArray("nokey")
  453. assert.Equal(t, 0, len(values))
  454. values = c.PostFormArray("foo")
  455. assert.Equal(t, 1, len(values))
  456. assert.Equal(t, "bar", values[0])
  457. dicts, ok := c.GetPostFormMap("names")
  458. assert.True(t, ok)
  459. assert.Equal(t, "thinkerou", dicts["a"])
  460. assert.Equal(t, "tianou", dicts["b"])
  461. dicts, ok = c.GetPostFormMap("nokey")
  462. assert.False(t, ok)
  463. assert.Equal(t, 0, len(dicts))
  464. dicts = c.PostFormMap("names")
  465. assert.Equal(t, "thinkerou", dicts["a"])
  466. assert.Equal(t, "tianou", dicts["b"])
  467. dicts = c.PostFormMap("nokey")
  468. assert.Equal(t, 0, len(dicts))
  469. }
  470. func TestContextSetCookie(t *testing.T) {
  471. c, _ := CreateTestContext(httptest.NewRecorder())
  472. c.SetCookie("user", "gin", 1, "/", "localhost", true, true)
  473. assert.Equal(t, "user=gin; Path=/; Domain=localhost; Max-Age=1; HttpOnly; Secure", c.Writer.Header().Get("Set-Cookie"))
  474. }
  475. func TestContextSetCookiePathEmpty(t *testing.T) {
  476. c, _ := CreateTestContext(httptest.NewRecorder())
  477. c.SetCookie("user", "gin", 1, "", "localhost", true, true)
  478. assert.Equal(t, "user=gin; Path=/; Domain=localhost; Max-Age=1; HttpOnly; Secure", c.Writer.Header().Get("Set-Cookie"))
  479. }
  480. func TestContextGetCookie(t *testing.T) {
  481. c, _ := CreateTestContext(httptest.NewRecorder())
  482. c.Request, _ = http.NewRequest("GET", "/get", nil)
  483. c.Request.Header.Set("Cookie", "user=gin")
  484. cookie, _ := c.Cookie("user")
  485. assert.Equal(t, "gin", cookie)
  486. _, err := c.Cookie("nokey")
  487. assert.Error(t, err)
  488. }
  489. func TestContextBodyAllowedForStatus(t *testing.T) {
  490. // todo(thinkerou): go1.6 not support StatusProcessing
  491. assert.False(t, false, bodyAllowedForStatus(102))
  492. assert.False(t, false, bodyAllowedForStatus(http.StatusNoContent))
  493. assert.False(t, false, bodyAllowedForStatus(http.StatusNotModified))
  494. assert.True(t, true, bodyAllowedForStatus(http.StatusInternalServerError))
  495. }
  496. type TestPanicRender struct {
  497. }
  498. func (*TestPanicRender) Render(http.ResponseWriter) error {
  499. return errors.New("TestPanicRender")
  500. }
  501. func (*TestPanicRender) WriteContentType(http.ResponseWriter) {}
  502. func TestContextRenderPanicIfErr(t *testing.T) {
  503. defer func() {
  504. r := recover()
  505. assert.Equal(t, "TestPanicRender", fmt.Sprint(r))
  506. }()
  507. w := httptest.NewRecorder()
  508. c, _ := CreateTestContext(w)
  509. c.Render(http.StatusOK, &TestPanicRender{})
  510. assert.Fail(t, "Panic not detected")
  511. }
  512. // Tests that the response is serialized as JSON
  513. // and Content-Type is set to application/json
  514. // and special HTML characters are escaped
  515. func TestContextRenderJSON(t *testing.T) {
  516. w := httptest.NewRecorder()
  517. c, _ := CreateTestContext(w)
  518. c.JSON(http.StatusCreated, H{"foo": "bar", "html": "<b>"})
  519. assert.Equal(t, http.StatusCreated, w.Code)
  520. assert.Equal(t, "{\"foo\":\"bar\",\"html\":\"\\u003cb\\u003e\"}", w.Body.String())
  521. assert.Equal(t, "application/json; charset=utf-8", w.Header().Get("Content-Type"))
  522. }
  523. // Tests that the response is serialized as JSONP
  524. // and Content-Type is set to application/javascript
  525. func TestContextRenderJSONP(t *testing.T) {
  526. w := httptest.NewRecorder()
  527. c, _ := CreateTestContext(w)
  528. c.Request, _ = http.NewRequest("GET", "http://example.com/?callback=x", nil)
  529. c.JSONP(http.StatusCreated, H{"foo": "bar"})
  530. assert.Equal(t, http.StatusCreated, w.Code)
  531. assert.Equal(t, "x({\"foo\":\"bar\"})", w.Body.String())
  532. assert.Equal(t, "application/javascript; charset=utf-8", w.Header().Get("Content-Type"))
  533. }
  534. // Tests that the response is serialized as JSONP
  535. // and Content-Type is set to application/json
  536. func TestContextRenderJSONPWithoutCallback(t *testing.T) {
  537. w := httptest.NewRecorder()
  538. c, _ := CreateTestContext(w)
  539. c.Request, _ = http.NewRequest("GET", "http://example.com", nil)
  540. c.JSONP(http.StatusCreated, H{"foo": "bar"})
  541. assert.Equal(t, http.StatusCreated, w.Code)
  542. assert.Equal(t, "{\"foo\":\"bar\"}", w.Body.String())
  543. assert.Equal(t, "application/json; charset=utf-8", w.Header().Get("Content-Type"))
  544. }
  545. // Tests that no JSON is rendered if code is 204
  546. func TestContextRenderNoContentJSON(t *testing.T) {
  547. w := httptest.NewRecorder()
  548. c, _ := CreateTestContext(w)
  549. c.JSON(http.StatusNoContent, H{"foo": "bar"})
  550. assert.Equal(t, http.StatusNoContent, w.Code)
  551. assert.Empty(t, w.Body.String())
  552. assert.Equal(t, "application/json; charset=utf-8", w.Header().Get("Content-Type"))
  553. }
  554. // Tests that the response is serialized as JSON
  555. // we change the content-type before
  556. func TestContextRenderAPIJSON(t *testing.T) {
  557. w := httptest.NewRecorder()
  558. c, _ := CreateTestContext(w)
  559. c.Header("Content-Type", "application/vnd.api+json")
  560. c.JSON(http.StatusCreated, H{"foo": "bar"})
  561. assert.Equal(t, http.StatusCreated, w.Code)
  562. assert.Equal(t, "{\"foo\":\"bar\"}", w.Body.String())
  563. assert.Equal(t, "application/vnd.api+json", w.Header().Get("Content-Type"))
  564. }
  565. // Tests that no Custom JSON is rendered if code is 204
  566. func TestContextRenderNoContentAPIJSON(t *testing.T) {
  567. w := httptest.NewRecorder()
  568. c, _ := CreateTestContext(w)
  569. c.Header("Content-Type", "application/vnd.api+json")
  570. c.JSON(http.StatusNoContent, H{"foo": "bar"})
  571. assert.Equal(t, http.StatusNoContent, w.Code)
  572. assert.Empty(t, w.Body.String())
  573. assert.Equal(t, w.Header().Get("Content-Type"), "application/vnd.api+json")
  574. }
  575. // Tests that the response is serialized as JSON
  576. // and Content-Type is set to application/json
  577. func TestContextRenderIndentedJSON(t *testing.T) {
  578. w := httptest.NewRecorder()
  579. c, _ := CreateTestContext(w)
  580. c.IndentedJSON(http.StatusCreated, H{"foo": "bar", "bar": "foo", "nested": H{"foo": "bar"}})
  581. assert.Equal(t, http.StatusCreated, w.Code)
  582. assert.Equal(t, "{\n \"bar\": \"foo\",\n \"foo\": \"bar\",\n \"nested\": {\n \"foo\": \"bar\"\n }\n}", w.Body.String())
  583. assert.Equal(t, "application/json; charset=utf-8", w.Header().Get("Content-Type"))
  584. }
  585. // Tests that no Custom JSON is rendered if code is 204
  586. func TestContextRenderNoContentIndentedJSON(t *testing.T) {
  587. w := httptest.NewRecorder()
  588. c, _ := CreateTestContext(w)
  589. c.IndentedJSON(http.StatusNoContent, H{"foo": "bar", "bar": "foo", "nested": H{"foo": "bar"}})
  590. assert.Equal(t, http.StatusNoContent, w.Code)
  591. assert.Empty(t, w.Body.String())
  592. assert.Equal(t, "application/json; charset=utf-8", w.Header().Get("Content-Type"))
  593. }
  594. // Tests that the response is serialized as Secure JSON
  595. // and Content-Type is set to application/json
  596. func TestContextRenderSecureJSON(t *testing.T) {
  597. w := httptest.NewRecorder()
  598. c, router := CreateTestContext(w)
  599. router.SecureJsonPrefix("&&&START&&&")
  600. c.SecureJSON(http.StatusCreated, []string{"foo", "bar"})
  601. assert.Equal(t, http.StatusCreated, w.Code)
  602. assert.Equal(t, "&&&START&&&[\"foo\",\"bar\"]", w.Body.String())
  603. assert.Equal(t, "application/json; charset=utf-8", w.Header().Get("Content-Type"))
  604. }
  605. // Tests that no Custom JSON is rendered if code is 204
  606. func TestContextRenderNoContentSecureJSON(t *testing.T) {
  607. w := httptest.NewRecorder()
  608. c, _ := CreateTestContext(w)
  609. c.SecureJSON(http.StatusNoContent, []string{"foo", "bar"})
  610. assert.Equal(t, http.StatusNoContent, w.Code)
  611. assert.Empty(t, w.Body.String())
  612. assert.Equal(t, "application/json; charset=utf-8", w.Header().Get("Content-Type"))
  613. }
  614. func TestContextRenderNoContentAsciiJSON(t *testing.T) {
  615. w := httptest.NewRecorder()
  616. c, _ := CreateTestContext(w)
  617. c.AsciiJSON(http.StatusNoContent, []string{"lang", "Go语言"})
  618. assert.Equal(t, http.StatusNoContent, w.Code)
  619. assert.Empty(t, w.Body.String())
  620. assert.Equal(t, "application/json", w.Header().Get("Content-Type"))
  621. }
  622. // Tests that the response executes the templates
  623. // and responds with Content-Type set to text/html
  624. func TestContextRenderHTML(t *testing.T) {
  625. w := httptest.NewRecorder()
  626. c, router := CreateTestContext(w)
  627. templ := template.Must(template.New("t").Parse(`Hello {{.name}}`))
  628. router.SetHTMLTemplate(templ)
  629. c.HTML(http.StatusCreated, "t", H{"name": "alexandernyquist"})
  630. assert.Equal(t, http.StatusCreated, w.Code)
  631. assert.Equal(t, "Hello alexandernyquist", w.Body.String())
  632. assert.Equal(t, "text/html; charset=utf-8", w.Header().Get("Content-Type"))
  633. }
  634. func TestContextRenderHTML2(t *testing.T) {
  635. w := httptest.NewRecorder()
  636. c, router := CreateTestContext(w)
  637. // print debug warning log when Engine.trees > 0
  638. router.addRoute("GET", "/", HandlersChain{func(_ *Context) {}})
  639. assert.Len(t, router.trees, 1)
  640. templ := template.Must(template.New("t").Parse(`Hello {{.name}}`))
  641. re := captureOutput(func() {
  642. SetMode(DebugMode)
  643. router.SetHTMLTemplate(templ)
  644. SetMode(TestMode)
  645. })
  646. assert.Equal(t, "[GIN-debug] [WARNING] Since SetHTMLTemplate() is NOT thread-safe. It should only be called\nat initialization. ie. before any route is registered or the router is listening in a socket:\n\n\trouter := gin.Default()\n\trouter.SetHTMLTemplate(template) // << good place\n\n", re)
  647. c.HTML(http.StatusCreated, "t", H{"name": "alexandernyquist"})
  648. assert.Equal(t, http.StatusCreated, w.Code)
  649. assert.Equal(t, "Hello alexandernyquist", w.Body.String())
  650. assert.Equal(t, "text/html; charset=utf-8", w.Header().Get("Content-Type"))
  651. }
  652. // Tests that no HTML is rendered if code is 204
  653. func TestContextRenderNoContentHTML(t *testing.T) {
  654. w := httptest.NewRecorder()
  655. c, router := CreateTestContext(w)
  656. templ := template.Must(template.New("t").Parse(`Hello {{.name}}`))
  657. router.SetHTMLTemplate(templ)
  658. c.HTML(http.StatusNoContent, "t", H{"name": "alexandernyquist"})
  659. assert.Equal(t, http.StatusNoContent, w.Code)
  660. assert.Empty(t, w.Body.String())
  661. assert.Equal(t, "text/html; charset=utf-8", w.Header().Get("Content-Type"))
  662. }
  663. // TestContextXML tests that the response is serialized as XML
  664. // and Content-Type is set to application/xml
  665. func TestContextRenderXML(t *testing.T) {
  666. w := httptest.NewRecorder()
  667. c, _ := CreateTestContext(w)
  668. c.XML(http.StatusCreated, H{"foo": "bar"})
  669. assert.Equal(t, http.StatusCreated, w.Code)
  670. assert.Equal(t, "<map><foo>bar</foo></map>", w.Body.String())
  671. assert.Equal(t, "application/xml; charset=utf-8", w.Header().Get("Content-Type"))
  672. }
  673. // Tests that no XML is rendered if code is 204
  674. func TestContextRenderNoContentXML(t *testing.T) {
  675. w := httptest.NewRecorder()
  676. c, _ := CreateTestContext(w)
  677. c.XML(http.StatusNoContent, H{"foo": "bar"})
  678. assert.Equal(t, http.StatusNoContent, w.Code)
  679. assert.Empty(t, w.Body.String())
  680. assert.Equal(t, "application/xml; charset=utf-8", w.Header().Get("Content-Type"))
  681. }
  682. // TestContextString tests that the response is returned
  683. // with Content-Type set to text/plain
  684. func TestContextRenderString(t *testing.T) {
  685. w := httptest.NewRecorder()
  686. c, _ := CreateTestContext(w)
  687. c.String(http.StatusCreated, "test %s %d", "string", 2)
  688. assert.Equal(t, http.StatusCreated, w.Code)
  689. assert.Equal(t, "test string 2", w.Body.String())
  690. assert.Equal(t, "text/plain; charset=utf-8", w.Header().Get("Content-Type"))
  691. }
  692. // Tests that no String is rendered if code is 204
  693. func TestContextRenderNoContentString(t *testing.T) {
  694. w := httptest.NewRecorder()
  695. c, _ := CreateTestContext(w)
  696. c.String(http.StatusNoContent, "test %s %d", "string", 2)
  697. assert.Equal(t, http.StatusNoContent, w.Code)
  698. assert.Empty(t, w.Body.String())
  699. assert.Equal(t, "text/plain; charset=utf-8", w.Header().Get("Content-Type"))
  700. }
  701. // TestContextString tests that the response is returned
  702. // with Content-Type set to text/html
  703. func TestContextRenderHTMLString(t *testing.T) {
  704. w := httptest.NewRecorder()
  705. c, _ := CreateTestContext(w)
  706. c.Header("Content-Type", "text/html; charset=utf-8")
  707. c.String(http.StatusCreated, "<html>%s %d</html>", "string", 3)
  708. assert.Equal(t, http.StatusCreated, w.Code)
  709. assert.Equal(t, "<html>string 3</html>", w.Body.String())
  710. assert.Equal(t, "text/html; charset=utf-8", w.Header().Get("Content-Type"))
  711. }
  712. // Tests that no HTML String is rendered if code is 204
  713. func TestContextRenderNoContentHTMLString(t *testing.T) {
  714. w := httptest.NewRecorder()
  715. c, _ := CreateTestContext(w)
  716. c.Header("Content-Type", "text/html; charset=utf-8")
  717. c.String(http.StatusNoContent, "<html>%s %d</html>", "string", 3)
  718. assert.Equal(t, http.StatusNoContent, w.Code)
  719. assert.Empty(t, w.Body.String())
  720. assert.Equal(t, "text/html; charset=utf-8", w.Header().Get("Content-Type"))
  721. }
  722. // TestContextData tests that the response can be written from `bytesting`
  723. // with specified MIME type
  724. func TestContextRenderData(t *testing.T) {
  725. w := httptest.NewRecorder()
  726. c, _ := CreateTestContext(w)
  727. c.Data(http.StatusCreated, "text/csv", []byte(`foo,bar`))
  728. assert.Equal(t, http.StatusCreated, w.Code)
  729. assert.Equal(t, "foo,bar", w.Body.String())
  730. assert.Equal(t, "text/csv", w.Header().Get("Content-Type"))
  731. }
  732. // Tests that no Custom Data is rendered if code is 204
  733. func TestContextRenderNoContentData(t *testing.T) {
  734. w := httptest.NewRecorder()
  735. c, _ := CreateTestContext(w)
  736. c.Data(http.StatusNoContent, "text/csv", []byte(`foo,bar`))
  737. assert.Equal(t, http.StatusNoContent, w.Code)
  738. assert.Empty(t, w.Body.String())
  739. assert.Equal(t, "text/csv", w.Header().Get("Content-Type"))
  740. }
  741. func TestContextRenderSSE(t *testing.T) {
  742. w := httptest.NewRecorder()
  743. c, _ := CreateTestContext(w)
  744. c.SSEvent("float", 1.5)
  745. c.Render(-1, sse.Event{
  746. Id: "123",
  747. Data: "text",
  748. })
  749. c.SSEvent("chat", H{
  750. "foo": "bar",
  751. "bar": "foo",
  752. })
  753. 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))
  754. }
  755. func TestContextRenderFile(t *testing.T) {
  756. w := httptest.NewRecorder()
  757. c, _ := CreateTestContext(w)
  758. c.Request, _ = http.NewRequest("GET", "/", nil)
  759. c.File("./gin.go")
  760. assert.Equal(t, http.StatusOK, w.Code)
  761. assert.Contains(t, w.Body.String(), "func New() *Engine {")
  762. assert.Equal(t, "text/plain; charset=utf-8", w.Header().Get("Content-Type"))
  763. }
  764. // TestContextRenderYAML tests that the response is serialized as YAML
  765. // and Content-Type is set to application/x-yaml
  766. func TestContextRenderYAML(t *testing.T) {
  767. w := httptest.NewRecorder()
  768. c, _ := CreateTestContext(w)
  769. c.YAML(http.StatusCreated, H{"foo": "bar"})
  770. assert.Equal(t, http.StatusCreated, w.Code)
  771. assert.Equal(t, "foo: bar\n", w.Body.String())
  772. assert.Equal(t, "application/x-yaml; charset=utf-8", w.Header().Get("Content-Type"))
  773. }
  774. // TestContextRenderProtoBuf tests that the response is serialized as ProtoBuf
  775. // and Content-Type is set to application/x-protobuf
  776. // and we just use the example protobuf to check if the response is correct
  777. func TestContextRenderProtoBuf(t *testing.T) {
  778. w := httptest.NewRecorder()
  779. c, _ := CreateTestContext(w)
  780. reps := []int64{int64(1), int64(2)}
  781. label := "test"
  782. data := &testdata.Test{
  783. Label: &label,
  784. Reps: reps,
  785. }
  786. c.ProtoBuf(http.StatusCreated, data)
  787. protoData, err := proto.Marshal(data)
  788. assert.NoError(t, err)
  789. assert.Equal(t, http.StatusCreated, w.Code)
  790. assert.Equal(t, string(protoData), w.Body.String())
  791. assert.Equal(t, "application/x-protobuf", w.Header().Get("Content-Type"))
  792. }
  793. func TestContextHeaders(t *testing.T) {
  794. c, _ := CreateTestContext(httptest.NewRecorder())
  795. c.Header("Content-Type", "text/plain")
  796. c.Header("X-Custom", "value")
  797. assert.Equal(t, "text/plain", c.Writer.Header().Get("Content-Type"))
  798. assert.Equal(t, "value", c.Writer.Header().Get("X-Custom"))
  799. c.Header("Content-Type", "text/html")
  800. c.Header("X-Custom", "")
  801. assert.Equal(t, "text/html", c.Writer.Header().Get("Content-Type"))
  802. _, exist := c.Writer.Header()["X-Custom"]
  803. assert.False(t, exist)
  804. }
  805. // TODO
  806. func TestContextRenderRedirectWithRelativePath(t *testing.T) {
  807. w := httptest.NewRecorder()
  808. c, _ := CreateTestContext(w)
  809. c.Request, _ = http.NewRequest("POST", "http://example.com", nil)
  810. assert.Panics(t, func() { c.Redirect(299, "/new_path") })
  811. assert.Panics(t, func() { c.Redirect(309, "/new_path") })
  812. c.Redirect(http.StatusMovedPermanently, "/path")
  813. c.Writer.WriteHeaderNow()
  814. assert.Equal(t, http.StatusMovedPermanently, w.Code)
  815. assert.Equal(t, "/path", w.Header().Get("Location"))
  816. }
  817. func TestContextRenderRedirectWithAbsolutePath(t *testing.T) {
  818. w := httptest.NewRecorder()
  819. c, _ := CreateTestContext(w)
  820. c.Request, _ = http.NewRequest("POST", "http://example.com", nil)
  821. c.Redirect(http.StatusFound, "http://google.com")
  822. c.Writer.WriteHeaderNow()
  823. assert.Equal(t, http.StatusFound, w.Code)
  824. assert.Equal(t, "http://google.com", w.Header().Get("Location"))
  825. }
  826. func TestContextRenderRedirectWith201(t *testing.T) {
  827. w := httptest.NewRecorder()
  828. c, _ := CreateTestContext(w)
  829. c.Request, _ = http.NewRequest("POST", "http://example.com", nil)
  830. c.Redirect(http.StatusCreated, "/resource")
  831. c.Writer.WriteHeaderNow()
  832. assert.Equal(t, http.StatusCreated, w.Code)
  833. assert.Equal(t, "/resource", w.Header().Get("Location"))
  834. }
  835. func TestContextRenderRedirectAll(t *testing.T) {
  836. c, _ := CreateTestContext(httptest.NewRecorder())
  837. c.Request, _ = http.NewRequest("POST", "http://example.com", nil)
  838. assert.Panics(t, func() { c.Redirect(http.StatusOK, "/resource") })
  839. assert.Panics(t, func() { c.Redirect(http.StatusAccepted, "/resource") })
  840. assert.Panics(t, func() { c.Redirect(299, "/resource") })
  841. assert.Panics(t, func() { c.Redirect(309, "/resource") })
  842. assert.NotPanics(t, func() { c.Redirect(http.StatusMultipleChoices, "/resource") })
  843. // todo(thinkerou): go1.6 not support StatusPermanentRedirect(308)
  844. // when we upgrade go version we can use http.StatusPermanentRedirect
  845. assert.NotPanics(t, func() { c.Redirect(308, "/resource") })
  846. }
  847. func TestContextNegotiationWithJSON(t *testing.T) {
  848. w := httptest.NewRecorder()
  849. c, _ := CreateTestContext(w)
  850. c.Request, _ = http.NewRequest("POST", "", nil)
  851. c.Negotiate(http.StatusOK, Negotiate{
  852. Offered: []string{MIMEJSON, MIMEXML},
  853. Data: H{"foo": "bar"},
  854. })
  855. assert.Equal(t, http.StatusOK, w.Code)
  856. assert.Equal(t, "{\"foo\":\"bar\"}", w.Body.String())
  857. assert.Equal(t, "application/json; charset=utf-8", w.Header().Get("Content-Type"))
  858. }
  859. func TestContextNegotiationWithXML(t *testing.T) {
  860. w := httptest.NewRecorder()
  861. c, _ := CreateTestContext(w)
  862. c.Request, _ = http.NewRequest("POST", "", nil)
  863. c.Negotiate(http.StatusOK, Negotiate{
  864. Offered: []string{MIMEXML, MIMEJSON},
  865. Data: H{"foo": "bar"},
  866. })
  867. assert.Equal(t, http.StatusOK, w.Code)
  868. assert.Equal(t, "<map><foo>bar</foo></map>", w.Body.String())
  869. assert.Equal(t, "application/xml; charset=utf-8", w.Header().Get("Content-Type"))
  870. }
  871. func TestContextNegotiationWithHTML(t *testing.T) {
  872. w := httptest.NewRecorder()
  873. c, router := CreateTestContext(w)
  874. c.Request, _ = http.NewRequest("POST", "", nil)
  875. templ := template.Must(template.New("t").Parse(`Hello {{.name}}`))
  876. router.SetHTMLTemplate(templ)
  877. c.Negotiate(http.StatusOK, Negotiate{
  878. Offered: []string{MIMEHTML},
  879. Data: H{"name": "gin"},
  880. HTMLName: "t",
  881. })
  882. assert.Equal(t, http.StatusOK, w.Code)
  883. assert.Equal(t, "Hello gin", w.Body.String())
  884. assert.Equal(t, "text/html; charset=utf-8", w.Header().Get("Content-Type"))
  885. }
  886. func TestContextNegotiationNotSupport(t *testing.T) {
  887. w := httptest.NewRecorder()
  888. c, _ := CreateTestContext(w)
  889. c.Request, _ = http.NewRequest("POST", "", nil)
  890. c.Negotiate(http.StatusOK, Negotiate{
  891. Offered: []string{MIMEPOSTForm},
  892. })
  893. assert.Equal(t, http.StatusNotAcceptable, w.Code)
  894. assert.Equal(t, c.index, abortIndex)
  895. assert.True(t, c.IsAborted())
  896. }
  897. func TestContextNegotiationFormat(t *testing.T) {
  898. c, _ := CreateTestContext(httptest.NewRecorder())
  899. c.Request, _ = http.NewRequest("POST", "", nil)
  900. assert.Panics(t, func() { c.NegotiateFormat() })
  901. assert.Equal(t, MIMEJSON, c.NegotiateFormat(MIMEJSON, MIMEXML))
  902. assert.Equal(t, MIMEHTML, c.NegotiateFormat(MIMEHTML, MIMEJSON))
  903. }
  904. func TestContextNegotiationFormatWithAccept(t *testing.T) {
  905. c, _ := CreateTestContext(httptest.NewRecorder())
  906. c.Request, _ = http.NewRequest("POST", "/", nil)
  907. c.Request.Header.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
  908. assert.Equal(t, MIMEXML, c.NegotiateFormat(MIMEJSON, MIMEXML))
  909. assert.Equal(t, MIMEHTML, c.NegotiateFormat(MIMEXML, MIMEHTML))
  910. assert.Empty(t, c.NegotiateFormat(MIMEJSON))
  911. }
  912. func TestContextNegotiationFormatCustom(t *testing.T) {
  913. c, _ := CreateTestContext(httptest.NewRecorder())
  914. c.Request, _ = http.NewRequest("POST", "/", nil)
  915. c.Request.Header.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
  916. c.Accepted = nil
  917. c.SetAccepted(MIMEJSON, MIMEXML)
  918. assert.Equal(t, MIMEJSON, c.NegotiateFormat(MIMEJSON, MIMEXML))
  919. assert.Equal(t, MIMEXML, c.NegotiateFormat(MIMEXML, MIMEHTML))
  920. assert.Equal(t, MIMEJSON, c.NegotiateFormat(MIMEJSON))
  921. }
  922. func TestContextIsAborted(t *testing.T) {
  923. c, _ := CreateTestContext(httptest.NewRecorder())
  924. assert.False(t, c.IsAborted())
  925. c.Abort()
  926. assert.True(t, c.IsAborted())
  927. c.Next()
  928. assert.True(t, c.IsAborted())
  929. c.index++
  930. assert.True(t, c.IsAborted())
  931. }
  932. // TestContextData tests that the response can be written from `bytesting`
  933. // with specified MIME type
  934. func TestContextAbortWithStatus(t *testing.T) {
  935. w := httptest.NewRecorder()
  936. c, _ := CreateTestContext(w)
  937. c.index = 4
  938. c.AbortWithStatus(http.StatusUnauthorized)
  939. assert.Equal(t, abortIndex, c.index)
  940. assert.Equal(t, http.StatusUnauthorized, c.Writer.Status())
  941. assert.Equal(t, http.StatusUnauthorized, w.Code)
  942. assert.True(t, c.IsAborted())
  943. }
  944. type testJSONAbortMsg struct {
  945. Foo string `json:"foo"`
  946. Bar string `json:"bar"`
  947. }
  948. func TestContextAbortWithStatusJSON(t *testing.T) {
  949. w := httptest.NewRecorder()
  950. c, _ := CreateTestContext(w)
  951. c.index = 4
  952. in := new(testJSONAbortMsg)
  953. in.Bar = "barValue"
  954. in.Foo = "fooValue"
  955. c.AbortWithStatusJSON(http.StatusUnsupportedMediaType, in)
  956. assert.Equal(t, abortIndex, c.index)
  957. assert.Equal(t, http.StatusUnsupportedMediaType, c.Writer.Status())
  958. assert.Equal(t, http.StatusUnsupportedMediaType, w.Code)
  959. assert.True(t, c.IsAborted())
  960. contentType := w.Header().Get("Content-Type")
  961. assert.Equal(t, "application/json; charset=utf-8", contentType)
  962. buf := new(bytes.Buffer)
  963. buf.ReadFrom(w.Body)
  964. jsonStringBody := buf.String()
  965. assert.Equal(t, fmt.Sprint(`{"foo":"fooValue","bar":"barValue"}`), jsonStringBody)
  966. }
  967. func TestContextError(t *testing.T) {
  968. c, _ := CreateTestContext(httptest.NewRecorder())
  969. assert.Empty(t, c.Errors)
  970. c.Error(errors.New("first error"))
  971. assert.Len(t, c.Errors, 1)
  972. assert.Equal(t, "Error #01: first error\n", c.Errors.String())
  973. c.Error(&Error{
  974. Err: errors.New("second error"),
  975. Meta: "some data 2",
  976. Type: ErrorTypePublic,
  977. })
  978. assert.Len(t, c.Errors, 2)
  979. assert.Equal(t, errors.New("first error"), c.Errors[0].Err)
  980. assert.Nil(t, c.Errors[0].Meta)
  981. assert.Equal(t, ErrorTypePrivate, c.Errors[0].Type)
  982. assert.Equal(t, errors.New("second error"), c.Errors[1].Err)
  983. assert.Equal(t, "some data 2", c.Errors[1].Meta)
  984. assert.Equal(t, ErrorTypePublic, c.Errors[1].Type)
  985. assert.Equal(t, c.Errors.Last(), c.Errors[1])
  986. defer func() {
  987. if recover() == nil {
  988. t.Error("didn't panic")
  989. }
  990. }()
  991. c.Error(nil)
  992. }
  993. func TestContextTypedError(t *testing.T) {
  994. c, _ := CreateTestContext(httptest.NewRecorder())
  995. c.Error(errors.New("externo 0")).SetType(ErrorTypePublic)
  996. c.Error(errors.New("interno 0")).SetType(ErrorTypePrivate)
  997. for _, err := range c.Errors.ByType(ErrorTypePublic) {
  998. assert.Equal(t, ErrorTypePublic, err.Type)
  999. }
  1000. for _, err := range c.Errors.ByType(ErrorTypePrivate) {
  1001. assert.Equal(t, ErrorTypePrivate, err.Type)
  1002. }
  1003. assert.Equal(t, []string{"externo 0", "interno 0"}, c.Errors.Errors())
  1004. }
  1005. func TestContextAbortWithError(t *testing.T) {
  1006. w := httptest.NewRecorder()
  1007. c, _ := CreateTestContext(w)
  1008. c.AbortWithError(http.StatusUnauthorized, errors.New("bad input")).SetMeta("some input")
  1009. assert.Equal(t, http.StatusUnauthorized, w.Code)
  1010. assert.Equal(t, abortIndex, c.index)
  1011. assert.True(t, c.IsAborted())
  1012. }
  1013. func TestContextClientIP(t *testing.T) {
  1014. c, _ := CreateTestContext(httptest.NewRecorder())
  1015. c.Request, _ = http.NewRequest("POST", "/", nil)
  1016. c.Request.Header.Set("X-Real-IP", " 10.10.10.10 ")
  1017. c.Request.Header.Set("X-Forwarded-For", " 20.20.20.20, 30.30.30.30")
  1018. c.Request.Header.Set("X-Appengine-Remote-Addr", "50.50.50.50")
  1019. c.Request.RemoteAddr = " 40.40.40.40:42123 "
  1020. assert.Equal(t, "20.20.20.20", c.ClientIP())
  1021. c.Request.Header.Del("X-Forwarded-For")
  1022. assert.Equal(t, "10.10.10.10", c.ClientIP())
  1023. c.Request.Header.Set("X-Forwarded-For", "30.30.30.30 ")
  1024. assert.Equal(t, "30.30.30.30", c.ClientIP())
  1025. c.Request.Header.Del("X-Forwarded-For")
  1026. c.Request.Header.Del("X-Real-IP")
  1027. c.engine.AppEngine = true
  1028. assert.Equal(t, "50.50.50.50", c.ClientIP())
  1029. c.Request.Header.Del("X-Appengine-Remote-Addr")
  1030. assert.Equal(t, "40.40.40.40", c.ClientIP())
  1031. // no port
  1032. c.Request.RemoteAddr = "50.50.50.50"
  1033. assert.Empty(t, c.ClientIP())
  1034. }
  1035. func TestContextContentType(t *testing.T) {
  1036. c, _ := CreateTestContext(httptest.NewRecorder())
  1037. c.Request, _ = http.NewRequest("POST", "/", nil)
  1038. c.Request.Header.Set("Content-Type", "application/json; charset=utf-8")
  1039. assert.Equal(t, "application/json", c.ContentType())
  1040. }
  1041. func TestContextAutoBindJSON(t *testing.T) {
  1042. c, _ := CreateTestContext(httptest.NewRecorder())
  1043. c.Request, _ = http.NewRequest("POST", "/", bytes.NewBufferString("{\"foo\":\"bar\", \"bar\":\"foo\"}"))
  1044. c.Request.Header.Add("Content-Type", MIMEJSON)
  1045. var obj struct {
  1046. Foo string `json:"foo"`
  1047. Bar string `json:"bar"`
  1048. }
  1049. assert.NoError(t, c.Bind(&obj))
  1050. assert.Equal(t, "foo", obj.Bar)
  1051. assert.Equal(t, "bar", obj.Foo)
  1052. assert.Empty(t, c.Errors)
  1053. }
  1054. func TestContextBindWithJSON(t *testing.T) {
  1055. w := httptest.NewRecorder()
  1056. c, _ := CreateTestContext(w)
  1057. c.Request, _ = http.NewRequest("POST", "/", bytes.NewBufferString("{\"foo\":\"bar\", \"bar\":\"foo\"}"))
  1058. c.Request.Header.Add("Content-Type", MIMEXML) // set fake content-type
  1059. var obj struct {
  1060. Foo string `json:"foo"`
  1061. Bar string `json:"bar"`
  1062. }
  1063. assert.NoError(t, c.BindJSON(&obj))
  1064. assert.Equal(t, "foo", obj.Bar)
  1065. assert.Equal(t, "bar", obj.Foo)
  1066. assert.Equal(t, 0, w.Body.Len())
  1067. }
  1068. func TestContextBindWithXML(t *testing.T) {
  1069. w := httptest.NewRecorder()
  1070. c, _ := CreateTestContext(w)
  1071. c.Request, _ = http.NewRequest("POST", "/", bytes.NewBufferString(`<?xml version="1.0" encoding="UTF-8"?>
  1072. <root>
  1073. <foo>FOO</foo>
  1074. <bar>BAR</bar>
  1075. </root>`))
  1076. c.Request.Header.Add("Content-Type", MIMEXML) // set fake content-type
  1077. var obj struct {
  1078. Foo string `xml:"foo"`
  1079. Bar string `xml:"bar"`
  1080. }
  1081. assert.NoError(t, c.BindXML(&obj))
  1082. assert.Equal(t, "FOO", obj.Foo)
  1083. assert.Equal(t, "BAR", obj.Bar)
  1084. assert.Equal(t, 0, w.Body.Len())
  1085. }
  1086. func TestContextBindWithQuery(t *testing.T) {
  1087. w := httptest.NewRecorder()
  1088. c, _ := CreateTestContext(w)
  1089. c.Request, _ = http.NewRequest("POST", "/?foo=bar&bar=foo", bytes.NewBufferString("foo=unused"))
  1090. var obj struct {
  1091. Foo string `form:"foo"`
  1092. Bar string `form:"bar"`
  1093. }
  1094. assert.NoError(t, c.BindQuery(&obj))
  1095. assert.Equal(t, "foo", obj.Bar)
  1096. assert.Equal(t, "bar", obj.Foo)
  1097. assert.Equal(t, 0, w.Body.Len())
  1098. }
  1099. func TestContextBadAutoBind(t *testing.T) {
  1100. w := httptest.NewRecorder()
  1101. c, _ := CreateTestContext(w)
  1102. c.Request, _ = http.NewRequest("POST", "http://example.com", bytes.NewBufferString("\"foo\":\"bar\", \"bar\":\"foo\"}"))
  1103. c.Request.Header.Add("Content-Type", MIMEJSON)
  1104. var obj struct {
  1105. Foo string `json:"foo"`
  1106. Bar string `json:"bar"`
  1107. }
  1108. assert.False(t, c.IsAborted())
  1109. assert.Error(t, c.Bind(&obj))
  1110. c.Writer.WriteHeaderNow()
  1111. assert.Empty(t, obj.Bar)
  1112. assert.Empty(t, obj.Foo)
  1113. assert.Equal(t, http.StatusBadRequest, w.Code)
  1114. assert.True(t, c.IsAborted())
  1115. }
  1116. func TestContextAutoShouldBindJSON(t *testing.T) {
  1117. c, _ := CreateTestContext(httptest.NewRecorder())
  1118. c.Request, _ = http.NewRequest("POST", "/", bytes.NewBufferString("{\"foo\":\"bar\", \"bar\":\"foo\"}"))
  1119. c.Request.Header.Add("Content-Type", MIMEJSON)
  1120. var obj struct {
  1121. Foo string `json:"foo"`
  1122. Bar string `json:"bar"`
  1123. }
  1124. assert.NoError(t, c.ShouldBind(&obj))
  1125. assert.Equal(t, "foo", obj.Bar)
  1126. assert.Equal(t, "bar", obj.Foo)
  1127. assert.Empty(t, c.Errors)
  1128. }
  1129. func TestContextShouldBindWithJSON(t *testing.T) {
  1130. w := httptest.NewRecorder()
  1131. c, _ := CreateTestContext(w)
  1132. c.Request, _ = http.NewRequest("POST", "/", bytes.NewBufferString("{\"foo\":\"bar\", \"bar\":\"foo\"}"))
  1133. c.Request.Header.Add("Content-Type", MIMEXML) // set fake content-type
  1134. var obj struct {
  1135. Foo string `json:"foo"`
  1136. Bar string `json:"bar"`
  1137. }
  1138. assert.NoError(t, c.ShouldBindJSON(&obj))
  1139. assert.Equal(t, "foo", obj.Bar)
  1140. assert.Equal(t, "bar", obj.Foo)
  1141. assert.Equal(t, 0, w.Body.Len())
  1142. }
  1143. func TestContextShouldBindWithXML(t *testing.T) {
  1144. w := httptest.NewRecorder()
  1145. c, _ := CreateTestContext(w)
  1146. c.Request, _ = http.NewRequest("POST", "/", bytes.NewBufferString(`<?xml version="1.0" encoding="UTF-8"?>
  1147. <root>
  1148. <foo>FOO</foo>
  1149. <bar>BAR</bar>
  1150. </root>`))
  1151. c.Request.Header.Add("Content-Type", MIMEXML) // set fake content-type
  1152. var obj struct {
  1153. Foo string `xml:"foo"`
  1154. Bar string `xml:"bar"`
  1155. }
  1156. assert.NoError(t, c.ShouldBindXML(&obj))
  1157. assert.Equal(t, "FOO", obj.Foo)
  1158. assert.Equal(t, "BAR", obj.Bar)
  1159. assert.Equal(t, 0, w.Body.Len())
  1160. }
  1161. func TestContextShouldBindWithQuery(t *testing.T) {
  1162. w := httptest.NewRecorder()
  1163. c, _ := CreateTestContext(w)
  1164. c.Request, _ = http.NewRequest("POST", "/?foo=bar&bar=foo", bytes.NewBufferString("foo=unused"))
  1165. var obj struct {
  1166. Foo string `form:"foo"`
  1167. Bar string `form:"bar"`
  1168. }
  1169. assert.NoError(t, c.ShouldBindQuery(&obj))
  1170. assert.Equal(t, "foo", obj.Bar)
  1171. assert.Equal(t, "bar", obj.Foo)
  1172. assert.Equal(t, 0, w.Body.Len())
  1173. }
  1174. func TestContextBadAutoShouldBind(t *testing.T) {
  1175. w := httptest.NewRecorder()
  1176. c, _ := CreateTestContext(w)
  1177. c.Request, _ = http.NewRequest("POST", "http://example.com", bytes.NewBufferString("\"foo\":\"bar\", \"bar\":\"foo\"}"))
  1178. c.Request.Header.Add("Content-Type", MIMEJSON)
  1179. var obj struct {
  1180. Foo string `json:"foo"`
  1181. Bar string `json:"bar"`
  1182. }
  1183. assert.False(t, c.IsAborted())
  1184. assert.Error(t, c.ShouldBind(&obj))
  1185. assert.Empty(t, obj.Bar)
  1186. assert.Empty(t, obj.Foo)
  1187. assert.False(t, c.IsAborted())
  1188. }
  1189. func TestContextShouldBindBodyWith(t *testing.T) {
  1190. type typeA struct {
  1191. Foo string `json:"foo" xml:"foo" binding:"required"`
  1192. }
  1193. type typeB struct {
  1194. Bar string `json:"bar" xml:"bar" binding:"required"`
  1195. }
  1196. for _, tt := range []struct {
  1197. name string
  1198. bindingA, bindingB binding.BindingBody
  1199. bodyA, bodyB string
  1200. }{
  1201. {
  1202. name: "JSON & JSON",
  1203. bindingA: binding.JSON,
  1204. bindingB: binding.JSON,
  1205. bodyA: `{"foo":"FOO"}`,
  1206. bodyB: `{"bar":"BAR"}`,
  1207. },
  1208. {
  1209. name: "JSON & XML",
  1210. bindingA: binding.JSON,
  1211. bindingB: binding.XML,
  1212. bodyA: `{"foo":"FOO"}`,
  1213. bodyB: `<?xml version="1.0" encoding="UTF-8"?>
  1214. <root>
  1215. <bar>BAR</bar>
  1216. </root>`,
  1217. },
  1218. {
  1219. name: "XML & XML",
  1220. bindingA: binding.XML,
  1221. bindingB: binding.XML,
  1222. bodyA: `<?xml version="1.0" encoding="UTF-8"?>
  1223. <root>
  1224. <foo>FOO</foo>
  1225. </root>`,
  1226. bodyB: `<?xml version="1.0" encoding="UTF-8"?>
  1227. <root>
  1228. <bar>BAR</bar>
  1229. </root>`,
  1230. },
  1231. } {
  1232. t.Logf("testing: %s", tt.name)
  1233. // bodyA to typeA and typeB
  1234. {
  1235. w := httptest.NewRecorder()
  1236. c, _ := CreateTestContext(w)
  1237. c.Request, _ = http.NewRequest(
  1238. "POST", "http://example.com", bytes.NewBufferString(tt.bodyA),
  1239. )
  1240. // When it binds to typeA and typeB, it finds the body is
  1241. // not typeB but typeA.
  1242. objA := typeA{}
  1243. assert.NoError(t, c.ShouldBindBodyWith(&objA, tt.bindingA))
  1244. assert.Equal(t, typeA{"FOO"}, objA)
  1245. objB := typeB{}
  1246. assert.Error(t, c.ShouldBindBodyWith(&objB, tt.bindingB))
  1247. assert.NotEqual(t, typeB{"BAR"}, objB)
  1248. }
  1249. // bodyB to typeA and typeB
  1250. {
  1251. // When it binds to typeA and typeB, it finds the body is
  1252. // not typeA but typeB.
  1253. w := httptest.NewRecorder()
  1254. c, _ := CreateTestContext(w)
  1255. c.Request, _ = http.NewRequest(
  1256. "POST", "http://example.com", bytes.NewBufferString(tt.bodyB),
  1257. )
  1258. objA := typeA{}
  1259. assert.Error(t, c.ShouldBindBodyWith(&objA, tt.bindingA))
  1260. assert.NotEqual(t, typeA{"FOO"}, objA)
  1261. objB := typeB{}
  1262. assert.NoError(t, c.ShouldBindBodyWith(&objB, tt.bindingB))
  1263. assert.Equal(t, typeB{"BAR"}, objB)
  1264. }
  1265. }
  1266. }
  1267. func TestContextGolangContext(t *testing.T) {
  1268. c, _ := CreateTestContext(httptest.NewRecorder())
  1269. c.Request, _ = http.NewRequest("POST", "/", bytes.NewBufferString("{\"foo\":\"bar\", \"bar\":\"foo\"}"))
  1270. assert.NoError(t, c.Err())
  1271. assert.Nil(t, c.Done())
  1272. ti, ok := c.Deadline()
  1273. assert.Equal(t, ti, time.Time{})
  1274. assert.False(t, ok)
  1275. assert.Equal(t, c.Value(0), c.Request)
  1276. assert.Nil(t, c.Value("foo"))
  1277. c.Set("foo", "bar")
  1278. assert.Equal(t, "bar", c.Value("foo"))
  1279. assert.Nil(t, c.Value(1))
  1280. }
  1281. func TestWebsocketsRequired(t *testing.T) {
  1282. // Example request from spec: https://tools.ietf.org/html/rfc6455#section-1.2
  1283. c, _ := CreateTestContext(httptest.NewRecorder())
  1284. c.Request, _ = http.NewRequest("GET", "/chat", nil)
  1285. c.Request.Header.Set("Host", "server.example.com")
  1286. c.Request.Header.Set("Upgrade", "websocket")
  1287. c.Request.Header.Set("Connection", "Upgrade")
  1288. c.Request.Header.Set("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==")
  1289. c.Request.Header.Set("Origin", "http://example.com")
  1290. c.Request.Header.Set("Sec-WebSocket-Protocol", "chat, superchat")
  1291. c.Request.Header.Set("Sec-WebSocket-Version", "13")
  1292. assert.True(t, c.IsWebsocket())
  1293. // Normal request, no websocket required.
  1294. c, _ = CreateTestContext(httptest.NewRecorder())
  1295. c.Request, _ = http.NewRequest("GET", "/chat", nil)
  1296. c.Request.Header.Set("Host", "server.example.com")
  1297. assert.False(t, c.IsWebsocket())
  1298. }
  1299. func TestGetRequestHeaderValue(t *testing.T) {
  1300. c, _ := CreateTestContext(httptest.NewRecorder())
  1301. c.Request, _ = http.NewRequest("GET", "/chat", nil)
  1302. c.Request.Header.Set("Gin-Version", "1.0.0")
  1303. assert.Equal(t, "1.0.0", c.GetHeader("Gin-Version"))
  1304. assert.Empty(t, c.GetHeader("Connection"))
  1305. }
  1306. func TestContextGetRawData(t *testing.T) {
  1307. c, _ := CreateTestContext(httptest.NewRecorder())
  1308. body := bytes.NewBufferString("Fetch binary post data")
  1309. c.Request, _ = http.NewRequest("POST", "/", body)
  1310. c.Request.Header.Add("Content-Type", MIMEPOSTForm)
  1311. data, err := c.GetRawData()
  1312. assert.Nil(t, err)
  1313. assert.Equal(t, "Fetch binary post data", string(data))
  1314. }
  1315. func TestContextRenderDataFromReader(t *testing.T) {
  1316. w := httptest.NewRecorder()
  1317. c, _ := CreateTestContext(w)
  1318. body := "#!PNG some raw data"
  1319. reader := strings.NewReader(body)
  1320. contentLength := int64(len(body))
  1321. contentType := "image/png"
  1322. extraHeaders := map[string]string{"Content-Disposition": `attachment; filename="gopher.png"`}
  1323. c.DataFromReader(http.StatusOK, contentLength, contentType, reader, extraHeaders)
  1324. assert.Equal(t, http.StatusOK, w.Code)
  1325. assert.Equal(t, body, w.Body.String())
  1326. assert.Equal(t, contentType, w.Header().Get("Content-Type"))
  1327. assert.Equal(t, fmt.Sprintf("%d", contentLength), w.Header().Get("Content-Length"))
  1328. assert.Equal(t, extraHeaders["Content-Disposition"], w.Header().Get("Content-Disposition"))
  1329. }
  1330. type TestResponseRecorder struct {
  1331. *httptest.ResponseRecorder
  1332. closeChannel chan bool
  1333. }
  1334. func (r *TestResponseRecorder) CloseNotify() <-chan bool {
  1335. return r.closeChannel
  1336. }
  1337. func (r *TestResponseRecorder) closeClient() {
  1338. r.closeChannel <- true
  1339. }
  1340. func CreateTestResponseRecorder() *TestResponseRecorder {
  1341. return &TestResponseRecorder{
  1342. httptest.NewRecorder(),
  1343. make(chan bool, 1),
  1344. }
  1345. }
  1346. func TestContextStream(t *testing.T) {
  1347. w := CreateTestResponseRecorder()
  1348. c, _ := CreateTestContext(w)
  1349. stopStream := true
  1350. c.Stream(func(w io.Writer) bool {
  1351. defer func() {
  1352. stopStream = false
  1353. }()
  1354. w.Write([]byte("test"))
  1355. return stopStream
  1356. })
  1357. assert.Equal(t, "testtest", w.Body.String())
  1358. }
  1359. func TestContextStreamWithClientGone(t *testing.T) {
  1360. w := CreateTestResponseRecorder()
  1361. c, _ := CreateTestContext(w)
  1362. c.Stream(func(writer io.Writer) bool {
  1363. defer func() {
  1364. w.closeClient()
  1365. }()
  1366. writer.Write([]byte("test"))
  1367. return true
  1368. })
  1369. assert.Equal(t, "test", w.Body.String())
  1370. }