-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathbreaker_test.go
139 lines (108 loc) · 2.17 KB
/
breaker_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
package breaker
import (
"errors"
"sync"
"testing"
"time"
)
func TestNew(t *testing.T) {
b := NewBreaker(1)
if b.threshold != 1 {
t.Errorf("Unexpected threshold for new breaker: %d", b.threshold)
}
if b.failures != 0 {
t.Errorf("Unexpected count for new breaker: %d", b.failures)
}
if b.IsOpen() {
t.Errorf("A new breaker should not be open")
}
}
func TestIsOpen(t *testing.T) {
b := NewBreaker(1)
if b.IsOpen() {
t.Errorf("A new breaker should not be open")
}
b.Trip()
if !b.IsOpen() {
t.Errorf("A Tripped breaker with a threshold of 1 should be open")
}
}
func TestIsClosed(t *testing.T) {
b := NewBreaker(1)
if !b.IsClosed() {
t.Errorf("A new breaker should be closed")
}
b.Trip()
if b.IsClosed() {
t.Errorf("A Tripped breaker with a threshold of 1 should not be closed")
}
}
func TestTrip(t *testing.T) {
b := NewBreaker(1)
b.Trip()
if b.failures != 1 {
t.Errorf("A Tripped breaker that was just made should have a count of 1")
}
}
func TestReset(t *testing.T) {
b := NewBreaker(1)
b.Trip()
b.Reset()
if b.failures != 0 {
t.Errorf("A Tripped and then Reset breaker that was just made should have a count of 0")
}
if b.IsOpen() {
t.Errorf("A freshly reset breaker should not be open.")
}
}
func TestDo(t *testing.T) {
b := NewBreaker(1)
b.Do(func() error {
return errors.New("Test Error")
}, 0)
if !b.IsOpen() {
t.Errorf("Expected a function that throws an error to close the breaker")
}
b2 := NewBreaker(1)
b2.Do(func() error {
time.Sleep(time.Second)
return nil
}, 0)
if !b2.IsOpen() {
t.Errorf("Expected a function that times out to trip the breaker")
}
b3 := NewBreaker(1)
err := b3.Do(func() error {
return nil
}, time.Second)
if err != nil {
t.Errorf("Did not expect an error for a successful call to Do.")
}
}
func TestTripAsync(t *testing.T) {
b := NewBreaker(10)
var wg sync.WaitGroup
wg.Add(2)
go func() {
i := 0
for i < 5 {
time.Sleep(time.Microsecond)
b.Trip()
i++
}
wg.Done()
}()
go func() {
i := 0
for i < 5 {
time.Sleep(time.Microsecond)
b.Trip()
i++
}
wg.Done()
}()
wg.Wait()
if b.IsClosed() {
t.Errorf("Breaker should not be closed.")
}
}