github.com/bingoohuang/gg@v0.0.0-20240325092523-45da7dee9335/pkg/netx/freeport/freeport_test.go (about) 1 package freeport 2 3 import ( 4 "net" 5 "strconv" 6 "testing" 7 8 "github.com/stretchr/testify/assert" 9 ) 10 11 func TestMustFreePort(t *testing.T) { 12 port := Port() 13 assert.True(t, IsFree(port)) 14 } 15 16 func BenchmarkFreePort(b *testing.B) { 17 for i := 0; i < b.N; i++ { 18 port := Port() 19 assert.True(b, port > 0) 20 } 21 } 22 23 func TestGetFreePort(t *testing.T) { 24 port, err := PortE() 25 if err != nil { 26 t.Error(err) 27 } 28 29 if port == 0 { 30 t.Error("port == 0") 31 } 32 33 // Try to listen on the port 34 l, err := net.Listen("tcp", "localhost"+":"+strconv.Itoa(port)) 35 if err != nil { 36 t.Error(err) 37 } 38 39 defer l.Close() 40 } 41 42 func TestGetFreePorts(t *testing.T) { 43 count := 3 44 ports, err := Ports(count) 45 if err != nil { 46 t.Error(err) 47 } 48 49 if len(ports) == 0 { 50 t.Error("len(ports) == 0") 51 } 52 53 for _, port := range ports { 54 if port == 0 { 55 t.Error("port == 0") 56 } 57 58 // Try to listen on the port 59 l, err := net.Listen("tcp", "localhost"+":"+strconv.Itoa(port)) 60 if err != nil { 61 t.Error(err) 62 } 63 defer l.Close() 64 } 65 } 66 67 func TestFindFreePortFrom(t *testing.T) { 68 p := PortStart(1024) // nolint gomnd 69 assert.True(t, p >= 1024) // nolint gomnd 70 }