Debian Codegraph @

exporters/stdout/stdoutmetric/internal/observ/instrumentation_test.go

raw
1 // Copyright The OpenTelemetry Authors
2 // SPDX-License-Identifier: Apache-2.0
3
4 package observ_test
5
6 import (
7 "errors"
8 "testing"
9
10 "github.com/stretchr/testify/assert"
11 "github.com/stretchr/testify/require"
12
13 "go.opentelemetry.io/otel"
14 "go.opentelemetry.io/otel/attribute"
15 "go.opentelemetry.io/otel/exporters/stdout/stdoutmetric/internal/observ"
16 "go.opentelemetry.io/otel/metric/noop"
17 "go.opentelemetry.io/otel/sdk/instrumentation"
18 sdkmetric "go.opentelemetry.io/otel/sdk/metric"
19 "go.opentelemetry.io/otel/sdk/metric/metricdata"
20 "go.opentelemetry.io/otel/sdk/metric/metricdata/metricdatatest"
21 semconv "go.opentelemetry.io/otel/semconv/v1.40.0"
22 "go.opentelemetry.io/otel/semconv/v1.40.0/otelconv"
23 )
24
25 type testSetup struct {
26 reader *sdkmetric.ManualReader
27 em *observ.Instrumentation
28 }
29
30 func setupTestMeterProvider(t *testing.T) *testSetup {
31 t.Helper()
32 t.Setenv("OTEL_GO_X_OBSERVABILITY", "true")
33
34 // drop metric reader metrics as we are only testing for stdoutmetric exporter
35 dropReaderMetrics := sdkmetric.NewView(
36 sdkmetric.Instrument{
37 Scope: instrumentation.Scope{Name: "go.opentelemetry.io/otel/sdk/metric/internal/observ"},
38 },
39 sdkmetric.Stream{Aggregation: sdkmetric.AggregationDrop{}},
40 )
41
42 reader := sdkmetric.NewManualReader()
43 mp := sdkmetric.NewMeterProvider(
44 sdkmetric.WithReader(reader),
45 sdkmetric.WithView(dropReaderMetrics),
46 )
47
48 originalMP := otel.GetMeterProvider()
49 otel.SetMeterProvider(mp)
50 t.Cleanup(func() { otel.SetMeterProvider(originalMP) })
51
52 em, err := observ.NewInstrumentation(0)
53 assert.NoError(t, err)
54
55 return &testSetup{
56 reader: reader,
57 em: em,
58 }
59 }
60
61 func collectMetrics(t *testing.T, setup *testSetup) metricdata.ResourceMetrics {
62 var rm metricdata.ResourceMetrics
63 err := setup.reader.Collect(t.Context(), &rm)
64 assert.NoError(t, err)
65 return rm
66 }
67
68 const exporterComponentID = 0
69
70 var errExport = errors.New("export failed")
71
72 func exporterSet(attrs ...attribute.KeyValue) attribute.Set {
73 return attribute.NewSet(append([]attribute.KeyValue{
74 observ.ExporterComponentName(exporterComponentID),
75 semconv.OTelComponentTypeKey.String(observ.ComponentType),
76 }, attrs...)...)
77 }
78
79 func dPt(set attribute.Set, value int64) metricdata.DataPoint[int64] {
80 return metricdata.DataPoint[int64]{Attributes: set, Value: value}
81 }
82
83 func exported(dPts ...metricdata.DataPoint[int64]) metricdata.Metrics {
84 return metricdata.Metrics{
85 Name: otelconv.SDKExporterMetricDataPointExported{}.Name(),
86 Description: otelconv.SDKExporterMetricDataPointExported{}.Description(),
87 Unit: otelconv.SDKExporterMetricDataPointExported{}.Unit(),
88 Data: metricdata.Sum[int64]{
89 Temporality: metricdata.CumulativeTemporality,
90 IsMonotonic: true,
91 DataPoints: dPts,
92 },
93 }
94 }
95
96 func inflight(dPts ...metricdata.DataPoint[int64]) metricdata.Metrics {
97 return metricdata.Metrics{
98 Name: otelconv.SDKExporterMetricDataPointInflight{}.Name(),
99 Description: otelconv.SDKExporterMetricDataPointInflight{}.Description(),
100 Unit: otelconv.SDKExporterMetricDataPointInflight{}.Unit(),
101 Data: metricdata.Sum[int64]{
102 Temporality: metricdata.CumulativeTemporality,
103 IsMonotonic: false,
104 DataPoints: dPts,
105 },
106 }
107 }
108
109 func duration(dPts ...metricdata.HistogramDataPoint[float64]) metricdata.Metrics {
110 return metricdata.Metrics{
111 Name: otelconv.SDKExporterOperationDuration{}.Name(),
112 Description: otelconv.SDKExporterOperationDuration{}.Description(),
113 Unit: otelconv.SDKExporterOperationDuration{}.Unit(),
114 Data: metricdata.Histogram[float64]{
115 Temporality: metricdata.CumulativeTemporality,
116 DataPoints: dPts,
117 },
118 }
119 }
120
121 func histDPt(set attribute.Set) metricdata.HistogramDataPoint[float64] {
122 return metricdata.HistogramDataPoint[float64]{
123 Attributes: set,
124 }
125 }
126
127 func checkMetrics(
128 t *testing.T,
129 rm metricdata.ResourceMetrics,
130 wantInflight, wantExported, wantDuration metricdata.Metrics,
131 ) {
132 t.Helper()
133 require.Len(t, rm.ScopeMetrics, 1)
134
135 m := rm.ScopeMetrics[0].Metrics
136 require.Len(t, m, 3)
137
138 opts := metricdatatest.IgnoreTimestamp()
139
140 metricdatatest.AssertEqual(t, wantInflight, m[0], opts)
141 metricdatatest.AssertEqual(t, wantExported, m[1], opts)
142 // ignoring values for histogram since duration is not deterministic
143 metricdatatest.AssertEqual(t, wantDuration, m[2], opts, metricdatatest.IgnoreValue())
144 }
145
146 func checkInflight(t *testing.T, rm metricdata.ResourceMetrics, wantInflight metricdata.Metrics) {
147 t.Helper()
148 require.Len(t, rm.ScopeMetrics, 1)
149
150 m := rm.ScopeMetrics[0].Metrics
151 require.NotEmpty(t, m)
152
153 inflightName := otelconv.SDKExporterMetricDataPointInflight{}.Name()
154 var inflightMetric metricdata.Metrics
155 found := false
156 for _, metric := range m {
157 if metric.Name == inflightName {
158 inflightMetric = metric
159 found = true
160 break
161 }
162 }
163 require.True(t, found)
164 metricdatatest.AssertEqual(t, wantInflight, inflightMetric, metricdatatest.IgnoreTimestamp())
165 }
166
167 func TestInstrumentationExportMetrics(t *testing.T) {
168 setup := setupTestMeterProvider(t)
169
170 ctx := t.Context()
171 op1 := setup.em.ExportMetrics(ctx, 2)
172 op2 := setup.em.ExportMetrics(ctx, 3)
173 op3 := setup.em.ExportMetrics(ctx, 1)
174 totalMetrics := int64(6)
175 checkInflight(t, collectMetrics(t, setup), inflight(dPt(exporterSet(), totalMetrics)))
176
177 op2.End(nil)
178 op1.End(errExport)
179 op3.End(nil)
180
181 successExported := int64(4)
182 erroredExported := int64(2)
183 checkMetrics(
184 t,
185 collectMetrics(t, setup),
186 inflight(dPt(exporterSet(), 0)),
187 exported(
188 dPt(exporterSet(), successExported),
189 dPt(exporterSet(semconv.ErrorType(errExport)), erroredExported),
190 ),
191 duration(
192 histDPt(exporterSet()),
193 histDPt(exporterSet(semconv.ErrorType(errExport))),
194 ),
195 )
196 }
197
198 func BenchmarkExportMetrics(b *testing.B) {
199 b.Setenv("OTEL_GO_X_OBSERVABILITY", "true")
200 orig := otel.GetMeterProvider()
201 b.Cleanup(func() {
202 otel.SetMeterProvider(orig)
203 })
204
205 // Ensure deterministic benchmark by using noop meter.
206 otel.SetMeterProvider(noop.NewMeterProvider())
207
208 newExp := func(b *testing.B) *observ.Instrumentation {
209 b.Helper()
210 em, err := observ.NewInstrumentation(0)
211 require.NoError(b, err)
212 require.NotNil(b, em)
213 return em
214 }
215
216 b.Run("NoError", func(b *testing.B) {
217 em := newExp(b)
218 b.ResetTimer()
219 b.ReportAllocs()
220 for b.Loop() {
221 op := em.ExportMetrics(b.Context(), 10)
222 op.End(nil)
223 }
224 })
225
226 b.Run("WithError", func(b *testing.B) {
227 em := newExp(b)
228 b.ResetTimer()
229 b.ReportAllocs()
230 for b.Loop() {
231 op := em.ExportMetrics(b.Context(), 10)
232 op.End(errExport)
233 }
234 })
235 }