■ ■ ■ ■ ■ ■
e2e/portforward/docker_test.go
| 1 | + | package portforward |
| 2 | + | |
| 3 | + | import ( |
| 4 | + | "encoding/json" |
| 5 | + | "strings" |
| 6 | + | "testing" |
| 7 | + | "time" |
| 8 | + | |
| 9 | + | "gotest.tools/assert" |
| 10 | + | "gotest.tools/poll" |
| 11 | + | "gotest.tools/v3/icmd" |
| 12 | + | ) |
| 13 | + | |
| 14 | + | const ( |
| 15 | + | imageNginx = "docker.io/library/nginx:1.23" |
| 16 | + | ) |
| 17 | + | |
| 18 | + | type forwarding struct { |
| 19 | + | LocalHost string `json:"localHost"` |
| 20 | + | LocalPort string `json:"localPort"` |
| 21 | + | RemoteHost string `json:"remoteHost"` |
| 22 | + | RemotePort string `json:"remotePort"` |
| 23 | + | } |
| 24 | + | |
| 25 | + | func TestPortForwardDockerRemotePort(t *testing.T) { |
| 26 | + | // Start target container. |
| 27 | + | targetID := runBackgroundNginx(t) |
| 28 | + | defer func() { removeContainer(t, targetID).Assert(t, icmd.Success) }() |
| 29 | + | |
| 30 | + | // Initiate port forwarding. |
| 31 | + | cmd := icmd.Command("cdebug", "port-forward", "-o", "json", targetID, "80") |
| 32 | + | res := icmd.StartCmd(cmd) |
| 33 | + | assert.NilError(t, res.Error) |
| 34 | + | defer func() { icmd.WaitOnCmd(cmd.Timeout, res).Assert(t, icmd.Success) }() |
| 35 | + | |
| 36 | + | // Wait until it's up and running. |
| 37 | + | var addr string |
| 38 | + | poll.WaitOn( |
| 39 | + | t, func(poll.LogT) poll.Result { |
| 40 | + | var fwds []forwarding |
| 41 | + | t.Log(res.Stdout()) |
| 42 | + | if json.Unmarshal([]byte(res.Stdout()), fwds) == nil && len(fwds) > 0 { |
| 43 | + | addr = fwds[0].LocalHost + ":" + fwds[0].LocalPort |
| 44 | + | return poll.Success() |
| 45 | + | } |
| 46 | + | |
| 47 | + | assert.NilError(t, res.Error) |
| 48 | + | return poll.Continue("waiting for `cdebug port-forward` to start up...") |
| 49 | + | }, |
| 50 | + | poll.WithDelay(500*time.Millisecond), |
| 51 | + | poll.WithTimeout(3*time.Second), |
| 52 | + | ) |
| 53 | + | |
| 54 | + | // Probe target through forwarded port. |
| 55 | + | t.Fatalf("not implemented: %s", addr) |
| 56 | + | } |
| 57 | + | |
| 58 | + | func runBackgroundNginx(t *testing.T) string { |
| 59 | + | res := icmd.RunCommand("docker", "run", "-d", imageNginx) |
| 60 | + | res.Assert(t, icmd.Success) |
| 61 | + | return strings.TrimSpace(res.Stdout()) |
| 62 | + | } |
| 63 | + | |
| 64 | + | func removeContainer(t *testing.T, id string) *icmd.Result { |
| 65 | + | return icmd.RunCommand("docker", "rm", id) |
| 66 | + | } |
| 67 | + | |