github.com/msales/pkg/v3@v3.24.0/health/handler_test.go (about) 1 package health_test 2 3 import ( 4 "errors" 5 "net/http" 6 "net/http/httptest" 7 "testing" 8 9 "github.com/msales/pkg/v3/health" 10 "github.com/stretchr/testify/assert" 11 ) 12 13 func Test_NullHealthReporter(t *testing.T) { 14 assert.NoError(t, health.Null().IsHealthy()) 15 } 16 17 func TestHandler_With(t *testing.T) { 18 h := health.NewHandler() 19 r1 := &testReporter{} 20 r2 := &testReporter{} 21 22 h.With(r1, r2) 23 24 w := httptest.NewRecorder() 25 req := httptest.NewRequest("GET", "/health", nil) 26 h.ServeHTTP(w, req) 27 assert.True(t, r1.called) 28 assert.True(t, r2.called) 29 } 30 31 func TestHandler_WithErrors(t *testing.T) { 32 h := health.NewHandler() 33 h.With(&testReporter{err: errors.New("test")}) 34 35 h.WithErrors() 36 37 w := httptest.NewRecorder() 38 req := httptest.NewRequest("GET", "/health", nil) 39 h.ServeHTTP(w, req) 40 assert.Equal(t, "test\n", w.Body.String()) 41 } 42 43 func TestHandler_ServeHTTP(t *testing.T) { 44 tests := []struct { 45 reporterErrs []error 46 code int 47 }{ 48 {[]error{nil}, http.StatusOK}, 49 {[]error{nil, nil}, http.StatusOK}, 50 {[]error{errors.New("")}, http.StatusServiceUnavailable}, 51 {[]error{errors.New(""), nil}, http.StatusServiceUnavailable}, 52 {[]error{nil, errors.New("")}, http.StatusServiceUnavailable}, 53 {[]error{errors.New(""), errors.New("")}, http.StatusServiceUnavailable}, 54 } 55 56 for _, tt := range tests { 57 var reporters []health.Reporter 58 59 for _, err := range tt.reporterErrs { 60 r := &testReporter{err: err} 61 reporters = append(reporters, r) 62 } 63 64 h := (health.NewHandler()).With(reporters...) 65 66 w := httptest.NewRecorder() 67 req := httptest.NewRequest("GET", "/health", nil) 68 69 h.ServeHTTP(w, req) 70 71 assert.Equal(t, tt.code, w.Code) 72 } 73 } 74 75 type testReporter struct { 76 called bool 77 err error 78 } 79 80 func (r *testReporter) IsHealthy() error { 81 r.called = true 82 83 return r.err 84 } 85 86 func TestReporterFunc_IsHealthy(t *testing.T) { 87 err := errors.New("test") 88 reporter := health.ReporterFunc(func() error { return err }) 89 result := reporter.IsHealthy() 90 91 assert.True(t, err == result) 92 }