osbuild-worker-executor/main_test: use random port for tests
this for sure is racy but better than colliding with other tests with a fixed port for sure
This commit is contained in:
parent
06d0bb63f6
commit
55c5602f91
1 changed files with 21 additions and 4 deletions
|
|
@ -3,8 +3,10 @@ package main_test
|
||||||
import (
|
import (
|
||||||
"context"
|
"context"
|
||||||
"fmt"
|
"fmt"
|
||||||
|
"net"
|
||||||
"net/http"
|
"net/http"
|
||||||
"os"
|
"os"
|
||||||
|
"strconv"
|
||||||
"testing"
|
"testing"
|
||||||
"time"
|
"time"
|
||||||
|
|
||||||
|
|
@ -49,11 +51,26 @@ func waitReady(ctx context.Context, timeout time.Duration, endpoint string) erro
|
||||||
}
|
}
|
||||||
}
|
}
|
||||||
|
|
||||||
|
// getFreePort() returns a free port.
|
||||||
|
// This is racy but better than using a fixed one
|
||||||
|
func getFreePort() (int, error) {
|
||||||
|
l, err := net.Listen("tcp", ":0")
|
||||||
|
if err != nil {
|
||||||
|
return 0, err
|
||||||
|
}
|
||||||
|
defer l.Close()
|
||||||
|
|
||||||
|
addr := l.Addr().(*net.TCPAddr)
|
||||||
|
return addr.Port, nil
|
||||||
|
}
|
||||||
|
|
||||||
func runTestServer(t *testing.T) (baseURL, buildBaseDir string, loggerHook *logrusTest.Hook) {
|
func runTestServer(t *testing.T) (baseURL, buildBaseDir string, loggerHook *logrusTest.Hook) {
|
||||||
host := "localhost"
|
host := "localhost"
|
||||||
port := "18002"
|
port, err := getFreePort()
|
||||||
|
assert.NoError(t, err, "failed to find a free port on localhost")
|
||||||
|
|
||||||
buildBaseDir = t.TempDir()
|
buildBaseDir = t.TempDir()
|
||||||
baseURL = fmt.Sprintf("http://%s:%s/", host, port)
|
baseURL = fmt.Sprintf("http://%s:%d/", host, port)
|
||||||
|
|
||||||
restore := main.MockUnixSethostname(func([]byte) error {
|
restore := main.MockUnixSethostname(func([]byte) error {
|
||||||
return nil
|
return nil
|
||||||
|
|
@ -68,14 +85,14 @@ func runTestServer(t *testing.T) (baseURL, buildBaseDir string, loggerHook *logr
|
||||||
|
|
||||||
args := []string{
|
args := []string{
|
||||||
"-host", host,
|
"-host", host,
|
||||||
"-port", port,
|
"-port", strconv.Itoa(port),
|
||||||
"-build-path", buildBaseDir,
|
"-build-path", buildBaseDir,
|
||||||
}
|
}
|
||||||
go func() {
|
go func() {
|
||||||
_ = main.Run(ctx, args, os.Getenv, logger)
|
_ = main.Run(ctx, args, os.Getenv, logger)
|
||||||
}()
|
}()
|
||||||
|
|
||||||
err := waitReady(ctx, defaultTimeout, baseURL)
|
err = waitReady(ctx, defaultTimeout, baseURL)
|
||||||
assert.NoError(t, err)
|
assert.NoError(t, err)
|
||||||
|
|
||||||
return baseURL, buildBaseDir, loggerHook
|
return baseURL, buildBaseDir, loggerHook
|
||||||
|
|
|
||||||
Loading…
Add table
Add a link
Reference in a new issue