forked from grpc-ecosystem/go-grpc-middleware
-
Notifications
You must be signed in to change notification settings - Fork 0
/
server_interceptors_test.go
319 lines (282 loc) · 13.9 KB
/
server_interceptors_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
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
package kit_test
import (
"io"
"runtime"
"strings"
"testing"
"time"
"github.com/go-kit/kit/log"
"github.com/go-kit/kit/log/level"
grpc_middleware "github.com/grpc-ecosystem/go-grpc-middleware"
grpc_kit "github.com/grpc-ecosystem/go-grpc-middleware/logging/kit"
grpc_ctxtags "github.com/grpc-ecosystem/go-grpc-middleware/tags"
pb_testproto "github.com/grpc-ecosystem/go-grpc-middleware/testing/testproto"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/stretchr/testify/suite"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
)
func customCodeToLevel(c codes.Code, logger log.Logger) log.Logger {
if c == codes.Unauthenticated {
// Make this a special case for tests, and an error.
return level.Error(logger)
}
return grpc_kit.DefaultCodeToLevel(c, logger)
}
func TestKitLoggingSuite(t *testing.T) {
if strings.HasPrefix(runtime.Version(), "go1.7") {
t.Skipf("Skipping due to json.RawMessage incompatibility with go1.7")
return
}
opts := []grpc_kit.Option{
grpc_kit.WithLevels(customCodeToLevel),
}
b := newKitBaseSuite(t)
b.InterceptorTestSuite.ServerOpts = []grpc.ServerOption{
grpc_middleware.WithStreamServerChain(
grpc_ctxtags.StreamServerInterceptor(grpc_ctxtags.WithFieldExtractor(grpc_ctxtags.CodeGenRequestFieldExtractor)),
grpc_kit.StreamServerInterceptor(b.logger, opts...)),
grpc_middleware.WithUnaryServerChain(
grpc_ctxtags.UnaryServerInterceptor(grpc_ctxtags.WithFieldExtractor(grpc_ctxtags.CodeGenRequestFieldExtractor)),
grpc_kit.UnaryServerInterceptor(b.logger, opts...)),
}
suite.Run(t, &kitServerSuite{b})
}
type kitServerSuite struct {
*kitBaseSuite
}
func (s *kitServerSuite) TestPing_WithCustomTags() {
deadline := time.Now().Add(3 * time.Second)
_, err := s.Client.Ping(s.DeadlineCtx(deadline), goodPing)
require.NoError(s.T(), err, "there must be not be an error on a successful call")
msgs := s.getOutputJSONs()
require.Len(s.T(), msgs, 2, "two log statements should be logged")
for _, m := range msgs {
assert.Equal(s.T(), m["grpc.service"], "mwitkow.testproto.TestService", "all lines must contain service name")
assert.Equal(s.T(), m["grpc.method"], "Ping", "all lines must contain method name")
assert.Equal(s.T(), m["span.kind"], "server", "all lines must contain the kind of call (server)")
assert.Equal(s.T(), m["custom_tags.string"], "something", "all lines must contain `custom_tags.string`")
assert.Equal(s.T(), m["grpc.request.value"], "something", "all lines must contain fields extracted")
assert.Equal(s.T(), m["custom_field"], "custom_value", "all lines must contain `custom_field`")
assert.Contains(s.T(), m, "custom_tags.int", "all lines must contain `custom_tags.int`")
require.Contains(s.T(), m, "grpc.start_time", "all lines must contain the start time")
_, err := time.Parse(time.RFC3339, m["grpc.start_time"].(string))
assert.NoError(s.T(), err, "should be able to parse start time as RFC3339")
require.Contains(s.T(), m, "grpc.request.deadline", "all lines must contain the deadline of the call")
_, err = time.Parse(time.RFC3339, m["grpc.request.deadline"].(string))
require.NoError(s.T(), err, "should be able to parse deadline as RFC3339")
assert.Equal(s.T(), m["grpc.request.deadline"], deadline.Format(time.RFC3339), "should have the same deadline that was set by the caller")
}
assert.Equal(s.T(), msgs[0]["msg"], "some ping", "handler's message must contain user message")
assert.Equal(s.T(), msgs[1]["msg"], "finished unary call with code OK", "handler's message must contain user message")
assert.Equal(s.T(), msgs[1]["level"], "info", "must be logged at info level")
assert.Contains(s.T(), msgs[1], "grpc.time_ms", "interceptor log statement should contain execution time")
}
func (s *kitServerSuite) TestPingError_WithCustomLevels() {
for _, tcase := range []struct {
code codes.Code
level level.Value
msg string
}{
{
code: codes.Internal,
level: level.ErrorValue(),
msg: "Internal must remap to ErrorLevel in DefaultCodeToLevel",
},
{
code: codes.NotFound,
level: level.InfoValue(),
msg: "NotFound must remap to InfoLevel in DefaultCodeToLevel",
},
{
code: codes.FailedPrecondition,
level: level.WarnValue(),
msg: "FailedPrecondition must remap to WarnLevel in DefaultCodeToLevel",
},
{
code: codes.Unauthenticated,
level: level.ErrorValue(),
msg: "Unauthenticated is overwritten to DPanicLevel with customCodeToLevel override, which probably didn't work",
},
} {
s.buffer.Reset()
_, err := s.Client.PingError(
s.SimpleCtx(),
&pb_testproto.PingRequest{Value: "something", ErrorCodeReturned: uint32(tcase.code)})
require.Error(s.T(), err, "each call here must return an error")
msgs := s.getOutputJSONs()
require.Len(s.T(), msgs, 1, "only the interceptor log message is printed in PingErr")
m := msgs[0]
assert.Equal(s.T(), m["grpc.service"], "mwitkow.testproto.TestService", "all lines must contain service name")
assert.Equal(s.T(), m["grpc.method"], "PingError", "all lines must contain method name")
assert.Equal(s.T(), m["grpc.code"], tcase.code.String(), "all lines have the correct gRPC code")
assert.Equal(s.T(), m["level"], tcase.level.String(), tcase.msg)
assert.Equal(s.T(), m["msg"], "finished unary call with code "+tcase.code.String(), "needs the correct end message")
require.Contains(s.T(), m, "grpc.start_time", "all lines must contain the start time")
_, err = time.Parse(time.RFC3339, m["grpc.start_time"].(string))
assert.NoError(s.T(), err, "should be able to parse start time as RFC3339")
}
}
func (s *kitServerSuite) TestPingList_WithCustomTags() {
stream, err := s.Client.PingList(s.SimpleCtx(), goodPing)
require.NoError(s.T(), err, "should not fail on establishing the stream")
for {
_, err := stream.Recv()
if err == io.EOF {
break
}
require.NoError(s.T(), err, "reading stream should not fail")
}
msgs := s.getOutputJSONs()
require.Len(s.T(), msgs, 2, "two log statements should be logged")
for _, m := range msgs {
assert.Equal(s.T(), m["grpc.service"], "mwitkow.testproto.TestService", "all lines must contain service name")
assert.Equal(s.T(), m["grpc.method"], "PingList", "all lines must contain method name")
assert.Equal(s.T(), m["span.kind"], "server", "all lines must contain the kind of call (server)")
assert.Equal(s.T(), m["custom_tags.string"], "something", "all lines must contain `custom_tags.string` set by AddFields")
assert.Equal(s.T(), m["grpc.request.value"], "something", "all lines must contain fields extracted from goodPing because of test.manual_extractfields.pb")
assert.Contains(s.T(), m, "custom_tags.int", "all lines must contain `custom_tags.int` set by AddFields")
require.Contains(s.T(), m, "grpc.start_time", "all lines must contain the start time")
_, err := time.Parse(time.RFC3339, m["grpc.start_time"].(string))
assert.NoError(s.T(), err, "should be able to parse start time as RFC3339")
}
assert.Equal(s.T(), msgs[0]["msg"], "some pinglist", "handler's message must contain user message")
assert.Equal(s.T(), msgs[1]["msg"], "finished streaming call with code OK", "handler's message must contain user message")
assert.Equal(s.T(), msgs[1]["level"], "info", "OK codes must be logged on info level.")
assert.Contains(s.T(), msgs[1], "grpc.time_ms", "interceptor log statement should contain execution time")
}
func TestKitLoggingOverrideSuite(t *testing.T) {
if strings.HasPrefix(runtime.Version(), "go1.7") {
t.Skip("Skipping due to json.RawMessage incompatibility with go1.7")
return
}
opts := []grpc_kit.Option{
grpc_kit.WithDurationField(grpc_kit.DurationToDurationField),
}
b := newKitBaseSuite(t)
b.InterceptorTestSuite.ServerOpts = []grpc.ServerOption{
grpc_middleware.WithStreamServerChain(
grpc_ctxtags.StreamServerInterceptor(),
grpc_kit.StreamServerInterceptor(b.logger, opts...)),
grpc_middleware.WithUnaryServerChain(
grpc_ctxtags.UnaryServerInterceptor(),
grpc_kit.UnaryServerInterceptor(b.logger, opts...)),
}
suite.Run(t, &kitServerOverrideSuite{b})
}
type kitServerOverrideSuite struct {
*kitBaseSuite
}
func (s *kitServerOverrideSuite) TestPing_HasOverriddenDuration() {
_, err := s.Client.Ping(s.SimpleCtx(), goodPing)
require.NoError(s.T(), err, "there must be not be an error on a successful call")
msgs := s.getOutputJSONs()
require.Len(s.T(), msgs, 2, "two log statements should be logged")
for _, m := range msgs {
assert.Equal(s.T(), m["grpc.service"], "mwitkow.testproto.TestService", "all lines must contain service name")
assert.Equal(s.T(), m["grpc.method"], "Ping", "all lines must contain method name")
}
assert.Equal(s.T(), msgs[0]["msg"], "some ping", "handler's message must contain user message")
assert.NotContains(s.T(), msgs[0], "grpc.time_ms", "handler's message must not contain default duration")
assert.NotContains(s.T(), msgs[0], "grpc.duration", "handler's message must not contain overridden duration")
assert.Equal(s.T(), msgs[1]["msg"], "finished unary call with code OK", "handler's message must contain user message")
assert.Equal(s.T(), msgs[1]["level"], "info", "OK error codes must be logged on info level.")
assert.NotContains(s.T(), msgs[1], "grpc.time_ms", "handler's message must not contain default duration")
assert.Contains(s.T(), msgs[1], "grpc.duration", "handler's message must contain overridden duration")
}
func (s *kitServerOverrideSuite) TestPingList_HasOverriddenDuration() {
stream, err := s.Client.PingList(s.SimpleCtx(), goodPing)
require.NoError(s.T(), err, "should not fail on establishing the stream")
for {
_, err := stream.Recv()
if err == io.EOF {
break
}
require.NoError(s.T(), err, "reading stream should not fail")
}
msgs := s.getOutputJSONs()
require.Len(s.T(), msgs, 2, "two log statements should be logged")
for _, m := range msgs {
s.T()
assert.Equal(s.T(), m["grpc.service"], "mwitkow.testproto.TestService", "all lines must contain service name")
assert.Equal(s.T(), m["grpc.method"], "PingList", "all lines must contain method name")
}
assert.Equal(s.T(), msgs[0]["msg"], "some pinglist", "handler's message must contain user message")
assert.NotContains(s.T(), msgs[0], "grpc.time_ms", "handler's message must not contain default duration")
assert.NotContains(s.T(), msgs[0], "grpc.duration", "handler's message must not contain overridden duration")
assert.Equal(s.T(), msgs[1]["msg"], "finished streaming call with code OK", "handler's message must contain user message")
assert.Equal(s.T(), msgs[1]["level"], "info", "OK error codes must be logged on info level.")
assert.NotContains(s.T(), msgs[1], "grpc.time_ms", "handler's message must not contain default duration")
assert.Contains(s.T(), msgs[1], "grpc.duration", "handler's message must contain overridden duration")
}
func TestKitServerOverrideSuppressedSuite(t *testing.T) {
if strings.HasPrefix(runtime.Version(), "go1.7") {
t.Skip("Skipping due to json.RawMessage incompatibility with go1.7")
return
}
opts := []grpc_kit.Option{
grpc_kit.WithDecider(func(method string, err error) bool {
if err != nil && method == "/mwitkow.testproto.TestService/PingError" {
return true
}
return false
}),
}
b := newKitBaseSuite(t)
b.InterceptorTestSuite.ServerOpts = []grpc.ServerOption{
grpc_middleware.WithStreamServerChain(
grpc_ctxtags.StreamServerInterceptor(),
grpc_kit.StreamServerInterceptor(b.logger, opts...)),
grpc_middleware.WithUnaryServerChain(
grpc_ctxtags.UnaryServerInterceptor(),
grpc_kit.UnaryServerInterceptor(b.logger, opts...)),
}
suite.Run(t, &kitServerOverridenDeciderSuite{b})
}
type kitServerOverridenDeciderSuite struct {
*kitBaseSuite
}
func (s *kitServerOverridenDeciderSuite) TestPing_HasOverriddenDecider() {
_, err := s.Client.Ping(s.SimpleCtx(), goodPing)
require.NoError(s.T(), err, "there must be not be an error on a successful call")
msgs := s.getOutputJSONs()
require.Len(s.T(), msgs, 1, "single log statements should be logged")
assert.Equal(s.T(), msgs[0]["grpc.service"], "mwitkow.testproto.TestService", "all lines must contain service name")
assert.Equal(s.T(), msgs[0]["grpc.method"], "Ping", "all lines must contain method name")
assert.Equal(s.T(), msgs[0]["msg"], "some ping", "handler's message must contain user message")
}
func (s *kitServerOverridenDeciderSuite) TestPingError_HasOverriddenDecider() {
code := codes.NotFound
msg := "NotFound must remap to InfoLevel in DefaultCodeToLevel"
s.buffer.Reset()
_, err := s.Client.PingError(
s.SimpleCtx(),
&pb_testproto.PingRequest{Value: "something", ErrorCodeReturned: uint32(code)})
require.Error(s.T(), err, "each call here must return an error")
msgs := s.getOutputJSONs()
require.Len(s.T(), msgs, 1, "only the interceptor log message is printed in PingErr")
m := msgs[0]
assert.Equal(s.T(), m["grpc.service"], "mwitkow.testproto.TestService", "all lines must contain service name")
assert.Equal(s.T(), m["grpc.method"], "PingError", "all lines must contain method name")
assert.Equal(s.T(), m["grpc.code"], code.String(), "all lines must contain the correct gRPC code")
assert.Equal(s.T(), m["level"], "info", msg)
}
func (s *kitServerOverridenDeciderSuite) TestPingList_HasOverriddenDecider() {
stream, err := s.Client.PingList(s.SimpleCtx(), goodPing)
require.NoError(s.T(), err, "should not fail on establishing the stream")
for {
_, err := stream.Recv()
if err == io.EOF {
break
}
require.NoError(s.T(), err, "reading stream should not fail")
}
msgs := s.getOutputJSONs()
require.Len(s.T(), msgs, 1, "single log statements should be logged")
assert.Equal(s.T(), msgs[0]["grpc.service"], "mwitkow.testproto.TestService", "all lines must contain service name")
assert.Equal(s.T(), msgs[0]["grpc.method"], "PingList", "all lines must contain method name")
assert.Equal(s.T(), msgs[0]["msg"], "some pinglist", "handler's message must contain user message")
assert.NotContains(s.T(), msgs[0], "grpc.time_ms", "handler's message must not contain default duration")
assert.NotContains(s.T(), msgs[0], "grpc.duration", "handler's message must not contain overridden duration")
}