github.com/imannamdari/v2ray-core/v5@v5.0.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  
     9  	"github.com/imannamdari/v2ray-core/v5/app/log"
    10  	"github.com/imannamdari/v2ray-core/v5/common"
    11  	clog "github.com/imannamdari/v2ray-core/v5/common/log"
    12  	"github.com/imannamdari/v2ray-core/v5/testing/mocks"
    13  )
    14  
    15  func TestCustomLogHandler(t *testing.T) {
    16  	mockCtl := gomock.NewController(t)
    17  	defer mockCtl.Finish()
    18  
    19  	var loggedValue []string
    20  
    21  	mockHandler := mocks.NewLogHandler(mockCtl)
    22  	mockHandler.EXPECT().Handle(gomock.Any()).AnyTimes().DoAndReturn(func(msg clog.Message) {
    23  		loggedValue = append(loggedValue, msg.String())
    24  	})
    25  
    26  	log.RegisterHandlerCreator(log.LogType_Console, func(lt log.LogType, options log.HandlerCreatorOptions) (clog.Handler, error) {
    27  		return mockHandler, nil
    28  	})
    29  
    30  	logger, err := log.New(context.Background(), &log.Config{
    31  		Error:  &log.LogSpecification{Type: log.LogType_Console, Level: clog.Severity_Debug},
    32  		Access: &log.LogSpecification{Type: 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  }