-
Notifications
You must be signed in to change notification settings - Fork 58
/
health_test.go
716 lines (563 loc) · 17.6 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
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
package health
import (
"errors"
"fmt"
"testing"
"time"
. "github.com/onsi/gomega"
"github.com/InVisionApp/go-health/v2/fakes"
"github.com/InVisionApp/go-logger"
"github.com/InVisionApp/go-logger/shims/testlog"
)
var (
testCheckInterval = time.Duration(10) * time.Millisecond
testLogger *testlog.TestLogger
)
type MockStatusListener struct{}
func (mock *MockStatusListener) HealthCheckFailed(entry *State) {
testLogger.Debug(entry.Name)
}
func (mock *MockStatusListener) HealthCheckRecovered(entry *State, recordedFailures int64, failureDurationSeconds float64) {
testLogger.Debug(entry.Name, recordedFailures, failureDurationSeconds)
}
// since we dont have before each in this testing framework...
func setupNewTestHealth() *Health {
h := New()
// replace with silent logger
h.Logger = log.NewNoop()
return h
}
func TestNew(t *testing.T) {
RegisterTestingT(t)
t.Run("Should return a filled out instance of Health", func(t *testing.T) {
h := setupNewTestHealth()
Expect(h.configs).ToNot(BeNil())
Expect(h.states).ToNot(BeNil())
Expect(h.runners).ToNot(BeNil())
})
}
func TestAddChecks(t *testing.T) {
RegisterTestingT(t)
t.Run("Happy path", func(t *testing.T) {
h := setupNewTestHealth()
testConfig := &Config{
Name: "foo",
Checker: &fakes.FakeICheckable{},
Interval: testCheckInterval,
Fatal: false,
}
err := h.AddChecks([]*Config{testConfig})
Expect(err).To(BeNil())
Expect(h.configs).To(ContainElement(testConfig))
Expect(len(h.configs)).To(Equal(1))
})
t.Run("Should error if healthcheck is already running", func(t *testing.T) {
h := setupNewTestHealth()
h.active.setTrue()
err := h.AddChecks([]*Config{})
Expect(err).To(HaveOccurred())
Expect(err).To(Equal(ErrNoAddCfgWhenActive))
})
t.Run("Should not error if passed in empty config slice", func(t *testing.T) {
h := setupNewTestHealth()
err := h.AddChecks([]*Config{})
Expect(err).ToNot(HaveOccurred())
})
}
func TestAddCheck(t *testing.T) {
RegisterTestingT(t)
t.Run("Happy path", func(t *testing.T) {
h := setupNewTestHealth()
testConfig := &Config{
Name: "foo",
Checker: &fakes.FakeICheckable{},
Interval: testCheckInterval,
Fatal: false,
}
err := h.AddCheck(testConfig)
Expect(err).To(BeNil())
Expect(h.configs).To(ContainElement(testConfig))
Expect(len(h.configs)).To(Equal(1))
})
t.Run("Should error if healthcheck is already running", func(t *testing.T) {
h := setupNewTestHealth()
h.active.setTrue()
err := h.AddCheck(&Config{})
Expect(err).To(HaveOccurred())
Expect(err).To(Equal(ErrNoAddCfgWhenActive))
})
}
func TestDisableLogging(t *testing.T) {
RegisterTestingT(t)
t.Run("Should set logger to noop logger", func(t *testing.T) {
h := New()
// Should initially be set to a basic logger
Expect(h.Logger).To(BeEquivalentTo(log.NewSimple()))
// Should set it to a noop logger
h.DisableLogging()
Expect(h.Logger).To(BeEquivalentTo(log.NewNoop()))
})
}
func TestFailed(t *testing.T) {
RegisterTestingT(t)
t.Run("Should return false if a fatally configured check hasn't errored", func(t *testing.T) {
t.Run("Happy path", func(t *testing.T) {
h := setupNewTestHealth()
checker1 := &fakes.FakeICheckable{}
checker1.StatusReturns(nil, nil)
cfgs := []*Config{
{
Name: "foo",
Checker: checker1,
Interval: testCheckInterval,
Fatal: true,
},
}
err := h.AddChecks(cfgs)
Expect(err).ToNot(HaveOccurred())
err = h.Start()
Expect(err).ToNot(HaveOccurred())
// More brittleness -- need to wait to ensure our checks have executed
time.Sleep(time.Duration(15) * time.Millisecond)
states, failed, err := h.State()
Expect(err).ToNot(HaveOccurred())
Expect(failed).To(BeFalse())
Expect(states).To(HaveKey("foo"))
Expect(h.Failed()).To(BeFalse())
})
})
t.Run("Should return true if a fatally configured check has failed", func(t *testing.T) {
h := setupNewTestHealth()
checker1 := &fakes.FakeICheckable{}
checker1.StatusReturns(nil, fmt.Errorf("things broke"))
checker2 := &fakes.FakeICheckable{}
checker2.StatusReturns(nil, nil)
cfgs := []*Config{
// order *is* relevant, failing check should be first
{
Name: "bar",
Checker: checker2,
Interval: testCheckInterval,
Fatal: true,
},
{
Name: "foo",
Checker: checker1,
Interval: testCheckInterval,
Fatal: true,
},
}
err := h.AddChecks(cfgs)
Expect(err).ToNot(HaveOccurred())
err = h.Start()
Expect(err).ToNot(HaveOccurred())
// More brittleness -- need to wait to ensure our checks have executed
time.Sleep(time.Duration(15) * time.Millisecond)
states, failed, err := h.State()
Expect(err).ToNot(HaveOccurred())
Expect(failed).To(BeTrue())
Expect(states).To(HaveKey("foo"))
Expect(h.Failed()).To(BeTrue())
})
}
func TestState(t *testing.T) {
RegisterTestingT(t)
t.Run("Happy path", func(t *testing.T) {
h := setupNewTestHealth()
checker1 := &fakes.FakeICheckable{}
checker1.StatusReturns(nil, fmt.Errorf("things broke"))
cfgs := []*Config{
{
Name: "foo",
Checker: checker1,
Interval: testCheckInterval,
Fatal: false,
},
}
err := h.AddChecks(cfgs)
Expect(err).ToNot(HaveOccurred())
err = h.Start()
Expect(err).ToNot(HaveOccurred())
// More brittleness -- need to wait to ensure our checks have executed
time.Sleep(time.Duration(15) * time.Millisecond)
states, failed, err := h.State()
Expect(err).ToNot(HaveOccurred())
Expect(failed).To(BeFalse())
Expect(states).To(HaveKey("foo"))
Expect(states["foo"].Err).To(Equal("things broke"))
})
t.Run("When a fatally-configured check fails and recovers, state should get updated accordingly", func(t *testing.T) {
h := setupNewTestHealth()
checker1 := &fakes.FakeICheckable{}
checker1.StatusReturns(nil, fmt.Errorf("things broke"))
checker2 := &fakes.FakeICheckable{}
checker2.StatusReturns(nil, nil)
cfgs := []*Config{
// order *is* relevant, failing check should be first
{
Name: "bar",
Checker: checker2,
Interval: testCheckInterval,
Fatal: true,
},
{
Name: "foo",
Checker: checker1,
Interval: testCheckInterval,
Fatal: true,
},
}
err := h.AddChecks(cfgs)
Expect(err).ToNot(HaveOccurred())
err = h.Start()
Expect(err).ToNot(HaveOccurred())
// More brittleness -- need to wait to ensure our checks have executed
time.Sleep(time.Duration(15) * time.Millisecond)
states, failed, err := h.State()
Expect(err).ToNot(HaveOccurred())
Expect(failed).To(BeTrue())
Expect(states).To(HaveKey("foo"))
Expect(states["foo"].Err).To(Equal("things broke"))
// And now, let's let it recover
checker1.StatusReturns(nil, nil)
time.Sleep(time.Duration(15) * time.Millisecond)
statesRecov, failedRecov, errRecov := h.State()
Expect(errRecov).ToNot(HaveOccurred())
Expect(failedRecov).To(BeFalse())
Expect(statesRecov).To(HaveKey("foo"))
Expect(statesRecov["foo"].Err).To(BeEmpty())
})
}
func TestStart(t *testing.T) {
RegisterTestingT(t)
t.Run("Happy path", func(t *testing.T) {
h := setupNewTestHealth()
checker1 := &fakes.FakeICheckable{}
checker2 := &fakes.FakeICheckable{}
cfgs := []*Config{
{
Name: "foo",
Checker: checker1,
Interval: testCheckInterval,
Fatal: false,
},
{
Name: "bar",
Checker: checker2,
Interval: testCheckInterval,
Fatal: false,
},
}
err := h.AddChecks(cfgs)
Expect(err).ToNot(HaveOccurred())
testLogger := testlog.New()
h.Logger = testLogger
err = h.Start()
Expect(err).ToNot(HaveOccurred())
// Correct number of runners were created
Expect(len(h.runners)).To(Equal(2))
// Runners are created (and saved) based on their name
for _, v := range cfgs {
Expect(h.runners).To(HaveKey(v.Name))
}
// This is pretty brittle - will update if this is causing random test failures
time.Sleep(time.Duration(15) * time.Millisecond)
// Both runners should've ran
Expect(checker1.StatusCallCount()).To(Equal(2), "Checker should have been executed")
Expect(checker2.StatusCallCount()).To(Equal(2), "Checker should have been executed")
// Both runners should've recorded their state
Expect(h.states).To(HaveKey("foo"))
Expect(h.states).To(HaveKey("bar"))
// Ensure that logger was hit as expected
Expect(testLogger.CallCount()).To(Equal(2))
msgs := testLogger.Bytes()
for _, cfg := range cfgs {
Expect(msgs).To(ContainSubstring("Starting checker name=" + cfg.Name))
}
})
t.Run("Should error if healthcheck already running", func(t *testing.T) {
h := setupNewTestHealth()
err := h.AddCheck(&Config{})
Expect(err).ToNot(HaveOccurred())
// Set the healthcheck state to active
h.active.setTrue()
err = h.Start()
Expect(err).To(Equal(ErrAlreadyRunning))
})
}
func TestStop(t *testing.T) {
RegisterTestingT(t)
t.Run("Happy path", func(t *testing.T) {
testLogger := testlog.New()
h, cfgs, err := setupRunners(nil, testLogger)
Expect(err).ToNot(HaveOccurred())
Expect(h).ToNot(BeNil())
// A bit brittle, but it'll do
time.Sleep(time.Duration(15) * time.Millisecond)
Expect(len(h.states)).To(Equal(2))
err = h.Stop()
Expect(err).ToNot(HaveOccurred())
// Wait a bit to ensure goroutines have exited
time.Sleep(15 * time.Millisecond)
// Runners map should be reset
Expect(h.runners).To(BeEmpty())
// Ensure that logger captured the start and stop messages
Expect(testLogger.CallCount()).To(Equal(6))
for _, cfg := range cfgs {
// 3rd and 4th message should indicate goroutine exit
msgs := testLogger.Bytes()
Expect(msgs).To(ContainSubstring("Stopping checker name=" + cfg.Name))
Expect(msgs).To(ContainSubstring("Checker exiting name=" + cfg.Name))
}
// Expect state map to be reset
Expect(len(h.states)).To(Equal(0))
})
t.Run("Should error if healthcheck is not running", func(t *testing.T) {
h := setupNewTestHealth()
err := h.AddCheck(&Config{})
Expect(err).ToNot(HaveOccurred())
// Set the healthcheck state to active
h.active.setFalse()
err = h.Stop()
Expect(err).To(Equal(ErrAlreadyStopped))
})
}
func TestStartRunner(t *testing.T) {
RegisterTestingT(t)
t.Run("Happy path - checkers do not fail", func(t *testing.T) {
h, cfgs, err := setupRunners(nil, nil)
Expect(err).ToNot(HaveOccurred())
Expect(h).ToNot(BeNil())
// Brittle...
time.Sleep(time.Duration(15) * time.Millisecond)
// Did the ticker fire and create a state entry?
for _, c := range cfgs {
Expect(h.states).To(HaveKey(c.Name))
Expect(h.states[c.Name].Status).To(Equal("ok"))
}
// Since nothing has failed, healthcheck should _not_ be in failed state
Expect(h.Failed()).To(BeFalse())
})
t.Run("Happy path - no checkers is noop", func(t *testing.T) {
h := New()
Expect(h).ToNot(BeNil())
err := h.Start()
Expect(err).ToNot(HaveOccurred())
Expect(h.active.val()).To(BeFalse())
})
t.Run("Happy path - 1 checker fails (non-fatal)", func(t *testing.T) {
checker1 := &fakes.FakeICheckable{}
checker2 := &fakes.FakeICheckable{}
checker2Error := errors.New("something failed")
checker2.StatusReturns(nil, checker2Error)
cfgs := []*Config{
{
Name: "foo",
Checker: checker1,
Interval: testCheckInterval,
Fatal: false,
},
{
Name: "bar",
Checker: checker2,
Interval: testCheckInterval,
Fatal: false,
},
}
h, _, err := setupRunners(cfgs, nil)
Expect(err).ToNot(HaveOccurred())
Expect(h).ToNot(BeNil())
// Brittle...
time.Sleep(time.Duration(15) * time.Millisecond)
// Did the ticker fire and create a state entry?
for _, c := range cfgs {
Expect(h.states).To(HaveKey(c.Name))
}
// First checker should've succeeded
Expect(h.states[cfgs[0].Name].Status).To(Equal("ok"))
// Second checker should've failed
Expect(h.states[cfgs[1].Name].Status).To(Equal("failed"))
Expect(h.states[cfgs[1].Name].Err).To(Equal(checker2Error.Error()))
// Since nothing has failed, healthcheck should _not_ be in failed state
Expect(h.Failed()).To(BeFalse())
})
t.Run("Happy path - 1 checker fails (fatal)", func(t *testing.T) {
checker1 := &fakes.FakeICheckable{}
checker2 := &fakes.FakeICheckable{}
checker2Err := errors.New("something failed")
checker2.StatusReturns(nil, checker2Err)
cfgs := []*Config{
{
Name: "foo",
Checker: checker1,
Interval: testCheckInterval,
Fatal: false,
},
{
Name: "bar",
Checker: checker2,
Interval: testCheckInterval,
Fatal: true,
},
}
h, _, err := setupRunners(cfgs, nil)
Expect(err).ToNot(HaveOccurred())
Expect(h).ToNot(BeNil())
// Brittle...
time.Sleep(time.Duration(15) * time.Millisecond)
// Did the ticker fire and create a state entry?
for _, c := range cfgs {
Expect(h.states).To(HaveKey(c.Name))
}
// First checker should've succeeded
Expect(h.states[cfgs[0].Name].Status).To(Equal("ok"))
// Second checker should've failed
Expect(h.states[cfgs[1].Name].Status).To(Equal("failed"))
Expect(h.states[cfgs[1].Name].Err).To(Equal(checker2Err.Error()))
// Since second checker has failed fatally, global healthcheck state should be failed as well
Expect(h.Failed()).To(BeTrue())
})
t.Run("Should call the OnComplete hook when the health check is complete", func(t *testing.T) {
checker := &fakes.FakeICheckable{}
var calledState *State
called := false
completeFunc := func(state *State) {
called = true
calledState = state
}
cfgs := []*Config{
{
Name: "SuperCheck",
Checker: checker,
Interval: testCheckInterval,
Fatal: false,
OnComplete: completeFunc,
},
}
h, _, err := setupRunners(cfgs, nil)
Expect(err).ToNot(HaveOccurred())
Expect(h).ToNot(BeNil())
// Brittle...
time.Sleep(time.Duration(15) * time.Millisecond)
// Did the ticker fire and create a state entry?
Expect(h.states).To(HaveKey(cfgs[0].Name))
// Hook should have been called
Expect(called).To(BeTrue())
Expect(calledState).ToNot(BeNil())
Expect(calledState.Name).To(Equal(cfgs[0].Name))
Expect(calledState.Status).To(Equal("ok"))
})
t.Run("Modifying the state in the OnComplete hook should not modify the one saved in the states map", func(t *testing.T) {
checker := &fakes.FakeICheckable{}
var calledState *State
called := false
changedName := "Guybrush Threepwood"
changedStatus := "never"
completeFunc := func(state *State) {
called = true
state.Name = changedName
state.Status = changedStatus
calledState = state
}
cfgs := []*Config{
{
Name: "CheckIt",
Checker: checker,
Interval: testCheckInterval,
Fatal: false,
OnComplete: completeFunc,
},
}
h, _, err := setupRunners(cfgs, nil)
Expect(err).ToNot(HaveOccurred())
Expect(h).ToNot(BeNil())
// Brittle...
time.Sleep(time.Duration(15) * time.Millisecond)
// Did the ticker fire and create a state entry?
Expect(h.states).To(HaveKey(cfgs[0].Name))
// Hook should have been called
Expect(called).To(BeTrue())
Expect(calledState).ToNot(BeNil())
//changed status in OnComplete should not affect internal states map
Expect(calledState.Name).To(Equal(changedName))
Expect(calledState.Status).To(Equal(changedStatus))
Expect(h.states[cfgs[0].Name].Name).To(Equal(cfgs[0].Name))
Expect(h.states[cfgs[0].Name].Status).To(Equal("ok"))
})
}
func TestStatusListenerOnFail(t *testing.T) {
RegisterTestingT(t)
t.Run("happy path - a health check fails and failure is reported, no previous states", func(tt *testing.T) {
testLogger = testlog.New()
checker := &fakes.FakeICheckable{}
checkErr := errors.New("check error")
checker.StatusReturns(nil, checkErr)
cfgs := []*Config{
{
Name: "FOOCHECK",
Checker: checker,
Interval: testCheckInterval,
Fatal: false,
},
}
h, _, err := setupRunners(cfgs, nil)
Expect(err).ToNot(HaveOccurred())
Expect(h).ToNot(BeNil())
// add listener
h.StatusListener = &MockStatusListener{}
// let the health check run once
time.Sleep(5 * time.Millisecond)
Expect(string(testLogger.Bytes())).To(ContainSubstring("FOOCHECK"))
})
t.Run("happy path - a health check fails and failure is reported, 3 previous states", func(tt *testing.T) {
testLogger = testlog.New()
checker := &fakes.FakeICheckable{}
checkErr := errors.New("check error")
checker.StatusReturnsOnCall(3, nil, checkErr)
cfgs := []*Config{
{
Name: "FOOCHECK",
Checker: checker,
Interval: testCheckInterval,
Fatal: false,
},
}
h, _, err := setupRunners(cfgs, nil)
Expect(err).ToNot(HaveOccurred())
Expect(h).ToNot(BeNil())
// add listener
h.StatusListener = &MockStatusListener{}
// let the health check run once
time.Sleep(35 * time.Millisecond)
Expect(string(testLogger.Bytes())).To(ContainSubstring("FOOCHECK"))
})
}
func TestStatusListenerOnRecover(t *testing.T) {
RegisterTestingT(t)
t.Run("happy path - health check recovers after 3 errors", func(tt *testing.T) {
testLogger = testlog.New()
checker := &fakes.FakeICheckable{}
checkErr := errors.New("check error")
checker.StatusReturnsOnCall(0, nil, checkErr)
checker.StatusReturnsOnCall(1, nil, checkErr)
checker.StatusReturnsOnCall(2, nil, checkErr)
cfgs := []*Config{
{
Name: "FOOCHECK",
Checker: checker,
Interval: testCheckInterval,
Fatal: false,
},
}
h, _, err := setupRunners(cfgs, nil)
Expect(err).ToNot(HaveOccurred())
Expect(h).ToNot(BeNil())
// add listener
h.StatusListener = &MockStatusListener{}
// let the health check recover and run a few more times
time.Sleep(55 * time.Millisecond)
// check name, number of total failures, number of seconds in failure
testStr := "FOOCHECK3 0.03"
Expect(string(testLogger.Bytes())).To(ContainSubstring(testStr))
})
}