Skip to content

Commit

Permalink
zapslog: add test coverage - WithGroup in WithGroup
Browse files Browse the repository at this point in the history
Signed-off-by: junya koyama <arukiidou@yahoo.co.jp>
  • Loading branch information
arukiidou committed Feb 4, 2024
1 parent 104e04f commit baa935c
Show file tree
Hide file tree
Showing 2 changed files with 18 additions and 1 deletion.
2 changes: 1 addition & 1 deletion exp/zapslog/handler.go
Original file line number Diff line number Diff line change
Expand Up @@ -197,7 +197,7 @@ func (h *Handler) WithAttrs(attrs []slog.Attr) slog.Handler {
func (h *Handler) WithGroup(group string) slog.Handler {
cloned := *h
if h.holdGroup != "" {
cloned.core = h.core.With([]zapcore.Field{zap.Namespace(group)})
cloned.core = h.core.With([]zapcore.Field{zap.Namespace(h.holdGroup)})
}
cloned.holdGroup = group
return &cloned
Expand Down
17 changes: 17 additions & 0 deletions exp/zapslog/handler_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -190,6 +190,23 @@ func TestInlineGroup(t *testing.T) {
func TestWithGroup(t *testing.T) {
t.Parallel()
fac, observedLogs := observer.New(zapcore.DebugLevel)
t.Run("group-in-group", func(t *testing.T) {
sl := slog.New(NewHandler(fac))
sl.With("a", "b").WithGroup("G").WithGroup("in").Info("msg", "c", "d")

logs := observedLogs.TakeAll()
require.Len(t, logs, 1, "Expected exactly one entry to be logged")
entry := logs[0]
assert.Equal(t, "", entry.LoggerName, "Unexpected logger name")
assert.Equal(t, map[string]any{
"G": map[string]any{
"in": map[string]any{
"c": "d",
},
},
"a": "b",
}, logs[0].ContextMap(), "Unexpected context")
})
t.Run("empty-group-record", func(t *testing.T) {
sl := slog.New(NewHandler(fac))
sl.With("a", "b").WithGroup("G").With("c", "d").WithGroup("H").Info("msg")
Expand Down

0 comments on commit baa935c

Please sign in to comment.