context_test.go 45 KB

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