Fix: TraceClient crashed in absense of a parentSpan in Context
Added TestTraceClientNoContextSpan to test for this situation
Bas van Beek
7 years ago
35 | 35 |
func TraceClient(tracer opentracing.Tracer, operationName string) endpoint.Middleware {
|
36 | 36 |
return func(next endpoint.Endpoint) endpoint.Endpoint {
|
37 | 37 |
return func(ctx context.Context, request interface{}) (interface{}, error) {
|
38 | |
parentSpan := opentracing.SpanFromContext(ctx)
|
39 | |
clientSpan := tracer.StartSpan(
|
40 | |
operationName,
|
41 | |
opentracing.ChildOf(parentSpan.Context()),
|
42 | |
)
|
|
38 |
var clientSpan opentracing.Span
|
|
39 |
if parentSpan := opentracing.SpanFromContext(ctx); parentSpan != nil {
|
|
40 |
clientSpan = tracer.StartSpan(
|
|
41 |
operationName,
|
|
42 |
opentracing.ChildOf(parentSpan.Context()),
|
|
43 |
)
|
|
44 |
} else {
|
|
45 |
clientSpan = tracer.StartSpan(operationName)
|
|
46 |
}
|
43 | 47 |
defer clientSpan.Finish()
|
44 | 48 |
otext.SpanKind.Set(clientSpan, otext.SpanKindRPCClient)
|
45 | 49 |
ctx = opentracing.ContextWithSpan(ctx, clientSpan)
|
93 | 93 |
t.Errorf("Want ParentID %q, have %q", want, have)
|
94 | 94 |
}
|
95 | 95 |
}
|
|
96 |
|
|
97 |
func TestTraceClientNoContextSpan(t *testing.T) {
|
|
98 |
tracer := mocktracer.New()
|
|
99 |
|
|
100 |
// Empty/background context.
|
|
101 |
tracedEndpoint := kitot.TraceClient(tracer, "testOp")(endpoint.Nop)
|
|
102 |
if _, err := tracedEndpoint(context.Background(), struct{}{}); err != nil {
|
|
103 |
t.Fatal(err)
|
|
104 |
}
|
|
105 |
|
|
106 |
// tracedEndpoint created a new Span.
|
|
107 |
finishedSpans := tracer.GetFinishedSpans()
|
|
108 |
if want, have := 1, len(finishedSpans); want != have {
|
|
109 |
t.Fatalf("Want %v span(s), found %v", want, have)
|
|
110 |
}
|
|
111 |
|
|
112 |
endpointSpan := finishedSpans[0]
|
|
113 |
if want, have := "testOp", endpointSpan.OperationName; want != have {
|
|
114 |
t.Fatalf("Want %q, have %q", want, have)
|
|
115 |
}
|
|
116 |
}
|