61 lines
1.8 KiB
Go
61 lines
1.8 KiB
Go
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 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)
|
|
}
|
|
}
|