Skip to content
Myr

logger_test.go

This file

Path

logger_test.go

488 lines · 15.6 KiB · Go

Last changed by

test(context): use http.StatusContinue constant instead of magic number 100 (#4542)Mehrdad Banikianbefore adoptionfb25834

History of this file

Take it

1// Copyright 2014 Manu Martinez-Almeida. All rights reserved.2// Use of this source code is governed by a MIT style3// license that can be found in the LICENSE file.45package gin67import (8	"errors"9	"fmt"10	"net/http"11	"strings"12	"testing"13	"time"1415	"github.com/stretchr/testify/assert"16)1718func init() {19	SetMode(TestMode)20}2122func TestLogger(t *testing.T) {23	buffer := new(strings.Builder)24	router := New()25	router.Use(LoggerWithWriter(buffer))26	router.GET("/example", func(c *Context) {})27	router.POST("/example", func(c *Context) {})28	router.PUT("/example", func(c *Context) {})29	router.DELETE("/example", func(c *Context) {})30	router.PATCH("/example", func(c *Context) {})31	router.HEAD("/example", func(c *Context) {})32	router.OPTIONS("/example", func(c *Context) {})3334	PerformRequest(router, http.MethodGet, "/example?a=100")35	assert.Contains(t, buffer.String(), "200")36	assert.Contains(t, buffer.String(), http.MethodGet)37	assert.Contains(t, buffer.String(), "/example")38	assert.Contains(t, buffer.String(), "a=100")3940	// I wrote these first (extending the above) but then realized they are more41	// like integration tests because they test the whole logging process rather42	// than individual functions. I'm not sure where these should go.43	buffer.Reset()44	PerformRequest(router, http.MethodPost, "/example")45	assert.Contains(t, buffer.String(), "200")46	assert.Contains(t, buffer.String(), http.MethodPost)47	assert.Contains(t, buffer.String(), "/example")4849	buffer.Reset()50	PerformRequest(router, http.MethodPut, "/example")51	assert.Contains(t, buffer.String(), "200")52	assert.Contains(t, buffer.String(), http.MethodPut)53	assert.Contains(t, buffer.String(), "/example")5455	buffer.Reset()56	PerformRequest(router, http.MethodDelete, "/example")57	assert.Contains(t, buffer.String(), "200")58	assert.Contains(t, buffer.String(), http.MethodDelete)59	assert.Contains(t, buffer.String(), "/example")6061	buffer.Reset()62	PerformRequest(router, "PATCH", "/example")63	assert.Contains(t, buffer.String(), "200")64	assert.Contains(t, buffer.String(), "PATCH")65	assert.Contains(t, buffer.String(), "/example")6667	buffer.Reset()68	PerformRequest(router, "HEAD", "/example")69	assert.Contains(t, buffer.String(), "200")70	assert.Contains(t, buffer.String(), "HEAD")71	assert.Contains(t, buffer.String(), "/example")7273	buffer.Reset()74	PerformRequest(router, "OPTIONS", "/example")75	assert.Contains(t, buffer.String(), "200")76	assert.Contains(t, buffer.String(), "OPTIONS")77	assert.Contains(t, buffer.String(), "/example")7879	buffer.Reset()80	PerformRequest(router, http.MethodGet, "/notfound")81	assert.Contains(t, buffer.String(), "404")82	assert.Contains(t, buffer.String(), http.MethodGet)83	assert.Contains(t, buffer.String(), "/notfound")84}8586func TestLoggerWithConfig(t *testing.T) {87	buffer := new(strings.Builder)88	router := New()89	router.Use(LoggerWithConfig(LoggerConfig{Output: buffer}))90	router.GET("/example", func(c *Context) {})91	router.POST("/example", func(c *Context) {})92	router.PUT("/example", func(c *Context) {})93	router.DELETE("/example", func(c *Context) {})94	router.PATCH("/example", func(c *Context) {})95	router.HEAD("/example", func(c *Context) {})96	router.OPTIONS("/example", func(c *Context) {})9798	PerformRequest(router, http.MethodGet, "/example?a=100")99	assert.Contains(t, buffer.String(), "200")100	assert.Contains(t, buffer.String(), http.MethodGet)101	assert.Contains(t, buffer.String(), "/example")102	assert.Contains(t, buffer.String(), "a=100")103104	// I wrote these first (extending the above) but then realized they are more105	// like integration tests because they test the whole logging process rather106	// than individual functions. I'm not sure where these should go.107	buffer.Reset()108	PerformRequest(router, http.MethodPost, "/example")109	assert.Contains(t, buffer.String(), "200")110	assert.Contains(t, buffer.String(), http.MethodPost)111	assert.Contains(t, buffer.String(), "/example")112113	buffer.Reset()114	PerformRequest(router, http.MethodPut, "/example")115	assert.Contains(t, buffer.String(), "200")116	assert.Contains(t, buffer.String(), http.MethodPut)117	assert.Contains(t, buffer.String(), "/example")118119	buffer.Reset()120	PerformRequest(router, http.MethodDelete, "/example")121	assert.Contains(t, buffer.String(), "200")122	assert.Contains(t, buffer.String(), http.MethodDelete)123	assert.Contains(t, buffer.String(), "/example")124125	buffer.Reset()126	PerformRequest(router, "PATCH", "/example")127	assert.Contains(t, buffer.String(), "200")128	assert.Contains(t, buffer.String(), "PATCH")129	assert.Contains(t, buffer.String(), "/example")130131	buffer.Reset()132	PerformRequest(router, "HEAD", "/example")133	assert.Contains(t, buffer.String(), "200")134	assert.Contains(t, buffer.String(), "HEAD")135	assert.Contains(t, buffer.String(), "/example")136137	buffer.Reset()138	PerformRequest(router, "OPTIONS", "/example")139	assert.Contains(t, buffer.String(), "200")140	assert.Contains(t, buffer.String(), "OPTIONS")141	assert.Contains(t, buffer.String(), "/example")142143	buffer.Reset()144	PerformRequest(router, http.MethodGet, "/notfound")145	assert.Contains(t, buffer.String(), "404")146	assert.Contains(t, buffer.String(), http.MethodGet)147	assert.Contains(t, buffer.String(), "/notfound")148}149150func TestLoggerWithFormatter(t *testing.T) {151	buffer := new(strings.Builder)152153	d := DefaultWriter154	DefaultWriter = buffer155	defer func() {156		DefaultWriter = d157	}()158159	router := New()160	router.Use(LoggerWithFormatter(func(param LogFormatterParams) string {161		return fmt.Sprintf("[FORMATTER TEST] %v | %3d | %13v | %15s | %-7s %#v\n%s",162			param.TimeStamp.Format("2006/01/02 - 15:04:05"),163			param.StatusCode,164			param.Latency,165			param.ClientIP,166			param.Method,167			param.Path,168			param.ErrorMessage,169		)170	}))171	router.GET("/example", func(c *Context) {})172	PerformRequest(router, http.MethodGet, "/example?a=100")173174	// output test175	assert.Contains(t, buffer.String(), "[FORMATTER TEST]")176	assert.Contains(t, buffer.String(), "200")177	assert.Contains(t, buffer.String(), http.MethodGet)178	assert.Contains(t, buffer.String(), "/example")179	assert.Contains(t, buffer.String(), "a=100")180}181182func TestLoggerWithConfigFormatting(t *testing.T) {183	var gotParam LogFormatterParams184	var gotKeys map[any]any185	buffer := new(strings.Builder)186187	router := New()188	router.engine.trustedCIDRs, _ = router.engine.prepareTrustedCIDRs()189190	router.Use(LoggerWithConfig(LoggerConfig{191		Output: buffer,192		Formatter: func(param LogFormatterParams) string {193			// for assert test194			gotParam = param195196			return fmt.Sprintf("[FORMATTER TEST] %v | %3d | %13v | %15s | %-7s %s\n%s",197				param.TimeStamp.Format("2006/01/02 - 15:04:05"),198				param.StatusCode,199				param.Latency,200				param.ClientIP,201				param.Method,202				param.Path,203				param.ErrorMessage,204			)205		},206	}))207	router.GET("/example", func(c *Context) {208		// set dummy ClientIP209		c.Request.Header.Set("X-Forwarded-For", "20.20.20.20")210		gotKeys = c.Keys211		time.Sleep(time.Millisecond)212	})213	PerformRequest(router, http.MethodGet, "/example?a=100")214215	// output test216	assert.Contains(t, buffer.String(), "[FORMATTER TEST]")217	assert.Contains(t, buffer.String(), "200")218	assert.Contains(t, buffer.String(), http.MethodGet)219	assert.Contains(t, buffer.String(), "/example")220	assert.Contains(t, buffer.String(), "a=100")221222	// LogFormatterParams test223	assert.NotNil(t, gotParam.Request)224	assert.NotEmpty(t, gotParam.TimeStamp)225	assert.Equal(t, 200, gotParam.StatusCode)226	assert.NotEmpty(t, gotParam.Latency)227	assert.Equal(t, "20.20.20.20", gotParam.ClientIP)228	assert.Equal(t, http.MethodGet, gotParam.Method)229	assert.Equal(t, "/example?a=100", gotParam.Path)230	assert.Empty(t, gotParam.ErrorMessage)231	assert.Equal(t, gotKeys, gotParam.Keys)232}233234func TestDefaultLogFormatter(t *testing.T) {235	timeStamp := time.Unix(1544173902, 0).UTC()236237	termFalseParam := LogFormatterParams{238		TimeStamp:    timeStamp,239		StatusCode:   200,240		Latency:      time.Second * 5,241		ClientIP:     "20.20.20.20",242		Method:       http.MethodGet,243		Path:         "/",244		ErrorMessage: "",245		isTerm:       false,246	}247248	termTrueParam := LogFormatterParams{249		TimeStamp:    timeStamp,250		StatusCode:   200,251		Latency:      time.Second * 5,252		ClientIP:     "20.20.20.20",253		Method:       http.MethodGet,254		Path:         "/",255		ErrorMessage: "",256		isTerm:       true,257	}258	termTrueLongDurationParam := LogFormatterParams{259		TimeStamp:    timeStamp,260		StatusCode:   200,261		Latency:      time.Millisecond * 9876543210,262		ClientIP:     "20.20.20.20",263		Method:       http.MethodGet,264		Path:         "/",265		ErrorMessage: "",266		isTerm:       true,267	}268269	termFalseLongDurationParam := LogFormatterParams{270		TimeStamp:    timeStamp,271		StatusCode:   200,272		Latency:      time.Millisecond * 9876543210,273		ClientIP:     "20.20.20.20",274		Method:       http.MethodGet,275		Path:         "/",276		ErrorMessage: "",277		isTerm:       false,278	}279280	assert.Equal(t, "[GIN] 2018/12/07 - 09:11:42 | 200 |       5s |     20.20.20.20 | GET      \"/\"\n", defaultLogFormatter(termFalseParam))281	assert.Equal(t, "[GIN] 2018/12/07 - 09:11:42 | 200 | 2743h29m0s |     20.20.20.20 | GET      \"/\"\n", defaultLogFormatter(termFalseLongDurationParam))282283	assert.Equal(t, "[GIN] 2018/12/07 - 09:11:42 |\x1b[97;42m 200 \x1b[0m|\x1b[97;41m       5s \x1b[0m|     20.20.20.20 |\x1b[97;44m GET     \x1b[0m \"/\"\n", defaultLogFormatter(termTrueParam))284	assert.Equal(t, "[GIN] 2018/12/07 - 09:11:42 |\x1b[97;42m 200 \x1b[0m|\x1b[97;41m 2743h29m0s \x1b[0m|     20.20.20.20 |\x1b[97;44m GET     \x1b[0m \"/\"\n", defaultLogFormatter(termTrueLongDurationParam))285}286287func TestColorForMethod(t *testing.T) {288	colorForMethod := func(method string) string {289		p := LogFormatterParams{290			Method: method,291		}292		return p.MethodColor()293	}294295	assert.Equal(t, blue, colorForMethod(http.MethodGet), "get should be blue")296	assert.Equal(t, cyan, colorForMethod(http.MethodPost), "post should be cyan")297	assert.Equal(t, yellow, colorForMethod(http.MethodPut), "put should be yellow")298	assert.Equal(t, red, colorForMethod(http.MethodDelete), "delete should be red")299	assert.Equal(t, green, colorForMethod("PATCH"), "patch should be green")300	assert.Equal(t, magenta, colorForMethod("HEAD"), "head should be magenta")301	assert.Equal(t, white, colorForMethod("OPTIONS"), "options should be white")302	assert.Equal(t, reset, colorForMethod("TRACE"), "trace is not defined and should be the reset color")303}304305func TestColorForStatus(t *testing.T) {306	colorForStatus := func(code int) string {307		p := LogFormatterParams{308			StatusCode: code,309		}310		return p.StatusCodeColor()311	}312313	assert.Equal(t, white, colorForStatus(http.StatusContinue), "1xx should be white")314	assert.Equal(t, green, colorForStatus(http.StatusOK), "2xx should be green")315	assert.Equal(t, white, colorForStatus(http.StatusMovedPermanently), "3xx should be white")316	assert.Equal(t, yellow, colorForStatus(http.StatusNotFound), "4xx should be yellow")317	assert.Equal(t, red, colorForStatus(2), "other things should be red")318}319320func TestColorForLatency(t *testing.T) {321	colorForLatency := func(latency time.Duration) string {322		p := LogFormatterParams{323			Latency: latency,324		}325		return p.LatencyColor()326	}327328	assert.Equal(t, white, colorForLatency(time.Duration(0)), "0 should be white")329	assert.Equal(t, white, colorForLatency(time.Millisecond*20), "20ms should be white")330	assert.Equal(t, green, colorForLatency(time.Millisecond*150), "150ms should be green")331	assert.Equal(t, cyan, colorForLatency(time.Millisecond*250), "250ms should be cyan")332	assert.Equal(t, blue, colorForLatency(time.Millisecond*400), "400ms should be blue")333	assert.Equal(t, yellow, colorForLatency(time.Millisecond*600), "600ms should be yellow")334	assert.Equal(t, magenta, colorForLatency(time.Millisecond*1500), "1.5s should be magenta")335	assert.Equal(t, red, colorForLatency(time.Second*3), "other things should be red")336}337338func TestResetColor(t *testing.T) {339	p := LogFormatterParams{}340	assert.Equal(t, string([]byte{27, 91, 48, 109}), p.ResetColor())341}342343func TestIsOutputColor(t *testing.T) {344	// test with isTerm flag true.345	p := LogFormatterParams{346		isTerm: true,347	}348349	consoleColorMode = autoColor350	assert.True(t, p.IsOutputColor())351352	ForceConsoleColor()353	assert.True(t, p.IsOutputColor())354355	DisableConsoleColor()356	assert.False(t, p.IsOutputColor())357358	// test with isTerm flag false.359	p = LogFormatterParams{360		isTerm: false,361	}362363	consoleColorMode = autoColor364	assert.False(t, p.IsOutputColor())365366	ForceConsoleColor()367	assert.True(t, p.IsOutputColor())368369	DisableConsoleColor()370	assert.False(t, p.IsOutputColor())371372	// reset console color mode.373	consoleColorMode = autoColor374}375376func TestErrorLogger(t *testing.T) {377	router := New()378	router.Use(ErrorLogger())379	router.GET("/error", func(c *Context) {380		c.Error(errors.New("this is an error")) //nolint: errcheck381	})382	router.GET("/abort", func(c *Context) {383		c.AbortWithError(http.StatusUnauthorized, errors.New("no authorized")) //nolint: errcheck384	})385	router.GET("/print", func(c *Context) {386		c.Error(errors.New("this is an error")) //nolint: errcheck387		c.String(http.StatusInternalServerError, "hola!")388	})389390	w := PerformRequest(router, http.MethodGet, "/error")391	assert.Equal(t, http.StatusOK, w.Code)392	assert.JSONEq(t, "{\"error\":\"this is an error\"}", w.Body.String())393394	w = PerformRequest(router, http.MethodGet, "/abort")395	assert.Equal(t, http.StatusUnauthorized, w.Code)396	assert.JSONEq(t, "{\"error\":\"no authorized\"}", w.Body.String())397398	w = PerformRequest(router, http.MethodGet, "/print")399	assert.Equal(t, http.StatusInternalServerError, w.Code)400	assert.Equal(t, "hola!{\"error\":\"this is an error\"}", w.Body.String())401}402403func TestLoggerWithWriterSkippingPaths(t *testing.T) {404	buffer := new(strings.Builder)405	router := New()406	router.Use(LoggerWithWriter(buffer, "/skipped"))407	router.GET("/logged", func(c *Context) {})408	router.GET("/skipped", func(c *Context) {})409410	PerformRequest(router, http.MethodGet, "/logged")411	assert.Contains(t, buffer.String(), "200")412413	buffer.Reset()414	PerformRequest(router, http.MethodGet, "/skipped")415	assert.Contains(t, buffer.String(), "")416}417418func TestLoggerWithConfigSkippingPaths(t *testing.T) {419	buffer := new(strings.Builder)420	router := New()421	router.Use(LoggerWithConfig(LoggerConfig{422		Output:    buffer,423		SkipPaths: []string{"/skipped"},424	}))425	router.GET("/logged", func(c *Context) {})426	router.GET("/skipped", func(c *Context) {})427428	PerformRequest(router, http.MethodGet, "/logged")429	assert.Contains(t, buffer.String(), "200")430431	buffer.Reset()432	PerformRequest(router, http.MethodGet, "/skipped")433	assert.Contains(t, buffer.String(), "")434}435436func TestLoggerWithConfigSkipper(t *testing.T) {437	buffer := new(strings.Builder)438	router := New()439	router.Use(LoggerWithConfig(LoggerConfig{440		Output: buffer,441		Skip: func(c *Context) bool {442			return c.Writer.Status() == http.StatusNoContent443		},444	}))445	router.GET("/logged", func(c *Context) { c.Status(http.StatusOK) })446	router.GET("/skipped", func(c *Context) { c.Status(http.StatusNoContent) })447448	PerformRequest(router, http.MethodGet, "/logged")449	assert.Contains(t, buffer.String(), "200")450451	buffer.Reset()452	PerformRequest(router, http.MethodGet, "/skipped")453	assert.Contains(t, buffer.String(), "")454}455456func TestDisableConsoleColor(t *testing.T) {457	New()458	assert.Equal(t, autoColor, consoleColorMode)459	DisableConsoleColor()460	assert.Equal(t, disableColor, consoleColorMode)461462	// reset console color mode.463	consoleColorMode = autoColor464}465466func TestForceConsoleColor(t *testing.T) {467	New()468	assert.Equal(t, autoColor, consoleColorMode)469	ForceConsoleColor()470	assert.Equal(t, forceColor, consoleColorMode)471472	// reset console color mode.473	consoleColorMode = autoColor474}475476func TestLoggerWithConfigSkipQueryString(t *testing.T) {477	buffer := new(strings.Builder)478	router := New()479	router.Use(LoggerWithConfig(LoggerConfig{480		Output:          buffer,481		SkipQueryString: true,482	}))483	router.GET("/logged", func(c *Context) { c.Status(http.StatusOK) })484485	PerformRequest(router, "GET", "/logged?a=21")486	assert.Contains(t, buffer.String(), "200")487	assert.NotContains(t, buffer.String(), "a=21")488}