-
Notifications
You must be signed in to change notification settings - Fork 0
/
Copy pathhttpbreaker_test.go
72 lines (56 loc) · 1.53 KB
/
httpbreaker_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
package httpbreaker
import (
"fmt"
"net/http"
"net/http/httptest"
"testing"
"time"
"github.com/sony/gobreaker"
"github.com/stretchr/testify/assert"
)
type testTransport struct {
res *http.Response
err error
}
func (tr testTransport) RoundTrip(req *http.Request) (*http.Response, error) {
return tr.res, tr.err
}
func TestSetup(t *testing.T) {
openTimeout := 100 * time.Millisecond
maxFailures := 2
cfg := gobreaker.Settings{
Name: "httpbreaker",
MaxRequests: 2,
Timeout: openTimeout,
ReadyToTrip: func(counts gobreaker.Counts) bool {
return counts.ConsecutiveFailures > uint32(maxFailures)
},
OnStateChange: func(name string, from gobreaker.State, to gobreaker.State) {
t.Logf("state %s -> %s", from, to)
},
}
res := httptest.NewRecorder()
res.WriteString("OK")
tr := &testTransport{
res: res.Result(),
err: fmt.Errorf("http error"),
}
client := Wrap(&http.Client{Transport: tr}, cfg)
_, err := client.Get("some_url")
assert.Error(t, err)
assert.Equal(t, client.State(), gobreaker.StateClosed)
_, err = client.Get("some_url")
assert.Error(t, err)
assert.Equal(t, client.State(), gobreaker.StateClosed)
_, err = client.Get("some_url")
assert.Error(t, err)
assert.Equal(t, client.State(), gobreaker.StateOpen)
time.Sleep(150 * time.Millisecond)
tr.err = nil
_, err = client.Get("some_url")
assert.NoError(t, err)
assert.Equal(t, client.State(), gobreaker.StateHalfOpen)
_, err = client.Get("some_url")
assert.NoError(t, err)
assert.Equal(t, client.State(), gobreaker.StateClosed)
}