context_test.go 41 KB

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