-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathrequest_test.go
More file actions
659 lines (548 loc) · 16.4 KB
/
Copy pathrequest_test.go
File metadata and controls
659 lines (548 loc) · 16.4 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
539
540
541
542
543
544
545
546
547
548
549
550
551
552
553
554
555
556
557
558
559
560
561
562
563
564
565
566
567
568
569
570
571
572
573
574
575
576
577
578
579
580
581
582
583
584
585
586
587
588
589
590
591
592
593
594
595
596
597
598
599
600
601
602
603
604
605
606
607
608
609
610
611
612
613
614
615
616
617
618
619
620
621
622
623
624
625
626
627
628
629
630
631
632
633
634
635
636
637
638
639
640
641
642
643
644
645
646
647
648
649
650
651
652
653
654
655
656
657
658
659
package httpstream_test
import (
"context"
"encoding/json"
"io"
"net/http"
"net/http/httptest"
"net/url"
"strings"
"testing"
"time"
"github.com/nativebpm/httpstream"
)
func TestNewRequest(t *testing.T) {
client := http.Client{}
ctx := context.Background()
url, _ := url.Parse("http://example.com/api")
req := httpstream.NewRequest(ctx, client, http.MethodGet, url.String())
if req == nil {
t.Fatal("NewRequest returned nil")
}
}
func TestRequest_PathParam(t *testing.T) {
tests := []struct {
name string
url string
params map[string]string
expected string
}{
{
name: "single_param",
url: "/users/{id}",
params: map[string]string{"id": "123"},
expected: "/users/123",
},
{
name: "multiple_params",
url: "/users/{userId}/posts/{postId}",
params: map[string]string{"userId": "123", "postId": "456"},
expected: "/users/123/posts/456",
},
{
name: "param_with_special_chars",
url: "/files/{filename}",
params: map[string]string{"filename": "my-file.pdf"},
expected: "/files/my-file.pdf",
},
{
name: "param_at_end",
url: "/api/v1/resource/{id}",
params: map[string]string{"id": "abc-def-ghi"},
expected: "/api/v1/resource/abc-def-ghi",
},
{
name: "multiple_same_param",
url: "/path/{param}/nested/{param}",
params: map[string]string{"param": "value"},
expected: "/path/value/nested/value",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
var receivedPath string
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
receivedPath = r.URL.Path
w.WriteHeader(http.StatusOK)
}))
defer server.Close()
client := http.Client{}
ctx := context.Background()
url, _ := url.Parse(server.URL + tt.url)
req := httpstream.NewRequest(ctx, client, http.MethodGet, url.String())
for key, value := range tt.params {
req = req.PathParam(key, value)
}
resp, err := req.Send()
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
defer resp.Body.Close()
if receivedPath != tt.expected {
t.Errorf("expected path %s, got %s", tt.expected, receivedPath)
}
})
}
}
func TestRequest_PathInt(t *testing.T) {
var receivedPath string
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
receivedPath = r.URL.Path
w.WriteHeader(http.StatusOK)
}))
defer server.Close()
client := http.Client{}
ctx := context.Background()
url, _ := url.Parse(server.URL + "/users/{id}/score/{score}")
resp, err := httpstream.NewRequest(ctx, client, http.MethodGet,
url.String()).
PathInt("id", 123).
PathInt("score", 95).
Send()
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
defer resp.Body.Close()
expected := "/users/123/score/95"
if receivedPath != expected {
t.Errorf("expected path %s, got %s", expected, receivedPath)
}
}
func TestRequest_PathBool(t *testing.T) {
tests := []struct {
name string
value bool
expected string
}{
{
name: "true",
value: true,
expected: "/api/active/true",
},
{
name: "false",
value: false,
expected: "/api/active/false",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
var receivedPath string
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
receivedPath = r.URL.Path
w.WriteHeader(http.StatusOK)
}))
defer server.Close()
client := http.Client{}
ctx := context.Background()
url, _ := url.Parse(server.URL + "/api/active/{status}")
resp, err := httpstream.NewRequest(ctx, client, http.MethodGet,
url.String()).
PathBool("status", tt.value).
Send()
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
defer resp.Body.Close()
if receivedPath != tt.expected {
t.Errorf("expected path %s, got %s", tt.expected, receivedPath)
}
})
}
}
func TestRequest_PathFloat(t *testing.T) {
var receivedPath string
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
receivedPath = r.URL.Path
w.WriteHeader(http.StatusOK)
}))
defer server.Close()
client := http.Client{}
ctx := context.Background()
url, _ := url.Parse(server.URL + "/products/{price}")
resp, err := httpstream.NewRequest(ctx, client, http.MethodGet,
url.String()).
PathFloat("price", 19.99).
Send()
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
defer resp.Body.Close()
expected := "/products/19.99"
if receivedPath != expected {
t.Errorf("expected path %s, got %s", expected, receivedPath)
}
}
func TestRequest_PathParamWithQueryParams(t *testing.T) {
var receivedPath string
var receivedQuery string
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
receivedPath = r.URL.Path
receivedQuery = r.URL.RawQuery
w.WriteHeader(http.StatusOK)
}))
defer server.Close()
client := http.Client{}
ctx := context.Background()
url, _ := url.Parse(server.URL + "/users/{id}/posts")
resp, err := httpstream.NewRequest(ctx, client,
http.MethodGet, url.String()).
PathParam("id", "123").
Param("page", "2").
Param("limit", "10").
Send()
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
defer resp.Body.Close()
expectedPath := "/users/123/posts"
if receivedPath != expectedPath {
t.Errorf("expected path %s, got %s", expectedPath, receivedPath)
}
if !strings.Contains(receivedQuery, "page=2") {
t.Errorf("expected query to contain page=2, got %s", receivedQuery)
}
if !strings.Contains(receivedQuery, "limit=10") {
t.Errorf("expected query to contain limit=10, got %s", receivedQuery)
}
}
func TestRequest_PathParamChaining(t *testing.T) {
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
w.WriteHeader(http.StatusOK)
}))
defer server.Close()
client := http.Client{}
ctx := context.Background()
url, _ := url.Parse(server.URL + "/api/{version}/users/{id}")
// Test that all methods return *Request for chaining
req := httpstream.NewRequest(ctx, client,
http.MethodGet, url.String()).
PathParam("version", "v1").
Header("X-Custom", "value").
PathInt("id", 123).
Param("filter", "active").
Bool("verbose", true)
resp, err := req.Send()
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
t.Errorf("expected status 200, got %d", resp.StatusCode)
}
}
func TestRequest_Param(t *testing.T) {
var receivedQuery string
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
receivedQuery = r.URL.RawQuery
w.WriteHeader(http.StatusOK)
}))
defer server.Close()
client := http.Client{}
ctx := context.Background()
url, _ := url.Parse(server.URL + "/api")
resp, err := httpstream.NewRequest(ctx, client, http.MethodGet, url.String()).
Param("key1", "value1").
Param("key2", "value2").
Send()
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
defer resp.Body.Close()
if !strings.Contains(receivedQuery, "key1=value1") {
t.Errorf("expected query to contain key1=value1, got %s", receivedQuery)
}
if !strings.Contains(receivedQuery, "key2=value2") {
t.Errorf("expected query to contain key2=value2, got %s", receivedQuery)
}
}
func TestRequest_TypedParams(t *testing.T) {
tests := []struct {
name string
setup func(*httpstream.Request) *httpstream.Request
expected map[string]string
}{
{
name: "bool_true",
setup: func(r *httpstream.Request) *httpstream.Request {
return r.Bool("active", true)
},
expected: map[string]string{"active": "true"},
},
{
name: "bool_false",
setup: func(r *httpstream.Request) *httpstream.Request {
return r.Bool("active", false)
},
expected: map[string]string{"active": "false"},
},
{
name: "int",
setup: func(r *httpstream.Request) *httpstream.Request {
return r.Int("count", 42)
},
expected: map[string]string{"count": "42"},
},
{
name: "float",
setup: func(r *httpstream.Request) *httpstream.Request {
return r.Float("price", 19.99)
},
expected: map[string]string{"price": "19.99"},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
var receivedQuery string
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
receivedQuery = r.URL.RawQuery
w.WriteHeader(http.StatusOK)
}))
defer server.Close()
client := http.Client{}
ctx := context.Background()
url, _ := url.Parse(server.URL + "/api")
req := httpstream.NewRequest(ctx, client, http.MethodGet, url.String())
resp, err := tt.setup(req).Send()
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
defer resp.Body.Close()
for key, expected := range tt.expected {
expectedParam := key + "=" + expected
if !strings.Contains(receivedQuery, expectedParam) {
t.Errorf("expected query to contain %s, got %s", expectedParam, receivedQuery)
}
}
})
}
}
func TestRequest_Header(t *testing.T) {
var receivedHeader string
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
receivedHeader = r.Header.Get("X-API-Key")
w.WriteHeader(http.StatusOK)
}))
defer server.Close()
client := http.Client{}
ctx := context.Background()
url, _ := url.Parse(server.URL)
resp, err := httpstream.NewRequest(ctx, client, http.MethodGet, url.String()).
Header("X-API-Key", "secret-token-123").
Send()
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
defer resp.Body.Close()
if receivedHeader != "secret-token-123" {
t.Errorf("expected header X-API-Key=secret-token-123, got %s", receivedHeader)
}
}
func TestRequest_JSON(t *testing.T) {
type User struct {
Name string `json:"name"`
Email string `json:"email"`
}
var receivedUser User
var receivedContentType string
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
receivedContentType = r.Header.Get("Content-Type")
body, err := io.ReadAll(r.Body)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
if err := json.Unmarshal(body, &receivedUser); err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
w.WriteHeader(http.StatusOK)
}))
defer server.Close()
client := http.Client{}
ctx := context.Background()
url, _ := url.Parse(server.URL + "/api/users")
user := User{Name: "John Doe", Email: "john@example.com"}
resp, err := httpstream.NewRequest(ctx, client, http.MethodPost, url.String()).
JSON(user).
Send()
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
defer resp.Body.Close()
if resp.StatusCode != http.StatusOK {
t.Errorf("expected status 200, got %d", resp.StatusCode)
}
if receivedContentType != "application/json" {
t.Errorf("expected Content-Type application/json, got %s", receivedContentType)
}
if receivedUser.Name != user.Name || receivedUser.Email != user.Email {
t.Errorf("expected user %+v, got %+v", user, receivedUser)
}
}
func TestRequest_Body(t *testing.T) {
var receivedBody string
var receivedContentType string
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
receivedContentType = r.Header.Get("Content-Type")
body, err := io.ReadAll(r.Body)
if err != nil {
http.Error(w, err.Error(), http.StatusBadRequest)
return
}
receivedBody = string(body)
w.WriteHeader(http.StatusOK)
}))
defer server.Close()
client := http.Client{}
ctx := context.Background()
url, _ := url.Parse(server.URL)
bodyContent := "custom body content"
resp, err := httpstream.NewRequest(ctx, client, http.MethodPost, url.String()).
Body(io.NopCloser(strings.NewReader(bodyContent)), "text/plain").
Send()
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
defer resp.Body.Close()
if receivedContentType != "text/plain" {
t.Errorf("expected Content-Type text/plain, got %s", receivedContentType)
}
if receivedBody != bodyContent {
t.Errorf("expected body %s, got %s", bodyContent, receivedBody)
}
}
func TestRequest_ContextCancellation(t *testing.T) {
blockCh := make(chan struct{})
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
<-blockCh // Block until test cleanup
w.WriteHeader(http.StatusOK)
}))
defer func() {
close(blockCh)
server.Close()
}()
client := http.Client{}
ctx, cancel := context.WithTimeout(context.Background(), 50*time.Millisecond)
defer cancel()
url, _ := url.Parse(server.URL)
_, err := httpstream.NewRequest(ctx, client, http.MethodGet, url.String()).Send()
if err == nil {
t.Fatal("expected context cancellation error, got nil")
}
if !strings.Contains(err.Error(), "context deadline exceeded") {
t.Errorf("expected context deadline exceeded error, got: %v", err)
}
}
func TestRequest_Timeout(t *testing.T) {
// Create a slow server
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
time.Sleep(200 * time.Millisecond)
w.WriteHeader(http.StatusOK)
}))
defer server.Close()
client := http.Client{}
url, _ := url.Parse(server.URL)
// Test 1: Request should timeout
ctx := context.Background()
_, err := httpstream.NewRequest(ctx, client, http.MethodGet, url.String()).
Timeout(50 * time.Millisecond).
Send()
if err == nil {
t.Error("Expected timeout error, got nil")
}
if !strings.Contains(err.Error(), "context deadline exceeded") {
t.Errorf("Expected context deadline exceeded error, got: %v", err)
}
url, _ = url.Parse(server.URL)
// Test 2: Request should succeed with longer timeout
resp, err := httpstream.NewRequest(ctx, client, http.MethodGet, url.String()).
Timeout(500 * time.Millisecond).
Send()
if err != nil {
t.Errorf("Unexpected error: %v", err)
}
if resp != nil {
resp.Body.Close()
if resp.StatusCode != http.StatusOK {
t.Errorf("Expected status 200, got %d", resp.StatusCode)
}
}
}
func TestRequest_JSONWithTimeout(t *testing.T) {
// Server that processes slowly
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
time.Sleep(200 * time.Millisecond)
io.Copy(io.Discard, r.Body)
w.WriteHeader(http.StatusOK)
}))
defer server.Close()
client := http.Client{}
ctx := context.Background()
url, _ := url.Parse(server.URL)
data := map[string]string{"key": "value"}
_, err := httpstream.NewRequest(ctx, client, http.MethodPost, url.String()).
JSON(data).
Timeout(50 * time.Millisecond).
Send()
if err == nil {
t.Error("Expected timeout error, got nil")
}
if !strings.Contains(err.Error(), "context deadline exceeded") {
t.Errorf("Expected context deadline exceeded error, got: %v", err)
}
}
func TestRequest_ComplexChaining(t *testing.T) {
type RequestData struct {
Name string `json:"name"`
Price float64 `json:"price"`
Active bool `json:"active"`
}
var receivedPath string
var receivedQuery string
var receivedHeader string
var receivedData RequestData
server := httptest.NewServer(http.HandlerFunc(func(w http.ResponseWriter, r *http.Request) {
receivedPath = r.URL.Path
receivedQuery = r.URL.RawQuery
receivedHeader = r.Header.Get("Authorization")
body, _ := io.ReadAll(r.Body)
err := json.Unmarshal(body, &receivedData)
if err != nil {
http.Error(w, "Invalid request payload", http.StatusBadRequest)
return
}
w.WriteHeader(http.StatusOK)
}))
defer server.Close()
client := http.Client{}
ctx := context.Background()
url, _ := url.Parse(server.URL + "/api/{version}/products/{id}")
data := RequestData{Name: "Product", Price: 99.99, Active: true}
resp, err := httpstream.NewRequest(ctx, client, http.MethodPost, url.String()).
PathParam("version", "v1").
PathInt("id", 123).
Header("Authorization", "Bearer token123").
Param("source", "web").
Bool("notify", true).
JSON(data).
Timeout(5 * time.Second).
Send()
if err != nil {
t.Fatalf("unexpected error: %v", err)
}
defer resp.Body.Close()
expectedPath := "/api/v1/products/123"
if receivedPath != expectedPath {
t.Errorf("expected path %s, got %s", expectedPath, receivedPath)
}
if !strings.Contains(receivedQuery, "source=web") {
t.Errorf("expected query to contain source=web, got %s", receivedQuery)
}
if receivedHeader != "Bearer token123" {
t.Errorf("expected Authorization header, got %s", receivedHeader)
}
if receivedData.Name != data.Name {
t.Errorf("expected data name %s, got %s", data.Name, receivedData.Name)
}
}