context_test.go 54 KB

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