aboutsummaryrefslogtreecommitdiffstats
path: root/logging/test/handler_test.go
blob: 5e9430a24666e0601e919651b182e984721c4bdf (plain) (blame)
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
package test_test

import (
	"fmt"
	"log/slog"
	"runtime"
	"testing"
	"testing/slogtest"

	"go.sudomsg.com/kit/logging/test"
)

func TestMockHandlerCompliance(t *testing.T) {
	var lastMock *test.MockHandler

	slogtest.Run(t,
		func(t *testing.T) slog.Handler {
			lastMock = test.NewMockLogHandler(t)
			return lastMock
		},
		func(t *testing.T) map[string]any {
			t.Helper()

			recs := lastMock.Records()
			if len(recs) == 0 {
				t.Fatalf("no records captured")
			}

			rec := recs[len(recs)-1]

			// Convert slog.Record to map[string]any
			m := make(map[string]any)
			if !rec.Time.IsZero() {
				m[slog.TimeKey] = rec.Time
			}
			if rec.PC != 0 {
				fs := runtime.CallersFrames([]uintptr{rec.PC})
				f, _ := fs.Next()
				m[slog.SourceKey] = fmt.Sprintf("%s:%d", f.File, f.Line)
			}
			m[slog.LevelKey] = rec.Level
			m[slog.MessageKey] = rec.Message

			rec.Attrs(func(attr slog.Attr) bool {
				insertAttr(t, m, attr)
				return true
			})

			return m
		},
	)
}

func insertAttr(t testing.TB, m map[string]any, attr slog.Attr) {
	t.Helper()

	if attr.Value.Kind() == slog.KindGroup {
		groupMap := make(map[string]any)
		for _, a := range attr.Value.Group() {
			insertAttr(t, groupMap, a)
		}
		m[attr.Key] = groupMap
	} else {
		m[attr.Key] = attr.Value.Any()
	}
}