Debian Codegraph @

instrumentation/go.mongodb.org/mongo-driver/v2/mongo/otelmongo/mongo_test.go

raw symbols SCIP
1 // Copyright The OpenTelemetry Authors
2 // SPDX-License-Identifier: Apache-2.0
3
4 package otelmongo
5
6 import (
7 "context"
8 "testing"
9 "time"
10
11 "github.com/stretchr/testify/assert"
12 "github.com/stretchr/testify/require"
13 "go.mongodb.org/mongo-driver/v2/bson"
14 "go.mongodb.org/mongo-driver/v2/event"
15 "go.mongodb.org/mongo-driver/v2/mongo"
16 "go.mongodb.org/mongo-driver/v2/mongo/options"
17 "go.mongodb.org/mongo-driver/v2/x/mongo/driver/drivertest"
18 "go.opentelemetry.io/otel/attribute"
19 "go.opentelemetry.io/otel/codes"
20 sdktrace "go.opentelemetry.io/otel/sdk/trace"
21 "go.opentelemetry.io/otel/sdk/trace/tracetest"
22 "go.opentelemetry.io/otel/trace"
23 )
24
25 type validator func(sdktrace.ReadOnlySpan) bool
26
27 func TestWithSpanNameFormatter(t *testing.T) {
28 tt := []struct {
29 title string
30 operation func(context.Context, *mongo.Database) (any, error)
31 expectedSpanName string
32 mockResponses []bson.D
33 SpanNameFormatter SpanNameFormatterFunc
34 }{
35 {
36 title: "insert using default SpanNameFormatter",
37 operation: func(ctx context.Context, db *mongo.Database) (any, error) {
38 return db.Collection("test-collection").InsertOne(ctx, bson.D{{Key: "test-item", Value: "test-value"}})
39 },
40 expectedSpanName: "test-collection.insert",
41 SpanNameFormatter: nil,
42 mockResponses: []bson.D{{{Key: "ok", Value: 1}}},
43 },
44 {
45 title: "delete with custom SpanNameFormatter",
46 operation: func(ctx context.Context, db *mongo.Database) (any, error) {
47 return db.Collection("test-collection").DeleteOne(ctx, bson.D{{Key: "test-item", Value: "test-value"}})
48 },
49 SpanNameFormatter: func(event *event.CommandStartedEvent) string {
50 return "my-" + event.CommandName + "-span"
51 },
52 expectedSpanName: "my-delete-span",
53 mockResponses: []bson.D{{{Key: "ok", Value: 1}}},
54 },
55 }
56 for _, tc := range tt {
57 t.Run(tc.title, func(t *testing.T) {
58 md := drivertest.NewMockDeployment()
59
60 sr := tracetest.NewSpanRecorder()
61 provider := sdktrace.NewTracerProvider(sdktrace.WithSpanProcessor(sr))
62
63 ctx, cancel := context.WithTimeout(t.Context(), time.Second*3)
64 defer cancel()
65
66 ctx, span := provider.Tracer("test").Start(ctx, "mongodb-test")
67 addr := "mongodb://localhost:27017/?connect=direct"
68 opts := options.Client()
69 opts.Deployment = md //nolint:staticcheck // This method is the current documented way to set the mongodb mock. See https://github.com/mongodb/mongo-go-driver/blob/v2.0.0/x/mongo/driver/drivertest/opmsg_deployment_test.go#L24
70 opts.Monitor = NewMonitor(
71 WithTracerProvider(provider),
72 WithSpanNameFormatter(tc.SpanNameFormatter),
73 )
74 opts.ApplyURI(addr)
75
76 md.AddResponses(tc.mockResponses...)
77 client, err := mongo.Connect(opts)
78 defer func() {
79 e := client.Disconnect(t.Context())
80 require.NoError(t, e)
81 }()
82 require.NoError(t, err)
83
84 _, err = tc.operation(ctx, client.Database("test-database"))
85 require.NoError(t, err)
86
87 span.End()
88 spans := sr.Ended()
89
90 s := spans[0]
91 assert.Equal(t, tc.expectedSpanName, s.Name())
92 })
93 }
94 }
95
96 func TestDBCrudOperation(t *testing.T) {
97 commonValidators := []validator{
98 func(s sdktrace.ReadOnlySpan) bool {
99 return assert.Equal(t, "test-collection.insert", s.Name(), "expected %s", s.Name())
100 },
101 func(s sdktrace.ReadOnlySpan) bool {
102 return assert.Contains(t, s.Attributes(), attribute.String("db.operation.name", "insert"))
103 },
104 func(s sdktrace.ReadOnlySpan) bool {
105 return assert.Contains(t, s.Attributes(), attribute.String("db.collection.name", "test-collection"))
106 },
107 func(s sdktrace.ReadOnlySpan) bool {
108 return assert.Equal(t, codes.Unset, s.Status().Code)
109 },
110 }
111
112 tt := []struct {
113 title string
114 operation func(context.Context, *mongo.Database) (any, error)
115 mockResponses []bson.D
116 excludeCommand bool
117 validators []validator
118 }{
119 {
120 title: "insert",
121 operation: func(ctx context.Context, db *mongo.Database) (any, error) {
122 return db.Collection("test-collection").InsertOne(ctx, bson.D{{Key: "test-item", Value: "test-value"}})
123 },
124 mockResponses: []bson.D{{{Key: "ok", Value: 1}}},
125 excludeCommand: false,
126 validators: append(commonValidators, func(s sdktrace.ReadOnlySpan) bool {
127 for _, attr := range s.Attributes() {
128 if attr.Key == "db.query.text" {
129 return assert.Contains(t, attr.Value.AsString(), `"test-item":"test-value"`)
130 }
131 }
132 return false
133 }),
134 },
135 {
136 title: "insert",
137 operation: func(ctx context.Context, db *mongo.Database) (any, error) {
138 return db.Collection("test-collection").InsertOne(ctx, bson.D{{Key: "test-item", Value: "test-value"}})
139 },
140 mockResponses: []bson.D{{{Key: "ok", Value: 1}}},
141 excludeCommand: true,
142 validators: append(commonValidators, func(s sdktrace.ReadOnlySpan) bool {
143 for _, attr := range s.Attributes() {
144 if attr.Key == "db.statement" {
145 return false
146 }
147 }
148 return true
149 }),
150 },
151 }
152 for _, tc := range tt {
153 title := tc.title
154 if tc.excludeCommand {
155 title += "/excludeCommand"
156 } else {
157 title += "/includeCommand"
158 }
159
160 t.Run(title, func(t *testing.T) {
161 md := drivertest.NewMockDeployment()
162
163 sr := tracetest.NewSpanRecorder()
164 provider := sdktrace.NewTracerProvider(sdktrace.WithSpanProcessor(sr))
165
166 ctx, cancel := context.WithTimeout(t.Context(), time.Second*3)
167 defer cancel()
168
169 ctx, span := provider.Tracer("test").Start(ctx, "mongodb-test")
170
171 addr := "mongodb://localhost:27017/?connect=direct"
172 opts := options.Client()
173 opts.Deployment = md //nolint:staticcheck // This method is the current documented way to set the mongodb mock. See https://github.com/mongodb/mongo-go-driver/blob/v2.0.0/x/mongo/driver/drivertest/opmsg_deployment_test.go#L24
174 opts.Monitor = NewMonitor(
175 WithTracerProvider(provider),
176 WithCommandAttributeDisabled(tc.excludeCommand),
177 )
178 opts.ApplyURI(addr)
179
180 md.AddResponses(tc.mockResponses...)
181 client, err := mongo.Connect(opts)
182 defer func() {
183 err := client.Disconnect(t.Context())
184 require.NoError(t, err)
185 }()
186 require.NoError(t, err)
187
188 _, err = tc.operation(ctx, client.Database("test-database"))
189 require.NoError(t, err)
190
191 span.End()
192
193 spans := sr.Ended()
194 require.Len(t, spans, 2, "expected 2 spans, received %d", len(spans))
195 assert.Len(t, spans, 2)
196 assert.Equal(t, spans[0].SpanContext().TraceID(), spans[1].SpanContext().TraceID())
197 assert.Equal(t, spans[0].Parent().SpanID(), spans[1].SpanContext().SpanID())
198 assert.Equal(t, span.SpanContext().SpanID(), spans[1].SpanContext().SpanID())
199
200 s := spans[0]
201 assert.Equal(t, trace.SpanKindClient, s.SpanKind())
202 attrs := s.Attributes()
203 assert.Contains(t, attrs, attribute.String("db.system.name", "mongodb"))
204 assert.Contains(t, attrs, attribute.String("network.peer.address", "<mock_connection>"))
205 assert.Contains(t, attrs, attribute.Int64("network.peer.port", int64(27017)))
206 assert.Contains(t, attrs, attribute.String("network.transport", "tcp"))
207 assert.Contains(t, attrs, attribute.String("db.namespace", "test-database"))
208 for _, v := range tc.validators {
209 assert.True(t, v(s))
210 }
211 })
212 }
213 }
214
215 func TestDBCollectionAttribute(t *testing.T) {
216 tt := []struct {
217 title string
218 operation func(context.Context, *mongo.Database) (any, error)
219 mockResponses []bson.D
220 validators []validator
221 }{
222 {
223 title: "delete",
224 operation: func(ctx context.Context, db *mongo.Database) (any, error) {
225 return db.Collection("test-collection").DeleteOne(ctx, bson.D{{Key: "test-item"}})
226 },
227 mockResponses: []bson.D{{{Key: "ok", Value: 1}}},
228 validators: []validator{
229 func(s sdktrace.ReadOnlySpan) bool {
230 return assert.Equal(t, "test-collection.delete", s.Name())
231 },
232 func(s sdktrace.ReadOnlySpan) bool {
233 return assert.Contains(t, s.Attributes(), attribute.String("db.operation.name", "delete"))
234 },
235 func(s sdktrace.ReadOnlySpan) bool {
236 return assert.Contains(t, s.Attributes(), attribute.String("db.collection.name", "test-collection"))
237 },
238 func(s sdktrace.ReadOnlySpan) bool {
239 return assert.Equal(t, codes.Unset, s.Status().Code)
240 },
241 },
242 },
243 {
244 title: "listCollectionNames",
245 operation: func(ctx context.Context, db *mongo.Database) (any, error) {
246 return db.ListCollectionNames(ctx, bson.D{})
247 },
248 mockResponses: []bson.D{
249 {
250 {Key: "ok", Value: 1},
251 {Key: "cursor", Value: bson.D{{Key: "firstBatch", Value: bson.A{}}}},
252 },
253 },
254 validators: []validator{
255 func(s sdktrace.ReadOnlySpan) bool {
256 return assert.Equal(t, "listCollections", s.Name())
257 },
258 func(s sdktrace.ReadOnlySpan) bool {
259 return assert.Contains(t, s.Attributes(), attribute.String("db.operation.name", "listCollections"))
260 },
261 func(s sdktrace.ReadOnlySpan) bool {
262 return assert.Equal(t, codes.Unset, s.Status().Code)
263 },
264 },
265 },
266 }
267 for _, tc := range tt {
268 t.Run(tc.title, func(t *testing.T) {
269 md := drivertest.NewMockDeployment()
270
271 sr := tracetest.NewSpanRecorder()
272 provider := sdktrace.NewTracerProvider(sdktrace.WithSpanProcessor(sr))
273
274 ctx, cancel := context.WithTimeout(t.Context(), time.Second*3)
275 defer cancel()
276
277 ctx, span := provider.Tracer("test").Start(ctx, "mongodb-test")
278
279 addr := "mongodb://localhost:27017/?connect=direct"
280 opts := options.Client()
281 opts.Deployment = md //nolint:staticcheck // This method is the current documented way to set the mongodb mock. See https://github.com/mongodb/mongo-go-driver/blob/v2.0.0/x/mongo/driver/drivertest/opmsg_deployment_test.go#L24
282 opts.Monitor = NewMonitor(
283 WithTracerProvider(provider),
284 WithCommandAttributeDisabled(true),
285 )
286 opts.ApplyURI(addr)
287
288 md.AddResponses(tc.mockResponses...)
289 client, err := mongo.Connect(opts)
290 require.NoError(t, err)
291
292 defer func() {
293 err := client.Disconnect(t.Context())
294 require.NoError(t, err)
295 }()
296
297 _, err = tc.operation(ctx, client.Database("test-database"))
298 require.NoError(t, err)
299
300 span.End()
301
302 spans := sr.Ended()
303 require.Len(t, spans, 2, "expected 2 spans, received %d", len(spans))
304 assert.Len(t, spans, 2)
305 assert.Equal(t, spans[0].SpanContext().TraceID(), spans[1].SpanContext().TraceID())
306 assert.Equal(t, spans[0].Parent().SpanID(), spans[1].SpanContext().SpanID())
307 assert.Equal(t, span.SpanContext().SpanID(), spans[1].SpanContext().SpanID())
308
309 s := spans[0]
310 assert.Equal(t, trace.SpanKindClient, s.SpanKind())
311 attrs := s.Attributes()
312 assert.Contains(t, attrs, attribute.String("db.system.name", "mongodb"))
313 assert.Contains(t, attrs, attribute.String("network.peer.address", "<mock_connection>"))
314 assert.Contains(t, attrs, attribute.Int64("network.peer.port", int64(27017)))
315 assert.Contains(t, attrs, attribute.String("network.transport", "tcp"))
316 assert.Contains(t, attrs, attribute.String("db.namespace", "test-database"))
317 for _, v := range tc.validators {
318 assert.True(t, v(s))
319 }
320 })
321 }
322 }
323
324 func TestPeerInfo(t *testing.T) {
325 tests := []struct {
326 name string
327 connectionID string
328 expectedHost string
329 expectedPort int
330 }{
331 {
332 name: "IPv4 with port",
333 connectionID: "127.0.0.1:27018",
334 expectedHost: "127.0.0.1",
335 expectedPort: 27018,
336 },
337 {
338 name: "IPv4 without port",
339 connectionID: "127.0.0.1",
340 expectedHost: "127.0.0.1",
341 expectedPort: 27017,
342 },
343 {
344 name: "IPv6 with port",
345 connectionID: "[::1]:27019",
346 expectedHost: "::1",
347 expectedPort: 27019,
348 },
349 {
350 name: "IPv6 without port with square brackets",
351 connectionID: "[::1]",
352 expectedHost: "[::1]",
353 expectedPort: 27017,
354 },
355 {
356 name: "IPv6 without port",
357 connectionID: "::1",
358 expectedHost: "::1",
359 expectedPort: 27017,
360 },
361 {
362 name: "Hostname with port",
363 connectionID: "example.com:27020",
364 expectedHost: "example.com",
365 expectedPort: 27020,
366 },
367 {
368 name: "Hostname without port",
369 connectionID: "example.com",
370 expectedHost: "example.com",
371 expectedPort: 27017,
372 },
373 }
374
375 for _, tc := range tests {
376 t.Run(tc.name, func(t *testing.T) {
377 t.Parallel()
378
379 host, port := peerInfo(tc.connectionID)
380 assert.Equal(t, tc.expectedHost, host)
381 assert.Equal(t, tc.expectedPort, port)
382 })
383 }
384 }