package health import ( "context" "encoding/json" "errors" "net/http" "net/http/httptest" "testing" ) func TestHealthzAlwaysOK(t *testing.T) { h := New() rr := httptest.NewRecorder() h.Healthz(rr, httptest.NewRequestWithContext(t.Context(), "GET", "/healthz", http.NoBody)) if rr.Code != 200 { t.Errorf("status = %d", rr.Code) } if rr.Body.String() != "ok" { t.Errorf("body = %q", rr.Body.String()) } } func TestReadyzNoCheckersIsOK(t *testing.T) { h := New() rr := httptest.NewRecorder() h.Readyz(rr, httptest.NewRequestWithContext(t.Context(), "GET", "/readyz", http.NoBody)) if rr.Code != 200 { t.Errorf("status = %d", rr.Code) } var body map[string]string if err := json.Unmarshal(rr.Body.Bytes(), &body); err != nil { t.Fatalf("decode: %v", err) } if len(body) != 0 { t.Errorf("expected empty results, got %v", body) } } func TestReadyzAllPass(t *testing.T) { h := New() h.Register("db", CheckerFunc(func(_ context.Context) error { return nil })) h.Register("cache", CheckerFunc(func(_ context.Context) error { return nil })) rr := httptest.NewRecorder() h.Readyz(rr, httptest.NewRequestWithContext(t.Context(), "GET", "/readyz", http.NoBody)) if rr.Code != 200 { t.Errorf("status = %d", rr.Code) } var body map[string]string if err := json.Unmarshal(rr.Body.Bytes(), &body); err != nil { t.Fatalf("decode: %v", err) } if body["db"] != "ok" || body["cache"] != "ok" { t.Errorf("body = %v", body) } } func TestReadyzOneFails(t *testing.T) { h := New() h.Register("db", CheckerFunc(func(_ context.Context) error { return nil })) h.Register("upstream", CheckerFunc(func(_ context.Context) error { return errors.New("dns fail") })) rr := httptest.NewRecorder() h.Readyz(rr, httptest.NewRequestWithContext(t.Context(), "GET", "/readyz", http.NoBody)) if rr.Code != 503 { t.Errorf("status = %d, want 503", rr.Code) } var body map[string]string if err := json.Unmarshal(rr.Body.Bytes(), &body); err != nil { t.Fatalf("decode: %v", err) } if body["db"] != "ok" { t.Errorf("db = %q", body["db"]) } if body["upstream"] != "dns fail" { t.Errorf("upstream = %q", body["upstream"]) } } func TestRegisterReplaces(t *testing.T) { h := New() h.Register("svc", CheckerFunc(func(_ context.Context) error { return errors.New("first") })) h.Register("svc", CheckerFunc(func(_ context.Context) error { return nil })) rr := httptest.NewRecorder() h.Readyz(rr, httptest.NewRequestWithContext(t.Context(), "GET", "/readyz", http.NoBody)) if rr.Code != 200 { t.Errorf("status = %d, want 200 after replace", rr.Code) } }