context_test.go 44 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738739740741742743744745746747748749750751752753754755756757758759760761762763764765766767768769770771772773774775776777778779780781782783784785786787788789790791792793794795796797798799800801802803804805806807808809810811812813814815816817818819820821822823824825826827828829830831832833834835836837838839840841842843844845846847848849850851852853854855856857858859860861862863864865866867868869870871872873874875876877878879880881882883884885886887888889890891892893894895896897898899900901902903904905906907908909910911912913914915916917918919920921922923924925926927928929930931932933934935936937938939940941942943944945946947948949950951952953954955956957958959960961962963964965966967968969970971972973974975976977978979980981982983984985986987988989990991992993994995996997998999100010011002100310041005100610071008100910101011101210131014101510161017101810191020102110221023102410251026102710281029103010311032103310341035103610371038103910401041104210431044104510461047104810491050105110521053105410551056105710581059106010611062106310641065106610671068106910701071107210731074107510761077107810791080108110821083108410851086108710881089109010911092109310941095109610971098109911001101110211031104110511061107110811091110111111121113111411151116111711181119112011211122112311241125112611271128112911301131113211331134113511361137113811391140114111421143114411451146114711481149115011511152115311541155115611571158115911601161116211631164116511661167116811691170117111721173117411751176117711781179118011811182118311841185118611871188118911901191119211931194119511961197119811991200120112021203120412051206120712081209121012111212121312141215121612171218121912201221122212231224122512261227122812291230123112321233123412351236123712381239124012411242124312441245124612471248124912501251125212531254125512561257125812591260126112621263126412651266126712681269127012711272127312741275127612771278127912801281128212831284128512861287128812891290129112921293129412951296129712981299130013011302130313041305130613071308130913101311131213131314131513161317131813191320132113221323132413251326132713281329133013311332133313341335133613371338133913401341134213431344134513461347134813491350135113521353135413551356135713581359136013611362136313641365136613671368136913701371137213731374137513761377137813791380138113821383138413851386138713881389139013911392139313941395139613971398139914001401140214031404140514061407140814091410141114121413141414151416141714181419142014211422142314241425142614271428142914301431143214331434143514361437143814391440144114421443144414451446144714481449145014511452145314541455145614571458145914601461146214631464146514661467146814691470147114721473
  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. // Tests that the response executes the templates
  566. // and responds with Content-Type set to text/html
  567. func TestContextRenderHTML(t *testing.T) {
  568. w := httptest.NewRecorder()
  569. c, router := CreateTestContext(w)
  570. templ := template.Must(template.New("t").Parse(`Hello {{.name}}`))
  571. router.SetHTMLTemplate(templ)
  572. c.HTML(201, "t", H{"name": "alexandernyquist"})
  573. assert.Equal(t, 201, w.Code)
  574. assert.Equal(t, "Hello alexandernyquist", w.Body.String())
  575. assert.Equal(t, "text/html; charset=utf-8", w.HeaderMap.Get("Content-Type"))
  576. }
  577. func TestContextRenderHTML2(t *testing.T) {
  578. w := httptest.NewRecorder()
  579. c, router := CreateTestContext(w)
  580. // print debug warning log when Engine.trees > 0
  581. router.addRoute("GET", "/", HandlersChain{func(_ *Context) {}})
  582. assert.Len(t, router.trees, 1)
  583. var b bytes.Buffer
  584. setup(&b)
  585. defer teardown()
  586. templ := template.Must(template.New("t").Parse(`Hello {{.name}}`))
  587. router.SetHTMLTemplate(templ)
  588. 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())
  589. c.HTML(201, "t", H{"name": "alexandernyquist"})
  590. assert.Equal(t, 201, w.Code)
  591. assert.Equal(t, "Hello alexandernyquist", w.Body.String())
  592. assert.Equal(t, "text/html; charset=utf-8", w.HeaderMap.Get("Content-Type"))
  593. }
  594. // Tests that no HTML is rendered if code is 204
  595. func TestContextRenderNoContentHTML(t *testing.T) {
  596. w := httptest.NewRecorder()
  597. c, router := CreateTestContext(w)
  598. templ := template.Must(template.New("t").Parse(`Hello {{.name}}`))
  599. router.SetHTMLTemplate(templ)
  600. c.HTML(204, "t", H{"name": "alexandernyquist"})
  601. assert.Equal(t, 204, w.Code)
  602. assert.Empty(t, w.Body.String())
  603. assert.Equal(t, "text/html; charset=utf-8", w.HeaderMap.Get("Content-Type"))
  604. }
  605. // TestContextXML tests that the response is serialized as XML
  606. // and Content-Type is set to application/xml
  607. func TestContextRenderXML(t *testing.T) {
  608. w := httptest.NewRecorder()
  609. c, _ := CreateTestContext(w)
  610. c.XML(201, H{"foo": "bar"})
  611. assert.Equal(t, 201, w.Code)
  612. assert.Equal(t, "<map><foo>bar</foo></map>", w.Body.String())
  613. assert.Equal(t, "application/xml; charset=utf-8", w.HeaderMap.Get("Content-Type"))
  614. }
  615. // Tests that no XML is rendered if code is 204
  616. func TestContextRenderNoContentXML(t *testing.T) {
  617. w := httptest.NewRecorder()
  618. c, _ := CreateTestContext(w)
  619. c.XML(204, H{"foo": "bar"})
  620. assert.Equal(t, 204, w.Code)
  621. assert.Empty(t, w.Body.String())
  622. assert.Equal(t, "application/xml; charset=utf-8", w.HeaderMap.Get("Content-Type"))
  623. }
  624. // TestContextString tests that the response is returned
  625. // with Content-Type set to text/plain
  626. func TestContextRenderString(t *testing.T) {
  627. w := httptest.NewRecorder()
  628. c, _ := CreateTestContext(w)
  629. c.String(201, "test %s %d", "string", 2)
  630. assert.Equal(t, 201, w.Code)
  631. assert.Equal(t, "test string 2", w.Body.String())
  632. assert.Equal(t, "text/plain; charset=utf-8", w.HeaderMap.Get("Content-Type"))
  633. }
  634. // Tests that no String is rendered if code is 204
  635. func TestContextRenderNoContentString(t *testing.T) {
  636. w := httptest.NewRecorder()
  637. c, _ := CreateTestContext(w)
  638. c.String(204, "test %s %d", "string", 2)
  639. assert.Equal(t, 204, w.Code)
  640. assert.Empty(t, w.Body.String())
  641. assert.Equal(t, "text/plain; charset=utf-8", w.HeaderMap.Get("Content-Type"))
  642. }
  643. // TestContextString tests that the response is returned
  644. // with Content-Type set to text/html
  645. func TestContextRenderHTMLString(t *testing.T) {
  646. w := httptest.NewRecorder()
  647. c, _ := CreateTestContext(w)
  648. c.Header("Content-Type", "text/html; charset=utf-8")
  649. c.String(201, "<html>%s %d</html>", "string", 3)
  650. assert.Equal(t, 201, w.Code)
  651. assert.Equal(t, "<html>string 3</html>", w.Body.String())
  652. assert.Equal(t, "text/html; charset=utf-8", w.HeaderMap.Get("Content-Type"))
  653. }
  654. // Tests that no HTML String is rendered if code is 204
  655. func TestContextRenderNoContentHTMLString(t *testing.T) {
  656. w := httptest.NewRecorder()
  657. c, _ := CreateTestContext(w)
  658. c.Header("Content-Type", "text/html; charset=utf-8")
  659. c.String(204, "<html>%s %d</html>", "string", 3)
  660. assert.Equal(t, 204, w.Code)
  661. assert.Empty(t, w.Body.String())
  662. assert.Equal(t, "text/html; charset=utf-8", w.HeaderMap.Get("Content-Type"))
  663. }
  664. // TestContextData tests that the response can be written from `bytesting`
  665. // with specified MIME type
  666. func TestContextRenderData(t *testing.T) {
  667. w := httptest.NewRecorder()
  668. c, _ := CreateTestContext(w)
  669. c.Data(201, "text/csv", []byte(`foo,bar`))
  670. assert.Equal(t, 201, w.Code)
  671. assert.Equal(t, "foo,bar", w.Body.String())
  672. assert.Equal(t, "text/csv", w.HeaderMap.Get("Content-Type"))
  673. }
  674. // Tests that no Custom Data is rendered if code is 204
  675. func TestContextRenderNoContentData(t *testing.T) {
  676. w := httptest.NewRecorder()
  677. c, _ := CreateTestContext(w)
  678. c.Data(204, "text/csv", []byte(`foo,bar`))
  679. assert.Equal(t, 204, w.Code)
  680. assert.Empty(t, w.Body.String())
  681. assert.Equal(t, "text/csv", w.HeaderMap.Get("Content-Type"))
  682. }
  683. func TestContextRenderSSE(t *testing.T) {
  684. w := httptest.NewRecorder()
  685. c, _ := CreateTestContext(w)
  686. c.SSEvent("float", 1.5)
  687. c.Render(-1, sse.Event{
  688. Id: "123",
  689. Data: "text",
  690. })
  691. c.SSEvent("chat", H{
  692. "foo": "bar",
  693. "bar": "foo",
  694. })
  695. 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))
  696. }
  697. func TestContextRenderFile(t *testing.T) {
  698. w := httptest.NewRecorder()
  699. c, _ := CreateTestContext(w)
  700. c.Request, _ = http.NewRequest("GET", "/", nil)
  701. c.File("./gin.go")
  702. assert.Equal(t, 200, w.Code)
  703. assert.Contains(t, w.Body.String(), "func New() *Engine {")
  704. assert.Equal(t, "text/plain; charset=utf-8", w.HeaderMap.Get("Content-Type"))
  705. }
  706. // TestContextRenderYAML tests that the response is serialized as YAML
  707. // and Content-Type is set to application/x-yaml
  708. func TestContextRenderYAML(t *testing.T) {
  709. w := httptest.NewRecorder()
  710. c, _ := CreateTestContext(w)
  711. c.YAML(201, H{"foo": "bar"})
  712. assert.Equal(t, 201, w.Code)
  713. assert.Equal(t, "foo: bar\n", w.Body.String())
  714. assert.Equal(t, "application/x-yaml; charset=utf-8", w.HeaderMap.Get("Content-Type"))
  715. }
  716. func TestContextHeaders(t *testing.T) {
  717. c, _ := CreateTestContext(httptest.NewRecorder())
  718. c.Header("Content-Type", "text/plain")
  719. c.Header("X-Custom", "value")
  720. assert.Equal(t, "text/plain", c.Writer.Header().Get("Content-Type"))
  721. assert.Equal(t, "value", c.Writer.Header().Get("X-Custom"))
  722. c.Header("Content-Type", "text/html")
  723. c.Header("X-Custom", "")
  724. assert.Equal(t, "text/html", c.Writer.Header().Get("Content-Type"))
  725. _, exist := c.Writer.Header()["X-Custom"]
  726. assert.False(t, exist)
  727. }
  728. // TODO
  729. func TestContextRenderRedirectWithRelativePath(t *testing.T) {
  730. w := httptest.NewRecorder()
  731. c, _ := CreateTestContext(w)
  732. c.Request, _ = http.NewRequest("POST", "http://example.com", nil)
  733. assert.Panics(t, func() { c.Redirect(299, "/new_path") })
  734. assert.Panics(t, func() { c.Redirect(309, "/new_path") })
  735. c.Redirect(301, "/path")
  736. c.Writer.WriteHeaderNow()
  737. assert.Equal(t, 301, w.Code)
  738. assert.Equal(t, "/path", w.Header().Get("Location"))
  739. }
  740. func TestContextRenderRedirectWithAbsolutePath(t *testing.T) {
  741. w := httptest.NewRecorder()
  742. c, _ := CreateTestContext(w)
  743. c.Request, _ = http.NewRequest("POST", "http://example.com", nil)
  744. c.Redirect(302, "http://google.com")
  745. c.Writer.WriteHeaderNow()
  746. assert.Equal(t, 302, w.Code)
  747. assert.Equal(t, "http://google.com", w.Header().Get("Location"))
  748. }
  749. func TestContextRenderRedirectWith201(t *testing.T) {
  750. w := httptest.NewRecorder()
  751. c, _ := CreateTestContext(w)
  752. c.Request, _ = http.NewRequest("POST", "http://example.com", nil)
  753. c.Redirect(201, "/resource")
  754. c.Writer.WriteHeaderNow()
  755. assert.Equal(t, 201, w.Code)
  756. assert.Equal(t, "/resource", w.Header().Get("Location"))
  757. }
  758. func TestContextRenderRedirectAll(t *testing.T) {
  759. c, _ := CreateTestContext(httptest.NewRecorder())
  760. c.Request, _ = http.NewRequest("POST", "http://example.com", nil)
  761. assert.Panics(t, func() { c.Redirect(200, "/resource") })
  762. assert.Panics(t, func() { c.Redirect(202, "/resource") })
  763. assert.Panics(t, func() { c.Redirect(299, "/resource") })
  764. assert.Panics(t, func() { c.Redirect(309, "/resource") })
  765. assert.NotPanics(t, func() { c.Redirect(300, "/resource") })
  766. assert.NotPanics(t, func() { c.Redirect(308, "/resource") })
  767. }
  768. func TestContextNegotiationWithJSON(t *testing.T) {
  769. w := httptest.NewRecorder()
  770. c, _ := CreateTestContext(w)
  771. c.Request, _ = http.NewRequest("POST", "", nil)
  772. c.Negotiate(200, Negotiate{
  773. Offered: []string{MIMEJSON, MIMEXML},
  774. Data: H{"foo": "bar"},
  775. })
  776. assert.Equal(t, 200, w.Code)
  777. assert.Equal(t, "{\"foo\":\"bar\"}", w.Body.String())
  778. assert.Equal(t, "application/json; charset=utf-8", w.HeaderMap.Get("Content-Type"))
  779. }
  780. func TestContextNegotiationWithXML(t *testing.T) {
  781. w := httptest.NewRecorder()
  782. c, _ := CreateTestContext(w)
  783. c.Request, _ = http.NewRequest("POST", "", nil)
  784. c.Negotiate(200, Negotiate{
  785. Offered: []string{MIMEXML, MIMEJSON},
  786. Data: H{"foo": "bar"},
  787. })
  788. assert.Equal(t, 200, w.Code)
  789. assert.Equal(t, "<map><foo>bar</foo></map>", w.Body.String())
  790. assert.Equal(t, "application/xml; charset=utf-8", w.HeaderMap.Get("Content-Type"))
  791. }
  792. func TestContextNegotiationWithHTML(t *testing.T) {
  793. w := httptest.NewRecorder()
  794. c, router := CreateTestContext(w)
  795. c.Request, _ = http.NewRequest("POST", "", nil)
  796. templ := template.Must(template.New("t").Parse(`Hello {{.name}}`))
  797. router.SetHTMLTemplate(templ)
  798. c.Negotiate(200, Negotiate{
  799. Offered: []string{MIMEHTML},
  800. Data: H{"name": "gin"},
  801. HTMLName: "t",
  802. })
  803. assert.Equal(t, 200, w.Code)
  804. assert.Equal(t, "Hello gin", w.Body.String())
  805. assert.Equal(t, "text/html; charset=utf-8", w.HeaderMap.Get("Content-Type"))
  806. }
  807. func TestContextNegotiationNotSupport(t *testing.T) {
  808. w := httptest.NewRecorder()
  809. c, _ := CreateTestContext(w)
  810. c.Request, _ = http.NewRequest("POST", "", nil)
  811. c.Negotiate(200, Negotiate{
  812. Offered: []string{MIMEPOSTForm},
  813. })
  814. assert.Equal(t, 406, w.Code)
  815. assert.Equal(t, c.index, abortIndex)
  816. assert.True(t, c.IsAborted())
  817. }
  818. func TestContextNegotiationFormat(t *testing.T) {
  819. c, _ := CreateTestContext(httptest.NewRecorder())
  820. c.Request, _ = http.NewRequest("POST", "", nil)
  821. assert.Panics(t, func() { c.NegotiateFormat() })
  822. assert.Equal(t, MIMEJSON, c.NegotiateFormat(MIMEJSON, MIMEXML))
  823. assert.Equal(t, MIMEHTML, c.NegotiateFormat(MIMEHTML, MIMEJSON))
  824. }
  825. func TestContextNegotiationFormatWithAccept(t *testing.T) {
  826. c, _ := CreateTestContext(httptest.NewRecorder())
  827. c.Request, _ = http.NewRequest("POST", "/", nil)
  828. c.Request.Header.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
  829. assert.Equal(t, MIMEXML, c.NegotiateFormat(MIMEJSON, MIMEXML))
  830. assert.Equal(t, MIMEHTML, c.NegotiateFormat(MIMEXML, MIMEHTML))
  831. assert.Empty(t, c.NegotiateFormat(MIMEJSON))
  832. }
  833. func TestContextNegotiationFormatCustum(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. c.Accepted = nil
  838. c.SetAccepted(MIMEJSON, MIMEXML)
  839. assert.Equal(t, MIMEJSON, c.NegotiateFormat(MIMEJSON, MIMEXML))
  840. assert.Equal(t, MIMEXML, c.NegotiateFormat(MIMEXML, MIMEHTML))
  841. assert.Equal(t, MIMEJSON, c.NegotiateFormat(MIMEJSON))
  842. }
  843. func TestContextIsAborted(t *testing.T) {
  844. c, _ := CreateTestContext(httptest.NewRecorder())
  845. assert.False(t, c.IsAborted())
  846. c.Abort()
  847. assert.True(t, c.IsAborted())
  848. c.Next()
  849. assert.True(t, c.IsAborted())
  850. c.index++
  851. assert.True(t, c.IsAborted())
  852. }
  853. // TestContextData tests that the response can be written from `bytesting`
  854. // with specified MIME type
  855. func TestContextAbortWithStatus(t *testing.T) {
  856. w := httptest.NewRecorder()
  857. c, _ := CreateTestContext(w)
  858. c.index = 4
  859. c.AbortWithStatus(401)
  860. assert.Equal(t, abortIndex, c.index)
  861. assert.Equal(t, 401, c.Writer.Status())
  862. assert.Equal(t, 401, w.Code)
  863. assert.True(t, c.IsAborted())
  864. }
  865. type testJSONAbortMsg struct {
  866. Foo string `json:"foo"`
  867. Bar string `json:"bar"`
  868. }
  869. func TestContextAbortWithStatusJSON(t *testing.T) {
  870. w := httptest.NewRecorder()
  871. c, _ := CreateTestContext(w)
  872. c.index = 4
  873. in := new(testJSONAbortMsg)
  874. in.Bar = "barValue"
  875. in.Foo = "fooValue"
  876. c.AbortWithStatusJSON(415, in)
  877. assert.Equal(t, abortIndex, c.index)
  878. assert.Equal(t, 415, c.Writer.Status())
  879. assert.Equal(t, 415, w.Code)
  880. assert.True(t, c.IsAborted())
  881. contentType := w.Header().Get("Content-Type")
  882. assert.Equal(t, "application/json; charset=utf-8", contentType)
  883. buf := new(bytes.Buffer)
  884. buf.ReadFrom(w.Body)
  885. jsonStringBody := buf.String()
  886. assert.Equal(t, fmt.Sprint(`{"foo":"fooValue","bar":"barValue"}`), jsonStringBody)
  887. }
  888. func TestContextError(t *testing.T) {
  889. c, _ := CreateTestContext(httptest.NewRecorder())
  890. assert.Empty(t, c.Errors)
  891. c.Error(errors.New("first error"))
  892. assert.Len(t, c.Errors, 1)
  893. assert.Equal(t, "Error #01: first error\n", c.Errors.String())
  894. c.Error(&Error{
  895. Err: errors.New("second error"),
  896. Meta: "some data 2",
  897. Type: ErrorTypePublic,
  898. })
  899. assert.Len(t, c.Errors, 2)
  900. assert.Equal(t, errors.New("first error"), c.Errors[0].Err)
  901. assert.Nil(t, c.Errors[0].Meta)
  902. assert.Equal(t, ErrorTypePrivate, c.Errors[0].Type)
  903. assert.Equal(t, errors.New("second error"), c.Errors[1].Err)
  904. assert.Equal(t, "some data 2", c.Errors[1].Meta)
  905. assert.Equal(t, ErrorTypePublic, c.Errors[1].Type)
  906. assert.Equal(t, c.Errors.Last(), c.Errors[1])
  907. defer func() {
  908. if recover() == nil {
  909. t.Error("didn't panic")
  910. }
  911. }()
  912. c.Error(nil)
  913. }
  914. func TestContextTypedError(t *testing.T) {
  915. c, _ := CreateTestContext(httptest.NewRecorder())
  916. c.Error(errors.New("externo 0")).SetType(ErrorTypePublic)
  917. c.Error(errors.New("interno 0")).SetType(ErrorTypePrivate)
  918. for _, err := range c.Errors.ByType(ErrorTypePublic) {
  919. assert.Equal(t, ErrorTypePublic, err.Type)
  920. }
  921. for _, err := range c.Errors.ByType(ErrorTypePrivate) {
  922. assert.Equal(t, ErrorTypePrivate, err.Type)
  923. }
  924. assert.Equal(t, []string{"externo 0", "interno 0"}, c.Errors.Errors())
  925. }
  926. func TestContextAbortWithError(t *testing.T) {
  927. w := httptest.NewRecorder()
  928. c, _ := CreateTestContext(w)
  929. c.AbortWithError(401, errors.New("bad input")).SetMeta("some input")
  930. assert.Equal(t, 401, w.Code)
  931. assert.Equal(t, abortIndex, c.index)
  932. assert.True(t, c.IsAborted())
  933. }
  934. func TestContextClientIP(t *testing.T) {
  935. c, _ := CreateTestContext(httptest.NewRecorder())
  936. c.Request, _ = http.NewRequest("POST", "/", nil)
  937. c.Request.Header.Set("X-Real-IP", " 10.10.10.10 ")
  938. c.Request.Header.Set("X-Forwarded-For", " 20.20.20.20, 30.30.30.30")
  939. c.Request.Header.Set("X-Appengine-Remote-Addr", "50.50.50.50")
  940. c.Request.RemoteAddr = " 40.40.40.40:42123 "
  941. assert.Equal(t, "20.20.20.20", c.ClientIP())
  942. c.Request.Header.Del("X-Forwarded-For")
  943. assert.Equal(t, "10.10.10.10", c.ClientIP())
  944. c.Request.Header.Set("X-Forwarded-For", "30.30.30.30 ")
  945. assert.Equal(t, "30.30.30.30", c.ClientIP())
  946. c.Request.Header.Del("X-Forwarded-For")
  947. c.Request.Header.Del("X-Real-IP")
  948. c.engine.AppEngine = true
  949. assert.Equal(t, "50.50.50.50", c.ClientIP())
  950. c.Request.Header.Del("X-Appengine-Remote-Addr")
  951. assert.Equal(t, "40.40.40.40", c.ClientIP())
  952. // no port
  953. c.Request.RemoteAddr = "50.50.50.50"
  954. assert.Empty(t, c.ClientIP())
  955. }
  956. func TestContextContentType(t *testing.T) {
  957. c, _ := CreateTestContext(httptest.NewRecorder())
  958. c.Request, _ = http.NewRequest("POST", "/", nil)
  959. c.Request.Header.Set("Content-Type", "application/json; charset=utf-8")
  960. assert.Equal(t, "application/json", c.ContentType())
  961. }
  962. func TestContextAutoBindJSON(t *testing.T) {
  963. c, _ := CreateTestContext(httptest.NewRecorder())
  964. c.Request, _ = http.NewRequest("POST", "/", bytes.NewBufferString("{\"foo\":\"bar\", \"bar\":\"foo\"}"))
  965. c.Request.Header.Add("Content-Type", MIMEJSON)
  966. var obj struct {
  967. Foo string `json:"foo"`
  968. Bar string `json:"bar"`
  969. }
  970. assert.NoError(t, c.Bind(&obj))
  971. assert.Equal(t, "foo", obj.Bar)
  972. assert.Equal(t, "bar", obj.Foo)
  973. assert.Empty(t, c.Errors)
  974. }
  975. func TestContextBindWithJSON(t *testing.T) {
  976. w := httptest.NewRecorder()
  977. c, _ := CreateTestContext(w)
  978. c.Request, _ = http.NewRequest("POST", "/", bytes.NewBufferString("{\"foo\":\"bar\", \"bar\":\"foo\"}"))
  979. c.Request.Header.Add("Content-Type", MIMEXML) // set fake content-type
  980. var obj struct {
  981. Foo string `json:"foo"`
  982. Bar string `json:"bar"`
  983. }
  984. assert.NoError(t, c.BindJSON(&obj))
  985. assert.Equal(t, "foo", obj.Bar)
  986. assert.Equal(t, "bar", obj.Foo)
  987. assert.Equal(t, 0, w.Body.Len())
  988. }
  989. func TestContextBindWithQuery(t *testing.T) {
  990. w := httptest.NewRecorder()
  991. c, _ := CreateTestContext(w)
  992. c.Request, _ = http.NewRequest("POST", "/?foo=bar&bar=foo", bytes.NewBufferString("foo=unused"))
  993. var obj struct {
  994. Foo string `form:"foo"`
  995. Bar string `form:"bar"`
  996. }
  997. assert.NoError(t, c.BindQuery(&obj))
  998. assert.Equal(t, "foo", obj.Bar)
  999. assert.Equal(t, "bar", obj.Foo)
  1000. assert.Equal(t, 0, w.Body.Len())
  1001. }
  1002. func TestContextBadAutoBind(t *testing.T) {
  1003. w := httptest.NewRecorder()
  1004. c, _ := CreateTestContext(w)
  1005. c.Request, _ = http.NewRequest("POST", "http://example.com", bytes.NewBufferString("\"foo\":\"bar\", \"bar\":\"foo\"}"))
  1006. c.Request.Header.Add("Content-Type", MIMEJSON)
  1007. var obj struct {
  1008. Foo string `json:"foo"`
  1009. Bar string `json:"bar"`
  1010. }
  1011. assert.False(t, c.IsAborted())
  1012. assert.Error(t, c.Bind(&obj))
  1013. c.Writer.WriteHeaderNow()
  1014. assert.Empty(t, obj.Bar)
  1015. assert.Empty(t, obj.Foo)
  1016. assert.Equal(t, 400, w.Code)
  1017. assert.True(t, c.IsAborted())
  1018. }
  1019. func TestContextAutoShouldBindJSON(t *testing.T) {
  1020. c, _ := CreateTestContext(httptest.NewRecorder())
  1021. c.Request, _ = http.NewRequest("POST", "/", bytes.NewBufferString("{\"foo\":\"bar\", \"bar\":\"foo\"}"))
  1022. c.Request.Header.Add("Content-Type", MIMEJSON)
  1023. var obj struct {
  1024. Foo string `json:"foo"`
  1025. Bar string `json:"bar"`
  1026. }
  1027. assert.NoError(t, c.ShouldBind(&obj))
  1028. assert.Equal(t, "foo", obj.Bar)
  1029. assert.Equal(t, "bar", obj.Foo)
  1030. assert.Empty(t, c.Errors)
  1031. }
  1032. func TestContextShouldBindWithJSON(t *testing.T) {
  1033. w := httptest.NewRecorder()
  1034. c, _ := CreateTestContext(w)
  1035. c.Request, _ = http.NewRequest("POST", "/", bytes.NewBufferString("{\"foo\":\"bar\", \"bar\":\"foo\"}"))
  1036. c.Request.Header.Add("Content-Type", MIMEXML) // set fake content-type
  1037. var obj struct {
  1038. Foo string `json:"foo"`
  1039. Bar string `json:"bar"`
  1040. }
  1041. assert.NoError(t, c.ShouldBindJSON(&obj))
  1042. assert.Equal(t, "foo", obj.Bar)
  1043. assert.Equal(t, "bar", obj.Foo)
  1044. assert.Equal(t, 0, w.Body.Len())
  1045. }
  1046. func TestContextShouldBindWithQuery(t *testing.T) {
  1047. w := httptest.NewRecorder()
  1048. c, _ := CreateTestContext(w)
  1049. c.Request, _ = http.NewRequest("POST", "/?foo=bar&bar=foo", bytes.NewBufferString("foo=unused"))
  1050. var obj struct {
  1051. Foo string `form:"foo"`
  1052. Bar string `form:"bar"`
  1053. }
  1054. assert.NoError(t, c.ShouldBindQuery(&obj))
  1055. assert.Equal(t, "foo", obj.Bar)
  1056. assert.Equal(t, "bar", obj.Foo)
  1057. assert.Equal(t, 0, w.Body.Len())
  1058. }
  1059. func TestContextBadAutoShouldBind(t *testing.T) {
  1060. w := httptest.NewRecorder()
  1061. c, _ := CreateTestContext(w)
  1062. c.Request, _ = http.NewRequest("POST", "http://example.com", bytes.NewBufferString("\"foo\":\"bar\", \"bar\":\"foo\"}"))
  1063. c.Request.Header.Add("Content-Type", MIMEJSON)
  1064. var obj struct {
  1065. Foo string `json:"foo"`
  1066. Bar string `json:"bar"`
  1067. }
  1068. assert.False(t, c.IsAborted())
  1069. assert.Error(t, c.ShouldBind(&obj))
  1070. assert.Empty(t, obj.Bar)
  1071. assert.Empty(t, obj.Foo)
  1072. assert.False(t, c.IsAborted())
  1073. }
  1074. func TestContextShouldBindBodyWith(t *testing.T) {
  1075. type typeA struct {
  1076. Foo string `json:"foo" xml:"foo" binding:"required"`
  1077. }
  1078. type typeB struct {
  1079. Bar string `json:"bar" xml:"bar" binding:"required"`
  1080. }
  1081. for _, tt := range []struct {
  1082. name string
  1083. bindingA, bindingB binding.BindingBody
  1084. bodyA, bodyB string
  1085. }{
  1086. {
  1087. name: "JSON & JSON",
  1088. bindingA: binding.JSON,
  1089. bindingB: binding.JSON,
  1090. bodyA: `{"foo":"FOO"}`,
  1091. bodyB: `{"bar":"BAR"}`,
  1092. },
  1093. {
  1094. name: "JSON & XML",
  1095. bindingA: binding.JSON,
  1096. bindingB: binding.XML,
  1097. bodyA: `{"foo":"FOO"}`,
  1098. bodyB: `<?xml version="1.0" encoding="UTF-8"?>
  1099. <root>
  1100. <bar>BAR</bar>
  1101. </root>`,
  1102. },
  1103. {
  1104. name: "XML & XML",
  1105. bindingA: binding.XML,
  1106. bindingB: binding.XML,
  1107. bodyA: `<?xml version="1.0" encoding="UTF-8"?>
  1108. <root>
  1109. <foo>FOO</foo>
  1110. </root>`,
  1111. bodyB: `<?xml version="1.0" encoding="UTF-8"?>
  1112. <root>
  1113. <bar>BAR</bar>
  1114. </root>`,
  1115. },
  1116. } {
  1117. t.Logf("testing: %s", tt.name)
  1118. // bodyA to typeA and typeB
  1119. {
  1120. w := httptest.NewRecorder()
  1121. c, _ := CreateTestContext(w)
  1122. c.Request, _ = http.NewRequest(
  1123. "POST", "http://example.com", bytes.NewBufferString(tt.bodyA),
  1124. )
  1125. // When it binds to typeA and typeB, it finds the body is
  1126. // not typeB but typeA.
  1127. objA := typeA{}
  1128. assert.NoError(t, c.ShouldBindBodyWith(&objA, tt.bindingA))
  1129. assert.Equal(t, typeA{"FOO"}, objA)
  1130. objB := typeB{}
  1131. assert.Error(t, c.ShouldBindBodyWith(&objB, tt.bindingB))
  1132. assert.NotEqual(t, typeB{"BAR"}, objB)
  1133. }
  1134. // bodyB to typeA and typeB
  1135. {
  1136. // When it binds to typeA and typeB, it finds the body is
  1137. // not typeA but typeB.
  1138. w := httptest.NewRecorder()
  1139. c, _ := CreateTestContext(w)
  1140. c.Request, _ = http.NewRequest(
  1141. "POST", "http://example.com", bytes.NewBufferString(tt.bodyB),
  1142. )
  1143. objA := typeA{}
  1144. assert.Error(t, c.ShouldBindBodyWith(&objA, tt.bindingA))
  1145. assert.NotEqual(t, typeA{"FOO"}, objA)
  1146. objB := typeB{}
  1147. assert.NoError(t, c.ShouldBindBodyWith(&objB, tt.bindingB))
  1148. assert.Equal(t, typeB{"BAR"}, objB)
  1149. }
  1150. }
  1151. }
  1152. func TestContextGolangContext(t *testing.T) {
  1153. c, _ := CreateTestContext(httptest.NewRecorder())
  1154. c.Request, _ = http.NewRequest("POST", "/", bytes.NewBufferString("{\"foo\":\"bar\", \"bar\":\"foo\"}"))
  1155. assert.NoError(t, c.Err())
  1156. assert.Nil(t, c.Done())
  1157. ti, ok := c.Deadline()
  1158. assert.Equal(t, ti, time.Time{})
  1159. assert.False(t, ok)
  1160. assert.Equal(t, c.Value(0), c.Request)
  1161. assert.Nil(t, c.Value("foo"))
  1162. c.Set("foo", "bar")
  1163. assert.Equal(t, "bar", c.Value("foo"))
  1164. assert.Nil(t, c.Value(1))
  1165. }
  1166. func TestWebsocketsRequired(t *testing.T) {
  1167. // Example request from spec: https://tools.ietf.org/html/rfc6455#section-1.2
  1168. c, _ := CreateTestContext(httptest.NewRecorder())
  1169. c.Request, _ = http.NewRequest("GET", "/chat", nil)
  1170. c.Request.Header.Set("Host", "server.example.com")
  1171. c.Request.Header.Set("Upgrade", "websocket")
  1172. c.Request.Header.Set("Connection", "Upgrade")
  1173. c.Request.Header.Set("Sec-WebSocket-Key", "dGhlIHNhbXBsZSBub25jZQ==")
  1174. c.Request.Header.Set("Origin", "http://example.com")
  1175. c.Request.Header.Set("Sec-WebSocket-Protocol", "chat, superchat")
  1176. c.Request.Header.Set("Sec-WebSocket-Version", "13")
  1177. assert.True(t, c.IsWebsocket())
  1178. // Normal request, no websocket required.
  1179. c, _ = CreateTestContext(httptest.NewRecorder())
  1180. c.Request, _ = http.NewRequest("GET", "/chat", nil)
  1181. c.Request.Header.Set("Host", "server.example.com")
  1182. assert.False(t, c.IsWebsocket())
  1183. }
  1184. func TestGetRequestHeaderValue(t *testing.T) {
  1185. c, _ := CreateTestContext(httptest.NewRecorder())
  1186. c.Request, _ = http.NewRequest("GET", "/chat", nil)
  1187. c.Request.Header.Set("Gin-Version", "1.0.0")
  1188. assert.Equal(t, "1.0.0", c.GetHeader("Gin-Version"))
  1189. assert.Empty(t, c.GetHeader("Connection"))
  1190. }
  1191. func TestContextGetRawData(t *testing.T) {
  1192. c, _ := CreateTestContext(httptest.NewRecorder())
  1193. body := bytes.NewBufferString("Fetch binary post data")
  1194. c.Request, _ = http.NewRequest("POST", "/", body)
  1195. c.Request.Header.Add("Content-Type", MIMEPOSTForm)
  1196. data, err := c.GetRawData()
  1197. assert.Nil(t, err)
  1198. assert.Equal(t, "Fetch binary post data", string(data))
  1199. }