1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23 24 25 26 27 28 29 30 31 32 33 34 35 36 37 38 39 40 41 42 43 44 45 46 47 48 49 50 51 52 53 54 55 56 57 58 59 60 61 62 63 64 65 66 67 68 69 70 71 72 73 74 75 76 77 78 79 80 81 82 83 84 85 86 87 88 89 90 91 92 93 94 95 96 97 98 99 100 101 102 103 104 105 106 107 108 109 110 111 112 113 114 115 116 117 118 119 120 121 122 123 124 125 126 127 128 129 130 131 132 133 134 135 136 137 138 139 140 141 142 143 144 145 146 147 148 149 150 151 152 153 154 155 156 157 158 159 160 161 162 163 164 165 166 167 168 169 170 171 172 173 174 175 176 177 178 179 180 181 182 183 184 185 186 187 188 189 190 191 192 193 194 195 196 197 198 199 200 201 202 203 204 205 206 207 208 209 210 211 212 213 214 215 216 217 218 219 220 221 222 223 224 225 226 227 228 229 230 231 232 233 234 235 236 237 238 239 240 241 242 243 244 245 246 247 248 249 250 251 252 253 254 255 256 257 258 259 260 261 262 263 264 265 266 267 268 269 270 271 272 273 274 275 276 277 278 279 280 281 282 283 284 285 286 287 288 289 290 291 292 293 294 295 296 297 298 299 300 301 302 303 304 305 306 307 308 309 310 311 312 313 314 315 316 317 318 319 320 321 322 323
|
// Copyright The OpenTelemetry Authors
// SPDX-License-Identifier: Apache-2.0
// Based on https://github.com/DataDog/dd-trace-go/blob/8fb554ff7cf694267f9077ae35e27ce4689ed8b6/contrib/gin-gonic/gin/gintrace_test.go
package test
import (
"errors"
"html/template"
"net/http"
"net/http/httptest"
"strconv"
"testing"
"github.com/gin-gonic/gin"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"go.opentelemetry.io/contrib/instrumentation/github.com/gin-gonic/gin/otelgin"
"go.opentelemetry.io/otel"
"go.opentelemetry.io/otel/codes"
sdktrace "go.opentelemetry.io/otel/sdk/trace"
"go.opentelemetry.io/otel/sdk/trace/tracetest"
"go.opentelemetry.io/otel/attribute"
oteltrace "go.opentelemetry.io/otel/trace"
)
func init() {
gin.SetMode(gin.ReleaseMode) // silence annoying log msgs
}
func TestChildSpanFromGlobalTracer(t *testing.T) {
sr := tracetest.NewSpanRecorder()
otel.SetTracerProvider(sdktrace.NewTracerProvider(sdktrace.WithSpanProcessor(sr)))
router := gin.New()
router.Use(otelgin.Middleware("foobar"))
router.GET("/user/:id", func(c *gin.Context) {})
r := httptest.NewRequest("GET", "/user/123", nil)
w := httptest.NewRecorder()
router.ServeHTTP(w, r)
assert.Len(t, sr.Ended(), 1)
}
func TestChildSpanFromCustomTracer(t *testing.T) {
sr := tracetest.NewSpanRecorder()
provider := sdktrace.NewTracerProvider(sdktrace.WithSpanProcessor(sr))
router := gin.New()
router.Use(otelgin.Middleware("foobar", otelgin.WithTracerProvider(provider)))
router.GET("/user/:id", func(c *gin.Context) {})
r := httptest.NewRequest("GET", "/user/123", nil)
w := httptest.NewRecorder()
router.ServeHTTP(w, r)
assert.Len(t, sr.Ended(), 1)
}
func TestTrace200(t *testing.T) {
sr := tracetest.NewSpanRecorder()
provider := sdktrace.NewTracerProvider(sdktrace.WithSpanProcessor(sr))
router := gin.New()
router.Use(otelgin.Middleware("foobar", otelgin.WithTracerProvider(provider)))
router.GET("/user/:id", func(c *gin.Context) {
id := c.Param("id")
_, _ = c.Writer.Write([]byte(id))
})
r := httptest.NewRequest("GET", "/user/123", nil)
w := httptest.NewRecorder()
// do and verify the request
router.ServeHTTP(w, r)
response := w.Result() //nolint:bodyclose // False positive for httptest.ResponseRecorder: https://github.com/timakin/bodyclose/issues/59.
require.Equal(t, http.StatusOK, response.StatusCode)
// verify traces look good
spans := sr.Ended()
require.Len(t, spans, 1)
span := spans[0]
assert.Equal(t, "/user/:id", span.Name())
assert.Equal(t, oteltrace.SpanKindServer, span.SpanKind())
attr := span.Attributes()
assert.Contains(t, attr, attribute.String("net.host.name", "foobar"))
assert.Contains(t, attr, attribute.Int("http.status_code", http.StatusOK))
assert.Contains(t, attr, attribute.String("http.method", "GET"))
assert.Contains(t, attr, attribute.String("http.route", "/user/:id"))
}
func TestError(t *testing.T) {
sr := tracetest.NewSpanRecorder()
provider := sdktrace.NewTracerProvider(sdktrace.WithSpanProcessor(sr))
// setup
router := gin.New()
router.Use(otelgin.Middleware("foobar", otelgin.WithTracerProvider(provider)))
// configure a handler that returns an error and 5xx status
// code
router.GET("/server_err", func(c *gin.Context) {
_ = c.AbortWithError(http.StatusInternalServerError, errors.New("oh no"))
})
r := httptest.NewRequest("GET", "/server_err", nil)
w := httptest.NewRecorder()
router.ServeHTTP(w, r)
response := w.Result() //nolint:bodyclose // False positive for httptest.ResponseRecorder: https://github.com/timakin/bodyclose/issues/59.
assert.Equal(t, http.StatusInternalServerError, response.StatusCode)
// verify the errors and status are correct
spans := sr.Ended()
require.Len(t, spans, 1)
span := spans[0]
assert.Equal(t, "/server_err", span.Name())
attr := span.Attributes()
assert.Contains(t, attr, attribute.String("net.host.name", "foobar"))
assert.Contains(t, attr, attribute.Int("http.status_code", http.StatusInternalServerError))
assert.Contains(t, attr, attribute.String("gin.errors", "Error #01: oh no\n"))
// server errors set the status
assert.Equal(t, codes.Error, span.Status().Code)
}
func TestSpanStatus(t *testing.T) {
testCases := []struct {
httpStatusCode int
wantSpanStatus codes.Code
}{
{http.StatusOK, codes.Unset},
{http.StatusBadRequest, codes.Unset},
{http.StatusInternalServerError, codes.Error},
}
for _, tc := range testCases {
t.Run(strconv.Itoa(tc.httpStatusCode), func(t *testing.T) {
sr := tracetest.NewSpanRecorder()
provider := sdktrace.NewTracerProvider()
provider.RegisterSpanProcessor(sr)
router := gin.New()
router.Use(otelgin.Middleware("foobar", otelgin.WithTracerProvider(provider)))
router.GET("/", func(c *gin.Context) {
c.Status(tc.httpStatusCode)
})
router.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest("GET", "/", nil))
require.Len(t, sr.Ended(), 1, "should emit a span")
assert.Equal(t, tc.wantSpanStatus, sr.Ended()[0].Status().Code, "should only set Error status for HTTP statuses >= 500")
})
}
}
func TestSpanName(t *testing.T) {
testCases := []struct {
requestPath string
spanNameFormatter otelgin.SpanNameFormatter
wantSpanName string
}{
{"/user/1", nil, "/user/:id"},
{"/user/1", func(r *http.Request) string { return r.URL.Path }, "/user/1"},
}
for _, tc := range testCases {
t.Run(tc.requestPath, func(t *testing.T) {
sr := tracetest.NewSpanRecorder()
provider := sdktrace.NewTracerProvider()
provider.RegisterSpanProcessor(sr)
router := gin.New()
router.Use(otelgin.Middleware("foobar", otelgin.WithTracerProvider(provider), otelgin.WithSpanNameFormatter(tc.spanNameFormatter)))
router.GET("/user/:id", func(c *gin.Context) {})
router.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest("GET", tc.requestPath, nil))
require.Len(t, sr.Ended(), 1, "should emit a span")
assert.Equal(t, tc.wantSpanName, sr.Ended()[0].Name(), "span name not correct")
})
}
}
func TestHTTPRouteWithSpanNameFormatter(t *testing.T) {
sr := tracetest.NewSpanRecorder()
provider := sdktrace.NewTracerProvider(sdktrace.WithSpanProcessor(sr))
router := gin.New()
router.Use(otelgin.Middleware("foobar",
otelgin.WithTracerProvider(provider),
otelgin.WithSpanNameFormatter(func(r *http.Request) string {
return r.URL.Path
}),
),
)
router.GET("/user/:id", func(c *gin.Context) {
id := c.Param("id")
_, _ = c.Writer.Write([]byte(id))
})
r := httptest.NewRequest("GET", "/user/123", nil)
w := httptest.NewRecorder()
// do and verify the request
router.ServeHTTP(w, r)
response := w.Result() //nolint:bodyclose // False positive for httptest.ResponseRecorder: https://github.com/timakin/bodyclose/issues/59.
require.Equal(t, http.StatusOK, response.StatusCode)
// verify traces look good
spans := sr.Ended()
require.Len(t, spans, 1)
span := spans[0]
assert.Equal(t, "/user/123", span.Name())
assert.Equal(t, oteltrace.SpanKindServer, span.SpanKind())
attr := span.Attributes()
assert.Contains(t, attr, attribute.String("http.method", "GET"))
assert.Contains(t, attr, attribute.String("http.route", "/user/:id"))
}
func TestHTML(t *testing.T) {
sr := tracetest.NewSpanRecorder()
provider := sdktrace.NewTracerProvider(sdktrace.WithSpanProcessor(sr))
// setup
router := gin.New()
router.Use(otelgin.Middleware("foobar", otelgin.WithTracerProvider(provider)))
// add a template
tmpl := template.Must(template.New("hello").Parse("hello {{.}}"))
router.SetHTMLTemplate(tmpl)
// a handler with an error and make the requests
router.GET("/hello", func(c *gin.Context) {
otelgin.HTML(c, http.StatusOK, "hello", "world")
})
r := httptest.NewRequest("GET", "/hello", nil)
w := httptest.NewRecorder()
router.ServeHTTP(w, r)
response := w.Result() //nolint:bodyclose // False positive for httptest.ResponseRecorder: https://github.com/timakin/bodyclose/issues/59.
assert.Equal(t, http.StatusOK, response.StatusCode)
assert.Equal(t, "hello world", w.Body.String())
// verify the errors and status are correct
spans := sr.Ended()
require.Len(t, spans, 2)
var tspan sdktrace.ReadOnlySpan
for _, s := range spans {
// we need to pick up the span we're searching for, as the
// order is not guaranteed within the buffer
if s.Name() == "gin.renderer.html" {
tspan = s
break
}
}
require.NotNil(t, tspan)
assert.Contains(t, tspan.Attributes(), attribute.String("go.template", "hello"))
}
func TestWithFilter(t *testing.T) {
t.Run("custom filter filtering route", func(t *testing.T) {
sr := tracetest.NewSpanRecorder()
otel.SetTracerProvider(sdktrace.NewTracerProvider(sdktrace.WithSpanProcessor(sr)))
router := gin.New()
f := func(req *http.Request) bool { return req.URL.Path != "/healthcheck" }
router.Use(otelgin.Middleware("foobar", otelgin.WithFilter(f)))
router.GET("/healthcheck", func(c *gin.Context) {})
r := httptest.NewRequest("GET", "/healthcheck", nil)
w := httptest.NewRecorder()
router.ServeHTTP(w, r)
assert.Empty(t, sr.Ended())
})
t.Run("custom filter not filtering route", func(t *testing.T) {
sr := tracetest.NewSpanRecorder()
otel.SetTracerProvider(sdktrace.NewTracerProvider(sdktrace.WithSpanProcessor(sr)))
router := gin.New()
f := func(req *http.Request) bool { return req.URL.Path != "/healthcheck" }
router.Use(otelgin.Middleware("foobar", otelgin.WithFilter(f)))
router.GET("/user/:id", func(c *gin.Context) {})
r := httptest.NewRequest("GET", "/user/123", nil)
w := httptest.NewRecorder()
router.ServeHTTP(w, r)
assert.Len(t, sr.Ended(), 1)
})
}
func TestWithGinFilter(t *testing.T) {
t.Run("custom filter filtering route", func(t *testing.T) {
sr := tracetest.NewSpanRecorder()
otel.SetTracerProvider(sdktrace.NewTracerProvider(sdktrace.WithSpanProcessor(sr)))
router := gin.New()
f := func(c *gin.Context) bool { return c.Request.URL.Path != "/healthcheck" }
router.Use(otelgin.Middleware("foobar", otelgin.WithGinFilter(f)))
router.GET("/healthcheck", func(c *gin.Context) {})
r := httptest.NewRequest("GET", "/healthcheck", nil)
w := httptest.NewRecorder()
router.ServeHTTP(w, r)
assert.Empty(t, sr.Ended())
})
t.Run("custom filter not filtering route", func(t *testing.T) {
sr := tracetest.NewSpanRecorder()
otel.SetTracerProvider(sdktrace.NewTracerProvider(sdktrace.WithSpanProcessor(sr)))
router := gin.New()
f := func(c *gin.Context) bool { return c.Request.URL.Path != "/user/:id" }
router.Use(otelgin.Middleware("foobar", otelgin.WithGinFilter(f)))
router.GET("/user/:id", func(c *gin.Context) {})
r := httptest.NewRequest("GET", "/user/123", nil)
w := httptest.NewRecorder()
router.ServeHTTP(w, r)
assert.Len(t, sr.Ended(), 1)
})
}
|