Skip to content

Commit

Permalink
🔥 Feature: Add thread-safe reading from a closed testConn
Browse files Browse the repository at this point in the history
  • Loading branch information
grivera64 committed Oct 3, 2024
1 parent 44cd700 commit 00405f7
Show file tree
Hide file tree
Showing 2 changed files with 46 additions and 5 deletions.
33 changes: 28 additions & 5 deletions helpers.go
Original file line number Diff line number Diff line change
Expand Up @@ -613,13 +613,36 @@ func isNoCache(cacheControl string) bool {
}

type testConn struct {
r bytes.Buffer
w bytes.Buffer
r bytes.Buffer
w bytes.Buffer
isClosed bool
sync.Mutex
}

func (c *testConn) Read(b []byte) (int, error) { return c.r.Read(b) } //nolint:wrapcheck // This must not be wrapped
func (c *testConn) Write(b []byte) (int, error) { return c.w.Write(b) } //nolint:wrapcheck // This must not be wrapped
func (*testConn) Close() error { return nil }
func (c *testConn) Read(b []byte) (int, error) {
c.Lock()
defer c.Unlock()

return c.r.Read(b) //nolint:wrapcheck // This must not be wrapped
}

func (c *testConn) Write(b []byte) (int, error) {
c.Lock()
defer c.Unlock()

if c.isClosed {
return 0, errors.New("testConn is closed")
}
return c.w.Write(b) //nolint:wrapcheck // This must not be wrapped
}

func (c *testConn) Close() error {
c.Lock()
defer c.Unlock()

c.isClosed = true
return nil
}

func (*testConn) LocalAddr() net.Addr { return &net.TCPAddr{Port: 0, Zone: "", IP: net.IPv4zero} }
func (*testConn) RemoteAddr() net.Addr { return &net.TCPAddr{Port: 0, Zone: "", IP: net.IPv4zero} }
Expand Down
18 changes: 18 additions & 0 deletions helpers_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -5,6 +5,7 @@
package fiber

import (
"errors"
"strings"
"testing"
"time"
Expand Down Expand Up @@ -514,6 +515,23 @@ func Test_Utils_TestConn_Deadline(t *testing.T) {
require.NoError(t, conn.SetWriteDeadline(time.Time{}))
}

func Test_Utils_TestConn_Closed_Write(t *testing.T) {
t.Parallel()
conn := &testConn{}

_, err := conn.Write([]byte("Hello World"))
require.NoError(t, err)

conn.Close()
_, err = conn.Write([]byte("This should fail"))
require.ErrorIs(t, err, errors.New("testConn is closed"))

buffer := make([]byte, 12)
_, err = conn.Read(buffer)
require.NoError(t, err)
require.Equal(t, []byte("Hello World"), buffer)
}

func Test_Utils_IsNoCache(t *testing.T) {
t.Parallel()
testCases := []struct {
Expand Down

0 comments on commit 00405f7

Please sign in to comment.