Skip to content

Commit f558531

Browse files
committed
Put slog tests in a helper, move funcr test
1 parent 83dbe72 commit f558531

File tree

4 files changed

+161
-87
lines changed

4 files changed

+161
-87
lines changed

funcr/slogsink_test.go

Lines changed: 43 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -20,13 +20,15 @@ limitations under the License.
2020
package funcr
2121

2222
import (
23+
"bytes"
2324
"fmt"
2425
"log/slog"
2526
"path/filepath"
2627
"runtime"
2728
"testing"
2829

2930
"github.com/go-logr/logr"
31+
"github.com/go-logr/logr/internal/testhelp"
3032
)
3133

3234
func TestSlogSink(t *testing.T) {
@@ -108,3 +110,44 @@ func TestSlogSinkWithCaller(t *testing.T) {
108110
t.Errorf("\nexpected %q\n got %q", expect, capt.log)
109111
}
110112
}
113+
114+
func TestRunSlogTests(t *testing.T) {
115+
fn := func(buffer *bytes.Buffer) slog.Handler {
116+
printfn := func(obj string) {
117+
fmt.Fprintln(buffer, obj)
118+
}
119+
opts := Options{
120+
LogTimestamp: true,
121+
Verbosity: 10,
122+
RenderBuiltinsHook: func(kvList []any) []any {
123+
mappedKVList := make([]any, len(kvList))
124+
for i := 0; i < len(kvList); i += 2 {
125+
key := kvList[i]
126+
switch key {
127+
case "ts":
128+
mappedKVList[i] = "time"
129+
default:
130+
mappedKVList[i] = key
131+
}
132+
mappedKVList[i+1] = kvList[i+1]
133+
}
134+
return mappedKVList
135+
},
136+
}
137+
logger := NewJSON(printfn, opts)
138+
return logr.ToSlogHandler(logger)
139+
}
140+
exceptions := []string{
141+
"a Handler should ignore a zero Record.Time", // Time is generated by sink.
142+
}
143+
testhelp.RunSlogTests(t, fn, exceptions...)
144+
}
145+
146+
func TestLogrSlogConversion(t *testing.T) {
147+
f := New(func(prefix, args string) {}, Options{})
148+
f2 := logr.FromSlogHandler(logr.ToSlogHandler(f))
149+
if want, got := f, f2; got != want {
150+
t.Helper()
151+
t.Errorf("Expected %T %+v, got instead: %T %+v", want, want, got, got)
152+
}
153+
}

internal/testhelp/slog.go

