forked from zeromicro/go-zero
-
Notifications
You must be signed in to change notification settings - Fork 0
/
breakers_test.go
114 lines (103 loc) · 2.4 KB
/
breakers_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
package breaker
import (
"errors"
"fmt"
"testing"
"github.com/stretchr/testify/assert"
"github.com/tal-tech/go-zero/core/stat"
)
func init() {
stat.SetReporter(nil)
}
func TestBreakersDo(t *testing.T) {
assert.Nil(t, Do("any", func() error {
return nil
}))
errDummy := errors.New("any")
assert.Equal(t, errDummy, Do("any", func() error {
return errDummy
}))
}
func TestBreakersDoWithAcceptable(t *testing.T) {
errDummy := errors.New("anyone")
for i := 0; i < 10000; i++ {
assert.Equal(t, errDummy, GetBreaker("anyone").DoWithAcceptable(func() error {
return errDummy
}, func(err error) bool {
return err == nil || err == errDummy
}))
}
verify(t, func() bool {
return Do("anyone", func() error {
return nil
}) == nil
})
for i := 0; i < 10000; i++ {
err := DoWithAcceptable("another", func() error {
return errDummy
}, func(err error) bool {
return err == nil
})
assert.True(t, err == errDummy || err == ErrServiceUnavailable)
}
verify(t, func() bool {
return ErrServiceUnavailable == Do("another", func() error {
return nil
})
})
}
func TestBreakersNoBreakerFor(t *testing.T) {
NoBreakerFor("any")
errDummy := errors.New("any")
for i := 0; i < 10000; i++ {
assert.Equal(t, errDummy, GetBreaker("any").Do(func() error {
return errDummy
}))
}
assert.Equal(t, nil, Do("any", func() error {
return nil
}))
}
func TestBreakersFallback(t *testing.T) {
errDummy := errors.New("any")
for i := 0; i < 10000; i++ {
err := DoWithFallback("fallback", func() error {
return errDummy
}, func(err error) error {
return nil
})
assert.True(t, err == nil || err == errDummy)
}
verify(t, func() bool {
return ErrServiceUnavailable == Do("fallback", func() error {
return nil
})
})
}
func TestBreakersAcceptableFallback(t *testing.T) {
errDummy := errors.New("any")
for i := 0; i < 10000; i++ {
err := DoWithFallbackAcceptable("acceptablefallback", func() error {
return errDummy
}, func(err error) error {
return nil
}, func(err error) bool {
return err == nil
})
assert.True(t, err == nil || err == errDummy)
}
verify(t, func() bool {
return ErrServiceUnavailable == Do("acceptablefallback", func() error {
return nil
})
})
}
func verify(t *testing.T, fn func() bool) {
var count int
for i := 0; i < 100; i++ {
if fn() {
count++
}
}
assert.True(t, count >= 80, fmt.Sprintf("should be greater than 80, actual %d", count))
}