From 93b166a48eee0cb37afb4bcd1ebdf9a0a5ec8339 Mon Sep 17 00:00:00 2001 From: Abhinav Gupta Date: Tue, 22 Aug 2023 06:07:53 -0700 Subject: [PATCH] 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 --- exp/go.mod | 1 + exp/go.sum | 1 + exp/zapslog/slog_go121_test.go | 42 ++++++++++++++++++++++++++++++++++ 3 files changed, 44 insertions(+) diff --git a/exp/go.mod b/exp/go.mod index 18e437164..aed0d3459 100644 --- a/exp/go.mod +++ b/exp/go.mod @@ -9,6 +9,7 @@ require ( ) require ( + github.com/benbjohnson/clock v1.1.0 // indirect github.com/davecgh/go-spew v1.1.1 // indirect github.com/pmezard/go-difflib v1.0.0 // indirect go.uber.org/atomic v1.10.0 // indirect diff --git a/exp/go.sum b/exp/go.sum index 2add8d8ea..d258f0331 100644 --- a/exp/go.sum +++ b/exp/go.sum @@ -1,4 +1,5 @@ github.com/benbjohnson/clock v1.1.0 h1:Q92kusRqC1XV2MjkWETPvjJVqKetz1OzxZB7mHJLju8= +github.com/benbjohnson/clock v1.1.0/go.mod h1:J11/hYXuz8f4ySSvYwY0FKfm+ezbsZBKZxNJlLklBHA= github.com/davecgh/go-spew v1.1.0/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= github.com/davecgh/go-spew v1.1.1 h1:vj9j/u1bqnvCEfJOwUhtlOARqs3+rkHYY13jYWTU97c= github.com/davecgh/go-spew v1.1.1/go.mod h1:J7Y8YcW2NihsgmVo/mv3lAwl/skON4iLHjSsI+c5H38= diff --git a/exp/zapslog/slog_go121_test.go b/exp/zapslog/slog_go121_test.go index 9fb82ace4..43029cf80 100644 --- a/exp/zapslog/slog_go121_test.go +++ b/exp/zapslog/slog_go121_test.go @@ -23,11 +23,15 @@ package zapslog import ( + "bytes" + "encoding/json" "log/slog" "testing" + "testing/slogtest" "github.com/stretchr/testify/require" "go.uber.org/zap/zapcore" + "go.uber.org/zap/zaptest" "go.uber.org/zap/zaptest/observer" ) @@ -48,3 +52,41 @@ func TestAddSource(t *testing.T) { "Unexpected caller annotation.", ) } + +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") +}