/
healthcheck_test.go
123 lines (110 loc) · 2.22 KB
/
healthcheck_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
package healthcheck
import (
"log"
"sync"
"testing"
"time"
)
type TestIndicator struct {
*sync.Mutex
hasBeenCalled bool
}
func (t *TestIndicator) Name() string {
return "test"
}
func (t *TestIndicator) IsHealthy() bool {
t.Lock()
t.hasBeenCalled = true
t.Unlock()
return true
}
func TestBasicFunction(t *testing.T) {
checker := New(time.Millisecond)
checker.RegisterIndicator(&TestIndicator{
&sync.Mutex{},
true,
})
cond := make(chan bool, 0)
checker.AddHook("testHook", func(m map[string]bool) {
ok := m["test"]
select {
case cond <- ok:
log.Println("Condition has been written")
default:
log.Println("Cant write condition")
}
})
checker.Start()
if !<-cond {
t.Error("Helthchecker failed")
}
checker.Stop()
}
func TestStopIfNotStarted(t *testing.T) {
checker := New(time.Millisecond)
err := checker.Stop()
if err == nil {
t.Error("Stopped not started checker")
}
}
func TestStartAlreadyStartedChecker(t *testing.T) {
checker := New(time.Millisecond)
err := checker.Start()
if err != nil {
t.Error("Start checker failed")
}
err = checker.Start()
if err == nil {
t.Error("The already started checker cannot be started")
}
checker.Stop()
}
func TestUnregister(t *testing.T) {
checker := New(time.Millisecond)
indicator := &TestIndicator{
&sync.Mutex{},
false,
}
checker.RegisterIndicator(indicator)
checker.Start()
time.Sleep(2 * time.Millisecond)
checker.UnregisterIndicator(indicator)
indicator.Lock()
indicator.hasBeenCalled = false
indicator.Unlock()
time.Sleep(2 * time.Millisecond)
if indicator.hasBeenCalled {
t.Error("Unregistration not sucessfull")
}
}
func TestRemoveHook(t *testing.T) {
checker := New(time.Millisecond)
counter := struct {
*sync.Mutex
called bool
}{
&sync.Mutex{},
false,
}
checker.AddHook("testHook", func(m map[string]bool) {
counter.Lock()
counter.called = true
counter.Unlock()
})
checker.Start()
time.Sleep(2 * time.Millisecond)
counter.Lock()
if !counter.called {
t.Error("Counter not called")
}
counter.called = false
counter.Unlock()
checker.RemoveHook("testHook")
time.Sleep(2 * time.Millisecond)
counter.Lock()
if counter.called {
t.Error("Counter should not be called")
}
counter.Unlock()
checker.Stop()
}