context_test.go 8.9 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312
  1. // Copyright 2014 Unknwon
  2. //
  3. // Licensed under the Apache License, Version 2.0 (the "License"): you may
  4. // not use this file except in compliance with the License. You may obtain
  5. // a copy of the License at
  6. //
  7. // http://www.apache.org/licenses/LICENSE-2.0
  8. //
  9. // Unless required by applicable law or agreed to in writing, software
  10. // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  11. // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  12. // License for the specific language governing permissions and limitations
  13. // under the License.
  14. package macaron
  15. import (
  16. "bytes"
  17. "io/ioutil"
  18. "net/http"
  19. "net/http/httptest"
  20. "net/url"
  21. "strings"
  22. "testing"
  23. "time"
  24. "github.com/Unknwon/com"
  25. . "github.com/smartystreets/goconvey/convey"
  26. )
  27. func Test_Context(t *testing.T) {
  28. Convey("Do advanced encapsulation operations", t, func() {
  29. m := Classic()
  30. m.Use(Renderers(RenderOptions{
  31. Directory: "fixtures/basic",
  32. }, "fixtures/basic2"))
  33. Convey("Get request body", func() {
  34. m.Get("/body1", func(ctx *Context) {
  35. data, err := ioutil.ReadAll(ctx.Req.Body().ReadCloser())
  36. So(err, ShouldBeNil)
  37. So(string(data), ShouldEqual, "This is my request body")
  38. })
  39. m.Get("/body2", func(ctx *Context) {
  40. data, err := ctx.Req.Body().Bytes()
  41. So(err, ShouldBeNil)
  42. So(string(data), ShouldEqual, "This is my request body")
  43. })
  44. m.Get("/body3", func(ctx *Context) {
  45. data, err := ctx.Req.Body().String()
  46. So(err, ShouldBeNil)
  47. So(data, ShouldEqual, "This is my request body")
  48. })
  49. for i := 1; i <= 3; i++ {
  50. resp := httptest.NewRecorder()
  51. req, err := http.NewRequest("GET", "/body"+com.ToStr(i), nil)
  52. req.Body = ioutil.NopCloser(bytes.NewBufferString("This is my request body"))
  53. So(err, ShouldBeNil)
  54. m.ServeHTTP(resp, req)
  55. }
  56. })
  57. Convey("Get remote IP address", func() {
  58. m.Get("/remoteaddr", func(ctx *Context) string {
  59. return ctx.RemoteAddr()
  60. })
  61. resp := httptest.NewRecorder()
  62. req, err := http.NewRequest("GET", "/remoteaddr", nil)
  63. req.RemoteAddr = "127.0.0.1:3333"
  64. So(err, ShouldBeNil)
  65. m.ServeHTTP(resp, req)
  66. So(resp.Body.String(), ShouldEqual, "127.0.0.1")
  67. })
  68. Convey("Render HTML", func() {
  69. m.Get("/html", func(ctx *Context) {
  70. ctx.HTML(304, "hello", "Unknwon") // 304 for logger test.
  71. })
  72. resp := httptest.NewRecorder()
  73. req, err := http.NewRequest("GET", "/html", nil)
  74. So(err, ShouldBeNil)
  75. m.ServeHTTP(resp, req)
  76. So(resp.Body.String(), ShouldEqual, "<h1>Hello Unknwon</h1>")
  77. m.Get("/html2", func(ctx *Context) {
  78. ctx.Data["Name"] = "Unknwon"
  79. ctx.HTMLSet(200, "basic2", "hello2")
  80. })
  81. resp = httptest.NewRecorder()
  82. req, err = http.NewRequest("GET", "/html2", nil)
  83. So(err, ShouldBeNil)
  84. m.ServeHTTP(resp, req)
  85. So(resp.Body.String(), ShouldEqual, "<h1>Hello Unknwon</h1>")
  86. })
  87. Convey("Parse from and query", func() {
  88. m.Get("/query", func(ctx *Context) string {
  89. var buf bytes.Buffer
  90. buf.WriteString(ctx.Query("name") + " ")
  91. buf.WriteString(ctx.QueryEscape("name") + " ")
  92. buf.WriteString(com.ToStr(ctx.QueryInt("int")) + " ")
  93. buf.WriteString(com.ToStr(ctx.QueryInt64("int64")) + " ")
  94. return buf.String()
  95. })
  96. m.Get("/query2", func(ctx *Context) string {
  97. var buf bytes.Buffer
  98. buf.WriteString(strings.Join(ctx.QueryStrings("list"), ",") + " ")
  99. buf.WriteString(strings.Join(ctx.QueryStrings("404"), ",") + " ")
  100. return buf.String()
  101. })
  102. resp := httptest.NewRecorder()
  103. req, err := http.NewRequest("GET", "/query?name=Unknwon&int=12&int64=123", nil)
  104. So(err, ShouldBeNil)
  105. m.ServeHTTP(resp, req)
  106. So(resp.Body.String(), ShouldEqual, "Unknwon Unknwon 12 123 ")
  107. resp = httptest.NewRecorder()
  108. req, err = http.NewRequest("GET", "/query2?list=item1&list=item2", nil)
  109. So(err, ShouldBeNil)
  110. m.ServeHTTP(resp, req)
  111. So(resp.Body.String(), ShouldEqual, "item1,item2 ")
  112. })
  113. Convey("URL parameter", func() {
  114. m.Get("/:name/:int/:int64", func(ctx *Context) string {
  115. var buf bytes.Buffer
  116. buf.WriteString(ctx.Params(":name") + " ")
  117. buf.WriteString(ctx.ParamsEscape(":name") + " ")
  118. buf.WriteString(com.ToStr(ctx.ParamsInt(":int")) + " ")
  119. buf.WriteString(com.ToStr(ctx.ParamsInt64(":int64")) + " ")
  120. return buf.String()
  121. })
  122. resp := httptest.NewRecorder()
  123. req, err := http.NewRequest("GET", "/user/1/13", nil)
  124. So(err, ShouldBeNil)
  125. m.ServeHTTP(resp, req)
  126. So(resp.Body.String(), ShouldEqual, "user user 1 13 ")
  127. })
  128. Convey("Get file", func() {
  129. m.Get("/getfile", func(ctx *Context) {
  130. ctx.GetFile("hi")
  131. })
  132. resp := httptest.NewRecorder()
  133. req, err := http.NewRequest("GET", "/getfile", nil)
  134. So(err, ShouldBeNil)
  135. m.ServeHTTP(resp, req)
  136. })
  137. Convey("Set and get cookie", func() {
  138. m.Get("/set", func(ctx *Context) {
  139. ctx.SetCookie("user", "Unknwon", 1)
  140. })
  141. resp := httptest.NewRecorder()
  142. req, err := http.NewRequest("GET", "/set", nil)
  143. So(err, ShouldBeNil)
  144. m.ServeHTTP(resp, req)
  145. So(resp.Header().Get("Set-Cookie"), ShouldEqual, "user=Unknwon; Path=/; Max-Age=1")
  146. m.Get("/get", func(ctx *Context) string {
  147. ctx.GetCookie("404")
  148. So(ctx.GetCookieInt("uid"), ShouldEqual, 1)
  149. So(ctx.GetCookieInt64("uid"), ShouldEqual, 1)
  150. return ctx.GetCookie("user")
  151. })
  152. resp = httptest.NewRecorder()
  153. req, err = http.NewRequest("GET", "/get", nil)
  154. So(err, ShouldBeNil)
  155. req.Header.Set("Cookie", "user=Unknwon; uid=1")
  156. m.ServeHTTP(resp, req)
  157. So(resp.Body.String(), ShouldEqual, "Unknwon")
  158. })
  159. Convey("Set and get secure cookie", func() {
  160. m.SetDefaultCookieSecret("macaron")
  161. m.Get("/set", func(ctx *Context) {
  162. ctx.SetSecureCookie("user", "Unknwon", 1)
  163. })
  164. resp := httptest.NewRecorder()
  165. req, err := http.NewRequest("GET", "/set", nil)
  166. So(err, ShouldBeNil)
  167. m.ServeHTTP(resp, req)
  168. So(strings.HasPrefix(resp.Header().Get("Set-Cookie"), "user=VW5rbndvbg==|"), ShouldBeTrue)
  169. m.Get("/get", func(ctx *Context) string {
  170. name, ok := ctx.GetSecureCookie("user")
  171. So(ok, ShouldBeTrue)
  172. return name
  173. })
  174. resp = httptest.NewRecorder()
  175. req, err = http.NewRequest("GET", "/get", nil)
  176. So(err, ShouldBeNil)
  177. req.Header.Set("Cookie", "user=VW5rbndvbg==|1409244667158399419|6097781707f68d9940ba1ef0e78cc84aaeebc48f; Path=/; Max-Age=1")
  178. m.ServeHTTP(resp, req)
  179. So(resp.Body.String(), ShouldEqual, "Unknwon")
  180. })
  181. Convey("Serve files", func() {
  182. m.Get("/file", func(ctx *Context) {
  183. ctx.ServeFile("fixtures/custom_funcs/index.tmpl")
  184. })
  185. resp := httptest.NewRecorder()
  186. req, err := http.NewRequest("GET", "/file", nil)
  187. So(err, ShouldBeNil)
  188. m.ServeHTTP(resp, req)
  189. So(resp.Body.String(), ShouldEqual, "{{ myCustomFunc }}")
  190. m.Get("/file2", func(ctx *Context) {
  191. ctx.ServeFile("fixtures/custom_funcs/index.tmpl", "ok.tmpl")
  192. })
  193. resp = httptest.NewRecorder()
  194. req, err = http.NewRequest("GET", "/file2", nil)
  195. So(err, ShouldBeNil)
  196. m.ServeHTTP(resp, req)
  197. So(resp.Body.String(), ShouldEqual, "{{ myCustomFunc }}")
  198. })
  199. Convey("Serve content", func() {
  200. m.Get("/content", func(ctx *Context) {
  201. ctx.ServeContent("content1", bytes.NewReader([]byte("Hello world!")))
  202. })
  203. resp := httptest.NewRecorder()
  204. req, err := http.NewRequest("GET", "/content", nil)
  205. So(err, ShouldBeNil)
  206. m.ServeHTTP(resp, req)
  207. So(resp.Body.String(), ShouldEqual, "Hello world!")
  208. m.Get("/content2", func(ctx *Context) {
  209. ctx.ServeContent("content1", bytes.NewReader([]byte("Hello world!")), time.Now())
  210. })
  211. resp = httptest.NewRecorder()
  212. req, err = http.NewRequest("GET", "/content2", nil)
  213. So(err, ShouldBeNil)
  214. m.ServeHTTP(resp, req)
  215. So(resp.Body.String(), ShouldEqual, "Hello world!")
  216. })
  217. })
  218. }
  219. func Test_Context_Render(t *testing.T) {
  220. Convey("Invalid render", t, func() {
  221. defer func() {
  222. So(recover(), ShouldNotBeNil)
  223. }()
  224. m := New()
  225. m.Get("/", func(ctx *Context) {
  226. ctx.HTML(200, "hey")
  227. })
  228. resp := httptest.NewRecorder()
  229. req, err := http.NewRequest("GET", "/", nil)
  230. So(err, ShouldBeNil)
  231. m.ServeHTTP(resp, req)
  232. })
  233. }
  234. func Test_Context_Redirect(t *testing.T) {
  235. Convey("Context with default redirect", t, func() {
  236. url, err := url.Parse("http://localhost/path/one")
  237. So(err, ShouldBeNil)
  238. resp := httptest.NewRecorder()
  239. req := http.Request{
  240. Method: "GET",
  241. URL: url,
  242. }
  243. ctx := &Context{
  244. Req: Request{&req},
  245. Resp: NewResponseWriter(resp),
  246. Data: make(map[string]interface{}),
  247. }
  248. ctx.Redirect("two")
  249. So(resp.Code, ShouldEqual, http.StatusFound)
  250. So(resp.HeaderMap["Location"][0], ShouldEqual, "/path/two")
  251. })
  252. Convey("Context with custom redirect", t, func() {
  253. url, err := url.Parse("http://localhost/path/one")
  254. So(err, ShouldBeNil)
  255. resp := httptest.NewRecorder()
  256. req := http.Request{
  257. Method: "GET",
  258. URL: url,
  259. }
  260. ctx := &Context{
  261. Req: Request{&req},
  262. Resp: NewResponseWriter(resp),
  263. Data: make(map[string]interface{}),
  264. }
  265. ctx.Redirect("two", 307)
  266. So(resp.Code, ShouldEqual, http.StatusTemporaryRedirect)
  267. So(resp.HeaderMap["Location"][0], ShouldEqual, "/path/two")
  268. })
  269. }