Files
archie/internal/platform/telemetry/telemetry_test.go
T

137 lines
4.6 KiB
Go

package telemetry
import (
"bytes"
"context"
json "encoding/json/v2"
"log/slog"
"net/http"
"net/http/httptest"
"strings"
"testing"
"go.opentelemetry.io/otel"
sdktrace "go.opentelemetry.io/otel/sdk/trace"
"go.opentelemetry.io/otel/trace"
)
// TestLogHandlerInjectsTraceAndSpanIDs guards that NewLogHandler attaches
// trace_id and span_id once when a valid span exists in ctx, and omits them
// when no span is active.
func TestLogHandlerInjectsTraceAndSpanIDs(t *testing.T) {
var buf bytes.Buffer
handler := NewLogHandler(NewLogHandler(slog.NewJSONHandler(&buf, nil)))
logger := slog.New(handler)
logger.InfoContext(t.Context(), "without span")
if strings.Contains(buf.String(), "trace_id") || strings.Contains(buf.String(), "span_id") {
t.Fatalf("unexpected trace fields without span: %s", buf.String())
}
buf.Reset()
tp := sdktrace.NewTracerProvider()
t.Cleanup(func() { _ = tp.Shutdown(context.Background()) })
ctx, span := tp.Tracer("telemetry-test").Start(t.Context(), "op")
defer span.End()
logger.InfoContext(ctx, "with span")
line := buf.String()
if strings.Count(line, `"trace_id"`) != 1 || strings.Count(line, `"span_id"`) != 1 {
t.Fatalf("expected single trace_id and span_id fields, got: %s", line)
}
var parsed map[string]any
if err := json.Unmarshal(bytes.TrimSpace(buf.Bytes()), &parsed); err != nil {
t.Fatalf("unmarshal log line: %v (%s)", err, line)
}
if parsed["trace_id"] != span.SpanContext().TraceID().String() {
t.Fatalf("trace_id = %v, want %s", parsed["trace_id"], span.SpanContext().TraceID().String())
}
if parsed["span_id"] != span.SpanContext().SpanID().String() {
t.Fatalf("span_id = %v, want %s", parsed["span_id"], span.SpanContext().SpanID().String())
}
}
// TestMetricsMiddlewareAndPrometheusOutput guards HTTP span creation, request
// status counting, and Prometheus text exposition formatting.
func TestMetricsMiddlewareAndPrometheusOutput(t *testing.T) {
prevTP := otel.GetTracerProvider()
tp := sdktrace.NewTracerProvider()
otel.SetTracerProvider(tp)
t.Cleanup(func() {
otel.SetTracerProvider(prevTP)
_ = tp.Shutdown(context.Background())
})
m := NewMetrics()
var sawValidSpan bool
var probeHadSpan bool
mux := http.NewServeMux()
mux.HandleFunc("/api/ok", func(w http.ResponseWriter, r *http.Request) {
sawValidSpan = trace.SpanContextFromContext(r.Context()).IsValid()
w.WriteHeader(http.StatusOK)
})
mux.HandleFunc("/api/missing", func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusNotFound)
})
mux.HandleFunc("/api/fail", func(w http.ResponseWriter, _ *http.Request) {
w.WriteHeader(http.StatusInternalServerError)
})
mux.HandleFunc("/healthz", func(w http.ResponseWriter, r *http.Request) {
probeHadSpan = trace.SpanContextFromContext(r.Context()).IsValid()
w.WriteHeader(http.StatusOK)
})
wrapped := m.Middleware(mux)
for _, path := range []string{"/api/ok", "/api/missing", "/api/fail", "/healthz"} {
rec := httptest.NewRecorder()
wrapped.ServeHTTP(rec, httptest.NewRequestWithContext(t.Context(), http.MethodGet, path, nil))
}
if !sawValidSpan {
t.Fatal("expected otelhttp middleware to create a valid span for /api/ok")
}
if probeHadSpan {
t.Fatal("expected /healthz probe to be excluded from otelhttp span creation")
}
metricsRec := httptest.NewRecorder()
m.MetricsHandler().ServeHTTP(metricsRec, httptest.NewRequestWithContext(t.Context(), http.MethodGet, "/metrics", nil))
if metricsRec.Code != http.StatusOK {
t.Fatalf("/metrics status = %d, want 200", metricsRec.Code)
}
if gotCT := metricsRec.Header().Get("Content-Type"); gotCT != metricsMediaType {
t.Fatalf("/metrics Content-Type = %q, want %q", gotCT, metricsMediaType)
}
body := metricsRec.Body.String()
for _, want := range []string{
"archie_uptime_seconds ",
"archie_http_requests_in_flight 0",
`archie_http_requests_total{status="2xx"} 2`,
`archie_http_requests_total{status="4xx"} 1`,
`archie_http_requests_total{status="5xx"} 1`,
"archie_http_request_duration_seconds_count 4",
"archie_http_request_duration_seconds_sum ",
"go_goroutines ",
"go_memstats_alloc_bytes ",
"go_gc_cycles_total ",
} {
if !strings.Contains(body, want) {
t.Fatalf("/metrics output missing %q:\n%s", want, body)
}
}
}
// TestSetupWithoutEndpoint guards that Setup succeeds as a no-op when
// OTEL_EXPORTER_OTLP_ENDPOINT is unset.
func TestSetupWithoutEndpoint(t *testing.T) {
t.Setenv(otlpEndpointEnv, "")
shutdown, err := Setup(t.Context(), "archie", "test")
if err != nil {
t.Fatalf("Setup() error = %v", err)
}
if err := shutdown(t.Context()); err != nil {
t.Fatalf("shutdown() error = %v", err)
}
}