Lines changed: 79 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,79 @@
1+
//go:build go1.21
2+
// +build go1.21
3+
4+
/*
5+
Copyright 2023 The logr Authors.
6+
7+
Licensed under the Apache License, Version 2.0 (the "License");
8+
you may not use this file except in compliance with the License.
9+
You may obtain a copy of the License at
10+
11+
http://www.apache.org/licenses/LICENSE-2.0
12+
13+
Unless required by applicable law or agreed to in writing, software
14+
distributed under the License is distributed on an "AS IS" BASIS,
15+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16+
See the License for the specific language governing permissions and
17+
limitations under the License.
18+
*/
19+
20+
// Package testhelp holds helper functions for the testing of logr and built-in
21+
// implementations.
22+
package testhelp
23+
24+
import (
25+
"bytes"
26+
"encoding/json"
27+
"log/slog"
28+
"strings"
29+
"testing"
30+
"testing/slogtest"
31+
)
32+
33+
// RunSlogTests runs slogtest.TestHandler on a given slog.Handler, which is
34+
// expected to emit JSON into the provided buffer.
35+
func RunSlogTests(t *testing.T, createHandler func(buffer *bytes.Buffer) slog.Handler, exceptions ...string) {
36+
var buffer bytes.Buffer
37+
handler := createHandler(&buffer)
38+
err := slogtest.TestHandler(handler, func() []map[string]any {
39+
var ms []map[string]any
40+
for _, line := range bytes.Split(buffer.Bytes(), []byte{'\n'}) {
41+
if len(line) == 0 {
42+
continue
43+
}
44+
var m map[string]any
45+
if err := json.Unmarshal(line, &m); err != nil {
46+
t.Errorf("%v: %q", err, string(line))
47+
}
48+
ms = append(ms, m)
49+
}
50+
return ms
51+
})
52+
53+
// Correlating failures with individual test cases is hard with the current API.
54+
// See https://github.com/golang/go/issues/61758
55+
t.Logf("Output:\n%s", buffer.String())
56+
if err != nil {
57+
if unwrappable, ok := err.(interface {
58+
Unwrap() []error
59+
}); ok {
60+
for _, err := range unwrappable.Unwrap() {
61+
if !containsOne(err.Error(), exceptions...) {
62+
t.Errorf("Unexpected error: %v", err)
63+
}
64+
}
65+
} else {
66+
// Shouldn't be reached, errors from errors.Join can be split up.
67+
t.Errorf("Unexpected errors:\n%v", err)
68+
}
69+
}
70+
}
71+
72+
func containsOne(hay string, needles ...string) bool {
73+
for _, needle := range needles {
74+
if strings.Contains(hay, needle) {
75+
return true
76+
}
77+
}
78+
return false
79+
}

internal/testhelp/slog_test.go

Lines changed: 33 additions & 0 deletions
Original file line numberDiff line numberDiff line change
@@ -0,0 +1,33 @@
1+
//go:build go1.21
2+
// +build go1.21
3+
4+
/*
5+
Copyright 2023 The logr Authors.
6+
7+
Licensed under the Apache License, Version 2.0 (the "License");
8+
you may not use this file except in compliance with the License.
9+
You may obtain a copy of the License at
10+
11+
http://www.apache.org/licenses/LICENSE-2.0
12+
13+
Unless required by applicable law or agreed to in writing, software
14+
distributed under the License is distributed on an "AS IS" BASIS,
15+
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
16+
See the License for the specific language governing permissions and
17+
limitations under the License.
18+
*/
19+
20+
package testhelp
21+
22+
import (
23+
"bytes"
24+
"log/slog"
25+
"testing"
26+
)
27+
28+
func TestRunSlogTestsOnSlogSink(t *testing.T) {
29+
// This proves that RunSlogTests works.
30+
RunSlogTests(t, func(buffer *bytes.Buffer) slog.Handler {
31+
return slog.NewJSONHandler(buffer, nil)
32+
})
33+
}

slogr_test.go

Lines changed: 6 additions & 87 deletions
Original file line numberDiff line numberDiff line change
@@ -21,7 +21,6 @@ package logr_test
2121

