From 2ec9568b10cff8bd82b78e34e9005552134135d6 Mon Sep 17 00:00:00 2001 From: Zhuowei Wang Date: Wed, 11 Sep 2024 15:30:27 +0800 Subject: [PATCH] feat: support new connection by fd --- net_dialer.go | 16 ++++++++++++++++ net_dialer_test.go | 15 +++++++++++++++ 2 files changed, 31 insertions(+) diff --git a/net_dialer.go b/net_dialer.go index 85f1b7c6..74edd91c 100644 --- a/net_dialer.go +++ b/net_dialer.go @@ -28,6 +28,22 @@ func DialConnection(network, address string, timeout time.Duration) (connection return defaultDialer.DialConnection(network, address, timeout) } +// NewFDConnection create a Connection initialed by any fd +// It's useful for write unit test for functions have args with the type of netpoll.Connection +// The typical usage like: +// +// rfd, wfd := netpoll.GetSysFdPairs() +// rconn, _ = netpoll.NewFDConnection(rfd) +// wconn, _ = netpoll.NewFDConnection(wfd) +func NewFDConnection(fd int) (Connection, error) { + conn := new(connection) + err := conn.init(&netFD{fd: fd}, nil) + if err != nil { + return nil, err + } + return conn, nil +} + // NewDialer only support TCP and unix socket now. func NewDialer() Dialer { return &dialer{} diff --git a/net_dialer_test.go b/net_dialer_test.go index 64fa50cf..88a16af8 100644 --- a/net_dialer_test.go +++ b/net_dialer_test.go @@ -214,6 +214,21 @@ func TestDialerThenClose(t *testing.T) { wg.Wait() } +func TestNewFDConnection(t *testing.T) { + r, w := GetSysFdPairs() + rconn, err := NewFDConnection(r) + MustNil(t, err) + wconn, err := NewFDConnection(w) + MustNil(t, err) + _, err = rconn.Writer().WriteString("hello") + MustNil(t, err) + err = rconn.Writer().Flush() + MustNil(t, err) + buf, err := wconn.Reader().Next(5) + MustNil(t, err) + Equal(t, string(buf), "hello") +} + func mockDialerEventLoop(idx int) EventLoop { el, _ := NewEventLoop(func(ctx context.Context, conn Connection) (err error) { defer func() {