This repository has been archived by the owner on Mar 26, 2021. It is now read-only.
forked from grpc-ecosystem/go-grpc-middleware
-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathinterceptors_test.go
217 lines (192 loc) · 8.94 KB
/
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
// Copyright 2017 Michal Witkowski. All Rights Reserved.
// See LICENSE for licensing terms.
package grpc_opentracing_test
import (
"encoding/json"
"testing"
"fmt"
"net/http"
"io"
"github.com/grpc-ecosystem/go-grpc-middleware"
"github.com/grpc-ecosystem/go-grpc-middleware/tags"
grpc_testing "github.com/grpc-ecosystem/go-grpc-middleware/testing"
pb_testproto "github.com/grpc-ecosystem/go-grpc-middleware/testing/testproto"
grpc_opentracing "github.com/grpc-ecosystem/go-grpc-middleware/tracing/opentracing"
opentracing "github.com/opentracing/opentracing-go"
"github.com/opentracing/opentracing-go/mocktracer"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"github.com/stretchr/testify/suite"
"golang.org/x/net/context"
"google.golang.org/grpc"
"google.golang.org/grpc/codes"
)
var (
goodPing = &pb_testproto.PingRequest{Value: "something", SleepTimeMs: 9999}
fakeInboundTraceId = 1337
fakeInboundSpanId = 999
)
func tagsToJson(value map[string]interface{}) string {
str, _ := json.Marshal(value)
return string(str)
}
func tagsFromJson(t *testing.T, jstring string) map[string]interface{} {
var msgMapTemplate interface{}
err := json.Unmarshal([]byte(jstring), &msgMapTemplate)
if err != nil {
t.Fatalf("failed unmarshaling tags from response %v", err)
}
return msgMapTemplate.(map[string]interface{})
}
type tracingAssertService struct {
pb_testproto.TestServiceServer
T *testing.T
}
func (s *tracingAssertService) Ping(ctx context.Context, ping *pb_testproto.PingRequest) (*pb_testproto.PingResponse, error) {
assert.NotNil(s.T, opentracing.SpanFromContext(ctx), "handlers must have the spancontext in their context, otherwise propagation will fail")
tags := grpc_ctxtags.Extract(ctx)
assert.True(s.T, tags.Has(grpc_opentracing.TagTraceId), "tags must contain traceid")
assert.True(s.T, tags.Has(grpc_opentracing.TagSpanId), "tags must contain traceid")
return s.TestServiceServer.Ping(ctx, ping)
}
func (s *tracingAssertService) PingError(ctx context.Context, ping *pb_testproto.PingRequest) (*pb_testproto.Empty, error) {
assert.NotNil(s.T, opentracing.SpanFromContext(ctx), "handlers must have the spancontext in their context, otherwise propagation will fail")
return s.TestServiceServer.PingError(ctx, ping)
}
func (s *tracingAssertService) PingList(ping *pb_testproto.PingRequest, stream pb_testproto.TestService_PingListServer) error {
assert.NotNil(s.T, opentracing.SpanFromContext(stream.Context()), "handlers must have the spancontext in their context, otherwise propagation will fail")
tags := grpc_ctxtags.Extract(stream.Context())
assert.True(s.T, tags.Has(grpc_opentracing.TagTraceId), "tags must contain traceid")
assert.True(s.T, tags.Has(grpc_opentracing.TagSpanId), "tags must contain traceid")
return s.TestServiceServer.PingList(ping, stream)
}
func (s *tracingAssertService) PingEmpty(ctx context.Context, empty *pb_testproto.Empty) (*pb_testproto.PingResponse, error) {
assert.NotNil(s.T, opentracing.SpanFromContext(ctx), "handlers must have the spancontext in their context, otherwise propagation will fail")
return s.TestServiceServer.PingEmpty(ctx, empty)
}
func TestTaggingSuite(t *testing.T) {
mockTracer := mocktracer.New()
opts := []grpc_opentracing.Option{
grpc_opentracing.WithTracer(mockTracer),
grpc_opentracing.WithIgnoredErrorCodes(codes.NotFound),
}
s := &OpentracingSuite{
mockTracer: mockTracer,
InterceptorTestSuite: &grpc_testing.InterceptorTestSuite{
TestService: &tracingAssertService{TestServiceServer: &grpc_testing.TestPingService{T: t}, T: t},
ClientOpts: []grpc.DialOption{
grpc.WithUnaryInterceptor(grpc_opentracing.UnaryClientInterceptor(opts...)),
grpc.WithStreamInterceptor(grpc_opentracing.StreamClientInterceptor(opts...)),
},
ServerOpts: []grpc.ServerOption{
grpc_middleware.WithStreamServerChain(
grpc_ctxtags.StreamServerInterceptor(grpc_ctxtags.WithFieldExtractor(grpc_ctxtags.CodeGenRequestFieldExtractor)),
grpc_opentracing.StreamServerInterceptor(opts...)),
grpc_middleware.WithUnaryServerChain(
grpc_ctxtags.UnaryServerInterceptor(grpc_ctxtags.WithFieldExtractor(grpc_ctxtags.CodeGenRequestFieldExtractor)),
grpc_opentracing.UnaryServerInterceptor(opts...)),
},
},
}
suite.Run(t, s)
}
type OpentracingSuite struct {
*grpc_testing.InterceptorTestSuite
mockTracer *mocktracer.MockTracer
}
func (s *OpentracingSuite) SetupTest() {
s.mockTracer.Reset()
}
func (s *OpentracingSuite) createContextFromFakeHttpRequestParent(ctx context.Context) context.Context {
hdr := http.Header{}
hdr.Set("mockpfx-ids-traceid", fmt.Sprint(fakeInboundTraceId))
hdr.Set("mockpfx-ids-spanid", fmt.Sprint(fakeInboundSpanId))
hdr.Set("mockpfx-ids-sampled", fmt.Sprint(true))
parentSpanContext, err := s.mockTracer.Extract(opentracing.HTTPHeaders, opentracing.HTTPHeadersCarrier(hdr))
require.NoError(s.T(), err, "parsing a fake HTTP request headers shouldn't fail, ever")
fakeSpan := s.mockTracer.StartSpan(
"/fake/parent/http/request",
// this is magical, it attaches the new span to the parent parentSpanContext, and creates an unparented one if empty.
opentracing.ChildOf(parentSpanContext),
)
fakeSpan.Finish()
return opentracing.ContextWithSpan(ctx, fakeSpan)
}
func (s *OpentracingSuite) assertTracesCreated(methodName string) (clientSpan *mocktracer.MockSpan, serverSpan *mocktracer.MockSpan) {
spans := s.mockTracer.FinishedSpans()
for _, span := range spans {
s.T().Logf("span: %v, tags: %v", span, span.Tags())
}
require.Len(s.T(), spans, 3, "should record 3 spans: one fake inbound, one client, one server")
traceIdAssert := fmt.Sprintf("traceId=%d", fakeInboundTraceId)
for _, span := range spans {
assert.Contains(s.T(), span.String(), traceIdAssert, "not part of the fake parent trace: %v", span)
if span.OperationName == methodName {
kind := fmt.Sprintf("%v", span.Tag("span.kind"))
if kind == "client" {
clientSpan = span
} else if kind == "server" {
serverSpan = span
}
assert.EqualValues(s.T(), span.Tag("component"), "gRPC", "span must be tagged with gRPC component")
}
}
require.NotNil(s.T(), clientSpan, "client span must be there")
require.NotNil(s.T(), serverSpan, "server span must be there")
assert.EqualValues(s.T(), serverSpan.Tag("grpc.request.value"), "something", "grpc_ctxtags must be propagated, in this case ones from request fields")
return clientSpan, serverSpan
}
func (s *OpentracingSuite) TestPing_PropagatesTraces() {
ctx := s.createContextFromFakeHttpRequestParent(s.SimpleCtx())
_, err := s.Client.Ping(ctx, goodPing)
require.NoError(s.T(), err, "there must be not be an on a successful call")
s.assertTracesCreated("/mwitkow.testproto.TestService/Ping")
}
func (s *OpentracingSuite) TestPing_ClientContextTags() {
const name = "opentracing.custom"
ctx := grpc_opentracing.ClientAddContextTags(
s.createContextFromFakeHttpRequestParent(s.SimpleCtx()),
opentracing.Tags{name: ""},
)
_, err := s.Client.Ping(ctx, goodPing)
require.NoError(s.T(), err, "there must be not be an on a successful call")
for _, span := range s.mockTracer.FinishedSpans() {
if span.OperationName == "/mwitkow.testproto.TestService/Ping" {
kind := fmt.Sprintf("%v", span.Tag("span.kind"))
if kind == "client" {
assert.Contains(s.T(), span.Tags(), name, "custom opentracing.Tags must be included in context")
}
}
}
}
func (s *OpentracingSuite) TestPingList_PropagatesTraces() {
ctx := s.createContextFromFakeHttpRequestParent(s.SimpleCtx())
stream, err := s.Client.PingList(ctx, 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")
}
s.assertTracesCreated("/mwitkow.testproto.TestService/PingList")
}
func (s *OpentracingSuite) TestPingError_PropagatesTraces() {
ctx := s.createContextFromFakeHttpRequestParent(s.SimpleCtx())
erroringPing := &pb_testproto.PingRequest{Value: "something", ErrorCodeReturned: uint32(codes.OutOfRange)}
_, err := s.Client.PingError(ctx, erroringPing)
require.Error(s.T(), err, "there must be an error returned here")
clientSpan, serverSpan := s.assertTracesCreated("/mwitkow.testproto.TestService/PingError")
assert.Equal(s.T(), true, clientSpan.Tag("error"), "client span needs to be marked as an error")
assert.Equal(s.T(), true, serverSpan.Tag("error"), "server span needs to be marked as an error")
}
func (s *OpentracingSuite) TestPingError_WhitelistTraces() {
ctx := s.createContextFromFakeHttpRequestParent(s.SimpleCtx())
erroringPing := &pb_testproto.PingRequest{Value: "something", ErrorCodeReturned: uint32(codes.NotFound)}
_, err := s.Client.PingError(ctx, erroringPing)
require.Error(s.T(), err, "there must be an error returned here")
clientSpan, serverSpan := s.assertTracesCreated("/mwitkow.testproto.TestService/PingError")
assert.Nil(s.T(), clientSpan.Tag("error"), "client span must not be marked as an error")
assert.Nil(s.T(), serverSpan.Tag("error"), "server span must not be marked as an error")
}