context_test.go 36 KB

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