|
23 | 23 | package zapslog |
24 | 24 |
|
25 | 25 | import ( |
| 26 | + "bytes" |
| 27 | + "encoding/json" |
26 | 28 | "log/slog" |
27 | 29 | "testing" |
| 30 | + "testing/slogtest" |
28 | 31 | "time" |
29 | 32 |
|
30 | 33 | "github.com/stretchr/testify/assert" |
31 | 34 | "github.com/stretchr/testify/require" |
32 | 35 | "go.uber.org/zap/zapcore" |
| 36 | + "go.uber.org/zap/zaptest" |
33 | 37 | "go.uber.org/zap/zaptest/observer" |
34 | 38 | ) |
35 | 39 |
|
@@ -189,3 +193,41 @@ func TestAttrKinds(t *testing.T) { |
189 | 193 | }, |
190 | 194 | entry.ContextMap()) |
191 | 195 | } |
| 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