Debian Codegraph @

internal/testing/oteltest/diff.go

raw
1 // Copyright 2019-2025 The Go Cloud Development Kit Authors
2 //
3 // Licensed under the Apache License, Version 2.0 (the "License");
4 // you may not use this file except in compliance with the License.
5 // You may obtain a copy of the License at
6 //
7 // https://www.apache.org/licenses/LICENSE-2.0
8 //
9 // Unless required by applicable law or agreed to in writing, software
10 // distributed under the License is distributed on an "AS IS" BASIS,
11 // WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
12 // See the License for the specific language governing permissions and
13 // limitations under the License.
14
15 package oteltest
16
17 import (
18 "fmt"
19 "go.opentelemetry.io/otel/codes"
20 "sort"
21 "strings"
22
23 "go.opentelemetry.io/otel/attribute"
24 "go.opentelemetry.io/otel/sdk/metric/metricdata"
25 sdktrace "go.opentelemetry.io/otel/sdk/trace"
26 "gocloud.dev/gcerrors"
27 )
28
29 var (
30 methodKey = attribute.Key("gocdk_method")
31 providerKey = attribute.Key("gocdk_provider")
32 statusKey = attribute.Key("gocdk_status")
33 )
34
35 // Call represents a method call/span with its result code.
36 type Call struct {
37 Method string
38 Code gcerrors.ErrorCode
39 Attrs []attribute.KeyValue
40 }
41
42 func formatSpanData(s sdktrace.ReadOnlySpan) string {
43 if s == nil {
44 return "missing"
45 }
46 // OTel uses codes.Code for status.
47 return fmt.Sprintf("<Name: %q, Code: %s>", s.Name(), s.Status().Code.String())
48 }
49
50 func formatCall(c *Call) string {
51 if c == nil {
52 return "nothing"
53 }
54 // gcerrors.ErrorCode is an int, just print it.
55 return fmt.Sprintf("<Name: %q, Code: %d>", c.Method, c.Code)
56 }
57
58 // Diff compares the list of spans and metric data obtained from OpenTelemetry
59 // instrumentation (using a test exporter like `sdktrace/tracetest.NewExporter`
60 // and `sdkmetric/metrictest.NewExporter`) with an expected list of calls.
61 // The span/metric name and status code/status attribute are compared.
62 // Order matters for traces (though not for metrics).
63 //
64 // gotSpans should be the result from a test trace exporter (e.g., exporter.GetSpans()).
65 // gotMetrics should be the result from a test metric exporter (e.g., exporter.GetMetrics()).
66 // namePrefix is the prefix prepended to method names in spans/metrics mostly its the package name.
67 // provider is the name of the provider used (e.g., "aws").
68 // want is the list of expected calls.
69 func Diff(gotSpans []sdktrace.ReadOnlySpan, gotMetrics []metricdata.ScopeMetrics, namePrefix, provider string, want []Call) string {
70 ds := diffSpans(gotSpans, namePrefix, want)
71 dc := DiffMetrics(gotMetrics, namePrefix, provider, want)
72 if len(ds) > 0 {
73 ds = "trace: " + ds + "\n"
74 }
75 if len(dc) > 0 {
76 dc = "metrics: " + dc
77 }
78 return ds + dc
79 }
80
81 func mapStatusCode(code gcerrors.ErrorCode) codes.Code {
82 // For gcerrors used by gocloud, OK -> Ok, everything else -> Error is common.
83 if code == gcerrors.OK {
84 return codes.Ok
85 }
86 return codes.Error
87 }
88
89 func diffSpans(got []sdktrace.ReadOnlySpan, prefix string, want []Call) string {
90 var diffs []string
91 add := func(i int, g sdktrace.ReadOnlySpan, w *Call) {
92 diffs = append(diffs, fmt.Sprintf("#%d: got %s, want %s", i, formatSpanData(g), formatCall(w)))
93 }
94
95 for i := 0; i < len(got) || i < len(want); i++ {
96 var gotSpan sdktrace.ReadOnlySpan
97 if i < len(got) {
98 gotSpan = got[i]
99 }
100
101 switch {
102 case i >= len(got):
103 add(i, nil, &want[i])
104 case i >= len(want):
105 add(i, gotSpan, nil)
106 default:
107 expectedName := prefix + "." + want[i].Method
108 expectedCode := mapStatusCode(want[i].Code) // Map wanted gcerrors code to OTel code.
109
110 if gotSpan == nil || gotSpan.Name() != expectedName || gotSpan.Status().Code != expectedCode {
111 w := want[i]
112 w.Method = prefix + "." + w.Method
113 add(i, gotSpan, &w)
114 }
115 }
116 }
117 return strings.Join(diffs, "\n")
118 }
119
120 func DiffMetrics(got []metricdata.ScopeMetrics, prefix, provider string, wantCalls []Call) string {
121 // OTel metric data is structured. We need to iterate through it to find the
122 // relevant metric data points and their attributes.
123 var diffs []string
124 gotTags := map[string]bool{} // map of canonicalized data point attributes
125
126 // Helper to convert attribute.Set to a canonical string key
127 attrSetToCanonicalString := func(set attribute.Set) string {
128 // Get key-value pairs, sort them, and format into a stable string.
129 attrs := make([]attribute.KeyValue, 0, set.Len())
130 iter := set.Iter()
131 for iter.Next() {
132 attrs = append(attrs, iter.Attribute())
133 }
134 sort.Slice(attrs, func(i, j int) bool {
135 return string(attrs[i].Key) < string(attrs[j].Key)
136 })
137 parts := make([]string, len(attrs))
138 for i, attr := range attrs {
139 // Format value based on type - attribute.Value doesn't have a simple String()
140 // that's guaranteed to be consistent for comparison. Using fmt.Sprint is safer.
141 parts[i] = fmt.Sprintf("%s:%s", attr.Key, fmt.Sprint(attr.Value.AsInterface()))
142 }
143 return strings.Join(parts, ",")
144 }
145
146 // Helper function to collect relevant attributes for tag comparison.
147 processAtrributes := func(attrSets ...attribute.Set) {
148
149 var requiredAttributes []attribute.KeyValue
150 for _, attrSet := range attrSets {
151 for _, a := range attrSet.ToSlice() {
152 if a.Key == providerKey {
153 requiredAttributes = append(requiredAttributes, a)
154 }
155
156 if a.Key == methodKey {
157 requiredAttributes = append(requiredAttributes, a)
158 }
159
160 if a.Key == statusKey {
161 requiredAttributes = append(requiredAttributes, a)
162 }
163 }
164 }
165
166 if len(requiredAttributes) > 0 {
167 gotTags[attrSetToCanonicalString(attribute.NewSet(requiredAttributes...))] = true
168 }
169
170 }
171
172 // Iterate through all collected metrics to find relevant data points.
173 for _, sm := range got {
174
175 for _, m := range sm.Metrics {
176
177 // Using a switch will allow us accommodate other types of metrics.
178 switch v := m.Data.(type) {
179 case metricdata.Sum[int64]:
180 // Handle int64 Sum metrics.
181 for _, dp := range v.DataPoints {
182 processAtrributes(sm.Scope.Attributes, dp.Attributes)
183 }
184 case metricdata.Sum[float64]:
185 // gocloud usually records counts. Check for Sum metrics.
186 for _, dp := range v.DataPoints {
187 processAtrributes(sm.Scope.Attributes, dp.Attributes)
188 }
189 default:
190 // Handle any other types of metrics.
191 processAtrributes(sm.Scope.Attributes)
192 }
193 }
194 }
195
196 // Check that each wanted call has a corresponding metric data point with the correct attributes.
197 for _, wc := range wantCalls {
198 // Construct the expected set of attributes for the wanted call.
199 expectedAttributes := []attribute.KeyValue{providerKey.String(provider)}
200
201 if wc.Method != "" {
202 expectedAttributes = append(expectedAttributes,
203 methodKey.String(prefix+"."+wc.Method),
204 statusKey.String(fmt.Sprint(wc.Code)))
205 }
206
207 // Canonicalize the expected attributes to check against the collected ones.
208 expectedKey := attrSetToCanonicalString(attribute.NewSet(expectedAttributes...))
209
210 if !gotTags[expectedKey] {
211 diffs = append(diffs, fmt.Sprintf("missing metric data point with attributes %q", expectedKey))
212 }
213 }
214 return strings.Join(diffs, "\n")
215 }