Commit ac2c5ab4 authored by Alberto Bertogli's avatar Alberto Bertogli

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.
parent 87e5acde
......@@ -3,6 +3,7 @@ package testlib
import (
......@@ -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 {
defer l.Close()
return l.Addr().String()
......@@ -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")
Markdown is supported
You are about to add 0 people to the discussion. Proceed with caution.
Finish editing this message first!
Please register or to comment