github.com/pingcap/tiflow@v0.0.0-20240520035814-5bf52d54e205/dm/openapi/logger_test.go (about)

     1  // Copyright 2021 PingCAP, Inc.
     2  //
     3  // Licensed under the Apache License, Version 2.0 (the "License");
     4  // you may not use this file except in compliance with the License.
     5  // You may obtain 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,
    11  // See the License for the specific language governing permissions and
    12  // limitations under the License.
    13  
    14  package openapi
    15  
    16  import (
    17  	"net/http"
    18  	"net/http/httptest"
    19  	"testing"
    20  
    21  	"github.com/gin-gonic/gin"
    22  	"github.com/pingcap/check"
    23  	"go.uber.org/zap"
    24  	"go.uber.org/zap/zaptest/observer"
    25  )
    26  
    27  var _ = check.Suite(&zapLoggerSuite{})
    28  
    29  type zapLoggerSuite struct{}
    30  
    31  func TestZapLogger(t *testing.T) {
    32  	check.TestingT(t)
    33  }
    34  
    35  func (t *zapLoggerSuite) TestZapLogger(c *check.C) {
    36  	r := gin.New()
    37  	obs, logs := observer.New(zap.DebugLevel)
    38  	logger := zap.New(obs)
    39  	r.Use(ZapLogger(logger))
    40  	r.GET("/something", func(c *gin.Context) {
    41  		c.String(http.StatusOK, "")
    42  	})
    43  
    44  	res := httptest.NewRecorder()
    45  	req := httptest.NewRequest(http.MethodGet, "/something", nil)
    46  	r.ServeHTTP(res, req)
    47  
    48  	logFields := logs.All()[0].ContextMap()
    49  	c.Assert(logFields["method"], check.Equals, "GET")
    50  	c.Assert(logFields["request"], check.Equals, "GET /something")
    51  	c.Assert(logFields["status"], check.Equals, int64(200))
    52  	c.Assert(logFields["duration"], check.NotNil)
    53  	c.Assert(logFields["host"], check.NotNil)
    54  	c.Assert(logFields["protocol"], check.NotNil)
    55  	c.Assert(logFields["remote_ip"], check.NotNil)
    56  	c.Assert(logFields["user_agent"], check.NotNil)
    57  	c.Assert(logFields["request"], check.NotNil)
    58  	c.Assert(logFields["error"], check.IsNil)
    59  }