From 2ee77da8058d539b854a2dcb97c481131a92a22a Mon Sep 17 00:00:00 2001 From: Xiaoxi He Date: Fri, 7 Sep 2018 11:26:04 +0800 Subject: [PATCH 01/45] Fix some typos Signed-off-by: Xiaoxi He (cherry picked from commit 5c0d2a0932afb1e9c9e26326a22fdbefa1069463) Signed-off-by: Sebastiaan van Stijn Upstream-commit: 0b46144ff726f57640b85e7b24a2443f46eb9e25 Component: engine --- components/engine/CHANGELOG.md | 2 +- components/engine/api/types/stats.go | 2 +- components/engine/cmd/dockerd/daemon.go | 2 +- components/engine/integration/service/create_test.go | 2 +- 4 files changed, 4 insertions(+), 4 deletions(-) diff --git a/components/engine/CHANGELOG.md b/components/engine/CHANGELOG.md index fec9269b79..83fb9f4f09 100644 --- a/components/engine/CHANGELOG.md +++ b/components/engine/CHANGELOG.md @@ -99,7 +99,7 @@ be found. * Add `--format` option to `docker node ls` [#30424](https://github.com/docker/docker/pull/30424) * Add `--prune` option to `docker stack deploy` to remove services that are no longer defined in the docker-compose file [#31302](https://github.com/docker/docker/pull/31302) * Add `PORTS` column for `docker service ls` when using `ingress` mode [#30813](https://github.com/docker/docker/pull/30813) -- Fix unnescessary re-deploying of tasks when environment-variables are used [#32364](https://github.com/docker/docker/pull/32364) +- Fix unnecessary re-deploying of tasks when environment-variables are used [#32364](https://github.com/docker/docker/pull/32364) - Fix `docker stack deploy` not supporting `endpoint_mode` when deploying from a docker compose file [#32333](https://github.com/docker/docker/pull/32333) - Proceed with startup if cluster component cannot be created to allow recovering from a broken swarm setup [#31631](https://github.com/docker/docker/pull/31631) diff --git a/components/engine/api/types/stats.go b/components/engine/api/types/stats.go index 60175c0613..9dc73431f3 100644 --- a/components/engine/api/types/stats.go +++ b/components/engine/api/types/stats.go @@ -120,7 +120,7 @@ type NetworkStats struct { RxBytes uint64 `json:"rx_bytes"` // Packets received. Windows and Linux. RxPackets uint64 `json:"rx_packets"` - // Received errors. Not used on Windows. Note that we dont `omitempty` this + // Received errors. Not used on Windows. Note that we don't `omitempty` this // field as it is expected in the >=v1.21 API stats structure. RxErrors uint64 `json:"rx_errors"` // Incoming packets dropped. Windows and Linux. diff --git a/components/engine/cmd/dockerd/daemon.go b/components/engine/cmd/dockerd/daemon.go index 839537316a..2bb42a3924 100644 --- a/components/engine/cmd/dockerd/daemon.go +++ b/components/engine/cmd/dockerd/daemon.go @@ -184,7 +184,7 @@ func (cli *DaemonCli) start(opts *daemonOptions) (err error) { d.StoreHosts(hosts) - // validate after NewDaemon has restored enabled plugins. Dont change order. + // validate after NewDaemon has restored enabled plugins. Don't change order. if err := validateAuthzPlugins(cli.Config.AuthorizationPlugins, pluginStore); err != nil { return fmt.Errorf("Error validating authorization plugin: %v", err) } diff --git a/components/engine/integration/service/create_test.go b/components/engine/integration/service/create_test.go index 1d15be176e..7112fa719c 100644 --- a/components/engine/integration/service/create_test.go +++ b/components/engine/integration/service/create_test.go @@ -138,7 +138,7 @@ func TestCreateWithDuplicateNetworkNames(t *testing.T) { network.WithDriver("bridge"), ) - // Dupliates with name but with different driver + // Duplicates with name but with different driver n3 := network.CreateNoError(t, context.Background(), client, name, network.WithDriver("overlay"), ) From 04efd9ec4ac4d6e6386330cf8014add12658fbe8 Mon Sep 17 00:00:00 2001 From: Arash Deshmeh Date: Thu, 13 Sep 2018 17:51:03 -0400 Subject: [PATCH 02/45] migrated ipc integration tests to integration/container Signed-off-by: Arash Deshmeh (cherry picked from commit febefb850d12e0ed1c2ab2a25336ece43204ba03) Signed-off-by: Sebastiaan van Stijn Upstream-commit: 6a1983ea7564697f18ce2aa1147646906abb97c4 Component: engine --- .../docker_api_ipcmode_test.go | 81 ------------- .../integration-cli/docker_cli_daemon_test.go | 61 ---------- .../integration/container/ipcmode_test.go | 114 ++++++++++++++++++ .../internal/test/environment/environment.go | 6 + 4 files changed, 120 insertions(+), 142 deletions(-) delete mode 100644 components/engine/integration-cli/docker_api_ipcmode_test.go diff --git a/components/engine/integration-cli/docker_api_ipcmode_test.go b/components/engine/integration-cli/docker_api_ipcmode_test.go deleted file mode 100644 index 9eb483d8b2..0000000000 --- a/components/engine/integration-cli/docker_api_ipcmode_test.go +++ /dev/null @@ -1,81 +0,0 @@ -// build +linux -package main - -import ( - "bufio" - "context" - "io/ioutil" - "os" - "strings" - - "github.com/docker/docker/api/types" - "github.com/docker/docker/api/types/container" - "github.com/docker/docker/integration-cli/checker" - "github.com/docker/docker/integration-cli/cli" - "github.com/go-check/check" -) - -/* testIpcCheckDevExists checks whether a given mount (identified by its - * major:minor pair from /proc/self/mountinfo) exists on the host system. - * - * The format of /proc/self/mountinfo is like: - * - * 29 23 0:24 / /dev/shm rw,nosuid,nodev shared:4 - tmpfs tmpfs rw - * ^^^^\ - * - this is the minor:major we look for - */ -func testIpcCheckDevExists(mm string) (bool, error) { - f, err := os.Open("/proc/self/mountinfo") - if err != nil { - return false, err - } - defer f.Close() - - s := bufio.NewScanner(f) - for s.Scan() { - fields := strings.Fields(s.Text()) - if len(fields) < 7 { - continue - } - if fields[2] == mm { - return true, nil - } - } - - return false, s.Err() -} - -/* TestAPIIpcModeHost checks that a container created with --ipc host - * can use IPC of the host system. - */ -func (s *DockerSuite) TestAPIIpcModeHost(c *check.C) { - testRequires(c, DaemonIsLinux, SameHostDaemon, NotUserNamespace) - - cfg := container.Config{ - Image: "busybox", - Cmd: []string{"top"}, - } - hostCfg := container.HostConfig{ - IpcMode: container.IpcMode("host"), - } - ctx := context.Background() - - client := testEnv.APIClient() - resp, err := client.ContainerCreate(ctx, &cfg, &hostCfg, nil, "") - c.Assert(err, checker.IsNil) - c.Assert(len(resp.Warnings), checker.Equals, 0) - name := resp.ID - - err = client.ContainerStart(ctx, name, types.ContainerStartOptions{}) - c.Assert(err, checker.IsNil) - - // check that IPC is shared - // 1. create a file inside container - cli.DockerCmd(c, "exec", name, "sh", "-c", "printf covfefe > /dev/shm/."+name) - // 2. check it's the same on the host - bytes, err := ioutil.ReadFile("/dev/shm/." + name) - c.Assert(err, checker.IsNil) - c.Assert(string(bytes), checker.Matches, "^covfefe$") - // 3. clean up - cli.DockerCmd(c, "exec", name, "rm", "-f", "/dev/shm/."+name) -} diff --git a/components/engine/integration-cli/docker_cli_daemon_test.go b/components/engine/integration-cli/docker_cli_daemon_test.go index d3cd5f1676..6431280732 100644 --- a/components/engine/integration-cli/docker_cli_daemon_test.go +++ b/components/engine/integration-cli/docker_cli_daemon_test.go @@ -2903,67 +2903,6 @@ func (s *DockerDaemonSuite) TestShmSizeReload(c *check.C) { c.Assert(strings.TrimSpace(out), check.Equals, fmt.Sprintf("%v", size)) } -// this is used to test both "private" and "shareable" daemon default ipc modes -func testDaemonIpcPrivateShareable(d *daemon.Daemon, c *check.C, mustExist bool) { - name := "test-ipcmode" - _, err := d.Cmd("run", "-d", "--name", name, "busybox", "top") - c.Assert(err, checker.IsNil) - - // get major:minor pair for /dev/shm from container's /proc/self/mountinfo - cmd := "awk '($5 == \"/dev/shm\") {printf $3}' /proc/self/mountinfo" - mm, err := d.Cmd("exec", "-i", name, "sh", "-c", cmd) - c.Assert(err, checker.IsNil) - c.Assert(mm, checker.Matches, "^[0-9]+:[0-9]+$") - - exists, err := testIpcCheckDevExists(mm) - c.Assert(err, checker.IsNil) - c.Logf("[testDaemonIpcPrivateShareable] ipcdev: %v, exists: %v, mustExist: %v\n", mm, exists, mustExist) - c.Assert(exists, checker.Equals, mustExist) -} - -// TestDaemonIpcModeShareable checks that --default-ipc-mode shareable works as intended. -func (s *DockerDaemonSuite) TestDaemonIpcModeShareable(c *check.C) { - testRequires(c, DaemonIsLinux, SameHostDaemon) - - s.d.StartWithBusybox(c, "--default-ipc-mode", "shareable") - testDaemonIpcPrivateShareable(s.d, c, true) -} - -// TestDaemonIpcModePrivate checks that --default-ipc-mode private works as intended. -func (s *DockerDaemonSuite) TestDaemonIpcModePrivate(c *check.C) { - testRequires(c, DaemonIsLinux, SameHostDaemon) - - s.d.StartWithBusybox(c, "--default-ipc-mode", "private") - testDaemonIpcPrivateShareable(s.d, c, false) -} - -// used to check if an IpcMode given in config works as intended -func testDaemonIpcFromConfig(s *DockerDaemonSuite, c *check.C, mode string, mustExist bool) { - f, err := ioutil.TempFile("", "test-daemon-ipc-config") - c.Assert(err, checker.IsNil) - defer os.Remove(f.Name()) - - config := `{"default-ipc-mode": "` + mode + `"}` - _, err = f.WriteString(config) - c.Assert(f.Close(), checker.IsNil) - c.Assert(err, checker.IsNil) - - s.d.StartWithBusybox(c, "--config-file", f.Name()) - testDaemonIpcPrivateShareable(s.d, c, mustExist) -} - -// TestDaemonIpcModePrivateFromConfig checks that "default-ipc-mode: private" config works as intended. -func (s *DockerDaemonSuite) TestDaemonIpcModePrivateFromConfig(c *check.C) { - testRequires(c, DaemonIsLinux, SameHostDaemon) - testDaemonIpcFromConfig(s, c, "private", false) -} - -// TestDaemonIpcModeShareableFromConfig checks that "default-ipc-mode: shareable" config works as intended. -func (s *DockerDaemonSuite) TestDaemonIpcModeShareableFromConfig(c *check.C) { - testRequires(c, DaemonIsLinux, SameHostDaemon) - testDaemonIpcFromConfig(s, c, "shareable", true) -} - func testDaemonStartIpcMode(c *check.C, from, mode string, valid bool) { d := daemon.New(c, dockerBinary, dockerdBinary, testdaemon.WithEnvironment(testEnv.Execution)) c.Logf("Checking IpcMode %s set from %s\n", mode, from) diff --git a/components/engine/integration/container/ipcmode_test.go b/components/engine/integration/container/ipcmode_test.go index b0ed84293f..7f4f818cfd 100644 --- a/components/engine/integration/container/ipcmode_test.go +++ b/components/engine/integration/container/ipcmode_test.go @@ -3,6 +3,7 @@ package container // import "github.com/docker/docker/integration/container" import ( "bufio" "context" + "io/ioutil" "os" "regexp" "strings" @@ -11,9 +12,11 @@ import ( "github.com/docker/docker/api/types" containertypes "github.com/docker/docker/api/types/container" "github.com/docker/docker/integration/internal/container" + "github.com/docker/docker/internal/test/daemon" "github.com/docker/docker/internal/test/request" "gotest.tools/assert" is "gotest.tools/assert/cmp" + "gotest.tools/fs" "gotest.tools/skip" ) @@ -179,3 +182,114 @@ func TestAPIIpcModeShareableAndContainer(t *testing.T) { testIpcContainer(t, "private", false) } + +/* TestAPIIpcModeHost checks that a container created with --ipc host + * can use IPC of the host system. + */ +func TestAPIIpcModeHost(t *testing.T) { + skip.If(t, testEnv.DaemonInfo.OSType != "linux" || testEnv.IsRemoteDaemon() || testEnv.IsUserNamespace()) + + cfg := containertypes.Config{ + Image: "busybox", + Cmd: []string{"top"}, + } + hostCfg := containertypes.HostConfig{ + IpcMode: containertypes.IpcMode("host"), + } + ctx := context.Background() + + client := testEnv.APIClient() + resp, err := client.ContainerCreate(ctx, &cfg, &hostCfg, nil, "") + assert.NilError(t, err) + assert.Check(t, is.Equal(len(resp.Warnings), 0)) + name := resp.ID + + err = client.ContainerStart(ctx, name, types.ContainerStartOptions{}) + assert.NilError(t, err) + + // check that IPC is shared + // 1. create a file inside container + _, err = container.Exec(ctx, client, name, []string{"sh", "-c", "printf covfefe > /dev/shm/." + name}) + assert.NilError(t, err) + // 2. check it's the same on the host + bytes, err := ioutil.ReadFile("/dev/shm/." + name) + assert.NilError(t, err) + assert.Check(t, is.Equal("covfefe", string(bytes))) + // 3. clean up + _, err = container.Exec(ctx, client, name, []string{"rm", "-f", "/dev/shm/." + name}) + assert.NilError(t, err) +} + +// testDaemonIpcPrivateShareable is a helper function to test "private" and "shareable" daemon default ipc modes. +func testDaemonIpcPrivateShareable(t *testing.T, mustBeShared bool, arg ...string) { + defer setupTest(t)() + + d := daemon.New(t) + d.StartWithBusybox(t, arg...) + defer d.Stop(t) + + client, err := d.NewClient() + assert.Check(t, err, "error creating client") + + cfg := containertypes.Config{ + Image: "busybox", + Cmd: []string{"top"}, + } + ctx := context.Background() + + resp, err := client.ContainerCreate(ctx, &cfg, &containertypes.HostConfig{}, nil, "") + assert.NilError(t, err) + assert.Check(t, is.Equal(len(resp.Warnings), 0)) + + err = client.ContainerStart(ctx, resp.ID, types.ContainerStartOptions{}) + assert.NilError(t, err) + + // get major:minor pair for /dev/shm from container's /proc/self/mountinfo + cmd := "awk '($5 == \"/dev/shm\") {printf $3}' /proc/self/mountinfo" + result, err := container.Exec(ctx, client, resp.ID, []string{"sh", "-c", cmd}) + assert.NilError(t, err) + mm := result.Combined() + assert.Check(t, is.Equal(true, regexp.MustCompile("^[0-9]+:[0-9]+$").MatchString(mm))) + + shared, err := testIpcCheckDevExists(mm) + assert.NilError(t, err) + t.Logf("[testDaemonIpcPrivateShareable] ipcdev: %v, shared: %v, mustBeShared: %v\n", mm, shared, mustBeShared) + assert.Check(t, is.Equal(shared, mustBeShared)) +} + +// TestDaemonIpcModeShareable checks that --default-ipc-mode shareable works as intended. +func TestDaemonIpcModeShareable(t *testing.T) { + skip.If(t, testEnv.DaemonInfo.OSType != "linux" || testEnv.IsRemoteDaemon()) + + testDaemonIpcPrivateShareable(t, true, "--default-ipc-mode", "shareable") +} + +// TestDaemonIpcModePrivate checks that --default-ipc-mode private works as intended. +func TestDaemonIpcModePrivate(t *testing.T) { + skip.If(t, testEnv.DaemonInfo.OSType != "linux" || testEnv.IsRemoteDaemon()) + + testDaemonIpcPrivateShareable(t, false, "--default-ipc-mode", "private") +} + +// used to check if an IpcMode given in config works as intended +func testDaemonIpcFromConfig(t *testing.T, mode string, mustExist bool) { + config := `{"default-ipc-mode": "` + mode + `"}` + file := fs.NewFile(t, "test-daemon-ipc-config", fs.WithContent(config)) + defer file.Remove() + + testDaemonIpcPrivateShareable(t, mustExist, "--config-file", file.Path()) +} + +// TestDaemonIpcModePrivateFromConfig checks that "default-ipc-mode: private" config works as intended. +func TestDaemonIpcModePrivateFromConfig(t *testing.T) { + skip.If(t, testEnv.DaemonInfo.OSType != "linux" || testEnv.IsRemoteDaemon()) + + testDaemonIpcFromConfig(t, "private", false) +} + +// TestDaemonIpcModeShareableFromConfig checks that "default-ipc-mode: shareable" config works as intended. +func TestDaemonIpcModeShareableFromConfig(t *testing.T) { + skip.If(t, testEnv.DaemonInfo.OSType != "linux" || testEnv.IsRemoteDaemon()) + + testDaemonIpcFromConfig(t, "shareable", true) +} diff --git a/components/engine/internal/test/environment/environment.go b/components/engine/internal/test/environment/environment.go index 74c8e2ce0a..5538d2097e 100644 --- a/components/engine/internal/test/environment/environment.go +++ b/components/engine/internal/test/environment/environment.go @@ -145,6 +145,12 @@ func (e *Execution) APIClient() client.APIClient { return e.client } +// IsUserNamespace returns whether the user namespace remapping is enabled +func (e *Execution) IsUserNamespace() bool { + root := os.Getenv("DOCKER_REMAP_ROOT") + return root != "" +} + // EnsureFrozenImagesLinux loads frozen test images into the daemon // if they aren't already loaded func EnsureFrozenImagesLinux(testEnv *Execution) error { From c97555715094fb87c3a1d52bd27717edf92b1c2d Mon Sep 17 00:00:00 2001 From: zhangyue Date: Sat, 10 Nov 2018 11:00:26 +0800 Subject: [PATCH 03/45] cli: fix images filter when use multi reference filter Signed-off-by: zhangyue (cherry picked from commit 5007c36d71ac86f5b47b6ba10a5ed6e841807284) Signed-off-by: Sebastiaan van Stijn Upstream-commit: 8a614d1b2494b6d2381e157a99ad2736a6038d2d Component: engine --- components/engine/daemon/images/images.go | 3 ++ .../engine/integration/image/list_test.go | 50 +++++++++++++++++++ 2 files changed, 53 insertions(+) create mode 100644 components/engine/integration/image/list_test.go diff --git a/components/engine/daemon/images/images.go b/components/engine/daemon/images/images.go index 49212341c5..94e0c1eb8d 100644 --- a/components/engine/daemon/images/images.go +++ b/components/engine/daemon/images/images.go @@ -152,6 +152,9 @@ func (i *ImageService) Images(imageFilters filters.Args, all bool, withExtraAttr if matchErr != nil { return nil, matchErr } + if found { + break + } } if !found { continue diff --git a/components/engine/integration/image/list_test.go b/components/engine/integration/image/list_test.go new file mode 100644 index 0000000000..9d6ce16537 --- /dev/null +++ b/components/engine/integration/image/list_test.go @@ -0,0 +1,50 @@ +package image // import "github.com/docker/docker/integration/image" + +import ( + "context" + "testing" + + "github.com/docker/docker/api/types" + "github.com/docker/docker/api/types/filters" + "github.com/docker/docker/internal/test/request" + "gotest.tools/assert" + is "gotest.tools/assert/cmp" +) + +// Regression : #38171 +func TestImagesFilterMultiReference(t *testing.T) { + defer setupTest(t)() + client := request.NewAPIClient(t) + ctx := context.Background() + + name := "images_filter_multi_reference" + repoTags := []string{ + name + ":v1", + name + ":v2", + name + ":v3", + name + ":v4", + } + + for _, repoTag := range repoTags { + err := client.ImageTag(ctx, "busybox:latest", repoTag) + assert.NilError(t, err) + } + + filter := filters.NewArgs() + filter.Add("reference", repoTags[0]) + filter.Add("reference", repoTags[1]) + filter.Add("reference", repoTags[2]) + options := types.ImageListOptions{ + All: false, + Filters: filter, + } + images, err := client.ImageList(ctx, options) + assert.NilError(t, err) + + assert.Check(t, is.Equal(len(images[0].RepoTags), 3)) + for _, repoTag := range images[0].RepoTags { + if repoTag != repoTags[0] && repoTag != repoTags[1] && repoTag != repoTags[2] { + t.Errorf("list images doesn't match any repoTag we expected, repoTag: %s", repoTag) + } + } +} From 7f2bfe773c09b49609229c48584a72d722f1fa8c Mon Sep 17 00:00:00 2001 From: Sebastiaan van Stijn Date: Sat, 22 Dec 2018 15:53:02 +0100 Subject: [PATCH 04/45] Test: Replace NewClient() with NewClientT() Signed-off-by: Sebastiaan van Stijn (cherry picked from commit 2cb7b73a1bdbf2e7ea6da7d0c050b303c2c4f5dc) Signed-off-by: Sebastiaan van Stijn Upstream-commit: bb221587404be76f404062618e7d947f4d1bd39b Component: engine --- .../integration-cli/daemon/daemon_swarm.go | 15 +-- .../docker_api_swarm_service_test.go | 9 +- .../integration-cli/docker_api_swarm_test.go | 16 +-- .../integration-cli/docker_cli_swarm_test.go | 6 +- .../container/daemon_linux_test.go | 13 +- .../integration/container/export_test.go | 7 +- .../integration/container/ipcmode_test.go | 9 +- .../integration/container/restart_test.go | 9 +- .../integration/network/ipvlan/ipvlan_test.go | 15 +-- .../network/macvlan/macvlan_test.go | 15 +-- .../integration/network/network_test.go | 23 ++-- .../integration/network/service_test.go | 111 +++++++++--------- .../plugin/authz/authz_plugin_test.go | 78 ++++++------ .../plugin/authz/authz_plugin_v2_test.go | 41 +++---- .../plugin/logging/validation_test.go | 9 +- .../integration/plugin/volumes/mounts_test.go | 11 +- .../system/cgroupdriver_systemd_test.go | 14 +-- .../engine/integration/system/info_test.go | 6 +- .../engine/internal/test/daemon/daemon.go | 16 ++- 19 files changed, 191 insertions(+), 232 deletions(-) diff --git a/components/engine/integration-cli/daemon/daemon_swarm.go b/components/engine/integration-cli/daemon/daemon_swarm.go index 4a6ce8a5c5..f43bd3b295 100644 --- a/components/engine/integration-cli/daemon/daemon_swarm.go +++ b/components/engine/integration-cli/daemon/daemon_swarm.go @@ -67,8 +67,7 @@ func (d *Daemon) CheckServiceUpdateState(service string) func(*check.C) (interfa // CheckPluginRunning returns the runtime state of the plugin func (d *Daemon) CheckPluginRunning(plugin string) func(c *check.C) (interface{}, check.CommentInterface) { return func(c *check.C) (interface{}, check.CommentInterface) { - apiclient, err := d.NewClient() - assert.NilError(c, err) + apiclient := d.NewClientT(c) resp, _, err := apiclient.PluginInspectWithRaw(context.Background(), plugin) if client.IsErrNotFound(err) { return false, check.Commentf("%v", err) @@ -81,8 +80,7 @@ func (d *Daemon) CheckPluginRunning(plugin string) func(c *check.C) (interface{} // CheckPluginImage returns the runtime state of the plugin func (d *Daemon) CheckPluginImage(plugin string) func(c *check.C) (interface{}, check.CommentInterface) { return func(c *check.C) (interface{}, check.CommentInterface) { - apiclient, err := d.NewClient() - assert.NilError(c, err) + apiclient := d.NewClientT(c) resp, _, err := apiclient.PluginInspectWithRaw(context.Background(), plugin) if client.IsErrNotFound(err) { return false, check.Commentf("%v", err) @@ -102,8 +100,7 @@ func (d *Daemon) CheckServiceTasks(service string) func(*check.C) (interface{}, // CheckRunningTaskNetworks returns the number of times each network is referenced from a task. func (d *Daemon) CheckRunningTaskNetworks(c *check.C) (interface{}, check.CommentInterface) { - cli, err := d.NewClient() - c.Assert(err, checker.IsNil) + cli := d.NewClientT(c) defer cli.Close() filterArgs := filters.NewArgs() @@ -127,8 +124,7 @@ func (d *Daemon) CheckRunningTaskNetworks(c *check.C) (interface{}, check.Commen // CheckRunningTaskImages returns the times each image is running as a task. func (d *Daemon) CheckRunningTaskImages(c *check.C) (interface{}, check.CommentInterface) { - cli, err := d.NewClient() - c.Assert(err, checker.IsNil) + cli := d.NewClientT(c) defer cli.Close() filterArgs := filters.NewArgs() @@ -177,8 +173,7 @@ func (d *Daemon) CheckControlAvailable(c *check.C) (interface{}, check.CommentIn // CheckLeader returns whether there is a leader on the swarm or not func (d *Daemon) CheckLeader(c *check.C) (interface{}, check.CommentInterface) { - cli, err := d.NewClient() - c.Assert(err, checker.IsNil) + cli := d.NewClientT(c) defer cli.Close() errList := check.Commentf("could not get node list") diff --git a/components/engine/integration-cli/docker_api_swarm_service_test.go b/components/engine/integration-cli/docker_api_swarm_service_test.go index 4d39a34b09..1986c94bb0 100644 --- a/components/engine/integration-cli/docker_api_swarm_service_test.go +++ b/components/engine/integration-cli/docker_api_swarm_service_test.go @@ -66,20 +66,19 @@ func (s *DockerSwarmSuite) TestAPISwarmServicesCreate(c *check.C) { id := d.CreateService(c, simpleTestService, setInstances(instances)) waitAndAssert(c, defaultReconciliationTimeout, d.CheckActiveContainerCount, checker.Equals, instances) - cli, err := d.NewClient() - c.Assert(err, checker.IsNil) - defer cli.Close() + client := d.NewClientT(c) + defer client.Close() options := types.ServiceInspectOptions{InsertDefaults: true} // insertDefaults inserts UpdateConfig when service is fetched by ID - resp, _, err := cli.ServiceInspectWithRaw(context.Background(), id, options) + resp, _, err := client.ServiceInspectWithRaw(context.Background(), id, options) out := fmt.Sprintf("%+v", resp) c.Assert(err, checker.IsNil) c.Assert(out, checker.Contains, "UpdateConfig") // insertDefaults inserts UpdateConfig when service is fetched by ID - resp, _, err = cli.ServiceInspectWithRaw(context.Background(), "top", options) + resp, _, err = client.ServiceInspectWithRaw(context.Background(), "top", options) out = fmt.Sprintf("%+v", resp) c.Assert(err, checker.IsNil) c.Assert(string(out), checker.Contains, "UpdateConfig") diff --git a/components/engine/integration-cli/docker_api_swarm_test.go b/components/engine/integration-cli/docker_api_swarm_test.go index ddbcd56556..9be5719c52 100644 --- a/components/engine/integration-cli/docker_api_swarm_test.go +++ b/components/engine/integration-cli/docker_api_swarm_test.go @@ -392,13 +392,12 @@ func (s *DockerSwarmSuite) TestAPISwarmRaftQuorum(c *check.C) { var service swarm.Service simpleTestService(&service) service.Spec.Name = "top2" - cli, err := d1.NewClient() - c.Assert(err, checker.IsNil) + cli := d1.NewClientT(c) defer cli.Close() // d1 will eventually step down from leader because there is no longer an active quorum, wait for that to happen waitAndAssert(c, defaultReconciliationTimeout, func(c *check.C) (interface{}, check.CommentInterface) { - _, err = cli.ServiceCreate(context.Background(), service.Spec, types.ServiceCreateOptions{}) + _, err := cli.ServiceCreate(context.Background(), service.Spec, types.ServiceCreateOptions{}) return err.Error(), nil }, checker.Contains, "Make sure more than half of the managers are online.") @@ -868,10 +867,9 @@ func (s *DockerSwarmSuite) TestAPISwarmServicesUpdateWithName(c *check.C) { instances = 5 setInstances(instances)(service) - cli, err := d.NewClient() - c.Assert(err, checker.IsNil) + cli := d.NewClientT(c) defer cli.Close() - _, err = cli.ServiceUpdate(context.Background(), service.Spec.Name, service.Version, service.Spec, types.ServiceUpdateOptions{}) + _, err := cli.ServiceUpdate(context.Background(), service.Spec.Name, service.Version, service.Spec, types.ServiceUpdateOptions{}) c.Assert(err, checker.IsNil) waitAndAssert(c, defaultReconciliationTimeout, d.CheckActiveContainerCount, checker.Equals, instances) } @@ -903,8 +901,7 @@ func (s *DockerSwarmSuite) TestAPISwarmErrorHandling(c *check.C) { // This test makes sure the fixes correctly output scopes instead. func (s *DockerSwarmSuite) TestAPIDuplicateNetworks(c *check.C) { d := s.AddDaemon(c, true, true) - cli, err := d.NewClient() - c.Assert(err, checker.IsNil) + cli := d.NewClientT(c) defer cli.Close() name := "foo" @@ -1033,8 +1030,7 @@ func (s *DockerSwarmSuite) TestAPINetworkInspectWithScope(c *check.C) { name := "test-scoped-network" ctx := context.Background() - apiclient, err := d.NewClient() - assert.NilError(c, err) + apiclient := d.NewClientT(c) resp, err := apiclient.NetworkCreate(ctx, name, types.NetworkCreate{Driver: "overlay"}) assert.NilError(c, err) diff --git a/components/engine/integration-cli/docker_cli_swarm_test.go b/components/engine/integration-cli/docker_cli_swarm_test.go index 3433e3b39a..dafe8c96ad 100644 --- a/components/engine/integration-cli/docker_cli_swarm_test.go +++ b/components/engine/integration-cli/docker_cli_swarm_test.go @@ -426,8 +426,7 @@ func (s *DockerSwarmSuite) TestOverlayAttachableOnSwarmLeave(c *check.C) { c.Assert(err, checker.IsNil, check.Commentf("%s", out)) // Leave the swarm - err = d.SwarmLeave(true) - c.Assert(err, checker.IsNil) + c.Assert(d.SwarmLeave(true), checker.IsNil) // Check the container is disconnected out, err = d.Cmd("inspect", "c1", "--format", "{{.NetworkSettings.Networks."+nwName+"}}") @@ -1703,8 +1702,7 @@ func (s *DockerSwarmSuite) TestNetworkInspectWithDuplicateNames(c *check.C) { Driver: "bridge", } - cli, err := d.NewClient() - c.Assert(err, checker.IsNil) + cli := d.NewClientT(c) defer cli.Close() n1, err := cli.NetworkCreate(context.Background(), name, options) diff --git a/components/engine/integration/container/daemon_linux_test.go b/components/engine/integration/container/daemon_linux_test.go index bd13e30939..36866a3087 100644 --- a/components/engine/integration/container/daemon_linux_test.go +++ b/components/engine/integration/container/daemon_linux_test.go @@ -36,18 +36,17 @@ func TestContainerStartOnDaemonRestart(t *testing.T) { d.StartWithBusybox(t, "--iptables=false") defer d.Stop(t) - client, err := d.NewClient() - assert.Check(t, err, "error creating client") + c := d.NewClientT(t) ctx := context.Background() - cID := container.Create(t, ctx, client) - defer client.ContainerRemove(ctx, cID, types.ContainerRemoveOptions{Force: true}) + cID := container.Create(t, ctx, c) + defer c.ContainerRemove(ctx, cID, types.ContainerRemoveOptions{Force: true}) - err = client.ContainerStart(ctx, cID, types.ContainerStartOptions{}) + err := c.ContainerStart(ctx, cID, types.ContainerStartOptions{}) assert.Check(t, err, "error starting test container") - inspect, err := client.ContainerInspect(ctx, cID) + inspect, err := c.ContainerInspect(ctx, cID) assert.Check(t, err, "error getting inspect data") ppid := getContainerdShimPid(t, inspect) @@ -63,7 +62,7 @@ func TestContainerStartOnDaemonRestart(t *testing.T) { d.Start(t, "--iptables=false") - err = client.ContainerStart(ctx, cID, types.ContainerStartOptions{}) + err = c.ContainerStart(ctx, cID, types.ContainerStartOptions{}) assert.Check(t, err, "failed to start test container") } diff --git a/components/engine/integration/container/export_test.go b/components/engine/integration/container/export_test.go index ed3a330500..17a21026cd 100644 --- a/components/engine/integration/container/export_test.go +++ b/components/engine/integration/container/export_test.go @@ -62,17 +62,16 @@ func TestExportContainerAfterDaemonRestart(t *testing.T) { skip.If(t, testEnv.IsRemoteDaemon()) d := daemon.New(t) - client, err := d.NewClient() - assert.NilError(t, err) + c := d.NewClientT(t) d.StartWithBusybox(t) defer d.Stop(t) ctx := context.Background() - ctrID := container.Create(t, ctx, client) + ctrID := container.Create(t, ctx, c) d.Restart(t) - _, err = client.ContainerExport(ctx, ctrID) + _, err := c.ContainerExport(ctx, ctrID) assert.NilError(t, err) } diff --git a/components/engine/integration/container/ipcmode_test.go b/components/engine/integration/container/ipcmode_test.go index 7f4f818cfd..fc079a4dae 100644 --- a/components/engine/integration/container/ipcmode_test.go +++ b/components/engine/integration/container/ipcmode_test.go @@ -228,8 +228,7 @@ func testDaemonIpcPrivateShareable(t *testing.T, mustBeShared bool, arg ...strin d.StartWithBusybox(t, arg...) defer d.Stop(t) - client, err := d.NewClient() - assert.Check(t, err, "error creating client") + c := d.NewClientT(t) cfg := containertypes.Config{ Image: "busybox", @@ -237,16 +236,16 @@ func testDaemonIpcPrivateShareable(t *testing.T, mustBeShared bool, arg ...strin } ctx := context.Background() - resp, err := client.ContainerCreate(ctx, &cfg, &containertypes.HostConfig{}, nil, "") + resp, err := c.ContainerCreate(ctx, &cfg, &containertypes.HostConfig{}, nil, "") assert.NilError(t, err) assert.Check(t, is.Equal(len(resp.Warnings), 0)) - err = client.ContainerStart(ctx, resp.ID, types.ContainerStartOptions{}) + err = c.ContainerStart(ctx, resp.ID, types.ContainerStartOptions{}) assert.NilError(t, err) // get major:minor pair for /dev/shm from container's /proc/self/mountinfo cmd := "awk '($5 == \"/dev/shm\") {printf $3}' /proc/self/mountinfo" - result, err := container.Exec(ctx, client, resp.ID, []string{"sh", "-c", cmd}) + result, err := container.Exec(ctx, c, resp.ID, []string{"sh", "-c", cmd}) assert.NilError(t, err) mm := result.Combined() assert.Check(t, is.Equal(true, regexp.MustCompile("^[0-9]+:[0-9]+$").MatchString(mm))) diff --git a/components/engine/integration/container/restart_test.go b/components/engine/integration/container/restart_test.go index 64b076410f..3da30c0f3a 100644 --- a/components/engine/integration/container/restart_test.go +++ b/components/engine/integration/container/restart_test.go @@ -26,7 +26,7 @@ func TestDaemonRestartKillContainers(t *testing.T) { xStart bool } - for _, c := range []testCase{ + for _, tc := range []testCase{ { desc: "container without restart policy", config: &container.Config{Image: "busybox", Cmd: []string{"top"}}, @@ -57,16 +57,15 @@ func TestDaemonRestartKillContainers(t *testing.T) { d.Stop(t) }, } { - t.Run(fmt.Sprintf("live-restore=%v/%s/%s", liveRestoreEnabled, c.desc, fnName), func(t *testing.T) { - c := c + t.Run(fmt.Sprintf("live-restore=%v/%s/%s", liveRestoreEnabled, tc.desc, fnName), func(t *testing.T) { + c := tc liveRestoreEnabled := liveRestoreEnabled stopDaemon := stopDaemon t.Parallel() d := daemon.New(t) - client, err := d.NewClient() - assert.NilError(t, err) + client := d.NewClientT(t) args := []string{"--iptables=false"} if liveRestoreEnabled { diff --git a/components/engine/integration/network/ipvlan/ipvlan_test.go b/components/engine/integration/network/ipvlan/ipvlan_test.go index b146494292..b2571cfaa4 100644 --- a/components/engine/integration/network/ipvlan/ipvlan_test.go +++ b/components/engine/integration/network/ipvlan/ipvlan_test.go @@ -32,19 +32,18 @@ func TestDockerNetworkIpvlanPersistance(t *testing.T) { n.CreateMasterDummy(t, master) defer n.DeleteInterface(t, master) - client, err := d.NewClient() - assert.NilError(t, err) + c := d.NewClientT(t) // create a network specifying the desired sub-interface name netName := "di-persist" - net.CreateNoError(t, context.Background(), client, netName, + net.CreateNoError(t, context.Background(), c, netName, net.WithIPvlan("di-dummy0.70", ""), ) - assert.Check(t, n.IsNetworkAvailable(client, netName)) + assert.Check(t, n.IsNetworkAvailable(c, netName)) // Restart docker daemon to test the config has persisted to disk d.Restart(t) - assert.Check(t, n.IsNetworkAvailable(client, netName)) + assert.Check(t, n.IsNetworkAvailable(c, netName)) } func TestDockerNetworkIpvlan(t *testing.T) { @@ -87,11 +86,9 @@ func TestDockerNetworkIpvlan(t *testing.T) { } { d := daemon.New(t, daemon.WithExperimental) d.StartWithBusybox(t) + c := d.NewClientT(t) - client, err := d.NewClient() - assert.NilError(t, err) - - t.Run(tc.name, tc.test(client)) + t.Run(tc.name, tc.test(c)) d.Stop(t) // FIXME(vdemeester) clean network diff --git a/components/engine/integration/network/macvlan/macvlan_test.go b/components/engine/integration/network/macvlan/macvlan_test.go index a81b9014b4..04b99ca1df 100644 --- a/components/engine/integration/network/macvlan/macvlan_test.go +++ b/components/engine/integration/network/macvlan/macvlan_test.go @@ -30,16 +30,15 @@ func TestDockerNetworkMacvlanPersistance(t *testing.T) { n.CreateMasterDummy(t, master) defer n.DeleteInterface(t, master) - client, err := d.NewClient() - assert.NilError(t, err) + c := d.NewClientT(t) netName := "dm-persist" - net.CreateNoError(t, context.Background(), client, netName, + net.CreateNoError(t, context.Background(), c, netName, net.WithMacvlan("dm-dummy0.60"), ) - assert.Check(t, n.IsNetworkAvailable(client, netName)) + assert.Check(t, n.IsNetworkAvailable(c, netName)) d.Restart(t) - assert.Check(t, n.IsNetworkAvailable(client, netName)) + assert.Check(t, n.IsNetworkAvailable(c, netName)) } func TestDockerNetworkMacvlan(t *testing.T) { @@ -69,11 +68,9 @@ func TestDockerNetworkMacvlan(t *testing.T) { } { d := daemon.New(t) d.StartWithBusybox(t) + c := d.NewClientT(t) - client, err := d.NewClient() - assert.NilError(t, err) - - t.Run(tc.name, tc.test(client)) + t.Run(tc.name, tc.test(c)) d.Stop(t) // FIXME(vdemeester) clean network diff --git a/components/engine/integration/network/network_test.go b/components/engine/integration/network/network_test.go index 5f62550f05..94236b7612 100644 --- a/components/engine/integration/network/network_test.go +++ b/components/engine/integration/network/network_test.go @@ -26,21 +26,20 @@ func TestRunContainerWithBridgeNone(t *testing.T) { d.StartWithBusybox(t, "-b", "none") defer d.Stop(t) - client, err := d.NewClient() - assert.Check(t, err, "error creating client") - + c := d.NewClientT(t) ctx := context.Background() - id1 := container.Run(t, ctx, client) - defer client.ContainerRemove(ctx, id1, types.ContainerRemoveOptions{Force: true}) - result, err := container.Exec(ctx, client, id1, []string{"ip", "l"}) + id1 := container.Run(t, ctx, c) + defer c.ContainerRemove(ctx, id1, types.ContainerRemoveOptions{Force: true}) + + result, err := container.Exec(ctx, c, id1, []string{"ip", "l"}) assert.NilError(t, err) assert.Check(t, is.Equal(false, strings.Contains(result.Combined(), "eth0")), "There shouldn't be eth0 in container in default(bridge) mode when bridge network is disabled") - id2 := container.Run(t, ctx, client, container.WithNetworkMode("bridge")) - defer client.ContainerRemove(ctx, id2, types.ContainerRemoveOptions{Force: true}) + id2 := container.Run(t, ctx, c, container.WithNetworkMode("bridge")) + defer c.ContainerRemove(ctx, id2, types.ContainerRemoveOptions{Force: true}) - result, err = container.Exec(ctx, client, id2, []string{"ip", "l"}) + result, err = container.Exec(ctx, c, id2, []string{"ip", "l"}) assert.NilError(t, err) assert.Check(t, is.Equal(false, strings.Contains(result.Combined(), "eth0")), "There shouldn't be eth0 in container in bridge mode when bridge network is disabled") @@ -51,10 +50,10 @@ func TestRunContainerWithBridgeNone(t *testing.T) { err = cmd.Run() assert.NilError(t, err, "Failed to get current process network namespace: %+v", err) - id3 := container.Run(t, ctx, client, container.WithNetworkMode("host")) - defer client.ContainerRemove(ctx, id3, types.ContainerRemoveOptions{Force: true}) + id3 := container.Run(t, ctx, c, container.WithNetworkMode("host")) + defer c.ContainerRemove(ctx, id3, types.ContainerRemoveOptions{Force: true}) - result, err = container.Exec(ctx, client, id3, []string{"sh", "-c", nsCommand}) + result, err = container.Exec(ctx, c, id3, []string{"sh", "-c", nsCommand}) assert.NilError(t, err) assert.Check(t, is.Equal(stdout.String(), result.Combined()), "The network namspace of container should be the same with host when --net=host and bridge network is disabled") } diff --git a/components/engine/integration/network/service_test.go b/components/engine/integration/network/service_test.go index 4762b577ac..3ea0890678 100644 --- a/components/engine/integration/network/service_test.go +++ b/components/engine/integration/network/service_test.go @@ -32,15 +32,16 @@ func TestDaemonRestartWithLiveRestore(t *testing.T) { d := daemon.New(t) defer d.Stop(t) d.Start(t) - d.Restart(t, "--live-restore=true", + d.Restart(t, + "--live-restore=true", "--default-address-pool", "base=175.30.0.0/16,size=16", - "--default-address-pool", "base=175.33.0.0/16,size=24") + "--default-address-pool", "base=175.33.0.0/16,size=24", + ) // Verify bridge network's subnet - cli, err := d.NewClient() - assert.Assert(t, err) - defer cli.Close() - out, err := cli.NetworkInspect(context.Background(), "bridge", types.NetworkInspectOptions{}) + c := d.NewClientT(t) + defer c.Close() + out, err := c.NetworkInspect(context.Background(), "bridge", types.NetworkInspectOptions{}) assert.NilError(t, err) // Make sure docker0 doesn't get override with new IP in live restore case assert.Equal(t, out.IPAM.Config[0].Subnet, "172.18.0.0/16") @@ -57,31 +58,32 @@ func TestDaemonDefaultNetworkPools(t *testing.T) { defer d.Stop(t) d.Start(t, "--default-address-pool", "base=175.30.0.0/16,size=16", - "--default-address-pool", "base=175.33.0.0/16,size=24") + "--default-address-pool", "base=175.33.0.0/16,size=24", + ) + + c := d.NewClientT(t) + defer c.Close() // Verify bridge network's subnet - cli, err := d.NewClient() - assert.Assert(t, err) - defer cli.Close() - out, err := cli.NetworkInspect(context.Background(), "bridge", types.NetworkInspectOptions{}) + out, err := c.NetworkInspect(context.Background(), "bridge", types.NetworkInspectOptions{}) assert.NilError(t, err) assert.Equal(t, out.IPAM.Config[0].Subnet, "175.30.0.0/16") // Create a bridge network and verify its subnet is the second default pool name := "elango" + t.Name() - network.CreateNoError(t, context.Background(), cli, name, + network.CreateNoError(t, context.Background(), c, name, network.WithDriver("bridge"), ) - out, err = cli.NetworkInspect(context.Background(), name, types.NetworkInspectOptions{}) + out, err = c.NetworkInspect(context.Background(), name, types.NetworkInspectOptions{}) assert.NilError(t, err) assert.Equal(t, out.IPAM.Config[0].Subnet, "175.33.0.0/24") // Create a bridge network and verify its subnet is the third default pool name = "saanvi" + t.Name() - network.CreateNoError(t, context.Background(), cli, name, + network.CreateNoError(t, context.Background(), c, name, network.WithDriver("bridge"), ) - out, err = cli.NetworkInspect(context.Background(), name, types.NetworkInspectOptions{}) + out, err = c.NetworkInspect(context.Background(), name, types.NetworkInspectOptions{}) assert.NilError(t, err) assert.Equal(t, out.IPAM.Config[0].Subnet, "175.33.1.0/24") delInterface(t, defaultNetworkBridge) @@ -96,17 +98,17 @@ func TestDaemonRestartWithExistingNetwork(t *testing.T) { d := daemon.New(t) d.Start(t) defer d.Stop(t) - // Verify bridge network's subnet - cli, err := d.NewClient() - assert.Assert(t, err) - defer cli.Close() + c := d.NewClientT(t) + defer c.Close() // Create a bridge network name := "elango" + t.Name() - network.CreateNoError(t, context.Background(), cli, name, + network.CreateNoError(t, context.Background(), c, name, network.WithDriver("bridge"), ) - out, err := cli.NetworkInspect(context.Background(), name, types.NetworkInspectOptions{}) + + // Verify bridge network's subnet + out, err := c.NetworkInspect(context.Background(), name, types.NetworkInspectOptions{}) assert.NilError(t, err) networkip := out.IPAM.Config[0].Subnet @@ -115,7 +117,7 @@ func TestDaemonRestartWithExistingNetwork(t *testing.T) { "--default-address-pool", "base=175.30.0.0/16,size=16", "--default-address-pool", "base=175.33.0.0/16,size=24") - out1, err := cli.NetworkInspect(context.Background(), name, types.NetworkInspectOptions{}) + out1, err := c.NetworkInspect(context.Background(), name, types.NetworkInspectOptions{}) assert.NilError(t, err) assert.Equal(t, out1.IPAM.Config[0].Subnet, networkip) delInterface(t, defaultNetworkBridge) @@ -129,40 +131,41 @@ func TestDaemonRestartWithExistingNetworkWithDefaultPoolRange(t *testing.T) { d := daemon.New(t) d.Start(t) defer d.Stop(t) - // Verify bridge network's subnet - cli, err := d.NewClient() - assert.Assert(t, err) - defer cli.Close() + c := d.NewClientT(t) + defer c.Close() // Create a bridge network name := "elango" + t.Name() - network.CreateNoError(t, context.Background(), cli, name, + network.CreateNoError(t, context.Background(), c, name, network.WithDriver("bridge"), ) - out, err := cli.NetworkInspect(context.Background(), name, types.NetworkInspectOptions{}) + + // Verify bridge network's subnet + out, err := c.NetworkInspect(context.Background(), name, types.NetworkInspectOptions{}) assert.NilError(t, err) networkip := out.IPAM.Config[0].Subnet // Create a bridge network name = "sthira" + t.Name() - network.CreateNoError(t, context.Background(), cli, name, + network.CreateNoError(t, context.Background(), c, name, network.WithDriver("bridge"), ) - out, err = cli.NetworkInspect(context.Background(), name, types.NetworkInspectOptions{}) + out, err = c.NetworkInspect(context.Background(), name, types.NetworkInspectOptions{}) assert.NilError(t, err) networkip2 := out.IPAM.Config[0].Subnet // Restart daemon with default address pool option d.Restart(t, "--default-address-pool", "base=175.18.0.0/16,size=16", - "--default-address-pool", "base=175.19.0.0/16,size=24") + "--default-address-pool", "base=175.19.0.0/16,size=24", + ) // Create a bridge network name = "saanvi" + t.Name() - network.CreateNoError(t, context.Background(), cli, name, + network.CreateNoError(t, context.Background(), c, name, network.WithDriver("bridge"), ) - out1, err := cli.NetworkInspect(context.Background(), name, types.NetworkInspectOptions{}) + out1, err := c.NetworkInspect(context.Background(), name, types.NetworkInspectOptions{}) assert.NilError(t, err) assert.Check(t, out1.IPAM.Config[0].Subnet != networkip) @@ -177,15 +180,17 @@ func TestDaemonWithBipAndDefaultNetworkPool(t *testing.T) { defaultNetworkBridge := "docker0" d := daemon.New(t) defer d.Stop(t) - d.Start(t, "--bip=172.60.0.1/16", + d.Start(t, + "--bip=172.60.0.1/16", "--default-address-pool", "base=175.30.0.0/16,size=16", - "--default-address-pool", "base=175.33.0.0/16,size=24") + "--default-address-pool", "base=175.33.0.0/16,size=24", + ) + + c := d.NewClientT(t) + defer c.Close() // Verify bridge network's subnet - cli, err := d.NewClient() - assert.Assert(t, err) - defer cli.Close() - out, err := cli.NetworkInspect(context.Background(), "bridge", types.NetworkInspectOptions{}) + out, err := c.NetworkInspect(context.Background(), "bridge", types.NetworkInspectOptions{}) assert.NilError(t, err) // Make sure BIP IP doesn't get override with new default address pool . assert.Equal(t, out.IPAM.Config[0].Subnet, "172.60.0.1/16") @@ -197,8 +202,8 @@ func TestServiceWithPredefinedNetwork(t *testing.T) { defer setupTest(t)() d := swarm.NewSwarm(t, testEnv) defer d.Stop(t) - client := d.NewClientT(t) - defer client.Close() + c := d.NewClientT(t) + defer c.Close() hostName := "host" var instances uint64 = 1 @@ -210,12 +215,12 @@ func TestServiceWithPredefinedNetwork(t *testing.T) { swarm.ServiceWithNetwork(hostName), ) - poll.WaitOn(t, serviceRunningCount(client, serviceID, instances), swarm.ServicePoll) + poll.WaitOn(t, serviceRunningCount(c, serviceID, instances), swarm.ServicePoll) - _, _, err := client.ServiceInspectWithRaw(context.Background(), serviceID, types.ServiceInspectOptions{}) + _, _, err := c.ServiceInspectWithRaw(context.Background(), serviceID, types.ServiceInspectOptions{}) assert.NilError(t, err) - err = client.ServiceRemove(context.Background(), serviceID) + err = c.ServiceRemove(context.Background(), serviceID) assert.NilError(t, err) } @@ -226,10 +231,10 @@ func TestServiceRemoveKeepsIngressNetwork(t *testing.T) { defer setupTest(t)() d := swarm.NewSwarm(t, testEnv) defer d.Stop(t) - client := d.NewClientT(t) - defer client.Close() + c := d.NewClientT(t) + defer c.Close() - poll.WaitOn(t, swarmIngressReady(client), swarm.NetworkPoll) + poll.WaitOn(t, swarmIngressReady(c), swarm.NetworkPoll) var instances uint64 = 1 @@ -247,20 +252,20 @@ func TestServiceRemoveKeepsIngressNetwork(t *testing.T) { }), ) - poll.WaitOn(t, serviceRunningCount(client, serviceID, instances), swarm.ServicePoll) + poll.WaitOn(t, serviceRunningCount(c, serviceID, instances), swarm.ServicePoll) - _, _, err := client.ServiceInspectWithRaw(context.Background(), serviceID, types.ServiceInspectOptions{}) + _, _, err := c.ServiceInspectWithRaw(context.Background(), serviceID, types.ServiceInspectOptions{}) assert.NilError(t, err) - err = client.ServiceRemove(context.Background(), serviceID) + err = c.ServiceRemove(context.Background(), serviceID) assert.NilError(t, err) - poll.WaitOn(t, serviceIsRemoved(client, serviceID), swarm.ServicePoll) - poll.WaitOn(t, noServices(client), swarm.ServicePoll) + poll.WaitOn(t, serviceIsRemoved(c, serviceID), swarm.ServicePoll) + poll.WaitOn(t, noServices(c), swarm.ServicePoll) // Ensure that "ingress" is not removed or corrupted time.Sleep(10 * time.Second) - netInfo, err := client.NetworkInspect(context.Background(), ingressNet, types.NetworkInspectOptions{ + netInfo, err := c.NetworkInspect(context.Background(), ingressNet, types.NetworkInspectOptions{ Verbose: true, Scope: "swarm", }) diff --git a/components/engine/integration/plugin/authz/authz_plugin_test.go b/components/engine/integration/plugin/authz/authz_plugin_test.go index d0f5d8a783..53e30a0f10 100644 --- a/components/engine/integration/plugin/authz/authz_plugin_test.go +++ b/components/engine/integration/plugin/authz/authz_plugin_test.go @@ -87,18 +87,16 @@ func TestAuthZPluginAllowRequest(t *testing.T) { ctrl.resRes.Allow = true d.StartWithBusybox(t, "--authorization-plugin="+testAuthZPlugin) - client, err := d.NewClient() - assert.NilError(t, err) - + c := d.NewClientT(t) ctx := context.Background() // Ensure command successful - cID := container.Run(t, ctx, client) + cID := container.Run(t, ctx, c) assertURIRecorded(t, ctrl.requestsURIs, "/containers/create") assertURIRecorded(t, ctrl.requestsURIs, fmt.Sprintf("/containers/%s/start", cID)) - _, err = client.ServerVersion(ctx) + _, err := c.ServerVersion(ctx) assert.NilError(t, err) assert.Equal(t, 1, ctrl.versionReqCount) assert.Equal(t, 1, ctrl.versionResCount) @@ -126,10 +124,10 @@ func TestAuthZPluginTLS(t *testing.T) { ctrl.reqRes.Allow = true ctrl.resRes.Allow = true - client, err := newTLSAPIClient(testDaemonHTTPSAddr, cacertPath, clientCertPath, clientKeyPath) + c, err := newTLSAPIClient(testDaemonHTTPSAddr, cacertPath, clientCertPath, clientKeyPath) assert.NilError(t, err) - _, err = client.ServerVersion(context.Background()) + _, err = c.ServerVersion(context.Background()) assert.NilError(t, err) assert.Equal(t, "client", ctrl.reqUser) @@ -153,11 +151,10 @@ func TestAuthZPluginDenyRequest(t *testing.T) { ctrl.reqRes.Allow = false ctrl.reqRes.Msg = unauthorizedMessage - client, err := d.NewClient() - assert.NilError(t, err) + c := d.NewClientT(t) // Ensure command is blocked - _, err = client.ServerVersion(context.Background()) + _, err := c.ServerVersion(context.Background()) assert.Assert(t, err != nil) assert.Equal(t, 1, ctrl.versionReqCount) assert.Equal(t, 0, ctrl.versionResCount) @@ -179,10 +176,10 @@ func TestAuthZPluginAPIDenyResponse(t *testing.T) { conn, err := net.DialTimeout(daemonURL.Scheme, daemonURL.Path, time.Second*10) assert.NilError(t, err) - client := httputil.NewClientConn(conn, nil) + c := httputil.NewClientConn(conn, nil) req, err := http.NewRequest("GET", "/version", nil) assert.NilError(t, err) - resp, err := client.Do(req) + resp, err := c.Do(req) assert.NilError(t, err) assert.DeepEqual(t, http.StatusForbidden, resp.StatusCode) @@ -195,11 +192,10 @@ func TestAuthZPluginDenyResponse(t *testing.T) { ctrl.resRes.Allow = false ctrl.resRes.Msg = unauthorizedMessage - client, err := d.NewClient() - assert.NilError(t, err) + c := d.NewClientT(t) // Ensure command is blocked - _, err = client.ServerVersion(context.Background()) + _, err := c.ServerVersion(context.Background()) assert.Assert(t, err != nil) assert.Equal(t, 1, ctrl.versionReqCount) assert.Equal(t, 1, ctrl.versionResCount) @@ -219,20 +215,18 @@ func TestAuthZPluginAllowEventStream(t *testing.T) { ctrl.resRes.Allow = true d.StartWithBusybox(t, "--authorization-plugin="+testAuthZPlugin) - client, err := d.NewClient() - assert.NilError(t, err) - + c := d.NewClientT(t) ctx := context.Background() - startTime := strconv.FormatInt(systemTime(t, client, testEnv).Unix(), 10) - events, errs, cancel := systemEventsSince(client, startTime) + startTime := strconv.FormatInt(systemTime(t, c, testEnv).Unix(), 10) + events, errs, cancel := systemEventsSince(c, startTime) defer cancel() // Create a container and wait for the creation events - cID := container.Run(t, ctx, client) + cID := container.Run(t, ctx, c) for i := 0; i < 100; i++ { - c, err := client.ContainerInspect(ctx, cID) + c, err := c.ContainerInspect(ctx, cID) assert.NilError(t, err) if c.State.Running { break @@ -304,11 +298,10 @@ func TestAuthZPluginErrorResponse(t *testing.T) { ctrl.reqRes.Allow = true ctrl.resRes.Err = errorMessage - client, err := d.NewClient() - assert.NilError(t, err) + c := d.NewClientT(t) // Ensure command is blocked - _, err = client.ServerVersion(context.Background()) + _, err := c.ServerVersion(context.Background()) assert.Assert(t, err != nil) assert.Equal(t, fmt.Sprintf("Error response from daemon: plugin %s failed with error: %s: %s", testAuthZPlugin, authorization.AuthZApiResponse, errorMessage), err.Error()) } @@ -318,11 +311,10 @@ func TestAuthZPluginErrorRequest(t *testing.T) { d.Start(t, "--authorization-plugin="+testAuthZPlugin) ctrl.reqRes.Err = errorMessage - client, err := d.NewClient() - assert.NilError(t, err) + c := d.NewClientT(t) // Ensure command is blocked - _, err = client.ServerVersion(context.Background()) + _, err := c.ServerVersion(context.Background()) assert.Assert(t, err != nil) assert.Equal(t, fmt.Sprintf("Error response from daemon: plugin %s failed with error: %s: %s", testAuthZPlugin, authorization.AuthZApiRequest, errorMessage), err.Error()) } @@ -334,10 +326,9 @@ func TestAuthZPluginEnsureNoDuplicatePluginRegistration(t *testing.T) { ctrl.reqRes.Allow = true ctrl.resRes.Allow = true - client, err := d.NewClient() - assert.NilError(t, err) + c := d.NewClientT(t) - _, err = client.ServerVersion(context.Background()) + _, err := c.ServerVersion(context.Background()) assert.NilError(t, err) // assert plugin is only called once.. @@ -351,9 +342,7 @@ func TestAuthZPluginEnsureLoadImportWorking(t *testing.T) { ctrl.resRes.Allow = true d.StartWithBusybox(t, "--authorization-plugin="+testAuthZPlugin, "--authorization-plugin="+testAuthZPlugin) - client, err := d.NewClient() - assert.NilError(t, err) - + c := d.NewClientT(t) ctx := context.Background() tmp, err := ioutil.TempDir("", "test-authz-load-import") @@ -362,16 +351,16 @@ func TestAuthZPluginEnsureLoadImportWorking(t *testing.T) { savedImagePath := filepath.Join(tmp, "save.tar") - err = imageSave(client, savedImagePath, "busybox") + err = imageSave(c, savedImagePath, "busybox") assert.NilError(t, err) - err = imageLoad(client, savedImagePath) + err = imageLoad(c, savedImagePath) assert.NilError(t, err) exportedImagePath := filepath.Join(tmp, "export.tar") - cID := container.Run(t, ctx, client) + cID := container.Run(t, ctx, c) - responseReader, err := client.ContainerExport(context.Background(), cID) + responseReader, err := c.ContainerExport(context.Background(), cID) assert.NilError(t, err) defer responseReader.Close() file, err := os.Create(exportedImagePath) @@ -380,7 +369,7 @@ func TestAuthZPluginEnsureLoadImportWorking(t *testing.T) { _, err = io.Copy(file, responseReader) assert.NilError(t, err) - err = imageImport(client, exportedImagePath) + err = imageImport(c, exportedImagePath) assert.NilError(t, err) } @@ -406,12 +395,11 @@ func TestAuthzPluginEnsureContainerCopyToFrom(t *testing.T) { written += n } + c := d.NewClientT(t) ctx := context.Background() - client, err := d.NewClient() - assert.Assert(t, err) - cID := container.Run(t, ctx, client) - defer client.ContainerRemove(ctx, cID, types.ContainerRemoveOptions{Force: true}) + cID := container.Run(t, ctx, c) + defer c.ContainerRemove(ctx, cID, types.ContainerRemoveOptions{Force: true}) _, err = f.Seek(0, io.SeekStart) assert.Assert(t, err) @@ -425,10 +413,10 @@ func TestAuthzPluginEnsureContainerCopyToFrom(t *testing.T) { dstDir, preparedArchive, err := archive.PrepareArchiveCopy(srcArchive, srcInfo, archive.CopyInfo{Path: "/test"}) assert.Assert(t, err) - err = client.CopyToContainer(ctx, cID, dstDir, preparedArchive, types.CopyToContainerOptions{}) + err = c.CopyToContainer(ctx, cID, dstDir, preparedArchive, types.CopyToContainerOptions{}) assert.Assert(t, err) - rdr, _, err := client.CopyFromContainer(ctx, cID, "/test") + rdr, _, err := c.CopyFromContainer(ctx, cID, "/test") assert.Assert(t, err) _, err = io.Copy(ioutil.Discard, rdr) assert.Assert(t, err) diff --git a/components/engine/integration/plugin/authz/authz_plugin_v2_test.go b/components/engine/integration/plugin/authz/authz_plugin_v2_test.go index 6b5115146b..6b44108ec4 100644 --- a/components/engine/integration/plugin/authz/authz_plugin_v2_test.go +++ b/components/engine/integration/plugin/authz/authz_plugin_v2_test.go @@ -43,13 +43,11 @@ func TestAuthZPluginV2AllowNonVolumeRequest(t *testing.T) { skip.If(t, os.Getenv("DOCKER_ENGINE_GOARCH") != "amd64") defer setupTestV2(t)() - client, err := d.NewClient() - assert.NilError(t, err) - + c := d.NewClientT(t) ctx := context.Background() // Install authz plugin - err = pluginInstallGrantAllPermissions(client, authzPluginNameWithTag) + err := pluginInstallGrantAllPermissions(c, authzPluginNameWithTag) assert.NilError(t, err) // start the daemon with the plugin and load busybox, --net=none build fails otherwise // because it needs to pull busybox @@ -57,9 +55,9 @@ func TestAuthZPluginV2AllowNonVolumeRequest(t *testing.T) { d.LoadBusybox(t) // Ensure docker run command and accompanying docker ps are successful - cID := container.Run(t, ctx, client) + cID := container.Run(t, ctx, c) - _, err = client.ContainerInspect(ctx, cID) + _, err = c.ContainerInspect(ctx, cID) assert.NilError(t, err) } @@ -67,26 +65,25 @@ func TestAuthZPluginV2Disable(t *testing.T) { skip.If(t, os.Getenv("DOCKER_ENGINE_GOARCH") != "amd64") defer setupTestV2(t)() - client, err := d.NewClient() - assert.NilError(t, err) + c := d.NewClientT(t) // Install authz plugin - err = pluginInstallGrantAllPermissions(client, authzPluginNameWithTag) + err := pluginInstallGrantAllPermissions(c, authzPluginNameWithTag) assert.NilError(t, err) d.Restart(t, "--authorization-plugin="+authzPluginNameWithTag) d.LoadBusybox(t) - _, err = client.VolumeCreate(context.Background(), volumetypes.VolumeCreateBody{Driver: "local"}) + _, err = c.VolumeCreate(context.Background(), volumetypes.VolumeCreateBody{Driver: "local"}) assert.Assert(t, err != nil) assert.Assert(t, strings.Contains(err.Error(), fmt.Sprintf("Error response from daemon: plugin %s failed with error:", authzPluginNameWithTag))) // disable the plugin - err = client.PluginDisable(context.Background(), authzPluginNameWithTag, types.PluginDisableOptions{}) + err = c.PluginDisable(context.Background(), authzPluginNameWithTag, types.PluginDisableOptions{}) assert.NilError(t, err) // now test to see if the docker api works. - _, err = client.VolumeCreate(context.Background(), volumetypes.VolumeCreateBody{Driver: "local"}) + _, err = c.VolumeCreate(context.Background(), volumetypes.VolumeCreateBody{Driver: "local"}) assert.NilError(t, err) } @@ -94,34 +91,33 @@ func TestAuthZPluginV2RejectVolumeRequests(t *testing.T) { skip.If(t, os.Getenv("DOCKER_ENGINE_GOARCH") != "amd64") defer setupTestV2(t)() - client, err := d.NewClient() - assert.NilError(t, err) + c := d.NewClientT(t) // Install authz plugin - err = pluginInstallGrantAllPermissions(client, authzPluginNameWithTag) + err := pluginInstallGrantAllPermissions(c, authzPluginNameWithTag) assert.NilError(t, err) // restart the daemon with the plugin d.Restart(t, "--authorization-plugin="+authzPluginNameWithTag) - _, err = client.VolumeCreate(context.Background(), volumetypes.VolumeCreateBody{Driver: "local"}) + _, err = c.VolumeCreate(context.Background(), volumetypes.VolumeCreateBody{Driver: "local"}) assert.Assert(t, err != nil) assert.Assert(t, strings.Contains(err.Error(), fmt.Sprintf("Error response from daemon: plugin %s failed with error:", authzPluginNameWithTag))) - _, err = client.VolumeList(context.Background(), filters.Args{}) + _, err = c.VolumeList(context.Background(), filters.Args{}) assert.Assert(t, err != nil) assert.Assert(t, strings.Contains(err.Error(), fmt.Sprintf("Error response from daemon: plugin %s failed with error:", authzPluginNameWithTag))) // The plugin will block the command before it can determine the volume does not exist - err = client.VolumeRemove(context.Background(), "test", false) + err = c.VolumeRemove(context.Background(), "test", false) assert.Assert(t, err != nil) assert.Assert(t, strings.Contains(err.Error(), fmt.Sprintf("Error response from daemon: plugin %s failed with error:", authzPluginNameWithTag))) - _, err = client.VolumeInspect(context.Background(), "test") + _, err = c.VolumeInspect(context.Background(), "test") assert.Assert(t, err != nil) assert.Assert(t, strings.Contains(err.Error(), fmt.Sprintf("Error response from daemon: plugin %s failed with error:", authzPluginNameWithTag))) - _, err = client.VolumesPrune(context.Background(), filters.Args{}) + _, err = c.VolumesPrune(context.Background(), filters.Args{}) assert.Assert(t, err != nil) assert.Assert(t, strings.Contains(err.Error(), fmt.Sprintf("Error response from daemon: plugin %s failed with error:", authzPluginNameWithTag))) } @@ -130,11 +126,10 @@ func TestAuthZPluginV2BadManifestFailsDaemonStart(t *testing.T) { skip.If(t, os.Getenv("DOCKER_ENGINE_GOARCH") != "amd64") defer setupTestV2(t)() - client, err := d.NewClient() - assert.NilError(t, err) + c := d.NewClientT(t) // Install authz plugin with bad manifest - err = pluginInstallGrantAllPermissions(client, authzPluginBadManifestName) + err := pluginInstallGrantAllPermissions(c, authzPluginBadManifestName) assert.NilError(t, err) // start the daemon with the plugin, it will error diff --git a/components/engine/integration/plugin/logging/validation_test.go b/components/engine/integration/plugin/logging/validation_test.go index 200eb98759..dfa50132d2 100644 --- a/components/engine/integration/plugin/logging/validation_test.go +++ b/components/engine/integration/plugin/logging/validation_test.go @@ -24,14 +24,13 @@ func TestDaemonStartWithLogOpt(t *testing.T) { d.Start(t, "--iptables=false") defer d.Stop(t) - client, err := d.NewClient() - assert.Check(t, err) + c := d.NewClientT(t) ctx := context.Background() - createPlugin(t, client, "test", "dummy", asLogDriver) - err = client.PluginEnable(ctx, "test", types.PluginEnableOptions{Timeout: 30}) + createPlugin(t, c, "test", "dummy", asLogDriver) + err := c.PluginEnable(ctx, "test", types.PluginEnableOptions{Timeout: 30}) assert.Check(t, err) - defer client.PluginRemove(ctx, "test", types.PluginRemoveOptions{Force: true}) + defer c.PluginRemove(ctx, "test", types.PluginRemoveOptions{Force: true}) d.Stop(t) d.Start(t, "--iptables=false", "--log-driver=test", "--log-opt=foo=bar") diff --git a/components/engine/integration/plugin/volumes/mounts_test.go b/components/engine/integration/plugin/volumes/mounts_test.go index fb4b492c3a..e648ef6f14 100644 --- a/components/engine/integration/plugin/volumes/mounts_test.go +++ b/components/engine/integration/plugin/volumes/mounts_test.go @@ -24,15 +24,14 @@ func TestPluginWithDevMounts(t *testing.T) { d.Start(t, "--iptables=false") defer d.Stop(t) - client, err := d.NewClient() - assert.Assert(t, err) + c := d.NewClientT(t) ctx := context.Background() testDir, err := ioutil.TempDir("", "test-dir") assert.Assert(t, err) defer os.RemoveAll(testDir) - createPlugin(t, client, "test", "dummy", asVolumeDriver, func(c *plugin.Config) { + createPlugin(t, c, "test", "dummy", asVolumeDriver, func(c *plugin.Config) { root := "/" dev := "/dev" mounts := []types.PluginMount{ @@ -46,14 +45,14 @@ func TestPluginWithDevMounts(t *testing.T) { c.IpcHost = true }) - err = client.PluginEnable(ctx, "test", types.PluginEnableOptions{Timeout: 30}) + err = c.PluginEnable(ctx, "test", types.PluginEnableOptions{Timeout: 30}) assert.Assert(t, err) defer func() { - err := client.PluginRemove(ctx, "test", types.PluginRemoveOptions{Force: true}) + err := c.PluginRemove(ctx, "test", types.PluginRemoveOptions{Force: true}) assert.Check(t, err) }() - p, _, err := client.PluginInspectWithRaw(ctx, "test") + p, _, err := c.PluginInspectWithRaw(ctx, "test") assert.Assert(t, err) assert.Assert(t, p.Enabled) } diff --git a/components/engine/integration/system/cgroupdriver_systemd_test.go b/components/engine/integration/system/cgroupdriver_systemd_test.go index b955dd3025..5ab1ff3199 100644 --- a/components/engine/integration/system/cgroupdriver_systemd_test.go +++ b/components/engine/integration/system/cgroupdriver_systemd_test.go @@ -36,23 +36,23 @@ func TestCgroupDriverSystemdMemoryLimit(t *testing.T) { } d := daemon.New(t) - client, err := d.NewClient() - assert.NilError(t, err) + c := d.NewClientT(t) + d.StartWithBusybox(t, "--exec-opt", "native.cgroupdriver=systemd", "--iptables=false") defer d.Stop(t) const mem = 64 * 1024 * 1024 // 64 MB ctx := context.Background() - ctrID := container.Create(t, ctx, client, func(c *container.TestContainerConfig) { - c.HostConfig.Resources.Memory = mem + ctrID := container.Create(t, ctx, c, func(ctr *container.TestContainerConfig) { + ctr.HostConfig.Resources.Memory = mem }) - defer client.ContainerRemove(ctx, ctrID, types.ContainerRemoveOptions{Force: true}) + defer c.ContainerRemove(ctx, ctrID, types.ContainerRemoveOptions{Force: true}) - err = client.ContainerStart(ctx, ctrID, types.ContainerStartOptions{}) + err := c.ContainerStart(ctx, ctrID, types.ContainerStartOptions{}) assert.NilError(t, err) - s, err := client.ContainerInspect(ctx, ctrID) + s, err := c.ContainerInspect(ctx, ctrID) assert.NilError(t, err) assert.Equal(t, s.HostConfig.Memory, mem) } diff --git a/components/engine/integration/system/info_test.go b/components/engine/integration/system/info_test.go index 2051062d74..9743cdf04b 100644 --- a/components/engine/integration/system/info_test.go +++ b/components/engine/integration/system/info_test.go @@ -46,14 +46,12 @@ func TestInfoAPI(t *testing.T) { func TestInfoAPIWarnings(t *testing.T) { skip.If(t, testEnv.DaemonInfo.OSType == "windows", "FIXME") d := daemon.New(t) - - client, err := d.NewClient() - assert.NilError(t, err) + c := d.NewClientT(t) d.StartWithBusybox(t, "-H=0.0.0.0:23756", "-H="+d.Sock()) defer d.Stop(t) - info, err := client.Info(context.Background()) + info, err := c.Info(context.Background()) assert.NilError(t, err) stringsToCheck := []string{ diff --git a/components/engine/internal/test/daemon/daemon.go b/components/engine/internal/test/daemon/daemon.go index 4f56dff9bb..8d8df1c451 100644 --- a/components/engine/internal/test/daemon/daemon.go +++ b/components/engine/internal/test/daemon/daemon.go @@ -561,11 +561,10 @@ func (d *Daemon) LoadBusybox(t assert.TestingT) { assert.NilError(t, err, "failed to download busybox") defer reader.Close() - client, err := d.NewClient() - assert.NilError(t, err, "failed to create client") - defer client.Close() + c := d.NewClientT(t) + defer c.Close() - resp, err := client.ImageLoad(ctx, reader, true) + resp, err := c.ImageLoad(ctx, reader, true) assert.NilError(t, err, "failed to load busybox") defer resp.Body.Close() } @@ -625,7 +624,7 @@ func (d *Daemon) queryRootDir() (string, error) { return "", err } - client := &http.Client{ + c := &http.Client{ Transport: clientConfig.transport, } @@ -637,7 +636,7 @@ func (d *Daemon) queryRootDir() (string, error) { req.URL.Host = clientConfig.addr req.URL.Scheme = clientConfig.scheme - resp, err := client.Do(req) + resp, err := c.Do(req) if err != nil { return "", err } @@ -665,9 +664,8 @@ func (d *Daemon) Info(t assert.TestingT) types.Info { if ht, ok := t.(test.HelperT); ok { ht.Helper() } - apiclient, err := d.NewClient() - assert.NilError(t, err) - info, err := apiclient.Info(context.Background()) + c := d.NewClientT(t) + info, err := c.Info(context.Background()) assert.NilError(t, err) return info } From b202193ebd60ace79b9a9e5fe8bcddd84dfd5f75 Mon Sep 17 00:00:00 2001 From: Sebastiaan van Stijn Date: Thu, 3 Jan 2019 11:49:00 +0100 Subject: [PATCH 05/45] Don't mix t.Parallel() wth environment.ProtectAll() `testEnv` is a package-level variable, so protecting / restoring `testEnv` in parallel will result in "concurrent map write" errors. This patch removes `t.Parallel()` from tests that use this functionality (through `defer setupTest(t)()`). Note that _subtests_ can still be run in parallel, as the defer will be called after all subtests have completed. Signed-off-by: Sebastiaan van Stijn (cherry picked from commit 4d88a95d6730383624570f8730aa203a56caadc3) Signed-off-by: Sebastiaan van Stijn Upstream-commit: 05ecb140c4f3c4c7cbb860baa425104fa6f132ea Component: engine --- components/engine/integration/build/build_test.go | 2 +- components/engine/integration/container/update_linux_test.go | 2 -- 2 files changed, 1 insertion(+), 3 deletions(-) diff --git a/components/engine/integration/build/build_test.go b/components/engine/integration/build/build_test.go index 9b91ee2a38..60980c9f13 100644 --- a/components/engine/integration/build/build_test.go +++ b/components/engine/integration/build/build_test.go @@ -25,7 +25,7 @@ import ( func TestBuildWithRemoveAndForceRemove(t *testing.T) { skip.If(t, testEnv.DaemonInfo.OSType == "windows", "FIXME") defer setupTest(t)() - t.Parallel() + cases := []struct { name string dockerfile string diff --git a/components/engine/integration/container/update_linux_test.go b/components/engine/integration/container/update_linux_test.go index 7ebe64e7e3..eb4446c8f4 100644 --- a/components/engine/integration/container/update_linux_test.go +++ b/components/engine/integration/container/update_linux_test.go @@ -67,8 +67,6 @@ func TestUpdateMemory(t *testing.T) { } func TestUpdateCPUQuota(t *testing.T) { - t.Parallel() - defer setupTest(t)() client := request.NewAPIClient(t) ctx := context.Background() From f3a38b2efd349a4667a56efc7692edc61ef5a043 Mon Sep 17 00:00:00 2001 From: Sebastiaan van Stijn Date: Wed, 2 Jan 2019 14:16:25 +0100 Subject: [PATCH 06/45] Integration: use testenv.APIClient() A client is already created in testenv.New(), so we can just as well use that one, instead of creating a new client. Signed-off-by: Sebastiaan van Stijn (cherry picked from commit 0de62d9bbcb92e9b7c73ee4cdef51c2229878e05) Signed-off-by: Sebastiaan van Stijn Upstream-commit: e438d4799d6e233fe631d332973dcac1d977fef6 Component: engine --- components/engine/integration/build/build_test.go | 3 +-- .../engine/integration/container/create_test.go | 11 +++++------ .../engine/integration/container/diff_test.go | 3 +-- .../engine/integration/container/exec_test.go | 5 ++--- .../engine/integration/container/export_test.go | 3 +-- .../engine/integration/container/health_test.go | 3 +-- .../engine/integration/container/ipcmode_test.go | 5 ++--- .../engine/integration/container/kill_test.go | 12 ++++++------ .../integration/container/links_linux_test.go | 5 ++--- .../engine/integration/container/logs_test.go | 3 +-- .../integration/container/mounts_linux_test.go | 5 ++--- .../engine/integration/container/nat_test.go | 10 ++++++---- .../engine/integration/container/pause_test.go | 6 +++--- .../engine/integration/container/ps_test.go | 3 +-- .../engine/integration/container/remove_test.go | 11 +++++------ .../engine/integration/container/rename_test.go | 15 +++++++-------- .../engine/integration/container/resize_test.go | 7 +++---- .../engine/integration/container/stats_test.go | 3 +-- .../integration/container/stop_linux_test.go | 5 ++--- .../engine/integration/container/stop_test.go | 3 +-- .../integration/container/stop_windows_test.go | 3 +-- .../integration/container/update_linux_test.go | 5 ++--- .../engine/integration/container/update_test.go | 5 ++--- .../engine/integration/image/commit_test.go | 3 +-- .../engine/integration/image/import_test.go | 4 ++-- components/engine/integration/image/list_test.go | 3 +-- .../engine/integration/image/remove_test.go | 3 +-- components/engine/integration/image/tag_test.go | 13 ++++++------- .../engine/integration/network/delete_test.go | 13 +++++-------- .../engine/integration/system/event_test.go | 4 ++-- .../engine/integration/system/info_linux_test.go | 4 ++-- components/engine/integration/system/info_test.go | 4 ++-- .../engine/integration/system/login_test.go | 4 ++-- .../engine/integration/system/version_test.go | 4 ++-- .../engine/integration/volume/volume_test.go | 6 +++--- 35 files changed, 87 insertions(+), 112 deletions(-) diff --git a/components/engine/integration/build/build_test.go b/components/engine/integration/build/build_test.go index 60980c9f13..6a2b1fda9f 100644 --- a/components/engine/integration/build/build_test.go +++ b/components/engine/integration/build/build_test.go @@ -15,7 +15,6 @@ import ( "github.com/docker/docker/api/types/filters" "github.com/docker/docker/api/types/versions" "github.com/docker/docker/internal/test/fakecontext" - "github.com/docker/docker/internal/test/request" "github.com/docker/docker/pkg/jsonmessage" "gotest.tools/assert" is "gotest.tools/assert/cmp" @@ -89,7 +88,7 @@ func TestBuildWithRemoveAndForceRemove(t *testing.T) { }, } - client := request.NewAPIClient(t) + client := testEnv.APIClient() ctx := context.Background() for _, c := range cases { t.Run(c.name, func(t *testing.T) { diff --git a/components/engine/integration/container/create_test.go b/components/engine/integration/container/create_test.go index af65eeb685..35ed37bdc6 100644 --- a/components/engine/integration/container/create_test.go +++ b/components/engine/integration/container/create_test.go @@ -12,7 +12,6 @@ import ( "github.com/docker/docker/api/types/container" "github.com/docker/docker/api/types/network" ctr "github.com/docker/docker/integration/internal/container" - "github.com/docker/docker/internal/test/request" "github.com/docker/docker/oci" "gotest.tools/assert" is "gotest.tools/assert/cmp" @@ -22,7 +21,7 @@ import ( func TestCreateFailsWhenIdentifierDoesNotExist(t *testing.T) { defer setupTest(t)() - client := request.NewAPIClient(t) + client := testEnv.APIClient() testCases := []struct { doc string @@ -63,7 +62,7 @@ func TestCreateFailsWhenIdentifierDoesNotExist(t *testing.T) { func TestCreateWithInvalidEnv(t *testing.T) { defer setupTest(t)() - client := request.NewAPIClient(t) + client := testEnv.APIClient() testCases := []struct { env string @@ -106,7 +105,7 @@ func TestCreateTmpfsMountsTarget(t *testing.T) { skip.If(t, testEnv.DaemonInfo.OSType == "windows") defer setupTest(t)() - client := request.NewAPIClient(t) + client := testEnv.APIClient() testCases := []struct { target string @@ -148,7 +147,7 @@ func TestCreateWithCustomMaskedPaths(t *testing.T) { skip.If(t, testEnv.DaemonInfo.OSType != "linux") defer setupTest(t)() - client := request.NewAPIClient(t) + client := testEnv.APIClient() ctx := context.Background() testCases := []struct { @@ -227,7 +226,7 @@ func TestCreateWithCustomReadonlyPaths(t *testing.T) { skip.If(t, testEnv.DaemonInfo.OSType != "linux") defer setupTest(t)() - client := request.NewAPIClient(t) + client := testEnv.APIClient() ctx := context.Background() testCases := []struct { diff --git a/components/engine/integration/container/diff_test.go b/components/engine/integration/container/diff_test.go index 32ad94b934..ac0bac9af3 100644 --- a/components/engine/integration/container/diff_test.go +++ b/components/engine/integration/container/diff_test.go @@ -7,7 +7,6 @@ import ( containertypes "github.com/docker/docker/api/types/container" "github.com/docker/docker/integration/internal/container" - "github.com/docker/docker/internal/test/request" "github.com/docker/docker/pkg/archive" "gotest.tools/assert" "gotest.tools/poll" @@ -17,7 +16,7 @@ import ( func TestDiff(t *testing.T) { skip.If(t, testEnv.OSType == "windows", "FIXME") defer setupTest(t)() - client := request.NewAPIClient(t) + client := testEnv.APIClient() ctx := context.Background() cID := container.Run(t, ctx, client, container.WithCmd("sh", "-c", `mkdir /foo; echo xyzzy > /foo/bar`)) diff --git a/components/engine/integration/container/exec_test.go b/components/engine/integration/container/exec_test.go index 0c3e01af41..c7603ebd00 100644 --- a/components/engine/integration/container/exec_test.go +++ b/components/engine/integration/container/exec_test.go @@ -10,7 +10,6 @@ import ( "github.com/docker/docker/api/types/strslice" "github.com/docker/docker/api/types/versions" "github.com/docker/docker/integration/internal/container" - "github.com/docker/docker/internal/test/request" "gotest.tools/assert" is "gotest.tools/assert/cmp" "gotest.tools/skip" @@ -22,7 +21,7 @@ func TestExecWithCloseStdin(t *testing.T) { defer setupTest(t)() ctx := context.Background() - client := request.NewAPIClient(t) + client := testEnv.APIClient() // run top with detached mode cID := container.Run(t, ctx, client) @@ -89,7 +88,7 @@ func TestExec(t *testing.T) { skip.If(t, testEnv.OSType == "windows", "FIXME. Probably needs to wait for container to be in running state.") defer setupTest(t)() ctx := context.Background() - client := request.NewAPIClient(t) + client := testEnv.APIClient() cID := container.Run(t, ctx, client, container.WithTty(true), container.WithWorkingDir("/root")) diff --git a/components/engine/integration/container/export_test.go b/components/engine/integration/container/export_test.go index 17a21026cd..5ad8f9226a 100644 --- a/components/engine/integration/container/export_test.go +++ b/components/engine/integration/container/export_test.go @@ -10,7 +10,6 @@ import ( "github.com/docker/docker/api/types/filters" "github.com/docker/docker/integration/internal/container" "github.com/docker/docker/internal/test/daemon" - "github.com/docker/docker/internal/test/request" "github.com/docker/docker/pkg/jsonmessage" "gotest.tools/assert" is "gotest.tools/assert/cmp" @@ -23,7 +22,7 @@ func TestExportContainerAndImportImage(t *testing.T) { skip.If(t, testEnv.DaemonInfo.OSType == "windows") defer setupTest(t)() - client := request.NewAPIClient(t) + client := testEnv.APIClient() ctx := context.Background() cID := container.Run(t, ctx, client, container.WithCmd("true")) diff --git a/components/engine/integration/container/health_test.go b/components/engine/integration/container/health_test.go index b90e86e0c0..f4117f562a 100644 --- a/components/engine/integration/container/health_test.go +++ b/components/engine/integration/container/health_test.go @@ -9,7 +9,6 @@ import ( containertypes "github.com/docker/docker/api/types/container" "github.com/docker/docker/client" "github.com/docker/docker/integration/internal/container" - "github.com/docker/docker/internal/test/request" "gotest.tools/poll" "gotest.tools/skip" ) @@ -20,7 +19,7 @@ func TestHealthCheckWorkdir(t *testing.T) { skip.If(t, testEnv.OSType == "windows", "FIXME") defer setupTest(t)() ctx := context.Background() - client := request.NewAPIClient(t) + client := testEnv.APIClient() cID := container.Run(t, ctx, client, container.WithTty(true), container.WithWorkingDir("/foo"), func(c *container.TestContainerConfig) { c.Config.Healthcheck = &containertypes.HealthConfig{ diff --git a/components/engine/integration/container/ipcmode_test.go b/components/engine/integration/container/ipcmode_test.go index fc079a4dae..46a40ac856 100644 --- a/components/engine/integration/container/ipcmode_test.go +++ b/components/engine/integration/container/ipcmode_test.go @@ -13,7 +13,6 @@ import ( containertypes "github.com/docker/docker/api/types/container" "github.com/docker/docker/integration/internal/container" "github.com/docker/docker/internal/test/daemon" - "github.com/docker/docker/internal/test/request" "gotest.tools/assert" is "gotest.tools/assert/cmp" "gotest.tools/fs" @@ -61,7 +60,7 @@ func testIpcNonePrivateShareable(t *testing.T, mode string, mustBeMounted bool, hostCfg := containertypes.HostConfig{ IpcMode: containertypes.IpcMode(mode), } - client := request.NewAPIClient(t) + client := testEnv.APIClient() ctx := context.Background() resp, err := client.ContainerCreate(ctx, &cfg, &hostCfg, nil, "") @@ -132,7 +131,7 @@ func testIpcContainer(t *testing.T, donorMode string, mustWork bool) { IpcMode: containertypes.IpcMode(donorMode), } ctx := context.Background() - client := request.NewAPIClient(t) + client := testEnv.APIClient() // create and start the "donor" container resp, err := client.ContainerCreate(ctx, &cfg, &hostCfg, nil, "") diff --git a/components/engine/integration/container/kill_test.go b/components/engine/integration/container/kill_test.go index 0b51b5163c..2c73026e18 100644 --- a/components/engine/integration/container/kill_test.go +++ b/components/engine/integration/container/kill_test.go @@ -17,7 +17,7 @@ import ( func TestKillContainerInvalidSignal(t *testing.T) { defer setupTest(t)() - client := request.NewAPIClient(t) + client := testEnv.APIClient() ctx := context.Background() id := container.Run(t, ctx, client) @@ -33,7 +33,7 @@ func TestKillContainerInvalidSignal(t *testing.T) { func TestKillContainer(t *testing.T) { skip.If(t, testEnv.OSType == "windows", "TODO Windows: FIXME. No SIGWINCH") defer setupTest(t)() - client := request.NewAPIClient(t) + client := testEnv.APIClient() testCases := []struct { doc string @@ -73,7 +73,7 @@ func TestKillContainer(t *testing.T) { func TestKillWithStopSignalAndRestartPolicies(t *testing.T) { skip.If(t, testEnv.OSType == "windows", "Windows only supports 1.25 or later") defer setupTest(t)() - client := request.NewAPIClient(t) + client := testEnv.APIClient() testCases := []struct { doc string @@ -114,7 +114,7 @@ func TestKillStoppedContainer(t *testing.T) { skip.If(t, testEnv.OSType == "windows", "Windows only supports 1.25 or later") defer setupTest(t)() ctx := context.Background() - client := request.NewAPIClient(t) + client := testEnv.APIClient() id := container.Create(t, ctx, client) err := client.ContainerKill(ctx, id, "SIGKILL") assert.Assert(t, is.ErrorContains(err, "")) @@ -154,7 +154,7 @@ func TestInspectOomKilledTrue(t *testing.T) { defer setupTest(t)() ctx := context.Background() - client := request.NewAPIClient(t) + client := testEnv.APIClient() cID := container.Run(t, ctx, client, container.WithCmd("sh", "-c", "x=a; while true; do x=$x$x$x$x; done"), func(c *container.TestContainerConfig) { c.HostConfig.Resources.Memory = 32 * 1024 * 1024 @@ -172,7 +172,7 @@ func TestInspectOomKilledFalse(t *testing.T) { defer setupTest(t)() ctx := context.Background() - client := request.NewAPIClient(t) + client := testEnv.APIClient() cID := container.Run(t, ctx, client, container.WithCmd("sh", "-c", "echo hello world")) diff --git a/components/engine/integration/container/links_linux_test.go b/components/engine/integration/container/links_linux_test.go index 775bf6d365..df05fee691 100644 --- a/components/engine/integration/container/links_linux_test.go +++ b/components/engine/integration/container/links_linux_test.go @@ -9,7 +9,6 @@ import ( "github.com/docker/docker/api/types" "github.com/docker/docker/api/types/filters" "github.com/docker/docker/integration/internal/container" - "github.com/docker/docker/internal/test/request" "gotest.tools/assert" is "gotest.tools/assert/cmp" "gotest.tools/skip" @@ -22,7 +21,7 @@ func TestLinksEtcHostsContentMatch(t *testing.T) { skip.If(t, os.IsNotExist(err)) defer setupTest(t)() - client := request.NewAPIClient(t) + client := testEnv.APIClient() ctx := context.Background() cID := container.Run(t, ctx, client, container.WithNetworkMode("host")) @@ -38,7 +37,7 @@ func TestLinksContainerNames(t *testing.T) { skip.If(t, testEnv.DaemonInfo.OSType == "windows") defer setupTest(t)() - client := request.NewAPIClient(t) + client := testEnv.APIClient() ctx := context.Background() containerA := "first_" + t.Name() diff --git a/components/engine/integration/container/logs_test.go b/components/engine/integration/container/logs_test.go index 68fbe13a73..cc932df22d 100644 --- a/components/engine/integration/container/logs_test.go +++ b/components/engine/integration/container/logs_test.go @@ -7,7 +7,6 @@ import ( "github.com/docker/docker/api/types" "github.com/docker/docker/integration/internal/container" - "github.com/docker/docker/internal/test/request" "github.com/docker/docker/pkg/stdcopy" "gotest.tools/assert" "gotest.tools/skip" @@ -19,7 +18,7 @@ func TestLogsFollowTailEmpty(t *testing.T) { // FIXME(vdemeester) fails on a e2e run on linux... skip.If(t, testEnv.IsRemoteDaemon()) defer setupTest(t)() - client := request.NewAPIClient(t) + client := testEnv.APIClient() ctx := context.Background() id := container.Run(t, ctx, client, container.WithCmd("sleep", "100000")) diff --git a/components/engine/integration/container/mounts_linux_test.go b/components/engine/integration/container/mounts_linux_test.go index 8e7e663fd4..940c6ab882 100644 --- a/components/engine/integration/container/mounts_linux_test.go +++ b/components/engine/integration/container/mounts_linux_test.go @@ -11,7 +11,6 @@ import ( "github.com/docker/docker/api/types/mount" "github.com/docker/docker/api/types/network" "github.com/docker/docker/client" - "github.com/docker/docker/internal/test/request" "github.com/docker/docker/pkg/system" "gotest.tools/assert" is "gotest.tools/assert/cmp" @@ -82,9 +81,9 @@ func TestContainerNetworkMountsNoChown(t *testing.T) { func TestMountDaemonRoot(t *testing.T) { skip.If(t, testEnv.DaemonInfo.OSType == "windows" || testEnv.IsRemoteDaemon()) - t.Parallel() - client := request.NewAPIClient(t) + defer setupTest(t)() + client := testEnv.APIClient() ctx := context.Background() info, err := client.Info(ctx) if err != nil { diff --git a/components/engine/integration/container/nat_test.go b/components/engine/integration/container/nat_test.go index caaaf10fde..f920081837 100644 --- a/components/engine/integration/container/nat_test.go +++ b/components/engine/integration/container/nat_test.go @@ -13,7 +13,6 @@ import ( "github.com/docker/docker/api/types" "github.com/docker/docker/integration/internal/container" - "github.com/docker/docker/internal/test/request" "github.com/docker/go-connections/nat" "gotest.tools/assert" is "gotest.tools/assert/cmp" @@ -22,6 +21,7 @@ import ( ) func TestNetworkNat(t *testing.T) { + skip.If(t, testEnv.OSType == "windows", "FIXME") skip.If(t, testEnv.IsRemoteDaemon()) defer setupTest(t)() @@ -58,6 +58,7 @@ func TestNetworkLocalhostTCPNat(t *testing.T) { } func TestNetworkLoopbackNat(t *testing.T) { + skip.If(t, testEnv.OSType == "windows", "FIXME") skip.If(t, testEnv.IsRemoteDaemon()) defer setupTest(t)() @@ -67,7 +68,7 @@ func TestNetworkLoopbackNat(t *testing.T) { endpoint := getExternalAddress(t) - client := request.NewAPIClient(t) + client := testEnv.APIClient() ctx := context.Background() cID := container.Run(t, ctx, client, container.WithCmd("sh", "-c", fmt.Sprintf("stty raw && nc -w 5 %s 8080", endpoint.String())), container.WithTty(true), container.WithNetworkMode("container:"+serverContainerID)) @@ -88,7 +89,8 @@ func TestNetworkLoopbackNat(t *testing.T) { } func startServerContainer(t *testing.T, msg string, port int) string { - client := request.NewAPIClient(t) + t.Helper() + client := testEnv.APIClient() ctx := context.Background() cID := container.Run(t, ctx, client, container.WithName("server-"+t.Name()), container.WithCmd("sh", "-c", fmt.Sprintf("echo %q | nc -lp %d", msg, port)), container.WithExposedPorts(fmt.Sprintf("%d/tcp", port)), func(c *container.TestContainerConfig) { @@ -107,7 +109,7 @@ func startServerContainer(t *testing.T, msg string, port int) string { } func getExternalAddress(t *testing.T) net.IP { - skip.If(t, testEnv.OSType == "windows", "FIXME") + t.Helper() iface, err := net.InterfaceByName("eth0") skip.If(t, err != nil, "Test not running with `make test-integration`. Interface eth0 not found: %s", err) diff --git a/components/engine/integration/container/pause_test.go b/components/engine/integration/container/pause_test.go index 0905b95a83..875841d5ea 100644 --- a/components/engine/integration/container/pause_test.go +++ b/components/engine/integration/container/pause_test.go @@ -22,7 +22,7 @@ func TestPause(t *testing.T) { skip.If(t, testEnv.DaemonInfo.OSType == "windows" && testEnv.DaemonInfo.Isolation == "process") defer setupTest(t)() - client := request.NewAPIClient(t) + client := testEnv.APIClient() ctx := context.Background() cID := container.Run(t, ctx, client) @@ -54,7 +54,7 @@ func TestPauseFailsOnWindowsServerContainers(t *testing.T) { skip.If(t, testEnv.DaemonInfo.OSType != "windows" || testEnv.DaemonInfo.Isolation != "process") defer setupTest(t)() - client := request.NewAPIClient(t) + client := testEnv.APIClient() ctx := context.Background() cID := container.Run(t, ctx, client) @@ -68,7 +68,7 @@ func TestPauseStopPausedContainer(t *testing.T) { skip.If(t, testEnv.DaemonInfo.OSType == "windows") skip.If(t, versions.LessThan(testEnv.DaemonAPIVersion(), "1.31"), "broken in earlier versions") defer setupTest(t)() - client := request.NewAPIClient(t) + client := testEnv.APIClient() ctx := context.Background() cID := container.Run(t, ctx, client) diff --git a/components/engine/integration/container/ps_test.go b/components/engine/integration/container/ps_test.go index 4ae07043ab..93721bc08b 100644 --- a/components/engine/integration/container/ps_test.go +++ b/components/engine/integration/container/ps_test.go @@ -7,14 +7,13 @@ import ( "github.com/docker/docker/api/types" "github.com/docker/docker/api/types/filters" "github.com/docker/docker/integration/internal/container" - "github.com/docker/docker/internal/test/request" "gotest.tools/assert" is "gotest.tools/assert/cmp" ) func TestPsFilter(t *testing.T) { defer setupTest(t)() - client := request.NewAPIClient(t) + client := testEnv.APIClient() ctx := context.Background() prev := container.Create(t, ctx, client) diff --git a/components/engine/integration/container/remove_test.go b/components/engine/integration/container/remove_test.go index 5de13f22ad..e049674781 100644 --- a/components/engine/integration/container/remove_test.go +++ b/components/engine/integration/container/remove_test.go @@ -9,7 +9,6 @@ import ( "github.com/docker/docker/api/types" "github.com/docker/docker/api/types/filters" "github.com/docker/docker/integration/internal/container" - "github.com/docker/docker/internal/test/request" "gotest.tools/assert" is "gotest.tools/assert/cmp" "gotest.tools/fs" @@ -30,7 +29,7 @@ func TestRemoveContainerWithRemovedVolume(t *testing.T) { defer setupTest(t)() ctx := context.Background() - client := request.NewAPIClient(t) + client := testEnv.APIClient() prefix, slash := getPrefixAndSlashFromDaemonPlatform() @@ -56,7 +55,7 @@ func TestRemoveContainerWithRemovedVolume(t *testing.T) { func TestRemoveContainerWithVolume(t *testing.T) { defer setupTest(t)() ctx := context.Background() - client := request.NewAPIClient(t) + client := testEnv.APIClient() prefix, slash := getPrefixAndSlashFromDaemonPlatform() @@ -81,7 +80,7 @@ func TestRemoveContainerWithVolume(t *testing.T) { func TestRemoveContainerRunning(t *testing.T) { defer setupTest(t)() ctx := context.Background() - client := request.NewAPIClient(t) + client := testEnv.APIClient() cID := container.Run(t, ctx, client) @@ -92,7 +91,7 @@ func TestRemoveContainerRunning(t *testing.T) { func TestRemoveContainerForceRemoveRunning(t *testing.T) { defer setupTest(t)() ctx := context.Background() - client := request.NewAPIClient(t) + client := testEnv.APIClient() cID := container.Run(t, ctx, client) @@ -105,7 +104,7 @@ func TestRemoveContainerForceRemoveRunning(t *testing.T) { func TestRemoveInvalidContainer(t *testing.T) { defer setupTest(t)() ctx := context.Background() - client := request.NewAPIClient(t) + client := testEnv.APIClient() err := client.ContainerRemove(ctx, "unknown", types.ContainerRemoveOptions{}) assert.Check(t, is.ErrorContains(err, "No such container")) diff --git a/components/engine/integration/container/rename_test.go b/components/engine/integration/container/rename_test.go index 5c98608a8a..9cb54ef30c 100644 --- a/components/engine/integration/container/rename_test.go +++ b/components/engine/integration/container/rename_test.go @@ -10,7 +10,6 @@ import ( "github.com/docker/docker/api/types/network" "github.com/docker/docker/api/types/versions" "github.com/docker/docker/integration/internal/container" - "github.com/docker/docker/internal/test/request" "github.com/docker/docker/pkg/stringid" "gotest.tools/assert" is "gotest.tools/assert/cmp" @@ -27,7 +26,7 @@ func TestRenameLinkedContainer(t *testing.T) { skip.If(t, testEnv.OSType == "windows", "FIXME") defer setupTest(t)() ctx := context.Background() - client := request.NewAPIClient(t) + client := testEnv.APIClient() aName := "a0" + t.Name() bName := "b0" + t.Name() @@ -52,7 +51,7 @@ func TestRenameLinkedContainer(t *testing.T) { func TestRenameStoppedContainer(t *testing.T) { defer setupTest(t)() ctx := context.Background() - client := request.NewAPIClient(t) + client := testEnv.APIClient() oldName := "first_name" + t.Name() cID := container.Run(t, ctx, client, container.WithName(oldName), container.WithCmd("sh")) @@ -74,7 +73,7 @@ func TestRenameStoppedContainer(t *testing.T) { func TestRenameRunningContainerAndReuse(t *testing.T) { defer setupTest(t)() ctx := context.Background() - client := request.NewAPIClient(t) + client := testEnv.APIClient() oldName := "first_name" + t.Name() cID := container.Run(t, ctx, client, container.WithName(oldName)) @@ -102,7 +101,7 @@ func TestRenameRunningContainerAndReuse(t *testing.T) { func TestRenameInvalidName(t *testing.T) { defer setupTest(t)() ctx := context.Background() - client := request.NewAPIClient(t) + client := testEnv.APIClient() oldName := "first_name" + t.Name() cID := container.Run(t, ctx, client, container.WithName(oldName)) @@ -127,7 +126,7 @@ func TestRenameAnonymousContainer(t *testing.T) { skip.If(t, testEnv.OSType == "windows", "FIXME") defer setupTest(t)() ctx := context.Background() - client := request.NewAPIClient(t) + client := testEnv.APIClient() networkName := "network1" + t.Name() _, err := client.NetworkCreate(ctx, networkName, types.NetworkCreate{}) @@ -173,7 +172,7 @@ func TestRenameAnonymousContainer(t *testing.T) { func TestRenameContainerWithSameName(t *testing.T) { defer setupTest(t)() ctx := context.Background() - client := request.NewAPIClient(t) + client := testEnv.APIClient() oldName := "old" + t.Name() cID := container.Run(t, ctx, client, container.WithName(oldName)) @@ -196,7 +195,7 @@ func TestRenameContainerWithLinkedContainer(t *testing.T) { defer setupTest(t)() ctx := context.Background() - client := request.NewAPIClient(t) + client := testEnv.APIClient() db1Name := "db1" + t.Name() db1ID := container.Run(t, ctx, client, container.WithName(db1Name)) diff --git a/components/engine/integration/container/resize_test.go b/components/engine/integration/container/resize_test.go index 461ef14dfa..8d2ee7d1f3 100644 --- a/components/engine/integration/container/resize_test.go +++ b/components/engine/integration/container/resize_test.go @@ -9,7 +9,6 @@ import ( "github.com/docker/docker/api/types" "github.com/docker/docker/api/types/versions" "github.com/docker/docker/integration/internal/container" - "github.com/docker/docker/internal/test/request" req "github.com/docker/docker/internal/test/request" "gotest.tools/assert" is "gotest.tools/assert/cmp" @@ -20,7 +19,7 @@ import ( func TestResize(t *testing.T) { skip.If(t, testEnv.OSType == "windows", "FIXME") defer setupTest(t)() - client := request.NewAPIClient(t) + client := testEnv.APIClient() ctx := context.Background() cID := container.Run(t, ctx, client) @@ -38,7 +37,7 @@ func TestResizeWithInvalidSize(t *testing.T) { skip.If(t, versions.LessThan(testEnv.DaemonAPIVersion(), "1.32"), "broken in earlier versions") skip.If(t, testEnv.OSType == "windows", "FIXME") defer setupTest(t)() - client := request.NewAPIClient(t) + client := testEnv.APIClient() ctx := context.Background() cID := container.Run(t, ctx, client) @@ -53,7 +52,7 @@ func TestResizeWithInvalidSize(t *testing.T) { func TestResizeWhenContainerNotStarted(t *testing.T) { defer setupTest(t)() - client := request.NewAPIClient(t) + client := testEnv.APIClient() ctx := context.Background() cID := container.Run(t, ctx, client, container.WithCmd("echo")) diff --git a/components/engine/integration/container/stats_test.go b/components/engine/integration/container/stats_test.go index 6493a30573..8472cc9fd9 100644 --- a/components/engine/integration/container/stats_test.go +++ b/components/engine/integration/container/stats_test.go @@ -9,7 +9,6 @@ import ( "github.com/docker/docker/api/types" "github.com/docker/docker/integration/internal/container" - "github.com/docker/docker/internal/test/request" "gotest.tools/assert" is "gotest.tools/assert/cmp" "gotest.tools/poll" @@ -20,7 +19,7 @@ func TestStats(t *testing.T) { skip.If(t, !testEnv.DaemonInfo.MemoryLimit) defer setupTest(t)() - client := request.NewAPIClient(t) + client := testEnv.APIClient() ctx := context.Background() info, err := client.Info(ctx) diff --git a/components/engine/integration/container/stop_linux_test.go b/components/engine/integration/container/stop_linux_test.go index 92db0de41f..c0cc89d1c1 100644 --- a/components/engine/integration/container/stop_linux_test.go +++ b/components/engine/integration/container/stop_linux_test.go @@ -10,7 +10,6 @@ import ( "github.com/docker/docker/api/types" "github.com/docker/docker/integration/internal/container" - "github.com/docker/docker/internal/test/request" "gotest.tools/assert" "gotest.tools/icmd" "gotest.tools/poll" @@ -22,7 +21,7 @@ import ( // waiting is not limited (issue #35311). func TestStopContainerWithTimeout(t *testing.T) { defer setupTest(t)() - client := request.NewAPIClient(t) + client := testEnv.APIClient() ctx := context.Background() testCmd := container.WithCmd("sh", "-c", "sleep 2 && exit 42") @@ -76,7 +75,7 @@ func TestDeleteDevicemapper(t *testing.T) { skip.If(t, testEnv.IsRemoteDaemon, "cannot start daemon on remote test run") defer setupTest(t)() - client := request.NewAPIClient(t) + client := testEnv.APIClient() ctx := context.Background() id := container.Run(t, ctx, client, container.WithName("foo-"+t.Name()), container.WithCmd("echo")) diff --git a/components/engine/integration/container/stop_test.go b/components/engine/integration/container/stop_test.go index 03e76b054d..43d729b7b1 100644 --- a/components/engine/integration/container/stop_test.go +++ b/components/engine/integration/container/stop_test.go @@ -6,14 +6,13 @@ import ( "time" "github.com/docker/docker/integration/internal/container" - "github.com/docker/docker/internal/test/request" "gotest.tools/assert" "gotest.tools/poll" ) func TestStopContainerWithRestartPolicyAlways(t *testing.T) { defer setupTest(t)() - client := request.NewAPIClient(t) + client := testEnv.APIClient() ctx := context.Background() names := []string{"verifyRestart1-" + t.Name(), "verifyRestart2-" + t.Name()} diff --git a/components/engine/integration/container/stop_windows_test.go b/components/engine/integration/container/stop_windows_test.go index 0992f62bc9..2dd5a93ba9 100644 --- a/components/engine/integration/container/stop_windows_test.go +++ b/components/engine/integration/container/stop_windows_test.go @@ -7,7 +7,6 @@ import ( "time" "github.com/docker/docker/integration/internal/container" - "github.com/docker/docker/internal/test/request" "gotest.tools/assert" "gotest.tools/poll" "gotest.tools/skip" @@ -19,7 +18,7 @@ import ( func TestStopContainerWithTimeout(t *testing.T) { skip.If(t, testEnv.OSType == "windows") defer setupTest(t)() - client := request.NewAPIClient(t) + client := testEnv.APIClient() ctx := context.Background() testCmd := container.WithCmd("sh", "-c", "sleep 2 && exit 42") diff --git a/components/engine/integration/container/update_linux_test.go b/components/engine/integration/container/update_linux_test.go index eb4446c8f4..5c37bce768 100644 --- a/components/engine/integration/container/update_linux_test.go +++ b/components/engine/integration/container/update_linux_test.go @@ -9,7 +9,6 @@ import ( containertypes "github.com/docker/docker/api/types/container" "github.com/docker/docker/integration/internal/container" - "github.com/docker/docker/internal/test/request" "gotest.tools/assert" is "gotest.tools/assert/cmp" "gotest.tools/poll" @@ -22,7 +21,7 @@ func TestUpdateMemory(t *testing.T) { skip.If(t, !testEnv.DaemonInfo.SwapLimit) defer setupTest(t)() - client := request.NewAPIClient(t) + client := testEnv.APIClient() ctx := context.Background() cID := container.Run(t, ctx, client, func(c *container.TestContainerConfig) { @@ -68,7 +67,7 @@ func TestUpdateMemory(t *testing.T) { func TestUpdateCPUQuota(t *testing.T) { defer setupTest(t)() - client := request.NewAPIClient(t) + client := testEnv.APIClient() ctx := context.Background() cID := container.Run(t, ctx, client) diff --git a/components/engine/integration/container/update_test.go b/components/engine/integration/container/update_test.go index 0e32184d27..6a136a707e 100644 --- a/components/engine/integration/container/update_test.go +++ b/components/engine/integration/container/update_test.go @@ -7,7 +7,6 @@ import ( containertypes "github.com/docker/docker/api/types/container" "github.com/docker/docker/integration/internal/container" - "github.com/docker/docker/internal/test/request" "gotest.tools/assert" is "gotest.tools/assert/cmp" "gotest.tools/poll" @@ -15,7 +14,7 @@ import ( func TestUpdateRestartPolicy(t *testing.T) { defer setupTest(t)() - client := request.NewAPIClient(t) + client := testEnv.APIClient() ctx := context.Background() cID := container.Run(t, ctx, client, container.WithCmd("sh", "-c", "sleep 1 && false"), func(c *container.TestContainerConfig) { @@ -48,7 +47,7 @@ func TestUpdateRestartPolicy(t *testing.T) { func TestUpdateRestartWithAutoRemove(t *testing.T) { defer setupTest(t)() - client := request.NewAPIClient(t) + client := testEnv.APIClient() ctx := context.Background() cID := container.Run(t, ctx, client, func(c *container.TestContainerConfig) { diff --git a/components/engine/integration/image/commit_test.go b/components/engine/integration/image/commit_test.go index ad3f89ec79..996f3716a9 100644 --- a/components/engine/integration/image/commit_test.go +++ b/components/engine/integration/image/commit_test.go @@ -7,7 +7,6 @@ import ( "github.com/docker/docker/api/types" "github.com/docker/docker/api/types/versions" "github.com/docker/docker/integration/internal/container" - "github.com/docker/docker/internal/test/request" "gotest.tools/assert" is "gotest.tools/assert/cmp" "gotest.tools/skip" @@ -17,7 +16,7 @@ func TestCommitInheritsEnv(t *testing.T) { skip.If(t, versions.LessThan(testEnv.DaemonAPIVersion(), "1.36"), "broken in earlier versions") skip.If(t, testEnv.DaemonInfo.OSType == "windows", "FIXME") defer setupTest(t)() - client := request.NewAPIClient(t) + client := testEnv.APIClient() ctx := context.Background() cID1 := container.Create(t, ctx, client) diff --git a/components/engine/integration/image/import_test.go b/components/engine/integration/image/import_test.go index 2e2fdf7192..3c47099920 100644 --- a/components/engine/integration/image/import_test.go +++ b/components/engine/integration/image/import_test.go @@ -9,7 +9,6 @@ import ( "testing" "github.com/docker/docker/api/types" - "github.com/docker/docker/internal/test/request" "github.com/docker/docker/internal/testutil" "gotest.tools/skip" ) @@ -19,7 +18,8 @@ func TestImportExtremelyLargeImageWorks(t *testing.T) { skip.If(t, runtime.GOARCH == "arm64", "effective test will be time out") skip.If(t, testEnv.OSType == "windows", "TODO enable on windows") - client := request.NewAPIClient(t) + defer setupTest(t)() + client := testEnv.APIClient() // Construct an empty tar archive with about 8GB of junk padding at the // end. This should not cause any crashes (the padding should be mostly diff --git a/components/engine/integration/image/list_test.go b/components/engine/integration/image/list_test.go index 9d6ce16537..5b381d16c6 100644 --- a/components/engine/integration/image/list_test.go +++ b/components/engine/integration/image/list_test.go @@ -6,7 +6,6 @@ import ( "github.com/docker/docker/api/types" "github.com/docker/docker/api/types/filters" - "github.com/docker/docker/internal/test/request" "gotest.tools/assert" is "gotest.tools/assert/cmp" ) @@ -14,7 +13,7 @@ import ( // Regression : #38171 func TestImagesFilterMultiReference(t *testing.T) { defer setupTest(t)() - client := request.NewAPIClient(t) + client := testEnv.APIClient() ctx := context.Background() name := "images_filter_multi_reference" diff --git a/components/engine/integration/image/remove_test.go b/components/engine/integration/image/remove_test.go index 76d73a7135..68ef9aa1ec 100644 --- a/components/engine/integration/image/remove_test.go +++ b/components/engine/integration/image/remove_test.go @@ -6,7 +6,6 @@ import ( "github.com/docker/docker/api/types" "github.com/docker/docker/integration/internal/container" - "github.com/docker/docker/internal/test/request" "gotest.tools/assert" is "gotest.tools/assert/cmp" "gotest.tools/skip" @@ -16,7 +15,7 @@ func TestRemoveImageOrphaning(t *testing.T) { skip.If(t, testEnv.DaemonInfo.OSType == "windows", "FIXME") defer setupTest(t)() ctx := context.Background() - client := request.NewAPIClient(t) + client := testEnv.APIClient() img := "test-container-orphaning" diff --git a/components/engine/integration/image/tag_test.go b/components/engine/integration/image/tag_test.go index f3eb9eb7df..d237c48050 100644 --- a/components/engine/integration/image/tag_test.go +++ b/components/engine/integration/image/tag_test.go @@ -5,7 +5,6 @@ import ( "fmt" "testing" - "github.com/docker/docker/internal/test/request" "github.com/docker/docker/internal/testutil" "gotest.tools/assert" is "gotest.tools/assert/cmp" @@ -15,7 +14,7 @@ import ( // tagging a named image in a new unprefixed repo should work func TestTagUnprefixedRepoByNameOrName(t *testing.T) { defer setupTest(t)() - client := request.NewAPIClient(t) + client := testEnv.APIClient() ctx := context.Background() // By name @@ -33,7 +32,7 @@ func TestTagUnprefixedRepoByNameOrName(t *testing.T) { // TODO (yongtang): Migrate to unit tests func TestTagInvalidReference(t *testing.T) { defer setupTest(t)() - client := request.NewAPIClient(t) + client := testEnv.APIClient() ctx := context.Background() invalidRepos := []string{"fo$z$", "Foo@3cc", "Foo$3", "Foo*3", "Fo^3", "Foo!3", "F)xcz(", "fo%asd", "FOO/bar"} @@ -72,7 +71,7 @@ func TestTagInvalidReference(t *testing.T) { // ensure we allow the use of valid tags func TestTagValidPrefixedRepo(t *testing.T) { defer setupTest(t)() - client := request.NewAPIClient(t) + client := testEnv.APIClient() ctx := context.Background() validRepos := []string{"fooo/bar", "fooaa/test", "foooo:t", "HOSTNAME.DOMAIN.COM:443/foo/bar"} @@ -86,7 +85,7 @@ func TestTagValidPrefixedRepo(t *testing.T) { // tag an image with an existed tag name without -f option should work func TestTagExistedNameWithoutForce(t *testing.T) { defer setupTest(t)() - client := request.NewAPIClient(t) + client := testEnv.APIClient() ctx := context.Background() err := client.ImageTag(ctx, "busybox:latest", "busybox:test") @@ -98,7 +97,7 @@ func TestTagExistedNameWithoutForce(t *testing.T) { func TestTagOfficialNames(t *testing.T) { skip.If(t, testEnv.OSType == "windows") defer setupTest(t)() - client := request.NewAPIClient(t) + client := testEnv.APIClient() ctx := context.Background() names := []string{ @@ -128,7 +127,7 @@ func TestTagOfficialNames(t *testing.T) { // ensure tags can not match digests func TestTagMatchesDigest(t *testing.T) { defer setupTest(t)() - client := request.NewAPIClient(t) + client := testEnv.APIClient() ctx := context.Background() digest := "busybox@sha256:abcdef76720241213f5303bda7704ec4c2ef75613173910a56fb1b6e20251507" diff --git a/components/engine/integration/network/delete_test.go b/components/engine/integration/network/delete_test.go index f9ab91986d..5989eba169 100644 --- a/components/engine/integration/network/delete_test.go +++ b/components/engine/integration/network/delete_test.go @@ -6,8 +6,8 @@ import ( "github.com/docker/docker/api/types" "github.com/docker/docker/api/types/versions" + dclient "github.com/docker/docker/client" "github.com/docker/docker/integration/internal/network" - "github.com/docker/docker/internal/test/request" "gotest.tools/assert" is "gotest.tools/assert/cmp" "gotest.tools/skip" @@ -27,10 +27,7 @@ func containsNetwork(nws []types.NetworkResource, networkID string) bool { // first network's ID as name. // // After successful creation, properties of all three networks is returned -func createAmbiguousNetworks(t *testing.T) (string, string, string) { - client := request.NewAPIClient(t) - ctx := context.Background() - +func createAmbiguousNetworks(t *testing.T, ctx context.Context, client dclient.APIClient) (string, string, string) { // nolint: golint testNet := network.CreateNoError(t, ctx, client, "testNet") idPrefixNet := network.CreateNoError(t, ctx, client, testNet[:12]) fullIDNet := network.CreateNoError(t, ctx, client, testNet) @@ -48,7 +45,7 @@ func createAmbiguousNetworks(t *testing.T) (string, string, string) { func TestNetworkCreateDelete(t *testing.T) { skip.If(t, testEnv.DaemonInfo.OSType != "linux") defer setupTest(t)() - client := request.NewAPIClient(t) + client := testEnv.APIClient() ctx := context.Background() netName := "testnetwork_" + t.Name() @@ -71,9 +68,9 @@ func TestDockerNetworkDeletePreferID(t *testing.T) { skip.If(t, testEnv.OSType == "windows", "FIXME. Windows doesn't run DinD and uses networks shared between control daemon and daemon under test") defer setupTest(t)() - client := request.NewAPIClient(t) + client := testEnv.APIClient() ctx := context.Background() - testNet, idPrefixNet, fullIDNet := createAmbiguousNetworks(t) + testNet, idPrefixNet, fullIDNet := createAmbiguousNetworks(t, ctx, client) // Delete the network using a prefix of the first network's ID as name. // This should the network name with the id-prefix, not the original network. diff --git a/components/engine/integration/system/event_test.go b/components/engine/integration/system/event_test.go index 60d10407f6..4d47c79440 100644 --- a/components/engine/integration/system/event_test.go +++ b/components/engine/integration/system/event_test.go @@ -28,7 +28,7 @@ func TestEventsExecDie(t *testing.T) { skip.If(t, testEnv.OSType == "windows", "FIXME. Suspect may need to wait until container is running before exec") defer setupTest(t)() ctx := context.Background() - client := request.NewAPIClient(t) + client := testEnv.APIClient() cID := container.Run(t, ctx, client) @@ -78,7 +78,7 @@ func TestEventsBackwardsCompatible(t *testing.T) { skip.If(t, testEnv.OSType == "windows", "Windows doesn't support back-compat messages") defer setupTest(t)() ctx := context.Background() - client := request.NewAPIClient(t) + client := testEnv.APIClient() since := request.DaemonTime(ctx, t, client, testEnv) ts := strconv.FormatInt(since.Unix(), 10) diff --git a/components/engine/integration/system/info_linux_test.go b/components/engine/integration/system/info_linux_test.go index 50fa9874b4..e7e6145f3f 100644 --- a/components/engine/integration/system/info_linux_test.go +++ b/components/engine/integration/system/info_linux_test.go @@ -7,14 +7,14 @@ import ( "net/http" "testing" - "github.com/docker/docker/internal/test/request" req "github.com/docker/docker/internal/test/request" "gotest.tools/assert" is "gotest.tools/assert/cmp" ) func TestInfoBinaryCommits(t *testing.T) { - client := request.NewAPIClient(t) + defer setupTest(t)() + client := testEnv.APIClient() info, err := client.Info(context.Background()) assert.NilError(t, err) diff --git a/components/engine/integration/system/info_test.go b/components/engine/integration/system/info_test.go index 9743cdf04b..80058523a3 100644 --- a/components/engine/integration/system/info_test.go +++ b/components/engine/integration/system/info_test.go @@ -6,14 +6,14 @@ import ( "testing" "github.com/docker/docker/internal/test/daemon" - "github.com/docker/docker/internal/test/request" "gotest.tools/assert" is "gotest.tools/assert/cmp" "gotest.tools/skip" ) func TestInfoAPI(t *testing.T) { - client := request.NewAPIClient(t) + defer setupTest(t)() + client := testEnv.APIClient() info, err := client.Info(context.Background()) assert.NilError(t, err) diff --git a/components/engine/integration/system/login_test.go b/components/engine/integration/system/login_test.go index ad1a8756dc..819b7ee7f9 100644 --- a/components/engine/integration/system/login_test.go +++ b/components/engine/integration/system/login_test.go @@ -6,7 +6,6 @@ import ( "github.com/docker/docker/api/types" "github.com/docker/docker/integration/internal/requirement" - "github.com/docker/docker/internal/test/request" "gotest.tools/assert" is "gotest.tools/assert/cmp" "gotest.tools/skip" @@ -16,7 +15,8 @@ import ( func TestLoginFailsWithBadCredentials(t *testing.T) { skip.If(t, !requirement.HasHubConnectivity(t)) - client := request.NewAPIClient(t) + defer setupTest(t)() + client := testEnv.APIClient() config := types.AuthConfig{ Username: "no-user", diff --git a/components/engine/integration/system/version_test.go b/components/engine/integration/system/version_test.go index 8904c09b26..2f8d06bb38 100644 --- a/components/engine/integration/system/version_test.go +++ b/components/engine/integration/system/version_test.go @@ -4,13 +4,13 @@ import ( "context" "testing" - "github.com/docker/docker/internal/test/request" "gotest.tools/assert" is "gotest.tools/assert/cmp" ) func TestVersion(t *testing.T) { - client := request.NewAPIClient(t) + defer setupTest(t)() + client := testEnv.APIClient() version, err := client.ServerVersion(context.Background()) assert.NilError(t, err) diff --git a/components/engine/integration/volume/volume_test.go b/components/engine/integration/volume/volume_test.go index f29e3669d1..4ee109e675 100644 --- a/components/engine/integration/volume/volume_test.go +++ b/components/engine/integration/volume/volume_test.go @@ -22,7 +22,7 @@ import ( func TestVolumesCreateAndList(t *testing.T) { skip.If(t, testEnv.IsRemoteDaemon, "cannot run daemon when remote daemon") defer setupTest(t)() - client := request.NewAPIClient(t) + client := testEnv.APIClient() ctx := context.Background() name := t.Name() @@ -52,7 +52,7 @@ func TestVolumesCreateAndList(t *testing.T) { func TestVolumesRemove(t *testing.T) { skip.If(t, testEnv.OSType == "windows", "FIXME") defer setupTest(t)() - client := request.NewAPIClient(t) + client := testEnv.APIClient() ctx := context.Background() prefix, slash := getPrefixAndSlashFromDaemonPlatform() @@ -78,7 +78,7 @@ func TestVolumesRemove(t *testing.T) { func TestVolumesInspect(t *testing.T) { skip.If(t, testEnv.IsRemoteDaemon, "cannot run daemon when remote daemon") defer setupTest(t)() - client := request.NewAPIClient(t) + client := testEnv.APIClient() ctx := context.Background() now := time.Now() From b432f71813d38cc0463724d6ca11fd39f6fa6fd9 Mon Sep 17 00:00:00 2001 From: Sebastiaan van Stijn Date: Thu, 3 Jan 2019 12:19:15 +0100 Subject: [PATCH 07/45] Improve consistency in "skip" Signed-off-by: Sebastiaan van Stijn (cherry picked from commit a3948d17d330315c832112bfecfc15d5e19511b1) Signed-off-by: Sebastiaan van Stijn Upstream-commit: cdedf9ae3ef586a466bc34b9003def2a19c4b42c Component: engine --- .../engine/integration/container/daemon_linux_test.go | 1 - components/engine/integration/container/export_test.go | 2 +- .../engine/integration/container/links_linux_test.go | 2 +- components/engine/integration/container/logs_test.go | 2 +- components/engine/integration/container/nat_test.go | 6 +++--- components/engine/integration/container/remove_test.go | 2 +- components/engine/integration/container/rename_test.go | 2 +- .../engine/integration/network/ipvlan/ipvlan_test.go | 4 ++-- .../engine/integration/network/macvlan/macvlan_test.go | 4 ++-- components/engine/integration/network/service_test.go | 10 +++++----- .../integration/plugin/logging/logging_linux_test.go | 2 +- components/engine/integration/service/inspect_test.go | 2 +- 12 files changed, 19 insertions(+), 20 deletions(-) diff --git a/components/engine/integration/container/daemon_linux_test.go b/components/engine/integration/container/daemon_linux_test.go index 36866a3087..a676410690 100644 --- a/components/engine/integration/container/daemon_linux_test.go +++ b/components/engine/integration/container/daemon_linux_test.go @@ -29,7 +29,6 @@ import ( func TestContainerStartOnDaemonRestart(t *testing.T) { skip.If(t, testEnv.IsRemoteDaemon, "cannot start daemon on remote test run") skip.If(t, testEnv.DaemonInfo.OSType == "windows") - skip.If(t, testEnv.IsRemoteDaemon(), "cannot start daemon on remote test run") t.Parallel() d := daemon.New(t) diff --git a/components/engine/integration/container/export_test.go b/components/engine/integration/container/export_test.go index 5ad8f9226a..6727a67edc 100644 --- a/components/engine/integration/container/export_test.go +++ b/components/engine/integration/container/export_test.go @@ -58,7 +58,7 @@ func TestExportContainerAndImportImage(t *testing.T) { // condition, daemon restart is needed after container creation. func TestExportContainerAfterDaemonRestart(t *testing.T) { skip.If(t, testEnv.DaemonInfo.OSType == "windows") - skip.If(t, testEnv.IsRemoteDaemon()) + skip.If(t, testEnv.IsRemoteDaemon) d := daemon.New(t) c := d.NewClientT(t) diff --git a/components/engine/integration/container/links_linux_test.go b/components/engine/integration/container/links_linux_test.go index df05fee691..9a3c9d2719 100644 --- a/components/engine/integration/container/links_linux_test.go +++ b/components/engine/integration/container/links_linux_test.go @@ -15,7 +15,7 @@ import ( ) func TestLinksEtcHostsContentMatch(t *testing.T) { - skip.If(t, testEnv.IsRemoteDaemon()) + skip.If(t, testEnv.IsRemoteDaemon) hosts, err := ioutil.ReadFile("/etc/hosts") skip.If(t, os.IsNotExist(err)) diff --git a/components/engine/integration/container/logs_test.go b/components/engine/integration/container/logs_test.go index cc932df22d..0a3e83113a 100644 --- a/components/engine/integration/container/logs_test.go +++ b/components/engine/integration/container/logs_test.go @@ -16,7 +16,7 @@ import ( // Makes sure that when following we don't get an EOF error when there are no logs func TestLogsFollowTailEmpty(t *testing.T) { // FIXME(vdemeester) fails on a e2e run on linux... - skip.If(t, testEnv.IsRemoteDaemon()) + skip.If(t, testEnv.IsRemoteDaemon) defer setupTest(t)() client := testEnv.APIClient() ctx := context.Background() diff --git a/components/engine/integration/container/nat_test.go b/components/engine/integration/container/nat_test.go index f920081837..3e8144615c 100644 --- a/components/engine/integration/container/nat_test.go +++ b/components/engine/integration/container/nat_test.go @@ -22,7 +22,7 @@ import ( func TestNetworkNat(t *testing.T) { skip.If(t, testEnv.OSType == "windows", "FIXME") - skip.If(t, testEnv.IsRemoteDaemon()) + skip.If(t, testEnv.IsRemoteDaemon) defer setupTest(t)() @@ -41,7 +41,7 @@ func TestNetworkNat(t *testing.T) { func TestNetworkLocalhostTCPNat(t *testing.T) { skip.If(t, testEnv.DaemonInfo.OSType == "windows", "FIXME") - skip.If(t, testEnv.IsRemoteDaemon()) + skip.If(t, testEnv.IsRemoteDaemon) defer setupTest(t)() @@ -59,7 +59,7 @@ func TestNetworkLocalhostTCPNat(t *testing.T) { func TestNetworkLoopbackNat(t *testing.T) { skip.If(t, testEnv.OSType == "windows", "FIXME") - skip.If(t, testEnv.IsRemoteDaemon()) + skip.If(t, testEnv.IsRemoteDaemon) defer setupTest(t)() diff --git a/components/engine/integration/container/remove_test.go b/components/engine/integration/container/remove_test.go index e049674781..027c92001e 100644 --- a/components/engine/integration/container/remove_test.go +++ b/components/engine/integration/container/remove_test.go @@ -25,7 +25,7 @@ func getPrefixAndSlashFromDaemonPlatform() (prefix, slash string) { // Test case for #5244: `docker rm` fails if bind dir doesn't exist anymore func TestRemoveContainerWithRemovedVolume(t *testing.T) { - skip.If(t, testEnv.IsRemoteDaemon()) + skip.If(t, testEnv.IsRemoteDaemon) defer setupTest(t)() ctx := context.Background() diff --git a/components/engine/integration/container/rename_test.go b/components/engine/integration/container/rename_test.go index 9cb54ef30c..25474a7cb9 100644 --- a/components/engine/integration/container/rename_test.go +++ b/components/engine/integration/container/rename_test.go @@ -190,7 +190,7 @@ func TestRenameContainerWithSameName(t *testing.T) { // of the linked container should be updated so that the other // container could still reference to the container that is renamed. func TestRenameContainerWithLinkedContainer(t *testing.T) { - skip.If(t, testEnv.IsRemoteDaemon()) + skip.If(t, testEnv.IsRemoteDaemon) skip.If(t, testEnv.OSType == "windows", "FIXME") defer setupTest(t)() diff --git a/components/engine/integration/network/ipvlan/ipvlan_test.go b/components/engine/integration/network/ipvlan/ipvlan_test.go index b2571cfaa4..9b98ace41d 100644 --- a/components/engine/integration/network/ipvlan/ipvlan_test.go +++ b/components/engine/integration/network/ipvlan/ipvlan_test.go @@ -20,7 +20,7 @@ import ( func TestDockerNetworkIpvlanPersistance(t *testing.T) { // verify the driver automatically provisions the 802.1q link (di-dummy0.70) skip.If(t, testEnv.DaemonInfo.OSType == "windows") - skip.If(t, testEnv.IsRemoteDaemon()) + skip.If(t, testEnv.IsRemoteDaemon) skip.If(t, !ipvlanKernelSupport(), "Kernel doesn't support ipvlan") d := daemon.New(t, daemon.WithExperimental) @@ -48,7 +48,7 @@ func TestDockerNetworkIpvlanPersistance(t *testing.T) { func TestDockerNetworkIpvlan(t *testing.T) { skip.If(t, testEnv.DaemonInfo.OSType == "windows") - skip.If(t, testEnv.IsRemoteDaemon()) + skip.If(t, testEnv.IsRemoteDaemon) skip.If(t, !ipvlanKernelSupport(), "Kernel doesn't support ipvlan") for _, tc := range []struct { diff --git a/components/engine/integration/network/macvlan/macvlan_test.go b/components/engine/integration/network/macvlan/macvlan_test.go index 04b99ca1df..164dc4d0db 100644 --- a/components/engine/integration/network/macvlan/macvlan_test.go +++ b/components/engine/integration/network/macvlan/macvlan_test.go @@ -19,7 +19,7 @@ import ( func TestDockerNetworkMacvlanPersistance(t *testing.T) { // verify the driver automatically provisions the 802.1q link (dm-dummy0.60) - skip.If(t, testEnv.IsRemoteDaemon()) + skip.If(t, testEnv.IsRemoteDaemon) skip.If(t, !macvlanKernelSupport(), "Kernel doesn't support macvlan") d := daemon.New(t) @@ -42,7 +42,7 @@ func TestDockerNetworkMacvlanPersistance(t *testing.T) { } func TestDockerNetworkMacvlan(t *testing.T) { - skip.If(t, testEnv.IsRemoteDaemon()) + skip.If(t, testEnv.IsRemoteDaemon) skip.If(t, !macvlanKernelSupport(), "Kernel doesn't support macvlan") for _, tc := range []struct { diff --git a/components/engine/integration/network/service_test.go b/components/engine/integration/network/service_test.go index 3ea0890678..c418b2eee5 100644 --- a/components/engine/integration/network/service_test.go +++ b/components/engine/integration/network/service_test.go @@ -27,7 +27,7 @@ func delInterface(t *testing.T, ifName string) { func TestDaemonRestartWithLiveRestore(t *testing.T) { skip.If(t, testEnv.OSType == "windows") - skip.If(t, testEnv.IsRemoteDaemon()) + skip.If(t, testEnv.IsRemoteDaemon) skip.If(t, versions.LessThan(testEnv.DaemonAPIVersion(), "1.38"), "skip test from new feature") d := daemon.New(t) defer d.Stop(t) @@ -50,7 +50,7 @@ func TestDaemonRestartWithLiveRestore(t *testing.T) { func TestDaemonDefaultNetworkPools(t *testing.T) { skip.If(t, testEnv.OSType == "windows") // Remove docker0 bridge and the start daemon defining the predefined address pools - skip.If(t, testEnv.IsRemoteDaemon()) + skip.If(t, testEnv.IsRemoteDaemon) skip.If(t, versions.LessThan(testEnv.DaemonAPIVersion(), "1.38"), "skip test from new feature") defaultNetworkBridge := "docker0" delInterface(t, defaultNetworkBridge) @@ -92,7 +92,7 @@ func TestDaemonDefaultNetworkPools(t *testing.T) { func TestDaemonRestartWithExistingNetwork(t *testing.T) { skip.If(t, testEnv.OSType == "windows") - skip.If(t, testEnv.IsRemoteDaemon()) + skip.If(t, testEnv.IsRemoteDaemon) skip.If(t, versions.LessThan(testEnv.DaemonAPIVersion(), "1.38"), "skip test from new feature") defaultNetworkBridge := "docker0" d := daemon.New(t) @@ -125,7 +125,7 @@ func TestDaemonRestartWithExistingNetwork(t *testing.T) { func TestDaemonRestartWithExistingNetworkWithDefaultPoolRange(t *testing.T) { skip.If(t, testEnv.OSType == "windows") - skip.If(t, testEnv.IsRemoteDaemon()) + skip.If(t, testEnv.IsRemoteDaemon) skip.If(t, versions.LessThan(testEnv.DaemonAPIVersion(), "1.38"), "skip test from new feature") defaultNetworkBridge := "docker0" d := daemon.New(t) @@ -175,7 +175,7 @@ func TestDaemonRestartWithExistingNetworkWithDefaultPoolRange(t *testing.T) { func TestDaemonWithBipAndDefaultNetworkPool(t *testing.T) { skip.If(t, testEnv.OSType == "windows") - skip.If(t, testEnv.IsRemoteDaemon()) + skip.If(t, testEnv.IsRemoteDaemon) skip.If(t, versions.LessThan(testEnv.DaemonAPIVersion(), "1.38"), "skip test from new feature") defaultNetworkBridge := "docker0" d := daemon.New(t) diff --git a/components/engine/integration/plugin/logging/logging_linux_test.go b/components/engine/integration/plugin/logging/logging_linux_test.go index 3921fa6e69..eadc524503 100644 --- a/components/engine/integration/plugin/logging/logging_linux_test.go +++ b/components/engine/integration/plugin/logging/logging_linux_test.go @@ -16,7 +16,7 @@ import ( ) func TestContinueAfterPluginCrash(t *testing.T) { - skip.If(t, testEnv.IsRemoteDaemon(), "test requires daemon on the same host") + skip.If(t, testEnv.IsRemoteDaemon, "test requires daemon on the same host") t.Parallel() d := daemon.New(t) diff --git a/components/engine/integration/service/inspect_test.go b/components/engine/integration/service/inspect_test.go index 33e90938bd..c79751f930 100644 --- a/components/engine/integration/service/inspect_test.go +++ b/components/engine/integration/service/inspect_test.go @@ -19,7 +19,7 @@ import ( ) func TestInspect(t *testing.T) { - skip.If(t, testEnv.IsRemoteDaemon()) + skip.If(t, testEnv.IsRemoteDaemon) skip.If(t, testEnv.DaemonInfo.OSType == "windows") defer setupTest(t)() d := swarm.NewSwarm(t, testEnv) From ee07b18c8eafe7fa8f58ac7d687f500cc0c735ff Mon Sep 17 00:00:00 2001 From: Sebastiaan van Stijn Date: Thu, 3 Jan 2019 12:25:11 +0100 Subject: [PATCH 08/45] Only build IPCmode tests on Linux These tests can only be run on a local Linux daemon, so there's no need to build them on Windows Signed-off-by: Sebastiaan van Stijn (cherry picked from commit 84224935ea78d93e21a21c0e1e0aa3e83a5c7853) Signed-off-by: Sebastiaan van Stijn Upstream-commit: b4c0a7efd46d5fb13df7214aface1f291ba356d2 Component: engine --- .../container/{ipcmode_test.go => ipcmode_linux_test.go} | 0 1 file changed, 0 insertions(+), 0 deletions(-) rename components/engine/integration/container/{ipcmode_test.go => ipcmode_linux_test.go} (100%) diff --git a/components/engine/integration/container/ipcmode_test.go b/components/engine/integration/container/ipcmode_linux_test.go similarity index 100% rename from components/engine/integration/container/ipcmode_test.go rename to components/engine/integration/container/ipcmode_linux_test.go From 37d514b106f4aa528bf89038d7b82d3a2825076d Mon Sep 17 00:00:00 2001 From: Sebastiaan van Stijn Date: Thu, 3 Jan 2019 12:32:05 +0100 Subject: [PATCH 09/45] Simplify skip checks These tests are run on a local Linux daemon only, so no need to do a platform-check. Signed-off-by: Sebastiaan van Stijn (cherry picked from commit 69c0b7e47682a2a7a850122a9a2f711259fbb25a) Signed-off-by: Sebastiaan van Stijn Upstream-commit: bb6db57acc8a63f7f85fafe4be0cfe7fa929e3a1 Component: engine --- .../container/ipcmode_linux_test.go | 19 ++++++++++--------- .../container/mounts_linux_test.go | 4 ++-- 2 files changed, 12 insertions(+), 11 deletions(-) diff --git a/components/engine/integration/container/ipcmode_linux_test.go b/components/engine/integration/container/ipcmode_linux_test.go index 46a40ac856..49634ca732 100644 --- a/components/engine/integration/container/ipcmode_linux_test.go +++ b/components/engine/integration/container/ipcmode_linux_test.go @@ -92,7 +92,7 @@ func testIpcNonePrivateShareable(t *testing.T, mode string, mustBeMounted bool, // (--ipc none) works as expected. It makes sure there is no // /dev/shm mount inside the container. func TestIpcModeNone(t *testing.T) { - skip.If(t, testEnv.DaemonInfo.OSType != "linux" || testEnv.IsRemoteDaemon()) + skip.If(t, testEnv.IsRemoteDaemon) testIpcNonePrivateShareable(t, "none", false, false) } @@ -102,7 +102,7 @@ func TestIpcModeNone(t *testing.T) { // of /dev/shm mount from the container, and makes sure there is no // such pair on the host. func TestIpcModePrivate(t *testing.T) { - skip.If(t, testEnv.DaemonInfo.OSType != "linux" || testEnv.IsRemoteDaemon()) + skip.If(t, testEnv.IsRemoteDaemon) testIpcNonePrivateShareable(t, "private", true, false) } @@ -112,7 +112,7 @@ func TestIpcModePrivate(t *testing.T) { // of /dev/shm mount from the container, and makes sure such pair // also exists on the host. func TestIpcModeShareable(t *testing.T) { - skip.If(t, testEnv.DaemonInfo.OSType != "linux" || testEnv.IsRemoteDaemon()) + skip.If(t, testEnv.IsRemoteDaemon) testIpcNonePrivateShareable(t, "shareable", true, true) } @@ -175,7 +175,7 @@ func testIpcContainer(t *testing.T, donorMode string, mustWork bool) { // 1) a container created with --ipc container:ID can use IPC of another shareable container. // 2) a container created with --ipc container:ID can NOT use IPC of another private container. func TestAPIIpcModeShareableAndContainer(t *testing.T) { - skip.If(t, testEnv.DaemonInfo.OSType != "linux") + skip.If(t, testEnv.IsRemoteDaemon) testIpcContainer(t, "shareable", true) @@ -186,7 +186,8 @@ func TestAPIIpcModeShareableAndContainer(t *testing.T) { * can use IPC of the host system. */ func TestAPIIpcModeHost(t *testing.T) { - skip.If(t, testEnv.DaemonInfo.OSType != "linux" || testEnv.IsRemoteDaemon() || testEnv.IsUserNamespace()) + skip.If(t, testEnv.IsRemoteDaemon) + skip.If(t, testEnv.IsUserNamespace) cfg := containertypes.Config{ Image: "busybox", @@ -257,14 +258,14 @@ func testDaemonIpcPrivateShareable(t *testing.T, mustBeShared bool, arg ...strin // TestDaemonIpcModeShareable checks that --default-ipc-mode shareable works as intended. func TestDaemonIpcModeShareable(t *testing.T) { - skip.If(t, testEnv.DaemonInfo.OSType != "linux" || testEnv.IsRemoteDaemon()) + skip.If(t, testEnv.IsRemoteDaemon) testDaemonIpcPrivateShareable(t, true, "--default-ipc-mode", "shareable") } // TestDaemonIpcModePrivate checks that --default-ipc-mode private works as intended. func TestDaemonIpcModePrivate(t *testing.T) { - skip.If(t, testEnv.DaemonInfo.OSType != "linux" || testEnv.IsRemoteDaemon()) + skip.If(t, testEnv.IsRemoteDaemon) testDaemonIpcPrivateShareable(t, false, "--default-ipc-mode", "private") } @@ -280,14 +281,14 @@ func testDaemonIpcFromConfig(t *testing.T, mode string, mustExist bool) { // TestDaemonIpcModePrivateFromConfig checks that "default-ipc-mode: private" config works as intended. func TestDaemonIpcModePrivateFromConfig(t *testing.T) { - skip.If(t, testEnv.DaemonInfo.OSType != "linux" || testEnv.IsRemoteDaemon()) + skip.If(t, testEnv.IsRemoteDaemon) testDaemonIpcFromConfig(t, "private", false) } // TestDaemonIpcModeShareableFromConfig checks that "default-ipc-mode: shareable" config works as intended. func TestDaemonIpcModeShareableFromConfig(t *testing.T) { - skip.If(t, testEnv.DaemonInfo.OSType != "linux" || testEnv.IsRemoteDaemon()) + skip.If(t, testEnv.IsRemoteDaemon) testDaemonIpcFromConfig(t, "shareable", true) } diff --git a/components/engine/integration/container/mounts_linux_test.go b/components/engine/integration/container/mounts_linux_test.go index 940c6ab882..8f77bc055a 100644 --- a/components/engine/integration/container/mounts_linux_test.go +++ b/components/engine/integration/container/mounts_linux_test.go @@ -20,7 +20,7 @@ import ( func TestContainerNetworkMountsNoChown(t *testing.T) { // chown only applies to Linux bind mounted volumes; must be same host to verify - skip.If(t, testEnv.DaemonInfo.OSType == "windows" || testEnv.IsRemoteDaemon()) + skip.If(t, testEnv.IsRemoteDaemon) defer setupTest(t)() @@ -80,7 +80,7 @@ func TestContainerNetworkMountsNoChown(t *testing.T) { } func TestMountDaemonRoot(t *testing.T) { - skip.If(t, testEnv.DaemonInfo.OSType == "windows" || testEnv.IsRemoteDaemon()) + skip.If(t, testEnv.IsRemoteDaemon) defer setupTest(t)() client := testEnv.APIClient() From 7c76af22513e8679d8f93f97432bf1c33305b720 Mon Sep 17 00:00:00 2001 From: Sebastiaan van Stijn Date: Thu, 3 Jan 2019 13:05:22 +0100 Subject: [PATCH 10/45] Fix some minor wording / issues Signed-off-by: Sebastiaan van Stijn (cherry picked from commit 263e28a830c7c0ba573f8bb6aa37bee1c3956d22) Signed-off-by: Sebastiaan van Stijn Upstream-commit: 0a234f6a71c8dcecebf5ee32c6784b47ca97872c Component: engine --- components/engine/integration/container/stop_linux_test.go | 2 +- components/engine/internal/test/fakestorage/storage.go | 2 +- 2 files changed, 2 insertions(+), 2 deletions(-) diff --git a/components/engine/integration/container/stop_linux_test.go b/components/engine/integration/container/stop_linux_test.go index c0cc89d1c1..552706c25b 100644 --- a/components/engine/integration/container/stop_linux_test.go +++ b/components/engine/integration/container/stop_linux_test.go @@ -72,7 +72,7 @@ func TestStopContainerWithTimeout(t *testing.T) { func TestDeleteDevicemapper(t *testing.T) { skip.If(t, testEnv.DaemonInfo.Driver != "devicemapper") - skip.If(t, testEnv.IsRemoteDaemon, "cannot start daemon on remote test run") + skip.If(t, testEnv.IsRemoteDaemon) defer setupTest(t)() client := testEnv.APIClient() diff --git a/components/engine/internal/test/fakestorage/storage.go b/components/engine/internal/test/fakestorage/storage.go index b091cbc3f1..77d6e2fcb9 100644 --- a/components/engine/internal/test/fakestorage/storage.go +++ b/components/engine/internal/test/fakestorage/storage.go @@ -66,7 +66,7 @@ func New(t testingT, dir string, modifiers ...func(*fakecontext.Fake) error) Fak ctx := fakecontext.New(t, dir, modifiers...) switch { case testEnv.IsRemoteDaemon() && strings.HasPrefix(request.DaemonHost(), "unix:///"): - t.Skip(fmt.Sprintf("e2e run : daemon is remote but docker host points to a unix socket")) + t.Skip("e2e run : daemon is remote but docker host points to a unix socket") case testEnv.IsLocalDaemon(): return newLocalFakeStorage(ctx) default: From f976c7527690e37d7688e02be386f2bde28ee7d2 Mon Sep 17 00:00:00 2001 From: Sebastiaan van Stijn Date: Thu, 3 Jan 2019 22:49:00 +0100 Subject: [PATCH 11/45] Remove use of deprecated client.NewEnvClient() Signed-off-by: Sebastiaan van Stijn (cherry picked from commit c8ff5ecc091278520a890ce58ed891ec354bf6d9) Signed-off-by: Sebastiaan van Stijn Upstream-commit: b9102e2a6b4bb79e080e9ce9d46046532df6f152 Component: engine --- components/engine/client/README.md | 2 +- components/engine/client/client.go | 2 +- components/engine/client/client_test.go | 16 +-- .../engine/client/container_logs_test.go | 2 +- .../engine/client/container_wait_test.go | 2 +- components/engine/client/service_logs_test.go | 2 +- .../agent/worker/executor.go | 2 +- .../integration-cli-on-swarm/host/host.go | 2 +- .../integration-cli/docker_api_attach_test.go | 2 +- .../docker_api_containers_test.go | 102 +++++++++--------- .../integration-cli/docker_api_exec_test.go | 4 +- .../integration-cli/docker_api_images_test.go | 6 +- .../docker_api_inspect_test.go | 2 +- .../integration-cli/docker_api_logs_test.go | 8 +- .../integration-cli/docker_api_stats_test.go | 2 +- .../integration-cli/docker_cli_events_test.go | 2 +- .../integration-cli/docker_cli_exec_test.go | 2 +- .../docker_cli_plugins_logdriver_test.go | 2 +- .../integration-cli/docker_cli_run_test.go | 2 +- .../docker_cli_run_unix_test.go | 2 +- .../docker_cli_update_unix_test.go | 2 +- .../integration-cli/docker_cli_volume_test.go | 2 +- .../integration-cli/docker_utils_test.go | 4 +- .../integration-cli/requirements_test.go | 2 +- .../container/mounts_linux_test.go | 2 +- .../engine/internal/test/daemon/daemon.go | 2 +- 26 files changed, 90 insertions(+), 90 deletions(-) diff --git a/components/engine/client/README.md b/components/engine/client/README.md index 059dfb3ce7..992f18117d 100644 --- a/components/engine/client/README.md +++ b/components/engine/client/README.md @@ -16,7 +16,7 @@ import ( ) func main() { - cli, err := client.NewEnvClient() + cli, err := client.NewClientWithOpts(client.FromEnv) if err != nil { panic(err) } diff --git a/components/engine/client/client.go b/components/engine/client/client.go index 5031502acf..3714dc5369 100644 --- a/components/engine/client/client.go +++ b/components/engine/client/client.go @@ -23,7 +23,7 @@ For example, to list running containers (the equivalent of "docker ps"): ) func main() { - cli, err := client.NewEnvClient() + cli, err := client.NewClientWithOpts(client.FromEnv) if err != nil { panic(err) } diff --git a/components/engine/client/client_test.go b/components/engine/client/client_test.go index 58bccaa311..23ba3d36b6 100644 --- a/components/engine/client/client_test.go +++ b/components/engine/client/client_test.go @@ -16,7 +16,7 @@ import ( "gotest.tools/skip" ) -func TestNewEnvClient(t *testing.T) { +func TestNewClientWithOpsFromEnv(t *testing.T) { skip.If(t, runtime.GOOS == "windows") testcases := []struct { @@ -86,7 +86,7 @@ func TestNewEnvClient(t *testing.T) { defer env.PatchAll(t, nil)() for _, c := range testcases { env.PatchAll(t, c.envs) - apiclient, err := NewEnvClient() + apiclient, err := NewClientWithOpts(FromEnv) if c.expectedError != "" { assert.Check(t, is.Error(err, c.expectedError), c.doc) } else { @@ -167,7 +167,7 @@ func TestParseHostURL(t *testing.T) { } } -func TestNewEnvClientSetsDefaultVersion(t *testing.T) { +func TestNewClientWithOpsFromEnvSetsDefaultVersion(t *testing.T) { defer env.PatchAll(t, map[string]string{ "DOCKER_HOST": "", "DOCKER_API_VERSION": "", @@ -175,7 +175,7 @@ func TestNewEnvClientSetsDefaultVersion(t *testing.T) { "DOCKER_CERT_PATH": "", })() - client, err := NewEnvClient() + client, err := NewClientWithOpts(FromEnv) if err != nil { t.Fatal(err) } @@ -183,7 +183,7 @@ func TestNewEnvClientSetsDefaultVersion(t *testing.T) { expected := "1.22" os.Setenv("DOCKER_API_VERSION", expected) - client, err = NewEnvClient() + client, err = NewClientWithOpts(FromEnv) if err != nil { t.Fatal(err) } @@ -195,7 +195,7 @@ func TestNewEnvClientSetsDefaultVersion(t *testing.T) { func TestNegotiateAPIVersionEmpty(t *testing.T) { defer env.PatchAll(t, map[string]string{"DOCKER_API_VERSION": ""})() - client, err := NewEnvClient() + client, err := NewClientWithOpts(FromEnv) assert.NilError(t, err) ping := types.Ping{ @@ -219,7 +219,7 @@ func TestNegotiateAPIVersionEmpty(t *testing.T) { // TestNegotiateAPIVersion asserts that client.Client can // negotiate a compatible APIVersion with the server func TestNegotiateAPIVersion(t *testing.T) { - client, err := NewEnvClient() + client, err := NewClientWithOpts(FromEnv) assert.NilError(t, err) expected := "1.21" @@ -251,7 +251,7 @@ func TestNegotiateAPVersionOverride(t *testing.T) { expected := "9.99" defer env.PatchAll(t, map[string]string{"DOCKER_API_VERSION": expected})() - client, err := NewEnvClient() + client, err := NewClientWithOpts(FromEnv) assert.NilError(t, err) ping := types.Ping{ diff --git a/components/engine/client/container_logs_test.go b/components/engine/client/container_logs_test.go index 6d6e34e101..b610eb04f0 100644 --- a/components/engine/client/container_logs_test.go +++ b/components/engine/client/container_logs_test.go @@ -153,7 +153,7 @@ func ExampleClient_ContainerLogs_withTimeout() { ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() - client, _ := NewEnvClient() + client, _ := NewClientWithOpts(FromEnv) reader, err := client.ContainerLogs(ctx, "container_id", types.ContainerLogsOptions{}) if err != nil { log.Fatal(err) diff --git a/components/engine/client/container_wait_test.go b/components/engine/client/container_wait_test.go index 11a9203ddc..9236f6f406 100644 --- a/components/engine/client/container_wait_test.go +++ b/components/engine/client/container_wait_test.go @@ -65,7 +65,7 @@ func ExampleClient_ContainerWait_withTimeout() { ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() - client, _ := NewEnvClient() + client, _ := NewClientWithOpts(FromEnv) _, errC := client.ContainerWait(ctx, "container_id", "") if err := <-errC; err != nil { log.Fatal(err) diff --git a/components/engine/client/service_logs_test.go b/components/engine/client/service_logs_test.go index 28f3ab5c6b..d8779e0603 100644 --- a/components/engine/client/service_logs_test.go +++ b/components/engine/client/service_logs_test.go @@ -122,7 +122,7 @@ func ExampleClient_ServiceLogs_withTimeout() { ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() - client, _ := NewEnvClient() + client, _ := NewClientWithOpts(FromEnv) reader, err := client.ServiceLogs(ctx, "service_id", types.ContainerLogsOptions{}) if err != nil { log.Fatal(err) diff --git a/components/engine/hack/integration-cli-on-swarm/agent/worker/executor.go b/components/engine/hack/integration-cli-on-swarm/agent/worker/executor.go index eef80d461e..d37b6533f6 100644 --- a/components/engine/hack/integration-cli-on-swarm/agent/worker/executor.go +++ b/components/engine/hack/integration-cli-on-swarm/agent/worker/executor.go @@ -29,7 +29,7 @@ func dryTestChunkExecutor() testChunkExecutor { // service via bind-mounted API socket so as to execute the test chunk func privilegedTestChunkExecutor(autoRemove bool) testChunkExecutor { return func(image string, tests []string) (int64, string, error) { - cli, err := client.NewEnvClient() + cli, err := client.NewClientWithOpts(client.FromEnv) if err != nil { return 0, "", err } diff --git a/components/engine/hack/integration-cli-on-swarm/host/host.go b/components/engine/hack/integration-cli-on-swarm/host/host.go index fdc2a83e7f..c4cb2484a6 100644 --- a/components/engine/hack/integration-cli-on-swarm/host/host.go +++ b/components/engine/hack/integration-cli-on-swarm/host/host.go @@ -50,7 +50,7 @@ func xmain() (int, error) { if *randSeed == int64(0) { *randSeed = time.Now().UnixNano() } - cli, err := client.NewEnvClient() + cli, err := client.NewClientWithOpts(client.FromEnv) if err != nil { return 1, err } diff --git a/components/engine/integration-cli/docker_api_attach_test.go b/components/engine/integration-cli/docker_api_attach_test.go index 26633841db..ed03f3333b 100644 --- a/components/engine/integration-cli/docker_api_attach_test.go +++ b/components/engine/integration-cli/docker_api_attach_test.go @@ -177,7 +177,7 @@ func (s *DockerSuite) TestPostContainersAttach(c *check.C) { expectTimeout(conn, br, "stdout") // Test the client API - client, err := client.NewEnvClient() + client, err := client.NewClientWithOpts(client.FromEnv) c.Assert(err, checker.IsNil) defer client.Close() diff --git a/components/engine/integration-cli/docker_api_containers_test.go b/components/engine/integration-cli/docker_api_containers_test.go index ef67894106..e36c655f56 100644 --- a/components/engine/integration-cli/docker_api_containers_test.go +++ b/components/engine/integration-cli/docker_api_containers_test.go @@ -43,7 +43,7 @@ func (s *DockerSuite) TestContainerAPIGetAll(c *check.C) { name := "getall" dockerCmd(c, "run", "--name", name, "busybox", "true") - cli, err := client.NewEnvClient() + cli, err := client.NewClientWithOpts(client.FromEnv) c.Assert(err, checker.IsNil) defer cli.Close() @@ -62,7 +62,7 @@ func (s *DockerSuite) TestContainerAPIGetJSONNoFieldsOmitted(c *check.C) { startCount := getContainerCount(c) dockerCmd(c, "run", "busybox", "true") - cli, err := client.NewEnvClient() + cli, err := client.NewClientWithOpts(client.FromEnv) c.Assert(err, checker.IsNil) defer cli.Close() @@ -111,7 +111,7 @@ func (s *DockerSuite) TestContainerAPIPsOmitFields(c *check.C) { port := 80 runSleepingContainer(c, "--name", name, "--expose", strconv.Itoa(port)) - cli, err := client.NewEnvClient() + cli, err := client.NewClientWithOpts(client.FromEnv) c.Assert(err, checker.IsNil) defer cli.Close() @@ -143,7 +143,7 @@ func (s *DockerSuite) TestContainerAPIGetExport(c *check.C) { name := "exportcontainer" dockerCmd(c, "run", "--name", name, "busybox", "touch", "/test") - cli, err := client.NewEnvClient() + cli, err := client.NewClientWithOpts(client.FromEnv) c.Assert(err, checker.IsNil) defer cli.Close() @@ -170,7 +170,7 @@ func (s *DockerSuite) TestContainerAPIGetChanges(c *check.C) { name := "changescontainer" dockerCmd(c, "run", "--name", name, "busybox", "rm", "/etc/passwd") - cli, err := client.NewEnvClient() + cli, err := client.NewClientWithOpts(client.FromEnv) c.Assert(err, checker.IsNil) defer cli.Close() @@ -200,7 +200,7 @@ func (s *DockerSuite) TestGetContainerStats(c *check.C) { bc := make(chan b, 1) go func() { - cli, err := client.NewEnvClient() + cli, err := client.NewClientWithOpts(client.FromEnv) c.Assert(err, checker.IsNil) defer cli.Close() @@ -234,7 +234,7 @@ func (s *DockerSuite) TestGetContainerStatsRmRunning(c *check.C) { buf := &ChannelBuffer{C: make(chan []byte, 1)} defer buf.Close() - cli, err := client.NewEnvClient() + cli, err := client.NewClientWithOpts(client.FromEnv) c.Assert(err, checker.IsNil) defer cli.Close() @@ -305,7 +305,7 @@ func (s *DockerSuite) TestGetContainerStatsStream(c *check.C) { bc := make(chan b, 1) go func() { - cli, err := client.NewEnvClient() + cli, err := client.NewClientWithOpts(client.FromEnv) c.Assert(err, checker.IsNil) defer cli.Close() @@ -347,7 +347,7 @@ func (s *DockerSuite) TestGetContainerStatsNoStream(c *check.C) { bc := make(chan b, 1) go func() { - cli, err := client.NewEnvClient() + cli, err := client.NewClientWithOpts(client.FromEnv) c.Assert(err, checker.IsNil) defer cli.Close() @@ -384,7 +384,7 @@ func (s *DockerSuite) TestGetStoppedContainerStats(c *check.C) { // We expect an immediate response, but if it's not immediate, the test would hang, so put it in a goroutine // below we'll check this on a timeout. go func() { - cli, err := client.NewEnvClient() + cli, err := client.NewClientWithOpts(client.FromEnv) c.Assert(err, checker.IsNil) defer cli.Close() @@ -412,7 +412,7 @@ func (s *DockerSuite) TestContainerAPIPause(c *check.C) { out := cli.DockerCmd(c, "run", "-d", "busybox", "sleep", "30").Combined() ContainerID := strings.TrimSpace(out) - cli, err := client.NewEnvClient() + cli, err := client.NewClientWithOpts(client.FromEnv) c.Assert(err, checker.IsNil) defer cli.Close() @@ -438,7 +438,7 @@ func (s *DockerSuite) TestContainerAPITop(c *check.C) { id := strings.TrimSpace(string(out)) c.Assert(waitRun(id), checker.IsNil) - cli, err := client.NewEnvClient() + cli, err := client.NewClientWithOpts(client.FromEnv) c.Assert(err, checker.IsNil) defer cli.Close() @@ -461,7 +461,7 @@ func (s *DockerSuite) TestContainerAPITopWindows(c *check.C) { id := strings.TrimSpace(string(out)) c.Assert(waitRun(id), checker.IsNil) - cli, err := client.NewEnvClient() + cli, err := client.NewClientWithOpts(client.FromEnv) c.Assert(err, checker.IsNil) defer cli.Close() @@ -490,7 +490,7 @@ func (s *DockerSuite) TestContainerAPICommit(c *check.C) { cName := "testapicommit" dockerCmd(c, "run", "--name="+cName, "busybox", "/bin/sh", "-c", "touch /test") - cli, err := client.NewEnvClient() + cli, err := client.NewClientWithOpts(client.FromEnv) c.Assert(err, checker.IsNil) defer cli.Close() @@ -512,7 +512,7 @@ func (s *DockerSuite) TestContainerAPICommitWithLabelInConfig(c *check.C) { cName := "testapicommitwithconfig" dockerCmd(c, "run", "--name="+cName, "busybox", "/bin/sh", "-c", "touch /test") - cli, err := client.NewEnvClient() + cli, err := client.NewClientWithOpts(client.FromEnv) c.Assert(err, checker.IsNil) defer cli.Close() @@ -559,7 +559,7 @@ func (s *DockerSuite) TestContainerAPIBadPort(c *check.C) { }, } - cli, err := client.NewEnvClient() + cli, err := client.NewClientWithOpts(client.FromEnv) c.Assert(err, checker.IsNil) defer cli.Close() @@ -573,7 +573,7 @@ func (s *DockerSuite) TestContainerAPICreate(c *check.C) { Cmd: []string{"/bin/sh", "-c", "touch /test && ls /test"}, } - cli, err := client.NewEnvClient() + cli, err := client.NewClientWithOpts(client.FromEnv) c.Assert(err, checker.IsNil) defer cli.Close() @@ -586,7 +586,7 @@ func (s *DockerSuite) TestContainerAPICreate(c *check.C) { func (s *DockerSuite) TestContainerAPICreateEmptyConfig(c *check.C) { - cli, err := client.NewEnvClient() + cli, err := client.NewClientWithOpts(client.FromEnv) c.Assert(err, checker.IsNil) defer cli.Close() @@ -610,7 +610,7 @@ func (s *DockerSuite) TestContainerAPICreateMultipleNetworksConfig(c *check.C) { }, } - cli, err := client.NewEnvClient() + cli, err := client.NewClientWithOpts(client.FromEnv) c.Assert(err, checker.IsNil) defer cli.Close() @@ -632,7 +632,7 @@ func (s *DockerSuite) TestContainerAPICreateWithHostName(c *check.C) { Domainname: domainName, } - cli, err := client.NewEnvClient() + cli, err := client.NewClientWithOpts(client.FromEnv) c.Assert(err, checker.IsNil) defer cli.Close() @@ -668,7 +668,7 @@ func UtilCreateNetworkMode(c *check.C, networkMode containertypes.NetworkMode) { NetworkMode: networkMode, } - cli, err := client.NewEnvClient() + cli, err := client.NewClientWithOpts(client.FromEnv) c.Assert(err, checker.IsNil) defer cli.Close() @@ -695,7 +695,7 @@ func (s *DockerSuite) TestContainerAPICreateWithCpuSharesCpuset(c *check.C) { }, } - cli, err := client.NewEnvClient() + cli, err := client.NewClientWithOpts(client.FromEnv) c.Assert(err, checker.IsNil) defer cli.Close() @@ -943,7 +943,7 @@ func (s *DockerSuite) TestContainerAPIRename(c *check.C) { containerID := strings.TrimSpace(out) newName := "TestContainerAPIRenameNew" - cli, err := client.NewEnvClient() + cli, err := client.NewClientWithOpts(client.FromEnv) c.Assert(err, checker.IsNil) defer cli.Close() @@ -958,7 +958,7 @@ func (s *DockerSuite) TestContainerAPIKill(c *check.C) { name := "test-api-kill" runSleepingContainer(c, "-i", "--name", name) - cli, err := client.NewEnvClient() + cli, err := client.NewClientWithOpts(client.FromEnv) c.Assert(err, checker.IsNil) defer cli.Close() @@ -972,7 +972,7 @@ func (s *DockerSuite) TestContainerAPIKill(c *check.C) { func (s *DockerSuite) TestContainerAPIRestart(c *check.C) { name := "test-api-restart" runSleepingContainer(c, "-di", "--name", name) - cli, err := client.NewEnvClient() + cli, err := client.NewClientWithOpts(client.FromEnv) c.Assert(err, checker.IsNil) defer cli.Close() @@ -989,7 +989,7 @@ func (s *DockerSuite) TestContainerAPIRestartNotimeoutParam(c *check.C) { id := strings.TrimSpace(out) c.Assert(waitRun(id), checker.IsNil) - cli, err := client.NewEnvClient() + cli, err := client.NewClientWithOpts(client.FromEnv) c.Assert(err, checker.IsNil) defer cli.Close() @@ -1007,7 +1007,7 @@ func (s *DockerSuite) TestContainerAPIStart(c *check.C) { OpenStdin: true, } - cli, err := client.NewEnvClient() + cli, err := client.NewClientWithOpts(client.FromEnv) c.Assert(err, checker.IsNil) defer cli.Close() @@ -1030,7 +1030,7 @@ func (s *DockerSuite) TestContainerAPIStop(c *check.C) { runSleepingContainer(c, "-i", "--name", name) timeout := 30 * time.Second - cli, err := client.NewEnvClient() + cli, err := client.NewClientWithOpts(client.FromEnv) c.Assert(err, checker.IsNil) defer cli.Close() @@ -1053,7 +1053,7 @@ func (s *DockerSuite) TestContainerAPIWait(c *check.C) { } dockerCmd(c, "run", "--name", name, "busybox", sleepCmd, "2") - cli, err := client.NewEnvClient() + cli, err := client.NewClientWithOpts(client.FromEnv) c.Assert(err, checker.IsNil) defer cli.Close() @@ -1171,7 +1171,7 @@ func (s *DockerSuite) TestContainerAPIDelete(c *check.C) { dockerCmd(c, "stop", id) - cli, err := client.NewEnvClient() + cli, err := client.NewClientWithOpts(client.FromEnv) c.Assert(err, checker.IsNil) defer cli.Close() @@ -1180,7 +1180,7 @@ func (s *DockerSuite) TestContainerAPIDelete(c *check.C) { } func (s *DockerSuite) TestContainerAPIDeleteNotExist(c *check.C) { - cli, err := client.NewEnvClient() + cli, err := client.NewClientWithOpts(client.FromEnv) c.Assert(err, checker.IsNil) defer cli.Close() @@ -1197,7 +1197,7 @@ func (s *DockerSuite) TestContainerAPIDeleteForce(c *check.C) { Force: true, } - cli, err := client.NewEnvClient() + cli, err := client.NewClientWithOpts(client.FromEnv) c.Assert(err, checker.IsNil) defer cli.Close() @@ -1225,7 +1225,7 @@ func (s *DockerSuite) TestContainerAPIDeleteRemoveLinks(c *check.C) { RemoveLinks: true, } - cli, err := client.NewEnvClient() + cli, err := client.NewClientWithOpts(client.FromEnv) c.Assert(err, checker.IsNil) defer cli.Close() @@ -1242,7 +1242,7 @@ func (s *DockerSuite) TestContainerAPIDeleteConflict(c *check.C) { id := strings.TrimSpace(out) c.Assert(waitRun(id), checker.IsNil) - cli, err := client.NewEnvClient() + cli, err := client.NewClientWithOpts(client.FromEnv) c.Assert(err, checker.IsNil) defer cli.Close() @@ -1274,7 +1274,7 @@ func (s *DockerSuite) TestContainerAPIDeleteRemoveVolume(c *check.C) { RemoveVolumes: true, } - cli, err := client.NewEnvClient() + cli, err := client.NewClientWithOpts(client.FromEnv) c.Assert(err, checker.IsNil) defer cli.Close() @@ -1312,7 +1312,7 @@ func (s *DockerSuite) TestContainerAPIPostContainerStop(c *check.C) { containerID := strings.TrimSpace(out) c.Assert(waitRun(containerID), checker.IsNil) - cli, err := client.NewEnvClient() + cli, err := client.NewClientWithOpts(client.FromEnv) c.Assert(err, checker.IsNil) defer cli.Close() @@ -1329,7 +1329,7 @@ func (s *DockerSuite) TestPostContainerAPICreateWithStringOrSliceEntrypoint(c *c Cmd: []string{"hello", "world"}, } - cli, err := client.NewEnvClient() + cli, err := client.NewClientWithOpts(client.FromEnv) c.Assert(err, checker.IsNil) defer cli.Close() @@ -1356,7 +1356,7 @@ func (s *DockerSuite) TestPostContainersCreateWithStringOrSliceCmd(c *check.C) { Cmd: []string{"echo", "hello", "world"}, } - cli, err := client.NewEnvClient() + cli, err := client.NewClientWithOpts(client.FromEnv) c.Assert(err, checker.IsNil) defer cli.Close() @@ -1397,7 +1397,7 @@ func (s *DockerSuite) TestPostContainersCreateWithStringOrSliceCapAddDrop(c *che CapDrop: []string{"SETGID"}, } - cli, err := client.NewEnvClient() + cli, err := client.NewClientWithOpts(client.FromEnv) c.Assert(err, checker.IsNil) defer cli.Close() @@ -1453,7 +1453,7 @@ func (s *DockerSuite) TestPostContainersCreateWithWrongCpusetValues(c *check.C) // Not supported on Windows testRequires(c, DaemonIsLinux) - cli, err := client.NewEnvClient() + cli, err := client.NewClientWithOpts(client.FromEnv) c.Assert(err, checker.IsNil) defer cli.Close() @@ -1492,7 +1492,7 @@ func (s *DockerSuite) TestPostContainersCreateShmSizeNegative(c *check.C) { ShmSize: -1, } - cli, err := client.NewEnvClient() + cli, err := client.NewClientWithOpts(client.FromEnv) c.Assert(err, checker.IsNil) defer cli.Close() @@ -1509,7 +1509,7 @@ func (s *DockerSuite) TestPostContainersCreateShmSizeHostConfigOmitted(c *check. Cmd: []string{"mount"}, } - cli, err := client.NewEnvClient() + cli, err := client.NewClientWithOpts(client.FromEnv) c.Assert(err, checker.IsNil) defer cli.Close() @@ -1536,7 +1536,7 @@ func (s *DockerSuite) TestPostContainersCreateShmSizeOmitted(c *check.C) { Cmd: []string{"mount"}, } - cli, err := client.NewEnvClient() + cli, err := client.NewClientWithOpts(client.FromEnv) c.Assert(err, checker.IsNil) defer cli.Close() @@ -1567,7 +1567,7 @@ func (s *DockerSuite) TestPostContainersCreateWithShmSize(c *check.C) { ShmSize: 1073741824, } - cli, err := client.NewEnvClient() + cli, err := client.NewClientWithOpts(client.FromEnv) c.Assert(err, checker.IsNil) defer cli.Close() @@ -1593,7 +1593,7 @@ func (s *DockerSuite) TestPostContainersCreateMemorySwappinessHostConfigOmitted( Image: "busybox", } - cli, err := client.NewEnvClient() + cli, err := client.NewClientWithOpts(client.FromEnv) c.Assert(err, checker.IsNil) defer cli.Close() @@ -1623,7 +1623,7 @@ func (s *DockerSuite) TestPostContainersCreateWithOomScoreAdjInvalidRange(c *che OomScoreAdj: 1001, } - cli, err := client.NewEnvClient() + cli, err := client.NewClientWithOpts(client.FromEnv) c.Assert(err, checker.IsNil) defer cli.Close() @@ -1646,7 +1646,7 @@ func (s *DockerSuite) TestPostContainersCreateWithOomScoreAdjInvalidRange(c *che // test case for #22210 where an empty container name caused panic. func (s *DockerSuite) TestContainerAPIDeleteWithEmptyName(c *check.C) { - cli, err := client.NewEnvClient() + cli, err := client.NewClientWithOpts(client.FromEnv) c.Assert(err, checker.IsNil) defer cli.Close() @@ -1666,7 +1666,7 @@ func (s *DockerSuite) TestContainerAPIStatsWithNetworkDisabled(c *check.C) { NetworkDisabled: true, } - cli, err := client.NewEnvClient() + cli, err := client.NewClientWithOpts(client.FromEnv) c.Assert(err, checker.IsNil) defer cli.Close() @@ -1884,7 +1884,7 @@ func (s *DockerSuite) TestContainersAPICreateMountsValidation(c *check.C) { }...) } - cli, err := client.NewEnvClient() + cli, err := client.NewClientWithOpts(client.FromEnv) c.Assert(err, checker.IsNil) defer cli.Close() @@ -1918,7 +1918,7 @@ func (s *DockerSuite) TestContainerAPICreateMountsBindRead(c *check.C) { {Type: "bind", Source: tmpDir, Target: destPath}, }, } - cli, err := client.NewEnvClient() + cli, err := client.NewClientWithOpts(client.FromEnv) c.Assert(err, checker.IsNil) defer cli.Close() @@ -2169,7 +2169,7 @@ func (s *DockerSuite) TestContainersAPICreateMountsTmpfs(c *check.C) { }, } - cli, err := client.NewEnvClient() + cli, err := client.NewClientWithOpts(client.FromEnv) c.Assert(err, checker.IsNil) defer cli.Close() diff --git a/components/engine/integration-cli/docker_api_exec_test.go b/components/engine/integration-cli/docker_api_exec_test.go index 118f9971a7..1a288733f2 100644 --- a/components/engine/integration-cli/docker_api_exec_test.go +++ b/components/engine/integration-cli/docker_api_exec_test.go @@ -71,7 +71,7 @@ func (s *DockerSuite) TestExecAPICreateContainerPaused(c *check.C) { dockerCmd(c, "pause", name) - cli, err := client.NewEnvClient() + cli, err := client.NewClientWithOpts(client.FromEnv) c.Assert(err, checker.IsNil) defer cli.Close() @@ -155,7 +155,7 @@ func (s *DockerSuite) TestExecAPIStartWithDetach(c *check.C) { AttachStderr: true, } - cli, err := client.NewEnvClient() + cli, err := client.NewClientWithOpts(client.FromEnv) c.Assert(err, checker.IsNil) defer cli.Close() diff --git a/components/engine/integration-cli/docker_api_images_test.go b/components/engine/integration-cli/docker_api_images_test.go index f306cca617..5040c98e4b 100644 --- a/components/engine/integration-cli/docker_api_images_test.go +++ b/components/engine/integration-cli/docker_api_images_test.go @@ -20,7 +20,7 @@ import ( ) func (s *DockerSuite) TestAPIImagesFilter(c *check.C) { - cli, err := client.NewEnvClient() + cli, err := client.NewClientWithOpts(client.FromEnv) c.Assert(err, checker.IsNil) defer cli.Close() @@ -88,7 +88,7 @@ func (s *DockerSuite) TestAPIImagesSaveAndLoad(c *check.C) { } func (s *DockerSuite) TestAPIImagesDelete(c *check.C) { - cli, err := client.NewEnvClient() + cli, err := client.NewClientWithOpts(client.FromEnv) c.Assert(err, checker.IsNil) defer cli.Close() @@ -112,7 +112,7 @@ func (s *DockerSuite) TestAPIImagesDelete(c *check.C) { } func (s *DockerSuite) TestAPIImagesHistory(c *check.C) { - cli, err := client.NewEnvClient() + cli, err := client.NewClientWithOpts(client.FromEnv) c.Assert(err, checker.IsNil) defer cli.Close() diff --git a/components/engine/integration-cli/docker_api_inspect_test.go b/components/engine/integration-cli/docker_api_inspect_test.go index 68055b6c14..5c452db329 100644 --- a/components/engine/integration-cli/docker_api_inspect_test.go +++ b/components/engine/integration-cli/docker_api_inspect_test.go @@ -107,7 +107,7 @@ func (s *DockerSuite) TestInspectAPIContainerVolumeDriver(c *check.C) { func (s *DockerSuite) TestInspectAPIImageResponse(c *check.C) { dockerCmd(c, "tag", "busybox:latest", "busybox:mytag") - cli, err := client.NewEnvClient() + cli, err := client.NewClientWithOpts(client.FromEnv) c.Assert(err, checker.IsNil) defer cli.Close() diff --git a/components/engine/integration-cli/docker_api_logs_test.go b/components/engine/integration-cli/docker_api_logs_test.go index e809b46c2f..2e5bd724f3 100644 --- a/components/engine/integration-cli/docker_api_logs_test.go +++ b/components/engine/integration-cli/docker_api_logs_test.go @@ -59,7 +59,7 @@ func (s *DockerSuite) TestLogsAPIWithStdout(c *check.C) { func (s *DockerSuite) TestLogsAPINoStdoutNorStderr(c *check.C) { name := "logs_test" dockerCmd(c, "run", "-d", "-t", "--name", name, "busybox", "/bin/sh") - cli, err := client.NewEnvClient() + cli, err := client.NewClientWithOpts(client.FromEnv) c.Assert(err, checker.IsNil) defer cli.Close() @@ -102,7 +102,7 @@ func (s *DockerSuite) TestLogsAPIUntilFutureFollow(c *check.C) { c.Assert(err, checker.IsNil) until := daemonTime(c).Add(untilDur) - client, err := client.NewEnvClient() + client, err := client.NewClientWithOpts(client.FromEnv) if err != nil { c.Fatal(err) } @@ -153,7 +153,7 @@ func (s *DockerSuite) TestLogsAPIUntil(c *check.C) { name := "logsuntil" 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.NewEnvClient() + client, err := client.NewClientWithOpts(client.FromEnv) if err != nil { c.Fatal(err) } @@ -190,7 +190,7 @@ func (s *DockerSuite) TestLogsAPIUntilDefaultValue(c *check.C) { name := "logsuntildefaultval" dockerCmd(c, "run", "--name", name, "busybox", "/bin/sh", "-c", "for i in $(seq 1 3); do echo log$i; done") - client, err := client.NewEnvClient() + client, err := client.NewClientWithOpts(client.FromEnv) if err != nil { c.Fatal(err) } diff --git a/components/engine/integration-cli/docker_api_stats_test.go b/components/engine/integration-cli/docker_api_stats_test.go index 3954e4b2e0..1bae97c47c 100644 --- a/components/engine/integration-cli/docker_api_stats_test.go +++ b/components/engine/integration-cli/docker_api_stats_test.go @@ -262,7 +262,7 @@ func jsonBlobHasGTE121NetworkStats(blob map[string]interface{}) bool { func (s *DockerSuite) TestAPIStatsContainerNotFound(c *check.C) { testRequires(c, DaemonIsLinux) - cli, err := client.NewEnvClient() + cli, err := client.NewClientWithOpts(client.FromEnv) c.Assert(err, checker.IsNil) defer cli.Close() diff --git a/components/engine/integration-cli/docker_cli_events_test.go b/components/engine/integration-cli/docker_cli_events_test.go index 8db120d03d..c8e2a36962 100644 --- a/components/engine/integration-cli/docker_cli_events_test.go +++ b/components/engine/integration-cli/docker_cli_events_test.go @@ -458,7 +458,7 @@ func (s *DockerSuite) TestEventsResize(c *check.C) { cID := strings.TrimSpace(out) c.Assert(waitRun(cID), checker.IsNil) - cli, err := client.NewEnvClient() + cli, err := client.NewClientWithOpts(client.FromEnv) c.Assert(err, checker.IsNil) defer cli.Close() diff --git a/components/engine/integration-cli/docker_cli_exec_test.go b/components/engine/integration-cli/docker_cli_exec_test.go index 72059c79e6..d998876f6e 100644 --- a/components/engine/integration-cli/docker_cli_exec_test.go +++ b/components/engine/integration-cli/docker_cli_exec_test.go @@ -359,7 +359,7 @@ func (s *DockerSuite) TestExecInspectID(c *check.C) { } // But we should still be able to query the execID - cli, err := client.NewEnvClient() + cli, err := client.NewClientWithOpts(client.FromEnv) c.Assert(err, checker.IsNil) defer cli.Close() diff --git a/components/engine/integration-cli/docker_cli_plugins_logdriver_test.go b/components/engine/integration-cli/docker_cli_plugins_logdriver_test.go index 7d1ffcb632..5fbae29362 100644 --- a/components/engine/integration-cli/docker_cli_plugins_logdriver_test.go +++ b/components/engine/integration-cli/docker_cli_plugins_logdriver_test.go @@ -35,7 +35,7 @@ func (s *DockerSuite) TestPluginLogDriverInfoList(c *check.C) { dockerCmd(c, "plugin", "install", pluginName) - cli, err := client.NewEnvClient() + cli, err := client.NewClientWithOpts(client.FromEnv) c.Assert(err, checker.IsNil) defer cli.Close() diff --git a/components/engine/integration-cli/docker_cli_run_test.go b/components/engine/integration-cli/docker_cli_run_test.go index b4c4708e07..8393f3cb40 100644 --- a/components/engine/integration-cli/docker_cli_run_test.go +++ b/components/engine/integration-cli/docker_cli_run_test.go @@ -3898,7 +3898,7 @@ func (s *DockerSuite) TestRunNamedVolumesFromNotRemoved(c *check.C) { cid, _ := dockerCmd(c, "run", "-d", "--name=parent", "-v", "test:"+prefix+"/foo", "-v", prefix+"/bar", "busybox", "true") dockerCmd(c, "run", "--name=child", "--volumes-from=parent", "busybox", "true") - cli, err := client.NewEnvClient() + cli, err := client.NewClientWithOpts(client.FromEnv) c.Assert(err, checker.IsNil) defer cli.Close() diff --git a/components/engine/integration-cli/docker_cli_run_unix_test.go b/components/engine/integration-cli/docker_cli_run_unix_test.go index 64b33703b4..a72a756743 100644 --- a/components/engine/integration-cli/docker_cli_run_unix_test.go +++ b/components/engine/integration-cli/docker_cli_run_unix_test.go @@ -1568,7 +1568,7 @@ func (s *DockerSuite) TestRunWithNanoCPUs(c *check.C) { out, _ := dockerCmd(c, "run", "--cpus", "0.5", "--name", "test", "busybox", "sh", "-c", fmt.Sprintf("cat %s && cat %s", file1, file2)) c.Assert(strings.TrimSpace(out), checker.Equals, "50000\n100000") - clt, err := client.NewEnvClient() + clt, err := client.NewClientWithOpts(client.FromEnv) c.Assert(err, checker.IsNil) inspect, err := clt.ContainerInspect(context.Background(), "test") c.Assert(err, checker.IsNil) diff --git a/components/engine/integration-cli/docker_cli_update_unix_test.go b/components/engine/integration-cli/docker_cli_update_unix_test.go index 1fb30f04d6..7b4925a4ad 100644 --- a/components/engine/integration-cli/docker_cli_update_unix_test.go +++ b/components/engine/integration-cli/docker_cli_update_unix_test.go @@ -309,7 +309,7 @@ func (s *DockerSuite) TestUpdateWithNanoCPUs(c *check.C) { out, _ = dockerCmd(c, "exec", "top", "sh", "-c", fmt.Sprintf("cat %s && cat %s", file1, file2)) c.Assert(strings.TrimSpace(out), checker.Equals, "50000\n100000") - clt, err := client.NewEnvClient() + clt, err := client.NewClientWithOpts(client.FromEnv) c.Assert(err, checker.IsNil) inspect, err := clt.ContainerInspect(context.Background(), "top") c.Assert(err, checker.IsNil) diff --git a/components/engine/integration-cli/docker_cli_volume_test.go b/components/engine/integration-cli/docker_cli_volume_test.go index 257ac89701..9e25b52100 100644 --- a/components/engine/integration-cli/docker_cli_volume_test.go +++ b/components/engine/integration-cli/docker_cli_volume_test.go @@ -600,7 +600,7 @@ func (s *DockerSuite) TestDuplicateMountpointsForVolumesFromAndMounts(c *check.C err := os.MkdirAll("/tmp/data", 0755) c.Assert(err, checker.IsNil) // Mounts is available in API - cli, err := client.NewEnvClient() + cli, err := client.NewClientWithOpts(client.FromEnv) c.Assert(err, checker.IsNil) defer cli.Close() diff --git a/components/engine/integration-cli/docker_utils_test.go b/components/engine/integration-cli/docker_utils_test.go index 1c05bf5d04..d920077177 100644 --- a/components/engine/integration-cli/docker_utils_test.go +++ b/components/engine/integration-cli/docker_utils_test.go @@ -261,7 +261,7 @@ func daemonTime(c *check.C) time.Time { if testEnv.IsLocalDaemon() { return time.Now() } - cli, err := client.NewEnvClient() + cli, err := client.NewClientWithOpts(client.FromEnv) c.Assert(err, check.IsNil) defer cli.Close() @@ -373,7 +373,7 @@ func minimalBaseImage() string { } func getGoroutineNumber() (int, error) { - cli, err := client.NewEnvClient() + cli, err := client.NewClientWithOpts(client.FromEnv) if err != nil { return 0, err } diff --git a/components/engine/integration-cli/requirements_test.go b/components/engine/integration-cli/requirements_test.go index 28be59cd2c..a087d66603 100644 --- a/components/engine/integration-cli/requirements_test.go +++ b/components/engine/integration-cli/requirements_test.go @@ -49,7 +49,7 @@ func MinimumAPIVersion(version string) func() bool { } func OnlyDefaultNetworks() bool { - cli, err := client.NewEnvClient() + cli, err := client.NewClientWithOpts(client.FromEnv) if err != nil { return false } diff --git a/components/engine/integration/container/mounts_linux_test.go b/components/engine/integration/container/mounts_linux_test.go index 8f77bc055a..273cbf0135 100644 --- a/components/engine/integration/container/mounts_linux_test.go +++ b/components/engine/integration/container/mounts_linux_test.go @@ -54,7 +54,7 @@ func TestContainerNetworkMountsNoChown(t *testing.T) { }, } - cli, err := client.NewEnvClient() + cli, err := client.NewClientWithOpts(client.FromEnv) assert.NilError(t, err) defer cli.Close() diff --git a/components/engine/internal/test/daemon/daemon.go b/components/engine/internal/test/daemon/daemon.go index 8d8df1c451..cfa06fa934 100644 --- a/components/engine/internal/test/daemon/daemon.go +++ b/components/engine/internal/test/daemon/daemon.go @@ -552,7 +552,7 @@ func (d *Daemon) LoadBusybox(t assert.TestingT) { if ht, ok := t.(test.HelperT); ok { ht.Helper() } - clientHost, err := client.NewEnvClient() + clientHost, err := client.NewClientWithOpts(client.FromEnv) assert.NilError(t, err, "failed to create client") defer clientHost.Close() From df3af968c9410d55eaaf0c5c3a7967f982f74fa3 Mon Sep 17 00:00:00 2001 From: Yong Tang Date: Sat, 12 Jan 2019 22:59:49 +0000 Subject: [PATCH 12/45] Remove code duplication and consolidate networkIsRemoved This fix removes code duplication and consolidates networkIsRemoved into one place. Signed-off-by: Yong Tang (cherry picked from commit 28b7824caa9c8f1acc0471136a8a4fd80e51f491) Signed-off-by: Sebastiaan van Stijn Upstream-commit: dd20556e037b262473f3f8163dfc7c21e9161c8e Component: engine --- .../integration/internal/network/states.go | 20 +++++++++++++++++++ .../integration/network/inspect_test.go | 12 +---------- .../engine/integration/service/create_test.go | 18 ++++------------- 3 files changed, 25 insertions(+), 25 deletions(-) create mode 100644 components/engine/integration/internal/network/states.go diff --git a/components/engine/integration/internal/network/states.go b/components/engine/integration/internal/network/states.go new file mode 100644 index 0000000000..1f00e0b80c --- /dev/null +++ b/components/engine/integration/internal/network/states.go @@ -0,0 +1,20 @@ +package network + +import ( + "context" + + "github.com/docker/docker/api/types" + "github.com/docker/docker/client" + "gotest.tools/poll" +) + +// IsRemoved verifies the network is removed. +func IsRemoved(ctx context.Context, client client.NetworkAPIClient, networkID string) func(log poll.LogT) poll.Result { + return func(log poll.LogT) poll.Result { + _, err := client.NetworkInspect(ctx, networkID, types.NetworkInspectOptions{}) + if err == nil { + return poll.Continue("waiting for network %s to be removed", networkID) + } + return poll.Success() + } +} diff --git a/components/engine/integration/network/inspect_test.go b/components/engine/integration/network/inspect_test.go index 1e9ad94865..12ea884f2a 100644 --- a/components/engine/integration/network/inspect_test.go +++ b/components/engine/integration/network/inspect_test.go @@ -91,7 +91,7 @@ func TestInspectNetwork(t *testing.T) { err = client.NetworkRemove(context.Background(), overlayID) assert.NilError(t, err) - poll.WaitOn(t, networkIsRemoved(client, overlayID), poll.WithTimeout(1*time.Minute), poll.WithDelay(10*time.Second)) + poll.WaitOn(t, network.IsRemoved(context.Background(), client, overlayID), poll.WithTimeout(1*time.Minute), poll.WithDelay(10*time.Second)) } func serviceRunningTasksCount(client client.ServiceAPIClient, serviceID string, instances uint64) func(log poll.LogT) poll.Result { @@ -117,16 +117,6 @@ func serviceRunningTasksCount(client client.ServiceAPIClient, serviceID string, } } -func networkIsRemoved(client client.NetworkAPIClient, networkID string) func(log poll.LogT) poll.Result { - return func(log poll.LogT) poll.Result { - _, err := client.NetworkInspect(context.Background(), networkID, types.NetworkInspectOptions{}) - if err == nil { - return poll.Continue("waiting for network %s to be removed", networkID) - } - return poll.Success() - } -} - func serviceIsRemoved(client client.ServiceAPIClient, serviceID string) func(log poll.LogT) poll.Result { return func(log poll.LogT) poll.Result { filter := filters.NewArgs() diff --git a/components/engine/integration/service/create_test.go b/components/engine/integration/service/create_test.go index 7112fa719c..d64d352ed3 100644 --- a/components/engine/integration/service/create_test.go +++ b/components/engine/integration/service/create_test.go @@ -119,7 +119,7 @@ func TestCreateServiceMultipleTimes(t *testing.T) { err = client.NetworkRemove(context.Background(), overlayID) assert.NilError(t, err) - poll.WaitOn(t, networkIsRemoved(client, overlayID), poll.WithTimeout(1*time.Minute), poll.WithDelay(10*time.Second)) + poll.WaitOn(t, network.IsRemoved(context.Background(), client, overlayID), poll.WithTimeout(1*time.Minute), poll.WithDelay(10*time.Second)) } func TestCreateWithDuplicateNetworkNames(t *testing.T) { @@ -177,9 +177,9 @@ func TestCreateWithDuplicateNetworkNames(t *testing.T) { assert.NilError(t, err) // Make sure networks have been destroyed. - poll.WaitOn(t, networkIsRemoved(client, n3), poll.WithTimeout(1*time.Minute), poll.WithDelay(10*time.Second)) - poll.WaitOn(t, networkIsRemoved(client, n2), poll.WithTimeout(1*time.Minute), poll.WithDelay(10*time.Second)) - poll.WaitOn(t, networkIsRemoved(client, n1), poll.WithTimeout(1*time.Minute), poll.WithDelay(10*time.Second)) + poll.WaitOn(t, network.IsRemoved(context.Background(), client, n3), poll.WithTimeout(1*time.Minute), poll.WithDelay(10*time.Second)) + poll.WaitOn(t, network.IsRemoved(context.Background(), client, n2), poll.WithTimeout(1*time.Minute), poll.WithDelay(10*time.Second)) + poll.WaitOn(t, network.IsRemoved(context.Background(), client, n1), poll.WithTimeout(1*time.Minute), poll.WithDelay(10*time.Second)) } func TestCreateServiceSecretFileMode(t *testing.T) { @@ -367,13 +367,3 @@ func serviceIsRemoved(client client.ServiceAPIClient, serviceID string) func(log return poll.Success() } } - -func networkIsRemoved(client client.NetworkAPIClient, networkID string) func(log poll.LogT) poll.Result { - return func(log poll.LogT) poll.Result { - _, err := client.NetworkInspect(context.Background(), networkID, types.NetworkInspectOptions{}) - if err == nil { - return poll.Continue("waiting for network %s to be removed", networkID) - } - return poll.Success() - } -} From 66a128b214ad07f14970f4733b19ee288bc34031 Mon Sep 17 00:00:00 2001 From: Sebastiaan van Stijn Date: Mon, 14 Jan 2019 01:47:17 +0100 Subject: [PATCH 13/45] Refactor TestInspectNetwork Clean up and refactor this test; - make `serviceRunningTasksCount` to use a `desired-state` filter - use subtests, and inline the `validNetworkVerbose` checks; also use asserts for the individual checks, so that any failure will log exactly what failed - remove helper functions that are no longer needed Signed-off-by: Sebastiaan van Stijn (cherry picked from commit 60d93aab2e68b13b3f22c43add4762d3e8108227) Signed-off-by: Sebastiaan van Stijn Upstream-commit: 046352162f1a23f10a05b59e4fac9d932bcd4f35 Component: engine --- .../integration/network/inspect_test.go | 175 ++++++++---------- 1 file changed, 76 insertions(+), 99 deletions(-) diff --git a/components/engine/integration/network/inspect_test.go b/components/engine/integration/network/inspect_test.go index 12ea884f2a..9003387bac 100644 --- a/components/engine/integration/network/inspect_test.go +++ b/components/engine/integration/network/inspect_test.go @@ -3,7 +3,6 @@ package network // import "github.com/docker/docker/integration/network" import ( "context" "testing" - "time" "github.com/docker/docker/api/types" "github.com/docker/docker/api/types/filters" @@ -16,103 +15,118 @@ import ( "gotest.tools/skip" ) -const defaultSwarmPort = 2477 - func TestInspectNetwork(t *testing.T) { skip.If(t, testEnv.OSType == "windows", "FIXME") defer setupTest(t)() d := swarm.NewSwarm(t, testEnv) defer d.Stop(t) - client := d.NewClientT(t) - defer client.Close() + c := d.NewClientT(t) + defer c.Close() - overlayName := "overlay1" - overlayID := network.CreateNoError(t, context.Background(), client, overlayName, + networkName := "Overlay" + t.Name() + overlayID := network.CreateNoError(t, context.Background(), c, networkName, network.WithDriver("overlay"), network.WithCheckDuplicate(), ) - var instances uint64 = 4 + var instances uint64 = 2 serviceName := "TestService" + t.Name() serviceID := swarm.CreateService(t, d, swarm.ServiceWithReplicas(instances), swarm.ServiceWithName(serviceName), - swarm.ServiceWithNetwork(overlayName), + swarm.ServiceWithNetwork(networkName), ) - poll.WaitOn(t, serviceRunningTasksCount(client, serviceID, instances), swarm.ServicePoll) + poll.WaitOn(t, serviceRunningTasksCount(c, serviceID, instances), swarm.ServicePoll) - _, _, err := client.ServiceInspectWithRaw(context.Background(), serviceID, types.ServiceInspectOptions{}) + tests := []struct { + name string + network string + opts types.NetworkInspectOptions + }{ + { + name: "full network id", + network: overlayID, + opts: types.NetworkInspectOptions{ + Verbose: true, + }, + }, + { + name: "partial network id", + network: overlayID[0:11], + opts: types.NetworkInspectOptions{ + Verbose: true, + }, + }, + { + name: "network name", + network: networkName, + opts: types.NetworkInspectOptions{ + Verbose: true, + }, + }, + { + name: "network name and swarm scope", + network: networkName, + opts: types.NetworkInspectOptions{ + Verbose: true, + Scope: "swarm", + }, + }, + } + ctx := context.Background() + for _, tc := range tests { + tc := tc + t.Run(tc.name, func(t *testing.T) { + nw, err := c.NetworkInspect(ctx, tc.network, tc.opts) + assert.NilError(t, err) + + if service, ok := nw.Services[serviceName]; ok { + assert.Equal(t, len(service.Tasks), int(instances)) + } + + assert.Assert(t, nw.IPAM.Config != nil) + + for _, cfg := range nw.IPAM.Config { + assert.Assert(t, cfg.Gateway != "") + assert.Assert(t, cfg.Subnet != "") + } + }) + } + + // TODO find out why removing networks is needed; other tests fail if the network is not removed, even though they run on a new daemon. + err := c.ServiceRemove(ctx, serviceID) assert.NilError(t, err) - - // Test inspect verbose with full NetworkID - networkVerbose, err := client.NetworkInspect(context.Background(), overlayID, types.NetworkInspectOptions{ - Verbose: true, - }) + poll.WaitOn(t, serviceIsRemoved(c, serviceID), swarm.ServicePoll) + err = c.NetworkRemove(ctx, overlayID) assert.NilError(t, err) - assert.Assert(t, validNetworkVerbose(networkVerbose, serviceName, instances)) - - // Test inspect verbose with partial NetworkID - networkVerbose, err = client.NetworkInspect(context.Background(), overlayID[0:11], types.NetworkInspectOptions{ - Verbose: true, - }) - assert.NilError(t, err) - assert.Assert(t, validNetworkVerbose(networkVerbose, serviceName, instances)) - - // Test inspect verbose with Network name and swarm scope - networkVerbose, err = client.NetworkInspect(context.Background(), overlayName, types.NetworkInspectOptions{ - Verbose: true, - Scope: "swarm", - }) - assert.NilError(t, err) - assert.Assert(t, validNetworkVerbose(networkVerbose, serviceName, instances)) - - err = client.ServiceRemove(context.Background(), serviceID) - assert.NilError(t, err) - - poll.WaitOn(t, serviceIsRemoved(client, serviceID), swarm.ServicePoll) - poll.WaitOn(t, noTasks(client), swarm.ServicePoll) - - serviceID2 := swarm.CreateService(t, d, - swarm.ServiceWithReplicas(instances), - swarm.ServiceWithName(serviceName), - swarm.ServiceWithNetwork(overlayName), - ) - - poll.WaitOn(t, serviceRunningTasksCount(client, serviceID2, instances), swarm.ServicePoll) - - err = client.ServiceRemove(context.Background(), serviceID2) - assert.NilError(t, err) - - poll.WaitOn(t, serviceIsRemoved(client, serviceID2), swarm.ServicePoll) - poll.WaitOn(t, noTasks(client), swarm.ServicePoll) - - err = client.NetworkRemove(context.Background(), overlayID) - assert.NilError(t, err) - - poll.WaitOn(t, network.IsRemoved(context.Background(), client, overlayID), poll.WithTimeout(1*time.Minute), poll.WithDelay(10*time.Second)) + poll.WaitOn(t, network.IsRemoved(ctx, c, overlayID), swarm.NetworkPoll) } func serviceRunningTasksCount(client client.ServiceAPIClient, serviceID string, instances uint64) func(log poll.LogT) poll.Result { return func(log poll.LogT) poll.Result { - filter := filters.NewArgs() - filter.Add("service", serviceID) tasks, err := client.TaskList(context.Background(), types.TaskListOptions{ - Filters: filter, + Filters: filters.NewArgs( + filters.Arg("service", serviceID), + filters.Arg("desired-state", string(swarmtypes.TaskStateRunning)), + ), }) switch { case err != nil: return poll.Error(err) case len(tasks) == int(instances): for _, task := range tasks { + if task.Status.Err != "" { + log.Log("task error:", task.Status.Err) + } if task.Status.State != swarmtypes.TaskStateRunning { - return poll.Continue("waiting for tasks to enter run state") + return poll.Continue("waiting for tasks to enter run state (current status: %s)", task.Status.State) } } return poll.Success() default: - return poll.Continue("task count at %d waiting for %d", len(tasks), instances) + return poll.Continue("task count for service %s at %d waiting for %d", serviceID, len(tasks), instances) } } } @@ -130,40 +144,3 @@ func serviceIsRemoved(client client.ServiceAPIClient, serviceID string) func(log return poll.Success() } } - -func noTasks(client client.ServiceAPIClient) func(log poll.LogT) poll.Result { - return func(log poll.LogT) poll.Result { - filter := filters.NewArgs() - tasks, err := client.TaskList(context.Background(), types.TaskListOptions{ - Filters: filter, - }) - switch { - case err != nil: - return poll.Error(err) - case len(tasks) == 0: - return poll.Success() - default: - return poll.Continue("task count at %d waiting for 0", len(tasks)) - } - } -} - -// Check to see if Service and Tasks info are part of the inspect verbose response -func validNetworkVerbose(network types.NetworkResource, service string, instances uint64) bool { - if service, ok := network.Services[service]; ok { - if len(service.Tasks) != int(instances) { - return false - } - } - - if network.IPAM.Config == nil { - return false - } - - for _, cfg := range network.IPAM.Config { - if cfg.Gateway == "" || cfg.Subnet == "" { - return false - } - } - return true -} From 777ce4552762282d6818b3bea7e7416b4beb2493 Mon Sep 17 00:00:00 2001 From: Sebastiaan van Stijn Date: Mon, 14 Jan 2019 02:20:09 +0100 Subject: [PATCH 14/45] Integration tests: remove some duplicated code, and preserve context This introduces `NoTasksForService` and `NoTasks` poller checks, that can be used to check if no tasks are left in general, or for a specific service. Some redundant checks were also removed from some tests. Signed-off-by: Sebastiaan van Stijn (cherry picked from commit 56a68c15f8a093b1761e77a74d8b7acdfbcb30a2) Signed-off-by: Sebastiaan van Stijn Upstream-commit: 8f6421457d3be6280236aa466e533fb32cb4509b Component: engine --- .../integration/internal/swarm/states.go | 47 ++++++++++++ .../integration/network/inspect_test.go | 16 +---- .../integration/network/service_test.go | 17 ++--- .../engine/integration/service/create_test.go | 71 ++++--------------- 4 files changed, 71 insertions(+), 80 deletions(-) create mode 100644 components/engine/integration/internal/swarm/states.go diff --git a/components/engine/integration/internal/swarm/states.go b/components/engine/integration/internal/swarm/states.go new file mode 100644 index 0000000000..51d6200594 --- /dev/null +++ b/components/engine/integration/internal/swarm/states.go @@ -0,0 +1,47 @@ +package swarm + +import ( + "context" + + "github.com/docker/docker/api/types" + "github.com/docker/docker/api/types/filters" + "github.com/docker/docker/client" + "gotest.tools/poll" +) + +// NoTasksForService verifies that there are no more tasks for the given service +func NoTasksForService(ctx context.Context, client client.ServiceAPIClient, serviceID string) func(log poll.LogT) poll.Result { + return func(log poll.LogT) poll.Result { + tasks, err := client.TaskList(ctx, types.TaskListOptions{ + Filters: filters.NewArgs( + filters.Arg("service", serviceID), + ), + }) + if err == nil { + if len(tasks) == 0 { + return poll.Success() + } + if len(tasks) > 0 { + return poll.Continue("task count for service %s at %d waiting for 0", serviceID, len(tasks)) + } + return poll.Continue("waiting for tasks for service %s to be deleted", serviceID) + } + // TODO we should not use an error as indication that the tasks are gone. There may be other reasons for an error to occur. + return poll.Success() + } +} + +// NoTasks verifies that all tasks are gone +func NoTasks(ctx context.Context, client client.ServiceAPIClient) func(log poll.LogT) poll.Result { + return func(log poll.LogT) poll.Result { + tasks, err := client.TaskList(ctx, types.TaskListOptions{}) + switch { + case err != nil: + return poll.Error(err) + case len(tasks) == 0: + return poll.Success() + default: + return poll.Continue("waiting for all tasks to be removed: task count at %d", len(tasks)) + } + } +} diff --git a/components/engine/integration/network/inspect_test.go b/components/engine/integration/network/inspect_test.go index 9003387bac..d12ad6781d 100644 --- a/components/engine/integration/network/inspect_test.go +++ b/components/engine/integration/network/inspect_test.go @@ -98,7 +98,7 @@ func TestInspectNetwork(t *testing.T) { // TODO find out why removing networks is needed; other tests fail if the network is not removed, even though they run on a new daemon. err := c.ServiceRemove(ctx, serviceID) assert.NilError(t, err) - poll.WaitOn(t, serviceIsRemoved(c, serviceID), swarm.ServicePoll) + poll.WaitOn(t, swarm.NoTasksForService(ctx, c, serviceID), swarm.ServicePoll) err = c.NetworkRemove(ctx, overlayID) assert.NilError(t, err) poll.WaitOn(t, network.IsRemoved(ctx, c, overlayID), swarm.NetworkPoll) @@ -130,17 +130,3 @@ func serviceRunningTasksCount(client client.ServiceAPIClient, serviceID string, } } } - -func serviceIsRemoved(client client.ServiceAPIClient, serviceID string) func(log poll.LogT) poll.Result { - return func(log poll.LogT) poll.Result { - filter := filters.NewArgs() - filter.Add("service", serviceID) - _, err := client.TaskList(context.Background(), types.TaskListOptions{ - Filters: filter, - }) - if err == nil { - return poll.Continue("waiting for service %s to be deleted", serviceID) - } - return poll.Success() - } -} diff --git a/components/engine/integration/network/service_test.go b/components/engine/integration/network/service_test.go index c418b2eee5..a65d27564c 100644 --- a/components/engine/integration/network/service_test.go +++ b/components/engine/integration/network/service_test.go @@ -254,18 +254,19 @@ func TestServiceRemoveKeepsIngressNetwork(t *testing.T) { poll.WaitOn(t, serviceRunningCount(c, serviceID, instances), swarm.ServicePoll) - _, _, err := c.ServiceInspectWithRaw(context.Background(), serviceID, types.ServiceInspectOptions{}) + ctx := context.Background() + _, _, err := c.ServiceInspectWithRaw(ctx, serviceID, types.ServiceInspectOptions{}) assert.NilError(t, err) - err = c.ServiceRemove(context.Background(), serviceID) + err = c.ServiceRemove(ctx, serviceID) assert.NilError(t, err) - poll.WaitOn(t, serviceIsRemoved(c, serviceID), swarm.ServicePoll) - poll.WaitOn(t, noServices(c), swarm.ServicePoll) + poll.WaitOn(t, noServices(ctx, c), swarm.ServicePoll) + poll.WaitOn(t, swarm.NoTasks(ctx, c), swarm.ServicePoll) // Ensure that "ingress" is not removed or corrupted time.Sleep(10 * time.Second) - netInfo, err := c.NetworkInspect(context.Background(), ingressNet, types.NetworkInspectOptions{ + netInfo, err := c.NetworkInspect(ctx, ingressNet, types.NetworkInspectOptions{ Verbose: true, Scope: "swarm", }) @@ -312,16 +313,16 @@ func swarmIngressReady(client client.NetworkAPIClient) func(log poll.LogT) poll. } } -func noServices(client client.ServiceAPIClient) func(log poll.LogT) poll.Result { +func noServices(ctx context.Context, client client.ServiceAPIClient) func(log poll.LogT) poll.Result { return func(log poll.LogT) poll.Result { - services, err := client.ServiceList(context.Background(), types.ServiceListOptions{}) + services, err := client.ServiceList(ctx, types.ServiceListOptions{}) switch { case err != nil: return poll.Error(err) case len(services) == 0: return poll.Success() default: - return poll.Continue("Service count at %d waiting for 0", len(services)) + return poll.Continue("waiting for all services to be removed: service count at %d", len(services)) } } } diff --git a/components/engine/integration/service/create_test.go b/components/engine/integration/service/create_test.go index d64d352ed3..6e79bec9a8 100644 --- a/components/engine/integration/service/create_test.go +++ b/components/engine/integration/service/create_test.go @@ -79,9 +79,10 @@ func TestCreateServiceMultipleTimes(t *testing.T) { defer d.Stop(t) client := d.NewClientT(t) defer client.Close() + ctx := context.Background() overlayName := "overlay1_" + t.Name() - overlayID := network.CreateNoError(t, context.Background(), client, overlayName, + overlayID := network.CreateNoError(t, ctx, client, overlayName, network.WithCheckDuplicate(), network.WithDriver("overlay"), ) @@ -104,8 +105,7 @@ func TestCreateServiceMultipleTimes(t *testing.T) { err = client.ServiceRemove(context.Background(), serviceID) assert.NilError(t, err) - poll.WaitOn(t, serviceIsRemoved(client, serviceID), swarm.ServicePoll) - poll.WaitOn(t, noTasks(client), swarm.ServicePoll) + poll.WaitOn(t, swarm.NoTasksForService(ctx, client, serviceID), swarm.ServicePoll) serviceID2 := swarm.CreateService(t, d, serviceSpec...) poll.WaitOn(t, serviceRunningTasksCount(client, serviceID2, instances), swarm.ServicePoll) @@ -113,8 +113,7 @@ func TestCreateServiceMultipleTimes(t *testing.T) { err = client.ServiceRemove(context.Background(), serviceID2) assert.NilError(t, err) - poll.WaitOn(t, serviceIsRemoved(client, serviceID2), swarm.ServicePoll) - poll.WaitOn(t, noTasks(client), swarm.ServicePoll) + poll.WaitOn(t, swarm.NoTasksForService(ctx, client, serviceID2), swarm.ServicePoll) err = client.NetworkRemove(context.Background(), overlayID) assert.NilError(t, err) @@ -129,19 +128,14 @@ func TestCreateWithDuplicateNetworkNames(t *testing.T) { defer d.Stop(t) client := d.NewClientT(t) defer client.Close() + ctx := context.Background() name := "foo_" + t.Name() - n1 := network.CreateNoError(t, context.Background(), client, name, - network.WithDriver("bridge"), - ) - n2 := network.CreateNoError(t, context.Background(), client, name, - network.WithDriver("bridge"), - ) + n1 := network.CreateNoError(t, ctx, client, name, network.WithDriver("bridge")) + n2 := network.CreateNoError(t, ctx, client, name, network.WithDriver("bridge")) // Duplicates with name but with different driver - n3 := network.CreateNoError(t, context.Background(), client, name, - network.WithDriver("overlay"), - ) + n3 := network.CreateNoError(t, ctx, client, name, network.WithDriver("overlay")) // Create Service with the same name var instances uint64 = 1 @@ -155,16 +149,14 @@ func TestCreateWithDuplicateNetworkNames(t *testing.T) { poll.WaitOn(t, serviceRunningTasksCount(client, serviceID, instances), swarm.ServicePoll) - resp, _, err := client.ServiceInspectWithRaw(context.Background(), serviceID, types.ServiceInspectOptions{}) + resp, _, err := client.ServiceInspectWithRaw(ctx, serviceID, types.ServiceInspectOptions{}) assert.NilError(t, err) assert.Check(t, is.Equal(n3, resp.Spec.TaskTemplate.Networks[0].Target)) - // Remove Service - err = client.ServiceRemove(context.Background(), serviceID) + // Remove Service, and wait for its tasks to be removed + err = client.ServiceRemove(ctx, serviceID) assert.NilError(t, err) - - // Make sure task has been destroyed. - poll.WaitOn(t, serviceIsRemoved(client, serviceID), swarm.ServicePoll) + poll.WaitOn(t, swarm.NoTasksForService(ctx, client, serviceID), swarm.ServicePoll) // Remove networks err = client.NetworkRemove(context.Background(), n3) @@ -240,9 +232,7 @@ func TestCreateServiceSecretFileMode(t *testing.T) { err = client.ServiceRemove(ctx, serviceID) assert.NilError(t, err) - - poll.WaitOn(t, serviceIsRemoved(client, serviceID), swarm.ServicePoll) - poll.WaitOn(t, noTasks(client), swarm.ServicePoll) + poll.WaitOn(t, swarm.NoTasksForService(ctx, client, serviceID), swarm.ServicePoll) err = client.SecretRemove(ctx, secretName) assert.NilError(t, err) @@ -306,9 +296,7 @@ func TestCreateServiceConfigFileMode(t *testing.T) { err = client.ServiceRemove(ctx, serviceID) assert.NilError(t, err) - - poll.WaitOn(t, serviceIsRemoved(client, serviceID)) - poll.WaitOn(t, noTasks(client)) + poll.WaitOn(t, swarm.NoTasksForService(ctx, client, serviceID)) err = client.ConfigRemove(ctx, configName) assert.NilError(t, err) @@ -336,34 +324,3 @@ func serviceRunningTasksCount(client client.ServiceAPIClient, serviceID string, } } } - -func noTasks(client client.ServiceAPIClient) func(log poll.LogT) poll.Result { - return func(log poll.LogT) poll.Result { - filter := filters.NewArgs() - tasks, err := client.TaskList(context.Background(), types.TaskListOptions{ - Filters: filter, - }) - switch { - case err != nil: - return poll.Error(err) - case len(tasks) == 0: - return poll.Success() - default: - return poll.Continue("task count at %d waiting for 0", len(tasks)) - } - } -} - -func serviceIsRemoved(client client.ServiceAPIClient, serviceID string) func(log poll.LogT) poll.Result { - return func(log poll.LogT) poll.Result { - filter := filters.NewArgs() - filter.Add("service", serviceID) - _, err := client.TaskList(context.Background(), types.TaskListOptions{ - Filters: filter, - }) - if err == nil { - return poll.Continue("waiting for service %s to be deleted", serviceID) - } - return poll.Success() - } -} From bfd7f1289cc17d44bd2127a30e35482a468d80ce Mon Sep 17 00:00:00 2001 From: Sebastiaan van Stijn Date: Mon, 21 Jan 2019 12:07:36 +0100 Subject: [PATCH 15/45] integration-cli: remove deprecated daemonHost() utility Signed-off-by: Sebastiaan van Stijn (cherry picked from commit 3105ca26dc3dc5273e62dec622b8c40a1ae31b91) Signed-off-by: Sebastiaan van Stijn Upstream-commit: 8299d037ca8e2d2d43de56287d31ffb3d9a6ea98 Component: engine --- .../integration-cli/docker_api_attach_test.go | 14 +++++++------- .../integration-cli/docker_api_containers_test.go | 2 +- .../integration-cli/docker_api_exec_resize_test.go | 2 +- .../engine/integration-cli/docker_utils_test.go | 6 ------ 4 files changed, 9 insertions(+), 15 deletions(-) diff --git a/components/engine/integration-cli/docker_api_attach_test.go b/components/engine/integration-cli/docker_api_attach_test.go index ed03f3333b..3600aabc21 100644 --- a/components/engine/integration-cli/docker_api_attach_test.go +++ b/components/engine/integration-cli/docker_api_attach_test.go @@ -26,7 +26,7 @@ func (s *DockerSuite) TestGetContainersAttachWebsocket(c *check.C) { testRequires(c, DaemonIsLinux) out, _ := dockerCmd(c, "run", "-dit", "busybox", "cat") - rwc, err := request.SockConn(time.Duration(10*time.Second), daemonHost()) + rwc, err := request.SockConn(time.Duration(10*time.Second), request.DaemonHost()) c.Assert(err, checker.IsNil) cleanedContainerID := strings.TrimSpace(out) @@ -141,12 +141,12 @@ func (s *DockerSuite) TestPostContainersAttach(c *check.C) { cid, _ := dockerCmd(c, "run", "-di", "busybox", "cat") cid = strings.TrimSpace(cid) // Attach to the container's stdout stream. - conn, br, err := sockRequestHijack("POST", "/containers/"+cid+"/attach?stream=1&stdin=1&stdout=1", nil, "text/plain", daemonHost()) + conn, br, err := sockRequestHijack("POST", "/containers/"+cid+"/attach?stream=1&stdin=1&stdout=1", nil, "text/plain", request.DaemonHost()) c.Assert(err, checker.IsNil) // Check if the data from stdout can be received. expectSuccess(conn, br, "stdout", false) // Attach to the container's stderr stream. - conn, br, err = sockRequestHijack("POST", "/containers/"+cid+"/attach?stream=1&stdin=1&stderr=1", nil, "text/plain", daemonHost()) + conn, br, err = sockRequestHijack("POST", "/containers/"+cid+"/attach?stream=1&stdin=1&stderr=1", nil, "text/plain", request.DaemonHost()) c.Assert(err, checker.IsNil) // Since the container only emits stdout, attaching to stderr should return nothing. expectTimeout(conn, br, "stdout") @@ -154,10 +154,10 @@ func (s *DockerSuite) TestPostContainersAttach(c *check.C) { // Test the similar functions of the stderr stream. cid, _ = dockerCmd(c, "run", "-di", "busybox", "/bin/sh", "-c", "cat >&2") cid = strings.TrimSpace(cid) - conn, br, err = sockRequestHijack("POST", "/containers/"+cid+"/attach?stream=1&stdin=1&stderr=1", nil, "text/plain", daemonHost()) + conn, br, err = sockRequestHijack("POST", "/containers/"+cid+"/attach?stream=1&stdin=1&stderr=1", nil, "text/plain", request.DaemonHost()) c.Assert(err, checker.IsNil) expectSuccess(conn, br, "stderr", false) - conn, br, err = sockRequestHijack("POST", "/containers/"+cid+"/attach?stream=1&stdin=1&stdout=1", nil, "text/plain", daemonHost()) + conn, br, err = sockRequestHijack("POST", "/containers/"+cid+"/attach?stream=1&stdin=1&stdout=1", nil, "text/plain", request.DaemonHost()) c.Assert(err, checker.IsNil) expectTimeout(conn, br, "stderr") @@ -165,12 +165,12 @@ func (s *DockerSuite) TestPostContainersAttach(c *check.C) { cid, _ = dockerCmd(c, "run", "-dit", "busybox", "/bin/sh", "-c", "cat >&2") cid = strings.TrimSpace(cid) // Attach to stdout only. - conn, br, err = sockRequestHijack("POST", "/containers/"+cid+"/attach?stream=1&stdin=1&stdout=1", nil, "text/plain", daemonHost()) + conn, br, err = sockRequestHijack("POST", "/containers/"+cid+"/attach?stream=1&stdin=1&stdout=1", nil, "text/plain", request.DaemonHost()) c.Assert(err, checker.IsNil) expectSuccess(conn, br, "stdout", true) // Attach without stdout stream. - conn, br, err = sockRequestHijack("POST", "/containers/"+cid+"/attach?stream=1&stdin=1&stderr=1", nil, "text/plain", daemonHost()) + conn, br, err = sockRequestHijack("POST", "/containers/"+cid+"/attach?stream=1&stdin=1&stderr=1", nil, "text/plain", request.DaemonHost()) c.Assert(err, checker.IsNil) // Nothing should be received because both the stdout and stderr of the container will be // sent to the client as stdout when tty is enabled. diff --git a/components/engine/integration-cli/docker_api_containers_test.go b/components/engine/integration-cli/docker_api_containers_test.go index e36c655f56..4bd0c1bb54 100644 --- a/components/engine/integration-cli/docker_api_containers_test.go +++ b/components/engine/integration-cli/docker_api_containers_test.go @@ -1442,7 +1442,7 @@ func (s *DockerSuite) TestPutContainerArchiveErrSymlinkInVolumeToReadOnlyRootfs( // directory outside the volume. This should cause an error because the // rootfs is read-only. var httpClient *http.Client - cli, err := client.NewClient(daemonHost(), "v1.20", httpClient, map[string]string{}) + cli, err := client.NewClient(request.DaemonHost(), "v1.20", httpClient, map[string]string{}) c.Assert(err, checker.IsNil) err = cli.CopyToContainer(context.Background(), cID, "/vol2/symlinkToAbsDir", nil, types.CopyToContainerOptions{}) diff --git a/components/engine/integration-cli/docker_api_exec_resize_test.go b/components/engine/integration-cli/docker_api_exec_resize_test.go index 2db3d3e317..70d310aaf2 100644 --- a/components/engine/integration-cli/docker_api_exec_resize_test.go +++ b/components/engine/integration-cli/docker_api_exec_resize_test.go @@ -64,7 +64,7 @@ func (s *DockerSuite) TestExecResizeImmediatelyAfterExecStart(c *check.C) { } payload := bytes.NewBufferString(`{"Tty":true}`) - conn, _, err := sockRequestHijack("POST", fmt.Sprintf("/exec/%s/start", execID), payload, "application/json", daemonHost()) + conn, _, err := sockRequestHijack("POST", fmt.Sprintf("/exec/%s/start", execID), payload, "application/json", request.DaemonHost()) if err != nil { return fmt.Errorf("Failed to start the exec: %q", err.Error()) } diff --git a/components/engine/integration-cli/docker_utils_test.go b/components/engine/integration-cli/docker_utils_test.go index d920077177..732b2ac87c 100644 --- a/components/engine/integration-cli/docker_utils_test.go +++ b/components/engine/integration-cli/docker_utils_test.go @@ -19,16 +19,10 @@ import ( "github.com/docker/docker/integration-cli/checker" "github.com/docker/docker/integration-cli/cli" "github.com/docker/docker/integration-cli/daemon" - "github.com/docker/docker/internal/test/request" "github.com/go-check/check" "gotest.tools/icmd" ) -// Deprecated -func daemonHost() string { - return request.DaemonHost() -} - func deleteImages(images ...string) error { args := []string{dockerBinary, "rmi", "-f"} return icmd.RunCmd(icmd.Cmd{Command: append(args, images...)}).Error From a6c15caac6df3915ef4c9ccbd8238cf9d13a9e6d Mon Sep 17 00:00:00 2001 From: Sebastiaan van Stijn Date: Fri, 28 Dec 2018 16:10:32 +0100 Subject: [PATCH 16/45] Replace deprecated client.WithDialer() Signed-off-by: Sebastiaan van Stijn (cherry picked from commit 8d3feccfa9dd0c0b5d866eba982c89f739b5e5b2) Signed-off-by: Sebastiaan van Stijn Upstream-commit: 2c1307fc901fe13e3b45be71638734bf91a7e70f Component: engine --- components/engine/integration/plugin/authz/authz_plugin_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/components/engine/integration/plugin/authz/authz_plugin_test.go b/components/engine/integration/plugin/authz/authz_plugin_test.go index 53e30a0f10..234b82cbfb 100644 --- a/components/engine/integration/plugin/authz/authz_plugin_test.go +++ b/components/engine/integration/plugin/authz/authz_plugin_test.go @@ -141,7 +141,7 @@ func newTLSAPIClient(host, cacertPath, certPath, keyPath string) (client.APIClie } return client.NewClientWithOpts( client.WithTLSClientConfig(cacertPath, certPath, keyPath), - client.WithDialer(dialer), + client.WithDialContext(dialer.DialContext), client.WithHost(host)) } From 0e40cd84ba872449142319c06b61ea421796e043 Mon Sep 17 00:00:00 2001 From: Yong Tang Date: Wed, 9 Jan 2019 03:08:47 +0000 Subject: [PATCH 17/45] Use poll.WaitOn in authz_plugin_test.go This fix uses poll.WaitOn to replace customerized implementation in authz_plugin_test.go Signed-off-by: Yong Tang (cherry picked from commit 0492b0997b2fc739a9a6fe6831145297d8149e55) Signed-off-by: Sebastiaan van Stijn Upstream-commit: cdb40114b4b50bb86e03210186823895e4454653 Component: engine --- .../integration/plugin/authz/authz_plugin_test.go | 14 ++------------ 1 file changed, 2 insertions(+), 12 deletions(-) diff --git a/components/engine/integration/plugin/authz/authz_plugin_test.go b/components/engine/integration/plugin/authz/authz_plugin_test.go index 234b82cbfb..5408505acd 100644 --- a/components/engine/integration/plugin/authz/authz_plugin_test.go +++ b/components/engine/integration/plugin/authz/authz_plugin_test.go @@ -26,6 +26,7 @@ import ( "github.com/docker/docker/pkg/archive" "github.com/docker/docker/pkg/authorization" "gotest.tools/assert" + "gotest.tools/poll" "gotest.tools/skip" ) @@ -224,18 +225,7 @@ func TestAuthZPluginAllowEventStream(t *testing.T) { // Create a container and wait for the creation events cID := container.Run(t, ctx, c) - - for i := 0; i < 100; i++ { - c, err := c.ContainerInspect(ctx, cID) - assert.NilError(t, err) - if c.State.Running { - break - } - if i == 99 { - t.Fatal("Container didn't run within 10s") - } - time.Sleep(100 * time.Millisecond) - } + poll.WaitOn(t, container.IsInState(ctx, c, cID, "running")) created := false started := false From 4e454ab962c092020175e5eda1eddf1999aae044 Mon Sep 17 00:00:00 2001 From: Sebastiaan van Stijn Date: Sun, 13 Jan 2019 21:11:50 +0100 Subject: [PATCH 18/45] Add missing error-check in TestAPISwarmManagerRestore Signed-off-by: Sebastiaan van Stijn (cherry picked from commit 2e326eba7040042e7b4e9974ebd46aaa6b03dc4f) Signed-off-by: Sebastiaan van Stijn Upstream-commit: 092315055ae1cd24732b913fad53767328b20678 Component: engine --- components/engine/integration-cli/docker_api_swarm_test.go | 3 ++- 1 file changed, 2 insertions(+), 1 deletion(-) diff --git a/components/engine/integration-cli/docker_api_swarm_test.go b/components/engine/integration-cli/docker_api_swarm_test.go index 9be5719c52..2260f2cff1 100644 --- a/components/engine/integration-cli/docker_api_swarm_test.go +++ b/components/engine/integration-cli/docker_api_swarm_test.go @@ -507,7 +507,8 @@ func (s *DockerSwarmSuite) TestAPISwarmManagerRestore(c *check.C) { d3.Start(c) d3.GetService(c, id) - d3.Kill() + err := d3.Kill() + assert.NilError(c, err) time.Sleep(1 * time.Second) // time to handle signal d3.Start(c) d3.GetService(c, id) From d2f16c6807624fc9ff3b49034e9ab9830289e40b Mon Sep 17 00:00:00 2001 From: Sebastiaan van Stijn Date: Mon, 21 Jan 2019 13:16:02 +0100 Subject: [PATCH 19/45] Use assert.NilError() instead of assert.Assert() Signed-off-by: Sebastiaan van Stijn (cherry picked from commit 3449b12cc7eefa8ebd0de6ec8b9803c6ee823af0) Signed-off-by: Sebastiaan van Stijn Upstream-commit: 93de0314c7e44d625d791fa14d7316da6d1fc9c7 Component: engine --- components/engine/client/hijack_test.go | 12 +-- components/engine/daemon/daemon_linux_test.go | 26 +++---- .../daemon/logger/jsonfilelog/read_test.go | 6 +- .../engine/daemon/logger/local/local_test.go | 34 ++++---- .../daemon/logger/loggerutils/logfile_test.go | 4 +- .../plugin/authz/authz_plugin_test.go | 20 ++--- .../plugin/logging/logging_linux_test.go | 6 +- .../integration/plugin/volumes/mounts_test.go | 6 +- .../engine/pkg/tailfile/tailfile_test.go | 24 +++--- .../executor/containerd/containerd_test.go | 6 +- .../volume/service/service_linux_test.go | 16 ++-- .../engine/volume/service/service_test.go | 78 +++++++++---------- .../engine/volume/service/store_test.go | 4 +- 13 files changed, 121 insertions(+), 121 deletions(-) diff --git a/components/engine/client/hijack_test.go b/components/engine/client/hijack_test.go index d71dc9ea38..bc3b158fef 100644 --- a/components/engine/client/hijack_test.go +++ b/components/engine/client/hijack_test.go @@ -61,7 +61,7 @@ func TestTLSCloseWriter(t *testing.T) { break } } - assert.Assert(t, err) + assert.NilError(t, err) ts.Listener = l defer l.Close() @@ -76,13 +76,13 @@ func TestTLSCloseWriter(t *testing.T) { defer ts.Close() serverURL, err := url.Parse(ts.URL) - assert.Assert(t, err) + assert.NilError(t, err) client, err := NewClient("tcp://"+serverURL.Host, "", ts.Client(), nil) - assert.Assert(t, err) + assert.NilError(t, err) resp, err := client.postHijacked(context.Background(), "/asdf", url.Values{}, nil, map[string][]string{"Content-Type": {"text/plain"}}) - assert.Assert(t, err) + assert.NilError(t, err) defer resp.Close() if _, ok := resp.Conn.(types.CloseWriter); !ok { @@ -90,10 +90,10 @@ func TestTLSCloseWriter(t *testing.T) { } _, err = resp.Conn.Write([]byte("hello")) - assert.Assert(t, err) + assert.NilError(t, err) b, err := ioutil.ReadAll(resp.Reader) - assert.Assert(t, err) + assert.NilError(t, err) assert.Assert(t, string(b) == "hello") assert.Assert(t, resp.CloseWrite()) diff --git a/components/engine/daemon/daemon_linux_test.go b/components/engine/daemon/daemon_linux_test.go index 66d6aa20d8..88577a2b82 100644 --- a/components/engine/daemon/daemon_linux_test.go +++ b/components/engine/daemon/daemon_linux_test.go @@ -236,30 +236,30 @@ func TestRootMountCleanup(t *testing.T) { t.Parallel() testRoot, err := ioutil.TempDir("", t.Name()) - assert.Assert(t, err) + assert.NilError(t, err) defer os.RemoveAll(testRoot) cfg := &config.Config{} err = mount.MakePrivate(testRoot) - assert.Assert(t, err) + assert.NilError(t, err) defer mount.Unmount(testRoot) cfg.ExecRoot = filepath.Join(testRoot, "exec") cfg.Root = filepath.Join(testRoot, "daemon") err = os.Mkdir(cfg.ExecRoot, 0755) - assert.Assert(t, err) + assert.NilError(t, err) err = os.Mkdir(cfg.Root, 0755) - assert.Assert(t, err) + assert.NilError(t, err) d := &Daemon{configStore: cfg, root: cfg.Root} unmountFile := getUnmountOnShutdownPath(cfg) t.Run("regular dir no mountpoint", func(t *testing.T) { err = setupDaemonRootPropagation(cfg) - assert.Assert(t, err) + assert.NilError(t, err) _, err = os.Stat(unmountFile) - assert.Assert(t, err) + assert.NilError(t, err) checkMounted(t, cfg.Root, true) assert.Assert(t, d.cleanupMounts()) @@ -271,11 +271,11 @@ func TestRootMountCleanup(t *testing.T) { t.Run("root is a private mountpoint", func(t *testing.T) { err = mount.MakePrivate(cfg.Root) - assert.Assert(t, err) + assert.NilError(t, err) defer mount.Unmount(cfg.Root) err = setupDaemonRootPropagation(cfg) - assert.Assert(t, err) + assert.NilError(t, err) assert.Check(t, ensureShared(cfg.Root)) _, err = os.Stat(unmountFile) @@ -287,11 +287,11 @@ func TestRootMountCleanup(t *testing.T) { // mount is pre-configured with a shared mount t.Run("root is a shared mountpoint", func(t *testing.T) { err = mount.MakeShared(cfg.Root) - assert.Assert(t, err) + assert.NilError(t, err) defer mount.Unmount(cfg.Root) err = setupDaemonRootPropagation(cfg) - assert.Assert(t, err) + assert.NilError(t, err) if _, err := os.Stat(unmountFile); err == nil { t.Fatal("unmount file should not exist") @@ -305,13 +305,13 @@ func TestRootMountCleanup(t *testing.T) { // does not need mount but unmount file exists from previous run t.Run("old mount file is cleaned up on setup if not needed", func(t *testing.T) { err = mount.MakeShared(testRoot) - assert.Assert(t, err) + assert.NilError(t, err) defer mount.MakePrivate(testRoot) err = ioutil.WriteFile(unmountFile, nil, 0644) - assert.Assert(t, err) + assert.NilError(t, err) err = setupDaemonRootPropagation(cfg) - assert.Assert(t, err) + assert.NilError(t, err) _, err = os.Stat(unmountFile) assert.Check(t, os.IsNotExist(err), err) diff --git a/components/engine/daemon/logger/jsonfilelog/read_test.go b/components/engine/daemon/logger/jsonfilelog/read_test.go index cfa8694b19..0206ecb835 100644 --- a/components/engine/daemon/logger/jsonfilelog/read_test.go +++ b/components/engine/daemon/logger/jsonfilelog/read_test.go @@ -77,15 +77,15 @@ func TestEncodeDecode(t *testing.T) { decode := decodeFunc(buf) msg, err := decode() - assert.Assert(t, err) + assert.NilError(t, err) assert.Assert(t, string(msg.Line) == "hello 1\n", string(msg.Line)) msg, err = decode() - assert.Assert(t, err) + assert.NilError(t, err) assert.Assert(t, string(msg.Line) == "hello 2\n") msg, err = decode() - assert.Assert(t, err) + assert.NilError(t, err) assert.Assert(t, string(msg.Line) == "hello 3\n") _, err = decode() diff --git a/components/engine/daemon/logger/local/local_test.go b/components/engine/daemon/logger/local/local_test.go index 2da67bc6fb..6e0520d75e 100644 --- a/components/engine/daemon/logger/local/local_test.go +++ b/components/engine/daemon/logger/local/local_test.go @@ -28,13 +28,13 @@ func TestWriteLog(t *testing.T) { t.Parallel() dir, err := ioutil.TempDir("", t.Name()) - assert.Assert(t, err) + assert.NilError(t, err) defer os.RemoveAll(dir) logPath := filepath.Join(dir, "test.log") l, err := New(logger.Info{LogPath: logPath}) - assert.Assert(t, err) + assert.NilError(t, err) defer l.Close() m1 := logger.Message{Source: "stdout", Timestamp: time.Now().Add(-1 * 30 * time.Minute), Line: []byte("message 1")} @@ -43,14 +43,14 @@ func TestWriteLog(t *testing.T) { // copy the log message because the underying log writer resets the log message and returns it to a buffer pool err = l.Log(copyLogMessage(&m1)) - assert.Assert(t, err) + assert.NilError(t, err) err = l.Log(copyLogMessage(&m2)) - assert.Assert(t, err) + assert.NilError(t, err) err = l.Log(copyLogMessage(&m3)) - assert.Assert(t, err) + assert.NilError(t, err) f, err := os.Open(logPath) - assert.Assert(t, err) + assert.NilError(t, err) defer f.Close() dec := protoio.NewUint32DelimitedReader(f, binary.BigEndian, 1e6) @@ -66,19 +66,19 @@ func TestWriteLog(t *testing.T) { } err = dec.ReadMsg(&proto) - assert.Assert(t, err) + assert.NilError(t, err) messageToProto(&m1, &testProto, &partial) assert.Check(t, is.DeepEqual(testProto, proto), "expected:\n%+v\ngot:\n%+v", testProto, proto) seekMsgLen() err = dec.ReadMsg(&proto) - assert.Assert(t, err) + assert.NilError(t, err) messageToProto(&m2, &testProto, &partial) assert.Check(t, is.DeepEqual(testProto, proto)) seekMsgLen() err = dec.ReadMsg(&proto) - assert.Assert(t, err) + assert.NilError(t, err) messageToProto(&m3, &testProto, &partial) assert.Check(t, is.DeepEqual(testProto, proto), "expected:\n%+v\ngot:\n%+v", testProto, proto) } @@ -87,12 +87,12 @@ func TestReadLog(t *testing.T) { t.Parallel() dir, err := ioutil.TempDir("", t.Name()) - assert.Assert(t, err) + assert.NilError(t, err) defer os.RemoveAll(dir) logPath := filepath.Join(dir, "test.log") l, err := New(logger.Info{LogPath: logPath}) - assert.Assert(t, err) + assert.NilError(t, err) defer l.Close() m1 := logger.Message{Source: "stdout", Timestamp: time.Now().Add(-1 * 30 * time.Minute), Line: []byte("a message")} @@ -103,13 +103,13 @@ func TestReadLog(t *testing.T) { // copy the log message because the underlying log writer resets the log message and returns it to a buffer pool err = l.Log(copyLogMessage(&m1)) - assert.Assert(t, err) + assert.NilError(t, err) err = l.Log(copyLogMessage(&m2)) - assert.Assert(t, err) + assert.NilError(t, err) err = l.Log(copyLogMessage(&m3)) - assert.Assert(t, err) + assert.NilError(t, err) err = l.Log(copyLogMessage(&m4)) - assert.Assert(t, err) + assert.NilError(t, err) lr := l.(logger.LogReader) @@ -121,12 +121,12 @@ func TestReadLog(t *testing.T) { case <-ctx.Done(): assert.Assert(t, ctx.Err()) case err := <-lw.Err: - assert.Assert(t, err) + assert.NilError(t, err) case msg, open := <-lw.Msg: if !open { select { case err := <-lw.Err: - assert.Assert(t, err) + assert.NilError(t, err) default: assert.Assert(t, m == nil) return diff --git a/components/engine/daemon/logger/loggerutils/logfile_test.go b/components/engine/daemon/logger/loggerutils/logfile_test.go index e3e63210fc..ae3a74ced7 100644 --- a/components/engine/daemon/logger/loggerutils/logfile_test.go +++ b/components/engine/daemon/logger/loggerutils/logfile_test.go @@ -60,7 +60,7 @@ func TestTailFiles(t *testing.T) { case <-time.After(60 * time.Second): t.Fatal("timeout waiting for tail line") case err := <-watcher.Err: - assert.Assert(t, err) + assert.NilError(t, err) case msg := <-watcher.Msg: assert.Assert(t, msg != nil) assert.Assert(t, string(msg.Line) == "Roads?", string(msg.Line)) @@ -70,7 +70,7 @@ func TestTailFiles(t *testing.T) { case <-time.After(60 * time.Second): t.Fatal("timeout waiting for tail line") case err := <-watcher.Err: - assert.Assert(t, err) + assert.NilError(t, err) case msg := <-watcher.Msg: assert.Assert(t, msg != nil) assert.Assert(t, string(msg.Line) == "Where we're going we don't need roads.", string(msg.Line)) diff --git a/components/engine/integration/plugin/authz/authz_plugin_test.go b/components/engine/integration/plugin/authz/authz_plugin_test.go index 5408505acd..0cbf045e7c 100644 --- a/components/engine/integration/plugin/authz/authz_plugin_test.go +++ b/components/engine/integration/plugin/authz/authz_plugin_test.go @@ -370,18 +370,18 @@ func TestAuthzPluginEnsureContainerCopyToFrom(t *testing.T) { d.StartWithBusybox(t, "--authorization-plugin="+testAuthZPlugin, "--authorization-plugin="+testAuthZPlugin) dir, err := ioutil.TempDir("", t.Name()) - assert.Assert(t, err) + assert.NilError(t, err) defer os.RemoveAll(dir) f, err := ioutil.TempFile(dir, "send") - assert.Assert(t, err) + assert.NilError(t, err) defer f.Close() buf := make([]byte, 1024) fileSize := len(buf) * 1024 * 10 for written := 0; written < fileSize; { n, err := f.Write(buf) - assert.Assert(t, err) + assert.NilError(t, err) written += n } @@ -392,24 +392,24 @@ func TestAuthzPluginEnsureContainerCopyToFrom(t *testing.T) { defer c.ContainerRemove(ctx, cID, types.ContainerRemoveOptions{Force: true}) _, err = f.Seek(0, io.SeekStart) - assert.Assert(t, err) + assert.NilError(t, err) srcInfo, err := archive.CopyInfoSourcePath(f.Name(), false) - assert.Assert(t, err) + assert.NilError(t, err) srcArchive, err := archive.TarResource(srcInfo) - assert.Assert(t, err) + assert.NilError(t, err) defer srcArchive.Close() dstDir, preparedArchive, err := archive.PrepareArchiveCopy(srcArchive, srcInfo, archive.CopyInfo{Path: "/test"}) - assert.Assert(t, err) + assert.NilError(t, err) err = c.CopyToContainer(ctx, cID, dstDir, preparedArchive, types.CopyToContainerOptions{}) - assert.Assert(t, err) + assert.NilError(t, err) rdr, _, err := c.CopyFromContainer(ctx, cID, "/test") - assert.Assert(t, err) + assert.NilError(t, err) _, err = io.Copy(ioutil.Discard, rdr) - assert.Assert(t, err) + assert.NilError(t, err) } func imageSave(client client.APIClient, path, image string) error { diff --git a/components/engine/integration/plugin/logging/logging_linux_test.go b/components/engine/integration/plugin/logging/logging_linux_test.go index eadc524503..edddb1a42e 100644 --- a/components/engine/integration/plugin/logging/logging_linux_test.go +++ b/components/engine/integration/plugin/logging/logging_linux_test.go @@ -45,7 +45,7 @@ func TestContinueAfterPluginCrash(t *testing.T) { // Attach to the container to make sure it's written a few times to stdout attach, err := client.ContainerAttach(context.Background(), id, types.ContainerAttachOptions{Stream: true, Stdout: true}) - assert.Assert(t, err) + assert.NilError(t, err) chErr := make(chan error) go func() { @@ -62,7 +62,7 @@ func TestContinueAfterPluginCrash(t *testing.T) { select { case err := <-chErr: - assert.Assert(t, err) + assert.NilError(t, err) case <-time.After(60 * time.Second): t.Fatal("timeout waiting for container i/o") } @@ -71,7 +71,7 @@ func TestContinueAfterPluginCrash(t *testing.T) { // TODO(@cpuguy83): This is horribly hacky but is the only way to really test this case right now. // It would be nice if there was a way to know that a broken pipe has occurred without looking through the logs. log, err := os.Open(d.LogFileName()) - assert.Assert(t, err) + assert.NilError(t, err) scanner := bufio.NewScanner(log) for scanner.Scan() { assert.Assert(t, !strings.Contains(scanner.Text(), "broken pipe")) diff --git a/components/engine/integration/plugin/volumes/mounts_test.go b/components/engine/integration/plugin/volumes/mounts_test.go index e648ef6f14..ab2d585ca7 100644 --- a/components/engine/integration/plugin/volumes/mounts_test.go +++ b/components/engine/integration/plugin/volumes/mounts_test.go @@ -28,7 +28,7 @@ func TestPluginWithDevMounts(t *testing.T) { ctx := context.Background() testDir, err := ioutil.TempDir("", "test-dir") - assert.Assert(t, err) + assert.NilError(t, err) defer os.RemoveAll(testDir) createPlugin(t, c, "test", "dummy", asVolumeDriver, func(c *plugin.Config) { @@ -46,13 +46,13 @@ func TestPluginWithDevMounts(t *testing.T) { }) err = c.PluginEnable(ctx, "test", types.PluginEnableOptions{Timeout: 30}) - assert.Assert(t, err) + assert.NilError(t, err) defer func() { err := c.PluginRemove(ctx, "test", types.PluginRemoveOptions{Force: true}) assert.Check(t, err) }() p, _, err := c.PluginInspectWithRaw(ctx, "test") - assert.Assert(t, err) + assert.NilError(t, err) assert.Assert(t, p.Enabled) } diff --git a/components/engine/pkg/tailfile/tailfile_test.go b/components/engine/pkg/tailfile/tailfile_test.go index 4dde90f9e3..6a2af28a62 100644 --- a/components/engine/pkg/tailfile/tailfile_test.go +++ b/components/engine/pkg/tailfile/tailfile_test.go @@ -232,11 +232,11 @@ func TestNewTailReader(t *testing.T) { assert.Assert(t, lines == 0) return } - assert.Assert(t, err) + assert.NilError(t, err) assert.Check(t, lines == i, "%d -- %d", lines, i) b, err := ioutil.ReadAll(tr) - assert.Assert(t, err) + assert.NilError(t, err) expectLines := test.data[len(test.data)-i:] assert.Check(t, len(expectLines) == i) @@ -260,10 +260,10 @@ func TestNewTailReader(t *testing.T) { return } - assert.Assert(t, err) + assert.NilError(t, err) assert.Check(t, lines == len(test.data), "%d -- %d", lines, len(test.data)) b, err := ioutil.ReadAll(tr) - assert.Assert(t, err) + assert.NilError(t, err) assert.Check(t, bytes.Equal(b, []byte(s)), "\n%v\n%v", b, []byte(s)) }) }) @@ -273,16 +273,16 @@ func TestNewTailReader(t *testing.T) { t.Run("truncated last line", func(t *testing.T) { t.Run("more than available", func(t *testing.T) { tail, nLines, err := NewTailReader(ctx, strings.NewReader("a\nb\nextra"), 3) - assert.Assert(t, err) + assert.NilError(t, err) assert.Check(t, nLines == 2, nLines) rdr := bufio.NewReader(tail) data, _, err := rdr.ReadLine() - assert.Assert(t, err) + assert.NilError(t, err) assert.Check(t, string(data) == "a", string(data)) data, _, err = rdr.ReadLine() - assert.Assert(t, err) + assert.NilError(t, err) assert.Check(t, string(data) == "b", string(data)) _, _, err = rdr.ReadLine() @@ -292,16 +292,16 @@ func TestNewTailReader(t *testing.T) { t.Run("truncated last line", func(t *testing.T) { t.Run("exact", func(t *testing.T) { tail, nLines, err := NewTailReader(ctx, strings.NewReader("a\nb\nextra"), 2) - assert.Assert(t, err) + assert.NilError(t, err) assert.Check(t, nLines == 2, nLines) rdr := bufio.NewReader(tail) data, _, err := rdr.ReadLine() - assert.Assert(t, err) + assert.NilError(t, err) assert.Check(t, string(data) == "a", string(data)) data, _, err = rdr.ReadLine() - assert.Assert(t, err) + assert.NilError(t, err) assert.Check(t, string(data) == "b", string(data)) _, _, err = rdr.ReadLine() @@ -312,12 +312,12 @@ func TestNewTailReader(t *testing.T) { t.Run("truncated last line", func(t *testing.T) { t.Run("one line", func(t *testing.T) { tail, nLines, err := NewTailReader(ctx, strings.NewReader("a\nb\nextra"), 1) - assert.Assert(t, err) + assert.NilError(t, err) assert.Check(t, nLines == 1, nLines) rdr := bufio.NewReader(tail) data, _, err := rdr.ReadLine() - assert.Assert(t, err) + assert.NilError(t, err) assert.Check(t, string(data) == "b", string(data)) _, _, err = rdr.ReadLine() diff --git a/components/engine/plugin/executor/containerd/containerd_test.go b/components/engine/plugin/executor/containerd/containerd_test.go index e27063b1d8..3fb45981f3 100644 --- a/components/engine/plugin/executor/containerd/containerd_test.go +++ b/components/engine/plugin/executor/containerd/containerd_test.go @@ -28,7 +28,7 @@ func TestLifeCycle(t *testing.T) { mock.simulateStartError(false, id) err = exec.Create(id, specs.Spec{}, nil, nil) - assert.Assert(t, err) + assert.NilError(t, err) running, _ := exec.IsRunning(id) assert.Assert(t, running) @@ -39,12 +39,12 @@ func TestLifeCycle(t *testing.T) { mock.HandleExitEvent(id) // simulate a plugin that exits err = exec.Create(id, specs.Spec{}, nil, nil) - assert.Assert(t, err) + assert.NilError(t, err) } func setupTest(t *testing.T, client Client, eh ExitHandler) (*Executor, func()) { rootDir, err := ioutil.TempDir("", "test-daemon") - assert.Assert(t, err) + assert.NilError(t, err) assert.Assert(t, client != nil) assert.Assert(t, eh != nil) diff --git a/components/engine/volume/service/service_linux_test.go b/components/engine/volume/service/service_linux_test.go index e009cd1325..31b3f81e2c 100644 --- a/components/engine/volume/service/service_linux_test.go +++ b/components/engine/volume/service/service_linux_test.go @@ -22,11 +22,11 @@ func TestLocalVolumeSize(t *testing.T) { ds := volumedrivers.NewStore(nil) dir, err := ioutil.TempDir("", t.Name()) - assert.Assert(t, err) + assert.NilError(t, err) defer os.RemoveAll(dir) l, err := local.New(dir, idtools.Identity{UID: os.Getuid(), GID: os.Getegid()}) - assert.Assert(t, err) + assert.NilError(t, err) assert.Assert(t, ds.Register(l, volume.DefaultDriverName)) assert.Assert(t, ds.Register(testutils.NewFakeDriver("fake"), "fake")) @@ -35,20 +35,20 @@ func TestLocalVolumeSize(t *testing.T) { ctx := context.Background() v1, err := service.Create(ctx, "test1", volume.DefaultDriverName, opts.WithCreateReference("foo")) - assert.Assert(t, err) + assert.NilError(t, err) v2, err := service.Create(ctx, "test2", volume.DefaultDriverName) - assert.Assert(t, err) + assert.NilError(t, err) _, err = service.Create(ctx, "test3", "fake") - assert.Assert(t, err) + assert.NilError(t, err) data := make([]byte, 1024) err = ioutil.WriteFile(filepath.Join(v1.Mountpoint, "data"), data, 0644) - assert.Assert(t, err) + assert.NilError(t, err) err = ioutil.WriteFile(filepath.Join(v2.Mountpoint, "data"), data[:1], 0644) - assert.Assert(t, err) + assert.NilError(t, err) ls, err := service.LocalVolumesSize(ctx) - assert.Assert(t, err) + assert.NilError(t, err) assert.Assert(t, is.Len(ls, 2)) for _, v := range ls { diff --git a/components/engine/volume/service/service_test.go b/components/engine/volume/service/service_test.go index 870d19f8a0..64a17ad9c7 100644 --- a/components/engine/volume/service/service_test.go +++ b/components/engine/volume/service/service_test.go @@ -31,10 +31,10 @@ func TestServiceCreate(t *testing.T) { assert.Assert(t, errdefs.IsNotFound(err), err) v, err := service.Create(ctx, "v1", "d1") - assert.Assert(t, err) + assert.NilError(t, err) vCopy, err := service.Create(ctx, "v1", "d1") - assert.Assert(t, err) + assert.NilError(t, err) assert.Assert(t, is.DeepEqual(v, vCopy)) _, err = service.Create(ctx, "v1", "d2") @@ -43,9 +43,9 @@ func TestServiceCreate(t *testing.T) { assert.Assert(t, service.Remove(ctx, "v1")) _, err = service.Create(ctx, "v1", "d2") - assert.Assert(t, err) + assert.NilError(t, err) _, err = service.Create(ctx, "v1", "d2") - assert.Assert(t, err) + assert.NilError(t, err) } @@ -62,45 +62,45 @@ func TestServiceList(t *testing.T) { ctx := context.Background() _, err := service.Create(ctx, "v1", "d1") - assert.Assert(t, err) + assert.NilError(t, err) _, err = service.Create(ctx, "v2", "d1") - assert.Assert(t, err) + assert.NilError(t, err) _, err = service.Create(ctx, "v3", "d2") - assert.Assert(t, err) + assert.NilError(t, err) ls, _, err := service.List(ctx, filters.NewArgs(filters.Arg("driver", "d1"))) - assert.Assert(t, err) + assert.NilError(t, err) assert.Check(t, is.Len(ls, 2)) ls, _, err = service.List(ctx, filters.NewArgs(filters.Arg("driver", "d2"))) - assert.Assert(t, err) + assert.NilError(t, err) assert.Check(t, is.Len(ls, 1)) ls, _, err = service.List(ctx, filters.NewArgs(filters.Arg("driver", "notexist"))) - assert.Assert(t, err) + assert.NilError(t, err) assert.Check(t, is.Len(ls, 0)) ls, _, err = service.List(ctx, filters.NewArgs(filters.Arg("dangling", "true"))) - assert.Assert(t, err) + assert.NilError(t, err) assert.Check(t, is.Len(ls, 3)) ls, _, err = service.List(ctx, filters.NewArgs(filters.Arg("dangling", "false"))) - assert.Assert(t, err) + assert.NilError(t, err) assert.Check(t, is.Len(ls, 0)) _, err = service.Get(ctx, "v1", opts.WithGetReference("foo")) - assert.Assert(t, err) + assert.NilError(t, err) ls, _, err = service.List(ctx, filters.NewArgs(filters.Arg("dangling", "true"))) - assert.Assert(t, err) + assert.NilError(t, err) assert.Check(t, is.Len(ls, 2)) ls, _, err = service.List(ctx, filters.NewArgs(filters.Arg("dangling", "false"))) - assert.Assert(t, err) + assert.NilError(t, err) assert.Check(t, is.Len(ls, 1)) ls, _, err = service.List(ctx, filters.NewArgs(filters.Arg("dangling", "false"), filters.Arg("driver", "d2"))) - assert.Assert(t, err) + assert.NilError(t, err) assert.Check(t, is.Len(ls, 0)) ls, _, err = service.List(ctx, filters.NewArgs(filters.Arg("dangling", "true"), filters.Arg("driver", "d2"))) - assert.Assert(t, err) + assert.NilError(t, err) assert.Check(t, is.Len(ls, 1)) } @@ -115,7 +115,7 @@ func TestServiceRemove(t *testing.T) { ctx := context.Background() _, err := service.Create(ctx, "test", "d1") - assert.Assert(t, err) + assert.NilError(t, err) assert.Assert(t, service.Remove(ctx, "test")) assert.Assert(t, service.Remove(ctx, "test", opts.WithPurgeOnError(true))) @@ -136,15 +136,15 @@ func TestServiceGet(t *testing.T) { assert.Check(t, v == nil) created, err := service.Create(ctx, "test", "d1") - assert.Assert(t, err) + assert.NilError(t, err) assert.Assert(t, created != nil) v, err = service.Get(ctx, "test") - assert.Assert(t, err) + assert.NilError(t, err) assert.Assert(t, is.DeepEqual(created, v)) v, err = service.Get(ctx, "test", opts.WithGetResolveStatus) - assert.Assert(t, err) + assert.NilError(t, err) assert.Assert(t, is.Len(v.Status, 1), v.Status) v, err = service.Get(ctx, "test", opts.WithGetDriver("notarealdriver")) @@ -170,16 +170,16 @@ func TestServicePrune(t *testing.T) { ctx := context.Background() _, err := service.Create(ctx, "test", volume.DefaultDriverName) - assert.Assert(t, err) + assert.NilError(t, err) _, err = service.Create(ctx, "test2", "other") - assert.Assert(t, err) + assert.NilError(t, err) pr, err := service.Prune(ctx, filters.NewArgs(filters.Arg("label", "banana"))) - assert.Assert(t, err) + assert.NilError(t, err) assert.Assert(t, is.Len(pr.VolumesDeleted, 0)) pr, err = service.Prune(ctx, filters.NewArgs()) - assert.Assert(t, err) + assert.NilError(t, err) assert.Assert(t, is.Len(pr.VolumesDeleted, 1)) assert.Assert(t, is.Equal(pr.VolumesDeleted[0], "test")) @@ -187,48 +187,48 @@ func TestServicePrune(t *testing.T) { assert.Assert(t, IsNotExist(err), err) v, err := service.Get(ctx, "test2") - assert.Assert(t, err) + assert.NilError(t, err) assert.Assert(t, is.Equal(v.Driver, "other")) _, err = service.Create(ctx, "test", volume.DefaultDriverName) - assert.Assert(t, err) + assert.NilError(t, err) pr, err = service.Prune(ctx, filters.NewArgs(filters.Arg("label!", "banana"))) - assert.Assert(t, err) + assert.NilError(t, err) assert.Assert(t, is.Len(pr.VolumesDeleted, 1)) assert.Assert(t, is.Equal(pr.VolumesDeleted[0], "test")) v, err = service.Get(ctx, "test2") - assert.Assert(t, err) + assert.NilError(t, err) assert.Assert(t, is.Equal(v.Driver, "other")) _, err = service.Create(ctx, "test", volume.DefaultDriverName, opts.WithCreateLabels(map[string]string{"banana": ""})) - assert.Assert(t, err) + assert.NilError(t, err) pr, err = service.Prune(ctx, filters.NewArgs(filters.Arg("label!", "banana"))) - assert.Assert(t, err) + assert.NilError(t, err) assert.Assert(t, is.Len(pr.VolumesDeleted, 0)) _, err = service.Create(ctx, "test3", volume.DefaultDriverName, opts.WithCreateLabels(map[string]string{"banana": "split"})) - assert.Assert(t, err) + assert.NilError(t, err) pr, err = service.Prune(ctx, filters.NewArgs(filters.Arg("label!", "banana=split"))) - assert.Assert(t, err) + assert.NilError(t, err) assert.Assert(t, is.Len(pr.VolumesDeleted, 1)) assert.Assert(t, is.Equal(pr.VolumesDeleted[0], "test")) pr, err = service.Prune(ctx, filters.NewArgs(filters.Arg("label", "banana=split"))) - assert.Assert(t, err) + assert.NilError(t, err) assert.Assert(t, is.Len(pr.VolumesDeleted, 1)) assert.Assert(t, is.Equal(pr.VolumesDeleted[0], "test3")) v, err = service.Create(ctx, "test", volume.DefaultDriverName, opts.WithCreateReference(t.Name())) - assert.Assert(t, err) + assert.NilError(t, err) pr, err = service.Prune(ctx, filters.NewArgs()) - assert.Assert(t, err) + assert.NilError(t, err) assert.Assert(t, is.Len(pr.VolumesDeleted, 0)) assert.Assert(t, service.Release(ctx, v.Name, t.Name())) pr, err = service.Prune(ctx, filters.NewArgs()) - assert.Assert(t, err) + assert.NilError(t, err) assert.Assert(t, is.Len(pr.VolumesDeleted, 1)) assert.Assert(t, is.Equal(pr.VolumesDeleted[0], "test")) } @@ -237,10 +237,10 @@ func newTestService(t *testing.T, ds *volumedrivers.Store) (*VolumesService, fun t.Helper() dir, err := ioutil.TempDir("", t.Name()) - assert.Assert(t, err) + assert.NilError(t, err) store, err := NewStore(dir, ds) - assert.Assert(t, err) + assert.NilError(t, err) s := &VolumesService{vs: store, eventLogger: dummyEventLogger{}} return s, func() { assert.Check(t, s.Shutdown()) diff --git a/components/engine/volume/service/store_test.go b/components/engine/volume/service/store_test.go index 53345f318b..59a314d69b 100644 --- a/components/engine/volume/service/store_test.go +++ b/components/engine/volume/service/store_test.go @@ -179,12 +179,12 @@ func TestFindByReferenced(t *testing.T) { } dangling, _, err := s.Find(ctx, ByReferenced(false)) - assert.Assert(t, err) + assert.NilError(t, err) assert.Assert(t, len(dangling) == 1) assert.Check(t, dangling[0].Name() == "fake2") used, _, err := s.Find(ctx, ByReferenced(true)) - assert.Assert(t, err) + assert.NilError(t, err) assert.Assert(t, len(used) == 1) assert.Check(t, used[0].Name() == "fake1") } From 3153dc5a378badc27557eb5242562e94912d84ae Mon Sep 17 00:00:00 2001 From: Sebastiaan van Stijn Date: Mon, 21 Jan 2019 12:32:56 +0100 Subject: [PATCH 20/45] Remove use of deprecated client.NewClient() Signed-off-by: Sebastiaan van Stijn (cherry picked from commit 3a4bb96ab74125c95702b818725ba92a27e3a450) Signed-off-by: Sebastiaan van Stijn Upstream-commit: fd6a4681ee906890145556a497a81a914c6aed75 Component: engine --- components/engine/client/hijack_test.go | 2 +- .../engine/integration-cli/docker_api_containers_test.go | 3 +-- components/engine/integration-cli/docker_cli_daemon_test.go | 5 +---- 3 files changed, 3 insertions(+), 7 deletions(-) diff --git a/components/engine/client/hijack_test.go b/components/engine/client/hijack_test.go index bc3b158fef..255f818501 100644 --- a/components/engine/client/hijack_test.go +++ b/components/engine/client/hijack_test.go @@ -78,7 +78,7 @@ func TestTLSCloseWriter(t *testing.T) { serverURL, err := url.Parse(ts.URL) assert.NilError(t, err) - client, err := NewClient("tcp://"+serverURL.Host, "", ts.Client(), nil) + client, err := NewClientWithOpts(WithHost("tcp://"+serverURL.Host), WithHTTPClient(ts.Client())) assert.NilError(t, err) resp, err := client.postHijacked(context.Background(), "/asdf", url.Values{}, nil, map[string][]string{"Content-Type": {"text/plain"}}) diff --git a/components/engine/integration-cli/docker_api_containers_test.go b/components/engine/integration-cli/docker_api_containers_test.go index 4bd0c1bb54..164877bc2b 100644 --- a/components/engine/integration-cli/docker_api_containers_test.go +++ b/components/engine/integration-cli/docker_api_containers_test.go @@ -1441,8 +1441,7 @@ func (s *DockerSuite) TestPutContainerArchiveErrSymlinkInVolumeToReadOnlyRootfs( // Attempt to extract to a symlink in the volume which points to a // directory outside the volume. This should cause an error because the // rootfs is read-only. - var httpClient *http.Client - cli, err := client.NewClient(request.DaemonHost(), "v1.20", httpClient, map[string]string{}) + cli, err := client.NewClientWithOpts(client.FromEnv, client.WithVersion("v1.20")) c.Assert(err, checker.IsNil) err = cli.CopyToContainer(context.Background(), cID, "/vol2/symlinkToAbsDir", nil, types.CopyToContainerOptions{}) diff --git a/components/engine/integration-cli/docker_cli_daemon_test.go b/components/engine/integration-cli/docker_cli_daemon_test.go index 6431280732..a1944af493 100644 --- a/components/engine/integration-cli/docker_cli_daemon_test.go +++ b/components/engine/integration-cli/docker_cli_daemon_test.go @@ -24,9 +24,7 @@ import ( "time" "github.com/cloudflare/cfssl/helpers" - "github.com/docker/docker/api" "github.com/docker/docker/api/types" - "github.com/docker/docker/client" moby_daemon "github.com/docker/docker/daemon" "github.com/docker/docker/integration-cli/checker" "github.com/docker/docker/integration-cli/cli" @@ -3007,8 +3005,7 @@ func (s *DockerDaemonSuite) TestFailedPluginRemove(c *check.C) { testRequires(c, DaemonIsLinux, IsAmd64, SameHostDaemon) d := daemon.New(c, dockerBinary, dockerdBinary) d.Start(c) - cli, err := client.NewClient(d.Sock(), api.DefaultVersion, nil, nil) - c.Assert(err, checker.IsNil) + cli := d.NewClientT(c) ctx, cancel := context.WithTimeout(context.Background(), 300*time.Second) defer cancel() From 9295462ecc2adb1e1f0dc13e1312a7d9e46dda0b Mon Sep 17 00:00:00 2001 From: Brian Goff Date: Wed, 6 Feb 2019 15:33:07 -0800 Subject: [PATCH 21/45] Completely remove `d.NewClient` from testing tools Favor `d.NewClientT` instead. Signed-off-by: Brian Goff (cherry picked from commit e063099f918a01891db4389aaa6ba843e5d37fa9) Signed-off-by: Sebastiaan van Stijn Upstream-commit: 1efe4720feb93c7f47d717001091279636f2039e Component: engine --- .../integration-cli/docker_api_swarm_test.go | 16 +++---- .../integration-cli/docker_cli_swarm_test.go | 4 +- .../integration/network/service_test.go | 4 +- .../engine/integration/service/plugin_test.go | 48 +++++++++---------- .../engine/internal/test/daemon/daemon.go | 9 ---- .../engine/internal/test/daemon/plugin.go | 28 +++++------ .../engine/internal/test/daemon/swarm.go | 31 ++++++------ 7 files changed, 64 insertions(+), 76 deletions(-) diff --git a/components/engine/integration-cli/docker_api_swarm_test.go b/components/engine/integration-cli/docker_api_swarm_test.go index 2260f2cff1..c48e669c0d 100644 --- a/components/engine/integration-cli/docker_api_swarm_test.go +++ b/components/engine/integration-cli/docker_api_swarm_test.go @@ -47,7 +47,7 @@ func (s *DockerSwarmSuite) TestAPISwarmInit(c *check.C) { c.Assert(info.LocalNodeState, checker.Equals, swarm.LocalNodeStateActive) // Leaving cluster - c.Assert(d2.SwarmLeave(false), checker.IsNil) + c.Assert(d2.SwarmLeave(c, false), checker.IsNil) info = d2.SwarmInfo(c) c.Assert(info.ControlAvailable, checker.False) @@ -115,7 +115,7 @@ func (s *DockerSwarmSuite) TestAPISwarmJoinToken(c *check.C) { }) info = d2.SwarmInfo(c) c.Assert(info.LocalNodeState, checker.Equals, swarm.LocalNodeStateActive) - c.Assert(d2.SwarmLeave(false), checker.IsNil) + c.Assert(d2.SwarmLeave(c, false), checker.IsNil) info = d2.SwarmInfo(c) c.Assert(info.LocalNodeState, checker.Equals, swarm.LocalNodeStateInactive) @@ -137,7 +137,7 @@ func (s *DockerSwarmSuite) TestAPISwarmJoinToken(c *check.C) { d2.SwarmJoin(c, swarm.JoinRequest{JoinToken: workerToken, RemoteAddrs: []string{d1.SwarmListenAddr()}}) info = d2.SwarmInfo(c) c.Assert(info.LocalNodeState, checker.Equals, swarm.LocalNodeStateActive) - c.Assert(d2.SwarmLeave(false), checker.IsNil) + c.Assert(d2.SwarmLeave(c, false), checker.IsNil) info = d2.SwarmInfo(c) c.Assert(info.LocalNodeState, checker.Equals, swarm.LocalNodeStateInactive) @@ -156,7 +156,7 @@ func (s *DockerSwarmSuite) TestAPISwarmJoinToken(c *check.C) { d2.SwarmJoin(c, swarm.JoinRequest{JoinToken: workerToken, RemoteAddrs: []string{d1.SwarmListenAddr()}}) info = d2.SwarmInfo(c) c.Assert(info.LocalNodeState, checker.Equals, swarm.LocalNodeStateActive) - c.Assert(d2.SwarmLeave(false), checker.IsNil) + c.Assert(d2.SwarmLeave(c, false), checker.IsNil) info = d2.SwarmInfo(c) c.Assert(info.LocalNodeState, checker.Equals, swarm.LocalNodeStateInactive) } @@ -423,8 +423,8 @@ func (s *DockerSwarmSuite) TestAPISwarmLeaveRemovesContainer(c *check.C) { waitAndAssert(c, defaultReconciliationTimeout, d.CheckActiveContainerCount, checker.Equals, instances+1) - c.Assert(d.SwarmLeave(false), checker.NotNil) - c.Assert(d.SwarmLeave(true), checker.IsNil) + c.Assert(d.SwarmLeave(c, false), checker.NotNil) + c.Assert(d.SwarmLeave(c, true), checker.IsNil) waitAndAssert(c, defaultReconciliationTimeout, d.CheckActiveContainerCount, checker.Equals, 1) @@ -454,7 +454,7 @@ func (s *DockerSwarmSuite) TestAPISwarmLeaveOnPendingJoin(c *check.C) { info := d2.SwarmInfo(c) c.Assert(info.LocalNodeState, checker.Equals, swarm.LocalNodeStatePending) - c.Assert(d2.SwarmLeave(true), checker.IsNil) + c.Assert(d2.SwarmLeave(c, true), checker.IsNil) waitAndAssert(c, defaultReconciliationTimeout, d2.CheckActiveContainerCount, checker.Equals, 1) @@ -878,7 +878,7 @@ func (s *DockerSwarmSuite) TestAPISwarmServicesUpdateWithName(c *check.C) { // Unlocking an unlocked swarm results in an error func (s *DockerSwarmSuite) TestAPISwarmUnlockNotLocked(c *check.C) { d := s.AddDaemon(c, true, true) - err := d.SwarmUnlock(swarm.UnlockRequest{UnlockKey: "wrong-key"}) + err := d.SwarmUnlock(c, swarm.UnlockRequest{UnlockKey: "wrong-key"}) c.Assert(err, checker.NotNil) c.Assert(err.Error(), checker.Contains, "swarm is not locked") } diff --git a/components/engine/integration-cli/docker_cli_swarm_test.go b/components/engine/integration-cli/docker_cli_swarm_test.go index dafe8c96ad..4ee946f795 100644 --- a/components/engine/integration-cli/docker_cli_swarm_test.go +++ b/components/engine/integration-cli/docker_cli_swarm_test.go @@ -116,7 +116,7 @@ func (s *DockerSwarmSuite) TestSwarmInit(c *check.C) { c.Assert(spec.CAConfig.ExternalCAs[0].CACert, checker.Equals, "") c.Assert(spec.CAConfig.ExternalCAs[1].CACert, checker.Equals, string(expected)) - c.Assert(d.SwarmLeave(true), checker.IsNil) + c.Assert(d.SwarmLeave(c, true), checker.IsNil) cli.Docker(cli.Args("swarm", "init"), cli.Daemon(d)).Assert(c, icmd.Success) spec = getSpec() @@ -426,7 +426,7 @@ func (s *DockerSwarmSuite) TestOverlayAttachableOnSwarmLeave(c *check.C) { c.Assert(err, checker.IsNil, check.Commentf("%s", out)) // Leave the swarm - c.Assert(d.SwarmLeave(true), checker.IsNil) + c.Assert(d.SwarmLeave(c, true), checker.IsNil) // Check the container is disconnected out, err = d.Cmd("inspect", "c1", "--format", "{{.NetworkSettings.Networks."+nwName+"}}") diff --git a/components/engine/integration/network/service_test.go b/components/engine/integration/network/service_test.go index a65d27564c..13f471446c 100644 --- a/components/engine/integration/network/service_test.go +++ b/components/engine/integration/network/service_test.go @@ -365,7 +365,7 @@ func TestServiceWithDefaultAddressPoolInit(t *testing.T) { err = cli.ServiceRemove(context.Background(), serviceID) assert.NilError(t, err) - d.SwarmLeave(true) + d.SwarmLeave(t, true) d.Stop(t) // Clean up , set it back to original one to make sure other tests don't fail @@ -373,6 +373,6 @@ func TestServiceWithDefaultAddressPoolInit(t *testing.T) { ops = append(ops, daemon.WithSwarmDefaultAddrPool(ipAddr)) ops = append(ops, daemon.WithSwarmDefaultAddrPoolSubnetSize(24)) d = swarm.NewSwarm(t, testEnv, ops...) - d.SwarmLeave(true) + d.SwarmLeave(t, true) defer d.Stop(t) } diff --git a/components/engine/integration/service/plugin_test.go b/components/engine/integration/service/plugin_test.go index e476c2f1f4..16f0be567e 100644 --- a/components/engine/integration/service/plugin_test.go +++ b/components/engine/integration/service/plugin_test.go @@ -64,45 +64,45 @@ func TestServicePlugin(t *testing.T) { defer d3.Stop(t) id := d1.CreateService(t, makePlugin(repo, name, nil)) - poll.WaitOn(t, d1.PluginIsRunning(name), swarm.ServicePoll) - poll.WaitOn(t, d2.PluginIsRunning(name), swarm.ServicePoll) - poll.WaitOn(t, d3.PluginIsRunning(name), swarm.ServicePoll) + poll.WaitOn(t, d1.PluginIsRunning(t, name), swarm.ServicePoll) + poll.WaitOn(t, d2.PluginIsRunning(t, name), swarm.ServicePoll) + poll.WaitOn(t, d3.PluginIsRunning(t, name), swarm.ServicePoll) service := d1.GetService(t, id) d1.UpdateService(t, service, makePlugin(repo2, name, nil)) - poll.WaitOn(t, d1.PluginReferenceIs(name, repo2), swarm.ServicePoll) - poll.WaitOn(t, d2.PluginReferenceIs(name, repo2), swarm.ServicePoll) - poll.WaitOn(t, d3.PluginReferenceIs(name, repo2), swarm.ServicePoll) - poll.WaitOn(t, d1.PluginIsRunning(name), swarm.ServicePoll) - poll.WaitOn(t, d2.PluginIsRunning(name), swarm.ServicePoll) - poll.WaitOn(t, d3.PluginIsRunning(name), swarm.ServicePoll) + poll.WaitOn(t, d1.PluginReferenceIs(t, name, repo2), swarm.ServicePoll) + poll.WaitOn(t, d2.PluginReferenceIs(t, name, repo2), swarm.ServicePoll) + poll.WaitOn(t, d3.PluginReferenceIs(t, name, repo2), swarm.ServicePoll) + poll.WaitOn(t, d1.PluginIsRunning(t, name), swarm.ServicePoll) + poll.WaitOn(t, d2.PluginIsRunning(t, name), swarm.ServicePoll) + poll.WaitOn(t, d3.PluginIsRunning(t, name), swarm.ServicePoll) d1.RemoveService(t, id) - poll.WaitOn(t, d1.PluginIsNotPresent(name), swarm.ServicePoll) - poll.WaitOn(t, d2.PluginIsNotPresent(name), swarm.ServicePoll) - poll.WaitOn(t, d3.PluginIsNotPresent(name), swarm.ServicePoll) + poll.WaitOn(t, d1.PluginIsNotPresent(t, name), swarm.ServicePoll) + poll.WaitOn(t, d2.PluginIsNotPresent(t, name), swarm.ServicePoll) + poll.WaitOn(t, d3.PluginIsNotPresent(t, name), swarm.ServicePoll) // constrain to managers only id = d1.CreateService(t, makePlugin(repo, name, []string{"node.role==manager"})) - poll.WaitOn(t, d1.PluginIsRunning(name), swarm.ServicePoll) - poll.WaitOn(t, d2.PluginIsRunning(name), swarm.ServicePoll) - poll.WaitOn(t, d3.PluginIsNotPresent(name), swarm.ServicePoll) + poll.WaitOn(t, d1.PluginIsRunning(t, name), swarm.ServicePoll) + poll.WaitOn(t, d2.PluginIsRunning(t, name), swarm.ServicePoll) + poll.WaitOn(t, d3.PluginIsNotPresent(t, name), swarm.ServicePoll) d1.RemoveService(t, id) - poll.WaitOn(t, d1.PluginIsNotPresent(name), swarm.ServicePoll) - poll.WaitOn(t, d2.PluginIsNotPresent(name), swarm.ServicePoll) - poll.WaitOn(t, d3.PluginIsNotPresent(name), swarm.ServicePoll) + poll.WaitOn(t, d1.PluginIsNotPresent(t, name), swarm.ServicePoll) + poll.WaitOn(t, d2.PluginIsNotPresent(t, name), swarm.ServicePoll) + poll.WaitOn(t, d3.PluginIsNotPresent(t, name), swarm.ServicePoll) // with no name id = d1.CreateService(t, makePlugin(repo, "", nil)) - poll.WaitOn(t, d1.PluginIsRunning(repo), swarm.ServicePoll) - poll.WaitOn(t, d2.PluginIsRunning(repo), swarm.ServicePoll) - poll.WaitOn(t, d3.PluginIsRunning(repo), swarm.ServicePoll) + poll.WaitOn(t, d1.PluginIsRunning(t, repo), swarm.ServicePoll) + poll.WaitOn(t, d2.PluginIsRunning(t, repo), swarm.ServicePoll) + poll.WaitOn(t, d3.PluginIsRunning(t, repo), swarm.ServicePoll) d1.RemoveService(t, id) - poll.WaitOn(t, d1.PluginIsNotPresent(repo), swarm.ServicePoll) - poll.WaitOn(t, d2.PluginIsNotPresent(repo), swarm.ServicePoll) - poll.WaitOn(t, d3.PluginIsNotPresent(repo), swarm.ServicePoll) + poll.WaitOn(t, d1.PluginIsNotPresent(t, repo), swarm.ServicePoll) + poll.WaitOn(t, d2.PluginIsNotPresent(t, repo), swarm.ServicePoll) + poll.WaitOn(t, d3.PluginIsNotPresent(t, repo), swarm.ServicePoll) } func makePlugin(repo, name string, constraints []string) func(*swarmtypes.Service) { diff --git a/components/engine/internal/test/daemon/daemon.go b/components/engine/internal/test/daemon/daemon.go index cfa06fa934..ecc2e093a3 100644 --- a/components/engine/internal/test/daemon/daemon.go +++ b/components/engine/internal/test/daemon/daemon.go @@ -165,16 +165,7 @@ func (d *Daemon) ReadLogFile() ([]byte, error) { return ioutil.ReadFile(d.logFile.Name()) } -// NewClient creates new client based on daemon's socket path -// FIXME(vdemeester): replace NewClient with NewClientT -func (d *Daemon) NewClient() (*client.Client, error) { - return client.NewClientWithOpts( - client.FromEnv, - client.WithHost(d.Sock())) -} - // NewClientT creates new client based on daemon's socket path -// FIXME(vdemeester): replace NewClient with NewClientT func (d *Daemon) NewClientT(t assert.TestingT) *client.Client { if ht, ok := t.(test.HelperT); ok { ht.Helper() diff --git a/components/engine/internal/test/daemon/plugin.go b/components/engine/internal/test/daemon/plugin.go index 63bbeed219..ad66ebbf07 100644 --- a/components/engine/internal/test/daemon/plugin.go +++ b/components/engine/internal/test/daemon/plugin.go @@ -5,12 +5,13 @@ import ( "github.com/docker/docker/api/types" "github.com/docker/docker/client" + "gotest.tools/assert" "gotest.tools/poll" ) // PluginIsRunning provides a poller to check if the specified plugin is running -func (d *Daemon) PluginIsRunning(name string) func(poll.LogT) poll.Result { - return withClient(d, withPluginInspect(name, func(plugin *types.Plugin, t poll.LogT) poll.Result { +func (d *Daemon) PluginIsRunning(t assert.TestingT, name string) func(poll.LogT) poll.Result { + return withClient(t, d, withPluginInspect(name, func(plugin *types.Plugin, t poll.LogT) poll.Result { if plugin.Enabled { return poll.Success() } @@ -19,8 +20,8 @@ func (d *Daemon) PluginIsRunning(name string) func(poll.LogT) poll.Result { } // PluginIsNotRunning provides a poller to check if the specified plugin is not running -func (d *Daemon) PluginIsNotRunning(name string) func(poll.LogT) poll.Result { - return withClient(d, withPluginInspect(name, func(plugin *types.Plugin, t poll.LogT) poll.Result { +func (d *Daemon) PluginIsNotRunning(t assert.TestingT, name string) func(poll.LogT) poll.Result { + return withClient(t, d, withPluginInspect(name, func(plugin *types.Plugin, t poll.LogT) poll.Result { if !plugin.Enabled { return poll.Success() } @@ -29,8 +30,8 @@ func (d *Daemon) PluginIsNotRunning(name string) func(poll.LogT) poll.Result { } // PluginIsNotPresent provides a poller to check if the specified plugin is not present -func (d *Daemon) PluginIsNotPresent(name string) func(poll.LogT) poll.Result { - return withClient(d, func(c client.APIClient, t poll.LogT) poll.Result { +func (d *Daemon) PluginIsNotPresent(t assert.TestingT, name string) func(poll.LogT) poll.Result { + return withClient(t, d, func(c client.APIClient, t poll.LogT) poll.Result { _, _, err := c.PluginInspectWithRaw(context.Background(), name) if client.IsErrNotFound(err) { return poll.Success() @@ -43,8 +44,8 @@ func (d *Daemon) PluginIsNotPresent(name string) func(poll.LogT) poll.Result { } // PluginReferenceIs provides a poller to check if the specified plugin has the specified reference -func (d *Daemon) PluginReferenceIs(name, expectedRef string) func(poll.LogT) poll.Result { - return withClient(d, withPluginInspect(name, func(plugin *types.Plugin, t poll.LogT) poll.Result { +func (d *Daemon) PluginReferenceIs(t assert.TestingT, name, expectedRef string) func(poll.LogT) poll.Result { + return withClient(t, d, withPluginInspect(name, func(plugin *types.Plugin, t poll.LogT) poll.Result { if plugin.PluginReference == expectedRef { return poll.Success() } @@ -66,12 +67,9 @@ func withPluginInspect(name string, f func(*types.Plugin, poll.LogT) poll.Result } -func withClient(d *Daemon, f func(client.APIClient, poll.LogT) poll.Result) func(poll.LogT) poll.Result { - return func(t poll.LogT) poll.Result { - c, err := d.NewClient() - if err != nil { - poll.Error(err) - } - return f(c, t) +func withClient(t assert.TestingT, d *Daemon, f func(client.APIClient, poll.LogT) poll.Result) func(poll.LogT) poll.Result { + return func(pt poll.LogT) poll.Result { + c := d.NewClientT(t) + return f(c, pt) } } diff --git a/components/engine/internal/test/daemon/swarm.go b/components/engine/internal/test/daemon/swarm.go index ae6a62c9eb..4631222fcd 100644 --- a/components/engine/internal/test/daemon/swarm.go +++ b/components/engine/internal/test/daemon/swarm.go @@ -96,17 +96,14 @@ func (d *Daemon) SwarmJoin(t assert.TestingT, req swarm.JoinRequest) { } // SwarmLeave forces daemon to leave current cluster. -func (d *Daemon) SwarmLeave(force bool) error { - cli, err := d.NewClient() - if err != nil { - return fmt.Errorf("leaving swarm: failed to create client %v", err) - } +// +// The passed in TestingT is only used to validate that the client was successfully created +// Some tests rely on error checking the result of the actual unlock, so allow +// the error to be returned. +func (d *Daemon) SwarmLeave(t assert.TestingT, force bool) error { + cli := d.NewClientT(t) defer cli.Close() - err = cli.SwarmLeave(context.Background(), force) - if err != nil { - err = fmt.Errorf("leaving swarm: %v", err) - } - return err + return cli.SwarmLeave(context.Background(), force) } // SwarmInfo returns the swarm information of the daemon @@ -121,13 +118,15 @@ func (d *Daemon) SwarmInfo(t assert.TestingT) swarm.Info { } // SwarmUnlock tries to unlock a locked swarm -func (d *Daemon) SwarmUnlock(req swarm.UnlockRequest) error { - cli, err := d.NewClient() - if err != nil { - return fmt.Errorf("unlocking swarm: failed to create client %v", err) - } +// +// The passed in TestingT is only used to validate that the client was successfully created +// Some tests rely on error checking the result of the actual unlock, so allow +// the error to be returned. +func (d *Daemon) SwarmUnlock(t assert.TestingT, req swarm.UnlockRequest) error { + cli := d.NewClientT(t) defer cli.Close() - err = cli.SwarmUnlock(context.Background(), req) + + err := cli.SwarmUnlock(context.Background(), req) if err != nil { err = errors.Wrap(err, "unlocking swarm") } From 407b652dce9e9797ed26fda7c0e56d81dce177c3 Mon Sep 17 00:00:00 2001 From: Kir Kolyshkin Date: Fri, 24 Aug 2018 14:37:26 -0700 Subject: [PATCH 22/45] integration-cli: fix TestAttachDetach, rm TestAttachDetachTruncatedID It looks like the logic of the test became wrong after commit ae0883c ("Move TestAttachDetach to integration-cli"). The original logic was: * (a few first steps skipped for clarity) * send escape sequence to "attach"; * check "attach" is exiting (i.e. escape sequence works); * check the container is still alive; * kill the container. Also, timeouts were big at that time, in the order of seconds. The logic after the above mentioned commit and until now is: * ... * send escape sequence to "attach"; * check the container is running (why shouldn't it?); * kill the container; * checks that the "attach" has exited. So, from the "let's check detach using escape sequence is working" the test became something like "let's check that attach is gone once we kill the container". Let's fix the above test, also increasing the timeout waiting for attach to exit (which fails from time to time on power CI). Now, the second test, TestAttachDetachTruncatedID, does the exact same thing, except it uses a truncated container ID. It does not seem to be of much value, so let's remove it. Signed-off-by: Kir Kolyshkin (cherry picked from commit 9f3a343a5101ab661a6a97c9e149a0b11ccc320a) Signed-off-by: Sebastiaan van Stijn Upstream-commit: 17ae129697c10e9f866ffc253bc211f8912588df Component: engine --- .../docker_cli_attach_unix_test.go | 66 ++----------------- 1 file changed, 4 insertions(+), 62 deletions(-) diff --git a/components/engine/integration-cli/docker_cli_attach_unix_test.go b/components/engine/integration-cli/docker_cli_attach_unix_test.go index 9affb944b1..e270fda9cb 100644 --- a/components/engine/integration-cli/docker_cli_attach_unix_test.go +++ b/components/engine/integration-cli/docker_cli_attach_unix_test.go @@ -10,7 +10,6 @@ import ( "time" "github.com/docker/docker/integration-cli/checker" - "github.com/docker/docker/pkg/stringid" "github.com/go-check/check" "github.com/kr/pty" ) @@ -146,7 +145,7 @@ func (s *DockerSuite) TestAttachDetach(c *check.C) { c.Assert(err, check.IsNil) out, err = bufio.NewReader(stdout).ReadString('\n') c.Assert(err, check.IsNil) - c.Assert(strings.TrimSpace(out), checker.Equals, "hello", check.Commentf("expected 'hello', got %q", out)) + c.Assert(strings.TrimSpace(out), checker.Equals, "hello") // escape sequence _, err = cpty.Write([]byte{16}) @@ -158,72 +157,15 @@ func (s *DockerSuite) TestAttachDetach(c *check.C) { ch := make(chan struct{}) go func() { cmd.Wait() - ch <- struct{}{} - }() - - running := inspectField(c, id, "State.Running") - c.Assert(running, checker.Equals, "true", check.Commentf("expected container to still be running")) - - go func() { - dockerCmdWithResult("kill", id) + close(ch) }() select { case <-ch: - case <-time.After(10 * time.Millisecond): + case <-time.After(1 * time.Second): c.Fatal("timed out waiting for container to exit") } -} - -// TestAttachDetachTruncatedID checks that attach in tty mode can be detached -func (s *DockerSuite) TestAttachDetachTruncatedID(c *check.C) { - out, _ := dockerCmd(c, "run", "-itd", "busybox", "cat") - id := stringid.TruncateID(strings.TrimSpace(out)) - c.Assert(waitRun(id), check.IsNil) - - cpty, tty, err := pty.Open() - c.Assert(err, checker.IsNil) - defer cpty.Close() - - cmd := exec.Command(dockerBinary, "attach", id) - cmd.Stdin = tty - stdout, err := cmd.StdoutPipe() - c.Assert(err, checker.IsNil) - defer stdout.Close() - err = cmd.Start() - c.Assert(err, checker.IsNil) - - _, err = cpty.Write([]byte("hello\n")) - c.Assert(err, checker.IsNil) - out, err = bufio.NewReader(stdout).ReadString('\n') - c.Assert(err, checker.IsNil) - c.Assert(strings.TrimSpace(out), checker.Equals, "hello", check.Commentf("expected 'hello', got %q", out)) - - // escape sequence - _, err = cpty.Write([]byte{16}) - c.Assert(err, checker.IsNil) - time.Sleep(100 * time.Millisecond) - _, err = cpty.Write([]byte{17}) - c.Assert(err, checker.IsNil) - - ch := make(chan struct{}) - go func() { - cmd.Wait() - ch <- struct{}{} - }() - running := inspectField(c, id, "State.Running") - c.Assert(running, checker.Equals, "true", check.Commentf("expected container to still be running")) - - go func() { - dockerCmdWithResult("kill", id) - }() - - select { - case <-ch: - case <-time.After(10 * time.Millisecond): - c.Fatal("timed out waiting for container to exit") - } - + c.Assert(running, checker.Equals, "true") // container should be running } From 00a7935f141f7159430308b56d171c56b6ef1273 Mon Sep 17 00:00:00 2001 From: John Howard Date: Wed, 5 Sep 2018 16:38:25 -0700 Subject: [PATCH 23/45] Windows: Go1.11: Use long path names in build context (TestBuildSymlinkBreakout) Signed-off-by: John Howard (cherry picked from commit b1b9937bc75f0db9c804838ecce9bb6792a42525) Signed-off-by: Sebastiaan van Stijn Upstream-commit: 533b0f602d10af8fe325c3544a2411f5060a47b8 Component: engine --- .../integration-cli/docker_cli_build_test.go | 6 +++++ components/engine/pkg/system/path_unix.go | 10 ++++++++ components/engine/pkg/system/path_windows.go | 24 +++++++++++++++++++ 3 files changed, 40 insertions(+) create mode 100644 components/engine/pkg/system/path_unix.go create mode 100644 components/engine/pkg/system/path_windows.go diff --git a/components/engine/integration-cli/docker_cli_build_test.go b/components/engine/integration-cli/docker_cli_build_test.go index 1f9f49132e..53a54ce0fd 100644 --- a/components/engine/integration-cli/docker_cli_build_test.go +++ b/components/engine/integration-cli/docker_cli_build_test.go @@ -24,6 +24,7 @@ import ( "github.com/docker/docker/internal/test/fakestorage" "github.com/docker/docker/internal/testutil" "github.com/docker/docker/pkg/archive" + "github.com/docker/docker/pkg/system" "github.com/go-check/check" "github.com/moby/buildkit/frontend/dockerfile/command" "github.com/opencontainers/go-digest" @@ -3598,6 +3599,11 @@ func (s *DockerSuite) TestBuildSymlinkBreakout(c *check.C) { name := "testbuildsymlinkbreakout" tmpdir, err := ioutil.TempDir("", name) c.Assert(err, check.IsNil) + + // See https://github.com/moby/moby/pull/37770 for reason for next line. + tmpdir, err = system.GetLongPathName(tmpdir) + c.Assert(err, check.IsNil) + defer os.RemoveAll(tmpdir) ctx := filepath.Join(tmpdir, "context") if err := os.MkdirAll(ctx, 0755); err != nil { diff --git a/components/engine/pkg/system/path_unix.go b/components/engine/pkg/system/path_unix.go new file mode 100644 index 0000000000..b0b93196a1 --- /dev/null +++ b/components/engine/pkg/system/path_unix.go @@ -0,0 +1,10 @@ +// +build !windows + +package system // import "github.com/docker/docker/pkg/system" + +// GetLongPathName converts Windows short pathnames to full pathnames. +// For example C:\Users\ADMIN~1 --> C:\Users\Administrator. +// It is a no-op on non-Windows platforms +func GetLongPathName(path string) (string, error) { + return path, nil +} diff --git a/components/engine/pkg/system/path_windows.go b/components/engine/pkg/system/path_windows.go new file mode 100644 index 0000000000..188f2c2957 --- /dev/null +++ b/components/engine/pkg/system/path_windows.go @@ -0,0 +1,24 @@ +package system // import "github.com/docker/docker/pkg/system" + +import "syscall" + +// GetLongPathName converts Windows short pathnames to full pathnames. +// For example C:\Users\ADMIN~1 --> C:\Users\Administrator. +// It is a no-op on non-Windows platforms +func GetLongPathName(path string) (string, error) { + // See https://groups.google.com/forum/#!topic/golang-dev/1tufzkruoTg + p := syscall.StringToUTF16(path) + b := p // GetLongPathName says we can reuse buffer + n, err := syscall.GetLongPathName(&p[0], &b[0], uint32(len(b))) + if err != nil { + return "", err + } + if n > uint32(len(b)) { + b = make([]uint16, n) + _, err = syscall.GetLongPathName(&p[0], &b[0], uint32(len(b))) + if err != nil { + return "", err + } + } + return syscall.UTF16ToString(b), nil +} From 8c5907db7292a76bd353e76bfd51b061f0c18c7e Mon Sep 17 00:00:00 2001 From: Kir Kolyshkin Date: Mon, 10 Sep 2018 16:26:40 -0700 Subject: [PATCH 24/45] TestStartReturnCorrectExitCode: show error Signed-off-by: Kir Kolyshkin (cherry picked from commit 0d59f4305cbb1aaae1b0c6aab94c1e5a08b50bfb) Signed-off-by: Sebastiaan van Stijn Upstream-commit: d52a18f35215b127bd17e2a2d8cbfd2cb9ede5a3 Component: engine --- .../engine/integration-cli/docker_cli_start_test.go | 9 +++++---- 1 file changed, 5 insertions(+), 4 deletions(-) diff --git a/components/engine/integration-cli/docker_cli_start_test.go b/components/engine/integration-cli/docker_cli_start_test.go index cbe917bf4f..303deddb28 100644 --- a/components/engine/integration-cli/docker_cli_start_test.go +++ b/components/engine/integration-cli/docker_cli_start_test.go @@ -190,10 +190,11 @@ func (s *DockerSuite) TestStartReturnCorrectExitCode(c *check.C) { dockerCmd(c, "create", "--restart=on-failure:2", "--name", "withRestart", "busybox", "sh", "-c", "exit 11") dockerCmd(c, "create", "--rm", "--name", "withRm", "busybox", "sh", "-c", "exit 12") - _, exitCode, err := dockerCmdWithError("start", "-a", "withRestart") + out, exitCode, err := dockerCmdWithError("start", "-a", "withRestart") c.Assert(err, checker.NotNil) - c.Assert(exitCode, checker.Equals, 11) - _, exitCode, err = dockerCmdWithError("start", "-a", "withRm") + c.Assert(exitCode, checker.Equals, 11, check.Commentf("out: %s", out)) + + out, exitCode, err = dockerCmdWithError("start", "-a", "withRm") c.Assert(err, checker.NotNil) - c.Assert(exitCode, checker.Equals, 12) + c.Assert(exitCode, checker.Equals, 12, check.Commentf("out: %s", out)) } From b4531f8e24890957aa07f19fb73f76766674b5dd Mon Sep 17 00:00:00 2001 From: Kir Kolyshkin Date: Fri, 5 Oct 2018 11:10:28 -0700 Subject: [PATCH 25/45] integration-cli: fix netns test cleanup 1. Using MNT_FORCE flag does not make sense for nsfs. Using MNT_DETACH though might help. 2. When -check.vv is added to TESTFLAGS, there are a lot of messages like this one: > unmount of /tmp/dxr/d847fd103a4ba/netns failed: invalid argument and some like > unmount of /tmp/dxr/dd245af642d94/netns failed: no such file or directory The first one means directory is not a mount point, the second one means it's gone. Do ignore both of these. Signed-off-by: Kir Kolyshkin (cherry picked from commit 73baee2dcf546b2561bdd9a500b0af08cb62b1be) Signed-off-by: Sebastiaan van Stijn Upstream-commit: 90cb9b6545fbf7f91cf3eb427f627a7353ea684f Component: engine --- components/engine/internal/test/daemon/daemon_unix.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/components/engine/internal/test/daemon/daemon_unix.go b/components/engine/internal/test/daemon/daemon_unix.go index 9dd9e36f0c..eb604fec75 100644 --- a/components/engine/internal/test/daemon/daemon_unix.go +++ b/components/engine/internal/test/daemon/daemon_unix.go @@ -21,7 +21,7 @@ func cleanupNetworkNamespace(t testingT, execRoot string) { // new exec root. netnsPath := filepath.Join(execRoot, "netns") filepath.Walk(netnsPath, func(path string, info os.FileInfo, err error) error { - if err := unix.Unmount(path, unix.MNT_FORCE); err != nil { + if err := unix.Unmount(path, unix.MNT_DETACH); err != nil && err != unix.EINVAL && err != unix.ENOENT { t.Logf("unmount of %s failed: %v", path, err) } os.Remove(path) From 84be354cdfce794af579ad9a8603476315a85ed7 Mon Sep 17 00:00:00 2001 From: Kir Kolyshkin Date: Wed, 24 Oct 2018 22:49:33 -0700 Subject: [PATCH 26/45] docker_cli_swarm_test.go: rm unused arg Since commit 17173efbe00 checkSwarmLockedToUnlocked() no longer require its third argument, so remove it. Signed-off-by: Kir Kolyshkin (cherry picked from commit 66cb1222d6559e120d9d1a29932aa778aa517894) Signed-off-by: Sebastiaan van Stijn Upstream-commit: 2a02a2e9dae0045d550e98fa849aceafc0c41a0e Component: engine --- .../engine/integration-cli/docker_cli_swarm_test.go | 10 +++++----- 1 file changed, 5 insertions(+), 5 deletions(-) diff --git a/components/engine/integration-cli/docker_cli_swarm_test.go b/components/engine/integration-cli/docker_cli_swarm_test.go index 4ee946f795..f93075a639 100644 --- a/components/engine/integration-cli/docker_cli_swarm_test.go +++ b/components/engine/integration-cli/docker_cli_swarm_test.go @@ -1009,7 +1009,7 @@ func checkKeyIsEncrypted(d *daemon.Daemon) func(*check.C) (interface{}, check.Co } } -func checkSwarmLockedToUnlocked(c *check.C, d *daemon.Daemon, unlockKey string) { +func checkSwarmLockedToUnlocked(c *check.C, d *daemon.Daemon) { // Wait for the PEM file to become unencrypted waitAndAssert(c, defaultReconciliationTimeout, checkKeyIsEncrypted(d), checker.Equals, false) @@ -1100,7 +1100,7 @@ func (s *DockerSwarmSuite) TestSwarmInitLocked(c *check.C) { outs, err = d.Cmd("swarm", "update", "--autolock=false") c.Assert(err, checker.IsNil, check.Commentf("%s", outs)) - checkSwarmLockedToUnlocked(c, d, unlockKey) + checkSwarmLockedToUnlocked(c, d) outs, err = d.Cmd("node", "ls") c.Assert(err, checker.IsNil, check.Commentf("%s", outs)) @@ -1195,7 +1195,7 @@ func (s *DockerSwarmSuite) TestSwarmLockUnlockCluster(c *check.C) { // the ones that got the update are now set to unlocked for _, d := range []*daemon.Daemon{d1, d3} { - checkSwarmLockedToUnlocked(c, d, unlockKey) + checkSwarmLockedToUnlocked(c, d) } // d2 still locked @@ -1208,7 +1208,7 @@ func (s *DockerSwarmSuite) TestSwarmLockUnlockCluster(c *check.C) { c.Assert(getNodeStatus(c, d2), checker.Equals, swarm.LocalNodeStateActive) // once it's caught up, d2 is set to not be locked - checkSwarmLockedToUnlocked(c, d2, unlockKey) + checkSwarmLockedToUnlocked(c, d2) // managers who join now are never set to locked in the first place d4 := s.AddDaemon(c, true, true) @@ -1495,7 +1495,7 @@ func (s *DockerSwarmSuite) TestSwarmAlternateLockUnlock(c *check.C) { outs, err = d.Cmd("swarm", "update", "--autolock=false") c.Assert(err, checker.IsNil, check.Commentf("out: %v", outs)) - checkSwarmLockedToUnlocked(c, d, unlockKey) + checkSwarmLockedToUnlocked(c, d) } } From d81b3ef73bfdfbac57718b5f29823084aa163868 Mon Sep 17 00:00:00 2001 From: Kir Kolyshkin Date: Thu, 25 Oct 2018 01:08:45 -0700 Subject: [PATCH 27/45] internal/test/daemon: don't leak timers A timer is leaking on every daemon start and stop. Probably nothing major, but given the amount of daemon starts/stops during tests, it's better to be accurate about it. Signed-off-by: Kir Kolyshkin (cherry picked from commit 6016520162fdcb19f50d08c4f0b54b06a7a6eac0) Signed-off-by: Sebastiaan van Stijn Upstream-commit: 784a89354b118ef68f1f20fb4ff383c6282ea03c Component: engine --- components/engine/internal/test/daemon/daemon.go | 9 +++++++-- 1 file changed, 7 insertions(+), 2 deletions(-) diff --git a/components/engine/internal/test/daemon/daemon.go b/components/engine/internal/test/daemon/daemon.go index ecc2e093a3..c0b5c483f9 100644 --- a/components/engine/internal/test/daemon/daemon.go +++ b/components/engine/internal/test/daemon/daemon.go @@ -275,7 +275,10 @@ func (d *Daemon) StartWithLogFile(out *os.File, providedArgs ...string) error { d.Wait = wait - tick := time.Tick(500 * time.Millisecond) + ticker := time.NewTicker(500 * time.Millisecond) + defer ticker.Stop() + tick := ticker.C + // make sure daemon is ready to receive requests startTime := time.Now().Unix() for { @@ -413,7 +416,9 @@ func (d *Daemon) StopWithError() error { }() i := 1 - tick := time.Tick(time.Second) + ticker := time.NewTicker(time.Second) + defer ticker.Stop() + tick := ticker.C if err := d.cmd.Process.Signal(os.Interrupt); err != nil { if strings.Contains(err.Error(), "os: process already finished") { From 3a2688e1e500f0bbb06bbd31af3fbdd92c372494 Mon Sep 17 00:00:00 2001 From: Kir Kolyshkin Date: Mon, 29 Oct 2018 13:46:21 -0700 Subject: [PATCH 28/45] docker_cli_swarm_test: factor out common code This is repeated 6 times in different tests, with slight minor variations. Let's factor it out, for clarity. While at it, simplify the code: instead of more complex parsing of "docker swarm init|update --autolock" output (1) and checking if the key is also present in "docker swarm unlock-key" output (2), get the key from (2) and check it is present in (1). Signed-off-by: Kir Kolyshkin (cherry picked from commit 24cbb9897193894f4716583d1861091ab2fa1ae2) Signed-off-by: Sebastiaan van Stijn Upstream-commit: 6ec991ec8371bdba94480c587eea6ea24f3e9d43 Component: engine --- .../integration-cli/docker_cli_swarm_test.go | 108 +++--------------- 1 file changed, 19 insertions(+), 89 deletions(-) diff --git a/components/engine/integration-cli/docker_cli_swarm_test.go b/components/engine/integration-cli/docker_cli_swarm_test.go index f93075a639..30a769b68d 100644 --- a/components/engine/integration-cli/docker_cli_swarm_test.go +++ b/components/engine/integration-cli/docker_cli_swarm_test.go @@ -1055,22 +1055,7 @@ func (s *DockerSwarmSuite) TestSwarmInitLocked(c *check.C) { outs, err := d.Cmd("swarm", "init", "--autolock") c.Assert(err, checker.IsNil, check.Commentf("%s", outs)) - - c.Assert(outs, checker.Contains, "docker swarm unlock") - - var unlockKey string - for _, line := range strings.Split(outs, "\n") { - if strings.Contains(line, "SWMKEY") { - unlockKey = strings.TrimSpace(line) - break - } - } - - c.Assert(unlockKey, checker.Not(checker.Equals), "") - - outs, err = d.Cmd("swarm", "unlock-key", "-q") - c.Assert(err, checker.IsNil, check.Commentf("%s", outs)) - c.Assert(outs, checker.Equals, unlockKey+"\n") + unlockKey := getUnlockKey(d, c, outs) c.Assert(getNodeStatus(c, d), checker.Equals, swarm.LocalNodeStateActive) @@ -1155,22 +1140,7 @@ func (s *DockerSwarmSuite) TestSwarmLockUnlockCluster(c *check.C) { // enable autolock outs, err := d1.Cmd("swarm", "update", "--autolock") c.Assert(err, checker.IsNil, check.Commentf("%s", outs)) - - c.Assert(outs, checker.Contains, "docker swarm unlock") - - var unlockKey string - for _, line := range strings.Split(outs, "\n") { - if strings.Contains(line, "SWMKEY") { - unlockKey = strings.TrimSpace(line) - break - } - } - - c.Assert(unlockKey, checker.Not(checker.Equals), "") - - outs, err = d1.Cmd("swarm", "unlock-key", "-q") - c.Assert(err, checker.IsNil) - c.Assert(outs, checker.Equals, unlockKey+"\n") + unlockKey := getUnlockKey(d1, c, outs) // The ones that got the cluster update should be set to locked for _, d := range []*daemon.Daemon{d1, d3} { @@ -1222,22 +1192,7 @@ func (s *DockerSwarmSuite) TestSwarmJoinPromoteLocked(c *check.C) { // enable autolock outs, err := d1.Cmd("swarm", "update", "--autolock") c.Assert(err, checker.IsNil, check.Commentf("out: %v", outs)) - - c.Assert(outs, checker.Contains, "docker swarm unlock") - - var unlockKey string - for _, line := range strings.Split(outs, "\n") { - if strings.Contains(line, "SWMKEY") { - unlockKey = strings.TrimSpace(line) - break - } - } - - c.Assert(unlockKey, checker.Not(checker.Equals), "") - - outs, err = d1.Cmd("swarm", "unlock-key", "-q") - c.Assert(err, checker.IsNil) - c.Assert(outs, checker.Equals, unlockKey+"\n") + unlockKey := getUnlockKey(d1, c, outs) // joined workers start off unlocked d2 := s.AddDaemon(c, true, false) @@ -1295,22 +1250,7 @@ func (s *DockerSwarmSuite) TestSwarmRotateUnlockKey(c *check.C) { outs, err := d.Cmd("swarm", "update", "--autolock") c.Assert(err, checker.IsNil, check.Commentf("out: %v", outs)) - - c.Assert(outs, checker.Contains, "docker swarm unlock") - - var unlockKey string - for _, line := range strings.Split(outs, "\n") { - if strings.Contains(line, "SWMKEY") { - unlockKey = strings.TrimSpace(line) - break - } - } - - c.Assert(unlockKey, checker.Not(checker.Equals), "") - - outs, err = d.Cmd("swarm", "unlock-key", "-q") - c.Assert(err, checker.IsNil) - c.Assert(outs, checker.Equals, unlockKey+"\n") + unlockKey := getUnlockKey(d, c, outs) // Rotate multiple times for i := 0; i != 3; i++ { @@ -1387,22 +1327,7 @@ func (s *DockerSwarmSuite) TestSwarmClusterRotateUnlockKey(c *check.C) { outs, err := d1.Cmd("swarm", "update", "--autolock") c.Assert(err, checker.IsNil, check.Commentf("%s", outs)) - - c.Assert(outs, checker.Contains, "docker swarm unlock") - - var unlockKey string - for _, line := range strings.Split(outs, "\n") { - if strings.Contains(line, "SWMKEY") { - unlockKey = strings.TrimSpace(line) - break - } - } - - c.Assert(unlockKey, checker.Not(checker.Equals), "") - - outs, err = d1.Cmd("swarm", "unlock-key", "-q") - c.Assert(err, checker.IsNil, check.Commentf("%s", outs)) - c.Assert(outs, checker.Equals, unlockKey+"\n") + unlockKey := getUnlockKey(d1, c, outs) // Rotate multiple times for i := 0; i != 3; i++ { @@ -1469,21 +1394,13 @@ func (s *DockerSwarmSuite) TestSwarmClusterRotateUnlockKey(c *check.C) { func (s *DockerSwarmSuite) TestSwarmAlternateLockUnlock(c *check.C) { d := s.AddDaemon(c, true, true) - var unlockKey string for i := 0; i < 2; i++ { // set to lock outs, err := d.Cmd("swarm", "update", "--autolock") c.Assert(err, checker.IsNil, check.Commentf("out: %v", outs)) c.Assert(outs, checker.Contains, "docker swarm unlock") + unlockKey := getUnlockKey(d, c, outs) - for _, line := range strings.Split(outs, "\n") { - if strings.Contains(line, "SWMKEY") { - unlockKey = strings.TrimSpace(line) - break - } - } - - c.Assert(unlockKey, checker.Not(checker.Equals), "") checkSwarmUnlockedToLocked(c, d) cmd := d.Command("swarm", "unlock") @@ -2071,3 +1988,16 @@ func (s *DockerSwarmSuite) TestSwarmClusterEventsConfig(c *check.C) { // filtered by config waitForEvent(c, d, t1, "-f type=config", "config remove "+id, defaultRetryCount) } + +func getUnlockKey(d *daemon.Daemon, c *check.C, autolockOutput string) string { + unlockKey, err := d.Cmd("swarm", "unlock-key", "-q") + c.Assert(err, checker.IsNil, check.Commentf("%s", unlockKey)) + unlockKey = strings.TrimSuffix(unlockKey, "\n") + + // Check that "docker swarm init --autolock" or "docker swarm update --autolock" + // contains all the expected strings, including the unlock key + c.Assert(autolockOutput, checker.Contains, "docker swarm unlock") + c.Assert(autolockOutput, checker.Contains, unlockKey) + + return unlockKey +} From de3e7fdf71e582650ba90dd1293bd5c1001e7ede Mon Sep 17 00:00:00 2001 From: Kir Kolyshkin Date: Wed, 12 Sep 2018 19:30:09 -0700 Subject: [PATCH 29/45] TestAPISwarmLeaderElection: add some debug ...... Signed-off-by: Kir Kolyshkin (cherry picked from commit 06afc2d1e6f8c5052af71e8815266d30e29ed664) Signed-off-by: Sebastiaan van Stijn Upstream-commit: 2b498de10422c4d887c37ff1d51ac320e88151c8 Component: engine --- components/engine/integration-cli/docker_api_swarm_test.go | 4 ++-- components/engine/integration-cli/docker_utils_test.go | 6 ++++++ components/engine/internal/test/daemon/node.go | 2 +- 3 files changed, 9 insertions(+), 3 deletions(-) diff --git a/components/engine/integration-cli/docker_api_swarm_test.go b/components/engine/integration-cli/docker_api_swarm_test.go index c48e669c0d..83cf25e08b 100644 --- a/components/engine/integration-cli/docker_api_swarm_test.go +++ b/components/engine/integration-cli/docker_api_swarm_test.go @@ -340,6 +340,7 @@ func (s *DockerSwarmSuite) TestAPISwarmLeaderElection(c *check.C) { } // wait for an election to occur + c.Logf("Waiting for election to occur...") waitAndAssert(c, defaultReconciliationTimeout, checkLeader(d2, d3), checker.True) // assert that we have a new leader @@ -351,9 +352,8 @@ func (s *DockerSwarmSuite) TestAPISwarmLeaderElection(c *check.C) { // add the d1, the initial leader, back d1.Start(c) - // TODO(stevvooe): may need to wait for rejoin here - // wait for possible election + c.Logf("Waiting for possible election...") waitAndAssert(c, defaultReconciliationTimeout, checkLeader(d1, d2, d3), checker.True) // pick out the leader and the followers again diff --git a/components/engine/integration-cli/docker_utils_test.go b/components/engine/integration-cli/docker_utils_test.go index 732b2ac87c..8052c7951f 100644 --- a/components/engine/integration-cli/docker_utils_test.go +++ b/components/engine/integration-cli/docker_utils_test.go @@ -413,6 +413,12 @@ func getErrorMessage(c *check.C, body []byte) string { } func waitAndAssert(c *check.C, timeout time.Duration, f checkF, checker check.Checker, args ...interface{}) { + t1 := time.Now() + defer func() { + t2 := time.Now() + c.Logf("waited for %v (out of %v)", t2.Sub(t1), timeout) + }() + after := time.After(timeout) for { v, comment := f(c) diff --git a/components/engine/internal/test/daemon/node.go b/components/engine/internal/test/daemon/node.go index d9263a7f29..33dd365429 100644 --- a/components/engine/internal/test/daemon/node.go +++ b/components/engine/internal/test/daemon/node.go @@ -23,7 +23,7 @@ func (d *Daemon) GetNode(t assert.TestingT, id string) *swarm.Node { defer cli.Close() node, _, err := cli.NodeInspectWithRaw(context.Background(), id) - assert.NilError(t, err) + assert.NilError(t, err, "[%s] (*Daemon).GetNode: NodeInspectWithRaw(%q) failed", d.id, id) assert.Check(t, node.ID == id) return &node } From 80b75da5582cb61ae035ae6645d60965a00e88a6 Mon Sep 17 00:00:00 2001 From: Kir Kolyshkin Date: Thu, 25 Oct 2018 11:47:56 -0700 Subject: [PATCH 30/45] integration-cli/Test*Swarm*: use same args on restart When starting docker daemons for swarm testing, we disable iptables and use lo for communication (in order to avoid network conflicts). The problem is, these options are lost on restart, that can lead to any sorts of network conflicts and thus connectivity issues between swarm nodes. Fix this. This does not fix issues with swarm test failures, but it seems they appear are less often after this one. Signed-off-by: Kir Kolyshkin (cherry picked from commit 2ed512c7faea938b0b07e69187b8a132e2ecb66a) Signed-off-by: Sebastiaan van Stijn Upstream-commit: 553b09684cb68962403ebdc5495fb548364f778f Component: engine --- .../engine/integration-cli/check_test.go | 2 +- .../docker_api_swarm_node_test.go | 2 +- .../integration-cli/docker_api_swarm_test.go | 22 ++++++------- .../integration-cli/docker_cli_swarm_test.go | 32 +++++++++---------- .../engine/internal/test/daemon/swarm.go | 32 +++++++++++++------ 5 files changed, 49 insertions(+), 41 deletions(-) diff --git a/components/engine/integration-cli/check_test.go b/components/engine/integration-cli/check_test.go index 2282967ee5..10fe4e7646 100644 --- a/components/engine/integration-cli/check_test.go +++ b/components/engine/integration-cli/check_test.go @@ -333,7 +333,7 @@ func (s *DockerSwarmSuite) AddDaemon(c *check.C, joinSwarm, manager bool) *daemo d.StartAndSwarmInit(c) } } else { - d.StartWithBusybox(c, "--iptables=false", "--swarm-default-advertise-addr=lo") + d.StartNode(c) } s.portIndex++ diff --git a/components/engine/integration-cli/docker_api_swarm_node_test.go b/components/engine/integration-cli/docker_api_swarm_node_test.go index 191391620d..30c2285463 100644 --- a/components/engine/integration-cli/docker_api_swarm_node_test.go +++ b/components/engine/integration-cli/docker_api_swarm_node_test.go @@ -62,7 +62,7 @@ func (s *DockerSwarmSuite) TestAPISwarmNodeRemove(c *check.C) { c.Assert(len(nodes), checker.Equals, 2, check.Commentf("nodes: %#v", nodes)) // Restart the node that was removed - d2.Restart(c) + d2.RestartNode(c) // Give some time for the node to rejoin time.Sleep(1 * time.Second) diff --git a/components/engine/integration-cli/docker_api_swarm_test.go b/components/engine/integration-cli/docker_api_swarm_test.go index 83cf25e08b..fecbf1e860 100644 --- a/components/engine/integration-cli/docker_api_swarm_test.go +++ b/components/engine/integration-cli/docker_api_swarm_test.go @@ -67,8 +67,8 @@ func (s *DockerSwarmSuite) TestAPISwarmInit(c *check.C) { d1.Stop(c) d2.Stop(c) - d1.Start(c) - d2.Start(c) + d1.StartNode(c) + d2.StartNode(c) info = d1.SwarmInfo(c) c.Assert(info.ControlAvailable, checker.True) @@ -350,7 +350,7 @@ func (s *DockerSwarmSuite) TestAPISwarmLeaderElection(c *check.C) { stableleader := leader // add the d1, the initial leader, back - d1.Start(c) + d1.StartNode(c) // wait for possible election c.Logf("Waiting for possible election...") @@ -401,7 +401,7 @@ func (s *DockerSwarmSuite) TestAPISwarmRaftQuorum(c *check.C) { return err.Error(), nil }, checker.Contains, "Make sure more than half of the managers are online.") - d2.Start(c) + d2.StartNode(c) // make sure there is a leader waitAndAssert(c, defaultReconciliationTimeout, d1.CheckLeader, checker.IsNil) @@ -477,8 +477,7 @@ func (s *DockerSwarmSuite) TestAPISwarmRestoreOnPendingJoin(c *check.C) { waitAndAssert(c, defaultReconciliationTimeout, d.CheckLocalNodeState, checker.Equals, swarm.LocalNodeStatePending) - d.Stop(c) - d.Start(c) + d.RestartNode(c) info := d.SwarmInfo(c) c.Assert(info.LocalNodeState, checker.Equals, swarm.LocalNodeStateInactive) @@ -491,26 +490,23 @@ func (s *DockerSwarmSuite) TestAPISwarmManagerRestore(c *check.C) { id := d1.CreateService(c, simpleTestService, setInstances(instances)) d1.GetService(c, id) - d1.Stop(c) - d1.Start(c) + d1.RestartNode(c) d1.GetService(c, id) d2 := s.AddDaemon(c, true, true) d2.GetService(c, id) - d2.Stop(c) - d2.Start(c) + d2.RestartNode(c) d2.GetService(c, id) d3 := s.AddDaemon(c, true, true) d3.GetService(c, id) - d3.Stop(c) - d3.Start(c) + d3.RestartNode(c) d3.GetService(c, id) err := d3.Kill() assert.NilError(c, err) time.Sleep(1 * time.Second) // time to handle signal - d3.Start(c) + d3.StartNode(c) d3.GetService(c, id) } diff --git a/components/engine/integration-cli/docker_cli_swarm_test.go b/components/engine/integration-cli/docker_cli_swarm_test.go index 30a769b68d..3f307d7b9e 100644 --- a/components/engine/integration-cli/docker_cli_swarm_test.go +++ b/components/engine/integration-cli/docker_cli_swarm_test.go @@ -164,7 +164,7 @@ func (s *DockerSwarmSuite) TestSwarmIncompatibleDaemon(c *check.C) { c.Assert(err, checker.IsNil) c.Assert(string(content), checker.Contains, "--live-restore daemon configuration is incompatible with swarm mode") // restart for teardown - d.Start(c) + d.StartNode(c) } func (s *DockerSwarmSuite) TestSwarmServiceTemplatingHostname(c *check.C) { @@ -331,7 +331,7 @@ func (s *DockerSwarmSuite) TestSwarmContainerAutoStart(c *check.C) { c.Assert(err, checker.IsNil, check.Commentf("%s", out)) c.Assert(strings.TrimSpace(out), checker.Not(checker.Equals), "") - d.Restart(c) + d.RestartNode(c) out, err = d.Cmd("ps", "-q") c.Assert(err, checker.IsNil, check.Commentf("%s", out)) @@ -1013,7 +1013,7 @@ func checkSwarmLockedToUnlocked(c *check.C, d *daemon.Daemon) { // Wait for the PEM file to become unencrypted waitAndAssert(c, defaultReconciliationTimeout, checkKeyIsEncrypted(d), checker.Equals, false) - d.Restart(c) + d.RestartNode(c) c.Assert(getNodeStatus(c, d), checker.Equals, swarm.LocalNodeStateActive) } @@ -1021,7 +1021,7 @@ func checkSwarmUnlockedToLocked(c *check.C, d *daemon.Daemon) { // Wait for the PEM file to become encrypted waitAndAssert(c, defaultReconciliationTimeout, checkKeyIsEncrypted(d), checker.Equals, true) - d.Restart(c) + d.RestartNode(c) c.Assert(getNodeStatus(c, d), checker.Equals, swarm.LocalNodeStateLocked) } @@ -1060,7 +1060,7 @@ func (s *DockerSwarmSuite) TestSwarmInitLocked(c *check.C) { c.Assert(getNodeStatus(c, d), checker.Equals, swarm.LocalNodeStateActive) // It starts off locked - d.Restart(c) + d.RestartNode(c) c.Assert(getNodeStatus(c, d), checker.Equals, swarm.LocalNodeStateLocked) cmd := d.Command("swarm", "unlock") @@ -1099,7 +1099,7 @@ func (s *DockerSwarmSuite) TestSwarmLeaveLocked(c *check.C) { c.Assert(err, checker.IsNil, check.Commentf("%s", outs)) // It starts off locked - d.Restart(c, "--swarm-default-advertise-addr=lo") + d.RestartNode(c) info := d.SwarmInfo(c) c.Assert(info.LocalNodeState, checker.Equals, swarm.LocalNodeStateLocked) @@ -1131,7 +1131,7 @@ func (s *DockerSwarmSuite) TestSwarmLockUnlockCluster(c *check.C) { d3 := s.AddDaemon(c, true, true) // they start off unlocked - d2.Restart(c) + d2.RestartNode(c) c.Assert(getNodeStatus(c, d2), checker.Equals, swarm.LocalNodeStateActive) // stop this one so it does not get autolock info @@ -1153,7 +1153,7 @@ func (s *DockerSwarmSuite) TestSwarmLockUnlockCluster(c *check.C) { } // d2 never got the cluster update, so it is still set to unlocked - d2.Start(c) + d2.StartNode(c) c.Assert(getNodeStatus(c, d2), checker.Equals, swarm.LocalNodeStateActive) // d2 is now set to lock @@ -1182,7 +1182,7 @@ func (s *DockerSwarmSuite) TestSwarmLockUnlockCluster(c *check.C) { // managers who join now are never set to locked in the first place d4 := s.AddDaemon(c, true, true) - d4.Restart(c) + d4.RestartNode(c) c.Assert(getNodeStatus(c, d4), checker.Equals, swarm.LocalNodeStateActive) } @@ -1196,7 +1196,7 @@ func (s *DockerSwarmSuite) TestSwarmJoinPromoteLocked(c *check.C) { // joined workers start off unlocked d2 := s.AddDaemon(c, true, false) - d2.Restart(c) + d2.RestartNode(c) c.Assert(getNodeStatus(c, d2), checker.Equals, swarm.LocalNodeStateActive) // promote worker @@ -1241,7 +1241,7 @@ func (s *DockerSwarmSuite) TestSwarmJoinPromoteLocked(c *check.C) { }, checker.Equals, "swarm-worker") // by now, it should *never* be locked on restart - d3.Restart(c) + d3.RestartNode(c) c.Assert(getNodeStatus(c, d3), checker.Equals, swarm.LocalNodeStateActive) } @@ -1261,7 +1261,7 @@ func (s *DockerSwarmSuite) TestSwarmRotateUnlockKey(c *check.C) { c.Assert(newUnlockKey, checker.Not(checker.Equals), "") c.Assert(newUnlockKey, checker.Not(checker.Equals), unlockKey) - d.Restart(c) + d.RestartNode(c) c.Assert(getNodeStatus(c, d), checker.Equals, swarm.LocalNodeStateLocked) outs, _ = d.Cmd("node", "ls") @@ -1282,7 +1282,7 @@ func (s *DockerSwarmSuite) TestSwarmRotateUnlockKey(c *check.C) { time.Sleep(3 * time.Second) - d.Restart(c) + d.RestartNode(c) cmd = d.Command("swarm", "unlock") cmd.Stdin = bytes.NewBufferString(unlockKey) @@ -1338,8 +1338,8 @@ func (s *DockerSwarmSuite) TestSwarmClusterRotateUnlockKey(c *check.C) { c.Assert(newUnlockKey, checker.Not(checker.Equals), "") c.Assert(newUnlockKey, checker.Not(checker.Equals), unlockKey) - d2.Restart(c) - d3.Restart(c) + d2.RestartNode(c) + d3.RestartNode(c) for _, d := range []*daemon.Daemon{d2, d3} { c.Assert(getNodeStatus(c, d), checker.Equals, swarm.LocalNodeStateLocked) @@ -1362,7 +1362,7 @@ func (s *DockerSwarmSuite) TestSwarmClusterRotateUnlockKey(c *check.C) { time.Sleep(3 * time.Second) - d.Restart(c) + d.RestartNode(c) cmd = d.Command("swarm", "unlock") cmd.Stdin = bytes.NewBufferString(unlockKey) diff --git a/components/engine/internal/test/daemon/swarm.go b/components/engine/internal/test/daemon/swarm.go index 4631222fcd..c526d3eca9 100644 --- a/components/engine/internal/test/daemon/swarm.go +++ b/components/engine/internal/test/daemon/swarm.go @@ -16,26 +16,38 @@ const ( defaultSwarmListenAddr = "0.0.0.0" ) -// StartAndSwarmInit starts the daemon (with busybox) and init the swarm -func (d *Daemon) StartAndSwarmInit(t testingT) { +var ( + startArgs = []string{"--iptables=false", "--swarm-default-advertise-addr=lo"} +) + +// StartNode starts daemon to be used as a swarm node +func (d *Daemon) StartNode(t testingT) { if ht, ok := t.(test.HelperT); ok { ht.Helper() } // avoid networking conflicts - args := []string{"--iptables=false", "--swarm-default-advertise-addr=lo"} - d.StartWithBusybox(t, args...) + d.StartWithBusybox(t, startArgs...) +} +// RestartNode restarts a daemon to be used as a swarm node +func (d *Daemon) RestartNode(t testingT) { + if ht, ok := t.(test.HelperT); ok { + ht.Helper() + } + // avoid networking conflicts + d.Stop(t) + d.StartWithBusybox(t, startArgs...) +} + +// StartAndSwarmInit starts the daemon (with busybox) and init the swarm +func (d *Daemon) StartAndSwarmInit(t testingT) { + d.StartNode(t) d.SwarmInit(t, swarm.InitRequest{}) } // StartAndSwarmJoin starts the daemon (with busybox) and join the specified swarm as worker or manager func (d *Daemon) StartAndSwarmJoin(t testingT, leader *Daemon, manager bool) { - if ht, ok := t.(test.HelperT); ok { - ht.Helper() - } - // avoid networking conflicts - args := []string{"--iptables=false", "--swarm-default-advertise-addr=lo"} - d.StartWithBusybox(t, args...) + d.StartNode(t) tokens := leader.JoinTokens(t) token := tokens.Worker From e887118a6e675a199c981d70bcc4e151e0444d5e Mon Sep 17 00:00:00 2001 From: Sebastiaan van Stijn Date: Mon, 24 Dec 2018 13:16:05 +0100 Subject: [PATCH 31/45] Remove unused ExperimentalDaemon, NotS390X, NotPausable requirement checks Signed-off-by: Sebastiaan van Stijn (cherry picked from commit 362f737e1ccf9a1c3ac9599f48b10a33fd9b0e08) Signed-off-by: Sebastiaan van Stijn Upstream-commit: 008cc8ee495d5f13d44764e906d92a8999f4c473 Component: engine --- .../engine/integration-cli/requirements_test.go | 16 ---------------- 1 file changed, 16 deletions(-) diff --git a/components/engine/integration-cli/requirements_test.go b/components/engine/integration-cli/requirements_test.go index a087d66603..ddb1b4299e 100644 --- a/components/engine/integration-cli/requirements_test.go +++ b/components/engine/integration-cli/requirements_test.go @@ -60,11 +60,6 @@ func OnlyDefaultNetworks() bool { return true } -// Deprecated: use skip.If(t, !testEnv.DaemonInfo.ExperimentalBuild) -func ExperimentalDaemon() bool { - return testEnv.DaemonInfo.ExperimentalBuild -} - func IsAmd64() bool { return os.Getenv("DOCKER_ENGINE_GOARCH") == "amd64" } @@ -81,10 +76,6 @@ func NotPpc64le() bool { return ArchitectureIsNot("ppc64le") } -func NotS390X() bool { - return ArchitectureIsNot("s390x") -} - func SameHostDaemon() bool { return testEnv.IsLocalDaemon() } @@ -176,13 +167,6 @@ func IsPausable() bool { return true } -func NotPausable() bool { - if testEnv.OSType == "windows" { - return testEnv.DaemonInfo.Isolation == "process" - } - return false -} - func IsolationIs(expectedIsolation string) bool { return testEnv.OSType == "windows" && string(testEnv.DaemonInfo.Isolation) == expectedIsolation } From cfd34d85d8a9ed71cc78d33750a0d0dbba4b7bf5 Mon Sep 17 00:00:00 2001 From: Sebastiaan van Stijn Date: Mon, 24 Dec 2018 13:25:53 +0100 Subject: [PATCH 32/45] Remove SameHostDaemon, use testEnv.IsLocalDaemon instead Signed-off-by: Sebastiaan van Stijn (cherry picked from commit 43b15e924ffb7790ae087feac7618308a9e4b75e) Signed-off-by: Sebastiaan van Stijn Upstream-commit: 3304d91f1e69b53e92240fd3c604d178b0601dd5 Component: engine --- .../engine/integration-cli/check_test.go | 14 ++-- .../docker_api_containers_test.go | 10 +-- .../docker_api_containers_windows_test.go | 2 +- .../integration-cli/docker_api_exec_test.go | 2 +- .../integration-cli/docker_api_images_test.go | 2 +- .../integration-cli/docker_api_stats_test.go | 4 +- .../docker_api_swarm_service_test.go | 2 +- .../docker_cli_attach_unix_test.go | 2 +- .../integration-cli/docker_cli_build_test.go | 8 +- .../integration-cli/docker_cli_cp_test.go | 10 +-- .../docker_cli_cp_to_container_test.go | 2 +- .../docker_cli_cp_to_container_unix_test.go | 4 +- .../docker_cli_cp_utils_test.go | 2 +- .../integration-cli/docker_cli_create_test.go | 4 +- .../docker_cli_daemon_plugins_test.go | 4 +- .../integration-cli/docker_cli_daemon_test.go | 32 ++++---- .../integration-cli/docker_cli_events_test.go | 2 +- .../docker_cli_events_unix_test.go | 4 +- .../integration-cli/docker_cli_exec_test.go | 4 +- .../docker_cli_exec_unix_test.go | 6 +- ...er_cli_external_volume_driver_unix_test.go | 2 +- .../integration-cli/docker_cli_info_test.go | 12 +-- .../docker_cli_info_unix_test.go | 2 +- .../integration-cli/docker_cli_links_test.go | 4 +- .../docker_cli_network_unix_test.go | 26 +++--- .../docker_cli_plugins_test.go | 4 +- .../integration-cli/docker_cli_proxy_test.go | 4 +- .../docker_cli_restart_test.go | 8 +- .../integration-cli/docker_cli_run_test.go | 80 +++++++++---------- .../docker_cli_run_unix_test.go | 66 +++++++-------- .../docker_cli_save_load_test.go | 2 +- .../integration-cli/docker_cli_userns_test.go | 2 +- .../integration-cli/docker_cli_volume_test.go | 4 +- .../docker_hub_pull_suite_test.go | 2 +- .../integration-cli/requirements_test.go | 4 - .../integration-cli/requirements_unix_test.go | 6 +- 36 files changed, 172 insertions(+), 176 deletions(-) diff --git a/components/engine/integration-cli/check_test.go b/components/engine/integration-cli/check_test.go index 10fe4e7646..0abf18154a 100644 --- a/components/engine/integration-cli/check_test.go +++ b/components/engine/integration-cli/check_test.go @@ -125,7 +125,7 @@ func (s *DockerRegistrySuite) OnTimeout(c *check.C) { } func (s *DockerRegistrySuite) SetUpTest(c *check.C) { - testRequires(c, DaemonIsLinux, RegistryHosting, SameHostDaemon) + testRequires(c, DaemonIsLinux, RegistryHosting, testEnv.IsLocalDaemon) s.reg = registry.NewV2(c) s.reg.WaitReady(c) s.d = daemon.New(c, dockerBinary, dockerdBinary, testdaemon.WithEnvironment(testEnv.Execution)) @@ -158,7 +158,7 @@ func (s *DockerSchema1RegistrySuite) OnTimeout(c *check.C) { } func (s *DockerSchema1RegistrySuite) SetUpTest(c *check.C) { - testRequires(c, DaemonIsLinux, RegistryHosting, NotArm64, SameHostDaemon) + testRequires(c, DaemonIsLinux, RegistryHosting, NotArm64, testEnv.IsLocalDaemon) s.reg = registry.NewV2(c, registry.Schema1) s.reg.WaitReady(c) s.d = daemon.New(c, dockerBinary, dockerdBinary, testdaemon.WithEnvironment(testEnv.Execution)) @@ -191,7 +191,7 @@ func (s *DockerRegistryAuthHtpasswdSuite) OnTimeout(c *check.C) { } func (s *DockerRegistryAuthHtpasswdSuite) SetUpTest(c *check.C) { - testRequires(c, DaemonIsLinux, RegistryHosting, SameHostDaemon) + testRequires(c, DaemonIsLinux, RegistryHosting, testEnv.IsLocalDaemon) s.reg = registry.NewV2(c, registry.Htpasswd) s.reg.WaitReady(c) s.d = daemon.New(c, dockerBinary, dockerdBinary, testdaemon.WithEnvironment(testEnv.Execution)) @@ -226,7 +226,7 @@ func (s *DockerRegistryAuthTokenSuite) OnTimeout(c *check.C) { } func (s *DockerRegistryAuthTokenSuite) SetUpTest(c *check.C) { - testRequires(c, DaemonIsLinux, RegistryHosting, SameHostDaemon) + testRequires(c, DaemonIsLinux, RegistryHosting, testEnv.IsLocalDaemon) s.d = daemon.New(c, dockerBinary, dockerdBinary, testdaemon.WithEnvironment(testEnv.Execution)) } @@ -266,12 +266,12 @@ func (s *DockerDaemonSuite) OnTimeout(c *check.C) { } func (s *DockerDaemonSuite) SetUpTest(c *check.C) { - testRequires(c, DaemonIsLinux, SameHostDaemon) + testRequires(c, DaemonIsLinux, testEnv.IsLocalDaemon) s.d = daemon.New(c, dockerBinary, dockerdBinary, testdaemon.WithEnvironment(testEnv.Execution)) } func (s *DockerDaemonSuite) TearDownTest(c *check.C) { - testRequires(c, DaemonIsLinux, SameHostDaemon) + testRequires(c, DaemonIsLinux, testEnv.IsLocalDaemon) if s.d != nil { s.d.Stop(c) } @@ -318,7 +318,7 @@ func (s *DockerSwarmSuite) OnTimeout(c *check.C) { } func (s *DockerSwarmSuite) SetUpTest(c *check.C) { - testRequires(c, DaemonIsLinux, SameHostDaemon) + testRequires(c, DaemonIsLinux, testEnv.IsLocalDaemon) } func (s *DockerSwarmSuite) AddDaemon(c *check.C, joinSwarm, manager bool) *daemon.Daemon { diff --git a/components/engine/integration-cli/docker_api_containers_test.go b/components/engine/integration-cli/docker_api_containers_test.go index 164877bc2b..6e1d5d7e68 100644 --- a/components/engine/integration-cli/docker_api_containers_test.go +++ b/components/engine/integration-cli/docker_api_containers_test.go @@ -1252,7 +1252,7 @@ func (s *DockerSuite) TestContainerAPIDeleteConflict(c *check.C) { } func (s *DockerSuite) TestContainerAPIDeleteRemoveVolume(c *check.C) { - testRequires(c, SameHostDaemon) + testRequires(c, testEnv.IsLocalDaemon) vol := "/testvolume" if testEnv.OSType == "windows" { @@ -1426,7 +1426,7 @@ func (s *DockerSuite) TestPutContainerArchiveErrSymlinkInVolumeToReadOnlyRootfs( // Windows does not support read-only rootfs // Requires local volume mount bind. // --read-only + userns has remount issues - testRequires(c, SameHostDaemon, NotUserNamespace, DaemonIsLinux) + testRequires(c, testEnv.IsLocalDaemon, NotUserNamespace, DaemonIsLinux) testVol := getTestDir(c, "test-put-container-archive-err-symlink-in-volume-to-read-only-rootfs-") defer os.RemoveAll(testVol) @@ -1796,7 +1796,7 @@ func (s *DockerSuite) TestContainersAPICreateMountsValidation(c *check.C) { }, } - if SameHostDaemon() { + if testEnv.IsLocalDaemon() { tmpDir, err := ioutils.TempDir("", "test-mounts-api") c.Assert(err, checker.IsNil) defer os.RemoveAll(tmpDir) @@ -1899,7 +1899,7 @@ func (s *DockerSuite) TestContainersAPICreateMountsValidation(c *check.C) { } func (s *DockerSuite) TestContainerAPICreateMountsBindRead(c *check.C) { - testRequires(c, NotUserNamespace, SameHostDaemon) + testRequires(c, NotUserNamespace, testEnv.IsLocalDaemon) // also with data in the host side prefix, slash := getPrefixAndSlashFromDaemonPlatform() destPath := prefix + slash + "foo" @@ -1987,7 +1987,7 @@ func (s *DockerSuite) TestContainersAPICreateMountsCreate(c *check.C) { }, } - if SameHostDaemon() { + if testEnv.IsLocalDaemon() { // setup temp dir for testing binds tmpDir1, err := ioutil.TempDir("", "test-mounts-api-1") c.Assert(err, checker.IsNil) diff --git a/components/engine/integration-cli/docker_api_containers_windows_test.go b/components/engine/integration-cli/docker_api_containers_windows_test.go index c569574de5..dc3fbefbf2 100644 --- a/components/engine/integration-cli/docker_api_containers_windows_test.go +++ b/components/engine/integration-cli/docker_api_containers_windows_test.go @@ -19,7 +19,7 @@ import ( ) func (s *DockerSuite) TestContainersAPICreateMountsBindNamedPipe(c *check.C) { - testRequires(c, SameHostDaemon, DaemonIsWindowsAtLeastBuild(16299)) // Named pipe support was added in RS3 + testRequires(c, testEnv.IsLocalDaemon, DaemonIsWindowsAtLeastBuild(16299)) // Named pipe support was added in RS3 // Create a host pipe to map into the container hostPipeName := fmt.Sprintf(`\\.\pipe\docker-cli-test-pipe-%x`, rand.Uint64()) diff --git a/components/engine/integration-cli/docker_api_exec_test.go b/components/engine/integration-cli/docker_api_exec_test.go index 1a288733f2..3c98eb4ac1 100644 --- a/components/engine/integration-cli/docker_api_exec_test.go +++ b/components/engine/integration-cli/docker_api_exec_test.go @@ -212,7 +212,7 @@ func (s *DockerSuite) TestExecAPIStartInvalidCommand(c *check.C) { } func (s *DockerSuite) TestExecStateCleanup(c *check.C) { - testRequires(c, DaemonIsLinux, SameHostDaemon) + testRequires(c, DaemonIsLinux, testEnv.IsLocalDaemon) // This test checks accidental regressions. Not part of stable API. diff --git a/components/engine/integration-cli/docker_api_images_test.go b/components/engine/integration-cli/docker_api_images_test.go index 5040c98e4b..416c1f715c 100644 --- a/components/engine/integration-cli/docker_api_images_test.go +++ b/components/engine/integration-cli/docker_api_images_test.go @@ -147,7 +147,7 @@ func (s *DockerSuite) TestAPIImagesImportBadSrc(c *check.C) { } } - testRequires(c, Network, SameHostDaemon) + testRequires(c, Network, testEnv.IsLocalDaemon) server := httptest.NewServer(http.NewServeMux()) defer server.Close() diff --git a/components/engine/integration-cli/docker_api_stats_test.go b/components/engine/integration-cli/docker_api_stats_test.go index 1bae97c47c..d715cc67f5 100644 --- a/components/engine/integration-cli/docker_api_stats_test.go +++ b/components/engine/integration-cli/docker_api_stats_test.go @@ -97,7 +97,7 @@ func (s *DockerSuite) TestAPIStatsStoppedContainerInGoroutines(c *check.C) { } func (s *DockerSuite) TestAPIStatsNetworkStats(c *check.C) { - testRequires(c, SameHostDaemon) + testRequires(c, testEnv.IsLocalDaemon) out := runSleepingContainer(c) id := strings.TrimSpace(out) @@ -165,7 +165,7 @@ func (s *DockerSuite) TestAPIStatsNetworkStats(c *check.C) { func (s *DockerSuite) TestAPIStatsNetworkStatsVersioning(c *check.C) { // Windows doesn't support API versions less than 1.25, so no point testing 1.17 .. 1.21 - testRequires(c, SameHostDaemon, DaemonIsLinux) + testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux) out := runSleepingContainer(c) id := strings.TrimSpace(out) diff --git a/components/engine/integration-cli/docker_api_swarm_service_test.go b/components/engine/integration-cli/docker_api_swarm_service_test.go index 1986c94bb0..9b6764a714 100644 --- a/components/engine/integration-cli/docker_api_swarm_service_test.go +++ b/components/engine/integration-cli/docker_api_swarm_service_test.go @@ -537,7 +537,7 @@ func (s *DockerSwarmSuite) TestAPISwarmServicePlacementPrefs(c *check.C) { } func (s *DockerSwarmSuite) TestAPISwarmServicesStateReporting(c *check.C) { - testRequires(c, SameHostDaemon) + testRequires(c, testEnv.IsLocalDaemon) testRequires(c, DaemonIsLinux) d1 := s.AddDaemon(c, true, true) diff --git a/components/engine/integration-cli/docker_cli_attach_unix_test.go b/components/engine/integration-cli/docker_cli_attach_unix_test.go index e270fda9cb..6430d68ed3 100644 --- a/components/engine/integration-cli/docker_cli_attach_unix_test.go +++ b/components/engine/integration-cli/docker_cli_attach_unix_test.go @@ -16,7 +16,7 @@ import ( // #9860 Make sure attach ends when container ends (with no errors) func (s *DockerSuite) TestAttachClosedOnContainerStop(c *check.C) { - testRequires(c, SameHostDaemon) + testRequires(c, testEnv.IsLocalDaemon) out, _ := dockerCmd(c, "run", "-dti", "busybox", "/bin/sh", "-c", `trap 'exit 0' SIGTERM; while true; do sleep 1; done`) diff --git a/components/engine/integration-cli/docker_cli_build_test.go b/components/engine/integration-cli/docker_cli_build_test.go index 53a54ce0fd..d8275102cb 100644 --- a/components/engine/integration-cli/docker_cli_build_test.go +++ b/components/engine/integration-cli/docker_cli_build_test.go @@ -1047,7 +1047,7 @@ func (s *DockerSuite) TestBuildAddBadLinksVolume(c *check.C) { // Issue #5270 - ensure we throw a better error than "unexpected EOF" // when we can't access files in the context. func (s *DockerSuite) TestBuildWithInaccessibleFilesInContext(c *check.C) { - testRequires(c, DaemonIsLinux, UnixCli, SameHostDaemon) // test uses chown/chmod: not available on windows + testRequires(c, DaemonIsLinux, UnixCli, testEnv.IsLocalDaemon) // test uses chown/chmod: not available on windows { name := "testbuildinaccessiblefiles" @@ -1510,7 +1510,7 @@ func (s *DockerSuite) TestBuildPATH(c *check.C) { } func (s *DockerSuite) TestBuildContextCleanup(c *check.C) { - testRequires(c, SameHostDaemon) + testRequires(c, testEnv.IsLocalDaemon) name := "testbuildcontextcleanup" entries, err := ioutil.ReadDir(filepath.Join(testEnv.DaemonInfo.DockerRootDir, "tmp")) @@ -1532,7 +1532,7 @@ func (s *DockerSuite) TestBuildContextCleanup(c *check.C) { } func (s *DockerSuite) TestBuildContextCleanupFailedBuild(c *check.C) { - testRequires(c, SameHostDaemon) + testRequires(c, testEnv.IsLocalDaemon) name := "testbuildcontextcleanup" entries, err := ioutil.ReadDir(filepath.Join(testEnv.DaemonInfo.DockerRootDir, "tmp")) @@ -3971,7 +3971,7 @@ func (s *DockerSuite) TestBuildEmptyStringVolume(c *check.C) { } func (s *DockerSuite) TestBuildContainerWithCgroupParent(c *check.C) { - testRequires(c, SameHostDaemon, DaemonIsLinux) + testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux) cgroupParent := "test" data, err := ioutil.ReadFile("/proc/self/cgroup") diff --git a/components/engine/integration-cli/docker_cli_cp_test.go b/components/engine/integration-cli/docker_cli_cp_test.go index b2826ab922..e74af64d2c 100644 --- a/components/engine/integration-cli/docker_cli_cp_test.go +++ b/components/engine/integration-cli/docker_cli_cp_test.go @@ -256,7 +256,7 @@ func (s *DockerSuite) TestCpFromSymlinkToDirectory(c *check.C) { // container. func (s *DockerSuite) TestCpToSymlinkToDirectory(c *check.C) { testRequires(c, DaemonIsLinux) - testRequires(c, SameHostDaemon) // Requires local volume mount bind. + testRequires(c, testEnv.IsLocalDaemon) // Requires local volume mount bind. testVol, err := ioutil.TempDir("", "test-cp-to-symlink-to-dir-") c.Assert(err, checker.IsNil) @@ -379,7 +379,7 @@ func (s *DockerSuite) TestCpSymlinkComponent(c *check.C) { // Check that cp with unprivileged user doesn't return any error func (s *DockerSuite) TestCpUnprivilegedUser(c *check.C) { - testRequires(c, DaemonIsLinux, SameHostDaemon) + 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) @@ -404,7 +404,7 @@ func (s *DockerSuite) TestCpUnprivilegedUser(c *check.C) { func (s *DockerSuite) TestCpSpecialFiles(c *check.C) { testRequires(c, DaemonIsLinux) - testRequires(c, SameHostDaemon) + testRequires(c, testEnv.IsLocalDaemon) outDir, err := ioutil.TempDir("", "cp-test-special-files") c.Assert(err, checker.IsNil) @@ -453,7 +453,7 @@ func (s *DockerSuite) TestCpVolumePath(c *check.C) { // stat /tmp/cp-test-volumepath851508420/test gets permission denied for the user testRequires(c, NotUserNamespace) testRequires(c, DaemonIsLinux) - testRequires(c, SameHostDaemon) + testRequires(c, testEnv.IsLocalDaemon) tmpDir, err := ioutil.TempDir("", "cp-test-volumepath") c.Assert(err, checker.IsNil) @@ -560,7 +560,7 @@ func (s *DockerSuite) TestCpToStdout(c *check.C) { } func (s *DockerSuite) TestCpNameHasColon(c *check.C) { - testRequires(c, SameHostDaemon, DaemonIsLinux) + testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux) out, _ := dockerCmd(c, "run", "-d", "busybox", "/bin/sh", "-c", "echo lololol > /te:s:t") diff --git a/components/engine/integration-cli/docker_cli_cp_to_container_test.go b/components/engine/integration-cli/docker_cli_cp_to_container_test.go index 77567a3b95..27d3edcc21 100644 --- a/components/engine/integration-cli/docker_cli_cp_to_container_test.go +++ b/components/engine/integration-cli/docker_cli_cp_to_container_test.go @@ -23,7 +23,7 @@ func (s *DockerSuite) TestCpToSymlinkDestination(c *check.C) { // stat /tmp/test-cp-to-symlink-destination-262430901/vol3 gets permission denied for the user testRequires(c, NotUserNamespace) testRequires(c, DaemonIsLinux) - testRequires(c, SameHostDaemon) // Requires local volume mount bind. + testRequires(c, testEnv.IsLocalDaemon) // Requires local volume mount bind. testVol := getTestDir(c, "test-cp-to-symlink-destination-") defer os.RemoveAll(testVol) diff --git a/components/engine/integration-cli/docker_cli_cp_to_container_unix_test.go b/components/engine/integration-cli/docker_cli_cp_to_container_unix_test.go index 8f830dcf9d..ef1ad7de32 100644 --- a/components/engine/integration-cli/docker_cli_cp_to_container_unix_test.go +++ b/components/engine/integration-cli/docker_cli_cp_to_container_unix_test.go @@ -15,7 +15,7 @@ import ( ) func (s *DockerSuite) TestCpToContainerWithPermissions(c *check.C) { - testRequires(c, SameHostDaemon, DaemonIsLinux) + testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux) tmpDir := getTestDir(c, "test-cp-to-host-with-permissions") defer os.RemoveAll(tmpDir) @@ -39,7 +39,7 @@ func (s *DockerSuite) TestCpToContainerWithPermissions(c *check.C) { // Check ownership is root, both in non-userns and userns enabled modes func (s *DockerSuite) TestCpCheckDestOwnership(c *check.C) { - testRequires(c, DaemonIsLinux, SameHostDaemon) + testRequires(c, DaemonIsLinux, testEnv.IsLocalDaemon) tmpVolDir := getTestDir(c, "test-cp-tmpvol") containerID := makeTestContainer(c, testContainerOptions{volumes: []string{fmt.Sprintf("%s:/tmpvol", tmpVolDir)}}) diff --git a/components/engine/integration-cli/docker_cli_cp_utils_test.go b/components/engine/integration-cli/docker_cli_cp_utils_test.go index 79a016f0c6..3b540ae3fd 100644 --- a/components/engine/integration-cli/docker_cli_cp_utils_test.go +++ b/components/engine/integration-cli/docker_cli_cp_utils_test.go @@ -291,7 +291,7 @@ func containerStartOutputEquals(c *check.C, containerID, contents string) (err e } func defaultVolumes(tmpDir string) []string { - if SameHostDaemon() { + if testEnv.IsLocalDaemon() { return []string{ "/vol1", fmt.Sprintf("%s:/vol2", tmpDir), diff --git a/components/engine/integration-cli/docker_cli_create_test.go b/components/engine/integration-cli/docker_cli_create_test.go index cb4de73c5e..dbdf92915c 100644 --- a/components/engine/integration-cli/docker_cli_create_test.go +++ b/components/engine/integration-cli/docker_cli_create_test.go @@ -171,7 +171,7 @@ func (s *DockerSuite) TestCreateEchoStdout(c *check.C) { } func (s *DockerSuite) TestCreateVolumesCreated(c *check.C) { - testRequires(c, SameHostDaemon) + testRequires(c, testEnv.IsLocalDaemon) prefix, slash := getPrefixAndSlashFromDaemonPlatform() name := "test_create_volume" @@ -249,7 +249,7 @@ func (s *DockerSuite) TestCreateRM(c *check.C) { func (s *DockerSuite) TestCreateModeIpcContainer(c *check.C) { // Uses Linux specific functionality (--ipc) - testRequires(c, DaemonIsLinux, SameHostDaemon) + testRequires(c, DaemonIsLinux, testEnv.IsLocalDaemon) out, _ := dockerCmd(c, "create", "busybox") id := strings.TrimSpace(out) diff --git a/components/engine/integration-cli/docker_cli_daemon_plugins_test.go b/components/engine/integration-cli/docker_cli_daemon_plugins_test.go index 9a11c68089..000981d002 100644 --- a/components/engine/integration-cli/docker_cli_daemon_plugins_test.go +++ b/components/engine/integration-cli/docker_cli_daemon_plugins_test.go @@ -121,7 +121,7 @@ func (s *DockerDaemonSuite) TestDaemonShutdownLiveRestoreWithPlugins(c *check.C) // TestDaemonShutdownWithPlugins shuts down running plugins. func (s *DockerDaemonSuite) TestDaemonShutdownWithPlugins(c *check.C) { - testRequires(c, IsAmd64, Network, SameHostDaemon) + testRequires(c, IsAmd64, Network, testEnv.IsLocalDaemon) s.d.Start(c) if out, err := s.d.Cmd("plugin", "install", "--grant-all-permissions", pName); err != nil { @@ -159,7 +159,7 @@ func (s *DockerDaemonSuite) TestDaemonShutdownWithPlugins(c *check.C) { // TestDaemonKillWithPlugins leaves plugins running. func (s *DockerDaemonSuite) TestDaemonKillWithPlugins(c *check.C) { - testRequires(c, IsAmd64, Network, SameHostDaemon) + testRequires(c, IsAmd64, Network, testEnv.IsLocalDaemon) s.d.Start(c) if out, err := s.d.Cmd("plugin", "install", "--grant-all-permissions", pName); err != nil { diff --git a/components/engine/integration-cli/docker_cli_daemon_test.go b/components/engine/integration-cli/docker_cli_daemon_test.go index a1944af493..f91ef1d835 100644 --- a/components/engine/integration-cli/docker_cli_daemon_test.go +++ b/components/engine/integration-cli/docker_cli_daemon_test.go @@ -411,7 +411,7 @@ func (s *DockerDaemonSuite) TestDaemonIPv6Enabled(c *check.C) { // that running containers are given a link-local and global IPv6 address func (s *DockerDaemonSuite) TestDaemonIPv6FixedCIDR(c *check.C) { // IPv6 setup is messing with local bridge address. - testRequires(c, SameHostDaemon) + testRequires(c, testEnv.IsLocalDaemon) // Delete the docker0 bridge if its left around from previous daemon. It has to be recreated with // ipv6 enabled deleteInterface(c, "docker0") @@ -438,7 +438,7 @@ func (s *DockerDaemonSuite) TestDaemonIPv6FixedCIDR(c *check.C) { // the running containers are given an IPv6 address derived from the MAC address and the ipv6 fixed CIDR func (s *DockerDaemonSuite) TestDaemonIPv6FixedCIDRAndMac(c *check.C) { // IPv6 setup is messing with local bridge address. - testRequires(c, SameHostDaemon) + testRequires(c, testEnv.IsLocalDaemon) // Delete the docker0 bridge if its left around from previous daemon. It has to be recreated with // ipv6 enabled deleteInterface(c, "docker0") @@ -456,7 +456,7 @@ func (s *DockerDaemonSuite) TestDaemonIPv6FixedCIDRAndMac(c *check.C) { // TestDaemonIPv6HostMode checks that when the running a container with // network=host the host ipv6 addresses are not removed func (s *DockerDaemonSuite) TestDaemonIPv6HostMode(c *check.C) { - testRequires(c, SameHostDaemon) + testRequires(c, testEnv.IsLocalDaemon) deleteInterface(c, "docker0") s.d.StartWithBusybox(c, "--ipv6", "--fixed-cidr-v6=2001:db8:2::/64") @@ -820,7 +820,7 @@ func (s *DockerDaemonSuite) TestDaemonDefaultGatewayIPv4ExplicitOutsideContainer } func (s *DockerDaemonSuite) TestDaemonDefaultNetworkInvalidClusterConfig(c *check.C) { - testRequires(c, DaemonIsLinux, SameHostDaemon) + testRequires(c, DaemonIsLinux, testEnv.IsLocalDaemon) // Start daemon without docker0 bridge defaultNetworkBridge := "docker0" @@ -1768,7 +1768,7 @@ func (s *DockerDaemonSuite) TestBridgeIPIsExcludedFromAllocatorPool(c *check.C) // Test daemon for no space left on device error func (s *DockerDaemonSuite) TestDaemonNoSpaceLeftOnDeviceError(c *check.C) { - testRequires(c, SameHostDaemon, DaemonIsLinux, Network) + testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux, Network) testDir, err := ioutil.TempDir("", "no-space-left-on-device-test") c.Assert(err, checker.IsNil) @@ -2201,7 +2201,7 @@ func (s *DockerDaemonSuite) TestDaemonDebugLog(c *check.C) { } func (s *DockerDaemonSuite) TestDaemonDiscoveryBackendConfigReload(c *check.C) { - testRequires(c, SameHostDaemon, DaemonIsLinux) + testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux) // daemon config file daemonConfig := `{ "debug" : false }` @@ -2272,7 +2272,7 @@ func (s *DockerDaemonSuite) TestDaemonMaxConcurrency(c *check.C) { // Test case for #20936, #22443 func (s *DockerDaemonSuite) TestDaemonMaxConcurrencyWithConfigFile(c *check.C) { - testRequires(c, SameHostDaemon, DaemonIsLinux) + testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux) // daemon config file configFilePath := "test.json" @@ -2313,7 +2313,7 @@ func (s *DockerDaemonSuite) TestDaemonMaxConcurrencyWithConfigFile(c *check.C) { // Test case for #20936, #22443 func (s *DockerDaemonSuite) TestDaemonMaxConcurrencyWithConfigFileReload(c *check.C) { - testRequires(c, SameHostDaemon, DaemonIsLinux) + testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux) // daemon config file configFilePath := "test.json" @@ -2385,7 +2385,7 @@ func (s *DockerDaemonSuite) TestBuildOnDisabledBridgeNetworkDaemon(c *check.C) { // Test case for #21976 func (s *DockerDaemonSuite) TestDaemonDNSFlagsInHostMode(c *check.C) { - testRequires(c, SameHostDaemon, DaemonIsLinux) + testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux) s.d.StartWithBusybox(c, "--dns", "1.2.3.4", "--dns-search", "example.com", "--dns-opt", "timeout:3") @@ -2641,7 +2641,7 @@ func (s *DockerDaemonSuite) TestDaemonRestartSaveContainerExitCode(c *check.C) { } func (s *DockerDaemonSuite) TestDaemonWithUserlandProxyPath(c *check.C) { - testRequires(c, SameHostDaemon, DaemonIsLinux) + testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux) dockerProxyPath, err := exec.LookPath("docker-proxy") c.Assert(err, checker.IsNil) @@ -2672,7 +2672,7 @@ func (s *DockerDaemonSuite) TestDaemonWithUserlandProxyPath(c *check.C) { // Test case for #22471 func (s *DockerDaemonSuite) TestDaemonShutdownTimeout(c *check.C) { - testRequires(c, SameHostDaemon) + testRequires(c, testEnv.IsLocalDaemon) s.d.StartWithBusybox(c, "--shutdown-timeout=3") _, err := s.d.Cmd("run", "-d", "busybox", "top") @@ -2693,7 +2693,7 @@ func (s *DockerDaemonSuite) TestDaemonShutdownTimeout(c *check.C) { // Test case for #22471 func (s *DockerDaemonSuite) TestDaemonShutdownTimeoutWithConfigFile(c *check.C) { - testRequires(c, SameHostDaemon) + testRequires(c, testEnv.IsLocalDaemon) // daemon config file configFilePath := "test.json" @@ -2755,7 +2755,7 @@ func (s *DockerDaemonSuite) TestExecWithUserAfterLiveRestore(c *check.C) { } func (s *DockerDaemonSuite) TestRemoveContainerAfterLiveRestore(c *check.C) { - testRequires(c, DaemonIsLinux, overlayFSSupported, SameHostDaemon) + testRequires(c, DaemonIsLinux, overlayFSSupported, testEnv.IsLocalDaemon) s.d.StartWithBusybox(c, "--live-restore", "--storage-driver", "overlay") out, err := s.d.Cmd("run", "-d", "--name=top", "busybox", "top") c.Assert(err, check.IsNil, check.Commentf("Output: %s", out)) @@ -2788,7 +2788,7 @@ func (s *DockerDaemonSuite) TestRemoveContainerAfterLiveRestore(c *check.C) { // #29598 func (s *DockerDaemonSuite) TestRestartPolicyWithLiveRestore(c *check.C) { - testRequires(c, DaemonIsLinux, SameHostDaemon) + testRequires(c, DaemonIsLinux, testEnv.IsLocalDaemon) s.d.StartWithBusybox(c, "--live-restore") out, err := s.d.Cmd("run", "-d", "--restart", "always", "busybox", "top") @@ -2937,7 +2937,7 @@ func testDaemonStartIpcMode(c *check.C, from, mode string, valid bool) { // arguments for default IPC mode, and bails out with incorrect ones. // Both CLI option (--default-ipc-mode) and config parameter are tested. func (s *DockerDaemonSuite) TestDaemonStartWithIpcModes(c *check.C) { - testRequires(c, DaemonIsLinux, SameHostDaemon) + testRequires(c, DaemonIsLinux, testEnv.IsLocalDaemon) ipcModes := []struct { mode string @@ -3002,7 +3002,7 @@ func (s *DockerDaemonSuite) TestDaemonRestartIpcMode(c *check.C) { // TestFailedPluginRemove makes sure that a failed plugin remove does not block // the daemon from starting func (s *DockerDaemonSuite) TestFailedPluginRemove(c *check.C) { - testRequires(c, DaemonIsLinux, IsAmd64, SameHostDaemon) + testRequires(c, DaemonIsLinux, IsAmd64, testEnv.IsLocalDaemon) d := daemon.New(c, dockerBinary, dockerdBinary) d.Start(c) cli := d.NewClientT(c) diff --git a/components/engine/integration-cli/docker_cli_events_test.go b/components/engine/integration-cli/docker_cli_events_test.go index c8e2a36962..b042faf916 100644 --- a/components/engine/integration-cli/docker_cli_events_test.go +++ b/components/engine/integration-cli/docker_cli_events_test.go @@ -564,7 +564,7 @@ func (s *DockerRegistrySuite) TestEventsImageFilterPush(c *check.C) { func (s *DockerSuite) TestEventsFilterType(c *check.C) { // FIXME(vdemeester) fails on e2e run - testRequires(c, SameHostDaemon) + testRequires(c, testEnv.IsLocalDaemon) since := daemonUnixTime(c) name := "labelfiltertest" label := "io.docker.testing=image" diff --git a/components/engine/integration-cli/docker_cli_events_unix_test.go b/components/engine/integration-cli/docker_cli_events_unix_test.go index 92403e006e..73e558672c 100644 --- a/components/engine/integration-cli/docker_cli_events_unix_test.go +++ b/components/engine/integration-cli/docker_cli_events_unix_test.go @@ -389,7 +389,7 @@ func (s *DockerSuite) TestEventsFilterNetworkID(c *check.C) { } func (s *DockerDaemonSuite) TestDaemonEvents(c *check.C) { - testRequires(c, SameHostDaemon, DaemonIsLinux) + testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux) // daemon config file configFilePath := "test.json" @@ -458,7 +458,7 @@ func (s *DockerDaemonSuite) TestDaemonEvents(c *check.C) { } func (s *DockerDaemonSuite) TestDaemonEventsWithFilters(c *check.C) { - testRequires(c, SameHostDaemon, DaemonIsLinux) + testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux) // daemon config file configFilePath := "test.json" diff --git a/components/engine/integration-cli/docker_cli_exec_test.go b/components/engine/integration-cli/docker_cli_exec_test.go index d998876f6e..cdfd307041 100644 --- a/components/engine/integration-cli/docker_cli_exec_test.go +++ b/components/engine/integration-cli/docker_cli_exec_test.go @@ -86,7 +86,7 @@ func (s *DockerSuite) TestExecAfterContainerRestart(c *check.C) { func (s *DockerDaemonSuite) TestExecAfterDaemonRestart(c *check.C) { // TODO Windows CI: Requires a little work to get this ported. - testRequires(c, DaemonIsLinux, SameHostDaemon) + testRequires(c, DaemonIsLinux, testEnv.IsLocalDaemon) s.d.StartWithBusybox(c) out, err := s.d.Cmd("run", "-d", "--name", "top", "-p", "80", "busybox:latest", "top") @@ -394,7 +394,7 @@ func (s *DockerSuite) TestLinksPingLinkedContainersOnRename(c *check.C) { func (s *DockerSuite) TestRunMutableNetworkFiles(c *check.C) { // Not applicable on Windows to Windows CI. - testRequires(c, SameHostDaemon, DaemonIsLinux) + testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux) for _, fn := range []string{"resolv.conf", "hosts"} { containers := cli.DockerCmd(c, "ps", "-q", "-a").Combined() if containers != "" { diff --git a/components/engine/integration-cli/docker_cli_exec_unix_test.go b/components/engine/integration-cli/docker_cli_exec_unix_test.go index 4c77df4f11..9c58430282 100644 --- a/components/engine/integration-cli/docker_cli_exec_unix_test.go +++ b/components/engine/integration-cli/docker_cli_exec_unix_test.go @@ -45,7 +45,7 @@ func (s *DockerSuite) TestExecInteractiveStdinClose(c *check.C) { } func (s *DockerSuite) TestExecTTY(c *check.C) { - testRequires(c, DaemonIsLinux, SameHostDaemon) + testRequires(c, DaemonIsLinux, testEnv.IsLocalDaemon) dockerCmd(c, "run", "-d", "--name=test", "busybox", "sh", "-c", "echo hello > /foo && top") cmd := exec.Command(dockerBinary, "exec", "-it", "test", "sh") @@ -75,7 +75,7 @@ func (s *DockerSuite) TestExecTTY(c *check.C) { // Test the TERM env var is set when -t is provided on exec func (s *DockerSuite) TestExecWithTERM(c *check.C) { - testRequires(c, DaemonIsLinux, SameHostDaemon) + testRequires(c, DaemonIsLinux, testEnv.IsLocalDaemon) out, _ := dockerCmd(c, "run", "-id", "busybox", "/bin/cat") contID := strings.TrimSpace(out) cmd := exec.Command(dockerBinary, "exec", "-t", contID, "sh", "-c", "if [ -z $TERM ]; then exit 1; else exit 0; fi") @@ -87,7 +87,7 @@ func (s *DockerSuite) TestExecWithTERM(c *check.C) { // Test that the TERM env var is not set on exec when -t is not provided, even if it was set // on run func (s *DockerSuite) TestExecWithNoTERM(c *check.C) { - testRequires(c, DaemonIsLinux, SameHostDaemon) + testRequires(c, DaemonIsLinux, testEnv.IsLocalDaemon) out, _ := dockerCmd(c, "run", "-itd", "busybox", "/bin/cat") contID := strings.TrimSpace(out) cmd := exec.Command(dockerBinary, "exec", contID, "sh", "-c", "if [ -z $TERM ]; then exit 0; else exit 1; fi") diff --git a/components/engine/integration-cli/docker_cli_external_volume_driver_unix_test.go b/components/engine/integration-cli/docker_cli_external_volume_driver_unix_test.go index da8bb7e011..063f49822b 100644 --- a/components/engine/integration-cli/docker_cli_external_volume_driver_unix_test.go +++ b/components/engine/integration-cli/docker_cli_external_volume_driver_unix_test.go @@ -51,7 +51,7 @@ type DockerExternalVolumeSuite struct { } func (s *DockerExternalVolumeSuite) SetUpTest(c *check.C) { - testRequires(c, SameHostDaemon) + testRequires(c, testEnv.IsLocalDaemon) s.d = daemon.New(c, dockerBinary, dockerdBinary, testdaemon.WithEnvironment(testEnv.Execution)) s.ec = &eventCounter{} } diff --git a/components/engine/integration-cli/docker_cli_info_test.go b/components/engine/integration-cli/docker_cli_info_test.go index 65091029ee..e399d1477a 100644 --- a/components/engine/integration-cli/docker_cli_info_test.go +++ b/components/engine/integration-cli/docker_cli_info_test.go @@ -70,7 +70,7 @@ func (s *DockerSuite) TestInfoFormat(c *check.C) { // TestInfoDiscoveryBackend verifies that a daemon run with `--cluster-advertise` and // `--cluster-store` properly show the backend's endpoint in info output. func (s *DockerSuite) TestInfoDiscoveryBackend(c *check.C) { - testRequires(c, SameHostDaemon, DaemonIsLinux) + testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux) d := daemon.New(c, dockerBinary, dockerdBinary, testdaemon.WithEnvironment(testEnv.Execution)) discoveryBackend := "consul://consuladdr:consulport/some/path" @@ -87,7 +87,7 @@ func (s *DockerSuite) TestInfoDiscoveryBackend(c *check.C) { // TestInfoDiscoveryInvalidAdvertise verifies that a daemon run with // an invalid `--cluster-advertise` configuration func (s *DockerSuite) TestInfoDiscoveryInvalidAdvertise(c *check.C) { - testRequires(c, SameHostDaemon, DaemonIsLinux) + testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux) d := daemon.New(c, dockerBinary, dockerdBinary, testdaemon.WithEnvironment(testEnv.Execution)) discoveryBackend := "consul://consuladdr:consulport/some/path" @@ -104,7 +104,7 @@ func (s *DockerSuite) TestInfoDiscoveryInvalidAdvertise(c *check.C) { // TestInfoDiscoveryAdvertiseInterfaceName verifies that a daemon run with `--cluster-advertise` // configured with interface name properly show the advertise ip-address in info output. func (s *DockerSuite) TestInfoDiscoveryAdvertiseInterfaceName(c *check.C) { - testRequires(c, SameHostDaemon, Network, DaemonIsLinux) + testRequires(c, testEnv.IsLocalDaemon, Network, DaemonIsLinux) d := daemon.New(c, dockerBinary, dockerdBinary, testdaemon.WithEnvironment(testEnv.Execution)) discoveryBackend := "consul://consuladdr:consulport/some/path" @@ -175,7 +175,7 @@ func (s *DockerSuite) TestInfoDisplaysStoppedContainers(c *check.C) { } func (s *DockerSuite) TestInfoDebug(c *check.C) { - testRequires(c, SameHostDaemon, DaemonIsLinux) + testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux) d := daemon.New(c, dockerBinary, dockerdBinary, testdaemon.WithEnvironment(testEnv.Execution)) d.Start(c, "--debug") @@ -193,7 +193,7 @@ func (s *DockerSuite) TestInfoDebug(c *check.C) { } func (s *DockerSuite) TestInsecureRegistries(c *check.C) { - testRequires(c, SameHostDaemon, DaemonIsLinux) + testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux) registryCIDR := "192.168.1.0/24" registryHost := "insecurehost.com:5000" @@ -210,7 +210,7 @@ func (s *DockerSuite) TestInsecureRegistries(c *check.C) { } func (s *DockerDaemonSuite) TestRegistryMirrors(c *check.C) { - testRequires(c, SameHostDaemon, DaemonIsLinux) + testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux) registryMirror1 := "https://192.168.1.2" registryMirror2 := "http://registry.mirror.com:5000" diff --git a/components/engine/integration-cli/docker_cli_info_unix_test.go b/components/engine/integration-cli/docker_cli_info_unix_test.go index d55c05c4a5..3ac1f9534f 100644 --- a/components/engine/integration-cli/docker_cli_info_unix_test.go +++ b/components/engine/integration-cli/docker_cli_info_unix_test.go @@ -8,7 +8,7 @@ import ( ) func (s *DockerSuite) TestInfoSecurityOptions(c *check.C) { - testRequires(c, SameHostDaemon, seccompEnabled, Apparmor, DaemonIsLinux) + testRequires(c, testEnv.IsLocalDaemon, seccompEnabled, Apparmor, DaemonIsLinux) out, _ := dockerCmd(c, "info") c.Assert(out, checker.Contains, "Security Options:\n apparmor\n seccomp\n Profile: default\n") diff --git a/components/engine/integration-cli/docker_cli_links_test.go b/components/engine/integration-cli/docker_cli_links_test.go index 17b25d7994..3ddeb38b23 100644 --- a/components/engine/integration-cli/docker_cli_links_test.go +++ b/components/engine/integration-cli/docker_cli_links_test.go @@ -139,7 +139,7 @@ func (s *DockerSuite) TestLinksNotStartedParentNotFail(c *check.C) { func (s *DockerSuite) TestLinksHostsFilesInject(c *check.C) { testRequires(c, DaemonIsLinux) - testRequires(c, SameHostDaemon, ExecSupport) + testRequires(c, testEnv.IsLocalDaemon, ExecSupport) out, _ := dockerCmd(c, "run", "-itd", "--name", "one", "busybox", "top") idOne := strings.TrimSpace(out) @@ -157,7 +157,7 @@ func (s *DockerSuite) TestLinksHostsFilesInject(c *check.C) { func (s *DockerSuite) TestLinksUpdateOnRestart(c *check.C) { testRequires(c, DaemonIsLinux) - testRequires(c, SameHostDaemon, ExecSupport) + testRequires(c, testEnv.IsLocalDaemon, ExecSupport) 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(string(out)) diff --git a/components/engine/integration-cli/docker_cli_network_unix_test.go b/components/engine/integration-cli/docker_cli_network_unix_test.go index d3d6256a75..734e3ee88c 100644 --- a/components/engine/integration-cli/docker_cli_network_unix_test.go +++ b/components/engine/integration-cli/docker_cli_network_unix_test.go @@ -590,7 +590,7 @@ func (s *DockerNetworkSuite) TestDockerNetworkConnectDisconnect(c *check.C) { } func (s *DockerNetworkSuite) TestDockerNetworkIPAMMultipleNetworks(c *check.C) { - testRequires(c, SameHostDaemon) + testRequires(c, testEnv.IsLocalDaemon) // test0 bridge network dockerCmd(c, "network", "create", "--subnet=192.168.0.0/16", "test1") assertNwIsAvailable(c, "test1") @@ -631,7 +631,7 @@ func (s *DockerNetworkSuite) TestDockerNetworkIPAMMultipleNetworks(c *check.C) { } func (s *DockerNetworkSuite) TestDockerNetworkCustomIPAM(c *check.C) { - testRequires(c, SameHostDaemon) + testRequires(c, testEnv.IsLocalDaemon) // Create a bridge network using custom ipam driver dockerCmd(c, "network", "create", "--ipam-driver", dummyIPAMDriver, "br0") assertNwIsAvailable(c, "br0") @@ -647,7 +647,7 @@ func (s *DockerNetworkSuite) TestDockerNetworkCustomIPAM(c *check.C) { } func (s *DockerNetworkSuite) TestDockerNetworkIPAMOptions(c *check.C) { - testRequires(c, SameHostDaemon) + testRequires(c, testEnv.IsLocalDaemon) // Create a bridge network using custom ipam driver and options dockerCmd(c, "network", "create", "--ipam-driver", dummyIPAMDriver, "--ipam-opt", "opt1=drv1", "--ipam-opt", "opt2=drv2", "br0") assertNwIsAvailable(c, "br0") @@ -660,7 +660,7 @@ func (s *DockerNetworkSuite) TestDockerNetworkIPAMOptions(c *check.C) { } func (s *DockerNetworkSuite) TestDockerNetworkNullIPAMDriver(c *check.C) { - testRequires(c, SameHostDaemon) + testRequires(c, testEnv.IsLocalDaemon) // Create a network with null ipam driver _, _, err := dockerCmdWithError("network", "create", "-d", dummyNetworkDriver, "--ipam-driver", "null", "test000") c.Assert(err, check.IsNil) @@ -766,7 +766,7 @@ func (s *DockerNetworkSuite) TestDockerNetworkIPAMInvalidCombinations(c *check.C } func (s *DockerNetworkSuite) TestDockerNetworkDriverOptions(c *check.C) { - testRequires(c, SameHostDaemon) + testRequires(c, testEnv.IsLocalDaemon) dockerCmd(c, "network", "create", "-d", dummyNetworkDriver, "-o", "opt1=drv1", "-o", "opt2=drv2", "testopt") assertNwIsAvailable(c, "testopt") gopts := remoteDriverNetworkRequest.Options[netlabel.GenericData] @@ -950,7 +950,7 @@ func (s *DockerNetworkSuite) TestDockerNetworkLinkOnDefaultNetworkOnly(c *check. } func (s *DockerNetworkSuite) TestDockerNetworkOverlayPortMapping(c *check.C) { - testRequires(c, SameHostDaemon) + testRequires(c, testEnv.IsLocalDaemon) // Verify exposed ports are present in ps output when running a container on // a network managed by a driver which does not provide the default gateway // for the container @@ -977,7 +977,7 @@ func (s *DockerNetworkSuite) TestDockerNetworkOverlayPortMapping(c *check.C) { } func (s *DockerNetworkSuite) TestDockerNetworkDriverUngracefulRestart(c *check.C) { - testRequires(c, DaemonIsLinux, NotUserNamespace, SameHostDaemon) + testRequires(c, DaemonIsLinux, NotUserNamespace, testEnv.IsLocalDaemon) dnd := "dnd" did := "did" @@ -1018,7 +1018,7 @@ func (s *DockerNetworkSuite) TestDockerNetworkDriverUngracefulRestart(c *check.C } func (s *DockerNetworkSuite) TestDockerNetworkMacInspect(c *check.C) { - testRequires(c, SameHostDaemon) + testRequires(c, testEnv.IsLocalDaemon) // Verify endpoint MAC address is correctly populated in container's network settings nwn := "ov" ctn := "bb" @@ -1084,7 +1084,7 @@ func verifyContainerIsConnectedToNetworks(c *check.C, d *daemon.Daemon, cName st } func (s *DockerNetworkSuite) TestDockerNetworkMultipleNetworksGracefulDaemonRestart(c *check.C) { - testRequires(c, SameHostDaemon) + testRequires(c, testEnv.IsLocalDaemon) cName := "bb" nwList := []string{"nw1", "nw2", "nw3"} @@ -1103,7 +1103,7 @@ func (s *DockerNetworkSuite) TestDockerNetworkMultipleNetworksGracefulDaemonRest } func (s *DockerNetworkSuite) TestDockerNetworkMultipleNetworksUngracefulDaemonRestart(c *check.C) { - testRequires(c, SameHostDaemon) + testRequires(c, testEnv.IsLocalDaemon) cName := "cc" nwList := []string{"nw1", "nw2", "nw3"} @@ -1130,7 +1130,7 @@ func (s *DockerNetworkSuite) TestDockerNetworkRunNetByID(c *check.C) { } func (s *DockerNetworkSuite) TestDockerNetworkHostModeUngracefulDaemonRestart(c *check.C) { - testRequires(c, DaemonIsLinux, NotUserNamespace, SameHostDaemon) + testRequires(c, DaemonIsLinux, NotUserNamespace, testEnv.IsLocalDaemon) s.d.StartWithBusybox(c) // Run a few containers on host network @@ -1256,7 +1256,7 @@ func (s *DockerNetworkSuite) TestDockerNetworkRestartWithMultipleNetworks(c *che } func (s *DockerNetworkSuite) TestDockerNetworkConnectDisconnectToStoppedContainer(c *check.C) { - testRequires(c, SameHostDaemon) + testRequires(c, testEnv.IsLocalDaemon) dockerCmd(c, "network", "create", "test") dockerCmd(c, "create", "--name=foo", "busybox", "top") dockerCmd(c, "network", "connect", "test", "foo") @@ -1785,7 +1785,7 @@ func (s *DockerNetworkSuite) TestDockerNetworkDisconnectFromBridge(c *check.C) { // TestConntrackFlowsLeak covers the failure scenario of ticket: https://github.com/docker/docker/issues/8795 // Validates that conntrack is correctly cleaned once a container is destroyed func (s *DockerNetworkSuite) TestConntrackFlowsLeak(c *check.C) { - testRequires(c, IsAmd64, DaemonIsLinux, Network, SameHostDaemon) + testRequires(c, IsAmd64, DaemonIsLinux, Network, testEnv.IsLocalDaemon) // Create a new network cli.DockerCmd(c, "network", "create", "--subnet=192.168.10.0/24", "--gateway=192.168.10.1", "-o", "com.docker.network.bridge.host_binding_ipv4=192.168.10.1", "testbind") diff --git a/components/engine/integration-cli/docker_cli_plugins_test.go b/components/engine/integration-cli/docker_cli_plugins_test.go index 2cc5bfe2ff..802a745275 100644 --- a/components/engine/integration-cli/docker_cli_plugins_test.go +++ b/components/engine/integration-cli/docker_cli_plugins_test.go @@ -440,7 +440,7 @@ enabled: false`, id, name) } func (s *DockerSuite) TestPluginUpgrade(c *check.C) { - testRequires(c, DaemonIsLinux, Network, SameHostDaemon, IsAmd64, NotUserNamespace) + testRequires(c, DaemonIsLinux, Network, testEnv.IsLocalDaemon, IsAmd64, NotUserNamespace) plugin := "cpuguy83/docker-volume-driver-plugin-local:latest" pluginV2 := "cpuguy83/docker-volume-driver-plugin-local:v2" @@ -472,7 +472,7 @@ func (s *DockerSuite) TestPluginUpgrade(c *check.C) { } func (s *DockerSuite) TestPluginMetricsCollector(c *check.C) { - testRequires(c, DaemonIsLinux, Network, SameHostDaemon, IsAmd64) + testRequires(c, DaemonIsLinux, Network, testEnv.IsLocalDaemon, IsAmd64) d := daemon.New(c, dockerBinary, dockerdBinary) d.Start(c) defer d.Stop(c) diff --git a/components/engine/integration-cli/docker_cli_proxy_test.go b/components/engine/integration-cli/docker_cli_proxy_test.go index 52159aa9c5..e57c9c2c78 100644 --- a/components/engine/integration-cli/docker_cli_proxy_test.go +++ b/components/engine/integration-cli/docker_cli_proxy_test.go @@ -10,7 +10,7 @@ import ( ) func (s *DockerSuite) TestCLIProxyDisableProxyUnixSock(c *check.C) { - testRequires(c, DaemonIsLinux, SameHostDaemon) + testRequires(c, DaemonIsLinux, testEnv.IsLocalDaemon) icmd.RunCmd(icmd.Cmd{ Command: []string{dockerBinary, "info"}, @@ -21,7 +21,7 @@ func (s *DockerSuite) TestCLIProxyDisableProxyUnixSock(c *check.C) { // Can't use localhost here since go has a special case to not use proxy if connecting to localhost // See https://golang.org/pkg/net/http/#ProxyFromEnvironment func (s *DockerDaemonSuite) TestCLIProxyProxyTCPSock(c *check.C) { - testRequires(c, SameHostDaemon) + testRequires(c, testEnv.IsLocalDaemon) // get the IP to use to connect since we can't use localhost addrs, err := net.InterfaceAddrs() c.Assert(err, checker.IsNil) diff --git a/components/engine/integration-cli/docker_cli_restart_test.go b/components/engine/integration-cli/docker_cli_restart_test.go index 791677e6e0..7df6981709 100644 --- a/components/engine/integration-cli/docker_cli_restart_test.go +++ b/components/engine/integration-cli/docker_cli_restart_test.go @@ -76,7 +76,7 @@ func (s *DockerSuite) TestRestartWithVolumes(c *check.C) { } func (s *DockerSuite) TestRestartDisconnectedContainer(c *check.C) { - testRequires(c, DaemonIsLinux, SameHostDaemon, NotUserNamespace, NotArm) + testRequires(c, DaemonIsLinux, testEnv.IsLocalDaemon, NotUserNamespace, NotArm) // Run a container on the default bridge network out, _ := dockerCmd(c, "run", "-d", "--name", "c0", "busybox", "top") @@ -164,7 +164,7 @@ func (s *DockerSuite) TestRestartContainerwithGoodContainer(c *check.C) { } func (s *DockerSuite) TestRestartContainerSuccess(c *check.C) { - testRequires(c, SameHostDaemon) + testRequires(c, testEnv.IsLocalDaemon) out := runSleepingContainer(c, "-d", "--restart=always") id := strings.TrimSpace(out) @@ -191,7 +191,7 @@ func (s *DockerSuite) TestRestartContainerSuccess(c *check.C) { func (s *DockerSuite) TestRestartWithPolicyUserDefinedNetwork(c *check.C) { // TODO Windows. This may be portable following HNS integration post TP5. - testRequires(c, DaemonIsLinux, SameHostDaemon, NotUserNamespace, NotArm) + testRequires(c, DaemonIsLinux, testEnv.IsLocalDaemon, NotUserNamespace, NotArm) dockerCmd(c, "network", "create", "-d", "bridge", "udNet") dockerCmd(c, "run", "-d", "--net=udNet", "--name=first", "busybox", "top") @@ -234,7 +234,7 @@ func (s *DockerSuite) TestRestartWithPolicyUserDefinedNetwork(c *check.C) { } func (s *DockerSuite) TestRestartPolicyAfterRestart(c *check.C) { - testRequires(c, SameHostDaemon) + testRequires(c, testEnv.IsLocalDaemon) out := runSleepingContainer(c, "-d", "--restart=always") id := strings.TrimSpace(out) diff --git a/components/engine/integration-cli/docker_cli_run_test.go b/components/engine/integration-cli/docker_cli_run_test.go index 8393f3cb40..2a95853a43 100644 --- a/components/engine/integration-cli/docker_cli_run_test.go +++ b/components/engine/integration-cli/docker_cli_run_test.go @@ -383,7 +383,7 @@ func (s *DockerSuite) TestRunCreateVolumesInSymlinkDir(c *check.C) { ) // This test cannot run on a Windows daemon as // Windows does not support symlinks inside a volume path - testRequires(c, SameHostDaemon, DaemonIsLinux) + testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux) name := "test-volume-symlink" dir, err := ioutil.TempDir("", name) @@ -427,7 +427,7 @@ func (s *DockerSuite) TestRunCreateVolumesInSymlinkDir2(c *check.C) { ) // This test cannot run on a Windows daemon as // Windows does not support symlinks inside a volume path - testRequires(c, SameHostDaemon, DaemonIsLinux) + testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux) name := "test-volume-symlink2" if testEnv.OSType == "windows" { @@ -494,7 +494,7 @@ func (s *DockerSuite) TestRunVolumesFromInReadWriteMode(c *check.C) { } func (s *DockerSuite) TestVolumesFromGetsProperMode(c *check.C) { - testRequires(c, SameHostDaemon) + testRequires(c, testEnv.IsLocalDaemon) prefix, slash := getPrefixAndSlashFromDaemonPlatform() hostpath := RandomTmpDirPath("test", testEnv.OSType) if err := os.MkdirAll(hostpath, 0755); err != nil { @@ -525,7 +525,7 @@ func (s *DockerSuite) TestRunNoDupVolumes(c *check.C) { someplace := ":/someplace" if testEnv.OSType == "windows" { // Windows requires that the source directory exists before calling HCS - testRequires(c, SameHostDaemon) + testRequires(c, testEnv.IsLocalDaemon) someplace = `:c:\someplace` if err := os.MkdirAll(path1, 0755); err != nil { c.Fatalf("Failed to create %s: %q", path1, err) @@ -1198,7 +1198,7 @@ func (s *DockerSuite) TestRunAddingOptionalDevicesInvalidMode(c *check.C) { func (s *DockerSuite) TestRunModeHostname(c *check.C) { // Not applicable on Windows as Windows does not support -h - testRequires(c, SameHostDaemon, DaemonIsLinux, NotUserNamespace) + testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux, NotUserNamespace) out, _ := dockerCmd(c, "run", "-h=testhostname", "busybox", "cat", "/etc/hostname") @@ -1253,7 +1253,7 @@ func (s *DockerSuite) TestRunDisallowBindMountingRootToRoot(c *check.C) { // Verify that a container gets default DNS when only localhost resolvers exist func (s *DockerSuite) TestRunDNSDefaultOptions(c *check.C) { // Not applicable on Windows as this is testing Unix specific functionality - testRequires(c, SameHostDaemon, DaemonIsLinux) + testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux) // preserve original resolv.conf for restoring after test origResolvConf, err := ioutil.ReadFile("/etc/resolv.conf") @@ -1321,7 +1321,7 @@ func (s *DockerSuite) TestRunDNSRepeatOptions(c *check.C) { func (s *DockerSuite) TestRunDNSOptionsBasedOnHostResolvConf(c *check.C) { // Not applicable on Windows as testing Unix specific functionality - testRequires(c, SameHostDaemon, DaemonIsLinux) + testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux) origResolvConf, err := ioutil.ReadFile("/etc/resolv.conf") if os.IsNotExist(err) { @@ -1403,7 +1403,7 @@ func (s *DockerSuite) TestRunDNSOptionsBasedOnHostResolvConf(c *check.C) { // check if the container resolv.conf file has at least 0644 perm. func (s *DockerSuite) TestRunNonRootUserResolvName(c *check.C) { // Not applicable on Windows as Windows does not support --user - testRequires(c, SameHostDaemon, Network, DaemonIsLinux, NotArm) + testRequires(c, testEnv.IsLocalDaemon, Network, DaemonIsLinux, NotArm) dockerCmd(c, "run", "--name=testperm", "--user=nobody", "busybox", "nslookup", "apt.dockerproject.org") @@ -1425,7 +1425,7 @@ func (s *DockerSuite) TestRunNonRootUserResolvName(c *check.C) { // uses the host's /etc/resolv.conf and does not have any dns options provided. func (s *DockerSuite) TestRunResolvconfUpdate(c *check.C) { // Not applicable on Windows as testing unix specific functionality - testRequires(c, SameHostDaemon, DaemonIsLinux) + testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux) c.Skip("Unstable test, to be re-activated once #19937 is resolved") tmpResolvConf := []byte("search pommesfrites.fr\nnameserver 12.34.56.78\n") @@ -1880,7 +1880,7 @@ func (s *DockerSuite) TestRunEntrypoint(c *check.C) { } func (s *DockerSuite) TestRunBindMounts(c *check.C) { - testRequires(c, SameHostDaemon) + testRequires(c, testEnv.IsLocalDaemon) if testEnv.OSType == "linux" { testRequires(c, DaemonIsLinux, NotUserNamespace) } @@ -2030,7 +2030,7 @@ func (s *DockerSuite) TestRunWithInvalidMacAddress(c *check.C) { func (s *DockerSuite) TestRunDeallocatePortOnMissingIptablesRule(c *check.C) { // TODO Windows. Network settings are not propagated back to inspect. - testRequires(c, SameHostDaemon, DaemonIsLinux) + testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux) out := cli.DockerCmd(c, "run", "-d", "-p", "23:23", "busybox", "top").Combined() @@ -2048,7 +2048,7 @@ func (s *DockerSuite) TestRunPortInUse(c *check.C) { // TODO Windows. The duplicate NAT message returned by Windows will be // changing as is currently completely undecipherable. Does need modifying // to run sh rather than top though as top isn't in Windows busybox. - testRequires(c, SameHostDaemon, DaemonIsLinux) + testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux) port := "1234" dockerCmd(c, "run", "-d", "-p", port+":80", "busybox", "top") @@ -2086,7 +2086,7 @@ func (s *DockerSuite) TestRunAllocatePortInReservedRange(c *check.C) { // Regression test for #7792 func (s *DockerSuite) TestRunMountOrdering(c *check.C) { // TODO Windows: Post RS1. Windows does not support nested mounts. - testRequires(c, SameHostDaemon, DaemonIsLinux, NotUserNamespace) + testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux, NotUserNamespace) prefix, _ := getPrefixAndSlashFromDaemonPlatform() tmpDir, err := ioutil.TempDir("", "docker_nested_mount_test") @@ -2131,7 +2131,7 @@ func (s *DockerSuite) TestRunMountOrdering(c *check.C) { // Regression test for https://github.com/docker/docker/issues/8259 func (s *DockerSuite) TestRunReuseBindVolumeThatIsSymlink(c *check.C) { // Not applicable on Windows as Windows does not support volumes - testRequires(c, SameHostDaemon, DaemonIsLinux, NotUserNamespace) + testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux, NotUserNamespace) prefix, _ := getPrefixAndSlashFromDaemonPlatform() tmpDir, err := ioutil.TempDir(os.TempDir(), "testlink") @@ -2210,7 +2210,7 @@ func (s *DockerSuite) TestRunNoOutputFromPullInStdout(c *check.C) { } func (s *DockerSuite) TestRunVolumesCleanPaths(c *check.C) { - testRequires(c, SameHostDaemon) + testRequires(c, testEnv.IsLocalDaemon) prefix, slash := getPrefixAndSlashFromDaemonPlatform() buildImageSuccessfully(c, "run_volumes_clean_paths", build.WithDockerfile(`FROM busybox VOLUME `+prefix+`/foo/`)) @@ -2299,7 +2299,7 @@ func (s *DockerSuite) TestRunExposePort(c *check.C) { func (s *DockerSuite) TestRunModeIpcHost(c *check.C) { // Not applicable on Windows as uses Unix-specific capabilities - testRequires(c, SameHostDaemon, DaemonIsLinux, NotUserNamespace) + testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux, NotUserNamespace) hostIpc, err := os.Readlink("/proc/1/ns/ipc") if err != nil { @@ -2330,7 +2330,7 @@ func (s *DockerSuite) TestRunModeIpcContainerNotExists(c *check.C) { func (s *DockerSuite) TestRunModeIpcContainerNotRunning(c *check.C) { // Not applicable on Windows as uses Unix-specific capabilities - testRequires(c, SameHostDaemon, DaemonIsLinux) + testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux) out, _ := dockerCmd(c, "create", "busybox") @@ -2343,7 +2343,7 @@ func (s *DockerSuite) TestRunModeIpcContainerNotRunning(c *check.C) { func (s *DockerSuite) TestRunModePIDContainer(c *check.C) { // Not applicable on Windows as uses Unix-specific capabilities - testRequires(c, SameHostDaemon, DaemonIsLinux) + testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux) out, _ := dockerCmd(c, "run", "-d", "busybox", "sh", "-c", "top") @@ -2377,7 +2377,7 @@ func (s *DockerSuite) TestRunModePIDContainerNotExists(c *check.C) { func (s *DockerSuite) TestRunModePIDContainerNotRunning(c *check.C) { // Not applicable on Windows as uses Unix-specific capabilities - testRequires(c, SameHostDaemon, DaemonIsLinux) + testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux) out, _ := dockerCmd(c, "create", "busybox") @@ -2390,7 +2390,7 @@ func (s *DockerSuite) TestRunModePIDContainerNotRunning(c *check.C) { func (s *DockerSuite) TestRunMountShmMqueueFromHost(c *check.C) { // Not applicable on Windows as uses Unix-specific capabilities - testRequires(c, SameHostDaemon, DaemonIsLinux, NotUserNamespace) + testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux, NotUserNamespace) dockerCmd(c, "run", "-d", "--name", "shmfromhost", "-v", "/dev/shm:/dev/shm", "-v", "/dev/mqueue:/dev/mqueue", "busybox", "sh", "-c", "echo -n test > /dev/shm/test && touch /dev/mqueue/toto && top") defer os.Remove("/dev/mqueue/toto") @@ -2414,7 +2414,7 @@ func (s *DockerSuite) TestRunMountShmMqueueFromHost(c *check.C) { func (s *DockerSuite) TestContainerNetworkMode(c *check.C) { // Not applicable on Windows as uses Unix-specific capabilities - testRequires(c, SameHostDaemon, DaemonIsLinux) + testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux) out, _ := dockerCmd(c, "run", "-d", "busybox", "top") id := strings.TrimSpace(out) @@ -2435,7 +2435,7 @@ func (s *DockerSuite) TestContainerNetworkMode(c *check.C) { func (s *DockerSuite) TestRunModePIDHost(c *check.C) { // Not applicable on Windows as uses Unix-specific capabilities - testRequires(c, SameHostDaemon, DaemonIsLinux, NotUserNamespace) + testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux, NotUserNamespace) hostPid, err := os.Readlink("/proc/1/ns/pid") if err != nil { @@ -2457,7 +2457,7 @@ func (s *DockerSuite) TestRunModePIDHost(c *check.C) { func (s *DockerSuite) TestRunModeUTSHost(c *check.C) { // Not applicable on Windows as uses Unix-specific capabilities - testRequires(c, SameHostDaemon, DaemonIsLinux) + testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux) hostUTS, err := os.Readlink("/proc/1/ns/uts") if err != nil { @@ -2482,7 +2482,7 @@ func (s *DockerSuite) TestRunModeUTSHost(c *check.C) { func (s *DockerSuite) TestRunTLSVerify(c *check.C) { // Remote daemons use TLS and this test is not applicable when TLS is required. - testRequires(c, SameHostDaemon) + testRequires(c, testEnv.IsLocalDaemon) if out, code, err := dockerCmdWithError("ps"); err != nil || code != 0 { c.Fatalf("Should have worked: %v:\n%v", err, out) } @@ -2579,7 +2579,7 @@ func (s *DockerSuite) TestRunNonLocalMacAddress(c *check.C) { func (s *DockerSuite) TestRunNetHost(c *check.C) { // Not applicable on Windows as uses Unix-specific capabilities - testRequires(c, SameHostDaemon, DaemonIsLinux, NotUserNamespace) + testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux, NotUserNamespace) hostNet, err := os.Readlink("/proc/1/ns/net") if err != nil { @@ -2602,7 +2602,7 @@ func (s *DockerSuite) TestRunNetHost(c *check.C) { func (s *DockerSuite) TestRunNetHostTwiceSameName(c *check.C) { // TODO Windows. As Windows networking evolves and converges towards // CNM, this test may be possible to enable on Windows. - testRequires(c, SameHostDaemon, DaemonIsLinux, NotUserNamespace) + testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux, NotUserNamespace) dockerCmd(c, "run", "--rm", "--name=thost", "--net=host", "busybox", "true") dockerCmd(c, "run", "--rm", "--name=thost", "--net=host", "busybox", "true") @@ -2610,7 +2610,7 @@ func (s *DockerSuite) TestRunNetHostTwiceSameName(c *check.C) { func (s *DockerSuite) TestRunNetContainerWhichHost(c *check.C) { // Not applicable on Windows as uses Unix-specific capabilities - testRequires(c, SameHostDaemon, DaemonIsLinux, NotUserNamespace) + testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux, NotUserNamespace) hostNet, err := os.Readlink("/proc/1/ns/net") if err != nil { @@ -3073,7 +3073,7 @@ func (s *DockerSuite) TestRunWriteFilteredProc(c *check.C) { func (s *DockerSuite) TestRunNetworkFilesBindMount(c *check.C) { // Not applicable on Windows as uses Unix specific functionality - testRequires(c, SameHostDaemon, DaemonIsLinux) + testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux) expected := "test123" @@ -3097,7 +3097,7 @@ func (s *DockerSuite) TestRunNetworkFilesBindMount(c *check.C) { func (s *DockerSuite) TestRunNetworkFilesBindMountRO(c *check.C) { // Not applicable on Windows as uses Unix specific functionality - testRequires(c, SameHostDaemon, DaemonIsLinux) + testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux) filename := createTmpFile(c, "test123") defer os.Remove(filename) @@ -3119,7 +3119,7 @@ func (s *DockerSuite) TestRunNetworkFilesBindMountRO(c *check.C) { func (s *DockerSuite) TestRunNetworkFilesBindMountROFilesystem(c *check.C) { // Not applicable on Windows as uses Unix specific functionality - testRequires(c, SameHostDaemon, DaemonIsLinux, UserNamespaceROMount) + testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux, UserNamespaceROMount) filename := createTmpFile(c, "test123") defer os.Remove(filename) @@ -3148,7 +3148,7 @@ func (s *DockerSuite) TestRunNetworkFilesBindMountROFilesystem(c *check.C) { func (s *DockerSuite) TestPtraceContainerProcsFromHost(c *check.C) { // Not applicable on Windows as uses Unix specific functionality - testRequires(c, DaemonIsLinux, SameHostDaemon) + testRequires(c, DaemonIsLinux, testEnv.IsLocalDaemon) out, _ := dockerCmd(c, "run", "-d", "busybox", "top") id := strings.TrimSpace(out) @@ -3163,7 +3163,7 @@ func (s *DockerSuite) TestPtraceContainerProcsFromHost(c *check.C) { func (s *DockerSuite) TestAppArmorDeniesPtrace(c *check.C) { // Not applicable on Windows as uses Unix specific functionality - testRequires(c, SameHostDaemon, Apparmor, DaemonIsLinux) + testRequires(c, testEnv.IsLocalDaemon, Apparmor, DaemonIsLinux) // Run through 'sh' so we are NOT pid 1. Pid 1 may be able to trace // itself, but pid>1 should not be able to trace pid1. @@ -3175,7 +3175,7 @@ func (s *DockerSuite) TestAppArmorDeniesPtrace(c *check.C) { func (s *DockerSuite) TestAppArmorTraceSelf(c *check.C) { // Not applicable on Windows as uses Unix specific functionality - testRequires(c, DaemonIsLinux, SameHostDaemon, Apparmor) + testRequires(c, DaemonIsLinux, testEnv.IsLocalDaemon, Apparmor) _, exitCode, _ := dockerCmdWithError("run", "busybox", "readlink", "/proc/1/ns/net") if exitCode != 0 { @@ -3185,7 +3185,7 @@ func (s *DockerSuite) TestAppArmorTraceSelf(c *check.C) { func (s *DockerSuite) TestAppArmorDeniesChmodProc(c *check.C) { // Not applicable on Windows as uses Unix specific functionality - testRequires(c, SameHostDaemon, Apparmor, DaemonIsLinux, NotUserNamespace) + testRequires(c, testEnv.IsLocalDaemon, Apparmor, DaemonIsLinux, NotUserNamespace) _, exitCode, _ := dockerCmdWithError("run", "busybox", "chmod", "744", "/proc/cpuinfo") if exitCode == 0 { // If our test failed, attempt to repair the host system... @@ -3776,7 +3776,7 @@ func (s *DockerSuite) TestRunWithOomScoreAdjInvalidRange(c *check.C) { func (s *DockerSuite) TestRunVolumesMountedAsShared(c *check.C) { // Volume propagation is linux only. Also it creates directories for // bind mounting, so needs to be same host. - testRequires(c, DaemonIsLinux, SameHostDaemon, NotUserNamespace) + testRequires(c, DaemonIsLinux, testEnv.IsLocalDaemon, NotUserNamespace) // Prepare a source directory to bind mount tmpDir, err := ioutil.TempDir("", "volume-source") @@ -3807,7 +3807,7 @@ func (s *DockerSuite) TestRunVolumesMountedAsShared(c *check.C) { func (s *DockerSuite) TestRunVolumesMountedAsSlave(c *check.C) { // Volume propagation is linux only. Also it creates directories for // bind mounting, so needs to be same host. - testRequires(c, DaemonIsLinux, SameHostDaemon, NotUserNamespace) + testRequires(c, DaemonIsLinux, testEnv.IsLocalDaemon, NotUserNamespace) // Prepare a source directory to bind mount tmpDir, err := ioutil.TempDir("", "volume-source") @@ -4169,14 +4169,14 @@ func (s *DockerSuite) TestRunCredentialSpecFailures(c *check.C) { // Note it won't actually do anything in CI configuration with the spec, but // it should not fail to run a container. func (s *DockerSuite) TestRunCredentialSpecWellFormed(c *check.C) { - testRequires(c, DaemonIsWindows, SameHostDaemon) + testRequires(c, DaemonIsWindows, testEnv.IsLocalDaemon) validCS := readFile(`fixtures\credentialspecs\valid.json`, c) writeFile(filepath.Join(testEnv.DaemonInfo.DockerRootDir, `credentialspecs\valid.json`), validCS, c) dockerCmd(c, "run", `--security-opt=credentialspec=file://valid.json`, "busybox", "true") } func (s *DockerSuite) TestRunDuplicateMount(c *check.C) { - testRequires(c, SameHostDaemon, DaemonIsLinux, NotUserNamespace) + testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux, NotUserNamespace) tmpFile, err := ioutil.TempFile("", "touch-me") c.Assert(err, checker.IsNil) @@ -4312,7 +4312,7 @@ func (s *delayedReader) Read([]byte) (int, error) { // #28823 (originally #28639) func (s *DockerSuite) TestRunMountReadOnlyDevShm(c *check.C) { - testRequires(c, SameHostDaemon, DaemonIsLinux, NotUserNamespace) + testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux, NotUserNamespace) emptyDir, err := ioutil.TempDir("", "test-read-only-dev-shm") c.Assert(err, check.IsNil) defer os.RemoveAll(emptyDir) @@ -4324,7 +4324,7 @@ func (s *DockerSuite) TestRunMountReadOnlyDevShm(c *check.C) { } func (s *DockerSuite) TestRunMount(c *check.C) { - testRequires(c, DaemonIsLinux, SameHostDaemon, NotUserNamespace) + testRequires(c, DaemonIsLinux, testEnv.IsLocalDaemon, NotUserNamespace) // mnt1, mnt2, and testCatFooBar are commonly used in multiple test cases tmpDir, err := ioutil.TempDir("", "mount") diff --git a/components/engine/integration-cli/docker_cli_run_unix_test.go b/components/engine/integration-cli/docker_cli_run_unix_test.go index a72a756743..74f30187b6 100644 --- a/components/engine/integration-cli/docker_cli_run_unix_test.go +++ b/components/engine/integration-cli/docker_cli_run_unix_test.go @@ -61,7 +61,7 @@ func (s *DockerSuite) TestRunRedirectStdout(c *check.C) { // Test recursive bind mount works by default func (s *DockerSuite) TestRunWithVolumesIsRecursive(c *check.C) { // /tmp gets permission denied - testRequires(c, NotUserNamespace, SameHostDaemon) + testRequires(c, NotUserNamespace, testEnv.IsLocalDaemon) tmpDir, err := ioutil.TempDir("", "docker_recursive_mount_test") c.Assert(err, checker.IsNil) @@ -680,7 +680,7 @@ func (s *DockerSuite) TestRunWithSwappinessInvalid(c *check.C) { } func (s *DockerSuite) TestRunWithMemoryReservation(c *check.C) { - testRequires(c, SameHostDaemon, memoryReservationSupport) + 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) @@ -692,7 +692,7 @@ func (s *DockerSuite) TestRunWithMemoryReservation(c *check.C) { func (s *DockerSuite) TestRunWithMemoryReservationInvalid(c *check.C) { testRequires(c, memoryLimitSupport) - testRequires(c, SameHostDaemon, memoryReservationSupport) + testRequires(c, testEnv.IsLocalDaemon, memoryReservationSupport) out, _, err := dockerCmdWithError("run", "-m", "500M", "--memory-reservation", "800M", "busybox", "true") c.Assert(err, check.NotNil) expected := "Minimum memory limit can not be less than memory reservation limit" @@ -727,7 +727,7 @@ func (s *DockerSuite) TestRunSwapLessThanMemoryLimit(c *check.C) { } func (s *DockerSuite) TestRunInvalidCpusetCpusFlagValue(c *check.C) { - testRequires(c, cgroupCpuset, SameHostDaemon) + testRequires(c, cgroupCpuset, testEnv.IsLocalDaemon) sysInfo := sysinfo.New(true) cpus, err := parsers.ParseUintList(sysInfo.Cpus) @@ -921,7 +921,7 @@ func (s *DockerSuite) TestRunSysctls(c *check.C) { // TestRunSeccompProfileDenyUnshare checks that 'docker run --security-opt seccomp=/tmp/profile.json debian:jessie unshare' exits with operation not permitted. func (s *DockerSuite) TestRunSeccompProfileDenyUnshare(c *check.C) { - testRequires(c, SameHostDaemon, seccompEnabled, NotArm, Apparmor) + testRequires(c, testEnv.IsLocalDaemon, seccompEnabled, NotArm, Apparmor) jsonData := `{ "defaultAction": "SCMP_ACT_ALLOW", "syscalls": [ @@ -950,7 +950,7 @@ func (s *DockerSuite) TestRunSeccompProfileDenyUnshare(c *check.C) { // TestRunSeccompProfileDenyChmod checks that 'docker run --security-opt seccomp=/tmp/profile.json busybox chmod 400 /etc/hostname' exits with operation not permitted. func (s *DockerSuite) TestRunSeccompProfileDenyChmod(c *check.C) { - testRequires(c, SameHostDaemon, seccompEnabled) + testRequires(c, testEnv.IsLocalDaemon, seccompEnabled) jsonData := `{ "defaultAction": "SCMP_ACT_ALLOW", "syscalls": [ @@ -985,7 +985,7 @@ func (s *DockerSuite) TestRunSeccompProfileDenyChmod(c *check.C) { // TestRunSeccompProfileDenyUnshareUserns checks that 'docker run debian:jessie unshare --map-root-user --user sh -c whoami' with a specific profile to // deny unshare of a userns exits with operation not permitted. func (s *DockerSuite) TestRunSeccompProfileDenyUnshareUserns(c *check.C) { - testRequires(c, SameHostDaemon, seccompEnabled, NotArm, Apparmor) + testRequires(c, testEnv.IsLocalDaemon, seccompEnabled, NotArm, Apparmor) // from sched.h jsonData := fmt.Sprintf(`{ "defaultAction": "SCMP_ACT_ALLOW", @@ -1023,7 +1023,7 @@ func (s *DockerSuite) TestRunSeccompProfileDenyUnshareUserns(c *check.C) { // TestRunSeccompProfileDenyCloneUserns checks that 'docker run syscall-test' // with a the default seccomp profile exits with operation not permitted. func (s *DockerSuite) TestRunSeccompProfileDenyCloneUserns(c *check.C) { - testRequires(c, SameHostDaemon, seccompEnabled) + testRequires(c, testEnv.IsLocalDaemon, seccompEnabled) ensureSyscallTest(c) icmd.RunCommand(dockerBinary, "run", "syscall-test", "userns-test", "id").Assert(c, icmd.Expected{ @@ -1035,7 +1035,7 @@ func (s *DockerSuite) TestRunSeccompProfileDenyCloneUserns(c *check.C) { // TestRunSeccompUnconfinedCloneUserns checks that // 'docker run --security-opt seccomp=unconfined syscall-test' allows creating a userns. func (s *DockerSuite) TestRunSeccompUnconfinedCloneUserns(c *check.C) { - testRequires(c, SameHostDaemon, seccompEnabled, UserNamespaceInKernel, NotUserNamespace, unprivilegedUsernsClone) + testRequires(c, testEnv.IsLocalDaemon, seccompEnabled, UserNamespaceInKernel, NotUserNamespace, unprivilegedUsernsClone) ensureSyscallTest(c) // make sure running w privileged is ok @@ -1048,7 +1048,7 @@ func (s *DockerSuite) TestRunSeccompUnconfinedCloneUserns(c *check.C) { // TestRunSeccompAllowPrivCloneUserns checks that 'docker run --privileged syscall-test' // allows creating a userns. func (s *DockerSuite) TestRunSeccompAllowPrivCloneUserns(c *check.C) { - testRequires(c, SameHostDaemon, seccompEnabled, UserNamespaceInKernel, NotUserNamespace) + testRequires(c, testEnv.IsLocalDaemon, seccompEnabled, UserNamespaceInKernel, NotUserNamespace) ensureSyscallTest(c) // make sure running w privileged is ok @@ -1060,7 +1060,7 @@ func (s *DockerSuite) TestRunSeccompAllowPrivCloneUserns(c *check.C) { // TestRunSeccompProfileAllow32Bit checks that 32 bit code can run on x86_64 // with the default seccomp profile. func (s *DockerSuite) TestRunSeccompProfileAllow32Bit(c *check.C) { - testRequires(c, SameHostDaemon, seccompEnabled, IsAmd64) + testRequires(c, testEnv.IsLocalDaemon, seccompEnabled, IsAmd64) ensureSyscallTest(c) icmd.RunCommand(dockerBinary, "run", "syscall-test", "exit32-test").Assert(c, icmd.Success) @@ -1068,14 +1068,14 @@ func (s *DockerSuite) TestRunSeccompProfileAllow32Bit(c *check.C) { // TestRunSeccompAllowSetrlimit checks that 'docker run debian:jessie ulimit -v 1048510' succeeds. func (s *DockerSuite) TestRunSeccompAllowSetrlimit(c *check.C) { - testRequires(c, SameHostDaemon, seccompEnabled) + testRequires(c, testEnv.IsLocalDaemon, seccompEnabled) // ulimit uses setrlimit, so we want to make sure we don't break it icmd.RunCommand(dockerBinary, "run", "debian:jessie", "bash", "-c", "ulimit -v 1048510").Assert(c, icmd.Success) } func (s *DockerSuite) TestRunSeccompDefaultProfileAcct(c *check.C) { - testRequires(c, SameHostDaemon, seccompEnabled, NotUserNamespace) + testRequires(c, testEnv.IsLocalDaemon, seccompEnabled, NotUserNamespace) ensureSyscallTest(c) out, _, err := dockerCmdWithError("run", "syscall-test", "acct-test") @@ -1105,7 +1105,7 @@ func (s *DockerSuite) TestRunSeccompDefaultProfileAcct(c *check.C) { } func (s *DockerSuite) TestRunSeccompDefaultProfileNS(c *check.C) { - testRequires(c, SameHostDaemon, seccompEnabled, NotUserNamespace) + testRequires(c, testEnv.IsLocalDaemon, seccompEnabled, NotUserNamespace) ensureSyscallTest(c) out, _, err := dockerCmdWithError("run", "syscall-test", "ns-test", "echo", "hello0") @@ -1142,7 +1142,7 @@ func (s *DockerSuite) TestRunSeccompDefaultProfileNS(c *check.C) { // TestRunNoNewPrivSetuid checks that --security-opt='no-new-privileges=true' prevents // effective uid transtions on executing setuid binaries. func (s *DockerSuite) TestRunNoNewPrivSetuid(c *check.C) { - testRequires(c, DaemonIsLinux, NotUserNamespace, SameHostDaemon) + testRequires(c, DaemonIsLinux, NotUserNamespace, testEnv.IsLocalDaemon) ensureNNPTest(c) // test that running a setuid binary results in no effective uid transition @@ -1155,7 +1155,7 @@ func (s *DockerSuite) TestRunNoNewPrivSetuid(c *check.C) { // TestLegacyRunNoNewPrivSetuid checks that --security-opt=no-new-privileges prevents // effective uid transtions on executing setuid binaries. func (s *DockerSuite) TestLegacyRunNoNewPrivSetuid(c *check.C) { - testRequires(c, DaemonIsLinux, NotUserNamespace, SameHostDaemon) + testRequires(c, DaemonIsLinux, NotUserNamespace, testEnv.IsLocalDaemon) ensureNNPTest(c) // test that running a setuid binary results in no effective uid transition @@ -1166,7 +1166,7 @@ func (s *DockerSuite) TestLegacyRunNoNewPrivSetuid(c *check.C) { } func (s *DockerSuite) TestUserNoEffectiveCapabilitiesChown(c *check.C) { - testRequires(c, DaemonIsLinux, SameHostDaemon) + testRequires(c, DaemonIsLinux, testEnv.IsLocalDaemon) ensureSyscallTest(c) // test that a root user has default capability CAP_CHOWN @@ -1184,7 +1184,7 @@ func (s *DockerSuite) TestUserNoEffectiveCapabilitiesChown(c *check.C) { } func (s *DockerSuite) TestUserNoEffectiveCapabilitiesDacOverride(c *check.C) { - testRequires(c, DaemonIsLinux, SameHostDaemon) + testRequires(c, DaemonIsLinux, testEnv.IsLocalDaemon) ensureSyscallTest(c) // test that a root user has default capability CAP_DAC_OVERRIDE @@ -1197,7 +1197,7 @@ func (s *DockerSuite) TestUserNoEffectiveCapabilitiesDacOverride(c *check.C) { } func (s *DockerSuite) TestUserNoEffectiveCapabilitiesFowner(c *check.C) { - testRequires(c, DaemonIsLinux, SameHostDaemon) + testRequires(c, DaemonIsLinux, testEnv.IsLocalDaemon) ensureSyscallTest(c) // test that a root user has default capability CAP_FOWNER @@ -1213,7 +1213,7 @@ func (s *DockerSuite) TestUserNoEffectiveCapabilitiesFowner(c *check.C) { // TODO CAP_KILL func (s *DockerSuite) TestUserNoEffectiveCapabilitiesSetuid(c *check.C) { - testRequires(c, DaemonIsLinux, SameHostDaemon) + testRequires(c, DaemonIsLinux, testEnv.IsLocalDaemon) ensureSyscallTest(c) // test that a root user has default capability CAP_SETUID @@ -1231,7 +1231,7 @@ func (s *DockerSuite) TestUserNoEffectiveCapabilitiesSetuid(c *check.C) { } func (s *DockerSuite) TestUserNoEffectiveCapabilitiesSetgid(c *check.C) { - testRequires(c, DaemonIsLinux, SameHostDaemon) + testRequires(c, DaemonIsLinux, testEnv.IsLocalDaemon) ensureSyscallTest(c) // test that a root user has default capability CAP_SETGID @@ -1251,7 +1251,7 @@ func (s *DockerSuite) TestUserNoEffectiveCapabilitiesSetgid(c *check.C) { // TODO CAP_SETPCAP func (s *DockerSuite) TestUserNoEffectiveCapabilitiesNetBindService(c *check.C) { - testRequires(c, DaemonIsLinux, SameHostDaemon) + testRequires(c, DaemonIsLinux, testEnv.IsLocalDaemon) ensureSyscallTest(c) // test that a root user has default capability CAP_NET_BIND_SERVICE @@ -1269,7 +1269,7 @@ func (s *DockerSuite) TestUserNoEffectiveCapabilitiesNetBindService(c *check.C) } func (s *DockerSuite) TestUserNoEffectiveCapabilitiesNetRaw(c *check.C) { - testRequires(c, DaemonIsLinux, SameHostDaemon) + testRequires(c, DaemonIsLinux, testEnv.IsLocalDaemon) ensureSyscallTest(c) // test that a root user has default capability CAP_NET_RAW @@ -1287,7 +1287,7 @@ func (s *DockerSuite) TestUserNoEffectiveCapabilitiesNetRaw(c *check.C) { } func (s *DockerSuite) TestUserNoEffectiveCapabilitiesChroot(c *check.C) { - testRequires(c, DaemonIsLinux, SameHostDaemon) + testRequires(c, DaemonIsLinux, testEnv.IsLocalDaemon) ensureSyscallTest(c) // test that a root user has default capability CAP_SYS_CHROOT @@ -1305,7 +1305,7 @@ func (s *DockerSuite) TestUserNoEffectiveCapabilitiesChroot(c *check.C) { } func (s *DockerSuite) TestUserNoEffectiveCapabilitiesMknod(c *check.C) { - testRequires(c, DaemonIsLinux, NotUserNamespace, SameHostDaemon) + testRequires(c, DaemonIsLinux, NotUserNamespace, testEnv.IsLocalDaemon) ensureSyscallTest(c) // test that a root user has default capability CAP_MKNOD @@ -1327,7 +1327,7 @@ func (s *DockerSuite) TestUserNoEffectiveCapabilitiesMknod(c *check.C) { // TODO CAP_SETFCAP func (s *DockerSuite) TestRunApparmorProcDirectory(c *check.C) { - testRequires(c, SameHostDaemon, Apparmor) + testRequires(c, testEnv.IsLocalDaemon, Apparmor) // running w seccomp unconfined tests the apparmor profile result := icmd.RunCommand(dockerBinary, "run", "--security-opt", "seccomp=unconfined", "busybox", "chmod", "777", "/proc/1/cgroup") @@ -1346,7 +1346,7 @@ func (s *DockerSuite) TestRunApparmorProcDirectory(c *check.C) { // make sure the default profile can be successfully parsed (using unshare as it is // something which we know is blocked in the default profile) func (s *DockerSuite) TestRunSeccompWithDefaultProfile(c *check.C) { - testRequires(c, SameHostDaemon, seccompEnabled) + testRequires(c, testEnv.IsLocalDaemon, seccompEnabled) out, _, err := dockerCmdWithError("run", "--security-opt", "seccomp=../profiles/seccomp/default.json", "debian:jessie", "unshare", "--map-root-user", "--user", "sh", "-c", "whoami") c.Assert(err, checker.NotNil, check.Commentf("%s", out)) @@ -1355,7 +1355,7 @@ func (s *DockerSuite) TestRunSeccompWithDefaultProfile(c *check.C) { // TestRunDeviceSymlink checks run with device that follows symlink (#13840 and #22271) func (s *DockerSuite) TestRunDeviceSymlink(c *check.C) { - testRequires(c, DaemonIsLinux, NotUserNamespace, NotArm, SameHostDaemon) + testRequires(c, DaemonIsLinux, NotUserNamespace, NotArm, testEnv.IsLocalDaemon) if _, err := os.Stat("/dev/zero"); err != nil { c.Skip("Host does not have /dev/zero") } @@ -1404,7 +1404,7 @@ func (s *DockerSuite) TestRunDeviceSymlink(c *check.C) { // TestRunPIDsLimit makes sure the pids cgroup is set with --pids-limit func (s *DockerSuite) TestRunPIDsLimit(c *check.C) { - testRequires(c, SameHostDaemon, pidsLimit) + testRequires(c, testEnv.IsLocalDaemon, pidsLimit) file := "/sys/fs/cgroup/pids/pids.max" out, _ := dockerCmd(c, "run", "--name", "skittles", "--pids-limit", "4", "busybox", "cat", file) @@ -1441,7 +1441,7 @@ func (s *DockerSuite) TestRunUserDeviceAllowed(c *check.C) { } func (s *DockerDaemonSuite) TestRunSeccompJSONNewFormat(c *check.C) { - testRequires(c, SameHostDaemon, seccompEnabled) + testRequires(c, testEnv.IsLocalDaemon, seccompEnabled) s.d.StartWithBusybox(c) @@ -1466,7 +1466,7 @@ func (s *DockerDaemonSuite) TestRunSeccompJSONNewFormat(c *check.C) { } func (s *DockerDaemonSuite) TestRunSeccompJSONNoNameAndNames(c *check.C) { - testRequires(c, SameHostDaemon, seccompEnabled) + testRequires(c, testEnv.IsLocalDaemon, seccompEnabled) s.d.StartWithBusybox(c) @@ -1492,7 +1492,7 @@ func (s *DockerDaemonSuite) TestRunSeccompJSONNoNameAndNames(c *check.C) { } func (s *DockerDaemonSuite) TestRunSeccompJSONNoArchAndArchMap(c *check.C) { - testRequires(c, SameHostDaemon, seccompEnabled) + testRequires(c, testEnv.IsLocalDaemon, seccompEnabled) s.d.StartWithBusybox(c) @@ -1529,7 +1529,7 @@ func (s *DockerDaemonSuite) TestRunSeccompJSONNoArchAndArchMap(c *check.C) { } func (s *DockerDaemonSuite) TestRunWithDaemonDefaultSeccompProfile(c *check.C) { - testRequires(c, SameHostDaemon, seccompEnabled) + testRequires(c, testEnv.IsLocalDaemon, seccompEnabled) s.d.StartWithBusybox(c) diff --git a/components/engine/integration-cli/docker_cli_save_load_test.go b/components/engine/integration-cli/docker_cli_save_load_test.go index 688eac684e..ba1fa2b8b2 100644 --- a/components/engine/integration-cli/docker_cli_save_load_test.go +++ b/components/engine/integration-cli/docker_cli_save_load_test.go @@ -332,7 +332,7 @@ func listTar(f io.Reader) ([]string, error) { func (s *DockerSuite) TestLoadZeroSizeLayer(c *check.C) { // this will definitely not work if using remote daemon // very weird test - testRequires(c, DaemonIsLinux, SameHostDaemon) + testRequires(c, DaemonIsLinux, testEnv.IsLocalDaemon) dockerCmd(c, "load", "-i", "testdata/emptyLayer.tar") } diff --git a/components/engine/integration-cli/docker_cli_userns_test.go b/components/engine/integration-cli/docker_cli_userns_test.go index 13d1f56dc6..ede2d8f560 100644 --- a/components/engine/integration-cli/docker_cli_userns_test.go +++ b/components/engine/integration-cli/docker_cli_userns_test.go @@ -22,7 +22,7 @@ import ( // 1. validate uid/gid maps are set properly // 2. verify that files created are owned by remapped root func (s *DockerDaemonSuite) TestDaemonUserNamespaceRootSetting(c *check.C) { - testRequires(c, DaemonIsLinux, SameHostDaemon, UserNamespaceInKernel) + testRequires(c, DaemonIsLinux, testEnv.IsLocalDaemon, UserNamespaceInKernel) s.d.StartWithBusybox(c, "--userns-remap", "default") diff --git a/components/engine/integration-cli/docker_cli_volume_test.go b/components/engine/integration-cli/docker_cli_volume_test.go index 9e25b52100..dea1c25587 100644 --- a/components/engine/integration-cli/docker_cli_volume_test.go +++ b/components/engine/integration-cli/docker_cli_volume_test.go @@ -404,7 +404,7 @@ func (s *DockerSuite) TestVolumeCLIRmForceUsage(c *check.C) { } func (s *DockerSuite) TestVolumeCLIRmForce(c *check.C) { - testRequires(c, SameHostDaemon, DaemonIsLinux) + testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux) name := "test" out, _ := dockerCmd(c, "volume", "create", name) @@ -574,7 +574,7 @@ func (s *DockerSuite) TestDuplicateMountpointsForVolumesFromAndBind(c *check.C) // Test case (3) for 21845: duplicate targets for --volumes-from and `Mounts` (API only) func (s *DockerSuite) TestDuplicateMountpointsForVolumesFromAndMounts(c *check.C) { - testRequires(c, SameHostDaemon, DaemonIsLinux) + testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux) image := "vimage" buildImageSuccessfully(c, image, build.WithDockerfile(` diff --git a/components/engine/integration-cli/docker_hub_pull_suite_test.go b/components/engine/integration-cli/docker_hub_pull_suite_test.go index 125b8c10aa..34fddac983 100644 --- a/components/engine/integration-cli/docker_hub_pull_suite_test.go +++ b/components/engine/integration-cli/docker_hub_pull_suite_test.go @@ -40,7 +40,7 @@ func newDockerHubPullSuite() *DockerHubPullSuite { // SetUpSuite starts the suite daemon. func (s *DockerHubPullSuite) SetUpSuite(c *check.C) { - testRequires(c, DaemonIsLinux, SameHostDaemon) + testRequires(c, DaemonIsLinux, testEnv.IsLocalDaemon) s.d = daemon.New(c, dockerBinary, dockerdBinary, testdaemon.WithEnvironment(testEnv.Execution)) s.d.Start(c) } diff --git a/components/engine/integration-cli/requirements_test.go b/components/engine/integration-cli/requirements_test.go index ddb1b4299e..b3d20e28f1 100644 --- a/components/engine/integration-cli/requirements_test.go +++ b/components/engine/integration-cli/requirements_test.go @@ -76,10 +76,6 @@ func NotPpc64le() bool { return ArchitectureIsNot("ppc64le") } -func SameHostDaemon() bool { - return testEnv.IsLocalDaemon() -} - func UnixCli() bool { return isUnixCli } diff --git a/components/engine/integration-cli/requirements_unix_test.go b/components/engine/integration-cli/requirements_unix_test.go index 7ac79c4fe2..cea1db1e6d 100644 --- a/components/engine/integration-cli/requirements_unix_test.go +++ b/components/engine/integration-cli/requirements_unix_test.go @@ -65,11 +65,11 @@ func swapMemorySupport() bool { } func memorySwappinessSupport() bool { - return SameHostDaemon() && SysInfo.MemorySwappiness + return testEnv.IsLocalDaemon() && SysInfo.MemorySwappiness } func blkioWeight() bool { - return SameHostDaemon() && SysInfo.BlkioWeight + return testEnv.IsLocalDaemon() && SysInfo.BlkioWeight } func cgroupCpuset() bool { @@ -122,7 +122,7 @@ func overlay2Supported() bool { } func init() { - if SameHostDaemon() { + if testEnv.IsLocalDaemon() { SysInfo = sysinfo.New(true) } } From 463305c389e8af07d1eb98be46df86224a39a3bc Mon Sep 17 00:00:00 2001 From: Sebastiaan van Stijn Date: Sat, 12 Jan 2019 19:55:20 +0100 Subject: [PATCH 33/45] reduce flakiness of TestSwarmLockUnlockCluster and TestSwarmJoinPromoteLocked I noticed that this test failed, because the node was in status "pending". The test checks for the node's status immediately after it was restarted, so possibly it needs some time to unlock. 14:07:10 FAIL: docker_cli_swarm_test.go:1128: DockerSwarmSuite.TestSwarmLockUnlockCluster ... 14:07:10 docker_cli_swarm_test.go:1168: 14:07:10 checkSwarmLockedToUnlocked(c, d) 14:07:10 docker_cli_swarm_test.go:1017: 14:07:10 c.Assert(getNodeStatus(c, d), checker.Equals, swarm.LocalNodeStateActive) 14:07:10 ... obtained swarm.LocalNodeState = "pending" 14:07:10 ... expected swarm.LocalNodeState = "active" This patch adds a `waitAndAssert` for the node's status, with a 1 second timeout. Signed-off-by: Sebastiaan van Stijn (cherry picked from commit 973ca00d60712ef644b5b37abf7fa01078bb4ade) Signed-off-by: Sebastiaan van Stijn Upstream-commit: 954425f8bdb5db95355cb20be465d248f7c3b1f1 Component: engine --- .../engine/integration-cli/docker_cli_swarm_test.go | 8 ++++---- 1 file changed, 4 insertions(+), 4 deletions(-) diff --git a/components/engine/integration-cli/docker_cli_swarm_test.go b/components/engine/integration-cli/docker_cli_swarm_test.go index 3f307d7b9e..a9f8f401c2 100644 --- a/components/engine/integration-cli/docker_cli_swarm_test.go +++ b/components/engine/integration-cli/docker_cli_swarm_test.go @@ -1014,7 +1014,7 @@ func checkSwarmLockedToUnlocked(c *check.C, d *daemon.Daemon) { waitAndAssert(c, defaultReconciliationTimeout, checkKeyIsEncrypted(d), checker.Equals, false) d.RestartNode(c) - c.Assert(getNodeStatus(c, d), checker.Equals, swarm.LocalNodeStateActive) + waitAndAssert(c, time.Second, d.CheckLocalNodeState, checker.Equals, swarm.LocalNodeStateActive) } func checkSwarmUnlockedToLocked(c *check.C, d *daemon.Daemon) { @@ -1022,7 +1022,7 @@ func checkSwarmUnlockedToLocked(c *check.C, d *daemon.Daemon) { waitAndAssert(c, defaultReconciliationTimeout, checkKeyIsEncrypted(d), checker.Equals, true) d.RestartNode(c) - c.Assert(getNodeStatus(c, d), checker.Equals, swarm.LocalNodeStateLocked) + waitAndAssert(c, time.Second, d.CheckLocalNodeState, checker.Equals, swarm.LocalNodeStateLocked) } func (s *DockerSwarmSuite) TestUnlockEngineAndUnlockedSwarm(c *check.C) { @@ -1197,7 +1197,7 @@ func (s *DockerSwarmSuite) TestSwarmJoinPromoteLocked(c *check.C) { // joined workers start off unlocked d2 := s.AddDaemon(c, true, false) d2.RestartNode(c) - c.Assert(getNodeStatus(c, d2), checker.Equals, swarm.LocalNodeStateActive) + waitAndAssert(c, time.Second, d2.CheckLocalNodeState, checker.Equals, swarm.LocalNodeStateActive) // promote worker outs, err = d1.Cmd("node", "promote", d2.NodeID()) @@ -1242,7 +1242,7 @@ func (s *DockerSwarmSuite) TestSwarmJoinPromoteLocked(c *check.C) { // by now, it should *never* be locked on restart d3.RestartNode(c) - c.Assert(getNodeStatus(c, d3), checker.Equals, swarm.LocalNodeStateActive) + waitAndAssert(c, time.Second, d3.CheckLocalNodeState, checker.Equals, swarm.LocalNodeStateActive) } func (s *DockerSwarmSuite) TestSwarmRotateUnlockKey(c *check.C) { From 2794526c50fc4b1c6f5c8d62acf55f276d9211f3 Mon Sep 17 00:00:00 2001 From: Sebastiaan van Stijn Date: Mon, 14 Jan 2019 00:29:13 +0100 Subject: [PATCH 34/45] Make TestEventsFilterLabels less flaky This test sometimes failed because the number of events received did not match the expected number: FAIL: docker_cli_events_test.go:316: DockerSuite.TestEventsFilterLabels docker_cli_events_test.go:334: c.Assert(len(events), checker.Equals, 3) ... obtained int = 2 ... expected int = 3 This patch makes the test more stable, by: - use a wider range between `--since` and `--until`. These options were set so that the client detaches after events were received, but the actual range should not matter. Changing the range will cause more events to be returned, but we're specifically looking for the container ID's, so this should not make a difference for the actual test. - use `docker create` instead of `docker run` for the containers. the containers don't have to be running to trigger an event; using `create` speeds up the test. - check the exit code of the `docker create` to verify the containers were succesfully created. Signed-off-by: Sebastiaan van Stijn (cherry picked from commit 0e15c02465c87c82908bcc45b0c1d6bd38f27c32) Signed-off-by: Sebastiaan van Stijn Upstream-commit: 26f7e0a8b08b2890d079d4083735c05377770ca8 Component: engine --- .../integration-cli/docker_cli_events_test.go | 24 +++++++++++++------ 1 file changed, 17 insertions(+), 7 deletions(-) diff --git a/components/engine/integration-cli/docker_cli_events_test.go b/components/engine/integration-cli/docker_cli_events_test.go index b042faf916..ce3dec4b61 100644 --- a/components/engine/integration-cli/docker_cli_events_test.go +++ b/components/engine/integration-cli/docker_cli_events_test.go @@ -9,6 +9,7 @@ import ( "io/ioutil" "os" "os/exec" + "strconv" "strings" "time" @@ -314,29 +315,38 @@ func (s *DockerSuite) TestEventsFilterImageName(c *check.C) { } func (s *DockerSuite) TestEventsFilterLabels(c *check.C) { - since := daemonUnixTime(c) + since := strconv.FormatUint(uint64(daemonTime(c).Unix()), 10) label := "io.docker.testing=foo" - out, _ := dockerCmd(c, "run", "-d", "-l", label, "busybox:latest", "true") + out, exit := dockerCmd(c, "create", "-l", label, "busybox") + c.Assert(exit, checker.Equals, 0) container1 := strings.TrimSpace(out) - out, _ = dockerCmd(c, "run", "-d", "busybox", "true") + out, exit = dockerCmd(c, "create", "busybox") + c.Assert(exit, checker.Equals, 0) container2 := strings.TrimSpace(out) + // 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, "events", "--since", since, - "--until", daemonUnixTime(c), - "--filter", fmt.Sprintf("label=%s", label)) + "--until", strconv.FormatUint(uint64(daemonTime(c).Add(time.Second).Unix()), 10), + "--filter", "label="+label, + ) events := strings.Split(strings.TrimSpace(out), "\n") - c.Assert(len(events), checker.Equals, 3) + c.Assert(len(events), checker.GreaterThan, 0) + var found bool for _, e := range events { - c.Assert(e, checker.Contains, container1) + if strings.Contains(e, container1) { + found = true + } c.Assert(e, checker.Not(checker.Contains), container2) } + c.Assert(found, checker.Equals, true) } func (s *DockerSuite) TestEventsFilterImageLabels(c *check.C) { From 00e344213462dd1aa17e6b3716108b6531020436 Mon Sep 17 00:00:00 2001 From: Kir Kolyshkin Date: Fri, 8 Mar 2019 09:59:22 -0800 Subject: [PATCH 35/45] TestUpdateRestartWithAutoRemove: use WithAutoRemove Signed-off-by: Kir Kolyshkin (cherry picked from commit 39eaf1ef9709d79fc50095ee2a0546bd2f565ab2) Signed-off-by: Sebastiaan van Stijn Upstream-commit: f9823799281419aae1b30d961d5c719dd6e392e2 Component: engine --- components/engine/integration/container/update_test.go | 4 +--- 1 file changed, 1 insertion(+), 3 deletions(-) diff --git a/components/engine/integration/container/update_test.go b/components/engine/integration/container/update_test.go index 6a136a707e..129f8ead47 100644 --- a/components/engine/integration/container/update_test.go +++ b/components/engine/integration/container/update_test.go @@ -50,9 +50,7 @@ func TestUpdateRestartWithAutoRemove(t *testing.T) { client := testEnv.APIClient() ctx := context.Background() - cID := container.Run(t, ctx, client, func(c *container.TestContainerConfig) { - c.HostConfig.AutoRemove = true - }) + cID := container.Run(t, ctx, client, container.WithAutoRemove) _, err := client.ContainerUpdate(ctx, cID, containertypes.UpdateConfig{ RestartPolicy: containertypes.RestartPolicy{ From 9659d7a8ac16ecdfb1a89036279a8b78fac021f7 Mon Sep 17 00:00:00 2001 From: Kir Kolyshkin Date: Thu, 14 Feb 2019 16:10:15 -0800 Subject: [PATCH 36/45] integration/internal/container/ops: rm unused code Since container.Create() already initializes HostConfig to be non-nil, there is no need for this code. Remove it. Signed-off-by: Kir Kolyshkin (cherry picked from commit 17022b3ad2d95863e5acd17ebaf943b7761623cc) Signed-off-by: Sebastiaan van Stijn Upstream-commit: ed48a92a580b7ccc5c5837c7d802f787000146eb Component: engine --- components/engine/integration/internal/container/ops.go | 6 ------ 1 file changed, 6 deletions(-) diff --git a/components/engine/integration/internal/container/ops.go b/components/engine/integration/internal/container/ops.go index b2d170b4df..b26ef104da 100644 --- a/components/engine/integration/internal/container/ops.go +++ b/components/engine/integration/internal/container/ops.go @@ -120,18 +120,12 @@ func WithIPv6(network, ip string) func(*TestContainerConfig) { // WithLogDriver sets the log driver to use for the container func WithLogDriver(driver string) func(*TestContainerConfig) { return func(c *TestContainerConfig) { - if c.HostConfig == nil { - c.HostConfig = &containertypes.HostConfig{} - } c.HostConfig.LogConfig.Type = driver } } // WithAutoRemove sets the container to be removed on exit func WithAutoRemove(c *TestContainerConfig) { - if c.HostConfig == nil { - c.HostConfig = &containertypes.HostConfig{} - } c.HostConfig.AutoRemove = true } From 51a09b511653c040d384155a86e909f73e399506 Mon Sep 17 00:00:00 2001 From: Kir Kolyshkin Date: Thu, 14 Feb 2019 16:03:26 -0800 Subject: [PATCH 37/45] integration: add/use WithRestartPolicy NOTE TestUpdateRestartPolicy is left as is as otherwise it will decrease its readability. Signed-off-by: Kir Kolyshkin (cherry picked from commit f664df01d1836686c7a8a917e9da81d56c758d74) Signed-off-by: Sebastiaan van Stijn Upstream-commit: 2c546aace40872169b03e18f07294d3fbfa3d452 Component: engine --- components/engine/integration/container/kill_test.go | 12 +++++------- components/engine/integration/container/stop_test.go | 8 +++++--- .../engine/integration/internal/container/ops.go | 7 +++++++ 3 files changed, 17 insertions(+), 10 deletions(-) diff --git a/components/engine/integration/container/kill_test.go b/components/engine/integration/container/kill_test.go index 2c73026e18..60f4f179bd 100644 --- a/components/engine/integration/container/kill_test.go +++ b/components/engine/integration/container/kill_test.go @@ -5,7 +5,6 @@ import ( "testing" "time" - containertypes "github.com/docker/docker/api/types/container" "github.com/docker/docker/client" "github.com/docker/docker/integration/internal/container" "github.com/docker/docker/internal/test/request" @@ -96,12 +95,11 @@ func TestKillWithStopSignalAndRestartPolicies(t *testing.T) { tc := tc t.Run(tc.doc, func(t *testing.T) { ctx := context.Background() - id := container.Run(t, ctx, client, func(c *container.TestContainerConfig) { - c.Config.StopSignal = tc.stopsignal - c.HostConfig.RestartPolicy = containertypes.RestartPolicy{ - Name: "always", - } - }) + id := container.Run(t, ctx, client, + container.WithRestartPolicy("always"), + func(c *container.TestContainerConfig) { + c.Config.StopSignal = tc.stopsignal + }) err := client.ContainerKill(ctx, id, "TERM") assert.NilError(t, err) diff --git a/components/engine/integration/container/stop_test.go b/components/engine/integration/container/stop_test.go index 43d729b7b1..8a95f32f13 100644 --- a/components/engine/integration/container/stop_test.go +++ b/components/engine/integration/container/stop_test.go @@ -17,9 +17,11 @@ func TestStopContainerWithRestartPolicyAlways(t *testing.T) { names := []string{"verifyRestart1-" + t.Name(), "verifyRestart2-" + t.Name()} for _, name := range names { - container.Run(t, ctx, client, container.WithName(name), container.WithCmd("false"), func(c *container.TestContainerConfig) { - c.HostConfig.RestartPolicy.Name = "always" - }) + container.Run(t, ctx, client, + container.WithName(name), + container.WithCmd("false"), + container.WithRestartPolicy("always"), + ) } for _, name := range names { diff --git a/components/engine/integration/internal/container/ops.go b/components/engine/integration/internal/container/ops.go index b26ef104da..21e9094065 100644 --- a/components/engine/integration/internal/container/ops.go +++ b/components/engine/integration/internal/container/ops.go @@ -129,6 +129,13 @@ func WithAutoRemove(c *TestContainerConfig) { c.HostConfig.AutoRemove = true } +// WithRestartPolicy sets container's restart policy +func WithRestartPolicy(policy string) func(c *TestContainerConfig) { + return func(c *TestContainerConfig) { + c.HostConfig.RestartPolicy.Name = policy + } +} + // WithUser sets the user func WithUser(user string) func(c *TestContainerConfig) { return func(c *TestContainerConfig) { From aa5b904041bc1dd9ab0924e1fc81ee78349636e5 Mon Sep 17 00:00:00 2001 From: Kir Kolyshkin Date: Thu, 14 Feb 2019 17:08:00 -0800 Subject: [PATCH 38/45] TestDaemonRestartIpcMode: modernize Move the test case from integration-cli to integration. The test logic itself has not changed, except these two things: * the new test sets default-ipc-mode via command line rather than via daemon.json (less code); * the new test uses current API version. Signed-off-by: Kir Kolyshkin (cherry picked from commit 9fd765f07cc08ccc2ea991d21835bf50ece9318b) Signed-off-by: Sebastiaan van Stijn Upstream-commit: b228a498d55fcd47c741d51a510a7f5eab0794f7 Component: engine --- .../integration-cli/docker_cli_daemon_test.go | 41 ----------------- .../container/daemon_linux_test.go | 44 +++++++++++++++++++ 2 files changed, 44 insertions(+), 41 deletions(-) diff --git a/components/engine/integration-cli/docker_cli_daemon_test.go b/components/engine/integration-cli/docker_cli_daemon_test.go index f91ef1d835..1387a39a2d 100644 --- a/components/engine/integration-cli/docker_cli_daemon_test.go +++ b/components/engine/integration-cli/docker_cli_daemon_test.go @@ -2958,47 +2958,6 @@ func (s *DockerDaemonSuite) TestDaemonStartWithIpcModes(c *check.C) { } } -// TestDaemonRestartIpcMode makes sure a container keeps its ipc mode -// (derived from daemon default) even after the daemon is restarted -// with a different default ipc mode. -func (s *DockerDaemonSuite) TestDaemonRestartIpcMode(c *check.C) { - f, err := ioutil.TempFile("", "test-daemon-ipc-config-restart") - c.Assert(err, checker.IsNil) - file := f.Name() - defer os.Remove(file) - c.Assert(f.Close(), checker.IsNil) - - config := []byte(`{"default-ipc-mode": "private"}`) - c.Assert(ioutil.WriteFile(file, config, 0644), checker.IsNil) - s.d.StartWithBusybox(c, "--config-file", file) - - // check the container is created with private ipc mode as per daemon default - name := "ipc1" - _, err = s.d.Cmd("run", "-d", "--name", name, "--restart=always", "busybox", "top") - c.Assert(err, checker.IsNil) - m, err := s.d.InspectField(name, ".HostConfig.IpcMode") - c.Assert(err, check.IsNil) - c.Assert(m, checker.Equals, "private") - - // restart the daemon with shareable default ipc mode - config = []byte(`{"default-ipc-mode": "shareable"}`) - c.Assert(ioutil.WriteFile(file, config, 0644), checker.IsNil) - s.d.Restart(c, "--config-file", file) - - // check the container is still having private ipc mode - m, err = s.d.InspectField(name, ".HostConfig.IpcMode") - c.Assert(err, check.IsNil) - c.Assert(m, checker.Equals, "private") - - // check a new container is created with shareable ipc mode as per new daemon default - name = "ipc2" - _, err = s.d.Cmd("run", "-d", "--name", name, "busybox", "top") - c.Assert(err, checker.IsNil) - m, err = s.d.InspectField(name, ".HostConfig.IpcMode") - c.Assert(err, check.IsNil) - c.Assert(m, checker.Equals, "shareable") -} - // TestFailedPluginRemove makes sure that a failed plugin remove does not block // the daemon from starting func (s *DockerDaemonSuite) TestFailedPluginRemove(c *check.C) { diff --git a/components/engine/integration/container/daemon_linux_test.go b/components/engine/integration/container/daemon_linux_test.go index a676410690..efb97c5aac 100644 --- a/components/engine/integration/container/daemon_linux_test.go +++ b/components/engine/integration/container/daemon_linux_test.go @@ -13,6 +13,7 @@ import ( "github.com/docker/docker/internal/test/daemon" "golang.org/x/sys/unix" "gotest.tools/assert" + is "gotest.tools/assert/cmp" "gotest.tools/skip" ) @@ -76,3 +77,46 @@ func getContainerdShimPid(t *testing.T, c types.ContainerJSON) int { assert.Check(t, ppid != 1, "got unexpected ppid") return ppid } + +// TestDaemonRestartIpcMode makes sure a container keeps its ipc mode +// (derived from daemon default) even after the daemon is restarted +// with a different default ipc mode. +func TestDaemonRestartIpcMode(t *testing.T) { + skip.If(t, testEnv.IsRemoteDaemon, "cannot start daemon on remote test run") + skip.If(t, testEnv.DaemonInfo.OSType == "windows") + t.Parallel() + + d := daemon.New(t) + d.StartWithBusybox(t, "--iptables=false", "--default-ipc-mode=private") + defer d.Stop(t) + + c := d.NewClientT(t) + ctx := context.Background() + + // check the container is created with private ipc mode as per daemon default + cID := container.Run(t, ctx, c, + container.WithCmd("top"), + container.WithRestartPolicy("always"), + ) + defer c.ContainerRemove(ctx, cID, types.ContainerRemoveOptions{Force: true}) + + inspect, err := c.ContainerInspect(ctx, cID) + assert.NilError(t, err) + assert.Check(t, is.Equal(string(inspect.HostConfig.IpcMode), "private")) + + // restart the daemon with shareable default ipc mode + d.Restart(t, "--iptables=false", "--default-ipc-mode=shareable") + + // check the container is still having private ipc mode + inspect, err = c.ContainerInspect(ctx, cID) + assert.NilError(t, err) + assert.Check(t, is.Equal(string(inspect.HostConfig.IpcMode), "private")) + + // check a new container is created with shareable ipc mode as per new daemon default + cID = container.Run(t, ctx, c) + defer c.ContainerRemove(ctx, cID, types.ContainerRemoveOptions{Force: true}) + + inspect, err = c.ContainerInspect(ctx, cID) + assert.NilError(t, err) + assert.Check(t, is.Equal(string(inspect.HostConfig.IpcMode), "shareable")) +} From b175e2d89ee0ecd32da0ebe8cf790711de720320 Mon Sep 17 00:00:00 2001 From: Kir Kolyshkin Date: Tue, 2 Oct 2018 23:38:47 -0700 Subject: [PATCH 39/45] TestSwarmContainerEndpointOptions: fix debug In case of failure, stale out was printed. Fixes: 6212ea669b4e92b3 Signed-off-by: Kir Kolyshkin (cherry picked from commit 1921753b4b30dcca4fe772e7c1b0bc3f7bb7cd62) Signed-off-by: Sebastiaan van Stijn Upstream-commit: b60ecd32a1d3ba7debf02d15fe346ea5ca607bbd Component: engine --- .../engine/integration-cli/docker_cli_swarm_test.go | 12 ++++++------ 1 file changed, 6 insertions(+), 6 deletions(-) diff --git a/components/engine/integration-cli/docker_cli_swarm_test.go b/components/engine/integration-cli/docker_cli_swarm_test.go index a9f8f401c2..916020b8b1 100644 --- a/components/engine/integration-cli/docker_cli_swarm_test.go +++ b/components/engine/integration-cli/docker_cli_swarm_test.go @@ -345,21 +345,21 @@ func (s *DockerSwarmSuite) TestSwarmContainerEndpointOptions(c *check.C) { c.Assert(err, checker.IsNil, check.Commentf("%s", out)) c.Assert(strings.TrimSpace(out), checker.Not(checker.Equals), "") - _, err = d.Cmd("run", "-d", "--net=foo", "--name=first", "--net-alias=first-alias", "busybox:glibc", "top") + out, err = d.Cmd("run", "-d", "--net=foo", "--name=first", "--net-alias=first-alias", "busybox:glibc", "top") c.Assert(err, checker.IsNil, check.Commentf("%s", out)) - _, err = d.Cmd("run", "-d", "--net=foo", "--name=second", "busybox:glibc", "top") + out, err = d.Cmd("run", "-d", "--net=foo", "--name=second", "busybox:glibc", "top") c.Assert(err, checker.IsNil, check.Commentf("%s", out)) - _, err = d.Cmd("run", "-d", "--net=foo", "--net-alias=third-alias", "busybox:glibc", "top") + out, err = d.Cmd("run", "-d", "--net=foo", "--net-alias=third-alias", "busybox:glibc", "top") c.Assert(err, checker.IsNil, check.Commentf("%s", out)) // ping first container and its alias, also ping third and anonymous container by its alias - _, err = d.Cmd("exec", "second", "ping", "-c", "1", "first") + out, err = d.Cmd("exec", "second", "ping", "-c", "1", "first") c.Assert(err, check.IsNil, check.Commentf("%s", out)) - _, err = d.Cmd("exec", "second", "ping", "-c", "1", "first-alias") + out, err = d.Cmd("exec", "second", "ping", "-c", "1", "first-alias") c.Assert(err, check.IsNil, check.Commentf("%s", out)) - _, err = d.Cmd("exec", "second", "ping", "-c", "1", "third-alias") + out, err = d.Cmd("exec", "second", "ping", "-c", "1", "third-alias") c.Assert(err, check.IsNil, check.Commentf("%s", out)) } From ca79cb7afa3c6c35a19ee6019fd44f57b134aeda Mon Sep 17 00:00:00 2001 From: 16yuki0702 Date: Sat, 6 Oct 2018 03:43:14 +0900 Subject: [PATCH 40/45] Fix typo Signed-off-by: Hiroyuki Sasagawa (cherry picked from commit a28843150a7e926006798369f0ac31f32f028e36) Signed-off-by: Sebastiaan van Stijn Upstream-commit: 45dd95610a26bf4e1995bcc9ad814d60a7f3504a Component: engine --- components/engine/integration-cli/docker_cli_swarm_test.go | 2 +- 1 file changed, 1 insertion(+), 1 deletion(-) diff --git a/components/engine/integration-cli/docker_cli_swarm_test.go b/components/engine/integration-cli/docker_cli_swarm_test.go index 916020b8b1..e2b3954dcb 100644 --- a/components/engine/integration-cli/docker_cli_swarm_test.go +++ b/components/engine/integration-cli/docker_cli_swarm_test.go @@ -402,7 +402,7 @@ func (s *DockerSwarmSuite) TestOverlayAttachable(c *check.C) { c.Assert(err, checker.IsNil, check.Commentf("%s", out)) c.Assert(strings.TrimSpace(out), checker.Equals, "true") - // validate containers can attache to this overlay network + // validate containers can attach to this overlay network out, err = d.Cmd("run", "-d", "--network", "ovnet", "--name", "c1", "busybox", "top") c.Assert(err, checker.IsNil, check.Commentf("%s", out)) From 9d8e7a0e24aed9bd5b609ed7f492331ba9413cbb Mon Sep 17 00:00:00 2001 From: Sebastiaan van Stijn Date: Thu, 4 Apr 2019 10:09:27 +0200 Subject: [PATCH 41/45] Remove some checkers to discourage usage Signed-off-by: Sebastiaan van Stijn (cherry picked from commit 86f2ac4a6b5b746c3309b57e7e04bdbdb70d46d7) Signed-off-by: Sebastiaan van Stijn Upstream-commit: 8fcca0be3f31e8296a3ceefcb10acca636673b15 Component: engine --- .../engine/integration-cli/checker/checker.go | 30 ++++--------------- components/engine/vendor.conf | 2 +- 2 files changed, 7 insertions(+), 25 deletions(-) diff --git a/components/engine/integration-cli/checker/checker.go b/components/engine/integration-cli/checker/checker.go index d7fdc412ba..6b079c1fcd 100644 --- a/components/engine/integration-cli/checker/checker.go +++ b/components/engine/integration-cli/checker/checker.go @@ -9,38 +9,20 @@ import ( // As a commodity, we bring all check.Checker variables into the current namespace to avoid having // to think about check.X versus checker.X. var ( - DeepEquals = check.DeepEquals - ErrorMatches = check.ErrorMatches - FitsTypeOf = check.FitsTypeOf - HasLen = check.HasLen - Implements = check.Implements - IsNil = check.IsNil - Matches = check.Matches - Not = check.Not - NotNil = check.NotNil - PanicMatches = check.PanicMatches - Panics = check.Panics + DeepEquals = check.DeepEquals + HasLen = check.HasLen + IsNil = check.IsNil + Matches = check.Matches + Not = check.Not + NotNil = check.NotNil Contains = shakers.Contains - ContainsAny = shakers.ContainsAny Count = shakers.Count Equals = shakers.Equals - EqualFold = shakers.EqualFold False = shakers.False GreaterOrEqualThan = shakers.GreaterOrEqualThan GreaterThan = shakers.GreaterThan HasPrefix = shakers.HasPrefix - HasSuffix = shakers.HasSuffix - Index = shakers.Index - IndexAny = shakers.IndexAny - IsAfter = shakers.IsAfter - IsBefore = shakers.IsBefore - IsBetween = shakers.IsBetween - IsLower = shakers.IsLower - IsUpper = shakers.IsUpper LessOrEqualThan = shakers.LessOrEqualThan - LessThan = shakers.LessThan - TimeEquals = shakers.TimeEquals True = shakers.True - TimeIgnore = shakers.TimeIgnore ) diff --git a/components/engine/vendor.conf b/components/engine/vendor.conf index 02fcc8b561..da39f03235 100644 --- a/components/engine/vendor.conf +++ b/components/engine/vendor.conf @@ -12,7 +12,7 @@ github.com/kr/pty 5cf931ef8f github.com/mattn/go-shellwords v1.0.3 github.com/sirupsen/logrus v1.0.6 github.com/tchap/go-patricia v2.2.6 -github.com/vdemeester/shakers 24d7f1d6a71aa5d9cbe7390e4afb66b7eef9e1b3 +github.com/vdemeester/shakers 24d7f1d6a71aa5d9cbe7390e4afb66b7eef9e1b3 # v0.1.0 golang.org/x/net a680a1efc54dd51c040b3b5ce4939ea3cf2ea0d1 golang.org/x/sys ac767d655b305d4e9612f5f6e33120b9176c4ad4 github.com/docker/go-units 47565b4f722fb6ceae66b95f853feed578a4a51c # v0.3.3 From 45b389fec815b71d694b0f2d36868159b45d28e9 Mon Sep 17 00:00:00 2001 From: Sebastiaan van Stijn Date: Thu, 4 Apr 2019 15:23:19 +0200 Subject: [PATCH 42/45] Replace some checkers and assertions with gotest.tools Signed-off-by: Sebastiaan van Stijn (cherry picked from commit 6345208b9b067f19f7792edcc675f59a617a3ca5) Signed-off-by: Sebastiaan van Stijn Upstream-commit: 9a4d7bb0e25169fa7d48e24777c683587c29c25a Component: engine --- .../engine/integration-cli/benchmark_test.go | 4 +- .../engine/integration-cli/check_test.go | 8 +- .../engine/integration-cli/checker/checker.go | 14 +- .../engine/integration-cli/daemon/daemon.go | 3 +- .../integration-cli/daemon/daemon_swarm.go | 7 +- .../integration-cli/docker_api_attach_test.go | 71 +-- .../integration-cli/docker_api_build_test.go | 107 ++-- .../docker_api_build_windows_test.go | 5 +- .../docker_api_containers_test.go | 402 +++++++-------- .../docker_api_exec_resize_test.go | 10 +- .../integration-cli/docker_api_exec_test.go | 92 ++-- .../integration-cli/docker_api_images_test.go | 70 +-- .../docker_api_inspect_test.go | 47 +- .../integration-cli/docker_api_logs_test.go | 49 +- .../docker_api_network_test.go | 118 ++--- .../integration-cli/docker_api_stats_test.go | 61 ++- .../docker_api_swarm_service_test.go | 79 +-- .../integration-cli/docker_api_swarm_test.go | 211 ++++---- .../engine/integration-cli/docker_api_test.go | 68 +-- .../integration-cli/docker_cli_attach_test.go | 11 +- .../docker_cli_attach_unix_test.go | 40 +- .../integration-cli/docker_cli_build_test.go | 80 +-- .../docker_cli_build_unix_test.go | 9 +- .../docker_cli_by_digest_test.go | 76 ++- .../docker_cli_cp_from_container_test.go | 7 +- .../integration-cli/docker_cli_cp_test.go | 292 +++++------ .../docker_cli_cp_to_container_test.go | 11 +- .../docker_cli_cp_to_container_unix_test.go | 20 +- .../docker_cli_cp_utils_test.go | 14 +- .../integration-cli/docker_cli_create_test.go | 21 +- .../docker_cli_daemon_plugins_test.go | 64 +-- .../integration-cli/docker_cli_daemon_test.go | 438 ++++++++--------- .../integration-cli/docker_cli_events_test.go | 200 ++++---- .../docker_cli_events_unix_test.go | 150 +++--- .../integration-cli/docker_cli_exec_test.go | 150 +++--- .../docker_cli_exec_unix_test.go | 22 +- ...er_cli_external_volume_driver_unix_test.go | 71 +-- .../integration-cli/docker_cli_images_test.go | 18 +- .../integration-cli/docker_cli_import_test.go | 19 +- .../integration-cli/docker_cli_info_test.go | 29 +- .../docker_cli_inspect_test.go | 66 +-- .../integration-cli/docker_cli_links_test.go | 9 +- .../integration-cli/docker_cli_login_test.go | 9 +- .../integration-cli/docker_cli_logout_test.go | 55 ++- .../integration-cli/docker_cli_logs_test.go | 88 ++-- .../docker_cli_network_unix_test.go | 207 ++++---- .../docker_cli_plugins_logdriver_test.go | 14 +- .../docker_cli_plugins_test.go | 141 +++--- .../integration-cli/docker_cli_port_test.go | 21 +- .../integration-cli/docker_cli_proxy_test.go | 6 +- .../docker_cli_prune_unix_test.go | 53 +- .../integration-cli/docker_cli_ps_test.go | 52 +- .../docker_cli_pull_local_test.go | 45 +- .../integration-cli/docker_cli_pull_test.go | 65 +-- .../integration-cli/docker_cli_push_test.go | 93 ++-- .../docker_cli_registry_user_agent_test.go | 13 +- .../docker_cli_restart_test.go | 129 ++--- .../integration-cli/docker_cli_rmi_test.go | 15 +- .../integration-cli/docker_cli_run_test.go | 225 ++++----- .../docker_cli_run_unix_test.go | 205 ++++---- .../docker_cli_save_load_test.go | 55 ++- .../docker_cli_save_load_unix_test.go | 28 +- .../integration-cli/docker_cli_search_test.go | 62 +-- .../docker_cli_service_create_test.go | 93 ++-- .../docker_cli_service_health_test.go | 5 +- .../docker_cli_service_logs_test.go | 67 +-- .../docker_cli_service_scale_test.go | 14 +- .../integration-cli/docker_cli_sni_test.go | 7 +- .../integration-cli/docker_cli_start_test.go | 13 +- .../integration-cli/docker_cli_stats_test.go | 50 +- .../integration-cli/docker_cli_swarm_test.go | 465 +++++++++--------- .../docker_cli_swarm_unix_test.go | 31 +- .../integration-cli/docker_cli_top_test.go | 12 +- .../docker_cli_update_unix_test.go | 114 +++-- .../integration-cli/docker_cli_userns_test.go | 20 +- .../docker_cli_v2_only_test.go | 7 +- .../integration-cli/docker_cli_volume_test.go | 59 +-- .../docker_deprecated_api_v124_test.go | 93 ++-- .../docker_deprecated_api_v124_unix_test.go | 12 +- .../integration-cli/docker_utils_test.go | 34 +- .../integration-cli/events_utils_test.go | 14 +- .../fixtures_linux_daemon_test.go | 24 +- 82 files changed, 2930 insertions(+), 3028 deletions(-) diff --git a/components/engine/integration-cli/benchmark_test.go b/components/engine/integration-cli/benchmark_test.go index ae0f67f6b0..ed51f79ead 100644 --- a/components/engine/integration-cli/benchmark_test.go +++ b/components/engine/integration-cli/benchmark_test.go @@ -8,8 +8,8 @@ import ( "strings" "sync" - "github.com/docker/docker/integration-cli/checker" "github.com/go-check/check" + "gotest.tools/assert" ) func (s *DockerSuite) BenchmarkConcurrentContainerActions(c *check.C) { @@ -90,6 +90,6 @@ func (s *DockerSuite) BenchmarkConcurrentContainerActions(c *check.C) { close(chErr) for err := range chErr { - c.Assert(err, checker.IsNil) + assert.NilError(c, err) } } diff --git a/components/engine/integration-cli/check_test.go b/components/engine/integration-cli/check_test.go index 0abf18154a..2a0b1a25d5 100644 --- a/components/engine/integration-cli/check_test.go +++ b/components/engine/integration-cli/check_test.go @@ -14,7 +14,6 @@ import ( "testing" "time" - "github.com/docker/docker/integration-cli/checker" "github.com/docker/docker/integration-cli/cli" "github.com/docker/docker/integration-cli/daemon" "github.com/docker/docker/integration-cli/environment" @@ -25,6 +24,7 @@ import ( "github.com/docker/docker/internal/test/registry" "github.com/docker/docker/pkg/reexec" "github.com/go-check/check" + "gotest.tools/assert" ) const ( @@ -200,7 +200,7 @@ func (s *DockerRegistryAuthHtpasswdSuite) SetUpTest(c *check.C) { func (s *DockerRegistryAuthHtpasswdSuite) TearDownTest(c *check.C) { if s.reg != nil { out, err := s.d.Cmd("logout", privateRegistryURL) - c.Assert(err, check.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) s.reg.Close() } if s.d != nil { @@ -233,7 +233,7 @@ func (s *DockerRegistryAuthTokenSuite) SetUpTest(c *check.C) { func (s *DockerRegistryAuthTokenSuite) TearDownTest(c *check.C) { if s.reg != nil { out, err := s.d.Cmd("logout", privateRegistryURL) - c.Assert(err, check.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) s.reg.Close() } if s.d != nil { @@ -391,7 +391,7 @@ func (ps *DockerPluginSuite) SetUpSuite(c *check.C) { defer cancel() err := plugin.CreateInRegistry(ctx, ps.getPluginRepo(), nil) - c.Assert(err, checker.IsNil, check.Commentf("failed to create plugin")) + assert.NilError(c, err, "failed to create plugin") } func (ps *DockerPluginSuite) TearDownSuite(c *check.C) { diff --git a/components/engine/integration-cli/checker/checker.go b/components/engine/integration-cli/checker/checker.go index 6b079c1fcd..7a13fa283d 100644 --- a/components/engine/integration-cli/checker/checker.go +++ b/components/engine/integration-cli/checker/checker.go @@ -16,13 +16,9 @@ var ( Not = check.Not NotNil = check.NotNil - Contains = shakers.Contains - Count = shakers.Count - Equals = shakers.Equals - False = shakers.False - GreaterOrEqualThan = shakers.GreaterOrEqualThan - GreaterThan = shakers.GreaterThan - HasPrefix = shakers.HasPrefix - LessOrEqualThan = shakers.LessOrEqualThan - True = shakers.True + Contains = shakers.Contains + Equals = shakers.Equals + False = shakers.False + GreaterThan = shakers.GreaterThan + True = shakers.True ) diff --git a/components/engine/integration-cli/daemon/daemon.go b/components/engine/integration-cli/daemon/daemon.go index 3d1fa38d5d..4bf773b314 100644 --- a/components/engine/integration-cli/daemon/daemon.go +++ b/components/engine/integration-cli/daemon/daemon.go @@ -5,7 +5,6 @@ import ( "strings" "time" - "github.com/docker/docker/integration-cli/checker" "github.com/docker/docker/internal/test/daemon" "github.com/go-check/check" "github.com/pkg/errors" @@ -91,7 +90,7 @@ func (d *Daemon) inspectFieldWithError(name, field string) (string, error) { // FIXME(vdemeester) should re-use ActivateContainers in some way func (d *Daemon) CheckActiveContainerCount(c *check.C) (interface{}, check.CommentInterface) { out, err := d.Cmd("ps", "-q") - c.Assert(err, checker.IsNil) + assert.NilError(c, err) if len(strings.TrimSpace(out)) == 0 { return 0, nil } diff --git a/components/engine/integration-cli/daemon/daemon_swarm.go b/components/engine/integration-cli/daemon/daemon_swarm.go index f43bd3b295..0c2f003bbd 100644 --- a/components/engine/integration-cli/daemon/daemon_swarm.go +++ b/components/engine/integration-cli/daemon/daemon_swarm.go @@ -9,7 +9,6 @@ import ( "github.com/docker/docker/api/types/filters" "github.com/docker/docker/api/types/swarm" "github.com/docker/docker/client" - "github.com/docker/docker/integration-cli/checker" "github.com/go-check/check" "gotest.tools/assert" ) @@ -111,7 +110,7 @@ func (d *Daemon) CheckRunningTaskNetworks(c *check.C) (interface{}, check.Commen } tasks, err := cli.TaskList(context.Background(), options) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) result := make(map[string]int) for _, task := range tasks { @@ -135,7 +134,7 @@ func (d *Daemon) CheckRunningTaskImages(c *check.C) (interface{}, check.CommentI } tasks, err := cli.TaskList(context.Background(), options) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) result := make(map[string]int) for _, task := range tasks { @@ -167,7 +166,7 @@ func (d *Daemon) CheckLocalNodeState(c *check.C) (interface{}, check.CommentInte // CheckControlAvailable returns the current swarm control available func (d *Daemon) CheckControlAvailable(c *check.C) (interface{}, check.CommentInterface) { info := d.SwarmInfo(c) - c.Assert(info.LocalNodeState, checker.Equals, swarm.LocalNodeStateActive) + assert.Equal(c, info.LocalNodeState, swarm.LocalNodeStateActive) return info.ControlAvailable, nil } diff --git a/components/engine/integration-cli/docker_api_attach_test.go b/components/engine/integration-cli/docker_api_attach_test.go index 3600aabc21..00f8bc9d6f 100644 --- a/components/engine/integration-cli/docker_api_attach_test.go +++ b/components/engine/integration-cli/docker_api_attach_test.go @@ -14,12 +14,13 @@ import ( "github.com/docker/docker/api/types" "github.com/docker/docker/client" - "github.com/docker/docker/integration-cli/checker" "github.com/docker/docker/internal/test/request" "github.com/docker/docker/pkg/stdcopy" "github.com/go-check/check" "github.com/pkg/errors" "golang.org/x/net/websocket" + "gotest.tools/assert" + is "gotest.tools/assert/cmp" ) func (s *DockerSuite) TestGetContainersAttachWebsocket(c *check.C) { @@ -27,17 +28,17 @@ func (s *DockerSuite) TestGetContainersAttachWebsocket(c *check.C) { out, _ := dockerCmd(c, "run", "-dit", "busybox", "cat") rwc, err := request.SockConn(time.Duration(10*time.Second), request.DaemonHost()) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) cleanedContainerID := strings.TrimSpace(out) config, err := websocket.NewConfig( "/containers/"+cleanedContainerID+"/attach/ws?stream=1&stdin=1&stdout=1&stderr=1", "http://localhost", ) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) ws, err := websocket.NewClient(config, rwc) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) defer ws.Close() expected := []byte("hello") @@ -59,41 +60,41 @@ func (s *DockerSuite) TestGetContainersAttachWebsocket(c *check.C) { select { case err := <-inChan: - c.Assert(err, checker.IsNil) + assert.NilError(c, err) case <-time.After(5 * time.Second): c.Fatal("Timeout writing to ws") } select { case err := <-outChan: - c.Assert(err, checker.IsNil) + assert.NilError(c, err) case <-time.After(5 * time.Second): c.Fatal("Timeout reading from ws") } - c.Assert(actual, checker.DeepEquals, expected, check.Commentf("Websocket didn't return the expected data")) + assert.Assert(c, is.DeepEqual(actual, expected), "Websocket didn't return the expected data") } // regression gh14320 func (s *DockerSuite) TestPostContainersAttachContainerNotFound(c *check.C) { resp, _, err := request.Post("/containers/doesnotexist/attach") - c.Assert(err, checker.IsNil) + assert.NilError(c, err) // connection will shutdown, err should be "persistent connection closed" - c.Assert(resp.StatusCode, checker.Equals, http.StatusNotFound) + assert.Equal(c, resp.StatusCode, http.StatusNotFound) content, err := request.ReadBody(resp.Body) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) expected := "No such container: doesnotexist\r\n" - c.Assert(string(content), checker.Equals, expected) + assert.Equal(c, string(content), expected) } func (s *DockerSuite) TestGetContainersWsAttachContainerNotFound(c *check.C) { res, body, err := request.Get("/containers/doesnotexist/attach/ws") - c.Assert(res.StatusCode, checker.Equals, http.StatusNotFound) - c.Assert(err, checker.IsNil) + assert.Equal(c, res.StatusCode, http.StatusNotFound) + assert.NilError(c, err) b, err := request.ReadBody(body) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) expected := "No such container: doesnotexist" - c.Assert(getErrorMessage(c, b), checker.Contains, expected) + assert.Assert(c, strings.Contains(getErrorMessage(c, b), expected)) } func (s *DockerSuite) TestPostContainersAttach(c *check.C) { @@ -103,7 +104,7 @@ func (s *DockerSuite) TestPostContainersAttach(c *check.C) { defer conn.Close() expected := []byte("success") _, err := conn.Write(expected) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) conn.SetReadDeadline(time.Now().Add(time.Second)) lenHeader := 0 @@ -112,29 +113,29 @@ func (s *DockerSuite) TestPostContainersAttach(c *check.C) { } actual := make([]byte, len(expected)+lenHeader) _, err = io.ReadFull(br, actual) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) if !tty { fdMap := map[string]byte{ "stdin": 0, "stdout": 1, "stderr": 2, } - c.Assert(actual[0], checker.Equals, fdMap[stream]) + assert.Equal(c, actual[0], fdMap[stream]) } - c.Assert(actual[lenHeader:], checker.DeepEquals, expected, check.Commentf("Attach didn't return the expected data from %s", stream)) + assert.Assert(c, is.DeepEqual(actual[lenHeader:], expected), "Attach didn't return the expected data from %s", stream) } expectTimeout := func(conn net.Conn, br *bufio.Reader, stream string) { defer conn.Close() _, err := conn.Write([]byte{'t'}) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) conn.SetReadDeadline(time.Now().Add(time.Second)) actual := make([]byte, 1) _, err = io.ReadFull(br, actual) opErr, ok := err.(*net.OpError) - c.Assert(ok, checker.Equals, true, check.Commentf("Error is expected to be *net.OpError, got %v", err)) - c.Assert(opErr.Timeout(), checker.Equals, true, check.Commentf("Read from %s is expected to timeout", stream)) + assert.Assert(c, ok, "Error is expected to be *net.OpError, got %v", err) + assert.Assert(c, opErr.Timeout(), "Read from %s is expected to timeout", stream) } // Create a container that only emits stdout. @@ -142,12 +143,12 @@ func (s *DockerSuite) TestPostContainersAttach(c *check.C) { cid = strings.TrimSpace(cid) // Attach to the container's stdout stream. conn, br, err := sockRequestHijack("POST", "/containers/"+cid+"/attach?stream=1&stdin=1&stdout=1", nil, "text/plain", request.DaemonHost()) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) // Check if the data from stdout can be received. expectSuccess(conn, br, "stdout", false) // Attach to the container's stderr stream. conn, br, err = sockRequestHijack("POST", "/containers/"+cid+"/attach?stream=1&stdin=1&stderr=1", nil, "text/plain", request.DaemonHost()) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) // Since the container only emits stdout, attaching to stderr should return nothing. expectTimeout(conn, br, "stdout") @@ -155,10 +156,10 @@ func (s *DockerSuite) TestPostContainersAttach(c *check.C) { cid, _ = dockerCmd(c, "run", "-di", "busybox", "/bin/sh", "-c", "cat >&2") cid = strings.TrimSpace(cid) conn, br, err = sockRequestHijack("POST", "/containers/"+cid+"/attach?stream=1&stdin=1&stderr=1", nil, "text/plain", request.DaemonHost()) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) expectSuccess(conn, br, "stderr", false) conn, br, err = sockRequestHijack("POST", "/containers/"+cid+"/attach?stream=1&stdin=1&stdout=1", nil, "text/plain", request.DaemonHost()) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) expectTimeout(conn, br, "stderr") // Test with tty. @@ -166,19 +167,19 @@ func (s *DockerSuite) TestPostContainersAttach(c *check.C) { cid = strings.TrimSpace(cid) // Attach to stdout only. conn, br, err = sockRequestHijack("POST", "/containers/"+cid+"/attach?stream=1&stdin=1&stdout=1", nil, "text/plain", request.DaemonHost()) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) expectSuccess(conn, br, "stdout", true) // Attach without stdout stream. conn, br, err = sockRequestHijack("POST", "/containers/"+cid+"/attach?stream=1&stdin=1&stderr=1", nil, "text/plain", request.DaemonHost()) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) // Nothing should be received because both the stdout and stderr of the container will be // sent to the client as stdout when tty is enabled. expectTimeout(conn, br, "stdout") // Test the client API client, err := client.NewClientWithOpts(client.FromEnv) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) defer client.Close() cid, _ = dockerCmd(c, "run", "-di", "busybox", "/bin/sh", "-c", "echo hello; cat") @@ -194,19 +195,19 @@ func (s *DockerSuite) TestPostContainersAttach(c *check.C) { } resp, err := client.ContainerAttach(context.Background(), cid, attachOpts) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) expectSuccess(resp.Conn, resp.Reader, "stdout", false) // Make sure we do see "hello" if Logs is true attachOpts.Logs = true resp, err = client.ContainerAttach(context.Background(), cid, attachOpts) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) defer resp.Conn.Close() resp.Conn.SetReadDeadline(time.Now().Add(time.Second)) _, err = resp.Conn.Write([]byte("success")) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) var outBuf, errBuf bytes.Buffer _, err = stdcopy.StdCopy(&outBuf, &errBuf, resp.Reader) @@ -214,9 +215,9 @@ func (s *DockerSuite) TestPostContainersAttach(c *check.C) { // ignore the timeout error as it is expected err = nil } - c.Assert(err, checker.IsNil) - c.Assert(errBuf.String(), checker.Equals, "") - c.Assert(outBuf.String(), checker.Equals, "hello\nsuccess") + assert.NilError(c, err) + assert.Equal(c, errBuf.String(), "") + assert.Equal(c, outBuf.String(), "hello\nsuccess") } // SockRequestHijack creates a connection to specified host (with method, contenttype, …) and returns a hijacked connection diff --git a/components/engine/integration-cli/docker_api_build_test.go b/components/engine/integration-cli/docker_api_build_test.go index 144acbd046..aa702f0135 100644 --- a/components/engine/integration-cli/docker_api_build_test.go +++ b/components/engine/integration-cli/docker_api_build_test.go @@ -13,7 +13,6 @@ import ( "strings" "github.com/docker/docker/api/types" - "github.com/docker/docker/integration-cli/checker" "github.com/docker/docker/internal/test/fakecontext" "github.com/docker/docker/internal/test/fakegit" "github.com/docker/docker/internal/test/fakestorage" @@ -41,17 +40,17 @@ RUN find /tmp/` defer server.Close() res, body, err := request.Post("/build?dockerfile=baz&remote="+server.URL()+"/testD", request.JSON) - c.Assert(err, checker.IsNil) - c.Assert(res.StatusCode, checker.Equals, http.StatusOK) + assert.NilError(c, err) + assert.Equal(c, res.StatusCode, http.StatusOK) buf, err := request.ReadBody(body) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) // Make sure Dockerfile exists. // Make sure 'baz' doesn't exist ANYWHERE despite being mentioned in the URL out := string(buf) - c.Assert(out, checker.Contains, "RUN find /tmp") - c.Assert(out, checker.Not(checker.Contains), "baz") + assert.Assert(c, is.Contains(out, "RUN find /tmp")) + assert.Assert(c, !strings.Contains(out, "baz")) } func (s *DockerSuite) TestBuildAPIRemoteTarballContext(c *check.C) { @@ -64,15 +63,11 @@ func (s *DockerSuite) TestBuildAPIRemoteTarballContext(c *check.C) { Name: "Dockerfile", Size: int64(len(dockerfile)), }) - // failed to write tar file header - c.Assert(err, checker.IsNil) + assert.NilError(c, err, "failed to write tar file header") _, err = tw.Write(dockerfile) - // failed to write tar file content - c.Assert(err, checker.IsNil) - - // failed to close tar archive - c.Assert(tw.Close(), checker.IsNil) + assert.NilError(c, err, "failed to write tar file content") + assert.NilError(c, tw.Close(), "failed to close tar archive") server := fakestorage.New(c, "", fakecontext.WithBinaryFiles(map[string]*bytes.Buffer{ "testT.tar": buffer, @@ -80,8 +75,8 @@ func (s *DockerSuite) TestBuildAPIRemoteTarballContext(c *check.C) { defer server.Close() res, b, err := request.Post("/build?remote="+server.URL()+"/testT.tar", request.ContentType("application/tar")) - c.Assert(err, checker.IsNil) - c.Assert(res.StatusCode, checker.Equals, http.StatusOK) + assert.NilError(c, err) + assert.Equal(c, res.StatusCode, http.StatusOK) b.Close() } @@ -97,11 +92,11 @@ RUN echo 'wrong'`) Size: int64(len(dockerfile)), }) // failed to write tar file header - c.Assert(err, checker.IsNil) + assert.NilError(c, err) _, err = tw.Write(dockerfile) // failed to write tar file content - c.Assert(err, checker.IsNil) + assert.NilError(c, err) custom := []byte(`FROM busybox RUN echo 'right' @@ -112,14 +107,14 @@ RUN echo 'right' }) // failed to write tar file header - c.Assert(err, checker.IsNil) + assert.NilError(c, err) _, err = tw.Write(custom) // failed to write tar file content - c.Assert(err, checker.IsNil) + assert.NilError(c, err) // failed to close tar archive - c.Assert(tw.Close(), checker.IsNil) + assert.NilError(c, tw.Close()) server := fakestorage.New(c, "", fakecontext.WithBinaryFiles(map[string]*bytes.Buffer{ "testT.tar": buffer, @@ -128,15 +123,15 @@ RUN echo 'right' url := "/build?dockerfile=custom&remote=" + server.URL() + "/testT.tar" res, body, err := request.Post(url, request.ContentType("application/tar")) - c.Assert(err, checker.IsNil) - c.Assert(res.StatusCode, checker.Equals, http.StatusOK) + assert.NilError(c, err) + assert.Equal(c, res.StatusCode, http.StatusOK) defer body.Close() content, err := request.ReadBody(body) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) // Build used the wrong dockerfile. - c.Assert(string(content), checker.Not(checker.Contains), "wrong") + assert.Assert(c, !strings.Contains(string(content), "wrong")) } func (s *DockerSuite) TestBuildAPILowerDockerfile(c *check.C) { @@ -147,14 +142,14 @@ RUN echo from dockerfile`, defer git.Close() res, body, err := request.Post("/build?remote="+git.RepoURL, request.JSON) - c.Assert(err, checker.IsNil) - c.Assert(res.StatusCode, checker.Equals, http.StatusOK) + assert.NilError(c, err) + assert.Equal(c, res.StatusCode, http.StatusOK) buf, err := request.ReadBody(body) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) out := string(buf) - c.Assert(out, checker.Contains, "from dockerfile") + assert.Assert(c, is.Contains(out, "from dockerfile")) } func (s *DockerSuite) TestBuildAPIBuildGitWithF(c *check.C) { @@ -168,14 +163,14 @@ RUN echo from Dockerfile`, // Make sure it tries to 'dockerfile' query param value res, body, err := request.Post("/build?dockerfile=baz&remote="+git.RepoURL, request.JSON) - c.Assert(err, checker.IsNil) - c.Assert(res.StatusCode, checker.Equals, http.StatusOK) + assert.NilError(c, err) + assert.Equal(c, res.StatusCode, http.StatusOK) buf, err := request.ReadBody(body) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) out := string(buf) - c.Assert(out, checker.Contains, "from baz") + assert.Assert(c, is.Contains(out, "from baz")) } func (s *DockerSuite) TestBuildAPIDoubleDockerfile(c *check.C) { @@ -190,14 +185,14 @@ RUN echo from dockerfile`, // Make sure it tries to 'dockerfile' query param value res, body, err := request.Post("/build?remote="+git.RepoURL, request.JSON) - c.Assert(err, checker.IsNil) - c.Assert(res.StatusCode, checker.Equals, http.StatusOK) + assert.NilError(c, err) + assert.Equal(c, res.StatusCode, http.StatusOK) buf, err := request.ReadBody(body) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) out := string(buf) - c.Assert(out, checker.Contains, "from Dockerfile") + assert.Assert(c, is.Contains(out, "from Dockerfile")) } func (s *DockerSuite) TestBuildAPIUnnormalizedTarPaths(c *check.C) { @@ -216,35 +211,37 @@ func (s *DockerSuite) TestBuildAPIUnnormalizedTarPaths(c *check.C) { Size: int64(len(dockerfile)), }) //failed to write tar file header - c.Assert(err, checker.IsNil) + assert.NilError(c, err) _, err = tw.Write(dockerfile) // failed to write Dockerfile in tar file content - c.Assert(err, checker.IsNil) + assert.NilError(c, err) err = tw.WriteHeader(&tar.Header{ Name: "dir/./file", Size: int64(len(fileContents)), }) //failed to write tar file header - c.Assert(err, checker.IsNil) + assert.NilError(c, err) _, err = tw.Write(fileContents) // failed to write file contents in tar file content - c.Assert(err, checker.IsNil) + assert.NilError(c, err) // failed to close tar archive - c.Assert(tw.Close(), checker.IsNil) + assert.NilError(c, tw.Close()) res, body, err := request.Post("/build", request.RawContent(ioutil.NopCloser(buffer)), request.ContentType("application/x-tar")) - c.Assert(err, checker.IsNil) - c.Assert(res.StatusCode, checker.Equals, http.StatusOK) + assert.NilError(c, err) + assert.Equal(c, res.StatusCode, http.StatusOK) out, err := request.ReadBody(body) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) lines := strings.Split(string(out), "\n") - c.Assert(len(lines), checker.GreaterThan, 1) - c.Assert(lines[len(lines)-2], checker.Matches, ".*Successfully built [0-9a-f]{12}.*") + assert.Assert(c, len(lines) > 1) + matched, err := regexp.MatchString(".*Successfully built [0-9a-f]{12}.*", lines[len(lines)-2]) + assert.NilError(c, err) + assert.Assert(c, matched) re := regexp.MustCompile("Successfully built ([0-9a-f]{12})") matches := re.FindStringSubmatch(lines[len(lines)-2]) @@ -254,7 +251,7 @@ func (s *DockerSuite) TestBuildAPIUnnormalizedTarPaths(c *check.C) { imageA := buildFromTarContext([]byte("abc")) imageB := buildFromTarContext([]byte("def")) - c.Assert(imageA, checker.Not(checker.Equals), imageB) + assert.Assert(c, imageA != imageB) } func (s *DockerSuite) TestBuildOnBuildWithCopy(c *check.C) { @@ -274,12 +271,12 @@ func (s *DockerSuite) TestBuildOnBuildWithCopy(c *check.C) { "/build", request.RawContent(ctx.AsTarReader(c)), request.ContentType("application/x-tar")) - c.Assert(err, checker.IsNil) - c.Assert(res.StatusCode, checker.Equals, http.StatusOK) + assert.NilError(c, err) + assert.Equal(c, res.StatusCode, http.StatusOK) out, err := request.ReadBody(body) - c.Assert(err, checker.IsNil) - c.Assert(string(out), checker.Contains, "Successfully built") + assert.NilError(c, err) + assert.Assert(c, is.Contains(string(out), "Successfully built")) } func (s *DockerSuite) TestBuildOnBuildCache(c *check.C) { @@ -427,8 +424,8 @@ func (s *DockerSuite) TestBuildChownOnCopy(c *check.C) { "/build", request.RawContent(ctx.AsTarReader(c)), request.ContentType("application/x-tar")) - c.Assert(err, checker.IsNil) - c.Assert(res.StatusCode, checker.Equals, http.StatusOK) + assert.NilError(c, err) + assert.Equal(c, res.StatusCode, http.StatusOK) out, err := request.ReadBody(body) assert.NilError(c, err) @@ -527,8 +524,8 @@ ENV foo bar` "/build", request.RawContent(ctx.AsTarReader(c)), request.ContentType("application/x-tar")) - c.Assert(err, checker.IsNil) - c.Assert(res.StatusCode, checker.Equals, http.StatusOK) + assert.NilError(c, err) + assert.Equal(c, res.StatusCode, http.StatusOK) out, err := request.ReadBody(body) assert.NilError(c, err) diff --git a/components/engine/integration-cli/docker_api_build_windows_test.go b/components/engine/integration-cli/docker_api_build_windows_test.go index a605c5be39..d100c8e297 100644 --- a/components/engine/integration-cli/docker_api_build_windows_test.go +++ b/components/engine/integration-cli/docker_api_build_windows_test.go @@ -5,7 +5,6 @@ package main import ( "net/http" - "github.com/docker/docker/integration-cli/checker" "github.com/docker/docker/internal/test/fakecontext" "github.com/docker/docker/internal/test/request" "github.com/go-check/check" @@ -30,8 +29,8 @@ func (s *DockerSuite) TestBuildWithRecycleBin(c *check.C) { request.RawContent(ctx.AsTarReader(c)), request.ContentType("application/x-tar")) - c.Assert(err, checker.IsNil) - c.Assert(res.StatusCode, checker.Equals, http.StatusOK) + assert.NilError(c, err) + assert.Equal(c, res.StatusCode, http.StatusOK) out, err := request.ReadBody(body) assert.NilError(c, err) diff --git a/components/engine/integration-cli/docker_api_containers_test.go b/components/engine/integration-cli/docker_api_containers_test.go index 6e1d5d7e68..9a8882138b 100644 --- a/components/engine/integration-cli/docker_api_containers_test.go +++ b/components/engine/integration-cli/docker_api_containers_test.go @@ -44,15 +44,15 @@ func (s *DockerSuite) TestContainerAPIGetAll(c *check.C) { dockerCmd(c, "run", "--name", name, "busybox", "true") cli, err := client.NewClientWithOpts(client.FromEnv) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) defer cli.Close() options := types.ContainerListOptions{ All: true, } containers, err := cli.ContainerList(context.Background(), options) - c.Assert(err, checker.IsNil) - c.Assert(containers, checker.HasLen, startCount+1) + assert.NilError(c, err) + assert.Equal(c, len(containers), startCount+1) actual := containers[0].Names[0] c.Assert(actual, checker.Equals, "/"+name) } @@ -63,15 +63,15 @@ func (s *DockerSuite) TestContainerAPIGetJSONNoFieldsOmitted(c *check.C) { dockerCmd(c, "run", "busybox", "true") cli, err := client.NewClientWithOpts(client.FromEnv) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) defer cli.Close() options := types.ContainerListOptions{ All: true, } containers, err := cli.ContainerList(context.Background(), options) - c.Assert(err, checker.IsNil) - c.Assert(containers, checker.HasLen, startCount+1) + assert.NilError(c, err) + assert.Equal(c, len(containers), startCount+1) actual := fmt.Sprintf("%+v", containers[0]) // empty Labels field triggered this bug, make sense to check for everything @@ -112,14 +112,14 @@ func (s *DockerSuite) TestContainerAPIPsOmitFields(c *check.C) { runSleepingContainer(c, "--name", name, "--expose", strconv.Itoa(port)) cli, err := client.NewClientWithOpts(client.FromEnv) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) defer cli.Close() options := types.ContainerListOptions{ All: true, } containers, err := cli.ContainerList(context.Background(), options) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) var foundContainer containerPs for _, c := range containers { for _, testName := range c.Names { @@ -144,11 +144,11 @@ func (s *DockerSuite) TestContainerAPIGetExport(c *check.C) { dockerCmd(c, "run", "--name", name, "busybox", "touch", "/test") cli, err := client.NewClientWithOpts(client.FromEnv) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) defer cli.Close() body, err := cli.ContainerExport(context.Background(), name) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) defer body.Close() found := false for tarReader := tar.NewReader(body); ; { @@ -171,11 +171,11 @@ func (s *DockerSuite) TestContainerAPIGetChanges(c *check.C) { dockerCmd(c, "run", "--name", name, "busybox", "rm", "/etc/passwd") cli, err := client.NewClientWithOpts(client.FromEnv) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) defer cli.Close() changes, err := cli.ContainerDiff(context.Background(), name) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) // Check the changelog for removal of /etc/passwd success := false @@ -201,11 +201,11 @@ func (s *DockerSuite) TestGetContainerStats(c *check.C) { bc := make(chan b, 1) go func() { cli, err := client.NewClientWithOpts(client.FromEnv) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) defer cli.Close() stats, err := cli.ContainerStats(context.Background(), name, true) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) bc <- b{stats, err} }() @@ -223,7 +223,7 @@ func (s *DockerSuite) TestGetContainerStats(c *check.C) { defer sr.stats.Body.Close() var s *types.Stats // decode only one object from the stream - c.Assert(dec.Decode(&s), checker.IsNil) + assert.NilError(c, dec.Decode(&s)) } } @@ -235,11 +235,11 @@ func (s *DockerSuite) TestGetContainerStatsRmRunning(c *check.C) { defer buf.Close() cli, err := client.NewClientWithOpts(client.FromEnv) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) defer cli.Close() stats, err := cli.ContainerStats(context.Background(), id, true) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) defer stats.Body.Close() chErr := make(chan error, 1) @@ -251,13 +251,13 @@ func (s *DockerSuite) TestGetContainerStatsRmRunning(c *check.C) { b := make([]byte, 32) // make sure we've got some stats _, err = buf.ReadTimeout(b, 2*time.Second) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) // Now remove without `-f` and make sure we are still pulling stats _, _, err = dockerCmdWithError("rm", id) c.Assert(err, checker.Not(checker.IsNil), check.Commentf("rm should have failed but didn't")) _, err = buf.ReadTimeout(b, 2*time.Second) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) dockerCmd(c, "rm", "-f", id) c.Assert(<-chErr, checker.IsNil) @@ -306,11 +306,11 @@ func (s *DockerSuite) TestGetContainerStatsStream(c *check.C) { bc := make(chan b, 1) go func() { cli, err := client.NewClientWithOpts(client.FromEnv) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) defer cli.Close() stats, err := cli.ContainerStats(context.Background(), name, true) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) bc <- b{stats, err} }() @@ -326,7 +326,7 @@ func (s *DockerSuite) TestGetContainerStatsStream(c *check.C) { case sr := <-bc: b, err := ioutil.ReadAll(sr.stats.Body) defer sr.stats.Body.Close() - c.Assert(err, checker.IsNil) + assert.NilError(c, err) s := string(b) // count occurrences of "read" of types.Stats if l := strings.Count(s, "read"); l < 2 { @@ -348,11 +348,11 @@ func (s *DockerSuite) TestGetContainerStatsNoStream(c *check.C) { go func() { cli, err := client.NewClientWithOpts(client.FromEnv) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) defer cli.Close() stats, err := cli.ContainerStats(context.Background(), name, false) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) bc <- b{stats, err} }() @@ -368,10 +368,10 @@ func (s *DockerSuite) TestGetContainerStatsNoStream(c *check.C) { case sr := <-bc: b, err := ioutil.ReadAll(sr.stats.Body) defer sr.stats.Body.Close() - c.Assert(err, checker.IsNil) + assert.NilError(c, err) s := string(b) // count occurrences of `"read"` of types.Stats - c.Assert(strings.Count(s, `"read"`), checker.Equals, 1, check.Commentf("Expected only one stat streamed, got %d", strings.Count(s, `"read"`))) + assert.Assert(c, strings.Count(s, `"read"`) == 1, "Expected only one stat streamed, got %d", strings.Count(s, `"read"`)) } } @@ -385,7 +385,7 @@ func (s *DockerSuite) TestGetStoppedContainerStats(c *check.C) { // below we'll check this on a timeout. go func() { cli, err := client.NewClientWithOpts(client.FromEnv) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) defer cli.Close() resp, err := cli.ContainerStats(context.Background(), name, false) @@ -395,7 +395,7 @@ func (s *DockerSuite) TestGetStoppedContainerStats(c *check.C) { select { case err := <-chResp: - c.Assert(err, checker.IsNil) + assert.NilError(c, err) case <-time.After(10 * time.Second): c.Fatal("timeout waiting for stats response for stopped container") } @@ -413,11 +413,11 @@ func (s *DockerSuite) TestContainerAPIPause(c *check.C) { ContainerID := strings.TrimSpace(out) cli, err := client.NewClientWithOpts(client.FromEnv) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) defer cli.Close() err = cli.ContainerPause(context.Background(), ContainerID) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) pausedContainers := getPaused(c) @@ -426,7 +426,7 @@ func (s *DockerSuite) TestContainerAPIPause(c *check.C) { } err = cli.ContainerUnpause(context.Background(), ContainerID) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) pausedContainers = getPaused(c) c.Assert(pausedContainers, checker.HasLen, 0, check.Commentf("There should be no paused container.")) @@ -436,15 +436,15 @@ func (s *DockerSuite) TestContainerAPITop(c *check.C) { testRequires(c, DaemonIsLinux) out, _ := dockerCmd(c, "run", "-d", "busybox", "/bin/sh", "-c", "top") id := strings.TrimSpace(string(out)) - c.Assert(waitRun(id), checker.IsNil) + assert.NilError(c, waitRun(id)) cli, err := client.NewClientWithOpts(client.FromEnv) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) defer cli.Close() // sort by comm[andline] to make sure order stays the same in case of PID rollover top, err := cli.ContainerTop(context.Background(), id, []string{"aux", "--sort=comm"}) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) c.Assert(top.Titles, checker.HasLen, 11, check.Commentf("expected 11 titles, found %d: %v", len(top.Titles), top.Titles)) if top.Titles[0] != "USER" || top.Titles[10] != "COMMAND" { @@ -459,20 +459,20 @@ func (s *DockerSuite) TestContainerAPITopWindows(c *check.C) { testRequires(c, DaemonIsWindows) out := runSleepingContainer(c, "-d") id := strings.TrimSpace(string(out)) - c.Assert(waitRun(id), checker.IsNil) + assert.NilError(c, waitRun(id)) cli, err := client.NewClientWithOpts(client.FromEnv) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) defer cli.Close() top, err := cli.ContainerTop(context.Background(), id, nil) - c.Assert(err, checker.IsNil) - c.Assert(top.Titles, checker.HasLen, 4, check.Commentf("expected 4 titles, found %d: %v", len(top.Titles), top.Titles)) + assert.NilError(c, err) + assert.Equal(c, len(top.Titles), 4, "expected 4 titles, found %d: %v", len(top.Titles), top.Titles) if top.Titles[0] != "Name" || top.Titles[3] != "Private Working Set" { c.Fatalf("expected `Name` at `Titles[0]` and `Private Working Set` at Titles[3]: %v", top.Titles) } - c.Assert(len(top.Processes), checker.GreaterOrEqualThan, 2, check.Commentf("expected at least 2 processes, found %d: %v", len(top.Processes), top.Processes)) + assert.Assert(c, len(top.Processes) >= 2, "expected at least 2 processes, found %d: %v", len(top.Processes), top.Processes) foundProcess := false expectedProcess := "busybox.exe" @@ -483,7 +483,7 @@ func (s *DockerSuite) TestContainerAPITopWindows(c *check.C) { } } - c.Assert(foundProcess, checker.Equals, true, check.Commentf("expected to find %s: %v", expectedProcess, top.Processes)) + assert.Assert(c, foundProcess, "expected to find %s: %v", expectedProcess, top.Processes) } func (s *DockerSuite) TestContainerAPICommit(c *check.C) { @@ -491,7 +491,7 @@ func (s *DockerSuite) TestContainerAPICommit(c *check.C) { dockerCmd(c, "run", "--name="+cName, "busybox", "/bin/sh", "-c", "touch /test") cli, err := client.NewClientWithOpts(client.FromEnv) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) defer cli.Close() options := types.ContainerCommitOptions{ @@ -499,7 +499,7 @@ func (s *DockerSuite) TestContainerAPICommit(c *check.C) { } img, err := cli.ContainerCommit(context.Background(), cName, options) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) cmd := inspectField(c, img.ID, "Config.Cmd") c.Assert(cmd, checker.Equals, "[/bin/sh -c touch /test]", check.Commentf("got wrong Cmd from commit: %q", cmd)) @@ -513,7 +513,7 @@ func (s *DockerSuite) TestContainerAPICommitWithLabelInConfig(c *check.C) { dockerCmd(c, "run", "--name="+cName, "busybox", "/bin/sh", "-c", "touch /test") cli, err := client.NewClientWithOpts(client.FromEnv) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) defer cli.Close() config := containertypes.Config{ @@ -525,7 +525,7 @@ func (s *DockerSuite) TestContainerAPICommitWithLabelInConfig(c *check.C) { } img, err := cli.ContainerCommit(context.Background(), cName, options) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) label1 := inspectFieldMap(c, img.ID, "Config.Labels", "key1") c.Assert(label1, checker.Equals, "value1") @@ -560,11 +560,11 @@ func (s *DockerSuite) TestContainerAPIBadPort(c *check.C) { } cli, err := client.NewClientWithOpts(client.FromEnv) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) defer cli.Close() _, err = cli.ContainerCreate(context.Background(), &config, &hostConfig, &networktypes.NetworkingConfig{}, "") - c.Assert(err.Error(), checker.Contains, `invalid port specification: "aa80"`) + assert.ErrorContains(c, err, `invalid port specification: "aa80"`) } func (s *DockerSuite) TestContainerAPICreate(c *check.C) { @@ -574,26 +574,26 @@ func (s *DockerSuite) TestContainerAPICreate(c *check.C) { } cli, err := client.NewClientWithOpts(client.FromEnv) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) defer cli.Close() container, err := cli.ContainerCreate(context.Background(), &config, &containertypes.HostConfig{}, &networktypes.NetworkingConfig{}, "") - c.Assert(err, checker.IsNil) + assert.NilError(c, err) out, _ := dockerCmd(c, "start", "-a", container.ID) - c.Assert(strings.TrimSpace(out), checker.Equals, "/test") + assert.Equal(c, strings.TrimSpace(out), "/test") } func (s *DockerSuite) TestContainerAPICreateEmptyConfig(c *check.C) { cli, err := client.NewClientWithOpts(client.FromEnv) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) defer cli.Close() _, err = cli.ContainerCreate(context.Background(), &containertypes.Config{}, &containertypes.HostConfig{}, &networktypes.NetworkingConfig{}, "") expected := "No command specified" - c.Assert(err.Error(), checker.Contains, expected) + assert.ErrorContains(c, err, expected) } func (s *DockerSuite) TestContainerAPICreateMultipleNetworksConfig(c *check.C) { @@ -611,7 +611,7 @@ func (s *DockerSuite) TestContainerAPICreateMultipleNetworksConfig(c *check.C) { } cli, err := client.NewClientWithOpts(client.FromEnv) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) defer cli.Close() _, err = cli.ContainerCreate(context.Background(), &config, &containertypes.HostConfig{}, &networkingConfig, "") @@ -633,14 +633,14 @@ func (s *DockerSuite) TestContainerAPICreateWithHostName(c *check.C) { } cli, err := client.NewClientWithOpts(client.FromEnv) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) defer cli.Close() container, err := cli.ContainerCreate(context.Background(), &config, &containertypes.HostConfig{}, &networktypes.NetworkingConfig{}, "") - c.Assert(err, checker.IsNil) + assert.NilError(c, err) containerJSON, err := cli.ContainerInspect(context.Background(), container.ID) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) c.Assert(containerJSON.Config.Hostname, checker.Equals, hostName, check.Commentf("Mismatched Hostname")) c.Assert(containerJSON.Config.Domainname, checker.Equals, domainName, check.Commentf("Mismatched Domainname")) @@ -669,14 +669,14 @@ func UtilCreateNetworkMode(c *check.C, networkMode containertypes.NetworkMode) { } cli, err := client.NewClientWithOpts(client.FromEnv) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) defer cli.Close() container, err := cli.ContainerCreate(context.Background(), &config, &hostConfig, &networktypes.NetworkingConfig{}, "") - c.Assert(err, checker.IsNil) + assert.NilError(c, err) containerJSON, err := cli.ContainerInspect(context.Background(), container.ID) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) c.Assert(containerJSON.HostConfig.NetworkMode, checker.Equals, containertypes.NetworkMode(networkMode), check.Commentf("Mismatched NetworkMode")) } @@ -696,17 +696,17 @@ func (s *DockerSuite) TestContainerAPICreateWithCpuSharesCpuset(c *check.C) { } cli, err := client.NewClientWithOpts(client.FromEnv) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) defer cli.Close() container, err := cli.ContainerCreate(context.Background(), &config, &hostConfig, &networktypes.NetworkingConfig{}, "") - c.Assert(err, checker.IsNil) + assert.NilError(c, err) containerJSON, err := cli.ContainerInspect(context.Background(), container.ID) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) out := inspectField(c, containerJSON.ID, "HostConfig.CpuShares") - c.Assert(out, checker.Equals, "512") + assert.Equal(c, out, "512") outCpuset := inspectField(c, containerJSON.ID, "HostConfig.CpusetCpus") c.Assert(outCpuset, checker.Equals, "0") @@ -725,11 +725,11 @@ func (s *DockerSuite) TestContainerAPIVerifyHeader(c *check.C) { // Try with no content-type res, body, err := create("") - c.Assert(err, checker.IsNil) + assert.NilError(c, err) // todo: we need to figure out a better way to compare between dockerd versions // comparing between daemon API version is not precise. if versions.GreaterThanOrEqualTo(testEnv.DaemonAPIVersion(), "1.32") { - c.Assert(res.StatusCode, checker.Equals, http.StatusBadRequest) + assert.Equal(c, res.StatusCode, http.StatusBadRequest) } else { c.Assert(res.StatusCode, checker.Not(checker.Equals), http.StatusOK) } @@ -737,9 +737,9 @@ func (s *DockerSuite) TestContainerAPIVerifyHeader(c *check.C) { // Try with wrong content-type res, body, err = create("application/xml") - c.Assert(err, checker.IsNil) + assert.NilError(c, err) if versions.GreaterThanOrEqualTo(testEnv.DaemonAPIVersion(), "1.32") { - c.Assert(res.StatusCode, checker.Equals, http.StatusBadRequest) + assert.Equal(c, res.StatusCode, http.StatusBadRequest) } else { c.Assert(res.StatusCode, checker.Not(checker.Equals), http.StatusOK) } @@ -747,8 +747,8 @@ func (s *DockerSuite) TestContainerAPIVerifyHeader(c *check.C) { // now application/json res, body, err = create("application/json") - c.Assert(err, checker.IsNil) - c.Assert(res.StatusCode, checker.Equals, http.StatusCreated) + assert.NilError(c, err) + assert.Equal(c, res.StatusCode, http.StatusCreated) body.Close() } @@ -767,15 +767,15 @@ func (s *DockerSuite) TestContainerAPIInvalidPortSyntax(c *check.C) { }` res, body, err := request.Post("/containers/create", request.RawString(config), request.JSON) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) if versions.GreaterThanOrEqualTo(testEnv.DaemonAPIVersion(), "1.32") { - c.Assert(res.StatusCode, checker.Equals, http.StatusBadRequest) + assert.Equal(c, res.StatusCode, http.StatusBadRequest) } else { c.Assert(res.StatusCode, checker.Not(checker.Equals), http.StatusOK) } b, err := request.ReadBody(body) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) c.Assert(string(b[:]), checker.Contains, "invalid port") } @@ -791,15 +791,15 @@ func (s *DockerSuite) TestContainerAPIRestartPolicyInvalidPolicyName(c *check.C) }` res, body, err := request.Post("/containers/create", request.RawString(config), request.JSON) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) if versions.GreaterThanOrEqualTo(testEnv.DaemonAPIVersion(), "1.32") { - c.Assert(res.StatusCode, checker.Equals, http.StatusBadRequest) + assert.Equal(c, res.StatusCode, http.StatusBadRequest) } else { c.Assert(res.StatusCode, checker.Not(checker.Equals), http.StatusOK) } b, err := request.ReadBody(body) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) c.Assert(string(b[:]), checker.Contains, "invalid restart policy") } @@ -815,15 +815,15 @@ func (s *DockerSuite) TestContainerAPIRestartPolicyRetryMismatch(c *check.C) { }` res, body, err := request.Post("/containers/create", request.RawString(config), request.JSON) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) if versions.GreaterThanOrEqualTo(testEnv.DaemonAPIVersion(), "1.32") { - c.Assert(res.StatusCode, checker.Equals, http.StatusBadRequest) + assert.Equal(c, res.StatusCode, http.StatusBadRequest) } else { c.Assert(res.StatusCode, checker.Not(checker.Equals), http.StatusOK) } b, err := request.ReadBody(body) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) c.Assert(string(b[:]), checker.Contains, "maximum retry count cannot be used with restart policy") } @@ -839,15 +839,15 @@ func (s *DockerSuite) TestContainerAPIRestartPolicyNegativeRetryCount(c *check.C }` res, body, err := request.Post("/containers/create", request.RawString(config), request.JSON) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) if versions.GreaterThanOrEqualTo(testEnv.DaemonAPIVersion(), "1.32") { - c.Assert(res.StatusCode, checker.Equals, http.StatusBadRequest) + assert.Equal(c, res.StatusCode, http.StatusBadRequest) } else { c.Assert(res.StatusCode, checker.Not(checker.Equals), http.StatusOK) } b, err := request.ReadBody(body) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) c.Assert(string(b[:]), checker.Contains, "maximum retry count cannot be negative") } @@ -863,8 +863,8 @@ func (s *DockerSuite) TestContainerAPIRestartPolicyDefaultRetryCount(c *check.C) }` res, _, err := request.Post("/containers/create", request.RawString(config), request.JSON) - c.Assert(err, checker.IsNil) - c.Assert(res.StatusCode, checker.Equals, http.StatusCreated) + assert.NilError(c, err) + assert.Equal(c, res.StatusCode, http.StatusCreated) } // Issue 7941 - test to make sure a "null" in JSON is just ignored. @@ -894,18 +894,18 @@ func (s *DockerSuite) TestContainerAPIPostCreateNull(c *check.C) { "OnBuild":null}` res, body, err := request.Post("/containers/create", request.RawString(config), request.JSON) - c.Assert(err, checker.IsNil) - c.Assert(res.StatusCode, checker.Equals, http.StatusCreated) + assert.NilError(c, err) + assert.Equal(c, res.StatusCode, http.StatusCreated) b, err := request.ReadBody(body) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) type createResp struct { ID string } var container createResp c.Assert(json.Unmarshal(b, &container), checker.IsNil) out := inspectField(c, container.ID, "HostConfig.CpusetCpus") - c.Assert(out, checker.Equals, "") + assert.Equal(c, out, "") outMemory := inspectField(c, container.ID, "HostConfig.Memory") c.Assert(outMemory, checker.Equals, "0") @@ -925,12 +925,12 @@ func (s *DockerSuite) TestCreateWithTooLowMemoryLimit(c *check.C) { }` res, body, err := request.Post("/containers/create", request.RawString(config), request.JSON) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) b, err2 := request.ReadBody(body) c.Assert(err2, checker.IsNil) if versions.GreaterThanOrEqualTo(testEnv.DaemonAPIVersion(), "1.32") { - c.Assert(res.StatusCode, checker.Equals, http.StatusBadRequest) + assert.Equal(c, res.StatusCode, http.StatusBadRequest) } else { c.Assert(res.StatusCode, checker.Not(checker.Equals), http.StatusOK) } @@ -944,11 +944,11 @@ func (s *DockerSuite) TestContainerAPIRename(c *check.C) { newName := "TestContainerAPIRenameNew" cli, err := client.NewClientWithOpts(client.FromEnv) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) defer cli.Close() err = cli.ContainerRename(context.Background(), containerID, newName) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) name := inspectField(c, containerID, "Name") c.Assert(name, checker.Equals, "/"+newName, check.Commentf("Failed to rename container")) @@ -959,11 +959,11 @@ func (s *DockerSuite) TestContainerAPIKill(c *check.C) { runSleepingContainer(c, "-i", "--name", name) cli, err := client.NewClientWithOpts(client.FromEnv) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) defer cli.Close() err = cli.ContainerKill(context.Background(), name, "SIGKILL") - c.Assert(err, checker.IsNil) + assert.NilError(c, err) state := inspectField(c, name, "State.Running") c.Assert(state, checker.Equals, "false", check.Commentf("got wrong State from container %s: %q", name, state)) @@ -973,12 +973,12 @@ func (s *DockerSuite) TestContainerAPIRestart(c *check.C) { name := "test-api-restart" runSleepingContainer(c, "-di", "--name", name) cli, err := client.NewClientWithOpts(client.FromEnv) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) defer cli.Close() timeout := 1 * time.Second err = cli.ContainerRestart(context.Background(), name, &timeout) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) c.Assert(waitInspect(name, "{{ .State.Restarting }} {{ .State.Running }}", "false true", 15*time.Second), checker.IsNil) } @@ -987,14 +987,14 @@ func (s *DockerSuite) TestContainerAPIRestartNotimeoutParam(c *check.C) { name := "test-api-restart-no-timeout-param" out := runSleepingContainer(c, "-di", "--name", name) id := strings.TrimSpace(out) - c.Assert(waitRun(id), checker.IsNil) + assert.NilError(c, waitRun(id)) cli, err := client.NewClientWithOpts(client.FromEnv) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) defer cli.Close() err = cli.ContainerRestart(context.Background(), name, nil) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) c.Assert(waitInspect(name, "{{ .State.Restarting }} {{ .State.Running }}", "false true", 15*time.Second), checker.IsNil) } @@ -1008,19 +1008,19 @@ func (s *DockerSuite) TestContainerAPIStart(c *check.C) { } cli, err := client.NewClientWithOpts(client.FromEnv) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) defer cli.Close() _, err = cli.ContainerCreate(context.Background(), &config, &containertypes.HostConfig{}, &networktypes.NetworkingConfig{}, name) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) err = cli.ContainerStart(context.Background(), name, types.ContainerStartOptions{}) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) // second call to start should give 304 // maybe add ContainerStartWithRaw to test it err = cli.ContainerStart(context.Background(), name, types.ContainerStartOptions{}) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) // TODO(tibor): figure out why this doesn't work on windows } @@ -1031,17 +1031,17 @@ func (s *DockerSuite) TestContainerAPIStop(c *check.C) { timeout := 30 * time.Second cli, err := client.NewClientWithOpts(client.FromEnv) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) defer cli.Close() err = cli.ContainerStop(context.Background(), name, &timeout) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) c.Assert(waitInspect(name, "{{ .State.Running }}", "false", 60*time.Second), checker.IsNil) // second call to start should give 304 // maybe add ContainerStartWithRaw to test it err = cli.ContainerStop(context.Background(), name, &timeout) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) } func (s *DockerSuite) TestContainerAPIWait(c *check.C) { @@ -1054,14 +1054,14 @@ func (s *DockerSuite) TestContainerAPIWait(c *check.C) { dockerCmd(c, "run", "--name", name, "busybox", sleepCmd, "2") cli, err := client.NewClientWithOpts(client.FromEnv) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) defer cli.Close() waitresC, errC := cli.ContainerWait(context.Background(), name, "") select { case err = <-errC: - c.Assert(err, checker.IsNil) + assert.NilError(c, err) case waitres := <-waitresC: c.Assert(waitres.StatusCode, checker.Equals, int64(0)) } @@ -1076,8 +1076,8 @@ func (s *DockerSuite) TestContainerAPICopyNotExistsAnyMore(c *check.C) { } // no copy in client/ res, _, err := request.Post("/containers/"+name+"/copy", request.JSONBody(postData)) - c.Assert(err, checker.IsNil) - c.Assert(res.StatusCode, checker.Equals, http.StatusNotFound) + assert.NilError(c, err) + assert.Equal(c, res.StatusCode, http.StatusNotFound) } func (s *DockerSuite) TestContainerAPICopyPre124(c *check.C) { @@ -1090,8 +1090,8 @@ func (s *DockerSuite) TestContainerAPICopyPre124(c *check.C) { } res, body, err := request.Post("/v1.23/containers/"+name+"/copy", request.JSONBody(postData)) - c.Assert(err, checker.IsNil) - c.Assert(res.StatusCode, checker.Equals, http.StatusOK) + assert.NilError(c, err) + assert.Equal(c, res.StatusCode, http.StatusOK) found := false for tarReader := tar.NewReader(body); ; { @@ -1120,14 +1120,14 @@ func (s *DockerSuite) TestContainerAPICopyResourcePathEmptyPre124(c *check.C) { } res, body, err := request.Post("/v1.23/containers/"+name+"/copy", request.JSONBody(postData)) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) if versions.GreaterThanOrEqualTo(testEnv.DaemonAPIVersion(), "1.32") { - c.Assert(res.StatusCode, checker.Equals, http.StatusBadRequest) + assert.Equal(c, res.StatusCode, http.StatusBadRequest) } else { c.Assert(res.StatusCode, checker.Not(checker.Equals), http.StatusOK) } b, err := request.ReadBody(body) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) c.Assert(string(b), checker.Matches, "Path cannot be empty\n") } @@ -1141,14 +1141,14 @@ func (s *DockerSuite) TestContainerAPICopyResourcePathNotFoundPre124(c *check.C) } res, body, err := request.Post("/v1.23/containers/"+name+"/copy", request.JSONBody(postData)) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) if versions.LessThan(testEnv.DaemonAPIVersion(), "1.32") { - c.Assert(res.StatusCode, checker.Equals, http.StatusInternalServerError) + assert.Equal(c, res.StatusCode, http.StatusInternalServerError) } else { - c.Assert(res.StatusCode, checker.Equals, http.StatusNotFound) + assert.Equal(c, res.StatusCode, http.StatusNotFound) } b, err := request.ReadBody(body) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) c.Assert(string(b), checker.Matches, "Could not find the file /notexist in container "+name+"\n") } @@ -1159,50 +1159,50 @@ func (s *DockerSuite) TestContainerAPICopyContainerNotFoundPr124(c *check.C) { } res, _, err := request.Post("/v1.23/containers/notexists/copy", request.JSONBody(postData)) - c.Assert(err, checker.IsNil) - c.Assert(res.StatusCode, checker.Equals, http.StatusNotFound) + assert.NilError(c, err) + assert.Equal(c, res.StatusCode, http.StatusNotFound) } func (s *DockerSuite) TestContainerAPIDelete(c *check.C) { out := runSleepingContainer(c) id := strings.TrimSpace(out) - c.Assert(waitRun(id), checker.IsNil) + assert.NilError(c, waitRun(id)) dockerCmd(c, "stop", id) cli, err := client.NewClientWithOpts(client.FromEnv) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) defer cli.Close() err = cli.ContainerRemove(context.Background(), id, types.ContainerRemoveOptions{}) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) } func (s *DockerSuite) TestContainerAPIDeleteNotExist(c *check.C) { cli, err := client.NewClientWithOpts(client.FromEnv) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) defer cli.Close() err = cli.ContainerRemove(context.Background(), "doesnotexist", types.ContainerRemoveOptions{}) - c.Assert(err.Error(), checker.Contains, "No such container: doesnotexist") + assert.ErrorContains(c, err, "No such container: doesnotexist") } func (s *DockerSuite) TestContainerAPIDeleteForce(c *check.C) { out := runSleepingContainer(c) id := strings.TrimSpace(out) - c.Assert(waitRun(id), checker.IsNil) + assert.NilError(c, waitRun(id)) removeOptions := types.ContainerRemoveOptions{ Force: true, } cli, err := client.NewClientWithOpts(client.FromEnv) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) defer cli.Close() err = cli.ContainerRemove(context.Background(), id, removeOptions) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) } func (s *DockerSuite) TestContainerAPIDeleteRemoveLinks(c *check.C) { @@ -1211,7 +1211,7 @@ func (s *DockerSuite) TestContainerAPIDeleteRemoveLinks(c *check.C) { out, _ := dockerCmd(c, "run", "-d", "--name", "tlink1", "busybox", "top") id := strings.TrimSpace(out) - c.Assert(waitRun(id), checker.IsNil) + assert.NilError(c, waitRun(id)) out, _ = dockerCmd(c, "run", "--link", "tlink1:tlink1", "--name", "tlink2", "-d", "busybox", "top") @@ -1226,11 +1226,11 @@ func (s *DockerSuite) TestContainerAPIDeleteRemoveLinks(c *check.C) { } cli, err := client.NewClientWithOpts(client.FromEnv) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) defer cli.Close() err = cli.ContainerRemove(context.Background(), "tlink2/tlink1", removeOptions) - c.Assert(err, check.IsNil) + assert.NilError(c, err) linksPostRm := inspectFieldJSON(c, id2, "HostConfig.Links") c.Assert(linksPostRm, checker.Equals, "null", check.Commentf("call to api deleteContainer links should have removed the specified links")) @@ -1240,15 +1240,15 @@ func (s *DockerSuite) TestContainerAPIDeleteConflict(c *check.C) { out := runSleepingContainer(c) id := strings.TrimSpace(out) - c.Assert(waitRun(id), checker.IsNil) + assert.NilError(c, waitRun(id)) cli, err := client.NewClientWithOpts(client.FromEnv) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) defer cli.Close() err = cli.ContainerRemove(context.Background(), id, types.ContainerRemoveOptions{}) expected := "cannot remove a running container" - c.Assert(err.Error(), checker.Contains, expected) + assert.ErrorContains(c, err, expected) } func (s *DockerSuite) TestContainerAPIDeleteRemoveVolume(c *check.C) { @@ -1262,12 +1262,12 @@ func (s *DockerSuite) TestContainerAPIDeleteRemoveVolume(c *check.C) { out := runSleepingContainer(c, "-v", vol) id := strings.TrimSpace(out) - c.Assert(waitRun(id), checker.IsNil) + assert.NilError(c, waitRun(id)) source, err := inspectMountSourceField(id, vol) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) _, err = os.Stat(source) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) removeOptions := types.ContainerRemoveOptions{ Force: true, @@ -1275,11 +1275,11 @@ func (s *DockerSuite) TestContainerAPIDeleteRemoveVolume(c *check.C) { } cli, err := client.NewClientWithOpts(client.FromEnv) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) defer cli.Close() err = cli.ContainerRemove(context.Background(), id, removeOptions) - c.Assert(err, check.IsNil) + assert.NilError(c, err) _, err = os.Stat(source) c.Assert(os.IsNotExist(err), checker.True, check.Commentf("expected to get ErrNotExist error, got %v", err)) @@ -1303,7 +1303,7 @@ func (s *DockerSuite) TestContainerAPIChunkedEncoding(c *check.C) { })) c.Assert(err, checker.IsNil, check.Commentf("error creating container with chunked encoding")) defer resp.Body.Close() - c.Assert(resp.StatusCode, checker.Equals, http.StatusCreated) + assert.Equal(c, resp.StatusCode, http.StatusCreated) } func (s *DockerSuite) TestContainerAPIPostContainerStop(c *check.C) { @@ -1313,11 +1313,11 @@ func (s *DockerSuite) TestContainerAPIPostContainerStop(c *check.C) { c.Assert(waitRun(containerID), checker.IsNil) cli, err := client.NewClientWithOpts(client.FromEnv) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) defer cli.Close() err = cli.ContainerStop(context.Background(), containerID, nil) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) c.Assert(waitInspect(containerID, "{{ .State.Running }}", "false", 60*time.Second), checker.IsNil) } @@ -1330,13 +1330,13 @@ func (s *DockerSuite) TestPostContainerAPICreateWithStringOrSliceEntrypoint(c *c } cli, err := client.NewClientWithOpts(client.FromEnv) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) defer cli.Close() _, err = cli.ContainerCreate(context.Background(), &config, &containertypes.HostConfig{}, &networktypes.NetworkingConfig{}, "echotest") - c.Assert(err, checker.IsNil) + assert.NilError(c, err) out, _ := dockerCmd(c, "start", "-a", "echotest") - c.Assert(strings.TrimSpace(out), checker.Equals, "hello world") + assert.Equal(c, strings.TrimSpace(out), "hello world") config2 := struct { Image string @@ -1344,9 +1344,9 @@ func (s *DockerSuite) TestPostContainerAPICreateWithStringOrSliceEntrypoint(c *c Cmd []string }{"busybox", "echo", []string{"hello", "world"}} _, _, err = request.Post("/containers/create?name=echotest2", request.JSONBody(config2)) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) out, _ = dockerCmd(c, "start", "-a", "echotest2") - c.Assert(strings.TrimSpace(out), checker.Equals, "hello world") + assert.Equal(c, strings.TrimSpace(out), "hello world") } // #14170 @@ -1357,13 +1357,13 @@ func (s *DockerSuite) TestPostContainersCreateWithStringOrSliceCmd(c *check.C) { } cli, err := client.NewClientWithOpts(client.FromEnv) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) defer cli.Close() _, err = cli.ContainerCreate(context.Background(), &config, &containertypes.HostConfig{}, &networktypes.NetworkingConfig{}, "echotest") - c.Assert(err, checker.IsNil) + assert.NilError(c, err) out, _ := dockerCmd(c, "start", "-a", "echotest") - c.Assert(strings.TrimSpace(out), checker.Equals, "hello world") + assert.Equal(c, strings.TrimSpace(out), "hello world") config2 := struct { Image string @@ -1371,9 +1371,9 @@ func (s *DockerSuite) TestPostContainersCreateWithStringOrSliceCmd(c *check.C) { Cmd string }{"busybox", "echo", "hello world"} _, _, err = request.Post("/containers/create?name=echotest2", request.JSONBody(config2)) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) out, _ = dockerCmd(c, "start", "-a", "echotest2") - c.Assert(strings.TrimSpace(out), checker.Equals, "hello world") + assert.Equal(c, strings.TrimSpace(out), "hello world") } // regression #14318 @@ -1386,8 +1386,8 @@ func (s *DockerSuite) TestPostContainersCreateWithStringOrSliceCapAddDrop(c *che CapDrop string }{"busybox", "NET_ADMIN", "SYS_ADMIN"} res, _, err := request.Post("/containers/create?name=capaddtest0", request.JSONBody(config)) - c.Assert(err, checker.IsNil) - c.Assert(res.StatusCode, checker.Equals, http.StatusCreated) + assert.NilError(c, err) + assert.Equal(c, res.StatusCode, http.StatusCreated) config2 := containertypes.Config{ Image: "busybox", @@ -1398,11 +1398,11 @@ func (s *DockerSuite) TestPostContainersCreateWithStringOrSliceCapAddDrop(c *che } cli, err := client.NewClientWithOpts(client.FromEnv) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) defer cli.Close() _, err = cli.ContainerCreate(context.Background(), &config2, &hostConfig, &networktypes.NetworkingConfig{}, "capaddtest1") - c.Assert(err, checker.IsNil) + assert.NilError(c, err) } // #14915 @@ -1413,10 +1413,10 @@ func (s *DockerSuite) TestContainerAPICreateNoHostConfig118(c *check.C) { } cli, err := client.NewClientWithOpts(client.FromEnv, client.WithVersion("v1.18")) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) _, err = cli.ContainerCreate(context.Background(), &config, &containertypes.HostConfig{}, &networktypes.NetworkingConfig{}, "") - c.Assert(err, checker.IsNil) + assert.NilError(c, err) } // Ensure an error occurs when you have a container read-only rootfs but you @@ -1442,10 +1442,10 @@ func (s *DockerSuite) TestPutContainerArchiveErrSymlinkInVolumeToReadOnlyRootfs( // directory outside the volume. This should cause an error because the // rootfs is read-only. cli, err := client.NewClientWithOpts(client.FromEnv, client.WithVersion("v1.20")) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) err = cli.CopyToContainer(context.Background(), cID, "/vol2/symlinkToAbsDir", nil, types.CopyToContainerOptions{}) - c.Assert(err.Error(), checker.Contains, "container rootfs is marked read-only") + assert.ErrorContains(c, err, "container rootfs is marked read-only") } func (s *DockerSuite) TestPostContainersCreateWithWrongCpusetValues(c *check.C) { @@ -1453,7 +1453,7 @@ func (s *DockerSuite) TestPostContainersCreateWithWrongCpusetValues(c *check.C) testRequires(c, DaemonIsLinux) cli, err := client.NewClientWithOpts(client.FromEnv) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) defer cli.Close() config := containertypes.Config{ @@ -1468,7 +1468,7 @@ func (s *DockerSuite) TestPostContainersCreateWithWrongCpusetValues(c *check.C) _, err = cli.ContainerCreate(context.Background(), &config, &hostConfig1, &networktypes.NetworkingConfig{}, name) expected := "Invalid value 1-42,, for cpuset cpus" - c.Assert(err.Error(), checker.Contains, expected) + assert.ErrorContains(c, err, expected) hostConfig2 := containertypes.HostConfig{ Resources: containertypes.Resources{ @@ -1478,7 +1478,7 @@ func (s *DockerSuite) TestPostContainersCreateWithWrongCpusetValues(c *check.C) name = "wrong-cpuset-mems" _, err = cli.ContainerCreate(context.Background(), &config, &hostConfig2, &networktypes.NetworkingConfig{}, name) expected = "Invalid value 42-3,1-- for cpuset mems" - c.Assert(err.Error(), checker.Contains, expected) + assert.ErrorContains(c, err, expected) } func (s *DockerSuite) TestPostContainersCreateShmSizeNegative(c *check.C) { @@ -1492,11 +1492,11 @@ func (s *DockerSuite) TestPostContainersCreateShmSizeNegative(c *check.C) { } cli, err := client.NewClientWithOpts(client.FromEnv) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) defer cli.Close() _, err = cli.ContainerCreate(context.Background(), &config, &hostConfig, &networktypes.NetworkingConfig{}, "") - c.Assert(err.Error(), checker.Contains, "SHM size can not be less than 0") + assert.ErrorContains(c, err, "SHM size can not be less than 0") } func (s *DockerSuite) TestPostContainersCreateShmSizeHostConfigOmitted(c *check.C) { @@ -1509,14 +1509,14 @@ func (s *DockerSuite) TestPostContainersCreateShmSizeHostConfigOmitted(c *check. } cli, err := client.NewClientWithOpts(client.FromEnv) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) defer cli.Close() container, err := cli.ContainerCreate(context.Background(), &config, &containertypes.HostConfig{}, &networktypes.NetworkingConfig{}, "") - c.Assert(err, check.IsNil) + assert.NilError(c, err) containerJSON, err := cli.ContainerInspect(context.Background(), container.ID) - c.Assert(err, check.IsNil) + assert.NilError(c, err) c.Assert(containerJSON.HostConfig.ShmSize, check.Equals, defaultSHMSize) @@ -1536,14 +1536,14 @@ func (s *DockerSuite) TestPostContainersCreateShmSizeOmitted(c *check.C) { } cli, err := client.NewClientWithOpts(client.FromEnv) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) defer cli.Close() container, err := cli.ContainerCreate(context.Background(), &config, &containertypes.HostConfig{}, &networktypes.NetworkingConfig{}, "") - c.Assert(err, check.IsNil) + assert.NilError(c, err) containerJSON, err := cli.ContainerInspect(context.Background(), container.ID) - c.Assert(err, check.IsNil) + assert.NilError(c, err) c.Assert(containerJSON.HostConfig.ShmSize, check.Equals, int64(67108864)) @@ -1567,14 +1567,14 @@ func (s *DockerSuite) TestPostContainersCreateWithShmSize(c *check.C) { } cli, err := client.NewClientWithOpts(client.FromEnv) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) defer cli.Close() container, err := cli.ContainerCreate(context.Background(), &config, &hostConfig, &networktypes.NetworkingConfig{}, "") - c.Assert(err, check.IsNil) + assert.NilError(c, err) containerJSON, err := cli.ContainerInspect(context.Background(), container.ID) - c.Assert(err, check.IsNil) + assert.NilError(c, err) c.Assert(containerJSON.HostConfig.ShmSize, check.Equals, int64(1073741824)) @@ -1593,14 +1593,14 @@ func (s *DockerSuite) TestPostContainersCreateMemorySwappinessHostConfigOmitted( } cli, err := client.NewClientWithOpts(client.FromEnv) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) defer cli.Close() container, err := cli.ContainerCreate(context.Background(), &config, &containertypes.HostConfig{}, &networktypes.NetworkingConfig{}, "") - c.Assert(err, check.IsNil) + assert.NilError(c, err) containerJSON, err := cli.ContainerInspect(context.Background(), container.ID) - c.Assert(err, check.IsNil) + assert.NilError(c, err) if versions.LessThan(testEnv.DaemonAPIVersion(), "1.31") { c.Assert(*containerJSON.HostConfig.MemorySwappiness, check.Equals, int64(-1)) @@ -1623,14 +1623,14 @@ func (s *DockerSuite) TestPostContainersCreateWithOomScoreAdjInvalidRange(c *che } cli, err := client.NewClientWithOpts(client.FromEnv) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) defer cli.Close() name := "oomscoreadj-over" _, err = cli.ContainerCreate(context.Background(), &config, &hostConfig, &networktypes.NetworkingConfig{}, name) expected := "Invalid value 1001, range for oom score adj is [-1000, 1000]" - c.Assert(err.Error(), checker.Contains, expected) + assert.ErrorContains(c, err, expected) hostConfig = containertypes.HostConfig{ OomScoreAdj: -1001, @@ -1640,17 +1640,17 @@ func (s *DockerSuite) TestPostContainersCreateWithOomScoreAdjInvalidRange(c *che _, err = cli.ContainerCreate(context.Background(), &config, &hostConfig, &networktypes.NetworkingConfig{}, name) expected = "Invalid value -1001, range for oom score adj is [-1000, 1000]" - c.Assert(err.Error(), checker.Contains, expected) + assert.ErrorContains(c, err, expected) } // test case for #22210 where an empty container name caused panic. func (s *DockerSuite) TestContainerAPIDeleteWithEmptyName(c *check.C) { cli, err := client.NewClientWithOpts(client.FromEnv) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) defer cli.Close() err = cli.ContainerRemove(context.Background(), "", types.ContainerRemoveOptions{}) - c.Assert(err.Error(), checker.Contains, "No such container") + assert.ErrorContains(c, err, "No such container") } func (s *DockerSuite) TestContainerAPIStatsWithNetworkDisabled(c *check.C) { @@ -1666,14 +1666,14 @@ func (s *DockerSuite) TestContainerAPIStatsWithNetworkDisabled(c *check.C) { } cli, err := client.NewClientWithOpts(client.FromEnv) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) defer cli.Close() _, err = cli.ContainerCreate(context.Background(), &config, &containertypes.HostConfig{}, &networktypes.NetworkingConfig{}, name) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) err = cli.ContainerStart(context.Background(), name, types.ContainerStartOptions{}) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) c.Assert(waitRun(name), check.IsNil) @@ -1798,7 +1798,7 @@ func (s *DockerSuite) TestContainersAPICreateMountsValidation(c *check.C) { if testEnv.IsLocalDaemon() { tmpDir, err := ioutils.TempDir("", "test-mounts-api") - c.Assert(err, checker.IsNil) + assert.NilError(c, err) defer os.RemoveAll(tmpDir) cases = append(cases, []testCase{ { @@ -1884,16 +1884,16 @@ func (s *DockerSuite) TestContainersAPICreateMountsValidation(c *check.C) { } cli, err := client.NewClientWithOpts(client.FromEnv) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) defer cli.Close() for i, x := range cases { c.Logf("case %d", i) _, err = cli.ContainerCreate(context.Background(), &x.config, &x.hostConfig, &networktypes.NetworkingConfig{}, "") if len(x.msg) > 0 { - c.Assert(err.Error(), checker.Contains, x.msg, check.Commentf("%v", cases[i].config)) + assert.ErrorContains(c, err, x.msg, "%v", cases[i].config) } else { - c.Assert(err, checker.IsNil) + assert.NilError(c, err) } } } @@ -1904,10 +1904,10 @@ func (s *DockerSuite) TestContainerAPICreateMountsBindRead(c *check.C) { prefix, slash := getPrefixAndSlashFromDaemonPlatform() destPath := prefix + slash + "foo" tmpDir, err := ioutil.TempDir("", "test-mounts-api-bind") - c.Assert(err, checker.IsNil) + assert.NilError(c, err) defer os.RemoveAll(tmpDir) err = ioutil.WriteFile(filepath.Join(tmpDir, "bar"), []byte("hello"), 666) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) config := containertypes.Config{ Image: "busybox", Cmd: []string{"/bin/sh", "-c", "cat /foo/bar"}, @@ -1918,14 +1918,14 @@ func (s *DockerSuite) TestContainerAPICreateMountsBindRead(c *check.C) { }, } cli, err := client.NewClientWithOpts(client.FromEnv) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) defer cli.Close() _, err = cli.ContainerCreate(context.Background(), &config, &hostConfig, &networktypes.NetworkingConfig{}, "test") - c.Assert(err, checker.IsNil) + assert.NilError(c, err) out, _ := dockerCmd(c, "start", "-a", "test") - c.Assert(out, checker.Equals, "hello") + assert.Equal(c, out, "hello") } // Test Mounts comes out as expected for the MountPoint @@ -1990,7 +1990,7 @@ func (s *DockerSuite) TestContainersAPICreateMountsCreate(c *check.C) { if testEnv.IsLocalDaemon() { // setup temp dir for testing binds tmpDir1, err := ioutil.TempDir("", "test-mounts-api-1") - c.Assert(err, checker.IsNil) + assert.NilError(c, err) defer os.RemoveAll(tmpDir1) cases = append(cases, []testCase{ { @@ -2015,7 +2015,7 @@ func (s *DockerSuite) TestContainersAPICreateMountsCreate(c *check.C) { // for modes only supported on Linux if DaemonIsLinux() { tmpDir3, err := ioutils.TempDir("", "test-mounts-api-3") - c.Assert(err, checker.IsNil) + assert.NilError(c, err) defer os.RemoveAll(tmpDir3) c.Assert(mount.Mount(tmpDir3, tmpDir3, "none", "bind,rw"), checker.IsNil) @@ -2169,7 +2169,7 @@ func (s *DockerSuite) TestContainersAPICreateMountsTmpfs(c *check.C) { } cli, err := client.NewClientWithOpts(client.FromEnv) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) defer cli.Close() config := containertypes.Config{ @@ -2183,7 +2183,7 @@ func (s *DockerSuite) TestContainersAPICreateMountsTmpfs(c *check.C) { } _, err = cli.ContainerCreate(context.Background(), &config, &hostConfig, &networktypes.NetworkingConfig{}, cName) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) out, _ := dockerCmd(c, "start", "-a", cName) for _, option := range x.expectedOptions { c.Assert(out, checker.Contains, option) @@ -2197,12 +2197,12 @@ func (s *DockerSuite) TestContainersAPICreateMountsTmpfs(c *check.C) { func (s *DockerSuite) TestContainerKillCustomStopSignal(c *check.C) { id := strings.TrimSpace(runSleepingContainer(c, "--stop-signal=SIGTERM", "--restart=always")) res, _, err := request.Post("/containers/" + id + "/kill") - c.Assert(err, checker.IsNil) + assert.NilError(c, err) defer res.Body.Close() b, err := ioutil.ReadAll(res.Body) - c.Assert(err, checker.IsNil) - c.Assert(res.StatusCode, checker.Equals, http.StatusNoContent, check.Commentf(string(b))) + assert.NilError(c, err) + assert.Equal(c, res.StatusCode, http.StatusNoContent, string(b)) err = waitInspect(id, "{{.State.Running}} {{.State.Restarting}}", "false false", 30*time.Second) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) } diff --git a/components/engine/integration-cli/docker_api_exec_resize_test.go b/components/engine/integration-cli/docker_api_exec_resize_test.go index 70d310aaf2..75be90bb12 100644 --- a/components/engine/integration-cli/docker_api_exec_resize_test.go +++ b/components/engine/integration-cli/docker_api_exec_resize_test.go @@ -10,9 +10,9 @@ import ( "sync" "github.com/docker/docker/api/types/versions" - "github.com/docker/docker/integration-cli/checker" "github.com/docker/docker/internal/test/request" "github.com/go-check/check" + "gotest.tools/assert" ) func (s *DockerSuite) TestExecResizeAPIHeightWidthNoInt(c *check.C) { @@ -22,11 +22,11 @@ func (s *DockerSuite) TestExecResizeAPIHeightWidthNoInt(c *check.C) { endpoint := "/exec/" + cleanedContainerID + "/resize?h=foo&w=bar" res, _, err := request.Post(endpoint) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) if versions.LessThan(testEnv.DaemonAPIVersion(), "1.32") { - c.Assert(res.StatusCode, checker.Equals, http.StatusInternalServerError) + assert.Equal(c, res.StatusCode, http.StatusInternalServerError) } else { - c.Assert(res.StatusCode, checker.Equals, http.StatusBadRequest) + assert.Equal(c, res.StatusCode, http.StatusBadRequest) } } @@ -50,7 +50,7 @@ func (s *DockerSuite) TestExecResizeImmediatelyAfterExecStart(c *check.C) { } buf, err := request.ReadBody(body) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) out := map[string]string{} err = json.Unmarshal(buf, &out) diff --git a/components/engine/integration-cli/docker_api_exec_test.go b/components/engine/integration-cli/docker_api_exec_test.go index 3c98eb4ac1..dcb14af6de 100644 --- a/components/engine/integration-cli/docker_api_exec_test.go +++ b/components/engine/integration-cli/docker_api_exec_test.go @@ -19,6 +19,7 @@ import ( "github.com/docker/docker/integration-cli/checker" "github.com/docker/docker/internal/test/request" "github.com/go-check/check" + "gotest.tools/assert" ) // Regression test for #9414 @@ -27,17 +28,15 @@ func (s *DockerSuite) TestExecAPICreateNoCmd(c *check.C) { dockerCmd(c, "run", "-d", "-t", "--name", name, "busybox", "/bin/sh") res, body, err := request.Post(fmt.Sprintf("/containers/%s/exec", name), request.JSONBody(map[string]interface{}{"Cmd": nil})) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) if versions.LessThan(testEnv.DaemonAPIVersion(), "1.32") { - c.Assert(res.StatusCode, checker.Equals, http.StatusInternalServerError) + assert.Equal(c, res.StatusCode, http.StatusInternalServerError) } else { - c.Assert(res.StatusCode, checker.Equals, http.StatusBadRequest) + assert.Equal(c, res.StatusCode, http.StatusBadRequest) } b, err := request.ReadBody(body) - c.Assert(err, checker.IsNil) - - comment := check.Commentf("Expected message when creating exec command with no Cmd specified") - c.Assert(getErrorMessage(c, b), checker.Contains, "No exec command specified", comment) + assert.NilError(c, err) + assert.Assert(c, strings.Contains(getErrorMessage(c, b), "No exec command specified"), "Expected message when creating exec command with no Cmd specified") } func (s *DockerSuite) TestExecAPICreateNoValidContentType(c *check.C) { @@ -50,17 +49,15 @@ func (s *DockerSuite) TestExecAPICreateNoValidContentType(c *check.C) { } res, body, err := request.Post(fmt.Sprintf("/containers/%s/exec", name), request.RawContent(ioutil.NopCloser(jsonData)), request.ContentType("test/plain")) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) if versions.LessThan(testEnv.DaemonAPIVersion(), "1.32") { - c.Assert(res.StatusCode, checker.Equals, http.StatusInternalServerError) + assert.Equal(c, res.StatusCode, http.StatusInternalServerError) } else { - c.Assert(res.StatusCode, checker.Equals, http.StatusBadRequest) + assert.Equal(c, res.StatusCode, http.StatusBadRequest) } b, err := request.ReadBody(body) - c.Assert(err, checker.IsNil) - - comment := check.Commentf("Expected message when creating exec command with invalid Content-Type specified") - c.Assert(getErrorMessage(c, b), checker.Contains, "Content-Type specified", comment) + assert.NilError(c, err) + assert.Assert(c, strings.Contains(getErrorMessage(c, b), "Content-Type specified"), "Expected message when creating exec command with invalid Content-Type specified") } func (s *DockerSuite) TestExecAPICreateContainerPaused(c *check.C) { @@ -72,16 +69,14 @@ func (s *DockerSuite) TestExecAPICreateContainerPaused(c *check.C) { dockerCmd(c, "pause", name) cli, err := client.NewClientWithOpts(client.FromEnv) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) defer cli.Close() config := types.ExecConfig{ Cmd: []string{"true"}, } _, err = cli.ContainerExecCreate(context.Background(), name, config) - - comment := check.Commentf("Expected message when creating exec command with Container %s is paused", name) - c.Assert(err.Error(), checker.Contains, "Container "+name+" is paused, unpause the container before exec", comment) + assert.ErrorContains(c, err, "Container "+name+" is paused, unpause the container before exec", "Expected message when creating exec command with Container %s is paused", name) } func (s *DockerSuite) TestExecAPIStart(c *check.C) { @@ -93,7 +88,7 @@ func (s *DockerSuite) TestExecAPIStart(c *check.C) { var execJSON struct{ PID int } inspectExec(c, id, &execJSON) - c.Assert(execJSON.PID, checker.GreaterThan, 1) + assert.Assert(c, execJSON.PID > 1) id = createExec(c, "test") dockerCmd(c, "stop", "test") @@ -117,8 +112,8 @@ func (s *DockerSuite) TestExecAPIStartEnsureHeaders(c *check.C) { id := createExec(c, "test") resp, _, err := request.Post(fmt.Sprintf("/exec/%s/start", id), request.RawString(`{"Detach": true}`), request.JSON) - c.Assert(err, checker.IsNil) - c.Assert(resp.Header.Get("Server"), checker.Not(checker.Equals), "") + assert.NilError(c, err) + assert.Assert(c, resp.Header.Get("Server") != "") } func (s *DockerSuite) TestExecAPIStartBackwardsCompatible(c *check.C) { @@ -127,12 +122,12 @@ func (s *DockerSuite) TestExecAPIStartBackwardsCompatible(c *check.C) { id := createExec(c, "test") resp, body, err := request.Post(fmt.Sprintf("/v1.20/exec/%s/start", id), request.RawString(`{"Detach": true}`), request.ContentType("text/plain")) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) b, err := request.ReadBody(body) comment := check.Commentf("response body: %s", b) - c.Assert(err, checker.IsNil, comment) - c.Assert(resp.StatusCode, checker.Equals, http.StatusOK, comment) + assert.NilError(c, err, comment) + assert.Equal(c, resp.StatusCode, http.StatusOK, comment) } // #19362 @@ -156,21 +151,21 @@ func (s *DockerSuite) TestExecAPIStartWithDetach(c *check.C) { } cli, err := client.NewClientWithOpts(client.FromEnv) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) defer cli.Close() createResp, err := cli.ContainerExecCreate(context.Background(), name, config) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) _, body, err := request.Post(fmt.Sprintf("/exec/%s/start", createResp.ID), request.RawString(`{"Detach": true}`), request.JSON) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) b, err := request.ReadBody(body) comment := check.Commentf("response body: %s", b) - c.Assert(err, checker.IsNil, comment) + assert.NilError(c, err, comment) resp, _, err := request.Get("/_ping") - c.Assert(err, checker.IsNil) + assert.NilError(c, err) if resp.StatusCode != http.StatusOK { c.Fatal("daemon is down, it should alive") } @@ -189,7 +184,7 @@ func (s *DockerSuite) TestExecAPIStartValidCommand(c *check.C) { var inspectJSON struct{ ExecIDs []string } inspectContainer(c, name, &inspectJSON) - c.Assert(inspectJSON.ExecIDs, checker.IsNil) + assert.Assert(c, inspectJSON.ExecIDs == nil) } // #30311 @@ -208,7 +203,7 @@ func (s *DockerSuite) TestExecAPIStartInvalidCommand(c *check.C) { var inspectJSON struct{ ExecIDs []string } inspectContainer(c, name, &inspectJSON) - c.Assert(inspectJSON.ExecIDs, checker.IsNil) + assert.Assert(c, inspectJSON.ExecIDs == nil) } func (s *DockerSuite) TestExecStateCleanup(c *check.C) { @@ -224,13 +219,13 @@ func (s *DockerSuite) TestExecStateCleanup(c *check.C) { checkReadDir := func(c *check.C) (interface{}, check.CommentInterface) { fi, err := ioutil.ReadDir(stateDir) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) return len(fi), nil } fi, err := ioutil.ReadDir(stateDir) - c.Assert(err, checker.IsNil) - c.Assert(len(fi), checker.GreaterThan, 1) + assert.NilError(c, err) + assert.Assert(c, len(fi) > 1) id := createExecCmd(c, name, "ls") startExec(c, id, http.StatusOK) @@ -246,8 +241,8 @@ func (s *DockerSuite) TestExecStateCleanup(c *check.C) { dockerCmd(c, "stop", name) _, err = os.Stat(stateDir) - c.Assert(err, checker.NotNil) - c.Assert(os.IsNotExist(err), checker.True) + assert.ErrorContains(c, err, "") + assert.Assert(c, os.IsNotExist(err)) } func createExec(c *check.C, name string) string { @@ -256,34 +251,33 @@ func createExec(c *check.C, name string) string { func createExecCmd(c *check.C, name string, cmd string) string { _, reader, err := request.Post(fmt.Sprintf("/containers/%s/exec", name), request.JSONBody(map[string]interface{}{"Cmd": []string{cmd}})) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) b, err := ioutil.ReadAll(reader) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) defer reader.Close() createResp := struct { ID string `json:"Id"` }{} - c.Assert(json.Unmarshal(b, &createResp), checker.IsNil, check.Commentf(string(b))) + assert.NilError(c, json.Unmarshal(b, &createResp), string(b)) return createResp.ID } func startExec(c *check.C, id string, code int) { resp, body, err := request.Post(fmt.Sprintf("/exec/%s/start", id), request.RawString(`{"Detach": true}`), request.JSON) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) b, err := request.ReadBody(body) - comment := check.Commentf("response body: %s", b) - c.Assert(err, checker.IsNil, comment) - c.Assert(resp.StatusCode, checker.Equals, code, comment) + assert.NilError(c, err, "response body: %s", b) + assert.Equal(c, resp.StatusCode, code, "response body: %s", b) } func inspectExec(c *check.C, id string, out interface{}) { resp, body, err := request.Get(fmt.Sprintf("/exec/%s/json", id)) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) defer body.Close() - c.Assert(resp.StatusCode, checker.Equals, http.StatusOK) + assert.Equal(c, resp.StatusCode, http.StatusOK) err = json.NewDecoder(body).Decode(out) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) } func waitForExec(c *check.C, id string) { @@ -305,9 +299,9 @@ func waitForExec(c *check.C, id string) { func inspectContainer(c *check.C, id string, out interface{}) { resp, body, err := request.Get(fmt.Sprintf("/containers/%s/json", id)) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) defer body.Close() - c.Assert(resp.StatusCode, checker.Equals, http.StatusOK) + assert.Equal(c, resp.StatusCode, http.StatusOK) err = json.NewDecoder(body).Decode(out) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) } diff --git a/components/engine/integration-cli/docker_api_images_test.go b/components/engine/integration-cli/docker_api_images_test.go index 416c1f715c..9e4f84a581 100644 --- a/components/engine/integration-cli/docker_api_images_test.go +++ b/components/engine/integration-cli/docker_api_images_test.go @@ -11,17 +11,17 @@ import ( "github.com/docker/docker/api/types" "github.com/docker/docker/api/types/filters" "github.com/docker/docker/client" - "github.com/docker/docker/integration-cli/checker" "github.com/docker/docker/integration-cli/cli" "github.com/docker/docker/integration-cli/cli/build" "github.com/docker/docker/internal/test/request" "github.com/docker/docker/pkg/parsers/kernel" "github.com/go-check/check" + "gotest.tools/assert" ) func (s *DockerSuite) TestAPIImagesFilter(c *check.C) { cli, err := client.NewClientWithOpts(client.FromEnv) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) defer cli.Close() name := "utest:tag1" @@ -38,29 +38,29 @@ func (s *DockerSuite) TestAPIImagesFilter(c *check.C) { Filters: filters, } images, err := cli.ImageList(context.Background(), options) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) return images } //incorrect number of matches returned images := getImages("utest*/*") - c.Assert(images[0].RepoTags, checker.HasLen, 2) + assert.Equal(c, len(images[0].RepoTags), 2) images = getImages("utest") - c.Assert(images[0].RepoTags, checker.HasLen, 1) + assert.Equal(c, len(images[0].RepoTags), 1) images = getImages("utest*") - c.Assert(images[0].RepoTags, checker.HasLen, 1) + assert.Equal(c, len(images[0].RepoTags), 1) images = getImages("*5000*/*") - c.Assert(images[0].RepoTags, checker.HasLen, 1) + assert.Equal(c, len(images[0].RepoTags), 1) } func (s *DockerSuite) TestAPIImagesSaveAndLoad(c *check.C) { if runtime.GOOS == "windows" { v, err := kernel.GetKernelVersion() - c.Assert(err, checker.IsNil) + assert.NilError(c, err) build, _ := strconv.Atoi(strings.Split(strings.SplitN(v.String(), " ", 3)[2][1:], ".")[0]) if build == 16299 { c.Skip("Temporarily disabled on RS3 builds") @@ -72,24 +72,24 @@ func (s *DockerSuite) TestAPIImagesSaveAndLoad(c *check.C) { id := getIDByName(c, "saveandload") res, body, err := request.Get("/images/" + id + "/get") - c.Assert(err, checker.IsNil) + assert.NilError(c, err) defer body.Close() - c.Assert(res.StatusCode, checker.Equals, http.StatusOK) + assert.Equal(c, res.StatusCode, http.StatusOK) dockerCmd(c, "rmi", id) res, loadBody, err := request.Post("/images/load", request.RawContent(body), request.ContentType("application/x-tar")) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) defer loadBody.Close() - c.Assert(res.StatusCode, checker.Equals, http.StatusOK) + assert.Equal(c, res.StatusCode, http.StatusOK) inspectOut := cli.InspectCmd(c, id, cli.Format(".Id")).Combined() - c.Assert(strings.TrimSpace(string(inspectOut)), checker.Equals, id, check.Commentf("load did not work properly")) + assert.Equal(c, strings.TrimSpace(string(inspectOut)), id, "load did not work properly") } func (s *DockerSuite) TestAPIImagesDelete(c *check.C) { cli, err := client.NewClientWithOpts(client.FromEnv) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) defer cli.Close() if testEnv.OSType != "windows" { @@ -102,18 +102,18 @@ func (s *DockerSuite) TestAPIImagesDelete(c *check.C) { dockerCmd(c, "tag", name, "test:tag1") _, err = cli.ImageRemove(context.Background(), id, types.ImageRemoveOptions{}) - c.Assert(err.Error(), checker.Contains, "unable to delete") + assert.ErrorContains(c, err, "unable to delete") _, err = cli.ImageRemove(context.Background(), "test:noexist", types.ImageRemoveOptions{}) - c.Assert(err.Error(), checker.Contains, "No such image") + assert.ErrorContains(c, err, "No such image") _, err = cli.ImageRemove(context.Background(), "test:tag1", types.ImageRemoveOptions{}) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) } func (s *DockerSuite) TestAPIImagesHistory(c *check.C) { cli, err := client.NewClientWithOpts(client.FromEnv) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) defer cli.Close() if testEnv.OSType != "windows" { @@ -124,9 +124,9 @@ func (s *DockerSuite) TestAPIImagesHistory(c *check.C) { id := getIDByName(c, name) historydata, err := cli.ImageHistory(context.Background(), id) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) - c.Assert(historydata, checker.Not(checker.HasLen), 0) + assert.Assert(c, len(historydata) != 0) var found bool for _, tag := range historydata[0].Tags { if tag == "test-api-images-history:latest" { @@ -134,13 +134,13 @@ func (s *DockerSuite) TestAPIImagesHistory(c *check.C) { break } } - c.Assert(found, checker.True) + assert.Assert(c, found) } func (s *DockerSuite) TestAPIImagesImportBadSrc(c *check.C) { if runtime.GOOS == "windows" { v, err := kernel.GetKernelVersion() - c.Assert(err, checker.IsNil) + assert.NilError(c, err) build, _ := strconv.Atoi(strings.Split(strings.SplitN(v.String(), " ", 3)[2][1:], ".")[0]) if build == 16299 { c.Skip("Temporarily disabled on RS3 builds") @@ -164,9 +164,9 @@ func (s *DockerSuite) TestAPIImagesImportBadSrc(c *check.C) { for _, te := range tt { res, _, err := request.Post(strings.Join([]string{"/images/create?fromSrc=", te.fromSrc}, ""), request.JSON) - c.Assert(err, check.IsNil) - c.Assert(res.StatusCode, checker.Equals, te.statusExp) - c.Assert(res.Header.Get("Content-Type"), checker.Equals, "application/json") + assert.NilError(c, err) + assert.Equal(c, res.StatusCode, te.statusExp) + assert.Equal(c, res.Header.Get("Content-Type"), "application/json") } } @@ -176,10 +176,10 @@ func (s *DockerSuite) TestAPIImagesSearchJSONContentType(c *check.C) { testRequires(c, Network) res, b, err := request.Get("/images/search?term=test", request.JSON) - c.Assert(err, check.IsNil) + assert.NilError(c, err) b.Close() - c.Assert(res.StatusCode, checker.Equals, http.StatusOK) - c.Assert(res.Header.Get("Content-Type"), checker.Equals, "application/json") + assert.Equal(c, res.StatusCode, http.StatusOK) + assert.Equal(c, res.Header.Get("Content-Type"), "application/json") } // Test case for 30027: image size reported as -1 in v1.12 client against v1.13 daemon. @@ -189,20 +189,20 @@ func (s *DockerSuite) TestAPIImagesSizeCompatibility(c *check.C) { defer apiclient.Close() images, err := apiclient.ImageList(context.Background(), types.ImageListOptions{}) - c.Assert(err, checker.IsNil) - c.Assert(len(images), checker.Not(checker.Equals), 0) + assert.NilError(c, err) + assert.Assert(c, len(images) != 0) for _, image := range images { - c.Assert(image.Size, checker.Not(checker.Equals), int64(-1)) + assert.Assert(c, image.Size != int64(-1)) } apiclient, err = client.NewClientWithOpts(client.FromEnv, client.WithVersion("v1.24")) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) defer apiclient.Close() v124Images, err := apiclient.ImageList(context.Background(), types.ImageListOptions{}) - c.Assert(err, checker.IsNil) - c.Assert(len(v124Images), checker.Not(checker.Equals), 0) + assert.NilError(c, err) + assert.Assert(c, len(v124Images) != 0) for _, image := range v124Images { - c.Assert(image.Size, checker.Not(checker.Equals), int64(-1)) + assert.Assert(c, image.Size != int64(-1)) } } diff --git a/components/engine/integration-cli/docker_api_inspect_test.go b/components/engine/integration-cli/docker_api_inspect_test.go index 5c452db329..cc0fbc3205 100644 --- a/components/engine/integration-cli/docker_api_inspect_test.go +++ b/components/engine/integration-cli/docker_api_inspect_test.go @@ -8,7 +8,6 @@ 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/checker" "github.com/go-check/check" "gotest.tools/assert" is "gotest.tools/assert/cmp" @@ -45,16 +44,16 @@ func (s *DockerSuite) TestInspectAPIContainerResponse(c *check.C) { var inspectJSON map[string]interface{} err := json.Unmarshal(body, &inspectJSON) - c.Assert(err, checker.IsNil, check.Commentf("Unable to unmarshal body for version %s", cs.version)) + assert.NilError(c, err, "Unable to unmarshal body for version %s", cs.version) for _, key := range cs.keys { _, ok := inspectJSON[key] - c.Check(ok, checker.True, check.Commentf("%s does not exist in response for version %s", key, cs.version)) + assert.Check(c, ok, "%s does not exist in response for version %s", key, cs.version) } //Issue #6830: type not properly converted to JSON/back _, ok := inspectJSON["Path"].(bool) - c.Assert(ok, checker.False, check.Commentf("Path of `true` should not be converted to boolean `true` via JSON marshalling")) + assert.Assert(c, !ok, "Path of `true` should not be converted to boolean `true` via JSON marshalling") } } @@ -71,13 +70,13 @@ func (s *DockerSuite) TestInspectAPIContainerVolumeDriverLegacy(c *check.C) { var inspectJSON map[string]interface{} err := json.Unmarshal(body, &inspectJSON) - c.Assert(err, checker.IsNil, check.Commentf("Unable to unmarshal body for version %s", version)) + assert.NilError(c, err, "Unable to unmarshal body for version %s", version) config, ok := inspectJSON["Config"] - c.Assert(ok, checker.True, check.Commentf("Unable to find 'Config'")) + assert.Assert(c, ok, "Unable to find 'Config'") cfg := config.(map[string]interface{}) _, ok = cfg["VolumeDriver"] - c.Assert(ok, checker.True, check.Commentf("API version %s expected to include VolumeDriver in 'Config'", version)) + assert.Assert(c, ok, "API version %s expected to include VolumeDriver in 'Config'", version) } } @@ -90,31 +89,31 @@ func (s *DockerSuite) TestInspectAPIContainerVolumeDriver(c *check.C) { var inspectJSON map[string]interface{} err := json.Unmarshal(body, &inspectJSON) - c.Assert(err, checker.IsNil, check.Commentf("Unable to unmarshal body for version 1.25")) + assert.NilError(c, err, "Unable to unmarshal body for version 1.25") config, ok := inspectJSON["Config"] - c.Assert(ok, checker.True, check.Commentf("Unable to find 'Config'")) + assert.Assert(c, ok, "Unable to find 'Config'") cfg := config.(map[string]interface{}) _, ok = cfg["VolumeDriver"] - c.Assert(ok, checker.False, check.Commentf("API version 1.25 expected to not include VolumeDriver in 'Config'")) + assert.Assert(c, !ok, "API version 1.25 expected to not include VolumeDriver in 'Config'") config, ok = inspectJSON["HostConfig"] - c.Assert(ok, checker.True, check.Commentf("Unable to find 'HostConfig'")) + assert.Assert(c, ok, "Unable to find 'HostConfig'") cfg = config.(map[string]interface{}) _, ok = cfg["VolumeDriver"] - c.Assert(ok, checker.True, check.Commentf("API version 1.25 expected to include VolumeDriver in 'HostConfig'")) + assert.Assert(c, ok, "API version 1.25 expected to include VolumeDriver in 'HostConfig'") } func (s *DockerSuite) TestInspectAPIImageResponse(c *check.C) { dockerCmd(c, "tag", "busybox:latest", "busybox:mytag") cli, err := client.NewClientWithOpts(client.FromEnv) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) defer cli.Close() imageJSON, _, err := cli.ImageInspectWithRaw(context.Background(), "busybox") - c.Assert(err, checker.IsNil) + assert.NilError(c, err) - c.Assert(imageJSON.RepoTags, checker.HasLen, 2) + assert.Check(c, len(imageJSON.RepoTags) == 2) assert.Check(c, is.Contains(imageJSON.RepoTags, "busybox:latest")) assert.Check(c, is.Contains(imageJSON.RepoTags, "busybox:mytag")) } @@ -133,13 +132,13 @@ func (s *DockerSuite) TestInspectAPIEmptyFieldsInConfigPre121(c *check.C) { var inspectJSON map[string]interface{} err := json.Unmarshal(body, &inspectJSON) - c.Assert(err, checker.IsNil, check.Commentf("Unable to unmarshal body for version %s", version)) + assert.NilError(c, err, "Unable to unmarshal body for version %s", version) config, ok := inspectJSON["Config"] - c.Assert(ok, checker.True, check.Commentf("Unable to find 'Config'")) + assert.Assert(c, ok, "Unable to find 'Config'") cfg := config.(map[string]interface{}) for _, f := range []string{"MacAddress", "NetworkDisabled", "ExposedPorts"} { _, ok := cfg[f] - c.Check(ok, checker.True, check.Commentf("API version %s expected to include %s in 'Config'", version, f)) + assert.Check(c, ok, "API version %s expected to include %s in 'Config'", version, f) } } } @@ -155,10 +154,10 @@ func (s *DockerSuite) TestInspectAPIBridgeNetworkSettings120(c *check.C) { var inspectJSON v1p20.ContainerJSON err := json.Unmarshal(body, &inspectJSON) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) settings := inspectJSON.NetworkSettings - c.Assert(settings.IPAddress, checker.Not(checker.HasLen), 0) + assert.Assert(c, len(settings.IPAddress) != 0) } func (s *DockerSuite) TestInspectAPIBridgeNetworkSettings121(c *check.C) { @@ -172,10 +171,10 @@ func (s *DockerSuite) TestInspectAPIBridgeNetworkSettings121(c *check.C) { var inspectJSON types.ContainerJSON err := json.Unmarshal(body, &inspectJSON) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) settings := inspectJSON.NetworkSettings - c.Assert(settings.IPAddress, checker.Not(checker.HasLen), 0) - c.Assert(settings.Networks["bridge"], checker.Not(checker.IsNil)) - c.Assert(settings.IPAddress, checker.Equals, settings.Networks["bridge"].IPAddress) + assert.Assert(c, len(settings.IPAddress) != 0) + assert.Assert(c, settings.Networks["bridge"] != nil) + assert.Equal(c, settings.IPAddress, settings.Networks["bridge"].IPAddress) } diff --git a/components/engine/integration-cli/docker_api_logs_test.go b/components/engine/integration-cli/docker_api_logs_test.go index 2e5bd724f3..62a48f5ebe 100644 --- a/components/engine/integration-cli/docker_api_logs_test.go +++ b/components/engine/integration-cli/docker_api_logs_test.go @@ -14,16 +14,16 @@ import ( "github.com/docker/docker/api/types" "github.com/docker/docker/client" - "github.com/docker/docker/integration-cli/checker" "github.com/docker/docker/internal/test/request" "github.com/docker/docker/pkg/stdcopy" "github.com/go-check/check" + "gotest.tools/assert" ) func (s *DockerSuite) TestLogsAPIWithStdout(c *check.C) { out, _ := dockerCmd(c, "run", "-d", "-t", "busybox", "/bin/sh", "-c", "while true; do echo hello; sleep 1; done") id := strings.TrimSpace(out) - c.Assert(waitRun(id), checker.IsNil) + assert.NilError(c, waitRun(id)) type logOut struct { out string @@ -32,8 +32,8 @@ func (s *DockerSuite) TestLogsAPIWithStdout(c *check.C) { chLog := make(chan logOut) res, body, err := request.Get(fmt.Sprintf("/containers/%s/logs?follow=1&stdout=1×tamps=1", id)) - c.Assert(err, checker.IsNil) - c.Assert(res.StatusCode, checker.Equals, http.StatusOK) + assert.NilError(c, err) + assert.Equal(c, res.StatusCode, http.StatusOK) go func() { defer body.Close() @@ -47,7 +47,7 @@ func (s *DockerSuite) TestLogsAPIWithStdout(c *check.C) { select { case l := <-chLog: - c.Assert(l.err, checker.IsNil) + assert.NilError(c, l.err) if !strings.HasSuffix(l.out, "hello") { c.Fatalf("expected log output to container 'hello', but it does not") } @@ -60,12 +60,11 @@ func (s *DockerSuite) TestLogsAPINoStdoutNorStderr(c *check.C) { name := "logs_test" dockerCmd(c, "run", "-d", "-t", "--name", name, "busybox", "/bin/sh") cli, err := client.NewClientWithOpts(client.FromEnv) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) defer cli.Close() _, err = cli.ContainerLogs(context.Background(), name, types.ContainerLogsOptions{}) - expected := "Bad parameters: you must choose at least one stream" - c.Assert(err.Error(), checker.Contains, expected) + assert.ErrorContains(c, err, "Bad parameters: you must choose at least one stream") } // Regression test for #12704 @@ -76,7 +75,7 @@ func (s *DockerSuite) TestLogsAPIFollowEmptyOutput(c *check.C) { _, body, err := request.Get(fmt.Sprintf("/containers/%s/logs?follow=1&stdout=1&stderr=1&tail=all", name)) t1 := time.Now() - c.Assert(err, checker.IsNil) + assert.NilError(c, err) body.Close() elapsed := t1.Sub(t0).Seconds() if elapsed > 20.0 { @@ -87,19 +86,19 @@ func (s *DockerSuite) TestLogsAPIFollowEmptyOutput(c *check.C) { func (s *DockerSuite) TestLogsAPIContainerNotFound(c *check.C) { name := "nonExistentContainer" resp, _, err := request.Get(fmt.Sprintf("/containers/%s/logs?follow=1&stdout=1&stderr=1&tail=all", name)) - c.Assert(err, checker.IsNil) - c.Assert(resp.StatusCode, checker.Equals, http.StatusNotFound) + assert.NilError(c, err) + assert.Equal(c, resp.StatusCode, http.StatusNotFound) } func (s *DockerSuite) TestLogsAPIUntilFutureFollow(c *check.C) { testRequires(c, DaemonIsLinux) name := "logsuntilfuturefollow" dockerCmd(c, "run", "-d", "--name", name, "busybox", "/bin/sh", "-c", "while true; do date +%s; sleep 1; done") - c.Assert(waitRun(name), checker.IsNil) + assert.NilError(c, waitRun(name)) untilSecs := 5 untilDur, err := time.ParseDuration(fmt.Sprintf("%ds", untilSecs)) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) until := daemonTime(c).Add(untilDur) client, err := client.NewClientWithOpts(client.FromEnv) @@ -109,7 +108,7 @@ func (s *DockerSuite) TestLogsAPIUntilFutureFollow(c *check.C) { cfg := types.ContainerLogsOptions{Until: until.Format(time.RFC3339Nano), Follow: true, ShowStdout: true, Timestamps: true} reader, err := client.ContainerLogs(context.Background(), name, cfg) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) type logOut struct { out string @@ -138,10 +137,10 @@ func (s *DockerSuite) TestLogsAPIUntilFutureFollow(c *check.C) { for i := 0; i < untilSecs; i++ { select { case l := <-chLog: - c.Assert(l.err, checker.IsNil) + assert.NilError(c, l.err) i, err := strconv.ParseInt(strings.Split(l.out, " ")[1], 10, 64) - c.Assert(err, checker.IsNil) - c.Assert(time.Unix(i, 0).UnixNano(), checker.LessOrEqualThan, until.UnixNano()) + assert.NilError(c, err) + assert.Assert(c, time.Unix(i, 0).UnixNano() <= until.UnixNano()) case <-time.After(20 * time.Second): c.Fatal("timeout waiting for logs to exit") } @@ -160,22 +159,22 @@ func (s *DockerSuite) TestLogsAPIUntil(c *check.C) { extractBody := func(c *check.C, cfg types.ContainerLogsOptions) []string { reader, err := client.ContainerLogs(context.Background(), name, cfg) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) actualStdout := new(bytes.Buffer) actualStderr := ioutil.Discard _, err = stdcopy.StdCopy(actualStdout, actualStderr, reader) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) return strings.Split(actualStdout.String(), "\n") } // Get timestamp of second log line allLogs := extractBody(c, types.ContainerLogsOptions{Timestamps: true, ShowStdout: true}) - c.Assert(len(allLogs), checker.GreaterOrEqualThan, 3) + assert.Assert(c, len(allLogs) >= 3) t, err := time.Parse(time.RFC3339Nano, strings.Split(allLogs[1], " ")[0]) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) until := t.Format(time.RFC3339Nano) // Get logs until the timestamp of second line, i.e. first two lines @@ -183,7 +182,7 @@ func (s *DockerSuite) TestLogsAPIUntil(c *check.C) { // Ensure log lines after cut-off are excluded logsString := strings.Join(logs, "\n") - c.Assert(logsString, checker.Not(checker.Contains), "log3", check.Commentf("unexpected log message returned, until=%v", until)) + assert.Assert(c, !strings.Contains(logsString, "log3"), "unexpected log message returned, until=%v", until) } func (s *DockerSuite) TestLogsAPIUntilDefaultValue(c *check.C) { @@ -197,12 +196,12 @@ func (s *DockerSuite) TestLogsAPIUntilDefaultValue(c *check.C) { extractBody := func(c *check.C, cfg types.ContainerLogsOptions) []string { reader, err := client.ContainerLogs(context.Background(), name, cfg) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) actualStdout := new(bytes.Buffer) actualStderr := ioutil.Discard _, err = stdcopy.StdCopy(actualStdout, actualStderr, reader) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) return strings.Split(actualStdout.String(), "\n") } @@ -212,5 +211,5 @@ func (s *DockerSuite) TestLogsAPIUntilDefaultValue(c *check.C) { // Test with default value specified and parameter omitted defaultLogs := extractBody(c, types.ContainerLogsOptions{Timestamps: true, ShowStdout: true, Until: "0"}) - c.Assert(defaultLogs, checker.DeepEquals, allLogs) + assert.DeepEqual(c, defaultLogs, allLogs) } diff --git a/components/engine/integration-cli/docker_api_network_test.go b/components/engine/integration-cli/docker_api_network_test.go index 9ec2ba90e8..3e854c78e1 100644 --- a/components/engine/integration-cli/docker_api_network_test.go +++ b/components/engine/integration-cli/docker_api_network_test.go @@ -12,9 +12,9 @@ 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/checker" "github.com/docker/docker/internal/test/request" "github.com/go-check/check" + "gotest.tools/assert" ) func (s *DockerSuite) TestAPINetworkGetDefaults(c *check.C) { @@ -22,7 +22,7 @@ func (s *DockerSuite) TestAPINetworkGetDefaults(c *check.C) { // By default docker daemon creates 3 networks. check if they are present defaults := []string{"bridge", "host", "none"} for _, nn := range defaults { - c.Assert(isNetworkAvailable(c, nn), checker.Equals, true) + assert.Assert(c, isNetworkAvailable(c, nn)) } } @@ -44,7 +44,7 @@ func (s *DockerSuite) TestAPINetworkCreateCheckDuplicate(c *check.C) { // Creating a new network first createNetwork(c, configOnCheck, http.StatusCreated) - c.Assert(isNetworkAvailable(c, name), checker.Equals, true) + assert.Assert(c, isNetworkAvailable(c, name)) // Creating another network with same name and CheckDuplicate must fail isOlderAPI := versions.LessThan(testEnv.DaemonAPIVersion(), "1.34") @@ -67,14 +67,14 @@ func (s *DockerSuite) TestAPINetworkCreateCheckDuplicate(c *check.C) { func (s *DockerSuite) TestAPINetworkFilter(c *check.C) { testRequires(c, DaemonIsLinux) nr := getNetworkResource(c, getNetworkIDByName(c, "bridge")) - c.Assert(nr.Name, checker.Equals, "bridge") + assert.Equal(c, nr.Name, "bridge") } func (s *DockerSuite) TestAPINetworkInspectBridge(c *check.C) { testRequires(c, DaemonIsLinux) // Inspect default bridge network nr := getNetworkResource(c, "bridge") - c.Assert(nr.Name, checker.Equals, "bridge") + 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") @@ -83,16 +83,17 @@ func (s *DockerSuite) TestAPINetworkInspectBridge(c *check.C) { // inspect default bridge network again and make sure the container is connected nr = getNetworkResource(c, nr.ID) - c.Assert(nr.Driver, checker.Equals, "bridge") - c.Assert(nr.Scope, checker.Equals, "local") - c.Assert(nr.Internal, checker.Equals, false) - c.Assert(nr.EnableIPv6, checker.Equals, false) - c.Assert(nr.IPAM.Driver, checker.Equals, "default") - c.Assert(nr.Containers[containerID], checker.NotNil) + assert.Equal(c, nr.Driver, "bridge") + assert.Equal(c, nr.Scope, "local") + assert.Equal(c, nr.Internal, false) + assert.Equal(c, nr.EnableIPv6, false) + assert.Equal(c, nr.IPAM.Driver, "default") + _, ok := nr.Containers[containerID] + assert.Assert(c, ok) ip, _, err := net.ParseCIDR(nr.Containers[containerID].IPv4Address) - c.Assert(err, checker.IsNil) - c.Assert(ip.String(), checker.Equals, containerIP) + assert.NilError(c, err) + assert.Equal(c, ip.String(), containerIP) } func (s *DockerSuite) TestAPINetworkInspectUserDefinedNetwork(c *check.C) { @@ -111,19 +112,19 @@ func (s *DockerSuite) TestAPINetworkInspectUserDefinedNetwork(c *check.C) { }, } id0 := createNetwork(c, config, http.StatusCreated) - c.Assert(isNetworkAvailable(c, "br0"), checker.Equals, true) + assert.Assert(c, isNetworkAvailable(c, "br0")) nr := getNetworkResource(c, id0) - c.Assert(len(nr.IPAM.Config), checker.Equals, 1) - c.Assert(nr.IPAM.Config[0].Subnet, checker.Equals, "172.28.0.0/16") - c.Assert(nr.IPAM.Config[0].IPRange, checker.Equals, "172.28.5.0/24") - c.Assert(nr.IPAM.Config[0].Gateway, checker.Equals, "172.28.5.254") - c.Assert(nr.Options["foo"], checker.Equals, "bar") - c.Assert(nr.Options["opts"], checker.Equals, "dopts") + assert.Equal(c, len(nr.IPAM.Config), 1) + assert.Equal(c, nr.IPAM.Config[0].Subnet, "172.28.0.0/16") + assert.Equal(c, nr.IPAM.Config[0].IPRange, "172.28.5.0/24") + assert.Equal(c, nr.IPAM.Config[0].Gateway, "172.28.5.254") + assert.Equal(c, nr.Options["foo"], "bar") + assert.Equal(c, nr.Options["opts"], "dopts") // delete the network and make sure it is deleted deleteNetwork(c, id0, true) - c.Assert(isNetworkAvailable(c, "br0"), checker.Equals, false) + assert.Assert(c, !isNetworkAvailable(c, "br0")) } func (s *DockerSuite) TestAPINetworkConnectDisconnect(c *check.C) { @@ -135,9 +136,9 @@ func (s *DockerSuite) TestAPINetworkConnectDisconnect(c *check.C) { } id := createNetwork(c, config, http.StatusCreated) nr := getNetworkResource(c, id) - c.Assert(nr.Name, checker.Equals, name) - c.Assert(nr.ID, checker.Equals, id) - c.Assert(len(nr.Containers), checker.Equals, 0) + assert.Equal(c, nr.Name, name) + assert.Equal(c, nr.ID, id) + assert.Equal(c, len(nr.Containers), 0) // run a container out, _ := dockerCmd(c, "run", "-d", "--name", "test", "busybox", "top") @@ -148,20 +149,21 @@ func (s *DockerSuite) TestAPINetworkConnectDisconnect(c *check.C) { // inspect the network to make sure container is connected nr = getNetworkResource(c, nr.ID) - c.Assert(len(nr.Containers), checker.Equals, 1) - c.Assert(nr.Containers[containerID], checker.NotNil) + assert.Equal(c, len(nr.Containers), 1) + _, ok := nr.Containers[containerID] + assert.Assert(c, ok) // check if container IP matches network inspect ip, _, err := net.ParseCIDR(nr.Containers[containerID].IPv4Address) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) containerIP := findContainerIP(c, "test", "testnetwork") - c.Assert(ip.String(), checker.Equals, containerIP) + assert.Equal(c, ip.String(), containerIP) // disconnect container from the network disconnectNetwork(c, nr.ID, containerID) nr = getNetworkResource(c, nr.ID) - c.Assert(nr.Name, checker.Equals, name) - c.Assert(len(nr.Containers), checker.Equals, 0) + assert.Equal(c, nr.Name, name) + assert.Equal(c, len(nr.Containers), 0) // delete the network deleteNetwork(c, nr.ID, true) @@ -182,7 +184,7 @@ func (s *DockerSuite) TestAPINetworkIPAMMultipleBridgeNetworks(c *check.C) { }, } id0 := createNetwork(c, config0, http.StatusCreated) - c.Assert(isNetworkAvailable(c, "test0"), checker.Equals, true) + assert.Assert(c, isNetworkAvailable(c, "test0")) ipam1 := &network.IPAM{ Driver: "default", @@ -201,7 +203,7 @@ func (s *DockerSuite) TestAPINetworkIPAMMultipleBridgeNetworks(c *check.C) { } else { createNetwork(c, config1, http.StatusForbidden) } - c.Assert(isNetworkAvailable(c, "test1"), checker.Equals, false) + assert.Assert(c, !isNetworkAvailable(c, "test1")) ipam2 := &network.IPAM{ Driver: "default", @@ -216,20 +218,20 @@ func (s *DockerSuite) TestAPINetworkIPAMMultipleBridgeNetworks(c *check.C) { }, } createNetwork(c, config2, http.StatusCreated) - c.Assert(isNetworkAvailable(c, "test2"), checker.Equals, true) + assert.Assert(c, isNetworkAvailable(c, "test2")) // remove test0 and retry to create test1 deleteNetwork(c, id0, true) createNetwork(c, config1, http.StatusCreated) - c.Assert(isNetworkAvailable(c, "test1"), checker.Equals, true) + assert.Assert(c, isNetworkAvailable(c, "test1")) // for networks w/o ipam specified, docker will choose proper non-overlapping subnets createNetwork(c, types.NetworkCreateRequest{Name: "test3"}, http.StatusCreated) - c.Assert(isNetworkAvailable(c, "test3"), checker.Equals, true) + assert.Assert(c, isNetworkAvailable(c, "test3")) createNetwork(c, types.NetworkCreateRequest{Name: "test4"}, http.StatusCreated) - c.Assert(isNetworkAvailable(c, "test4"), checker.Equals, true) + assert.Assert(c, isNetworkAvailable(c, "test4")) createNetwork(c, types.NetworkCreateRequest{Name: "test5"}, http.StatusCreated) - c.Assert(isNetworkAvailable(c, "test5"), checker.Equals, true) + assert.Assert(c, isNetworkAvailable(c, "test5")) for i := 1; i < 6; i++ { deleteNetwork(c, fmt.Sprintf("test%d", i), true) @@ -267,13 +269,13 @@ func createDeletePredefinedNetwork(c *check.C, name string) { func isNetworkAvailable(c *check.C, name string) bool { resp, body, err := request.Get("/networks") - c.Assert(err, checker.IsNil) + assert.NilError(c, err) defer resp.Body.Close() - c.Assert(resp.StatusCode, checker.Equals, http.StatusOK) + assert.Equal(c, resp.StatusCode, http.StatusOK) var nJSON []types.NetworkResource err = json.NewDecoder(body).Decode(&nJSON) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) for _, n := range nJSON { if n.Name == name { @@ -290,16 +292,16 @@ func getNetworkIDByName(c *check.C, name string) string { ) filterArgs.Add("name", name) filterJSON, err := filters.ToJSON(filterArgs) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) v.Set("filters", filterJSON) resp, body, err := request.Get("/networks?" + v.Encode()) - c.Assert(resp.StatusCode, checker.Equals, http.StatusOK) - c.Assert(err, checker.IsNil) + assert.Equal(c, resp.StatusCode, http.StatusOK) + assert.NilError(c, err) var nJSON []types.NetworkResource err = json.NewDecoder(body).Decode(&nJSON) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) var res string for _, n := range nJSON { // Find exact match @@ -307,37 +309,37 @@ func getNetworkIDByName(c *check.C, name string) string { res = n.ID } } - c.Assert(res, checker.Not(checker.Equals), "") + assert.Assert(c, res != "") return res } func getNetworkResource(c *check.C, id string) *types.NetworkResource { _, obj, err := request.Get("/networks/" + id) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) nr := types.NetworkResource{} err = json.NewDecoder(obj).Decode(&nr) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) return &nr } func createNetwork(c *check.C, config types.NetworkCreateRequest, expectedStatusCode int) string { resp, body, err := request.Post("/networks/create", request.JSONBody(config)) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) defer resp.Body.Close() if expectedStatusCode >= 0 { - c.Assert(resp.StatusCode, checker.Equals, expectedStatusCode) + assert.Equal(c, resp.StatusCode, expectedStatusCode) } else { - c.Assert(resp.StatusCode, checker.Not(checker.Equals), -expectedStatusCode) + assert.Assert(c, resp.StatusCode != -expectedStatusCode) } if expectedStatusCode == http.StatusCreated || expectedStatusCode < 0 { var nr types.NetworkCreateResponse err = json.NewDecoder(body).Decode(&nr) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) return nr.ID } @@ -350,8 +352,8 @@ func connectNetwork(c *check.C, nid, cid string) { } resp, _, err := request.Post("/networks/"+nid+"/connect", request.JSONBody(config)) - c.Assert(resp.StatusCode, checker.Equals, http.StatusOK) - c.Assert(err, checker.IsNil) + assert.Equal(c, resp.StatusCode, http.StatusOK) + assert.NilError(c, err) } func disconnectNetwork(c *check.C, nid, cid string) { @@ -360,17 +362,17 @@ func disconnectNetwork(c *check.C, nid, cid string) { } resp, _, err := request.Post("/networks/"+nid+"/disconnect", request.JSONBody(config)) - c.Assert(resp.StatusCode, checker.Equals, http.StatusOK) - c.Assert(err, checker.IsNil) + assert.Equal(c, resp.StatusCode, http.StatusOK) + assert.NilError(c, err) } func deleteNetwork(c *check.C, id string, shouldSucceed bool) { resp, _, err := request.Delete("/networks/" + id) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) defer resp.Body.Close() if !shouldSucceed { - c.Assert(resp.StatusCode, checker.Not(checker.Equals), http.StatusOK) + assert.Assert(c, resp.StatusCode != http.StatusOK) return } - c.Assert(resp.StatusCode, checker.Equals, http.StatusNoContent) + assert.Equal(c, resp.StatusCode, http.StatusNoContent) } diff --git a/components/engine/integration-cli/docker_api_stats_test.go b/components/engine/integration-cli/docker_api_stats_test.go index d715cc67f5..63ee9231fe 100644 --- a/components/engine/integration-cli/docker_api_stats_test.go +++ b/components/engine/integration-cli/docker_api_stats_test.go @@ -15,9 +15,9 @@ import ( "github.com/docker/docker/api/types" "github.com/docker/docker/api/types/versions" "github.com/docker/docker/client" - "github.com/docker/docker/integration-cli/checker" "github.com/docker/docker/internal/test/request" "github.com/go-check/check" + "gotest.tools/assert" ) var expectedNetworkInterfaceStats = strings.Split("rx_bytes rx_dropped rx_errors rx_packets tx_bytes tx_dropped tx_errors tx_packets", " ") @@ -26,15 +26,16 @@ func (s *DockerSuite) TestAPIStatsNoStreamGetCpu(c *check.C) { out, _ := dockerCmd(c, "run", "-d", "busybox", "/bin/sh", "-c", "while true;usleep 100; do echo 'Hello'; done") id := strings.TrimSpace(out) - c.Assert(waitRun(id), checker.IsNil) + assert.NilError(c, waitRun(id)) resp, body, err := request.Get(fmt.Sprintf("/containers/%s/stats?stream=false", id)) - c.Assert(err, checker.IsNil) - c.Assert(resp.StatusCode, checker.Equals, http.StatusOK) - c.Assert(resp.Header.Get("Content-Type"), checker.Equals, "application/json") + assert.NilError(c, err) + assert.Equal(c, resp.StatusCode, http.StatusOK) + assert.Equal(c, resp.Header.Get("Content-Type"), "application/json") + assert.Equal(c, resp.Header.Get("Content-Type"), "application/json") var v *types.Stats err = json.NewDecoder(body).Decode(&v) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) body.Close() var cpuPercent = 0.0 @@ -58,7 +59,7 @@ func (s *DockerSuite) TestAPIStatsNoStreamGetCpu(c *check.C) { } } - c.Assert(cpuPercent, check.Not(checker.Equals), 0.0, check.Commentf("docker stats with no-stream get cpu usage failed: was %v", cpuPercent)) + assert.Assert(c, cpuPercent != 0.0, "docker stats with no-stream get cpu usage failed: was %v", cpuPercent) } func (s *DockerSuite) TestAPIStatsStoppedContainerInGoroutines(c *check.C) { @@ -67,10 +68,10 @@ func (s *DockerSuite) TestAPIStatsStoppedContainerInGoroutines(c *check.C) { getGoRoutines := func() int { _, body, err := request.Get(fmt.Sprintf("/info")) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) info := types.Info{} err = json.NewDecoder(body).Decode(&info) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) body.Close() return info.NGoroutines } @@ -78,14 +79,14 @@ func (s *DockerSuite) TestAPIStatsStoppedContainerInGoroutines(c *check.C) { // When the HTTP connection is closed, the number of goroutines should not increase. routines := getGoRoutines() _, body, err := request.Get(fmt.Sprintf("/containers/%s/stats", id)) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) body.Close() t := time.After(30 * time.Second) for { select { case <-t: - c.Assert(getGoRoutines(), checker.LessOrEqualThan, routines) + assert.Assert(c, getGoRoutines() <= routines) return default: if n := getGoRoutines(); n <= routines { @@ -101,7 +102,7 @@ func (s *DockerSuite) TestAPIStatsNetworkStats(c *check.C) { out := runSleepingContainer(c) id := strings.TrimSpace(out) - c.Assert(waitRun(id), checker.IsNil) + assert.NilError(c, waitRun(id)) // Retrieve the container address net := "bridge" @@ -141,7 +142,7 @@ func (s *DockerSuite) TestAPIStatsNetworkStats(c *check.C) { err = err2 } } - c.Assert(err, checker.IsNil) + assert.NilError(c, err) pingouts := string(pingout[:]) nwStatsPost := getNetworkStats(c, id) for _, v := range nwStatsPost { @@ -157,10 +158,8 @@ func (s *DockerSuite) TestAPIStatsNetworkStats(c *check.C) { expRxPkts++ expTxPkts++ } - c.Assert(postTxPackets, checker.GreaterOrEqualThan, expTxPkts, - check.Commentf("Reported less TxPackets than expected. Expected >= %d. Found %d. %s", expTxPkts, postTxPackets, pingouts)) - c.Assert(postRxPackets, checker.GreaterOrEqualThan, expRxPkts, - check.Commentf("Reported less RxPackets than expected. Expected >= %d. Found %d. %s", expRxPkts, postRxPackets, pingouts)) + assert.Assert(c, postTxPackets >= expTxPkts, "Reported less TxPackets than expected. Expected >= %d. Found %d. %s", expTxPkts, postTxPackets, pingouts) + assert.Assert(c, postRxPackets >= expRxPkts, "Reported less RxPackets than expected. Expected >= %d. Found %d. %s", expRxPkts, postRxPackets, pingouts) } func (s *DockerSuite) TestAPIStatsNetworkStatsVersioning(c *check.C) { @@ -169,7 +168,7 @@ func (s *DockerSuite) TestAPIStatsNetworkStatsVersioning(c *check.C) { out := runSleepingContainer(c) id := strings.TrimSpace(out) - c.Assert(waitRun(id), checker.IsNil) + assert.NilError(c, waitRun(id)) wg := sync.WaitGroup{} for i := 17; i <= 21; i++ { @@ -179,11 +178,9 @@ func (s *DockerSuite) TestAPIStatsNetworkStatsVersioning(c *check.C) { apiVersion := fmt.Sprintf("v1.%d", i) statsJSONBlob := getVersionedStats(c, id, apiVersion) if versions.LessThan(apiVersion, "v1.21") { - c.Assert(jsonBlobHasLTv121NetworkStats(statsJSONBlob), checker.Equals, true, - check.Commentf("Stats JSON blob from API %s %#v does not look like a =v1.21 API stats structure", apiVersion, statsJSONBlob)) + assert.Assert(c, jsonBlobHasGTE121NetworkStats(statsJSONBlob), "Stats JSON blob from API %s %#v does not look like a >=v1.21 API stats structure", apiVersion, statsJSONBlob) } }(i) } @@ -194,10 +191,10 @@ func getNetworkStats(c *check.C, id string) map[string]types.NetworkStats { var st *types.StatsJSON _, body, err := request.Get(fmt.Sprintf("/containers/%s/stats?stream=false", id)) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) err = json.NewDecoder(body).Decode(&st) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) body.Close() return st.Networks @@ -211,11 +208,11 @@ func getVersionedStats(c *check.C, id string, apiVersion string) map[string]inte stats := make(map[string]interface{}) _, body, err := request.Get(fmt.Sprintf("/%s/containers/%s/stats?stream=false", apiVersion, id)) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) defer body.Close() err = json.NewDecoder(body).Decode(&stats) - c.Assert(err, checker.IsNil, check.Commentf("failed to decode stat: %s", err)) + assert.NilError(c, err, "failed to decode stat: %s", err) return stats } @@ -263,15 +260,15 @@ func jsonBlobHasGTE121NetworkStats(blob map[string]interface{}) bool { func (s *DockerSuite) TestAPIStatsContainerNotFound(c *check.C) { testRequires(c, DaemonIsLinux) cli, err := client.NewClientWithOpts(client.FromEnv) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) defer cli.Close() expected := "No such container: nonexistent" _, err = cli.ContainerStats(context.Background(), "nonexistent", true) - c.Assert(err.Error(), checker.Contains, expected) + assert.ErrorContains(c, err, expected) _, err = cli.ContainerStats(context.Background(), "nonexistent", false) - c.Assert(err.Error(), checker.Contains, expected) + assert.ErrorContains(c, err, expected) } func (s *DockerSuite) TestAPIStatsNoStreamConnectedContainers(c *check.C) { @@ -279,11 +276,11 @@ func (s *DockerSuite) TestAPIStatsNoStreamConnectedContainers(c *check.C) { out1 := runSleepingContainer(c) id1 := strings.TrimSpace(out1) - c.Assert(waitRun(id1), checker.IsNil) + assert.NilError(c, waitRun(id1)) out2 := runSleepingContainer(c, "--net", "container:"+id1) id2 := strings.TrimSpace(out2) - c.Assert(waitRun(id2), checker.IsNil) + assert.NilError(c, waitRun(id2)) ch := make(chan error, 1) go func() { @@ -307,7 +304,7 @@ func (s *DockerSuite) TestAPIStatsNoStreamConnectedContainers(c *check.C) { select { case err := <-ch: - c.Assert(err, checker.IsNil, check.Commentf("Error in stats Engine API: %v", err)) + assert.NilError(c, err, "Error in stats Engine API: %v", err) case <-time.After(15 * time.Second): c.Fatalf("Stats did not return after timeout") } diff --git a/components/engine/integration-cli/docker_api_swarm_service_test.go b/components/engine/integration-cli/docker_api_swarm_service_test.go index 9b6764a714..e58255820c 100644 --- a/components/engine/integration-cli/docker_api_swarm_service_test.go +++ b/components/engine/integration-cli/docker_api_swarm_service_test.go @@ -18,6 +18,7 @@ import ( testdaemon "github.com/docker/docker/internal/test/daemon" "github.com/go-check/check" "golang.org/x/sys/unix" + "gotest.tools/assert" "gotest.tools/icmd" ) @@ -45,18 +46,18 @@ func (s *DockerSwarmSuite) TestAPIServiceUpdatePort(c *check.C) { // Inspect the service and verify port mapping. updatedService := d.GetService(c, serviceID) - c.Assert(updatedService.Spec.EndpointSpec, check.NotNil) - c.Assert(len(updatedService.Spec.EndpointSpec.Ports), check.Equals, 1) - c.Assert(updatedService.Spec.EndpointSpec.Ports[0].TargetPort, check.Equals, uint32(8083)) - c.Assert(updatedService.Spec.EndpointSpec.Ports[0].PublishedPort, check.Equals, uint32(8082)) + assert.Assert(c, updatedService.Spec.EndpointSpec != nil) + assert.Equal(c, len(updatedService.Spec.EndpointSpec.Ports), 1) + assert.Equal(c, updatedService.Spec.EndpointSpec.Ports[0].TargetPort, uint32(8083)) + assert.Equal(c, updatedService.Spec.EndpointSpec.Ports[0].PublishedPort, uint32(8082)) } func (s *DockerSwarmSuite) TestAPISwarmServicesEmptyList(c *check.C) { d := s.AddDaemon(c, true, true) services := d.ListServices(c) - c.Assert(services, checker.NotNil) - c.Assert(len(services), checker.Equals, 0, check.Commentf("services: %#v", services)) + assert.Assert(c, services != nil) + assert.Assert(c, len(services) == 0, "services: %#v", services) } func (s *DockerSwarmSuite) TestAPISwarmServicesCreate(c *check.C) { @@ -74,14 +75,14 @@ func (s *DockerSwarmSuite) TestAPISwarmServicesCreate(c *check.C) { // insertDefaults inserts UpdateConfig when service is fetched by ID resp, _, err := client.ServiceInspectWithRaw(context.Background(), id, options) out := fmt.Sprintf("%+v", resp) - c.Assert(err, checker.IsNil) - c.Assert(out, checker.Contains, "UpdateConfig") + assert.NilError(c, err) + assert.Assert(c, strings.Contains(out, "UpdateConfig")) // insertDefaults inserts UpdateConfig when service is fetched by ID resp, _, err = client.ServiceInspectWithRaw(context.Background(), "top", options) out = fmt.Sprintf("%+v", resp) - c.Assert(err, checker.IsNil) - c.Assert(string(out), checker.Contains, "UpdateConfig") + assert.NilError(c, err) + assert.Assert(c, strings.Contains(out, "UpdateConfig")) service := d.GetService(c, id) instances = 5 @@ -155,7 +156,7 @@ func (s *DockerSwarmSuite) TestAPISwarmServicesUpdate(c *check.C) { // create a different tag for _, d := range daemons { out, err := d.Cmd("tag", image1, image2) - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) } // create service @@ -187,7 +188,7 @@ func (s *DockerSwarmSuite) TestAPISwarmServicesUpdate(c *check.C) { // Roll back to the previous version. This uses the CLI because // rollback used to be a client-side operation. out, err := daemons[0].Cmd("service", "update", "--detach", "--rollback", id) - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) // first batch waitAndAssert(c, defaultReconciliationTimeout, daemons[0].CheckRunningTaskImages, checker.DeepEquals, @@ -296,7 +297,7 @@ func (s *DockerSwarmSuite) TestAPISwarmServicesUpdateStartFirst(c *check.C) { // Roll back to the previous version. This uses the CLI because // rollback is a client-side operation. out, err := d.Cmd("service", "update", "--detach", "--rollback", id) - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) // first batch waitAndAssert(c, defaultReconciliationTimeout, d.CheckRunningTaskImages, checker.DeepEquals, @@ -336,12 +337,12 @@ func (s *DockerSwarmSuite) TestAPISwarmServicesFailedUpdate(c *check.C) { // should update 2 tasks and then pause waitAndAssert(c, defaultReconciliationTimeout, daemons[0].CheckServiceUpdateState(id), checker.Equals, swarm.UpdateStatePaused) v, _ := daemons[0].CheckServiceRunningTasks(id)(c) - c.Assert(v, checker.Equals, instances-2) + assert.Assert(c, v == instances-2) // Roll back to the previous version. This uses the CLI because // rollback used to be a client-side operation. out, err := daemons[0].Cmd("service", "update", "--detach", "--rollback", id) - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) waitAndAssert(c, defaultReconciliationTimeout, daemons[0].CheckRunningTaskImages, checker.DeepEquals, map[string]int{image1: instances}) @@ -366,7 +367,7 @@ func (s *DockerSwarmSuite) TestAPISwarmServiceConstraintRole(c *check.C) { tasks := daemons[0].GetServiceTasks(c, id) for _, task := range tasks { node := daemons[0].GetNode(c, task.NodeID) - c.Assert(node.Spec.Role, checker.Equals, swarm.NodeRoleWorker) + assert.Equal(c, node.Spec.Role, swarm.NodeRoleWorker) } //remove service daemons[0].RemoveService(c, id) @@ -380,7 +381,7 @@ func (s *DockerSwarmSuite) TestAPISwarmServiceConstraintRole(c *check.C) { // validate tasks are running on manager nodes for _, task := range tasks { node := daemons[0].GetNode(c, task.NodeID) - c.Assert(node.Spec.Role, checker.Equals, swarm.NodeRoleManager) + assert.Equal(c, node.Spec.Role, swarm.NodeRoleManager) } //remove service daemons[0].RemoveService(c, id) @@ -395,7 +396,7 @@ func (s *DockerSwarmSuite) TestAPISwarmServiceConstraintRole(c *check.C) { // validate tasks are not assigned to any node tasks = daemons[0].GetServiceTasks(c, id) for _, task := range tasks { - c.Assert(task.NodeID, checker.Equals, "") + assert.Equal(c, task.NodeID, "") } } @@ -408,7 +409,7 @@ func (s *DockerSwarmSuite) TestAPISwarmServiceConstraintLabel(c *check.C) { // wait for nodes ready waitAndAssert(c, 5*time.Second, daemons[0].CheckNodeReadyCount, checker.Equals, nodeCount) nodes := daemons[0].ListNodes(c) - c.Assert(len(nodes), checker.Equals, nodeCount) + assert.Equal(c, len(nodes), nodeCount) // add labels to nodes daemons[0].UpdateNode(c, nodes[0].ID, func(n *swarm.Node) { @@ -433,7 +434,7 @@ func (s *DockerSwarmSuite) TestAPISwarmServiceConstraintLabel(c *check.C) { tasks := daemons[0].GetServiceTasks(c, id) // validate all tasks are running on nodes[0] for _, task := range tasks { - c.Assert(task.NodeID, checker.Equals, nodes[0].ID) + assert.Assert(c, task.NodeID == nodes[0].ID) } //remove service daemons[0].RemoveService(c, id) @@ -446,7 +447,7 @@ func (s *DockerSwarmSuite) TestAPISwarmServiceConstraintLabel(c *check.C) { tasks = daemons[0].GetServiceTasks(c, id) // validate all tasks are NOT running on nodes[0] for _, task := range tasks { - c.Assert(task.NodeID, checker.Not(checker.Equals), nodes[0].ID) + assert.Assert(c, task.NodeID != nodes[0].ID) } //remove service daemons[0].RemoveService(c, id) @@ -460,7 +461,7 @@ func (s *DockerSwarmSuite) TestAPISwarmServiceConstraintLabel(c *check.C) { tasks = daemons[0].GetServiceTasks(c, id) // validate tasks are not assigned for _, task := range tasks { - c.Assert(task.NodeID, checker.Equals, "") + assert.Assert(c, task.NodeID == "") } //remove service daemons[0].RemoveService(c, id) @@ -478,7 +479,7 @@ func (s *DockerSwarmSuite) TestAPISwarmServiceConstraintLabel(c *check.C) { tasks = daemons[0].GetServiceTasks(c, id) // validate tasks are not assigned for _, task := range tasks { - c.Assert(task.NodeID, checker.Equals, "") + assert.Assert(c, task.NodeID == "") } // make nodes[1] fulfills the constraints daemons[0].UpdateNode(c, nodes[1].ID, func(n *swarm.Node) { @@ -490,7 +491,7 @@ func (s *DockerSwarmSuite) TestAPISwarmServiceConstraintLabel(c *check.C) { waitAndAssert(c, defaultReconciliationTimeout, daemons[0].CheckServiceRunningTasks(id), checker.Equals, instances) tasks = daemons[0].GetServiceTasks(c, id) for _, task := range tasks { - c.Assert(task.NodeID, checker.Equals, nodes[1].ID) + assert.Assert(c, task.NodeID == nodes[1].ID) } } @@ -503,7 +504,7 @@ func (s *DockerSwarmSuite) TestAPISwarmServicePlacementPrefs(c *check.C) { // wait for nodes ready waitAndAssert(c, 5*time.Second, daemons[0].CheckNodeReadyCount, checker.Equals, nodeCount) nodes := daemons[0].ListNodes(c) - c.Assert(len(nodes), checker.Equals, nodeCount) + assert.Equal(c, len(nodes), nodeCount) // add labels to nodes daemons[0].UpdateNode(c, nodes[0].ID, func(n *swarm.Node) { @@ -531,9 +532,9 @@ func (s *DockerSwarmSuite) TestAPISwarmServicePlacementPrefs(c *check.C) { for _, task := range tasks { tasksOnNode[task.NodeID]++ } - c.Assert(tasksOnNode[nodes[0].ID], checker.Equals, 2) - c.Assert(tasksOnNode[nodes[1].ID], checker.Equals, 1) - c.Assert(tasksOnNode[nodes[2].ID], checker.Equals, 1) + assert.Assert(c, tasksOnNode[nodes[0].ID] == 2) + assert.Assert(c, tasksOnNode[nodes[1].ID] == 1) + assert.Assert(c, tasksOnNode[nodes[2].ID] == 1) } func (s *DockerSwarmSuite) TestAPISwarmServicesStateReporting(c *check.C) { @@ -562,24 +563,24 @@ func (s *DockerSwarmSuite) TestAPISwarmServicesStateReporting(c *check.C) { } containers := getContainers() - c.Assert(containers, checker.HasLen, instances) + assert.Assert(c, len(containers) == instances) var toRemove string for i := range containers { toRemove = i } _, err := containers[toRemove].Cmd("stop", toRemove) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) waitAndAssert(c, defaultReconciliationTimeout, reducedCheck(sumAsIntegers, d1.CheckActiveContainerCount, d2.CheckActiveContainerCount, d3.CheckActiveContainerCount), checker.Equals, instances) containers2 := getContainers() - c.Assert(containers2, checker.HasLen, instances) + assert.Assert(c, len(containers2) == instances) for i := range containers { if i == toRemove { - c.Assert(containers2[i], checker.IsNil) + assert.Assert(c, containers2[i] == nil) } else { - c.Assert(containers2[i], checker.NotNil) + assert.Assert(c, containers2[i] != nil) } } @@ -590,22 +591,22 @@ func (s *DockerSwarmSuite) TestAPISwarmServicesStateReporting(c *check.C) { // try with killing process outside of docker pidStr, err := containers[toRemove].Cmd("inspect", "-f", "{{.State.Pid}}", toRemove) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) pid, err := strconv.Atoi(strings.TrimSpace(pidStr)) - c.Assert(err, checker.IsNil) - c.Assert(unix.Kill(pid, unix.SIGKILL), checker.IsNil) + assert.NilError(c, err) + assert.NilError(c, unix.Kill(pid, unix.SIGKILL)) time.Sleep(time.Second) // give some time to handle the signal waitAndAssert(c, defaultReconciliationTimeout, reducedCheck(sumAsIntegers, d1.CheckActiveContainerCount, d2.CheckActiveContainerCount, d3.CheckActiveContainerCount), checker.Equals, instances) containers2 = getContainers() - c.Assert(containers2, checker.HasLen, instances) + assert.Assert(c, len(containers2) == instances) for i := range containers { if i == toRemove { - c.Assert(containers2[i], checker.IsNil) + assert.Assert(c, containers2[i] == nil) } else { - c.Assert(containers2[i], checker.NotNil) + assert.Assert(c, containers2[i] != nil) } } } diff --git a/components/engine/integration-cli/docker_api_swarm_test.go b/components/engine/integration-cli/docker_api_swarm_test.go index fecbf1e860..e7d1b98332 100644 --- a/components/engine/integration-cli/docker_api_swarm_test.go +++ b/components/engine/integration-cli/docker_api_swarm_test.go @@ -37,21 +37,21 @@ func (s *DockerSwarmSuite) TestAPISwarmInit(c *check.C) { // todo: should find a better way to verify that components are running than /info d1 := s.AddDaemon(c, true, true) info := d1.SwarmInfo(c) - c.Assert(info.ControlAvailable, checker.True) - c.Assert(info.LocalNodeState, checker.Equals, swarm.LocalNodeStateActive) - c.Assert(info.Cluster.RootRotationInProgress, checker.False) + assert.Equal(c, info.ControlAvailable, true) + assert.Equal(c, info.LocalNodeState, swarm.LocalNodeStateActive) + assert.Equal(c, info.Cluster.RootRotationInProgress, false) d2 := s.AddDaemon(c, true, false) info = d2.SwarmInfo(c) - c.Assert(info.ControlAvailable, checker.False) - c.Assert(info.LocalNodeState, checker.Equals, swarm.LocalNodeStateActive) + assert.Equal(c, info.ControlAvailable, false) + assert.Equal(c, info.LocalNodeState, swarm.LocalNodeStateActive) // Leaving cluster - c.Assert(d2.SwarmLeave(c, false), checker.IsNil) + assert.NilError(c, d2.SwarmLeave(c, false)) info = d2.SwarmInfo(c) - c.Assert(info.ControlAvailable, checker.False) - c.Assert(info.LocalNodeState, checker.Equals, swarm.LocalNodeStateInactive) + assert.Equal(c, info.ControlAvailable, false) + assert.Equal(c, info.LocalNodeState, swarm.LocalNodeStateInactive) d2.SwarmJoin(c, swarm.JoinRequest{ ListenAddr: d1.SwarmListenAddr(), @@ -60,8 +60,8 @@ func (s *DockerSwarmSuite) TestAPISwarmInit(c *check.C) { }) info = d2.SwarmInfo(c) - c.Assert(info.ControlAvailable, checker.False) - c.Assert(info.LocalNodeState, checker.Equals, swarm.LocalNodeStateActive) + assert.Equal(c, info.ControlAvailable, false) + assert.Equal(c, info.LocalNodeState, swarm.LocalNodeStateActive) // Current state restoring after restarts d1.Stop(c) @@ -71,12 +71,12 @@ func (s *DockerSwarmSuite) TestAPISwarmInit(c *check.C) { d2.StartNode(c) info = d1.SwarmInfo(c) - c.Assert(info.ControlAvailable, checker.True) - c.Assert(info.LocalNodeState, checker.Equals, swarm.LocalNodeStateActive) + assert.Equal(c, info.ControlAvailable, true) + assert.Equal(c, info.LocalNodeState, swarm.LocalNodeStateActive) info = d2.SwarmInfo(c) - c.Assert(info.ControlAvailable, checker.False) - c.Assert(info.LocalNodeState, checker.Equals, swarm.LocalNodeStateActive) + assert.Equal(c, info.ControlAvailable, false) + assert.Equal(c, info.LocalNodeState, swarm.LocalNodeStateActive) } func (s *DockerSwarmSuite) TestAPISwarmJoinToken(c *check.C) { @@ -91,20 +91,18 @@ func (s *DockerSwarmSuite) TestAPISwarmJoinToken(c *check.C) { ListenAddr: d2.SwarmListenAddr(), RemoteAddrs: []string{d1.SwarmListenAddr()}, }) - c.Assert(err, checker.NotNil) - c.Assert(err.Error(), checker.Contains, "join token is necessary") + assert.ErrorContains(c, err, "join token is necessary") info := d2.SwarmInfo(c) - c.Assert(info.LocalNodeState, checker.Equals, swarm.LocalNodeStateInactive) + assert.Equal(c, info.LocalNodeState, swarm.LocalNodeStateInactive) err = c2.SwarmJoin(context.Background(), swarm.JoinRequest{ ListenAddr: d2.SwarmListenAddr(), JoinToken: "foobaz", RemoteAddrs: []string{d1.SwarmListenAddr()}, }) - c.Assert(err, checker.NotNil) - c.Assert(err.Error(), checker.Contains, "invalid join token") + assert.ErrorContains(c, err, "invalid join token") info = d2.SwarmInfo(c) - c.Assert(info.LocalNodeState, checker.Equals, swarm.LocalNodeStateInactive) + assert.Equal(c, info.LocalNodeState, swarm.LocalNodeStateInactive) workerToken := d1.JoinTokens(c).Worker @@ -114,10 +112,10 @@ func (s *DockerSwarmSuite) TestAPISwarmJoinToken(c *check.C) { RemoteAddrs: []string{d1.SwarmListenAddr()}, }) info = d2.SwarmInfo(c) - c.Assert(info.LocalNodeState, checker.Equals, swarm.LocalNodeStateActive) - c.Assert(d2.SwarmLeave(c, false), checker.IsNil) + assert.Equal(c, info.LocalNodeState, swarm.LocalNodeStateActive) + assert.NilError(c, d2.SwarmLeave(c, false)) info = d2.SwarmInfo(c) - c.Assert(info.LocalNodeState, checker.Equals, swarm.LocalNodeStateInactive) + assert.Equal(c, info.LocalNodeState, swarm.LocalNodeStateInactive) // change tokens d1.RotateTokens(c) @@ -127,19 +125,18 @@ func (s *DockerSwarmSuite) TestAPISwarmJoinToken(c *check.C) { JoinToken: workerToken, RemoteAddrs: []string{d1.SwarmListenAddr()}, }) - c.Assert(err, checker.NotNil) - c.Assert(err.Error(), checker.Contains, "join token is necessary") + assert.ErrorContains(c, err, "join token is necessary") info = d2.SwarmInfo(c) - c.Assert(info.LocalNodeState, checker.Equals, swarm.LocalNodeStateInactive) + assert.Equal(c, info.LocalNodeState, swarm.LocalNodeStateInactive) workerToken = d1.JoinTokens(c).Worker d2.SwarmJoin(c, swarm.JoinRequest{JoinToken: workerToken, RemoteAddrs: []string{d1.SwarmListenAddr()}}) info = d2.SwarmInfo(c) - c.Assert(info.LocalNodeState, checker.Equals, swarm.LocalNodeStateActive) - c.Assert(d2.SwarmLeave(c, false), checker.IsNil) + assert.Equal(c, info.LocalNodeState, swarm.LocalNodeStateActive) + assert.NilError(c, d2.SwarmLeave(c, false)) info = d2.SwarmInfo(c) - c.Assert(info.LocalNodeState, checker.Equals, swarm.LocalNodeStateInactive) + assert.Equal(c, info.LocalNodeState, swarm.LocalNodeStateInactive) // change spec, don't change tokens d1.UpdateSwarm(c, func(s *swarm.Spec) {}) @@ -148,17 +145,16 @@ func (s *DockerSwarmSuite) TestAPISwarmJoinToken(c *check.C) { ListenAddr: d2.SwarmListenAddr(), RemoteAddrs: []string{d1.SwarmListenAddr()}, }) - c.Assert(err, checker.NotNil) - c.Assert(err.Error(), checker.Contains, "join token is necessary") + assert.ErrorContains(c, err, "join token is necessary") info = d2.SwarmInfo(c) - c.Assert(info.LocalNodeState, checker.Equals, swarm.LocalNodeStateInactive) + assert.Equal(c, info.LocalNodeState, swarm.LocalNodeStateInactive) d2.SwarmJoin(c, swarm.JoinRequest{JoinToken: workerToken, RemoteAddrs: []string{d1.SwarmListenAddr()}}) info = d2.SwarmInfo(c) - c.Assert(info.LocalNodeState, checker.Equals, swarm.LocalNodeStateActive) - c.Assert(d2.SwarmLeave(c, false), checker.IsNil) + assert.Equal(c, info.LocalNodeState, swarm.LocalNodeStateActive) + assert.NilError(c, d2.SwarmLeave(c, false)) info = d2.SwarmInfo(c) - c.Assert(info.LocalNodeState, checker.Equals, swarm.LocalNodeStateInactive) + assert.Equal(c, info.LocalNodeState, swarm.LocalNodeStateInactive) } func (s *DockerSwarmSuite) TestUpdateSwarmAddExternalCA(c *check.C) { @@ -178,9 +174,9 @@ func (s *DockerSwarmSuite) TestUpdateSwarmAddExternalCA(c *check.C) { } }) info := d1.SwarmInfo(c) - c.Assert(info.Cluster.Spec.CAConfig.ExternalCAs, checker.HasLen, 2) - c.Assert(info.Cluster.Spec.CAConfig.ExternalCAs[0].CACert, checker.Equals, "") - c.Assert(info.Cluster.Spec.CAConfig.ExternalCAs[1].CACert, checker.Equals, "cacert") + assert.Equal(c, len(info.Cluster.Spec.CAConfig.ExternalCAs), 2) + assert.Equal(c, info.Cluster.Spec.CAConfig.ExternalCAs[0].CACert, "") + assert.Equal(c, info.Cluster.Spec.CAConfig.ExternalCAs[1].CACert, "cacert") } func (s *DockerSwarmSuite) TestAPISwarmCAHash(c *check.C) { @@ -195,8 +191,7 @@ func (s *DockerSwarmSuite) TestAPISwarmCAHash(c *check.C) { JoinToken: replacementToken, RemoteAddrs: []string{d1.SwarmListenAddr()}, }) - c.Assert(err, checker.NotNil) - c.Assert(err.Error(), checker.Contains, "remote CA does not match fingerprint") + assert.ErrorContains(c, err, "remote CA does not match fingerprint") } func (s *DockerSwarmSuite) TestAPISwarmPromoteDemote(c *check.C) { @@ -205,8 +200,8 @@ func (s *DockerSwarmSuite) TestAPISwarmPromoteDemote(c *check.C) { d2 := s.AddDaemon(c, true, false) info := d2.SwarmInfo(c) - c.Assert(info.ControlAvailable, checker.False) - c.Assert(info.LocalNodeState, checker.Equals, swarm.LocalNodeStateActive) + assert.Equal(c, info.ControlAvailable, false) + assert.Equal(c, info.LocalNodeState, swarm.LocalNodeStateActive) d1.UpdateNode(c, d2.NodeID(), func(n *swarm.Node) { n.Spec.Role = swarm.NodeRoleManager @@ -243,10 +238,10 @@ func (s *DockerSwarmSuite) TestAPISwarmPromoteDemote(c *check.C) { node.Spec.Role = swarm.NodeRoleWorker url := fmt.Sprintf("/nodes/%s/update?version=%d", node.ID, node.Version.Index) res, body, err := request.Post(url, request.Host(d1.Sock()), request.JSONBody(node.Spec)) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) b, err := request.ReadBody(body) - c.Assert(err, checker.IsNil) - c.Assert(res.StatusCode, checker.Equals, http.StatusBadRequest, check.Commentf("output: %q", string(b))) + assert.NilError(c, err) + assert.Equal(c, res.StatusCode, http.StatusBadRequest, "output: %q", string(b)) // The warning specific to demoting the last manager is best-effort and // won't appear until the Role field of the demoted manager has been @@ -255,11 +250,11 @@ func (s *DockerSwarmSuite) TestAPISwarmPromoteDemote(c *check.C) { // it anchors the regexp contrary to the documentation, and this makes // it impossible to match something that includes a line break. if !strings.Contains(string(b), "last manager of the swarm") { - c.Assert(string(b), checker.Contains, "this would result in a loss of quorum") + assert.Assert(c, strings.Contains(string(b), "this would result in a loss of quorum")) } info = d1.SwarmInfo(c) - c.Assert(info.LocalNodeState, checker.Equals, swarm.LocalNodeStateActive) - c.Assert(info.ControlAvailable, checker.True) + assert.Equal(c, info.LocalNodeState, swarm.LocalNodeStateActive) + assert.Equal(c, info.ControlAvailable, true) // Promote already demoted node d1.UpdateNode(c, d2.NodeID(), func(n *swarm.Node) { @@ -290,7 +285,7 @@ func (s *DockerSwarmSuite) TestAPISwarmLeaderProxy(c *check.C) { // query each node and make sure it returns 3 services for _, d := range []*daemon.Daemon{d1, d2, d3} { services := d.ListServices(c) - c.Assert(services, checker.HasLen, 3) + assert.Equal(c, len(services), 3) } } @@ -308,9 +303,9 @@ func (s *DockerSwarmSuite) TestAPISwarmLeaderElection(c *check.C) { d3 := s.AddDaemon(c, true, true) // assert that the first node we made is the leader, and the other two are followers - c.Assert(d1.GetNode(c, d1.NodeID()).ManagerStatus.Leader, checker.True) - c.Assert(d1.GetNode(c, d2.NodeID()).ManagerStatus.Leader, checker.False) - c.Assert(d1.GetNode(c, d3.NodeID()).ManagerStatus.Leader, checker.False) + assert.Equal(c, d1.GetNode(c, d1.NodeID()).ManagerStatus.Leader, true) + assert.Equal(c, d1.GetNode(c, d2.NodeID()).ManagerStatus.Leader, false) + assert.Equal(c, d1.GetNode(c, d3.NodeID()).ManagerStatus.Leader, false) d1.Stop(c) @@ -344,7 +339,7 @@ func (s *DockerSwarmSuite) TestAPISwarmLeaderElection(c *check.C) { waitAndAssert(c, defaultReconciliationTimeout, checkLeader(d2, d3), checker.True) // assert that we have a new leader - c.Assert(leader, checker.NotNil) + assert.Assert(c, leader != nil) // Keep track of the current leader, since we want that to be chosen. stableleader := leader @@ -358,10 +353,10 @@ func (s *DockerSwarmSuite) TestAPISwarmLeaderElection(c *check.C) { // pick out the leader and the followers again // verify that we still only have 1 leader and 2 followers - c.Assert(leader, checker.NotNil) - c.Assert(followers, checker.HasLen, 2) + assert.Assert(c, leader != nil) + assert.Equal(c, len(followers), 2) // and that after we added d1 back, the leader hasn't changed - c.Assert(leader.NodeID(), checker.Equals, stableleader.NodeID()) + assert.Equal(c, leader.NodeID(), stableleader.NodeID()) } func (s *DockerSwarmSuite) TestAPISwarmRaftQuorum(c *check.C) { @@ -418,19 +413,19 @@ func (s *DockerSwarmSuite) TestAPISwarmLeaveRemovesContainer(c *check.C) { d.CreateService(c, simpleTestService, setInstances(instances)) id, err := d.Cmd("run", "-d", "busybox", "top") - c.Assert(err, checker.IsNil, check.Commentf("%s", id)) + assert.NilError(c, err, id) id = strings.TrimSpace(id) waitAndAssert(c, defaultReconciliationTimeout, d.CheckActiveContainerCount, checker.Equals, instances+1) - c.Assert(d.SwarmLeave(c, false), checker.NotNil) - c.Assert(d.SwarmLeave(c, true), checker.IsNil) + assert.ErrorContains(c, d.SwarmLeave(c, false), "") + assert.NilError(c, d.SwarmLeave(c, true)) waitAndAssert(c, defaultReconciliationTimeout, d.CheckActiveContainerCount, checker.Equals, 1) id2, err := d.Cmd("ps", "-q") - c.Assert(err, checker.IsNil, check.Commentf("%s", id2)) - c.Assert(id, checker.HasPrefix, strings.TrimSpace(id2)) + assert.NilError(c, err, id2) + assert.Assert(c, strings.HasPrefix(id, strings.TrimSpace(id2))) } // #23629 @@ -440,7 +435,7 @@ func (s *DockerSwarmSuite) TestAPISwarmLeaveOnPendingJoin(c *check.C) { d2 := s.AddDaemon(c, false, false) id, err := d2.Cmd("run", "-d", "busybox", "top") - c.Assert(err, checker.IsNil, check.Commentf("%s", id)) + assert.NilError(c, err, id) id = strings.TrimSpace(id) c2 := d2.NewClientT(c) @@ -448,19 +443,18 @@ func (s *DockerSwarmSuite) TestAPISwarmLeaveOnPendingJoin(c *check.C) { ListenAddr: d2.SwarmListenAddr(), RemoteAddrs: []string{"123.123.123.123:1234"}, }) - c.Assert(err, check.NotNil) - c.Assert(err.Error(), checker.Contains, "Timeout was reached") + assert.ErrorContains(c, err, "Timeout was reached") info := d2.SwarmInfo(c) - c.Assert(info.LocalNodeState, checker.Equals, swarm.LocalNodeStatePending) + assert.Equal(c, info.LocalNodeState, swarm.LocalNodeStatePending) - c.Assert(d2.SwarmLeave(c, true), checker.IsNil) + assert.NilError(c, d2.SwarmLeave(c, true)) waitAndAssert(c, defaultReconciliationTimeout, d2.CheckActiveContainerCount, checker.Equals, 1) id2, err := d2.Cmd("ps", "-q") - c.Assert(err, checker.IsNil, check.Commentf("%s", id2)) - c.Assert(id, checker.HasPrefix, strings.TrimSpace(id2)) + assert.NilError(c, err, id2) + assert.Assert(c, strings.HasPrefix(id, strings.TrimSpace(id2))) } // #23705 @@ -472,15 +466,14 @@ func (s *DockerSwarmSuite) TestAPISwarmRestoreOnPendingJoin(c *check.C) { ListenAddr: d.SwarmListenAddr(), RemoteAddrs: []string{"123.123.123.123:1234"}, }) - c.Assert(err, check.NotNil) - c.Assert(err.Error(), checker.Contains, "Timeout was reached") + assert.ErrorContains(c, err, "Timeout was reached") waitAndAssert(c, defaultReconciliationTimeout, d.CheckLocalNodeState, checker.Equals, swarm.LocalNodeStatePending) d.RestartNode(c) info := d.SwarmInfo(c) - c.Assert(info.LocalNodeState, checker.Equals, swarm.LocalNodeStateInactive) + assert.Equal(c, info.LocalNodeState, swarm.LocalNodeStateInactive) } func (s *DockerSwarmSuite) TestAPISwarmManagerRestore(c *check.C) { @@ -540,16 +533,16 @@ func (s *DockerSwarmSuite) TestAPISwarmInvalidAddress(c *check.C) { ListenAddr: "", } res, _, err := request.Post("/swarm/init", request.Host(d.Sock()), request.JSONBody(req)) - c.Assert(err, checker.IsNil) - c.Assert(res.StatusCode, checker.Equals, http.StatusBadRequest) + assert.NilError(c, err) + assert.Equal(c, res.StatusCode, http.StatusBadRequest) req2 := swarm.JoinRequest{ ListenAddr: "0.0.0.0:2377", RemoteAddrs: []string{""}, } res, _, err = request.Post("/swarm/join", request.Host(d.Sock()), request.JSONBody(req2)) - c.Assert(err, checker.IsNil) - c.Assert(res.StatusCode, checker.Equals, http.StatusBadRequest) + assert.NilError(c, err) + assert.Equal(c, res.StatusCode, http.StatusBadRequest) } func (s *DockerSwarmSuite) TestAPISwarmForceNewCluster(c *check.C) { @@ -578,8 +571,8 @@ func (s *DockerSwarmSuite) TestAPISwarmForceNewCluster(c *check.C) { d3 := s.AddDaemon(c, true, true) info := d3.SwarmInfo(c) - c.Assert(info.ControlAvailable, checker.True) - c.Assert(info.LocalNodeState, checker.Equals, swarm.LocalNodeStateActive) + assert.Equal(c, info.ControlAvailable, true) + assert.Equal(c, info.LocalNodeState, swarm.LocalNodeStateActive) instances = 4 d3.UpdateService(c, d3.GetService(c, id), setInstances(instances)) @@ -770,22 +763,22 @@ func checkClusterHealth(c *check.C, cl []*daemon.Daemon, managerCount, workerCou waitAndAssert(c, defaultReconciliationTimeout, waitActive, checker.True) if n.Spec.Role == swarm.NodeRoleManager { - c.Assert(n.ManagerStatus, checker.NotNil, check.Commentf("manager status of node %s (manager), reported by %s", n.ID, d.NodeID())) + assert.Assert(c, n.ManagerStatus != nil, "manager status of node %s (manager), reported by %s", n.ID, d.NodeID()) if n.ManagerStatus.Leader { leaderFound = true } mCount++ } else { - c.Assert(n.ManagerStatus, checker.IsNil, check.Commentf("manager status of node %s (worker), reported by %s", n.ID, d.NodeID())) + assert.Assert(c, n.ManagerStatus == nil, "manager status of node %s (worker), reported by %s", n.ID, d.NodeID()) wCount++ } } - c.Assert(leaderFound, checker.True, check.Commentf("lack of leader reported by node %s", info.NodeID)) - c.Assert(mCount, checker.Equals, managerCount, check.Commentf("managers count reported by node %s", info.NodeID)) - c.Assert(wCount, checker.Equals, workerCount, check.Commentf("workers count reported by node %s", info.NodeID)) + assert.Equal(c, leaderFound, true, "lack of leader reported by node %s", info.NodeID) + assert.Equal(c, mCount, managerCount, "managers count reported by node %s", info.NodeID) + assert.Equal(c, wCount, workerCount, "workers count reported by node %s", info.NodeID) } - c.Assert(totalMCount, checker.Equals, managerCount) - c.Assert(totalWCount, checker.Equals, workerCount) + assert.Equal(c, totalMCount, managerCount) + assert.Equal(c, totalWCount, workerCount) } func (s *DockerSwarmSuite) TestAPISwarmRestartCluster(c *check.C) { @@ -795,16 +788,16 @@ func (s *DockerSwarmSuite) TestAPISwarmRestartCluster(c *check.C) { for i := 0; i < mCount; i++ { manager := s.AddDaemon(c, true, true) info := manager.SwarmInfo(c) - c.Assert(info.ControlAvailable, checker.True) - c.Assert(info.LocalNodeState, checker.Equals, swarm.LocalNodeStateActive) + assert.Equal(c, info.ControlAvailable, true) + assert.Equal(c, info.LocalNodeState, swarm.LocalNodeStateActive) nodes = append(nodes, manager) } for i := 0; i < wCount; i++ { worker := s.AddDaemon(c, true, false) info := worker.SwarmInfo(c) - c.Assert(info.ControlAvailable, checker.False) - c.Assert(info.LocalNodeState, checker.Equals, swarm.LocalNodeStateActive) + assert.Equal(c, info.ControlAvailable, false) + assert.Equal(c, info.LocalNodeState, swarm.LocalNodeStateActive) nodes = append(nodes, worker) } @@ -825,7 +818,7 @@ func (s *DockerSwarmSuite) TestAPISwarmRestartCluster(c *check.C) { wg.Wait() close(errs) for err := range errs { - c.Assert(err, check.IsNil) + assert.NilError(c, err) } } @@ -846,7 +839,7 @@ func (s *DockerSwarmSuite) TestAPISwarmRestartCluster(c *check.C) { wg.Wait() close(errs) for err := range errs { - c.Assert(err, check.IsNil) + assert.NilError(c, err) } } @@ -867,7 +860,7 @@ func (s *DockerSwarmSuite) TestAPISwarmServicesUpdateWithName(c *check.C) { cli := d.NewClientT(c) defer cli.Close() _, err := cli.ServiceUpdate(context.Background(), service.Spec.Name, service.Version, service.Spec, types.ServiceUpdateOptions{}) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) waitAndAssert(c, defaultReconciliationTimeout, d.CheckActiveContainerCount, checker.Equals, instances) } @@ -875,22 +868,20 @@ func (s *DockerSwarmSuite) TestAPISwarmServicesUpdateWithName(c *check.C) { func (s *DockerSwarmSuite) TestAPISwarmUnlockNotLocked(c *check.C) { d := s.AddDaemon(c, true, true) err := d.SwarmUnlock(c, swarm.UnlockRequest{UnlockKey: "wrong-key"}) - c.Assert(err, checker.NotNil) - c.Assert(err.Error(), checker.Contains, "swarm is not locked") + assert.ErrorContains(c, err, "swarm is not locked") } // #29885 func (s *DockerSwarmSuite) TestAPISwarmErrorHandling(c *check.C) { ln, err := net.Listen("tcp", fmt.Sprintf(":%d", defaultSwarmPort)) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) defer ln.Close() d := s.AddDaemon(c, false, false) client := d.NewClientT(c) _, err = client.SwarmInit(context.Background(), swarm.InitRequest{ ListenAddr: d.SwarmListenAddr(), }) - c.Assert(err, checker.NotNil) - c.Assert(err.Error(), checker.Contains, "address already in use") + assert.ErrorContains(c, err, "address already in use") } // Test case for 30242, where duplicate networks, with different drivers `bridge` and `overlay`, @@ -909,20 +900,20 @@ func (s *DockerSwarmSuite) TestAPIDuplicateNetworks(c *check.C) { networkCreate.Driver = "bridge" n1, err := cli.NetworkCreate(context.Background(), name, networkCreate) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) networkCreate.Driver = "overlay" n2, err := cli.NetworkCreate(context.Background(), name, networkCreate) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) r1, err := cli.NetworkInspect(context.Background(), n1.ID, types.NetworkInspectOptions{}) - c.Assert(err, checker.IsNil) - c.Assert(r1.Scope, checker.Equals, "local") + assert.NilError(c, err) + assert.Equal(c, r1.Scope, "local") r2, err := cli.NetworkInspect(context.Background(), n2.ID, types.NetworkInspectOptions{}) - c.Assert(err, checker.IsNil) - c.Assert(r2.Scope, checker.Equals, "swarm") + assert.NilError(c, err) + assert.Equal(c, r2.Scope, "swarm") } // Test case for 30178 @@ -932,7 +923,7 @@ func (s *DockerSwarmSuite) TestAPISwarmHealthcheckNone(c *check.C) { d := s.AddDaemon(c, true, true) out, err := d.Cmd("network", "create", "-d", "overlay", "lb") - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) instances := 1 d.CreateService(c, simpleTestService, setInstances(instances), func(s *swarm.Service) { @@ -950,7 +941,7 @@ func (s *DockerSwarmSuite) TestAPISwarmHealthcheckNone(c *check.C) { containers := d.ActiveContainers(c) out, err = d.Cmd("exec", containers[0], "ping", "-c1", "-W3", "top") - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) } func (s *DockerSwarmSuite) TestSwarmRepeatedRootRotation(c *check.C) { @@ -971,7 +962,7 @@ func (s *DockerSwarmSuite) TestSwarmRepeatedRootRotation(c *check.C) { KeyRequest: csr.NewBasicKeyRequest(), CA: &csr.CAConfig{Expiry: ca.RootCAExpiration}, }) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) } expectedCert := string(cert) m.UpdateSwarm(c, func(s *swarm.Spec) { @@ -986,8 +977,8 @@ func (s *DockerSwarmSuite) TestSwarmRepeatedRootRotation(c *check.C) { info := m.SwarmInfo(c) // the desired CA cert and key is always redacted - c.Assert(info.Cluster.Spec.CAConfig.SigningCAKey, checker.Equals, "") - c.Assert(info.Cluster.Spec.CAConfig.SigningCACert, checker.Equals, "") + assert.Equal(c, info.Cluster.Spec.CAConfig.SigningCAKey, "") + assert.Equal(c, info.Cluster.Spec.CAConfig.SigningCACert, "") clusterTLSInfo = info.Cluster.TLSInfo @@ -1000,7 +991,7 @@ func (s *DockerSwarmSuite) TestSwarmRepeatedRootRotation(c *check.C) { time.Sleep(250 * time.Millisecond) } if cert != nil { - c.Assert(clusterTLSInfo.TrustRoot, checker.Equals, expectedCert) + assert.Equal(c, clusterTLSInfo.TrustRoot, expectedCert) } // could take another second or two for the nodes to trust the new roots after they've all gotten // new TLS certificates @@ -1016,8 +1007,8 @@ func (s *DockerSwarmSuite) TestSwarmRepeatedRootRotation(c *check.C) { time.Sleep(250 * time.Millisecond) } - c.Assert(m.GetNode(c, m.NodeID()).Description.TLSInfo, checker.DeepEquals, clusterTLSInfo) - c.Assert(m.GetNode(c, w.NodeID()).Description.TLSInfo, checker.DeepEquals, clusterTLSInfo) + assert.DeepEqual(c, m.GetNode(c, m.NodeID()).Description.TLSInfo, clusterTLSInfo) + assert.DeepEqual(c, m.GetNode(c, w.NodeID()).Description.TLSInfo, clusterTLSInfo) currentTrustRoot = clusterTLSInfo.TrustRoot } } diff --git a/components/engine/integration-cli/docker_api_test.go b/components/engine/integration-cli/docker_api_test.go index 5b7e3e97f9..ecf69bb964 100644 --- a/components/engine/integration-cli/docker_api_test.go +++ b/components/engine/integration-cli/docker_api_test.go @@ -10,27 +10,27 @@ import ( "github.com/docker/docker/api" "github.com/docker/docker/api/types/versions" - "github.com/docker/docker/integration-cli/checker" "github.com/docker/docker/internal/test/request" "github.com/go-check/check" + "gotest.tools/assert" ) func (s *DockerSuite) TestAPIOptionsRoute(c *check.C) { resp, _, err := request.Do("/", request.Method(http.MethodOptions)) - c.Assert(err, checker.IsNil) - c.Assert(resp.StatusCode, checker.Equals, http.StatusOK) + assert.NilError(c, err) + assert.Equal(c, resp.StatusCode, http.StatusOK) } func (s *DockerSuite) TestAPIGetEnabledCORS(c *check.C) { res, body, err := request.Get("/version") - c.Assert(err, checker.IsNil) - c.Assert(res.StatusCode, checker.Equals, http.StatusOK) + assert.NilError(c, err) + assert.Equal(c, res.StatusCode, http.StatusOK) body.Close() // TODO: @runcom incomplete tests, why old integration tests had this headers // and here none of the headers below are in the response? //c.Log(res.Header) - //c.Assert(res.Header.Get("Access-Control-Allow-Origin"), check.Equals, "*") - //c.Assert(res.Header.Get("Access-Control-Allow-Headers"), check.Equals, "Origin, X-Requested-With, Content-Type, Accept, X-Registry-Auth") + //assert.Equal(c, res.Header.Get("Access-Control-Allow-Origin"), "*") + //assert.Equal(c, res.Header.Get("Access-Control-Allow-Headers"), "Origin, X-Requested-With, Content-Type, Accept, X-Registry-Auth") } func (s *DockerSuite) TestAPIClientVersionOldNotSupported(c *check.C) { @@ -42,33 +42,33 @@ func (s *DockerSuite) TestAPIClientVersionOldNotSupported(c *check.C) { } v := strings.Split(api.MinVersion, ".") vMinInt, err := strconv.Atoi(v[1]) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) vMinInt-- v[1] = strconv.Itoa(vMinInt) version := strings.Join(v, ".") resp, body, err := request.Get("/v" + version + "/version") - c.Assert(err, checker.IsNil) + assert.NilError(c, err) defer body.Close() - c.Assert(resp.StatusCode, checker.Equals, http.StatusBadRequest) + assert.Equal(c, resp.StatusCode, http.StatusBadRequest) expected := fmt.Sprintf("client version %s is too old. Minimum supported API version is %s, please upgrade your client to a newer version", version, api.MinVersion) content, err := ioutil.ReadAll(body) - c.Assert(err, checker.IsNil) - c.Assert(strings.TrimSpace(string(content)), checker.Contains, expected) + assert.NilError(c, err) + assert.Equal(c, strings.TrimSpace(string(content)), expected) } func (s *DockerSuite) TestAPIErrorJSON(c *check.C) { httpResp, body, err := request.Post("/containers/create", request.JSONBody(struct{}{})) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) if versions.LessThan(testEnv.DaemonAPIVersion(), "1.32") { - c.Assert(httpResp.StatusCode, checker.Equals, http.StatusInternalServerError) + assert.Equal(c, httpResp.StatusCode, http.StatusInternalServerError) } else { - c.Assert(httpResp.StatusCode, checker.Equals, http.StatusBadRequest) + assert.Equal(c, httpResp.StatusCode, http.StatusBadRequest) } - c.Assert(httpResp.Header.Get("Content-Type"), checker.Equals, "application/json") + assert.Assert(c, strings.Contains(httpResp.Header.Get("Content-Type"), "application/json")) b, err := request.ReadBody(body) - c.Assert(err, checker.IsNil) - c.Assert(getErrorMessage(c, b), checker.Equals, "Config cannot be empty in order to create a container") + assert.NilError(c, err) + assert.Equal(c, getErrorMessage(c, b), "Config cannot be empty in order to create a container") } func (s *DockerSuite) TestAPIErrorPlainText(c *check.C) { @@ -76,35 +76,35 @@ func (s *DockerSuite) TestAPIErrorPlainText(c *check.C) { // in v1.23, but changed in 1.24, hence not applicable on Windows. See apiVersionSupportsJSONErrors testRequires(c, DaemonIsLinux) httpResp, body, err := request.Post("/v1.23/containers/create", request.JSONBody(struct{}{})) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) if versions.LessThan(testEnv.DaemonAPIVersion(), "1.32") { - c.Assert(httpResp.StatusCode, checker.Equals, http.StatusInternalServerError) + assert.Equal(c, httpResp.StatusCode, http.StatusInternalServerError) } else { - c.Assert(httpResp.StatusCode, checker.Equals, http.StatusBadRequest) + assert.Equal(c, httpResp.StatusCode, http.StatusBadRequest) } - c.Assert(httpResp.Header.Get("Content-Type"), checker.Contains, "text/plain") + assert.Assert(c, strings.Contains(httpResp.Header.Get("Content-Type"), "text/plain")) b, err := request.ReadBody(body) - c.Assert(err, checker.IsNil) - c.Assert(strings.TrimSpace(string(b)), checker.Equals, "Config cannot be empty in order to create a container") + assert.NilError(c, err) + assert.Equal(c, strings.TrimSpace(string(b)), "Config cannot be empty in order to create a container") } func (s *DockerSuite) TestAPIErrorNotFoundJSON(c *check.C) { // 404 is a different code path to normal errors, so test separately httpResp, body, err := request.Get("/notfound", request.JSON) - c.Assert(err, checker.IsNil) - c.Assert(httpResp.StatusCode, checker.Equals, http.StatusNotFound) - c.Assert(httpResp.Header.Get("Content-Type"), checker.Equals, "application/json") + assert.NilError(c, err) + assert.Equal(c, httpResp.StatusCode, http.StatusNotFound) + assert.Assert(c, strings.Contains(httpResp.Header.Get("Content-Type"), "application/json")) b, err := request.ReadBody(body) - c.Assert(err, checker.IsNil) - c.Assert(getErrorMessage(c, b), checker.Equals, "page not found") + assert.NilError(c, err) + assert.Equal(c, getErrorMessage(c, b), "page not found") } func (s *DockerSuite) TestAPIErrorNotFoundPlainText(c *check.C) { httpResp, body, err := request.Get("/v1.23/notfound", request.JSON) - c.Assert(err, checker.IsNil) - c.Assert(httpResp.StatusCode, checker.Equals, http.StatusNotFound) - c.Assert(httpResp.Header.Get("Content-Type"), checker.Contains, "text/plain") + assert.NilError(c, err) + assert.Equal(c, httpResp.StatusCode, http.StatusNotFound) + assert.Assert(c, strings.Contains(httpResp.Header.Get("Content-Type"), "text/plain")) b, err := request.ReadBody(body) - c.Assert(err, checker.IsNil) - c.Assert(strings.TrimSpace(string(b)), checker.Equals, "page not found") + assert.NilError(c, err) + assert.Equal(c, strings.TrimSpace(string(b)), "page not found") } diff --git a/components/engine/integration-cli/docker_cli_attach_test.go b/components/engine/integration-cli/docker_cli_attach_test.go index ef2c708bbe..d8ad4cc752 100644 --- a/components/engine/integration-cli/docker_cli_attach_test.go +++ b/components/engine/integration-cli/docker_cli_attach_test.go @@ -12,6 +12,7 @@ import ( "github.com/docker/docker/integration-cli/cli" "github.com/go-check/check" + "gotest.tools/assert" "gotest.tools/icmd" ) @@ -99,7 +100,7 @@ func (s *DockerSuite) TestAttachTTYWithoutStdin(c *check.C) { out, _ := dockerCmd(c, "run", "-d", "-ti", "busybox") id := strings.TrimSpace(out) - c.Assert(waitRun(id), check.IsNil) + assert.NilError(c, waitRun(id)) done := make(chan error) go func() { @@ -126,7 +127,7 @@ func (s *DockerSuite) TestAttachTTYWithoutStdin(c *check.C) { select { case err := <-done: - c.Assert(err, check.IsNil) + assert.NilError(c, err) case <-time.After(attachWait): c.Fatal("attach is running but should have failed") } @@ -144,7 +145,7 @@ func (s *DockerSuite) TestAttachDisconnect(c *check.C) { } defer stdin.Close() stdout, err := cmd.StdoutPipe() - c.Assert(err, check.IsNil) + assert.NilError(c, err) defer stdout.Close() c.Assert(cmd.Start(), check.IsNil) defer func() { @@ -153,9 +154,9 @@ func (s *DockerSuite) TestAttachDisconnect(c *check.C) { }() _, err = stdin.Write([]byte("hello\n")) - c.Assert(err, check.IsNil) + assert.NilError(c, err) out, err = bufio.NewReader(stdout).ReadString('\n') - c.Assert(err, check.IsNil) + assert.NilError(c, err) c.Assert(strings.TrimSpace(out), check.Equals, "hello") c.Assert(stdin.Close(), check.IsNil) diff --git a/components/engine/integration-cli/docker_cli_attach_unix_test.go b/components/engine/integration-cli/docker_cli_attach_unix_test.go index 6430d68ed3..2a8d705a42 100644 --- a/components/engine/integration-cli/docker_cli_attach_unix_test.go +++ b/components/engine/integration-cli/docker_cli_attach_unix_test.go @@ -9,9 +9,9 @@ import ( "strings" "time" - "github.com/docker/docker/integration-cli/checker" "github.com/go-check/check" "github.com/kr/pty" + "gotest.tools/assert" ) // #9860 Make sure attach ends when container ends (with no errors) @@ -21,17 +21,17 @@ func (s *DockerSuite) TestAttachClosedOnContainerStop(c *check.C) { out, _ := dockerCmd(c, "run", "-dti", "busybox", "/bin/sh", "-c", `trap 'exit 0' SIGTERM; while true; do sleep 1; done`) id := strings.TrimSpace(out) - c.Assert(waitRun(id), check.IsNil) + assert.NilError(c, waitRun(id)) pty, tty, err := pty.Open() - c.Assert(err, check.IsNil) + assert.NilError(c, err) attachCmd := exec.Command(dockerBinary, "attach", id) attachCmd.Stdin = tty attachCmd.Stdout = tty attachCmd.Stderr = tty err = attachCmd.Start() - c.Assert(err, check.IsNil) + assert.NilError(c, err) errChan := make(chan error) go func() { @@ -62,7 +62,7 @@ func (s *DockerSuite) TestAttachAfterDetach(c *check.C) { name := "detachtest" cpty, tty, err := pty.Open() - c.Assert(err, checker.IsNil, check.Commentf("Could not open pty: %v", err)) + assert.NilError(c, err, "Could not open pty: %v", err) cmd := exec.Command(dockerBinary, "run", "-ti", "--name", name, "busybox") cmd.Stdin = tty cmd.Stdout = tty @@ -87,7 +87,7 @@ func (s *DockerSuite) TestAttachAfterDetach(c *check.C) { } cpty, tty, err = pty.Open() - c.Assert(err, checker.IsNil, check.Commentf("Could not open pty: %v", err)) + assert.NilError(c, err, "Could not open pty: %v", err) cmd = exec.Command(dockerBinary, "attach", name) cmd.Stdin = tty @@ -95,7 +95,7 @@ func (s *DockerSuite) TestAttachAfterDetach(c *check.C) { cmd.Stderr = tty err = cmd.Start() - c.Assert(err, checker.IsNil) + assert.NilError(c, err) defer cmd.Process.Kill() bytes := make([]byte, 10) @@ -114,45 +114,45 @@ func (s *DockerSuite) TestAttachAfterDetach(c *check.C) { select { case err := <-readErr: - c.Assert(err, check.IsNil) + assert.NilError(c, err) case <-time.After(2 * time.Second): c.Fatal("timeout waiting for attach read") } - c.Assert(string(bytes[:nBytes]), checker.Contains, "/ #") + assert.Assert(c, strings.Contains(string(bytes[:nBytes]), "/ #")) } // TestAttachDetach checks that attach in tty mode can be detached using the long container ID func (s *DockerSuite) TestAttachDetach(c *check.C) { out, _ := dockerCmd(c, "run", "-itd", "busybox", "cat") id := strings.TrimSpace(out) - c.Assert(waitRun(id), check.IsNil) + assert.NilError(c, waitRun(id)) cpty, tty, err := pty.Open() - c.Assert(err, check.IsNil) + assert.NilError(c, err) defer cpty.Close() cmd := exec.Command(dockerBinary, "attach", id) cmd.Stdin = tty stdout, err := cmd.StdoutPipe() - c.Assert(err, check.IsNil) + assert.NilError(c, err) defer stdout.Close() err = cmd.Start() - c.Assert(err, check.IsNil) - c.Assert(waitRun(id), check.IsNil) + assert.NilError(c, err) + assert.NilError(c, waitRun(id)) _, err = cpty.Write([]byte("hello\n")) - c.Assert(err, check.IsNil) + assert.NilError(c, err) out, err = bufio.NewReader(stdout).ReadString('\n') - c.Assert(err, check.IsNil) - c.Assert(strings.TrimSpace(out), checker.Equals, "hello") + assert.NilError(c, err) + assert.Equal(c, strings.TrimSpace(out), "hello") // escape sequence _, err = cpty.Write([]byte{16}) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) time.Sleep(100 * time.Millisecond) _, err = cpty.Write([]byte{17}) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) ch := make(chan struct{}) go func() { @@ -167,5 +167,5 @@ func (s *DockerSuite) TestAttachDetach(c *check.C) { } running := inspectField(c, id, "State.Running") - c.Assert(running, checker.Equals, "true") // container should be running + assert.Equal(c, running, "true") // container should be running } diff --git a/components/engine/integration-cli/docker_cli_build_test.go b/components/engine/integration-cli/docker_cli_build_test.go index d8275102cb..b223e97b12 100644 --- a/components/engine/integration-cli/docker_cli_build_test.go +++ b/components/engine/integration-cli/docker_cli_build_test.go @@ -28,6 +28,7 @@ import ( "github.com/go-check/check" "github.com/moby/buildkit/frontend/dockerfile/command" "github.com/opencontainers/go-digest" + "gotest.tools/assert" "gotest.tools/icmd" ) @@ -498,7 +499,7 @@ func (s *DockerSuite) TestBuildAddSingleFileToWorkdir(c *check.C) { case <-time.After(15 * time.Second): c.Fatal("Build with adding to workdir timed out") case err := <-errChan: - c.Assert(err, check.IsNil) + assert.NilError(c, err) } } @@ -656,7 +657,7 @@ func (s *DockerSuite) TestBuildCopyWildcard(c *check.C) { "file2.txt": "test2", "dir/nested_file": "nested file", "dir/nested_dir/nest_nest_file": "2 times nested", - "dirt": "dirty", + "dirt": "dirty", })) defer ctx.Close() @@ -841,7 +842,7 @@ COPY test_file .`), case <-time.After(15 * time.Second): c.Fatal("Build with adding to workdir timed out") case err := <-errChan: - c.Assert(err, check.IsNil) + assert.NilError(c, err) } } @@ -2068,9 +2069,9 @@ func (s *DockerSuite) TestBuildNoContext(c *check.C) { func (s *DockerSuite) TestBuildDockerfileStdin(c *check.C) { name := "stdindockerfile" tmpDir, err := ioutil.TempDir("", "fake-context") - c.Assert(err, check.IsNil) + assert.NilError(c, err) err = ioutil.WriteFile(filepath.Join(tmpDir, "foo"), []byte("bar"), 0600) - c.Assert(err, check.IsNil) + assert.NilError(c, err) icmd.RunCmd(icmd.Cmd{ Command: []string{dockerBinary, "build", "-t", name, "-f", "-", tmpDir}, @@ -2110,12 +2111,12 @@ func (s *DockerSuite) TestBuildDockerfileStdinDockerignoreIgnored(c *check.C) { func (s *DockerSuite) testBuildDockerfileStdinNoExtraFiles(c *check.C, hasDockerignore, ignoreDockerignore bool) { name := "stdindockerfilenoextra" tmpDir, err := ioutil.TempDir("", "fake-context") - c.Assert(err, check.IsNil) + assert.NilError(c, err) defer os.RemoveAll(tmpDir) writeFile := func(filename, content string) { err = ioutil.WriteFile(filepath.Join(tmpDir, filename), []byte(content), 0600) - c.Assert(err, check.IsNil) + assert.NilError(c, err) } writeFile("foo", "bar") @@ -2850,7 +2851,7 @@ RUN cat /existing-directory/test/foo | grep Hi ADD test.tar /existing-directory-trailing-slash/ RUN cat /existing-directory-trailing-slash/test/foo | grep Hi` tmpDir, err := ioutil.TempDir("", "fake-context") - c.Assert(err, check.IsNil) + assert.NilError(c, err) testTar, err := os.Create(filepath.Join(tmpDir, "test.tar")) if err != nil { c.Fatalf("failed to create test.tar archive: %v", err) @@ -2890,7 +2891,7 @@ func (s *DockerSuite) TestBuildAddBrokenTar(c *check.C) { FROM busybox ADD test.tar /` tmpDir, err := ioutil.TempDir("", "fake-context") - c.Assert(err, check.IsNil) + assert.NilError(c, err) testTar, err := os.Create(filepath.Join(tmpDir, "test.tar")) if err != nil { c.Fatalf("failed to create test.tar archive: %v", err) @@ -2958,7 +2959,7 @@ func (s *DockerSuite) TestBuildAddTarXz(c *check.C) { ADD test.tar.xz / RUN cat /test/foo | grep Hi` tmpDir, err := ioutil.TempDir("", "fake-context") - c.Assert(err, check.IsNil) + assert.NilError(c, err) testTar, err := os.Create(filepath.Join(tmpDir, "test.tar")) if err != nil { c.Fatalf("failed to create test.tar archive: %v", err) @@ -3005,7 +3006,7 @@ func (s *DockerSuite) TestBuildAddTarXzGz(c *check.C) { ADD test.tar.xz.gz / RUN ls /test.tar.xz.gz` tmpDir, err := ioutil.TempDir("", "fake-context") - c.Assert(err, check.IsNil) + assert.NilError(c, err) testTar, err := os.Create(filepath.Join(tmpDir, "test.tar")) if err != nil { c.Fatalf("failed to create test.tar archive: %v", err) @@ -3598,11 +3599,11 @@ RUN [ $(ls -l /test | awk '{print $3":"$4}') = 'root:root' ] func (s *DockerSuite) TestBuildSymlinkBreakout(c *check.C) { name := "testbuildsymlinkbreakout" tmpdir, err := ioutil.TempDir("", name) - c.Assert(err, check.IsNil) + assert.NilError(c, err) // See https://github.com/moby/moby/pull/37770 for reason for next line. tmpdir, err = system.GetLongPathName(tmpdir) - c.Assert(err, check.IsNil) + assert.NilError(c, err) defer os.RemoveAll(tmpdir) ctx := filepath.Join(tmpdir, "context") @@ -3991,7 +3992,7 @@ RUN cat /proc/self/cgroup `)) result.Assert(c, icmd.Success) m, err := regexp.MatchString(fmt.Sprintf("memory:.*/%s/.*", cgroupParent), result.Combined()) - c.Assert(err, check.IsNil) + assert.NilError(c, err) if !m { c.Fatalf("There is no expected memory cgroup with parent /%s/: %s", cgroupParent, result.Combined()) } @@ -4769,14 +4770,14 @@ func (s *DockerSuite) TestBuildCacheBrokenSymlink(c *check.C) { defer ctx.Close() err := os.Symlink(filepath.Join(ctx.Dir, "nosuchfile"), filepath.Join(ctx.Dir, "asymlink")) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) // warm up cache cli.BuildCmd(c, name, build.WithExternalBuildContext(ctx)) // add new file to context, should invalidate cache err = ioutil.WriteFile(filepath.Join(ctx.Dir, "newfile"), []byte("foo"), 0644) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) result := cli.BuildCmd(c, name, build.WithExternalBuildContext(ctx)) if strings.Contains(result.Combined(), "Using cache") { @@ -4796,7 +4797,7 @@ func (s *DockerSuite) TestBuildFollowSymlinkToFile(c *check.C) { defer ctx.Close() err := os.Symlink("foo", filepath.Join(ctx.Dir, "asymlink")) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) cli.BuildCmd(c, name, build.WithExternalBuildContext(ctx)) @@ -4805,7 +4806,7 @@ func (s *DockerSuite) TestBuildFollowSymlinkToFile(c *check.C) { // change target file should invalidate cache err = ioutil.WriteFile(filepath.Join(ctx.Dir, "foo"), []byte("baz"), 0644) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) result := cli.BuildCmd(c, name, build.WithExternalBuildContext(ctx)) c.Assert(result.Combined(), checker.Not(checker.Contains), "Using cache") @@ -4827,7 +4828,7 @@ func (s *DockerSuite) TestBuildFollowSymlinkToDir(c *check.C) { defer ctx.Close() err := os.Symlink("foo", filepath.Join(ctx.Dir, "asymlink")) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) cli.BuildCmd(c, name, build.WithExternalBuildContext(ctx)) @@ -4836,7 +4837,7 @@ func (s *DockerSuite) TestBuildFollowSymlinkToDir(c *check.C) { // change target file should invalidate cache err = ioutil.WriteFile(filepath.Join(ctx.Dir, "foo/def"), []byte("bax"), 0644) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) result := cli.BuildCmd(c, name, build.WithExternalBuildContext(ctx)) c.Assert(result.Combined(), checker.Not(checker.Contains), "Using cache") @@ -4860,7 +4861,7 @@ func (s *DockerSuite) TestBuildSymlinkBasename(c *check.C) { defer ctx.Close() err := os.Symlink("foo", filepath.Join(ctx.Dir, "asymlink")) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) cli.BuildCmd(c, name, build.WithExternalBuildContext(ctx)) @@ -4885,7 +4886,7 @@ func (s *DockerSuite) TestBuildCacheRootSource(c *check.C) { // change file, should invalidate cache err := ioutil.WriteFile(filepath.Join(ctx.Dir, "foo"), []byte("baz"), 0644) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) result := cli.BuildCmd(c, name, build.WithExternalBuildContext(ctx)) @@ -5021,9 +5022,9 @@ func (s *DockerRegistryAuthHtpasswdSuite) TestBuildWithExternalAuth(c *check.C) defer os.Setenv("PATH", osPath) workingDir, err := os.Getwd() - c.Assert(err, checker.IsNil) + assert.NilError(c, err) absolute, err := filepath.Abs(filepath.Join(workingDir, "fixtures", "auth")) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) testPath := fmt.Sprintf("%s%c%s", osPath, filepath.ListSeparator, absolute) os.Setenv("PATH", testPath) @@ -5031,18 +5032,18 @@ func (s *DockerRegistryAuthHtpasswdSuite) TestBuildWithExternalAuth(c *check.C) repoName := fmt.Sprintf("%v/dockercli/busybox:authtest", privateRegistryURL) tmp, err := ioutil.TempDir("", "integration-cli-") - c.Assert(err, checker.IsNil) + assert.NilError(c, err) externalAuthConfig := `{ "credsStore": "shell-test" }` configPath := filepath.Join(tmp, "config.json") err = ioutil.WriteFile(configPath, []byte(externalAuthConfig), 0644) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) dockerCmd(c, "--config", tmp, "login", "-u", s.reg.Username(), "-p", s.reg.Password(), privateRegistryURL) b, err := ioutil.ReadFile(configPath) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) c.Assert(string(b), checker.Not(checker.Contains), "\"auth\":") dockerCmd(c, "--config", tmp, "tag", "busybox", repoName) @@ -5480,7 +5481,7 @@ func (s *DockerSuite) TestBuildCacheFrom(c *check.C) { ADD baz / RUN touch newfile` err = ioutil.WriteFile(filepath.Join(ctx.Dir, "Dockerfile"), []byte(dockerfile), 0644) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) result = cli.BuildCmd(c, "build2", cli.WithFlags("--cache-from=build1"), build.WithExternalBuildContext(ctx)) id2 = getIDByName(c, "build2") @@ -5664,14 +5665,14 @@ func (s *DockerSuite) TestBuildMultiStageCopyFromSyntax(c *check.C) { c.Assert(getIDByName(c, "build1"), checker.Equals, getIDByName(c, "build2")) err := ioutil.WriteFile(filepath.Join(ctx.Dir, "Dockerfile"), []byte(fmt.Sprintf(dockerfile, "COPY baz/aa foo")), 0644) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) // changing file in parent block should not affect last block result = cli.BuildCmd(c, "build3", build.WithExternalBuildContext(ctx)) c.Assert(strings.Count(result.Combined(), "Using cache"), checker.Equals, 5) err = ioutil.WriteFile(filepath.Join(ctx.Dir, "foo"), []byte("pqr"), 0644) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) // changing file in parent block should affect both first and last block result = cli.BuildCmd(c, "build4", build.WithExternalBuildContext(ctx)) @@ -5782,9 +5783,9 @@ func (s *DockerSuite) TestBuildMultiStageImplicitFrom(c *check.C) { if DaemonIsWindows() { out := cli.DockerCmd(c, "run", "build1", "cat", "License.txt").Combined() - c.Assert(len(out), checker.GreaterThan, 10) + assert.Assert(c, len(out) > 10) out2 := cli.DockerCmd(c, "run", "build1", "cat", "foo").Combined() - c.Assert(out, check.Equals, out2) + assert.Equal(c, out, out2) } } @@ -6055,7 +6056,7 @@ FROM busybox WORKDIR /foo/bar `)) out, _ := dockerCmd(c, "inspect", "--format", "{{ json .Config.Cmd }}", image) - c.Assert(strings.TrimSpace(out), checker.Equals, `["sh"]`) + assert.Equal(c, strings.TrimSpace(out), `["sh"]`) image = "testworkdirlabelimagecmd" buildImageSuccessfully(c, image, build.WithDockerfile(` @@ -6065,7 +6066,7 @@ LABEL a=b `)) out, _ = dockerCmd(c, "inspect", "--format", "{{ json .Config.Cmd }}", image) - c.Assert(strings.TrimSpace(out), checker.Equals, `["sh"]`) + assert.Equal(c, strings.TrimSpace(out), `["sh"]`) } // Test case for 28902/28909 @@ -6150,7 +6151,8 @@ CMD echo foo `)) out, _ := dockerCmd(c, "inspect", "--format", "{{ json .Config.Cmd }}", "build2") - c.Assert(strings.TrimSpace(out), checker.Equals, `["/bin/sh","-c","echo foo"]`) + expected := `["/bin/sh","-c","echo foo"]` + assert.Equal(c, strings.TrimSpace(out), expected) } // FIXME(vdemeester) should migrate to docker/cli tests @@ -6172,9 +6174,9 @@ ENV BAR BAZ`), cli.WithFlags("--iidfile", tmpIidFile)) id, err := ioutil.ReadFile(tmpIidFile) - c.Assert(err, check.IsNil) + assert.NilError(c, err) d, err := digest.Parse(string(id)) - c.Assert(err, check.IsNil) + assert.NilError(c, err) c.Assert(d.String(), checker.Equals, getIDByName(c, name)) } @@ -6188,7 +6190,7 @@ func (s *DockerSuite) TestBuildIidFileCleanupOnFail(c *check.C) { tmpIidFile := filepath.Join(tmpDir, "iid") err = ioutil.WriteFile(tmpIidFile, []byte("Dummy"), 0666) - c.Assert(err, check.IsNil) + assert.NilError(c, err) cli.Docker(cli.Build("testbuildiidfilecleanuponfail"), build.WithDockerfile(`FROM `+minimalBaseImage()+` @@ -6197,6 +6199,6 @@ func (s *DockerSuite) TestBuildIidFileCleanupOnFail(c *check.C) { ExitCode: 1, }) _, err = os.Stat(tmpIidFile) - c.Assert(err, check.NotNil) + assert.ErrorContains(c, err, "") c.Assert(os.IsNotExist(err), check.Equals, true) } diff --git a/components/engine/integration-cli/docker_cli_build_unix_test.go b/components/engine/integration-cli/docker_cli_build_unix_test.go index 8cad28f457..af005f5d1f 100644 --- a/components/engine/integration-cli/docker_cli_build_unix_test.go +++ b/components/engine/integration-cli/docker_cli_build_unix_test.go @@ -21,6 +21,7 @@ import ( "github.com/docker/docker/internal/test/fakecontext" "github.com/docker/go-units" "github.com/go-check/check" + "gotest.tools/assert" "gotest.tools/icmd" ) @@ -96,7 +97,7 @@ func (s *DockerSuite) TestBuildAddChangeOwnership(c *check.C) { RUN [ $(stat -c %U:%G "/bar/foo") = 'root:root' ] ` tmpDir, err := ioutil.TempDir("", "fake-context") - c.Assert(err, check.IsNil) + assert.NilError(c, err) testFile, err := os.Create(filepath.Join(tmpDir, "foo")) if err != nil { c.Fatalf("failed to create foo file: %v", err) @@ -135,9 +136,9 @@ func (s *DockerSuite) TestBuildCancellationKillsSleep(c *check.C) { name := "testbuildcancellation" observer, err := newEventObserver(c) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) err = observer.Start() - c.Assert(err, checker.IsNil) + assert.NilError(c, err) defer observer.Stop() // (Note: one year, will never finish) @@ -148,7 +149,7 @@ func (s *DockerSuite) TestBuildCancellationKillsSleep(c *check.C) { buildCmd.Dir = ctx.Dir stdoutBuild, err := buildCmd.StdoutPipe() - c.Assert(err, checker.IsNil) + assert.NilError(c, err) if err := buildCmd.Start(); err != nil { c.Fatalf("failed to run build: %s", err) diff --git a/components/engine/integration-cli/docker_cli_by_digest_test.go b/components/engine/integration-cli/docker_cli_by_digest_test.go index 006cf11e1a..c884d31751 100644 --- a/components/engine/integration-cli/docker_cli_by_digest_test.go +++ b/components/engine/integration-cli/docker_cli_by_digest_test.go @@ -53,7 +53,7 @@ func setupImageWithTag(c *check.C, tag string) (digest.Digest, error) { cli.DockerCmd(c, "rmi", repoAndTag) matches := pushDigestRegex.FindStringSubmatch(out) - c.Assert(matches, checker.HasLen, 2, check.Commentf("unable to parse digest from push output: %s", out)) + assert.Equal(c, len(matches), 2, "unable to parse digest from push output: %s", out) pushDigest := matches[1] return digest.Digest(pushDigest), nil @@ -62,14 +62,14 @@ func setupImageWithTag(c *check.C, tag string) (digest.Digest, error) { func testPullByTagDisplaysDigest(c *check.C) { testRequires(c, DaemonIsLinux) pushDigest, err := setupImage(c) - c.Assert(err, checker.IsNil, check.Commentf("error setting up image")) + assert.NilError(c, err, "error setting up image") // pull from the registry using the tag out, _ := dockerCmd(c, "pull", repoName) // the pull output includes "Digest: ", so find that matches := digestRegex.FindStringSubmatch(out) - c.Assert(matches, checker.HasLen, 2, check.Commentf("unable to parse digest from pull output: %s", out)) + assert.Equal(c, len(matches), 2, "unable to parse digest from push output: %s", out) pullDigest := matches[1] // make sure the pushed and pull digests match @@ -87,7 +87,7 @@ func (s *DockerSchema1RegistrySuite) TestPullByTagDisplaysDigest(c *check.C) { func testPullByDigest(c *check.C) { testRequires(c, DaemonIsLinux) pushDigest, err := setupImage(c) - c.Assert(err, checker.IsNil, check.Commentf("error setting up image")) + assert.NilError(c, err, "error setting up image") // pull from the registry using the @ reference imageReference := fmt.Sprintf("%s@%s", repoName, pushDigest) @@ -95,7 +95,7 @@ func testPullByDigest(c *check.C) { // the pull output includes "Digest: ", so find that matches := digestRegex.FindStringSubmatch(out) - c.Assert(matches, checker.HasLen, 2, check.Commentf("unable to parse digest from pull output: %s", out)) + assert.Equal(c, len(matches), 2, "unable to parse digest from push output: %s", out) pullDigest := matches[1] // make sure the pushed and pull digests match @@ -129,7 +129,7 @@ func (s *DockerSchema1RegistrySuite) TestPullByDigestNoFallback(c *check.C) { func (s *DockerRegistrySuite) TestCreateByDigest(c *check.C) { pushDigest, err := setupImage(c) - c.Assert(err, checker.IsNil, check.Commentf("error setting up image")) + assert.NilError(c, err, "error setting up image") imageReference := fmt.Sprintf("%s@%s", repoName, pushDigest) @@ -137,12 +137,12 @@ func (s *DockerRegistrySuite) TestCreateByDigest(c *check.C) { dockerCmd(c, "create", "--name", containerName, imageReference) res := inspectField(c, containerName, "Config.Image") - c.Assert(res, checker.Equals, imageReference) + assert.Equal(c, res, imageReference) } func (s *DockerRegistrySuite) TestRunByDigest(c *check.C) { pushDigest, err := setupImage(c) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) imageReference := fmt.Sprintf("%s@%s", repoName, pushDigest) @@ -155,12 +155,12 @@ func (s *DockerRegistrySuite) TestRunByDigest(c *check.C) { c.Assert(matches[1], checker.Equals, "1", check.Commentf("Expected %q, got %q", "1", matches[1])) res := inspectField(c, containerName, "Config.Image") - c.Assert(res, checker.Equals, imageReference) + assert.Equal(c, res, imageReference) } func (s *DockerRegistrySuite) TestRemoveImageByDigest(c *check.C) { digest, err := setupImage(c) - c.Assert(err, checker.IsNil, check.Commentf("error setting up image")) + assert.NilError(c, err, "error setting up image") imageReference := fmt.Sprintf("%s@%s", repoName, digest) @@ -172,18 +172,17 @@ func (s *DockerRegistrySuite) TestRemoveImageByDigest(c *check.C) { // do the delete err = deleteImages(imageReference) - c.Assert(err, checker.IsNil, check.Commentf("unexpected error deleting image")) + assert.NilError(c, err, "unexpected error deleting image") // try to inspect again - it should error this time _, err = inspectFieldWithError(imageReference, "Id") //unexpected nil err trying to inspect what should be a non-existent image - c.Assert(err, checker.NotNil) - c.Assert(err.Error(), checker.Contains, "No such object") + assert.ErrorContains(c, err, "No such object") } func (s *DockerRegistrySuite) TestBuildByDigest(c *check.C) { digest, err := setupImage(c) - c.Assert(err, checker.IsNil, check.Commentf("error setting up image")) + assert.NilError(c, err, "error setting up image") imageReference := fmt.Sprintf("%s@%s", repoName, digest) @@ -198,17 +197,17 @@ func (s *DockerRegistrySuite) TestBuildByDigest(c *check.C) { buildImageSuccessfully(c, name, build.WithDockerfile(fmt.Sprintf( `FROM %s CMD ["/bin/echo", "Hello World"]`, imageReference))) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) // get the build's image id res := inspectField(c, name, "Config.Image") // make sure they match - c.Assert(res, checker.Equals, imageID) + assert.Equal(c, res, imageID) } func (s *DockerRegistrySuite) TestTagByDigest(c *check.C) { digest, err := setupImage(c) - c.Assert(err, checker.IsNil, check.Commentf("error setting up image")) + assert.NilError(c, err, "error setting up image") imageReference := fmt.Sprintf("%s@%s", repoName, digest) @@ -222,12 +221,12 @@ func (s *DockerRegistrySuite) TestTagByDigest(c *check.C) { expectedID := inspectField(c, imageReference, "Id") tagID := inspectField(c, tag, "Id") - c.Assert(tagID, checker.Equals, expectedID) + assert.Equal(c, tagID, expectedID) } func (s *DockerRegistrySuite) TestListImagesWithoutDigests(c *check.C) { digest, err := setupImage(c) - c.Assert(err, checker.IsNil, check.Commentf("error setting up image")) + assert.NilError(c, err, "error setting up image") imageReference := fmt.Sprintf("%s@%s", repoName, digest) @@ -242,7 +241,7 @@ func (s *DockerRegistrySuite) TestListImagesWithDigests(c *check.C) { // setup image1 digest1, err := setupImageWithTag(c, "tag1") - c.Assert(err, checker.IsNil, check.Commentf("error setting up image")) + assert.NilError(c, err, "error setting up image") imageReference1 := fmt.Sprintf("%s@%s", repoName, digest1) c.Logf("imageReference1 = %s", imageReference1) @@ -258,7 +257,7 @@ func (s *DockerRegistrySuite) TestListImagesWithDigests(c *check.C) { // setup image2 digest2, err := setupImageWithTag(c, "tag2") //error setting up image - c.Assert(err, checker.IsNil) + assert.NilError(c, err) imageReference2 := fmt.Sprintf("%s@%s", repoName, digest2) c.Logf("imageReference2 = %s", imageReference2) @@ -318,7 +317,7 @@ func (s *DockerRegistrySuite) TestListImagesWithDigests(c *check.C) { func (s *DockerRegistrySuite) TestListDanglingImagesWithDigests(c *check.C) { // setup image1 digest1, err := setupImageWithTag(c, "dangle1") - c.Assert(err, checker.IsNil, check.Commentf("error setting up image")) + assert.NilError(c, err, "error setting up image") imageReference1 := fmt.Sprintf("%s@%s", repoName, digest1) c.Logf("imageReference1 = %s", imageReference1) @@ -334,7 +333,7 @@ func (s *DockerRegistrySuite) TestListDanglingImagesWithDigests(c *check.C) { // setup image2 digest2, err := setupImageWithTag(c, "dangle2") //error setting up image - c.Assert(err, checker.IsNil) + assert.NilError(c, err) imageReference2 := fmt.Sprintf("%s@%s", repoName, digest2) c.Logf("imageReference2 = %s", imageReference2) @@ -401,7 +400,7 @@ func (s *DockerRegistrySuite) TestInspectImageWithDigests(c *check.C) { var imageJSON []types.ImageInspect err = json.Unmarshal([]byte(out), &imageJSON) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) c.Assert(imageJSON, checker.HasLen, 1) c.Assert(imageJSON[0].RepoDigests, checker.HasLen, 1) assert.Check(c, is.Contains(imageJSON[0].RepoDigests, imageReference)) @@ -411,7 +410,7 @@ func (s *DockerRegistrySuite) TestPsListContainersFilterAncestorImageByDigest(c existingContainers := ExistingContainerIDs(c) digest, err := setupImage(c) - c.Assert(err, checker.IsNil, check.Commentf("error setting up image")) + assert.NilError(c, err, "error setting up image") imageReference := fmt.Sprintf("%s@%s", repoName, digest) @@ -436,8 +435,7 @@ func (s *DockerRegistrySuite) TestPsListContainersFilterAncestorImageByDigest(c // Invalid imageReference out, _ := dockerCmd(c, "ps", "-a", "-q", "--no-trunc", fmt.Sprintf("--filter=ancestor=busybox@%s", digest)) - // Filter container for ancestor filter should be empty - c.Assert(strings.TrimSpace(out), checker.Equals, "") + 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) @@ -446,7 +444,7 @@ func (s *DockerRegistrySuite) TestPsListContainersFilterAncestorImageByDigest(c func (s *DockerRegistrySuite) TestDeleteImageByIDOnlyPulledByDigest(c *check.C) { pushDigest, err := setupImage(c) - c.Assert(err, checker.IsNil, check.Commentf("error setting up image")) + assert.NilError(c, err, "error setting up image") // pull from the registry using the @ reference imageReference := fmt.Sprintf("%s@%s", repoName, pushDigest) @@ -460,12 +458,12 @@ func (s *DockerRegistrySuite) TestDeleteImageByIDOnlyPulledByDigest(c *check.C) dockerCmd(c, "rmi", imageID) _, err = inspectFieldWithError(imageID, "Id") - c.Assert(err, checker.NotNil, check.Commentf("image should have been deleted")) + assert.ErrorContains(c, err, "", "image should have been deleted") } func (s *DockerRegistrySuite) TestDeleteImageWithDigestAndTag(c *check.C) { pushDigest, err := setupImage(c) - c.Assert(err, checker.IsNil, check.Commentf("error setting up image")) + assert.NilError(c, err, "error setting up image") // pull from the registry using the @ reference imageReference := fmt.Sprintf("%s@%s", repoName, pushDigest) @@ -487,12 +485,12 @@ func (s *DockerRegistrySuite) TestDeleteImageWithDigestAndTag(c *check.C) { // rmi should have deleted the tag, the digest reference, and the image itself _, err = inspectFieldWithError(imageID, "Id") - c.Assert(err, checker.NotNil, check.Commentf("image should have been deleted")) + assert.ErrorContains(c, err, "", "image should have been deleted") } func (s *DockerRegistrySuite) TestDeleteImageWithDigestAndMultiRepoTag(c *check.C) { pushDigest, err := setupImage(c) - c.Assert(err, checker.IsNil, check.Commentf("error setting up image")) + assert.NilError(c, err, "error setting up image") repo2 := fmt.Sprintf("%s/%s", repoName, "repo2") @@ -512,16 +510,16 @@ func (s *DockerRegistrySuite) TestDeleteImageWithDigestAndMultiRepoTag(c *check. // rmi should have deleted repoTag and image reference, but left repoTag2 inspectField(c, repoTag2, "Id") _, err = inspectFieldWithError(imageReference, "Id") - c.Assert(err, checker.NotNil, check.Commentf("image digest reference should have been removed")) + assert.ErrorContains(c, err, "", "image digest reference should have been removed") _, err = inspectFieldWithError(repoTag, "Id") - c.Assert(err, checker.NotNil, check.Commentf("image tag reference should have been removed")) + assert.ErrorContains(c, err, "", "image tag reference should have been removed") dockerCmd(c, "rmi", repoTag2) // rmi should have deleted the tag, the digest reference, and the image itself _, err = inspectFieldWithError(imageID, "Id") - c.Assert(err, checker.NotNil, check.Commentf("image should have been deleted")) + assert.ErrorContains(c, err, "", "image should have been deleted") } // TestPullFailsWithAlteredManifest tests that a `docker pull` fails when @@ -530,14 +528,14 @@ func (s *DockerRegistrySuite) TestDeleteImageWithDigestAndMultiRepoTag(c *check. func (s *DockerRegistrySuite) TestPullFailsWithAlteredManifest(c *check.C) { testRequires(c, DaemonIsLinux) manifestDigest, err := setupImage(c) - c.Assert(err, checker.IsNil, check.Commentf("error setting up image")) + assert.NilError(c, err, "error setting up image") // Load the target manifest blob. manifestBlob := s.reg.ReadBlobContents(c, manifestDigest) var imgManifest schema2.Manifest err = json.Unmarshal(manifestBlob, &imgManifest) - c.Assert(err, checker.IsNil, check.Commentf("unable to decode image manifest from blob")) + assert.NilError(c, err, "unable to decode image manifest from blob") // Change a layer in the manifest. imgManifest.Layers[0].Digest = digest.Digest("sha256:0123456789abcdef0123456789abcdef0123456789abcdef0123456789abcdef") @@ -548,7 +546,7 @@ func (s *DockerRegistrySuite) TestPullFailsWithAlteredManifest(c *check.C) { defer undo() alteredManifestBlob, err := json.MarshalIndent(imgManifest, "", " ") - c.Assert(err, checker.IsNil, check.Commentf("unable to encode altered image manifest to JSON")) + assert.NilError(c, err, "unable to encode altered image manifest to JSON") s.reg.WriteBlobContents(c, manifestDigest, alteredManifestBlob) @@ -561,7 +559,7 @@ func (s *DockerRegistrySuite) TestPullFailsWithAlteredManifest(c *check.C) { c.Assert(exitStatus, checker.Not(check.Equals), 0) expectedErrorMsg := fmt.Sprintf("manifest verification failed for digest %s", manifestDigest) - c.Assert(out, checker.Contains, expectedErrorMsg) + assert.Assert(c, is.Contains(out, expectedErrorMsg)) } // TestPullFailsWithAlteredManifest tests that a `docker pull` fails when diff --git a/components/engine/integration-cli/docker_cli_cp_from_container_test.go b/components/engine/integration-cli/docker_cli_cp_from_container_test.go index 499be54522..98c35fc453 100644 --- a/components/engine/integration-cli/docker_cli_cp_from_container_test.go +++ b/components/engine/integration-cli/docker_cli_cp_from_container_test.go @@ -6,6 +6,7 @@ import ( "github.com/docker/docker/integration-cli/checker" "github.com/go-check/check" + "gotest.tools/assert" ) // Try all of the test cases from the archive package which implements the @@ -147,7 +148,7 @@ func (s *DockerSuite) TestCpFromCaseB(c *check.C) { dstDir := cpPathTrailingSep(tmpDir, "testDir") err := runDockerCp(c, srcPath, dstDir, nil) - c.Assert(err, checker.NotNil) + assert.ErrorContains(c, err, "") c.Assert(isCpDirNotExist(err), checker.True, check.Commentf("expected DirNotExists error, but got %T: %s", err, err)) } @@ -263,7 +264,7 @@ func (s *DockerSuite) TestCpFromCaseF(c *check.C) { dstFile := cpPath(tmpDir, "file1") err := runDockerCp(c, srcDir, dstFile, nil) - c.Assert(err, checker.NotNil) + assert.ErrorContains(c, err, "") c.Assert(isCpCannotCopyDir(err), checker.True, check.Commentf("expected ErrCannotCopyDir error, but got %T: %s", err, err)) } @@ -355,7 +356,7 @@ func (s *DockerSuite) TestCpFromCaseI(c *check.C) { dstFile := cpPath(tmpDir, "file1") err := runDockerCp(c, srcDir, dstFile, nil) - c.Assert(err, checker.NotNil) + assert.ErrorContains(c, err, "") c.Assert(isCpCannotCopyDir(err), checker.True, check.Commentf("expected ErrCannotCopyDir error, but got %T: %s", err, err)) } diff --git a/components/engine/integration-cli/docker_cli_cp_test.go b/components/engine/integration-cli/docker_cli_cp_test.go index e74af64d2c..9e84ee2698 100644 --- a/components/engine/integration-cli/docker_cli_cp_test.go +++ b/components/engine/integration-cli/docker_cli_cp_test.go @@ -10,8 +10,9 @@ import ( "path/filepath" "strings" - "github.com/docker/docker/integration-cli/checker" "github.com/go-check/check" + "gotest.tools/assert" + is "gotest.tools/assert/cmp" "gotest.tools/icmd" ) @@ -28,9 +29,7 @@ const ( // Ensure that an all-local path case returns an error. func (s *DockerSuite) TestCpLocalOnly(c *check.C) { err := runDockerCp(c, "foo", "bar", nil) - c.Assert(err, checker.NotNil) - - c.Assert(err.Error(), checker.Contains, "must specify at least one container source") + assert.ErrorContains(c, err, "must specify at least one container source") } // Test for #5656 @@ -41,20 +40,18 @@ func (s *DockerSuite) TestCpGarbagePath(c *check.C) { containerID := strings.TrimSpace(out) out, _ = dockerCmd(c, "wait", containerID) - // failed to set up container - c.Assert(strings.TrimSpace(out), checker.Equals, "0") - - c.Assert(os.MkdirAll(cpTestPath, os.ModeDir), checker.IsNil) + assert.Equal(c, strings.TrimSpace(out), "0", "failed to set up container") + assert.NilError(c, os.MkdirAll(cpTestPath, os.ModeDir)) hostFile, err := os.Create(cpFullPath) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) defer hostFile.Close() defer os.RemoveAll(cpTestPathParent) fmt.Fprintf(hostFile, "%s", cpHostContents) tmpdir, err := ioutil.TempDir("", "docker-integration") - c.Assert(err, checker.IsNil) + assert.NilError(c, err) tmpname := filepath.Join(tmpdir, cpTestName) defer os.RemoveAll(tmpdir) @@ -67,13 +64,9 @@ func (s *DockerSuite) TestCpGarbagePath(c *check.C) { defer file.Close() test, err := ioutil.ReadAll(file) - c.Assert(err, checker.IsNil) - - // output matched host file -- garbage path can escape container rootfs - c.Assert(string(test), checker.Not(checker.Equals), cpHostContents) - - // output doesn't match the input for garbage path - c.Assert(string(test), checker.Equals, cpContainerContents) + assert.NilError(c, err) + assert.Assert(c, string(test) != cpHostContents, "output matched host file -- garbage path can escape container rootfs") + assert.Assert(c, string(test) == cpContainerContents, "output doesn't match the input for garbage path") } // Check that relative paths are relative to the container's rootfs @@ -83,20 +76,18 @@ func (s *DockerSuite) TestCpRelativePath(c *check.C) { containerID := strings.TrimSpace(out) out, _ = dockerCmd(c, "wait", containerID) - // failed to set up container - c.Assert(strings.TrimSpace(out), checker.Equals, "0") - - c.Assert(os.MkdirAll(cpTestPath, os.ModeDir), checker.IsNil) + assert.Equal(c, strings.TrimSpace(out), "0", "failed to set up container") + assert.NilError(c, os.MkdirAll(cpTestPath, os.ModeDir)) hostFile, err := os.Create(cpFullPath) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) defer hostFile.Close() defer os.RemoveAll(cpTestPathParent) fmt.Fprintf(hostFile, "%s", cpHostContents) tmpdir, err := ioutil.TempDir("", "docker-integration") - c.Assert(err, checker.IsNil) + assert.NilError(c, err) tmpname := filepath.Join(tmpdir, cpTestName) defer os.RemoveAll(tmpdir) @@ -107,7 +98,7 @@ func (s *DockerSuite) TestCpRelativePath(c *check.C) { // get this unix-path manipulation on windows with filepath. relPath = cpFullPath[1:] } - c.Assert(path.IsAbs(cpFullPath), checker.True, check.Commentf("path %s was assumed to be an absolute path", cpFullPath)) + assert.Assert(c, path.IsAbs(cpFullPath), "path %s was assumed to be an absolute path", cpFullPath) dockerCmd(c, "cp", containerID+":"+relPath, tmpdir) @@ -115,13 +106,9 @@ func (s *DockerSuite) TestCpRelativePath(c *check.C) { defer file.Close() test, err := ioutil.ReadAll(file) - c.Assert(err, checker.IsNil) - - // output matched host file -- relative path can escape container rootfs - c.Assert(string(test), checker.Not(checker.Equals), cpHostContents) - - // output doesn't match the input for relative path - c.Assert(string(test), checker.Equals, cpContainerContents) + assert.NilError(c, err) + assert.Assert(c, string(test) != cpHostContents, "output matched host file -- relative path can escape container rootfs") + assert.Assert(c, string(test) == cpContainerContents, "output doesn't match the input for relative path") } // Check that absolute paths are relative to the container's rootfs @@ -131,20 +118,18 @@ func (s *DockerSuite) TestCpAbsolutePath(c *check.C) { containerID := strings.TrimSpace(out) out, _ = dockerCmd(c, "wait", containerID) - // failed to set up container - c.Assert(strings.TrimSpace(out), checker.Equals, "0") - - c.Assert(os.MkdirAll(cpTestPath, os.ModeDir), checker.IsNil) + assert.Equal(c, strings.TrimSpace(out), "0", "failed to set up container") + assert.NilError(c, os.MkdirAll(cpTestPath, os.ModeDir)) hostFile, err := os.Create(cpFullPath) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) defer hostFile.Close() defer os.RemoveAll(cpTestPathParent) fmt.Fprintf(hostFile, "%s", cpHostContents) tmpdir, err := ioutil.TempDir("", "docker-integration") - c.Assert(err, checker.IsNil) + assert.NilError(c, err) tmpname := filepath.Join(tmpdir, cpTestName) defer os.RemoveAll(tmpdir) @@ -157,13 +142,9 @@ func (s *DockerSuite) TestCpAbsolutePath(c *check.C) { defer file.Close() test, err := ioutil.ReadAll(file) - c.Assert(err, checker.IsNil) - - // output matched host file -- absolute path can escape container rootfs - c.Assert(string(test), checker.Not(checker.Equals), cpHostContents) - - // output doesn't match the input for absolute path - c.Assert(string(test), checker.Equals, cpContainerContents) + assert.NilError(c, err) + assert.Assert(c, string(test) != cpHostContents, "output matched host file -- absolute path can escape container rootfs") + assert.Assert(c, string(test) == cpContainerContents, "output doesn't match the input for absolute path") } // Test for #5619 @@ -175,20 +156,19 @@ func (s *DockerSuite) TestCpAbsoluteSymlink(c *check.C) { containerID := strings.TrimSpace(out) out, _ = dockerCmd(c, "wait", containerID) - // failed to set up container - c.Assert(strings.TrimSpace(out), checker.Equals, "0") + assert.Equal(c, strings.TrimSpace(out), "0", "failed to set up container") - c.Assert(os.MkdirAll(cpTestPath, os.ModeDir), checker.IsNil) + assert.NilError(c, os.MkdirAll(cpTestPath, os.ModeDir)) hostFile, err := os.Create(cpFullPath) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) defer hostFile.Close() defer os.RemoveAll(cpTestPathParent) fmt.Fprintf(hostFile, "%s", cpHostContents) tmpdir, err := ioutil.TempDir("", "docker-integration") - c.Assert(err, checker.IsNil) + assert.NilError(c, err) tmpname := filepath.Join(tmpdir, "container_path") defer os.RemoveAll(tmpdir) @@ -199,9 +179,8 @@ func (s *DockerSuite) TestCpAbsoluteSymlink(c *check.C) { // We should have copied a symlink *NOT* the file itself! linkTarget, err := os.Readlink(tmpname) - c.Assert(err, checker.IsNil) - - c.Assert(linkTarget, checker.Equals, filepath.FromSlash(cpFullPath)) + assert.NilError(c, err) + assert.Equal(c, linkTarget, filepath.FromSlash(cpFullPath)) } // Check that symlinks to a directory behave as expected when copying one from @@ -213,11 +192,10 @@ func (s *DockerSuite) TestCpFromSymlinkToDirectory(c *check.C) { containerID := strings.TrimSpace(out) out, _ = dockerCmd(c, "wait", containerID) - // failed to set up container - c.Assert(strings.TrimSpace(out), checker.Equals, "0") + assert.Equal(c, strings.TrimSpace(out), "0", "failed to set up container") testDir, err := ioutil.TempDir("", "test-cp-from-symlink-to-dir-") - c.Assert(err, checker.IsNil) + assert.NilError(c, err) defer os.RemoveAll(testDir) // This copy command should copy the symlink, not the target, into the @@ -226,9 +204,9 @@ func (s *DockerSuite) TestCpFromSymlinkToDirectory(c *check.C) { expectedPath := filepath.Join(testDir, "dir_link") linkTarget, err := os.Readlink(expectedPath) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) - c.Assert(linkTarget, checker.Equals, filepath.FromSlash(cpTestPathParent)) + assert.Equal(c, linkTarget, filepath.FromSlash(cpTestPathParent)) os.Remove(expectedPath) @@ -243,13 +221,12 @@ func (s *DockerSuite) TestCpFromSymlinkToDirectory(c *check.C) { if err == nil { out = fmt.Sprintf("target name was copied: %q - %q", stat.Mode(), stat.Name()) } - c.Assert(err, checker.NotNil, check.Commentf("%s", out)) + assert.ErrorContains(c, err, "", out) // It *should* have copied the directory using the asked name "dir_link". stat, err = os.Lstat(expectedPath) - c.Assert(err, checker.IsNil, check.Commentf("unable to stat resource at %q", expectedPath)) - - c.Assert(stat.IsDir(), checker.True, check.Commentf("should have copied a directory but got %q instead", stat.Mode())) + assert.NilError(c, err, "unable to stat resource at %q", expectedPath) + assert.Assert(c, stat.IsDir(), "should have copied a directory but got %q instead", stat.Mode()) } // Check that symlinks to a directory behave as expected when copying one to a @@ -259,7 +236,7 @@ func (s *DockerSuite) TestCpToSymlinkToDirectory(c *check.C) { testRequires(c, testEnv.IsLocalDaemon) // Requires local volume mount bind. testVol, err := ioutil.TempDir("", "test-cp-to-symlink-to-dir-") - c.Assert(err, checker.IsNil) + assert.NilError(c, err) defer os.RemoveAll(testVol) // Create a test container with a local volume. We will test by copying @@ -270,25 +247,25 @@ func (s *DockerSuite) TestCpToSymlinkToDirectory(c *check.C) { // Create a temp directory to hold a test file nested in a directory. testDir, err := ioutil.TempDir("", "test-cp-to-symlink-to-dir-") - c.Assert(err, checker.IsNil) + assert.NilError(c, err) defer os.RemoveAll(testDir) // This file will be at "/testDir/some/path/test" and will be copied into // the test volume later. hostTestFilename := filepath.Join(testDir, cpFullPath) - c.Assert(os.MkdirAll(filepath.Dir(hostTestFilename), os.FileMode(0700)), checker.IsNil) - c.Assert(ioutil.WriteFile(hostTestFilename, []byte(cpHostContents), os.FileMode(0600)), checker.IsNil) + assert.NilError(c, os.MkdirAll(filepath.Dir(hostTestFilename), os.FileMode(0700))) + assert.NilError(c, ioutil.WriteFile(hostTestFilename, []byte(cpHostContents), os.FileMode(0600))) // Now create another temp directory to hold a symlink to the // "/testDir/some" directory. linkDir, err := ioutil.TempDir("", "test-cp-to-symlink-to-dir-") - c.Assert(err, checker.IsNil) + assert.NilError(c, err) defer os.RemoveAll(linkDir) // Then symlink "/linkDir/dir_link" to "/testdir/some". linkTarget := filepath.Join(testDir, cpTestPathParent) localLink := filepath.Join(linkDir, "dir_link") - c.Assert(os.Symlink(linkTarget, localLink), checker.IsNil) + assert.NilError(c, os.Symlink(linkTarget, localLink)) // Now copy that symlink into the test volume in the container. dockerCmd(c, "cp", localLink, containerID+":/testVol") @@ -296,9 +273,8 @@ func (s *DockerSuite) TestCpToSymlinkToDirectory(c *check.C) { // This copy command should have copied the symlink *not* the target. expectedPath := filepath.Join(testVol, "dir_link") actualLinkTarget, err := os.Readlink(expectedPath) - c.Assert(err, checker.IsNil, check.Commentf("unable to read symlink at %q", expectedPath)) - - c.Assert(actualLinkTarget, checker.Equals, linkTarget) + assert.NilError(c, err, "unable to read symlink at %q", expectedPath) + assert.Equal(c, actualLinkTarget, linkTarget) // Good, now remove that copied link for the next test. os.Remove(expectedPath) @@ -315,21 +291,19 @@ func (s *DockerSuite) TestCpToSymlinkToDirectory(c *check.C) { if err == nil { out = fmt.Sprintf("target name was copied: %q - %q", stat.Mode(), stat.Name()) } - c.Assert(err, checker.NotNil, check.Commentf("%s", out)) + assert.ErrorContains(c, err, "", out) // It *should* have copied the directory using the asked name "dir_link". stat, err = os.Lstat(expectedPath) - c.Assert(err, checker.IsNil, check.Commentf("unable to stat resource at %q", expectedPath)) - - c.Assert(stat.IsDir(), checker.True, check.Commentf("should have copied a directory but got %q instead", stat.Mode())) + assert.NilError(c, err, "unable to stat resource at %q", expectedPath) + assert.Assert(c, stat.IsDir(), "should have copied a directory but got %q instead", stat.Mode()) // And this directory should contain the file copied from the host at the // expected location: "/testVol/dir_link/path/test" expectedFilepath := filepath.Join(testVol, "dir_link/path/test") fileContents, err := ioutil.ReadFile(expectedFilepath) - c.Assert(err, checker.IsNil) - - c.Assert(string(fileContents), checker.Equals, cpHostContents) + assert.NilError(c, err) + assert.Equal(c, string(fileContents), cpHostContents) } // Test for #5619 @@ -341,13 +315,12 @@ func (s *DockerSuite) TestCpSymlinkComponent(c *check.C) { containerID := strings.TrimSpace(out) out, _ = dockerCmd(c, "wait", containerID) - // failed to set up container - c.Assert(strings.TrimSpace(out), checker.Equals, "0") + assert.Equal(c, strings.TrimSpace(out), "0", "failed to set up container") - c.Assert(os.MkdirAll(cpTestPath, os.ModeDir), checker.IsNil) + assert.NilError(c, os.MkdirAll(cpTestPath, os.ModeDir)) hostFile, err := os.Create(cpFullPath) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) defer hostFile.Close() defer os.RemoveAll(cpTestPathParent) @@ -355,7 +328,7 @@ func (s *DockerSuite) TestCpSymlinkComponent(c *check.C) { tmpdir, err := ioutil.TempDir("", "docker-integration") - c.Assert(err, checker.IsNil) + assert.NilError(c, err) tmpname := filepath.Join(tmpdir, cpTestName) defer os.RemoveAll(tmpdir) @@ -368,13 +341,9 @@ func (s *DockerSuite) TestCpSymlinkComponent(c *check.C) { defer file.Close() test, err := ioutil.ReadAll(file) - c.Assert(err, checker.IsNil) - - // output matched host file -- symlink path component can escape container rootfs - c.Assert(string(test), checker.Not(checker.Equals), cpHostContents) - - // output doesn't match the input for symlink path component - c.Assert(string(test), checker.Equals, cpContainerContents) + assert.NilError(c, err) + assert.Assert(c, string(test) != cpHostContents, "output matched host file -- symlink path component can escape container rootfs") + assert.Equal(c, string(test), cpContainerContents, "output doesn't match the input for symlink path component") } // Check that cp with unprivileged user doesn't return any error @@ -387,15 +356,15 @@ func (s *DockerSuite) TestCpUnprivilegedUser(c *check.C) { containerID := strings.TrimSpace(out) out, _ = dockerCmd(c, "wait", containerID) - // failed to set up container - c.Assert(strings.TrimSpace(out), checker.Equals, "0") + assert.Equal(c, strings.TrimSpace(out), "0", "failed to set up container") tmpdir, err := ioutil.TempDir("", "docker-integration") - c.Assert(err, checker.IsNil) + assert.NilError(c, err) defer os.RemoveAll(tmpdir) - c.Assert(os.Chmod(tmpdir, 0777), checker.IsNil) + err = os.Chmod(tmpdir, 0777) + assert.NilError(c, err) result := icmd.RunCommand("su", "unprivilegeduser", "-c", fmt.Sprintf("%s cp %s:%s %s", dockerBinary, containerID, cpTestName, tmpdir)) @@ -407,7 +376,7 @@ func (s *DockerSuite) TestCpSpecialFiles(c *check.C) { testRequires(c, testEnv.IsLocalDaemon) outDir, err := ioutil.TempDir("", "cp-test-special-files") - c.Assert(err, checker.IsNil) + assert.NilError(c, err) defer os.RemoveAll(outDir) out, _ := dockerCmd(c, "run", "-d", "busybox", "/bin/sh", "-c", "touch /foo") @@ -415,38 +384,31 @@ func (s *DockerSuite) TestCpSpecialFiles(c *check.C) { containerID := strings.TrimSpace(out) out, _ = dockerCmd(c, "wait", containerID) - // failed to set up container - c.Assert(strings.TrimSpace(out), checker.Equals, "0") + 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) expected := readContainerFile(c, containerID, "resolv.conf") actual, err := ioutil.ReadFile(outDir + "/resolv.conf") - c.Assert(err, checker.IsNil) - - // Expected copied file to be duplicate of the container resolvconf - c.Assert(bytes.Equal(actual, expected), checker.True) + assert.NilError(c, err) + 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) expected = readContainerFile(c, containerID, "hosts") actual, err = ioutil.ReadFile(outDir + "/hosts") - c.Assert(err, checker.IsNil) - - // Expected copied file to be duplicate of the container hosts - c.Assert(bytes.Equal(actual, expected), checker.True) + assert.NilError(c, err) + 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) expected = readContainerFile(c, containerID, "hostname") actual, err = ioutil.ReadFile(outDir + "/hostname") - c.Assert(err, checker.IsNil) - - // Expected copied file to be duplicate of the container resolvconf - c.Assert(bytes.Equal(actual, expected), checker.True) + assert.NilError(c, err) + assert.Assert(c, bytes.Equal(actual, expected), "Expected copied file to be duplicate of the container hostname") } func (s *DockerSuite) TestCpVolumePath(c *check.C) { @@ -456,66 +418,60 @@ func (s *DockerSuite) TestCpVolumePath(c *check.C) { testRequires(c, testEnv.IsLocalDaemon) tmpDir, err := ioutil.TempDir("", "cp-test-volumepath") - c.Assert(err, checker.IsNil) + assert.NilError(c, err) defer os.RemoveAll(tmpDir) outDir, err := ioutil.TempDir("", "cp-test-volumepath-out") - c.Assert(err, checker.IsNil) + assert.NilError(c, err) defer os.RemoveAll(outDir) _, err = os.Create(tmpDir + "/test") - c.Assert(err, checker.IsNil) + 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 := strings.TrimSpace(out) out, _ = dockerCmd(c, "wait", containerID) - // failed to set up container - c.Assert(strings.TrimSpace(out), checker.Equals, "0") + assert.Equal(c, strings.TrimSpace(out), "0", "failed to set up container") // Copy actual volume path dockerCmd(c, "cp", containerID+":/foo", outDir) stat, err := os.Stat(outDir + "/foo") - c.Assert(err, checker.IsNil) - // expected copied content to be dir - c.Assert(stat.IsDir(), checker.True) + assert.NilError(c, err) + assert.Assert(c, stat.IsDir(), "Expected copied content to be dir") + stat, err = os.Stat(outDir + "/foo/bar") - c.Assert(err, checker.IsNil) - // Expected file `bar` to be a file - c.Assert(stat.IsDir(), checker.False) + assert.NilError(c, err) + assert.Assert(c, !stat.IsDir(), "Expected file `bar` to be a file") // Copy file nested in volume dockerCmd(c, "cp", containerID+":/foo/bar", outDir) stat, err = os.Stat(outDir + "/bar") - c.Assert(err, checker.IsNil) - // Expected file `bar` to be a file - c.Assert(stat.IsDir(), checker.False) + 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) stat, err = os.Stat(outDir + "/baz") - c.Assert(err, checker.IsNil) - // Expected `baz` to be a dir - c.Assert(stat.IsDir(), checker.True) + 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) fb, err := ioutil.ReadFile(outDir + "/baz/test") - c.Assert(err, checker.IsNil) + assert.NilError(c, err) fb2, err := ioutil.ReadFile(tmpDir + "/test") - c.Assert(err, checker.IsNil) - // Expected copied file to be duplicate of bind-mounted file - c.Assert(bytes.Equal(fb, fb2), checker.True) + assert.NilError(c, err) + 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) fb, err = ioutil.ReadFile(outDir + "/test") - c.Assert(err, checker.IsNil) + assert.NilError(c, err) fb2, err = ioutil.ReadFile(tmpDir + "/test") - c.Assert(err, checker.IsNil) - // Expected copied file to be duplicate of bind-mounted file - c.Assert(bytes.Equal(fb, fb2), checker.True) + assert.NilError(c, err) + assert.Assert(c, bytes.Equal(fb, fb2), "Expected copied file to be duplicate of bind-mounted file") } func (s *DockerSuite) TestCpToDot(c *check.C) { @@ -524,20 +480,21 @@ func (s *DockerSuite) TestCpToDot(c *check.C) { containerID := strings.TrimSpace(out) out, _ = dockerCmd(c, "wait", containerID) - // failed to set up container - c.Assert(strings.TrimSpace(out), checker.Equals, "0") + assert.Equal(c, strings.TrimSpace(out), "0", "failed to set up container") tmpdir, err := ioutil.TempDir("", "docker-integration") - c.Assert(err, checker.IsNil) + assert.NilError(c, err) defer os.RemoveAll(tmpdir) cwd, err := os.Getwd() - c.Assert(err, checker.IsNil) + assert.NilError(c, err) defer os.Chdir(cwd) - c.Assert(os.Chdir(tmpdir), checker.IsNil) + err = os.Chdir(tmpdir) + assert.NilError(c, err) + dockerCmd(c, "cp", containerID+":/test", ".") content, err := ioutil.ReadFile("./test") - c.Assert(err, checker.IsNil) - c.Assert(string(content), checker.Equals, "lololol\n") + assert.NilError(c, err) + assert.Equal(c, string(content), "lololol\n") } func (s *DockerSuite) TestCpToStdout(c *check.C) { @@ -546,17 +503,15 @@ func (s *DockerSuite) TestCpToStdout(c *check.C) { containerID := strings.TrimSpace(out) out, _ = dockerCmd(c, "wait", containerID) - // failed to set up container - c.Assert(strings.TrimSpace(out), checker.Equals, "0") + assert.Equal(c, strings.TrimSpace(out), "0", "failed to set up container") out, err := RunCommandPipelineWithOutput( exec.Command(dockerBinary, "cp", containerID+":/test", "-"), exec.Command("tar", "-vtf", "-")) - c.Assert(err, checker.IsNil) - - c.Assert(out, checker.Contains, "test") - c.Assert(out, checker.Contains, "-rw") + assert.NilError(c, err) + assert.Check(c, is.Contains(out, "test")) + assert.Check(c, is.Contains(out, "-rw")) } func (s *DockerSuite) TestCpNameHasColon(c *check.C) { @@ -567,16 +522,15 @@ func (s *DockerSuite) TestCpNameHasColon(c *check.C) { containerID := strings.TrimSpace(out) out, _ = dockerCmd(c, "wait", containerID) - // failed to set up container - c.Assert(strings.TrimSpace(out), checker.Equals, "0") + assert.Equal(c, strings.TrimSpace(out), "0", "failed to set up container") tmpdir, err := ioutil.TempDir("", "docker-integration") - c.Assert(err, checker.IsNil) + assert.NilError(c, err) defer os.RemoveAll(tmpdir) dockerCmd(c, "cp", containerID+":/te:s:t", tmpdir) content, err := ioutil.ReadFile(tmpdir + "/te:s:t") - c.Assert(err, checker.IsNil) - c.Assert(string(content), checker.Equals, "lololol\n") + assert.NilError(c, err) + assert.Equal(c, string(content), "lololol\n") } func (s *DockerSuite) TestCopyAndRestart(c *check.C) { @@ -586,18 +540,16 @@ func (s *DockerSuite) TestCopyAndRestart(c *check.C) { containerID := strings.TrimSpace(out) out, _ = dockerCmd(c, "wait", containerID) - // failed to set up container - c.Assert(strings.TrimSpace(out), checker.Equals, "0") + assert.Equal(c, strings.TrimSpace(out), "0", "failed to set up container") tmpDir, err := ioutil.TempDir("", "test-docker-restart-after-copy-") - c.Assert(err, checker.IsNil) + assert.NilError(c, err) defer os.RemoveAll(tmpDir) dockerCmd(c, "cp", fmt.Sprintf("%s:/etc/group", containerID), tmpDir) out, _ = dockerCmd(c, "start", "-a", containerID) - - c.Assert(strings.TrimSpace(out), checker.Equals, expectedMsg) + assert.Equal(c, strings.TrimSpace(out), expectedMsg) } func (s *DockerSuite) TestCopyCreatedContainer(c *check.C) { @@ -605,7 +557,7 @@ func (s *DockerSuite) TestCopyCreatedContainer(c *check.C) { dockerCmd(c, "create", "--name", "test_cp", "-v", "/test", "busybox") tmpDir, err := ioutil.TempDir("", "test") - c.Assert(err, checker.IsNil) + assert.NilError(c, err) defer os.RemoveAll(tmpDir) dockerCmd(c, "cp", "test_cp:/bin/sh", tmpDir) } @@ -616,21 +568,15 @@ func (s *DockerSuite) TestCopyCreatedContainer(c *check.C) { func (s *DockerSuite) TestCpSymlinkFromConToHostFollowSymlink(c *check.C) { 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") - if exitCode != 0 { - c.Fatal("failed to create a container", out) - } + assert.Equal(c, exitCode, 0, "failed to set up container: %s", out) cleanedContainerID := strings.TrimSpace(out) out, _ = dockerCmd(c, "wait", cleanedContainerID) - if strings.TrimSpace(out) != "0" { - c.Fatal("failed to set up container", out) - } + assert.Equal(c, strings.TrimSpace(out), "0", "failed to set up container") testDir, err := ioutil.TempDir("", "test-cp-symlink-container-to-host-follow-symlink") - if err != nil { - c.Fatal(err) - } + assert.NilError(c, err) defer os.RemoveAll(testDir) // This copy command should copy the symlink, not the target, into the @@ -641,12 +587,9 @@ func (s *DockerSuite) TestCpSymlinkFromConToHostFollowSymlink(c *check.C) { expected := []byte(cpContainerContents) actual, err := ioutil.ReadFile(expectedPath) - c.Assert(err, checker.IsNil) - - if !bytes.Equal(actual, expected) { - c.Fatalf("Expected copied file to be duplicate of the container symbol link target") - } + assert.NilError(c, err) os.Remove(expectedPath) + assert.Assert(c, bytes.Equal(actual, expected), "Expected copied file to be duplicate of the container symbol link target") // now test copy symbol link to a non-existing file in host expectedPath = filepath.Join(testDir, "somefile_host") @@ -658,10 +601,7 @@ func (s *DockerSuite) TestCpSymlinkFromConToHostFollowSymlink(c *check.C) { dockerCmd(c, "cp", "-L", cleanedContainerID+":"+"/dir_link", expectedPath) actual, err = ioutil.ReadFile(expectedPath) - c.Assert(err, checker.IsNil) - - if !bytes.Equal(actual, expected) { - c.Fatalf("Expected copied file to be duplicate of the container symbol link target") - } + assert.NilError(c, err) defer os.Remove(expectedPath) + assert.Assert(c, bytes.Equal(actual, expected), "Expected copied file to be duplicate of the container symbol link target") } diff --git a/components/engine/integration-cli/docker_cli_cp_to_container_test.go b/components/engine/integration-cli/docker_cli_cp_to_container_test.go index 27d3edcc21..cbf2fdcf0e 100644 --- a/components/engine/integration-cli/docker_cli_cp_to_container_test.go +++ b/components/engine/integration-cli/docker_cli_cp_to_container_test.go @@ -5,6 +5,7 @@ import ( "github.com/docker/docker/integration-cli/checker" "github.com/go-check/check" + "gotest.tools/assert" ) // Try all of the test cases from the archive package which implements the @@ -155,7 +156,7 @@ func (s *DockerSuite) TestCpToCaseB(c *check.C) { dstDir := containerCpPathTrailingSep(containerID, "testDir") err := runDockerCp(c, srcPath, dstDir, nil) - c.Assert(err, checker.NotNil) + assert.ErrorContains(c, err, "") c.Assert(isCpDirNotExist(err), checker.True, check.Commentf("expected DirNotExists error, but got %T: %s", err, err)) } @@ -285,7 +286,7 @@ func (s *DockerSuite) TestCpToCaseF(c *check.C) { dstFile := containerCpPath(containerID, "/root/file1") err := runDockerCp(c, srcDir, dstFile, nil) - c.Assert(err, checker.NotNil) + assert.ErrorContains(c, err, "") c.Assert(isCpCannotCopyDir(err), checker.True, check.Commentf("expected ErrCannotCopyDir error, but got %T: %s", err, err)) } @@ -390,7 +391,7 @@ func (s *DockerSuite) TestCpToCaseI(c *check.C) { dstFile := containerCpPath(containerID, "/root/file1") err := runDockerCp(c, srcDir, dstFile, nil) - c.Assert(err, checker.NotNil) + assert.ErrorContains(c, err, "") c.Assert(isCpCannotCopyDir(err), checker.True, check.Commentf("expected ErrCannotCopyDir error, but got %T: %s", err, err)) } @@ -459,7 +460,7 @@ func (s *DockerSuite) TestCpToErrReadOnlyRootfs(c *check.C) { dstPath := containerCpPath(containerID, "/root/shouldNotExist") err := runDockerCp(c, srcPath, dstPath, nil) - c.Assert(err, checker.NotNil) + assert.ErrorContains(c, err, "") c.Assert(isCpCannotCopyReadOnly(err), checker.True, check.Commentf("expected ErrContainerRootfsReadonly error, but got %T: %s", err, err)) @@ -486,7 +487,7 @@ func (s *DockerSuite) TestCpToErrReadOnlyVolume(c *check.C) { dstPath := containerCpPath(containerID, "/vol_ro/shouldNotExist") err := runDockerCp(c, srcPath, dstPath, nil) - c.Assert(err, checker.NotNil) + assert.ErrorContains(c, err, "") c.Assert(isCpCannotCopyReadOnly(err), checker.True, check.Commentf("expected ErrVolumeReadonly error, but got %T: %s", err, err)) diff --git a/components/engine/integration-cli/docker_cli_cp_to_container_unix_test.go b/components/engine/integration-cli/docker_cli_cp_to_container_unix_test.go index ef1ad7de32..bbf0040f12 100644 --- a/components/engine/integration-cli/docker_cli_cp_to_container_unix_test.go +++ b/components/engine/integration-cli/docker_cli_cp_to_container_unix_test.go @@ -9,9 +9,9 @@ import ( "strconv" "strings" - "github.com/docker/docker/integration-cli/checker" "github.com/docker/docker/pkg/system" "github.com/go-check/check" + "gotest.tools/assert" ) func (s *DockerSuite) TestCpToContainerWithPermissions(c *check.C) { @@ -25,16 +25,16 @@ func (s *DockerSuite) TestCpToContainerWithPermissions(c *check.C) { containerName := "permtest" _, exc := dockerCmd(c, "create", "--name", containerName, "debian:jessie", "/bin/bash", "-c", "stat -c '%u %g %a' /permdirtest /permdirtest/permtest") - c.Assert(exc, checker.Equals, 0) + assert.Equal(c, exc, 0) defer dockerCmd(c, "rm", "-f", containerName) srcPath := cpPath(tmpDir, "permdirtest") dstPath := containerCpPath(containerName, "/") - c.Assert(runDockerCp(c, srcPath, dstPath, []string{"-a"}), checker.IsNil) + assert.NilError(c, runDockerCp(c, srcPath, dstPath, []string{"-a"})) out, err := startContainerGetOutput(c, containerName) - c.Assert(err, checker.IsNil, check.Commentf("output: %v", out)) - c.Assert(strings.TrimSpace(out), checker.Equals, "2 2 700\n65534 65534 400", check.Commentf("output: %v", out)) + assert.NilError(c, err, "output: %v", out) + assert.Equal(c, strings.TrimSpace(out), "2 2 700\n65534 65534 400", "output: %v", out) } // Check ownership is root, both in non-userns and userns enabled modes @@ -53,14 +53,14 @@ func (s *DockerSuite) TestCpCheckDestOwnership(c *check.C) { dstPath := containerCpPath(containerID, "/tmpvol", "file1") err := runDockerCp(c, srcPath, dstPath, nil) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) stat, err := system.Stat(filepath.Join(tmpVolDir, "file1")) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) uid, gid, err := getRootUIDGID() - c.Assert(err, checker.IsNil) - c.Assert(stat.UID(), checker.Equals, uint32(uid), check.Commentf("Copied file not owned by container root UID")) - c.Assert(stat.GID(), checker.Equals, uint32(gid), check.Commentf("Copied file not owned by container root GID")) + assert.NilError(c, err) + assert.Equal(c, stat.UID(), uint32(uid), "Copied file not owned by container root UID") + assert.Equal(c, stat.GID(), uint32(gid), "Copied file not owned by container root GID") } func getRootUIDGID() (int, int, error) { diff --git a/components/engine/integration-cli/docker_cli_cp_utils_test.go b/components/engine/integration-cli/docker_cli_cp_utils_test.go index 3b540ae3fd..3215c8f9d4 100644 --- a/components/engine/integration-cli/docker_cli_cp_utils_test.go +++ b/components/engine/integration-cli/docker_cli_cp_utils_test.go @@ -10,9 +10,9 @@ import ( "runtime" "strings" - "github.com/docker/docker/integration-cli/checker" "github.com/docker/docker/pkg/archive" "github.com/go-check/check" + "gotest.tools/assert" ) type fileType uint32 @@ -97,15 +97,15 @@ func makeTestContentInDir(c *check.C, dir string) { path := filepath.Join(dir, filepath.FromSlash(fd.path)) switch fd.filetype { case ftRegular: - c.Assert(ioutil.WriteFile(path, []byte(fd.contents+"\n"), os.FileMode(fd.mode)), checker.IsNil) + assert.NilError(c, ioutil.WriteFile(path, []byte(fd.contents+"\n"), os.FileMode(fd.mode))) case ftDir: - c.Assert(os.Mkdir(path, os.FileMode(fd.mode)), checker.IsNil) + assert.NilError(c, os.Mkdir(path, os.FileMode(fd.mode))) case ftSymlink: - c.Assert(os.Symlink(fd.contents, path), checker.IsNil) + assert.NilError(c, os.Symlink(fd.contents, path)) } if fd.filetype != ftSymlink && runtime.GOOS != "windows" { - c.Assert(os.Chown(path, fd.uid, fd.gid), checker.IsNil) + assert.NilError(c, os.Chown(path, fd.uid, fd.gid)) } } } @@ -158,7 +158,7 @@ func makeTestContainer(c *check.C, options testContainerOptions) (containerID st if exitCode != "0" { out, _ = dockerCmd(c, "logs", containerID) } - c.Assert(exitCode, checker.Equals, "0", check.Commentf("failed to make test container: %s", out)) + assert.Equal(c, exitCode, "0", "failed to make test container: %s", out) return } @@ -223,7 +223,7 @@ func getTestDir(c *check.C, label string) (tmpDir string) { tmpDir, err = ioutil.TempDir("", label) // unable to make temporary directory - c.Assert(err, checker.IsNil) + assert.NilError(c, err) return } diff --git a/components/engine/integration-cli/docker_cli_create_test.go b/components/engine/integration-cli/docker_cli_create_test.go index dbdf92915c..2b1681d32b 100644 --- a/components/engine/integration-cli/docker_cli_create_test.go +++ b/components/engine/integration-cli/docker_cli_create_test.go @@ -15,6 +15,8 @@ import ( "github.com/docker/docker/pkg/stringid" "github.com/docker/go-connections/nat" "github.com/go-check/check" + "gotest.tools/assert" + is "gotest.tools/assert/cmp" ) // Make sure we can create a simple container with some args @@ -36,7 +38,7 @@ func (s *DockerSuite) TestCreateArgs(c *check.C) { err := json.Unmarshal([]byte(out), &containers) c.Assert(err, check.IsNil, check.Commentf("Error inspecting the container: %s", err)) - c.Assert(containers, checker.HasLen, 1) + assert.Equal(c, len(containers), 1) cont := containers[0] c.Assert(string(cont.Path), checker.Equals, "command", check.Commentf("Unexpected container path. Expected command, received: %s", cont.Path)) @@ -75,7 +77,7 @@ func (s *DockerSuite) TestCreateShrinkRootfs(c *check.C) { // Ensure this fails because of the defaultBaseFsSize is 10G out, _, err := dockerCmdWithError("create", "--storage-opt", "size=5G", "busybox") - c.Assert(err, check.NotNil, check.Commentf("%s", out)) + assert.ErrorContains(c, err, "", out) c.Assert(out, checker.Contains, "Container size cannot be smaller than") } @@ -95,7 +97,7 @@ func (s *DockerSuite) TestCreateHostConfig(c *check.C) { err := json.Unmarshal([]byte(out), &containers) c.Assert(err, check.IsNil, check.Commentf("Error inspecting the container: %s", err)) - c.Assert(containers, checker.HasLen, 1) + assert.Equal(c, len(containers), 1) cont := containers[0] c.Assert(cont.HostConfig, check.NotNil, check.Commentf("Expected HostConfig, got none")) @@ -116,7 +118,7 @@ func (s *DockerSuite) TestCreateWithPortRange(c *check.C) { } err := json.Unmarshal([]byte(out), &containers) c.Assert(err, check.IsNil, check.Commentf("Error inspecting the container: %s", err)) - c.Assert(containers, checker.HasLen, 1) + assert.Equal(c, len(containers), 1) cont := containers[0] @@ -146,7 +148,7 @@ func (s *DockerSuite) TestCreateWithLargePortRange(c *check.C) { err := json.Unmarshal([]byte(out), &containers) c.Assert(err, check.IsNil, check.Commentf("Error inspecting the container: %s", err)) - c.Assert(containers, checker.HasLen, 1) + assert.Equal(c, len(containers), 1) cont := containers[0] c.Assert(cont.HostConfig, check.NotNil, check.Commentf("Expected HostConfig, got none")) @@ -166,8 +168,7 @@ func (s *DockerSuite) TestCreateEchoStdout(c *check.C) { cleanedContainerID := strings.TrimSpace(out) out, _ = dockerCmd(c, "start", "-ai", cleanedContainerID) - c.Assert(out, checker.Equals, "test123\n", check.Commentf("container should've printed 'test123', got %q", out)) - + assert.Equal(c, out, "test123\n", "container should've printed 'test123', got %q", out) } func (s *DockerSuite) TestCreateVolumesCreated(c *check.C) { @@ -226,8 +227,7 @@ func (s *DockerSuite) TestCreateHostnameWithNumber(c *check.C) { image = testEnv.PlatformDefaults.BaseImage } out, _ := dockerCmd(c, "run", "-h", "web.0", image, "hostname") - c.Assert(strings.TrimSpace(out), checker.Equals, "web.0", check.Commentf("hostname not set, expected `web.0`, got: %s", out)) - + assert.Equal(c, strings.TrimSpace(out), "web.0", "hostname not set, expected `web.0`, got: %s", out) } func (s *DockerSuite) TestCreateRM(c *check.C) { @@ -316,8 +316,9 @@ func (s *DockerSuite) TestCreateWithWorkdir(c *check.C) { func (s *DockerSuite) TestCreateWithInvalidLogOpts(c *check.C) { name := "test-invalidate-log-opts" out, _, err := dockerCmdWithError("create", "--name", name, "--log-opt", "invalid=true", "busybox") - c.Assert(err, checker.NotNil) + assert.ErrorContains(c, err, "") c.Assert(out, checker.Contains, "unknown log opt") + assert.Assert(c, is.Contains(out, "unknown log opt")) out, _ = dockerCmd(c, "ps", "-a") c.Assert(out, checker.Not(checker.Contains), name) diff --git a/components/engine/integration-cli/docker_cli_daemon_plugins_test.go b/components/engine/integration-cli/docker_cli_daemon_plugins_test.go index 000981d002..355313f013 100644 --- a/components/engine/integration-cli/docker_cli_daemon_plugins_test.go +++ b/components/engine/integration-cli/docker_cli_daemon_plugins_test.go @@ -5,10 +5,10 @@ package main import ( "strings" - "github.com/docker/docker/integration-cli/checker" "github.com/docker/docker/pkg/mount" "github.com/go-check/check" "golang.org/x/sys/unix" + "gotest.tools/assert" "gotest.tools/icmd" ) @@ -37,8 +37,8 @@ func (s *DockerDaemonSuite) TestDaemonRestartWithPluginEnabled(c *check.C) { if err != nil { c.Fatalf("Could not list plugins: %v %s", err, out) } - c.Assert(out, checker.Contains, pName) - c.Assert(out, checker.Contains, "true") + assert.Assert(c, strings.Contains(out, pName)) + assert.Assert(c, strings.Contains(out, "true")) } // TestDaemonRestartWithPluginDisabled tests state restore for a disabled plugin @@ -63,8 +63,8 @@ func (s *DockerDaemonSuite) TestDaemonRestartWithPluginDisabled(c *check.C) { if err != nil { c.Fatalf("Could not list plugins: %v %s", err, out) } - c.Assert(out, checker.Contains, pName) - c.Assert(out, checker.Contains, "false") + assert.Assert(c, strings.Contains(out, pName)) + assert.Assert(c, strings.Contains(out, "false")) } // TestDaemonKillLiveRestoreWithPlugins SIGKILLs daemon started with --live-restore. @@ -221,14 +221,14 @@ func (s *DockerDaemonSuite) TestVolumePlugin(c *check.C) { if err != nil { c.Fatalf("Could not list volume: %v %s", err, out) } - c.Assert(out, checker.Contains, volName) - c.Assert(out, checker.Contains, pName) + assert.Assert(c, strings.Contains(out, volName)) + assert.Assert(c, strings.Contains(out, pName)) out, err = s.d.Cmd("run", "--rm", "-v", volName+":"+destDir, "busybox", "touch", destDir+destFile) - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) out, err = s.d.Cmd("run", "--rm", "-v", volName+":"+destDir, "busybox", "ls", destDir+destFile) - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) } func (s *DockerDaemonSuite) TestPluginVolumeRemoveOnRestart(c *check.C) { @@ -237,26 +237,26 @@ func (s *DockerDaemonSuite) TestPluginVolumeRemoveOnRestart(c *check.C) { s.d.Start(c, "--live-restore=true") out, err := s.d.Cmd("plugin", "install", "--grant-all-permissions", pName) - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) - c.Assert(strings.TrimSpace(out), checker.Contains, pName) + assert.NilError(c, err, out) + assert.Assert(c, strings.Contains(out, pName)) out, err = s.d.Cmd("volume", "create", "--driver", pName, "test") - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) s.d.Restart(c, "--live-restore=true") out, err = s.d.Cmd("plugin", "disable", pName) - c.Assert(err, checker.NotNil, check.Commentf("%s", out)) - c.Assert(out, checker.Contains, "in use") + assert.ErrorContains(c, err, "", out) + assert.Assert(c, strings.Contains(out, "in use")) out, err = s.d.Cmd("volume", "rm", "test") - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) out, err = s.d.Cmd("plugin", "disable", pName) - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) out, err = s.d.Cmd("plugin", "rm", pName) - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) } func existsMountpointWithPrefix(mountpointPrefix string) (bool, error) { @@ -278,7 +278,7 @@ func (s *DockerDaemonSuite) TestPluginListFilterEnabled(c *check.C) { s.d.Start(c) out, err := s.d.Cmd("plugin", "install", "--grant-all-permissions", pNameWithTag, "--disable") - c.Assert(err, check.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) defer func() { if out, err := s.d.Cmd("plugin", "remove", pNameWithTag); err != nil { @@ -287,17 +287,17 @@ func (s *DockerDaemonSuite) TestPluginListFilterEnabled(c *check.C) { }() out, err = s.d.Cmd("plugin", "ls", "--filter", "enabled=true") - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) - c.Assert(out, checker.Not(checker.Contains), pName) + assert.NilError(c, err, out) + assert.Assert(c, !strings.Contains(out, pName)) out, err = s.d.Cmd("plugin", "ls", "--filter", "enabled=false") - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) - c.Assert(out, checker.Contains, pName) - c.Assert(out, checker.Contains, "false") + assert.NilError(c, err, out) + assert.Assert(c, strings.Contains(out, pName)) + assert.Assert(c, strings.Contains(out, "false")) out, err = s.d.Cmd("plugin", "ls") - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) - c.Assert(out, checker.Contains, pName) + assert.NilError(c, err, out) + assert.Assert(c, strings.Contains(out, pName)) } func (s *DockerDaemonSuite) TestPluginListFilterCapability(c *check.C) { @@ -306,7 +306,7 @@ func (s *DockerDaemonSuite) TestPluginListFilterCapability(c *check.C) { s.d.Start(c) out, err := s.d.Cmd("plugin", "install", "--grant-all-permissions", pNameWithTag, "--disable") - c.Assert(err, check.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) defer func() { if out, err := s.d.Cmd("plugin", "remove", pNameWithTag); err != nil { @@ -315,14 +315,14 @@ func (s *DockerDaemonSuite) TestPluginListFilterCapability(c *check.C) { }() out, err = s.d.Cmd("plugin", "ls", "--filter", "capability=volumedriver") - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) - c.Assert(out, checker.Contains, pName) + assert.NilError(c, err, out) + assert.Assert(c, strings.Contains(out, pName)) out, err = s.d.Cmd("plugin", "ls", "--filter", "capability=authz") - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) - c.Assert(out, checker.Not(checker.Contains), pName) + assert.NilError(c, err, out) + assert.Assert(c, !strings.Contains(out, pName)) out, err = s.d.Cmd("plugin", "ls") - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) - c.Assert(out, checker.Contains, pName) + assert.NilError(c, err, out) + assert.Assert(c, strings.Contains(out, pName)) } diff --git a/components/engine/integration-cli/docker_cli_daemon_test.go b/components/engine/integration-cli/docker_cli_daemon_test.go index 1387a39a2d..d1a709b736 100644 --- a/components/engine/integration-cli/docker_cli_daemon_test.go +++ b/components/engine/integration-cli/docker_cli_daemon_test.go @@ -39,6 +39,7 @@ import ( "github.com/go-check/check" "github.com/kr/pty" "golang.org/x/sys/unix" + "gotest.tools/assert" "gotest.tools/icmd" ) @@ -50,9 +51,8 @@ func (s *DockerDaemonSuite) TestLegacyDaemonCommand(c *check.C) { cmd := exec.Command(dockerBinary, "daemon", "--storage-driver=vfs", "--debug") err := cmd.Start() go cmd.Wait() - c.Assert(err, checker.IsNil, check.Commentf("could not start daemon using 'docker daemon'")) - - c.Assert(cmd.Process.Kill(), checker.IsNil) + assert.NilError(c, err, "could not start daemon using 'docker daemon'") + assert.NilError(c, cmd.Process.Kill()) } func (s *DockerDaemonSuite) TestDaemonRestartWithRunningContainersPorts(c *check.C) { @@ -107,7 +107,7 @@ func (s *DockerDaemonSuite) TestDaemonRestartWithVolumesRefs(c *check.C) { } out, err := s.d.Cmd("inspect", "-f", "{{json .Mounts}}", "volrestarttest1") - c.Assert(err, check.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) if _, err := inspectMountPointJSON(out, "/foo"); err != nil { c.Fatalf("Expected volume to exist: /foo, error: %v\n", err) @@ -119,10 +119,10 @@ func (s *DockerDaemonSuite) TestDaemonRestartUnlessStopped(c *check.C) { s.d.StartWithBusybox(c) out, err := s.d.Cmd("run", "-d", "--name", "top1", "--restart", "always", "busybox:latest", "top") - c.Assert(err, check.IsNil, check.Commentf("run top1: %v", out)) + assert.NilError(c, err, "run top1: %v", out) out, err = s.d.Cmd("run", "-d", "--name", "top2", "--restart", "unless-stopped", "busybox:latest", "top") - c.Assert(err, check.IsNil, check.Commentf("run top2: %v", out)) + assert.NilError(c, err, "run top2: %v", out) testRun := func(m map[string]bool, prefix string) { var format string @@ -142,10 +142,10 @@ func (s *DockerDaemonSuite) TestDaemonRestartUnlessStopped(c *check.C) { testRun(map[string]bool{"top1": true, "top2": true}, "") out, err = s.d.Cmd("stop", "top1") - c.Assert(err, check.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) out, err = s.d.Cmd("stop", "top2") - c.Assert(err, check.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) // both stopped testRun(map[string]bool{"top1": false, "top2": false}, "") @@ -156,7 +156,7 @@ func (s *DockerDaemonSuite) TestDaemonRestartUnlessStopped(c *check.C) { testRun(map[string]bool{"top1": true, "top2": false}, "After daemon restart: ") out, err = s.d.Cmd("start", "top2") - c.Assert(err, check.IsNil, check.Commentf("start top2: %v", out)) + assert.NilError(c, err, "start top2: %v", out) s.d.Restart(c) @@ -169,29 +169,29 @@ func (s *DockerDaemonSuite) TestDaemonRestartOnFailure(c *check.C) { s.d.StartWithBusybox(c) out, err := s.d.Cmd("run", "-d", "--name", "test1", "--restart", "on-failure:3", "busybox:latest", "false") - c.Assert(err, check.IsNil, check.Commentf("run top1: %v", out)) + assert.NilError(c, err, "run top1: %v", out) // wait test1 to stop hostArgs := []string{"--host", s.d.Sock()} err = waitInspectWithArgs("test1", "{{.State.Running}} {{.State.Restarting}}", "false false", 10*time.Second, hostArgs...) - c.Assert(err, checker.IsNil, check.Commentf("test1 should exit but not")) + assert.NilError(c, err, "test1 should exit but not") // record last start time out, err = s.d.Cmd("inspect", "-f={{.State.StartedAt}}", "test1") - c.Assert(err, checker.IsNil, check.Commentf("out: %v", out)) + assert.NilError(c, err, "out: %v", out) lastStartTime := out s.d.Restart(c) // test1 shouldn't restart at all err = waitInspectWithArgs("test1", "{{.State.Running}} {{.State.Restarting}}", "false false", 0, hostArgs...) - c.Assert(err, checker.IsNil, check.Commentf("test1 should exit but not")) + assert.NilError(c, err, "test1 should exit but not") // make sure test1 isn't restarted when daemon restart // if "StartAt" time updates, means test1 was once restarted. out, err = s.d.Cmd("inspect", "-f={{.State.StartedAt}}", "test1") - c.Assert(err, checker.IsNil, check.Commentf("out: %v", out)) - c.Assert(out, checker.Equals, lastStartTime, check.Commentf("test1 shouldn't start after daemon restarts")) + assert.NilError(c, err, "out: %v", out) + assert.Equal(c, out, lastStartTime, "test1 shouldn't start after daemon restarts") } func (s *DockerDaemonSuite) TestDaemonStartIptablesFalse(c *check.C) { @@ -255,7 +255,7 @@ func getBaseDeviceSize(c *check.C, d *daemon.Daemon) int64 { func parseDeviceSize(c *check.C, raw string) int64 { size, err := units.RAMInBytes(strings.TrimSpace(raw)) - c.Assert(err, check.IsNil) + assert.NilError(c, err) return size } @@ -419,17 +419,17 @@ func (s *DockerDaemonSuite) TestDaemonIPv6FixedCIDR(c *check.C) { s.d.StartWithBusybox(c, "--ipv6", "--fixed-cidr-v6=2001:db8:2::/64", "--default-gateway-v6=2001:db8:2::100") out, err := s.d.Cmd("run", "-itd", "--name=ipv6test", "busybox:latest") - c.Assert(err, checker.IsNil, check.Commentf("Could not run container: %s, %v", out, err)) + assert.NilError(c, err, "Could not run container: %s, %v", out, err) out, err = s.d.Cmd("inspect", "--format", "{{.NetworkSettings.Networks.bridge.GlobalIPv6Address}}", "ipv6test") - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) out = strings.Trim(out, " \r\n'") ip := net.ParseIP(out) c.Assert(ip, checker.NotNil, check.Commentf("Container should have a global IPv6 address")) out, err = s.d.Cmd("inspect", "--format", "{{.NetworkSettings.Networks.bridge.IPv6Gateway}}", "ipv6test") - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) c.Assert(strings.Trim(out, " \r\n'"), checker.Equals, "2001:db8:2::100", check.Commentf("Container should have a global IPv6 gateway")) } @@ -446,10 +446,10 @@ func (s *DockerDaemonSuite) TestDaemonIPv6FixedCIDRAndMac(c *check.C) { s.d.StartWithBusybox(c, "--ipv6", "--fixed-cidr-v6=2001:db8:1::/64") out, err := s.d.Cmd("run", "-itd", "--name=ipv6test", "--mac-address", "AA:BB:CC:DD:EE:FF", "busybox") - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) out, err = s.d.Cmd("inspect", "--format", "{{.NetworkSettings.Networks.bridge.GlobalIPv6Address}}", "ipv6test") - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) c.Assert(strings.Trim(out, " \r\n'"), checker.Equals, "2001:db8:1::aabb:ccdd:eeff") } @@ -461,10 +461,10 @@ func (s *DockerDaemonSuite) TestDaemonIPv6HostMode(c *check.C) { s.d.StartWithBusybox(c, "--ipv6", "--fixed-cidr-v6=2001:db8:2::/64") out, err := s.d.Cmd("run", "-itd", "--name=hostcnt", "--network=host", "busybox:latest") - c.Assert(err, checker.IsNil, check.Commentf("Could not run container: %s, %v", out, err)) + assert.NilError(c, err, "Could not run container: %s, %v", out, err) out, err = s.d.Cmd("exec", "hostcnt", "ip", "-6", "addr", "show", "docker0") - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) c.Assert(strings.Trim(out, " \r\n'"), checker.Contains, "2001:db8:2::1") } @@ -475,7 +475,7 @@ func (s *DockerDaemonSuite) TestDaemonLogLevelWrong(c *check.C) { func (s *DockerDaemonSuite) TestDaemonLogLevelDebug(c *check.C) { s.d.Start(c, "--log-level=debug") content, err := s.d.ReadLogFile() - c.Assert(err, checker.IsNil) + assert.NilError(c, err) if !strings.Contains(string(content), `level=debug`) { c.Fatalf(`Missing level="debug" in log file:\n%s`, string(content)) } @@ -485,7 +485,7 @@ func (s *DockerDaemonSuite) TestDaemonLogLevelFatal(c *check.C) { // we creating new daemons to create new logFile s.d.Start(c, "--log-level=fatal") content, err := s.d.ReadLogFile() - c.Assert(err, checker.IsNil) + assert.NilError(c, err) if strings.Contains(string(content), `level=debug`) { c.Fatalf(`Should not have level="debug" in log file:\n%s`, string(content)) } @@ -494,7 +494,7 @@ func (s *DockerDaemonSuite) TestDaemonLogLevelFatal(c *check.C) { func (s *DockerDaemonSuite) TestDaemonFlagD(c *check.C) { s.d.Start(c, "-D") content, err := s.d.ReadLogFile() - c.Assert(err, checker.IsNil) + assert.NilError(c, err) if !strings.Contains(string(content), `level=debug`) { c.Fatalf(`Should have level="debug" in log file using -D:\n%s`, string(content)) } @@ -503,7 +503,7 @@ func (s *DockerDaemonSuite) TestDaemonFlagD(c *check.C) { func (s *DockerDaemonSuite) TestDaemonFlagDebug(c *check.C) { s.d.Start(c, "--debug") content, err := s.d.ReadLogFile() - c.Assert(err, checker.IsNil) + assert.NilError(c, err) if !strings.Contains(string(content), `level=debug`) { c.Fatalf(`Should have level="debug" in log file using --debug:\n%s`, string(content)) } @@ -512,7 +512,7 @@ func (s *DockerDaemonSuite) TestDaemonFlagDebug(c *check.C) { func (s *DockerDaemonSuite) TestDaemonFlagDebugLogLevelFatal(c *check.C) { s.d.Start(c, "--debug", "--log-level=fatal") content, err := s.d.ReadLogFile() - c.Assert(err, checker.IsNil) + assert.NilError(c, err) if !strings.Contains(string(content), `level=debug`) { c.Fatalf(`Should have level="debug" in log file when using both --debug and --log-level=fatal:\n%s`, string(content)) } @@ -580,7 +580,7 @@ func (s *DockerDaemonSuite) TestDaemonExitOnFailure(c *check.C) { func (s *DockerDaemonSuite) TestDaemonBridgeExternal(c *check.C) { d := s.d err := d.StartWithError("--bridge", "nosuchbridge") - c.Assert(err, check.NotNil, check.Commentf("--bridge option with an invalid bridge should cause the daemon to fail")) + assert.ErrorContains(c, err, "", `--bridge option with an invalid bridge should cause the daemon to fail`) defer d.Restart(c) bridgeName := "external-bridge" @@ -598,13 +598,11 @@ func (s *DockerDaemonSuite) TestDaemonBridgeExternal(c *check.C) { }) out, err := d.Cmd("run", "-d", "--name", "ExtContainer", "busybox", "top") - c.Assert(err, check.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) containerIP := d.FindContainerIP(c, "ExtContainer") ip := net.ParseIP(containerIP) - c.Assert(bridgeIPNet.Contains(ip), check.Equals, true, - check.Commentf("Container IP-Address must be in the same subnet range : %s", - containerIP)) + assert.Assert(c, bridgeIPNet.Contains(ip), "Container IP-Address must be in the same subnet range : %s", containerIP) } func (s *DockerDaemonSuite) TestDaemonBridgeNone(c *check.C) { @@ -622,8 +620,8 @@ func (s *DockerDaemonSuite) TestDaemonBridgeNone(c *check.C) { // verify default "bridge" network is not there out, err := d.Cmd("network", "inspect", "bridge") - c.Assert(err, check.NotNil, check.Commentf("\"bridge\" network should not be present if daemon started with --bridge=none")) - c.Assert(strings.Contains(out, "No such network"), check.Equals, true) + assert.ErrorContains(c, err, "", `"bridge" network should not be present if daemon started with --bridge=none`) + assert.Assert(c, strings.Contains(out, "No such network")) } func createInterface(c *check.C, ifType string, ifName string, ipNet string) { @@ -669,7 +667,7 @@ func (s *DockerDaemonSuite) TestDaemonBridgeIP(c *check.C) { }) out, err := d.Cmd("run", "-d", "--name", "test", "busybox", "top") - c.Assert(err, check.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) containerIP := d.FindContainerIP(c, "test") ip = net.ParseIP(containerIP) @@ -716,8 +714,7 @@ func (s *DockerDaemonSuite) TestDaemonBridgeFixedCidr(c *check.C) { cName := "Container" + strconv.Itoa(i) out, err := d.Cmd("run", "-d", "--name", cName, "busybox", "top") if err != nil { - c.Assert(strings.Contains(out, "no available IPv4 addresses"), check.Equals, true, - check.Commentf("Could not run a Container : %s %s", err.Error(), out)) + assert.Assert(c, strings.Contains(out, "no available IPv4 addresses"), "Could not run a Container : %s %s", err.Error(), out) } } } @@ -735,16 +732,16 @@ func (s *DockerDaemonSuite) TestDaemonBridgeFixedCidr2(c *check.C) { defer s.d.Restart(c) out, err := d.Cmd("run", "-d", "--name", "bb", "busybox", "top") - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) defer d.Cmd("stop", "bb") out, err = d.Cmd("exec", "bb", "/bin/sh", "-c", "ifconfig eth0 | awk '/inet addr/{print substr($2,6)}'") - c.Assert(err, check.IsNil) - c.Assert(out, checker.Equals, "10.2.2.0\n") + assert.NilError(c, err) + assert.Equal(c, out, "10.2.2.0\n") out, err = d.Cmd("run", "--rm", "busybox", "/bin/sh", "-c", "ifconfig eth0 | awk '/inet addr/{print substr($2,6)}'") - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) - c.Assert(out, checker.Equals, "10.2.2.2\n") + assert.NilError(c, err, out) + assert.Equal(c, out, "10.2.2.2\n") } func (s *DockerDaemonSuite) TestDaemonBridgeFixedCIDREqualBridgeNetwork(c *check.C) { @@ -760,7 +757,7 @@ func (s *DockerDaemonSuite) TestDaemonBridgeFixedCIDREqualBridgeNetwork(c *check defer s.d.Restart(c) out, err := d.Cmd("run", "-d", "busybox", "top") - c.Assert(err, check.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) cid1 := strings.TrimSpace(out) defer d.Cmd("stop", cid1) } @@ -779,7 +776,7 @@ func (s *DockerDaemonSuite) TestDaemonDefaultGatewayIPv4Implicit(c *check.C) { expectedMessage := fmt.Sprintf("default via %s dev", bridgeIP) out, err := d.Cmd("run", "busybox", "ip", "-4", "route", "list", "0/0") - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) c.Assert(strings.Contains(out, expectedMessage), check.Equals, true, check.Commentf("Implicit default gateway should be bridge IP %s, but default route was '%s'", bridgeIP, strings.TrimSpace(out))) @@ -801,7 +798,7 @@ func (s *DockerDaemonSuite) TestDaemonDefaultGatewayIPv4Explicit(c *check.C) { expectedMessage := fmt.Sprintf("default via %s dev", gatewayIP) out, err := d.Cmd("run", "busybox", "ip", "-4", "route", "list", "0/0") - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) c.Assert(strings.Contains(out, expectedMessage), check.Equals, true, check.Commentf("Explicit default gateway should be %s, but default route was '%s'", gatewayIP, strings.TrimSpace(out))) @@ -855,7 +852,7 @@ func (s *DockerDaemonSuite) TestDaemonIP(c *check.C) { defer deleteInterface(c, ifName) _, err = d.Cmd("run", "-d", "-p", "8000:8000", "busybox", "top") - c.Assert(err, check.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) result := icmd.RunCommand("iptables", "-t", "nat", "-nvL") result.Assert(c, icmd.Success) @@ -898,7 +895,7 @@ func (s *DockerDaemonSuite) TestDaemonICCPing(c *check.C) { pingCmd := fmt.Sprintf("ping -c 1 %s -W 1", ip.String()) runArgs := []string{"run", "--rm", "busybox", "sh", "-c", pingCmd} out, err := d.Cmd(runArgs...) - c.Assert(err, check.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) } func (s *DockerDaemonSuite) TestDaemonICCLinkExpose(c *check.C) { @@ -921,10 +918,10 @@ func (s *DockerDaemonSuite) TestDaemonICCLinkExpose(c *check.C) { check.Commentf("iptables output should have contained %q, but was %q", regex, result.Combined())) out, err := d.Cmd("run", "-d", "--expose", "4567", "--name", "icc1", "busybox", "nc", "-l", "-p", "4567") - c.Assert(err, check.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) out, err = d.Cmd("run", "--link", "icc1:icc1", "busybox", "nc", "icc1", "4567") - c.Assert(err, check.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) } func (s *DockerDaemonSuite) TestDaemonLinksIpTablesRulesWhenLinkAndUnlink(c *check.C) { @@ -938,9 +935,9 @@ func (s *DockerDaemonSuite) TestDaemonLinksIpTablesRulesWhenLinkAndUnlink(c *che defer s.d.Restart(c) out, err := s.d.Cmd("run", "-d", "--name", "child", "--publish", "8080:80", "busybox", "top") - c.Assert(err, check.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) out, err = s.d.Cmd("run", "-d", "--name", "parent", "--link", "child:http", "busybox", "top") - c.Assert(err, check.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) childIP := s.d.FindContainerIP(c, "child") parentIP := s.d.FindContainerIP(c, "parent") @@ -1030,9 +1027,9 @@ func (s *DockerDaemonSuite) TestDaemonLoggingDriverDefault(c *check.C) { s.d.StartWithBusybox(c) out, err := s.d.Cmd("run", "--name=test", "busybox", "echo", "testline") - c.Assert(err, check.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) id, err := s.d.GetIDByName("test") - c.Assert(err, check.IsNil) + assert.NilError(c, err) logPath := filepath.Join(s.d.Root, "containers", id, id+"-json.log") @@ -1072,7 +1069,7 @@ func (s *DockerDaemonSuite) TestDaemonLoggingDriverDefaultOverride(c *check.C) { c.Fatal(out, err) } id, err := s.d.GetIDByName("test") - c.Assert(err, check.IsNil) + assert.NilError(c, err) logPath := filepath.Join(s.d.Root, "containers", id, id+"-json.log") @@ -1089,7 +1086,7 @@ func (s *DockerDaemonSuite) TestDaemonLoggingDriverNone(c *check.C) { c.Fatal(out, err) } id, err := s.d.GetIDByName("test") - c.Assert(err, check.IsNil) + assert.NilError(c, err) logPath := filepath.Join(s.d.Root, "containers", id, id+"-json.log") @@ -1106,7 +1103,7 @@ func (s *DockerDaemonSuite) TestDaemonLoggingDriverNoneOverride(c *check.C) { c.Fatal(out, err) } id, err := s.d.GetIDByName("test") - c.Assert(err, check.IsNil) + assert.NilError(c, err) logPath := filepath.Join(s.d.Root, "containers", id, id+"-json.log") @@ -1142,12 +1139,12 @@ func (s *DockerDaemonSuite) TestDaemonLoggingDriverNoneLogsError(c *check.C) { s.d.StartWithBusybox(c, "--log-driver=none") out, err := s.d.Cmd("run", "--name=test", "busybox", "echo", "testline") - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) out, err = s.d.Cmd("logs", "test") c.Assert(err, check.NotNil, check.Commentf("Logs should fail with 'none' driver")) expected := `configured logging driver does not support reading` - c.Assert(out, checker.Contains, expected) + assert.Assert(c, strings.Contains(out, expected)) } func (s *DockerDaemonSuite) TestDaemonLoggingDriverShouldBeIgnoredForBuild(c *check.C) { @@ -1406,9 +1403,9 @@ func pingContainers(c *check.C, d *daemon.Daemon, expectFailure bool) { _, _, err := dockerCmdWithError(args...) if expectFailure { - c.Assert(err, check.NotNil) + assert.ErrorContains(c, err, "") } else { - c.Assert(err, check.IsNil) + assert.NilError(c, err) } args = append(dargs, "rm", "-f", "container1") @@ -1421,7 +1418,7 @@ func (s *DockerDaemonSuite) TestDaemonRestartWithSocketAsVolume(c *check.C) { socket := filepath.Join(s.d.Folder, "docker.sock") out, err := s.d.Cmd("run", "--restart=always", "-v", socket+":/sock", "busybox") - c.Assert(err, check.IsNil, check.Commentf("Output: %s", out)) + assert.NilError(c, err, "Output: %s", out) s.d.Restart(c) } @@ -1432,21 +1429,22 @@ func (s *DockerDaemonSuite) TestCleanupMountsAfterDaemonAndContainerKill(c *chec d.StartWithBusybox(c) out, err := d.Cmd("run", "-d", "busybox", "top") - c.Assert(err, check.IsNil, check.Commentf("Output: %s", out)) + assert.NilError(c, err, "Output: %s", out) + id := strings.TrimSpace(out) // If there are no mounts with container id visible from the host // (as those are in container's own mount ns), there is nothing // to check here and the test should be skipped. mountOut, err := ioutil.ReadFile("/proc/self/mountinfo") - c.Assert(err, check.IsNil, check.Commentf("Output: %s", mountOut)) + assert.NilError(c, err, "Output: %s", mountOut) if !strings.Contains(string(mountOut), id) { d.Stop(c) c.Skip("no container mounts visible in host ns") } // kill the daemon - c.Assert(d.Kill(), check.IsNil) + assert.NilError(c, d.Kill()) // kill the container icmd.RunCommand(ctrBinary, "--address", containerdSocket, @@ -1457,9 +1455,8 @@ func (s *DockerDaemonSuite) TestCleanupMountsAfterDaemonAndContainerKill(c *chec // Now, container mounts should be gone. mountOut, err = ioutil.ReadFile("/proc/self/mountinfo") - c.Assert(err, check.IsNil, check.Commentf("Output: %s", mountOut)) - comment := check.Commentf("%s is still mounted from older daemon start:\nDaemon root repository %s\n%s", id, d.Root, mountOut) - c.Assert(strings.Contains(string(mountOut), id), check.Equals, false, comment) + assert.NilError(c, err, "Output: %s", mountOut) + assert.Assert(c, !strings.Contains(string(mountOut), id), "%s is still mounted from older daemon start:\nDaemon root repository %s\n%s", id, d.Root, mountOut) d.Stop(c) } @@ -1470,19 +1467,18 @@ func (s *DockerDaemonSuite) TestCleanupMountsAfterGracefulShutdown(c *check.C) { d.StartWithBusybox(c) out, err := d.Cmd("run", "-d", "busybox", "top") - c.Assert(err, check.IsNil, check.Commentf("Output: %s", out)) + assert.NilError(c, err, "Output: %s", out) id := strings.TrimSpace(out) // Send SIGINT and daemon should clean up - c.Assert(d.Signal(os.Interrupt), check.IsNil) + assert.NilError(c, d.Signal(os.Interrupt)) // Wait for the daemon to stop. - c.Assert(<-d.Wait, checker.IsNil) + assert.NilError(c, <-d.Wait) mountOut, err := ioutil.ReadFile("/proc/self/mountinfo") - c.Assert(err, check.IsNil, check.Commentf("Output: %s", mountOut)) + assert.NilError(c, err, "Output: %s", mountOut) - comment := check.Commentf("%s is still mounted from older daemon start:\nDaemon root repository %s\n%s", id, d.Root, mountOut) - c.Assert(strings.Contains(string(mountOut), id), check.Equals, false, comment) + assert.Assert(c, !strings.Contains(string(mountOut), id), "%s is still mounted from older daemon start:\nDaemon root repository %s\n%s", id, d.Root, mountOut) } func (s *DockerDaemonSuite) TestDaemonRestartWithContainerRunning(t *check.C) { @@ -1563,22 +1559,22 @@ func (s *DockerDaemonSuite) TestDaemonRestartWithContainerWithRestartPolicyAlway s.d.StartWithBusybox(c) out, err := s.d.Cmd("run", "-d", "--restart", "always", "busybox", "top") - c.Assert(err, check.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) id := strings.TrimSpace(out) out, err = s.d.Cmd("stop", id) - c.Assert(err, check.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) out, err = s.d.Cmd("wait", id) - c.Assert(err, check.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) out, err = s.d.Cmd("ps", "-q") - c.Assert(err, check.IsNil, check.Commentf("%s", out)) - c.Assert(out, check.Equals, "") + assert.NilError(c, err, out) + assert.Equal(c, out, "") s.d.Restart(c) out, err = s.d.Cmd("ps", "-q") - c.Assert(err, check.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) c.Assert(strings.TrimSpace(out), check.Equals, id[:12]) } @@ -1586,16 +1582,16 @@ func (s *DockerDaemonSuite) TestDaemonWideLogConfig(c *check.C) { s.d.StartWithBusybox(c, "--log-opt=max-size=1k") name := "logtest" out, err := s.d.Cmd("run", "-d", "--log-opt=max-file=5", "--name", name, "busybox", "top") - c.Assert(err, check.IsNil, check.Commentf("Output: %s, err: %v", out, err)) + assert.NilError(c, err, "Output: %s, err: %v", out, err) out, err = s.d.Cmd("inspect", "-f", "{{ .HostConfig.LogConfig.Config }}", name) - c.Assert(err, check.IsNil, check.Commentf("Output: %s", out)) - c.Assert(out, checker.Contains, "max-size:1k") - c.Assert(out, checker.Contains, "max-file:5") + assert.NilError(c, err, "Output: %s", out) + assert.Assert(c, strings.Contains(out, "max-size:1k")) + assert.Assert(c, strings.Contains(out, "max-file:5")) out, err = s.d.Cmd("inspect", "-f", "{{ .HostConfig.LogConfig.Type }}", name) - c.Assert(err, check.IsNil, check.Commentf("Output: %s", out)) - c.Assert(strings.TrimSpace(out), checker.Equals, "json-file") + assert.NilError(c, err, "Output: %s", out) + assert.Equal(c, strings.TrimSpace(out), "json-file") } func (s *DockerDaemonSuite) TestDaemonRestartWithPausedContainer(c *check.C) { @@ -1635,7 +1631,7 @@ func (s *DockerDaemonSuite) TestDaemonRestartRmVolumeInUse(c *check.C) { s.d.StartWithBusybox(c) out, err := s.d.Cmd("create", "-v", "test:/foo", "busybox") - c.Assert(err, check.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) s.d.Restart(c) @@ -1648,11 +1644,11 @@ func (s *DockerDaemonSuite) TestDaemonRestartLocalVolumes(c *check.C) { s.d.Start(c) out, err := s.d.Cmd("volume", "create", "test") - c.Assert(err, check.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) s.d.Restart(c) out, err = s.d.Cmd("volume", "inspect", "test") - c.Assert(err, check.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) } // FIXME(vdemeester) should be a unit test @@ -1714,9 +1710,9 @@ func (s *DockerDaemonSuite) TestDaemonStartWithDefaultTLSHost(c *check.C) { // ensure when connecting to the server that only a single acceptable CA is requested contents, err := ioutil.ReadFile("fixtures/https/ca.pem") - c.Assert(err, checker.IsNil) + assert.NilError(c, err) rootCert, err := helpers.ParseCertificatePEM(contents) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) rootPool := x509.NewCertPool() rootPool.AddCert(rootCert) @@ -1732,7 +1728,7 @@ func (s *DockerDaemonSuite) TestDaemonStartWithDefaultTLSHost(c *check.C) { return &cert, nil }, }) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) conn.Close() c.Assert(certRequestInfo, checker.NotNil) @@ -1771,7 +1767,7 @@ func (s *DockerDaemonSuite) TestDaemonNoSpaceLeftOnDeviceError(c *check.C) { testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux, Network) testDir, err := ioutil.TempDir("", "no-space-left-on-device-test") - c.Assert(err, checker.IsNil) + assert.NilError(c, err) defer os.RemoveAll(testDir) c.Assert(mount.MakeRShared(testDir), checker.IsNil) defer mount.Unmount(testDir) @@ -1823,7 +1819,7 @@ func (s *DockerDaemonSuite) TestDaemonRestartContainerLinksRestart(c *check.C) { wg.Wait() close(chErr) for err := range chErr { - c.Assert(err, check.IsNil) + assert.NilError(c, err) } parent1Args = append([]string{"run", "-d"}, parent1Args...) @@ -1832,9 +1828,9 @@ func (s *DockerDaemonSuite) TestDaemonRestartContainerLinksRestart(c *check.C) { parent2Args = append(parent2Args, []string{"--name=parent2", "--restart=always", "busybox", "top"}...) _, err := s.d.Cmd(parent1Args...) - c.Assert(err, check.IsNil) + assert.NilError(c, err) _, err = s.d.Cmd(parent2Args...) - c.Assert(err, check.IsNil) + assert.NilError(c, err) s.d.Stop(c) // clear the log file -- we don't need any of it but may for the next part @@ -1844,7 +1840,7 @@ func (s *DockerDaemonSuite) TestDaemonRestartContainerLinksRestart(c *check.C) { for _, num := range []string{"1", "2"} { out, err := s.d.Cmd("inspect", "-f", "{{ .State.Running }}", "parent"+num) - c.Assert(err, check.IsNil) + assert.NilError(c, err) if strings.TrimSpace(out) != "true" { log, _ := ioutil.ReadFile(s.d.LogFileName()) c.Fatalf("parent container is not running\n%s", string(log)) @@ -1862,11 +1858,11 @@ func (s *DockerDaemonSuite) TestDaemonCgroupParent(c *check.C) { defer s.d.Restart(c) out, err := s.d.Cmd("run", "--name", name, "busybox", "cat", "/proc/self/cgroup") - c.Assert(err, checker.IsNil) + assert.NilError(c, err) cgroupPaths := ParseCgroupPaths(string(out)) c.Assert(len(cgroupPaths), checker.Not(checker.Equals), 0, check.Commentf("unexpected output - %q", string(out))) out, err = s.d.Cmd("inspect", "-f", "{{.Id}}", name) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) id := strings.TrimSpace(string(out)) expectedCgroup := path.Join(cgroupParent, id) found := false @@ -1884,21 +1880,21 @@ func (s *DockerDaemonSuite) TestDaemonRestartWithLinks(c *check.C) { s.d.StartWithBusybox(c) out, err := s.d.Cmd("run", "-d", "--name=test", "busybox", "top") - c.Assert(err, check.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) out, err = s.d.Cmd("run", "--name=test2", "--link", "test:abc", "busybox", "sh", "-c", "ping -c 1 -w 1 abc") - c.Assert(err, check.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) s.d.Restart(c) // should fail since test is not running yet out, err = s.d.Cmd("start", "test2") - c.Assert(err, check.NotNil, check.Commentf("%s", out)) + assert.ErrorContains(c, err, "", out) out, err = s.d.Cmd("start", "test") - c.Assert(err, check.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) out, err = s.d.Cmd("start", "-a", "test2") - c.Assert(err, check.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) c.Assert(strings.Contains(out, "1 packets transmitted, 1 packets received"), check.Equals, true, check.Commentf("%s", out)) } @@ -1907,26 +1903,26 @@ func (s *DockerDaemonSuite) TestDaemonRestartWithNames(c *check.C) { s.d.StartWithBusybox(c) out, err := s.d.Cmd("create", "--name=test", "busybox") - c.Assert(err, check.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) out, err = s.d.Cmd("run", "-d", "--name=test2", "busybox", "top") - c.Assert(err, check.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) test2ID := strings.TrimSpace(out) out, err = s.d.Cmd("run", "-d", "--name=test3", "--link", "test2:abc", "busybox", "top") - c.Assert(err, check.IsNil) + assert.NilError(c, err) test3ID := strings.TrimSpace(out) s.d.Restart(c) _, err = s.d.Cmd("create", "--name=test", "busybox") - c.Assert(err, check.NotNil, check.Commentf("expected error trying to create container with duplicate name")) + assert.ErrorContains(c, err, "", "expected error trying to create container with duplicate name") // this one is no longer needed, removing simplifies the remainder of the test out, err = s.d.Cmd("rm", "-f", "test") - c.Assert(err, check.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) out, err = s.d.Cmd("ps", "-a", "--no-trunc") - c.Assert(err, check.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) lines := strings.Split(strings.TrimSpace(out), "\n")[1:] @@ -1937,16 +1933,16 @@ func (s *DockerDaemonSuite) TestDaemonRestartWithNames(c *check.C) { names := fields[len(fields)-1] switch fields[0] { case test2ID: - c.Assert(names, check.Equals, "test2,test3/abc") + assert.Equal(c, names, "test2,test3/abc") test2validated = true case test3ID: - c.Assert(names, check.Equals, "test3") + assert.Equal(c, names, "test3") test3validated = true } } - c.Assert(test2validated, check.Equals, true) - c.Assert(test3validated, check.Equals, true) + assert.Assert(c, test2validated) + assert.Assert(c, test3validated) } // TestDaemonRestartWithKilledRunningContainer requires live restore of running containers @@ -1962,7 +1958,7 @@ func (s *DockerDaemonSuite) TestDaemonRestartWithKilledRunningContainer(t *check cid = strings.TrimSpace(cid) pid, err := s.d.Cmd("inspect", "-f", "{{.State.Pid}}", cid) - t.Assert(err, check.IsNil) + assert.NilError(t, err) pid = strings.TrimSpace(pid) // Kill the daemon @@ -1988,7 +1984,7 @@ func (s *DockerDaemonSuite) TestDaemonRestartWithKilledRunningContainer(t *check // Check that we've got the correct exit code out, err := s.d.Cmd("inspect", "-f", "{{.State.ExitCode}}", cid) - t.Assert(err, check.IsNil) + assert.NilError(t, err) out = strings.TrimSpace(out) if out != "143" { @@ -2005,7 +2001,7 @@ func (s *DockerDaemonSuite) TestCleanupMountsAfterDaemonCrash(c *check.C) { s.d.StartWithBusybox(c, "--live-restore") out, err := s.d.Cmd("run", "-d", "busybox", "top") - c.Assert(err, check.IsNil, check.Commentf("Output: %s", out)) + assert.NilError(c, err, "Output: %s", out) id := strings.TrimSpace(out) // kill the daemon @@ -2026,7 +2022,7 @@ func (s *DockerDaemonSuite) TestCleanupMountsAfterDaemonCrash(c *check.C) { // container should be running. out, err = s.d.Cmd("inspect", "--format={{.State.Running}}", id) - c.Assert(err, check.IsNil, check.Commentf("Output: %s", out)) + assert.NilError(c, err, "Output: %s", out) out = strings.TrimSpace(out) if out != "true" { c.Fatalf("Container %s expected to stay alive after daemon restart", id) @@ -2034,7 +2030,7 @@ func (s *DockerDaemonSuite) TestCleanupMountsAfterDaemonCrash(c *check.C) { // 'docker stop' should work. out, err = s.d.Cmd("stop", id) - c.Assert(err, check.IsNil, check.Commentf("Output: %s", out)) + assert.NilError(c, err, "Output: %s", out) if skipMountCheck { return @@ -2059,7 +2055,7 @@ func (s *DockerDaemonSuite) TestDaemonRestartWithUnpausedRunningContainer(t *che cid = strings.TrimSpace(cid) pid, err := s.d.Cmd("inspect", "-f", "{{.State.Pid}}", cid) - t.Assert(err, check.IsNil) + assert.NilError(t, err) // pause the container if _, err := s.d.Cmd("pause", cid); err != nil { @@ -2091,7 +2087,7 @@ func (s *DockerDaemonSuite) TestDaemonRestartWithUnpausedRunningContainer(t *che // Check that we've got the correct status out, err := s.d.Cmd("inspect", "-f", "{{.State.Status}}", cid) - t.Assert(err, check.IsNil) + assert.NilError(t, err) out = strings.TrimSpace(out) if out != "running" { @@ -2109,24 +2105,24 @@ func (s *DockerDaemonSuite) TestRunLinksChanged(c *check.C) { s.d.StartWithBusybox(c) out, err := s.d.Cmd("run", "-d", "--name=test", "busybox", "top") - c.Assert(err, check.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) out, err = s.d.Cmd("run", "--name=test2", "--link=test:abc", "busybox", "sh", "-c", "ping -c 1 abc") - c.Assert(err, check.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) c.Assert(out, checker.Contains, "1 packets transmitted, 1 packets received") out, err = s.d.Cmd("rm", "-f", "test") - c.Assert(err, check.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) out, err = s.d.Cmd("run", "-d", "--name=test", "busybox", "top") - c.Assert(err, check.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) out, err = s.d.Cmd("start", "-a", "test2") - c.Assert(err, check.NotNil, check.Commentf("%s", out)) + assert.ErrorContains(c, err, "", out) c.Assert(out, check.Not(checker.Contains), "1 packets transmitted, 1 packets received") s.d.Restart(c) out, err = s.d.Cmd("start", "-a", "test2") - c.Assert(err, check.NotNil, check.Commentf("%s", out)) + assert.ErrorContains(c, err, "", out) c.Assert(out, check.Not(checker.Contains), "1 packets transmitted, 1 packets received") } @@ -2139,7 +2135,7 @@ func (s *DockerDaemonSuite) TestDaemonStartWithoutColors(c *check.C) { done := make(chan bool) p, tty, err := pty.Open() - c.Assert(err, checker.IsNil) + assert.NilError(c, err) defer func() { tty.Close() p.Close() @@ -2164,7 +2160,7 @@ func (s *DockerDaemonSuite) TestDaemonStartWithoutColors(c *check.C) { // pty for the next test. p.Close() p, tty, err = pty.Open() - c.Assert(err, checker.IsNil) + assert.NilError(c, err) go func() { io.Copy(b, p) @@ -2186,7 +2182,7 @@ func (s *DockerDaemonSuite) TestDaemonDebugLog(c *check.C) { debugLog := "\x1b[37mDEBU\x1b" p, tty, err := pty.Open() - c.Assert(err, checker.IsNil) + assert.NilError(c, err) defer func() { tty.Close() p.Close() @@ -2214,7 +2210,7 @@ func (s *DockerDaemonSuite) TestDaemonDiscoveryBackendConfigReload(c *check.C) { }() _, err = configFile.Write([]byte(daemonConfig)) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) // --log-level needs to be set so that d.Start() doesn't add --debug causing // a conflict with the config @@ -2228,18 +2224,18 @@ func (s *DockerDaemonSuite) TestDaemonDiscoveryBackendConfigReload(c *check.C) { }` err = configFile.Truncate(0) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) _, err = configFile.Seek(0, os.SEEK_SET) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) _, err = configFile.Write([]byte(daemonConfig)) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) err = s.d.ReloadConfig() c.Assert(err, checker.IsNil, check.Commentf("error reloading daemon config")) out, err := s.d.Cmd("info") - c.Assert(err, checker.IsNil) + assert.NilError(c, err) c.Assert(out, checker.Contains, fmt.Sprintf("Cluster Store: consul://consuladdr:consulport/some/path")) c.Assert(out, checker.Contains, fmt.Sprintf("Cluster Advertise: 192.168.56.100:0")) @@ -2250,11 +2246,11 @@ func (s *DockerDaemonSuite) TestDaemonLogOptions(c *check.C) { s.d.StartWithBusybox(c, "--log-driver=syslog", "--log-opt=syslog-address=udp://127.0.0.1:514") out, err := s.d.Cmd("run", "-d", "--log-driver=json-file", "busybox", "top") - c.Assert(err, check.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) id := strings.TrimSpace(out) out, err = s.d.Cmd("inspect", "--format='{{.HostConfig.LogConfig}}'", id) - c.Assert(err, check.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) c.Assert(out, checker.Contains, "{json-file map[]}") } @@ -2265,7 +2261,7 @@ func (s *DockerDaemonSuite) TestDaemonMaxConcurrency(c *check.C) { expectedMaxConcurrentUploads := `level=debug msg="Max Concurrent Uploads: 6"` expectedMaxConcurrentDownloads := `level=debug msg="Max Concurrent Downloads: 8"` content, err := s.d.ReadLogFile() - c.Assert(err, checker.IsNil) + assert.NilError(c, err) c.Assert(string(content), checker.Contains, expectedMaxConcurrentUploads) c.Assert(string(content), checker.Contains, expectedMaxConcurrentDownloads) } @@ -2277,7 +2273,7 @@ func (s *DockerDaemonSuite) TestDaemonMaxConcurrencyWithConfigFile(c *check.C) { // daemon config file configFilePath := "test.json" configFile, err := os.Create(configFilePath) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) defer os.Remove(configFilePath) daemonConfig := `{ "max-concurrent-downloads" : 8 }` @@ -2288,12 +2284,12 @@ func (s *DockerDaemonSuite) TestDaemonMaxConcurrencyWithConfigFile(c *check.C) { expectedMaxConcurrentUploads := `level=debug msg="Max Concurrent Uploads: 5"` expectedMaxConcurrentDownloads := `level=debug msg="Max Concurrent Downloads: 8"` content, err := s.d.ReadLogFile() - c.Assert(err, checker.IsNil) + assert.NilError(c, err) c.Assert(string(content), checker.Contains, expectedMaxConcurrentUploads) c.Assert(string(content), checker.Contains, expectedMaxConcurrentDownloads) configFile, err = os.Create(configFilePath) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) daemonConfig = `{ "max-concurrent-uploads" : 7, "max-concurrent-downloads" : 9 }` fmt.Fprintf(configFile, "%s", daemonConfig) configFile.Close() @@ -2306,7 +2302,7 @@ func (s *DockerDaemonSuite) TestDaemonMaxConcurrencyWithConfigFile(c *check.C) { expectedMaxConcurrentUploads = `level=debug msg="Reset Max Concurrent Uploads: 7"` expectedMaxConcurrentDownloads = `level=debug msg="Reset Max Concurrent Downloads: 9"` content, err = s.d.ReadLogFile() - c.Assert(err, checker.IsNil) + assert.NilError(c, err) c.Assert(string(content), checker.Contains, expectedMaxConcurrentUploads) c.Assert(string(content), checker.Contains, expectedMaxConcurrentDownloads) } @@ -2318,7 +2314,7 @@ func (s *DockerDaemonSuite) TestDaemonMaxConcurrencyWithConfigFileReload(c *chec // daemon config file configFilePath := "test.json" configFile, err := os.Create(configFilePath) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) defer os.Remove(configFilePath) daemonConfig := `{ "max-concurrent-uploads" : null }` @@ -2329,12 +2325,12 @@ func (s *DockerDaemonSuite) TestDaemonMaxConcurrencyWithConfigFileReload(c *chec expectedMaxConcurrentUploads := `level=debug msg="Max Concurrent Uploads: 5"` expectedMaxConcurrentDownloads := `level=debug msg="Max Concurrent Downloads: 3"` content, err := s.d.ReadLogFile() - c.Assert(err, checker.IsNil) + assert.NilError(c, err) c.Assert(string(content), checker.Contains, expectedMaxConcurrentUploads) c.Assert(string(content), checker.Contains, expectedMaxConcurrentDownloads) configFile, err = os.Create(configFilePath) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) daemonConfig = `{ "max-concurrent-uploads" : 1, "max-concurrent-downloads" : null }` fmt.Fprintf(configFile, "%s", daemonConfig) configFile.Close() @@ -2347,12 +2343,12 @@ func (s *DockerDaemonSuite) TestDaemonMaxConcurrencyWithConfigFileReload(c *chec expectedMaxConcurrentUploads = `level=debug msg="Reset Max Concurrent Uploads: 1"` expectedMaxConcurrentDownloads = `level=debug msg="Reset Max Concurrent Downloads: 3"` content, err = s.d.ReadLogFile() - c.Assert(err, checker.IsNil) + assert.NilError(c, err) c.Assert(string(content), checker.Contains, expectedMaxConcurrentUploads) c.Assert(string(content), checker.Contains, expectedMaxConcurrentDownloads) configFile, err = os.Create(configFilePath) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) daemonConfig = `{ "labels":["foo=bar"] }` fmt.Fprintf(configFile, "%s", daemonConfig) configFile.Close() @@ -2364,7 +2360,7 @@ func (s *DockerDaemonSuite) TestDaemonMaxConcurrencyWithConfigFileReload(c *chec expectedMaxConcurrentUploads = `level=debug msg="Reset Max Concurrent Uploads: 5"` expectedMaxConcurrentDownloads = `level=debug msg="Reset Max Concurrent Downloads: 3"` content, err = s.d.ReadLogFile() - c.Assert(err, checker.IsNil) + assert.NilError(c, err) c.Assert(string(content), checker.Contains, expectedMaxConcurrentUploads) c.Assert(string(content), checker.Contains, expectedMaxConcurrentDownloads) } @@ -2400,7 +2396,7 @@ func (s *DockerDaemonSuite) TestDaemonDNSFlagsInHostMode(c *check.C) { func (s *DockerDaemonSuite) TestRunWithRuntimeFromConfigFile(c *check.C) { conf, err := ioutil.TempFile("", "config-file-") - c.Assert(err, check.IsNil) + assert.NilError(c, err) configName := conf.Name() conf.Close() defer os.Remove(configName) @@ -2425,19 +2421,19 @@ func (s *DockerDaemonSuite) TestRunWithRuntimeFromConfigFile(c *check.C) { // Run with default runtime out, err := s.d.Cmd("run", "--rm", "busybox", "ls") - c.Assert(err, check.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) // Run with default runtime explicitly out, err = s.d.Cmd("run", "--rm", "--runtime=runc", "busybox", "ls") - c.Assert(err, check.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) // Run with oci (same path as default) but keep it around out, err = s.d.Cmd("run", "--name", "oci-runtime-ls", "--runtime=oci", "busybox", "ls") - c.Assert(err, check.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) // Run with "vm" out, err = s.d.Cmd("run", "--rm", "--runtime=vm", "busybox", "ls") - c.Assert(err, check.NotNil, check.Commentf("%s", out)) + assert.ErrorContains(c, err, "", out) c.Assert(out, checker.Contains, "/usr/local/bin/vm-manager: no such file or directory") // Reset config to only have the default @@ -2454,16 +2450,16 @@ func (s *DockerDaemonSuite) TestRunWithRuntimeFromConfigFile(c *check.C) { // Run with default runtime out, err = s.d.Cmd("run", "--rm", "--runtime=runc", "busybox", "ls") - c.Assert(err, check.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) // Run with "oci" out, err = s.d.Cmd("run", "--rm", "--runtime=oci", "busybox", "ls") - c.Assert(err, check.NotNil, check.Commentf("%s", out)) + assert.ErrorContains(c, err, "", out) c.Assert(out, checker.Contains, "Unknown runtime specified oci") // Start previously created container with oci out, err = s.d.Cmd("start", "oci-runtime-ls") - c.Assert(err, check.NotNil, check.Commentf("%s", out)) + assert.ErrorContains(c, err, "", out) c.Assert(out, checker.Contains, "Unknown runtime specified oci") // Check that we can't override the default runtime @@ -2482,7 +2478,7 @@ func (s *DockerDaemonSuite) TestRunWithRuntimeFromConfigFile(c *check.C) { <-time.After(1 * time.Second) content, err := s.d.ReadLogFile() - c.Assert(err, checker.IsNil) + assert.NilError(c, err) c.Assert(string(content), checker.Contains, `file configuration validation failed (runtime name 'runc' is reserved)`) // Check that we can select a default runtime @@ -2508,12 +2504,12 @@ func (s *DockerDaemonSuite) TestRunWithRuntimeFromConfigFile(c *check.C) { <-time.After(1 * time.Second) out, err = s.d.Cmd("run", "--rm", "busybox", "ls") - c.Assert(err, check.NotNil, check.Commentf("%s", out)) + assert.ErrorContains(c, err, "", out) c.Assert(out, checker.Contains, "/usr/local/bin/vm-manager: no such file or directory") // Run with default runtime explicitly out, err = s.d.Cmd("run", "--rm", "--runtime=runc", "busybox", "ls") - c.Assert(err, check.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) } func (s *DockerDaemonSuite) TestRunWithRuntimeFromCommandLine(c *check.C) { @@ -2521,19 +2517,19 @@ func (s *DockerDaemonSuite) TestRunWithRuntimeFromCommandLine(c *check.C) { // Run with default runtime out, err := s.d.Cmd("run", "--rm", "busybox", "ls") - c.Assert(err, check.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) // Run with default runtime explicitly out, err = s.d.Cmd("run", "--rm", "--runtime=runc", "busybox", "ls") - c.Assert(err, check.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) // Run with oci (same path as default) but keep it around out, err = s.d.Cmd("run", "--name", "oci-runtime-ls", "--runtime=oci", "busybox", "ls") - c.Assert(err, check.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) // Run with "vm" out, err = s.d.Cmd("run", "--rm", "--runtime=vm", "busybox", "ls") - c.Assert(err, check.NotNil, check.Commentf("%s", out)) + assert.ErrorContains(c, err, "", out) c.Assert(out, checker.Contains, "/usr/local/bin/vm-manager: no such file or directory") // Start a daemon without any extra runtimes @@ -2542,16 +2538,16 @@ func (s *DockerDaemonSuite) TestRunWithRuntimeFromCommandLine(c *check.C) { // Run with default runtime out, err = s.d.Cmd("run", "--rm", "--runtime=runc", "busybox", "ls") - c.Assert(err, check.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) // Run with "oci" out, err = s.d.Cmd("run", "--rm", "--runtime=oci", "busybox", "ls") - c.Assert(err, check.NotNil, check.Commentf("%s", out)) + assert.ErrorContains(c, err, "", out) c.Assert(out, checker.Contains, "Unknown runtime specified oci") // Start previously created container with oci out, err = s.d.Cmd("start", "oci-runtime-ls") - c.Assert(err, check.NotNil, check.Commentf("%s", out)) + assert.ErrorContains(c, err, "", out) c.Assert(out, checker.Contains, "Unknown runtime specified oci") // Check that we can't override the default runtime @@ -2559,7 +2555,7 @@ func (s *DockerDaemonSuite) TestRunWithRuntimeFromCommandLine(c *check.C) { c.Assert(s.d.StartWithError("--add-runtime", "runc=my-runc"), checker.NotNil) content, err := s.d.ReadLogFile() - c.Assert(err, checker.IsNil) + assert.NilError(c, err) c.Assert(string(content), checker.Contains, `runtime name 'runc' is reserved`) // Check that we can select a default runtime @@ -2567,12 +2563,12 @@ func (s *DockerDaemonSuite) TestRunWithRuntimeFromCommandLine(c *check.C) { s.d.StartWithBusybox(c, "--default-runtime=vm", "--add-runtime", "oci=runc", "--add-runtime", "vm=/usr/local/bin/vm-manager") out, err = s.d.Cmd("run", "--rm", "busybox", "ls") - c.Assert(err, check.NotNil, check.Commentf("%s", out)) + assert.ErrorContains(c, err, "", out) c.Assert(out, checker.Contains, "/usr/local/bin/vm-manager: no such file or directory") // Run with default runtime explicitly out, err = s.d.Cmd("run", "--rm", "--runtime=runc", "busybox", "ls") - c.Assert(err, check.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) } func (s *DockerDaemonSuite) TestDaemonRestartWithAutoRemoveContainer(c *check.C) { @@ -2586,7 +2582,7 @@ func (s *DockerDaemonSuite) TestDaemonRestartWithAutoRemoveContainer(c *check.C) c.Assert(err, checker.IsNil, check.Commentf("run top2: %v", out)) out, err = s.d.Cmd("ps") - c.Assert(err, checker.IsNil) + assert.NilError(c, err) c.Assert(out, checker.Contains, "top1", check.Commentf("top1 should be running")) c.Assert(out, checker.Contains, "top2", check.Commentf("top2 should be running")) @@ -2594,7 +2590,7 @@ func (s *DockerDaemonSuite) TestDaemonRestartWithAutoRemoveContainer(c *check.C) s.d.Restart(c) out, err = s.d.Cmd("ps", "-a") - c.Assert(err, checker.IsNil, check.Commentf("out: %v", out)) + assert.NilError(c, err, "out: %v", out) c.Assert(out, checker.Contains, "top1", check.Commentf("top1 should exist after daemon restarts")) c.Assert(out, checker.Not(checker.Contains), "top2", check.Commentf("top2 should be removed after daemon restarts")) } @@ -2612,17 +2608,17 @@ func (s *DockerDaemonSuite) TestDaemonRestartSaveContainerExitCode(c *check.C) { // See the discussion on https://github.com/docker/docker/pull/30227#issuecomment-274161426, // and https://github.com/docker/docker/pull/26061#r78054578 for more information. _, err := s.d.Cmd("run", "--name", containerName, "--init=false", "busybox", "toto") - c.Assert(err, checker.NotNil) + assert.ErrorContains(c, err, "") // Check that those values were saved on disk out, err := s.d.Cmd("inspect", "-f", "{{.State.ExitCode}}", containerName) out = strings.TrimSpace(out) - c.Assert(err, checker.IsNil) - c.Assert(out, checker.Equals, "127") + assert.NilError(c, err) + assert.Equal(c, out, "127") errMsg1, err := s.d.Cmd("inspect", "-f", "{{.State.Error}}", containerName) errMsg1 = strings.TrimSpace(errMsg1) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) c.Assert(errMsg1, checker.Contains, "executable file not found") // now restart daemon @@ -2631,41 +2627,41 @@ func (s *DockerDaemonSuite) TestDaemonRestartSaveContainerExitCode(c *check.C) { // Check that those values are still around out, err = s.d.Cmd("inspect", "-f", "{{.State.ExitCode}}", containerName) out = strings.TrimSpace(out) - c.Assert(err, checker.IsNil) - c.Assert(out, checker.Equals, "127") + assert.NilError(c, err) + assert.Equal(c, out, "127") out, err = s.d.Cmd("inspect", "-f", "{{.State.Error}}", containerName) out = strings.TrimSpace(out) - c.Assert(err, checker.IsNil) - c.Assert(out, checker.Equals, errMsg1) + assert.NilError(c, err) + assert.Equal(c, out, errMsg1) } func (s *DockerDaemonSuite) TestDaemonWithUserlandProxyPath(c *check.C) { testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux) dockerProxyPath, err := exec.LookPath("docker-proxy") - c.Assert(err, checker.IsNil) + assert.NilError(c, err) tmpDir, err := ioutil.TempDir("", "test-docker-proxy") - c.Assert(err, checker.IsNil) + assert.NilError(c, err) newProxyPath := filepath.Join(tmpDir, "docker-proxy") cmd := exec.Command("cp", dockerProxyPath, newProxyPath) - c.Assert(cmd.Run(), checker.IsNil) + assert.NilError(c, cmd.Run()) // custom one s.d.StartWithBusybox(c, "--userland-proxy-path", newProxyPath) out, err := s.d.Cmd("run", "-p", "5000:5000", "busybox:latest", "true") - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) // try with the original one s.d.Restart(c, "--userland-proxy-path", dockerProxyPath) out, err = s.d.Cmd("run", "-p", "5000:5000", "busybox:latest", "true") - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) // not exist s.d.Restart(c, "--userland-proxy-path", "/does/not/exist") out, err = s.d.Cmd("run", "-p", "5000:5000", "busybox:latest", "true") - c.Assert(err, checker.NotNil, check.Commentf("%s", out)) + assert.ErrorContains(c, err, "", out) c.Assert(out, checker.Contains, "driver failed programming external connectivity on endpoint") c.Assert(out, checker.Contains, "/does/not/exist: no such file or directory") } @@ -2676,7 +2672,7 @@ func (s *DockerDaemonSuite) TestDaemonShutdownTimeout(c *check.C) { s.d.StartWithBusybox(c, "--shutdown-timeout=3") _, err := s.d.Cmd("run", "-d", "busybox", "top") - c.Assert(err, check.IsNil) + assert.NilError(c, err) c.Assert(s.d.Signal(unix.SIGINT), checker.IsNil) @@ -2687,7 +2683,7 @@ func (s *DockerDaemonSuite) TestDaemonShutdownTimeout(c *check.C) { expectedMessage := `level=debug msg="daemon configured with a 3 seconds minimum shutdown timeout"` content, err := s.d.ReadLogFile() - c.Assert(err, checker.IsNil) + assert.NilError(c, err) c.Assert(string(content), checker.Contains, expectedMessage) } @@ -2698,7 +2694,7 @@ func (s *DockerDaemonSuite) TestDaemonShutdownTimeoutWithConfigFile(c *check.C) // daemon config file configFilePath := "test.json" configFile, err := os.Create(configFilePath) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) defer os.Remove(configFilePath) daemonConfig := `{ "shutdown-timeout" : 8 }` @@ -2707,7 +2703,7 @@ func (s *DockerDaemonSuite) TestDaemonShutdownTimeoutWithConfigFile(c *check.C) s.d.Start(c, fmt.Sprintf("--config-file=%s", configFilePath)) configFile, err = os.Create(configFilePath) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) daemonConfig = `{ "shutdown-timeout" : 5 }` fmt.Fprintf(configFile, "%s", daemonConfig) configFile.Close() @@ -2721,7 +2717,7 @@ func (s *DockerDaemonSuite) TestDaemonShutdownTimeoutWithConfigFile(c *check.C) expectedMessage := `level=debug msg="Reset Shutdown Timeout: 5"` content, err := s.d.ReadLogFile() - c.Assert(err, checker.IsNil) + assert.NilError(c, err) c.Assert(string(content), checker.Contains, expectedMessage) } @@ -2731,7 +2727,7 @@ func (s *DockerDaemonSuite) TestExecWithUserAfterLiveRestore(c *check.C) { s.d.StartWithBusybox(c, "--live-restore") out, err := s.d.Cmd("run", "-d", "--name=top", "busybox", "sh", "-c", "addgroup -S test && adduser -S -G test test -D -s /bin/sh && touch /adduser_end && top") - c.Assert(err, check.IsNil, check.Commentf("Output: %s", out)) + assert.NilError(c, err, "Output: %s", out) s.d.WaitRun("top") @@ -2751,14 +2747,14 @@ func (s *DockerDaemonSuite) TestExecWithUserAfterLiveRestore(c *check.C) { c.Assert(out2, check.Equals, out1, check.Commentf("Output: before restart '%s', after restart '%s'", out1, out2)) out, err = s.d.Cmd("stop", "top") - c.Assert(err, check.IsNil, check.Commentf("Output: %s", out)) + assert.NilError(c, err, "Output: %s", out) } func (s *DockerDaemonSuite) TestRemoveContainerAfterLiveRestore(c *check.C) { testRequires(c, DaemonIsLinux, overlayFSSupported, testEnv.IsLocalDaemon) s.d.StartWithBusybox(c, "--live-restore", "--storage-driver", "overlay") out, err := s.d.Cmd("run", "-d", "--name=top", "busybox", "top") - c.Assert(err, check.IsNil, check.Commentf("Output: %s", out)) + assert.NilError(c, err, "Output: %s", out) s.d.WaitRun("top") @@ -2766,13 +2762,13 @@ func (s *DockerDaemonSuite) TestRemoveContainerAfterLiveRestore(c *check.C) { s.d.Restart(c, "--live-restore", "--storage-driver", "overlay") out, err = s.d.Cmd("stop", "top") - c.Assert(err, check.IsNil, check.Commentf("Output: %s", out)) + assert.NilError(c, err, "Output: %s", out) // test if the rootfs mountpoint still exist mountpoint, err := s.d.InspectField("top", ".GraphDriver.Data.MergedDir") - c.Assert(err, check.IsNil) + assert.NilError(c, err) f, err := os.Open("/proc/self/mountinfo") - c.Assert(err, check.IsNil) + assert.NilError(c, err) defer f.Close() sc := bufio.NewScanner(f) for sc.Scan() { @@ -2783,7 +2779,7 @@ func (s *DockerDaemonSuite) TestRemoveContainerAfterLiveRestore(c *check.C) { } out, err = s.d.Cmd("rm", "top") - c.Assert(err, check.IsNil, check.Commentf("Output: %s", out)) + assert.NilError(c, err, "Output: %s", out) } // #29598 @@ -2792,7 +2788,7 @@ func (s *DockerDaemonSuite) TestRestartPolicyWithLiveRestore(c *check.C) { s.d.StartWithBusybox(c, "--live-restore") out, err := s.d.Cmd("run", "-d", "--restart", "always", "busybox", "top") - c.Assert(err, check.IsNil, check.Commentf("output: %s", out)) + assert.NilError(c, err, "Output: %s", out) id := strings.TrimSpace(out) type state struct { @@ -2804,16 +2800,16 @@ func (s *DockerDaemonSuite) TestRestartPolicyWithLiveRestore(c *check.C) { var origState state err = json.Unmarshal([]byte(strings.TrimSpace(out)), &origState) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) s.d.Restart(c, "--live-restore") pid, err := s.d.Cmd("inspect", "-f", "{{.State.Pid}}", id) - c.Assert(err, check.IsNil) + assert.NilError(c, err) pidint, err := strconv.Atoi(strings.TrimSpace(pid)) - c.Assert(err, check.IsNil) - c.Assert(pidint, checker.GreaterThan, 0) - c.Assert(unix.Kill(pidint, unix.SIGKILL), check.IsNil) + assert.NilError(c, err) + assert.Assert(c, pidint > 0) + assert.NilError(c, unix.Kill(pidint, unix.SIGKILL)) ticker := time.NewTicker(50 * time.Millisecond) timeout := time.After(10 * time.Second) @@ -2830,7 +2826,7 @@ func (s *DockerDaemonSuite) TestRestartPolicyWithLiveRestore(c *check.C) { var newState state err = json.Unmarshal([]byte(strings.TrimSpace(out)), &newState) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) if !newState.Running { continue @@ -2841,7 +2837,7 @@ func (s *DockerDaemonSuite) TestRestartPolicyWithLiveRestore(c *check.C) { } out, err = s.d.Cmd("stop", id) - c.Assert(err, check.IsNil, check.Commentf("output: %s", out)) + assert.NilError(c, err, "Output: %s", out) } func (s *DockerDaemonSuite) TestShmSize(c *check.C) { @@ -2854,10 +2850,10 @@ func (s *DockerDaemonSuite) TestShmSize(c *check.C) { name := "shm1" out, err := s.d.Cmd("run", "--name", name, "busybox", "mount") - c.Assert(err, check.IsNil, check.Commentf("Output: %s", out)) + assert.NilError(c, err, "Output: %s", out) c.Assert(pattern.MatchString(out), checker.True) out, err = s.d.Cmd("inspect", "--format", "{{.HostConfig.ShmSize}}", name) - c.Assert(err, check.IsNil, check.Commentf("Output: %s", out)) + assert.NilError(c, err, "Output: %s", out) c.Assert(strings.TrimSpace(out), check.Equals, fmt.Sprintf("%v", size)) } @@ -2878,10 +2874,10 @@ func (s *DockerDaemonSuite) TestShmSizeReload(c *check.C) { name := "shm1" out, err := s.d.Cmd("run", "--name", name, "busybox", "mount") - c.Assert(err, check.IsNil, check.Commentf("Output: %s", out)) + assert.NilError(c, err, "Output: %s", out) c.Assert(pattern.MatchString(out), checker.True) out, err = s.d.Cmd("inspect", "--format", "{{.HostConfig.ShmSize}}", name) - c.Assert(err, check.IsNil, check.Commentf("Output: %s", out)) + assert.NilError(c, err, "Output: %s", out) c.Assert(strings.TrimSpace(out), check.Equals, fmt.Sprintf("%v", size)) size = 67108864 * 3 @@ -2894,10 +2890,10 @@ func (s *DockerDaemonSuite) TestShmSizeReload(c *check.C) { name = "shm2" out, err = s.d.Cmd("run", "--name", name, "busybox", "mount") - c.Assert(err, check.IsNil, check.Commentf("Output: %s", out)) + assert.NilError(c, err, "Output: %s", out) c.Assert(pattern.MatchString(out), checker.True) out, err = s.d.Cmd("inspect", "--format", "{{.HostConfig.ShmSize}}", name) - c.Assert(err, check.IsNil, check.Commentf("Output: %s", out)) + assert.NilError(c, err, "Output: %s", out) c.Assert(strings.TrimSpace(out), check.Equals, fmt.Sprintf("%v", size)) } @@ -2908,12 +2904,12 @@ func testDaemonStartIpcMode(c *check.C, from, mode string, valid bool) { switch from { case "config": f, err := ioutil.TempFile("", "test-daemon-ipc-config") - c.Assert(err, checker.IsNil) + assert.NilError(c, err) defer os.Remove(f.Name()) config := `{"default-ipc-mode": "` + mode + `"}` _, err = f.WriteString(config) - c.Assert(f.Close(), checker.IsNil) - c.Assert(err, checker.IsNil) + assert.NilError(c, f.Close()) + assert.NilError(c, err) serr = d.StartWithError("--config-file", f.Name()) case "cli": @@ -2926,9 +2922,9 @@ func testDaemonStartIpcMode(c *check.C, from, mode string, valid bool) { } if valid { - c.Assert(serr, check.IsNil) + assert.NilError(c, serr) } else { - c.Assert(serr, check.NotNil) + assert.ErrorContains(c, serr, "") icmd.RunCommand("grep", "-E", "IPC .* is (invalid|not supported)", d.LogFileName()).Assert(c, icmd.Success) } } @@ -2975,26 +2971,26 @@ func (s *DockerDaemonSuite) TestFailedPluginRemove(c *check.C) { AcceptAllPermissions: true, RemoteRef: "cpuguy83/docker-logdriver-test", }) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) defer out.Close() io.Copy(ioutil.Discard, out) ctx, cancel = context.WithTimeout(context.Background(), 30*time.Second) defer cancel() p, _, err := cli.PluginInspectWithRaw(ctx, name) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) // simulate a bad/partial removal by removing the plugin config. configPath := filepath.Join(d.Root, "plugins", p.ID, "config.json") - c.Assert(os.Remove(configPath), checker.IsNil) + assert.NilError(c, os.Remove(configPath)) d.Restart(c) ctx, cancel = context.WithTimeout(context.Background(), 30*time.Second) defer cancel() _, err = cli.Ping(ctx) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) _, _, err = cli.PluginInspectWithRaw(ctx, name) // plugin should be gone since the config.json is gone - c.Assert(err, checker.NotNil) + assert.ErrorContains(c, err, "") } diff --git a/components/engine/integration-cli/docker_cli_events_test.go b/components/engine/integration-cli/docker_cli_events_test.go index ce3dec4b61..611ae3c7d2 100644 --- a/components/engine/integration-cli/docker_cli_events_test.go +++ b/components/engine/integration-cli/docker_cli_events_test.go @@ -17,10 +17,11 @@ import ( eventtypes "github.com/docker/docker/api/types/events" "github.com/docker/docker/client" eventstestutils "github.com/docker/docker/daemon/events/testutils" - "github.com/docker/docker/integration-cli/checker" "github.com/docker/docker/integration-cli/cli" "github.com/docker/docker/integration-cli/cli/build" "github.com/go-check/check" + "gotest.tools/assert" + is "gotest.tools/assert/cmp" "gotest.tools/icmd" ) @@ -47,15 +48,9 @@ func (s *DockerSuite) TestEventsTimestampFormats(c *check.C) { events = events[:len(events)-1] nEvents := len(events) - c.Assert(nEvents, checker.GreaterOrEqualThan, 5) //Missing expected event + assert.Assert(c, nEvents >= 5) //Missing expected event containerEvents := eventActionsByIDAndType(c, events, name, "container") - c.Assert(containerEvents, checker.HasLen, 5, check.Commentf("events: %v", events)) - - c.Assert(containerEvents[0], checker.Equals, "create", check.Commentf("%s", out)) - c.Assert(containerEvents[1], checker.Equals, "attach", check.Commentf("%s", out)) - c.Assert(containerEvents[2], checker.Equals, "start", check.Commentf("%s", out)) - c.Assert(containerEvents[3], checker.Equals, "die", check.Commentf("%s", out)) - c.Assert(containerEvents[4], checker.Equals, "destroy", check.Commentf("%s", out)) + assert.Assert(c, is.DeepEqual(containerEvents, []string{"create", "attach", "start", "die", "destroy"}), out) } } @@ -78,7 +73,7 @@ func (s *DockerSuite) TestEventsUntag(c *check.C) { // get the two elements before the last, which are the untags we're // looking for. for _, v := range events[nEvents-3 : nEvents-1] { - c.Assert(v, checker.Contains, "untag", check.Commentf("event should be untag")) + assert.Check(c, strings.Contains(v, "untag"), "event should be untag") } } @@ -89,16 +84,9 @@ func (s *DockerSuite) TestEventsContainerEvents(c *check.C) { events := strings.Split(out, "\n") events = events[:len(events)-1] - nEvents := len(events) - c.Assert(nEvents, checker.GreaterOrEqualThan, 5) //Missing expected event + assert.Assert(c, len(events) >= 5) //Missing expected event containerEvents := eventActionsByIDAndType(c, events, "container-events-test", "container") - c.Assert(containerEvents, checker.HasLen, 5, check.Commentf("events: %v", events)) - - c.Assert(containerEvents[0], checker.Equals, "create", check.Commentf("%s", out)) - c.Assert(containerEvents[1], checker.Equals, "attach", check.Commentf("%s", out)) - c.Assert(containerEvents[2], checker.Equals, "start", check.Commentf("%s", out)) - c.Assert(containerEvents[3], checker.Equals, "die", check.Commentf("%s", out)) - c.Assert(containerEvents[4], checker.Equals, "destroy", check.Commentf("%s", out)) + assert.Assert(c, is.DeepEqual(containerEvents[:5], []string{"create", "attach", "start", "die", "destroy"}), out) } func (s *DockerSuite) TestEventsContainerEventsAttrSort(c *check.C) { @@ -109,19 +97,20 @@ func (s *DockerSuite) TestEventsContainerEventsAttrSort(c *check.C) { events := strings.Split(out, "\n") nEvents := len(events) - c.Assert(nEvents, checker.GreaterOrEqualThan, 3) //Missing expected event + assert.Assert(c, nEvents >= 3) //Missing expected event matchedEvents := 0 for _, event := range events { matches := eventstestutils.ScanMap(event) if matches["eventType"] == "container" && matches["action"] == "create" { matchedEvents++ - c.Assert(out, checker.Contains, "(image=busybox, name=container-events-test)", check.Commentf("Event attributes not sorted")) + assert.Check(c, strings.Contains(out, "(image=busybox, name=container-events-test)"), "Event attributes not sorted") + } else if matches["eventType"] == "container" && matches["action"] == "start" { matchedEvents++ - c.Assert(out, checker.Contains, "(image=busybox, name=container-events-test)", check.Commentf("Event attributes not sorted")) + assert.Check(c, strings.Contains(out, "(image=busybox, name=container-events-test)"), "Event attributes not sorted") } } - c.Assert(matchedEvents, checker.Equals, 2, check.Commentf("missing events for container container-events-test:\n%s", out)) + assert.Equal(c, matchedEvents, 2, "missing events for container container-events-test:\n%s", out) } func (s *DockerSuite) TestEventsContainerEventsSinceUnixEpoch(c *check.C) { @@ -133,15 +122,9 @@ func (s *DockerSuite) TestEventsContainerEventsSinceUnixEpoch(c *check.C) { events = events[:len(events)-1] nEvents := len(events) - c.Assert(nEvents, checker.GreaterOrEqualThan, 5) //Missing expected event + assert.Assert(c, nEvents >= 5) //Missing expected event containerEvents := eventActionsByIDAndType(c, events, "since-epoch-test", "container") - c.Assert(containerEvents, checker.HasLen, 5, check.Commentf("events: %v", events)) - - c.Assert(containerEvents[0], checker.Equals, "create", check.Commentf("%s", out)) - c.Assert(containerEvents[1], checker.Equals, "attach", check.Commentf("%s", out)) - c.Assert(containerEvents[2], checker.Equals, "start", check.Commentf("%s", out)) - c.Assert(containerEvents[3], checker.Equals, "die", check.Commentf("%s", out)) - c.Assert(containerEvents[4], checker.Equals, "destroy", check.Commentf("%s", out)) + assert.Assert(c, is.DeepEqual(containerEvents, []string{"create", "attach", "start", "die", "destroy"}), out) } func (s *DockerSuite) TestEventsImageTag(c *check.C) { @@ -154,12 +137,12 @@ func (s *DockerSuite) TestEventsImageTag(c *check.C) { "--since", since, "--until", daemonUnixTime(c)) events := strings.Split(strings.TrimSpace(out), "\n") - c.Assert(events, checker.HasLen, 1, check.Commentf("was expecting 1 event. out=%s", out)) + assert.Equal(c, len(events), 1, "was expecting 1 event. out=%s", out) event := strings.TrimSpace(events[0]) matches := eventstestutils.ScanMap(event) - c.Assert(matchEventID(matches, image), checker.True, check.Commentf("matches: %v\nout:\n%s", matches, out)) - c.Assert(matches["action"], checker.Equals, "tag") + assert.Assert(c, matchEventID(matches, image), "matches: %v\nout:\n%s", matches, out) + assert.Equal(c, matches["action"], "tag") } func (s *DockerSuite) TestEventsImagePull(c *check.C) { @@ -176,9 +159,8 @@ func (s *DockerSuite) TestEventsImagePull(c *check.C) { events := strings.Split(strings.TrimSpace(out), "\n") event := strings.TrimSpace(events[len(events)-1]) matches := eventstestutils.ScanMap(event) - c.Assert(matches["id"], checker.Equals, "hello-world:latest") - c.Assert(matches["action"], checker.Equals, "pull") - + assert.Equal(c, matches["id"], "hello-world:latest") + assert.Equal(c, matches["action"], "pull") } func (s *DockerSuite) TestEventsImageImport(c *check.C) { @@ -194,15 +176,15 @@ func (s *DockerSuite) TestEventsImageImport(c *check.C) { exec.Command(dockerBinary, "export", cleanedContainerID), exec.Command(dockerBinary, "import", "-"), ) - c.Assert(err, checker.IsNil, check.Commentf("import failed with output: %q", out)) + 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") events := strings.Split(strings.TrimSpace(out), "\n") - c.Assert(events, checker.HasLen, 1) + assert.Equal(c, len(events), 1) matches := eventstestutils.ScanMap(events[0]) - c.Assert(matches["id"], checker.Equals, imageRef, check.Commentf("matches: %v\nout:\n%s\n", matches, out)) - c.Assert(matches["action"], checker.Equals, "import", check.Commentf("matches: %v\nout:\n%s\n", matches, out)) + assert.Equal(c, matches["id"], imageRef, "matches: %v\nout:\n%s\n", matches, out) + assert.Equal(c, matches["action"], "import", "matches: %v\nout:\n%s\n", matches, out) } func (s *DockerSuite) TestEventsImageLoad(c *check.C) { @@ -213,13 +195,13 @@ func (s *DockerSuite) TestEventsImageLoad(c *check.C) { out, _ := dockerCmd(c, "images", "-q", "--no-trunc", myImageName) longImageID := strings.TrimSpace(out) - c.Assert(longImageID, checker.Not(check.Equals), "", check.Commentf("Id should not be empty")) + 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) noImageID := strings.TrimSpace(out) - c.Assert(noImageID, checker.Equals, "", check.Commentf("Should not have any image")) + assert.Equal(c, noImageID, "", "Should not have any image") dockerCmd(c, "load", "-i", "saveimg.tar") result := icmd.RunCommand("rm", "-rf", "saveimg.tar") @@ -227,21 +209,21 @@ func (s *DockerSuite) TestEventsImageLoad(c *check.C) { out, _ = dockerCmd(c, "images", "-q", "--no-trunc", myImageName) imageID := strings.TrimSpace(out) - c.Assert(imageID, checker.Equals, longImageID, check.Commentf("Should have same image id as before")) + assert.Equal(c, imageID, longImageID, "Should have same image id as before") out, _ = dockerCmd(c, "events", "--since", since, "--until", daemonUnixTime(c), "--filter", "event=load") events := strings.Split(strings.TrimSpace(out), "\n") - c.Assert(events, checker.HasLen, 1) + assert.Equal(c, len(events), 1) matches := eventstestutils.ScanMap(events[0]) - c.Assert(matches["id"], checker.Equals, imageID, check.Commentf("matches: %v\nout:\n%s\n", matches, out)) - c.Assert(matches["action"], checker.Equals, "load", check.Commentf("matches: %v\nout:\n%s\n", matches, out)) + 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") events = strings.Split(strings.TrimSpace(out), "\n") - c.Assert(events, checker.HasLen, 1) + assert.Equal(c, len(events), 1) matches = eventstestutils.ScanMap(events[0]) - c.Assert(matches["id"], checker.Equals, imageID, check.Commentf("matches: %v\nout:\n%s\n", matches, out)) - c.Assert(matches["action"], checker.Equals, "save", check.Commentf("matches: %v\nout:\n%s\n", matches, out)) + assert.Equal(c, matches["id"], imageID, "matches: %v\nout:\n%s\n", matches, out) + assert.Equal(c, matches["action"], "save", "matches: %v\nout:\n%s\n", matches, out) } func (s *DockerSuite) TestEventsPluginOps(c *check.C) { @@ -257,16 +239,10 @@ func (s *DockerSuite) TestEventsPluginOps(c *check.C) { events := strings.Split(out, "\n") events = events[:len(events)-1] - nEvents := len(events) - c.Assert(nEvents, checker.GreaterOrEqualThan, 4) + assert.Assert(c, len(events) >= 4) pluginEvents := eventActionsByIDAndType(c, events, pNameWithTag, "plugin") - c.Assert(pluginEvents, checker.HasLen, 4, check.Commentf("events: %v", events)) - - c.Assert(pluginEvents[0], checker.Equals, "pull", check.Commentf("%s", out)) - c.Assert(pluginEvents[1], checker.Equals, "enable", check.Commentf("%s", out)) - c.Assert(pluginEvents[2], checker.Equals, "disable", check.Commentf("%s", out)) - c.Assert(pluginEvents[3], checker.Equals, "remove", check.Commentf("%s", out)) + assert.Assert(c, is.DeepEqual(pluginEvents, []string{"pull", "enable", "disable", "remove"}), out) } func (s *DockerSuite) TestEventsFilters(c *check.C) { @@ -281,8 +257,7 @@ func (s *DockerSuite) TestEventsFilters(c *check.C) { // make sure we at least got 2 start events count := strings.Count(out, "start") - c.Assert(strings.Count(out, "start"), checker.GreaterOrEqualThan, 2, check.Commentf("should have had 2 start events but had %d, out: %s", count, out)) - + assert.Assert(c, count >= 2, "should have had 2 start events but had %d, out: %s", count, out) } func (s *DockerSuite) TestEventsFilterImageName(c *check.C) { @@ -298,7 +273,7 @@ func (s *DockerSuite) TestEventsFilterImageName(c *check.C) { out, _ = dockerCmd(c, "events", "--since", since, "--until", daemonUnixTime(c), "--filter", fmt.Sprintf("image=%s", name)) events := strings.Split(out, "\n") events = events[:len(events)-1] - c.Assert(events, checker.Not(checker.HasLen), 0) //Expected events but found none for the image busybox:latest + assert.Assert(c, len(events) != 0, "Expected events but found none for the image busybox:latest") count1 := 0 count2 := 0 @@ -309,9 +284,8 @@ func (s *DockerSuite) TestEventsFilterImageName(c *check.C) { count2++ } } - c.Assert(count1, checker.Not(checker.Equals), 0, check.Commentf("Expected event from container but got %d from %s", count1, container1)) - c.Assert(count2, checker.Not(checker.Equals), 0, check.Commentf("Expected event from container but got %d from %s", count2, container2)) - + assert.Assert(c, count1 != 0, "Expected event from container but got %d from %s", count1, container1) + assert.Assert(c, count2 != 0, "Expected event from container but got %d from %s", count2, container2) } func (s *DockerSuite) TestEventsFilterLabels(c *check.C) { @@ -319,11 +293,11 @@ func (s *DockerSuite) TestEventsFilterLabels(c *check.C) { label := "io.docker.testing=foo" out, exit := dockerCmd(c, "create", "-l", label, "busybox") - c.Assert(exit, checker.Equals, 0) + assert.Equal(c, exit, 0) container1 := strings.TrimSpace(out) out, exit = dockerCmd(c, "create", "busybox") - c.Assert(exit, checker.Equals, 0) + assert.Equal(c, exit, 0) container2 := strings.TrimSpace(out) // fetch events with `--until`, so that the client detaches after a second @@ -337,16 +311,16 @@ func (s *DockerSuite) TestEventsFilterLabels(c *check.C) { ) events := strings.Split(strings.TrimSpace(out), "\n") - c.Assert(len(events), checker.GreaterThan, 0) + assert.Assert(c, len(events) > 0) var found bool for _, e := range events { if strings.Contains(e, container1) { found = true } - c.Assert(e, checker.Not(checker.Contains), container2) + assert.Assert(c, !strings.Contains(e, container2)) } - c.Assert(found, checker.Equals, true) + assert.Assert(c, found) } func (s *DockerSuite) TestEventsFilterImageLabels(c *check.C) { @@ -373,9 +347,9 @@ func (s *DockerSuite) TestEventsFilterImageLabels(c *check.C) { events := strings.Split(strings.TrimSpace(out), "\n") // 2 events from the "docker tag" command, another one is from "docker build" - c.Assert(events, checker.HasLen, 3, check.Commentf("Events == %s", events)) + assert.Equal(c, len(events), 3, "Events == %s", events) for _, e := range events { - c.Assert(e, checker.Contains, "labelfiltertest") + assert.Check(c, strings.Contains(e, "labelfiltertest")) } } @@ -408,12 +382,12 @@ func (s *DockerSuite) TestEventsFilterContainer(c *check.C) { // filter by names out, _ := dockerCmd(c, "events", "--since", since, "--until", until, "--filter", "container="+name) events := strings.Split(strings.TrimSuffix(out, "\n"), "\n") - c.Assert(checkEvents(ID, events), checker.IsNil) + assert.NilError(c, checkEvents(ID, events)) // filter by ID's out, _ = dockerCmd(c, "events", "--since", since, "--until", until, "--filter", "container="+ID) events = strings.Split(strings.TrimSuffix(out, "\n"), "\n") - c.Assert(checkEvents(ID, events), checker.IsNil) + assert.NilError(c, checkEvents(ID, events)) } } @@ -431,7 +405,7 @@ func (s *DockerSuite) TestEventsCommit(c *check.C) { until := daemonUnixTime(c) out = cli.DockerCmd(c, "events", "-f", "container="+cID, "--until="+until).Combined() - c.Assert(out, checker.Contains, "commit", check.Commentf("Missing 'commit' log event")) + assert.Assert(c, strings.Contains(out, "commit"), "Missing 'commit' log event") } func (s *DockerSuite) TestEventsCopy(c *check.C) { @@ -443,10 +417,10 @@ func (s *DockerSuite) TestEventsCopy(c *check.C) { // Create an empty test file. tempFile, err := ioutil.TempFile("", "test-events-copy-") - c.Assert(err, checker.IsNil) + assert.NilError(c, err) defer os.Remove(tempFile.Name()) - c.Assert(tempFile.Close(), checker.IsNil) + assert.NilError(c, tempFile.Close()) dockerCmd(c, "create", "--name=cptest", id) @@ -454,22 +428,22 @@ func (s *DockerSuite) TestEventsCopy(c *check.C) { until := daemonUnixTime(c) out, _ := dockerCmd(c, "events", "--since=0", "-f", "container=cptest", "--until="+until) - c.Assert(out, checker.Contains, "archive-path", check.Commentf("Missing 'archive-path' log event\n")) + assert.Assert(c, strings.Contains(out, "archive-path"), "Missing 'archive-path' log event") dockerCmd(c, "cp", tempFile.Name(), "cptest:/filecopy") until = daemonUnixTime(c) out, _ = dockerCmd(c, "events", "-f", "container=cptest", "--until="+until) - c.Assert(out, checker.Contains, "extract-to-dir", check.Commentf("Missing 'extract-to-dir' log event")) + assert.Assert(c, strings.Contains(out, "extract-to-dir"), "Missing 'extract-to-dir' log event") } func (s *DockerSuite) TestEventsResize(c *check.C) { out := runSleepingContainer(c, "-d") cID := strings.TrimSpace(out) - c.Assert(waitRun(cID), checker.IsNil) + assert.NilError(c, waitRun(cID)) cli, err := client.NewClientWithOpts(client.FromEnv) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) defer cli.Close() options := types.ResizeOptions{ @@ -477,13 +451,13 @@ func (s *DockerSuite) TestEventsResize(c *check.C) { Width: 24, } err = cli.ContainerResize(context.Background(), cID, options) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) dockerCmd(c, "stop", cID) until := daemonUnixTime(c) out, _ = dockerCmd(c, "events", "-f", "container="+cID, "--until="+until) - c.Assert(out, checker.Contains, "resize", check.Commentf("Missing 'resize' log event")) + assert.Assert(c, strings.Contains(out, "resize"), "Missing 'resize' log event") } func (s *DockerSuite) TestEventsAttach(c *check.C) { @@ -496,12 +470,12 @@ func (s *DockerSuite) TestEventsAttach(c *check.C) { cmd := exec.Command(dockerBinary, "attach", cID) stdin, err := cmd.StdinPipe() - c.Assert(err, checker.IsNil) + assert.NilError(c, err) defer stdin.Close() stdout, err := cmd.StdoutPipe() - c.Assert(err, checker.IsNil) + assert.NilError(c, err) defer stdout.Close() - c.Assert(cmd.Start(), checker.IsNil) + assert.NilError(c, cmd.Start()) defer func() { cmd.Process.Kill() cmd.Wait() @@ -509,19 +483,19 @@ func (s *DockerSuite) TestEventsAttach(c *check.C) { // Make sure we're done attaching by writing/reading some stuff _, err = stdin.Write([]byte("hello\n")) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) out, err = bufio.NewReader(stdout).ReadString('\n') - c.Assert(err, checker.IsNil) - c.Assert(strings.TrimSpace(out), checker.Equals, "hello", check.Commentf("expected 'hello'")) + assert.NilError(c, err) + assert.Equal(c, strings.TrimSpace(out), "hello") - c.Assert(stdin.Close(), checker.IsNil) + assert.NilError(c, stdin.Close()) cli.DockerCmd(c, "kill", cID) cli.WaitExited(c, cID, 5*time.Second) until := daemonUnixTime(c) out = cli.DockerCmd(c, "events", "-f", "container="+cID, "--until="+until).Combined() - c.Assert(out, checker.Contains, "attach", check.Commentf("Missing 'attach' log event")) + assert.Assert(c, strings.Contains(out, "attach"), "Missing 'attach' log event") } func (s *DockerSuite) TestEventsRename(c *check.C) { @@ -532,7 +506,7 @@ func (s *DockerSuite) TestEventsRename(c *check.C) { 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) - c.Assert(out, checker.Contains, "rename", check.Commentf("Missing 'rename' log event\n")) + assert.Assert(c, strings.Contains(out, "rename"), "Missing 'rename' log event") } func (s *DockerSuite) TestEventsTop(c *check.C) { @@ -541,14 +515,14 @@ func (s *DockerSuite) TestEventsTop(c *check.C) { out := runSleepingContainer(c, "-d") cID := strings.TrimSpace(out) - c.Assert(waitRun(cID), checker.IsNil) + assert.NilError(c, waitRun(cID)) dockerCmd(c, "top", cID) dockerCmd(c, "stop", cID) until := daemonUnixTime(c) out, _ = dockerCmd(c, "events", "-f", "container="+cID, "--until="+until) - c.Assert(out, checker.Contains, " top", check.Commentf("Missing 'top' log event")) + assert.Assert(c, strings.Contains(out, "top"), "Missing 'top' log event") } // #14316 @@ -561,7 +535,7 @@ func (s *DockerRegistrySuite) TestEventsImageFilterPush(c *check.C) { out, _ := dockerCmd(c, "run", "-d", "busybox", "top") cID := strings.TrimSpace(out) - c.Assert(waitRun(cID), checker.IsNil) + assert.NilError(c, waitRun(cID)) dockerCmd(c, "commit", cID, repoName) dockerCmd(c, "stop", cID) @@ -569,7 +543,7 @@ func (s *DockerRegistrySuite) TestEventsImageFilterPush(c *check.C) { until := daemonUnixTime(c) out, _ = dockerCmd(c, "events", "-f", "image="+repoName, "-f", "event=push", "--until", until) - c.Assert(out, checker.Contains, repoName, check.Commentf("Missing 'push' log event for %s", repoName)) + assert.Assert(c, strings.Contains(out, repoName), "Missing 'push' log event for %s", repoName) } func (s *DockerSuite) TestEventsFilterType(c *check.C) { @@ -598,9 +572,9 @@ func (s *DockerSuite) TestEventsFilterType(c *check.C) { events := strings.Split(strings.TrimSpace(out), "\n") // 2 events from the "docker tag" command, another one is from "docker build" - c.Assert(events, checker.HasLen, 3, check.Commentf("Events == %s", events)) + assert.Equal(c, len(events), 3, "Events == %s", events) for _, e := range events { - c.Assert(e, checker.Contains, "labelfiltertest") + assert.Check(c, strings.Contains(e, "labelfiltertest")) } out, _ = dockerCmd( @@ -613,7 +587,7 @@ func (s *DockerSuite) TestEventsFilterType(c *check.C) { events = strings.Split(strings.TrimSpace(out), "\n") // Events generated by the container that builds the image - c.Assert(events, checker.HasLen, 2, check.Commentf("Events == %s", events)) + assert.Equal(c, len(events), 2, "Events == %s", events) out, _ = dockerCmd( c, @@ -622,7 +596,7 @@ func (s *DockerSuite) TestEventsFilterType(c *check.C) { "--until", daemonUnixTime(c), "--filter", "type=network") events = strings.Split(strings.TrimSpace(out), "\n") - c.Assert(len(events), checker.GreaterOrEqualThan, 1, check.Commentf("Events == %s", events)) + assert.Assert(c, len(events) >= 1, "Events == %s", events) } // #25798 @@ -643,7 +617,7 @@ func (s *DockerSuite) TestEventsSpecialFiltersWithExecCreate(c *check.C) { ) events := strings.Split(strings.TrimSpace(out), "\n") - c.Assert(len(events), checker.Equals, 1, check.Commentf("%s", out)) + assert.Equal(c, len(events), 1, out) out, _ = dockerCmd( c, @@ -653,7 +627,7 @@ func (s *DockerSuite) TestEventsSpecialFiltersWithExecCreate(c *check.C) { "--filter", "event=exec_create", ) - c.Assert(len(events), checker.Equals, 1, check.Commentf("%s", out)) + assert.Equal(c, len(events), 1, out) } func (s *DockerSuite) TestEventsFilterImageInContainerAction(c *check.C) { @@ -663,7 +637,7 @@ func (s *DockerSuite) TestEventsFilterImageInContainerAction(c *check.C) { out, _ := dockerCmd(c, "events", "--filter", "image=busybox", "--since", since, "--until", daemonUnixTime(c)) events := strings.Split(strings.TrimSpace(out), "\n") - c.Assert(len(events), checker.GreaterThan, 1, check.Commentf("%s", out)) + assert.Assert(c, len(events) > 1, out) } func (s *DockerSuite) TestEventsContainerRestart(c *check.C) { @@ -677,7 +651,7 @@ func (s *DockerSuite) TestEventsContainerRestart(c *check.C) { } err := waitInspect("testEvent", "{{ .State.Restarting }} {{ .State.Running }}", "false false", waitTime) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) var ( createCount int @@ -688,7 +662,7 @@ func (s *DockerSuite) TestEventsContainerRestart(c *check.C) { events := strings.Split(strings.TrimSpace(out), "\n") nEvents := len(events) - c.Assert(nEvents, checker.GreaterOrEqualThan, 1) //Missing expected event + assert.Assert(c, nEvents >= 1) //Missing expected event actions := eventActionsByIDAndType(c, events, "testEvent", "container") for _, a := range actions { @@ -701,9 +675,9 @@ func (s *DockerSuite) TestEventsContainerRestart(c *check.C) { dieCount++ } } - c.Assert(createCount, checker.Equals, 1, check.Commentf("testEvent should be created 1 times: %v", actions)) - c.Assert(startCount, checker.Equals, 4, check.Commentf("testEvent should start 4 times: %v", actions)) - c.Assert(dieCount, checker.Equals, 4, check.Commentf("testEvent should die 4 times: %v", actions)) + assert.Equal(c, createCount, 1, "testEvent should be created 1 times: %v", actions) + assert.Equal(c, startCount, 4, "testEvent should start 4 times: %v", actions) + assert.Equal(c, dieCount, 4, "testEvent should die 4 times: %v", actions) } func (s *DockerSuite) TestEventsSinceInTheFuture(c *check.C) { @@ -714,8 +688,8 @@ func (s *DockerSuite) TestEventsSinceInTheFuture(c *check.C) { until := since.Add(time.Duration(-24) * time.Hour) out, _, err := dockerCmdWithError("events", "--filter", "image=busybox", "--since", parseEventTime(since), "--until", parseEventTime(until)) - c.Assert(err, checker.NotNil) - c.Assert(out, checker.Contains, "cannot be after `until`") + assert.ErrorContains(c, err, "") + assert.Assert(c, strings.Contains(out, "cannot be after `until`")) } func (s *DockerSuite) TestEventsUntilInThePast(c *check.C) { @@ -731,8 +705,8 @@ func (s *DockerSuite) TestEventsUntilInThePast(c *check.C) { out, _ := dockerCmd(c, "events", "--filter", "image=busybox", "--since", since, "--until", until) - c.Assert(out, checker.Not(checker.Contains), "test-container2") - c.Assert(out, checker.Contains, "test-container") + assert.Assert(c, !strings.Contains(out, "test-container2")) + assert.Assert(c, strings.Contains(out, "test-container")) } func (s *DockerSuite) TestEventsFormat(c *check.C) { @@ -749,13 +723,13 @@ func (s *DockerSuite) TestEventsFormat(c *check.C) { if err = dec.Decode(&ev); err == io.EOF { break } - c.Assert(err, checker.IsNil) + assert.NilError(c, err) if ev.Status == "start" { startCount++ } } - c.Assert(startCount, checker.Equals, 2, check.Commentf("should have had 2 start events but had %d, out: %s", startCount, out)) + assert.Equal(c, startCount, 2, "should have had 2 start events but had %d, out: %s", startCount, out) } func (s *DockerSuite) TestEventsFormatBadFunc(c *check.C) { diff --git a/components/engine/integration-cli/docker_cli_events_unix_test.go b/components/engine/integration-cli/docker_cli_events_unix_test.go index 73e558672c..05cd54fd4a 100644 --- a/components/engine/integration-cli/docker_cli_events_unix_test.go +++ b/components/engine/integration-cli/docker_cli_events_unix_test.go @@ -13,11 +13,11 @@ import ( "time" "unicode" - "github.com/docker/docker/integration-cli/checker" "github.com/docker/docker/integration-cli/cli/build" "github.com/go-check/check" "github.com/kr/pty" "golang.org/x/sys/unix" + "gotest.tools/assert" ) // #5979 @@ -26,26 +26,25 @@ func (s *DockerSuite) TestEventsRedirectStdout(c *check.C) { dockerCmd(c, "run", "busybox", "true") file, err := ioutil.TempFile("", "") - c.Assert(err, checker.IsNil, check.Commentf("could not create temp file")) + assert.NilError(c, err, "could not create temp file") defer os.Remove(file.Name()) command := fmt.Sprintf("%s events --since=%s --until=%s > %s", dockerBinary, since, daemonUnixTime(c), file.Name()) _, tty, err := pty.Open() - c.Assert(err, checker.IsNil, check.Commentf("Could not open pty")) + assert.NilError(c, err, "Could not open pty") cmd := exec.Command("sh", "-c", command) cmd.Stdin = tty cmd.Stdout = tty cmd.Stderr = tty - c.Assert(cmd.Run(), checker.IsNil, check.Commentf("run err for command %q", command)) + assert.NilError(c, cmd.Run(), "run err for command %q", command) scanner := bufio.NewScanner(file) for scanner.Scan() { for _, ch := range scanner.Text() { - c.Assert(unicode.IsControl(ch), checker.False, check.Commentf("found control character %v", []byte(string(ch)))) + assert.Check(c, unicode.IsControl(ch) == false, "found control character %v", []byte(string(ch))) } } - c.Assert(scanner.Err(), checker.IsNil, check.Commentf("Scan err for command %q", command)) - + assert.NilError(c, scanner.Err(), "Scan err for command %q", command) } func (s *DockerSuite) TestEventsOOMDisableFalse(c *check.C) { @@ -61,7 +60,7 @@ func (s *DockerSuite) TestEventsOOMDisableFalse(c *check.C) { }() select { case err := <-errChan: - c.Assert(err, checker.IsNil) + assert.NilError(c, err) case <-time.After(30 * time.Second): c.Fatal("Timeout waiting for container to die on OOM") } @@ -70,12 +69,12 @@ func (s *DockerSuite) TestEventsOOMDisableFalse(c *check.C) { events := strings.Split(strings.TrimSuffix(out, "\n"), "\n") nEvents := len(events) - c.Assert(nEvents, checker.GreaterOrEqualThan, 5) //Missing expected event - c.Assert(parseEventAction(c, events[nEvents-5]), checker.Equals, "create") - c.Assert(parseEventAction(c, events[nEvents-4]), checker.Equals, "attach") - c.Assert(parseEventAction(c, events[nEvents-3]), checker.Equals, "start") - c.Assert(parseEventAction(c, events[nEvents-2]), checker.Equals, "oom") - c.Assert(parseEventAction(c, events[nEvents-1]), checker.Equals, "die") + assert.Assert(c, nEvents >= 5) + assert.Equal(c, parseEventAction(c, events[nEvents-5]), "create") + assert.Equal(c, parseEventAction(c, events[nEvents-4]), "attach") + assert.Equal(c, parseEventAction(c, events[nEvents-3]), "start") + assert.Equal(c, parseEventAction(c, events[nEvents-2]), "oom") + assert.Equal(c, parseEventAction(c, events[nEvents-1]), "die") } func (s *DockerSuite) TestEventsOOMDisableTrue(c *check.C) { @@ -83,9 +82,9 @@ func (s *DockerSuite) TestEventsOOMDisableTrue(c *check.C) { errChan := make(chan error) observer, err := newEventObserver(c) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) err = observer.Start() - c.Assert(err, checker.IsNil) + assert.NilError(c, err) defer observer.Stop() go func() { @@ -96,7 +95,7 @@ func (s *DockerSuite) TestEventsOOMDisableTrue(c *check.C) { } }() - c.Assert(waitRun("oomTrue"), checker.IsNil) + assert.NilError(c, waitRun("oomTrue")) defer dockerCmdWithResult("kill", "oomTrue") containerID := inspectField(c, "oomTrue", "Id") @@ -122,7 +121,7 @@ func (s *DockerSuite) TestEventsOOMDisableTrue(c *check.C) { } status := inspectField(c, "oomTrue", "State.Status") - c.Assert(strings.TrimSpace(status), checker.Equals, "running", check.Commentf("container should be still running")) + assert.Equal(c, strings.TrimSpace(status), "running", "container should be still running") } // #18453 @@ -135,8 +134,8 @@ func (s *DockerSuite) TestEventsContainerFilterByName(c *check.C) { c2 := strings.TrimSpace(cOut) waitRun("bar") out, _ := dockerCmd(c, "events", "-f", "container=foo", "--since=0", "--until", daemonUnixTime(c)) - c.Assert(out, checker.Contains, c1, check.Commentf("%s", out)) - c.Assert(out, checker.Not(checker.Contains), c2, check.Commentf("%s", out)) + assert.Assert(c, strings.Contains(out, c1), out) + assert.Assert(c, !strings.Contains(out, c2), out) } // #18453 @@ -145,7 +144,7 @@ func (s *DockerSuite) TestEventsContainerFilterBeforeCreate(c *check.C) { buf := &bytes.Buffer{} cmd := exec.Command(dockerBinary, "events", "-f", "container=foo", "--since=0") cmd.Stdout = buf - c.Assert(cmd.Start(), check.IsNil) + assert.NilError(c, cmd.Start()) defer cmd.Wait() defer cmd.Process.Kill() @@ -182,15 +181,15 @@ func (s *DockerSuite) TestVolumeEvents(c *check.C) { until := daemonUnixTime(c) out, _ := dockerCmd(c, "events", "--since", since, "--until", until) events := strings.Split(strings.TrimSpace(out), "\n") - c.Assert(len(events), checker.GreaterThan, 4) + assert.Assert(c, len(events) > 4) volumeEvents := eventActionsByIDAndType(c, events, "test-event-volume-local", "volume") - c.Assert(volumeEvents, checker.HasLen, 5) - c.Assert(volumeEvents[0], checker.Equals, "create") - c.Assert(volumeEvents[1], checker.Equals, "create") - c.Assert(volumeEvents[2], checker.Equals, "mount") - c.Assert(volumeEvents[3], checker.Equals, "unmount") - c.Assert(volumeEvents[4], checker.Equals, "destroy") + assert.Equal(c, len(volumeEvents), 5) + assert.Equal(c, volumeEvents[0], "create") + assert.Equal(c, volumeEvents[1], "create") + assert.Equal(c, volumeEvents[2], "mount") + assert.Equal(c, volumeEvents[3], "unmount") + assert.Equal(c, volumeEvents[4], "destroy") } func (s *DockerSuite) TestNetworkEvents(c *check.C) { @@ -210,14 +209,14 @@ func (s *DockerSuite) TestNetworkEvents(c *check.C) { until := daemonUnixTime(c) out, _ := dockerCmd(c, "events", "--since", since, "--until", until) events := strings.Split(strings.TrimSpace(out), "\n") - c.Assert(len(events), checker.GreaterThan, 4) + assert.Assert(c, len(events) > 4) netEvents := eventActionsByIDAndType(c, events, "test-event-network-local", "network") - c.Assert(netEvents, checker.HasLen, 4) - c.Assert(netEvents[0], checker.Equals, "create") - c.Assert(netEvents[1], checker.Equals, "connect") - c.Assert(netEvents[2], checker.Equals, "disconnect") - c.Assert(netEvents[3], checker.Equals, "destroy") + assert.Equal(c, len(netEvents), 4) + assert.Equal(c, netEvents[0], "create") + assert.Equal(c, netEvents[1], "connect") + assert.Equal(c, netEvents[2], "disconnect") + assert.Equal(c, netEvents[3], "destroy") } func (s *DockerSuite) TestEventsContainerWithMultiNetwork(c *check.C) { @@ -239,22 +238,22 @@ func (s *DockerSuite) TestEventsContainerWithMultiNetwork(c *check.C) { netEvents := strings.Split(strings.TrimSpace(out), "\n") // received two network disconnect events - c.Assert(len(netEvents), checker.Equals, 2) - c.Assert(netEvents[0], checker.Contains, "disconnect") - c.Assert(netEvents[1], checker.Contains, "disconnect") + assert.Equal(c, len(netEvents), 2) + assert.Assert(c, strings.Contains(netEvents[0], "disconnect")) + assert.Assert(c, strings.Contains(netEvents[1], "disconnect")) //both networks appeared in the network event output - c.Assert(out, checker.Contains, "test-event-network-local-1") - c.Assert(out, checker.Contains, "test-event-network-local-2") + assert.Assert(c, strings.Contains(out, "test-event-network-local-1")) + assert.Assert(c, strings.Contains(out, "test-event-network-local-2")) } func (s *DockerSuite) TestEventsStreaming(c *check.C) { testRequires(c, DaemonIsLinux) observer, err := newEventObserver(c) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) err = observer.Start() - c.Assert(err, checker.IsNil) + assert.NilError(c, err) defer observer.Stop() out, _ := dockerCmd(c, "run", "-d", "busybox:latest", "true") @@ -306,16 +305,16 @@ func (s *DockerSuite) TestEventsImageUntagDelete(c *check.C) { testRequires(c, DaemonIsLinux) observer, err := newEventObserver(c) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) err = observer.Start() - c.Assert(err, checker.IsNil) + assert.NilError(c, err) defer observer.Stop() name := "testimageevents" buildImageSuccessfully(c, name, build.WithDockerfile(`FROM scratch MAINTAINER "docker"`)) imageID := getIDByName(c, name) - c.Assert(deleteImages(name), checker.IsNil) + assert.NilError(c, deleteImages(name)) testActions := map[string]chan bool{ "untag": make(chan bool, 1), @@ -351,13 +350,13 @@ func (s *DockerSuite) TestEventsFilterVolumeAndNetworkType(c *check.C) { out, _ := dockerCmd(c, "events", "--filter", "type=volume", "--filter", "type=network", "--since", since, "--until", daemonUnixTime(c)) events := strings.Split(strings.TrimSpace(out), "\n") - c.Assert(len(events), checker.GreaterOrEqualThan, 2, check.Commentf("%s", out)) + assert.Assert(c, len(events) >= 2, out) networkActions := eventActionsByIDAndType(c, events, "test-event-network-type", "network") volumeActions := eventActionsByIDAndType(c, events, "test-event-volume-type", "volume") - c.Assert(volumeActions[0], checker.Equals, "create") - c.Assert(networkActions[0], checker.Equals, "create") + assert.Equal(c, volumeActions[0], "create") + assert.Equal(c, networkActions[0], "create") } func (s *DockerSuite) TestEventsFilterVolumeID(c *check.C) { @@ -368,10 +367,11 @@ func (s *DockerSuite) TestEventsFilterVolumeID(c *check.C) { dockerCmd(c, "volume", "create", "test-event-volume-id") out, _ := dockerCmd(c, "events", "--filter", "volume=test-event-volume-id", "--since", since, "--until", daemonUnixTime(c)) events := strings.Split(strings.TrimSpace(out), "\n") - c.Assert(events, checker.HasLen, 1) + assert.Equal(c, len(events), 1) - c.Assert(events[0], checker.Contains, "test-event-volume-id") - c.Assert(events[0], checker.Contains, "driver=local") + assert.Equal(c, len(events), 1) + assert.Assert(c, strings.Contains(events[0], "test-event-volume-id")) + assert.Assert(c, strings.Contains(events[0], "driver=local")) } func (s *DockerSuite) TestEventsFilterNetworkID(c *check.C) { @@ -382,10 +382,9 @@ func (s *DockerSuite) TestEventsFilterNetworkID(c *check.C) { dockerCmd(c, "network", "create", "test-event-network-local") out, _ := dockerCmd(c, "events", "--filter", "network=test-event-network-local", "--since", since, "--until", daemonUnixTime(c)) events := strings.Split(strings.TrimSpace(out), "\n") - c.Assert(events, checker.HasLen, 1) - - c.Assert(events[0], checker.Contains, "test-event-network-local") - c.Assert(events[0], checker.Contains, "type=bridge") + assert.Equal(c, len(events), 1) + assert.Assert(c, strings.Contains(events[0], "test-event-network-local")) + assert.Assert(c, strings.Contains(events[0], "type=bridge")) } func (s *DockerDaemonSuite) TestDaemonEvents(c *check.C) { @@ -394,7 +393,7 @@ func (s *DockerDaemonSuite) TestDaemonEvents(c *check.C) { // daemon config file configFilePath := "test.json" configFile, err := os.Create(configFilePath) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) defer os.Remove(configFilePath) daemonConfig := `{"labels":["foo=bar"]}` @@ -404,7 +403,7 @@ func (s *DockerDaemonSuite) TestDaemonEvents(c *check.C) { // Get daemon ID out, err := s.d.Cmd("info") - c.Assert(err, checker.IsNil) + assert.NilError(c, err) daemonID := "" daemonName := "" for _, line := range strings.Split(out, "\n") { @@ -414,20 +413,20 @@ func (s *DockerDaemonSuite) TestDaemonEvents(c *check.C) { daemonName = strings.TrimPrefix(line, "Name: ") } } - c.Assert(daemonID, checker.Not(checker.Equals), "") + assert.Assert(c, daemonID != "") configFile, err = os.Create(configFilePath) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) daemonConfig = `{"max-concurrent-downloads":1,"labels":["bar=foo"], "shutdown-timeout": 10}` fmt.Fprintf(configFile, "%s", daemonConfig) configFile.Close() - c.Assert(s.d.Signal(unix.SIGHUP), checker.IsNil) + assert.NilError(c, s.d.Signal(unix.SIGHUP)) time.Sleep(3 * time.Second) out, err = s.d.Cmd("events", "--since=0", "--until", daemonUnixTime(c)) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) // only check for values known (daemon ID/name) or explicitly set above, // otherwise just check for names being present. @@ -453,7 +452,7 @@ func (s *DockerDaemonSuite) TestDaemonEvents(c *check.C) { } for _, s := range expectedSubstrings { - c.Assert(out, checker.Contains, s) + assert.Check(c, strings.Contains(out, s)) } } @@ -463,7 +462,7 @@ func (s *DockerDaemonSuite) TestDaemonEventsWithFilters(c *check.C) { // daemon config file configFilePath := "test.json" configFile, err := os.Create(configFilePath) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) defer os.Remove(configFilePath) daemonConfig := `{"labels":["foo=bar"]}` @@ -473,7 +472,7 @@ func (s *DockerDaemonSuite) TestDaemonEventsWithFilters(c *check.C) { // Get daemon ID out, err := s.d.Cmd("info") - c.Assert(err, checker.IsNil) + assert.NilError(c, err) daemonID := "" daemonName := "" for _, line := range strings.Split(out, "\n") { @@ -483,29 +482,28 @@ func (s *DockerDaemonSuite) TestDaemonEventsWithFilters(c *check.C) { daemonName = strings.TrimPrefix(line, "Name: ") } } - c.Assert(daemonID, checker.Not(checker.Equals), "") - - c.Assert(s.d.Signal(unix.SIGHUP), checker.IsNil) + assert.Assert(c, daemonID != "") + assert.NilError(c, s.d.Signal(unix.SIGHUP)) time.Sleep(3 * time.Second) out, err = s.d.Cmd("events", "--since=0", "--until", daemonUnixTime(c), "--filter", fmt.Sprintf("daemon=%s", daemonID)) - c.Assert(err, checker.IsNil) - c.Assert(out, checker.Contains, fmt.Sprintf("daemon reload %s", daemonID)) + assert.NilError(c, err) + assert.Assert(c, strings.Contains(out, fmt.Sprintf("daemon reload %s", daemonID))) out, err = s.d.Cmd("events", "--since=0", "--until", daemonUnixTime(c), "--filter", fmt.Sprintf("daemon=%s", daemonName)) - c.Assert(err, checker.IsNil) - c.Assert(out, checker.Contains, fmt.Sprintf("daemon reload %s", daemonID)) + assert.NilError(c, err) + assert.Assert(c, strings.Contains(out, fmt.Sprintf("daemon reload %s", daemonID))) out, err = s.d.Cmd("events", "--since=0", "--until", daemonUnixTime(c), "--filter", "daemon=foo") - c.Assert(err, checker.IsNil) - c.Assert(out, checker.Not(checker.Contains), fmt.Sprintf("daemon reload %s", daemonID)) + assert.NilError(c, err) + assert.Assert(c, !strings.Contains(out, fmt.Sprintf("daemon reload %s", daemonID))) out, err = s.d.Cmd("events", "--since=0", "--until", daemonUnixTime(c), "--filter", "type=daemon") - c.Assert(err, checker.IsNil) - c.Assert(out, checker.Contains, fmt.Sprintf("daemon reload %s", daemonID)) + assert.NilError(c, err) + assert.Assert(c, strings.Contains(out, fmt.Sprintf("daemon reload %s", daemonID))) out, err = s.d.Cmd("events", "--since=0", "--until", daemonUnixTime(c), "--filter", "type=container") - c.Assert(err, checker.IsNil) - c.Assert(out, checker.Not(checker.Contains), fmt.Sprintf("daemon reload %s", daemonID)) + assert.NilError(c, err) + assert.Assert(c, !strings.Contains(out, fmt.Sprintf("daemon reload %s", daemonID))) } diff --git a/components/engine/integration-cli/docker_cli_exec_test.go b/components/engine/integration-cli/docker_cli_exec_test.go index cdfd307041..5f60a76409 100644 --- a/components/engine/integration-cli/docker_cli_exec_test.go +++ b/components/engine/integration-cli/docker_cli_exec_test.go @@ -17,23 +17,22 @@ import ( "time" "github.com/docker/docker/client" - "github.com/docker/docker/integration-cli/checker" "github.com/docker/docker/integration-cli/cli" "github.com/docker/docker/integration-cli/cli/build" "github.com/docker/docker/pkg/parsers/kernel" "github.com/go-check/check" + "gotest.tools/assert" + is "gotest.tools/assert/cmp" "gotest.tools/icmd" ) func (s *DockerSuite) TestExec(c *check.C) { testRequires(c, DaemonIsLinux) out, _ := dockerCmd(c, "run", "-d", "--name", "testing", "busybox", "sh", "-c", "echo test > /tmp/file && top") - c.Assert(waitRun(strings.TrimSpace(out)), check.IsNil) + assert.NilError(c, waitRun(strings.TrimSpace(out))) out, _ = dockerCmd(c, "exec", "testing", "cat", "/tmp/file") - out = strings.Trim(out, "\r\n") - c.Assert(out, checker.Equals, "test") - + assert.Equal(c, strings.Trim(out, "\r\n"), "test") } func (s *DockerSuite) TestExecInteractive(c *check.C) { @@ -42,22 +41,22 @@ func (s *DockerSuite) TestExecInteractive(c *check.C) { execCmd := exec.Command(dockerBinary, "exec", "-i", "testing", "sh") stdin, err := execCmd.StdinPipe() - c.Assert(err, checker.IsNil) + assert.NilError(c, err) stdout, err := execCmd.StdoutPipe() - c.Assert(err, checker.IsNil) + assert.NilError(c, err) err = execCmd.Start() - c.Assert(err, checker.IsNil) + assert.NilError(c, err) _, err = stdin.Write([]byte("cat /tmp/file\n")) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) r := bufio.NewReader(stdout) line, err := r.ReadString('\n') - c.Assert(err, checker.IsNil) + assert.NilError(c, err) line = strings.TrimSpace(line) - c.Assert(line, checker.Equals, "test") + assert.Equal(c, line, "test") err = stdin.Close() - c.Assert(err, checker.IsNil) + assert.NilError(c, err) errChan := make(chan error) go func() { errChan <- execCmd.Wait() @@ -65,7 +64,7 @@ func (s *DockerSuite) TestExecInteractive(c *check.C) { }() select { case err := <-errChan: - c.Assert(err, checker.IsNil) + assert.NilError(c, err) case <-time.After(1 * time.Second): c.Fatal("docker exec failed to exit on stdin close") } @@ -75,13 +74,12 @@ func (s *DockerSuite) TestExecInteractive(c *check.C) { func (s *DockerSuite) TestExecAfterContainerRestart(c *check.C) { out := runSleepingContainer(c) cleanedContainerID := strings.TrimSpace(out) - c.Assert(waitRun(cleanedContainerID), check.IsNil) + assert.NilError(c, waitRun(cleanedContainerID)) dockerCmd(c, "restart", cleanedContainerID) - c.Assert(waitRun(cleanedContainerID), check.IsNil) + assert.NilError(c, waitRun(cleanedContainerID)) out, _ = dockerCmd(c, "exec", cleanedContainerID, "echo", "hello") - outStr := strings.TrimSpace(out) - c.Assert(outStr, checker.Equals, "hello") + assert.Equal(c, strings.TrimSpace(out), "hello") } func (s *DockerDaemonSuite) TestExecAfterDaemonRestart(c *check.C) { @@ -90,18 +88,16 @@ func (s *DockerDaemonSuite) TestExecAfterDaemonRestart(c *check.C) { s.d.StartWithBusybox(c) out, err := s.d.Cmd("run", "-d", "--name", "top", "-p", "80", "busybox:latest", "top") - c.Assert(err, checker.IsNil, check.Commentf("Could not run top: %s", out)) + assert.NilError(c, err, "Could not run top: %s", out) s.d.Restart(c) out, err = s.d.Cmd("start", "top") - c.Assert(err, checker.IsNil, check.Commentf("Could not start top after daemon restart: %s", out)) + assert.NilError(c, err, "Could not start top after daemon restart: %s", out) out, err = s.d.Cmd("exec", "top", "echo", "hello") - c.Assert(err, checker.IsNil, check.Commentf("Could not exec on container top: %s", out)) - - outStr := strings.TrimSpace(string(out)) - c.Assert(outStr, checker.Equals, "hello") + assert.NilError(c, err, "Could not exec on container top: %s", out) + assert.Equal(c, strings.TrimSpace(out), "hello") } // Regression test for #9155, #9044 @@ -112,23 +108,23 @@ func (s *DockerSuite) TestExecEnv(c *check.C) { // a subsequent exec will not have LALA set/ testRequires(c, DaemonIsLinux) runSleepingContainer(c, "-e", "LALA=value1", "-e", "LALA=value2", "-d", "--name", "testing") - c.Assert(waitRun("testing"), check.IsNil) + assert.NilError(c, waitRun("testing")) out, _ := dockerCmd(c, "exec", "testing", "env") - c.Assert(out, checker.Not(checker.Contains), "LALA=value1") - c.Assert(out, checker.Contains, "LALA=value2") - c.Assert(out, checker.Contains, "HOME=/root") + assert.Check(c, !strings.Contains(out, "LALA=value1")) + assert.Check(c, strings.Contains(out, "LALA=value2")) + assert.Check(c, strings.Contains(out, "HOME=/root")) } func (s *DockerSuite) TestExecSetEnv(c *check.C) { testRequires(c, DaemonIsLinux) runSleepingContainer(c, "-e", "HOME=/root", "-d", "--name", "testing") - c.Assert(waitRun("testing"), check.IsNil) + assert.NilError(c, waitRun("testing")) out, _ := dockerCmd(c, "exec", "-e", "HOME=/another", "-e", "ABC=xyz", "testing", "env") - c.Assert(out, checker.Not(checker.Contains), "HOME=/root") - c.Assert(out, checker.Contains, "HOME=/another") - c.Assert(out, checker.Contains, "ABC=xyz") + assert.Check(c, !strings.Contains(out, "HOME=/root")) + assert.Check(c, strings.Contains(out, "HOME=/another")) + assert.Check(c, strings.Contains(out, "ABC=xyz")) } func (s *DockerSuite) TestExecExitStatus(c *check.C) { @@ -146,10 +142,10 @@ func (s *DockerSuite) TestExecPausedContainer(c *check.C) { dockerCmd(c, "pause", "testing") out, _, err := dockerCmdWithError("exec", ContainerID, "echo", "hello") - c.Assert(err, checker.NotNil, check.Commentf("container should fail to exec new command if it is paused")) + assert.ErrorContains(c, err, "", "container should fail to exec new command if it is paused") expected := ContainerID + " is paused, unpause the container before exec" - c.Assert(out, checker.Contains, expected, check.Commentf("container should not exec new command if it is paused")) + assert.Assert(c, is.Contains(out, expected), "container should not exec new command if it is paused") } // regression test for #9476 @@ -160,24 +156,24 @@ func (s *DockerSuite) TestExecTTYCloseStdin(c *check.C) { cmd := exec.Command(dockerBinary, "exec", "-i", "exec_tty_stdin", "cat") stdinRw, err := cmd.StdinPipe() - c.Assert(err, checker.IsNil) + assert.NilError(c, err) stdinRw.Write([]byte("test")) stdinRw.Close() out, _, err := runCommandWithOutput(cmd) - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) out, _ = dockerCmd(c, "top", "exec_tty_stdin") outArr := strings.Split(out, "\n") - c.Assert(len(outArr), checker.LessOrEqualThan, 3, check.Commentf("exec process left running")) - c.Assert(out, checker.Not(checker.Contains), "nsenter-exec") + assert.Assert(c, len(outArr) <= 3, "exec process left running") + assert.Assert(c, !strings.Contains(out, "nsenter-exec")) } func (s *DockerSuite) TestExecTTYWithoutStdin(c *check.C) { out, _ := dockerCmd(c, "run", "-d", "-ti", "busybox") id := strings.TrimSpace(out) - c.Assert(waitRun(id), checker.IsNil) + assert.NilError(c, waitRun(id)) errChan := make(chan error) go func() { @@ -204,7 +200,7 @@ func (s *DockerSuite) TestExecTTYWithoutStdin(c *check.C) { select { case err := <-errChan: - c.Assert(err, check.IsNil) + assert.NilError(c, err) case <-time.After(3 * time.Second): c.Fatal("exec is running but should have failed") } @@ -249,7 +245,7 @@ func (s *DockerSuite) TestExecStopNotHanging(c *check.C) { case <-time.After(3 * time.Second): c.Fatal("Container stop timed out") case s := <-ch: - c.Assert(s.err, check.IsNil) + assert.NilError(c, s.err) } } @@ -287,7 +283,7 @@ func (s *DockerSuite) TestExecCgroup(c *check.C) { close(errChan) for err := range errChan { - c.Assert(err, checker.IsNil) + assert.NilError(c, err) } for _, cg := range execCgroups { @@ -311,14 +307,14 @@ func (s *DockerSuite) TestExecInspectID(c *check.C) { id := strings.TrimSuffix(out, "\n") out = inspectField(c, id, "ExecIDs") - c.Assert(out, checker.Equals, "[]", check.Commentf("ExecIDs should be empty, got: %s", out)) + assert.Equal(c, out, "[]", "ExecIDs should be empty, got: %s", out) // Start an exec, have it block waiting so we can do some checking cmd := exec.Command(dockerBinary, "exec", id, "sh", "-c", "while ! test -e /execid1; do sleep 1; done") err := cmd.Start() - c.Assert(err, checker.IsNil, check.Commentf("failed to start the exec cmd")) + assert.NilError(c, err, "failed to start the exec cmd") // Give the exec 10 chances/seconds to start then give up and stop the test tries := 10 @@ -329,19 +325,17 @@ func (s *DockerSuite) TestExecInspectID(c *check.C) { if out != "[]" && out != "" { break } - c.Assert(i+1, checker.Not(checker.Equals), tries, check.Commentf("ExecIDs still empty after 10 second")) + assert.Check(c, i+1 != tries, "ExecIDs still empty after 10 second") time.Sleep(1 * time.Second) } // Save execID for later execID, err := inspectFilter(id, "index .ExecIDs 0") - c.Assert(err, checker.IsNil, check.Commentf("failed to get the exec id")) + assert.NilError(c, err, "failed to get the exec id") // End the exec by creating the missing file - err = exec.Command(dockerBinary, "exec", id, - "sh", "-c", "touch /execid1").Run() - - c.Assert(err, checker.IsNil, check.Commentf("failed to run the 2nd exec cmd")) + err = exec.Command(dockerBinary, "exec", id, "sh", "-c", "touch /execid1").Run() + assert.NilError(c, err, "failed to run the 2nd exec cmd") // Wait for 1st exec to complete cmd.Wait() @@ -354,26 +348,25 @@ func (s *DockerSuite) TestExecInspectID(c *check.C) { if out == "[]" { break } - c.Assert(i+1, checker.Not(checker.Equals), tries, check.Commentf("ExecIDs still not empty after 10 second")) + assert.Check(c, i+1 != tries, "ExecIDs still empty after 10 second") time.Sleep(1 * time.Second) } // But we should still be able to query the execID cli, err := client.NewClientWithOpts(client.FromEnv) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) defer cli.Close() _, err = cli.ContainerExecInspect(context.Background(), execID) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) // 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) - c.Assert(ec, checker.Equals, 0, check.Commentf("error removing container: %s", out)) + assert.Equal(c, ec, 0, "error removing container: %s", out) _, err = cli.ContainerExecInspect(context.Background(), execID) - expected := "No such exec instance" - c.Assert(err.Error(), checker.Contains, expected) + assert.ErrorContains(c, err, "No such exec instance") } func (s *DockerSuite) TestLinksPingLinkedContainersOnRename(c *check.C) { @@ -382,10 +375,10 @@ func (s *DockerSuite) TestLinksPingLinkedContainersOnRename(c *check.C) { var out string out, _ = dockerCmd(c, "run", "-d", "--name", "container1", "busybox", "top") idA := strings.TrimSpace(out) - c.Assert(idA, checker.Not(checker.Equals), "", check.Commentf("%s, id should not be nil", out)) + assert.Assert(c, idA != "", "%s, id should not be nil", out) out, _ = dockerCmd(c, "run", "-d", "--link", "container1:alias1", "--name", "container2", "busybox", "top") idB := strings.TrimSpace(out) - c.Assert(idB, checker.Not(checker.Equals), "", check.Commentf("%s, id should not be nil", 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") @@ -403,14 +396,14 @@ func (s *DockerSuite) TestRunMutableNetworkFiles(c *check.C) { content := runCommandAndReadContainerFile(c, fn, dockerBinary, "run", "-d", "--name", "c1", "busybox", "sh", "-c", fmt.Sprintf("echo success >/etc/%s && top", fn)) - c.Assert(strings.TrimSpace(string(content)), checker.Equals, "success", check.Commentf("Content was not what was modified in the container", string(content))) + 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") contID := strings.TrimSpace(out) netFilePath := containerStorageFile(contID, fn) f, err := os.OpenFile(netFilePath, os.O_WRONLY|os.O_SYNC|os.O_APPEND, 0644) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) if _, err := f.Seek(0, 0); err != nil { f.Close() @@ -429,7 +422,7 @@ func (s *DockerSuite) TestRunMutableNetworkFiles(c *check.C) { f.Close() res, _ := dockerCmd(c, "exec", contID, "cat", "/etc/"+fn) - c.Assert(res, checker.Equals, "success2\n") + assert.Equal(c, res, "success2\n") } } @@ -440,10 +433,10 @@ func (s *DockerSuite) TestExecWithUser(c *check.C) { dockerCmd(c, "run", "-d", "--name", "parent", "busybox", "top") out, _ := dockerCmd(c, "exec", "-u", "1", "parent", "id") - c.Assert(out, checker.Contains, "uid=1(daemon) gid=1(daemon)") + assert.Assert(c, strings.Contains(out, "uid=1(daemon) gid=1(daemon)")) out, _ = dockerCmd(c, "exec", "-u", "root", "parent", "id") - c.Assert(out, checker.Contains, "uid=0(root) gid=0(root)", check.Commentf("exec with user by id expected daemon user got %s", out)) + assert.Assert(c, strings.Contains(out, "uid=0(root) gid=0(root)"), "exec with user by id expected daemon user got %s", out) } func (s *DockerSuite) TestExecWithPrivileged(c *check.C) { @@ -463,7 +456,7 @@ func (s *DockerSuite) TestExecWithPrivileged(c *check.C) { result.Assert(c, icmd.Success) actual := strings.TrimSpace(result.Combined()) - c.Assert(actual, checker.Equals, "ok", check.Commentf("exec mknod in --cap-drop=ALL container with --privileged failed, output: %q", result.Combined())) + assert.Equal(c, actual, "ok", "exec mknod in --cap-drop=ALL container with --privileged failed, output: %q", result.Combined()) // Check subsequent unprivileged exec cannot mknod icmd.RunCommand(dockerBinary, "exec", "parent", "sh", "-c", "mknod /tmp/sdc b 8 32").Assert(c, icmd.Expected{ @@ -473,8 +466,7 @@ func (s *DockerSuite) TestExecWithPrivileged(c *check.C) { // Confirm at no point was mknod allowed result = icmd.RunCommand(dockerBinary, "logs", "parent") result.Assert(c, icmd.Success) - c.Assert(result.Combined(), checker.Not(checker.Contains), "Success") - + assert.Assert(c, !strings.Contains(result.Combined(), "Success")) } func (s *DockerSuite) TestExecWithImageUser(c *check.C) { @@ -487,7 +479,7 @@ func (s *DockerSuite) TestExecWithImageUser(c *check.C) { dockerCmd(c, "run", "-d", "--name", "dockerioexec", name, "top") out, _ := dockerCmd(c, "exec", "dockerioexec", "whoami") - c.Assert(out, checker.Contains, "dockerio", check.Commentf("exec with user by id expected dockerio user got %s", out)) + assert.Assert(c, strings.Contains(out, "dockerio"), "exec with user by id expected dockerio user got %s", out) } func (s *DockerSuite) TestExecOnReadonlyContainer(c *check.C) { @@ -502,11 +494,11 @@ func (s *DockerSuite) TestExecUlimits(c *check.C) { testRequires(c, DaemonIsLinux) name := "testexeculimits" runSleepingContainer(c, "-d", "--ulimit", "nofile=511:511", "--name", name) - c.Assert(waitRun(name), checker.IsNil) + assert.NilError(c, waitRun(name)) out, _, err := dockerCmdWithError("exec", name, "sh", "-c", "ulimit -n") - c.Assert(err, checker.IsNil) - c.Assert(strings.TrimSpace(out), checker.Equals, "511") + assert.NilError(c, err) + assert.Equal(c, strings.TrimSpace(out), "511") } // #15750 @@ -516,22 +508,22 @@ func (s *DockerSuite) TestExecStartFails(c *check.C) { testRequires(c, DaemonIsLinux) name := "exec-15750" runSleepingContainer(c, "-d", "--name", name) - c.Assert(waitRun(name), checker.IsNil) + assert.NilError(c, waitRun(name)) out, _, err := dockerCmdWithError("exec", name, "no-such-cmd") - c.Assert(err, checker.NotNil, check.Commentf("%s", out)) - c.Assert(out, checker.Contains, "executable file not found") + assert.ErrorContains(c, err, "", out) + assert.Assert(c, strings.Contains(out, "executable file not found")) } // Fix regression in https://github.com/docker/docker/pull/26461#issuecomment-250287297 func (s *DockerSuite) TestExecWindowsPathNotWiped(c *check.C) { testRequires(c, DaemonIsWindows) out, _ := dockerCmd(c, "run", "-d", "--name", "testing", minimalBaseImage(), "powershell", "start-sleep", "60") - c.Assert(waitRun(strings.TrimSpace(out)), check.IsNil) + assert.NilError(c, waitRun(strings.TrimSpace(out))) out, _ = dockerCmd(c, "exec", "testing", "powershell", "write-host", "$env:PATH") out = strings.ToLower(strings.Trim(out, "\r\n")) - c.Assert(out, checker.Contains, `windowspowershell\v1.0`) + assert.Assert(c, strings.Contains(out, `windowspowershell\v1.0`)) } func (s *DockerSuite) TestExecEnvLinksHost(c *check.C) { @@ -539,8 +531,8 @@ func (s *DockerSuite) TestExecEnvLinksHost(c *check.C) { runSleepingContainer(c, "-d", "--name", "foo") runSleepingContainer(c, "-d", "--link", "foo:db", "--hostname", "myhost", "--name", "bar") out, _ := dockerCmd(c, "exec", "bar", "env") - c.Assert(out, checker.Contains, "HOSTNAME=myhost") - c.Assert(out, checker.Contains, "DB_NAME=/bar/db") + assert.Check(c, is.Contains(out, "HOSTNAME=myhost")) + assert.Check(c, is.Contains(out, "DB_NAME=/bar/db")) } func (s *DockerSuite) TestExecWindowsOpenHandles(c *check.C) { @@ -548,7 +540,7 @@ func (s *DockerSuite) TestExecWindowsOpenHandles(c *check.C) { if runtime.GOOS == "windows" { v, err := kernel.GetKernelVersion() - c.Assert(err, checker.IsNil) + assert.NilError(c, err) build, _ := strconv.Atoi(strings.Split(strings.SplitN(v.String(), " ", 3)[2][1:], ".")[0]) if build >= 17743 { c.Skip("Temporarily disabled on RS5 17743+ builds due to platform bug") @@ -626,7 +618,7 @@ func (s *DockerSuite) TestExecWindowsOpenHandles(c *check.C) { // Ensure the background sleep is still running out, _ := dockerCmd(c, "top", "test") - c.Assert(strings.Count(out, "busybox.exe"), checker.Equals, 2) + assert.Equal(c, strings.Count(out, "busybox.exe"), 2) // The exec should exit when the background sleep exits select { @@ -635,7 +627,7 @@ func (s *DockerSuite) TestExecWindowsOpenHandles(c *check.C) { case <-exec: // Ensure the background sleep has actually exited out, _ := dockerCmd(c, "top", "test") - c.Assert(strings.Count(out, "busybox.exe"), checker.Equals, 1) + assert.Equal(c, strings.Count(out, "busybox.exe"), 1) break } } diff --git a/components/engine/integration-cli/docker_cli_exec_unix_test.go b/components/engine/integration-cli/docker_cli_exec_unix_test.go index 9c58430282..8f860072c5 100644 --- a/components/engine/integration-cli/docker_cli_exec_unix_test.go +++ b/components/engine/integration-cli/docker_cli_exec_unix_test.go @@ -9,9 +9,9 @@ import ( "strings" "time" - "github.com/docker/docker/integration-cli/checker" "github.com/go-check/check" "github.com/kr/pty" + "gotest.tools/assert" ) // regression test for #12546 @@ -22,7 +22,7 @@ func (s *DockerSuite) TestExecInteractiveStdinClose(c *check.C) { cmd := exec.Command(dockerBinary, "exec", "-i", contID, "echo", "-n", "hello") p, err := pty.Start(cmd) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) b := bytes.NewBuffer(nil) @@ -31,13 +31,13 @@ func (s *DockerSuite) TestExecInteractiveStdinClose(c *check.C) { select { case err := <-ch: - c.Assert(err, checker.IsNil) + assert.NilError(c, err) io.Copy(b, p) p.Close() bs := b.Bytes() bs = bytes.Trim(bs, "\x00") output := string(bs[:]) - c.Assert(strings.TrimSpace(output), checker.Equals, "hello") + assert.Equal(c, strings.TrimSpace(output), "hello") case <-time.After(5 * time.Second): p.Close() c.Fatal("timed out running docker exec") @@ -50,11 +50,11 @@ func (s *DockerSuite) TestExecTTY(c *check.C) { cmd := exec.Command(dockerBinary, "exec", "-it", "test", "sh") p, err := pty.Start(cmd) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) defer p.Close() _, err = p.Write([]byte("cat /foo && exit\n")) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) chErr := make(chan error) go func() { @@ -62,15 +62,15 @@ func (s *DockerSuite) TestExecTTY(c *check.C) { }() select { case err := <-chErr: - c.Assert(err, checker.IsNil) + assert.NilError(c, err) case <-time.After(3 * time.Second): c.Fatal("timeout waiting for exec to exit") } buf := make([]byte, 256) read, err := p.Read(buf) - c.Assert(err, checker.IsNil) - c.Assert(bytes.Contains(buf, []byte("hello")), checker.Equals, true, check.Commentf(string(buf[:read]))) + assert.NilError(c, err) + assert.Assert(c, bytes.Contains(buf, []byte("hello")), string(buf[:read])) } // Test the TERM env var is set when -t is provided on exec @@ -80,7 +80,7 @@ func (s *DockerSuite) TestExecWithTERM(c *check.C) { 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 { - c.Assert(err, checker.IsNil) + assert.NilError(c, err) } } @@ -92,6 +92,6 @@ func (s *DockerSuite) TestExecWithNoTERM(c *check.C) { 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 { - c.Assert(err, checker.IsNil) + assert.NilError(c, err) } } diff --git a/components/engine/integration-cli/docker_cli_external_volume_driver_unix_test.go b/components/engine/integration-cli/docker_cli_external_volume_driver_unix_test.go index 063f49822b..b876d9f6fe 100644 --- a/components/engine/integration-cli/docker_cli_external_volume_driver_unix_test.go +++ b/components/engine/integration-cli/docker_cli_external_volume_driver_unix_test.go @@ -22,6 +22,7 @@ import ( "github.com/docker/docker/pkg/stringid" "github.com/docker/docker/volume" "github.com/go-check/check" + "gotest.tools/assert" ) const volumePluginName = "test-external-volume-driver" @@ -268,10 +269,10 @@ func newVolumePlugin(c *check.C, name string) *volumePlugin { }) err := os.MkdirAll("/etc/docker/plugins", 0755) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) err = ioutil.WriteFile("/etc/docker/plugins/"+name+".spec", []byte(s.Server.URL), 0644) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) return s } @@ -279,7 +280,7 @@ func (s *DockerExternalVolumeSuite) TearDownSuite(c *check.C) { s.volumePlugin.Close() err := os.RemoveAll("/etc/docker/plugins") - c.Assert(err, checker.IsNil) + assert.NilError(c, err) } func (s *DockerExternalVolumeSuite) TestVolumeCLICreateOptionConflict(c *check.C) { @@ -291,22 +292,22 @@ func (s *DockerExternalVolumeSuite) TestVolumeCLICreateOptionConflict(c *check.C out, _ = dockerCmd(c, "volume", "inspect", "--format={{ .Driver }}", "test") _, _, err = dockerCmdWithError("volume", "create", "test", "--driver", strings.TrimSpace(out)) - c.Assert(err, check.IsNil) + assert.NilError(c, err) } func (s *DockerExternalVolumeSuite) TestExternalVolumeDriverNamed(c *check.C) { s.d.StartWithBusybox(c) out, err := s.d.Cmd("run", "--rm", "--name", "test-data", "-v", "external-volume-test:/tmp/external-volume-test", "--volume-driver", volumePluginName, "busybox:latest", "cat", "/tmp/external-volume-test/test") - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) c.Assert(out, checker.Contains, s.Server.URL) _, err = s.d.Cmd("volume", "rm", "external-volume-test") - c.Assert(err, checker.IsNil) + assert.NilError(c, err) p := hostVolumePath("external-volume-test") _, err = os.Lstat(p) - c.Assert(err, checker.NotNil) + assert.ErrorContains(c, err, "") c.Assert(os.IsNotExist(err), checker.True, check.Commentf("Expected volume path in host to not exist: %s, %v\n", p, err)) c.Assert(s.ec.activations, checker.Equals, 1) @@ -320,7 +321,7 @@ func (s *DockerExternalVolumeSuite) TestExternalVolumeDriverUnnamed(c *check.C) s.d.StartWithBusybox(c) out, err := s.d.Cmd("run", "--rm", "--name", "test-data", "-v", "/tmp/external-volume-test", "--volume-driver", volumePluginName, "busybox:latest", "cat", "/tmp/external-volume-test/test") - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) c.Assert(out, checker.Contains, s.Server.URL) c.Assert(s.ec.activations, checker.Equals, 1) @@ -334,13 +335,13 @@ func (s *DockerExternalVolumeSuite) TestExternalVolumeDriverVolumesFrom(c *check s.d.StartWithBusybox(c) out, err := s.d.Cmd("run", "--name", "vol-test1", "-v", "/foo", "--volume-driver", volumePluginName, "busybox:latest") - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) out, err = s.d.Cmd("run", "--rm", "--volumes-from", "vol-test1", "--name", "vol-test2", "busybox", "ls", "/tmp") - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) out, err = s.d.Cmd("rm", "-fv", "vol-test1") - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) c.Assert(s.ec.activations, checker.Equals, 1) c.Assert(s.ec.creations, checker.Equals, 1) @@ -353,10 +354,10 @@ func (s *DockerExternalVolumeSuite) TestExternalVolumeDriverDeleteContainer(c *c s.d.StartWithBusybox(c) out, err := s.d.Cmd("run", "--name", "vol-test1", "-v", "/foo", "--volume-driver", volumePluginName, "busybox:latest") - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) out, err = s.d.Cmd("rm", "-fv", "vol-test1") - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) c.Assert(s.ec.activations, checker.Equals, 1) c.Assert(s.ec.creations, checker.Equals, 1) @@ -373,7 +374,7 @@ func hostVolumePath(name string) string { func (s *DockerExternalVolumeSuite) TestExternalVolumeDriverLookupNotBlocked(c *check.C) { specPath := "/etc/docker/plugins/down-driver.spec" err := ioutil.WriteFile(specPath, []byte("tcp://127.0.0.7:9999"), 0644) - c.Assert(err, check.IsNil) + assert.NilError(c, err) defer os.RemoveAll(specPath) chCmd1 := make(chan struct{}) @@ -399,7 +400,7 @@ func (s *DockerExternalVolumeSuite) TestExternalVolumeDriverLookupNotBlocked(c * cmd2.Process.Kill() c.Fatalf("volume create with down driver finished unexpectedly") case err := <-chCmd2: - c.Assert(err, checker.IsNil) + assert.NilError(c, err) case <-time.After(5 * time.Second): cmd2.Process.Kill() c.Fatal("volume creates are blocked by previous create requests when previous driver is down") @@ -428,13 +429,13 @@ func (s *DockerExternalVolumeSuite) TestExternalVolumeDriverRetryNotImmediatelyE select { case err := <-errchan: - c.Assert(err, checker.IsNil) + assert.NilError(c, err) case <-time.After(8 * time.Second): c.Fatal("volume creates fail when plugin not immediately available") } _, err := s.d.Cmd("volume", "rm", "external-volume-test") - c.Assert(err, checker.IsNil) + assert.NilError(c, err) c.Assert(p.ec.activations, checker.Equals, 1) c.Assert(p.ec.creations, checker.Equals, 1) @@ -474,7 +475,7 @@ func (s *DockerExternalVolumeSuite) TestExternalVolumeDriverList(c *check.C) { func (s *DockerExternalVolumeSuite) TestExternalVolumeDriverGet(c *check.C) { out, _, err := dockerCmdWithError("volume", "inspect", "dummy") - c.Assert(err, check.NotNil, check.Commentf("%s", out)) + assert.ErrorContains(c, err, "", out) c.Assert(out, checker.Contains, "No such volume") c.Assert(s.ec.gets, check.Equals, 1) @@ -509,10 +510,10 @@ func (s *DockerExternalVolumeSuite) TestExternalVolumeDriverGetEmptyResponse(c * s.d.Start(c) out, err := s.d.Cmd("volume", "create", "-d", volumePluginName, "abc2", "--opt", "ninja=1") - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) out, err = s.d.Cmd("volume", "inspect", "abc2") - c.Assert(err, checker.NotNil, check.Commentf("%s", out)) + assert.ErrorContains(c, err, "", out) c.Assert(out, checker.Contains, "No such volume") } @@ -525,11 +526,11 @@ func (s *DockerExternalVolumeSuite) TestExternalVolumeDriverPathCalls(c *check.C c.Assert(s.ec.paths, checker.Equals, 0) out, err := s.d.Cmd("volume", "create", "test", "--driver=test-external-volume-driver") - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) c.Assert(s.ec.paths, checker.Equals, 0) out, err = s.d.Cmd("volume", "ls") - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) c.Assert(s.ec.paths, checker.Equals, 0) } @@ -537,8 +538,8 @@ func (s *DockerExternalVolumeSuite) TestExternalVolumeDriverMountID(c *check.C) s.d.StartWithBusybox(c) out, err := s.d.Cmd("run", "--rm", "-v", "external-volume-test:/tmp/external-volume-test", "--volume-driver", volumePluginName, "busybox:latest", "cat", "/tmp/external-volume-test/test") - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) - c.Assert(strings.TrimSpace(out), checker.Not(checker.Equals), "") + assert.NilError(c, err, out) + assert.Assert(c, strings.TrimSpace(out) != "") } // Check that VolumeDriver.Capabilities gets called, and only called once @@ -548,11 +549,11 @@ func (s *DockerExternalVolumeSuite) TestExternalVolumeDriverCapabilities(c *chec for i := 0; i < 3; i++ { out, err := s.d.Cmd("volume", "create", "-d", volumePluginName, fmt.Sprintf("test%d", i)) - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) c.Assert(s.ec.caps, checker.Equals, 1) out, err = s.d.Cmd("volume", "inspect", "--format={{.Scope}}", fmt.Sprintf("test%d", i)) - c.Assert(err, checker.IsNil) - c.Assert(strings.TrimSpace(out), checker.Equals, volume.GlobalScope) + assert.NilError(c, err) + assert.Equal(c, strings.TrimSpace(out), volume.GlobalScope) } } @@ -564,10 +565,10 @@ func (s *DockerExternalVolumeSuite) TestExternalVolumeDriverOutOfBandDelete(c *c s.d.StartWithBusybox(c) out, err := s.d.Cmd("volume", "create", "-d", driverName, "--name", "test") - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) out, err = s.d.Cmd("volume", "create", "-d", "local", "--name", "test") - c.Assert(err, checker.NotNil, check.Commentf("%s", out)) + assert.ErrorContains(c, err, "", out) c.Assert(out, checker.Contains, "must be unique") // simulate out of band volume deletion on plugin level @@ -575,13 +576,13 @@ func (s *DockerExternalVolumeSuite) TestExternalVolumeDriverOutOfBandDelete(c *c // test re-create with same driver out, err = s.d.Cmd("volume", "create", "-d", driverName, "--opt", "foo=bar", "--name", "test") - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) out, err = s.d.Cmd("volume", "inspect", "test") - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) var vs []types.Volume err = json.Unmarshal([]byte(out), &vs) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) c.Assert(vs, checker.HasLen, 1) c.Assert(vs[0].Driver, checker.Equals, driverName) c.Assert(vs[0].Options, checker.NotNil) @@ -593,13 +594,13 @@ func (s *DockerExternalVolumeSuite) TestExternalVolumeDriverOutOfBandDelete(c *c // test create with different driver out, err = s.d.Cmd("volume", "create", "-d", "local", "--name", "test") - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) out, err = s.d.Cmd("volume", "inspect", "test") - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) vs = nil err = json.Unmarshal([]byte(out), &vs) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) c.Assert(vs, checker.HasLen, 1) c.Assert(vs[0].Options, checker.HasLen, 0) c.Assert(vs[0].Driver, checker.Equals, "local") diff --git a/components/engine/integration-cli/docker_cli_images_test.go b/components/engine/integration-cli/docker_cli_images_test.go index 0dd319fbc9..652acc5299 100644 --- a/components/engine/integration-cli/docker_cli_images_test.go +++ b/components/engine/integration-cli/docker_cli_images_test.go @@ -14,6 +14,8 @@ import ( "github.com/docker/docker/integration-cli/cli/build" "github.com/docker/docker/pkg/stringid" "github.com/go-check/check" + "gotest.tools/assert" + is "gotest.tools/assert/cmp" "gotest.tools/icmd" ) @@ -68,7 +70,7 @@ func (s *DockerSuite) TestImagesOrderedByCreationDate(c *check.C) { func (s *DockerSuite) TestImagesErrorWithInvalidFilterNameTest(c *check.C) { out, _, err := dockerCmdWithError("images", "-f", "FOO=123") - c.Assert(err, checker.NotNil) + assert.ErrorContains(c, err, "") c.Assert(out, checker.Contains, "Invalid filter") } @@ -96,7 +98,7 @@ func (s *DockerSuite) TestImagesFilterLabelMatch(c *check.C) { out, _ = dockerCmd(c, "images", "--no-trunc", "-q", "-f", "label=match=me too") out = strings.TrimSpace(out) - c.Assert(out, check.Equals, image2ID) + assert.Equal(c, out, image2ID) } // Regression : #15659 @@ -109,7 +111,7 @@ func (s *DockerSuite) TestCommitWithFilterLabel(c *check.C) { out, _ = dockerCmd(c, "images", "--no-trunc", "-q", "-f", "label=foo.version=1.0.0-1") out = strings.TrimSpace(out) - c.Assert(out, check.Equals, imageID) + assert.Equal(c, out, imageID) } func (s *DockerSuite) TestImagesFilterSinceAndBefore(c *check.C) { @@ -252,7 +254,7 @@ func (s *DockerSuite) TestImagesEnsureDanglingImageOnlyListedOnce(c *check.C) { // FIXME(vdemeester) should be a unit test for `docker image ls` func (s *DockerSuite) TestImagesWithIncorrectFilter(c *check.C) { out, _, err := dockerCmdWithError("images", "-f", "dangling=invalid") - c.Assert(err, check.NotNil) + assert.ErrorContains(c, err, "") c.Assert(out, checker.Contains, "Invalid filter") } @@ -336,7 +338,7 @@ func (s *DockerSuite) TestImagesFormat(c *check.C) { expected := []string{"myimage", "myimage"} var names []string names = append(names, lines...) - c.Assert(names, checker.DeepEquals, expected, check.Commentf("Expected array with truncated names: %v, got: %v", expected, names)) + assert.Assert(c, is.DeepEqual(names, expected), "Expected array with truncated names: %v, got: %v", expected, names) } // ImagesDefaultFormatAndQuiet @@ -355,12 +357,12 @@ func (s *DockerSuite) TestImagesFormatDefaultFormat(c *check.C) { "imagesFormat": "{{ .ID }} default" }` d, err := ioutil.TempDir("", "integration-cli-") - c.Assert(err, checker.IsNil) + assert.NilError(c, err) defer os.RemoveAll(d) err = ioutil.WriteFile(filepath.Join(d, "config.json"), []byte(config), 0644) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) out, _ = dockerCmd(c, "--config", d, "images", "-q", "myimage") - c.Assert(out, checker.Equals, imageID+"\n", check.Commentf("Expected to print only the image id, got %v\n", out)) + assert.Equal(c, out, imageID+"\n", "Expected to print only the image id, got %v\n", out) } diff --git a/components/engine/integration-cli/docker_cli_import_test.go b/components/engine/integration-cli/docker_cli_import_test.go index 9f8e915803..11cebf1bba 100644 --- a/components/engine/integration-cli/docker_cli_import_test.go +++ b/components/engine/integration-cli/docker_cli_import_test.go @@ -12,6 +12,7 @@ import ( "github.com/docker/docker/integration-cli/checker" "github.com/docker/docker/integration-cli/cli" "github.com/go-check/check" + "gotest.tools/assert" "gotest.tools/icmd" ) @@ -24,13 +25,13 @@ func (s *DockerSuite) TestImportDisplay(c *check.C) { exec.Command(dockerBinary, "export", cleanedContainerID), exec.Command(dockerBinary, "import", "-"), ) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) - c.Assert(out, checker.Count, "\n", 1, check.Commentf("display is expected 1 '\\n' but didn'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") - c.Assert(out, checker.Equals, "", check.Commentf("command output should've been nothing.")) + assert.Equal(c, out, "", "command output should've been nothing.") } func (s *DockerSuite) TestImportBadURL(c *check.C) { @@ -58,11 +59,11 @@ func (s *DockerSuite) TestImportFile(c *check.C) { }).Assert(c, icmd.Success) out, _ := dockerCmd(c, "import", temporaryFile.Name()) - c.Assert(out, checker.Count, "\n", 1, check.Commentf("display is expected 1 '\\n' but didn'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") - c.Assert(out, checker.Equals, "", check.Commentf("command output should've been nothing.")) + assert.Equal(c, out, "", "command output should've been nothing.") } func (s *DockerSuite) TestImportGzipped(c *check.C) { @@ -81,11 +82,11 @@ func (s *DockerSuite) TestImportGzipped(c *check.C) { c.Assert(w.Close(), checker.IsNil, check.Commentf("failed to close gzip writer")) temporaryFile.Close() out, _ := dockerCmd(c, "import", temporaryFile.Name()) - c.Assert(out, checker.Count, "\n", 1, check.Commentf("display is expected 1 '\\n' but didn'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") - c.Assert(out, checker.Equals, "", check.Commentf("command output should've been nothing.")) + assert.Equal(c, out, "", "command output should've been nothing.") } func (s *DockerSuite) TestImportFileWithMessage(c *check.C) { @@ -103,7 +104,7 @@ func (s *DockerSuite) TestImportFileWithMessage(c *check.C) { message := "Testing commit message" out, _ := dockerCmd(c, "import", "-m", message, temporaryFile.Name()) - c.Assert(out, checker.Count, "\n", 1, check.Commentf("display is expected 1 '\\n' but didn't")) + 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) @@ -116,7 +117,7 @@ func (s *DockerSuite) TestImportFileWithMessage(c *check.C) { c.Assert(message, checker.Equals, split[3], check.Commentf("didn't get expected value in commit message")) out, _ = dockerCmd(c, "run", "--rm", image, "true") - c.Assert(out, checker.Equals, "", check.Commentf("command output should've been nothing")) + assert.Equal(c, out, "", "command output should've been nothing") } func (s *DockerSuite) TestImportFileNonExistentFile(c *check.C) { diff --git a/components/engine/integration-cli/docker_cli_info_test.go b/components/engine/integration-cli/docker_cli_info_test.go index e399d1477a..24d9c61a3c 100644 --- a/components/engine/integration-cli/docker_cli_info_test.go +++ b/components/engine/integration-cli/docker_cli_info_test.go @@ -10,6 +10,7 @@ import ( "github.com/docker/docker/integration-cli/daemon" testdaemon "github.com/docker/docker/internal/test/daemon" "github.com/go-check/check" + "gotest.tools/assert" ) // ensure docker info succeeds @@ -62,9 +63,9 @@ func (s *DockerSuite) TestInfoFormat(c *check.C) { c.Assert(status, checker.Equals, 0) var m map[string]interface{} err := json.Unmarshal([]byte(out), &m) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) _, _, err = dockerCmdWithError("info", "--format", "{{.badString}}") - c.Assert(err, checker.NotNil) + assert.ErrorContains(c, err, "") } // TestInfoDiscoveryBackend verifies that a daemon run with `--cluster-advertise` and @@ -79,7 +80,7 @@ func (s *DockerSuite) TestInfoDiscoveryBackend(c *check.C) { defer d.Stop(c) out, err := d.Cmd("info") - c.Assert(err, checker.IsNil) + assert.NilError(c, err) c.Assert(out, checker.Contains, fmt.Sprintf("Cluster Store: %s\n", discoveryBackend)) c.Assert(out, checker.Contains, fmt.Sprintf("Cluster Advertise: %s\n", discoveryAdvertise)) } @@ -94,11 +95,11 @@ func (s *DockerSuite) TestInfoDiscoveryInvalidAdvertise(c *check.C) { // --cluster-advertise with an invalid string is an error err := d.StartWithError(fmt.Sprintf("--cluster-store=%s", discoveryBackend), "--cluster-advertise=invalid") - c.Assert(err, checker.NotNil) + assert.ErrorContains(c, err, "") // --cluster-advertise without --cluster-store is also an error err = d.StartWithError("--cluster-advertise=1.1.1.1:2375") - c.Assert(err, checker.NotNil) + assert.ErrorContains(c, err, "") } // TestInfoDiscoveryAdvertiseInterfaceName verifies that a daemon run with `--cluster-advertise` @@ -114,15 +115,15 @@ func (s *DockerSuite) TestInfoDiscoveryAdvertiseInterfaceName(c *check.C) { defer d.Stop(c) iface, err := net.InterfaceByName(discoveryAdvertise) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) addrs, err := iface.Addrs() - c.Assert(err, checker.IsNil) - c.Assert(len(addrs), checker.GreaterThan, 0) + assert.NilError(c, err) + assert.Assert(c, len(addrs) > 0) ip, _, err := net.ParseCIDR(addrs[0].String()) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) out, err := d.Cmd("info") - c.Assert(err, checker.IsNil) + assert.NilError(c, err) c.Assert(out, checker.Contains, fmt.Sprintf("Cluster Store: %s\n", discoveryBackend)) c.Assert(out, checker.Contains, fmt.Sprintf("Cluster Advertise: %s:2375\n", ip.String())) } @@ -182,7 +183,7 @@ func (s *DockerSuite) TestInfoDebug(c *check.C) { defer d.Stop(c) out, err := d.Cmd("--debug", "info") - c.Assert(err, checker.IsNil) + assert.NilError(c, err) c.Assert(out, checker.Contains, "Debug Mode (client): true\n") c.Assert(out, checker.Contains, "Debug Mode (server): true\n") c.Assert(out, checker.Contains, "File Descriptors") @@ -203,7 +204,7 @@ func (s *DockerSuite) TestInsecureRegistries(c *check.C) { defer d.Stop(c) out, err := d.Cmd("info") - c.Assert(err, checker.IsNil) + assert.NilError(c, err) c.Assert(out, checker.Contains, "Insecure Registries:\n") c.Assert(out, checker.Contains, fmt.Sprintf(" %s\n", registryHost)) c.Assert(out, checker.Contains, fmt.Sprintf(" %s\n", registryCIDR)) @@ -218,7 +219,7 @@ func (s *DockerDaemonSuite) TestRegistryMirrors(c *check.C) { s.d.Start(c, "--registry-mirror="+registryMirror1, "--registry-mirror="+registryMirror2) out, err := s.d.Cmd("info") - c.Assert(err, checker.IsNil) + assert.NilError(c, err) c.Assert(out, checker.Contains, "Registry Mirrors:\n") c.Assert(out, checker.Contains, fmt.Sprintf(" %s", registryMirror1)) c.Assert(out, checker.Contains, fmt.Sprintf(" %s", registryMirror2)) @@ -228,7 +229,7 @@ func existingContainerStates(c *check.C) map[string]int { out, _ := dockerCmd(c, "info", "--format", "{{json .}}") var m map[string]interface{} err := json.Unmarshal([]byte(out), &m) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) res := map[string]int{} res["Containers"] = int(m["Containers"].(float64)) res["ContainersRunning"] = int(m["ContainersRunning"].(float64)) diff --git a/components/engine/integration-cli/docker_cli_inspect_test.go b/components/engine/integration-cli/docker_cli_inspect_test.go index d027c44775..620272f65f 100644 --- a/components/engine/integration-cli/docker_cli_inspect_test.go +++ b/components/engine/integration-cli/docker_cli_inspect_test.go @@ -12,6 +12,7 @@ import ( "github.com/docker/docker/api/types/container" "github.com/docker/docker/integration-cli/checker" "github.com/go-check/check" + "gotest.tools/assert" "gotest.tools/icmd" ) @@ -84,7 +85,7 @@ func (s *DockerSuite) TestInspectTypeFlagContainer(c *check.C) { formatStr := "--format={{.State.Running}}" out, _ := dockerCmd(c, "inspect", "--type=container", formatStr, "busybox") - c.Assert(out, checker.Equals, "true\n") // not a container JSON + assert.Equal(c, out, "true\n") // not a container JSON } func (s *DockerSuite) TestInspectTypeFlagWithNoContainer(c *check.C) { @@ -96,7 +97,7 @@ func (s *DockerSuite) TestInspectTypeFlagWithNoContainer(c *check.C) { _, _, err := dockerCmdWithError("inspect", "--type=container", "busybox") // docker inspect should fail, as there is no container named busybox - c.Assert(err, checker.NotNil) + assert.ErrorContains(c, err, "") } func (s *DockerSuite) TestInspectTypeFlagWithImage(c *check.C) { @@ -134,7 +135,7 @@ func (s *DockerSuite) TestInspectImageFilterInt(c *check.C) { formatStr := fmt.Sprintf("--format={{eq .Size %d}}", size) out, _ = dockerCmd(c, "inspect", formatStr, imageTest) result, err := strconv.ParseBool(strings.TrimSuffix(out, "\n")) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) c.Assert(result, checker.Equals, true) } @@ -156,7 +157,7 @@ func (s *DockerSuite) TestInspectContainerFilterInt(c *check.C) { formatStr := fmt.Sprintf("--format={{eq .State.ExitCode %d}}", exitCode) out, _ = dockerCmd(c, "inspect", formatStr, id) inspectResult, err := strconv.ParseBool(strings.TrimSuffix(out, "\n")) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) c.Assert(inspectResult, checker.Equals, true) } @@ -218,7 +219,7 @@ func (s *DockerSuite) TestInspectBindMountPoint(c *check.C) { var mp []types.MountPoint err := json.Unmarshal([]byte(vol), &mp) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) // check that there is only one mountpoint c.Assert(mp, check.HasLen, 1) @@ -244,7 +245,7 @@ func (s *DockerSuite) TestInspectNamedMountPoint(c *check.C) { var mp []types.MountPoint err := json.Unmarshal([]byte(vol), &mp) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) // check that there is only one mountpoint c.Assert(mp, checker.HasLen, 1) @@ -267,16 +268,16 @@ func (s *DockerSuite) TestInspectTimesAsRFC3339Nano(c *check.C) { created := inspectField(c, id, "Created") _, err := time.Parse(time.RFC3339Nano, startedAt) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) _, err = time.Parse(time.RFC3339Nano, finishedAt) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) _, err = time.Parse(time.RFC3339Nano, created) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) created = inspectField(c, "busybox", "Created") _, err = time.Parse(time.RFC3339Nano, created) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) } // #15633 @@ -334,13 +335,13 @@ func (s *DockerSuite) TestInspectJSONFields(c *check.C) { runSleepingContainer(c, "--name=busybox", "-d") out, _, err := dockerCmdWithError("inspect", "--type=container", "--format={{.HostConfig.Dns}}", "busybox") - c.Assert(err, check.IsNil) - c.Assert(out, checker.Equals, "[]\n") + assert.NilError(c, err) + assert.Equal(c, out, "[]\n") } func (s *DockerSuite) TestInspectByPrefix(c *check.C) { id := inspectField(c, "busybox", "Id") - c.Assert(id, checker.HasPrefix, "sha256:") + assert.Assert(c, strings.HasPrefix(id, "sha256:")) id2 := inspectField(c, id[:12], "Id") c.Assert(id, checker.Equals, id2) @@ -372,7 +373,7 @@ func (s *DockerSuite) TestInspectHistory(c *check.C) { dockerCmd(c, "run", "--name=testcont", "busybox", "echo", "hello") dockerCmd(c, "commit", "-m", "test comment", "testcont", "testimg") out, _, err := dockerCmdWithError("inspect", "--format='{{.Comment}}'", "testimg") - c.Assert(err, check.IsNil) + assert.NilError(c, err) c.Assert(out, checker.Contains, "test comment") } @@ -385,7 +386,7 @@ func (s *DockerSuite) TestInspectContainerNetworkDefault(c *check.C) { out := inspectField(c, contName, "NetworkSettings.Networks") c.Assert(out, checker.Contains, "bridge") out = inspectField(c, contName, "NetworkSettings.Networks.bridge.NetworkID") - c.Assert(strings.TrimSpace(out), checker.Equals, strings.TrimSpace(netOut)) + assert.Equal(c, strings.TrimSpace(out), strings.TrimSpace(netOut)) } func (s *DockerSuite) TestInspectContainerNetworkCustom(c *check.C) { @@ -396,18 +397,17 @@ func (s *DockerSuite) TestInspectContainerNetworkCustom(c *check.C) { out := inspectField(c, "container1", "NetworkSettings.Networks") c.Assert(out, checker.Contains, "net1") out = inspectField(c, "container1", "NetworkSettings.Networks.net1.NetworkID") - c.Assert(strings.TrimSpace(out), checker.Equals, strings.TrimSpace(netOut)) + assert.Equal(c, strings.TrimSpace(out), strings.TrimSpace(netOut)) } func (s *DockerSuite) TestInspectRootFS(c *check.C) { out, _, err := dockerCmdWithError("inspect", "busybox") - c.Assert(err, check.IsNil) + assert.NilError(c, err) var imageJSON []types.ImageInspect err = json.Unmarshal([]byte(out), &imageJSON) - c.Assert(err, checker.IsNil) - - c.Assert(len(imageJSON[0].RootFS.Layers), checker.GreaterOrEqualThan, 1) + assert.NilError(c, err) + assert.Assert(c, len(imageJSON[0].RootFS.Layers) >= 1) } func (s *DockerSuite) TestInspectAmpersand(c *check.C) { @@ -423,30 +423,30 @@ func (s *DockerSuite) TestInspectAmpersand(c *check.C) { func (s *DockerSuite) TestInspectPlugin(c *check.C) { testRequires(c, DaemonIsLinux, IsAmd64, Network) _, _, err := dockerCmdWithError("plugin", "install", "--grant-all-permissions", pNameWithTag) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) out, _, err := dockerCmdWithError("inspect", "--type", "plugin", "--format", "{{.Name}}", pNameWithTag) - c.Assert(err, checker.IsNil) - c.Assert(strings.TrimSpace(out), checker.Equals, pNameWithTag) + assert.NilError(c, err) + assert.Equal(c, strings.TrimSpace(out), pNameWithTag) out, _, err = dockerCmdWithError("inspect", "--format", "{{.Name}}", pNameWithTag) - c.Assert(err, checker.IsNil) - c.Assert(strings.TrimSpace(out), checker.Equals, pNameWithTag) + assert.NilError(c, err) + assert.Equal(c, strings.TrimSpace(out), pNameWithTag) // Even without tag the inspect still work out, _, err = dockerCmdWithError("inspect", "--type", "plugin", "--format", "{{.Name}}", pNameWithTag) - c.Assert(err, checker.IsNil) - c.Assert(strings.TrimSpace(out), checker.Equals, pNameWithTag) + assert.NilError(c, err) + assert.Equal(c, strings.TrimSpace(out), pNameWithTag) out, _, err = dockerCmdWithError("inspect", "--format", "{{.Name}}", pNameWithTag) - c.Assert(err, checker.IsNil) - c.Assert(strings.TrimSpace(out), checker.Equals, pNameWithTag) + assert.NilError(c, err) + assert.Equal(c, strings.TrimSpace(out), pNameWithTag) _, _, err = dockerCmdWithError("plugin", "disable", pNameWithTag) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) out, _, err = dockerCmdWithError("plugin", "remove", pNameWithTag) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) c.Assert(out, checker.Contains, pNameWithTag) } @@ -454,7 +454,7 @@ func (s *DockerSuite) TestInspectPlugin(c *check.C) { func (s *DockerSuite) TestInspectUnknownObject(c *check.C) { // This test should work on both Windows and Linux out, _, err := dockerCmdWithError("inspect", "foobar") - c.Assert(err, checker.NotNil) + assert.ErrorContains(c, err, "") c.Assert(out, checker.Contains, "Error: No such object: foobar") - c.Assert(err.Error(), checker.Contains, "Error: No such object: foobar") + assert.ErrorContains(c, err, "Error: No such object: foobar") } diff --git a/components/engine/integration-cli/docker_cli_links_test.go b/components/engine/integration-cli/docker_cli_links_test.go index 3ddeb38b23..9be3ea117a 100644 --- a/components/engine/integration-cli/docker_cli_links_test.go +++ b/components/engine/integration-cli/docker_cli_links_test.go @@ -10,6 +10,7 @@ import ( "github.com/docker/docker/integration-cli/checker" "github.com/docker/docker/runconfig" "github.com/go-check/check" + "gotest.tools/assert" ) func (s *DockerSuite) TestLinksPingUnlinkedContainers(c *check.C) { @@ -99,14 +100,14 @@ func (s *DockerSuite) TestLinksInspectLinksStarted(c *check.C) { var result []string err := json.Unmarshal([]byte(links), &result) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) var expected = []string{ "/container1:/testinspectlink/alias1", "/container2:/testinspectlink/alias2", } sort.Strings(result) - c.Assert(result, checker.DeepEquals, expected) + assert.DeepEqual(c, result, expected) } func (s *DockerSuite) TestLinksInspectLinksStopped(c *check.C) { @@ -119,14 +120,14 @@ func (s *DockerSuite) TestLinksInspectLinksStopped(c *check.C) { var result []string err := json.Unmarshal([]byte(links), &result) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) var expected = []string{ "/container1:/testinspectlink/alias1", "/container2:/testinspectlink/alias2", } sort.Strings(result) - c.Assert(result, checker.DeepEquals, expected) + assert.DeepEqual(c, result, expected) } func (s *DockerSuite) TestLinksNotStartedParentNotFail(c *check.C) { diff --git a/components/engine/integration-cli/docker_cli_login_test.go b/components/engine/integration-cli/docker_cli_login_test.go index 546f55c0b9..b147f4887c 100644 --- a/components/engine/integration-cli/docker_cli_login_test.go +++ b/components/engine/integration-cli/docker_cli_login_test.go @@ -3,9 +3,10 @@ package main import ( "bytes" "os/exec" + "strings" - "github.com/docker/docker/integration-cli/checker" "github.com/go-check/check" + "gotest.tools/assert" ) func (s *DockerSuite) TestLoginWithoutTTY(c *check.C) { @@ -16,14 +17,14 @@ func (s *DockerSuite) TestLoginWithoutTTY(c *check.C) { // run the command and block until it's done err := cmd.Run() - c.Assert(err, checker.NotNil) //"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 *check.C) { // wrong credentials out, _, err := dockerCmdWithError("login", "-u", s.reg.Username(), "-p", "WRONGPASSWORD", privateRegistryURL) - c.Assert(err, checker.NotNil, check.Commentf("%s", out)) - c.Assert(out, checker.Contains, "401 Unauthorized") + assert.ErrorContains(c, err, "", out) + assert.Assert(c, strings.Contains(out, "401 Unauthorized")) // now it's fine dockerCmd(c, "login", "-u", s.reg.Username(), "-p", s.reg.Password(), privateRegistryURL) diff --git a/components/engine/integration-cli/docker_cli_logout_test.go b/components/engine/integration-cli/docker_cli_logout_test.go index ee4b032b76..5fce1cb74e 100644 --- a/components/engine/integration-cli/docker_cli_logout_test.go +++ b/components/engine/integration-cli/docker_cli_logout_test.go @@ -7,9 +7,10 @@ import ( "os" "os/exec" "path/filepath" + "strings" - "github.com/docker/docker/integration-cli/checker" "github.com/go-check/check" + "gotest.tools/assert" ) func (s *DockerRegistryAuthHtpasswdSuite) TestLogoutWithExternalAuth(c *check.C) { @@ -19,9 +20,9 @@ func (s *DockerRegistryAuthHtpasswdSuite) TestLogoutWithExternalAuth(c *check.C) defer os.Setenv("PATH", osPath) workingDir, err := os.Getwd() - c.Assert(err, checker.IsNil) + assert.NilError(c, err) absolute, err := filepath.Abs(filepath.Join(workingDir, "fixtures", "auth")) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) testPath := fmt.Sprintf("%s%c%s", osPath, filepath.ListSeparator, absolute) os.Setenv("PATH", testPath) @@ -29,38 +30,38 @@ func (s *DockerRegistryAuthHtpasswdSuite) TestLogoutWithExternalAuth(c *check.C) repoName := fmt.Sprintf("%v/dockercli/busybox:authtest", privateRegistryURL) tmp, err := ioutil.TempDir("", "integration-cli-") - c.Assert(err, checker.IsNil) + assert.NilError(c, err) defer os.RemoveAll(tmp) externalAuthConfig := `{ "credsStore": "shell-test" }` configPath := filepath.Join(tmp, "config.json") err = ioutil.WriteFile(configPath, []byte(externalAuthConfig), 0644) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) _, err = s.d.Cmd("--config", tmp, "login", "-u", s.reg.Username(), "-p", s.reg.Password(), privateRegistryURL) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) b, err := ioutil.ReadFile(configPath) - c.Assert(err, checker.IsNil) - c.Assert(string(b), checker.Not(checker.Contains), "\"auth\":") - c.Assert(string(b), checker.Contains, privateRegistryURL) + assert.NilError(c, err) + 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) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) _, err = s.d.Cmd("--config", tmp, "push", repoName) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) _, err = s.d.Cmd("--config", tmp, "logout", privateRegistryURL) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) b, err = ioutil.ReadFile(configPath) - c.Assert(err, checker.IsNil) - c.Assert(string(b), checker.Not(checker.Contains), privateRegistryURL) + assert.NilError(c, err) + assert.Assert(c, !strings.Contains(string(b), privateRegistryURL)) // check I cannot pull anymore out, err := s.d.Cmd("--config", tmp, "pull", repoName) - c.Assert(err, check.NotNil, check.Commentf("%s", out)) - c.Assert(out, checker.Contains, "no basic auth credentials") + assert.ErrorContains(c, err, "", out) + assert.Assert(c, strings.Contains(out, "no basic auth credentials")) } // #23100 @@ -69,9 +70,9 @@ func (s *DockerRegistryAuthHtpasswdSuite) TestLogoutWithWrongHostnamesStored(c * defer os.Setenv("PATH", osPath) workingDir, err := os.Getwd() - c.Assert(err, checker.IsNil) + assert.NilError(c, err) absolute, err := filepath.Abs(filepath.Join(workingDir, "fixtures", "auth")) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) testPath := fmt.Sprintf("%s%c%s", osPath, filepath.ListSeparator, absolute) os.Setenv("PATH", testPath) @@ -79,28 +80,28 @@ func (s *DockerRegistryAuthHtpasswdSuite) TestLogoutWithWrongHostnamesStored(c * cmd := exec.Command("docker-credential-shell-test", "store") stdin := bytes.NewReader([]byte(fmt.Sprintf(`{"ServerURL": "https://%s", "Username": "%s", "Secret": "%s"}`, privateRegistryURL, s.reg.Username(), s.reg.Password()))) cmd.Stdin = stdin - c.Assert(cmd.Run(), checker.IsNil) + assert.NilError(c, cmd.Run()) tmp, err := ioutil.TempDir("", "integration-cli-") - c.Assert(err, checker.IsNil) + assert.NilError(c, err) externalAuthConfig := fmt.Sprintf(`{ "auths": {"https://%s": {}}, "credsStore": "shell-test" }`, privateRegistryURL) configPath := filepath.Join(tmp, "config.json") err = ioutil.WriteFile(configPath, []byte(externalAuthConfig), 0644) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) dockerCmd(c, "--config", tmp, "login", "-u", s.reg.Username(), "-p", s.reg.Password(), privateRegistryURL) b, err := ioutil.ReadFile(configPath) - c.Assert(err, checker.IsNil) - c.Assert(string(b), checker.Contains, fmt.Sprintf("\"https://%s\": {}", privateRegistryURL)) - c.Assert(string(b), checker.Contains, fmt.Sprintf("\"%s\": {}", privateRegistryURL)) + 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) b, err = ioutil.ReadFile(configPath) - c.Assert(err, checker.IsNil) - c.Assert(string(b), checker.Not(checker.Contains), fmt.Sprintf("\"https://%s\": {}", privateRegistryURL)) - c.Assert(string(b), checker.Not(checker.Contains), fmt.Sprintf("\"%s\": {}", privateRegistryURL)) + 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))) } diff --git a/components/engine/integration-cli/docker_cli_logs_test.go b/components/engine/integration-cli/docker_cli_logs_test.go index 2740de6f06..dadb827a60 100644 --- a/components/engine/integration-cli/docker_cli_logs_test.go +++ b/components/engine/integration-cli/docker_cli_logs_test.go @@ -8,10 +8,10 @@ import ( "strings" "time" - "github.com/docker/docker/integration-cli/checker" "github.com/docker/docker/integration-cli/cli" "github.com/docker/docker/pkg/jsonmessage" "github.com/go-check/check" + "gotest.tools/assert" "gotest.tools/icmd" ) @@ -35,7 +35,7 @@ func testLogsContainerPagination(c *check.C, testLen int) { id := strings.TrimSpace(out) dockerCmd(c, "wait", id) out, _ = dockerCmd(c, "logs", id) - c.Assert(out, checker.HasLen, testLen+1) + assert.Equal(c, len(out), testLen+1) } func (s *DockerSuite) TestLogsTimestamps(c *check.C) { @@ -49,16 +49,16 @@ func (s *DockerSuite) TestLogsTimestamps(c *check.C) { lines := strings.Split(out, "\n") - c.Assert(lines, checker.HasLen, testLen+1) + assert.Equal(c, len(lines), testLen+1) ts := regexp.MustCompile(`^.* `) for _, l := range lines { if l != "" { _, err := time.Parse(jsonmessage.RFC3339NanoFixed+" ", ts.FindString(l)) - c.Assert(err, checker.IsNil, check.Commentf("Failed to parse timestamp from %v", l)) + assert.NilError(c, err, "Failed to parse timestamp from %v", l) // ensure we have padded 0's - c.Assert(l[29], checker.Equals, uint8('Z')) + assert.Equal(c, l[29], uint8('Z')) } } } @@ -98,27 +98,27 @@ func (s *DockerSuite) TestLogsTail(c *check.C) { out = cli.DockerCmd(c, "logs", "--tail", "0", id).Combined() lines := strings.Split(out, "\n") - c.Assert(lines, checker.HasLen, 1) + assert.Equal(c, len(lines), 1) out = cli.DockerCmd(c, "logs", "--tail", "5", id).Combined() lines = strings.Split(out, "\n") - c.Assert(lines, checker.HasLen, 6) + assert.Equal(c, len(lines), 6) out = cli.DockerCmd(c, "logs", "--tail", "99", id).Combined() lines = strings.Split(out, "\n") - c.Assert(lines, checker.HasLen, 100) + assert.Equal(c, len(lines), 100) out = cli.DockerCmd(c, "logs", "--tail", "all", id).Combined() lines = strings.Split(out, "\n") - c.Assert(lines, checker.HasLen, testLen+1) + assert.Equal(c, len(lines), testLen+1) out = cli.DockerCmd(c, "logs", "--tail", "-1", id).Combined() lines = strings.Split(out, "\n") - c.Assert(lines, checker.HasLen, testLen+1) + assert.Equal(c, len(lines), testLen+1) out = cli.DockerCmd(c, "logs", "--tail", "random", id).Combined() lines = strings.Split(out, "\n") - c.Assert(lines, checker.HasLen, testLen+1) + assert.Equal(c, len(lines), testLen+1) } func (s *DockerSuite) TestLogsFollowStopped(c *check.C) { @@ -126,7 +126,7 @@ func (s *DockerSuite) TestLogsFollowStopped(c *check.C) { id := getIDByName(c, "test") logsCmd := exec.Command(dockerBinary, "logs", "-f", id) - c.Assert(logsCmd.Start(), checker.IsNil) + assert.NilError(c, logsCmd.Start()) errChan := make(chan error) go func() { @@ -136,7 +136,7 @@ func (s *DockerSuite) TestLogsFollowStopped(c *check.C) { select { case err := <-errChan: - c.Assert(err, checker.IsNil) + assert.NilError(c, err) case <-time.After(30 * time.Second): c.Fatal("Following logs is hanged") } @@ -149,19 +149,19 @@ func (s *DockerSuite) TestLogsSince(c *check.C) { log2Line := strings.Split(strings.Split(out, "\n")[1], " ") t, err := time.Parse(time.RFC3339Nano, log2Line[0]) // the timestamp log2 is written - c.Assert(err, checker.IsNil) + 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) // Skip 2 seconds unexpected := []string{"log1", "log2"} for _, v := range unexpected { - c.Assert(out, checker.Not(checker.Contains), v, check.Commentf("unexpected log message returned, since=%v", since)) + assert.Check(c, !strings.Contains(out, v), "unexpected log message returned, since=%v", since) } // Test to make sure a bad since format is caught by the client out, _, _ = dockerCmdWithError("logs", "-t", "--since=2006-01-02T15:04:0Z", name) - c.Assert(out, checker.Contains, "cannot parse \"0Z\" as \"05\"", check.Commentf("bad since format passed to server")) + assert.Assert(c, strings.Contains(out, `cannot parse "0Z" as "05"`), "bad since format passed to server") // Test with default value specified and parameter omitted expected := []string{"log1", "log2", "log3"} @@ -172,7 +172,7 @@ func (s *DockerSuite) TestLogsSince(c *check.C) { result := icmd.RunCommand(dockerBinary, cmd...) result.Assert(c, icmd.Success) for _, v := range expected { - c.Assert(result.Combined(), checker.Contains, v) + assert.Check(c, strings.Contains(result.Combined(), v)) } } } @@ -195,18 +195,18 @@ func (s *DockerSuite) TestLogsSinceFutureFollow(c *check.C) { } } - c.Assert(timestamp, checker.Not(checker.Equals), "") + assert.Assert(c, timestamp != "") t, err := time.Parse(time.RFC3339Nano, timestamp) - c.Assert(err, check.IsNil) + assert.NilError(c, err) since := t.Unix() + 2 out, _ := dockerCmd(c, "logs", "-t", "-f", fmt.Sprintf("--since=%v", since), name) - c.Assert(out, checker.Not(checker.HasLen), 0, check.Commentf("cannot read from empty log")) + assert.Assert(c, len(out) != 0, "cannot read from empty log") lines := strings.Split(strings.TrimSpace(out), "\n") for _, v := range lines { ts, err := time.Parse(time.RFC3339Nano, strings.Split(v, " ")[0]) - c.Assert(err, checker.IsNil, check.Commentf("cannot parse timestamp output from log: '%v'", v)) - c.Assert(ts.Unix() >= since, checker.Equals, true, check.Commentf("earlier log found. since=%v logdate=%v", since, ts)) + assert.NilError(c, err, "cannot parse timestamp output from log: '%v'", v) + assert.Assert(c, ts.Unix() >= since, "earlier log found. since=%v logdate=%v", since, ts) } } @@ -228,22 +228,22 @@ func (s *DockerSuite) TestLogsFollowSlowStdoutConsumer(c *check.C) { logCmd := exec.Command(dockerBinary, "logs", "-f", id) stdout, err := logCmd.StdoutPipe() - c.Assert(err, checker.IsNil) - c.Assert(logCmd.Start(), checker.IsNil) + assert.NilError(c, err) + assert.NilError(c, logCmd.Start()) defer func() { go logCmd.Wait() }() // First read slowly bytes1, err := ConsumeWithSpeed(stdout, 10, 50*time.Millisecond, stopSlowRead) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) // After the container has finished we can continue reading fast bytes2, err := ConsumeWithSpeed(stdout, 32*1024, 0, nil) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) - c.Assert(logCmd.Wait(), checker.IsNil) + assert.NilError(c, logCmd.Wait()) actual := bytes1 + bytes2 - c.Assert(actual, checker.Equals, expected) + assert.Equal(c, actual, expected) } // ConsumeWithSpeed reads chunkSize bytes from reader before sleeping @@ -272,14 +272,14 @@ func ConsumeWithSpeed(reader io.Reader, chunkSize int, interval time.Duration, s func (s *DockerSuite) TestLogsFollowGoroutinesWithStdout(c *check.C) { out, _ := dockerCmd(c, "run", "-d", "busybox", "/bin/sh", "-c", "while true; do echo hello; sleep 2; done") id := strings.TrimSpace(out) - c.Assert(waitRun(id), checker.IsNil) + assert.NilError(c, waitRun(id)) nroutines, err := getGoroutineNumber() - c.Assert(err, checker.IsNil) + assert.NilError(c, err) cmd := exec.Command(dockerBinary, "logs", "-f", id) r, w := io.Pipe() cmd.Stdout = w - c.Assert(cmd.Start(), checker.IsNil) + assert.NilError(c, cmd.Start()) go cmd.Wait() // Make sure pipe is written to @@ -289,37 +289,37 @@ func (s *DockerSuite) TestLogsFollowGoroutinesWithStdout(c *check.C) { _, err := r.Read(b) chErr <- err }() - c.Assert(<-chErr, checker.IsNil) - c.Assert(cmd.Process.Kill(), checker.IsNil) + assert.NilError(c, <-chErr) + assert.NilError(c, cmd.Process.Kill()) r.Close() cmd.Wait() // NGoroutines is not updated right away, so we need to wait before failing - c.Assert(waitForGoroutines(nroutines), checker.IsNil) + assert.NilError(c, waitForGoroutines(nroutines)) } func (s *DockerSuite) TestLogsFollowGoroutinesNoOutput(c *check.C) { out, _ := dockerCmd(c, "run", "-d", "busybox", "/bin/sh", "-c", "while true; do sleep 2; done") id := strings.TrimSpace(out) - c.Assert(waitRun(id), checker.IsNil) + assert.NilError(c, waitRun(id)) nroutines, err := getGoroutineNumber() - c.Assert(err, checker.IsNil) + assert.NilError(c, err) cmd := exec.Command(dockerBinary, "logs", "-f", id) - c.Assert(cmd.Start(), checker.IsNil) + assert.NilError(c, cmd.Start()) go cmd.Wait() time.Sleep(200 * time.Millisecond) - c.Assert(cmd.Process.Kill(), checker.IsNil) + assert.NilError(c, cmd.Process.Kill()) cmd.Wait() // NGoroutines is not updated right away, so we need to wait before failing - c.Assert(waitForGoroutines(nroutines), checker.IsNil) + assert.NilError(c, waitForGoroutines(nroutines)) } func (s *DockerSuite) TestLogsCLIContainerNotFound(c *check.C) { name := "testlogsnocontainer" out, _, _ := dockerCmdWithError("logs", name) message := fmt.Sprintf("No such container: %s\n", name) - c.Assert(out, checker.Contains, message) + assert.Assert(c, strings.Contains(out, message)) } func (s *DockerSuite) TestLogsWithDetails(c *check.C) { @@ -327,10 +327,10 @@ func (s *DockerSuite) TestLogsWithDetails(c *check.C) { out, _ := dockerCmd(c, "logs", "--details", "--timestamps", "test") logFields := strings.Fields(strings.TrimSpace(out)) - c.Assert(len(logFields), checker.Equals, 3, check.Commentf("%s", out)) + assert.Equal(c, len(logFields), 3, out) details := strings.Split(logFields[1], ",") - c.Assert(details, checker.HasLen, 2) - c.Assert(details[0], checker.Equals, "baz=qux") - c.Assert(details[1], checker.Equals, "foo=bar") + assert.Equal(c, len(details), 2) + assert.Equal(c, details[0], "baz=qux") + assert.Equal(c, details[1], "foo=bar") } diff --git a/components/engine/integration-cli/docker_cli_network_unix_test.go b/components/engine/integration-cli/docker_cli_network_unix_test.go index 734e3ee88c..fd0355adb5 100644 --- a/components/engine/integration-cli/docker_cli_network_unix_test.go +++ b/components/engine/integration-cli/docker_cli_network_unix_test.go @@ -29,6 +29,7 @@ import ( "github.com/go-check/check" "github.com/vishvananda/netlink" "golang.org/x/sys/unix" + "gotest.tools/assert" "gotest.tools/icmd" ) @@ -209,15 +210,15 @@ func setupRemoteNetworkDrivers(c *check.C, mux *http.ServeMux, url, netDrv, ipam }) err := os.MkdirAll("/etc/docker/plugins", 0755) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) fileName := fmt.Sprintf("/etc/docker/plugins/%s.spec", netDrv) err = ioutil.WriteFile(fileName, []byte(url), 0644) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) ipamFileName := fmt.Sprintf("/etc/docker/plugins/%s.spec", ipamDrv) err = ioutil.WriteFile(ipamFileName, []byte(url), 0644) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) } func (s *DockerNetworkSuite) TearDownSuite(c *check.C) { @@ -228,7 +229,7 @@ func (s *DockerNetworkSuite) TearDownSuite(c *check.C) { s.server.Close() err := os.RemoveAll("/etc/docker/plugins") - c.Assert(err, checker.IsNil) + assert.NilError(c, err) } func assertNwIsAvailable(c *check.C, name string) { @@ -268,14 +269,14 @@ func assertNwList(c *check.C, out string, expectNws []string) { } // network ls should contains all expected networks - c.Assert(nwList, checker.DeepEquals, expectNws) + assert.DeepEqual(c, nwList, expectNws) } func getNwResource(c *check.C, name string) *types.NetworkResource { out, _ := dockerCmd(c, "network", "inspect", name) var nr []types.NetworkResource err := json.Unmarshal([]byte(out), &nr) - c.Assert(err, check.IsNil) + assert.NilError(c, err) return &nr[0] } @@ -291,7 +292,7 @@ func (s *DockerNetworkSuite) TestDockerNetworkCreatePredefined(c *check.C) { for _, net := range predefined { // predefined networks can't be created again out, _, err := dockerCmdWithError("network", "create", net) - c.Assert(err, checker.NotNil, check.Commentf("%v", out)) + assert.ErrorContains(c, err, "", out) } } @@ -301,7 +302,7 @@ func (s *DockerNetworkSuite) TestDockerNetworkCreateHostBind(c *check.C) { out := runSleepingContainer(c, "--net=testbind", "-p", "5000:5000") id := strings.TrimSpace(out) - c.Assert(waitRun(id), checker.IsNil) + assert.NilError(c, waitRun(id)) out, _ = dockerCmd(c, "ps") c.Assert(out, checker.Contains, "192.168.10.1:5000->5000/tcp") } @@ -311,7 +312,7 @@ func (s *DockerNetworkSuite) TestDockerNetworkRmPredefined(c *check.C) { for _, net := range predefined { // predefined networks can't be removed out, _, err := dockerCmdWithError("network", "rm", net) - c.Assert(err, checker.NotNil, check.Commentf("%v", out)) + assert.ErrorContains(c, err, "", out) } } @@ -388,7 +389,7 @@ func (s *DockerNetworkSuite) TestDockerNetworkCreateLabel(c *check.C) { assertNwIsAvailable(c, testNet) out, _, err := dockerCmdWithError("network", "inspect", "--format={{ .Labels."+testLabel+" }}", testNet) - c.Assert(err, check.IsNil) + assert.NilError(c, err) c.Assert(strings.TrimSpace(out), check.Equals, testValue) dockerCmd(c, "network", "rm", testNet) @@ -397,7 +398,7 @@ func (s *DockerNetworkSuite) TestDockerNetworkCreateLabel(c *check.C) { func (s *DockerSuite) TestDockerNetworkDeleteNotExists(c *check.C) { out, _, err := dockerCmdWithError("network", "rm", "test") - c.Assert(err, checker.NotNil, check.Commentf("%v", out)) + assert.ErrorContains(c, err, "", out) } func (s *DockerSuite) TestDockerNetworkDeleteMultiple(c *check.C) { @@ -428,8 +429,8 @@ func (s *DockerSuite) TestDockerNetworkInspect(c *check.C) { out, _ := dockerCmd(c, "network", "inspect", "host") var networkResources []types.NetworkResource err := json.Unmarshal([]byte(out), &networkResources) - c.Assert(err, check.IsNil) - c.Assert(networkResources, checker.HasLen, 1) + assert.NilError(c, err) + assert.Equal(c, len(networkResources), 1) out, _ = dockerCmd(c, "network", "inspect", "--format={{ .Name }}", "host") c.Assert(strings.TrimSpace(out), check.Equals, "host") @@ -452,8 +453,8 @@ func (s *DockerSuite) TestDockerInspectMultipleNetwork(c *check.C) { var networkResources []types.NetworkResource err := json.Unmarshal([]byte(result.Stdout()), &networkResources) - c.Assert(err, check.IsNil) - c.Assert(networkResources, checker.HasLen, 2) + assert.NilError(c, err) + assert.Equal(c, len(networkResources), 2) } func (s *DockerSuite) TestDockerInspectMultipleNetworksIncludingNonexistent(c *check.C) { @@ -468,8 +469,8 @@ func (s *DockerSuite) TestDockerInspectMultipleNetworksIncludingNonexistent(c *c var networkResources []types.NetworkResource err := json.Unmarshal([]byte(result.Stdout()), &networkResources) - c.Assert(err, check.IsNil) - c.Assert(networkResources, checker.HasLen, 1) + assert.NilError(c, err) + assert.Equal(c, len(networkResources), 1) // Only one non-existent network to inspect // Should print an error and return an exitCode, nothing else @@ -491,8 +492,8 @@ func (s *DockerSuite) TestDockerInspectMultipleNetworksIncludingNonexistent(c *c networkResources = []types.NetworkResource{} err = json.Unmarshal([]byte(result.Stdout()), &networkResources) - c.Assert(err, check.IsNil) - c.Assert(networkResources, checker.HasLen, 1) + assert.NilError(c, err) + assert.Equal(c, len(networkResources), 1) } func (s *DockerSuite) TestDockerInspectNetworkWithContainerName(c *check.C) { @@ -514,11 +515,11 @@ func (s *DockerSuite) TestDockerInspectNetworkWithContainerName(c *check.C) { out, _ = dockerCmd(c, "network", "inspect", "brNetForInspect") var networkResources []types.NetworkResource err := json.Unmarshal([]byte(out), &networkResources) - c.Assert(err, check.IsNil) - c.Assert(networkResources, checker.HasLen, 1) + assert.NilError(c, err) + assert.Equal(c, len(networkResources), 1) container, ok := networkResources[0].Containers[containerID] - c.Assert(ok, checker.True) - c.Assert(container.Name, checker.Equals, "testNetInspect1") + assert.Assert(c, ok) + assert.Equal(c, container.Name, "testNetInspect1") // rename container and check docker inspect output update newName := "HappyNewName" @@ -528,12 +529,11 @@ func (s *DockerSuite) TestDockerInspectNetworkWithContainerName(c *check.C) { out, _ = dockerCmd(c, "network", "inspect", "brNetForInspect") var newNetRes []types.NetworkResource err = json.Unmarshal([]byte(out), &newNetRes) - c.Assert(err, check.IsNil) + assert.NilError(c, err) c.Assert(newNetRes, checker.HasLen, 1) container1, ok := newNetRes[0].Containers[containerID] - c.Assert(ok, checker.True) - c.Assert(container1.Name, checker.Equals, newName) - + assert.Assert(c, ok) + assert.Equal(c, container1.Name, newName) } func (s *DockerNetworkSuite) TestDockerNetworkConnectDisconnect(c *check.C) { @@ -559,7 +559,7 @@ func (s *DockerNetworkSuite) TestDockerNetworkConnectDisconnect(c *check.C) { // check if container IP matches network inspect ip, _, err := net.ParseCIDR(nr.Containers[containerID].IPv4Address) - c.Assert(err, check.IsNil) + assert.NilError(c, err) containerIP := findContainerIP(c, "test", "test") c.Assert(ip.String(), checker.Equals, containerIP) @@ -663,7 +663,7 @@ func (s *DockerNetworkSuite) TestDockerNetworkNullIPAMDriver(c *check.C) { testRequires(c, testEnv.IsLocalDaemon) // Create a network with null ipam driver _, _, err := dockerCmdWithError("network", "create", "-d", dummyNetworkDriver, "--ipam-driver", "null", "test000") - c.Assert(err, check.IsNil) + assert.NilError(c, err) assertNwIsAvailable(c, "test000") // Verify the inspect data contains the default subnet provided by the null @@ -736,7 +736,7 @@ func (s *DockerNetworkSuite) TestDockerNetworkInspectCustomSpecified(c *check.C) c.Assert(nr.IPAM.Config[0].Subnet, checker.Equals, "172.28.0.0/16") c.Assert(nr.IPAM.Config[0].IPRange, checker.Equals, "172.28.5.0/24") c.Assert(nr.IPAM.Config[0].Gateway, checker.Equals, "172.28.5.254") - c.Assert(nr.Internal, checker.False) + assert.Equal(c, nr.Internal, false) dockerCmd(c, "network", "rm", "br0") assertNwNotAvailable(c, "br0") } @@ -744,15 +744,15 @@ func (s *DockerNetworkSuite) TestDockerNetworkInspectCustomSpecified(c *check.C) func (s *DockerNetworkSuite) TestDockerNetworkIPAMInvalidCombinations(c *check.C) { // network with ip-range out of subnet range _, _, err := dockerCmdWithError("network", "create", "--subnet=192.168.0.0/16", "--ip-range=192.170.0.0/16", "test") - c.Assert(err, check.NotNil) + assert.ErrorContains(c, err, "") // network with multiple gateways for a single subnet _, _, err = dockerCmdWithError("network", "create", "--subnet=192.168.0.0/16", "--gateway=192.168.0.1", "--gateway=192.168.0.2", "test") - c.Assert(err, check.NotNil) + assert.ErrorContains(c, err, "") // Multiple overlapping subnets in the same network must fail _, _, err = dockerCmdWithError("network", "create", "--subnet=192.168.0.0/16", "--subnet=192.168.1.0/16", "test") - c.Assert(err, check.NotNil) + assert.ErrorContains(c, err, "") // overlapping subnets across networks must fail // create a valid test0 network @@ -760,7 +760,7 @@ func (s *DockerNetworkSuite) TestDockerNetworkIPAMInvalidCombinations(c *check.C assertNwIsAvailable(c, "test0") // create an overlapping test1 network _, _, err = dockerCmdWithError("network", "create", "--subnet=192.168.128.0/17", "test1") - c.Assert(err, check.NotNil) + assert.ErrorContains(c, err, "") dockerCmd(c, "network", "rm", "test0") assertNwNotAvailable(c, "test0") } @@ -789,10 +789,10 @@ func (s *DockerNetworkSuite) TestDockerPluginV2NetworkDriver(c *check.C) { npNameWithTag = npName + ":" + npTag ) _, _, err := dockerCmdWithError("plugin", "install", "--grant-all-permissions", npNameWithTag) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) out, _, err := dockerCmdWithError("plugin", "ls") - c.Assert(err, checker.IsNil) + assert.NilError(c, err) c.Assert(out, checker.Contains, npName) c.Assert(out, checker.Contains, npTag) c.Assert(out, checker.Contains, "true") @@ -818,46 +818,46 @@ func (s *DockerDaemonSuite) TestDockerNetworkNoDiscoveryDefaultBridgeNetwork(c * // run two containers and store first container's etc/hosts content out, err := s.d.Cmd("run", "-d", "busybox", "top") - c.Assert(err, check.IsNil) + assert.NilError(c, err) cid1 := strings.TrimSpace(out) defer s.d.Cmd("stop", cid1) hosts, err := s.d.Cmd("exec", cid1, "cat", hostsFile) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) out, err = s.d.Cmd("run", "-d", "--name", "container2", "busybox", "top") - c.Assert(err, check.IsNil) + assert.NilError(c, err) cid2 := strings.TrimSpace(out) // verify first container's etc/hosts file has not changed after spawning the second named container hostsPost, err := s.d.Cmd("exec", cid1, "cat", hostsFile) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) c.Assert(string(hosts), checker.Equals, string(hostsPost), check.Commentf("Unexpected %s change on second container creation", hostsFile)) // stop container 2 and verify first container's etc/hosts has not changed _, err = s.d.Cmd("stop", cid2) - c.Assert(err, check.IsNil) + assert.NilError(c, err) hostsPost, err = s.d.Cmd("exec", cid1, "cat", hostsFile) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) c.Assert(string(hosts), checker.Equals, string(hostsPost), check.Commentf("Unexpected %s change on second container creation", hostsFile)) // but discovery is on when connecting to non default bridge network network := "anotherbridge" out, err = s.d.Cmd("network", "create", network) - c.Assert(err, check.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) defer s.d.Cmd("network", "rm", network) out, err = s.d.Cmd("network", "connect", network, cid1) - c.Assert(err, check.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) hosts, err = s.d.Cmd("exec", cid1, "cat", hostsFile) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) hostsPost, err = s.d.Cmd("exec", cid1, "cat", hostsFile) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) c.Assert(string(hosts), checker.Equals, string(hostsPost), check.Commentf("Unexpected %s change on second network connection", hostsFile)) } @@ -918,9 +918,9 @@ func (s *DockerNetworkSuite) TestDockerNetworkAnonymousEndpoint(c *check.C) { // verify that container 1 and 2 can't ping the named container now _, _, err := dockerCmdWithError("exec", cid1, "ping", "-c", "1", cName) - c.Assert(err, check.NotNil) + assert.ErrorContains(c, err, "") _, _, err = dockerCmdWithError("exec", cid2, "ping", "-c", "1", cName) - c.Assert(err, check.NotNil) + assert.ErrorContains(c, err, "") } func (s *DockerNetworkSuite) TestDockerNetworkLinkOnDefaultNetworkOnly(c *check.C) { @@ -942,7 +942,7 @@ func (s *DockerNetworkSuite) TestDockerNetworkLinkOnDefaultNetworkOnly(c *check. // Try launching a container on default network, linking to the second container. Must fail _, _, err := dockerCmdWithError("run", "-d", "--link", fmt.Sprintf("%s:%s", cnt2, cnt2), "busybox", "top") - c.Assert(err, checker.NotNil) + assert.ErrorContains(c, err, "") // Connect second container to default network. Now a container on default network can link to it dockerCmd(c, "network", "connect", "bridge", cnt2) @@ -987,10 +987,10 @@ func (s *DockerNetworkSuite) TestDockerNetworkDriverUngracefulRestart(c *check.C s.d.StartWithBusybox(c) _, err := s.d.Cmd("network", "create", "-d", dnd, "--subnet", "1.1.1.0/24", "net1") - c.Assert(err, checker.IsNil) + assert.NilError(c, err) _, err = s.d.Cmd("run", "-itd", "--net", "net1", "--name", "foo", "--ip", "1.1.1.10", "busybox", "sh") - c.Assert(err, checker.IsNil) + assert.NilError(c, err) // Kill daemon and restart c.Assert(s.d.Kill(), checker.IsNil) @@ -1014,7 +1014,7 @@ func (s *DockerNetworkSuite) TestDockerNetworkDriverUngracefulRestart(c *check.C // trying to reuse the same ip must succeed _, err = s.d.Cmd("run", "-itd", "--net", "net1", "--name", "bar", "--ip", "1.1.1.10", "busybox", "sh") - c.Assert(err, checker.IsNil) + assert.NilError(c, err) } func (s *DockerNetworkSuite) TestDockerNetworkMacInspect(c *check.C) { @@ -1037,7 +1037,7 @@ func (s *DockerSuite) TestInspectAPIMultipleNetworks(c *check.C) { dockerCmd(c, "network", "create", "mybridge2") out, _ := dockerCmd(c, "run", "-d", "busybox", "top") id := strings.TrimSpace(out) - c.Assert(waitRun(id), check.IsNil) + assert.NilError(c, waitRun(id)) dockerCmd(c, "network", "connect", "mybridge1", id) dockerCmd(c, "network", "connect", "mybridge2", id) @@ -1045,14 +1045,14 @@ func (s *DockerSuite) TestInspectAPIMultipleNetworks(c *check.C) { body := getInspectBody(c, "v1.20", id) var inspect120 v1p20.ContainerJSON err := json.Unmarshal(body, &inspect120) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) versionedIP := inspect120.NetworkSettings.IPAddress body = getInspectBody(c, "v1.21", id) var inspect121 types.ContainerJSON err = json.Unmarshal(body, &inspect121) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) c.Assert(inspect121.NetworkSettings.Networks, checker.HasLen, 3) bridge := inspect121.NetworkSettings.Networks["bridge"] @@ -1063,14 +1063,14 @@ func (s *DockerSuite) TestInspectAPIMultipleNetworks(c *check.C) { func connectContainerToNetworks(c *check.C, d *daemon.Daemon, cName string, nws []string) { // Run a container on the default network out, err := d.Cmd("run", "-d", "--name", cName, "busybox", "top") - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) // Attach the container to other networks for _, nw := range nws { out, err = d.Cmd("network", "create", nw) - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) out, err = d.Cmd("network", "connect", nw, cName) - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) } } @@ -1078,7 +1078,7 @@ func verifyContainerIsConnectedToNetworks(c *check.C, d *daemon.Daemon, cName st // Verify container is connected to all the networks for _, nw := range nws { out, err := d.Cmd("inspect", "-f", fmt.Sprintf("{{.NetworkSettings.Networks.%s}}", nw), cName) - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) c.Assert(out, checker.Not(checker.Equals), "\n") } } @@ -1097,7 +1097,7 @@ func (s *DockerNetworkSuite) TestDockerNetworkMultipleNetworksGracefulDaemonRest s.d.Restart(c) _, err := s.d.Cmd("start", cName) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) verifyContainerIsConnectedToNetworks(c, s.d, cName, nwList) } @@ -1118,7 +1118,7 @@ func (s *DockerNetworkSuite) TestDockerNetworkMultipleNetworksUngracefulDaemonRe // Restart container _, err := s.d.Cmd("start", cName) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) verifyContainerIsConnectedToNetworks(c, s.d, cName, nwList) } @@ -1137,11 +1137,11 @@ func (s *DockerNetworkSuite) TestDockerNetworkHostModeUngracefulDaemonRestart(c for i := 0; i < 10; i++ { cName := fmt.Sprintf("hostc-%d", i) out, err := s.d.Cmd("run", "-d", "--name", cName, "--net=host", "--restart=always", "busybox", "top") - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) // verify container has finished starting before killing daemon err = s.d.WaitRun(cName) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) } // Kill daemon ungracefully and restart @@ -1151,7 +1151,7 @@ func (s *DockerNetworkSuite) TestDockerNetworkHostModeUngracefulDaemonRestart(c // make sure all the containers are up and running for i := 0; i < 10; i++ { err := s.d.WaitRun(fmt.Sprintf("hostc-%d", i)) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) } } @@ -1160,7 +1160,7 @@ func (s *DockerNetworkSuite) TestDockerNetworkConnectToHostFromOtherNetwork(c *c c.Assert(waitRun("container1"), check.IsNil) dockerCmd(c, "network", "disconnect", "bridge", "container1") out, _, err := dockerCmdWithError("network", "connect", "host", "container1") - c.Assert(err, checker.NotNil, check.Commentf("%s", out)) + assert.ErrorContains(c, err, "", out) c.Assert(out, checker.Contains, runconfig.ErrConflictHostNetwork.Error()) } @@ -1419,9 +1419,9 @@ func (s *DockerNetworkSuite) TestDockerNetworkConnectLinkLocalIP(c *check.C) { // run a container with incorrect link-local address _, _, err := dockerCmdWithError("run", "--link-local-ip", "169.253.5.5", "busybox", "top") - c.Assert(err, check.NotNil) + assert.ErrorContains(c, err, "") _, _, err = dockerCmdWithError("run", "--link-local-ip", "2001:db8::89", "busybox", "top") - c.Assert(err, check.NotNil) + assert.ErrorContains(c, err, "") // run two containers with link-local ip on the test network dockerCmd(c, "run", "-d", "--name", "c0", "--net=n0", "--link-local-ip", "169.254.7.7", "--link-local-ip", "fe80::254:77", "busybox", "top") @@ -1436,11 +1436,11 @@ func (s *DockerNetworkSuite) TestDockerNetworkConnectLinkLocalIP(c *check.C) { // verify the three containers can ping each other via the link-local addresses _, _, err = dockerCmdWithError("exec", "c0", "ping", "-c", "1", "169.254.8.8") - c.Assert(err, check.IsNil) + assert.NilError(c, err) _, _, err = dockerCmdWithError("exec", "c1", "ping", "-c", "1", "169.254.9.9") - c.Assert(err, check.IsNil) + assert.NilError(c, err) _, _, err = dockerCmdWithError("exec", "c2", "ping", "-c", "1", "169.254.7.7") - c.Assert(err, check.IsNil) + assert.NilError(c, err) // Stop and restart the three containers dockerCmd(c, "stop", "c0") @@ -1452,11 +1452,11 @@ func (s *DockerNetworkSuite) TestDockerNetworkConnectLinkLocalIP(c *check.C) { // verify the ping again _, _, err = dockerCmdWithError("exec", "c0", "ping", "-c", "1", "169.254.8.8") - c.Assert(err, check.IsNil) + assert.NilError(c, err) _, _, err = dockerCmdWithError("exec", "c1", "ping", "-c", "1", "169.254.9.9") - c.Assert(err, check.IsNil) + assert.NilError(c, err) _, _, err = dockerCmdWithError("exec", "c2", "ping", "-c", "1", "169.254.7.7") - c.Assert(err, check.IsNil) + assert.NilError(c, err) } func (s *DockerSuite) TestUserDefinedNetworkConnectDisconnectLink(c *check.C) { @@ -1475,9 +1475,9 @@ func (s *DockerSuite) TestUserDefinedNetworkConnectDisconnectLink(c *check.C) { // ping to first and its alias FirstInFoo1 must succeed _, _, err := dockerCmdWithError("exec", "second", "ping", "-c", "1", "first") - c.Assert(err, check.IsNil) + assert.NilError(c, err) _, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "FirstInFoo1") - c.Assert(err, check.IsNil) + assert.NilError(c, err) // connect first container to foo2 network dockerCmd(c, "network", "connect", "foo2", "first") @@ -1486,18 +1486,18 @@ func (s *DockerSuite) TestUserDefinedNetworkConnectDisconnectLink(c *check.C) { // ping the new alias in network foo2 _, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "FirstInFoo2") - c.Assert(err, check.IsNil) + assert.NilError(c, err) // disconnect first container from foo1 network dockerCmd(c, "network", "disconnect", "foo1", "first") // link in foo1 network must fail _, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "FirstInFoo1") - c.Assert(err, check.NotNil) + assert.ErrorContains(c, err, "") // link in foo2 network must succeed _, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "FirstInFoo2") - c.Assert(err, check.IsNil) + assert.NilError(c, err) } func (s *DockerNetworkSuite) TestDockerNetworkDisconnectDefault(c *check.C) { @@ -1528,7 +1528,7 @@ func (s *DockerNetworkSuite) TestDockerNetworkConnectWithAliasOnDefaultNetworks( containerID := strings.TrimSpace(out) for _, net := range defaults { res, _, err := dockerCmdWithError("network", "connect", "--alias", "alias"+net, net, containerID) - c.Assert(err, checker.NotNil) + assert.ErrorContains(c, err, "") c.Assert(res, checker.Contains, runconfig.ErrUnsupportedNetworkAndAlias.Error()) } } @@ -1546,13 +1546,13 @@ func (s *DockerSuite) TestUserDefinedNetworkConnectDisconnectAlias(c *check.C) { // ping first container and its alias _, _, err := dockerCmdWithError("exec", "second", "ping", "-c", "1", "first") - c.Assert(err, check.IsNil) + assert.NilError(c, err) _, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "foo") - c.Assert(err, check.IsNil) + assert.NilError(c, err) // ping first container's short-id alias _, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", stringid.TruncateID(cid)) - c.Assert(err, check.IsNil) + assert.NilError(c, err) // connect first container to net2 network dockerCmd(c, "network", "connect", "--alias=bar", "net2", "first") @@ -1561,21 +1561,21 @@ func (s *DockerSuite) TestUserDefinedNetworkConnectDisconnectAlias(c *check.C) { // ping the new alias in network foo2 _, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "bar") - c.Assert(err, check.IsNil) + assert.NilError(c, err) // disconnect first container from net1 network dockerCmd(c, "network", "disconnect", "net1", "first") // ping to net1 scoped alias "foo" must fail _, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "foo") - c.Assert(err, check.NotNil) + assert.ErrorContains(c, err, "") // ping to net2 scoped alias "bar" must still succeed _, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "bar") - c.Assert(err, check.IsNil) + assert.NilError(c, err) // ping to net2 scoped alias short-id must still succeed _, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", stringid.TruncateID(cid)) - c.Assert(err, check.IsNil) + assert.NilError(c, err) // verify the alias option is rejected when running on predefined network out, _, err := dockerCmdWithError("run", "--rm", "--name=any", "--net-alias=any", "busybox:glibc", "top") @@ -1600,15 +1600,15 @@ func (s *DockerSuite) TestUserDefinedNetworkConnectivity(c *check.C) { // ping first container by its unqualified name _, _, err := dockerCmdWithError("exec", "c2.net1", "ping", "-c", "1", "c1.net1") - c.Assert(err, check.IsNil) + assert.NilError(c, err) // ping first container by its qualified name _, _, err = dockerCmdWithError("exec", "c2.net1", "ping", "-c", "1", "c1.net1.br.net1") - c.Assert(err, check.IsNil) + assert.NilError(c, err) // ping with first qualified name masked by an additional domain. should fail _, _, err = dockerCmdWithError("exec", "c2.net1", "ping", "-c", "1", "c1.net1.br.net1.google.com") - c.Assert(err, check.NotNil) + assert.ErrorContains(c, err, "") } func (s *DockerSuite) TestEmbeddedDNSInvalidInput(c *check.C) { @@ -1628,7 +1628,7 @@ func (s *DockerSuite) TestDockerNetworkConnectFailsNoInspectChange(c *check.C) { // A failing redundant network connect should not alter current container's endpoint settings _, _, err := dockerCmdWithError("network", "connect", "bridge", "bb") - c.Assert(err, check.NotNil) + assert.ErrorContains(c, err, "") ns1 := inspectField(c, "bb", "NetworkSettings.Networks.bridge") c.Assert(ns1, check.Equals, ns0) @@ -1645,10 +1645,10 @@ func (s *DockerSuite) TestDockerNetworkInternalMode(c *check.C) { dockerCmd(c, "run", "-d", "--net=internal", "--name=second", "busybox:glibc", "top") c.Assert(waitRun("second"), check.IsNil) out, _, err := dockerCmdWithError("exec", "first", "ping", "-W", "4", "-c", "1", "8.8.8.8") - c.Assert(err, check.NotNil) + assert.ErrorContains(c, err, "") c.Assert(out, checker.Contains, "100% packet loss") _, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "first") - c.Assert(err, check.IsNil) + assert.NilError(c, err) } // Test for #21401 @@ -1748,25 +1748,26 @@ func (s *DockerNetworkSuite) TestDockerNetworkFlagAlias(c *check.C) { func (s *DockerNetworkSuite) TestDockerNetworkValidateIP(c *check.C) { _, _, err := dockerCmdWithError("network", "create", "--ipv6", "--subnet=172.28.0.0/16", "--subnet=2001:db8:1234::/64", "mynet") - c.Assert(err, check.IsNil) + assert.NilError(c, err) assertNwIsAvailable(c, "mynet") _, _, err = dockerCmdWithError("run", "-d", "--name", "mynet0", "--net=mynet", "--ip", "172.28.99.88", "--ip6", "2001:db8:1234::9988", "busybox", "top") - c.Assert(err, check.IsNil) + assert.NilError(c, err) c.Assert(waitRun("mynet0"), check.IsNil) verifyIPAddressConfig(c, "mynet0", "mynet", "172.28.99.88", "2001:db8:1234::9988") verifyIPAddresses(c, "mynet0", "mynet", "172.28.99.88", "2001:db8:1234::9988") _, _, err = dockerCmdWithError("run", "--net=mynet", "--ip", "mynet_ip", "--ip6", "2001:db8:1234::9999", "busybox", "top") - c.Assert(err.Error(), checker.Contains, "invalid IPv4 address") + assert.ErrorContains(c, err, "invalid IPv4 address") _, _, err = dockerCmdWithError("run", "--net=mynet", "--ip", "172.28.99.99", "--ip6", "mynet_ip6", "busybox", "top") - c.Assert(err.Error(), checker.Contains, "invalid IPv6 address") + assert.ErrorContains(c, err, "invalid IPv6 address") + // This is a case of IPv4 address to `--ip6` _, _, err = dockerCmdWithError("run", "--net=mynet", "--ip6", "172.28.99.99", "busybox", "top") - c.Assert(err.Error(), checker.Contains, "invalid IPv6 address") + assert.ErrorContains(c, err, "invalid IPv6 address") // This is a special case of an IPv4-mapped IPv6 address _, _, err = dockerCmdWithError("run", "--net=mynet", "--ip6", "::ffff:172.28.99.99", "busybox", "top") - c.Assert(err.Error(), checker.Contains, "invalid IPv6 address") + assert.ErrorContains(c, err, "invalid IPv6 address") } // Test case for 26220 @@ -1779,7 +1780,7 @@ func (s *DockerNetworkSuite) TestDockerNetworkDisconnectFromBridge(c *check.C) { dockerCmd(c, "create", "--name", name, "busybox", "top") _, _, err := dockerCmdWithError("network", "disconnect", network, name) - c.Assert(err, check.IsNil) + assert.NilError(c, err) } // TestConntrackFlowsLeak covers the failure scenario of ticket: https://github.com/docker/docker/issues/8795 @@ -1801,7 +1802,7 @@ func (s *DockerNetworkSuite) TestConntrackFlowsLeak(c *check.C) { // Get all the flows using netlink flows, err := netlink.ConntrackTableList(netlink.ConntrackTable, unix.AF_INET) - c.Assert(err, check.IsNil) + assert.NilError(c, err) var flowMatch int for _, flow := range flows { // count only the flows that we are interested in, skipping others that can be laying around the host @@ -1812,14 +1813,14 @@ func (s *DockerNetworkSuite) TestConntrackFlowsLeak(c *check.C) { } } // The client should have created only 1 flow - c.Assert(flowMatch, checker.Equals, 1) + assert.Equal(c, flowMatch, 1) // Now delete the server, this will trigger the conntrack cleanup cli.DockerCmd(c, "rm", "-fv", "server") // Fetch again all the flows and validate that there is no server flow in the conntrack laying around flows, err = netlink.ConntrackTableList(netlink.ConntrackTable, unix.AF_INET) - c.Assert(err, check.IsNil) + assert.NilError(c, err) flowMatch = 0 for _, flow := range flows { if flow.Forward.Protocol == unix.IPPROTO_UDP && @@ -1829,5 +1830,5 @@ func (s *DockerNetworkSuite) TestConntrackFlowsLeak(c *check.C) { } } // All the flows have to be gone - c.Assert(flowMatch, checker.Equals, 0) + assert.Equal(c, flowMatch, 0) } diff --git a/components/engine/integration-cli/docker_cli_plugins_logdriver_test.go b/components/engine/integration-cli/docker_cli_plugins_logdriver_test.go index 5fbae29362..df013e4e14 100644 --- a/components/engine/integration-cli/docker_cli_plugins_logdriver_test.go +++ b/components/engine/integration-cli/docker_cli_plugins_logdriver_test.go @@ -5,8 +5,8 @@ import ( "strings" "github.com/docker/docker/client" - "github.com/docker/docker/integration-cli/checker" "github.com/go-check/check" + "gotest.tools/assert" ) func (s *DockerSuite) TestPluginLogDriver(c *check.C) { @@ -17,11 +17,11 @@ func (s *DockerSuite) TestPluginLogDriver(c *check.C) { dockerCmd(c, "plugin", "install", pluginName) dockerCmd(c, "run", "--log-driver", pluginName, "--name=test", "busybox", "echo", "hello") out, _ := dockerCmd(c, "logs", "test") - c.Assert(strings.TrimSpace(out), checker.Equals, "hello") + assert.Equal(c, strings.TrimSpace(out), "hello") dockerCmd(c, "start", "-a", "test") out, _ = dockerCmd(c, "logs", "test") - c.Assert(strings.TrimSpace(out), checker.Equals, "hello\nhello") + assert.Equal(c, strings.TrimSpace(out), "hello\nhello") dockerCmd(c, "rm", "test") dockerCmd(c, "plugin", "disable", pluginName) @@ -36,13 +36,13 @@ func (s *DockerSuite) TestPluginLogDriverInfoList(c *check.C) { dockerCmd(c, "plugin", "install", pluginName) cli, err := client.NewClientWithOpts(client.FromEnv) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) defer cli.Close() info, err := cli.Info(context.Background()) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) drivers := strings.Join(info.Plugins.Log, " ") - c.Assert(drivers, checker.Contains, "json-file") - c.Assert(drivers, checker.Not(checker.Contains), pluginName) + assert.Assert(c, strings.Contains(drivers, "json-file")) + assert.Assert(c, !strings.Contains(drivers, pluginName)) } diff --git a/components/engine/integration-cli/docker_cli_plugins_test.go b/components/engine/integration-cli/docker_cli_plugins_test.go index 802a745275..bd9cfab612 100644 --- a/components/engine/integration-cli/docker_cli_plugins_test.go +++ b/components/engine/integration-cli/docker_cli_plugins_test.go @@ -17,6 +17,7 @@ import ( "github.com/docker/docker/integration-cli/daemon" "github.com/docker/docker/internal/test/fixtures/plugin" "github.com/go-check/check" + "gotest.tools/assert" ) var ( @@ -31,26 +32,26 @@ var ( func (ps *DockerPluginSuite) TestPluginBasicOps(c *check.C) { plugin := ps.getPluginRepoWithTag() _, _, err := dockerCmdWithError("plugin", "install", "--grant-all-permissions", plugin) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) out, _, err := dockerCmdWithError("plugin", "ls") - c.Assert(err, checker.IsNil) + assert.NilError(c, err) c.Assert(out, checker.Contains, plugin) c.Assert(out, checker.Contains, "true") id, _, err := dockerCmdWithError("plugin", "inspect", "-f", "{{.Id}}", plugin) id = strings.TrimSpace(id) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) out, _, err = dockerCmdWithError("plugin", "remove", plugin) - c.Assert(err, checker.NotNil) + assert.ErrorContains(c, err, "") c.Assert(out, checker.Contains, "is enabled") _, _, err = dockerCmdWithError("plugin", "disable", plugin) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) out, _, err = dockerCmdWithError("plugin", "remove", plugin) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) c.Assert(out, checker.Contains, plugin) _, err = os.Stat(filepath.Join(testEnv.DaemonInfo.DockerRootDir, "plugins", id)) @@ -63,13 +64,13 @@ func (ps *DockerPluginSuite) TestPluginForceRemove(c *check.C) { pNameWithTag := ps.getPluginRepoWithTag() _, _, err := dockerCmdWithError("plugin", "install", "--grant-all-permissions", pNameWithTag) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) out, _, _ := dockerCmdWithError("plugin", "remove", pNameWithTag) c.Assert(out, checker.Contains, "is enabled") out, _, err = dockerCmdWithError("plugin", "remove", "--force", pNameWithTag) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) c.Assert(out, checker.Contains, pNameWithTag) } @@ -77,32 +78,32 @@ func (s *DockerSuite) TestPluginActive(c *check.C) { testRequires(c, DaemonIsLinux, IsAmd64, Network) _, _, err := dockerCmdWithError("plugin", "install", "--grant-all-permissions", pNameWithTag) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) _, _, err = dockerCmdWithError("volume", "create", "-d", pNameWithTag, "--name", "testvol1") - c.Assert(err, checker.IsNil) + assert.NilError(c, err) out, _, _ := dockerCmdWithError("plugin", "disable", pNameWithTag) c.Assert(out, checker.Contains, "in use") _, _, err = dockerCmdWithError("volume", "rm", "testvol1") - c.Assert(err, checker.IsNil) + assert.NilError(c, err) _, _, err = dockerCmdWithError("plugin", "disable", pNameWithTag) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) out, _, err = dockerCmdWithError("plugin", "remove", pNameWithTag) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) c.Assert(out, checker.Contains, pNameWithTag) } func (s *DockerSuite) TestPluginActiveNetwork(c *check.C) { testRequires(c, DaemonIsLinux, IsAmd64, Network) _, _, err := dockerCmdWithError("plugin", "install", "--grant-all-permissions", npNameWithTag) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) out, _, err := dockerCmdWithError("network", "create", "-d", npNameWithTag, "test") - c.Assert(err, checker.IsNil) + assert.NilError(c, err) nID := strings.TrimSpace(out) @@ -110,16 +111,16 @@ func (s *DockerSuite) TestPluginActiveNetwork(c *check.C) { c.Assert(out, checker.Contains, "is in use") _, _, err = dockerCmdWithError("network", "rm", nID) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) out, _, _ = dockerCmdWithError("plugin", "remove", npNameWithTag) c.Assert(out, checker.Contains, "is enabled") _, _, err = dockerCmdWithError("plugin", "disable", npNameWithTag) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) out, _, err = dockerCmdWithError("plugin", "remove", npNameWithTag) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) c.Assert(out, checker.Contains, npNameWithTag) } @@ -127,30 +128,30 @@ func (ps *DockerPluginSuite) TestPluginInstallDisable(c *check.C) { pName := ps.getPluginRepoWithTag() out, _, err := dockerCmdWithError("plugin", "install", "--grant-all-permissions", "--disable", pName) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) c.Assert(strings.TrimSpace(out), checker.Contains, pName) out, _, err = dockerCmdWithError("plugin", "ls") - c.Assert(err, checker.IsNil) + assert.NilError(c, err) c.Assert(out, checker.Contains, "false") out, _, err = dockerCmdWithError("plugin", "enable", pName) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) c.Assert(strings.TrimSpace(out), checker.Contains, pName) out, _, err = dockerCmdWithError("plugin", "disable", pName) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) c.Assert(strings.TrimSpace(out), checker.Contains, pName) out, _, err = dockerCmdWithError("plugin", "remove", pName) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) c.Assert(strings.TrimSpace(out), checker.Contains, pName) } func (s *DockerSuite) TestPluginInstallDisableVolumeLs(c *check.C) { testRequires(c, DaemonIsLinux, IsAmd64, Network) out, _, err := dockerCmdWithError("plugin", "install", "--grant-all-permissions", "--disable", pName) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) c.Assert(strings.TrimSpace(out), checker.Contains, pName) dockerCmd(c, "volume", "ls") @@ -198,11 +199,11 @@ func (ps *DockerPluginSuite) TestPluginSet(c *check.C) { c.Assert(strings.TrimSpace(env), checker.Contains, "bar") out, _, err := dockerCmdWithError("plugin", "set", name, "pmount2.source=bar2") - c.Assert(err, checker.NotNil) + assert.ErrorContains(c, err, "") c.Assert(out, checker.Contains, "Plugin config has no mount source") out, _, err = dockerCmdWithError("plugin", "set", name, "pdev2.path=/dev/bar2") - c.Assert(err, checker.NotNil) + assert.ErrorContains(c, err, "") c.Assert(out, checker.Contains, "Plugin config has no device path") } @@ -233,7 +234,7 @@ func (ps *DockerPluginSuite) TestPluginInstallImage(c *check.C) { dockerCmd(c, "push", repoName) out, _, err := dockerCmdWithError("plugin", "install", repoName) - c.Assert(err, checker.NotNil) + assert.ErrorContains(c, err, "") c.Assert(out, checker.Contains, `Encountered remote "application/vnd.docker.container.image.v1+json"(image) when fetching`) } @@ -241,51 +242,51 @@ func (ps *DockerPluginSuite) TestPluginEnableDisableNegative(c *check.C) { pName := ps.getPluginRepoWithTag() out, _, err := dockerCmdWithError("plugin", "install", "--grant-all-permissions", pName) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) c.Assert(strings.TrimSpace(out), checker.Contains, pName) out, _, err = dockerCmdWithError("plugin", "enable", pName) - c.Assert(err, checker.NotNil) + assert.ErrorContains(c, err, "") c.Assert(strings.TrimSpace(out), checker.Contains, "already enabled") _, _, err = dockerCmdWithError("plugin", "disable", pName) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) out, _, err = dockerCmdWithError("plugin", "disable", pName) - c.Assert(err, checker.NotNil) + assert.ErrorContains(c, err, "") c.Assert(strings.TrimSpace(out), checker.Contains, "already disabled") _, _, err = dockerCmdWithError("plugin", "remove", pName) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) } func (ps *DockerPluginSuite) TestPluginCreate(c *check.C) { name := "foo/bar-driver" temp, err := ioutil.TempDir("", "foo") - c.Assert(err, checker.IsNil) + assert.NilError(c, err) defer os.RemoveAll(temp) data := `{"description": "foo plugin"}` err = ioutil.WriteFile(filepath.Join(temp, "config.json"), []byte(data), 0644) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) err = os.MkdirAll(filepath.Join(temp, "rootfs"), 0700) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) out, _, err := dockerCmdWithError("plugin", "create", name, temp) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) c.Assert(out, checker.Contains, name) out, _, err = dockerCmdWithError("plugin", "ls") - c.Assert(err, checker.IsNil) + assert.NilError(c, err) c.Assert(out, checker.Contains, name) out, _, err = dockerCmdWithError("plugin", "create", name, temp) - c.Assert(err, checker.NotNil) + assert.ErrorContains(c, err, "") c.Assert(out, checker.Contains, "already exist") out, _, err = dockerCmdWithError("plugin", "ls") - c.Assert(err, checker.IsNil) + assert.NilError(c, err) c.Assert(out, checker.Contains, name) // The output will consists of one HEADER line and one line of foo/bar-driver c.Assert(len(strings.Split(strings.TrimSpace(out), "\n")), checker.Equals, 2) @@ -295,49 +296,49 @@ func (ps *DockerPluginSuite) TestPluginInspect(c *check.C) { pNameWithTag := ps.getPluginRepoWithTag() _, _, err := dockerCmdWithError("plugin", "install", "--grant-all-permissions", pNameWithTag) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) out, _, err := dockerCmdWithError("plugin", "ls") - c.Assert(err, checker.IsNil) + assert.NilError(c, err) c.Assert(out, checker.Contains, pNameWithTag) c.Assert(out, checker.Contains, "true") // Find the ID first out, _, err = dockerCmdWithError("plugin", "inspect", "-f", "{{.Id}}", pNameWithTag) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) id := strings.TrimSpace(out) - c.Assert(id, checker.Not(checker.Equals), "") + assert.Assert(c, id != "") // Long form out, _, err = dockerCmdWithError("plugin", "inspect", "-f", "{{.Id}}", id) - c.Assert(err, checker.IsNil) - c.Assert(strings.TrimSpace(out), checker.Equals, id) + assert.NilError(c, err) + assert.Equal(c, strings.TrimSpace(out), id) // Short form out, _, err = dockerCmdWithError("plugin", "inspect", "-f", "{{.Id}}", id[:5]) - c.Assert(err, checker.IsNil) - c.Assert(strings.TrimSpace(out), checker.Equals, id) + assert.NilError(c, err) + assert.Equal(c, strings.TrimSpace(out), id) // Name with tag form out, _, err = dockerCmdWithError("plugin", "inspect", "-f", "{{.Id}}", pNameWithTag) - c.Assert(err, checker.IsNil) - c.Assert(strings.TrimSpace(out), checker.Equals, id) + assert.NilError(c, err) + assert.Equal(c, strings.TrimSpace(out), id) // Name without tag form out, _, err = dockerCmdWithError("plugin", "inspect", "-f", "{{.Id}}", ps.getPluginRepo()) - c.Assert(err, checker.IsNil) - c.Assert(strings.TrimSpace(out), checker.Equals, id) + assert.NilError(c, err) + assert.Equal(c, strings.TrimSpace(out), id) _, _, err = dockerCmdWithError("plugin", "disable", pNameWithTag) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) out, _, err = dockerCmdWithError("plugin", "remove", pNameWithTag) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) c.Assert(out, checker.Contains, pNameWithTag) // After remove nothing should be found _, _, err = dockerCmdWithError("plugin", "inspect", "-f", "{{.Id}}", id[:5]) - c.Assert(err, checker.NotNil) + assert.ErrorContains(c, err, "") } // Test case for https://github.com/docker/docker/pull/29186#discussion_r91277345 @@ -346,9 +347,9 @@ func (s *DockerSuite) TestPluginInspectOnWindows(c *check.C) { testRequires(c, DaemonIsWindows) out, _, err := dockerCmdWithError("plugin", "inspect", "foobar") - c.Assert(err, checker.NotNil) + assert.ErrorContains(c, err, "") c.Assert(out, checker.Contains, "plugins are not supported on this platform") - c.Assert(err.Error(), checker.Contains, "plugins are not supported on this platform") + assert.ErrorContains(c, err, "plugins are not supported on this platform") } func (ps *DockerPluginSuite) TestPluginIDPrefix(c *check.C) { @@ -367,11 +368,11 @@ func (ps *DockerPluginSuite) TestPluginIDPrefix(c *check.C) { // Find ID first id, _, err := dockerCmdWithError("plugin", "inspect", "-f", "{{.Id}}", name) id = strings.TrimSpace(id) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) // List current state out, _, err := dockerCmdWithError("plugin", "ls") - c.Assert(err, checker.IsNil) + assert.NilError(c, err) c.Assert(out, checker.Contains, name) c.Assert(out, checker.Contains, "false") @@ -385,36 +386,36 @@ func (ps *DockerPluginSuite) TestPluginIDPrefix(c *check.C) { // Enable _, _, err = dockerCmdWithError("plugin", "enable", id[:5]) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) out, _, err = dockerCmdWithError("plugin", "ls") - c.Assert(err, checker.IsNil) + assert.NilError(c, err) c.Assert(out, checker.Contains, name) c.Assert(out, checker.Contains, "true") // Disable _, _, err = dockerCmdWithError("plugin", "disable", id[:5]) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) out, _, err = dockerCmdWithError("plugin", "ls") - c.Assert(err, checker.IsNil) + assert.NilError(c, err) c.Assert(out, checker.Contains, name) c.Assert(out, checker.Contains, "false") // Remove _, _, err = dockerCmdWithError("plugin", "remove", id[:5]) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) // List returns none out, _, err = dockerCmdWithError("plugin", "ls") - c.Assert(err, checker.IsNil) + assert.NilError(c, err) c.Assert(out, checker.Not(checker.Contains), name) } func (ps *DockerPluginSuite) TestPluginListDefaultFormat(c *check.C) { config, err := ioutil.TempDir("", "config-file-") - c.Assert(err, check.IsNil) + assert.NilError(c, err) defer os.RemoveAll(config) err = ioutil.WriteFile(filepath.Join(config, "config.json"), []byte(`{"pluginsFormat": "raw"}`), 0644) - c.Assert(err, check.IsNil) + assert.NilError(c, err) name := "test:latest" client := testEnv.APIClient() @@ -449,7 +450,7 @@ func (s *DockerSuite) TestPluginUpgrade(c *check.C) { dockerCmd(c, "run", "--rm", "-v", "bananas:/apple", "busybox", "sh", "-c", "touch /apple/core") out, _, err := dockerCmdWithError("plugin", "upgrade", "--grant-all-permissions", plugin, pluginV2) - c.Assert(err, checker.NotNil, check.Commentf("%s", out)) + assert.ErrorContains(c, err, "", out) c.Assert(out, checker.Contains, "disabled before upgrading") out, _ = dockerCmd(c, "plugin", "inspect", "--format={{.ID}}", plugin) @@ -464,7 +465,7 @@ func (s *DockerSuite) TestPluginUpgrade(c *check.C) { // make sure "v2" file exists _, err = os.Stat(filepath.Join(testEnv.DaemonInfo.DockerRootDir, "plugins", id, "rootfs", "v2")) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) dockerCmd(c, "plugin", "enable", plugin) dockerCmd(c, "volume", "inspect", "bananas") @@ -483,11 +484,11 @@ func (s *DockerSuite) TestPluginMetricsCollector(c *check.C) { // plugin lisens on localhost:19393 and proxies the metrics resp, err := http.Get("http://localhost:19393/metrics") - c.Assert(err, checker.IsNil) + assert.NilError(c, err) defer resp.Body.Close() b, err := ioutil.ReadAll(resp.Body) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) // check that a known metric is there... don't expect this metric to change over time.. probably safe c.Assert(string(b), checker.Contains, "container_actions") } diff --git a/components/engine/integration-cli/docker_cli_port_test.go b/components/engine/integration-cli/docker_cli_port_test.go index 84058cda10..32f59eb3f4 100644 --- a/components/engine/integration-cli/docker_cli_port_test.go +++ b/components/engine/integration-cli/docker_cli_port_test.go @@ -10,6 +10,7 @@ import ( "github.com/docker/docker/integration-cli/checker" "github.com/go-check/check" + "gotest.tools/assert" ) func (s *DockerSuite) TestPortList(c *check.C) { @@ -22,13 +23,13 @@ func (s *DockerSuite) TestPortList(c *check.C) { err := assertPortList(c, out, []string{"0.0.0.0:9876"}) // Port list is not correct - c.Assert(err, checker.IsNil) + assert.NilError(c, err) out, _ = dockerCmd(c, "port", firstID) err = assertPortList(c, out, []string{"80/tcp -> 0.0.0.0:9876"}) // Port list is not correct - c.Assert(err, checker.IsNil) + assert.NilError(c, err) dockerCmd(c, "rm", "-f", firstID) @@ -44,7 +45,7 @@ func (s *DockerSuite) TestPortList(c *check.C) { err = assertPortList(c, out, []string{"0.0.0.0:9876"}) // Port list is not correct - c.Assert(err, checker.IsNil) + assert.NilError(c, err) out, _ = dockerCmd(c, "port", ID) @@ -53,7 +54,7 @@ func (s *DockerSuite) TestPortList(c *check.C) { "81/tcp -> 0.0.0.0:9877", "82/tcp -> 0.0.0.0:9878"}) // Port list is not correct - c.Assert(err, checker.IsNil) + assert.NilError(c, err) dockerCmd(c, "rm", "-f", ID) @@ -70,7 +71,7 @@ func (s *DockerSuite) TestPortList(c *check.C) { err = assertPortList(c, out, []string{"0.0.0.0:9876", "0.0.0.0:9999"}) // Port list is not correct - c.Assert(err, checker.IsNil) + assert.NilError(c, err) out, _ = dockerCmd(c, "port", ID) @@ -80,7 +81,7 @@ func (s *DockerSuite) TestPortList(c *check.C) { "81/tcp -> 0.0.0.0:9877", "82/tcp -> 0.0.0.0:9878"}) // Port list is not correct - c.Assert(err, checker.IsNil) + assert.NilError(c, err) dockerCmd(c, "rm", "-f", ID) testRange := func() { @@ -96,7 +97,7 @@ func (s *DockerSuite) TestPortList(c *check.C) { err = assertPortList(c, out, []string{fmt.Sprintf("80/tcp -> 0.0.0.0:%d", 9090+i)}) // Port list is not correct - c.Assert(err, checker.IsNil) + assert.NilError(c, err) } // test port range exhaustion @@ -137,7 +138,7 @@ func (s *DockerSuite) TestPortList(c *check.C) { "82/tcp -> 0.0.0.0:9802", "83/tcp -> 0.0.0.0:9803"}) // Port list is not correct - c.Assert(err, checker.IsNil) + assert.NilError(c, err) dockerCmd(c, "rm", "-f", ID) // test mixing protocols in same port range @@ -152,7 +153,7 @@ func (s *DockerSuite) TestPortList(c *check.C) { // Running this test multiple times causes the TCP port to increment. err = assertPortRange(c, out, []int{8000, 8080}, []int{8000, 8080}) // Port list is not correct - c.Assert(err, checker.IsNil) + assert.NilError(c, err) dockerCmd(c, "rm", "-f", ID) } @@ -292,7 +293,7 @@ func (s *DockerSuite) TestPortHostBinding(c *check.C) { err := assertPortList(c, out, []string{"0.0.0.0:9876"}) // Port list is not correct - c.Assert(err, checker.IsNil) + assert.NilError(c, err) dockerCmd(c, "run", "--net=host", "busybox", "nc", "localhost", "9876") diff --git a/components/engine/integration-cli/docker_cli_proxy_test.go b/components/engine/integration-cli/docker_cli_proxy_test.go index e57c9c2c78..d7bb1c8fbe 100644 --- a/components/engine/integration-cli/docker_cli_proxy_test.go +++ b/components/engine/integration-cli/docker_cli_proxy_test.go @@ -4,8 +4,8 @@ import ( "net" "strings" - "github.com/docker/docker/integration-cli/checker" "github.com/go-check/check" + "gotest.tools/assert" "gotest.tools/icmd" ) @@ -24,7 +24,7 @@ func (s *DockerDaemonSuite) TestCLIProxyProxyTCPSock(c *check.C) { testRequires(c, testEnv.IsLocalDaemon) // get the IP to use to connect since we can't use localhost addrs, err := net.InterfaceAddrs() - c.Assert(err, checker.IsNil) + assert.NilError(c, err) var ip string for _, addr := range addrs { sAddr := addr.String() @@ -35,7 +35,7 @@ func (s *DockerDaemonSuite) TestCLIProxyProxyTCPSock(c *check.C) { } } - c.Assert(ip, checker.Not(checker.Equals), "") + assert.Assert(c, ip != "") s.d.Start(c, "-H", "tcp://"+ip+":2375") diff --git a/components/engine/integration-cli/docker_cli_prune_unix_test.go b/components/engine/integration-cli/docker_cli_prune_unix_test.go index d60420b591..0264950df8 100644 --- a/components/engine/integration-cli/docker_cli_prune_unix_test.go +++ b/components/engine/integration-cli/docker_cli_prune_unix_test.go @@ -15,17 +15,18 @@ import ( "github.com/docker/docker/integration-cli/cli/build" "github.com/docker/docker/integration-cli/daemon" "github.com/go-check/check" + "gotest.tools/assert" "gotest.tools/icmd" ) func pruneNetworkAndVerify(c *check.C, d *daemon.Daemon, kept, pruned []string) { _, err := d.Cmd("network", "prune", "--force") - c.Assert(err, checker.IsNil) + assert.NilError(c, err) for _, s := range kept { waitAndAssert(c, defaultReconciliationTimeout, func(*check.C) (interface{}, check.CommentInterface) { out, err := d.Cmd("network", "ls", "--format", "{{.Name}}") - c.Assert(err, checker.IsNil) + assert.NilError(c, err) return out, nil }, checker.Contains, s) } @@ -33,7 +34,7 @@ func pruneNetworkAndVerify(c *check.C, d *daemon.Daemon, kept, pruned []string) for _, s := range pruned { waitAndAssert(c, defaultReconciliationTimeout, func(*check.C) (interface{}, check.CommentInterface) { out, err := d.Cmd("network", "ls", "--format", "{{.Name}}") - c.Assert(err, checker.IsNil) + assert.NilError(c, err) return out, nil }, checker.Not(checker.Contains), s) } @@ -42,17 +43,17 @@ func pruneNetworkAndVerify(c *check.C, d *daemon.Daemon, kept, pruned []string) func (s *DockerSwarmSuite) TestPruneNetwork(c *check.C) { d := s.AddDaemon(c, true, true) _, err := d.Cmd("network", "create", "n1") // used by container (testprune) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) _, err = d.Cmd("network", "create", "n2") - c.Assert(err, checker.IsNil) + assert.NilError(c, err) _, err = d.Cmd("network", "create", "n3", "--driver", "overlay") // used by service (testprunesvc) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) _, err = d.Cmd("network", "create", "n4", "--driver", "overlay") - c.Assert(err, checker.IsNil) + assert.NilError(c, err) cName := "testprune" _, err = d.Cmd("run", "-d", "--name", cName, "--net", "n1", "busybox", "top") - c.Assert(err, checker.IsNil) + assert.NilError(c, err) serviceName := "testprunesvc" replicas := 1 @@ -61,8 +62,8 @@ func (s *DockerSwarmSuite) TestPruneNetwork(c *check.C) { "--replicas", strconv.Itoa(replicas), "--network", "n3", "busybox", "top") - c.Assert(err, checker.IsNil) - c.Assert(strings.TrimSpace(out), checker.Not(checker.Equals), "") + assert.NilError(c, err) + assert.Assert(c, strings.TrimSpace(out) != "") waitAndAssert(c, defaultReconciliationTimeout, d.CheckActiveContainerCount, checker.Equals, replicas+1) // prune and verify @@ -70,9 +71,9 @@ func (s *DockerSwarmSuite) TestPruneNetwork(c *check.C) { // remove containers, then prune and verify again _, err = d.Cmd("rm", "-f", cName) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) _, err = d.Cmd("service", "rm", serviceName) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) waitAndAssert(c, defaultReconciliationTimeout, d.CheckActiveContainerCount, checker.Equals, 0) pruneNetworkAndVerify(c, d, []string{}, []string{"n1", "n3"}) @@ -90,23 +91,23 @@ func (s *DockerDaemonSuite) TestPruneImageDangling(c *check.C) { id := strings.TrimSpace(result.Combined()) out, err := s.d.Cmd("images", "-q", "--no-trunc") - c.Assert(err, checker.IsNil) + assert.NilError(c, err) c.Assert(strings.TrimSpace(out), checker.Contains, id) out, err = s.d.Cmd("image", "prune", "--force") - c.Assert(err, checker.IsNil) + assert.NilError(c, err) c.Assert(strings.TrimSpace(out), checker.Not(checker.Contains), id) out, err = s.d.Cmd("images", "-q", "--no-trunc") - c.Assert(err, checker.IsNil) + assert.NilError(c, err) c.Assert(strings.TrimSpace(out), checker.Contains, id) out, err = s.d.Cmd("image", "prune", "--force", "--all") - c.Assert(err, checker.IsNil) + assert.NilError(c, err) c.Assert(strings.TrimSpace(out), checker.Contains, id) out, err = s.d.Cmd("images", "-q", "--no-trunc") - c.Assert(err, checker.IsNil) + assert.NilError(c, err) c.Assert(strings.TrimSpace(out), checker.Not(checker.Contains), id) } @@ -150,10 +151,10 @@ func (s *DockerSuite) TestPruneContainerLabel(c *check.C) { // Add a config file of label=foobar, that will have no impact if cli is label!=foobar config := `{"pruneFilters": ["label=foobar"]}` d, err := ioutil.TempDir("", "integration-cli-") - c.Assert(err, checker.IsNil) + assert.NilError(c, err) defer os.RemoveAll(d) err = ioutil.WriteFile(filepath.Join(d, "config.json"), []byte(config), 0644) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) // With config.json only, prune based on label=foobar out = cli.DockerCmd(c, "--config", d, "container", "prune", "--force").Combined() @@ -208,10 +209,10 @@ func (s *DockerSuite) TestPruneVolumeLabel(c *check.C) { // Add a config file of label=foobar, that will have no impact if cli is label!=foobar config := `{"pruneFilters": ["label=foobar"]}` d, err := ioutil.TempDir("", "integration-cli-") - c.Assert(err, checker.IsNil) + assert.NilError(c, err) defer os.RemoveAll(d) err = ioutil.WriteFile(filepath.Join(d, "config.json"), []byte(config), 0644) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) // With config.json only, prune based on label=foobar out, _ = dockerCmd(c, "--config", d, "volume", "prune", "--force") @@ -278,7 +279,7 @@ func (s *DockerDaemonSuite) TestPruneImageLabel(c *check.C) { result.Assert(c, icmd.Success) id1 := strings.TrimSpace(result.Combined()) out, err := s.d.Cmd("images", "-q", "--no-trunc") - c.Assert(err, checker.IsNil) + assert.NilError(c, err) c.Assert(strings.TrimSpace(out), checker.Contains, id1) result = cli.BuildCmd(c, "test2", cli.Daemon(s.d), @@ -289,21 +290,21 @@ func (s *DockerDaemonSuite) TestPruneImageLabel(c *check.C) { result.Assert(c, icmd.Success) id2 := strings.TrimSpace(result.Combined()) out, err = s.d.Cmd("images", "-q", "--no-trunc") - c.Assert(err, checker.IsNil) + assert.NilError(c, err) c.Assert(strings.TrimSpace(out), checker.Contains, id2) out, err = s.d.Cmd("image", "prune", "--force", "--all", "--filter", "label=foo=bar") - c.Assert(err, checker.IsNil) + assert.NilError(c, err) c.Assert(strings.TrimSpace(out), checker.Contains, id1) c.Assert(strings.TrimSpace(out), checker.Not(checker.Contains), id2) out, err = s.d.Cmd("image", "prune", "--force", "--all", "--filter", "label!=bar=foo") - c.Assert(err, checker.IsNil) + assert.NilError(c, err) c.Assert(strings.TrimSpace(out), checker.Not(checker.Contains), id1) c.Assert(strings.TrimSpace(out), checker.Not(checker.Contains), id2) out, err = s.d.Cmd("image", "prune", "--force", "--all", "--filter", "label=bar=foo") - c.Assert(err, checker.IsNil) + assert.NilError(c, err) c.Assert(strings.TrimSpace(out), checker.Not(checker.Contains), id1) c.Assert(strings.TrimSpace(out), checker.Contains, id2) } diff --git a/components/engine/integration-cli/docker_cli_ps_test.go b/components/engine/integration-cli/docker_cli_ps_test.go index 824ca683ba..f34cd0f8a8 100644 --- a/components/engine/integration-cli/docker_cli_ps_test.go +++ b/components/engine/integration-cli/docker_cli_ps_test.go @@ -13,6 +13,8 @@ import ( "github.com/docker/docker/integration-cli/cli/build" "github.com/docker/docker/pkg/stringid" "github.com/go-check/check" + "gotest.tools/assert" + is "gotest.tools/assert/cmp" "gotest.tools/icmd" ) @@ -147,7 +149,7 @@ func (s *DockerSuite) TestPsListContainersSize(c *check.C) { baseSizeIndex := strings.Index(baseLines[0], "SIZE") baseFoundsize := baseLines[1][baseSizeIndex:] baseBytes, err := strconv.Atoi(strings.Split(baseFoundsize, "B")[0]) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) name := "test_size" dockerCmd(c, "run", "--name", name, "busybox", "sh", "-c", "echo 1 > test") @@ -167,7 +169,7 @@ func (s *DockerSuite) TestPsListContainersSize(c *check.C) { } result.Assert(c, icmd.Success) lines := strings.Split(strings.Trim(result.Combined(), "\n "), "\n") - c.Assert(lines, checker.HasLen, 2, check.Commentf("Expected 2 lines for 'ps -s -n=1' output, got %d", len(lines))) + assert.Equal(c, len(lines), 2, "Expected 2 lines for 'ps -s -n=1' output, got %d", len(lines)) sizeIndex := strings.Index(lines[0], "SIZE") idIndex := strings.Index(lines[0], "CONTAINER ID") foundID := lines[1][idIndex : idIndex+12] @@ -497,7 +499,7 @@ func (s *DockerSuite) TestPsRightTagName(c *check.C) { lines = RemoveLinesForExistingElements(lines, existingContainers) // skip header lines = lines[1:] - c.Assert(lines, checker.HasLen, 3, check.Commentf("There should be 3 running container, got %d", len(lines))) + assert.Equal(c, len(lines), 3, "There should be 3 running container, got %d", len(lines)) for _, line := range lines { f := strings.Fields(line) switch f[0] { @@ -540,7 +542,7 @@ func (s *DockerSuite) TestPsListContainersFilterCreated(c *check.C) { // filter containers by 'create' - note, no -a needed out, _ = dockerCmd(c, "ps", "-q", "-f", "status=created") containerOut := strings.TrimSpace(out) - c.Assert(cID, checker.HasPrefix, containerOut) + assert.Assert(c, strings.HasPrefix(cID, containerOut)) } // Test for GitHub issue #12595 @@ -641,15 +643,15 @@ func (s *DockerSuite) TestPsShowMounts(c *check.C) { lines := strings.Split(strings.TrimSpace(string(out)), "\n") lines = RemoveLinesForExistingElements(lines, existingContainers) - c.Assert(lines, checker.HasLen, 3) + assert.Equal(c, len(lines), 3) fields := strings.Fields(lines[0]) - c.Assert(fields, checker.HasLen, 2) + assert.Equal(c, len(fields), 2) c.Assert(fields[0], checker.Equals, "bind-mount-test") c.Assert(fields[1], checker.Equals, bindMountSource) fields = strings.Fields(lines[1]) - c.Assert(fields, checker.HasLen, 2) + assert.Equal(c, len(fields), 2) anonymousVolumeID := fields[1] @@ -661,7 +663,7 @@ func (s *DockerSuite) TestPsShowMounts(c *check.C) { lines = strings.Split(strings.TrimSpace(string(out)), "\n") lines = RemoveLinesForExistingElements(lines, existingContainers) - c.Assert(lines, checker.HasLen, 1) + assert.Equal(c, len(lines), 1) fields = strings.Fields(lines[0]) c.Assert(fields[1], checker.Equals, "ps-volume-test") @@ -675,7 +677,7 @@ func (s *DockerSuite) TestPsShowMounts(c *check.C) { lines = strings.Split(strings.TrimSpace(string(out)), "\n") lines = RemoveLinesForExistingElements(lines, existingContainers) - c.Assert(lines, checker.HasLen, 2) + assert.Equal(c, len(lines), 2) fields = strings.Fields(lines[0]) c.Assert(fields[1], checker.Equals, anonymousVolumeID) @@ -687,10 +689,10 @@ func (s *DockerSuite) TestPsShowMounts(c *check.C) { lines = strings.Split(strings.TrimSpace(string(out)), "\n") lines = RemoveLinesForExistingElements(lines, existingContainers) - c.Assert(lines, checker.HasLen, 1) + assert.Equal(c, len(lines), 1) fields = strings.Fields(lines[0]) - c.Assert(fields, checker.HasLen, 2) + assert.Equal(c, len(fields), 2) c.Assert(fields[0], checker.Equals, "bind-mount-test") c.Assert(fields[1], checker.Equals, bindMountSource) @@ -699,10 +701,10 @@ func (s *DockerSuite) TestPsShowMounts(c *check.C) { lines = strings.Split(strings.TrimSpace(string(out)), "\n") lines = RemoveLinesForExistingElements(lines, existingContainers) - c.Assert(lines, checker.HasLen, 1) + assert.Equal(c, len(lines), 1) fields = strings.Fields(lines[0]) - c.Assert(fields, checker.HasLen, 2) + assert.Equal(c, len(fields), 2) c.Assert(fields[0], checker.Equals, "bind-mount-test") c.Assert(fields[1], checker.Equals, bindMountSource) @@ -731,7 +733,7 @@ func (s *DockerSuite) TestPsListContainersFilterNetwork(c *check.C) { lines = lines[1:] // ps output should have no containers - c.Assert(RemoveLinesForExistingElements(lines, existing), checker.HasLen, 0) + assert.Equal(c, len(RemoveLinesForExistingElements(lines, existing)), 0) // Filter docker ps on network bridge out, _ = dockerCmd(c, "ps", "--filter", "network=bridge") @@ -743,7 +745,7 @@ func (s *DockerSuite) TestPsListContainersFilterNetwork(c *check.C) { lines = lines[1:] // ps output should have only one container - c.Assert(RemoveLinesForExistingElements(lines, existing), checker.HasLen, 1) + assert.Equal(c, len(RemoveLinesForExistingElements(lines, existing)), 1) // Making sure onbridgenetwork is on the output c.Assert(containerOut, checker.Contains, "onbridgenetwork", check.Commentf("Missing the container on network\n")) @@ -758,7 +760,7 @@ func (s *DockerSuite) TestPsListContainersFilterNetwork(c *check.C) { lines = lines[1:] //ps output should have both the containers - c.Assert(RemoveLinesForExistingElements(lines, existing), checker.HasLen, 2) + assert.Equal(c, len(RemoveLinesForExistingElements(lines, existing)), 2) // Making sure onbridgenetwork and onnonenetwork is on the output c.Assert(containerOut, checker.Contains, "onnonenetwork", check.Commentf("Missing the container on none network\n")) @@ -770,7 +772,7 @@ func (s *DockerSuite) TestPsListContainersFilterNetwork(c *check.C) { out, _ = dockerCmd(c, "ps", "--filter", "network="+nwID) containerOut = strings.TrimSpace(string(out)) - c.Assert(containerOut, checker.Contains, "onbridgenetwork") + assert.Assert(c, is.Contains(containerOut, "onbridgenetwork")) // Filter by partial network ID partialnwID := string(nwID[0:4]) @@ -784,7 +786,7 @@ func (s *DockerSuite) TestPsListContainersFilterNetwork(c *check.C) { lines = lines[1:] // ps output should have only one container - c.Assert(RemoveLinesForExistingElements(lines, existing), checker.HasLen, 1) + assert.Equal(c, len(RemoveLinesForExistingElements(lines, existing)), 1) // Making sure onbridgenetwork is on the output c.Assert(containerOut, checker.Contains, "onbridgenetwork", check.Commentf("Missing the container on network\n")) @@ -803,11 +805,11 @@ func (s *DockerSuite) TestPsByOrder(c *check.C) { // Run multiple time should have the same result out = cli.DockerCmd(c, "ps", "--no-trunc", "-q", "-f", "name=xyz").Combined() - c.Assert(strings.TrimSpace(out), checker.Equals, fmt.Sprintf("%s\n%s", container2, container1)) + assert.Equal(c, strings.TrimSpace(out), fmt.Sprintf("%s\n%s", container2, container1)) // Run multiple time should have the same result out = cli.DockerCmd(c, "ps", "--no-trunc", "-q", "-f", "name=xyz").Combined() - c.Assert(strings.TrimSpace(out), checker.Equals, fmt.Sprintf("%s\n%s", container2, container1)) + assert.Equal(c, strings.TrimSpace(out), fmt.Sprintf("%s\n%s", container2, container1)) } func (s *DockerSuite) TestPsListContainersFilterPorts(c *check.C) { @@ -833,17 +835,17 @@ func (s *DockerSuite) TestPsListContainersFilterPorts(c *check.C) { c.Assert(strings.TrimSpace(out), checker.Not(checker.Equals), id2) out, _ = dockerCmd(c, "ps", "--no-trunc", "-q", "--filter", "publish=80-81") - c.Assert(strings.TrimSpace(out), checker.Equals, id1) + assert.Equal(c, strings.TrimSpace(out), id1) c.Assert(strings.TrimSpace(out), checker.Not(checker.Equals), id2) out, _ = dockerCmd(c, "ps", "--no-trunc", "-q", "--filter", "expose=80/tcp") - c.Assert(strings.TrimSpace(out), checker.Equals, id1) + assert.Equal(c, strings.TrimSpace(out), id1) c.Assert(strings.TrimSpace(out), checker.Not(checker.Equals), id2) out, _ = dockerCmd(c, "ps", "--no-trunc", "-q", "--filter", "expose=8080/tcp") out = RemoveOutputForExistingElements(out, existingContainers) c.Assert(strings.TrimSpace(out), checker.Not(checker.Equals), id1) - c.Assert(strings.TrimSpace(out), checker.Equals, id2) + assert.Equal(c, strings.TrimSpace(out), id2) } func (s *DockerSuite) TestPsNotShowLinknamesOfDeletedContainer(c *check.C) { @@ -859,11 +861,11 @@ func (s *DockerSuite) TestPsNotShowLinknamesOfDeletedContainer(c *check.C) { expected := []string{"bbb", "aaa,bbb/aaa"} var names []string names = append(names, lines...) - c.Assert(expected, checker.DeepEquals, names, check.Commentf("Expected array with non-truncated names: %v, got: %v", expected, names)) + assert.Assert(c, is.DeepEqual(names, expected), "Expected array with non-truncated names: %v, got: %v", expected, names) dockerCmd(c, "rm", "bbb") out, _ = dockerCmd(c, "ps", "--no-trunc", "-a", "--format", "{{.Names}}") out = RemoveOutputForExistingElements(out, existingContainers) - c.Assert(strings.TrimSpace(out), checker.Equals, "aaa") + assert.Equal(c, strings.TrimSpace(out), "aaa") } diff --git a/components/engine/integration-cli/docker_cli_pull_local_test.go b/components/engine/integration-cli/docker_cli_pull_local_test.go index 33d4ae5e7c..b6b774ea44 100644 --- a/components/engine/integration-cli/docker_cli_pull_local_test.go +++ b/components/engine/integration-cli/docker_cli_pull_local_test.go @@ -17,6 +17,7 @@ import ( "github.com/docker/docker/integration-cli/cli/build" "github.com/go-check/check" "github.com/opencontainers/go-digest" + "gotest.tools/assert" "gotest.tools/icmd" ) @@ -47,7 +48,7 @@ func testPullImageWithAliases(c *check.C) { dockerCmd(c, "inspect", repos[0]) for _, repo := range repos[1:] { _, _, err := dockerCmdWithError("inspect", repo) - c.Assert(err, checker.NotNil, check.Commentf("Image %v shouldn't have been pulled down", repo)) + assert.ErrorContains(c, err, "", "Image %v shouldn't have been pulled down", repo) } } @@ -96,14 +97,14 @@ func testConcurrentPullWholeRepo(c *check.C) { // package is not goroutine-safe. for i := 0; i != numPulls; i++ { err := <-results - c.Assert(err, checker.IsNil, check.Commentf("concurrent pull failed with error: %v", err)) + assert.NilError(c, err, "concurrent pull failed with error: %v", err) } // Ensure all tags were pulled successfully for _, repo := range repos { dockerCmd(c, "inspect", repo) out, _ := dockerCmd(c, "run", "--rm", repo) - c.Assert(strings.TrimSpace(out), checker.Equals, "/bin/sh -c echo "+repo) + assert.Equal(c, strings.TrimSpace(out), "/bin/sh -c echo "+repo) } } @@ -134,7 +135,7 @@ func testConcurrentFailingPull(c *check.C) { // package is not goroutine-safe. for i := 0; i != numPulls; i++ { err := <-results - c.Assert(err, checker.NotNil, check.Commentf("expected pull to fail")) + assert.ErrorContains(c, err, "", "expected pull to fail") } } @@ -183,14 +184,14 @@ func testConcurrentPullMultipleTags(c *check.C) { // package is not goroutine-safe. for range repos { err := <-results - c.Assert(err, checker.IsNil, check.Commentf("concurrent pull failed with error: %v", err)) + assert.NilError(c, err, "concurrent pull failed with error: %v", err) } // Ensure all tags were pulled successfully for _, repo := range repos { dockerCmd(c, "inspect", repo) out, _ := dockerCmd(c, "run", "--rm", repo) - c.Assert(strings.TrimSpace(out), checker.Equals, "/bin/sh -c echo "+repo) + assert.Equal(c, strings.TrimSpace(out), "/bin/sh -c echo "+repo) } } @@ -286,7 +287,7 @@ func (s *DockerSchema1RegistrySuite) TestPullNoLayers(c *check.C) { func (s *DockerRegistrySuite) TestPullManifestList(c *check.C) { testRequires(c, NotArm) pushDigest, err := setupImage(c) - c.Assert(err, checker.IsNil, check.Commentf("error setting up image")) + assert.NilError(c, err, "error setting up image") // Inject a manifest list into the registry manifestList := &manifestlist.ManifestList{ @@ -321,7 +322,7 @@ func (s *DockerRegistrySuite) TestPullManifestList(c *check.C) { } manifestListJSON, err := json.MarshalIndent(manifestList, "", " ") - c.Assert(err, checker.IsNil, check.Commentf("error marshalling manifest list")) + assert.NilError(c, err, "error marshalling manifest list") manifestListDigest := digest.FromBytes(manifestListJSON) hexDigest := manifestListDigest.Hex() @@ -331,10 +332,10 @@ func (s *DockerRegistrySuite) TestPullManifestList(c *check.C) { // Write manifest list to blob store blobDir := filepath.Join(registryV2Path, "blobs", "sha256", hexDigest[:2], hexDigest) err = os.MkdirAll(blobDir, 0755) - c.Assert(err, checker.IsNil, check.Commentf("error creating blob dir")) + assert.NilError(c, err, "error creating blob dir") blobPath := filepath.Join(blobDir, "data") err = ioutil.WriteFile(blobPath, []byte(manifestListJSON), 0644) - c.Assert(err, checker.IsNil, check.Commentf("error writing manifest list")) + assert.NilError(c, err, "error writing manifest list") // Add to revision store revisionDir := filepath.Join(registryV2Path, "repositories", remoteRepoName, "_manifests", "revisions", "sha256", hexDigest) @@ -347,7 +348,7 @@ func (s *DockerRegistrySuite) TestPullManifestList(c *check.C) { // Update tag tagPath := filepath.Join(registryV2Path, "repositories", remoteRepoName, "_manifests", "tags", "latest", "current", "link") err = ioutil.WriteFile(tagPath, []byte(manifestListDigest.String()), 0644) - c.Assert(err, checker.IsNil, check.Commentf("error writing tag link")) + assert.NilError(c, err, "error writing tag link") // Verify that the image can be pulled through the manifest list. out, _ := dockerCmd(c, "pull", repoName) @@ -358,7 +359,7 @@ func (s *DockerRegistrySuite) TestPullManifestList(c *check.C) { pullDigest := matches[1] // Make sure the pushed and pull digests match - c.Assert(manifestListDigest.String(), checker.Equals, pullDigest) + assert.Equal(c, manifestListDigest.String(), pullDigest) // Was the image actually created? dockerCmd(c, "inspect", repoName) @@ -372,9 +373,9 @@ func (s *DockerRegistryAuthHtpasswdSuite) TestPullWithExternalAuthLoginWithSchem defer os.Setenv("PATH", osPath) workingDir, err := os.Getwd() - c.Assert(err, checker.IsNil) + assert.NilError(c, err) absolute, err := filepath.Abs(filepath.Join(workingDir, "fixtures", "auth")) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) testPath := fmt.Sprintf("%s%c%s", osPath, filepath.ListSeparator, absolute) os.Setenv("PATH", testPath) @@ -382,18 +383,18 @@ func (s *DockerRegistryAuthHtpasswdSuite) TestPullWithExternalAuthLoginWithSchem repoName := fmt.Sprintf("%v/dockercli/busybox:authtest", privateRegistryURL) tmp, err := ioutil.TempDir("", "integration-cli-") - c.Assert(err, checker.IsNil) + assert.NilError(c, err) externalAuthConfig := `{ "credsStore": "shell-test" }` configPath := filepath.Join(tmp, "config.json") err = ioutil.WriteFile(configPath, []byte(externalAuthConfig), 0644) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) dockerCmd(c, "--config", tmp, "login", "-u", s.reg.Username(), "-p", s.reg.Password(), privateRegistryURL) b, err := ioutil.ReadFile(configPath) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) c.Assert(string(b), checker.Not(checker.Contains), "\"auth\":") dockerCmd(c, "--config", tmp, "tag", "busybox", repoName) @@ -417,9 +418,9 @@ func (s *DockerRegistryAuthHtpasswdSuite) TestPullWithExternalAuth(c *check.C) { defer os.Setenv("PATH", osPath) workingDir, err := os.Getwd() - c.Assert(err, checker.IsNil) + assert.NilError(c, err) absolute, err := filepath.Abs(filepath.Join(workingDir, "fixtures", "auth")) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) testPath := fmt.Sprintf("%s%c%s", osPath, filepath.ListSeparator, absolute) os.Setenv("PATH", testPath) @@ -427,18 +428,18 @@ func (s *DockerRegistryAuthHtpasswdSuite) TestPullWithExternalAuth(c *check.C) { repoName := fmt.Sprintf("%v/dockercli/busybox:authtest", privateRegistryURL) tmp, err := ioutil.TempDir("", "integration-cli-") - c.Assert(err, checker.IsNil) + assert.NilError(c, err) externalAuthConfig := `{ "credsStore": "shell-test" }` configPath := filepath.Join(tmp, "config.json") err = ioutil.WriteFile(configPath, []byte(externalAuthConfig), 0644) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) dockerCmd(c, "--config", tmp, "login", "-u", s.reg.Username(), "-p", s.reg.Password(), privateRegistryURL) b, err := ioutil.ReadFile(configPath) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) c.Assert(string(b), checker.Not(checker.Contains), "\"auth\":") dockerCmd(c, "--config", tmp, "tag", "busybox", repoName) diff --git a/components/engine/integration-cli/docker_cli_pull_test.go b/components/engine/integration-cli/docker_cli_pull_test.go index 0e88b1e56f..dbf97568dc 100644 --- a/components/engine/integration-cli/docker_cli_pull_test.go +++ b/components/engine/integration-cli/docker_cli_pull_test.go @@ -7,9 +7,10 @@ import ( "sync" "time" - "github.com/docker/docker/integration-cli/checker" "github.com/go-check/check" "github.com/opencontainers/go-digest" + "gotest.tools/assert" + is "gotest.tools/assert/cmp" ) // TestPullFromCentralRegistry pulls an image from the central registry and verifies that the client @@ -19,21 +20,22 @@ func (s *DockerHubPullSuite) TestPullFromCentralRegistry(c *check.C) { out := s.Cmd(c, "pull", "hello-world") defer deleteImages("hello-world") - c.Assert(out, checker.Contains, "Using default tag: latest", check.Commentf("expected the 'latest' tag to be automatically assumed")) - c.Assert(out, checker.Contains, "Pulling from library/hello-world", check.Commentf("expected the 'library/' prefix to be automatically assumed")) - c.Assert(out, checker.Contains, "Downloaded newer image for hello-world:latest") + assert.Assert(c, strings.Contains(out, "Using default tag: latest"), "expected the 'latest' tag to be automatically assumed") + assert.Assert(c, strings.Contains(out, "Pulling from library/hello-world"), "expected the 'library/' prefix to be automatically assumed") + assert.Assert(c, strings.Contains(out, "Downloaded newer image for hello-world:latest")) matches := regexp.MustCompile(`Digest: (.+)\n`).FindAllStringSubmatch(out, -1) - c.Assert(len(matches), checker.Equals, 1, check.Commentf("expected exactly one image digest in the output")) - c.Assert(len(matches[0]), checker.Equals, 2, check.Commentf("unexpected number of submatches for the digest")) + assert.Equal(c, len(matches), 1, "expected exactly one image digest in the output") + assert.Equal(c, len(matches[0]), 2, "unexpected number of submatches for the digest") _, err := digest.Parse(matches[0][1]) - c.Check(err, checker.IsNil, check.Commentf("invalid digest %q in output", matches[0][1])) + assert.NilError(c, err, "invalid digest %q in output", matches[0][1]) // We should have a single entry in images. img := strings.TrimSpace(s.Cmd(c, "images")) splitImg := strings.Split(img, "\n") - c.Assert(splitImg, checker.HasLen, 2) - c.Assert(splitImg[1], checker.Matches, `hello-world\s+latest.*?`, check.Commentf("invalid output for `docker images` (expected image and tag name")) + assert.Equal(c, len(splitImg), 2) + match, _ := regexp.MatchString(`hello-world\s+latest.*?`, splitImg[1]) + assert.Assert(c, match, "invalid output for `docker images` (expected image and tag name)") } // TestPullNonExistingImage pulls non-existing images from the central registry, with different @@ -97,13 +99,13 @@ func (s *DockerHubPullSuite) TestPullNonExistingImage(c *check.C) { // Process the results (out, err). for record := range recordChan { if len(record.option) == 0 { - c.Assert(record.err, checker.NotNil, check.Commentf("expected non-zero exit status when pulling non-existing image: %s", record.out)) - c.Assert(record.out, checker.Contains, fmt.Sprintf("pull access denied for %s, repository does not exist or may require 'docker login'", record.e.repo), check.Commentf("expected image not found error messages")) + assert.ErrorContains(c, record.err, "", "expected non-zero exit status when pulling non-existing image: %s", record.out) + assert.Assert(c, strings.Contains(record.out, fmt.Sprintf("pull access denied for %s, repository does not exist or may require 'docker login'", record.e.repo)), "expected image not found error messages") } else { // pull -a on a nonexistent registry should fall back as well - c.Assert(record.err, checker.NotNil, check.Commentf("expected non-zero exit status when pulling non-existing image: %s", record.out)) - c.Assert(record.out, checker.Contains, fmt.Sprintf("pull access denied for %s, repository does not exist or may require 'docker login'", record.e.repo), check.Commentf("expected image not found error messages")) - c.Assert(record.out, checker.Not(checker.Contains), "unauthorized", check.Commentf(`message should not contain "unauthorized"`)) + assert.ErrorContains(c, record.err, "", "expected non-zero exit status when pulling non-existing image: %s", record.out) + assert.Assert(c, strings.Contains(record.out, fmt.Sprintf("pull access denied for %s, repository does not exist or may require 'docker login'", record.e.repo)), "expected image not found error messages") + assert.Assert(c, !strings.Contains(record.out, "unauthorized"), `message should not contain "unauthorized"`) } } @@ -168,7 +170,7 @@ func (s *DockerHubPullSuite) TestPullFromCentralRegistryImplicitRefParts(c *chec s.Cmd(c, "rmi", ref) s.Cmd(c, "tag", "hello-world-backup", "hello-world") } - c.Assert(out, checker.Contains, "Image is up to date for hello-world:latest") + assert.Assert(c, strings.Contains(out, "Image is up to date for hello-world:latest")) } s.Cmd(c, "rmi", "hello-world-backup") @@ -176,17 +178,18 @@ func (s *DockerHubPullSuite) TestPullFromCentralRegistryImplicitRefParts(c *chec // We should have a single entry in images. img := strings.TrimSpace(s.Cmd(c, "images")) splitImg := strings.Split(img, "\n") - c.Assert(splitImg, checker.HasLen, 2) - c.Assert(splitImg[1], checker.Matches, `hello-world\s+latest.*?`, check.Commentf("invalid output for `docker images` (expected image and tag name")) + assert.Equal(c, len(splitImg), 2) + match, _ := regexp.MatchString(`hello-world\s+latest.*?`, splitImg[1]) + assert.Assert(c, match, "invalid output for `docker images` (expected image and tag name)") } // TestPullScratchNotAllowed verifies that pulling 'scratch' is rejected. func (s *DockerHubPullSuite) TestPullScratchNotAllowed(c *check.C) { testRequires(c, DaemonIsLinux) out, err := s.CmdWithError("pull", "scratch") - c.Assert(err, checker.NotNil, check.Commentf("expected pull of scratch to fail")) - c.Assert(out, checker.Contains, "'scratch' is a reserved name") - c.Assert(out, checker.Not(checker.Contains), "Pulling repository scratch") + assert.ErrorContains(c, err, "", "expected pull of scratch to fail") + assert.Assert(c, strings.Contains(out, "'scratch' is a reserved name")) + assert.Assert(c, !strings.Contains(out, "Pulling repository scratch")) } // TestPullAllTagsFromCentralRegistry pulls using `all-tags` for a given image and verifies that it @@ -196,12 +199,12 @@ func (s *DockerHubPullSuite) TestPullAllTagsFromCentralRegistry(c *check.C) { s.Cmd(c, "pull", "dockercore/engine-pull-all-test-fixture") outImageCmd := s.Cmd(c, "images", "dockercore/engine-pull-all-test-fixture") splitOutImageCmd := strings.Split(strings.TrimSpace(outImageCmd), "\n") - c.Assert(splitOutImageCmd, checker.HasLen, 2) + assert.Equal(c, len(splitOutImageCmd), 2) s.Cmd(c, "pull", "--all-tags=true", "dockercore/engine-pull-all-test-fixture") outImageAllTagCmd := s.Cmd(c, "images", "dockercore/engine-pull-all-test-fixture") linesCount := strings.Count(outImageAllTagCmd, "\n") - c.Assert(linesCount, checker.GreaterThan, 2, check.Commentf("pulling all tags should provide more than two images, got %s", outImageAllTagCmd)) + assert.Assert(c, linesCount > 2, "pulling all tags should provide more than two images, got %s", outImageAllTagCmd) // Verify that the line for 'dockercore/engine-pull-all-test-fixture:latest' is left unchanged. var latestLine string @@ -211,7 +214,7 @@ func (s *DockerHubPullSuite) TestPullAllTagsFromCentralRegistry(c *check.C) { break } } - c.Assert(latestLine, checker.Not(checker.Equals), "", check.Commentf("no entry for dockercore/engine-pull-all-test-fixture:latest found after pulling all tags")) + assert.Assert(c, latestLine != "", "no entry for dockercore/engine-pull-all-test-fixture:latest found after pulling all tags") splitLatest := strings.Fields(latestLine) splitCurrent := strings.Fields(splitOutImageCmd[1]) @@ -228,7 +231,7 @@ func (s *DockerHubPullSuite) TestPullAllTagsFromCentralRegistry(c *check.C) { splitCurrent[4] = "" splitCurrent[5] = "" - c.Assert(splitLatest, checker.DeepEquals, splitCurrent, check.Commentf("dockercore/engine-pull-all-test-fixture:latest was changed after pulling all tags")) + assert.Assert(c, is.DeepEqual(splitLatest, splitCurrent), "dockercore/engine-pull-all-test-fixture:latest was changed after pulling all tags") } // TestPullClientDisconnect kills the client during a pull operation and verifies that the operation @@ -241,34 +244,34 @@ func (s *DockerHubPullSuite) TestPullClientDisconnect(c *check.C) { pullCmd := s.MakeCmd("pull", repoName) stdout, err := pullCmd.StdoutPipe() - c.Assert(err, checker.IsNil) + assert.NilError(c, err) err = pullCmd.Start() - c.Assert(err, checker.IsNil) + assert.NilError(c, err) go pullCmd.Wait() // Cancel as soon as we get some output. buf := make([]byte, 10) _, err = stdout.Read(buf) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) err = pullCmd.Process.Kill() - c.Assert(err, checker.IsNil) + assert.NilError(c, err) time.Sleep(2 * time.Second) _, err = s.CmdWithError("inspect", repoName) - c.Assert(err, checker.NotNil, check.Commentf("image was pulled after client disconnected")) + assert.ErrorContains(c, err, "", "image was pulled after client disconnected") } // Regression test for https://github.com/docker/docker/issues/26429 func (s *DockerSuite) TestPullLinuxImageFailsOnWindows(c *check.C) { testRequires(c, DaemonIsWindows, Network) _, _, err := dockerCmdWithError("pull", "ubuntu") - c.Assert(err.Error(), checker.Contains, "no matching manifest") + assert.ErrorContains(c, err, "no matching manifest") } // Regression test for https://github.com/docker/docker/issues/28892 func (s *DockerSuite) TestPullWindowsImageFailsOnLinux(c *check.C) { testRequires(c, DaemonIsLinux, Network) _, _, err := dockerCmdWithError("pull", "microsoft/nanoserver") - c.Assert(err.Error(), checker.Contains, "cannot be used on this platform") + assert.ErrorContains(c, err, "cannot be used on this platform") } diff --git a/components/engine/integration-cli/docker_cli_push_test.go b/components/engine/integration-cli/docker_cli_push_test.go index 0f0df1ab24..ebef8493ef 100644 --- a/components/engine/integration-cli/docker_cli_push_test.go +++ b/components/engine/integration-cli/docker_cli_push_test.go @@ -11,9 +11,9 @@ import ( "sync" "github.com/docker/distribution/reference" - "github.com/docker/docker/integration-cli/checker" "github.com/docker/docker/integration-cli/cli/build" "github.com/go-check/check" + "gotest.tools/assert" "gotest.tools/icmd" ) @@ -37,7 +37,7 @@ func (s *DockerSchema1RegistrySuite) TestPushBusyboxImage(c *check.C) { // pushing an image without a prefix should throw an error func (s *DockerSuite) TestPushUnprefixedRepo(c *check.C) { out, _, err := dockerCmdWithError("push", "busybox") - c.Assert(err, check.NotNil, check.Commentf("pushing an unprefixed repo didn't result in a non-zero exit status: %s", out)) + assert.ErrorContains(c, err, "", "pushing an unprefixed repo didn't result in a non-zero exit status: %s", out) } func testPushUntagged(c *check.C) { @@ -45,8 +45,8 @@ func testPushUntagged(c *check.C) { expected := "An image does not exist locally with the tag" out, _, err := dockerCmdWithError("push", repoName) - c.Assert(err, check.NotNil, check.Commentf("pushing the image to the private registry should have failed: output %q", out)) - c.Assert(out, checker.Contains, expected, check.Commentf("pushing the image failed")) + assert.ErrorContains(c, err, "", "pushing the image to the private registry should have failed: output %q", out) + assert.Assert(c, strings.Contains(out, expected), "pushing the image failed") } func (s *DockerRegistrySuite) TestPushUntagged(c *check.C) { @@ -62,8 +62,8 @@ func testPushBadTag(c *check.C) { expected := "does not exist" out, _, err := dockerCmdWithError("push", repoName) - c.Assert(err, check.NotNil, check.Commentf("pushing the image to the private registry should have failed: output %q", out)) - c.Assert(out, checker.Contains, expected, check.Commentf("pushing the image failed")) + assert.ErrorContains(c, err, "", "pushing the image to the private registry should have failed: output %q", out) + assert.Assert(c, strings.Contains(out, expected), "pushing the image failed") } func (s *DockerRegistrySuite) TestPushBadTag(c *check.C) { @@ -104,10 +104,10 @@ func testPushMultipleTags(c *check.C) { out1Lines = append(out1Lines, outputLine) } } - c.Assert(out2Lines, checker.HasLen, len(out1Lines)) + assert.Equal(c, len(out2Lines), len(out1Lines)) for i := range out1Lines { - c.Assert(out1Lines[i], checker.Equals, out2Lines[i]) + assert.Equal(c, out1Lines[i], out2Lines[i]) } } @@ -122,14 +122,14 @@ func (s *DockerSchema1RegistrySuite) TestPushMultipleTags(c *check.C) { func testPushEmptyLayer(c *check.C) { repoName := fmt.Sprintf("%v/dockercli/emptylayer", privateRegistryURL) emptyTarball, err := ioutil.TempFile("", "empty_tarball") - c.Assert(err, check.IsNil, check.Commentf("Unable to create test file")) + assert.NilError(c, err, "Unable to create test file") tw := tar.NewWriter(emptyTarball) err = tw.Close() - c.Assert(err, check.IsNil, check.Commentf("Error creating empty tarball")) + assert.NilError(c, err, "Error creating empty tarball") freader, err := os.Open(emptyTarball.Name()) - c.Assert(err, check.IsNil, check.Commentf("Could not open test tarball")) + assert.NilError(c, err, "Could not open test tarball") defer freader.Close() icmd.RunCmd(icmd.Cmd{ @@ -139,7 +139,7 @@ func testPushEmptyLayer(c *check.C) { // Now verify we can push it out, _, err := dockerCmdWithError("push", repoName) - c.Assert(err, check.IsNil, check.Commentf("pushing the image to the private registry has failed: %s", out)) + assert.NilError(c, err, "pushing the image to the private registry has failed: %s", out) } func (s *DockerRegistrySuite) TestPushEmptyLayer(c *check.C) { @@ -180,7 +180,7 @@ func testConcurrentPush(c *check.C) { for range repos { err := <-results - c.Assert(err, checker.IsNil, check.Commentf("concurrent push failed with error: %v", err)) + assert.NilError(c, err, "concurrent push failed with error: %v", err) } // Clear local images store. @@ -192,7 +192,7 @@ func testConcurrentPush(c *check.C) { dockerCmd(c, "pull", repo) dockerCmd(c, "inspect", repo) out, _ := dockerCmd(c, "run", "--rm", repo) - c.Assert(strings.TrimSpace(out), checker.Equals, "/bin/sh -c echo "+repo) + assert.Equal(c, strings.TrimSpace(out), "/bin/sh -c echo "+repo) } } @@ -210,39 +210,40 @@ func (s *DockerRegistrySuite) TestCrossRepositoryLayerPush(c *check.C) { dockerCmd(c, "tag", "busybox", sourceRepoName) // push the image to the registry out1, _, err := dockerCmdWithError("push", sourceRepoName) - c.Assert(err, check.IsNil, check.Commentf("pushing the image to the private registry has failed: %s", out1)) + assert.NilError(c, err, "pushing the image to the private registry has failed: %s", out1) // ensure that none of the layers were mounted from another repository during push - c.Assert(strings.Contains(out1, "Mounted from"), check.Equals, false) + assert.Assert(c, !strings.Contains(out1, "Mounted from")) digest1 := reference.DigestRegexp.FindString(out1) - c.Assert(len(digest1), checker.GreaterThan, 0, check.Commentf("no digest found for pushed manifest")) + assert.Assert(c, len(digest1) > 0, "no digest found for pushed manifest") destRepoName := fmt.Sprintf("%v/dockercli/crossrepopush", privateRegistryURL) // retag the image to upload the same layers to another repo in the same registry dockerCmd(c, "tag", "busybox", destRepoName) // push the image to the registry out2, _, err := dockerCmdWithError("push", destRepoName) - c.Assert(err, check.IsNil, check.Commentf("pushing the image to the private registry has failed: %s", out2)) + assert.NilError(c, err, "pushing the image to the private registry has failed: %s", out2) + // ensure that layers were mounted from the first repo during push - c.Assert(strings.Contains(out2, "Mounted from dockercli/busybox"), check.Equals, true) + assert.Assert(c, strings.Contains(out2, "Mounted from dockercli/busybox")) digest2 := reference.DigestRegexp.FindString(out2) - c.Assert(len(digest2), checker.GreaterThan, 0, check.Commentf("no digest found for pushed manifest")) - c.Assert(digest1, check.Equals, digest2) + assert.Assert(c, len(digest2) > 0, "no digest found for pushed manifest") + assert.Equal(c, digest1, digest2) // ensure that pushing again produces the same digest out3, _, err := dockerCmdWithError("push", destRepoName) - c.Assert(err, check.IsNil, check.Commentf("pushing the image to the private registry has failed: %s", out2)) + assert.NilError(c, err, "pushing the image to the private registry has failed: %s", out3) digest3 := reference.DigestRegexp.FindString(out3) - c.Assert(len(digest2), checker.GreaterThan, 0, check.Commentf("no digest found for pushed manifest")) - c.Assert(digest3, check.Equals, digest2) + assert.Assert(c, len(digest3) > 0, "no digest found for pushed manifest") + 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") - c.Assert(out4, check.Equals, "hello world") + assert.Equal(c, out4, "hello world") } func (s *DockerSchema1RegistrySuite) TestCrossRepositoryLayerPushNotSupported(c *check.C) { @@ -282,9 +283,9 @@ func (s *DockerRegistryAuthHtpasswdSuite) TestPushNoCredentialsNoRetry(c *check. repoName := fmt.Sprintf("%s/busybox", privateRegistryURL) dockerCmd(c, "tag", "busybox", repoName) out, _, err := dockerCmdWithError("push", repoName) - c.Assert(err, check.NotNil, check.Commentf("%s", out)) - c.Assert(out, check.Not(checker.Contains), "Retrying") - c.Assert(out, checker.Contains, "no basic auth credentials") + assert.ErrorContains(c, err, "", out) + assert.Assert(c, !strings.Contains(out, "Retrying")) + assert.Assert(c, strings.Contains(out, "no basic auth credentials")) } // This may be flaky but it's needed not to regress on unauthorized push, see #21054 @@ -293,8 +294,8 @@ func (s *DockerSuite) TestPushToCentralRegistryUnauthorized(c *check.C) { repoName := "test/busybox" dockerCmd(c, "tag", "busybox", repoName) out, _, err := dockerCmdWithError("push", repoName) - c.Assert(err, check.NotNil, check.Commentf("%s", out)) - c.Assert(out, check.Not(checker.Contains), "Retrying") + assert.ErrorContains(c, err, "", out) + assert.Assert(c, !strings.Contains(out, "Retrying")) } func getTestTokenService(status int, body string, retries int) *httptest.Server { @@ -322,9 +323,9 @@ func (s *DockerRegistryAuthTokenSuite) TestPushTokenServiceUnauthResponse(c *che repoName := fmt.Sprintf("%s/busybox", privateRegistryURL) dockerCmd(c, "tag", "busybox", repoName) out, _, err := dockerCmdWithError("push", repoName) - c.Assert(err, check.NotNil, check.Commentf("%s", out)) - c.Assert(out, checker.Not(checker.Contains), "Retrying") - c.Assert(out, checker.Contains, "unauthorized: a message") + assert.ErrorContains(c, err, "", out) + assert.Assert(c, !strings.Contains(out, "Retrying")) + assert.Assert(c, strings.Contains(out, "unauthorized: a message")) } func (s *DockerRegistryAuthTokenSuite) TestPushMisconfiguredTokenServiceResponseUnauthorized(c *check.C) { @@ -334,10 +335,10 @@ func (s *DockerRegistryAuthTokenSuite) TestPushMisconfiguredTokenServiceResponse repoName := fmt.Sprintf("%s/busybox", privateRegistryURL) dockerCmd(c, "tag", "busybox", repoName) out, _, err := dockerCmdWithError("push", repoName) - c.Assert(err, check.NotNil, check.Commentf("%s", out)) - c.Assert(out, checker.Not(checker.Contains), "Retrying") + assert.ErrorContains(c, err, "", out) + assert.Assert(c, !strings.Contains(out, "Retrying")) split := strings.Split(out, "\n") - c.Assert(split[len(split)-2], check.Equals, "unauthorized: authentication required") + assert.Equal(c, split[len(split)-2], "unauthorized: authentication required") } func (s *DockerRegistryAuthTokenSuite) TestPushMisconfiguredTokenServiceResponseError(c *check.C) { @@ -347,12 +348,12 @@ func (s *DockerRegistryAuthTokenSuite) TestPushMisconfiguredTokenServiceResponse repoName := fmt.Sprintf("%s/busybox", privateRegistryURL) dockerCmd(c, "tag", "busybox", repoName) out, _, err := dockerCmdWithError("push", repoName) - c.Assert(err, check.NotNil, check.Commentf("%s", out)) + assert.ErrorContains(c, err, "", out) // TODO: isolate test so that it can be guaranteed that the 503 will trigger xfer retries - //c.Assert(out, checker.Contains, "Retrying") - //c.Assert(out, checker.Not(checker.Contains), "Retrying in 15") + //assert.Assert(c, strings.Contains(out, "Retrying")) + //assert.Assert(c, !strings.Contains(out, "Retrying in 15")) split := strings.Split(out, "\n") - c.Assert(split[len(split)-2], check.Equals, "toomanyrequests: out of tokens") + assert.Equal(c, split[len(split)-2], "toomanyrequests: out of tokens") } func (s *DockerRegistryAuthTokenSuite) TestPushMisconfiguredTokenServiceResponseUnparsable(c *check.C) { @@ -362,10 +363,10 @@ func (s *DockerRegistryAuthTokenSuite) TestPushMisconfiguredTokenServiceResponse repoName := fmt.Sprintf("%s/busybox", privateRegistryURL) dockerCmd(c, "tag", "busybox", repoName) out, _, err := dockerCmdWithError("push", repoName) - c.Assert(err, check.NotNil, check.Commentf("%s", out)) - c.Assert(out, checker.Not(checker.Contains), "Retrying") + assert.ErrorContains(c, err, "", out) + assert.Assert(c, !strings.Contains(out, "Retrying")) split := strings.Split(out, "\n") - c.Assert(split[len(split)-2], checker.Contains, "error parsing HTTP 403 response body: ") + assert.Assert(c, strings.Contains(split[len(split)-2], "error parsing HTTP 403 response body: ")) } func (s *DockerRegistryAuthTokenSuite) TestPushMisconfiguredTokenServiceResponseNoToken(c *check.C) { @@ -375,8 +376,8 @@ func (s *DockerRegistryAuthTokenSuite) TestPushMisconfiguredTokenServiceResponse repoName := fmt.Sprintf("%s/busybox", privateRegistryURL) dockerCmd(c, "tag", "busybox", repoName) out, _, err := dockerCmdWithError("push", repoName) - c.Assert(err, check.NotNil, check.Commentf("%s", out)) - c.Assert(out, checker.Not(checker.Contains), "Retrying") + assert.ErrorContains(c, err, "", out) + assert.Assert(c, !strings.Contains(out, "Retrying")) split := strings.Split(out, "\n") - c.Assert(split[len(split)-2], check.Equals, "authorization server did not include a token in the response") + assert.Equal(c, split[len(split)-2], "authorization server did not include a token in the response") } diff --git a/components/engine/integration-cli/docker_cli_registry_user_agent_test.go b/components/engine/integration-cli/docker_cli_registry_user_agent_test.go index 7ee3c3d1ba..90f7c8e7c3 100644 --- a/components/engine/integration-cli/docker_cli_registry_user_agent_test.go +++ b/components/engine/integration-cli/docker_cli_registry_user_agent_test.go @@ -9,6 +9,7 @@ import ( "github.com/docker/docker/internal/test/registry" "github.com/go-check/check" + "gotest.tools/assert" ) // unescapeBackslashSemicolonParens unescapes \;() @@ -32,21 +33,21 @@ func regexpCheckUA(c *check.C, ua string) { re := regexp.MustCompile("(?P.+) UpstreamClient(?P.+)") substrArr := re.FindStringSubmatch(ua) - c.Assert(substrArr, check.HasLen, 3, check.Commentf("Expected 'UpstreamClient()' with upstream client UA")) + assert.Equal(c, len(substrArr), 3, "Expected 'UpstreamClient()' with upstream client UA") dockerUA := substrArr[1] upstreamUAEscaped := substrArr[2] // check dockerUA looks correct reDockerUA := regexp.MustCompile("^docker/[0-9A-Za-z+]") bMatchDockerUA := reDockerUA.MatchString(dockerUA) - c.Assert(bMatchDockerUA, check.Equals, true, check.Commentf("Docker Engine User-Agent malformed")) + assert.Assert(c, bMatchDockerUA, "Docker Engine User-Agent malformed") // check upstreamUA looks correct // Expecting something like: Docker-Client/1.11.0-dev (linux) upstreamUA := unescapeBackslashSemicolonParens(upstreamUAEscaped) reUpstreamUA := regexp.MustCompile("^\\(Docker-Client/[0-9A-Za-z+]") bMatchUpstreamUA := reUpstreamUA.MatchString(upstreamUA) - c.Assert(bMatchUpstreamUA, check.Equals, true, check.Commentf("(Upstream) Docker Client User-Agent malformed")) + assert.Assert(c, bMatchUpstreamUA, "(Upstream) Docker Client User-Agent malformed") } // registerUserAgentHandler registers a handler for the `/v2/*` endpoint. @@ -75,18 +76,18 @@ func (s *DockerRegistrySuite) TestUserAgentPassThrough(c *check.C) { reg, err := registry.NewMock(c) defer reg.Close() - c.Assert(err, check.IsNil) + assert.NilError(c, err) registerUserAgentHandler(reg, &ua) repoName := fmt.Sprintf("%s/busybox", reg.URL()) s.d.StartWithBusybox(c, "--insecure-registry", reg.URL()) tmp, err := ioutil.TempDir("", "integration-cli-") - c.Assert(err, check.IsNil) + assert.NilError(c, err) defer os.RemoveAll(tmp) dockerfile, err := makefile(tmp, fmt.Sprintf("FROM %s", repoName)) - c.Assert(err, check.IsNil, check.Commentf("Unable to create test dockerfile")) + assert.NilError(c, err, "Unable to create test dockerfile") s.d.Cmd("build", "--file", dockerfile, tmp) regexpCheckUA(c, ua) diff --git a/components/engine/integration-cli/docker_cli_restart_test.go b/components/engine/integration-cli/docker_cli_restart_test.go index 7df6981709..48f1754093 100644 --- a/components/engine/integration-cli/docker_cli_restart_test.go +++ b/components/engine/integration-cli/docker_cli_restart_test.go @@ -8,6 +8,8 @@ import ( "github.com/docker/docker/integration-cli/checker" "github.com/go-check/check" + "gotest.tools/assert" + is "gotest.tools/assert/cmp" ) func (s *DockerSuite) TestRestartStoppedContainer(c *check.C) { @@ -15,16 +17,16 @@ func (s *DockerSuite) TestRestartStoppedContainer(c *check.C) { cleanedContainerID := getIDByName(c, "test") out, _ := dockerCmd(c, "logs", cleanedContainerID) - c.Assert(out, checker.Equals, "foobar\n") + assert.Equal(c, out, "foobar\n") dockerCmd(c, "restart", cleanedContainerID) // Wait until the container has stopped err := waitInspect(cleanedContainerID, "{{.State.Running}}", "false", 20*time.Second) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) out, _ = dockerCmd(c, "logs", cleanedContainerID) - c.Assert(out, checker.Equals, "foobar\nfoobar\n") + assert.Equal(c, out, "foobar\nfoobar\n") } func (s *DockerSuite) TestRestartRunningContainer(c *check.C) { @@ -32,7 +34,7 @@ func (s *DockerSuite) TestRestartRunningContainer(c *check.C) { cleanedContainerID := strings.TrimSpace(out) - c.Assert(waitRun(cleanedContainerID), checker.IsNil) + assert.NilError(c, waitRun(cleanedContainerID)) getLogs := func(c *check.C) (interface{}, check.CommentInterface) { out, _ := dockerCmd(c, "logs", cleanedContainerID) @@ -43,7 +45,7 @@ func (s *DockerSuite) TestRestartRunningContainer(c *check.C) { waitAndAssert(c, 10*time.Second, getLogs, checker.Equals, "foobar\n") dockerCmd(c, "restart", "-t", "1", cleanedContainerID) - c.Assert(waitRun(cleanedContainerID), checker.IsNil) + assert.NilError(c, waitRun(cleanedContainerID)) // Wait 10 seconds for first 'echo' appear (again) in the logs waitAndAssert(c, 10*time.Second, getLogs, checker.Equals, "foobar\nfoobar\n") @@ -56,23 +58,23 @@ func (s *DockerSuite) TestRestartWithVolumes(c *check.C) { cleanedContainerID := strings.TrimSpace(out) out, err := inspectFilter(cleanedContainerID, "len .Mounts") - c.Assert(err, check.IsNil, check.Commentf("failed to inspect %s: %s", cleanedContainerID, out)) + assert.NilError(c, err, "failed to inspect %s: %s", cleanedContainerID, out) out = strings.Trim(out, " \n\r") - c.Assert(out, checker.Equals, "1") + assert.Equal(c, out, "1") source, err := inspectMountSourceField(cleanedContainerID, prefix+slash+"test") - c.Assert(err, checker.IsNil) + assert.NilError(c, err) dockerCmd(c, "restart", cleanedContainerID) out, err = inspectFilter(cleanedContainerID, "len .Mounts") - c.Assert(err, check.IsNil, check.Commentf("failed to inspect %s: %s", cleanedContainerID, out)) + assert.NilError(c, err, "failed to inspect %s: %s", cleanedContainerID, out) out = strings.Trim(out, " \n\r") - c.Assert(out, checker.Equals, "1") + assert.Equal(c, out, "1") sourceAfterRestart, err := inspectMountSourceField(cleanedContainerID, prefix+slash+"test") - c.Assert(err, checker.IsNil) - c.Assert(source, checker.Equals, sourceAfterRestart) + assert.NilError(c, err) + assert.Equal(c, source, sourceAfterRestart) } func (s *DockerSuite) TestRestartDisconnectedContainer(c *check.C) { @@ -81,15 +83,15 @@ func (s *DockerSuite) TestRestartDisconnectedContainer(c *check.C) { // Run a container on the default bridge network out, _ := dockerCmd(c, "run", "-d", "--name", "c0", "busybox", "top") cleanedContainerID := strings.TrimSpace(out) - c.Assert(waitRun(cleanedContainerID), checker.IsNil) + assert.NilError(c, waitRun(cleanedContainerID)) // Disconnect the container from the network - out, err := dockerCmd(c, "network", "disconnect", "bridge", "c0") - c.Assert(err, check.NotNil, check.Commentf("%s", out)) + out, exitCode := dockerCmd(c, "network", "disconnect", "bridge", "c0") + assert.Assert(c, exitCode == 0, out) // Restart the container - dockerCmd(c, "restart", "c0") - c.Assert(err, check.NotNil, check.Commentf("%s", out)) + out, exitCode = dockerCmd(c, "restart", "c0") + assert.Assert(c, exitCode == 0, out) } func (s *DockerSuite) TestRestartPolicyNO(c *check.C) { @@ -97,7 +99,7 @@ func (s *DockerSuite) TestRestartPolicyNO(c *check.C) { id := strings.TrimSpace(string(out)) name := inspectField(c, id, "HostConfig.RestartPolicy.Name") - c.Assert(name, checker.Equals, "no") + assert.Equal(c, name, "no") } func (s *DockerSuite) TestRestartPolicyAlways(c *check.C) { @@ -105,18 +107,18 @@ func (s *DockerSuite) TestRestartPolicyAlways(c *check.C) { id := strings.TrimSpace(string(out)) name := inspectField(c, id, "HostConfig.RestartPolicy.Name") - c.Assert(name, checker.Equals, "always") + assert.Equal(c, name, "always") MaximumRetryCount := inspectField(c, id, "HostConfig.RestartPolicy.MaximumRetryCount") // MaximumRetryCount=0 if the restart policy is always - c.Assert(MaximumRetryCount, checker.Equals, "0") + assert.Equal(c, MaximumRetryCount, "0") } func (s *DockerSuite) TestRestartPolicyOnFailure(c *check.C) { out, _, err := dockerCmdWithError("create", "--restart=on-failure:-1", "busybox") - c.Assert(err, check.NotNil, check.Commentf("%s", out)) - c.Assert(out, checker.Contains, "maximum retry count cannot be negative") + 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") @@ -124,8 +126,8 @@ func (s *DockerSuite) TestRestartPolicyOnFailure(c *check.C) { name := inspectField(c, id, "HostConfig.RestartPolicy.Name") maxRetry := inspectField(c, id, "HostConfig.RestartPolicy.MaximumRetryCount") - c.Assert(name, checker.Equals, "on-failure") - c.Assert(maxRetry, checker.Equals, "1") + assert.Equal(c, name, "on-failure") + assert.Equal(c, maxRetry, "1") out, _ = dockerCmd(c, "create", "--restart=on-failure:0", "busybox") @@ -133,8 +135,8 @@ func (s *DockerSuite) TestRestartPolicyOnFailure(c *check.C) { name = inspectField(c, id, "HostConfig.RestartPolicy.Name") maxRetry = inspectField(c, id, "HostConfig.RestartPolicy.MaximumRetryCount") - c.Assert(name, checker.Equals, "on-failure") - c.Assert(maxRetry, checker.Equals, "0") + assert.Equal(c, name, "on-failure") + assert.Equal(c, maxRetry, "0") out, _ = dockerCmd(c, "create", "--restart=on-failure", "busybox") @@ -142,8 +144,8 @@ func (s *DockerSuite) TestRestartPolicyOnFailure(c *check.C) { name = inspectField(c, id, "HostConfig.RestartPolicy.Name") maxRetry = inspectField(c, id, "HostConfig.RestartPolicy.MaximumRetryCount") - c.Assert(name, checker.Equals, "on-failure") - c.Assert(maxRetry, checker.Equals, "0") + assert.Equal(c, name, "on-failure") + assert.Equal(c, maxRetry, "0") } // a good container with --restart=on-failure:3 @@ -153,14 +155,13 @@ func (s *DockerSuite) TestRestartContainerwithGoodContainer(c *check.C) { id := strings.TrimSpace(string(out)) err := waitInspect(id, "{{ .State.Restarting }} {{ .State.Running }}", "false false", 30*time.Second) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) count := inspectField(c, id, "RestartCount") - c.Assert(count, checker.Equals, "0") + assert.Equal(c, count, "0") MaximumRetryCount := inspectField(c, id, "HostConfig.RestartPolicy.MaximumRetryCount") - c.Assert(MaximumRetryCount, checker.Equals, "3") - + assert.Equal(c, MaximumRetryCount, "3") } func (s *DockerSuite) TestRestartContainerSuccess(c *check.C) { @@ -168,25 +169,25 @@ func (s *DockerSuite) TestRestartContainerSuccess(c *check.C) { out := runSleepingContainer(c, "-d", "--restart=always") id := strings.TrimSpace(out) - c.Assert(waitRun(id), check.IsNil) + assert.NilError(c, waitRun(id)) pidStr := inspectField(c, id, "State.Pid") pid, err := strconv.Atoi(pidStr) - c.Assert(err, check.IsNil) + assert.NilError(c, err) p, err := os.FindProcess(pid) - c.Assert(err, check.IsNil) - c.Assert(p, check.NotNil) + assert.NilError(c, err) + assert.Assert(c, p != nil) err = p.Kill() - c.Assert(err, check.IsNil) + assert.NilError(c, err) err = waitInspect(id, "{{.RestartCount}}", "1", 30*time.Second) - c.Assert(err, check.IsNil) + assert.NilError(c, err) err = waitInspect(id, "{{.State.Status}}", "running", 30*time.Second) - c.Assert(err, check.IsNil) + assert.NilError(c, err) } func (s *DockerSuite) TestRestartWithPolicyUserDefinedNetwork(c *check.C) { @@ -195,42 +196,42 @@ func (s *DockerSuite) TestRestartWithPolicyUserDefinedNetwork(c *check.C) { dockerCmd(c, "network", "create", "-d", "bridge", "udNet") dockerCmd(c, "run", "-d", "--net=udNet", "--name=first", "busybox", "top") - c.Assert(waitRun("first"), check.IsNil) + assert.NilError(c, waitRun("first")) dockerCmd(c, "run", "-d", "--restart=always", "--net=udNet", "--name=second", "--link=first:foo", "busybox", "top") - c.Assert(waitRun("second"), check.IsNil) + assert.NilError(c, waitRun("second")) // ping to first and its alias foo must succeed _, _, err := dockerCmdWithError("exec", "second", "ping", "-c", "1", "first") - c.Assert(err, check.IsNil) + assert.NilError(c, err) _, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "foo") - c.Assert(err, check.IsNil) + assert.NilError(c, err) // Now kill the second container and let the restart policy kick in pidStr := inspectField(c, "second", "State.Pid") pid, err := strconv.Atoi(pidStr) - c.Assert(err, check.IsNil) + assert.NilError(c, err) p, err := os.FindProcess(pid) - c.Assert(err, check.IsNil) - c.Assert(p, check.NotNil) + assert.NilError(c, err) + assert.Assert(c, p != nil) err = p.Kill() - c.Assert(err, check.IsNil) + assert.NilError(c, err) err = waitInspect("second", "{{.RestartCount}}", "1", 5*time.Second) - c.Assert(err, check.IsNil) + assert.NilError(c, err) err = waitInspect("second", "{{.State.Status}}", "running", 5*time.Second) - c.Assert(err, check.IsNil) + assert.NilError(c, err) // ping to first and its alias foo must still succeed _, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "first") - c.Assert(err, check.IsNil) + assert.NilError(c, err) _, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "foo") - c.Assert(err, check.IsNil) + assert.NilError(c, err) } func (s *DockerSuite) TestRestartPolicyAfterRestart(c *check.C) { @@ -238,29 +239,29 @@ func (s *DockerSuite) TestRestartPolicyAfterRestart(c *check.C) { out := runSleepingContainer(c, "-d", "--restart=always") id := strings.TrimSpace(out) - c.Assert(waitRun(id), check.IsNil) + assert.NilError(c, waitRun(id)) dockerCmd(c, "restart", id) - c.Assert(waitRun(id), check.IsNil) + assert.NilError(c, waitRun(id)) pidStr := inspectField(c, id, "State.Pid") pid, err := strconv.Atoi(pidStr) - c.Assert(err, check.IsNil) + assert.NilError(c, err) p, err := os.FindProcess(pid) - c.Assert(err, check.IsNil) - c.Assert(p, check.NotNil) + assert.NilError(c, err) + assert.Assert(c, p != nil) err = p.Kill() - c.Assert(err, check.IsNil) + assert.NilError(c, err) err = waitInspect(id, "{{.RestartCount}}", "1", 30*time.Second) - c.Assert(err, check.IsNil) + assert.NilError(c, err) err = waitInspect(id, "{{.State.Status}}", "running", 30*time.Second) - c.Assert(err, check.IsNil) + assert.NilError(c, err) } func (s *DockerSuite) TestRestartContainerwithRestartPolicy(c *check.C) { @@ -274,7 +275,7 @@ func (s *DockerSuite) TestRestartContainerwithRestartPolicy(c *check.C) { waitTimeout = 150 * time.Second } err := waitInspect(id1, "{{ .State.Restarting }} {{ .State.Running }}", "false false", waitTimeout) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) dockerCmd(c, "restart", id1) dockerCmd(c, "restart", id2) @@ -289,9 +290,9 @@ func (s *DockerSuite) TestRestartContainerwithRestartPolicy(c *check.C) { dockerCmd(c, "kill", id1) dockerCmd(c, "kill", id2) err = waitInspect(id1, "{{ .State.Restarting }} {{ .State.Running }}", "false false", waitTimeout) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) err = waitInspect(id2, "{{ .State.Restarting }} {{ .State.Running }}", "false false", waitTimeout) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) } func (s *DockerSuite) TestRestartAutoRemoveContainer(c *check.C) { @@ -300,10 +301,10 @@ func (s *DockerSuite) TestRestartAutoRemoveContainer(c *check.C) { id := strings.TrimSpace(string(out)) dockerCmd(c, "restart", id) err := waitInspect(id, "{{ .State.Restarting }} {{ .State.Running }}", "false true", 15*time.Second) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) out, _ = dockerCmd(c, "ps") - c.Assert(out, checker.Contains, id[:12], check.Commentf("container should be restarted instead of removed: %v", out)) + 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) diff --git a/components/engine/integration-cli/docker_cli_rmi_test.go b/components/engine/integration-cli/docker_cli_rmi_test.go index 6622856823..d1445cf73f 100644 --- a/components/engine/integration-cli/docker_cli_rmi_test.go +++ b/components/engine/integration-cli/docker_cli_rmi_test.go @@ -10,6 +10,7 @@ import ( "github.com/docker/docker/integration-cli/cli/build" "github.com/docker/docker/pkg/stringid" "github.com/go-check/check" + "gotest.tools/assert" "gotest.tools/icmd" ) @@ -24,7 +25,7 @@ func (s *DockerSuite) TestRmiWithContainerFails(c *check.C) { // try to delete the image out, _, err := dockerCmdWithError("rmi", "busybox") // Container is using image, should not be able to rmi - c.Assert(err, checker.NotNil) + assert.ErrorContains(c, err, "") // Container is using image, error message should contain errSubstr c.Assert(out, checker.Contains, errSubstr, check.Commentf("Container: %q", cleanedContainerID)) @@ -152,7 +153,7 @@ func (s *DockerSuite) TestRmiImageIDForceWithRunningContainersAndMultipleTags(c out, _, err := dockerCmdWithError("rmi", "-f", imgID) // rmi -f should not delete image with running containers - c.Assert(err, checker.NotNil) + assert.ErrorContains(c, err, "") c.Assert(out, checker.Contains, "(cannot be forced) - image is being used by running container") } @@ -217,7 +218,7 @@ func (s *DockerSuite) TestRmiForceWithMultipleRepositories(c *check.C) { func (s *DockerSuite) TestRmiBlank(c *check.C) { out, _, err := dockerCmdWithError("rmi", " ") // Should have failed to delete ' ' image - c.Assert(err, checker.NotNil) + assert.ErrorContains(c, err, "") // Wrong error message generated c.Assert(out, checker.Not(checker.Contains), "no such id", check.Commentf("out: %s", out)) // Expected error message not generated @@ -245,7 +246,7 @@ func (s *DockerSuite) TestRmiContainerImageNotFound(c *check.C) { // Try to remove the image of the running container and see if it fails as expected. out, _, err := dockerCmdWithError("rmi", "-f", imageIds[0]) // The image of the running container should not be removed. - c.Assert(err, checker.NotNil) + assert.ErrorContains(c, err, "") c.Assert(out, checker.Contains, "image is being used by running container", check.Commentf("out: %s", out)) } @@ -284,7 +285,7 @@ RUN echo 2 #layer2 // Try to untag "tmp2" without the -f flag. out, _, err := dockerCmdWithError("rmi", newTag) // should not be untagged without the -f flag - c.Assert(err, checker.NotNil) + assert.ErrorContains(c, err, "") c.Assert(out, checker.Contains, cid[:12]) c.Assert(out, checker.Contains, "(must force)") @@ -301,7 +302,7 @@ func (*DockerSuite) TestRmiParentImageFail(c *check.C) { id := inspectField(c, "busybox", "ID") out, _, err := dockerCmdWithError("rmi", id) - c.Assert(err, check.NotNil) + assert.ErrorContains(c, err, "") if !strings.Contains(out, "image has dependent child images") { c.Fatalf("rmi should have failed because it's a parent image, got %s", out) } @@ -330,7 +331,7 @@ func (s *DockerSuite) TestRmiByIDHardConflict(c *check.C) { imgID := inspectField(c, "busybox:latest", "Id") _, _, err := dockerCmdWithError("rmi", imgID[:12]) - c.Assert(err, checker.NotNil) + assert.ErrorContains(c, err, "") // check that tag was not removed imgID2 := inspectField(c, "busybox:latest", "Id") diff --git a/components/engine/integration-cli/docker_cli_run_test.go b/components/engine/integration-cli/docker_cli_run_test.go index 2a95853a43..02b4ff9ac0 100644 --- a/components/engine/integration-cli/docker_cli_run_test.go +++ b/components/engine/integration-cli/docker_cli_run_test.go @@ -36,6 +36,7 @@ import ( "github.com/docker/libnetwork/resolvconf" "github.com/docker/libnetwork/types" "github.com/go-check/check" + "gotest.tools/assert" "gotest.tools/icmd" ) @@ -89,8 +90,8 @@ func (s *DockerSuite) TestRunExitCodeZero(c *check.C) { // the exit code should be 1 func (s *DockerSuite) TestRunExitCodeOne(c *check.C) { _, exitCode, err := dockerCmdWithError("run", "busybox", "false") - c.Assert(err, checker.NotNil) - c.Assert(exitCode, checker.Equals, 1) + assert.ErrorContains(c, err, "") + assert.Equal(c, exitCode, 1) } // it should be possible to pipe in data via stdin to a process running in a container @@ -220,15 +221,15 @@ func (s *DockerSuite) TestUserDefinedNetworkLinks(c *check.C) { // ping to first and its alias foo must succeed _, _, err := dockerCmdWithError("exec", "second", "ping", "-c", "1", "first") - c.Assert(err, check.IsNil) + assert.NilError(c, err) _, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "foo") - c.Assert(err, check.IsNil) + assert.NilError(c, err) // ping to third and its alias must fail _, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "third") - c.Assert(err, check.NotNil) + assert.ErrorContains(c, err, "") _, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "bar") - c.Assert(err, check.NotNil) + assert.ErrorContains(c, err, "") // start third container now dockerCmd(c, "run", "-d", "--net=udlinkNet", "--name=third", "busybox", "top") @@ -236,9 +237,9 @@ func (s *DockerSuite) TestUserDefinedNetworkLinks(c *check.C) { // ping to third and its alias must succeed now _, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "third") - c.Assert(err, check.IsNil) + assert.NilError(c, err) _, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "bar") - c.Assert(err, check.IsNil) + assert.NilError(c, err) } func (s *DockerSuite) TestUserDefinedNetworkLinksWithRestart(c *check.C) { @@ -254,9 +255,9 @@ func (s *DockerSuite) TestUserDefinedNetworkLinksWithRestart(c *check.C) { // ping to first and its alias foo must succeed _, _, err := dockerCmdWithError("exec", "second", "ping", "-c", "1", "first") - c.Assert(err, check.IsNil) + assert.NilError(c, err) _, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "foo") - c.Assert(err, check.IsNil) + assert.NilError(c, err) // Restart first container dockerCmd(c, "restart", "first") @@ -264,9 +265,9 @@ func (s *DockerSuite) TestUserDefinedNetworkLinksWithRestart(c *check.C) { // ping to first and its alias foo must still succeed _, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "first") - c.Assert(err, check.IsNil) + assert.NilError(c, err) _, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "foo") - c.Assert(err, check.IsNil) + assert.NilError(c, err) // Restart second container dockerCmd(c, "restart", "second") @@ -274,9 +275,9 @@ func (s *DockerSuite) TestUserDefinedNetworkLinksWithRestart(c *check.C) { // ping to first and its alias foo must still succeed _, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "first") - c.Assert(err, check.IsNil) + assert.NilError(c, err) _, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "foo") - c.Assert(err, check.IsNil) + assert.NilError(c, err) } func (s *DockerSuite) TestRunWithNetAliasOnDefaultNetworks(c *check.C) { @@ -285,7 +286,7 @@ func (s *DockerSuite) TestRunWithNetAliasOnDefaultNetworks(c *check.C) { defaults := []string{"bridge", "host", "none"} for _, net := range defaults { out, _, err := dockerCmdWithError("run", "-d", "--net", net, "--net-alias", "alias_"+net, "busybox", "top") - c.Assert(err, checker.NotNil) + assert.ErrorContains(c, err, "") c.Assert(out, checker.Contains, runconfig.ErrUnsupportedNetworkAndAlias.Error()) } } @@ -312,14 +313,14 @@ func (s *DockerSuite) TestUserDefinedNetworkAlias(c *check.C) { // ping to first and its network-scoped aliases _, _, err := dockerCmdWithError("exec", "second", "ping", "-c", "1", "first") - c.Assert(err, check.IsNil) + assert.NilError(c, err) _, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "foo1") - c.Assert(err, check.IsNil) + assert.NilError(c, err) _, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "foo2") - c.Assert(err, check.IsNil) + assert.NilError(c, err) // ping first container's short-id alias _, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", stringid.TruncateID(cid1)) - c.Assert(err, check.IsNil) + assert.NilError(c, err) // Restart first container dockerCmd(c, "restart", "first") @@ -327,20 +328,20 @@ func (s *DockerSuite) TestUserDefinedNetworkAlias(c *check.C) { // ping to first and its network-scoped aliases must succeed _, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "first") - c.Assert(err, check.IsNil) + assert.NilError(c, err) _, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "foo1") - c.Assert(err, check.IsNil) + assert.NilError(c, err) _, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", "foo2") - c.Assert(err, check.IsNil) + assert.NilError(c, err) // ping first container's short-id alias _, _, err = dockerCmdWithError("exec", "second", "ping", "-c", "1", stringid.TruncateID(cid1)) - c.Assert(err, check.IsNil) + assert.NilError(c, err) } // Issue 9677. func (s *DockerSuite) TestRunWithDaemonFlags(c *check.C) { out, _, err := dockerCmdWithError("--exec-opt", "foo=bar", "run", "-i", "busybox", "true") - c.Assert(err, checker.NotNil) + assert.ErrorContains(c, err, "") c.Assert(out, checker.Contains, "unknown flag: --exec-opt") } @@ -623,7 +624,7 @@ func (s *DockerSuite) TestRunCreateVolumeWithSymlink(c *check.C) { // Cannot run on Windows as relies on Linux-specific functionality (sh -c mount...) testRequires(c, DaemonIsLinux) workingDirectory, err := ioutil.TempDir("", "TestRunCreateVolumeWithSymlink") - c.Assert(err, checker.IsNil) + assert.NilError(c, err) image := "docker-test-createvolumewithsymlink" buildCmd := exec.Command(dockerBinary, "build", "-t", image, "-") @@ -641,7 +642,7 @@ func (s *DockerSuite) TestRunCreateVolumeWithSymlink(c *check.C) { } volPath, err := inspectMountSourceField("test-createvolumewithsymlink", "/bar/foo") - c.Assert(err, checker.IsNil) + assert.NilError(c, err) _, exitCode, err = dockerCmdWithError("rm", "-v", "test-createvolumewithsymlink") if err != nil || exitCode != 0 { @@ -661,7 +662,7 @@ func (s *DockerSuite) TestRunVolumesFromSymlinkPath(c *check.C) { testRequires(c, DaemonIsLinux) workingDirectory, err := ioutil.TempDir("", "TestRunVolumesFromSymlinkPath") - c.Assert(err, checker.IsNil) + assert.NilError(c, err) name := "docker-test-volumesfromsymlinkpath" prefix := "" dfContents := `FROM busybox @@ -810,7 +811,7 @@ func (s *DockerSuite) TestRunTwoConcurrentContainers(c *check.C) { close(errChan) for err := range errChan { - c.Assert(err, check.IsNil) + assert.NilError(c, err) } } @@ -1776,7 +1777,7 @@ func (s *DockerSuite) TestRunExitOnStdinClose(c *check.C) { }() select { case err := <-finish: - c.Assert(err, check.IsNil) + assert.NilError(c, err) case <-time.After(time.Duration(delay) * time.Second): c.Fatal("docker run failed to exit on stdin close") } @@ -1795,7 +1796,7 @@ func (s *DockerSuite) TestRunInteractiveWithRestartPolicy(c *check.C) { Command: []string{dockerBinary, "run", "-i", "--name", name, "--restart=always", "busybox", "sh"}, Stdin: bytes.NewBufferString("exit 11"), }) - c.Assert(result.Error, checker.IsNil) + assert.NilError(c, result.Error) defer func() { dockerCmdWithResult("stop", name).Assert(c, icmd.Success) }() @@ -2222,7 +2223,7 @@ func (s *DockerSuite) TestRunVolumesCleanPaths(c *check.C) { } out, err = inspectMountSourceField("dark_helmet", prefix+slash+`foo`) - c.Assert(err, check.IsNil) + assert.NilError(c, err) if !strings.Contains(strings.ToLower(out), strings.ToLower(testEnv.PlatformDefaults.VolumesConfigPath)) { c.Fatalf("Volume was not defined for %s/foo\n%q", prefix, out) } @@ -2233,7 +2234,7 @@ func (s *DockerSuite) TestRunVolumesCleanPaths(c *check.C) { } out, err = inspectMountSourceField("dark_helmet", prefix+slash+"bar") - c.Assert(err, check.IsNil) + assert.NilError(c, err) if !strings.Contains(strings.ToLower(out), strings.ToLower(testEnv.PlatformDefaults.VolumesConfigPath)) { c.Fatalf("Volume was not defined for %s/bar\n%q", prefix, out) } @@ -2396,7 +2397,7 @@ func (s *DockerSuite) TestRunMountShmMqueueFromHost(c *check.C) { defer os.Remove("/dev/mqueue/toto") defer os.Remove("/dev/shm/test") volPath, err := inspectMountSourceField("shmfromhost", "/dev/shm") - c.Assert(err, checker.IsNil) + assert.NilError(c, err) if volPath != "/dev/shm" { c.Fatalf("volumePath should have been /dev/shm, was %s", volPath) } @@ -2418,7 +2419,7 @@ func (s *DockerSuite) TestContainerNetworkMode(c *check.C) { out, _ := dockerCmd(c, "run", "-d", "busybox", "top") id := strings.TrimSpace(out) - c.Assert(waitRun(id), check.IsNil) + assert.NilError(c, waitRun(id)) pid1 := inspectField(c, id, "State.Pid") parentContainerNet, err := os.Readlink(fmt.Sprintf("/proc/%s/ns/net", pid1)) @@ -2554,7 +2555,7 @@ func (s *DockerSuite) TestRunTTYWithPipe(c *check.C) { select { case err := <-errChan: - c.Assert(err, check.IsNil) + assert.NilError(c, err) case <-time.After(30 * time.Second): c.Fatal("container is running but should have failed") } @@ -2638,7 +2639,7 @@ func (s *DockerSuite) TestRunAllowPortRangeThroughPublish(c *check.C) { var ports nat.PortMap err := json.Unmarshal([]byte(portstr), &ports) - c.Assert(err, checker.IsNil, check.Commentf("failed to unmarshal: %v", portstr)) + assert.NilError(c, err, "failed to unmarshal: %v", portstr) for port, binding := range ports { portnum, _ := strconv.Atoi(strings.Split(string(port), "/")[0]) if portnum < 3000 || portnum > 3003 { @@ -2716,11 +2717,11 @@ func (s *DockerSuite) TestPermissionsPtsReadonlyRootfs(c *check.C) { func testReadOnlyFile(c *check.C, testPriv bool, filenames ...string) { touch := "touch " + strings.Join(filenames, " ") out, _, err := dockerCmdWithError("run", "--read-only", "--rm", "busybox", "sh", "-c", touch) - c.Assert(err, checker.NotNil) + assert.ErrorContains(c, err, "") for _, f := range filenames { expected := "touch: " + f + ": Read-only file system" - c.Assert(out, checker.Contains, expected) + assert.Assert(c, strings.Contains(out, expected)) } if !testPriv { @@ -2728,11 +2729,11 @@ func testReadOnlyFile(c *check.C, testPriv bool, filenames ...string) { } out, _, err = dockerCmdWithError("run", "--read-only", "--privileged", "--rm", "busybox", "sh", "-c", touch) - c.Assert(err, checker.NotNil) + assert.ErrorContains(c, err, "") for _, f := range filenames { expected := "touch: " + f + ": Read-only file system" - c.Assert(out, checker.Contains, expected) + assert.Assert(c, strings.Contains(out, expected)) } } @@ -2825,7 +2826,7 @@ func (s *DockerSuite) TestRunPIDHostWithChildIsKillable(c *check.C) { }() select { case err := <-errchan: - c.Assert(err, check.IsNil) + assert.NilError(c, err) case <-time.After(5 * time.Second): c.Fatal("Kill container timed out") } @@ -3031,14 +3032,14 @@ func (s *DockerSuite) TestVolumeFromMixedRWOptions(c *check.C) { if testEnv.OSType != "windows" { mRO, err := inspectMountPoint("test-volumes-1", prefix+slash+"test") - c.Assert(err, checker.IsNil, check.Commentf("failed to inspect mount point")) + assert.NilError(c, err, "failed to inspect mount point") if mRO.RW { c.Fatalf("Expected RO volume was RW") } } mRW, err := inspectMountPoint("test-volumes-2", prefix+slash+"test") - c.Assert(err, checker.IsNil, check.Commentf("failed to inspect mount point")) + assert.NilError(c, err, "failed to inspect mount point") if !mRW.RW { c.Fatalf("Expected RW volume was RO") } @@ -3152,7 +3153,7 @@ func (s *DockerSuite) TestPtraceContainerProcsFromHost(c *check.C) { out, _ := dockerCmd(c, "run", "-d", "busybox", "top") id := strings.TrimSpace(out) - c.Assert(waitRun(id), check.IsNil) + assert.NilError(c, waitRun(id)) pid1 := inspectField(c, id, "State.Pid") _, err := os.Readlink(fmt.Sprintf("/proc/%s/ns/net", pid1)) @@ -3501,18 +3502,18 @@ func (s *DockerSuite) TestContainersNetworkIsolation(c *check.C) { // Check Isolation between containers : ping must fail _, _, err := dockerCmdWithError("exec", "first", "ping", "-c", "1", "second") - c.Assert(err, check.NotNil) + assert.ErrorContains(c, err, "") // Connect first container to testnetwork2 dockerCmd(c, "network", "connect", "testnetwork2", "first") // ping must succeed now _, _, err = dockerCmdWithError("exec", "first", "ping", "-c", "1", "second") - c.Assert(err, check.IsNil) + assert.NilError(c, err) // Disconnect first container from testnetwork2 dockerCmd(c, "network", "disconnect", "testnetwork2", "first") // ping must fail again _, _, err = dockerCmdWithError("exec", "first", "ping", "-c", "1", "second") - c.Assert(err, check.NotNil) + assert.ErrorContains(c, err, "") } func (s *DockerSuite) TestNetworkRmWithActiveContainers(c *check.C) { @@ -3526,11 +3527,11 @@ func (s *DockerSuite) TestNetworkRmWithActiveContainers(c *check.C) { c.Assert(waitRun("second"), check.IsNil) // Network delete with active containers must fail _, _, err := dockerCmdWithError("network", "rm", "testnetwork1") - c.Assert(err, check.NotNil) + assert.ErrorContains(c, err, "") dockerCmd(c, "stop", "first") _, _, err = dockerCmdWithError("network", "rm", "testnetwork1") - c.Assert(err, check.NotNil) + assert.ErrorContains(c, err, "") } func (s *DockerSuite) TestContainerRestartInMultipleNetworks(c *check.C) { @@ -3555,9 +3556,9 @@ func (s *DockerSuite) TestContainerRestartInMultipleNetworks(c *check.C) { // Stop second container and test ping failures on both networks dockerCmd(c, "stop", "second") _, _, err := dockerCmdWithError("exec", "first", "ping", "-c", "1", "second.testnetwork1") - c.Assert(err, check.NotNil) + assert.ErrorContains(c, err, "") _, _, err = dockerCmdWithError("exec", "first", "ping", "-c", "1", "second.testnetwork2") - c.Assert(err, check.NotNil) + assert.ErrorContains(c, err, "") // Start second container and connectivity must be restored on both networks dockerCmd(c, "start", "second") @@ -3576,7 +3577,7 @@ func (s *DockerSuite) TestContainerWithConflictingHostNetworks(c *check.C) { // Connecting to the user defined network must fail _, _, err := dockerCmdWithError("network", "connect", "testnetwork1", "first") - c.Assert(err, check.NotNil) + assert.ErrorContains(c, err, "") } func (s *DockerSuite) TestContainerWithConflictingSharedNetwork(c *check.C) { @@ -3592,7 +3593,7 @@ func (s *DockerSuite) TestContainerWithConflictingSharedNetwork(c *check.C) { // Connecting to the user defined network must fail out, _, err := dockerCmdWithError("network", "connect", "testnetwork1", "second") - c.Assert(err, check.NotNil) + assert.ErrorContains(c, err, "") c.Assert(out, checker.Contains, runconfig.ErrConflictSharedNetwork.Error()) } @@ -3606,7 +3607,7 @@ func (s *DockerSuite) TestContainerWithConflictingNoneNetwork(c *check.C) { // Connecting to the user defined network must fail out, _, err := dockerCmdWithError("network", "connect", "testnetwork1", "first") - c.Assert(err, check.NotNil) + assert.ErrorContains(c, err, "") c.Assert(out, checker.Contains, runconfig.ErrConflictNoNetwork.Error()) // create a container connected to testnetwork1 @@ -3615,14 +3616,14 @@ func (s *DockerSuite) TestContainerWithConflictingNoneNetwork(c *check.C) { // Connect second container to none network. it must fail as well _, _, err = dockerCmdWithError("network", "connect", "none", "second") - c.Assert(err, check.NotNil) + assert.ErrorContains(c, err, "") } // #11957 - stdin with no tty does not exit if stdin is not closed even though container exited func (s *DockerSuite) TestRunStdinBlockedAfterContainerExit(c *check.C) { cmd := exec.Command(dockerBinary, "run", "-i", "--name=test", "busybox", "true") in, err := cmd.StdinPipe() - c.Assert(err, check.IsNil) + assert.NilError(c, err) defer in.Close() stdout := bytes.NewBuffer(nil) cmd.Stdout = stdout @@ -3646,7 +3647,7 @@ func (s *DockerSuite) TestRunWrongCpusetCpusFlagValue(c *check.C) { // TODO Windows: This needs validation (error out) in the daemon. testRequires(c, DaemonIsLinux) out, exitCode, err := dockerCmdWithError("run", "--cpuset-cpus", "1-10,11--", "busybox", "true") - c.Assert(err, check.NotNil) + assert.ErrorContains(c, err, "") expected := "Error response from daemon: Invalid value 1-10,11-- for cpuset cpus.\n" if !(strings.Contains(out, expected) || exitCode == 125) { c.Fatalf("Expected output to contain %q with exitCode 125, got out: %q exitCode: %v", expected, out, exitCode) @@ -3657,7 +3658,7 @@ func (s *DockerSuite) TestRunWrongCpusetMemsFlagValue(c *check.C) { // TODO Windows: This needs validation (error out) in the daemon. testRequires(c, DaemonIsLinux) out, exitCode, err := dockerCmdWithError("run", "--cpuset-mems", "1-42--", "busybox", "true") - c.Assert(err, check.NotNil) + assert.ErrorContains(c, err, "") expected := "Error response from daemon: Invalid value 1-42-- for cpuset mems.\n" if !(strings.Contains(out, expected) || exitCode == 125) { c.Fatalf("Expected output to contain %q with exitCode 125, got out: %q exitCode: %v", expected, out, exitCode) @@ -3760,13 +3761,13 @@ func (s *DockerSuite) TestRunWithOomScoreAdjInvalidRange(c *check.C) { testRequires(c, DaemonIsLinux) out, _, err := dockerCmdWithError("run", "--oom-score-adj", "1001", "busybox", "true") - c.Assert(err, check.NotNil) + assert.ErrorContains(c, err, "") expected := "Invalid value 1001, range for oom score adj is [-1000, 1000]." if !strings.Contains(out, expected) { c.Fatalf("Expected output to contain %q, got %q instead", expected, out) } out, _, err = dockerCmdWithError("run", "--oom-score-adj", "-1001", "busybox", "true") - c.Assert(err, check.NotNil) + assert.ErrorContains(c, err, "") expected = "Invalid value -1001, range for oom score adj is [-1000, 1000]." if !strings.Contains(out, expected) { c.Fatalf("Expected output to contain %q, got %q instead", expected, out) @@ -3882,13 +3883,13 @@ func (s *DockerSuite) TestRunNamedVolumeNotRemoved(c *check.C) { dockerCmd(c, "run", "--rm", "-v", "test:"+prefix+"/foo", "-v", prefix+"/bar", "busybox", "true") dockerCmd(c, "volume", "inspect", "test") out, _ := dockerCmd(c, "volume", "ls", "-q") - c.Assert(strings.TrimSpace(out), checker.Contains, "test") + assert.Assert(c, strings.Contains(out, "test")) dockerCmd(c, "run", "--name=test", "-v", "test:"+prefix+"/foo", "-v", prefix+"/bar", "busybox", "true") dockerCmd(c, "rm", "-fv", "test") dockerCmd(c, "volume", "inspect", "test") out, _ = dockerCmd(c, "volume", "ls", "-q") - c.Assert(strings.TrimSpace(out), checker.Contains, "test") + assert.Assert(c, strings.Contains(out, "test")) } func (s *DockerSuite) TestRunNamedVolumesFromNotRemoved(c *check.C) { @@ -3899,11 +3900,11 @@ func (s *DockerSuite) TestRunNamedVolumesFromNotRemoved(c *check.C) { dockerCmd(c, "run", "--name=child", "--volumes-from=parent", "busybox", "true") cli, err := client.NewClientWithOpts(client.FromEnv) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) defer cli.Close() container, err := cli.ContainerInspect(context.Background(), strings.TrimSpace(cid)) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) var vname string for _, v := range container.Mounts { if v.Name != "test" { @@ -3918,7 +3919,7 @@ func (s *DockerSuite) TestRunNamedVolumesFromNotRemoved(c *check.C) { dockerCmd(c, "rm", "-fv", "child") dockerCmd(c, "volume", "inspect", "test") out, _ := dockerCmd(c, "volume", "ls", "-q") - c.Assert(strings.TrimSpace(out), checker.Contains, "test") + assert.Assert(c, strings.Contains(out, "test")) c.Assert(strings.TrimSpace(out), checker.Not(checker.Contains), vname) } @@ -3930,7 +3931,7 @@ func (s *DockerSuite) TestRunAttachFailedNoLeak(c *check.C) { // otherwise report build 9200. if runtime.GOOS == "windows" { v, err := kernel.GetKernelVersion() - c.Assert(err, checker.IsNil) + assert.NilError(c, err) build, _ := strconv.Atoi(strings.Split(strings.SplitN(v.String(), " ", 3)[2][1:], ".")[0]) if build == 16299 { c.Skip("Temporarily disabled on RS3 builds") @@ -3938,7 +3939,7 @@ func (s *DockerSuite) TestRunAttachFailedNoLeak(c *check.C) { } nroutines, err := getGoroutineNumber() - c.Assert(err, checker.IsNil) + assert.NilError(c, err) runSleepingContainer(c, "--name=test", "-p", "8000:8000") @@ -3968,7 +3969,7 @@ func (s *DockerSuite) TestRunVolumeWithOneCharacter(c *check.C) { testRequires(c, DaemonIsLinux) out, _ := dockerCmd(c, "run", "-v", "/tmp/q:/foo", "busybox", "sh", "-c", "find /foo") - c.Assert(strings.TrimSpace(out), checker.Equals, "/foo") + assert.Equal(c, strings.TrimSpace(out), "/foo") } func (s *DockerSuite) TestRunVolumeCopyFlag(c *check.C) { @@ -3980,29 +3981,29 @@ func (s *DockerSuite) TestRunVolumeCopyFlag(c *check.C) { // test with the nocopy flag out, _, err := dockerCmdWithError("run", "-v", "test:/foo:nocopy", "volumecopy") - c.Assert(err, checker.NotNil, check.Commentf("%s", out)) + assert.ErrorContains(c, err, "", out) // test default behavior which is to copy for non-binds out, _ = dockerCmd(c, "run", "-v", "test:/foo", "volumecopy") - c.Assert(strings.TrimSpace(out), checker.Equals, "hello") + assert.Equal(c, strings.TrimSpace(out), "hello") // error out when the volume is already populated out, _, err = dockerCmdWithError("run", "-v", "test:/foo:copy", "volumecopy") - c.Assert(err, checker.NotNil, check.Commentf("%s", out)) + assert.ErrorContains(c, err, "", out) // do not error out when copy isn't explicitly set even though it's already populated out, _ = dockerCmd(c, "run", "-v", "test:/foo", "volumecopy") - c.Assert(strings.TrimSpace(out), checker.Equals, "hello") + assert.Equal(c, strings.TrimSpace(out), "hello") // do not allow copy modes on volumes-from dockerCmd(c, "run", "--name=test", "-v", "/foo", "busybox", "true") out, _, err = dockerCmdWithError("run", "--volumes-from=test:copy", "busybox", "true") - c.Assert(err, checker.NotNil, check.Commentf("%s", out)) + assert.ErrorContains(c, err, "", out) out, _, err = dockerCmdWithError("run", "--volumes-from=test:nocopy", "busybox", "true") - c.Assert(err, checker.NotNil, check.Commentf("%s", out)) + assert.ErrorContains(c, err, "", out) // do not allow copy modes on binds out, _, err = dockerCmdWithError("run", "-v", "/foo:/bar:copy", "busybox", "true") - c.Assert(err, checker.NotNil, check.Commentf("%s", out)) + assert.ErrorContains(c, err, "", out) out, _, err = dockerCmdWithError("run", "-v", "/foo:/bar:nocopy", "busybox", "true") - c.Assert(err, checker.NotNil, check.Commentf("%s", out)) + assert.ErrorContains(c, err, "", out) } // Test case for #21976 @@ -4054,7 +4055,7 @@ func (s *DockerSuite) TestRunRmAndWait(c *check.C) { out, code, err := dockerCmdWithError("wait", "test") c.Assert(err, checker.IsNil, check.Commentf("out: %s; exit code: %d", out, code)) - c.Assert(out, checker.Equals, "2\n", check.Commentf("exit code: %d", code)) + assert.Equal(c, out, "2\n", "exit code: %d", code) c.Assert(code, checker.Equals, 0) } @@ -4117,29 +4118,29 @@ func (s *DockerDaemonSuite) TestRunWithUlimitAndDaemonDefault(c *check.C) { name := "test-A" _, err := s.d.Cmd("run", "--name", name, "-d", "busybox", "top") - c.Assert(err, checker.IsNil) - c.Assert(s.d.WaitRun(name), check.IsNil) + assert.NilError(c, err) + assert.NilError(c, s.d.WaitRun(name)) out, err := s.d.Cmd("inspect", "--format", "{{.HostConfig.Ulimits}}", name) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) c.Assert(out, checker.Contains, "[nofile=65535:65535]") name = "test-B" _, err = s.d.Cmd("run", "--name", name, "--ulimit=nofile=42", "-d", "busybox", "top") - c.Assert(err, checker.IsNil) - c.Assert(s.d.WaitRun(name), check.IsNil) + assert.NilError(c, err) + assert.NilError(c, s.d.WaitRun(name)) out, err = s.d.Cmd("inspect", "--format", "{{.HostConfig.Ulimits}}", name) - c.Assert(err, checker.IsNil) - c.Assert(out, checker.Contains, "[nofile=42:42]") + assert.NilError(c, err) + assert.Assert(c, strings.Contains(out, "[nofile=42:42]")) } func (s *DockerSuite) TestRunStoppedLoggingDriverNoLeak(c *check.C) { nroutines, err := getGoroutineNumber() - c.Assert(err, checker.IsNil) + assert.NilError(c, err) out, _, err := dockerCmdWithError("run", "--name=fail", "--log-driver=splunk", "busybox", "true") - c.Assert(err, checker.NotNil) + assert.ErrorContains(c, err, "") c.Assert(out, checker.Contains, "failed to initialize logging driver", check.Commentf("error should be about logging driver, got output %s", out)) // NGoroutines is not updated right away, so we need to wait before failing @@ -4179,7 +4180,7 @@ func (s *DockerSuite) TestRunDuplicateMount(c *check.C) { testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux, NotUserNamespace) tmpFile, err := ioutil.TempFile("", "touch-me") - c.Assert(err, checker.IsNil) + assert.NilError(c, err) defer tmpFile.Close() data := "touch-me-foo-bar\n" @@ -4200,30 +4201,30 @@ func (s *DockerSuite) TestRunWindowsWithCPUCount(c *check.C) { testRequires(c, DaemonIsWindows) out, _ := dockerCmd(c, "run", "--cpu-count=1", "--name", "test", "busybox", "echo", "testing") - c.Assert(strings.TrimSpace(out), checker.Equals, "testing") + assert.Equal(c, strings.TrimSpace(out), "testing") out = inspectField(c, "test", "HostConfig.CPUCount") - c.Assert(out, check.Equals, "1") + assert.Equal(c, out, "1") } func (s *DockerSuite) TestRunWindowsWithCPUShares(c *check.C) { testRequires(c, DaemonIsWindows) out, _ := dockerCmd(c, "run", "--cpu-shares=1000", "--name", "test", "busybox", "echo", "testing") - c.Assert(strings.TrimSpace(out), checker.Equals, "testing") + assert.Equal(c, strings.TrimSpace(out), "testing") out = inspectField(c, "test", "HostConfig.CPUShares") - c.Assert(out, check.Equals, "1000") + assert.Equal(c, out, "1000") } func (s *DockerSuite) TestRunWindowsWithCPUPercent(c *check.C) { testRequires(c, DaemonIsWindows) out, _ := dockerCmd(c, "run", "--cpu-percent=80", "--name", "test", "busybox", "echo", "testing") - c.Assert(strings.TrimSpace(out), checker.Equals, "testing") + assert.Equal(c, strings.TrimSpace(out), "testing") out = inspectField(c, "test", "HostConfig.CPUPercent") - c.Assert(out, check.Equals, "80") + assert.Equal(c, out, "80") } func (s *DockerSuite) TestRunProcessIsolationWithCPUCountCPUSharesAndCPUPercent(c *check.C) { @@ -4235,13 +4236,13 @@ func (s *DockerSuite) TestRunProcessIsolationWithCPUCountCPUSharesAndCPUPercent( c.Assert(strings.TrimSpace(out), checker.Contains, "testing") out = inspectField(c, "test", "HostConfig.CPUCount") - c.Assert(out, check.Equals, "1") + assert.Equal(c, out, "1") out = inspectField(c, "test", "HostConfig.CPUShares") - c.Assert(out, check.Equals, "0") + assert.Equal(c, out, "0") out = inspectField(c, "test", "HostConfig.CPUPercent") - c.Assert(out, check.Equals, "0") + assert.Equal(c, out, "0") } func (s *DockerSuite) TestRunHypervIsolationWithCPUCountCPUSharesAndCPUPercent(c *check.C) { @@ -4251,13 +4252,13 @@ func (s *DockerSuite) TestRunHypervIsolationWithCPUCountCPUSharesAndCPUPercent(c c.Assert(strings.TrimSpace(out), checker.Contains, "testing") out = inspectField(c, "test", "HostConfig.CPUCount") - c.Assert(out, check.Equals, "1") + assert.Equal(c, out, "1") out = inspectField(c, "test", "HostConfig.CPUShares") - c.Assert(out, check.Equals, "1000") + assert.Equal(c, out, "1000") out = inspectField(c, "test", "HostConfig.CPUPercent") - c.Assert(out, check.Equals, "80") + assert.Equal(c, out, "80") } // Test for #25099 @@ -4267,16 +4268,16 @@ func (s *DockerSuite) TestRunEmptyEnv(c *check.C) { expectedOutput := "invalid environment variable:" out, _, err := dockerCmdWithError("run", "-e", "", "busybox", "true") - c.Assert(err, checker.NotNil) - c.Assert(out, checker.Contains, expectedOutput) + assert.ErrorContains(c, err, "") + assert.Assert(c, strings.Contains(out, expectedOutput)) out, _, err = dockerCmdWithError("run", "-e", "=", "busybox", "true") - c.Assert(err, checker.NotNil) - c.Assert(out, checker.Contains, expectedOutput) + assert.ErrorContains(c, err, "") + assert.Assert(c, strings.Contains(out, expectedOutput)) out, _, err = dockerCmdWithError("run", "-e", "=foo", "busybox", "true") - c.Assert(err, checker.NotNil) - c.Assert(out, checker.Contains, expectedOutput) + assert.ErrorContains(c, err, "") + assert.Assert(c, strings.Contains(out, expectedOutput)) } // #28658 @@ -4298,7 +4299,7 @@ func (s *DockerSuite) TestSlowStdinClosing(c *check.C) { case <-time.After(30 * time.Second): c.Fatal("running container timed out") // cleanup in teardown case err := <-done: - c.Assert(err, checker.IsNil) + assert.NilError(c, err) } } } @@ -4314,12 +4315,12 @@ func (s *delayedReader) Read([]byte) (int, error) { func (s *DockerSuite) TestRunMountReadOnlyDevShm(c *check.C) { testRequires(c, testEnv.IsLocalDaemon, DaemonIsLinux, NotUserNamespace) emptyDir, err := ioutil.TempDir("", "test-read-only-dev-shm") - c.Assert(err, check.IsNil) + assert.NilError(c, err) defer os.RemoveAll(emptyDir) out, _, err := dockerCmdWithError("run", "--rm", "--read-only", "-v", fmt.Sprintf("%s:/dev/shm:ro", emptyDir), "busybox", "touch", "/dev/shm/foo") - c.Assert(err, checker.NotNil, check.Commentf("%s", out)) + assert.ErrorContains(c, err, "", out) c.Assert(out, checker.Contains, "Read-only file system") } @@ -4508,7 +4509,7 @@ func (s *DockerSuite) TestRunHostnameFQDN(c *check.C) { expectedOutput := "foobar.example.com\nfoobar.example.com\nfoobar\nexample.com\nfoobar.example.com" out, _ := dockerCmd(c, "run", "--hostname=foobar.example.com", "busybox", "sh", "-c", `cat /etc/hostname && hostname && hostname -s && hostname -d && hostname -f`) - c.Assert(strings.TrimSpace(out), checker.Equals, expectedOutput) + assert.Equal(c, strings.TrimSpace(out), expectedOutput) out, _ = dockerCmd(c, "run", "--hostname=foobar.example.com", "busybox", "sh", "-c", `cat /etc/hosts`) expectedOutput = "foobar.example.com foobar" @@ -4521,7 +4522,7 @@ func (s *DockerSuite) TestRunHostnameInHostMode(c *check.C) { expectedOutput := "foobar\nfoobar" out, _ := dockerCmd(c, "run", "--net=host", "--hostname=foobar", "busybox", "sh", "-c", `echo $HOSTNAME && hostname`) - c.Assert(strings.TrimSpace(out), checker.Equals, expectedOutput) + assert.Equal(c, strings.TrimSpace(out), expectedOutput) } func (s *DockerSuite) TestRunAddDeviceCgroupRule(c *check.C) { @@ -4535,12 +4536,12 @@ func (s *DockerSuite) TestRunAddDeviceCgroupRule(c *check.C) { } out, _ = dockerCmd(c, "run", "--rm", fmt.Sprintf("--device-cgroup-rule=%s", deviceRule), "busybox", "grep", deviceRule, "/sys/fs/cgroup/devices/devices.list") - c.Assert(strings.TrimSpace(out), checker.Equals, deviceRule) + assert.Equal(c, strings.TrimSpace(out), deviceRule) } // Verifies that running as local system is operating correctly on Windows func (s *DockerSuite) TestWindowsRunAsSystem(c *check.C) { testRequires(c, DaemonIsWindowsAtLeastBuild(15000)) out, _ := dockerCmd(c, "run", "--net=none", `--user=nt authority\system`, "--hostname=XYZZY", minimalBaseImage(), "cmd", "/c", `@echo %USERNAME%`) - c.Assert(strings.TrimSpace(out), checker.Equals, "XYZZY$") + assert.Equal(c, strings.TrimSpace(out), "XYZZY$") } diff --git a/components/engine/integration-cli/docker_cli_run_unix_test.go b/components/engine/integration-cli/docker_cli_run_unix_test.go index 74f30187b6..cd3f5e356b 100644 --- a/components/engine/integration-cli/docker_cli_run_unix_test.go +++ b/components/engine/integration-cli/docker_cli_run_unix_test.go @@ -27,6 +27,7 @@ import ( "github.com/docker/docker/pkg/sysinfo" "github.com/go-check/check" "github.com/kr/pty" + "gotest.tools/assert" "gotest.tools/icmd" ) @@ -39,7 +40,7 @@ func (s *DockerSuite) TestRunRedirectStdout(c *check.C) { cmd.Stdin = tty cmd.Stdout = tty cmd.Stderr = tty - c.Assert(cmd.Start(), checker.IsNil) + assert.NilError(c, cmd.Start()) ch := make(chan error) go func() { ch <- cmd.Wait() @@ -63,7 +64,7 @@ func (s *DockerSuite) TestRunWithVolumesIsRecursive(c *check.C) { // /tmp gets permission denied testRequires(c, NotUserNamespace, testEnv.IsLocalDaemon) tmpDir, err := ioutil.TempDir("", "docker_recursive_mount_test") - c.Assert(err, checker.IsNil) + assert.NilError(c, err) defer os.RemoveAll(tmpDir) @@ -73,7 +74,7 @@ func (s *DockerSuite) TestRunWithVolumesIsRecursive(c *check.C) { c.Assert(mount.Mount("tmpfs", tmpfsDir, "tmpfs", ""), checker.IsNil, check.Commentf("failed to create a tmpfs mount at %s", tmpfsDir)) f, err := ioutil.TempFile(tmpfsDir, "touch-me") - c.Assert(err, checker.IsNil) + 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") @@ -101,27 +102,27 @@ func (s *DockerSuite) TestRunAttachDetach(c *check.C) { cmd := exec.Command(dockerBinary, "attach", name) stdout, err := cmd.StdoutPipe() - c.Assert(err, checker.IsNil) + assert.NilError(c, err) cpty, tty, err := pty.Open() - c.Assert(err, checker.IsNil) + assert.NilError(c, err) defer cpty.Close() cmd.Stdin = tty - c.Assert(cmd.Start(), checker.IsNil) + assert.NilError(c, cmd.Start()) c.Assert(waitRun(name), check.IsNil) _, err = cpty.Write([]byte("hello\n")) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) out, err := bufio.NewReader(stdout).ReadString('\n') - c.Assert(err, checker.IsNil) - c.Assert(strings.TrimSpace(out), checker.Equals, "hello") + assert.NilError(c, err) + assert.Equal(c, strings.TrimSpace(out), "hello") // escape sequence _, err = cpty.Write([]byte{16}) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) time.Sleep(100 * time.Millisecond) _, err = cpty.Write([]byte{17}) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) ch := make(chan struct{}) go func() { @@ -235,7 +236,7 @@ func (s *DockerSuite) TestRunAttachDetachFromInvalidFlag(c *check.C) { } // it should print a warning to indicate the detach key flag is invalid errStr := "Invalid detach keys (ctrl-A,a) provided" - c.Assert(strings.TrimSpace(out), checker.Equals, errStr) + assert.Equal(c, strings.TrimSpace(out), errStr) } // TestRunAttachDetachFromConfig checks attaching and detaching with the escape sequence specified via config file. @@ -247,7 +248,7 @@ func (s *DockerSuite) TestRunAttachDetachFromConfig(c *check.C) { homeKey := homedir.Key() homeVal := homedir.Get() tmpDir, err := ioutil.TempDir("", "fake-home") - c.Assert(err, checker.IsNil) + assert.NilError(c, err) defer os.RemoveAll(tmpDir) dotDocker := filepath.Join(tmpDir, ".docker") @@ -262,7 +263,7 @@ func (s *DockerSuite) TestRunAttachDetachFromConfig(c *check.C) { }` err = ioutil.WriteFile(tmpCfg, []byte(data), 0600) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) // Then do the work name := "attach-detach" @@ -330,7 +331,7 @@ func (s *DockerSuite) TestRunAttachDetachKeysOverrideConfig(c *check.C) { homeKey := homedir.Key() homeVal := homedir.Get() tmpDir, err := ioutil.TempDir("", "fake-home") - c.Assert(err, checker.IsNil) + assert.NilError(c, err) defer os.RemoveAll(tmpDir) dotDocker := filepath.Join(tmpDir, ".docker") @@ -345,7 +346,7 @@ func (s *DockerSuite) TestRunAttachDetachKeysOverrideConfig(c *check.C) { }` err = ioutil.WriteFile(tmpCfg, []byte(data), 0600) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) // Then do the work name := "attach-detach" @@ -460,10 +461,10 @@ func (s *DockerSuite) TestRunWithCPUQuota(c *check.C) { file := "/sys/fs/cgroup/cpu/cpu.cfs_quota_us" out, _ := dockerCmd(c, "run", "--cpu-quota", "8000", "--name", "test", "busybox", "cat", file) - c.Assert(strings.TrimSpace(out), checker.Equals, "8000") + assert.Equal(c, strings.TrimSpace(out), "8000") out = inspectField(c, "test", "HostConfig.CpuQuota") - c.Assert(out, checker.Equals, "8000", check.Commentf("setting the CPU CFS quota failed")) + assert.Equal(c, out, "8000", "setting the CPU CFS quota failed") } func (s *DockerSuite) TestRunWithCpuPeriod(c *check.C) { @@ -471,29 +472,29 @@ func (s *DockerSuite) TestRunWithCpuPeriod(c *check.C) { file := "/sys/fs/cgroup/cpu/cpu.cfs_period_us" out, _ := dockerCmd(c, "run", "--cpu-period", "50000", "--name", "test", "busybox", "cat", file) - c.Assert(strings.TrimSpace(out), checker.Equals, "50000") + assert.Equal(c, strings.TrimSpace(out), "50000") out, _ = dockerCmd(c, "run", "--cpu-period", "0", "busybox", "cat", file) - c.Assert(strings.TrimSpace(out), checker.Equals, "100000") + assert.Equal(c, strings.TrimSpace(out), "100000") out = inspectField(c, "test", "HostConfig.CpuPeriod") - c.Assert(out, checker.Equals, "50000", check.Commentf("setting the CPU CFS period failed")) + assert.Equal(c, out, "50000", "setting the CPU CFS period failed") } func (s *DockerSuite) TestRunWithInvalidCpuPeriod(c *check.C) { testRequires(c, cpuCfsPeriod) out, _, err := dockerCmdWithError("run", "--cpu-period", "900", "busybox", "true") - c.Assert(err, check.NotNil) + assert.ErrorContains(c, err, "") expected := "CPU cfs period can not be less than 1ms (i.e. 1000) or larger than 1s (i.e. 1000000)" - c.Assert(out, checker.Contains, expected) + assert.Assert(c, strings.Contains(out, expected)) out, _, err = dockerCmdWithError("run", "--cpu-period", "2000000", "busybox", "true") - c.Assert(err, check.NotNil) - c.Assert(out, checker.Contains, expected) + assert.ErrorContains(c, err, "") + assert.Assert(c, strings.Contains(out, expected)) out, _, err = dockerCmdWithError("run", "--cpu-period", "-3", "busybox", "true") - c.Assert(err, check.NotNil) - c.Assert(out, checker.Contains, expected) + assert.ErrorContains(c, err, "") + assert.Assert(c, strings.Contains(out, expected)) } func (s *DockerSuite) TestRunWithKernelMemory(c *check.C) { @@ -513,14 +514,14 @@ func (s *DockerSuite) TestRunWithInvalidKernelMemory(c *check.C) { testRequires(c, DaemonIsLinux, kernelMemorySupport) out, _, err := dockerCmdWithError("run", "--kernel-memory", "2M", "busybox", "true") - c.Assert(err, check.NotNil) + assert.ErrorContains(c, err, "") expected := "Minimum kernel memory limit allowed is 4MB" - c.Assert(out, checker.Contains, expected) + assert.Assert(c, strings.Contains(out, expected)) out, _, err = dockerCmdWithError("run", "--kernel-memory", "-16m", "--name", "test2", "busybox", "echo", "test") - c.Assert(err, check.NotNil) + assert.ErrorContains(c, err, "") expected = "invalid size" - c.Assert(out, checker.Contains, expected) + assert.Assert(c, strings.Contains(out, expected)) } func (s *DockerSuite) TestRunWithCPUShares(c *check.C) { @@ -528,10 +529,10 @@ func (s *DockerSuite) TestRunWithCPUShares(c *check.C) { file := "/sys/fs/cgroup/cpu/cpu.shares" out, _ := dockerCmd(c, "run", "--cpu-shares", "1000", "--name", "test", "busybox", "cat", file) - c.Assert(strings.TrimSpace(out), checker.Equals, "1000") + assert.Equal(c, strings.TrimSpace(out), "1000") out = inspectField(c, "test", "HostConfig.CPUShares") - c.Assert(out, check.Equals, "1000") + assert.Equal(c, out, "1000") } // "test" should be printed @@ -548,10 +549,10 @@ func (s *DockerSuite) TestRunWithCpusetCpus(c *check.C) { file := "/sys/fs/cgroup/cpuset/cpuset.cpus" out, _ := dockerCmd(c, "run", "--cpuset-cpus", "0", "--name", "test", "busybox", "cat", file) - c.Assert(strings.TrimSpace(out), checker.Equals, "0") + assert.Equal(c, strings.TrimSpace(out), "0") out = inspectField(c, "test", "HostConfig.CpusetCpus") - c.Assert(out, check.Equals, "0") + assert.Equal(c, out, "0") } func (s *DockerSuite) TestRunWithCpusetMems(c *check.C) { @@ -559,10 +560,10 @@ func (s *DockerSuite) TestRunWithCpusetMems(c *check.C) { file := "/sys/fs/cgroup/cpuset/cpuset.mems" out, _ := dockerCmd(c, "run", "--cpuset-mems", "0", "--name", "test", "busybox", "cat", file) - c.Assert(strings.TrimSpace(out), checker.Equals, "0") + assert.Equal(c, strings.TrimSpace(out), "0") out = inspectField(c, "test", "HostConfig.CpusetMems") - c.Assert(out, check.Equals, "0") + assert.Equal(c, out, "0") } func (s *DockerSuite) TestRunWithBlkioWeight(c *check.C) { @@ -570,48 +571,48 @@ func (s *DockerSuite) TestRunWithBlkioWeight(c *check.C) { file := "/sys/fs/cgroup/blkio/blkio.weight" out, _ := dockerCmd(c, "run", "--blkio-weight", "300", "--name", "test", "busybox", "cat", file) - c.Assert(strings.TrimSpace(out), checker.Equals, "300") + assert.Equal(c, strings.TrimSpace(out), "300") out = inspectField(c, "test", "HostConfig.BlkioWeight") - c.Assert(out, check.Equals, "300") + assert.Equal(c, out, "300") } func (s *DockerSuite) TestRunWithInvalidBlkioWeight(c *check.C) { testRequires(c, blkioWeight) out, _, err := dockerCmdWithError("run", "--blkio-weight", "5", "busybox", "true") - c.Assert(err, check.NotNil, check.Commentf("%s", out)) + assert.ErrorContains(c, err, "", out) expected := "Range of blkio weight is from 10 to 1000" - c.Assert(out, checker.Contains, expected) + assert.Assert(c, strings.Contains(out, expected)) } func (s *DockerSuite) TestRunWithInvalidPathforBlkioWeightDevice(c *check.C) { testRequires(c, blkioWeight) out, _, err := dockerCmdWithError("run", "--blkio-weight-device", "/dev/sdX:100", "busybox", "true") - c.Assert(err, check.NotNil, check.Commentf("%s", out)) + assert.ErrorContains(c, err, "", out) } func (s *DockerSuite) TestRunWithInvalidPathforBlkioDeviceReadBps(c *check.C) { testRequires(c, blkioWeight) out, _, err := dockerCmdWithError("run", "--device-read-bps", "/dev/sdX:500", "busybox", "true") - c.Assert(err, check.NotNil, check.Commentf("%s", out)) + assert.ErrorContains(c, err, "", out) } func (s *DockerSuite) TestRunWithInvalidPathforBlkioDeviceWriteBps(c *check.C) { testRequires(c, blkioWeight) out, _, err := dockerCmdWithError("run", "--device-write-bps", "/dev/sdX:500", "busybox", "true") - c.Assert(err, check.NotNil, check.Commentf("%s", out)) + assert.ErrorContains(c, err, "", out) } func (s *DockerSuite) TestRunWithInvalidPathforBlkioDeviceReadIOps(c *check.C) { testRequires(c, blkioWeight) out, _, err := dockerCmdWithError("run", "--device-read-iops", "/dev/sdX:500", "busybox", "true") - c.Assert(err, check.NotNil, check.Commentf("%s", out)) + assert.ErrorContains(c, err, "", out) } func (s *DockerSuite) TestRunWithInvalidPathforBlkioDeviceWriteIOps(c *check.C) { testRequires(c, blkioWeight) out, _, err := dockerCmdWithError("run", "--device-write-iops", "/dev/sdX:500", "busybox", "true") - c.Assert(err, check.NotNil, check.Commentf("%s", out)) + assert.ErrorContains(c, err, "", out) } func (s *DockerSuite) TestRunOOMExitCode(c *check.C) { @@ -628,7 +629,7 @@ func (s *DockerSuite) TestRunOOMExitCode(c *check.C) { select { case err := <-errChan: - c.Assert(err, check.IsNil) + assert.NilError(c, err) case <-time.After(600 * time.Second): c.Fatal("Timeout waiting for container to die on OOM") } @@ -661,21 +662,21 @@ func (s *DockerSuite) TestRunWithSwappiness(c *check.C) { testRequires(c, memorySwappinessSupport) file := "/sys/fs/cgroup/memory/memory.swappiness" out, _ := dockerCmd(c, "run", "--memory-swappiness", "0", "--name", "test", "busybox", "cat", file) - c.Assert(strings.TrimSpace(out), checker.Equals, "0") + assert.Equal(c, strings.TrimSpace(out), "0") out = inspectField(c, "test", "HostConfig.MemorySwappiness") - c.Assert(out, check.Equals, "0") + assert.Equal(c, out, "0") } func (s *DockerSuite) TestRunWithSwappinessInvalid(c *check.C) { testRequires(c, memorySwappinessSupport) out, _, err := dockerCmdWithError("run", "--memory-swappiness", "101", "busybox", "true") - c.Assert(err, check.NotNil) + assert.ErrorContains(c, err, "") expected := "Valid memory swappiness range is 0-100" c.Assert(out, checker.Contains, expected, check.Commentf("Expected output to contain %q, not %q", out, expected)) out, _, err = dockerCmdWithError("run", "--memory-swappiness", "-10", "busybox", "true") - c.Assert(err, check.NotNil) + assert.ErrorContains(c, err, "") c.Assert(out, checker.Contains, expected, check.Commentf("Expected output to contain %q, not %q", out, expected)) } @@ -684,22 +685,22 @@ func (s *DockerSuite) TestRunWithMemoryReservation(c *check.C) { file := "/sys/fs/cgroup/memory/memory.soft_limit_in_bytes" out, _ := dockerCmd(c, "run", "--memory-reservation", "200M", "--name", "test", "busybox", "cat", file) - c.Assert(strings.TrimSpace(out), checker.Equals, "209715200") + assert.Equal(c, strings.TrimSpace(out), "209715200") out = inspectField(c, "test", "HostConfig.MemoryReservation") - c.Assert(out, check.Equals, "209715200") + assert.Equal(c, out, "209715200") } func (s *DockerSuite) TestRunWithMemoryReservationInvalid(c *check.C) { testRequires(c, memoryLimitSupport) testRequires(c, testEnv.IsLocalDaemon, memoryReservationSupport) out, _, err := dockerCmdWithError("run", "-m", "500M", "--memory-reservation", "800M", "busybox", "true") - c.Assert(err, check.NotNil) + assert.ErrorContains(c, err, "") expected := "Minimum memory limit can not be less than memory reservation limit" c.Assert(strings.TrimSpace(out), checker.Contains, expected, check.Commentf("run container should fail with invalid memory reservation")) out, _, err = dockerCmdWithError("run", "--memory-reservation", "1k", "busybox", "true") - c.Assert(err, check.NotNil) + assert.ErrorContains(c, err, "") expected = "Minimum memory reservation allowed is 4MB" c.Assert(strings.TrimSpace(out), checker.Contains, expected, check.Commentf("run container should fail with invalid memory reservation")) } @@ -721,9 +722,9 @@ func (s *DockerSuite) TestRunSwapLessThanMemoryLimit(c *check.C) { testRequires(c, swapMemorySupport) out, _, err := dockerCmdWithError("run", "-m", "16m", "--memory-swap", "15m", "busybox", "echo", "test") expected := "Minimum memoryswap limit should be larger than memory limit" - c.Assert(err, check.NotNil) + assert.ErrorContains(c, err, "") - c.Assert(out, checker.Contains, expected) + assert.Assert(c, strings.Contains(out, expected)) } func (s *DockerSuite) TestRunInvalidCpusetCpusFlagValue(c *check.C) { @@ -731,7 +732,7 @@ func (s *DockerSuite) TestRunInvalidCpusetCpusFlagValue(c *check.C) { sysInfo := sysinfo.New(true) cpus, err := parsers.ParseUintList(sysInfo.Cpus) - c.Assert(err, check.IsNil) + assert.NilError(c, err) var invalid int for i := 0; i <= len(cpus)+1; i++ { if !cpus[i] { @@ -740,9 +741,9 @@ func (s *DockerSuite) TestRunInvalidCpusetCpusFlagValue(c *check.C) { } } out, _, err := dockerCmdWithError("run", "--cpuset-cpus", strconv.Itoa(invalid), "busybox", "true") - c.Assert(err, check.NotNil) + assert.ErrorContains(c, err, "") expected := fmt.Sprintf("Error response from daemon: Requested CPUs are not available - requested %s, available: %s", strconv.Itoa(invalid), sysInfo.Cpus) - c.Assert(out, checker.Contains, expected) + assert.Assert(c, strings.Contains(out, expected)) } func (s *DockerSuite) TestRunInvalidCpusetMemsFlagValue(c *check.C) { @@ -750,7 +751,7 @@ func (s *DockerSuite) TestRunInvalidCpusetMemsFlagValue(c *check.C) { sysInfo := sysinfo.New(true) mems, err := parsers.ParseUintList(sysInfo.Mems) - c.Assert(err, check.IsNil) + assert.NilError(c, err) var invalid int for i := 0; i <= len(mems)+1; i++ { if !mems[i] { @@ -759,27 +760,27 @@ func (s *DockerSuite) TestRunInvalidCpusetMemsFlagValue(c *check.C) { } } out, _, err := dockerCmdWithError("run", "--cpuset-mems", strconv.Itoa(invalid), "busybox", "true") - c.Assert(err, check.NotNil) + assert.ErrorContains(c, err, "") expected := fmt.Sprintf("Error response from daemon: Requested memory nodes are not available - requested %s, available: %s", strconv.Itoa(invalid), sysInfo.Mems) - c.Assert(out, checker.Contains, expected) + assert.Assert(c, strings.Contains(out, expected)) } func (s *DockerSuite) TestRunInvalidCPUShares(c *check.C) { testRequires(c, cpuShare, DaemonIsLinux) out, _, err := dockerCmdWithError("run", "--cpu-shares", "1", "busybox", "echo", "test") - c.Assert(err, check.NotNil, check.Commentf("%s", out)) + assert.ErrorContains(c, err, "", out) expected := "The minimum allowed cpu-shares is 2" - c.Assert(out, checker.Contains, expected) + assert.Assert(c, strings.Contains(out, expected)) out, _, err = dockerCmdWithError("run", "--cpu-shares", "-1", "busybox", "echo", "test") - c.Assert(err, check.NotNil, check.Commentf("%s", out)) + assert.ErrorContains(c, err, "", out) expected = "shares: invalid argument" - c.Assert(out, checker.Contains, expected) + assert.Assert(c, strings.Contains(out, expected)) out, _, err = dockerCmdWithError("run", "--cpu-shares", "99999999", "busybox", "echo", "test") - c.Assert(err, check.NotNil, check.Commentf("%s", out)) + assert.ErrorContains(c, err, "", out) expected = "The maximum allowed cpu-shares is" - c.Assert(out, checker.Contains, expected) + assert.Assert(c, strings.Contains(out, expected)) } func (s *DockerSuite) TestRunWithDefaultShmSize(c *check.C) { @@ -810,7 +811,7 @@ func (s *DockerSuite) TestRunWithShmSize(c *check.C) { func (s *DockerSuite) TestRunTmpfsMountsEnsureOrdered(c *check.C) { tmpFile, err := ioutil.TempFile("", "test") - c.Assert(err, check.IsNil) + assert.NilError(c, err) defer tmpFile.Close() out, _ := dockerCmd(c, "run", "--tmpfs", "/run", "-v", tmpFile.Name()+":/run/test", "busybox", "ls", "/run") c.Assert(out, checker.Contains, "test") @@ -900,7 +901,7 @@ func (s *DockerSuite) TestRunSysctls(c *check.C) { sysctls := make(map[string]string) err = json.Unmarshal([]byte(out), &sysctls) - c.Assert(err, check.IsNil) + assert.NilError(c, err) c.Assert(sysctls["net.ipv4.ip_forward"], check.Equals, "1") out, _ = dockerCmd(c, "run", "--sysctl", "net.ipv4.ip_forward=0", "--name", "test1", "busybox", "cat", "/proc/sys/net/ipv4/ip_forward") @@ -909,7 +910,7 @@ func (s *DockerSuite) TestRunSysctls(c *check.C) { out = inspectFieldJSON(c, "test1", "HostConfig.Sysctls") err = json.Unmarshal([]byte(out), &sysctls) - c.Assert(err, check.IsNil) + assert.NilError(c, err) c.Assert(sysctls["net.ipv4.ip_forward"], check.Equals, "0") icmd.RunCommand(dockerBinary, "run", "--sysctl", "kernel.foobar=1", "--name", "test2", @@ -969,7 +970,7 @@ func (s *DockerSuite) TestRunSeccompProfileDenyChmod(c *check.C) { ] }` tmpFile, err := ioutil.TempFile("", "profile.json") - c.Assert(err, check.IsNil) + assert.NilError(c, err) defer tmpFile.Close() if _, err := tmpFile.Write([]byte(jsonData)); err != nil { @@ -1349,8 +1350,8 @@ func (s *DockerSuite) TestRunSeccompWithDefaultProfile(c *check.C) { testRequires(c, testEnv.IsLocalDaemon, seccompEnabled) out, _, err := dockerCmdWithError("run", "--security-opt", "seccomp=../profiles/seccomp/default.json", "debian:jessie", "unshare", "--map-root-user", "--user", "sh", "-c", "whoami") - c.Assert(err, checker.NotNil, check.Commentf("%s", out)) - c.Assert(strings.TrimSpace(out), checker.Equals, "unshare: unshare failed: Operation not permitted") + assert.ErrorContains(c, err, "", out) + assert.Equal(c, strings.TrimSpace(out), "unshare: unshare failed: Operation not permitted") } // TestRunDeviceSymlink checks run with device that follows symlink (#13840 and #22271) @@ -1362,23 +1363,23 @@ func (s *DockerSuite) TestRunDeviceSymlink(c *check.C) { // Create a temporary directory to create symlink tmpDir, err := ioutil.TempDir("", "docker_device_follow_symlink_tests") - c.Assert(err, checker.IsNil) + assert.NilError(c, err) defer os.RemoveAll(tmpDir) // Create a symbolic link to /dev/zero symZero := filepath.Join(tmpDir, "zero") err = os.Symlink("/dev/zero", symZero) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) // Create a temporary file "temp" inside tmpDir, write some data to "tmpDir/temp", // then create a symlink "tmpDir/file" to the temporary file "tmpDir/temp". tmpFile := filepath.Join(tmpDir, "temp") err = ioutil.WriteFile(tmpFile, []byte("temp"), 0666) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) symFile := filepath.Join(tmpDir, "file") err = os.Symlink(tmpFile, symFile) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) // Create a symbolic link to /dev/zero, this time with a relative path (#22271) err = os.Symlink("zero", "/dev/symzero") @@ -1394,7 +1395,7 @@ func (s *DockerSuite) TestRunDeviceSymlink(c *check.C) { // 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") - c.Assert(err, check.NotNil) + assert.ErrorContains(c, err, "") c.Assert(strings.Trim(out, "\r\n"), checker.Contains, "not a device node", check.Commentf("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) @@ -1408,10 +1409,10 @@ func (s *DockerSuite) TestRunPIDsLimit(c *check.C) { file := "/sys/fs/cgroup/pids/pids.max" out, _ := dockerCmd(c, "run", "--name", "skittles", "--pids-limit", "4", "busybox", "cat", file) - c.Assert(strings.TrimSpace(out), checker.Equals, "4") + assert.Equal(c, strings.TrimSpace(out), "4") out = inspectField(c, "skittles", "HostConfig.PidsLimit") - c.Assert(out, checker.Equals, "4", check.Commentf("setting the pids limit failed")) + assert.Equal(c, out, "4", "setting the pids limit failed") } func (s *DockerSuite) TestRunPrivilegedAllowedDevices(c *check.C) { @@ -1420,7 +1421,7 @@ func (s *DockerSuite) TestRunPrivilegedAllowedDevices(c *check.C) { file := "/sys/fs/cgroup/devices/devices.list" out, _ := dockerCmd(c, "run", "--privileged", "busybox", "cat", file) c.Logf("out: %q", out) - c.Assert(strings.TrimSpace(out), checker.Equals, "a *:* rwm") + assert.Equal(c, strings.TrimSpace(out), "a *:* rwm") } func (s *DockerSuite) TestRunUserDeviceAllowed(c *check.C) { @@ -1455,13 +1456,13 @@ func (s *DockerDaemonSuite) TestRunSeccompJSONNewFormat(c *check.C) { ] }` tmpFile, err := ioutil.TempFile("", "profile.json") - c.Assert(err, check.IsNil) + assert.NilError(c, err) defer tmpFile.Close() _, err = tmpFile.Write([]byte(jsonData)) - c.Assert(err, check.IsNil) + assert.NilError(c, err) out, err := s.d.Cmd("run", "--security-opt", "seccomp="+tmpFile.Name(), "busybox", "chmod", "777", ".") - c.Assert(err, check.NotNil) + assert.ErrorContains(c, err, "") c.Assert(out, checker.Contains, "Operation not permitted") } @@ -1481,13 +1482,13 @@ func (s *DockerDaemonSuite) TestRunSeccompJSONNoNameAndNames(c *check.C) { ] }` tmpFile, err := ioutil.TempFile("", "profile.json") - c.Assert(err, check.IsNil) + assert.NilError(c, err) defer tmpFile.Close() _, err = tmpFile.Write([]byte(jsonData)) - c.Assert(err, check.IsNil) + assert.NilError(c, err) out, err := s.d.Cmd("run", "--security-opt", "seccomp="+tmpFile.Name(), "busybox", "chmod", "777", ".") - c.Assert(err, check.NotNil) + assert.ErrorContains(c, err, "") c.Assert(out, checker.Contains, "'name' and 'names' were specified in the seccomp profile, use either 'name' or 'names'") } @@ -1518,13 +1519,13 @@ func (s *DockerDaemonSuite) TestRunSeccompJSONNoArchAndArchMap(c *check.C) { ] }` tmpFile, err := ioutil.TempFile("", "profile.json") - c.Assert(err, check.IsNil) + assert.NilError(c, err) defer tmpFile.Close() _, err = tmpFile.Write([]byte(jsonData)) - c.Assert(err, check.IsNil) + assert.NilError(c, err) out, err := s.d.Cmd("run", "--security-opt", "seccomp="+tmpFile.Name(), "busybox", "chmod", "777", ".") - c.Assert(err, check.NotNil) + assert.ErrorContains(c, err, "") c.Assert(out, checker.Contains, "'architectures' and 'archMap' were specified in the seccomp profile, use either 'architectures' or 'archMap'") } @@ -1535,7 +1536,7 @@ func (s *DockerDaemonSuite) TestRunWithDaemonDefaultSeccompProfile(c *check.C) { // 1) verify I can run containers with the Docker default shipped profile which allows chmod _, err := s.d.Cmd("run", "busybox", "chmod", "777", ".") - c.Assert(err, check.IsNil) + assert.NilError(c, err) jsonData := `{ "defaultAction": "SCMP_ACT_ALLOW", @@ -1547,16 +1548,16 @@ func (s *DockerDaemonSuite) TestRunWithDaemonDefaultSeccompProfile(c *check.C) { ] }` tmpFile, err := ioutil.TempFile("", "profile.json") - c.Assert(err, check.IsNil) + assert.NilError(c, err) defer tmpFile.Close() _, err = tmpFile.Write([]byte(jsonData)) - c.Assert(err, check.IsNil) + assert.NilError(c, err) // 2) restart the daemon and add a custom seccomp profile in which we deny chmod s.d.Restart(c, "--seccomp-profile="+tmpFile.Name()) out, err := s.d.Cmd("run", "busybox", "chmod", "777", ".") - c.Assert(err, check.NotNil) + assert.ErrorContains(c, err, "") c.Assert(out, checker.Contains, "Operation not permitted") } @@ -1566,20 +1567,20 @@ func (s *DockerSuite) TestRunWithNanoCPUs(c *check.C) { 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)) - c.Assert(strings.TrimSpace(out), checker.Equals, "50000\n100000") + assert.Equal(c, strings.TrimSpace(out), "50000\n100000") clt, err := client.NewClientWithOpts(client.FromEnv) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) inspect, err := clt.ContainerInspect(context.Background(), "test") - c.Assert(err, checker.IsNil) + assert.NilError(c, err) c.Assert(inspect.HostConfig.NanoCPUs, checker.Equals, int64(500000000)) out = inspectField(c, "test", "HostConfig.CpuQuota") - c.Assert(out, checker.Equals, "0", check.Commentf("CPU CFS quota should be 0")) + assert.Equal(c, out, "0", "CPU CFS quota should be 0") out = inspectField(c, "test", "HostConfig.CpuPeriod") - c.Assert(out, checker.Equals, "0", check.Commentf("CPU CFS period should be 0")) + assert.Equal(c, out, "0", "CPU CFS period should be 0") out, _, err = dockerCmdWithError("run", "--cpus", "0.5", "--cpu-quota", "50000", "--cpu-period", "100000", "busybox", "sh") - c.Assert(err, check.NotNil) + assert.ErrorContains(c, err, "") c.Assert(out, checker.Contains, "Conflicting options: Nano CPUs and CPU Period cannot both be set") } diff --git a/components/engine/integration-cli/docker_cli_save_load_test.go b/components/engine/integration-cli/docker_cli_save_load_test.go index ba1fa2b8b2..67536d893e 100644 --- a/components/engine/integration-cli/docker_cli_save_load_test.go +++ b/components/engine/integration-cli/docker_cli_save_load_test.go @@ -19,6 +19,8 @@ import ( "github.com/docker/docker/integration-cli/cli/build" "github.com/go-check/check" "github.com/opencontainers/go-digest" + "gotest.tools/assert" + is "gotest.tools/assert/cmp" "gotest.tools/icmd" ) @@ -37,7 +39,7 @@ func (s *DockerSuite) TestSaveXzAndLoadRepoStdout(c *check.C) { exec.Command(dockerBinary, "save", repoName), exec.Command("xz", "-c"), exec.Command("gzip", "-c")) - c.Assert(err, checker.IsNil, check.Commentf("failed to save repo: %v %v", out, err)) + assert.NilError(c, err, "failed to save repo: %v %v", out, err) deleteImages(repoName) icmd.RunCmd(icmd.Cmd{ @@ -48,7 +50,7 @@ func (s *DockerSuite) TestSaveXzAndLoadRepoStdout(c *check.C) { }) after, _, err := dockerCmdWithError("inspect", repoName) - c.Assert(err, checker.NotNil, check.Commentf("the repo should not exist: %v", after)) + assert.ErrorContains(c, err, "", "the repo should not exist: %v", after) } // save a repo using xz+gz compression and try to load it using stdout @@ -66,7 +68,7 @@ func (s *DockerSuite) TestSaveXzGzAndLoadRepoStdout(c *check.C) { exec.Command(dockerBinary, "save", repoName), exec.Command("xz", "-c"), exec.Command("gzip", "-c")) - c.Assert(err, checker.IsNil, check.Commentf("failed to save repo: %v %v", out, err)) + assert.NilError(c, err, "failed to save repo: %v %v", out, err) deleteImages(repoName) @@ -78,7 +80,7 @@ func (s *DockerSuite) TestSaveXzGzAndLoadRepoStdout(c *check.C) { }) after, _, err := dockerCmdWithError("inspect", repoName) - c.Assert(err, checker.NotNil, check.Commentf("the repo should not exist: %v", after)) + assert.ErrorContains(c, err, "", "the repo should not exist: %v", after) } func (s *DockerSuite) TestSaveSingleTag(c *check.C) { @@ -93,7 +95,7 @@ func (s *DockerSuite) TestSaveSingleTag(c *check.C) { exec.Command(dockerBinary, "save", fmt.Sprintf("%v:latest", repoName)), exec.Command("tar", "t"), exec.Command("grep", "-E", fmt.Sprintf("(^repositories$|%v)", cleanedImageID))) - c.Assert(err, checker.IsNil, check.Commentf("failed to save repo with image ID and 'repositories' file: %s, %v", out, err)) + assert.NilError(c, err, "failed to save repo with image ID and 'repositories' file: %s, %v", out, err) } func (s *DockerSuite) TestSaveCheckTimes(c *check.C) { @@ -105,14 +107,14 @@ func (s *DockerSuite) TestSaveCheckTimes(c *check.C) { Created time.Time } err := json.Unmarshal([]byte(out), &data) - c.Assert(err, checker.IsNil, check.Commentf("failed to marshal from %q: err %v", repoName, err)) - c.Assert(len(data), checker.Not(checker.Equals), 0, check.Commentf("failed to marshal the data from %q", repoName)) + assert.NilError(c, err, "failed to marshal from %q: err %v", repoName, err) + assert.Assert(c, len(data) != 0, "failed to marshal the data from %q", repoName) tarTvTimeFormat := "2006-01-02 15:04" out, err = RunCommandPipelineWithOutput( exec.Command(dockerBinary, "save", repoName), exec.Command("tar", "tv"), exec.Command("grep", "-E", fmt.Sprintf("%s %s", data[0].Created.Format(tarTvTimeFormat), digest.Digest(data[0].ID).Hex()))) - c.Assert(err, checker.IsNil, check.Commentf("failed to save repo with image ID and 'repositories' file: %s, %v", out, err)) + assert.NilError(c, err, "failed to save repo with image ID and 'repositories' file: %s, %v", out, err) } func (s *DockerSuite) TestSaveImageId(c *check.C) { @@ -169,10 +171,10 @@ func (s *DockerSuite) TestSaveAndLoadRepoFlags(c *check.C) { out, err := RunCommandPipelineWithOutput( exec.Command(dockerBinary, "save", repoName), exec.Command(dockerBinary, "load")) - c.Assert(err, checker.IsNil, check.Commentf("failed to save and load repo: %s, %v", out, err)) + assert.NilError(c, err, "failed to save and load repo: %s, %v", out, err) after, _ := dockerCmd(c, "inspect", repoName) - c.Assert(before, checker.Equals, after, check.Commentf("inspect is not the same after a save / load")) + assert.Equal(c, before, after, "inspect is not the same after a save / load") } func (s *DockerSuite) TestSaveWithNoExistImage(c *check.C) { @@ -181,8 +183,8 @@ func (s *DockerSuite) TestSaveWithNoExistImage(c *check.C) { imgName := "foobar-non-existing-image" out, _, err := dockerCmdWithError("save", "-o", "test-img.tar", imgName) - c.Assert(err, checker.NotNil, check.Commentf("save image should fail for non-existing image")) - c.Assert(out, checker.Contains, fmt.Sprintf("No such image: %s", imgName)) + assert.ErrorContains(c, err, "", "save image should fail for non-existing image") + assert.Assert(c, strings.Contains(out, fmt.Sprintf("No such image: %s", imgName))) } func (s *DockerSuite) TestSaveMultipleNames(c *check.C) { @@ -200,7 +202,7 @@ func (s *DockerSuite) TestSaveMultipleNames(c *check.C) { exec.Command("tar", "xO", "repositories"), exec.Command("grep", "-q", "-E", "(-one|-two)"), ) - c.Assert(err, checker.IsNil, check.Commentf("failed to save multiple repos: %s, %v", out, err)) + assert.NilError(c, err, "failed to save multiple repos: %s, %v", out, err) } func (s *DockerSuite) TestSaveRepoWithMultipleImages(c *check.C) { @@ -230,7 +232,7 @@ func (s *DockerSuite) TestSaveRepoWithMultipleImages(c *check.C) { out, err := RunCommandPipelineWithOutput( exec.Command(dockerBinary, "save", repoName, "busybox:latest"), exec.Command("tar", "t")) - c.Assert(err, checker.IsNil, check.Commentf("failed to save multiple images: %s, %v", out, err)) + assert.NilError(c, err, "failed to save multiple images: %s, %v", out, err) lines := strings.Split(strings.TrimSpace(out), "\n") var actual []string @@ -251,7 +253,7 @@ func (s *DockerSuite) TestSaveRepoWithMultipleImages(c *check.C) { sort.Strings(actual) sort.Strings(expected) - c.Assert(actual, checker.DeepEquals, expected, check.Commentf("archive does not contains the right layers: got %v, expected %v, output: %q", actual, expected, out)) + assert.Assert(c, is.DeepEqual(actual, expected), "archive does not contains the right layers: got %v, expected %v, output: %q", actual, expected, out) } // Issue #6722 #5892 ensure directories are included in changes @@ -275,10 +277,10 @@ func (s *DockerSuite) TestSaveDirectoryPermissions(c *check.C) { exec.Command(dockerBinary, "save", name), exec.Command("tar", "-xf", "-", "-C", extractionDirectory), ) - c.Assert(err, checker.IsNil, check.Commentf("failed to save and extract image: %s", out)) + assert.NilError(c, err, "failed to save and extract image: %s", out) dirs, err := ioutil.ReadDir(extractionDirectory) - c.Assert(err, checker.IsNil, check.Commentf("failed to get a listing of the layer directories: %s", err)) + assert.NilError(c, err, "failed to get a listing of the layer directories: %s", err) found := false for _, entry := range dirs { @@ -287,7 +289,8 @@ func (s *DockerSuite) TestSaveDirectoryPermissions(c *check.C) { layerPath := filepath.Join(extractionDirectory, entry.Name(), "layer.tar") f, err := os.Open(layerPath) - c.Assert(err, checker.IsNil, check.Commentf("failed to open %s: %s", layerPath, err)) + assert.NilError(c, err, "failed to open %s: %s", layerPath, err) + defer f.Close() entries, err := listTar(f) @@ -296,7 +299,7 @@ func (s *DockerSuite) TestSaveDirectoryPermissions(c *check.C) { entriesSansDev = append(entriesSansDev, e) } } - c.Assert(err, checker.IsNil, check.Commentf("encountered error while listing tar entries: %s", err)) + assert.NilError(c, err, "encountered error while listing tar entries: %s", err) if reflect.DeepEqual(entriesSansDev, layerEntries) || reflect.DeepEqual(entriesSansDev, layerEntriesAUFS) { found = true @@ -305,8 +308,7 @@ func (s *DockerSuite) TestSaveDirectoryPermissions(c *check.C) { } } - c.Assert(found, checker.Equals, true, check.Commentf("failed to find the layer with the right content listing")) - + assert.Assert(c, found, "failed to find the layer with the right content listing") } func listTar(f io.Reader) ([]string, error) { @@ -358,7 +360,7 @@ func (s *DockerSuite) TestSaveLoadParents(c *check.C) { idBar := makeImage(idFoo, "bar") tmpDir, err := ioutil.TempDir("", "save-load-parents") - c.Assert(err, checker.IsNil) + assert.NilError(c, err) defer os.RemoveAll(tmpDir) c.Log("tmpdir", tmpDir) @@ -370,10 +372,10 @@ func (s *DockerSuite) TestSaveLoadParents(c *check.C) { dockerCmd(c, "load", "-i", outfile) inspectOut := inspectField(c, idBar, "Parent") - c.Assert(inspectOut, checker.Equals, idFoo) + assert.Equal(c, inspectOut, idFoo) inspectOut = inspectField(c, idFoo, "Parent") - c.Assert(inspectOut, checker.Equals, "") + assert.Equal(c, inspectOut, "") } func (s *DockerSuite) TestSaveLoadNoTag(c *check.C) { @@ -388,7 +390,7 @@ func (s *DockerSuite) TestSaveLoadNoTag(c *check.C) { out, err := RunCommandPipelineWithOutput( exec.Command(dockerBinary, "save", id), exec.Command(dockerBinary, "load")) - c.Assert(err, checker.IsNil, check.Commentf("failed to save and load repo: %s, %v", out, err)) + assert.NilError(c, err, "failed to save and load repo: %s, %v", out, err) // Should not show 'name' but should show the image ID during the load c.Assert(out, checker.Not(checker.Contains), "Loaded image: ") @@ -399,7 +401,8 @@ func (s *DockerSuite) TestSaveLoadNoTag(c *check.C) { out, err = RunCommandPipelineWithOutput( exec.Command(dockerBinary, "save", name), exec.Command(dockerBinary, "load")) - c.Assert(err, checker.IsNil, check.Commentf("failed to save and load repo: %s, %v", out, err)) + assert.NilError(c, err, "failed to save and load repo: %s, %v", out, err) + c.Assert(out, checker.Contains, "Loaded image: "+name+":latest") c.Assert(out, checker.Not(checker.Contains), "Loaded image ID:") } diff --git a/components/engine/integration-cli/docker_cli_save_load_unix_test.go b/components/engine/integration-cli/docker_cli_save_load_unix_test.go index da520e41c0..4d85204d42 100644 --- a/components/engine/integration-cli/docker_cli_save_load_unix_test.go +++ b/components/engine/integration-cli/docker_cli_save_load_unix_test.go @@ -11,10 +11,10 @@ import ( "strings" "time" - "github.com/docker/docker/integration-cli/checker" "github.com/docker/docker/integration-cli/cli/build" "github.com/go-check/check" "github.com/kr/pty" + "gotest.tools/assert" "gotest.tools/icmd" ) @@ -28,7 +28,7 @@ func (s *DockerSuite) TestSaveAndLoadRepoStdout(c *check.C) { before = strings.TrimRight(before, "\n") tmpFile, err := ioutil.TempFile("", "foobar-save-load-test.tar") - c.Assert(err, check.IsNil) + assert.NilError(c, err) defer os.Remove(tmpFile.Name()) icmd.RunCmd(icmd.Cmd{ @@ -37,7 +37,7 @@ func (s *DockerSuite) TestSaveAndLoadRepoStdout(c *check.C) { }).Assert(c, icmd.Success) tmpFile, err = os.Open(tmpFile.Name()) - c.Assert(err, check.IsNil) + assert.NilError(c, err) defer tmpFile.Close() deleteImages(repoName) @@ -50,24 +50,24 @@ func (s *DockerSuite) TestSaveAndLoadRepoStdout(c *check.C) { after := inspectField(c, repoName, "Id") after = strings.TrimRight(after, "\n") - c.Assert(after, check.Equals, before) //inspect is not the same after a save / load + assert.Equal(c, after, before, "inspect is not the same after a save / load") deleteImages(repoName) pty, tty, err := pty.Open() - c.Assert(err, check.IsNil) + assert.NilError(c, err) cmd := exec.Command(dockerBinary, "save", repoName) cmd.Stdin = tty cmd.Stdout = tty cmd.Stderr = tty - c.Assert(cmd.Start(), check.IsNil) - c.Assert(cmd.Wait(), check.NotNil) //did not break writing to a TTY + assert.NilError(c, cmd.Start()) + assert.ErrorContains(c, cmd.Wait(), "", "did not break writing to a TTY") buf := make([]byte, 1024) n, err := pty.Read(buf) - c.Assert(err, check.IsNil) //could not read tty output - c.Assert(string(buf[:n]), checker.Contains, "cowardly refusing", check.Commentf("help output is not being yielded")) + 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") } func (s *DockerSuite) TestSaveAndLoadWithProgressBar(c *check.C) { @@ -84,24 +84,24 @@ func (s *DockerSuite) TestSaveAndLoadWithProgressBar(c *check.C) { dockerCmd(c, "tag", "busybox", name) out, _ := dockerCmd(c, "load", "-i", tmptar) expected := fmt.Sprintf("The image %s:latest already exists, renaming the old one with ID", name) - c.Assert(out, checker.Contains, expected) + assert.Assert(c, strings.Contains(out, expected)) } // fail because load didn't receive data from stdin func (s *DockerSuite) TestLoadNoStdinFail(c *check.C) { pty, tty, err := pty.Open() - c.Assert(err, check.IsNil) + assert.NilError(c, err) ctx, cancel := context.WithTimeout(context.Background(), 5*time.Second) defer cancel() cmd := exec.CommandContext(ctx, dockerBinary, "load") cmd.Stdin = tty cmd.Stdout = tty cmd.Stderr = tty - c.Assert(cmd.Run(), check.NotNil) // docker-load should fail + assert.ErrorContains(c, cmd.Run(), "", "docker-load should fail") buf := make([]byte, 1024) n, err := pty.Read(buf) - c.Assert(err, check.IsNil) //could not read tty output - c.Assert(string(buf[:n]), checker.Contains, "requested load from stdin, but stdin is empty") + assert.NilError(c, err) //could not read tty output + assert.Assert(c, strings.Contains(string(buf[:n]), "requested load from stdin, but stdin is empty")) } diff --git a/components/engine/integration-cli/docker_cli_search_test.go b/components/engine/integration-cli/docker_cli_search_test.go index 809088a115..2f811d4b96 100644 --- a/components/engine/integration-cli/docker_cli_search_test.go +++ b/components/engine/integration-cli/docker_cli_search_test.go @@ -4,8 +4,8 @@ import ( "fmt" "strings" - "github.com/docker/docker/integration-cli/checker" "github.com/go-check/check" + "gotest.tools/assert" ) // search for repos named "registry" on the central registry @@ -13,67 +13,67 @@ func (s *DockerSuite) TestSearchOnCentralRegistry(c *check.C) { testRequires(c, Network, DaemonIsLinux) out, _ := dockerCmd(c, "search", "busybox") - c.Assert(out, checker.Contains, "Busybox base image.", check.Commentf("couldn't find any repository named (or containing) 'Busybox base image.'")) + assert.Assert(c, strings.Contains(out, "Busybox base image."), "couldn't find any repository named (or containing) 'Busybox base image.'") } func (s *DockerSuite) TestSearchStarsOptionWithWrongParameter(c *check.C) { out, _, err := dockerCmdWithError("search", "--filter", "stars=a", "busybox") - c.Assert(err, check.NotNil, check.Commentf("%s", out)) - c.Assert(out, checker.Contains, "Invalid filter", check.Commentf("couldn't find the invalid filter warning")) + assert.ErrorContains(c, err, "", out) + assert.Assert(c, strings.Contains(out, "Invalid filter"), "couldn't find the invalid filter warning") out, _, err = dockerCmdWithError("search", "-f", "stars=a", "busybox") - c.Assert(err, check.NotNil, check.Commentf("%s", out)) - c.Assert(out, checker.Contains, "Invalid filter", check.Commentf("couldn't find the invalid filter warning")) + assert.ErrorContains(c, err, "", out) + assert.Assert(c, strings.Contains(out, "Invalid filter"), "couldn't find the invalid filter warning") out, _, err = dockerCmdWithError("search", "-f", "is-automated=a", "busybox") - c.Assert(err, check.NotNil, check.Commentf("%s", out)) - c.Assert(out, checker.Contains, "Invalid filter", check.Commentf("couldn't find the invalid filter warning")) + assert.ErrorContains(c, err, "", out) + assert.Assert(c, strings.Contains(out, "Invalid filter"), "couldn't find the invalid filter warning") out, _, err = dockerCmdWithError("search", "-f", "is-official=a", "busybox") - c.Assert(err, check.NotNil, check.Commentf("%s", out)) - c.Assert(out, checker.Contains, "Invalid filter", check.Commentf("couldn't find the invalid filter warning")) + assert.ErrorContains(c, err, "", out) + assert.Assert(c, strings.Contains(out, "Invalid filter"), "couldn't find the invalid filter warning") // -s --stars deprecated since Docker 1.13 out, _, err = dockerCmdWithError("search", "--stars=a", "busybox") - c.Assert(err, check.NotNil, check.Commentf("%s", out)) - c.Assert(out, checker.Contains, "invalid syntax", check.Commentf("couldn't find the invalid value warning")) + assert.ErrorContains(c, err, "", out) + assert.Assert(c, strings.Contains(out, "invalid syntax"), "couldn't find the invalid value warning") // -s --stars deprecated since Docker 1.13 out, _, err = dockerCmdWithError("search", "-s=-1", "busybox") - c.Assert(err, check.NotNil, check.Commentf("%s", out)) - c.Assert(out, checker.Contains, "invalid syntax", check.Commentf("couldn't find the invalid value warning")) + assert.ErrorContains(c, err, "", out) + assert.Assert(c, strings.Contains(out, "invalid syntax"), "couldn't find the invalid value warning") } func (s *DockerSuite) TestSearchCmdOptions(c *check.C) { testRequires(c, Network, DaemonIsLinux) out, _ := dockerCmd(c, "search", "--help") - c.Assert(out, checker.Contains, "Usage:\tdocker search [OPTIONS] TERM") + assert.Assert(c, strings.Contains(out, "Usage:\tdocker search [OPTIONS] TERM")) outSearchCmd, _ := dockerCmd(c, "search", "busybox") outSearchCmdNotrunc, _ := dockerCmd(c, "search", "--no-trunc=true", "busybox") - c.Assert(len(outSearchCmd) > len(outSearchCmdNotrunc), check.Equals, false, check.Commentf("The no-trunc option can't take effect.")) + assert.Assert(c, len(outSearchCmd) <= len(outSearchCmdNotrunc), "The no-trunc option can't take effect.") outSearchCmdautomated, _ := dockerCmd(c, "search", "--filter", "is-automated=true", "busybox") //The busybox is a busybox base image, not an AUTOMATED image. outSearchCmdautomatedSlice := strings.Split(outSearchCmdautomated, "\n") for i := range outSearchCmdautomatedSlice { - c.Assert(strings.HasPrefix(outSearchCmdautomatedSlice[i], "busybox "), check.Equals, false, check.Commentf("The busybox is not an AUTOMATED image: %s", outSearchCmdautomated)) + 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. outSearchCmdNotOfficialSlice := strings.Split(outSearchCmdNotOfficial, "\n") for i := range outSearchCmdNotOfficialSlice { - c.Assert(strings.HasPrefix(outSearchCmdNotOfficialSlice[i], "busybox "), check.Equals, false, check.Commentf("The busybox is not an OFFICIAL image: %s", outSearchCmdNotOfficial)) + 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. outSearchCmdOfficialSlice := strings.Split(outSearchCmdOfficial, "\n") - c.Assert(outSearchCmdOfficialSlice, checker.HasLen, 3) // 1 header, 1 line, 1 carriage return - c.Assert(strings.HasPrefix(outSearchCmdOfficialSlice[1], "busybox "), check.Equals, true, check.Commentf("The busybox is an OFFICIAL image: %s", outSearchCmdNotOfficial)) + 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=2", "busybox") - c.Assert(strings.Count(outSearchCmdStars, "[OK]") > strings.Count(outSearchCmd, "[OK]"), check.Equals, false, check.Commentf("The quantity of images with stars should be less than that of all images: %s", outSearchCmdStars)) + assert.Assert(c, strings.Count(outSearchCmdStars, "[OK]") <= strings.Count(outSearchCmd, "[OK]"), "The quantity of images with stars should be less than that of all images: %s", outSearchCmdStars) dockerCmd(c, "search", "--filter", "is-automated=true", "--filter", "stars=2", "--no-trunc=true", "busybox") @@ -81,12 +81,12 @@ func (s *DockerSuite) TestSearchCmdOptions(c *check.C) { outSearchCmdautomated1, _ := dockerCmd(c, "search", "--automated=true", "busybox") //The busybox is a busybox base image, not an AUTOMATED image. outSearchCmdautomatedSlice1 := strings.Split(outSearchCmdautomated1, "\n") for i := range outSearchCmdautomatedSlice1 { - c.Assert(strings.HasPrefix(outSearchCmdautomatedSlice1[i], "busybox "), check.Equals, false, check.Commentf("The busybox is not an AUTOMATED image: %s", outSearchCmdautomated)) + assert.Assert(c, !strings.HasPrefix(outSearchCmdautomatedSlice1[i], "busybox "), "The busybox is not an AUTOMATED image: %s", outSearchCmdautomated) } // -s --stars deprecated since Docker 1.13 outSearchCmdStars1, _ := dockerCmd(c, "search", "--stars=2", "busybox") - c.Assert(strings.Count(outSearchCmdStars1, "[OK]") > strings.Count(outSearchCmd, "[OK]"), check.Equals, false, check.Commentf("The quantity of images with stars should be less than that of all images: %s", outSearchCmdStars1)) + assert.Assert(c, strings.Count(outSearchCmdStars1, "[OK]") <= strings.Count(outSearchCmd, "[OK]"), "The quantity of images with stars should be less than that of all images: %s", outSearchCmdStars1) // -s --stars deprecated since Docker 1.13 dockerCmd(c, "search", "--stars=2", "--automated=true", "--no-trunc=true", "busybox") @@ -105,27 +105,27 @@ func (s *DockerSuite) TestSearchWithLimit(c *check.C) { limit := 10 out, _, err := dockerCmdWithError("search", fmt.Sprintf("--limit=%d", limit), "docker") - c.Assert(err, checker.IsNil) + assert.NilError(c, err) outSlice := strings.Split(out, "\n") - c.Assert(outSlice, checker.HasLen, limit+2) // 1 header, 1 carriage return + assert.Equal(c, len(outSlice), limit+2) // 1 header, 1 carriage return limit = 50 out, _, err = dockerCmdWithError("search", fmt.Sprintf("--limit=%d", limit), "docker") - c.Assert(err, checker.IsNil) + assert.NilError(c, err) outSlice = strings.Split(out, "\n") - c.Assert(outSlice, checker.HasLen, limit+2) // 1 header, 1 carriage return + assert.Equal(c, len(outSlice), limit+2) // 1 header, 1 carriage return limit = 100 out, _, err = dockerCmdWithError("search", fmt.Sprintf("--limit=%d", limit), "docker") - c.Assert(err, checker.IsNil) + assert.NilError(c, err) outSlice = strings.Split(out, "\n") - c.Assert(outSlice, checker.HasLen, limit+2) // 1 header, 1 carriage return + assert.Equal(c, len(outSlice), limit+2) // 1 header, 1 carriage return limit = 0 _, _, err = dockerCmdWithError("search", fmt.Sprintf("--limit=%d", limit), "docker") - c.Assert(err, checker.Not(checker.IsNil)) + assert.ErrorContains(c, err, "") limit = 200 _, _, err = dockerCmdWithError("search", fmt.Sprintf("--limit=%d", limit), "docker") - c.Assert(err, checker.Not(checker.IsNil)) + assert.ErrorContains(c, err, "") } diff --git a/components/engine/integration-cli/docker_cli_service_create_test.go b/components/engine/integration-cli/docker_cli_service_create_test.go index d00e15a0e3..f1d875b846 100644 --- a/components/engine/integration-cli/docker_cli_service_create_test.go +++ b/components/engine/integration-cli/docker_cli_service_create_test.go @@ -13,12 +13,13 @@ import ( "github.com/docker/docker/api/types/swarm" "github.com/docker/docker/integration-cli/checker" "github.com/go-check/check" + "gotest.tools/assert" ) func (s *DockerSwarmSuite) TestServiceCreateMountVolume(c *check.C) { d := s.AddDaemon(c, true, true) out, err := d.Cmd("service", "create", "--no-resolve-image", "--detach=true", "--mount", "type=volume,source=foo,target=/foo,volume-nocopy", "busybox", "top") - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) id := strings.TrimSpace(out) var tasks []swarm.Task @@ -37,7 +38,7 @@ func (s *DockerSwarmSuite) TestServiceCreateMountVolume(c *check.C) { // check container mount config out, err = s.nodeCmd(c, task.NodeID, "inspect", "--format", "{{json .HostConfig.Mounts}}", task.Status.ContainerStatus.ContainerID) - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) var mountConfig []mount.Mount c.Assert(json.Unmarshal([]byte(out), &mountConfig), checker.IsNil) @@ -51,7 +52,7 @@ func (s *DockerSwarmSuite) TestServiceCreateMountVolume(c *check.C) { // check container mounts actual out, err = s.nodeCmd(c, task.NodeID, "inspect", "--format", "{{json .Mounts}}", task.Status.ContainerStatus.ContainerID) - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) var mounts []types.MountPoint c.Assert(json.Unmarshal([]byte(out), &mounts), checker.IsNil) @@ -77,14 +78,14 @@ func (s *DockerSwarmSuite) TestServiceCreateWithSecretSimple(c *check.C) { c.Assert(id, checker.Not(checker.Equals), "", check.Commentf("secrets: %s", id)) out, err := d.Cmd("service", "create", "--detach", "--no-resolve-image", "--name", serviceName, "--secret", testName, "busybox", "top") - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) out, err = d.Cmd("service", "inspect", "--format", "{{ json .Spec.TaskTemplate.ContainerSpec.Secrets }}", serviceName) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) var refs []swarm.SecretReference c.Assert(json.Unmarshal([]byte(out), &refs), checker.IsNil) - c.Assert(refs, checker.HasLen, 1) + assert.Equal(c, len(refs), 1) c.Assert(refs[0].SecretName, checker.Equals, testName) c.Assert(refs[0].File, checker.Not(checker.IsNil)) @@ -93,7 +94,7 @@ func (s *DockerSwarmSuite) TestServiceCreateWithSecretSimple(c *check.C) { c.Assert(refs[0].File.GID, checker.Equals, "0") out, err = d.Cmd("service", "rm", serviceName) - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) d.DeleteSecret(c, testName) } @@ -126,14 +127,14 @@ func (s *DockerSwarmSuite) TestServiceCreateWithSecretSourceTargetPaths(c *check serviceCmd = append(serviceCmd, secretFlags...) serviceCmd = append(serviceCmd, "busybox", "top") out, err := d.Cmd(serviceCmd...) - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) out, err = d.Cmd("service", "inspect", "--format", "{{ json .Spec.TaskTemplate.ContainerSpec.Secrets }}", serviceName) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) var refs []swarm.SecretReference c.Assert(json.Unmarshal([]byte(out), &refs), checker.IsNil) - c.Assert(refs, checker.HasLen, len(testPaths)) + assert.Equal(c, len(refs), len(testPaths)) var tasks []swarm.Task waitAndAssert(c, defaultReconciliationTimeout, func(c *check.C) (interface{}, check.CommentInterface) { @@ -155,12 +156,12 @@ func (s *DockerSwarmSuite) TestServiceCreateWithSecretSourceTargetPaths(c *check path = filepath.Join("/run/secrets", path) } out, err := d.Cmd("exec", task.Status.ContainerStatus.ContainerID, "cat", path) - c.Assert(err, checker.IsNil) - c.Assert(out, checker.Equals, "TESTINGDATA "+testName+" "+testTarget) + assert.NilError(c, err) + assert.Equal(c, out, "TESTINGDATA "+testName+" "+testTarget) } out, err = d.Cmd("service", "rm", serviceName) - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) } func (s *DockerSwarmSuite) TestServiceCreateWithSecretReferencedTwice(c *check.C) { @@ -176,14 +177,14 @@ func (s *DockerSwarmSuite) TestServiceCreateWithSecretReferencedTwice(c *check.C serviceName := "svc" out, err := d.Cmd("service", "create", "--detach", "--no-resolve-image", "--name", serviceName, "--secret", "source=mysecret,target=target1", "--secret", "source=mysecret,target=target2", "busybox", "top") - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) out, err = d.Cmd("service", "inspect", "--format", "{{ json .Spec.TaskTemplate.ContainerSpec.Secrets }}", serviceName) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) var refs []swarm.SecretReference c.Assert(json.Unmarshal([]byte(out), &refs), checker.IsNil) - c.Assert(refs, checker.HasLen, 2) + assert.Equal(c, len(refs), 2) var tasks []swarm.Task waitAndAssert(c, defaultReconciliationTimeout, func(c *check.C) (interface{}, check.CommentInterface) { @@ -200,15 +201,15 @@ func (s *DockerSwarmSuite) TestServiceCreateWithSecretReferencedTwice(c *check.C }, checker.Equals, true) for _, target := range []string{"target1", "target2"} { - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) path := filepath.Join("/run/secrets", target) out, err := d.Cmd("exec", task.Status.ContainerStatus.ContainerID, "cat", path) - c.Assert(err, checker.IsNil) - c.Assert(out, checker.Equals, "TESTINGDATA") + assert.NilError(c, err) + assert.Equal(c, out, "TESTINGDATA") } out, err = d.Cmd("service", "rm", serviceName) - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) } func (s *DockerSwarmSuite) TestServiceCreateWithConfigSimple(c *check.C) { @@ -225,14 +226,14 @@ func (s *DockerSwarmSuite) TestServiceCreateWithConfigSimple(c *check.C) { c.Assert(id, checker.Not(checker.Equals), "", check.Commentf("configs: %s", id)) out, err := d.Cmd("service", "create", "--detach", "--no-resolve-image", "--name", serviceName, "--config", testName, "busybox", "top") - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) out, err = d.Cmd("service", "inspect", "--format", "{{ json .Spec.TaskTemplate.ContainerSpec.Configs }}", serviceName) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) var refs []swarm.ConfigReference c.Assert(json.Unmarshal([]byte(out), &refs), checker.IsNil) - c.Assert(refs, checker.HasLen, 1) + assert.Equal(c, len(refs), 1) c.Assert(refs[0].ConfigName, checker.Equals, testName) c.Assert(refs[0].File, checker.Not(checker.IsNil)) @@ -241,7 +242,7 @@ func (s *DockerSwarmSuite) TestServiceCreateWithConfigSimple(c *check.C) { c.Assert(refs[0].File.GID, checker.Equals, "0") out, err = d.Cmd("service", "rm", serviceName) - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) d.DeleteConfig(c, testName) } @@ -273,14 +274,14 @@ func (s *DockerSwarmSuite) TestServiceCreateWithConfigSourceTargetPaths(c *check serviceCmd = append(serviceCmd, configFlags...) serviceCmd = append(serviceCmd, "busybox", "top") out, err := d.Cmd(serviceCmd...) - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) out, err = d.Cmd("service", "inspect", "--format", "{{ json .Spec.TaskTemplate.ContainerSpec.Configs }}", serviceName) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) var refs []swarm.ConfigReference c.Assert(json.Unmarshal([]byte(out), &refs), checker.IsNil) - c.Assert(refs, checker.HasLen, len(testPaths)) + assert.Equal(c, len(refs), len(testPaths)) var tasks []swarm.Task waitAndAssert(c, defaultReconciliationTimeout, func(c *check.C) (interface{}, check.CommentInterface) { @@ -302,12 +303,12 @@ func (s *DockerSwarmSuite) TestServiceCreateWithConfigSourceTargetPaths(c *check path = filepath.Join("/", path) } out, err := d.Cmd("exec", task.Status.ContainerStatus.ContainerID, "cat", path) - c.Assert(err, checker.IsNil) - c.Assert(out, checker.Equals, "TESTINGDATA "+testName+" "+testTarget) + assert.NilError(c, err) + assert.Equal(c, out, "TESTINGDATA "+testName+" "+testTarget) } out, err = d.Cmd("service", "rm", serviceName) - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) } func (s *DockerSwarmSuite) TestServiceCreateWithConfigReferencedTwice(c *check.C) { @@ -323,14 +324,14 @@ func (s *DockerSwarmSuite) TestServiceCreateWithConfigReferencedTwice(c *check.C serviceName := "svc" out, err := d.Cmd("service", "create", "--detach", "--no-resolve-image", "--name", serviceName, "--config", "source=myconfig,target=target1", "--config", "source=myconfig,target=target2", "busybox", "top") - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) out, err = d.Cmd("service", "inspect", "--format", "{{ json .Spec.TaskTemplate.ContainerSpec.Configs }}", serviceName) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) var refs []swarm.ConfigReference c.Assert(json.Unmarshal([]byte(out), &refs), checker.IsNil) - c.Assert(refs, checker.HasLen, 2) + assert.Equal(c, len(refs), 2) var tasks []swarm.Task waitAndAssert(c, defaultReconciliationTimeout, func(c *check.C) (interface{}, check.CommentInterface) { @@ -347,21 +348,21 @@ func (s *DockerSwarmSuite) TestServiceCreateWithConfigReferencedTwice(c *check.C }, checker.Equals, true) for _, target := range []string{"target1", "target2"} { - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) path := filepath.Join("/", target) out, err := d.Cmd("exec", task.Status.ContainerStatus.ContainerID, "cat", path) - c.Assert(err, checker.IsNil) - c.Assert(out, checker.Equals, "TESTINGDATA") + assert.NilError(c, err) + assert.Equal(c, out, "TESTINGDATA") } out, err = d.Cmd("service", "rm", serviceName) - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) } func (s *DockerSwarmSuite) TestServiceCreateMountTmpfs(c *check.C) { d := s.AddDaemon(c, true, true) out, err := d.Cmd("service", "create", "--no-resolve-image", "--detach=true", "--mount", "type=tmpfs,target=/foo,tmpfs-size=1MB", "busybox", "sh", "-c", "mount | grep foo; tail -f /dev/null") - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) id := strings.TrimSpace(out) var tasks []swarm.Task @@ -380,7 +381,7 @@ func (s *DockerSwarmSuite) TestServiceCreateMountTmpfs(c *check.C) { // check container mount config out, err = s.nodeCmd(c, task.NodeID, "inspect", "--format", "{{json .HostConfig.Mounts}}", task.Status.ContainerStatus.ContainerID) - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) var mountConfig []mount.Mount c.Assert(json.Unmarshal([]byte(out), &mountConfig), checker.IsNil) @@ -394,7 +395,7 @@ func (s *DockerSwarmSuite) TestServiceCreateMountTmpfs(c *check.C) { // check container mounts actual out, err = s.nodeCmd(c, task.NodeID, "inspect", "--format", "{{json .Mounts}}", task.Status.ContainerStatus.ContainerID) - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) var mounts []types.MountPoint c.Assert(json.Unmarshal([]byte(out), &mounts), checker.IsNil) @@ -406,18 +407,18 @@ func (s *DockerSwarmSuite) TestServiceCreateMountTmpfs(c *check.C) { c.Assert(mounts[0].RW, checker.Equals, true) out, err = s.nodeCmd(c, task.NodeID, "logs", task.Status.ContainerStatus.ContainerID) - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) - c.Assert(strings.TrimSpace(out), checker.HasPrefix, "tmpfs on /foo type tmpfs") - c.Assert(strings.TrimSpace(out), checker.Contains, "size=1024k") + assert.NilError(c, err, out) + assert.Assert(c, strings.HasPrefix(strings.TrimSpace(out), "tmpfs on /foo type tmpfs")) + assert.Assert(c, strings.Contains(strings.TrimSpace(out), "size=1024k")) } func (s *DockerSwarmSuite) TestServiceCreateWithNetworkAlias(c *check.C) { d := s.AddDaemon(c, true, true) out, err := d.Cmd("network", "create", "--scope=swarm", "test_swarm_br") - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) out, err = d.Cmd("service", "create", "--no-resolve-image", "--detach=true", "--network=name=test_swarm_br,alias=srv_alias", "--name=alias_tst_container", "busybox", "top") - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) id := strings.TrimSpace(out) var tasks []swarm.Task @@ -436,7 +437,7 @@ func (s *DockerSwarmSuite) TestServiceCreateWithNetworkAlias(c *check.C) { // check container alias config out, err = s.nodeCmd(c, task.NodeID, "inspect", "--format", "{{json .NetworkSettings.Networks.test_swarm_br.Aliases}}", task.Status.ContainerStatus.ContainerID) - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) // Make sure the only alias seen is the container-id var aliases []string diff --git a/components/engine/integration-cli/docker_cli_service_health_test.go b/components/engine/integration-cli/docker_cli_service_health_test.go index 994ee77b99..8f6a69b0bc 100644 --- a/components/engine/integration-cli/docker_cli_service_health_test.go +++ b/components/engine/integration-cli/docker_cli_service_health_test.go @@ -12,6 +12,7 @@ import ( "github.com/docker/docker/integration-cli/cli" "github.com/docker/docker/integration-cli/cli/build" "github.com/go-check/check" + "gotest.tools/assert" "gotest.tools/icmd" ) @@ -34,7 +35,7 @@ func (s *DockerSwarmSuite) TestServiceHealthRun(c *check.C) { serviceName := "healthServiceRun" out, err := d.Cmd("service", "create", "--no-resolve-image", "--detach=true", "--name", serviceName, imageName, "top") - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) id := strings.TrimSpace(out) var tasks []swarm.Task @@ -95,7 +96,7 @@ func (s *DockerSwarmSuite) TestServiceHealthStart(c *check.C) { serviceName := "healthServiceStart" out, err := d.Cmd("service", "create", "--no-resolve-image", "--detach=true", "--name", serviceName, imageName, "top") - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) id := strings.TrimSpace(out) var tasks []swarm.Task diff --git a/components/engine/integration-cli/docker_cli_service_logs_test.go b/components/engine/integration-cli/docker_cli_service_logs_test.go index ba337491b1..d85286676e 100644 --- a/components/engine/integration-cli/docker_cli_service_logs_test.go +++ b/components/engine/integration-cli/docker_cli_service_logs_test.go @@ -13,6 +13,7 @@ import ( "github.com/docker/docker/integration-cli/checker" "github.com/docker/docker/integration-cli/daemon" "github.com/go-check/check" + "gotest.tools/assert" "gotest.tools/icmd" ) @@ -33,8 +34,8 @@ func (s *DockerSwarmSuite) TestServiceLogs(c *check.C) { for name, message := range services { out, err := d.Cmd("service", "create", "--detach", "--no-resolve-image", "--name", name, "busybox", "sh", "-c", fmt.Sprintf("echo %s; tail -f /dev/null", message)) - c.Assert(err, checker.IsNil) - c.Assert(strings.TrimSpace(out), checker.Not(checker.Equals), "") + assert.NilError(c, err) + assert.Assert(c, strings.TrimSpace(out) != "") } // make sure task has been deployed. @@ -44,9 +45,9 @@ func (s *DockerSwarmSuite) TestServiceLogs(c *check.C) { for name, message := range services { out, err := d.Cmd("service", "logs", name) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) c.Logf("log for %q: %q", name, out) - c.Assert(out, checker.Contains, message) + assert.Assert(c, strings.Contains(out, message)) } } @@ -75,8 +76,8 @@ func (s *DockerSwarmSuite) TestServiceLogsCompleteness(c *check.C) { // make a service that prints 6 lines out, err := d.Cmd("service", "create", "--detach", "--no-resolve-image", "--name", name, "busybox", "sh", "-c", "for line in $(seq 0 5); do echo log test $line; done; sleep 100000") - c.Assert(err, checker.IsNil) - c.Assert(strings.TrimSpace(out), checker.Not(checker.Equals), "") + assert.NilError(c, err) + assert.Assert(c, strings.TrimSpace(out) != "") // make sure task has been deployed. waitAndAssert(c, defaultReconciliationTimeout, d.CheckActiveContainerCount, checker.Equals, 1) @@ -84,14 +85,14 @@ func (s *DockerSwarmSuite) TestServiceLogsCompleteness(c *check.C) { waitAndAssert(c, defaultReconciliationTimeout, countLogLines(d, name), checker.Equals, 6) out, err = d.Cmd("service", "logs", name) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) lines := strings.Split(strings.TrimSpace(out), "\n") // i have heard anecdotal reports that logs may come back from the engine // mis-ordered. if this tests fails, consider the possibility that that // might be occurring for i, line := range lines { - c.Assert(line, checker.Contains, fmt.Sprintf("log test %v", i)) + assert.Assert(c, strings.Contains(line, fmt.Sprintf("log test %v", i))) } } @@ -102,20 +103,20 @@ func (s *DockerSwarmSuite) TestServiceLogsTail(c *check.C) { // make a service that prints 6 lines out, err := d.Cmd("service", "create", "--detach", "--no-resolve-image", "--name", name, "busybox", "sh", "-c", "for line in $(seq 1 6); do echo log test $line; done; sleep 100000") - c.Assert(err, checker.IsNil) - c.Assert(strings.TrimSpace(out), checker.Not(checker.Equals), "") + assert.NilError(c, err) + assert.Assert(c, strings.TrimSpace(out) != "") // make sure task has been deployed. waitAndAssert(c, defaultReconciliationTimeout, d.CheckActiveContainerCount, checker.Equals, 1) waitAndAssert(c, defaultReconciliationTimeout, countLogLines(d, name), checker.Equals, 6) out, err = d.Cmd("service", "logs", "--tail=2", name) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) lines := strings.Split(strings.TrimSpace(out), "\n") for i, line := range lines { // doing i+5 is hacky but not too fragile, it's good enough. if it flakes something else is wrong - c.Assert(line, checker.Contains, fmt.Sprintf("log test %v", i+5)) + assert.Assert(c, strings.Contains(line, fmt.Sprintf("log test %v", i+5))) } } @@ -126,31 +127,31 @@ func (s *DockerSwarmSuite) TestServiceLogsSince(c *check.C) { name := "TestServiceLogsSince" out, err := d.Cmd("service", "create", "--detach", "--no-resolve-image", "--name", name, "busybox", "sh", "-c", "for i in $(seq 1 3); do sleep .1; echo log$i; done; sleep 10000000") - c.Assert(err, checker.IsNil) - c.Assert(strings.TrimSpace(out), checker.Not(checker.Equals), "") + assert.NilError(c, err) + assert.Assert(c, strings.TrimSpace(out) != "") waitAndAssert(c, defaultReconciliationTimeout, d.CheckActiveContainerCount, checker.Equals, 1) // wait a sec for the logs to come in waitAndAssert(c, defaultReconciliationTimeout, countLogLines(d, name), checker.Equals, 3) out, err = d.Cmd("service", "logs", "-t", name) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) log2Line := strings.Split(strings.Split(out, "\n")[1], " ") t, err := time.Parse(time.RFC3339Nano, log2Line[0]) // timestamp log2 is written - c.Assert(err, checker.IsNil) + assert.NilError(c, err) u := t.Add(50 * time.Millisecond) // add .05s so log1 & log2 don't show up since := u.Format(time.RFC3339Nano) out, err = d.Cmd("service", "logs", "-t", fmt.Sprintf("--since=%v", since), name) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) unexpected := []string{"log1", "log2"} expected := []string{"log3"} for _, v := range unexpected { - c.Assert(out, checker.Not(checker.Contains), v, check.Commentf("unexpected log message returned, since=%v", u)) + assert.Assert(c, !strings.Contains(out, v), "unexpected log message returned, since=%v", u) } for _, v := range expected { - c.Assert(out, checker.Contains, v, check.Commentf("expected log message %v, was not present, since=%v", u)) + assert.Assert(c, strings.Contains(out, v), "expected log message %v, was not present, since=%v", u) } } @@ -160,8 +161,8 @@ func (s *DockerSwarmSuite) TestServiceLogsFollow(c *check.C) { name := "TestServiceLogsFollow" out, err := d.Cmd("service", "create", "--detach", "--no-resolve-image", "--name", name, "busybox", "sh", "-c", "while true; do echo log test; sleep 0.1; done") - c.Assert(err, checker.IsNil) - c.Assert(strings.TrimSpace(out), checker.Not(checker.Equals), "") + assert.NilError(c, err) + assert.Assert(c, strings.TrimSpace(out) != "") // make sure task has been deployed. waitAndAssert(c, defaultReconciliationTimeout, d.CheckActiveContainerCount, checker.Equals, 1) @@ -171,7 +172,7 @@ func (s *DockerSwarmSuite) TestServiceLogsFollow(c *check.C) { r, w := io.Pipe() cmd.Stdout = w cmd.Stderr = w - c.Assert(cmd.Start(), checker.IsNil) + assert.NilError(c, cmd.Start()) go cmd.Wait() // Make sure pipe is written to @@ -192,12 +193,12 @@ func (s *DockerSwarmSuite) TestServiceLogsFollow(c *check.C) { for i := 0; i < 3; i++ { msg := <-ch - c.Assert(msg.err, checker.IsNil) - c.Assert(string(msg.data), checker.Contains, "log test") + assert.NilError(c, msg.err) + assert.Assert(c, strings.Contains(string(msg.data), "log test")) } close(done) - c.Assert(cmd.Process.Kill(), checker.IsNil) + assert.NilError(c, cmd.Process.Kill()) } func (s *DockerSwarmSuite) TestServiceLogsTaskLogs(c *check.C) { @@ -220,7 +221,7 @@ func (s *DockerSwarmSuite) TestServiceLogsTaskLogs(c *check.C) { // ^^ verify that we get no error // then verify that we have an id in stdout id := strings.TrimSpace(result.Stdout()) - c.Assert(id, checker.Not(checker.Equals), "") + assert.Assert(c, id != "") // so, right here, we're basically inspecting by id and returning only // the ID. if they don't match, the service doesn't exist. result = icmd.RunCmd(d.Command("service", "inspect", "--format=\"{{.ID}}\"", id)) @@ -235,7 +236,7 @@ func (s *DockerSwarmSuite) TestServiceLogsTaskLogs(c *check.C) { result.Assert(c, icmd.Expected{}) // make sure we have two tasks taskIDs := strings.Split(strings.TrimSpace(result.Stdout()), "\n") - c.Assert(taskIDs, checker.HasLen, replicas) + assert.Equal(c, len(taskIDs), replicas) for _, taskID := range taskIDs { c.Logf("checking task %v", taskID) @@ -246,9 +247,9 @@ func (s *DockerSwarmSuite) TestServiceLogsTaskLogs(c *check.C) { c.Logf("checking messages for %v", taskID) for i, line := range lines { // make sure the message is in order - c.Assert(line, checker.Contains, fmt.Sprintf("log test %v", i)) + assert.Assert(c, strings.Contains(line, fmt.Sprintf("log test %v", i))) // make sure it contains the task id - c.Assert(line, checker.Contains, taskID) + assert.Assert(c, strings.Contains(line, taskID)) } } } @@ -273,7 +274,7 @@ func (s *DockerSwarmSuite) TestServiceLogsTTY(c *check.C) { result.Assert(c, icmd.Expected{}) id := strings.TrimSpace(result.Stdout()) - c.Assert(id, checker.Not(checker.Equals), "") + assert.Assert(c, id != "") // so, right here, we're basically inspecting by id and returning only // the ID. if they don't match, the service doesn't exist. result = icmd.RunCmd(d.Command("service", "inspect", "--format=\"{{.ID}}\"", id)) @@ -311,7 +312,7 @@ func (s *DockerSwarmSuite) TestServiceLogsNoHangDeletedContainer(c *check.C) { result.Assert(c, icmd.Expected{}) // get the service id id := strings.TrimSpace(result.Stdout()) - c.Assert(id, checker.Not(checker.Equals), "") + assert.Assert(c, id != "") // make sure task has been deployed. waitAndAssert(c, defaultReconciliationTimeout, d.CheckActiveContainerCount, checker.Equals, 1) @@ -321,7 +322,7 @@ func (s *DockerSwarmSuite) TestServiceLogsNoHangDeletedContainer(c *check.C) { // now find and nuke the container result = icmd.RunCmd(d.Command("ps", "-q")) containerID := strings.TrimSpace(result.Stdout()) - c.Assert(containerID, checker.Not(checker.Equals), "") + assert.Assert(c, containerID != "") result = icmd.RunCmd(d.Command("stop", containerID)) result.Assert(c, icmd.Expected{Out: containerID}) result = icmd.RunCmd(d.Command("rm", containerID)) @@ -364,7 +365,7 @@ func (s *DockerSwarmSuite) TestServiceLogsDetails(c *check.C) { result.Assert(c, icmd.Expected{}) id := strings.TrimSpace(result.Stdout()) - c.Assert(id, checker.Not(checker.Equals), "") + assert.Assert(c, id != "") // make sure task has been deployed waitAndAssert(c, defaultReconciliationTimeout, d.CheckActiveContainerCount, checker.Equals, 1) diff --git a/components/engine/integration-cli/docker_cli_service_scale_test.go b/components/engine/integration-cli/docker_cli_service_scale_test.go index ad045ee570..f02bc738aa 100644 --- a/components/engine/integration-cli/docker_cli_service_scale_test.go +++ b/components/engine/integration-cli/docker_cli_service_scale_test.go @@ -6,8 +6,8 @@ import ( "fmt" "strings" - "github.com/docker/docker/integration-cli/checker" "github.com/go-check/check" + "gotest.tools/assert" ) func (s *DockerSwarmSuite) TestServiceScale(c *check.C) { @@ -22,16 +22,16 @@ func (s *DockerSwarmSuite) TestServiceScale(c *check.C) { // Create services _, err := d.Cmd(service1Args...) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) _, err = d.Cmd(service2Args...) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) _, err = d.Cmd("service", "scale", "TestService1=2") - c.Assert(err, checker.IsNil) + assert.NilError(c, err) out, err := d.Cmd("service", "scale", "TestService1=foobar") - c.Assert(err, checker.NotNil) + assert.ErrorContains(c, err, "") str := fmt.Sprintf("%s: invalid replicas value %s", service1Name, "foobar") if !strings.Contains(out, str) { @@ -39,7 +39,7 @@ func (s *DockerSwarmSuite) TestServiceScale(c *check.C) { } out, err = d.Cmd("service", "scale", "TestService1=-1") - c.Assert(err, checker.NotNil) + assert.ErrorContains(c, err, "") str = fmt.Sprintf("%s: invalid replicas value %s", service1Name, "-1") if !strings.Contains(out, str) { @@ -48,7 +48,7 @@ func (s *DockerSwarmSuite) TestServiceScale(c *check.C) { // TestService2 is a global mode out, err = d.Cmd("service", "scale", "TestService2=2") - c.Assert(err, checker.NotNil) + assert.ErrorContains(c, err, "") str = fmt.Sprintf("%s: scale can only be used with replicated mode\n", service2Name) if out != str { diff --git a/components/engine/integration-cli/docker_cli_sni_test.go b/components/engine/integration-cli/docker_cli_sni_test.go index f50b5bbf6d..e64911de42 100644 --- a/components/engine/integration-cli/docker_cli_sni_test.go +++ b/components/engine/integration-cli/docker_cli_sni_test.go @@ -11,6 +11,7 @@ import ( "strings" "github.com/go-check/check" + "gotest.tools/assert" ) func (s *DockerSuite) TestClientSetsTLSServerName(c *check.C) { @@ -27,7 +28,7 @@ func (s *DockerSuite) TestClientSetsTLSServerName(c *check.C) { virtualHostServer.Config.ErrorLog = log.New(ioutil.Discard, "", 0) u, err := url.Parse(virtualHostServer.URL) - c.Assert(err, check.IsNil) + assert.NilError(c, err) hostPort := u.Host serverName = strings.Split(hostPort, ":")[0] @@ -36,9 +37,9 @@ func (s *DockerSuite) TestClientSetsTLSServerName(c *check.C) { cmd.Run() // check that the fake server was hit at least once - c.Assert(len(serverNameReceived) > 0, check.Equals, true) + assert.Assert(c, len(serverNameReceived) > 0) // check that for each hit the right server name was received for _, item := range serverNameReceived { - c.Check(item, check.Equals, serverName) + assert.Check(c, item == serverName) } } diff --git a/components/engine/integration-cli/docker_cli_start_test.go b/components/engine/integration-cli/docker_cli_start_test.go index 303deddb28..dfaf0721d2 100644 --- a/components/engine/integration-cli/docker_cli_start_test.go +++ b/components/engine/integration-cli/docker_cli_start_test.go @@ -8,6 +8,7 @@ import ( "github.com/docker/docker/integration-cli/checker" "github.com/docker/docker/integration-cli/cli" "github.com/go-check/check" + "gotest.tools/assert" "gotest.tools/icmd" ) @@ -34,7 +35,7 @@ func (s *DockerSuite) TestStartAttachReturnsOnError(c *check.C) { select { case err := <-ch: - c.Assert(err, check.IsNil) + assert.NilError(c, err) case <-time.After(5 * time.Second): c.Fatalf("Attach did not exit properly") } @@ -121,7 +122,7 @@ func (s *DockerSuite) TestStartMultipleContainers(c *check.C) { out := inspectField(c, "parent", "State.Running") // Container should be stopped - c.Assert(out, checker.Equals, "false") + assert.Equal(c, out, "false") // start all the three containers, container `child_first` start first which should be failed // container 'parent' start second and then start container 'child_second' @@ -138,7 +139,7 @@ func (s *DockerSuite) TestStartMultipleContainers(c *check.C) { for container, expected := range map[string]string{"parent": "true", "child_first": "false", "child_second": "true"} { out := inspectField(c, container, "State.Running") // Container running state wrong - c.Assert(out, checker.Equals, expected) + assert.Equal(c, out, expected) } } @@ -166,7 +167,7 @@ func (s *DockerSuite) TestStartAttachMultipleContainers(c *check.C) { for container, expected := range map[string]string{"test1": "false", "test2": "false", "test3": "false"} { out := inspectField(c, container, "State.Running") // Container running state wrong - c.Assert(out, checker.Equals, expected) + assert.Equal(c, out, expected) } } @@ -191,10 +192,10 @@ func (s *DockerSuite) TestStartReturnCorrectExitCode(c *check.C) { dockerCmd(c, "create", "--rm", "--name", "withRm", "busybox", "sh", "-c", "exit 12") out, exitCode, err := dockerCmdWithError("start", "-a", "withRestart") - c.Assert(err, checker.NotNil) + assert.ErrorContains(c, err, "") c.Assert(exitCode, checker.Equals, 11, check.Commentf("out: %s", out)) out, exitCode, err = dockerCmdWithError("start", "-a", "withRm") - c.Assert(err, checker.NotNil) + assert.ErrorContains(c, err, "") c.Assert(exitCode, checker.Equals, 12, check.Commentf("out: %s", out)) } diff --git a/components/engine/integration-cli/docker_cli_stats_test.go b/components/engine/integration-cli/docker_cli_stats_test.go index 454836367f..c21b730506 100644 --- a/components/engine/integration-cli/docker_cli_stats_test.go +++ b/components/engine/integration-cli/docker_cli_stats_test.go @@ -7,9 +7,10 @@ import ( "strings" "time" - "github.com/docker/docker/integration-cli/checker" "github.com/docker/docker/integration-cli/cli" "github.com/go-check/check" + "gotest.tools/assert" + is "gotest.tools/assert/cmp" ) func (s *DockerSuite) TestStatsNoStream(c *check.C) { @@ -17,7 +18,7 @@ func (s *DockerSuite) TestStatsNoStream(c *check.C) { testRequires(c, DaemonIsLinux) out, _ := dockerCmd(c, "run", "-d", "busybox", "top") id := strings.TrimSpace(out) - c.Assert(waitRun(id), checker.IsNil) + assert.NilError(c, waitRun(id)) statsCmd := exec.Command(dockerBinary, "stats", "--no-stream", id) type output struct { @@ -33,8 +34,8 @@ func (s *DockerSuite) TestStatsNoStream(c *check.C) { select { case outerr := <-ch: - c.Assert(outerr.err, checker.IsNil, check.Commentf("Error running stats: %v", outerr.err)) - c.Assert(string(outerr.out), checker.Contains, id[:12]) //running container wasn't present in output + assert.NilError(c, outerr.err, "Error running stats: %v", outerr.err) + assert.Assert(c, is.Contains(string(outerr.out), id[:12]), "running container wasn't present in output") case <-time.After(3 * time.Second): statsCmd.Process.Kill() c.Fatalf("stats did not return immediately when not streaming") @@ -46,12 +47,12 @@ func (s *DockerSuite) TestStatsContainerNotFound(c *check.C) { testRequires(c, DaemonIsLinux) out, _, err := dockerCmdWithError("stats", "notfound") - c.Assert(err, checker.NotNil) - c.Assert(out, checker.Contains, "No such container: notfound", check.Commentf("Expected to fail on not found container stats, got %q instead", out)) + assert.ErrorContains(c, err, "") + assert.Assert(c, is.Contains(out, "No such container: notfound"), "Expected to fail on not found container stats, got %q instead", out) out, _, err = dockerCmdWithError("stats", "--no-stream", "notfound") - c.Assert(err, checker.NotNil) - c.Assert(out, checker.Contains, "No such container: notfound", check.Commentf("Expected to fail on not found container stats with --no-stream, got %q instead", out)) + assert.ErrorContains(c, err, "") + assert.Assert(c, is.Contains(out, "No such container: notfound"), "Expected to fail on not found container stats with --no-stream, got %q instead", out) } func (s *DockerSuite) TestStatsAllRunningNoStream(c *check.C) { @@ -60,13 +61,13 @@ func (s *DockerSuite) TestStatsAllRunningNoStream(c *check.C) { out, _ := dockerCmd(c, "run", "-d", "busybox", "top") id1 := strings.TrimSpace(out)[:12] - c.Assert(waitRun(id1), check.IsNil) + assert.NilError(c, waitRun(id1)) out, _ = dockerCmd(c, "run", "-d", "busybox", "top") id2 := strings.TrimSpace(out)[:12] - c.Assert(waitRun(id2), check.IsNil) + assert.NilError(c, waitRun(id2)) out, _ = dockerCmd(c, "run", "-d", "busybox", "top") id3 := strings.TrimSpace(out)[:12] - c.Assert(waitRun(id3), check.IsNil) + assert.NilError(c, waitRun(id3)) dockerCmd(c, "stop", id3) out, _ = dockerCmd(c, "stats", "--no-stream") @@ -84,10 +85,10 @@ func (s *DockerSuite) TestStatsAllRunningNoStream(c *check.C) { outLines := strings.Split(out, "\n") // check stat result of id2 contains real data realData := reg.Find([]byte(outLines[1][12:])) - c.Assert(realData, checker.NotNil, check.Commentf("stat result are empty: %s", out)) + assert.Assert(c, realData != nil, "stat result are empty: %s", out) // check stat result of id1 contains real data realData = reg.Find([]byte(outLines[2][12:])) - c.Assert(realData, checker.NotNil, check.Commentf("stat result are empty: %s", out)) + assert.Assert(c, realData != nil, "stat result are empty: %s", out) } func (s *DockerSuite) TestStatsAllNoStream(c *check.C) { @@ -96,11 +97,11 @@ func (s *DockerSuite) TestStatsAllNoStream(c *check.C) { out, _ := dockerCmd(c, "run", "-d", "busybox", "top") id1 := strings.TrimSpace(out)[:12] - c.Assert(waitRun(id1), check.IsNil) + assert.NilError(c, waitRun(id1)) dockerCmd(c, "stop", id1) out, _ = dockerCmd(c, "run", "-d", "busybox", "top") id2 := strings.TrimSpace(out)[:12] - c.Assert(waitRun(id2), check.IsNil) + assert.NilError(c, waitRun(id2)) out, _ = dockerCmd(c, "stats", "--all", "--no-stream") if !strings.Contains(out, id1) || !strings.Contains(out, id2) { @@ -113,10 +114,11 @@ func (s *DockerSuite) TestStatsAllNoStream(c *check.C) { outLines := strings.Split(out, "\n") // check stat result of id2 contains real data realData := reg.Find([]byte(outLines[1][12:])) - c.Assert(realData, checker.NotNil, check.Commentf("stat result of %s is empty: %s", id2, out)) + assert.Assert(c, realData != nil, "stat result of %s is empty: %s", id2, out) + // check stat result of id1 contains all zero realData = reg.Find([]byte(outLines[2][12:])) - c.Assert(realData, checker.IsNil, check.Commentf("stat result of %s should be empty : %s", id1, out)) + assert.Assert(c, realData == nil, "stat result of %s should be empty : %s", id1, out) } func (s *DockerSuite) TestStatsAllNewContainersAdded(c *check.C) { @@ -129,8 +131,8 @@ func (s *DockerSuite) TestStatsAllNewContainersAdded(c *check.C) { runSleepingContainer(c, "-d") statsCmd := exec.Command(dockerBinary, "stats") stdout, err := statsCmd.StdoutPipe() - c.Assert(err, check.IsNil) - c.Assert(statsCmd.Start(), check.IsNil) + assert.NilError(c, err) + assert.NilError(c, statsCmd.Start()) go statsCmd.Wait() defer statsCmd.Process.Kill() @@ -149,7 +151,7 @@ func (s *DockerSuite) TestStatsAllNewContainersAdded(c *check.C) { }() out := runSleepingContainer(c, "-d") - c.Assert(waitRun(strings.TrimSpace(out)), check.IsNil) + assert.NilError(c, waitRun(strings.TrimSpace(out))) id <- strings.TrimSpace(out)[:12] select { @@ -171,10 +173,10 @@ func (s *DockerSuite) TestStatsFormatAll(c *check.C) { cli.WaitExited(c, "ExitedOne", 5*time.Second) out := cli.DockerCmd(c, "stats", "--no-stream", "--format", "{{.Name}}").Combined() - c.Assert(out, checker.Contains, "RunningOne") - c.Assert(out, checker.Not(checker.Contains), "ExitedOne") + assert.Assert(c, is.Contains(out, "RunningOne")) + assert.Assert(c, !strings.Contains(out, "ExitedOne")) out = cli.DockerCmd(c, "stats", "--all", "--no-stream", "--format", "{{.Name}}").Combined() - c.Assert(out, checker.Contains, "RunningOne") - c.Assert(out, checker.Contains, "ExitedOne") + assert.Assert(c, is.Contains(out, "RunningOne")) + assert.Assert(c, is.Contains(out, "ExitedOne")) } diff --git a/components/engine/integration-cli/docker_cli_swarm_test.go b/components/engine/integration-cli/docker_cli_swarm_test.go index e2b3954dcb..1b20cbf95d 100644 --- a/components/engine/integration-cli/docker_cli_swarm_test.go +++ b/components/engine/integration-cli/docker_cli_swarm_test.go @@ -29,6 +29,7 @@ import ( "github.com/docker/swarmkit/ca/keyutils" "github.com/go-check/check" "github.com/vishvananda/netlink" + "gotest.tools/assert" "gotest.tools/fs" "gotest.tools/icmd" ) @@ -42,7 +43,7 @@ func (s *DockerSwarmSuite) TestSwarmUpdate(c *check.C) { } out, err := d.Cmd("swarm", "update", "--cert-expiry", "30h", "--dispatcher-heartbeat", "11s") - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) spec := getSpec() c.Assert(spec.CAConfig.NodeCertExpiry, checker.Equals, 30*time.Hour) @@ -50,7 +51,7 @@ func (s *DockerSwarmSuite) TestSwarmUpdate(c *check.C) { // setting anything under 30m for cert-expiry is not allowed out, err = d.Cmd("swarm", "update", "--cert-expiry", "15m") - c.Assert(err, checker.NotNil) + assert.ErrorContains(c, err, "") c.Assert(out, checker.Contains, "minimum certificate expiry time") spec = getSpec() c.Assert(spec.CAConfig.NodeCertExpiry, checker.Equals, 30*time.Hour) @@ -61,7 +62,7 @@ func (s *DockerSwarmSuite) TestSwarmUpdate(c *check.C) { cli.Daemon(d)).Assert(c, icmd.Success) expected, err := ioutil.ReadFile("fixtures/https/ca.pem") - c.Assert(err, checker.IsNil) + assert.NilError(c, err) spec = getSpec() c.Assert(spec.CAConfig.ExternalCAs, checker.HasLen, 2) @@ -107,7 +108,7 @@ func (s *DockerSwarmSuite) TestSwarmInit(c *check.C) { cli.Daemon(d)).Assert(c, icmd.Success) expected, err := ioutil.ReadFile("fixtures/https/ca.pem") - c.Assert(err, checker.IsNil) + assert.NilError(c, err) spec := getSpec() c.Assert(spec.CAConfig.NodeCertExpiry, checker.Equals, 30*time.Hour) @@ -139,7 +140,7 @@ func (s *DockerSwarmSuite) TestSwarmInitIPv6(c *check.C) { func (s *DockerSwarmSuite) TestSwarmInitUnspecifiedAdvertiseAddr(c *check.C) { d := s.AddDaemon(c, false, false) out, err := d.Cmd("swarm", "init", "--advertise-addr", "0.0.0.0") - c.Assert(err, checker.NotNil) + assert.ErrorContains(c, err, "") c.Assert(out, checker.Contains, "advertise address must be a non-zero IP address") } @@ -147,21 +148,21 @@ func (s *DockerSwarmSuite) TestSwarmIncompatibleDaemon(c *check.C) { // init swarm mode and stop a daemon d := s.AddDaemon(c, true, true) info := d.SwarmInfo(c) - c.Assert(info.LocalNodeState, checker.Equals, swarm.LocalNodeStateActive) + assert.Equal(c, info.LocalNodeState, swarm.LocalNodeStateActive) d.Stop(c) // start a daemon with --cluster-store and --cluster-advertise err := d.StartWithError("--cluster-store=consul://consuladdr:consulport/some/path", "--cluster-advertise=1.1.1.1:2375") - c.Assert(err, checker.NotNil) + assert.ErrorContains(c, err, "") content, err := d.ReadLogFile() - c.Assert(err, checker.IsNil) + assert.NilError(c, err) c.Assert(string(content), checker.Contains, "--cluster-store and --cluster-advertise daemon configurations are incompatible with swarm mode") // start a daemon with --live-restore err = d.StartWithError("--live-restore") - c.Assert(err, checker.NotNil) + assert.ErrorContains(c, err, "") content, err = d.ReadLogFile() - c.Assert(err, checker.IsNil) + assert.NilError(c, err) c.Assert(string(content), checker.Contains, "--live-restore daemon configuration is incompatible with swarm mode") // restart for teardown d.StartNode(c) @@ -173,14 +174,14 @@ func (s *DockerSwarmSuite) TestSwarmServiceTemplatingHostname(c *check.C) { c.Assert(err, checker.IsNil, check.Commentf("%s", hostname)) out, err := d.Cmd("service", "create", "--detach", "--no-resolve-image", "--name", "test", "--hostname", "{{.Service.Name}}-{{.Task.Slot}}-{{.Node.Hostname}}", "busybox", "top") - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) // make sure task has been deployed. waitAndAssert(c, defaultReconciliationTimeout, d.CheckActiveContainerCount, checker.Equals, 1) containers := d.ActiveContainers(c) out, err = d.Cmd("inspect", "--type", "container", "--format", "{{.Config.Hostname}}", containers[0]) - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) c.Assert(strings.Split(out, "\n")[0], checker.Equals, "test-1-"+strings.Split(hostname, "\n")[0], check.Commentf("hostname with templating invalid")) } @@ -192,35 +193,35 @@ func (s *DockerSwarmSuite) TestSwarmServiceListFilter(c *check.C) { name2 := "redis-cluster" name3 := "other-cluster" out, err := d.Cmd("service", "create", "--detach", "--no-resolve-image", "--name", name1, "busybox", "top") - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) - c.Assert(strings.TrimSpace(out), checker.Not(checker.Equals), "") + assert.NilError(c, err, out) + assert.Assert(c, strings.TrimSpace(out) != "") out, err = d.Cmd("service", "create", "--detach", "--no-resolve-image", "--name", name2, "busybox", "top") - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) - c.Assert(strings.TrimSpace(out), checker.Not(checker.Equals), "") + assert.NilError(c, err, out) + assert.Assert(c, strings.TrimSpace(out) != "") out, err = d.Cmd("service", "create", "--detach", "--no-resolve-image", "--name", name3, "busybox", "top") - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) - c.Assert(strings.TrimSpace(out), checker.Not(checker.Equals), "") + assert.NilError(c, err, out) + assert.Assert(c, strings.TrimSpace(out) != "") filter1 := "name=redis-cluster-md5" filter2 := "name=redis-cluster" // We search checker.Contains with `name+" "` to prevent prefix only. out, err = d.Cmd("service", "ls", "--filter", filter1) - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) c.Assert(out, checker.Contains, name1+" ") c.Assert(out, checker.Not(checker.Contains), name2+" ") c.Assert(out, checker.Not(checker.Contains), name3+" ") out, err = d.Cmd("service", "ls", "--filter", filter2) - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) c.Assert(out, checker.Contains, name1+" ") c.Assert(out, checker.Contains, name2+" ") c.Assert(out, checker.Not(checker.Contains), name3+" ") out, err = d.Cmd("service", "ls") - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) c.Assert(out, checker.Contains, name1+" ") c.Assert(out, checker.Contains, name2+" ") c.Assert(out, checker.Contains, name3+" ") @@ -230,18 +231,18 @@ func (s *DockerSwarmSuite) TestSwarmNodeListFilter(c *check.C) { d := s.AddDaemon(c, true, true) out, err := d.Cmd("node", "inspect", "--format", "{{ .Description.Hostname }}", "self") - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) - c.Assert(strings.TrimSpace(out), checker.Not(checker.Equals), "") + assert.NilError(c, err, out) + assert.Assert(c, strings.TrimSpace(out) != "") name := strings.TrimSpace(out) filter := "name=" + name[:4] out, err = d.Cmd("node", "ls", "--filter", filter) - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) c.Assert(out, checker.Contains, name) out, err = d.Cmd("node", "ls", "--filter", "name=none") - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) c.Assert(out, checker.Not(checker.Contains), name) } @@ -250,8 +251,8 @@ func (s *DockerSwarmSuite) TestSwarmNodeTaskListFilter(c *check.C) { name := "redis-cluster-md5" out, err := d.Cmd("service", "create", "--detach", "--no-resolve-image", "--name", name, "--replicas=3", "busybox", "top") - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) - c.Assert(strings.TrimSpace(out), checker.Not(checker.Equals), "") + assert.NilError(c, err, out) + assert.Assert(c, strings.TrimSpace(out) != "") // make sure task has been deployed. waitAndAssert(c, defaultReconciliationTimeout, d.CheckActiveContainerCount, checker.Equals, 3) @@ -259,13 +260,13 @@ func (s *DockerSwarmSuite) TestSwarmNodeTaskListFilter(c *check.C) { filter := "name=redis-cluster" out, err = d.Cmd("node", "ps", "--filter", filter, "self") - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) c.Assert(out, checker.Contains, name+".1") c.Assert(out, checker.Contains, name+".2") c.Assert(out, checker.Contains, name+".3") out, err = d.Cmd("node", "ps", "--filter", "name=none", "self") - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) c.Assert(out, checker.Not(checker.Contains), name+".1") c.Assert(out, checker.Not(checker.Contains), name+".2") c.Assert(out, checker.Not(checker.Contains), name+".3") @@ -277,21 +278,21 @@ func (s *DockerSwarmSuite) TestSwarmPublishAdd(c *check.C) { name := "top" out, err := d.Cmd("service", "create", "--detach", "--no-resolve-image", "--name", name, "--label", "x=y", "busybox", "top") - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) - c.Assert(strings.TrimSpace(out), checker.Not(checker.Equals), "") + assert.NilError(c, err, out) + assert.Assert(c, strings.TrimSpace(out) != "") out, err = d.Cmd("service", "update", "--detach", "--publish-add", "80:80", name) - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) out, err = d.Cmd("service", "update", "--detach", "--publish-add", "80:80", name) - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) _, err = d.Cmd("service", "update", "--detach", "--publish-add", "80:80", "--publish-add", "80:20", name) - c.Assert(err, checker.NotNil) + assert.ErrorContains(c, err, "") out, err = d.Cmd("service", "inspect", "--format", "{{ .Spec.EndpointSpec.Ports }}", name) - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) - c.Assert(strings.TrimSpace(out), checker.Equals, "[{ tcp 80 80 ingress}]") + assert.NilError(c, err, out) + assert.Equal(c, strings.TrimSpace(out), "[{ tcp 80 80 ingress}]") } func (s *DockerSwarmSuite) TestSwarmServiceWithGroup(c *check.C) { @@ -299,92 +300,92 @@ func (s *DockerSwarmSuite) TestSwarmServiceWithGroup(c *check.C) { name := "top" out, err := d.Cmd("service", "create", "--detach", "--no-resolve-image", "--name", name, "--user", "root:root", "--group", "wheel", "--group", "audio", "--group", "staff", "--group", "777", "busybox", "top") - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) - c.Assert(strings.TrimSpace(out), checker.Not(checker.Equals), "") + assert.NilError(c, err, out) + assert.Assert(c, strings.TrimSpace(out) != "") // make sure task has been deployed. waitAndAssert(c, defaultReconciliationTimeout, d.CheckActiveContainerCount, checker.Equals, 1) out, err = d.Cmd("ps", "-q") - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) - c.Assert(strings.TrimSpace(out), checker.Not(checker.Equals), "") + assert.NilError(c, err, out) + assert.Assert(c, strings.TrimSpace(out) != "") container := strings.TrimSpace(out) out, err = d.Cmd("exec", container, "id") - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) - c.Assert(strings.TrimSpace(out), checker.Equals, "uid=0(root) gid=0(root) groups=10(wheel),29(audio),50(staff),777") + assert.NilError(c, err, out) + assert.Equal(c, strings.TrimSpace(out), "uid=0(root) gid=0(root) groups=10(wheel),29(audio),50(staff),777") } func (s *DockerSwarmSuite) TestSwarmContainerAutoStart(c *check.C) { d := s.AddDaemon(c, true, true) out, err := d.Cmd("network", "create", "--attachable", "-d", "overlay", "foo") - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) - c.Assert(strings.TrimSpace(out), checker.Not(checker.Equals), "") + assert.NilError(c, err, out) + assert.Assert(c, strings.TrimSpace(out) != "") out, err = d.Cmd("run", "-id", "--restart=always", "--net=foo", "--name=test", "busybox", "top") - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) - c.Assert(strings.TrimSpace(out), checker.Not(checker.Equals), "") + assert.NilError(c, err, out) + assert.Assert(c, strings.TrimSpace(out) != "") out, err = d.Cmd("ps", "-q") - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) - c.Assert(strings.TrimSpace(out), checker.Not(checker.Equals), "") + assert.NilError(c, err, out) + assert.Assert(c, strings.TrimSpace(out) != "") d.RestartNode(c) out, err = d.Cmd("ps", "-q") - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) - c.Assert(strings.TrimSpace(out), checker.Not(checker.Equals), "") + assert.NilError(c, err, out) + assert.Assert(c, strings.TrimSpace(out) != "") } func (s *DockerSwarmSuite) TestSwarmContainerEndpointOptions(c *check.C) { d := s.AddDaemon(c, true, true) out, err := d.Cmd("network", "create", "--attachable", "-d", "overlay", "foo") - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) - c.Assert(strings.TrimSpace(out), checker.Not(checker.Equals), "") + assert.NilError(c, err, out) + assert.Assert(c, strings.TrimSpace(out) != "") out, err = d.Cmd("run", "-d", "--net=foo", "--name=first", "--net-alias=first-alias", "busybox:glibc", "top") - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) out, err = d.Cmd("run", "-d", "--net=foo", "--name=second", "busybox:glibc", "top") - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) out, err = d.Cmd("run", "-d", "--net=foo", "--net-alias=third-alias", "busybox:glibc", "top") - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) // ping first container and its alias, also ping third and anonymous container by its alias out, err = d.Cmd("exec", "second", "ping", "-c", "1", "first") - c.Assert(err, check.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) out, err = d.Cmd("exec", "second", "ping", "-c", "1", "first-alias") - c.Assert(err, check.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) out, err = d.Cmd("exec", "second", "ping", "-c", "1", "third-alias") - c.Assert(err, check.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) } func (s *DockerSwarmSuite) TestSwarmContainerAttachByNetworkId(c *check.C) { d := s.AddDaemon(c, true, true) out, err := d.Cmd("network", "create", "--attachable", "-d", "overlay", "testnet") - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) - c.Assert(strings.TrimSpace(out), checker.Not(checker.Equals), "") + assert.NilError(c, err, out) + assert.Assert(c, strings.TrimSpace(out) != "") networkID := strings.TrimSpace(out) out, err = d.Cmd("run", "-d", "--net", networkID, "busybox", "top") - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) cID := strings.TrimSpace(out) d.WaitRun(cID) out, err = d.Cmd("rm", "-f", cID) - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) out, err = d.Cmd("network", "rm", "testnet") - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) checkNetwork := func(*check.C) (interface{}, check.CommentInterface) { out, err := d.Cmd("network", "ls") - c.Assert(err, checker.IsNil) + assert.NilError(c, err) return out, nil } @@ -395,22 +396,22 @@ func (s *DockerSwarmSuite) TestOverlayAttachable(c *check.C) { d := s.AddDaemon(c, true, true) out, err := d.Cmd("network", "create", "-d", "overlay", "--attachable", "ovnet") - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) // validate attachable out, err = d.Cmd("network", "inspect", "--format", "{{json .Attachable}}", "ovnet") - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) - c.Assert(strings.TrimSpace(out), checker.Equals, "true") + assert.NilError(c, err, out) + assert.Equal(c, strings.TrimSpace(out), "true") // validate containers can attach to this overlay network out, err = d.Cmd("run", "-d", "--network", "ovnet", "--name", "c1", "busybox", "top") - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) // redo validation, there was a bug that the value of attachable changes after // containers attach to the network out, err = d.Cmd("network", "inspect", "--format", "{{json .Attachable}}", "ovnet") - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) - c.Assert(strings.TrimSpace(out), checker.Equals, "true") + assert.NilError(c, err, out) + assert.Equal(c, strings.TrimSpace(out), "true") } func (s *DockerSwarmSuite) TestOverlayAttachableOnSwarmLeave(c *check.C) { @@ -419,23 +420,23 @@ func (s *DockerSwarmSuite) TestOverlayAttachableOnSwarmLeave(c *check.C) { // Create an attachable swarm network nwName := "attovl" out, err := d.Cmd("network", "create", "-d", "overlay", "--attachable", nwName) - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) // Connect a container to the network out, err = d.Cmd("run", "-d", "--network", nwName, "--name", "c1", "busybox", "top") - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) // Leave the swarm c.Assert(d.SwarmLeave(c, true), checker.IsNil) // Check the container is disconnected out, err = d.Cmd("inspect", "c1", "--format", "{{.NetworkSettings.Networks."+nwName+"}}") - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) - c.Assert(strings.TrimSpace(out), checker.Equals, "") + assert.NilError(c, err, out) + assert.Equal(c, strings.TrimSpace(out), "") // Check the network is gone out, err = d.Cmd("network", "ls", "--format", "{{.Name}}") - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) c.Assert(out, checker.Not(checker.Contains), nwName) } @@ -444,23 +445,23 @@ func (s *DockerSwarmSuite) TestOverlayAttachableReleaseResourcesOnFailure(c *che // Create attachable network out, err := d.Cmd("network", "create", "-d", "overlay", "--attachable", "--subnet", "10.10.9.0/24", "ovnet") - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) // Attach a container with specific IP out, err = d.Cmd("run", "-d", "--network", "ovnet", "--name", "c1", "--ip", "10.10.9.33", "busybox", "top") - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) // Attempt to attach another container with same IP, must fail out, err = d.Cmd("run", "-d", "--network", "ovnet", "--name", "c2", "--ip", "10.10.9.33", "busybox", "top") - c.Assert(err, checker.NotNil, check.Commentf("%s", out)) + assert.ErrorContains(c, err, "", out) // Remove first container out, err = d.Cmd("rm", "-f", "c1") - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) // Verify the network can be removed, no phantom network attachment task left over out, err = d.Cmd("network", "rm", "ovnet") - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) } func (s *DockerSwarmSuite) TestSwarmIngressNetwork(c *check.C) { @@ -478,16 +479,16 @@ func (s *DockerSwarmSuite) TestSwarmIngressNetwork(c *check.C) { // And recreated out, err := d.Cmd("network", "create", "-d", "overlay", "--ingress", "new-ingress") - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) // But only one is allowed out, err = d.Cmd("network", "create", "-d", "overlay", "--ingress", "another-ingress") - c.Assert(err, checker.NotNil) + assert.ErrorContains(c, err, "") c.Assert(strings.TrimSpace(out), checker.Contains, "is already present") // It cannot be removed if it is being used out, err = d.Cmd("service", "create", "--detach", "--no-resolve-image", "--name", "srv1", "-p", "9000:8000", "busybox", "top") - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) result = removeNetwork("new-ingress") result.Assert(c, icmd.Expected{ @@ -497,24 +498,24 @@ func (s *DockerSwarmSuite) TestSwarmIngressNetwork(c *check.C) { // But it can be removed once no more services depend on it out, err = d.Cmd("service", "update", "--detach", "--publish-rm", "9000:8000", "srv1") - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) result = removeNetwork("new-ingress") result.Assert(c, icmd.Success) // A service which needs the ingress network cannot be created if no ingress is present out, err = d.Cmd("service", "create", "--detach", "--no-resolve-image", "--name", "srv2", "-p", "500:500", "busybox", "top") - c.Assert(err, checker.NotNil) + assert.ErrorContains(c, err, "") c.Assert(strings.TrimSpace(out), checker.Contains, "no ingress network is present") // An existing service cannot be updated to use the ingress nw if the nw is not present out, err = d.Cmd("service", "update", "--detach", "--publish-add", "9000:8000", "srv1") - c.Assert(err, checker.NotNil) + assert.ErrorContains(c, err, "") c.Assert(strings.TrimSpace(out), checker.Contains, "no ingress network is present") // But services which do not need routing mesh can be created regardless out, err = d.Cmd("service", "create", "--detach", "--no-resolve-image", "--name", "srv3", "--endpoint-mode", "dnsrr", "busybox", "top") - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) } func (s *DockerSwarmSuite) TestSwarmCreateServiceWithNoIngressNetwork(c *check.C) { @@ -529,9 +530,9 @@ func (s *DockerSwarmSuite) TestSwarmCreateServiceWithNoIngressNetwork(c *check.C // Create a overlay network and launch a service on it // Make sure nothing panics because ingress network is missing out, err := d.Cmd("network", "create", "-d", "overlay", "another-network") - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) out, err = d.Cmd("service", "create", "--detach", "--no-resolve-image", "--name", "srv4", "--network", "another-network", "busybox", "top") - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) } // Test case for #24108, also the case from: @@ -541,14 +542,14 @@ func (s *DockerSwarmSuite) TestSwarmTaskListFilter(c *check.C) { name := "redis-cluster-md5" out, err := d.Cmd("service", "create", "--detach", "--no-resolve-image", "--name", name, "--replicas=3", "busybox", "top") - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) - c.Assert(strings.TrimSpace(out), checker.Not(checker.Equals), "") + assert.NilError(c, err, out) + assert.Assert(c, strings.TrimSpace(out) != "") filter := "name=redis-cluster" checkNumTasks := func(*check.C) (interface{}, check.CommentInterface) { out, err := d.Cmd("service", "ps", "--filter", filter, name) - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) return len(strings.Split(out, "\n")) - 2, nil // includes header and nl in last line } @@ -556,41 +557,41 @@ func (s *DockerSwarmSuite) TestSwarmTaskListFilter(c *check.C) { waitAndAssert(c, defaultReconciliationTimeout, checkNumTasks, checker.Equals, 3) out, err = d.Cmd("service", "ps", "--filter", filter, name) - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) c.Assert(out, checker.Contains, name+".1") c.Assert(out, checker.Contains, name+".2") c.Assert(out, checker.Contains, name+".3") out, err = d.Cmd("service", "ps", "--filter", "name="+name+".1", name) - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) c.Assert(out, checker.Contains, name+".1") c.Assert(out, checker.Not(checker.Contains), name+".2") c.Assert(out, checker.Not(checker.Contains), name+".3") out, err = d.Cmd("service", "ps", "--filter", "name=none", name) - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) c.Assert(out, checker.Not(checker.Contains), name+".1") c.Assert(out, checker.Not(checker.Contains), name+".2") c.Assert(out, checker.Not(checker.Contains), name+".3") name = "redis-cluster-sha1" out, err = d.Cmd("service", "create", "--detach", "--no-resolve-image", "--name", name, "--mode=global", "busybox", "top") - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) - c.Assert(strings.TrimSpace(out), checker.Not(checker.Equals), "") + assert.NilError(c, err, out) + assert.Assert(c, strings.TrimSpace(out) != "") waitAndAssert(c, defaultReconciliationTimeout, checkNumTasks, checker.Equals, 1) filter = "name=redis-cluster" out, err = d.Cmd("service", "ps", "--filter", filter, name) - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) c.Assert(out, checker.Contains, name) out, err = d.Cmd("service", "ps", "--filter", "name="+name, name) - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) c.Assert(out, checker.Contains, name) out, err = d.Cmd("service", "ps", "--filter", "name=none", name) - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) c.Assert(out, checker.Not(checker.Contains), name) } @@ -599,28 +600,28 @@ func (s *DockerSwarmSuite) TestPsListContainersFilterIsTask(c *check.C) { // Create a bare container out, err := d.Cmd("run", "-d", "--name=bare-container", "busybox", "top") - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) bareID := strings.TrimSpace(out)[:12] // Create a service name := "busybox-top" out, err = d.Cmd("service", "create", "--detach", "--no-resolve-image", "--name", name, "busybox", "top") - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) - c.Assert(strings.TrimSpace(out), checker.Not(checker.Equals), "") + assert.NilError(c, err, out) + assert.Assert(c, strings.TrimSpace(out) != "") // make sure task has been deployed. waitAndAssert(c, defaultReconciliationTimeout, d.CheckServiceRunningTasks(name), checker.Equals, 1) // Filter non-tasks out, err = d.Cmd("ps", "-a", "-q", "--filter=is-task=false") - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) psOut := strings.TrimSpace(out) c.Assert(psOut, checker.Equals, bareID, check.Commentf("Expected id %s, got %s for is-task label, output %q", bareID, psOut, out)) // Filter tasks out, err = d.Cmd("ps", "-a", "-q", "--filter=is-task=true") - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) lines := strings.Split(strings.Trim(out, "\n "), "\n") - c.Assert(lines, checker.HasLen, 1) + assert.Equal(c, len(lines), 1) c.Assert(lines[0], checker.Not(checker.Equals), bareID, check.Commentf("Expected not %s, but got it for is-task label, output %q", bareID, out)) } @@ -784,15 +785,15 @@ func setupRemoteGlobalNetworkPlugin(c *check.C, mux *http.ServeMux, url, netDrv, }) err := os.MkdirAll("/etc/docker/plugins", 0755) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) fileName := fmt.Sprintf("/etc/docker/plugins/%s.spec", netDrv) err = ioutil.WriteFile(fileName, []byte(url), 0644) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) ipamFileName := fmt.Sprintf("/etc/docker/plugins/%s.spec", ipamDrv) err = ioutil.WriteFile(ipamFileName, []byte(url), 0644) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) } func (s *DockerSwarmSuite) TestSwarmNetworkPlugin(c *check.C) { @@ -803,13 +804,13 @@ func (s *DockerSwarmSuite) TestSwarmNetworkPlugin(c *check.C) { defer func() { s.server.Close() err := os.RemoveAll("/etc/docker/plugins") - c.Assert(err, checker.IsNil) + assert.NilError(c, err) }() d := s.AddDaemon(c, true, true) out, err := d.Cmd("network", "create", "-d", globalNetworkPlugin, "foo") - c.Assert(err, checker.NotNil, check.Commentf("%s", out)) + assert.ErrorContains(c, err, "", out) c.Assert(out, checker.Contains, "not supported in swarm mode") } @@ -819,16 +820,16 @@ func (s *DockerSwarmSuite) TestSwarmServiceEnvFile(c *check.C) { path := filepath.Join(d.Folder, "env.txt") err := ioutil.WriteFile(path, []byte("VAR1=A\nVAR2=A\n"), 0644) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) name := "worker" out, err := d.Cmd("service", "create", "--detach", "--no-resolve-image", "--env-file", path, "--env", "VAR1=B", "--env", "VAR1=C", "--env", "VAR2=", "--env", "VAR2", "--name", name, "busybox", "top") - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) - c.Assert(strings.TrimSpace(out), checker.Not(checker.Equals), "") + assert.NilError(c, err, out) + assert.Assert(c, strings.TrimSpace(out) != "") // The complete env is [VAR1=A VAR2=A VAR1=B VAR1=C VAR2= VAR2] and duplicates will be removed => [VAR1=C VAR2] out, err = d.Cmd("inspect", "--format", "{{ .Spec.TaskTemplate.ContainerSpec.Env }}", name) - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) c.Assert(out, checker.Contains, "[VAR1=C VAR2]") } @@ -842,41 +843,41 @@ func (s *DockerSwarmSuite) TestSwarmServiceTTY(c *check.C) { // Without --tty expectedOutput := "none" out, err := d.Cmd("service", "create", "--detach", "--no-resolve-image", "--name", name, "busybox", "sh", "-c", ttyCheck) - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) // Make sure task has been deployed. waitAndAssert(c, defaultReconciliationTimeout, d.CheckActiveContainerCount, checker.Equals, 1) // We need to get the container id. out, err = d.Cmd("ps", "-q", "--no-trunc") - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) id := strings.TrimSpace(out) out, err = d.Cmd("exec", id, "cat", "/status") - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) c.Assert(out, checker.Contains, expectedOutput, check.Commentf("Expected '%s', but got %q", expectedOutput, out)) // Remove service out, err = d.Cmd("service", "rm", name) - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) // Make sure container has been destroyed. waitAndAssert(c, defaultReconciliationTimeout, d.CheckActiveContainerCount, checker.Equals, 0) // With --tty expectedOutput = "TTY" out, err = d.Cmd("service", "create", "--detach", "--no-resolve-image", "--name", name, "--tty", "busybox", "sh", "-c", ttyCheck) - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) // Make sure task has been deployed. waitAndAssert(c, defaultReconciliationTimeout, d.CheckActiveContainerCount, checker.Equals, 1) // We need to get the container id. out, err = d.Cmd("ps", "-q", "--no-trunc") - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) id = strings.TrimSpace(out) out, err = d.Cmd("exec", id, "cat", "/status") - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) c.Assert(out, checker.Contains, expectedOutput, check.Commentf("Expected '%s', but got %q", expectedOutput, out)) } @@ -886,21 +887,21 @@ func (s *DockerSwarmSuite) TestSwarmServiceTTYUpdate(c *check.C) { // Create a service name := "top" out, err := d.Cmd("service", "create", "--detach", "--no-resolve-image", "--name", name, "busybox", "top") - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) // Make sure task has been deployed. waitAndAssert(c, defaultReconciliationTimeout, d.CheckActiveContainerCount, checker.Equals, 1) out, err = d.Cmd("service", "inspect", "--format", "{{ .Spec.TaskTemplate.ContainerSpec.TTY }}", name) - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) - c.Assert(strings.TrimSpace(out), checker.Equals, "false") + assert.NilError(c, err, out) + assert.Equal(c, strings.TrimSpace(out), "false") out, err = d.Cmd("service", "update", "--detach", "--tty", name) - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) out, err = d.Cmd("service", "inspect", "--format", "{{ .Spec.TaskTemplate.ContainerSpec.TTY }}", name) - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) - c.Assert(strings.TrimSpace(out), checker.Equals, "true") + assert.NilError(c, err, out) + assert.Equal(c, strings.TrimSpace(out), "true") } func (s *DockerSwarmSuite) TestSwarmServiceNetworkUpdate(c *check.C) { @@ -948,14 +949,14 @@ func (s *DockerSwarmSuite) TestDNSConfig(c *check.C) { // Create a service name := "top" out, err := d.Cmd("service", "create", "--detach", "--no-resolve-image", "--name", name, "--dns=1.2.3.4", "--dns-search=example.com", "--dns-option=timeout:3", "busybox", "top") - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) // Make sure task has been deployed. waitAndAssert(c, defaultReconciliationTimeout, d.CheckActiveContainerCount, checker.Equals, 1) // We need to get the container id. out, err = d.Cmd("ps", "-a", "-q", "--no-trunc") - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) id := strings.TrimSpace(out) // Compare against expected output. @@ -963,7 +964,7 @@ func (s *DockerSwarmSuite) TestDNSConfig(c *check.C) { expectedOutput2 := "search example.com" expectedOutput3 := "options timeout:3" out, err = d.Cmd("exec", id, "cat", "/etc/resolv.conf") - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) c.Assert(out, checker.Contains, expectedOutput1, check.Commentf("Expected '%s', but got %q", expectedOutput1, out)) c.Assert(out, checker.Contains, expectedOutput2, check.Commentf("Expected '%s', but got %q", expectedOutput2, out)) c.Assert(out, checker.Contains, expectedOutput3, check.Commentf("Expected '%s', but got %q", expectedOutput3, out)) @@ -975,17 +976,17 @@ func (s *DockerSwarmSuite) TestDNSConfigUpdate(c *check.C) { // Create a service name := "top" out, err := d.Cmd("service", "create", "--detach", "--no-resolve-image", "--name", name, "busybox", "top") - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) // Make sure task has been deployed. waitAndAssert(c, defaultReconciliationTimeout, d.CheckActiveContainerCount, checker.Equals, 1) out, err = d.Cmd("service", "update", "--detach", "--dns-add=1.2.3.4", "--dns-search-add=example.com", "--dns-option-add=timeout:3", name) - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) out, err = d.Cmd("service", "inspect", "--format", "{{ .Spec.TaskTemplate.ContainerSpec.DNSConfig }}", name) - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) - c.Assert(strings.TrimSpace(out), checker.Equals, "{[1.2.3.4] [example.com] [timeout:3]}") + assert.NilError(c, err, out) + assert.Equal(c, strings.TrimSpace(out), "{[1.2.3.4] [example.com] [timeout:3]}") } func getNodeStatus(c *check.C, d *daemon.Daemon) swarm.LocalNodeState { @@ -1038,7 +1039,7 @@ func (s *DockerSwarmSuite) TestUnlockEngineAndUnlockedSwarm(c *check.C) { c.Assert(result.Combined(), checker.Not(checker.Contains), "Please enter unlock key") out, err := d.Cmd("swarm", "init") - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) // unlocking an unlocked swarm should return an error - it does not even ask for the key cmd = d.Command("swarm", "unlock") @@ -1102,7 +1103,7 @@ func (s *DockerSwarmSuite) TestSwarmLeaveLocked(c *check.C) { d.RestartNode(c) info := d.SwarmInfo(c) - c.Assert(info.LocalNodeState, checker.Equals, swarm.LocalNodeStateLocked) + assert.Equal(c, info.LocalNodeState, swarm.LocalNodeStateLocked) outs, _ = d.Cmd("node", "ls") c.Assert(outs, checker.Contains, "Swarm is encrypted and needs to be unlocked") @@ -1116,13 +1117,13 @@ func (s *DockerSwarmSuite) TestSwarmLeaveLocked(c *check.C) { c.Assert(err, checker.IsNil, check.Commentf("%s", outs)) info = d.SwarmInfo(c) - c.Assert(info.LocalNodeState, checker.Equals, swarm.LocalNodeStateInactive) + assert.Equal(c, info.LocalNodeState, swarm.LocalNodeStateInactive) outs, err = d.Cmd("swarm", "init") c.Assert(err, checker.IsNil, check.Commentf("%s", outs)) info = d.SwarmInfo(c) - c.Assert(info.LocalNodeState, checker.Equals, swarm.LocalNodeStateActive) + assert.Equal(c, info.LocalNodeState, swarm.LocalNodeStateActive) } func (s *DockerSwarmSuite) TestSwarmLockUnlockCluster(c *check.C) { @@ -1201,7 +1202,7 @@ func (s *DockerSwarmSuite) TestSwarmJoinPromoteLocked(c *check.C) { // promote worker outs, err = d1.Cmd("node", "promote", d2.NodeID()) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) c.Assert(outs, checker.Contains, "promoted to a manager in the swarm") // join new manager node @@ -1219,7 +1220,7 @@ func (s *DockerSwarmSuite) TestSwarmJoinPromoteLocked(c *check.C) { // demote manager back to worker - workers are not locked outs, err = d1.Cmd("node", "demote", d3.NodeID()) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) c.Assert(outs, checker.Contains, "demoted in the swarm") // Wait for it to actually be demoted, for the key and cert to be replaced. @@ -1303,7 +1304,7 @@ func (s *DockerSwarmSuite) TestSwarmRotateUnlockKey(c *check.C) { c.Assert(getNodeStatus(c, d), checker.Equals, swarm.LocalNodeStateActive) outs, err = d.Cmd("node", "ls") - c.Assert(err, checker.IsNil) + assert.NilError(c, err) c.Assert(outs, checker.Not(checker.Contains), "Swarm is encrypted and needs to be unlocked") unlockKey = newUnlockKey @@ -1422,20 +1423,20 @@ func (s *DockerSwarmSuite) TestExtraHosts(c *check.C) { // Create a service name := "top" out, err := d.Cmd("service", "create", "--detach", "--no-resolve-image", "--name", name, "--host=example.com:1.2.3.4", "busybox", "top") - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) // Make sure task has been deployed. waitAndAssert(c, defaultReconciliationTimeout, d.CheckActiveContainerCount, checker.Equals, 1) // We need to get the container id. out, err = d.Cmd("ps", "-a", "-q", "--no-trunc") - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) id := strings.TrimSpace(out) // Compare against expected output. expectedOutput := "1.2.3.4\texample.com" out, err = d.Cmd("exec", id, "cat", "/etc/hosts") - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) c.Assert(out, checker.Contains, expectedOutput, check.Commentf("Expected '%s', but got %q", expectedOutput, out)) } @@ -1448,38 +1449,38 @@ func (s *DockerSwarmSuite) TestSwarmManagerAddress(c *check.C) { expectedOutput := fmt.Sprintf("Manager Addresses:\n 127.0.0.1:%d\n", d1.SwarmPort) out, err := d1.Cmd("info") - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) - c.Assert(out, checker.Contains, expectedOutput) + assert.NilError(c, err, out) + assert.Assert(c, strings.Contains(out, expectedOutput)) out, err = d2.Cmd("info") - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) - c.Assert(out, checker.Contains, expectedOutput) + assert.NilError(c, err, out) + assert.Assert(c, strings.Contains(out, expectedOutput)) out, err = d3.Cmd("info") - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) - c.Assert(out, checker.Contains, expectedOutput) + assert.NilError(c, err, out) + assert.Assert(c, strings.Contains(out, expectedOutput)) } func (s *DockerSwarmSuite) TestSwarmNetworkIPAMOptions(c *check.C) { d := s.AddDaemon(c, true, true) out, err := d.Cmd("network", "create", "-d", "overlay", "--ipam-opt", "foo=bar", "foo") - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) - c.Assert(strings.TrimSpace(out), checker.Not(checker.Equals), "") + assert.NilError(c, err, out) + assert.Assert(c, strings.TrimSpace(out) != "") out, err = d.Cmd("network", "inspect", "--format", "{{.IPAM.Options}}", "foo") - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) c.Assert(strings.TrimSpace(out), checker.Contains, "foo:bar") c.Assert(strings.TrimSpace(out), checker.Contains, "com.docker.network.ipam.serial:true") out, err = d.Cmd("service", "create", "--detach", "--no-resolve-image", "--network=foo", "--name", "top", "busybox", "top") - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) // make sure task has been deployed. waitAndAssert(c, defaultReconciliationTimeout, d.CheckActiveContainerCount, checker.Equals, 1) out, err = d.Cmd("network", "inspect", "--format", "{{.IPAM.Options}}", "foo") - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) c.Assert(strings.TrimSpace(out), checker.Contains, "foo:bar") c.Assert(strings.TrimSpace(out), checker.Contains, "com.docker.network.ipam.serial:true") } @@ -1489,7 +1490,7 @@ func (s *DockerSwarmSuite) TestSwarmNetworkIPAMOptions(c *check.C) { func (s *DockerSwarmSuite) TestSwarmNetworkCreateIssue27866(c *check.C) { d := s.AddDaemon(c, true, true) out, err := d.Cmd("network", "inspect", "-f", "{{.Id}}", "ingress") - c.Assert(err, checker.IsNil, check.Commentf("out: %v", out)) + assert.NilError(c, err, "out: %v", out) ingressID := strings.TrimSpace(out) c.Assert(ingressID, checker.Not(checker.Equals), "") @@ -1498,9 +1499,9 @@ func (s *DockerSwarmSuite) TestSwarmNetworkCreateIssue27866(c *check.C) { newNetName := ingressID[0:2] out, err = d.Cmd("network", "create", "--driver", "overlay", newNetName) // In #27866, it was failing because of "network with name %s already exists" - c.Assert(err, checker.IsNil, check.Commentf("out: %v", out)) + assert.NilError(c, err, "out: %v", out) out, err = d.Cmd("network", "rm", newNetName) - c.Assert(err, checker.IsNil, check.Commentf("out: %v", out)) + assert.NilError(c, err, "out: %v", out) } // Test case for https://github.com/docker/docker/pull/27938#issuecomment-265768303 @@ -1518,15 +1519,15 @@ func (s *DockerSwarmSuite) TestSwarmNetworkCreateDup(c *check.C) { c.Logf("Creating a network named %q with %q, then %q", nwName, driver1, driver2) out, err := d.Cmd("network", "create", "--driver", driver1, nwName) - c.Assert(err, checker.IsNil, check.Commentf("out: %v", out)) + assert.NilError(c, err, "out: %v", out) out, err = d.Cmd("network", "create", "--driver", driver2, nwName) c.Assert(out, checker.Contains, fmt.Sprintf("network with name %s already exists", nwName)) - c.Assert(err, checker.NotNil) + assert.ErrorContains(c, err, "") c.Logf("As expected, the attempt to network %q with %q failed: %s", nwName, driver2, out) out, err = d.Cmd("network", "rm", nwName) - c.Assert(err, checker.IsNil, check.Commentf("out: %v", out)) + assert.NilError(c, err, "out: %v", out) } } } @@ -1535,7 +1536,7 @@ func (s *DockerSwarmSuite) TestSwarmPublishDuplicatePorts(c *check.C) { d := s.AddDaemon(c, true, true) out, err := d.Cmd("service", "create", "--no-resolve-image", "--detach=true", "--publish", "5005:80", "--publish", "5006:80", "--publish", "80", "--publish", "80", "busybox", "top") - c.Assert(err, check.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) id := strings.TrimSpace(out) // make sure task has been deployed. @@ -1544,7 +1545,7 @@ func (s *DockerSwarmSuite) TestSwarmPublishDuplicatePorts(c *check.C) { // Total len = 4, with 2 dynamic ports and 2 non-dynamic ports // Dynamic ports are likely to be 30000 and 30001 but doesn't matter out, err = d.Cmd("service", "inspect", "--format", "{{.Endpoint.Ports}} len={{len .Endpoint.Ports}}", id) - c.Assert(err, check.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) c.Assert(out, checker.Contains, "len=4") c.Assert(out, checker.Contains, "{ tcp 80 5005 ingress}") c.Assert(out, checker.Contains, "{ tcp 80 5006 ingress}") @@ -1554,27 +1555,27 @@ func (s *DockerSwarmSuite) TestSwarmJoinWithDrain(c *check.C) { d := s.AddDaemon(c, true, true) out, err := d.Cmd("node", "ls") - c.Assert(err, checker.IsNil) + assert.NilError(c, err) c.Assert(out, checker.Not(checker.Contains), "Drain") out, err = d.Cmd("swarm", "join-token", "-q", "manager") - c.Assert(err, checker.IsNil) - c.Assert(strings.TrimSpace(out), checker.Not(checker.Equals), "") + assert.NilError(c, err) + assert.Assert(c, strings.TrimSpace(out) != "") token := strings.TrimSpace(out) d1 := s.AddDaemon(c, false, false) out, err = d1.Cmd("swarm", "join", "--availability=drain", "--token", token, d.SwarmListenAddr()) - c.Assert(err, checker.IsNil) - c.Assert(strings.TrimSpace(out), checker.Not(checker.Equals), "") + assert.NilError(c, err) + assert.Assert(c, strings.TrimSpace(out) != "") out, err = d.Cmd("node", "ls") - c.Assert(err, checker.IsNil) + assert.NilError(c, err) c.Assert(out, checker.Contains, "Drain") out, err = d1.Cmd("node", "ls") - c.Assert(err, checker.IsNil) + assert.NilError(c, err) c.Assert(out, checker.Contains, "Drain") } @@ -1582,10 +1583,10 @@ func (s *DockerSwarmSuite) TestSwarmInitWithDrain(c *check.C) { d := s.AddDaemon(c, false, false) out, err := d.Cmd("swarm", "init", "--availability", "drain") - c.Assert(err, checker.IsNil, check.Commentf("out: %v", out)) + assert.NilError(c, err, "out: %v", out) out, err = d.Cmd("node", "ls") - c.Assert(err, checker.IsNil) + assert.NilError(c, err) c.Assert(out, checker.Contains, "Drain") } @@ -1595,19 +1596,19 @@ func (s *DockerSwarmSuite) TestSwarmReadonlyRootfs(c *check.C) { d := s.AddDaemon(c, true, true) out, err := d.Cmd("service", "create", "--detach", "--no-resolve-image", "--name", "top", "--read-only", "busybox", "top") - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) // make sure task has been deployed. waitAndAssert(c, defaultReconciliationTimeout, d.CheckActiveContainerCount, checker.Equals, 1) out, err = d.Cmd("service", "inspect", "--format", "{{ .Spec.TaskTemplate.ContainerSpec.ReadOnly }}", "top") - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) - c.Assert(strings.TrimSpace(out), checker.Equals, "true") + assert.NilError(c, err, out) + assert.Equal(c, strings.TrimSpace(out), "true") containers := d.ActiveContainers(c) out, err = d.Cmd("inspect", "--type", "container", "--format", "{{.HostConfig.ReadonlyRootfs}}", containers[0]) - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) - c.Assert(strings.TrimSpace(out), checker.Equals, "true") + assert.NilError(c, err, out) + assert.Equal(c, strings.TrimSpace(out), "true") } func (s *DockerSwarmSuite) TestNetworkInspectWithDuplicateNames(c *check.C) { @@ -1623,55 +1624,55 @@ func (s *DockerSwarmSuite) TestNetworkInspectWithDuplicateNames(c *check.C) { defer cli.Close() n1, err := cli.NetworkCreate(context.Background(), name, options) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) // Full ID always works out, err := d.Cmd("network", "inspect", "--format", "{{.ID}}", n1.ID) - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) - c.Assert(strings.TrimSpace(out), checker.Equals, n1.ID) + assert.NilError(c, err, out) + assert.Equal(c, strings.TrimSpace(out), n1.ID) // Name works if it is unique out, err = d.Cmd("network", "inspect", "--format", "{{.ID}}", name) - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) - c.Assert(strings.TrimSpace(out), checker.Equals, n1.ID) + assert.NilError(c, err, out) + assert.Equal(c, strings.TrimSpace(out), n1.ID) n2, err := cli.NetworkCreate(context.Background(), name, options) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) // Full ID always works out, err = d.Cmd("network", "inspect", "--format", "{{.ID}}", n1.ID) - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) - c.Assert(strings.TrimSpace(out), checker.Equals, n1.ID) + assert.NilError(c, err, out) + assert.Equal(c, strings.TrimSpace(out), n1.ID) out, err = d.Cmd("network", "inspect", "--format", "{{.ID}}", n2.ID) - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) - c.Assert(strings.TrimSpace(out), checker.Equals, n2.ID) + assert.NilError(c, err, out) + assert.Equal(c, strings.TrimSpace(out), n2.ID) // Name with duplicates out, err = d.Cmd("network", "inspect", "--format", "{{.ID}}", name) - c.Assert(err, checker.NotNil, check.Commentf("%s", out)) + assert.ErrorContains(c, err, "", out) c.Assert(out, checker.Contains, "2 matches found based on name") out, err = d.Cmd("network", "rm", n2.ID) - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) // Dupliates with name but with different driver options.Driver = "overlay" n2, err = cli.NetworkCreate(context.Background(), name, options) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) // Full ID always works out, err = d.Cmd("network", "inspect", "--format", "{{.ID}}", n1.ID) - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) - c.Assert(strings.TrimSpace(out), checker.Equals, n1.ID) + assert.NilError(c, err, out) + assert.Equal(c, strings.TrimSpace(out), n1.ID) out, err = d.Cmd("network", "inspect", "--format", "{{.ID}}", n2.ID) - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) - c.Assert(strings.TrimSpace(out), checker.Equals, n2.ID) + assert.NilError(c, err, out) + assert.Equal(c, strings.TrimSpace(out), n2.ID) // Name with duplicates out, err = d.Cmd("network", "inspect", "--format", "{{.ID}}", name) - c.Assert(err, checker.NotNil, check.Commentf("%s", out)) + assert.ErrorContains(c, err, "", out) c.Assert(out, checker.Contains, "2 matches found based on name") } @@ -1681,44 +1682,44 @@ func (s *DockerSwarmSuite) TestSwarmStopSignal(c *check.C) { d := s.AddDaemon(c, true, true) out, err := d.Cmd("service", "create", "--detach", "--no-resolve-image", "--name", "top", "--stop-signal=SIGHUP", "busybox", "top") - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) // make sure task has been deployed. waitAndAssert(c, defaultReconciliationTimeout, d.CheckActiveContainerCount, checker.Equals, 1) out, err = d.Cmd("service", "inspect", "--format", "{{ .Spec.TaskTemplate.ContainerSpec.StopSignal }}", "top") - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) - c.Assert(strings.TrimSpace(out), checker.Equals, "SIGHUP") + assert.NilError(c, err, out) + assert.Equal(c, strings.TrimSpace(out), "SIGHUP") containers := d.ActiveContainers(c) out, err = d.Cmd("inspect", "--type", "container", "--format", "{{.Config.StopSignal}}", containers[0]) - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) - c.Assert(strings.TrimSpace(out), checker.Equals, "SIGHUP") + assert.NilError(c, err, out) + assert.Equal(c, strings.TrimSpace(out), "SIGHUP") out, err = d.Cmd("service", "update", "--detach", "--stop-signal=SIGUSR1", "top") - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) out, err = d.Cmd("service", "inspect", "--format", "{{ .Spec.TaskTemplate.ContainerSpec.StopSignal }}", "top") - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) - c.Assert(strings.TrimSpace(out), checker.Equals, "SIGUSR1") + assert.NilError(c, err, out) + assert.Equal(c, strings.TrimSpace(out), "SIGUSR1") } func (s *DockerSwarmSuite) TestSwarmServiceLsFilterMode(c *check.C) { d := s.AddDaemon(c, true, true) out, err := d.Cmd("service", "create", "--detach", "--no-resolve-image", "--name", "top1", "busybox", "top") - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) - c.Assert(strings.TrimSpace(out), checker.Not(checker.Equals), "") + assert.NilError(c, err, out) + assert.Assert(c, strings.TrimSpace(out) != "") out, err = d.Cmd("service", "create", "--detach", "--no-resolve-image", "--name", "top2", "--mode=global", "busybox", "top") - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) - c.Assert(strings.TrimSpace(out), checker.Not(checker.Equals), "") + assert.NilError(c, err, out) + assert.Assert(c, strings.TrimSpace(out) != "") // make sure task has been deployed. waitAndAssert(c, defaultReconciliationTimeout, d.CheckActiveContainerCount, checker.Equals, 2) out, err = d.Cmd("service", "ls") - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) c.Assert(out, checker.Contains, "top1") c.Assert(out, checker.Contains, "top2") c.Assert(out, checker.Not(checker.Contains), "localnet") @@ -1726,10 +1727,10 @@ func (s *DockerSwarmSuite) TestSwarmServiceLsFilterMode(c *check.C) { out, err = d.Cmd("service", "ls", "--filter", "mode=global") c.Assert(out, checker.Not(checker.Contains), "top1") c.Assert(out, checker.Contains, "top2") - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) out, err = d.Cmd("service", "ls", "--filter", "mode=replicated") - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) c.Assert(out, checker.Contains, "top1") c.Assert(out, checker.Not(checker.Contains), "top2") } @@ -1738,11 +1739,11 @@ func (s *DockerSwarmSuite) TestSwarmInitUnspecifiedDataPathAddr(c *check.C) { d := s.AddDaemon(c, false, false) out, err := d.Cmd("swarm", "init", "--data-path-addr", "0.0.0.0") - c.Assert(err, checker.NotNil) + assert.ErrorContains(c, err, "") c.Assert(out, checker.Contains, "data path address must be a non-zero IP") out, err = d.Cmd("swarm", "init", "--data-path-addr", "0.0.0.0:2000") - c.Assert(err, checker.NotNil) + assert.ErrorContains(c, err, "") c.Assert(out, checker.Contains, "data path address must be a non-zero IP") } @@ -1750,8 +1751,8 @@ func (s *DockerSwarmSuite) TestSwarmJoinLeave(c *check.C) { d := s.AddDaemon(c, true, true) out, err := d.Cmd("swarm", "join-token", "-q", "worker") - c.Assert(err, checker.IsNil) - c.Assert(strings.TrimSpace(out), checker.Not(checker.Equals), "") + assert.NilError(c, err) + assert.Assert(c, strings.TrimSpace(out) != "") token := strings.TrimSpace(out) @@ -1759,11 +1760,11 @@ func (s *DockerSwarmSuite) TestSwarmJoinLeave(c *check.C) { d1 := s.AddDaemon(c, false, false) for i := 0; i < 10; i++ { out, err = d1.Cmd("swarm", "join", "--token", token, d.SwarmListenAddr()) - c.Assert(err, checker.IsNil) - c.Assert(strings.TrimSpace(out), checker.Not(checker.Equals), "") + assert.NilError(c, err) + assert.Assert(c, strings.TrimSpace(out) != "") _, err = d1.Cmd("swarm", "leave") - c.Assert(err, checker.IsNil) + assert.NilError(c, err) } } @@ -1783,7 +1784,7 @@ func waitForEvent(c *check.C, d *daemon.Daemon, since string, filter string, eve } else { out, err = d.Cmd("events", "--since", since, "--until", until) } - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) if strings.Contains(out, event) { return strings.TrimSpace(out) } @@ -1803,7 +1804,7 @@ func (s *DockerSwarmSuite) TestSwarmClusterEventsSource(c *check.C) { // create a network out, err := d1.Cmd("network", "create", "--attachable", "-d", "overlay", "foo") - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) networkID := strings.TrimSpace(out) c.Assert(networkID, checker.Not(checker.Equals), "") @@ -1821,7 +1822,7 @@ func (s *DockerSwarmSuite) TestSwarmClusterEventsScope(c *check.C) { // create a service out, err := d.Cmd("service", "create", "--no-resolve-image", "--name", "test", "--detach=false", "busybox", "top") - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) serviceID := strings.Split(out, "\n")[0] // scope swarm filters cluster events @@ -1842,12 +1843,12 @@ func (s *DockerSwarmSuite) TestSwarmClusterEventsType(c *check.C) { // create a service out, err := d.Cmd("service", "create", "--no-resolve-image", "--name", "test", "--detach=false", "busybox", "top") - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) serviceID := strings.Split(out, "\n")[0] // create a network out, err = d.Cmd("network", "create", "--attachable", "-d", "overlay", "foo") - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) networkID := strings.TrimSpace(out) c.Assert(networkID, checker.Not(checker.Equals), "") @@ -1865,7 +1866,7 @@ func (s *DockerSwarmSuite) TestSwarmClusterEventsService(c *check.C) { // create a service out, err := d.Cmd("service", "create", "--no-resolve-image", "--name", "test", "--detach=false", "busybox", "top") - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) serviceID := strings.Split(out, "\n")[0] // validate service create event @@ -1873,7 +1874,7 @@ func (s *DockerSwarmSuite) TestSwarmClusterEventsService(c *check.C) { t1 := daemonUnixTime(c) out, err = d.Cmd("service", "update", "--force", "--detach=false", "test") - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) // wait for service update start out = waitForEvent(c, d, t1, "-f scope=swarm", "service update "+serviceID, defaultRetryCount) @@ -1887,7 +1888,7 @@ func (s *DockerSwarmSuite) TestSwarmClusterEventsService(c *check.C) { // scale service t2 := daemonUnixTime(c) out, err = d.Cmd("service", "scale", "test=3") - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) out = waitForEvent(c, d, t2, "-f scope=swarm", "service update "+serviceID, defaultRetryCount) c.Assert(out, checker.Contains, "replicas.new=3, replicas.old=1") @@ -1895,7 +1896,7 @@ func (s *DockerSwarmSuite) TestSwarmClusterEventsService(c *check.C) { // remove service t3 := daemonUnixTime(c) out, err = d.Cmd("service", "rm", "test") - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) waitForEvent(c, d, t3, "-f scope=swarm", "service remove "+serviceID, defaultRetryCount) } @@ -1910,7 +1911,7 @@ func (s *DockerSwarmSuite) TestSwarmClusterEventsNode(c *check.C) { t1 := daemonUnixTime(c) out, err := d1.Cmd("node", "update", "--availability=pause", d3ID) - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) // filter by type out = waitForEvent(c, d1, t1, "-f type=node", "node update "+d3ID, defaultRetryCount) @@ -1918,13 +1919,13 @@ func (s *DockerSwarmSuite) TestSwarmClusterEventsNode(c *check.C) { t2 := daemonUnixTime(c) out, err = d1.Cmd("node", "demote", d3ID) - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) waitForEvent(c, d1, t2, "-f type=node", "node update "+d3ID, defaultRetryCount) t3 := daemonUnixTime(c) out, err = d1.Cmd("node", "rm", "-f", d3ID) - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) // filter by scope waitForEvent(c, d1, t3, "-f scope=swarm", "node remove "+d3ID, defaultRetryCount) @@ -1935,7 +1936,7 @@ func (s *DockerSwarmSuite) TestSwarmClusterEventsNetwork(c *check.C) { // create a network out, err := d.Cmd("network", "create", "--attachable", "-d", "overlay", "foo") - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) networkID := strings.TrimSpace(out) waitForEvent(c, d, "0", "-f scope=swarm", "network create "+networkID, defaultRetryCount) @@ -1943,7 +1944,7 @@ func (s *DockerSwarmSuite) TestSwarmClusterEventsNetwork(c *check.C) { // remove network t1 := daemonUnixTime(c) out, err = d.Cmd("network", "rm", "foo") - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) // filtered by network waitForEvent(c, d, t1, "-f type=network", "network remove "+networkID, defaultRetryCount) diff --git a/components/engine/integration-cli/docker_cli_swarm_unix_test.go b/components/engine/integration-cli/docker_cli_swarm_unix_test.go index 7473937eda..bfaa08b19b 100644 --- a/components/engine/integration-cli/docker_cli_swarm_unix_test.go +++ b/components/engine/integration-cli/docker_cli_swarm_unix_test.go @@ -10,13 +10,14 @@ import ( "github.com/docker/docker/api/types/swarm" "github.com/docker/docker/integration-cli/checker" "github.com/go-check/check" + "gotest.tools/assert" ) func (s *DockerSwarmSuite) TestSwarmVolumePlugin(c *check.C) { d := s.AddDaemon(c, true, true) out, err := d.Cmd("service", "create", "--detach", "--no-resolve-image", "--mount", "type=volume,source=my-volume,destination=/foo,volume-driver=customvolumedriver", "--name", "top", "busybox", "top") - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) // Make sure task stays pending before plugin is available waitAndAssert(c, defaultReconciliationTimeout, d.CheckServiceTasksInStateWithError("top", swarm.TaskStatePending, "missing plugin on 1 node"), checker.Equals, 1) @@ -26,7 +27,7 @@ func (s *DockerSwarmSuite) TestSwarmVolumePlugin(c *check.C) { // create a dummy volume to trigger lazy loading of the plugin out, err = d.Cmd("volume", "create", "-d", "customvolumedriver", "hello") - c.Assert(err, checker.IsNil, check.Commentf("%s", out)) + assert.NilError(c, err, out) // TODO(aaronl): It will take about 15 seconds for swarm to realize the // plugin was loaded. Switching the test over to plugin v2 would avoid @@ -36,21 +37,21 @@ func (s *DockerSwarmSuite) TestSwarmVolumePlugin(c *check.C) { waitAndAssert(c, defaultReconciliationTimeout, d.CheckActiveContainerCount, checker.Equals, 1) out, err = d.Cmd("ps", "-q") - c.Assert(err, checker.IsNil) + assert.NilError(c, err) containerID := strings.TrimSpace(out) out, err = d.Cmd("inspect", "-f", "{{json .Mounts}}", containerID) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) var mounts []struct { Name string Driver string } - c.Assert(json.NewDecoder(strings.NewReader(out)).Decode(&mounts), checker.IsNil) - c.Assert(len(mounts), checker.Equals, 1, check.Commentf("%s", out)) - c.Assert(mounts[0].Name, checker.Equals, "my-volume") - c.Assert(mounts[0].Driver, checker.Equals, "customvolumedriver") + assert.NilError(c, json.NewDecoder(strings.NewReader(out)).Decode(&mounts)) + assert.Equal(c, len(mounts), 1, string(out)) + assert.Equal(c, mounts[0].Name, "my-volume") + assert.Equal(c, mounts[0].Driver, "customvolumedriver") } // Test network plugin filter in swarm @@ -63,27 +64,27 @@ func (s *DockerSwarmSuite) TestSwarmNetworkPluginV2(c *check.C) { pluginName := "aragunathan/global-net-plugin:latest" _, err := d1.Cmd("plugin", "install", pluginName, "--grant-all-permissions") - c.Assert(err, checker.IsNil) + assert.NilError(c, err) _, err = d2.Cmd("plugin", "install", pluginName, "--grant-all-permissions") - c.Assert(err, checker.IsNil) + assert.NilError(c, err) // create network networkName := "globalnet" _, err = d1.Cmd("network", "create", "--driver", pluginName, networkName) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) // create a global service to ensure that both nodes will have an instance serviceName := "my-service" _, err = d1.Cmd("service", "create", "--detach", "--no-resolve-image", "--name", serviceName, "--mode=global", "--network", networkName, "busybox", "top") - c.Assert(err, checker.IsNil) + assert.NilError(c, err) // wait for tasks ready waitAndAssert(c, defaultReconciliationTimeout, reducedCheck(sumAsIntegers, d1.CheckActiveContainerCount, d2.CheckActiveContainerCount), checker.Equals, 2) // remove service _, err = d1.Cmd("service", "rm", serviceName) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) // wait to ensure all containers have exited before removing the plugin. Else there's a // possibility of container exits erroring out due to plugins being unavailable. @@ -91,14 +92,14 @@ func (s *DockerSwarmSuite) TestSwarmNetworkPluginV2(c *check.C) { // disable plugin on worker _, err = d2.Cmd("plugin", "disable", "-f", pluginName) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) time.Sleep(20 * time.Second) image := "busybox:latest" // create a new global service again. _, err = d1.Cmd("service", "create", "--detach", "--no-resolve-image", "--name", serviceName, "--mode=global", "--network", networkName, image, "top") - c.Assert(err, checker.IsNil) + assert.NilError(c, err) waitAndAssert(c, defaultReconciliationTimeout, d1.CheckRunningTaskImages, checker.DeepEquals, map[string]int{image: 1}) diff --git a/components/engine/integration-cli/docker_cli_top_test.go b/components/engine/integration-cli/docker_cli_top_test.go index 50744b0111..b078b7b5fc 100644 --- a/components/engine/integration-cli/docker_cli_top_test.go +++ b/components/engine/integration-cli/docker_cli_top_test.go @@ -3,8 +3,8 @@ package main import ( "strings" - "github.com/docker/docker/integration-cli/checker" "github.com/go-check/check" + "gotest.tools/assert" "gotest.tools/icmd" ) @@ -40,8 +40,8 @@ func (s *DockerSuite) TestTopNonPrivileged(c *check.C) { lookingFor = "top" } - c.Assert(out1, checker.Contains, lookingFor, check.Commentf("top should've listed `%s` in the process list, but failed the first time", lookingFor)) - c.Assert(out2, checker.Contains, lookingFor, check.Commentf("top should've listed `%s` in the process list, but failed the second time", lookingFor)) + assert.Assert(c, strings.Contains(out1, lookingFor), "top should've listed `%s` in the process list, but failed the first time", lookingFor) + assert.Assert(c, strings.Contains(out2, lookingFor), "top should've listed `%s` in the process list, but failed the second time", lookingFor) } // TestTopWindowsCoreProcesses validates that there are lines for the critical @@ -54,7 +54,7 @@ func (s *DockerSuite) TestTopWindowsCoreProcesses(c *check.C) { out1, _ := dockerCmd(c, "top", cleanedContainerID) lookingFor := []string{"smss.exe", "csrss.exe", "wininit.exe", "services.exe", "lsass.exe", "CExecSvc.exe"} for i, s := range lookingFor { - c.Assert(out1, checker.Contains, s, check.Commentf("top should've listed `%s` in the process list, but failed. Test case %d", s, i)) + assert.Assert(c, strings.Contains(out1, s), "top should've listed `%s` in the process list, but failed. Test case %d", s, i) } } @@ -68,6 +68,6 @@ func (s *DockerSuite) TestTopPrivileged(c *check.C) { out2, _ := dockerCmd(c, "top", cleanedContainerID) dockerCmd(c, "kill", cleanedContainerID) - c.Assert(out1, checker.Contains, "top", check.Commentf("top should've listed `top` in the process list, but failed the first time")) - c.Assert(out2, checker.Contains, "top", check.Commentf("top should've listed `top` in the process list, but failed the second time")) + assert.Assert(c, strings.Contains(out1, "top"), "top should've listed `top` in the process list, but failed the first time") + assert.Assert(c, strings.Contains(out2, "top"), "top should've listed `top` in the process list, but failed the second time") } diff --git a/components/engine/integration-cli/docker_cli_update_unix_test.go b/components/engine/integration-cli/docker_cli_update_unix_test.go index 7b4925a4ad..9a7446a90f 100644 --- a/components/engine/integration-cli/docker_cli_update_unix_test.go +++ b/components/engine/integration-cli/docker_cli_update_unix_test.go @@ -12,11 +12,11 @@ import ( "github.com/docker/docker/api/types" "github.com/docker/docker/client" - "github.com/docker/docker/integration-cli/checker" "github.com/docker/docker/internal/test/request" "github.com/docker/docker/pkg/parsers/kernel" "github.com/go-check/check" "github.com/kr/pty" + "gotest.tools/assert" ) func (s *DockerSuite) TestUpdateRunningContainer(c *check.C) { @@ -27,11 +27,11 @@ func (s *DockerSuite) TestUpdateRunningContainer(c *check.C) { dockerCmd(c, "run", "-d", "--name", name, "-m", "300M", "busybox", "top") dockerCmd(c, "update", "-m", "500M", name) - c.Assert(inspectField(c, name, "HostConfig.Memory"), checker.Equals, "524288000") + 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) - c.Assert(strings.TrimSpace(out), checker.Equals, "524288000") + assert.Equal(c, strings.TrimSpace(out), "524288000") } func (s *DockerSuite) TestUpdateRunningContainerWithRestart(c *check.C) { @@ -43,11 +43,11 @@ func (s *DockerSuite) TestUpdateRunningContainerWithRestart(c *check.C) { dockerCmd(c, "update", "-m", "500M", name) dockerCmd(c, "restart", name) - c.Assert(inspectField(c, name, "HostConfig.Memory"), checker.Equals, "524288000") + 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) - c.Assert(strings.TrimSpace(out), checker.Equals, "524288000") + assert.Equal(c, strings.TrimSpace(out), "524288000") } func (s *DockerSuite) TestUpdateStoppedContainer(c *check.C) { @@ -59,10 +59,10 @@ func (s *DockerSuite) TestUpdateStoppedContainer(c *check.C) { dockerCmd(c, "run", "--name", name, "-m", "300M", "busybox", "cat", file) dockerCmd(c, "update", "-m", "500M", name) - c.Assert(inspectField(c, name, "HostConfig.Memory"), checker.Equals, "524288000") + assert.Equal(c, inspectField(c, name, "HostConfig.Memory"), "524288000") out, _ := dockerCmd(c, "start", "-a", name) - c.Assert(strings.TrimSpace(out), checker.Equals, "524288000") + assert.Equal(c, strings.TrimSpace(out), "524288000") } func (s *DockerSuite) TestUpdatePausedContainer(c *check.C) { @@ -74,12 +74,12 @@ func (s *DockerSuite) TestUpdatePausedContainer(c *check.C) { dockerCmd(c, "pause", name) dockerCmd(c, "update", "--cpu-shares", "500", name) - c.Assert(inspectField(c, name, "HostConfig.CPUShares"), checker.Equals, "500") + 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) - c.Assert(strings.TrimSpace(out), checker.Equals, "500") + assert.Equal(c, strings.TrimSpace(out), "500") } func (s *DockerSuite) TestUpdateWithUntouchedFields(c *check.C) { @@ -93,11 +93,11 @@ func (s *DockerSuite) TestUpdateWithUntouchedFields(c *check.C) { // Update memory and not touch cpus, `cpuset.cpus` should still have the old value out := inspectField(c, name, "HostConfig.CPUShares") - c.Assert(out, check.Equals, "800") + assert.Equal(c, out, "800") file := "/sys/fs/cgroup/cpu/cpu.shares" out, _ = dockerCmd(c, "exec", name, "cat", file) - c.Assert(strings.TrimSpace(out), checker.Equals, "800") + assert.Equal(c, strings.TrimSpace(out), "800") } func (s *DockerSuite) TestUpdateContainerInvalidValue(c *check.C) { @@ -107,9 +107,9 @@ func (s *DockerSuite) TestUpdateContainerInvalidValue(c *check.C) { name := "test-update-container" dockerCmd(c, "run", "-d", "--name", name, "-m", "300M", "busybox", "true") out, _, err := dockerCmdWithError("update", "-m", "2M", name) - c.Assert(err, check.NotNil) + assert.ErrorContains(c, err, "") expected := "Minimum memory limit allowed is 4MB" - c.Assert(out, checker.Contains, expected) + assert.Assert(c, strings.Contains(out, expected)) } func (s *DockerSuite) TestUpdateContainerWithoutFlags(c *check.C) { @@ -119,7 +119,7 @@ func (s *DockerSuite) TestUpdateContainerWithoutFlags(c *check.C) { name := "test-update-container" dockerCmd(c, "run", "-d", "--name", name, "-m", "300M", "busybox", "true") _, _, err := dockerCmdWithError("update", name) - c.Assert(err, check.NotNil) + assert.ErrorContains(c, err, "") } func (s *DockerSuite) TestUpdateKernelMemory(c *check.C) { @@ -129,11 +129,11 @@ func (s *DockerSuite) TestUpdateKernelMemory(c *check.C) { dockerCmd(c, "run", "-d", "--name", name, "--kernel-memory", "50M", "busybox", "top") dockerCmd(c, "update", "--kernel-memory", "100M", name) - c.Assert(inspectField(c, name, "HostConfig.KernelMemory"), checker.Equals, "104857600") + assert.Equal(c, inspectField(c, name, "HostConfig.KernelMemory"), "104857600") file := "/sys/fs/cgroup/memory/memory.kmem.limit_in_bytes" out, _ := dockerCmd(c, "exec", name, "cat", file) - c.Assert(strings.TrimSpace(out), checker.Equals, "104857600") + assert.Equal(c, strings.TrimSpace(out), "104857600") } func (s *DockerSuite) TestUpdateKernelMemoryUninitialized(c *check.C) { @@ -146,17 +146,17 @@ func (s *DockerSuite) TestUpdateKernelMemoryUninitialized(c *check.C) { // Update kernel memory to a running container without kernel memory initialized // is not allowed before kernel version 4.6. if !isNewKernel { - c.Assert(err, check.NotNil) + assert.ErrorContains(c, err, "") } else { - c.Assert(err, check.IsNil) + assert.NilError(c, err) } dockerCmd(c, "pause", name) _, _, err = dockerCmdWithError("update", "--kernel-memory", "200M", name) if !isNewKernel { - c.Assert(err, check.NotNil) + assert.ErrorContains(c, err, "") } else { - c.Assert(err, check.IsNil) + assert.NilError(c, err) } dockerCmd(c, "unpause", name) @@ -164,11 +164,11 @@ func (s *DockerSuite) TestUpdateKernelMemoryUninitialized(c *check.C) { dockerCmd(c, "update", "--kernel-memory", "300M", name) dockerCmd(c, "start", name) - c.Assert(inspectField(c, name, "HostConfig.KernelMemory"), checker.Equals, "314572800") + assert.Equal(c, inspectField(c, name, "HostConfig.KernelMemory"), "314572800") file := "/sys/fs/cgroup/memory/memory.kmem.limit_in_bytes" out, _ := dockerCmd(c, "exec", name, "cat", file) - c.Assert(strings.TrimSpace(out), checker.Equals, "314572800") + assert.Equal(c, strings.TrimSpace(out), "314572800") } // GetKernelVersion gets the current kernel version. @@ -192,11 +192,11 @@ func (s *DockerSuite) TestUpdateSwapMemoryOnly(c *check.C) { dockerCmd(c, "run", "-d", "--name", name, "--memory", "300M", "--memory-swap", "500M", "busybox", "top") dockerCmd(c, "update", "--memory-swap", "600M", name) - c.Assert(inspectField(c, name, "HostConfig.MemorySwap"), checker.Equals, "629145600") + 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) - c.Assert(strings.TrimSpace(out), checker.Equals, "629145600") + assert.Equal(c, strings.TrimSpace(out), "629145600") } func (s *DockerSuite) TestUpdateInvalidSwapMemory(c *check.C) { @@ -209,19 +209,19 @@ func (s *DockerSuite) TestUpdateInvalidSwapMemory(c *check.C) { _, _, err := dockerCmdWithError("update", "--memory-swap", "200M", name) // Update invalid swap memory should fail. // This will pass docker config validation, but failed at kernel validation - c.Assert(err, check.NotNil) + assert.ErrorContains(c, err, "") // Update invalid swap memory with failure should not change HostConfig - c.Assert(inspectField(c, name, "HostConfig.Memory"), checker.Equals, "314572800") - c.Assert(inspectField(c, name, "HostConfig.MemorySwap"), checker.Equals, "524288000") + 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) - c.Assert(inspectField(c, name, "HostConfig.MemorySwap"), checker.Equals, "629145600") + 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) - c.Assert(strings.TrimSpace(out), checker.Equals, "629145600") + assert.Equal(c, strings.TrimSpace(out), "629145600") } func (s *DockerSuite) TestUpdateStats(c *check.C) { @@ -231,16 +231,16 @@ func (s *DockerSuite) TestUpdateStats(c *check.C) { name := "foo" dockerCmd(c, "run", "-d", "-ti", "--name", name, "-m", "500m", "busybox") - c.Assert(waitRun(name), checker.IsNil) + assert.NilError(c, waitRun(name)) getMemLimit := func(id string) uint64 { resp, body, err := request.Get(fmt.Sprintf("/containers/%s/stats?stream=false", id)) - c.Assert(err, checker.IsNil) - c.Assert(resp.Header.Get("Content-Type"), checker.Equals, "application/json") + assert.NilError(c, err) + assert.Equal(c, resp.Header.Get("Content-Type"), "application/json") var v *types.Stats err = json.NewDecoder(body).Decode(&v) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) body.Close() return v.MemoryStats.Limit @@ -250,9 +250,7 @@ func (s *DockerSuite) TestUpdateStats(c *check.C) { dockerCmd(c, "update", "--cpu-quota", "2000", name) curMemLimit := getMemLimit(name) - - c.Assert(preMemLimit, checker.Equals, curMemLimit) - + assert.Equal(c, preMemLimit, curMemLimit) } func (s *DockerSuite) TestUpdateMemoryWithSwapMemory(c *check.C) { @@ -263,8 +261,8 @@ func (s *DockerSuite) TestUpdateMemoryWithSwapMemory(c *check.C) { name := "test-update-container" dockerCmd(c, "run", "-d", "--name", name, "--memory", "300M", "busybox", "top") out, _, err := dockerCmdWithError("update", "--memory", "800M", name) - c.Assert(err, checker.NotNil) - c.Assert(out, checker.Contains, "Memory limit should be smaller than already set memoryswap limit") + 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) } @@ -277,24 +275,24 @@ func (s *DockerSuite) TestUpdateNotAffectMonitorRestartPolicy(c *check.C) { dockerCmd(c, "update", "--cpu-shares", "512", id) cpty, tty, err := pty.Open() - c.Assert(err, checker.IsNil) + assert.NilError(c, err) defer cpty.Close() cmd := exec.Command(dockerBinary, "attach", id) cmd.Stdin = tty - c.Assert(cmd.Start(), checker.IsNil) + assert.NilError(c, cmd.Start()) defer cmd.Process.Kill() _, err = cpty.Write([]byte("exit\n")) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) - c.Assert(cmd.Wait(), checker.IsNil) + assert.NilError(c, cmd.Wait()) // container should restart again and keep running err = waitInspect(id, "{{.RestartCount}}", "1", 30*time.Second) - c.Assert(err, checker.IsNil) - c.Assert(waitRun(id), checker.IsNil) + assert.NilError(c, err) + assert.NilError(c, waitRun(id)) } func (s *DockerSuite) TestUpdateWithNanoCPUs(c *check.C) { @@ -304,36 +302,36 @@ func (s *DockerSuite) TestUpdateWithNanoCPUs(c *check.C) { file2 := "/sys/fs/cgroup/cpu/cpu.cfs_period_us" out, _ := dockerCmd(c, "run", "-d", "--cpus", "0.5", "--name", "top", "busybox", "top") - c.Assert(strings.TrimSpace(out), checker.Not(checker.Equals), "") + assert.Assert(c, strings.TrimSpace(out) != "") out, _ = dockerCmd(c, "exec", "top", "sh", "-c", fmt.Sprintf("cat %s && cat %s", file1, file2)) - c.Assert(strings.TrimSpace(out), checker.Equals, "50000\n100000") + assert.Equal(c, strings.TrimSpace(out), "50000\n100000") clt, err := client.NewClientWithOpts(client.FromEnv) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) inspect, err := clt.ContainerInspect(context.Background(), "top") - c.Assert(err, checker.IsNil) - c.Assert(inspect.HostConfig.NanoCPUs, checker.Equals, int64(500000000)) + assert.NilError(c, err) + assert.Equal(c, inspect.HostConfig.NanoCPUs, int64(500000000)) out = inspectField(c, "top", "HostConfig.CpuQuota") - c.Assert(out, checker.Equals, "0", check.Commentf("CPU CFS quota should be 0")) + assert.Equal(c, out, "0", "CPU CFS quota should be 0") out = inspectField(c, "top", "HostConfig.CpuPeriod") - c.Assert(out, checker.Equals, "0", check.Commentf("CPU CFS period should be 0")) + assert.Equal(c, out, "0", "CPU CFS period should be 0") out, _, err = dockerCmdWithError("update", "--cpu-quota", "80000", "top") - c.Assert(err, checker.NotNil) - c.Assert(out, checker.Contains, "Conflicting options: CPU Quota cannot be updated as NanoCPUs has already been set") + 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") inspect, err = clt.ContainerInspect(context.Background(), "top") - c.Assert(err, checker.IsNil) - c.Assert(inspect.HostConfig.NanoCPUs, checker.Equals, int64(800000000)) + assert.NilError(c, err) + assert.Equal(c, inspect.HostConfig.NanoCPUs, int64(800000000)) out = inspectField(c, "top", "HostConfig.CpuQuota") - c.Assert(out, checker.Equals, "0", check.Commentf("CPU CFS quota should be 0")) + assert.Equal(c, out, "0", "CPU CFS quota should be 0") out = inspectField(c, "top", "HostConfig.CpuPeriod") - c.Assert(out, checker.Equals, "0", check.Commentf("CPU CFS period should be 0")) + 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)) - c.Assert(strings.TrimSpace(out), checker.Equals, "80000\n100000") + assert.Equal(c, strings.TrimSpace(out), "80000\n100000") } diff --git a/components/engine/integration-cli/docker_cli_userns_test.go b/components/engine/integration-cli/docker_cli_userns_test.go index ede2d8f560..1cbf367fe4 100644 --- a/components/engine/integration-cli/docker_cli_userns_test.go +++ b/components/engine/integration-cli/docker_cli_userns_test.go @@ -16,6 +16,7 @@ import ( "github.com/docker/docker/pkg/stringid" "github.com/docker/docker/pkg/system" "github.com/go-check/check" + "gotest.tools/assert" ) // user namespaces test: run daemon with remapped root setting @@ -27,7 +28,7 @@ func (s *DockerDaemonSuite) TestDaemonUserNamespaceRootSetting(c *check.C) { s.d.StartWithBusybox(c, "--userns-remap", "default") tmpDir, err := ioutil.TempDir("", "userns") - c.Assert(err, checker.IsNil) + assert.NilError(c, err) defer os.RemoveAll(tmpDir) @@ -39,21 +40,22 @@ func (s *DockerDaemonSuite) TestDaemonUserNamespaceRootSetting(c *check.C) { uidgid := strings.Split(filepath.Base(s.d.Root), ".") c.Assert(uidgid, checker.HasLen, 2, check.Commentf("Should have gotten uid/gid strings from root dirname: %s", filepath.Base(s.d.Root))) uid, err := strconv.Atoi(uidgid[0]) - c.Assert(err, checker.IsNil, check.Commentf("Can't parse uid")) + assert.NilError(c, err, "Can't parse uid") gid, err := strconv.Atoi(uidgid[1]) - c.Assert(err, checker.IsNil, check.Commentf("Can't parse gid")) + assert.NilError(c, err, "Can't parse gid") // writable by the remapped root UID/GID pair - c.Assert(os.Chown(tmpDir, uid, gid), checker.IsNil) + assert.NilError(c, os.Chown(tmpDir, uid, gid)) out, err := s.d.Cmd("run", "-d", "--name", "userns", "-v", tmpDir+":/goofy", "-v", tmpDirNotExists+":/donald", "busybox", "sh", "-c", "touch /goofy/testfile; top") - c.Assert(err, checker.IsNil, check.Commentf("Output: %s", out)) + assert.NilError(c, err, "Output: %s", out) + user := s.findUser(c, "userns") c.Assert(uidgid[0], checker.Equals, user) // check that the created directory is owned by remapped uid:gid statNotExists, err := system.Stat(tmpDirNotExists) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) c.Assert(statNotExists.UID(), checker.Equals, uint32(uid), check.Commentf("Created directory not owned by remapped root UID")) c.Assert(statNotExists.GID(), checker.Equals, uint32(gid), check.Commentf("Created directory not owned by remapped root GID")) @@ -64,16 +66,16 @@ func (s *DockerDaemonSuite) TestDaemonUserNamespaceRootSetting(c *check.C) { _, err = RunCommandPipelineWithOutput( exec.Command("cat", "/proc/"+strings.TrimSpace(pid)+"/uid_map"), exec.Command("grep", "-E", fmt.Sprintf("0[[:space:]]+%d[[:space:]]+", uid))) - c.Assert(err, check.IsNil) + assert.NilError(c, err) _, err = RunCommandPipelineWithOutput( exec.Command("cat", "/proc/"+strings.TrimSpace(pid)+"/gid_map"), exec.Command("grep", "-E", fmt.Sprintf("0[[:space:]]+%d[[:space:]]+", gid))) - c.Assert(err, check.IsNil) + assert.NilError(c, err) // check that the touched file is owned by remapped uid:gid stat, err := system.Stat(filepath.Join(tmpDir, "testfile")) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) c.Assert(stat.UID(), checker.Equals, uint32(uid), check.Commentf("Touched file not owned by remapped root UID")) c.Assert(stat.GID(), checker.Equals, uint32(gid), check.Commentf("Touched file not owned by remapped root GID")) diff --git a/components/engine/integration-cli/docker_cli_v2_only_test.go b/components/engine/integration-cli/docker_cli_v2_only_test.go index df0c01a517..aa15694523 100644 --- a/components/engine/integration-cli/docker_cli_v2_only_test.go +++ b/components/engine/integration-cli/docker_cli_v2_only_test.go @@ -8,6 +8,7 @@ import ( "github.com/docker/docker/internal/test/registry" "github.com/go-check/check" + "gotest.tools/assert" ) func makefile(path string, contents string) (string, error) { @@ -27,7 +28,7 @@ func makefile(path string, contents string) (string, error) { func (s *DockerRegistrySuite) TestV2Only(c *check.C) { reg, err := registry.NewMock(c) defer reg.Close() - c.Assert(err, check.IsNil) + assert.NilError(c, err) reg.RegisterHandler("/v2/", func(w http.ResponseWriter, r *http.Request) { w.WriteHeader(404) @@ -42,11 +43,11 @@ func (s *DockerRegistrySuite) TestV2Only(c *check.C) { s.d.Start(c, "--insecure-registry", reg.URL()) tmp, err := ioutil.TempDir("", "integration-cli-") - c.Assert(err, check.IsNil) + assert.NilError(c, err) defer os.RemoveAll(tmp) dockerfileName, err := makefile(tmp, fmt.Sprintf("FROM %s/busybox", reg.URL())) - c.Assert(err, check.IsNil, check.Commentf("Unable to create test dockerfile")) + assert.NilError(c, err, "Unable to create test dockerfile") s.d.Cmd("build", "--file", dockerfileName, tmp) diff --git a/components/engine/integration-cli/docker_cli_volume_test.go b/components/engine/integration-cli/docker_cli_volume_test.go index dea1c25587..8e6321f3ed 100644 --- a/components/engine/integration-cli/docker_cli_volume_test.go +++ b/components/engine/integration-cli/docker_cli_volume_test.go @@ -16,6 +16,7 @@ import ( "github.com/docker/docker/integration-cli/checker" "github.com/docker/docker/integration-cli/cli/build" "github.com/go-check/check" + "gotest.tools/assert" "gotest.tools/icmd" ) @@ -23,7 +24,7 @@ func (s *DockerSuite) TestVolumeCLICreate(c *check.C) { dockerCmd(c, "volume", "create") _, _, err := dockerCmdWithError("volume", "create", "-d", "nosuchdriver") - c.Assert(err, check.NotNil) + assert.ErrorContains(c, err, "") // test using hidden --name option out, _ := dockerCmd(c, "volume", "create", "--name=test") @@ -100,32 +101,16 @@ func (s *DockerSuite) TestVolumeLsFormatDefaultFormat(c *check.C) { "volumesFormat": "{{ .Name }} default" }` d, err := ioutil.TempDir("", "integration-cli-") - c.Assert(err, checker.IsNil) + assert.NilError(c, err) defer os.RemoveAll(d) err = ioutil.WriteFile(filepath.Join(d, "config.json"), []byte(config), 0644) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) out, _ := dockerCmd(c, "--config", d, "volume", "ls") assertVolumesInList(c, out, []string{"aaa default", "soo default", "test default"}) } -// assertVolList checks volume retrieved with ls command -// equals to expected volume list -// note: out should be `volume ls [option]` result -func assertVolList(c *check.C, out string, expectVols []string) { - lines := strings.Split(out, "\n") - var volList []string - for _, line := range lines[1 : len(lines)-1] { - volFields := strings.Fields(line) - // wrap all volume name in volList - volList = append(volList, volFields[1]) - } - - // volume ls should contains all expected volumes - c.Assert(volList, checker.DeepEquals, expectVols) -} - func assertVolumesInList(c *check.C, out string, expected []string) { lines := strings.Split(strings.TrimSpace(string(out)), "\n") for _, expect := range expected { @@ -136,7 +121,7 @@ func assertVolumesInList(c *check.C, out string, expected []string) { break } } - c.Assert(found, checker.Equals, true, check.Commentf("Expected volume not found: %v, got: %v", expect, lines)) + assert.Assert(c, found, "Expected volume not found: %v, got: %v", expect, lines) } } @@ -192,13 +177,13 @@ func (s *DockerSuite) TestVolumeCLILsFilterDangling(c *check.C) { func (s *DockerSuite) TestVolumeCLILsErrorWithInvalidFilterName(c *check.C) { out, _, err := dockerCmdWithError("volume", "ls", "-f", "FOO=123") - c.Assert(err, checker.NotNil) + assert.ErrorContains(c, err, "") c.Assert(out, checker.Contains, "Invalid filter") } func (s *DockerSuite) TestVolumeCLILsWithIncorrectFilterValue(c *check.C) { out, _, err := dockerCmdWithError("volume", "ls", "-f", "dangling=invalid") - c.Assert(err, check.NotNil) + assert.ErrorContains(c, err, "") c.Assert(out, checker.Contains, "Invalid filter") } @@ -301,7 +286,7 @@ func (s *DockerSuite) TestVolumeCLICreateLabel(c *check.C) { testValue := "bar" _, _, err := dockerCmdWithError("volume", "create", "--label", testLabel+"="+testValue, testVol) - c.Assert(err, check.IsNil) + assert.NilError(c, err) out, _ := dockerCmd(c, "volume", "inspect", "--format={{ .Labels."+testLabel+" }}", testVol) c.Assert(strings.TrimSpace(out), check.Equals, testValue) @@ -326,7 +311,7 @@ func (s *DockerSuite) TestVolumeCLICreateLabelMultiple(c *check.C) { } _, _, err := dockerCmdWithError(args...) - c.Assert(err, check.IsNil) + assert.NilError(c, err) for k, v := range testLabels { out, _ := dockerCmd(c, "volume", "inspect", "--format={{ .Labels."+k+" }}", testVol) @@ -337,11 +322,11 @@ func (s *DockerSuite) TestVolumeCLICreateLabelMultiple(c *check.C) { func (s *DockerSuite) TestVolumeCLILsFilterLabels(c *check.C) { testVol1 := "testvolcreatelabel-1" _, _, err := dockerCmdWithError("volume", "create", "--label", "foo=bar1", testVol1) - c.Assert(err, check.IsNil) + assert.NilError(c, err) testVol2 := "testvolcreatelabel-2" _, _, err = dockerCmdWithError("volume", "create", "--label", "foo=bar2", testVol2) - c.Assert(err, check.IsNil) + assert.NilError(c, err) out, _ := dockerCmd(c, "volume", "ls", "--filter", "label=foo") @@ -368,11 +353,11 @@ func (s *DockerSuite) TestVolumeCLILsFilterDrivers(c *check.C) { // using default volume driver local to create volumes testVol1 := "testvol-1" _, _, err := dockerCmdWithError("volume", "create", testVol1) - c.Assert(err, check.IsNil) + assert.NilError(c, err) testVol2 := "testvol-2" _, _, err = dockerCmdWithError("volume", "create", testVol2) - c.Assert(err, check.IsNil) + assert.NilError(c, err) // filter with driver=local out, _ := dockerCmd(c, "volume", "ls", "--filter", "driver=local") @@ -412,7 +397,7 @@ func (s *DockerSuite) TestVolumeCLIRmForce(c *check.C) { c.Assert(id, checker.Equals, name) out, _ = dockerCmd(c, "volume", "inspect", "--format", "{{.Mountpoint}}", name) - c.Assert(strings.TrimSpace(out), checker.Not(checker.Equals), "") + 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) @@ -438,8 +423,8 @@ func (s *DockerSuite) TestVolumeCLIRmForceInUse(c *check.C) { cid := strings.TrimSpace(out) _, _, err := dockerCmdWithError("volume", "rm", "-f", name) - c.Assert(err, check.NotNil) - c.Assert(err.Error(), checker.Contains, "volume is in use") + assert.ErrorContains(c, err, "") + assert.ErrorContains(c, err, "volume is in use") out, _ = dockerCmd(c, "volume", "ls") c.Assert(out, checker.Contains, name) @@ -448,8 +433,8 @@ func (s *DockerSuite) TestVolumeCLIRmForceInUse(c *check.C) { // Calling `volume rm` a second time to confirm it's not removed // when calling twice. _, _, err = dockerCmdWithError("volume", "rm", "-f", name) - c.Assert(err, check.NotNil) - c.Assert(err.Error(), checker.Contains, "volume is in use") + assert.ErrorContains(c, err, "") + assert.ErrorContains(c, err, "volume is in use") out, _ = dockerCmd(c, "volume", "ls") c.Assert(out, checker.Contains, name) @@ -516,7 +501,7 @@ func (s *DockerSuite) TestDuplicateMountpointsForVolumesFrom(c *check.C) { // Only the second volume will be referenced, this is backward compatible out, _ = dockerCmd(c, "inspect", "--format", "{{(index .Mounts 0).Name}}", "app") - c.Assert(strings.TrimSpace(out), checker.Equals, data2) + assert.Equal(c, strings.TrimSpace(out), data2) dockerCmd(c, "rm", "-f", "-v", "app") dockerCmd(c, "rm", "-f", "-v", "data1") @@ -598,10 +583,10 @@ func (s *DockerSuite) TestDuplicateMountpointsForVolumesFromAndMounts(c *check.C c.Assert(strings.TrimSpace(out), checker.Contains, data2) err := os.MkdirAll("/tmp/data", 0755) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) // Mounts is available in API cli, err := client.NewClientWithOpts(client.FromEnv) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) defer cli.Close() config := container.Config{ @@ -621,7 +606,7 @@ func (s *DockerSuite) TestDuplicateMountpointsForVolumesFromAndMounts(c *check.C } _, err = cli.ContainerCreate(context.Background(), &config, &hostConfig, &network.NetworkingConfig{}, "app") - c.Assert(err, checker.IsNil) + 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") diff --git a/components/engine/integration-cli/docker_deprecated_api_v124_test.go b/components/engine/integration-cli/docker_deprecated_api_v124_test.go index ffb06da40f..03fc72de33 100644 --- a/components/engine/integration-cli/docker_deprecated_api_v124_test.go +++ b/components/engine/integration-cli/docker_deprecated_api_v124_test.go @@ -8,9 +8,10 @@ import ( "strings" "github.com/docker/docker/api/types/versions" - "github.com/docker/docker/integration-cli/checker" "github.com/docker/docker/internal/test/request" "github.com/go-check/check" + "gotest.tools/assert" + is "gotest.tools/assert/cmp" ) func formatV123StartAPIURL(url string) string { @@ -24,15 +25,15 @@ func (s *DockerSuite) TestDeprecatedContainerAPIStartHostConfig(c *check.C) { "Binds": []string{"/aa:/bb"}, } res, body, err := request.Post("/containers/"+name+"/start", request.JSONBody(config)) - c.Assert(err, checker.IsNil) - c.Assert(res.StatusCode, checker.Equals, http.StatusBadRequest) + assert.NilError(c, err) + assert.Equal(c, res.StatusCode, http.StatusBadRequest) if versions.GreaterThanOrEqualTo(testEnv.DaemonAPIVersion(), "1.32") { // assertions below won't work before 1.32 buf, err := request.ReadBody(body) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) - c.Assert(res.StatusCode, checker.Equals, http.StatusBadRequest) - c.Assert(string(buf), checker.Contains, "was deprecated since API v1.22") + assert.Equal(c, res.StatusCode, http.StatusBadRequest) + assert.Assert(c, strings.Contains(string(buf), "was deprecated since API v1.22")) } } @@ -50,20 +51,20 @@ func (s *DockerSuite) TestDeprecatedContainerAPIStartVolumeBinds(c *check.C) { } res, _, err := request.Post(formatV123StartAPIURL("/containers/create?name="+name), request.JSONBody(config)) - c.Assert(err, checker.IsNil) - c.Assert(res.StatusCode, checker.Equals, http.StatusCreated) + assert.NilError(c, err) + assert.Equal(c, res.StatusCode, http.StatusCreated) bindPath := RandomTmpDirPath("test", testEnv.OSType) config = map[string]interface{}{ "Binds": []string{bindPath + ":" + path}, } res, _, err = request.Post(formatV123StartAPIURL("/containers/"+name+"/start"), request.JSONBody(config)) - c.Assert(err, checker.IsNil) - c.Assert(res.StatusCode, checker.Equals, http.StatusNoContent) + assert.NilError(c, err) + assert.Equal(c, res.StatusCode, http.StatusNoContent) pth, err := inspectMountSourceField(name, path) - c.Assert(err, checker.IsNil) - c.Assert(pth, checker.Equals, bindPath, check.Commentf("expected volume host path to be %s, got %s", bindPath, pth)) + assert.NilError(c, err) + assert.Equal(c, pth, bindPath, "expected volume host path to be %s, got %s", bindPath, pth) } // Test for GH#10618 @@ -77,8 +78,8 @@ func (s *DockerSuite) TestDeprecatedContainerAPIStartDupVolumeBinds(c *check.C) } res, _, err := request.Post(formatV123StartAPIURL("/containers/create?name="+name), request.JSONBody(config)) - c.Assert(err, checker.IsNil) - c.Assert(res.StatusCode, checker.Equals, http.StatusCreated) + assert.NilError(c, err) + assert.Equal(c, res.StatusCode, http.StatusCreated) bindPath1 := RandomTmpDirPath("test1", testEnv.OSType) bindPath2 := RandomTmpDirPath("test2", testEnv.OSType) @@ -87,17 +88,17 @@ func (s *DockerSuite) TestDeprecatedContainerAPIStartDupVolumeBinds(c *check.C) "Binds": []string{bindPath1 + ":/tmp", bindPath2 + ":/tmp"}, } res, body, err := request.Post(formatV123StartAPIURL("/containers/"+name+"/start"), request.JSONBody(config)) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) buf, err := request.ReadBody(body) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) if versions.LessThan(testEnv.DaemonAPIVersion(), "1.32") { - c.Assert(res.StatusCode, checker.Equals, http.StatusInternalServerError) + assert.Equal(c, res.StatusCode, http.StatusInternalServerError) } else { - c.Assert(res.StatusCode, checker.Equals, http.StatusBadRequest) + assert.Equal(c, res.StatusCode, http.StatusBadRequest) } - c.Assert(string(buf), checker.Contains, "Duplicate mount point", check.Commentf("Expected failure due to duplicate bind mounts to same path, instead got: %q with error: %v", string(buf), err)) + assert.Assert(c, strings.Contains(string(buf), "Duplicate mount point"), "Expected failure due to duplicate bind mounts to same path, instead got: %q with error: %v", string(buf), err) } func (s *DockerSuite) TestDeprecatedContainerAPIStartVolumesFrom(c *check.C) { @@ -115,21 +116,21 @@ func (s *DockerSuite) TestDeprecatedContainerAPIStartVolumesFrom(c *check.C) { } res, _, err := request.Post(formatV123StartAPIURL("/containers/create?name="+name), request.JSONBody(config)) - c.Assert(err, checker.IsNil) - c.Assert(res.StatusCode, checker.Equals, http.StatusCreated) + assert.NilError(c, err) + assert.Equal(c, res.StatusCode, http.StatusCreated) config = map[string]interface{}{ "VolumesFrom": []string{volName}, } res, _, err = request.Post(formatV123StartAPIURL("/containers/"+name+"/start"), request.JSONBody(config)) - c.Assert(err, checker.IsNil) - c.Assert(res.StatusCode, checker.Equals, http.StatusNoContent) + assert.NilError(c, err) + assert.Equal(c, res.StatusCode, http.StatusNoContent) pth, err := inspectMountSourceField(name, volPath) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) pth2, err := inspectMountSourceField(volName, volPath) - c.Assert(err, checker.IsNil) - c.Assert(pth, checker.Equals, pth2, check.Commentf("expected volume host path to be %s, got %s", pth, pth2)) + assert.NilError(c, err) + assert.Equal(c, pth, pth2, "expected volume host path to be %s, got %s", pth, pth2) } // #9981 - Allow a docker created volume (ie, one in /var/lib/docker/volumes) to be used to overwrite (via passing in Binds on api start) an existing volume @@ -139,18 +140,18 @@ func (s *DockerSuite) TestDeprecatedPostContainerBindNormalVolume(c *check.C) { dockerCmd(c, "create", "-v", "/foo", "--name=one", "busybox") fooDir, err := inspectMountSourceField("one", "/foo") - c.Assert(err, checker.IsNil) + assert.NilError(c, err) dockerCmd(c, "create", "-v", "/foo", "--name=two", "busybox") bindSpec := map[string][]string{"Binds": {fooDir + ":/foo"}} res, _, err := request.Post(formatV123StartAPIURL("/containers/two/start"), request.JSONBody(bindSpec)) - c.Assert(err, checker.IsNil) - c.Assert(res.StatusCode, checker.Equals, http.StatusNoContent) + assert.NilError(c, err) + assert.Equal(c, res.StatusCode, http.StatusNoContent) fooDir2, err := inspectMountSourceField("two", "/foo") - c.Assert(err, checker.IsNil) - c.Assert(fooDir2, checker.Equals, fooDir, check.Commentf("expected volume path to be %s, got: %s", fooDir, fooDir2)) + assert.NilError(c, err) + assert.Equal(c, fooDir2, fooDir, "expected volume path to be %s, got: %s", fooDir, fooDir2) } func (s *DockerSuite) TestDeprecatedStartWithTooLowMemoryLimit(c *check.C) { @@ -166,15 +167,15 @@ func (s *DockerSuite) TestDeprecatedStartWithTooLowMemoryLimit(c *check.C) { }` res, body, err := request.Post(formatV123StartAPIURL("/containers/"+containerID+"/start"), request.RawString(config), request.JSON) - c.Assert(err, checker.IsNil) - b, err2 := request.ReadBody(body) - c.Assert(err2, checker.IsNil) + assert.NilError(c, err) + b, err := request.ReadBody(body) + assert.NilError(c, err) if versions.LessThan(testEnv.DaemonAPIVersion(), "1.32") { - c.Assert(res.StatusCode, checker.Equals, http.StatusInternalServerError) + assert.Equal(c, res.StatusCode, http.StatusInternalServerError) } else { - c.Assert(res.StatusCode, checker.Equals, http.StatusBadRequest) + assert.Equal(c, res.StatusCode, http.StatusBadRequest) } - c.Assert(string(b), checker.Contains, "Minimum memory limit allowed is 4MB") + assert.Assert(c, is.Contains(string(b), "Minimum memory limit allowed is 4MB")) } // #14640 @@ -189,8 +190,8 @@ func (s *DockerSuite) TestDeprecatedPostContainersStartWithoutLinksInHostConfig( config := `{"HostConfig":` + hc + `}` res, b, err := request.Post(formatV123StartAPIURL("/containers/"+name+"/start"), request.RawString(config), request.JSON) - c.Assert(err, checker.IsNil) - c.Assert(res.StatusCode, checker.Equals, http.StatusNoContent) + assert.NilError(c, err) + assert.Equal(c, res.StatusCode, http.StatusNoContent) b.Close() } @@ -207,8 +208,8 @@ func (s *DockerSuite) TestDeprecatedPostContainersStartWithLinksInHostConfig(c * config := `{"HostConfig":` + hc + `}` res, b, err := request.Post(formatV123StartAPIURL("/containers/"+name+"/start"), request.RawString(config), request.JSON) - c.Assert(err, checker.IsNil) - c.Assert(res.StatusCode, checker.Equals, http.StatusNoContent) + assert.NilError(c, err) + assert.Equal(c, res.StatusCode, http.StatusNoContent) b.Close() } @@ -227,8 +228,8 @@ func (s *DockerSuite) TestDeprecatedPostContainersStartWithLinksInHostConfigIdLi config := `{"HostConfig":` + hc + `}` res, b, err := request.Post(formatV123StartAPIURL("/containers/"+name+"/start"), request.RawString(config), request.JSON) - c.Assert(err, checker.IsNil) - c.Assert(res.StatusCode, checker.Equals, http.StatusNoContent) + assert.NilError(c, err) + assert.Equal(c, res.StatusCode, http.StatusNoContent) b.Close() } @@ -241,10 +242,10 @@ func (s *DockerSuite) TestDeprecatedStartWithNilDNS(c *check.C) { config := `{"HostConfig": {"Dns": null}}` res, b, err := request.Post(formatV123StartAPIURL("/containers/"+containerID+"/start"), request.RawString(config), request.JSON) - c.Assert(err, checker.IsNil) - c.Assert(res.StatusCode, checker.Equals, http.StatusNoContent) + assert.NilError(c, err) + assert.Equal(c, res.StatusCode, http.StatusNoContent) b.Close() dns := inspectFieldJSON(c, containerID, "HostConfig.Dns") - c.Assert(dns, checker.Equals, "[]") + assert.Equal(c, dns, "[]") } diff --git a/components/engine/integration-cli/docker_deprecated_api_v124_unix_test.go b/components/engine/integration-cli/docker_deprecated_api_v124_unix_test.go index c182b2a7aa..0aae30be80 100644 --- a/components/engine/integration-cli/docker_deprecated_api_v124_unix_test.go +++ b/components/engine/integration-cli/docker_deprecated_api_v124_unix_test.go @@ -3,11 +3,11 @@ package main import ( - "fmt" + "strings" - "github.com/docker/docker/integration-cli/checker" "github.com/docker/docker/internal/test/request" "github.com/go-check/check" + "gotest.tools/assert" ) // #19100 This is a deprecated feature test, it should be removed in Docker 1.12 @@ -23,9 +23,9 @@ func (s *DockerNetworkSuite) TestDeprecatedDockerNetworkStartAPIWithHostconfig(c }, } _, _, err := request.Post(formatV123StartAPIURL("/containers/"+conName+"/start"), request.JSONBody(config)) - c.Assert(err, checker.IsNil) - c.Assert(waitRun(conName), checker.IsNil) + assert.NilError(c, err) + assert.NilError(c, waitRun(conName)) networks := inspectField(c, conName, "NetworkSettings.Networks") - c.Assert(networks, checker.Contains, netName, check.Commentf(fmt.Sprintf("Should contain '%s' network", netName))) - c.Assert(networks, checker.Not(checker.Contains), "bridge", check.Commentf("Should not contain 'bridge' network")) + assert.Assert(c, strings.Contains(networks, netName), "Should contain '%s' network", netName) + assert.Assert(c, !strings.Contains(networks, "bridge"), "Should not contain 'bridge' network") } diff --git a/components/engine/integration-cli/docker_utils_test.go b/components/engine/integration-cli/docker_utils_test.go index 8052c7951f..c142564483 100644 --- a/components/engine/integration-cli/docker_utils_test.go +++ b/components/engine/integration-cli/docker_utils_test.go @@ -16,10 +16,10 @@ import ( "github.com/docker/docker/api/types" "github.com/docker/docker/client" - "github.com/docker/docker/integration-cli/checker" "github.com/docker/docker/integration-cli/cli" "github.com/docker/docker/integration-cli/daemon" "github.com/go-check/check" + "gotest.tools/assert" "gotest.tools/icmd" ) @@ -66,7 +66,7 @@ func getContainerCount(c *check.C) int { output = strings.TrimLeft(output, containers) output = strings.Trim(output, " ") containerCount, err := strconv.Atoi(output) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) return containerCount } } @@ -100,7 +100,7 @@ func inspectFieldWithError(name, field string) (string, error) { func inspectField(c *check.C, name, field string) string { out, err := inspectFilter(name, fmt.Sprintf(".%s", field)) if c != nil { - c.Assert(err, check.IsNil) + assert.NilError(c, err) } return out } @@ -109,7 +109,7 @@ func inspectField(c *check.C, name, field string) string { func inspectFieldJSON(c *check.C, name, field string) string { out, err := inspectFilter(name, fmt.Sprintf("json .%s", field)) if c != nil { - c.Assert(err, check.IsNil) + assert.NilError(c, err) } return out } @@ -118,7 +118,7 @@ func inspectFieldJSON(c *check.C, name, field string) string { func inspectFieldMap(c *check.C, name, path, field string) string { out, err := inspectFilter(name, fmt.Sprintf("index .%s %q", path, field)) if c != nil { - c.Assert(err, check.IsNil) + assert.NilError(c, err) } return out } @@ -181,7 +181,7 @@ func inspectImage(c *check.C, name, filter string) string { func getIDByName(c *check.C, name string) string { id, err := inspectFieldWithError(name, "Id") - c.Assert(err, checker.IsNil) + assert.NilError(c, err) return id } @@ -203,18 +203,18 @@ func writeFile(dst, content string, c *check.C) { // Create subdirectories if necessary c.Assert(os.MkdirAll(path.Dir(dst), 0700), check.IsNil) f, err := os.OpenFile(dst, os.O_CREATE|os.O_RDWR|os.O_TRUNC, 0700) - c.Assert(err, check.IsNil) + assert.NilError(c, err) defer f.Close() // Write content (truncate if it exists) _, err = io.Copy(f, strings.NewReader(content)) - c.Assert(err, check.IsNil) + assert.NilError(c, err) } // Return the contents of file at path `src`. // Fail the test when error occurs. func readFile(src string, c *check.C) (content string) { data, err := ioutil.ReadFile(src) - c.Assert(err, check.IsNil) + assert.NilError(c, err) return string(data) } @@ -236,11 +236,11 @@ func runCommandAndReadContainerFile(c *check.C, filename string, command string, func readContainerFile(c *check.C, containerID, filename string) []byte { f, err := os.Open(containerStorageFile(containerID, filename)) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) defer f.Close() content, err := ioutil.ReadAll(f) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) return content } @@ -256,11 +256,11 @@ func daemonTime(c *check.C) time.Time { return time.Now() } cli, err := client.NewClientWithOpts(client.FromEnv) - c.Assert(err, check.IsNil) + assert.NilError(c, err) defer cli.Close() info, err := cli.Info(context.Background()) - c.Assert(err, check.IsNil) + assert.NilError(c, err) dt, err := time.Parse(time.RFC3339Nano, info.SystemTime) c.Assert(err, check.IsNil, check.Commentf("invalid time format in GET /info response")) @@ -306,12 +306,12 @@ func appendBaseEnv(isTLS bool, env ...string) []string { func createTmpFile(c *check.C, content string) string { f, err := ioutil.TempFile("", "testfile") - c.Assert(err, check.IsNil) + assert.NilError(c, err) filename := f.Name() err = ioutil.WriteFile(filename, []byte(content), 0644) - c.Assert(err, check.IsNil) + assert.NilError(c, err) return filename } @@ -337,10 +337,10 @@ func waitInspectWithArgs(name, expr, expected string, timeout time.Duration, arg func getInspectBody(c *check.C, version, id string) []byte { cli, err := client.NewClientWithOpts(client.FromEnv, client.WithVersion(version)) - c.Assert(err, check.IsNil) + assert.NilError(c, err) defer cli.Close() _, body, err := cli.ContainerInspectWithRaw(context.Background(), id, false) - c.Assert(err, check.IsNil) + assert.NilError(c, err) return body } diff --git a/components/engine/integration-cli/events_utils_test.go b/components/engine/integration-cli/events_utils_test.go index 356b2c326d..f63082af9f 100644 --- a/components/engine/integration-cli/events_utils_test.go +++ b/components/engine/integration-cli/events_utils_test.go @@ -10,9 +10,9 @@ import ( "strings" eventstestutils "github.com/docker/docker/daemon/events/testutils" - "github.com/docker/docker/integration-cli/checker" "github.com/go-check/check" "github.com/sirupsen/logrus" + "gotest.tools/assert" ) // eventMatcher is a function that tries to match an event input. @@ -155,7 +155,7 @@ func eventActionsByIDAndType(c *check.C, events []string, id, eventType string) var filtered []string for _, event := range events { matches := eventstestutils.ScanMap(event) - c.Assert(matches, checker.Not(checker.IsNil)) + assert.Assert(c, matches != nil) if matchIDAndEventType(matches, id, eventType) { filtered = append(filtered, matches["action"]) } @@ -188,8 +188,8 @@ func parseEvents(c *check.C, out, match string) { for _, event := range events { matches := eventstestutils.ScanMap(event) matched, err := regexp.MatchString(match, matches["action"]) - c.Assert(err, checker.IsNil) - c.Assert(matched, checker.True, check.Commentf("Matcher: %s did not match %s", match, matches["action"])) + assert.NilError(c, err) + assert.Assert(c, matched, "Matcher: %s did not match %s", match, matches["action"]) } } @@ -197,10 +197,10 @@ func parseEventsWithID(c *check.C, out, match, id string) { events := strings.Split(strings.TrimSpace(out), "\n") for _, event := range events { matches := eventstestutils.ScanMap(event) - c.Assert(matchEventID(matches, id), checker.True) + assert.Assert(c, matchEventID(matches, id)) matched, err := regexp.MatchString(match, matches["action"]) - c.Assert(err, checker.IsNil) - c.Assert(matched, checker.True, check.Commentf("Matcher: %s did not match %s", match, matches["action"])) + assert.NilError(c, err) + assert.Assert(c, matched, "Matcher: %s did not match %s", match, matches["action"]) } } diff --git a/components/engine/integration-cli/fixtures_linux_daemon_test.go b/components/engine/integration-cli/fixtures_linux_daemon_test.go index 2387a9ebee..5c874ec14b 100644 --- a/components/engine/integration-cli/fixtures_linux_daemon_test.go +++ b/components/engine/integration-cli/fixtures_linux_daemon_test.go @@ -10,9 +10,9 @@ import ( "strings" "sync" - "github.com/docker/docker/integration-cli/checker" "github.com/docker/docker/internal/test/fixtures/load" "github.com/go-check/check" + "gotest.tools/assert" ) type testingT interface { @@ -44,21 +44,21 @@ func ensureSyscallTest(c *check.C) { } tmp, err := ioutil.TempDir("", "syscall-test-build") - c.Assert(err, checker.IsNil, check.Commentf("couldn't create temp dir")) + assert.NilError(c, err, "couldn't create temp dir") defer os.RemoveAll(tmp) gcc, err := exec.LookPath("gcc") - c.Assert(err, checker.IsNil, check.Commentf("could not find gcc")) + assert.NilError(c, err, "could not find gcc") tests := []string{"userns", "ns", "acct", "setuid", "setgid", "socket", "raw"} for _, test := range tests { out, err := exec.Command(gcc, "-g", "-Wall", "-static", fmt.Sprintf("../contrib/syscall-test/%s.c", test), "-o", fmt.Sprintf("%s/%s-test", tmp, test)).CombinedOutput() - c.Assert(err, checker.IsNil, check.Commentf(string(out))) + assert.NilError(c, err, string(out)) } if runtime.GOOS == "linux" && runtime.GOARCH == "amd64" { out, err := exec.Command(gcc, "-s", "-m32", "-nostdlib", "-static", "../contrib/syscall-test/exit32.s", "-o", tmp+"/"+"exit32-test").CombinedOutput() - c.Assert(err, checker.IsNil, check.Commentf(string(out))) + assert.NilError(c, err, string(out)) } dockerFile := filepath.Join(tmp, "Dockerfile") @@ -67,7 +67,7 @@ func ensureSyscallTest(c *check.C) { COPY . /usr/bin/ `) err = ioutil.WriteFile(dockerFile, content, 600) - c.Assert(err, checker.IsNil) + assert.NilError(c, err) var buildArgs []string if arg := os.Getenv("DOCKER_BUILD_ARGS"); strings.TrimSpace(arg) != "" { @@ -80,7 +80,7 @@ func ensureSyscallTest(c *check.C) { func ensureSyscallTestBuild(c *check.C) { err := load.FrozenImagesLinux(testEnv.APIClient(), "buildpack-deps:jessie") - c.Assert(err, checker.IsNil) + assert.NilError(c, err) var buildArgs []string if arg := os.Getenv("DOCKER_BUILD_ARGS"); strings.TrimSpace(arg) != "" { @@ -99,13 +99,13 @@ func ensureNNPTest(c *check.C) { } tmp, err := ioutil.TempDir("", "docker-nnp-test") - c.Assert(err, checker.IsNil) + assert.NilError(c, err) gcc, err := exec.LookPath("gcc") - c.Assert(err, checker.IsNil, check.Commentf("could not find gcc")) + assert.NilError(c, err, "could not find gcc") out, err := exec.Command(gcc, "-g", "-Wall", "-static", "../contrib/nnp-test/nnp-test.c", "-o", filepath.Join(tmp, "nnp-test")).CombinedOutput() - c.Assert(err, checker.IsNil, check.Commentf(string(out))) + assert.NilError(c, err, string(out)) dockerfile := filepath.Join(tmp, "Dockerfile") content := ` @@ -114,7 +114,7 @@ func ensureNNPTest(c *check.C) { RUN chmod +s /usr/bin/nnp-test ` err = ioutil.WriteFile(dockerfile, []byte(content), 600) - c.Assert(err, checker.IsNil, check.Commentf("could not write Dockerfile for nnp-test image")) + assert.NilError(c, err, "could not write Dockerfile for nnp-test image") var buildArgs []string if arg := os.Getenv("DOCKER_BUILD_ARGS"); strings.TrimSpace(arg) != "" { @@ -127,7 +127,7 @@ func ensureNNPTest(c *check.C) { func ensureNNPTestBuild(c *check.C) { err := load.FrozenImagesLinux(testEnv.APIClient(), "buildpack-deps:jessie") - c.Assert(err, checker.IsNil) + assert.NilError(c, err) var buildArgs []string if arg := os.Getenv("DOCKER_BUILD_ARGS"); strings.TrimSpace(arg) != "" { From 461407c57d88df6fd487c89f34771b93f58430cc Mon Sep 17 00:00:00 2001 From: Sebastiaan van Stijn Date: Thu, 18 Apr 2019 00:26:43 +0200 Subject: [PATCH 43/45] Migrate some remaining Manifest V1 tests Signed-off-by: Sebastiaan van Stijn Upstream-commit: 7e65b6978b9137dad8c2bf70c0812e4cb25ff25c Component: engine --- .../integration-cli/docker_cli_push_test.go | 19 ++++++++++--------- 1 file changed, 10 insertions(+), 9 deletions(-) diff --git a/components/engine/integration-cli/docker_cli_push_test.go b/components/engine/integration-cli/docker_cli_push_test.go index ebef8493ef..7d8530a033 100644 --- a/components/engine/integration-cli/docker_cli_push_test.go +++ b/components/engine/integration-cli/docker_cli_push_test.go @@ -1,7 +1,6 @@ package main import ( - "archive/tar" "fmt" "io/ioutil" "net/http" @@ -10,6 +9,8 @@ import ( "strings" "sync" + "archive/tar" + "github.com/docker/distribution/reference" "github.com/docker/docker/integration-cli/cli/build" "github.com/go-check/check" @@ -252,31 +253,31 @@ func (s *DockerSchema1RegistrySuite) TestCrossRepositoryLayerPushNotSupported(c dockerCmd(c, "tag", "busybox", sourceRepoName) // push the image to the registry out1, _, err := dockerCmdWithError("push", sourceRepoName) - c.Assert(err, check.IsNil, check.Commentf("pushing the image to the private registry has failed: %s", out1)) + assert.NilError(c, err, "pushing the image to the private registry has failed: %s", out1) // ensure that none of the layers were mounted from another repository during push - c.Assert(strings.Contains(out1, "Mounted from"), check.Equals, false) + assert.Assert(c, !strings.Contains(out1, "Mounted from")) digest1 := reference.DigestRegexp.FindString(out1) - c.Assert(len(digest1), checker.GreaterThan, 0, check.Commentf("no digest found for pushed manifest")) + assert.Assert(c, len(digest1) > 0, "no digest found for pushed manifest") destRepoName := fmt.Sprintf("%v/dockercli/crossrepopush", privateRegistryURL) // retag the image to upload the same layers to another repo in the same registry dockerCmd(c, "tag", "busybox", destRepoName) // push the image to the registry out2, _, err := dockerCmdWithError("push", destRepoName) - c.Assert(err, check.IsNil, check.Commentf("pushing the image to the private registry has failed: %s", out2)) + assert.NilError(c, err, "pushing the image to the private registry has failed: %s", out2) // schema1 registry should not support cross-repo layer mounts, so ensure that this does not happen - c.Assert(strings.Contains(out2, "Mounted from"), check.Equals, false) + assert.Assert(c, !strings.Contains(out2, "Mounted from")) digest2 := reference.DigestRegexp.FindString(out2) - c.Assert(len(digest2), checker.GreaterThan, 0, check.Commentf("no digest found for pushed manifest")) - c.Assert(digest1, check.Not(check.Equals), digest2) + assert.Assert(c, len(digest2) > 0, "no digest found for pushed manifest") + assert.Assert(c, digest1 != digest2) // ensure that we can pull and run the second pushed repository dockerCmd(c, "rmi", destRepoName) dockerCmd(c, "pull", destRepoName) out3, _ := dockerCmd(c, "run", destRepoName, "echo", "-n", "hello world") - c.Assert(out3, check.Equals, "hello world") + assert.Equal(c, out3, "hello world") } func (s *DockerRegistryAuthHtpasswdSuite) TestPushNoCredentialsNoRetry(c *check.C) { From 647deceb071077771da4c2145459052a4675e1c7 Mon Sep 17 00:00:00 2001 From: Stefan Scherer Date: Tue, 15 Jan 2019 18:24:15 +0100 Subject: [PATCH 44/45] Improve 'no matching manifest' error Signed-off-by: Stefan Scherer (cherry picked from commit 4b9db209fe7ed25736244bd2b56faf43a9f908dd) Signed-off-by: Sebastiaan van Stijn (cherry picked from commit 6099336ae61ca43cafe9420f3188c796cb0812bc) Signed-off-by: Sebastiaan van Stijn Upstream-commit: e4bc7d2fc05fcff4817f39e52b34b17a8f56cd9a Component: engine --- components/engine/distribution/pull_v2.go | 2 +- .../engine/distribution/pull_v2_test.go | 23 +++++++++++++++++++ .../engine/distribution/pull_v2_unix.go | 7 ++++++ .../engine/distribution/pull_v2_windows.go | 8 +++++++ 4 files changed, 39 insertions(+), 1 deletion(-) diff --git a/components/engine/distribution/pull_v2.go b/components/engine/distribution/pull_v2.go index 8f05cfa0b2..8a5989597e 100644 --- a/components/engine/distribution/pull_v2.go +++ b/components/engine/distribution/pull_v2.go @@ -756,7 +756,7 @@ func (p *v2Puller) pullManifestList(ctx context.Context, ref reference.Named, mf manifestMatches := filterManifests(mfstList.Manifests, platform) if len(manifestMatches) == 0 { - errMsg := fmt.Sprintf("no matching manifest for %s in the manifest list entries", platforms.Format(platform)) + errMsg := fmt.Sprintf("no matching manifest for %s in the manifest list entries", formatPlatform(platform)) logrus.Debugf(errMsg) return "", "", errors.New(errMsg) } diff --git a/components/engine/distribution/pull_v2_test.go b/components/engine/distribution/pull_v2_test.go index ca3470c8cf..7c14d50026 100644 --- a/components/engine/distribution/pull_v2_test.go +++ b/components/engine/distribution/pull_v2_test.go @@ -2,8 +2,10 @@ package distribution // import "github.com/docker/docker/distribution" import ( "encoding/json" + "fmt" "io/ioutil" "reflect" + "regexp" "runtime" "strings" "testing" @@ -11,6 +13,7 @@ import ( "github.com/docker/distribution/manifest/schema1" "github.com/docker/distribution/reference" "github.com/opencontainers/go-digest" + specs "github.com/opencontainers/image-spec/specs-go/v1" "gotest.tools/assert" is "gotest.tools/assert/cmp" ) @@ -182,3 +185,23 @@ func TestValidateManifest(t *testing.T) { t.Fatal("expected validateManifest to fail with digest error") } } + +func TestFormatPlatform(t *testing.T) { + var platform specs.Platform + var result = formatPlatform(platform) + if strings.HasPrefix(result, "unknown") { + t.Fatal("expected formatPlatform to show a known platform") + } + if !strings.HasPrefix(result, runtime.GOOS) { + t.Fatal("expected formatPlatform to show the current platform") + } + if runtime.GOOS == "windows" { + if !strings.HasPrefix(result, "windows") { + t.Fatal("expected formatPlatform to show windows platform") + } + matches, _ := regexp.MatchString("windows.* [0-9]", result) + if !matches { + t.Fatal(fmt.Sprintf("expected formatPlatform to show windows platform with a version, but got '%s'", result)) + } + } +} diff --git a/components/engine/distribution/pull_v2_unix.go b/components/engine/distribution/pull_v2_unix.go index adbaf41451..fea1eb6e66 100644 --- a/components/engine/distribution/pull_v2_unix.go +++ b/components/engine/distribution/pull_v2_unix.go @@ -58,3 +58,10 @@ func withDefault(p specs.Platform) specs.Platform { } return p } + +func formatPlatform(platform specs.Platform) string { + if platform.OS == "" { + platform = platforms.DefaultSpec() + } + return platforms.Format(platform) +} diff --git a/components/engine/distribution/pull_v2_windows.go b/components/engine/distribution/pull_v2_windows.go index 1ae167ef77..1162e9a8bb 100644 --- a/components/engine/distribution/pull_v2_windows.go +++ b/components/engine/distribution/pull_v2_windows.go @@ -11,6 +11,7 @@ import ( "strconv" "strings" + "github.com/containerd/containerd/platforms" "github.com/docker/distribution" "github.com/docker/distribution/manifest/manifestlist" "github.com/docker/distribution/manifest/schema2" @@ -136,3 +137,10 @@ func checkImageCompatibility(imageOS, imageOSVersion string) error { } return nil } + +func formatPlatform(platform specs.Platform) string { + if platform.OS == "" { + platform = platforms.DefaultSpec() + } + return fmt.Sprintf("%s %s", platforms.Format(platform), system.GetOSVersion().ToString()) +} From 2bb8a5be9736c1c19afb1e8b301c83ba1ff211d4 Mon Sep 17 00:00:00 2001 From: Stefan Scherer Date: Wed, 17 Apr 2019 09:49:48 +0200 Subject: [PATCH 45/45] Use current windows servercore image Signed-off-by: Stefan Scherer (cherry picked from commit aad7e9797b2e9a980b28d7d77bc119cb4b7e57dc) Signed-off-by: Sebastiaan van Stijn Upstream-commit: 04d0295c0cdfe3e67ab51ca611e3a7dd8a49b668 Component: engine --- components/engine/integration-cli/docker_cli_pull_test.go | 6 +++--- 1 file changed, 3 insertions(+), 3 deletions(-) diff --git a/components/engine/integration-cli/docker_cli_pull_test.go b/components/engine/integration-cli/docker_cli_pull_test.go index dbf97568dc..8526a10855 100644 --- a/components/engine/integration-cli/docker_cli_pull_test.go +++ b/components/engine/integration-cli/docker_cli_pull_test.go @@ -266,12 +266,12 @@ func (s *DockerHubPullSuite) TestPullClientDisconnect(c *check.C) { func (s *DockerSuite) TestPullLinuxImageFailsOnWindows(c *check.C) { testRequires(c, DaemonIsWindows, Network) _, _, err := dockerCmdWithError("pull", "ubuntu") - assert.ErrorContains(c, err, "no matching manifest") + assert.ErrorContains(c, err, "no matching manifest for windows") } // Regression test for https://github.com/docker/docker/issues/28892 func (s *DockerSuite) TestPullWindowsImageFailsOnLinux(c *check.C) { testRequires(c, DaemonIsLinux, Network) - _, _, err := dockerCmdWithError("pull", "microsoft/nanoserver") - assert.ErrorContains(c, err, "cannot be used on this platform") + _, _, err := dockerCmdWithError("pull", "mcr.microsoft.com/windows/servercore:ltsc2019") + assert.ErrorContains(c, err, "no matching manifest for linux") }