github.com/nyan233/littlerpc@v0.4.6-0.20230316182519-0c8d5c48abaf/plugins/logger/logger_test.go (about)

     1  package logger
     2  
     3  import (
     4  	"context"
     5  	lContext "github.com/nyan233/littlerpc/core/common/context"
     6  	"github.com/nyan233/littlerpc/core/common/errorhandler"
     7  	"github.com/nyan233/littlerpc/core/common/logger"
     8  	"github.com/nyan233/littlerpc/core/middle/plugin"
     9  	"github.com/nyan233/littlerpc/core/protocol/message"
    10  	"github.com/nyan233/littlerpc/core/protocol/message/gen"
    11  	"github.com/stretchr/testify/assert"
    12  	"net"
    13  	"os"
    14  	"testing"
    15  	"time"
    16  )
    17  
    18  func TestPluginLogger(t *testing.T) {
    19  	l := New(os.Stdout)
    20  	pCtx := lContext.WithInitData(context.Background(), &lContext.InitData{
    21  		Start:       time.Now(),
    22  		ServiceName: "test/api/v1.Hello",
    23  		MsgType:     message.Call,
    24  	})
    25  	ctx := &plugin.Context{
    26  		PluginContext: pCtx,
    27  		Logger:        logger.DefaultLogger,
    28  		EHandler:      nil,
    29  	}
    30  	msg := gen.NoMux(gen.Big)
    31  	testLogger(t, msg, ctx, l, message.Call)
    32  	testLogger(t, msg, ctx, l, message.ContextCancel)
    33  	testLogger(t, msg, ctx, l, message.Ping)
    34  }
    35  
    36  func testLogger(t *testing.T, msg *message.Message, ctx *plugin.Context, l plugin.ServerPlugin, msgType uint8) {
    37  	data := lContext.CheckInitData(ctx.PluginContext)
    38  	data.MsgType = msgType
    39  	assert.Nil(t, l.Receive4S(ctx, msg))
    40  	msg.SetServiceName("")
    41  	time.Sleep(time.Nanosecond * 100)
    42  	addr, _ := net.ResolveTCPAddr("tcp", "localhost:52372")
    43  	ctx.PluginContext = lContext.WithRemoteAddr(ctx.PluginContext, addr)
    44  	assert.Nil(t, l.AfterSend4S(ctx, msg, nil))
    45  	newAddr, _ := net.ResolveTCPAddr("tcp", "localhost:325")
    46  	ctx.PluginContext = lContext.WithRemoteAddr(ctx.PluginContext, newAddr)
    47  	time.Sleep(time.Nanosecond * 120)
    48  	assert.Nil(t, l.AfterSend4S(ctx, msg, errorhandler.ContextNotFound))
    49  }