context_test.go 58 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473147414751476147714781479148014811482148314841485148614871488148914901491149214931494149514961497149814991500150115021503150415051506150715081509151015111512151315141515151615171518151915201521152215231524152515261527152815291530153115321533153415351536153715381539154015411542154315441545154615471548154915501551155215531554155515561557155815591560156115621563156415651566156715681569157015711572157315741575157615771578157915801581158215831584158515861587158815891590159115921593159415951596159715981599160016011602160316041605160616071608160916101611161216131614161516161617161816191620162116221623162416251626162716281629163016311632163316341635163616371638163916401641164216431644164516461647164816491650165116521653165416551656165716581659166016611662166316641665166616671668166916701671167216731674167516761677167816791680168116821683168416851686168716881689169016911692169316941695169616971698169917001701170217031704170517061707170817091710171117121713171417151716171717181719172017211722172317241725172617271728172917301731173217331734173517361737173817391740174117421743174417451746174717481749175017511752175317541755175617571758175917601761176217631764176517661767176817691770177117721773177417751776177717781779178017811782178317841785178617871788178917901791179217931794179517961797179817991800180118021803180418051806180718081809181018111812181318141815181618171818181918201821182218231824182518261827182818291830183118321833183418351836183718381839184018411842184318441845184618471848184918501851185218531854185518561857185818591860186118621863186418651866186718681869187018711872187318741875187618771878187918801881188218831884188518861887188818891890189118921893189418951896189718981899190019011902190319041905190619071908190919101911191219131914191519161917191819191920192119221923192419251926192719281929193019311932193319341935
  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.SetSameSite(http.SameSiteLaxMode)
  503. c.SetCookie("user", "gin", 1, "/", "localhost", true, true)
  504. assert.Equal(t, "user=gin; Path=/; Domain=localhost; Max-Age=1; HttpOnly; Secure; SameSite=Lax", c.Writer.Header().Get("Set-Cookie"))
  505. }
  506. func TestContextSetCookiePathEmpty(t *testing.T) {
  507. c, _ := CreateTestContext(httptest.NewRecorder())
  508. c.SetSameSite(http.SameSiteLaxMode)
  509. c.SetCookie("user", "gin", 1, "", "localhost", true, true)
  510. assert.Equal(t, "user=gin; Path=/; Domain=localhost; Max-Age=1; HttpOnly; Secure; SameSite=Lax", c.Writer.Header().Get("Set-Cookie"))
  511. }
  512. func TestContextGetCookie(t *testing.T) {
  513. c, _ := CreateTestContext(httptest.NewRecorder())
  514. c.Request, _ = http.NewRequest("GET", "/get", nil)
  515. c.Request.Header.Set("Cookie", "user=gin")
  516. cookie, _ := c.Cookie("user")
  517. assert.Equal(t, "gin", cookie)
  518. _, err := c.Cookie("nokey")
  519. assert.Error(t, err)
  520. }
  521. func TestContextBodyAllowedForStatus(t *testing.T) {
  522. assert.False(t, false, bodyAllowedForStatus(http.StatusProcessing))
  523. assert.False(t, false, bodyAllowedForStatus(http.StatusNoContent))
  524. assert.False(t, false, bodyAllowedForStatus(http.StatusNotModified))
  525. assert.True(t, true, bodyAllowedForStatus(http.StatusInternalServerError))
  526. }
  527. type TestPanicRender struct {
  528. }
  529. func (*TestPanicRender) Render(http.ResponseWriter) error {
  530. return errors.New("TestPanicRender")
  531. }
  532. func (*TestPanicRender) WriteContentType(http.ResponseWriter) {}
  533. func TestContextRenderPanicIfErr(t *testing.T) {
  534. defer func() {
  535. r := recover()
  536. assert.Equal(t, "TestPanicRender", fmt.Sprint(r))
  537. }()
  538. w := httptest.NewRecorder()
  539. c, _ := CreateTestContext(w)
  540. c.Render(http.StatusOK, &TestPanicRender{})
  541. assert.Fail(t, "Panic not detected")
  542. }
  543. // Tests that the response is serialized as JSON
  544. // and Content-Type is set to application/json
  545. // and special HTML characters are escaped
  546. func TestContextRenderJSON(t *testing.T) {
  547. w := httptest.NewRecorder()
  548. c, _ := CreateTestContext(w)
  549. c.JSON(http.StatusCreated, H{"foo": "bar", "html": "<b>"})
  550. assert.Equal(t, http.StatusCreated, w.Code)
  551. assert.Equal(t, "{\"foo\":\"bar\",\"html\":\"\\u003cb\\u003e\"}", w.Body.String())
  552. assert.Equal(t, "application/json; charset=utf-8", w.Header().Get("Content-Type"))
  553. }
  554. // Tests that the response is serialized as JSONP
  555. // and Content-Type is set to application/javascript
  556. func TestContextRenderJSONP(t *testing.T) {
  557. w := httptest.NewRecorder()
  558. c, _ := CreateTestContext(w)
  559. c.Request, _ = http.NewRequest("GET", "http://example.com/?callback=x", nil)
  560. c.JSONP(http.StatusCreated, H{"foo": "bar"})
  561. assert.Equal(t, http.StatusCreated, w.Code)
  562. assert.Equal(t, "x({\"foo\":\"bar\"});", w.Body.String())
  563. assert.Equal(t, "application/javascript; charset=utf-8", w.Header().Get("Content-Type"))
  564. }
  565. // Tests that the response is serialized as JSONP
  566. // and Content-Type is set to application/json
  567. func TestContextRenderJSONPWithoutCallback(t *testing.T) {
  568. w := httptest.NewRecorder()
  569. c, _ := CreateTestContext(w)
  570. c.Request, _ = http.NewRequest("GET", "http://example.com", nil)
  571. c.JSONP(http.StatusCreated, H{"foo": "bar"})
  572. assert.Equal(t, http.StatusCreated, w.Code)
  573. assert.Equal(t, "{\"foo\":\"bar\"}", w.Body.String())
  574. assert.Equal(t, "application/json; charset=utf-8", w.Header().Get("Content-Type"))
  575. }
  576. // Tests that no JSON is rendered if code is 204
  577. func TestContextRenderNoContentJSON(t *testing.T) {
  578. w := httptest.NewRecorder()
  579. c, _ := CreateTestContext(w)
  580. c.JSON(http.StatusNoContent, H{"foo": "bar"})
  581. assert.Equal(t, http.StatusNoContent, w.Code)
  582. assert.Empty(t, w.Body.String())
  583. assert.Equal(t, "application/json; charset=utf-8", w.Header().Get("Content-Type"))
  584. }
  585. // Tests that the response is serialized as JSON
  586. // we change the content-type before
  587. func TestContextRenderAPIJSON(t *testing.T) {
  588. w := httptest.NewRecorder()
  589. c, _ := CreateTestContext(w)
  590. c.Header("Content-Type", "application/vnd.api+json")
  591. c.JSON(http.StatusCreated, H{"foo": "bar"})
  592. assert.Equal(t, http.StatusCreated, w.Code)
  593. assert.Equal(t, "{\"foo\":\"bar\"}", w.Body.String())
  594. assert.Equal(t, "application/vnd.api+json", w.Header().Get("Content-Type"))
  595. }
  596. // Tests that no Custom JSON is rendered if code is 204
  597. func TestContextRenderNoContentAPIJSON(t *testing.T) {
  598. w := httptest.NewRecorder()
  599. c, _ := CreateTestContext(w)
  600. c.Header("Content-Type", "application/vnd.api+json")
  601. c.JSON(http.StatusNoContent, H{"foo": "bar"})
  602. assert.Equal(t, http.StatusNoContent, w.Code)
  603. assert.Empty(t, w.Body.String())
  604. assert.Equal(t, w.Header().Get("Content-Type"), "application/vnd.api+json")
  605. }
  606. // Tests that the response is serialized as JSON
  607. // and Content-Type is set to application/json
  608. func TestContextRenderIndentedJSON(t *testing.T) {
  609. w := httptest.NewRecorder()
  610. c, _ := CreateTestContext(w)
  611. c.IndentedJSON(http.StatusCreated, H{"foo": "bar", "bar": "foo", "nested": H{"foo": "bar"}})
  612. assert.Equal(t, http.StatusCreated, w.Code)
  613. assert.Equal(t, "{\n \"bar\": \"foo\",\n \"foo\": \"bar\",\n \"nested\": {\n \"foo\": \"bar\"\n }\n}", w.Body.String())
  614. assert.Equal(t, "application/json; charset=utf-8", w.Header().Get("Content-Type"))
  615. }
  616. // Tests that no Custom JSON is rendered if code is 204
  617. func TestContextRenderNoContentIndentedJSON(t *testing.T) {
  618. w := httptest.NewRecorder()
  619. c, _ := CreateTestContext(w)
  620. c.IndentedJSON(http.StatusNoContent, H{"foo": "bar", "bar": "foo", "nested": H{"foo": "bar"}})
  621. assert.Equal(t, http.StatusNoContent, w.Code)
  622. assert.Empty(t, w.Body.String())
  623. assert.Equal(t, "application/json; charset=utf-8", w.Header().Get("Content-Type"))
  624. }
  625. // Tests that the response is serialized as Secure JSON
  626. // and Content-Type is set to application/json
  627. func TestContextRenderSecureJSON(t *testing.T) {
  628. w := httptest.NewRecorder()
  629. c, router := CreateTestContext(w)
  630. router.SecureJsonPrefix("&&&START&&&")
  631. c.SecureJSON(http.StatusCreated, []string{"foo", "bar"})
  632. assert.Equal(t, http.StatusCreated, w.Code)
  633. assert.Equal(t, "&&&START&&&[\"foo\",\"bar\"]", w.Body.String())
  634. assert.Equal(t, "application/json; charset=utf-8", w.Header().Get("Content-Type"))
  635. }
  636. // Tests that no Custom JSON is rendered if code is 204
  637. func TestContextRenderNoContentSecureJSON(t *testing.T) {
  638. w := httptest.NewRecorder()
  639. c, _ := CreateTestContext(w)
  640. c.SecureJSON(http.StatusNoContent, []string{"foo", "bar"})
  641. assert.Equal(t, http.StatusNoContent, w.Code)
  642. assert.Empty(t, w.Body.String())
  643. assert.Equal(t, "application/json; charset=utf-8", w.Header().Get("Content-Type"))
  644. }
  645. func TestContextRenderNoContentAsciiJSON(t *testing.T) {
  646. w := httptest.NewRecorder()
  647. c, _ := CreateTestContext(w)
  648. c.AsciiJSON(http.StatusNoContent, []string{"lang", "Go语言"})
  649. assert.Equal(t, http.StatusNoContent, w.Code)
  650. assert.Empty(t, w.Body.String())
  651. assert.Equal(t, "application/json", w.Header().Get("Content-Type"))
  652. }
  653. // Tests that the response is serialized as JSON
  654. // and Content-Type is set to application/json
  655. // and special HTML characters are preserved
  656. func TestContextRenderPureJSON(t *testing.T) {
  657. w := httptest.NewRecorder()
  658. c, _ := CreateTestContext(w)
  659. c.PureJSON(http.StatusCreated, H{"foo": "bar", "html": "<b>"})
  660. assert.Equal(t, http.StatusCreated, w.Code)
  661. assert.Equal(t, "{\"foo\":\"bar\",\"html\":\"<b>\"}\n", w.Body.String())
  662. assert.Equal(t, "application/json; charset=utf-8", w.Header().Get("Content-Type"))
  663. }
  664. // Tests that the response executes the templates
  665. // and responds with Content-Type set to text/html
  666. func TestContextRenderHTML(t *testing.T) {
  667. w := httptest.NewRecorder()
  668. c, router := CreateTestContext(w)
  669. templ := template.Must(template.New("t").Parse(`Hello {{.name}}`))
  670. router.SetHTMLTemplate(templ)
  671. c.HTML(http.StatusCreated, "t", H{"name": "alexandernyquist"})
  672. assert.Equal(t, http.StatusCreated, w.Code)
  673. assert.Equal(t, "Hello alexandernyquist", w.Body.String())
  674. assert.Equal(t, "text/html; charset=utf-8", w.Header().Get("Content-Type"))
  675. }
  676. func TestContextRenderHTML2(t *testing.T) {
  677. w := httptest.NewRecorder()
  678. c, router := CreateTestContext(w)
  679. // print debug warning log when Engine.trees > 0
  680. router.addRoute("GET", "/", HandlersChain{func(_ *Context) {}})
  681. assert.Len(t, router.trees, 1)
  682. templ := template.Must(template.New("t").Parse(`Hello {{.name}}`))
  683. re := captureOutput(t, func() {
  684. SetMode(DebugMode)
  685. router.SetHTMLTemplate(templ)
  686. SetMode(TestMode)
  687. })
  688. 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)
  689. c.HTML(http.StatusCreated, "t", H{"name": "alexandernyquist"})
  690. assert.Equal(t, http.StatusCreated, w.Code)
  691. assert.Equal(t, "Hello alexandernyquist", w.Body.String())
  692. assert.Equal(t, "text/html; charset=utf-8", w.Header().Get("Content-Type"))
  693. }
  694. // Tests that no HTML is rendered if code is 204
  695. func TestContextRenderNoContentHTML(t *testing.T) {
  696. w := httptest.NewRecorder()
  697. c, router := CreateTestContext(w)
  698. templ := template.Must(template.New("t").Parse(`Hello {{.name}}`))
  699. router.SetHTMLTemplate(templ)
  700. c.HTML(http.StatusNoContent, "t", H{"name": "alexandernyquist"})
  701. assert.Equal(t, http.StatusNoContent, w.Code)
  702. assert.Empty(t, w.Body.String())
  703. assert.Equal(t, "text/html; charset=utf-8", w.Header().Get("Content-Type"))
  704. }
  705. // TestContextXML tests that the response is serialized as XML
  706. // and Content-Type is set to application/xml
  707. func TestContextRenderXML(t *testing.T) {
  708. w := httptest.NewRecorder()
  709. c, _ := CreateTestContext(w)
  710. c.XML(http.StatusCreated, H{"foo": "bar"})
  711. assert.Equal(t, http.StatusCreated, w.Code)
  712. assert.Equal(t, "<map><foo>bar</foo></map>", w.Body.String())
  713. assert.Equal(t, "application/xml; charset=utf-8", w.Header().Get("Content-Type"))
  714. }
  715. // Tests that no XML is rendered if code is 204
  716. func TestContextRenderNoContentXML(t *testing.T) {
  717. w := httptest.NewRecorder()
  718. c, _ := CreateTestContext(w)
  719. c.XML(http.StatusNoContent, H{"foo": "bar"})
  720. assert.Equal(t, http.StatusNoContent, w.Code)
  721. assert.Empty(t, w.Body.String())
  722. assert.Equal(t, "application/xml; charset=utf-8", w.Header().Get("Content-Type"))
  723. }
  724. // TestContextString tests that the response is returned
  725. // with Content-Type set to text/plain
  726. func TestContextRenderString(t *testing.T) {
  727. w := httptest.NewRecorder()
  728. c, _ := CreateTestContext(w)
  729. c.String(http.StatusCreated, "test %s %d", "string", 2)
  730. assert.Equal(t, http.StatusCreated, w.Code)
  731. assert.Equal(t, "test string 2", w.Body.String())
  732. assert.Equal(t, "text/plain; charset=utf-8", w.Header().Get("Content-Type"))
  733. }
  734. // Tests that no String is rendered if code is 204
  735. func TestContextRenderNoContentString(t *testing.T) {
  736. w := httptest.NewRecorder()
  737. c, _ := CreateTestContext(w)
  738. c.String(http.StatusNoContent, "test %s %d", "string", 2)
  739. assert.Equal(t, http.StatusNoContent, w.Code)
  740. assert.Empty(t, w.Body.String())
  741. assert.Equal(t, "text/plain; charset=utf-8", w.Header().Get("Content-Type"))
  742. }
  743. // TestContextString tests that the response is returned
  744. // with Content-Type set to text/html
  745. func TestContextRenderHTMLString(t *testing.T) {
  746. w := httptest.NewRecorder()
  747. c, _ := CreateTestContext(w)
  748. c.Header("Content-Type", "text/html; charset=utf-8")
  749. c.String(http.StatusCreated, "<html>%s %d</html>", "string", 3)
  750. assert.Equal(t, http.StatusCreated, w.Code)
  751. assert.Equal(t, "<html>string 3</html>", w.Body.String())
  752. assert.Equal(t, "text/html; charset=utf-8", w.Header().Get("Content-Type"))
  753. }
  754. // Tests that no HTML String is rendered if code is 204
  755. func TestContextRenderNoContentHTMLString(t *testing.T) {
  756. w := httptest.NewRecorder()
  757. c, _ := CreateTestContext(w)
  758. c.Header("Content-Type", "text/html; charset=utf-8")
  759. c.String(http.StatusNoContent, "<html>%s %d</html>", "string", 3)
  760. assert.Equal(t, http.StatusNoContent, w.Code)
  761. assert.Empty(t, w.Body.String())
  762. assert.Equal(t, "text/html; charset=utf-8", w.Header().Get("Content-Type"))
  763. }
  764. // TestContextData tests that the response can be written from `bytesting`
  765. // with specified MIME type
  766. func TestContextRenderData(t *testing.T) {
  767. w := httptest.NewRecorder()
  768. c, _ := CreateTestContext(w)
  769. c.Data(http.StatusCreated, "text/csv", []byte(`foo,bar`))
  770. assert.Equal(t, http.StatusCreated, w.Code)
  771. assert.Equal(t, "foo,bar", w.Body.String())
  772. assert.Equal(t, "text/csv", w.Header().Get("Content-Type"))
  773. }
  774. // Tests that no Custom Data is rendered if code is 204
  775. func TestContextRenderNoContentData(t *testing.T) {
  776. w := httptest.NewRecorder()
  777. c, _ := CreateTestContext(w)
  778. c.Data(http.StatusNoContent, "text/csv", []byte(`foo,bar`))
  779. assert.Equal(t, http.StatusNoContent, w.Code)
  780. assert.Empty(t, w.Body.String())
  781. assert.Equal(t, "text/csv", w.Header().Get("Content-Type"))
  782. }
  783. func TestContextRenderSSE(t *testing.T) {
  784. w := httptest.NewRecorder()
  785. c, _ := CreateTestContext(w)
  786. c.SSEvent("float", 1.5)
  787. c.Render(-1, sse.Event{
  788. Id: "123",
  789. Data: "text",
  790. })
  791. c.SSEvent("chat", H{
  792. "foo": "bar",
  793. "bar": "foo",
  794. })
  795. 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))
  796. }
  797. func TestContextRenderFile(t *testing.T) {
  798. w := httptest.NewRecorder()
  799. c, _ := CreateTestContext(w)
  800. c.Request, _ = http.NewRequest("GET", "/", nil)
  801. c.File("./gin.go")
  802. assert.Equal(t, http.StatusOK, w.Code)
  803. assert.Contains(t, w.Body.String(), "func New() *Engine {")
  804. assert.Equal(t, "text/plain; charset=utf-8", w.Header().Get("Content-Type"))
  805. }
  806. func TestContextRenderFileFromFS(t *testing.T) {
  807. w := httptest.NewRecorder()
  808. c, _ := CreateTestContext(w)
  809. c.Request, _ = http.NewRequest("GET", "/some/path", nil)
  810. c.FileFromFS("./gin.go", Dir(".", false))
  811. assert.Equal(t, http.StatusOK, w.Code)
  812. assert.Contains(t, w.Body.String(), "func New() *Engine {")
  813. assert.Equal(t, "text/plain; charset=utf-8", w.Header().Get("Content-Type"))
  814. assert.Equal(t, "/some/path", c.Request.URL.Path)
  815. }
  816. func TestContextRenderAttachment(t *testing.T) {
  817. w := httptest.NewRecorder()
  818. c, _ := CreateTestContext(w)
  819. newFilename := "new_filename.go"
  820. c.Request, _ = http.NewRequest("GET", "/", nil)
  821. c.FileAttachment("./gin.go", newFilename)
  822. assert.Equal(t, 200, w.Code)
  823. assert.Contains(t, w.Body.String(), "func New() *Engine {")
  824. assert.Equal(t, fmt.Sprintf("attachment; filename=\"%s\"", newFilename), w.HeaderMap.Get("Content-Disposition"))
  825. }
  826. // TestContextRenderYAML tests that the response is serialized as YAML
  827. // and Content-Type is set to application/x-yaml
  828. func TestContextRenderYAML(t *testing.T) {
  829. w := httptest.NewRecorder()
  830. c, _ := CreateTestContext(w)
  831. c.YAML(http.StatusCreated, H{"foo": "bar"})
  832. assert.Equal(t, http.StatusCreated, w.Code)
  833. assert.Equal(t, "foo: bar\n", w.Body.String())
  834. assert.Equal(t, "application/x-yaml; charset=utf-8", w.Header().Get("Content-Type"))
  835. }
  836. // TestContextRenderProtoBuf tests that the response is serialized as ProtoBuf
  837. // and Content-Type is set to application/x-protobuf
  838. // and we just use the example protobuf to check if the response is correct
  839. func TestContextRenderProtoBuf(t *testing.T) {
  840. w := httptest.NewRecorder()
  841. c, _ := CreateTestContext(w)
  842. reps := []int64{int64(1), int64(2)}
  843. label := "test"
  844. data := &testdata.Test{
  845. Label: &label,
  846. Reps: reps,
  847. }
  848. c.ProtoBuf(http.StatusCreated, data)
  849. protoData, err := proto.Marshal(data)
  850. assert.NoError(t, err)
  851. assert.Equal(t, http.StatusCreated, w.Code)
  852. assert.Equal(t, string(protoData), w.Body.String())
  853. assert.Equal(t, "application/x-protobuf", w.Header().Get("Content-Type"))
  854. }
  855. func TestContextHeaders(t *testing.T) {
  856. c, _ := CreateTestContext(httptest.NewRecorder())
  857. c.Header("Content-Type", "text/plain")
  858. c.Header("X-Custom", "value")
  859. assert.Equal(t, "text/plain", c.Writer.Header().Get("Content-Type"))
  860. assert.Equal(t, "value", c.Writer.Header().Get("X-Custom"))
  861. c.Header("Content-Type", "text/html")
  862. c.Header("X-Custom", "")
  863. assert.Equal(t, "text/html", c.Writer.Header().Get("Content-Type"))
  864. _, exist := c.Writer.Header()["X-Custom"]
  865. assert.False(t, exist)
  866. }
  867. // TODO
  868. func TestContextRenderRedirectWithRelativePath(t *testing.T) {
  869. w := httptest.NewRecorder()
  870. c, _ := CreateTestContext(w)
  871. c.Request, _ = http.NewRequest("POST", "http://example.com", nil)
  872. assert.Panics(t, func() { c.Redirect(299, "/new_path") })
  873. assert.Panics(t, func() { c.Redirect(309, "/new_path") })
  874. c.Redirect(http.StatusMovedPermanently, "/path")
  875. c.Writer.WriteHeaderNow()
  876. assert.Equal(t, http.StatusMovedPermanently, w.Code)
  877. assert.Equal(t, "/path", w.Header().Get("Location"))
  878. }
  879. func TestContextRenderRedirectWithAbsolutePath(t *testing.T) {
  880. w := httptest.NewRecorder()
  881. c, _ := CreateTestContext(w)
  882. c.Request, _ = http.NewRequest("POST", "http://example.com", nil)
  883. c.Redirect(http.StatusFound, "http://google.com")
  884. c.Writer.WriteHeaderNow()
  885. assert.Equal(t, http.StatusFound, w.Code)
  886. assert.Equal(t, "http://google.com", w.Header().Get("Location"))
  887. }
  888. func TestContextRenderRedirectWith201(t *testing.T) {
  889. w := httptest.NewRecorder()
  890. c, _ := CreateTestContext(w)
  891. c.Request, _ = http.NewRequest("POST", "http://example.com", nil)
  892. c.Redirect(http.StatusCreated, "/resource")
  893. c.Writer.WriteHeaderNow()
  894. assert.Equal(t, http.StatusCreated, w.Code)
  895. assert.Equal(t, "/resource", w.Header().Get("Location"))
  896. }
  897. func TestContextRenderRedirectAll(t *testing.T) {
  898. c, _ := CreateTestContext(httptest.NewRecorder())
  899. c.Request, _ = http.NewRequest("POST", "http://example.com", nil)
  900. assert.Panics(t, func() { c.Redirect(http.StatusOK, "/resource") })
  901. assert.Panics(t, func() { c.Redirect(http.StatusAccepted, "/resource") })
  902. assert.Panics(t, func() { c.Redirect(299, "/resource") })
  903. assert.Panics(t, func() { c.Redirect(309, "/resource") })
  904. assert.NotPanics(t, func() { c.Redirect(http.StatusMultipleChoices, "/resource") })
  905. assert.NotPanics(t, func() { c.Redirect(http.StatusPermanentRedirect, "/resource") })
  906. }
  907. func TestContextNegotiationWithJSON(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{MIMEJSON, MIMEXML, MIMEYAML},
  913. Data: H{"foo": "bar"},
  914. })
  915. assert.Equal(t, http.StatusOK, w.Code)
  916. assert.Equal(t, "{\"foo\":\"bar\"}", w.Body.String())
  917. assert.Equal(t, "application/json; charset=utf-8", w.Header().Get("Content-Type"))
  918. }
  919. func TestContextNegotiationWithXML(t *testing.T) {
  920. w := httptest.NewRecorder()
  921. c, _ := CreateTestContext(w)
  922. c.Request, _ = http.NewRequest("POST", "", nil)
  923. c.Negotiate(http.StatusOK, Negotiate{
  924. Offered: []string{MIMEXML, MIMEJSON, MIMEYAML},
  925. Data: H{"foo": "bar"},
  926. })
  927. assert.Equal(t, http.StatusOK, w.Code)
  928. assert.Equal(t, "<map><foo>bar</foo></map>", w.Body.String())
  929. assert.Equal(t, "application/xml; charset=utf-8", w.Header().Get("Content-Type"))
  930. }
  931. func TestContextNegotiationWithHTML(t *testing.T) {
  932. w := httptest.NewRecorder()
  933. c, router := CreateTestContext(w)
  934. c.Request, _ = http.NewRequest("POST", "", nil)
  935. templ := template.Must(template.New("t").Parse(`Hello {{.name}}`))
  936. router.SetHTMLTemplate(templ)
  937. c.Negotiate(http.StatusOK, Negotiate{
  938. Offered: []string{MIMEHTML},
  939. Data: H{"name": "gin"},
  940. HTMLName: "t",
  941. })
  942. assert.Equal(t, http.StatusOK, w.Code)
  943. assert.Equal(t, "Hello gin", w.Body.String())
  944. assert.Equal(t, "text/html; charset=utf-8", w.Header().Get("Content-Type"))
  945. }
  946. func TestContextNegotiationNotSupport(t *testing.T) {
  947. w := httptest.NewRecorder()
  948. c, _ := CreateTestContext(w)
  949. c.Request, _ = http.NewRequest("POST", "", nil)
  950. c.Negotiate(http.StatusOK, Negotiate{
  951. Offered: []string{MIMEPOSTForm},
  952. })
  953. assert.Equal(t, http.StatusNotAcceptable, w.Code)
  954. assert.Equal(t, c.index, abortIndex)
  955. assert.True(t, c.IsAborted())
  956. }
  957. func TestContextNegotiationFormat(t *testing.T) {
  958. c, _ := CreateTestContext(httptest.NewRecorder())
  959. c.Request, _ = http.NewRequest("POST", "", nil)
  960. assert.Panics(t, func() { c.NegotiateFormat() })
  961. assert.Equal(t, MIMEJSON, c.NegotiateFormat(MIMEJSON, MIMEXML))
  962. assert.Equal(t, MIMEHTML, c.NegotiateFormat(MIMEHTML, MIMEJSON))
  963. }
  964. func TestContextNegotiationFormatWithAccept(t *testing.T) {
  965. c, _ := CreateTestContext(httptest.NewRecorder())
  966. c.Request, _ = http.NewRequest("POST", "/", nil)
  967. c.Request.Header.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9;q=0.8")
  968. assert.Equal(t, MIMEXML, c.NegotiateFormat(MIMEJSON, MIMEXML))
  969. assert.Equal(t, MIMEHTML, c.NegotiateFormat(MIMEXML, MIMEHTML))
  970. assert.Empty(t, c.NegotiateFormat(MIMEJSON))
  971. }
  972. func TestContextNegotiationFormatWithWildcardAccept(t *testing.T) {
  973. c, _ := CreateTestContext(httptest.NewRecorder())
  974. c.Request, _ = http.NewRequest("POST", "/", nil)
  975. c.Request.Header.Add("Accept", "*/*")
  976. assert.Equal(t, c.NegotiateFormat("*/*"), "*/*")
  977. assert.Equal(t, c.NegotiateFormat("text/*"), "text/*")
  978. assert.Equal(t, c.NegotiateFormat("application/*"), "application/*")
  979. assert.Equal(t, c.NegotiateFormat(MIMEJSON), MIMEJSON)
  980. assert.Equal(t, c.NegotiateFormat(MIMEXML), MIMEXML)
  981. assert.Equal(t, c.NegotiateFormat(MIMEHTML), MIMEHTML)
  982. c, _ = CreateTestContext(httptest.NewRecorder())
  983. c.Request, _ = http.NewRequest("POST", "/", nil)
  984. c.Request.Header.Add("Accept", "text/*")
  985. assert.Equal(t, c.NegotiateFormat("*/*"), "*/*")
  986. assert.Equal(t, c.NegotiateFormat("text/*"), "text/*")
  987. assert.Equal(t, c.NegotiateFormat("application/*"), "")
  988. assert.Equal(t, c.NegotiateFormat(MIMEJSON), "")
  989. assert.Equal(t, c.NegotiateFormat(MIMEXML), "")
  990. assert.Equal(t, c.NegotiateFormat(MIMEHTML), MIMEHTML)
  991. }
  992. func TestContextNegotiationFormatCustom(t *testing.T) {
  993. c, _ := CreateTestContext(httptest.NewRecorder())
  994. c.Request, _ = http.NewRequest("POST", "/", nil)
  995. c.Request.Header.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9;q=0.8")
  996. c.Accepted = nil
  997. c.SetAccepted(MIMEJSON, MIMEXML)
  998. assert.Equal(t, MIMEJSON, c.NegotiateFormat(MIMEJSON, MIMEXML))
  999. assert.Equal(t, MIMEXML, c.NegotiateFormat(MIMEXML, MIMEHTML))
  1000. assert.Equal(t, MIMEJSON, c.NegotiateFormat(MIMEJSON))
  1001. }
  1002. func TestContextIsAborted(t *testing.T) {
  1003. c, _ := CreateTestContext(httptest.NewRecorder())
  1004. assert.False(t, c.IsAborted())
  1005. c.Abort()
  1006. assert.True(t, c.IsAborted())
  1007. c.Next()
  1008. assert.True(t, c.IsAborted())
  1009. c.index++
  1010. assert.True(t, c.IsAborted())
  1011. }
  1012. // TestContextData tests that the response can be written from `bytesting`
  1013. // with specified MIME type
  1014. func TestContextAbortWithStatus(t *testing.T) {
  1015. w := httptest.NewRecorder()
  1016. c, _ := CreateTestContext(w)
  1017. c.index = 4
  1018. c.AbortWithStatus(http.StatusUnauthorized)
  1019. assert.Equal(t, abortIndex, c.index)
  1020. assert.Equal(t, http.StatusUnauthorized, c.Writer.Status())
  1021. assert.Equal(t, http.StatusUnauthorized, w.Code)
  1022. assert.True(t, c.IsAborted())
  1023. }
  1024. type testJSONAbortMsg struct {
  1025. Foo string `json:"foo"`
  1026. Bar string `json:"bar"`
  1027. }
  1028. func TestContextAbortWithStatusJSON(t *testing.T) {
  1029. w := httptest.NewRecorder()
  1030. c, _ := CreateTestContext(w)
  1031. c.index = 4
  1032. in := new(testJSONAbortMsg)
  1033. in.Bar = "barValue"
  1034. in.Foo = "fooValue"
  1035. c.AbortWithStatusJSON(http.StatusUnsupportedMediaType, in)
  1036. assert.Equal(t, abortIndex, c.index)
  1037. assert.Equal(t, http.StatusUnsupportedMediaType, c.Writer.Status())
  1038. assert.Equal(t, http.StatusUnsupportedMediaType, w.Code)
  1039. assert.True(t, c.IsAborted())
  1040. contentType := w.Header().Get("Content-Type")
  1041. assert.Equal(t, "application/json; charset=utf-8", contentType)
  1042. buf := new(bytes.Buffer)
  1043. _, err := buf.ReadFrom(w.Body)
  1044. assert.NoError(t, err)
  1045. jsonStringBody := buf.String()
  1046. assert.Equal(t, fmt.Sprint("{\"foo\":\"fooValue\",\"bar\":\"barValue\"}"), jsonStringBody)
  1047. }
  1048. func TestContextError(t *testing.T) {
  1049. c, _ := CreateTestContext(httptest.NewRecorder())
  1050. assert.Empty(t, c.Errors)
  1051. firstErr := errors.New("first error")
  1052. c.Error(firstErr) // nolint: errcheck
  1053. assert.Len(t, c.Errors, 1)
  1054. assert.Equal(t, "Error #01: first error\n", c.Errors.String())
  1055. secondErr := errors.New("second error")
  1056. c.Error(&Error{ // nolint: errcheck
  1057. Err: secondErr,
  1058. Meta: "some data 2",
  1059. Type: ErrorTypePublic,
  1060. })
  1061. assert.Len(t, c.Errors, 2)
  1062. assert.Equal(t, firstErr, c.Errors[0].Err)
  1063. assert.Nil(t, c.Errors[0].Meta)
  1064. assert.Equal(t, ErrorTypePrivate, c.Errors[0].Type)
  1065. assert.Equal(t, secondErr, c.Errors[1].Err)
  1066. assert.Equal(t, "some data 2", c.Errors[1].Meta)
  1067. assert.Equal(t, ErrorTypePublic, c.Errors[1].Type)
  1068. assert.Equal(t, c.Errors.Last(), c.Errors[1])
  1069. defer func() {
  1070. if recover() == nil {
  1071. t.Error("didn't panic")
  1072. }
  1073. }()
  1074. c.Error(nil) // nolint: errcheck
  1075. }
  1076. func TestContextTypedError(t *testing.T) {
  1077. c, _ := CreateTestContext(httptest.NewRecorder())
  1078. c.Error(errors.New("externo 0")).SetType(ErrorTypePublic) // nolint: errcheck
  1079. c.Error(errors.New("interno 0")).SetType(ErrorTypePrivate) // nolint: errcheck
  1080. for _, err := range c.Errors.ByType(ErrorTypePublic) {
  1081. assert.Equal(t, ErrorTypePublic, err.Type)
  1082. }
  1083. for _, err := range c.Errors.ByType(ErrorTypePrivate) {
  1084. assert.Equal(t, ErrorTypePrivate, err.Type)
  1085. }
  1086. assert.Equal(t, []string{"externo 0", "interno 0"}, c.Errors.Errors())
  1087. }
  1088. func TestContextAbortWithError(t *testing.T) {
  1089. w := httptest.NewRecorder()
  1090. c, _ := CreateTestContext(w)
  1091. c.AbortWithError(http.StatusUnauthorized, errors.New("bad input")).SetMeta("some input") // nolint: errcheck
  1092. assert.Equal(t, http.StatusUnauthorized, w.Code)
  1093. assert.Equal(t, abortIndex, c.index)
  1094. assert.True(t, c.IsAborted())
  1095. }
  1096. func TestContextClientIP(t *testing.T) {
  1097. c, _ := CreateTestContext(httptest.NewRecorder())
  1098. c.Request, _ = http.NewRequest("POST", "/", nil)
  1099. c.Request.Header.Set("X-Real-IP", " 10.10.10.10 ")
  1100. c.Request.Header.Set("X-Forwarded-For", " 20.20.20.20, 30.30.30.30")
  1101. c.Request.Header.Set("X-Appengine-Remote-Addr", "50.50.50.50")
  1102. c.Request.RemoteAddr = " 40.40.40.40:42123 "
  1103. assert.Equal(t, "20.20.20.20", c.ClientIP())
  1104. c.Request.Header.Del("X-Forwarded-For")
  1105. assert.Equal(t, "10.10.10.10", c.ClientIP())
  1106. c.Request.Header.Set("X-Forwarded-For", "30.30.30.30 ")
  1107. assert.Equal(t, "30.30.30.30", c.ClientIP())
  1108. c.Request.Header.Del("X-Forwarded-For")
  1109. c.Request.Header.Del("X-Real-IP")
  1110. c.engine.AppEngine = true
  1111. assert.Equal(t, "50.50.50.50", c.ClientIP())
  1112. c.Request.Header.Del("X-Appengine-Remote-Addr")
  1113. assert.Equal(t, "40.40.40.40", c.ClientIP())
  1114. // no port
  1115. c.Request.RemoteAddr = "50.50.50.50"
  1116. assert.Empty(t, c.ClientIP())
  1117. }
  1118. func TestContextContentType(t *testing.T) {
  1119. c, _ := CreateTestContext(httptest.NewRecorder())
  1120. c.Request, _ = http.NewRequest("POST", "/", nil)
  1121. c.Request.Header.Set("Content-Type", "application/json; charset=utf-8")
  1122. assert.Equal(t, "application/json", c.ContentType())
  1123. }
  1124. func TestContextAutoBindJSON(t *testing.T) {
  1125. c, _ := CreateTestContext(httptest.NewRecorder())
  1126. c.Request, _ = http.NewRequest("POST", "/", bytes.NewBufferString("{\"foo\":\"bar\", \"bar\":\"foo\"}"))
  1127. c.Request.Header.Add("Content-Type", MIMEJSON)
  1128. var obj struct {
  1129. Foo string `json:"foo"`
  1130. Bar string `json:"bar"`
  1131. }
  1132. assert.NoError(t, c.Bind(&obj))
  1133. assert.Equal(t, "foo", obj.Bar)
  1134. assert.Equal(t, "bar", obj.Foo)
  1135. assert.Empty(t, c.Errors)
  1136. }
  1137. func TestContextBindWithJSON(t *testing.T) {
  1138. w := httptest.NewRecorder()
  1139. c, _ := CreateTestContext(w)
  1140. c.Request, _ = http.NewRequest("POST", "/", bytes.NewBufferString("{\"foo\":\"bar\", \"bar\":\"foo\"}"))
  1141. c.Request.Header.Add("Content-Type", MIMEXML) // set fake content-type
  1142. var obj struct {
  1143. Foo string `json:"foo"`
  1144. Bar string `json:"bar"`
  1145. }
  1146. assert.NoError(t, c.BindJSON(&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 TestContextBindWithXML(t *testing.T) {
  1152. w := httptest.NewRecorder()
  1153. c, _ := CreateTestContext(w)
  1154. c.Request, _ = http.NewRequest("POST", "/", bytes.NewBufferString(`<?xml version="1.0" encoding="UTF-8"?>
  1155. <root>
  1156. <foo>FOO</foo>
  1157. <bar>BAR</bar>
  1158. </root>`))
  1159. c.Request.Header.Add("Content-Type", MIMEXML) // set fake content-type
  1160. var obj struct {
  1161. Foo string `xml:"foo"`
  1162. Bar string `xml:"bar"`
  1163. }
  1164. assert.NoError(t, c.BindXML(&obj))
  1165. assert.Equal(t, "FOO", obj.Foo)
  1166. assert.Equal(t, "BAR", obj.Bar)
  1167. assert.Equal(t, 0, w.Body.Len())
  1168. }
  1169. func TestContextBindHeader(t *testing.T) {
  1170. w := httptest.NewRecorder()
  1171. c, _ := CreateTestContext(w)
  1172. c.Request, _ = http.NewRequest("POST", "/", nil)
  1173. c.Request.Header.Add("rate", "8000")
  1174. c.Request.Header.Add("domain", "music")
  1175. c.Request.Header.Add("limit", "1000")
  1176. var testHeader struct {
  1177. Rate int `header:"Rate"`
  1178. Domain string `header:"Domain"`
  1179. Limit int `header:"limit"`
  1180. }
  1181. assert.NoError(t, c.BindHeader(&testHeader))
  1182. assert.Equal(t, 8000, testHeader.Rate)
  1183. assert.Equal(t, "music", testHeader.Domain)
  1184. assert.Equal(t, 1000, testHeader.Limit)
  1185. assert.Equal(t, 0, w.Body.Len())
  1186. }
  1187. func TestContextBindWithQuery(t *testing.T) {
  1188. w := httptest.NewRecorder()
  1189. c, _ := CreateTestContext(w)
  1190. c.Request, _ = http.NewRequest("POST", "/?foo=bar&bar=foo", bytes.NewBufferString("foo=unused"))
  1191. var obj struct {
  1192. Foo string `form:"foo"`
  1193. Bar string `form:"bar"`
  1194. }
  1195. assert.NoError(t, c.BindQuery(&obj))
  1196. assert.Equal(t, "foo", obj.Bar)
  1197. assert.Equal(t, "bar", obj.Foo)
  1198. assert.Equal(t, 0, w.Body.Len())
  1199. }
  1200. func TestContextBindWithYAML(t *testing.T) {
  1201. w := httptest.NewRecorder()
  1202. c, _ := CreateTestContext(w)
  1203. c.Request, _ = http.NewRequest("POST", "/", bytes.NewBufferString("foo: bar\nbar: foo"))
  1204. c.Request.Header.Add("Content-Type", MIMEXML) // set fake content-type
  1205. var obj struct {
  1206. Foo string `yaml:"foo"`
  1207. Bar string `yaml:"bar"`
  1208. }
  1209. assert.NoError(t, c.BindYAML(&obj))
  1210. assert.Equal(t, "foo", obj.Bar)
  1211. assert.Equal(t, "bar", obj.Foo)
  1212. assert.Equal(t, 0, w.Body.Len())
  1213. }
  1214. func TestContextBadAutoBind(t *testing.T) {
  1215. w := httptest.NewRecorder()
  1216. c, _ := CreateTestContext(w)
  1217. c.Request, _ = http.NewRequest("POST", "http://example.com", bytes.NewBufferString("\"foo\":\"bar\", \"bar\":\"foo\"}"))
  1218. c.Request.Header.Add("Content-Type", MIMEJSON)
  1219. var obj struct {
  1220. Foo string `json:"foo"`
  1221. Bar string `json:"bar"`
  1222. }
  1223. assert.False(t, c.IsAborted())
  1224. assert.Error(t, c.Bind(&obj))
  1225. c.Writer.WriteHeaderNow()
  1226. assert.Empty(t, obj.Bar)
  1227. assert.Empty(t, obj.Foo)
  1228. assert.Equal(t, http.StatusBadRequest, w.Code)
  1229. assert.True(t, c.IsAborted())
  1230. }
  1231. func TestContextAutoShouldBindJSON(t *testing.T) {
  1232. c, _ := CreateTestContext(httptest.NewRecorder())
  1233. c.Request, _ = http.NewRequest("POST", "/", bytes.NewBufferString("{\"foo\":\"bar\", \"bar\":\"foo\"}"))
  1234. c.Request.Header.Add("Content-Type", MIMEJSON)
  1235. var obj struct {
  1236. Foo string `json:"foo"`
  1237. Bar string `json:"bar"`
  1238. }
  1239. assert.NoError(t, c.ShouldBind(&obj))
  1240. assert.Equal(t, "foo", obj.Bar)
  1241. assert.Equal(t, "bar", obj.Foo)
  1242. assert.Empty(t, c.Errors)
  1243. }
  1244. func TestContextShouldBindWithJSON(t *testing.T) {
  1245. w := httptest.NewRecorder()
  1246. c, _ := CreateTestContext(w)
  1247. c.Request, _ = http.NewRequest("POST", "/", bytes.NewBufferString("{\"foo\":\"bar\", \"bar\":\"foo\"}"))
  1248. c.Request.Header.Add("Content-Type", MIMEXML) // set fake content-type
  1249. var obj struct {
  1250. Foo string `json:"foo"`
  1251. Bar string `json:"bar"`
  1252. }
  1253. assert.NoError(t, c.ShouldBindJSON(&obj))
  1254. assert.Equal(t, "foo", obj.Bar)
  1255. assert.Equal(t, "bar", obj.Foo)
  1256. assert.Equal(t, 0, w.Body.Len())
  1257. }
  1258. func TestContextShouldBindWithXML(t *testing.T) {
  1259. w := httptest.NewRecorder()
  1260. c, _ := CreateTestContext(w)
  1261. c.Request, _ = http.NewRequest("POST", "/", bytes.NewBufferString(`<?xml version="1.0" encoding="UTF-8"?>
  1262. <root>
  1263. <foo>FOO</foo>
  1264. <bar>BAR</bar>
  1265. </root>`))
  1266. c.Request.Header.Add("Content-Type", MIMEXML) // set fake content-type
  1267. var obj struct {
  1268. Foo string `xml:"foo"`
  1269. Bar string `xml:"bar"`
  1270. }
  1271. assert.NoError(t, c.ShouldBindXML(&obj))
  1272. assert.Equal(t, "FOO", obj.Foo)
  1273. assert.Equal(t, "BAR", obj.Bar)
  1274. assert.Equal(t, 0, w.Body.Len())
  1275. }
  1276. func TestContextShouldBindHeader(t *testing.T) {
  1277. w := httptest.NewRecorder()
  1278. c, _ := CreateTestContext(w)
  1279. c.Request, _ = http.NewRequest("POST", "/", nil)
  1280. c.Request.Header.Add("rate", "8000")
  1281. c.Request.Header.Add("domain", "music")
  1282. c.Request.Header.Add("limit", "1000")
  1283. var testHeader struct {
  1284. Rate int `header:"Rate"`
  1285. Domain string `header:"Domain"`
  1286. Limit int `header:"limit"`
  1287. }
  1288. assert.NoError(t, c.ShouldBindHeader(&testHeader))
  1289. assert.Equal(t, 8000, testHeader.Rate)
  1290. assert.Equal(t, "music", testHeader.Domain)
  1291. assert.Equal(t, 1000, testHeader.Limit)
  1292. assert.Equal(t, 0, w.Body.Len())
  1293. }
  1294. func TestContextShouldBindWithQuery(t *testing.T) {
  1295. w := httptest.NewRecorder()
  1296. c, _ := CreateTestContext(w)
  1297. c.Request, _ = http.NewRequest("POST", "/?foo=bar&bar=foo&Foo=bar1&Bar=foo1", bytes.NewBufferString("foo=unused"))
  1298. var obj struct {
  1299. Foo string `form:"foo"`
  1300. Bar string `form:"bar"`
  1301. Foo1 string `form:"Foo"`
  1302. Bar1 string `form:"Bar"`
  1303. }
  1304. assert.NoError(t, c.ShouldBindQuery(&obj))
  1305. assert.Equal(t, "foo", obj.Bar)
  1306. assert.Equal(t, "bar", obj.Foo)
  1307. assert.Equal(t, "foo1", obj.Bar1)
  1308. assert.Equal(t, "bar1", obj.Foo1)
  1309. assert.Equal(t, 0, w.Body.Len())
  1310. }
  1311. func TestContextShouldBindWithYAML(t *testing.T) {
  1312. w := httptest.NewRecorder()
  1313. c, _ := CreateTestContext(w)
  1314. c.Request, _ = http.NewRequest("POST", "/", bytes.NewBufferString("foo: bar\nbar: foo"))
  1315. c.Request.Header.Add("Content-Type", MIMEXML) // set fake content-type
  1316. var obj struct {
  1317. Foo string `yaml:"foo"`
  1318. Bar string `yaml:"bar"`
  1319. }
  1320. assert.NoError(t, c.ShouldBindYAML(&obj))
  1321. assert.Equal(t, "foo", obj.Bar)
  1322. assert.Equal(t, "bar", obj.Foo)
  1323. assert.Equal(t, 0, w.Body.Len())
  1324. }
  1325. func TestContextBadAutoShouldBind(t *testing.T) {
  1326. w := httptest.NewRecorder()
  1327. c, _ := CreateTestContext(w)
  1328. c.Request, _ = http.NewRequest("POST", "http://example.com", bytes.NewBufferString("\"foo\":\"bar\", \"bar\":\"foo\"}"))
  1329. c.Request.Header.Add("Content-Type", MIMEJSON)
  1330. var obj struct {
  1331. Foo string `json:"foo"`
  1332. Bar string `json:"bar"`
  1333. }
  1334. assert.False(t, c.IsAborted())
  1335. assert.Error(t, c.ShouldBind(&obj))
  1336. assert.Empty(t, obj.Bar)
  1337. assert.Empty(t, obj.Foo)
  1338. assert.False(t, c.IsAborted())
  1339. }
  1340. func TestContextShouldBindBodyWith(t *testing.T) {
  1341. type typeA struct {
  1342. Foo string `json:"foo" xml:"foo" binding:"required"`
  1343. }
  1344. type typeB struct {
  1345. Bar string `json:"bar" xml:"bar" binding:"required"`
  1346. }
  1347. for _, tt := range []struct {
  1348. name string
  1349. bindingA, bindingB binding.BindingBody
  1350. bodyA, bodyB string
  1351. }{
  1352. {
  1353. name: "JSON & JSON",
  1354. bindingA: binding.JSON,
  1355. bindingB: binding.JSON,
  1356. bodyA: `{"foo":"FOO"}`,
  1357. bodyB: `{"bar":"BAR"}`,
  1358. },
  1359. {
  1360. name: "JSON & XML",
  1361. bindingA: binding.JSON,
  1362. bindingB: binding.XML,
  1363. bodyA: `{"foo":"FOO"}`,
  1364. bodyB: `<?xml version="1.0" encoding="UTF-8"?>
  1365. <root>
  1366. <bar>BAR</bar>
  1367. </root>`,
  1368. },
  1369. {
  1370. name: "XML & XML",
  1371. bindingA: binding.XML,
  1372. bindingB: binding.XML,
  1373. bodyA: `<?xml version="1.0" encoding="UTF-8"?>
  1374. <root>
  1375. <foo>FOO</foo>
  1376. </root>`,
  1377. bodyB: `<?xml version="1.0" encoding="UTF-8"?>
  1378. <root>
  1379. <bar>BAR</bar>
  1380. </root>`,
  1381. },
  1382. } {
  1383. t.Logf("testing: %s", tt.name)
  1384. // bodyA to typeA and typeB
  1385. {
  1386. w := httptest.NewRecorder()
  1387. c, _ := CreateTestContext(w)
  1388. c.Request, _ = http.NewRequest(
  1389. "POST", "http://example.com", bytes.NewBufferString(tt.bodyA),
  1390. )
  1391. // When it binds to typeA and typeB, it finds the body is
  1392. // not typeB but typeA.
  1393. objA := typeA{}
  1394. assert.NoError(t, c.ShouldBindBodyWith(&objA, tt.bindingA))
  1395. assert.Equal(t, typeA{"FOO"}, objA)
  1396. objB := typeB{}
  1397. assert.Error(t, c.ShouldBindBodyWith(&objB, tt.bindingB))
  1398. assert.NotEqual(t, typeB{"BAR"}, objB)
  1399. }
  1400. // bodyB to typeA and typeB
  1401. {
  1402. // When it binds to typeA and typeB, it finds the body is
  1403. // not typeA but typeB.
  1404. w := httptest.NewRecorder()
  1405. c, _ := CreateTestContext(w)
  1406. c.Request, _ = http.NewRequest(
  1407. "POST", "http://example.com", bytes.NewBufferString(tt.bodyB),
  1408. )
  1409. objA := typeA{}
  1410. assert.Error(t, c.ShouldBindBodyWith(&objA, tt.bindingA))
  1411. assert.NotEqual(t, typeA{"FOO"}, objA)
  1412. objB := typeB{}
  1413. assert.NoError(t, c.ShouldBindBodyWith(&objB, tt.bindingB))
  1414. assert.Equal(t, typeB{"BAR"}, objB)
  1415. }
  1416. }
  1417. }
  1418. func TestContextGolangContext(t *testing.T) {
  1419. c, _ := CreateTestContext(httptest.NewRecorder())
  1420. c.Request, _ = http.NewRequest("POST", "/", bytes.NewBufferString("{\"foo\":\"bar\", \"bar\":\"foo\"}"))
  1421. assert.NoError(t, c.Err())
  1422. assert.Nil(t, c.Done())
  1423. ti, ok := c.Deadline()
  1424. assert.Equal(t, ti, time.Time{})
  1425. assert.False(t, ok)
  1426. assert.Equal(t, c.Value(0), c.Request)
  1427. assert.Nil(t, c.Value("foo"))
  1428. c.Set("foo", "bar")
  1429. assert.Equal(t, "bar", c.Value("foo"))
  1430. assert.Nil(t, c.Value(1))
  1431. }
  1432. func TestWebsocketsRequired(t *testing.T) {
  1433. // Example request from spec: https://tools.ietf.org/html/rfc6455#section-1.2
  1434. c, _ := CreateTestContext(httptest.NewRecorder())
  1435. c.Request, _ = http.NewRequest("GET", "/chat", nil)
  1436. c.Request.Header.Set("Host", "server.example.com")
  1437. c.Request.Header.Set("Upgrade", "websocket")
  1438. c.Request.Header.Set("Connection", "Upgrade")
  1439. c.Request.Header.Set("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==")
  1440. c.Request.Header.Set("Origin", "http://example.com")
  1441. c.Request.Header.Set("Sec-WebSocket-Protocol", "chat, superchat")
  1442. c.Request.Header.Set("Sec-WebSocket-Version", "13")
  1443. assert.True(t, c.IsWebsocket())
  1444. // Normal request, no websocket required.
  1445. c, _ = CreateTestContext(httptest.NewRecorder())
  1446. c.Request, _ = http.NewRequest("GET", "/chat", nil)
  1447. c.Request.Header.Set("Host", "server.example.com")
  1448. assert.False(t, c.IsWebsocket())
  1449. }
  1450. func TestGetRequestHeaderValue(t *testing.T) {
  1451. c, _ := CreateTestContext(httptest.NewRecorder())
  1452. c.Request, _ = http.NewRequest("GET", "/chat", nil)
  1453. c.Request.Header.Set("Gin-Version", "1.0.0")
  1454. assert.Equal(t, "1.0.0", c.GetHeader("Gin-Version"))
  1455. assert.Empty(t, c.GetHeader("Connection"))
  1456. }
  1457. func TestContextGetRawData(t *testing.T) {
  1458. c, _ := CreateTestContext(httptest.NewRecorder())
  1459. body := bytes.NewBufferString("Fetch binary post data")
  1460. c.Request, _ = http.NewRequest("POST", "/", body)
  1461. c.Request.Header.Add("Content-Type", MIMEPOSTForm)
  1462. data, err := c.GetRawData()
  1463. assert.Nil(t, err)
  1464. assert.Equal(t, "Fetch binary post data", string(data))
  1465. }
  1466. func TestContextRenderDataFromReader(t *testing.T) {
  1467. w := httptest.NewRecorder()
  1468. c, _ := CreateTestContext(w)
  1469. body := "#!PNG some raw data"
  1470. reader := strings.NewReader(body)
  1471. contentLength := int64(len(body))
  1472. contentType := "image/png"
  1473. extraHeaders := map[string]string{"Content-Disposition": `attachment; filename="gopher.png"`}
  1474. c.DataFromReader(http.StatusOK, contentLength, contentType, reader, extraHeaders)
  1475. assert.Equal(t, http.StatusOK, w.Code)
  1476. assert.Equal(t, body, w.Body.String())
  1477. assert.Equal(t, contentType, w.Header().Get("Content-Type"))
  1478. assert.Equal(t, fmt.Sprintf("%d", contentLength), w.Header().Get("Content-Length"))
  1479. assert.Equal(t, extraHeaders["Content-Disposition"], w.Header().Get("Content-Disposition"))
  1480. }
  1481. func TestContextRenderDataFromReaderNoHeaders(t *testing.T) {
  1482. w := httptest.NewRecorder()
  1483. c, _ := CreateTestContext(w)
  1484. body := "#!PNG some raw data"
  1485. reader := strings.NewReader(body)
  1486. contentLength := int64(len(body))
  1487. contentType := "image/png"
  1488. c.DataFromReader(http.StatusOK, contentLength, contentType, reader, nil)
  1489. assert.Equal(t, http.StatusOK, w.Code)
  1490. assert.Equal(t, body, w.Body.String())
  1491. assert.Equal(t, contentType, w.Header().Get("Content-Type"))
  1492. assert.Equal(t, fmt.Sprintf("%d", contentLength), w.Header().Get("Content-Length"))
  1493. }
  1494. type TestResponseRecorder struct {
  1495. *httptest.ResponseRecorder
  1496. closeChannel chan bool
  1497. }
  1498. func (r *TestResponseRecorder) CloseNotify() <-chan bool {
  1499. return r.closeChannel
  1500. }
  1501. func (r *TestResponseRecorder) closeClient() {
  1502. r.closeChannel <- true
  1503. }
  1504. func CreateTestResponseRecorder() *TestResponseRecorder {
  1505. return &TestResponseRecorder{
  1506. httptest.NewRecorder(),
  1507. make(chan bool, 1),
  1508. }
  1509. }
  1510. func TestContextStream(t *testing.T) {
  1511. w := CreateTestResponseRecorder()
  1512. c, _ := CreateTestContext(w)
  1513. stopStream := true
  1514. c.Stream(func(w io.Writer) bool {
  1515. defer func() {
  1516. stopStream = false
  1517. }()
  1518. _, err := w.Write([]byte("test"))
  1519. assert.NoError(t, err)
  1520. return stopStream
  1521. })
  1522. assert.Equal(t, "testtest", w.Body.String())
  1523. }
  1524. func TestContextStreamWithClientGone(t *testing.T) {
  1525. w := CreateTestResponseRecorder()
  1526. c, _ := CreateTestContext(w)
  1527. c.Stream(func(writer io.Writer) bool {
  1528. defer func() {
  1529. w.closeClient()
  1530. }()
  1531. _, err := writer.Write([]byte("test"))
  1532. assert.NoError(t, err)
  1533. return true
  1534. })
  1535. assert.Equal(t, "test", w.Body.String())
  1536. }
  1537. func TestContextResetInHandler(t *testing.T) {
  1538. w := CreateTestResponseRecorder()
  1539. c, _ := CreateTestContext(w)
  1540. c.handlers = []HandlerFunc{
  1541. func(c *Context) { c.reset() },
  1542. }
  1543. assert.NotPanics(t, func() {
  1544. c.Next()
  1545. })
  1546. }
  1547. func TestRaceParamsContextCopy(t *testing.T) {
  1548. DefaultWriter = os.Stdout
  1549. router := Default()
  1550. nameGroup := router.Group("/:name")
  1551. var wg sync.WaitGroup
  1552. wg.Add(2)
  1553. {
  1554. nameGroup.GET("/api", func(c *Context) {
  1555. go func(c *Context, param string) {
  1556. defer wg.Done()
  1557. // First assert must be executed after the second request
  1558. time.Sleep(50 * time.Millisecond)
  1559. assert.Equal(t, c.Param("name"), param)
  1560. }(c.Copy(), c.Param("name"))
  1561. })
  1562. }
  1563. performRequest(router, "GET", "/name1/api")
  1564. performRequest(router, "GET", "/name2/api")
  1565. wg.Wait()
  1566. }
  1567. func TestContextWithKeysMutex(t *testing.T) {
  1568. c := &Context{}
  1569. c.Set("foo", "bar")
  1570. value, err := c.Get("foo")
  1571. assert.Equal(t, "bar", value)
  1572. assert.True(t, err)
  1573. value, err = c.Get("foo2")
  1574. assert.Nil(t, value)
  1575. assert.False(t, err)
  1576. }