Add TestFreePort(...) which just returns an available free localhost port (#964)

This commit is contained in:
Jim authored and GitHub committed 2021-02-25 14:31:14 -05:00
1 parent 72aa110f72
commit 64e6053278
2 files changed
+46

No files matched your search

+21
View File
@@ -0,0 +1,21 @@
package testutil
import (
"net"
"testing"
"github.com/stretchr/testify/require"
)
// TestFreePort just returns an available free localhost port
func TestFreePort(t *testing.T) int {
t.Helper()
require := require.New(t)
addr, err := net.ResolveTCPAddr("tcp", "localhost:0")
require.NoError(err)
l, err := net.ListenTCP("tcp", addr)
require.NoError(err)
defer l.Close()
return l.Addr().(*net.TCPAddr).Port
}
+25
View File
@@ -0,0 +1,25 @@
package testutil
import (
"fmt"
"net"
"testing"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
func Test_TestFreePort(t *testing.T) {
t.Parallel()
t.Run("simple-validation", func(t *testing.T) {
assert, require := assert.New(t), require.New(t)
p := TestFreePort(t)
assert.NotEmpty(p)
addr, err := net.ResolveTCPAddr("tcp", fmt.Sprintf("localhost:%d", p))
require.NoError(err)
l, err := net.ListenTCP("tcp", addr)
require.NoError(err)
defer l.Close()
})
}