Files
obsx/health_test.go
T
M.ShakhmatovandClaude Opus 5.5 5cd2375d37 Add liveness and readiness health checks
Concurrent checks with per-check timeouts and panic recovery, HTTP
handlers, grpc.health.v1 server, SetReady for graceful shutdown and
the health_check_status metric.

Co-Authored-By: Claude Opus 5.5 <noreply@anthropic.com>
2026-10-30 00:18:43 +03:00

120 lines
3.5 KiB
Go

package obsx
import (
"context"
"encoding/json"
"errors"
"net/http"
"net/http/httptest"
"strings"
"testing"
"time"
)
func TestHealth_NoChecks(t *testing.T) {
h := NewHealth(HealthConfig{})
if r := h.CheckLiveness(context.Background()); !r.Healthy() {
t.Errorf("liveness = %+v, want ok", r)
}
if r := h.CheckReadiness(context.Background()); !r.Healthy() {
t.Errorf("readiness = %+v, want ok", r)
}
}
func TestHealth_ReadinessChecks(t *testing.T) {
m := NewMetrics(MetricsConfig{})
h := NewHealth(HealthConfig{Timeout: 50 * time.Millisecond, Metrics: m})
h.AddReadinessCheck("db", func(ctx context.Context) error { return nil })
h.AddReadinessCheck("cache", func(ctx context.Context) error { return errors.New("connection refused") })
h.AddReadinessCheck("slow", func(ctx context.Context) error {
<-ctx.Done()
return ctx.Err()
})
h.AddReadinessCheck("stuck", func(ctx context.Context) error {
time.Sleep(time.Second) // ignores ctx; must not block the probe
return nil
})
h.AddReadinessCheck("panics", func(ctx context.Context) error { panic("oops") })
start := time.Now()
r := h.CheckReadiness(context.Background())
if elapsed := time.Since(start); elapsed > 500*time.Millisecond {
t.Errorf("readiness took %s, checks must time out", elapsed)
}
if r.Healthy() {
t.Fatal("readiness must fail")
}
if r.Checks["db"].Status != StatusOK {
t.Errorf("db = %+v", r.Checks["db"])
}
if c := r.Checks["cache"]; c.Status != StatusFail || c.Error != "connection refused" {
t.Errorf("cache = %+v", c)
}
if c := r.Checks["stuck"]; c.Status != StatusFail || !strings.Contains(c.Error, "timed out") {
t.Errorf("stuck = %+v", c)
}
if c := r.Checks["panics"]; c.Status != StatusFail || !strings.Contains(c.Error, "panic: oops") {
t.Errorf("panics = %+v", c)
}
// Liveness is independent of readiness checks.
if !h.CheckLiveness(context.Background()).Healthy() {
t.Error("liveness must not include readiness checks")
}
body := scrape(t, m)
for _, want := range []string{
`health_check_status{check="db",kind="readiness"} 1`,
`health_check_status{check="cache",kind="readiness"} 0`,
} {
if !strings.Contains(body, want) {
t.Errorf("metrics missing %q", want)
}
}
}
func TestHealth_SetReady(t *testing.T) {
h := NewHealth(HealthConfig{})
called := false
h.AddReadinessCheck("db", func(ctx context.Context) error { called = true; return nil })
h.SetReady(false)
r := h.CheckReadiness(context.Background())
if r.Healthy() || called {
t.Errorf("not-ready service must fail without running checks: %+v called=%v", r, called)
}
h.SetReady(true)
if !h.CheckReadiness(context.Background()).Healthy() || !called {
t.Error("ready service must run checks and pass")
}
}
func TestHealth_Handlers(t *testing.T) {
h := NewHealth(HealthConfig{})
h.AddLivenessCheck("deadlock", func(ctx context.Context) error { return errors.New("stuck") })
w := httptest.NewRecorder()
h.LivenessHandler().ServeHTTP(w, httptest.NewRequest("GET", "/healthz", nil))
if w.Code != http.StatusServiceUnavailable {
t.Errorf("liveness code = %d, want 503", w.Code)
}
var r Report
if err := json.Unmarshal(w.Body.Bytes(), &r); err != nil {
t.Fatal(err)
}
if r.Status != StatusFail || r.Checks["deadlock"].Error != "stuck" {
t.Errorf("unexpected report: %+v", r)
}
if ct := w.Header().Get("Content-Type"); ct != "application/json" {
t.Errorf("Content-Type = %q", ct)
}
w = httptest.NewRecorder()
h.ReadinessHandler().ServeHTTP(w, httptest.NewRequest("GET", "/readyz", nil))
if w.Code != http.StatusOK {
t.Errorf("readiness code = %d, want 200", w.Code)
}
}