context_test.go 47 KB

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