context_test.go 50 KB

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