65 lines
1.6 KiB
Go
65 lines
1.6 KiB
Go
package obsx
|
|
|
|
import (
|
|
"io"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"strings"
|
|
"testing"
|
|
)
|
|
|
|
func TestMetrics_Counter(t *testing.T) {
|
|
m := NewMetrics(MetricsConfig{Namespace: "test"})
|
|
c := m.Counter("requests_total", "Total requests", "method")
|
|
c.WithLabelValues("GET").Inc()
|
|
c.WithLabelValues("GET").Inc()
|
|
c.WithLabelValues("POST").Inc()
|
|
|
|
body := scrape(t, m)
|
|
if !strings.Contains(body, `test_requests_total{method="GET"} 2`) {
|
|
t.Errorf("expected GET counter=2, got:\n%s", body)
|
|
}
|
|
if !strings.Contains(body, `test_requests_total{method="POST"} 1`) {
|
|
t.Errorf("expected POST counter=1, got:\n%s", body)
|
|
}
|
|
}
|
|
|
|
func TestMetrics_Histogram(t *testing.T) {
|
|
m := NewMetrics(MetricsConfig{Namespace: "test"})
|
|
h := m.Histogram("duration_seconds", "Duration", nil, "op")
|
|
h.WithLabelValues("query").Observe(0.1)
|
|
|
|
body := scrape(t, m)
|
|
if !strings.Contains(body, "test_duration_seconds") {
|
|
t.Errorf("expected histogram, got:\n%s", body)
|
|
}
|
|
}
|
|
|
|
func TestMetrics_Gauge(t *testing.T) {
|
|
m := NewMetrics(MetricsConfig{Namespace: "test"})
|
|
g := m.Gauge("connections", "Active connections", "pool")
|
|
g.WithLabelValues("main").Set(42)
|
|
|
|
body := scrape(t, m)
|
|
if !strings.Contains(body, `test_connections{pool="main"} 42`) {
|
|
t.Errorf("expected gauge=42, got:\n%s", body)
|
|
}
|
|
}
|
|
|
|
func TestMetrics_Handler(t *testing.T) {
|
|
m := NewMetrics(MetricsConfig{})
|
|
handler := m.Handler()
|
|
if handler == nil {
|
|
t.Fatal("Handler returned nil")
|
|
}
|
|
}
|
|
|
|
func scrape(t *testing.T, m *Metrics) string {
|
|
t.Helper()
|
|
w := httptest.NewRecorder()
|
|
r, _ := http.NewRequest("GET", "/metrics", nil)
|
|
m.Handler().ServeHTTP(w, r)
|
|
body, _ := io.ReadAll(w.Body)
|
|
return string(body)
|
|
}
|