-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathclient_test.go
More file actions
439 lines (390 loc) · 11.5 KB
/
client_test.go
File metadata and controls
439 lines (390 loc) · 11.5 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
package maxigo
import (
"context"
"encoding/json"
"errors"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"testing"
"time"
)
func TestNew(t *testing.T) {
t.Run("valid token", func(t *testing.T) {
c, err := New("test-token")
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if c == nil {
t.Fatal("client should not be nil")
}
if c.token != "test-token" {
t.Errorf("token = %q, want %q", c.token, "test-token")
}
if c.baseURL != defaultBaseURL {
t.Errorf("baseURL = %q, want %q", c.baseURL, defaultBaseURL)
}
})
t.Run("empty token", func(t *testing.T) {
_, err := New("")
if !errors.Is(err, ErrEmptyToken) {
t.Errorf("err = %v, want ErrEmptyToken", err)
}
})
t.Run("with base URL", func(t *testing.T) {
c, err := New("token", WithBaseURL("http://localhost:8080"))
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if c.baseURL != "http://localhost:8080" {
t.Errorf("baseURL = %q, want %q", c.baseURL, "http://localhost:8080")
}
})
t.Run("with timeout", func(t *testing.T) {
c, err := New("token", WithTimeout(5*time.Second))
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if c.timeout != 5*time.Second {
t.Errorf("timeout = %v, want %v", c.timeout, 5*time.Second)
}
})
t.Run("with custom HTTP client", func(t *testing.T) {
custom := &http.Client{Timeout: 99 * time.Second}
c, err := New("token", WithHTTPClient(custom))
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if c.httpClient == custom {
t.Error("httpClient should be a copy, not the original")
}
})
}
func testClient(t *testing.T, handler http.HandlerFunc) (*Client, *httptest.Server) {
t.Helper()
srv := httptest.NewServer(handler)
t.Cleanup(srv.Close)
c, err := New("test-token", WithBaseURL(srv.URL))
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
return c, srv
}
// strPtr returns a pointer to s. Test helper for *string fields.
func strPtr(s string) *string { return &s }
// writeJSON writes v as JSON to the response writer. Test helper.
func writeJSON(t *testing.T, w http.ResponseWriter, v any) {
t.Helper()
w.Header().Set("Content-Type", "application/json")
if err := json.NewEncoder(w).Encode(v); err != nil {
t.Fatalf("failed to encode JSON: %v", err)
}
}
// readJSON decodes the request body as JSON. Test helper.
func readJSON(t *testing.T, r *http.Request, v any) {
t.Helper()
if err := json.NewDecoder(r.Body).Decode(v); err != nil {
t.Fatalf("failed to decode JSON: %v", err)
}
}
// writeError writes an error response. Test helper.
func writeError(t *testing.T, w http.ResponseWriter, statusCode int, body string) {
t.Helper()
w.WriteHeader(statusCode)
if _, err := w.Write([]byte(body)); err != nil {
t.Fatalf("failed to write: %v", err)
}
}
func TestDoSuccess(t *testing.T) {
c, _ := testClient(t, func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("Authorization") != "test-token" {
t.Errorf("Authorization = %q, want %q", r.Header.Get("Authorization"), "test-token")
}
if r.URL.Query().Get("access_token") != "" {
t.Errorf("access_token should not be in query, got %q", r.URL.Query().Get("access_token"))
}
w.Header().Set("Content-Type", "application/json")
writeJSON(t, w, map[string]string{"status": "ok"})
})
var result map[string]string
err := c.do(context.Background(), "Test", http.MethodGet, "/test", nil, nil, &result)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if result["status"] != "ok" {
t.Errorf("status = %q, want %q", result["status"], "ok")
}
}
func TestDoWithBody(t *testing.T) {
c, _ := testClient(t, func(w http.ResponseWriter, r *http.Request) {
if r.Header.Get("Content-Type") != "application/json" {
t.Errorf("Content-Type = %q, want %q", r.Header.Get("Content-Type"), "application/json")
}
var body map[string]string
readJSON(t, r, &body)
if body["text"] != "hello" {
t.Errorf("text = %q, want %q", body["text"], "hello")
}
writeJSON(t, w, map[string]bool{"success": true})
})
body := map[string]string{"text": "hello"}
var result map[string]bool
err := c.do(context.Background(), "Test", http.MethodPost, "/test", nil, body, &result)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
if !result["success"] {
t.Error("success should be true")
}
}
func TestDoAPIError(t *testing.T) {
tests := []struct {
name string
statusCode int
body string
wantMsg string
}{
{
name: "unauthorized",
statusCode: http.StatusUnauthorized,
body: `{"code":"verify.token","message":"Invalid access_token"}`,
wantMsg: "Invalid access_token",
},
{
name: "forbidden",
statusCode: http.StatusForbidden,
body: `{"code":"access.denied","message":"you don't have permission"}`,
wantMsg: "you don't have permission",
},
{
name: "not found",
statusCode: http.StatusNotFound,
body: `{"code":"not.found","message":"chat not found"}`,
wantMsg: "chat not found",
},
{
name: "rate limited",
statusCode: http.StatusTooManyRequests,
body: `{"code":"rate.limit","message":"too many requests"}`,
wantMsg: "too many requests",
},
{
name: "server error",
statusCode: http.StatusInternalServerError,
body: `{"code":"internal","message":"internal server error"}`,
wantMsg: "internal server error",
},
{
name: "invalid JSON error body",
statusCode: http.StatusBadGateway,
body: `not json`,
wantMsg: "Bad Gateway",
},
{
name: "error with error field only",
statusCode: http.StatusBadRequest,
body: `{"code":"bad","error":"something broke"}`,
wantMsg: "something broke",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
c, _ := testClient(t, func(w http.ResponseWriter, r *http.Request) {
writeError(t, w, tt.statusCode, tt.body)
})
err := c.do(context.Background(), "TestOp", http.MethodGet, "/test", nil, nil, nil)
if err == nil {
t.Fatal("expected error")
}
var e *Error
if !errors.As(err, &e) {
t.Fatalf("expected *Error, got %T", err)
}
if e.Kind != ErrAPI {
t.Errorf("Kind = %v, want ErrAPI", e.Kind)
}
if e.StatusCode != tt.statusCode {
t.Errorf("StatusCode = %d, want %d", e.StatusCode, tt.statusCode)
}
if e.Message != tt.wantMsg {
t.Errorf("Message = %q, want %q", e.Message, tt.wantMsg)
}
if e.Op != "TestOp" {
t.Errorf("Op = %q, want %q", e.Op, "TestOp")
}
})
}
}
func TestDoContextCanceled(t *testing.T) {
c, _ := testClient(t, func(w http.ResponseWriter, r *http.Request) {
time.Sleep(5 * time.Second)
})
ctx, cancel := context.WithCancel(context.Background())
cancel() // cancel immediately
err := c.do(ctx, "TestOp", http.MethodGet, "/test", nil, nil, nil)
if err == nil {
t.Fatal("expected error")
}
var e *Error
if !errors.As(err, &e) {
t.Fatalf("expected *Error, got %T", err)
}
if e.Kind != ErrTimeout {
t.Errorf("Kind = %v, want ErrTimeout", e.Kind)
}
if !e.Timeout() {
t.Error("Timeout() should return true")
}
}
func TestDoDecodeError(t *testing.T) {
c, _ := testClient(t, func(w http.ResponseWriter, r *http.Request) {
w.Header().Set("Content-Type", "application/json")
_, _ = w.Write([]byte(`{invalid json`))
})
var result map[string]string
err := c.do(context.Background(), "TestOp", http.MethodGet, "/test", nil, nil, &result)
if err == nil {
t.Fatal("expected error")
}
var e *Error
if !errors.As(err, &e) {
t.Fatalf("expected *Error, got %T", err)
}
if e.Kind != ErrDecode {
t.Errorf("Kind = %v, want ErrDecode", e.Kind)
}
}
func TestDoNilResult(t *testing.T) {
c, _ := testClient(t, func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte(`{"ignored":"data"}`))
})
err := c.do(context.Background(), "TestOp", http.MethodDelete, "/test", nil, nil, nil)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
}
func TestIsTimeout(t *testing.T) {
t.Run("true for timeout error", func(t *testing.T) {
if !isTimeout(&testTimeoutError{timeout: true}) {
t.Error("isTimeout should return true")
}
})
t.Run("false for non-timeout error", func(t *testing.T) {
if isTimeout(&testTimeoutError{timeout: false}) {
t.Error("isTimeout should return false")
}
})
t.Run("false for regular error", func(t *testing.T) {
if isTimeout(errors.New("some error")) {
t.Error("isTimeout should return false for regular error")
}
})
}
type testTimeoutError struct {
timeout bool
}
func (e *testTimeoutError) Error() string { return "test timeout" }
func (e *testTimeoutError) Timeout() bool { return e.timeout }
func TestDoMarshalError(t *testing.T) {
c, _ := testClient(t, func(w http.ResponseWriter, r *http.Request) {
t.Fatal("request should not be sent")
})
// func() cannot be marshaled to JSON
err := c.do(context.Background(), "TestOp", http.MethodPost, "/test", nil, func() {}, nil)
if err == nil {
t.Fatal("expected error")
}
var e *Error
if !errors.As(err, &e) {
t.Fatalf("expected *Error, got %T", err)
}
if e.Kind != ErrDecode {
t.Errorf("Kind = %v, want ErrDecode", e.Kind)
}
if e.Op != "TestOp" {
t.Errorf("Op = %q, want TestOp", e.Op)
}
}
func TestDoHTTPClientTimeout(t *testing.T) {
srv := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
time.Sleep(time.Second)
}))
t.Cleanup(srv.Close)
c, err := New("test-token",
WithBaseURL(srv.URL),
WithHTTPClient(&http.Client{Timeout: 5 * time.Millisecond}),
WithTimeout(0),
)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
err = c.do(context.Background(), "TestOp", http.MethodGet, "/test", nil, nil, nil)
if err == nil {
t.Fatal("expected error")
}
var e *Error
if !errors.As(err, &e) {
t.Fatalf("expected *Error, got %T", err)
}
if e.Kind != ErrTimeout {
t.Errorf("Kind = %v, want ErrTimeout", e.Kind)
}
}
func TestDoUploadTimeout(t *testing.T) {
c, srv := testClient(t, func(w http.ResponseWriter, r *http.Request) {
t.Fatal("request should not reach server")
})
ctx, cancel := context.WithCancel(context.Background())
cancel()
_, err := c.doUpload(ctx, "TestUpload", srv.URL+"/upload", "test.txt", strings.NewReader("data"))
if err == nil {
t.Fatal("expected error")
}
var e *Error
if !errors.As(err, &e) {
t.Fatalf("expected *Error, got %T", err)
}
if e.Kind != ErrTimeout {
t.Errorf("Kind = %v, want ErrTimeout", e.Kind)
}
}
func TestDoUploadNon200(t *testing.T) {
c, srv := testClient(t, func(w http.ResponseWriter, r *http.Request) {
writeError(t, w, http.StatusInternalServerError, "upload failed")
})
_, err := c.doUpload(context.Background(), "TestUpload", srv.URL+"/upload", "test.txt", strings.NewReader("data"))
if err == nil {
t.Fatal("expected error")
}
var e *Error
if !errors.As(err, &e) {
t.Fatalf("expected *Error, got %T", err)
}
if e.Kind != ErrAPI {
t.Errorf("Kind = %v, want ErrAPI", e.Kind)
}
if e.StatusCode != http.StatusInternalServerError {
t.Errorf("StatusCode = %d, want 500", e.StatusCode)
}
}
func TestDoQueryParams(t *testing.T) {
c, _ := testClient(t, func(w http.ResponseWriter, r *http.Request) {
if r.URL.Query().Get("chat_id") != "123" {
t.Errorf("chat_id = %q, want %q", r.URL.Query().Get("chat_id"), "123")
}
if r.URL.Query().Get("count") != "50" {
t.Errorf("count = %q, want %q", r.URL.Query().Get("count"), "50")
}
w.WriteHeader(http.StatusOK)
_, _ = w.Write([]byte(`{}`))
})
q := make(url.Values)
q.Set("chat_id", "123")
q.Set("count", "50")
err := c.do(context.Background(), "TestOp", http.MethodGet, "/test", q, nil, nil)
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
}