context_test.go 57 KB

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