health_test.go46 lines, 1.2 KB
| 1 | package health_test |
| 2 | |
| 3 | import ( |
| 4 | "context" |
| 5 | "errors" |
| 6 | "log/slog" |
| 7 | "net/http" |
| 8 | "net/http/httptest" |
| 9 | "testing" |
| 10 | |
| 11 | "github.com/fiston-user/payments/internal/platform/health" |
| 12 | ) |
| 13 | |
| 14 | func TestProbes(t *testing.T) { |
| 15 | t.Parallel() |
| 16 | tests := []struct { |
| 17 | name string |
| 18 | err error // what the database check returns |
| 19 | drain bool |
| 20 | ready int // /readyz's status: /healthz must always be 200 |
| 21 | }{ |
| 22 | {"ready", nil, false, http.StatusOK}, |
| 23 | {"database down", errors.New("connection refused"), false, http.StatusServiceUnavailable}, |
| 24 | {"draining", nil, true, http.StatusServiceUnavailable}, |
| 25 | } |
| 26 | for _, tt := range tests { |
| 27 | t.Run(tt.name, func(t *testing.T) { |
| 28 | t.Parallel() |
| 29 | p := health.New(slog.New(slog.DiscardHandler), map[string]health.Check{ |
| 30 | "postgres": func(context.Context) error { return tt.err }, |
| 31 | }) |
| 32 | if tt.drain { |
| 33 | p.Drain(0) |
| 34 | } |
| 35 | mux := http.NewServeMux() |
| 36 | p.Register(mux) |
| 37 | for path, want := range map[string]int{"/healthz": http.StatusOK, "/readyz": tt.ready} { |
| 38 | rr := httptest.NewRecorder() |
| 39 | mux.ServeHTTP(rr, httptest.NewRequest("GET", path, nil)) |
| 40 | if rr.Code != want { |
| 41 | t.Errorf("%s: status %d, want %d", path, rr.Code, want) |
| 42 | } |
| 43 | } |
| 44 | }) |
| 45 | } |
| 46 | } |