context_test.go 38 KB

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