logger_test.go 1.8 KB

12345678910111213141516171819202122232425262728293031323334353637383940414243444546474849505152535455565758596061626364656667
  1. // Copyright 2013 Martini Authors
  2. // Copyright 2014 Unknwon
  3. //
  4. // Licensed under the Apache License, Version 2.0 (the "License"): you may
  5. // not use this file except in compliance with the License. You may obtain
  6. // a copy of the License at
  7. //
  8. // http://www.apache.org/licenses/LICENSE-2.0
  9. //
  10. // Unless required by applicable law or agreed to in writing, software
  11. // distributed under the License is distributed on an "AS IS" BASIS, WITHOUT
  12. // WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied. See the
  13. // License for the specific language governing permissions and limitations
  14. // under the License.
  15. package macaron
  16. import (
  17. "bytes"
  18. "log"
  19. "net/http"
  20. "net/http/httptest"
  21. "testing"
  22. "github.com/Unknwon/com"
  23. . "github.com/smartystreets/goconvey/convey"
  24. )
  25. func Test_Logger(t *testing.T) {
  26. Convey("Global logger", t, func() {
  27. buf := bytes.NewBufferString("")
  28. m := New()
  29. m.Map(log.New(buf, "[Macaron] ", 0))
  30. m.Use(Logger())
  31. m.Use(func(res http.ResponseWriter) {
  32. res.WriteHeader(http.StatusNotFound)
  33. })
  34. m.Get("/", func() {})
  35. resp := httptest.NewRecorder()
  36. req, err := http.NewRequest("GET", "http://localhost:4000/", nil)
  37. So(err, ShouldBeNil)
  38. m.ServeHTTP(resp, req)
  39. So(resp.Code, ShouldEqual, http.StatusNotFound)
  40. So(len(buf.String()), ShouldBeGreaterThan, 0)
  41. })
  42. if !isWindows {
  43. Convey("Color console output", t, func() {
  44. m := Classic()
  45. m.Get("/:code:int", func(ctx *Context) (int, string) {
  46. return ctx.ParamsInt(":code"), ""
  47. })
  48. // Just for testing if logger would capture.
  49. codes := []int{200, 201, 202, 301, 302, 304, 401, 403, 404, 500}
  50. for _, code := range codes {
  51. resp := httptest.NewRecorder()
  52. req, err := http.NewRequest("GET", "http://localhost:4000/"+com.ToStr(code), nil)
  53. So(err, ShouldBeNil)
  54. m.ServeHTTP(resp, req)
  55. So(resp.Code, ShouldEqual, code)
  56. }
  57. })
  58. }
  59. }