123456789101112131415161718192021222324252627282930313233343536373839404142434445464748495051525354555657585960616263646566676869707172737475767778798081828384858687888990919293949596979899100101102103104105106107108109110111112113114115116117118119120121122123124125126127128129130131132133134135136137138139140141142143144145146147148149150151152153154155156157158159160161162163164165166167168169170171172173174175176177178179180181182183184185186187188189190191192193194195196197198199200201202203204205206207208209210211212213214215216217218219220221222223224225226227228229230231232233234235236237238239240241242243244245246247248249250251252253254255256257258259260261262263264265266267268269270271272273274275276277278279280281282283284285286287288289290291292293294295296297298299300301302303304305306307308309310311312313314315316317318319320321322323324325326327328329330331332333334335336337338339340341342343344345346347348349350351352353354355356357358359360361362363364365366367368369370371372373374375376377378379380381382383384385386387388389390391392393394395396397398399400401402403404405406407408409410411412413414415416417418419420421422423424425426427428429430431432433434 |
- // Copyright 2014 Manu Martinez-Almeida. All rights reserved.
- // Use of this source code is governed by a MIT style
- // license that can be found in the LICENSE file.
- package gin
- import (
- "bytes"
- "errors"
- "fmt"
- "net/http"
- "testing"
- "time"
- "github.com/stretchr/testify/assert"
- )
- func init() {
- SetMode(TestMode)
- }
- func TestLogger(t *testing.T) {
- buffer := new(bytes.Buffer)
- router := New()
- router.Use(LoggerWithWriter(buffer))
- router.GET("/example", func(c *Context) {})
- router.POST("/example", func(c *Context) {})
- router.PUT("/example", func(c *Context) {})
- router.DELETE("/example", func(c *Context) {})
- router.PATCH("/example", func(c *Context) {})
- router.HEAD("/example", func(c *Context) {})
- router.OPTIONS("/example", func(c *Context) {})
- performRequest(router, "GET", "/example?a=100")
- assert.Contains(t, buffer.String(), "200")
- assert.Contains(t, buffer.String(), "GET")
- assert.Contains(t, buffer.String(), "/example")
- assert.Contains(t, buffer.String(), "a=100")
- // I wrote these first (extending the above) but then realized they are more
- // like integration tests because they test the whole logging process rather
- // than individual functions. Im not sure where these should go.
- buffer.Reset()
- performRequest(router, "POST", "/example")
- assert.Contains(t, buffer.String(), "200")
- assert.Contains(t, buffer.String(), "POST")
- assert.Contains(t, buffer.String(), "/example")
- buffer.Reset()
- performRequest(router, "PUT", "/example")
- assert.Contains(t, buffer.String(), "200")
- assert.Contains(t, buffer.String(), "PUT")
- assert.Contains(t, buffer.String(), "/example")
- buffer.Reset()
- performRequest(router, "DELETE", "/example")
- assert.Contains(t, buffer.String(), "200")
- assert.Contains(t, buffer.String(), "DELETE")
- assert.Contains(t, buffer.String(), "/example")
- buffer.Reset()
- performRequest(router, "PATCH", "/example")
- assert.Contains(t, buffer.String(), "200")
- assert.Contains(t, buffer.String(), "PATCH")
- assert.Contains(t, buffer.String(), "/example")
- buffer.Reset()
- performRequest(router, "HEAD", "/example")
- assert.Contains(t, buffer.String(), "200")
- assert.Contains(t, buffer.String(), "HEAD")
- assert.Contains(t, buffer.String(), "/example")
- buffer.Reset()
- performRequest(router, "OPTIONS", "/example")
- assert.Contains(t, buffer.String(), "200")
- assert.Contains(t, buffer.String(), "OPTIONS")
- assert.Contains(t, buffer.String(), "/example")
- buffer.Reset()
- performRequest(router, "GET", "/notfound")
- assert.Contains(t, buffer.String(), "404")
- assert.Contains(t, buffer.String(), "GET")
- assert.Contains(t, buffer.String(), "/notfound")
- }
- func TestLoggerWithConfig(t *testing.T) {
- buffer := new(bytes.Buffer)
- router := New()
- router.Use(LoggerWithConfig(LoggerConfig{Output: buffer}))
- router.GET("/example", func(c *Context) {})
- router.POST("/example", func(c *Context) {})
- router.PUT("/example", func(c *Context) {})
- router.DELETE("/example", func(c *Context) {})
- router.PATCH("/example", func(c *Context) {})
- router.HEAD("/example", func(c *Context) {})
- router.OPTIONS("/example", func(c *Context) {})
- performRequest(router, "GET", "/example?a=100")
- assert.Contains(t, buffer.String(), "200")
- assert.Contains(t, buffer.String(), "GET")
- assert.Contains(t, buffer.String(), "/example")
- assert.Contains(t, buffer.String(), "a=100")
- // I wrote these first (extending the above) but then realized they are more
- // like integration tests because they test the whole logging process rather
- // than individual functions. Im not sure where these should go.
- buffer.Reset()
- performRequest(router, "POST", "/example")
- assert.Contains(t, buffer.String(), "200")
- assert.Contains(t, buffer.String(), "POST")
- assert.Contains(t, buffer.String(), "/example")
- buffer.Reset()
- performRequest(router, "PUT", "/example")
- assert.Contains(t, buffer.String(), "200")
- assert.Contains(t, buffer.String(), "PUT")
- assert.Contains(t, buffer.String(), "/example")
- buffer.Reset()
- performRequest(router, "DELETE", "/example")
- assert.Contains(t, buffer.String(), "200")
- assert.Contains(t, buffer.String(), "DELETE")
- assert.Contains(t, buffer.String(), "/example")
- buffer.Reset()
- performRequest(router, "PATCH", "/example")
- assert.Contains(t, buffer.String(), "200")
- assert.Contains(t, buffer.String(), "PATCH")
- assert.Contains(t, buffer.String(), "/example")
- buffer.Reset()
- performRequest(router, "HEAD", "/example")
- assert.Contains(t, buffer.String(), "200")
- assert.Contains(t, buffer.String(), "HEAD")
- assert.Contains(t, buffer.String(), "/example")
- buffer.Reset()
- performRequest(router, "OPTIONS", "/example")
- assert.Contains(t, buffer.String(), "200")
- assert.Contains(t, buffer.String(), "OPTIONS")
- assert.Contains(t, buffer.String(), "/example")
- buffer.Reset()
- performRequest(router, "GET", "/notfound")
- assert.Contains(t, buffer.String(), "404")
- assert.Contains(t, buffer.String(), "GET")
- assert.Contains(t, buffer.String(), "/notfound")
- }
- func TestLoggerWithFormatter(t *testing.T) {
- buffer := new(bytes.Buffer)
- d := DefaultWriter
- DefaultWriter = buffer
- defer func() {
- DefaultWriter = d
- }()
- router := New()
- router.Use(LoggerWithFormatter(func(param LogFormatterParams) string {
- return fmt.Sprintf("[FORMATTER TEST] %v | %3d | %13v | %15s | %-7s %s\n%s",
- param.TimeStamp.Format("2006/01/02 - 15:04:05"),
- param.StatusCode,
- param.Latency,
- param.ClientIP,
- param.Method,
- param.Path,
- param.ErrorMessage,
- )
- }))
- router.GET("/example", func(c *Context) {})
- performRequest(router, "GET", "/example?a=100")
- // output test
- assert.Contains(t, buffer.String(), "[FORMATTER TEST]")
- assert.Contains(t, buffer.String(), "200")
- assert.Contains(t, buffer.String(), "GET")
- assert.Contains(t, buffer.String(), "/example")
- assert.Contains(t, buffer.String(), "a=100")
- }
- func TestLoggerWithConfigFormatting(t *testing.T) {
- var gotParam LogFormatterParams
- var gotKeys map[string]interface{}
- buffer := new(bytes.Buffer)
- router := New()
- router.Use(LoggerWithConfig(LoggerConfig{
- Output: buffer,
- Formatter: func(param LogFormatterParams) string {
- // for assert test
- gotParam = param
- return fmt.Sprintf("[FORMATTER TEST] %v | %3d | %13v | %15s | %-7s %s\n%s",
- param.TimeStamp.Format("2006/01/02 - 15:04:05"),
- param.StatusCode,
- param.Latency,
- param.ClientIP,
- param.Method,
- param.Path,
- param.ErrorMessage,
- )
- },
- }))
- router.GET("/example", func(c *Context) {
- // set dummy ClientIP
- c.Request.Header.Set("X-Forwarded-For", "20.20.20.20")
- gotKeys = c.Keys
- })
- performRequest(router, "GET", "/example?a=100")
- // output test
- assert.Contains(t, buffer.String(), "[FORMATTER TEST]")
- assert.Contains(t, buffer.String(), "200")
- assert.Contains(t, buffer.String(), "GET")
- assert.Contains(t, buffer.String(), "/example")
- assert.Contains(t, buffer.String(), "a=100")
- // LogFormatterParams test
- assert.NotNil(t, gotParam.Request)
- assert.NotEmpty(t, gotParam.TimeStamp)
- assert.Equal(t, 200, gotParam.StatusCode)
- assert.NotEmpty(t, gotParam.Latency)
- assert.Equal(t, "20.20.20.20", gotParam.ClientIP)
- assert.Equal(t, "GET", gotParam.Method)
- assert.Equal(t, "/example?a=100", gotParam.Path)
- assert.Empty(t, gotParam.ErrorMessage)
- assert.Equal(t, gotKeys, gotParam.Keys)
- }
- func TestDefaultLogFormatter(t *testing.T) {
- timeStamp := time.Unix(1544173902, 0).UTC()
- termFalseParam := LogFormatterParams{
- TimeStamp: timeStamp,
- StatusCode: 200,
- Latency: time.Second * 5,
- ClientIP: "20.20.20.20",
- Method: "GET",
- Path: "/",
- ErrorMessage: "",
- isTerm: false,
- }
- termTrueParam := LogFormatterParams{
- TimeStamp: timeStamp,
- StatusCode: 200,
- Latency: time.Second * 5,
- ClientIP: "20.20.20.20",
- Method: "GET",
- Path: "/",
- ErrorMessage: "",
- isTerm: true,
- }
- termTrueLongDurationParam := LogFormatterParams{
- TimeStamp: timeStamp,
- StatusCode: 200,
- Latency: time.Millisecond * 9876543210,
- ClientIP: "20.20.20.20",
- Method: "GET",
- Path: "/",
- ErrorMessage: "",
- isTerm: true,
- }
- termFalseLongDurationParam := LogFormatterParams{
- TimeStamp: timeStamp,
- StatusCode: 200,
- Latency: time.Millisecond * 9876543210,
- ClientIP: "20.20.20.20",
- Method: "GET",
- Path: "/",
- ErrorMessage: "",
- isTerm: false,
- }
- assert.Equal(t, "[GIN] 2018/12/07 - 09:11:42 | 200 | 5s | 20.20.20.20 | GET /\n", defaultLogFormatter(termFalseParam))
- assert.Equal(t, "[GIN] 2018/12/07 - 09:11:42 | 200 | 2743h29m3s | 20.20.20.20 | GET /\n", defaultLogFormatter(termFalseLongDurationParam))
- assert.Equal(t, "[GIN] 2018/12/07 - 09:11:42 |\x1b[97;42m 200 \x1b[0m| 5s | 20.20.20.20 |\x1b[97;44m GET \x1b[0m /\n", defaultLogFormatter(termTrueParam))
- assert.Equal(t, "[GIN] 2018/12/07 - 09:11:42 |\x1b[97;42m 200 \x1b[0m| 2743h29m3s | 20.20.20.20 |\x1b[97;44m GET \x1b[0m /\n", defaultLogFormatter(termTrueLongDurationParam))
- }
- func TestColorForMethod(t *testing.T) {
- colorForMethod := func(method string) string {
- p := LogFormatterParams{
- Method: method,
- }
- return p.MethodColor()
- }
- assert.Equal(t, blue, colorForMethod("GET"), "get should be blue")
- assert.Equal(t, cyan, colorForMethod("POST"), "post should be cyan")
- assert.Equal(t, yellow, colorForMethod("PUT"), "put should be yellow")
- assert.Equal(t, red, colorForMethod("DELETE"), "delete should be red")
- assert.Equal(t, green, colorForMethod("PATCH"), "patch should be green")
- assert.Equal(t, magenta, colorForMethod("HEAD"), "head should be magenta")
- assert.Equal(t, white, colorForMethod("OPTIONS"), "options should be white")
- assert.Equal(t, reset, colorForMethod("TRACE"), "trace is not defined and should be the reset color")
- }
- func TestColorForStatus(t *testing.T) {
- colorForStatus := func(code int) string {
- p := LogFormatterParams{
- StatusCode: code,
- }
- return p.StatusCodeColor()
- }
- assert.Equal(t, green, colorForStatus(http.StatusOK), "2xx should be green")
- assert.Equal(t, white, colorForStatus(http.StatusMovedPermanently), "3xx should be white")
- assert.Equal(t, yellow, colorForStatus(http.StatusNotFound), "4xx should be yellow")
- assert.Equal(t, red, colorForStatus(2), "other things should be red")
- }
- func TestResetColor(t *testing.T) {
- p := LogFormatterParams{}
- assert.Equal(t, string([]byte{27, 91, 48, 109}), p.ResetColor())
- }
- func TestIsOutputColor(t *testing.T) {
- // test with isTerm flag true.
- p := LogFormatterParams{
- isTerm: true,
- }
- consoleColorMode = autoColor
- assert.Equal(t, true, p.IsOutputColor())
- ForceConsoleColor()
- assert.Equal(t, true, p.IsOutputColor())
- DisableConsoleColor()
- assert.Equal(t, false, p.IsOutputColor())
- // test with isTerm flag false.
- p = LogFormatterParams{
- isTerm: false,
- }
- consoleColorMode = autoColor
- assert.Equal(t, false, p.IsOutputColor())
- ForceConsoleColor()
- assert.Equal(t, true, p.IsOutputColor())
- DisableConsoleColor()
- assert.Equal(t, false, p.IsOutputColor())
- // reset console color mode.
- consoleColorMode = autoColor
- }
- func TestErrorLogger(t *testing.T) {
- router := New()
- router.Use(ErrorLogger())
- router.GET("/error", func(c *Context) {
- c.Error(errors.New("this is an error")) // nolint: errcheck
- })
- router.GET("/abort", func(c *Context) {
- c.AbortWithError(http.StatusUnauthorized, errors.New("no authorized")) // nolint: errcheck
- })
- router.GET("/print", func(c *Context) {
- c.Error(errors.New("this is an error")) // nolint: errcheck
- c.String(http.StatusInternalServerError, "hola!")
- })
- w := performRequest(router, "GET", "/error")
- assert.Equal(t, http.StatusOK, w.Code)
- assert.Equal(t, "{\"error\":\"this is an error\"}\n", w.Body.String())
- w = performRequest(router, "GET", "/abort")
- assert.Equal(t, http.StatusUnauthorized, w.Code)
- assert.Equal(t, "{\"error\":\"no authorized\"}\n", w.Body.String())
- w = performRequest(router, "GET", "/print")
- assert.Equal(t, http.StatusInternalServerError, w.Code)
- assert.Equal(t, "hola!{\"error\":\"this is an error\"}\n", w.Body.String())
- }
- func TestLoggerWithWriterSkippingPaths(t *testing.T) {
- buffer := new(bytes.Buffer)
- router := New()
- router.Use(LoggerWithWriter(buffer, "/skipped"))
- router.GET("/logged", func(c *Context) {})
- router.GET("/skipped", func(c *Context) {})
- performRequest(router, "GET", "/logged")
- assert.Contains(t, buffer.String(), "200")
- buffer.Reset()
- performRequest(router, "GET", "/skipped")
- assert.Contains(t, buffer.String(), "")
- }
- func TestLoggerWithConfigSkippingPaths(t *testing.T) {
- buffer := new(bytes.Buffer)
- router := New()
- router.Use(LoggerWithConfig(LoggerConfig{
- Output: buffer,
- SkipPaths: []string{"/skipped"},
- }))
- router.GET("/logged", func(c *Context) {})
- router.GET("/skipped", func(c *Context) {})
- performRequest(router, "GET", "/logged")
- assert.Contains(t, buffer.String(), "200")
- buffer.Reset()
- performRequest(router, "GET", "/skipped")
- assert.Contains(t, buffer.String(), "")
- }
- func TestDisableConsoleColor(t *testing.T) {
- New()
- assert.Equal(t, autoColor, consoleColorMode)
- DisableConsoleColor()
- assert.Equal(t, disableColor, consoleColorMode)
- // reset console color mode.
- consoleColorMode = autoColor
- }
- func TestForceConsoleColor(t *testing.T) {
- New()
- assert.Equal(t, autoColor, consoleColorMode)
- ForceConsoleColor()
- assert.Equal(t, forceColor, consoleColorMode)
- // reset console color mode.
- consoleColorMode = autoColor
- }
|