2222
import (
2323
"bytes"
24-
"encoding/json"
2524
"errors"
2625
"fmt"
2726
"io"
@@ -31,10 +30,10 @@ import (
3130
"runtime"
3231
"strings"
3332
"testing"
34-
"testing/slogtest"
3533

3634
"github.com/go-logr/logr"
3735
"github.com/go-logr/logr/funcr"
36+
"github.com/go-logr/logr/internal/testhelp"
3837
)
3938

4039
var debugWithoutTime = &slog.HandlerOptions{
@@ -105,92 +104,16 @@ func TestWithCallDepth(t *testing.T) {
105104
}
106105
}
107106

108-
func TestJSONHandler(t *testing.T) {
107+
func TestRunSlogTestsOnSlogSink(t *testing.T) {
109108
// This proves that slogSink passes slog's own tests.
110-
testSlog(t, func(buffer *bytes.Buffer) slog.Handler {
111-
return slog.NewJSONHandler(buffer, nil)
112-
})
113-
}
114-
115-
func TestFuncrHandler(t *testing.T) {
116-
fn := func(buffer *bytes.Buffer) slog.Handler {
117-
printfn := func(obj string) {
118-
fmt.Fprintln(buffer, obj)
119-
}
120-
opts := funcr.Options{
121-
LogTimestamp: true,
122-
Verbosity: 10,
123-
RenderBuiltinsHook: func(kvList []any) []any {
124-
mappedKVList := make([]any, len(kvList))
125-
for i := 0; i < len(kvList); i += 2 {
126-
key := kvList[i]
127-
switch key {
128-
case "ts":
129-
mappedKVList[i] = "time"
130-
default:
131-
mappedKVList[i] = key
132-
}
133-
mappedKVList[i+1] = kvList[i+1]
134-
}
135-
return mappedKVList
136-
},
137-
}
138-
logger := funcr.NewJSON(printfn, opts)
109+
testhelp.RunSlogTests(t, func(buffer *bytes.Buffer) slog.Handler {
110+
handler := slog.NewJSONHandler(buffer, nil)
111+
logger := logr.FromSlogHandler(handler)
139112
return logr.ToSlogHandler(logger)
140-
}
141-
exceptions := []string{
142-
"a Handler should ignore a zero Record.Time", // Time is generated by sink.
143-
}
144-
testSlog(t, fn, exceptions...)
145-
}
146-
147-
func testSlog(t *testing.T, createHandler func(buffer *bytes.Buffer) slog.Handler, exceptions ...string) {
148-
var buffer bytes.Buffer
149-
handler := createHandler(&buffer)
150-
err := slogtest.TestHandler(handler, func() []map[string]any {
151-
var ms []map[string]any
152-
for _, line := range bytes.Split(buffer.Bytes(), []byte{'\n'}) {
153-
if len(line) == 0 {
154-
continue
155-
}
156-
var m map[string]any
157-
if err := json.Unmarshal(line, &m); err != nil {
158-
t.Errorf("%v: %q", err, string(line))
159-
}
160-
ms = append(ms, m)
161-
}
162-
return ms
163113
})
164-
165-
// Correlating failures with individual test cases is hard with the current API.
166-
// See https://github.com/golang/go/issues/61758
167-
t.Logf("Output:\n%s", buffer.String())
168-
if err != nil {
169-
if unwrappable, ok := err.(interface {
170-
Unwrap() []error
171-
}); ok {
172-
for _, err := range unwrappable.Unwrap() {
173-
if !containsOne(err.Error(), exceptions...) {
174-
t.Errorf("Unexpected error: %v", err)
175-
}
176-
}
177-
} else {
178-
// Shouldn't be reached, errors from errors.Join can be split up.
179-
t.Errorf("Unexpected errors:\n%v", err)
180-
}
181-
}
182114
}
183115

184-
func containsOne(hay string, needles ...string) bool {
185-
for _, needle := range needles {
186-
if strings.Contains(hay, needle) {
187-
return true
188-
}
189-
}
190-
return false
191-
}
192-
193-
func TestDiscard(_ *testing.T) {
116+
func TestSlogSinkOnDiscard(_ *testing.T) {
194117
// Compile-test
195118
logger := slog.New(logr.ToSlogHandler(logr.Discard()))
196119
logger.WithGroup("foo").With("x", 1).Info("hello")
@@ -205,10 +128,6 @@ func TestConversion(t *testing.T) {
205128
e2 := logr.FromSlogHandler(logr.ToSlogHandler(e))
206129
expectEqual(t, e, e2)
207130

208-
f := funcr.New(func(prefix, args string) {}, funcr.Options{})
209-
f2 := logr.FromSlogHandler(logr.ToSlogHandler(f))
210-
expectEqual(t, f, f2)
211-
212131
text := slog.NewTextHandler(io.Discard, nil)
213132
text2 := logr.ToSlogHandler(logr.FromSlogHandler(text))
214133
expectEqual(t, text, text2)

0 commit comments

Comments
 (0)