-
Notifications
You must be signed in to change notification settings - Fork 0
Expand file tree
/
Copy pathconnection_test.go
More file actions
583 lines (526 loc) · 14.4 KB
/
Copy pathconnection_test.go
File metadata and controls
583 lines (526 loc) · 14.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
package http2
import (
"bufio"
"encoding/binary"
"io"
"sync"
"testing"
"time"
)
// TestConnectionConstants tests connection-related constants
func TestConnectionConstants(t *testing.T) {
tests := []struct {
name string
constant uint32
expected uint32
}{
{"SettingsHeaderTableSize", SettingsHeaderTableSize, 0x1},
{"SettingsEnablePush", SettingsEnablePush, 0x2},
{"SettingsMaxConcurrentStreams", SettingsMaxConcurrentStreams, 0x3},
{"SettingsInitialWindowSize", SettingsInitialWindowSize, 0x4},
{"SettingsMaxFrameSize", SettingsMaxFrameSize, 0x5},
{"SettingsMaxHeaderListSize", SettingsMaxHeaderListSize, 0x6},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if tt.constant != tt.expected {
t.Errorf("%s = 0x%x, want 0x%x", tt.name, tt.constant, tt.expected)
}
})
}
}
// TestErrorCodeConstants tests error code constants
func TestErrorCodeConstants(t *testing.T) {
tests := []struct {
name string
code uint32
expected uint32
}{
{"ErrorCodeNoError", ErrorCodeNoError, 0x0},
{"ErrorCodeProtocolError", ErrorCodeProtocolError, 0x1},
{"ErrorCodeInternalError", ErrorCodeInternalError, 0x2},
{"ErrorCodeFlowControlError", ErrorCodeFlowControlError, 0x3},
{"ErrorCodeSettingsTimeout", ErrorCodeSettingsTimeout, 0x4},
{"ErrorCodeStreamClosed", ErrorCodeStreamClosed, 0x5},
{"ErrorCodeFrameSizeError", ErrorCodeFrameSizeError, 0x6},
{"ErrorCodeRefusedStream", ErrorCodeRefusedStream, 0x7},
{"ErrorCodeCancel", ErrorCodeCancel, 0x8},
{"ErrorCodeCompressionError", ErrorCodeCompressionError, 0x9},
{"ErrorCodeConnectError", ErrorCodeConnectError, 0xa},
{"ErrorCodeEnhanceYourCalm", ErrorCodeEnhanceYourCalm, 0xb},
{"ErrorCodeInadequateSecurity", ErrorCodeInadequateSecurity, 0xc},
{"ErrorCodeHTTP11Required", ErrorCodeHTTP11Required, 0xd},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
if tt.code != tt.expected {
t.Errorf("%s = 0x%x, want 0x%x", tt.name, tt.code, tt.expected)
}
})
}
}
// TestConnectionPreface tests connection preface constant
func TestConnectionPreface(t *testing.T) {
expected := []byte("PRI * HTTP/2.0\r\n\r\nSM\r\n\r\n")
if string(ConnectionPreface) != string(expected) {
t.Errorf("ConnectionPreface = %q, want %q", ConnectionPreface, expected)
}
if len(ConnectionPreface) != 24 {
t.Errorf("ConnectionPreface length = %d, want 24", len(ConnectionPreface))
}
}
// TestFrameReaderReadFrame tests frame reading
func TestFrameReaderReadFrame(t *testing.T) {
tests := []struct {
name string
data []byte
wantLength uint32
wantType uint8
wantFlags uint8
wantStream uint32
}{
{
name: "SETTINGS frame",
data: []byte{
0x00, 0x00, 0x00, // Length: 0
0x04, // Type: SETTINGS
0x00, // Flags: 0
0x00, 0x00, 0x00, 0x00, // Stream ID: 0
},
wantLength: 0,
wantType: FrameTypeSETTINGS,
wantFlags: 0,
wantStream: 0,
},
{
name: "HEADERS frame",
data: []byte{
0x00, 0x00, 0x0A, // Length: 10
0x01, // Type: HEADERS
0x04, // Flags: END_HEADERS
0x00, 0x00, 0x00, 0x01, // Stream ID: 1
// Payload (10 bytes)
0x00, 0x01, 0x02, 0x03, 0x04,
0x05, 0x06, 0x07, 0x08, 0x09,
},
wantLength: 10,
wantType: FrameTypeHEADERS,
wantFlags: FlagHeadersEndHeaders,
wantStream: 1,
},
{
name: "DATA frame",
data: []byte{
0x00, 0x00, 0x05, // Length: 5
0x00, // Type: DATA
0x01, // Flags: END_STREAM
0x00, 0x00, 0x00, 0x03, // Stream ID: 3
// Payload (5 bytes)
0x68, 0x65, 0x6C, 0x6C, 0x6F, // "hello"
},
wantLength: 5,
wantType: FrameTypeDATA,
wantFlags: FlagDataEndStream,
wantStream: 3,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// Create a buffer reader from test data
mockR := &mockReader{data: tt.data}
bufReader := bufio.NewReader(mockR)
fr := newFrameReader(bufReader)
frame, err := fr.ReadFrame()
if err != nil {
t.Fatalf("ReadFrame() error = %v", err)
}
if frame.length != tt.wantLength {
t.Errorf("Length = %d, want %d", frame.length, tt.wantLength)
}
if frame.frameType != tt.wantType {
t.Errorf("Type = %d, want %d", frame.frameType, tt.wantType)
}
if frame.flags != tt.wantFlags {
t.Errorf("Flags = 0x%x, want 0x%x", frame.flags, tt.wantFlags)
}
if frame.streamID != tt.wantStream {
t.Errorf("StreamID = %d, want %d", frame.streamID, tt.wantStream)
}
if len(frame.payload) != int(tt.wantLength) {
t.Errorf("Payload length = %d, want %d", len(frame.payload), tt.wantLength)
}
})
}
}
// TestCalculateHeadersSize tests header size calculation
func TestCalculateHeadersSize(t *testing.T) {
tests := []struct {
name string
headers map[string]string
wantSize int
}{
{
name: "Empty headers",
headers: map[string]string{},
wantSize: 0,
},
{
name: "Single header",
headers: map[string]string{
"name": "value",
},
wantSize: 11, // "name" (4) + "value" (5) + 2 separators = 11
},
{
name: "Multiple headers",
headers: map[string]string{
":method": "GET",
":path": "/",
},
wantSize: 20, // ":method" (7) + "GET" (3) + ":path" (5) + "/" (1) + 4 separators = 20
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
size := calculateHeadersSize(tt.headers)
if size != tt.wantSize {
t.Errorf("calculateHeadersSize() = %d, want %d", size, tt.wantSize)
}
})
}
}
// TestStreamRequestStructure tests StreamRequest structure
func TestStreamRequestStructure(t *testing.T) {
req := &streamRequest{
streamID: 1,
headers: map[string]string{
":method": "GET",
":path": "/test",
},
body: []byte("test body"),
endStream: true,
priority: 0,
responseChan: make(chan *streamResponse, 1),
timestamp: time.Now(),
}
if req.streamID != 1 {
t.Errorf("streamID = %d, want 1", req.streamID)
}
if req.headers[":method"] != "GET" {
t.Error("headers not set correctly")
}
if string(req.body) != "test body" {
t.Error("body not set correctly")
}
if !req.endStream {
t.Error("endStream should be true")
}
if req.responseChan == nil {
t.Error("responseChan should not be nil")
}
}
// TestStreamResponseStructure tests StreamResponse structure
func TestStreamResponseStructure(t *testing.T) {
resp := &streamResponse{
streamID: 1,
headers: map[string]string{
":status": "200",
},
body: []byte("response body"),
status: 200,
err: nil,
}
if resp.streamID != 1 {
t.Errorf("streamID = %d, want 1", resp.streamID)
}
if resp.headers[":status"] != "200" {
t.Error("headers not set correctly")
}
if string(resp.body) != "response body" {
t.Error("body not set correctly")
}
if resp.status != 200 {
t.Errorf("status = %d, want 200", resp.status)
}
}
// TestConnectionStatsStructure tests ConnectionStats structure
func TestConnectionStatsStructure(t *testing.T) {
stats := connectionStats{
BytesSent: 1024,
BytesReceived: 2048,
FramesSent: 10,
FramesReceived: 20,
StreamsCreated: 5,
StreamsClosed: 3,
HeadersEncoded: 8,
HeadersDecoded: 12,
CompressionRatio: 0.75,
LastActivity: time.Now(),
}
if stats.BytesSent != 1024 {
t.Errorf("BytesSent = %d, want 1024", stats.BytesSent)
}
if stats.FramesSent != 10 {
t.Errorf("FramesSent = %d, want 10", stats.FramesSent)
}
if stats.StreamsCreated != 5 {
t.Errorf("StreamsCreated = %d, want 5", stats.StreamsCreated)
}
}
// TestStreamWorkerStructure tests StreamWorker structure
func TestStreamWorkerStructure(t *testing.T) {
worker := &streamWorker{
id: 1,
conn: nil, // Would be set to actual connection
requests: make(chan *streamRequest, 10),
shutdown: make(chan struct{}),
wg: sync.WaitGroup{},
}
if worker.id != 1 {
t.Errorf("id = %d, want 1", worker.id)
}
if worker.requests == nil {
t.Error("requests channel should not be nil")
}
if worker.shutdown == nil {
t.Error("shutdown channel should not be nil")
}
}
// TestFrameValidation tests frame validation logic
func TestFrameValidation(t *testing.T) {
// Note: This tests the concept of frame validation
// Actual validation would require a connection instance
tests := []struct {
name string
frame *frame
isValid bool
}{
{
name: "Valid SETTINGS frame",
frame: &frame{
length: 0,
frameType: FrameTypeSETTINGS,
flags: 0,
streamID: 0,
},
isValid: true,
},
{
name: "Valid DATA frame",
frame: &frame{
length: 100,
frameType: FrameTypeDATA,
flags: FlagDataEndStream,
streamID: 1,
},
isValid: true,
},
{
name: "Invalid - DATA on stream 0",
frame: &frame{
length: 100,
frameType: FrameTypeDATA,
flags: 0,
streamID: 0, // DATA cannot be on stream 0
},
isValid: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// Basic validation checks
if tt.frame.frameType == FrameTypeDATA && tt.frame.streamID == 0 {
if tt.isValid {
t.Error("DATA frame on stream 0 should be invalid")
}
}
})
}
}
// TestSettingsFrameCreation tests SETTINGS frame creation
func TestSettingsFrameCreation(t *testing.T) {
// Test ACK frame
ackFrame := &frame{
frameType: FrameTypeSETTINGS,
flags: FlagSettingsAck,
streamID: 0,
length: 0,
payload: []byte{},
}
if ackFrame.frameType != FrameTypeSETTINGS {
t.Error("ACK frame should be SETTINGS type")
}
if (ackFrame.flags & FlagSettingsAck) == 0 {
t.Error("ACK flag should be set")
}
if ackFrame.length != 0 {
t.Error("ACK frame should have zero length")
}
// Test non-ACK frame with settings
settings := map[uint16]uint32{
SettingsMaxConcurrentStreams: 100,
SettingsInitialWindowSize: 65535,
}
payload := make([]byte, 0, len(settings)*6)
for id, value := range settings {
buf := make([]byte, 6)
binary.BigEndian.PutUint16(buf[0:2], id)
binary.BigEndian.PutUint32(buf[2:6], value)
payload = append(payload, buf...)
}
settingsFrame := &frame{
frameType: FrameTypeSETTINGS,
flags: 0,
streamID: 0,
length: uint32(len(payload)),
payload: payload,
}
if settingsFrame.length != uint32(len(settings)*6) {
t.Errorf("SETTINGS frame length = %d, want %d", settingsFrame.length, len(settings)*6)
}
}
// TestWindowUpdateFrame tests WINDOW_UPDATE frame
func TestWindowUpdateFrame(t *testing.T) {
increment := uint32(1000)
payload := make([]byte, 4)
binary.BigEndian.PutUint32(payload, increment&0x7FFFFFFF)
frame := &frame{
length: 4,
frameType: FrameTypeWINDOW_UPDATE,
flags: 0,
streamID: 0,
payload: payload,
}
if frame.length != 4 {
t.Errorf("WINDOW_UPDATE length = %d, want 4", frame.length)
}
// Parse increment back
parsedIncrement := binary.BigEndian.Uint32(frame.payload) & 0x7FFFFFFF
if parsedIncrement != increment {
t.Errorf("Increment = %d, want %d", parsedIncrement, increment)
}
}
// TestPingFrame tests PING frame
func TestPingFrame(t *testing.T) {
pingData := []byte{0x00, 0x01, 0x02, 0x03, 0x04, 0x05, 0x06, 0x07}
pingFrame := &frame{
length: 8,
frameType: FrameTypePING,
flags: 0,
streamID: 0,
payload: pingData,
}
if pingFrame.length != 8 {
t.Errorf("PING length = %d, want 8", pingFrame.length)
}
if len(pingFrame.payload) != 8 {
t.Errorf("PING payload length = %d, want 8", len(pingFrame.payload))
}
// PING ACK
ackFrame := &frame{
length: 8,
frameType: FrameTypePING,
flags: FlagPingAck,
streamID: 0,
payload: pingData,
}
if (ackFrame.flags & FlagPingAck) == 0 {
t.Error("PING ACK flag should be set")
}
}
// TestGoAwayFrame tests GOAWAY frame
func TestGoAwayFrame(t *testing.T) {
lastStreamID := uint32(5)
errorCode := uint32(ErrorCodeNoError)
debugData := []byte("shutdown")
payload := make([]byte, 8+len(debugData))
binary.BigEndian.PutUint32(payload[0:4], lastStreamID&0x7FFFFFFF)
binary.BigEndian.PutUint32(payload[4:8], errorCode)
copy(payload[8:], debugData)
frame := &frame{
length: uint32(len(payload)),
frameType: FrameTypeGOAWAY,
flags: 0,
streamID: 0,
payload: payload,
}
// Parse back
parsedLastStreamID := binary.BigEndian.Uint32(frame.payload[0:4]) & 0x7FFFFFFF
parsedErrorCode := binary.BigEndian.Uint32(frame.payload[4:8])
parsedDebugData := frame.payload[8:]
if parsedLastStreamID != lastStreamID {
t.Errorf("LastStreamID = %d, want %d", parsedLastStreamID, lastStreamID)
}
if parsedErrorCode != errorCode {
t.Errorf("ErrorCode = %d, want %d", parsedErrorCode, errorCode)
}
if string(parsedDebugData) != string(debugData) {
t.Errorf("DebugData = %s, want %s", parsedDebugData, debugData)
}
}
// TestRstStreamFrame tests RST_STREAM frame
func TestRstStreamFrame(t *testing.T) {
errorCode := uint32(ErrorCodeCancel)
payload := make([]byte, 4)
binary.BigEndian.PutUint32(payload, errorCode)
frame := &frame{
length: 4,
frameType: FrameTypeRST_STREAM,
flags: 0,
streamID: 1,
payload: payload,
}
if frame.streamID == 0 {
t.Error("RST_STREAM should have non-zero stream ID")
}
parsedErrorCode := binary.BigEndian.Uint32(frame.payload)
if parsedErrorCode != errorCode {
t.Errorf("ErrorCode = %d, want %d", parsedErrorCode, errorCode)
}
}
// mockReader implements io.Reader for testing
type mockReader struct {
data []byte
pos int
}
func (m *mockReader) Read(p []byte) (n int, err error) {
if m.pos >= len(m.data) {
return 0, io.EOF
}
n = copy(p, m.data[m.pos:])
m.pos += n
return n, nil
}
// BenchmarkFrameReaderReadFrame benchmarks frame reading
func BenchmarkFrameReaderReadFrame(b *testing.B) {
// Create test frame data
frameData := make([]byte, 9+100) // Header + 100 bytes payload
frameData[0] = 0x00
frameData[1] = 0x00
frameData[2] = 0x64 // Length: 100
frameData[3] = FrameTypeDATA
frameData[4] = 0
binary.BigEndian.PutUint32(frameData[5:9], 1)
b.ResetTimer()
for i := 0; i < b.N; i++ {
mockR := &mockReader{data: frameData}
bufReader := bufio.NewReader(mockR)
fr := newFrameReader(bufReader)
_, _ = fr.ReadFrame()
}
}
// BenchmarkCalculateHeadersSize benchmarks header size calculation
func BenchmarkCalculateHeadersSize(b *testing.B) {
headers := map[string]string{
":method": "POST",
":path": "/api/users",
":scheme": "https",
":authority": "example.com",
"content-type": "application/json",
"user-agent": "test/1.0",
}
b.ResetTimer()
for i := 0; i < b.N; i++ {
_ = calculateHeadersSize(headers)
}
}