context_test.go 38 KB

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