context_test.go 47 KB

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