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:
@@ -3,6 +3,7 @@ package testlib
|
|||||||
|
|
||||||
import (
|
import (
|
||||||
"io/ioutil"
|
"io/ioutil"
|
||||||
|
"net"
|
||||||
"os"
|
"os"
|
||||||
"strings"
|
"strings"
|
||||||
"testing"
|
"testing"
|
||||||
@@ -52,3 +53,14 @@ func Rewrite(t *testing.T, path, contents string) error {
|
|||||||
|
|
||||||
return err
|
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()
|
||||||
|
}
|
||||||
|
|||||||
@@ -76,3 +76,10 @@ func TestRewrite(t *testing.T) {
|
|||||||
t.Errorf("basic rewrite failed")
|
t.Errorf("basic rewrite failed")
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
func TestGetFreePort(t *testing.T) {
|
||||||
|
p := GetFreePort()
|
||||||
|
if p == "" {
|
||||||
|
t.Errorf("failed to get free port")
|
||||||
|
}
|
||||||
|
}
|
||||||
|
|||||||
Reference in New Issue
Block a user