74 lines
2.2 KiB
Go
74 lines
2.2 KiB
Go
package health
|
|
|
|
import (
|
|
"context"
|
|
"encoding/json"
|
|
"errors"
|
|
"net/http"
|
|
"net/http/httptest"
|
|
"testing"
|
|
"time"
|
|
|
|
omni "git.yuntuo.hk/k2safe/go-omni"
|
|
"git.yuntuo.hk/k2safe/go-omni/transport/nethttp"
|
|
)
|
|
|
|
func TestCheckerReadinessReportsAllProbes(t *testing.T) {
|
|
checker, err := New(
|
|
Probe{Name: "database", Check: func(context.Context) error { return nil }},
|
|
Probe{Name: "cache", Check: func(context.Context) error { return errors.New("connection refused") }},
|
|
)
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
app := omni.NewWithRouter(nethttp.New())
|
|
app.GET("/live", checker.LivenessHandler())
|
|
app.GET("/ready", checker.ReadinessHandler())
|
|
|
|
live := httptest.NewRecorder()
|
|
app.ServeHTTP(live, httptest.NewRequest(http.MethodGet, "/live", nil))
|
|
if live.Code != http.StatusOK {
|
|
t.Fatalf("expected liveness 200, got %d", live.Code)
|
|
}
|
|
|
|
ready := httptest.NewRecorder()
|
|
app.ServeHTTP(ready, httptest.NewRequest(http.MethodGet, "/ready", nil))
|
|
if ready.Code != http.StatusServiceUnavailable {
|
|
t.Fatalf("expected readiness 503, got %d", ready.Code)
|
|
}
|
|
var body struct {
|
|
Code string `json:"code"`
|
|
Data Result `json:"data"`
|
|
}
|
|
if err := json.Unmarshal(ready.Body.Bytes(), &body); err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
if body.Code != "NOT_READY" || body.Data.Status != StatusNotReady || len(body.Data.Checks) != 2 || body.Data.Checks[1].Error != "connection refused" {
|
|
t.Fatalf("unexpected readiness response: %+v", body)
|
|
}
|
|
}
|
|
|
|
func TestCheckerTimeoutAndRegistrationValidation(t *testing.T) {
|
|
checker, err := New(Probe{
|
|
Name: "slow",
|
|
Timeout: 5 * time.Millisecond,
|
|
Check: func(ctx context.Context) error {
|
|
<-ctx.Done()
|
|
return ctx.Err()
|
|
},
|
|
})
|
|
if err != nil {
|
|
t.Fatal(err)
|
|
}
|
|
result := checker.Check(context.Background())
|
|
if result.Ready() || result.Checks[0].Status != StatusNotReady {
|
|
t.Fatalf("expected timeout to fail readiness: %+v", result)
|
|
}
|
|
|
|
for _, probe := range []Probe{{Check: func(context.Context) error { return nil }}, {Name: "slow", Check: func(context.Context) error { return nil }}, {Name: "negative", Timeout: -time.Second, Check: func(context.Context) error { return nil }}} {
|
|
if err := checker.Add(probe); err == nil {
|
|
t.Fatalf("expected registration error for %+v", probe)
|
|
}
|
|
}
|
|
}
|