46 lines
1.6 KiB
Go
46 lines
1.6 KiB
Go
package middleware
|
|
|
|
import (
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"testing"
|
|
|
|
"github.com/gin-gonic/gin"
|
|
"github.com/prometheus/client_golang/prometheus/testutil"
|
|
|
|
"go-sms/internal/pkg/metrics"
|
|
)
|
|
|
|
// TestMetricsMiddleware_CountsAndDuration 验证请求埋点:计数/耗时/在途回落。
|
|
func TestMetricsMiddleware_CountsAndDuration(t *testing.T) {
|
|
gin.SetMode(gin.TestMode)
|
|
r := gin.New()
|
|
r.Use(Metrics())
|
|
r.GET("/ping", func(c *gin.Context) { c.String(200, "pong") })
|
|
r.GET("/boom", func(c *gin.Context) { c.String(500, "err") })
|
|
|
|
for i := 0; i < 3; i++ {
|
|
r.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest(http.MethodGet, "/ping", nil))
|
|
}
|
|
r.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest(http.MethodGet, "/boom", nil))
|
|
r.ServeHTTP(httptest.NewRecorder(), httptest.NewRequest(http.MethodGet, "/not-exist", nil)) // unmatched
|
|
|
|
if got := testutil.ToFloat64(metrics.HTTPRequestsTotal.WithLabelValues("GET", "/ping", "200")); got != 3 {
|
|
t.Errorf("/ping 200 计数 = %v, 期望 3", got)
|
|
}
|
|
if got := testutil.ToFloat64(metrics.HTTPRequestsTotal.WithLabelValues("GET", "/boom", "500")); got != 1 {
|
|
t.Errorf("/boom 500 计数 = %v, 期望 1", got)
|
|
}
|
|
if got := testutil.ToFloat64(metrics.HTTPRequestsTotal.WithLabelValues("GET", "unmatched", "404")); got != 1 {
|
|
t.Errorf("unmatched 计数 = %v, 期望 1", got)
|
|
}
|
|
// 耗时观测:>0 计数 3
|
|
if got := testutil.CollectAndCount(metrics.HTTPRequestDuration); got == 0 {
|
|
t.Error("耗时直方图无观测")
|
|
}
|
|
// 在途数回落为 0(请求结束后 Dec)
|
|
if got := testutil.ToFloat64(metrics.HTTPRequestsInFlight); got != 0 {
|
|
t.Errorf("在途数 = %v, 期望 0", got)
|
|
}
|
|
}
|