context_test.go 46 KB

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