package process import ( "context" "net/http" "testing" "github.com/stretchr/testify/assert" "github.com/stretchr/testify/require" ) func TestHealthServer_Endpoints_Good(t *testing.T) { hs := NewHealthServer("127.0.0.1:0") err := hs.Start() require.NoError(t, err) defer func() { _ = hs.Stop(context.Background()) }() addr := hs.Addr() require.NotEmpty(t, addr) resp, err := http.Get("http://" + addr + "/health") require.NoError(t, err) assert.Equal(t, http.StatusOK, resp.StatusCode) _ = resp.Body.Close() resp, err = http.Get("http://" + addr + "/ready") require.NoError(t, err) assert.Equal(t, http.StatusOK, resp.StatusCode) _ = resp.Body.Close() hs.SetReady(false) resp, err = http.Get("http://" + addr + "/ready") require.NoError(t, err) assert.Equal(t, http.StatusServiceUnavailable, resp.StatusCode) _ = resp.Body.Close() } func TestHealthServer_WithChecks_Good(t *testing.T) { hs := NewHealthServer("127.0.0.1:0") healthy := true hs.AddCheck(func() error { if !healthy { return assert.AnError } return nil }) err := hs.Start() require.NoError(t, err) defer func() { _ = hs.Stop(context.Background()) }() addr := hs.Addr() resp, err := http.Get("http://" + addr + "/health") require.NoError(t, err) assert.Equal(t, http.StatusOK, resp.StatusCode) _ = resp.Body.Close() healthy = false resp, err = http.Get("http://" + addr + "/health") require.NoError(t, err) assert.Equal(t, http.StatusServiceUnavailable, resp.StatusCode) _ = resp.Body.Close() } func TestHealthServer_StopImmediately_Good(t *testing.T) { hs := NewHealthServer("127.0.0.1:0") require.NoError(t, hs.Start()) require.NoError(t, hs.Stop(context.Background())) } func TestWaitForHealth_Reachable_Good(t *testing.T) { hs := NewHealthServer("127.0.0.1:0") require.NoError(t, hs.Start()) defer func() { _ = hs.Stop(context.Background()) }() ok := WaitForHealth(hs.Addr(), 2_000) assert.True(t, ok) } func TestWaitForHealth_Unreachable_Bad(t *testing.T) { ok := WaitForHealth("127.0.0.1:19999", 500) assert.False(t, ok) }