-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathutils_test.go
More file actions
103 lines (90 loc) · 2.36 KB
/
utils_test.go
File metadata and controls
103 lines (90 loc) · 2.36 KB
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
package slogbuffer_test
import (
"bytes"
"context"
"fmt"
"github.com/delicb/slogbuffer"
"io"
"log/slog"
"regexp"
"slices"
"strings"
"testing"
)
func getSimplifiedTextHandler() (slog.Handler, io.Reader) {
writer := new(bytes.Buffer)
return slog.NewTextHandler(writer, &slog.HandlerOptions{
ReplaceAttr: func(groups []string, attr slog.Attr) slog.Attr {
// remove time
if attr.Key == "time" {
return slog.Attr{}
}
return attr
},
}), writer
}
func filterOut[T any](s []T, f func(T) bool) []T {
res := make([]T, 0, len(s))
for _, el := range s {
if f(el) {
res = append(res, el)
}
}
return slices.Clip(res)
}
func getLines(t *testing.T, r io.Reader) []string {
t.Helper()
all, err := io.ReadAll(r)
if err != nil {
t.Fatalf("reading all lines: %v", err)
}
return filterOut(
strings.Split(strings.TrimSpace(string(all)), "\n"),
func(s string) bool { return s != "" },
)
}
func setRealHandler(t *testing.T, h *slogbuffer.BufferLogHandler, real slog.Handler) {
t.Helper()
if err := h.SetRealHandler(context.Background(), real); err != nil {
t.Fatalf("setting real handler: %v", err)
}
}
func expectLinesNo(t *testing.T, lines []string, no int) {
t.Helper()
if len(lines) != no {
t.Fatalf("expect %d lines, got %d", no, len(lines))
}
}
func expectLevel(t *testing.T, line string, level slog.Level) {
t.Helper()
if !strings.Contains(line, fmt.Sprintf("level=%s", level.String())) {
t.Fatalf("expected level %s, line is %s", level.String(), line)
}
}
var hasSpaceRe = regexp.MustCompile(`\s`)
func maybeQuoteVal(key string, val string) string {
if hasSpaceRe.MatchString(val) {
return fmt.Sprintf("%s=%q", key, val)
}
return fmt.Sprintf("%s=%s", key, val)
}
func expectMsg(t *testing.T, line string, msg string) {
t.Helper()
if !strings.Contains(line, maybeQuoteVal("msg", msg)) {
t.Fatalf("expected msg %s, line is %s", msg, line)
}
}
func expectAttr(t *testing.T, line string, key string, value string) {
t.Helper()
expectedAttr := maybeQuoteVal(key, value)
if !strings.Contains(line, expectedAttr) {
t.Fatalf("expected attribute %s, line is %s", expectedAttr, line)
}
}
func expectNoAttr(t *testing.T, line string, key string, value string) {
t.Helper()
unexpectedAttr := maybeQuoteVal(key, value)
if strings.Contains(line, unexpectedAttr) {
t.Fatalf("unexpected attribute %s, line is %s", unexpectedAttr, line)
}
}