Skip to content

Commit

Permalink
Get rid of testSlogSink
Browse files Browse the repository at this point in the history
  • Loading branch information
thockin committed Dec 4, 2023
1 parent e21e309 commit 014a8b1
Showing 1 changed file with 8 additions and 36 deletions.
44 changes: 8 additions & 36 deletions slogr_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -21,7 +21,6 @@ package logr_test

import (
"bytes"
"context"
"encoding/json"
"errors"
"fmt"
Expand Down Expand Up @@ -107,41 +106,14 @@ func TestWithCallDepth(t *testing.T) {
}

func TestJSONHandler(t *testing.T) {
testSlog(t, func(buffer *bytes.Buffer) logr.Logger {
handler := slog.NewJSONHandler(buffer, nil)
sink := testSlogSink{handler: handler}
return logr.New(sink)
// This proves that slogSink passes slog's own tests.
testSlog(t, func(buffer *bytes.Buffer) slog.Handler {
return slog.NewJSONHandler(buffer, nil)
})
}

var _ logr.LogSink = testSlogSink{}
var _ logr.SlogSink = testSlogSink{}

// testSlogSink is only used through slog and thus doesn't need to implement the
// normal LogSink methods.
type testSlogSink struct {
handler slog.Handler
}

func (s testSlogSink) Init(logr.RuntimeInfo) {}
func (s testSlogSink) Enabled(int) bool { return true }
func (s testSlogSink) Error(error, string, ...interface{}) {}
func (s testSlogSink) Info(int, string, ...interface{}) {}
func (s testSlogSink) WithName(string) logr.LogSink { return s }
func (s testSlogSink) WithValues(...interface{}) logr.LogSink { return s }

func (s testSlogSink) Handle(ctx context.Context, record slog.Record) error {
return s.handler.Handle(ctx, record)
}
func (s testSlogSink) WithAttrs(attrs []slog.Attr) logr.SlogSink {
return testSlogSink{handler: s.handler.WithAttrs(attrs)}
}
func (s testSlogSink) WithGroup(name string) logr.SlogSink {
return testSlogSink{handler: s.handler.WithGroup(name)}
}

func TestFuncrHandler(t *testing.T) {
fn := func(buffer *bytes.Buffer) logr.Logger {
fn := func(buffer *bytes.Buffer) slog.Handler {
printfn := func(obj string) {
fmt.Fprintln(buffer, obj)
}
Expand All @@ -163,18 +135,18 @@ func TestFuncrHandler(t *testing.T) {
return mappedKVList
},
}
return funcr.NewJSON(printfn, opts)
logger := funcr.NewJSON(printfn, opts)
return logr.ToSlogHandler(logger)
}
exceptions := []string{
"a Handler should ignore a zero Record.Time", // Time is generated by sink.
}
testSlog(t, fn, exceptions...)
}

func testSlog(t *testing.T, createLogger func(buffer *bytes.Buffer) logr.Logger, exceptions ...string) {
func testSlog(t *testing.T, createHandler func(buffer *bytes.Buffer) slog.Handler, exceptions ...string) {
var buffer bytes.Buffer
logger := createLogger(&buffer)
handler := logr.ToSlogHandler(logger)
handler := createHandler(&buffer)
err := slogtest.TestHandler(handler, func() []map[string]any {
var ms []map[string]any
for _, line := range bytes.Split(buffer.Bytes(), []byte{'\n'}) {
Expand Down

0 comments on commit 014a8b1

Please sign in to comment.