context_test.go 45 KB

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