context_test.go 40 KB

1234567891011121314151617181920212223242526272829303132333435363738394041424344454647484950515253545556575859606162636465666768697071727374757677787980818283848586878889909192939495969798991001011021031041051061071081091101111121131141151161171181191201211221231241251261271281291301311321331341351361371381391401411421431441451461471481491501511521531541551561571581591601611621631641651661671681691701711721731741751761771781791801811821831841851861871881891901911921931941951961971981992002012022032042052062072082092102112122132142152162172182192202212222232242252262272282292302312322332342352362372382392402412422432442452462472482492502512522532542552562572582592602612622632642652662672682692702712722732742752762772782792802812822832842852862872882892902912922932942952962972982993003013023033043053063073083093103113123133143153163173183193203213223233243253263273283293303313323333343353363373383393403413423433443453463473483493503513523533543553563573583593603613623633643653663673683693703713723733743753763773783793803813823833843853863873883893903913923933943953963973983994004014024034044054064074084094104114124134144154164174184194204214224234244254264274284294304314324334344354364374384394404414424434444454464474484494504514524534544554564574584594604614624634644654664674684694704714724734744754764774784794804814824834844854864874884894904914924934944954964974984995005015025035045055065075085095105115125135145155165175185195205215225235245255265275285295305315325335345355365375385395405415425435445455465475485495505515525535545555565575585595605615625635645655665675685695705715725735745755765775785795805815825835845855865875885895905915925935945955965975985996006016026036046056066076086096106116126136146156166176186196206216226236246256266276286296306316326336346356366376386396406416426436446456466476486496506516526536546556566576586596606616626636646656666676686696706716726736746756766776786796806816826836846856866876886896906916926936946956966976986997007017027037047057067077087097107117127137147157167177187197207217227237247257267277287297307317327337347357367377387397407417427437447457467477487497507517527537547557567577587597607617627637647657667677687697707717727737747757767777787797807817827837847857867877887897907917927937947957967977987998008018028038048058068078088098108118128138148158168178188198208218228238248258268278288298308318328338348358368378388398408418428438448458468478488498508518528538548558568578588598608618628638648658668678688698708718728738748758768778788798808818828838848858868878888898908918928938948958968978988999009019029039049059069079089099109119129139149159169179189199209219229239249259269279289299309319329339349359369379389399409419429439449459469479489499509519529539549559569579589599609619629639649659669679689699709719729739749759769779789799809819829839849859869879889899909919929939949959969979989991000100110021003100410051006100710081009101010111012101310141015101610171018101910201021102210231024102510261027102810291030103110321033103410351036103710381039104010411042104310441045104610471048104910501051105210531054105510561057105810591060106110621063106410651066106710681069107010711072107310741075107610771078107910801081108210831084108510861087108810891090109110921093109410951096109710981099110011011102110311041105110611071108110911101111111211131114111511161117111811191120112111221123112411251126112711281129113011311132113311341135113611371138113911401141114211431144114511461147114811491150115111521153115411551156115711581159116011611162116311641165116611671168116911701171117211731174117511761177117811791180118111821183118411851186118711881189119011911192119311941195119611971198119912001201120212031204120512061207120812091210121112121213121412151216121712181219122012211222122312241225122612271228122912301231123212331234123512361237123812391240124112421243124412451246124712481249125012511252125312541255125612571258125912601261126212631264126512661267126812691270127112721273127412751276127712781279128012811282128312841285128612871288128912901291129212931294129512961297129812991300130113021303130413051306130713081309131013111312131313141315131613171318131913201321132213231324132513261327132813291330133113321333133413351336133713381339134013411342134313441345134613471348134913501351135213531354
  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, value, "bar")
  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, c.MustGet("foo"), "bar")
  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.Equal(t, true, 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, value, "bar")
  284. assert.Equal(t, c.DefaultQuery("foo", "none"), "bar")
  285. assert.Equal(t, c.Query("foo"), "bar")
  286. value, ok = c.GetQuery("page")
  287. assert.True(t, ok)
  288. assert.Equal(t, value, "10")
  289. assert.Equal(t, c.DefaultQuery("page", "0"), "10")
  290. assert.Equal(t, c.Query("page"), "10")
  291. value, ok = c.GetQuery("id")
  292. assert.True(t, ok)
  293. assert.Empty(t, value)
  294. assert.Equal(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, c.DefaultQuery("NoKey", "nada"), "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, c.DefaultPostForm("foo", "none"), "bar")
  313. assert.Equal(t, c.PostForm("foo"), "bar")
  314. assert.Empty(t, c.Query("foo"))
  315. value, ok := c.GetPostForm("page")
  316. assert.True(t, ok)
  317. assert.Equal(t, value, "11")
  318. assert.Equal(t, c.DefaultPostForm("page", "0"), "11")
  319. assert.Equal(t, c.PostForm("page"), "11")
  320. assert.Equal(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.Equal(t, c.DefaultPostForm("both", "nothing"), "")
  326. assert.Equal(t, c.Query("both"), "GET")
  327. value, ok = c.GetQuery("id")
  328. assert.True(t, ok)
  329. assert.Equal(t, value, "main")
  330. assert.Equal(t, c.DefaultPostForm("id", "000"), "000")
  331. assert.Equal(t, c.Query("id"), "main")
  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, c.DefaultPostForm("NoKey", "nada"), "nada")
  340. assert.Equal(t, c.DefaultQuery("NoKey", "nothing"), "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, obj.Foo, "bar")
  352. assert.Equal(t, obj.ID, "main")
  353. assert.Equal(t, obj.Page, 11)
  354. assert.Equal(t, obj.Both, "")
  355. assert.Equal(t, obj.Array, []string{"first", "second"})
  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, obj.Foo, "bar")
  385. assert.Equal(t, obj.Bar, "10")
  386. assert.Equal(t, obj.BarAsInt, 10)
  387. assert.Equal(t, obj.Array, []string{"first", "second"})
  388. assert.Equal(t, obj.ID, "")
  389. assert.Equal(t, obj.TimeLocal.Format("02/01/2006 15:04"), "31/12/2016 14:55")
  390. assert.Equal(t, obj.TimeLocal.Location(), time.Local)
  391. assert.Equal(t, obj.TimeUTC.Format("02/01/2006 15:04"), "31/12/2016 14:55")
  392. assert.Equal(t, obj.TimeUTC.Location(), time.UTC)
  393. loc, _ := time.LoadLocation("Asia/Tokyo")
  394. assert.Equal(t, obj.TimeLocation.Format("02/01/2006 15:04"), "31/12/2016 14:55")
  395. assert.Equal(t, obj.TimeLocation.Location(), loc)
  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, c.DefaultQuery("id", "nothing"), "nothing")
  402. value, ok = c.GetPostForm("foo")
  403. assert.True(t, ok)
  404. assert.Equal(t, value, "bar")
  405. assert.Equal(t, c.PostForm("foo"), "bar")
  406. value, ok = c.GetPostForm("array")
  407. assert.True(t, ok)
  408. assert.Equal(t, value, "first")
  409. assert.Equal(t, c.PostForm("array"), "first")
  410. assert.Equal(t, c.DefaultPostForm("bar", "nothing"), "10")
  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, c.DefaultPostForm("nokey", "nothing"), "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, c.Writer.Header().Get("Set-Cookie"), "user=gin; Path=/; Domain=localhost; Max-Age=1; HttpOnly; Secure")
  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, c.Writer.Header().Get("Set-Cookie"), "user=gin; Path=/; Domain=localhost; Max-Age=1; HttpOnly; Secure")
  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, cookie, "gin")
  449. _, err := c.Cookie("nokey")
  450. assert.Error(t, err)
  451. }
  452. func TestContextBodyAllowedForStatus(t *testing.T) {
  453. assert.Equal(t, false, bodyAllowedForStatus(102))
  454. assert.Equal(t, false, bodyAllowedForStatus(204))
  455. assert.Equal(t, false, bodyAllowedForStatus(304))
  456. assert.Equal(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.Equal(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.Equal(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, w.Code, 201)
  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.Equal(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, w.Code, 201)
  541. assert.Equal(t, w.Body.String(), "&&&START&&&[\"foo\",\"bar\"]")
  542. assert.Equal(t, w.HeaderMap.Get("Content-Type"), "application/json; charset=utf-8")
  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.Equal(t, "", w.Body.String())
  551. assert.Equal(t, w.HeaderMap.Get("Content-Type"), "application/json; charset=utf-8")
  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, w.Code, 201)
  562. assert.Equal(t, w.Body.String(), "Hello alexandernyquist")
  563. assert.Equal(t, w.HeaderMap.Get("Content-Type"), "text/html; charset=utf-8")
  564. }
  565. // Tests that no HTML is rendered if code is 204
  566. func TestContextRenderNoContentHTML(t *testing.T) {
  567. w := httptest.NewRecorder()
  568. c, router := CreateTestContext(w)
  569. templ := template.Must(template.New("t").Parse(`Hello {{.name}}`))
  570. router.SetHTMLTemplate(templ)
  571. c.HTML(204, "t", H{"name": "alexandernyquist"})
  572. assert.Equal(t, 204, w.Code)
  573. assert.Equal(t, "", w.Body.String())
  574. assert.Equal(t, w.HeaderMap.Get("Content-Type"), "text/html; charset=utf-8")
  575. }
  576. // TestContextXML tests that the response is serialized as XML
  577. // and Content-Type is set to application/xml
  578. func TestContextRenderXML(t *testing.T) {
  579. w := httptest.NewRecorder()
  580. c, _ := CreateTestContext(w)
  581. c.XML(201, H{"foo": "bar"})
  582. assert.Equal(t, w.Code, 201)
  583. assert.Equal(t, w.Body.String(), "<map><foo>bar</foo></map>")
  584. assert.Equal(t, w.HeaderMap.Get("Content-Type"), "application/xml; charset=utf-8")
  585. }
  586. // Tests that no XML is rendered if code is 204
  587. func TestContextRenderNoContentXML(t *testing.T) {
  588. w := httptest.NewRecorder()
  589. c, _ := CreateTestContext(w)
  590. c.XML(204, H{"foo": "bar"})
  591. assert.Equal(t, 204, w.Code)
  592. assert.Equal(t, "", w.Body.String())
  593. assert.Equal(t, w.HeaderMap.Get("Content-Type"), "application/xml; charset=utf-8")
  594. }
  595. // TestContextString tests that the response is returned
  596. // with Content-Type set to text/plain
  597. func TestContextRenderString(t *testing.T) {
  598. w := httptest.NewRecorder()
  599. c, _ := CreateTestContext(w)
  600. c.String(201, "test %s %d", "string", 2)
  601. assert.Equal(t, w.Code, 201)
  602. assert.Equal(t, w.Body.String(), "test string 2")
  603. assert.Equal(t, w.HeaderMap.Get("Content-Type"), "text/plain; charset=utf-8")
  604. }
  605. // Tests that no String is rendered if code is 204
  606. func TestContextRenderNoContentString(t *testing.T) {
  607. w := httptest.NewRecorder()
  608. c, _ := CreateTestContext(w)
  609. c.String(204, "test %s %d", "string", 2)
  610. assert.Equal(t, 204, w.Code)
  611. assert.Equal(t, "", w.Body.String())
  612. assert.Equal(t, w.HeaderMap.Get("Content-Type"), "text/plain; charset=utf-8")
  613. }
  614. // TestContextString tests that the response is returned
  615. // with Content-Type set to text/html
  616. func TestContextRenderHTMLString(t *testing.T) {
  617. w := httptest.NewRecorder()
  618. c, _ := CreateTestContext(w)
  619. c.Header("Content-Type", "text/html; charset=utf-8")
  620. c.String(201, "<html>%s %d</html>", "string", 3)
  621. assert.Equal(t, w.Code, 201)
  622. assert.Equal(t, w.Body.String(), "<html>string 3</html>")
  623. assert.Equal(t, w.HeaderMap.Get("Content-Type"), "text/html; charset=utf-8")
  624. }
  625. // Tests that no HTML String is rendered if code is 204
  626. func TestContextRenderNoContentHTMLString(t *testing.T) {
  627. w := httptest.NewRecorder()
  628. c, _ := CreateTestContext(w)
  629. c.Header("Content-Type", "text/html; charset=utf-8")
  630. c.String(204, "<html>%s %d</html>", "string", 3)
  631. assert.Equal(t, 204, w.Code)
  632. assert.Equal(t, "", w.Body.String())
  633. assert.Equal(t, w.HeaderMap.Get("Content-Type"), "text/html; charset=utf-8")
  634. }
  635. // TestContextData tests that the response can be written from `bytesting`
  636. // with specified MIME type
  637. func TestContextRenderData(t *testing.T) {
  638. w := httptest.NewRecorder()
  639. c, _ := CreateTestContext(w)
  640. c.Data(201, "text/csv", []byte(`foo,bar`))
  641. assert.Equal(t, w.Code, 201)
  642. assert.Equal(t, w.Body.String(), "foo,bar")
  643. assert.Equal(t, w.HeaderMap.Get("Content-Type"), "text/csv")
  644. }
  645. // Tests that no Custom Data is rendered if code is 204
  646. func TestContextRenderNoContentData(t *testing.T) {
  647. w := httptest.NewRecorder()
  648. c, _ := CreateTestContext(w)
  649. c.Data(204, "text/csv", []byte(`foo,bar`))
  650. assert.Equal(t, 204, w.Code)
  651. assert.Equal(t, "", w.Body.String())
  652. assert.Equal(t, w.HeaderMap.Get("Content-Type"), "text/csv")
  653. }
  654. func TestContextRenderSSE(t *testing.T) {
  655. w := httptest.NewRecorder()
  656. c, _ := CreateTestContext(w)
  657. c.SSEvent("float", 1.5)
  658. c.Render(-1, sse.Event{
  659. Id: "123",
  660. Data: "text",
  661. })
  662. c.SSEvent("chat", H{
  663. "foo": "bar",
  664. "bar": "foo",
  665. })
  666. 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))
  667. }
  668. func TestContextRenderFile(t *testing.T) {
  669. w := httptest.NewRecorder()
  670. c, _ := CreateTestContext(w)
  671. c.Request, _ = http.NewRequest("GET", "/", nil)
  672. c.File("./gin.go")
  673. assert.Equal(t, w.Code, 200)
  674. assert.Contains(t, w.Body.String(), "func New() *Engine {")
  675. assert.Equal(t, w.HeaderMap.Get("Content-Type"), "text/plain; charset=utf-8")
  676. }
  677. // TestContextRenderYAML tests that the response is serialized as YAML
  678. // and Content-Type is set to application/x-yaml
  679. func TestContextRenderYAML(t *testing.T) {
  680. w := httptest.NewRecorder()
  681. c, _ := CreateTestContext(w)
  682. c.YAML(201, H{"foo": "bar"})
  683. assert.Equal(t, w.Code, 201)
  684. assert.Equal(t, w.Body.String(), "foo: bar\n")
  685. assert.Equal(t, w.HeaderMap.Get("Content-Type"), "application/x-yaml; charset=utf-8")
  686. }
  687. func TestContextHeaders(t *testing.T) {
  688. c, _ := CreateTestContext(httptest.NewRecorder())
  689. c.Header("Content-Type", "text/plain")
  690. c.Header("X-Custom", "value")
  691. assert.Equal(t, c.Writer.Header().Get("Content-Type"), "text/plain")
  692. assert.Equal(t, c.Writer.Header().Get("X-Custom"), "value")
  693. c.Header("Content-Type", "text/html")
  694. c.Header("X-Custom", "")
  695. assert.Equal(t, c.Writer.Header().Get("Content-Type"), "text/html")
  696. _, exist := c.Writer.Header()["X-Custom"]
  697. assert.False(t, exist)
  698. }
  699. // TODO
  700. func TestContextRenderRedirectWithRelativePath(t *testing.T) {
  701. w := httptest.NewRecorder()
  702. c, _ := CreateTestContext(w)
  703. c.Request, _ = http.NewRequest("POST", "http://example.com", nil)
  704. assert.Panics(t, func() { c.Redirect(299, "/new_path") })
  705. assert.Panics(t, func() { c.Redirect(309, "/new_path") })
  706. c.Redirect(301, "/path")
  707. c.Writer.WriteHeaderNow()
  708. assert.Equal(t, w.Code, 301)
  709. assert.Equal(t, w.Header().Get("Location"), "/path")
  710. }
  711. func TestContextRenderRedirectWithAbsolutePath(t *testing.T) {
  712. w := httptest.NewRecorder()
  713. c, _ := CreateTestContext(w)
  714. c.Request, _ = http.NewRequest("POST", "http://example.com", nil)
  715. c.Redirect(302, "http://google.com")
  716. c.Writer.WriteHeaderNow()
  717. assert.Equal(t, w.Code, 302)
  718. assert.Equal(t, w.Header().Get("Location"), "http://google.com")
  719. }
  720. func TestContextRenderRedirectWith201(t *testing.T) {
  721. w := httptest.NewRecorder()
  722. c, _ := CreateTestContext(w)
  723. c.Request, _ = http.NewRequest("POST", "http://example.com", nil)
  724. c.Redirect(201, "/resource")
  725. c.Writer.WriteHeaderNow()
  726. assert.Equal(t, w.Code, 201)
  727. assert.Equal(t, w.Header().Get("Location"), "/resource")
  728. }
  729. func TestContextRenderRedirectAll(t *testing.T) {
  730. c, _ := CreateTestContext(httptest.NewRecorder())
  731. c.Request, _ = http.NewRequest("POST", "http://example.com", nil)
  732. assert.Panics(t, func() { c.Redirect(200, "/resource") })
  733. assert.Panics(t, func() { c.Redirect(202, "/resource") })
  734. assert.Panics(t, func() { c.Redirect(299, "/resource") })
  735. assert.Panics(t, func() { c.Redirect(309, "/resource") })
  736. assert.NotPanics(t, func() { c.Redirect(300, "/resource") })
  737. assert.NotPanics(t, func() { c.Redirect(308, "/resource") })
  738. }
  739. func TestContextNegotiationWithJSON(t *testing.T) {
  740. w := httptest.NewRecorder()
  741. c, _ := CreateTestContext(w)
  742. c.Request, _ = http.NewRequest("POST", "", nil)
  743. c.Negotiate(200, Negotiate{
  744. Offered: []string{MIMEJSON, MIMEXML},
  745. Data: H{"foo": "bar"},
  746. })
  747. assert.Equal(t, 200, w.Code)
  748. assert.Equal(t, "{\"foo\":\"bar\"}", w.Body.String())
  749. assert.Equal(t, "application/json; charset=utf-8", w.HeaderMap.Get("Content-Type"))
  750. }
  751. func TestContextNegotiationWithXML(t *testing.T) {
  752. w := httptest.NewRecorder()
  753. c, _ := CreateTestContext(w)
  754. c.Request, _ = http.NewRequest("POST", "", nil)
  755. c.Negotiate(200, Negotiate{
  756. Offered: []string{MIMEXML, MIMEJSON},
  757. Data: H{"foo": "bar"},
  758. })
  759. assert.Equal(t, 200, w.Code)
  760. assert.Equal(t, "<map><foo>bar</foo></map>", w.Body.String())
  761. assert.Equal(t, "application/xml; charset=utf-8", w.HeaderMap.Get("Content-Type"))
  762. }
  763. func TestContextNegotiationWithHTML(t *testing.T) {
  764. w := httptest.NewRecorder()
  765. c, router := CreateTestContext(w)
  766. c.Request, _ = http.NewRequest("POST", "", nil)
  767. templ := template.Must(template.New("t").Parse(`Hello {{.name}}`))
  768. router.SetHTMLTemplate(templ)
  769. c.Negotiate(200, Negotiate{
  770. Offered: []string{MIMEHTML},
  771. Data: H{"name": "gin"},
  772. HTMLName: "t",
  773. })
  774. assert.Equal(t, 200, w.Code)
  775. assert.Equal(t, "Hello gin", w.Body.String())
  776. assert.Equal(t, "text/html; charset=utf-8", w.HeaderMap.Get("Content-Type"))
  777. }
  778. func TestContextNegotiationNotSupport(t *testing.T) {
  779. w := httptest.NewRecorder()
  780. c, _ := CreateTestContext(w)
  781. c.Request, _ = http.NewRequest("POST", "", nil)
  782. c.Negotiate(200, Negotiate{
  783. Offered: []string{MIMEPOSTForm},
  784. })
  785. assert.Equal(t, 406, w.Code)
  786. assert.Equal(t, c.index, abortIndex)
  787. assert.True(t, c.IsAborted())
  788. }
  789. func TestContextNegotiationFormat(t *testing.T) {
  790. c, _ := CreateTestContext(httptest.NewRecorder())
  791. c.Request, _ = http.NewRequest("POST", "", nil)
  792. assert.Panics(t, func() { c.NegotiateFormat() })
  793. assert.Equal(t, c.NegotiateFormat(MIMEJSON, MIMEXML), MIMEJSON)
  794. assert.Equal(t, c.NegotiateFormat(MIMEHTML, MIMEJSON), MIMEHTML)
  795. }
  796. func TestContextNegotiationFormatWithAccept(t *testing.T) {
  797. c, _ := CreateTestContext(httptest.NewRecorder())
  798. c.Request, _ = http.NewRequest("POST", "/", nil)
  799. c.Request.Header.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
  800. assert.Equal(t, c.NegotiateFormat(MIMEJSON, MIMEXML), MIMEXML)
  801. assert.Equal(t, c.NegotiateFormat(MIMEXML, MIMEHTML), MIMEHTML)
  802. assert.Equal(t, c.NegotiateFormat(MIMEJSON), "")
  803. }
  804. func TestContextNegotiationFormatCustum(t *testing.T) {
  805. c, _ := CreateTestContext(httptest.NewRecorder())
  806. c.Request, _ = http.NewRequest("POST", "/", nil)
  807. c.Request.Header.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
  808. c.Accepted = nil
  809. c.SetAccepted(MIMEJSON, MIMEXML)
  810. assert.Equal(t, c.NegotiateFormat(MIMEJSON, MIMEXML), MIMEJSON)
  811. assert.Equal(t, c.NegotiateFormat(MIMEXML, MIMEHTML), MIMEXML)
  812. assert.Equal(t, c.NegotiateFormat(MIMEJSON), MIMEJSON)
  813. }
  814. func TestContextIsAborted(t *testing.T) {
  815. c, _ := CreateTestContext(httptest.NewRecorder())
  816. assert.False(t, c.IsAborted())
  817. c.Abort()
  818. assert.True(t, c.IsAborted())
  819. c.Next()
  820. assert.True(t, c.IsAborted())
  821. c.index++
  822. assert.True(t, c.IsAborted())
  823. }
  824. // TestContextData tests that the response can be written from `bytesting`
  825. // with specified MIME type
  826. func TestContextAbortWithStatus(t *testing.T) {
  827. w := httptest.NewRecorder()
  828. c, _ := CreateTestContext(w)
  829. c.index = 4
  830. c.AbortWithStatus(401)
  831. assert.Equal(t, c.index, abortIndex)
  832. assert.Equal(t, c.Writer.Status(), 401)
  833. assert.Equal(t, w.Code, 401)
  834. assert.True(t, c.IsAborted())
  835. }
  836. type testJSONAbortMsg struct {
  837. Foo string `json:"foo"`
  838. Bar string `json:"bar"`
  839. }
  840. func TestContextAbortWithStatusJSON(t *testing.T) {
  841. w := httptest.NewRecorder()
  842. c, _ := CreateTestContext(w)
  843. c.index = 4
  844. in := new(testJSONAbortMsg)
  845. in.Bar = "barValue"
  846. in.Foo = "fooValue"
  847. c.AbortWithStatusJSON(415, in)
  848. assert.Equal(t, c.index, abortIndex)
  849. assert.Equal(t, c.Writer.Status(), 415)
  850. assert.Equal(t, w.Code, 415)
  851. assert.True(t, c.IsAborted())
  852. contentType := w.Header().Get("Content-Type")
  853. assert.Equal(t, contentType, "application/json; charset=utf-8")
  854. buf := new(bytes.Buffer)
  855. buf.ReadFrom(w.Body)
  856. jsonStringBody := buf.String()
  857. assert.Equal(t, fmt.Sprint(`{"foo":"fooValue","bar":"barValue"}`), jsonStringBody)
  858. }
  859. func TestContextError(t *testing.T) {
  860. c, _ := CreateTestContext(httptest.NewRecorder())
  861. assert.Empty(t, c.Errors)
  862. c.Error(errors.New("first error"))
  863. assert.Len(t, c.Errors, 1)
  864. assert.Equal(t, c.Errors.String(), "Error #01: first error\n")
  865. c.Error(&Error{
  866. Err: errors.New("second error"),
  867. Meta: "some data 2",
  868. Type: ErrorTypePublic,
  869. })
  870. assert.Len(t, c.Errors, 2)
  871. assert.Equal(t, c.Errors[0].Err, errors.New("first error"))
  872. assert.Nil(t, c.Errors[0].Meta)
  873. assert.Equal(t, c.Errors[0].Type, ErrorTypePrivate)
  874. assert.Equal(t, c.Errors[1].Err, errors.New("second error"))
  875. assert.Equal(t, c.Errors[1].Meta, "some data 2")
  876. assert.Equal(t, c.Errors[1].Type, ErrorTypePublic)
  877. assert.Equal(t, c.Errors.Last(), c.Errors[1])
  878. defer func() {
  879. if recover() == nil {
  880. t.Error("didn't panic")
  881. }
  882. }()
  883. c.Error(nil)
  884. }
  885. func TestContextTypedError(t *testing.T) {
  886. c, _ := CreateTestContext(httptest.NewRecorder())
  887. c.Error(errors.New("externo 0")).SetType(ErrorTypePublic)
  888. c.Error(errors.New("interno 0")).SetType(ErrorTypePrivate)
  889. for _, err := range c.Errors.ByType(ErrorTypePublic) {
  890. assert.Equal(t, err.Type, ErrorTypePublic)
  891. }
  892. for _, err := range c.Errors.ByType(ErrorTypePrivate) {
  893. assert.Equal(t, err.Type, ErrorTypePrivate)
  894. }
  895. assert.Equal(t, c.Errors.Errors(), []string{"externo 0", "interno 0"})
  896. }
  897. func TestContextAbortWithError(t *testing.T) {
  898. w := httptest.NewRecorder()
  899. c, _ := CreateTestContext(w)
  900. c.AbortWithError(401, errors.New("bad input")).SetMeta("some input")
  901. assert.Equal(t, w.Code, 401)
  902. assert.Equal(t, c.index, abortIndex)
  903. assert.True(t, c.IsAborted())
  904. }
  905. func TestContextClientIP(t *testing.T) {
  906. c, _ := CreateTestContext(httptest.NewRecorder())
  907. c.Request, _ = http.NewRequest("POST", "/", nil)
  908. c.Request.Header.Set("X-Real-IP", " 10.10.10.10 ")
  909. c.Request.Header.Set("X-Forwarded-For", " 20.20.20.20, 30.30.30.30")
  910. c.Request.Header.Set("X-Appengine-Remote-Addr", "50.50.50.50")
  911. c.Request.RemoteAddr = " 40.40.40.40:42123 "
  912. assert.Equal(t, "20.20.20.20", c.ClientIP())
  913. c.Request.Header.Del("X-Forwarded-For")
  914. assert.Equal(t, "10.10.10.10", c.ClientIP())
  915. c.Request.Header.Set("X-Forwarded-For", "30.30.30.30 ")
  916. assert.Equal(t, "30.30.30.30", c.ClientIP())
  917. c.Request.Header.Del("X-Forwarded-For")
  918. c.Request.Header.Del("X-Real-IP")
  919. c.engine.AppEngine = true
  920. assert.Equal(t, "50.50.50.50", c.ClientIP())
  921. c.Request.Header.Del("X-Appengine-Remote-Addr")
  922. assert.Equal(t, "40.40.40.40", c.ClientIP())
  923. // no port
  924. c.Request.RemoteAddr = "50.50.50.50"
  925. assert.Equal(t, "", c.ClientIP())
  926. }
  927. func TestContextContentType(t *testing.T) {
  928. c, _ := CreateTestContext(httptest.NewRecorder())
  929. c.Request, _ = http.NewRequest("POST", "/", nil)
  930. c.Request.Header.Set("Content-Type", "application/json; charset=utf-8")
  931. assert.Equal(t, c.ContentType(), "application/json")
  932. }
  933. func TestContextAutoBindJSON(t *testing.T) {
  934. c, _ := CreateTestContext(httptest.NewRecorder())
  935. c.Request, _ = http.NewRequest("POST", "/", bytes.NewBufferString("{\"foo\":\"bar\", \"bar\":\"foo\"}"))
  936. c.Request.Header.Add("Content-Type", MIMEJSON)
  937. var obj struct {
  938. Foo string `json:"foo"`
  939. Bar string `json:"bar"`
  940. }
  941. assert.NoError(t, c.Bind(&obj))
  942. assert.Equal(t, obj.Bar, "foo")
  943. assert.Equal(t, obj.Foo, "bar")
  944. assert.Empty(t, c.Errors)
  945. }
  946. func TestContextBindWithJSON(t *testing.T) {
  947. w := httptest.NewRecorder()
  948. c, _ := CreateTestContext(w)
  949. c.Request, _ = http.NewRequest("POST", "/", bytes.NewBufferString("{\"foo\":\"bar\", \"bar\":\"foo\"}"))
  950. c.Request.Header.Add("Content-Type", MIMEXML) // set fake content-type
  951. var obj struct {
  952. Foo string `json:"foo"`
  953. Bar string `json:"bar"`
  954. }
  955. assert.NoError(t, c.BindJSON(&obj))
  956. assert.Equal(t, obj.Bar, "foo")
  957. assert.Equal(t, obj.Foo, "bar")
  958. assert.Equal(t, w.Body.Len(), 0)
  959. }
  960. func TestContextBindWithQuery(t *testing.T) {
  961. w := httptest.NewRecorder()
  962. c, _ := CreateTestContext(w)
  963. c.Request, _ = http.NewRequest("POST", "/?foo=bar&bar=foo", bytes.NewBufferString("foo=unused"))
  964. var obj struct {
  965. Foo string `form:"foo"`
  966. Bar string `form:"bar"`
  967. }
  968. assert.NoError(t, c.BindQuery(&obj))
  969. assert.Equal(t, "foo", obj.Bar)
  970. assert.Equal(t, "bar", obj.Foo)
  971. assert.Equal(t, 0, w.Body.Len())
  972. }
  973. func TestContextBadAutoBind(t *testing.T) {
  974. w := httptest.NewRecorder()
  975. c, _ := CreateTestContext(w)
  976. c.Request, _ = http.NewRequest("POST", "http://example.com", bytes.NewBufferString("\"foo\":\"bar\", \"bar\":\"foo\"}"))
  977. c.Request.Header.Add("Content-Type", MIMEJSON)
  978. var obj struct {
  979. Foo string `json:"foo"`
  980. Bar string `json:"bar"`
  981. }
  982. assert.False(t, c.IsAborted())
  983. assert.Error(t, c.Bind(&obj))
  984. c.Writer.WriteHeaderNow()
  985. assert.Empty(t, obj.Bar)
  986. assert.Empty(t, obj.Foo)
  987. assert.Equal(t, w.Code, 400)
  988. assert.True(t, c.IsAborted())
  989. }
  990. func TestContextAutoShouldBindJSON(t *testing.T) {
  991. c, _ := CreateTestContext(httptest.NewRecorder())
  992. c.Request, _ = http.NewRequest("POST", "/", bytes.NewBufferString("{\"foo\":\"bar\", \"bar\":\"foo\"}"))
  993. c.Request.Header.Add("Content-Type", MIMEJSON)
  994. var obj struct {
  995. Foo string `json:"foo"`
  996. Bar string `json:"bar"`
  997. }
  998. assert.NoError(t, c.ShouldBind(&obj))
  999. assert.Equal(t, obj.Bar, "foo")
  1000. assert.Equal(t, obj.Foo, "bar")
  1001. assert.Empty(t, c.Errors)
  1002. }
  1003. func TestContextShouldBindWithJSON(t *testing.T) {
  1004. w := httptest.NewRecorder()
  1005. c, _ := CreateTestContext(w)
  1006. c.Request, _ = http.NewRequest("POST", "/", bytes.NewBufferString("{\"foo\":\"bar\", \"bar\":\"foo\"}"))
  1007. c.Request.Header.Add("Content-Type", MIMEXML) // set fake content-type
  1008. var obj struct {
  1009. Foo string `json:"foo"`
  1010. Bar string `json:"bar"`
  1011. }
  1012. assert.NoError(t, c.ShouldBindJSON(&obj))
  1013. assert.Equal(t, obj.Bar, "foo")
  1014. assert.Equal(t, obj.Foo, "bar")
  1015. assert.Equal(t, w.Body.Len(), 0)
  1016. }
  1017. func TestContextShouldBindWithQuery(t *testing.T) {
  1018. w := httptest.NewRecorder()
  1019. c, _ := CreateTestContext(w)
  1020. c.Request, _ = http.NewRequest("POST", "/?foo=bar&bar=foo", bytes.NewBufferString("foo=unused"))
  1021. var obj struct {
  1022. Foo string `form:"foo"`
  1023. Bar string `form:"bar"`
  1024. }
  1025. assert.NoError(t, c.ShouldBindQuery(&obj))
  1026. assert.Equal(t, "foo", obj.Bar)
  1027. assert.Equal(t, "bar", obj.Foo)
  1028. assert.Equal(t, 0, w.Body.Len())
  1029. }
  1030. func TestContextBadAutoShouldBind(t *testing.T) {
  1031. w := httptest.NewRecorder()
  1032. c, _ := CreateTestContext(w)
  1033. c.Request, _ = http.NewRequest("POST", "http://example.com", bytes.NewBufferString("\"foo\":\"bar\", \"bar\":\"foo\"}"))
  1034. c.Request.Header.Add("Content-Type", MIMEJSON)
  1035. var obj struct {
  1036. Foo string `json:"foo"`
  1037. Bar string `json:"bar"`
  1038. }
  1039. assert.False(t, c.IsAborted())
  1040. assert.Error(t, c.ShouldBind(&obj))
  1041. assert.Empty(t, obj.Bar)
  1042. assert.Empty(t, obj.Foo)
  1043. assert.False(t, c.IsAborted())
  1044. }
  1045. func TestContextGolangContext(t *testing.T) {
  1046. c, _ := CreateTestContext(httptest.NewRecorder())
  1047. c.Request, _ = http.NewRequest("POST", "/", bytes.NewBufferString("{\"foo\":\"bar\", \"bar\":\"foo\"}"))
  1048. assert.NoError(t, c.Err())
  1049. assert.Nil(t, c.Done())
  1050. ti, ok := c.Deadline()
  1051. assert.Equal(t, ti, time.Time{})
  1052. assert.False(t, ok)
  1053. assert.Equal(t, c.Value(0), c.Request)
  1054. assert.Nil(t, c.Value("foo"))
  1055. c.Set("foo", "bar")
  1056. assert.Equal(t, c.Value("foo"), "bar")
  1057. assert.Nil(t, c.Value(1))
  1058. }
  1059. func TestWebsocketsRequired(t *testing.T) {
  1060. // Example request from spec: https://tools.ietf.org/html/rfc6455#section-1.2
  1061. c, _ := CreateTestContext(httptest.NewRecorder())
  1062. c.Request, _ = http.NewRequest("GET", "/chat", nil)
  1063. c.Request.Header.Set("Host", "server.example.com")
  1064. c.Request.Header.Set("Upgrade", "websocket")
  1065. c.Request.Header.Set("Connection", "Upgrade")
  1066. c.Request.Header.Set("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==")
  1067. c.Request.Header.Set("Origin", "http://example.com")
  1068. c.Request.Header.Set("Sec-WebSocket-Protocol", "chat, superchat")
  1069. c.Request.Header.Set("Sec-WebSocket-Version", "13")
  1070. assert.True(t, c.IsWebsocket())
  1071. // Normal request, no websocket required.
  1072. c, _ = CreateTestContext(httptest.NewRecorder())
  1073. c.Request, _ = http.NewRequest("GET", "/chat", nil)
  1074. c.Request.Header.Set("Host", "server.example.com")
  1075. assert.False(t, c.IsWebsocket())
  1076. }
  1077. func TestGetRequestHeaderValue(t *testing.T) {
  1078. c, _ := CreateTestContext(httptest.NewRecorder())
  1079. c.Request, _ = http.NewRequest("GET", "/chat", nil)
  1080. c.Request.Header.Set("Gin-Version", "1.0.0")
  1081. assert.Equal(t, "1.0.0", c.GetHeader("Gin-Version"))
  1082. assert.Equal(t, "", c.GetHeader("Connection"))
  1083. }
  1084. func TestContextGetRawData(t *testing.T) {
  1085. c, _ := CreateTestContext(httptest.NewRecorder())
  1086. body := bytes.NewBufferString("Fetch binary post data")
  1087. c.Request, _ = http.NewRequest("POST", "/", body)
  1088. c.Request.Header.Add("Content-Type", MIMEPOSTForm)
  1089. data, err := c.GetRawData()
  1090. assert.Nil(t, err)
  1091. assert.Equal(t, "Fetch binary post data", string(data))
  1092. }