git » chasquid » commit ac2c5ab

test: Add testlib.GetFreePort function

author Alberto Bertogli
2019-11-30 11:34:14 UTC
committer Alberto Bertogli
2019-11-30 11:38:46 UTC
parent 87e5acde595ebb8fff6f346e308586de061b13b3

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.

internal/testlib/testlib.go +12 -0
internal/testlib/testlib_test.go +7 -0

diff --git a/internal/testlib/testlib.go b/internal/testlib/testlib.go
index 34299fe..d2bde57 100644
--- a/internal/testlib/testlib.go
+++ b/internal/testlib/testlib.go
@@ -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()
+}
diff --git a/internal/testlib/testlib_test.go b/internal/testlib/testlib_test.go
index 71b84ef..10c90eb 100644
--- a/internal/testlib/testlib_test.go
+++ b/internal/testlib/testlib_test.go
@@ -76,3 +76,10 @@ func TestRewrite(t *testing.T) {
 		t.Errorf("basic rewrite failed")
 	}
 }
+
+func TestGetFreePort(t *testing.T) {
+	p := GetFreePort()
+	if p == "" {
+		t.Errorf("failed to get free port")
+	}
+}