Skip to content
New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

zapslog: Test with slogtest #1335

Closed
wants to merge 1 commit into from
Closed
Changes from all commits
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
42 changes: 42 additions & 0 deletions exp/zapslog/handler_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -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"
)

Expand Down Expand Up @@ -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))
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")
}
Loading