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