context_test.go 52 KB

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