-
Notifications
You must be signed in to change notification settings - Fork 3
/
middleware_test.go
117 lines (105 loc) · 2.19 KB
/
middleware_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
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
104
105
106
107
108
109
110
111
112
113
114
115
116
117
package logging
import (
"fmt"
"io"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
"log/slog"
"github.com/stretchr/testify/assert"
)
func newTestLogger() (out *strings.Builder, logger *slog.Logger) {
out = new(strings.Builder)
handler := slog.NewJSONHandler(out, &slog.HandlerOptions{
Level: slog.LevelDebug,
}).WithAttrs([]slog.Attr{slog.String("time", "not")})
return out, slog.New(handler)
}
type testWriter struct {
*httptest.ResponseRecorder
err error
}
func (w *testWriter) Write(b []byte) (int, error) {
if w.err != nil {
return 0, w.err
}
return w.ResponseRecorder.Write(b)
}
func newTestWriter(err error) *testWriter {
return &testWriter{
ResponseRecorder: httptest.NewRecorder(),
err: err,
}
}
func TestMiddleware(t *testing.T) {
tests := []struct {
name string
err error
want string
}{
{
name: "ok",
want: `{
"level":"INFO",
"time": "not",
"msg":"request served",
"id":"id1",
"duration":1000000000,
"request":{
"method":"GET",
"url":"https://example.com/path/"
},
"response":{
"status":200,
"written":13
}
}`,
},
{
name: "error",
err: io.ErrClosedPipe,
want: `{
"level":"WARN",
"time": "not",
"msg":"write response",
"error": "io: read/write on closed pipe",
"id":"id1",
"duration":1000000000,
"request":{
"method":"GET",
"url":"https://example.com/path/"
},
"response":{
"status":200,
"written":0
}
}`,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
logOut, logger := newTestLogger()
mw := Middleware(
WithLogger(logger),
WithIDFunc(func() slog.Attr {
return slog.String("id", "id1")
}),
WithDurationFunc(func(time.Time) time.Duration {
return time.Second
}),
WithRequestAttr(requestToAttr),
WithLoggedWriter(newLoggedWriter),
)
next := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
fmt.Fprint(w, "Hello, World!")
})
w := newTestWriter(tt.err)
r := httptest.NewRequest("GET", "https://example.com/path/", nil)
mw(next).ServeHTTP(w, r)
got := logOut.String()
assert.JSONEq(t, tt.want, got)
})
}
}