forked from zeromicro/go-zero
-
Notifications
You must be signed in to change notification settings - Fork 0
/
breaker_test.go
132 lines (117 loc) · 2.39 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
package breaker
import (
"errors"
"fmt"
"strconv"
"strings"
"testing"
"github.com/stretchr/testify/assert"
"github.com/tal-tech/go-zero/core/stat"
)
func init() {
stat.SetReporter(nil)
}
func TestCircuitBreaker_Allow(t *testing.T) {
b := NewBreaker()
assert.True(t, len(b.Name()) > 0)
_, err := b.Allow()
assert.Nil(t, err)
}
func TestLogReason(t *testing.T) {
b := NewBreaker()
assert.True(t, len(b.Name()) > 0)
for i := 0; i < 1000; i++ {
_ = b.Do(func() error {
return errors.New(strconv.Itoa(i))
})
}
errs := b.(*circuitBreaker).throttle.(loggedThrottle).errWin
assert.Equal(t, numHistoryReasons, errs.count)
}
func TestErrorWindow(t *testing.T) {
tests := []struct {
name string
reasons []string
}{
{
name: "no error",
},
{
name: "one error",
reasons: []string{"foo"},
},
{
name: "two errors",
reasons: []string{"foo", "bar"},
},
{
name: "five errors",
reasons: []string{"first", "second", "third", "fourth", "fifth"},
},
{
name: "six errors",
reasons: []string{"first", "second", "third", "fourth", "fifth", "sixth"},
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
var ew errorWindow
for _, reason := range test.reasons {
ew.add(reason)
}
var reasons []string
if len(test.reasons) > numHistoryReasons {
reasons = test.reasons[len(test.reasons)-numHistoryReasons:]
} else {
reasons = test.reasons
}
for _, reason := range reasons {
assert.True(t, strings.Contains(ew.String(), reason), fmt.Sprintf("actual: %s", ew.String()))
}
})
}
}
func TestPromiseWithReason(t *testing.T) {
tests := []struct {
name string
reason string
expect string
}{
{
name: "success",
},
{
name: "success",
reason: "fail",
expect: "fail",
},
}
for _, test := range tests {
t.Run(test.name, func(t *testing.T) {
promise := promiseWithReason{
promise: new(mockedPromise),
errWin: new(errorWindow),
}
if len(test.reason) == 0 {
promise.Accept()
} else {
promise.Reject(test.reason)
}
assert.True(t, strings.Contains(promise.errWin.String(), test.expect))
})
}
}
func BenchmarkGoogleBreaker(b *testing.B) {
br := NewBreaker()
for i := 0; i < b.N; i++ {
_ = br.Do(func() error {
return nil
})
}
}
type mockedPromise struct {
}
func (m *mockedPromise) Accept() {
}
func (m *mockedPromise) Reject() {
}