Merge pull request #46088 from thaJeztah/remove_deprecated_utils

integration-cli: remove deprecated `dockerCmd` and `waitRun` utilities
This commit is contained in:
Sebastiaan van Stijn 2023-10-20 15:44:46 +02:00 committed by GitHub
commit c3ca4f5de0
No known key found for this signature in database
GPG key ID: 4AEE18F83AFDEB23
66 changed files with 2719 additions and 2816 deletions

View file

@ -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() {

View file

@ -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

View file

@ -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))
}

View file

@ -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{}{

View file

@ -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))

View file

@ -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")

View file

@ -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)

View file

@ -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)

View file

@ -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

View file

@ -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() {

View file

@ -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,

View file

@ -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)

File diff suppressed because it is too large Load diff

View file

@ -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)

View file

@ -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: <digest>", so find that
matches := digestRegex.FindStringSubmatch(out)
@ -91,7 +94,7 @@ func testPullByDigest(c *testing.T) {
// pull from the registry using the <name>@<digest> 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: <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 <name>@<digest> 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 <name>@<digest> 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 <name>@<digest> 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 <name>@<digest> 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=<none>, digest = $digest1
re1 := regexp.MustCompile(`\s*` + repoName + `\s*<none>\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=<none>, 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, <none> AND repo, <none>, 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=<none>, digest = $digest1
re1 := regexp.MustCompile(`\s*` + repoName + `\s*<none>\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=<none>, 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, <none> AND repo, <none>, 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 <name>@<digest> 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 <name>@<digest> 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 <name>@<digest> 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 <name>@<digest> 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 <name>@<digest> 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")

View file

@ -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]")

View file

@ -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)

View file

@ -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, "/")

View file

@ -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)

View file

@ -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"))

View file

@ -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, "")
}

View file

@ -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,

View file

@ -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"))

View file

@ -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"))
}

View file

@ -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 {

View file

@ -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)

View file

@ -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")
}

View file

@ -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 <container id> [ -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 <image id> 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

View file

@ -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)
}

View file

@ -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")
}

View file

@ -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)

View file

@ -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), "<nil>,<nil>", 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]) != "<nil>")
@ -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`))
}

View file

@ -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")
}

View file

@ -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)
}

View file

@ -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)

View file

@ -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)

View file

@ -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:<name|id>"))
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()))
}

File diff suppressed because it is too large Load diff

View file

@ -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)

View file

@ -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) {

View file

@ -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")

View file

@ -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))

View file

@ -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")
}

View file

@ -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: <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)
}

View file

@ -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")
}

View file

@ -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")

View file

@ -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)
}

View file

@ -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)
}

View file

@ -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")

File diff suppressed because it is too large Load diff

View file

@ -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)

View file

@ -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)

View file

@ -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"))
}

View file

@ -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

View file

@ -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

View file

@ -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 {

View file

@ -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")

View file

@ -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")
}

View file

@ -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))
}

View file

@ -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)

View file

@ -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")

View file

@ -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.

View file

@ -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 {

View file

@ -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...)
}

View file

@ -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)

View file

@ -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/<pid>/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 != "" {