From 805b145a06325e8150a23356715aaab2fc1a4b15 Mon Sep 17 00:00:00 2001 From: Lukasz Mierzwa Date: Fri, 6 Dec 2024 16:32:16 +0000 Subject: [PATCH] Add tests for log handler --- internal/log/handler_test.go | 106 +++++++++++++++++++++++++++++++++++ 1 file changed, 106 insertions(+) create mode 100644 internal/log/handler_test.go diff --git a/internal/log/handler_test.go b/internal/log/handler_test.go new file mode 100644 index 00000000..5d792b4e --- /dev/null +++ b/internal/log/handler_test.go @@ -0,0 +1,106 @@ +package log + +import ( + "bytes" + "encoding/json" + "errors" + "log/slog" + "strconv" + "testing" + + "github.com/stretchr/testify/require" +) + +func TestHandler(t *testing.T) { + type testCaseT struct { + run func(l *slog.Logger) + expected string + noColor bool + } + + testCases := []testCaseT{ + { + noColor: true, + run: func(l *slog.Logger) { + l.Debug("foo", slog.Int("count", 5)) + }, + expected: "level=DEBUG msg=foo count=5\n", + }, + { + noColor: false, + run: func(l *slog.Logger) { + l.Debug("foo", slog.Int("count", 5)) + }, + expected: "level=DEBUG msg=foo count=5\n", + }, + { + noColor: true, + run: func(l *slog.Logger) { + l.Debug("foo", slog.Int("count", 5)) + l.Info("bar", slog.String("string", "a b c"), slog.Any("list", []int{1, 2, 3})) + }, + expected: "level=DEBUG msg=foo count=5\nlevel=INFO msg=bar string=\"a b c\" list=[1,2,3]\n", + }, + { + noColor: true, + run: func(l *slog.Logger) { + l.Warn("bar", slog.Any("strings", []string{"a", "b", "c + d"})) + }, + expected: "level=WARN msg=bar strings=[\"a\",\"b\",\"c + d\"]\n", + }, + { + noColor: true, + run: func(l *slog.Logger) { + l.Error("bar", slog.Any("err", errors.New("error"))) + }, + expected: "level=ERROR msg=bar err=error\n", + }, + { + noColor: false, + run: func(l *slog.Logger) { + l.Error("bar", slog.Any("err", errors.New("error"))) + }, + expected: "level=ERROR msg=bar err=error\n", + }, + { + noColor: true, + run: func(l *slog.Logger) { + l.Error("bar", slog.Any("err", nil)) + }, + expected: "level=ERROR msg=bar err=null\n", + }, + { + noColor: true, + run: func(l *slog.Logger) { + type Foo struct { + N json.Number + } + x := Foo{json.Number(`invalid`)} + l.Error("bar", slog.Any("err", x)) + }, + expected: "level=ERROR msg=bar err={invalid}\n", + }, + { + noColor: true, + run: func(l *slog.Logger) { + l.With(slog.String("with", "true")).Error("bar") + }, + expected: "level=ERROR msg=bar\n", + }, + { + noColor: true, + run: func(l *slog.Logger) { + l.Info("bar", slog.Group("group", slog.String("with", "true"))) + }, + expected: "level=INFO msg=bar group=[{\"Key\":\"with\",\"Value\":{}}]\n", + }, + } + + for i, tc := range testCases { + t.Run(strconv.Itoa(i), func(t *testing.T) { + dst := bytes.NewBufferString("") + tc.run(slog.New(newHandler(dst, slog.LevelDebug.Level(), tc.noColor))) + require.Equal(t, tc.expected, dst.String()) + }) + } +}