| 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 testhelp holds helper functions for the testing of logr and built-in |
| 20 |
// implementations. |
| 21 |
package testhelp |
| 22 |
|
| 23 |
import ( |
| 24 |
"bytes" |
| 25 |
"encoding/json" |
| 26 |
"log/slog" |
| 27 |
"strings" |
| 28 |
"testing" |
| 29 |
"testing/slogtest" |
| 30 |
) |
| 31 |
|
| 32 |
// RunSlogTests runs slogtest.TestHandler on a given slog.Handler, which is |
| 33 |
// expected to emit JSON into the provided buffer. |
| 34 |
func RunSlogTests(t *testing.T, createHandler func(buffer *bytes.Buffer) slog.Handler, exceptions ...string) { |
| 35 |
var buffer bytes.Buffer |
| 36 |
handler := createHandler(&buffer) |
| 37 |
err := slogtest.TestHandler(handler, func() []map[string]any { |
| 38 |
var ms []map[string]any |
| 39 |
for _, line := range bytes.Split(buffer.Bytes(), []byte{'\n'}) { |
| 40 |
if len(line) == 0 { |
| 41 |
continue |
| 42 |
} |
| 43 |
var m map[string]any |
| 44 |
if err := json.Unmarshal(line, &m); err != nil { |
| 45 |
t.Errorf("%v: %q", err, string(line)) |
| 46 |
} |
| 47 |
ms = append(ms, m) |
| 48 |
} |
| 49 |
return ms |
| 50 |
}) |
| 51 |
|
| 52 |
// Correlating failures with individual test cases is hard with the current API. |
| 53 |
// See https://github.com/golang/go/issues/61758 |
| 54 |
t.Logf("Output:\n%s", buffer.String()) |
| 55 |
if err != nil { |
| 56 |
if unwrappable, ok := err.(interface { |
| 57 |
Unwrap() []error |
| 58 |
}); ok { |
| 59 |
for _, err := range unwrappable.Unwrap() { |
| 60 |
if !containsOne(err.Error(), exceptions...) { |
| 61 |
t.Errorf("Unexpected error: %v", err) |
| 62 |
} |
| 63 |
} |
| 64 |
} else { |
| 65 |
// Shouldn't be reached, errors from errors.Join can be split up. |
| 66 |
t.Errorf("Unexpected errors:\n%v", err) |
| 67 |
} |
| 68 |
} |
| 69 |
} |
| 70 |
|
| 71 |
func containsOne(hay string, needles ...string) bool { |
| 72 |
for _, needle := range needles { |
| 73 |
if strings.Contains(hay, needle) { |
| 74 |
return true |
| 75 |
} |
| 76 |
} |
| 77 |
return false |
| 78 |
} |