-
Notifications
You must be signed in to change notification settings - Fork 3
Expand file tree
/
Copy pathconn_test.go
More file actions
907 lines (802 loc) · 21.5 KB
/
conn_test.go
File metadata and controls
907 lines (802 loc) · 21.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
package pulse
import (
"net"
"os"
"sync/atomic"
"testing"
"time"
"github.com/antlabs/pulse/core"
)
const testSessionData = "test_session"
func Test_OnData(t *testing.T) {
c := &Conn{fd: 0, readBufferSize: 4096}
var receivedData []byte
var receivedErr error
var closeErr error
options := &Options{
callback: ToCallback(
func(c *Conn, err error) {
receivedErr = err
},
func(c *Conn, data []byte) {
receivedData = data
},
func(c *Conn, err error) {
closeErr = err
},
),
}
options.taskType = TaskTypeInEventLoop
testData := []byte("hello")
handleData(c, options, testData)
if string(receivedData) != string(testData) {
t.Errorf("OnData callback received wrong data, got %v, want %v", receivedData, testData)
}
if receivedErr != nil {
t.Errorf("OnOpen callback received unexpected error: %v", receivedErr)
}
if closeErr != nil {
t.Errorf("OnClose callback received unexpected error: %v", closeErr)
}
}
func Test_Listen(t *testing.T) {
// 第一次监听应该成功
listener1, err := net.Listen("tcp", "127.0.0.1:8080")
if err != nil {
t.Fatalf("First Listen() failed: %v", err)
}
defer func() {
if err := listener1.Close(); err != nil {
t.Logf("failed to close listener1: %v", err)
}
}()
// 第二次监听应该失败,因为端口已被占用
listener2, err := net.Listen("tcp", "127.0.0.1:8080")
if err == nil {
t.Error("Second Listen() should fail, but succeeded")
if listener2 != nil {
if err := listener2.Close(); err != nil {
t.Logf("failed to close listener2: %v", err)
}
}
}
}
func TestConn_SetDeadline(t *testing.T) {
tests := []struct {
name string
time time.Time
wantErr bool
}{
{
name: "set future deadline",
time: time.Now().Add(time.Second),
wantErr: false,
},
{
name: "set past deadline",
time: time.Now().Add(-time.Second),
wantErr: true,
},
{
name: "clear deadline",
time: time.Time{},
wantErr: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// 为每个子测试创建独立的连接
fd, err := os.OpenFile("/dev/null", os.O_RDONLY, 0600)
if err != nil {
t.Fatalf("OpenFile() error = %v", err)
}
defer func() {
if err := fd.Close(); err != nil {
t.Logf("failed to close fd: %v", err)
}
}()
conn := &Conn{
fd: int64(fd.Fd()),
readBufferSize: 4096,
safeConns: &core.SafeConns[Conn]{},
}
err = conn.SetDeadline(tt.time)
if (err != nil) != tt.wantErr {
t.Errorf("SetDeadline() error = %v, wantErr %v", err, tt.wantErr)
}
// 对于过去的时间,连接应该被关闭
if tt.time.Before(time.Now()) && !tt.time.IsZero() {
// 给一点时间让close操作完成
time.Sleep(10 * time.Millisecond)
// Use public method to check if connection is closed
err := conn.SetDeadline(time.Now().Add(time.Second))
if err == nil {
t.Error("Connection should be closed for past deadline")
}
return
}
// 验证读写定时器都被正确设置 - 通过尝试清除来检查
if !tt.time.IsZero() {
// 尝试清除deadline,如果成功说明timer已设置
err := conn.SetDeadline(time.Time{})
if err != nil {
t.Error("Should be able to clear deadline when connection is alive")
}
}
})
}
// 测试连接关闭的情况
fd, err := os.OpenFile("/dev/null", os.O_RDONLY, 0600)
if err != nil {
t.Fatalf("OpenFile() error = %v", err)
}
defer func() {
if err := fd.Close(); err != nil {
t.Logf("failed to close fd: %v", err)
}
}()
conn := &Conn{
fd: int64(fd.Fd()),
readBufferSize: 4096,
safeConns: &core.SafeConns[Conn]{},
}
conn.closeNoLock()
err = conn.SetDeadline(time.Now().Add(time.Second))
if err == nil {
t.Error("SetDeadline() should return error when connection is closed")
}
}
func TestConn_SetReadDeadline(t *testing.T) {
tests := []struct {
name string
time time.Time
wantErr bool
}{
{
name: "set future deadline",
time: time.Now().Add(time.Second),
wantErr: false,
},
{
name: "set past deadline",
time: time.Now().Add(-time.Second),
wantErr: false,
},
{
name: "clear deadline",
time: time.Time{},
wantErr: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// 为每个子测试创建独立的连接
fd, err := os.OpenFile("/dev/null", os.O_RDONLY, 0600)
if err != nil {
t.Fatalf("OpenFile() error = %v", err)
}
defer func() {
if err := fd.Close(); err != nil {
t.Logf("failed to close fd: %v", err)
}
}()
conn := &Conn{
fd: int64(fd.Fd()),
readBufferSize: 4096,
safeConns: &core.SafeConns[Conn]{},
}
err = conn.SetReadDeadline(tt.time)
if (err != nil) != tt.wantErr {
t.Errorf("SetReadDeadline() error = %v, wantErr %v", err, tt.wantErr)
}
// 对于过去的时间,连接应该被关闭
if tt.time.Before(time.Now()) && !tt.time.IsZero() {
// 给一点时间让close操作完成
time.Sleep(10 * time.Millisecond)
// Use public method to check if connection is closed
err := conn.SetReadDeadline(time.Now().Add(time.Second))
if err == nil {
t.Error("Connection should be closed for past deadline")
}
return
}
// 验证读定时器被正确设置 - 通过尝试清除来检查
if !tt.time.IsZero() {
// 尝试清除read deadline,如果成功说明timer已设置
err := conn.SetReadDeadline(time.Time{})
if err != nil {
t.Error("Should be able to clear read deadline when connection is alive")
}
}
})
}
// 测试连接关闭的情况
fd, err := os.OpenFile("/dev/null", os.O_RDONLY, 0600)
if err != nil {
t.Fatalf("OpenFile() error = %v", err)
}
defer func() {
if err := fd.Close(); err != nil {
t.Logf("failed to close fd: %v", err)
}
}()
conn := &Conn{
fd: int64(fd.Fd()),
readBufferSize: 4096,
safeConns: &core.SafeConns[Conn]{},
}
conn.closeNoLock()
err = conn.SetReadDeadline(time.Now().Add(time.Second))
if err == nil {
t.Error("SetReadDeadline() should return error when connection is closed")
}
}
func TestConn_SetWriteDeadline(t *testing.T) {
tests := []struct {
name string
time time.Time
wantErr bool
}{
{
name: "set future deadline",
time: time.Now().Add(time.Second),
wantErr: false,
},
{
name: "set past deadline",
time: time.Now().Add(-time.Second),
wantErr: false,
},
{
name: "clear deadline",
time: time.Time{},
wantErr: false,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
// 为每个子测试创建独立的连接
fd, err := os.OpenFile("/dev/null", os.O_RDONLY, 0600)
if err != nil {
t.Fatalf("OpenFile() error = %v", err)
}
defer func() {
if err := fd.Close(); err != nil {
t.Logf("failed to close fd: %v", err)
}
}()
conn := &Conn{
fd: int64(fd.Fd()),
readBufferSize: 4096,
safeConns: &core.SafeConns[Conn]{},
}
err = conn.SetWriteDeadline(tt.time)
if (err != nil) != tt.wantErr {
t.Errorf("SetWriteDeadline() error = %v, wantErr %v", err, tt.wantErr)
}
// 对于过去的时间,连接应该被关闭
if tt.time.Before(time.Now()) && !tt.time.IsZero() {
// 给一点时间让close操作完成
time.Sleep(10 * time.Millisecond)
// Use public method to check if connection is closed
err := conn.SetWriteDeadline(time.Now().Add(time.Second))
if err == nil {
t.Error("Connection should be closed for past deadline")
}
return
}
// 验证写定时器被正确设置 - 通过尝试清除来检查
if !tt.time.IsZero() {
// 尝试清除write deadline,如果成功说明timer已设置
err := conn.SetWriteDeadline(time.Time{})
if err != nil {
t.Error("Should be able to clear write deadline when connection is alive")
}
}
})
}
// 测试连接关闭的情况
fd, err := os.OpenFile("/dev/null", os.O_RDONLY, 0600)
if err != nil {
t.Fatalf("OpenFile() error = %v", err)
}
defer func() {
if err := fd.Close(); err != nil {
t.Logf("failed to close fd: %v", err)
}
}()
conn := &Conn{
fd: int64(fd.Fd()),
readBufferSize: 4096,
safeConns: &core.SafeConns[Conn]{},
}
conn.closeNoLock()
err = conn.SetWriteDeadline(time.Now().Add(time.Second))
if err == nil {
t.Error("SetWriteDeadline() should return error when connection is closed")
}
}
func TestConn_DeadlineTimeout(t *testing.T) {
fd, err := os.OpenFile("/dev/null", os.O_RDONLY, 0600)
if err != nil {
t.Fatalf("OpenFile() error = %v", err)
}
defer func() {
if err := fd.Close(); err != nil {
t.Logf("failed to close fd: %v", err)
}
}()
conn := &Conn{
fd: int64(fd.Fd()),
readBufferSize: 4096,
safeConns: &core.SafeConns[Conn]{},
}
// 设置一个很短的超时时间
timeout := 100 * time.Millisecond
err = conn.SetDeadline(time.Now().Add(timeout))
if err != nil {
t.Fatalf("SetDeadline() error = %v", err)
}
// 等待超时发生
time.Sleep(timeout + 50*time.Millisecond)
// 验证连接是否被关闭
if atomic.LoadInt64(&conn.fd) != -1 {
t.Error("Connection should be closed after deadline")
}
// 验证定时器是否被清理
if conn.readTimer != nil {
t.Error("readTimer should be nil after deadline")
}
if conn.writeTimer != nil {
t.Error("writeTimer should be nil after deadline")
}
// 验证在已关闭的连接上设置超时应该返回错误
err = conn.SetDeadline(time.Now().Add(time.Second))
if err == nil {
t.Error("SetDeadline() should return error on closed connection")
}
}
func TestConn_DeadlineReset(t *testing.T) {
fd, err := os.OpenFile("/dev/null", os.O_RDONLY, 0600)
if err != nil {
t.Fatalf("OpenFile() error = %v", err)
}
defer func() {
if err := fd.Close(); err != nil {
t.Logf("failed to close fd: %v", err)
}
}()
fd2 := fd.Fd()
conn := &Conn{
fd: int64(fd2),
readBufferSize: 4096,
safeConns: &core.SafeConns[Conn]{},
}
// 设置初始超时 - 相对较短的时间
initialTimeout := 100 * time.Millisecond
startTime := time.Now()
err = conn.SetDeadline(startTime.Add(initialTimeout))
if err != nil {
t.Fatalf("SetDeadline() error = %v", err)
}
// 等待一半时间
time.Sleep(initialTimeout / 2) // 等待50ms
// 重置超时时间为更长的时间 - 从现在开始计算
newTimeout := 200 * time.Millisecond
resetTime := time.Now()
err = conn.SetDeadline(resetTime.Add(newTimeout))
if err != nil {
t.Fatalf("Reset SetDeadline() error = %v", err)
}
// 等待超过初始超时时间但小于新超时时间
// 已经等待了50ms,再等待80ms,总共130ms
// 这应该超过初始的100ms但小于新的200ms
time.Sleep(80 * time.Millisecond)
// 验证连接仍然存活,通过尝试设置新的deadline来测试
err = conn.SetDeadline(time.Now().Add(1 * time.Second))
if err != nil {
t.Error("Connection should still be alive after reset deadline, but SetDeadline failed:", err)
return
}
// 清除deadline以防止干扰后续测试
err = conn.SetDeadline(time.Time{})
if err != nil {
t.Fatalf("Clear deadline error = %v", err)
}
// 重新设置一个短的deadline来测试关闭
shortTimeout := 50 * time.Millisecond
err = conn.SetDeadline(time.Now().Add(shortTimeout))
if err != nil {
t.Fatalf("Set short deadline error = %v", err)
}
// 等待超时
time.Sleep(shortTimeout + 50*time.Millisecond)
// 验证连接是否被关闭,通过尝试设置deadline来测试
err = conn.SetDeadline(time.Now().Add(1 * time.Second))
if err == nil {
t.Error("Connection should be closed after short deadline, but SetDeadline succeeded")
}
}
// TestCallback_OnOpen 测试OnOpen回调功能
func TestCallback_OnOpen(t *testing.T) {
tests := []struct {
name string
expectError bool
setup func() *Conn
}{
{
name: "successful connection open",
expectError: false,
setup: func() *Conn {
fd, err := os.OpenFile("/dev/null", os.O_RDONLY, 0600)
if err != nil {
t.Fatalf("OpenFile() error = %v", err)
}
return &Conn{
fd: int64(fd.Fd()),
readBufferSize: 4096,
safeConns: &core.SafeConns[Conn]{},
}
},
},
{
name: "connection with session data",
expectError: false,
setup: func() *Conn {
fd, err := os.OpenFile("/dev/null", os.O_RDONLY, 0600)
if err != nil {
t.Fatalf("OpenFile() error = %v", err)
}
conn := &Conn{
fd: int64(fd.Fd()),
readBufferSize: 4096,
safeConns: &core.SafeConns[Conn]{},
}
conn.SetSession("test_session_data")
return conn
},
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
conn := tt.setup()
defer func() {
if atomic.LoadInt64(&conn.fd) != -1 {
conn.Close()
}
}()
var onOpenCalled bool
var onOpenConn *Conn
var onOpenErr error
callback := ToCallback(
func(c *Conn, err error) {
onOpenCalled = true
onOpenConn = c
onOpenErr = err
},
func(c *Conn, data []byte) {
// Do nothing for this test
},
func(c *Conn, err error) {
// Do nothing for this test
},
)
// 调用OnOpen
callback.OnOpen(conn)
// 验证回调被调用
if !onOpenCalled {
t.Error("OnOpen callback was not called")
}
// 验证传递的连接对象
if onOpenConn != conn {
t.Error("OnOpen callback received wrong connection object")
}
// 验证错误参数(ToCallback中OnOpen总是传nil)
if onOpenErr != nil {
t.Errorf("OnOpen callback received unexpected error: %v", onOpenErr)
}
// 验证连接状态
if atomic.LoadInt64(&conn.fd) == -1 {
t.Error("Connection should not be closed after OnOpen")
}
})
}
}
// TestCallback_OnClose 测试OnClose回调功能
func TestCallback_OnClose(t *testing.T) {
tests := []struct {
name string
setupError error
expectError bool
closeMethod func(*Conn)
expectedClosed bool
}{
{
name: "normal close without error",
setupError: nil,
expectError: false,
closeMethod: func(c *Conn) { c.Close() },
expectedClosed: true,
},
{
name: "close with simulated network error",
setupError: net.ErrClosed,
expectError: true,
closeMethod: func(c *Conn) { c.Close() },
expectedClosed: true,
},
{
name: "close already closed connection",
setupError: nil,
expectError: false,
closeMethod: func(c *Conn) {
c.Close() // First close
c.Close() // Second close should be safe
},
expectedClosed: true,
},
}
for _, tt := range tests {
t.Run(tt.name, func(t *testing.T) {
fd, err := os.OpenFile("/dev/null", os.O_RDONLY, 0600)
if err != nil {
t.Fatalf("OpenFile() error = %v", err)
}
conn := &Conn{
fd: int64(fd.Fd()),
readBufferSize: 4096,
safeConns: &core.SafeConns[Conn]{},
}
var onCloseCalled bool
var onCloseConn *Conn
var onCloseErr error
var callCount int
callback := ToCallback(
func(c *Conn, err error) {
// Do nothing for this test
},
func(c *Conn, data []byte) {
// Do nothing for this test
},
func(c *Conn, err error) {
callCount++
onCloseCalled = true
onCloseConn = c
onCloseErr = err
},
)
// 执行关闭操作
tt.closeMethod(conn)
// 模拟调用OnClose(在实际应用中,这会在连接关闭时自动调用)
callback.OnClose(conn, tt.setupError)
// 验证回调被调用
if !onCloseCalled {
t.Error("OnClose callback was not called")
}
// 验证传递的连接对象
if onCloseConn != conn {
t.Error("OnClose callback received wrong connection object")
}
// 验证错误参数
if tt.expectError && onCloseErr == nil {
t.Error("OnClose callback should have received an error")
}
if !tt.expectError && onCloseErr != nil {
t.Errorf("OnClose callback received unexpected error: %v", onCloseErr)
}
// 验证连接状态
if tt.expectedClosed && atomic.LoadInt64(&conn.fd) != -1 {
t.Error("Connection should be closed")
}
// 验证回调只被调用一次(即使多次调用Close)
if callCount > 1 {
t.Errorf("OnClose callback was called %d times, expected 1", callCount)
}
})
}
}
// TestConn_CloseCleanup 测试连接关闭时的清理工作
func TestConn_CloseCleanup(t *testing.T) {
fd, err := os.OpenFile("/dev/null", os.O_RDONLY, 0600)
if err != nil {
t.Fatalf("OpenFile() error = %v", err)
}
conn := &Conn{
fd: int64(fd.Fd()),
readBufferSize: 4096,
safeConns: &core.SafeConns[Conn]{},
}
// 设置一些状态用于测试清理
conn.SetSession(testSessionData)
// 设置定时器
_ = conn.SetDeadline(time.Now().Add(time.Hour))
// 添加一些写缓冲区
testData := []byte("test data for buffer")
buf := getBytes(len(testData))
copy(*buf, testData)
conn.wbufList = append(conn.wbufList, buf)
// 验证设置成功
if conn.GetSession() != testSessionData {
t.Error("Session should be set")
}
if conn.readTimer == nil || conn.writeTimer == nil {
t.Error("Timers should be set")
}
if len(conn.wbufList) == 0 {
t.Error("Write buffer should not be empty")
}
var onCloseCallbackCalled bool
callback := ToCallback(
func(c *Conn, err error) {
// Do nothing
},
func(c *Conn, data []byte) {
// Do nothing
},
func(c *Conn, err error) {
onCloseCallbackCalled = true
},
)
// 关闭连接
conn.Close()
callback.OnClose(conn, nil)
// 验证连接被关闭
if atomic.LoadInt64(&conn.fd) != -1 {
t.Error("Connection fd should be -1 after close")
}
// 验证定时器被清理
if conn.readTimer != nil {
t.Error("Read timer should be nil after close")
}
if conn.writeTimer != nil {
t.Error("Write timer should be nil after close")
}
// 验证写缓冲区被清理
if len(conn.wbufList) != 0 {
t.Error("Write buffer list should be empty after close")
}
// 验证回调被调用
if !onCloseCallbackCalled {
t.Error("OnClose callback should be called")
}
// 验证Session仍然可以访问(Session不会被清理,由用户决定)
if conn.GetSession() != testSessionData {
t.Error("Session should still be accessible after close")
}
}
// TestConn_CloseWithTimeout 测试超时关闭的OnClose回调
func TestConn_CloseWithTimeout(t *testing.T) {
fd, err := os.OpenFile("/dev/null", os.O_RDONLY, 0600)
if err != nil {
t.Fatalf("OpenFile() error = %v", err)
}
conn := &Conn{
fd: int64(fd.Fd()),
readBufferSize: 4096,
safeConns: &core.SafeConns[Conn]{},
}
var onCloseCallbackCalled bool
var timeoutOccurred bool
callback := ToCallback(
func(c *Conn, err error) {
// Do nothing
},
func(c *Conn, data []byte) {
// Do nothing
},
func(c *Conn, err error) {
onCloseCallbackCalled = true
// 在实际场景中,超时关闭可能会传递特定的错误
},
)
// 设置一个很短的超时时间
timeout := 50 * time.Millisecond
err = conn.SetDeadline(time.Now().Add(timeout))
if err != nil {
t.Fatalf("SetDeadline() error = %v", err)
}
// 等待超时发生
time.Sleep(timeout + 20*time.Millisecond)
// 验证连接被超时关闭
if atomic.LoadInt64(&conn.fd) != -1 {
t.Error("Connection should be closed after timeout")
conn.Close() // 手动清理
} else {
timeoutOccurred = true
}
// 模拟超时关闭时的OnClose调用
if timeoutOccurred {
callback.OnClose(conn, nil)
}
// 验证超时确实发生
if !timeoutOccurred {
t.Error("Timeout should have occurred")
}
// 验证回调被调用
if timeoutOccurred && !onCloseCallbackCalled {
t.Error("OnClose callback should be called after timeout")
}
}
// TestCallback_ToCallback 测试ToCallback函数
func TestCallback_ToCallback(t *testing.T) {
var onOpenCalled, onDataCalled, onCloseCalled bool
var receivedConn *Conn
var receivedData []byte
var receivedErr error
callback := ToCallback(
func(c *Conn, err error) {
onOpenCalled = true
receivedConn = c
receivedErr = err
},
func(c *Conn, data []byte) {
onDataCalled = true
receivedConn = c
receivedData = data
},
func(c *Conn, err error) {
onCloseCalled = true
receivedConn = c
receivedErr = err
},
)
// 创建测试连接
fd, err := os.OpenFile("/dev/null", os.O_RDONLY, 0600)
if err != nil {
t.Fatalf("OpenFile() error = %v", err)
}
defer func() {
if err := fd.Close(); err != nil {
t.Logf("failed to close fd: %v", err)
}
}()
conn := &Conn{
fd: int64(fd.Fd()),
readBufferSize: 4096,
safeConns: &core.SafeConns[Conn]{},
}
defer conn.Close()
testData := []byte("test data")
testErr := net.ErrClosed
// 测试OnOpen
callback.OnOpen(conn)
if !onOpenCalled {
t.Error("OnOpen should be called")
}
if receivedConn != conn {
t.Error("OnOpen should receive correct connection")
}
if receivedErr != nil {
t.Error("OnOpen should receive nil error through ToCallback")
}
// 重置状态
onOpenCalled = false
receivedConn = nil
receivedErr = nil
// 测试OnData
callback.OnData(conn, testData)
if !onDataCalled {
t.Error("OnData should be called")
}
if receivedConn != conn {
t.Error("OnData should receive correct connection")
}
if string(receivedData) != string(testData) {
t.Error("OnData should receive correct data")
}
// 重置状态
onDataCalled = false
receivedConn = nil
receivedData = nil
// 测试OnClose
callback.OnClose(conn, testErr)
if !onCloseCalled {
t.Error("OnClose should be called")
}
if receivedConn != conn {
t.Error("OnClose should receive correct connection")
}
if receivedErr != testErr {
t.Error("OnClose should receive correct error")
}
}