Skip to content

Commit

Permalink
test(netutil): add tests for StoppableListener
Browse files Browse the repository at this point in the history
- Added unit tests for StoppableListener to cover various scenarios:
  - Valid and invalid addresses
  - Accepting connections after stopping
  - Successful connection acceptance
- Improved test coverage and ensured reliability of the StoppableListener
  implementation.
  • Loading branch information
ijsong committed Dec 12, 2024
1 parent acf7b7c commit 44c7bb6
Showing 1 changed file with 82 additions and 0 deletions.
82 changes: 82 additions & 0 deletions pkg/util/netutil/netutil_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -2,15 +2,97 @@ package netutil

import (
"context"
"net"
"strconv"
"sync"
"testing"
"time"

"github.com/stretchr/testify/require"
"go.uber.org/goleak"

"github.com/kakao/varlog/pkg/types"
"github.com/kakao/varlog/pkg/verrors"
)

func TestStoppableListener(t *testing.T) {
tcs := []struct {
name string
addr string
wantErr bool
}{
{
name: "ValidAddress",
addr: "127.0.0.1:0",
wantErr: false,
},
{
name: "InvalidAddress",
addr: "127.0.0.1:-1",
wantErr: true,
},
}

for _, tc := range tcs {
t.Run(tc.name, func(t *testing.T) {
lis, err := NewStoppableListener(context.Background(), tc.addr)
if tc.wantErr {
require.Error(t, err)
return
}
require.NoError(t, err)
require.NotNil(t, lis)

err = lis.Close()
require.NoError(t, err)
})
}
}

func TestStoppableListener_AcceptStopped(t *testing.T) {
const expireDuration = 10 * time.Millisecond

ctx, cancel := context.WithTimeout(context.Background(), expireDuration)
defer cancel()

lis, err := NewStoppableListener(ctx, "127.0.0.1:0")
require.NoError(t, err)
t.Cleanup(func() {
err := lis.Close()
require.NoError(t, err)
})

_, err = lis.Accept()
require.Equal(t, verrors.ErrStopped, err)
}

func TestStoppableListener_AcceptSucceed(t *testing.T) {
lis, err := NewStoppableListener(context.Background(), "127.0.0.1:0")
require.NoError(t, err)
t.Cleanup(func() {
err := lis.Close()
require.NoError(t, err)
})

addr := lis.Addr().String()
var wg sync.WaitGroup
wg.Add(1)
go func() {
defer wg.Done()
conn, err := net.Dial("tcp", addr)
require.NoError(t, err)
err = conn.Close()
require.NoError(t, err)
}()

conn, err := lis.Accept()
require.NoError(t, err)
require.NotNil(t, conn)

err = conn.Close()
require.NoError(t, err)
}

func TestGetListenerAddr(t *testing.T) {
tests := []struct {
in string
Expand Down

0 comments on commit 44c7bb6

Please sign in to comment.