-
Notifications
You must be signed in to change notification settings - Fork 0
/
wrap_test.go
75 lines (65 loc) · 1.59 KB
/
wrap_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
package slogw
import (
"bytes"
"context"
"encoding/json"
"log/slog"
"testing"
"github.com/stretchr/testify/assert"
)
func TestWrapWithRegister(t *testing.T) {
logging := func(ctx context.Context) {
slog.InfoContext(ctx, "test")
}
type ctxKey1Tyep struct{}
ctxKey1 := ctxKey1Tyep{}
addKeyValue := func(ctx context.Context, v string) context.Context {
return context.WithValue(ctx, ctxKey1, v)
}
defaultWrapFuncs = nil
Register(
func(orig HandleFunc) HandleFunc {
return func(ctx context.Context, rec slog.Record) error {
val, ok := ctx.Value(ctxKey1).(string)
if ok {
rec.Add("key1", val)
}
return orig(ctx, rec)
}
},
)
newLoggerAndBuf := func() (*slog.Logger, *bytes.Buffer) {
buf := bytes.NewBufferString("")
logger := New(slog.NewJSONHandler(buf, nil))
return logger, buf
}
type pattern struct {
ctx context.Context
key1Value *string
name string
}
strPtr := func(s string) *string {
return &s
}
patterns := []pattern{
{context.Background(), nil, "no value"},
{addKeyValue(context.Background(), "value1"), strPtr("value1"), "value1"},
{addKeyValue(context.Background(), "value2"), strPtr("value2"), "value2"},
}
for _, ptn := range patterns {
t.Run(ptn.name, func(t *testing.T) {
logger, buf := newLoggerAndBuf()
slog.SetDefault(logger)
logging(ptn.ctx)
d := map[string]any{}
t.Logf("buf: %s\n", buf.String())
err := json.Unmarshal(buf.Bytes(), &d)
assert.NoError(t, err)
if ptn.key1Value == nil {
assert.Nil(t, d["key1"])
} else {
assert.Equal(t, *ptn.key1Value, d["key1"])
}
})
}
}