context_test.go 48 KB

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