cloudflare/pint

Public

mirrored fromhttps://github.com/cloudflare/pintAvailable

CodeCommitsIssuesPull requestsActionsInsightsSecurity
v0.75.0

Branches

Tags

  • No tags available.
0Branches0Tags
Go to file
Add file
Code

Clone

HTTPS

Download ZIP

internal/log/handler_test.go

106lines · modecode

1package log
2
3import (
4 "bytes"
5 "encoding/json"
6 "errors"
7 "log/slog"
8 "strconv"
9 "testing"
10
11 "github.com/stretchr/testify/require"
12)
13
14func TestHandler(t *testing.T) {
15 type testCaseT struct {
16 run func(l *slog.Logger)
17 expected string
18 noColor bool
19 }
20
21 testCases := []testCaseT{
22 {
23 noColor: true,
24 run: func(l *slog.Logger) {
25 l.Debug("foo", slog.Int("count", 5))
26 },
27 expected: "level=DEBUG msg=foo count=5\n",
28 },
29 {
30 noColor: false,
31 run: func(l *slog.Logger) {
32 l.Debug("foo", slog.Int("count", 5))
33 },
34 expected: "level=DEBUG msg=foo count=5\n", // nolint: staticcheck
35 },
36 {
37 noColor: true,
38 run: func(l *slog.Logger) {
39 l.Debug("foo", slog.Int("count", 5))
40 l.Info("bar", slog.String("string", "a b c"), slog.Any("list", []int{1, 2, 3}))
41 },
42 expected: "level=DEBUG msg=foo count=5\nlevel=INFO msg=bar string=\"a b c\" list=[1,2,3]\n",
43 },
44 {
45 noColor: true,
46 run: func(l *slog.Logger) {
47 l.Warn("bar", slog.Any("strings", []string{"a", "b", "c + d"}))
48 },
49 expected: "level=WARN msg=bar strings=[\"a\",\"b\",\"c + d\"]\n",
50 },
51 {
52 noColor: true,
53 run: func(l *slog.Logger) {
54 l.Error("bar", slog.Any("err", errors.New("error")))
55 },
56 expected: "level=ERROR msg=bar err=error\n",
57 },
58 {
59 noColor: false,
60 run: func(l *slog.Logger) {
61 l.Error("bar", slog.Any("err", errors.New("error")))
62 },
63 expected: "level=ERROR msg=bar err=error\n", // nolint: staticcheck
64 },
65 {
66 noColor: true,
67 run: func(l *slog.Logger) {
68 l.Error("bar", slog.Any("err", nil))
69 },
70 expected: "level=ERROR msg=bar err=null\n",
71 },
72 {
73 noColor: true,
74 run: func(l *slog.Logger) {
75 type Foo struct {
76 N json.Number
77 }
78 x := Foo{json.Number(`invalid`)}
79 l.Error("bar", slog.Any("err", x))
80 },
81 expected: "level=ERROR msg=bar err={invalid}\n",
82 },
83 {
84 noColor: true,
85 run: func(l *slog.Logger) {
86 l.With(slog.String("with", "true")).Error("bar")
87 },
88 expected: "level=ERROR msg=bar\n",
89 },
90 {
91 noColor: true,
92 run: func(l *slog.Logger) {
93 l.Info("bar", slog.Group("group", slog.String("with", "true")))
94 },
95 expected: "level=INFO msg=bar group=[{\"Key\":\"with\",\"Value\":{}}]\n",
96 },
97 }
98
99 for i, tc := range testCases {
100 t.Run(strconv.Itoa(i), func(t *testing.T) {
101 dst := bytes.NewBufferString("")
102 tc.run(slog.New(newHandler(dst, slog.LevelDebug.Level(), tc.noColor)))
103 require.Equal(t, tc.expected, dst.String())
104 })
105 }
106}
107