package metrics import ( "net/http" "net/http/httptest" "strings" "testing" ) func TestRegistryRendersCountersWithLabels(t *testing.T) { registry := NewRegistry() registry.AddCounter("vehicle_frames_total", Labels{"protocol": "JT808", "status": "ok"}, 2) registry.IncCounter("vehicle_frames_total", Labels{"status": "ok", "protocol": "JT808"}) registry.IncCounter("vehicle_publish_errors_total", Labels{"target": "kafka"}) text := registry.Render() for _, want := range []string{ `# TYPE vehicle_frames_total counter`, `vehicle_frames_total{protocol="JT808",status="ok"} 3`, `# TYPE vehicle_publish_errors_total counter`, `vehicle_publish_errors_total{target="kafka"} 1`, } { if !strings.Contains(text, want) { t.Fatalf("metrics missing %s:\n%s", want, text) } } } func TestRegistryRendersGaugesWithLabels(t *testing.T) { registry := NewRegistry() registry.SetGauge("vehicle_gateway_connections", Labels{"protocol": "JT808"}, 2) registry.AddGauge("vehicle_gateway_connections", Labels{"protocol": "JT808"}, -1) registry.SetGauge("vehicle_gateway_connections", Labels{"protocol": "GB32960"}, 3) text := registry.Render() for _, want := range []string{ `# TYPE vehicle_gateway_connections gauge`, `vehicle_gateway_connections{protocol="GB32960"} 3`, `vehicle_gateway_connections{protocol="JT808"} 1`, } { if !strings.Contains(text, want) { t.Fatalf("metrics missing %s:\n%s", want, text) } } } func TestHandlerServesPrometheusText(t *testing.T) { registry := NewRegistry() registry.IncCounter("vehicle_kafka_commits_total", Labels{"service": "history"}) handler := NewHandler(registry) request := httptest.NewRequest(http.MethodGet, "/metrics", nil) response := httptest.NewRecorder() handler.ServeHTTP(response, request) if response.Code != http.StatusOK { t.Fatalf("status = %d body=%s", response.Code, response.Body.String()) } if got := response.Header().Get("Content-Type"); !strings.Contains(got, "text/plain") { t.Fatalf("content-type = %q", got) } if !strings.Contains(response.Body.String(), `vehicle_kafka_commits_total{service="history"} 1`) { t.Fatalf("body = %s", response.Body.String()) } } func TestHandlerRejectsNonMetricsPath(t *testing.T) { handler := NewHandler(NewRegistry()) request := httptest.NewRequest(http.MethodGet, "/readyz", nil) response := httptest.NewRecorder() handler.ServeHTTP(response, request) if response.Code != http.StatusNotFound { t.Fatalf("status = %d", response.Code) } }