context_test.go 41 KB

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