Debian Codegraph @

instrumentation/github.com/labstack/echo/otelecho/echo_test.go

raw
1 // Copyright The OpenTelemetry Authors
2 // SPDX-License-Identifier: Apache-2.0
3
4 // Based on https://github.com/DataDog/dd-trace-go/blob/8fb554ff7cf694267f9077ae35e27ce4689ed8b6/contrib/gin-gonic/gin/gintrace_test.go
5
6 package otelecho
7
8 import (
9 "fmt"
10 "net/http"
11 "net/http/httptest"
12 "strings"
13 "testing"
14
15 "github.com/labstack/echo/v4"
16 "github.com/stretchr/testify/assert"
17 "github.com/stretchr/testify/require"
18 "go.opentelemetry.io/otel"
19 "go.opentelemetry.io/otel/attribute"
20 "go.opentelemetry.io/otel/propagation"
21 "go.opentelemetry.io/otel/trace"
22 "go.opentelemetry.io/otel/trace/noop"
23
24 b3prop "go.opentelemetry.io/contrib/propagators/b3"
25
26 sdkmetric "go.opentelemetry.io/otel/sdk/metric"
27 "go.opentelemetry.io/otel/sdk/metric/metricdata"
28 "go.opentelemetry.io/otel/sdk/metric/metricdata/metricdatatest"
29 )
30
31 func TestGetSpanNotInstrumented(t *testing.T) {
32 router := echo.New()
33 router.GET("/ping", func(c echo.Context) error {
34 // Assert we don't have a span on the context.
35 span := trace.SpanFromContext(c.Request().Context())
36 ok := !span.SpanContext().IsValid()
37 assert.True(t, ok)
38 return c.String(http.StatusOK, "ok")
39 })
40 r := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/ping", http.NoBody)
41 w := httptest.NewRecorder()
42 router.ServeHTTP(w, r)
43 response := w.Result()
44 assert.Equal(t, http.StatusOK, response.StatusCode)
45 }
46
47 func TestPropagationWithGlobalPropagators(t *testing.T) {
48 provider := noop.NewTracerProvider()
49 otel.SetTextMapPropagator(propagation.TraceContext{})
50
51 r := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/user/123", http.NoBody)
52 w := httptest.NewRecorder()
53
54 ctx := t.Context()
55 sc := trace.NewSpanContext(trace.SpanContextConfig{
56 TraceID: trace.TraceID{0x01},
57 SpanID: trace.SpanID{0x01},
58 })
59 ctx = trace.ContextWithRemoteSpanContext(ctx, sc)
60 ctx, _ = provider.Tracer(ScopeName).Start(ctx, "test")
61 otel.GetTextMapPropagator().Inject(ctx, propagation.HeaderCarrier(r.Header))
62
63 router := echo.New()
64 router.Use(Middleware("foobar", WithTracerProvider(provider)))
65 router.GET("/user/:id", func(c echo.Context) error {
66 span := trace.SpanFromContext(c.Request().Context())
67 assert.Equal(t, sc.TraceID(), span.SpanContext().TraceID())
68 assert.Equal(t, sc.SpanID(), span.SpanContext().SpanID())
69 return c.NoContent(http.StatusOK)
70 })
71
72 router.ServeHTTP(w, r)
73 otel.SetTextMapPropagator(propagation.NewCompositeTextMapPropagator())
74 assert.Equal(t, http.StatusOK, w.Result().StatusCode, "should call the 'user' handler")
75 }
76
77 func TestPropagationWithCustomPropagators(t *testing.T) {
78 provider := noop.NewTracerProvider()
79
80 b3 := b3prop.New()
81
82 r := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/user/123", http.NoBody)
83 w := httptest.NewRecorder()
84
85 ctx := t.Context()
86 sc := trace.NewSpanContext(trace.SpanContextConfig{
87 TraceID: trace.TraceID{0x01},
88 SpanID: trace.SpanID{0x01},
89 })
90 ctx = trace.ContextWithRemoteSpanContext(ctx, sc)
91 ctx, _ = provider.Tracer(ScopeName).Start(ctx, "test")
92 b3.Inject(ctx, propagation.HeaderCarrier(r.Header))
93
94 router := echo.New()
95 router.Use(Middleware("foobar", WithTracerProvider(provider), WithPropagators(b3)))
96 router.GET("/user/:id", func(c echo.Context) error {
97 span := trace.SpanFromContext(c.Request().Context())
98 assert.Equal(t, sc.TraceID(), span.SpanContext().TraceID())
99 assert.Equal(t, sc.SpanID(), span.SpanContext().SpanID())
100 return c.NoContent(http.StatusOK)
101 })
102
103 router.ServeHTTP(w, r)
104 assert.Equal(t, http.StatusOK, w.Result().StatusCode, "should call the 'user' handler")
105 }
106
107 func TestSkipper(t *testing.T) {
108 r := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/ping", http.NoBody)
109 w := httptest.NewRecorder()
110
111 skipper := func(c echo.Context) bool {
112 return c.Request().RequestURI == "/ping"
113 }
114
115 router := echo.New()
116 router.Use(Middleware("foobar", WithSkipper(skipper)))
117 router.GET("/ping", func(c echo.Context) error {
118 span := trace.SpanFromContext(c.Request().Context())
119 assert.False(t, span.SpanContext().HasSpanID())
120 assert.False(t, span.SpanContext().HasTraceID())
121 return c.NoContent(http.StatusOK)
122 })
123
124 router.ServeHTTP(w, r)
125 assert.Equal(t, http.StatusOK, w.Result().StatusCode, "should call the 'ping' handler")
126 }
127
128 func TestMetrics(t *testing.T) {
129 tests := []struct {
130 name string
131 metricAttributeExtractor func(*http.Request) []attribute.KeyValue
132 echoMetricAttributeExtractor func(echo.Context) []attribute.KeyValue
133 requestTarget string
134 wantRouteAttr string
135 wantStatus int64
136 }{
137 {
138 name: "default",
139 metricAttributeExtractor: nil,
140 echoMetricAttributeExtractor: nil,
141 requestTarget: "/user/123",
142 wantRouteAttr: "/user/:id",
143 wantStatus: 200,
144 },
145 {
146 name: "request target not exist",
147 metricAttributeExtractor: nil,
148 echoMetricAttributeExtractor: nil,
149 requestTarget: "/abc/123",
150 wantStatus: 404,
151 },
152 {
153 name: "with metric attributes callback",
154 metricAttributeExtractor: func(r *http.Request) []attribute.KeyValue {
155 return []attribute.KeyValue{
156 attribute.String("key1", "value1"),
157 attribute.String("key2", "value"),
158 attribute.String("method", strings.ToUpper(r.Method)),
159 }
160 },
161 echoMetricAttributeExtractor: func(_ echo.Context) []attribute.KeyValue {
162 return []attribute.KeyValue{
163 attribute.String("key3", "value3"),
164 }
165 },
166 requestTarget: "/user/123",
167 wantRouteAttr: "/user/:id",
168 wantStatus: 200,
169 },
170 }
171
172 for _, tt := range tests {
173 t.Run(tt.name, func(t *testing.T) {
174 reader := sdkmetric.NewManualReader()
175 meterProvider := sdkmetric.NewMeterProvider(sdkmetric.WithReader(reader))
176
177 e := echo.New()
178 e.Use(Middleware("foobar",
179 WithMeterProvider(meterProvider),
180 WithMetricAttributeFn(tt.metricAttributeExtractor),
181 WithEchoMetricAttributeFn(tt.echoMetricAttributeExtractor),
182 ))
183 e.GET("/user/:id", func(c echo.Context) error {
184 id := c.Param("id")
185 assert.Equal(t, "123", id)
186 return c.String(http.StatusOK, id)
187 })
188
189 r := httptest.NewRequestWithContext(t.Context(), http.MethodGet, tt.requestTarget, http.NoBody)
190 w := httptest.NewRecorder()
191 e.ServeHTTP(w, r)
192
193 // verify metrics
194 rm := metricdata.ResourceMetrics{}
195 require.NoError(t, reader.Collect(t.Context(), &rm))
196
197 require.Len(t, rm.ScopeMetrics, 1)
198 sm := rm.ScopeMetrics[0]
199 assert.Equal(t, ScopeName, sm.Scope.Name)
200 assert.Equal(t, Version, sm.Scope.Version)
201
202 attrs := []attribute.KeyValue{
203 attribute.String("http.request.method", "GET"),
204 attribute.Int64("http.response.status_code", tt.wantStatus),
205 attribute.String("network.protocol.name", "http"),
206 attribute.String("network.protocol.version", fmt.Sprintf("1.%d", r.ProtoMinor)),
207 attribute.String("server.address", "foobar"),
208 attribute.String("url.scheme", "http"),
209 }
210 if tt.wantRouteAttr != "" {
211 attrs = append(attrs, attribute.String("http.route", tt.wantRouteAttr))
212 }
213
214 if tt.metricAttributeExtractor != nil {
215 attrs = append(attrs, tt.metricAttributeExtractor(r)...)
216 }
217 if tt.echoMetricAttributeExtractor != nil {
218 // Create a mock context to get echo attributes
219 mockCtx := echo.New().NewContext(r, httptest.NewRecorder())
220 mockCtx.SetParamNames("id")
221 mockCtx.SetParamValues("123")
222 mockCtx.SetPath("/user/:id")
223 attrs = append(attrs, tt.echoMetricAttributeExtractor(mockCtx)...)
224 }
225
226 metricdatatest.AssertEqual(t, metricdata.Metrics{
227 Name: "http.server.request.body.size",
228 Description: "Size of HTTP server request bodies.",
229 Unit: "By",
230 Data: metricdata.Histogram[int64]{
231 Temporality: metricdata.CumulativeTemporality,
232 DataPoints: []metricdata.HistogramDataPoint[int64]{
233 {
234 Attributes: attribute.NewSet(attrs...),
235 },
236 },
237 },
238 }, sm.Metrics[0], metricdatatest.IgnoreTimestamp(), metricdatatest.IgnoreValue(), metricdatatest.IgnoreExemplars())
239
240 metricdatatest.AssertEqual(t, metricdata.Metrics{
241 Name: "http.server.response.body.size",
242 Description: "Size of HTTP server response bodies.",
243 Unit: "By",
244 Data: metricdata.Histogram[int64]{
245 Temporality: metricdata.CumulativeTemporality,
246 DataPoints: []metricdata.HistogramDataPoint[int64]{
247 {
248 Attributes: attribute.NewSet(attrs...),
249 },
250 },
251 },
252 }, sm.Metrics[1], metricdatatest.IgnoreTimestamp(), metricdatatest.IgnoreValue(), metricdatatest.IgnoreExemplars())
253
254 metricdatatest.AssertEqual(t, metricdata.Metrics{
255 Name: "http.server.request.duration",
256 Description: "Duration of HTTP server requests.",
257 Unit: "s",
258 Data: metricdata.Histogram[float64]{
259 Temporality: metricdata.CumulativeTemporality,
260 DataPoints: []metricdata.HistogramDataPoint[float64]{
261 {
262 Attributes: attribute.NewSet(attrs...),
263 },
264 },
265 },
266 }, sm.Metrics[2], metricdatatest.IgnoreTimestamp(), metricdatatest.IgnoreValue(), metricdatatest.IgnoreExemplars())
267 })
268 }
269 }
270
271 func TestWithMetricAttributeFn(t *testing.T) {
272 reader := sdkmetric.NewManualReader()
273 meterProvider := sdkmetric.NewMeterProvider(sdkmetric.WithReader(reader))
274
275 e := echo.New()
276 e.Use(Middleware("test-service",
277 WithMeterProvider(meterProvider),
278 WithMetricAttributeFn(func(r *http.Request) []attribute.KeyValue {
279 return []attribute.KeyValue{
280 attribute.String("custom.header", r.Header.Get("X-Test-Header")),
281 }
282 }),
283 ))
284
285 e.GET("/test", func(c echo.Context) error {
286 return c.String(http.StatusOK, "test response")
287 })
288
289 r := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/test", http.NoBody)
290 r.Header.Set("X-Test-Header", "test-value")
291 w := httptest.NewRecorder()
292 e.ServeHTTP(w, r)
293
294 assert.Equal(t, http.StatusOK, w.Result().StatusCode)
295
296 // verify metrics
297 rm := metricdata.ResourceMetrics{}
298 require.NoError(t, reader.Collect(t.Context(), &rm))
299 require.Len(t, rm.ScopeMetrics, 1)
300 sm := rm.ScopeMetrics[0]
301 require.Len(t, sm.Metrics, 3)
302
303 // Check that custom attribute is present
304 found := false
305 for _, metric := range sm.Metrics {
306 if metric.Name == "http.server.request.duration" {
307 histogram := metric.Data.(metricdata.Histogram[float64])
308 require.Len(t, histogram.DataPoints, 1)
309 attrs := histogram.DataPoints[0].Attributes.ToSlice()
310 for _, attr := range attrs {
311 if attr.Key == "custom.header" && attr.Value.AsString() == "test-value" {
312 found = true
313 break
314 }
315 }
316 }
317 }
318 assert.True(t, found, "custom attribute should be found in metrics")
319 }
320
321 func TestWithEchoMetricAttributeFn(t *testing.T) {
322 reader := sdkmetric.NewManualReader()
323 meterProvider := sdkmetric.NewMeterProvider(sdkmetric.WithReader(reader))
324
325 e := echo.New()
326 e.Use(Middleware("test-service",
327 WithMeterProvider(meterProvider),
328 WithEchoMetricAttributeFn(func(c echo.Context) []attribute.KeyValue {
329 return []attribute.KeyValue{
330 // This is just for testing. Avoid high cardinality metrics such as "id" in production code
331 attribute.String("echo.param.id", c.Param("id")),
332 attribute.String("echo.path", c.Path()),
333 }
334 }),
335 ))
336
337 e.GET("/user/:id", func(c echo.Context) error {
338 return c.String(http.StatusOK, "user: "+c.Param("id"))
339 })
340
341 r := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/user/456", http.NoBody)
342 w := httptest.NewRecorder()
343 e.ServeHTTP(w, r)
344
345 assert.Equal(t, http.StatusOK, w.Result().StatusCode)
346
347 // verify metrics
348 rm := metricdata.ResourceMetrics{}
349 require.NoError(t, reader.Collect(t.Context(), &rm))
350 require.Len(t, rm.ScopeMetrics, 1)
351 sm := rm.ScopeMetrics[0]
352 require.Len(t, sm.Metrics, 3)
353
354 // Check that custom attributes are present
355 foundID := false
356 foundPath := false
357 for _, metric := range sm.Metrics {
358 if metric.Name == "http.server.request.duration" {
359 histogram := metric.Data.(metricdata.Histogram[float64])
360 require.Len(t, histogram.DataPoints, 1)
361 attrs := histogram.DataPoints[0].Attributes.ToSlice()
362 for _, attr := range attrs {
363 if attr.Key == "echo.param.id" && attr.Value.AsString() == "456" {
364 foundID = true
365 }
366 if attr.Key == "echo.path" && attr.Value.AsString() == "/user/:id" {
367 foundPath = true
368 }
369 }
370 }
371 }
372 assert.True(t, foundID, "echo param id attribute should be found")
373 assert.True(t, foundPath, "echo path attribute should be found")
374 }
375
376 func TestWithOnError(t *testing.T) {
377 tests := []struct {
378 name string
379 opt Option
380 wantHandlerCalled int
381 }{
382 {
383 name: "without WithOnError option (default)",
384 opt: nil,
385 wantHandlerCalled: 2,
386 },
387 {
388 name: "nil WithOnError option",
389 opt: WithOnError(nil),
390 wantHandlerCalled: 2,
391 },
392 {
393 name: "custom WithOnError with c.Error call",
394 opt: WithOnError(func(c echo.Context, err error) {
395 err = fmt.Errorf("call from OnError: %w", err)
396 c.Error(err)
397 }),
398 wantHandlerCalled: 2,
399 },
400 {
401 name: "custom onError without c.Error call",
402 opt: WithOnError(func(_ echo.Context, err error) {
403 t.Logf("Inside custom OnError: %v", err)
404 }),
405 wantHandlerCalled: 1,
406 },
407 }
408
409 for _, tt := range tests {
410 t.Run(tt.name, func(t *testing.T) {
411 r := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/ping", http.NoBody)
412 w := httptest.NewRecorder()
413
414 router := echo.New()
415 if tt.opt != nil {
416 router.Use(Middleware("foobar", tt.opt))
417 } else {
418 router.Use(Middleware("foobar"))
419 }
420
421 router.GET("/ping", func(_ echo.Context) error {
422 return assert.AnError
423 })
424
425 handlerCalled := 0
426 router.HTTPErrorHandler = func(err error, c echo.Context) {
427 handlerCalled++
428 assert.ErrorIs(t, err, assert.AnError, "test error is expected in error handler")
429 assert.NoError(t, c.NoContent(http.StatusTeapot))
430 }
431
432 router.ServeHTTP(w, r)
433 assert.Equal(t, http.StatusTeapot, w.Result().StatusCode, "should call the 'ping' handler")
434 assert.Equal(t, tt.wantHandlerCalled, handlerCalled, "handler called times mismatch")
435 })
436 }
437 }