Skip to content

Commit

Permalink
osbuild-worker-executor/main_test: use random port for tests
Browse files Browse the repository at this point in the history
this for sure is racy but better than colliding with other tests
with a fixed port for sure
  • Loading branch information
schuellerf authored and mvo5 committed Jun 24, 2024
1 parent 06d0bb6 commit 55c5602
Showing 1 changed file with 21 additions and 4 deletions.
25 changes: 21 additions & 4 deletions cmd/osbuild-worker-executor/main_test.go
Original file line number Diff line number Diff line change
Expand Up @@ -3,8 +3,10 @@ package main_test
import (
"context"
"fmt"
"net"
"net/http"
"os"
"strconv"
"testing"
"time"

Expand Down Expand Up @@ -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) {
host := "localhost"
port := "18002"
port, err := getFreePort()
assert.NoError(t, err, "failed to find a free port on localhost")

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 {
return nil
Expand All @@ -68,14 +85,14 @@ func runTestServer(t *testing.T) (baseURL, buildBaseDir string, loggerHook *logr

args := []string{
"-host", host,
"-port", port,
"-port", strconv.Itoa(port),
"-build-path", buildBaseDir,
}
go func() {
_ = main.Run(ctx, args, os.Getenv, logger)
}()

err := waitReady(ctx, defaultTimeout, baseURL)
err = waitReady(ctx, defaultTimeout, baseURL)
assert.NoError(t, err)

return baseURL, buildBaseDir, loggerHook
Expand Down

0 comments on commit 55c5602

Please sign in to comment.