From 29d3c8d7897dde32e9714aa23c7008bfaa160136 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/handler_test.go | 42 +++++++++++++++++++++++++++++++++++++ 3 files changed, 44 insertions(+) diff --git a/exp/go.mod b/exp/go.mod index 162b00e27..c0e93b771 100644 --- a/exp/go.mod +++ b/exp/go.mod @@ -8,6 +8,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 f333d47c4..811fb1dbc 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/handler_test.go b/exp/zapslog/handler_test.go index c5c75d991..be269f081 100644 --- a/exp/zapslog/handler_test.go +++ b/exp/zapslog/handler_test.go @@ -23,12 +23,16 @@ package zapslog import ( + "bytes" + "encoding/json" "log/slog" "testing" + "testing/slogtest" "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" ) @@ -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") +}