-
Notifications
You must be signed in to change notification settings - Fork 415
/
mocktracer.go
253 lines (219 loc) · 6.42 KB
/
mocktracer.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
// Unless explicitly stated otherwise all files in this repository are licensed
// under the Apache License Version 2.0.
// This product includes software developed at Datadog (https://www.datadoghq.com/).
// Copyright 2016 Datadog, Inc.
// Package mocktracer provides a mock implementation of the tracer used in testing. It
// allows querying spans generated at runtime, without having them actually be sent to
// an agent. It provides a simple way to test that instrumentation is running correctly
// in your application.
//
// Simply call "Start" at the beginning of your tests to start and obtain an instance
// of the mock tracer.
package mocktracer
import (
"strconv"
"strings"
"sync"
"gopkg.in/DataDog/dd-trace-go.v1/ddtrace"
"gopkg.in/DataDog/dd-trace-go.v1/ddtrace/internal"
"gopkg.in/DataDog/dd-trace-go.v1/ddtrace/tracer"
)
var _ ddtrace.Tracer = (*mocktracer)(nil)
var _ Tracer = (*mocktracer)(nil)
// Tracer exposes an interface for querying the currently running mock tracer.
type Tracer interface {
// OpenSpans returns the set of started spans that have not been finished yet.
OpenSpans() []Span
// FinishedSpans returns the set of finished spans.
FinishedSpans() []Span
// InjectedComments returns the set of sql comments injected on queries.
InjectedComments() []string
// Reset resets the spans and services recorded in the tracer. This is
// especially useful when running tests in a loop, where a clean start
// is desired for FinishedSpans calls.
Reset()
// Stop deactivates the mock tracer and allows a normal tracer to take over.
// It should always be called when testing has finished.
Stop()
}
// Start sets the internal tracer to a mock and returns an interface
// which allows querying it. Call Start at the beginning of your tests
// to activate the mock tracer. When your test runs, use the returned
// interface to query the tracer's state.
func Start() Tracer {
t := newMockTracer()
internal.SetGlobalTracer(t)
internal.Testing = true
return t
}
type mocktracer struct {
sync.RWMutex // guards below spans
finishedSpans []Span
injectedComments []string
openSpans map[uint64]Span
}
func newMockTracer() *mocktracer {
var t mocktracer
t.openSpans = make(map[uint64]Span)
return &t
}
// Stop deactivates the mock tracer and sets the active tracer to a no-op.
func (*mocktracer) Stop() {
internal.SetGlobalTracer(&internal.NoopTracer{})
internal.Testing = false
}
func (t *mocktracer) StartSpan(operationName string, opts ...ddtrace.StartSpanOption) ddtrace.Span {
var cfg ddtrace.StartSpanConfig
for _, fn := range opts {
fn(&cfg)
}
span := newSpan(t, operationName, &cfg)
t.Lock()
t.openSpans[span.SpanID()] = span
t.Unlock()
return span
}
func (t *mocktracer) OpenSpans() []Span {
t.RLock()
defer t.RUnlock()
spans := make([]Span, 0, len(t.openSpans))
for _, s := range t.openSpans {
spans = append(spans, s)
}
return spans
}
func (t *mocktracer) FinishedSpans() []Span {
t.RLock()
defer t.RUnlock()
return t.finishedSpans
}
func (t *mocktracer) InjectedComments() []string {
t.RLock()
defer t.RUnlock()
return t.injectedComments
}
func (t *mocktracer) Reset() {
t.Lock()
defer t.Unlock()
for k := range t.openSpans {
delete(t.openSpans, k)
}
t.injectedComments = nil
t.finishedSpans = nil
}
func (t *mocktracer) addFinishedSpan(s Span) {
t.Lock()
defer t.Unlock()
delete(t.openSpans, s.SpanID())
if t.finishedSpans == nil {
t.finishedSpans = make([]Span, 0, 1)
}
t.finishedSpans = append(t.finishedSpans, s)
}
const (
traceHeader = tracer.DefaultTraceIDHeader
spanHeader = tracer.DefaultParentIDHeader
priorityHeader = tracer.DefaultPriorityHeader
baggagePrefix = tracer.DefaultBaggageHeaderPrefix
)
func (t *mocktracer) Extract(carrier interface{}) (ddtrace.SpanContext, error) {
reader, ok := carrier.(tracer.TextMapReader)
if !ok {
return nil, tracer.ErrInvalidCarrier
}
var sc spanContext
err := reader.ForeachKey(func(key, v string) error {
k := strings.ToLower(key)
if k == traceHeader {
id, err := strconv.ParseUint(v, 10, 64)
if err != nil {
return tracer.ErrSpanContextCorrupted
}
sc.traceID = id
}
if k == spanHeader {
id, err := strconv.ParseUint(v, 10, 64)
if err != nil {
return tracer.ErrSpanContextCorrupted
}
sc.spanID = id
}
if k == priorityHeader {
p, err := strconv.Atoi(v)
if err != nil {
return tracer.ErrSpanContextCorrupted
}
sc.priority = p
sc.hasPriority = true
}
if strings.HasPrefix(k, baggagePrefix) {
sc.setBaggageItem(strings.TrimPrefix(k, baggagePrefix), v)
}
return nil
})
if err != nil {
return nil, err
}
if sc.traceID == 0 || sc.spanID == 0 {
return nil, tracer.ErrSpanContextNotFound
}
return &sc, err
}
func (t *mocktracer) Inject(context ddtrace.SpanContext, carrier interface{}) error {
writer, ok := carrier.(tracer.TextMapWriter)
if !ok {
return tracer.ErrInvalidCarrier
}
ctx, ok := context.(*spanContext)
if !ok || ctx.traceID == 0 || ctx.spanID == 0 {
return tracer.ErrInvalidSpanContext
}
writer.Set(traceHeader, strconv.FormatUint(ctx.traceID, 10))
writer.Set(spanHeader, strconv.FormatUint(ctx.spanID, 10))
if ctx.hasSamplingPriority() {
writer.Set(priorityHeader, strconv.Itoa(ctx.priority))
}
ctx.ForeachBaggageItem(func(k, v string) bool {
writer.Set(baggagePrefix+k, v)
return true
})
return nil
}
func (t *mocktracer) InjectWithOptions(context ddtrace.SpanContext, carrier interface{}, opts ...tracer.InjectionOption) error {
writer, ok := carrier.(tracer.TextMapWriter)
if !ok {
return tracer.ErrInvalidCarrier
}
ctx, ok := context.(*spanContext)
if !ok || ctx.traceID == 0 || ctx.spanID == 0 {
return tracer.ErrInvalidSpanContext
}
cfg := ddtrace.InjectionConfig{}
for _, apply := range opts {
apply(&cfg)
}
if cfg.TraceIDKey != "" {
writer.Set(cfg.TraceIDKey, "test-trace-id")
}
if cfg.SpanIDKey != "" {
writer.Set(cfg.SpanIDKey, "test-span-id")
}
if cfg.SamplingPriorityKey != "" {
writer.Set(cfg.SamplingPriorityKey, strconv.Itoa(ctx.priority))
}
if cfg.EnvKey != "" {
writer.Set(cfg.EnvKey, "test-env")
}
if cfg.ParentVersionKey != "" {
writer.Set(cfg.ParentVersionKey, "v-test")
}
if cfg.ServiceNameKey != "" {
writer.Set(cfg.ServiceNameKey, "test-service")
}
sqlCommentCarrier, ok := carrier.(*tracer.SQLCommentCarrier)
if ok {
// Save injected comments to assert the sql commenting behavior
t.injectedComments = append(t.injectedComments, sqlCommentCarrier.CommentedQuery(""))
}
return nil
}