Debian Codegraph @

slogr_test.go

raw
1 //go:build go1.21
2
3 /*
4 Copyright 2023 The logr Authors.
5
6 Licensed under the Apache License, Version 2.0 (the "License");
7 you may not use this file except in compliance with the License.
8 You may obtain a copy of the License at
9
10 http://www.apache.org/licenses/LICENSE-2.0
11
12 Unless required by applicable law or agreed to in writing, software
13 distributed under the License is distributed on an "AS IS" BASIS,
14 WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
15 See the License for the specific language governing permissions and
16 limitations under the License.
17 */
18
19 package logr
20
21 import (
22 "bytes"
23 "fmt"
24 "io"
25 "log/slog"
26 "os"
27 "path"
28 "runtime"
29 "strings"
30 "testing"
31
32 "github.com/go-logr/logr/internal/testhelp"
33 )
34
35 func TestToSlogHandler(t *testing.T) {
36 t.Run("from simple Logger", func(t *testing.T) {
37 logger := New(&testLogSink{})
38 handler := ToSlogHandler(logger)
39 if _, ok := handler.(*slogHandler); !ok {
40 t.Errorf("expected type *slogHandler, got %T", handler)
41 }
42 })
43
44 t.Run("from slog-enabled Logger", func(t *testing.T) {
45 logger := New(&testSlogSink{})
46 handler := ToSlogHandler(logger)
47 if _, ok := handler.(*slogHandler); !ok {
48 t.Errorf("expected type *slogHandler, got %T", handler)
49 }
50 })
51
52 t.Run("from slogSink Logger", func(t *testing.T) {
53 logger := New(&slogSink{handler: slog.NewJSONHandler(os.Stderr, nil)})
54 handler := ToSlogHandler(logger)
55 if _, ok := handler.(*slog.JSONHandler); !ok {
56 t.Errorf("expected type *slog.JSONHandler, got %T", handler)
57 }
58 })
59 }
60
61 func TestFromSlogHandler(t *testing.T) {
62 t.Run("from slog Handler", func(t *testing.T) {
63 handler := slog.NewJSONHandler(os.Stderr, nil)
64 logger := FromSlogHandler(handler)
65 if _, ok := logger.sink.(*slogSink); !ok {
66 t.Errorf("expected type *slogSink, got %T", logger.sink)
67 }
68 })
69
70 t.Run("from simple slogHandler Handler", func(t *testing.T) {
71 handler := &slogHandler{sink: &testLogSink{}}
72 logger := FromSlogHandler(handler)
73 if _, ok := logger.sink.(*testLogSink); !ok {
74 t.Errorf("expected type *testSlogSink, got %T", logger.sink)
75 }
76 })
77
78 t.Run("from discard slogHandler Handler", func(t *testing.T) {
79 handler := &slogHandler{}
80 logger := FromSlogHandler(handler)
81 if logger != Discard() {
82 t.Errorf("expected type *testSlogSink, got %T", logger.sink)
83 }
84 })
85 }
86
87 var debugWithoutTime = &slog.HandlerOptions{
88 ReplaceAttr: func(_ []string, a slog.Attr) slog.Attr {
89 if a.Key == "time" {
90 return slog.Attr{}
91 }
92 return a
93 },
94 Level: slog.LevelDebug,
95 }
96
97 func TestWithCallDepth(t *testing.T) {
98 debugWithCaller := *debugWithoutTime
99 debugWithCaller.AddSource = true
100 var buffer bytes.Buffer
101 logger := FromSlogHandler(slog.NewTextHandler(&buffer, &debugWithCaller))
102
103 logHelper := func(logger Logger) {
104 logger.WithCallDepth(1).Info("hello")
105 }
106
107 logHelper(logger)
108 _, file, line, _ := runtime.Caller(0)
109 expectedSource := fmt.Sprintf("%s:%d", path.Base(file), line-1)
110 actual := buffer.String()
111 if !strings.Contains(actual, expectedSource) {
112 t.Errorf("expected log entry with %s as caller source code location, got instead:\n%s", expectedSource, actual)
113 }
114 }
115
116 func TestRunSlogTestsOnNaiveSlogHandler(t *testing.T) {
117 // This proves that slogHandler passes slog's own tests when given a
118 // LogSink which does not implement SlogSink.
119 exceptions := []string{
120 // logr sinks handle time themselves
121 "a Handler should ignore a zero Record.Time",
122 // slogHandler does not do groups "properly", so these all fail with
123 // "missing group". It's looking for `"G":{"a":"b"}` and getting
124 // `"G.a": "b"`.
125 //
126 // NOTE: These make a weird coupling to Go versions. Newer Go versions
127 // don't need some of these exceptions, but older ones do. It's unclear
128 // if that is because something changed in slog or if the test was
129 // removed.
130 "a Handler should handle Group attributes",
131 "a Handler should handle the WithGroup method",
132 "a Handler should handle multiple WithGroup and WithAttr calls",
133 "a Handler should not output groups for an empty Record",
134 "a Handler should not output groups if there are no attributes",
135 "a Handler should not output nested groups if there are no attributes",
136 "a Handler should call Resolve on attribute values in groups",
137 "a Handler should call Resolve on attribute values in groups from WithAttrs",
138 }
139 testhelp.RunSlogTests(t, func(buffer *bytes.Buffer) slog.Handler {
140 // We want a known-good Logger that emits JSON but is not a slogHandler
141 // or SlogSink (since those get special treatment). We can trust that
142 // the slog JSONHandler works.
143 handler := slog.NewJSONHandler(buffer, nil)
144 sink := &passthruLogSink{handler: handler} // passthruLogSink does not implement SlogSink.
145 logger := New(sink)
146 return ToSlogHandler(logger)
147 }, exceptions...)
148 }
149
150 func TestRunSlogTestsOnEnlightenedSlogHandler(t *testing.T) {
151 // This proves that slogHandler passes slog's own tests when given a
152 // LogSink which implements SlogSink.
153 exceptions := []string{}
154 testhelp.RunSlogTests(t, func(buffer *bytes.Buffer) slog.Handler {
155 // We want a known-good Logger that emits JSON and implements SlogSink,
156 // to cover those paths. We can trust that the slog JSONHandler works.
157 handler := slog.NewJSONHandler(buffer, nil)
158 sink := &passthruSlogSink{handler: handler} // passthruSlogSink implements SlogSink.
159 logger := New(sink)
160 return ToSlogHandler(logger)
161 }, exceptions...)
162 }
163
164 func TestSlogSinkOnDiscard(_ *testing.T) {
165 // Compile-test
166 logger := slog.New(ToSlogHandler(Discard()))
167 logger.WithGroup("foo").With("x", 1).Info("hello")
168 }
169
170 func TestConversion(t *testing.T) {
171 d := Discard()
172 d2 := FromSlogHandler(ToSlogHandler(d))
173 expectEqual(t, d, d2)
174
175 e := Logger{}
176 e2 := FromSlogHandler(ToSlogHandler(e))
177 expectEqual(t, e, e2)
178
179 text := slog.NewTextHandler(io.Discard, nil)
180 text2 := ToSlogHandler(FromSlogHandler(text))
181 expectEqual(t, text, text2)
182
183 text3 := ToSlogHandler(FromSlogHandler(text).V(1))
184 if handler, ok := text3.(interface {
185 GetLevel() slog.Level
186 }); ok {
187 expectEqual(t, handler.GetLevel(), slog.Level(1))
188 } else {
189 t.Errorf("Expected a slogHandler which implements V(1), got instead: %T %+v", text3, text3)
190 }
191 }
192
193 func expectEqual(t *testing.T, expected, actual any) {
194 if expected != actual {
195 t.Helper()
196 t.Errorf("Expected %T %+v, got instead: %T %+v", expected, expected, actual, actual)
197 }
198 }