|
|
|
@ -11,8 +11,6 @@ import (
|
|
|
|
|
"runtime"
|
|
|
|
|
"sync"
|
|
|
|
|
"time"
|
|
|
|
|
|
|
|
|
|
"github.com/mitchellh/go-testing-interface"
|
|
|
|
|
)
|
|
|
|
|
|
|
|
|
|
const (
|
|
|
|
@ -251,6 +249,8 @@ func alloc() (int, net.Listener) {
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// MustTake is the same as Take except it panics on error.
|
|
|
|
|
//
|
|
|
|
|
// Deprecated: Use GetN or Port instead.
|
|
|
|
|
func MustTake(n int) (ports []int) {
|
|
|
|
|
ports, err := Take(n)
|
|
|
|
|
if err != nil {
|
|
|
|
@ -263,6 +263,8 @@ func MustTake(n int) (ports []int) {
|
|
|
|
|
// to call this method concurrently. Ports have been tested to be available on
|
|
|
|
|
// 127.0.0.1 TCP but there is no guarantee that they will remain free in the
|
|
|
|
|
// future.
|
|
|
|
|
//
|
|
|
|
|
// Most callers should prefer GetN or Port.
|
|
|
|
|
func Take(n int) (ports []int, err error) {
|
|
|
|
|
if n <= 0 {
|
|
|
|
|
return nil, fmt.Errorf("freeport: cannot take %d ports", n)
|
|
|
|
@ -381,11 +383,39 @@ func logf(severity string, format string, a ...interface{}) {
|
|
|
|
|
fmt.Fprintf(os.Stderr, "["+severity+"] freeport: "+format+"\n", a...)
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
type TestingT interface {
|
|
|
|
|
Helper()
|
|
|
|
|
Fatalf(format string, args ...interface{})
|
|
|
|
|
Cleanup(func())
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// GetN returns n free ports from the allocated port block, and returns the
|
|
|
|
|
// ports to the pool when the test ends. See Take for more details.
|
|
|
|
|
func GetN(t TestingT, n int) []int {
|
|
|
|
|
t.Helper()
|
|
|
|
|
ports, err := Take(n)
|
|
|
|
|
if err != nil {
|
|
|
|
|
t.Fatalf("failed to take %v ports: %w", n, err)
|
|
|
|
|
}
|
|
|
|
|
t.Cleanup(func() {
|
|
|
|
|
Return(ports)
|
|
|
|
|
})
|
|
|
|
|
return ports
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Port returns a single free port from the allocated port block, and returns the
|
|
|
|
|
// port to the pool when the test ends. See Take for more details.
|
|
|
|
|
// Use GetN if more than a single port is required.
|
|
|
|
|
func Port(t TestingT) int {
|
|
|
|
|
t.Helper()
|
|
|
|
|
return GetN(t, 1)[0]
|
|
|
|
|
}
|
|
|
|
|
|
|
|
|
|
// Deprecated: Please use Take/Return calls instead.
|
|
|
|
|
func Get(n int) (ports []int) { return MustTake(n) }
|
|
|
|
|
|
|
|
|
|
// Deprecated: Please use Take/Return calls instead.
|
|
|
|
|
func GetT(t testing.T, n int) (ports []int) { return MustTake(n) }
|
|
|
|
|
func GetT(t TestingT, n int) (ports []int) { return MustTake(n) }
|
|
|
|
|
|
|
|
|
|
// Deprecated: Please use Take/Return calls instead.
|
|
|
|
|
func Free(n int) (ports []int, err error) { return MustTake(n), nil }
|
|
|
|
|