-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient_test.go
More file actions
372 lines (314 loc) · 10.9 KB
/
client_test.go
File metadata and controls
372 lines (314 loc) · 10.9 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
329
330
331
332
333
334
335
336
337
338
339
340
341
342
343
344
345
346
347
348
349
350
351
352
353
354
355
356
357
358
359
360
361
362
363
364
365
366
367
368
369
370
371
372
package control
import (
"context"
"fmt"
"math/rand"
"net/http"
"net/http/httptest"
"os"
"sync/atomic"
"testing"
"time"
"github.com/stretchr/testify/assert"
)
var token string
var url string = API_URL
var apps []string
func TestMain(m *testing.M) {
token = os.Getenv("ABLY_ACCOUNT_TOKEN")
rand.Seed(time.Now().UnixNano())
if os.Getenv("ABLY_CONTROL_URL") != "" {
url = os.Getenv("ABLY_CONTROL_URL")
}
// Attempt to clean up apps if anything went wrong (only if not skipping integration tests)
if os.Getenv("SKIP_INTEGRATION") == "" && token != "" {
client, _, err := NewClientWithURL(token, url)
if err == nil {
for _, v := range apps {
_ = client.DeleteApp(v)
}
}
}
code := m.Run()
os.Exit(code)
}
// skipIntegrationTest skips tests that interact with the API if SKIP_INTEGRATION is set.
func skipIntegrationTest(t *testing.T) {
if os.Getenv("SKIP_INTEGRATION") != "" {
t.Skip("SKIP_INTEGRATION is set, skipping integration test")
}
}
func newTestApp(t *testing.T, client *Client) App {
n := rand.Uint64()
name := "test-" + fmt.Sprint(n)
t.Logf("creating app with name: %s", name)
app := NewApp{
Name: name,
Status: "enabled",
//TLSOnly: false,
FcmKey: "",
FcmServiceAccount: "",
FcmProjectId: "",
ApnsCertificate: "",
ApnsPrivateKey: "",
ApnsUseSandboxEndpoint: false,
}
app_ret, err := client.CreateApp(&app)
assert.NoError(t, err)
apps = append(apps, app.ID)
return app_ret
}
func newTestClient(t *testing.T) (Client, Me) {
skipIntegrationTest(t)
client, me, err := NewClientWithURL(token, url)
assert.NoError(t, err)
return client, me
}
// TestAblyAgent tests that client requests set the Ably-Agent HTTP header.
func TestAblyAgent(t *testing.T) {
// start a test HTTP server which tracks the value of the Ably-Agent
// HTTP header and returns an empty JSON object.
var ablyAgent string
handler := http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
ablyAgent = req.Header.Get("Ably-Agent")
w.Header().Set("Content-Type", "application/json")
w.Header().Set("Content-Length", "2")
w.WriteHeader(http.StatusOK)
w.Write([]byte("{}"))
})
srv := httptest.NewServer(handler)
// initialise a client, which will make a request to /me
client, _, err := NewClientWithURL("s3cr3t", srv.URL)
assert.NoError(t, err)
// check the Ably-Agent HTTP header was set
assert.Equal(t, "ably-control-go/"+VERSION, ablyAgent)
// add an extra Ably-Agent entry
client.AppendAblyAgent("test", "1.2.3")
// check requests now set the updated Ably-Agent HTTP header
_, err = client.Me()
assert.NoError(t, err)
assert.Equal(t, "ably-control-go/"+VERSION+" test/1.2.3", ablyAgent)
}
// noRetryDelay returns a zero-delay backoff function for fast tests.
func noRetryDelay() Backoff {
return func(min, max time.Duration, attemptNum int, resp *http.Response) time.Duration {
return 0
}
}
// TestRetryOn5xxErrors tests that the client retries on 5xx server errors.
func TestRetryOn5xxErrors(t *testing.T) {
var requestCount int32
handler := http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
count := atomic.AddInt32(&requestCount, 1)
if count < 3 {
// First two requests return 503
w.WriteHeader(http.StatusServiceUnavailable)
w.Write([]byte(`{"message": "Service unavailable"}`))
return
}
// Third request succeeds
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
w.Write([]byte(`{}`))
})
srv := httptest.NewServer(handler)
defer srv.Close()
client, _, err := NewClientWithURL("test-token", srv.URL,
WithRetryMax(4),
WithBackoff(noRetryDelay()),
)
assert.NoError(t, err)
assert.Equal(t, int32(3), atomic.LoadInt32(&requestCount), "expected 3 requests (1 initial + 2 retries)")
assert.NotNil(t, client)
}
// TestNoRetryOn4xxErrors tests that the client does NOT retry on 4xx client errors.
func TestNoRetryOn4xxErrors(t *testing.T) {
var requestCount int32
handler := http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
atomic.AddInt32(&requestCount, 1)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusBadRequest)
w.Write([]byte(`{"message": "Bad request", "code": 40000, "statusCode": 400}`))
})
srv := httptest.NewServer(handler)
defer srv.Close()
_, _, err := NewClientWithURL("test-token", srv.URL,
WithRetryMax(4),
WithBackoff(noRetryDelay()),
)
assert.Error(t, err)
assert.Equal(t, int32(1), atomic.LoadInt32(&requestCount), "expected exactly 1 request (no retries on 4xx)")
errorInfo, ok := err.(ErrorInfo)
assert.True(t, ok, "error should be ErrorInfo")
assert.Equal(t, 400, errorInfo.StatusCode)
}
// TestRetryMaxExceeded tests that the client gives up after max retries.
func TestRetryMaxExceeded(t *testing.T) {
var requestCount int32
handler := http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
atomic.AddInt32(&requestCount, 1)
w.WriteHeader(http.StatusServiceUnavailable)
w.Write([]byte(`{"message": "Service unavailable"}`))
})
srv := httptest.NewServer(handler)
defer srv.Close()
_, _, err := NewClientWithURL("test-token", srv.URL,
WithRetryMax(3),
WithBackoff(noRetryDelay()),
)
assert.Error(t, err)
// Initial request + 3 retries = 4 total requests
assert.Equal(t, int32(4), atomic.LoadInt32(&requestCount), "expected 4 requests (1 initial + 3 retries)")
}
// TestRetryMaxOption tests that WithRetryMax correctly configures retry attempts.
func TestRetryMaxOption(t *testing.T) {
var requestCount int32
handler := http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
atomic.AddInt32(&requestCount, 1)
w.WriteHeader(http.StatusServiceUnavailable)
w.Write([]byte(`{"message": "Service unavailable"}`))
})
srv := httptest.NewServer(handler)
defer srv.Close()
// Test with RetryMax of 1
_, _, err := NewClientWithURL("test-token", srv.URL,
WithRetryMax(1),
WithBackoff(noRetryDelay()),
)
assert.Error(t, err)
// Initial request + 1 retry = 2 total requests
assert.Equal(t, int32(2), atomic.LoadInt32(&requestCount), "expected 2 requests with RetryMax=1")
}
// TestBackoffConfiguration tests that backoff receives correct min/max configuration.
func TestBackoffConfiguration(t *testing.T) {
var capturedMin, capturedMax time.Duration
var capturedAttempts []int
handler := http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
w.WriteHeader(http.StatusServiceUnavailable)
w.Write([]byte(`{"message": "Service unavailable"}`))
})
srv := httptest.NewServer(handler)
defer srv.Close()
expectedMin := 5 * time.Second
expectedMax := 60 * time.Second
customBackoff := func(min, max time.Duration, attemptNum int, resp *http.Response) time.Duration {
capturedMin = min
capturedMax = max
capturedAttempts = append(capturedAttempts, attemptNum)
return 0 // Don't actually wait
}
_, _, _ = NewClientWithURL("test-token", srv.URL,
WithRetryMax(2),
WithRetryWaitMin(expectedMin),
WithRetryWaitMax(expectedMax),
WithBackoff(customBackoff),
)
assert.Equal(t, expectedMin, capturedMin, "backoff should receive configured min wait")
assert.Equal(t, expectedMax, capturedMax, "backoff should receive configured max wait")
assert.Equal(t, []int{0, 1}, capturedAttempts, "backoff should be called with attempt numbers 0 and 1")
}
// TestWithHTTPClient tests that a custom HTTP client can be provided.
func TestWithHTTPClient(t *testing.T) {
customTransport := &http.Transport{
MaxIdleConns: 100,
}
customHTTPClient := &http.Client{
Transport: customTransport,
Timeout: 30 * time.Second,
}
handler := http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
w.Write([]byte(`{}`))
})
srv := httptest.NewServer(handler)
defer srv.Close()
client, _, err := NewClientWithURL("test-token", srv.URL,
WithHTTPClient(customHTTPClient),
)
assert.NoError(t, err)
assert.NotNil(t, client)
// Verify the custom HTTP client is being used by checking it was set
assert.Equal(t, customHTTPClient, client.httpClient.HTTPClient)
}
// TestCheckRetryOption tests that a custom CheckRetry function can be provided.
func TestCheckRetryOption(t *testing.T) {
var checkRetryCalled int32
handler := http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
w.WriteHeader(http.StatusServiceUnavailable)
w.Write([]byte(`{"message": "Service unavailable"}`))
})
srv := httptest.NewServer(handler)
defer srv.Close()
customCheckRetry := func(ctx context.Context, resp *http.Response, err error) (bool, error) {
atomic.AddInt32(&checkRetryCalled, 1)
// Never retry
return false, nil
}
_, _, err := NewClientWithURL("test-token", srv.URL,
WithRetryMax(3),
WithCheckRetry(customCheckRetry),
WithBackoff(noRetryDelay()),
)
assert.Error(t, err)
// CheckRetry is called once and returns false, so only 1 request
assert.Equal(t, int32(1), atomic.LoadInt32(&checkRetryCalled), "custom CheckRetry should be called")
}
// TestRetryOn429TooManyRequests tests that the client retries on 429 rate limit errors.
func TestRetryOn429TooManyRequests(t *testing.T) {
var requestCount int32
handler := http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
count := atomic.AddInt32(&requestCount, 1)
if count < 3 {
// First two requests return 429
w.Header().Set("Retry-After", "0")
w.WriteHeader(http.StatusTooManyRequests)
w.Write([]byte(`{"message": "Rate limit exceeded"}`))
return
}
// Third request succeeds
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
w.Write([]byte(`{}`))
})
srv := httptest.NewServer(handler)
defer srv.Close()
client, _, err := NewClientWithURL("test-token", srv.URL,
WithRetryMax(4),
WithBackoff(noRetryDelay()),
)
assert.NoError(t, err)
assert.Equal(t, int32(3), atomic.LoadInt32(&requestCount), "expected 3 requests (1 initial + 2 retries on 429)")
assert.NotNil(t, client)
}
// TestRetryOnConnectionError tests that the client retries on connection errors.
// This simulates the status code 0 scenario that can occur with connection issues.
func TestRetryOnConnectionError(t *testing.T) {
var requestCount int32
// Start a server that we'll shut down to simulate connection errors
handler := http.HandlerFunc(func(w http.ResponseWriter, req *http.Request) {
count := atomic.AddInt32(&requestCount, 1)
if count < 3 {
// Close connection abruptly to simulate connection error
hj, ok := w.(http.Hijacker)
if ok {
conn, _, _ := hj.Hijack()
conn.Close()
return
}
}
// Third request succeeds
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(http.StatusOK)
w.Write([]byte(`{}`))
})
srv := httptest.NewServer(handler)
defer srv.Close()
client, _, err := NewClientWithURL("test-token", srv.URL,
WithRetryMax(4),
WithBackoff(noRetryDelay()),
)
assert.NoError(t, err)
assert.Equal(t, int32(3), atomic.LoadInt32(&requestCount), "expected 3 requests (retries on connection error)")
assert.NotNil(t, client)
}