forked from influxdata/influxdb
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathmiddleware_test.go
274 lines (245 loc) · 5.54 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
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
package http
import (
"bytes"
"encoding/json"
"fmt"
"io"
"net/http"
"net/http/httptest"
"net/url"
"strconv"
"strings"
"testing"
"github.com/influxdata/influxdb/v2/logger"
"go.uber.org/zap"
"go.uber.org/zap/zapcore"
)
func TestLoggingMW(t *testing.T) {
newDebugLogger := func(t *testing.T) (*zap.Logger, *bytes.Buffer) {
t.Helper()
var buf bytes.Buffer
log, err := (&logger.Config{
Format: "auto",
Level: zapcore.DebugLevel,
}).New(&buf)
if err != nil {
t.Fatal(err)
}
return log, &buf
}
urlWithQueries := func(path string, queryPairs ...string) url.URL {
u := url.URL{
Path: path,
}
params := u.Query()
for i := 0; i < len(queryPairs)/2; i++ {
k, v := queryPairs[i*2], queryPairs[i*2+1]
params.Add(k, v)
}
return u
}
encodeBody := func(t *testing.T, k, v string) *bytes.Buffer {
t.Helper()
m := map[string]string{k: v}
var buf bytes.Buffer
err := json.NewEncoder(&buf).Encode(m)
if err != nil {
t.Fatal(err)
}
return &buf
}
getKVPair := func(s string) (string, string) {
kv := strings.Split(s, "=")
switch len(kv) {
case 1:
return kv[0], ""
case 2:
return kv[0], strings.TrimSuffix(kv[1], "\n")
default:
return "", ""
}
}
echoHandler := http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
var m map[string]string
err := json.NewDecoder(r.Body).Decode(&m)
if err != nil {
w.WriteHeader(422)
return
}
defer r.Body.Close()
// set a non 200 status code here
w.WriteHeader(202)
_, err = w.Write([]byte("ack"))
if err != nil {
w.WriteHeader(500)
return
}
})
teeReader := func(r *bytes.Buffer, w io.Writer) io.Reader {
if r == nil {
return nil
}
return io.TeeReader(r, w)
}
type testRun struct {
name string
method string
path string
queryPairs []string
hasBody bool
hideBody bool
}
testEndpoint := func(tt testRun) func(t *testing.T) {
fn := func(t *testing.T) {
t.Helper()
log, buf := newDebugLogger(t)
reqURL := urlWithQueries(tt.path, tt.queryPairs...)
var body *bytes.Buffer
if tt.hasBody {
body = encodeBody(t, "bin", "shake")
}
var trackerBuf bytes.Buffer
req := httptest.NewRequest(tt.method, reqURL.String(), teeReader(body, &trackerBuf))
rec := httptest.NewRecorder()
LoggingMW(log)(echoHandler).ServeHTTP(rec, req)
expected := map[string]string{
"method": tt.method,
"host": "example.com",
"path": reqURL.Path,
"query": reqURL.RawQuery,
"proto": "HTTP/1.1",
"status_code": strconv.Itoa(rec.Code),
"response_size": strconv.Itoa(rec.Body.Len()),
"content_length": strconv.FormatInt(req.ContentLength, 10),
}
if tt.hasBody {
expected["body"] = fmt.Sprintf("%q", trackerBuf.String())
}
// skip first 4 pairs, is the base logger stuff
for _, pair := range strings.Split(buf.String(), " ")[4:] {
k, v := getKVPair(pair)
switch k {
case "took", "remote":
if v == "" {
t.Errorf("unexpected value(%q) for key(%q): expected=non empty string", v, k)
}
case "body":
if tt.hideBody && v != "" {
t.Errorf("expected body to be \"\" but got=%q", v)
continue
}
fallthrough
case "user_agent":
default:
if expectedV := expected[k]; expectedV != v {
t.Errorf("unexpected value(%q) for key(%q): expected=%q", v, k, expectedV)
}
}
}
}
return fn
}
t.Run("logs the http request", func(t *testing.T) {
tests := []testRun{
{
name: "GET",
method: "GET",
path: "/foo",
queryPairs: []string{"dodgers", "are", "the", "terrible"},
},
{
name: "POST",
method: "POST",
path: "/foo",
queryPairs: []string{"bin", "shake"},
hasBody: true,
},
{
name: "PUT",
method: "PUT",
path: "/foo",
queryPairs: []string{"ninja", "turtles"},
hasBody: true,
},
{
name: "PATCH",
method: "PATCH",
path: "/foo",
queryPairs: []string{"peach", "daisy", "mario", "luigi"},
hasBody: true,
},
}
for _, tt := range tests {
t.Run(tt.name, testEndpoint(tt))
}
})
t.Run("does not log body for blacklisted routes", func(t *testing.T) {
tests := []testRun{
{
name: "signin",
method: "POSTT",
path: "/api/v2/signin",
},
{
name: "signout",
method: "POST",
path: "/api/v2/signout",
},
{
name: "me path",
method: "POST",
path: "/api/v2/me",
},
{
name: "me password path",
method: "POST",
path: "/api/v2/me/password",
},
{
name: "user password path",
method: "POST",
path: "/api/v2/users/user-id/password",
},
{
name: "write path",
method: "POST",
path: "/api/v2/write",
},
{
name: "legacy write path",
method: "POST",
path: "/write",
},
{
name: "orgs id secrets path",
method: "PATCH",
path: "/api/v2/orgs/org-id/secrets",
},
{
name: "orgs id secrets delete path",
method: "POST",
path: "/api/v2/orgs/org-id/secrets/delete",
},
{
name: "setup path",
method: "POST",
path: "/api/v2/setup",
},
{
name: "notifications endpoints path",
method: "POST",
path: "/api/v2/notificationEndpoints",
},
{
name: "notifications endpoints id path",
method: "PUT",
path: "/api/v2/notificationEndpoints/notification-id",
},
}
for _, tt := range tests {
tt.hasBody = true
tt.hideBody = true
t.Run(tt.name, testEndpoint(tt))
}
})
}