1
0
mirror of https://blitiri.com.ar/repos/chasquid synced 2025-12-18 14:47:03 +00:00

test: Add testlib.GetFreePort function

Some tests require picking ports, and today resort to hard-coding,
which is brittle.

This patch adds a testlib.GetFreePort function to help pick free ports.

It is not totally race-free, but is much better than hard-coding.
This commit is contained in:
Alberto Bertogli
2019-11-30 11:34:14 +00:00
parent 87e5acde59
commit ac2c5ab4db
2 changed files with 19 additions and 0 deletions

View File

@@ -3,6 +3,7 @@ package testlib
import (
"io/ioutil"
"net"
"os"
"strings"
"testing"
@@ -52,3 +53,14 @@ func Rewrite(t *testing.T, path, contents string) error {
return err
}
// GetFreePort returns a free TCP port. This is hacky and not race-free, but
// it works well enough for testing purposes.
func GetFreePort() string {
l, err := net.Listen("tcp", "localhost:0")
if err != nil {
panic(err)
}
defer l.Close()
return l.Addr().String()
}