-
Notifications
You must be signed in to change notification settings - Fork 7
/
Copy pathhttp_test.go
194 lines (169 loc) · 5.61 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
136
137
138
139
140
141
142
143
144
145
146
147
148
149
150
151
152
153
154
155
156
157
158
159
160
161
162
163
164
165
166
167
168
169
170
171
172
173
174
175
176
177
178
179
180
181
182
183
184
185
186
187
188
189
190
191
192
193
194
package utility
import (
"context"
"io"
"io/ioutil"
"net/http"
"net/http/httptest"
"strings"
"sync/atomic"
"testing"
"github.com/PuerkitoBio/rehttp"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
"golang.org/x/oauth2"
)
func TestPooledHTTPClient(t *testing.T) {
t.Run("Initialized", func(t *testing.T) {
require.NotNil(t, httpClientPool)
cl := GetHTTPClient()
require.NotNil(t, cl)
require.NotPanics(t, func() { PutHTTPClient(cl) })
})
t.Run("ResettingSkipCert", func(t *testing.T) {
cl := GetHTTPClient()
cl.Transport.(*http.Transport).TLSClientConfig.InsecureSkipVerify = true
PutHTTPClient(cl)
cl2 := GetHTTPClient()
assert.Equal(t, cl, cl2)
assert.False(t, cl.Transport.(*http.Transport).TLSClientConfig.InsecureSkipVerify)
assert.False(t, cl2.Transport.(*http.Transport).TLSClientConfig.InsecureSkipVerify)
})
t.Run("RehttpPool", func(t *testing.T) {
initHTTPPool()
cl := GetHTTPClient()
clt := cl.Transport
PutHTTPClient(cl)
rcl := GetDefaultHTTPRetryableClient()
assert.Equal(t, cl, rcl)
assert.NotEqual(t, clt, rcl.Transport)
assert.Equal(t, clt, rcl.Transport.(*rehttp.Transport).RoundTripper)
})
}
type mockTransport struct {
count int
expectedToken string
status int
}
func (t *mockTransport) RoundTrip(req *http.Request) (*http.Response, error) {
t.count++
resp := http.Response{
StatusCode: t.status,
Header: http.Header{},
Body: ioutil.NopCloser(strings.NewReader("hi")),
}
token := req.Header.Get("Authorization")
split := strings.Split(token, " ")
if len(split) != 2 || split[0] != "Bearer" || split[1] != t.expectedToken {
resp.StatusCode = http.StatusForbidden
}
return &resp, nil
}
func TestRetryableOauthClient(t *testing.T) {
t.Run("Passing", func(t *testing.T) {
c := GetOauth2DefaultHTTPRetryableClient("hi")
defer PutHTTPClient(c)
transport := &mockTransport{expectedToken: "hi", status: http.StatusOK}
oldTransport := c.Transport.(*oauth2.Transport).Base.(*rehttp.Transport).RoundTripper
defer func() {
c.Transport.(*oauth2.Transport).Base.(*rehttp.Transport).RoundTripper = oldTransport
}()
c.Transport.(*oauth2.Transport).Base.(*rehttp.Transport).RoundTripper = transport
resp, err := c.Get("https://example.com")
assert.NoError(t, err)
assert.NotNil(t, resp)
assert.Equal(t, 1, transport.count)
assert.Equal(t, http.StatusOK, resp.StatusCode)
})
t.Run("Failed", func(t *testing.T) {
conf := NewDefaultHTTPRetryConf()
conf.MaxRetries = 5
c := GetOauth2HTTPRetryableClient("hi", conf)
defer PutHTTPClient(c)
transport := &mockTransport{expectedToken: "hi", status: http.StatusInternalServerError}
oldTransport := c.Transport.(*oauth2.Transport).Base.(*rehttp.Transport).RoundTripper
defer func() {
c.Transport.(*oauth2.Transport).Base.(*rehttp.Transport).RoundTripper = oldTransport
}()
c.Transport.(*oauth2.Transport).Base.(*rehttp.Transport).RoundTripper = transport
resp, err := c.Get("https://example.com")
assert.NoError(t, err)
assert.NotNil(t, resp)
assert.Equal(t, 6, transport.count)
assert.Equal(t, http.StatusInternalServerError, resp.StatusCode)
})
}
func TestRetryRequestOn413(t *testing.T) {
var callCount int32
handler := NewMockHandler()
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
// Decide the status code dynamically for the first vs. subsequent calls
callCount++
if callCount == 1 {
handler.StatusCode = http.StatusRequestEntityTooLarge // 413
} else {
handler.StatusCode = http.StatusOK
}
handler.ServeHTTP(w, r)
}))
defer server.Close()
opts := RetryRequestOptions{
RetryOptions: RetryOptions{
MaxAttempts: 3,
},
RetryOn413: true,
}
req, err := http.NewRequest(http.MethodGet, server.URL, nil)
require.NoError(t, err, "failed to create request")
resp, err := RetryRequest(context.Background(), req, opts)
require.NoError(t, err, "request failed")
assert.Equal(t, http.StatusOK, resp.StatusCode, "expected 200 status code")
assert.GreaterOrEqual(t, atomic.LoadInt32(&callCount), int32(2), "expected multiple attempts")
}
func TestMockHandler(t *testing.T) {
handler := NewMockHandler()
server := httptest.NewServer(handler)
defer server.Close()
client := server.Client()
t.Run("Serve", func(t *testing.T) {
urlString := server.URL + "/example"
handler.Header = map[string][]string{
"header1": {"header1"},
"header2": {"header1", "header2"},
}
handler.Body = []byte("some body")
handler.StatusCode = http.StatusOK
req, err := http.NewRequest(http.MethodGet, urlString, nil)
require.NoError(t, err)
resp, err := client.Do(req)
require.NoError(t, err)
assert.Len(t, handler.Calls, 1)
for key, values := range handler.Header {
assert.Equal(t, values, resp.Header.Values(key))
}
assert.Equal(t, handler.StatusCode, resp.StatusCode)
body, err := io.ReadAll(resp.Body)
require.NoError(t, err)
assert.Equal(t, handler.Body, body)
assert.NoError(t, handler.GetWriteError())
urlString = server.URL + "/example2"
handler.Header = map[string][]string{
"header1": {"header1"},
}
handler.Body = []byte("example not found")
handler.StatusCode = http.StatusNotFound
req, err = http.NewRequest(http.MethodGet, urlString, nil)
require.NoError(t, err)
resp, err = client.Do(req)
require.NoError(t, err)
assert.Len(t, handler.Calls, 2)
for key, values := range handler.Header {
assert.Equal(t, values, resp.Header.Values(key))
}
assert.Equal(t, handler.StatusCode, resp.StatusCode)
body, err = io.ReadAll(resp.Body)
require.NoError(t, err)
assert.Equal(t, handler.Body, body)
assert.NoError(t, handler.GetWriteError())
})
}