github.com/moqsien/xraycore@v1.8.5/app/log/log_test.go (about)

     1  package log_test
     2  
     3  import (
     4  	"context"
     5  	"testing"
     6  
     7  	"github.com/golang/mock/gomock"
     8  	"github.com/moqsien/xraycore/app/log"
     9  	"github.com/moqsien/xraycore/common"
    10  	clog "github.com/moqsien/xraycore/common/log"
    11  	"github.com/moqsien/xraycore/testing/mocks"
    12  )
    13  
    14  func TestCustomLogHandler(t *testing.T) {
    15  	mockCtl := gomock.NewController(t)
    16  	defer mockCtl.Finish()
    17  
    18  	var loggedValue []string
    19  
    20  	mockHandler := mocks.NewLogHandler(mockCtl)
    21  	mockHandler.EXPECT().Handle(gomock.Any()).AnyTimes().DoAndReturn(func(msg clog.Message) {
    22  		loggedValue = append(loggedValue, msg.String())
    23  	})
    24  
    25  	log.RegisterHandlerCreator(log.LogType_Console, func(lt log.LogType, options log.HandlerCreatorOptions) (clog.Handler, error) {
    26  		return mockHandler, nil
    27  	})
    28  
    29  	logger, err := log.New(context.Background(), &log.Config{
    30  		ErrorLogLevel: clog.Severity_Debug,
    31  		ErrorLogType:  log.LogType_Console,
    32  		AccessLogType: log.LogType_None,
    33  	})
    34  	common.Must(err)
    35  
    36  	common.Must(logger.Start())
    37  
    38  	clog.Record(&clog.GeneralMessage{
    39  		Severity: clog.Severity_Debug,
    40  		Content:  "test",
    41  	})
    42  
    43  	if len(loggedValue) < 2 {
    44  		t.Fatal("expected 2 log messages, but actually ", loggedValue)
    45  	}
    46  
    47  	if loggedValue[1] != "[Debug] test" {
    48  		t.Fatal("expected '[Debug] test', but actually ", loggedValue[1])
    49  	}
    50  
    51  	common.Must(logger.Close())
    52  }