diff --git a/integration-cli/benchmark_test.go b/integration-cli/benchmark_test.go index 1f9fc2abcb..48521632a3 100644 --- a/integration-cli/benchmark_test.go +++ b/integration-cli/benchmark_test.go @@ -10,6 +10,7 @@ import ( "testing" "time" + "github.com/docker/docker/integration-cli/cli" "gotest.tools/v3/assert" ) @@ -108,7 +109,7 @@ func (s *DockerBenchmarkSuite) BenchmarkConcurrentContainerActions(c *testing.B) } func (s *DockerBenchmarkSuite) BenchmarkLogsCLIRotateFollow(c *testing.B) { - out, _ := dockerCmd(c, "run", "-d", "--log-opt", "max-size=1b", "--log-opt", "max-file=10", "busybox", "sh", "-c", "while true; do usleep 50000; echo hello; done") + out := cli.DockerCmd(c, "run", "-d", "--log-opt", "max-size=1b", "--log-opt", "max-file=10", "busybox", "sh", "-c", "while true; do usleep 50000; echo hello; done").Combined() id := strings.TrimSpace(out) ch := make(chan error, 1) go func() { diff --git a/integration-cli/docker_api_attach_test.go b/integration-cli/docker_api_attach_test.go index b77292db71..7dedb738a9 100644 --- a/integration-cli/docker_api_attach_test.go +++ b/integration-cli/docker_api_attach_test.go @@ -13,6 +13,7 @@ import ( "github.com/docker/docker/api/types" "github.com/docker/docker/api/types/container" "github.com/docker/docker/client" + "github.com/docker/docker/integration-cli/cli" "github.com/docker/docker/pkg/stdcopy" "github.com/docker/docker/testutil" "github.com/docker/docker/testutil/request" @@ -24,14 +25,14 @@ import ( ) func (s *DockerAPISuite) TestGetContainersAttachWebsocket(c *testing.T) { - out, _ := dockerCmd(c, "run", "-di", "busybox", "cat") + cid := cli.DockerCmd(c, "run", "-di", "busybox", "cat").Stdout() + cid = strings.TrimSpace(cid) rwc, err := request.SockConn(10*time.Second, request.DaemonHost()) assert.NilError(c, err) - cleanedContainerID := strings.TrimSpace(out) config, err := websocket.NewConfig( - "/containers/"+cleanedContainerID+"/attach/ws?stream=1&stdin=1&stdout=1&stderr=1", + "/containers/"+cid+"/attach/ws?stream=1&stdin=1&stdout=1&stderr=1", "http://localhost", ) assert.NilError(c, err) @@ -136,7 +137,7 @@ func (s *DockerAPISuite) TestPostContainersAttach(c *testing.T) { } // Create a container that only emits stdout. - cid, _ := dockerCmd(c, "run", "-di", "busybox", "cat") + cid := cli.DockerCmd(c, "run", "-di", "busybox", "cat").Stdout() cid = strings.TrimSpace(cid) // Attach to the container's stdout stream. @@ -152,7 +153,7 @@ func (s *DockerAPISuite) TestPostContainersAttach(c *testing.T) { expectTimeout(wc, br, "stdout") // Test the similar functions of the stderr stream. - cid, _ = dockerCmd(c, "run", "-di", "busybox", "/bin/sh", "-c", "cat >&2") + cid = cli.DockerCmd(c, "run", "-di", "busybox", "/bin/sh", "-c", "cat >&2").Stdout() cid = strings.TrimSpace(cid) wc, br, err = requestHijack(http.MethodPost, "/containers/"+cid+"/attach?stream=1&stdin=1&stderr=1", nil, "text/plain", request.DaemonHost()) assert.NilError(c, err) @@ -162,7 +163,7 @@ func (s *DockerAPISuite) TestPostContainersAttach(c *testing.T) { expectTimeout(wc, br, "stderr") // Test with tty. - cid, _ = dockerCmd(c, "run", "-dit", "busybox", "/bin/sh", "-c", "cat >&2") + cid = cli.DockerCmd(c, "run", "-dit", "busybox", "/bin/sh", "-c", "cat >&2").Stdout() cid = strings.TrimSpace(cid) // Attach to stdout only. wc, br, err = requestHijack(http.MethodPost, "/containers/"+cid+"/attach?stream=1&stdin=1&stdout=1", nil, "text/plain", request.DaemonHost()) @@ -181,7 +182,7 @@ func (s *DockerAPISuite) TestPostContainersAttach(c *testing.T) { assert.NilError(c, err) defer apiClient.Close() - cid, _ = dockerCmd(c, "run", "-di", "busybox", "/bin/sh", "-c", "echo hello; cat") + cid = cli.DockerCmd(c, "run", "-di", "busybox", "/bin/sh", "-c", "echo hello; cat").Stdout() cid = strings.TrimSpace(cid) // Make sure we don't see "hello" if Logs is false diff --git a/integration-cli/docker_api_containers_test.go b/integration-cli/docker_api_containers_test.go index 69bcc2fa35..c39835399d 100644 --- a/integration-cli/docker_api_containers_test.go +++ b/integration-cli/docker_api_containers_test.go @@ -38,18 +38,17 @@ import ( func (s *DockerAPISuite) TestContainerAPIGetAll(c *testing.T) { startCount := getContainerCount(c) - name := "getall" - dockerCmd(c, "run", "--name", name, "busybox", "true") + const name = "getall" + cli.DockerCmd(c, "run", "--name", name, "busybox", "true") apiClient, err := client.NewClientWithOpts(client.FromEnv) assert.NilError(c, err) defer apiClient.Close() - options := container.ListOptions{ - All: true, - } ctx := testutil.GetContext(c) - containers, err := apiClient.ContainerList(ctx, options) + containers, err := apiClient.ContainerList(ctx, container.ListOptions{ + All: true, + }) assert.NilError(c, err) assert.Equal(c, len(containers), startCount+1) actual := containers[0].Names[0] @@ -59,7 +58,7 @@ func (s *DockerAPISuite) TestContainerAPIGetAll(c *testing.T) { // regression test for empty json field being omitted #13691 func (s *DockerAPISuite) TestContainerAPIGetJSONNoFieldsOmitted(c *testing.T) { startCount := getContainerCount(c) - dockerCmd(c, "run", "busybox", "true") + cli.DockerCmd(c, "run", "busybox", "true") apiClient, err := client.NewClientWithOpts(client.FromEnv) assert.NilError(c, err) @@ -101,8 +100,8 @@ func (s *DockerAPISuite) TestContainerAPIGetJSONNoFieldsOmitted(c *testing.T) { func (s *DockerAPISuite) TestContainerAPIGetExport(c *testing.T) { // Not supported on Windows as Windows does not support docker export testRequires(c, DaemonIsLinux) - name := "exportcontainer" - dockerCmd(c, "run", "--name", name, "busybox", "touch", "/test") + const name = "exportcontainer" + cli.DockerCmd(c, "run", "--name", name, "busybox", "touch", "/test") apiClient, err := client.NewClientWithOpts(client.FromEnv) assert.NilError(c, err) @@ -128,8 +127,8 @@ func (s *DockerAPISuite) TestContainerAPIGetExport(c *testing.T) { func (s *DockerAPISuite) TestContainerAPIGetChanges(c *testing.T) { // Not supported on Windows as Windows does not support docker diff (/containers/name/changes) testRequires(c, DaemonIsLinux) - name := "changescontainer" - dockerCmd(c, "run", "--name", name, "busybox", "rm", "/etc/passwd") + const name = "changescontainer" + cli.DockerCmd(c, "run", "--name", name, "busybox", "rm", "/etc/passwd") apiClient, err := client.NewClientWithOpts(client.FromEnv) assert.NilError(c, err) @@ -170,7 +169,7 @@ func (s *DockerAPISuite) TestGetContainerStats(c *testing.T) { // allow some time to stream the stats from the container time.Sleep(4 * time.Second) - dockerCmd(c, "rm", "-f", name) + cli.DockerCmd(c, "rm", "-f", name) // collect the results from the stats stream or timeout and fail // if the stream was not disconnected. @@ -187,8 +186,7 @@ func (s *DockerAPISuite) TestGetContainerStats(c *testing.T) { } func (s *DockerAPISuite) TestGetContainerStatsRmRunning(c *testing.T) { - out := runSleepingContainer(c) - id := strings.TrimSpace(out) + id := runSleepingContainer(c) buf := &ChannelBuffer{C: make(chan []byte, 1)} defer buf.Close() @@ -218,7 +216,7 @@ func (s *DockerAPISuite) TestGetContainerStatsRmRunning(c *testing.T) { _, err = buf.ReadTimeout(b, 2*time.Second) assert.NilError(c, err) - dockerCmd(c, "rm", "-f", id) + cli.DockerCmd(c, "rm", "-f", id) assert.Assert(c, <-chErr == nil) } @@ -254,7 +252,7 @@ func (c *ChannelBuffer) ReadTimeout(p []byte, n time.Duration) (int, error) { // previous test was just checking one stat entry so it didn't fail (stats with // stream false always return one stat) func (s *DockerAPISuite) TestGetContainerStatsStream(c *testing.T) { - name := "statscontainer" + const name = "statscontainer" runSleepingContainer(c, "--name", name) type b struct { @@ -275,7 +273,7 @@ func (s *DockerAPISuite) TestGetContainerStatsStream(c *testing.T) { // allow some time to stream the stats from the container time.Sleep(4 * time.Second) - dockerCmd(c, "rm", "-f", name) + cli.DockerCmd(c, "rm", "-f", name) // collect the results from the stats stream or timeout and fail // if the stream was not disconnected. @@ -295,7 +293,7 @@ func (s *DockerAPISuite) TestGetContainerStatsStream(c *testing.T) { } func (s *DockerAPISuite) TestGetContainerStatsNoStream(c *testing.T) { - name := "statscontainer" + const name = "statscontainer2" runSleepingContainer(c, "--name", name) type b struct { @@ -317,7 +315,7 @@ func (s *DockerAPISuite) TestGetContainerStatsNoStream(c *testing.T) { // allow some time to stream the stats from the container time.Sleep(4 * time.Second) - dockerCmd(c, "rm", "-f", name) + cli.DockerCmd(c, "rm", "-f", name) // collect the results from the stats stream or timeout and fail // if the stream was not disconnected. @@ -335,8 +333,8 @@ func (s *DockerAPISuite) TestGetContainerStatsNoStream(c *testing.T) { } func (s *DockerAPISuite) TestGetStoppedContainerStats(c *testing.T) { - name := "statscontainer" - dockerCmd(c, "create", "--name", name, "busybox", "ps") + const name = "statscontainer3" + cli.DockerCmd(c, "create", "--name", name, "busybox", "ps") chResp := make(chan error, 1) @@ -394,9 +392,9 @@ func (s *DockerAPISuite) TestContainerAPIPause(c *testing.T) { func (s *DockerAPISuite) TestContainerAPITop(c *testing.T) { testRequires(c, DaemonIsLinux) - out, _ := dockerCmd(c, "run", "-d", "busybox", "/bin/sh", "-c", "top && true") + out := cli.DockerCmd(c, "run", "-d", "busybox", "/bin/sh", "-c", "top && true").Stdout() id := strings.TrimSpace(out) - assert.NilError(c, waitRun(id)) + cli.WaitRun(c, id) apiClient, err := client.NewClientWithOpts(client.FromEnv) assert.NilError(c, err) @@ -417,9 +415,8 @@ func (s *DockerAPISuite) TestContainerAPITop(c *testing.T) { func (s *DockerAPISuite) TestContainerAPITopWindows(c *testing.T) { testRequires(c, DaemonIsWindows) - out := runSleepingContainer(c, "-d") - id := strings.TrimSpace(out) - assert.NilError(c, waitRun(id)) + id := runSleepingContainer(c, "-d") + cli.WaitRun(c, id) apiClient, err := client.NewClientWithOpts(client.FromEnv) assert.NilError(c, err) @@ -447,8 +444,8 @@ func (s *DockerAPISuite) TestContainerAPITopWindows(c *testing.T) { } func (s *DockerAPISuite) TestContainerAPICommit(c *testing.T) { - cName := "testapicommit" - dockerCmd(c, "run", "--name="+cName, "busybox", "/bin/sh", "-c", "touch /test") + const cName = "testapicommit" + cli.DockerCmd(c, "run", "--name="+cName, "busybox", "/bin/sh", "-c", "touch /test") apiClient, err := client.NewClientWithOpts(client.FromEnv) assert.NilError(c, err) @@ -465,12 +462,12 @@ func (s *DockerAPISuite) TestContainerAPICommit(c *testing.T) { assert.Equal(c, cmd, "[/bin/sh -c touch /test]", fmt.Sprintf("got wrong Cmd from commit: %q", cmd)) // sanity check, make sure the image is what we think it is - dockerCmd(c, "run", img.ID, "ls", "/test") + cli.DockerCmd(c, "run", img.ID, "ls", "/test") } func (s *DockerAPISuite) TestContainerAPICommitWithLabelInConfig(c *testing.T) { - cName := "testapicommitwithconfig" - dockerCmd(c, "run", "--name="+cName, "busybox", "/bin/sh", "-c", "touch /test") + const cName = "testapicommitwithconfig" + cli.DockerCmd(c, "run", "--name="+cName, "busybox", "/bin/sh", "-c", "touch /test") apiClient, err := client.NewClientWithOpts(client.FromEnv) assert.NilError(c, err) @@ -498,7 +495,7 @@ func (s *DockerAPISuite) TestContainerAPICommitWithLabelInConfig(c *testing.T) { assert.Equal(c, cmd, "[/bin/sh -c touch /test]", fmt.Sprintf("got wrong Cmd from commit: %q", cmd)) // sanity check, make sure the image is what we think it is - dockerCmd(c, "run", img.ID, "ls", "/test") + cli.DockerCmd(c, "run", img.ID, "ls", "/test") } func (s *DockerAPISuite) TestContainerAPIBadPort(c *testing.T) { @@ -542,7 +539,7 @@ func (s *DockerAPISuite) TestContainerAPICreate(c *testing.T) { ctr, err := apiClient.ContainerCreate(testutil.GetContext(c), &config, &container.HostConfig{}, &network.NetworkingConfig{}, nil, "") assert.NilError(c, err) - out, _ := dockerCmd(c, "start", "-a", ctr.ID) + out := cli.DockerCmd(c, "start", "-a", ctr.ID).Stdout() assert.Equal(c, strings.TrimSpace(out), "/test") } @@ -848,10 +845,9 @@ func (s *DockerAPISuite) TestCreateWithTooLowMemoryLimit(c *testing.T) { } func (s *DockerAPISuite) TestContainerAPIRename(c *testing.T) { - out, _ := dockerCmd(c, "run", "--name", "TestContainerAPIRename", "-d", "busybox", "sh") - + out := cli.DockerCmd(c, "run", "--name", "TestContainerAPIRename", "-d", "busybox", "sh").Stdout() containerID := strings.TrimSpace(out) - newName := "TestContainerAPIRenameNew" + const newName = "TestContainerAPIRenameNew" apiClient, err := client.NewClientWithOpts(client.FromEnv) assert.NilError(c, err) @@ -865,7 +861,7 @@ func (s *DockerAPISuite) TestContainerAPIRename(c *testing.T) { } func (s *DockerAPISuite) TestContainerAPIKill(c *testing.T) { - name := "test-api-kill" + const name = "test-api-kill" runSleepingContainer(c, "-i", "--name", name) apiClient, err := client.NewClientWithOpts(client.FromEnv) @@ -880,7 +876,7 @@ func (s *DockerAPISuite) TestContainerAPIKill(c *testing.T) { } func (s *DockerAPISuite) TestContainerAPIRestart(c *testing.T) { - name := "test-api-restart" + const name = "test-api-restart" runSleepingContainer(c, "-di", "--name", name) apiClient, err := client.NewClientWithOpts(client.FromEnv) assert.NilError(c, err) @@ -894,10 +890,9 @@ func (s *DockerAPISuite) TestContainerAPIRestart(c *testing.T) { } func (s *DockerAPISuite) TestContainerAPIRestartNotimeoutParam(c *testing.T) { - name := "test-api-restart-no-timeout-param" - out := runSleepingContainer(c, "-di", "--name", name) - id := strings.TrimSpace(out) - assert.NilError(c, waitRun(id)) + const name = "test-api-restart-no-timeout-param" + id := runSleepingContainer(c, "-di", "--name", name) + cli.WaitRun(c, id) apiClient, err := client.NewClientWithOpts(client.FromEnv) assert.NilError(c, err) @@ -910,7 +905,7 @@ func (s *DockerAPISuite) TestContainerAPIRestartNotimeoutParam(c *testing.T) { } func (s *DockerAPISuite) TestContainerAPIStart(c *testing.T) { - name := "testing-start" + const name = "testing-start" config := container.Config{ Image: "busybox", Cmd: append([]string{"/bin/sh", "-c"}, sleepCommandForDaemonPlatform()...), @@ -936,7 +931,7 @@ func (s *DockerAPISuite) TestContainerAPIStart(c *testing.T) { } func (s *DockerAPISuite) TestContainerAPIStop(c *testing.T) { - name := "test-api-stop" + const name = "test-api-stop" runSleepingContainer(c, "-i", "--name", name) timeout := 30 @@ -959,13 +954,13 @@ func (s *DockerAPISuite) TestContainerAPIStop(c *testing.T) { } func (s *DockerAPISuite) TestContainerAPIWait(c *testing.T) { - name := "test-api-wait" + const name = "test-api-wait" sleepCmd := "/bin/sleep" if testEnv.DaemonInfo.OSType == "windows" { sleepCmd = "sleep" } - dockerCmd(c, "run", "--name", name, "busybox", sleepCmd, "2") + cli.DockerCmd(c, "run", "--name", name, "busybox", sleepCmd, "2") apiClient, err := client.NewClientWithOpts(client.FromEnv) assert.NilError(c, err) @@ -982,8 +977,8 @@ func (s *DockerAPISuite) TestContainerAPIWait(c *testing.T) { } func (s *DockerAPISuite) TestContainerAPICopyNotExistsAnyMore(c *testing.T) { - name := "test-container-api-copy" - dockerCmd(c, "run", "--name", name, "busybox", "touch", "/test.txt") + const name = "test-container-api-copy" + cli.DockerCmd(c, "run", "--name", name, "busybox", "touch", "/test.txt") postData := types.CopyConfig{ Resource: "/test.txt", @@ -996,8 +991,8 @@ func (s *DockerAPISuite) TestContainerAPICopyNotExistsAnyMore(c *testing.T) { func (s *DockerAPISuite) TestContainerAPICopyPre124(c *testing.T) { testRequires(c, DaemonIsLinux) // Windows only supports 1.25 or later - name := "test-container-api-copy" - dockerCmd(c, "run", "--name", name, "busybox", "touch", "/test.txt") + const name = "test-container-api-copy" + cli.DockerCmd(c, "run", "--name", name, "busybox", "touch", "/test.txt") postData := types.CopyConfig{ Resource: "/test.txt", @@ -1026,8 +1021,8 @@ func (s *DockerAPISuite) TestContainerAPICopyPre124(c *testing.T) { func (s *DockerAPISuite) TestContainerAPICopyResourcePathEmptyPre124(c *testing.T) { testRequires(c, DaemonIsLinux) // Windows only supports 1.25 or later - name := "test-container-api-copy-resource-empty" - dockerCmd(c, "run", "--name", name, "busybox", "touch", "/test.txt") + const name = "test-container-api-copy-resource-empty" + cli.DockerCmd(c, "run", "--name", name, "busybox", "touch", "/test.txt") postData := types.CopyConfig{ Resource: "", @@ -1047,8 +1042,8 @@ func (s *DockerAPISuite) TestContainerAPICopyResourcePathEmptyPre124(c *testing. func (s *DockerAPISuite) TestContainerAPICopyResourcePathNotFoundPre124(c *testing.T) { testRequires(c, DaemonIsLinux) // Windows only supports 1.25 or later - name := "test-container-api-copy-resource-not-found" - dockerCmd(c, "run", "--name", name, "busybox") + const name = "test-container-api-copy-resource-not-found" + cli.DockerCmd(c, "run", "--name", name, "busybox") postData := types.CopyConfig{ Resource: "/notexist", @@ -1078,12 +1073,9 @@ func (s *DockerAPISuite) TestContainerAPICopyContainerNotFoundPr124(c *testing.T } func (s *DockerAPISuite) TestContainerAPIDelete(c *testing.T) { - out := runSleepingContainer(c) - - id := strings.TrimSpace(out) - assert.NilError(c, waitRun(id)) - - dockerCmd(c, "stop", id) + id := runSleepingContainer(c) + cli.WaitRun(c, id) + cli.DockerCmd(c, "stop", id) apiClient, err := client.NewClientWithOpts(client.FromEnv) assert.NilError(c, err) @@ -1103,9 +1095,8 @@ func (s *DockerAPISuite) TestContainerAPIDeleteNotExist(c *testing.T) { } func (s *DockerAPISuite) TestContainerAPIDeleteForce(c *testing.T) { - out := runSleepingContainer(c) - id := strings.TrimSpace(out) - assert.NilError(c, waitRun(id)) + id := runSleepingContainer(c) + cli.WaitRun(c, id) removeOptions := container.RemoveOptions{ Force: true, @@ -1122,15 +1113,13 @@ func (s *DockerAPISuite) TestContainerAPIDeleteForce(c *testing.T) { func (s *DockerAPISuite) TestContainerAPIDeleteRemoveLinks(c *testing.T) { // Windows does not support links testRequires(c, DaemonIsLinux) - out, _ := dockerCmd(c, "run", "-d", "--name", "tlink1", "busybox", "top") - + out := cli.DockerCmd(c, "run", "-d", "--name", "tlink1", "busybox", "top").Stdout() id := strings.TrimSpace(out) - assert.NilError(c, waitRun(id)) - - out, _ = dockerCmd(c, "run", "--link", "tlink1:tlink1", "--name", "tlink2", "-d", "busybox", "top") + cli.WaitRun(c, id) + out = cli.DockerCmd(c, "run", "--link", "tlink1:tlink1", "--name", "tlink2", "-d", "busybox", "top").Stdout() id2 := strings.TrimSpace(out) - assert.Assert(c, waitRun(id2) == nil) + cli.WaitRun(c, id2) links := inspectFieldJSON(c, id2, "HostConfig.Links") assert.Equal(c, links, `["/tlink1:/tlink2/tlink1"]`, "expected to have links between containers") @@ -1158,10 +1147,8 @@ func (s *DockerAPISuite) TestContainerAPIDeleteRemoveVolume(c *testing.T) { vol = `c:\testvolume` } - out := runSleepingContainer(c, "-v", vol) - - id := strings.TrimSpace(out) - assert.NilError(c, waitRun(id)) + id := runSleepingContainer(c, "-v", vol) + cli.WaitRun(c, id) source, err := inspectMountSourceField(id, vol) assert.NilError(c, err) @@ -1205,10 +1192,8 @@ func (s *DockerAPISuite) TestContainerAPIChunkedEncoding(c *testing.T) { } func (s *DockerAPISuite) TestContainerAPIPostContainerStop(c *testing.T) { - out := runSleepingContainer(c) - - containerID := strings.TrimSpace(out) - assert.Assert(c, waitRun(containerID) == nil) + containerID := runSleepingContainer(c) + cli.WaitRun(c, containerID) apiClient, err := client.NewClientWithOpts(client.FromEnv) assert.NilError(c, err) @@ -1233,7 +1218,7 @@ func (s *DockerAPISuite) TestPostContainerAPICreateWithStringOrSliceEntrypoint(c _, err = apiClient.ContainerCreate(testutil.GetContext(c), &config, &container.HostConfig{}, &network.NetworkingConfig{}, nil, "echotest") assert.NilError(c, err) - out, _ := dockerCmd(c, "start", "-a", "echotest") + out := cli.DockerCmd(c, "start", "-a", "echotest").Combined() assert.Equal(c, strings.TrimSpace(out), "hello world") config2 := struct { @@ -1243,7 +1228,7 @@ func (s *DockerAPISuite) TestPostContainerAPICreateWithStringOrSliceEntrypoint(c }{"busybox", "echo", []string{"hello", "world"}} _, _, err = request.Post(testutil.GetContext(c), "/containers/create?name=echotest2", request.JSONBody(config2)) assert.NilError(c, err) - out, _ = dockerCmd(c, "start", "-a", "echotest2") + out = cli.DockerCmd(c, "start", "-a", "echotest2").Combined() assert.Equal(c, strings.TrimSpace(out), "hello world") } @@ -1260,7 +1245,7 @@ func (s *DockerAPISuite) TestPostContainersCreateWithStringOrSliceCmd(c *testing _, err = apiClient.ContainerCreate(testutil.GetContext(c), &config, &container.HostConfig{}, &network.NetworkingConfig{}, nil, "echotest") assert.NilError(c, err) - out, _ := dockerCmd(c, "start", "-a", "echotest") + out := cli.DockerCmd(c, "start", "-a", "echotest").Combined() assert.Equal(c, strings.TrimSpace(out), "hello world") config2 := struct { @@ -1270,7 +1255,7 @@ func (s *DockerAPISuite) TestPostContainersCreateWithStringOrSliceCmd(c *testing }{"busybox", "echo", "hello world"} _, _, err = request.Post(testutil.GetContext(c), "/containers/create?name=echotest2", request.JSONBody(config2)) assert.NilError(c, err) - out, _ = dockerCmd(c, "start", "-a", "echotest2") + out = cli.DockerCmd(c, "start", "-a", "echotest2").Combined() assert.Equal(c, strings.TrimSpace(out), "hello world") } @@ -1364,7 +1349,7 @@ func (s *DockerAPISuite) TestPostContainersCreateWithWrongCpusetValues(c *testin CpusetCpus: "1-42,,", }, } - name := "wrong-cpuset-cpus" + const name = "wrong-cpuset-cpus" _, err = apiClient.ContainerCreate(testutil.GetContext(c), &config, &hostConfig1, &network.NetworkingConfig{}, nil, name) expected := "Invalid value 1-42,, for cpuset cpus" @@ -1375,8 +1360,8 @@ func (s *DockerAPISuite) TestPostContainersCreateWithWrongCpusetValues(c *testin CpusetMems: "42-3,1--", }, } - name = "wrong-cpuset-mems" - _, err = apiClient.ContainerCreate(testutil.GetContext(c), &config, &hostConfig2, &network.NetworkingConfig{}, nil, name) + const name2 = "wrong-cpuset-mems" + _, err = apiClient.ContainerCreate(testutil.GetContext(c), &config, &hostConfig2, &network.NetworkingConfig{}, nil, name2) expected = "Invalid value 42-3,1-- for cpuset mems" assert.ErrorContains(c, err, expected) } @@ -1420,7 +1405,7 @@ func (s *DockerAPISuite) TestPostContainersCreateShmSizeHostConfigOmitted(c *tes assert.Equal(c, containerJSON.HostConfig.ShmSize, dconfig.DefaultShmSize) - out, _ := dockerCmd(c, "start", "-i", containerJSON.ID) + out := cli.DockerCmd(c, "start", "-i", containerJSON.ID).Combined() shmRegexp := regexp.MustCompile(`shm on /dev/shm type tmpfs(.*)size=65536k`) if !shmRegexp.MatchString(out) { c.Fatalf("Expected shm of 64MB in mount command, got %v", out) @@ -1447,7 +1432,7 @@ func (s *DockerAPISuite) TestPostContainersCreateShmSizeOmitted(c *testing.T) { assert.Equal(c, containerJSON.HostConfig.ShmSize, int64(67108864)) - out, _ := dockerCmd(c, "start", "-i", containerJSON.ID) + out := cli.DockerCmd(c, "start", "-i", containerJSON.ID).Combined() shmRegexp := regexp.MustCompile(`shm on /dev/shm type tmpfs(.*)size=65536k`) if !shmRegexp.MatchString(out) { c.Fatalf("Expected shm of 64MB in mount command, got %v", out) @@ -1478,7 +1463,7 @@ func (s *DockerAPISuite) TestPostContainersCreateWithShmSize(c *testing.T) { assert.Equal(c, containerJSON.HostConfig.ShmSize, int64(1073741824)) - out, _ := dockerCmd(c, "start", "-i", containerJSON.ID) + out := cli.DockerCmd(c, "start", "-i", containerJSON.ID).Combined() shmRegex := regexp.MustCompile(`shm on /dev/shm type tmpfs(.*)size=1048576k`) if !shmRegex.MatchString(out) { c.Fatalf("Expected shm of 1GB in mount command, got %v", out) @@ -1526,7 +1511,7 @@ func (s *DockerAPISuite) TestPostContainersCreateWithOomScoreAdjInvalidRange(c * assert.NilError(c, err) defer apiClient.Close() - name := "oomscoreadj-over" + const name = "oomscoreadj-over" _, err = apiClient.ContainerCreate(testutil.GetContext(c), &config, &hostConfig, &network.NetworkingConfig{}, nil, name) expected := "Invalid value 1001, range for oom score adj is [-1000, 1000]" @@ -1536,8 +1521,8 @@ func (s *DockerAPISuite) TestPostContainersCreateWithOomScoreAdjInvalidRange(c * OomScoreAdj: -1001, } - name = "oomscoreadj-low" - _, err = apiClient.ContainerCreate(testutil.GetContext(c), &config, &hostConfig, &network.NetworkingConfig{}, nil, name) + const name2 = "oomscoreadj-low" + _, err = apiClient.ContainerCreate(testutil.GetContext(c), &config, &hostConfig, &network.NetworkingConfig{}, nil, name2) expected = "Invalid value -1001, range for oom score adj is [-1000, 1000]" assert.ErrorContains(c, err, expected) @@ -1557,7 +1542,7 @@ func (s *DockerAPISuite) TestContainerAPIStatsWithNetworkDisabled(c *testing.T) // Problematic on Windows as Windows does not support stats testRequires(c, DaemonIsLinux) - name := "testing-network-disabled" + const name = "testing-network-disabled" config := container.Config{ Image: "busybox", @@ -1574,8 +1559,7 @@ func (s *DockerAPISuite) TestContainerAPIStatsWithNetworkDisabled(c *testing.T) err = apiClient.ContainerStart(testutil.GetContext(c), name, container.StartOptions{}) assert.NilError(c, err) - - assert.Assert(c, waitRun(name) == nil) + cli.WaitRun(c, name) type b struct { stats types.ContainerStats @@ -1589,7 +1573,7 @@ func (s *DockerAPISuite) TestContainerAPIStatsWithNetworkDisabled(c *testing.T) // allow some time to stream the stats from the container time.Sleep(4 * time.Second) - dockerCmd(c, "rm", "-f", name) + cli.DockerCmd(c, "rm", "-f", name) // collect the results from the stats stream or timeout and fail // if the stream was not disconnected. @@ -1943,7 +1927,7 @@ func (s *DockerAPISuite) TestContainerAPICreateMountsBindRead(c *testing.T) { _, err = apiClient.ContainerCreate(testutil.GetContext(c), &config, &hostConfig, &network.NetworkingConfig{}, nil, "test") assert.NilError(c, err) - out, _ := dockerCmd(c, "start", "-a", "test") + out := cli.DockerCmd(c, "start", "-a", "test").Combined() assert.Equal(c, out, "hello") } @@ -2197,7 +2181,7 @@ func (s *DockerAPISuite) TestContainersAPICreateMountsTmpfs(c *testing.T) { _, err = apiClient.ContainerCreate(testutil.GetContext(c), &config, &hostConfig, &network.NetworkingConfig{}, nil, cName) assert.NilError(c, err) - out, _ := dockerCmd(c, "start", "-a", cName) + out := cli.DockerCmd(c, "start", "-a", cName).Combined() for _, option := range x.expectedOptions { assert.Assert(c, strings.Contains(out, option)) } diff --git a/integration-cli/docker_api_exec_resize_test.go b/integration-cli/docker_api_exec_resize_test.go index c1d5edf2fd..d722a877b5 100644 --- a/integration-cli/docker_api_exec_resize_test.go +++ b/integration-cli/docker_api_exec_resize_test.go @@ -11,6 +11,7 @@ import ( "testing" "github.com/docker/docker/api/types/versions" + "github.com/docker/docker/integration-cli/cli" "github.com/docker/docker/testutil" "github.com/docker/docker/testutil/request" "github.com/pkg/errors" @@ -19,7 +20,7 @@ import ( func (s *DockerAPISuite) TestExecResizeAPIHeightWidthNoInt(c *testing.T) { testRequires(c, DaemonIsLinux) - out, _ := dockerCmd(c, "run", "-d", "busybox", "top") + out := cli.DockerCmd(c, "run", "-d", "busybox", "top").Stdout() cleanedContainerID := strings.TrimSpace(out) endpoint := "/exec/" + cleanedContainerID + "/resize?h=foo&w=bar" @@ -35,7 +36,7 @@ func (s *DockerAPISuite) TestExecResizeAPIHeightWidthNoInt(c *testing.T) { // Part of #14845 func (s *DockerAPISuite) TestExecResizeImmediatelyAfterExecStart(c *testing.T) { name := "exec_resize_test" - dockerCmd(c, "run", "-d", "-i", "-t", "--name", name, "--restart", "always", "busybox", "/bin/sh") + cli.DockerCmd(c, "run", "-d", "-i", "-t", "--name", name, "--restart", "always", "busybox", "/bin/sh") testExecResize := func() error { data := map[string]interface{}{ diff --git a/integration-cli/docker_api_exec_test.go b/integration-cli/docker_api_exec_test.go index 6a015e6645..00c333c4ce 100644 --- a/integration-cli/docker_api_exec_test.go +++ b/integration-cli/docker_api_exec_test.go @@ -16,6 +16,7 @@ import ( "github.com/docker/docker/api/types/versions" "github.com/docker/docker/client" "github.com/docker/docker/integration-cli/checker" + "github.com/docker/docker/integration-cli/cli" "github.com/docker/docker/testutil" "github.com/docker/docker/testutil/request" "gotest.tools/v3/assert" @@ -26,7 +27,7 @@ import ( // Regression test for #9414 func (s *DockerAPISuite) TestExecAPICreateNoCmd(c *testing.T) { name := "exec_test" - dockerCmd(c, "run", "-d", "-t", "--name", name, "busybox", "/bin/sh") + cli.DockerCmd(c, "run", "-d", "-t", "--name", name, "busybox", "/bin/sh") res, body, err := request.Post(testutil.GetContext(c), fmt.Sprintf("/containers/%s/exec", name), request.JSONBody(map[string]interface{}{"Cmd": nil})) assert.NilError(c, err) @@ -42,7 +43,7 @@ func (s *DockerAPISuite) TestExecAPICreateNoCmd(c *testing.T) { func (s *DockerAPISuite) TestExecAPICreateNoValidContentType(c *testing.T) { name := "exec_test" - dockerCmd(c, "run", "-d", "-t", "--name", name, "busybox", "/bin/sh") + cli.DockerCmd(c, "run", "-d", "-t", "--name", name, "busybox", "/bin/sh") jsonData := bytes.NewBuffer(nil) if err := json.NewEncoder(jsonData).Encode(map[string]interface{}{"Cmd": nil}); err != nil { @@ -65,9 +66,9 @@ func (s *DockerAPISuite) TestExecAPICreateContainerPaused(c *testing.T) { // Not relevant on Windows as Windows containers cannot be paused testRequires(c, DaemonIsLinux) name := "exec_create_test" - dockerCmd(c, "run", "-d", "-t", "--name", name, "busybox", "/bin/sh") + cli.DockerCmd(c, "run", "-d", "-t", "--name", name, "busybox", "/bin/sh") - dockerCmd(c, "pause", name) + cli.DockerCmd(c, "pause", name) apiClient, err := client.NewClientWithOpts(client.FromEnv) assert.NilError(c, err) @@ -82,7 +83,7 @@ func (s *DockerAPISuite) TestExecAPICreateContainerPaused(c *testing.T) { func (s *DockerAPISuite) TestExecAPIStart(c *testing.T) { testRequires(c, DaemonIsLinux) // Uses pause/unpause but bits may be salvageable to Windows to Windows CI - dockerCmd(c, "run", "-d", "--name", "test", "busybox", "top") + cli.DockerCmd(c, "run", "-d", "--name", "test", "busybox", "top") id := createExec(c, "test") startExec(c, id, http.StatusOK) @@ -92,24 +93,24 @@ func (s *DockerAPISuite) TestExecAPIStart(c *testing.T) { assert.Assert(c, execJSON.PID > 1) id = createExec(c, "test") - dockerCmd(c, "stop", "test") + cli.DockerCmd(c, "stop", "test") startExec(c, id, http.StatusNotFound) - dockerCmd(c, "start", "test") + cli.DockerCmd(c, "start", "test") startExec(c, id, http.StatusNotFound) // make sure exec is created before pausing id = createExec(c, "test") - dockerCmd(c, "pause", "test") + cli.DockerCmd(c, "pause", "test") startExec(c, id, http.StatusConflict) - dockerCmd(c, "unpause", "test") + cli.DockerCmd(c, "unpause", "test") startExec(c, id, http.StatusOK) } func (s *DockerAPISuite) TestExecAPIStartEnsureHeaders(c *testing.T) { testRequires(c, DaemonIsLinux) - dockerCmd(c, "run", "-d", "--name", "test", "busybox", "top") + cli.DockerCmd(c, "run", "-d", "--name", "test", "busybox", "top") id := createExec(c, "test") resp, _, err := request.Post(testutil.GetContext(c), fmt.Sprintf("/exec/%s/start", id), request.RawString(`{"Detach": true}`), request.JSON) @@ -177,7 +178,7 @@ func (s *DockerAPISuite) TestExecAPIStartWithDetach(c *testing.T) { // #30311 func (s *DockerAPISuite) TestExecAPIStartValidCommand(c *testing.T) { name := "exec_test" - dockerCmd(c, "run", "-d", "-t", "--name", name, "busybox", "/bin/sh") + cli.DockerCmd(c, "run", "-d", "-t", "--name", name, "busybox", "/bin/sh") id := createExecCmd(c, name, "true") startExec(c, id, http.StatusOK) @@ -194,7 +195,7 @@ func (s *DockerAPISuite) TestExecAPIStartValidCommand(c *testing.T) { // #30311 func (s *DockerAPISuite) TestExecAPIStartInvalidCommand(c *testing.T) { name := "exec_test" - dockerCmd(c, "run", "-d", "-t", "--name", name, "busybox", "/bin/sh") + cli.DockerCmd(c, "run", "-d", "-t", "--name", name, "busybox", "/bin/sh") id := createExecCmd(c, name, "invalid") if versions.LessThan(testEnv.DaemonAPIVersion(), "1.32") { @@ -217,7 +218,7 @@ func (s *DockerAPISuite) TestExecStateCleanup(c *testing.T) { // This test checks accidental regressions. Not part of stable API. name := "exec_cleanup" - cid, _ := dockerCmd(c, "run", "-d", "-t", "--name", name, "busybox", "/bin/sh") + cid := cli.DockerCmd(c, "run", "-d", "-t", "--name", name, "busybox", "/bin/sh").Stdout() cid = strings.TrimSpace(cid) stateDir := "/var/run/docker/containerd/" + cid @@ -246,7 +247,7 @@ func (s *DockerAPISuite) TestExecStateCleanup(c *testing.T) { poll.WaitOn(c, pollCheck(c, checkReadDir, checker.Equals(len(fi))), poll.WithTimeout(5*time.Second)) - dockerCmd(c, "stop", name) + cli.DockerCmd(c, "stop", name) _, err = os.Stat(stateDir) assert.ErrorContains(c, err, "") assert.Assert(c, os.IsNotExist(err)) diff --git a/integration-cli/docker_api_images_test.go b/integration-cli/docker_api_images_test.go index 8846761c84..b75cb79b26 100644 --- a/integration-cli/docker_api_images_test.go +++ b/integration-cli/docker_api_images_test.go @@ -26,7 +26,7 @@ func (s *DockerAPISuite) TestAPIImagesSaveAndLoad(c *testing.T) { defer body.Close() assert.Equal(c, res.StatusCode, http.StatusOK) - dockerCmd(c, "rmi", id) + cli.DockerCmd(c, "rmi", id) res, loadBody, err := request.Post(ctx, "/images/load", request.RawContent(body), request.ContentType("application/x-tar")) assert.NilError(c, err) @@ -49,7 +49,7 @@ func (s *DockerAPISuite) TestAPIImagesDelete(c *testing.T) { buildImageSuccessfully(c, name, build.WithDockerfile("FROM busybox\nENV FOO bar")) id := getIDByName(c, name) - dockerCmd(c, "tag", name, "test:tag1") + cli.DockerCmd(c, "tag", name, "test:tag1") _, err = apiClient.ImageRemove(testutil.GetContext(c), id, types.ImageRemoveOptions{}) assert.ErrorContains(c, err, "unable to delete") diff --git a/integration-cli/docker_api_inspect_test.go b/integration-cli/docker_api_inspect_test.go index a946afe404..c8f410d366 100644 --- a/integration-cli/docker_api_inspect_test.go +++ b/integration-cli/docker_api_inspect_test.go @@ -8,15 +8,16 @@ import ( "github.com/docker/docker/api/types" "github.com/docker/docker/api/types/versions/v1p20" "github.com/docker/docker/client" + "github.com/docker/docker/integration-cli/cli" "github.com/docker/docker/testutil" "gotest.tools/v3/assert" is "gotest.tools/v3/assert/cmp" ) func (s *DockerAPISuite) TestInspectAPIContainerResponse(c *testing.T) { - out, _ := dockerCmd(c, "run", "-d", "busybox", "true") - + out := cli.DockerCmd(c, "run", "-d", "busybox", "true").Stdout() cleanedContainerID := strings.TrimSpace(out) + keysBase := []string{ "Id", "State", "Created", "Path", "Args", "Config", "Image", "NetworkSettings", "ResolvConfPath", "HostnamePath", "HostsPath", "LogPath", "Name", "Driver", "MountLabel", "ProcessLabel", "GraphDriver", @@ -61,8 +62,7 @@ func (s *DockerAPISuite) TestInspectAPIContainerResponse(c *testing.T) { func (s *DockerAPISuite) TestInspectAPIContainerVolumeDriverLegacy(c *testing.T) { // No legacy implications for Windows testRequires(c, DaemonIsLinux) - out, _ := dockerCmd(c, "run", "-d", "busybox", "true") - + out := cli.DockerCmd(c, "run", "-d", "busybox", "true").Stdout() cleanedContainerID := strings.TrimSpace(out) cases := []string{"v1.19", "v1.20"} @@ -82,8 +82,7 @@ func (s *DockerAPISuite) TestInspectAPIContainerVolumeDriverLegacy(c *testing.T) } func (s *DockerAPISuite) TestInspectAPIContainerVolumeDriver(c *testing.T) { - out, _ := dockerCmd(c, "run", "-d", "--volume-driver", "local", "busybox", "true") - + out := cli.DockerCmd(c, "run", "-d", "--volume-driver", "local", "busybox", "true").Stdout() cleanedContainerID := strings.TrimSpace(out) body := getInspectBody(c, "v1.25", cleanedContainerID) @@ -106,7 +105,7 @@ func (s *DockerAPISuite) TestInspectAPIContainerVolumeDriver(c *testing.T) { } func (s *DockerAPISuite) TestInspectAPIImageResponse(c *testing.T) { - dockerCmd(c, "tag", "busybox:latest", "busybox:mytag") + cli.DockerCmd(c, "tag", "busybox:latest", "busybox:mytag") apiClient, err := client.NewClientWithOpts(client.FromEnv) assert.NilError(c, err) defer apiClient.Close() @@ -123,8 +122,7 @@ func (s *DockerAPISuite) TestInspectAPIImageResponse(c *testing.T) { func (s *DockerAPISuite) TestInspectAPIEmptyFieldsInConfigPre121(c *testing.T) { // Not relevant on Windows testRequires(c, DaemonIsLinux) - out, _ := dockerCmd(c, "run", "-d", "busybox", "true") - + out := cli.DockerCmd(c, "run", "-d", "busybox", "true").Stdout() cleanedContainerID := strings.TrimSpace(out) cases := []string{"v1.19", "v1.20"} @@ -147,9 +145,9 @@ func (s *DockerAPISuite) TestInspectAPIEmptyFieldsInConfigPre121(c *testing.T) { func (s *DockerAPISuite) TestInspectAPIBridgeNetworkSettings120(c *testing.T) { // Not relevant on Windows, and besides it doesn't have any bridge network settings testRequires(c, DaemonIsLinux) - out, _ := dockerCmd(c, "run", "-d", "busybox", "top") + out := cli.DockerCmd(c, "run", "-d", "busybox", "top").Stdout() containerID := strings.TrimSpace(out) - waitRun(containerID) + cli.WaitRun(c, containerID) body := getInspectBody(c, "v1.20", containerID) @@ -164,9 +162,9 @@ func (s *DockerAPISuite) TestInspectAPIBridgeNetworkSettings120(c *testing.T) { func (s *DockerAPISuite) TestInspectAPIBridgeNetworkSettings121(c *testing.T) { // Windows doesn't have any bridge network settings testRequires(c, DaemonIsLinux) - out, _ := dockerCmd(c, "run", "-d", "busybox", "top") + out := cli.DockerCmd(c, "run", "-d", "busybox", "top").Stdout() containerID := strings.TrimSpace(out) - waitRun(containerID) + cli.WaitRun(c, containerID) body := getInspectBody(c, "v1.21", containerID) diff --git a/integration-cli/docker_api_logs_test.go b/integration-cli/docker_api_logs_test.go index dc3c60b648..3f83ae1e86 100644 --- a/integration-cli/docker_api_logs_test.go +++ b/integration-cli/docker_api_logs_test.go @@ -13,6 +13,7 @@ import ( "github.com/docker/docker/api/types/container" "github.com/docker/docker/client" + "github.com/docker/docker/integration-cli/cli" "github.com/docker/docker/pkg/stdcopy" "github.com/docker/docker/testutil" "github.com/docker/docker/testutil/request" @@ -20,9 +21,9 @@ import ( ) func (s *DockerAPISuite) TestLogsAPIWithStdout(c *testing.T) { - out, _ := dockerCmd(c, "run", "-d", "-t", "busybox", "/bin/sh", "-c", "while true; do echo hello; sleep 1; done") + out := cli.DockerCmd(c, "run", "-d", "-t", "busybox", "/bin/sh", "-c", "while true; do echo hello; sleep 1; done").Stdout() id := strings.TrimSpace(out) - assert.NilError(c, waitRun(id)) + cli.WaitRun(c, id) type logOut struct { out string @@ -56,8 +57,8 @@ func (s *DockerAPISuite) TestLogsAPIWithStdout(c *testing.T) { } func (s *DockerAPISuite) TestLogsAPINoStdoutNorStderr(c *testing.T) { - name := "logs_test" - dockerCmd(c, "run", "-d", "-t", "--name", name, "busybox", "/bin/sh") + const name = "logs_test" + cli.DockerCmd(c, "run", "-d", "-t", "--name", name, "busybox", "/bin/sh") apiClient, err := client.NewClientWithOpts(client.FromEnv) assert.NilError(c, err) defer apiClient.Close() @@ -68,9 +69,9 @@ func (s *DockerAPISuite) TestLogsAPINoStdoutNorStderr(c *testing.T) { // Regression test for #12704 func (s *DockerAPISuite) TestLogsAPIFollowEmptyOutput(c *testing.T) { - name := "logs_test" + const name = "logs_test" t0 := time.Now() - dockerCmd(c, "run", "-d", "-t", "--name", name, "busybox", "sleep", "10") + cli.DockerCmd(c, "run", "-d", "-t", "--name", name, "busybox", "sleep", "10") _, body, err := request.Get(testutil.GetContext(c), fmt.Sprintf("/containers/%s/logs?follow=1&stdout=1&stderr=1&tail=all", name)) t1 := time.Now() @@ -91,21 +92,21 @@ func (s *DockerAPISuite) TestLogsAPIContainerNotFound(c *testing.T) { func (s *DockerAPISuite) TestLogsAPIUntilFutureFollow(c *testing.T) { testRequires(c, DaemonIsLinux) - name := "logsuntilfuturefollow" - dockerCmd(c, "run", "-d", "--name", name, "busybox", "/bin/sh", "-c", "while true; do date +%s; sleep 1; done") - assert.NilError(c, waitRun(name)) + const name = "logsuntilfuturefollow" + cli.DockerCmd(c, "run", "-d", "--name", name, "busybox", "/bin/sh", "-c", "while true; do date +%s; sleep 1; done") + cli.WaitRun(c, name) untilSecs := 5 untilDur, err := time.ParseDuration(fmt.Sprintf("%ds", untilSecs)) assert.NilError(c, err) until := daemonTime(c).Add(untilDur) - client, err := client.NewClientWithOpts(client.FromEnv) + apiClient, err := client.NewClientWithOpts(client.FromEnv) if err != nil { c.Fatal(err) } - reader, err := client.ContainerLogs(testutil.GetContext(c), name, container.LogsOptions{ + reader, err := apiClient.ContainerLogs(testutil.GetContext(c), name, container.LogsOptions{ Until: until.Format(time.RFC3339Nano), Follow: true, ShowStdout: true, @@ -163,16 +164,16 @@ func (s *DockerAPISuite) TestLogsAPIUntilFutureFollow(c *testing.T) { func (s *DockerAPISuite) TestLogsAPIUntil(c *testing.T) { testRequires(c, MinimumAPIVersion("1.34")) - name := "logsuntil" - dockerCmd(c, "run", "--name", name, "busybox", "/bin/sh", "-c", "for i in $(seq 1 3); do echo log$i; sleep 1; done") + const name = "logsuntil" + cli.DockerCmd(c, "run", "--name", name, "busybox", "/bin/sh", "-c", "for i in $(seq 1 3); do echo log$i; sleep 1; done") - client, err := client.NewClientWithOpts(client.FromEnv) + apiClient, err := client.NewClientWithOpts(client.FromEnv) if err != nil { c.Fatal(err) } extractBody := func(c *testing.T, cfg container.LogsOptions) []string { - reader, err := client.ContainerLogs(testutil.GetContext(c), name, cfg) + reader, err := apiClient.ContainerLogs(testutil.GetContext(c), name, cfg) assert.NilError(c, err) actualStdout := new(bytes.Buffer) @@ -200,16 +201,16 @@ func (s *DockerAPISuite) TestLogsAPIUntil(c *testing.T) { } func (s *DockerAPISuite) TestLogsAPIUntilDefaultValue(c *testing.T) { - name := "logsuntildefaultval" - dockerCmd(c, "run", "--name", name, "busybox", "/bin/sh", "-c", "for i in $(seq 1 3); do echo log$i; done") + const name = "logsuntildefaultval" + cli.DockerCmd(c, "run", "--name", name, "busybox", "/bin/sh", "-c", "for i in $(seq 1 3); do echo log$i; done") - client, err := client.NewClientWithOpts(client.FromEnv) + apiClient, err := client.NewClientWithOpts(client.FromEnv) if err != nil { c.Fatal(err) } extractBody := func(c *testing.T, cfg container.LogsOptions) []string { - reader, err := client.ContainerLogs(testutil.GetContext(c), name, cfg) + reader, err := apiClient.ContainerLogs(testutil.GetContext(c), name, cfg) assert.NilError(c, err) actualStdout := new(bytes.Buffer) diff --git a/integration-cli/docker_api_network_test.go b/integration-cli/docker_api_network_test.go index ae8da51851..566a864709 100644 --- a/integration-cli/docker_api_network_test.go +++ b/integration-cli/docker_api_network_test.go @@ -13,6 +13,7 @@ import ( "github.com/docker/docker/api/types/filters" "github.com/docker/docker/api/types/network" "github.com/docker/docker/api/types/versions" + "github.com/docker/docker/integration-cli/cli" "github.com/docker/docker/testutil" "github.com/docker/docker/testutil/request" "gotest.tools/v3/assert" @@ -40,7 +41,7 @@ func (s *DockerAPISuite) TestAPINetworkInspectBridge(c *testing.T) { assert.Equal(c, nr.Name, "bridge") // run a container and attach it to the default bridge network - out, _ := dockerCmd(c, "run", "-d", "--name", "test", "busybox", "top") + out := cli.DockerCmd(c, "run", "-d", "--name", "test", "busybox", "top").Stdout() containerID := strings.TrimSpace(out) containerIP := findContainerIP(c, "test", "bridge") @@ -104,7 +105,7 @@ func (s *DockerAPISuite) TestAPINetworkConnectDisconnect(c *testing.T) { assert.Equal(c, len(nr.Containers), 0) // run a container - out, _ := dockerCmd(c, "run", "-d", "--name", "test", "busybox", "top") + out := cli.DockerCmd(c, "run", "-d", "--name", "test", "busybox", "top").Stdout() containerID := strings.TrimSpace(out) // connect the container to the test network diff --git a/integration-cli/docker_api_stats_test.go b/integration-cli/docker_api_stats_test.go index f85160cdc4..4d31aee079 100644 --- a/integration-cli/docker_api_stats_test.go +++ b/integration-cli/docker_api_stats_test.go @@ -16,6 +16,7 @@ import ( "github.com/docker/docker/api/types/system" "github.com/docker/docker/api/types/versions" "github.com/docker/docker/client" + "github.com/docker/docker/integration-cli/cli" "github.com/docker/docker/testutil" "github.com/docker/docker/testutil/request" "gotest.tools/v3/assert" @@ -26,10 +27,9 @@ var expectedNetworkInterfaceStats = strings.Split("rx_bytes rx_dropped rx_errors func (s *DockerAPISuite) TestAPIStatsNoStreamGetCpu(c *testing.T) { skip.If(c, RuntimeIsWindowsContainerd(), "FIXME: Broken on Windows + containerd combination") - out, _ := dockerCmd(c, "run", "-d", "busybox", "/bin/sh", "-c", "while true;usleep 100; do echo 'Hello'; done") - + out := cli.DockerCmd(c, "run", "-d", "busybox", "/bin/sh", "-c", "while true;usleep 100; do echo 'Hello'; done").Stdout() id := strings.TrimSpace(out) - assert.NilError(c, waitRun(id)) + cli.WaitRun(c, id) resp, body, err := request.Get(testutil.GetContext(c), fmt.Sprintf("/containers/%s/stats?stream=false", id)) assert.NilError(c, err) assert.Equal(c, resp.StatusCode, http.StatusOK) @@ -66,7 +66,7 @@ func (s *DockerAPISuite) TestAPIStatsNoStreamGetCpu(c *testing.T) { } func (s *DockerAPISuite) TestAPIStatsStoppedContainerInGoroutines(c *testing.T) { - out, _ := dockerCmd(c, "run", "-d", "busybox", "/bin/sh", "-c", "echo 1") + out := cli.DockerCmd(c, "run", "-d", "busybox", "/bin/sh", "-c", "echo 1").Stdout() id := strings.TrimSpace(out) getGoRoutines := func() int { @@ -104,9 +104,8 @@ func (s *DockerAPISuite) TestAPIStatsNetworkStats(c *testing.T) { skip.If(c, RuntimeIsWindowsContainerd(), "FIXME: Broken on Windows + containerd combination") testRequires(c, testEnv.IsLocalDaemon) - out := runSleepingContainer(c) - id := strings.TrimSpace(out) - assert.NilError(c, waitRun(id)) + id := runSleepingContainer(c) + cli.WaitRun(c, id) // Retrieve the container address net := "bridge" @@ -170,9 +169,8 @@ func (s *DockerAPISuite) TestAPIStatsNetworkStatsVersioning(c *testing.T) { // Windows doesn't support API versions less than 1.25, so no point testing 1.17 .. 1.21 testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux) - out := runSleepingContainer(c) - id := strings.TrimSpace(out) - assert.NilError(c, waitRun(id)) + id := runSleepingContainer(c) + cli.WaitRun(c, id) wg := sync.WaitGroup{} for i := 17; i <= 21; i++ { @@ -278,13 +276,11 @@ func (s *DockerAPISuite) TestAPIStatsContainerNotFound(c *testing.T) { func (s *DockerAPISuite) TestAPIStatsNoStreamConnectedContainers(c *testing.T) { testRequires(c, DaemonIsLinux) - out1 := runSleepingContainer(c) - id1 := strings.TrimSpace(out1) - assert.NilError(c, waitRun(id1)) + id1 := runSleepingContainer(c) + cli.WaitRun(c, id1) - out2 := runSleepingContainer(c, "--net", "container:"+id1) - id2 := strings.TrimSpace(out2) - assert.NilError(c, waitRun(id2)) + id2 := runSleepingContainer(c, "--net", "container:"+id1) + cli.WaitRun(c, id2) ch := make(chan error, 1) go func() { diff --git a/integration-cli/docker_cli_attach_test.go b/integration-cli/docker_cli_attach_test.go index 9bd7410e4d..1137b1d37d 100644 --- a/integration-cli/docker_cli_attach_test.go +++ b/integration-cli/docker_cli_attach_test.go @@ -110,10 +110,9 @@ func (s *DockerCLIAttachSuite) TestAttachTTYWithoutStdin(c *testing.T) { // will just fail and `MISS` all the other tests. For now, disabling it. Will // open an issue to track re-enabling this and root-causing the problem. testRequires(c, DaemonIsLinux) - out, _ := dockerCmd(c, "run", "-d", "-ti", "busybox") - + out := cli.DockerCmd(c, "run", "-d", "-ti", "busybox").Stdout() id := strings.TrimSpace(out) - assert.NilError(c, waitRun(id)) + cli.WaitRun(c, id) done := make(chan error, 1) go func() { @@ -129,10 +128,17 @@ func (s *DockerCLIAttachSuite) TestAttachTTYWithoutStdin(c *testing.T) { if runtime.GOOS == "windows" { expected += ". If you are using mintty, try prefixing the command with 'winpty'" } - if out, _, err := runCommandWithOutput(cmd); err == nil { + result := icmd.RunCmd(icmd.Cmd{ + Command: cmd.Args, + Env: cmd.Env, + Dir: cmd.Dir, + Stdin: cmd.Stdin, + Stdout: cmd.Stdout, + }) + if result.Error == nil { done <- fmt.Errorf("attach should have failed") return - } else if !strings.Contains(out, expected) { + } else if !strings.Contains(result.Combined(), expected) { done <- fmt.Errorf("attach failed with error %q: expected %q", out, expected) return } @@ -148,7 +154,7 @@ func (s *DockerCLIAttachSuite) TestAttachTTYWithoutStdin(c *testing.T) { func (s *DockerCLIAttachSuite) TestAttachDisconnect(c *testing.T) { testRequires(c, DaemonIsLinux) - out, _ := dockerCmd(c, "run", "-di", "busybox", "/bin/cat") + out := cli.DockerCmd(c, "run", "-di", "busybox", "/bin/cat").Stdout() id := strings.TrimSpace(out) cmd := exec.Command(dockerBinary, "attach", id) @@ -182,9 +188,9 @@ func (s *DockerCLIAttachSuite) TestAttachDisconnect(c *testing.T) { func (s *DockerCLIAttachSuite) TestAttachPausedContainer(c *testing.T) { testRequires(c, IsPausable) runSleepingContainer(c, "-d", "--name=test") - dockerCmd(c, "pause", "test") + cli.DockerCmd(c, "pause", "test") - result := dockerCmdWithResult("attach", "test") + result := cli.Docker(cli.Args("attach", "test")) result.Assert(c, icmd.Expected{ Error: "exit status 1", ExitCode: 1, diff --git a/integration-cli/docker_cli_attach_unix_test.go b/integration-cli/docker_cli_attach_unix_test.go index c0db3f4a12..c283d01c83 100644 --- a/integration-cli/docker_cli_attach_unix_test.go +++ b/integration-cli/docker_cli_attach_unix_test.go @@ -11,6 +11,7 @@ import ( "time" "github.com/creack/pty" + "github.com/docker/docker/integration-cli/cli" "gotest.tools/v3/assert" ) @@ -18,12 +19,11 @@ import ( func (s *DockerCLIAttachSuite) TestAttachClosedOnContainerStop(c *testing.T) { testRequires(c, testEnv.IsLocalDaemon) - out, _ := dockerCmd(c, "run", "-dti", "busybox", "/bin/sh", "-c", `trap 'exit 0' SIGTERM; while true; do sleep 1; done`) - + out := cli.DockerCmd(c, "run", "-dti", "busybox", "/bin/sh", "-c", `trap 'exit 0' SIGTERM; while true; do sleep 1; done`).Stdout() id := strings.TrimSpace(out) - assert.NilError(c, waitRun(id)) + cli.WaitRun(c, id) - pty, tty, err := pty.Open() + pt, tty, err := pty.Open() assert.NilError(c, err) attachCmd := exec.Command(dockerBinary, "attach", id) @@ -38,19 +38,19 @@ func (s *DockerCLIAttachSuite) TestAttachClosedOnContainerStop(c *testing.T) { time.Sleep(300 * time.Millisecond) defer close(errChan) // Container is waiting for us to signal it to stop - dockerCmd(c, "stop", id) + cli.DockerCmd(c, "stop", id) // And wait for the attach command to end errChan <- attachCmd.Wait() }() // Wait for the docker to end (should be done by the // stop command in the go routine) - dockerCmd(c, "wait", id) + cli.DockerCmd(c, "wait", id) select { case err := <-errChan: tty.Close() - out, _ := io.ReadAll(pty) + out, _ := io.ReadAll(pt) assert.Assert(c, err == nil, "out: %v", string(out)) case <-time.After(attachWait): c.Fatal("timed out without attach returning") @@ -73,7 +73,7 @@ func (s *DockerCLIAttachSuite) TestAttachAfterDetach(c *testing.T) { close(cmdExit) }() - assert.Assert(c, waitRun(name) == nil) + cli.WaitRun(c, name) cpty.Write([]byte{16}) time.Sleep(100 * time.Millisecond) @@ -123,9 +123,9 @@ func (s *DockerCLIAttachSuite) TestAttachAfterDetach(c *testing.T) { // TestAttachDetach checks that attach in tty mode can be detached using the long container ID func (s *DockerCLIAttachSuite) TestAttachDetach(c *testing.T) { - out, _ := dockerCmd(c, "run", "-itd", "busybox", "cat") + out := cli.DockerCmd(c, "run", "-itd", "busybox", "cat").Stdout() id := strings.TrimSpace(out) - assert.NilError(c, waitRun(id)) + cli.WaitRun(c, id) cpty, tty, err := pty.Open() assert.NilError(c, err) @@ -138,7 +138,7 @@ func (s *DockerCLIAttachSuite) TestAttachDetach(c *testing.T) { defer stdout.Close() err = cmd.Start() assert.NilError(c, err) - assert.NilError(c, waitRun(id)) + cli.WaitRun(c, id) _, err = cpty.Write([]byte("hello\n")) assert.NilError(c, err) diff --git a/integration-cli/docker_cli_build_test.go b/integration-cli/docker_cli_build_test.go index d97a94099e..78462fb22e 100644 --- a/integration-cli/docker_cli_build_test.go +++ b/integration-cli/docker_cli_build_test.go @@ -51,7 +51,7 @@ func (s *DockerCLIBuildSuite) TestBuildJSONEmptyRun(c *testing.T) { } func (s *DockerCLIBuildSuite) TestBuildShCmdJSONEntrypoint(c *testing.T) { - name := "testbuildshcmdjsonentrypoint" + const name = "testbuildshcmdjsonentrypoint" expected := "/bin/sh -c echo test" if testEnv.DaemonInfo.OSType == "windows" { expected = "cmd /S /C echo test" @@ -62,7 +62,7 @@ func (s *DockerCLIBuildSuite) TestBuildShCmdJSONEntrypoint(c *testing.T) { ENTRYPOINT ["echo"] CMD echo test `)) - out, _ := dockerCmd(c, "run", "--rm", name) + out := cli.DockerCmd(c, "run", "--rm", name).Combined() if strings.TrimSpace(out) != expected { c.Fatalf("CMD did not contain %q : %q", expected, out) @@ -72,7 +72,7 @@ func (s *DockerCLIBuildSuite) TestBuildShCmdJSONEntrypoint(c *testing.T) { func (s *DockerCLIBuildSuite) TestBuildEnvironmentReplacementUser(c *testing.T) { // Windows does not support FROM scratch or the USER command testRequires(c, DaemonIsLinux) - name := "testbuildenvironmentreplacement" + const name = "testbuildenvironmentreplacement" buildImageSuccessfully(c, name, build.WithDockerfile(` FROM scratch @@ -87,7 +87,7 @@ func (s *DockerCLIBuildSuite) TestBuildEnvironmentReplacementUser(c *testing.T) } func (s *DockerCLIBuildSuite) TestBuildEnvironmentReplacementVolume(c *testing.T) { - name := "testbuildenvironmentreplacement" + const name = "testbuildenvironmentreplacement" var volumePath string @@ -113,7 +113,7 @@ func (s *DockerCLIBuildSuite) TestBuildEnvironmentReplacementVolume(c *testing.T func (s *DockerCLIBuildSuite) TestBuildEnvironmentReplacementExpose(c *testing.T) { // Windows does not support FROM scratch or the EXPOSE command testRequires(c, DaemonIsLinux) - name := "testbuildenvironmentreplacement" + const name = "testbuildenvironmentreplacement" buildImageSuccessfully(c, name, build.WithDockerfile(` FROM scratch @@ -135,7 +135,7 @@ func (s *DockerCLIBuildSuite) TestBuildEnvironmentReplacementExpose(c *testing.T } func (s *DockerCLIBuildSuite) TestBuildEnvironmentReplacementWorkdir(c *testing.T) { - name := "testbuildenvironmentreplacement" + const name = "testbuildenvironmentreplacement" buildImageSuccessfully(c, name, build.WithDockerfile(` FROM busybox @@ -155,7 +155,7 @@ func (s *DockerCLIBuildSuite) TestBuildEnvironmentReplacementWorkdir(c *testing. } func (s *DockerCLIBuildSuite) TestBuildEnvironmentReplacementAddCopy(c *testing.T) { - name := "testbuildenvironmentreplacement" + const name = "testbuildenvironmentreplacement" buildImageSuccessfully(c, name, build.WithBuildContext(c, build.WithFile("Dockerfile", ` @@ -181,7 +181,7 @@ func (s *DockerCLIBuildSuite) TestBuildEnvironmentReplacementAddCopy(c *testing. func (s *DockerCLIBuildSuite) TestBuildEnvironmentReplacementEnv(c *testing.T) { // ENV expansions work differently in Windows testRequires(c, DaemonIsLinux) - name := "testbuildenvironmentreplacement" + const name = "testbuildenvironmentreplacement" buildImageSuccessfully(c, name, build.WithDockerfile(` FROM busybox @@ -243,7 +243,7 @@ func (s *DockerCLIBuildSuite) TestBuildEnvironmentReplacementEnv(c *testing.T) { func (s *DockerCLIBuildSuite) TestBuildHandleEscapesInVolume(c *testing.T) { // The volume paths used in this test are invalid on Windows testRequires(c, DaemonIsLinux) - name := "testbuildhandleescapes" + const name = "testbuildhandleescapes" testCases := []struct { volumeValue string @@ -280,13 +280,13 @@ func (s *DockerCLIBuildSuite) TestBuildHandleEscapesInVolume(c *testing.T) { } // Remove the image for the next iteration - dockerCmd(c, "rmi", name) + cli.DockerCmd(c, "rmi", name) } } func (s *DockerCLIBuildSuite) TestBuildOnBuildLowercase(c *testing.T) { - name := "testbuildonbuildlowercase" - name2 := "testbuildonbuildlowercase2" + const name = "testbuildonbuildlowercase" + const name2 = "testbuildonbuildlowercase2" buildImageSuccessfully(c, name, build.WithDockerfile(` FROM busybox @@ -310,14 +310,14 @@ func (s *DockerCLIBuildSuite) TestBuildOnBuildLowercase(c *testing.T) { func (s *DockerCLIBuildSuite) TestBuildEnvEscapes(c *testing.T) { // ENV expansions work differently in Windows testRequires(c, DaemonIsLinux) - name := "testbuildenvescapes" + const name = "testbuildenvescapes" buildImageSuccessfully(c, name, build.WithDockerfile(` FROM busybox ENV TEST foo CMD echo \$ `)) - out, _ := dockerCmd(c, "run", "-t", name) + out := cli.DockerCmd(c, "run", "-t", name).Combined() if strings.TrimSpace(out) != "$" { c.Fatalf("Env TEST was not overwritten with bar when foo was supplied to dockerfile: was %q", strings.TrimSpace(out)) } @@ -326,14 +326,14 @@ func (s *DockerCLIBuildSuite) TestBuildEnvEscapes(c *testing.T) { func (s *DockerCLIBuildSuite) TestBuildEnvOverwrite(c *testing.T) { // ENV expansions work differently in Windows testRequires(c, DaemonIsLinux) - name := "testbuildenvoverwrite" + const name = "testbuildenvoverwrite" buildImageSuccessfully(c, name, build.WithDockerfile(` FROM busybox ENV TEST foo CMD echo ${TEST} `)) - out, _ := dockerCmd(c, "run", "-e", "TEST=bar", "-t", name) + out := cli.DockerCmd(c, "run", "-e", "TEST=bar", "-t", name).Combined() if strings.TrimSpace(out) != "bar" { c.Fatalf("Env TEST was not overwritten with bar when foo was supplied to dockerfile: was %q", strings.TrimSpace(out)) } @@ -341,8 +341,8 @@ func (s *DockerCLIBuildSuite) TestBuildEnvOverwrite(c *testing.T) { // FIXME(vdemeester) why we disabled cache here ? func (s *DockerCLIBuildSuite) TestBuildOnBuildCmdEntrypointJSON(c *testing.T) { - name1 := "onbuildcmd" - name2 := "onbuildgenerated" + const name1 = "onbuildcmd" + const name2 = "onbuildgenerated" cli.BuildCmd(c, name1, build.WithDockerfile(` FROM busybox @@ -358,8 +358,8 @@ ONBUILD RUN ["true"]`)) // FIXME(vdemeester) why we disabled cache here ? func (s *DockerCLIBuildSuite) TestBuildOnBuildEntrypointJSON(c *testing.T) { - name1 := "onbuildcmd" - name2 := "onbuildgenerated" + const name1 = "onbuildcmd" + const name2 = "onbuildgenerated" buildImageSuccessfully(c, name1, build.WithDockerfile(` FROM busybox @@ -367,7 +367,7 @@ ONBUILD ENTRYPOINT ["echo"]`)) buildImageSuccessfully(c, name2, build.WithDockerfile(fmt.Sprintf("FROM %s\nCMD [\"hello world\"]\n", name1))) - out, _ := dockerCmd(c, "run", name2) + out := cli.DockerCmd(c, "run", name2).Combined() if !regexp.MustCompile(`(?m)^hello world`).MatchString(out) { c.Fatal("got malformed output from onbuild", out) } @@ -375,7 +375,7 @@ ONBUILD ENTRYPOINT ["echo"]`)) func (s *DockerCLIBuildSuite) TestBuildCacheAdd(c *testing.T) { testRequires(c, DaemonIsLinux) // Windows doesn't have httpserver image yet - name := "testbuildtwoimageswithadd" + const name = "testbuildtwoimageswithadd" server := fakestorage.New(c, "", fakecontext.WithFiles(map[string]string{ "robots.txt": "hello", "index.html": "world", @@ -398,7 +398,7 @@ func (s *DockerCLIBuildSuite) TestBuildLastModified(c *testing.T) { // has changed in the master busybox image. testRequires(c, DaemonIsLinux) - name := "testbuildlastmodified" + const name = "testbuildlastmodified" server := fakestorage.New(c, "", fakecontext.WithFiles(map[string]string{ "file": "hello", @@ -446,7 +446,7 @@ ADD %s/file /` // Makes sure that we don't use the cache if the contents of // a file in a subfolder of the context is modified and we re-build. func (s *DockerCLIBuildSuite) TestBuildModifyFileInFolder(c *testing.T) { - name := "testbuildmodifyfileinfolder" + const name = "testbuildmodifyfileinfolder" ctx := fakecontext.New(c, "", fakecontext.WithDockerfile(`FROM busybox RUN ["mkdir", "/test"] @@ -484,7 +484,7 @@ RUN [ $(ls -l /exists | awk '{print $3":"$4}') = 'dockerio:dockerio' ]`, expecte // Issue #3960: "ADD src ." hangs func (s *DockerCLIBuildSuite) TestBuildAddSingleFileToWorkdir(c *testing.T) { - name := "testaddsinglefiletoworkdir" + const name = "testaddsinglefiletoworkdir" ctx := fakecontext.New(c, "", fakecontext.WithDockerfile( `FROM busybox ADD test_file .`), @@ -562,7 +562,7 @@ func (s *DockerCLIBuildSuite) TestBuildUsernamespaceValidateRemappedRoot(c *test "COPY test_dir /new_dir", "WORKDIR /new_dir", } - name := "testbuildusernamespacevalidateremappedroot" + const name = "testbuildusernamespacevalidateremappedroot" for _, tc := range testCases { cli.BuildCmd(c, name, build.WithBuildContext(c, build.WithFile("Dockerfile", fmt.Sprintf(`FROM busybox @@ -576,7 +576,7 @@ RUN [ $(ls -l / | grep new_dir | awk '{print $3":"$4}') = 'root:root' ]`, tc)), func (s *DockerCLIBuildSuite) TestBuildAddAndCopyFileWithWhitespace(c *testing.T) { testRequires(c, DaemonIsLinux) // Not currently passing on Windows - name := "testaddfilewithwhitespace" + const name = "testaddfilewithwhitespace" for _, command := range []string{"ADD", "COPY"} { cli.BuildCmd(c, name, build.WithBuildContext(c, @@ -625,7 +625,7 @@ RUN find "test4" "C:/test_dir/test_file4" RUN find "test5" "C:/test dir/test_file5" RUN find "test6" "C:/test dir/test_file6"` - name := "testcopyfilewithwhitespace" + const name = "testcopyfilewithwhitespace" cli.BuildCmd(c, name, build.WithBuildContext(c, build.WithFile("Dockerfile", dockerfile), build.WithFile("test file1", "test1"), @@ -638,7 +638,7 @@ RUN find "test6" "C:/test dir/test_file6"` } func (s *DockerCLIBuildSuite) TestBuildCopyWildcard(c *testing.T) { - name := "testcopywildcard" + const name = "testcopywildcard" server := fakestorage.New(c, "", fakecontext.WithFiles(map[string]string{ "robots.txt": "hello", "index.html": "world", @@ -697,7 +697,7 @@ func (s *DockerCLIBuildSuite) TestBuildCopyWildcardInName(c *testing.T) { } func (s *DockerCLIBuildSuite) TestBuildCopyWildcardCache(c *testing.T) { - name := "testcopywildcardcache" + const name = "testcopywildcardcache" ctx := fakecontext.New(c, "", fakecontext.WithDockerfile(`FROM busybox COPY file1.txt /tmp/`), fakecontext.WithFiles(map[string]string{ @@ -826,7 +826,7 @@ RUN [ $(ls -l /exists | awk '{print $3":"$4}') = 'dockerio:dockerio' ]`, expecte // Issue #3960: "ADD src ." hangs - adapted for COPY func (s *DockerCLIBuildSuite) TestBuildCopySingleFileToWorkdir(c *testing.T) { - name := "testcopysinglefiletoworkdir" + const name = "testcopysinglefiletoworkdir" ctx := fakecontext.New(c, "", fakecontext.WithDockerfile(`FROM busybox COPY test_file .`), fakecontext.WithFiles(map[string]string{ @@ -934,7 +934,7 @@ func (s *DockerCLIBuildSuite) TestBuildAddBadLinks(c *testing.T) { ADD foo.txt /symlink/ ` targetFile := "foo.txt" - name := "test-link-absolute" + const name = "test-link-absolute" ctx := fakecontext.New(c, "", fakecontext.WithDockerfile(dockerfile)) defer ctx.Close() @@ -1048,7 +1048,7 @@ func (s *DockerCLIBuildSuite) TestBuildWithInaccessibleFilesInContext(c *testing testRequires(c, DaemonIsLinux, UnixCli, testEnv.IsLocalDaemon) // test uses chown/chmod: not available on windows { - name := "testbuildinaccessiblefiles" + const name = "testbuildinaccessiblefiles" ctx := fakecontext.New(c, "", fakecontext.WithDockerfile("FROM scratch\nADD . /foo/"), fakecontext.WithFiles(map[string]string{"fileWithoutReadAccess": "foo"}), @@ -1081,7 +1081,7 @@ func (s *DockerCLIBuildSuite) TestBuildWithInaccessibleFilesInContext(c *testing } } { - name := "testbuildinaccessibledirectory" + const name = "testbuildinaccessibledirectory" ctx := fakecontext.New(c, "", fakecontext.WithDockerfile("FROM scratch\nADD . /foo/"), fakecontext.WithFiles(map[string]string{"directoryWeCantStat/bar": "foo"}), @@ -1119,7 +1119,7 @@ func (s *DockerCLIBuildSuite) TestBuildWithInaccessibleFilesInContext(c *testing } } { - name := "testlinksok" + const name = "testlinksok" ctx := fakecontext.New(c, "", fakecontext.WithDockerfile("FROM scratch\nADD . /foo/")) defer ctx.Close() @@ -1133,7 +1133,7 @@ func (s *DockerCLIBuildSuite) TestBuildWithInaccessibleFilesInContext(c *testing buildImageSuccessfully(c, name, build.WithExternalBuildContext(ctx)) } { - name := "testbuildignoredinaccessible" + const name = "testbuildignoredinaccessible" ctx := fakecontext.New(c, "", fakecontext.WithDockerfile("FROM scratch\nADD . /foo/"), fakecontext.WithFiles(map[string]string{ @@ -1168,7 +1168,7 @@ func (s *DockerCLIBuildSuite) TestBuildWithInaccessibleFilesInContext(c *testing func (s *DockerCLIBuildSuite) TestBuildForceRm(c *testing.T) { containerCountBefore := getContainerCount(c) - name := "testbuildforcerm" + const name = "testbuildforcerm" r := buildImage(name, cli.WithFlags("--force-rm"), build.WithBuildContext(c, build.WithFile("Dockerfile", `FROM busybox @@ -1185,7 +1185,7 @@ func (s *DockerCLIBuildSuite) TestBuildForceRm(c *testing.T) { } func (s *DockerCLIBuildSuite) TestBuildRm(c *testing.T) { - name := "testbuildrm" + const name = "testbuildrm" testCases := []struct { buildflags []string @@ -1223,7 +1223,7 @@ func (s *DockerCLIBuildSuite) TestBuildRm(c *testing.T) { } } - dockerCmd(c, "rmi", name) + cli.DockerCmd(c, "rmi", name) } } @@ -1262,7 +1262,7 @@ func (s *DockerCLIBuildSuite) TestBuildWithVolumes(c *testing.T) { } func (s *DockerCLIBuildSuite) TestBuildMaintainer(c *testing.T) { - name := "testbuildmaintainer" + const name = "testbuildmaintainer" buildImageSuccessfully(c, name, build.WithDockerfile(`FROM `+minimalBaseImage()+` MAINTAINER dockerio`)) @@ -1276,7 +1276,7 @@ func (s *DockerCLIBuildSuite) TestBuildMaintainer(c *testing.T) { func (s *DockerCLIBuildSuite) TestBuildUser(c *testing.T) { testRequires(c, DaemonIsLinux) - name := "testbuilduser" + const name = "testbuilduser" expected := "dockerio" buildImageSuccessfully(c, name, build.WithDockerfile(`FROM busybox RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd @@ -1289,7 +1289,7 @@ func (s *DockerCLIBuildSuite) TestBuildUser(c *testing.T) { } func (s *DockerCLIBuildSuite) TestBuildRelativeWorkdir(c *testing.T) { - name := "testbuildrelativeworkdir" + const name = "testbuildrelativeworkdir" var ( expected1 string @@ -1375,7 +1375,7 @@ func (s *DockerCLIBuildSuite) TestBuildWindowsAddCopyPathProcessing(c *testing.T } func (s *DockerCLIBuildSuite) TestBuildWorkdirWithEnvVariables(c *testing.T) { - name := "testbuildworkdirwithenvvariables" + const name = "testbuildworkdirwithenvvariables" var expected string if testEnv.DaemonInfo.OSType == "windows" { @@ -1435,7 +1435,7 @@ func (s *DockerCLIBuildSuite) TestBuildRelativeCopy(c *testing.T) { // FIXME(vdemeester) should be unit test func (s *DockerCLIBuildSuite) TestBuildBlankName(c *testing.T) { - name := "testbuildblankname" + const name = "testbuildblankname" testCases := []struct { expression string expectedStderr string @@ -1465,7 +1465,7 @@ func (s *DockerCLIBuildSuite) TestBuildBlankName(c *testing.T) { func (s *DockerCLIBuildSuite) TestBuildEnv(c *testing.T) { testRequires(c, DaemonIsLinux) // ENV expansion is different in Windows - name := "testbuildenv" + const name = "testbuildenv" expected := "[PATH=/test:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin PORT=2375]" buildImageSuccessfully(c, name, build.WithDockerfile(`FROM busybox ENV PATH /test:$PATH @@ -1509,7 +1509,7 @@ func (s *DockerCLIBuildSuite) TestBuildPATH(c *testing.T) { func (s *DockerCLIBuildSuite) TestBuildContextCleanup(c *testing.T) { testRequires(c, testEnv.IsLocalDaemon) - name := "testbuildcontextcleanup" + const name = "testbuildcontextcleanup" entries, err := os.ReadDir(filepath.Join(testEnv.DaemonInfo.DockerRootDir, "tmp")) if err != nil { c.Fatalf("failed to list contents of tmp dir: %s", err) @@ -1530,7 +1530,7 @@ func (s *DockerCLIBuildSuite) TestBuildContextCleanup(c *testing.T) { func (s *DockerCLIBuildSuite) TestBuildContextCleanupFailedBuild(c *testing.T) { testRequires(c, testEnv.IsLocalDaemon) - name := "testbuildcontextcleanup" + const name = "testbuildcontextcleanup" entries, err := os.ReadDir(filepath.Join(testEnv.DaemonInfo.DockerRootDir, "tmp")) if err != nil { c.Fatalf("failed to list contents of tmp dir: %s", err) @@ -1570,7 +1570,7 @@ func compareDirectoryEntries(e1 []os.DirEntry, e2 []os.DirEntry) error { } func (s *DockerCLIBuildSuite) TestBuildCmd(c *testing.T) { - name := "testbuildcmd" + const name = "testbuildcmd" expected := "[/bin/echo Hello World]" buildImageSuccessfully(c, name, build.WithDockerfile(`FROM `+minimalBaseImage()+` @@ -1584,7 +1584,7 @@ func (s *DockerCLIBuildSuite) TestBuildCmd(c *testing.T) { func (s *DockerCLIBuildSuite) TestBuildExpose(c *testing.T) { testRequires(c, DaemonIsLinux) // Expose not implemented on Windows - name := "testbuildexpose" + const name = "testbuildexpose" expected := "map[2375/tcp:{}]" buildImageSuccessfully(c, name, build.WithDockerfile(`FROM scratch @@ -1622,7 +1622,7 @@ func (s *DockerCLIBuildSuite) TestBuildExposeMorePorts(c *testing.T) { buf := bytes.NewBuffer(nil) tmpl.Execute(buf, portList) - name := "testbuildexpose" + const name = "testbuildexpose" buildImageSuccessfully(c, name, build.WithDockerfile(buf.String())) // check if all the ports are saved inside Config.ExposedPorts @@ -1663,7 +1663,7 @@ func (s *DockerCLIBuildSuite) TestBuildExposeOrder(c *testing.T) { func (s *DockerCLIBuildSuite) TestBuildExposeUpperCaseProto(c *testing.T) { testRequires(c, DaemonIsLinux) // Expose not implemented on Windows - name := "testbuildexposeuppercaseproto" + const name = "testbuildexposeuppercaseproto" expected := "map[5678/udp:{}]" buildImageSuccessfully(c, name, build.WithDockerfile(`FROM scratch EXPOSE 5678/UDP`)) @@ -1674,8 +1674,8 @@ func (s *DockerCLIBuildSuite) TestBuildExposeUpperCaseProto(c *testing.T) { } func (s *DockerCLIBuildSuite) TestBuildEmptyEntrypointInheritance(c *testing.T) { - name := "testbuildentrypointinheritance" - name2 := "testbuildentrypointinheritance2" + const name = "testbuildentrypointinheritance" + const name2 = "testbuildentrypointinheritance2" buildImageSuccessfully(c, name, build.WithDockerfile(`FROM busybox ENTRYPOINT ["/bin/echo"]`)) @@ -1697,7 +1697,7 @@ func (s *DockerCLIBuildSuite) TestBuildEmptyEntrypointInheritance(c *testing.T) } func (s *DockerCLIBuildSuite) TestBuildEmptyEntrypoint(c *testing.T) { - name := "testbuildentrypoint" + const name = "testbuildentrypoint" expected := "[]" buildImageSuccessfully(c, name, build.WithDockerfile(`FROM busybox @@ -1710,7 +1710,7 @@ func (s *DockerCLIBuildSuite) TestBuildEmptyEntrypoint(c *testing.T) { } func (s *DockerCLIBuildSuite) TestBuildEntrypoint(c *testing.T) { - name := "testbuildentrypoint" + const name = "testbuildentrypoint" expected := "[/bin/echo]" buildImageSuccessfully(c, name, build.WithDockerfile(`FROM `+minimalBaseImage()+` @@ -1743,7 +1743,7 @@ func (s *DockerCLIBuildSuite) TestBuildOnBuildLimitedInheritance(c *testing.T) { func (s *DockerCLIBuildSuite) TestBuildSameDockerfileWithAndWithoutCache(c *testing.T) { testRequires(c, DaemonIsLinux) // Expose not implemented on Windows - name := "testbuildwithcache" + const name = "testbuildwithcache" dockerfile := `FROM scratch MAINTAINER dockerio EXPOSE 5432 @@ -1764,7 +1764,7 @@ func (s *DockerCLIBuildSuite) TestBuildSameDockerfileWithAndWithoutCache(c *test // Make sure that ADD/COPY still populate the cache even if they don't use it func (s *DockerCLIBuildSuite) TestBuildConditionalCache(c *testing.T) { - name := "testbuildconditionalcache" + const name = "testbuildconditionalcache" dockerfile := ` FROM busybox @@ -1798,7 +1798,7 @@ func (s *DockerCLIBuildSuite) TestBuildConditionalCache(c *testing.T) { } func (s *DockerCLIBuildSuite) TestBuildAddMultipleLocalFileWithAndWithoutCache(c *testing.T) { - name := "testbuildaddmultiplelocalfilewithcache" + const name = "testbuildaddmultiplelocalfilewithcache" baseName := name + "-base" cli.BuildCmd(c, baseName, build.WithDockerfile(` @@ -1830,8 +1830,8 @@ func (s *DockerCLIBuildSuite) TestBuildAddMultipleLocalFileWithAndWithoutCache(c } func (s *DockerCLIBuildSuite) TestBuildCopyDirButNotFile(c *testing.T) { - name := "testbuildcopydirbutnotfile" - name2 := "testbuildcopydirbutnotfile2" + const name = "testbuildcopydirbutnotfile" + const name2 = "testbuildcopydirbutnotfile2" dockerfile := ` FROM ` + minimalBaseImage() + ` @@ -1854,10 +1854,10 @@ func (s *DockerCLIBuildSuite) TestBuildCopyDirButNotFile(c *testing.T) { } func (s *DockerCLIBuildSuite) TestBuildAddCurrentDirWithCache(c *testing.T) { - name := "testbuildaddcurrentdirwithcache" - name2 := name + "2" - name3 := name + "3" - name4 := name + "4" + const name = "testbuildaddcurrentdirwithcache" + const name2 = name + "2" + const name3 = name + "3" + const name4 = name + "4" dockerfile := ` FROM ` + minimalBaseImage() + ` MAINTAINER dockerio @@ -1901,7 +1901,7 @@ func (s *DockerCLIBuildSuite) TestBuildAddCurrentDirWithCache(c *testing.T) { // FIXME(vdemeester) this really seems to test the same thing as before (TestBuildAddMultipleLocalFileWithAndWithoutCache) func (s *DockerCLIBuildSuite) TestBuildAddCurrentDirWithoutCache(c *testing.T) { - name := "testbuildaddcurrentdirwithoutcache" + const name = "testbuildaddcurrentdirwithoutcache" dockerfile := ` FROM ` + minimalBaseImage() + ` MAINTAINER dockerio @@ -1920,7 +1920,7 @@ func (s *DockerCLIBuildSuite) TestBuildAddCurrentDirWithoutCache(c *testing.T) { } func (s *DockerCLIBuildSuite) TestBuildAddRemoteFileWithAndWithoutCache(c *testing.T) { - name := "testbuildaddremotefilewithcache" + const name = "testbuildaddremotefilewithcache" server := fakestorage.New(c, "", fakecontext.WithFiles(map[string]string{ "baz": "hello", })) @@ -1945,9 +1945,9 @@ func (s *DockerCLIBuildSuite) TestBuildAddRemoteFileWithAndWithoutCache(c *testi } func (s *DockerCLIBuildSuite) TestBuildAddRemoteFileMTime(c *testing.T) { - name := "testbuildaddremotefilemtime" - name2 := name + "2" - name3 := name + "3" + const name = "testbuildaddremotefilemtime" + const name2 = name + "2" + const name3 = name + "3" files := map[string]string{"baz": "hello"} server := fakestorage.New(c, "", fakecontext.WithFiles(files)) @@ -1988,7 +1988,7 @@ func (s *DockerCLIBuildSuite) TestBuildAddRemoteFileMTime(c *testing.T) { // FIXME(vdemeester) this really seems to test the same thing as before (combined) func (s *DockerCLIBuildSuite) TestBuildAddLocalAndRemoteFilesWithAndWithoutCache(c *testing.T) { - name := "testbuildaddlocalandremotefilewithcache" + const name = "testbuildaddlocalandremotefilewithcache" server := fakestorage.New(c, "", fakecontext.WithFiles(map[string]string{ "baz": "hello", })) @@ -2030,7 +2030,7 @@ CMD ["cat", "/foo"]`), if err != nil { c.Fatalf("failed to build context tar: %v", err) } - name := "contexttar" + const name = "contexttar" cli.BuildCmd(c, name, build.WithStdinContext(context)) } @@ -2044,7 +2044,7 @@ func (s *DockerCLIBuildSuite) TestBuildContextTarNoCompression(c *testing.T) { } func (s *DockerCLIBuildSuite) TestBuildNoContext(c *testing.T) { - name := "nocontext" + const name = "nocontext" icmd.RunCmd(icmd.Cmd{ Command: []string{dockerBinary, "build", "-t", name, "-"}, Stdin: strings.NewReader( @@ -2052,14 +2052,14 @@ func (s *DockerCLIBuildSuite) TestBuildNoContext(c *testing.T) { CMD ["echo", "ok"]`), }).Assert(c, icmd.Success) - if out, _ := dockerCmd(c, "run", "--rm", "nocontext"); out != "ok\n" { + if out := cli.DockerCmd(c, "run", "--rm", "nocontext").Combined(); out != "ok\n" { c.Fatalf("run produced invalid output: %q, expected %q", out, "ok") } } // FIXME(vdemeester) migrate to docker/cli e2e func (s *DockerCLIBuildSuite) TestBuildDockerfileStdin(c *testing.T) { - name := "stdindockerfile" + const name = "stdindockerfile" tmpDir, err := os.MkdirTemp("", "fake-context") assert.NilError(c, err) err = os.WriteFile(filepath.Join(tmpDir, "foo"), []byte("bar"), 0o600) @@ -2079,7 +2079,7 @@ CMD ["cat", "/foo"]`), // FIXME(vdemeester) migrate to docker/cli tests (unit or e2e) func (s *DockerCLIBuildSuite) TestBuildDockerfileStdinConflict(c *testing.T) { - name := "stdindockerfiletarcontext" + const name = "stdindockerfiletarcontext" icmd.RunCmd(icmd.Cmd{ Command: []string{dockerBinary, "build", "-t", name, "-f", "-", "-"}, }).Assert(c, icmd.Expected{ @@ -2101,7 +2101,7 @@ func (s *DockerCLIBuildSuite) TestBuildDockerfileStdinDockerignoreIgnored(c *tes } func (s *DockerCLIBuildSuite) testBuildDockerfileStdinNoExtraFiles(c *testing.T, hasDockerignore, ignoreDockerignore bool) { - name := "stdindockerfilenoextra" + const name = "stdindockerfilenoextra" tmpDir, err := os.MkdirTemp("", "fake-context") assert.NilError(c, err) defer os.RemoveAll(tmpDir) @@ -2142,13 +2142,13 @@ COPY . /baz`), func (s *DockerCLIBuildSuite) TestBuildWithVolumeOwnership(c *testing.T) { testRequires(c, DaemonIsLinux) - name := "testbuildimg" + const name = "testbuildimg" buildImageSuccessfully(c, name, build.WithDockerfile(`FROM busybox:latest RUN mkdir /test && chown daemon:daemon /test && chmod 0600 /test VOLUME /test`)) - out, _ := dockerCmd(c, "run", "--rm", "testbuildimg", "ls", "-la", "/test") + out := cli.DockerCmd(c, "run", "--rm", "testbuildimg", "ls", "-la", "/test").Combined() if expected := "drw-------"; !strings.Contains(out, expected) { c.Fatalf("expected %s received %s", expected, out) } @@ -2160,7 +2160,7 @@ func (s *DockerCLIBuildSuite) TestBuildWithVolumeOwnership(c *testing.T) { // testing #1405 - config.Cmd does not get cleaned up if // utilizing cache func (s *DockerCLIBuildSuite) TestBuildEntrypointRunCleanup(c *testing.T) { - name := "testbuildcmdcleanup" + const name = "testbuildcmdcleanup" buildImageSuccessfully(c, name, build.WithDockerfile(`FROM busybox RUN echo "hello"`)) @@ -2179,7 +2179,7 @@ func (s *DockerCLIBuildSuite) TestBuildEntrypointRunCleanup(c *testing.T) { } func (s *DockerCLIBuildSuite) TestBuildAddFileNotFound(c *testing.T) { - name := "testbuildaddnotfound" + const name = "testbuildaddnotfound" buildImage(name, build.WithBuildContext(c, build.WithFile("Dockerfile", `FROM `+minimalBaseImage()+` @@ -2192,7 +2192,7 @@ func (s *DockerCLIBuildSuite) TestBuildAddFileNotFound(c *testing.T) { func (s *DockerCLIBuildSuite) TestBuildInheritance(c *testing.T) { testRequires(c, DaemonIsLinux) - name := "testbuildinheritance" + const name = "testbuildinheritance" buildImageSuccessfully(c, name, build.WithDockerfile(`FROM scratch EXPOSE 2375`)) @@ -2212,7 +2212,7 @@ func (s *DockerCLIBuildSuite) TestBuildInheritance(c *testing.T) { } func (s *DockerCLIBuildSuite) TestBuildFails(c *testing.T) { - name := "testbuildfails" + const name = "testbuildfails" buildImage(name, build.WithDockerfile(`FROM busybox RUN sh -c "exit 23"`)).Assert(c, icmd.Expected{ ExitCode: 23, @@ -2221,7 +2221,7 @@ func (s *DockerCLIBuildSuite) TestBuildFails(c *testing.T) { } func (s *DockerCLIBuildSuite) TestBuildOnBuild(c *testing.T) { - name := "testbuildonbuild" + const name = "testbuildonbuild" buildImageSuccessfully(c, name, build.WithDockerfile(`FROM busybox ONBUILD RUN touch foobar`)) buildImageSuccessfully(c, name, build.WithDockerfile(fmt.Sprintf(`FROM %s @@ -2234,7 +2234,7 @@ func (s *DockerCLIBuildSuite) TestBuildAddToSymlinkDest(c *testing.T) { if testEnv.DaemonInfo.OSType == "windows" { makeLink = `mklink /D C:\bar C:\foo` } - name := "testbuildaddtosymlinkdest" + const name = "testbuildaddtosymlinkdest" buildImageSuccessfully(c, name, build.WithBuildContext(c, build.WithFile("Dockerfile", ` FROM busybox @@ -2248,7 +2248,7 @@ func (s *DockerCLIBuildSuite) TestBuildAddToSymlinkDest(c *testing.T) { } func (s *DockerCLIBuildSuite) TestBuildEscapeWhitespace(c *testing.T) { - name := "testbuildescapewhitespace" + const name = "testbuildescapewhitespace" buildImageSuccessfully(c, name, build.WithDockerfile(` # ESCAPE=\ @@ -2266,20 +2266,20 @@ docker.com>" func (s *DockerCLIBuildSuite) TestBuildVerifyIntString(c *testing.T) { // Verify that strings that look like ints are still passed as strings - name := "testbuildstringing" + const name = "testbuildstringing" buildImageSuccessfully(c, name, build.WithDockerfile(` FROM busybox MAINTAINER 123`)) - out, _ := dockerCmd(c, "inspect", name) + out := cli.DockerCmd(c, "inspect", name).Stdout() if !strings.Contains(out, `"123"`) { c.Fatalf("Output does not contain the int as a string:\n%s", out) } } func (s *DockerCLIBuildSuite) TestBuildDockerignore(c *testing.T) { - name := "testbuilddockerignore" + const name = "testbuilddockerignore" buildImageSuccessfully(c, name, build.WithBuildContext(c, build.WithFile("Dockerfile", ` FROM busybox @@ -2317,7 +2317,7 @@ dir`), } func (s *DockerCLIBuildSuite) TestBuildDockerignoreCleanPaths(c *testing.T) { - name := "testbuilddockerignorecleanpaths" + const name = "testbuilddockerignorecleanpaths" buildImageSuccessfully(c, name, build.WithBuildContext(c, build.WithFile("Dockerfile", ` FROM busybox @@ -2331,7 +2331,7 @@ func (s *DockerCLIBuildSuite) TestBuildDockerignoreCleanPaths(c *testing.T) { } func (s *DockerCLIBuildSuite) TestBuildDockerignoreExceptions(c *testing.T) { - name := "testbuilddockerignoreexceptions" + const name = "testbuilddockerignoreexceptions" buildImageSuccessfully(c, name, build.WithBuildContext(c, build.WithFile("Dockerfile", ` FROM busybox @@ -2376,7 +2376,7 @@ dir } func (s *DockerCLIBuildSuite) TestBuildDockerignoringDockerfile(c *testing.T) { - name := "testbuilddockerignoredockerfile" + const name = "testbuilddockerignoredockerfile" dockerfile := ` FROM busybox ADD . /tmp/ @@ -2394,7 +2394,7 @@ func (s *DockerCLIBuildSuite) TestBuildDockerignoringDockerfile(c *testing.T) { } func (s *DockerCLIBuildSuite) TestBuildDockerignoringRenamedDockerfile(c *testing.T) { - name := "testbuilddockerignoredockerfile" + const name = "testbuilddockerignoredockerfile" dockerfile := ` FROM busybox ADD . /tmp/ @@ -2415,7 +2415,7 @@ func (s *DockerCLIBuildSuite) TestBuildDockerignoringRenamedDockerfile(c *testin } func (s *DockerCLIBuildSuite) TestBuildDockerignoringDockerignore(c *testing.T) { - name := "testbuilddockerignoredockerignore" + const name = "testbuilddockerignoredockerignore" dockerfile := ` FROM busybox ADD . /tmp/ @@ -2428,7 +2428,7 @@ func (s *DockerCLIBuildSuite) TestBuildDockerignoringDockerignore(c *testing.T) } func (s *DockerCLIBuildSuite) TestBuildDockerignoreTouchDockerfile(c *testing.T) { - name := "testbuilddockerignoretouchdockerfile" + const name = "testbuilddockerignoretouchdockerfile" dockerfile := ` FROM busybox ADD . /tmp/` @@ -2470,7 +2470,7 @@ func (s *DockerCLIBuildSuite) TestBuildDockerignoreTouchDockerfile(c *testing.T) } func (s *DockerCLIBuildSuite) TestBuildDockerignoringWholeDir(c *testing.T) { - name := "testbuilddockerignorewholedir" + const name = "testbuilddockerignorewholedir" dockerfile := ` FROM busybox @@ -2487,7 +2487,7 @@ func (s *DockerCLIBuildSuite) TestBuildDockerignoringWholeDir(c *testing.T) { } func (s *DockerCLIBuildSuite) TestBuildDockerignoringOnlyDotfiles(c *testing.T) { - name := "testbuilddockerignorewholedir" + const name = "testbuilddockerignorewholedir" dockerfile := ` FROM busybox @@ -2504,7 +2504,7 @@ func (s *DockerCLIBuildSuite) TestBuildDockerignoringOnlyDotfiles(c *testing.T) } func (s *DockerCLIBuildSuite) TestBuildDockerignoringBadExclusion(c *testing.T) { - name := "testbuilddockerignorebadexclusion" + const name = "testbuilddockerignorebadexclusion" buildImage(name, build.WithBuildContext(c, build.WithFile("Dockerfile", ` FROM busybox @@ -2538,7 +2538,7 @@ func (s *DockerCLIBuildSuite) TestBuildDockerignoringWildTopDir(c *testing.T) { build.WithFile(".dockerignore", variant), )) - dockerCmd(c, "rmi", "noname") + cli.DockerCmd(c, "rmi", "noname") } } @@ -2607,7 +2607,7 @@ dir1/dir3/** func (s *DockerCLIBuildSuite) TestBuildLineBreak(c *testing.T) { testRequires(c, DaemonIsLinux) - name := "testbuildlinebreak" + const name = "testbuildlinebreak" buildImageSuccessfully(c, name, build.WithDockerfile(`FROM busybox RUN sh -c 'echo root:testpass \ > /tmp/passwd' @@ -2618,7 +2618,7 @@ RUN sh -c "[ "$(ls -d /var/run/sshd)" = "/var/run/sshd" ]"`)) func (s *DockerCLIBuildSuite) TestBuildEOLInLine(c *testing.T) { testRequires(c, DaemonIsLinux) - name := "testbuildeolinline" + const name = "testbuildeolinline" buildImageSuccessfully(c, name, build.WithDockerfile(`FROM busybox RUN sh -c 'echo root:testpass > /tmp/passwd' RUN echo "foo \n bar"; echo "baz" @@ -2629,7 +2629,7 @@ RUN sh -c "[ "$(ls -d /var/run/sshd)" = "/var/run/sshd" ]"`)) func (s *DockerCLIBuildSuite) TestBuildCommentsShebangs(c *testing.T) { testRequires(c, DaemonIsLinux) - name := "testbuildcomments" + const name = "testbuildcomments" buildImageSuccessfully(c, name, build.WithDockerfile(`FROM busybox # This is an ordinary comment. RUN { echo '#!/bin/sh'; echo 'echo hello world'; } > /hello.sh @@ -2643,7 +2643,7 @@ RUN [ "$(/hello.sh)" = "hello world" ]`)) func (s *DockerCLIBuildSuite) TestBuildUsersAndGroups(c *testing.T) { testRequires(c, DaemonIsLinux) - name := "testbuildusers" + const name = "testbuildusers" buildImageSuccessfully(c, name, build.WithDockerfile(`FROM busybox # Make sure our defaults work @@ -2701,7 +2701,7 @@ func (s *DockerCLIBuildSuite) TestBuildEnvUsage(c *testing.T) { // /docker/world/hello is not owned by the correct user testRequires(c, NotUserNamespace) testRequires(c, DaemonIsLinux) - name := "testbuildenvusage" + const name = "testbuildenvusage" dockerfile := `FROM busybox ENV HOME /root ENV PATH $HOME/bin:$PATH @@ -2732,7 +2732,7 @@ func (s *DockerCLIBuildSuite) TestBuildEnvUsage2(c *testing.T) { // /docker/world/hello is not owned by the correct user testRequires(c, NotUserNamespace) testRequires(c, DaemonIsLinux) - name := "testbuildenvusage2" + const name = "testbuildenvusage2" dockerfile := `FROM busybox ENV abc=def def="hello world" RUN [ "$abc,$def" = "def,hello world" ] @@ -2799,7 +2799,7 @@ RUN [ "$eee1,$eee2,$eee3,$eee4" = 'foo,foo,foo,foo' ] func (s *DockerCLIBuildSuite) TestBuildAddScript(c *testing.T) { testRequires(c, DaemonIsLinux) - name := "testbuildaddscript" + const name = "testbuildaddscript" dockerfile := ` FROM busybox ADD test /test @@ -2816,7 +2816,7 @@ RUN [ "$(cat /testfile)" = 'test!' ]` func (s *DockerCLIBuildSuite) TestBuildAddTar(c *testing.T) { // /test/foo is not owned by the correct user testRequires(c, NotUserNamespace) - name := "testbuildaddtar" + const name = "testbuildaddtar" ctx := func() *fakecontext.Fake { dockerfile := ` @@ -2868,7 +2868,7 @@ RUN cat /existing-directory-trailing-slash/test/foo | grep Hi` } func (s *DockerCLIBuildSuite) TestBuildAddBrokenTar(c *testing.T) { - name := "testbuildaddbrokentar" + const name = "testbuildaddbrokentar" ctx := func() *fakecontext.Fake { dockerfile := ` @@ -2919,7 +2919,7 @@ ADD test.tar /` } func (s *DockerCLIBuildSuite) TestBuildAddNonTar(c *testing.T) { - name := "testbuildaddnontar" + const name = "testbuildaddnontar" // Should not try to extract test.tar buildImageSuccessfully(c, name, build.WithBuildContext(c, @@ -2935,7 +2935,7 @@ func (s *DockerCLIBuildSuite) TestBuildAddTarXz(c *testing.T) { // /test/foo is not owned by the correct user testRequires(c, NotUserNamespace) testRequires(c, DaemonIsLinux) - name := "testbuildaddtarxz" + const name = "testbuildaddtarxz" ctx := func() *fakecontext.Fake { dockerfile := ` @@ -2982,7 +2982,7 @@ func (s *DockerCLIBuildSuite) TestBuildAddTarXz(c *testing.T) { func (s *DockerCLIBuildSuite) TestBuildAddTarXzGz(c *testing.T) { testRequires(c, DaemonIsLinux) - name := "testbuildaddtarxzgz" + const name = "testbuildaddtarxzgz" ctx := func() *fakecontext.Fake { dockerfile := ` @@ -3034,7 +3034,7 @@ func (s *DockerCLIBuildSuite) TestBuildAddTarXzGz(c *testing.T) { // FIXME(vdemeester) most of the from git tests could be moved to `docker/cli` e2e tests func (s *DockerCLIBuildSuite) TestBuildFromGit(c *testing.T) { - name := "testbuildfromgit" + const name = "testbuildfromgit" git := fakegit.New(c, "repo", map[string]string{ "Dockerfile": `FROM busybox ADD first /first @@ -3053,7 +3053,7 @@ func (s *DockerCLIBuildSuite) TestBuildFromGit(c *testing.T) { } func (s *DockerCLIBuildSuite) TestBuildFromGitWithContext(c *testing.T) { - name := "testbuildfromgit" + const name = "testbuildfromgit" git := fakegit.New(c, "repo", map[string]string{ "docker/Dockerfile": `FROM busybox ADD first /first @@ -3072,7 +3072,7 @@ func (s *DockerCLIBuildSuite) TestBuildFromGitWithContext(c *testing.T) { } func (s *DockerCLIBuildSuite) TestBuildFromGitWithF(c *testing.T) { - name := "testbuildfromgitwithf" + const name = "testbuildfromgitwithf" git := fakegit.New(c, "repo", map[string]string{ "myApp/myDockerfile": `FROM busybox RUN echo hi from Dockerfile`, @@ -3085,7 +3085,7 @@ func (s *DockerCLIBuildSuite) TestBuildFromGitWithF(c *testing.T) { } func (s *DockerCLIBuildSuite) TestBuildFromRemoteTarball(c *testing.T) { - name := "testbuildfromremotetarball" + const name = "testbuildfromremotetarball" buffer := new(bytes.Buffer) tw := tar.NewWriter(buffer) @@ -3120,7 +3120,7 @@ func (s *DockerCLIBuildSuite) TestBuildFromRemoteTarball(c *testing.T) { } func (s *DockerCLIBuildSuite) TestBuildCleanupCmdOnEntrypoint(c *testing.T) { - name := "testbuildcmdcleanuponentrypoint" + const name = "testbuildcmdcleanuponentrypoint" buildImageSuccessfully(c, name, build.WithDockerfile(`FROM `+minimalBaseImage()+` CMD ["test"] @@ -3139,7 +3139,7 @@ func (s *DockerCLIBuildSuite) TestBuildCleanupCmdOnEntrypoint(c *testing.T) { } func (s *DockerCLIBuildSuite) TestBuildClearCmd(c *testing.T) { - name := "testbuildclearcmd" + const name = "testbuildclearcmd" buildImageSuccessfully(c, name, build.WithDockerfile(`FROM `+minimalBaseImage()+` ENTRYPOINT ["/bin/bash"] CMD []`)) @@ -3154,7 +3154,7 @@ func (s *DockerCLIBuildSuite) TestBuildEmptyCmd(c *testing.T) { // Skip on Windows. Base image on Windows has a CMD set in the image. testRequires(c, DaemonIsLinux) - name := "testbuildemptycmd" + const name = "testbuildemptycmd" buildImageSuccessfully(c, name, build.WithDockerfile("FROM "+minimalBaseImage()+"\nMAINTAINER quux\n")) res := inspectFieldJSON(c, name, "Config.Cmd") @@ -3164,7 +3164,7 @@ func (s *DockerCLIBuildSuite) TestBuildEmptyCmd(c *testing.T) { } func (s *DockerCLIBuildSuite) TestBuildOnBuildOutput(c *testing.T) { - name := "testbuildonbuildparent" + const name = "testbuildonbuildparent" buildImageSuccessfully(c, name, build.WithDockerfile("FROM busybox\nONBUILD RUN echo foo\n")) buildImage(name, build.WithDockerfile("FROM "+name+"\nMAINTAINER quux\n")).Assert(c, icmd.Expected{ @@ -3182,7 +3182,7 @@ func (s *DockerCLIBuildSuite) TestBuildInvalidTag(c *testing.T) { } func (s *DockerCLIBuildSuite) TestBuildCmdShDashC(c *testing.T) { - name := "testbuildcmdshc" + const name = "testbuildcmdshc" buildImageSuccessfully(c, name, build.WithDockerfile("FROM busybox\nCMD echo cmd\n")) res := inspectFieldJSON(c, name, "Config.Cmd") @@ -3199,7 +3199,7 @@ func (s *DockerCLIBuildSuite) TestBuildCmdSpaces(c *testing.T) { // Test to make sure that when we strcat arrays we take into account // the arg separator to make sure ["echo","hi"] and ["echo hi"] don't // look the same - name := "testbuildcmdspaces" + const name = "testbuildcmdspaces" buildImageSuccessfully(c, name, build.WithDockerfile("FROM busybox\nCMD [\"echo hi\"]\n")) id1 := getIDByName(c, name) @@ -3222,7 +3222,7 @@ func (s *DockerCLIBuildSuite) TestBuildCmdSpaces(c *testing.T) { } func (s *DockerCLIBuildSuite) TestBuildCmdJSONNoShDashC(c *testing.T) { - name := "testbuildcmdjson" + const name = "testbuildcmdjson" buildImageSuccessfully(c, name, build.WithDockerfile("FROM busybox\nCMD [\"echo\", \"cmd\"]")) res := inspectFieldJSON(c, name, "Config.Cmd") @@ -3277,15 +3277,15 @@ func (s *DockerCLIBuildSuite) TestBuildEntrypointCanBeOverriddenByChildInspect(c } func (s *DockerCLIBuildSuite) TestBuildRunShEntrypoint(c *testing.T) { - name := "testbuildentrypoint" + const name = "testbuildentrypoint" buildImageSuccessfully(c, name, build.WithDockerfile(`FROM busybox ENTRYPOINT echo`)) - dockerCmd(c, "run", "--rm", name) + cli.DockerCmd(c, "run", "--rm", name) } func (s *DockerCLIBuildSuite) TestBuildExoticShellInterpolation(c *testing.T) { testRequires(c, DaemonIsLinux) - name := "testbuildexoticshellinterpolation" + const name = "testbuildexoticshellinterpolation" buildImageSuccessfully(c, name, build.WithDockerfile(` FROM busybox @@ -3314,7 +3314,7 @@ func (s *DockerCLIBuildSuite) TestBuildVerifySingleQuoteFails(c *testing.T) { // of double quotes (per the JSON spec). This means we interpret it // as a "string" instead of "JSON array" and pass it on to "sh -c" and // it should barf on it. - name := "testbuildsinglequotefails" + const name = "testbuildsinglequotefails" expectedExitCode := 2 buildImageSuccessfully(c, name, build.WithDockerfile(`FROM busybox @@ -3326,7 +3326,7 @@ func (s *DockerCLIBuildSuite) TestBuildVerifySingleQuoteFails(c *testing.T) { } func (s *DockerCLIBuildSuite) TestBuildVerboseOut(c *testing.T) { - name := "testbuildverboseout" + const name = "testbuildverboseout" expected := "\n123\n" if testEnv.DaemonInfo.OSType == "windows" { @@ -3340,7 +3340,7 @@ RUN echo 123`)).Assert(c, icmd.Expected{ } func (s *DockerCLIBuildSuite) TestBuildWithTabs(c *testing.T) { - name := "testbuildwithtabs" + const name = "testbuildwithtabs" buildImageSuccessfully(c, name, build.WithDockerfile("FROM busybox\nRUN echo\tone\t\ttwo")) res := inspectFieldJSON(c, name, "ContainerConfig.Cmd") expected1 := `["/bin/sh","-c","echo\tone\t\ttwo"]` @@ -3355,7 +3355,7 @@ func (s *DockerCLIBuildSuite) TestBuildWithTabs(c *testing.T) { } func (s *DockerCLIBuildSuite) TestBuildLabels(c *testing.T) { - name := "testbuildlabel" + const name = "testbuildlabel" expected := `{"License":"GPL","Vendor":"Acme"}` buildImageSuccessfully(c, name, build.WithDockerfile(`FROM busybox LABEL Vendor=Acme @@ -3367,7 +3367,7 @@ func (s *DockerCLIBuildSuite) TestBuildLabels(c *testing.T) { } func (s *DockerCLIBuildSuite) TestBuildLabelsCache(c *testing.T) { - name := "testbuildlabelcache" + const name = "testbuildlabelcache" buildImageSuccessfully(c, name, build.WithDockerfile(`FROM busybox LABEL Vendor=Acme`)) @@ -3510,7 +3510,7 @@ func (s *DockerCLIBuildSuite) TestBuildNotVerboseFailureRemote(c *testing.T) { // stderr in verbose mode are identical. // TODO(vdemeester) with cobra, stdout has a carriage return too much so this test should not check stdout URL := "http://something.invalid" - name := "quiet_build_wrong_remote" + const name = "quiet_build_wrong_remote" quietResult := buildImage(name, cli.WithFlags("-q"), build.WithContextPath(URL)) quietResult.Assert(c, icmd.Expected{ ExitCode: 1, @@ -3538,7 +3538,7 @@ func (s *DockerCLIBuildSuite) TestBuildNotVerboseFailureRemote(c *testing.T) { func (s *DockerCLIBuildSuite) TestBuildStderr(c *testing.T) { // This test just makes sure that no non-error output goes // to stderr - name := "testbuildstderr" + const name = "testbuildstderr" result := buildImage(name, build.WithDockerfile("FROM busybox\nRUN echo one")) result.Assert(c, icmd.Success) @@ -3556,7 +3556,7 @@ func (s *DockerCLIBuildSuite) TestBuildStderr(c *testing.T) { func (s *DockerCLIBuildSuite) TestBuildChownSingleFile(c *testing.T) { testRequires(c, UnixCli, DaemonIsLinux) // test uses chown: not available on windows - name := "testbuildchownsinglefile" + const name = "testbuildchownsinglefile" ctx := fakecontext.New(c, "", fakecontext.WithDockerfile(` @@ -3578,7 +3578,7 @@ RUN [ $(ls -l /test | awk '{print $3":"$4}') = 'root:root' ] } func (s *DockerCLIBuildSuite) TestBuildSymlinkBreakout(c *testing.T) { - name := "testbuildsymlinkbreakout" + const name = "testbuildsymlinkbreakout" tmpdir, err := os.MkdirTemp("", name) assert.NilError(c, err) @@ -3636,7 +3636,7 @@ func (s *DockerCLIBuildSuite) TestBuildXZHost(c *testing.T) { // /usr/local/sbin/xz gets permission denied for the user testRequires(c, NotUserNamespace) testRequires(c, DaemonIsLinux) - name := "testbuildxzhost" + const name = "testbuildxzhost" buildImageSuccessfully(c, name, build.WithBuildContext(c, build.WithFile("Dockerfile", ` @@ -3673,7 +3673,7 @@ CMD cat /foo/file`), build.WithFile("content", expected), )) - out, _ := dockerCmd(c, "run", "--rm", name) + out := cli.DockerCmd(c, "run", "--rm", name).Combined() if out != expected { c.Fatalf("expected file contents for /foo/file to be %q but received %q", expected, out) } @@ -3754,7 +3754,7 @@ RUN sh -c "find /tmp/" # sh -c is needed on Windows to use the correct find`) } func (s *DockerCLIBuildSuite) TestBuildFromOfficialNames(c *testing.T) { - name := "testbuildfromofficial" + const name = "testbuildfromofficial" fromNames := []string{ "busybox", "docker.io/busybox", @@ -3766,7 +3766,7 @@ func (s *DockerCLIBuildSuite) TestBuildFromOfficialNames(c *testing.T) { for idx, fromName := range fromNames { imgName := fmt.Sprintf("%s%d", name, idx) buildImageSuccessfully(c, imgName, build.WithDockerfile("FROM "+fromName)) - dockerCmd(c, "rmi", imgName) + cli.DockerCmd(c, "rmi", imgName) } } @@ -3774,7 +3774,7 @@ func (s *DockerCLIBuildSuite) TestBuildFromOfficialNames(c *testing.T) { func (s *DockerCLIBuildSuite) TestBuildSpaces(c *testing.T) { // Test to make sure that leading/trailing spaces on a command // doesn't change the error msg we get - name := "testspaces" + const name = "testspaces" ctx := fakecontext.New(c, "", fakecontext.WithDockerfile("FROM busybox\nCOPY\n")) defer ctx.Close() @@ -3835,7 +3835,7 @@ func (s *DockerCLIBuildSuite) TestBuildSpaces(c *testing.T) { func (s *DockerCLIBuildSuite) TestBuildSpacesWithQuotes(c *testing.T) { // Test to make sure that spaces in quotes aren't lost - name := "testspacesquotes" + const name = "testspacesquotes" dockerfile := `FROM busybox RUN echo " \ @@ -3927,7 +3927,7 @@ func (s *DockerCLIBuildSuite) TestBuildDotDotFile(c *testing.T) { func (s *DockerCLIBuildSuite) TestBuildRUNoneJSON(c *testing.T) { testRequires(c, DaemonIsLinux) // No hello-world Windows image - name := "testbuildrunonejson" + const name = "testbuildrunonejson" buildImage(name, build.WithDockerfile(`FROM hello-world:frozen RUN [ "/hello" ]`)).Assert(c, icmd.Expected{ @@ -3936,7 +3936,7 @@ RUN [ "/hello" ]`)).Assert(c, icmd.Expected{ } func (s *DockerCLIBuildSuite) TestBuildEmptyStringVolume(c *testing.T) { - name := "testbuildemptystringvolume" + const name = "testbuildemptystringvolume" buildImage(name, build.WithDockerfile(` FROM busybox @@ -3979,7 +3979,7 @@ func (s *DockerCLIBuildSuite) TestBuildNoDupOutput(c *testing.T) { // Check to make sure our build output prints the Dockerfile cmd // property - there was a bug that caused it to be duplicated on the // Step X line - name := "testbuildnodupoutput" + const name = "testbuildnodupoutput" result := buildImage(name, build.WithDockerfile(` FROM busybox RUN env`)) @@ -3994,7 +3994,7 @@ func (s *DockerCLIBuildSuite) TestBuildNoDupOutput(c *testing.T) { // FIXME(vdemeester) could be a unit test func (s *DockerCLIBuildSuite) TestBuildStartsFromOne(c *testing.T) { // Explicit check to ensure that build starts from step 1 rather than 0 - name := "testbuildstartsfromone" + const name = "testbuildstartsfromone" result := buildImage(name, build.WithDockerfile(`FROM busybox`)) result.Assert(c, icmd.Success) exp := "\nStep 1/1 : FROM busybox\n" @@ -4006,7 +4006,7 @@ func (s *DockerCLIBuildSuite) TestBuildStartsFromOne(c *testing.T) { func (s *DockerCLIBuildSuite) TestBuildRUNErrMsg(c *testing.T) { // Test to make sure the bad command is quoted with just "s and // not as a Go []string - name := "testbuildbadrunerrmsg" + const name = "testbuildbadrunerrmsg" shell := "/bin/sh -c" exitCode := 127 if testEnv.DaemonInfo.OSType == "windows" { @@ -4026,7 +4026,7 @@ func (s *DockerCLIBuildSuite) TestBuildRUNErrMsg(c *testing.T) { // Issue #15634: COPY fails when path starts with "null" func (s *DockerCLIBuildSuite) TestBuildNullStringInAddCopyVolume(c *testing.T) { - name := "testbuildnullstringinaddcopyvolume" + const name = "testbuildnullstringinaddcopyvolume" volName := "nullvolume" if testEnv.DaemonInfo.OSType == "windows" { volName = `C:\\nullvolume` @@ -4056,7 +4056,7 @@ func (s *DockerCLIBuildSuite) TestBuildStopSignal(c *testing.T) { } containerName := "test-container-stop-signal" - dockerCmd(c, "run", "-d", "--name", containerName, imgName, "top") + cli.DockerCmd(c, "run", "-d", "--name", containerName, imgName, "top") res = inspectFieldJSON(c, containerName, "Config.StopSignal") if res != `"SIGKILL"` { c.Fatalf("Signal %s, expected SIGKILL", res) @@ -4088,7 +4088,7 @@ func (s *DockerCLIBuildSuite) TestBuildBuildTimeArg(c *testing.T) { }) containerName := "bldargCont" - out, _ := dockerCmd(c, "run", "--name", containerName, imgName) + out := cli.DockerCmd(c, "run", "--name", containerName, imgName).Combined() out = strings.Trim(out, " \r\n'") if out != "" { c.Fatalf("run produced invalid output: %q, expected empty string", out) @@ -4109,7 +4109,7 @@ func (s *DockerCLIBuildSuite) TestBuildBuildTimeArgHistory(c *testing.T) { Out: envVal, }) - out, _ := dockerCmd(c, "history", "--no-trunc", imgName) + out := cli.DockerCmd(c, "history", "--no-trunc", imgName).Combined() outputTabs := strings.Split(out, "\n")[1] if !strings.Contains(outputTabs, envDef) { c.Fatalf("failed to find arg default in image history output: %q expected: %q", outputTabs, envDef) @@ -4259,7 +4259,7 @@ func (s *DockerCLIBuildSuite) TestBuildBuildTimeArgOverrideArgDefinedBeforeEnv(c } containerName := "bldargCont" - if out, _ := dockerCmd(c, "run", "--name", containerName, imgName); !strings.Contains(out, envValOverride) { + if out := cli.DockerCmd(c, "run", "--name", containerName, imgName).Combined(); !strings.Contains(out, envValOverride) { c.Fatalf("run produced invalid output: %q, expected %q", out, envValOverride) } } @@ -4287,7 +4287,7 @@ func (s *DockerCLIBuildSuite) TestBuildBuildTimeArgOverrideEnvDefinedBeforeArg(c } containerName := "bldargCont" - if out, _ := dockerCmd(c, "run", "--name", containerName, imgName); !strings.Contains(out, envValOverride) { + if out := cli.DockerCmd(c, "run", "--name", containerName, imgName).Combined(); !strings.Contains(out, envValOverride) { c.Fatalf("run produced invalid output: %q, expected %q", out, envValOverride) } } @@ -4405,7 +4405,7 @@ func (s *DockerCLIBuildSuite) TestBuildBuildTimeArgExpansionOverride(c *testing. } containerName := "bldargCont" - if out, _ := dockerCmd(c, "run", "--name", containerName, imgName); !strings.Contains(out, envValOverride) { + if out := cli.DockerCmd(c, "run", "--name", containerName, imgName).Combined(); !strings.Contains(out, envValOverride) { c.Fatalf("run produced invalid output: %q, expected %q", out, envValOverride) } } @@ -4429,7 +4429,7 @@ func (s *DockerCLIBuildSuite) TestBuildBuildTimeArgUntrustedDefinedAfterUse(c *t } containerName := "bldargCont" - if out, _ := dockerCmd(c, "run", "--name", containerName, imgName); out != "\n" { + if out := cli.DockerCmd(c, "run", "--name", containerName, imgName).Combined(); out != "\n" { c.Fatalf("run produced invalid output: %q, expected empty string", out) } } @@ -4452,7 +4452,7 @@ func (s *DockerCLIBuildSuite) TestBuildBuildTimeArgBuiltinArg(c *testing.T) { c.Fatalf("failed to access environment variable in output: %q expected: %q", result.Combined(), envVal) } containerName := "bldargCont" - if out, _ := dockerCmd(c, "run", "--name", containerName, imgName); out != "\n" { + if out := cli.DockerCmd(c, "run", "--name", containerName, imgName).Combined(); out != "\n" { c.Fatalf("run produced invalid output: %q, expected empty string", out) } } @@ -4478,7 +4478,7 @@ func (s *DockerCLIBuildSuite) TestBuildBuildTimeArgDefaultOverride(c *testing.T) } containerName := "bldargCont" - if out, _ := dockerCmd(c, "run", "--name", containerName, imgName); !strings.Contains(out, envValOverride) { + if out := cli.DockerCmd(c, "run", "--name", containerName, imgName).Combined(); !strings.Contains(out, envValOverride) { c.Fatalf("run produced invalid output: %q, expected %q", out, envValOverride) } } @@ -4692,7 +4692,7 @@ func (s *DockerCLIBuildSuite) TestBuildNoNamedVolume(c *testing.T) { if testEnv.DaemonInfo.OSType == "windows" { volName = "testname:C:\\foo" } - dockerCmd(c, "run", "-v", volName, "busybox", "sh", "-c", "touch /foo/oops") + cli.DockerCmd(c, "run", "-v", volName, "busybox", "sh", "-c", "touch /foo/oops") dockerFile := `FROM busybox VOLUME ` + volName + ` @@ -4712,7 +4712,7 @@ func (s *DockerCLIBuildSuite) TestBuildTagEvent(c *testing.T) { buildImageSuccessfully(c, "test", build.WithDockerfile(dockerFile)) until := daemonUnixTime(c) - out, _ := dockerCmd(c, "events", "--since", since, "--until", until, "--filter", "type=image") + out := cli.DockerCmd(c, "events", "--since", since, "--until", until, "--filter", "type=image").Stdout() events := strings.Split(strings.TrimSpace(out), "\n") actions := eventActionsByIDAndType(c, events, "test:latest", "image") var foundTag bool @@ -4741,7 +4741,7 @@ func (s *DockerCLIBuildSuite) TestBuildMultipleTags(c *testing.T) { // #17290 func (s *DockerCLIBuildSuite) TestBuildCacheBrokenSymlink(c *testing.T) { - name := "testbuildbrokensymlink" + const name = "testbuildbrokensymlink" ctx := fakecontext.New(c, "", fakecontext.WithDockerfile(` FROM busybox @@ -4768,7 +4768,7 @@ func (s *DockerCLIBuildSuite) TestBuildCacheBrokenSymlink(c *testing.T) { } func (s *DockerCLIBuildSuite) TestBuildFollowSymlinkToFile(c *testing.T) { - name := "testbuildbrokensymlink" + const name = "testbuildbrokensymlink" ctx := fakecontext.New(c, "", fakecontext.WithDockerfile(` FROM busybox @@ -4797,7 +4797,7 @@ func (s *DockerCLIBuildSuite) TestBuildFollowSymlinkToFile(c *testing.T) { } func (s *DockerCLIBuildSuite) TestBuildFollowSymlinkToDir(c *testing.T) { - name := "testbuildbrokensymlink" + const name = "testbuildbrokensymlink" ctx := fakecontext.New(c, "", fakecontext.WithDockerfile(` FROM busybox @@ -4829,7 +4829,7 @@ func (s *DockerCLIBuildSuite) TestBuildFollowSymlinkToDir(c *testing.T) { // TestBuildSymlinkBasename tests that target file gets basename from symlink, // not from the target file. func (s *DockerCLIBuildSuite) TestBuildSymlinkBasename(c *testing.T) { - name := "testbuildbrokensymlink" + const name = "testbuildbrokensymlink" ctx := fakecontext.New(c, "", fakecontext.WithDockerfile(` FROM busybox @@ -4850,7 +4850,7 @@ func (s *DockerCLIBuildSuite) TestBuildSymlinkBasename(c *testing.T) { // #17827 func (s *DockerCLIBuildSuite) TestBuildCacheRootSource(c *testing.T) { - name := "testbuildrootsource" + const name = "testbuildrootsource" ctx := fakecontext.New(c, "", fakecontext.WithDockerfile(` FROM busybox @@ -4891,7 +4891,7 @@ func (s *DockerCLIBuildSuite) TestBuildFailsGitNotCallable(c *testing.T) { // TestBuildWorkdirWindowsPath tests that a Windows style path works as a workdir func (s *DockerCLIBuildSuite) TestBuildWorkdirWindowsPath(c *testing.T) { testRequires(c, DaemonIsWindows) - name := "testbuildworkdirwindowspath" + const name = "testbuildworkdirwindowspath" buildImageSuccessfully(c, name, build.WithDockerfile(` FROM `+testEnv.PlatformDefaults.BaseImage+` RUN mkdir C:\\work @@ -4901,7 +4901,7 @@ func (s *DockerCLIBuildSuite) TestBuildWorkdirWindowsPath(c *testing.T) { } func (s *DockerCLIBuildSuite) TestBuildLabel(c *testing.T) { - name := "testbuildlabel" + const name = "testbuildlabel" testLabel := "foo" buildImageSuccessfully(c, name, cli.WithFlags("--label", testLabel), @@ -4918,7 +4918,7 @@ func (s *DockerCLIBuildSuite) TestBuildLabel(c *testing.T) { } func (s *DockerCLIBuildSuite) TestBuildLabelOneNode(c *testing.T) { - name := "testbuildlabel" + const name = "testbuildlabel" buildImageSuccessfully(c, name, cli.WithFlags("--label", "foo=bar"), build.WithDockerfile("FROM busybox")) @@ -4932,7 +4932,7 @@ func (s *DockerCLIBuildSuite) TestBuildLabelOneNode(c *testing.T) { } func (s *DockerCLIBuildSuite) TestBuildLabelCacheCommit(c *testing.T) { - name := "testbuildlabelcachecommit" + const name = "testbuildlabelcachecommit" testLabel := "foo" buildImageSuccessfully(c, name, build.WithDockerfile(` @@ -4953,7 +4953,7 @@ func (s *DockerCLIBuildSuite) TestBuildLabelCacheCommit(c *testing.T) { } func (s *DockerCLIBuildSuite) TestBuildLabelMultiple(c *testing.T) { - name := "testbuildlabelmultiple" + const name = "testbuildlabelmultiple" testLabels := map[string]string{ "foo": "bar", "123": "456", @@ -4979,7 +4979,7 @@ func (s *DockerCLIBuildSuite) TestBuildLabelMultiple(c *testing.T) { } func (s *DockerRegistryAuthHtpasswdSuite) TestBuildFromAuthenticatedRegistry(c *testing.T) { - dockerCmd(c, "login", "-u", s.reg.Username(), "-p", s.reg.Password(), privateRegistryURL) + cli.DockerCmd(c, "login", "-u", s.reg.Username(), "-p", s.reg.Password(), privateRegistryURL) baseImage := privateRegistryURL + "/baseimage" buildImageSuccessfully(c, baseImage, build.WithDockerfile(` @@ -4987,8 +4987,8 @@ func (s *DockerRegistryAuthHtpasswdSuite) TestBuildFromAuthenticatedRegistry(c * ENV env1 val1 `)) - dockerCmd(c, "push", baseImage) - dockerCmd(c, "rmi", baseImage) + cli.DockerCmd(c, "push", baseImage) + cli.DockerCmd(c, "rmi", baseImage) buildImageSuccessfully(c, baseImage, build.WithDockerfile(fmt.Sprintf(` FROM %s @@ -5017,16 +5017,16 @@ func (s *DockerRegistryAuthHtpasswdSuite) TestBuildWithExternalAuth(c *testing.T err = os.WriteFile(configPath, []byte(externalAuthConfig), 0o644) assert.NilError(c, err) - dockerCmd(c, "--config", tmp, "login", "-u", s.reg.Username(), "-p", s.reg.Password(), privateRegistryURL) + cli.DockerCmd(c, "--config", tmp, "login", "-u", s.reg.Username(), "-p", s.reg.Password(), privateRegistryURL) b, err := os.ReadFile(configPath) assert.NilError(c, err) assert.Assert(c, !strings.Contains(string(b), "\"auth\":")) - dockerCmd(c, "--config", tmp, "tag", "busybox", repoName) - dockerCmd(c, "--config", tmp, "push", repoName) + cli.DockerCmd(c, "--config", tmp, "tag", "busybox", repoName) + cli.DockerCmd(c, "--config", tmp, "push", repoName) // make sure the image is pulled when building - dockerCmd(c, "rmi", repoName) + cli.DockerCmd(c, "rmi", repoName) icmd.RunCmd(icmd.Cmd{ Command: []string{dockerBinary, "--config", tmp, "build", "-"}, @@ -5115,7 +5115,7 @@ func (s *DockerCLIBuildSuite) TestBuildLabelsOverride(c *testing.T) { // Test case for #22855 func (s *DockerCLIBuildSuite) TestBuildDeleteCommittedFile(c *testing.T) { - name := "test-delete-committed-file" + const name = "test-delete-committed-file" buildImageSuccessfully(c, name, build.WithDockerfile(`FROM busybox RUN echo test > file RUN test -e file @@ -5130,7 +5130,7 @@ func (s *DockerCLIBuildSuite) TestBuildDockerignoreComment(c *testing.T) { // it is more reliable, but that's not a good fix. testRequires(c, DaemonIsLinux) - name := "testbuilddockerignorecleanpaths" + const name = "testbuilddockerignorecleanpaths" dockerfile := ` FROM busybox ADD . /tmp/ @@ -5159,7 +5159,7 @@ foo2 // Test case for #23221 func (s *DockerCLIBuildSuite) TestBuildWithUTF8BOM(c *testing.T) { - name := "test-with-utf8-bom" + const name = "test-with-utf8-bom" dockerfile := []byte(`FROM busybox`) bomDockerfile := append([]byte{0xEF, 0xBB, 0xBF}, dockerfile...) buildImageSuccessfully(c, name, build.WithBuildContext(c, @@ -5169,7 +5169,7 @@ func (s *DockerCLIBuildSuite) TestBuildWithUTF8BOM(c *testing.T) { // Test case for UTF-8 BOM in .dockerignore, related to #23221 func (s *DockerCLIBuildSuite) TestBuildWithUTF8BOMDockerignore(c *testing.T) { - name := "test-with-utf8-bom-dockerignore" + const name = "test-with-utf8-bom-dockerignore" dockerfile := ` FROM busybox ADD . /tmp/ @@ -5186,7 +5186,7 @@ func (s *DockerCLIBuildSuite) TestBuildWithUTF8BOMDockerignore(c *testing.T) { // #22489 Shell test to confirm config gets updated correctly func (s *DockerCLIBuildSuite) TestBuildShellUpdatesConfig(c *testing.T) { - name := "testbuildshellupdatesconfig" + const name = "testbuildshellupdatesconfig" buildImageSuccessfully(c, name, build.WithDockerfile(`FROM `+minimalBaseImage()+` SHELL ["foo", "-bar"]`)) @@ -5203,7 +5203,7 @@ func (s *DockerCLIBuildSuite) TestBuildShellUpdatesConfig(c *testing.T) { // #22489 Changing the shell multiple times and CMD after. func (s *DockerCLIBuildSuite) TestBuildShellMultiple(c *testing.T) { - name := "testbuildshellmultiple" + const name = "testbuildshellmultiple" result := buildImage(name, build.WithDockerfile(`FROM busybox RUN echo defaultshell @@ -5231,7 +5231,7 @@ func (s *DockerCLIBuildSuite) TestBuildShellMultiple(c *testing.T) { // A container started from the image uses the shell-form CMD. // Last shell is ls. CMD is -l. So should contain 'total '. - outrun, _ := dockerCmd(c, "run", "--rm", name) + outrun := cli.DockerCmd(c, "run", "--rm", name).Combined() if !strings.Contains(outrun, "total ") { c.Fatalf("Expected started container to run ls -l. %s", outrun) } @@ -5239,14 +5239,14 @@ func (s *DockerCLIBuildSuite) TestBuildShellMultiple(c *testing.T) { // #22489. Changed SHELL with ENTRYPOINT func (s *DockerCLIBuildSuite) TestBuildShellEntrypoint(c *testing.T) { - name := "testbuildshellentrypoint" + const name = "testbuildshellentrypoint" buildImageSuccessfully(c, name, build.WithDockerfile(`FROM busybox SHELL ["ls"] ENTRYPOINT -l`)) // A container started from the image uses the shell-form ENTRYPOINT. // Shell is ls. ENTRYPOINT is -l. So should contain 'total '. - outrun, _ := dockerCmd(c, "run", "--rm", name) + outrun := cli.DockerCmd(c, "run", "--rm", name).Combined() if !strings.Contains(outrun, "total ") { c.Fatalf("Expected started container to run ls -l. %s", outrun) } @@ -5254,10 +5254,10 @@ func (s *DockerCLIBuildSuite) TestBuildShellEntrypoint(c *testing.T) { // #22489 Shell test to confirm shell is inherited in a subsequent build func (s *DockerCLIBuildSuite) TestBuildShellInherited(c *testing.T) { - name1 := "testbuildshellinherited1" + const name1 = "testbuildshellinherited1" buildImageSuccessfully(c, name1, build.WithDockerfile(`FROM busybox SHELL ["ls"]`)) - name2 := "testbuildshellinherited2" + const name2 = "testbuildshellinherited2" buildImage(name2, build.WithDockerfile(`FROM `+name1+` RUN -l`)).Assert(c, icmd.Expected{ // ls -l has "total " followed by some number in it, ls without -l does not. @@ -5267,7 +5267,7 @@ func (s *DockerCLIBuildSuite) TestBuildShellInherited(c *testing.T) { // #22489 Shell test to confirm non-JSON doesn't work func (s *DockerCLIBuildSuite) TestBuildShellNotJSON(c *testing.T) { - name := "testbuildshellnotjson" + const name = "testbuildshellnotjson" buildImage(name, build.WithDockerfile(`FROM `+minimalBaseImage()+` sHeLl exec -form`, // Casing explicit to ensure error is upper-cased. @@ -5281,7 +5281,7 @@ func (s *DockerCLIBuildSuite) TestBuildShellNotJSON(c *testing.T) { // This would error if the default shell were still cmd. func (s *DockerCLIBuildSuite) TestBuildShellWindowsPowershell(c *testing.T) { testRequires(c, DaemonIsWindows) - name := "testbuildshellpowershell" + const name = "testbuildshellpowershell" buildImage(name, build.WithDockerfile(`FROM `+minimalBaseImage()+` SHELL ["powershell", "-command"] RUN Write-Host John`)).Assert(c, icmd.Expected{ @@ -5293,16 +5293,16 @@ func (s *DockerCLIBuildSuite) TestBuildShellWindowsPowershell(c *testing.T) { // Tests WORKDIR, ADD func (s *DockerCLIBuildSuite) TestBuildEscapeNotBackslashWordTest(c *testing.T) { testRequires(c, DaemonIsWindows) - name := "testbuildescapenotbackslashwordtesta" - buildImage(name, build.WithDockerfile(`# escape= `+"`"+` + const name1 = "testbuildescapenotbackslashwordtesta" + buildImage(name1, build.WithDockerfile(`# escape= `+"`"+` FROM `+minimalBaseImage()+` WORKDIR c:\windows RUN dir /w`)).Assert(c, icmd.Expected{ Out: "[System32]", }) - name = "testbuildescapenotbackslashwordtestb" - buildImage(name, build.WithDockerfile(`# escape= `+"`"+` + const name2 = "testbuildescapenotbackslashwordtestb" + buildImage(name2, build.WithDockerfile(`# escape= `+"`"+` FROM `+minimalBaseImage()+` SHELL ["powershell.exe"] WORKDIR c:\foo @@ -5316,7 +5316,7 @@ func (s *DockerCLIBuildSuite) TestBuildEscapeNotBackslashWordTest(c *testing.T) // but an exec-form CMD is marked. func (s *DockerCLIBuildSuite) TestBuildCmdShellArgsEscaped(c *testing.T) { testRequires(c, DaemonIsWindows) - name1 := "testbuildcmdshellescapedshellform" + const name1 = "testbuildcmdshellescapedshellform" buildImageSuccessfully(c, name1, build.WithDockerfile(` FROM `+minimalBaseImage()+` CMD "ipconfig" @@ -5325,8 +5325,8 @@ func (s *DockerCLIBuildSuite) TestBuildCmdShellArgsEscaped(c *testing.T) { if res != "true" { c.Fatalf("CMD did not update Config.ArgsEscaped on image: %v", res) } - dockerCmd(c, "run", "--name", "inspectme1", name1) - dockerCmd(c, "wait", "inspectme1") + cli.DockerCmd(c, "run", "--name", "inspectme1", name1) + cli.DockerCmd(c, "wait", "inspectme1") res = inspectFieldJSON(c, name1, "Config.Cmd") if res != `["cmd /S /C \"ipconfig\""]` { @@ -5334,7 +5334,7 @@ func (s *DockerCLIBuildSuite) TestBuildCmdShellArgsEscaped(c *testing.T) { } // Now in JSON/exec-form - name2 := "testbuildcmdshellescapedexecform" + const name2 = "testbuildcmdshellescapedexecform" buildImageSuccessfully(c, name2, build.WithDockerfile(` FROM `+minimalBaseImage()+` CMD ["ipconfig"] @@ -5343,8 +5343,8 @@ func (s *DockerCLIBuildSuite) TestBuildCmdShellArgsEscaped(c *testing.T) { if res != "false" { c.Fatalf("CMD set Config.ArgsEscaped on image: %v", res) } - dockerCmd(c, "run", "--name", "inspectme2", name2) - dockerCmd(c, "wait", "inspectme2") + cli.DockerCmd(c, "run", "--name", "inspectme2", name2) + cli.DockerCmd(c, "wait", "inspectme2") res = inspectFieldJSON(c, name2, "Config.Cmd") if res != `["ipconfig"]` { @@ -5354,7 +5354,7 @@ func (s *DockerCLIBuildSuite) TestBuildCmdShellArgsEscaped(c *testing.T) { // Test case for #24912. func (s *DockerCLIBuildSuite) TestBuildStepsWithProgress(c *testing.T) { - name := "testbuildstepswithprogress" + const name = "testbuildstepswithprogress" totalRun := 5 result := buildImage(name, build.WithDockerfile("FROM busybox\n"+strings.Repeat("RUN echo foo\n", totalRun))) result.Assert(c, icmd.Success) @@ -5365,7 +5365,7 @@ func (s *DockerCLIBuildSuite) TestBuildStepsWithProgress(c *testing.T) { } func (s *DockerCLIBuildSuite) TestBuildWithFailure(c *testing.T) { - name := "testbuildwithfailure" + const name = "testbuildwithfailure" // First test case can only detect `nobody` in runtime so all steps will show up dockerfile := "FROM busybox\nRUN nobody" @@ -5523,7 +5523,7 @@ func (s *DockerCLIBuildSuite) TestBuildMultiStageCache(c *testing.T) { func (s *DockerCLIBuildSuite) TestBuildNetNone(c *testing.T) { testRequires(c, DaemonIsLinux) - name := "testbuildnetnone" + const name = "testbuildnetnone" buildImage(name, cli.WithFlags("--network=none"), build.WithDockerfile(` FROM busybox RUN ping -c 1 8.8.8.8 @@ -5536,23 +5536,23 @@ func (s *DockerCLIBuildSuite) TestBuildNetNone(c *testing.T) { func (s *DockerCLIBuildSuite) TestBuildNetContainer(c *testing.T) { testRequires(c, DaemonIsLinux) - id, _ := dockerCmd(c, "run", "--hostname", "foobar", "-d", "busybox", "nc", "-ll", "-p", "1234", "-e", "hostname") + id := cli.DockerCmd(c, "run", "--hostname", "foobar", "-d", "busybox", "nc", "-ll", "-p", "1234", "-e", "hostname").Stdout() - name := "testbuildnetcontainer" + const name = "testbuildnetcontainer" buildImageSuccessfully(c, name, cli.WithFlags("--network=container:"+strings.TrimSpace(id)), build.WithDockerfile(` FROM busybox RUN nc localhost 1234 > /otherhost `)) - host, _ := dockerCmd(c, "run", "testbuildnetcontainer", "cat", "/otherhost") + host := cli.DockerCmd(c, "run", "testbuildnetcontainer", "cat", "/otherhost").Combined() assert.Equal(c, strings.TrimSpace(host), "foobar") } func (s *DockerCLIBuildSuite) TestBuildWithExtraHost(c *testing.T) { testRequires(c, DaemonIsLinux) - name := "testbuildwithextrahost" + const name = "testbuildwithextrahost" buildImageSuccessfully(c, name, cli.WithFlags( "--add-host", "foo:127.0.0.1", @@ -5970,7 +5970,7 @@ func (s *DockerCLIBuildSuite) TestBuildOpaqueDirectory(c *testing.T) { // Windows test for USER in dockerfile func (s *DockerCLIBuildSuite) TestBuildWindowsUser(c *testing.T) { testRequires(c, DaemonIsWindows) - name := "testbuildwindowsuser" + const name = "testbuildwindowsuser" buildImage(name, build.WithDockerfile(`FROM `+testEnv.PlatformDefaults.BaseImage+` RUN net user user /add USER user @@ -5986,7 +5986,7 @@ func (s *DockerCLIBuildSuite) TestBuildWindowsUser(c *testing.T) { // directory. Fix for 27545 (found on Windows, but regression good for Linux too). // Note 27545 was reverted in 28505, but a new fix was added subsequently in 28514. func (s *DockerCLIBuildSuite) TestBuildCopyFileDotWithWorkdir(c *testing.T) { - name := "testbuildcopyfiledotwithworkdir" + const name = "testbuildcopyfiledotwithworkdir" buildImageSuccessfully(c, name, build.WithBuildContext(c, build.WithFile("Dockerfile", `FROM busybox WORKDIR /foo @@ -6000,7 +6000,7 @@ RUN ["cat", "/foo/file"] // Case-insensitive environment variables on Windows func (s *DockerCLIBuildSuite) TestBuildWindowsEnvCaseInsensitive(c *testing.T) { testRequires(c, DaemonIsWindows) - name := "testbuildwindowsenvcaseinsensitive" + const name = "testbuildwindowsenvcaseinsensitive" buildImageSuccessfully(c, name, build.WithDockerfile(` FROM `+testEnv.PlatformDefaults.BaseImage+` ENV FOO=bar foo=baz @@ -6018,7 +6018,7 @@ func (s *DockerCLIBuildSuite) TestBuildWorkdirImageCmd(c *testing.T) { FROM busybox WORKDIR /foo/bar `)) - out, _ := dockerCmd(c, "inspect", "--format", "{{ json .Config.Cmd }}", image) + out := cli.DockerCmd(c, "inspect", "--format", "{{ json .Config.Cmd }}", image).Stdout() assert.Equal(c, strings.TrimSpace(out), `["sh"]`) image = "testworkdirlabelimagecmd" @@ -6028,14 +6028,14 @@ WORKDIR /foo/bar LABEL a=b `)) - out, _ = dockerCmd(c, "inspect", "--format", "{{ json .Config.Cmd }}", image) + out = cli.DockerCmd(c, "inspect", "--format", "{{ json .Config.Cmd }}", image).Stdout() assert.Equal(c, strings.TrimSpace(out), `["sh"]`) } // Test case for 28902/28909 func (s *DockerCLIBuildSuite) TestBuildWorkdirCmd(c *testing.T) { testRequires(c, DaemonIsLinux) - name := "testbuildworkdircmd" + const name = "testbuildworkdircmd" dockerFile := ` FROM busybox WORKDIR / @@ -6048,7 +6048,7 @@ func (s *DockerCLIBuildSuite) TestBuildWorkdirCmd(c *testing.T) { // FIXME(vdemeester) should be a unit test func (s *DockerCLIBuildSuite) TestBuildLineErrorOnBuild(c *testing.T) { - name := "test_build_line_error_onbuild" + const name = "test_build_line_error_onbuild" buildImage(name, build.WithDockerfile(`FROM busybox ONBUILD `)).Assert(c, icmd.Expected{ @@ -6059,7 +6059,7 @@ func (s *DockerCLIBuildSuite) TestBuildLineErrorOnBuild(c *testing.T) { // FIXME(vdemeester) should be a unit test func (s *DockerCLIBuildSuite) TestBuildLineErrorUnknownInstruction(c *testing.T) { - name := "test_build_line_error_unknown_instruction" + const name = "test_build_line_error_unknown_instruction" cli.Docker(cli.Args("build", "-t", name), build.WithDockerfile(`FROM busybox RUN echo hello world NOINSTRUCTION echo ba @@ -6073,7 +6073,7 @@ func (s *DockerCLIBuildSuite) TestBuildLineErrorUnknownInstruction(c *testing.T) // FIXME(vdemeester) should be a unit test func (s *DockerCLIBuildSuite) TestBuildLineErrorWithEmptyLines(c *testing.T) { - name := "test_build_line_error_with_empty_lines" + const name = "test_build_line_error_with_empty_lines" cli.Docker(cli.Args("build", "-t", name), build.WithDockerfile(` FROM busybox @@ -6090,7 +6090,7 @@ func (s *DockerCLIBuildSuite) TestBuildLineErrorWithEmptyLines(c *testing.T) { // FIXME(vdemeester) should be a unit test func (s *DockerCLIBuildSuite) TestBuildLineErrorWithComments(c *testing.T) { - name := "test_build_line_error_with_comments" + const name = "test_build_line_error_with_comments" cli.Docker(cli.Args("build", "-t", name), build.WithDockerfile(`FROM busybox # This will print hello world # and then ba @@ -6113,7 +6113,7 @@ FROM build1 CMD echo foo `)) - out, _ := dockerCmd(c, "inspect", "--format", "{{ json .Config.Cmd }}", "build2") + out := cli.DockerCmd(c, "inspect", "--format", "{{ json .Config.Cmd }}", "build2").Stdout() expected := `["/bin/sh","-c","echo foo"]` if testEnv.DaemonInfo.OSType == "windows" { expected = `["/bin/sh -c echo foo"]` @@ -6130,7 +6130,7 @@ func (s *DockerCLIBuildSuite) TestBuildIidFile(c *testing.T) { defer os.RemoveAll(tmpDir) tmpIidFile := filepath.Join(tmpDir, "iid") - name := "testbuildiidfile" + const name = "testbuildiidfile" // Use a Dockerfile with multiple stages to ensure we get the last one cli.BuildCmd(c, name, build.WithDockerfile(`FROM `+minimalBaseImage()+` AS stage1 diff --git a/integration-cli/docker_cli_build_unix_test.go b/integration-cli/docker_cli_build_unix_test.go index 6b1667c93f..c71e729805 100644 --- a/integration-cli/docker_cli_build_unix_test.go +++ b/integration-cli/docker_cli_build_unix_test.go @@ -25,8 +25,8 @@ import ( func (s *DockerCLIBuildSuite) TestBuildResourceConstraintsAreUsed(c *testing.T) { testRequires(c, cpuCfsQuota) - name := "testbuildresourceconstraints" - buildLabel := "DockerCLIBuildSuite.TestBuildResourceConstraintsAreUsed" + const name = "testbuildresourceconstraints" + const buildLabel = "DockerCLIBuildSuite.TestBuildResourceConstraintsAreUsed" ctx := fakecontext.New(c, "", fakecontext.WithDockerfile(` FROM hello-world:frozen @@ -85,7 +85,7 @@ func (s *DockerCLIBuildSuite) TestBuildResourceConstraintsAreUsed(c *testing.T) func (s *DockerCLIBuildSuite) TestBuildAddChangeOwnership(c *testing.T) { testRequires(c, DaemonIsLinux) - name := "testbuildaddown" + const name = "testbuildaddown" ctx := func() *fakecontext.Fake { dockerfile := ` @@ -131,7 +131,7 @@ func (s *DockerCLIBuildSuite) TestBuildAddChangeOwnership(c *testing.T) { // Potential issue: newEventObserver uses docker events, which is not hooked up to buildkit. func (s *DockerCLIBuildSuite) TestBuildCancellationKillsSleep(c *testing.T) { testRequires(c, DaemonIsLinux, TODOBuildkit) - name := "testbuildcancellation" + const name = "testbuildcancellation" observer, err := newEventObserver(c) assert.NilError(c, err) diff --git a/integration-cli/docker_cli_by_digest_test.go b/integration-cli/docker_cli_by_digest_test.go index ed99cc8354..5bebae2250 100644 --- a/integration-cli/docker_cli_by_digest_test.go +++ b/integration-cli/docker_cli_by_digest_test.go @@ -20,9 +20,12 @@ import ( "gotest.tools/v3/skip" ) +const ( + remoteRepoName = "dockercli/busybox-by-dgst" + repoName = privateRegistryURL + "/" + remoteRepoName +) + var ( - remoteRepoName = "dockercli/busybox-by-dgst" - repoName = fmt.Sprintf("%s/%s", privateRegistryURL, remoteRepoName) pushDigestRegex = regexp.MustCompile(`[\S]+: digest: ([\S]+) size: [0-9]+`) digestRegex = regexp.MustCompile(`Digest: ([\S]+)`) ) @@ -32,7 +35,7 @@ func setupImage(c *testing.T) (digest.Digest, error) { } func setupImageWithTag(c *testing.T, tag string) (digest.Digest, error) { - containerName := "busyboxbydigest" + const containerName = "busyboxbydigest" // new file is committed because this layer is used for detecting malicious // changes. if this was committed as empty layer it would be skipped on pull @@ -65,7 +68,7 @@ func testPullByTagDisplaysDigest(c *testing.T) { assert.NilError(c, err, "error setting up image") // pull from the registry using the tag - out, _ := dockerCmd(c, "pull", repoName) + out := cli.DockerCmd(c, "pull", repoName).Combined() // the pull output includes "Digest: ", so find that matches := digestRegex.FindStringSubmatch(out) @@ -91,7 +94,7 @@ func testPullByDigest(c *testing.T) { // pull from the registry using the @ reference imageReference := fmt.Sprintf("%s@%s", repoName, pushDigest) - out, _ := dockerCmd(c, "pull", imageReference) + out := cli.DockerCmd(c, "pull", imageReference).Combined() // the pull output includes "Digest: ", so find that matches := digestRegex.FindStringSubmatch(out) @@ -139,8 +142,8 @@ func (s *DockerRegistrySuite) TestCreateByDigest(c *testing.T) { imageReference := fmt.Sprintf("%s@%s", repoName, pushDigest) - containerName := "createByDigest" - dockerCmd(c, "create", "--name", containerName, imageReference) + const containerName = "createByDigest" + cli.DockerCmd(c, "create", "--name", containerName, imageReference) res := inspectField(c, containerName, "Config.Image") assert.Equal(c, res, imageReference) @@ -152,8 +155,8 @@ func (s *DockerRegistrySuite) TestRunByDigest(c *testing.T) { imageReference := fmt.Sprintf("%s@%s", repoName, pushDigest) - containerName := "runByDigest" - out, _ := dockerCmd(c, "run", "--name", containerName, imageReference, "sh", "-c", "echo found=$digest") + const containerName = "runByDigest" + out := cli.DockerCmd(c, "run", "--name", containerName, imageReference, "sh", "-c", "echo found=$digest").Combined() foundRegex := regexp.MustCompile("found=([^\n]+)") matches := foundRegex.FindStringSubmatch(out) @@ -165,13 +168,13 @@ func (s *DockerRegistrySuite) TestRunByDigest(c *testing.T) { } func (s *DockerRegistrySuite) TestRemoveImageByDigest(c *testing.T) { - digest, err := setupImage(c) + imgDigest, err := setupImage(c) assert.NilError(c, err, "error setting up image") - imageReference := fmt.Sprintf("%s@%s", repoName, digest) + imageReference := fmt.Sprintf("%s@%s", repoName, imgDigest) // pull from the registry using the @ reference - dockerCmd(c, "pull", imageReference) + cli.DockerCmd(c, "pull", imageReference) // make sure inspect runs ok inspectField(c, imageReference, "Id") @@ -188,19 +191,19 @@ func (s *DockerRegistrySuite) TestRemoveImageByDigest(c *testing.T) { func (s *DockerRegistrySuite) TestBuildByDigest(c *testing.T) { skip.If(c, testEnv.UsingSnapshotter(), "Config.Image is not created with containerd, buildkit doesn't set it either") - digest, err := setupImage(c) + imgDigest, err := setupImage(c) assert.NilError(c, err, "error setting up image") - imageReference := fmt.Sprintf("%s@%s", repoName, digest) + imageReference := fmt.Sprintf("%s@%s", repoName, imgDigest) // pull from the registry using the @ reference - dockerCmd(c, "pull", imageReference) + cli.DockerCmd(c, "pull", imageReference) // get the image id imageID := inspectField(c, imageReference, "Id") // do the build - name := "buildbydigest" + const name = "buildbydigest" buildImageSuccessfully(c, name, build.WithDockerfile(fmt.Sprintf( `FROM %s CMD ["/bin/echo", "Hello World"]`, imageReference))) @@ -213,17 +216,17 @@ func (s *DockerRegistrySuite) TestBuildByDigest(c *testing.T) { } func (s *DockerRegistrySuite) TestTagByDigest(c *testing.T) { - digest, err := setupImage(c) + imgDigest, err := setupImage(c) assert.NilError(c, err, "error setting up image") - imageReference := fmt.Sprintf("%s@%s", repoName, digest) + imageReference := fmt.Sprintf("%s@%s", repoName, imgDigest) // pull from the registry using the @ reference - dockerCmd(c, "pull", imageReference) + cli.DockerCmd(c, "pull", imageReference) // tag it - tag := "tagbydigest" - dockerCmd(c, "tag", imageReference, tag) + const tag = "tagbydigest" + cli.DockerCmd(c, "tag", imageReference, tag) expectedID := inspectField(c, imageReference, "Id") @@ -232,15 +235,15 @@ func (s *DockerRegistrySuite) TestTagByDigest(c *testing.T) { } func (s *DockerRegistrySuite) TestListImagesWithoutDigests(c *testing.T) { - digest, err := setupImage(c) + imgDigest, err := setupImage(c) assert.NilError(c, err, "error setting up image") - imageReference := fmt.Sprintf("%s@%s", repoName, digest) + imageReference := fmt.Sprintf("%s@%s", repoName, imgDigest) // pull from the registry using the @ reference - dockerCmd(c, "pull", imageReference) + cli.DockerCmd(c, "pull", imageReference) - out, _ := dockerCmd(c, "images") + out := cli.DockerCmd(c, "images").Stdout() assert.Assert(c, !strings.Contains(out, "DIGEST"), "list output should not have contained DIGEST header") } @@ -252,10 +255,10 @@ func (s *DockerRegistrySuite) TestListImagesWithDigests(c *testing.T) { c.Logf("imageReference1 = %s", imageReference1) // pull image1 by digest - dockerCmd(c, "pull", imageReference1) + cli.DockerCmd(c, "pull", imageReference1) // list images - out, _ := dockerCmd(c, "images", "--digests") + out := cli.DockerCmd(c, "images", "--digests").Combined() // make sure repo shown, tag=, digest = $digest1 re1 := regexp.MustCompile(`\s*` + repoName + `\s*\s*` + digest1.String() + `\s`) @@ -267,13 +270,13 @@ func (s *DockerRegistrySuite) TestListImagesWithDigests(c *testing.T) { c.Logf("imageReference2 = %s", imageReference2) // pull image1 by digest - dockerCmd(c, "pull", imageReference1) + cli.DockerCmd(c, "pull", imageReference1) // pull image2 by digest - dockerCmd(c, "pull", imageReference2) + cli.DockerCmd(c, "pull", imageReference2) // list images - out, _ = dockerCmd(c, "images", "--digests") + out = cli.DockerCmd(c, "images", "--digests").Stdout() // make sure repo shown, tag=, digest = $digest1 assert.Assert(c, re1.MatchString(out), "expected %q: %s", re1.String(), out) @@ -283,10 +286,10 @@ func (s *DockerRegistrySuite) TestListImagesWithDigests(c *testing.T) { assert.Assert(c, re2.MatchString(out), "expected %q: %s", re2.String(), out) // pull tag1 - dockerCmd(c, "pull", repoName+":tag1") + cli.DockerCmd(c, "pull", repoName+":tag1") // list images - out, _ = dockerCmd(c, "images", "--digests") + out = cli.DockerCmd(c, "images", "--digests").Stdout() // make sure image 1 has repo, tag, AND repo, , digest reWithDigest1 := regexp.MustCompile(`\s*` + repoName + `\s*tag1\s*` + digest1.String() + `\s`) @@ -295,10 +298,10 @@ func (s *DockerRegistrySuite) TestListImagesWithDigests(c *testing.T) { assert.Assert(c, re2.MatchString(out), "expected %q: %s", re2.String(), out) // pull tag 2 - dockerCmd(c, "pull", repoName+":tag2") + cli.DockerCmd(c, "pull", repoName+":tag2") // list images - out, _ = dockerCmd(c, "images", "--digests") + out = cli.DockerCmd(c, "images", "--digests").Stdout() // make sure image 1 has repo, tag, digest assert.Assert(c, reWithDigest1.MatchString(out), "expected %q: %s", reWithDigest1.String(), out) @@ -308,7 +311,7 @@ func (s *DockerRegistrySuite) TestListImagesWithDigests(c *testing.T) { assert.Assert(c, reWithDigest2.MatchString(out), "expected %q: %s", reWithDigest2.String(), out) // list images - out, _ = dockerCmd(c, "images", "--digests") + out = cli.DockerCmd(c, "images", "--digests").Stdout() // make sure image 1 has repo, tag, digest assert.Assert(c, reWithDigest1.MatchString(out), "expected %q: %s", reWithDigest1.String(), out) @@ -327,10 +330,10 @@ func (s *DockerRegistrySuite) TestListDanglingImagesWithDigests(c *testing.T) { c.Logf("imageReference1 = %s", imageReference1) // pull image1 by digest - dockerCmd(c, "pull", imageReference1) + cli.DockerCmd(c, "pull", imageReference1) // list images - out, _ := dockerCmd(c, "images", "--digests") + out := cli.DockerCmd(c, "images", "--digests").Stdout() // make sure repo shown, tag=, digest = $digest1 re1 := regexp.MustCompile(`\s*` + repoName + `\s*\s*` + digest1.String() + `\s`) @@ -343,13 +346,13 @@ func (s *DockerRegistrySuite) TestListDanglingImagesWithDigests(c *testing.T) { c.Logf("imageReference2 = %s", imageReference2) // pull image1 by digest - dockerCmd(c, "pull", imageReference1) + cli.DockerCmd(c, "pull", imageReference1) // pull image2 by digest - dockerCmd(c, "pull", imageReference2) + cli.DockerCmd(c, "pull", imageReference2) // list images - out, _ = dockerCmd(c, "images", "--digests", "--filter=dangling=true") + out = cli.DockerCmd(c, "images", "--digests", "--filter=dangling=true").Stdout() // make sure repo shown, tag=, digest = $digest1 assert.Assert(c, re1.MatchString(out), "expected %q: %s", re1.String(), out) @@ -359,10 +362,10 @@ func (s *DockerRegistrySuite) TestListDanglingImagesWithDigests(c *testing.T) { assert.Assert(c, re2.MatchString(out), "expected %q: %s", re2.String(), out) // pull dangle1 tag - dockerCmd(c, "pull", repoName+":dangle1") + cli.DockerCmd(c, "pull", repoName+":dangle1") // list images - out, _ = dockerCmd(c, "images", "--digests", "--filter=dangling=true") + out = cli.DockerCmd(c, "images", "--digests", "--filter=dangling=true").Stdout() // make sure image 1 has repo, tag, AND repo, , digest reWithDigest1 := regexp.MustCompile(`\s*` + repoName + `\s*dangle1\s*` + digest1.String() + `\s`) @@ -371,10 +374,10 @@ func (s *DockerRegistrySuite) TestListDanglingImagesWithDigests(c *testing.T) { assert.Assert(c, re2.MatchString(out), "expected %q: %s", re2.String(), out) // pull dangle2 tag - dockerCmd(c, "pull", repoName+":dangle2") + cli.DockerCmd(c, "pull", repoName+":dangle2") // list images, show tagged images - out, _ = dockerCmd(c, "images", "--digests") + out = cli.DockerCmd(c, "images", "--digests").Stdout() // make sure image 1 has repo, tag, digest assert.Assert(c, reWithDigest1.MatchString(out), "expected %q: %s", reWithDigest1.String(), out) @@ -384,7 +387,7 @@ func (s *DockerRegistrySuite) TestListDanglingImagesWithDigests(c *testing.T) { assert.Assert(c, reWithDigest2.MatchString(out), "expected %q: %s", reWithDigest2.String(), out) // list images, no longer dangling, should not match - out, _ = dockerCmd(c, "images", "--digests", "--filter=dangling=true") + out = cli.DockerCmd(c, "images", "--digests", "--filter=dangling=true").Stdout() // make sure image 1 has repo, tag, digest assert.Assert(c, !reWithDigest1.MatchString(out), "unexpected %q: %s", reWithDigest1.String(), out) @@ -393,15 +396,15 @@ func (s *DockerRegistrySuite) TestListDanglingImagesWithDigests(c *testing.T) { } func (s *DockerRegistrySuite) TestInspectImageWithDigests(c *testing.T) { - digest, err := setupImage(c) + imgDigest, err := setupImage(c) assert.Assert(c, err == nil, "error setting up image") - imageReference := fmt.Sprintf("%s@%s", repoName, digest) + imageReference := fmt.Sprintf("%s@%s", repoName, imgDigest) // pull from the registry using the @ reference - dockerCmd(c, "pull", imageReference) + cli.DockerCmd(c, "pull", imageReference) - out, _ := dockerCmd(c, "inspect", imageReference) + out := cli.DockerCmd(c, "inspect", imageReference).Stdout() var imageJSON []types.ImageInspect err = json.Unmarshal([]byte(out), &imageJSON) @@ -414,36 +417,36 @@ func (s *DockerRegistrySuite) TestInspectImageWithDigests(c *testing.T) { func (s *DockerRegistrySuite) TestPsListContainersFilterAncestorImageByDigest(c *testing.T) { existingContainers := ExistingContainerIDs(c) - digest, err := setupImage(c) + imgDigest, err := setupImage(c) assert.NilError(c, err, "error setting up image") - imageReference := fmt.Sprintf("%s@%s", repoName, digest) + imageReference := fmt.Sprintf("%s@%s", repoName, imgDigest) // pull from the registry using the @ reference - dockerCmd(c, "pull", imageReference) + cli.DockerCmd(c, "pull", imageReference) // build an image from it - imageName1 := "images_ps_filter_test" + const imageName1 = "images_ps_filter_test" buildImageSuccessfully(c, imageName1, build.WithDockerfile(fmt.Sprintf( `FROM %s LABEL match me 1`, imageReference))) // run a container based on that - dockerCmd(c, "run", "--name=test1", imageReference, "echo", "hello") + cli.DockerCmd(c, "run", "--name=test1", imageReference, "echo", "hello") expectedID := getIDByName(c, "test1") // run a container based on the a descendant of that too - dockerCmd(c, "run", "--name=test2", imageName1, "echo", "hello") + cli.DockerCmd(c, "run", "--name=test2", imageName1, "echo", "hello") expectedID1 := getIDByName(c, "test2") expectedIDs := []string{expectedID, expectedID1} // Invalid imageReference - out, _ := dockerCmd(c, "ps", "-a", "-q", "--no-trunc", fmt.Sprintf("--filter=ancestor=busybox@%s", digest)) + out := cli.DockerCmd(c, "ps", "-a", "-q", "--no-trunc", fmt.Sprintf("--filter=ancestor=busybox@%s", imgDigest)).Stdout() assert.Equal(c, strings.TrimSpace(out), "", "Filter container for ancestor filter should be empty") // Valid imageReference - out, _ = dockerCmd(c, "ps", "-a", "-q", "--no-trunc", "--filter=ancestor="+imageReference) + out = cli.DockerCmd(c, "ps", "-a", "-q", "--no-trunc", "--filter=ancestor="+imageReference).Stdout() checkPsAncestorFilterOutput(c, RemoveOutputForExistingElements(out, existingContainers), imageReference, expectedIDs) } @@ -453,14 +456,14 @@ func (s *DockerRegistrySuite) TestDeleteImageByIDOnlyPulledByDigest(c *testing.T // pull from the registry using the @ reference imageReference := fmt.Sprintf("%s@%s", repoName, pushDigest) - dockerCmd(c, "pull", imageReference) + cli.DockerCmd(c, "pull", imageReference) // just in case... - dockerCmd(c, "tag", imageReference, repoName+":sometag") + cli.DockerCmd(c, "tag", imageReference, repoName+":sometag") imageID := inspectField(c, imageReference, "Id") - dockerCmd(c, "rmi", imageID) + cli.DockerCmd(c, "rmi", imageID) _, err = inspectFieldWithError(imageID, "Id") assert.ErrorContains(c, err, "", "image should have been deleted") @@ -472,21 +475,21 @@ func (s *DockerRegistrySuite) TestDeleteImageWithDigestAndTag(c *testing.T) { // pull from the registry using the @ reference imageReference := fmt.Sprintf("%s@%s", repoName, pushDigest) - dockerCmd(c, "pull", imageReference) + cli.DockerCmd(c, "pull", imageReference) imageID := inspectField(c, imageReference, "Id") - repoTag := repoName + ":sometag" - repoTag2 := repoName + ":othertag" - dockerCmd(c, "tag", imageReference, repoTag) - dockerCmd(c, "tag", imageReference, repoTag2) + const repoTag = repoName + ":sometag" + const repoTag2 = repoName + ":othertag" + cli.DockerCmd(c, "tag", imageReference, repoTag) + cli.DockerCmd(c, "tag", imageReference, repoTag2) - dockerCmd(c, "rmi", repoTag2) + cli.DockerCmd(c, "rmi", repoTag2) // rmi should have deleted only repoTag2, because there's another tag inspectField(c, repoTag, "Id") - dockerCmd(c, "rmi", repoTag) + cli.DockerCmd(c, "rmi", repoTag) // rmi should have deleted the tag, the digest reference, and the image itself _, err = inspectFieldWithError(imageID, "Id") @@ -501,16 +504,16 @@ func (s *DockerRegistrySuite) TestDeleteImageWithDigestAndMultiRepoTag(c *testin // pull from the registry using the @ reference imageReference := fmt.Sprintf("%s@%s", repoName, pushDigest) - dockerCmd(c, "pull", imageReference) + cli.DockerCmd(c, "pull", imageReference) imageID := inspectField(c, imageReference, "Id") repoTag := repoName + ":sometag" repoTag2 := repo2 + ":othertag" - dockerCmd(c, "tag", imageReference, repoTag) - dockerCmd(c, "tag", imageReference, repoTag2) + cli.DockerCmd(c, "tag", imageReference, repoTag) + cli.DockerCmd(c, "tag", imageReference, repoTag2) - dockerCmd(c, "rmi", repoTag) + cli.DockerCmd(c, "rmi", repoTag) // rmi should have deleted repoTag and image reference, but left repoTag2 inspectField(c, repoTag2, "Id") @@ -520,7 +523,7 @@ func (s *DockerRegistrySuite) TestDeleteImageWithDigestAndMultiRepoTag(c *testin _, err = inspectFieldWithError(repoTag, "Id") assert.ErrorContains(c, err, "", "image tag reference should have been removed") - dockerCmd(c, "rmi", repoTag2) + cli.DockerCmd(c, "rmi", repoTag2) // rmi should have deleted the tag, the digest reference, and the image itself _, err = inspectFieldWithError(imageID, "Id") diff --git a/integration-cli/docker_cli_commit_test.go b/integration-cli/docker_cli_commit_test.go index 14ad01b560..5213b351b2 100644 --- a/integration-cli/docker_cli_commit_test.go +++ b/integration-cli/docker_cli_commit_test.go @@ -40,57 +40,56 @@ func (s *DockerCLICommitSuite) TestCommitAfterContainerIsDone(c *testing.T) { func (s *DockerCLICommitSuite) TestCommitWithoutPause(c *testing.T) { testRequires(c, DaemonIsLinux) - out, _ := dockerCmd(c, "run", "-i", "-a", "stdin", "busybox", "echo", "foo") + out := cli.DockerCmd(c, "run", "-i", "-a", "stdin", "busybox", "echo", "foo").Combined() cleanedContainerID := strings.TrimSpace(out) - dockerCmd(c, "wait", cleanedContainerID) + cli.DockerCmd(c, "wait", cleanedContainerID) - out, _ = dockerCmd(c, "commit", "-p=false", cleanedContainerID) + out = cli.DockerCmd(c, "commit", "-p=false", cleanedContainerID).Combined() cleanedImageID := strings.TrimSpace(out) - dockerCmd(c, "inspect", cleanedImageID) + cli.DockerCmd(c, "inspect", cleanedImageID) } // TestCommitPausedContainer tests that a paused container is not unpaused after being committed func (s *DockerCLICommitSuite) TestCommitPausedContainer(c *testing.T) { testRequires(c, DaemonIsLinux) - out, _ := dockerCmd(c, "run", "-i", "-d", "busybox") + containerID := cli.DockerCmd(c, "run", "-i", "-d", "busybox").Stdout() + containerID = strings.TrimSpace(containerID) - cleanedContainerID := strings.TrimSpace(out) + cli.DockerCmd(c, "pause", containerID) + cli.DockerCmd(c, "commit", containerID) - dockerCmd(c, "pause", cleanedContainerID) - dockerCmd(c, "commit", cleanedContainerID) - - out = inspectField(c, cleanedContainerID, "State.Paused") + out := inspectField(c, containerID, "State.Paused") // commit should not unpause a paused container assert.Assert(c, strings.Contains(out, "true")) } func (s *DockerCLICommitSuite) TestCommitNewFile(c *testing.T) { - dockerCmd(c, "run", "--name", "committer", "busybox", "/bin/sh", "-c", "echo koye > /foo") + cli.DockerCmd(c, "run", "--name", "committer", "busybox", "/bin/sh", "-c", "echo koye > /foo") - imageID, _ := dockerCmd(c, "commit", "committer") + imageID := cli.DockerCmd(c, "commit", "committer").Stdout() imageID = strings.TrimSpace(imageID) - out, _ := dockerCmd(c, "run", imageID, "cat", "/foo") + out := cli.DockerCmd(c, "run", imageID, "cat", "/foo").Combined() actual := strings.TrimSpace(out) assert.Equal(c, actual, "koye") } func (s *DockerCLICommitSuite) TestCommitHardlink(c *testing.T) { testRequires(c, DaemonIsLinux) - firstOutput, _ := dockerCmd(c, "run", "-t", "--name", "hardlinks", "busybox", "sh", "-c", "touch file1 && ln file1 file2 && ls -di file1 file2") + firstOutput := cli.DockerCmd(c, "run", "-t", "--name", "hardlinks", "busybox", "sh", "-c", "touch file1 && ln file1 file2 && ls -di file1 file2").Combined() chunks := strings.Split(strings.TrimSpace(firstOutput), " ") inode := chunks[0] chunks = strings.SplitAfterN(strings.TrimSpace(firstOutput), " ", 2) assert.Assert(c, strings.Contains(chunks[1], chunks[0]), "Failed to create hardlink in a container. Expected to find %q in %q", inode, chunks[1:]) - imageID, _ := dockerCmd(c, "commit", "hardlinks", "hardlinks") + imageID := cli.DockerCmd(c, "commit", "hardlinks", "hardlinks").Stdout() imageID = strings.TrimSpace(imageID) - secondOutput, _ := dockerCmd(c, "run", "-t", imageID, "ls", "-di", "file1", "file2") + secondOutput := cli.DockerCmd(c, "run", "-t", imageID, "ls", "-di", "file1", "file2").Combined() chunks = strings.Split(strings.TrimSpace(secondOutput), " ") inode = chunks[0] @@ -99,28 +98,28 @@ func (s *DockerCLICommitSuite) TestCommitHardlink(c *testing.T) { } func (s *DockerCLICommitSuite) TestCommitTTY(c *testing.T) { - dockerCmd(c, "run", "-t", "--name", "tty", "busybox", "/bin/ls") + cli.DockerCmd(c, "run", "-t", "--name", "tty", "busybox", "/bin/ls") - imageID, _ := dockerCmd(c, "commit", "tty", "ttytest") + imageID := cli.DockerCmd(c, "commit", "tty", "ttytest").Stdout() imageID = strings.TrimSpace(imageID) - dockerCmd(c, "run", imageID, "/bin/ls") + cli.DockerCmd(c, "run", imageID, "/bin/ls") } func (s *DockerCLICommitSuite) TestCommitWithHostBindMount(c *testing.T) { testRequires(c, DaemonIsLinux) - dockerCmd(c, "run", "--name", "bind-commit", "-v", "/dev/null:/winning", "busybox", "true") + cli.DockerCmd(c, "run", "--name", "bind-commit", "-v", "/dev/null:/winning", "busybox", "true") - imageID, _ := dockerCmd(c, "commit", "bind-commit", "bindtest") + imageID := cli.DockerCmd(c, "commit", "bind-commit", "bindtest").Stdout() imageID = strings.TrimSpace(imageID) - dockerCmd(c, "run", imageID, "true") + cli.DockerCmd(c, "run", imageID, "true") } func (s *DockerCLICommitSuite) TestCommitChange(c *testing.T) { - dockerCmd(c, "run", "--name", "test", "busybox", "true") + cli.DockerCmd(c, "run", "--name", "test", "busybox", "true") - imageID, _ := dockerCmd(c, "commit", + imageID := cli.DockerCmd(c, "commit", "--change", `EXPOSE 8080`, "--change", `ENV DEBUG true`, "--change", `ENV test 1`, @@ -132,7 +131,8 @@ func (s *DockerCLICommitSuite) TestCommitChange(c *testing.T) { "--change", `USER testuser`, "--change", `VOLUME /var/lib/docker`, "--change", `ONBUILD /usr/local/bin/python-build --dir /app/src`, - "test", "test-commit") + "test", "test-commit", + ).Stdout() imageID = strings.TrimSpace(imageID) expectedEnv := "[DEBUG=true test=1 PATH=/foo]" @@ -168,11 +168,9 @@ func (s *DockerCLICommitSuite) TestCommitChange(c *testing.T) { } func (s *DockerCLICommitSuite) TestCommitChangeLabels(c *testing.T) { - dockerCmd(c, "run", "--name", "test", "--label", "some=label", "busybox", "true") + cli.DockerCmd(c, "run", "--name", "test", "--label", "some=label", "busybox", "true") - imageID, _ := dockerCmd(c, "commit", - "--change", "LABEL some=label2", - "test", "test-commit") + imageID := cli.DockerCmd(c, "commit", "--change", "LABEL some=label2", "test", "test-commit").Stdout() imageID = strings.TrimSpace(imageID) assert.Equal(c, inspectField(c, imageID, "Config.Labels"), "map[some:label2]") diff --git a/integration-cli/docker_cli_cp_test.go b/integration-cli/docker_cli_cp_test.go index 1252ca85e8..9ef2ea65e3 100644 --- a/integration-cli/docker_cli_cp_test.go +++ b/integration-cli/docker_cli_cp_test.go @@ -12,6 +12,7 @@ import ( "strings" "testing" + "github.com/docker/docker/integration-cli/cli" "gotest.tools/v3/assert" is "gotest.tools/v3/assert/cmp" "gotest.tools/v3/icmd" @@ -48,11 +49,10 @@ func (s *DockerCLICpSuite) TestCpLocalOnly(c *testing.T) { // Test for #5656 // Check that garbage paths don't escape the container's rootfs func (s *DockerCLICpSuite) TestCpGarbagePath(c *testing.T) { - out, _ := dockerCmd(c, "run", "-d", "busybox", "/bin/sh", "-c", "mkdir -p '"+cpTestPath+"' && echo -n '"+cpContainerContents+"' > "+cpFullPath) + containerID := cli.DockerCmd(c, "run", "-d", "busybox", "/bin/sh", "-c", "mkdir -p '"+cpTestPath+"' && echo -n '"+cpContainerContents+"' > "+cpFullPath).Stdout() + containerID = strings.TrimSpace(containerID) - containerID := strings.TrimSpace(out) - - out, _ = dockerCmd(c, "wait", containerID) + out := cli.DockerCmd(c, "wait", containerID).Combined() assert.Equal(c, strings.TrimSpace(out), "0", "failed to set up container") assert.NilError(c, os.MkdirAll(cpTestPath, os.ModeDir)) @@ -69,9 +69,8 @@ func (s *DockerCLICpSuite) TestCpGarbagePath(c *testing.T) { tmpname := filepath.Join(tmpdir, cpTestName) defer os.RemoveAll(tmpdir) - path := path.Join("../../../../../../../../../../../../", cpFullPath) - - dockerCmd(c, "cp", containerID+":"+path, tmpdir) + containerPath := path.Join("../../../../../../../../../../../../", cpFullPath) + cli.DockerCmd(c, "cp", containerID+":"+containerPath, tmpdir) file, _ := os.Open(tmpname) defer file.Close() @@ -84,11 +83,10 @@ func (s *DockerCLICpSuite) TestCpGarbagePath(c *testing.T) { // Check that relative paths are relative to the container's rootfs func (s *DockerCLICpSuite) TestCpRelativePath(c *testing.T) { - out, _ := dockerCmd(c, "run", "-d", "busybox", "/bin/sh", "-c", "mkdir -p '"+cpTestPath+"' && echo -n '"+cpContainerContents+"' > "+cpFullPath) + containerID := cli.DockerCmd(c, "run", "-d", "busybox", "/bin/sh", "-c", "mkdir -p '"+cpTestPath+"' && echo -n '"+cpContainerContents+"' > "+cpFullPath).Stdout() + containerID = strings.TrimSpace(containerID) - containerID := strings.TrimSpace(out) - - out, _ = dockerCmd(c, "wait", containerID) + out := cli.DockerCmd(c, "wait", containerID).Combined() assert.Equal(c, strings.TrimSpace(out), "0", "failed to set up container") assert.NilError(c, os.MkdirAll(cpTestPath, os.ModeDir)) @@ -113,7 +111,7 @@ func (s *DockerCLICpSuite) TestCpRelativePath(c *testing.T) { } assert.Assert(c, path.IsAbs(cpFullPath), "path %s was assumed to be an absolute path", cpFullPath) - dockerCmd(c, "cp", containerID+":"+relPath, tmpdir) + cli.DockerCmd(c, "cp", containerID+":"+relPath, tmpdir) file, _ := os.Open(tmpname) defer file.Close() @@ -126,11 +124,10 @@ func (s *DockerCLICpSuite) TestCpRelativePath(c *testing.T) { // Check that absolute paths are relative to the container's rootfs func (s *DockerCLICpSuite) TestCpAbsolutePath(c *testing.T) { - out, _ := dockerCmd(c, "run", "-d", "busybox", "/bin/sh", "-c", "mkdir -p '"+cpTestPath+"' && echo -n '"+cpContainerContents+"' > "+cpFullPath) + containerID := cli.DockerCmd(c, "run", "-d", "busybox", "/bin/sh", "-c", "mkdir -p '"+cpTestPath+"' && echo -n '"+cpContainerContents+"' > "+cpFullPath).Stdout() + containerID = strings.TrimSpace(containerID) - containerID := strings.TrimSpace(out) - - out, _ = dockerCmd(c, "wait", containerID) + out := cli.DockerCmd(c, "wait", containerID).Combined() assert.Equal(c, strings.TrimSpace(out), "0", "failed to set up container") assert.NilError(c, os.MkdirAll(cpTestPath, os.ModeDir)) @@ -147,9 +144,7 @@ func (s *DockerCLICpSuite) TestCpAbsolutePath(c *testing.T) { tmpname := filepath.Join(tmpdir, cpTestName) defer os.RemoveAll(tmpdir) - path := cpFullPath - - dockerCmd(c, "cp", containerID+":"+path, tmpdir) + cli.DockerCmd(c, "cp", containerID+":"+cpFullPath, tmpdir) file, _ := os.Open(tmpname) defer file.Close() @@ -164,11 +159,10 @@ func (s *DockerCLICpSuite) TestCpAbsolutePath(c *testing.T) { // Check that absolute symlinks are still relative to the container's rootfs func (s *DockerCLICpSuite) TestCpAbsoluteSymlink(c *testing.T) { testRequires(c, DaemonIsLinux) - out, _ := dockerCmd(c, "run", "-d", "busybox", "/bin/sh", "-c", "mkdir -p '"+cpTestPath+"' && echo -n '"+cpContainerContents+"' > "+cpFullPath+" && ln -s "+cpFullPath+" container_path") + containerID := cli.DockerCmd(c, "run", "-d", "busybox", "/bin/sh", "-c", "mkdir -p '"+cpTestPath+"' && echo -n '"+cpContainerContents+"' > "+cpFullPath+" && ln -s "+cpFullPath+" container_path").Stdout() + containerID = strings.TrimSpace(containerID) - containerID := strings.TrimSpace(out) - - out, _ = dockerCmd(c, "wait", containerID) + out := cli.DockerCmd(c, "wait", containerID).Combined() assert.Equal(c, strings.TrimSpace(out), "0", "failed to set up container") assert.NilError(c, os.MkdirAll(cpTestPath, os.ModeDir)) @@ -186,9 +180,8 @@ func (s *DockerCLICpSuite) TestCpAbsoluteSymlink(c *testing.T) { tmpname := filepath.Join(tmpdir, "container_path") defer os.RemoveAll(tmpdir) - path := path.Join("/", "container_path") - - dockerCmd(c, "cp", containerID+":"+path, tmpdir) + containerPath := path.Join("/", "container_path") + cli.DockerCmd(c, "cp", containerID+":"+containerPath, tmpdir) // We should have copied a symlink *NOT* the file itself! linkTarget, err := os.Readlink(tmpname) @@ -200,11 +193,10 @@ func (s *DockerCLICpSuite) TestCpAbsoluteSymlink(c *testing.T) { // a container. func (s *DockerCLICpSuite) TestCpFromSymlinkToDirectory(c *testing.T) { testRequires(c, DaemonIsLinux) - out, _ := dockerCmd(c, "run", "-d", "busybox", "/bin/sh", "-c", "mkdir -p '"+cpTestPath+"' && echo -n '"+cpContainerContents+"' > "+cpFullPath+" && ln -s "+cpTestPathParent+" /dir_link") + containerID := cli.DockerCmd(c, "run", "-d", "busybox", "/bin/sh", "-c", "mkdir -p '"+cpTestPath+"' && echo -n '"+cpContainerContents+"' > "+cpFullPath+" && ln -s "+cpTestPathParent+" /dir_link").Stdout() + containerID = strings.TrimSpace(containerID) - containerID := strings.TrimSpace(out) - - out, _ = dockerCmd(c, "wait", containerID) + out := cli.DockerCmd(c, "wait", containerID).Combined() assert.Equal(c, strings.TrimSpace(out), "0", "failed to set up container") testDir, err := os.MkdirTemp("", "test-cp-from-symlink-to-dir-") @@ -213,7 +205,7 @@ func (s *DockerCLICpSuite) TestCpFromSymlinkToDirectory(c *testing.T) { // This copy command should copy the symlink, not the target, into the // temporary directory. - dockerCmd(c, "cp", containerID+":"+"/dir_link", testDir) + cli.DockerCmd(c, "cp", containerID+":"+"/dir_link", testDir) expectedPath := filepath.Join(testDir, "dir_link") linkTarget, err := os.Readlink(expectedPath) @@ -225,7 +217,7 @@ func (s *DockerCLICpSuite) TestCpFromSymlinkToDirectory(c *testing.T) { // This copy command should resolve the symlink (note the trailing // separator), copying the target into the temporary directory. - dockerCmd(c, "cp", containerID+":"+"/dir_link/", testDir) + cli.DockerCmd(c, "cp", containerID+":"+"/dir_link/", testDir) // It *should not* have copied the directory using the target's name, but // used the given name instead. @@ -254,9 +246,8 @@ func (s *DockerCLICpSuite) TestCpToSymlinkToDirectory(c *testing.T) { // Create a test container with a local volume. We will test by copying // to the volume path in the container which we can then verify locally. - out, _ := dockerCmd(c, "create", "-v", testVol+":/testVol", "busybox") - - containerID := strings.TrimSpace(out) + containerID := cli.DockerCmd(c, "create", "-v", testVol+":/testVol", "busybox").Stdout() + containerID = strings.TrimSpace(containerID) // Create a temp directory to hold a test file nested in a directory. testDir, err := os.MkdirTemp("", "test-cp-to-symlink-to-dir-") @@ -281,7 +272,7 @@ func (s *DockerCLICpSuite) TestCpToSymlinkToDirectory(c *testing.T) { assert.NilError(c, os.Symlink(linkTarget, localLink)) // Now copy that symlink into the test volume in the container. - dockerCmd(c, "cp", localLink, containerID+":/testVol") + cli.DockerCmd(c, "cp", localLink, containerID+":/testVol") // This copy command should have copied the symlink *not* the target. expectedPath := filepath.Join(testVol, "dir_link") @@ -295,16 +286,15 @@ func (s *DockerCLICpSuite) TestCpToSymlinkToDirectory(c *testing.T) { // This copy command should resolve the symlink (note the trailing // separator), copying the target into the test volume directory in the // container. - dockerCmd(c, "cp", localLink+"/", containerID+":/testVol") + cli.DockerCmd(c, "cp", localLink+"/", containerID+":/testVol") // It *should not* have copied the directory using the target's name, but // used the given name instead. unexpectedPath := filepath.Join(testVol, cpTestPathParent) stat, err := os.Lstat(unexpectedPath) if err == nil { - out = fmt.Sprintf("target name was copied: %q - %q", stat.Mode(), stat.Name()) + c.Errorf("target name was unexpectedly preserved: %q - %q", stat.Mode(), stat.Name()) } - assert.ErrorContains(c, err, "", out) // It *should* have copied the directory using the asked name "dir_link". stat, err = os.Lstat(expectedPath) @@ -323,11 +313,10 @@ func (s *DockerCLICpSuite) TestCpToSymlinkToDirectory(c *testing.T) { // Check that symlinks which are part of the resource path are still relative to the container's rootfs func (s *DockerCLICpSuite) TestCpSymlinkComponent(c *testing.T) { testRequires(c, DaemonIsLinux) - out, _ := dockerCmd(c, "run", "-d", "busybox", "/bin/sh", "-c", "mkdir -p '"+cpTestPath+"' && echo -n '"+cpContainerContents+"' > "+cpFullPath+" && ln -s "+cpTestPath+" container_path") + containerID := cli.DockerCmd(c, "run", "-d", "busybox", "/bin/sh", "-c", "mkdir -p '"+cpTestPath+"' && echo -n '"+cpContainerContents+"' > "+cpFullPath+" && ln -s "+cpTestPath+" container_path").Stdout() + containerID = strings.TrimSpace(containerID) - containerID := strings.TrimSpace(out) - - out, _ = dockerCmd(c, "wait", containerID) + out := cli.DockerCmd(c, "wait", containerID).Combined() assert.Equal(c, strings.TrimSpace(out), "0", "failed to set up container") assert.NilError(c, os.MkdirAll(cpTestPath, os.ModeDir)) @@ -346,9 +335,8 @@ func (s *DockerCLICpSuite) TestCpSymlinkComponent(c *testing.T) { tmpname := filepath.Join(tmpdir, cpTestName) defer os.RemoveAll(tmpdir) - path := path.Join("/", "container_path", cpTestName) - - dockerCmd(c, "cp", containerID+":"+path, tmpdir) + containerPath := path.Join("/", "container_path", cpTestName) + cli.DockerCmd(c, "cp", containerID+":"+containerPath, tmpdir) file, _ := os.Open(tmpname) defer file.Close() @@ -364,11 +352,10 @@ func (s *DockerCLICpSuite) TestCpUnprivilegedUser(c *testing.T) { testRequires(c, DaemonIsLinux, testEnv.IsLocalDaemon) testRequires(c, UnixCli) // uses chmod/su: not available on windows - out, _ := dockerCmd(c, "run", "-d", "busybox", "/bin/sh", "-c", "touch "+cpTestName) + containerID := cli.DockerCmd(c, "run", "-d", "busybox", "/bin/sh", "-c", "touch "+cpTestName).Stdout() + containerID = strings.TrimSpace(containerID) - containerID := strings.TrimSpace(out) - - out, _ = dockerCmd(c, "wait", containerID) + out := cli.DockerCmd(c, "wait", containerID).Combined() assert.Equal(c, strings.TrimSpace(out), "0", "failed to set up container") tmpdir, err := os.MkdirTemp("", "docker-integration") @@ -379,8 +366,7 @@ func (s *DockerCLICpSuite) TestCpUnprivilegedUser(c *testing.T) { err = os.Chmod(tmpdir, 0o777) assert.NilError(c, err) - result := icmd.RunCommand("su", "unprivilegeduser", "-c", - fmt.Sprintf("%s cp %s:%s %s", dockerBinary, containerID, cpTestName, tmpdir)) + result := icmd.RunCommand("su", "unprivilegeduser", "-c", fmt.Sprintf("%s cp %s:%s %s", dockerBinary, containerID, cpTestName, tmpdir)) result.Assert(c, icmd.Expected{}) } @@ -392,15 +378,14 @@ func (s *DockerCLICpSuite) TestCpSpecialFiles(c *testing.T) { assert.NilError(c, err) defer os.RemoveAll(outDir) - out, _ := dockerCmd(c, "run", "-d", "busybox", "/bin/sh", "-c", "touch /foo") + containerID := cli.DockerCmd(c, "run", "-d", "busybox", "/bin/sh", "-c", "touch /foo").Stdout() + containerID = strings.TrimSpace(containerID) - containerID := strings.TrimSpace(out) - - out, _ = dockerCmd(c, "wait", containerID) + out := cli.DockerCmd(c, "wait", containerID).Combined() assert.Equal(c, strings.TrimSpace(out), "0", "failed to set up container") // Copy actual /etc/resolv.conf - dockerCmd(c, "cp", containerID+":/etc/resolv.conf", outDir) + cli.DockerCmd(c, "cp", containerID+":/etc/resolv.conf", outDir) expected := readContainerFile(c, containerID, "resolv.conf") actual, err := os.ReadFile(outDir + "/resolv.conf") @@ -408,7 +393,7 @@ func (s *DockerCLICpSuite) TestCpSpecialFiles(c *testing.T) { assert.Assert(c, bytes.Equal(actual, expected), "Expected copied file to be duplicate of the container resolvconf") // Copy actual /etc/hosts - dockerCmd(c, "cp", containerID+":/etc/hosts", outDir) + cli.DockerCmd(c, "cp", containerID+":/etc/hosts", outDir) expected = readContainerFile(c, containerID, "hosts") actual, err = os.ReadFile(outDir + "/hosts") @@ -416,7 +401,7 @@ func (s *DockerCLICpSuite) TestCpSpecialFiles(c *testing.T) { assert.Assert(c, bytes.Equal(actual, expected), "Expected copied file to be duplicate of the container hosts") // Copy actual /etc/resolv.conf - dockerCmd(c, "cp", containerID+":/etc/hostname", outDir) + cli.DockerCmd(c, "cp", containerID+":/etc/hostname", outDir) expected = readContainerFile(c, containerID, "hostname") actual, err = os.ReadFile(outDir + "/hostname") @@ -439,15 +424,14 @@ func (s *DockerCLICpSuite) TestCpVolumePath(c *testing.T) { _, err = os.Create(tmpDir + "/test") assert.NilError(c, err) - out, _ := dockerCmd(c, "run", "-d", "-v", "/foo", "-v", tmpDir+"/test:/test", "-v", tmpDir+":/baz", "busybox", "/bin/sh", "-c", "touch /foo/bar") + containerID := cli.DockerCmd(c, "run", "-d", "-v", "/foo", "-v", tmpDir+"/test:/test", "-v", tmpDir+":/baz", "busybox", "/bin/sh", "-c", "touch /foo/bar").Stdout() + containerID = strings.TrimSpace(containerID) - containerID := strings.TrimSpace(out) - - out, _ = dockerCmd(c, "wait", containerID) + out := cli.DockerCmd(c, "wait", containerID).Combined() assert.Equal(c, strings.TrimSpace(out), "0", "failed to set up container") // Copy actual volume path - dockerCmd(c, "cp", containerID+":/foo", outDir) + cli.DockerCmd(c, "cp", containerID+":/foo", outDir) stat, err := os.Stat(outDir + "/foo") assert.NilError(c, err) @@ -458,20 +442,20 @@ func (s *DockerCLICpSuite) TestCpVolumePath(c *testing.T) { assert.Assert(c, !stat.IsDir(), "Expected file `bar` to be a file") // Copy file nested in volume - dockerCmd(c, "cp", containerID+":/foo/bar", outDir) + cli.DockerCmd(c, "cp", containerID+":/foo/bar", outDir) stat, err = os.Stat(outDir + "/bar") assert.NilError(c, err) assert.Assert(c, !stat.IsDir(), "Expected file `bar` to be a file") // Copy Bind-mounted dir - dockerCmd(c, "cp", containerID+":/baz", outDir) + cli.DockerCmd(c, "cp", containerID+":/baz", outDir) stat, err = os.Stat(outDir + "/baz") assert.NilError(c, err) assert.Assert(c, stat.IsDir(), "Expected `baz` to be a dir") // Copy file nested in bind-mounted dir - dockerCmd(c, "cp", containerID+":/baz/test", outDir) + cli.DockerCmd(c, "cp", containerID+":/baz/test", outDir) fb, err := os.ReadFile(outDir + "/baz/test") assert.NilError(c, err) fb2, err := os.ReadFile(tmpDir + "/test") @@ -479,7 +463,7 @@ func (s *DockerCLICpSuite) TestCpVolumePath(c *testing.T) { assert.Assert(c, bytes.Equal(fb, fb2), "Expected copied file to be duplicate of bind-mounted file") // Copy bind-mounted file - dockerCmd(c, "cp", containerID+":/test", outDir) + cli.DockerCmd(c, "cp", containerID+":/test", outDir) fb, err = os.ReadFile(outDir + "/test") assert.NilError(c, err) fb2, err = os.ReadFile(tmpDir + "/test") @@ -488,11 +472,10 @@ func (s *DockerCLICpSuite) TestCpVolumePath(c *testing.T) { } func (s *DockerCLICpSuite) TestCpToDot(c *testing.T) { - out, _ := dockerCmd(c, "run", "-d", "busybox", "/bin/sh", "-c", "echo lololol > /test") + containerID := cli.DockerCmd(c, "run", "-d", "busybox", "/bin/sh", "-c", "echo lololol > /test").Stdout() + containerID = strings.TrimSpace(containerID) - containerID := strings.TrimSpace(out) - - out, _ = dockerCmd(c, "wait", containerID) + out := cli.DockerCmd(c, "wait", containerID).Combined() assert.Equal(c, strings.TrimSpace(out), "0", "failed to set up container") tmpdir, err := os.MkdirTemp("", "docker-integration") @@ -504,18 +487,17 @@ func (s *DockerCLICpSuite) TestCpToDot(c *testing.T) { err = os.Chdir(tmpdir) assert.NilError(c, err) - dockerCmd(c, "cp", containerID+":/test", ".") + cli.DockerCmd(c, "cp", containerID+":/test", ".") content, err := os.ReadFile("./test") assert.NilError(c, err) assert.Equal(c, string(content), "lololol\n") } func (s *DockerCLICpSuite) TestCpToStdout(c *testing.T) { - out, _ := dockerCmd(c, "run", "-d", "busybox", "/bin/sh", "-c", "echo lololol > /test") + containerID := cli.DockerCmd(c, "run", "-d", "busybox", "/bin/sh", "-c", "echo lololol > /test").Stdout() + containerID = strings.TrimSpace(containerID) - containerID := strings.TrimSpace(out) - - out, _ = dockerCmd(c, "wait", containerID) + out := cli.DockerCmd(c, "wait", containerID).Combined() assert.Equal(c, strings.TrimSpace(out), "0", "failed to set up container") out, err := RunCommandPipelineWithOutput( @@ -530,17 +512,16 @@ func (s *DockerCLICpSuite) TestCpToStdout(c *testing.T) { func (s *DockerCLICpSuite) TestCpNameHasColon(c *testing.T) { testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux) - out, _ := dockerCmd(c, "run", "-d", "busybox", "/bin/sh", "-c", "echo lololol > /te:s:t") + containerID := cli.DockerCmd(c, "run", "-d", "busybox", "/bin/sh", "-c", "echo lololol > /te:s:t").Stdout() + containerID = strings.TrimSpace(containerID) - containerID := strings.TrimSpace(out) - - out, _ = dockerCmd(c, "wait", containerID) + out := cli.DockerCmd(c, "wait", containerID).Combined() assert.Equal(c, strings.TrimSpace(out), "0", "failed to set up container") tmpdir, err := os.MkdirTemp("", "docker-integration") assert.NilError(c, err) defer os.RemoveAll(tmpdir) - dockerCmd(c, "cp", containerID+":/te:s:t", tmpdir) + cli.DockerCmd(c, "cp", containerID+":/te:s:t", tmpdir) content, err := os.ReadFile(tmpdir + "/te:s:t") assert.NilError(c, err) assert.Equal(c, string(content), "lololol\n") @@ -548,31 +529,31 @@ func (s *DockerCLICpSuite) TestCpNameHasColon(c *testing.T) { func (s *DockerCLICpSuite) TestCopyAndRestart(c *testing.T) { testRequires(c, DaemonIsLinux) - expectedMsg := "hello" - out, _ := dockerCmd(c, "run", "-d", "busybox", "echo", expectedMsg) - containerID := strings.TrimSpace(out) + const expectedMsg = "hello" + containerID := cli.DockerCmd(c, "run", "-d", "busybox", "echo", expectedMsg).Stdout() + containerID = strings.TrimSpace(containerID) - out, _ = dockerCmd(c, "wait", containerID) + out := cli.DockerCmd(c, "wait", containerID).Combined() assert.Equal(c, strings.TrimSpace(out), "0", "failed to set up container") tmpDir, err := os.MkdirTemp("", "test-docker-restart-after-copy-") assert.NilError(c, err) defer os.RemoveAll(tmpDir) - dockerCmd(c, "cp", fmt.Sprintf("%s:/etc/group", containerID), tmpDir) + cli.DockerCmd(c, "cp", fmt.Sprintf("%s:/etc/group", containerID), tmpDir) - out, _ = dockerCmd(c, "start", "-a", containerID) + out = cli.DockerCmd(c, "start", "-a", containerID).Combined() assert.Equal(c, strings.TrimSpace(out), expectedMsg) } func (s *DockerCLICpSuite) TestCopyCreatedContainer(c *testing.T) { testRequires(c, DaemonIsLinux) - dockerCmd(c, "create", "--name", "test_cp", "-v", "/test", "busybox") + cli.DockerCmd(c, "create", "--name", "test_cp", "-v", "/test", "busybox") tmpDir, err := os.MkdirTemp("", "test") assert.NilError(c, err) defer os.RemoveAll(tmpDir) - dockerCmd(c, "cp", "test_cp:/bin/sh", tmpDir) + cli.DockerCmd(c, "cp", "test_cp:/bin/sh", tmpDir) } // test copy with option `-L`: following symbol link @@ -580,12 +561,11 @@ func (s *DockerCLICpSuite) TestCopyCreatedContainer(c *testing.T) { // a container to host following symbol link func (s *DockerCLICpSuite) TestCpSymlinkFromConToHostFollowSymlink(c *testing.T) { testRequires(c, DaemonIsLinux) - out, exitCode := dockerCmd(c, "run", "-d", "busybox", "/bin/sh", "-c", "mkdir -p '"+cpTestPath+"' && echo -n '"+cpContainerContents+"' > "+cpFullPath+" && ln -s "+cpFullPath+" /dir_link") - assert.Equal(c, exitCode, 0, "failed to set up container: %s", out) + result := cli.DockerCmd(c, "run", "-d", "busybox", "/bin/sh", "-c", "mkdir -p '"+cpTestPath+"' && echo -n '"+cpContainerContents+"' > "+cpFullPath+" && ln -s "+cpFullPath+" /dir_link") + assert.Equal(c, result.ExitCode, 0, "failed to set up container: %s", result.Combined()) + containerID := strings.TrimSpace(result.Stdout()) - cleanedContainerID := strings.TrimSpace(out) - - out, _ = dockerCmd(c, "wait", cleanedContainerID) + out := cli.DockerCmd(c, "wait", containerID).Combined() assert.Equal(c, strings.TrimSpace(out), "0", "failed to set up container") testDir, err := os.MkdirTemp("", "test-cp-symlink-container-to-host-follow-symlink") @@ -594,7 +574,7 @@ func (s *DockerCLICpSuite) TestCpSymlinkFromConToHostFollowSymlink(c *testing.T) // This copy command should copy the symlink, not the target, into the // temporary directory. - dockerCmd(c, "cp", "-L", cleanedContainerID+":"+"/dir_link", testDir) + cli.DockerCmd(c, "cp", "-L", containerID+":"+"/dir_link", testDir) expectedPath := filepath.Join(testDir, "dir_link") @@ -611,7 +591,7 @@ func (s *DockerCLICpSuite) TestCpSymlinkFromConToHostFollowSymlink(c *testing.T) os.Remove(expectedPath) } - dockerCmd(c, "cp", "-L", cleanedContainerID+":"+"/dir_link", expectedPath) + cli.DockerCmd(c, "cp", "-L", containerID+":"+"/dir_link", expectedPath) actual, err = os.ReadFile(expectedPath) assert.NilError(c, err) diff --git a/integration-cli/docker_cli_cp_to_container_unix_test.go b/integration-cli/docker_cli_cp_to_container_unix_test.go index 040b9322df..10213beb00 100644 --- a/integration-cli/docker_cli_cp_to_container_unix_test.go +++ b/integration-cli/docker_cli_cp_to_container_unix_test.go @@ -12,6 +12,7 @@ import ( "syscall" "testing" + "github.com/docker/docker/integration-cli/cli" "gotest.tools/v3/assert" ) @@ -25,9 +26,9 @@ func (s *DockerCLICpSuite) TestCpToContainerWithPermissions(c *testing.T) { containerName := "permtest" - _, exc := dockerCmd(c, "create", "--name", containerName, "busybox", "/bin/sh", "-c", "stat -c '%u %g %a' /permdirtest /permdirtest/permtest") + exc := cli.DockerCmd(c, "create", "--name", containerName, "busybox", "/bin/sh", "-c", "stat -c '%u %g %a' /permdirtest /permdirtest/permtest").ExitCode assert.Equal(c, exc, 0) - defer dockerCmd(c, "rm", "-f", containerName) + defer cli.DockerCmd(c, "rm", "-f", containerName) srcPath := cpPath(tmpDir, "permdirtest") dstPath := containerCpPath(containerName, "/") diff --git a/integration-cli/docker_cli_cp_utils_test.go b/integration-cli/docker_cli_cp_utils_test.go index a62638b2a0..847d1100a6 100644 --- a/integration-cli/docker_cli_cp_utils_test.go +++ b/integration-cli/docker_cli_cp_utils_test.go @@ -11,6 +11,7 @@ import ( "strings" "testing" + "github.com/docker/docker/integration-cli/cli" "github.com/docker/docker/pkg/archive" "gotest.tools/v3/assert" ) @@ -150,15 +151,15 @@ func makeTestContainer(c *testing.T, options testContainerOptions) (containerID args = append(args, "busybox", "/bin/sh", "-c", options.command) - out, _ := dockerCmd(c, args...) + out := cli.DockerCmd(c, args...).Combined() containerID = strings.TrimSpace(out) - out, _ = dockerCmd(c, "wait", containerID) + out = cli.DockerCmd(c, "wait", containerID).Combined() exitCode := strings.TrimSpace(out) if exitCode != "0" { - out, _ = dockerCmd(c, "logs", containerID) + out = cli.DockerCmd(c, "logs", containerID).Combined() } assert.Equal(c, exitCode, "0", "failed to make test container: %s", out) diff --git a/integration-cli/docker_cli_create_test.go b/integration-cli/docker_cli_create_test.go index ce888cec7d..f3912d805d 100644 --- a/integration-cli/docker_cli_create_test.go +++ b/integration-cli/docker_cli_create_test.go @@ -33,11 +33,10 @@ func (s *DockerCLICreateSuite) OnTimeout(c *testing.T) { // Make sure we can create a simple container with some args func (s *DockerCLICreateSuite) TestCreateArgs(c *testing.T) { // Intentionally clear entrypoint, as the Windows busybox image needs an entrypoint, which breaks this test - out, _ := dockerCmd(c, "create", "--entrypoint=", "busybox", "command", "arg1", "arg2", "arg with space", "-c", "flags") + containerID := cli.DockerCmd(c, "create", "--entrypoint=", "busybox", "command", "arg1", "arg2", "arg with space", "-c", "flags").Stdout() + containerID = strings.TrimSpace(containerID) - cleanedContainerID := strings.TrimSpace(out) - - out, _ = dockerCmd(c, "inspect", cleanedContainerID) + out := cli.DockerCmd(c, "inspect", containerID).Combined() var containers []struct { Path string @@ -66,11 +65,10 @@ func (s *DockerCLICreateSuite) TestCreateArgs(c *testing.T) { // Make sure we can set hostconfig options too func (s *DockerCLICreateSuite) TestCreateHostConfig(c *testing.T) { - out, _ := dockerCmd(c, "create", "-P", "busybox", "echo") + containerID := cli.DockerCmd(c, "create", "-P", "busybox", "echo").Stdout() + containerID = strings.TrimSpace(containerID) - cleanedContainerID := strings.TrimSpace(out) - - out, _ = dockerCmd(c, "inspect", cleanedContainerID) + out := cli.DockerCmd(c, "inspect", containerID).Stdout() var containers []struct { HostConfig *struct { @@ -88,11 +86,10 @@ func (s *DockerCLICreateSuite) TestCreateHostConfig(c *testing.T) { } func (s *DockerCLICreateSuite) TestCreateWithPortRange(c *testing.T) { - out, _ := dockerCmd(c, "create", "-p", "3300-3303:3300-3303/tcp", "busybox", "echo") + containerID := cli.DockerCmd(c, "create", "-p", "3300-3303:3300-3303/tcp", "busybox", "echo").Stdout() + containerID = strings.TrimSpace(containerID) - cleanedContainerID := strings.TrimSpace(out) - - out, _ = dockerCmd(c, "inspect", cleanedContainerID) + out := cli.DockerCmd(c, "inspect", containerID).Stdout() var containers []struct { HostConfig *struct { @@ -115,11 +112,10 @@ func (s *DockerCLICreateSuite) TestCreateWithPortRange(c *testing.T) { } func (s *DockerCLICreateSuite) TestCreateWithLargePortRange(c *testing.T) { - out, _ := dockerCmd(c, "create", "-p", "1-65535:1-65535/tcp", "busybox", "echo") + containerID := cli.DockerCmd(c, "create", "-p", "1-65535:1-65535/tcp", "busybox", "echo").Stdout() + containerID = strings.TrimSpace(containerID) - cleanedContainerID := strings.TrimSpace(out) - - out, _ = dockerCmd(c, "inspect", cleanedContainerID) + out := cli.DockerCmd(c, "inspect", containerID).Stdout() var containers []struct { HostConfig *struct { @@ -143,11 +139,10 @@ func (s *DockerCLICreateSuite) TestCreateWithLargePortRange(c *testing.T) { // "test123" should be printed by docker create + start func (s *DockerCLICreateSuite) TestCreateEchoStdout(c *testing.T) { - out, _ := dockerCmd(c, "create", "busybox", "echo", "test123") + containerID := cli.DockerCmd(c, "create", "busybox", "echo", "test123").Stdout() + containerID = strings.TrimSpace(containerID) - cleanedContainerID := strings.TrimSpace(out) - - out, _ = dockerCmd(c, "start", "-ai", cleanedContainerID) + out := cli.DockerCmd(c, "start", "-ai", containerID).Combined() assert.Equal(c, out, "test123\n", "container should've printed 'test123', got %q", out) } @@ -155,8 +150,8 @@ func (s *DockerCLICreateSuite) TestCreateVolumesCreated(c *testing.T) { testRequires(c, testEnv.IsLocalDaemon) prefix, slash := getPrefixAndSlashFromDaemonPlatform() - name := "test_create_volume" - dockerCmd(c, "create", "--name", name, "-v", prefix+slash+"foo", "busybox") + const name = "test_create_volume" + cli.DockerCmd(c, "create", "--name", name, "-v", prefix+slash+"foo", "busybox") dir, err := inspectMountSourceField(name, prefix+slash+"foo") assert.Assert(c, err == nil, "Error getting volume host path: %q", err) @@ -170,9 +165,9 @@ func (s *DockerCLICreateSuite) TestCreateVolumesCreated(c *testing.T) { } func (s *DockerCLICreateSuite) TestCreateLabels(c *testing.T) { - name := "test_create_labels" + const name = "test_create_labels" expected := map[string]string{"k1": "v1", "k2": "v2"} - dockerCmd(c, "create", "--name", name, "-l", "k1=v1", "--label", "k2=v2", "busybox") + cli.DockerCmd(c, "create", "--name", name, "-l", "k1=v1", "--label", "k2=v2", "busybox") actual := make(map[string]string) inspectFieldAndUnmarshall(c, name, "Config.Labels", &actual) @@ -187,9 +182,9 @@ func (s *DockerCLICreateSuite) TestCreateLabelFromImage(c *testing.T) { buildImageSuccessfully(c, imageName, build.WithDockerfile(`FROM busybox LABEL k1=v1 k2=v2`)) - name := "test_create_labels_from_image" + const name = "test_create_labels_from_image" expected := map[string]string{"k2": "x", "k3": "v3", "k1": "v1"} - dockerCmd(c, "create", "--name", name, "-l", "k2=x", "--label", "k3=v3", imageName) + cli.DockerCmd(c, "create", "--name", name, "-l", "k2=x", "--label", "k3=v3", imageName) actual := make(map[string]string) inspectFieldAndUnmarshall(c, name, "Config.Labels", &actual) @@ -205,7 +200,7 @@ func (s *DockerCLICreateSuite) TestCreateHostnameWithNumber(c *testing.T) { if testEnv.DaemonInfo.OSType == "windows" { image = testEnv.PlatformDefaults.BaseImage } - out, _ := dockerCmd(c, "run", "-h", "web.0", image, "hostname") + out := cli.DockerCmd(c, "run", "-h", "web.0", image, "hostname").Combined() assert.Equal(c, strings.TrimSpace(out), "web.0", "hostname not set, expected `web.0`, got: %s", out) } @@ -214,26 +209,24 @@ func (s *DockerCLICreateSuite) TestCreateRM(c *testing.T) { // "Created" state, and has ever been run. Test "rm -f" too. // create a container - out, _ := dockerCmd(c, "create", "busybox") - cID := strings.TrimSpace(out) - - dockerCmd(c, "rm", cID) + cID := cli.DockerCmd(c, "create", "busybox").Stdout() + cID = strings.TrimSpace(cID) + cli.DockerCmd(c, "rm", cID) // Now do it again so we can "rm -f" this time - out, _ = dockerCmd(c, "create", "busybox") - - cID = strings.TrimSpace(out) - dockerCmd(c, "rm", "-f", cID) + cID = cli.DockerCmd(c, "create", "busybox").Stdout() + cID = strings.TrimSpace(cID) + cli.DockerCmd(c, "rm", "-f", cID) } func (s *DockerCLICreateSuite) TestCreateModeIpcContainer(c *testing.T) { // Uses Linux specific functionality (--ipc) testRequires(c, DaemonIsLinux, testEnv.IsLocalDaemon) - out, _ := dockerCmd(c, "create", "busybox") - id := strings.TrimSpace(out) + id := cli.DockerCmd(c, "create", "busybox").Stdout() + id = strings.TrimSpace(id) - dockerCmd(c, "create", fmt.Sprintf("--ipc=container:%s", id), "busybox") + cli.DockerCmd(c, "create", fmt.Sprintf("--ipc=container:%s", id), "busybox") } func (s *DockerCLICreateSuite) TestCreateByImageID(c *testing.T) { @@ -243,8 +236,8 @@ func (s *DockerCLICreateSuite) TestCreateByImageID(c *testing.T) { imageID := getIDByName(c, imageName) truncatedImageID := stringid.TruncateID(imageID) - dockerCmd(c, "create", imageID) - dockerCmd(c, "create", truncatedImageID) + cli.DockerCmd(c, "create", imageID) + cli.DockerCmd(c, "create", truncatedImageID) // Ensure this fails out, exit, _ := dockerCmdWithError("create", fmt.Sprintf("%s:%s", imageName, imageID)) @@ -270,43 +263,43 @@ func (s *DockerCLICreateSuite) TestCreateByImageID(c *testing.T) { } func (s *DockerCLICreateSuite) TestCreateStopSignal(c *testing.T) { - name := "test_create_stop_signal" - dockerCmd(c, "create", "--name", name, "--stop-signal", "9", "busybox") + const name = "test_create_stop_signal" + cli.DockerCmd(c, "create", "--name", name, "--stop-signal", "9", "busybox") res := inspectFieldJSON(c, name, "Config.StopSignal") assert.Assert(c, strings.Contains(res, "9")) } func (s *DockerCLICreateSuite) TestCreateWithWorkdir(c *testing.T) { - name := "foo" + const name = "foo" prefix, slash := getPrefixAndSlashFromDaemonPlatform() dir := prefix + slash + "home" + slash + "foo" + slash + "bar" - dockerCmd(c, "create", "--name", name, "-w", dir, "busybox") + cli.DockerCmd(c, "create", "--name", name, "-w", dir, "busybox") // Windows does not create the workdir until the container is started if testEnv.DaemonInfo.OSType == "windows" { - dockerCmd(c, "start", name) + cli.DockerCmd(c, "start", name) if testEnv.DaemonInfo.Isolation.IsHyperV() { // Hyper-V isolated containers do not allow file-operations on a // running container. This test currently uses `docker cp` to verify // that the WORKDIR was automatically created, which cannot be done // while the container is running. - dockerCmd(c, "stop", name) + cli.DockerCmd(c, "stop", name) } } // TODO: rewrite this test to not use `docker cp` for verifying that the WORKDIR was created - dockerCmd(c, "cp", fmt.Sprintf("%s:%s", name, dir), prefix+slash+"tmp") + cli.DockerCmd(c, "cp", fmt.Sprintf("%s:%s", name, dir), prefix+slash+"tmp") } func (s *DockerCLICreateSuite) TestCreateWithInvalidLogOpts(c *testing.T) { - name := "test-invalidate-log-opts" + const name = "test-invalidate-log-opts" out, _, err := dockerCmdWithError("create", "--name", name, "--log-opt", "invalid=true", "busybox") assert.ErrorContains(c, err, "") assert.Assert(c, strings.Contains(out, "unknown log opt")) assert.Assert(c, is.Contains(out, "unknown log opt")) - out, _ = dockerCmd(c, "ps", "-a") + out = cli.DockerCmd(c, "ps", "-a").Stdout() assert.Assert(c, !strings.Contains(out, name)) } @@ -315,12 +308,12 @@ func (s *DockerCLICreateSuite) TestCreate64ByteHexID(c *testing.T) { out := inspectField(c, "busybox", "Id") imageID := strings.TrimPrefix(strings.TrimSpace(out), "sha256:") - dockerCmd(c, "create", imageID) + cli.DockerCmd(c, "create", imageID) } // Test case for #23498 func (s *DockerCLICreateSuite) TestCreateUnsetEntrypoint(c *testing.T) { - name := "test-entrypoint" + const name = "test-entrypoint" dockerfile := `FROM busybox ADD entrypoint.sh /entrypoint.sh RUN chmod 755 /entrypoint.sh @@ -348,12 +341,12 @@ exec "$@"`, // #22471 func (s *DockerCLICreateSuite) TestCreateStopTimeout(c *testing.T) { name1 := "test_create_stop_timeout_1" - dockerCmd(c, "create", "--name", name1, "--stop-timeout", "15", "busybox") + cli.DockerCmd(c, "create", "--name", name1, "--stop-timeout", "15", "busybox") res := inspectFieldJSON(c, name1, "Config.StopTimeout") assert.Assert(c, strings.Contains(res, "15")) name2 := "test_create_stop_timeout_2" - dockerCmd(c, "create", "--name", name2, "busybox") + cli.DockerCmd(c, "create", "--name", name2, "busybox") res = inspectFieldJSON(c, name2, "Config.StopTimeout") assert.Assert(c, strings.Contains(res, "null")) diff --git a/integration-cli/docker_cli_daemon_test.go b/integration-cli/docker_cli_daemon_test.go index bbbca6794f..84e469747b 100644 --- a/integration-cli/docker_cli_daemon_test.go +++ b/integration-cli/docker_cli_daemon_test.go @@ -1267,7 +1267,7 @@ func pingContainers(c *testing.T, d *daemon.Daemon, expectFailure bool) { } args := append(dargs, "run", "-d", "--name", "container1", "busybox", "top") - dockerCmd(c, args...) + cli.DockerCmd(c, args...) args = append(dargs, "run", "--rm", "--link", "container1:alias1", "busybox", "sh", "-c") pingCmd := "ping -c 1 %s -W 1" @@ -1281,7 +1281,7 @@ func pingContainers(c *testing.T, d *daemon.Daemon, expectFailure bool) { } args = append(dargs, "rm", "-f", "container1") - dockerCmd(c, args...) + cli.DockerCmd(c, args...) } func (s *DockerDaemonSuite) TestDaemonRestartWithSocketAsVolume(c *testing.T) { @@ -1549,14 +1549,13 @@ func (s *DockerDaemonSuite) TestDaemonStartWithDefaultTLSHost(c *testing.T) { // The client with --tlsverify should also use default host localhost:2376 c.Setenv("DOCKER_HOST", "") - out, _ := dockerCmd( - c, + out := cli.DockerCmd(c, "--tlsverify", "--tlscacert", "fixtures/https/ca.pem", "--tlscert", "fixtures/https/client-cert.pem", "--tlskey", "fixtures/https/client-key.pem", "version", - ) + ).Stdout() if !strings.Contains(out, "Server") { c.Fatalf("docker version should return information of server side") } @@ -1627,10 +1626,10 @@ func (s *DockerDaemonSuite) TestDaemonNoSpaceLeftOnDeviceError(c *testing.T) { // create a 3MiB image (with a 2MiB ext4 fs) and mount it as graph root // Why in a container? Because `mount` sometimes behaves weirdly and often fails outright on this test in debian:bullseye (which is what the test suite runs under if run from the Makefile) - dockerCmd(c, "run", "--rm", "-v", testDir+":/test", "busybox", "sh", "-c", "dd of=/test/testfs.img bs=1M seek=3 count=0") + cli.DockerCmd(c, "run", "--rm", "-v", testDir+":/test", "busybox", "sh", "-c", "dd of=/test/testfs.img bs=1M seek=3 count=0") icmd.RunCommand("mkfs.ext4", "-F", filepath.Join(testDir, "testfs.img")).Assert(c, icmd.Success) - dockerCmd(c, "run", "--privileged", "--rm", "-v", testDir+":/test:shared", "busybox", "sh", "-c", "mkdir -p /test/test-mount && mount -n -t ext4 /test/testfs.img /test/test-mount") + cli.DockerCmd(c, "run", "--privileged", "--rm", "-v", testDir+":/test:shared", "busybox", "sh", "-c", "mkdir -p /test/test-mount && mount -n -t ext4 /test/testfs.img /test/test-mount") defer mount.Unmount(filepath.Join(testDir, "test-mount")) driver := "vfs" @@ -1732,8 +1731,8 @@ func (s *DockerDaemonSuite) TestDaemonCgroupParent(c *testing.T) { id := strings.TrimSpace(out) expectedCgroup := path.Join(cgroupParent, id) found := false - for _, path := range cgroupPaths { - if strings.HasSuffix(path, expectedCgroup) { + for _, p := range cgroupPaths { + if strings.HasSuffix(p, expectedCgroup) { found = true break } @@ -2768,13 +2767,13 @@ func (s *DockerDaemonSuite) TestFailedPluginRemove(c *testing.T) { testRequires(c, DaemonIsLinux, IsAmd64, testEnv.IsLocalDaemon) d := daemon.New(c, dockerBinary, dockerdBinary) d.Start(c) - cli := d.NewClientT(c) + apiClient := d.NewClientT(c) ctx, cancel := context.WithTimeout(testutil.GetContext(c), 300*time.Second) defer cancel() name := "test-plugin-rm-fail" - out, err := cli.PluginInstall(ctx, name, types.PluginInstallOptions{ + out, err := apiClient.PluginInstall(ctx, name, types.PluginInstallOptions{ Disabled: true, AcceptAllPermissions: true, RemoteRef: "cpuguy83/docker-logdriver-test", @@ -2785,7 +2784,7 @@ func (s *DockerDaemonSuite) TestFailedPluginRemove(c *testing.T) { ctx, cancel = context.WithTimeout(testutil.GetContext(c), 30*time.Second) defer cancel() - p, _, err := cli.PluginInspectWithRaw(ctx, name) + p, _, err := apiClient.PluginInspectWithRaw(ctx, name) assert.NilError(c, err) // simulate a bad/partial removal by removing the plugin config. @@ -2795,10 +2794,10 @@ func (s *DockerDaemonSuite) TestFailedPluginRemove(c *testing.T) { d.Restart(c) ctx, cancel = context.WithTimeout(testutil.GetContext(c), 30*time.Second) defer cancel() - _, err = cli.Ping(ctx) + _, err = apiClient.Ping(ctx) assert.NilError(c, err) - _, _, err = cli.PluginInspectWithRaw(ctx, name) + _, _, err = apiClient.PluginInspectWithRaw(ctx, name) // plugin should be gone since the config.json is gone assert.ErrorContains(c, err, "") } diff --git a/integration-cli/docker_cli_events_test.go b/integration-cli/docker_cli_events_test.go index 244a71fa74..1e655e666a 100644 --- a/integration-cli/docker_cli_events_test.go +++ b/integration-cli/docker_cli_events_test.go @@ -43,7 +43,7 @@ func (s *DockerCLIEventSuite) TestEventsTimestampFormats(c *testing.T) { // Start stopwatch, generate an event start := daemonTime(c) time.Sleep(1100 * time.Millisecond) // so that first event occur in different second from since (just for the case) - dockerCmd(c, "run", "--rm", "--name", name, "busybox", "true") + cli.DockerCmd(c, "run", "--rm", "--name", name, "busybox", "true") time.Sleep(1100 * time.Millisecond) // so that until > since end := daemonTime(c) @@ -55,7 +55,7 @@ func (s *DockerCLIEventSuite) TestEventsTimestampFormats(c *testing.T) { // --since=$start must contain only the 'untag' event for _, f := range []func(time.Time) string{unixTs, rfc3339, duration} { since, until := f(start), f(end) - out, _ := dockerCmd(c, "events", "--since="+since, "--until="+until) + out := cli.DockerCmd(c, "events", "--since="+since, "--until="+until).Stdout() events := strings.Split(out, "\n") events = events[:len(events)-1] @@ -68,10 +68,10 @@ func (s *DockerCLIEventSuite) TestEventsTimestampFormats(c *testing.T) { func (s *DockerCLIEventSuite) TestEventsUntag(c *testing.T) { image := "busybox" - dockerCmd(c, "tag", image, "utest:tag1") - dockerCmd(c, "tag", image, "utest:tag2") - dockerCmd(c, "rmi", "utest:tag1") - dockerCmd(c, "rmi", "utest:tag2") + cli.DockerCmd(c, "tag", image, "utest:tag1") + cli.DockerCmd(c, "tag", image, "utest:tag2") + cli.DockerCmd(c, "rmi", "utest:tag1") + cli.DockerCmd(c, "rmi", "utest:tag2") result := icmd.RunCmd(icmd.Cmd{ Command: []string{dockerBinary, "events", "--since=1"}, @@ -90,9 +90,9 @@ func (s *DockerCLIEventSuite) TestEventsUntag(c *testing.T) { } func (s *DockerCLIEventSuite) TestEventsContainerEvents(c *testing.T) { - dockerCmd(c, "run", "--rm", "--name", "container-events-test", "busybox", "true") + cli.DockerCmd(c, "run", "--rm", "--name", "container-events-test", "busybox", "true") - out, _ := dockerCmd(c, "events", "--until", daemonUnixTime(c)) + out := cli.DockerCmd(c, "events", "--until", daemonUnixTime(c)).Stdout() events := strings.Split(out, "\n") events = events[:len(events)-1] @@ -105,9 +105,9 @@ func (s *DockerCLIEventSuite) TestEventsContainerEvents(c *testing.T) { func (s *DockerCLIEventSuite) TestEventsContainerEventsAttrSort(c *testing.T) { since := daemonUnixTime(c) - dockerCmd(c, "run", "--rm", "--name", "container-events-test", "busybox", "true") + cli.DockerCmd(c, "run", "--rm", "--name", "container-events-test", "busybox", "true") - out, _ := dockerCmd(c, "events", "--filter", "container=container-events-test", "--since", since, "--until", daemonUnixTime(c)) + out := cli.DockerCmd(c, "events", "--filter", "container=container-events-test", "--since", since, "--until", daemonUnixTime(c)).Stdout() events := strings.Split(out, "\n") nEvents := len(events) @@ -127,10 +127,10 @@ func (s *DockerCLIEventSuite) TestEventsContainerEventsAttrSort(c *testing.T) { } func (s *DockerCLIEventSuite) TestEventsContainerEventsSinceUnixEpoch(c *testing.T) { - dockerCmd(c, "run", "--rm", "--name", "since-epoch-test", "busybox", "true") + cli.DockerCmd(c, "run", "--rm", "--name", "since-epoch-test", "busybox", "true") timeBeginning := time.Unix(0, 0).Format(time.RFC3339Nano) timeBeginning = strings.ReplaceAll(timeBeginning, "Z", ".000000000Z") - out, _ := dockerCmd(c, "events", "--since", timeBeginning, "--until", daemonUnixTime(c)) + out := cli.DockerCmd(c, "events", "--since", timeBeginning, "--until", daemonUnixTime(c)).Stdout() events := strings.Split(out, "\n") events = events[:len(events)-1] @@ -144,10 +144,9 @@ func (s *DockerCLIEventSuite) TestEventsImageTag(c *testing.T) { time.Sleep(1 * time.Second) // because API has seconds granularity since := daemonUnixTime(c) image := "testimageevents:tag" - dockerCmd(c, "tag", "busybox", image) + cli.DockerCmd(c, "tag", "busybox", image) - out, _ := dockerCmd(c, "events", - "--since", since, "--until", daemonUnixTime(c)) + out := cli.DockerCmd(c, "events", "--since", since, "--until", daemonUnixTime(c)).Stdout() events := strings.Split(strings.TrimSpace(out), "\n") assert.Equal(c, len(events), 1, "was expecting 1 event. out=%s", out) @@ -164,11 +163,9 @@ func (s *DockerCLIEventSuite) TestEventsImagePull(c *testing.T) { since := daemonUnixTime(c) testRequires(c, Network) - dockerCmd(c, "pull", "hello-world") - - out, _ := dockerCmd(c, "events", - "--since", since, "--until", daemonUnixTime(c)) + cli.DockerCmd(c, "pull", "hello-world") + out := cli.DockerCmd(c, "events", "--since", since, "--until", daemonUnixTime(c)).Stdout() events := strings.Split(strings.TrimSpace(out), "\n") event := strings.TrimSpace(events[len(events)-1]) matches := eventstestutils.ScanMap(event) @@ -181,7 +178,7 @@ func (s *DockerCLIEventSuite) TestEventsImageImport(c *testing.T) { // more reliable (@swernli) testRequires(c, DaemonIsLinux) - out, _ := dockerCmd(c, "run", "-d", "busybox", "true") + out := cli.DockerCmd(c, "run", "-d", "busybox", "true").Stdout() cleanedContainerID := strings.TrimSpace(out) since := daemonUnixTime(c) @@ -192,7 +189,7 @@ func (s *DockerCLIEventSuite) TestEventsImageImport(c *testing.T) { assert.NilError(c, err, "import failed with output: %q", out) imageRef := strings.TrimSpace(out) - out, _ = dockerCmd(c, "events", "--since", since, "--until", daemonUnixTime(c), "--filter", "event=import") + out = cli.DockerCmd(c, "events", "--since", since, "--until", daemonUnixTime(c), "--filter", "event=import").Stdout() events := strings.Split(strings.TrimSpace(out), "\n") assert.Equal(c, len(events), 1) matches := eventstestutils.ScanMap(events[0]) @@ -203,35 +200,35 @@ func (s *DockerCLIEventSuite) TestEventsImageImport(c *testing.T) { func (s *DockerCLIEventSuite) TestEventsImageLoad(c *testing.T) { testRequires(c, DaemonIsLinux) myImageName := "footest:v1" - dockerCmd(c, "tag", "busybox", myImageName) + cli.DockerCmd(c, "tag", "busybox", myImageName) since := daemonUnixTime(c) - out, _ := dockerCmd(c, "images", "-q", "--no-trunc", myImageName) + out := cli.DockerCmd(c, "images", "-q", "--no-trunc", myImageName).Stdout() longImageID := strings.TrimSpace(out) assert.Assert(c, longImageID != "", "Id should not be empty") - dockerCmd(c, "save", "-o", "saveimg.tar", myImageName) - dockerCmd(c, "rmi", myImageName) - out, _ = dockerCmd(c, "images", "-q", myImageName) + cli.DockerCmd(c, "save", "-o", "saveimg.tar", myImageName) + cli.DockerCmd(c, "rmi", myImageName) + out = cli.DockerCmd(c, "images", "-q", myImageName).Stdout() noImageID := strings.TrimSpace(out) assert.Equal(c, noImageID, "", "Should not have any image") - dockerCmd(c, "load", "-i", "saveimg.tar") + cli.DockerCmd(c, "load", "-i", "saveimg.tar") result := icmd.RunCommand("rm", "-rf", "saveimg.tar") result.Assert(c, icmd.Success) - out, _ = dockerCmd(c, "images", "-q", "--no-trunc", myImageName) + out = cli.DockerCmd(c, "images", "-q", "--no-trunc", myImageName).Stdout() imageID := strings.TrimSpace(out) assert.Equal(c, imageID, longImageID, "Should have same image id as before") - out, _ = dockerCmd(c, "events", "--since", since, "--until", daemonUnixTime(c), "--filter", "event=load") + out = cli.DockerCmd(c, "events", "--since", since, "--until", daemonUnixTime(c), "--filter", "event=load").Stdout() events := strings.Split(strings.TrimSpace(out), "\n") assert.Equal(c, len(events), 1) matches := eventstestutils.ScanMap(events[0]) assert.Equal(c, matches["id"], imageID, "matches: %v\nout:\n%s\n", matches, out) assert.Equal(c, matches["action"], "load", "matches: %v\nout:\n%s\n", matches, out) - out, _ = dockerCmd(c, "events", "--since", since, "--until", daemonUnixTime(c), "--filter", "event=save") + out = cli.DockerCmd(c, "events", "--since", since, "--until", daemonUnixTime(c), "--filter", "event=save").Stdout() events = strings.Split(strings.TrimSpace(out), "\n") assert.Equal(c, len(events), 1) matches = eventstestutils.ScanMap(events[0]) @@ -244,11 +241,11 @@ func (s *DockerCLIEventSuite) TestEventsPluginOps(c *testing.T) { since := daemonUnixTime(c) - dockerCmd(c, "plugin", "install", pNameWithTag, "--grant-all-permissions") - dockerCmd(c, "plugin", "disable", pNameWithTag) - dockerCmd(c, "plugin", "remove", pNameWithTag) + cli.DockerCmd(c, "plugin", "install", pNameWithTag, "--grant-all-permissions") + cli.DockerCmd(c, "plugin", "disable", pNameWithTag) + cli.DockerCmd(c, "plugin", "remove", pNameWithTag) - out, _ := dockerCmd(c, "events", "--since", since, "--until", daemonUnixTime(c)) + out := cli.DockerCmd(c, "events", "--since", since, "--until", daemonUnixTime(c)).Stdout() events := strings.Split(out, "\n") events = events[:len(events)-1] @@ -260,12 +257,12 @@ func (s *DockerCLIEventSuite) TestEventsPluginOps(c *testing.T) { func (s *DockerCLIEventSuite) TestEventsFilters(c *testing.T) { since := daemonUnixTime(c) - dockerCmd(c, "run", "--rm", "busybox", "true") - dockerCmd(c, "run", "--rm", "busybox", "true") - out, _ := dockerCmd(c, "events", "--since", since, "--until", daemonUnixTime(c), "--filter", "event=die") + cli.DockerCmd(c, "run", "--rm", "busybox", "true") + cli.DockerCmd(c, "run", "--rm", "busybox", "true") + out := cli.DockerCmd(c, "events", "--since", since, "--until", daemonUnixTime(c), "--filter", "event=die").Stdout() parseEvents(c, out, "die") - out, _ = dockerCmd(c, "events", "--since", since, "--until", daemonUnixTime(c), "--filter", "event=die", "--filter", "event=start") + out = cli.DockerCmd(c, "events", "--since", since, "--until", daemonUnixTime(c), "--filter", "event=die", "--filter", "event=start").Stdout() parseEvents(c, out, "die|start") // make sure we at least got 2 start events @@ -276,14 +273,14 @@ func (s *DockerCLIEventSuite) TestEventsFilters(c *testing.T) { func (s *DockerCLIEventSuite) TestEventsFilterImageName(c *testing.T) { since := daemonUnixTime(c) - out, _ := dockerCmd(c, "run", "--name", "container_1", "-d", "busybox:latest", "true") + out := cli.DockerCmd(c, "run", "--name", "container_1", "-d", "busybox:latest", "true").Stdout() container1 := strings.TrimSpace(out) - out, _ = dockerCmd(c, "run", "--name", "container_2", "-d", "busybox", "true") + out = cli.DockerCmd(c, "run", "--name", "container_2", "-d", "busybox", "true").Stdout() container2 := strings.TrimSpace(out) name := "busybox" - out, _ = dockerCmd(c, "events", "--since", since, "--until", daemonUnixTime(c), "--filter", fmt.Sprintf("image=%s", name)) + out = cli.DockerCmd(c, "events", "--since", since, "--until", daemonUnixTime(c), "--filter", fmt.Sprintf("image=%s", name)).Stdout() events := strings.Split(out, "\n") events = events[:len(events)-1] assert.Assert(c, len(events) != 0, "Expected events but found none for the image busybox:latest") @@ -305,23 +302,22 @@ func (s *DockerCLIEventSuite) TestEventsFilterLabels(c *testing.T) { since := strconv.FormatUint(uint64(daemonTime(c).Unix()), 10) label := "io.docker.testing=foo" - out, exit := dockerCmd(c, "create", "-l", label, "busybox") - assert.Equal(c, exit, 0) - container1 := strings.TrimSpace(out) + result := cli.DockerCmd(c, "create", "-l", label, "busybox") + assert.Equal(c, result.ExitCode, 0) + container1 := strings.TrimSpace(result.Stdout()) - out, exit = dockerCmd(c, "create", "busybox") - assert.Equal(c, exit, 0) - container2 := strings.TrimSpace(out) + result = cli.DockerCmd(c, "create", "busybox") + assert.Equal(c, result.ExitCode, 0) + container2 := strings.TrimSpace(result.Stdout()) // fetch events with `--until`, so that the client detaches after a second // instead of staying attached, waiting for more events to arrive. - out, _ = dockerCmd( - c, + out := cli.DockerCmd(c, "events", "--since", since, "--until", strconv.FormatUint(uint64(daemonTime(c).Add(time.Second).Unix()), 10), "--filter", "label="+label, - ) + ).Stdout() events := strings.Split(strings.TrimSpace(out), "\n") assert.Assert(c, len(events) > 0) @@ -345,17 +341,17 @@ func (s *DockerCLIEventSuite) TestEventsFilterImageLabels(c *testing.T) { buildImageSuccessfully(c, name, build.WithDockerfile(fmt.Sprintf(` FROM busybox:latest LABEL %s`, label))) - dockerCmd(c, "tag", name, "labelfiltertest:tag1") - dockerCmd(c, "tag", name, "labelfiltertest:tag2") - dockerCmd(c, "tag", "busybox:latest", "labelfiltertest:tag3") + cli.DockerCmd(c, "tag", name, "labelfiltertest:tag1") + cli.DockerCmd(c, "tag", name, "labelfiltertest:tag2") + cli.DockerCmd(c, "tag", "busybox:latest", "labelfiltertest:tag3") - out, _ := dockerCmd( - c, + out := cli.DockerCmd(c, "events", "--since", since, "--until", daemonUnixTime(c), "--filter", fmt.Sprintf("label=%s", label), - "--filter", "type=image") + "--filter", "type=image", + ).Stdout() events := strings.Split(strings.TrimSpace(out), "\n") @@ -371,7 +367,7 @@ func (s *DockerCLIEventSuite) TestEventsFilterContainer(c *testing.T) { nameID := make(map[string]string) for _, name := range []string{"container_1", "container_2"} { - dockerCmd(c, "run", "--name", name, "busybox", "true") + cli.DockerCmd(c, "run", "--name", name, "busybox", "true") id := inspectField(c, name, "Id") nameID[name] = id } @@ -393,12 +389,12 @@ func (s *DockerCLIEventSuite) TestEventsFilterContainer(c *testing.T) { for name, ID := range nameID { // filter by names - out, _ := dockerCmd(c, "events", "--since", since, "--until", until, "--filter", "container="+name) + out := cli.DockerCmd(c, "events", "--since", since, "--until", until, "--filter", "container="+name).Stdout() events := strings.Split(strings.TrimSuffix(out, "\n"), "\n") assert.NilError(c, checkEvents(ID, events)) // filter by ID's - out, _ = dockerCmd(c, "events", "--since", since, "--until", until, "--filter", "container="+ID) + out = cli.DockerCmd(c, "events", "--since", since, "--until", until, "--filter", "container="+ID).Stdout() events = strings.Split(strings.TrimSuffix(out, "\n"), "\n") assert.NilError(c, checkEvents(ID, events)) } @@ -408,8 +404,7 @@ func (s *DockerCLIEventSuite) TestEventsCommit(c *testing.T) { // Problematic on Windows as cannot commit a running container testRequires(c, DaemonIsLinux) - out := runSleepingContainer(c) - cID := strings.TrimSpace(out) + cID := runSleepingContainer(c) cli.WaitRun(c, cID) cli.DockerCmd(c, "commit", "-m", "test", cID) @@ -417,7 +412,7 @@ func (s *DockerCLIEventSuite) TestEventsCommit(c *testing.T) { cli.WaitExited(c, cID, 5*time.Second) until := daemonUnixTime(c) - out = cli.DockerCmd(c, "events", "-f", "container="+cID, "--until="+until).Combined() + out := cli.DockerCmd(c, "events", "-f", "container="+cID, "--until="+until).Combined() assert.Assert(c, strings.Contains(out, "commit"), "Missing 'commit' log event") } @@ -435,25 +430,24 @@ func (s *DockerCLIEventSuite) TestEventsCopy(c *testing.T) { assert.NilError(c, tempFile.Close()) - dockerCmd(c, "create", "--name=cptest", id) + cli.DockerCmd(c, "create", "--name=cptest", id) - dockerCmd(c, "cp", "cptest:/file", tempFile.Name()) + cli.DockerCmd(c, "cp", "cptest:/file", tempFile.Name()) until := daemonUnixTime(c) - out, _ := dockerCmd(c, "events", "--since=0", "-f", "container=cptest", "--until="+until) + out := cli.DockerCmd(c, "events", "--since=0", "-f", "container=cptest", "--until="+until).Stdout() assert.Assert(c, strings.Contains(out, "archive-path"), "Missing 'archive-path' log event") - dockerCmd(c, "cp", tempFile.Name(), "cptest:/filecopy") + cli.DockerCmd(c, "cp", tempFile.Name(), "cptest:/filecopy") until = daemonUnixTime(c) - out, _ = dockerCmd(c, "events", "-f", "container=cptest", "--until="+until) + out = cli.DockerCmd(c, "events", "-f", "container=cptest", "--until="+until).Stdout() assert.Assert(c, strings.Contains(out, "extract-to-dir"), "Missing 'extract-to-dir' log event") } func (s *DockerCLIEventSuite) TestEventsResize(c *testing.T) { - out := runSleepingContainer(c, "-d", "-t") - cID := strings.TrimSpace(out) - assert.NilError(c, waitRun(cID)) + cID := runSleepingContainer(c, "-d", "-t") + cli.WaitRun(c, cID) apiClient, err := client.NewClientWithOpts(client.FromEnv) assert.NilError(c, err) @@ -466,10 +460,10 @@ func (s *DockerCLIEventSuite) TestEventsResize(c *testing.T) { err = apiClient.ContainerResize(testutil.GetContext(c), cID, options) assert.NilError(c, err) - dockerCmd(c, "stop", cID) + cli.DockerCmd(c, "stop", cID) until := daemonUnixTime(c) - out, _ = dockerCmd(c, "events", "-f", "container="+cID, "--until="+until) + out := cli.DockerCmd(c, "events", "-f", "container="+cID, "--until="+until).Combined() assert.Assert(c, strings.Contains(out, "resize"), "Missing 'resize' log event") } @@ -512,13 +506,13 @@ func (s *DockerCLIEventSuite) TestEventsAttach(c *testing.T) { } func (s *DockerCLIEventSuite) TestEventsRename(c *testing.T) { - out, _ := dockerCmd(c, "run", "--name", "oldName", "busybox", "true") + out := cli.DockerCmd(c, "run", "--name", "oldName", "busybox", "true").Stdout() cID := strings.TrimSpace(out) - dockerCmd(c, "rename", "oldName", "newName") + cli.DockerCmd(c, "rename", "oldName", "newName") until := daemonUnixTime(c) // filter by the container id because the name in the event will be the new name. - out, _ = dockerCmd(c, "events", "-f", "container="+cID, "--until", until) + out = cli.DockerCmd(c, "events", "-f", "container="+cID, "--until", until).Stdout() assert.Assert(c, strings.Contains(out, "rename"), "Missing 'rename' log event") } @@ -526,15 +520,14 @@ func (s *DockerCLIEventSuite) TestEventsTop(c *testing.T) { // Problematic on Windows as Windows does not support top testRequires(c, DaemonIsLinux) - out := runSleepingContainer(c, "-d") - cID := strings.TrimSpace(out) - assert.NilError(c, waitRun(cID)) + cID := runSleepingContainer(c, "-d") + cli.WaitRun(c, cID) - dockerCmd(c, "top", cID) - dockerCmd(c, "stop", cID) + cli.DockerCmd(c, "top", cID) + cli.DockerCmd(c, "stop", cID) until := daemonUnixTime(c) - out, _ = dockerCmd(c, "events", "-f", "container="+cID, "--until="+until) + out := cli.DockerCmd(c, "events", "-f", "container="+cID, "--until="+until).Combined() assert.Assert(c, strings.Contains(out, "top"), "Missing 'top' log event") } @@ -544,19 +537,19 @@ func (s *DockerRegistrySuite) TestEventsImageFilterPush(c *testing.T) { // supporting push testRequires(c, DaemonIsLinux) testRequires(c, Network) - repoName := fmt.Sprintf("%v/dockercli/testf", privateRegistryURL) + imgRepoName := fmt.Sprintf("%v/dockercli/testf", privateRegistryURL) - out, _ := dockerCmd(c, "run", "-d", "busybox", "top") + out := cli.DockerCmd(c, "run", "-d", "busybox", "top").Stdout() cID := strings.TrimSpace(out) - assert.NilError(c, waitRun(cID)) + cli.WaitRun(c, cID) - dockerCmd(c, "commit", cID, repoName) - dockerCmd(c, "stop", cID) - dockerCmd(c, "push", repoName) + cli.DockerCmd(c, "commit", cID, imgRepoName) + cli.DockerCmd(c, "stop", cID) + cli.DockerCmd(c, "push", imgRepoName) until := daemonUnixTime(c) - out, _ = dockerCmd(c, "events", "-f", "image="+repoName, "-f", "event=push", "--until", until) - assert.Assert(c, strings.Contains(out, repoName), "Missing 'push' log event for %s", repoName) + out = cli.DockerCmd(c, "events", "-f", "image="+imgRepoName, "-f", "event=push", "--until", until).Stdout() + assert.Assert(c, strings.Contains(out, imgRepoName), "Missing 'push' log event for %s", imgRepoName) } func (s *DockerCLIEventSuite) TestEventsFilterType(c *testing.T) { @@ -570,17 +563,17 @@ func (s *DockerCLIEventSuite) TestEventsFilterType(c *testing.T) { buildImageSuccessfully(c, name, build.WithDockerfile(fmt.Sprintf(` FROM busybox:latest LABEL %s`, label))) - dockerCmd(c, "tag", name, "labelfiltertest:tag1") - dockerCmd(c, "tag", name, "labelfiltertest:tag2") - dockerCmd(c, "tag", "busybox:latest", "labelfiltertest:tag3") + cli.DockerCmd(c, "tag", name, "labelfiltertest:tag1") + cli.DockerCmd(c, "tag", name, "labelfiltertest:tag2") + cli.DockerCmd(c, "tag", "busybox:latest", "labelfiltertest:tag3") - out, _ := dockerCmd( - c, + out := cli.DockerCmd(c, "events", "--since", since, "--until", daemonUnixTime(c), "--filter", fmt.Sprintf("label=%s", label), - "--filter", "type=image") + "--filter", "type=image", + ).Stdout() events := strings.Split(strings.TrimSpace(out), "\n") @@ -590,24 +583,24 @@ func (s *DockerCLIEventSuite) TestEventsFilterType(c *testing.T) { assert.Check(c, strings.Contains(e, "labelfiltertest")) } - out, _ = dockerCmd( - c, + out = cli.DockerCmd(c, "events", "--since", since, "--until", daemonUnixTime(c), "--filter", fmt.Sprintf("label=%s", label), - "--filter", "type=container") + "--filter", "type=container", + ).Stdout() events = strings.Split(strings.TrimSpace(out), "\n") // Events generated by the container that builds the image assert.Equal(c, len(events), 2, "Events == %s", events) - out, _ = dockerCmd( - c, + out = cli.DockerCmd(c, "events", "--since", since, "--until", daemonUnixTime(c), - "--filter", "type=network") + "--filter", "type=network", + ).Stdout() events = strings.Split(strings.TrimSpace(out), "\n") assert.Assert(c, len(events) >= 1, "Events == %s", events) } @@ -616,45 +609,42 @@ func (s *DockerCLIEventSuite) TestEventsFilterType(c *testing.T) { func (s *DockerCLIEventSuite) TestEventsSpecialFiltersWithExecCreate(c *testing.T) { since := daemonUnixTime(c) runSleepingContainer(c, "--name", "test-container", "-d") - waitRun("test-container") + cli.WaitRun(c, "test-container") - dockerCmd(c, "exec", "test-container", "echo", "hello-world") + cli.DockerCmd(c, "exec", "test-container", "echo", "hello-world") - out, _ := dockerCmd( - c, + out := cli.DockerCmd(c, "events", "--since", since, "--until", daemonUnixTime(c), "--filter", "event='exec_create: echo hello-world'", - ) + ).Stdout() events := strings.Split(strings.TrimSpace(out), "\n") assert.Equal(c, len(events), 1, out) - out, _ = dockerCmd( - c, + out = cli.DockerCmd(c, "events", "--since", since, "--until", daemonUnixTime(c), "--filter", "event=exec_create", - ) + ).Stdout() assert.Equal(c, len(events), 1, out) } func (s *DockerCLIEventSuite) TestEventsFilterImageInContainerAction(c *testing.T) { since := daemonUnixTime(c) - dockerCmd(c, "run", "--name", "test-container", "-d", "busybox", "true") - waitRun("test-container") + cli.DockerCmd(c, "run", "-d", "busybox", "true") - out, _ := dockerCmd(c, "events", "--filter", "image=busybox", "--since", since, "--until", daemonUnixTime(c)) + out := cli.DockerCmd(c, "events", "--filter", "image=busybox", "--since", since, "--until", daemonUnixTime(c)).Stdout() events := strings.Split(strings.TrimSpace(out), "\n") assert.Assert(c, len(events) > 1, out) } func (s *DockerCLIEventSuite) TestEventsContainerRestart(c *testing.T) { - dockerCmd(c, "run", "-d", "--name=testEvent", "--restart=on-failure:3", "busybox", "false") + cli.DockerCmd(c, "run", "-d", "--name=testEvent", "--restart=on-failure:3", "busybox", "false") // wait until test2 is auto removed. waitTime := 10 * time.Second @@ -671,7 +661,7 @@ func (s *DockerCLIEventSuite) TestEventsContainerRestart(c *testing.T) { startCount int dieCount int ) - out, _ := dockerCmd(c, "events", "--since=0", "--until", daemonUnixTime(c), "-f", "container=testEvent") + out := cli.DockerCmd(c, "events", "--since=0", "--until", daemonUnixTime(c), "-f", "container=testEvent").Stdout() events := strings.Split(strings.TrimSpace(out), "\n") nEvents := len(events) @@ -694,8 +684,7 @@ func (s *DockerCLIEventSuite) TestEventsContainerRestart(c *testing.T) { } func (s *DockerCLIEventSuite) TestEventsSinceInTheFuture(c *testing.T) { - dockerCmd(c, "run", "--name", "test-container", "-d", "busybox", "true") - waitRun("test-container") + cli.DockerCmd(c, "run", "--name", "test-container", "-d", "busybox", "true") since := daemonTime(c) until := since.Add(time.Duration(-24) * time.Hour) @@ -708,15 +697,13 @@ func (s *DockerCLIEventSuite) TestEventsSinceInTheFuture(c *testing.T) { func (s *DockerCLIEventSuite) TestEventsUntilInThePast(c *testing.T) { since := daemonUnixTime(c) - dockerCmd(c, "run", "--name", "test-container", "-d", "busybox", "true") - waitRun("test-container") + cli.DockerCmd(c, "run", "--name", "test-container", "-d", "busybox", "true") until := daemonUnixTime(c) - dockerCmd(c, "run", "--name", "test-container2", "-d", "busybox", "true") - waitRun("test-container2") + cli.DockerCmd(c, "run", "--name", "test-container2", "-d", "busybox", "true") - out, _ := dockerCmd(c, "events", "--filter", "image=busybox", "--since", since, "--until", until) + out := cli.DockerCmd(c, "events", "--filter", "image=busybox", "--since", since, "--until", until).Stdout() assert.Assert(c, !strings.Contains(out, "test-container2")) assert.Assert(c, strings.Contains(out, "test-container")) @@ -724,9 +711,9 @@ func (s *DockerCLIEventSuite) TestEventsUntilInThePast(c *testing.T) { func (s *DockerCLIEventSuite) TestEventsFormat(c *testing.T) { since := daemonUnixTime(c) - dockerCmd(c, "run", "--rm", "busybox", "true") - dockerCmd(c, "run", "--rm", "busybox", "true") - out, _ := dockerCmd(c, "events", "--since", since, "--until", daemonUnixTime(c), "--format", "{{json .}}") + cli.DockerCmd(c, "run", "--rm", "busybox", "true") + cli.DockerCmd(c, "run", "--rm", "busybox", "true") + out := cli.DockerCmd(c, "events", "--since", since, "--until", daemonUnixTime(c), "--format", "{{json .}}").Stdout() dec := json.NewDecoder(strings.NewReader(out)) // make sure we got 2 start events startCount := 0 @@ -747,7 +734,7 @@ func (s *DockerCLIEventSuite) TestEventsFormat(c *testing.T) { func (s *DockerCLIEventSuite) TestEventsFormatBadFunc(c *testing.T) { // make sure it fails immediately, without receiving any event - result := dockerCmdWithResult("events", "--format", "{{badFuncString .}}") + result := cli.Docker(cli.Args("events", "--format", "{{badFuncString .}}")) result.Assert(c, icmd.Expected{ Error: "exit status 64", ExitCode: 64, @@ -757,7 +744,7 @@ func (s *DockerCLIEventSuite) TestEventsFormatBadFunc(c *testing.T) { func (s *DockerCLIEventSuite) TestEventsFormatBadField(c *testing.T) { // make sure it fails immediately, without receiving any event - result := dockerCmdWithResult("events", "--format", "{{.badFieldString}}") + result := cli.Docker(cli.Args("events", "--format", "{{.badFieldString}}")) result.Assert(c, icmd.Expected{ Error: "exit status 64", ExitCode: 64, diff --git a/integration-cli/docker_cli_events_unix_test.go b/integration-cli/docker_cli_events_unix_test.go index a213ff072a..1e22763bc3 100644 --- a/integration-cli/docker_cli_events_unix_test.go +++ b/integration-cli/docker_cli_events_unix_test.go @@ -14,6 +14,7 @@ import ( "unicode" "github.com/creack/pty" + "github.com/docker/docker/integration-cli/cli" "github.com/docker/docker/integration-cli/cli/build" "golang.org/x/sys/unix" "gotest.tools/v3/assert" @@ -24,7 +25,7 @@ import ( // #5979 func (s *DockerCLIEventSuite) TestEventsRedirectStdout(c *testing.T) { since := daemonUnixTime(c) - dockerCmd(c, "run", "busybox", "true") + cli.DockerCmd(c, "run", "busybox", "true") file, err := os.CreateTemp("", "") assert.NilError(c, err, "could not create temp file") @@ -67,7 +68,7 @@ func (s *DockerCLIEventSuite) TestEventsOOMDisableFalse(c *testing.T) { c.Fatal("Timeout waiting for container to die on OOM") } - out, _ := dockerCmd(c, "events", "--since=0", "-f", "container=oomFalse", "--until", daemonUnixTime(c)) + out := cli.DockerCmd(c, "events", "--since=0", "-f", "container=oomFalse", "--until", daemonUnixTime(c)).Stdout() events := strings.Split(strings.TrimSuffix(out, "\n"), "\n") nEvents := len(events) @@ -98,7 +99,7 @@ func (s *DockerCLIEventSuite) TestEventsOOMDisableTrue(c *testing.T) { } }() - assert.NilError(c, waitRun("oomTrue")) + cli.WaitRun(c, "oomTrue") defer dockerCmdWithResult("kill", "oomTrue") containerID := inspectField(c, "oomTrue", "Id") @@ -130,13 +131,13 @@ func (s *DockerCLIEventSuite) TestEventsOOMDisableTrue(c *testing.T) { // #18453 func (s *DockerCLIEventSuite) TestEventsContainerFilterByName(c *testing.T) { testRequires(c, DaemonIsLinux) - cOut, _ := dockerCmd(c, "run", "--name=foo", "-d", "busybox", "top") + cOut := cli.DockerCmd(c, "run", "--name=foo", "-d", "busybox", "top").Stdout() c1 := strings.TrimSpace(cOut) - waitRun("foo") - cOut, _ = dockerCmd(c, "run", "--name=bar", "-d", "busybox", "top") + cli.WaitRun(c, "foo") + cOut = cli.DockerCmd(c, "run", "--name=bar", "-d", "busybox", "top").Stdout() c2 := strings.TrimSpace(cOut) - waitRun("bar") - out, _ := dockerCmd(c, "events", "-f", "container=foo", "--since=0", "--until", daemonUnixTime(c)) + cli.WaitRun(c, "bar") + out := cli.DockerCmd(c, "events", "-f", "container=foo", "--since=0", "--until", daemonUnixTime(c)).Stdout() assert.Assert(c, strings.Contains(out, c1), out) assert.Assert(c, !strings.Contains(out, c2), out) } @@ -153,7 +154,7 @@ func (s *DockerCLIEventSuite) TestEventsContainerFilterBeforeCreate(c *testing.T // Sleep for a second to make sure we are testing the case where events are listened before container starts. time.Sleep(time.Second) - id, _ := dockerCmd(c, "run", "--name=foo", "-d", "busybox", "top") + id := cli.DockerCmd(c, "run", "--name=foo", "-d", "busybox", "top").Stdout() cID := strings.TrimSpace(id) for i := 0; ; i++ { out := buf.String() @@ -173,16 +174,15 @@ func (s *DockerCLIEventSuite) TestVolumeEvents(c *testing.T) { since := daemonUnixTime(c) // Observe create/mount volume actions - dockerCmd(c, "volume", "create", "test-event-volume-local") - dockerCmd(c, "run", "--name", "test-volume-container", "--volume", "test-event-volume-local:/foo", "-d", "busybox", "true") - waitRun("test-volume-container") + cli.DockerCmd(c, "volume", "create", "test-event-volume-local") + cli.DockerCmd(c, "run", "--name", "test-volume-container", "--volume", "test-event-volume-local:/foo", "-d", "busybox", "true") // Observe unmount/destroy volume actions - dockerCmd(c, "rm", "-f", "test-volume-container") - dockerCmd(c, "volume", "rm", "test-event-volume-local") + cli.DockerCmd(c, "rm", "-f", "test-volume-container") + cli.DockerCmd(c, "volume", "rm", "test-event-volume-local") until := daemonUnixTime(c) - out, _ := dockerCmd(c, "events", "--since", since, "--until", until) + out := cli.DockerCmd(c, "events", "--since", since, "--until", until).Stdout() events := strings.Split(strings.TrimSpace(out), "\n") assert.Assert(c, len(events) > 3) @@ -200,16 +200,15 @@ func (s *DockerCLIEventSuite) TestNetworkEvents(c *testing.T) { since := daemonUnixTime(c) // Observe create/connect network actions - dockerCmd(c, "network", "create", "test-event-network-local") - dockerCmd(c, "run", "--name", "test-network-container", "--net", "test-event-network-local", "-d", "busybox", "true") - waitRun("test-network-container") + cli.DockerCmd(c, "network", "create", "test-event-network-local") + cli.DockerCmd(c, "run", "--name", "test-network-container", "--net", "test-event-network-local", "-d", "busybox", "true") // Observe disconnect/destroy network actions - dockerCmd(c, "rm", "-f", "test-network-container") - dockerCmd(c, "network", "rm", "test-event-network-local") + cli.DockerCmd(c, "rm", "-f", "test-network-container") + cli.DockerCmd(c, "network", "rm", "test-event-network-local") until := daemonUnixTime(c) - out, _ := dockerCmd(c, "events", "--since", since, "--until", until) + out := cli.DockerCmd(c, "events", "--since", since, "--until", until).Stdout() events := strings.Split(strings.TrimSpace(out), "\n") assert.Assert(c, len(events) > 4) @@ -225,18 +224,18 @@ func (s *DockerCLIEventSuite) TestEventsContainerWithMultiNetwork(c *testing.T) testRequires(c, DaemonIsLinux) // Observe create/connect network actions - dockerCmd(c, "network", "create", "test-event-network-local-1") - dockerCmd(c, "network", "create", "test-event-network-local-2") - dockerCmd(c, "run", "--name", "test-network-container", "--net", "test-event-network-local-1", "-td", "busybox", "sh") - waitRun("test-network-container") - dockerCmd(c, "network", "connect", "test-event-network-local-2", "test-network-container") + cli.DockerCmd(c, "network", "create", "test-event-network-local-1") + cli.DockerCmd(c, "network", "create", "test-event-network-local-2") + cli.DockerCmd(c, "run", "--name", "test-network-container", "--net", "test-event-network-local-1", "-td", "busybox", "sh") + cli.WaitRun(c, "test-network-container") + cli.DockerCmd(c, "network", "connect", "test-event-network-local-2", "test-network-container") since := daemonUnixTime(c) - dockerCmd(c, "stop", "-t", "1", "test-network-container") + cli.DockerCmd(c, "stop", "-t", "1", "test-network-container") until := daemonUnixTime(c) - out, _ := dockerCmd(c, "events", "--since", since, "--until", until, "-f", "type=network") + out := cli.DockerCmd(c, "events", "--since", since, "--until", until, "-f", "type=network").Stdout() netEvents := strings.Split(strings.TrimSpace(out), "\n") // received two network disconnect events @@ -258,7 +257,7 @@ func (s *DockerCLIEventSuite) TestEventsStreaming(c *testing.T) { assert.NilError(c, err) defer observer.Stop() - out, _ := dockerCmd(c, "run", "-d", "busybox:latest", "true") + out := cli.DockerCmd(c, "run", "-d", "busybox:latest", "true").Stdout() containerID := strings.TrimSpace(out) testActions := map[string]chan bool{ @@ -293,7 +292,7 @@ func (s *DockerCLIEventSuite) TestEventsStreaming(c *testing.T) { // ignore, done } - dockerCmd(c, "rm", containerID) + cli.DockerCmd(c, "rm", containerID) select { case <-time.After(5 * time.Second): @@ -347,10 +346,10 @@ func (s *DockerCLIEventSuite) TestEventsFilterVolumeAndNetworkType(c *testing.T) since := daemonUnixTime(c) - dockerCmd(c, "network", "create", "test-event-network-type") - dockerCmd(c, "volume", "create", "test-event-volume-type") + cli.DockerCmd(c, "network", "create", "test-event-network-type") + cli.DockerCmd(c, "volume", "create", "test-event-volume-type") - out, _ := dockerCmd(c, "events", "--filter", "type=volume", "--filter", "type=network", "--since", since, "--until", daemonUnixTime(c)) + out := cli.DockerCmd(c, "events", "--filter", "type=volume", "--filter", "type=network", "--since", since, "--until", daemonUnixTime(c)).Stdout() events := strings.Split(strings.TrimSpace(out), "\n") assert.Assert(c, len(events) >= 2, out) @@ -366,8 +365,8 @@ func (s *DockerCLIEventSuite) TestEventsFilterVolumeID(c *testing.T) { since := daemonUnixTime(c) - dockerCmd(c, "volume", "create", "test-event-volume-id") - out, _ := dockerCmd(c, "events", "--filter", "volume=test-event-volume-id", "--since", since, "--until", daemonUnixTime(c)) + cli.DockerCmd(c, "volume", "create", "test-event-volume-id") + out := cli.DockerCmd(c, "events", "--filter", "volume=test-event-volume-id", "--since", since, "--until", daemonUnixTime(c)).Stdout() events := strings.Split(strings.TrimSpace(out), "\n") assert.Equal(c, len(events), 1) @@ -381,8 +380,8 @@ func (s *DockerCLIEventSuite) TestEventsFilterNetworkID(c *testing.T) { since := daemonUnixTime(c) - dockerCmd(c, "network", "create", "test-event-network-local") - out, _ := dockerCmd(c, "events", "--filter", "network=test-event-network-local", "--since", since, "--until", daemonUnixTime(c)) + cli.DockerCmd(c, "network", "create", "test-event-network-local") + out := cli.DockerCmd(c, "events", "--filter", "network=test-event-network-local", "--since", since, "--until", daemonUnixTime(c)).Stdout() events := strings.Split(strings.TrimSpace(out), "\n") assert.Equal(c, len(events), 1) assert.Assert(c, strings.Contains(events[0], "test-event-network-local")) diff --git a/integration-cli/docker_cli_exec_test.go b/integration-cli/docker_cli_exec_test.go index c3da7ffab4..80d51d061d 100644 --- a/integration-cli/docker_cli_exec_test.go +++ b/integration-cli/docker_cli_exec_test.go @@ -37,16 +37,16 @@ func (s *DockerCLIExecSuite) OnTimeout(c *testing.T) { func (s *DockerCLIExecSuite) TestExec(c *testing.T) { testRequires(c, DaemonIsLinux) - out, _ := dockerCmd(c, "run", "-d", "--name", "testing", "busybox", "sh", "-c", "echo test > /tmp/file && top") - assert.NilError(c, waitRun(strings.TrimSpace(out))) + out := cli.DockerCmd(c, "run", "-d", "--name", "testing", "busybox", "sh", "-c", "echo test > /tmp/file && top").Stdout() + cli.WaitRun(c, strings.TrimSpace(out)) - out, _ = dockerCmd(c, "exec", "testing", "cat", "/tmp/file") + out = cli.DockerCmd(c, "exec", "testing", "cat", "/tmp/file").Stdout() assert.Equal(c, strings.Trim(out, "\r\n"), "test") } func (s *DockerCLIExecSuite) TestExecInteractive(c *testing.T) { testRequires(c, DaemonIsLinux) - dockerCmd(c, "run", "-d", "--name", "testing", "busybox", "sh", "-c", "echo test > /tmp/file && top") + cli.DockerCmd(c, "run", "-d", "--name", "testing", "busybox", "sh", "-c", "echo test > /tmp/file && top") execCmd := exec.Command(dockerBinary, "exec", "-i", "testing", "sh") stdin, err := execCmd.StdinPipe() @@ -80,13 +80,12 @@ func (s *DockerCLIExecSuite) TestExecInteractive(c *testing.T) { } func (s *DockerCLIExecSuite) TestExecAfterContainerRestart(c *testing.T) { - out := runSleepingContainer(c) - cleanedContainerID := strings.TrimSpace(out) - assert.NilError(c, waitRun(cleanedContainerID)) - dockerCmd(c, "restart", cleanedContainerID) - assert.NilError(c, waitRun(cleanedContainerID)) + cID := runSleepingContainer(c) + cli.WaitRun(c, cID) + cli.DockerCmd(c, "restart", cID) + cli.WaitRun(c, cID) - out, _ = dockerCmd(c, "exec", cleanedContainerID, "echo", "hello") + out := cli.DockerCmd(c, "exec", cID, "echo", "hello").Combined() assert.Equal(c, strings.TrimSpace(out), "hello") } @@ -116,9 +115,9 @@ func (s *DockerCLIExecSuite) TestExecEnv(c *testing.T) { // a subsequent exec will not have LALA set/ testRequires(c, DaemonIsLinux) runSleepingContainer(c, "-e", "LALA=value1", "-e", "LALA=value2", "-d", "--name", "testing") - assert.NilError(c, waitRun("testing")) + cli.WaitRun(c, "testing") - out, _ := dockerCmd(c, "exec", "testing", "env") + out := cli.DockerCmd(c, "exec", "testing", "env").Stdout() assert.Check(c, !strings.Contains(out, "LALA=value1")) assert.Check(c, strings.Contains(out, "LALA=value2")) assert.Check(c, strings.Contains(out, "HOME=/root")) @@ -127,9 +126,9 @@ func (s *DockerCLIExecSuite) TestExecEnv(c *testing.T) { func (s *DockerCLIExecSuite) TestExecSetEnv(c *testing.T) { testRequires(c, DaemonIsLinux) runSleepingContainer(c, "-e", "HOME=/root", "-d", "--name", "testing") - assert.NilError(c, waitRun("testing")) + cli.WaitRun(c, "testing") - out, _ := dockerCmd(c, "exec", "-e", "HOME=/another", "-e", "ABC=xyz", "testing", "env") + out := cli.DockerCmd(c, "exec", "-e", "HOME=/another", "-e", "ABC=xyz", "testing", "env").Stdout() assert.Check(c, !strings.Contains(out, "HOME=/root")) assert.Check(c, strings.Contains(out, "HOME=/another")) assert.Check(c, strings.Contains(out, "ABC=xyz")) @@ -145,10 +144,9 @@ func (s *DockerCLIExecSuite) TestExecExitStatus(c *testing.T) { func (s *DockerCLIExecSuite) TestExecPausedContainer(c *testing.T) { testRequires(c, IsPausable) - out := runSleepingContainer(c, "-d", "--name", "testing") - ContainerID := strings.TrimSpace(out) + ContainerID := runSleepingContainer(c, "-d", "--name", "testing") - dockerCmd(c, "pause", "testing") + cli.DockerCmd(c, "pause", "testing") out, _, err := dockerCmdWithError("exec", ContainerID, "echo", "hello") assert.ErrorContains(c, err, "", "container should fail to exec new command if it is paused") @@ -160,7 +158,7 @@ func (s *DockerCLIExecSuite) TestExecPausedContainer(c *testing.T) { func (s *DockerCLIExecSuite) TestExecTTYCloseStdin(c *testing.T) { // TODO Windows CI: This requires some work to port to Windows. testRequires(c, DaemonIsLinux) - dockerCmd(c, "run", "-d", "-it", "--name", "exec_tty_stdin", "busybox") + cli.DockerCmd(c, "run", "-d", "-it", "--name", "exec_tty_stdin", "busybox") cmd := exec.Command(dockerBinary, "exec", "-i", "exec_tty_stdin", "cat") stdinRw, err := cmd.StdinPipe() @@ -172,16 +170,16 @@ func (s *DockerCLIExecSuite) TestExecTTYCloseStdin(c *testing.T) { out, _, err := runCommandWithOutput(cmd) assert.NilError(c, err, out) - out, _ = dockerCmd(c, "top", "exec_tty_stdin") + out = cli.DockerCmd(c, "top", "exec_tty_stdin").Combined() outArr := strings.Split(out, "\n") assert.Assert(c, len(outArr) <= 3, "exec process left running") assert.Assert(c, !strings.Contains(out, "nsenter-exec")) } func (s *DockerCLIExecSuite) TestExecTTYWithoutStdin(c *testing.T) { - out, _ := dockerCmd(c, "run", "-d", "-ti", "busybox") + out := cli.DockerCmd(c, "run", "-d", "-ti", "busybox").Stdout() id := strings.TrimSpace(out) - assert.NilError(c, waitRun(id)) + cli.WaitRun(c, id) errChan := make(chan error, 1) go func() { @@ -219,7 +217,7 @@ func (s *DockerCLIExecSuite) TestExecParseError(c *testing.T) { // TODO Windows CI: Requires some extra work. Consider copying the // runSleepingContainer helper to have an exec version. testRequires(c, DaemonIsLinux) - dockerCmd(c, "run", "-d", "--name", "top", "busybox", "top") + cli.DockerCmd(c, "run", "-d", "--name", "top", "busybox", "top") // Test normal (non-detached) case first icmd.RunCommand(dockerBinary, "exec", "top").Assert(c, icmd.Expected{ @@ -233,7 +231,7 @@ func (s *DockerCLIExecSuite) TestExecStopNotHanging(c *testing.T) { // TODO Windows CI: Requires some extra work. Consider copying the // runSleepingContainer helper to have an exec version. testRequires(c, DaemonIsLinux) - dockerCmd(c, "run", "-d", "--name", "testing", "busybox", "top") + cli.DockerCmd(c, "run", "-d", "--name", "testing", "busybox", "top") result := icmd.StartCmd(icmd.Command(dockerBinary, "exec", "testing", "top")) result.Assert(c, icmd.Success) @@ -261,9 +259,9 @@ func (s *DockerCLIExecSuite) TestExecCgroup(c *testing.T) { // Not applicable on Windows - using Linux specific functionality testRequires(c, NotUserNamespace) testRequires(c, DaemonIsLinux) - dockerCmd(c, "run", "-d", "--name", "testing", "busybox", "top") + cli.DockerCmd(c, "run", "-d", "--name", "testing", "busybox", "top") - out, _ := dockerCmd(c, "exec", "testing", "cat", "/proc/1/cgroup") + out := cli.DockerCmd(c, "exec", "testing", "cat", "/proc/1/cgroup").Stdout() containerCgroups := sort.StringSlice(strings.Split(out, "\n")) var wg sync.WaitGroup @@ -311,10 +309,9 @@ func (s *DockerCLIExecSuite) TestExecCgroup(c *testing.T) { } func (s *DockerCLIExecSuite) TestExecInspectID(c *testing.T) { - out := runSleepingContainer(c, "-d") - id := strings.TrimSuffix(out, "\n") + id := runSleepingContainer(c, "-d") - out = inspectField(c, id, "ExecIDs") + out := inspectField(c, id, "ExecIDs") assert.Equal(c, out, "[]", "ExecIDs should be empty, got: %s", out) // Start an exec, have it block waiting so we can do some checking @@ -370,8 +367,8 @@ func (s *DockerCLIExecSuite) TestExecInspectID(c *testing.T) { // Now delete the container and then an 'inspect' on the exec should // result in a 404 (not 'container not running') - out, ec := dockerCmd(c, "rm", "-f", id) - assert.Equal(c, ec, 0, "error removing container: %s", out) + res := cli.DockerCmd(c, "rm", "-f", id) + assert.Equal(c, res.ExitCode, 0, "error removing container: %s", res.Combined()) _, err = apiClient.ContainerExecInspect(testutil.GetContext(c), execID) assert.ErrorContains(c, err, "No such exec instance") @@ -380,17 +377,16 @@ func (s *DockerCLIExecSuite) TestExecInspectID(c *testing.T) { func (s *DockerCLIExecSuite) TestLinksPingLinkedContainersOnRename(c *testing.T) { // Problematic on Windows as Windows does not support links testRequires(c, DaemonIsLinux) - var out string - out, _ = dockerCmd(c, "run", "-d", "--name", "container1", "busybox", "top") + out := cli.DockerCmd(c, "run", "-d", "--name", "container1", "busybox", "top").Stdout() idA := strings.TrimSpace(out) assert.Assert(c, idA != "", "%s, id should not be nil", out) - out, _ = dockerCmd(c, "run", "-d", "--link", "container1:alias1", "--name", "container2", "busybox", "top") + out = cli.DockerCmd(c, "run", "-d", "--link", "container1:alias1", "--name", "container2", "busybox", "top").Stdout() idB := strings.TrimSpace(out) assert.Assert(c, idB != "", "%s, id should not be nil", out) - dockerCmd(c, "exec", "container2", "ping", "-c", "1", "alias1", "-W", "1") - dockerCmd(c, "rename", "container1", "container_new") - dockerCmd(c, "exec", "container2", "ping", "-c", "1", "alias1", "-W", "1") + cli.DockerCmd(c, "exec", "container2", "ping", "-c", "1", "alias1", "-W", "1") + cli.DockerCmd(c, "rename", "container1", "container_new") + cli.DockerCmd(c, "exec", "container2", "ping", "-c", "1", "alias1", "-W", "1") } func (s *DockerCLIExecSuite) TestRunMutableNetworkFiles(c *testing.T) { @@ -406,7 +402,7 @@ func (s *DockerCLIExecSuite) TestRunMutableNetworkFiles(c *testing.T) { assert.Equal(c, strings.TrimSpace(string(content)), "success", "Content was not what was modified in the container", string(content)) - out, _ := dockerCmd(c, "run", "-d", "--name", "c2", "busybox", "top") + out := cli.DockerCmd(c, "run", "-d", "--name", "c2", "busybox", "top").Stdout() contID := strings.TrimSpace(out) netFilePath := containerStorageFile(contID, fn) @@ -429,7 +425,7 @@ func (s *DockerCLIExecSuite) TestRunMutableNetworkFiles(c *testing.T) { } f.Close() - res, _ := dockerCmd(c, "exec", contID, "cat", "/etc/"+fn) + res := cli.DockerCmd(c, "exec", contID, "cat", "/etc/"+fn).Stdout() assert.Equal(c, res, "success2\n") } } @@ -438,12 +434,12 @@ func (s *DockerCLIExecSuite) TestExecWithUser(c *testing.T) { // TODO Windows CI: This may be fixable in the future once Windows // supports users testRequires(c, DaemonIsLinux) - dockerCmd(c, "run", "-d", "--name", "parent", "busybox", "top") + cli.DockerCmd(c, "run", "-d", "--name", "parent", "busybox", "top") - out, _ := dockerCmd(c, "exec", "-u", "1", "parent", "id") + out := cli.DockerCmd(c, "exec", "-u", "1", "parent", "id").Stdout() assert.Assert(c, strings.Contains(out, "uid=1(daemon) gid=1(daemon)")) - out, _ = dockerCmd(c, "exec", "-u", "root", "parent", "id") + out = cli.DockerCmd(c, "exec", "-u", "root", "parent", "id").Stdout() assert.Assert(c, strings.Contains(out, "uid=0(root) gid=0(root)"), "exec with user by id expected daemon user got %s", out) } @@ -451,7 +447,7 @@ func (s *DockerCLIExecSuite) TestExecWithPrivileged(c *testing.T) { // Not applicable on Windows testRequires(c, DaemonIsLinux, NotUserNamespace) // Start main loop which attempts mknod repeatedly - dockerCmd(c, "run", "-d", "--name", "parent", "--cap-drop=ALL", "busybox", "sh", "-c", `while (true); do if [ -e /exec_priv ]; then cat /exec_priv && mknod /tmp/sda b 8 0 && echo "Success"; else echo "Privileged exec has not run yet"; fi; usleep 10000; done`) + cli.DockerCmd(c, "run", "-d", "--name", "parent", "--cap-drop=ALL", "busybox", "sh", "-c", `while (true); do if [ -e /exec_priv ]; then cat /exec_priv && mknod /tmp/sda b 8 0 && echo "Success"; else echo "Privileged exec has not run yet"; fi; usleep 10000; done`) // Check exec mknod doesn't work icmd.RunCommand(dockerBinary, "exec", "parent", "sh", "-c", "mknod /tmp/sdb b 8 16").Assert(c, icmd.Expected{ @@ -480,13 +476,13 @@ func (s *DockerCLIExecSuite) TestExecWithPrivileged(c *testing.T) { func (s *DockerCLIExecSuite) TestExecWithImageUser(c *testing.T) { // Not applicable on Windows testRequires(c, DaemonIsLinux) - name := "testbuilduser" + const name = "testbuilduser" buildImageSuccessfully(c, name, build.WithDockerfile(`FROM busybox RUN echo 'dockerio:x:1001:1001::/bin:/bin/false' >> /etc/passwd USER dockerio`)) - dockerCmd(c, "run", "-d", "--name", "dockerioexec", name, "top") + cli.DockerCmd(c, "run", "-d", "--name", "dockerioexec", name, "top") - out, _ := dockerCmd(c, "exec", "dockerioexec", "whoami") + out := cli.DockerCmd(c, "exec", "dockerioexec", "whoami").Stdout() assert.Assert(c, strings.Contains(out, "dockerio"), "exec with user by id expected dockerio user got %s", out) } @@ -494,15 +490,15 @@ func (s *DockerCLIExecSuite) TestExecOnReadonlyContainer(c *testing.T) { // Windows does not support read-only // --read-only + userns has remount issues testRequires(c, DaemonIsLinux, NotUserNamespace) - dockerCmd(c, "run", "-d", "--read-only", "--name", "parent", "busybox", "top") - dockerCmd(c, "exec", "parent", "true") + cli.DockerCmd(c, "run", "-d", "--read-only", "--name", "parent", "busybox", "top") + cli.DockerCmd(c, "exec", "parent", "true") } func (s *DockerCLIExecSuite) TestExecUlimits(c *testing.T) { testRequires(c, DaemonIsLinux) - name := "testexeculimits" + const name = "testexeculimits" runSleepingContainer(c, "-d", "--ulimit", "nofile=511:511", "--name", name) - assert.NilError(c, waitRun(name)) + cli.WaitRun(c, name) out, _, err := dockerCmdWithError("exec", name, "sh", "-c", "ulimit -n") assert.NilError(c, err) @@ -511,9 +507,9 @@ func (s *DockerCLIExecSuite) TestExecUlimits(c *testing.T) { // #15750 func (s *DockerCLIExecSuite) TestExecStartFails(c *testing.T) { - name := "exec-15750" + const name = "exec-15750" runSleepingContainer(c, "-d", "--name", name) - assert.NilError(c, waitRun(name)) + cli.WaitRun(c, name) out, _, err := dockerCmdWithError("exec", name, "no-such-cmd") assert.ErrorContains(c, err, "", out) @@ -528,10 +524,10 @@ func (s *DockerCLIExecSuite) TestExecStartFails(c *testing.T) { // Fix regression in https://github.com/docker/docker/pull/26461#issuecomment-250287297 func (s *DockerCLIExecSuite) TestExecWindowsPathNotWiped(c *testing.T) { testRequires(c, DaemonIsWindows) - out, _ := dockerCmd(c, "run", "-d", "--name", "testing", minimalBaseImage(), "powershell", "start-sleep", "60") - assert.NilError(c, waitRun(strings.TrimSpace(out))) + out := cli.DockerCmd(c, "run", "-d", "--name", "testing", minimalBaseImage(), "powershell", "start-sleep", "60").Stdout() + cli.WaitRun(c, strings.TrimSpace(out)) - out, _ = dockerCmd(c, "exec", "testing", "powershell", "write-host", "$env:PATH") + out = cli.DockerCmd(c, "exec", "testing", "powershell", "write-host", "$env:PATH").Stdout() out = strings.ToLower(strings.Trim(out, "\r\n")) assert.Assert(c, strings.Contains(out, `windowspowershell\v1.0`)) } @@ -540,7 +536,7 @@ func (s *DockerCLIExecSuite) TestExecEnvLinksHost(c *testing.T) { testRequires(c, DaemonIsLinux) runSleepingContainer(c, "-d", "--name", "foo") runSleepingContainer(c, "-d", "--link", "foo:db", "--hostname", "myhost", "--name", "bar") - out, _ := dockerCmd(c, "exec", "bar", "env") + out := cli.DockerCmd(c, "exec", "bar", "env").Stdout() assert.Check(c, is.Contains(out, "HOSTNAME=myhost")) assert.Check(c, is.Contains(out, "DB_NAME=/bar/db")) } diff --git a/integration-cli/docker_cli_exec_unix_test.go b/integration-cli/docker_cli_exec_unix_test.go index d0682cca34..c91ef36544 100644 --- a/integration-cli/docker_cli_exec_unix_test.go +++ b/integration-cli/docker_cli_exec_unix_test.go @@ -11,13 +11,14 @@ import ( "time" "github.com/creack/pty" + "github.com/docker/docker/integration-cli/cli" "gotest.tools/v3/assert" ) // regression test for #12546 func (s *DockerCLIExecSuite) TestExecInteractiveStdinClose(c *testing.T) { testRequires(c, DaemonIsLinux) - out, _ := dockerCmd(c, "run", "-itd", "busybox", "/bin/cat") + out := cli.DockerCmd(c, "run", "-itd", "busybox", "/bin/cat").Stdout() contID := strings.TrimSpace(out) cmd := exec.Command(dockerBinary, "exec", "-i", contID, "echo", "-n", "hello") @@ -46,7 +47,7 @@ func (s *DockerCLIExecSuite) TestExecInteractiveStdinClose(c *testing.T) { func (s *DockerCLIExecSuite) TestExecTTY(c *testing.T) { testRequires(c, DaemonIsLinux, testEnv.IsLocalDaemon) - dockerCmd(c, "run", "-d", "--name=test", "busybox", "sh", "-c", "echo hello > /foo && top") + cli.DockerCmd(c, "run", "-d", "--name=test", "busybox", "sh", "-c", "echo hello > /foo && top") cmd := exec.Command(dockerBinary, "exec", "-it", "test", "sh") p, err := pty.Start(cmd) @@ -76,7 +77,7 @@ func (s *DockerCLIExecSuite) TestExecTTY(c *testing.T) { // Test the TERM env var is set when -t is provided on exec func (s *DockerCLIExecSuite) TestExecWithTERM(c *testing.T) { testRequires(c, DaemonIsLinux, testEnv.IsLocalDaemon) - out, _ := dockerCmd(c, "run", "-id", "busybox", "/bin/cat") + out := cli.DockerCmd(c, "run", "-id", "busybox", "/bin/cat").Stdout() contID := strings.TrimSpace(out) cmd := exec.Command(dockerBinary, "exec", "-t", contID, "sh", "-c", "if [ -z $TERM ]; then exit 1; else exit 0; fi") if err := cmd.Run(); err != nil { @@ -88,7 +89,7 @@ func (s *DockerCLIExecSuite) TestExecWithTERM(c *testing.T) { // on run func (s *DockerCLIExecSuite) TestExecWithNoTERM(c *testing.T) { testRequires(c, DaemonIsLinux, testEnv.IsLocalDaemon) - out, _ := dockerCmd(c, "run", "-itd", "busybox", "/bin/cat") + out := cli.DockerCmd(c, "run", "-itd", "busybox", "/bin/cat").Stdout() contID := strings.TrimSpace(out) cmd := exec.Command(dockerBinary, "exec", contID, "sh", "-c", "if [ -z $TERM ]; then exit 0; else exit 1; fi") if err := cmd.Run(); err != nil { diff --git a/integration-cli/docker_cli_external_volume_driver_test.go b/integration-cli/docker_cli_external_volume_driver_test.go index a20c03920f..49575ec9d5 100644 --- a/integration-cli/docker_cli_external_volume_driver_test.go +++ b/integration-cli/docker_cli_external_volume_driver_test.go @@ -16,6 +16,7 @@ import ( "github.com/docker/docker/api/types" volumetypes "github.com/docker/docker/api/types/volume" + "github.com/docker/docker/integration-cli/cli" "github.com/docker/docker/integration-cli/daemon" "github.com/docker/docker/pkg/plugins" "github.com/docker/docker/pkg/stringid" @@ -277,13 +278,13 @@ func (s *DockerExternalVolumeSuite) TearDownSuite(ctx context.Context, c *testin } func (s *DockerExternalVolumeSuite) TestVolumeCLICreateOptionConflict(c *testing.T) { - dockerCmd(c, "volume", "create", "test") + cli.DockerCmd(c, "volume", "create", "test") out, _, err := dockerCmdWithError("volume", "create", "test", "--driver", volumePluginName) assert.Assert(c, err != nil, "volume create exception name already in use with another driver") assert.Assert(c, strings.Contains(out, "must be unique")) - out, _ = dockerCmd(c, "volume", "inspect", "--format={{ .Driver }}", "test") - _, _, err = dockerCmdWithError("volume", "create", "test", "--driver", strings.TrimSpace(out)) + driver := cli.DockerCmd(c, "volume", "inspect", "--format={{ .Driver }}", "test").Stdout() + _, _, err = dockerCmdWithError("volume", "create", "test", "--driver", strings.TrimSpace(driver)) assert.NilError(c, err) } @@ -440,8 +441,8 @@ func (s *DockerExternalVolumeSuite) TestExternalVolumeDriverRetryNotImmediatelyE } func (s *DockerExternalVolumeSuite) TestExternalVolumeDriverBindExternalVolume(c *testing.T) { - dockerCmd(c, "volume", "create", "-d", volumePluginName, "foo") - dockerCmd(c, "run", "-d", "--name", "testing", "-v", "foo:/bar", "busybox", "top") + cli.DockerCmd(c, "volume", "create", "-d", volumePluginName, "foo") + cli.DockerCmd(c, "run", "-d", "--name", "testing", "-v", "foo:/bar", "busybox", "top") var mounts []struct { Name string @@ -455,8 +456,8 @@ func (s *DockerExternalVolumeSuite) TestExternalVolumeDriverBindExternalVolume(c } func (s *DockerExternalVolumeSuite) TestExternalVolumeDriverList(c *testing.T) { - dockerCmd(c, "volume", "create", "-d", volumePluginName, "abc3") - out, _ := dockerCmd(c, "volume", "ls") + cli.DockerCmd(c, "volume", "create", "-d", volumePluginName, "abc3") + out := cli.DockerCmd(c, "volume", "ls").Stdout() ls := strings.Split(strings.TrimSpace(out), "\n") assert.Equal(c, len(ls), 2, fmt.Sprintf("\n%s", out)) @@ -474,8 +475,8 @@ func (s *DockerExternalVolumeSuite) TestExternalVolumeDriverGet(c *testing.T) { assert.Assert(c, strings.Contains(out, "No such volume")) assert.Equal(c, s.ec.gets, 1) - dockerCmd(c, "volume", "create", "test", "-d", volumePluginName) - out, _ = dockerCmd(c, "volume", "inspect", "test") + cli.DockerCmd(c, "volume", "create", "test", "-d", volumePluginName) + out = cli.DockerCmd(c, "volume", "inspect", "test").Stdout() type vol struct { Status map[string]string @@ -489,10 +490,10 @@ func (s *DockerExternalVolumeSuite) TestExternalVolumeDriverGet(c *testing.T) { } func (s *DockerExternalVolumeSuite) TestExternalVolumeDriverWithDaemonRestart(c *testing.T) { - dockerCmd(c, "volume", "create", "-d", volumePluginName, "abc1") + cli.DockerCmd(c, "volume", "create", "-d", volumePluginName, "abc1") s.d.Restart(c) - dockerCmd(c, "run", "--name=test", "-v", "abc1:/foo", "busybox", "true") + cli.DockerCmd(c, "run", "--name=test", "-v", "abc1:/foo", "busybox", "true") var mounts []types.MountPoint inspectFieldAndUnmarshall(c, "test", "Mounts", &mounts) assert.Equal(c, len(mounts), 1) diff --git a/integration-cli/docker_cli_health_test.go b/integration-cli/docker_cli_health_test.go index e7818df2b6..cfc9aff83e 100644 --- a/integration-cli/docker_cli_health_test.go +++ b/integration-cli/docker_cli_health_test.go @@ -9,6 +9,7 @@ import ( "time" "github.com/docker/docker/api/types" + "github.com/docker/docker/integration-cli/cli" "github.com/docker/docker/integration-cli/cli/build" "gotest.tools/v3/assert" ) @@ -29,7 +30,7 @@ func waitForHealthStatus(c *testing.T, name string, prev string, expected string prev = prev + "\n" expected = expected + "\n" for { - out, _ := dockerCmd(c, "inspect", "--format={{.State.Health.Status}}", name) + out := cli.DockerCmd(c, "inspect", "--format={{.State.Health.Status}}", name).Stdout() if out == expected { return } @@ -42,7 +43,7 @@ func waitForHealthStatus(c *testing.T, name string, prev string, expected string } func getHealth(c *testing.T, name string) *types.Health { - out, _ := dockerCmd(c, "inspect", "--format={{json .State.Health}}", name) + out := cli.DockerCmd(c, "inspect", "--format={{json .State.Health}}", name).Stdout() var health types.Health err := json.Unmarshal([]byte(out), &health) assert.Equal(c, err, nil) @@ -64,54 +65,54 @@ func (s *DockerCLIHealthSuite) TestHealth(c *testing.T) { // No health status before starting name := "test_health" - cid, _ := dockerCmd(c, "create", "--name", name, imageName) - out, _ := dockerCmd(c, "ps", "-a", "--format={{.ID}} {{.Status}}") + cid := cli.DockerCmd(c, "create", "--name", name, imageName).Stdout() + out := cli.DockerCmd(c, "ps", "-a", "--format={{.ID}} {{.Status}}").Stdout() out = RemoveOutputForExistingElements(out, existingContainers) assert.Equal(c, out, cid[:12]+" Created\n") // Inspect the options - out, _ = dockerCmd(c, "inspect", - "--format=timeout={{.Config.Healthcheck.Timeout}} interval={{.Config.Healthcheck.Interval}} retries={{.Config.Healthcheck.Retries}} test={{.Config.Healthcheck.Test}}", name) + out = cli.DockerCmd(c, "inspect", "--format=timeout={{.Config.Healthcheck.Timeout}} interval={{.Config.Healthcheck.Interval}} retries={{.Config.Healthcheck.Retries}} test={{.Config.Healthcheck.Test}}", name).Stdout() assert.Equal(c, out, "timeout=30s interval=1s retries=0 test=[CMD-SHELL cat /status]\n") // Start - dockerCmd(c, "start", name) + cli.DockerCmd(c, "start", name) waitForHealthStatus(c, name, "starting", "healthy") // Make it fail - dockerCmd(c, "exec", name, "rm", "/status") + cli.DockerCmd(c, "exec", name, "rm", "/status") waitForHealthStatus(c, name, "healthy", "unhealthy") // Inspect the status - out, _ = dockerCmd(c, "inspect", "--format={{.State.Health.Status}}", name) + out = cli.DockerCmd(c, "inspect", "--format={{.State.Health.Status}}", name).Stdout() assert.Equal(c, out, "unhealthy\n") // Make it healthy again - dockerCmd(c, "exec", name, "touch", "/status") + cli.DockerCmd(c, "exec", name, "touch", "/status") waitForHealthStatus(c, name, "unhealthy", "healthy") // Remove container - dockerCmd(c, "rm", "-f", name) + cli.DockerCmd(c, "rm", "-f", name) // Disable the check from the CLI - dockerCmd(c, "create", "--name=noh", "--no-healthcheck", imageName) - out, _ = dockerCmd(c, "inspect", "--format={{.Config.Healthcheck.Test}}", "noh") + cli.DockerCmd(c, "create", "--name=noh", "--no-healthcheck", imageName) + out = cli.DockerCmd(c, "inspect", "--format={{.Config.Healthcheck.Test}}", "noh").Stdout() assert.Equal(c, out, "[NONE]\n") - dockerCmd(c, "rm", "noh") + cli.DockerCmd(c, "rm", "noh") // Disable the check with a new build buildImageSuccessfully(c, "no_healthcheck", build.WithDockerfile(`FROM testhealth HEALTHCHECK NONE`)) - out, _ = dockerCmd(c, "inspect", "--format={{.Config.Healthcheck.Test}}", "no_healthcheck") + out = cli.DockerCmd(c, "inspect", "--format={{.Config.Healthcheck.Test}}", "no_healthcheck").Stdout() assert.Equal(c, out, "[NONE]\n") // Enable the checks from the CLI - _, _ = dockerCmd(c, "run", "-d", "--name=fatal_healthcheck", + cli.DockerCmd(c, "run", "-d", "--name=fatal_healthcheck", "--health-interval=1s", "--health-retries=3", "--health-cmd=cat /status", - "no_healthcheck") + "no_healthcheck", + ) waitForHealthStatus(c, "fatal_healthcheck", "starting", "healthy") health := getHealth(c, "fatal_healthcheck") assert.Equal(c, health.Status, "healthy") @@ -121,27 +122,26 @@ func (s *DockerCLIHealthSuite) TestHealth(c *testing.T) { assert.Equal(c, last.Output, "OK\n") // Fail the check - dockerCmd(c, "exec", "fatal_healthcheck", "rm", "/status") + cli.DockerCmd(c, "exec", "fatal_healthcheck", "rm", "/status") waitForHealthStatus(c, "fatal_healthcheck", "healthy", "unhealthy") - failsStr, _ := dockerCmd(c, "inspect", "--format={{.State.Health.FailingStreak}}", "fatal_healthcheck") + failsStr := cli.DockerCmd(c, "inspect", "--format={{.State.Health.FailingStreak}}", "fatal_healthcheck").Combined() fails, err := strconv.Atoi(strings.TrimSpace(failsStr)) - assert.Assert(c, err == nil) + assert.Check(c, err) assert.Equal(c, fails >= 3, true) - dockerCmd(c, "rm", "-f", "fatal_healthcheck") + cli.DockerCmd(c, "rm", "-f", "fatal_healthcheck") // Check timeout // Note: if the interval is too small, it seems that Docker spends all its time running health // checks and never gets around to killing it. - _, _ = dockerCmd(c, "run", "-d", "--name=test", - "--health-interval=1s", "--health-cmd=sleep 5m", "--health-timeout=1s", imageName) + cli.DockerCmd(c, "run", "-d", "--name=test", "--health-interval=1s", "--health-cmd=sleep 5m", "--health-timeout=1s", imageName) waitForHealthStatus(c, "test", "starting", "unhealthy") health = getHealth(c, "test") last = health.Log[len(health.Log)-1] assert.Equal(c, health.Status, "unhealthy") assert.Equal(c, last.ExitCode, -1) assert.Equal(c, last.Output, "Health check exceeded timeout (1s)") - dockerCmd(c, "rm", "-f", "test") + cli.DockerCmd(c, "rm", "-f", "test") // Check JSON-format buildImageSuccessfully(c, imageName, build.WithDockerfile(`FROM busybox @@ -150,8 +150,7 @@ func (s *DockerCLIHealthSuite) TestHealth(c *testing.T) { STOPSIGNAL SIGKILL HEALTHCHECK --interval=1s --timeout=30s \ CMD ["cat", "/my status"]`)) - out, _ = dockerCmd(c, "inspect", - "--format={{.Config.Healthcheck.Test}}", imageName) + out = cli.DockerCmd(c, "inspect", "--format={{.Config.Healthcheck.Test}}", imageName).Stdout() assert.Equal(c, out, "[CMD cat /my status]\n") } @@ -166,13 +165,13 @@ ENTRYPOINT /bin/sh -c "sleep 600"`)) name := "env_test_health" // No health status before starting - dockerCmd(c, "run", "-d", "--name", name, "-e", "FOO", imageName) + cli.DockerCmd(c, "run", "-d", "--name", name, "-e", "FOO", imageName) defer func() { - dockerCmd(c, "rm", "-f", name) - dockerCmd(c, "rmi", imageName) + cli.DockerCmd(c, "rm", "-f", name) + cli.DockerCmd(c, "rmi", imageName) }() // Start - dockerCmd(c, "start", name) + cli.DockerCmd(c, "start", name) waitForHealthStatus(c, name, "starting", "healthy") } diff --git a/integration-cli/docker_cli_history_test.go b/integration-cli/docker_cli_history_test.go index ef6e7439f4..400dcfb6d9 100644 --- a/integration-cli/docker_cli_history_test.go +++ b/integration-cli/docker_cli_history_test.go @@ -8,6 +8,7 @@ import ( "strings" "testing" + "github.com/docker/docker/integration-cli/cli" "github.com/docker/docker/integration-cli/cli/build" "gotest.tools/v3/assert" "gotest.tools/v3/assert/cmp" @@ -28,7 +29,7 @@ func (s *DockerCLIHistorySuite) OnTimeout(c *testing.T) { // This is a heisen-test. Because the created timestamp of images and the behavior of // sort is not predictable it doesn't always fail. func (s *DockerCLIHistorySuite) TestBuildHistory(c *testing.T) { - name := "testbuildhistory" + const name = "testbuildhistory" buildImageSuccessfully(c, name, build.WithDockerfile(`FROM `+minimalBaseImage()+` LABEL label.A="A" LABEL label.B="B" @@ -57,7 +58,7 @@ LABEL label.X="X" LABEL label.Y="Y" LABEL label.Z="Z"`)) - out, _ := dockerCmd(c, "history", name) + out := cli.DockerCmd(c, "history", name).Combined() actualValues := strings.Split(out, "\n")[1:27] expectedValues := [26]string{"Z", "Y", "X", "W", "V", "U", "T", "S", "R", "Q", "P", "O", "N", "M", "L", "K", "J", "I", "H", "G", "F", "E", "D", "C", "B", "A"} @@ -69,7 +70,7 @@ LABEL label.Z="Z"`)) } func (s *DockerCLIHistorySuite) TestHistoryExistentImage(c *testing.T) { - dockerCmd(c, "history", "busybox") + cli.DockerCmd(c, "history", "busybox") } func (s *DockerCLIHistorySuite) TestHistoryNonExistentImage(c *testing.T) { @@ -78,26 +79,24 @@ func (s *DockerCLIHistorySuite) TestHistoryNonExistentImage(c *testing.T) { } func (s *DockerCLIHistorySuite) TestHistoryImageWithComment(c *testing.T) { - name := "testhistoryimagewithcomment" + const name = "testhistoryimagewithcomment" // make an image through docker commit [ -m messages ] + cli.DockerCmd(c, "run", "--name", name, "busybox", "true") + cli.DockerCmd(c, "wait", name) - dockerCmd(c, "run", "--name", name, "busybox", "true") - dockerCmd(c, "wait", name) - - comment := "This_is_a_comment" - dockerCmd(c, "commit", "-m="+comment, name, name) + const comment = "This_is_a_comment" + cli.DockerCmd(c, "commit", "-m="+comment, name, name) // test docker history to check comment messages - - out, _ := dockerCmd(c, "history", name) + out := cli.DockerCmd(c, "history", name).Combined() outputTabs := strings.Fields(strings.Split(out, "\n")[1]) actualValue := outputTabs[len(outputTabs)-1] assert.Assert(c, strings.Contains(actualValue, comment)) } func (s *DockerCLIHistorySuite) TestHistoryHumanOptionFalse(c *testing.T) { - out, _ := dockerCmd(c, "history", "--human=false", "busybox") + out := cli.DockerCmd(c, "history", "--human=false", "busybox").Combined() lines := strings.Split(out, "\n") sizeColumnRegex, _ := regexp.Compile("SIZE +") indices := sizeColumnRegex.FindStringIndex(lines[0]) @@ -115,7 +114,7 @@ func (s *DockerCLIHistorySuite) TestHistoryHumanOptionFalse(c *testing.T) { } func (s *DockerCLIHistorySuite) TestHistoryHumanOptionTrue(c *testing.T) { - out, _ := dockerCmd(c, "history", "--human=true", "busybox") + out := cli.DockerCmd(c, "history", "--human=true", "busybox").Combined() lines := strings.Split(out, "\n") sizeColumnRegex, _ := regexp.Compile("SIZE +") humanSizeRegexRaw := "\\d+.*B" // Matches human sizes like 10 MB, 3.2 KB, etc diff --git a/integration-cli/docker_cli_images_test.go b/integration-cli/docker_cli_images_test.go index 29e20a3e61..737b58e3e7 100644 --- a/integration-cli/docker_cli_images_test.go +++ b/integration-cli/docker_cli_images_test.go @@ -11,6 +11,7 @@ import ( "testing" "time" + "github.com/docker/docker/integration-cli/cli" "github.com/docker/docker/integration-cli/cli/build" "github.com/docker/docker/pkg/stringid" "gotest.tools/v3/assert" @@ -31,22 +32,22 @@ func (s *DockerCLIImagesSuite) OnTimeout(c *testing.T) { } func (s *DockerCLIImagesSuite) TestImagesEnsureImageIsListed(c *testing.T) { - imagesOut, _ := dockerCmd(c, "images") + imagesOut := cli.DockerCmd(c, "images").Stdout() assert.Assert(c, strings.Contains(imagesOut, "busybox")) } func (s *DockerCLIImagesSuite) TestImagesEnsureImageWithTagIsListed(c *testing.T) { - name := "imagewithtag" - dockerCmd(c, "tag", "busybox", name+":v1") - dockerCmd(c, "tag", "busybox", name+":v1v1") - dockerCmd(c, "tag", "busybox", name+":v2") + const name = "imagewithtag" + cli.DockerCmd(c, "tag", "busybox", name+":v1") + cli.DockerCmd(c, "tag", "busybox", name+":v1v1") + cli.DockerCmd(c, "tag", "busybox", name+":v2") - imagesOut, _ := dockerCmd(c, "images", name+":v1") + imagesOut := cli.DockerCmd(c, "images", name+":v1").Stdout() assert.Assert(c, strings.Contains(imagesOut, name)) assert.Assert(c, strings.Contains(imagesOut, "v1")) assert.Assert(c, !strings.Contains(imagesOut, "v2")) assert.Assert(c, !strings.Contains(imagesOut, "v1v1")) - imagesOut, _ = dockerCmd(c, "images", name) + imagesOut = cli.DockerCmd(c, "images", name).Stdout() assert.Assert(c, strings.Contains(imagesOut, name)) assert.Assert(c, strings.Contains(imagesOut, "v1")) assert.Assert(c, strings.Contains(imagesOut, "v1v1")) @@ -54,7 +55,7 @@ func (s *DockerCLIImagesSuite) TestImagesEnsureImageWithTagIsListed(c *testing.T } func (s *DockerCLIImagesSuite) TestImagesEnsureImageWithBadTagIsNotListed(c *testing.T) { - imagesOut, _ := dockerCmd(c, "images", "busybox:nonexistent") + imagesOut := cli.DockerCmd(c, "images", "busybox:nonexistent").Stdout() assert.Assert(c, !strings.Contains(imagesOut, "busybox")) } @@ -71,7 +72,7 @@ func (s *DockerCLIImagesSuite) TestImagesOrderedByCreationDate(c *testing.T) { MAINTAINER dockerio3`)) id3 := getIDByName(c, "order:test_b") - out, _ := dockerCmd(c, "images", "-q", "--no-trunc") + out := cli.DockerCmd(c, "images", "-q", "--no-trunc").Stdout() imgs := strings.Split(out, "\n") assert.Equal(c, imgs[0], id3, fmt.Sprintf("First image must be %s, got %s", id3, imgs[0])) assert.Equal(c, imgs[1], id2, fmt.Sprintf("First image must be %s, got %s", id2, imgs[1])) @@ -85,9 +86,9 @@ func (s *DockerCLIImagesSuite) TestImagesErrorWithInvalidFilterNameTest(c *testi } func (s *DockerCLIImagesSuite) TestImagesFilterLabelMatch(c *testing.T) { - imageName1 := "images_filter_test1" - imageName2 := "images_filter_test2" - imageName3 := "images_filter_test3" + const imageName1 = "images_filter_test1" + const imageName2 = "images_filter_test2" + const imageName3 = "images_filter_test3" buildImageSuccessfully(c, imageName1, build.WithDockerfile(`FROM busybox LABEL match me`)) image1ID := getIDByName(c, imageName1) @@ -100,7 +101,7 @@ func (s *DockerCLIImagesSuite) TestImagesFilterLabelMatch(c *testing.T) { LABEL nomatch me`)) image3ID := getIDByName(c, imageName3) - out, _ := dockerCmd(c, "images", "--no-trunc", "-q", "-f", "label=match") + out := cli.DockerCmd(c, "images", "--no-trunc", "-q", "-f", "label=match").Stdout() out = strings.TrimSpace(out) assert.Assert(c, is.Regexp(fmt.Sprintf("^[\\s\\w:]*%s[\\s\\w:]*$", image1ID), out)) @@ -108,7 +109,7 @@ func (s *DockerCLIImagesSuite) TestImagesFilterLabelMatch(c *testing.T) { assert.Assert(c, !is.Regexp(fmt.Sprintf("^[\\s\\w:]*%s[\\s\\w:]*$", image3ID), out)().Success()) - out, _ = dockerCmd(c, "images", "--no-trunc", "-q", "-f", "label=match=me too") + out = cli.DockerCmd(c, "images", "--no-trunc", "-q", "-f", "label=match=me too").Stdout() out = strings.TrimSpace(out) assert.Equal(c, out, image2ID) } @@ -116,12 +117,12 @@ func (s *DockerCLIImagesSuite) TestImagesFilterLabelMatch(c *testing.T) { // Regression : #15659 func (s *DockerCLIImagesSuite) TestCommitWithFilterLabel(c *testing.T) { // Create a container - dockerCmd(c, "run", "--name", "bar", "busybox", "/bin/sh") + cli.DockerCmd(c, "run", "--name", "bar", "busybox", "/bin/sh") // Commit with labels "using changes" - out, _ := dockerCmd(c, "commit", "-c", "LABEL foo.version=1.0.0-1", "-c", "LABEL foo.name=bar", "-c", "LABEL foo.author=starlord", "bar", "bar:1.0.0-1") - imageID := strings.TrimSpace(out) + imageID := cli.DockerCmd(c, "commit", "-c", "LABEL foo.version=1.0.0-1", "-c", "LABEL foo.name=bar", "-c", "LABEL foo.author=starlord", "bar", "bar:1.0.0-1").Stdout() + imageID = strings.TrimSpace(imageID) - out, _ = dockerCmd(c, "images", "--no-trunc", "-q", "-f", "label=foo.version=1.0.0-1") + out := cli.DockerCmd(c, "images", "--no-trunc", "-q", "-f", "label=foo.version=1.0.0-1").Stdout() out = strings.TrimSpace(out) assert.Equal(c, out, imageID) } @@ -139,34 +140,34 @@ LABEL number=3`)) expected := []string{imageID3, imageID2} - out, _ := dockerCmd(c, "images", "-f", "since=image:1", "image") + out := cli.DockerCmd(c, "images", "-f", "since=image:1", "image").Stdout() assert.Equal(c, assertImageList(out, expected), true, fmt.Sprintf("SINCE filter: Image list is not in the correct order: %v\n%s", expected, out)) - out, _ = dockerCmd(c, "images", "-f", "since="+imageID1, "image") + out = cli.DockerCmd(c, "images", "-f", "since="+imageID1, "image").Stdout() assert.Equal(c, assertImageList(out, expected), true, fmt.Sprintf("SINCE filter: Image list is not in the correct order: %v\n%s", expected, out)) expected = []string{imageID3} - out, _ = dockerCmd(c, "images", "-f", "since=image:2", "image") + out = cli.DockerCmd(c, "images", "-f", "since=image:2", "image").Stdout() assert.Equal(c, assertImageList(out, expected), true, fmt.Sprintf("SINCE filter: Image list is not in the correct order: %v\n%s", expected, out)) - out, _ = dockerCmd(c, "images", "-f", "since="+imageID2, "image") + out = cli.DockerCmd(c, "images", "-f", "since="+imageID2, "image").Stdout() assert.Equal(c, assertImageList(out, expected), true, fmt.Sprintf("SINCE filter: Image list is not in the correct order: %v\n%s", expected, out)) expected = []string{imageID2, imageID1} - out, _ = dockerCmd(c, "images", "-f", "before=image:3", "image") + out = cli.DockerCmd(c, "images", "-f", "before=image:3", "image").Stdout() assert.Equal(c, assertImageList(out, expected), true, fmt.Sprintf("BEFORE filter: Image list is not in the correct order: %v\n%s", expected, out)) - out, _ = dockerCmd(c, "images", "-f", "before="+imageID3, "image") + out = cli.DockerCmd(c, "images", "-f", "before="+imageID3, "image").Stdout() assert.Equal(c, assertImageList(out, expected), true, fmt.Sprintf("BEFORE filter: Image list is not in the correct order: %v\n%s", expected, out)) expected = []string{imageID1} - out, _ = dockerCmd(c, "images", "-f", "before=image:2", "image") + out = cli.DockerCmd(c, "images", "-f", "before=image:2", "image").Stdout() assert.Equal(c, assertImageList(out, expected), true, fmt.Sprintf("BEFORE filter: Image list is not in the correct order: %v\n%s", expected, out)) - out, _ = dockerCmd(c, "images", "-f", "before="+imageID2, "image") + out = cli.DockerCmd(c, "images", "-f", "before="+imageID2, "image").Stdout() assert.Equal(c, assertImageList(out, expected), true, fmt.Sprintf("BEFORE filter: Image list is not in the correct order: %v\n%s", expected, out)) } @@ -197,7 +198,7 @@ func assertImageList(out string, expected []string) bool { // FIXME(vdemeester) should be a unit test on `docker image ls` func (s *DockerCLIImagesSuite) TestImagesFilterSpaceTrimCase(c *testing.T) { - imageName := "images_filter_test" + const imageName = "images_filter_test" // Build a image and fail to build so that we have dangling images ? buildImage(imageName, build.WithDockerfile(`FROM busybox RUN touch /test/foo @@ -216,7 +217,7 @@ func (s *DockerCLIImagesSuite) TestImagesFilterSpaceTrimCase(c *testing.T) { imageListings := make([][]string, 5) for idx, filter := range filters { - out, _ := dockerCmd(c, "images", "-q", "-f", filter) + out := cli.DockerCmd(c, "images", "-q", "-f", filter).Stdout() listing := strings.Split(out, "\n") sort.Strings(listing) imageListings[idx] = listing @@ -239,24 +240,24 @@ func (s *DockerCLIImagesSuite) TestImagesFilterSpaceTrimCase(c *testing.T) { func (s *DockerCLIImagesSuite) TestImagesEnsureDanglingImageOnlyListedOnce(c *testing.T) { testRequires(c, DaemonIsLinux) // create container 1 - out, _ := dockerCmd(c, "run", "-d", "busybox", "true") - containerID1 := strings.TrimSpace(out) + containerID1 := cli.DockerCmd(c, "run", "-d", "busybox", "true").Stdout() + containerID1 = strings.TrimSpace(containerID1) // tag as foobox - out, _ = dockerCmd(c, "commit", containerID1, "foobox") - imageID := stringid.TruncateID(strings.TrimSpace(out)) + imageID := cli.DockerCmd(c, "commit", containerID1, "foobox").Stdout() + imageID = stringid.TruncateID(strings.TrimSpace(imageID)) // overwrite the tag, making the previous image dangling - dockerCmd(c, "tag", "busybox", "foobox") + cli.DockerCmd(c, "tag", "busybox", "foobox") - out, _ = dockerCmd(c, "images", "-q", "-f", "dangling=true") + out := cli.DockerCmd(c, "images", "-q", "-f", "dangling=true").Stdout() // Expect one dangling image assert.Equal(c, strings.Count(out, imageID), 1) - out, _ = dockerCmd(c, "images", "-q", "-f", "dangling=false") + out = cli.DockerCmd(c, "images", "-q", "-f", "dangling=false").Stdout() // dangling=false would not include dangling images assert.Assert(c, !strings.Contains(out, imageID)) - out, _ = dockerCmd(c, "images") + out = cli.DockerCmd(c, "images").Stdout() // docker images still include dangling images assert.Assert(c, strings.Contains(out, imageID)) } @@ -269,11 +270,11 @@ func (s *DockerCLIImagesSuite) TestImagesWithIncorrectFilter(c *testing.T) { } func (s *DockerCLIImagesSuite) TestImagesEnsureOnlyHeadsImagesShown(c *testing.T) { - dockerfile := ` + const dockerfile = ` FROM busybox MAINTAINER docker ENV foo bar` - name := "scratch-image" + const name = "scratch-image" result := buildImage(name, build.WithDockerfile(dockerfile)) result.Assert(c, icmd.Success) id := getIDByName(c, name) @@ -284,7 +285,7 @@ func (s *DockerCLIImagesSuite) TestImagesEnsureOnlyHeadsImagesShown(c *testing.T split := strings.Split(result.Combined(), "\n") intermediate := strings.TrimSpace(split[5][7:]) - out, _ := dockerCmd(c, "images") + out := cli.DockerCmd(c, "images").Stdout() // images shouldn't show non-heads images assert.Assert(c, !strings.Contains(out, intermediate)) // images should contain final built images @@ -293,15 +294,15 @@ func (s *DockerCLIImagesSuite) TestImagesEnsureOnlyHeadsImagesShown(c *testing.T func (s *DockerCLIImagesSuite) TestImagesEnsureImagesFromScratchShown(c *testing.T) { testRequires(c, DaemonIsLinux) // Windows does not support FROM scratch - dockerfile := ` + const dockerfile = ` FROM scratch MAINTAINER docker` - name := "scratch-image" + const name = "scratch-image" buildImageSuccessfully(c, name, build.WithDockerfile(dockerfile)) id := getIDByName(c, name) - out, _ := dockerCmd(c, "images") + out := cli.DockerCmd(c, "images").Stdout() // images should contain images built from scratch assert.Assert(c, strings.Contains(out, stringid.TruncateID(id))) } @@ -309,41 +310,41 @@ func (s *DockerCLIImagesSuite) TestImagesEnsureImagesFromScratchShown(c *testing // For W2W - equivalent to TestImagesEnsureImagesFromScratchShown but Windows // doesn't support from scratch func (s *DockerCLIImagesSuite) TestImagesEnsureImagesFromBusyboxShown(c *testing.T) { - dockerfile := ` + const dockerfile = ` FROM busybox MAINTAINER docker` - name := "busybox-image" + const name = "busybox-image" buildImageSuccessfully(c, name, build.WithDockerfile(dockerfile)) id := getIDByName(c, name) - out, _ := dockerCmd(c, "images") + out := cli.DockerCmd(c, "images").Stdout() // images should contain images built from busybox assert.Assert(c, strings.Contains(out, stringid.TruncateID(id))) } // #18181 func (s *DockerCLIImagesSuite) TestImagesFilterNameWithPort(c *testing.T) { - tag := "a.b.c.d:5000/hello" - dockerCmd(c, "tag", "busybox", tag) - out, _ := dockerCmd(c, "images", tag) + const tag = "a.b.c.d:5000/hello" + cli.DockerCmd(c, "tag", "busybox", tag) + out := cli.DockerCmd(c, "images", tag).Stdout() assert.Assert(c, strings.Contains(out, tag)) - out, _ = dockerCmd(c, "images", tag+":latest") + out = cli.DockerCmd(c, "images", tag+":latest").Stdout() assert.Assert(c, strings.Contains(out, tag)) - out, _ = dockerCmd(c, "images", tag+":no-such-tag") + out = cli.DockerCmd(c, "images", tag+":no-such-tag").Stdout() assert.Assert(c, !strings.Contains(out, tag)) } func (s *DockerCLIImagesSuite) TestImagesFormat(c *testing.T) { // testRequires(c, DaemonIsLinux) - tag := "myimage" - dockerCmd(c, "tag", "busybox", tag+":v1") - dockerCmd(c, "tag", "busybox", tag+":v2") + const imageName = "myimage" + cli.DockerCmd(c, "tag", "busybox", imageName+":v1") + cli.DockerCmd(c, "tag", "busybox", imageName+":v2") - out, _ := dockerCmd(c, "images", "--format", "{{.Repository}}", tag) + out := cli.DockerCmd(c, "images", "--format", "{{.Repository}}", imageName).Stdout() lines := strings.Split(strings.TrimSpace(out), "\n") - expected := []string{"myimage", "myimage"} + expected := []string{imageName, imageName} var names []string names = append(names, lines...) assert.Assert(c, is.DeepEqual(names, expected), "Expected array with truncated names: %v, got: %v", expected, names) @@ -354,14 +355,14 @@ func (s *DockerCLIImagesSuite) TestImagesFormatDefaultFormat(c *testing.T) { testRequires(c, DaemonIsLinux) // create container 1 - out, _ := dockerCmd(c, "run", "-d", "busybox", "true") - containerID1 := strings.TrimSpace(out) + containerID1 := cli.DockerCmd(c, "run", "-d", "busybox", "true").Stdout() + containerID1 = strings.TrimSpace(containerID1) // tag as foobox - out, _ = dockerCmd(c, "commit", containerID1, "myimage") - imageID := stringid.TruncateID(strings.TrimSpace(out)) + imageID := cli.DockerCmd(c, "commit", containerID1, "myimage").Stdout() + imageID = stringid.TruncateID(strings.TrimSpace(imageID)) - config := `{ + const config = `{ "imagesFormat": "{{ .ID }} default" }` d, err := os.MkdirTemp("", "integration-cli-") @@ -371,6 +372,6 @@ func (s *DockerCLIImagesSuite) TestImagesFormatDefaultFormat(c *testing.T) { err = os.WriteFile(filepath.Join(d, "config.json"), []byte(config), 0o644) assert.NilError(c, err) - out, _ = dockerCmd(c, "--config", d, "images", "-q", "myimage") + out := cli.DockerCmd(c, "--config", d, "images", "-q", "myimage").Stdout() assert.Equal(c, out, imageID+"\n", "Expected to print only the image id, got %v\n", out) } diff --git a/integration-cli/docker_cli_import_test.go b/integration-cli/docker_cli_import_test.go index 36b40cd3df..050dff7095 100644 --- a/integration-cli/docker_cli_import_test.go +++ b/integration-cli/docker_cli_import_test.go @@ -29,11 +29,11 @@ func (s *DockerCLIImportSuite) OnTimeout(c *testing.T) { func (s *DockerCLIImportSuite) TestImportDisplay(c *testing.T) { testRequires(c, DaemonIsLinux) - out, _ := dockerCmd(c, "run", "-d", "busybox", "true") - cleanedContainerID := strings.TrimSpace(out) + cID := cli.DockerCmd(c, "run", "-d", "busybox", "true").Stdout() + cID = strings.TrimSpace(cID) out, err := RunCommandPipelineWithOutput( - exec.Command(dockerBinary, "export", cleanedContainerID), + exec.Command(dockerBinary, "export", cID), exec.Command(dockerBinary, "import", "-"), ) assert.NilError(c, err) @@ -41,7 +41,7 @@ func (s *DockerCLIImportSuite) TestImportDisplay(c *testing.T) { assert.Assert(c, strings.Count(out, "\n") == 1, "display is expected 1 '\\n' but didn't") image := strings.TrimSpace(out) - out, _ = dockerCmd(c, "run", "--rm", image, "true") + out = cli.DockerCmd(c, "run", "--rm", image, "true").Combined() assert.Equal(c, out, "", "command output should've been nothing.") } @@ -58,7 +58,7 @@ func (s *DockerCLIImportSuite) TestImportBadURL(c *testing.T) { func (s *DockerCLIImportSuite) TestImportFile(c *testing.T) { testRequires(c, DaemonIsLinux) - dockerCmd(c, "run", "--name", "test-import", "busybox", "true") + cli.DockerCmd(c, "run", "--name", "test-import", "busybox", "true") temporaryFile, err := os.CreateTemp("", "exportImportTest") assert.Assert(c, err == nil, "failed to create temporary file") @@ -69,17 +69,17 @@ func (s *DockerCLIImportSuite) TestImportFile(c *testing.T) { Stdout: bufio.NewWriter(temporaryFile), }).Assert(c, icmd.Success) - out, _ := dockerCmd(c, "import", temporaryFile.Name()) + out := cli.DockerCmd(c, "import", temporaryFile.Name()).Combined() assert.Assert(c, strings.Count(out, "\n") == 1, "display is expected 1 '\\n' but didn't") image := strings.TrimSpace(out) - out, _ = dockerCmd(c, "run", "--rm", image, "true") + out = cli.DockerCmd(c, "run", "--rm", image, "true").Combined() assert.Equal(c, out, "", "command output should've been nothing.") } func (s *DockerCLIImportSuite) TestImportGzipped(c *testing.T) { testRequires(c, DaemonIsLinux) - dockerCmd(c, "run", "--name", "test-import", "busybox", "true") + cli.DockerCmd(c, "run", "--name", "test-import", "busybox", "true") temporaryFile, err := os.CreateTemp("", "exportImportTest") assert.Assert(c, err == nil, "failed to create temporary file") @@ -92,17 +92,17 @@ func (s *DockerCLIImportSuite) TestImportGzipped(c *testing.T) { }).Assert(c, icmd.Success) assert.Assert(c, w.Close() == nil, "failed to close gzip writer") temporaryFile.Close() - out, _ := dockerCmd(c, "import", temporaryFile.Name()) + out := cli.DockerCmd(c, "import", temporaryFile.Name()).Combined() assert.Assert(c, strings.Count(out, "\n") == 1, "display is expected 1 '\\n' but didn't") image := strings.TrimSpace(out) - out, _ = dockerCmd(c, "run", "--rm", image, "true") + out = cli.DockerCmd(c, "run", "--rm", image, "true").Combined() assert.Equal(c, out, "", "command output should've been nothing.") } func (s *DockerCLIImportSuite) TestImportFileWithMessage(c *testing.T) { testRequires(c, DaemonIsLinux) - dockerCmd(c, "run", "--name", "test-import", "busybox", "true") + cli.DockerCmd(c, "run", "--name", "test-import", "busybox", "true") temporaryFile, err := os.CreateTemp("", "exportImportTest") assert.Assert(c, err == nil, "failed to create temporary file") @@ -114,11 +114,11 @@ func (s *DockerCLIImportSuite) TestImportFileWithMessage(c *testing.T) { }).Assert(c, icmd.Success) message := "Testing commit message" - out, _ := dockerCmd(c, "import", "-m", message, temporaryFile.Name()) + out := cli.DockerCmd(c, "import", "-m", message, temporaryFile.Name()).Combined() assert.Assert(c, strings.Count(out, "\n") == 1, "display is expected 1 '\\n' but didn't") image := strings.TrimSpace(out) - out, _ = dockerCmd(c, "history", image) + out = cli.DockerCmd(c, "history", image).Combined() split := strings.Split(out, "\n") assert.Equal(c, len(split), 3, "expected 3 lines from image history") @@ -127,7 +127,7 @@ func (s *DockerCLIImportSuite) TestImportFileWithMessage(c *testing.T) { assert.Equal(c, message, split[3], "didn't get expected value in commit message") - out, _ = dockerCmd(c, "run", "--rm", image, "true") + out = cli.DockerCmd(c, "run", "--rm", image, "true").Combined() assert.Equal(c, out, "", "command output should've been nothing") } diff --git a/integration-cli/docker_cli_info_test.go b/integration-cli/docker_cli_info_test.go index 4c95d134ff..e22f2a2570 100644 --- a/integration-cli/docker_cli_info_test.go +++ b/integration-cli/docker_cli_info_test.go @@ -7,6 +7,7 @@ import ( "strings" "testing" + "github.com/docker/docker/integration-cli/cli" "gotest.tools/v3/assert" ) @@ -24,7 +25,7 @@ func (s *DockerCLIInfoSuite) OnTimeout(c *testing.T) { // ensure docker info succeeds func (s *DockerCLIInfoSuite) TestInfoEnsureSucceeds(c *testing.T) { - out, _ := dockerCmd(c, "info") + out := cli.DockerCmd(c, "info").Stdout() // always shown fields stringsToCheck := []string{ @@ -71,8 +72,8 @@ func (s *DockerCLIInfoSuite) TestInfoDisplaysRunningContainers(c *testing.T) { existing := existingContainerStates(c) - dockerCmd(c, "run", "-d", "busybox", "top") - out, _ := dockerCmd(c, "info") + cli.DockerCmd(c, "run", "-d", "busybox", "top") + out := cli.DockerCmd(c, "info").Stdout() assert.Assert(c, strings.Contains(out, fmt.Sprintf("Containers: %d\n", existing["Containers"]+1))) assert.Assert(c, strings.Contains(out, fmt.Sprintf(" Running: %d\n", existing["ContainersRunning"]+1))) assert.Assert(c, strings.Contains(out, fmt.Sprintf(" Paused: %d\n", existing["ContainersPaused"]))) @@ -84,12 +85,11 @@ func (s *DockerCLIInfoSuite) TestInfoDisplaysPausedContainers(c *testing.T) { existing := existingContainerStates(c) - out := runSleepingContainer(c, "-d") - cleanedContainerID := strings.TrimSpace(out) + id := runSleepingContainer(c, "-d") - dockerCmd(c, "pause", cleanedContainerID) + cli.DockerCmd(c, "pause", id) - out, _ = dockerCmd(c, "info") + out := cli.DockerCmd(c, "info").Stdout() assert.Assert(c, strings.Contains(out, fmt.Sprintf("Containers: %d\n", existing["Containers"]+1))) assert.Assert(c, strings.Contains(out, fmt.Sprintf(" Running: %d\n", existing["ContainersRunning"]))) assert.Assert(c, strings.Contains(out, fmt.Sprintf(" Paused: %d\n", existing["ContainersPaused"]+1))) @@ -101,12 +101,12 @@ func (s *DockerCLIInfoSuite) TestInfoDisplaysStoppedContainers(c *testing.T) { existing := existingContainerStates(c) - out, _ := dockerCmd(c, "run", "-d", "busybox", "top") + out := cli.DockerCmd(c, "run", "-d", "busybox", "top").Stdout() cleanedContainerID := strings.TrimSpace(out) - dockerCmd(c, "stop", cleanedContainerID) + cli.DockerCmd(c, "stop", cleanedContainerID) - out, _ = dockerCmd(c, "info") + out = cli.DockerCmd(c, "info").Stdout() assert.Assert(c, strings.Contains(out, fmt.Sprintf("Containers: %d\n", existing["Containers"]+1))) assert.Assert(c, strings.Contains(out, fmt.Sprintf(" Running: %d\n", existing["ContainersRunning"]))) assert.Assert(c, strings.Contains(out, fmt.Sprintf(" Paused: %d\n", existing["ContainersPaused"]))) @@ -114,7 +114,7 @@ func (s *DockerCLIInfoSuite) TestInfoDisplaysStoppedContainers(c *testing.T) { } func existingContainerStates(c *testing.T) map[string]int { - out, _ := dockerCmd(c, "info", "--format", "{{json .}}") + out := cli.DockerCmd(c, "info", "--format", "{{json .}}").Stdout() var m map[string]interface{} err := json.Unmarshal([]byte(out), &m) assert.NilError(c, err) diff --git a/integration-cli/docker_cli_inspect_test.go b/integration-cli/docker_cli_inspect_test.go index 7b2aebfbbe..04f5aa31b0 100644 --- a/integration-cli/docker_cli_inspect_test.go +++ b/integration-cli/docker_cli_inspect_test.go @@ -12,6 +12,7 @@ import ( "github.com/docker/docker/api/types" "github.com/docker/docker/api/types/container" + "github.com/docker/docker/integration-cli/cli" "gotest.tools/v3/assert" "gotest.tools/v3/icmd" ) @@ -48,7 +49,7 @@ func (s *DockerCLIInspectSuite) TestInspectImage(c *testing.T) { } func (s *DockerCLIInspectSuite) TestInspectInt64(c *testing.T) { - dockerCmd(c, "run", "-d", "-m=300M", "--name", "inspectTest", "busybox", "true") + cli.DockerCmd(c, "run", "-d", "-m=300M", "--name", "inspectTest", "busybox", "true") inspectOut := inspectField(c, "inspectTest", "HostConfig.Memory") assert.Equal(c, inspectOut, "314572800") } @@ -57,7 +58,7 @@ func (s *DockerCLIInspectSuite) TestInspectDefault(c *testing.T) { // Both the container and image are named busybox. docker inspect will fetch the container JSON. // If the container JSON is not available, it will go for the image JSON. - out, _ := dockerCmd(c, "run", "--name=busybox", "-d", "busybox", "true") + out := cli.DockerCmd(c, "run", "--name=busybox", "-d", "busybox", "true").Stdout() containerID := strings.TrimSpace(out) inspectOut := inspectField(c, "busybox", "Id") @@ -65,26 +66,25 @@ func (s *DockerCLIInspectSuite) TestInspectDefault(c *testing.T) { } func (s *DockerCLIInspectSuite) TestInspectStatus(c *testing.T) { - out := runSleepingContainer(c, "-d") - out = strings.TrimSpace(out) + id := runSleepingContainer(c, "-d") - inspectOut := inspectField(c, out, "State.Status") + inspectOut := inspectField(c, id, "State.Status") assert.Equal(c, inspectOut, "running") // Windows does not support pause/unpause on Windows Server Containers. // (RS1 does for Hyper-V Containers, but production CI is not setup for that) if testEnv.DaemonInfo.OSType != "windows" { - dockerCmd(c, "pause", out) - inspectOut = inspectField(c, out, "State.Status") + cli.DockerCmd(c, "pause", id) + inspectOut = inspectField(c, id, "State.Status") assert.Equal(c, inspectOut, "paused") - dockerCmd(c, "unpause", out) - inspectOut = inspectField(c, out, "State.Status") + cli.DockerCmd(c, "unpause", id) + inspectOut = inspectField(c, id, "State.Status") assert.Equal(c, inspectOut, "running") } - dockerCmd(c, "stop", out) - inspectOut = inspectField(c, out, "State.Status") + cli.DockerCmd(c, "stop", id) + inspectOut = inspectField(c, id, "State.Status") assert.Equal(c, inspectOut, "exited") } @@ -94,7 +94,7 @@ func (s *DockerCLIInspectSuite) TestInspectTypeFlagContainer(c *testing.T) { runSleepingContainer(c, "--name=busybox", "-d") formatStr := "--format={{.State.Running}}" - out, _ := dockerCmd(c, "inspect", "--type=container", formatStr, "busybox") + out := cli.DockerCmd(c, "inspect", "--type=container", formatStr, "busybox").Stdout() assert.Equal(c, out, "true\n") // not a container JSON } @@ -103,7 +103,7 @@ func (s *DockerCLIInspectSuite) TestInspectTypeFlagWithNoContainer(c *testing.T) // JSON. Since there is no container named busybox and --type=container, docker inspect will // not try to get the image JSON. It will throw an error. - dockerCmd(c, "run", "-d", "busybox", "true") + cli.DockerCmd(c, "run", "-d", "busybox", "true") _, _, err := dockerCmdWithError("inspect", "--type=container", "busybox") // docker inspect should fail, as there is no container named busybox @@ -115,9 +115,9 @@ func (s *DockerCLIInspectSuite) TestInspectTypeFlagWithImage(c *testing.T) { // JSON as --type=image. if there is no image with name busybox, docker inspect // will throw an error. - dockerCmd(c, "run", "--name=busybox", "-d", "busybox", "true") + cli.DockerCmd(c, "run", "--name=busybox", "-d", "busybox", "true") - out, _ := dockerCmd(c, "inspect", "--type=image", "busybox") + out := cli.DockerCmd(c, "inspect", "--type=image", "busybox").Stdout() // not an image JSON assert.Assert(c, !strings.Contains(out, "State")) } @@ -126,7 +126,7 @@ func (s *DockerCLIInspectSuite) TestInspectTypeFlagWithInvalidValue(c *testing.T // Both the container and image are named busybox. docker inspect will fail // as --type=foobar is not a valid value for the flag. - dockerCmd(c, "run", "--name=busybox", "-d", "busybox", "true") + cli.DockerCmd(c, "run", "--name=busybox", "-d", "busybox", "true") out, exitCode, err := dockerCmdWithError("inspect", "--type=foobar", "busybox") assert.Assert(c, err != nil, "%d", exitCode) @@ -144,7 +144,7 @@ func (s *DockerCLIInspectSuite) TestInspectImageFilterInt(c *testing.T) { // now see if the size turns out to be the same formatStr := fmt.Sprintf("--format={{eq .Size %d}}", size) - out, _ = dockerCmd(c, "inspect", formatStr, imageTest) + out = cli.DockerCmd(c, "inspect", formatStr, imageTest).Stdout() result, err := strconv.ParseBool(strings.TrimSuffix(out, "\n")) assert.NilError(c, err) assert.Equal(c, result, true) @@ -166,7 +166,7 @@ func (s *DockerCLIInspectSuite) TestInspectContainerFilterInt(c *testing.T) { // now get the exit code to verify formatStr := fmt.Sprintf("--format={{eq .State.ExitCode %d}}", exitCode) - out, _ = dockerCmd(c, "inspect", formatStr, id) + out = cli.DockerCmd(c, "inspect", formatStr, id).Stdout() inspectResult, err := strconv.ParseBool(strings.TrimSuffix(out, "\n")) assert.NilError(c, err) assert.Equal(c, inspectResult, true) @@ -181,7 +181,7 @@ func (s *DockerCLIInspectSuite) TestInspectBindMountPoint(c *testing.T) { os.Mkdir(`c:\data`, os.ModeDir) } - dockerCmd(c, "run", "-d", "--name", "test", "-v", prefix+slash+"data:"+prefix+slash+"data:ro"+modifier, "busybox", "cat") + cli.DockerCmd(c, "run", "-d", "--name", "test", "-v", prefix+slash+"data:"+prefix+slash+"data:ro"+modifier, "busybox", "cat") vol := inspectFieldJSON(c, "test", "Mounts") @@ -207,7 +207,7 @@ func (s *DockerCLIInspectSuite) TestInspectBindMountPoint(c *testing.T) { func (s *DockerCLIInspectSuite) TestInspectNamedMountPoint(c *testing.T) { prefix, slash := getPrefixAndSlashFromDaemonPlatform() - dockerCmd(c, "run", "-d", "--name", "test", "-v", "data:"+prefix+slash+"data", "busybox", "cat") + cli.DockerCmd(c, "run", "-d", "--name", "test", "-v", "data:"+prefix+slash+"data", "busybox", "cat") vol := inspectFieldJSON(c, "test", "Mounts") @@ -229,7 +229,7 @@ func (s *DockerCLIInspectSuite) TestInspectNamedMountPoint(c *testing.T) { // #14947 func (s *DockerCLIInspectSuite) TestInspectTimesAsRFC3339Nano(c *testing.T) { - out, _ := dockerCmd(c, "run", "-d", "busybox", "true") + out := cli.DockerCmd(c, "run", "-d", "busybox", "true").Stdout() id := strings.TrimSpace(out) startedAt := inspectField(c, id, "State.StartedAt") finishedAt := inspectField(c, id, "State.FinishedAt") @@ -250,7 +250,7 @@ func (s *DockerCLIInspectSuite) TestInspectTimesAsRFC3339Nano(c *testing.T) { // #15633 func (s *DockerCLIInspectSuite) TestInspectLogConfigNoType(c *testing.T) { - dockerCmd(c, "create", "--name=test", "--log-opt", "max-file=42", "busybox") + cli.DockerCmd(c, "create", "--name=test", "--log-opt", "max-file=42", "busybox") var logConfig container.LogConfig out := inspectFieldJSON(c, "test", "HostConfig.LogConfig") @@ -269,7 +269,7 @@ func (s *DockerCLIInspectSuite) TestInspectNoSizeFlagContainer(c *testing.T) { runSleepingContainer(c, "--name=busybox", "-d") formatStr := "--format={{.SizeRw}},{{.SizeRootFs}}" - out, _ := dockerCmd(c, "inspect", "--type=container", formatStr, "busybox") + out := cli.DockerCmd(c, "inspect", "--type=container", formatStr, "busybox").Stdout() assert.Equal(c, strings.TrimSpace(out), ",", fmt.Sprintf("Expected not to display size info: %s", out)) } @@ -277,7 +277,7 @@ func (s *DockerCLIInspectSuite) TestInspectSizeFlagContainer(c *testing.T) { runSleepingContainer(c, "--name=busybox", "-d") formatStr := "--format='{{.SizeRw}},{{.SizeRootFs}}'" - out, _ := dockerCmd(c, "inspect", "-s", "--type=container", formatStr, "busybox") + out := cli.DockerCmd(c, "inspect", "-s", "--type=container", formatStr, "busybox").Stdout() sz := strings.Split(out, ",") assert.Assert(c, strings.TrimSpace(sz[0]) != "") @@ -335,8 +335,8 @@ func (s *DockerCLIInspectSuite) TestInspectStopWhenNotFound(c *testing.T) { } func (s *DockerCLIInspectSuite) TestInspectHistory(c *testing.T) { - dockerCmd(c, "run", "--name=testcont", "busybox", "echo", "hello") - dockerCmd(c, "commit", "-m", "test comment", "testcont", "testimg") + cli.DockerCmd(c, "run", "--name=testcont", "busybox", "echo", "hello") + cli.DockerCmd(c, "commit", "-m", "test comment", "testcont", "testimg") out, _, err := dockerCmdWithError("inspect", "--format='{{.Comment}}'", "testimg") assert.NilError(c, err) assert.Assert(c, strings.Contains(out, "test comment")) @@ -346,8 +346,8 @@ func (s *DockerCLIInspectSuite) TestInspectContainerNetworkDefault(c *testing.T) testRequires(c, DaemonIsLinux) contName := "test1" - dockerCmd(c, "run", "--name", contName, "-d", "busybox", "top") - netOut, _ := dockerCmd(c, "network", "inspect", "--format={{.ID}}", "bridge") + cli.DockerCmd(c, "run", "--name", contName, "-d", "busybox", "top") + netOut := cli.DockerCmd(c, "network", "inspect", "--format={{.ID}}", "bridge").Stdout() out := inspectField(c, contName, "NetworkSettings.Networks") assert.Assert(c, strings.Contains(out, "bridge")) out = inspectField(c, contName, "NetworkSettings.Networks.bridge.NetworkID") @@ -357,8 +357,8 @@ func (s *DockerCLIInspectSuite) TestInspectContainerNetworkDefault(c *testing.T) func (s *DockerCLIInspectSuite) TestInspectContainerNetworkCustom(c *testing.T) { testRequires(c, DaemonIsLinux) - netOut, _ := dockerCmd(c, "network", "create", "net1") - dockerCmd(c, "run", "--name=container1", "--net=net1", "-d", "busybox", "top") + netOut := cli.DockerCmd(c, "network", "create", "net1").Stdout() + cli.DockerCmd(c, "run", "--name=container1", "--net=net1", "-d", "busybox", "top") out := inspectField(c, "container1", "NetworkSettings.Networks") assert.Assert(c, strings.Contains(out, "net1")) out = inspectField(c, "container1", "NetworkSettings.Networks.net1.NetworkID") @@ -379,9 +379,9 @@ func (s *DockerCLIInspectSuite) TestInspectAmpersand(c *testing.T) { testRequires(c, DaemonIsLinux) name := "test" - out, _ := dockerCmd(c, "run", "--name", name, "--env", `TEST_ENV="soanni&rtr"`, "busybox", "env") + out := cli.DockerCmd(c, "run", "--name", name, "--env", `TEST_ENV="soanni&rtr"`, "busybox", "env").Stdout() assert.Assert(c, strings.Contains(out, `soanni&rtr`)) - out, _ = dockerCmd(c, "inspect", name) + out = cli.DockerCmd(c, "inspect", name).Stdout() assert.Assert(c, strings.Contains(out, `soanni&rtr`)) } diff --git a/integration-cli/docker_cli_links_test.go b/integration-cli/docker_cli_links_test.go index 300a8f2f7d..06deefaf70 100644 --- a/integration-cli/docker_cli_links_test.go +++ b/integration-cli/docker_cli_links_test.go @@ -9,6 +9,7 @@ import ( "strings" "testing" + "github.com/docker/docker/integration-cli/cli" "github.com/docker/docker/runconfig" "gotest.tools/v3/assert" is "gotest.tools/v3/assert/cmp" @@ -62,8 +63,8 @@ func testLinkPingOnNetwork(c *testing.T, network string) { runArgs2 := append([]string{"run", "-d", "--name", "container2", "--hostname", "wilma"}, postArgs...) // Run the two named containers - dockerCmd(c, runArgs1...) - dockerCmd(c, runArgs2...) + cli.DockerCmd(c, runArgs1...) + cli.DockerCmd(c, runArgs2...) postArgs = []string{} if network != "" { @@ -77,34 +78,32 @@ func testLinkPingOnNetwork(c *testing.T, network string) { // test ping by alias, ping by name, and ping by hostname // 1. Ping by alias - dockerCmd(c, append(runArgs, fmt.Sprintf(pingCmd, "alias1", "alias2"))...) + cli.DockerCmd(c, append(runArgs, fmt.Sprintf(pingCmd, "alias1", "alias2"))...) // 2. Ping by container name - dockerCmd(c, append(runArgs, fmt.Sprintf(pingCmd, "container1", "container2"))...) + cli.DockerCmd(c, append(runArgs, fmt.Sprintf(pingCmd, "container1", "container2"))...) // 3. Ping by hostname - dockerCmd(c, append(runArgs, fmt.Sprintf(pingCmd, "fred", "wilma"))...) + cli.DockerCmd(c, append(runArgs, fmt.Sprintf(pingCmd, "fred", "wilma"))...) // Clean for next round - dockerCmd(c, "rm", "-f", "container1") - dockerCmd(c, "rm", "-f", "container2") + cli.DockerCmd(c, "rm", "-f", "container1") + cli.DockerCmd(c, "rm", "-f", "container2") } func (s *DockerCLILinksSuite) TestLinksPingLinkedContainersAfterRename(c *testing.T) { testRequires(c, DaemonIsLinux) - out, _ := dockerCmd(c, "run", "-d", "--name", "container1", "busybox", "top") - idA := strings.TrimSpace(out) - out, _ = dockerCmd(c, "run", "-d", "--name", "container2", "busybox", "top") - idB := strings.TrimSpace(out) - dockerCmd(c, "rename", "container1", "container_new") - dockerCmd(c, "run", "--rm", "--link", "container_new:alias1", "--link", "container2:alias2", "busybox", "sh", "-c", "ping -c 1 alias1 -W 1 && ping -c 1 alias2 -W 1") - dockerCmd(c, "kill", idA) - dockerCmd(c, "kill", idB) + idA := cli.DockerCmd(c, "run", "-d", "--name", "container1", "busybox", "top").Stdout() + idB := cli.DockerCmd(c, "run", "-d", "--name", "container2", "busybox", "top").Stdout() + cli.DockerCmd(c, "rename", "container1", "container_new") + cli.DockerCmd(c, "run", "--rm", "--link", "container_new:alias1", "--link", "container2:alias2", "busybox", "sh", "-c", "ping -c 1 alias1 -W 1 && ping -c 1 alias2 -W 1") + cli.DockerCmd(c, "kill", strings.TrimSpace(idA)) + cli.DockerCmd(c, "kill", strings.TrimSpace(idB)) } func (s *DockerCLILinksSuite) TestLinksInspectLinksStarted(c *testing.T) { testRequires(c, DaemonIsLinux) - dockerCmd(c, "run", "-d", "--name", "container1", "busybox", "top") - dockerCmd(c, "run", "-d", "--name", "container2", "busybox", "top") - dockerCmd(c, "run", "-d", "--name", "testinspectlink", "--link", "container1:alias1", "--link", "container2:alias2", "busybox", "top") + cli.DockerCmd(c, "run", "-d", "--name", "container1", "busybox", "top") + cli.DockerCmd(c, "run", "-d", "--name", "container2", "busybox", "top") + cli.DockerCmd(c, "run", "-d", "--name", "testinspectlink", "--link", "container1:alias1", "--link", "container2:alias2", "busybox", "top") links := inspectFieldJSON(c, "testinspectlink", "HostConfig.Links") var result []string @@ -122,9 +121,9 @@ func (s *DockerCLILinksSuite) TestLinksInspectLinksStarted(c *testing.T) { func (s *DockerCLILinksSuite) TestLinksInspectLinksStopped(c *testing.T) { testRequires(c, DaemonIsLinux) - dockerCmd(c, "run", "-d", "--name", "container1", "busybox", "top") - dockerCmd(c, "run", "-d", "--name", "container2", "busybox", "top") - dockerCmd(c, "run", "-d", "--name", "testinspectlink", "--link", "container1:alias1", "--link", "container2:alias2", "busybox", "true") + cli.DockerCmd(c, "run", "-d", "--name", "container1", "busybox", "top") + cli.DockerCmd(c, "run", "-d", "--name", "container2", "busybox", "top") + cli.DockerCmd(c, "run", "-d", "--name", "testinspectlink", "--link", "container1:alias1", "--link", "container2:alias2", "busybox", "true") links := inspectFieldJSON(c, "testinspectlink", "HostConfig.Links") var result []string @@ -141,22 +140,20 @@ func (s *DockerCLILinksSuite) TestLinksInspectLinksStopped(c *testing.T) { func (s *DockerCLILinksSuite) TestLinksNotStartedParentNotFail(c *testing.T) { testRequires(c, DaemonIsLinux) - dockerCmd(c, "create", "--name=first", "busybox", "top") - dockerCmd(c, "create", "--name=second", "--link=first:first", "busybox", "top") - dockerCmd(c, "start", "first") + cli.DockerCmd(c, "create", "--name=first", "busybox", "top") + cli.DockerCmd(c, "create", "--name=second", "--link=first:first", "busybox", "top") + cli.DockerCmd(c, "start", "first") } func (s *DockerCLILinksSuite) TestLinksHostsFilesInject(c *testing.T) { testRequires(c, DaemonIsLinux) testRequires(c, testEnv.IsLocalDaemon) - out, _ := dockerCmd(c, "run", "-itd", "--name", "one", "busybox", "top") - idOne := strings.TrimSpace(out) - - out, _ = dockerCmd(c, "run", "-itd", "--name", "two", "--link", "one:onetwo", "busybox", "top") - idTwo := strings.TrimSpace(out) - - assert.Assert(c, waitRun(idTwo) == nil) + idOne := cli.DockerCmd(c, "run", "-itd", "--name", "one", "busybox", "top").Stdout() + idOne = strings.TrimSpace(idOne) + idTwo := cli.DockerCmd(c, "run", "-itd", "--name", "two", "--link", "one:onetwo", "busybox", "top").Stdout() + idTwo = strings.TrimSpace(idTwo) + cli.WaitRun(c, idTwo) readContainerFileWithExec(c, idOne, "/etc/hosts") contentTwo := readContainerFileWithExec(c, idTwo, "/etc/hosts") @@ -167,9 +164,9 @@ func (s *DockerCLILinksSuite) TestLinksHostsFilesInject(c *testing.T) { func (s *DockerCLILinksSuite) TestLinksUpdateOnRestart(c *testing.T) { testRequires(c, DaemonIsLinux) testRequires(c, testEnv.IsLocalDaemon) - dockerCmd(c, "run", "-d", "--name", "one", "busybox", "top") - out, _ := dockerCmd(c, "run", "-d", "--name", "two", "--link", "one:onetwo", "--link", "one:one", "busybox", "top") - id := strings.TrimSpace(out) + cli.DockerCmd(c, "run", "-d", "--name", "one", "busybox", "top") + id := cli.DockerCmd(c, "run", "-d", "--name", "two", "--link", "one:onetwo", "--link", "one:one", "busybox", "top").Stdout() + id = strings.TrimSpace(id) realIP := inspectField(c, "one", "NetworkSettings.Networks.bridge.IPAddress") content := readContainerFileWithExec(c, id, "/etc/hosts") @@ -186,7 +183,7 @@ func (s *DockerCLILinksSuite) TestLinksUpdateOnRestart(c *testing.T) { ip = getIP(content, "onetwo") assert.Check(c, is.Equal(ip, realIP)) - dockerCmd(c, "restart", "one") + cli.DockerCmd(c, "restart", "one") realIP = inspectField(c, "one", "NetworkSettings.Networks.bridge.IPAddress") content = readContainerFileWithExec(c, id, "/etc/hosts") @@ -199,8 +196,8 @@ func (s *DockerCLILinksSuite) TestLinksUpdateOnRestart(c *testing.T) { func (s *DockerCLILinksSuite) TestLinksEnvs(c *testing.T) { testRequires(c, DaemonIsLinux) - dockerCmd(c, "run", "-d", "-e", "e1=", "-e", "e2=v2", "-e", "e3=v3=v3", "--name=first", "busybox", "top") - out, _ := dockerCmd(c, "run", "--name=second", "--link=first:first", "busybox", "env") + cli.DockerCmd(c, "run", "-d", "-e", "e1=", "-e", "e2=v2", "-e", "e3=v3=v3", "--name=first", "busybox", "top") + out := cli.DockerCmd(c, "run", "--name=second", "--link=first:first", "busybox", "env").Stdout() assert.Assert(c, is.Contains(out, "FIRST_ENV_e1=\n")) assert.Assert(c, is.Contains(out, "FIRST_ENV_e2=v2")) assert.Assert(c, is.Contains(out, "FIRST_ENV_e3=v3=v3")) @@ -208,15 +205,13 @@ func (s *DockerCLILinksSuite) TestLinksEnvs(c *testing.T) { func (s *DockerCLILinksSuite) TestLinkShortDefinition(c *testing.T) { testRequires(c, DaemonIsLinux) - out, _ := dockerCmd(c, "run", "-d", "--name", "shortlinkdef", "busybox", "top") + cid := cli.DockerCmd(c, "run", "-d", "--name", "shortlinkdef", "busybox", "top").Stdout() + cid = strings.TrimSpace(cid) + cli.WaitRun(c, cid) - cid := strings.TrimSpace(out) - assert.Assert(c, waitRun(cid) == nil) - - out, _ = dockerCmd(c, "run", "-d", "--name", "link2", "--link", "shortlinkdef", "busybox", "top") - - cid2 := strings.TrimSpace(out) - assert.Assert(c, waitRun(cid2) == nil) + cid2 := cli.DockerCmd(c, "run", "-d", "--name", "link2", "--link", "shortlinkdef", "busybox", "top").Stdout() + cid2 = strings.TrimSpace(cid2) + cli.WaitRun(c, cid2) links := inspectFieldJSON(c, cid2, "HostConfig.Links") assert.Equal(c, links, `["/shortlinkdef:/link2/shortlinkdef"]`) @@ -224,7 +219,7 @@ func (s *DockerCLILinksSuite) TestLinkShortDefinition(c *testing.T) { func (s *DockerCLILinksSuite) TestLinksNetworkHostContainer(c *testing.T) { testRequires(c, DaemonIsLinux, NotUserNamespace) - dockerCmd(c, "run", "-d", "--net", "host", "--name", "host_container", "busybox", "top") + cli.DockerCmd(c, "run", "-d", "--net", "host", "--name", "host_container", "busybox", "top") out, _, err := dockerCmdWithError("run", "--name", "should_fail", "--link", "host_container:tester", "busybox", "true") // Running container linking to a container with --net host should have failed @@ -235,14 +230,14 @@ func (s *DockerCLILinksSuite) TestLinksNetworkHostContainer(c *testing.T) { func (s *DockerCLILinksSuite) TestLinksEtcHostsRegularFile(c *testing.T) { testRequires(c, DaemonIsLinux, NotUserNamespace) - out, _ := dockerCmd(c, "run", "--net=host", "busybox", "ls", "-la", "/etc/hosts") + out := cli.DockerCmd(c, "run", "--net=host", "busybox", "ls", "-la", "/etc/hosts").Stdout() // /etc/hosts should be a regular file assert.Assert(c, is.Regexp("^-.+\n$", out)) } func (s *DockerCLILinksSuite) TestLinksMultipleWithSameName(c *testing.T) { testRequires(c, DaemonIsLinux) - dockerCmd(c, "run", "-d", "--name=upstream-a", "busybox", "top") - dockerCmd(c, "run", "-d", "--name=upstream-b", "busybox", "top") - dockerCmd(c, "run", "--link", "upstream-a:upstream", "--link", "upstream-b:upstream", "busybox", "sh", "-c", "ping -c 1 upstream") + cli.DockerCmd(c, "run", "-d", "--name=upstream-a", "busybox", "top") + cli.DockerCmd(c, "run", "-d", "--name=upstream-b", "busybox", "top") + cli.DockerCmd(c, "run", "--link", "upstream-a:upstream", "--link", "upstream-b:upstream", "busybox", "sh", "-c", "ping -c 1 upstream") } diff --git a/integration-cli/docker_cli_login_test.go b/integration-cli/docker_cli_login_test.go index 83eefe8973..920396ee49 100644 --- a/integration-cli/docker_cli_login_test.go +++ b/integration-cli/docker_cli_login_test.go @@ -7,6 +7,7 @@ import ( "strings" "testing" + "github.com/docker/docker/integration-cli/cli" "gotest.tools/v3/assert" ) @@ -30,7 +31,7 @@ func (s *DockerCLILoginSuite) TestLoginWithoutTTY(c *testing.T) { // run the command and block until it's done err := cmd.Run() - assert.ErrorContains(c, err, "") //"Expected non nil err when logging in & TTY not available" + assert.ErrorContains(c, err, "") // "Expected non nil err when logging in & TTY not available" } func (s *DockerRegistryAuthHtpasswdSuite) TestLoginToPrivateRegistry(c *testing.T) { @@ -40,5 +41,5 @@ func (s *DockerRegistryAuthHtpasswdSuite) TestLoginToPrivateRegistry(c *testing. assert.Assert(c, strings.Contains(out, "401 Unauthorized")) // now it's fine - dockerCmd(c, "login", "-u", s.reg.Username(), "-p", s.reg.Password(), privateRegistryURL) + cli.DockerCmd(c, "login", "-u", s.reg.Username(), "-p", s.reg.Password(), privateRegistryURL) } diff --git a/integration-cli/docker_cli_logout_test.go b/integration-cli/docker_cli_logout_test.go index f080d8c43e..6bcec50877 100644 --- a/integration-cli/docker_cli_logout_test.go +++ b/integration-cli/docker_cli_logout_test.go @@ -9,6 +9,7 @@ import ( "strings" "testing" + "github.com/docker/docker/integration-cli/cli" "github.com/docker/docker/testutil" "gotest.tools/v3/assert" ) @@ -26,7 +27,7 @@ func (s *DockerRegistryAuthHtpasswdSuite) TestLogoutWithExternalAuth(c *testing. testPath := fmt.Sprintf("%s%c%s", osPath, filepath.ListSeparator, absolute) c.Setenv("PATH", testPath) - repoName := fmt.Sprintf("%v/dockercli/busybox:authtest", privateRegistryURL) + imgRepoName := fmt.Sprintf("%v/dockercli/busybox:authtest", privateRegistryURL) tmp, err := os.MkdirTemp("", "integration-cli-") assert.NilError(c, err) @@ -46,9 +47,9 @@ func (s *DockerRegistryAuthHtpasswdSuite) TestLogoutWithExternalAuth(c *testing. assert.Assert(c, !strings.Contains(string(b), `"auth":`)) assert.Assert(c, strings.Contains(string(b), privateRegistryURL)) - _, err = s.d.Cmd("--config", tmp, "tag", "busybox", repoName) + _, err = s.d.Cmd("--config", tmp, "tag", "busybox", imgRepoName) assert.NilError(c, err) - _, err = s.d.Cmd("--config", tmp, "push", repoName) + _, err = s.d.Cmd("--config", tmp, "push", imgRepoName) assert.NilError(c, err) _, err = s.d.Cmd("--config", tmp, "logout", privateRegistryURL) assert.NilError(c, err) @@ -58,7 +59,7 @@ func (s *DockerRegistryAuthHtpasswdSuite) TestLogoutWithExternalAuth(c *testing. assert.Assert(c, !strings.Contains(string(b), privateRegistryURL)) // check I cannot pull anymore - out, err := s.d.Cmd("--config", tmp, "pull", repoName) + out, err := s.d.Cmd("--config", tmp, "pull", imgRepoName) assert.ErrorContains(c, err, "", out) assert.Assert(c, strings.Contains(out, "no basic auth credentials")) } @@ -88,14 +89,14 @@ func (s *DockerRegistryAuthHtpasswdSuite) TestLogoutWithWrongHostnamesStored(c * err = os.WriteFile(configPath, []byte(externalAuthConfig), 0o644) assert.NilError(c, err) - dockerCmd(c, "--config", tmp, "login", "-u", s.reg.Username(), "-p", s.reg.Password(), privateRegistryURL) + cli.DockerCmd(c, "--config", tmp, "login", "-u", s.reg.Username(), "-p", s.reg.Password(), privateRegistryURL) b, err := os.ReadFile(configPath) assert.NilError(c, err) assert.Assert(c, strings.Contains(string(b), fmt.Sprintf(`"https://%s": {}`, privateRegistryURL))) assert.Assert(c, strings.Contains(string(b), fmt.Sprintf(`"%s": {}`, privateRegistryURL))) - dockerCmd(c, "--config", tmp, "logout", privateRegistryURL) + cli.DockerCmd(c, "--config", tmp, "logout", privateRegistryURL) b, err = os.ReadFile(configPath) assert.NilError(c, err) diff --git a/integration-cli/docker_cli_logs_test.go b/integration-cli/docker_cli_logs_test.go index a979141110..6ceff3a47b 100644 --- a/integration-cli/docker_cli_logs_test.go +++ b/integration-cli/docker_cli_logs_test.go @@ -47,22 +47,20 @@ func (s *DockerCLILogsSuite) TestLogsContainerMuchBiggerThanPage(c *testing.T) { } func testLogsContainerPagination(c *testing.T, testLen int) { - out, _ := dockerCmd(c, "run", "-d", "busybox", "sh", "-c", fmt.Sprintf("for i in $(seq 1 %d); do echo -n = >> a.a; done; echo >> a.a; cat a.a", testLen)) - id := strings.TrimSpace(out) - dockerCmd(c, "wait", id) - out, _ = dockerCmd(c, "logs", id) + id := cli.DockerCmd(c, "run", "-d", "busybox", "sh", "-c", fmt.Sprintf("for i in $(seq 1 %d); do echo -n = >> a.a; done; echo >> a.a; cat a.a", testLen)).Stdout() + id = strings.TrimSpace(id) + cli.DockerCmd(c, "wait", id) + out := cli.DockerCmd(c, "logs", id).Combined() assert.Equal(c, len(out), testLen+1) } func (s *DockerCLILogsSuite) TestLogsTimestamps(c *testing.T) { testLen := 100 - out, _ := dockerCmd(c, "run", "-d", "busybox", "sh", "-c", fmt.Sprintf("for i in $(seq 1 %d); do echo = >> a.a; done; cat a.a", testLen)) - - id := strings.TrimSpace(out) - dockerCmd(c, "wait", id) - - out, _ = dockerCmd(c, "logs", "-t", id) + id := cli.DockerCmd(c, "run", "-d", "busybox", "sh", "-c", fmt.Sprintf("for i in $(seq 1 %d); do echo = >> a.a; done; cat a.a", testLen)).Stdout() + id = strings.TrimSpace(id) + cli.DockerCmd(c, "wait", id) + out := cli.DockerCmd(c, "logs", "-t", id).Combined() lines := strings.Split(out, "\n") assert.Equal(c, len(lines), testLen+1) @@ -138,7 +136,7 @@ func (s *DockerCLILogsSuite) TestLogsTail(c *testing.T) { } func (s *DockerCLILogsSuite) TestLogsFollowStopped(c *testing.T) { - dockerCmd(c, "run", "--name=test", "busybox", "echo", "hello") + cli.DockerCmd(c, "run", "--name=test", "busybox", "echo", "hello") id := getIDByName(c, "test") logsCmd := exec.Command(dockerBinary, "logs", "-f", id) @@ -160,14 +158,14 @@ func (s *DockerCLILogsSuite) TestLogsFollowStopped(c *testing.T) { func (s *DockerCLILogsSuite) TestLogsSince(c *testing.T) { name := "testlogssince" - dockerCmd(c, "run", "--name="+name, "busybox", "/bin/sh", "-c", "for i in $(seq 1 3); do sleep 2; echo log$i; done") - out, _ := dockerCmd(c, "logs", "-t", name) + cli.DockerCmd(c, "run", "--name="+name, "busybox", "/bin/sh", "-c", "for i in $(seq 1 3); do sleep 2; echo log$i; done") + out := cli.DockerCmd(c, "logs", "-t", name).Combined() log2Line := strings.Split(strings.Split(out, "\n")[1], " ") t, err := time.Parse(time.RFC3339Nano, log2Line[0]) // the timestamp log2 is written assert.NilError(c, err) since := t.Unix() + 1 // add 1s so log1 & log2 doesn't show up - out, _ = dockerCmd(c, "logs", "-t", fmt.Sprintf("--since=%v", since), name) + out = cli.DockerCmd(c, "logs", "-t", fmt.Sprintf("--since=%v", since), name).Combined() // Skip 2 seconds unexpected := []string{"log1", "log2"} @@ -197,14 +195,14 @@ func (s *DockerCLILogsSuite) TestLogsSinceFutureFollow(c *testing.T) { // TODO Windows TP5 - Figure out why this test is so flakey. Disabled for now. testRequires(c, DaemonIsLinux) name := "testlogssincefuturefollow" - dockerCmd(c, "run", "-d", "--name", name, "busybox", "/bin/sh", "-c", `for i in $(seq 1 5); do echo log$i; sleep 1; done`) + cli.DockerCmd(c, "run", "-d", "--name", name, "busybox", "/bin/sh", "-c", `for i in $(seq 1 5); do echo log$i; sleep 1; done`) // Extract one timestamp from the log file to give us a starting point for // our `--since` argument. Because the log producer runs in the background, // we need to check repeatedly for some output to be produced. var timestamp string for i := 0; i != 100 && timestamp == ""; i++ { - if out, _ := dockerCmd(c, "logs", "-t", name); out == "" { + if out := cli.DockerCmd(c, "logs", "-t", name).Combined(); out == "" { time.Sleep(time.Millisecond * 100) // Retry } else { timestamp = strings.Split(strings.Split(out, "\n")[0], " ")[0] @@ -216,7 +214,7 @@ func (s *DockerCLILogsSuite) TestLogsSinceFutureFollow(c *testing.T) { assert.NilError(c, err) since := t.Unix() + 2 - out, _ := dockerCmd(c, "logs", "-t", "-f", fmt.Sprintf("--since=%v", since), name) + out := cli.DockerCmd(c, "logs", "-t", "-f", fmt.Sprintf("--since=%v", since), name).Combined() assert.Assert(c, len(out) != 0, "cannot read from empty log") lines := strings.Split(strings.TrimSpace(out), "\n") for _, v := range lines { @@ -231,14 +229,13 @@ func (s *DockerCLILogsSuite) TestLogsFollowSlowStdoutConsumer(c *testing.T) { // TODO Windows: Fix this test for TP5. testRequires(c, DaemonIsLinux) expected := 150000 - out, _ := dockerCmd(c, "run", "-d", "busybox", "/bin/sh", "-c", fmt.Sprintf("usleep 600000; yes X | head -c %d", expected)) - - id := strings.TrimSpace(out) + id := cli.DockerCmd(c, "run", "-d", "busybox", "/bin/sh", "-c", fmt.Sprintf("usleep 600000; yes X | head -c %d", expected)).Stdout() + id = strings.TrimSpace(id) stopSlowRead := make(chan bool) go func() { - dockerCmd(c, "wait", id) + cli.DockerCmd(c, "wait", id) stopSlowRead <- true }() @@ -389,8 +386,8 @@ func (s *DockerCLILogsSuite) TestLogsCLIContainerNotFound(c *testing.T) { } func (s *DockerCLILogsSuite) TestLogsWithDetails(c *testing.T) { - dockerCmd(c, "run", "--name=test", "--label", "foo=bar", "-e", "baz=qux", "--log-opt", "labels=foo", "--log-opt", "env=baz", "busybox", "echo", "hello") - out, _ := dockerCmd(c, "logs", "--details", "--timestamps", "test") + cli.DockerCmd(c, "run", "--name=test", "--label", "foo=bar", "-e", "baz=qux", "--log-opt", "labels=foo", "--log-opt", "env=baz", "busybox", "echo", "hello") + out := cli.DockerCmd(c, "logs", "--details", "--timestamps", "test").Combined() logFields := strings.Fields(strings.TrimSpace(out)) assert.Equal(c, len(logFields), 3, out) diff --git a/integration-cli/docker_cli_netmode_test.go b/integration-cli/docker_cli_netmode_test.go index 035a58be3b..80ba1374f1 100644 --- a/integration-cli/docker_cli_netmode_test.go +++ b/integration-cli/docker_cli_netmode_test.go @@ -5,6 +5,7 @@ import ( "strings" "testing" + "github.com/docker/docker/integration-cli/cli" "github.com/docker/docker/runconfig" "gotest.tools/v3/assert" ) @@ -28,72 +29,71 @@ func (s *DockerCLINetmodeSuite) OnTimeout(c *testing.T) { } // DockerCmdWithFail executes a docker command that is supposed to fail and returns -// the output, the exit code. If the command returns a Nil error, it will fail and -// stop the tests. -func dockerCmdWithFail(c *testing.T, args ...string) (string, int) { - out, status, err := dockerCmdWithError(args...) +// the output. If the command returns a Nil error, it will fail and stop the tests. +func dockerCmdWithFail(c *testing.T, args ...string) string { + out, _, err := dockerCmdWithError(args...) assert.Assert(c, err != nil, "%v", out) - return out, status + return out } func (s *DockerCLINetmodeSuite) TestNetHostnameWithNetHost(c *testing.T) { testRequires(c, DaemonIsLinux, NotUserNamespace) - out, _ := dockerCmd(c, "run", "--net=host", "busybox", "ps") + out := cli.DockerCmd(c, "run", "--net=host", "busybox", "ps").Stdout() assert.Assert(c, strings.Contains(out, stringCheckPS)) } func (s *DockerCLINetmodeSuite) TestNetHostname(c *testing.T) { testRequires(c, DaemonIsLinux) - out, _ := dockerCmd(c, "run", "-h=name", "busybox", "ps") + out := cli.DockerCmd(c, "run", "-h=name", "busybox", "ps").Stdout() assert.Assert(c, strings.Contains(out, stringCheckPS)) - out, _ = dockerCmd(c, "run", "-h=name", "--net=bridge", "busybox", "ps") + out = cli.DockerCmd(c, "run", "-h=name", "--net=bridge", "busybox", "ps").Stdout() assert.Assert(c, strings.Contains(out, stringCheckPS)) - out, _ = dockerCmd(c, "run", "-h=name", "--net=none", "busybox", "ps") + out = cli.DockerCmd(c, "run", "-h=name", "--net=none", "busybox", "ps").Stdout() assert.Assert(c, strings.Contains(out, stringCheckPS)) - out, _ = dockerCmdWithFail(c, "run", "-h=name", "--net=container:other", "busybox", "ps") + out = dockerCmdWithFail(c, "run", "-h=name", "--net=container:other", "busybox", "ps") assert.Assert(c, strings.Contains(out, runconfig.ErrConflictNetworkHostname.Error())) - out, _ = dockerCmdWithFail(c, "run", "--net=container", "busybox", "ps") + out = dockerCmdWithFail(c, "run", "--net=container", "busybox", "ps") assert.Assert(c, strings.Contains(out, "invalid container format container:")) - out, _ = dockerCmdWithFail(c, "run", "--net=weird", "busybox", "ps") + out = dockerCmdWithFail(c, "run", "--net=weird", "busybox", "ps") assert.Assert(c, strings.Contains(strings.ToLower(out), "not found")) } func (s *DockerCLINetmodeSuite) TestConflictContainerNetworkAndLinks(c *testing.T) { testRequires(c, DaemonIsLinux) - out, _ := dockerCmdWithFail(c, "run", "--net=container:other", "--link=zip:zap", "busybox", "ps") + out := dockerCmdWithFail(c, "run", "--net=container:other", "--link=zip:zap", "busybox", "ps") assert.Assert(c, strings.Contains(out, runconfig.ErrConflictContainerNetworkAndLinks.Error())) } func (s *DockerCLINetmodeSuite) TestConflictContainerNetworkHostAndLinks(c *testing.T) { testRequires(c, DaemonIsLinux, NotUserNamespace) - out, _ := dockerCmdWithFail(c, "run", "--net=host", "--link=zip:zap", "busybox", "ps") + out := dockerCmdWithFail(c, "run", "--net=host", "--link=zip:zap", "busybox", "ps") assert.Assert(c, strings.Contains(out, runconfig.ErrConflictHostNetworkAndLinks.Error())) } func (s *DockerCLINetmodeSuite) TestConflictNetworkModeNetHostAndOptions(c *testing.T) { testRequires(c, DaemonIsLinux, NotUserNamespace) - out, _ := dockerCmdWithFail(c, "run", "--net=host", "--mac-address=92:d0:c6:0a:29:33", "busybox", "ps") + out := dockerCmdWithFail(c, "run", "--net=host", "--mac-address=92:d0:c6:0a:29:33", "busybox", "ps") assert.Assert(c, strings.Contains(out, runconfig.ErrConflictContainerNetworkAndMac.Error())) } func (s *DockerCLINetmodeSuite) TestConflictNetworkModeAndOptions(c *testing.T) { testRequires(c, DaemonIsLinux) - out, _ := dockerCmdWithFail(c, "run", "--net=container:other", "--dns=8.8.8.8", "busybox", "ps") + out := dockerCmdWithFail(c, "run", "--net=container:other", "--dns=8.8.8.8", "busybox", "ps") assert.Assert(c, strings.Contains(out, runconfig.ErrConflictNetworkAndDNS.Error())) - out, _ = dockerCmdWithFail(c, "run", "--net=container:other", "--add-host=name:8.8.8.8", "busybox", "ps") + out = dockerCmdWithFail(c, "run", "--net=container:other", "--add-host=name:8.8.8.8", "busybox", "ps") assert.Assert(c, strings.Contains(out, runconfig.ErrConflictNetworkHosts.Error())) - out, _ = dockerCmdWithFail(c, "run", "--net=container:other", "--mac-address=92:d0:c6:0a:29:33", "busybox", "ps") + out = dockerCmdWithFail(c, "run", "--net=container:other", "--mac-address=92:d0:c6:0a:29:33", "busybox", "ps") assert.Assert(c, strings.Contains(out, runconfig.ErrConflictContainerNetworkAndMac.Error())) - out, _ = dockerCmdWithFail(c, "run", "--net=container:other", "-P", "busybox", "ps") + out = dockerCmdWithFail(c, "run", "--net=container:other", "-P", "busybox", "ps") assert.Assert(c, strings.Contains(out, runconfig.ErrConflictNetworkPublishPorts.Error())) - out, _ = dockerCmdWithFail(c, "run", "--net=container:other", "-p", "8080", "busybox", "ps") + out = dockerCmdWithFail(c, "run", "--net=container:other", "-p", "8080", "busybox", "ps") assert.Assert(c, strings.Contains(out, runconfig.ErrConflictNetworkPublishPorts.Error())) - out, _ = dockerCmdWithFail(c, "run", "--net=container:other", "--expose", "8000-9000", "busybox", "ps") + out = dockerCmdWithFail(c, "run", "--net=container:other", "--expose", "8000-9000", "busybox", "ps") assert.Assert(c, strings.Contains(out, runconfig.ErrConflictNetworkExposePorts.Error())) } diff --git a/integration-cli/docker_cli_network_unix_test.go b/integration-cli/docker_cli_network_unix_test.go index 8875eef2ba..de0ff2b8fc 100644 --- a/integration-cli/docker_cli_network_unix_test.go +++ b/integration-cli/docker_cli_network_unix_test.go @@ -237,7 +237,7 @@ func assertNwNotAvailable(c *testing.T, name string) { } func isNwPresent(c *testing.T, name string) bool { - out, _ := dockerCmd(c, "network", "ls") + out := cli.DockerCmd(c, "network", "ls").Stdout() lines := strings.Split(out, "\n") for i := 1; i < len(lines)-1; i++ { netFields := strings.Fields(lines[i]) @@ -265,7 +265,7 @@ func assertNwList(c *testing.T, out string, expectNws []string) { } func getNwResource(c *testing.T, name string) *types.NetworkResource { - out, _ := dockerCmd(c, "network", "inspect", name) + out := cli.DockerCmd(c, "network", "inspect", name).Stdout() var nr []types.NetworkResource err := json.Unmarshal([]byte(out), &nr) assert.NilError(c, err) @@ -281,29 +281,28 @@ func (s *DockerNetworkSuite) TestDockerNetworkLsDefault(c *testing.T) { func (s *DockerNetworkSuite) TestDockerNetworkCreatePredefined(c *testing.T) { predefined := []string{"bridge", "host", "none", "default"} - for _, net := range predefined { + for _, nw := range predefined { // predefined networks can't be created again - out, _, err := dockerCmdWithError("network", "create", net) + out, _, err := dockerCmdWithError("network", "create", nw) assert.ErrorContains(c, err, "", out) } } func (s *DockerNetworkSuite) TestDockerNetworkCreateHostBind(c *testing.T) { - dockerCmd(c, "network", "create", "--subnet=192.168.10.0/24", "--gateway=192.168.10.1", "-o", "com.docker.network.bridge.host_binding_ipv4=192.168.10.1", "testbind") + cli.DockerCmd(c, "network", "create", "--subnet=192.168.10.0/24", "--gateway=192.168.10.1", "-o", "com.docker.network.bridge.host_binding_ipv4=192.168.10.1", "testbind") assertNwIsAvailable(c, "testbind") - out := runSleepingContainer(c, "--net=testbind", "-p", "5000:5000") - id := strings.TrimSpace(out) - assert.NilError(c, waitRun(id)) - out, _ = dockerCmd(c, "ps") + id := runSleepingContainer(c, "--net=testbind", "-p", "5000:5000") + cli.WaitRun(c, id) + out := cli.DockerCmd(c, "ps").Stdout() assert.Assert(c, strings.Contains(out, "192.168.10.1:5000->5000/tcp")) } func (s *DockerNetworkSuite) TestDockerNetworkRmPredefined(c *testing.T) { predefined := []string{"bridge", "host", "none", "default"} - for _, net := range predefined { + for _, nw := range predefined { // predefined networks can't be removed - out, _, err := dockerCmdWithError("network", "rm", net) + out, _, err := dockerCmdWithError("network", "rm", nw) assert.ErrorContains(c, err, "", out) } } @@ -314,62 +313,62 @@ func (s *DockerNetworkSuite) TestDockerNetworkLsFilter(c *testing.T) { testNet := "testnet1" testLabel := "foo" testValue := "bar" - out, _ := dockerCmd(c, "network", "create", "dev") + out := cli.DockerCmd(c, "network", "create", "dev").Stdout() defer func() { - dockerCmd(c, "network", "rm", "dev") - dockerCmd(c, "network", "rm", testNet) + cli.DockerCmd(c, "network", "rm", "dev") + cli.DockerCmd(c, "network", "rm", testNet) }() networkID := strings.TrimSpace(out) // filter with partial ID // only show 'dev' network - out, _ = dockerCmd(c, "network", "ls", "-f", "id="+networkID[0:5]) + out = cli.DockerCmd(c, "network", "ls", "-f", "id="+networkID[0:5]).Stdout() assertNwList(c, out, []string{"dev"}) - out, _ = dockerCmd(c, "network", "ls", "-f", "name=dge") + out = cli.DockerCmd(c, "network", "ls", "-f", "name=dge").Stdout() assertNwList(c, out, []string{"bridge"}) // only show built-in network (bridge, none, host) - out, _ = dockerCmd(c, "network", "ls", "-f", "type=builtin") + out = cli.DockerCmd(c, "network", "ls", "-f", "type=builtin").Stdout() assertNwList(c, out, []string{"bridge", "host", "none"}) // only show custom networks (dev) - out, _ = dockerCmd(c, "network", "ls", "-f", "type=custom") + out = cli.DockerCmd(c, "network", "ls", "-f", "type=custom").Stdout() assertNwList(c, out, []string{"dev"}) // show all networks with filter // it should be equivalent of ls without option - out, _ = dockerCmd(c, "network", "ls", "-f", "type=custom", "-f", "type=builtin") + out = cli.DockerCmd(c, "network", "ls", "-f", "type=custom", "-f", "type=builtin").Stdout() assertNwList(c, out, []string{"bridge", "dev", "host", "none"}) - dockerCmd(c, "network", "create", "--label", testLabel+"="+testValue, testNet) + cli.DockerCmd(c, "network", "create", "--label", testLabel+"="+testValue, testNet) assertNwIsAvailable(c, testNet) - out, _ = dockerCmd(c, "network", "ls", "-f", "label="+testLabel) + out = cli.DockerCmd(c, "network", "ls", "-f", "label="+testLabel).Stdout() assertNwList(c, out, []string{testNet}) - out, _ = dockerCmd(c, "network", "ls", "-f", "label="+testLabel+"="+testValue) + out = cli.DockerCmd(c, "network", "ls", "-f", "label="+testLabel+"="+testValue).Stdout() assertNwList(c, out, []string{testNet}) - out, _ = dockerCmd(c, "network", "ls", "-f", "label=nonexistent") + out = cli.DockerCmd(c, "network", "ls", "-f", "label=nonexistent").Stdout() outArr := strings.Split(strings.TrimSpace(out), "\n") assert.Equal(c, len(outArr), 1, fmt.Sprintf("%s\n", out)) - out, _ = dockerCmd(c, "network", "ls", "-f", "driver=null") + out = cli.DockerCmd(c, "network", "ls", "-f", "driver=null").Stdout() assertNwList(c, out, []string{"none"}) - out, _ = dockerCmd(c, "network", "ls", "-f", "driver=host") + out = cli.DockerCmd(c, "network", "ls", "-f", "driver=host").Stdout() assertNwList(c, out, []string{"host"}) - out, _ = dockerCmd(c, "network", "ls", "-f", "driver=bridge") + out = cli.DockerCmd(c, "network", "ls", "-f", "driver=bridge").Stdout() assertNwList(c, out, []string{"bridge", "dev", testNet}) } func (s *DockerNetworkSuite) TestDockerNetworkCreateDelete(c *testing.T) { - dockerCmd(c, "network", "create", "test") + cli.DockerCmd(c, "network", "create", "test") assertNwIsAvailable(c, "test") - dockerCmd(c, "network", "rm", "test") + cli.DockerCmd(c, "network", "rm", "test") assertNwNotAvailable(c, "test") } @@ -378,14 +377,14 @@ func (s *DockerNetworkSuite) TestDockerNetworkCreateLabel(c *testing.T) { testLabel := "foo" testValue := "bar" - dockerCmd(c, "network", "create", "--label", testLabel+"="+testValue, testNet) + cli.DockerCmd(c, "network", "create", "--label", testLabel+"="+testValue, testNet) assertNwIsAvailable(c, testNet) out, _, err := dockerCmdWithError("network", "inspect", "--format={{ .Labels."+testLabel+" }}", testNet) assert.NilError(c, err) assert.Equal(c, strings.TrimSpace(out), testValue) - dockerCmd(c, "network", "rm", testNet) + cli.DockerCmd(c, "network", "rm", testNet) assertNwNotAvailable(c, testNet) } @@ -395,15 +394,15 @@ func (s *DockerCLINetworkSuite) TestDockerNetworkDeleteNotExists(c *testing.T) { } func (s *DockerCLINetworkSuite) TestDockerNetworkDeleteMultiple(c *testing.T) { - dockerCmd(c, "network", "create", "testDelMulti0") + cli.DockerCmd(c, "network", "create", "testDelMulti0") assertNwIsAvailable(c, "testDelMulti0") - dockerCmd(c, "network", "create", "testDelMulti1") + cli.DockerCmd(c, "network", "create", "testDelMulti1") assertNwIsAvailable(c, "testDelMulti1") - dockerCmd(c, "network", "create", "testDelMulti2") + cli.DockerCmd(c, "network", "create", "testDelMulti2") assertNwIsAvailable(c, "testDelMulti2") - out, _ := dockerCmd(c, "run", "-d", "--net", "testDelMulti2", "busybox", "top") + out := cli.DockerCmd(c, "run", "-d", "--net", "testDelMulti2", "busybox", "top").Stdout() containerID := strings.TrimSpace(out) - waitRun(containerID) + cli.WaitRun(c, containerID) // delete three networks at the same time, since testDelMulti2 // contains active container, its deletion should fail. @@ -419,24 +418,24 @@ func (s *DockerCLINetworkSuite) TestDockerNetworkDeleteMultiple(c *testing.T) { } func (s *DockerCLINetworkSuite) TestDockerNetworkInspect(c *testing.T) { - out, _ := dockerCmd(c, "network", "inspect", "host") + out := cli.DockerCmd(c, "network", "inspect", "host").Stdout() var networkResources []types.NetworkResource err := json.Unmarshal([]byte(out), &networkResources) assert.NilError(c, err) assert.Equal(c, len(networkResources), 1) - out, _ = dockerCmd(c, "network", "inspect", "--format={{ .Name }}", "host") + out = cli.DockerCmd(c, "network", "inspect", "--format={{ .Name }}", "host").Stdout() assert.Equal(c, strings.TrimSpace(out), "host") } func (s *DockerCLINetworkSuite) TestDockerNetworkInspectWithID(c *testing.T) { - out, _ := dockerCmd(c, "network", "create", "test2") + out := cli.DockerCmd(c, "network", "create", "test2").Stdout() networkID := strings.TrimSpace(out) assertNwIsAvailable(c, "test2") - out, _ = dockerCmd(c, "network", "inspect", "--format={{ .Id }}", "test2") + out = cli.DockerCmd(c, "network", "inspect", "--format={{ .Id }}", "test2").Stdout() assert.Equal(c, strings.TrimSpace(out), networkID) - out, _ = dockerCmd(c, "network", "inspect", "--format={{ .ID }}", "test2") + out = cli.DockerCmd(c, "network", "inspect", "--format={{ .ID }}", "test2").Stdout() assert.Equal(c, strings.TrimSpace(out), networkID) } @@ -490,22 +489,22 @@ func (s *DockerCLINetworkSuite) TestDockerInspectMultipleNetworksIncludingNonexi } func (s *DockerCLINetworkSuite) TestDockerInspectNetworkWithContainerName(c *testing.T) { - dockerCmd(c, "network", "create", "brNetForInspect") + cli.DockerCmd(c, "network", "create", "brNetForInspect") assertNwIsAvailable(c, "brNetForInspect") defer func() { - dockerCmd(c, "network", "rm", "brNetForInspect") + cli.DockerCmd(c, "network", "rm", "brNetForInspect") assertNwNotAvailable(c, "brNetForInspect") }() - out, _ := dockerCmd(c, "run", "-d", "--name", "testNetInspect1", "--net", "brNetForInspect", "busybox", "top") - assert.Assert(c, waitRun("testNetInspect1") == nil) + out := cli.DockerCmd(c, "run", "-d", "--name", "testNetInspect1", "--net", "brNetForInspect", "busybox", "top").Stdout() + cli.WaitRun(c, "testNetInspect1") containerID := strings.TrimSpace(out) defer func() { // we don't stop container by name, because we'll rename it later - dockerCmd(c, "stop", containerID) + cli.DockerCmd(c, "stop", containerID) }() - out, _ = dockerCmd(c, "network", "inspect", "brNetForInspect") + out = cli.DockerCmd(c, "network", "inspect", "brNetForInspect").Stdout() var networkResources []types.NetworkResource err := json.Unmarshal([]byte(out), &networkResources) assert.NilError(c, err) @@ -516,10 +515,10 @@ func (s *DockerCLINetworkSuite) TestDockerInspectNetworkWithContainerName(c *tes // rename container and check docker inspect output update newName := "HappyNewName" - dockerCmd(c, "rename", "testNetInspect1", newName) + cli.DockerCmd(c, "rename", "testNetInspect1", newName) // check whether network inspect works properly - out, _ = dockerCmd(c, "network", "inspect", "brNetForInspect") + out = cli.DockerCmd(c, "network", "inspect", "brNetForInspect").Stdout() var newNetRes []types.NetworkResource err = json.Unmarshal([]byte(out), &newNetRes) assert.NilError(c, err) @@ -530,7 +529,7 @@ func (s *DockerCLINetworkSuite) TestDockerInspectNetworkWithContainerName(c *tes } func (s *DockerNetworkSuite) TestDockerNetworkConnectDisconnect(c *testing.T) { - dockerCmd(c, "network", "create", "test") + cli.DockerCmd(c, "network", "create", "test") assertNwIsAvailable(c, "test") nr := getNwResource(c, "test") @@ -538,12 +537,12 @@ func (s *DockerNetworkSuite) TestDockerNetworkConnectDisconnect(c *testing.T) { assert.Equal(c, len(nr.Containers), 0) // run a container - out, _ := dockerCmd(c, "run", "-d", "--name", "test", "busybox", "top") - assert.Assert(c, waitRun("test") == nil) + out := cli.DockerCmd(c, "run", "-d", "--name", "test", "busybox", "top").Stdout() + cli.WaitRun(c, "test") containerID := strings.TrimSpace(out) // connect the container to the test network - dockerCmd(c, "network", "connect", "test", containerID) + cli.DockerCmd(c, "network", "connect", "test", containerID) // inspect the network to make sure container is connected nr = getNetworkResource(c, nr.ID) @@ -556,14 +555,14 @@ func (s *DockerNetworkSuite) TestDockerNetworkConnectDisconnect(c *testing.T) { assert.Equal(c, ip.String(), containerIP) // disconnect container from the network - dockerCmd(c, "network", "disconnect", "test", containerID) + cli.DockerCmd(c, "network", "disconnect", "test", containerID) nr = getNwResource(c, "test") assert.Equal(c, nr.Name, "test") assert.Equal(c, len(nr.Containers), 0) // run another container - out, _ = dockerCmd(c, "run", "-d", "--net", "test", "--name", "test2", "busybox", "top") - assert.Assert(c, waitRun("test2") == nil) + out = cli.DockerCmd(c, "run", "-d", "--net", "test", "--name", "test2", "busybox", "top").Stdout() + cli.WaitRun(c, "test2") containerID = strings.TrimSpace(out) nr = getNwResource(c, "test") @@ -571,43 +570,43 @@ func (s *DockerNetworkSuite) TestDockerNetworkConnectDisconnect(c *testing.T) { assert.Equal(c, len(nr.Containers), 1) // force disconnect the container to the test network - dockerCmd(c, "network", "disconnect", "-f", "test", containerID) + cli.DockerCmd(c, "network", "disconnect", "-f", "test", containerID) nr = getNwResource(c, "test") assert.Equal(c, nr.Name, "test") assert.Equal(c, len(nr.Containers), 0) - dockerCmd(c, "network", "rm", "test") + cli.DockerCmd(c, "network", "rm", "test") assertNwNotAvailable(c, "test") } func (s *DockerNetworkSuite) TestDockerNetworkIPAMMultipleNetworks(c *testing.T) { testRequires(c, testEnv.IsLocalDaemon) // test0 bridge network - dockerCmd(c, "network", "create", "--subnet=192.168.0.0/16", "test1") + cli.DockerCmd(c, "network", "create", "--subnet=192.168.0.0/16", "test1") assertNwIsAvailable(c, "test1") // test2 bridge network does not overlap - dockerCmd(c, "network", "create", "--subnet=192.169.0.0/16", "test2") + cli.DockerCmd(c, "network", "create", "--subnet=192.169.0.0/16", "test2") assertNwIsAvailable(c, "test2") // for networks w/o ipam specified, docker will choose proper non-overlapping subnets - dockerCmd(c, "network", "create", "test3") + cli.DockerCmd(c, "network", "create", "test3") assertNwIsAvailable(c, "test3") - dockerCmd(c, "network", "create", "test4") + cli.DockerCmd(c, "network", "create", "test4") assertNwIsAvailable(c, "test4") - dockerCmd(c, "network", "create", "test5") + cli.DockerCmd(c, "network", "create", "test5") assertNwIsAvailable(c, "test5") // test network with multiple subnets // bridge network doesn't support multiple subnets. hence, use a dummy driver that supports - dockerCmd(c, "network", "create", "-d", dummyNetworkDriver, "--subnet=192.170.0.0/16", "--subnet=192.171.0.0/16", "test6") + cli.DockerCmd(c, "network", "create", "-d", dummyNetworkDriver, "--subnet=192.170.0.0/16", "--subnet=192.171.0.0/16", "test6") assertNwIsAvailable(c, "test6") // test network with multiple subnets with valid ipam combinations // also check same subnet across networks when the driver supports it. - dockerCmd(c, "network", "create", "-d", dummyNetworkDriver, + cli.DockerCmd(c, "network", "create", "-d", dummyNetworkDriver, "--subnet=192.172.0.0/16", "--subnet=192.173.0.0/16", "--gateway=192.172.0.100", "--gateway=192.173.0.100", "--ip-range=192.172.1.0/24", @@ -618,14 +617,14 @@ func (s *DockerNetworkSuite) TestDockerNetworkIPAMMultipleNetworks(c *testing.T) // cleanup for i := 1; i < 8; i++ { - dockerCmd(c, "network", "rm", fmt.Sprintf("test%d", i)) + cli.DockerCmd(c, "network", "rm", fmt.Sprintf("test%d", i)) } } func (s *DockerNetworkSuite) TestDockerNetworkCustomIPAM(c *testing.T) { testRequires(c, testEnv.IsLocalDaemon) // Create a bridge network using custom ipam driver - dockerCmd(c, "network", "create", "--ipam-driver", dummyIPAMDriver, "br0") + cli.DockerCmd(c, "network", "create", "--ipam-driver", dummyIPAMDriver, "br0") assertNwIsAvailable(c, "br0") // Verify expected network ipam fields are there @@ -634,14 +633,14 @@ func (s *DockerNetworkSuite) TestDockerNetworkCustomIPAM(c *testing.T) { assert.Equal(c, nr.IPAM.Driver, dummyIPAMDriver) // remove network and exercise remote ipam driver - dockerCmd(c, "network", "rm", "br0") + cli.DockerCmd(c, "network", "rm", "br0") assertNwNotAvailable(c, "br0") } func (s *DockerNetworkSuite) TestDockerNetworkIPAMOptions(c *testing.T) { testRequires(c, testEnv.IsLocalDaemon) // Create a bridge network using custom ipam driver and options - dockerCmd(c, "network", "create", "--ipam-driver", dummyIPAMDriver, "--ipam-opt", "opt1=drv1", "--ipam-opt", "opt2=drv2", "br0") + cli.DockerCmd(c, "network", "create", "--ipam-driver", dummyIPAMDriver, "--ipam-opt", "opt1=drv1", "--ipam-opt", "opt2=drv2", "br0") assertNwIsAvailable(c, "br0") // Verify expected network ipam options @@ -695,7 +694,7 @@ func (s *DockerNetworkSuite) TestDockerNetworkInspectDefault(c *testing.T) { func (s *DockerNetworkSuite) TestDockerNetworkInspectCustomUnspecified(c *testing.T) { // if unspecified, network subnet will be selected from inside preferred pool - dockerCmd(c, "network", "create", "test01") + cli.DockerCmd(c, "network", "create", "test01") assertNwIsAvailable(c, "test01") nr := getNetworkResource(c, "test01") @@ -706,12 +705,12 @@ func (s *DockerNetworkSuite) TestDockerNetworkInspectCustomUnspecified(c *testin assert.Equal(c, nr.IPAM.Driver, "default") assert.Equal(c, len(nr.IPAM.Config), 1) - dockerCmd(c, "network", "rm", "test01") + cli.DockerCmd(c, "network", "rm", "test01") assertNwNotAvailable(c, "test01") } func (s *DockerNetworkSuite) TestDockerNetworkInspectCustomSpecified(c *testing.T) { - dockerCmd(c, "network", "create", "--driver=bridge", "--ipv6", "--subnet=fd80:24e2:f998:72d6::/64", "--subnet=172.28.0.0/16", "--ip-range=172.28.5.0/24", "--gateway=172.28.5.254", "br0") + cli.DockerCmd(c, "network", "create", "--driver=bridge", "--ipv6", "--subnet=fd80:24e2:f998:72d6::/64", "--subnet=172.28.0.0/16", "--ip-range=172.28.5.0/24", "--gateway=172.28.5.254", "br0") assertNwIsAvailable(c, "br0") nr := getNetworkResource(c, "br0") @@ -725,7 +724,7 @@ func (s *DockerNetworkSuite) TestDockerNetworkInspectCustomSpecified(c *testing. assert.Equal(c, nr.IPAM.Config[0].IPRange, "172.28.5.0/24") assert.Equal(c, nr.IPAM.Config[0].Gateway, "172.28.5.254") assert.Equal(c, nr.Internal, false) - dockerCmd(c, "network", "rm", "br0") + cli.DockerCmd(c, "network", "rm", "br0") assertNwNotAvailable(c, "br0") } @@ -744,18 +743,18 @@ func (s *DockerNetworkSuite) TestDockerNetworkIPAMInvalidCombinations(c *testing // overlapping subnets across networks must fail // create a valid test0 network - dockerCmd(c, "network", "create", "--subnet=192.168.0.0/16", "test0") + cli.DockerCmd(c, "network", "create", "--subnet=192.168.0.0/16", "test0") assertNwIsAvailable(c, "test0") // create an overlapping test1 network _, _, err = dockerCmdWithError("network", "create", "--subnet=192.168.128.0/17", "test1") assert.ErrorContains(c, err, "") - dockerCmd(c, "network", "rm", "test0") + cli.DockerCmd(c, "network", "rm", "test0") assertNwNotAvailable(c, "test0") } func (s *DockerNetworkSuite) TestDockerNetworkDriverOptions(c *testing.T) { testRequires(c, testEnv.IsLocalDaemon) - dockerCmd(c, "network", "create", "-d", dummyNetworkDriver, "-o", "opt1=drv1", "-o", "opt2=drv2", "testopt") + cli.DockerCmd(c, "network", "create", "-d", dummyNetworkDriver, "-o", "opt1=drv1", "-o", "opt2=drv2", "testopt") assertNwIsAvailable(c, "testopt") gopts := remoteDriverNetworkRequest.Options[netlabel.GenericData] assert.Assert(c, gopts != nil) @@ -763,7 +762,7 @@ func (s *DockerNetworkSuite) TestDockerNetworkDriverOptions(c *testing.T) { assert.Equal(c, ok, true) assert.Equal(c, opts["opt1"], "drv1") assert.Equal(c, opts["opt2"], "drv2") - dockerCmd(c, "network", "rm", "testopt") + cli.DockerCmd(c, "network", "rm", "testopt") assertNwNotAvailable(c, "testopt") } @@ -783,9 +782,9 @@ func (s *DockerNetworkSuite) TestDockerPluginV2NetworkDriver(c *testing.T) { assert.Assert(c, strings.Contains(out, npName)) assert.Assert(c, strings.Contains(out, npTag)) assert.Assert(c, strings.Contains(out, "true")) - dockerCmd(c, "network", "create", "-d", npNameWithTag, "v2net") + cli.DockerCmd(c, "network", "create", "-d", npNameWithTag, "v2net") assertNwIsAvailable(c, "v2net") - dockerCmd(c, "network", "rm", "v2net") + cli.DockerCmd(c, "network", "rm", "v2net") assertNwNotAvailable(c, "v2net") } @@ -848,16 +847,16 @@ func (s *DockerNetworkSuite) TestDockerNetworkAnonymousEndpoint(c *testing.T) { cstmBridgeNw := "custom-bridge-nw" cstmBridgeNw1 := "custom-bridge-nw1" - dockerCmd(c, "network", "create", "-d", "bridge", cstmBridgeNw) + cli.DockerCmd(c, "network", "create", "-d", "bridge", cstmBridgeNw) assertNwIsAvailable(c, cstmBridgeNw) // run two anonymous containers and store their etc/hosts content - out, _ := dockerCmd(c, "run", "-d", "--net", cstmBridgeNw, "busybox", "top") + out := cli.DockerCmd(c, "run", "-d", "--net", cstmBridgeNw, "busybox", "top").Stdout() cid1 := strings.TrimSpace(out) hosts1 := readContainerFileWithExec(c, cid1, hostsFile) - out, _ = dockerCmd(c, "run", "-d", "--net", cstmBridgeNw, "busybox", "top") + out = cli.DockerCmd(c, "run", "-d", "--net", cstmBridgeNw, "busybox", "top").Stdout() cid2 := strings.TrimSpace(out) // verify first container etc/hosts file has not changed @@ -865,25 +864,25 @@ func (s *DockerNetworkSuite) TestDockerNetworkAnonymousEndpoint(c *testing.T) { assert.Equal(c, string(hosts1), string(hosts1post), fmt.Sprintf("Unexpected %s change on anonymous container creation", hostsFile)) // Connect the 2nd container to a new network and verify the // first container /etc/hosts file still hasn't changed. - dockerCmd(c, "network", "create", "-d", "bridge", cstmBridgeNw1) + cli.DockerCmd(c, "network", "create", "-d", "bridge", cstmBridgeNw1) assertNwIsAvailable(c, cstmBridgeNw1) - dockerCmd(c, "network", "connect", cstmBridgeNw1, cid2) + cli.DockerCmd(c, "network", "connect", cstmBridgeNw1, cid2) hosts2 := readContainerFileWithExec(c, cid2, hostsFile) hosts1post = readContainerFileWithExec(c, cid1, hostsFile) assert.Equal(c, string(hosts1), string(hosts1post), fmt.Sprintf("Unexpected %s change on container connect", hostsFile)) // start a named container cName := "AnyName" - out, _ = dockerCmd(c, "run", "-d", "--net", cstmBridgeNw, "--name", cName, "busybox", "top") + out = cli.DockerCmd(c, "run", "-d", "--net", cstmBridgeNw, "--name", cName, "busybox", "top").Stdout() cid3 := strings.TrimSpace(out) // verify that container 1 and 2 can ping the named container - dockerCmd(c, "exec", cid1, "ping", "-c", "1", cName) - dockerCmd(c, "exec", cid2, "ping", "-c", "1", cName) + cli.DockerCmd(c, "exec", cid1, "ping", "-c", "1", cName) + cli.DockerCmd(c, "exec", cid2, "ping", "-c", "1", cName) // Stop named container and verify first two containers' etc/hosts file hasn't changed - dockerCmd(c, "stop", cid3) + cli.DockerCmd(c, "stop", cid3) hosts1post = readContainerFileWithExec(c, cid1, hostsFile) assert.Equal(c, string(hosts1), string(hosts1post), fmt.Sprintf("Unexpected %s change on name container creation", hostsFile)) hosts2post := readContainerFileWithExec(c, cid2, hostsFile) @@ -902,23 +901,23 @@ func (s *DockerNetworkSuite) TestDockerNetworkLinkOnDefaultNetworkOnly(c *testin network := "anotherbridge" // Run first container on default network - dockerCmd(c, "run", "-d", "--name", cnt1, "busybox", "top") + cli.DockerCmd(c, "run", "-d", "--name", cnt1, "busybox", "top") // Create another network and run the second container on it - dockerCmd(c, "network", "create", network) + cli.DockerCmd(c, "network", "create", network) assertNwIsAvailable(c, network) - dockerCmd(c, "run", "-d", "--net", network, "--name", cnt2, "busybox", "top") + cli.DockerCmd(c, "run", "-d", "--net", network, "--name", cnt2, "busybox", "top") // Try launching a container on default network, linking to the first container. Must succeed - dockerCmd(c, "run", "-d", "--link", fmt.Sprintf("%s:%s", cnt1, cnt1), "busybox", "top") + cli.DockerCmd(c, "run", "-d", "--link", fmt.Sprintf("%s:%s", cnt1, cnt1), "busybox", "top") // Try launching a container on default network, linking to the second container. Must fail _, _, err := dockerCmdWithError("run", "-d", "--link", fmt.Sprintf("%s:%s", cnt2, cnt2), "busybox", "top") assert.ErrorContains(c, err, "") // Connect second container to default network. Now a container on default network can link to it - dockerCmd(c, "network", "connect", "bridge", cnt2) - dockerCmd(c, "run", "-d", "--link", fmt.Sprintf("%s:%s", cnt2, cnt2), "busybox", "top") + cli.DockerCmd(c, "network", "connect", "bridge", cnt2) + cli.DockerCmd(c, "run", "-d", "--link", fmt.Sprintf("%s:%s", cnt2, cnt2), "busybox", "top") } func (s *DockerNetworkSuite) TestDockerNetworkOverlayPortMapping(c *testing.T) { @@ -933,15 +932,15 @@ func (s *DockerNetworkSuite) TestDockerNetworkOverlayPortMapping(c *testing.T) { expose1 := fmt.Sprintf("--expose=%d", port1) expose2 := fmt.Sprintf("--expose=%d", port2) - dockerCmd(c, "network", "create", "-d", dummyNetworkDriver, nwn) + cli.DockerCmd(c, "network", "create", "-d", dummyNetworkDriver, nwn) assertNwIsAvailable(c, nwn) - dockerCmd(c, "run", "-d", "--net", nwn, "--name", ctn, expose1, expose2, "busybox", "top") + cli.DockerCmd(c, "run", "-d", "--net", nwn, "--name", ctn, expose1, expose2, "busybox", "top") // Check docker ps o/p for last created container reports the unpublished ports unpPort1 := fmt.Sprintf("%d/tcp", port1) unpPort2 := fmt.Sprintf("%d/tcp", port2) - out, _ := dockerCmd(c, "ps", "-n=1") + out := cli.DockerCmd(c, "ps", "-n=1").Stdout() // Missing unpublished ports in docker ps output assert.Assert(c, strings.Contains(out, unpPort1)) // Missing unpublished ports in docker ps output @@ -997,24 +996,24 @@ func (s *DockerNetworkSuite) TestDockerNetworkMacInspect(c *testing.T) { nwn := "ov" ctn := "bb" - dockerCmd(c, "network", "create", "-d", dummyNetworkDriver, nwn) + cli.DockerCmd(c, "network", "create", "-d", dummyNetworkDriver, nwn) assertNwIsAvailable(c, nwn) - dockerCmd(c, "run", "-d", "--net", nwn, "--name", ctn, "busybox", "top") + cli.DockerCmd(c, "run", "-d", "--net", nwn, "--name", ctn, "busybox", "top") mac := inspectField(c, ctn, "NetworkSettings.Networks."+nwn+".MacAddress") assert.Equal(c, mac, "a0:b1:c2:d3:e4:f5") } func (s *DockerCLINetworkSuite) TestInspectAPIMultipleNetworks(c *testing.T) { - dockerCmd(c, "network", "create", "mybridge1") - dockerCmd(c, "network", "create", "mybridge2") - out, _ := dockerCmd(c, "run", "-d", "busybox", "top") + cli.DockerCmd(c, "network", "create", "mybridge1") + cli.DockerCmd(c, "network", "create", "mybridge2") + out := cli.DockerCmd(c, "run", "-d", "busybox", "top").Stdout() id := strings.TrimSpace(out) - assert.NilError(c, waitRun(id)) + cli.WaitRun(c, id) - dockerCmd(c, "network", "connect", "mybridge1", id) - dockerCmd(c, "network", "connect", "mybridge2", id) + cli.DockerCmd(c, "network", "connect", "mybridge1", id) + cli.DockerCmd(c, "network", "connect", "mybridge2", id) body := getInspectBody(c, "v1.20", id) var inspect120 v1p20.ContainerJSON @@ -1100,7 +1099,7 @@ func (s *DockerNetworkSuite) TestDockerNetworkMultipleNetworksUngracefulDaemonRe } func (s *DockerNetworkSuite) TestDockerNetworkRunNetByID(c *testing.T) { - out, _ := dockerCmd(c, "network", "create", "one") + out := cli.DockerCmd(c, "network", "create", "one").Stdout() containerOut, _, err := dockerCmdWithError("run", "-d", "--net", strings.TrimSpace(out), "busybox", "top") assert.Assert(c, err == nil, containerOut) } @@ -1133,31 +1132,31 @@ func (s *DockerNetworkSuite) TestDockerNetworkHostModeUngracefulDaemonRestart(c } func (s *DockerNetworkSuite) TestDockerNetworkConnectToHostFromOtherNetwork(c *testing.T) { - dockerCmd(c, "run", "-d", "--name", "container1", "busybox", "top") - assert.Assert(c, waitRun("container1") == nil) - dockerCmd(c, "network", "disconnect", "bridge", "container1") + cli.DockerCmd(c, "run", "-d", "--name", "container1", "busybox", "top") + cli.WaitRun(c, "container1") + cli.DockerCmd(c, "network", "disconnect", "bridge", "container1") out, _, err := dockerCmdWithError("network", "connect", "host", "container1") assert.ErrorContains(c, err, "", out) assert.Assert(c, strings.Contains(out, runconfig.ErrConflictHostNetwork.Error())) } func (s *DockerNetworkSuite) TestDockerNetworkDisconnectFromHost(c *testing.T) { - dockerCmd(c, "run", "-d", "--name", "container1", "--net=host", "busybox", "top") - assert.Assert(c, waitRun("container1") == nil) + cli.DockerCmd(c, "run", "-d", "--name", "container1", "--net=host", "busybox", "top") + cli.WaitRun(c, "container1") out, _, err := dockerCmdWithError("network", "disconnect", "host", "container1") assert.Assert(c, err != nil, "Should err out disconnect from host") assert.Assert(c, strings.Contains(out, runconfig.ErrConflictHostNetwork.Error())) } func (s *DockerNetworkSuite) TestDockerNetworkConnectWithPortMapping(c *testing.T) { - dockerCmd(c, "network", "create", "test1") - dockerCmd(c, "run", "-d", "--name", "c1", "-p", "5000:5000", "busybox", "top") - assert.Assert(c, waitRun("c1") == nil) - dockerCmd(c, "network", "connect", "test1", "c1") + cli.DockerCmd(c, "network", "create", "test1") + cli.DockerCmd(c, "run", "-d", "--name", "c1", "-p", "5000:5000", "busybox", "top") + cli.WaitRun(c, "c1") + cli.DockerCmd(c, "network", "connect", "test1", "c1") } func verifyPortMap(c *testing.T, container, port, originalMapping string, mustBeEqual bool) { - currentMapping, _ := dockerCmd(c, "port", container, port) + currentMapping := cli.DockerCmd(c, "port", container, port).Stdout() if mustBeEqual { assert.Equal(c, currentMapping, originalMapping) } else { @@ -1171,60 +1170,60 @@ func (s *DockerNetworkSuite) TestDockerNetworkConnectDisconnectWithPortMapping(c // the container default gateway to change, and verify docker port cmd // returns congruent information cnt := "c1" - dockerCmd(c, "network", "create", "aaa") - dockerCmd(c, "network", "create", "ccc") + cli.DockerCmd(c, "network", "create", "aaa") + cli.DockerCmd(c, "network", "create", "ccc") - dockerCmd(c, "run", "-d", "--name", cnt, "-p", "9000:90", "-p", "70", "busybox", "top") - assert.Assert(c, waitRun(cnt) == nil) - curPortMap, _ := dockerCmd(c, "port", cnt, "70") - curExplPortMap, _ := dockerCmd(c, "port", cnt, "90") + cli.DockerCmd(c, "run", "-d", "--name", cnt, "-p", "9000:90", "-p", "70", "busybox", "top") + cli.WaitRun(c, cnt) + curPortMap := cli.DockerCmd(c, "port", cnt, "70").Stdout() + curExplPortMap := cli.DockerCmd(c, "port", cnt, "90").Stdout() // Connect to a network which causes the container's default gw switch - dockerCmd(c, "network", "connect", "aaa", cnt) + cli.DockerCmd(c, "network", "connect", "aaa", cnt) verifyPortMap(c, cnt, "70", curPortMap, false) verifyPortMap(c, cnt, "90", curExplPortMap, true) // Read current mapping - curPortMap, _ = dockerCmd(c, "port", cnt, "70") + curPortMap = cli.DockerCmd(c, "port", cnt, "70").Stdout() // Disconnect from a network which causes the container's default gw switch - dockerCmd(c, "network", "disconnect", "aaa", cnt) + cli.DockerCmd(c, "network", "disconnect", "aaa", cnt) verifyPortMap(c, cnt, "70", curPortMap, false) verifyPortMap(c, cnt, "90", curExplPortMap, true) // Read current mapping - curPortMap, _ = dockerCmd(c, "port", cnt, "70") + curPortMap = cli.DockerCmd(c, "port", cnt, "70").Stdout() // Connect to a network which does not cause the container's default gw switch - dockerCmd(c, "network", "connect", "ccc", cnt) + cli.DockerCmd(c, "network", "connect", "ccc", cnt) verifyPortMap(c, cnt, "70", curPortMap, true) verifyPortMap(c, cnt, "90", curExplPortMap, true) } func (s *DockerNetworkSuite) TestDockerNetworkConnectWithMac(c *testing.T) { macAddress := "02:42:ac:11:00:02" - dockerCmd(c, "network", "create", "mynetwork") - dockerCmd(c, "run", "--name=test", "-d", "--mac-address", macAddress, "busybox", "top") - assert.Assert(c, waitRun("test") == nil) + cli.DockerCmd(c, "network", "create", "mynetwork") + cli.DockerCmd(c, "run", "--name=test", "-d", "--mac-address", macAddress, "busybox", "top") + cli.WaitRun(c, "test") mac1 := inspectField(c, "test", "NetworkSettings.Networks.bridge.MacAddress") assert.Equal(c, strings.TrimSpace(mac1), macAddress) - dockerCmd(c, "network", "connect", "mynetwork", "test") + cli.DockerCmd(c, "network", "connect", "mynetwork", "test") mac2 := inspectField(c, "test", "NetworkSettings.Networks.mynetwork.MacAddress") assert.Assert(c, strings.TrimSpace(mac2) != strings.TrimSpace(mac1)) } func (s *DockerNetworkSuite) TestDockerNetworkInspectCreatedContainer(c *testing.T) { - dockerCmd(c, "create", "--name", "test", "busybox") + cli.DockerCmd(c, "create", "--name", "test", "busybox") networks := inspectField(c, "test", "NetworkSettings.Networks") assert.Assert(c, strings.Contains(networks, "bridge"), "Should return 'bridge' network") } func (s *DockerNetworkSuite) TestDockerNetworkRestartWithMultipleNetworks(c *testing.T) { - dockerCmd(c, "network", "create", "test") - dockerCmd(c, "run", "--name=foo", "-d", "busybox", "top") - assert.Assert(c, waitRun("foo") == nil) - dockerCmd(c, "network", "connect", "test", "foo") - dockerCmd(c, "restart", "foo") + cli.DockerCmd(c, "network", "create", "test") + cli.DockerCmd(c, "run", "--name=foo", "-d", "busybox", "top") + cli.WaitRun(c, "foo") + cli.DockerCmd(c, "network", "connect", "test", "foo") + cli.DockerCmd(c, "restart", "foo") networks := inspectField(c, "foo", "NetworkSettings.Networks") assert.Assert(c, strings.Contains(networks, "bridge"), "Should contain 'bridge' network") assert.Assert(c, strings.Contains(networks, "test"), "Should contain 'test' network") @@ -1232,9 +1231,9 @@ func (s *DockerNetworkSuite) TestDockerNetworkRestartWithMultipleNetworks(c *tes func (s *DockerNetworkSuite) TestDockerNetworkConnectDisconnectToStoppedContainer(c *testing.T) { testRequires(c, testEnv.IsLocalDaemon) - dockerCmd(c, "network", "create", "test") - dockerCmd(c, "create", "--name=foo", "busybox", "top") - dockerCmd(c, "network", "connect", "test", "foo") + cli.DockerCmd(c, "network", "create", "test") + cli.DockerCmd(c, "create", "--name=foo", "busybox", "top") + cli.DockerCmd(c, "network", "connect", "test", "foo") networks := inspectField(c, "foo", "NetworkSettings.Networks") assert.Assert(c, strings.Contains(networks, "test"), "Should contain 'test' network") // Restart docker daemon to test the config has persisted to disk @@ -1242,16 +1241,16 @@ func (s *DockerNetworkSuite) TestDockerNetworkConnectDisconnectToStoppedContaine networks = inspectField(c, "foo", "NetworkSettings.Networks") assert.Assert(c, strings.Contains(networks, "test"), "Should contain 'test' network") // start the container and test if we can ping it from another container in the same network - dockerCmd(c, "start", "foo") - assert.Assert(c, waitRun("foo") == nil) + cli.DockerCmd(c, "start", "foo") + cli.WaitRun(c, "foo") ip := inspectField(c, "foo", "NetworkSettings.Networks.test.IPAddress") ip = strings.TrimSpace(ip) - dockerCmd(c, "run", "--net=test", "busybox", "sh", "-c", fmt.Sprintf("ping -c 1 %s", ip)) + cli.DockerCmd(c, "run", "--net=test", "busybox", "sh", "-c", fmt.Sprintf("ping -c 1 %s", ip)) - dockerCmd(c, "stop", "foo") + cli.DockerCmd(c, "stop", "foo") // Test disconnect - dockerCmd(c, "network", "disconnect", "test", "foo") + cli.DockerCmd(c, "network", "disconnect", "test", "foo") networks = inspectField(c, "foo", "NetworkSettings.Networks") assert.Assert(c, !strings.Contains(networks, "test"), "Should not contain 'test' network") // Restart docker daemon to test the config has persisted to disk @@ -1261,42 +1260,42 @@ func (s *DockerNetworkSuite) TestDockerNetworkConnectDisconnectToStoppedContaine } func (s *DockerNetworkSuite) TestDockerNetworkDisconnectContainerNonexistingNetwork(c *testing.T) { - dockerCmd(c, "network", "create", "test") - dockerCmd(c, "run", "--net=test", "-d", "--name=foo", "busybox", "top") + cli.DockerCmd(c, "network", "create", "test") + cli.DockerCmd(c, "run", "--net=test", "-d", "--name=foo", "busybox", "top") networks := inspectField(c, "foo", "NetworkSettings.Networks") assert.Assert(c, strings.Contains(networks, "test"), "Should contain 'test' network") // Stop container and remove network - dockerCmd(c, "stop", "foo") - dockerCmd(c, "network", "rm", "test") + cli.DockerCmd(c, "stop", "foo") + cli.DockerCmd(c, "network", "rm", "test") // Test disconnecting stopped container from nonexisting network - dockerCmd(c, "network", "disconnect", "-f", "test", "foo") + cli.DockerCmd(c, "network", "disconnect", "-f", "test", "foo") networks = inspectField(c, "foo", "NetworkSettings.Networks") assert.Assert(c, !strings.Contains(networks, "test"), "Should not contain 'test' network") } func (s *DockerNetworkSuite) TestDockerNetworkConnectPreferredIP(c *testing.T) { // create two networks - dockerCmd(c, "network", "create", "--ipv6", "--subnet=172.28.0.0/16", "--subnet=2001:db8:1234::/64", "n0") + cli.DockerCmd(c, "network", "create", "--ipv6", "--subnet=172.28.0.0/16", "--subnet=2001:db8:1234::/64", "n0") assertNwIsAvailable(c, "n0") - dockerCmd(c, "network", "create", "--ipv6", "--subnet=172.30.0.0/16", "--ip-range=172.30.5.0/24", "--subnet=2001:db8:abcd::/64", "--ip-range=2001:db8:abcd::/80", "n1") + cli.DockerCmd(c, "network", "create", "--ipv6", "--subnet=172.30.0.0/16", "--ip-range=172.30.5.0/24", "--subnet=2001:db8:abcd::/64", "--ip-range=2001:db8:abcd::/80", "n1") assertNwIsAvailable(c, "n1") // run a container on first network specifying the ip addresses - dockerCmd(c, "run", "-d", "--name", "c0", "--net=n0", "--ip", "172.28.99.88", "--ip6", "2001:db8:1234::9988", "busybox", "top") - assert.Assert(c, waitRun("c0") == nil) + cli.DockerCmd(c, "run", "-d", "--name", "c0", "--net=n0", "--ip", "172.28.99.88", "--ip6", "2001:db8:1234::9988", "busybox", "top") + cli.WaitRun(c, "c0") verifyIPAddressConfig(c, "c0", "n0", "172.28.99.88", "2001:db8:1234::9988") verifyIPAddresses(c, "c0", "n0", "172.28.99.88", "2001:db8:1234::9988") // connect the container to the second network specifying an ip addresses - dockerCmd(c, "network", "connect", "--ip", "172.30.5.44", "--ip6", "2001:db8:abcd::5544", "n1", "c0") + cli.DockerCmd(c, "network", "connect", "--ip", "172.30.5.44", "--ip6", "2001:db8:abcd::5544", "n1", "c0") verifyIPAddressConfig(c, "c0", "n1", "172.30.5.44", "2001:db8:abcd::5544") verifyIPAddresses(c, "c0", "n1", "172.30.5.44", "2001:db8:abcd::5544") // Stop and restart the container - dockerCmd(c, "stop", "c0") - dockerCmd(c, "start", "c0") + cli.DockerCmd(c, "stop", "c0") + cli.DockerCmd(c, "start", "c0") // verify requested addresses are applied and configs are still there verifyIPAddressConfig(c, "c0", "n0", "172.28.99.88", "2001:db8:1234::9988") @@ -1312,24 +1311,24 @@ func (s *DockerNetworkSuite) TestDockerNetworkConnectPreferredIP(c *testing.T) { func (s *DockerNetworkSuite) TestDockerNetworkConnectPreferredIPStoppedContainer(c *testing.T) { // create a container - dockerCmd(c, "create", "--name", "c0", "busybox", "top") + cli.DockerCmd(c, "create", "--name", "c0", "busybox", "top") // create a network - dockerCmd(c, "network", "create", "--ipv6", "--subnet=172.30.0.0/16", "--subnet=2001:db8:abcd::/64", "n0") + cli.DockerCmd(c, "network", "create", "--ipv6", "--subnet=172.30.0.0/16", "--subnet=2001:db8:abcd::/64", "n0") assertNwIsAvailable(c, "n0") // connect the container to the network specifying an ip addresses - dockerCmd(c, "network", "connect", "--ip", "172.30.55.44", "--ip6", "2001:db8:abcd::5544", "n0", "c0") + cli.DockerCmd(c, "network", "connect", "--ip", "172.30.55.44", "--ip6", "2001:db8:abcd::5544", "n0", "c0") verifyIPAddressConfig(c, "c0", "n0", "172.30.55.44", "2001:db8:abcd::5544") // start the container, verify config has not changed and ip addresses are assigned - dockerCmd(c, "start", "c0") - assert.Assert(c, waitRun("c0") == nil) + cli.DockerCmd(c, "start", "c0") + cli.WaitRun(c, "c0") verifyIPAddressConfig(c, "c0", "n0", "172.30.55.44", "2001:db8:abcd::5544") verifyIPAddresses(c, "c0", "n0", "172.30.55.44", "2001:db8:abcd::5544") // stop the container and check ip config has not changed - dockerCmd(c, "stop", "c0") + cli.DockerCmd(c, "stop", "c0") verifyIPAddressConfig(c, "c0", "n0", "172.30.55.44", "2001:db8:abcd::5544") } @@ -1340,7 +1339,7 @@ func (s *DockerNetworkSuite) TestDockerNetworkUnsupportedRequiredIP(c *testing.T } // requested IP is not supported on networks with no user defined subnets - dockerCmd(c, "network", "create", "n0") + cli.DockerCmd(c, "network", "create", "n0") assertNwIsAvailable(c, "n0") out, _, err := dockerCmdWithError("run", "-d", "--ip", "172.28.99.88", "--net", "n0", "busybox", "top") @@ -1349,7 +1348,7 @@ func (s *DockerNetworkSuite) TestDockerNetworkUnsupportedRequiredIP(c *testing.T out, _, err = dockerCmdWithError("run", "-d", "--ip6", "2001:db8:1234::9988", "--net", "n0", "busybox", "top") assert.Assert(c, err != nil, "out: %s", out) assert.Assert(c, strings.Contains(out, runconfig.ErrUnsupportedNetworkNoSubnetAndIP.Error())) - dockerCmd(c, "network", "rm", "n0") + cli.DockerCmd(c, "network", "rm", "n0") assertNwNotAvailable(c, "n0") } @@ -1381,7 +1380,7 @@ func verifyIPAddresses(c *testing.T, cName, nwname, ipv4, ipv6 string) { func (s *DockerNetworkSuite) TestDockerNetworkConnectLinkLocalIP(c *testing.T) { // create one test network - dockerCmd(c, "network", "create", "--ipv6", "--subnet=2001:db8:1234::/64", "n0") + cli.DockerCmd(c, "network", "create", "--ipv6", "--subnet=2001:db8:1234::/64", "n0") assertNwIsAvailable(c, "n0") // run a container with incorrect link-local address @@ -1391,15 +1390,15 @@ func (s *DockerNetworkSuite) TestDockerNetworkConnectLinkLocalIP(c *testing.T) { assert.ErrorContains(c, err, "") // run two containers with link-local ip on the test network - dockerCmd(c, "run", "-d", "--name", "c0", "--net=n0", "--link-local-ip", "169.254.7.7", "--link-local-ip", "fe80::254:77", "busybox", "top") - assert.Assert(c, waitRun("c0") == nil) - dockerCmd(c, "run", "-d", "--name", "c1", "--net=n0", "--link-local-ip", "169.254.8.8", "--link-local-ip", "fe80::254:88", "busybox", "top") - assert.Assert(c, waitRun("c1") == nil) + cli.DockerCmd(c, "run", "-d", "--name", "c0", "--net=n0", "--link-local-ip", "169.254.7.7", "--link-local-ip", "fe80::254:77", "busybox", "top") + cli.WaitRun(c, "c0") + cli.DockerCmd(c, "run", "-d", "--name", "c1", "--net=n0", "--link-local-ip", "169.254.8.8", "--link-local-ip", "fe80::254:88", "busybox", "top") + cli.WaitRun(c, "c1") // run a container on the default network and connect it to the test network specifying a link-local address - dockerCmd(c, "run", "-d", "--name", "c2", "busybox", "top") - assert.Assert(c, waitRun("c2") == nil) - dockerCmd(c, "network", "connect", "--link-local-ip", "169.254.9.9", "n0", "c2") + cli.DockerCmd(c, "run", "-d", "--name", "c2", "busybox", "top") + cli.WaitRun(c, "c2") + cli.DockerCmd(c, "network", "connect", "--link-local-ip", "169.254.9.9", "n0", "c2") // verify the three containers can ping each other via the link-local addresses _, _, err = dockerCmdWithError("exec", "c0", "ping", "-c", "1", "169.254.8.8") @@ -1410,12 +1409,12 @@ func (s *DockerNetworkSuite) TestDockerNetworkConnectLinkLocalIP(c *testing.T) { assert.NilError(c, err) // Stop and restart the three containers - dockerCmd(c, "stop", "c0") - dockerCmd(c, "stop", "c1") - dockerCmd(c, "stop", "c2") - dockerCmd(c, "start", "c0") - dockerCmd(c, "start", "c1") - dockerCmd(c, "start", "c2") + cli.DockerCmd(c, "stop", "c0") + cli.DockerCmd(c, "stop", "c1") + cli.DockerCmd(c, "stop", "c2") + cli.DockerCmd(c, "start", "c0") + cli.DockerCmd(c, "start", "c1") + cli.DockerCmd(c, "start", "c2") // verify the ping again _, _, err = dockerCmdWithError("exec", "c0", "ping", "-c", "1", "169.254.8.8") @@ -1428,17 +1427,16 @@ func (s *DockerNetworkSuite) TestDockerNetworkConnectLinkLocalIP(c *testing.T) { func (s *DockerCLINetworkSuite) TestUserDefinedNetworkConnectDisconnectLink(c *testing.T) { testRequires(c, DaemonIsLinux, NotUserNamespace) - dockerCmd(c, "network", "create", "-d", "bridge", "foo1") - dockerCmd(c, "network", "create", "-d", "bridge", "foo2") + cli.DockerCmd(c, "network", "create", "-d", "bridge", "foo1") + cli.DockerCmd(c, "network", "create", "-d", "bridge", "foo2") - dockerCmd(c, "run", "-d", "--net=foo1", "--name=first", "busybox", "top") - assert.Assert(c, waitRun("first") == nil) + cli.DockerCmd(c, "run", "-d", "--net=foo1", "--name=first", "busybox", "top") + cli.WaitRun(c, "first") // run a container in a user-defined network with a link for an existing container // and a link for a container that doesn't exist - dockerCmd(c, "run", "-d", "--net=foo1", "--name=second", "--link=first:FirstInFoo1", - "--link=third:bar", "busybox", "top") - assert.Assert(c, waitRun("second") == nil) + cli.DockerCmd(c, "run", "-d", "--net=foo1", "--name=second", "--link=first:FirstInFoo1", "--link=third:bar", "busybox", "top") + cli.WaitRun(c, "second") // ping to first and its alias FirstInFoo1 must succeed _, _, err := dockerCmdWithError("exec", "second", "ping", "-c", "1", "first") @@ -1447,16 +1445,16 @@ func (s *DockerCLINetworkSuite) TestUserDefinedNetworkConnectDisconnectLink(c *t assert.NilError(c, err) // connect first container to foo2 network - dockerCmd(c, "network", "connect", "foo2", "first") + cli.DockerCmd(c, "network", "connect", "foo2", "first") // connect second container to foo2 network with a different alias for first container - dockerCmd(c, "network", "connect", "--link=first:FirstInFoo2", "foo2", "second") + cli.DockerCmd(c, "network", "connect", "--link=first:FirstInFoo2", "foo2", "second") // ping the new alias in network foo2 _, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "FirstInFoo2") assert.NilError(c, err) // disconnect first container from foo1 network - dockerCmd(c, "network", "disconnect", "foo1", "first") + cli.DockerCmd(c, "network", "disconnect", "foo1", "first") // link in foo1 network must fail _, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "FirstInFoo1") @@ -1472,15 +1470,15 @@ func (s *DockerNetworkSuite) TestDockerNetworkDisconnectDefault(c *testing.T) { netWorkName2 := "test2" containerName := "foo" - dockerCmd(c, "network", "create", netWorkName1) - dockerCmd(c, "network", "create", netWorkName2) - dockerCmd(c, "create", "--name", containerName, "busybox", "top") - dockerCmd(c, "network", "connect", netWorkName1, containerName) - dockerCmd(c, "network", "connect", netWorkName2, containerName) - dockerCmd(c, "network", "disconnect", "bridge", containerName) + cli.DockerCmd(c, "network", "create", netWorkName1) + cli.DockerCmd(c, "network", "create", netWorkName2) + cli.DockerCmd(c, "create", "--name", containerName, "busybox", "top") + cli.DockerCmd(c, "network", "connect", netWorkName1, containerName) + cli.DockerCmd(c, "network", "connect", netWorkName2, containerName) + cli.DockerCmd(c, "network", "disconnect", "bridge", containerName) - dockerCmd(c, "start", containerName) - assert.Assert(c, waitRun(containerName) == nil) + cli.DockerCmd(c, "start", containerName) + cli.WaitRun(c, containerName) networks := inspectField(c, containerName, "NetworkSettings.Networks") assert.Assert(c, strings.Contains(networks, netWorkName1), fmt.Sprintf("Should contain '%s' network", netWorkName1)) assert.Assert(c, strings.Contains(networks, netWorkName2), fmt.Sprintf("Should contain '%s' network", netWorkName2)) @@ -1491,10 +1489,10 @@ func (s *DockerNetworkSuite) TestDockerNetworkConnectWithAliasOnDefaultNetworks( testRequires(c, DaemonIsLinux, NotUserNamespace) defaults := []string{"bridge", "host", "none"} - out, _ := dockerCmd(c, "run", "-d", "--net=none", "busybox", "top") + out := cli.DockerCmd(c, "run", "-d", "--net=none", "busybox", "top").Stdout() containerID := strings.TrimSpace(out) - for _, net := range defaults { - res, _, err := dockerCmdWithError("network", "connect", "--alias", "alias"+net, net, containerID) + for _, nw := range defaults { + res, _, err := dockerCmdWithError("network", "connect", "--alias", "alias"+nw, nw, containerID) assert.ErrorContains(c, err, "") assert.Assert(c, strings.Contains(res, runconfig.ErrUnsupportedNetworkAndAlias.Error())) } @@ -1502,14 +1500,14 @@ func (s *DockerNetworkSuite) TestDockerNetworkConnectWithAliasOnDefaultNetworks( func (s *DockerCLINetworkSuite) TestUserDefinedNetworkConnectDisconnectAlias(c *testing.T) { testRequires(c, DaemonIsLinux, NotUserNamespace) - dockerCmd(c, "network", "create", "-d", "bridge", "net1") - dockerCmd(c, "network", "create", "-d", "bridge", "net2") + cli.DockerCmd(c, "network", "create", "-d", "bridge", "net1") + cli.DockerCmd(c, "network", "create", "-d", "bridge", "net2") - cid, _ := dockerCmd(c, "run", "-d", "--net=net1", "--name=first", "--net-alias=foo", "busybox:glibc", "top") - assert.Assert(c, waitRun("first") == nil) + cid := cli.DockerCmd(c, "run", "-d", "--net=net1", "--name=first", "--net-alias=foo", "busybox:glibc", "top").Stdout() + cli.WaitRun(c, "first") - dockerCmd(c, "run", "-d", "--net=net1", "--name=second", "busybox:glibc", "top") - assert.Assert(c, waitRun("second") == nil) + cli.DockerCmd(c, "run", "-d", "--net=net1", "--name=second", "busybox:glibc", "top") + cli.WaitRun(c, "second") // ping first container and its alias _, _, err := dockerCmdWithError("exec", "second", "ping", "-c", "1", "first") @@ -1522,16 +1520,16 @@ func (s *DockerCLINetworkSuite) TestUserDefinedNetworkConnectDisconnectAlias(c * assert.NilError(c, err) // connect first container to net2 network - dockerCmd(c, "network", "connect", "--alias=bar", "net2", "first") + cli.DockerCmd(c, "network", "connect", "--alias=bar", "net2", "first") // connect second container to foo2 network with a different alias for first container - dockerCmd(c, "network", "connect", "net2", "second") + cli.DockerCmd(c, "network", "connect", "net2", "second") // ping the new alias in network foo2 _, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "bar") assert.NilError(c, err) // disconnect first container from net1 network - dockerCmd(c, "network", "disconnect", "net1", "first") + cli.DockerCmd(c, "network", "disconnect", "net1", "first") // ping to net1 scoped alias "foo" must fail _, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "foo") @@ -1556,13 +1554,13 @@ func (s *DockerCLINetworkSuite) TestUserDefinedNetworkConnectDisconnectAlias(c * func (s *DockerCLINetworkSuite) TestUserDefinedNetworkConnectivity(c *testing.T) { testRequires(c, DaemonIsLinux, NotUserNamespace) - dockerCmd(c, "network", "create", "-d", "bridge", "br.net1") + cli.DockerCmd(c, "network", "create", "-d", "bridge", "br.net1") - dockerCmd(c, "run", "-d", "--net=br.net1", "--name=c1.net1", "busybox:glibc", "top") - assert.Assert(c, waitRun("c1.net1") == nil) + cli.DockerCmd(c, "run", "-d", "--net=br.net1", "--name=c1.net1", "busybox:glibc", "top") + cli.WaitRun(c, "c1.net1") - dockerCmd(c, "run", "-d", "--net=br.net1", "--name=c2.net1", "busybox:glibc", "top") - assert.Assert(c, waitRun("c2.net1") == nil) + cli.DockerCmd(c, "run", "-d", "--net=br.net1", "--name=c2.net1", "busybox:glibc", "top") + cli.WaitRun(c, "c2.net1") // ping first container by its unqualified name _, _, err := dockerCmdWithError("exec", "c2.net1", "ping", "-c", "1", "c1.net1") @@ -1579,16 +1577,16 @@ func (s *DockerCLINetworkSuite) TestUserDefinedNetworkConnectivity(c *testing.T) func (s *DockerCLINetworkSuite) TestEmbeddedDNSInvalidInput(c *testing.T) { testRequires(c, DaemonIsLinux, NotUserNamespace) - dockerCmd(c, "network", "create", "-d", "bridge", "nw1") + cli.DockerCmd(c, "network", "create", "-d", "bridge", "nw1") // Sending garbage to embedded DNS shouldn't crash the daemon - dockerCmd(c, "run", "-i", "--net=nw1", "--name=c1", "debian:bullseye-slim", "bash", "-c", "echo InvalidQuery > /dev/udp/127.0.0.11/53") + cli.DockerCmd(c, "run", "-i", "--net=nw1", "--name=c1", "debian:bullseye-slim", "bash", "-c", "echo InvalidQuery > /dev/udp/127.0.0.11/53") } func (s *DockerCLINetworkSuite) TestDockerNetworkConnectFailsNoInspectChange(c *testing.T) { - dockerCmd(c, "run", "-d", "--name=bb", "busybox", "top") - assert.Assert(c, waitRun("bb") == nil) - defer dockerCmd(c, "stop", "bb") + cli.DockerCmd(c, "run", "-d", "--name=bb", "busybox", "top") + cli.WaitRun(c, "bb") + defer cli.DockerCmd(c, "stop", "bb") ns0 := inspectField(c, "bb", "NetworkSettings.Networks.bridge") @@ -1601,15 +1599,15 @@ func (s *DockerCLINetworkSuite) TestDockerNetworkConnectFailsNoInspectChange(c * } func (s *DockerCLINetworkSuite) TestDockerNetworkInternalMode(c *testing.T) { - dockerCmd(c, "network", "create", "--driver=bridge", "--internal", "internal") + cli.DockerCmd(c, "network", "create", "--driver=bridge", "--internal", "internal") assertNwIsAvailable(c, "internal") nr := getNetworkResource(c, "internal") assert.Assert(c, nr.Internal) - dockerCmd(c, "run", "-d", "--net=internal", "--name=first", "busybox:glibc", "top") - assert.Assert(c, waitRun("first") == nil) - dockerCmd(c, "run", "-d", "--net=internal", "--name=second", "busybox:glibc", "top") - assert.Assert(c, waitRun("second") == nil) + cli.DockerCmd(c, "run", "-d", "--net=internal", "--name=first", "busybox:glibc", "top") + cli.WaitRun(c, "first") + cli.DockerCmd(c, "run", "-d", "--net=internal", "--name=second", "busybox:glibc", "top") + cli.WaitRun(c, "second") out, _, err := dockerCmdWithError("exec", "first", "ping", "-W", "4", "-c", "1", "8.8.8.8") assert.ErrorContains(c, err, "") assert.Assert(c, is.Contains(out, "Network is unreachable")) @@ -1619,14 +1617,14 @@ func (s *DockerCLINetworkSuite) TestDockerNetworkInternalMode(c *testing.T) { // Test for #21401 func (s *DockerNetworkSuite) TestDockerNetworkCreateDeleteSpecialCharacters(c *testing.T) { - dockerCmd(c, "network", "create", "test@#$") + cli.DockerCmd(c, "network", "create", "test@#$") assertNwIsAvailable(c, "test@#$") - dockerCmd(c, "network", "rm", "test@#$") + cli.DockerCmd(c, "network", "rm", "test@#$") assertNwNotAvailable(c, "test@#$") - dockerCmd(c, "network", "create", "kiwl$%^") + cli.DockerCmd(c, "network", "create", "kiwl$%^") assertNwIsAvailable(c, "kiwl$%^") - dockerCmd(c, "network", "rm", "kiwl$%^") + cli.DockerCmd(c, "network", "rm", "kiwl$%^") assertNwNotAvailable(c, "kiwl$%^") } @@ -1701,11 +1699,11 @@ func (s *DockerDaemonSuite) TestDaemonRestartRestoreBridgeNetwork(t *testing.T) } func (s *DockerNetworkSuite) TestDockerNetworkFlagAlias(c *testing.T) { - dockerCmd(c, "network", "create", "user") - output, status := dockerCmd(c, "run", "--rm", "--network=user", "--network-alias=foo", "busybox", "true") - assert.Equal(c, status, 0, fmt.Sprintf("unexpected status code %d (%s)", status, output)) + cli.DockerCmd(c, "network", "create", "user") + result := cli.DockerCmd(c, "run", "--rm", "--network=user", "--network-alias=foo", "busybox", "true") + assert.Equal(c, result.ExitCode, 0, fmt.Sprintf("unexpected status code %d (%s)", result.ExitCode, result.Combined())) - output, status, _ = dockerCmdWithError("run", "--rm", "--network=user", "--net-alias=foo", "--network-alias=bar", "busybox", "true") + output, status, _ := dockerCmdWithError("run", "--rm", "--network=user", "--net-alias=foo", "--network-alias=bar", "busybox", "true") assert.Equal(c, status, 0, fmt.Sprintf("unexpected status code %d (%s)", status, output)) } @@ -1716,7 +1714,7 @@ func (s *DockerNetworkSuite) TestDockerNetworkValidateIP(c *testing.T) { _, _, err = dockerCmdWithError("run", "-d", "--name", "mynet0", "--net=mynet", "--ip", "172.28.99.88", "--ip6", "2001:db8:1234::9988", "busybox", "top") assert.NilError(c, err) - assert.Assert(c, waitRun("mynet0") == nil) + cli.WaitRun(c, "mynet0") verifyIPAddressConfig(c, "mynet0", "mynet", "172.28.99.88", "2001:db8:1234::9988") verifyIPAddresses(c, "mynet0", "mynet", "172.28.99.88", "2001:db8:1234::9988") @@ -1735,12 +1733,11 @@ func (s *DockerNetworkSuite) TestDockerNetworkValidateIP(c *testing.T) { // Test case for 26220 func (s *DockerNetworkSuite) TestDockerNetworkDisconnectFromBridge(c *testing.T) { - out, _ := dockerCmd(c, "network", "inspect", "--format", "{{.Id}}", "bridge") - + out := cli.DockerCmd(c, "network", "inspect", "--format", "{{.Id}}", "bridge").Stdout() network := strings.TrimSpace(out) name := "test" - dockerCmd(c, "create", "--name", name, "busybox", "top") + cli.DockerCmd(c, "create", "--name", name, "busybox", "top") _, _, err := dockerCmdWithError("network", "disconnect", network, name) assert.NilError(c, err) diff --git a/integration-cli/docker_cli_plugins_logdriver_test.go b/integration-cli/docker_cli_plugins_logdriver_test.go index ea821f32d2..2bb80e3b8c 100644 --- a/integration-cli/docker_cli_plugins_logdriver_test.go +++ b/integration-cli/docker_cli_plugins_logdriver_test.go @@ -6,6 +6,7 @@ import ( "testing" "github.com/docker/docker/client" + "github.com/docker/docker/integration-cli/cli" "github.com/docker/docker/testutil" "gotest.tools/v3/assert" ) @@ -25,28 +26,28 @@ func (s *DockerCLIPluginLogDriverSuite) OnTimeout(c *testing.T) { func (s *DockerCLIPluginLogDriverSuite) TestPluginLogDriver(c *testing.T) { testRequires(c, IsAmd64, DaemonIsLinux) - pluginName := "cpuguy83/docker-logdriver-test:latest" + const pluginName = "cpuguy83/docker-logdriver-test:latest" - dockerCmd(c, "plugin", "install", pluginName) - dockerCmd(c, "run", "--log-driver", pluginName, "--name=test", "busybox", "echo", "hello") - out, _ := dockerCmd(c, "logs", "test") + cli.DockerCmd(c, "plugin", "install", pluginName) + cli.DockerCmd(c, "run", "--log-driver", pluginName, "--name=test", "busybox", "echo", "hello") + out := cli.DockerCmd(c, "logs", "test").Combined() assert.Equal(c, strings.TrimSpace(out), "hello") - dockerCmd(c, "start", "-a", "test") - out, _ = dockerCmd(c, "logs", "test") + cli.DockerCmd(c, "start", "-a", "test") + out = cli.DockerCmd(c, "logs", "test").Combined() assert.Equal(c, strings.TrimSpace(out), "hello\nhello") - dockerCmd(c, "rm", "test") - dockerCmd(c, "plugin", "disable", pluginName) - dockerCmd(c, "plugin", "rm", pluginName) + cli.DockerCmd(c, "rm", "test") + cli.DockerCmd(c, "plugin", "disable", pluginName) + cli.DockerCmd(c, "plugin", "rm", pluginName) } // Make sure log drivers are listed in info, and v2 plugins are not. func (s *DockerCLIPluginLogDriverSuite) TestPluginLogDriverInfoList(c *testing.T) { testRequires(c, IsAmd64, DaemonIsLinux) - pluginName := "cpuguy83/docker-logdriver-test" + const pluginName = "cpuguy83/docker-logdriver-test" - dockerCmd(c, "plugin", "install", pluginName) + cli.DockerCmd(c, "plugin", "install", pluginName) apiClient, err := client.NewClientWithOpts(client.FromEnv) assert.NilError(c, err) diff --git a/integration-cli/docker_cli_plugins_test.go b/integration-cli/docker_cli_plugins_test.go index d7b6b6817a..f3be79fbdd 100644 --- a/integration-cli/docker_cli_plugins_test.go +++ b/integration-cli/docker_cli_plugins_test.go @@ -22,7 +22,7 @@ import ( "gotest.tools/v3/skip" ) -var ( +const ( pluginProcessName = "sample-volume-plugin" pName = "tiborvass/sample-volume-plugin" npName = "tiborvass/test-docker-netplugin" @@ -44,27 +44,27 @@ func (s *DockerCLIPluginsSuite) OnTimeout(c *testing.T) { } func (ps *DockerPluginSuite) TestPluginBasicOps(c *testing.T) { - plugin := ps.getPluginRepoWithTag() - _, _, err := dockerCmdWithError("plugin", "install", "--grant-all-permissions", plugin) + pluginName := ps.getPluginRepoWithTag() + _, _, err := dockerCmdWithError("plugin", "install", "--grant-all-permissions", pluginName) assert.NilError(c, err) out, _, err := dockerCmdWithError("plugin", "ls") assert.NilError(c, err) - assert.Check(c, is.Contains(out, plugin)) + assert.Check(c, is.Contains(out, pluginName)) assert.Check(c, is.Contains(out, "true")) - id, _, err := dockerCmdWithError("plugin", "inspect", "-f", "{{.Id}}", plugin) + id, _, err := dockerCmdWithError("plugin", "inspect", "-f", "{{.Id}}", pluginName) id = strings.TrimSpace(id) assert.NilError(c, err) - out, _, err = dockerCmdWithError("plugin", "remove", plugin) + out, _, err = dockerCmdWithError("plugin", "remove", pluginName) assert.ErrorContains(c, err, "") assert.Check(c, is.Contains(out, "is enabled")) - _, _, err = dockerCmdWithError("plugin", "disable", plugin) + _, _, err = dockerCmdWithError("plugin", "disable", pluginName) assert.NilError(c, err) - out, _, err = dockerCmdWithError("plugin", "remove", plugin) + out, _, err = dockerCmdWithError("plugin", "remove", pluginName) assert.NilError(c, err) - assert.Check(c, is.Contains(out, plugin)) + assert.Check(c, is.Contains(out, pluginName)) _, err = os.Stat(filepath.Join(testEnv.DaemonInfo.DockerRootDir, "plugins", id)) if !os.IsNotExist(err) { c.Fatal(err) @@ -72,16 +72,16 @@ func (ps *DockerPluginSuite) TestPluginBasicOps(c *testing.T) { } func (ps *DockerPluginSuite) TestPluginForceRemove(c *testing.T) { - pNameWithTag := ps.getPluginRepoWithTag() + pluginName := ps.getPluginRepoWithTag() - _, _, err := dockerCmdWithError("plugin", "install", "--grant-all-permissions", pNameWithTag) + _, _, err := dockerCmdWithError("plugin", "install", "--grant-all-permissions", pluginName) assert.NilError(c, err) - out, _, _ := dockerCmdWithError("plugin", "remove", pNameWithTag) + out, _, _ := dockerCmdWithError("plugin", "remove", pluginName) assert.Check(c, is.Contains(out, "is enabled")) - out, _, err = dockerCmdWithError("plugin", "remove", "--force", pNameWithTag) + out, _, err = dockerCmdWithError("plugin", "remove", "--force", pluginName) assert.NilError(c, err) - assert.Check(c, is.Contains(out, pNameWithTag)) + assert.Check(c, is.Contains(out, pluginName)) } func (s *DockerCLIPluginsSuite) TestPluginActive(c *testing.T) { @@ -132,23 +132,23 @@ func (s *DockerCLIPluginsSuite) TestPluginActiveNetwork(c *testing.T) { } func (ps *DockerPluginSuite) TestPluginInstallDisable(c *testing.T) { - pName := ps.getPluginRepoWithTag() + pluginName := ps.getPluginRepoWithTag() - out, _, err := dockerCmdWithError("plugin", "install", "--grant-all-permissions", "--disable", pName) + out, _, err := dockerCmdWithError("plugin", "install", "--grant-all-permissions", "--disable", pluginName) assert.NilError(c, err) - assert.Check(c, is.Contains(out, pName)) + assert.Check(c, is.Contains(out, pluginName)) out, _, err = dockerCmdWithError("plugin", "ls") assert.NilError(c, err) assert.Check(c, is.Contains(out, "false")) - out, _, err = dockerCmdWithError("plugin", "enable", pName) + out, _, err = dockerCmdWithError("plugin", "enable", pluginName) assert.NilError(c, err) - assert.Check(c, is.Contains(out, pName)) - out, _, err = dockerCmdWithError("plugin", "disable", pName) + assert.Check(c, is.Contains(out, pluginName)) + out, _, err = dockerCmdWithError("plugin", "disable", pluginName) assert.NilError(c, err) - assert.Check(c, is.Contains(out, pName)) - out, _, err = dockerCmdWithError("plugin", "remove", pName) + assert.Check(c, is.Contains(out, pluginName)) + out, _, err = dockerCmdWithError("plugin", "remove", pluginName) assert.NilError(c, err) - assert.Check(c, is.Contains(out, pName)) + assert.Check(c, is.Contains(out, pluginName)) } func (s *DockerCLIPluginsSuite) TestPluginInstallDisableVolumeLs(c *testing.T) { @@ -156,7 +156,7 @@ func (s *DockerCLIPluginsSuite) TestPluginInstallDisableVolumeLs(c *testing.T) { out, _, err := dockerCmdWithError("plugin", "install", "--grant-all-permissions", "--disable", pName) assert.NilError(c, err) assert.Check(c, is.Contains(out, pName)) - dockerCmd(c, "volume", "ls") + cli.DockerCmd(c, "volume", "ls") } func (ps *DockerPluginSuite) TestPluginSet(c *testing.T) { @@ -184,20 +184,20 @@ func (ps *DockerPluginSuite) TestPluginSet(c *testing.T) { }) assert.Assert(c, err == nil, "failed to create test plugin") - env, _ := dockerCmd(c, "plugin", "inspect", "-f", "{{.Settings.Env}}", name) + env := cli.DockerCmd(c, "plugin", "inspect", "-f", "{{.Settings.Env}}", name).Stdout() assert.Check(c, is.Equal(strings.TrimSpace(env), "[DEBUG=0]")) - dockerCmd(c, "plugin", "set", name, "DEBUG=1") + cli.DockerCmd(c, "plugin", "set", name, "DEBUG=1") - env, _ = dockerCmd(c, "plugin", "inspect", "-f", "{{.Settings.Env}}", name) + env = cli.DockerCmd(c, "plugin", "inspect", "-f", "{{.Settings.Env}}", name).Stdout() assert.Check(c, is.Equal(strings.TrimSpace(env), "[DEBUG=1]")) - env, _ = dockerCmd(c, "plugin", "inspect", "-f", "{{with $mount := index .Settings.Mounts 0}}{{$mount.Source}}{{end}}", name) - assert.Check(c, is.Contains(env, mntSrc)) - dockerCmd(c, "plugin", "set", name, "pmount1.source=bar") + mounts := cli.DockerCmd(c, "plugin", "inspect", "-f", "{{with $mount := index .Settings.Mounts 0}}{{$mount.Source}}{{end}}", name).Stdout() + assert.Check(c, is.Contains(mounts, mntSrc)) + cli.DockerCmd(c, "plugin", "set", name, "pmount1.source=bar") - env, _ = dockerCmd(c, "plugin", "inspect", "-f", "{{with $mount := index .Settings.Mounts 0}}{{$mount.Source}}{{end}}", name) - assert.Check(c, is.Contains(env, "bar")) + mounts = cli.DockerCmd(c, "plugin", "inspect", "-f", "{{with $mount := index .Settings.Mounts 0}}{{$mount.Source}}{{end}}", name).Stdout() + assert.Check(c, is.Contains(mounts, "bar")) out, _, err := dockerCmdWithError("plugin", "set", name, "pmount2.source=bar2") assert.ErrorContains(c, err, "") assert.Check(c, is.Contains(out, "Plugin config has no mount source")) @@ -207,17 +207,17 @@ func (ps *DockerPluginSuite) TestPluginSet(c *testing.T) { } func (ps *DockerPluginSuite) TestPluginInstallArgs(c *testing.T) { - pName := path.Join(ps.registryHost(), "plugin", "testplugininstallwithargs") + pluginName := path.Join(ps.registryHost(), "plugin", "testplugininstallwithargs") ctx, cancel := context.WithTimeout(testutil.GetContext(c), 60*time.Second) defer cancel() - plugin.CreateInRegistry(ctx, pName, nil, func(cfg *plugin.Config) { + plugin.CreateInRegistry(ctx, pluginName, nil, func(cfg *plugin.Config) { cfg.Env = []types.PluginEnv{{Name: "DEBUG", Settable: []string{"value"}}} }) - out, _ := dockerCmd(c, "plugin", "install", "--grant-all-permissions", "--disable", pName, "DEBUG=1") - assert.Check(c, is.Contains(out, pName)) - env, _ := dockerCmd(c, "plugin", "inspect", "-f", "{{.Settings.Env}}", pName) + out := cli.DockerCmd(c, "plugin", "install", "--grant-all-permissions", "--disable", pluginName, "DEBUG=1").Stdout() + assert.Check(c, is.Contains(out, pluginName)) + env := cli.DockerCmd(c, "plugin", "inspect", "-f", "{{.Settings.Env}}", pluginName).Stdout() assert.Check(c, is.Equal(strings.TrimSpace(env), "[DEBUG=1]")) } @@ -225,33 +225,33 @@ func (ps *DockerPluginSuite) TestPluginInstallImage(c *testing.T) { testRequires(c, IsAmd64) skip.If(c, GitHubActions, "FIXME: https://github.com/moby/moby/issues/43996") - repoName := fmt.Sprintf("%v/dockercli/busybox", privateRegistryURL) + const imgRepo = privateRegistryURL + "/dockercli/busybox" // tag the image to upload it to the private registry - dockerCmd(c, "tag", "busybox", repoName) + cli.DockerCmd(c, "tag", "busybox", imgRepo) // push the image to the registry - dockerCmd(c, "push", repoName) + cli.DockerCmd(c, "push", imgRepo) - out, _, err := dockerCmdWithError("plugin", "install", repoName) + out, _, err := dockerCmdWithError("plugin", "install", imgRepo) assert.ErrorContains(c, err, "") assert.Check(c, is.Contains(out, `Encountered remote "application/vnd.docker.container.image.v1+json"(image) when fetching`)) } func (ps *DockerPluginSuite) TestPluginEnableDisableNegative(c *testing.T) { - pName := ps.getPluginRepoWithTag() + pluginName := ps.getPluginRepoWithTag() - out, _, err := dockerCmdWithError("plugin", "install", "--grant-all-permissions", pName) + out, _, err := dockerCmdWithError("plugin", "install", "--grant-all-permissions", pluginName) assert.NilError(c, err) - assert.Check(c, is.Contains(out, pName)) - out, _, err = dockerCmdWithError("plugin", "enable", pName) + assert.Check(c, is.Contains(out, pluginName)) + out, _, err = dockerCmdWithError("plugin", "enable", pluginName) assert.ErrorContains(c, err, "") assert.Check(c, is.Contains(out, "already enabled")) - _, _, err = dockerCmdWithError("plugin", "disable", pName) + _, _, err = dockerCmdWithError("plugin", "disable", pluginName) assert.NilError(c, err) - out, _, err = dockerCmdWithError("plugin", "disable", pName) + out, _, err = dockerCmdWithError("plugin", "disable", pluginName) assert.ErrorContains(c, err, "") assert.Check(c, is.Contains(out, "already disabled")) - _, _, err = dockerCmdWithError("plugin", "remove", pName) + _, _, err = dockerCmdWithError("plugin", "remove", pluginName) assert.NilError(c, err) } @@ -285,17 +285,17 @@ func (ps *DockerPluginSuite) TestPluginCreate(c *testing.T) { } func (ps *DockerPluginSuite) TestPluginInspect(c *testing.T) { - pNameWithTag := ps.getPluginRepoWithTag() + pluginName := ps.getPluginRepoWithTag() - _, _, err := dockerCmdWithError("plugin", "install", "--grant-all-permissions", pNameWithTag) + _, _, err := dockerCmdWithError("plugin", "install", "--grant-all-permissions", pluginName) assert.NilError(c, err) out, _, err := dockerCmdWithError("plugin", "ls") assert.NilError(c, err) - assert.Check(c, is.Contains(out, pNameWithTag)) + assert.Check(c, is.Contains(out, pluginName)) assert.Check(c, is.Contains(out, "true")) // Find the ID first - out, _, err = dockerCmdWithError("plugin", "inspect", "-f", "{{.Id}}", pNameWithTag) + out, _, err = dockerCmdWithError("plugin", "inspect", "-f", "{{.Id}}", pluginName) assert.NilError(c, err) id := strings.TrimSpace(out) assert.Assert(c, id != "") @@ -311,7 +311,7 @@ func (ps *DockerPluginSuite) TestPluginInspect(c *testing.T) { assert.Check(c, is.Equal(strings.TrimSpace(out), id)) // Name with tag form - out, _, err = dockerCmdWithError("plugin", "inspect", "-f", "{{.Id}}", pNameWithTag) + out, _, err = dockerCmdWithError("plugin", "inspect", "-f", "{{.Id}}", pluginName) assert.NilError(c, err) assert.Check(c, is.Equal(strings.TrimSpace(out), id)) @@ -320,12 +320,12 @@ func (ps *DockerPluginSuite) TestPluginInspect(c *testing.T) { assert.NilError(c, err) assert.Check(c, is.Equal(strings.TrimSpace(out), id)) - _, _, err = dockerCmdWithError("plugin", "disable", pNameWithTag) + _, _, err = dockerCmdWithError("plugin", "disable", pluginName) assert.NilError(c, err) - out, _, err = dockerCmdWithError("plugin", "remove", pNameWithTag) + out, _, err = dockerCmdWithError("plugin", "remove", pluginName) assert.NilError(c, err) - assert.Check(c, is.Contains(out, pNameWithTag)) + assert.Check(c, is.Contains(out, pluginName)) // After remove nothing should be found _, _, err = dockerCmdWithError("plugin", "inspect", "-f", "{{.Id}}", id[:5]) assert.ErrorContains(c, err, "") @@ -365,12 +365,12 @@ func (ps *DockerPluginSuite) TestPluginIDPrefix(c *testing.T) { assert.NilError(c, err) assert.Check(c, is.Contains(out, name)) assert.Check(c, is.Contains(out, "false")) - env, _ := dockerCmd(c, "plugin", "inspect", "-f", "{{.Settings.Env}}", id[:5]) + env := cli.DockerCmd(c, "plugin", "inspect", "-f", "{{.Settings.Env}}", id[:5]).Stdout() assert.Check(c, is.Equal(strings.TrimSpace(env), "[DEBUG=0]")) - dockerCmd(c, "plugin", "set", id[:5], "DEBUG=1") + cli.DockerCmd(c, "plugin", "set", id[:5], "DEBUG=1") - env, _ = dockerCmd(c, "plugin", "inspect", "-f", "{{.Settings.Env}}", id[:5]) + env = cli.DockerCmd(c, "plugin", "inspect", "-f", "{{.Settings.Env}}", id[:5]).Stdout() assert.Check(c, is.Equal(strings.TrimSpace(env), "[DEBUG=1]")) // Enable @@ -414,8 +414,8 @@ func (ps *DockerPluginSuite) TestPluginListDefaultFormat(c *testing.T) { }) assert.Assert(c, err == nil, "failed to create test plugin") - out, _ := dockerCmd(c, "plugin", "inspect", "--format", "{{.ID}}", name) - id := strings.TrimSpace(out) + id := cli.DockerCmd(c, "plugin", "inspect", "--format", "{{.ID}}", name).Stdout() + id = strings.TrimSpace(id) // We expect the format to be in `raw + --no-trunc` expectedOutput := fmt.Sprintf(`plugin_id: %s @@ -423,39 +423,39 @@ name: %s description: test plugin enabled: false`, id, name) - out, _ = dockerCmd(c, "--config", config, "plugin", "ls", "--no-trunc") + out := cli.DockerCmd(c, "--config", config, "plugin", "ls", "--no-trunc").Combined() assert.Check(c, is.Contains(out, expectedOutput)) } func (s *DockerCLIPluginsSuite) TestPluginUpgrade(c *testing.T) { testRequires(c, DaemonIsLinux, Network, testEnv.IsLocalDaemon, IsAmd64, NotUserNamespace) - plugin := "cpuguy83/docker-volume-driver-plugin-local:latest" - pluginV2 := "cpuguy83/docker-volume-driver-plugin-local:v2" + const pluginName = "cpuguy83/docker-volume-driver-plugin-local:latest" + const pluginV2 = "cpuguy83/docker-volume-driver-plugin-local:v2" - dockerCmd(c, "plugin", "install", "--grant-all-permissions", plugin) - dockerCmd(c, "volume", "create", "--driver", plugin, "bananas") - dockerCmd(c, "run", "--rm", "-v", "bananas:/apple", "busybox", "sh", "-c", "touch /apple/core") + cli.DockerCmd(c, "plugin", "install", "--grant-all-permissions", pluginName) + cli.DockerCmd(c, "volume", "create", "--driver", pluginName, "bananas") + cli.DockerCmd(c, "run", "--rm", "-v", "bananas:/apple", "busybox", "sh", "-c", "touch /apple/core") - out, _, err := dockerCmdWithError("plugin", "upgrade", "--grant-all-permissions", plugin, pluginV2) + out, _, err := dockerCmdWithError("plugin", "upgrade", "--grant-all-permissions", pluginName, pluginV2) assert.ErrorContains(c, err, "", out) assert.Check(c, is.Contains(out, "disabled before upgrading")) - out, _ = dockerCmd(c, "plugin", "inspect", "--format={{.ID}}", plugin) - id := strings.TrimSpace(out) + id := cli.DockerCmd(c, "plugin", "inspect", "--format={{.ID}}", pluginName).Stdout() + id = strings.TrimSpace(id) // make sure "v2" does not exists _, err = os.Stat(filepath.Join(testEnv.DaemonInfo.DockerRootDir, "plugins", id, "rootfs", "v2")) assert.Assert(c, os.IsNotExist(err), out) - dockerCmd(c, "plugin", "disable", "-f", plugin) - dockerCmd(c, "plugin", "upgrade", "--grant-all-permissions", "--skip-remote-check", plugin, pluginV2) + cli.DockerCmd(c, "plugin", "disable", "-f", pluginName) + cli.DockerCmd(c, "plugin", "upgrade", "--grant-all-permissions", "--skip-remote-check", pluginName, pluginV2) // make sure "v2" file exists _, err = os.Stat(filepath.Join(testEnv.DaemonInfo.DockerRootDir, "plugins", id, "rootfs", "v2")) assert.NilError(c, err) - dockerCmd(c, "plugin", "enable", plugin) - dockerCmd(c, "volume", "inspect", "bananas") - dockerCmd(c, "run", "--rm", "-v", "bananas:/apple", "busybox", "sh", "-c", "ls -lh /apple/core") + cli.DockerCmd(c, "plugin", "enable", pluginName) + cli.DockerCmd(c, "volume", "inspect", "bananas") + cli.DockerCmd(c, "run", "--rm", "-v", "bananas:/apple", "busybox", "sh", "-c", "ls -lh /apple/core") } func (s *DockerCLIPluginsSuite) TestPluginMetricsCollector(c *testing.T) { diff --git a/integration-cli/docker_cli_port_test.go b/integration-cli/docker_cli_port_test.go index e388e8f2fb..96b38e0216 100644 --- a/integration-cli/docker_cli_port_test.go +++ b/integration-cli/docker_cli_port_test.go @@ -9,6 +9,7 @@ import ( "strings" "testing" + "github.com/docker/docker/integration-cli/cli" "github.com/docker/docker/testutil" "gotest.tools/v3/assert" is "gotest.tools/v3/assert/cmp" @@ -31,32 +32,33 @@ func (s *DockerCLIPortSuite) TestPortList(c *testing.T) { ctx := testutil.GetContext(c) // one port - out, _ := dockerCmd(c, "run", "-d", "-p", "9876:80", "busybox", "top") - firstID := strings.TrimSpace(out) + firstID := cli.DockerCmd(c, "run", "-d", "-p", "9876:80", "busybox", "top").Stdout() + firstID = strings.TrimSpace(firstID) - out, _ = dockerCmd(c, "port", firstID, "80") + out := cli.DockerCmd(c, "port", firstID, "80").Stdout() assertPortList(c, out, []string{"0.0.0.0:9876", "[::]:9876"}) - out, _ = dockerCmd(c, "port", firstID) + out = cli.DockerCmd(c, "port", firstID).Stdout() assertPortList(c, out, []string{"80/tcp -> 0.0.0.0:9876", "80/tcp -> [::]:9876"}) - dockerCmd(c, "rm", "-f", firstID) + cli.DockerCmd(c, "rm", "-f", firstID) // three port - out, _ = dockerCmd(c, "run", "-d", + id := cli.DockerCmd(c, "run", "-d", "-p", "9876:80", "-p", "9877:81", "-p", "9878:82", - "busybox", "top") - ID := strings.TrimSpace(out) + "busybox", "top", + ).Stdout() + id = strings.TrimSpace(id) - out, _ = dockerCmd(c, "port", ID, "80") + out = cli.DockerCmd(c, "port", id, "80").Stdout() assertPortList(c, out, []string{"0.0.0.0:9876", "[::]:9876"}) - out, _ = dockerCmd(c, "port", ID) + out = cli.DockerCmd(c, "port", id).Stdout() assertPortList(c, out, []string{ "80/tcp -> 0.0.0.0:9876", @@ -67,22 +69,23 @@ func (s *DockerCLIPortSuite) TestPortList(c *testing.T) { "82/tcp -> [::]:9878", }) - dockerCmd(c, "rm", "-f", ID) + cli.DockerCmd(c, "rm", "-f", id) // more and one port mapped to the same container port - out, _ = dockerCmd(c, "run", "-d", + id = cli.DockerCmd(c, "run", "-d", "-p", "9876:80", "-p", "9999:80", "-p", "9877:81", "-p", "9878:82", - "busybox", "top") - ID = strings.TrimSpace(out) + "busybox", "top", + ).Stdout() + id = strings.TrimSpace(id) - out, _ = dockerCmd(c, "port", ID, "80") + out = cli.DockerCmd(c, "port", id, "80").Stdout() assertPortList(c, out, []string{"0.0.0.0:9876", "[::]:9876", "0.0.0.0:9999", "[::]:9999"}) - out, _ = dockerCmd(c, "port", ID) + out = cli.DockerCmd(c, "port", id).Stdout() assertPortList(c, out, []string{ "80/tcp -> 0.0.0.0:9876", @@ -94,16 +97,16 @@ func (s *DockerCLIPortSuite) TestPortList(c *testing.T) { "82/tcp -> 0.0.0.0:9878", "82/tcp -> [::]:9878", }) - dockerCmd(c, "rm", "-f", ID) + cli.DockerCmd(c, "rm", "-f", id) testRange := func() { // host port ranges used IDs := make([]string, 3) for i := 0; i < 3; i++ { - out, _ = dockerCmd(c, "run", "-d", "-p", "9090-9092:80", "busybox", "top") + out = cli.DockerCmd(c, "run", "-d", "-p", "9090-9092:80", "busybox", "top").Stdout() IDs[i] = strings.TrimSpace(out) - out, _ = dockerCmd(c, "port", IDs[i]) + out = cli.DockerCmd(c, "port", IDs[i]).Stdout() assertPortList(c, out, []string{ fmt.Sprintf("80/tcp -> 0.0.0.0:%d", 9090+i), @@ -117,7 +120,7 @@ func (s *DockerCLIPortSuite) TestPortList(c *testing.T) { assert.Assert(c, err != nil, "out: %s", out) for i := 0; i < 3; i++ { - dockerCmd(c, "rm", "-f", IDs[i]) + cli.DockerCmd(c, "rm", "-f", IDs[i]) } } testRange() @@ -132,10 +135,10 @@ func (s *DockerCLIPortSuite) TestPortList(c *testing.T) { } // test host range:container range spec. - out, _ = dockerCmd(c, "run", "-d", "-p", "9800-9803:80-83", "busybox", "top") - ID = strings.TrimSpace(out) + id = cli.DockerCmd(c, "run", "-d", "-p", "9800-9803:80-83", "busybox", "top").Stdout() + id = strings.TrimSpace(id) - out, _ = dockerCmd(c, "port", ID) + out = cli.DockerCmd(c, "port", id).Stdout() assertPortList(c, out, []string{ "80/tcp -> 0.0.0.0:9800", @@ -147,17 +150,17 @@ func (s *DockerCLIPortSuite) TestPortList(c *testing.T) { "83/tcp -> 0.0.0.0:9803", "83/tcp -> [::]:9803", }) - dockerCmd(c, "rm", "-f", ID) + cli.DockerCmd(c, "rm", "-f", id) // test mixing protocols in same port range - out, _ = dockerCmd(c, "run", "-d", "-p", "8000-8080:80", "-p", "8000-8080:80/udp", "busybox", "top") - ID = strings.TrimSpace(out) - - out, _ = dockerCmd(c, "port", ID) + id = cli.DockerCmd(c, "run", "-d", "-p", "8000-8080:80", "-p", "8000-8080:80/udp", "busybox", "top").Stdout() + id = strings.TrimSpace(id) + out = cli.DockerCmd(c, "port", id).Stdout() // Running this test multiple times causes the TCP port to increment. - assertPortRange(ctx, ID, []int{8000, 8080}, []int{8000, 8080}) - dockerCmd(c, "rm", "-f", ID) + err := assertPortRange(ctx, id, []int{8000, 8080}, []int{8000, 8080}) + assert.Check(c, err) + cli.DockerCmd(c, "rm", "-f", id) } func assertPortList(c *testing.T, out string, expected []string) { @@ -231,7 +234,7 @@ func assertPortRange(ctx context.Context, id string, expectedTCP, expectedUDP [] } func stopRemoveContainer(id string, c *testing.T) { - dockerCmd(c, "rm", "-f", id) + cli.DockerCmd(c, "rm", "-f", id) } func (s *DockerCLIPortSuite) TestUnpublishedPortsInPsOutput(c *testing.T) { @@ -241,23 +244,23 @@ func (s *DockerCLIPortSuite) TestUnpublishedPortsInPsOutput(c *testing.T) { port2 := 443 expose1 := fmt.Sprintf("--expose=%d", port1) expose2 := fmt.Sprintf("--expose=%d", port2) - dockerCmd(c, "run", "-d", expose1, expose2, "busybox", "sleep", "5") + cli.DockerCmd(c, "run", "-d", expose1, expose2, "busybox", "sleep", "5") // Check docker ps o/p for last created container reports the unpublished ports unpPort1 := fmt.Sprintf("%d/tcp", port1) unpPort2 := fmt.Sprintf("%d/tcp", port2) - out, _ := dockerCmd(c, "ps", "-n=1") + out := cli.DockerCmd(c, "ps", "-n=1").Stdout() // Missing unpublished ports in docker ps output assert.Assert(c, strings.Contains(out, unpPort1)) // Missing unpublished ports in docker ps output assert.Assert(c, strings.Contains(out, unpPort2)) // Run the container forcing to publish the exposed ports - dockerCmd(c, "run", "-d", "-P", expose1, expose2, "busybox", "sleep", "5") + cli.DockerCmd(c, "run", "-d", "-P", expose1, expose2, "busybox", "sleep", "5") // Check docker ps o/p for last created container reports the exposed ports in the port bindings expBndRegx1 := regexp.MustCompile(`0.0.0.0:\d\d\d\d\d->` + unpPort1) expBndRegx2 := regexp.MustCompile(`0.0.0.0:\d\d\d\d\d->` + unpPort2) - out, _ = dockerCmd(c, "ps", "-n=1") + out = cli.DockerCmd(c, "ps", "-n=1").Stdout() // Cannot find expected port binding port (0.0.0.0:xxxxx->unpPort1) in docker ps output assert.Equal(c, expBndRegx1.MatchString(out), true, fmt.Sprintf("out: %s; unpPort1: %s", out, unpPort1)) // Cannot find expected port binding port (0.0.0.0:xxxxx->unpPort2) in docker ps output @@ -267,13 +270,14 @@ func (s *DockerCLIPortSuite) TestUnpublishedPortsInPsOutput(c *testing.T) { offset := 10000 pFlag1 := fmt.Sprintf("%d:%d", offset+port1, port1) pFlag2 := fmt.Sprintf("%d:%d", offset+port2, port2) - out, _ = dockerCmd(c, "run", "-d", "-p", pFlag1, "-p", pFlag2, expose1, expose2, "busybox", "sleep", "5") - id := strings.TrimSpace(out) + + id := cli.DockerCmd(c, "run", "-d", "-p", pFlag1, "-p", pFlag2, expose1, expose2, "busybox", "sleep", "5").Stdout() + id = strings.TrimSpace(id) // Check docker ps o/p for last created container reports the specified port mappings expBnd1 := fmt.Sprintf("0.0.0.0:%d->%s", offset+port1, unpPort1) expBnd2 := fmt.Sprintf("0.0.0.0:%d->%s", offset+port2, unpPort2) - out, _ = dockerCmd(c, "ps", "-n=1") + out = cli.DockerCmd(c, "ps", "-n=1").Stdout() // Cannot find expected port binding (expBnd1) in docker ps output assert.Assert(c, strings.Contains(out, expBnd1)) // Cannot find expected port binding (expBnd2) in docker ps output @@ -282,11 +286,11 @@ func (s *DockerCLIPortSuite) TestUnpublishedPortsInPsOutput(c *testing.T) { stopRemoveContainer(id, c) // Run the container with explicit port bindings and no exposed ports - out, _ = dockerCmd(c, "run", "-d", "-p", pFlag1, "-p", pFlag2, "busybox", "sleep", "5") - id = strings.TrimSpace(out) + id = cli.DockerCmd(c, "run", "-d", "-p", pFlag1, "-p", pFlag2, "busybox", "sleep", "5").Stdout() + id = strings.TrimSpace(id) // Check docker ps o/p for last created container reports the specified port mappings - out, _ = dockerCmd(c, "ps", "-n=1") + out = cli.DockerCmd(c, "ps", "-n=1").Stdout() // Cannot find expected port binding (expBnd1) in docker ps output assert.Assert(c, strings.Contains(out, expBnd1)) // Cannot find expected port binding (expBnd2) in docker ps output @@ -295,10 +299,10 @@ func (s *DockerCLIPortSuite) TestUnpublishedPortsInPsOutput(c *testing.T) { stopRemoveContainer(id, c) // Run the container with one unpublished exposed port and one explicit port binding - dockerCmd(c, "run", "-d", expose1, "-p", pFlag2, "busybox", "sleep", "5") + cli.DockerCmd(c, "run", "-d", expose1, "-p", pFlag2, "busybox", "sleep", "5") // Check docker ps o/p for last created container reports the specified unpublished port and port mapping - out, _ = dockerCmd(c, "ps", "-n=1") + out = cli.DockerCmd(c, "ps", "-n=1").Stdout() // Missing unpublished exposed ports (unpPort1) in docker ps output assert.Assert(c, strings.Contains(out, unpPort1)) // Missing port binding (expBnd2) in docker ps output @@ -307,16 +311,16 @@ func (s *DockerCLIPortSuite) TestUnpublishedPortsInPsOutput(c *testing.T) { func (s *DockerCLIPortSuite) TestPortHostBinding(c *testing.T) { testRequires(c, DaemonIsLinux, NotUserNamespace) - out, _ := dockerCmd(c, "run", "-d", "-p", "9876:80", "busybox", "nc", "-l", "-p", "80") - firstID := strings.TrimSpace(out) + firstID := cli.DockerCmd(c, "run", "-d", "-p", "9876:80", "busybox", "nc", "-l", "-p", "80").Stdout() + firstID = strings.TrimSpace(firstID) - out, _ = dockerCmd(c, "port", firstID, "80") + out := cli.DockerCmd(c, "port", firstID, "80").Stdout() assertPortList(c, out, []string{"0.0.0.0:9876", "[::]:9876"}) - dockerCmd(c, "run", "--net=host", "busybox", "nc", "localhost", "9876") + cli.DockerCmd(c, "run", "--net=host", "busybox", "nc", "localhost", "9876") - dockerCmd(c, "rm", "-f", firstID) + cli.DockerCmd(c, "rm", "-f", firstID) out, _, err := dockerCmdWithError("run", "--net=host", "busybox", "nc", "localhost", "9876") // Port is still bound after the Container is removed @@ -325,15 +329,14 @@ func (s *DockerCLIPortSuite) TestPortHostBinding(c *testing.T) { func (s *DockerCLIPortSuite) TestPortExposeHostBinding(c *testing.T) { testRequires(c, DaemonIsLinux, NotUserNamespace) - out, _ := dockerCmd(c, "run", "-d", "-P", "--expose", "80", "busybox", "nc", "-l", "-p", "80") - firstID := strings.TrimSpace(out) + firstID := cli.DockerCmd(c, "run", "-d", "-P", "--expose", "80", "busybox", "nc", "-l", "-p", "80").Stdout() + firstID = strings.TrimSpace(firstID) - out, _ = dockerCmd(c, "inspect", "--format", `{{index .NetworkSettings.Ports "80/tcp" 0 "HostPort" }}`, firstID) + exposedPort := cli.DockerCmd(c, "inspect", "--format", `{{index .NetworkSettings.Ports "80/tcp" 0 "HostPort" }}`, firstID).Stdout() + exposedPort = strings.TrimSpace(exposedPort) + cli.DockerCmd(c, "run", "--net=host", "busybox", "nc", "127.0.0.1", exposedPort) - exposedPort := strings.TrimSpace(out) - dockerCmd(c, "run", "--net=host", "busybox", "nc", "127.0.0.1", exposedPort) - - dockerCmd(c, "rm", "-f", firstID) + cli.DockerCmd(c, "rm", "-f", firstID) out, _, err := dockerCmdWithError("run", "--net=host", "busybox", "nc", "127.0.0.1", exposedPort) // Port is still bound after the Container is removed @@ -342,19 +345,18 @@ func (s *DockerCLIPortSuite) TestPortExposeHostBinding(c *testing.T) { func (s *DockerCLIPortSuite) TestPortBindingOnSandbox(c *testing.T) { testRequires(c, DaemonIsLinux, NotUserNamespace) - dockerCmd(c, "network", "create", "--internal", "-d", "bridge", "internal-net") + cli.DockerCmd(c, "network", "create", "--internal", "-d", "bridge", "internal-net") nr := getNetworkResource(c, "internal-net") assert.Equal(c, nr.Internal, true) - dockerCmd(c, "run", "--net", "internal-net", "-d", "--name", "c1", - "-p", "8080:8080", "busybox", "nc", "-l", "-p", "8080") - assert.Assert(c, waitRun("c1") == nil) + cli.DockerCmd(c, "run", "--net", "internal-net", "-d", "--name", "c1", "-p", "8080:8080", "busybox", "nc", "-l", "-p", "8080") + cli.WaitRun(c, "c1") _, _, err := dockerCmdWithError("run", "--net=host", "busybox", "nc", "localhost", "8080") assert.Assert(c, err != nil, "Port mapping on internal network is expected to fail") // Connect container to another normal bridge network - dockerCmd(c, "network", "create", "-d", "bridge", "foo-net") - dockerCmd(c, "network", "connect", "foo-net", "c1") + cli.DockerCmd(c, "network", "create", "-d", "bridge", "foo-net") + cli.DockerCmd(c, "network", "connect", "foo-net", "c1") _, _, err = dockerCmdWithError("run", "--net=host", "busybox", "nc", "localhost", "8080") assert.Assert(c, err == nil, "Port mapping on the new network is expected to succeed") diff --git a/integration-cli/docker_cli_prune_unix_test.go b/integration-cli/docker_cli_prune_unix_test.go index a7241038e5..e5c7e81326 100644 --- a/integration-cli/docker_cli_prune_unix_test.go +++ b/integration-cli/docker_cli_prune_unix_test.go @@ -169,42 +169,48 @@ func (s *DockerCLIPruneSuite) TestPruneContainerLabel(c *testing.T) { assert.Assert(c, !strings.Contains(strings.TrimSpace(out), id2)) assert.Assert(c, !strings.Contains(strings.TrimSpace(out), id3)) assert.Assert(c, strings.Contains(strings.TrimSpace(out), id4)) + out = cli.DockerCmd(c, "container", "prune", "--force", "--filter", "label=foo").Combined() assert.Assert(c, strings.Contains(strings.TrimSpace(out), id1)) assert.Assert(c, !strings.Contains(strings.TrimSpace(out), id2)) assert.Assert(c, !strings.Contains(strings.TrimSpace(out), id3)) + out = cli.DockerCmd(c, "ps", "-a", "-q", "--no-trunc").Combined() assert.Assert(c, !strings.Contains(strings.TrimSpace(out), id1)) assert.Assert(c, strings.Contains(strings.TrimSpace(out), id2)) assert.Assert(c, strings.Contains(strings.TrimSpace(out), id3)) + out = cli.DockerCmd(c, "container", "prune", "--force", "--filter", "label!=bar").Combined() assert.Assert(c, !strings.Contains(strings.TrimSpace(out), id2)) assert.Assert(c, strings.Contains(strings.TrimSpace(out), id3)) + out = cli.DockerCmd(c, "ps", "-a", "-q", "--no-trunc").Combined() assert.Assert(c, strings.Contains(strings.TrimSpace(out), id2)) assert.Assert(c, !strings.Contains(strings.TrimSpace(out), id3)) + // With config.json label=foobar and CLI label!=foobar, CLI label!=foobar supersede out = cli.DockerCmd(c, "--config", d, "container", "prune", "--force", "--filter", "label!=foobar").Combined() assert.Assert(c, strings.Contains(strings.TrimSpace(out), id2)) + out = cli.DockerCmd(c, "ps", "-a", "-q", "--no-trunc").Combined() assert.Assert(c, !strings.Contains(strings.TrimSpace(out), id2)) } func (s *DockerCLIPruneSuite) TestPruneVolumeLabel(c *testing.T) { - out, _ := dockerCmd(c, "volume", "create", "--label", "foo") - id1 := strings.TrimSpace(out) + id1 := cli.DockerCmd(c, "volume", "create", "--label", "foo").Stdout() + id1 = strings.TrimSpace(id1) assert.Assert(c, id1 != "") - out, _ = dockerCmd(c, "volume", "create", "--label", "bar") - id2 := strings.TrimSpace(out) + id2 := cli.DockerCmd(c, "volume", "create", "--label", "bar").Stdout() + id2 = strings.TrimSpace(id2) assert.Assert(c, id2 != "") - out, _ = dockerCmd(c, "volume", "create") - id3 := strings.TrimSpace(out) + id3 := cli.DockerCmd(c, "volume", "create").Stdout() + id3 = strings.TrimSpace(id3) assert.Assert(c, id3 != "") - out, _ = dockerCmd(c, "volume", "create", "--label", "foobar") - id4 := strings.TrimSpace(out) + id4 := cli.DockerCmd(c, "volume", "create", "--label", "foobar").Stdout() + id4 = strings.TrimSpace(id4) assert.Assert(c, id4 != "") // Add a config file of label=foobar, that will have no impact if cli is label!=foobar @@ -216,46 +222,53 @@ func (s *DockerCLIPruneSuite) TestPruneVolumeLabel(c *testing.T) { assert.NilError(c, err) // With config.json only, prune based on label=foobar - out, _ = dockerCmd(c, "--config", d, "volume", "prune", "--force") + out := cli.DockerCmd(c, "--config", d, "volume", "prune", "--force").Combined() assert.Assert(c, !strings.Contains(strings.TrimSpace(out), id1)) assert.Assert(c, !strings.Contains(strings.TrimSpace(out), id2)) assert.Assert(c, !strings.Contains(strings.TrimSpace(out), id3)) assert.Assert(c, strings.Contains(strings.TrimSpace(out), id4)) - out, _ = dockerCmd(c, "volume", "prune", "--force", "--filter", "label=foo") + + out = cli.DockerCmd(c, "volume", "prune", "--force", "--filter", "label=foo").Combined() assert.Assert(c, strings.Contains(strings.TrimSpace(out), id1)) assert.Assert(c, !strings.Contains(strings.TrimSpace(out), id2)) assert.Assert(c, !strings.Contains(strings.TrimSpace(out), id3)) - out, _ = dockerCmd(c, "volume", "ls", "--format", "{{.Name}}") + + out = cli.DockerCmd(c, "volume", "ls", "--format", "{{.Name}}").Stdout() assert.Assert(c, !strings.Contains(strings.TrimSpace(out), id1)) assert.Assert(c, strings.Contains(strings.TrimSpace(out), id2)) assert.Assert(c, strings.Contains(strings.TrimSpace(out), id3)) - out, _ = dockerCmd(c, "volume", "prune", "--force", "--filter", "label!=bar") + + out = cli.DockerCmd(c, "volume", "prune", "--force", "--filter", "label!=bar").Combined() assert.Assert(c, !strings.Contains(strings.TrimSpace(out), id2)) assert.Assert(c, strings.Contains(strings.TrimSpace(out), id3)) - out, _ = dockerCmd(c, "volume", "ls", "--format", "{{.Name}}") + + out = cli.DockerCmd(c, "volume", "ls", "--format", "{{.Name}}").Stdout() assert.Assert(c, strings.Contains(strings.TrimSpace(out), id2)) assert.Assert(c, !strings.Contains(strings.TrimSpace(out), id3)) + // With config.json label=foobar and CLI label!=foobar, CLI label!=foobar supersede - out, _ = dockerCmd(c, "--config", d, "volume", "prune", "--force", "--filter", "label!=foobar") + out = cli.DockerCmd(c, "--config", d, "volume", "prune", "--force", "--filter", "label!=foobar").Combined() assert.Assert(c, strings.Contains(strings.TrimSpace(out), id2)) - out, _ = dockerCmd(c, "volume", "ls", "--format", "{{.Name}}") + out = cli.DockerCmd(c, "volume", "ls", "--format", "{{.Name}}").Stdout() assert.Assert(c, !strings.Contains(strings.TrimSpace(out), id2)) } func (s *DockerCLIPruneSuite) TestPruneNetworkLabel(c *testing.T) { - dockerCmd(c, "network", "create", "--label", "foo", "n1") - dockerCmd(c, "network", "create", "--label", "bar", "n2") - dockerCmd(c, "network", "create", "n3") + cli.DockerCmd(c, "network", "create", "--label", "foo", "n1") + cli.DockerCmd(c, "network", "create", "--label", "bar", "n2") + cli.DockerCmd(c, "network", "create", "n3") - out, _ := dockerCmd(c, "network", "prune", "--force", "--filter", "label=foo") + out := cli.DockerCmd(c, "network", "prune", "--force", "--filter", "label=foo").Combined() assert.Assert(c, strings.Contains(strings.TrimSpace(out), "n1")) assert.Assert(c, !strings.Contains(strings.TrimSpace(out), "n2")) assert.Assert(c, !strings.Contains(strings.TrimSpace(out), "n3")) - out, _ = dockerCmd(c, "network", "prune", "--force", "--filter", "label!=bar") + + out = cli.DockerCmd(c, "network", "prune", "--force", "--filter", "label!=bar").Combined() assert.Assert(c, !strings.Contains(strings.TrimSpace(out), "n1")) assert.Assert(c, !strings.Contains(strings.TrimSpace(out), "n2")) assert.Assert(c, strings.Contains(strings.TrimSpace(out), "n3")) - out, _ = dockerCmd(c, "network", "prune", "--force") + + out = cli.DockerCmd(c, "network", "prune", "--force").Combined() assert.Assert(c, !strings.Contains(strings.TrimSpace(out), "n1")) assert.Assert(c, strings.Contains(strings.TrimSpace(out), "n2")) assert.Assert(c, !strings.Contains(strings.TrimSpace(out), "n3")) @@ -282,17 +295,21 @@ func (s *DockerDaemonSuite) TestPruneImageLabel(c *testing.T) { ) result.Assert(c, icmd.Success) id2 := strings.TrimSpace(result.Combined()) + out, err = s.d.Cmd("images", "-q", "--no-trunc") assert.NilError(c, err) assert.Assert(c, strings.Contains(strings.TrimSpace(out), id2)) + out, err = s.d.Cmd("image", "prune", "--force", "--all", "--filter", "label=foo=bar") assert.NilError(c, err) assert.Assert(c, strings.Contains(strings.TrimSpace(out), id1)) assert.Assert(c, !strings.Contains(strings.TrimSpace(out), id2)) + out, err = s.d.Cmd("image", "prune", "--force", "--all", "--filter", "label!=bar=foo") assert.NilError(c, err) assert.Assert(c, !strings.Contains(strings.TrimSpace(out), id1)) assert.Assert(c, !strings.Contains(strings.TrimSpace(out), id2)) + out, err = s.d.Cmd("image", "prune", "--force", "--all", "--filter", "label=bar=foo") assert.NilError(c, err) assert.Assert(c, !strings.Contains(strings.TrimSpace(out), id1)) diff --git a/integration-cli/docker_cli_ps_test.go b/integration-cli/docker_cli_ps_test.go index c8c9744a23..e7b694d383 100644 --- a/integration-cli/docker_cli_ps_test.go +++ b/integration-cli/docker_cli_ps_test.go @@ -34,102 +34,98 @@ func (s *DockerCLIPsSuite) OnTimeout(c *testing.T) { func (s *DockerCLIPsSuite) TestPsListContainersBase(c *testing.T) { existingContainers := ExistingContainerIDs(c) - out := runSleepingContainer(c, "-d") - firstID := strings.TrimSpace(out) - - out = runSleepingContainer(c, "-d") - secondID := strings.TrimSpace(out) + firstID := runSleepingContainer(c, "-d") + secondID := runSleepingContainer(c, "-d") // not long running - out, _ = dockerCmd(c, "run", "-d", "busybox", "true") + out := cli.DockerCmd(c, "run", "-d", "busybox", "true").Stdout() thirdID := strings.TrimSpace(out) - out = runSleepingContainer(c, "-d") - fourthID := strings.TrimSpace(out) + fourthID := runSleepingContainer(c, "-d") // make sure the second is running - assert.Assert(c, waitRun(secondID) == nil) + cli.WaitRun(c, secondID) // make sure third one is not running - dockerCmd(c, "wait", thirdID) + cli.DockerCmd(c, "wait", thirdID) // make sure the forth is running - assert.Assert(c, waitRun(fourthID) == nil) + cli.WaitRun(c, fourthID) // all - out, _ = dockerCmd(c, "ps", "-a") + out = cli.DockerCmd(c, "ps", "-a").Stdout() assert.Equal(c, assertContainerList(RemoveOutputForExistingElements(out, existingContainers), []string{fourthID, thirdID, secondID, firstID}), true, fmt.Sprintf("ALL: Container list is not in the correct order: \n%s", out)) // running - out, _ = dockerCmd(c, "ps") + out = cli.DockerCmd(c, "ps").Stdout() assert.Equal(c, assertContainerList(RemoveOutputForExistingElements(out, existingContainers), []string{fourthID, secondID, firstID}), true, fmt.Sprintf("RUNNING: Container list is not in the correct order: \n%s", out)) // limit - out, _ = dockerCmd(c, "ps", "-n=2", "-a") + out = cli.DockerCmd(c, "ps", "-n=2", "-a").Stdout() expected := []string{fourthID, thirdID} assert.Equal(c, assertContainerList(RemoveOutputForExistingElements(out, existingContainers), expected), true, fmt.Sprintf("LIMIT & ALL: Container list is not in the correct order: \n%s", out)) - out, _ = dockerCmd(c, "ps", "-n=2") + out = cli.DockerCmd(c, "ps", "-n=2").Stdout() assert.Equal(c, assertContainerList(RemoveOutputForExistingElements(out, existingContainers), expected), true, fmt.Sprintf("LIMIT: Container list is not in the correct order: \n%s", out)) // filter since - out, _ = dockerCmd(c, "ps", "-f", "since="+firstID, "-a") + out = cli.DockerCmd(c, "ps", "-f", "since="+firstID, "-a").Stdout() expected = []string{fourthID, thirdID, secondID} assert.Equal(c, assertContainerList(RemoveOutputForExistingElements(out, existingContainers), expected), true, fmt.Sprintf("SINCE filter & ALL: Container list is not in the correct order: \n%s", out)) - out, _ = dockerCmd(c, "ps", "-f", "since="+firstID) + out = cli.DockerCmd(c, "ps", "-f", "since="+firstID).Stdout() expected = []string{fourthID, secondID} assert.Equal(c, assertContainerList(RemoveOutputForExistingElements(out, existingContainers), expected), true, fmt.Sprintf("SINCE filter: Container list is not in the correct order: \n%s", out)) - out, _ = dockerCmd(c, "ps", "-f", "since="+thirdID) + out = cli.DockerCmd(c, "ps", "-f", "since="+thirdID).Stdout() expected = []string{fourthID} assert.Equal(c, assertContainerList(RemoveOutputForExistingElements(out, existingContainers), expected), true, fmt.Sprintf("SINCE filter: Container list is not in the correct order: \n%s", out)) // filter before - out, _ = dockerCmd(c, "ps", "-f", "before="+fourthID, "-a") + out = cli.DockerCmd(c, "ps", "-f", "before="+fourthID, "-a").Stdout() expected = []string{thirdID, secondID, firstID} assert.Equal(c, assertContainerList(RemoveOutputForExistingElements(out, existingContainers), expected), true, fmt.Sprintf("BEFORE filter & ALL: Container list is not in the correct order: \n%s", out)) - out, _ = dockerCmd(c, "ps", "-f", "before="+fourthID) + out = cli.DockerCmd(c, "ps", "-f", "before="+fourthID).Stdout() expected = []string{secondID, firstID} assert.Equal(c, assertContainerList(RemoveOutputForExistingElements(out, existingContainers), expected), true, fmt.Sprintf("BEFORE filter: Container list is not in the correct order: \n%s", out)) - out, _ = dockerCmd(c, "ps", "-f", "before="+thirdID) + out = cli.DockerCmd(c, "ps", "-f", "before="+thirdID).Stdout() expected = []string{secondID, firstID} assert.Equal(c, assertContainerList(RemoveOutputForExistingElements(out, existingContainers), expected), true, fmt.Sprintf("SINCE filter: Container list is not in the correct order: \n%s", out)) // filter since & before - out, _ = dockerCmd(c, "ps", "-f", "since="+firstID, "-f", "before="+fourthID, "-a") + out = cli.DockerCmd(c, "ps", "-f", "since="+firstID, "-f", "before="+fourthID, "-a").Stdout() expected = []string{thirdID, secondID} assert.Equal(c, assertContainerList(RemoveOutputForExistingElements(out, existingContainers), expected), true, fmt.Sprintf("SINCE filter, BEFORE filter & ALL: Container list is not in the correct order: \n%s", out)) - out, _ = dockerCmd(c, "ps", "-f", "since="+firstID, "-f", "before="+fourthID) + out = cli.DockerCmd(c, "ps", "-f", "since="+firstID, "-f", "before="+fourthID).Stdout() expected = []string{secondID} assert.Equal(c, assertContainerList(RemoveOutputForExistingElements(out, existingContainers), expected), true, fmt.Sprintf("SINCE filter, BEFORE filter: Container list is not in the correct order: \n%s", out)) // filter since & limit - out, _ = dockerCmd(c, "ps", "-f", "since="+firstID, "-n=2", "-a") + out = cli.DockerCmd(c, "ps", "-f", "since="+firstID, "-n=2", "-a").Stdout() expected = []string{fourthID, thirdID} assert.Equal(c, assertContainerList(RemoveOutputForExistingElements(out, existingContainers), expected), true, fmt.Sprintf("SINCE filter, LIMIT & ALL: Container list is not in the correct order: \n%s", out)) - out, _ = dockerCmd(c, "ps", "-f", "since="+firstID, "-n=2") + out = cli.DockerCmd(c, "ps", "-f", "since="+firstID, "-n=2").Stdout() assert.Equal(c, assertContainerList(RemoveOutputForExistingElements(out, existingContainers), expected), true, fmt.Sprintf("SINCE filter, LIMIT: Container list is not in the correct order: \n%s", out)) // filter before & limit - out, _ = dockerCmd(c, "ps", "-f", "before="+fourthID, "-n=1", "-a") + out = cli.DockerCmd(c, "ps", "-f", "before="+fourthID, "-n=1", "-a").Stdout() expected = []string{thirdID} assert.Equal(c, assertContainerList(RemoveOutputForExistingElements(out, existingContainers), expected), true, fmt.Sprintf("BEFORE filter, LIMIT & ALL: Container list is not in the correct order: \n%s", out)) - out, _ = dockerCmd(c, "ps", "-f", "before="+fourthID, "-n=1") + out = cli.DockerCmd(c, "ps", "-f", "before="+fourthID, "-n=1").Stdout() assert.Equal(c, assertContainerList(RemoveOutputForExistingElements(out, existingContainers), expected), true, fmt.Sprintf("BEFORE filter, LIMIT: Container list is not in the correct order: \n%s", out)) // filter since & filter before & limit - out, _ = dockerCmd(c, "ps", "-f", "since="+firstID, "-f", "before="+fourthID, "-n=1", "-a") + out = cli.DockerCmd(c, "ps", "-f", "since="+firstID, "-f", "before="+fourthID, "-n=1", "-a").Stdout() expected = []string{thirdID} assert.Equal(c, assertContainerList(RemoveOutputForExistingElements(out, existingContainers), expected), true, fmt.Sprintf("SINCE filter, BEFORE filter, LIMIT & ALL: Container list is not in the correct order: \n%s", out)) - out, _ = dockerCmd(c, "ps", "-f", "since="+firstID, "-f", "before="+fourthID, "-n=1") + out = cli.DockerCmd(c, "ps", "-f", "since="+firstID, "-f", "before="+fourthID, "-n=1").Stdout() assert.Equal(c, assertContainerList(RemoveOutputForExistingElements(out, existingContainers), expected), true, fmt.Sprintf("SINCE filter, BEFORE filter, LIMIT: Container list is not in the correct order: \n%s", out)) } @@ -154,17 +150,17 @@ func assertContainerList(out string, expected []string) bool { func (s *DockerCLIPsSuite) TestPsListContainersSize(c *testing.T) { // Problematic on Windows as it doesn't report the size correctly @swernli testRequires(c, DaemonIsLinux) - dockerCmd(c, "run", "-d", "busybox") + cli.DockerCmd(c, "run", "-d", "busybox") - baseOut, _ := dockerCmd(c, "ps", "-s", "-n=1") + baseOut := cli.DockerCmd(c, "ps", "-s", "-n=1").Stdout() baseLines := strings.Split(strings.Trim(baseOut, "\n "), "\n") baseSizeIndex := strings.Index(baseLines[0], "SIZE") baseFoundsize, _, _ := strings.Cut(baseLines[1][baseSizeIndex:], " ") baseBytes, err := units.FromHumanSize(baseFoundsize) assert.NilError(c, err) - name := "test_size" - dockerCmd(c, "run", "--name", name, "busybox", "sh", "-c", "echo 1 > test") + const name = "test_size" + cli.DockerCmd(c, "run", "--name", name, "busybox", "sh", "-c", "echo 1 > test") id := getIDByName(c, name) var result *icmd.Result @@ -254,18 +250,16 @@ func (s *DockerCLIPsSuite) TestPsListContainersFilterHealth(c *testing.T) { skip.If(c, RuntimeIsWindowsContainerd(), "FIXME. Hang on Windows + containerd combination") existingContainers := ExistingContainerIDs(c) // Test legacy no health check - out := runSleepingContainer(c, "--name=none_legacy") - containerID := strings.TrimSpace(out) + containerID := runSleepingContainer(c, "--name=none_legacy") cli.WaitRun(c, containerID) - out = cli.DockerCmd(c, "ps", "-q", "-l", "--no-trunc", "--filter=health=none").Combined() + out := cli.DockerCmd(c, "ps", "-q", "-l", "--no-trunc", "--filter=health=none").Combined() containerOut := strings.TrimSpace(out) assert.Equal(c, containerOut, containerID, fmt.Sprintf("Expected id %s, got %s for legacy none filter, output: %q", containerID, containerOut, out)) // Test no health check specified explicitly - out = runSleepingContainer(c, "--name=none", "--no-healthcheck") - containerID = strings.TrimSpace(out) + containerID = runSleepingContainer(c, "--name=none", "--no-healthcheck") cli.WaitRun(c, containerID) @@ -284,8 +278,7 @@ func (s *DockerCLIPsSuite) TestPsListContainersFilterHealth(c *testing.T) { assert.Equal(c, containerOut, containerID, fmt.Sprintf("Expected containerID %s, got %s for unhealthy filter, output: %q", containerID, containerOut, out)) // Check passing healthcheck - out = runSleepingContainer(c, "--name=passing_container", "--health-cmd=exit 0", "--health-interval=1s") - containerID = strings.TrimSpace(out) + containerID = runSleepingContainer(c, "--name=passing_container", "--health-cmd=exit 0", "--health-interval=1s") waitForHealthStatus(c, "passing_container", "starting", "healthy") @@ -296,28 +289,28 @@ func (s *DockerCLIPsSuite) TestPsListContainersFilterHealth(c *testing.T) { func (s *DockerCLIPsSuite) TestPsListContainersFilterID(c *testing.T) { // start container - out, _ := dockerCmd(c, "run", "-d", "busybox") + out := cli.DockerCmd(c, "run", "-d", "busybox").Stdout() firstID := strings.TrimSpace(out) // start another container runSleepingContainer(c) // filter containers by id - out, _ = dockerCmd(c, "ps", "-a", "-q", "--filter=id="+firstID) + out = cli.DockerCmd(c, "ps", "-a", "-q", "--filter=id="+firstID).Stdout() containerOut := strings.TrimSpace(out) assert.Equal(c, containerOut, firstID[:12], fmt.Sprintf("Expected id %s, got %s for exited filter, output: %q", firstID[:12], containerOut, out)) } func (s *DockerCLIPsSuite) TestPsListContainersFilterName(c *testing.T) { // start container - dockerCmd(c, "run", "--name=a_name_to_match", "busybox") + cli.DockerCmd(c, "run", "--name=a_name_to_match", "busybox") id := getIDByName(c, "a_name_to_match") // start another container runSleepingContainer(c, "--name=b_name_to_match") // filter containers by name - out, _ := dockerCmd(c, "ps", "-a", "-q", "--filter=name=a_name_to_match") + out := cli.DockerCmd(c, "ps", "-a", "-q", "--filter=name=a_name_to_match").Stdout() containerOut := strings.TrimSpace(out) assert.Equal(c, containerOut, id[:12], fmt.Sprintf("Expected id %s, got %s for exited filter, output: %q", id[:12], containerOut, out)) } @@ -350,23 +343,23 @@ func (s *DockerCLIPsSuite) TestPsListContainersFilterAncestorImage(c *testing.T) imageID2 := getIDByName(c, imageName2) // start containers - dockerCmd(c, "run", "--name=first", "busybox", "echo", "hello") + cli.DockerCmd(c, "run", "--name=first", "busybox", "echo", "hello") firstID := getIDByName(c, "first") // start another container - dockerCmd(c, "run", "--name=second", "busybox", "echo", "hello") + cli.DockerCmd(c, "run", "--name=second", "busybox", "echo", "hello") secondID := getIDByName(c, "second") // start third container - dockerCmd(c, "run", "--name=third", imageName1, "echo", "hello") + cli.DockerCmd(c, "run", "--name=third", imageName1, "echo", "hello") thirdID := getIDByName(c, "third") // start fourth container - dockerCmd(c, "run", "--name=fourth", imageName1Tagged, "echo", "hello") + cli.DockerCmd(c, "run", "--name=fourth", imageName1Tagged, "echo", "hello") fourthID := getIDByName(c, "fourth") // start fifth container - dockerCmd(c, "run", "--name=fifth", imageName2, "echo", "hello") + cli.DockerCmd(c, "run", "--name=fifth", imageName2, "echo", "hello") fifthID := getIDByName(c, "fifth") filterTestSuite := []struct { @@ -394,12 +387,12 @@ func (s *DockerCLIPsSuite) TestPsListContainersFilterAncestorImage(c *testing.T) var out string for _, filter := range filterTestSuite { - out, _ = dockerCmd(c, "ps", "-a", "-q", "--no-trunc", "--filter=ancestor="+filter.filterName) + out = cli.DockerCmd(c, "ps", "-a", "-q", "--no-trunc", "--filter=ancestor="+filter.filterName).Stdout() checkPsAncestorFilterOutput(c, RemoveOutputForExistingElements(out, existingContainers), filter.filterName, filter.expectedIDs) } // Multiple ancestor filter - out, _ = dockerCmd(c, "ps", "-a", "-q", "--no-trunc", "--filter=ancestor="+imageName2, "--filter=ancestor="+imageName1Tagged) + out = cli.DockerCmd(c, "ps", "-a", "-q", "--no-trunc", "--filter=ancestor="+imageName2, "--filter=ancestor="+imageName1Tagged).Stdout() checkPsAncestorFilterOutput(c, RemoveOutputForExistingElements(out, existingContainers), imageName2+","+imageName1Tagged, []string{fourthID, fifthID}) } @@ -427,34 +420,34 @@ func checkPsAncestorFilterOutput(c *testing.T, out string, filterName string, ex func (s *DockerCLIPsSuite) TestPsListContainersFilterLabel(c *testing.T) { // start container - dockerCmd(c, "run", "--name=first", "-l", "match=me", "-l", "second=tag", "busybox") + cli.DockerCmd(c, "run", "--name=first", "-l", "match=me", "-l", "second=tag", "busybox") firstID := getIDByName(c, "first") // start another container - dockerCmd(c, "run", "--name=second", "-l", "match=me too", "busybox") + cli.DockerCmd(c, "run", "--name=second", "-l", "match=me too", "busybox") secondID := getIDByName(c, "second") // start third container - dockerCmd(c, "run", "--name=third", "-l", "nomatch=me", "busybox") + cli.DockerCmd(c, "run", "--name=third", "-l", "nomatch=me", "busybox") thirdID := getIDByName(c, "third") // filter containers by exact match - out, _ := dockerCmd(c, "ps", "-a", "-q", "--no-trunc", "--filter=label=match=me") + out := cli.DockerCmd(c, "ps", "-a", "-q", "--no-trunc", "--filter=label=match=me").Stdout() containerOut := strings.TrimSpace(out) assert.Equal(c, containerOut, firstID, fmt.Sprintf("Expected id %s, got %s for exited filter, output: %q", firstID, containerOut, out)) // filter containers by two labels - out, _ = dockerCmd(c, "ps", "-a", "-q", "--no-trunc", "--filter=label=match=me", "--filter=label=second=tag") + out = cli.DockerCmd(c, "ps", "-a", "-q", "--no-trunc", "--filter=label=match=me", "--filter=label=second=tag").Stdout() containerOut = strings.TrimSpace(out) assert.Equal(c, containerOut, firstID, fmt.Sprintf("Expected id %s, got %s for exited filter, output: %q", firstID, containerOut, out)) // filter containers by two labels, but expect not found because of AND behavior - out, _ = dockerCmd(c, "ps", "-a", "-q", "--no-trunc", "--filter=label=match=me", "--filter=label=second=tag-no") + out = cli.DockerCmd(c, "ps", "-a", "-q", "--no-trunc", "--filter=label=match=me", "--filter=label=second=tag-no").Stdout() containerOut = strings.TrimSpace(out) assert.Equal(c, containerOut, "", fmt.Sprintf("Expected nothing, got %s for exited filter, output: %q", containerOut, out)) // filter containers by exact key - out, _ = dockerCmd(c, "ps", "-a", "-q", "--no-trunc", "--filter=label=match") + out = cli.DockerCmd(c, "ps", "-a", "-q", "--no-trunc", "--filter=label=match").Stdout() containerOut = strings.TrimSpace(out) assert.Assert(c, strings.Contains(containerOut, firstID)) assert.Assert(c, strings.Contains(containerOut, secondID)) @@ -468,8 +461,8 @@ func (s *DockerCLIPsSuite) TestPsListContainersFilterExited(c *testing.T) { skip.If(c, DaemonIsWindows(), "FLAKY on Windows, see #20819") runSleepingContainer(c, "--name=sleep") - firstZero, _ := dockerCmd(c, "run", "-d", "busybox", "true") - secondZero, _ := dockerCmd(c, "run", "-d", "busybox", "true") + firstZero := cli.DockerCmd(c, "run", "-d", "busybox", "true").Stdout() + secondZero := cli.DockerCmd(c, "run", "-d", "busybox", "true").Stdout() out, _, err := dockerCmdWithError("run", "--name", "nonzero1", "busybox", "false") assert.Assert(c, err != nil, "Should fail. out: %s", out) @@ -480,12 +473,12 @@ func (s *DockerCLIPsSuite) TestPsListContainersFilterExited(c *testing.T) { secondNonZero := getIDByName(c, "nonzero2") // filter containers by exited=0 - out, _ = dockerCmd(c, "ps", "-a", "-q", "--no-trunc", "--filter=exited=0") + out = cli.DockerCmd(c, "ps", "-a", "-q", "--no-trunc", "--filter=exited=0").Stdout() assert.Assert(c, strings.Contains(out, strings.TrimSpace(firstZero))) assert.Assert(c, strings.Contains(out, strings.TrimSpace(secondZero))) assert.Assert(c, !strings.Contains(out, strings.TrimSpace(firstNonZero))) assert.Assert(c, !strings.Contains(out, strings.TrimSpace(secondNonZero))) - out, _ = dockerCmd(c, "ps", "-a", "-q", "--no-trunc", "--filter=exited=1") + out = cli.DockerCmd(c, "ps", "-a", "-q", "--no-trunc", "--filter=exited=1").Stdout() assert.Assert(c, strings.Contains(out, strings.TrimSpace(firstNonZero))) assert.Assert(c, strings.Contains(out, strings.TrimSpace(secondNonZero))) assert.Assert(c, !strings.Contains(out, strings.TrimSpace(firstZero))) @@ -499,25 +492,16 @@ func (s *DockerCLIPsSuite) TestPsRightTagName(c *testing.T) { existingContainers := ExistingContainerNames(c) tag := "asybox:shmatest" - dockerCmd(c, "tag", "busybox", tag) + cli.DockerCmd(c, "tag", "busybox", tag) - var id1 string - out := runSleepingContainer(c) - id1 = strings.TrimSpace(out) + id1 := runSleepingContainer(c) + id2 := runSleepingContainerInImage(c, tag) - var id2 string - out = runSleepingContainerInImage(c, tag) - id2 = strings.TrimSpace(out) + imageID := inspectField(c, "busybox", "Id") - var imageID string - out = inspectField(c, "busybox", "Id") - imageID = strings.TrimSpace(out) + id3 := runSleepingContainerInImage(c, imageID) - var id3 string - out = runSleepingContainerInImage(c, imageID) - id3 = strings.TrimSpace(out) - - out, _ = dockerCmd(c, "ps", "--no-trunc") + out := cli.DockerCmd(c, "ps", "--no-trunc").Stdout() lines := strings.Split(strings.TrimSpace(out), "\n") lines = RemoveLinesForExistingElements(lines, existingContainers) // skip header @@ -540,15 +524,15 @@ func (s *DockerCLIPsSuite) TestPsRightTagName(c *testing.T) { func (s *DockerCLIPsSuite) TestPsListContainersFilterCreated(c *testing.T) { // create a container - out, _ := dockerCmd(c, "create", "busybox") + out := cli.DockerCmd(c, "create", "busybox").Stdout() cID := strings.TrimSpace(out) shortCID := cID[:12] // Make sure it DOESN'T show up w/o a '-a' for normal 'ps' - out, _ = dockerCmd(c, "ps", "-q") + out = cli.DockerCmd(c, "ps", "-q").Stdout() assert.Assert(c, !strings.Contains(out, shortCID), "Should have not seen '%s' in ps output:\n%s", shortCID, out) // Make sure it DOES show up as 'Created' for 'ps -a' - out, _ = dockerCmd(c, "ps", "-a") + out = cli.DockerCmd(c, "ps", "-a").Stdout() hits := 0 for _, line := range strings.Split(out, "\n") { @@ -562,7 +546,7 @@ func (s *DockerCLIPsSuite) TestPsListContainersFilterCreated(c *testing.T) { assert.Equal(c, hits, 1, fmt.Sprintf("Should have seen '%s' in ps -a output once:%d\n%s", shortCID, hits, out)) // filter containers by 'create' - note, no -a needed - out, _ = dockerCmd(c, "ps", "-q", "-f", "status=created") + out = cli.DockerCmd(c, "ps", "-q", "-f", "status=created").Stdout() containerOut := strings.TrimSpace(out) assert.Assert(c, strings.Contains(containerOut, shortCID), "Should have seen '%s' in ps output:\n%s", shortCID, out) } @@ -618,15 +602,15 @@ func (s *DockerCLIPsSuite) TestPsImageIDAfterUpdate(c *testing.T) { func (s *DockerCLIPsSuite) TestPsNotShowPortsOfStoppedContainer(c *testing.T) { testRequires(c, DaemonIsLinux) - dockerCmd(c, "run", "--name=foo", "-d", "-p", "6000:5000", "busybox", "top") - assert.Assert(c, waitRun("foo") == nil) - ports, _ := dockerCmd(c, "ps", "--format", "{{ .Ports }}", "--filter", "name=foo") + cli.DockerCmd(c, "run", "--name=foo", "-d", "-p", "6000:5000", "busybox", "top") + cli.WaitRun(c, "foo") + ports := cli.DockerCmd(c, "ps", "--format", "{{ .Ports }}", "--filter", "name=foo").Stdout() expected := ":6000->5000/tcp" assert.Assert(c, is.Contains(ports, expected), "Expected: %v, got: %v", expected, ports) - dockerCmd(c, "kill", "foo") - dockerCmd(c, "wait", "foo") - ports, _ = dockerCmd(c, "ps", "--format", "{{ .Ports }}", "--filter", "name=foo") + cli.DockerCmd(c, "kill", "foo") + cli.DockerCmd(c, "wait", "foo") + ports = cli.DockerCmd(c, "ps", "--format", "{{ .Ports }}", "--filter", "name=foo").Stdout() assert.Equal(c, ports, "", "Should not got %v", expected) } @@ -637,12 +621,12 @@ func (s *DockerCLIPsSuite) TestPsShowMounts(c *testing.T) { mp := prefix + slash + "test" - dockerCmd(c, "volume", "create", "ps-volume-test") + cli.DockerCmd(c, "volume", "create", "ps-volume-test") // volume mount containers runSleepingContainer(c, "--name=volume-test-1", "--volume", "ps-volume-test:"+mp) - assert.Assert(c, waitRun("volume-test-1") == nil) + cli.WaitRun(c, "volume-test-1") runSleepingContainer(c, "--name=volume-test-2", "--volume", mp) - assert.Assert(c, waitRun("volume-test-2") == nil) + cli.WaitRun(c, "volume-test-2") // bind mount container var bindMountSource string var bindMountDestination string @@ -654,9 +638,9 @@ func (s *DockerCLIPsSuite) TestPsShowMounts(c *testing.T) { bindMountDestination = "/t" } runSleepingContainer(c, "--name=bind-mount-test", "-v", bindMountSource+":"+bindMountDestination) - assert.Assert(c, waitRun("bind-mount-test") == nil) + cli.WaitRun(c, "bind-mount-test") - out, _ := dockerCmd(c, "ps", "--format", "{{.Names}} {{.Mounts}}") + out := cli.DockerCmd(c, "ps", "--format", "{{.Names}} {{.Mounts}}").Stdout() lines := strings.Split(strings.TrimSpace(out), "\n") lines = RemoveLinesForExistingElements(lines, existingContainers) @@ -676,7 +660,7 @@ func (s *DockerCLIPsSuite) TestPsShowMounts(c *testing.T) { assert.Equal(c, fields[1], "ps-volume-test") // filter by volume name - out, _ = dockerCmd(c, "ps", "--format", "{{.Names}} {{.Mounts}}", "--filter", "volume=ps-volume-test") + out = cli.DockerCmd(c, "ps", "--format", "{{.Names}} {{.Mounts}}", "--filter", "volume=ps-volume-test").Stdout() lines = strings.Split(strings.TrimSpace(out), "\n") lines = RemoveLinesForExistingElements(lines, existingContainers) @@ -686,11 +670,11 @@ func (s *DockerCLIPsSuite) TestPsShowMounts(c *testing.T) { assert.Equal(c, fields[1], "ps-volume-test") // empty results filtering by unknown volume - out, _ = dockerCmd(c, "ps", "--format", "{{.Names}} {{.Mounts}}", "--filter", "volume=this-volume-should-not-exist") + out = cli.DockerCmd(c, "ps", "--format", "{{.Names}} {{.Mounts}}", "--filter", "volume=this-volume-should-not-exist").Stdout() assert.Equal(c, len(strings.TrimSpace(out)), 0) // filter by mount destination - out, _ = dockerCmd(c, "ps", "--format", "{{.Names}} {{.Mounts}}", "--filter", "volume="+mp) + out = cli.DockerCmd(c, "ps", "--format", "{{.Names}} {{.Mounts}}", "--filter", "volume="+mp).Stdout() lines = strings.Split(strings.TrimSpace(out), "\n") lines = RemoveLinesForExistingElements(lines, existingContainers) @@ -702,7 +686,7 @@ func (s *DockerCLIPsSuite) TestPsShowMounts(c *testing.T) { assert.Equal(c, fields[1], "ps-volume-test") // filter by bind mount source - out, _ = dockerCmd(c, "ps", "--format", "{{.Names}} {{.Mounts}}", "--filter", "volume="+bindMountSource) + out = cli.DockerCmd(c, "ps", "--format", "{{.Names}} {{.Mounts}}", "--filter", "volume="+bindMountSource).Stdout() lines = strings.Split(strings.TrimSpace(out), "\n") lines = RemoveLinesForExistingElements(lines, existingContainers) @@ -714,7 +698,7 @@ func (s *DockerCLIPsSuite) TestPsShowMounts(c *testing.T) { assert.Equal(c, fields[1], bindMountSource) // filter by bind mount destination - out, _ = dockerCmd(c, "ps", "--format", "{{.Names}} {{.Mounts}}", "--filter", "volume="+bindMountDestination) + out = cli.DockerCmd(c, "ps", "--format", "{{.Names}} {{.Mounts}}", "--filter", "volume="+bindMountDestination).Stdout() lines = strings.Split(strings.TrimSpace(out), "\n") lines = RemoveLinesForExistingElements(lines, existingContainers) @@ -726,7 +710,7 @@ func (s *DockerCLIPsSuite) TestPsShowMounts(c *testing.T) { assert.Equal(c, fields[1], bindMountSource) // empty results filtering by unknown mount point - out, _ = dockerCmd(c, "ps", "--format", "{{.Names}} {{.Mounts}}", "--filter", "volume="+prefix+slash+"this-path-was-never-mounted") + out = cli.DockerCmd(c, "ps", "--format", "{{.Names}} {{.Mounts}}", "--filter", "volume="+prefix+slash+"this-path-was-never-mounted").Stdout() assert.Equal(c, len(strings.TrimSpace(out)), 0) } @@ -742,7 +726,7 @@ func (s *DockerCLIPsSuite) TestPsListContainersFilterNetwork(c *testing.T) { runSleepingContainer(c, "--net=none", "--name=onnonenetwork") // Filter docker ps on non existing network - out, _ := dockerCmd(c, "ps", "--filter", "network=doesnotexist") + out := cli.DockerCmd(c, "ps", "--filter", "network=doesnotexist").Stdout() containerOut := strings.TrimSpace(out) lines := strings.Split(containerOut, "\n") @@ -753,7 +737,7 @@ func (s *DockerCLIPsSuite) TestPsListContainersFilterNetwork(c *testing.T) { assert.Equal(c, len(RemoveLinesForExistingElements(lines, existing)), 0) // Filter docker ps on network bridge - out, _ = dockerCmd(c, "ps", "--filter", "network=bridge") + out = cli.DockerCmd(c, "ps", "--filter", "network=bridge").Stdout() containerOut = strings.TrimSpace(out) lines = strings.Split(containerOut, "\n") @@ -767,7 +751,7 @@ func (s *DockerCLIPsSuite) TestPsListContainersFilterNetwork(c *testing.T) { // Making sure onbridgenetwork is on the output assert.Assert(c, strings.Contains(containerOut, "onbridgenetwork"), "Missing the container on network\n") // Filter docker ps on networks bridge and none - out, _ = dockerCmd(c, "ps", "--filter", "network=bridge", "--filter", "network=none") + out = cli.DockerCmd(c, "ps", "--filter", "network=bridge", "--filter", "network=none").Stdout() containerOut = strings.TrimSpace(out) lines = strings.Split(containerOut, "\n") @@ -781,18 +765,18 @@ func (s *DockerCLIPsSuite) TestPsListContainersFilterNetwork(c *testing.T) { // Making sure onbridgenetwork and onnonenetwork is on the output assert.Assert(c, strings.Contains(containerOut, "onnonenetwork"), "Missing the container on none network\n") assert.Assert(c, strings.Contains(containerOut, "onbridgenetwork"), "Missing the container on bridge network\n") - nwID, _ := dockerCmd(c, "network", "inspect", "--format", "{{.ID}}", "bridge") + nwID := cli.DockerCmd(c, "network", "inspect", "--format", "{{.ID}}", "bridge").Stdout() // Filter by network ID - out, _ = dockerCmd(c, "ps", "--filter", "network="+nwID) + out = cli.DockerCmd(c, "ps", "--filter", "network="+nwID).Stdout() containerOut = strings.TrimSpace(out) assert.Assert(c, is.Contains(containerOut, "onbridgenetwork")) // Filter by partial network ID - partialnwID := nwID[0:4] + partialNwID := nwID[0:4] - out, _ = dockerCmd(c, "ps", "--filter", "network="+partialnwID) + out = cli.DockerCmd(c, "ps", "--filter", "network="+partialNwID).Stdout() containerOut = strings.TrimSpace(out) lines = strings.Split(containerOut, "\n") @@ -808,17 +792,14 @@ func (s *DockerCLIPsSuite) TestPsListContainersFilterNetwork(c *testing.T) { } func (s *DockerCLIPsSuite) TestPsByOrder(c *testing.T) { - out := runSleepingContainer(c, "--name", "xyz-abc") - container1 := strings.TrimSpace(out) - - out = runSleepingContainer(c, "--name", "xyz-123") - container2 := strings.TrimSpace(out) + container1 := runSleepingContainer(c, "--name", "xyz-abc") + container2 := runSleepingContainer(c, "--name", "xyz-123") runSleepingContainer(c, "--name", "789-abc") runSleepingContainer(c, "--name", "789-123") // Run multiple time should have the same result - out = cli.DockerCmd(c, "ps", "--no-trunc", "-q", "-f", "name=xyz").Combined() + out := cli.DockerCmd(c, "ps", "--no-trunc", "-q", "-f", "name=xyz").Combined() assert.Equal(c, strings.TrimSpace(out), fmt.Sprintf("%s\n%s", container2, container1)) // Run multiple time should have the same result @@ -830,46 +811,46 @@ func (s *DockerCLIPsSuite) TestPsListContainersFilterPorts(c *testing.T) { testRequires(c, DaemonIsLinux) existingContainers := ExistingContainerIDs(c) - out, _ := dockerCmd(c, "run", "-d", "--publish=80", "busybox", "top") + out := cli.DockerCmd(c, "run", "-d", "--publish=80", "busybox", "top").Stdout() id1 := strings.TrimSpace(out) - out, _ = dockerCmd(c, "run", "-d", "--expose=8080", "busybox", "top") + out = cli.DockerCmd(c, "run", "-d", "--expose=8080", "busybox", "top").Stdout() id2 := strings.TrimSpace(out) - out, _ = dockerCmd(c, "run", "-d", "-p", "1090:90", "busybox", "top") + out = cli.DockerCmd(c, "run", "-d", "-p", "1090:90", "busybox", "top").Stdout() id3 := strings.TrimSpace(out) - out, _ = dockerCmd(c, "ps", "--no-trunc", "-q") + out = cli.DockerCmd(c, "ps", "--no-trunc", "-q").Stdout() assert.Assert(c, strings.Contains(strings.TrimSpace(out), id1)) assert.Assert(c, strings.Contains(strings.TrimSpace(out), id2)) assert.Assert(c, strings.Contains(strings.TrimSpace(out), id3)) - out, _ = dockerCmd(c, "ps", "--no-trunc", "-q", "--filter", "publish=80-8080/udp") + out = cli.DockerCmd(c, "ps", "--no-trunc", "-q", "--filter", "publish=80-8080/udp").Stdout() assert.Assert(c, strings.TrimSpace(out) != id1) assert.Assert(c, strings.TrimSpace(out) != id2) assert.Assert(c, strings.TrimSpace(out) != id3) - out, _ = dockerCmd(c, "ps", "--no-trunc", "-q", "--filter", "expose=8081") + out = cli.DockerCmd(c, "ps", "--no-trunc", "-q", "--filter", "expose=8081").Stdout() assert.Assert(c, strings.TrimSpace(out) != id1) assert.Assert(c, strings.TrimSpace(out) != id2) assert.Assert(c, strings.TrimSpace(out) != id3) - out, _ = dockerCmd(c, "ps", "--no-trunc", "-q", "--filter", "publish=80-81") + out = cli.DockerCmd(c, "ps", "--no-trunc", "-q", "--filter", "publish=80-81").Stdout() assert.Assert(c, strings.TrimSpace(out) != id1) assert.Assert(c, strings.TrimSpace(out) != id2) assert.Assert(c, strings.TrimSpace(out) != id3) - out, _ = dockerCmd(c, "ps", "--no-trunc", "-q", "--filter", "expose=80/tcp") + out = cli.DockerCmd(c, "ps", "--no-trunc", "-q", "--filter", "expose=80/tcp").Stdout() assert.Equal(c, strings.TrimSpace(out), id1) assert.Assert(c, strings.TrimSpace(out) != id2) assert.Assert(c, strings.TrimSpace(out) != id3) - out, _ = dockerCmd(c, "ps", "--no-trunc", "-q", "--filter", "publish=1090") + out = cli.DockerCmd(c, "ps", "--no-trunc", "-q", "--filter", "publish=1090").Stdout() assert.Assert(c, strings.TrimSpace(out) != id1) assert.Assert(c, strings.TrimSpace(out) != id2) assert.Equal(c, strings.TrimSpace(out), id3) - out, _ = dockerCmd(c, "ps", "--no-trunc", "-q", "--filter", "expose=8080/tcp") + out = cli.DockerCmd(c, "ps", "--no-trunc", "-q", "--filter", "expose=8080/tcp").Stdout() out = RemoveOutputForExistingElements(out, existingContainers) assert.Assert(c, strings.TrimSpace(out) != id1) assert.Equal(c, strings.TrimSpace(out), id2) @@ -880,10 +861,10 @@ func (s *DockerCLIPsSuite) TestPsNotShowLinknamesOfDeletedContainer(c *testing.T testRequires(c, DaemonIsLinux, MinimumAPIVersion("1.31")) existingContainers := ExistingContainerNames(c) - dockerCmd(c, "create", "--name=aaa", "busybox", "top") - dockerCmd(c, "create", "--name=bbb", "--link=aaa", "busybox", "top") + cli.DockerCmd(c, "create", "--name=aaa", "busybox", "top") + cli.DockerCmd(c, "create", "--name=bbb", "--link=aaa", "busybox", "top") - out, _ := dockerCmd(c, "ps", "--no-trunc", "-a", "--format", "{{.Names}}") + out := cli.DockerCmd(c, "ps", "--no-trunc", "-a", "--format", "{{.Names}}").Stdout() lines := strings.Split(strings.TrimSpace(out), "\n") lines = RemoveLinesForExistingElements(lines, existingContainers) expected := []string{"bbb", "aaa,bbb/aaa"} @@ -891,9 +872,9 @@ func (s *DockerCLIPsSuite) TestPsNotShowLinknamesOfDeletedContainer(c *testing.T names = append(names, lines...) assert.Assert(c, is.DeepEqual(names, expected), "Expected array with non-truncated names: %v, got: %v", expected, names) - dockerCmd(c, "rm", "bbb") + cli.DockerCmd(c, "rm", "bbb") - out, _ = dockerCmd(c, "ps", "--no-trunc", "-a", "--format", "{{.Names}}") + out = cli.DockerCmd(c, "ps", "--no-trunc", "-a", "--format", "{{.Names}}").Stdout() out = RemoveOutputForExistingElements(out, existingContainers) assert.Equal(c, strings.TrimSpace(out), "aaa") } diff --git a/integration-cli/docker_cli_pull_local_test.go b/integration-cli/docker_cli_pull_local_test.go index 403cfed457..1b2169b610 100644 --- a/integration-cli/docker_cli_pull_local_test.go +++ b/integration-cli/docker_cli_pull_local_test.go @@ -13,6 +13,7 @@ import ( "github.com/docker/distribution/manifest" "github.com/docker/distribution/manifest/manifestlist" "github.com/docker/distribution/manifest/schema2" + "github.com/docker/docker/integration-cli/cli" "github.com/docker/docker/integration-cli/cli/build" "github.com/opencontainers/go-digest" "gotest.tools/v3/assert" @@ -24,26 +25,26 @@ import ( // // Ref: docker/docker#8141 func testPullImageWithAliases(c *testing.T) { - repoName := fmt.Sprintf("%v/dockercli/busybox", privateRegistryURL) + const imgRepo = privateRegistryURL + "/dockercli/busybox" var repos []string for _, tag := range []string{"recent", "fresh"} { - repos = append(repos, fmt.Sprintf("%v:%v", repoName, tag)) + repos = append(repos, fmt.Sprintf("%v:%v", imgRepo, tag)) } // Tag and push the same image multiple times. for _, repo := range repos { - dockerCmd(c, "tag", "busybox", repo) - dockerCmd(c, "push", repo) + cli.DockerCmd(c, "tag", "busybox", repo) + cli.DockerCmd(c, "push", repo) } // Clear local images store. args := append([]string{"rmi"}, repos...) - dockerCmd(c, args...) + cli.DockerCmd(c, args...) // Pull a single tag and verify it doesn't bring down all aliases. - dockerCmd(c, "pull", repos[0]) - dockerCmd(c, "inspect", repos[0]) + cli.DockerCmd(c, "pull", repos[0]) + cli.DockerCmd(c, "inspect", repos[0]) for _, repo := range repos[1:] { _, _, err := dockerCmdWithError("inspect", repo) assert.ErrorContains(c, err, "", "Image %v shouldn't have been pulled down", repo) @@ -60,11 +61,11 @@ func (s *DockerSchema1RegistrySuite) TestPullImageWithAliases(c *testing.T) { // testConcurrentPullWholeRepo pulls the same repo concurrently. func testConcurrentPullWholeRepo(c *testing.T) { - repoName := fmt.Sprintf("%v/dockercli/busybox", privateRegistryURL) + const imgRepo = privateRegistryURL + "/dockercli/busybox" var repos []string for _, tag := range []string{"recent", "fresh", "todays"} { - repo := fmt.Sprintf("%v:%v", repoName, tag) + repo := fmt.Sprintf("%v:%v", imgRepo, tag) buildImageSuccessfully(c, repo, build.WithDockerfile(fmt.Sprintf(` FROM busybox ENTRYPOINT ["/bin/echo"] @@ -72,13 +73,13 @@ func testConcurrentPullWholeRepo(c *testing.T) { ENV BAR bar CMD echo %s `, repo))) - dockerCmd(c, "push", repo) + cli.DockerCmd(c, "push", repo) repos = append(repos, repo) } // Clear local images store. args := append([]string{"rmi"}, repos...) - dockerCmd(c, args...) + cli.DockerCmd(c, args...) // Run multiple re-pulls concurrently numPulls := 3 @@ -86,7 +87,7 @@ func testConcurrentPullWholeRepo(c *testing.T) { for i := 0; i != numPulls; i++ { go func() { - result := icmd.RunCommand(dockerBinary, "pull", "-a", repoName) + result := icmd.RunCommand(dockerBinary, "pull", "-a", imgRepo) results <- result.Error }() } @@ -100,8 +101,8 @@ func testConcurrentPullWholeRepo(c *testing.T) { // Ensure all tags were pulled successfully for _, repo := range repos { - dockerCmd(c, "inspect", repo) - out, _ := dockerCmd(c, "run", "--rm", repo) + cli.DockerCmd(c, "inspect", repo) + out := cli.DockerCmd(c, "run", "--rm", repo).Combined() assert.Equal(c, strings.TrimSpace(out), "/bin/sh -c echo "+repo) } } @@ -116,7 +117,7 @@ func (s *DockerSchema1RegistrySuite) TestConcurrentPullWholeRepo(c *testing.T) { // testConcurrentFailingPull tries a concurrent pull that doesn't succeed. func testConcurrentFailingPull(c *testing.T) { - repoName := fmt.Sprintf("%v/dockercli/busybox", privateRegistryURL) + const imgRepo = privateRegistryURL + "/dockercli/busybox" // Run multiple pulls concurrently numPulls := 3 @@ -124,7 +125,7 @@ func testConcurrentFailingPull(c *testing.T) { for i := 0; i != numPulls; i++ { go func() { - result := icmd.RunCommand(dockerBinary, "pull", repoName+":asdfasdf") + result := icmd.RunCommand(dockerBinary, "pull", imgRepo+":asdfasdf") results <- result.Error }() } @@ -148,11 +149,11 @@ func (s *DockerSchema1RegistrySuite) TestConcurrentFailingPull(c *testing.T) { // testConcurrentPullMultipleTags pulls multiple tags from the same repo // concurrently. func testConcurrentPullMultipleTags(c *testing.T) { - repoName := fmt.Sprintf("%v/dockercli/busybox", privateRegistryURL) + const imgRepo = privateRegistryURL + "/dockercli/busybox" var repos []string for _, tag := range []string{"recent", "fresh", "todays"} { - repo := fmt.Sprintf("%v:%v", repoName, tag) + repo := fmt.Sprintf("%v:%v", imgRepo, tag) buildImageSuccessfully(c, repo, build.WithDockerfile(fmt.Sprintf(` FROM busybox ENTRYPOINT ["/bin/echo"] @@ -160,13 +161,13 @@ func testConcurrentPullMultipleTags(c *testing.T) { ENV BAR bar CMD echo %s `, repo))) - dockerCmd(c, "push", repo) + cli.DockerCmd(c, "push", repo) repos = append(repos, repo) } // Clear local images store. args := append([]string{"rmi"}, repos...) - dockerCmd(c, args...) + cli.DockerCmd(c, args...) // Re-pull individual tags, in parallel results := make(chan error, len(repos)) @@ -187,8 +188,8 @@ func testConcurrentPullMultipleTags(c *testing.T) { // Ensure all tags were pulled successfully for _, repo := range repos { - dockerCmd(c, "inspect", repo) - out, _ := dockerCmd(c, "run", "--rm", repo) + cli.DockerCmd(c, "inspect", repo) + out := cli.DockerCmd(c, "run", "--rm", repo).Combined() assert.Equal(c, strings.TrimSpace(out), "/bin/sh -c echo "+repo) } } @@ -204,8 +205,8 @@ func (s *DockerSchema1RegistrySuite) TestConcurrentPullMultipleTags(c *testing.T // testPullIDStability verifies that pushing an image and pulling it back // preserves the image ID. func testPullIDStability(c *testing.T) { - derivedImage := privateRegistryURL + "/dockercli/id-stability" - baseImage := "busybox" + const derivedImage = privateRegistryURL + "/dockercli/id-stability" + const baseImage = "busybox" buildImageSuccessfully(c, derivedImage, build.WithDockerfile(fmt.Sprintf(` FROM %s @@ -216,10 +217,10 @@ func testPullIDStability(c *testing.T) { `, baseImage, derivedImage))) originalID := getIDByName(c, derivedImage) - dockerCmd(c, "push", derivedImage) + cli.DockerCmd(c, "push", derivedImage) // Pull - out, _ := dockerCmd(c, "pull", derivedImage) + out := cli.DockerCmd(c, "pull", derivedImage).Combined() if strings.Contains(out, "Pull complete") { c.Fatalf("repull redownloaded a layer: %s", out) } @@ -231,24 +232,23 @@ func testPullIDStability(c *testing.T) { } // Make sure the image runs correctly - out, _ = dockerCmd(c, "run", "--rm", derivedImage) + out = cli.DockerCmd(c, "run", "--rm", derivedImage).Combined() if strings.TrimSpace(out) != derivedImage { c.Fatalf("expected %s; got %s", derivedImage, out) } // Confirm that repushing and repulling does not change the computed ID - dockerCmd(c, "push", derivedImage) - dockerCmd(c, "rmi", derivedImage) - dockerCmd(c, "pull", derivedImage) + cli.DockerCmd(c, "push", derivedImage) + cli.DockerCmd(c, "rmi", derivedImage) + cli.DockerCmd(c, "pull", derivedImage) derivedIDAfterPull = getIDByName(c, derivedImage) - if derivedIDAfterPull != originalID { c.Fatal("image's ID unexpectedly changed after a repush/repull") } // Make sure the image still runs - out, _ = dockerCmd(c, "run", "--rm", derivedImage) + out = cli.DockerCmd(c, "run", "--rm", derivedImage).Combined() if strings.TrimSpace(out) != derivedImage { c.Fatalf("expected %s; got %s", derivedImage, out) } @@ -264,14 +264,14 @@ func (s *DockerSchema1RegistrySuite) TestPullIDStability(c *testing.T) { // #21213 func testPullNoLayers(c *testing.T) { - repoName := fmt.Sprintf("%v/dockercli/scratch", privateRegistryURL) + const imgRepo = privateRegistryURL + "/dockercli/scratch" - buildImageSuccessfully(c, repoName, build.WithDockerfile(` + buildImageSuccessfully(c, imgRepo, build.WithDockerfile(` FROM scratch ENV foo bar`)) - dockerCmd(c, "push", repoName) - dockerCmd(c, "rmi", repoName) - dockerCmd(c, "pull", repoName) + cli.DockerCmd(c, "push", imgRepo) + cli.DockerCmd(c, "rmi", imgRepo) + cli.DockerCmd(c, "pull", imgRepo) } func (s *DockerRegistrySuite) TestPullNoLayers(c *testing.T) { @@ -348,7 +348,7 @@ func (s *DockerRegistrySuite) TestPullManifestList(c *testing.T) { assert.NilError(c, err, "error writing tag link") // Verify that the image can be pulled through the manifest list. - out, _ := dockerCmd(c, "pull", repoName) + out := cli.DockerCmd(c, "pull", repoName).Combined() // The pull output includes "Digest: ", so find that matches := digestRegex.FindStringSubmatch(out) @@ -359,9 +359,9 @@ func (s *DockerRegistrySuite) TestPullManifestList(c *testing.T) { assert.Equal(c, manifestListDigest.String(), pullDigest) // Was the image actually created? - dockerCmd(c, "inspect", repoName) + cli.DockerCmd(c, "inspect", repoName) - dockerCmd(c, "rmi", repoName) + cli.DockerCmd(c, "rmi", repoName) } // #23100 @@ -375,7 +375,7 @@ func (s *DockerRegistryAuthHtpasswdSuite) TestPullWithExternalAuthLoginWithSchem testPath := fmt.Sprintf("%s%c%s", osPath, filepath.ListSeparator, absolute) c.Setenv("PATH", testPath) - repoName := fmt.Sprintf("%v/dockercli/busybox:authtest", privateRegistryURL) + const imgRepo = privateRegistryURL + "/dockercli/busybox:authtest" tmp, err := os.MkdirTemp("", "integration-cli-") assert.NilError(c, err) @@ -386,25 +386,25 @@ func (s *DockerRegistryAuthHtpasswdSuite) TestPullWithExternalAuthLoginWithSchem err = os.WriteFile(configPath, []byte(externalAuthConfig), 0o644) assert.NilError(c, err) - dockerCmd(c, "--config", tmp, "login", "-u", s.reg.Username(), "-p", s.reg.Password(), privateRegistryURL) + cli.DockerCmd(c, "--config", tmp, "login", "-u", s.reg.Username(), "-p", s.reg.Password(), privateRegistryURL) b, err := os.ReadFile(configPath) assert.NilError(c, err) assert.Assert(c, !strings.Contains(string(b), `"auth":`)) - dockerCmd(c, "--config", tmp, "tag", "busybox", repoName) - dockerCmd(c, "--config", tmp, "push", repoName) + cli.DockerCmd(c, "--config", tmp, "tag", "busybox", imgRepo) + cli.DockerCmd(c, "--config", tmp, "push", imgRepo) - dockerCmd(c, "--config", tmp, "logout", privateRegistryURL) - dockerCmd(c, "--config", tmp, "login", "-u", s.reg.Username(), "-p", s.reg.Password(), "https://"+privateRegistryURL) - dockerCmd(c, "--config", tmp, "pull", repoName) + cli.DockerCmd(c, "--config", tmp, "logout", privateRegistryURL) + cli.DockerCmd(c, "--config", tmp, "login", "-u", s.reg.Username(), "-p", s.reg.Password(), "https://"+privateRegistryURL) + cli.DockerCmd(c, "--config", tmp, "pull", imgRepo) // likewise push should work repoName2 := fmt.Sprintf("%v/dockercli/busybox:nocreds", privateRegistryURL) - dockerCmd(c, "tag", repoName, repoName2) - dockerCmd(c, "--config", tmp, "push", repoName2) + cli.DockerCmd(c, "tag", imgRepo, repoName2) + cli.DockerCmd(c, "--config", tmp, "push", repoName2) // logout should work w scheme also because it will be stripped - dockerCmd(c, "--config", tmp, "logout", "https://"+privateRegistryURL) + cli.DockerCmd(c, "--config", tmp, "logout", "https://"+privateRegistryURL) } func (s *DockerRegistryAuthHtpasswdSuite) TestPullWithExternalAuth(c *testing.T) { @@ -417,7 +417,7 @@ func (s *DockerRegistryAuthHtpasswdSuite) TestPullWithExternalAuth(c *testing.T) testPath := fmt.Sprintf("%s%c%s", osPath, filepath.ListSeparator, absolute) c.Setenv("PATH", testPath) - repoName := fmt.Sprintf("%v/dockercli/busybox:authtest", privateRegistryURL) + const imgRepo = privateRegistryURL + "/dockercli/busybox:authtest" tmp, err := os.MkdirTemp("", "integration-cli-") assert.NilError(c, err) @@ -428,34 +428,34 @@ func (s *DockerRegistryAuthHtpasswdSuite) TestPullWithExternalAuth(c *testing.T) err = os.WriteFile(configPath, []byte(externalAuthConfig), 0o644) assert.NilError(c, err) - dockerCmd(c, "--config", tmp, "login", "-u", s.reg.Username(), "-p", s.reg.Password(), privateRegistryURL) + cli.DockerCmd(c, "--config", tmp, "login", "-u", s.reg.Username(), "-p", s.reg.Password(), privateRegistryURL) b, err := os.ReadFile(configPath) assert.NilError(c, err) assert.Assert(c, !strings.Contains(string(b), `"auth":`)) - dockerCmd(c, "--config", tmp, "tag", "busybox", repoName) - dockerCmd(c, "--config", tmp, "push", repoName) + cli.DockerCmd(c, "--config", tmp, "tag", "busybox", imgRepo) + cli.DockerCmd(c, "--config", tmp, "push", imgRepo) - dockerCmd(c, "--config", tmp, "pull", repoName) + cli.DockerCmd(c, "--config", tmp, "pull", imgRepo) } // TestRunImplicitPullWithNoTag should pull implicitly only the default tag (latest) func (s *DockerRegistrySuite) TestRunImplicitPullWithNoTag(c *testing.T) { testRequires(c, DaemonIsLinux) - repo := fmt.Sprintf("%v/dockercli/busybox", privateRegistryURL) - repoTag1 := fmt.Sprintf("%v:latest", repo) - repoTag2 := fmt.Sprintf("%v:t1", repo) + const imgRepo = privateRegistryURL + "/dockercli/busybox" + const repoTag1 = imgRepo + ":latest" + const repoTag2 = imgRepo + ":t1" // tag the image and upload it to the private registry - dockerCmd(c, "tag", "busybox", repoTag1) - dockerCmd(c, "tag", "busybox", repoTag2) - dockerCmd(c, "push", repo) - dockerCmd(c, "rmi", repoTag1) - dockerCmd(c, "rmi", repoTag2) + cli.DockerCmd(c, "tag", "busybox", repoTag1) + cli.DockerCmd(c, "tag", "busybox", repoTag2) + cli.DockerCmd(c, "push", imgRepo) + cli.DockerCmd(c, "rmi", repoTag1) + cli.DockerCmd(c, "rmi", repoTag2) - out, _ := dockerCmd(c, "run", repo) - assert.Assert(c, strings.Contains(out, fmt.Sprintf("Unable to find image '%s:latest' locally", repo))) + out := cli.DockerCmd(c, "run", imgRepo).Combined() + assert.Assert(c, strings.Contains(out, fmt.Sprintf("Unable to find image '%s:latest' locally", imgRepo))) // There should be only one line for repo, the one with repo:latest - outImageCmd, _ := dockerCmd(c, "images", repo) + outImageCmd := cli.DockerCmd(c, "images", imgRepo).Stdout() splitOutImageCmd := strings.Split(strings.TrimSpace(outImageCmd), "\n") assert.Equal(c, len(splitOutImageCmd), 2) } diff --git a/integration-cli/docker_cli_pull_test.go b/integration-cli/docker_cli_pull_test.go index 0e349b6e98..4c6b508c96 100644 --- a/integration-cli/docker_cli_pull_test.go +++ b/integration-cli/docker_cli_pull_test.go @@ -181,9 +181,9 @@ func (s *DockerHubPullSuite) TestPullAllTagsFromCentralRegistry(c *testing.T) { // Ref: docker/docker#15589 func (s *DockerHubPullSuite) TestPullClientDisconnect(c *testing.T) { testRequires(c, DaemonIsLinux) - repoName := "hello-world:latest" + const imgRepo = "hello-world:latest" - pullCmd := s.MakeCmd("pull", repoName) + pullCmd := s.MakeCmd("pull", imgRepo) stdout, err := pullCmd.StdoutPipe() assert.NilError(c, err) err = pullCmd.Start() @@ -199,7 +199,7 @@ func (s *DockerHubPullSuite) TestPullClientDisconnect(c *testing.T) { assert.NilError(c, err) time.Sleep(2 * time.Second) - _, err = s.CmdWithError("inspect", repoName) + _, err = s.CmdWithError("inspect", imgRepo) assert.ErrorContains(c, err, "", "image was pulled after client disconnected") } diff --git a/integration-cli/docker_cli_push_test.go b/integration-cli/docker_cli_push_test.go index 4b0c317a11..ae4a0d08f9 100644 --- a/integration-cli/docker_cli_push_test.go +++ b/integration-cli/docker_cli_push_test.go @@ -13,6 +13,7 @@ import ( "github.com/distribution/reference" "github.com/docker/docker/api/types/versions" + "github.com/docker/docker/integration-cli/cli" "github.com/docker/docker/integration-cli/cli/build" "gotest.tools/v3/assert" "gotest.tools/v3/icmd" @@ -31,11 +32,11 @@ func (s *DockerCLIPushSuite) OnTimeout(c *testing.T) { } func (s *DockerRegistrySuite) TestPushBusyboxImage(c *testing.T) { - repoName := fmt.Sprintf("%v/dockercli/busybox", privateRegistryURL) + const imgRepo = privateRegistryURL + "/dockercli/busybox" // tag the image to upload it to the private registry - dockerCmd(c, "tag", "busybox", repoName) + cli.DockerCmd(c, "tag", "busybox", imgRepo) // push the image to the registry - dockerCmd(c, "push", repoName) + cli.DockerCmd(c, "push", imgRepo) } // pushing an image without a prefix should throw an error @@ -45,44 +46,44 @@ func (s *DockerCLIPushSuite) TestPushUnprefixedRepo(c *testing.T) { } func (s *DockerRegistrySuite) TestPushUntagged(c *testing.T) { - repoName := fmt.Sprintf("%v/dockercli/busybox", privateRegistryURL) - expected := "An image does not exist locally with the tag" + const imgRepo = privateRegistryURL + "/dockercli/busybox" - out, _, err := dockerCmdWithError("push", repoName) + out, _, err := dockerCmdWithError("push", imgRepo) assert.ErrorContains(c, err, "", "pushing the image to the private registry should have failed: output %q", out) + const expected = "An image does not exist locally with the tag" assert.Assert(c, strings.Contains(out, expected), "pushing the image failed") } func (s *DockerRegistrySuite) TestPushBadTag(c *testing.T) { - repoName := fmt.Sprintf("%v/dockercli/busybox:latest", privateRegistryURL) - expected := "does not exist" + const imgRepo = privateRegistryURL + "/dockercli/busybox:latest" - out, _, err := dockerCmdWithError("push", repoName) + out, _, err := dockerCmdWithError("push", imgRepo) assert.ErrorContains(c, err, "", "pushing the image to the private registry should have failed: output %q", out) + const expected = "does not exist" assert.Assert(c, strings.Contains(out, expected), "pushing the image failed") } func (s *DockerRegistrySuite) TestPushMultipleTags(c *testing.T) { - repoName := fmt.Sprintf("%v/dockercli/busybox", privateRegistryURL) - repoTag1 := fmt.Sprintf("%v/dockercli/busybox:t1", privateRegistryURL) - repoTag2 := fmt.Sprintf("%v/dockercli/busybox:t2", privateRegistryURL) + const imgRepo = privateRegistryURL + "/dockercli/busybox" + const repoTag1 = imgRepo + ":t1" + const repoTag2 = imgRepo + ":t2" // tag the image and upload it to the private registry - dockerCmd(c, "tag", "busybox", repoTag1) - dockerCmd(c, "tag", "busybox", repoTag2) + cli.DockerCmd(c, "tag", "busybox", repoTag1) + cli.DockerCmd(c, "tag", "busybox", repoTag2) args := []string{"push"} if versions.GreaterThanOrEqualTo(DockerCLIVersion(c), "20.10.0") { // 20.10 CLI removed implicit push all tags and requires the "--all" flag args = append(args, "--all-tags") } - args = append(args, repoName) + args = append(args, imgRepo) - dockerCmd(c, args...) + cli.DockerCmd(c, args...) imageAlreadyExists := ": Image already exists" // Ensure layer list is equivalent for repoTag1 and repoTag2 - out1, _ := dockerCmd(c, "push", repoTag1) + out1 := cli.DockerCmd(c, "push", repoTag1).Combined() var out1Lines []string for _, outputLine := range strings.Split(out1, "\n") { if strings.Contains(outputLine, imageAlreadyExists) { @@ -90,7 +91,7 @@ func (s *DockerRegistrySuite) TestPushMultipleTags(c *testing.T) { } } - out2, _ := dockerCmd(c, "push", repoTag2) + out2 := cli.DockerCmd(c, "push", repoTag2).Combined() var out2Lines []string for _, outputLine := range strings.Split(out2, "\n") { if strings.Contains(outputLine, imageAlreadyExists) { @@ -101,7 +102,8 @@ func (s *DockerRegistrySuite) TestPushMultipleTags(c *testing.T) { } func (s *DockerRegistrySuite) TestPushEmptyLayer(c *testing.T) { - repoName := fmt.Sprintf("%v/dockercli/emptylayer", privateRegistryURL) + const imgRepo = privateRegistryURL + "/dockercli/emptylayer" + emptyTarball, err := os.CreateTemp("", "empty_tarball") assert.NilError(c, err, "Unable to create test file") @@ -114,23 +116,23 @@ func (s *DockerRegistrySuite) TestPushEmptyLayer(c *testing.T) { defer freader.Close() icmd.RunCmd(icmd.Cmd{ - Command: []string{dockerBinary, "import", "-", repoName}, + Command: []string{dockerBinary, "import", "-", imgRepo}, Stdin: freader, }).Assert(c, icmd.Success) // Now verify we can push it - out, _, err := dockerCmdWithError("push", repoName) + out, _, err := dockerCmdWithError("push", imgRepo) assert.NilError(c, err, "pushing the image to the private registry has failed: %s", out) } // TestConcurrentPush pushes multiple tags to the same repo // concurrently. func (s *DockerRegistrySuite) TestConcurrentPush(c *testing.T) { - repoName := fmt.Sprintf("%v/dockercli/busybox", privateRegistryURL) + const imgRepo = privateRegistryURL + "/dockercli/busybox" var repos []string for _, tag := range []string{"push1", "push2", "push3"} { - repo := fmt.Sprintf("%v:%v", repoName, tag) + repo := fmt.Sprintf("%v:%v", imgRepo, tag) buildImageSuccessfully(c, repo, build.WithDockerfile(fmt.Sprintf(` FROM busybox ENTRYPOINT ["/bin/echo"] @@ -158,21 +160,22 @@ func (s *DockerRegistrySuite) TestConcurrentPush(c *testing.T) { // Clear local images store. args := append([]string{"rmi"}, repos...) - dockerCmd(c, args...) + cli.DockerCmd(c, args...) // Re-pull and run individual tags, to make sure pushes succeeded for _, repo := range repos { - dockerCmd(c, "pull", repo) - dockerCmd(c, "inspect", repo) - out, _ := dockerCmd(c, "run", "--rm", repo) + cli.DockerCmd(c, "pull", repo) + cli.DockerCmd(c, "inspect", repo) + out := cli.DockerCmd(c, "run", "--rm", repo).Combined() assert.Equal(c, strings.TrimSpace(out), "/bin/sh -c echo "+repo) } } func (s *DockerRegistrySuite) TestCrossRepositoryLayerPush(c *testing.T) { - sourceRepoName := fmt.Sprintf("%v/dockercli/busybox", privateRegistryURL) + const sourceRepoName = privateRegistryURL + "/dockercli/busybox" + // tag the image to upload it to the private registry - dockerCmd(c, "tag", "busybox", sourceRepoName) + cli.DockerCmd(c, "tag", "busybox", sourceRepoName) // push the image to the registry out1, _, err := dockerCmdWithError("push", sourceRepoName) assert.NilError(c, err, "pushing the image to the private registry has failed: %s", out1) @@ -182,9 +185,10 @@ func (s *DockerRegistrySuite) TestCrossRepositoryLayerPush(c *testing.T) { digest1 := reference.DigestRegexp.FindString(out1) assert.Assert(c, len(digest1) > 0, "no digest found for pushed manifest") - destRepoName := fmt.Sprintf("%v/dockercli/crossrepopush", privateRegistryURL) + const destRepoName = privateRegistryURL + "/dockercli/crossrepopush" + // retag the image to upload the same layers to another repo in the same registry - dockerCmd(c, "tag", "busybox", destRepoName) + cli.DockerCmd(c, "tag", "busybox", destRepoName) // push the image to the registry out2, _, err := dockerCmdWithError("push", destRepoName) assert.NilError(c, err, "pushing the image to the private registry has failed: %s", out2) @@ -205,16 +209,16 @@ func (s *DockerRegistrySuite) TestCrossRepositoryLayerPush(c *testing.T) { assert.Equal(c, digest3, digest2) // ensure that we can pull and run the cross-repo-pushed repository - dockerCmd(c, "rmi", destRepoName) - dockerCmd(c, "pull", destRepoName) - out4, _ := dockerCmd(c, "run", destRepoName, "echo", "-n", "hello world") + cli.DockerCmd(c, "rmi", destRepoName) + cli.DockerCmd(c, "pull", destRepoName) + out4 := cli.DockerCmd(c, "run", destRepoName, "echo", "-n", "hello world").Combined() assert.Equal(c, out4, "hello world") } func (s *DockerRegistryAuthHtpasswdSuite) TestPushNoCredentialsNoRetry(c *testing.T) { - repoName := fmt.Sprintf("%s/busybox", privateRegistryURL) - dockerCmd(c, "tag", "busybox", repoName) - out, _, err := dockerCmdWithError("push", repoName) + const imgRepo = privateRegistryURL + "/busybox" + cli.DockerCmd(c, "tag", "busybox", imgRepo) + out, _, err := dockerCmdWithError("push", imgRepo) assert.ErrorContains(c, err, "", out) assert.Assert(c, !strings.Contains(out, "Retrying")) assert.Assert(c, strings.Contains(out, "no basic auth credentials")) @@ -223,9 +227,10 @@ func (s *DockerRegistryAuthHtpasswdSuite) TestPushNoCredentialsNoRetry(c *testin // This may be flaky but it's needed not to regress on unauthorized push, see #21054 func (s *DockerCLIPushSuite) TestPushToCentralRegistryUnauthorized(c *testing.T) { testRequires(c, Network) - repoName := "test/busybox" - dockerCmd(c, "tag", "busybox", repoName) - out, _, err := dockerCmdWithError("push", repoName) + + const imgRepo = "test/busybox" + cli.DockerCmd(c, "tag", "busybox", imgRepo) + out, _, err := dockerCmdWithError("push", imgRepo) assert.ErrorContains(c, err, "", out) assert.Assert(c, !strings.Contains(out, "Retrying")) } @@ -252,9 +257,10 @@ func (s *DockerRegistryAuthTokenSuite) TestPushTokenServiceUnauthResponse(c *tes ts := getTestTokenService(http.StatusUnauthorized, `{"errors": [{"Code":"UNAUTHORIZED", "message": "a message", "detail": null}]}`, 0) defer ts.Close() s.setupRegistryWithTokenService(c, ts.URL) - repoName := fmt.Sprintf("%s/busybox", privateRegistryURL) - dockerCmd(c, "tag", "busybox", repoName) - out, _, err := dockerCmdWithError("push", repoName) + + const imgRepo = privateRegistryURL + "/busybox" + cli.DockerCmd(c, "tag", "busybox", imgRepo) + out, _, err := dockerCmdWithError("push", imgRepo) assert.ErrorContains(c, err, "", out) assert.Assert(c, !strings.Contains(out, "Retrying")) assert.Assert(c, strings.Contains(out, "unauthorized: a message")) @@ -264,9 +270,10 @@ func (s *DockerRegistryAuthTokenSuite) TestPushMisconfiguredTokenServiceResponse ts := getTestTokenService(http.StatusUnauthorized, `{"error": "unauthorized"}`, 0) defer ts.Close() s.setupRegistryWithTokenService(c, ts.URL) - repoName := fmt.Sprintf("%s/busybox", privateRegistryURL) - dockerCmd(c, "tag", "busybox", repoName) - out, _, err := dockerCmdWithError("push", repoName) + + const imgRepo = privateRegistryURL + "/busybox" + cli.DockerCmd(c, "tag", "busybox", imgRepo) + out, _, err := dockerCmdWithError("push", imgRepo) assert.ErrorContains(c, err, "", out) assert.Assert(c, !strings.Contains(out, "Retrying")) split := strings.Split(out, "\n") @@ -277,9 +284,10 @@ func (s *DockerRegistryAuthTokenSuite) TestPushMisconfiguredTokenServiceResponse ts := getTestTokenService(http.StatusTooManyRequests, `{"errors": [{"code":"TOOMANYREQUESTS","message":"out of tokens"}]}`, 3) defer ts.Close() s.setupRegistryWithTokenService(c, ts.URL) - repoName := fmt.Sprintf("%s/busybox", privateRegistryURL) - dockerCmd(c, "tag", "busybox", repoName) - out, _, err := dockerCmdWithError("push", repoName) + + const imgRepo = privateRegistryURL + "/busybox" + cli.DockerCmd(c, "tag", "busybox", imgRepo) + out, _, err := dockerCmdWithError("push", imgRepo) assert.ErrorContains(c, err, "", out) // TODO: isolate test so that it can be guaranteed that the 503 will trigger xfer retries // assert.Assert(c, strings.Contains(out, "Retrying")) @@ -292,9 +300,10 @@ func (s *DockerRegistryAuthTokenSuite) TestPushMisconfiguredTokenServiceResponse ts := getTestTokenService(http.StatusForbidden, `no way`, 0) defer ts.Close() s.setupRegistryWithTokenService(c, ts.URL) - repoName := fmt.Sprintf("%s/busybox", privateRegistryURL) - dockerCmd(c, "tag", "busybox", repoName) - out, _, err := dockerCmdWithError("push", repoName) + + const imgRepo = privateRegistryURL + "/busybox" + cli.DockerCmd(c, "tag", "busybox", imgRepo) + out, _, err := dockerCmdWithError("push", imgRepo) assert.ErrorContains(c, err, "", out) assert.Assert(c, !strings.Contains(out, "Retrying")) split := strings.Split(out, "\n") @@ -305,9 +314,10 @@ func (s *DockerRegistryAuthTokenSuite) TestPushMisconfiguredTokenServiceResponse ts := getTestTokenService(http.StatusOK, `{"something": "wrong"}`, 0) defer ts.Close() s.setupRegistryWithTokenService(c, ts.URL) - repoName := fmt.Sprintf("%s/busybox", privateRegistryURL) - dockerCmd(c, "tag", "busybox", repoName) - out, _, err := dockerCmdWithError("push", repoName) + + const imgRepo = privateRegistryURL + "/busybox" + cli.DockerCmd(c, "tag", "busybox", imgRepo) + out, _, err := dockerCmdWithError("push", imgRepo) assert.ErrorContains(c, err, "", out) assert.Assert(c, !strings.Contains(out, "Retrying")) split := strings.Split(out, "\n") diff --git a/integration-cli/docker_cli_registry_user_agent_test.go b/integration-cli/docker_cli_registry_user_agent_test.go index 0ddc2f7e19..f83d98f4d0 100644 --- a/integration-cli/docker_cli_registry_user_agent_test.go +++ b/integration-cli/docker_cli_registry_user_agent_test.go @@ -1,7 +1,6 @@ package main import ( - "fmt" "net/http" "os" "regexp" @@ -80,7 +79,7 @@ func (s *DockerRegistrySuite) TestUserAgentPassThrough(c *testing.T) { defer reg.Close() registerUserAgentHandler(reg, &ua) - repoName := fmt.Sprintf("%s/busybox", reg.URL()) + imgRepo := reg.URL() + "/busybox" s.d.StartWithBusybox(ctx, c, "--insecure-registry", reg.URL()) @@ -88,7 +87,7 @@ func (s *DockerRegistrySuite) TestUserAgentPassThrough(c *testing.T) { assert.NilError(c, err) defer os.RemoveAll(tmp) - dockerfile, err := makefile(tmp, fmt.Sprintf("FROM %s", repoName)) + dockerfile, err := makefile(tmp, "FROM "+imgRepo) assert.NilError(c, err, "Unable to create test dockerfile") s.d.Cmd("build", "--file", dockerfile, tmp) @@ -97,10 +96,10 @@ func (s *DockerRegistrySuite) TestUserAgentPassThrough(c *testing.T) { s.d.Cmd("login", "-u", "richard", "-p", "testtest", reg.URL()) regexpCheckUA(c, ua) - s.d.Cmd("pull", repoName) + s.d.Cmd("pull", imgRepo) regexpCheckUA(c, ua) - s.d.Cmd("tag", "busybox", repoName) - s.d.Cmd("push", repoName) + s.d.Cmd("tag", "busybox", imgRepo) + s.d.Cmd("push", imgRepo) regexpCheckUA(c, ua) } diff --git a/integration-cli/docker_cli_restart_test.go b/integration-cli/docker_cli_restart_test.go index 3732a4756a..757c16784e 100644 --- a/integration-cli/docker_cli_restart_test.go +++ b/integration-cli/docker_cli_restart_test.go @@ -9,6 +9,7 @@ import ( "time" "github.com/docker/docker/integration-cli/checker" + "github.com/docker/docker/integration-cli/cli" "gotest.tools/v3/assert" is "gotest.tools/v3/assert/cmp" "gotest.tools/v3/poll" @@ -28,39 +29,37 @@ func (s *DockerCLIRestartSuite) OnTimeout(c *testing.T) { } func (s *DockerCLIRestartSuite) TestRestartStoppedContainer(c *testing.T) { - dockerCmd(c, "run", "--name=test", "busybox", "echo", "foobar") - cleanedContainerID := getIDByName(c, "test") + cli.DockerCmd(c, "run", "--name=test", "busybox", "echo", "foobar") + cID := getIDByName(c, "test") - out, _ := dockerCmd(c, "logs", cleanedContainerID) + out := cli.DockerCmd(c, "logs", cID).Combined() assert.Equal(c, out, "foobar\n") - dockerCmd(c, "restart", cleanedContainerID) + cli.DockerCmd(c, "restart", cID) // Wait until the container has stopped - err := waitInspect(cleanedContainerID, "{{.State.Running}}", "false", 20*time.Second) + err := waitInspect(cID, "{{.State.Running}}", "false", 20*time.Second) assert.NilError(c, err) - out, _ = dockerCmd(c, "logs", cleanedContainerID) + out = cli.DockerCmd(c, "logs", cID).Combined() assert.Equal(c, out, "foobar\nfoobar\n") } func (s *DockerCLIRestartSuite) TestRestartRunningContainer(c *testing.T) { - out, _ := dockerCmd(c, "run", "-d", "busybox", "sh", "-c", "echo foobar && sleep 30 && echo 'should not print this'") - - cleanedContainerID := strings.TrimSpace(out) - - assert.NilError(c, waitRun(cleanedContainerID)) + cID := cli.DockerCmd(c, "run", "-d", "busybox", "sh", "-c", "echo foobar && sleep 30 && echo 'should not print this'").Stdout() + cID = strings.TrimSpace(cID) + cli.WaitRun(c, cID) getLogs := func(c *testing.T) (interface{}, string) { - out, _ := dockerCmd(c, "logs", cleanedContainerID) + out := cli.DockerCmd(c, "logs", cID).Combined() return out, "" } // Wait 10 seconds for the 'echo' to appear in the logs poll.WaitOn(c, pollCheck(c, getLogs, checker.Equals("foobar\n")), poll.WithTimeout(10*time.Second)) - dockerCmd(c, "restart", "-t", "1", cleanedContainerID) - assert.NilError(c, waitRun(cleanedContainerID)) + cli.DockerCmd(c, "restart", "-t", "1", cID) + cli.WaitRun(c, cID) // Wait 10 seconds for first 'echo' appear (again) in the logs poll.WaitOn(c, pollCheck(c, getLogs, checker.Equals("foobar\nfoobar\n")), poll.WithTimeout(10*time.Second)) @@ -69,25 +68,23 @@ func (s *DockerCLIRestartSuite) TestRestartRunningContainer(c *testing.T) { // Test that restarting a container with a volume does not create a new volume on restart. Regression test for #819. func (s *DockerCLIRestartSuite) TestRestartWithVolumes(c *testing.T) { prefix, slash := getPrefixAndSlashFromDaemonPlatform() - out := runSleepingContainer(c, "-d", "-v", prefix+slash+"test") - - cleanedContainerID := strings.TrimSpace(out) - out, err := inspectFilter(cleanedContainerID, "len .Mounts") - assert.NilError(c, err, "failed to inspect %s: %s", cleanedContainerID, out) + cID := runSleepingContainer(c, "-d", "-v", prefix+slash+"test") + out, err := inspectFilter(cID, "len .Mounts") + assert.NilError(c, err, "failed to inspect %s: %s", cID, out) out = strings.Trim(out, " \n\r") assert.Equal(c, out, "1") - source, err := inspectMountSourceField(cleanedContainerID, prefix+slash+"test") + source, err := inspectMountSourceField(cID, prefix+slash+"test") assert.NilError(c, err) - dockerCmd(c, "restart", cleanedContainerID) + cli.DockerCmd(c, "restart", cID) - out, err = inspectFilter(cleanedContainerID, "len .Mounts") - assert.NilError(c, err, "failed to inspect %s: %s", cleanedContainerID, out) + out, err = inspectFilter(cID, "len .Mounts") + assert.NilError(c, err, "failed to inspect %s: %s", cID, out) out = strings.Trim(out, " \n\r") assert.Equal(c, out, "1") - sourceAfterRestart, err := inspectMountSourceField(cleanedContainerID, prefix+slash+"test") + sourceAfterRestart, err := inspectMountSourceField(cID, prefix+slash+"test") assert.NilError(c, err) assert.Equal(c, source, sourceAfterRestart) } @@ -96,31 +93,29 @@ func (s *DockerCLIRestartSuite) TestRestartDisconnectedContainer(c *testing.T) { testRequires(c, DaemonIsLinux, testEnv.IsLocalDaemon, NotUserNamespace) // Run a container on the default bridge network - out, _ := dockerCmd(c, "run", "-d", "--name", "c0", "busybox", "top") - cleanedContainerID := strings.TrimSpace(out) - assert.NilError(c, waitRun(cleanedContainerID)) + cID := cli.DockerCmd(c, "run", "-d", "--name", "c0", "busybox", "top").Stdout() + cID = strings.TrimSpace(cID) + cli.WaitRun(c, cID) // Disconnect the container from the network - out, exitCode := dockerCmd(c, "network", "disconnect", "bridge", "c0") - assert.Assert(c, exitCode == 0, out) + result := cli.DockerCmd(c, "network", "disconnect", "bridge", "c0") + assert.Assert(c, result.ExitCode == 0, result.Combined()) // Restart the container - out, exitCode = dockerCmd(c, "restart", "c0") - assert.Assert(c, exitCode == 0, out) + result = cli.DockerCmd(c, "restart", "c0") + assert.Assert(c, result.ExitCode == 0, result.Combined()) } func (s *DockerCLIRestartSuite) TestRestartPolicyNO(c *testing.T) { - out, _ := dockerCmd(c, "create", "--restart=no", "busybox") - - id := strings.TrimSpace(out) - name := inspectField(c, id, "HostConfig.RestartPolicy.Name") + cID := cli.DockerCmd(c, "create", "--restart=no", "busybox").Stdout() + cID = strings.TrimSpace(cID) + name := inspectField(c, cID, "HostConfig.RestartPolicy.Name") assert.Equal(c, name, "no") } func (s *DockerCLIRestartSuite) TestRestartPolicyAlways(c *testing.T) { - out, _ := dockerCmd(c, "create", "--restart=always", "busybox") - - id := strings.TrimSpace(out) + id := cli.DockerCmd(c, "create", "--restart=always", "busybox").Stdout() + id = strings.TrimSpace(id) name := inspectField(c, id, "HostConfig.RestartPolicy.Name") assert.Equal(c, name, "always") @@ -135,30 +130,24 @@ func (s *DockerCLIRestartSuite) TestRestartPolicyOnFailure(c *testing.T) { assert.ErrorContains(c, err, "", out) assert.Assert(c, strings.Contains(out, "maximum retry count cannot be negative")) - out, _ = dockerCmd(c, "create", "--restart=on-failure:1", "busybox") - - id := strings.TrimSpace(out) + id := cli.DockerCmd(c, "create", "--restart=on-failure:1", "busybox").Stdout() + id = strings.TrimSpace(id) name := inspectField(c, id, "HostConfig.RestartPolicy.Name") maxRetry := inspectField(c, id, "HostConfig.RestartPolicy.MaximumRetryCount") - assert.Equal(c, name, "on-failure") assert.Equal(c, maxRetry, "1") - out, _ = dockerCmd(c, "create", "--restart=on-failure:0", "busybox") - - id = strings.TrimSpace(out) + id = cli.DockerCmd(c, "create", "--restart=on-failure:0", "busybox").Stdout() + id = strings.TrimSpace(id) name = inspectField(c, id, "HostConfig.RestartPolicy.Name") maxRetry = inspectField(c, id, "HostConfig.RestartPolicy.MaximumRetryCount") - assert.Equal(c, name, "on-failure") assert.Equal(c, maxRetry, "0") - out, _ = dockerCmd(c, "create", "--restart=on-failure", "busybox") - - id = strings.TrimSpace(out) + id = cli.DockerCmd(c, "create", "--restart=on-failure", "busybox").Stdout() + id = strings.TrimSpace(id) name = inspectField(c, id, "HostConfig.RestartPolicy.Name") maxRetry = inspectField(c, id, "HostConfig.RestartPolicy.MaximumRetryCount") - assert.Equal(c, name, "on-failure") assert.Equal(c, maxRetry, "0") } @@ -166,9 +155,8 @@ func (s *DockerCLIRestartSuite) TestRestartPolicyOnFailure(c *testing.T) { // a good container with --restart=on-failure:3 // MaximumRetryCount!=0; RestartCount=0 func (s *DockerCLIRestartSuite) TestRestartContainerwithGoodContainer(c *testing.T) { - out, _ := dockerCmd(c, "run", "-d", "--restart=on-failure:3", "busybox", "true") - - id := strings.TrimSpace(out) + id := cli.DockerCmd(c, "run", "-d", "--restart=on-failure:3", "busybox", "true").Stdout() + id = strings.TrimSpace(id) err := waitInspect(id, "{{ .State.Restarting }} {{ .State.Running }}", "false false", 30*time.Second) assert.NilError(c, err) @@ -189,9 +177,8 @@ func (s *DockerCLIRestartSuite) TestRestartContainerSuccess(c *testing.T) { testRequires(c, testEnv.DaemonInfo.Isolation.IsProcess) } - out := runSleepingContainer(c, "-d", "--restart=always") - id := strings.TrimSpace(out) - assert.NilError(c, waitRun(id)) + id := runSleepingContainer(c, "-d", "--restart=always") + cli.WaitRun(c, id) pidStr := inspectField(c, id, "State.Pid") @@ -215,14 +202,13 @@ func (s *DockerCLIRestartSuite) TestRestartContainerSuccess(c *testing.T) { func (s *DockerCLIRestartSuite) TestRestartWithPolicyUserDefinedNetwork(c *testing.T) { // TODO Windows. This may be portable following HNS integration post TP5. testRequires(c, DaemonIsLinux, testEnv.IsLocalDaemon, NotUserNamespace) - dockerCmd(c, "network", "create", "-d", "bridge", "udNet") + cli.DockerCmd(c, "network", "create", "-d", "bridge", "udNet") - dockerCmd(c, "run", "-d", "--net=udNet", "--name=first", "busybox", "top") - assert.NilError(c, waitRun("first")) + cli.DockerCmd(c, "run", "-d", "--net=udNet", "--name=first", "busybox", "top") + cli.WaitRun(c, "first") - dockerCmd(c, "run", "-d", "--restart=always", "--net=udNet", "--name=second", - "--link=first:foo", "busybox", "top") - assert.NilError(c, waitRun("second")) + cli.DockerCmd(c, "run", "-d", "--restart=always", "--net=udNet", "--name=second", "--link=first:foo", "busybox", "top") + cli.WaitRun(c, "second") // ping to first and its alias foo must succeed _, _, err := dockerCmdWithError("exec", "second", "ping", "-c", "1", "first") @@ -266,13 +252,11 @@ func (s *DockerCLIRestartSuite) TestRestartPolicyAfterRestart(c *testing.T) { testRequires(c, testEnv.DaemonInfo.Isolation.IsProcess) } - out := runSleepingContainer(c, "-d", "--restart=always") - id := strings.TrimSpace(out) - assert.NilError(c, waitRun(id)) + id := runSleepingContainer(c, "-d", "--restart=always") + cli.WaitRun(c, id) - dockerCmd(c, "restart", id) - - assert.NilError(c, waitRun(id)) + cli.DockerCmd(c, "restart", id) + cli.WaitRun(c, id) pidStr := inspectField(c, id, "State.Pid") @@ -294,11 +278,11 @@ func (s *DockerCLIRestartSuite) TestRestartPolicyAfterRestart(c *testing.T) { } func (s *DockerCLIRestartSuite) TestRestartContainerwithRestartPolicy(c *testing.T) { - out1, _ := dockerCmd(c, "run", "-d", "--restart=on-failure:3", "busybox", "false") - out2, _ := dockerCmd(c, "run", "-d", "--restart=always", "busybox", "false") + id1 := cli.DockerCmd(c, "run", "-d", "--restart=on-failure:3", "busybox", "false").Stdout() + id1 = strings.TrimSpace(id1) + id2 := cli.DockerCmd(c, "run", "-d", "--restart=always", "busybox", "false").Stdout() + id2 = strings.TrimSpace(id2) - id1 := strings.TrimSpace(out1) - id2 := strings.TrimSpace(out2) waitTimeout := 15 * time.Second if testEnv.DaemonInfo.OSType == "windows" { waitTimeout = 150 * time.Second @@ -306,18 +290,18 @@ func (s *DockerCLIRestartSuite) TestRestartContainerwithRestartPolicy(c *testing err := waitInspect(id1, "{{ .State.Restarting }} {{ .State.Running }}", "false false", waitTimeout) assert.NilError(c, err) - dockerCmd(c, "restart", id1) - dockerCmd(c, "restart", id2) + cli.DockerCmd(c, "restart", id1) + cli.DockerCmd(c, "restart", id2) // Make sure we can stop/start (regression test from a705e166cf3bcca62543150c2b3f9bfeae45ecfa) - dockerCmd(c, "stop", id1) - dockerCmd(c, "stop", id2) - dockerCmd(c, "start", id1) - dockerCmd(c, "start", id2) + cli.DockerCmd(c, "stop", id1) + cli.DockerCmd(c, "stop", id2) + cli.DockerCmd(c, "start", id1) + cli.DockerCmd(c, "start", id2) // Kill the containers, making sure they are stopped at the end of the test - dockerCmd(c, "kill", id1) - dockerCmd(c, "kill", id2) + cli.DockerCmd(c, "kill", id1) + cli.DockerCmd(c, "kill", id2) err = waitInspect(id1, "{{ .State.Restarting }} {{ .State.Running }}", "false false", waitTimeout) assert.NilError(c, err) err = waitInspect(id2, "{{ .State.Restarting }} {{ .State.Running }}", "false false", waitTimeout) @@ -325,16 +309,14 @@ func (s *DockerCLIRestartSuite) TestRestartContainerwithRestartPolicy(c *testing } func (s *DockerCLIRestartSuite) TestRestartAutoRemoveContainer(c *testing.T) { - out := runSleepingContainer(c, "--rm") - - id := strings.TrimSpace(out) - dockerCmd(c, "restart", id) + id := runSleepingContainer(c, "--rm") + cli.DockerCmd(c, "restart", id) err := waitInspect(id, "{{ .State.Restarting }} {{ .State.Running }}", "false true", 15*time.Second) assert.NilError(c, err) - out, _ = dockerCmd(c, "ps") + out := cli.DockerCmd(c, "ps").Stdout() assert.Assert(c, is.Contains(out, id[:12]), "container should be restarted instead of removed: %v", out) // Kill the container to make sure it will be removed - dockerCmd(c, "kill", id) + cli.DockerCmd(c, "kill", id) } diff --git a/integration-cli/docker_cli_rmi_test.go b/integration-cli/docker_cli_rmi_test.go index dc71bd7b77..44a4c61c72 100644 --- a/integration-cli/docker_cli_rmi_test.go +++ b/integration-cli/docker_cli_rmi_test.go @@ -31,59 +31,58 @@ func (s *DockerCLIRmiSuite) TestRmiWithContainerFails(c *testing.T) { errSubstr := "is using it" // create a container - out, _ := dockerCmd(c, "run", "-d", "busybox", "true") - - cleanedContainerID := strings.TrimSpace(out) + cID := cli.DockerCmd(c, "run", "-d", "busybox", "true").Stdout() + cID = strings.TrimSpace(cID) // try to delete the image out, _, err := dockerCmdWithError("rmi", "busybox") // Container is using image, should not be able to rmi assert.ErrorContains(c, err, "") // Container is using image, error message should contain errSubstr - assert.Assert(c, strings.Contains(out, errSubstr), "Container: %q", cleanedContainerID) + assert.Assert(c, strings.Contains(out, errSubstr), "Container: %q", cID) // make sure it didn't delete the busybox name - images, _ := dockerCmd(c, "images") + images := cli.DockerCmd(c, "images").Stdout() // The name 'busybox' should not have been removed from images assert.Assert(c, strings.Contains(images, "busybox")) } func (s *DockerCLIRmiSuite) TestRmiTag(c *testing.T) { - imagesBefore, _ := dockerCmd(c, "images", "-a") - dockerCmd(c, "tag", "busybox", "utest:tag1") - dockerCmd(c, "tag", "busybox", "utest/docker:tag2") - dockerCmd(c, "tag", "busybox", "utest:5000/docker:tag3") + imagesBefore := cli.DockerCmd(c, "images", "-a").Stdout() + cli.DockerCmd(c, "tag", "busybox", "utest:tag1") + cli.DockerCmd(c, "tag", "busybox", "utest/docker:tag2") + cli.DockerCmd(c, "tag", "busybox", "utest:5000/docker:tag3") { - imagesAfter, _ := dockerCmd(c, "images", "-a") + imagesAfter := cli.DockerCmd(c, "images", "-a").Stdout() assert.Equal(c, strings.Count(imagesAfter, "\n"), strings.Count(imagesBefore, "\n")+3, fmt.Sprintf("before: %q\n\nafter: %q\n", imagesBefore, imagesAfter)) } - dockerCmd(c, "rmi", "utest/docker:tag2") + cli.DockerCmd(c, "rmi", "utest/docker:tag2") { - imagesAfter, _ := dockerCmd(c, "images", "-a") + imagesAfter := cli.DockerCmd(c, "images", "-a").Stdout() assert.Equal(c, strings.Count(imagesAfter, "\n"), strings.Count(imagesBefore, "\n")+2, fmt.Sprintf("before: %q\n\nafter: %q\n", imagesBefore, imagesAfter)) } - dockerCmd(c, "rmi", "utest:5000/docker:tag3") + cli.DockerCmd(c, "rmi", "utest:5000/docker:tag3") { - imagesAfter, _ := dockerCmd(c, "images", "-a") + imagesAfter := cli.DockerCmd(c, "images", "-a").Stdout() assert.Equal(c, strings.Count(imagesAfter, "\n"), strings.Count(imagesBefore, "\n")+1, fmt.Sprintf("before: %q\n\nafter: %q\n", imagesBefore, imagesAfter)) } - dockerCmd(c, "rmi", "utest:tag1") + cli.DockerCmd(c, "rmi", "utest:tag1") { - imagesAfter, _ := dockerCmd(c, "images", "-a") + imagesAfter := cli.DockerCmd(c, "images", "-a").Stdout() assert.Equal(c, strings.Count(imagesAfter, "\n"), strings.Count(imagesBefore, "\n"), fmt.Sprintf("before: %q\n\nafter: %q\n", imagesBefore, imagesAfter)) } } func (s *DockerCLIRmiSuite) TestRmiImgIDMultipleTag(c *testing.T) { - out := cli.DockerCmd(c, "run", "-d", "busybox", "/bin/sh", "-c", "mkdir '/busybox-one'").Combined() - containerID := strings.TrimSpace(out) + cID := cli.DockerCmd(c, "run", "-d", "busybox", "/bin/sh", "-c", "mkdir '/busybox-one'").Combined() + cID = strings.TrimSpace(cID) // Wait for it to exit as cannot commit a running container on Windows, and // it will take a few seconds to exit if testEnv.DaemonInfo.OSType == "windows" { - cli.WaitExited(c, containerID, 60*time.Second) + cli.WaitExited(c, cID, 60*time.Second) } - cli.DockerCmd(c, "commit", containerID, "busybox-one") + cli.DockerCmd(c, "commit", cID, "busybox-one") imagesBefore := cli.DockerCmd(c, "images", "-a").Combined() cli.DockerCmd(c, "tag", "busybox-one", "busybox-one:tag1") @@ -96,17 +95,17 @@ func (s *DockerCLIRmiSuite) TestRmiImgIDMultipleTag(c *testing.T) { imgID := inspectField(c, "busybox-one:tag1", "Id") // run a container with the image - out = runSleepingContainerInImage(c, "busybox-one") - containerID = strings.TrimSpace(out) + cID = runSleepingContainerInImage(c, "busybox-one") + cID = strings.TrimSpace(cID) // first checkout without force it fails // rmi tagged in multiple repos should have failed without force cli.Docker(cli.Args("rmi", imgID)).Assert(c, icmd.Expected{ ExitCode: 1, - Err: fmt.Sprintf("conflict: unable to delete %s (cannot be forced) - image is being used by running container %s", stringid.TruncateID(imgID), stringid.TruncateID(containerID)), + Err: fmt.Sprintf("conflict: unable to delete %s (cannot be forced) - image is being used by running container %s", stringid.TruncateID(imgID), stringid.TruncateID(cID)), }) - cli.DockerCmd(c, "stop", containerID) + cli.DockerCmd(c, "stop", cID) cli.DockerCmd(c, "rmi", "-f", imgID) imagesAfter = cli.DockerCmd(c, "images", "-a").Combined() @@ -115,16 +114,16 @@ func (s *DockerCLIRmiSuite) TestRmiImgIDMultipleTag(c *testing.T) { } func (s *DockerCLIRmiSuite) TestRmiImgIDForce(c *testing.T) { - out := cli.DockerCmd(c, "run", "-d", "busybox", "/bin/sh", "-c", "mkdir '/busybox-test'").Combined() - containerID := strings.TrimSpace(out) + cID := cli.DockerCmd(c, "run", "-d", "busybox", "/bin/sh", "-c", "mkdir '/busybox-test'").Combined() + cID = strings.TrimSpace(cID) // Wait for it to exit as cannot commit a running container on Windows, and // it will take a few seconds to exit if testEnv.DaemonInfo.OSType == "windows" { - cli.WaitExited(c, containerID, 60*time.Second) + cli.WaitExited(c, cID, 60*time.Second) } - cli.DockerCmd(c, "commit", containerID, "busybox-test") + cli.DockerCmd(c, "commit", cID, "busybox-test") imagesBefore := cli.DockerCmd(c, "images", "-a").Combined() cli.DockerCmd(c, "tag", "busybox-test", "utest:tag1") @@ -158,7 +157,7 @@ func (s *DockerCLIRmiSuite) TestRmiImageIDForceWithRunningContainersAndMultipleT imgID := getIDByName(c, "test-14116") newTag := "newtag" - dockerCmd(c, "tag", imgID, newTag) + cli.DockerCmd(c, "tag", imgID, newTag) runSleepingContainerInImage(c, imgID) out, _, err := dockerCmdWithError("rmi", "-f", imgID) @@ -171,11 +170,11 @@ func (s *DockerCLIRmiSuite) TestRmiTagWithExistingContainers(c *testing.T) { container := "test-delete-tag" newtag := "busybox:newtag" bb := "busybox:latest" - dockerCmd(c, "tag", bb, newtag) + cli.DockerCmd(c, "tag", bb, newtag) - dockerCmd(c, "run", "--name", container, bb, "/bin/true") + cli.DockerCmd(c, "run", "--name", container, bb, "/bin/true") - out, _ := dockerCmd(c, "rmi", newtag) + out := cli.DockerCmd(c, "rmi", newtag).Combined() assert.Equal(c, strings.Count(out, "Untagged: "), 1) } @@ -188,22 +187,22 @@ func (s *DockerCLIRmiSuite) TestRmiForceWithExistingContainers(c *testing.T) { MAINTAINER foo`), }).Assert(c, icmd.Success) - dockerCmd(c, "run", "--name", "test-force-rmi", image, "/bin/true") + cli.DockerCmd(c, "run", "--name", "test-force-rmi", image, "/bin/true") - dockerCmd(c, "rmi", "-f", image) + cli.DockerCmd(c, "rmi", "-f", image) } func (s *DockerCLIRmiSuite) TestRmiWithMultipleRepositories(c *testing.T) { newRepo := "127.0.0.1:5000/busybox" oldRepo := "busybox" newTag := "busybox:test" - dockerCmd(c, "tag", oldRepo, newRepo) + cli.DockerCmd(c, "tag", oldRepo, newRepo) - dockerCmd(c, "run", "--name", "test", oldRepo, "touch", "/abcd") + cli.DockerCmd(c, "run", "--name", "test", oldRepo, "touch", "/abcd") - dockerCmd(c, "commit", "test", newTag) + cli.DockerCmd(c, "commit", "test", newTag) - out, _ := dockerCmd(c, "rmi", newTag) + out := cli.DockerCmd(c, "rmi", newTag).Combined() assert.Assert(c, strings.Contains(out, "Untagged: "+newTag)) } @@ -214,13 +213,13 @@ func (s *DockerCLIRmiSuite) TestRmiForceWithMultipleRepositories(c *testing.T) { buildImageSuccessfully(c, tag1, build.WithDockerfile(`FROM busybox MAINTAINER "docker"`)) - dockerCmd(c, "tag", tag1, tag2) + cli.DockerCmd(c, "tag", tag1, tag2) - out, _ := dockerCmd(c, "rmi", "-f", tag2) + out := cli.DockerCmd(c, "rmi", "-f", tag2).Combined() assert.Assert(c, strings.Contains(out, "Untagged: "+tag2)) assert.Assert(c, !strings.Contains(out, "Untagged: "+tag1)) // Check built image still exists - images, _ := dockerCmd(c, "images", "-a") + images := cli.DockerCmd(c, "images", "-a").Stdout() assert.Assert(c, strings.Contains(images, imageName), "Built image missing %q; Images: %q", imageName, images) } @@ -249,8 +248,8 @@ func (s *DockerCLIRmiSuite) TestRmiContainerImageNotFound(c *testing.T) { runSleepingContainerInImage(c, imageNames[0]) // Create a stopped container, and then force remove its image. - dockerCmd(c, "run", imageNames[1], "true") - dockerCmd(c, "rmi", "-f", imageIds[1]) + cli.DockerCmd(c, "run", imageNames[1], "true") + cli.DockerCmd(c, "rmi", "-f", imageIds[1]) // Try to remove the image of the running container and see if it fails as expected. out, _, err := dockerCmdWithError("rmi", "-f", imageIds[0]) @@ -270,35 +269,35 @@ RUN echo 1 #layer1 RUN echo 2 #layer2 ` buildImageSuccessfully(c, image, build.WithoutCache, build.WithDockerfile(dockerfile)) - out, _ := dockerCmd(c, "history", "-q", image) + out := cli.DockerCmd(c, "history", "-q", image).Stdout() ids := strings.Split(out, "\n") idToTag := ids[2] // Tag layer0 to "tmp2". newTag := "tmp2" - dockerCmd(c, "tag", idToTag, newTag) + cli.DockerCmd(c, "tag", idToTag, newTag) // Create a container based on "tmp1". - dockerCmd(c, "run", "-d", image, "true") + cli.DockerCmd(c, "run", "-d", image, "true") // See if the "tmp2" can be untagged. - out, _ = dockerCmd(c, "rmi", newTag) + out = cli.DockerCmd(c, "rmi", newTag).Combined() // Expected 1 untagged entry assert.Equal(c, strings.Count(out, "Untagged: "), 1, fmt.Sprintf("out: %s", out)) // Now let's add the tag again and create a container based on it. - dockerCmd(c, "tag", idToTag, newTag) - out, _ = dockerCmd(c, "run", "-d", newTag, "true") - cid := strings.TrimSpace(out) + cli.DockerCmd(c, "tag", idToTag, newTag) + cID := cli.DockerCmd(c, "run", "-d", newTag, "true").Stdout() + cID = strings.TrimSpace(cID) // At this point we have 2 containers, one based on layer2 and another based on layer0. // Try to untag "tmp2" without the -f flag. out, _, err := dockerCmdWithError("rmi", newTag) // should not be untagged without the -f flag assert.ErrorContains(c, err, "") - assert.Assert(c, strings.Contains(out, cid[:12])) + assert.Assert(c, strings.Contains(out, cID[:12])) assert.Assert(c, strings.Contains(out, "(must force)")) // Add the -f flag and test again. - out, _ = dockerCmd(c, "rmi", "-f", newTag) + out = cli.DockerCmd(c, "rmi", "-f", newTag).Combined() // should be allowed to untag with the -f flag assert.Assert(c, strings.Contains(out, fmt.Sprintf("Untagged: %s:latest", newTag))) } @@ -319,24 +318,24 @@ func (*DockerCLIRmiSuite) TestRmiParentImageFail(c *testing.T) { } func (s *DockerCLIRmiSuite) TestRmiWithParentInUse(c *testing.T) { - out, _ := dockerCmd(c, "create", "busybox") - cID := strings.TrimSpace(out) + cID := cli.DockerCmd(c, "create", "busybox").Stdout() + cID = strings.TrimSpace(cID) - out, _ = dockerCmd(c, "commit", cID) - imageID := strings.TrimSpace(out) + imageID := cli.DockerCmd(c, "commit", cID).Stdout() + imageID = strings.TrimSpace(imageID) - out, _ = dockerCmd(c, "create", imageID) - cID = strings.TrimSpace(out) + cID = cli.DockerCmd(c, "create", imageID).Stdout() + cID = strings.TrimSpace(cID) - out, _ = dockerCmd(c, "commit", cID) - imageID = strings.TrimSpace(out) + imageID = cli.DockerCmd(c, "commit", cID).Stdout() + imageID = strings.TrimSpace(imageID) - dockerCmd(c, "rmi", imageID) + cli.DockerCmd(c, "rmi", imageID) } // #18873 func (s *DockerCLIRmiSuite) TestRmiByIDHardConflict(c *testing.T) { - dockerCmd(c, "create", "busybox") + cli.DockerCmd(c, "create", "busybox") imgID := inspectField(c, "busybox:latest", "Id") diff --git a/integration-cli/docker_cli_run_test.go b/integration-cli/docker_cli_run_test.go index 0487a60a7c..c96a0f6a9b 100644 --- a/integration-cli/docker_cli_run_test.go +++ b/integration-cli/docker_cli_run_test.go @@ -54,7 +54,7 @@ func (s *DockerCLIRunSuite) OnTimeout(c *testing.T) { // "test123" should be printed by docker run func (s *DockerCLIRunSuite) TestRunEchoStdout(c *testing.T) { - out, _ := dockerCmd(c, "run", "busybox", "echo", "test123") + out := cli.DockerCmd(c, "run", "busybox", "echo", "test123").Combined() if out != "test123\n" { c.Fatalf("container should've printed 'test123', got '%s'", out) } @@ -62,7 +62,7 @@ func (s *DockerCLIRunSuite) TestRunEchoStdout(c *testing.T) { // "test" should be printed func (s *DockerCLIRunSuite) TestRunEchoNamedContainer(c *testing.T) { - out, _ := dockerCmd(c, "run", "--name", "testfoonamedcontainer", "busybox", "echo", "test") + out := cli.DockerCmd(c, "run", "--name", "testfoonamedcontainer", "busybox", "echo", "test").Combined() if out != "test\n" { c.Errorf("container should've printed 'test'") } @@ -72,7 +72,7 @@ func (s *DockerCLIRunSuite) TestRunEchoNamedContainer(c *testing.T) { // specific functionality and cannot run on Windows. func (s *DockerCLIRunSuite) TestRunLeakyFileDescriptors(c *testing.T) { testRequires(c, DaemonIsLinux) - out, _ := dockerCmd(c, "run", "busybox", "ls", "-C", "/proc/self/fd") + out := cli.DockerCmd(c, "run", "busybox", "ls", "-C", "/proc/self/fd").Combined() // normally, we should only get 0, 1, and 2, but 3 gets created by "ls" when it does "opendir" on the "fd" directory if out != "0 1 2 3\n" { @@ -87,15 +87,15 @@ func (s *DockerCLIRunSuite) TestRunLookupGoogleDNS(c *testing.T) { if testEnv.DaemonInfo.OSType == "windows" { // nslookup isn't present in Windows busybox. Is built-in. Further, // nslookup isn't present in nanoserver. Hence just use PowerShell... - dockerCmd(c, "run", testEnv.PlatformDefaults.BaseImage, "powershell", "Resolve-DNSName", "google.com") + cli.DockerCmd(c, "run", testEnv.PlatformDefaults.BaseImage, "powershell", "Resolve-DNSName", "google.com") } else { - dockerCmd(c, "run", "busybox", "nslookup", "google.com") + cli.DockerCmd(c, "run", "busybox", "nslookup", "google.com") } } // the exit code should be 0 func (s *DockerCLIRunSuite) TestRunExitCodeZero(c *testing.T) { - dockerCmd(c, "run", "busybox", "true") + cli.DockerCmd(c, "run", "busybox", "true") } // the exit code should be 1 @@ -117,30 +117,27 @@ func (s *DockerCLIRunSuite) TestRunStdinPipe(c *testing.T) { out := result.Stdout() out = strings.TrimSpace(out) - dockerCmd(c, "wait", out) + cli.DockerCmd(c, "wait", out) - logsOut, _ := dockerCmd(c, "logs", out) - - containerLogs := strings.TrimSpace(logsOut) + containerLogs := cli.DockerCmd(c, "logs", out).Combined() + containerLogs = strings.TrimSpace(containerLogs) if containerLogs != "blahblah" { c.Errorf("logs didn't print the container's logs %s", containerLogs) } - dockerCmd(c, "rm", out) + cli.DockerCmd(c, "rm", out) } // the container's ID should be printed when starting a container in detached mode func (s *DockerCLIRunSuite) TestRunDetachedContainerIDPrinting(c *testing.T) { - out, _ := dockerCmd(c, "run", "-d", "busybox", "true") - - out = strings.TrimSpace(out) - dockerCmd(c, "wait", out) - - rmOut, _ := dockerCmd(c, "rm", out) + id := cli.DockerCmd(c, "run", "-d", "busybox", "true").Stdout() + id = strings.TrimSpace(id) + cli.DockerCmd(c, "wait", id) + rmOut := cli.DockerCmd(c, "rm", id).Stdout() rmOut = strings.TrimSpace(rmOut) - if rmOut != out { - c.Errorf("rm didn't print the container ID %s %s", out, rmOut) + if rmOut != id { + c.Errorf("rm didn't print the container ID %s %s", id, rmOut) } } @@ -153,16 +150,14 @@ func (s *DockerCLIRunSuite) TestRunWorkingDirectory(c *testing.T) { } // First with -w - out, _ := dockerCmd(c, "run", "-w", dir, image, "pwd") - out = strings.TrimSpace(out) - if out != dir { + out := cli.DockerCmd(c, "run", "-w", dir, image, "pwd").Stdout() + if strings.TrimSpace(out) != dir { c.Errorf("-w failed to set working directory") } // Then with --workdir - out, _ = dockerCmd(c, "run", "--workdir", dir, image, "pwd") - out = strings.TrimSpace(out) - if out != dir { + out = cli.DockerCmd(c, "run", "--workdir", dir, image, "pwd").Stdout() + if strings.TrimSpace(out) != dir { c.Errorf("--workdir failed to set working directory") } } @@ -191,11 +186,11 @@ func (s *DockerCLIRunSuite) TestRunLinksContainerWithContainerName(c *testing.T) // TODO Windows: This test cannot run on a Windows daemon as the networking // settings are not populated back yet on inspect. testRequires(c, DaemonIsLinux) - dockerCmd(c, "run", "-i", "-t", "-d", "--name", "parent", "busybox") + cli.DockerCmd(c, "run", "-i", "-t", "-d", "--name", "parent", "busybox") ip := inspectField(c, "parent", "NetworkSettings.Networks.bridge.IPAddress") - out, _ := dockerCmd(c, "run", "--link", "parent:test", "busybox", "/bin/cat", "/etc/hosts") + out := cli.DockerCmd(c, "run", "--link", "parent:test", "busybox", "/bin/cat", "/etc/hosts").Combined() if !strings.Contains(out, ip+" test") { c.Fatalf("use a container name to link target failed") } @@ -206,12 +201,11 @@ func (s *DockerCLIRunSuite) TestRunLinksContainerWithContainerID(c *testing.T) { // TODO Windows: This test cannot run on a Windows daemon as the networking // settings are not populated back yet on inspect. testRequires(c, DaemonIsLinux) - cID, _ := dockerCmd(c, "run", "-i", "-t", "-d", "busybox") - + cID := cli.DockerCmd(c, "run", "-i", "-t", "-d", "busybox").Stdout() cID = strings.TrimSpace(cID) ip := inspectField(c, cID, "NetworkSettings.Networks.bridge.IPAddress") - out, _ := dockerCmd(c, "run", "--link", cID+":test", "busybox", "/bin/cat", "/etc/hosts") + out := cli.DockerCmd(c, "run", "--link", cID+":test", "busybox", "/bin/cat", "/etc/hosts").Combined() if !strings.Contains(out, ip+" test") { c.Fatalf("use a container id to link target failed") } @@ -219,16 +213,15 @@ func (s *DockerCLIRunSuite) TestRunLinksContainerWithContainerID(c *testing.T) { func (s *DockerCLIRunSuite) TestUserDefinedNetworkLinks(c *testing.T) { testRequires(c, DaemonIsLinux, NotUserNamespace) - dockerCmd(c, "network", "create", "-d", "bridge", "udlinkNet") + cli.DockerCmd(c, "network", "create", "-d", "bridge", "udlinkNet") - dockerCmd(c, "run", "-d", "--net=udlinkNet", "--name=first", "busybox", "top") - assert.Assert(c, waitRun("first") == nil) + cli.DockerCmd(c, "run", "-d", "--net=udlinkNet", "--name=first", "busybox", "top") + cli.WaitRun(c, "first") // run a container in user-defined network udlinkNet with a link for an existing container // and a link for a container that doesn't exist - dockerCmd(c, "run", "-d", "--net=udlinkNet", "--name=second", "--link=first:foo", - "--link=third:bar", "busybox", "top") - assert.Assert(c, waitRun("second") == nil) + cli.DockerCmd(c, "run", "-d", "--net=udlinkNet", "--name=second", "--link=first:foo", "--link=third:bar", "busybox", "top") + cli.WaitRun(c, "second") // ping to first and its alias foo must succeed _, _, err := dockerCmdWithError("exec", "second", "ping", "-c", "1", "first") @@ -243,8 +236,8 @@ func (s *DockerCLIRunSuite) TestUserDefinedNetworkLinks(c *testing.T) { assert.ErrorContains(c, err, "") // start third container now - dockerCmd(c, "run", "-d", "--net=udlinkNet", "--name=third", "busybox", "top") - assert.Assert(c, waitRun("third") == nil) + cli.DockerCmd(c, "run", "-d", "--net=udlinkNet", "--name=third", "busybox", "top") + cli.WaitRun(c, "third") // ping to third and its alias must succeed now _, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "third") @@ -255,14 +248,13 @@ func (s *DockerCLIRunSuite) TestUserDefinedNetworkLinks(c *testing.T) { func (s *DockerCLIRunSuite) TestUserDefinedNetworkLinksWithRestart(c *testing.T) { testRequires(c, DaemonIsLinux, NotUserNamespace) - dockerCmd(c, "network", "create", "-d", "bridge", "udlinkNet") + cli.DockerCmd(c, "network", "create", "-d", "bridge", "udlinkNet") - dockerCmd(c, "run", "-d", "--net=udlinkNet", "--name=first", "busybox", "top") - assert.Assert(c, waitRun("first") == nil) + cli.DockerCmd(c, "run", "-d", "--net=udlinkNet", "--name=first", "busybox", "top") + cli.WaitRun(c, "first") - dockerCmd(c, "run", "-d", "--net=udlinkNet", "--name=second", "--link=first:foo", - "busybox", "top") - assert.Assert(c, waitRun("second") == nil) + cli.DockerCmd(c, "run", "-d", "--net=udlinkNet", "--name=second", "--link=first:foo", "busybox", "top") + cli.WaitRun(c, "second") // ping to first and its alias foo must succeed _, _, err := dockerCmdWithError("exec", "second", "ping", "-c", "1", "first") @@ -271,8 +263,8 @@ func (s *DockerCLIRunSuite) TestUserDefinedNetworkLinksWithRestart(c *testing.T) assert.NilError(c, err) // Restart first container - dockerCmd(c, "restart", "first") - assert.Assert(c, waitRun("first") == nil) + cli.DockerCmd(c, "restart", "first") + cli.WaitRun(c, "first") // ping to first and its alias foo must still succeed _, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "first") @@ -281,8 +273,8 @@ func (s *DockerCLIRunSuite) TestUserDefinedNetworkLinksWithRestart(c *testing.T) assert.NilError(c, err) // Restart second container - dockerCmd(c, "restart", "second") - assert.Assert(c, waitRun("second") == nil) + cli.DockerCmd(c, "restart", "second") + cli.WaitRun(c, "second") // ping to first and its alias foo must still succeed _, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "first") @@ -295,8 +287,8 @@ func (s *DockerCLIRunSuite) TestRunWithNetAliasOnDefaultNetworks(c *testing.T) { testRequires(c, DaemonIsLinux, NotUserNamespace) defaults := []string{"bridge", "host", "none"} - for _, net := range defaults { - out, _, err := dockerCmdWithError("run", "-d", "--net", net, "--net-alias", "alias_"+net, "busybox", "top") + for _, nw := range defaults { + out, _, err := dockerCmdWithError("run", "-d", "--net", nw, "--net-alias", "alias_"+nw, "busybox", "top") assert.ErrorContains(c, err, "") assert.Assert(c, strings.Contains(out, runconfig.ErrUnsupportedNetworkAndAlias.Error())) } @@ -304,17 +296,17 @@ func (s *DockerCLIRunSuite) TestRunWithNetAliasOnDefaultNetworks(c *testing.T) { func (s *DockerCLIRunSuite) TestUserDefinedNetworkAlias(c *testing.T) { testRequires(c, DaemonIsLinux, NotUserNamespace) - dockerCmd(c, "network", "create", "-d", "bridge", "net1") + cli.DockerCmd(c, "network", "create", "-d", "bridge", "net1") - cid1, _ := dockerCmd(c, "run", "-d", "--net=net1", "--name=first", "--net-alias=foo1", "--net-alias=foo2", "busybox:glibc", "top") - assert.Assert(c, waitRun("first") == nil) + cid1 := cli.DockerCmd(c, "run", "-d", "--net=net1", "--name=first", "--net-alias=foo1", "--net-alias=foo2", "busybox:glibc", "top").Stdout() + cli.WaitRun(c, "first") // Check if default short-id alias is added automatically id := strings.TrimSpace(cid1) aliases := inspectField(c, id, "NetworkSettings.Networks.net1.Aliases") assert.Assert(c, strings.Contains(aliases, stringid.TruncateID(id))) - cid2, _ := dockerCmd(c, "run", "-d", "--net=net1", "--name=second", "busybox:glibc", "top") - assert.Assert(c, waitRun("second") == nil) + cid2 := cli.DockerCmd(c, "run", "-d", "--net=net1", "--name=second", "busybox:glibc", "top").Stdout() + cli.WaitRun(c, "second") // Check if default short-id alias is added automatically id = strings.TrimSpace(cid2) @@ -332,8 +324,8 @@ func (s *DockerCLIRunSuite) TestUserDefinedNetworkAlias(c *testing.T) { assert.NilError(c, err) // Restart first container - dockerCmd(c, "restart", "first") - assert.Assert(c, waitRun("first") == nil) + cli.DockerCmd(c, "restart", "first") + cli.WaitRun(c, "first") // ping to first and its network-scoped aliases must succeed _, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "first") @@ -356,29 +348,26 @@ func (s *DockerCLIRunSuite) TestRunWithDaemonFlags(c *testing.T) { // Regression test for #4979 func (s *DockerCLIRunSuite) TestRunWithVolumesFromExited(c *testing.T) { - var ( - out string - exitCode int - ) + var result *icmd.Result // Create a file in a volume if testEnv.DaemonInfo.OSType == "windows" { - out, exitCode = dockerCmd(c, "run", "--name", "test-data", "--volume", `c:\some\dir`, testEnv.PlatformDefaults.BaseImage, "cmd", "/c", `echo hello > c:\some\dir\file`) + result = cli.DockerCmd(c, "run", "--name", "test-data", "--volume", `c:\some\dir`, testEnv.PlatformDefaults.BaseImage, "cmd", "/c", `echo hello > c:\some\dir\file`) } else { - out, exitCode = dockerCmd(c, "run", "--name", "test-data", "--volume", "/some/dir", "busybox", "touch", "/some/dir/file") + result = cli.DockerCmd(c, "run", "--name", "test-data", "--volume", "/some/dir", "busybox", "touch", "/some/dir/file") } - if exitCode != 0 { - c.Fatal("1", out, exitCode) + if result.ExitCode != 0 { + c.Fatal("1", result.Combined(), result.ExitCode) } // Read the file from another container using --volumes-from to access the volume in the second container if testEnv.DaemonInfo.OSType == "windows" { - out, exitCode = dockerCmd(c, "run", "--volumes-from", "test-data", testEnv.PlatformDefaults.BaseImage, "cmd", "/c", `type c:\some\dir\file`) + result = cli.DockerCmd(c, "run", "--volumes-from", "test-data", testEnv.PlatformDefaults.BaseImage, "cmd", "/c", `type c:\some\dir\file`) } else { - out, exitCode = dockerCmd(c, "run", "--volumes-from", "test-data", "busybox", "cat", "/some/dir/file") + result = cli.DockerCmd(c, "run", "--volumes-from", "test-data", "busybox", "cat", "/some/dir/file") } - if exitCode != 0 { - c.Fatal("2", out, exitCode) + if result.ExitCode != 0 { + c.Fatal("2", result.Combined(), result.ExitCode) } } @@ -424,7 +413,7 @@ func (s *DockerCLIRunSuite) TestRunCreateVolumesInSymlinkDir(c *testing.T) { cmd = "true" } buildImageSuccessfully(c, name, build.WithDockerfile(dockerFile)) - dockerCmd(c, "run", "-v", containerPath, name, cmd) + cli.DockerCmd(c, "run", "-v", containerPath, name, cmd) } // Volume path is a symlink in the container @@ -449,7 +438,7 @@ func (s *DockerCLIRunSuite) TestRunCreateVolumesInSymlinkDir2(c *testing.T) { cmd = "true" } buildImageSuccessfully(c, name, build.WithDockerfile(dockerFile)) - dockerCmd(c, "run", "-v", containerPath, name, cmd) + cli.DockerCmd(c, "run", "-v", containerPath, name, cmd) } func (s *DockerCLIRunSuite) TestRunVolumesMountedAsReadonly(c *testing.T) { @@ -471,7 +460,7 @@ func (s *DockerCLIRunSuite) TestRunVolumesFromInReadonlyModeFails(c *testing.T) volumeDir = "/test" fileInVol = `/test/file` } - dockerCmd(c, "run", "--name", "parent", "-v", volumeDir, "busybox", "true") + cli.DockerCmd(c, "run", "--name", "parent", "-v", volumeDir, "busybox", "true") if _, code, err := dockerCmdWithError("run", "--volumes-from", "parent:ro", "busybox", "touch", fileInVol); err == nil || code == 0 { c.Fatalf("run should fail because volume is ro: exit code %d", code) @@ -492,14 +481,14 @@ func (s *DockerCLIRunSuite) TestRunVolumesFromInReadWriteMode(c *testing.T) { fileInVol = "/test/file" } - dockerCmd(c, "run", "--name", "parent", "-v", volumeDir, "busybox", "true") - dockerCmd(c, "run", "--volumes-from", "parent:rw", "busybox", "touch", fileInVol) + cli.DockerCmd(c, "run", "--name", "parent", "-v", volumeDir, "busybox", "true") + cli.DockerCmd(c, "run", "--volumes-from", "parent:rw", "busybox", "touch", fileInVol) if out, _, err := dockerCmdWithError("run", "--volumes-from", "parent:bar", "busybox", "touch", fileInVol); err == nil || !strings.Contains(out, `invalid mode: bar`) { c.Fatalf("running --volumes-from parent:bar should have failed with invalid mode: %q", out) } - dockerCmd(c, "run", "--volumes-from", "parent", "busybox", "touch", fileInVol) + cli.DockerCmd(c, "run", "--volumes-from", "parent", "busybox", "touch", fileInVol) } func (s *DockerCLIRunSuite) TestVolumesFromGetsProperMode(c *testing.T) { @@ -511,14 +500,14 @@ func (s *DockerCLIRunSuite) TestVolumesFromGetsProperMode(c *testing.T) { } defer os.RemoveAll(hostpath) - dockerCmd(c, "run", "--name", "parent", "-v", hostpath+":"+prefix+slash+"test:ro", "busybox", "true") + cli.DockerCmd(c, "run", "--name", "parent", "-v", hostpath+":"+prefix+slash+"test:ro", "busybox", "true") // Expect this "rw" mode to be be ignored since the inherited volume is "ro" if _, _, err := dockerCmdWithError("run", "--volumes-from", "parent:rw", "busybox", "touch", prefix+slash+"test"+slash+"file"); err == nil { c.Fatal("Expected volumes-from to inherit read-only volume even when passing in `rw`") } - dockerCmd(c, "run", "--name", "parent2", "-v", hostpath+":"+prefix+slash+"test:ro", "busybox", "true") + cli.DockerCmd(c, "run", "--name", "parent2", "-v", hostpath+":"+prefix+slash+"test:ro", "busybox", "true") // Expect this to be read-only since both are "ro" if _, _, err := dockerCmdWithError("run", "--volumes-from", "parent2:ro", "busybox", "touch", prefix+slash+"test"+slash+"file"); err == nil { @@ -570,11 +559,11 @@ func (s *DockerCLIRunSuite) TestRunNoDupVolumes(c *testing.T) { } // create failed should have create volume volumename1 or volumename2 // we should remove volumename2 or volumename2 successfully - out, _ := dockerCmd(c, "volume", "ls") + out := cli.DockerCmd(c, "volume", "ls").Stdout() if strings.Contains(out, volumename1) { - dockerCmd(c, "volume", "rm", volumename1) + cli.DockerCmd(c, "volume", "rm", volumename1) } else { - dockerCmd(c, "volume", "rm", volumename2) + cli.DockerCmd(c, "volume", "rm", volumename2) } } @@ -584,8 +573,8 @@ func (s *DockerCLIRunSuite) TestRunApplyVolumesFromBeforeVolumes(c *testing.T) { if testEnv.DaemonInfo.OSType == "windows" { prefix = `c:` } - dockerCmd(c, "run", "--name", "parent", "-v", prefix+"/test", "busybox", "touch", prefix+"/test/foo") - dockerCmd(c, "run", "--volumes-from", "parent", "-v", prefix+"/test", "busybox", "cat", prefix+"/test/foo") + cli.DockerCmd(c, "run", "--name", "parent", "-v", prefix+"/test", "busybox", "touch", prefix+"/test/foo") + cli.DockerCmd(c, "run", "--volumes-from", "parent", "-v", prefix+"/test", "busybox", "cat", prefix+"/test/foo") } func (s *DockerCLIRunSuite) TestRunMultipleVolumesFrom(c *testing.T) { @@ -593,9 +582,9 @@ func (s *DockerCLIRunSuite) TestRunMultipleVolumesFrom(c *testing.T) { if testEnv.DaemonInfo.OSType == "windows" { prefix = `c:` } - dockerCmd(c, "run", "--name", "parent1", "-v", prefix+"/test", "busybox", "touch", prefix+"/test/foo") - dockerCmd(c, "run", "--name", "parent2", "-v", prefix+"/other", "busybox", "touch", prefix+"/other/bar") - dockerCmd(c, "run", "--volumes-from", "parent1", "--volumes-from", "parent2", "busybox", "sh", "-c", "cat /test/foo && cat /other/bar") + cli.DockerCmd(c, "run", "--name", "parent1", "-v", prefix+"/test", "busybox", "touch", prefix+"/test/foo") + cli.DockerCmd(c, "run", "--name", "parent2", "-v", prefix+"/other", "busybox", "touch", prefix+"/other/bar") + cli.DockerCmd(c, "run", "--volumes-from", "parent1", "--volumes-from", "parent2", "busybox", "sh", "-c", "cat /test/foo && cat /other/bar") } // this tests verifies the ID format for the container @@ -623,7 +612,7 @@ func (s *DockerCLIRunSuite) TestRunCreateVolume(c *testing.T) { if testEnv.DaemonInfo.OSType == "windows" { prefix = `c:` } - dockerCmd(c, "run", "-v", prefix+"/var/lib/data", "busybox", "true") + cli.DockerCmd(c, "run", "-v", prefix+"/var/lib/data", "busybox", "true") } // Test that creating a volume with a symlink in its path works correctly. Test for #5152. @@ -726,7 +715,7 @@ func (s *DockerCLIRunSuite) TestRunUserDefaults(c *testing.T) { if testEnv.DaemonInfo.OSType == "windows" { expected = "uid=0(root) gid=0(root) groups=0(root)" } - out, _ := dockerCmd(c, "run", "busybox", "id") + out := cli.DockerCmd(c, "run", "busybox", "id").Stdout() if !strings.Contains(out, expected) { c.Fatalf("expected '%s' got %s", expected, out) } @@ -736,7 +725,7 @@ func (s *DockerCLIRunSuite) TestRunUserByName(c *testing.T) { // TODO Windows: This test cannot run on a Windows daemon as Windows does // not support the use of -u testRequires(c, DaemonIsLinux) - out, _ := dockerCmd(c, "run", "-u", "root", "busybox", "id") + out := cli.DockerCmd(c, "run", "-u", "root", "busybox", "id").Stdout() if !strings.Contains(out, "uid=0(root) gid=0(root)") { c.Fatalf("expected root user got %s", out) } @@ -746,7 +735,7 @@ func (s *DockerCLIRunSuite) TestRunUserByID(c *testing.T) { // TODO Windows: This test cannot run on a Windows daemon as Windows does // not support the use of -u testRequires(c, DaemonIsLinux) - out, _ := dockerCmd(c, "run", "-u", "1", "busybox", "id") + out := cli.DockerCmd(c, "run", "-u", "1", "busybox", "id").Stdout() if !strings.Contains(out, "uid=1(daemon) gid=1(daemon)") { c.Fatalf("expected daemon user got %s", out) } @@ -931,9 +920,9 @@ func (s *DockerCLIRunSuite) TestRunEnvironmentOverride(c *testing.T) { func (s *DockerCLIRunSuite) TestRunContainerNetwork(c *testing.T) { if testEnv.DaemonInfo.OSType == "windows" { // Windows busybox does not have ping. Use built in ping instead. - dockerCmd(c, "run", testEnv.PlatformDefaults.BaseImage, "ping", "-n", "1", "127.0.0.1") + cli.DockerCmd(c, "run", testEnv.PlatformDefaults.BaseImage, "ping", "-n", "1", "127.0.0.1") } else { - dockerCmd(c, "run", "busybox", "ping", "-c", "1", "127.0.0.1") + cli.DockerCmd(c, "run", "busybox", "ping", "-c", "1", "127.0.0.1") } } @@ -941,7 +930,7 @@ func (s *DockerCLIRunSuite) TestRunNetHostNotAllowedWithLinks(c *testing.T) { // TODO Windows: This is Linux specific as --link is not supported and // this will be deprecated in favor of container networking model. testRequires(c, DaemonIsLinux, NotUserNamespace) - dockerCmd(c, "run", "--name", "linked", "busybox", "true") + cli.DockerCmd(c, "run", "--name", "linked", "busybox", "true") _, _, err := dockerCmdWithError("run", "--net=host", "--link", "linked:linked", "busybox", "true") if err == nil { @@ -957,7 +946,7 @@ func (s *DockerCLIRunSuite) TestRunNetHostNotAllowedWithLinks(c *testing.T) { func (s *DockerCLIRunSuite) TestRunFullHostnameSet(c *testing.T) { // TODO Windows: -h is not yet functional. testRequires(c, DaemonIsLinux) - out, _ := dockerCmd(c, "run", "-h", "foo.bar.baz", "busybox", "hostname") + out := cli.DockerCmd(c, "run", "-h", "foo.bar.baz", "busybox", "hostname").Combined() if actual := strings.Trim(out, "\r\n"); actual != "foo.bar.baz" { c.Fatalf("expected hostname 'foo.bar.baz', received %s", actual) } @@ -967,7 +956,7 @@ func (s *DockerCLIRunSuite) TestRunPrivilegedCanMknod(c *testing.T) { // Not applicable for Windows as Windows daemon does not support // the concept of --privileged, and mknod is a Unix concept. testRequires(c, DaemonIsLinux, NotUserNamespace) - out, _ := dockerCmd(c, "run", "--privileged", "busybox", "sh", "-c", "mknod /tmp/sda b 8 0 && echo ok") + out := cli.DockerCmd(c, "run", "--privileged", "busybox", "sh", "-c", "mknod /tmp/sda b 8 0 && echo ok").Combined() if actual := strings.Trim(out, "\r\n"); actual != "ok" { c.Fatalf("expected output ok received %s", actual) } @@ -977,7 +966,7 @@ func (s *DockerCLIRunSuite) TestRunUnprivilegedCanMknod(c *testing.T) { // Not applicable for Windows as Windows daemon does not support // the concept of --privileged, and mknod is a Unix concept. testRequires(c, DaemonIsLinux, NotUserNamespace) - out, _ := dockerCmd(c, "run", "busybox", "sh", "-c", "mknod /tmp/sda b 8 0 && echo ok") + out := cli.DockerCmd(c, "run", "busybox", "sh", "-c", "mknod /tmp/sda b 8 0 && echo ok").Combined() if actual := strings.Trim(out, "\r\n"); actual != "ok" { c.Fatalf("expected output ok received %s", actual) } @@ -1033,7 +1022,7 @@ func (s *DockerCLIRunSuite) TestRunCapDropALLCannotMknod(c *testing.T) { func (s *DockerCLIRunSuite) TestRunCapDropALLAddMknodCanMknod(c *testing.T) { // Not applicable for Windows as there is no concept of --cap-drop or mknod testRequires(c, DaemonIsLinux, NotUserNamespace) - out, _ := dockerCmd(c, "run", "--cap-drop=ALL", "--cap-add=MKNOD", "--cap-add=SETGID", "busybox", "sh", "-c", "mknod /tmp/sda b 8 0 && echo ok") + out := cli.DockerCmd(c, "run", "--cap-drop=ALL", "--cap-add=MKNOD", "--cap-add=SETGID", "busybox", "sh", "-c", "mknod /tmp/sda b 8 0 && echo ok").Combined() if actual := strings.Trim(out, "\r\n"); actual != "ok" { c.Fatalf("expected output ok received %s", actual) @@ -1052,7 +1041,7 @@ func (s *DockerCLIRunSuite) TestRunCapAddInvalid(c *testing.T) { func (s *DockerCLIRunSuite) TestRunCapAddCanDownInterface(c *testing.T) { // Not applicable for Windows as there is no concept of --cap-add testRequires(c, DaemonIsLinux) - out, _ := dockerCmd(c, "run", "--cap-add=NET_ADMIN", "busybox", "sh", "-c", "ip link set eth0 down && echo ok") + out := cli.DockerCmd(c, "run", "--cap-add=NET_ADMIN", "busybox", "sh", "-c", "ip link set eth0 down && echo ok").Combined() if actual := strings.Trim(out, "\r\n"); actual != "ok" { c.Fatalf("expected output ok received %s", actual) @@ -1062,7 +1051,7 @@ func (s *DockerCLIRunSuite) TestRunCapAddCanDownInterface(c *testing.T) { func (s *DockerCLIRunSuite) TestRunCapAddALLCanDownInterface(c *testing.T) { // Not applicable for Windows as there is no concept of --cap-add testRequires(c, DaemonIsLinux) - out, _ := dockerCmd(c, "run", "--cap-add=ALL", "busybox", "sh", "-c", "ip link set eth0 down && echo ok") + out := cli.DockerCmd(c, "run", "--cap-add=ALL", "busybox", "sh", "-c", "ip link set eth0 down && echo ok").Combined() if actual := strings.Trim(out, "\r\n"); actual != "ok" { c.Fatalf("expected output ok received %s", actual) @@ -1084,7 +1073,7 @@ func (s *DockerCLIRunSuite) TestRunCapAddALLDropNetAdminCanDownInterface(c *test func (s *DockerCLIRunSuite) TestRunGroupAdd(c *testing.T) { // Not applicable for Windows as there is no concept of --group-add testRequires(c, DaemonIsLinux) - out, _ := dockerCmd(c, "run", "--group-add=audio", "--group-add=staff", "--group-add=777", "busybox", "sh", "-c", "id") + out := cli.DockerCmd(c, "run", "--group-add=audio", "--group-add=staff", "--group-add=777", "busybox", "sh", "-c", "id").Combined() groupsList := "uid=0(root) gid=0(root) groups=0(root),10(wheel),29(audio),50(staff),777" if actual := strings.Trim(out, "\r\n"); actual != groupsList { @@ -1095,7 +1084,7 @@ func (s *DockerCLIRunSuite) TestRunGroupAdd(c *testing.T) { func (s *DockerCLIRunSuite) TestRunPrivilegedCanMount(c *testing.T) { // Not applicable for Windows as there is no concept of --privileged testRequires(c, DaemonIsLinux, NotUserNamespace) - out, _ := dockerCmd(c, "run", "--privileged", "busybox", "sh", "-c", "mount -t tmpfs none /tmp && echo ok") + out := cli.DockerCmd(c, "run", "--privileged", "busybox", "sh", "-c", "mount -t tmpfs none /tmp && echo ok").Combined() if actual := strings.Trim(out, "\r\n"); actual != "ok" { c.Fatalf("expected output ok received %s", actual) @@ -1142,7 +1131,7 @@ func (s *DockerCLIRunSuite) TestRunProcNotWritableInNonPrivilegedContainers(c *t func (s *DockerCLIRunSuite) TestRunProcWritableInPrivilegedContainers(c *testing.T) { // Not applicable for Windows as there is no concept of --privileged testRequires(c, DaemonIsLinux, NotUserNamespace) - if _, code := dockerCmd(c, "run", "--privileged", "busybox", "sh", "-c", "touch /proc/sysrq-trigger"); code != 0 { + if result := cli.DockerCmd(c, "run", "--privileged", "busybox", "sh", "-c", "touch /proc/sysrq-trigger"); result.ExitCode != 0 { c.Fatalf("proc should be writable in privileged container") } } @@ -1151,7 +1140,7 @@ func (s *DockerCLIRunSuite) TestRunDeviceNumbers(c *testing.T) { // Not applicable on Windows as /dev/ is a Unix specific concept // TODO: NotUserNamespace could be removed here if "root" "root" is replaced w user testRequires(c, DaemonIsLinux, NotUserNamespace) - out, _ := dockerCmd(c, "run", "busybox", "sh", "-c", "ls -l /dev/null") + out := cli.DockerCmd(c, "run", "busybox", "sh", "-c", "ls -l /dev/null").Combined() deviceLineFields := strings.Fields(out) deviceLineFields[6] = "" deviceLineFields[7] = "" @@ -1166,7 +1155,7 @@ func (s *DockerCLIRunSuite) TestRunDeviceNumbers(c *testing.T) { func (s *DockerCLIRunSuite) TestRunThatCharacterDevicesActLikeCharacterDevices(c *testing.T) { // Not applicable on Windows as /dev/ is a Unix specific concept testRequires(c, DaemonIsLinux) - out, _ := dockerCmd(c, "run", "busybox", "sh", "-c", "dd if=/dev/zero of=/zero bs=1k count=5 2> /dev/null ; du -h /zero") + out := cli.DockerCmd(c, "run", "busybox", "sh", "-c", "dd if=/dev/zero of=/zero bs=1k count=5 2> /dev/null ; du -h /zero").Combined() if actual := strings.Trim(out, "\r\n"); actual[0] == '0' { c.Fatalf("expected a new file called /zero to be create that is greater than 0 bytes long, but du says: %s", actual) } @@ -1175,13 +1164,13 @@ func (s *DockerCLIRunSuite) TestRunThatCharacterDevicesActLikeCharacterDevices(c func (s *DockerCLIRunSuite) TestRunUnprivilegedWithChroot(c *testing.T) { // Not applicable on Windows as it does not support chroot testRequires(c, DaemonIsLinux) - dockerCmd(c, "run", "busybox", "chroot", "/", "true") + cli.DockerCmd(c, "run", "busybox", "chroot", "/", "true") } func (s *DockerCLIRunSuite) TestRunAddingOptionalDevices(c *testing.T) { // Not applicable on Windows as Windows does not support --device testRequires(c, DaemonIsLinux, NotUserNamespace) - out, _ := dockerCmd(c, "run", "--device", "/dev/zero:/dev/nulo", "busybox", "sh", "-c", "ls /dev/nulo") + out := cli.DockerCmd(c, "run", "--device", "/dev/zero:/dev/nulo", "busybox", "sh", "-c", "ls /dev/nulo").Combined() if actual := strings.Trim(out, "\r\n"); actual != "/dev/nulo" { c.Fatalf("expected output /dev/nulo, received %s", actual) } @@ -1190,7 +1179,7 @@ func (s *DockerCLIRunSuite) TestRunAddingOptionalDevices(c *testing.T) { func (s *DockerCLIRunSuite) TestRunAddingOptionalDevicesNoSrc(c *testing.T) { // Not applicable on Windows as Windows does not support --device testRequires(c, DaemonIsLinux, NotUserNamespace) - out, _ := dockerCmd(c, "run", "--device", "/dev/zero:rw", "busybox", "sh", "-c", "ls /dev/zero") + out := cli.DockerCmd(c, "run", "--device", "/dev/zero:rw", "busybox", "sh", "-c", "ls /dev/zero").Combined() if actual := strings.Trim(out, "\r\n"); actual != "/dev/zero" { c.Fatalf("expected output /dev/zero, received %s", actual) } @@ -1209,13 +1198,13 @@ func (s *DockerCLIRunSuite) TestRunModeHostname(c *testing.T) { // Not applicable on Windows as Windows does not support -h testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux, NotUserNamespace) - out, _ := dockerCmd(c, "run", "-h=testhostname", "busybox", "cat", "/etc/hostname") + out := cli.DockerCmd(c, "run", "-h=testhostname", "busybox", "cat", "/etc/hostname").Combined() if actual := strings.Trim(out, "\r\n"); actual != "testhostname" { c.Fatalf("expected 'testhostname', but says: %q", actual) } - out, _ = dockerCmd(c, "run", "--net=host", "busybox", "cat", "/etc/hostname") + out = cli.DockerCmd(c, "run", "--net=host", "busybox", "cat", "/etc/hostname").Combined() hostname, err := os.Hostname() if err != nil { @@ -1227,7 +1216,7 @@ func (s *DockerCLIRunSuite) TestRunModeHostname(c *testing.T) { } func (s *DockerCLIRunSuite) TestRunRootWorkdir(c *testing.T) { - out, _ := dockerCmd(c, "run", "--workdir", "/", "busybox", "pwd") + out := cli.DockerCmd(c, "run", "--workdir", "/", "busybox", "pwd").Combined() expected := "/\n" if testEnv.DaemonInfo.OSType == "windows" { expected = "C:" + expected @@ -1240,9 +1229,9 @@ func (s *DockerCLIRunSuite) TestRunRootWorkdir(c *testing.T) { func (s *DockerCLIRunSuite) TestRunAllowBindMountingRoot(c *testing.T) { if testEnv.DaemonInfo.OSType == "windows" { // Windows busybox will fail with Permission Denied on items such as pagefile.sys - dockerCmd(c, "run", "-v", `c:\:c:\host`, testEnv.PlatformDefaults.BaseImage, "cmd", "-c", "dir", `c:\host`) + cli.DockerCmd(c, "run", "-v", `c:\:c:\host`, testEnv.PlatformDefaults.BaseImage, "cmd", "-c", "dir", `c:\host`) } else { - dockerCmd(c, "run", "-v", "/:/host", "busybox", "ls", "/host") + cli.DockerCmd(c, "run", "-v", "/:/host", "busybox", "ls", "/host") } } @@ -1284,7 +1273,7 @@ func (s *DockerCLIRunSuite) TestRunDNSDefaultOptions(c *testing.T) { c.Fatal(err) } - actual, _ := dockerCmd(c, "run", "busybox", "cat", "/etc/resolv.conf") + actual := cli.DockerCmd(c, "run", "busybox", "cat", "/etc/resolv.conf").Combined() // check that the actual defaults are appended to the commented out // localhost resolver (which should be preserved) // NOTE: if we ever change the defaults from google dns, this will break @@ -1340,8 +1329,7 @@ func (s *DockerCLIRunSuite) TestRunDNSOptionsBasedOnHostResolvConf(c *testing.T) hostNameservers := resolvconf.GetNameservers(origResolvConf, resolvconf.IP) hostSearch := resolvconf.GetSearchDomains(origResolvConf) - var out string - out, _ = dockerCmd(c, "run", "--dns=127.0.0.1", "busybox", "cat", "/etc/resolv.conf") + out := cli.DockerCmd(c, "run", "--dns=127.0.0.1", "busybox", "cat", "/etc/resolv.conf").Combined() if actualNameservers := resolvconf.GetNameservers([]byte(out), resolvconf.IP); actualNameservers[0] != "127.0.0.1" { c.Fatalf("expected '127.0.0.1', but says: %q", actualNameservers[0]) @@ -1357,7 +1345,7 @@ func (s *DockerCLIRunSuite) TestRunDNSOptionsBasedOnHostResolvConf(c *testing.T) } } - out, _ = dockerCmd(c, "run", "--dns-search=mydomain", "busybox", "cat", "/etc/resolv.conf") + out = cli.DockerCmd(c, "run", "--dns-search=mydomain", "busybox", "cat", "/etc/resolv.conf").Combined() actualNameservers := resolvconf.GetNameservers([]byte(out), resolvconf.IP) if len(actualNameservers) != len(hostNameservers) { @@ -1392,7 +1380,7 @@ func (s *DockerCLIRunSuite) TestRunDNSOptionsBasedOnHostResolvConf(c *testing.T) hostSearch = resolvconf.GetSearchDomains(resolvConf) - out, _ = dockerCmd(c, "run", "busybox", "cat", "/etc/resolv.conf") + out = cli.DockerCmd(c, "run", "busybox", "cat", "/etc/resolv.conf").Combined() if actualNameservers = resolvconf.GetNameservers([]byte(out), resolvconf.IP); actualNameservers[0] != "12.34.56.78" || len(actualNameservers) != 1 { c.Fatalf("expected '12.34.56.78', but has: %v", actualNameservers) } @@ -1414,7 +1402,7 @@ func (s *DockerCLIRunSuite) TestRunNonRootUserResolvName(c *testing.T) { // Not applicable on Windows as Windows does not support --user testRequires(c, testEnv.IsLocalDaemon, Network, DaemonIsLinux) - dockerCmd(c, "run", "--name=testperm", "--user=nobody", "busybox", "nslookup", "example.com") + cli.DockerCmd(c, "run", "--name=testperm", "--user=nobody", "busybox", "nslookup", "example.com") cID := getIDByName(c, "testperm") @@ -1465,7 +1453,7 @@ func (s *DockerCLIRunSuite) TestRunResolvconfUpdate(c *testing.T) { }() // 1. test that a restarting container gets an updated resolv.conf - dockerCmd(c, "run", "--name=first", "busybox", "true") + cli.DockerCmd(c, "run", "--name=first", "busybox", "true") containerID1 := getIDByName(c, "first") // replace resolv.conf with our temporary copy @@ -1474,7 +1462,7 @@ func (s *DockerCLIRunSuite) TestRunResolvconfUpdate(c *testing.T) { } // start the container again to pickup changes - dockerCmd(c, "start", "first") + cli.DockerCmd(c, "start", "first") // check for update in container containerResolv := readContainerFile(c, containerID1, "resolv.conf") @@ -1488,7 +1476,7 @@ func (s *DockerCLIRunSuite) TestRunResolvconfUpdate(c *testing.T) { } */ // 2. test that a restarting container does not receive resolv.conf updates // if it modified the container copy of the starting point resolv.conf - dockerCmd(c, "run", "--name=second", "busybox", "sh", "-c", "echo 'search mylittlepony.com' >>/etc/resolv.conf") + cli.DockerCmd(c, "run", "--name=second", "busybox", "sh", "-c", "echo 'search mylittlepony.com' >>/etc/resolv.conf") containerID2 := getIDByName(c, "second") // make a change to resolv.conf (in this case replacing our tmp copy with orig copy) @@ -1497,7 +1485,7 @@ func (s *DockerCLIRunSuite) TestRunResolvconfUpdate(c *testing.T) { } // start the container again - dockerCmd(c, "start", "second") + cli.DockerCmd(c, "start", "second") // check for update in container containerResolv = readContainerFile(c, containerID2, "resolv.conf") @@ -1506,8 +1494,8 @@ func (s *DockerCLIRunSuite) TestRunResolvconfUpdate(c *testing.T) { } // 3. test that a running container's resolv.conf is not modified while running - out, _ := dockerCmd(c, "run", "-d", "busybox", "top") - runningContainerID := strings.TrimSpace(out) + runningContainerID := cli.DockerCmd(c, "run", "-d", "busybox", "top").Stdout() + runningContainerID = strings.TrimSpace(runningContainerID) // replace resolv.conf if err := os.WriteFile("/etc/resolv.conf", tmpResolvConf, 0o644); err != nil { @@ -1522,7 +1510,7 @@ func (s *DockerCLIRunSuite) TestRunResolvconfUpdate(c *testing.T) { // 4. test that a running container's resolv.conf is updated upon restart // (the above container is still running..) - dockerCmd(c, "restart", runningContainerID) + cli.DockerCmd(c, "restart", runningContainerID) // check for update in container containerResolv = readContainerFile(c, runningContainerID, "resolv.conf") @@ -1539,7 +1527,7 @@ func (s *DockerCLIRunSuite) TestRunResolvconfUpdate(c *testing.T) { } // start the container again to pickup changes - dockerCmd(c, "start", "first") + cli.DockerCmd(c, "start", "first") // our first exited container ID should have been updated, but with default DNS // after the cleanup of resolv.conf found only a localhost nameserver: @@ -1558,7 +1546,7 @@ func (s *DockerCLIRunSuite) TestRunResolvconfUpdate(c *testing.T) { } // Run the container so it picks up the old settings - dockerCmd(c, "run", "--name=third", "busybox", "true") + cli.DockerCmd(c, "run", "--name=third", "busybox", "true") containerID3 := getIDByName(c, "third") // Create a modified resolv.conf.aside and override resolv.conf with it @@ -1572,7 +1560,7 @@ func (s *DockerCLIRunSuite) TestRunResolvconfUpdate(c *testing.T) { } // start the container again to pickup changes - dockerCmd(c, "start", "third") + cli.DockerCmd(c, "start", "third") // check for update in container containerResolv = readContainerFile(c, containerID3, "resolv.conf") @@ -1586,7 +1574,7 @@ func (s *DockerCLIRunSuite) TestRunResolvconfUpdate(c *testing.T) { func (s *DockerCLIRunSuite) TestRunAddHost(c *testing.T) { // Not applicable on Windows as it does not support --add-host testRequires(c, DaemonIsLinux) - out, _ := dockerCmd(c, "run", "--add-host=extra:86.75.30.9", "busybox", "grep", "extra", "/etc/hosts") + out := cli.DockerCmd(c, "run", "--add-host=extra:86.75.30.9", "busybox", "grep", "extra", "/etc/hosts").Combined() actual := strings.Trim(out, "\r\n") if actual != "86.75.30.9\textra" { @@ -1596,7 +1584,7 @@ func (s *DockerCLIRunSuite) TestRunAddHost(c *testing.T) { // Regression test for #6983 func (s *DockerCLIRunSuite) TestRunAttachStdErrOnlyTTYMode(c *testing.T) { - _, exitCode := dockerCmd(c, "run", "-t", "-a", "stderr", "busybox", "true") + exitCode := cli.DockerCmd(c, "run", "-t", "-a", "stderr", "busybox", "true").ExitCode if exitCode != 0 { c.Fatalf("Container should have exited with error code 0") } @@ -1604,7 +1592,7 @@ func (s *DockerCLIRunSuite) TestRunAttachStdErrOnlyTTYMode(c *testing.T) { // Regression test for #6983 func (s *DockerCLIRunSuite) TestRunAttachStdOutOnlyTTYMode(c *testing.T) { - _, exitCode := dockerCmd(c, "run", "-t", "-a", "stdout", "busybox", "true") + exitCode := cli.DockerCmd(c, "run", "-t", "-a", "stdout", "busybox", "true").ExitCode if exitCode != 0 { c.Fatalf("Container should have exited with error code 0") } @@ -1612,7 +1600,7 @@ func (s *DockerCLIRunSuite) TestRunAttachStdOutOnlyTTYMode(c *testing.T) { // Regression test for #6983 func (s *DockerCLIRunSuite) TestRunAttachStdOutAndErrTTYMode(c *testing.T) { - _, exitCode := dockerCmd(c, "run", "-t", "-a", "stdout", "-a", "stderr", "busybox", "true") + exitCode := cli.DockerCmd(c, "run", "-t", "-a", "stdout", "-a", "stderr", "busybox", "true").ExitCode if exitCode != 0 { c.Fatalf("Container should have exited with error code 0") } @@ -1631,9 +1619,9 @@ func (s *DockerCLIRunSuite) TestRunAttachWithDetach(c *testing.T) { func (s *DockerCLIRunSuite) TestRunState(c *testing.T) { // TODO Windows: This needs some rework as Windows busybox does not support top testRequires(c, DaemonIsLinux) - out, _ := dockerCmd(c, "run", "-d", "busybox", "top") + id := cli.DockerCmd(c, "run", "-d", "busybox", "top").Stdout() + id = strings.TrimSpace(id) - id := strings.TrimSpace(out) state := inspectField(c, id, "State.Running") if state != "true" { c.Fatal("Container state is 'not running'") @@ -1643,7 +1631,7 @@ func (s *DockerCLIRunSuite) TestRunState(c *testing.T) { c.Fatal("Container state Pid 0") } - dockerCmd(c, "stop", id) + cli.DockerCmd(c, "stop", id) state = inspectField(c, id, "State.Running") if state != "false" { c.Fatal("Container state is 'running'") @@ -1653,7 +1641,7 @@ func (s *DockerCLIRunSuite) TestRunState(c *testing.T) { c.Fatalf("Container state Pid %s, but expected %s", pid2, pid1) } - dockerCmd(c, "start", id) + cli.DockerCmd(c, "start", id) state = inspectField(c, id, "State.Running") if state != "true" { c.Fatal("Container state is 'not running'") @@ -1675,7 +1663,7 @@ func (s *DockerCLIRunSuite) TestRunCopyVolumeUIDGID(c *testing.T) { RUN mkdir -p /hello && touch /hello/test && chown dockerio.dockerio /hello`)) // Test that the uid and gid is copied from the image to the volume - out, _ := dockerCmd(c, "run", "--rm", "-v", "/hello", name, "sh", "-c", `ls -l / | grep hello | awk '{print $3":"$4}'`) + out := cli.DockerCmd(c, "run", "--rm", "-v", "/hello", name, "sh", "-c", `ls -l / | grep hello | awk '{print $3":"$4}'`).Combined() out = strings.TrimSpace(out) if out != "dockerio:dockerio" { c.Fatalf("Wrong /hello ownership: %s, expected dockerio:dockerio", out) @@ -1692,7 +1680,7 @@ func (s *DockerCLIRunSuite) TestRunCopyVolumeContent(c *testing.T) { RUN mkdir -p /hello/local && echo hello > /hello/local/world`)) // Test that the content is copied from the image to the volume - out, _ := dockerCmd(c, "run", "--rm", "-v", "/hello", name, "find", "/hello") + out := cli.DockerCmd(c, "run", "--rm", "-v", "/hello", name, "find", "/hello").Combined() if !(strings.Contains(out, "/hello/local/world") && strings.Contains(out, "/hello/local")) { c.Fatal("Container failed to transfer content to volume") } @@ -1704,11 +1692,11 @@ func (s *DockerCLIRunSuite) TestRunCleanupCmdOnEntrypoint(c *testing.T) { ENTRYPOINT ["echo"] CMD ["testingpoint"]`)) - out, exit := dockerCmd(c, "run", "--entrypoint", "whoami", name) - if exit != 0 { - c.Fatalf("expected exit code 0 received %d, out: %q", exit, out) + result := cli.DockerCmd(c, "run", "--entrypoint", "whoami", name) + out := strings.TrimSpace(result.Combined()) + if result.ExitCode != 0 { + c.Fatalf("expected exit code 0 received %d, out: %q", result.ExitCode, out) } - out = strings.TrimSpace(out) expected := "root" if testEnv.DaemonInfo.OSType == "windows" { if strings.Contains(testEnv.PlatformDefaults.BaseImage, "servercore") { @@ -1820,12 +1808,12 @@ func (s *DockerCLIRunSuite) TestRunWriteSpecialFilesAndNotCommit(c *testing.T) { func testRunWriteSpecialFilesAndNotCommit(c *testing.T, name, path string) { command := fmt.Sprintf("echo test2267 >> %s && cat %s", path, path) - out, _ := dockerCmd(c, "run", "--name", name, "busybox", "sh", "-c", command) + out := cli.DockerCmd(c, "run", "--name", name, "busybox", "sh", "-c", command).Combined() if !strings.Contains(out, "test2267") { c.Fatalf("%s should contain 'test2267'", path) } - out, _ = dockerCmd(c, "diff", name) + out = cli.DockerCmd(c, "diff", name).Combined() if len(strings.Trim(out, "\r\n")) != 0 && !eqToBaseDiff(out, c) { c.Fatal("diff should be empty") } @@ -1833,9 +1821,9 @@ func testRunWriteSpecialFilesAndNotCommit(c *testing.T, name, path string) { func eqToBaseDiff(out string, c *testing.T) bool { name := "eqToBaseDiff" + testutil.GenerateRandomAlphaOnlyString(32) - dockerCmd(c, "run", "--name", name, "busybox", "echo", "hello") + cli.DockerCmd(c, "run", "--name", name, "busybox", "echo", "hello") cID := getIDByName(c, name) - baseDiff, _ := dockerCmd(c, "diff", cID) + baseDiff := cli.DockerCmd(c, "diff", cID).Combined() baseArr := strings.Split(baseDiff, "\n") sort.Strings(baseArr) outArr := strings.Split(out, "\n") @@ -1873,11 +1861,10 @@ func (s *DockerCLIRunSuite) TestRunWithBadDevice(c *testing.T) { } func (s *DockerCLIRunSuite) TestRunEntrypoint(c *testing.T) { - name := "entrypoint" - - out, _ := dockerCmd(c, "run", "--name", name, "--entrypoint", "echo", "busybox", "-n", "foobar") - expected := "foobar" + const name = "entrypoint" + const expected = "foobar" + out := cli.DockerCmd(c, "run", "--name", name, "--entrypoint", "echo", "busybox", "-n", "foobar").Combined() if out != expected { c.Fatalf("Output should be %q, actual out: %q", expected, out) } @@ -1900,16 +1887,16 @@ func (s *DockerCLIRunSuite) TestRunBindMounts(c *testing.T) { writeFile(path.Join(tmpDir, "touch-me"), "", c) // Test reading from a read-only bind mount - out, _ := dockerCmd(c, "run", "-v", fmt.Sprintf("%s:%s/tmpx:ro", tmpDir, prefix), "busybox", "ls", prefix+"/tmpx") + out := cli.DockerCmd(c, "run", "-v", fmt.Sprintf("%s:%s/tmpx:ro", tmpDir, prefix), "busybox", "ls", prefix+"/tmpx").Combined() if !strings.Contains(out, "touch-me") { c.Fatal("Container failed to read from bind mount") } // test writing to bind mount if testEnv.DaemonInfo.OSType == "windows" { - dockerCmd(c, "run", "-v", fmt.Sprintf(`%s:c:\tmp:rw`, tmpDir), "busybox", "touch", "c:/tmp/holla") + cli.DockerCmd(c, "run", "-v", fmt.Sprintf(`%s:c:\tmp:rw`, tmpDir), "busybox", "touch", "c:/tmp/holla") } else { - dockerCmd(c, "run", "-v", fmt.Sprintf("%s:/tmp:rw", tmpDir), "busybox", "touch", "/tmp/holla") + cli.DockerCmd(c, "run", "-v", fmt.Sprintf("%s:/tmp:rw", tmpDir), "busybox", "touch", "/tmp/holla") } readFile(path.Join(tmpDir, "holla"), c) // Will fail if the file doesn't exist @@ -1923,7 +1910,7 @@ func (s *DockerCLIRunSuite) TestRunBindMounts(c *testing.T) { // Windows does not (and likely never will) support mounting a single file if testEnv.DaemonInfo.OSType != "windows" { // test mount a file - dockerCmd(c, "run", "-v", fmt.Sprintf("%s/holla:/tmp/holla:rw", tmpDir), "busybox", "sh", "-c", "echo -n 'yotta' > /tmp/holla") + cli.DockerCmd(c, "run", "-v", fmt.Sprintf("%s/holla:/tmp/holla:rw", tmpDir), "busybox", "sh", "-c", "echo -n 'yotta' > /tmp/holla") content := readFile(path.Join(tmpDir, "holla"), c) // Will fail if the file doesn't exist expected := "yotta" if content != expected { @@ -1970,9 +1957,8 @@ func (s *DockerCLIRunSuite) TestRunCidFileCheckIDLength(c *testing.T) { tmpCidFile := path.Join(tmpDir, "cid") defer os.RemoveAll(tmpDir) - out, _ := dockerCmd(c, "run", "-d", "--cidfile", tmpCidFile, "busybox", "true") - - id := strings.TrimSpace(out) + id := cli.DockerCmd(c, "run", "-d", "--cidfile", tmpCidFile, "busybox", "true").Stdout() + id = strings.TrimSpace(id) buffer, err := os.ReadFile(tmpCidFile) if err != nil { c.Fatal(err) @@ -1991,10 +1977,10 @@ func (s *DockerCLIRunSuite) TestRunSetMacAddress(c *testing.T) { mac := "12:34:56:78:9a:bc" var out string if testEnv.DaemonInfo.OSType == "windows" { - out, _ = dockerCmd(c, "run", "-i", "--rm", fmt.Sprintf("--mac-address=%s", mac), "busybox", "sh", "-c", "ipconfig /all | grep 'Physical Address' | awk '{print $12}'") + out = cli.DockerCmd(c, "run", "-i", "--rm", fmt.Sprintf("--mac-address=%s", mac), "busybox", "sh", "-c", "ipconfig /all | grep 'Physical Address' | awk '{print $12}'").Combined() mac = strings.ReplaceAll(strings.ToUpper(mac), ":", "-") // To Windows-style MACs } else { - out, _ = dockerCmd(c, "run", "-i", "--rm", fmt.Sprintf("--mac-address=%s", mac), "busybox", "/bin/sh", "-c", "ip link show eth0 | tail -1 | awk '{print $2}'") + out = cli.DockerCmd(c, "run", "-i", "--rm", fmt.Sprintf("--mac-address=%s", mac), "busybox", "/bin/sh", "-c", "ip link show eth0 | tail -1 | awk '{print $2}'").Combined() } actualMac := strings.TrimSpace(out) @@ -2006,8 +1992,8 @@ func (s *DockerCLIRunSuite) TestRunSetMacAddress(c *testing.T) { func (s *DockerCLIRunSuite) TestRunInspectMacAddress(c *testing.T) { // TODO Windows. Network settings are not propagated back to inspect. testRequires(c, DaemonIsLinux) - mac := "12:34:56:78:9a:bc" - out, _ := dockerCmd(c, "run", "-d", "--mac-address="+mac, "busybox", "top") + const mac = "12:34:56:78:9a:bc" + out := cli.DockerCmd(c, "run", "-d", "--mac-address="+mac, "busybox", "top").Combined() id := strings.TrimSpace(out) inspectedMac := inspectField(c, id, "NetworkSettings.Networks.bridge.MacAddress") @@ -2048,7 +2034,7 @@ func (s *DockerCLIRunSuite) TestRunPortInUse(c *testing.T) { testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux) port := "1234" - dockerCmd(c, "run", "-d", "-p", port+":80", "busybox", "top") + cli.DockerCmd(c, "run", "-d", "-p", port+":80", "busybox", "top") out, _, err := dockerCmdWithError("run", "-d", "-p", port+":80", "busybox", "top") if err == nil { @@ -2064,10 +2050,10 @@ func (s *DockerCLIRunSuite) TestRunAllocatePortInReservedRange(c *testing.T) { // TODO Windows. -P is not yet supported testRequires(c, DaemonIsLinux) // allocate a dynamic port to get the most recent - out, _ := dockerCmd(c, "run", "-d", "-P", "-p", "80", "busybox", "top") + id := cli.DockerCmd(c, "run", "-d", "-P", "-p", "80", "busybox", "top").Stdout() + id = strings.TrimSpace(id) - id := strings.TrimSpace(out) - out, _ = dockerCmd(c, "inspect", "--format", `{{index .NetworkSettings.Ports "80/tcp" 0 "HostPort" }}`, id) + out := cli.DockerCmd(c, "inspect", "--format", `{{index .NetworkSettings.Ports "80/tcp" 0 "HostPort" }}`, id).Stdout() out = strings.TrimSpace(out) port, err := strconv.ParseInt(out, 10, 64) if err != nil { @@ -2076,7 +2062,7 @@ func (s *DockerCLIRunSuite) TestRunAllocatePortInReservedRange(c *testing.T) { // allocate a static port and a dynamic port together, with static port // takes the next recent port in dynamic port range. - dockerCmd(c, "run", "-d", "-P", "-p", "80", "-p", fmt.Sprintf("%d:8080", port+1), "busybox", "top") + cli.DockerCmd(c, "run", "-d", "-P", "-p", "80", "-p", fmt.Sprintf("%d:8080", port+1), "busybox", "top") } // Regression test for #7792 @@ -2115,7 +2101,7 @@ func (s *DockerCLIRunSuite) TestRunMountOrdering(c *testing.T) { c.Fatal(err) } - dockerCmd(c, "run", + cli.DockerCmd(c, "run", "-v", fmt.Sprintf("%s:"+prefix+"/tmp", tmpDir), "-v", fmt.Sprintf("%s:"+prefix+"/tmp/foo", fooDir), "-v", fmt.Sprintf("%s:"+prefix+"/tmp/tmp2", tmpDir2), @@ -2143,11 +2129,11 @@ func (s *DockerCLIRunSuite) TestRunReuseBindVolumeThatIsSymlink(c *testing.T) { defer os.RemoveAll(linkPath) // Create first container - dockerCmd(c, "run", "-v", fmt.Sprintf("%s:"+prefix+"/tmp/test", linkPath), "busybox", "ls", prefix+"/tmp/test") + cli.DockerCmd(c, "run", "-v", fmt.Sprintf("%s:"+prefix+"/tmp/test", linkPath), "busybox", "ls", prefix+"/tmp/test") // Create second container with same symlinked path // This will fail if the referenced issue is hit with a "Volume exists" error - dockerCmd(c, "run", "-v", fmt.Sprintf("%s:"+prefix+"/tmp/test", linkPath), "busybox", "ls", prefix+"/tmp/test") + cli.DockerCmd(c, "run", "-v", fmt.Sprintf("%s:"+prefix+"/tmp/test", linkPath), "busybox", "ls", prefix+"/tmp/test") } // GH#10604: Test an "/etc" volume doesn't overlay special bind mounts in container @@ -2155,17 +2141,17 @@ func (s *DockerCLIRunSuite) TestRunCreateVolumeEtc(c *testing.T) { // While Windows supports volumes, it does not support --add-host hence // this test is not applicable on Windows. testRequires(c, DaemonIsLinux) - out, _ := dockerCmd(c, "run", "--dns=127.0.0.1", "-v", "/etc", "busybox", "cat", "/etc/resolv.conf") + out := cli.DockerCmd(c, "run", "--dns=127.0.0.1", "-v", "/etc", "busybox", "cat", "/etc/resolv.conf").Stdout() if !strings.Contains(out, "nameserver 127.0.0.1") { c.Fatal("/etc volume mount hides /etc/resolv.conf") } - out, _ = dockerCmd(c, "run", "-h=test123", "-v", "/etc", "busybox", "cat", "/etc/hostname") + out = cli.DockerCmd(c, "run", "-h=test123", "-v", "/etc", "busybox", "cat", "/etc/hostname").Stdout() if !strings.Contains(out, "test123") { c.Fatal("/etc volume mount hides /etc/hostname") } - out, _ = dockerCmd(c, "run", "--add-host=test:192.168.0.1", "-v", "/etc", "busybox", "cat", "/etc/hosts") + out = cli.DockerCmd(c, "run", "--add-host=test:192.168.0.1", "-v", "/etc", "busybox", "cat", "/etc/hosts").Stdout() out = strings.ReplaceAll(out, "\n", " ") if !strings.Contains(out, "192.168.0.1\ttest") || !strings.Contains(out, "127.0.0.1\tlocalhost") { c.Fatal("/etc volume mount hides /etc/hosts") @@ -2180,7 +2166,7 @@ func (s *DockerCLIRunSuite) TestVolumesNoCopyData(c *testing.T) { buildImageSuccessfully(c, "dataimage", build.WithDockerfile(`FROM busybox RUN ["mkdir", "-p", "/foo"] RUN ["touch", "/foo/bar"]`)) - dockerCmd(c, "run", "--name", "test", "-v", prefix+slash+"foo", "busybox") + cli.DockerCmd(c, "run", "--name", "test", "-v", prefix+slash+"foo", "busybox") if out, _, err := dockerCmdWithError("run", "--volumes-from", "test", "dataimage", "ls", "-lh", "/foo/bar"); err == nil || !strings.Contains(out, "No such file or directory") { c.Fatalf("Data was copied on volumes-from but shouldn't be:\n%q", out) @@ -2210,7 +2196,7 @@ func (s *DockerCLIRunSuite) TestRunVolumesCleanPaths(c *testing.T) { prefix, slash := getPrefixAndSlashFromDaemonPlatform() buildImageSuccessfully(c, "run_volumes_clean_paths", build.WithDockerfile(`FROM busybox VOLUME `+prefix+`/foo/`)) - dockerCmd(c, "run", "-v", prefix+"/foo", "-v", prefix+"/bar/", "--name", "dark_helmet", "run_volumes_clean_paths") + cli.DockerCmd(c, "run", "-v", prefix+"/foo", "-v", prefix+"/bar/", "--name", "dark_helmet", "run_volumes_clean_paths") out, err := inspectMountSourceField("dark_helmet", prefix+slash+"foo"+slash) if err != errMountNotFound { @@ -2268,9 +2254,9 @@ func (s *DockerCLIRunSuite) TestRunAllowPortRangeThroughExpose(c *testing.T) { // TODO Windows: -P is not currently supported. Also network // settings are not propagated back. testRequires(c, DaemonIsLinux) - out, _ := dockerCmd(c, "run", "-d", "--expose", "3000-3003", "-P", "busybox", "top") + id := cli.DockerCmd(c, "run", "-d", "--expose", "3000-3003", "-P", "busybox", "top").Stdout() + id = strings.TrimSpace(id) - id := strings.TrimSpace(out) portstr := inspectFieldJSON(c, id, "NetworkSettings.Ports") var ports nat.PortMap if err := json.Unmarshal([]byte(portstr), &ports); err != nil { @@ -2302,13 +2288,13 @@ func (s *DockerCLIRunSuite) TestRunModeIpcHost(c *testing.T) { c.Fatal(err) } - out, _ := dockerCmd(c, "run", "--ipc=host", "busybox", "readlink", "/proc/self/ns/ipc") + out := cli.DockerCmd(c, "run", "--ipc=host", "busybox", "readlink", "/proc/self/ns/ipc").Combined() out = strings.Trim(out, "\n") if hostIpc != out { c.Fatalf("IPC different with --ipc=host %s != %s\n", hostIpc, out) } - out, _ = dockerCmd(c, "run", "busybox", "readlink", "/proc/self/ns/ipc") + out = cli.DockerCmd(c, "run", "busybox", "readlink", "/proc/self/ns/ipc").Combined() out = strings.Trim(out, "\n") if hostIpc == out { c.Fatalf("IPC should be different without --ipc=host %s == %s\n", hostIpc, out) @@ -2328,9 +2314,9 @@ func (s *DockerCLIRunSuite) TestRunModeIpcContainerNotRunning(c *testing.T) { // Not applicable on Windows as uses Unix-specific capabilities testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux) - out, _ := dockerCmd(c, "create", "busybox") + id := cli.DockerCmd(c, "create", "busybox").Stdout() + id = strings.TrimSpace(id) - id := strings.TrimSpace(out) out, _, err := dockerCmdWithError("run", fmt.Sprintf("--ipc=container:%s", id), "busybox") if err == nil { c.Fatalf("Run container with ipc mode container should fail with non running container: %s\n%s", out, err) @@ -2341,9 +2327,9 @@ func (s *DockerCLIRunSuite) TestRunModePIDContainer(c *testing.T) { // Not applicable on Windows as uses Unix-specific capabilities testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux) - out, _ := dockerCmd(c, "run", "-d", "busybox", "sh", "-c", "top") + id := cli.DockerCmd(c, "run", "-d", "busybox", "sh", "-c", "top").Stdout() + id = strings.TrimSpace(id) - id := strings.TrimSpace(out) state := inspectField(c, id, "State.Running") if state != "true" { c.Fatal("Container state is 'not running'") @@ -2355,7 +2341,7 @@ func (s *DockerCLIRunSuite) TestRunModePIDContainer(c *testing.T) { c.Fatal(err) } - out, _ = dockerCmd(c, "run", fmt.Sprintf("--pid=container:%s", id), "busybox", "readlink", "/proc/self/ns/pid") + out := cli.DockerCmd(c, "run", fmt.Sprintf("--pid=container:%s", id), "busybox", "readlink", "/proc/self/ns/pid").Combined() out = strings.Trim(out, "\n") if parentContainerPid != out { c.Fatalf("PID different with --pid=container:%s %s != %s\n", id, parentContainerPid, out) @@ -2375,9 +2361,9 @@ func (s *DockerCLIRunSuite) TestRunModePIDContainerNotRunning(c *testing.T) { // Not applicable on Windows as uses Unix-specific capabilities testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux) - out, _ := dockerCmd(c, "create", "busybox") + id := cli.DockerCmd(c, "create", "busybox").Stdout() + id = strings.TrimSpace(id) - id := strings.TrimSpace(out) out, _, err := dockerCmdWithError("run", fmt.Sprintf("--pid=container:%s", id), "busybox") if err == nil { c.Fatalf("Run container with pid mode container should fail with non running container: %s\n%s", out, err) @@ -2388,7 +2374,7 @@ func (s *DockerCLIRunSuite) TestRunMountShmMqueueFromHost(c *testing.T) { // Not applicable on Windows as uses Unix-specific capabilities testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux, NotUserNamespace) - dockerCmd(c, "run", "-d", "--name", "shmfromhost", "-v", "/dev/shm:/dev/shm", "-v", "/dev/mqueue:/dev/mqueue", "busybox", "sh", "-c", "echo -n test > /dev/shm/test && touch /dev/mqueue/toto && top") + cli.DockerCmd(c, "run", "-d", "--name", "shmfromhost", "-v", "/dev/shm:/dev/shm", "-v", "/dev/mqueue:/dev/mqueue", "busybox", "sh", "-c", "echo -n test > /dev/shm/test && touch /dev/mqueue/toto && top") defer os.Remove("/dev/mqueue/toto") defer os.Remove("/dev/shm/test") volPath, err := inspectMountSourceField("shmfromhost", "/dev/shm") @@ -2397,7 +2383,7 @@ func (s *DockerCLIRunSuite) TestRunMountShmMqueueFromHost(c *testing.T) { c.Fatalf("volumePath should have been /dev/shm, was %s", volPath) } - out, _ := dockerCmd(c, "run", "--name", "ipchost", "--ipc", "host", "busybox", "cat", "/dev/shm/test") + out := cli.DockerCmd(c, "run", "--name", "ipchost", "--ipc", "host", "busybox", "cat", "/dev/shm/test").Combined() if out != "test" { c.Fatalf("Output of /dev/shm/test expected test but found: %s", out) } @@ -2412,9 +2398,9 @@ func (s *DockerCLIRunSuite) TestContainerNetworkMode(c *testing.T) { // Not applicable on Windows as uses Unix-specific capabilities testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux) - out, _ := dockerCmd(c, "run", "-d", "busybox", "top") - id := strings.TrimSpace(out) - assert.NilError(c, waitRun(id)) + id := cli.DockerCmd(c, "run", "-d", "busybox", "top").Stdout() + id = strings.TrimSpace(id) + cli.WaitRun(c, id) pid1 := inspectField(c, id, "State.Pid") parentContainerNet, err := os.Readlink(fmt.Sprintf("/proc/%s/ns/net", pid1)) @@ -2422,7 +2408,7 @@ func (s *DockerCLIRunSuite) TestContainerNetworkMode(c *testing.T) { c.Fatal(err) } - out, _ = dockerCmd(c, "run", fmt.Sprintf("--net=container:%s", id), "busybox", "readlink", "/proc/self/ns/net") + out := cli.DockerCmd(c, "run", fmt.Sprintf("--net=container:%s", id), "busybox", "readlink", "/proc/self/ns/net").Combined() out = strings.Trim(out, "\n") if parentContainerNet != out { c.Fatalf("NET different with --net=container:%s %s != %s\n", id, parentContainerNet, out) @@ -2438,19 +2424,19 @@ func (s *DockerCLIRunSuite) TestRunModeUTSHost(c *testing.T) { c.Fatal(err) } - out, _ := dockerCmd(c, "run", "--uts=host", "busybox", "readlink", "/proc/self/ns/uts") + out := cli.DockerCmd(c, "run", "--uts=host", "busybox", "readlink", "/proc/self/ns/uts").Combined() out = strings.Trim(out, "\n") if hostUTS != out { c.Fatalf("UTS different with --uts=host %s != %s\n", hostUTS, out) } - out, _ = dockerCmd(c, "run", "busybox", "readlink", "/proc/self/ns/uts") + out = cli.DockerCmd(c, "run", "busybox", "readlink", "/proc/self/ns/uts").Combined() out = strings.Trim(out, "\n") if hostUTS == out { c.Fatalf("UTS should be different without --uts=host %s == %s\n", hostUTS, out) } - out, _ = dockerCmdWithFail(c, "run", "-h=name", "--uts=host", "busybox", "ps") + out = dockerCmdWithFail(c, "run", "-h=name", "--uts=host", "busybox", "ps") assert.Assert(c, strings.Contains(out, runconfig.ErrConflictUTSHostname.Error())) } @@ -2475,11 +2461,10 @@ func (s *DockerCLIRunSuite) TestRunPortFromDockerRangeInUse(c *testing.T) { // re-instated. testRequires(c, DaemonIsLinux) // first find allocator current position - out, _ := dockerCmd(c, "run", "-d", "-p", ":80", "busybox", "top") + id := cli.DockerCmd(c, "run", "-d", "-p", ":80", "busybox", "top").Stdout() + id = strings.TrimSpace(id) - id := strings.TrimSpace(out) - - out, _ = dockerCmd(c, "inspect", "--format", `{{index .NetworkSettings.Ports "80/tcp" 0 "HostPort" }}`, id) + out := cli.DockerCmd(c, "inspect", "--format", `{{index .NetworkSettings.Ports "80/tcp" 0 "HostPort" }}`, id).Stdout() out = strings.TrimSpace(out) if out == "" { c.Fatal("docker port command output is empty") @@ -2495,10 +2480,9 @@ func (s *DockerCLIRunSuite) TestRunPortFromDockerRangeInUse(c *testing.T) { } defer l.Close() - out, _ = dockerCmd(c, "run", "-d", "-p", ":80", "busybox", "top") - - id = strings.TrimSpace(out) - dockerCmd(c, "port", id) + id = cli.DockerCmd(c, "run", "-d", "-p", ":80", "busybox", "top").Stdout() + id = strings.TrimSpace(id) + cli.DockerCmd(c, "port", id) } func (s *DockerCLIRunSuite) TestRunTTYWithPipe(c *testing.T) { @@ -2545,7 +2529,7 @@ func (s *DockerCLIRunSuite) TestRunNonLocalMacAddress(c *testing.T) { expected = strings.ReplaceAll(strings.ToUpper(addr), ":", "-") } - if out, _ := dockerCmd(c, args...); !strings.Contains(out, expected) { + if out := cli.DockerCmd(c, args...).Combined(); !strings.Contains(out, expected) { c.Fatalf("Output should have contained %q: %s", expected, out) } } @@ -2559,13 +2543,13 @@ func (s *DockerCLIRunSuite) TestRunNetHost(c *testing.T) { c.Fatal(err) } - out, _ := dockerCmd(c, "run", "--net=host", "busybox", "readlink", "/proc/self/ns/net") + out := cli.DockerCmd(c, "run", "--net=host", "busybox", "readlink", "/proc/self/ns/net").Combined() out = strings.Trim(out, "\n") if hostNet != out { c.Fatalf("Net namespace different with --net=host %s != %s\n", hostNet, out) } - out, _ = dockerCmd(c, "run", "busybox", "readlink", "/proc/self/ns/net") + out = cli.DockerCmd(c, "run", "busybox", "readlink", "/proc/self/ns/net").Combined() out = strings.Trim(out, "\n") if hostNet == out { c.Fatalf("Net namespace should be different without --net=host %s == %s\n", hostNet, out) @@ -2577,8 +2561,8 @@ func (s *DockerCLIRunSuite) TestRunNetHostTwiceSameName(c *testing.T) { // CNM, this test may be possible to enable on Windows. testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux, NotUserNamespace) - dockerCmd(c, "run", "--rm", "--name=thost", "--net=host", "busybox", "true") - dockerCmd(c, "run", "--rm", "--name=thost", "--net=host", "busybox", "true") + cli.DockerCmd(c, "run", "--rm", "--name=thost", "--net=host", "busybox", "true") + cli.DockerCmd(c, "run", "--rm", "--name=thost", "--net=host", "busybox", "true") } func (s *DockerCLIRunSuite) TestRunNetContainerWhichHost(c *testing.T) { @@ -2590,9 +2574,9 @@ func (s *DockerCLIRunSuite) TestRunNetContainerWhichHost(c *testing.T) { c.Fatal(err) } - dockerCmd(c, "run", "-d", "--net=host", "--name=test", "busybox", "top") + cli.DockerCmd(c, "run", "-d", "--net=host", "--name=test", "busybox", "top") - out, _ := dockerCmd(c, "run", "--net=container:test", "busybox", "readlink", "/proc/self/ns/net") + out := cli.DockerCmd(c, "run", "--net=container:test", "busybox", "readlink", "/proc/self/ns/net").Combined() out = strings.Trim(out, "\n") if hostNet != out { c.Fatalf("Container should have host network namespace") @@ -2604,21 +2588,20 @@ func (s *DockerCLIRunSuite) TestRunAllowPortRangeThroughPublish(c *testing.T) { // Windows does not currently support --expose, or populate the network // settings seen through inspect. testRequires(c, DaemonIsLinux) - out, _ := dockerCmd(c, "run", "-d", "--expose", "3000-3003", "-p", "3000-3003", "busybox", "top") - - id := strings.TrimSpace(out) - portstr := inspectFieldJSON(c, id, "NetworkSettings.Ports") + id := cli.DockerCmd(c, "run", "-d", "--expose", "3000-3003", "-p", "3000-3003", "busybox", "top").Stdout() + id = strings.TrimSpace(id) + portStr := inspectFieldJSON(c, id, "NetworkSettings.Ports") var ports nat.PortMap - err := json.Unmarshal([]byte(portstr), &ports) - assert.NilError(c, err, "failed to unmarshal: %v", portstr) + err := json.Unmarshal([]byte(portStr), &ports) + assert.NilError(c, err, "failed to unmarshal: %v", portStr) for port, binding := range ports { portnum, _ := strconv.Atoi(strings.Split(string(port), "/")[0]) if portnum < 3000 || portnum > 3003 { c.Fatalf("Port %d is out of range ", portnum) } if len(binding) == 0 || len(binding[0].HostPort) == 0 { - c.Fatal("Port is not mapped for the port "+port, out) + c.Fatal("Port is not mapped for the port "+port, id) } } } @@ -2632,13 +2615,13 @@ func (s *DockerCLIRunSuite) TestRunSetDefaultRestartPolicy(c *testing.T) { } func (s *DockerCLIRunSuite) TestRunRestartMaxRetries(c *testing.T) { - out, _ := dockerCmd(c, "run", "-d", "--restart=on-failure:3", "busybox", "false") + id := cli.DockerCmd(c, "run", "-d", "--restart=on-failure:3", "busybox", "false").Stdout() + id = strings.TrimSpace(id) timeout := 10 * time.Second if testEnv.DaemonInfo.OSType == "windows" { timeout = 120 * time.Second } - id := strings.TrimSpace(out) if err := waitInspect(id, "{{ .State.Restarting }} {{ .State.Running }}", "false false", timeout); err != nil { c.Fatal(err) } @@ -2655,7 +2638,7 @@ func (s *DockerCLIRunSuite) TestRunRestartMaxRetries(c *testing.T) { } func (s *DockerCLIRunSuite) TestRunContainerWithWritableRootfs(c *testing.T) { - dockerCmd(c, "run", "--rm", "busybox", "touch", "/file") + cli.DockerCmd(c, "run", "--rm", "busybox", "touch", "/file") } func (s *DockerCLIRunSuite) TestRunContainerWithReadonlyRootfs(c *testing.T) { @@ -2676,10 +2659,11 @@ func (s *DockerCLIRunSuite) TestPermissionsPtsReadonlyRootfs(c *testing.T) { testRequires(c, DaemonIsLinux, UserNamespaceROMount) // Ensure we have not broken writing /dev/pts - out, status := dockerCmd(c, "run", "--read-only", "--rm", "busybox", "mount") - if status != 0 { + result := cli.DockerCmd(c, "run", "--read-only", "--rm", "busybox", "mount") + if result.ExitCode != 0 { c.Fatal("Could not obtain mounts when checking /dev/pts mntpnt.") } + out := result.Combined() expected := "type devpts (rw," if !strings.Contains(out, expected) { c.Fatalf("expected output to contain %s but contains %s", expected, out) @@ -2713,9 +2697,9 @@ func (s *DockerCLIRunSuite) TestRunContainerWithReadonlyEtcHostsAndLinkedContain // Not applicable on Windows which does not support --link testRequires(c, DaemonIsLinux, UserNamespaceROMount) - dockerCmd(c, "run", "-d", "--name", "test-etc-hosts-ro-linked", "busybox", "top") + cli.DockerCmd(c, "run", "-d", "--name", "test-etc-hosts-ro-linked", "busybox", "top") - out, _ := dockerCmd(c, "run", "--read-only", "--link", "test-etc-hosts-ro-linked:testlinked", "busybox", "cat", "/etc/hosts") + out := cli.DockerCmd(c, "run", "--read-only", "--link", "test-etc-hosts-ro-linked:testlinked", "busybox", "cat", "/etc/hosts").Stdout() if !strings.Contains(out, "testlinked") { c.Fatal("Expected /etc/hosts to be updated even if --read-only enabled") } @@ -2725,7 +2709,7 @@ func (s *DockerCLIRunSuite) TestRunContainerWithReadonlyRootfsWithDNSFlag(c *tes // Not applicable on Windows which does not support either --read-only or --dns. testRequires(c, DaemonIsLinux, UserNamespaceROMount) - out, _ := dockerCmd(c, "run", "--read-only", "--dns", "1.1.1.1", "busybox", "/bin/cat", "/etc/resolv.conf") + out := cli.DockerCmd(c, "run", "--read-only", "--dns", "1.1.1.1", "busybox", "/bin/cat", "/etc/resolv.conf").Stdout() if !strings.Contains(out, "1.1.1.1") { c.Fatal("Expected /etc/resolv.conf to be updated even if --read-only enabled and --dns flag used") } @@ -2735,7 +2719,7 @@ func (s *DockerCLIRunSuite) TestRunContainerWithReadonlyRootfsWithAddHostFlag(c // Not applicable on Windows which does not support --read-only testRequires(c, DaemonIsLinux, UserNamespaceROMount) - out, _ := dockerCmd(c, "run", "--read-only", "--add-host", "testreadonly:127.0.0.1", "busybox", "/bin/cat", "/etc/hosts") + out := cli.DockerCmd(c, "run", "--read-only", "--add-host", "testreadonly:127.0.0.1", "busybox", "/bin/cat", "/etc/hosts").Stdout() if !strings.Contains(out, "testreadonly") { c.Fatal("Expected /etc/hosts to be updated even if --read-only enabled and --add-host flag used") } @@ -2747,10 +2731,10 @@ func (s *DockerCLIRunSuite) TestRunVolumesFromRestartAfterRemoved(c *testing.T) runSleepingContainer(c, "--name=restarter", "--volumes-from", "voltest") // Remove the main volume container and restart the consuming container - dockerCmd(c, "rm", "-f", "voltest") + cli.DockerCmd(c, "rm", "-f", "voltest") // This should not fail since the volumes-from were already applied - dockerCmd(c, "restart", "restarter") + cli.DockerCmd(c, "restart", "restarter") } // run container with --rm should remove container if exit code != 0 @@ -2790,9 +2774,8 @@ func (s *DockerCLIRunSuite) TestRunPIDHostWithChildIsKillable(c *testing.T) { // Not applicable on Windows as uses Unix specific functionality testRequires(c, DaemonIsLinux, NotUserNamespace) name := "ibuildthecloud" - dockerCmd(c, "run", "-d", "--pid=host", "--name", name, "busybox", "sh", "-c", "sleep 30; echo hi") - - assert.Assert(c, waitRun(name) == nil) + cli.DockerCmd(c, "run", "-d", "--pid=host", "--name", name, "busybox", "sh", "-c", "sleep 30; echo hi") + cli.WaitRun(c, name) errchan := make(chan error, 1) go func() { @@ -2900,7 +2883,7 @@ func (s *DockerCLIRunSuite) TestMountIntoSys(c *testing.T) { // Not applicable on Windows as uses Unix specific functionality testRequires(c, DaemonIsLinux) testRequires(c, NotUserNamespace) - dockerCmd(c, "run", "-v", "/sys/fs/cgroup", "busybox", "true") + cli.DockerCmd(c, "run", "-v", "/sys/fs/cgroup", "busybox", "true") } func (s *DockerCLIRunSuite) TestRunUnshareProc(c *testing.T) { @@ -2964,8 +2947,8 @@ func (s *DockerCLIRunSuite) TestRunUnshareProc(c *testing.T) { func (s *DockerCLIRunSuite) TestRunPublishPort(c *testing.T) { // TODO Windows: This may be possible once Windows moves to libnetwork and CNM testRequires(c, DaemonIsLinux) - dockerCmd(c, "run", "-d", "--name", "test", "--expose", "8080", "busybox", "top") - out, _ := dockerCmd(c, "port", "test") + cli.DockerCmd(c, "run", "-d", "--name", "test", "--expose", "8080", "busybox", "top") + out := cli.DockerCmd(c, "port", "test").Stdout() out = strings.Trim(out, "\r\n") if out != "" { c.Fatalf("run without --publish-all should not publish port, out should be nil, but got: %s", out) @@ -2977,10 +2960,11 @@ func (s *DockerCLIRunSuite) TestDevicePermissions(c *testing.T) { // Not applicable on Windows as uses Unix specific functionality testRequires(c, DaemonIsLinux) const permissions = "crw-rw-rw-" - out, status := dockerCmd(c, "run", "--device", "/dev/fuse:/dev/fuse:mrw", "busybox:latest", "ls", "-l", "/dev/fuse") - if status != 0 { - c.Fatalf("expected status 0, got %d", status) + result := cli.DockerCmd(c, "run", "--device", "/dev/fuse:/dev/fuse:mrw", "busybox:latest", "ls", "-l", "/dev/fuse") + if result.ExitCode != 0 { + c.Fatalf("expected status 0, got %d", result.ExitCode) } + out := result.Combined() if !strings.HasPrefix(out, permissions) { c.Fatalf("output should begin with %q, got %q", permissions, out) } @@ -2989,7 +2973,7 @@ func (s *DockerCLIRunSuite) TestDevicePermissions(c *testing.T) { func (s *DockerCLIRunSuite) TestRunCapAddCHOWN(c *testing.T) { // Not applicable on Windows as uses Unix specific functionality testRequires(c, DaemonIsLinux) - out, _ := dockerCmd(c, "run", "--cap-drop=ALL", "--cap-add=CHOWN", "busybox", "sh", "-c", "adduser -D -H newuser && chown newuser /home && echo ok") + out := cli.DockerCmd(c, "run", "--cap-drop=ALL", "--cap-add=CHOWN", "busybox", "sh", "-c", "adduser -D -H newuser && chown newuser /home && echo ok").Combined() if actual := strings.Trim(out, "\r\n"); actual != "ok" { c.Fatalf("expected output ok received %s", actual) @@ -3000,10 +2984,10 @@ func (s *DockerCLIRunSuite) TestRunCapAddCHOWN(c *testing.T) { func (s *DockerCLIRunSuite) TestVolumeFromMixedRWOptions(c *testing.T) { prefix, slash := getPrefixAndSlashFromDaemonPlatform() - dockerCmd(c, "run", "--name", "parent", "-v", prefix+"/test", "busybox", "true") + cli.DockerCmd(c, "run", "--name", "parent", "-v", prefix+"/test", "busybox", "true") - dockerCmd(c, "run", "--volumes-from", "parent:ro", "--name", "test-volumes-1", "busybox", "true") - dockerCmd(c, "run", "--volumes-from", "parent:rw", "--name", "test-volumes-2", "busybox", "true") + cli.DockerCmd(c, "run", "--volumes-from", "parent:ro", "--name", "test-volumes-1", "busybox", "true") + cli.DockerCmd(c, "run", "--volumes-from", "parent:rw", "--name", "test-volumes-2", "busybox", "true") if testEnv.DaemonInfo.OSType != "windows" { mRO, err := inspectMountPoint("test-volumes-1", prefix+slash+"test") @@ -3064,7 +3048,7 @@ func (s *DockerCLIRunSuite) TestRunNetworkFilesBindMount(c *testing.T) { nwfiles := []string{"/etc/resolv.conf", "/etc/hosts", "/etc/hostname"} for i := range nwfiles { - actual, _ := dockerCmd(c, "run", "-v", filename+":"+nwfiles[i], "busybox", "cat", nwfiles[i]) + actual := cli.DockerCmd(c, "run", "-v", filename+":"+nwfiles[i], "busybox", "cat", nwfiles[i]).Combined() if actual != expected { c.Fatalf("expected %s be: %q, but was: %q", nwfiles[i], expected, actual) } @@ -3108,7 +3092,7 @@ func (s *DockerCLIRunSuite) TestRunNetworkFilesBindMountROFilesystem(c *testing. nwfiles := []string{"/etc/resolv.conf", "/etc/hosts", "/etc/hostname"} for i := range nwfiles { - _, exitCode := dockerCmd(c, "run", "-v", filename+":"+nwfiles[i], "--read-only", "busybox", "touch", nwfiles[i]) + exitCode := cli.DockerCmd(c, "run", "-v", filename+":"+nwfiles[i], "--read-only", "busybox", "touch", nwfiles[i]).ExitCode if exitCode != 0 { c.Fatalf("run should not fail because %s is mounted writable on read-only root filesystem: exit code %d", nwfiles[i], exitCode) } @@ -3126,9 +3110,9 @@ func (s *DockerCLIRunSuite) TestPtraceContainerProcsFromHost(c *testing.T) { // Not applicable on Windows as uses Unix specific functionality testRequires(c, DaemonIsLinux, testEnv.IsLocalDaemon) - out, _ := dockerCmd(c, "run", "-d", "busybox", "top") - id := strings.TrimSpace(out) - assert.NilError(c, waitRun(id)) + id := cli.DockerCmd(c, "run", "-d", "busybox", "top").Stdout() + id = strings.TrimSpace(id) + cli.WaitRun(c, id) pid1 := inspectField(c, id, "State.Pid") _, err := os.Readlink(fmt.Sprintf("/proc/%s/ns/net", pid1)) @@ -3176,7 +3160,7 @@ func (s *DockerCLIRunSuite) TestRunCapAddSYSTIME(c *testing.T) { // Not applicable on Windows as uses Unix specific functionality testRequires(c, DaemonIsLinux) - dockerCmd(c, "run", "--cap-drop=ALL", "--cap-add=SYS_TIME", "busybox", "sh", "-c", "grep ^CapEff /proc/self/status | sed 's/^CapEff:\t//' | grep ^0000000002000000$") + cli.DockerCmd(c, "run", "--cap-drop=ALL", "--cap-add=SYS_TIME", "busybox", "sh", "-c", "grep ^CapEff /proc/self/status | sed 's/^CapEff:\t//' | grep ^0000000002000000$") } // run create container failed should clean up the container @@ -3195,12 +3179,12 @@ func (s *DockerCLIRunSuite) TestRunCreateContainerFailedCleanUp(c *testing.T) { func (s *DockerCLIRunSuite) TestRunNamedVolume(c *testing.T) { prefix, _ := getPrefixAndSlashFromDaemonPlatform() testRequires(c, DaemonIsLinux) - dockerCmd(c, "run", "--name=test", "-v", "testing:"+prefix+"/foo", "busybox", "sh", "-c", "echo hello > "+prefix+"/foo/bar") + cli.DockerCmd(c, "run", "--name=test", "-v", "testing:"+prefix+"/foo", "busybox", "sh", "-c", "echo hello > "+prefix+"/foo/bar") - out, _ := dockerCmd(c, "run", "--volumes-from", "test", "busybox", "sh", "-c", "cat "+prefix+"/foo/bar") + out := cli.DockerCmd(c, "run", "--volumes-from", "test", "busybox", "sh", "-c", "cat "+prefix+"/foo/bar").Combined() assert.Equal(c, strings.TrimSpace(out), "hello") - out, _ = dockerCmd(c, "run", "-v", "testing:"+prefix+"/foo", "busybox", "sh", "-c", "cat "+prefix+"/foo/bar") + out = cli.DockerCmd(c, "run", "-v", "testing:"+prefix+"/foo", "busybox", "sh", "-c", "cat "+prefix+"/foo/bar").Combined() assert.Equal(c, strings.TrimSpace(out), "hello") } @@ -3208,7 +3192,7 @@ func (s *DockerCLIRunSuite) TestRunWithUlimits(c *testing.T) { // Not applicable on Windows as uses Unix specific functionality testRequires(c, DaemonIsLinux) - out, _ := dockerCmd(c, "run", "--name=testulimits", "--ulimit", "nofile=42", "busybox", "/bin/sh", "-c", "ulimit -n") + out := cli.DockerCmd(c, "run", "--name=testulimits", "--ulimit", "nofile=42", "busybox", "/bin/sh", "-c", "ulimit -n").Combined() ul := strings.TrimSpace(out) if ul != "42" { c.Fatalf("expected `ulimit -n` to be 42, got %s", ul) @@ -3238,8 +3222,8 @@ func testRunContainerWithCgroupParent(c *testing.T, cgroupParent, name string) { id := getIDByName(c, name) expectedCgroup := path.Join(cgroupParent, id) found := false - for _, path := range cgroupPaths { - if strings.HasSuffix(path, expectedCgroup) { + for _, p := range cgroupPaths { + if strings.HasSuffix(p, expectedCgroup) { found = true break } @@ -3278,8 +3262,8 @@ func testRunInvalidCgroupParent(c *testing.T, cgroupParent, cleanCgroupParent, n id := getIDByName(c, name) expectedCgroup := path.Join(cleanCgroupParent, id) found := false - for _, path := range cgroupPaths { - if strings.HasSuffix(path, expectedCgroup) { + for _, p := range cgroupPaths { + if strings.HasSuffix(p, expectedCgroup) { found = true break } @@ -3341,7 +3325,7 @@ func (s *DockerCLIRunSuite) TestRunContainerNetModeWithDNSMacHosts(c *testing.T) func (s *DockerCLIRunSuite) TestRunContainerNetModeWithExposePort(c *testing.T) { // Not applicable on Windows which does not support --net=container testRequires(c, DaemonIsLinux) - dockerCmd(c, "run", "-d", "--name", "parent", "busybox", "top") + cli.DockerCmd(c, "run", "-d", "--name", "parent", "busybox", "top") out, _, err := dockerCmdWithError("run", "-p", "5000:5000", "--net=container:parent", "busybox") if err == nil || !strings.Contains(out, runconfig.ErrConflictNetworkPublishPorts.Error()) { @@ -3362,17 +3346,17 @@ func (s *DockerCLIRunSuite) TestRunContainerNetModeWithExposePort(c *testing.T) func (s *DockerCLIRunSuite) TestRunLinkToContainerNetMode(c *testing.T) { // Not applicable on Windows which does not support --net=container or --link testRequires(c, DaemonIsLinux) - dockerCmd(c, "run", "--name", "test", "-d", "busybox", "top") - dockerCmd(c, "run", "--name", "parent", "-d", "--net=container:test", "busybox", "top") - dockerCmd(c, "run", "-d", "--link=parent:parent", "busybox", "top") - dockerCmd(c, "run", "--name", "child", "-d", "--net=container:parent", "busybox", "top") - dockerCmd(c, "run", "-d", "--link=child:child", "busybox", "top") + cli.DockerCmd(c, "run", "--name", "test", "-d", "busybox", "top") + cli.DockerCmd(c, "run", "--name", "parent", "-d", "--net=container:test", "busybox", "top") + cli.DockerCmd(c, "run", "-d", "--link=parent:parent", "busybox", "top") + cli.DockerCmd(c, "run", "--name", "child", "-d", "--net=container:parent", "busybox", "top") + cli.DockerCmd(c, "run", "-d", "--link=child:child", "busybox", "top") } func (s *DockerCLIRunSuite) TestRunLoopbackOnlyExistsWhenNetworkingDisabled(c *testing.T) { // TODO Windows: This may be possible to convert. testRequires(c, DaemonIsLinux) - out, _ := dockerCmd(c, "run", "--net=none", "busybox", "ip", "-o", "-4", "a", "show", "up") + out := cli.DockerCmd(c, "run", "--net=none", "busybox", "ip", "-o", "-4", "a", "show", "up").Combined() var ( count = 0 @@ -3397,9 +3381,9 @@ func (s *DockerCLIRunSuite) TestRunLoopbackOnlyExistsWhenNetworkingDisabled(c *t // Issue #4681 func (s *DockerCLIRunSuite) TestRunLoopbackWhenNetworkDisabled(c *testing.T) { if testEnv.DaemonInfo.OSType == "windows" { - dockerCmd(c, "run", "--net=none", testEnv.PlatformDefaults.BaseImage, "ping", "-n", "1", "127.0.0.1") + cli.DockerCmd(c, "run", "--net=none", testEnv.PlatformDefaults.BaseImage, "ping", "-n", "1", "127.0.0.1") } else { - dockerCmd(c, "run", "--net=none", "busybox", "ping", "-c", "1", "127.0.0.1") + cli.DockerCmd(c, "run", "--net=none", "busybox", "ping", "-c", "1", "127.0.0.1") } } @@ -3407,9 +3391,9 @@ func (s *DockerCLIRunSuite) TestRunModeNetContainerHostname(c *testing.T) { // Windows does not support --net=container testRequires(c, DaemonIsLinux) - dockerCmd(c, "run", "-i", "-d", "--name", "parent", "busybox", "top") - out, _ := dockerCmd(c, "exec", "parent", "cat", "/etc/hostname") - out1, _ := dockerCmd(c, "run", "--net=container:parent", "busybox", "cat", "/etc/hostname") + cli.DockerCmd(c, "run", "-i", "-d", "--name", "parent", "busybox", "top") + out := cli.DockerCmd(c, "exec", "parent", "cat", "/etc/hostname").Combined() + out1 := cli.DockerCmd(c, "run", "--net=container:parent", "busybox", "cat", "/etc/hostname").Combined() if out1 != out { c.Fatal("containers with shared net namespace should have same hostname") @@ -3420,8 +3404,8 @@ func (s *DockerCLIRunSuite) TestRunNetworkNotInitializedNoneMode(c *testing.T) { // TODO Windows: Network settings are not currently propagated. This may // be resolved in the future with the move to libnetwork and CNM. testRequires(c, DaemonIsLinux) - out, _ := dockerCmd(c, "run", "-d", "--net=none", "busybox", "top") - id := strings.TrimSpace(out) + id := cli.DockerCmd(c, "run", "-d", "--net=none", "busybox", "top").Stdout() + id = strings.TrimSpace(id) res := inspectField(c, id, "NetworkSettings.Networks.none.IPAddress") if res != "" { c.Fatalf("For 'none' mode network must not be initialized, but container got IP: %s", res) @@ -3431,61 +3415,61 @@ func (s *DockerCLIRunSuite) TestRunNetworkNotInitializedNoneMode(c *testing.T) { func (s *DockerCLIRunSuite) TestTwoContainersInNetHost(c *testing.T) { // Not applicable as Windows does not support --net=host testRequires(c, DaemonIsLinux, NotUserNamespace, NotUserNamespace) - dockerCmd(c, "run", "-d", "--net=host", "--name=first", "busybox", "top") - dockerCmd(c, "run", "-d", "--net=host", "--name=second", "busybox", "top") - dockerCmd(c, "stop", "first") - dockerCmd(c, "stop", "second") + cli.DockerCmd(c, "run", "-d", "--net=host", "--name=first", "busybox", "top") + cli.DockerCmd(c, "run", "-d", "--net=host", "--name=second", "busybox", "top") + cli.DockerCmd(c, "stop", "first") + cli.DockerCmd(c, "stop", "second") } func (s *DockerCLIRunSuite) TestContainersInUserDefinedNetwork(c *testing.T) { testRequires(c, DaemonIsLinux, NotUserNamespace) - dockerCmd(c, "network", "create", "-d", "bridge", "testnetwork") - dockerCmd(c, "run", "-d", "--net=testnetwork", "--name=first", "busybox", "top") - assert.Assert(c, waitRun("first") == nil) - dockerCmd(c, "run", "-t", "--net=testnetwork", "--name=second", "busybox", "ping", "-c", "1", "first") + cli.DockerCmd(c, "network", "create", "-d", "bridge", "testnetwork") + cli.DockerCmd(c, "run", "-d", "--net=testnetwork", "--name=first", "busybox", "top") + cli.WaitRun(c, "first") + cli.DockerCmd(c, "run", "-t", "--net=testnetwork", "--name=second", "busybox", "ping", "-c", "1", "first") } func (s *DockerCLIRunSuite) TestContainersInMultipleNetworks(c *testing.T) { testRequires(c, DaemonIsLinux, NotUserNamespace) // Create 2 networks using bridge driver - dockerCmd(c, "network", "create", "-d", "bridge", "testnetwork1") - dockerCmd(c, "network", "create", "-d", "bridge", "testnetwork2") + cli.DockerCmd(c, "network", "create", "-d", "bridge", "testnetwork1") + cli.DockerCmd(c, "network", "create", "-d", "bridge", "testnetwork2") // Run and connect containers to testnetwork1 - dockerCmd(c, "run", "-d", "--net=testnetwork1", "--name=first", "busybox", "top") - assert.Assert(c, waitRun("first") == nil) - dockerCmd(c, "run", "-d", "--net=testnetwork1", "--name=second", "busybox", "top") - assert.Assert(c, waitRun("second") == nil) + cli.DockerCmd(c, "run", "-d", "--net=testnetwork1", "--name=first", "busybox", "top") + cli.WaitRun(c, "first") + cli.DockerCmd(c, "run", "-d", "--net=testnetwork1", "--name=second", "busybox", "top") + cli.WaitRun(c, "second") // Check connectivity between containers in testnetwork2 - dockerCmd(c, "exec", "first", "ping", "-c", "1", "second.testnetwork1") + cli.DockerCmd(c, "exec", "first", "ping", "-c", "1", "second.testnetwork1") // Connect containers to testnetwork2 - dockerCmd(c, "network", "connect", "testnetwork2", "first") - dockerCmd(c, "network", "connect", "testnetwork2", "second") + cli.DockerCmd(c, "network", "connect", "testnetwork2", "first") + cli.DockerCmd(c, "network", "connect", "testnetwork2", "second") // Check connectivity between containers - dockerCmd(c, "exec", "second", "ping", "-c", "1", "first.testnetwork2") + cli.DockerCmd(c, "exec", "second", "ping", "-c", "1", "first.testnetwork2") } func (s *DockerCLIRunSuite) TestContainersNetworkIsolation(c *testing.T) { testRequires(c, DaemonIsLinux, NotUserNamespace) // Create 2 networks using bridge driver - dockerCmd(c, "network", "create", "-d", "bridge", "testnetwork1") - dockerCmd(c, "network", "create", "-d", "bridge", "testnetwork2") + cli.DockerCmd(c, "network", "create", "-d", "bridge", "testnetwork1") + cli.DockerCmd(c, "network", "create", "-d", "bridge", "testnetwork2") // Run 1 container in testnetwork1 and another in testnetwork2 - dockerCmd(c, "run", "-d", "--net=testnetwork1", "--name=first", "busybox", "top") - assert.Assert(c, waitRun("first") == nil) - dockerCmd(c, "run", "-d", "--net=testnetwork2", "--name=second", "busybox", "top") - assert.Assert(c, waitRun("second") == nil) + cli.DockerCmd(c, "run", "-d", "--net=testnetwork1", "--name=first", "busybox", "top") + cli.WaitRun(c, "first") + cli.DockerCmd(c, "run", "-d", "--net=testnetwork2", "--name=second", "busybox", "top") + cli.WaitRun(c, "second") // Check Isolation between containers : ping must fail _, _, err := dockerCmdWithError("exec", "first", "ping", "-c", "1", "second") assert.ErrorContains(c, err, "") // Connect first container to testnetwork2 - dockerCmd(c, "network", "connect", "testnetwork2", "first") + cli.DockerCmd(c, "network", "connect", "testnetwork2", "first") // ping must succeed now _, _, err = dockerCmdWithError("exec", "first", "ping", "-c", "1", "second") assert.NilError(c, err) // Disconnect first container from testnetwork2 - dockerCmd(c, "network", "disconnect", "testnetwork2", "first") + cli.DockerCmd(c, "network", "disconnect", "testnetwork2", "first") // ping must fail again _, _, err = dockerCmdWithError("exec", "first", "ping", "-c", "1", "second") assert.ErrorContains(c, err, "") @@ -3494,17 +3478,17 @@ func (s *DockerCLIRunSuite) TestContainersNetworkIsolation(c *testing.T) { func (s *DockerCLIRunSuite) TestNetworkRmWithActiveContainers(c *testing.T) { testRequires(c, DaemonIsLinux, NotUserNamespace) // Create 2 networks using bridge driver - dockerCmd(c, "network", "create", "-d", "bridge", "testnetwork1") + cli.DockerCmd(c, "network", "create", "-d", "bridge", "testnetwork1") // Run and connect containers to testnetwork1 - dockerCmd(c, "run", "-d", "--net=testnetwork1", "--name=first", "busybox", "top") - assert.Assert(c, waitRun("first") == nil) - dockerCmd(c, "run", "-d", "--net=testnetwork1", "--name=second", "busybox", "top") - assert.Assert(c, waitRun("second") == nil) + cli.DockerCmd(c, "run", "-d", "--net=testnetwork1", "--name=first", "busybox", "top") + cli.WaitRun(c, "first") + cli.DockerCmd(c, "run", "-d", "--net=testnetwork1", "--name=second", "busybox", "top") + cli.WaitRun(c, "second") // Network delete with active containers must fail _, _, err := dockerCmdWithError("network", "rm", "testnetwork1") assert.ErrorContains(c, err, "") - dockerCmd(c, "stop", "first") + cli.DockerCmd(c, "stop", "first") _, _, err = dockerCmdWithError("network", "rm", "testnetwork1") assert.ErrorContains(c, err, "") } @@ -3512,43 +3496,43 @@ func (s *DockerCLIRunSuite) TestNetworkRmWithActiveContainers(c *testing.T) { func (s *DockerCLIRunSuite) TestContainerRestartInMultipleNetworks(c *testing.T) { testRequires(c, DaemonIsLinux, NotUserNamespace) // Create 2 networks using bridge driver - dockerCmd(c, "network", "create", "-d", "bridge", "testnetwork1") - dockerCmd(c, "network", "create", "-d", "bridge", "testnetwork2") + cli.DockerCmd(c, "network", "create", "-d", "bridge", "testnetwork1") + cli.DockerCmd(c, "network", "create", "-d", "bridge", "testnetwork2") // Run and connect containers to testnetwork1 - dockerCmd(c, "run", "-d", "--net=testnetwork1", "--name=first", "busybox", "top") - assert.Assert(c, waitRun("first") == nil) - dockerCmd(c, "run", "-d", "--net=testnetwork1", "--name=second", "busybox", "top") - assert.Assert(c, waitRun("second") == nil) + cli.DockerCmd(c, "run", "-d", "--net=testnetwork1", "--name=first", "busybox", "top") + cli.WaitRun(c, "first") + cli.DockerCmd(c, "run", "-d", "--net=testnetwork1", "--name=second", "busybox", "top") + cli.WaitRun(c, "second") // Check connectivity between containers in testnetwork2 - dockerCmd(c, "exec", "first", "ping", "-c", "1", "second.testnetwork1") + cli.DockerCmd(c, "exec", "first", "ping", "-c", "1", "second.testnetwork1") // Connect containers to testnetwork2 - dockerCmd(c, "network", "connect", "testnetwork2", "first") - dockerCmd(c, "network", "connect", "testnetwork2", "second") + cli.DockerCmd(c, "network", "connect", "testnetwork2", "first") + cli.DockerCmd(c, "network", "connect", "testnetwork2", "second") // Check connectivity between containers - dockerCmd(c, "exec", "second", "ping", "-c", "1", "first.testnetwork2") + cli.DockerCmd(c, "exec", "second", "ping", "-c", "1", "first.testnetwork2") // Stop second container and test ping failures on both networks - dockerCmd(c, "stop", "second") + cli.DockerCmd(c, "stop", "second") _, _, err := dockerCmdWithError("exec", "first", "ping", "-c", "1", "second.testnetwork1") assert.ErrorContains(c, err, "") _, _, err = dockerCmdWithError("exec", "first", "ping", "-c", "1", "second.testnetwork2") assert.ErrorContains(c, err, "") // Start second container and connectivity must be restored on both networks - dockerCmd(c, "start", "second") - dockerCmd(c, "exec", "first", "ping", "-c", "1", "second.testnetwork1") - dockerCmd(c, "exec", "second", "ping", "-c", "1", "first.testnetwork2") + cli.DockerCmd(c, "start", "second") + cli.DockerCmd(c, "exec", "first", "ping", "-c", "1", "second.testnetwork1") + cli.DockerCmd(c, "exec", "second", "ping", "-c", "1", "first.testnetwork2") } func (s *DockerCLIRunSuite) TestContainerWithConflictingHostNetworks(c *testing.T) { testRequires(c, DaemonIsLinux, NotUserNamespace) // Run a container with --net=host - dockerCmd(c, "run", "-d", "--net=host", "--name=first", "busybox", "top") - assert.Assert(c, waitRun("first") == nil) + cli.DockerCmd(c, "run", "-d", "--net=host", "--name=first", "busybox", "top") + cli.WaitRun(c, "first") // Create a network using bridge driver - dockerCmd(c, "network", "create", "-d", "bridge", "testnetwork1") + cli.DockerCmd(c, "network", "create", "-d", "bridge", "testnetwork1") // Connecting to the user defined network must fail _, _, err := dockerCmdWithError("network", "connect", "testnetwork1", "first") @@ -3557,14 +3541,14 @@ func (s *DockerCLIRunSuite) TestContainerWithConflictingHostNetworks(c *testing. func (s *DockerCLIRunSuite) TestContainerWithConflictingSharedNetwork(c *testing.T) { testRequires(c, DaemonIsLinux) - dockerCmd(c, "run", "-d", "--name=first", "busybox", "top") - assert.Assert(c, waitRun("first") == nil) + cli.DockerCmd(c, "run", "-d", "--name=first", "busybox", "top") + cli.WaitRun(c, "first") // Run second container in first container's network namespace - dockerCmd(c, "run", "-d", "--net=container:first", "--name=second", "busybox", "top") - assert.Assert(c, waitRun("second") == nil) + cli.DockerCmd(c, "run", "-d", "--net=container:first", "--name=second", "busybox", "top") + cli.WaitRun(c, "second") // Create a network using bridge driver - dockerCmd(c, "network", "create", "-d", "bridge", "testnetwork1") + cli.DockerCmd(c, "network", "create", "-d", "bridge", "testnetwork1") // Connecting to the user defined network must fail out, _, err := dockerCmdWithError("network", "connect", "testnetwork1", "second") @@ -3574,19 +3558,19 @@ func (s *DockerCLIRunSuite) TestContainerWithConflictingSharedNetwork(c *testing func (s *DockerCLIRunSuite) TestContainerWithConflictingNoneNetwork(c *testing.T) { testRequires(c, DaemonIsLinux) - dockerCmd(c, "run", "-d", "--net=none", "--name=first", "busybox", "top") - assert.Assert(c, waitRun("first") == nil) + cli.DockerCmd(c, "run", "-d", "--net=none", "--name=first", "busybox", "top") + cli.WaitRun(c, "first") // Create a network using bridge driver - dockerCmd(c, "network", "create", "-d", "bridge", "testnetwork1") + cli.DockerCmd(c, "network", "create", "-d", "bridge", "testnetwork1") // Connecting to the user defined network must fail out, _, err := dockerCmdWithError("network", "connect", "testnetwork1", "first") assert.ErrorContains(c, err, "") assert.Assert(c, strings.Contains(out, runconfig.ErrConflictNoNetwork.Error())) // create a container connected to testnetwork1 - dockerCmd(c, "run", "-d", "--net=testnetwork1", "--name=second", "busybox", "top") - assert.Assert(c, waitRun("second") == nil) + cli.DockerCmd(c, "run", "-d", "--net=testnetwork1", "--name=second", "busybox", "top") + cli.WaitRun(c, "second") // Connect second container to none network. it must fail as well _, _, err = dockerCmdWithError("network", "connect", "none", "second") @@ -3713,7 +3697,7 @@ func (s *DockerCLIRunSuite) TestRunInitLayerPathOwnership(c *testing.T) { RUN chown dockerio:dockerio /etc`)) // Test that dockerio ownership of /etc is retained at runtime - out, _ := dockerCmd(c, "run", "--rm", name, "stat", "-c", "%U:%G", "/etc") + out := cli.DockerCmd(c, "run", "--rm", name, "stat", "-c", "%U:%G", "/etc").Combined() out = strings.TrimSpace(out) if out != "dockerio:dockerio" { c.Fatalf("Wrong /etc ownership: expected dockerio:dockerio, got %q", out) @@ -3723,10 +3707,10 @@ func (s *DockerCLIRunSuite) TestRunInitLayerPathOwnership(c *testing.T) { func (s *DockerCLIRunSuite) TestRunWithOomScoreAdj(c *testing.T) { testRequires(c, DaemonIsLinux) - expected := "642" - out, _ := dockerCmd(c, "run", "--oom-score-adj", expected, "busybox", "cat", "/proc/self/oom_score_adj") + const expected = "642" + out := cli.DockerCmd(c, "run", "--oom-score-adj", expected, "busybox", "cat", "/proc/self/oom_score_adj").Combined() oomScoreAdj := strings.TrimSpace(out) - if oomScoreAdj != "642" { + if oomScoreAdj != expected { c.Fatalf("Expected oom_score_adj set to %q, got %q instead", expected, oomScoreAdj) } } @@ -3764,34 +3748,34 @@ func (s *DockerCLIRunSuite) TestRunNamedVolumeCopyImageData(c *testing.T) { RUN mkdir -p /foo && echo hello > /foo/hello `)) - dockerCmd(c, "run", "-v", "foo:/foo", testImg) - out, _ := dockerCmd(c, "run", "-v", "foo:/foo", "busybox", "cat", "/foo/hello") + cli.DockerCmd(c, "run", "-v", "foo:/foo", testImg) + out := cli.DockerCmd(c, "run", "-v", "foo:/foo", "busybox", "cat", "/foo/hello").Stdout() assert.Equal(c, strings.TrimSpace(out), "hello") } func (s *DockerCLIRunSuite) TestRunNamedVolumeNotRemoved(c *testing.T) { prefix, _ := getPrefixAndSlashFromDaemonPlatform() - dockerCmd(c, "volume", "create", "test") + cli.DockerCmd(c, "volume", "create", "test") - dockerCmd(c, "run", "--rm", "-v", "test:"+prefix+"/foo", "-v", prefix+"/bar", "busybox", "true") - dockerCmd(c, "volume", "inspect", "test") - out, _ := dockerCmd(c, "volume", "ls", "-q") + cli.DockerCmd(c, "run", "--rm", "-v", "test:"+prefix+"/foo", "-v", prefix+"/bar", "busybox", "true") + cli.DockerCmd(c, "volume", "inspect", "test") + out := cli.DockerCmd(c, "volume", "ls", "-q").Combined() assert.Assert(c, strings.Contains(out, "test")) - dockerCmd(c, "run", "--name=test", "-v", "test:"+prefix+"/foo", "-v", prefix+"/bar", "busybox", "true") - dockerCmd(c, "rm", "-fv", "test") - dockerCmd(c, "volume", "inspect", "test") - out, _ = dockerCmd(c, "volume", "ls", "-q") + cli.DockerCmd(c, "run", "--name=test", "-v", "test:"+prefix+"/foo", "-v", prefix+"/bar", "busybox", "true") + cli.DockerCmd(c, "rm", "-fv", "test") + cli.DockerCmd(c, "volume", "inspect", "test") + out = cli.DockerCmd(c, "volume", "ls", "-q").Combined() assert.Assert(c, strings.Contains(out, "test")) } func (s *DockerCLIRunSuite) TestRunNamedVolumesFromNotRemoved(c *testing.T) { prefix, _ := getPrefixAndSlashFromDaemonPlatform() - dockerCmd(c, "volume", "create", "test") - cid, _ := dockerCmd(c, "run", "-d", "--name=parent", "-v", "test:"+prefix+"/foo", "-v", prefix+"/bar", "busybox", "true") - dockerCmd(c, "run", "--name=child", "--volumes-from=parent", "busybox", "true") + cli.DockerCmd(c, "volume", "create", "test") + cid := cli.DockerCmd(c, "run", "-d", "--name=parent", "-v", "test:"+prefix+"/foo", "-v", prefix+"/bar", "busybox", "true").Stdout() + cli.DockerCmd(c, "run", "--name=child", "--volumes-from=parent", "busybox", "true") apiClient, err := client.NewClientWithOpts(client.FromEnv) assert.NilError(c, err) @@ -3808,11 +3792,11 @@ func (s *DockerCLIRunSuite) TestRunNamedVolumesFromNotRemoved(c *testing.T) { assert.Assert(c, vname != "") // Remove the parent so there are not other references to the volumes - dockerCmd(c, "rm", "-f", "parent") + cli.DockerCmd(c, "rm", "-f", "parent") // now remove the child and ensure the named volume (and only the named volume) still exists - dockerCmd(c, "rm", "-fv", "child") - dockerCmd(c, "volume", "inspect", "test") - out, _ := dockerCmd(c, "volume", "ls", "-q") + cli.DockerCmd(c, "rm", "-fv", "child") + cli.DockerCmd(c, "volume", "inspect", "test") + out := cli.DockerCmd(c, "volume", "ls", "-q").Combined() assert.Assert(c, strings.Contains(out, "test")) assert.Assert(c, !strings.Contains(strings.TrimSpace(out), vname)) } @@ -3872,7 +3856,7 @@ func (s *DockerCLIRunSuite) TestRunAttachFailedNoLeak(c *testing.T) { func (s *DockerCLIRunSuite) TestRunVolumeWithOneCharacter(c *testing.T) { testRequires(c, DaemonIsLinux) - out, _ := dockerCmd(c, "run", "-v", "/tmp/q:/foo", "busybox", "sh", "-c", "find /foo") + out := cli.DockerCmd(c, "run", "-v", "/tmp/q:/foo", "busybox", "sh", "-c", "find /foo").Combined() assert.Equal(c, strings.TrimSpace(out), "/foo") } @@ -3881,23 +3865,23 @@ func (s *DockerCLIRunSuite) TestRunVolumeCopyFlag(c *testing.T) { buildImageSuccessfully(c, "volumecopy", build.WithDockerfile(`FROM busybox RUN mkdir /foo && echo hello > /foo/bar CMD cat /foo/bar`)) - dockerCmd(c, "volume", "create", "test") + cli.DockerCmd(c, "volume", "create", "test") // test with the nocopy flag out, _, err := dockerCmdWithError("run", "-v", "test:/foo:nocopy", "volumecopy") assert.ErrorContains(c, err, "", out) // test default behavior which is to copy for non-binds - out, _ = dockerCmd(c, "run", "-v", "test:/foo", "volumecopy") + out = cli.DockerCmd(c, "run", "-v", "test:/foo", "volumecopy").Combined() assert.Equal(c, strings.TrimSpace(out), "hello") // error out when the volume is already populated out, _, err = dockerCmdWithError("run", "-v", "test:/foo:copy", "volumecopy") assert.ErrorContains(c, err, "", out) // do not error out when copy isn't explicitly set even though it's already populated - out, _ = dockerCmd(c, "run", "-v", "test:/foo", "volumecopy") + out = cli.DockerCmd(c, "run", "-v", "test:/foo", "volumecopy").Combined() assert.Equal(c, strings.TrimSpace(out), "hello") // do not allow copy modes on volumes-from - dockerCmd(c, "run", "--name=test", "-v", "/foo", "busybox", "true") + cli.DockerCmd(c, "run", "--name=test", "-v", "/foo", "busybox", "true") out, _, err = dockerCmdWithError("run", "--volumes-from=test:copy", "busybox", "true") assert.ErrorContains(c, err, "", out) out, _, err = dockerCmdWithError("run", "--volumes-from=test:nocopy", "busybox", "true") @@ -3950,12 +3934,12 @@ func (s *DockerCLIRunSuite) TestRunAddHostInHostMode(c *testing.T) { testRequires(c, DaemonIsLinux, NotUserNamespace) expectedOutput := "1.2.3.4\textra" - out, _ := dockerCmd(c, "run", "--add-host=extra:1.2.3.4", "--net=host", "busybox", "cat", "/etc/hosts") + out := cli.DockerCmd(c, "run", "--add-host=extra:1.2.3.4", "--net=host", "busybox", "cat", "/etc/hosts").Combined() assert.Assert(c, strings.Contains(out, expectedOutput), "Expected '%s', but got %q", expectedOutput, out) } func (s *DockerCLIRunSuite) TestRunRmAndWait(c *testing.T) { - dockerCmd(c, "run", "--name=test", "--rm", "-d", "busybox", "sh", "-c", "sleep 3;exit 2") + cli.DockerCmd(c, "run", "--name=test", "--rm", "-d", "busybox", "sh", "-c", "sleep 3;exit 2") out, code, err := dockerCmdWithError("wait", "test") assert.Assert(c, err == nil, "out: %s; exit code: %d", out, code) @@ -4088,7 +4072,7 @@ func (s *DockerCLIRunSuite) TestRunCredentialSpecWellFormed(c *testing.T) { for _, value := range []string{"file://valid.json", "raw://" + validCredSpecs} { // `nltest /PARENTDOMAIN` simply reads the local config, and does not require having an AD // controller handy - out, _ := dockerCmd(c, "run", "--rm", "--security-opt=credentialspec="+value, minimalBaseImage(), "nltest", "/PARENTDOMAIN") + out := cli.DockerCmd(c, "run", "--rm", "--security-opt=credentialspec="+value, minimalBaseImage(), "nltest", "/PARENTDOMAIN").Combined() assert.Assert(c, strings.Contains(out, "hyperv.local.")) assert.Assert(c, strings.Contains(out, "The command completed successfully")) @@ -4108,7 +4092,7 @@ func (s *DockerCLIRunSuite) TestRunDuplicateMount(c *testing.T) { } name := "test" - out, _ := dockerCmd(c, "run", "--name", name, "-v", "/tmp:/tmp", "-v", "/tmp:/tmp", "busybox", "sh", "-c", "cat "+tmpFile.Name()+" && ls /") + out := cli.DockerCmd(c, "run", "--name", name, "-v", "/tmp:/tmp", "-v", "/tmp:/tmp", "busybox", "sh", "-c", "cat "+tmpFile.Name()+" && ls /").Combined() assert.Assert(c, !strings.Contains(out, "tmp:")) assert.Assert(c, strings.Contains(out, data)) out = inspectFieldJSON(c, name, "Config.Volumes") @@ -4118,7 +4102,7 @@ func (s *DockerCLIRunSuite) TestRunDuplicateMount(c *testing.T) { func (s *DockerCLIRunSuite) TestRunWindowsWithCPUCount(c *testing.T) { testRequires(c, DaemonIsWindows) - out, _ := dockerCmd(c, "run", "--cpu-count=1", "--name", "test", "busybox", "echo", "testing") + out := cli.DockerCmd(c, "run", "--cpu-count=1", "--name", "test", "busybox", "echo", "testing").Combined() assert.Equal(c, strings.TrimSpace(out), "testing") out = inspectField(c, "test", "HostConfig.CPUCount") @@ -4128,7 +4112,7 @@ func (s *DockerCLIRunSuite) TestRunWindowsWithCPUCount(c *testing.T) { func (s *DockerCLIRunSuite) TestRunWindowsWithCPUShares(c *testing.T) { testRequires(c, DaemonIsWindows) - out, _ := dockerCmd(c, "run", "--cpu-shares=1000", "--name", "test", "busybox", "echo", "testing") + out := cli.DockerCmd(c, "run", "--cpu-shares=1000", "--name", "test", "busybox", "echo", "testing").Combined() assert.Equal(c, strings.TrimSpace(out), "testing") out = inspectField(c, "test", "HostConfig.CPUShares") @@ -4138,7 +4122,7 @@ func (s *DockerCLIRunSuite) TestRunWindowsWithCPUShares(c *testing.T) { func (s *DockerCLIRunSuite) TestRunWindowsWithCPUPercent(c *testing.T) { testRequires(c, DaemonIsWindows) - out, _ := dockerCmd(c, "run", "--cpu-percent=80", "--name", "test", "busybox", "echo", "testing") + out := cli.DockerCmd(c, "run", "--cpu-percent=80", "--name", "test", "busybox", "echo", "testing").Combined() assert.Equal(c, strings.TrimSpace(out), "testing") out = inspectField(c, "test", "HostConfig.CPUPercent") @@ -4148,7 +4132,7 @@ func (s *DockerCLIRunSuite) TestRunWindowsWithCPUPercent(c *testing.T) { func (s *DockerCLIRunSuite) TestRunProcessIsolationWithCPUCountCPUSharesAndCPUPercent(c *testing.T) { testRequires(c, DaemonIsWindows, testEnv.DaemonInfo.Isolation.IsProcess) - out, _ := dockerCmd(c, "run", "--cpu-count=1", "--cpu-shares=1000", "--cpu-percent=80", "--name", "test", "busybox", "echo", "testing") + out := cli.DockerCmd(c, "run", "--cpu-count=1", "--cpu-shares=1000", "--cpu-percent=80", "--name", "test", "busybox", "echo", "testing").Combined() assert.Assert(c, strings.Contains(strings.TrimSpace(out), "WARNING: Conflicting options: CPU count takes priority over CPU shares on Windows Server Containers. CPU shares discarded")) assert.Assert(c, strings.Contains(strings.TrimSpace(out), "WARNING: Conflicting options: CPU count takes priority over CPU percent on Windows Server Containers. CPU percent discarded")) assert.Assert(c, strings.Contains(strings.TrimSpace(out), "testing")) @@ -4165,7 +4149,7 @@ func (s *DockerCLIRunSuite) TestRunProcessIsolationWithCPUCountCPUSharesAndCPUPe func (s *DockerCLIRunSuite) TestRunHypervIsolationWithCPUCountCPUSharesAndCPUPercent(c *testing.T) { testRequires(c, DaemonIsWindows, testEnv.DaemonInfo.Isolation.IsHyperV) - out, _ := dockerCmd(c, "run", "--cpu-count=1", "--cpu-shares=1000", "--cpu-percent=80", "--name", "test", "busybox", "echo", "testing") + out := cli.DockerCmd(c, "run", "--cpu-count=1", "--cpu-shares=1000", "--cpu-percent=80", "--name", "test", "busybox", "echo", "testing").Combined() assert.Assert(c, strings.Contains(strings.TrimSpace(out), "testing")) out = inspectField(c, "test", "HostConfig.CPUCount") assert.Equal(c, out, "1") @@ -4270,11 +4254,11 @@ func (s *DockerCLIRunSuite) TestRunMount(c *testing.T) { c.Fatal(err) } testCatFooBar := func(cName string) error { - out, _ := dockerCmd(c, "exec", cName, "cat", "/foo/test1") + out := cli.DockerCmd(c, "exec", cName, "cat", "/foo/test1").Stdout() if out != "test1" { return fmt.Errorf("%s not mounted on /foo", mnt1) } - out, _ = dockerCmd(c, "exec", cName, "cat", "/bar/test2") + out = cli.DockerCmd(c, "exec", cName, "cat", "/bar/test2").Stdout() if out != "test2" { return fmt.Errorf("%s not mounted on /bar", mnt2) } @@ -4361,7 +4345,7 @@ func (s *DockerCLIRunSuite) TestRunMount(c *testing.T) { }, valid: true, fn: func(cName string) error { - out, _ := dockerCmd(c, "exec", cName, "cat", "/foo/test1") + out := cli.DockerCmd(c, "exec", cName, "cat", "/foo/test1").Combined() if out != "test1" { return fmt.Errorf("%s not mounted on /foo", mnt1) } @@ -4414,7 +4398,7 @@ func (s *DockerCLIRunSuite) TestRunMount(c *testing.T) { if testCase.valid { assert.Assert(c, err == nil, "got error while creating a container with %v (%s)", opts, cName) assert.Assert(c, testCase.fn(cName) == nil, "got error while executing test for %v (%s)", opts, cName) - dockerCmd(c, "rm", "-f", cName) + cli.DockerCmd(c, "rm", "-f", cName) } else { assert.Assert(c, err != nil, "got nil while creating a container with %v (%s)", opts, cName) } @@ -4428,10 +4412,10 @@ func (s *DockerCLIRunSuite) TestRunHostnameFQDN(c *testing.T) { testRequires(c, DaemonIsLinux) expectedOutput := "foobar.example.com\nfoobar.example.com\nfoobar\nexample.com\nfoobar.example.com" - out, _ := dockerCmd(c, "run", "--hostname=foobar.example.com", "busybox", "sh", "-c", `cat /etc/hostname && hostname && hostname -s && hostname -d && hostname -f`) + out := cli.DockerCmd(c, "run", "--hostname=foobar.example.com", "busybox", "sh", "-c", `cat /etc/hostname && hostname && hostname -s && hostname -d && hostname -f`).Combined() assert.Equal(c, strings.TrimSpace(out), expectedOutput) - out, _ = dockerCmd(c, "run", "--hostname=foobar.example.com", "busybox", "sh", "-c", `cat /etc/hosts`) + out = cli.DockerCmd(c, "run", "--hostname=foobar.example.com", "busybox", "sh", "-c", `cat /etc/hosts`).Combined() expectedOutput = "foobar.example.com foobar" assert.Assert(c, strings.Contains(strings.TrimSpace(out), expectedOutput)) } @@ -4440,28 +4424,28 @@ func (s *DockerCLIRunSuite) TestRunHostnameFQDN(c *testing.T) { func (s *DockerCLIRunSuite) TestRunHostnameInHostMode(c *testing.T) { testRequires(c, DaemonIsLinux, NotUserNamespace) - expectedOutput := "foobar\nfoobar" - out, _ := dockerCmd(c, "run", "--net=host", "--hostname=foobar", "busybox", "sh", "-c", `echo $HOSTNAME && hostname`) + const expectedOutput = "foobar\nfoobar" + out := cli.DockerCmd(c, "run", "--net=host", "--hostname=foobar", "busybox", "sh", "-c", `echo $HOSTNAME && hostname`).Combined() assert.Equal(c, strings.TrimSpace(out), expectedOutput) } func (s *DockerCLIRunSuite) TestRunAddDeviceCgroupRule(c *testing.T) { testRequires(c, DaemonIsLinux) - deviceRule := "c 7:128 rwm" + const deviceRule = "c 7:128 rwm" - out, _ := dockerCmd(c, "run", "--rm", "busybox", "cat", "/sys/fs/cgroup/devices/devices.list") + out := cli.DockerCmd(c, "run", "--rm", "busybox", "cat", "/sys/fs/cgroup/devices/devices.list").Combined() if strings.Contains(out, deviceRule) { c.Fatalf("%s shouldn't been in the device.list", deviceRule) } - out, _ = dockerCmd(c, "run", "--rm", fmt.Sprintf("--device-cgroup-rule=%s", deviceRule), "busybox", "grep", deviceRule, "/sys/fs/cgroup/devices/devices.list") + out = cli.DockerCmd(c, "run", "--rm", fmt.Sprintf("--device-cgroup-rule=%s", deviceRule), "busybox", "grep", deviceRule, "/sys/fs/cgroup/devices/devices.list").Combined() assert.Equal(c, strings.TrimSpace(out), deviceRule) } // Verifies that running as local system is operating correctly on Windows func (s *DockerCLIRunSuite) TestWindowsRunAsSystem(c *testing.T) { testRequires(c, DaemonIsWindows) - out, _ := dockerCmd(c, "run", "--net=none", `--user=nt authority\system`, "--hostname=XYZZY", minimalBaseImage(), "cmd", "/c", `@echo %USERNAME%`) + out := cli.DockerCmd(c, "run", "--net=none", `--user=nt authority\system`, "--hostname=XYZZY", minimalBaseImage(), "cmd", "/c", `@echo %USERNAME%`).Combined() assert.Equal(c, strings.TrimSpace(out), "XYZZY$") } diff --git a/integration-cli/docker_cli_run_unix_test.go b/integration-cli/docker_cli_run_unix_test.go index d2049bb4fc..014137755f 100644 --- a/integration-cli/docker_cli_run_unix_test.go +++ b/integration-cli/docker_cli_run_unix_test.go @@ -75,7 +75,7 @@ func (s *DockerCLIRunSuite) TestRunWithVolumesIsRecursive(c *testing.T) { assert.NilError(c, err) defer f.Close() - out, _ := dockerCmd(c, "run", "--name", "test-data", "--volume", fmt.Sprintf("%s:/tmp:ro", tmpDir), "busybox:latest", "ls", "/tmp/tmpfs") + out := cli.DockerCmd(c, "run", "--name", "test-data", "--volume", fmt.Sprintf("%s:/tmp:ro", tmpDir), "busybox:latest", "ls", "/tmp/tmpfs").Combined() assert.Assert(c, strings.Contains(out, filepath.Base(f.Name())), "Recursive bind mount test failed. Expected file not found") } @@ -85,17 +85,17 @@ func (s *DockerCLIRunSuite) TestRunDeviceDirectory(c *testing.T) { c.Skip("Host does not have /dev/snd") } - out, _ := dockerCmd(c, "run", "--device", "/dev/snd:/dev/snd", "busybox", "sh", "-c", "ls /dev/snd/") + out := cli.DockerCmd(c, "run", "--device", "/dev/snd:/dev/snd", "busybox", "sh", "-c", "ls /dev/snd/").Combined() assert.Assert(c, strings.Contains(strings.Trim(out, "\r\n"), "timer"), "expected output /dev/snd/timer") - out, _ = dockerCmd(c, "run", "--device", "/dev/snd:/dev/othersnd", "busybox", "sh", "-c", "ls /dev/othersnd/") + out = cli.DockerCmd(c, "run", "--device", "/dev/snd:/dev/othersnd", "busybox", "sh", "-c", "ls /dev/othersnd/").Combined() assert.Assert(c, strings.Contains(strings.Trim(out, "\r\n"), "seq"), "expected output /dev/othersnd/seq") } // TestRunAttachDetach checks attaching and detaching with the default escape sequence. func (s *DockerCLIRunSuite) TestRunAttachDetach(c *testing.T) { - name := "attach-detach" + const name = "attach-detach" - dockerCmd(c, "run", "--name", name, "-itd", "busybox", "cat") + cli.DockerCmd(c, "run", "--name", name, "-itd", "busybox", "cat") cmd := exec.Command(dockerBinary, "attach", name) stdout, err := cmd.StdoutPipe() @@ -105,7 +105,7 @@ func (s *DockerCLIRunSuite) TestRunAttachDetach(c *testing.T) { defer cpty.Close() cmd.Stdin = tty assert.NilError(c, cmd.Start()) - assert.Assert(c, waitRun(name) == nil) + cli.WaitRun(c, name) _, err = cpty.Write([]byte("hello\n")) assert.NilError(c, err) @@ -136,7 +136,7 @@ func (s *DockerCLIRunSuite) TestRunAttachDetach(c *testing.T) { running := inspectField(c, name, "State.Running") assert.Equal(c, running, "true", "expected container to still be running") - out, _ = dockerCmd(c, "events", "--since=0", "--until", daemonUnixTime(c), "-f", "container="+name) + out = cli.DockerCmd(c, "events", "--since=0", "--until", daemonUnixTime(c), "-f", "container="+name).Stdout() // attach and detach event should be monitored assert.Assert(c, strings.Contains(out, "attach")) assert.Assert(c, strings.Contains(out, "detach")) @@ -144,11 +144,11 @@ func (s *DockerCLIRunSuite) TestRunAttachDetach(c *testing.T) { // TestRunAttachDetachFromFlag checks attaching and detaching with the escape sequence specified via flags. func (s *DockerCLIRunSuite) TestRunAttachDetachFromFlag(c *testing.T) { - name := "attach-detach" + const name = "attach-detach" keyCtrlA := []byte{1} keyA := []byte{97} - dockerCmd(c, "run", "--name", name, "-itd", "busybox", "cat") + cli.DockerCmd(c, "run", "--name", name, "-itd", "busybox", "cat") cmd := exec.Command(dockerBinary, "attach", "--detach-keys=ctrl-a,a", name) stdout, err := cmd.StdoutPipe() @@ -164,7 +164,7 @@ func (s *DockerCLIRunSuite) TestRunAttachDetachFromFlag(c *testing.T) { if err := cmd.Start(); err != nil { c.Fatal(err) } - assert.Assert(c, waitRun(name) == nil) + cli.WaitRun(c, name) if _, err := cpty.Write([]byte("hello\n")); err != nil { c.Fatal(err) @@ -205,9 +205,9 @@ func (s *DockerCLIRunSuite) TestRunAttachDetachFromFlag(c *testing.T) { // TestRunAttachDetachFromInvalidFlag checks attaching and detaching with the escape sequence specified via flags. func (s *DockerCLIRunSuite) TestRunAttachDetachFromInvalidFlag(c *testing.T) { - name := "attach-detach" - dockerCmd(c, "run", "--name", name, "-itd", "busybox", "top") - assert.Assert(c, waitRun(name) == nil) + const name = "attach-detach" + cli.DockerCmd(c, "run", "--name", name, "-itd", "busybox", "top") + cli.WaitRun(c, name) // specify an invalid detach key, container will ignore it and use default cmd := exec.Command(dockerBinary, "attach", "--detach-keys=ctrl-A,a", name) @@ -264,8 +264,8 @@ func (s *DockerCLIRunSuite) TestRunAttachDetachFromConfig(c *testing.T) { assert.NilError(c, err) // Then do the work - name := "attach-detach" - dockerCmd(c, "run", "--name", name, "-itd", "busybox", "cat") + const name = "attach-detach" + cli.DockerCmd(c, "run", "--name", name, "-itd", "busybox", "cat") cmd := exec.Command(dockerBinary, "attach", name) stdout, err := cmd.StdoutPipe() @@ -281,7 +281,7 @@ func (s *DockerCLIRunSuite) TestRunAttachDetachFromConfig(c *testing.T) { if err := cmd.Start(); err != nil { c.Fatal(err) } - assert.Assert(c, waitRun(name) == nil) + cli.WaitRun(c, name) if _, err := cpty.Write([]byte("hello\n")); err != nil { c.Fatal(err) @@ -348,8 +348,8 @@ func (s *DockerCLIRunSuite) TestRunAttachDetachKeysOverrideConfig(c *testing.T) assert.NilError(c, err) // Then do the work - name := "attach-detach" - dockerCmd(c, "run", "--name", name, "-itd", "busybox", "cat") + const name = "attach-detach" + cli.DockerCmd(c, "run", "--name", name, "-itd", "busybox", "cat") cmd := exec.Command(dockerBinary, "attach", "--detach-keys=ctrl-a,a", name) stdout, err := cmd.StdoutPipe() @@ -365,7 +365,7 @@ func (s *DockerCLIRunSuite) TestRunAttachDetachKeysOverrideConfig(c *testing.T) if err := cmd.Start(); err != nil { c.Fatal(err) } - assert.Assert(c, waitRun(name) == nil) + cli.WaitRun(c, name) if _, err := cpty.Write([]byte("hello\n")); err != nil { c.Fatal(err) @@ -405,11 +405,11 @@ func (s *DockerCLIRunSuite) TestRunAttachDetachKeysOverrideConfig(c *testing.T) } func (s *DockerCLIRunSuite) TestRunAttachInvalidDetachKeySequencePreserved(c *testing.T) { - name := "attach-detach" + const name = "attach-detach" keyA := []byte{97} keyB := []byte{98} - dockerCmd(c, "run", "--name", name, "-itd", "busybox", "cat") + cli.DockerCmd(c, "run", "--name", name, "-itd", "busybox", "cat") cmd := exec.Command(dockerBinary, "attach", "--detach-keys=a,b,c", name) stdout, err := cmd.StdoutPipe() @@ -426,7 +426,7 @@ func (s *DockerCLIRunSuite) TestRunAttachInvalidDetachKeySequencePreserved(c *te c.Fatal(err) } go cmd.Wait() - assert.Assert(c, waitRun(name) == nil) + cli.WaitRun(c, name) // Invalid escape sequence aba, should print aba in output if _, err := cpty.Write(keyA); err != nil { @@ -458,8 +458,8 @@ func (s *DockerCLIRunSuite) TestRunAttachInvalidDetachKeySequencePreserved(c *te func (s *DockerCLIRunSuite) TestRunWithCPUQuota(c *testing.T) { testRequires(c, cpuCfsQuota) - file := "/sys/fs/cgroup/cpu/cpu.cfs_quota_us" - out, _ := dockerCmd(c, "run", "--cpu-quota", "8000", "--name", "test", "busybox", "cat", file) + const file = "/sys/fs/cgroup/cpu/cpu.cfs_quota_us" + out := cli.DockerCmd(c, "run", "--cpu-quota", "8000", "--name", "test", "busybox", "cat", file).Combined() assert.Equal(c, strings.TrimSpace(out), "8000") out = inspectField(c, "test", "HostConfig.CpuQuota") @@ -469,11 +469,11 @@ func (s *DockerCLIRunSuite) TestRunWithCPUQuota(c *testing.T) { func (s *DockerCLIRunSuite) TestRunWithCpuPeriod(c *testing.T) { testRequires(c, cpuCfsPeriod) - file := "/sys/fs/cgroup/cpu/cpu.cfs_period_us" - out, _ := dockerCmd(c, "run", "--cpu-period", "50000", "--name", "test", "busybox", "cat", file) + const file = "/sys/fs/cgroup/cpu/cpu.cfs_period_us" + out := cli.DockerCmd(c, "run", "--cpu-period", "50000", "--name", "test", "busybox", "cat", file).Combined() assert.Equal(c, strings.TrimSpace(out), "50000") - out, _ = dockerCmd(c, "run", "--cpu-period", "0", "busybox", "cat", file) + out = cli.DockerCmd(c, "run", "--cpu-period", "0", "busybox", "cat", file).Combined() assert.Equal(c, strings.TrimSpace(out), "100000") out = inspectField(c, "test", "HostConfig.CpuPeriod") @@ -499,8 +499,8 @@ func (s *DockerCLIRunSuite) TestRunWithInvalidCpuPeriod(c *testing.T) { func (s *DockerCLIRunSuite) TestRunWithCPUShares(c *testing.T) { testRequires(c, cpuShare) - file := "/sys/fs/cgroup/cpu/cpu.shares" - out, _ := dockerCmd(c, "run", "--cpu-shares", "1000", "--name", "test", "busybox", "cat", file) + const file = "/sys/fs/cgroup/cpu/cpu.shares" + out := cli.DockerCmd(c, "run", "--cpu-shares", "1000", "--name", "test", "busybox", "cat", file).Combined() assert.Equal(c, strings.TrimSpace(out), "1000") out = inspectField(c, "test", "HostConfig.CPUShares") @@ -519,8 +519,8 @@ func (s *DockerCLIRunSuite) TestRunEchoStdoutWithCPUSharesAndMemoryLimit(c *test func (s *DockerCLIRunSuite) TestRunWithCpusetCpus(c *testing.T) { testRequires(c, cgroupCpuset) - file := "/sys/fs/cgroup/cpuset/cpuset.cpus" - out, _ := dockerCmd(c, "run", "--cpuset-cpus", "0", "--name", "test", "busybox", "cat", file) + const file = "/sys/fs/cgroup/cpuset/cpuset.cpus" + out := cli.DockerCmd(c, "run", "--cpuset-cpus", "0", "--name", "test", "busybox", "cat", file).Combined() assert.Equal(c, strings.TrimSpace(out), "0") out = inspectField(c, "test", "HostConfig.CpusetCpus") @@ -530,8 +530,8 @@ func (s *DockerCLIRunSuite) TestRunWithCpusetCpus(c *testing.T) { func (s *DockerCLIRunSuite) TestRunWithCpusetMems(c *testing.T) { testRequires(c, cgroupCpuset) - file := "/sys/fs/cgroup/cpuset/cpuset.mems" - out, _ := dockerCmd(c, "run", "--cpuset-mems", "0", "--name", "test", "busybox", "cat", file) + const file = "/sys/fs/cgroup/cpuset/cpuset.mems" + out := cli.DockerCmd(c, "run", "--cpuset-mems", "0", "--name", "test", "busybox", "cat", file).Combined() assert.Equal(c, strings.TrimSpace(out), "0") out = inspectField(c, "test", "HostConfig.CpusetMems") @@ -541,8 +541,8 @@ func (s *DockerCLIRunSuite) TestRunWithCpusetMems(c *testing.T) { func (s *DockerCLIRunSuite) TestRunWithBlkioWeight(c *testing.T) { testRequires(c, blkioWeight) - file := "/sys/fs/cgroup/blkio/blkio.weight" - out, _ := dockerCmd(c, "run", "--blkio-weight", "300", "--name", "test", "busybox", "cat", file) + const file = "/sys/fs/cgroup/blkio/blkio.weight" + out := cli.DockerCmd(c, "run", "--blkio-weight", "300", "--name", "test", "busybox", "cat", file).Combined() assert.Equal(c, strings.TrimSpace(out), "300") out = inspectField(c, "test", "HostConfig.BlkioWeight") @@ -610,7 +610,7 @@ func (s *DockerCLIRunSuite) TestRunOOMExitCode(c *testing.T) { func (s *DockerCLIRunSuite) TestRunWithMemoryLimit(c *testing.T) { testRequires(c, memoryLimitSupport) - file := "/sys/fs/cgroup/memory/memory.limit_in_bytes" + const file = "/sys/fs/cgroup/memory/memory.limit_in_bytes" cli.DockerCmd(c, "run", "-m", "32M", "--name", "test", "busybox", "cat", file).Assert(c, icmd.Expected{ Out: "33554432", }) @@ -627,13 +627,13 @@ func (s *DockerCLIRunSuite) TestRunWithoutMemoryswapLimit(c *testing.T) { testRequires(c, DaemonIsLinux) testRequires(c, memoryLimitSupport) testRequires(c, swapMemorySupport) - dockerCmd(c, "run", "-m", "32m", "--memory-swap", "-1", "busybox", "true") + cli.DockerCmd(c, "run", "-m", "32m", "--memory-swap", "-1", "busybox", "true") } func (s *DockerCLIRunSuite) TestRunWithSwappiness(c *testing.T) { testRequires(c, memorySwappinessSupport) - file := "/sys/fs/cgroup/memory/memory.swappiness" - out, _ := dockerCmd(c, "run", "--memory-swappiness", "0", "--name", "test", "busybox", "cat", file) + const file = "/sys/fs/cgroup/memory/memory.swappiness" + out := cli.DockerCmd(c, "run", "--memory-swappiness", "0", "--name", "test", "busybox", "cat", file).Combined() assert.Equal(c, strings.TrimSpace(out), "0") out = inspectField(c, "test", "HostConfig.MemorySwappiness") @@ -654,8 +654,8 @@ func (s *DockerCLIRunSuite) TestRunWithSwappinessInvalid(c *testing.T) { func (s *DockerCLIRunSuite) TestRunWithMemoryReservation(c *testing.T) { testRequires(c, testEnv.IsLocalDaemon, memoryReservationSupport) - file := "/sys/fs/cgroup/memory/memory.soft_limit_in_bytes" - out, _ := dockerCmd(c, "run", "--memory-reservation", "200M", "--name", "test", "busybox", "cat", file) + const file = "/sys/fs/cgroup/memory/memory.soft_limit_in_bytes" + out := cli.DockerCmd(c, "run", "--memory-reservation", "200M", "--name", "test", "busybox", "cat", file).Combined() assert.Equal(c, strings.TrimSpace(out), "209715200") out = inspectField(c, "test", "HostConfig.MemoryReservation") @@ -676,13 +676,12 @@ func (s *DockerCLIRunSuite) TestRunWithMemoryReservationInvalid(c *testing.T) { } func (s *DockerCLIRunSuite) TestStopContainerSignal(c *testing.T) { - out, _ := dockerCmd(c, "run", "--stop-signal", "SIGUSR1", "-d", "busybox", "/bin/sh", "-c", `trap 'echo "exit trapped"; exit 0' USR1; while true; do sleep 1; done`) - containerID := strings.TrimSpace(out) + containerID := cli.DockerCmd(c, "run", "--stop-signal", "SIGUSR1", "-d", "busybox", "/bin/sh", "-c", `trap 'echo "exit trapped"; exit 0' USR1; while true; do sleep 1; done`).Stdout() + containerID = strings.TrimSpace(containerID) + cli.WaitRun(c, containerID) - assert.Assert(c, waitRun(containerID) == nil) - - dockerCmd(c, "stop", containerID) - out, _ = dockerCmd(c, "logs", containerID) + cli.DockerCmd(c, "stop", containerID) + out := cli.DockerCmd(c, "logs", containerID).Combined() assert.Assert(c, strings.Contains(out, "exit trapped"), "Expected `exit trapped` in the log") } @@ -756,8 +755,8 @@ func (s *DockerCLIRunSuite) TestRunInvalidCPUShares(c *testing.T) { func (s *DockerCLIRunSuite) TestRunWithDefaultShmSize(c *testing.T) { testRequires(c, DaemonIsLinux) - name := "shm-default" - out, _ := dockerCmd(c, "run", "--name", name, "busybox", "mount") + const name = "shm-default" + out := cli.DockerCmd(c, "run", "--name", name, "busybox", "mount").Combined() shmRegex := regexp.MustCompile(`shm on /dev/shm type tmpfs(.*)size=65536k`) if !shmRegex.MatchString(out) { c.Fatalf("Expected shm of 64MB in mount command, got %v", out) @@ -769,8 +768,8 @@ func (s *DockerCLIRunSuite) TestRunWithDefaultShmSize(c *testing.T) { func (s *DockerCLIRunSuite) TestRunWithShmSize(c *testing.T) { testRequires(c, DaemonIsLinux) - name := "shm" - out, _ := dockerCmd(c, "run", "--name", name, "--shm-size=1G", "busybox", "mount") + const name = "shm" + out := cli.DockerCmd(c, "run", "--name", name, "--shm-size=1G", "busybox", "mount").Combined() shmRegex := regexp.MustCompile(`shm on /dev/shm type tmpfs(.*)size=1048576k`) if !shmRegex.MatchString(out) { c.Fatalf("Expected shm of 1GB in mount command, got %v", out) @@ -783,7 +782,7 @@ func (s *DockerCLIRunSuite) TestRunTmpfsMountsEnsureOrdered(c *testing.T) { tmpFile, err := os.CreateTemp("", "test") assert.NilError(c, err) defer tmpFile.Close() - out, _ := dockerCmd(c, "run", "--tmpfs", "/run", "-v", tmpFile.Name()+":/run/test", "busybox", "ls", "/run") + out := cli.DockerCmd(c, "run", "--tmpfs", "/run", "-v", tmpFile.Name()+":/run/test", "busybox", "ls", "/run").Combined() assert.Assert(c, strings.Contains(out, "test")) } @@ -809,13 +808,13 @@ func (s *DockerCLIRunSuite) TestRunTmpfsMounts(c *testing.T) { } func (s *DockerCLIRunSuite) TestRunTmpfsMountsOverrideImageVolumes(c *testing.T) { - name := "img-with-volumes" + const name = "img-with-volumes" buildImageSuccessfully(c, name, build.WithDockerfile(` FROM busybox VOLUME /run RUN touch /run/stuff `)) - out, _ := dockerCmd(c, "run", "--tmpfs", "/run", name, "ls", "/run") + out := cli.DockerCmd(c, "run", "--tmpfs", "/run", name, "ls", "/run").Combined() assert.Assert(c, !strings.Contains(out, "stuff")) } @@ -824,25 +823,25 @@ func (s *DockerCLIRunSuite) TestRunTmpfsMountsWithOptions(c *testing.T) { testRequires(c, DaemonIsLinux) expectedOptions := []string{"rw", "nosuid", "nodev", "noexec", "relatime"} - out, _ := dockerCmd(c, "run", "--tmpfs", "/tmp", "busybox", "sh", "-c", "mount | grep 'tmpfs on /tmp'") + out := cli.DockerCmd(c, "run", "--tmpfs", "/tmp", "busybox", "sh", "-c", "mount | grep 'tmpfs on /tmp'").Combined() for _, option := range expectedOptions { assert.Assert(c, strings.Contains(out, option)) } assert.Assert(c, !strings.Contains(out, "size=")) expectedOptions = []string{"rw", "nosuid", "nodev", "noexec", "relatime"} - out, _ = dockerCmd(c, "run", "--tmpfs", "/tmp:rw", "busybox", "sh", "-c", "mount | grep 'tmpfs on /tmp'") + out = cli.DockerCmd(c, "run", "--tmpfs", "/tmp:rw", "busybox", "sh", "-c", "mount | grep 'tmpfs on /tmp'").Combined() for _, option := range expectedOptions { assert.Assert(c, strings.Contains(out, option)) } assert.Assert(c, !strings.Contains(out, "size=")) expectedOptions = []string{"rw", "nosuid", "nodev", "relatime", "size=8192k"} - out, _ = dockerCmd(c, "run", "--tmpfs", "/tmp:rw,exec,size=8192k", "busybox", "sh", "-c", "mount | grep 'tmpfs on /tmp'") + out = cli.DockerCmd(c, "run", "--tmpfs", "/tmp:rw,exec,size=8192k", "busybox", "sh", "-c", "mount | grep 'tmpfs on /tmp'").Combined() for _, option := range expectedOptions { assert.Assert(c, strings.Contains(out, option)) } expectedOptions = []string{"rw", "nosuid", "nodev", "noexec", "relatime", "size=4096k"} - out, _ = dockerCmd(c, "run", "--tmpfs", "/tmp:rw,size=8192k,exec,size=4096k,noexec", "busybox", "sh", "-c", "mount | grep 'tmpfs on /tmp'") + out = cli.DockerCmd(c, "run", "--tmpfs", "/tmp:rw,size=8192k,exec,size=4096k,noexec", "busybox", "sh", "-c", "mount | grep 'tmpfs on /tmp'").Combined() for _, option := range expectedOptions { assert.Assert(c, strings.Contains(out, option)) } @@ -852,7 +851,7 @@ func (s *DockerCLIRunSuite) TestRunTmpfsMountsWithOptions(c *testing.T) { // /tmp shared // so we only capture `shared` here. expectedOptions = []string{"shared"} - out, _ = dockerCmd(c, "run", "--tmpfs", "/tmp:shared", "debian:bullseye-slim", "findmnt", "-o", "TARGET,PROPAGATION", "/tmp") + out = cli.DockerCmd(c, "run", "--tmpfs", "/tmp:shared", "debian:bullseye-slim", "findmnt", "-o", "TARGET,PROPAGATION", "/tmp").Combined() for _, option := range expectedOptions { assert.Assert(c, strings.Contains(out, option)) } @@ -862,7 +861,7 @@ func (s *DockerCLIRunSuite) TestRunSysctls(c *testing.T) { testRequires(c, DaemonIsLinux) var err error - out, _ := dockerCmd(c, "run", "--sysctl", "net.ipv4.ip_forward=1", "--name", "test", "busybox", "cat", "/proc/sys/net/ipv4/ip_forward") + out := cli.DockerCmd(c, "run", "--sysctl", "net.ipv4.ip_forward=1", "--name", "test", "busybox", "cat", "/proc/sys/net/ipv4/ip_forward").Combined() assert.Equal(c, strings.TrimSpace(out), "1") out = inspectFieldJSON(c, "test", "HostConfig.Sysctls") @@ -872,7 +871,7 @@ func (s *DockerCLIRunSuite) TestRunSysctls(c *testing.T) { assert.NilError(c, err) assert.Equal(c, sysctls["net.ipv4.ip_forward"], "1") - out, _ = dockerCmd(c, "run", "--sysctl", "net.ipv4.ip_forward=0", "--name", "test1", "busybox", "cat", "/proc/sys/net/ipv4/ip_forward") + out = cli.DockerCmd(c, "run", "--sysctl", "net.ipv4.ip_forward=0", "--name", "test1", "busybox", "cat", "/proc/sys/net/ipv4/ip_forward").Combined() assert.Equal(c, strings.TrimSpace(out), "0") out = inspectFieldJSON(c, "test1", "HostConfig.Sysctls") @@ -891,7 +890,7 @@ func (s *DockerCLIRunSuite) TestRunSysctls(c *testing.T) { // TestRunSeccompProfileDenyUnshare checks that 'docker run --security-opt seccomp=/tmp/profile.json debian:bullseye-slim unshare' exits with operation not permitted. func (s *DockerCLIRunSuite) TestRunSeccompProfileDenyUnshare(c *testing.T) { testRequires(c, testEnv.IsLocalDaemon, seccompEnabled, Apparmor) - jsonData := `{ + const jsonData = `{ "defaultAction": "SCMP_ACT_ALLOW", "syscalls": [ { @@ -920,7 +919,7 @@ func (s *DockerCLIRunSuite) TestRunSeccompProfileDenyUnshare(c *testing.T) { // TestRunSeccompProfileDenyChmod checks that 'docker run --security-opt seccomp=/tmp/profile.json busybox chmod 400 /etc/hostname' exits with operation not permitted. func (s *DockerCLIRunSuite) TestRunSeccompProfileDenyChmod(c *testing.T) { testRequires(c, testEnv.IsLocalDaemon, seccompEnabled) - jsonData := `{ + const jsonData = `{ "defaultAction": "SCMP_ACT_ALLOW", "syscalls": [ { @@ -1139,7 +1138,7 @@ func (s *DockerCLIRunSuite) TestUserNoEffectiveCapabilitiesChown(c *testing.T) { ensureSyscallTest(testutil.GetContext(c), c) // test that a root user has default capability CAP_CHOWN - dockerCmd(c, "run", "busybox", "chown", "100", "/tmp") + cli.DockerCmd(c, "run", "busybox", "chown", "100", "/tmp") // test that non root user does not have default capability CAP_CHOWN icmd.RunCommand(dockerBinary, "run", "--user", "1000:1000", "busybox", "chown", "100", "/tmp").Assert(c, icmd.Expected{ ExitCode: 1, @@ -1157,7 +1156,7 @@ func (s *DockerCLIRunSuite) TestUserNoEffectiveCapabilitiesDacOverride(c *testin ensureSyscallTest(testutil.GetContext(c), c) // test that a root user has default capability CAP_DAC_OVERRIDE - dockerCmd(c, "run", "busybox", "sh", "-c", "echo test > /etc/passwd") + cli.DockerCmd(c, "run", "busybox", "sh", "-c", "echo test > /etc/passwd") // test that non root user does not have default capability CAP_DAC_OVERRIDE icmd.RunCommand(dockerBinary, "run", "--user", "1000:1000", "busybox", "sh", "-c", "echo test > /etc/passwd").Assert(c, icmd.Expected{ ExitCode: 1, @@ -1170,7 +1169,7 @@ func (s *DockerCLIRunSuite) TestUserNoEffectiveCapabilitiesFowner(c *testing.T) ensureSyscallTest(testutil.GetContext(c), c) // test that a root user has default capability CAP_FOWNER - dockerCmd(c, "run", "busybox", "chmod", "777", "/etc/passwd") + cli.DockerCmd(c, "run", "busybox", "chmod", "777", "/etc/passwd") // test that non root user does not have default capability CAP_FOWNER icmd.RunCommand(dockerBinary, "run", "--user", "1000:1000", "busybox", "chmod", "777", "/etc/passwd").Assert(c, icmd.Expected{ ExitCode: 1, @@ -1186,7 +1185,7 @@ func (s *DockerCLIRunSuite) TestUserNoEffectiveCapabilitiesSetuid(c *testing.T) ensureSyscallTest(testutil.GetContext(c), c) // test that a root user has default capability CAP_SETUID - dockerCmd(c, "run", "syscall-test", "setuid-test") + cli.DockerCmd(c, "run", "syscall-test", "setuid-test") // test that non root user does not have default capability CAP_SETUID icmd.RunCommand(dockerBinary, "run", "--user", "1000:1000", "syscall-test", "setuid-test").Assert(c, icmd.Expected{ ExitCode: 1, @@ -1204,7 +1203,7 @@ func (s *DockerCLIRunSuite) TestUserNoEffectiveCapabilitiesSetgid(c *testing.T) ensureSyscallTest(testutil.GetContext(c), c) // test that a root user has default capability CAP_SETGID - dockerCmd(c, "run", "syscall-test", "setgid-test") + cli.DockerCmd(c, "run", "syscall-test", "setgid-test") // test that non root user does not have default capability CAP_SETGID icmd.RunCommand(dockerBinary, "run", "--user", "1000:1000", "syscall-test", "setgid-test").Assert(c, icmd.Expected{ ExitCode: 1, @@ -1232,7 +1231,7 @@ func (s *DockerCLIRunSuite) TestUserNoEffectiveCapabilitiesNetBindService(c *tes ensureSyscallTest(testutil.GetContext(c), c) // test that a root user has default capability CAP_NET_BIND_SERVICE - dockerCmd(c, "run", "syscall-test", "socket-test") + cli.DockerCmd(c, "run", "syscall-test", "socket-test") // test that non root user does not have default capability CAP_NET_BIND_SERVICE // as we allow this via sysctl, also tweak the sysctl back to default args := []string{"run", "--user", "1000:1000"} @@ -1261,7 +1260,7 @@ func (s *DockerCLIRunSuite) TestUserNoEffectiveCapabilitiesNetRaw(c *testing.T) ensureSyscallTest(testutil.GetContext(c), c) // test that a root user has default capability CAP_NET_RAW - dockerCmd(c, "run", "syscall-test", "raw-test") + cli.DockerCmd(c, "run", "syscall-test", "raw-test") // test that non root user does not have default capability CAP_NET_RAW icmd.RunCommand(dockerBinary, "run", "--user", "1000:1000", "syscall-test", "raw-test").Assert(c, icmd.Expected{ ExitCode: 1, @@ -1279,7 +1278,7 @@ func (s *DockerCLIRunSuite) TestUserNoEffectiveCapabilitiesChroot(c *testing.T) ensureSyscallTest(testutil.GetContext(c), c) // test that a root user has default capability CAP_SYS_CHROOT - dockerCmd(c, "run", "busybox", "chroot", "/", "/bin/true") + cli.DockerCmd(c, "run", "busybox", "chroot", "/", "/bin/true") // test that non root user does not have default capability CAP_SYS_CHROOT icmd.RunCommand(dockerBinary, "run", "--user", "1000:1000", "busybox", "chroot", "/", "/bin/true").Assert(c, icmd.Expected{ ExitCode: 1, @@ -1297,7 +1296,7 @@ func (s *DockerCLIRunSuite) TestUserNoEffectiveCapabilitiesMknod(c *testing.T) { ensureSyscallTest(testutil.GetContext(c), c) // test that a root user has default capability CAP_MKNOD - dockerCmd(c, "run", "busybox", "mknod", "/tmp/node", "b", "1", "2") + cli.DockerCmd(c, "run", "busybox", "mknod", "/tmp/node", "b", "1", "2") // test that non root user does not have default capability CAP_MKNOD // test that root user can drop default capability CAP_SYS_CHROOT icmd.RunCommand(dockerBinary, "run", "--user", "1000:1000", "busybox", "mknod", "/tmp/node", "b", "1", "2").Assert(c, icmd.Expected{ @@ -1377,14 +1376,14 @@ func (s *DockerCLIRunSuite) TestRunDeviceSymlink(c *testing.T) { defer os.Remove("/dev/symzero") // md5sum of 'dd if=/dev/zero bs=4K count=8' is bb7df04e1b0a2570657527a7e108ae23 - out, _ := dockerCmd(c, "run", "--device", symZero+":/dev/symzero", "busybox", "sh", "-c", "dd if=/dev/symzero bs=4K count=8 | md5sum") + out := cli.DockerCmd(c, "run", "--device", symZero+":/dev/symzero", "busybox", "sh", "-c", "dd if=/dev/symzero bs=4K count=8 | md5sum").Combined() assert.Assert(c, strings.Contains(strings.Trim(out, "\r\n"), "bb7df04e1b0a2570657527a7e108ae23"), "expected output bb7df04e1b0a2570657527a7e108ae23") // symlink "tmpDir/file" to a file "tmpDir/temp" will result in an error as it is not a device. out, _, err = dockerCmdWithError("run", "--device", symFile+":/dev/symzero", "busybox", "sh", "-c", "dd if=/dev/symzero bs=4K count=8 | md5sum") assert.ErrorContains(c, err, "") assert.Assert(c, strings.Contains(strings.Trim(out, "\r\n"), "not a device node"), "expected output 'not a device node'") // md5sum of 'dd if=/dev/zero bs=4K count=8' is bb7df04e1b0a2570657527a7e108ae23 (this time check with relative path backed, see #22271) - out, _ = dockerCmd(c, "run", "--device", "/dev/symzero:/dev/symzero", "busybox", "sh", "-c", "dd if=/dev/symzero bs=4K count=8 | md5sum") + out = cli.DockerCmd(c, "run", "--device", "/dev/symzero:/dev/symzero", "busybox", "sh", "-c", "dd if=/dev/symzero bs=4K count=8 | md5sum").Combined() assert.Assert(c, strings.Contains(strings.Trim(out, "\r\n"), "bb7df04e1b0a2570657527a7e108ae23"), "expected output bb7df04e1b0a2570657527a7e108ae23") } @@ -1392,8 +1391,8 @@ func (s *DockerCLIRunSuite) TestRunDeviceSymlink(c *testing.T) { func (s *DockerCLIRunSuite) TestRunPIDsLimit(c *testing.T) { testRequires(c, testEnv.IsLocalDaemon, pidsLimit) - file := "/sys/fs/cgroup/pids/pids.max" - out, _ := dockerCmd(c, "run", "--name", "skittles", "--pids-limit", "4", "busybox", "cat", file) + const file = "/sys/fs/cgroup/pids/pids.max" + out := cli.DockerCmd(c, "run", "--name", "skittles", "--pids-limit", "4", "busybox", "cat", file).Combined() assert.Equal(c, strings.TrimSpace(out), "4") out = inspectField(c, "skittles", "HostConfig.PidsLimit") @@ -1403,8 +1402,8 @@ func (s *DockerCLIRunSuite) TestRunPIDsLimit(c *testing.T) { func (s *DockerCLIRunSuite) TestRunPrivilegedAllowedDevices(c *testing.T) { testRequires(c, DaemonIsLinux, NotUserNamespace) - file := "/sys/fs/cgroup/devices/devices.list" - out, _ := dockerCmd(c, "run", "--privileged", "busybox", "cat", file) + const file = "/sys/fs/cgroup/devices/devices.list" + out := cli.DockerCmd(c, "run", "--privileged", "busybox", "cat", file).Combined() c.Logf("out: %q", out) assert.Equal(c, strings.TrimSpace(out), "a *:* rwm") } @@ -1421,8 +1420,8 @@ func (s *DockerCLIRunSuite) TestRunUserDeviceAllowed(c *testing.T) { c.Skip("Could not stat /dev/snd/timer") } - file := "/sys/fs/cgroup/devices/devices.list" - out, _ := dockerCmd(c, "run", "--device", "/dev/snd/timer:w", "busybox", "cat", file) + const file = "/sys/fs/cgroup/devices/devices.list" + out := cli.DockerCmd(c, "run", "--device", "/dev/snd/timer:w", "busybox", "cat", file).Combined() assert.Assert(c, strings.Contains(out, fmt.Sprintf("c %d:%d w", stat.Rdev/256, stat.Rdev%256))) } @@ -1432,7 +1431,7 @@ func (s *DockerDaemonSuite) TestRunSeccompJSONNewFormat(c *testing.T) { s.d.StartWithBusybox(ctx, c) - jsonData := `{ + const jsonData = `{ "defaultAction": "SCMP_ACT_ALLOW", "syscalls": [ { @@ -1458,7 +1457,7 @@ func (s *DockerDaemonSuite) TestRunSeccompJSONNoNameAndNames(c *testing.T) { s.d.StartWithBusybox(ctx, c) - jsonData := `{ + const jsonData = `{ "defaultAction": "SCMP_ACT_ALLOW", "syscalls": [ { @@ -1485,7 +1484,7 @@ func (s *DockerDaemonSuite) TestRunSeccompJSONNoArchAndArchMap(c *testing.T) { s.d.StartWithBusybox(ctx, c) - jsonData := `{ + const jsonData = `{ "archMap": [ { "architecture": "SCMP_ARCH_X86_64", @@ -1527,7 +1526,7 @@ func (s *DockerDaemonSuite) TestRunWithDaemonDefaultSeccompProfile(c *testing.T) _, err := s.d.Cmd("run", "busybox", "chmod", "777", ".") assert.NilError(c, err) - jsonData := `{ + const jsonData = `{ "defaultAction": "SCMP_ACT_ALLOW", "syscalls": [ { @@ -1557,9 +1556,9 @@ func (s *DockerDaemonSuite) TestRunWithDaemonDefaultSeccompProfile(c *testing.T) func (s *DockerCLIRunSuite) TestRunWithNanoCPUs(c *testing.T) { testRequires(c, cpuCfsQuota, cpuCfsPeriod) - file1 := "/sys/fs/cgroup/cpu/cpu.cfs_quota_us" - file2 := "/sys/fs/cgroup/cpu/cpu.cfs_period_us" - out, _ := dockerCmd(c, "run", "--cpus", "0.5", "--name", "test", "busybox", "sh", "-c", fmt.Sprintf("cat %s && cat %s", file1, file2)) + const file1 = "/sys/fs/cgroup/cpu/cpu.cfs_quota_us" + const file2 = "/sys/fs/cgroup/cpu/cpu.cfs_period_us" + out := cli.DockerCmd(c, "run", "--cpus", "0.5", "--name", "test", "busybox", "sh", "-c", fmt.Sprintf("cat %s && cat %s", file1, file2)).Combined() assert.Equal(c, strings.TrimSpace(out), "50000\n100000") clt, err := client.NewClientWithOpts(client.FromEnv) diff --git a/integration-cli/docker_cli_save_load_test.go b/integration-cli/docker_cli_save_load_test.go index 033cdeaada..492b1da330 100644 --- a/integration-cli/docker_cli_save_load_test.go +++ b/integration-cli/docker_cli_save_load_test.go @@ -11,6 +11,7 @@ import ( "testing" "github.com/docker/docker/api/types" + "github.com/docker/docker/integration-cli/cli" "github.com/docker/docker/integration-cli/cli/build" "gotest.tools/v3/assert" is "gotest.tools/v3/assert/cmp" @@ -34,19 +35,19 @@ func (s *DockerCLISaveLoadSuite) OnTimeout(c *testing.T) { func (s *DockerCLISaveLoadSuite) TestSaveXzAndLoadRepoStdout(c *testing.T) { testRequires(c, DaemonIsLinux) name := "test-save-xz-and-load-repo-stdout" - dockerCmd(c, "run", "--name", name, "busybox", "true") + cli.DockerCmd(c, "run", "--name", name, "busybox", "true") - repoName := "foobar-save-load-test-xz-gz" - out, _ := dockerCmd(c, "commit", name, repoName) + imgRepoName := "foobar-save-load-test-xz-gz" + out := cli.DockerCmd(c, "commit", name, imgRepoName).Combined() - dockerCmd(c, "inspect", repoName) + cli.DockerCmd(c, "inspect", imgRepoName) repoTarball, err := RunCommandPipelineWithOutput( - exec.Command(dockerBinary, "save", repoName), + exec.Command(dockerBinary, "save", imgRepoName), exec.Command("xz", "-c"), exec.Command("gzip", "-c")) assert.NilError(c, err, "failed to save repo: %v %v", out, err) - deleteImages(repoName) + deleteImages(imgRepoName) icmd.RunCmd(icmd.Cmd{ Command: []string{dockerBinary, "load"}, @@ -55,7 +56,7 @@ func (s *DockerCLISaveLoadSuite) TestSaveXzAndLoadRepoStdout(c *testing.T) { ExitCode: 1, }) - after, _, err := dockerCmdWithError("inspect", repoName) + after, _, err := dockerCmdWithError("inspect", imgRepoName) assert.ErrorContains(c, err, "", "the repo should not exist: %v", after) } @@ -63,12 +64,12 @@ func (s *DockerCLISaveLoadSuite) TestSaveXzAndLoadRepoStdout(c *testing.T) { func (s *DockerCLISaveLoadSuite) TestSaveXzGzAndLoadRepoStdout(c *testing.T) { testRequires(c, DaemonIsLinux) name := "test-save-xz-gz-and-load-repo-stdout" - dockerCmd(c, "run", "--name", name, "busybox", "true") + cli.DockerCmd(c, "run", "--name", name, "busybox", "true") repoName := "foobar-save-load-test-xz-gz" - dockerCmd(c, "commit", name, repoName) + cli.DockerCmd(c, "commit", name, repoName) - dockerCmd(c, "inspect", repoName) + cli.DockerCmd(c, "inspect", repoName) out, err := RunCommandPipelineWithOutput( exec.Command(dockerBinary, "save", repoName), @@ -91,10 +92,10 @@ func (s *DockerCLISaveLoadSuite) TestSaveXzGzAndLoadRepoStdout(c *testing.T) { func (s *DockerCLISaveLoadSuite) TestSaveSingleTag(c *testing.T) { testRequires(c, DaemonIsLinux) - repoName := "foobar-save-single-tag-test" - dockerCmd(c, "tag", "busybox:latest", fmt.Sprintf("%v:latest", repoName)) + imgRepoName := "foobar-save-single-tag-test" + cli.DockerCmd(c, "tag", "busybox:latest", fmt.Sprintf("%v:latest", imgRepoName)) - out, _ := dockerCmd(c, "images", "-q", "--no-trunc", repoName) + out := cli.DockerCmd(c, "images", "-q", "--no-trunc", imgRepoName).Stdout() cleanedImageID := strings.TrimSpace(out) filesFilter := fmt.Sprintf("(^manifest.json$|%v)", cleanedImageID) @@ -102,7 +103,7 @@ func (s *DockerCLISaveLoadSuite) TestSaveSingleTag(c *testing.T) { filesFilter = fmt.Sprintf("(^index.json$|^manifest.json$|%v)", cleanedImageID) } out, err := RunCommandPipelineWithOutput( - exec.Command(dockerBinary, "save", fmt.Sprintf("%v:latest", repoName)), + exec.Command(dockerBinary, "save", fmt.Sprintf("%v:latest", imgRepoName)), exec.Command("tar", "t"), exec.Command("grep", "-E", filesFilter)) assert.NilError(c, err, "failed to save repo with image ID and index files: %s, %v", out, err) @@ -110,13 +111,13 @@ func (s *DockerCLISaveLoadSuite) TestSaveSingleTag(c *testing.T) { func (s *DockerCLISaveLoadSuite) TestSaveImageId(c *testing.T) { testRequires(c, DaemonIsLinux) - repoName := "foobar-save-image-id-test" - dockerCmd(c, "tag", "emptyfs:latest", fmt.Sprintf("%v:latest", repoName)) + imgRepoName := "foobar-save-image-id-test" + cli.DockerCmd(c, "tag", "emptyfs:latest", fmt.Sprintf("%v:latest", imgRepoName)) - out, _ := dockerCmd(c, "images", "-q", "--no-trunc", repoName) + out := cli.DockerCmd(c, "images", "-q", "--no-trunc", imgRepoName).Stdout() cleanedLongImageID := strings.TrimPrefix(strings.TrimSpace(out), "sha256:") - out, _ = dockerCmd(c, "images", "-q", repoName) + out = cli.DockerCmd(c, "images", "-q", imgRepoName).Stdout() cleanedShortImageID := strings.TrimSpace(out) // Make sure IDs are not empty @@ -138,7 +139,7 @@ func (s *DockerCLISaveLoadSuite) TestSaveImageId(c *testing.T) { defer func() { saveCmd.Wait() tarCmd.Wait() - dockerCmd(c, "rmi", repoName) + cli.DockerCmd(c, "rmi", imgRepoName) }() out, _, err = runCommandWithOutput(grepCmd) @@ -149,24 +150,22 @@ func (s *DockerCLISaveLoadSuite) TestSaveImageId(c *testing.T) { // save a repo and try to load it using flags func (s *DockerCLISaveLoadSuite) TestSaveAndLoadRepoFlags(c *testing.T) { testRequires(c, DaemonIsLinux) - name := "test-save-and-load-repo-flags" - dockerCmd(c, "run", "--name", name, "busybox", "true") + const name = "test-save-and-load-repo-flags" + cli.DockerCmd(c, "run", "--name", name, "busybox", "true") - repoName := "foobar-save-load-test" + const imgRepoName = "foobar-save-load-test" - deleteImages(repoName) - dockerCmd(c, "commit", name, repoName) + deleteImages(imgRepoName) + cli.DockerCmd(c, "commit", name, imgRepoName) - beforeStr, _, err := dockerCmdWithError("inspect", repoName) - assert.NilError(c, err, "failed to inspect before save") + beforeStr := cli.DockerCmd(c, "inspect", imgRepoName).Stdout() out, err := RunCommandPipelineWithOutput( - exec.Command(dockerBinary, "save", repoName), + exec.Command(dockerBinary, "save", imgRepoName), exec.Command(dockerBinary, "load")) assert.NilError(c, err, "failed to save and load repo: %s, %v", out, err) - afterStr, _, err := dockerCmdWithError("inspect", repoName) - assert.NilError(c, err, "failed to inspect after load") + afterStr := cli.DockerCmd(c, "inspect", imgRepoName).Stdout() var before, after []types.ImageInspect err = json.Unmarshal([]byte(beforeStr), &before) @@ -204,13 +203,13 @@ func (s *DockerCLISaveLoadSuite) TestSaveWithNoExistImage(c *testing.T) { func (s *DockerCLISaveLoadSuite) TestSaveMultipleNames(c *testing.T) { testRequires(c, DaemonIsLinux) - repoName := "foobar-save-multi-name-test" + const imgRepoName = "foobar-save-multi-name-test" - oneTag := fmt.Sprintf("%v-one:latest", repoName) - twoTag := fmt.Sprintf("%v-two:latest", repoName) + oneTag := fmt.Sprintf("%v-one:latest", imgRepoName) + twoTag := fmt.Sprintf("%v-two:latest", imgRepoName) - dockerCmd(c, "tag", "emptyfs:latest", oneTag) - dockerCmd(c, "tag", "emptyfs:latest", twoTag) + cli.DockerCmd(c, "tag", "emptyfs:latest", oneTag) + cli.DockerCmd(c, "tag", "emptyfs:latest", twoTag) out, err := RunCommandPipelineWithOutput( exec.Command(dockerBinary, "save", strings.TrimSuffix(oneTag, ":latest"), twoTag), @@ -233,7 +232,7 @@ func (s *DockerCLISaveLoadSuite) TestLoadZeroSizeLayer(c *testing.T) { // very weird test testRequires(c, DaemonIsLinux, testEnv.IsLocalDaemon) - dockerCmd(c, "load", "-i", "testdata/emptyLayer.tar") + cli.DockerCmd(c, "load", "-i", "testdata/emptyLayer.tar") } func (s *DockerCLISaveLoadSuite) TestSaveLoadParents(c *testing.T) { @@ -241,14 +240,13 @@ func (s *DockerCLISaveLoadSuite) TestSaveLoadParents(c *testing.T) { skip.If(c, testEnv.UsingSnapshotter(), "Parent image property is not supported with containerd") makeImage := func(from string, addfile string) string { - var out string - out, _ = dockerCmd(c, "run", "-d", from, "touch", addfile) - cleanedContainerID := strings.TrimSpace(out) + id := cli.DockerCmd(c, "run", "-d", from, "touch", addfile).Stdout() + id = strings.TrimSpace(id) - out, _ = dockerCmd(c, "commit", cleanedContainerID) - imageID := strings.TrimSpace(out) + imageID := cli.DockerCmd(c, "commit", id).Stdout() + imageID = strings.TrimSpace(imageID) - dockerCmd(c, "rm", "-f", cleanedContainerID) + cli.DockerCmd(c, "rm", "-f", id) return imageID } @@ -263,9 +261,9 @@ func (s *DockerCLISaveLoadSuite) TestSaveLoadParents(c *testing.T) { outfile := filepath.Join(tmpDir, "out.tar") - dockerCmd(c, "save", "-o", outfile, idBar, idFoo) - dockerCmd(c, "rmi", idBar) - dockerCmd(c, "load", "-i", outfile) + cli.DockerCmd(c, "save", "-o", outfile, idBar, idFoo) + cli.DockerCmd(c, "rmi", idBar) + cli.DockerCmd(c, "load", "-i", outfile) inspectOut := inspectField(c, idBar, "Parent") assert.Equal(c, inspectOut, idFoo) diff --git a/integration-cli/docker_cli_save_load_unix_test.go b/integration-cli/docker_cli_save_load_unix_test.go index 13e585d3f6..91f3e61706 100644 --- a/integration-cli/docker_cli_save_load_unix_test.go +++ b/integration-cli/docker_cli_save_load_unix_test.go @@ -12,6 +12,7 @@ import ( "time" "github.com/creack/pty" + "github.com/docker/docker/integration-cli/cli" "github.com/docker/docker/integration-cli/cli/build" "github.com/docker/docker/testutil" "gotest.tools/v3/assert" @@ -22,10 +23,10 @@ import ( // save a repo and try to load it using stdout func (s *DockerCLISaveLoadSuite) TestSaveAndLoadRepoStdout(c *testing.T) { name := "test-save-and-load-repo-stdout" - dockerCmd(c, "run", "--name", name, "busybox", "true") + cli.DockerCmd(c, "run", "--name", name, "busybox", "true") - repoName := "foobar-save-load-test" - before, _ := dockerCmd(c, "commit", name, repoName) + imgRepoName := "foobar-save-load-test" + before := cli.DockerCmd(c, "commit", name, imgRepoName).Stdout() before = strings.TrimRight(before, "\n") tmpFile, err := os.CreateTemp("", "foobar-save-load-test.tar") @@ -33,7 +34,7 @@ func (s *DockerCLISaveLoadSuite) TestSaveAndLoadRepoStdout(c *testing.T) { defer os.Remove(tmpFile.Name()) icmd.RunCmd(icmd.Cmd{ - Command: []string{dockerBinary, "save", repoName}, + Command: []string{dockerBinary, "save", imgRepoName}, Stdout: tmpFile, }).Assert(c, icmd.Success) @@ -41,23 +42,23 @@ func (s *DockerCLISaveLoadSuite) TestSaveAndLoadRepoStdout(c *testing.T) { assert.NilError(c, err) defer tmpFile.Close() - deleteImages(repoName) + deleteImages(imgRepoName) icmd.RunCmd(icmd.Cmd{ Command: []string{dockerBinary, "load"}, Stdin: tmpFile, }).Assert(c, icmd.Success) - after := inspectField(c, repoName, "Id") + after := inspectField(c, imgRepoName, "Id") after = strings.TrimRight(after, "\n") assert.Equal(c, after, before, "inspect is not the same after a save / load") - deleteImages(repoName) + deleteImages(imgRepoName) - pty, tty, err := pty.Open() + p, tty, err := pty.Open() assert.NilError(c, err) - cmd := exec.Command(dockerBinary, "save", repoName) + cmd := exec.Command(dockerBinary, "save", imgRepoName) cmd.Stdin = tty cmd.Stdout = tty cmd.Stderr = tty @@ -66,7 +67,7 @@ func (s *DockerCLISaveLoadSuite) TestSaveAndLoadRepoStdout(c *testing.T) { buf := make([]byte, 1024) - n, err := pty.Read(buf) + n, err := p.Read(buf) assert.NilError(c, err, "could not read tty output") assert.Assert(c, strings.Contains(string(buf[:n]), "cowardly refusing"), "help output is not being yielded") } @@ -81,19 +82,19 @@ func (s *DockerCLISaveLoadSuite) TestSaveAndLoadWithProgressBar(c *testing.T) { `)) tmptar := name + ".tar" - dockerCmd(c, "save", "-o", tmptar, name) + cli.DockerCmd(c, "save", "-o", tmptar, name) defer os.Remove(tmptar) - dockerCmd(c, "rmi", name) - dockerCmd(c, "tag", "busybox", name) - out, _ := dockerCmd(c, "load", "-i", tmptar) + cli.DockerCmd(c, "rmi", name) + cli.DockerCmd(c, "tag", "busybox", name) + out := cli.DockerCmd(c, "load", "-i", tmptar).Combined() expected := fmt.Sprintf("The image %s:latest already exists, renaming the old one with ID", name) assert.Assert(c, strings.Contains(out, expected)) } // fail because load didn't receive data from stdin func (s *DockerCLISaveLoadSuite) TestLoadNoStdinFail(c *testing.T) { - pty, tty, err := pty.Open() + p, tty, err := pty.Open() assert.NilError(c, err) ctx, cancel := context.WithTimeout(testutil.GetContext(c), 5*time.Second) defer cancel() @@ -105,7 +106,7 @@ func (s *DockerCLISaveLoadSuite) TestLoadNoStdinFail(c *testing.T) { buf := make([]byte, 1024) - n, err := pty.Read(buf) + n, err := p.Read(buf) assert.NilError(c, err) // could not read tty output assert.Assert(c, strings.Contains(string(buf[:n]), "requested load from stdin, but stdin is empty")) } diff --git a/integration-cli/docker_cli_search_test.go b/integration-cli/docker_cli_search_test.go index af89c7b869..09c3a85720 100644 --- a/integration-cli/docker_cli_search_test.go +++ b/integration-cli/docker_cli_search_test.go @@ -6,6 +6,7 @@ import ( "strings" "testing" + "github.com/docker/docker/integration-cli/cli" "gotest.tools/v3/assert" ) @@ -23,7 +24,7 @@ func (s *DockerCLISearchSuite) OnTimeout(c *testing.T) { // search for repos named "registry" on the central registry func (s *DockerCLISearchSuite) TestSearchOnCentralRegistry(c *testing.T) { - out, _ := dockerCmd(c, "search", "busybox") + out := cli.DockerCmd(c, "search", "busybox").Stdout() assert.Assert(c, strings.Contains(out, "Busybox base image."), "couldn't find any repository named (or containing) 'Busybox base image.'") } @@ -46,35 +47,35 @@ func (s *DockerCLISearchSuite) TestSearchStarsOptionWithWrongParameter(c *testin } func (s *DockerCLISearchSuite) TestSearchCmdOptions(c *testing.T) { - outSearchCmd, _ := dockerCmd(c, "search", "busybox") + outSearchCmd := cli.DockerCmd(c, "search", "busybox").Combined() assert.Assert(c, strings.Count(outSearchCmd, "\n") > 3, outSearchCmd) - outSearchCmdautomated, _ := dockerCmd(c, "search", "--filter", "is-automated=true", "busybox") // The busybox is a busybox base image, not an AUTOMATED image. + outSearchCmdautomated := cli.DockerCmd(c, "search", "--filter", "is-automated=true", "busybox").Combined() // The busybox is a busybox base image, not an AUTOMATED image. outSearchCmdautomatedSlice := strings.Split(outSearchCmdautomated, "\n") for i := range outSearchCmdautomatedSlice { assert.Assert(c, !strings.HasPrefix(outSearchCmdautomatedSlice[i], "busybox "), "The busybox is not an AUTOMATED image: %s", outSearchCmdautomated) } - outSearchCmdNotOfficial, _ := dockerCmd(c, "search", "--filter", "is-official=false", "busybox") // The busybox is a busybox base image, official image. + outSearchCmdNotOfficial := cli.DockerCmd(c, "search", "--filter", "is-official=false", "busybox").Combined() // The busybox is a busybox base image, official image. outSearchCmdNotOfficialSlice := strings.Split(outSearchCmdNotOfficial, "\n") for i := range outSearchCmdNotOfficialSlice { assert.Assert(c, !strings.HasPrefix(outSearchCmdNotOfficialSlice[i], "busybox "), "The busybox is not an OFFICIAL image: %s", outSearchCmdNotOfficial) } - outSearchCmdOfficial, _ := dockerCmd(c, "search", "--filter", "is-official=true", "busybox") // The busybox is a busybox base image, official image. + outSearchCmdOfficial := cli.DockerCmd(c, "search", "--filter", "is-official=true", "busybox").Combined() // The busybox is a busybox base image, official image. outSearchCmdOfficialSlice := strings.Split(outSearchCmdOfficial, "\n") assert.Equal(c, len(outSearchCmdOfficialSlice), 3) // 1 header, 1 line, 1 carriage return assert.Assert(c, strings.HasPrefix(outSearchCmdOfficialSlice[1], "busybox "), "The busybox is an OFFICIAL image: %s", outSearchCmdOfficial) - outSearchCmdStars, _ := dockerCmd(c, "search", "--filter", "stars=10", "busybox") + outSearchCmdStars := cli.DockerCmd(c, "search", "--filter", "stars=10", "busybox").Combined() assert.Assert(c, strings.Count(outSearchCmdStars, "\n") <= strings.Count(outSearchCmd, "\n"), "Number of images with 10+ stars should be less than that of all images:\noutSearchCmdStars: %s\noutSearch: %s\n", outSearchCmdStars, outSearchCmd) - dockerCmd(c, "search", "--filter", "is-automated=true", "--filter", "stars=2", "--no-trunc=true", "busybox") + cli.DockerCmd(c, "search", "--filter", "is-automated=true", "--filter", "stars=2", "--no-trunc=true", "busybox") } // search for repos which start with "ubuntu-" on the central registry func (s *DockerCLISearchSuite) TestSearchOnCentralRegistryWithDash(c *testing.T) { - dockerCmd(c, "search", "ubuntu-") + cli.DockerCmd(c, "search", "ubuntu-") } // test case for #23055 diff --git a/integration-cli/docker_cli_start_test.go b/integration-cli/docker_cli_start_test.go index 229aebd468..fa8683a615 100644 --- a/integration-cli/docker_cli_start_test.go +++ b/integration-cli/docker_cli_start_test.go @@ -28,7 +28,7 @@ func (s *DockerCLIStartSuite) OnTimeout(c *testing.T) { func (s *DockerCLIStartSuite) TestStartAttachReturnsOnError(c *testing.T) { // Windows does not support link testRequires(c, DaemonIsLinux) - dockerCmd(c, "run", "--name", "test", "busybox") + cli.DockerCmd(c, "run", "--name", "test", "busybox") // Expect this to fail because the above container is stopped, this is what we want out, _, err := dockerCmdWithError("run", "--name", "test2", "--link", "test:test", "busybox") @@ -69,12 +69,12 @@ func (s *DockerCLIStartSuite) TestStartAttachCorrectExitCode(c *testing.T) { func (s *DockerCLIStartSuite) TestStartAttachSilent(c *testing.T) { name := "teststartattachcorrectexitcode" - dockerCmd(c, "run", "--name", name, "busybox", "echo", "test") + cli.DockerCmd(c, "run", "--name", name, "busybox", "echo", "test") // make sure the container has exited before trying the "start -a" - dockerCmd(c, "wait", name) + cli.DockerCmd(c, "wait", name) - startOut, _ := dockerCmd(c, "start", "-a", name) + startOut := cli.DockerCmd(c, "start", "-a", name).Combined() // start -a produced unexpected output assert.Equal(c, startOut, "test\n") } @@ -83,7 +83,7 @@ func (s *DockerCLIStartSuite) TestStartRecordError(c *testing.T) { // TODO Windows CI: Requires further porting work. Should be possible. testRequires(c, DaemonIsLinux) // when container runs successfully, we should not have state.Error - dockerCmd(c, "run", "-d", "-p", "9999:9999", "--name", "test", "busybox", "top") + cli.DockerCmd(c, "run", "-d", "-p", "9999:9999", "--name", "test", "busybox", "top") stateErr := inspectField(c, "test", "State.Error") // Expected to not have state error assert.Equal(c, stateErr, "") @@ -96,8 +96,8 @@ func (s *DockerCLIStartSuite) TestStartRecordError(c *testing.T) { stateErr = inspectField(c, "test2", "State.Error") assert.Assert(c, strings.Contains(stateErr, "port is already allocated")) // Expect the conflict to be resolved when we stop the initial container - dockerCmd(c, "stop", "test") - dockerCmd(c, "start", "test2") + cli.DockerCmd(c, "stop", "test") + cli.DockerCmd(c, "start", "test2") stateErr = inspectField(c, "test2", "State.Error") // Expected to not have state error but got one assert.Equal(c, stateErr, "") @@ -109,7 +109,7 @@ func (s *DockerCLIStartSuite) TestStartPausedContainer(c *testing.T) { runSleepingContainer(c, "-d", "--name", "testing") - dockerCmd(c, "pause", "testing") + cli.DockerCmd(c, "pause", "testing") out, _, err := dockerCmdWithError("start", "testing") // an error should have been shown that you cannot start paused container @@ -122,14 +122,14 @@ func (s *DockerCLIStartSuite) TestStartMultipleContainers(c *testing.T) { // Windows does not support --link testRequires(c, DaemonIsLinux) // run a container named 'parent' and create two container link to `parent` - dockerCmd(c, "run", "-d", "--name", "parent", "busybox", "top") + cli.DockerCmd(c, "run", "-d", "--name", "parent", "busybox", "top") for _, container := range []string{"child_first", "child_second"} { - dockerCmd(c, "create", "--name", container, "--link", "parent:parent", "busybox", "top") + cli.DockerCmd(c, "create", "--name", container, "--link", "parent:parent", "busybox", "top") } // stop 'parent' container - dockerCmd(c, "stop", "parent") + cli.DockerCmd(c, "stop", "parent") out := inspectField(c, "parent", "State.Running") // Container should be stopped @@ -137,8 +137,8 @@ func (s *DockerCLIStartSuite) TestStartMultipleContainers(c *testing.T) { // start all the three containers, container `child_first` start first which should be failed // container 'parent' start second and then start container 'child_second' - expOut := "Cannot link to a non running container" - expErr := "failed to start containers: [child_first]" + const expOut = "Cannot link to a non running container" + const expErr = "failed to start containers: [child_first]" out, _, err := dockerCmdWithError("start", "child_first", "parent", "child_second") // err shouldn't be nil because start will fail assert.Assert(c, err != nil, "out: %s", out) @@ -162,7 +162,7 @@ func (s *DockerCLIStartSuite) TestStartAttachMultipleContainers(c *testing.T) { // stop all the containers for _, container := range []string{"test1", "test2", "test3"} { - dockerCmd(c, "stop", container) + cli.DockerCmd(c, "stop", container) } // test start and attach multiple containers at once, expected error diff --git a/integration-cli/docker_cli_stats_test.go b/integration-cli/docker_cli_stats_test.go index 070e149905..e6994834e4 100644 --- a/integration-cli/docker_cli_stats_test.go +++ b/integration-cli/docker_cli_stats_test.go @@ -29,9 +29,9 @@ func (s *DockerCLIStatsSuite) OnTimeout(c *testing.T) { func (s *DockerCLIStatsSuite) TestStatsNoStream(c *testing.T) { // Windows does not support stats testRequires(c, DaemonIsLinux) - out, _ := dockerCmd(c, "run", "-d", "busybox", "top") - id := strings.TrimSpace(out) - assert.NilError(c, waitRun(id)) + id := cli.DockerCmd(c, "run", "-d", "busybox", "top").Stdout() + id = strings.TrimSpace(id) + cli.WaitRun(c, id) statsCmd := exec.Command(dockerBinary, "stats", "--no-stream", id) type output struct { @@ -72,18 +72,18 @@ func (s *DockerCLIStatsSuite) TestStatsAllRunningNoStream(c *testing.T) { // Windows does not support stats testRequires(c, DaemonIsLinux) - out, _ := dockerCmd(c, "run", "-d", "busybox", "top") - id1 := strings.TrimSpace(out)[:12] - assert.NilError(c, waitRun(id1)) - out, _ = dockerCmd(c, "run", "-d", "busybox", "top") - id2 := strings.TrimSpace(out)[:12] - assert.NilError(c, waitRun(id2)) - out, _ = dockerCmd(c, "run", "-d", "busybox", "top") - id3 := strings.TrimSpace(out)[:12] - assert.NilError(c, waitRun(id3)) - dockerCmd(c, "stop", id3) + id1 := cli.DockerCmd(c, "run", "-d", "busybox", "top").Stdout() + id1 = strings.TrimSpace(id1)[:12] + cli.WaitRun(c, id1) + id2 := cli.DockerCmd(c, "run", "-d", "busybox", "top").Stdout() + id2 = strings.TrimSpace(id2)[:12] + cli.WaitRun(c, id2) + id3 := cli.DockerCmd(c, "run", "-d", "busybox", "top").Stdout() + id3 = strings.TrimSpace(id3)[:12] + cli.WaitRun(c, id3) + cli.DockerCmd(c, "stop", id3) - out, _ = dockerCmd(c, "stats", "--no-stream") + out := cli.DockerCmd(c, "stats", "--no-stream").Combined() if !strings.Contains(out, id1) || !strings.Contains(out, id2) { c.Fatalf("Expected stats output to contain both %s and %s, got %s", id1, id2, out) } @@ -108,15 +108,15 @@ func (s *DockerCLIStatsSuite) TestStatsAllNoStream(c *testing.T) { // Windows does not support stats testRequires(c, DaemonIsLinux) - out, _ := dockerCmd(c, "run", "-d", "busybox", "top") - id1 := strings.TrimSpace(out)[:12] - assert.NilError(c, waitRun(id1)) - dockerCmd(c, "stop", id1) - out, _ = dockerCmd(c, "run", "-d", "busybox", "top") - id2 := strings.TrimSpace(out)[:12] - assert.NilError(c, waitRun(id2)) + id1 := cli.DockerCmd(c, "run", "-d", "busybox", "top").Stdout() + id1 = strings.TrimSpace(id1)[:12] + cli.WaitRun(c, id1) + cli.DockerCmd(c, "stop", id1) + id2 := cli.DockerCmd(c, "run", "-d", "busybox", "top").Stdout() + id2 = strings.TrimSpace(id2)[:12] + cli.WaitRun(c, id2) - out, _ = dockerCmd(c, "stats", "--all", "--no-stream") + out := cli.DockerCmd(c, "stats", "--all", "--no-stream").Combined() if !strings.Contains(out, id1) || !strings.Contains(out, id2) { c.Fatalf("Expected stats output to contain both %s and %s, got %s", id1, id2, out) } @@ -164,7 +164,7 @@ func (s *DockerCLIStatsSuite) TestStatsAllNewContainersAdded(c *testing.T) { }() out := runSleepingContainer(c, "-d") - assert.NilError(c, waitRun(strings.TrimSpace(out))) + cli.WaitRun(c, out) id <- strings.TrimSpace(out)[:12] select { diff --git a/integration-cli/docker_cli_top_test.go b/integration-cli/docker_cli_top_test.go index b57d8c4b2a..fc24381a33 100644 --- a/integration-cli/docker_cli_top_test.go +++ b/integration-cli/docker_cli_top_test.go @@ -5,6 +5,7 @@ import ( "strings" "testing" + "github.com/docker/docker/integration-cli/cli" "gotest.tools/v3/assert" "gotest.tools/v3/icmd" ) @@ -32,7 +33,7 @@ func (s *DockerCLITopSuite) TestTopMultipleArgs(c *testing.T) { default: expected = icmd.Expected{Out: "PID"} } - result := dockerCmdWithResult("top", cleanedContainerID, "-o", "pid") + result := cli.Docker(cli.Args("top", cleanedContainerID, "-o", "pid")) result.Assert(c, expected) } @@ -40,9 +41,9 @@ func (s *DockerCLITopSuite) TestTopNonPrivileged(c *testing.T) { out := runSleepingContainer(c, "-d") cleanedContainerID := strings.TrimSpace(out) - out1, _ := dockerCmd(c, "top", cleanedContainerID) - out2, _ := dockerCmd(c, "top", cleanedContainerID) - dockerCmd(c, "kill", cleanedContainerID) + out1 := cli.DockerCmd(c, "top", cleanedContainerID).Combined() + out2 := cli.DockerCmd(c, "top", cleanedContainerID).Combined() + cli.DockerCmd(c, "kill", cleanedContainerID) // Windows will list the name of the launched executable which in this case is busybox.exe, without the parameters. // Linux will display the command executed in the container @@ -62,9 +63,8 @@ func (s *DockerCLITopSuite) TestTopNonPrivileged(c *testing.T) { // very different to Linux in this regard. func (s *DockerCLITopSuite) TestTopWindowsCoreProcesses(c *testing.T) { testRequires(c, DaemonIsWindows) - out := runSleepingContainer(c, "-d") - cleanedContainerID := strings.TrimSpace(out) - out1, _ := dockerCmd(c, "top", cleanedContainerID) + cID := runSleepingContainer(c, "-d") + out1 := cli.DockerCmd(c, "top", cID).Combined() lookingFor := []string{"smss.exe", "csrss.exe", "wininit.exe", "services.exe", "lsass.exe", "CExecSvc.exe"} for i, s := range lookingFor { assert.Assert(c, strings.Contains(out1, s), "top should've listed `%s` in the process list, but failed. Test case %d", s, i) @@ -74,12 +74,12 @@ func (s *DockerCLITopSuite) TestTopWindowsCoreProcesses(c *testing.T) { func (s *DockerCLITopSuite) TestTopPrivileged(c *testing.T) { // Windows does not support --privileged testRequires(c, DaemonIsLinux, NotUserNamespace) - out, _ := dockerCmd(c, "run", "--privileged", "-i", "-d", "busybox", "top") - cleanedContainerID := strings.TrimSpace(out) + cID := cli.DockerCmd(c, "run", "--privileged", "-i", "-d", "busybox", "top").Stdout() + cID = strings.TrimSpace(cID) - out1, _ := dockerCmd(c, "top", cleanedContainerID) - out2, _ := dockerCmd(c, "top", cleanedContainerID) - dockerCmd(c, "kill", cleanedContainerID) + out1 := cli.DockerCmd(c, "top", cID).Combined() + out2 := cli.DockerCmd(c, "top", cID).Combined() + cli.DockerCmd(c, "kill", cID) assert.Assert(c, strings.Contains(out1, "top"), "top should've listed `top` in the process list, but failed the first time") assert.Assert(c, strings.Contains(out2, "top"), "top should've listed `top` in the process list, but failed the second time") diff --git a/integration-cli/docker_cli_update_unix_test.go b/integration-cli/docker_cli_update_unix_test.go index 6925b95afe..e8f2ae0c37 100644 --- a/integration-cli/docker_cli_update_unix_test.go +++ b/integration-cli/docker_cli_update_unix_test.go @@ -14,6 +14,7 @@ import ( "github.com/creack/pty" "github.com/docker/docker/api/types" "github.com/docker/docker/client" + "github.com/docker/docker/integration-cli/cli" "github.com/docker/docker/testutil" "github.com/docker/docker/testutil/request" "gotest.tools/v3/assert" @@ -31,14 +32,14 @@ func (s *DockerCLIUpdateSuite) TestUpdateRunningContainer(c *testing.T) { testRequires(c, DaemonIsLinux) testRequires(c, memoryLimitSupport) - name := "test-update-container" - dockerCmd(c, "run", "-d", "--name", name, "-m", "300M", "busybox", "top") - dockerCmd(c, "update", "-m", "500M", name) + const name = "test-update-container" + cli.DockerCmd(c, "run", "-d", "--name", name, "-m", "300M", "busybox", "top") + cli.DockerCmd(c, "update", "-m", "500M", name) assert.Equal(c, inspectField(c, name, "HostConfig.Memory"), "524288000") - file := "/sys/fs/cgroup/memory/memory.limit_in_bytes" - out, _ := dockerCmd(c, "exec", name, "cat", file) + const file = "/sys/fs/cgroup/memory/memory.limit_in_bytes" + out := cli.DockerCmd(c, "exec", name, "cat", file).Stdout() assert.Equal(c, strings.TrimSpace(out), "524288000") } @@ -46,15 +47,15 @@ func (s *DockerCLIUpdateSuite) TestUpdateRunningContainerWithRestart(c *testing. testRequires(c, DaemonIsLinux) testRequires(c, memoryLimitSupport) - name := "test-update-container" - dockerCmd(c, "run", "-d", "--name", name, "-m", "300M", "busybox", "top") - dockerCmd(c, "update", "-m", "500M", name) - dockerCmd(c, "restart", name) + const name = "test-update-container" + cli.DockerCmd(c, "run", "-d", "--name", name, "-m", "300M", "busybox", "top") + cli.DockerCmd(c, "update", "-m", "500M", name) + cli.DockerCmd(c, "restart", name) assert.Equal(c, inspectField(c, name, "HostConfig.Memory"), "524288000") - file := "/sys/fs/cgroup/memory/memory.limit_in_bytes" - out, _ := dockerCmd(c, "exec", name, "cat", file) + const file = "/sys/fs/cgroup/memory/memory.limit_in_bytes" + out := cli.DockerCmd(c, "exec", name, "cat", file).Stdout() assert.Equal(c, strings.TrimSpace(out), "524288000") } @@ -62,14 +63,14 @@ func (s *DockerCLIUpdateSuite) TestUpdateStoppedContainer(c *testing.T) { testRequires(c, DaemonIsLinux) testRequires(c, memoryLimitSupport) - name := "test-update-container" - file := "/sys/fs/cgroup/memory/memory.limit_in_bytes" - dockerCmd(c, "run", "--name", name, "-m", "300M", "busybox", "cat", file) - dockerCmd(c, "update", "-m", "500M", name) + const name = "test-update-container" + const file = "/sys/fs/cgroup/memory/memory.limit_in_bytes" + cli.DockerCmd(c, "run", "--name", name, "-m", "300M", "busybox", "cat", file) + cli.DockerCmd(c, "update", "-m", "500M", name) assert.Equal(c, inspectField(c, name, "HostConfig.Memory"), "524288000") - out, _ := dockerCmd(c, "start", "-a", name) + out := cli.DockerCmd(c, "start", "-a", name).Stdout() assert.Equal(c, strings.TrimSpace(out), "524288000") } @@ -77,16 +78,16 @@ func (s *DockerCLIUpdateSuite) TestUpdatePausedContainer(c *testing.T) { testRequires(c, DaemonIsLinux) testRequires(c, cpuShare) - name := "test-update-container" - dockerCmd(c, "run", "-d", "--name", name, "--cpu-shares", "1000", "busybox", "top") - dockerCmd(c, "pause", name) - dockerCmd(c, "update", "--cpu-shares", "500", name) + const name = "test-update-container" + cli.DockerCmd(c, "run", "-d", "--name", name, "--cpu-shares", "1000", "busybox", "top") + cli.DockerCmd(c, "pause", name) + cli.DockerCmd(c, "update", "--cpu-shares", "500", name) assert.Equal(c, inspectField(c, name, "HostConfig.CPUShares"), "500") - dockerCmd(c, "unpause", name) - file := "/sys/fs/cgroup/cpu/cpu.shares" - out, _ := dockerCmd(c, "exec", name, "cat", file) + cli.DockerCmd(c, "unpause", name) + const file = "/sys/fs/cgroup/cpu/cpu.shares" + out := cli.DockerCmd(c, "exec", name, "cat", file).Stdout() assert.Equal(c, strings.TrimSpace(out), "500") } @@ -95,16 +96,16 @@ func (s *DockerCLIUpdateSuite) TestUpdateWithUntouchedFields(c *testing.T) { testRequires(c, memoryLimitSupport) testRequires(c, cpuShare) - name := "test-update-container" - dockerCmd(c, "run", "-d", "--name", name, "-m", "300M", "--cpu-shares", "800", "busybox", "top") - dockerCmd(c, "update", "-m", "500M", name) + const name = "test-update-container" + cli.DockerCmd(c, "run", "-d", "--name", name, "-m", "300M", "--cpu-shares", "800", "busybox", "top") + cli.DockerCmd(c, "update", "-m", "500M", name) // Update memory and not touch cpus, `cpuset.cpus` should still have the old value out := inspectField(c, name, "HostConfig.CPUShares") assert.Equal(c, out, "800") - file := "/sys/fs/cgroup/cpu/cpu.shares" - out, _ = dockerCmd(c, "exec", name, "cat", file) + const file = "/sys/fs/cgroup/cpu/cpu.shares" + out = cli.DockerCmd(c, "exec", name, "cat", file).Stdout() assert.Equal(c, strings.TrimSpace(out), "800") } @@ -112,8 +113,8 @@ func (s *DockerCLIUpdateSuite) TestUpdateContainerInvalidValue(c *testing.T) { testRequires(c, DaemonIsLinux) testRequires(c, memoryLimitSupport) - name := "test-update-container" - dockerCmd(c, "run", "-d", "--name", name, "-m", "300M", "busybox", "true") + const name = "test-update-container" + cli.DockerCmd(c, "run", "-d", "--name", name, "-m", "300M", "busybox", "true") out, _, err := dockerCmdWithError("update", "-m", "2M", name) assert.ErrorContains(c, err, "") expected := "Minimum memory limit allowed is 6MB" @@ -124,8 +125,8 @@ func (s *DockerCLIUpdateSuite) TestUpdateContainerWithoutFlags(c *testing.T) { testRequires(c, DaemonIsLinux) testRequires(c, memoryLimitSupport) - name := "test-update-container" - dockerCmd(c, "run", "-d", "--name", name, "-m", "300M", "busybox", "true") + const name = "test-update-container" + cli.DockerCmd(c, "run", "-d", "--name", name, "-m", "300M", "busybox", "true") _, _, err := dockerCmdWithError("update", name) assert.ErrorContains(c, err, "") } @@ -135,14 +136,14 @@ func (s *DockerCLIUpdateSuite) TestUpdateSwapMemoryOnly(c *testing.T) { testRequires(c, memoryLimitSupport) testRequires(c, swapMemorySupport) - name := "test-update-container" - dockerCmd(c, "run", "-d", "--name", name, "--memory", "300M", "--memory-swap", "500M", "busybox", "top") - dockerCmd(c, "update", "--memory-swap", "600M", name) + const name = "test-update-container" + cli.DockerCmd(c, "run", "-d", "--name", name, "--memory", "300M", "--memory-swap", "500M", "busybox", "top") + cli.DockerCmd(c, "update", "--memory-swap", "600M", name) assert.Equal(c, inspectField(c, name, "HostConfig.MemorySwap"), "629145600") - file := "/sys/fs/cgroup/memory/memory.memsw.limit_in_bytes" - out, _ := dockerCmd(c, "exec", name, "cat", file) + const file = "/sys/fs/cgroup/memory/memory.memsw.limit_in_bytes" + out := cli.DockerCmd(c, "exec", name, "cat", file).Stdout() assert.Equal(c, strings.TrimSpace(out), "629145600") } @@ -151,8 +152,8 @@ func (s *DockerCLIUpdateSuite) TestUpdateInvalidSwapMemory(c *testing.T) { testRequires(c, memoryLimitSupport) testRequires(c, swapMemorySupport) - name := "test-update-container" - dockerCmd(c, "run", "-d", "--name", name, "--memory", "300M", "--memory-swap", "500M", "busybox", "top") + const name = "test-update-container" + cli.DockerCmd(c, "run", "-d", "--name", name, "--memory", "300M", "--memory-swap", "500M", "busybox", "top") _, _, err := dockerCmdWithError("update", "--memory-swap", "200M", name) // Update invalid swap memory should fail. // This will pass docker config validation, but failed at kernel validation @@ -162,12 +163,12 @@ func (s *DockerCLIUpdateSuite) TestUpdateInvalidSwapMemory(c *testing.T) { assert.Equal(c, inspectField(c, name, "HostConfig.Memory"), "314572800") assert.Equal(c, inspectField(c, name, "HostConfig.MemorySwap"), "524288000") - dockerCmd(c, "update", "--memory-swap", "600M", name) + cli.DockerCmd(c, "update", "--memory-swap", "600M", name) assert.Equal(c, inspectField(c, name, "HostConfig.MemorySwap"), "629145600") - file := "/sys/fs/cgroup/memory/memory.memsw.limit_in_bytes" - out, _ := dockerCmd(c, "exec", name, "cat", file) + const file = "/sys/fs/cgroup/memory/memory.memsw.limit_in_bytes" + out := cli.DockerCmd(c, "exec", name, "cat", file).Stdout() assert.Equal(c, strings.TrimSpace(out), "629145600") } @@ -175,10 +176,9 @@ func (s *DockerCLIUpdateSuite) TestUpdateStats(c *testing.T) { testRequires(c, DaemonIsLinux) testRequires(c, memoryLimitSupport) testRequires(c, cpuCfsQuota) - name := "foo" - dockerCmd(c, "run", "-d", "-ti", "--name", name, "-m", "500m", "busybox") - - assert.NilError(c, waitRun(name)) + const name = "foo" + cli.DockerCmd(c, "run", "-d", "-ti", "--name", name, "-m", "500m", "busybox") + cli.WaitRun(c, name) getMemLimit := func(id string) uint64 { resp, body, err := request.Get(testutil.GetContext(c), fmt.Sprintf("/containers/%s/stats?stream=false", id)) @@ -194,7 +194,7 @@ func (s *DockerCLIUpdateSuite) TestUpdateStats(c *testing.T) { } preMemLimit := getMemLimit(name) - dockerCmd(c, "update", "--cpu-quota", "2000", name) + cli.DockerCmd(c, "update", "--cpu-quota", "2000", name) curMemLimit := getMemLimit(name) assert.Equal(c, preMemLimit, curMemLimit) @@ -205,21 +205,21 @@ func (s *DockerCLIUpdateSuite) TestUpdateMemoryWithSwapMemory(c *testing.T) { testRequires(c, memoryLimitSupport) testRequires(c, swapMemorySupport) - name := "test-update-container" - dockerCmd(c, "run", "-d", "--name", name, "--memory", "300M", "busybox", "top") + const name = "test-update-container" + cli.DockerCmd(c, "run", "-d", "--name", name, "--memory", "300M", "busybox", "top") out, _, err := dockerCmdWithError("update", "--memory", "800M", name) assert.ErrorContains(c, err, "") assert.Assert(c, strings.Contains(out, "Memory limit should be smaller than already set memoryswap limit")) - dockerCmd(c, "update", "--memory", "800M", "--memory-swap", "1000M", name) + cli.DockerCmd(c, "update", "--memory", "800M", "--memory-swap", "1000M", name) } func (s *DockerCLIUpdateSuite) TestUpdateNotAffectMonitorRestartPolicy(c *testing.T) { testRequires(c, DaemonIsLinux, cpuShare) - out, _ := dockerCmd(c, "run", "-tid", "--restart=always", "busybox", "sh") - id := strings.TrimSpace(out) - dockerCmd(c, "update", "--cpu-shares", "512", id) + id := cli.DockerCmd(c, "run", "-tid", "--restart=always", "busybox", "sh").Stdout() + id = strings.TrimSpace(id) + cli.DockerCmd(c, "update", "--cpu-shares", "512", id) cpty, tty, err := pty.Open() assert.NilError(c, err) @@ -239,19 +239,19 @@ func (s *DockerCLIUpdateSuite) TestUpdateNotAffectMonitorRestartPolicy(c *testin // container should restart again and keep running err = waitInspect(id, "{{.RestartCount}}", "1", 30*time.Second) assert.NilError(c, err) - assert.NilError(c, waitRun(id)) + cli.WaitRun(c, id) } func (s *DockerCLIUpdateSuite) TestUpdateWithNanoCPUs(c *testing.T) { testRequires(c, cpuCfsQuota, cpuCfsPeriod) - file1 := "/sys/fs/cgroup/cpu/cpu.cfs_quota_us" - file2 := "/sys/fs/cgroup/cpu/cpu.cfs_period_us" + const file1 = "/sys/fs/cgroup/cpu/cpu.cfs_quota_us" + const file2 = "/sys/fs/cgroup/cpu/cpu.cfs_period_us" - out, _ := dockerCmd(c, "run", "-d", "--cpus", "0.5", "--name", "top", "busybox", "top") + out := cli.DockerCmd(c, "run", "-d", "--cpus", "0.5", "--name", "top", "busybox", "top").Stdout() assert.Assert(c, strings.TrimSpace(out) != "") - out, _ = dockerCmd(c, "exec", "top", "sh", "-c", fmt.Sprintf("cat %s && cat %s", file1, file2)) + out = cli.DockerCmd(c, "exec", "top", "sh", "-c", fmt.Sprintf("cat %s && cat %s", file1, file2)).Combined() assert.Equal(c, strings.TrimSpace(out), "50000\n100000") clt, err := client.NewClientWithOpts(client.FromEnv) @@ -269,7 +269,7 @@ func (s *DockerCLIUpdateSuite) TestUpdateWithNanoCPUs(c *testing.T) { assert.ErrorContains(c, err, "") assert.Assert(c, strings.Contains(out, "Conflicting options: CPU Quota cannot be updated as NanoCPUs has already been set")) - dockerCmd(c, "update", "--cpus", "0.8", "top") + cli.DockerCmd(c, "update", "--cpus", "0.8", "top") inspect, err = clt.ContainerInspect(testutil.GetContext(c), "top") assert.NilError(c, err) assert.Equal(c, inspect.HostConfig.NanoCPUs, int64(800000000)) @@ -279,6 +279,6 @@ func (s *DockerCLIUpdateSuite) TestUpdateWithNanoCPUs(c *testing.T) { out = inspectField(c, "top", "HostConfig.CpuPeriod") assert.Equal(c, out, "0", "CPU CFS period should be 0") - out, _ = dockerCmd(c, "exec", "top", "sh", "-c", fmt.Sprintf("cat %s && cat %s", file1, file2)) + out = cli.DockerCmd(c, "exec", "top", "sh", "-c", fmt.Sprintf("cat %s && cat %s", file1, file2)).Combined() assert.Equal(c, strings.TrimSpace(out), "80000\n100000") } diff --git a/integration-cli/docker_cli_volume_test.go b/integration-cli/docker_cli_volume_test.go index 5faa425176..7fc4d20b39 100644 --- a/integration-cli/docker_cli_volume_test.go +++ b/integration-cli/docker_cli_volume_test.go @@ -13,6 +13,7 @@ import ( "github.com/docker/docker/api/types/mount" "github.com/docker/docker/api/types/network" "github.com/docker/docker/client" + "github.com/docker/docker/integration-cli/cli" "github.com/docker/docker/integration-cli/cli/build" "github.com/docker/docker/testutil" "gotest.tools/v3/assert" @@ -32,37 +33,37 @@ func (s *DockerCLIVolumeSuite) OnTimeout(c *testing.T) { } func (s *DockerCLIVolumeSuite) TestVolumeCLICreate(c *testing.T) { - dockerCmd(c, "volume", "create") + cli.DockerCmd(c, "volume", "create") _, _, err := dockerCmdWithError("volume", "create", "-d", "nosuchdriver") assert.ErrorContains(c, err, "") // test using hidden --name option - out, _ := dockerCmd(c, "volume", "create", "--name=test") - name := strings.TrimSpace(out) + name := cli.DockerCmd(c, "volume", "create", "--name=test").Stdout() + name = strings.TrimSpace(name) assert.Equal(c, name, "test") - out, _ = dockerCmd(c, "volume", "create", "test2") - name = strings.TrimSpace(out) + name = cli.DockerCmd(c, "volume", "create", "test2").Stdout() + name = strings.TrimSpace(name) assert.Equal(c, name, "test2") } func (s *DockerCLIVolumeSuite) TestVolumeCLIInspect(c *testing.T) { assert.Assert(c, exec.Command(dockerBinary, "volume", "inspect", "doesnotexist").Run() != nil, "volume inspect should error on non-existent volume") - out, _ := dockerCmd(c, "volume", "create") - name := strings.TrimSpace(out) - out, _ = dockerCmd(c, "volume", "inspect", "--format={{ .Name }}", name) + name := cli.DockerCmd(c, "volume", "create").Stdout() + name = strings.TrimSpace(name) + out := cli.DockerCmd(c, "volume", "inspect", "--format={{ .Name }}", name).Stdout() assert.Equal(c, strings.TrimSpace(out), name) - dockerCmd(c, "volume", "create", "test") - out, _ = dockerCmd(c, "volume", "inspect", "--format={{ .Name }}", "test") + cli.DockerCmd(c, "volume", "create", "test") + out = cli.DockerCmd(c, "volume", "inspect", "--format={{ .Name }}", "test").Stdout() assert.Equal(c, strings.TrimSpace(out), "test") } func (s *DockerCLIVolumeSuite) TestVolumeCLIInspectMulti(c *testing.T) { - dockerCmd(c, "volume", "create", "test1") - dockerCmd(c, "volume", "create", "test2") - dockerCmd(c, "volume", "create", "test3") + cli.DockerCmd(c, "volume", "create", "test1") + cli.DockerCmd(c, "volume", "create", "test2") + cli.DockerCmd(c, "volume", "create", "test3") result := dockerCmdWithResult("volume", "inspect", "--format={{ .Name }}", "test1", "test2", "doesnotexist", "test3") result.Assert(c, icmd.Expected{ @@ -78,32 +79,32 @@ func (s *DockerCLIVolumeSuite) TestVolumeCLIInspectMulti(c *testing.T) { func (s *DockerCLIVolumeSuite) TestVolumeCLILs(c *testing.T) { prefix, _ := getPrefixAndSlashFromDaemonPlatform() - dockerCmd(c, "volume", "create", "aaa") + cli.DockerCmd(c, "volume", "create", "aaa") - dockerCmd(c, "volume", "create", "test") + cli.DockerCmd(c, "volume", "create", "test") - dockerCmd(c, "volume", "create", "soo") - dockerCmd(c, "run", "-v", "soo:"+prefix+"/foo", "busybox", "ls", "/") + cli.DockerCmd(c, "volume", "create", "soo") + cli.DockerCmd(c, "run", "-v", "soo:"+prefix+"/foo", "busybox", "ls", "/") - out, _ := dockerCmd(c, "volume", "ls", "-q") + out := cli.DockerCmd(c, "volume", "ls", "-q").Stdout() assertVolumesInList(c, out, []string{"aaa", "soo", "test"}) } func (s *DockerCLIVolumeSuite) TestVolumeLsFormat(c *testing.T) { - dockerCmd(c, "volume", "create", "aaa") - dockerCmd(c, "volume", "create", "test") - dockerCmd(c, "volume", "create", "soo") + cli.DockerCmd(c, "volume", "create", "aaa") + cli.DockerCmd(c, "volume", "create", "test") + cli.DockerCmd(c, "volume", "create", "soo") - out, _ := dockerCmd(c, "volume", "ls", "--format", "{{.Name}}") + out := cli.DockerCmd(c, "volume", "ls", "--format", "{{.Name}}").Stdout() assertVolumesInList(c, out, []string{"aaa", "soo", "test"}) } func (s *DockerCLIVolumeSuite) TestVolumeLsFormatDefaultFormat(c *testing.T) { - dockerCmd(c, "volume", "create", "aaa") - dockerCmd(c, "volume", "create", "test") - dockerCmd(c, "volume", "create", "soo") + cli.DockerCmd(c, "volume", "create", "aaa") + cli.DockerCmd(c, "volume", "create", "test") + cli.DockerCmd(c, "volume", "create", "soo") - config := `{ + const config = `{ "volumesFormat": "{{ .Name }} default" }` d, err := os.MkdirTemp("", "integration-cli-") @@ -113,7 +114,7 @@ func (s *DockerCLIVolumeSuite) TestVolumeLsFormatDefaultFormat(c *testing.T) { err = os.WriteFile(filepath.Join(d, "config.json"), []byte(config), 0o644) assert.NilError(c, err) - out, _ := dockerCmd(c, "--config", d, "volume", "ls") + out := cli.DockerCmd(c, "--config", d, "volume", "ls").Stdout() assertVolumesInList(c, out, []string{"aaa default", "soo default", "test default"}) } @@ -133,44 +134,46 @@ func assertVolumesInList(c *testing.T, out string, expected []string) { func (s *DockerCLIVolumeSuite) TestVolumeCLILsFilterDangling(c *testing.T) { prefix, _ := getPrefixAndSlashFromDaemonPlatform() - dockerCmd(c, "volume", "create", "testnotinuse1") - dockerCmd(c, "volume", "create", "testisinuse1") - dockerCmd(c, "volume", "create", "testisinuse2") + cli.DockerCmd(c, "volume", "create", "testnotinuse1") + cli.DockerCmd(c, "volume", "create", "testisinuse1") + cli.DockerCmd(c, "volume", "create", "testisinuse2") // Make sure both "created" (but not started), and started // containers are included in reference counting - dockerCmd(c, "run", "--name", "volume-test1", "-v", "testisinuse1:"+prefix+"/foo", "busybox", "true") - dockerCmd(c, "create", "--name", "volume-test2", "-v", "testisinuse2:"+prefix+"/foo", "busybox", "true") - - out, _ := dockerCmd(c, "volume", "ls") + cli.DockerCmd(c, "run", "--name", "volume-test1", "-v", "testisinuse1:"+prefix+"/foo", "busybox", "true") + cli.DockerCmd(c, "create", "--name", "volume-test2", "-v", "testisinuse2:"+prefix+"/foo", "busybox", "true") // No filter, all volumes should show + out := cli.DockerCmd(c, "volume", "ls").Stdout() assert.Assert(c, strings.Contains(out, "testnotinuse1\n"), "expected volume 'testnotinuse1' in output") assert.Assert(c, strings.Contains(out, "testisinuse1\n"), "expected volume 'testisinuse1' in output") assert.Assert(c, strings.Contains(out, "testisinuse2\n"), "expected volume 'testisinuse2' in output") - out, _ = dockerCmd(c, "volume", "ls", "--filter", "dangling=false") // Explicitly disabling dangling + out = cli.DockerCmd(c, "volume", "ls", "--filter", "dangling=false").Stdout() assert.Assert(c, !strings.Contains(out, "testnotinuse1\n"), "expected volume 'testnotinuse1' in output") assert.Assert(c, strings.Contains(out, "testisinuse1\n"), "expected volume 'testisinuse1' in output") assert.Assert(c, strings.Contains(out, "testisinuse2\n"), "expected volume 'testisinuse2' in output") - out, _ = dockerCmd(c, "volume", "ls", "--filter", "dangling=true") // Filter "dangling" volumes; only "dangling" (unused) volumes should be in the output + out = cli.DockerCmd(c, "volume", "ls", "--filter", "dangling=true").Stdout() assert.Assert(c, strings.Contains(out, "testnotinuse1\n"), "expected volume 'testnotinuse1' in output") assert.Assert(c, !strings.Contains(out, "testisinuse1\n"), "volume 'testisinuse1' in output, but not expected") assert.Assert(c, !strings.Contains(out, "testisinuse2\n"), "volume 'testisinuse2' in output, but not expected") - out, _ = dockerCmd(c, "volume", "ls", "--filter", "dangling=1") + // Filter "dangling" volumes; only "dangling" (unused) volumes should be in the output, dangling also accept 1 + out = cli.DockerCmd(c, "volume", "ls", "--filter", "dangling=1").Stdout() assert.Assert(c, strings.Contains(out, "testnotinuse1\n"), "expected volume 'testnotinuse1' in output") assert.Assert(c, !strings.Contains(out, "testisinuse1\n"), "volume 'testisinuse1' in output, but not expected") assert.Assert(c, !strings.Contains(out, "testisinuse2\n"), "volume 'testisinuse2' in output, but not expected") - out, _ = dockerCmd(c, "volume", "ls", "--filter", "dangling=0") + // dangling=0 is same as dangling=false case + out = cli.DockerCmd(c, "volume", "ls", "--filter", "dangling=0").Stdout() assert.Assert(c, !strings.Contains(out, "testnotinuse1\n"), "expected volume 'testnotinuse1' in output") assert.Assert(c, strings.Contains(out, "testisinuse1\n"), "expected volume 'testisinuse1' in output") assert.Assert(c, strings.Contains(out, "testisinuse2\n"), "expected volume 'testisinuse2' in output") - out, _ = dockerCmd(c, "volume", "ls", "--filter", "name=testisin") + + out = cli.DockerCmd(c, "volume", "ls", "--filter", "name=testisin").Stdout() assert.Assert(c, !strings.Contains(out, "testnotinuse1\n"), "expected volume 'testnotinuse1' in output") assert.Assert(c, strings.Contains(out, "testisinuse1\n"), "expected volume 'testisinuse1' in output") assert.Assert(c, strings.Contains(out, "testisinuse2\n"), "expected volume 'testisinuse2' in output") @@ -190,38 +193,38 @@ func (s *DockerCLIVolumeSuite) TestVolumeCLILsWithIncorrectFilterValue(c *testin func (s *DockerCLIVolumeSuite) TestVolumeCLIRm(c *testing.T) { prefix, _ := getPrefixAndSlashFromDaemonPlatform() - out, _ := dockerCmd(c, "volume", "create") - id := strings.TrimSpace(out) + id := cli.DockerCmd(c, "volume", "create").Stdout() + id = strings.TrimSpace(id) - dockerCmd(c, "volume", "create", "test") - dockerCmd(c, "volume", "rm", id) - dockerCmd(c, "volume", "rm", "test") + cli.DockerCmd(c, "volume", "create", "test") + cli.DockerCmd(c, "volume", "rm", id) + cli.DockerCmd(c, "volume", "rm", "test") volumeID := "testing" - dockerCmd(c, "run", "-v", volumeID+":"+prefix+"/foo", "--name=test", "busybox", "sh", "-c", "echo hello > /foo/bar") + cli.DockerCmd(c, "run", "-v", volumeID+":"+prefix+"/foo", "--name=test", "busybox", "sh", "-c", "echo hello > /foo/bar") icmd.RunCommand(dockerBinary, "volume", "rm", "testing").Assert(c, icmd.Expected{ ExitCode: 1, Error: "exit status 1", }) - out, _ = dockerCmd(c, "run", "--volumes-from=test", "--name=test2", "busybox", "sh", "-c", "cat /foo/bar") + out := cli.DockerCmd(c, "run", "--volumes-from=test", "--name=test2", "busybox", "sh", "-c", "cat /foo/bar").Combined() assert.Equal(c, strings.TrimSpace(out), "hello") - dockerCmd(c, "rm", "-fv", "test2") - dockerCmd(c, "volume", "inspect", volumeID) - dockerCmd(c, "rm", "-f", "test") + cli.DockerCmd(c, "rm", "-fv", "test2") + cli.DockerCmd(c, "volume", "inspect", volumeID) + cli.DockerCmd(c, "rm", "-f", "test") - out, _ = dockerCmd(c, "run", "--name=test2", "-v", volumeID+":"+prefix+"/foo", "busybox", "sh", "-c", "cat /foo/bar") + out = cli.DockerCmd(c, "run", "--name=test2", "-v", volumeID+":"+prefix+"/foo", "busybox", "sh", "-c", "cat /foo/bar").Combined() assert.Equal(c, strings.TrimSpace(out), "hello", "volume data was removed") - dockerCmd(c, "rm", "test2") + cli.DockerCmd(c, "rm", "test2") - dockerCmd(c, "volume", "rm", volumeID) + cli.DockerCmd(c, "volume", "rm", volumeID) assert.Assert(c, exec.Command("volume", "rm", "doesnotexist").Run() != nil, "volume rm should fail with non-existent volume") } // FIXME(vdemeester) should be a unit test in cli/command/volume package func (s *DockerCLIVolumeSuite) TestVolumeCLINoArgs(c *testing.T) { - out, _ := dockerCmd(c, "volume") + out := cli.DockerCmd(c, "volume").Combined() // no args should produce the cmd usage output usage := "Usage: docker volume COMMAND" assert.Assert(c, strings.Contains(out, usage)) @@ -243,8 +246,8 @@ func (s *DockerCLIVolumeSuite) TestVolumeCLINoArgs(c *testing.T) { } func (s *DockerCLIVolumeSuite) TestVolumeCLIInspectTmplError(c *testing.T) { - out, _ := dockerCmd(c, "volume", "create") - name := strings.TrimSpace(out) + name := cli.DockerCmd(c, "volume", "create").Stdout() + name = strings.TrimSpace(name) out, exitCode, err := dockerCmdWithError("volume", "inspect", "--format='{{ .FooBar }}'", name) assert.Assert(c, err != nil, "Output: %s", out) @@ -255,9 +258,9 @@ func (s *DockerCLIVolumeSuite) TestVolumeCLIInspectTmplError(c *testing.T) { func (s *DockerCLIVolumeSuite) TestVolumeCLICreateWithOpts(c *testing.T) { testRequires(c, DaemonIsLinux) - dockerCmd(c, "volume", "create", "-d", "local", "test", "--opt=type=tmpfs", "--opt=device=tmpfs", "--opt=o=size=1m,uid=1000") - out, _ := dockerCmd(c, "run", "-v", "test:/foo", "busybox", "mount") + cli.DockerCmd(c, "volume", "create", "-d", "local", "test", "--opt=type=tmpfs", "--opt=device=tmpfs", "--opt=o=size=1m,uid=1000") + out := cli.DockerCmd(c, "run", "-v", "test:/foo", "busybox", "mount").Stdout() mounts := strings.Split(out, "\n") var found bool for _, m := range mounts { @@ -277,19 +280,19 @@ func (s *DockerCLIVolumeSuite) TestVolumeCLICreateWithOpts(c *testing.T) { } func (s *DockerCLIVolumeSuite) TestVolumeCLICreateLabel(c *testing.T) { - testVol := "testvolcreatelabel" - testLabel := "foo" - testValue := "bar" + const testVol = "testvolcreatelabel" + const testLabel = "foo" + const testValue = "bar" _, _, err := dockerCmdWithError("volume", "create", "--label", testLabel+"="+testValue, testVol) assert.NilError(c, err) - out, _ := dockerCmd(c, "volume", "inspect", "--format={{ .Labels."+testLabel+" }}", testVol) + out := cli.DockerCmd(c, "volume", "inspect", "--format={{ .Labels."+testLabel+" }}", testVol).Stdout() assert.Equal(c, strings.TrimSpace(out), testValue) } func (s *DockerCLIVolumeSuite) TestVolumeCLICreateLabelMultiple(c *testing.T) { - testVol := "testvolcreatelabel" + const testVol = "testvolcreatelabel" testLabels := map[string]string{ "foo": "bar", @@ -310,7 +313,7 @@ func (s *DockerCLIVolumeSuite) TestVolumeCLICreateLabelMultiple(c *testing.T) { assert.NilError(c, err) for k, v := range testLabels { - out, _ := dockerCmd(c, "volume", "inspect", "--format={{ .Labels."+k+" }}", testVol) + out := cli.DockerCmd(c, "volume", "inspect", "--format={{ .Labels."+k+" }}", testVol).Stdout() assert.Equal(c, strings.TrimSpace(out), v) } } @@ -324,21 +327,21 @@ func (s *DockerCLIVolumeSuite) TestVolumeCLILsFilterLabels(c *testing.T) { _, _, err = dockerCmdWithError("volume", "create", "--label", "foo=bar2", testVol2) assert.NilError(c, err) - out, _ := dockerCmd(c, "volume", "ls", "--filter", "label=foo") - // filter with label=key + out := cli.DockerCmd(c, "volume", "ls", "--filter", "label=foo").Stdout() assert.Assert(c, strings.Contains(out, "testvolcreatelabel-1\n"), "expected volume 'testvolcreatelabel-1' in output") assert.Assert(c, strings.Contains(out, "testvolcreatelabel-2\n"), "expected volume 'testvolcreatelabel-2' in output") - out, _ = dockerCmd(c, "volume", "ls", "--filter", "label=foo=bar1") // filter with label=key=value + out = cli.DockerCmd(c, "volume", "ls", "--filter", "label=foo=bar1").Stdout() assert.Assert(c, strings.Contains(out, "testvolcreatelabel-1\n"), "expected volume 'testvolcreatelabel-1' in output") assert.Assert(c, !strings.Contains(out, "testvolcreatelabel-2\n"), "expected volume 'testvolcreatelabel-2 in output") - out, _ = dockerCmd(c, "volume", "ls", "--filter", "label=non-exist") + + out = cli.DockerCmd(c, "volume", "ls", "--filter", "label=non-exist").Stdout() outArr := strings.Split(strings.TrimSpace(out), "\n") assert.Equal(c, len(outArr), 1, fmt.Sprintf("\n%s", out)) - out, _ = dockerCmd(c, "volume", "ls", "--filter", "label=foo=non-exist") + out = cli.DockerCmd(c, "volume", "ls", "--filter", "label=foo=non-exist").Stdout() outArr = strings.Split(strings.TrimSpace(out), "\n") assert.Equal(c, len(outArr), 1, fmt.Sprintf("\n%s", out)) } @@ -354,71 +357,72 @@ func (s *DockerCLIVolumeSuite) TestVolumeCLILsFilterDrivers(c *testing.T) { assert.NilError(c, err) // filter with driver=local - out, _ := dockerCmd(c, "volume", "ls", "--filter", "driver=local") + out := cli.DockerCmd(c, "volume", "ls", "--filter", "driver=local").Stdout() assert.Assert(c, strings.Contains(out, "testvol-1\n"), "expected volume 'testvol-1' in output") assert.Assert(c, strings.Contains(out, "testvol-2\n"), "expected volume 'testvol-2' in output") + // filter with driver=invaliddriver - out, _ = dockerCmd(c, "volume", "ls", "--filter", "driver=invaliddriver") + out = cli.DockerCmd(c, "volume", "ls", "--filter", "driver=invaliddriver").Stdout() outArr := strings.Split(strings.TrimSpace(out), "\n") assert.Equal(c, len(outArr), 1, fmt.Sprintf("\n%s", out)) // filter with driver=loca - out, _ = dockerCmd(c, "volume", "ls", "--filter", "driver=loca") + out = cli.DockerCmd(c, "volume", "ls", "--filter", "driver=loca").Stdout() outArr = strings.Split(strings.TrimSpace(out), "\n") assert.Equal(c, len(outArr), 1, fmt.Sprintf("\n%s", out)) // filter with driver= - out, _ = dockerCmd(c, "volume", "ls", "--filter", "driver=") + out = cli.DockerCmd(c, "volume", "ls", "--filter", "driver=").Stdout() outArr = strings.Split(strings.TrimSpace(out), "\n") assert.Equal(c, len(outArr), 1, fmt.Sprintf("\n%s", out)) } func (s *DockerCLIVolumeSuite) TestVolumeCLIRmForceUsage(c *testing.T) { - out, _ := dockerCmd(c, "volume", "create") - id := strings.TrimSpace(out) + id := cli.DockerCmd(c, "volume", "create").Stdout() + id = strings.TrimSpace(id) - dockerCmd(c, "volume", "rm", "-f", id) - dockerCmd(c, "volume", "rm", "--force", "nonexist") + cli.DockerCmd(c, "volume", "rm", "-f", id) + cli.DockerCmd(c, "volume", "rm", "--force", "nonexist") } func (s *DockerCLIVolumeSuite) TestVolumeCLIRmForce(c *testing.T) { testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux) - name := "test" - out, _ := dockerCmd(c, "volume", "create", name) - id := strings.TrimSpace(out) + const name = "test" + id := cli.DockerCmd(c, "volume", "create", name).Stdout() + id = strings.TrimSpace(id) assert.Equal(c, id, name) - out, _ = dockerCmd(c, "volume", "inspect", "--format", "{{.Mountpoint}}", name) + out := cli.DockerCmd(c, "volume", "inspect", "--format", "{{.Mountpoint}}", name).Stdout() assert.Assert(c, strings.TrimSpace(out) != "") // Mountpoint is in the form of "/var/lib/docker/volumes/.../_data", removing `/_data` path := strings.TrimSuffix(strings.TrimSpace(out), "/_data") icmd.RunCommand("rm", "-rf", path).Assert(c, icmd.Success) - dockerCmd(c, "volume", "rm", "-f", name) - out, _ = dockerCmd(c, "volume", "ls") + cli.DockerCmd(c, "volume", "rm", "-f", name) + out = cli.DockerCmd(c, "volume", "ls").Stdout() assert.Assert(c, !strings.Contains(out, name)) - dockerCmd(c, "volume", "create", name) - out, _ = dockerCmd(c, "volume", "ls") + cli.DockerCmd(c, "volume", "create", name) + out = cli.DockerCmd(c, "volume", "ls").Stdout() assert.Assert(c, strings.Contains(out, name)) } // TestVolumeCLIRmForceInUse verifies that repeated `docker volume rm -f` calls does not remove a volume // if it is in use. Test case for https://github.com/docker/docker/issues/31446 func (s *DockerCLIVolumeSuite) TestVolumeCLIRmForceInUse(c *testing.T) { - name := "testvolume" - out, _ := dockerCmd(c, "volume", "create", name) - id := strings.TrimSpace(out) + const name = "testvolume" + id := cli.DockerCmd(c, "volume", "create", name).Stdout() + id = strings.TrimSpace(id) assert.Equal(c, id, name) prefix, slash := getPrefixAndSlashFromDaemonPlatform() - out, _ = dockerCmd(c, "create", "-v", "testvolume:"+prefix+slash+"foo", "busybox") - cid := strings.TrimSpace(out) + cid := cli.DockerCmd(c, "create", "-v", "testvolume:"+prefix+slash+"foo", "busybox").Stdout() + cid = strings.TrimSpace(cid) _, _, err := dockerCmdWithError("volume", "rm", "-f", name) assert.ErrorContains(c, err, "") assert.ErrorContains(c, err, "volume is in use") - out, _ = dockerCmd(c, "volume", "ls") + out := cli.DockerCmd(c, "volume", "ls").Stdout() assert.Assert(c, strings.Contains(out, name)) // The original issue did not _remove_ the volume from the list // the first time. But a second call to `volume rm` removed it. @@ -427,18 +431,18 @@ func (s *DockerCLIVolumeSuite) TestVolumeCLIRmForceInUse(c *testing.T) { _, _, err = dockerCmdWithError("volume", "rm", "-f", name) assert.ErrorContains(c, err, "") assert.ErrorContains(c, err, "volume is in use") - out, _ = dockerCmd(c, "volume", "ls") + out = cli.DockerCmd(c, "volume", "ls").Stdout() assert.Assert(c, strings.Contains(out, name)) // Verify removing the volume after the container is removed works - _, e := dockerCmd(c, "rm", cid) + e := cli.DockerCmd(c, "rm", cid).ExitCode assert.Equal(c, e, 0) - _, e = dockerCmd(c, "volume", "rm", "-f", name) + e = cli.DockerCmd(c, "volume", "rm", "-f", name).ExitCode assert.Equal(c, e, 0) - out, e = dockerCmd(c, "volume", "ls") - assert.Equal(c, e, 0) - assert.Assert(c, !strings.Contains(out, name)) + result := cli.DockerCmd(c, "volume", "ls") + assert.Equal(c, result.ExitCode, 0) + assert.Assert(c, !strings.Contains(result.Stdout(), name)) } func (s *DockerCLIVolumeSuite) TestVolumeCliInspectWithVolumeOpts(c *testing.T) { @@ -446,16 +450,16 @@ func (s *DockerCLIVolumeSuite) TestVolumeCliInspectWithVolumeOpts(c *testing.T) // Without options name := "test1" - dockerCmd(c, "volume", "create", "-d", "local", name) - out, _ := dockerCmd(c, "volume", "inspect", "--format={{ .Options }}", name) + cli.DockerCmd(c, "volume", "create", "-d", "local", name) + out := cli.DockerCmd(c, "volume", "inspect", "--format={{ .Options }}", name).Stdout() assert.Assert(c, strings.Contains(strings.TrimSpace(out), "map[]")) // With options name = "test2" k1, v1 := "type", "tmpfs" k2, v2 := "device", "tmpfs" k3, v3 := "o", "size=1m,uid=1000" - dockerCmd(c, "volume", "create", "-d", "local", name, "--opt", fmt.Sprintf("%s=%s", k1, v1), "--opt", fmt.Sprintf("%s=%s", k2, v2), "--opt", fmt.Sprintf("%s=%s", k3, v3)) - out, _ = dockerCmd(c, "volume", "inspect", "--format={{ .Options }}", name) + cli.DockerCmd(c, "volume", "create", "-d", "local", name, "--opt", fmt.Sprintf("%s=%s", k1, v1), "--opt", fmt.Sprintf("%s=%s", k2, v2), "--opt", fmt.Sprintf("%s=%s", k3, v3)) + out = cli.DockerCmd(c, "volume", "inspect", "--format={{ .Options }}", name).Stdout() assert.Assert(c, strings.Contains(strings.TrimSpace(out), fmt.Sprintf("%s:%s", k1, v1))) assert.Assert(c, strings.Contains(strings.TrimSpace(out), fmt.Sprintf("%s:%s", k2, v2))) assert.Assert(c, strings.Contains(strings.TrimSpace(out), fmt.Sprintf("%s:%s", k3, v3))) @@ -465,39 +469,39 @@ func (s *DockerCLIVolumeSuite) TestVolumeCliInspectWithVolumeOpts(c *testing.T) func (s *DockerCLIVolumeSuite) TestDuplicateMountpointsForVolumesFrom(c *testing.T) { testRequires(c, DaemonIsLinux) - image := "vimage" + const image = "vimage" buildImageSuccessfully(c, image, build.WithDockerfile(` FROM busybox VOLUME ["/tmp/data"]`)) - dockerCmd(c, "run", "--name=data1", image, "true") - dockerCmd(c, "run", "--name=data2", image, "true") + cli.DockerCmd(c, "run", "--name=data1", image, "true") + cli.DockerCmd(c, "run", "--name=data2", image, "true") - out, _ := dockerCmd(c, "inspect", "--format", "{{(index .Mounts 0).Name}}", "data1") - data1 := strings.TrimSpace(out) + data1 := cli.DockerCmd(c, "inspect", "--format", "{{(index .Mounts 0).Name}}", "data1").Stdout() + data1 = strings.TrimSpace(data1) assert.Assert(c, data1 != "") - out, _ = dockerCmd(c, "inspect", "--format", "{{(index .Mounts 0).Name}}", "data2") - data2 := strings.TrimSpace(out) + data2 := cli.DockerCmd(c, "inspect", "--format", "{{(index .Mounts 0).Name}}", "data2").Stdout() + data2 = strings.TrimSpace(data2) assert.Assert(c, data2 != "") // Both volume should exist - out, _ = dockerCmd(c, "volume", "ls", "-q") + out := cli.DockerCmd(c, "volume", "ls", "-q").Stdout() assert.Assert(c, strings.Contains(strings.TrimSpace(out), data1)) assert.Assert(c, strings.Contains(strings.TrimSpace(out), data2)) out, _, err := dockerCmdWithError("run", "--name=app", "--volumes-from=data1", "--volumes-from=data2", "-d", "busybox", "top") assert.Assert(c, err == nil, "Out: %s", out) // Only the second volume will be referenced, this is backward compatible - out, _ = dockerCmd(c, "inspect", "--format", "{{(index .Mounts 0).Name}}", "app") + out = cli.DockerCmd(c, "inspect", "--format", "{{(index .Mounts 0).Name}}", "app").Stdout() assert.Equal(c, strings.TrimSpace(out), data2) - dockerCmd(c, "rm", "-f", "-v", "app") - dockerCmd(c, "rm", "-f", "-v", "data1") - dockerCmd(c, "rm", "-f", "-v", "data2") + cli.DockerCmd(c, "rm", "-f", "-v", "app") + cli.DockerCmd(c, "rm", "-f", "-v", "data1") + cli.DockerCmd(c, "rm", "-f", "-v", "data2") // Both volume should not exist - out, _ = dockerCmd(c, "volume", "ls", "-q") + out = cli.DockerCmd(c, "volume", "ls", "-q").Stdout() assert.Assert(c, !strings.Contains(strings.TrimSpace(out), data1)) assert.Assert(c, !strings.Contains(strings.TrimSpace(out), data2)) } @@ -506,24 +510,24 @@ func (s *DockerCLIVolumeSuite) TestDuplicateMountpointsForVolumesFrom(c *testing func (s *DockerCLIVolumeSuite) TestDuplicateMountpointsForVolumesFromAndBind(c *testing.T) { testRequires(c, DaemonIsLinux) - image := "vimage" + const image = "vimage" buildImageSuccessfully(c, image, build.WithDockerfile(` FROM busybox VOLUME ["/tmp/data"]`)) - dockerCmd(c, "run", "--name=data1", image, "true") - dockerCmd(c, "run", "--name=data2", image, "true") + cli.DockerCmd(c, "run", "--name=data1", image, "true") + cli.DockerCmd(c, "run", "--name=data2", image, "true") - out, _ := dockerCmd(c, "inspect", "--format", "{{(index .Mounts 0).Name}}", "data1") - data1 := strings.TrimSpace(out) + data1 := cli.DockerCmd(c, "inspect", "--format", "{{(index .Mounts 0).Name}}", "data1").Stdout() + data1 = strings.TrimSpace(data1) assert.Assert(c, data1 != "") - out, _ = dockerCmd(c, "inspect", "--format", "{{(index .Mounts 0).Name}}", "data2") - data2 := strings.TrimSpace(out) + data2 := cli.DockerCmd(c, "inspect", "--format", "{{(index .Mounts 0).Name}}", "data2").Stdout() + data2 = strings.TrimSpace(data2) assert.Assert(c, data2 != "") // Both volume should exist - out, _ = dockerCmd(c, "volume", "ls", "-q") + out := cli.DockerCmd(c, "volume", "ls", "-q").Stdout() assert.Assert(c, strings.Contains(strings.TrimSpace(out), data1)) assert.Assert(c, strings.Contains(strings.TrimSpace(out), data2)) // /tmp/data is automatically created, because we are not using the modern mount API here @@ -531,15 +535,15 @@ func (s *DockerCLIVolumeSuite) TestDuplicateMountpointsForVolumesFromAndBind(c * assert.Assert(c, err == nil, "Out: %s", out) // No volume will be referenced (mount is /tmp/data), this is backward compatible - out, _ = dockerCmd(c, "inspect", "--format", "{{(index .Mounts 0).Name}}", "app") + out = cli.DockerCmd(c, "inspect", "--format", "{{(index .Mounts 0).Name}}", "app").Stdout() assert.Assert(c, !strings.Contains(strings.TrimSpace(out), data1)) assert.Assert(c, !strings.Contains(strings.TrimSpace(out), data2)) - dockerCmd(c, "rm", "-f", "-v", "app") - dockerCmd(c, "rm", "-f", "-v", "data1") - dockerCmd(c, "rm", "-f", "-v", "data2") + cli.DockerCmd(c, "rm", "-f", "-v", "app") + cli.DockerCmd(c, "rm", "-f", "-v", "data1") + cli.DockerCmd(c, "rm", "-f", "-v", "data2") // Both volume should not exist - out, _ = dockerCmd(c, "volume", "ls", "-q") + out = cli.DockerCmd(c, "volume", "ls", "-q").Stdout() assert.Assert(c, !strings.Contains(strings.TrimSpace(out), data1)) assert.Assert(c, !strings.Contains(strings.TrimSpace(out), data2)) } @@ -548,28 +552,29 @@ func (s *DockerCLIVolumeSuite) TestDuplicateMountpointsForVolumesFromAndBind(c * func (s *DockerCLIVolumeSuite) TestDuplicateMountpointsForVolumesFromAndMounts(c *testing.T) { testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux) - image := "vimage" + const image = "vimage" buildImageSuccessfully(c, image, build.WithDockerfile(` FROM busybox VOLUME ["/tmp/data"]`)) - dockerCmd(c, "run", "--name=data1", image, "true") - dockerCmd(c, "run", "--name=data2", image, "true") + cli.DockerCmd(c, "run", "--name=data1", image, "true") + cli.DockerCmd(c, "run", "--name=data2", image, "true") - out, _ := dockerCmd(c, "inspect", "--format", "{{(index .Mounts 0).Name}}", "data1") - data1 := strings.TrimSpace(out) + data1 := cli.DockerCmd(c, "inspect", "--format", "{{(index .Mounts 0).Name}}", "data1").Stdout() + data1 = strings.TrimSpace(data1) assert.Assert(c, data1 != "") - out, _ = dockerCmd(c, "inspect", "--format", "{{(index .Mounts 0).Name}}", "data2") - data2 := strings.TrimSpace(out) + data2 := cli.DockerCmd(c, "inspect", "--format", "{{(index .Mounts 0).Name}}", "data2").Stdout() + data2 = strings.TrimSpace(data2) assert.Assert(c, data2 != "") // Both volume should exist - out, _ = dockerCmd(c, "volume", "ls", "-q") + out := cli.DockerCmd(c, "volume", "ls", "-q").Stdout() assert.Assert(c, strings.Contains(strings.TrimSpace(out), data1)) assert.Assert(c, strings.Contains(strings.TrimSpace(out), data2)) err := os.MkdirAll("/tmp/data", 0o755) assert.NilError(c, err) + // Mounts is available in API apiClient, err := client.NewClientWithOpts(client.FromEnv) assert.NilError(c, err) @@ -595,15 +600,15 @@ func (s *DockerCLIVolumeSuite) TestDuplicateMountpointsForVolumesFromAndMounts(c assert.NilError(c, err) // No volume will be referenced (mount is /tmp/data), this is backward compatible - out, _ = dockerCmd(c, "inspect", "--format", "{{(index .Mounts 0).Name}}", "app") + out = cli.DockerCmd(c, "inspect", "--format", "{{(index .Mounts 0).Name}}", "app").Stdout() assert.Assert(c, !strings.Contains(strings.TrimSpace(out), data1)) assert.Assert(c, !strings.Contains(strings.TrimSpace(out), data2)) - dockerCmd(c, "rm", "-f", "-v", "app") - dockerCmd(c, "rm", "-f", "-v", "data1") - dockerCmd(c, "rm", "-f", "-v", "data2") + cli.DockerCmd(c, "rm", "-f", "-v", "app") + cli.DockerCmd(c, "rm", "-f", "-v", "data1") + cli.DockerCmd(c, "rm", "-f", "-v", "data2") // Both volume should not exist - out, _ = dockerCmd(c, "volume", "ls", "-q") + out = cli.DockerCmd(c, "volume", "ls", "-q").Stdout() assert.Assert(c, !strings.Contains(strings.TrimSpace(out), data1)) assert.Assert(c, !strings.Contains(strings.TrimSpace(out), data2)) } diff --git a/integration-cli/docker_deprecated_api_v124_test.go b/integration-cli/docker_deprecated_api_v124_test.go index db13662a5d..648ee99570 100644 --- a/integration-cli/docker_deprecated_api_v124_test.go +++ b/integration-cli/docker_deprecated_api_v124_test.go @@ -9,6 +9,7 @@ import ( "testing" "github.com/docker/docker/api/types/versions" + "github.com/docker/docker/integration-cli/cli" "github.com/docker/docker/testutil" "github.com/docker/docker/testutil/request" "gotest.tools/v3/assert" @@ -21,7 +22,7 @@ func formatV123StartAPIURL(url string) string { func (s *DockerAPISuite) TestDeprecatedContainerAPIStartHostConfig(c *testing.T) { name := "test-deprecated-api-124" - dockerCmd(c, "create", "--name", name, "busybox") + cli.DockerCmd(c, "create", "--name", name, "busybox") config := map[string]interface{}{ "Binds": []string{"/aa:/bb"}, } @@ -108,7 +109,7 @@ func (s *DockerAPISuite) TestDeprecatedContainerAPIStartVolumesFrom(c *testing.T volName := "voltst" volPath := "/tmp" - dockerCmd(c, "run", "--name", volName, "-v", volPath, "busybox") + cli.DockerCmd(c, "run", "--name", volName, "-v", volPath, "busybox") name := "TestContainerAPIStartVolumesFrom" config := map[string]interface{}{ @@ -138,12 +139,12 @@ func (s *DockerAPISuite) TestDeprecatedContainerAPIStartVolumesFrom(c *testing.T func (s *DockerAPISuite) TestDeprecatedPostContainerBindNormalVolume(c *testing.T) { // TODO Windows to Windows CI - Port this testRequires(c, DaemonIsLinux) - dockerCmd(c, "create", "-v", "/foo", "--name=one", "busybox") + cli.DockerCmd(c, "create", "-v", "/foo", "--name=one", "busybox") fooDir, err := inspectMountSourceField("one", "/foo") assert.NilError(c, err) - dockerCmd(c, "create", "-v", "/foo", "--name=two", "busybox") + cli.DockerCmd(c, "create", "-v", "/foo", "--name=two", "busybox") bindSpec := map[string][]string{"Binds": {fooDir + ":/foo"}} res, _, err := request.Post(testutil.GetContext(c), formatV123StartAPIURL("/containers/two/start"), request.JSONBody(bindSpec)) @@ -158,11 +159,10 @@ func (s *DockerAPISuite) TestDeprecatedPostContainerBindNormalVolume(c *testing. func (s *DockerAPISuite) TestDeprecatedStartWithTooLowMemoryLimit(c *testing.T) { // TODO Windows: Port once memory is supported testRequires(c, DaemonIsLinux) - out, _ := dockerCmd(c, "create", "busybox") + containerID := cli.DockerCmd(c, "create", "busybox").Stdout() + containerID = strings.TrimSpace(containerID) - containerID := strings.TrimSpace(out) - - config := `{ + const config = `{ "CpuShares": 100, "Memory": 524287 }` @@ -185,7 +185,7 @@ func (s *DockerAPISuite) TestDeprecatedPostContainersStartWithoutLinksInHostConf // An alternate test could be written to validate the negative testing aspect of this testRequires(c, DaemonIsLinux) name := "test-host-config-links" - dockerCmd(c, append([]string{"create", "--name", name, "busybox"}, sleepCommandForDaemonPlatform()...)...) + cli.DockerCmd(c, append([]string{"create", "--name", name, "busybox"}, sleepCommandForDaemonPlatform()...)...) hc := inspectFieldJSON(c, name, "HostConfig") config := `{"HostConfig":` + hc + `}` @@ -202,8 +202,8 @@ func (s *DockerAPISuite) TestDeprecatedPostContainersStartWithLinksInHostConfig( // An alternate test could be written to validate the negative testing aspect of this testRequires(c, DaemonIsLinux) name := "test-host-config-links" - dockerCmd(c, "run", "--name", "foo", "-d", "busybox", "top") - dockerCmd(c, "create", "--name", name, "--link", "foo:bar", "busybox", "top") + cli.DockerCmd(c, "run", "--name", "foo", "-d", "busybox", "top") + cli.DockerCmd(c, "create", "--name", name, "--link", "foo:bar", "busybox", "top") hc := inspectFieldJSON(c, name, "HostConfig") config := `{"HostConfig":` + hc + `}` @@ -218,12 +218,12 @@ func (s *DockerAPISuite) TestDeprecatedPostContainersStartWithLinksInHostConfig( func (s *DockerAPISuite) TestDeprecatedPostContainersStartWithLinksInHostConfigIdLinked(c *testing.T) { // Windows does not support links testRequires(c, DaemonIsLinux) - name := "test-host-config-links" - out, _ := dockerCmd(c, "run", "--name", "link0", "-d", "busybox", "top") - defer dockerCmd(c, "stop", "link0") - id := strings.TrimSpace(out) - dockerCmd(c, "create", "--name", name, "--link", id, "busybox", "top") - defer dockerCmd(c, "stop", name) + const name = "test-host-config-links" + containerID := cli.DockerCmd(c, "run", "--name", "link0", "-d", "busybox", "top").Combined() + containerID = strings.TrimSpace(containerID) + defer cli.DockerCmd(c, "stop", "link0") + cli.DockerCmd(c, "create", "--name", name, "--link", containerID, "busybox", "top") + defer cli.DockerCmd(c, "stop", name) hc := inspectFieldJSON(c, name, "HostConfig") config := `{"HostConfig":` + hc + `}` @@ -237,10 +237,10 @@ func (s *DockerAPISuite) TestDeprecatedPostContainersStartWithLinksInHostConfigI func (s *DockerAPISuite) TestDeprecatedStartWithNilDNS(c *testing.T) { // TODO Windows: Add once DNS is supported testRequires(c, DaemonIsLinux) - out, _ := dockerCmd(c, "create", "busybox") - containerID := strings.TrimSpace(out) + containerID := cli.DockerCmd(c, "create", "busybox").Stdout() + containerID = strings.TrimSpace(containerID) - config := `{"HostConfig": {"Dns": null}}` + const config = `{"HostConfig": {"Dns": null}}` res, b, err := request.Post(testutil.GetContext(c), formatV123StartAPIURL("/containers/"+containerID+"/start"), request.RawString(config), request.JSON) assert.NilError(c, err) diff --git a/integration-cli/docker_deprecated_api_v124_unix_test.go b/integration-cli/docker_deprecated_api_v124_unix_test.go index dc182c35bc..574f14f22b 100644 --- a/integration-cli/docker_deprecated_api_v124_unix_test.go +++ b/integration-cli/docker_deprecated_api_v124_unix_test.go @@ -6,6 +6,7 @@ import ( "strings" "testing" + "github.com/docker/docker/integration-cli/cli" "github.com/docker/docker/testutil" "github.com/docker/docker/testutil/request" "gotest.tools/v3/assert" @@ -13,10 +14,10 @@ import ( // #19100 This is a deprecated feature test, it should be removed in Docker 1.12 func (s *DockerNetworkSuite) TestDeprecatedDockerNetworkStartAPIWithHostconfig(c *testing.T) { - netName := "test" - conName := "foo" - dockerCmd(c, "network", "create", netName) - dockerCmd(c, "create", "--name", conName, "busybox", "top") + const netName = "test" + const conName = "foo" + cli.DockerCmd(c, "network", "create", netName) + cli.DockerCmd(c, "create", "--name", conName, "busybox", "top") config := map[string]interface{}{ "HostConfig": map[string]interface{}{ @@ -25,7 +26,7 @@ func (s *DockerNetworkSuite) TestDeprecatedDockerNetworkStartAPIWithHostconfig(c } _, _, err := request.Post(testutil.GetContext(c), formatV123StartAPIURL("/containers/"+conName+"/start"), request.JSONBody(config)) assert.NilError(c, err) - assert.NilError(c, waitRun(conName)) + cli.WaitRun(c, conName) networks := inspectField(c, conName, "NetworkSettings.Networks") assert.Assert(c, strings.Contains(networks, netName), "Should contain '%s' network", netName) assert.Assert(c, !strings.Contains(networks, "bridge"), "Should not contain 'bridge' network") diff --git a/integration-cli/docker_utils_test.go b/integration-cli/docker_utils_test.go index 834880a1f4..1490ab2e86 100644 --- a/integration-cli/docker_utils_test.go +++ b/integration-cli/docker_utils_test.go @@ -39,13 +39,6 @@ func dockerCmdWithError(args ...string) (string, int, error) { return result.Combined(), result.ExitCode, result.Error } -// Deprecated: use cli.Docker or cli.DockerCmd -func dockerCmd(c testing.TB, args ...string) (string, int) { - c.Helper() - result := cli.DockerCmd(c, args...) - return result.Combined(), result.ExitCode -} - // Deprecated: use cli.Docker or cli.DockerCmd func dockerCmdWithResult(args ...string) *icmd.Result { return cli.Docker(cli.Args(args...)) @@ -53,7 +46,7 @@ func dockerCmdWithResult(args ...string) *icmd.Result { func findContainerIP(c *testing.T, id string, network string) string { c.Helper() - out, _ := dockerCmd(c, "inspect", fmt.Sprintf("--format='{{ .NetworkSettings.Networks.%s.IPAddress }}'", network), id) + out := cli.DockerCmd(c, "inspect", fmt.Sprintf("--format='{{ .NetworkSettings.Networks.%s.IPAddress }}'", network), id).Stdout() return strings.Trim(out, " \r\n'") } @@ -216,9 +209,7 @@ func runCommandAndReadContainerFile(c *testing.T, filename string, command strin result := icmd.RunCommand(command, args...) result.Assert(c, icmd.Success) contID := strings.TrimSpace(result.Combined()) - if err := waitRun(contID); err != nil { - c.Fatalf("%v: %q", contID, err) - } + cli.WaitRun(c, contID) return readContainerFile(c, contID, filename) } @@ -309,12 +300,6 @@ func createTmpFile(c *testing.T, content string) string { return filename } -// waitRun will wait for the specified container to be running, maximum 5 seconds. -// Deprecated: use cli.WaitFor -func waitRun(contID string) error { - return daemon.WaitInspectWithArgs(dockerBinary, contID, "{{.State.Running}}", "true", 5*time.Second) -} - // waitInspect will wait for the specified container to have the specified string // in the inspect output. It will wait until the specified timeout (in seconds) // is reached. diff --git a/integration-cli/events_utils_test.go b/integration-cli/events_utils_test.go index 827ec0f662..2e63645460 100644 --- a/integration-cli/events_utils_test.go +++ b/integration-cli/events_utils_test.go @@ -13,6 +13,7 @@ import ( "github.com/containerd/log" eventstestutils "github.com/docker/docker/daemon/events/testutils" + "github.com/docker/docker/integration-cli/cli" "gotest.tools/v3/assert" ) @@ -100,7 +101,7 @@ func (e *eventObserver) CheckEventError(c *testing.T, id, event string, match ev if e.disconnectionError != nil { until := daemonUnixTime(c) - out, _ := dockerCmd(c, "events", "--since", e.startTime, "--until", until) + out := cli.DockerCmd(c, "events", "--since", e.startTime, "--until", until).Stdout() events := strings.Split(strings.TrimSpace(out), "\n") for _, e := range events { if _, ok := match(e); ok { diff --git a/integration-cli/fixtures_linux_daemon_test.go b/integration-cli/fixtures_linux_daemon_test.go index 384169462e..0ec24a101f 100644 --- a/integration-cli/fixtures_linux_daemon_test.go +++ b/integration-cli/fixtures_linux_daemon_test.go @@ -10,6 +10,7 @@ import ( "strings" "testing" + "github.com/docker/docker/integration-cli/cli" "github.com/docker/docker/testutil/fixtures/load" "gotest.tools/v3/assert" ) @@ -61,7 +62,7 @@ func ensureSyscallTest(ctx context.Context, c *testing.T) { } buildArgs = append(buildArgs, []string{"-q", "-t", "syscall-test", tmp}...) buildArgs = append([]string{"build"}, buildArgs...) - dockerCmd(c, buildArgs...) + cli.DockerCmd(c, buildArgs...) } func ensureSyscallTestBuild(ctx context.Context, c *testing.T) { @@ -74,7 +75,7 @@ func ensureSyscallTestBuild(ctx context.Context, c *testing.T) { } buildArgs = append(buildArgs, []string{"-q", "-t", "syscall-test", "../contrib/syscall-test"}...) buildArgs = append([]string{"build"}, buildArgs...) - dockerCmd(c, buildArgs...) + cli.DockerCmd(c, buildArgs...) } func ensureNNPTest(ctx context.Context, c *testing.T) { @@ -116,7 +117,7 @@ func ensureNNPTest(ctx context.Context, c *testing.T) { } buildArgs = append(buildArgs, []string{"-q", "-t", "nnp-test", tmp}...) buildArgs = append([]string{"build"}, buildArgs...) - dockerCmd(c, buildArgs...) + cli.DockerCmd(c, buildArgs...) } func ensureNNPTestBuild(ctx context.Context, c *testing.T) { @@ -129,5 +130,5 @@ func ensureNNPTestBuild(ctx context.Context, c *testing.T) { } buildArgs = append(buildArgs, []string{"-q", "-t", "npp-test", "../contrib/nnp-test"}...) buildArgs = append([]string{"build"}, buildArgs...) - dockerCmd(c, buildArgs...) + cli.DockerCmd(c, buildArgs...) } diff --git a/integration-cli/requirements_test.go b/integration-cli/requirements_test.go index 9786fd9fac..425c98672f 100644 --- a/integration-cli/requirements_test.go +++ b/integration-cli/requirements_test.go @@ -15,6 +15,7 @@ import ( "github.com/docker/docker/api/types/swarm" "github.com/docker/docker/api/types/versions" "github.com/docker/docker/client" + "github.com/docker/docker/integration-cli/cli" "github.com/docker/docker/integration-cli/requirement" "github.com/docker/docker/testutil/registry" ) @@ -173,7 +174,7 @@ func TODOBuildkit() bool { } func DockerCLIVersion(t testing.TB) string { - out, _ := dockerCmd(t, "--version") + out := cli.DockerCmd(t, "--version").Stdout() version := strings.Fields(out) if len(version) < 3 { t.Fatal("unknown version output", version) diff --git a/integration-cli/utils_test.go b/integration-cli/utils_test.go index 1be232afe0..136f15c69e 100644 --- a/integration-cli/utils_test.go +++ b/integration-cli/utils_test.go @@ -8,6 +8,7 @@ import ( "strings" "testing" + "github.com/docker/docker/integration-cli/cli" "github.com/docker/docker/testutil" "github.com/pkg/errors" "gotest.tools/v3/icmd" @@ -23,19 +24,14 @@ func getPrefixAndSlashFromDaemonPlatform() (prefix, slash string) { // TODO: update code to call cmd.RunCmd directly, and remove this function // Deprecated: use gotest.tools/icmd func runCommandWithOutput(execCmd *exec.Cmd) (string, int, error) { - result := icmd.RunCmd(transformCmd(execCmd)) - return result.Combined(), result.ExitCode, result.Error -} - -// Temporary shim for migrating commands to the new function -func transformCmd(execCmd *exec.Cmd) icmd.Cmd { - return icmd.Cmd{ + result := icmd.RunCmd(icmd.Cmd{ Command: execCmd.Args, Env: execCmd.Env, Dir: execCmd.Dir, Stdin: execCmd.Stdin, Stdout: execCmd.Stdout, - } + }) + return result.Combined(), result.ExitCode, result.Error } // ParseCgroupPaths parses 'procCgroupData', which is output of '/proc//cgroup', and returns @@ -135,7 +131,7 @@ func existingElements(c *testing.T, opts elementListOptions) []string { if opts.format != "" { args = append(args, "--format", opts.format) } - out, _ := dockerCmd(c, args...) + out := cli.DockerCmd(c, args...).Combined() var lines []string for _, l := range strings.Split(out, "\n") { if l != "" {