-
Notifications
You must be signed in to change notification settings - Fork 0
/
handler_test.go
108 lines (92 loc) · 1.92 KB
/
handler_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
package cslog
import (
"context"
"io"
"log/slog"
"os"
"slices"
"strings"
"testing"
"github.com/stretchr/testify/require"
)
func TestCtx(t *testing.T) {
opt := &slog.HandlerOptions{
Level: slog.LevelDebug,
}
opt = WithoutTime(opt)
l := slog.New(slog.NewJSONHandler(os.Stdout, opt))
ctx := FromBackground(l)
Debug(ctx, "hello", slog.String("from", "outer"))
ctx = WithAttrs(ctx, slog.String("from", "outer"))
f := func(ctx context.Context) {
ctx = WithAttrs(ctx, slog.String("from", "inner"))
Debug(ctx, "hello")
ctx = WithAttrs(ctx, slog.Int("count", 1))
Debug(ctx, "goodbye")
}
f(WithGroup(ctx, "f"))
Debug(ctx, "goodbye")
}
func TestReplaceFn(t *testing.T) {
opt := &slog.HandlerOptions{
Level: slog.LevelDebug,
ReplaceAttr: func(groups []string, a slog.Attr) slog.Attr {
if slices.Contains(groups, "secret") {
return slog.Attr{
Key: a.Key,
Value: slog.StringValue(strings.Repeat("*", len(a.Value.String()))),
}
}
return a
},
}
f := new(Fixture)
tt := []struct {
name string
w io.Writer
initOpts *slog.HandlerOptions
forDisplay bool
}{
{
"stdout -- inspection",
os.Stdout,
opt,
true,
},
{
name: "fixture",
w: f,
initOpts: opt,
},
{
name: "fixture with nil start",
w: f,
initOpts: nil,
},
}
// print it
for _, tc := range tt {
t.Run(tc.name, func(t *testing.T) {
l := slog.New(slog.NewJSONHandler(tc.w, WithoutTime(opt)))
l.Debug("hello", slog.Group("secret", slog.String("value", "foo")))
if tc.forDisplay {
return
}
require.NotContains(t, f.Body, "time")
require.NotContains(t, f.Body, "foo")
require.Contains(t, f.Body, "value")
require.Contains(t, f.Body, "secret")
f.Reset()
})
}
}
type Fixture struct {
Body string
}
func (f *Fixture) Write(b []byte) (int, error) {
f.Body = string(b)
return len(b), nil
}
func (f *Fixture) Reset() {
f.Body = ""
}