Skip to content

Commit

Permalink
zapslog: Test with slogtest
Browse files Browse the repository at this point in the history
Adds a test for zapslog that verifies its behavior
with slogtest's TestHandler function.
This verifies compliance with the slog logging contract.

Resolves uber-go#1334
  • Loading branch information
abhinav committed Oct 5, 2023
1 parent 87577d8 commit d064fd7
Showing 1 changed file with 42 additions and 0 deletions.
42 changes: 42 additions & 0 deletions exp/zapslog/handler_test.go
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")
}

0 comments on commit d064fd7

Please sign in to comment.