Skip to content

Commit

Permalink
Put slog tests in a helper, move funcr test
Browse files Browse the repository at this point in the history
  • Loading branch information
thockin committed Dec 8, 2023
1 parent 83dbe72 commit f558531
Show file tree
Hide file tree
Showing 4 changed files with 161 additions and 87 deletions.
43 changes: 43 additions & 0 deletions funcr/slogsink_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -20,13 +20,15 @@ limitations under the License.
package funcr

import (
"bytes"
"fmt"
"log/slog"
"path/filepath"
"runtime"
"testing"

"github.com/go-logr/logr"
"github.com/go-logr/logr/internal/testhelp"
)

func TestSlogSink(t *testing.T) {
Expand Down Expand Up @@ -108,3 +110,44 @@ func TestSlogSinkWithCaller(t *testing.T) {
t.Errorf("\nexpected %q\n got %q", expect, capt.log)
}
}

func TestRunSlogTests(t *testing.T) {
fn := func(buffer *bytes.Buffer) slog.Handler {
printfn := func(obj string) {
fmt.Fprintln(buffer, obj)
}
opts := Options{
LogTimestamp: true,
Verbosity: 10,
RenderBuiltinsHook: func(kvList []any) []any {
mappedKVList := make([]any, len(kvList))
for i := 0; i < len(kvList); i += 2 {
key := kvList[i]
switch key {
case "ts":
mappedKVList[i] = "time"
default:
mappedKVList[i] = key
}
mappedKVList[i+1] = kvList[i+1]
}
return mappedKVList
},
}
logger := NewJSON(printfn, opts)
return logr.ToSlogHandler(logger)
}
exceptions := []string{
"a Handler should ignore a zero Record.Time", // Time is generated by sink.
}
testhelp.RunSlogTests(t, fn, exceptions...)
}

func TestLogrSlogConversion(t *testing.T) {
f := New(func(prefix, args string) {}, Options{})
f2 := logr.FromSlogHandler(logr.ToSlogHandler(f))
if want, got := f, f2; got != want {
t.Helper()
t.Errorf("Expected %T %+v, got instead: %T %+v", want, want, got, got)
}
}
79 changes: 79 additions & 0 deletions internal/testhelp/slog.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,79 @@
//go:build go1.21
// +build go1.21

/*
Copyright 2023 The logr Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

// Package testhelp holds helper functions for the testing of logr and built-in
// implementations.
package testhelp

import (
"bytes"
"encoding/json"
"log/slog"
"strings"
"testing"
"testing/slogtest"
)

// RunSlogTests runs slogtest.TestHandler on a given slog.Handler, which is
// expected to emit JSON into the provided buffer.
func RunSlogTests(t *testing.T, createHandler func(buffer *bytes.Buffer) slog.Handler, exceptions ...string) {
var buffer bytes.Buffer
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'}) {
if len(line) == 0 {
continue
}
var m map[string]any
if err := json.Unmarshal(line, &m); err != nil {
t.Errorf("%v: %q", err, string(line))
}
ms = append(ms, m)
}
return ms
})

// Correlating failures with individual test cases is hard with the current API.
// See https://github.com/golang/go/issues/61758
t.Logf("Output:\n%s", buffer.String())
if err != nil {
if unwrappable, ok := err.(interface {
Unwrap() []error
}); ok {
for _, err := range unwrappable.Unwrap() {
if !containsOne(err.Error(), exceptions...) {
t.Errorf("Unexpected error: %v", err)
}
}
} else {
// Shouldn't be reached, errors from errors.Join can be split up.
t.Errorf("Unexpected errors:\n%v", err)
}
}
}

func containsOne(hay string, needles ...string) bool {
for _, needle := range needles {
if strings.Contains(hay, needle) {
return true
}
}
return false
}
33 changes: 33 additions & 0 deletions internal/testhelp/slog_test.go
Original file line number Diff line number Diff line change
@@ -0,0 +1,33 @@
//go:build go1.21
// +build go1.21

/*
Copyright 2023 The logr Authors.
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.
*/

package testhelp

