-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathhttp_client_test.go
More file actions
538 lines (483 loc) · 16.3 KB
/
Copy pathhttp_client_test.go
File metadata and controls
538 lines (483 loc) · 16.3 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
373
374
375
376
377
378
379
380
381
382
383
384
385
386
387
388
389
390
391
392
393
394
395
396
397
398
399
400
401
402
403
404
405
406
407
408
409
410
411
412
413
414
415
416
417
418
419
420
421
422
423
424
425
426
427
428
429
430
431
432
433
434
435
436
437
438
439
440
441
442
443
444
445
446
447
448
449
450
451
452
453
454
455
456
457
458
459
460
461
462
463
464
465
466
467
468
469
470
471
472
473
474
475
476
477
478
479
480
481
482
483
484
485
486
487
488
489
490
491
492
493
494
495
496
497
498
499
500
501
502
503
504
505
506
507
508
509
510
511
512
513
514
515
516
517
518
519
520
521
522
523
524
525
526
527
528
529
530
531
532
533
534
535
536
537
538
package threads
import (
"context"
"errors"
"net"
"net/http"
"net/url"
"strings"
"sync/atomic"
"testing"
"time"
)
func TestHTTPClient_RetryOnServerError(t *testing.T) {
var attempts int32
handler := func(w http.ResponseWriter, r *http.Request) {
count := atomic.AddInt32(&attempts, 1)
if count < 3 {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(500)
_, _ = w.Write([]byte(`{"error":{"message":"Internal error","type":"OAuthException","code":2,"is_transient":true}}`))
return
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(200)
_, _ = w.Write([]byte(`{"ok":true}`))
}
httpClient := newTestHTTPClient(t, http.HandlerFunc(handler), &RetryConfig{
MaxRetries: 3,
InitialDelay: 10 * time.Millisecond,
MaxDelay: 50 * time.Millisecond,
BackoffFactor: 2.0,
})
resp, err := httpClient.Do(&RequestOptions{Method: "GET", Path: "/test"}, "token")
if err != nil {
t.Fatalf("expected success after retries, got: %v", err)
}
if resp.StatusCode != 200 {
t.Errorf("expected 200, got %d", resp.StatusCode)
}
if atomic.LoadInt32(&attempts) != 3 {
t.Errorf("expected 3 attempts, got %d", atomic.LoadInt32(&attempts))
}
}
func TestHTTPClient_NoRetryOnValidationError(t *testing.T) {
var attempts int32
handler := func(w http.ResponseWriter, r *http.Request) {
atomic.AddInt32(&attempts, 1)
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(400)
_, _ = w.Write([]byte(`{"error":{"message":"Bad request","type":"OAuthException","code":100}}`))
}
httpClient := newTestHTTPClient(t, http.HandlerFunc(handler), &RetryConfig{
MaxRetries: 3,
InitialDelay: 10 * time.Millisecond,
MaxDelay: 50 * time.Millisecond,
BackoffFactor: 2.0,
})
_, err := httpClient.Do(&RequestOptions{Method: "GET", Path: "/test"}, "token")
if err == nil {
t.Fatal("expected error for 400")
}
if atomic.LoadInt32(&attempts) != 1 {
t.Errorf("expected 1 attempt (no retry for 400), got %d", atomic.LoadInt32(&attempts))
}
}
func TestHTTPClient_ContextCancellation(t *testing.T) {
handler := func(w http.ResponseWriter, r *http.Request) {
select {
case <-r.Context().Done():
case <-time.After(5 * time.Second):
}
w.WriteHeader(200)
}
httpClient := newTestHTTPClient(t, http.HandlerFunc(handler), &RetryConfig{
MaxRetries: 0,
InitialDelay: time.Second,
MaxDelay: time.Second,
BackoffFactor: 1.0,
})
ctx, cancel := context.WithTimeout(context.Background(), 100*time.Millisecond)
defer cancel()
_, err := httpClient.Do(&RequestOptions{Method: "GET", Path: "/slow", Context: ctx}, "token")
if err == nil {
t.Fatal("expected error from context cancellation")
}
}
func TestHTTPClient_ParseRateLimitHeaders(t *testing.T) {
handler := func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("X-RateLimit-Limit", "100")
w.Header().Set("X-RateLimit-Remaining", "42")
w.Header().Set("X-RateLimit-Reset", "1735689600")
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(200)
_, _ = w.Write([]byte(`{}`))
}
httpClient := newTestHTTPClient(t, http.HandlerFunc(handler), &RetryConfig{
MaxRetries: 0, InitialDelay: time.Second, MaxDelay: time.Second, BackoffFactor: 1.0,
})
resp, err := httpClient.Do(&RequestOptions{Method: "GET", Path: "/test"}, "token")
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if resp.RateLimit == nil {
t.Fatal("expected rate limit info")
}
if resp.RateLimit.Limit != 100 {
t.Errorf("expected limit 100, got %d", resp.RateLimit.Limit)
}
if resp.RateLimit.Remaining != 42 {
t.Errorf("expected remaining 42, got %d", resp.RateLimit.Remaining)
}
}
func TestHTTPClient_PUT(t *testing.T) {
handler := func(w http.ResponseWriter, r *http.Request) {
if r.Method != "PUT" {
t.Errorf("expected PUT, got %s", r.Method)
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(200)
_, _ = w.Write([]byte(`{"ok":true}`))
}
httpClient := newTestHTTPClient(t, http.HandlerFunc(handler), &RetryConfig{
MaxRetries: 0, InitialDelay: time.Second, MaxDelay: time.Second, BackoffFactor: 1.0,
})
resp, err := httpClient.PUT("/test", url.Values{"key": {"value"}}, "token")
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if resp.StatusCode != 200 {
t.Errorf("expected 200, got %d", resp.StatusCode)
}
}
func TestHTTPClient_DELETE(t *testing.T) {
handler := func(w http.ResponseWriter, r *http.Request) {
if r.Method != "DELETE" {
t.Errorf("expected DELETE, got %s", r.Method)
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(200)
_, _ = w.Write([]byte(`{"ok":true}`))
}
httpClient := newTestHTTPClient(t, http.HandlerFunc(handler), &RetryConfig{
MaxRetries: 0, InitialDelay: time.Second, MaxDelay: time.Second, BackoffFactor: 1.0,
})
resp, err := httpClient.DELETE("/test", "token")
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if resp.StatusCode != 200 {
t.Errorf("expected 200, got %d", resp.StatusCode)
}
}
func TestHTTPClient_POST_URLValues(t *testing.T) {
handler := func(w http.ResponseWriter, r *http.Request) {
if r.Method != "POST" {
t.Errorf("expected POST, got %s", r.Method)
}
if r.Header.Get("Content-Type") != "application/x-www-form-urlencoded" {
t.Errorf("expected application/x-www-form-urlencoded, got %s", r.Header.Get("Content-Type"))
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(200)
_, _ = w.Write([]byte(`{}`))
}
httpClient := newTestHTTPClient(t, http.HandlerFunc(handler), &RetryConfig{
MaxRetries: 0, InitialDelay: time.Second, MaxDelay: time.Second, BackoffFactor: 1.0,
})
_, err := httpClient.POST("/test", url.Values{"key": {"val"}}, "token")
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
}
func TestHTTPClient_POST_JSONBody(t *testing.T) {
handler := func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("Content-Type") != "application/json" {
t.Errorf("expected application/json, got %s", r.Header.Get("Content-Type"))
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(200)
_, _ = w.Write([]byte(`{}`))
}
httpClient := newTestHTTPClient(t, http.HandlerFunc(handler), &RetryConfig{
MaxRetries: 0, InitialDelay: time.Second, MaxDelay: time.Second, BackoffFactor: 1.0,
})
// Passing a struct should be JSON-encoded
_, err := httpClient.POST("/test", map[string]string{"key": "value"}, "token")
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
}
func TestHTTPClient_POST_StringBody(t *testing.T) {
handler := func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("Content-Type") != "text/plain" {
t.Errorf("expected text/plain, got %s", r.Header.Get("Content-Type"))
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(200)
_, _ = w.Write([]byte(`{}`))
}
httpClient := newTestHTTPClient(t, http.HandlerFunc(handler), &RetryConfig{
MaxRetries: 0, InitialDelay: time.Second, MaxDelay: time.Second, BackoffFactor: 1.0,
})
_, err := httpClient.POST("/test", "hello body", "token")
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
}
func TestHTTPClient_POST_ByteBody(t *testing.T) {
handler := func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("Content-Type") != "application/octet-stream" {
t.Errorf("expected application/octet-stream, got %s", r.Header.Get("Content-Type"))
}
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(200)
_, _ = w.Write([]byte(`{}`))
}
httpClient := newTestHTTPClient(t, http.HandlerFunc(handler), &RetryConfig{
MaxRetries: 0, InitialDelay: time.Second, MaxDelay: time.Second, BackoffFactor: 1.0,
})
_, err := httpClient.POST("/test", []byte("binary data"), "token")
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
}
func TestWrapNetworkError_Timeout(t *testing.T) {
httpClient := &HTTPClient{
logger: &noopLogger{},
}
// Create a timeout error
timeoutErr := &net.DNSError{IsTimeout: true}
wrapped := httpClient.wrapNetworkError(timeoutErr)
var netErr *NetworkError
if !errors.As(wrapped, &netErr) {
t.Fatalf("expected NetworkError, got %T", wrapped)
}
if !netErr.Temporary {
t.Error("expected temporary error for timeout")
}
}
func TestWrapNetworkError_Generic(t *testing.T) {
httpClient := &HTTPClient{
logger: &noopLogger{},
}
wrapped := httpClient.wrapNetworkError(errors.New("some network problem"))
var netErr *NetworkError
if !errors.As(wrapped, &netErr) {
t.Fatalf("expected NetworkError, got %T", wrapped)
}
if netErr.Temporary {
t.Error("expected non-temporary error for generic error")
}
}
func TestCreateErrorFromResponse_401(t *testing.T) {
httpClient := &HTTPClient{logger: &noopLogger{}}
resp := &Response{
StatusCode: 401,
Body: []byte(`{"error":{"message":"Unauthorized","type":"OAuthException","code":190}}`),
}
err := httpClient.createErrorFromResponse(resp)
if !IsAuthenticationError(err) {
t.Errorf("expected AuthenticationError, got %T", err)
}
}
func TestCreateErrorFromResponse_429(t *testing.T) {
httpClient := &HTTPClient{logger: &noopLogger{}}
resp := &Response{
StatusCode: 429,
Body: []byte(`{"error":{"message":"rate limited","type":"rate_limit","code":429}}`),
RateLimit: &RateLimitInfo{RetryAfter: 60 * time.Second, Reset: time.Now().Add(time.Minute)},
}
err := httpClient.createErrorFromResponse(resp)
if !IsRateLimitError(err) {
t.Errorf("expected RateLimitError, got %T", err)
}
}
func TestCreateErrorFromResponse_429_NoRateLimit(t *testing.T) {
httpClient := &HTTPClient{logger: &noopLogger{}}
resp := &Response{
StatusCode: 429,
Body: []byte(`{"error":{"message":"rate limited"}}`),
}
err := httpClient.createErrorFromResponse(resp)
if !IsRateLimitError(err) {
t.Errorf("expected RateLimitError, got %T", err)
}
}
func TestCreateErrorFromResponse_429_WithRateLimiter(t *testing.T) {
rl := NewRateLimiter(&RateLimiterConfig{InitialLimit: 100})
httpClient := &HTTPClient{logger: &noopLogger{}}
httpClient.setRateLimiter(rl)
resp := &Response{
StatusCode: 429,
Body: []byte(`{"error":{"message":"rate limited"}}`),
RateLimit: &RateLimitInfo{RetryAfter: 30 * time.Second},
}
_ = httpClient.createErrorFromResponse(resp)
if !rl.IsRateLimited() {
t.Error("expected rate limiter to be marked as rate limited")
}
}
func TestCreateErrorFromResponse_400(t *testing.T) {
httpClient := &HTTPClient{logger: &noopLogger{}}
resp := &Response{
StatusCode: 400,
Body: []byte(`{"error":{"message":"Bad request","type":"validation","code":100}}`),
}
err := httpClient.createErrorFromResponse(resp)
if !IsValidationError(err) {
t.Errorf("expected ValidationError, got %T", err)
}
}
func TestCreateErrorFromResponse_422(t *testing.T) {
httpClient := &HTTPClient{logger: &noopLogger{}}
resp := &Response{
StatusCode: 422,
Body: []byte(`{"error":{"message":"Unprocessable","type":"validation","code":100}}`),
}
err := httpClient.createErrorFromResponse(resp)
if !IsValidationError(err) {
t.Errorf("expected ValidationError, got %T", err)
}
}
func TestCreateErrorFromResponse_500(t *testing.T) {
httpClient := &HTTPClient{logger: &noopLogger{}}
resp := &Response{
StatusCode: 500,
Body: []byte(`{"error":{"message":"Server error","type":"server","code":500,"is_transient":true}}`),
}
err := httpClient.createErrorFromResponse(resp)
if !IsAPIError(err) {
t.Errorf("expected APIError, got %T", err)
}
}
func TestCreateErrorFromResponse_EmptyBody(t *testing.T) {
httpClient := &HTTPClient{logger: &noopLogger{}}
resp := &Response{
StatusCode: 500,
Body: nil,
}
err := httpClient.createErrorFromResponse(resp)
if err == nil {
t.Fatal("expected error")
}
}
func TestCreateErrorFromResponse_LongBody(t *testing.T) {
httpClient := &HTTPClient{logger: &noopLogger{}}
// Create a body longer than 500 chars
longBody := make([]byte, 600)
for i := range longBody {
longBody[i] = 'x'
}
resp := &Response{
StatusCode: 500,
Body: longBody,
}
err := httpClient.createErrorFromResponse(resp)
if err == nil {
t.Fatal("expected error")
}
}
func TestLogRequest_WithLogger(t *testing.T) {
httpClient := &HTTPClient{logger: &noopLogger{}}
req, _ := http.NewRequest("GET", "http://example.com/test", nil)
// Should not panic
httpClient.logRequest(req, nil)
}
func TestLogRequest_WithJSONBody(t *testing.T) {
httpClient := &HTTPClient{logger: &noopLogger{}}
req, _ := http.NewRequest("POST", "http://example.com/test", nil)
req.Header.Set("Content-Type", "application/json")
httpClient.logRequest(req, map[string]string{"key": "value"})
}
func TestLogRequest_WithNonJSONBody(t *testing.T) {
httpClient := &HTTPClient{logger: &noopLogger{}}
req, _ := http.NewRequest("POST", "http://example.com/test", nil)
req.Header.Set("Content-Type", "text/plain")
httpClient.logRequest(req, "hello")
}
func TestLogRequest_NilLogger(t *testing.T) {
httpClient := &HTTPClient{logger: nil}
req, _ := http.NewRequest("GET", "http://example.com/test", nil)
// Should not panic
httpClient.logRequest(req, nil)
}
func TestHTTPClient_ParseRetryAfterHeader(t *testing.T) {
handler := func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("X-RateLimit-Limit", "100")
w.Header().Set("X-RateLimit-Remaining", "0")
w.Header().Set("Retry-After", "60")
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(200)
_, _ = w.Write([]byte(`{}`))
}
httpClient := newTestHTTPClient(t, http.HandlerFunc(handler), &RetryConfig{
MaxRetries: 0, InitialDelay: time.Second, MaxDelay: time.Second, BackoffFactor: 1.0,
})
resp, err := httpClient.Do(&RequestOptions{Method: "GET", Path: "/test"}, "token")
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if resp.RateLimit.RetryAfter != 60*time.Second {
t.Errorf("expected 60s retry after, got %v", resp.RateLimit.RetryAfter)
}
}
func TestHTTPClient_NoRateLimitHeaders(t *testing.T) {
handler := func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
w.WriteHeader(200)
_, _ = w.Write([]byte(`{}`))
}
httpClient := newTestHTTPClient(t, http.HandlerFunc(handler), &RetryConfig{
MaxRetries: 0, InitialDelay: time.Second, MaxDelay: time.Second, BackoffFactor: 1.0,
})
resp, err := httpClient.Do(&RequestOptions{Method: "GET", Path: "/test"}, "token")
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if resp.RateLimit != nil {
t.Error("expected nil rate limit info when no headers")
}
}
// TestSanitizeURL_RedactsSecrets: several Threads auth endpoints pass
// access_token / client_secret in the query string, so the debug log path
// must redact them before writing the URL.
func TestSanitizeURL_RedactsSecrets(t *testing.T) {
cases := []struct {
name string
raw string
want []string // substrings that MUST appear
notWant []string // substrings that MUST NOT appear
}{
{
name: "access_token redacted",
raw: "https://api.example.com/me?fields=id&access_token=SECRET123",
want: []string{"access_token=%5BREDACTED%5D", "fields=id"},
notWant: []string{"SECRET123"},
},
{
name: "client_secret redacted",
raw: "https://api.example.com/oauth/access_token?client_id=pub&client_secret=S3CR3T&grant_type=client_credentials",
want: []string{"client_secret=%5BREDACTED%5D", "client_id=pub"},
notWant: []string{"S3CR3T"},
},
{
name: "multiple sensitive params redacted",
raw: "https://api.example.com/debug_token?input_token=IT&access_token=AT",
want: []string{"input_token=%5BREDACTED%5D", "access_token=%5BREDACTED%5D"},
notWant: []string{"IT", "AT"},
},
{
name: "no query string unchanged",
raw: "https://api.example.com/me",
want: []string{"https://api.example.com/me"},
notWant: []string{"REDACTED"},
},
{
name: "only non-sensitive params unchanged",
raw: "https://api.example.com/me?fields=id,username",
// Non-sensitive → fast path returns original RawQuery unmodified.
want: []string{"fields=id,username"},
notWant: []string{"REDACTED"},
},
}
for _, tc := range cases {
t.Run(tc.name, func(t *testing.T) {
u, err := url.Parse(tc.raw)
if err != nil {
t.Fatalf("parse: %v", err)
}
got := sanitizeURL(u)
for _, want := range tc.want {
if !strings.Contains(got, want) {
t.Errorf("expected %q to contain %q", got, want)
}
}
for _, notWant := range tc.notWant {
if strings.Contains(got, notWant) {
t.Errorf("expected %q NOT to contain %q", got, notWant)
}
}
})
}
}