Quellcode durchsuchen

if address already in use in unit tests, try a different port

Victor Vieux vor 12 Jahren
Ursprung
Commit
2a53717e8f
1 geänderte Dateien mit 39 neuen und 10 gelöschten Zeilen
  1. 39 10
      runtime_test.go

+ 39 - 10
runtime_test.go

@@ -5,9 +5,12 @@ import (
 	"github.com/dotcloud/docker/utils"
 	"io"
 	"io/ioutil"
+	"log"
 	"net"
 	"os"
 	"os/user"
+	"strconv"
+	"strings"
 	"sync"
 	"testing"
 	"time"
@@ -277,24 +280,50 @@ func TestGet(t *testing.T) {
 
 }
 
-// Run a container with a TCP port allocated, and test that it can receive connections on localhost
-func TestAllocatePortLocalhost(t *testing.T) {
-	runtime, err := newTestRuntime()
-	if err != nil {
-		t.Fatal(err)
-	}
+func findAvailalblePort(runtime *Runtime, port int) (*Container, error) {
+	strPort := strconv.Itoa(port)
 	container, err := NewBuilder(runtime).Create(&Config{
 		Image:     GetTestImage(runtime).Id,
-		Cmd:       []string{"sh", "-c", "echo well hello there | nc -l -p 5555"},
-		PortSpecs: []string{"5555"},
+		Cmd:       []string{"sh", "-c", "echo well hello there | nc -l -p " + strPort},
+		PortSpecs: []string{strPort},
 	},
 	)
 	if err != nil {
-		t.Fatal(err)
+		return nil, err
 	}
 	if err := container.Start(); err != nil {
+		if strings.Contains(err.Error(), "address already in use") {
+			return nil, nil
+		}
+		return nil, err
+	}
+	return container, nil
+}
+
+// Run a container with a TCP port allocated, and test that it can receive connections on localhost
+func TestAllocatePortLocalhost(t *testing.T) {
+	runtime, err := newTestRuntime()
+	if err != nil {
 		t.Fatal(err)
 	}
+	port := 5554
+
+	var container *Container
+	for {
+		port += 1
+		log.Println("Trying port", port)
+		t.Log("Trying port", port)
+		container, err = findAvailalblePort(runtime, port)
+		if container != nil {
+			break
+		}
+		if err != nil {
+			t.Fatal(err)
+		}
+		log.Println("Port", port, "already in use")
+		t.Log("Port", port, "already in use")
+	}
+
 	defer container.Kill()
 
 	setTimeout(t, "Waiting for the container to be started timed out", 2*time.Second, func() {
@@ -308,7 +337,7 @@ func TestAllocatePortLocalhost(t *testing.T) {
 
 	conn, err := net.Dial("tcp",
 		fmt.Sprintf(
-			"localhost:%s", container.NetworkSettings.PortMapping["5555"],
+			"localhost:%s", container.NetworkSettings.PortMapping[strconv.Itoa(port)],
 		),
 	)
 	if err != nil {