import (
"bytes"
"log/slog"
"testing"
)

func TestRunSlogTestsOnSlogSink(t *testing.T) {
// This proves that RunSlogTests works.
RunSlogTests(t, func(buffer *bytes.Buffer) slog.Handler {
return slog.NewJSONHandler(buffer, nil)
})
}
93 changes: 6 additions & 87 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"
"encoding/json"
"errors"
"fmt"
"io"
Expand All @@ -31,10 +30,10 @@ import (
"runtime"
"strings"
"testing"
"testing/slogtest"

"github.com/go-logr/logr"
"github.com/go-logr/logr/funcr"
"github.com/go-logr/logr/internal/testhelp"
)

var debugWithoutTime = &slog.HandlerOptions{
Expand Down Expand Up @@ -105,92 +104,16 @@ func TestWithCallDepth(t *testing.T) {
}
}

func TestJSONHandler(t *testing.T) {
func TestRunSlogTestsOnSlogSink(t *testing.T) {
// This proves that slogSink passes slog's own tests.
testSlog(t, func(buffer *bytes.Buffer) slog.Handler {
return slog.NewJSONHandler(buffer, nil)
})
}

func TestFuncrHandler(t *testing.T) {
fn := func(buffer *bytes.Buffer) slog.Handler {
printfn := func(obj string) {
fmt.Fprintln(buffer, obj)
}
opts := funcr.Options{
LogTimestamp: true,
Verbosity: 10,
RenderBuiltinsHook: func(kvList []any) []any {
mappedKVList := make([]any, len(kvList))
for i := 0; i < len(kvList); i += 2 {
key := kvList[i]
switch key {
case "ts":
mappedKVList[i] = "time"
default:
mappedKVList[i] = key
}
mappedKVList[i+1] = kvList[i+1]
}
return mappedKVList
},
}
logger := funcr.NewJSON(printfn, opts)
testhelp.RunSlogTests(t, func(buffer *bytes.Buffer) slog.Handler {
handler := slog.NewJSONHandler(buffer, nil)
logger := logr.FromSlogHandler(handler)
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, createHandler func(buffer *bytes.Buffer) slog.Handler, exceptions ...string) {
var buffer bytes.Buffer
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'}) {
if len(line) == 0 {
continue
}
var m map[string]any
if err := json.Unmarshal(line, &m); err != nil {
t.Errorf("%v: %q", err, string(line))
}
ms = append(ms, m)
}
return ms
})

// Correlating failures with individual test cases is hard with the current API.
// See https://github.com/golang/go/issues/61758
t.Logf("Output:\n%s", buffer.String())
if err != nil {
if unwrappable, ok := err.(interface {
Unwrap() []error
}); ok {
for _, err := range unwrappable.Unwrap() {
if !containsOne(err.Error(), exceptions...) {
t.Errorf("Unexpected error: %v", err)
}
}
} else {
// Shouldn't be reached, errors from errors.Join can be split up.
t.Errorf("Unexpected errors:\n%v", err)
}
}
}

func containsOne(hay string, needles ...string) bool {
for _, needle := range needles {
if strings.Contains(hay, needle) {
return true
}
}
return false
}

func TestDiscard(_ *testing.T) {
func TestSlogSinkOnDiscard(_ *testing.T) {
// Compile-test
logger := slog.New(logr.ToSlogHandler(logr.Discard()))
logger.WithGroup("foo").With("x", 1).Info("hello")
Expand All @@ -205,10 +128,6 @@ func TestConversion(t *testing.T) {
e2 := logr.FromSlogHandler(logr.ToSlogHandler(e))
expectEqual(t, e, e2)

f := funcr.New(func(prefix, args string) {}, funcr.Options{})
f2 := logr.FromSlogHandler(logr.ToSlogHandler(f))
expectEqual(t, f, f2)

text := slog.NewTextHandler(io.Discard, nil)
text2 := logr.ToSlogHandler(logr.FromSlogHandler(text))
expectEqual(t, text, text2)
Expand Down

0 comments on commit f558531

Please sign in to comment.