Skip to content

Commit 0f41b37

Browse files
committed
opt: fix the nil panic in conn.Flush() and increase the code coverage
1 parent abcc031 commit 0f41b37

File tree

2 files changed

+31
-5
lines changed

2 files changed

+31
-5
lines changed

connection.go

+1-1
Original file line numberDiff line numberDiff line change
@@ -376,7 +376,7 @@ func (c *conn) WriteTo(w io.Writer) (n int64, err error) {
376376
}
377377

378378
func (c *conn) Flush() error {
379-
if c.outboundBuffer.IsEmpty() {
379+
if c.outboundBuffer == nil || c.outboundBuffer.IsEmpty() {
380380
return nil
381381
}
382382

gnet_test.go

+30-4
Original file line numberDiff line numberDiff line change
@@ -34,6 +34,7 @@ import (
3434
"github.com/stretchr/testify/assert"
3535
"github.com/stretchr/testify/require"
3636
"go.uber.org/zap"
37+
"golang.org/x/sys/unix"
3738

3839
gerr "github.com/panjf2000/gnet/v2/pkg/errors"
3940
"github.com/panjf2000/gnet/v2/pkg/logging"
@@ -326,6 +327,24 @@ func (s *testServer) OnTraffic(c Conn) (action Action) {
326327
}
327328
buf, _ := c.Next(-1)
328329
_, _ = c.Write(buf)
330+
331+
// Only for code coverage of testing.
332+
if !s.multicore {
333+
assert.NoErrorf(s.tester, c.Flush(), "flush error")
334+
_ = c.Fd()
335+
fd, err := c.Dup()
336+
assert.NoError(s.tester, err)
337+
assert.Greater(s.tester, fd, 0)
338+
assert.NoErrorf(s.tester, unix.Close(fd), "close error")
339+
assert.NoErrorf(s.tester, c.SetReadBuffer(streamLen), "set read buffer error")
340+
assert.NoErrorf(s.tester, c.SetWriteBuffer(streamLen), "set write buffer error")
341+
if s.network == "tcp" {
342+
assert.NoErrorf(s.tester, c.SetLinger(1), "set linger error")
343+
assert.NoErrorf(s.tester, c.SetNoDelay(false), "set no delay error")
344+
assert.NoErrorf(s.tester, c.SetKeepAlivePeriod(time.Minute), "set keep alive period error")
345+
}
346+
}
347+
329348
return
330349
}
331350

@@ -773,9 +792,13 @@ func (t *testCloseActionErrorServer) OnClose(c Conn, err error) (action Action)
773792

774793
func (t *testCloseActionErrorServer) OnTraffic(c Conn) (action Action) {
775794
n := c.InboundBuffered()
776-
buf, _ := c.Peek(n)
777-
_, _ = c.Write(buf)
778-
_, _ = c.Discard(n)
795+
buf := make([]byte, n)
796+
m, err := c.Read(buf)
797+
assert.NoError(t.tester, err)
798+
assert.EqualValuesf(t.tester, n, m, "read %d bytes, expected %d", m, n)
799+
n, err = c.Write(buf)
800+
assert.NoError(t.tester, err)
801+
assert.EqualValuesf(t.tester, m, n, "wrote %d bytes, expected %d", n, m)
779802
action = Close
780803
return
781804
}
@@ -1001,7 +1024,10 @@ func (t *testCloseConnectionServer) OnTraffic(c Conn) (action Action) {
10011024
_, _ = c.Discard(-1)
10021025
go func() {
10031026
time.Sleep(time.Second)
1004-
_ = c.Close()
1027+
_ = c.CloseWithCallback(func(c Conn, err error) error {
1028+
assert.ErrorIsf(t.tester, err, gerr.ErrEngineShutdown, "should be engine shutdown error")
1029+
return nil
1030+
})
10051031
}()
10061032
return
10071033
}

0 commit comments

Comments
 (0)