context_test.go 52 KB

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