package obsx import ( "context" "database/sql" "database/sql/driver" "errors" "io" "net/http" "net/http/httptest" "strings" "testing" sdktrace "go.opentelemetry.io/otel/sdk/trace" ) 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) } func TestMetrics_Sub(t *testing.T) { m := NewMetrics(MetricsConfig{Namespace: "app"}) m.Sub("db").Counter("queries_total", "Queries").WithLabelValues().Inc() if !strings.Contains(scrape(t, m), "app_db_queries_total 1") { t.Error("Sub factory must share the registry and namespace") } } func TestMetrics_IdempotentRegistration(t *testing.T) { m := NewMetrics(MetricsConfig{}) a := m.Counter("events_total", "Events", "kind") b := m.Counter("events_total", "Events", "kind") if a != b { t.Error("registering an identical metric must return the existing collector") } defer func() { if recover() == nil { t.Error("conflicting registration must panic") } }() m.Counter("events_total", "Events", "other_label") } func TestMetrics_Funcs(t *testing.T) { m := NewMetrics(MetricsConfig{Namespace: "q"}) m.GaugeFunc("depth", "Queue depth", func() float64 { return 7 }) m.CounterFunc("processed_total", "Processed", func() float64 { return 3 }) body := scrape(t, m) if !strings.Contains(body, "q_depth 7") || !strings.Contains(body, "q_processed_total 3") { t.Errorf("func metrics missing:\n%s", body) } } func TestMetrics_DBStats(t *testing.T) { m := NewMetrics(MetricsConfig{}) // sql.OpenDB does not dial, so no real database is needed. db := sql.OpenDB(nopConnector{}) defer db.Close() m.RegisterDBStats(db, "main") m.RegisterDBStats(db, "main") // idempotent if !strings.Contains(scrape(t, m), `go_sql_max_open_connections{db_name="main"}`) { t.Error("db stats missing") } } func TestMetrics_Exemplars(t *testing.T) { m := NewMetrics(MetricsConfig{}) h := m.Histogram("latency_seconds", "Latency", nil) tp := sdktrace.NewTracerProvider() ctx, span := tp.Tracer("t").Start(context.Background(), "op") observe(ctx, h.WithLabelValues(), 0.2) span.End() w := httptest.NewRecorder() r := httptest.NewRequest("GET", "/metrics", nil) r.Header.Set("Accept", "application/openmetrics-text; version=1.0.0") m.Handler().ServeHTTP(w, r) if !strings.Contains(w.Body.String(), `# {trace_id="`+span.SpanContext().TraceID().String()+`"} 0.2`) { t.Errorf("exemplar missing from OpenMetrics output:\n%s", w.Body.String()) } } type nopConnector struct{} func (nopConnector) Connect(context.Context) (driver.Conn, error) { return nil, errors.New("no db") } func (nopConnector) Driver() driver.Driver { return nil }