-
Notifications
You must be signed in to change notification settings - Fork 31
/
health_test.go
266 lines (208 loc) · 8.23 KB
/
health_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
73
74
75
76
77
78
79
80
81
82
83
84
85
86
87
88
89
90
91
92
93
94
95
96
97
98
99
100
101
102
103
104
105
106
107
108
109
110
111
112
113
114
115
116
117
118
119
120
121
122
123
124
125
126
127
128
129
130
131
132
133
134
135
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
package gosundheit_test
import (
"context"
"errors"
"fmt"
"sync"
"testing"
"time"
"github.com/fortytw2/leaktest"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/mock"
. "github.com/AppsFlyer/go-sundheit"
"github.com/AppsFlyer/go-sundheit/checks"
)
const (
successMsg = "success"
failedMsg = "failed"
failingCheckName = "failing.check"
passingCheckName = "passing.check"
initiallyPassingCheckName = "initially.passing.check"
)
func TestHealthWithEmptySetup(t *testing.T) {
h := New()
assert.True(t, h.IsHealthy(), "empty health")
results, healthy := h.Results()
assert.True(t, healthy, "results of empty setup")
assert.Empty(t, results, "results of empty setup")
h.DeregisterAll()
}
func TestHealthWithBogusCheck(t *testing.T) {
h := New()
err := h.RegisterCheck(nil)
defer h.DeregisterAll()
assert.EqualError(t, err, "check must not be nil")
assert.True(t, h.IsHealthy(), "health after bogus register")
results, healthy := h.Results()
assert.True(t, healthy, "results after bogus register")
assert.Empty(t, results, "results after bogus register")
}
func TestRegisterCheckValidations(t *testing.T) {
h := New()
defer h.DeregisterAll()
// should return an error for nil check
assert.EqualError(t, h.RegisterCheck(nil), "check must not be nil")
// should return an error for missing check name
assert.EqualError(t, h.RegisterCheck(&checks.CustomCheck{}), "check name must not be empty")
// Should return an error for missing execution period
assert.EqualError(t, h.RegisterCheck(&checks.CustomCheck{CheckName: "non-empty"}), "execution period must be greater than 0")
hWithExecPeriod := New(ExecutionPeriod(1 * time.Minute))
defer hWithExecPeriod.DeregisterAll()
// should inherit the execution period from the health instance
assert.NoError(t, hWithExecPeriod.RegisterCheck(&checks.CustomCheck{CheckName: "non-empty"}))
}
func TestRegisterDeregister(t *testing.T) {
leaktest.Check(t)
h := New()
registerCheck(h, failingCheckName, false, false)
registerCheck(h, passingCheckName, true, false)
registerCheck(h, initiallyPassingCheckName, true, true)
assert.False(t, h.IsHealthy(), "health after registration before first run")
results, healthy := h.Results()
assert.False(t, healthy, "health results after registration before first run")
assert.NotEmpty(t, results, "health after registration before first run")
passingCheck, ok1 := results[passingCheckName]
failingCheck, ok2 := results[failingCheckName]
initiallyPassingCheck, ok3 := results[initiallyPassingCheckName]
assert.True(t, ok1, "check exists")
assert.True(t, ok2, "check exists")
assert.True(t, ok3, "check exists")
assert.False(t, passingCheck.IsHealthy(), "check initially fails until first execution by default")
assert.False(t, failingCheck.IsHealthy(), "check initially fails until first execution by default")
assert.True(t, initiallyPassingCheck.IsHealthy(), "check should initially pass")
assert.Contains(t, passingCheck.String(), "didn't run yet", "initial details")
assert.Contains(t, failingCheck.String(), "didn't run yet", "initial details")
assert.Contains(t, initiallyPassingCheck.String(), "didn't run yet", "initial details")
// await first execution
time.Sleep(50 * time.Millisecond)
assert.False(t, h.IsHealthy(), "health after registration before first run with one failing check")
results, healthy = h.Results()
assert.False(t, healthy, "health results after registration before first run with one failing check")
passingCheck, ok1 = results[passingCheckName]
failingCheck, ok2 = results[failingCheckName]
initiallyPassingCheck, ok3 = results[initiallyPassingCheckName]
assert.True(t, ok1, "check exists")
assert.True(t, ok2, "check exists")
assert.True(t, ok3, "check exists")
assert.True(t, passingCheck.IsHealthy(), "succeeding check should pass")
assert.False(t, failingCheck.IsHealthy(), "failing check check should fail")
assert.True(t, initiallyPassingCheck.IsHealthy(), "passing check check should pass")
assert.NotContains(t, passingCheck.String(), "didn't run yet", "details after execution")
assert.NotContains(t, failingCheck.String(), "didn't run yet", "details after execution")
assert.NotContains(t, initiallyPassingCheck.String(), "didn't run yet", "details after execution")
assert.Contains(t, passingCheck.String(), "success", "details after execution")
assert.Contains(t, failingCheck.String(), "fail", "details after execution")
assert.Contains(t, initiallyPassingCheck.String(), "success", "details after execution")
h.Deregister(failingCheckName)
// await check cleanup
time.Sleep(50 * time.Millisecond)
assert.True(t, h.IsHealthy(), "health after failing checks deregistration")
results, healthy = h.Results()
assert.True(t, healthy, "results of only passing checks should be healthy")
assert.Equal(t, 2, len(results), "num results after deregistration")
_, ok1 = results[passingCheckName]
_, ok2 = results[failingCheckName]
_, ok3 = results[initiallyPassingCheckName]
assert.True(t, ok1, "check exists")
assert.False(t, ok2, "check should have been removed")
assert.True(t, ok3, "check exists")
h.DeregisterAll()
// await stop
time.Sleep(50 * time.Millisecond)
results, _ = h.Results()
assert.Empty(t, results, "results after stop")
}
func registerCheck(h Health, name string, passing bool, initiallyPassing bool) {
i := 0
checkFunc := func(ctx context.Context) (details interface{}, err error) {
i++
if passing {
return fmt.Sprintf("%s; i=%d", successMsg, i), nil
}
return fmt.Sprintf("%s; i=%d", failedMsg, i), errors.New(failedMsg)
}
_ = h.RegisterCheck(
&checks.CustomCheck{
CheckName: name,
CheckFunc: checkFunc,
},
InitialDelay(20*time.Millisecond),
ExecutionPeriod(20*time.Millisecond),
InitiallyPassing(initiallyPassing),
)
}
func TestCheckListener(t *testing.T) {
listenerMock := &checkListenerMock{}
listenerMock.On("OnCheckRegistered", failingCheckName, mock.AnythingOfType("Result")).Return()
listenerMock.On("OnCheckRegistered", passingCheckName, mock.AnythingOfType("Result")).Return()
listenerMock.On("OnCheckStarted", failingCheckName).Return()
listenerMock.On("OnCheckStarted", passingCheckName).Return()
listenerMock.On("OnCheckCompleted", failingCheckName, mock.AnythingOfType("Result")).Return()
listenerMock.On("OnCheckCompleted", passingCheckName, mock.AnythingOfType("Result")).Return()
h := New(WithCheckListeners(listenerMock))
registerCheck(h, failingCheckName, false, false)
registerCheck(h, passingCheckName, true, false)
defer h.DeregisterAll()
// await first execution
time.Sleep(30 * time.Millisecond)
listenerMock.AssertExpectations(t)
completedChecks := listenerMock.getCompletedChecks()
assert.Equal(t, 2, len(completedChecks), "num completed checks")
for _, c := range completedChecks {
if c.name == failingCheckName {
assert.False(t, c.res.IsHealthy())
assert.Error(t, c.res.Error)
assert.Equal(t, "failed; i=1", c.res.Details)
} else {
assert.True(t, c.res.IsHealthy())
assert.NoError(t, c.res.Error)
assert.Equal(t, "success; i=1", c.res.Details)
}
}
}
func TestHealthListeners(t *testing.T) {
listenerMock := &healthListenerMock{}
listenerMock.On(
"OnResultsUpdated",
mock.AnythingOfType("map[string]gosundheit.Result")).
Return().Times(2)
h := New(WithHealthListeners(listenerMock))
registerCheck(h, failingCheckName, false, false)
registerCheck(h, passingCheckName, true, false)
defer h.DeregisterAll()
// await first execution
time.Sleep(30 * time.Millisecond)
listenerMock.AssertExpectations(t)
}
func (l *checkListenerMock) getCompletedChecks() []completedCheck {
l.lock.RLock()
defer l.lock.RUnlock()
return l.completed
}
type checkListenerMock struct {
mock.Mock
completed []completedCheck
lock sync.RWMutex
}
type completedCheck struct {
name string
res Result
}
func (l *checkListenerMock) OnCheckRegistered(name string, result Result) {
l.Called(name, result)
}
func (l *checkListenerMock) OnCheckStarted(name string) {
l.Called(name)
}
func (l *checkListenerMock) OnCheckCompleted(name string, res Result) {
l.lock.Lock()
defer l.lock.Unlock()
l.Called(name, res)
l.completed = append(l.completed, completedCheck{name, res})
}
type healthListenerMock struct {
mock.Mock
}
func (h *healthListenerMock) OnResultsUpdated(results map[string]Result) {
h.Called(results)
}