package health import ( "context" "errors" "net/http" "net/http/httptest" "strings" "testing" "time" ) func TestReadinessReturns503WithTypedDependencyReason(t *testing.T) { handler := ReadinessHandler{Runtime: "test", Probes: []Probe{{Name: "postgres", Check: func(context.Context) error { return errors.New("connection refused") }}}} recorder := httptest.NewRecorder() handler.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/readyz", nil)) if recorder.Code != http.StatusServiceUnavailable || !strings.Contains(recorder.Body.String(), `"reason":"DEPENDENCY_UNAVAILABLE"`) { t.Fatalf("readiness response = %d %s", recorder.Code, recorder.Body.String()) } } func TestReadinessReturns200WhenAllProbesPass(t *testing.T) { handler := ReadinessHandler{Runtime: "test", Probes: []Probe{{Name: "postgres", Check: func(context.Context) error { return nil }}}} recorder := httptest.NewRecorder() handler.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/readyz", nil)) if recorder.Code != http.StatusOK || !strings.Contains(recorder.Body.String(), `"status":"ready"`) { t.Fatalf("readiness response = %d %s", recorder.Code, recorder.Body.String()) } } func TestHTTPProbeWithHeadersSendsHeaders(t *testing.T) { server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.Header.Get("Authorization") != "Bearer health-key" { t.Fatalf("authorization=%q", r.Header.Get("Authorization")) } w.WriteHeader(http.StatusOK) })) defer server.Close() probe := HTTPProbeWithHeaders(server.Client(), server.URL, map[string]string{"Authorization": "Bearer health-key"}) if err := probe.Check(context.Background()); err != nil { t.Fatal(err) } } func TestReadinessUsesPerProbeTimeout(t *testing.T) { handler := ReadinessHandler{Runtime: "test", Timeout: time.Millisecond, Probes: []Probe{{ Name: "slow-but-required", Timeout: time.Second, Check: func(context.Context) error { return nil }, }}} recorder := httptest.NewRecorder() handler.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/readyz", nil)) if recorder.Code != http.StatusOK { t.Fatalf("readiness response = %d %s", recorder.Code, recorder.Body.String()) } } func TestReadinessStaysAvailableWithOptionalDependencyDegraded(t *testing.T) { handler := ReadinessHandler{Runtime: "test", Probes: []Probe{ {Name: "lifeboat", Check: func(context.Context) error { return nil }}, {Name: "opportunistic-gpu", Optional: true, Check: func(context.Context) error { return errors.New("timeout") }}, }} recorder := httptest.NewRecorder() handler.ServeHTTP(recorder, httptest.NewRequest(http.MethodGet, "/readyz", nil)) body := recorder.Body.String() if recorder.Code != http.StatusOK || !strings.Contains(body, `"status":"ready"`) || !strings.Contains(body, `"state":"DEGRADED"`) { t.Fatalf("readiness response = %d %s", recorder.Code, body) } }