| 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 otelgin_test |
| 7 |
|
| 8 |
import ( |
| 9 |
"errors" |
| 10 |
"fmt" |
| 11 |
"html/template" |
| 12 |
"net/http" |
| 13 |
"net/http/httptest" |
| 14 |
"strconv" |
| 15 |
"strings" |
| 16 |
"testing" |
| 17 |
|
| 18 |
"github.com/gin-gonic/gin" |
| 19 |
"github.com/stretchr/testify/assert" |
| 20 |
"github.com/stretchr/testify/require" |
| 21 |
"go.opentelemetry.io/otel" |
| 22 |
"go.opentelemetry.io/otel/attribute" |
| 23 |
"go.opentelemetry.io/otel/codes" |
| 24 |
"go.opentelemetry.io/otel/propagation" |
| 25 |
sdkmetric "go.opentelemetry.io/otel/sdk/metric" |
| 26 |
"go.opentelemetry.io/otel/sdk/metric/metricdata" |
| 27 |
"go.opentelemetry.io/otel/sdk/metric/metricdata/metricdatatest" |
| 28 |
sdktrace "go.opentelemetry.io/otel/sdk/trace" |
| 29 |
"go.opentelemetry.io/otel/sdk/trace/tracetest" |
| 30 |
"go.opentelemetry.io/otel/trace" |
| 31 |
"go.opentelemetry.io/otel/trace/noop" |
| 32 |
|
| 33 |
"go.opentelemetry.io/contrib/instrumentation/github.com/gin-gonic/gin/otelgin" |
| 34 |
b3prop "go.opentelemetry.io/contrib/propagators/b3" |
| 35 |
) |
| 36 |
|
| 37 |
func init() { |
| 38 |
gin.SetMode(gin.ReleaseMode) // silence annoying log msgs |
| 39 |
} |
| 40 |
|
| 41 |
func TestGetSpanNotInstrumented(t *testing.T) { |
| 42 |
router := gin.New() |
| 43 |
router.GET("/ping", func(c *gin.Context) { |
| 44 |
// Assert we don't have a span on the context. |
| 45 |
span := trace.SpanFromContext(c.Request.Context()) |
| 46 |
ok := !span.SpanContext().IsValid() |
| 47 |
assert.True(t, ok) |
| 48 |
_, _ = c.Writer.WriteString("ok") |
| 49 |
}) |
| 50 |
r := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/ping", http.NoBody) |
| 51 |
w := httptest.NewRecorder() |
| 52 |
router.ServeHTTP(w, r) |
| 53 |
response := w.Result() |
| 54 |
assert.Equal(t, http.StatusOK, response.StatusCode) |
| 55 |
} |
| 56 |
|
| 57 |
func TestPropagationWithGlobalPropagators(t *testing.T) { |
| 58 |
provider := noop.NewTracerProvider() |
| 59 |
otel.SetTextMapPropagator(b3prop.New()) |
| 60 |
|
| 61 |
r := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/user/123", http.NoBody) |
| 62 |
w := httptest.NewRecorder() |
| 63 |
|
| 64 |
ctx := t.Context() |
| 65 |
sc := trace.NewSpanContext(trace.SpanContextConfig{ |
| 66 |
TraceID: trace.TraceID{0x01}, |
| 67 |
SpanID: trace.SpanID{0x01}, |
| 68 |
}) |
| 69 |
ctx = trace.ContextWithRemoteSpanContext(ctx, sc) |
| 70 |
ctx, _ = provider.Tracer(otelgin.ScopeName).Start(ctx, "test") |
| 71 |
otel.GetTextMapPropagator().Inject(ctx, propagation.HeaderCarrier(r.Header)) |
| 72 |
|
| 73 |
router := gin.New() |
| 74 |
router.Use(otelgin.Middleware("foobar", otelgin.WithTracerProvider(provider))) |
| 75 |
router.GET("/user/:id", func(c *gin.Context) { |
| 76 |
span := trace.SpanFromContext(c.Request.Context()) |
| 77 |
assert.Equal(t, sc.TraceID(), span.SpanContext().TraceID()) |
| 78 |
assert.Equal(t, sc.SpanID(), span.SpanContext().SpanID()) |
| 79 |
}) |
| 80 |
|
| 81 |
router.ServeHTTP(w, r) |
| 82 |
} |
| 83 |
|
| 84 |
func TestPropagationWithCustomPropagators(t *testing.T) { |
| 85 |
provider := noop.NewTracerProvider() |
| 86 |
b3 := b3prop.New() |
| 87 |
|
| 88 |
r := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/user/123", http.NoBody) |
| 89 |
w := httptest.NewRecorder() |
| 90 |
|
| 91 |
ctx := t.Context() |
| 92 |
sc := trace.NewSpanContext(trace.SpanContextConfig{ |
| 93 |
TraceID: trace.TraceID{0x01}, |
| 94 |
SpanID: trace.SpanID{0x01}, |
| 95 |
}) |
| 96 |
ctx = trace.ContextWithRemoteSpanContext(ctx, sc) |
| 97 |
ctx, _ = provider.Tracer(otelgin.ScopeName).Start(ctx, "test") |
| 98 |
b3.Inject(ctx, propagation.HeaderCarrier(r.Header)) |
| 99 |
|
| 100 |
router := gin.New() |
| 101 |
router.Use(otelgin.Middleware("foobar", otelgin.WithTracerProvider(provider), otelgin.WithPropagators(b3))) |
| 102 |
router.GET("/user/:id", func(c *gin.Context) { |
| 103 |
span := trace.SpanFromContext(c.Request.Context()) |
| 104 |
assert.Equal(t, sc.TraceID(), span.SpanContext().TraceID()) |
| 105 |
assert.Equal(t, sc.SpanID(), span.SpanContext().SpanID()) |
| 106 |
}) |
| 107 |
|
| 108 |
router.ServeHTTP(w, r) |
| 109 |
} |
| 110 |
|
| 111 |
func TestChildSpanFromGlobalTracer(t *testing.T) { |
| 112 |
sr := tracetest.NewSpanRecorder() |
| 113 |
otel.SetTracerProvider(sdktrace.NewTracerProvider(sdktrace.WithSpanProcessor(sr))) |
| 114 |
|
| 115 |
router := gin.New() |
| 116 |
router.Use(otelgin.Middleware("foobar")) |
| 117 |
router.GET("/user/:id", func(*gin.Context) {}) |
| 118 |
|
| 119 |
r := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/user/123", http.NoBody) |
| 120 |
w := httptest.NewRecorder() |
| 121 |
|
| 122 |
router.ServeHTTP(w, r) |
| 123 |
assert.Len(t, sr.Ended(), 1) |
| 124 |
} |
| 125 |
|
| 126 |
func TestChildSpanFromCustomTracer(t *testing.T) { |
| 127 |
sr := tracetest.NewSpanRecorder() |
| 128 |
provider := sdktrace.NewTracerProvider(sdktrace.WithSpanProcessor(sr)) |
| 129 |
|
| 130 |
router := gin.New() |
| 131 |
router.Use(otelgin.Middleware("foobar", otelgin.WithTracerProvider(provider))) |
| 132 |
router.GET("/user/:id", func(*gin.Context) {}) |
| 133 |
|
| 134 |
r := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/user/123", http.NoBody) |
| 135 |
w := httptest.NewRecorder() |
| 136 |
|
| 137 |
router.ServeHTTP(w, r) |
| 138 |
assert.Len(t, sr.Ended(), 1) |
| 139 |
} |
| 140 |
|
| 141 |
func TestTrace200(t *testing.T) { |
| 142 |
sr := tracetest.NewSpanRecorder() |
| 143 |
provider := sdktrace.NewTracerProvider(sdktrace.WithSpanProcessor(sr)) |
| 144 |
|
| 145 |
router := gin.New() |
| 146 |
router.Use(otelgin.Middleware("foobar", otelgin.WithTracerProvider(provider))) |
| 147 |
router.GET("/user/:id", func(c *gin.Context) { |
| 148 |
id := c.Param("id") |
| 149 |
_, _ = c.Writer.WriteString(id) |
| 150 |
}) |
| 151 |
|
| 152 |
r := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/user/123", http.NoBody) |
| 153 |
w := httptest.NewRecorder() |
| 154 |
|
| 155 |
// do and verify the request |
| 156 |
router.ServeHTTP(w, r) |
| 157 |
response := w.Result() |
| 158 |
require.Equal(t, http.StatusOK, response.StatusCode) |
| 159 |
|
| 160 |
// verify traces look good |
| 161 |
spans := sr.Ended() |
| 162 |
require.Len(t, spans, 1) |
| 163 |
span := spans[0] |
| 164 |
assert.Equal(t, "GET /user/:id", span.Name()) |
| 165 |
assert.Equal(t, trace.SpanKindServer, span.SpanKind()) |
| 166 |
attr := span.Attributes() |
| 167 |
assert.Contains(t, attr, attribute.String("server.address", "foobar")) |
| 168 |
assert.Contains(t, attr, attribute.Int("http.response.status_code", http.StatusOK)) |
| 169 |
assert.Contains(t, attr, attribute.String("http.request.method", "GET")) |
| 170 |
assert.Contains(t, attr, attribute.String("http.route", "/user/:id")) |
| 171 |
assert.Empty(t, span.Events()) |
| 172 |
assert.Equal(t, codes.Unset, span.Status().Code) |
| 173 |
assert.Empty(t, span.Status().Description) |
| 174 |
} |
| 175 |
|
| 176 |
func TestError(t *testing.T) { |
| 177 |
sr := tracetest.NewSpanRecorder() |
| 178 |
provider := sdktrace.NewTracerProvider(sdktrace.WithSpanProcessor(sr)) |
| 179 |
|
| 180 |
// setup |
| 181 |
router := gin.New() |
| 182 |
router.Use(otelgin.Middleware("foobar", otelgin.WithTracerProvider(provider))) |
| 183 |
|
| 184 |
// configure a handler that returns an error and 5xx status |
| 185 |
// code |
| 186 |
router.GET("/server_err", func(c *gin.Context) { |
| 187 |
_ = c.Error(errors.New("oh no one")) |
| 188 |
_ = c.AbortWithError(http.StatusInternalServerError, errors.New("oh no two")) |
| 189 |
}) |
| 190 |
r := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/server_err", http.NoBody) |
| 191 |
w := httptest.NewRecorder() |
| 192 |
router.ServeHTTP(w, r) |
| 193 |
response := w.Result() |
| 194 |
assert.Equal(t, http.StatusInternalServerError, response.StatusCode) |
| 195 |
|
| 196 |
// verify the errors and status are correct |
| 197 |
spans := sr.Ended() |
| 198 |
require.Len(t, spans, 1) |
| 199 |
span := spans[0] |
| 200 |
assert.Equal(t, "GET /server_err", span.Name()) |
| 201 |
attr := span.Attributes() |
| 202 |
assert.Contains(t, attr, attribute.String("server.address", "foobar")) |
| 203 |
assert.Contains(t, attr, attribute.Int("http.response.status_code", http.StatusInternalServerError)) |
| 204 |
|
| 205 |
// verify the error events |
| 206 |
events := span.Events() |
| 207 |
require.Len(t, events, 2) |
| 208 |
assert.Equal(t, "exception", events[0].Name) |
| 209 |
assert.Contains(t, events[0].Attributes, attribute.String("exception.type", "*errors.errorString")) |
| 210 |
assert.Contains(t, events[0].Attributes, attribute.String("exception.message", "oh no one")) |
| 211 |
assert.Equal(t, "exception", events[1].Name) |
| 212 |
assert.Contains(t, events[1].Attributes, attribute.String("exception.type", "*errors.errorString")) |
| 213 |
assert.Contains(t, events[1].Attributes, attribute.String("exception.message", "oh no two")) |
| 214 |
|
| 215 |
// server errors set the status |
| 216 |
assert.Equal(t, codes.Error, span.Status().Code) |
| 217 |
assert.Equal(t, "Error #01: oh no one\nError #02: oh no two\n", span.Status().Description) |
| 218 |
} |
| 219 |
|
| 220 |
func TestSpanStatus(t *testing.T) { |
| 221 |
testCases := []struct { |
| 222 |
httpStatusCode int |
| 223 |
wantSpanStatus codes.Code |
| 224 |
}{ |
| 225 |
{http.StatusOK, codes.Unset}, |
| 226 |
{http.StatusBadRequest, codes.Unset}, |
| 227 |
{http.StatusInternalServerError, codes.Error}, |
| 228 |
} |
| 229 |
for _, tc := range testCases { |
| 230 |
t.Run(strconv.Itoa(tc.httpStatusCode), func(t *testing.T) { |
| 231 |
sr := tracetest.NewSpanRecorder() |
| 232 |
provider := sdktrace.NewTracerProvider() |
| 233 |
provider.RegisterSpanProcessor(sr) |
| 234 |
router := gin.New() |
| 235 |
router.Use(otelgin.Middleware("foobar", otelgin.WithTracerProvider(provider))) |
| 236 |
router.GET("/", func(c *gin.Context) { |
| 237 |
c.Status(tc.httpStatusCode) |
| 238 |
}) |
| 239 |
|
| 240 |
router.ServeHTTP(httptest.NewRecorder(), httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/", http.NoBody)) |
| 241 |
|
| 242 |
require.Len(t, sr.Ended(), 1, "should emit a span") |
| 243 |
assert.Equal(t, tc.wantSpanStatus, sr.Ended()[0].Status().Code, "should only set Error status for HTTP statuses >= 500") |
| 244 |
}) |
| 245 |
} |
| 246 |
|
| 247 |
t.Run("The status code is 200, but an error is returned", func(t *testing.T) { |
| 248 |
sr := tracetest.NewSpanRecorder() |
| 249 |
provider := sdktrace.NewTracerProvider( |
| 250 |
sdktrace.WithSpanProcessor(sr), |
| 251 |
) |
| 252 |
|
| 253 |
router := gin.New() |
| 254 |
router.Use(otelgin.Middleware("foobar", otelgin.WithTracerProvider(provider))) |
| 255 |
router.GET("/", func(c *gin.Context) { |
| 256 |
_ = c.Error(errors.New("something went wrong")) |
| 257 |
c.JSON(http.StatusOK, nil) |
| 258 |
}) |
| 259 |
|
| 260 |
router.ServeHTTP(httptest.NewRecorder(), httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/", http.NoBody)) |
| 261 |
|
| 262 |
require.Len(t, sr.Ended(), 1) |
| 263 |
assert.Equal(t, codes.Error, sr.Ended()[0].Status().Code) |
| 264 |
require.Len(t, sr.Ended()[0].Events(), 1) |
| 265 |
assert.Contains(t, sr.Ended()[0].Events()[0].Attributes, attribute.String("exception.message", "something went wrong")) |
| 266 |
}) |
| 267 |
} |
| 268 |
|
| 269 |
func TestWithSpanOptions_CustomAttributesAndSpanKind(t *testing.T) { |
| 270 |
sr := tracetest.NewSpanRecorder() |
| 271 |
provider := sdktrace.NewTracerProvider(sdktrace.WithSpanProcessor(sr)) |
| 272 |
|
| 273 |
customAttr := attribute.String("custom.key", "custom.value") |
| 274 |
|
| 275 |
router := gin.New() |
| 276 |
router.Use(otelgin.Middleware("foobar", |
| 277 |
otelgin.WithTracerProvider(provider), |
| 278 |
otelgin.WithSpanStartOptions(trace.WithAttributes(customAttr)), |
| 279 |
)) |
| 280 |
router.GET("/test", func(*gin.Context) {}) |
| 281 |
|
| 282 |
r := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/test", http.NoBody) |
| 283 |
w := httptest.NewRecorder() |
| 284 |
router.ServeHTTP(w, r) |
| 285 |
|
| 286 |
spans := sr.Ended() |
| 287 |
require.Len(t, spans, 1) |
| 288 |
|
| 289 |
span := spans[0] |
| 290 |
assert.Contains(t, span.Attributes(), customAttr) |
| 291 |
assert.Equal(t, trace.SpanKindServer, span.SpanKind()) |
| 292 |
} |
| 293 |
|
| 294 |
func TestSpanName(t *testing.T) { |
| 295 |
sr := tracetest.NewSpanRecorder() |
| 296 |
provider := sdktrace.NewTracerProvider( |
| 297 |
sdktrace.WithSpanProcessor(sr), |
| 298 |
) |
| 299 |
|
| 300 |
testCases := []struct { |
| 301 |
method string |
| 302 |
route string |
| 303 |
requestPath string |
| 304 |
spanNameFormatter otelgin.SpanNameFormatter |
| 305 |
wantSpanName string |
| 306 |
}{ |
| 307 |
// Test for standard methods |
| 308 |
{http.MethodGet, "/user/:id", "/user/1", nil, "GET /user/:id"}, |
| 309 |
{http.MethodPost, "/user/:id", "/user/1", nil, "POST /user/:id"}, |
| 310 |
{http.MethodPut, "/user/:id", "/user/1", nil, "PUT /user/:id"}, |
| 311 |
{http.MethodPatch, "/user/:id", "/user/1", nil, "PATCH /user/:id"}, |
| 312 |
{http.MethodDelete, "/user/:id", "/user/1", nil, "DELETE /user/:id"}, |
| 313 |
{http.MethodConnect, "/user/:id", "/user/1", nil, "CONNECT /user/:id"}, |
| 314 |
{http.MethodOptions, "/user/:id", "/user/1", nil, "OPTIONS /user/:id"}, |
| 315 |
{http.MethodTrace, "/user/:id", "/user/1", nil, "TRACE /user/:id"}, |
| 316 |
// Test for no route |
| 317 |
{http.MethodGet, "", "/user/1", nil, "GET"}, |
| 318 |
// Test for invalid method |
| 319 |
{"INVALID", "/user/:id", "/user/1", nil, "HTTP /user/:id"}, |
| 320 |
// Test for custom span name formatter |
| 321 |
{http.MethodGet, "/user/:id", "/user/1", func(c *gin.Context) string { return c.Request.URL.Path }, "/user/1"}, |
| 322 |
} |
| 323 |
for _, tc := range testCases { |
| 324 |
t.Run(fmt.Sprintf("method: %s, route: %s, requestPath: %s", tc.method, tc.route, tc.requestPath), func(t *testing.T) { |
| 325 |
defer sr.Reset() |
| 326 |
|
| 327 |
router := gin.New() |
| 328 |
router.Use(otelgin.Middleware("foobar", otelgin.WithTracerProvider(provider), otelgin.WithSpanNameFormatter(tc.spanNameFormatter))) |
| 329 |
router.Handle(tc.method, tc.route, func(*gin.Context) {}) |
| 330 |
|
| 331 |
router.ServeHTTP(httptest.NewRecorder(), httptest.NewRequestWithContext(t.Context(), tc.method, tc.requestPath, http.NoBody)) |
| 332 |
|
| 333 |
require.Len(t, sr.Ended(), 1, "should emit a span") |
| 334 |
assert.Equal(t, tc.wantSpanName, sr.Ended()[0].Name(), "span name not correct") |
| 335 |
}) |
| 336 |
} |
| 337 |
} |
| 338 |
|
| 339 |
func TestHTTPRouteWithSpanNameFormatter(t *testing.T) { |
| 340 |
sr := tracetest.NewSpanRecorder() |
| 341 |
provider := sdktrace.NewTracerProvider(sdktrace.WithSpanProcessor(sr)) |
| 342 |
|
| 343 |
router := gin.New() |
| 344 |
router.Use(otelgin.Middleware("foobar", |
| 345 |
otelgin.WithTracerProvider(provider), |
| 346 |
otelgin.WithSpanNameFormatter(func(c *gin.Context) string { |
| 347 |
return c.Request.URL.Path |
| 348 |
}), |
| 349 |
), |
| 350 |
) |
| 351 |
router.GET("/user/:id", func(c *gin.Context) { |
| 352 |
id := c.Param("id") |
| 353 |
_, _ = c.Writer.WriteString(id) |
| 354 |
}) |
| 355 |
|
| 356 |
r := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/user/123", http.NoBody) |
| 357 |
w := httptest.NewRecorder() |
| 358 |
|
| 359 |
// do and verify the request |
| 360 |
router.ServeHTTP(w, r) |
| 361 |
response := w.Result() |
| 362 |
require.Equal(t, http.StatusOK, response.StatusCode) |
| 363 |
|
| 364 |
// verify traces look good |
| 365 |
spans := sr.Ended() |
| 366 |
require.Len(t, spans, 1) |
| 367 |
span := spans[0] |
| 368 |
assert.Equal(t, "/user/123", span.Name()) |
| 369 |
assert.Equal(t, trace.SpanKindServer, span.SpanKind()) |
| 370 |
attr := span.Attributes() |
| 371 |
assert.Contains(t, attr, attribute.String("http.request.method", "GET")) |
| 372 |
assert.Contains(t, attr, attribute.String("http.route", "/user/:id")) |
| 373 |
} |
| 374 |
|
| 375 |
func TestHTML(t *testing.T) { |
| 376 |
sr := tracetest.NewSpanRecorder() |
| 377 |
provider := sdktrace.NewTracerProvider(sdktrace.WithSpanProcessor(sr)) |
| 378 |
|
| 379 |
// setup |
| 380 |
router := gin.New() |
| 381 |
router.Use(otelgin.Middleware("foobar", otelgin.WithTracerProvider(provider))) |
| 382 |
|
| 383 |
// add a template |
| 384 |
tmpl := template.Must(template.New("hello").Parse("hello {{.}}")) |
| 385 |
router.SetHTMLTemplate(tmpl) |
| 386 |
|
| 387 |
// a handler with an error and make the requests |
| 388 |
router.GET("/hello", func(c *gin.Context) { |
| 389 |
otelgin.HTML(c, http.StatusOK, "hello", "world") |
| 390 |
}) |
| 391 |
r := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/hello", http.NoBody) |
| 392 |
w := httptest.NewRecorder() |
| 393 |
router.ServeHTTP(w, r) |
| 394 |
response := w.Result() |
| 395 |
assert.Equal(t, http.StatusOK, response.StatusCode) |
| 396 |
assert.Equal(t, "hello world", w.Body.String()) |
| 397 |
|
| 398 |
// verify the errors and status are correct |
| 399 |
spans := sr.Ended() |
| 400 |
require.Len(t, spans, 2) |
| 401 |
var tspan sdktrace.ReadOnlySpan |
| 402 |
for _, s := range spans { |
| 403 |
// we need to pick up the span we're searching for, as the |
| 404 |
// order is not guaranteed within the buffer |
| 405 |
if s.Name() == "gin.renderer.html" { |
| 406 |
tspan = s |
| 407 |
break |
| 408 |
} |
| 409 |
} |
| 410 |
require.NotNil(t, tspan) |
| 411 |
assert.Contains(t, tspan.Attributes(), attribute.String("go.template", "hello")) |
| 412 |
} |
| 413 |
|
| 414 |
func TestWithFilter(t *testing.T) { |
| 415 |
t.Run("custom filter filtering route", func(t *testing.T) { |
| 416 |
sr := tracetest.NewSpanRecorder() |
| 417 |
otel.SetTracerProvider(sdktrace.NewTracerProvider(sdktrace.WithSpanProcessor(sr))) |
| 418 |
|
| 419 |
router := gin.New() |
| 420 |
f := func(req *http.Request) bool { return req.URL.Path != "/healthcheck" } |
| 421 |
router.Use(otelgin.Middleware("foobar", otelgin.WithFilter(f))) |
| 422 |
router.GET("/healthcheck", func(*gin.Context) {}) |
| 423 |
|
| 424 |
r := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/healthcheck", http.NoBody) |
| 425 |
w := httptest.NewRecorder() |
| 426 |
|
| 427 |
router.ServeHTTP(w, r) |
| 428 |
assert.Empty(t, sr.Ended()) |
| 429 |
}) |
| 430 |
|
| 431 |
t.Run("custom filter not filtering route", func(t *testing.T) { |
| 432 |
sr := tracetest.NewSpanRecorder() |
| 433 |
otel.SetTracerProvider(sdktrace.NewTracerProvider(sdktrace.WithSpanProcessor(sr))) |
| 434 |
|
| 435 |
router := gin.New() |
| 436 |
f := func(req *http.Request) bool { return req.URL.Path != "/healthcheck" } |
| 437 |
router.Use(otelgin.Middleware("foobar", otelgin.WithFilter(f))) |
| 438 |
router.GET("/user/:id", func(*gin.Context) {}) |
| 439 |
|
| 440 |
r := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/user/123", http.NoBody) |
| 441 |
w := httptest.NewRecorder() |
| 442 |
|
| 443 |
router.ServeHTTP(w, r) |
| 444 |
assert.Len(t, sr.Ended(), 1) |
| 445 |
}) |
| 446 |
} |
| 447 |
|
| 448 |
func TestWithGinFilter(t *testing.T) { |
| 449 |
t.Run("custom filter filtering route", func(t *testing.T) { |
| 450 |
sr := tracetest.NewSpanRecorder() |
| 451 |
otel.SetTracerProvider(sdktrace.NewTracerProvider(sdktrace.WithSpanProcessor(sr))) |
| 452 |
|
| 453 |
router := gin.New() |
| 454 |
f := func(c *gin.Context) bool { return c.Request.URL.Path != "/healthcheck" } |
| 455 |
router.Use(otelgin.Middleware("foobar", otelgin.WithGinFilter(f))) |
| 456 |
router.GET("/healthcheck", func(*gin.Context) {}) |
| 457 |
|
| 458 |
r := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/healthcheck", http.NoBody) |
| 459 |
w := httptest.NewRecorder() |
| 460 |
|
| 461 |
router.ServeHTTP(w, r) |
| 462 |
assert.Empty(t, sr.Ended()) |
| 463 |
}) |
| 464 |
|
| 465 |
t.Run("custom filter not filtering route", func(t *testing.T) { |
| 466 |
sr := tracetest.NewSpanRecorder() |
| 467 |
otel.SetTracerProvider(sdktrace.NewTracerProvider(sdktrace.WithSpanProcessor(sr))) |
| 468 |
|
| 469 |
router := gin.New() |
| 470 |
f := func(c *gin.Context) bool { return c.Request.URL.Path != "/user/:id" } |
| 471 |
router.Use(otelgin.Middleware("foobar", otelgin.WithGinFilter(f))) |
| 472 |
router.GET("/user/:id", func(*gin.Context) {}) |
| 473 |
|
| 474 |
r := httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/user/123", http.NoBody) |
| 475 |
w := httptest.NewRecorder() |
| 476 |
|
| 477 |
router.ServeHTTP(w, r) |
| 478 |
assert.Len(t, sr.Ended(), 1) |
| 479 |
}) |
| 480 |
} |
| 481 |
|
| 482 |
func TestMetrics(t *testing.T) { |
| 483 |
tests := []struct { |
| 484 |
name string |
| 485 |
metricAttributeExtractor func(*http.Request) []attribute.KeyValue |
| 486 |
ginMetricAttributeExtractor func(*gin.Context) []attribute.KeyValue |
| 487 |
requestTarget string |
| 488 |
wantRouteAttr string |
| 489 |
wantStatus int64 |
| 490 |
}{ |
| 491 |
{ |
| 492 |
name: "default", |
| 493 |
metricAttributeExtractor: nil, |
| 494 |
ginMetricAttributeExtractor: nil, |
| 495 |
requestTarget: "/user/123", |
| 496 |
wantRouteAttr: "/user/:id", |
| 497 |
wantStatus: 200, |
| 498 |
}, |
| 499 |
{ |
| 500 |
name: "request target not exist", |
| 501 |
metricAttributeExtractor: nil, |
| 502 |
ginMetricAttributeExtractor: nil, |
| 503 |
requestTarget: "/abc/123", |
| 504 |
wantStatus: 404, |
| 505 |
}, |
| 506 |
{ |
| 507 |
name: "with metric attributes callback", |
| 508 |
metricAttributeExtractor: func(r *http.Request) []attribute.KeyValue { |
| 509 |
return []attribute.KeyValue{ |
| 510 |
attribute.String("key1", "value1"), |
| 511 |
attribute.String("key2", "value"), |
| 512 |
attribute.String("method", strings.ToUpper(r.Method)), |
| 513 |
} |
| 514 |
}, |
| 515 |
ginMetricAttributeExtractor: func(*gin.Context) []attribute.KeyValue { |
| 516 |
return []attribute.KeyValue{ |
| 517 |
attribute.String("key3", "value3"), |
| 518 |
} |
| 519 |
}, |
| 520 |
requestTarget: "/user/123", |
| 521 |
wantRouteAttr: "/user/:id", |
| 522 |
wantStatus: 200, |
| 523 |
}, |
| 524 |
} |
| 525 |
|
| 526 |
for _, tt := range tests { |
| 527 |
t.Run(tt.name, func(t *testing.T) { |
| 528 |
reader := sdkmetric.NewManualReader() |
| 529 |
meterProvider := sdkmetric.NewMeterProvider(sdkmetric.WithReader(reader)) |
| 530 |
|
| 531 |
router := gin.New() |
| 532 |
router.Use(otelgin.Middleware("foobar", |
| 533 |
otelgin.WithMeterProvider(meterProvider), |
| 534 |
otelgin.WithMetricAttributeFn(tt.metricAttributeExtractor), |
| 535 |
otelgin.WithGinMetricAttributeFn(tt.ginMetricAttributeExtractor), |
| 536 |
)) |
| 537 |
router.GET("/user/:id", func(c *gin.Context) { |
| 538 |
id := c.Param("id") |
| 539 |
assert.Equal(t, "123", id) |
| 540 |
_, _ = c.Writer.WriteString(id) |
| 541 |
}) |
| 542 |
|
| 543 |
r := httptest.NewRequestWithContext(t.Context(), http.MethodGet, tt.requestTarget, http.NoBody) |
| 544 |
w := httptest.NewRecorder() |
| 545 |
c, _ := gin.CreateTestContext(w) |
| 546 |
c.Request = r |
| 547 |
router.ServeHTTP(w, r) |
| 548 |
|
| 549 |
// verify metrics |
| 550 |
rm := metricdata.ResourceMetrics{} |
| 551 |
require.NoError(t, reader.Collect(t.Context(), &rm)) |
| 552 |
|
| 553 |
require.Len(t, rm.ScopeMetrics, 1) |
| 554 |
sm := rm.ScopeMetrics[0] |
| 555 |
assert.Equal(t, otelgin.ScopeName, sm.Scope.Name) |
| 556 |
assert.Equal(t, otelgin.Version, sm.Scope.Version) |
| 557 |
|
| 558 |
attrs := []attribute.KeyValue{ |
| 559 |
attribute.String("http.request.method", "GET"), |
| 560 |
attribute.Int64("http.response.status_code", tt.wantStatus), |
| 561 |
attribute.String("network.protocol.name", "http"), |
| 562 |
attribute.String("network.protocol.version", fmt.Sprintf("1.%d", r.ProtoMinor)), |
| 563 |
attribute.String("server.address", "foobar"), |
| 564 |
attribute.String("url.scheme", "http"), |
| 565 |
} |
| 566 |
if tt.wantRouteAttr != "" { |
| 567 |
attrs = append(attrs, attribute.String("http.route", tt.wantRouteAttr)) |
| 568 |
} |
| 569 |
|
| 570 |
if tt.metricAttributeExtractor != nil { |
| 571 |
attrs = append(attrs, tt.metricAttributeExtractor(r)...) |
| 572 |
} |
| 573 |
if tt.ginMetricAttributeExtractor != nil { |
| 574 |
attrs = append(attrs, tt.ginMetricAttributeExtractor(c)...) |
| 575 |
} |
| 576 |
|
| 577 |
metricdatatest.AssertEqual(t, metricdata.Metrics{ |
| 578 |
Name: "http.server.request.body.size", |
| 579 |
Description: "Size of HTTP server request bodies.", |
| 580 |
Unit: "By", |
| 581 |
Data: metricdata.Histogram[int64]{ |
| 582 |
Temporality: metricdata.CumulativeTemporality, |
| 583 |
DataPoints: []metricdata.HistogramDataPoint[int64]{ |
| 584 |
{ |
| 585 |
Attributes: attribute.NewSet(attrs...), |
| 586 |
}, |
| 587 |
}, |
| 588 |
}, |
| 589 |
}, sm.Metrics[0], metricdatatest.IgnoreTimestamp(), metricdatatest.IgnoreValue(), metricdatatest.IgnoreExemplars()) |
| 590 |
|
| 591 |
metricdatatest.AssertEqual(t, metricdata.Metrics{ |
| 592 |
Name: "http.server.response.body.size", |
| 593 |
Description: "Size of HTTP server response bodies.", |
| 594 |
Unit: "By", |
| 595 |
Data: metricdata.Histogram[int64]{ |
| 596 |
Temporality: metricdata.CumulativeTemporality, |
| 597 |
DataPoints: []metricdata.HistogramDataPoint[int64]{ |
| 598 |
{ |
| 599 |
Attributes: attribute.NewSet(attrs...), |
| 600 |
}, |
| 601 |
}, |
| 602 |
}, |
| 603 |
}, sm.Metrics[1], metricdatatest.IgnoreTimestamp(), metricdatatest.IgnoreValue(), metricdatatest.IgnoreExemplars()) |
| 604 |
|
| 605 |
metricdatatest.AssertEqual(t, metricdata.Metrics{ |
| 606 |
Name: "http.server.request.duration", |
| 607 |
Description: "Duration of HTTP server requests.", |
| 608 |
Unit: "s", |
| 609 |
Data: metricdata.Histogram[float64]{ |
| 610 |
Temporality: metricdata.CumulativeTemporality, |
| 611 |
DataPoints: []metricdata.HistogramDataPoint[float64]{ |
| 612 |
{ |
| 613 |
Attributes: attribute.NewSet(attrs...), |
| 614 |
}, |
| 615 |
}, |
| 616 |
}, |
| 617 |
}, sm.Metrics[2], metricdatatest.IgnoreTimestamp(), metricdatatest.IgnoreValue(), metricdatatest.IgnoreExemplars()) |
| 618 |
}) |
| 619 |
} |
| 620 |
} |