Skip to content

Commit d064fd7

Browse files
committed
zapslog: Test with slogtest
Adds a test for zapslog that verifies its behavior with slogtest's TestHandler function. This verifies compliance with the slog logging contract. Resolves #1334
1 parent 87577d8 commit d064fd7

File tree

1 file changed

+42
-0
lines changed

1 file changed

+42
-0
lines changed

exp/zapslog/handler_test.go

Lines changed: 42 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -23,13 +23,17 @@
2323
package zapslog
2424

2525
import (
26+
"bytes"
27+
"encoding/json"
2628
"log/slog"
2729
"testing"
30+
"testing/slogtest"
2831
"time"
2932

3033
"github.com/stretchr/testify/assert"
3134
"github.com/stretchr/testify/require"
3235
"go.uber.org/zap/zapcore"
36+
"go.uber.org/zap/zaptest"
3337
"go.uber.org/zap/zaptest/observer"
3438
)
3539

@@ -189,3 +193,41 @@ func TestAttrKinds(t *testing.T) {
189193
},
190194
entry.ContextMap())
191195
}
196+
197+
func TestSlogtest(t *testing.T) {
198+
var buff bytes.Buffer
199+
core := zapcore.NewCore(
200+
zapcore.NewJSONEncoder(zapcore.EncoderConfig{
201+
TimeKey: slog.TimeKey,
202+
MessageKey: slog.MessageKey,
203+
LevelKey: slog.LevelKey,
204+
EncodeLevel: zapcore.CapitalLevelEncoder,
205+
EncodeTime: zapcore.RFC3339TimeEncoder,
206+
}),
207+
zapcore.AddSync(&buff),
208+
zapcore.DebugLevel,
209+
)
210+
211+
// zaptest doesn't expose the underlying core,
212+
// so we'll extract it from the logger.
213+
testCore := zaptest.NewLogger(t).Core()
214+
215+
handler := NewHandler(zapcore.NewTee(core, testCore))
216+
err := slogtest.TestHandler(
217+
handler,
218+
func() []map[string]any {
219+
// Parse the newline-delimted JSON in buff.
220+
var entries []map[string]any
221+
222+
dec := json.NewDecoder(bytes.NewReader(buff.Bytes()))
223+
for dec.More() {
224+
var ent map[string]any
225+
require.NoError(t, dec.Decode(&ent), "Error decoding log message")
226+
entries = append(entries, ent)
227+
}
228+
229+
return entries
230+
},
231+
)
232+
require.NoError(t, err, "Unexpected error from slogtest.TestHandler")
233+
}

0 commit comments

Comments
 (0)