package health import ( "context" "net/http" "net/http/httptest" "strings" "testing" ) func TestCheckHealthyServer(t *testing.T) { srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) { if r.URL.Path != "/healthz" || r.Method != http.MethodGet { http.NotFound(w, r) return } w.Header().Set("Content-Type", "application/json") _, _ = w.Write([]byte(`{"status":"ok"}`)) })) defer srv.Close() rep := Check(context.Background(), srv.Client(), srv.URL) if !rep.OK { t.Fatalf("expected OK, got %+v", rep) } if rep.StatusCode != http.StatusOK || rep.URL != srv.URL+"/healthz" { t.Fatalf("unexpected report %+v", rep) } if !strings.Contains(rep.Detail, "status: ok") { t.Fatalf("detail should quote the status, got %q", rep.Detail) } } func TestCheckNonOriServer(t *testing.T) { srv := httptest.NewServer(http.NotFoundHandler()) defer srv.Close() rep := Check(context.Background(), srv.Client(), srv.URL) if rep.OK { t.Fatalf("expected failure for 404, got %+v", rep) } if rep.StatusCode != http.StatusNotFound || !strings.Contains(rep.Detail, "404") { t.Fatalf("unexpected report %+v", rep) } } func TestCheckUnreachableServer(t *testing.T) { srv := httptest.NewServer(http.NotFoundHandler()) addr := srv.URL srv.Close() // nothing listens there any more rep := Check(context.Background(), nil, addr) if rep.OK || rep.StatusCode != 0 { t.Fatalf("expected transport failure, got %+v", rep) } if !strings.Contains(rep.Detail, "cannot reach ori") { t.Fatalf("unexpected detail %q", rep.Detail) } } func TestCheckPlainOKBody(t *testing.T) { srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, _ *http.Request) { _, _ = w.Write([]byte("OK")) })) defer srv.Close() rep := Check(context.Background(), srv.Client(), srv.URL) if !rep.OK || rep.Detail != "ori is reachable" { t.Fatalf("a 2xx with a non-JSON body must still count as healthy, got %+v", rep) } } func TestCheckCancelledContext(t *testing.T) { ctx, cancel := context.WithCancel(context.Background()) cancel() rep := Check(ctx, nil, "http://127.0.0.1:1") if rep.OK { t.Fatalf("expected failure with a cancelled context, got %+v", rep) } }