Skip to content

Commit

Permalink
test: fix leak test
Browse files Browse the repository at this point in the history
  • Loading branch information
Ehco1996 committed Feb 18, 2024
1 parent 4277434 commit 0a1730c
Showing 1 changed file with 11 additions and 11 deletions.
22 changes: 11 additions & 11 deletions internal/conn/conn_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -73,51 +73,51 @@ func TestCopyConn(t *testing.T) {
assert.NoError(t, err)
defer echoServer.Close()

// 数据准备
msg := "Hello, TCP!"

// 在另一个goroutine中启动回显服务器
go func() {
for {
conn, err := echoServer.Accept()
if err != nil {
return // 避免无限制的错误日志
return
}
go func(c net.Conn) {
defer c.Close()
io.Copy(c, c) // 简单的回显服务
io.Copy(c, c)
}(conn)
}
}()

// 客户端连接到回显服务器
clientConn, err := net.Dial("tcp", echoServer.Addr().String())
assert.NoError(t, err)
defer clientConn.Close()

// 模拟内部连接,这里简化为再次使用客户端连接;实际使用中应为独立的连接
remoteConn, err := net.Dial("tcp", echoServer.Addr().String())
assert.NoError(t, err)
defer remoteConn.Close()

// 为 copyConn 函数创建包装后的连接
c1 := &innerConn{Conn: clientConn, remoteLabel: "client", stats: &Stats{}}
c2 := &innerConn{Conn: remoteConn, remoteLabel: "server", stats: &Stats{}}

// 在goroutine中启动copyConn以避免阻塞
done := make(chan struct{})
go func() {
if err := copyConn(c1, c2); err != nil {
t.Log(err) // 使用t.Log而不是assert.NoError来避免在goroutine中调用t的方法
t.Log(err)
}
done <- struct{}{}
close(done)
}()

// 发送数据到客户端连接,观察是否能通过转发正确回显
_, err = clientConn.Write([]byte(msg))
assert.NoError(t, err)

// 读取回显的数据
buffer := make([]byte, len(msg))
_, err = clientConn.Read(buffer)
assert.NoError(t, err)
assert.Equal(t, msg, string(buffer))
//close the connection
_ = clientConn.Close()
_ = remoteConn.Close()
// wait for the copyConn to finish
<-done
}

0 comments on commit 0a1730c

Please sign in to comment.