From 056a308b2a8da4d20d8e8819d6c6b930cc67e3e1 Mon Sep 17 00:00:00 2001 From: TheFox0x7 Date: Thu, 23 Jan 2025 23:59:44 +0100 Subject: [PATCH] test(metrics): add middleware test --- go.mod | 1 + routers/common/middleware.go | 2 +- routers/common/middleware_test.go | 24 ++++++++++++++++-------- 3 files changed, 18 insertions(+), 9 deletions(-) diff --git a/go.mod b/go.mod index 69f5b2728d2..88e495d9ed9 100644 --- a/go.mod +++ b/go.mod @@ -242,6 +242,7 @@ require ( github.com/klauspost/pgzip v1.2.6 // indirect github.com/kr/pretty v0.3.1 // indirect github.com/kr/text v0.2.0 // indirect + github.com/kylelemons/godebug v1.1.0 // indirect github.com/libdns/libdns v0.2.2 // indirect github.com/magiconair/properties v1.8.7 // indirect github.com/mailru/easyjson v0.7.7 // indirect diff --git a/routers/common/middleware.go b/routers/common/middleware.go index 30484583fd4..5d7a2ee03e2 100644 --- a/routers/common/middleware.go +++ b/routers/common/middleware.go @@ -165,7 +165,7 @@ func RouteMetrics() func(h http.Handler) http.Handler { route := chi.RouteContext(req.Context()).RoutePattern() code := strconv.Itoa(m.WrittenStatus()) reqDurationHistogram.WithLabelValues(req.Method, code, route).Observe(time.Since(start).Seconds()) - respSizeHistogram.WithLabelValues(req.Method, code, route).Observe(float64(m.Size())) + respSizeHistogram.WithLabelValues(req.Method, code, route).Observe(float64(m.WrittenSize())) size := req.ContentLength if size < 0 { size = 0 diff --git a/routers/common/middleware_test.go b/routers/common/middleware_test.go index 03612faf223..b2ec73c565d 100644 --- a/routers/common/middleware_test.go +++ b/routers/common/middleware_test.go @@ -1,4 +1,4 @@ -package common_test +package common import ( "net/http" @@ -6,25 +6,33 @@ import ( "testing" "time" - "code.gitea.io/gitea/routers/common" - "github.com/go-chi/chi/v5" + "github.com/prometheus/client_golang/prometheus/testutil" + "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestMetricsMiddlewere(t *testing.T) { - - middleware := common.RouteMetrics() + middleware := RouteMetrics() r := chi.NewRouter() r.Use(middleware) r.Get("/", http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { w.Write([]byte("test")) time.Sleep(5 * time.Millisecond) })) - testServer := httptest.NewServer(r) - + // Check all defined metrics + verify := func(i int) { + assert.Equal(t, testutil.CollectAndCount(reqDurationHistogram, "http_server_request_duration"), i) + assert.Equal(t, testutil.CollectAndCount(reqSizeHistogram, "http_server_request_body_size"), i) + assert.Equal(t, testutil.CollectAndCount(respSizeHistogram, "http_server_response_body_size"), i) + assert.Equal(t, testutil.CollectAndCount(reqInflightGauge, "http_server_active_requests"), i) + } + + // Check they don't exist before making a request + verify(0) _, err := http.Get(testServer.URL) require.NoError(t, err) - + // Check they do exist after making the request + verify(1) }