Skip to content

chore: consolidate various randomPort() implementations #12362

New issue

Have a question about this project? Sign up for a free GitHub account to open an issue and contact its maintainers and the community.

By clicking “Sign up for GitHub”, you agree to our terms of service and privacy statement. We’ll occasionally send you account related emails.

Already on GitHub? Sign in to your account

Merged
merged 2 commits into from
Feb 29, 2024
Merged
Show file tree
Hide file tree
Changes from 1 commit
Commits
File filter

Filter by extension

Filter by extension

Conversations
Failed to load comments.
Loading
Jump to
Jump to file
Failed to load files.
Loading
Diff view
Diff view
Prev Previous commit
fixup! chore: DRY up various randomPort() implementations
  • Loading branch information
johnstcn committed Feb 29, 2024
commit 257c8d1a8049298ac8da485c57bb51eb3a20cce9
2 changes: 1 addition & 1 deletion agent/agent_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -837,7 +837,7 @@ func TestAgent_TCPRemoteForwarding(t *testing.T) {
var ll net.Listener
var err error
for {
randomPort = testutil.RandomPortNoListen()
randomPort = testutil.RandomPortNoListen(t)
Copy link
Member

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

nit: testutil.FreePort?

Copy link
Member Author

Choose a reason for hiding this comment

The reason will be displayed to describe this comment to others. Learn more.

This one isn't guaranteed to be free and relies on pure randommess.
Regarding the other implementation, I just picked the existing name.
We can rename later if need be. 👍

addr := net.TCPAddrFromAddrPort(netip.AddrPortFrom(localhost, randomPort))
ll, err = sshClient.ListenTCP(addr)
if err != nil {
Expand Down
14 changes: 12 additions & 2 deletions testutil/port.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,11 +3,19 @@ package testutil
import (
"math/rand"
"net"
"sync"
"testing"
"time"

"github.com/stretchr/testify/require"
)

var (
// nolint:gosec // not used for cryptography
rnd = rand.New(rand.NewSource(time.Now().Unix()))
rndMu sync.Mutex
)

// RandomPort is a helper function to find a free random port.
// Note that the OS may reallocate the port very quickly, so
// this is not _guaranteed_.
Expand All @@ -23,13 +31,15 @@ func RandomPort(t *testing.T) int {
// RandomPortNoListen returns a random port in the ephemeral port range.
// Does not attempt to listen and close to find a port as the OS may
// reallocate the port very quickly.
func RandomPortNoListen() uint16 {
func RandomPortNoListen(*testing.T) uint16 {
const (
// Overlap of windows, linux in https://en.wikipedia.org/wiki/Ephemeral_port
min = 49152
max = 60999
)
n := max - min
x := rand.Intn(n) //nolint: gosec
rndMu.Lock()
x := rnd.Intn(n)
rndMu.Unlock()
return uint16(min + x)
}