Browse code

Add a test for allocating tcp ports and reaching them on localhost

Solomon Hykes authored on 2013/04/20 12:46:07
Showing 1 changed files
... ...
@@ -1,9 +1,11 @@
1 1
 package docker
2 2
 
3 3
 import (
4
+	"fmt"
4 5
 	"github.com/dotcloud/docker/rcli"
5 6
 	"io"
6 7
 	"io/ioutil"
8
+	"net"
7 9
 	"os"
8 10
 	"os/exec"
9 11
 	"os/user"
... ...
@@ -254,6 +256,47 @@ func TestGet(t *testing.T) {
254 254
 
255 255
 }
256 256
 
257
+// Run a container with a TCP port allocated, and test that it can receive connections on localhost
258
+func TestAllocatePortLocalhost(t *testing.T) {
259
+	runtime, err := newTestRuntime()
260
+	if err != nil {
261
+		t.Fatal(err)
262
+	}
263
+	container, err := runtime.Create(&Config{
264
+		Image:     GetTestImage(runtime).Id,
265
+		Cmd:       []string{"sh", "-c", "echo well hello there | nc -l -p 5555"},
266
+		PortSpecs: []string{"5555"},
267
+	},
268
+	)
269
+	if err != nil {
270
+		t.Fatal(err)
271
+	}
272
+	if err := container.Start(); err != nil {
273
+		t.Fatal(err)
274
+	}
275
+	defer container.Kill()
276
+	time.Sleep(300 * time.Millisecond) // Wait for the container to run
277
+	conn, err := net.Dial("tcp",
278
+		fmt.Sprintf(
279
+			"localhost:%s", container.NetworkSettings.PortMapping["5555"],
280
+		),
281
+	)
282
+	if err != nil {
283
+		t.Fatal(err)
284
+	}
285
+	defer conn.Close()
286
+	output, err := ioutil.ReadAll(conn)
287
+	if err != nil {
288
+		t.Fatal(err)
289
+	}
290
+	if string(output) != "well hello there\n" {
291
+		t.Fatalf("Received wrong output from network connection: should be '%s', not '%s'",
292
+			"well hello there\n",
293
+			string(output),
294
+		)
295
+	}
296
+}
297
+
257 298
 func TestRestore(t *testing.T) {
258 299
 
259 300
 	root, err := ioutil.TempDir("", "docker-test")