-
Notifications
You must be signed in to change notification settings - Fork 12
Expand file tree
/
Copy pathtransport_test.go
More file actions
328 lines (293 loc) · 9.19 KB
/
transport_test.go
File metadata and controls
328 lines (293 loc) · 9.19 KB
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
195
196
197
198
199
200
201
202
203
204
205
206
207
208
209
210
211
212
213
214
215
216
217
218
219
220
221
222
223
224
225
226
227
228
229
230
231
232
233
234
235
236
237
238
239
240
241
242
243
244
245
246
247
248
249
250
251
252
253
254
255
256
257
258
259
260
261
262
263
264
265
266
267
268
269
270
271
272
273
274
275
276
277
278
279
280
281
282
283
284
285
286
287
288
289
290
291
292
293
294
295
296
297
298
299
300
301
302
303
304
305
306
307
308
309
310
311
312
313
314
315
316
317
318
319
320
321
322
323
324
325
326
327
328
package statsig
import (
"encoding/json"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"testing"
"time"
)
type Empty struct{}
type ServerResponse struct {
Name string `json:"name"`
}
func TestNonRetryable(t *testing.T) {
testServer := httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
if req.Method != "POST" {
t.Errorf("Expected ‘POST’ request, got '%s'", req.Method)
}
res.WriteHeader(http.StatusNotFound)
}))
defer testServer.Close()
in := Empty{}
var out ServerResponse
opt := &Options{
API: testServer.URL,
}
n := newTransport("secret-123", opt)
_, err := n.post("/123", in, &out, RequestOptions{retries: 2}, nil)
if err == nil {
t.Errorf("Expected error for network request but got nil")
}
}
func TestLocalMode(t *testing.T) {
hit := false
testServer := httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
hit = true
res.WriteHeader(http.StatusNotFound)
}))
defer testServer.Close()
in := Empty{}
var out ServerResponse
opt := &Options{
API: testServer.URL,
LocalMode: true,
}
n := newTransport("secret-123", opt)
_, err := n.post("/123", in, &out, RequestOptions{retries: 2}, nil)
if err != nil {
t.Errorf("Expected no error for network request")
}
if hit {
t.Errorf("Expected transport class not to hit the server")
}
}
func TestRetries(t *testing.T) {
tries := 0
testServer := httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
defer func() {
tries = tries + 1
}()
switch tries {
case 0:
res.WriteHeader(http.StatusInternalServerError)
case 1:
output := ServerResponse{
Name: "test",
}
res.WriteHeader(http.StatusOK)
_ = json.NewEncoder(res).Encode(output)
}
}))
defer func() { testServer.Close() }()
in := Empty{}
var out ServerResponse
opt := &Options{
API: testServer.URL,
}
n := newTransport("secret-123", opt)
_, err := n.post("/123", in, out, RequestOptions{retries: 2}, nil)
if err != nil {
t.Errorf("Expected successful request but got error")
}
}
func TestProxy(t *testing.T) {
testServerHit := false
testServer := httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
res.WriteHeader(http.StatusOK)
testServerHit = true
}))
defer testServer.Close()
in := Empty{}
var out ServerResponse
url, _ := url.Parse(testServer.URL)
opt := &Options{
Transport: &http.Transport{Proxy: http.ProxyURL(url)},
}
n := newTransport("secret-123", opt)
_, _ = n.post("/123", in, &out, RequestOptions{}, nil)
if !testServerHit {
t.Errorf("Expected request to hit proxy server")
}
}
func TestDefaultNetworkTimeout(t *testing.T) {
n := newTransport("secret-123", &Options{})
if n.client.Timeout != defaultTimeout {
t.Errorf("Expected default timeout %s, got %s", defaultTimeout, n.client.Timeout)
}
}
func TestCustomNetworkTimeout(t *testing.T) {
timeout := 5 * time.Second
n := newTransport("secret-123", &Options{NetworkTimeout: timeout})
if n.client.Timeout != timeout {
t.Errorf("Expected timeout %s, got %s", timeout, n.client.Timeout)
}
}
func TestCustomHTTPClient(t *testing.T) {
customTransport := &http.Transport{}
customClient := &http.Client{
Timeout: 7 * time.Second,
Transport: customTransport,
}
n := newTransport("secret-123", &Options{
HTTPClient: customClient,
NetworkTimeout: time.Second,
Transport: &http.Transport{},
})
if n.client != customClient {
t.Errorf("Expected transport to use provided HTTP client")
}
if n.client.Timeout != 7*time.Second {
t.Errorf("Expected provided client timeout to be preserved")
}
if n.client.Transport != customTransport {
t.Errorf("Expected provided client transport to be preserved")
}
}
func TestNetworkTimeoutAffectsRequests(t *testing.T) {
testServer := httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
time.Sleep(200 * time.Millisecond)
res.WriteHeader(http.StatusOK)
_ = json.NewEncoder(res).Encode(ServerResponse{Name: "slow"})
}))
defer testServer.Close()
n := newTransport("secret-123", &Options{
API: testServer.URL,
NetworkTimeout: 20 * time.Millisecond,
})
start := time.Now()
_, err := n.post("/123", Empty{}, &ServerResponse{}, RequestOptions{}, nil)
elapsed := time.Since(start)
if err == nil {
t.Errorf("Expected request to time out")
}
if elapsed >= 150*time.Millisecond {
t.Errorf("Expected timeout before server response, got %s", elapsed)
}
}
func TestCustomHTTPClientOverridesNetworkTimeoutForRequests(t *testing.T) {
testServer := httptest.NewServer(http.HandlerFunc(func(res http.ResponseWriter, req *http.Request) {
time.Sleep(50 * time.Millisecond)
res.WriteHeader(http.StatusOK)
_ = json.NewEncoder(res).Encode(ServerResponse{Name: "ok"})
}))
defer testServer.Close()
n := newTransport("secret-123", &Options{
API: testServer.URL,
NetworkTimeout: 10 * time.Millisecond,
HTTPClient: &http.Client{
Timeout: 200 * time.Millisecond,
},
})
var out ServerResponse
start := time.Now()
_, err := n.post("/123", Empty{}, &out, RequestOptions{}, nil)
elapsed := time.Since(start)
if err != nil {
t.Errorf("Expected request to succeed with custom HTTP client, got %v", err)
}
if out.Name != "ok" {
t.Errorf("Expected response body to be decoded")
}
if elapsed < 50*time.Millisecond {
t.Errorf("Expected request to wait for server response, got %s", elapsed)
}
}
func TestDownloadConfigSpecsLogsRequestBuildErrors(t *testing.T) {
InitializeGlobalOutputLogger(OutputLoggerOptions{}, nil)
n := newTransport("secret-123", &Options{
APIOverrides: APIOverrides{
DownloadConfigSpecs: "http://[::1",
},
})
var out downloadConfigSpecResponse
var err error
stderrLogs := swallow_stderr(func() {
_, err = n.download_config_specs(0, &out, nil, nil)
})
if err == nil {
t.Fatalf("Expected request build failure for invalid download_config_specs override")
}
if !strings.Contains(stderrLogs, "download_config_specs") {
t.Errorf("Expected stderr logs to mention download_config_specs, got %q", stderrLogs)
}
if !strings.Contains(stderrLogs, "base_api=http://[::1") {
t.Errorf("Expected stderr logs to mention invalid base API, got %q", stderrLogs)
}
if !strings.Contains(stderrLogs, "endpoint=/download_config_specs/secret-****.json") {
t.Errorf("Expected stderr logs to mention the endpoint path, got %q", stderrLogs)
}
}
func TestGetAPIFromURLForVersionedPath(t *testing.T) {
got := getAPIFromURL("http://localhost:8080/v1/download_config_specs")
if got != "http://localhost:8080/v1" {
t.Errorf("Expected version-normalized API, got %q", got)
}
}
func TestGetAPIFromURLForNonVersionedPath(t *testing.T) {
got := getAPIFromURL("http://localhost:8080/download_config_specs")
if got != "http://localhost:8080" {
t.Errorf("Expected host-only API for non-versioned path, got %q", got)
}
}
func TestGetNetworkSourceServiceAndRequestPathVersioned(t *testing.T) {
sourceService, requestPath := getNetworkSourceServiceAndRequestPath("http://localhost:8080/v1/download_config_specs/secret-key.json")
if sourceService != "http://localhost:8080" {
t.Errorf("Expected source service to be host root, got %q", sourceService)
}
if requestPath != "/v1/download_config_specs" {
t.Errorf("Expected versioned request path, got %q", requestPath)
}
}
func TestShouldLogNetworkRequestLatencyForLegacyNonVersionedEndpoint(t *testing.T) {
if !shouldLogNetworkRequestLatency("http://localhost:8080/download_config_specs/secret-key.json") {
t.Errorf("Expected non-versioned download_config_specs URL to be loggable")
}
}
func TestShouldNotLogNetworkRequestLatencyForNonV1VersionedEndpoint(t *testing.T) {
if shouldLogNetworkRequestLatency("http://localhost:8080/v3/download_config_specs/secret-key.json") {
t.Errorf("Expected non-v1 download_config_specs URL to be non-loggable in legacy go")
}
}
func TestGetAPIFromURLEdgeCases(t *testing.T) {
tests := []struct {
name string
in string
want string
}{
{
name: "base URL only remains unchanged",
in: "https://example.com",
want: "https://example.com",
},
{
name: "version path with no digits returns host",
in: "https://example.com/v/download_config_specs",
want: "https://example.com",
},
{
name: "version prefix with suffix returns host",
in: "https://example.com/v1beta/download_config_specs",
want: "https://example.com",
},
{
name: "version path only keeps version",
in: "https://example.com/v10",
want: "https://example.com/v10",
},
}
for _, tc := range tests {
t.Run(tc.name, func(t *testing.T) {
got := getAPIFromURL(tc.in)
if got != tc.want {
t.Errorf("Expected %q, got %q", tc.want, got)
}
})
}
}
func TestBuildURLSetsNormalizedCurrentSourceAPI(t *testing.T) {
n := newTransport("secret-123", &Options{
APIOverrides: APIOverrides{
DownloadConfigSpecs: "http://localhost:8080/v1/download_config_specs",
},
})
context := newInitContext()
_, err := n.buildURL("/v1/download_config_specs/secret-123.json", false, context)
if err != nil {
t.Fatalf("Expected buildURL to succeed, got %v", err)
}
if context.CurrentSourceAPI != "http://localhost:8080/v1" {
t.Errorf("Expected normalized source API to include only version prefix, got %q", context.CurrentSourceAPI)
}
}