Debian Codegraph @

instrumentation/go.mongodb.org/mongo-driver/v2/mongo/otelmongo/metrics_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/mongo"
15 "go.mongodb.org/mongo-driver/v2/mongo/options"
16 "go.mongodb.org/mongo-driver/v2/x/mongo/driver/drivertest"
17 "go.opentelemetry.io/otel/sdk/metric"
18 "go.opentelemetry.io/otel/sdk/metric/metricdata"
19 )
20
21 const (
22 testAddr = "mongodb://localhost:27017/?connect=direct"
23 )
24
25 func TestMetricsOperationDuration(t *testing.T) {
26 reader := metric.NewManualReader()
27 provider := metric.NewMeterProvider(metric.WithReader(reader))
28
29 md := drivertest.NewMockDeployment()
30
31 ctx, cancel := context.WithTimeout(t.Context(), time.Second*3)
32 defer cancel()
33
34 opts := options.Client()
35 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
36 opts.Monitor = NewMonitor(
37 WithMeterProvider(provider),
38 WithCommandAttributeDisabled(false),
39 )
40 opts.ApplyURI(testAddr)
41
42 md.AddResponses([]bson.D{{{Key: "ok", Value: 1}}}...)
43 client, err := mongo.Connect(opts)
44 require.NoError(t, err)
45 defer func() {
46 err := client.Disconnect(t.Context())
47 require.NoError(t, err)
48 }()
49
50 // Perform an insert operation
51 _, err = client.Database("test-database").Collection("test-collection").InsertOne(ctx, bson.D{{Key: "test-item", Value: "test-value"}})
52 require.NoError(t, err)
53
54 // Collect metrics
55 var rm metricdata.ResourceMetrics
56 err = reader.Collect(ctx, &rm)
57 require.NoError(t, err)
58
59 // Verify metrics were recorded
60 require.Len(t, rm.ScopeMetrics, 1)
61 scopeMetrics := rm.ScopeMetrics[0]
62 assert.Equal(t, ScopeName, scopeMetrics.Scope.Name)
63
64 // Find the operation duration metric
65 var foundDuration bool
66 for _, m := range scopeMetrics.Metrics {
67 if m.Name != "db.client.operation.duration" {
68 continue
69 }
70 foundDuration = true
71 histogram, ok := m.Data.(metricdata.Histogram[float64])
72 assert.True(t, ok, "expected histogram data type")
73 assert.NotEmpty(t, histogram.DataPoints)
74
75 // Check that attributes are present
76 dp := histogram.DataPoints[0]
77 attrs := dp.Attributes.ToSlice()
78 hasDBSystem := false
79 hasOperation := false
80 for _, attr := range attrs {
81 if attr.Key == "db.system.name" && attr.Value.AsString() == "mongodb" {
82 hasDBSystem = true
83 }
84 if attr.Key == "db.operation.name" && attr.Value.AsString() == "insert" {
85 hasOperation = true
86 }
87 }
88 assert.True(t, hasDBSystem, "expected db.system.name attribute")
89 assert.True(t, hasOperation, "expected db.operation.name attribute")
90 }
91 assert.True(t, foundDuration, "expected db.client.operation.duration metric")
92 }
93
94 func TestMetricsOperationFailure(t *testing.T) {
95 reader := metric.NewManualReader()
96 provider := metric.NewMeterProvider(metric.WithReader(reader))
97
98 md := drivertest.NewMockDeployment()
99
100 ctx, cancel := context.WithTimeout(t.Context(), time.Second*3)
101 defer cancel()
102
103 opts := options.Client()
104 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
105 opts.Monitor = NewMonitor(
106 WithMeterProvider(provider),
107 WithCommandAttributeDisabled(true),
108 )
109 opts.ApplyURI(testAddr)
110
111 // Simulate an error response
112 md.AddResponses([]bson.D{{{Key: "ok", Value: 0}, {Key: "errmsg", Value: "test error"}}}...)
113 client, err := mongo.Connect(opts)
114 require.NoError(t, err)
115 defer func() {
116 err := client.Disconnect(t.Context())
117 require.NoError(t, err)
118 }()
119
120 _, err = client.Database("test-database").Collection("test-collection").InsertOne(ctx, bson.D{{Key: "test-item", Value: "test-value"}})
121 require.Error(t, err)
122
123 // Collect metrics
124 var rm metricdata.ResourceMetrics
125 err = reader.Collect(ctx, &rm)
126 require.NoError(t, err)
127
128 // Verify metrics were recorded even for failed operations
129 require.Len(t, rm.ScopeMetrics, 1)
130 scopeMetrics := rm.ScopeMetrics[0]
131 assert.NotEmpty(t, scopeMetrics.Metrics)
132 }
133
134 func TestNewMonitorWithInvalidMeterProvider(t *testing.T) {
135 // This test verifies that NewMonitor handles errors gracefully
136 // even if metric creation fails. The function should not panic
137 // and should return a valid monitor that can be used.
138
139 // Using a nil meter provider will use the global one, which should work
140 monitor := NewMonitor()
141 assert.NotNil(t, monitor)
142 assert.NotNil(t, monitor.Started)
143 assert.NotNil(t, monitor.Succeeded)
144 assert.NotNil(t, monitor.Failed)
145 }