| 1 | package health |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "errors" |
| 6 | "net/http" |
| 7 | "net/http/httptest" |
| 8 | "testing" |
| 9 | ) |
| 10 | |
| 11 | // Ready follows what the process needs, and it says no for good once we leave. |
| 12 | // Live says yes through all of it. |
| 13 | func TestReady(t *testing.T) { |
| 14 | var postgres error |
| 15 | h := New(func(context.Context) error { return postgres }) |
| 16 | mux := http.NewServeMux() |
| 17 | h.Routes(mux) |
| 18 | ask := func(path string) int { |
| 19 | rec := httptest.NewRecorder() |
| 20 | mux.ServeHTTP(rec, httptest.NewRequest("GET", path, nil)) |
| 21 | return rec.Code |
| 22 | } |
| 23 | for _, step := range []struct { |
| 24 | name string |
| 25 | do func() |
| 26 | ready int |
| 27 | }{ |
| 28 | {"at the start", func() {}, 200}, |
| 29 | {"postgres is away", func() { postgres = errors.New("no answer") }, 503}, |
| 30 | {"postgres is back", func() { postgres = nil }, 200}, |
| 31 | {"we are leaving", h.Leave, 503}, |
| 32 | } { |
| 33 | step.do() |
| 34 | if got := ask("/readyz"); got != step.ready { |
| 35 | t.Errorf("%s: ready says %d, want %d", step.name, got, step.ready) |
| 36 | } |
| 37 | if got := ask("/healthz"); got != 200 { |
| 38 | t.Errorf("%s: live says %d, want 200", step.name, got) |
| 39 | } |
| 40 | } |
| 41 | } |