Skip to content

Commit

Permalink
Get random free port in websocket tests
Browse files Browse the repository at this point in the history
  • Loading branch information
sergystepanov committed Feb 17, 2024
1 parent e7e2810 commit b79b4c4
Showing 1 changed file with 20 additions and 1 deletion.
21 changes: 20 additions & 1 deletion pkg/com/net_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -4,6 +4,7 @@ import (
"encoding/json"
"fmt"
"math/rand"
"net"
"net/http"
"net/url"
"sync"
Expand Down Expand Up @@ -49,7 +50,13 @@ func TestWebsocket(t *testing.T) {
}

func testWebsocket(t *testing.T) {
addr := ":8989"
port, err := getFreePort()
if err != nil {
t.Logf("couldn't get any free port")
t.Skip()
}
addr := fmt.Sprintf(":%v", port)

server := newServer(addr, t)
client := newClient(t, url.URL{Scheme: "ws", Host: "localhost" + addr, Path: "/ws"})
clDone := client.ProcessPackets(func(in TestIn) error { return nil })
Expand Down Expand Up @@ -206,3 +213,15 @@ func newServer(addr string, t *testing.T) *serverHandler {
wg.Wait()
return &handler
}

func getFreePort() (port int, err error) {
var a *net.TCPAddr
var l *net.TCPListener
if a, err = net.ResolveTCPAddr("tcp", ":0"); err == nil {
if l, err = net.ListenTCP("tcp", a); err == nil {
defer func() { _ = l.Close() }()
return l.Addr().(*net.TCPAddr).Port, nil
}
}
return
}

0 comments on commit b79b4c4

Please sign in to comment.