2015-05-19 01:13:17 +03:00
|
|
|
package connection
|
|
|
|
|
|
|
|
import (
|
|
|
|
"fmt"
|
|
|
|
"net"
|
|
|
|
"os"
|
2015-07-15 05:38:15 +03:00
|
|
|
"runtime"
|
2015-05-19 01:13:17 +03:00
|
|
|
"testing"
|
|
|
|
|
|
|
|
"github.com/stretchr/testify/assert"
|
|
|
|
)
|
|
|
|
|
|
|
|
func Test_portAvailable(t *testing.T) {
|
2015-07-15 05:38:15 +03:00
|
|
|
if runtime.GOOS == "windows" {
|
|
|
|
t.Skip("FIXME")
|
|
|
|
}
|
|
|
|
|
2017-01-20 22:41:24 +03:00
|
|
|
assert.Equal(t, true, portAvailable(30000))
|
2015-05-19 01:13:17 +03:00
|
|
|
|
2017-01-20 22:41:24 +03:00
|
|
|
serv, err := net.Listen("tcp", "127.0.0.1:30000")
|
2015-05-19 01:13:17 +03:00
|
|
|
if err != nil {
|
2016-01-22 21:12:00 +03:00
|
|
|
fmt.Fprintln(os.Stderr, "Unable to start test tcp listener:", err)
|
2015-05-19 01:13:17 +03:00
|
|
|
t.Fail()
|
|
|
|
return
|
|
|
|
}
|
|
|
|
defer serv.Close()
|
|
|
|
|
|
|
|
go func() {
|
|
|
|
for {
|
|
|
|
conn, err := serv.Accept()
|
|
|
|
if err == nil {
|
|
|
|
conn.Close()
|
|
|
|
}
|
2015-10-20 05:09:22 +03:00
|
|
|
serv.Close()
|
2015-05-19 01:13:17 +03:00
|
|
|
}
|
|
|
|
}()
|
|
|
|
|
2017-01-20 22:41:24 +03:00
|
|
|
assert.Equal(t, false, portAvailable(30000))
|
|
|
|
assert.Equal(t, true, portAvailable(30001))
|
2015-05-19 01:13:17 +03:00
|
|
|
}
|
|
|
|
|
|
|
|
func Test_getAvailablePort(t *testing.T) {
|
2015-07-15 05:38:15 +03:00
|
|
|
if runtime.GOOS == "windows" {
|
|
|
|
t.Skip("FIXME")
|
|
|
|
}
|
|
|
|
|
2017-01-20 22:41:24 +03:00
|
|
|
port, err := AvailablePort(30000, 1)
|
2015-05-19 01:13:17 +03:00
|
|
|
assert.Equal(t, nil, err)
|
2017-01-20 22:41:24 +03:00
|
|
|
assert.Equal(t, 30000, port)
|
2015-05-19 01:13:17 +03:00
|
|
|
|
2017-01-20 22:41:24 +03:00
|
|
|
serv, err := net.Listen("tcp", "127.0.0.1:30000")
|
2015-05-19 01:13:17 +03:00
|
|
|
if err != nil {
|
2016-01-22 21:12:00 +03:00
|
|
|
fmt.Fprintln(os.Stderr, "Unable to start test tcp listener:", err)
|
2015-05-19 01:13:17 +03:00
|
|
|
t.Fail()
|
|
|
|
return
|
|
|
|
}
|
|
|
|
defer serv.Close()
|
|
|
|
|
|
|
|
go func() {
|
|
|
|
for {
|
|
|
|
conn, err := serv.Accept()
|
|
|
|
if err == nil {
|
|
|
|
conn.Close()
|
|
|
|
}
|
|
|
|
}
|
|
|
|
}()
|
|
|
|
|
2017-01-20 22:41:24 +03:00
|
|
|
port, err = AvailablePort(30000, 0)
|
2015-05-19 01:13:17 +03:00
|
|
|
assert.EqualError(t, err, "No available port")
|
|
|
|
assert.Equal(t, -1, port)
|
|
|
|
|
2017-01-20 22:41:24 +03:00
|
|
|
port, err = AvailablePort(30000, 1)
|
2015-05-19 01:13:17 +03:00
|
|
|
assert.Equal(t, nil, err)
|
2017-01-20 22:41:24 +03:00
|
|
|
assert.Equal(t, 30001, port)
|
2015-05-19 01:13:17 +03:00
|
|
|
}
|