@@ -10,8 +10,11 @@ import (
1010 "fmt"
1111 "io"
1212 "log"
13+ "net"
1314 "net/http"
15+ "os"
1416 "reflect"
17+ "runtime"
1518 "strings"
1619 "sync"
1720 "sync/atomic"
@@ -88,6 +91,61 @@ func Subtests(t *testing.T, receiver any) {
8891 }
8992}
9093
94+ func FreePort (t * testing.T ) (int , net.Listener , * os.File ) {
95+ t .Helper ()
96+ // bind to localhost because we don't want to allow external connections
97+ l , err := net .ListenTCP ("tcp" , & net.TCPAddr {IP : net .IPv4 (127 , 0 , 0 , 1 )})
98+ if err != nil {
99+ t .Fatal ("Failed to listen on a free port:" , err )
100+ }
101+ var f * os.File
102+ if runtime .GOOS != "windows" {
103+ f , err = l .File ()
104+ if err != nil {
105+ t .Fatal ("Failed to get file for a free port:" , err )
106+ }
107+ }
108+ t .Cleanup (func () {
109+ l .Close ()
110+ if f != nil {
111+ f .Close ()
112+ }
113+ })
114+ return l .Addr ().(* net.TCPAddr ).Port , l , f
115+ }
116+
117+ func PortalPorts (t * testing.T ) (* PortalTest , []string ) {
118+ httpPort , hl , httpFD := FreePort (t )
119+ httpsPort , sl , httpsFD := FreePort (t )
120+ rpcPort , rl , rpcFD := FreePort (t )
121+
122+ if runtime .GOOS == "windows" {
123+ hl .Close ()
124+ sl .Close ()
125+ rl .Close ()
126+
127+ return & PortalTest {
128+ HTTPPort : httpPort ,
129+ HTTPSPort : httpsPort ,
130+ RPCPort : rpcPort ,
131+ }, []string {
132+ fmt .Sprintf ("-http_port=%v" , httpPort ),
133+ fmt .Sprintf ("-https_port=%v" , httpsPort ),
134+ fmt .Sprintf ("-rpc_port=%v" , rpcPort ),
135+ }
136+ } else {
137+ return & PortalTest {
138+ HTTPPort : httpPort ,
139+ HTTPSPort : httpsPort ,
140+ RPCPort : rpcPort ,
141+ }, []string {
142+ fmt .Sprintf ("-http_port=-%v" , httpFD .Fd ()),
143+ fmt .Sprintf ("-https_port=-%v" , httpsFD .Fd ()),
144+ fmt .Sprintf ("-rpc_port=-%v" , rpcFD .Fd ()),
145+ }
146+ }
147+ }
148+
91149// This needs to be run before any t.Cleanup() operations you do in your
92150// function so that Cleanup from this function runs after any goroutines from
93151// the test are shut down and waited on.
0 commit comments