...

Source file src/github.com/grpc-ecosystem/go-grpc-middleware/logging/zap/ctxzap/context_test.go

Documentation: github.com/grpc-ecosystem/go-grpc-middleware/logging/zap/ctxzap

     1  package ctxzap
     2  
     3  import (
     4  	"context"
     5  	"runtime"
     6  	"testing"
     7  
     8  	"go.uber.org/zap"
     9  	"go.uber.org/zap/zapcore"
    10  	"go.uber.org/zap/zaptest"
    11  )
    12  
    13  func TestShorthands(t *testing.T) {
    14  	cases := []struct {
    15  		fn    func(ctx context.Context, msg string, fields ...zapcore.Field)
    16  		level zapcore.Level
    17  	}{
    18  		{Debug, zap.DebugLevel},
    19  		{Info, zap.InfoLevel},
    20  		{Warn, zap.WarnLevel},
    21  		{Error, zap.ErrorLevel},
    22  	}
    23  	const message = "omg!"
    24  	for _, c := range cases {
    25  		t.Run(c.level.String(), func(t *testing.T) {
    26  			called := false
    27  			logger := zaptest.NewLogger(t, zaptest.WrapOptions(zap.Hooks(func(e zapcore.Entry) error {
    28  				called = true
    29  				if e.Level != c.level {
    30  					t.Fatalf("Expected %v, got %v", c.level, e.Level)
    31  				}
    32  				if e.Message != message {
    33  					t.Fatalf("message: expected %v, got %v", message, e.Message)
    34  				}
    35  				if _, file, _, _ := runtime.Caller(0); e.Caller.File != file {
    36  					t.Errorf("caller: expected %v, got %v", file, e.Caller.File)
    37  				}
    38  				return nil
    39  			}))).WithOptions(zap.AddCaller())
    40  			ctx := ToContext(context.Background(), logger)
    41  			c.fn(ctx, message)
    42  			if !called {
    43  				t.Fatal("hook not called")
    44  			}
    45  		})
    46  	}
    47  }
    48  
    49  func TestShorthandsNoop(t *testing.T) {
    50  	// Just check we don't panic if there is no logger in the context.
    51  	Debug(context.Background(), "no-op")
    52  	Info(context.Background(), "no-op")
    53  	Warn(context.Background(), "no-op")
    54  	Error(context.Background(), "no-op")
    55  }
    56  

View as plain text