github.com/zooyer/miskit@v1.0.71/micro/middleware_test.go (about)

     1  package micro
     2  
     3  import (
     4  	"io/ioutil"
     5  	"net/http"
     6  	"testing"
     7  
     8  	"github.com/gin-gonic/gin"
     9  	"github.com/stretchr/testify/assert"
    10  	"github.com/zooyer/miskit/log"
    11  	"github.com/zooyer/miskit/trace"
    12  )
    13  
    14  func TestTrace(t *testing.T) {
    15  	engine := gin.New()
    16  	engine.Use(Trace("test"))
    17  	engine.GET("/trace", func(ctx *gin.Context) {
    18  		trace := trace.Get(ctx)
    19  		ctx.JSON(http.StatusOK, trace)
    20  	})
    21  
    22  	resp := get(engine, "/trace")
    23  	data, _ := ioutil.ReadAll(resp.Body)
    24  	assert.Equal(t, http.StatusOK, resp.Code)
    25  	assert.NotEqual(t, "", string(data))
    26  	t.Log(string(data))
    27  }
    28  
    29  func TestLogger(t *testing.T) {
    30  	var (
    31  		config = log.Config{
    32  			Level: "DEBUG",
    33  		}
    34  		stdout    = log.NewStdoutRecorder(log.TextFormatter(true))
    35  		logger, _ = log.New(config, nil)
    36  	)
    37  	logger.SetDefaultRecorder(stdout)
    38  
    39  	engine := gin.New()
    40  	engine.Use(Logger(logger))
    41  	engine.GET("/logger", func(ctx *gin.Context) {
    42  		ctx.JSON(http.StatusOK, ctx.Query("action"))
    43  	})
    44  
    45  	resp := get(engine, "/logger?action=test")
    46  	data, _ := ioutil.ReadAll(resp.Body)
    47  	assert.Equal(t, http.StatusOK, resp.Code)
    48  	assert.Equal(t, `"test"`, string(data))
    49  }
    50  
    51  func TestRecover(t *testing.T) {
    52  	var (
    53  		config = log.Config{
    54  			Level: "DEBUG",
    55  		}
    56  		stdout    = log.NewStdoutRecorder(log.TextFormatter(true))
    57  		logger, _ = log.New(config, nil)
    58  	)
    59  	logger.SetDefaultRecorder(stdout)
    60  
    61  	engine := gin.New()
    62  	engine.Use(Recover(logger))
    63  	engine.GET("/recover", func(ctx *gin.Context) {
    64  		panic("test")
    65  	})
    66  
    67  	resp := get(engine, "/recover")
    68  	data, _ := ioutil.ReadAll(resp.Body)
    69  	assert.Equal(t, http.StatusInternalServerError, resp.Code)
    70  	assert.Equal(t, `"test"`, string(data))
    71  	t.Log(string(data))
    72  }