-
Notifications
You must be signed in to change notification settings - Fork 14
/
Copy pathhttp_test.go
135 lines (127 loc) · 2.67 KB
/
http_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
package mango
import (
"errors"
"net/http"
"strings"
"testing"
"time"
)
func TestHTTPClientRetryWrap_do(t *testing.T) {
testCases := []struct {
name string
client httpClientRetryWrap
errMsg string
}{
{
name: "Retrying failed",
client: httpClientRetryWrap{
config: config{
count: 2,
pause: time.Nanosecond,
statuses: []int{http.StatusGatewayTimeout},
},
client: &httpClientMock{
returnedResponse: []*http.Response{
{
StatusCode: http.StatusGatewayTimeout,
},
{
StatusCode: http.StatusGatewayTimeout,
},
},
},
},
errMsg: "request retrying failed",
},
{
name: "Retry is not needed",
client: httpClientRetryWrap{
config: config{
count: 2,
pause: time.Nanosecond,
statuses: []int{http.StatusGatewayTimeout},
},
client: &httpClientMock{
returnedResponse: []*http.Response{
{
StatusCode: http.StatusOK,
},
},
},
},
},
{
name: "Error while request",
client: httpClientRetryWrap{
config: config{
count: 2,
pause: time.Nanosecond,
statuses: []int{http.StatusGatewayTimeout},
},
client: &httpClientMock{
returnedError: errors.New("some error"),
},
},
errMsg: "some error",
},
{
name: "Success after few attempts",
client: httpClientRetryWrap{
config: config{
count: 3,
pause: time.Nanosecond,
statuses: []int{http.StatusGatewayTimeout},
},
client: &httpClientMock{
returnedResponse: []*http.Response{
{
StatusCode: http.StatusGatewayTimeout,
},
{
StatusCode: http.StatusGatewayTimeout,
},
{
StatusCode: http.StatusOK,
},
},
},
},
},
}
for _, tc := range testCases {
t.Run(tc.name, func(t *testing.T) {
req, err := http.NewRequest("GET", "http://test.de", nil)
if err != nil {
t.Fatal(err)
}
_, err = tc.client.do(req)
if tc.errMsg != "" {
if err == nil {
t.Fatal("should be an error")
}
if !strings.Contains(err.Error(), tc.errMsg) {
t.Fatalf("(%s) should contains string (%s)", err.Error(), tc.errMsg)
}
} else {
if err != nil {
t.Fatal("should not be an error")
}
}
})
}
}
type httpClientMock struct {
returnedError error
returnedResponse []*http.Response
}
func (s *httpClientMock) Do(req *http.Request) (*http.Response, error) {
if s.returnedError != nil {
return nil, s.returnedError
}
if len(s.returnedResponse) == 0 {
return nil, errors.New("httpClientMock: nothing to return")
}
res := s.returnedResponse[0]
s.returnedResponse = s.returnedResponse[1:]
return res, nil
}