67 lines
1.9 KiB
Go
67 lines
1.9 KiB
Go
package metrics
|
|
|
|
import (
|
|
"net/http/httptest"
|
|
"strings"
|
|
"testing"
|
|
|
|
"github.com/prometheus/client_golang/prometheus/testutil"
|
|
)
|
|
|
|
// TestRegistry_ContainsCoreMetrics 验收项:Registry 含核心指标定义。
|
|
// Vec 类指标需先实例化标签(Handler 场景下由请求埋点产生)再计数。
|
|
func TestRegistry_ContainsCoreMetrics(t *testing.T) {
|
|
HTTPRequestsTotal.WithLabelValues("GET", "/t", "200").Inc()
|
|
HTTPRequestDuration.WithLabelValues("GET", "/t").Observe(0.01)
|
|
SMSSubmitTotal.WithLabelValues("ok").Inc()
|
|
SMSReportTotal.WithLabelValues("DELIVRD").Inc()
|
|
KafkaProducerMessages.WithLabelValues("sms-submit", "ok").Inc()
|
|
|
|
for _, name := range []string{
|
|
"http_requests_total",
|
|
"http_request_duration_seconds",
|
|
"http_requests_in_flight",
|
|
"sms_submit_total",
|
|
"sms_report_total",
|
|
"kafka_producer_messages_total",
|
|
} {
|
|
if got := testutil.CollectAndCount(Registry(), name); got == 0 {
|
|
t.Errorf("Registry 缺少指标 %s", name)
|
|
}
|
|
}
|
|
}
|
|
|
|
// TestHandler_ExposesMetrics 验收项:Handler 输出含 HELP/TYPE 与指标族名。
|
|
func TestHandler_ExposesMetrics(t *testing.T) {
|
|
// 预置数据
|
|
HTTPRequestsTotal.WithLabelValues("GET", "/health", "200").Inc()
|
|
HTTPRequestDuration.WithLabelValues("GET", "/health").Observe(0.012)
|
|
HTTPRequestsInFlight.Set(2)
|
|
|
|
srv := httptest.NewServer(Handler())
|
|
defer srv.Close()
|
|
|
|
resp, err := srv.Client().Get(srv.URL)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
defer func() { _ = resp.Body.Close() }()
|
|
body := make([]byte, 1<<20)
|
|
n, _ := resp.Body.Read(body)
|
|
out := string(body[:n])
|
|
|
|
for _, want := range []string{
|
|
"http_requests_total",
|
|
"http_request_duration_seconds",
|
|
"http_request_duration_seconds_bucket",
|
|
"http_requests_in_flight",
|
|
`{method="GET",route="/health",status="200"}`,
|
|
`{method="GET",route="/health"}`,
|
|
"go_goroutines", // Go 运行时指标
|
|
} {
|
|
if !strings.Contains(out, want) {
|
|
t.Errorf("/metrics 输出缺少 %q", want)
|
|
}
|
|
}
|
|
}
|