context_test.go 22 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434435436437438439440441442443444445446447448449450451452453454455456457458459460461462463464465466467468469470471472473474475476477478479480481482483484485486487488489490491492493494495496497498499500501502503504505506507508509510511512513514515516517518519520521522523524525526527528529530531532533534535536537538539540541542543544545546547548549550551552553554555556557558559560561562563564565566567568569570571572573574575576577578579580581582583584585586587588589590591592593594595596597598599600601602603604605606607608609610611612613614615616617618619620621622623624625626627628629630631632633634635636637638639640641642643644645646647648649650651652653654655656657658659660661662663664665666667668669670671672673674675676677678679680681682683684685686687688689690691692693694695696697698699700701702703704705706707708709710711712713714715716717718719720721722723724725726727728729730731732733734735736737738
  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. "html/template"
  9. "mime/multipart"
  10. "net/http"
  11. "net/http/httptest"
  12. "strings"
  13. "testing"
  14. "time"
  15. "github.com/manucorporat/sse"
  16. "github.com/stretchr/testify/assert"
  17. )
  18. // Unit tests TODO
  19. // func (c *Context) File(filepath string) {
  20. // func (c *Context) Negotiate(code int, config Negotiate) {
  21. // BAD case: func (c *Context) Render(code int, render render.Render, obj ...interface{}) {
  22. // test that information is not leaked when reusing Contexts (using the Pool)
  23. func createMultipartRequest() *http.Request {
  24. boundary := "--testboundary"
  25. body := new(bytes.Buffer)
  26. mw := multipart.NewWriter(body)
  27. defer mw.Close()
  28. must(mw.SetBoundary(boundary))
  29. must(mw.WriteField("foo", "bar"))
  30. must(mw.WriteField("bar", "10"))
  31. must(mw.WriteField("bar", "foo2"))
  32. must(mw.WriteField("array", "first"))
  33. must(mw.WriteField("array", "second"))
  34. must(mw.WriteField("id", ""))
  35. req, err := http.NewRequest("POST", "/", body)
  36. must(err)
  37. req.Header.Set("Content-Type", MIMEMultipartPOSTForm+"; boundary="+boundary)
  38. return req
  39. }
  40. func must(err error) {
  41. if err != nil {
  42. panic(err.Error())
  43. }
  44. }
  45. func TestContextReset(t *testing.T) {
  46. router := New()
  47. c := router.allocateContext()
  48. assert.Equal(t, c.engine, router)
  49. c.index = 2
  50. c.Writer = &responseWriter{ResponseWriter: httptest.NewRecorder()}
  51. c.Params = Params{Param{}}
  52. c.Error(errors.New("test"))
  53. c.Set("foo", "bar")
  54. c.reset()
  55. assert.False(t, c.IsAborted())
  56. assert.Nil(t, c.Keys)
  57. assert.Nil(t, c.Accepted)
  58. assert.Len(t, c.Errors, 0)
  59. assert.Empty(t, c.Errors.Errors())
  60. assert.Empty(t, c.Errors.ByType(ErrorTypeAny))
  61. assert.Len(t, c.Params, 0)
  62. assert.EqualValues(t, c.index, -1)
  63. assert.Equal(t, c.Writer.(*responseWriter), &c.writermem)
  64. }
  65. func TestContextHandlers(t *testing.T) {
  66. c, _, _ := CreateTestContext()
  67. assert.Nil(t, c.handlers)
  68. assert.Nil(t, c.handlers.Last())
  69. c.handlers = HandlersChain{}
  70. assert.NotNil(t, c.handlers)
  71. assert.Nil(t, c.handlers.Last())
  72. f := func(c *Context) {}
  73. g := func(c *Context) {}
  74. c.handlers = HandlersChain{f}
  75. compareFunc(t, f, c.handlers.Last())
  76. c.handlers = HandlersChain{f, g}
  77. compareFunc(t, g, c.handlers.Last())
  78. }
  79. // TestContextSetGet tests that a parameter is set correctly on the
  80. // current context and can be retrieved using Get.
  81. func TestContextSetGet(t *testing.T) {
  82. c, _, _ := CreateTestContext()
  83. c.Set("foo", "bar")
  84. value, err := c.Get("foo")
  85. assert.Equal(t, value, "bar")
  86. assert.True(t, err)
  87. value, err = c.Get("foo2")
  88. assert.Nil(t, value)
  89. assert.False(t, err)
  90. assert.Equal(t, c.MustGet("foo"), "bar")
  91. assert.Panics(t, func() { c.MustGet("no_exist") })
  92. }
  93. func TestContextSetGetValues(t *testing.T) {
  94. c, _, _ := CreateTestContext()
  95. c.Set("string", "this is a string")
  96. c.Set("int32", int32(-42))
  97. c.Set("int64", int64(42424242424242))
  98. c.Set("uint64", uint64(42))
  99. c.Set("float32", float32(4.2))
  100. c.Set("float64", 4.2)
  101. var a interface{} = 1
  102. c.Set("intInterface", a)
  103. assert.Exactly(t, c.MustGet("string").(string), "this is a string")
  104. assert.Exactly(t, c.MustGet("int32").(int32), int32(-42))
  105. assert.Exactly(t, c.MustGet("int64").(int64), int64(42424242424242))
  106. assert.Exactly(t, c.MustGet("uint64").(uint64), uint64(42))
  107. assert.Exactly(t, c.MustGet("float32").(float32), float32(4.2))
  108. assert.Exactly(t, c.MustGet("float64").(float64), 4.2)
  109. assert.Exactly(t, c.MustGet("intInterface").(int), 1)
  110. }
  111. func TestContextCopy(t *testing.T) {
  112. c, _, _ := CreateTestContext()
  113. c.index = 2
  114. c.Request, _ = http.NewRequest("POST", "/hola", nil)
  115. c.handlers = HandlersChain{func(c *Context) {}}
  116. c.Params = Params{Param{Key: "foo", Value: "bar"}}
  117. c.Set("foo", "bar")
  118. cp := c.Copy()
  119. assert.Nil(t, cp.handlers)
  120. assert.Nil(t, cp.writermem.ResponseWriter)
  121. assert.Equal(t, &cp.writermem, cp.Writer.(*responseWriter))
  122. assert.Equal(t, cp.Request, c.Request)
  123. assert.Equal(t, cp.index, abortIndex)
  124. assert.Equal(t, cp.Keys, c.Keys)
  125. assert.Equal(t, cp.engine, c.engine)
  126. assert.Equal(t, cp.Params, c.Params)
  127. }
  128. func TestContextHandlerName(t *testing.T) {
  129. c, _, _ := CreateTestContext()
  130. c.handlers = HandlersChain{func(c *Context) {}, handlerNameTest}
  131. assert.Regexp(t, "^(.*/vendor/)?github.com/gin-gonic/gin.handlerNameTest$", c.HandlerName())
  132. }
  133. func handlerNameTest(c *Context) {
  134. }
  135. func TestContextQuery(t *testing.T) {
  136. c, _, _ := CreateTestContext()
  137. c.Request, _ = http.NewRequest("GET", "http://example.com/?foo=bar&page=10&id=", nil)
  138. value, ok := c.GetQuery("foo")
  139. assert.True(t, ok)
  140. assert.Equal(t, value, "bar")
  141. assert.Equal(t, c.DefaultQuery("foo", "none"), "bar")
  142. assert.Equal(t, c.Query("foo"), "bar")
  143. value, ok = c.GetQuery("page")
  144. assert.True(t, ok)
  145. assert.Equal(t, value, "10")
  146. assert.Equal(t, c.DefaultQuery("page", "0"), "10")
  147. assert.Equal(t, c.Query("page"), "10")
  148. value, ok = c.GetQuery("id")
  149. assert.True(t, ok)
  150. assert.Empty(t, value)
  151. assert.Equal(t, c.DefaultQuery("id", "nada"), "")
  152. assert.Empty(t, c.Query("id"))
  153. value, ok = c.GetQuery("NoKey")
  154. assert.False(t, ok)
  155. assert.Empty(t, value)
  156. assert.Equal(t, c.DefaultQuery("NoKey", "nada"), "nada")
  157. assert.Empty(t, c.Query("NoKey"))
  158. // postform should not mess
  159. value, ok = c.GetPostForm("page")
  160. assert.False(t, ok)
  161. assert.Empty(t, value)
  162. assert.Empty(t, c.PostForm("foo"))
  163. }
  164. func TestContextQueryAndPostForm(t *testing.T) {
  165. c, _, _ := CreateTestContext()
  166. body := bytes.NewBufferString("foo=bar&page=11&both=&foo=second")
  167. c.Request, _ = http.NewRequest("POST", "/?both=GET&id=main&id=omit&array[]=first&array[]=second", body)
  168. c.Request.Header.Add("Content-Type", MIMEPOSTForm)
  169. assert.Equal(t, c.DefaultPostForm("foo", "none"), "bar")
  170. assert.Equal(t, c.PostForm("foo"), "bar")
  171. assert.Empty(t, c.Query("foo"))
  172. value, ok := c.GetPostForm("page")
  173. assert.True(t, ok)
  174. assert.Equal(t, value, "11")
  175. assert.Equal(t, c.DefaultPostForm("page", "0"), "11")
  176. assert.Equal(t, c.PostForm("page"), "11")
  177. assert.Equal(t, c.Query("page"), "")
  178. value, ok = c.GetPostForm("both")
  179. assert.True(t, ok)
  180. assert.Empty(t, value)
  181. assert.Empty(t, c.PostForm("both"))
  182. assert.Equal(t, c.DefaultPostForm("both", "nothing"), "")
  183. assert.Equal(t, c.Query("both"), "GET")
  184. value, ok = c.GetQuery("id")
  185. assert.True(t, ok)
  186. assert.Equal(t, value, "main")
  187. assert.Equal(t, c.DefaultPostForm("id", "000"), "000")
  188. assert.Equal(t, c.Query("id"), "main")
  189. assert.Empty(t, c.PostForm("id"))
  190. value, ok = c.GetQuery("NoKey")
  191. assert.False(t, ok)
  192. assert.Empty(t, value)
  193. value, ok = c.GetPostForm("NoKey")
  194. assert.False(t, ok)
  195. assert.Empty(t, value)
  196. assert.Equal(t, c.DefaultPostForm("NoKey", "nada"), "nada")
  197. assert.Equal(t, c.DefaultQuery("NoKey", "nothing"), "nothing")
  198. assert.Empty(t, c.PostForm("NoKey"))
  199. assert.Empty(t, c.Query("NoKey"))
  200. var obj struct {
  201. Foo string `form:"foo"`
  202. ID string `form:"id"`
  203. Page int `form:"page"`
  204. Both string `form:"both"`
  205. Array []string `form:"array[]"`
  206. }
  207. assert.NoError(t, c.Bind(&obj))
  208. assert.Equal(t, obj.Foo, "bar")
  209. assert.Equal(t, obj.ID, "main")
  210. assert.Equal(t, obj.Page, 11)
  211. assert.Equal(t, obj.Both, "")
  212. assert.Equal(t, obj.Array, []string{"first", "second"})
  213. values, ok := c.GetQueryArray("array[]")
  214. assert.True(t, ok)
  215. assert.Equal(t, "first", values[0])
  216. assert.Equal(t, "second", values[1])
  217. values = c.QueryArray("array[]")
  218. assert.Equal(t, "first", values[0])
  219. assert.Equal(t, "second", values[1])
  220. values = c.QueryArray("nokey")
  221. assert.Equal(t, 0, len(values))
  222. values = c.QueryArray("both")
  223. assert.Equal(t, 1, len(values))
  224. assert.Equal(t, "GET", values[0])
  225. }
  226. func TestContextPostFormMultipart(t *testing.T) {
  227. c, _, _ := CreateTestContext()
  228. c.Request = createMultipartRequest()
  229. var obj struct {
  230. Foo string `form:"foo"`
  231. Bar string `form:"bar"`
  232. BarAsInt int `form:"bar"`
  233. Array []string `form:"array"`
  234. ID string `form:"id"`
  235. }
  236. assert.NoError(t, c.Bind(&obj))
  237. assert.Equal(t, obj.Foo, "bar")
  238. assert.Equal(t, obj.Bar, "10")
  239. assert.Equal(t, obj.BarAsInt, 10)
  240. assert.Equal(t, obj.Array, []string{"first", "second"})
  241. assert.Equal(t, obj.ID, "")
  242. value, ok := c.GetQuery("foo")
  243. assert.False(t, ok)
  244. assert.Empty(t, value)
  245. assert.Empty(t, c.Query("bar"))
  246. assert.Equal(t, c.DefaultQuery("id", "nothing"), "nothing")
  247. value, ok = c.GetPostForm("foo")
  248. assert.True(t, ok)
  249. assert.Equal(t, value, "bar")
  250. assert.Equal(t, c.PostForm("foo"), "bar")
  251. value, ok = c.GetPostForm("array")
  252. assert.True(t, ok)
  253. assert.Equal(t, value, "first")
  254. assert.Equal(t, c.PostForm("array"), "first")
  255. assert.Equal(t, c.DefaultPostForm("bar", "nothing"), "10")
  256. value, ok = c.GetPostForm("id")
  257. assert.True(t, ok)
  258. assert.Empty(t, value)
  259. assert.Empty(t, c.PostForm("id"))
  260. assert.Empty(t, c.DefaultPostForm("id", "nothing"))
  261. value, ok = c.GetPostForm("nokey")
  262. assert.False(t, ok)
  263. assert.Empty(t, value)
  264. assert.Equal(t, c.DefaultPostForm("nokey", "nothing"), "nothing")
  265. values, ok := c.GetPostFormArray("array")
  266. assert.True(t, ok)
  267. assert.Equal(t, "first", values[0])
  268. assert.Equal(t, "second", values[1])
  269. values = c.PostFormArray("array")
  270. assert.Equal(t, "first", values[0])
  271. assert.Equal(t, "second", values[1])
  272. values = c.PostFormArray("nokey")
  273. assert.Equal(t, 0, len(values))
  274. values = c.PostFormArray("foo")
  275. assert.Equal(t, 1, len(values))
  276. assert.Equal(t, "bar", values[0])
  277. }
  278. func TestContextSetCookie(t *testing.T) {
  279. c, _, _ := CreateTestContext()
  280. c.SetCookie("user", "gin", 1, "/", "localhost", true, true)
  281. assert.Equal(t, c.Writer.Header().Get("Set-Cookie"), "user=gin; Path=/; Domain=localhost; Max-Age=1; HttpOnly; Secure")
  282. }
  283. func TestContextGetCookie(t *testing.T) {
  284. c, _, _ := CreateTestContext()
  285. c.Request, _ = http.NewRequest("GET", "/get", nil)
  286. c.Request.Header.Set("Cookie", "user=gin")
  287. cookie, _ := c.Cookie("user")
  288. assert.Equal(t, cookie, "gin")
  289. }
  290. // Tests that the response is serialized as JSON
  291. // and Content-Type is set to application/json
  292. func TestContextRenderJSON(t *testing.T) {
  293. c, w, _ := CreateTestContext()
  294. c.JSON(201, H{"foo": "bar"})
  295. assert.Equal(t, w.Code, 201)
  296. assert.Equal(t, w.Body.String(), "{\"foo\":\"bar\"}\n")
  297. assert.Equal(t, w.HeaderMap.Get("Content-Type"), "application/json; charset=utf-8")
  298. }
  299. // Tests that the response is serialized as JSON
  300. // we change the content-type before
  301. func TestContextRenderAPIJSON(t *testing.T) {
  302. c, w, _ := CreateTestContext()
  303. c.Header("Content-Type", "application/vnd.api+json")
  304. c.JSON(201, H{"foo": "bar"})
  305. assert.Equal(t, w.Code, 201)
  306. assert.Equal(t, w.Body.String(), "{\"foo\":\"bar\"}\n")
  307. assert.Equal(t, w.HeaderMap.Get("Content-Type"), "application/vnd.api+json")
  308. }
  309. // Tests that the response is serialized as JSON
  310. // and Content-Type is set to application/json
  311. func TestContextRenderIndentedJSON(t *testing.T) {
  312. c, w, _ := CreateTestContext()
  313. c.IndentedJSON(201, H{"foo": "bar", "bar": "foo", "nested": H{"foo": "bar"}})
  314. assert.Equal(t, w.Code, 201)
  315. assert.Equal(t, w.Body.String(), "{\n \"bar\": \"foo\",\n \"foo\": \"bar\",\n \"nested\": {\n \"foo\": \"bar\"\n }\n}")
  316. assert.Equal(t, w.HeaderMap.Get("Content-Type"), "application/json; charset=utf-8")
  317. }
  318. // Tests that the response executes the templates
  319. // and responds with Content-Type set to text/html
  320. func TestContextRenderHTML(t *testing.T) {
  321. c, w, router := CreateTestContext()
  322. templ := template.Must(template.New("t").Parse(`Hello {{.name}}`))
  323. router.SetHTMLTemplate(templ)
  324. c.HTML(201, "t", H{"name": "alexandernyquist"})
  325. assert.Equal(t, w.Code, 201)
  326. assert.Equal(t, w.Body.String(), "Hello alexandernyquist")
  327. assert.Equal(t, w.HeaderMap.Get("Content-Type"), "text/html; charset=utf-8")
  328. }
  329. // TestContextXML tests that the response is serialized as XML
  330. // and Content-Type is set to application/xml
  331. func TestContextRenderXML(t *testing.T) {
  332. c, w, _ := CreateTestContext()
  333. c.XML(201, H{"foo": "bar"})
  334. assert.Equal(t, w.Code, 201)
  335. assert.Equal(t, w.Body.String(), "<map><foo>bar</foo></map>")
  336. assert.Equal(t, w.HeaderMap.Get("Content-Type"), "application/xml; charset=utf-8")
  337. }
  338. // TestContextString tests that the response is returned
  339. // with Content-Type set to text/plain
  340. func TestContextRenderString(t *testing.T) {
  341. c, w, _ := CreateTestContext()
  342. c.String(201, "test %s %d", "string", 2)
  343. assert.Equal(t, w.Code, 201)
  344. assert.Equal(t, w.Body.String(), "test string 2")
  345. assert.Equal(t, w.HeaderMap.Get("Content-Type"), "text/plain; charset=utf-8")
  346. }
  347. // TestContextString tests that the response is returned
  348. // with Content-Type set to text/html
  349. func TestContextRenderHTMLString(t *testing.T) {
  350. c, w, _ := CreateTestContext()
  351. c.Header("Content-Type", "text/html; charset=utf-8")
  352. c.String(201, "<html>%s %d</html>", "string", 3)
  353. assert.Equal(t, w.Code, 201)
  354. assert.Equal(t, w.Body.String(), "<html>string 3</html>")
  355. assert.Equal(t, w.HeaderMap.Get("Content-Type"), "text/html; charset=utf-8")
  356. }
  357. // TestContextData tests that the response can be written from `bytesting`
  358. // with specified MIME type
  359. func TestContextRenderData(t *testing.T) {
  360. c, w, _ := CreateTestContext()
  361. c.Data(201, "text/csv", []byte(`foo,bar`))
  362. assert.Equal(t, w.Code, 201)
  363. assert.Equal(t, w.Body.String(), "foo,bar")
  364. assert.Equal(t, w.HeaderMap.Get("Content-Type"), "text/csv")
  365. }
  366. func TestContextRenderSSE(t *testing.T) {
  367. c, w, _ := CreateTestContext()
  368. c.SSEvent("float", 1.5)
  369. c.Render(-1, sse.Event{
  370. Id: "123",
  371. Data: "text",
  372. })
  373. c.SSEvent("chat", H{
  374. "foo": "bar",
  375. "bar": "foo",
  376. })
  377. 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))
  378. }
  379. func TestContextRenderFile(t *testing.T) {
  380. c, w, _ := CreateTestContext()
  381. c.Request, _ = http.NewRequest("GET", "/", nil)
  382. c.File("./gin.go")
  383. assert.Equal(t, w.Code, 200)
  384. assert.Contains(t, w.Body.String(), "func New() *Engine {")
  385. assert.Equal(t, w.HeaderMap.Get("Content-Type"), "text/plain; charset=utf-8")
  386. }
  387. // TestContextRenderYAML tests that the response is serialized as YAML
  388. // and Content-Type is set to application/x-yaml
  389. func TestContextRenderYAML(t *testing.T) {
  390. c, w, _ := CreateTestContext()
  391. c.YAML(201, H{"foo": "bar"})
  392. assert.Equal(t, w.Code, 201)
  393. assert.Equal(t, w.Body.String(), "foo: bar\n")
  394. assert.Equal(t, w.HeaderMap.Get("Content-Type"), "application/x-yaml; charset=utf-8")
  395. }
  396. func TestContextHeaders(t *testing.T) {
  397. c, _, _ := CreateTestContext()
  398. c.Header("Content-Type", "text/plain")
  399. c.Header("X-Custom", "value")
  400. assert.Equal(t, c.Writer.Header().Get("Content-Type"), "text/plain")
  401. assert.Equal(t, c.Writer.Header().Get("X-Custom"), "value")
  402. c.Header("Content-Type", "text/html")
  403. c.Header("X-Custom", "")
  404. assert.Equal(t, c.Writer.Header().Get("Content-Type"), "text/html")
  405. _, exist := c.Writer.Header()["X-Custom"]
  406. assert.False(t, exist)
  407. }
  408. // TODO
  409. func TestContextRenderRedirectWithRelativePath(t *testing.T) {
  410. c, w, _ := CreateTestContext()
  411. c.Request, _ = http.NewRequest("POST", "http://example.com", nil)
  412. assert.Panics(t, func() { c.Redirect(299, "/new_path") })
  413. assert.Panics(t, func() { c.Redirect(309, "/new_path") })
  414. c.Redirect(301, "/path")
  415. c.Writer.WriteHeaderNow()
  416. assert.Equal(t, w.Code, 301)
  417. assert.Equal(t, w.Header().Get("Location"), "/path")
  418. }
  419. func TestContextRenderRedirectWithAbsolutePath(t *testing.T) {
  420. c, w, _ := CreateTestContext()
  421. c.Request, _ = http.NewRequest("POST", "http://example.com", nil)
  422. c.Redirect(302, "http://google.com")
  423. c.Writer.WriteHeaderNow()
  424. assert.Equal(t, w.Code, 302)
  425. assert.Equal(t, w.Header().Get("Location"), "http://google.com")
  426. }
  427. func TestContextRenderRedirectWith201(t *testing.T) {
  428. c, w, _ := CreateTestContext()
  429. c.Request, _ = http.NewRequest("POST", "http://example.com", nil)
  430. c.Redirect(201, "/resource")
  431. c.Writer.WriteHeaderNow()
  432. assert.Equal(t, w.Code, 201)
  433. assert.Equal(t, w.Header().Get("Location"), "/resource")
  434. }
  435. func TestContextRenderRedirectAll(t *testing.T) {
  436. c, _, _ := CreateTestContext()
  437. c.Request, _ = http.NewRequest("POST", "http://example.com", nil)
  438. assert.Panics(t, func() { c.Redirect(200, "/resource") })
  439. assert.Panics(t, func() { c.Redirect(202, "/resource") })
  440. assert.Panics(t, func() { c.Redirect(299, "/resource") })
  441. assert.Panics(t, func() { c.Redirect(309, "/resource") })
  442. assert.NotPanics(t, func() { c.Redirect(300, "/resource") })
  443. assert.NotPanics(t, func() { c.Redirect(308, "/resource") })
  444. }
  445. func TestContextNegotiationFormat(t *testing.T) {
  446. c, _, _ := CreateTestContext()
  447. c.Request, _ = http.NewRequest("POST", "", nil)
  448. assert.Panics(t, func() { c.NegotiateFormat() })
  449. assert.Equal(t, c.NegotiateFormat(MIMEJSON, MIMEXML), MIMEJSON)
  450. assert.Equal(t, c.NegotiateFormat(MIMEHTML, MIMEJSON), MIMEHTML)
  451. }
  452. func TestContextNegotiationFormatWithAccept(t *testing.T) {
  453. c, _, _ := CreateTestContext()
  454. c.Request, _ = http.NewRequest("POST", "/", nil)
  455. c.Request.Header.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
  456. assert.Equal(t, c.NegotiateFormat(MIMEJSON, MIMEXML), MIMEXML)
  457. assert.Equal(t, c.NegotiateFormat(MIMEXML, MIMEHTML), MIMEHTML)
  458. assert.Equal(t, c.NegotiateFormat(MIMEJSON), "")
  459. }
  460. func TestContextNegotiationFormatCustum(t *testing.T) {
  461. c, _, _ := CreateTestContext()
  462. c.Request, _ = http.NewRequest("POST", "/", nil)
  463. c.Request.Header.Add("Accept", "text/html,application/xhtml+xml,application/xml;q=0.9,*/*;q=0.8")
  464. c.Accepted = nil
  465. c.SetAccepted(MIMEJSON, MIMEXML)
  466. assert.Equal(t, c.NegotiateFormat(MIMEJSON, MIMEXML), MIMEJSON)
  467. assert.Equal(t, c.NegotiateFormat(MIMEXML, MIMEHTML), MIMEXML)
  468. assert.Equal(t, c.NegotiateFormat(MIMEJSON), MIMEJSON)
  469. }
  470. func TestContextIsAborted(t *testing.T) {
  471. c, _, _ := CreateTestContext()
  472. assert.False(t, c.IsAborted())
  473. c.Abort()
  474. assert.True(t, c.IsAborted())
  475. c.Next()
  476. assert.True(t, c.IsAborted())
  477. c.index++
  478. assert.True(t, c.IsAborted())
  479. }
  480. // TestContextData tests that the response can be written from `bytesting`
  481. // with specified MIME type
  482. func TestContextAbortWithStatus(t *testing.T) {
  483. c, w, _ := CreateTestContext()
  484. c.index = 4
  485. c.AbortWithStatus(401)
  486. assert.Equal(t, c.index, abortIndex)
  487. assert.Equal(t, c.Writer.Status(), 401)
  488. assert.Equal(t, w.Code, 401)
  489. assert.True(t, c.IsAborted())
  490. }
  491. func TestContextError(t *testing.T) {
  492. c, _, _ := CreateTestContext()
  493. assert.Empty(t, c.Errors)
  494. c.Error(errors.New("first error"))
  495. assert.Len(t, c.Errors, 1)
  496. assert.Equal(t, c.Errors.String(), "Error #01: first error\n")
  497. c.Error(&Error{
  498. Err: errors.New("second error"),
  499. Meta: "some data 2",
  500. Type: ErrorTypePublic,
  501. })
  502. assert.Len(t, c.Errors, 2)
  503. assert.Equal(t, c.Errors[0].Err, errors.New("first error"))
  504. assert.Nil(t, c.Errors[0].Meta)
  505. assert.Equal(t, c.Errors[0].Type, ErrorTypePrivate)
  506. assert.Equal(t, c.Errors[1].Err, errors.New("second error"))
  507. assert.Equal(t, c.Errors[1].Meta, "some data 2")
  508. assert.Equal(t, c.Errors[1].Type, ErrorTypePublic)
  509. assert.Equal(t, c.Errors.Last(), c.Errors[1])
  510. }
  511. func TestContextTypedError(t *testing.T) {
  512. c, _, _ := CreateTestContext()
  513. c.Error(errors.New("externo 0")).SetType(ErrorTypePublic)
  514. c.Error(errors.New("interno 0")).SetType(ErrorTypePrivate)
  515. for _, err := range c.Errors.ByType(ErrorTypePublic) {
  516. assert.Equal(t, err.Type, ErrorTypePublic)
  517. }
  518. for _, err := range c.Errors.ByType(ErrorTypePrivate) {
  519. assert.Equal(t, err.Type, ErrorTypePrivate)
  520. }
  521. assert.Equal(t, c.Errors.Errors(), []string{"externo 0", "interno 0"})
  522. }
  523. func TestContextAbortWithError(t *testing.T) {
  524. c, w, _ := CreateTestContext()
  525. c.AbortWithError(401, errors.New("bad input")).SetMeta("some input")
  526. assert.Equal(t, w.Code, 401)
  527. assert.Equal(t, c.index, abortIndex)
  528. assert.True(t, c.IsAborted())
  529. }
  530. func TestContextClientIP(t *testing.T) {
  531. c, _, _ := CreateTestContext()
  532. c.Request, _ = http.NewRequest("POST", "/", nil)
  533. c.Request.Header.Set("X-Real-IP", " 10.10.10.10 ")
  534. c.Request.Header.Set("X-Forwarded-For", " 20.20.20.20, 30.30.30.30")
  535. c.Request.RemoteAddr = " 40.40.40.40:42123 "
  536. assert.Equal(t, c.ClientIP(), "10.10.10.10")
  537. c.Request.Header.Del("X-Real-IP")
  538. assert.Equal(t, c.ClientIP(), "20.20.20.20")
  539. c.Request.Header.Set("X-Forwarded-For", "30.30.30.30 ")
  540. assert.Equal(t, c.ClientIP(), "30.30.30.30")
  541. c.Request.Header.Del("X-Forwarded-For")
  542. assert.Equal(t, c.ClientIP(), "40.40.40.40")
  543. }
  544. func TestContextContentType(t *testing.T) {
  545. c, _, _ := CreateTestContext()
  546. c.Request, _ = http.NewRequest("POST", "/", nil)
  547. c.Request.Header.Set("Content-Type", "application/json; charset=utf-8")
  548. assert.Equal(t, c.ContentType(), "application/json")
  549. }
  550. func TestContextAutoBindJSON(t *testing.T) {
  551. c, _, _ := CreateTestContext()
  552. c.Request, _ = http.NewRequest("POST", "/", bytes.NewBufferString("{\"foo\":\"bar\", \"bar\":\"foo\"}"))
  553. c.Request.Header.Add("Content-Type", MIMEJSON)
  554. var obj struct {
  555. Foo string `json:"foo"`
  556. Bar string `json:"bar"`
  557. }
  558. assert.NoError(t, c.Bind(&obj))
  559. assert.Equal(t, obj.Bar, "foo")
  560. assert.Equal(t, obj.Foo, "bar")
  561. assert.Empty(t, c.Errors)
  562. }
  563. func TestContextBindWithJSON(t *testing.T) {
  564. c, w, _ := CreateTestContext()
  565. c.Request, _ = http.NewRequest("POST", "/", bytes.NewBufferString("{\"foo\":\"bar\", \"bar\":\"foo\"}"))
  566. c.Request.Header.Add("Content-Type", MIMEXML) // set fake content-type
  567. var obj struct {
  568. Foo string `json:"foo"`
  569. Bar string `json:"bar"`
  570. }
  571. assert.NoError(t, c.BindJSON(&obj))
  572. assert.Equal(t, obj.Bar, "foo")
  573. assert.Equal(t, obj.Foo, "bar")
  574. assert.Equal(t, w.Body.Len(), 0)
  575. }
  576. func TestContextBadAutoBind(t *testing.T) {
  577. c, w, _ := CreateTestContext()
  578. c.Request, _ = http.NewRequest("POST", "http://example.com", bytes.NewBufferString("\"foo\":\"bar\", \"bar\":\"foo\"}"))
  579. c.Request.Header.Add("Content-Type", MIMEJSON)
  580. var obj struct {
  581. Foo string `json:"foo"`
  582. Bar string `json:"bar"`
  583. }
  584. assert.False(t, c.IsAborted())
  585. assert.Error(t, c.Bind(&obj))
  586. c.Writer.WriteHeaderNow()
  587. assert.Empty(t, obj.Bar)
  588. assert.Empty(t, obj.Foo)
  589. assert.Equal(t, w.Code, 400)
  590. assert.True(t, c.IsAborted())
  591. }
  592. func TestContextGolangContext(t *testing.T) {
  593. c, _, _ := CreateTestContext()
  594. c.Request, _ = http.NewRequest("POST", "/", bytes.NewBufferString("{\"foo\":\"bar\", \"bar\":\"foo\"}"))
  595. assert.NoError(t, c.Err())
  596. assert.Nil(t, c.Done())
  597. ti, ok := c.Deadline()
  598. assert.Equal(t, ti, time.Time{})
  599. assert.False(t, ok)
  600. assert.Equal(t, c.Value(0), c.Request)
  601. assert.Nil(t, c.Value("foo"))
  602. c.Set("foo", "bar")
  603. assert.Equal(t, c.Value("foo"), "bar")
  604. assert.Nil(t, c.Value(1))
  605. }