-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathclient_test.go
More file actions
1010 lines (902 loc) · 26.5 KB
/
Copy pathclient_test.go
File metadata and controls
1010 lines (902 loc) · 26.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
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
660
661
662
663
664
665
666
667
668
669
670
671
672
673
674
675
676
677
678
679
680
681
682
683
684
685
686
687
688
689
690
691
692
693
694
695
696
697
698
699
700
701
702
703
704
705
706
707
708
709
710
711
712
713
714
715
716
717
718
719
720
721
722
723
724
725
726
727
728
729
730
731
732
733
734
735
736
737
738
739
740
741
742
743
744
745
746
747
748
749
750
751
752
753
754
755
756
757
758
759
760
761
762
763
764
765
766
767
768
769
770
771
772
773
774
775
776
777
778
779
780
781
782
783
784
785
786
787
788
789
790
791
792
793
794
795
796
797
798
799
800
801
802
803
804
805
806
807
808
809
810
811
812
813
814
815
816
817
818
819
820
821
822
823
824
825
826
827
828
829
830
831
832
833
834
835
836
837
838
839
840
841
842
843
844
845
846
847
848
849
850
851
852
853
854
855
856
857
858
859
860
861
862
863
864
865
866
867
868
869
870
871
872
873
874
875
876
877
878
879
880
881
882
883
884
885
886
887
888
889
890
891
892
893
894
895
896
897
898
899
900
901
902
903
904
905
906
907
908
909
910
911
912
913
914
915
916
917
918
919
920
921
922
923
924
925
926
927
928
929
930
931
932
933
934
935
936
937
938
939
940
941
942
943
944
945
946
947
948
949
950
951
952
953
954
955
956
957
958
959
960
961
962
963
964
965
966
967
968
969
970
971
972
973
974
975
976
977
978
979
980
981
982
983
984
985
986
987
988
989
990
991
992
993
994
995
996
997
998
999
1000
package http2
import (
"context"
"strings"
"sync"
"sync/atomic"
"testing"
"time"
)
// TestClientConstants tests client configuration constants
func TestClientConstants(t *testing.T) {
tests := []struct {
name string
constant interface{}
expected interface{}
}{
{"DefaultRequestTimeout", DefaultRequestTimeout, 30 * time.Second},
{"ConnectionSetupTimeout", ConnectionSetupTimeout, 10 * time.Second},
{"MaxRetryAttempts", MaxRetryAttempts, 3},
{"RetryBackoffDuration", RetryBackoffDuration, 100 * time.Millisecond},
{"ClientUserAgent", ClientUserAgent, "http2-client/1.0"},
{"RequestQueueSize", RequestQueueSize, 10000},
{"DefaultClientWindow", DefaultClientWindow, 1048576},
{"ClientMaxFrameSize", ClientMaxFrameSize, 1048576},
{"ClientMaxHeaderListSize", ClientMaxHeaderListSize, 16384},
{"ClientMaxConcurrentStreams", ClientMaxConcurrentStreams, 1000},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if tt.constant != tt.expected {
t.Errorf("%s = %v, want %v", tt.name, tt.constant, tt.expected)
}
})
}
}
// TestPseudoHeaderConstants tests HTTP/2 pseudo-header constants
func TestPseudoHeaderConstants(t *testing.T) {
tests := []struct {
name string
constant string
expected string
}{
{"PseudoHeaderMethod", PseudoHeaderMethod, ":method"},
{"PseudoHeaderPath", PseudoHeaderPath, ":path"},
{"PseudoHeaderScheme", PseudoHeaderScheme, ":scheme"},
{"PseudoHeaderAuthority", PseudoHeaderAuthority, ":authority"},
{"PseudoHeaderStatus", PseudoHeaderStatus, ":status"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if tt.constant != tt.expected {
t.Errorf("%s = %s, want %s", tt.name, tt.constant, tt.expected)
}
})
}
}
// TestHTTPMethodConstants tests HTTP method constants
func TestHTTPMethodConstants(t *testing.T) {
tests := []struct {
name string
constant string
expected string
}{
{"MethodGET", MethodGET, "GET"},
{"MethodPOST", MethodPOST, "POST"},
{"MethodPUT", MethodPUT, "PUT"},
{"MethodDELETE", MethodDELETE, "DELETE"},
{"MethodHEAD", MethodHEAD, "HEAD"},
{"MethodOPTIONS", MethodOPTIONS, "OPTIONS"},
{"MethodPATCH", MethodPATCH, "PATCH"},
{"MethodCONNECT", MethodCONNECT, "CONNECT"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if tt.constant != tt.expected {
t.Errorf("%s = %s, want %s", tt.name, tt.constant, tt.expected)
}
})
}
}
// TestSchemeConstants tests HTTP scheme constants
func TestSchemeConstants(t *testing.T) {
tests := []struct {
name string
constant string
expected string
}{
{"SchemeHTTP", SchemeHTTP, "http"},
{"SchemeHTTPS", SchemeHTTPS, "https"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if tt.constant != tt.expected {
t.Errorf("%s = %s, want %s", tt.name, tt.constant, tt.expected)
}
})
}
}
// TestHeaderConstants tests common HTTP header constants
func TestHeaderConstants(t *testing.T) {
tests := []struct {
name string
constant string
expected string
}{
{"HeaderContentType", HeaderContentType, "content-type"},
{"HeaderContentLength", HeaderContentLength, "content-length"},
{"HeaderAccept", HeaderAccept, "accept"},
{"HeaderUserAgent", HeaderUserAgent, "user-agent"},
{"HeaderAuthorization", HeaderAuthorization, "authorization"},
{"HeaderAcceptEncoding", HeaderAcceptEncoding, "accept-encoding"},
{"HeaderCacheControl", HeaderCacheControl, "cache-control"},
{"HeaderConnection", HeaderConnection, "connection"},
{"HeaderHost", HeaderHost, "host"},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if tt.constant != tt.expected {
t.Errorf("%s = %s, want %s", tt.name, tt.constant, tt.expected)
}
})
}
}
// TestClientRequest tests ClientRequest structure
func TestClientRequest(t *testing.T) {
ctx := context.Background()
respChan := make(chan *ClientResponse, 1)
req := &ClientRequest{
Method: "GET",
URL: "/test",
Headers: map[string]string{"foo": "bar"},
Body: []byte("test body"),
Timeout: 5 * time.Second,
Context: ctx,
Response: respChan,
}
if req.Method != "GET" {
t.Errorf("Method = %s, want GET", req.Method)
}
if req.URL != "/test" {
t.Errorf("URL = %s, want /test", req.URL)
}
if req.Headers["foo"] != "bar" {
t.Errorf("Headers[foo] = %s, want bar", req.Headers["foo"])
}
if string(req.Body) != "test body" {
t.Errorf("Body = %s, want test body", string(req.Body))
}
if req.Timeout != 5*time.Second {
t.Errorf("Timeout = %v, want 5s", req.Timeout)
}
}
// TestClientResponse tests ClientResponse structure
func TestClientResponse(t *testing.T) {
resp := &ClientResponse{
StatusCode: 200,
Status: "200",
Headers: map[string]string{"content-type": "text/html"},
Body: []byte("response body"),
Error: nil,
StreamID: 1,
Duration: 100 * time.Millisecond,
}
if resp.StatusCode != 200 {
t.Errorf("StatusCode = %d, want 200", resp.StatusCode)
}
if resp.Status != "200" {
t.Errorf("Status = %s, want 200", resp.Status)
}
if resp.Headers["content-type"] != "text/html" {
t.Errorf("Headers[content-type] = %s, want text/html", resp.Headers["content-type"])
}
if string(resp.Body) != "response body" {
t.Errorf("Body = %s, want response body", string(resp.Body))
}
if resp.StreamID != 1 {
t.Errorf("StreamID = %d, want 1", resp.StreamID)
}
if resp.Duration != 100*time.Millisecond {
t.Errorf("Duration = %v, want 100ms", resp.Duration)
}
}
// TestParseURL tests URL parsing
func TestParseURL(t *testing.T) {
tests := []struct {
name string
url string
expectedPath string
expectedAuthority string
}{
{
name: "Root path",
url: "/",
expectedPath: "/",
expectedAuthority: "",
},
{
name: "Simple path",
url: "/api/users",
expectedPath: "/api/users",
expectedAuthority: "",
},
{
name: "Full URL with path",
url: "https://example.com/api/users",
expectedPath: "/api/users",
expectedAuthority: "example.com",
},
{
name: "Full URL without path",
url: "https://example.com",
expectedPath: "/",
expectedAuthority: "example.com",
},
{
name: "URL with port and path",
url: "http://localhost:8080/test",
expectedPath: "/test",
expectedAuthority: "localhost:8080",
},
{
name: "Empty URL",
url: "",
expectedPath: "",
expectedAuthority: "",
},
{
name: "URL with query string",
url: "https://api.example.com/search?q=test",
expectedPath: "/search?q=test",
expectedAuthority: "api.example.com",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
path, authority := parseURL(tt.url)
if path != tt.expectedPath {
t.Errorf("path = %s, want %s", path, tt.expectedPath)
}
if authority != tt.expectedAuthority {
t.Errorf("authority = %s, want %s", authority, tt.expectedAuthority)
}
})
}
}
// TestFindString tests string search helper
func TestFindString(t *testing.T) {
tests := []struct {
name string
s string
substr string
expected int
}{
{"Found at beginning", "hello world", "hello", 0},
{"Found at middle", "hello world", "o w", 4},
{"Found at end", "hello world", "world", 6},
{"Not found", "hello world", "foo", -1},
{"Empty substring", "hello", "", 0},
{"Empty string", "", "hello", -1},
{"Exact match", "test", "test", 0},
{"Substring longer than string", "hi", "hello", -1},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result := findString(tt.s, tt.substr)
if result != tt.expected {
t.Errorf("findString(%q, %q) = %d, want %d", tt.s, tt.substr, result, tt.expected)
}
})
}
}
// TestClientIsConnectionSpecificHeader tests connection-specific header check
func TestClientIsConnectionSpecificHeader(t *testing.T) {
tests := []struct {
name string
header string
expected bool
}{
{"connection", "connection", true},
{"keep-alive", "keep-alive", true},
{"proxy-connection", "proxy-connection", true},
{"transfer-encoding", "transfer-encoding", true},
{"upgrade", "upgrade", true},
{"content-type", "content-type", false},
{"authorization", "authorization", false},
{"user-agent", "user-agent", false},
{"accept", "accept", false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result := isConnectionSpecificHeader(tt.header)
if result != tt.expected {
t.Errorf("isConnectionSpecificHeader(%s) = %v, want %v", tt.header, result, tt.expected)
}
})
}
}
// TestIsPseudoHeader tests pseudo-header check
func TestIsPseudoHeader(t *testing.T) {
tests := []struct {
name string
header string
expected bool
}{
{":method", ":method", true},
{":path", ":path", true},
{":scheme", ":scheme", true},
{":authority", ":authority", true},
{":status", ":status", true},
{"content-type", "content-type", false},
{"user-agent", "user-agent", false},
{"empty", "", false},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result := isPseudoHeader(tt.header)
if result != tt.expected {
t.Errorf("isPseudoHeader(%s) = %v, want %v", tt.header, result, tt.expected)
}
})
}
}
// TestParseStatusCode tests status code parsing
func TestParseStatusCode(t *testing.T) {
tests := []struct {
name string
status string
expected int
}{
{"100", "100", 100},
{"101", "101", 101},
{"200", "200", 200},
{"201", "201", 201},
{"202", "202", 202},
{"204", "204", 204},
{"206", "206", 206},
{"300", "300", 300},
{"301", "301", 301},
{"302", "302", 302},
{"304", "304", 304},
{"307", "307", 307},
{"308", "308", 308},
{"400", "400", 400},
{"401", "401", 401},
{"403", "403", 403},
{"404", "404", 404},
{"405", "405", 405},
{"409", "409", 409},
{"410", "410", 410},
{"412", "412", 412},
{"413", "413", 413},
{"415", "415", 415},
{"429", "429", 429},
{"500", "500", 500},
{"501", "501", 501},
{"502", "502", 502},
{"503", "503", 503},
{"504", "504", 504},
{"Custom 999", "999", 999},
{"Invalid", "invalid", 0},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result := parseStatusCode(tt.status)
if result != tt.expected {
t.Errorf("parseStatusCode(%s) = %d, want %d", tt.status, result, tt.expected)
}
})
}
}
// TestPrepareHeaders tests header preparation for HTTP/2
func TestPrepareHeaders(t *testing.T) {
// Create a mock client
client := &Client{
scheme: "https",
defaultHeaders: map[string]string{
"user-agent": "test-agent/1.0",
"accept-encoding": "gzip",
},
}
tests := []struct {
name string
method string
url string
headers map[string]string
checkKey string
checkVal string
}{
{
name: "GET request with path",
method: "GET",
url: "/api/users",
headers: map[string]string{"accept": "application/json"},
checkKey: ":method",
checkVal: "GET",
},
{
name: "POST request with headers",
method: "POST",
url: "/api/data",
headers: map[string]string{"content-type": "application/json"},
checkKey: "content-type",
checkVal: "application/json",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
result := client.prepareHeaders(tt.method, tt.url, tt.headers)
// Check pseudo-headers are present
if result[":method"] != tt.method {
t.Errorf(":method = %s, want %s", result[":method"], tt.method)
}
if result[":scheme"] != "https" {
t.Errorf(":scheme = %s, want https", result[":scheme"])
}
// Check specific header
if result[tt.checkKey] != tt.checkVal {
t.Errorf("%s = %s, want %s", tt.checkKey, result[tt.checkKey], tt.checkVal)
}
// Verify connection-specific headers are filtered
if _, exists := result["connection"]; exists {
t.Error("connection header should be filtered out")
}
})
}
}
// TestPrepareHeadersFiltersConnectionHeaders tests that connection-specific headers are filtered
func TestPrepareHeadersFiltersConnectionHeaders(t *testing.T) {
client := &Client{
scheme: "https",
defaultHeaders: map[string]string{},
}
headers := map[string]string{
"connection": "keep-alive",
"keep-alive": "timeout=5",
"transfer-encoding": "chunked",
"upgrade": "websocket",
"content-type": "text/plain",
}
result := client.prepareHeaders("GET", "/test", headers)
// Connection-specific headers should be filtered
if _, exists := result["connection"]; exists {
t.Error("connection header should be filtered")
}
if _, exists := result["keep-alive"]; exists {
t.Error("keep-alive header should be filtered")
}
if _, exists := result["transfer-encoding"]; exists {
t.Error("transfer-encoding header should be filtered")
}
if _, exists := result["upgrade"]; exists {
t.Error("upgrade header should be filtered")
}
// Regular headers should be kept
if result["content-type"] != "text/plain" {
t.Error("content-type header should be kept")
}
}
// TestPrepareHeadersPseudoHeadersFirst tests that pseudo-headers come first
func TestPrepareHeadersPseudoHeadersFirst(t *testing.T) {
client := &Client{
scheme: "https",
defaultHeaders: map[string]string{},
}
headers := map[string]string{
"content-type": "application/json",
"accept": "application/json",
}
result := client.prepareHeaders("POST", "/api/data", headers)
// Check all pseudo-headers are present
pseudoHeaders := []string{":method", ":scheme", ":path", ":authority"}
for _, header := range pseudoHeaders {
if _, exists := result[header]; !exists {
t.Errorf("Pseudo-header %s is missing", header)
}
}
}
// TestClientSetTimeout tests timeout setting
func TestClientSetTimeout(t *testing.T) {
client := &Client{
timeout: DefaultRequestTimeout,
}
newTimeout := 60 * time.Second
client.SetTimeout(newTimeout)
if client.timeout != newTimeout {
t.Errorf("Timeout = %v, want %v", client.timeout, newTimeout)
}
}
// TestClientSetUserAgent tests user agent setting
func TestClientSetUserAgent(t *testing.T) {
client := &Client{
defaultHeaders: make(map[string]string),
}
newAgent := "custom-agent/2.0"
client.SetUserAgent(newAgent)
if client.userAgent != newAgent {
t.Errorf("UserAgent = %s, want %s", client.userAgent, newAgent)
}
if client.defaultHeaders["user-agent"] != newAgent {
t.Errorf("defaultHeaders[user-agent] = %s, want %s", client.defaultHeaders["user-agent"], newAgent)
}
}
// TestClientSetDefaultHeader tests default header setting
func TestClientSetDefaultHeader(t *testing.T) {
client := &Client{
defaultHeaders: make(map[string]string),
}
client.SetDefaultHeader("custom-header", "custom-value")
if client.defaultHeaders["custom-header"] != "custom-value" {
t.Errorf("defaultHeaders[custom-header] = %s, want custom-value", client.defaultHeaders["custom-header"])
}
// Try to set connection-specific header (should be ignored)
client.SetDefaultHeader("connection", "keep-alive")
if _, exists := client.defaultHeaders["connection"]; exists {
t.Error("connection header should not be set")
}
}
// TestClientStatsStructure tests stats structure
func TestClientStatsStructure(t *testing.T) {
// Create mock client with stats
client := &Client{
activeRequests: 5,
totalRequests: 100,
totalErrors: 10,
startTime: time.Now().Add(-1 * time.Hour),
}
// Create minimal mock connection
// Note: We can't easily create a full Connection without network
// So we'll test the stats fields that don't depend on connection
// Test atomic loads work correctly
if atomic.LoadInt64(&client.activeRequests) != 5 {
t.Errorf("active_requests = %v, want 5", client.activeRequests)
}
if atomic.LoadInt64(&client.totalRequests) != 100 {
t.Errorf("total_requests = %v, want 100", client.totalRequests)
}
if atomic.LoadInt64(&client.totalErrors) != 10 {
t.Errorf("total_errors = %v, want 10", client.totalErrors)
}
uptime := time.Since(client.startTime).Seconds()
if uptime < 3600 || uptime > 3700 {
t.Errorf("uptime = %v, want ~3600", uptime)
}
}
// TestClientAtomicOperations tests atomic stats operations
func TestClientAtomicOperations(t *testing.T) {
client := &Client{}
// Test atomic increments
atomic.AddInt64(&client.activeRequests, 1)
atomic.AddInt64(&client.totalRequests, 1)
atomic.AddInt64(&client.totalErrors, 1)
if atomic.LoadInt64(&client.activeRequests) != 1 {
t.Errorf("activeRequests = %d, want 1", client.activeRequests)
}
if atomic.LoadInt64(&client.totalRequests) != 1 {
t.Errorf("totalRequests = %d, want 1", client.totalRequests)
}
if atomic.LoadInt64(&client.totalErrors) != 1 {
t.Errorf("totalErrors = %d, want 1", client.totalErrors)
}
// Test atomic decrements
atomic.AddInt64(&client.activeRequests, -1)
if atomic.LoadInt64(&client.activeRequests) != 0 {
t.Errorf("activeRequests = %d, want 0", client.activeRequests)
}
}
// TestClientClosedFlag tests client closed flag
func TestClientClosedFlag(t *testing.T) {
client := &Client{}
if atomic.LoadInt32(&client.closed) != 0 {
t.Error("Client should not be closed initially")
}
atomic.StoreInt32(&client.closed, 1)
if atomic.LoadInt32(&client.closed) != 1 {
t.Error("Client should be marked as closed")
}
}
// TestClientRequestQueueSize tests request queue initialization
func TestClientRequestQueueSize(t *testing.T) {
queue := make(chan *ClientRequest, RequestQueueSize)
if cap(queue) != RequestQueueSize {
t.Errorf("Request queue capacity = %d, want %d", cap(queue), RequestQueueSize)
}
}
// TestParseURLEdgeCases tests edge cases in URL parsing
func TestParseURLEdgeCases(t *testing.T) {
tests := []struct {
name string
url string
expectedPath string
expectedAuthority string
}{
{
name: "Path with multiple slashes",
url: "///api///users///",
expectedPath: "///api///users///",
expectedAuthority: "",
},
{
name: "URL with fragment",
url: "https://example.com/page#section",
expectedPath: "/page#section",
expectedAuthority: "example.com",
},
{
name: "URL with username:password",
url: "https://user:pass@example.com/secure",
expectedPath: "/secure",
expectedAuthority: "user:pass@example.com",
},
{
name: "Relative path",
url: "api/users",
expectedPath: "api/users",
expectedAuthority: "",
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
path, authority := parseURL(tt.url)
if path != tt.expectedPath {
t.Errorf("path = %s, want %s", path, tt.expectedPath)
}
if authority != tt.expectedAuthority {
t.Errorf("authority = %s, want %s", authority, tt.expectedAuthority)
}
})
}
}
// TestFindStringPerformance tests findString with various string sizes
func TestFindStringPerformance(t *testing.T) {
longString := strings.Repeat("a", 1000) + "target" + strings.Repeat("b", 1000)
result := findString(longString, "target")
if result != 1000 {
t.Errorf("findString() = %d, want 1000", result)
}
// Test not found in long string
result = findString(longString, "notfound")
if result != -1 {
t.Errorf("findString() = %d, want -1", result)
}
}
// BenchmarkPrepareHeaders benchmarks header preparation
func BenchmarkPrepareHeaders(b *testing.B) {
client := &Client{
scheme: "https",
defaultHeaders: map[string]string{
"user-agent": "test-agent/1.0",
"accept-encoding": "gzip, deflate",
},
}
headers := map[string]string{
"content-type": "application/json",
"accept": "application/json",
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
_ = client.prepareHeaders("POST", "/api/users", headers)
}
}
// BenchmarkParseURL benchmarks URL parsing
func BenchmarkParseURL(b *testing.B) {
url := "https://api.example.com:8080/api/v1/users?page=1&limit=10"
b.ResetTimer()
for i := 0; i < b.N; i++ {
_, _ = parseURL(url)
}
}
// BenchmarkParseStatusCode benchmarks status code parsing
func BenchmarkParseStatusCode(b *testing.B) {
b.ResetTimer()
for i := 0; i < b.N; i++ {
_ = parseStatusCode("200")
}
}
// BenchmarkFindString benchmarks string finding
func BenchmarkFindString(b *testing.B) {
s := "https://api.example.com/api/users"
substr := "://"
b.ResetTimer()
for i := 0; i < b.N; i++ {
_ = findString(s, substr)
}
}
// TestClientConcurrentRequests tests that multiple requests can be sent concurrently
func TestClientConcurrentRequests(t *testing.T) {
// This test verifies that the client has request processors running
// and can handle concurrent request queuing without blocking
client := &Client{
address: "example.com:443",
scheme: SchemeHTTPS,
timeout: DefaultRequestTimeout,
userAgent: ClientUserAgent,
defaultHeaders: make(map[string]string),
requestQueue: make(chan *ClientRequest, RequestQueueSize),
ctx: context.Background(),
}
// Simulate sending 10 concurrent requests
var sentCount int32
const numRequests = 10
for i := 0; i < numRequests; i++ {
req := &ClientRequest{
Method: "GET",
URL: "/test",
Headers: make(map[string]string),
Body: nil,
Timeout: 1 * time.Second,
Response: make(chan *ClientResponse, 1),
}
// Try to queue the request (should not block if queue is working)
select {
case client.requestQueue <- req:
atomic.AddInt32(&sentCount, 1)
case <-time.After(100 * time.Millisecond):
t.Errorf("Request %d blocked - queue not being processed", i)
}
}
// Verify all requests were queued
if count := atomic.LoadInt32(&sentCount); count != numRequests {
t.Errorf("Sent %d requests, want %d", count, numRequests)
}
// Verify queue has the requests
queueLen := len(client.requestQueue)
if queueLen != numRequests {
t.Errorf("Queue length = %d, want %d", queueLen, numRequests)
}
}
// TestClientConcurrentProcessing tests concurrent request processing with goroutines
func TestClientConcurrentProcessing(t *testing.T) {
// This test verifies that multiple goroutines can send requests concurrently
// without blocking each other
client := &Client{
address: "example.com:443",
scheme: SchemeHTTPS,
timeout: DefaultRequestTimeout,
userAgent: ClientUserAgent,
defaultHeaders: make(map[string]string),
requestQueue: make(chan *ClientRequest, RequestQueueSize),
ctx: context.Background(),
}
const numGoroutines = 20
const requestsPerGoroutine = 5
var processedCount int32
// Start multiple goroutines sending requests concurrently
var wg sync.WaitGroup
for g := 0; g < numGoroutines; g++ {
wg.Add(1)
go func(goroutineID int) {
defer wg.Done()
for r := 0; r < requestsPerGoroutine; r++ {
req := &ClientRequest{
Method: "GET",
URL: "/test",
Headers: make(map[string]string),
Body: nil,
Timeout: 1 * time.Second,
Response: make(chan *ClientResponse, 1),
}
// Send request - should not block
select {
case client.requestQueue <- req:
atomic.AddInt32(&processedCount, 1)
case <-time.After(100 * time.Millisecond):
t.Errorf("Goroutine %d request %d blocked", goroutineID, r)
}
}
}(g)
}
// Wait for all goroutines to finish
wg.Wait()
// Verify all requests were queued
expectedCount := int32(numGoroutines * requestsPerGoroutine)
if count := atomic.LoadInt32(&processedCount); count != expectedCount {
t.Errorf("Processed %d requests, want %d", count, expectedCount)
}
// Verify queue length
queueLen := len(client.requestQueue)
if queueLen != int(expectedCount) {
t.Errorf("Queue length = %d, want %d", queueLen, expectedCount)
}
}
// BenchmarkClientConcurrentRequests benchmarks concurrent request queuing
func BenchmarkClientConcurrentRequests(b *testing.B) {
client := &Client{
address: "example.com:443",
scheme: SchemeHTTPS,
timeout: DefaultRequestTimeout,
userAgent: ClientUserAgent,
defaultHeaders: make(map[string]string),
requestQueue: make(chan *ClientRequest, RequestQueueSize),
ctx: context.Background(),
}
// Drain queue to prevent blocking
done := make(chan struct{})
go func() {
for {
select {
case <-client.requestQueue:
case <-done:
return
}
}
}()
defer close(done)
b.ResetTimer()
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
req := &ClientRequest{
Method: "GET",
URL: "/api/v1/test",
Headers: make(map[string]string),
Body: nil,
Timeout: 1 * time.Second,
Response: make(chan *ClientResponse, 1),
}
client.requestQueue <- req
}
})
}
// BenchmarkClientRequestQueuing benchmarks request queuing throughput
func BenchmarkClientRequestQueuing(b *testing.B) {
client := &Client{
address: "example.com:443",
scheme: SchemeHTTPS,
timeout: DefaultRequestTimeout,
userAgent: ClientUserAgent,
defaultHeaders: make(map[string]string),
requestQueue: make(chan *ClientRequest, RequestQueueSize),
ctx: context.Background(),
}
// Start a goroutine to drain the queue so it doesn't fill up
done := make(chan struct{})
go func() {
for {
select {
case <-client.requestQueue:
// Drain request
case <-done:
return
}
}
}()
defer close(done)
b.ResetTimer()
for i := 0; i < b.N; i++ {
req := &ClientRequest{
Method: "GET",
URL: "/api/v1/test",
Headers: make(map[string]string),
Body: nil,
Timeout: 1 * time.Second,
Response: make(chan *ClientResponse, 1),
}
client.requestQueue <- req
}
}
// BenchmarkClientConcurrentQueuingWithDrain benchmarks parallel queuing with processing
func BenchmarkClientConcurrentQueuingWithDrain(b *testing.B) {
client := &Client{
address: "example.com:443",
scheme: SchemeHTTPS,
timeout: DefaultRequestTimeout,
userAgent: ClientUserAgent,
defaultHeaders: make(map[string]string),
requestQueue: make(chan *ClientRequest, RequestQueueSize),
ctx: context.Background(),
}
// Start 4 processors to drain the queue (simulating real usage)
done := make(chan struct{})
var wg sync.WaitGroup
for i := 0; i < 4; i++ {
wg.Add(1)
go func() {
defer wg.Done()
for {
select {
case <-client.requestQueue:
// Process (drain) request
case <-done:
return
}
}
}()
}
b.ResetTimer()
b.RunParallel(func(pb *testing.PB) {
for pb.Next() {
req := &ClientRequest{
Method: "GET",
URL: "/api/v1/test",
Headers: make(map[string]string),
Body: nil,
Timeout: 1 * time.Second,
Response: make(chan *ClientResponse, 1),