context_test.go 8.8 KB

123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314
  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. ctx.SetParams(":name", ctx.Params(":name"))
  117. buf.WriteString(ctx.Params(":name") + " ")
  118. buf.WriteString(ctx.ParamsEscape(":name") + " ")
  119. buf.WriteString(com.ToStr(ctx.ParamsInt(":int")) + " ")
  120. buf.WriteString(com.ToStr(ctx.ParamsInt64(":int64")) + " ")
  121. return buf.String()
  122. })
  123. resp := httptest.NewRecorder()
  124. req, err := http.NewRequest("GET", "/user/1/13", nil)
  125. So(err, ShouldBeNil)
  126. m.ServeHTTP(resp, req)
  127. So(resp.Body.String(), ShouldEqual, "user user 1 13 ")
  128. })
  129. Convey("Get file", func() {
  130. m.Get("/getfile", func(ctx *Context) {
  131. ctx.GetFile("hi")
  132. })
  133. resp := httptest.NewRecorder()
  134. req, err := http.NewRequest("GET", "/getfile", nil)
  135. So(err, ShouldBeNil)
  136. m.ServeHTTP(resp, req)
  137. })
  138. Convey("Set and get cookie", func() {
  139. m.Get("/set", func(ctx *Context) {
  140. ctx.SetCookie("user", "Unknwon", 1)
  141. })
  142. resp := httptest.NewRecorder()
  143. req, err := http.NewRequest("GET", "/set", nil)
  144. So(err, ShouldBeNil)
  145. m.ServeHTTP(resp, req)
  146. So(resp.Header().Get("Set-Cookie"), ShouldEqual, "user=Unknwon; Path=/; Max-Age=1")
  147. m.Get("/get", func(ctx *Context) string {
  148. ctx.GetCookie("404")
  149. So(ctx.GetCookieInt("uid"), ShouldEqual, 1)
  150. So(ctx.GetCookieInt64("uid"), ShouldEqual, 1)
  151. return ctx.GetCookie("user")
  152. })
  153. resp = httptest.NewRecorder()
  154. req, err = http.NewRequest("GET", "/get", nil)
  155. So(err, ShouldBeNil)
  156. req.Header.Set("Cookie", "user=Unknwon; uid=1")
  157. m.ServeHTTP(resp, req)
  158. So(resp.Body.String(), ShouldEqual, "Unknwon")
  159. })
  160. Convey("Set and get secure cookie", func() {
  161. m.SetDefaultCookieSecret("macaron")
  162. m.Get("/set", func(ctx *Context) {
  163. ctx.SetSecureCookie("user", "Unknwon", 1)
  164. })
  165. resp := httptest.NewRecorder()
  166. req, err := http.NewRequest("GET", "/set", nil)
  167. So(err, ShouldBeNil)
  168. m.ServeHTTP(resp, req)
  169. cookie := resp.Header().Get("Set-Cookie")
  170. m.Get("/get", func(ctx *Context) string {
  171. name, ok := ctx.GetSecureCookie("user")
  172. So(ok, ShouldBeTrue)
  173. return name
  174. })
  175. resp = httptest.NewRecorder()
  176. req, err = http.NewRequest("GET", "/get", nil)
  177. So(err, ShouldBeNil)
  178. req.Header.Set("Cookie", cookie)
  179. m.ServeHTTP(resp, req)
  180. So(resp.Body.String(), ShouldEqual, "Unknwon")
  181. })
  182. Convey("Serve files", func() {
  183. m.Get("/file", func(ctx *Context) {
  184. ctx.ServeFile("fixtures/custom_funcs/index.tmpl")
  185. })
  186. resp := httptest.NewRecorder()
  187. req, err := http.NewRequest("GET", "/file", nil)
  188. So(err, ShouldBeNil)
  189. m.ServeHTTP(resp, req)
  190. So(resp.Body.String(), ShouldEqual, "{{ myCustomFunc }}")
  191. m.Get("/file2", func(ctx *Context) {
  192. ctx.ServeFile("fixtures/custom_funcs/index.tmpl", "ok.tmpl")
  193. })
  194. resp = httptest.NewRecorder()
  195. req, err = http.NewRequest("GET", "/file2", nil)
  196. So(err, ShouldBeNil)
  197. m.ServeHTTP(resp, req)
  198. So(resp.Body.String(), ShouldEqual, "{{ myCustomFunc }}")
  199. })
  200. Convey("Serve content", func() {
  201. m.Get("/content", func(ctx *Context) {
  202. ctx.ServeContent("content1", bytes.NewReader([]byte("Hello world!")))
  203. })
  204. resp := httptest.NewRecorder()
  205. req, err := http.NewRequest("GET", "/content", nil)
  206. So(err, ShouldBeNil)
  207. m.ServeHTTP(resp, req)
  208. So(resp.Body.String(), ShouldEqual, "Hello world!")
  209. m.Get("/content2", func(ctx *Context) {
  210. ctx.ServeContent("content1", bytes.NewReader([]byte("Hello world!")), time.Now())
  211. })
  212. resp = httptest.NewRecorder()
  213. req, err = http.NewRequest("GET", "/content2", nil)
  214. So(err, ShouldBeNil)
  215. m.ServeHTTP(resp, req)
  216. So(resp.Body.String(), ShouldEqual, "Hello world!")
  217. })
  218. })
  219. }
  220. func Test_Context_Render(t *testing.T) {
  221. Convey("Invalid render", t, func() {
  222. defer func() {
  223. So(recover(), ShouldNotBeNil)
  224. }()
  225. m := New()
  226. m.Get("/", func(ctx *Context) {
  227. ctx.HTML(200, "hey")
  228. })
  229. resp := httptest.NewRecorder()
  230. req, err := http.NewRequest("GET", "/", nil)
  231. So(err, ShouldBeNil)
  232. m.ServeHTTP(resp, req)
  233. })
  234. }
  235. func Test_Context_Redirect(t *testing.T) {
  236. Convey("Context with default redirect", t, func() {
  237. url, err := url.Parse("http://localhost/path/one")
  238. So(err, ShouldBeNil)
  239. resp := httptest.NewRecorder()
  240. req := http.Request{
  241. Method: "GET",
  242. URL: url,
  243. }
  244. ctx := &Context{
  245. Req: Request{&req},
  246. Resp: NewResponseWriter(resp),
  247. Data: make(map[string]interface{}),
  248. }
  249. ctx.Redirect("two")
  250. So(resp.Code, ShouldEqual, http.StatusFound)
  251. So(resp.HeaderMap["Location"][0], ShouldEqual, "/path/two")
  252. })
  253. Convey("Context with custom redirect", t, func() {
  254. url, err := url.Parse("http://localhost/path/one")
  255. So(err, ShouldBeNil)
  256. resp := httptest.NewRecorder()
  257. req := http.Request{
  258. Method: "GET",
  259. URL: url,
  260. }
  261. ctx := &Context{
  262. Req: Request{&req},
  263. Resp: NewResponseWriter(resp),
  264. Data: make(map[string]interface{}),
  265. }
  266. ctx.Redirect("two", 307)
  267. So(resp.Code, ShouldEqual, http.StatusTemporaryRedirect)
  268. So(resp.HeaderMap["Location"][0], ShouldEqual, "/path/two")
  269. })
  270. }