diff --git a/exp/zapslog/handler_test.go b/exp/zapslog/handler_test.go index 68339df62..7e9ee7ae8 100644 --- a/exp/zapslog/handler_test.go +++ b/exp/zapslog/handler_test.go @@ -23,13 +23,17 @@ package zapslog import ( + "bytes" + "encoding/json" "log/slog" "testing" + "testing/slogtest" "time" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" "go.uber.org/zap/zapcore" + "go.uber.org/zap/zaptest" "go.uber.org/zap/zaptest/observer" ) @@ -189,3 +193,41 @@ func TestAttrKinds(t *testing.T) { }, entry.ContextMap()) } + +func TestSlogtest(t *testing.T) { + var buff bytes.Buffer + core := zapcore.NewCore( + zapcore.NewJSONEncoder(zapcore.EncoderConfig{ + TimeKey: slog.TimeKey, + MessageKey: slog.MessageKey, + LevelKey: slog.LevelKey, + EncodeLevel: zapcore.CapitalLevelEncoder, + EncodeTime: zapcore.RFC3339TimeEncoder, + }), + zapcore.AddSync(&buff), + zapcore.DebugLevel, + ) + + // zaptest doesn't expose the underlying core, + // so we'll extract it from the logger. + testCore := zaptest.NewLogger(t).Core() + + handler := NewHandler(zapcore.NewTee(core, testCore), nil /* options */) + err := slogtest.TestHandler( + handler, + func() []map[string]any { + // Parse the newline-delimted JSON in buff. + var entries []map[string]any + + dec := json.NewDecoder(bytes.NewReader(buff.Bytes())) + for dec.More() { + var ent map[string]any + require.NoError(t, dec.Decode(&ent), "Error decoding log message") + entries = append(entries, ent) + } + + return entries + }, + ) + require.NoError(t, err, "Unexpected error from slogtest.TestHandler") +}