diff --git a/cli/command/bundlefile/bundlefile_test.go b/cli/command/bundlefile/bundlefile_test.go index bd059c4dca..08bf896db6 100644 --- a/cli/command/bundlefile/bundlefile_test.go +++ b/cli/command/bundlefile/bundlefile_test.go @@ -5,7 +5,8 @@ import ( "strings" "testing" - "github.com/stretchr/testify/assert" + "github.com/gotestyourself/gotestyourself/assert" + is "github.com/gotestyourself/gotestyourself/assert/cmp" ) func TestLoadFileV01Success(t *testing.T) { @@ -25,9 +26,9 @@ func TestLoadFileV01Success(t *testing.T) { }`) bundle, err := LoadFile(reader) - assert.NoError(t, err) - assert.Equal(t, "0.1", bundle.Version) - assert.Len(t, bundle.Services, 2) + assert.Check(t, err) + assert.Check(t, is.Equal("0.1", bundle.Version)) + assert.Check(t, is.Len(bundle.Services, 2)) } func TestLoadFileSyntaxError(t *testing.T) { @@ -37,7 +38,7 @@ func TestLoadFileSyntaxError(t *testing.T) { }`) _, err := LoadFile(reader) - assert.EqualError(t, err, "JSON syntax error at byte 37: invalid character 'u' looking for beginning of value") + assert.Check(t, is.Error(err, "JSON syntax error at byte 37: invalid character 'u' looking for beginning of value")) } func TestLoadFileTypeError(t *testing.T) { @@ -52,7 +53,7 @@ func TestLoadFileTypeError(t *testing.T) { }`) _, err := LoadFile(reader) - assert.EqualError(t, err, "Unexpected type at byte 94. Expected []string but received string.") + assert.Check(t, is.Error(err, "Unexpected type at byte 94. Expected []string but received string.")) } func TestPrint(t *testing.T) { @@ -66,12 +67,12 @@ func TestPrint(t *testing.T) { }, }, } - assert.NoError(t, Print(&buffer, bundle)) + assert.Check(t, Print(&buffer, bundle)) output := buffer.String() - assert.Contains(t, output, "\"Image\": \"image\"") - assert.Contains(t, output, + assert.Check(t, is.Contains(output, "\"Image\": \"image\"")) + assert.Check(t, is.Contains(output, `"Command": [ "echo", "something" - ]`) + ]`)) } diff --git a/cli/command/checkpoint/create_test.go b/cli/command/checkpoint/create_test.go index 19bd3920c0..838e889f1b 100644 --- a/cli/command/checkpoint/create_test.go +++ b/cli/command/checkpoint/create_test.go @@ -8,8 +8,9 @@ import ( "github.com/docker/cli/internal/test" "github.com/docker/cli/internal/test/testutil" "github.com/docker/docker/api/types" + "github.com/gotestyourself/gotestyourself/assert" + is "github.com/gotestyourself/gotestyourself/assert/cmp" "github.com/pkg/errors" - "github.com/stretchr/testify/assert" ) func TestCheckpointCreateErrors(t *testing.T) { @@ -63,10 +64,10 @@ func TestCheckpointCreateWithOptions(t *testing.T) { cmd.SetArgs([]string{"container-foo", checkpoint}) cmd.Flags().Set("leave-running", "true") cmd.Flags().Set("checkpoint-dir", "/dir/foo") - assert.NoError(t, cmd.Execute()) - assert.Equal(t, "container-foo", containerID) - assert.Equal(t, checkpoint, checkpointID) - assert.Equal(t, "/dir/foo", checkpointDir) - assert.Equal(t, false, exit) - assert.Equal(t, checkpoint, strings.TrimSpace(cli.OutBuffer().String())) + assert.Check(t, cmd.Execute()) + assert.Check(t, is.Equal("container-foo", containerID)) + assert.Check(t, is.Equal(checkpoint, checkpointID)) + assert.Check(t, is.Equal("/dir/foo", checkpointDir)) + assert.Check(t, is.Equal(false, exit)) + assert.Check(t, is.Equal(checkpoint, strings.TrimSpace(cli.OutBuffer().String()))) } diff --git a/cli/command/checkpoint/list_test.go b/cli/command/checkpoint/list_test.go index 373460d3be..6c2277b517 100644 --- a/cli/command/checkpoint/list_test.go +++ b/cli/command/checkpoint/list_test.go @@ -7,9 +7,10 @@ import ( "github.com/docker/cli/internal/test" "github.com/docker/cli/internal/test/testutil" "github.com/docker/docker/api/types" + "github.com/gotestyourself/gotestyourself/assert" + is "github.com/gotestyourself/gotestyourself/assert/cmp" "github.com/gotestyourself/gotestyourself/golden" "github.com/pkg/errors" - "github.com/stretchr/testify/assert" ) func TestCheckpointListErrors(t *testing.T) { @@ -60,8 +61,8 @@ func TestCheckpointListWithOptions(t *testing.T) { cmd := newListCommand(cli) cmd.SetArgs([]string{"container-foo"}) cmd.Flags().Set("checkpoint-dir", "/dir/foo") - assert.NoError(t, cmd.Execute()) - assert.Equal(t, "container-foo", containerID) - assert.Equal(t, "/dir/foo", checkpointDir) + assert.Check(t, cmd.Execute()) + assert.Check(t, is.Equal("container-foo", containerID)) + assert.Check(t, is.Equal("/dir/foo", checkpointDir)) golden.Assert(t, cli.OutBuffer().String(), "checkpoint-list-with-options.golden") } diff --git a/cli/command/checkpoint/remove_test.go b/cli/command/checkpoint/remove_test.go index 6100d75e41..386a1a0a12 100644 --- a/cli/command/checkpoint/remove_test.go +++ b/cli/command/checkpoint/remove_test.go @@ -7,8 +7,9 @@ import ( "github.com/docker/cli/internal/test" "github.com/docker/cli/internal/test/testutil" "github.com/docker/docker/api/types" + "github.com/gotestyourself/gotestyourself/assert" + is "github.com/gotestyourself/gotestyourself/assert/cmp" "github.com/pkg/errors" - "github.com/stretchr/testify/assert" ) func TestCheckpointRemoveErrors(t *testing.T) { @@ -58,8 +59,8 @@ func TestCheckpointRemoveWithOptions(t *testing.T) { cmd := newRemoveCommand(cli) cmd.SetArgs([]string{"container-foo", "checkpoint-bar"}) cmd.Flags().Set("checkpoint-dir", "/dir/foo") - assert.NoError(t, cmd.Execute()) - assert.Equal(t, "container-foo", containerID) - assert.Equal(t, "checkpoint-bar", checkpointID) - assert.Equal(t, "/dir/foo", checkpointDir) + assert.Check(t, cmd.Execute()) + assert.Check(t, is.Equal("container-foo", containerID)) + assert.Check(t, is.Equal("checkpoint-bar", checkpointID)) + assert.Check(t, is.Equal("/dir/foo", checkpointDir)) } diff --git a/cli/command/cli_test.go b/cli/command/cli_test.go index 9a440ef138..dec09c8ee5 100644 --- a/cli/command/cli_test.go +++ b/cli/command/cli_test.go @@ -12,10 +12,10 @@ import ( "github.com/docker/docker/api" "github.com/docker/docker/api/types" "github.com/docker/docker/client" + "github.com/gotestyourself/gotestyourself/assert" + is "github.com/gotestyourself/gotestyourself/assert/cmp" "github.com/gotestyourself/gotestyourself/fs" "github.com/pkg/errors" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" "golang.org/x/net/context" ) @@ -28,15 +28,15 @@ func TestNewAPIClientFromFlags(t *testing.T) { }, } apiclient, err := NewAPIClientFromFlags(opts, configFile) - require.NoError(t, err) - assert.Equal(t, host, apiclient.DaemonHost()) + assert.NilError(t, err) + assert.Check(t, is.Equal(host, apiclient.DaemonHost())) expectedHeaders := map[string]string{ "My-Header": "Custom-Value", "User-Agent": UserAgent(), } - assert.Equal(t, expectedHeaders, apiclient.(*client.Client).CustomHTTPHeaders()) - assert.Equal(t, api.DefaultVersion, apiclient.ClientVersion()) + assert.Check(t, is.DeepEqual(expectedHeaders, apiclient.(*client.Client).CustomHTTPHeaders())) + assert.Check(t, is.Equal(api.DefaultVersion, apiclient.ClientVersion())) } func TestNewAPIClientFromFlagsWithAPIVersionFromEnv(t *testing.T) { @@ -46,20 +46,20 @@ func TestNewAPIClientFromFlagsWithAPIVersionFromEnv(t *testing.T) { opts := &flags.CommonOptions{} configFile := &configfile.ConfigFile{} apiclient, err := NewAPIClientFromFlags(opts, configFile) - require.NoError(t, err) - assert.Equal(t, customVersion, apiclient.ClientVersion()) + assert.NilError(t, err) + assert.Check(t, is.Equal(customVersion, apiclient.ClientVersion())) } // TODO: use gotestyourself/env.Patch func patchEnvVariable(t *testing.T, key, value string) func() { oldValue, ok := os.LookupEnv(key) - require.NoError(t, os.Setenv(key, value)) + assert.NilError(t, os.Setenv(key, value)) return func() { if !ok { - require.NoError(t, os.Unsetenv(key)) + assert.NilError(t, os.Unsetenv(key)) return } - require.NoError(t, os.Setenv(key, oldValue)) + assert.NilError(t, os.Setenv(key, oldValue)) } } @@ -125,8 +125,8 @@ func TestInitializeFromClient(t *testing.T) { cli := &DockerCli{client: apiclient} cli.initializeFromClient() - assert.Equal(t, testcase.expectedServer, cli.serverInfo) - assert.Equal(t, testcase.negotiated, apiclient.negotiated) + assert.Check(t, is.DeepEqual(testcase.expectedServer, cli.serverInfo)) + assert.Check(t, is.Equal(testcase.negotiated, apiclient.negotiated)) }) } } @@ -164,8 +164,8 @@ func TestExperimentalCLI(t *testing.T) { cli := &DockerCli{client: apiclient, err: os.Stderr} cliconfig.SetDir(dir.Path()) err := cli.Initialize(flags.NewClientOptions()) - assert.NoError(t, err) - assert.Equal(t, testcase.expectedExperimentalCLI, cli.ClientInfo().HasExperimental) + assert.Check(t, err) + assert.Check(t, is.Equal(testcase.expectedExperimentalCLI, cli.ClientInfo().HasExperimental)) }) } } @@ -267,9 +267,9 @@ func TestOrchestratorSwitch(t *testing.T) { options.Common.Orchestrator = testcase.flagOrchestrator } err := cli.Initialize(options) - assert.NoError(t, err) - assert.Equal(t, testcase.expectedKubernetes, cli.ClientInfo().HasKubernetes()) - assert.Equal(t, testcase.expectedOrchestrator, string(cli.ClientInfo().Orchestrator)) + assert.Check(t, err) + assert.Check(t, is.Equal(testcase.expectedKubernetes, cli.ClientInfo().HasKubernetes())) + assert.Check(t, is.Equal(testcase.expectedOrchestrator, string(cli.ClientInfo().Orchestrator))) }) } } @@ -335,7 +335,7 @@ func TestGetClientWithPassword(t *testing.T) { return } - assert.NoError(t, err) + assert.Check(t, err) }) } } diff --git a/cli/command/config/create_test.go b/cli/command/config/create_test.go index 5838ae6bb7..faa9ba972a 100644 --- a/cli/command/config/create_test.go +++ b/cli/command/config/create_test.go @@ -11,9 +11,10 @@ import ( "github.com/docker/cli/internal/test/testutil" "github.com/docker/docker/api/types" "github.com/docker/docker/api/types/swarm" + "github.com/gotestyourself/gotestyourself/assert" + is "github.com/gotestyourself/gotestyourself/assert/cmp" "github.com/gotestyourself/gotestyourself/golden" "github.com/pkg/errors" - "github.com/stretchr/testify/assert" ) const configDataFile = "config-create-with-name.golden" @@ -70,9 +71,9 @@ func TestConfigCreateWithName(t *testing.T) { cmd := newConfigCreateCommand(cli) cmd.SetArgs([]string{name, filepath.Join("testdata", configDataFile)}) - assert.NoError(t, cmd.Execute()) + assert.Check(t, cmd.Execute()) golden.Assert(t, string(actual), configDataFile) - assert.Equal(t, "ID-"+name, strings.TrimSpace(cli.OutBuffer().String())) + assert.Check(t, is.Equal("ID-"+name, strings.TrimSpace(cli.OutBuffer().String()))) } func TestConfigCreateWithLabels(t *testing.T) { @@ -83,7 +84,7 @@ func TestConfigCreateWithLabels(t *testing.T) { name := "foo" data, err := ioutil.ReadFile(filepath.Join("testdata", configDataFile)) - assert.NoError(t, err) + assert.Check(t, err) expected := swarm.ConfigSpec{ Annotations: swarm.Annotations{ @@ -109,8 +110,8 @@ func TestConfigCreateWithLabels(t *testing.T) { cmd.SetArgs([]string{name, filepath.Join("testdata", configDataFile)}) cmd.Flags().Set("label", "lbl1=Label-foo") cmd.Flags().Set("label", "lbl2=Label-bar") - assert.NoError(t, cmd.Execute()) - assert.Equal(t, "ID-"+name, strings.TrimSpace(cli.OutBuffer().String())) + assert.Check(t, cmd.Execute()) + assert.Check(t, is.Equal("ID-"+name, strings.TrimSpace(cli.OutBuffer().String()))) } func TestConfigCreateWithTemplatingDriver(t *testing.T) { @@ -138,6 +139,6 @@ func TestConfigCreateWithTemplatingDriver(t *testing.T) { cmd := newConfigCreateCommand(cli) cmd.SetArgs([]string{name, filepath.Join("testdata", configDataFile)}) cmd.Flags().Set("template-driver", expectedDriver.Name) - assert.NoError(t, cmd.Execute()) - assert.Equal(t, "ID-"+name, strings.TrimSpace(cli.OutBuffer().String())) + assert.Check(t, cmd.Execute()) + assert.Check(t, is.Equal("ID-"+name, strings.TrimSpace(cli.OutBuffer().String()))) } diff --git a/cli/command/config/inspect_test.go b/cli/command/config/inspect_test.go index 5ff280fd2a..7c5930d413 100644 --- a/cli/command/config/inspect_test.go +++ b/cli/command/config/inspect_test.go @@ -12,8 +12,8 @@ import ( // Import builders to get the builder function as package function . "github.com/docker/cli/internal/test/builders" "github.com/docker/cli/internal/test/testutil" + "github.com/gotestyourself/gotestyourself/assert" "github.com/gotestyourself/gotestyourself/golden" - "github.com/stretchr/testify/assert" ) func TestConfigInspectErrors(t *testing.T) { @@ -96,7 +96,7 @@ func TestConfigInspectWithoutFormat(t *testing.T) { cli := test.NewFakeCli(&fakeClient{configInspectFunc: tc.configInspectFunc}) cmd := newConfigInspectCommand(cli) cmd.SetArgs(tc.args) - assert.NoError(t, cmd.Execute()) + assert.Check(t, cmd.Execute()) golden.Assert(t, cli.OutBuffer().String(), fmt.Sprintf("config-inspect-without-format.%s.golden", tc.name)) } } @@ -133,7 +133,7 @@ func TestConfigInspectWithFormat(t *testing.T) { cmd := newConfigInspectCommand(cli) cmd.SetArgs(tc.args) cmd.Flags().Set("format", tc.format) - assert.NoError(t, cmd.Execute()) + assert.Check(t, cmd.Execute()) golden.Assert(t, cli.OutBuffer().String(), fmt.Sprintf("config-inspect-with-format.%s.golden", tc.name)) } } @@ -167,7 +167,7 @@ func TestConfigInspectPretty(t *testing.T) { cmd.SetArgs([]string{"configID"}) cmd.Flags().Set("pretty", "true") - assert.NoError(t, cmd.Execute()) + assert.Check(t, cmd.Execute()) golden.Assert(t, cli.OutBuffer().String(), fmt.Sprintf("config-inspect-pretty.%s.golden", tc.name)) } } diff --git a/cli/command/config/ls_test.go b/cli/command/config/ls_test.go index f3946d2e5f..b1ec2d1c93 100644 --- a/cli/command/config/ls_test.go +++ b/cli/command/config/ls_test.go @@ -13,8 +13,9 @@ import ( // Import builders to get the builder function as package function . "github.com/docker/cli/internal/test/builders" "github.com/docker/cli/internal/test/testutil" + "github.com/gotestyourself/gotestyourself/assert" + is "github.com/gotestyourself/gotestyourself/assert/cmp" "github.com/gotestyourself/gotestyourself/golden" - "github.com/stretchr/testify/assert" ) func TestConfigListErrors(t *testing.T) { @@ -72,7 +73,7 @@ func TestConfigList(t *testing.T) { }, }) cmd := newConfigListCommand(cli) - assert.NoError(t, cmd.Execute()) + assert.Check(t, cmd.Execute()) golden.Assert(t, cli.OutBuffer().String(), "config-list-sort.golden") } @@ -89,7 +90,7 @@ func TestConfigListWithQuietOption(t *testing.T) { }) cmd := newConfigListCommand(cli) cmd.Flags().Set("quiet", "true") - assert.NoError(t, cmd.Execute()) + assert.Check(t, cmd.Execute()) golden.Assert(t, cli.OutBuffer().String(), "config-list-with-quiet-option.golden") } @@ -108,7 +109,7 @@ func TestConfigListWithConfigFormat(t *testing.T) { ConfigFormat: "{{ .Name }} {{ .Labels }}", }) cmd := newConfigListCommand(cli) - assert.NoError(t, cmd.Execute()) + assert.Check(t, cmd.Execute()) golden.Assert(t, cli.OutBuffer().String(), "config-list-with-config-format.golden") } @@ -125,15 +126,15 @@ func TestConfigListWithFormat(t *testing.T) { }) cmd := newConfigListCommand(cli) cmd.Flags().Set("format", "{{ .Name }} {{ .Labels }}") - assert.NoError(t, cmd.Execute()) + assert.Check(t, cmd.Execute()) golden.Assert(t, cli.OutBuffer().String(), "config-list-with-format.golden") } func TestConfigListWithFilter(t *testing.T) { cli := test.NewFakeCli(&fakeClient{ configListFunc: func(options types.ConfigListOptions) ([]swarm.Config, error) { - assert.Equal(t, "foo", options.Filters.Get("name")[0]) - assert.Equal(t, "lbl1=Label-bar", options.Filters.Get("label")[0]) + assert.Check(t, is.Equal("foo", options.Filters.Get("name")[0])) + assert.Check(t, is.Equal("lbl1=Label-bar", options.Filters.Get("label")[0])) return []swarm.Config{ *Config(ConfigID("ID-foo"), ConfigName("foo"), @@ -153,6 +154,6 @@ func TestConfigListWithFilter(t *testing.T) { cmd := newConfigListCommand(cli) cmd.Flags().Set("filter", "name=foo") cmd.Flags().Set("filter", "label=lbl1=Label-bar") - assert.NoError(t, cmd.Execute()) + assert.Check(t, cmd.Execute()) golden.Assert(t, cli.OutBuffer().String(), "config-list-with-filter.golden") } diff --git a/cli/command/config/remove_test.go b/cli/command/config/remove_test.go index f7142a2566..e4af842cf0 100644 --- a/cli/command/config/remove_test.go +++ b/cli/command/config/remove_test.go @@ -7,8 +7,9 @@ import ( "github.com/docker/cli/internal/test" "github.com/docker/cli/internal/test/testutil" + "github.com/gotestyourself/gotestyourself/assert" + is "github.com/gotestyourself/gotestyourself/assert/cmp" "github.com/pkg/errors" - "github.com/stretchr/testify/assert" ) func TestConfigRemoveErrors(t *testing.T) { @@ -52,9 +53,9 @@ func TestConfigRemoveWithName(t *testing.T) { }) cmd := newConfigRemoveCommand(cli) cmd.SetArgs(names) - assert.NoError(t, cmd.Execute()) - assert.Equal(t, names, strings.Split(strings.TrimSpace(cli.OutBuffer().String()), "\n")) - assert.Equal(t, names, removedConfigs) + assert.Check(t, cmd.Execute()) + assert.Check(t, is.DeepEqual(names, strings.Split(strings.TrimSpace(cli.OutBuffer().String()), "\n"))) + assert.Check(t, is.DeepEqual(names, removedConfigs)) } func TestConfigRemoveContinueAfterError(t *testing.T) { @@ -74,6 +75,6 @@ func TestConfigRemoveContinueAfterError(t *testing.T) { cmd := newConfigRemoveCommand(cli) cmd.SetArgs(names) cmd.SetOutput(ioutil.Discard) - assert.EqualError(t, cmd.Execute(), "error removing config: foo") - assert.Equal(t, names, removedConfigs) + assert.Check(t, is.Error(cmd.Execute(), "error removing config: foo")) + assert.Check(t, is.DeepEqual(names, removedConfigs)) } diff --git a/cli/command/container/attach_test.go b/cli/command/container/attach_test.go index 1c305aa7a1..0d519de65b 100644 --- a/cli/command/container/attach_test.go +++ b/cli/command/container/attach_test.go @@ -7,11 +7,11 @@ import ( "github.com/docker/cli/cli" "github.com/docker/cli/internal/test" - "github.com/docker/cli/internal/test/testutil" "github.com/docker/docker/api/types" "github.com/docker/docker/api/types/container" + "github.com/gotestyourself/gotestyourself/assert" + is "github.com/gotestyourself/gotestyourself/assert/cmp" "github.com/pkg/errors" - "github.com/stretchr/testify/assert" ) func TestNewAttachCommandErrors(t *testing.T) { @@ -74,7 +74,7 @@ func TestNewAttachCommandErrors(t *testing.T) { cmd := NewAttachCommand(test.NewFakeCli(&fakeClient{inspectFunc: tc.containerInspectFunc})) cmd.SetOutput(ioutil.Discard) cmd.SetArgs(tc.args) - testutil.ErrorContains(t, cmd.Execute(), tc.expectedError) + assert.ErrorContains(t, cmd.Execute(), tc.expectedError) } } @@ -101,9 +101,7 @@ func TestGetExitStatus(t *testing.T) { }, { result: &container.ContainerWaitOKBody{ - Error: &container.ContainerWaitOKBodyError{ - expectedErr.Error(), - }, + Error: &container.ContainerWaitOKBodyError{expectedErr.Error()}, }, expectedError: expectedErr, }, @@ -123,6 +121,10 @@ func TestGetExitStatus(t *testing.T) { resultC <- *testcase.result } err := getExitStatus(errC, resultC) - assert.Equal(t, testcase.expectedError, err) + if testcase.expectedError == nil { + assert.Check(t, err) + } else { + assert.Check(t, is.Error(err, testcase.expectedError.Error())) + } } } diff --git a/cli/command/container/cp_test.go b/cli/command/container/cp_test.go index ce4430746e..11b799b48e 100644 --- a/cli/command/container/cp_test.go +++ b/cli/command/container/cp_test.go @@ -12,10 +12,10 @@ import ( "github.com/docker/cli/internal/test/testutil" "github.com/docker/docker/api/types" "github.com/docker/docker/pkg/archive" + "github.com/gotestyourself/gotestyourself/assert" + is "github.com/gotestyourself/gotestyourself/assert/cmp" "github.com/gotestyourself/gotestyourself/fs" "github.com/gotestyourself/gotestyourself/skip" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" ) func TestRunCopyWithInvalidArguments(t *testing.T) { @@ -44,7 +44,7 @@ func TestRunCopyWithInvalidArguments(t *testing.T) { for _, testcase := range testcases { t.Run(testcase.doc, func(t *testing.T) { err := runCopy(test.NewFakeCli(nil), testcase.options) - assert.EqualError(t, err, testcase.expectedErr) + assert.Check(t, is.Error(err, testcase.expectedErr)) }) } } @@ -54,16 +54,16 @@ func TestRunCopyFromContainerToStdout(t *testing.T) { fakeClient := &fakeClient{ containerCopyFromFunc: func(container, srcPath string) (io.ReadCloser, types.ContainerPathStat, error) { - assert.Equal(t, "container", container) + assert.Check(t, is.Equal("container", container)) return ioutil.NopCloser(strings.NewReader(tarContent)), types.ContainerPathStat{}, nil }, } options := copyOptions{source: "container:/path", destination: "-"} cli := test.NewFakeCli(fakeClient) err := runCopy(cli, options) - require.NoError(t, err) - assert.Equal(t, tarContent, cli.OutBuffer().String()) - assert.Equal(t, "", cli.ErrBuffer().String()) + assert.NilError(t, err) + assert.Check(t, is.Equal(tarContent, cli.OutBuffer().String())) + assert.Check(t, is.Equal("", cli.ErrBuffer().String())) } func TestRunCopyFromContainerToFilesystem(t *testing.T) { @@ -73,7 +73,7 @@ func TestRunCopyFromContainerToFilesystem(t *testing.T) { fakeClient := &fakeClient{ containerCopyFromFunc: func(container, srcPath string) (io.ReadCloser, types.ContainerPathStat, error) { - assert.Equal(t, "container", container) + assert.Check(t, is.Equal("container", container)) readCloser, err := archive.TarWithOptions(destDir.Path(), &archive.TarOptions{}) return readCloser, types.ContainerPathStat{}, err }, @@ -81,13 +81,13 @@ func TestRunCopyFromContainerToFilesystem(t *testing.T) { options := copyOptions{source: "container:/path", destination: destDir.Path()} cli := test.NewFakeCli(fakeClient) err := runCopy(cli, options) - require.NoError(t, err) - assert.Equal(t, "", cli.OutBuffer().String()) - assert.Equal(t, "", cli.ErrBuffer().String()) + assert.NilError(t, err) + assert.Check(t, is.Equal("", cli.OutBuffer().String())) + assert.Check(t, is.Equal("", cli.ErrBuffer().String())) content, err := ioutil.ReadFile(destDir.Join("file1")) - require.NoError(t, err) - assert.Equal(t, "content\n", string(content)) + assert.NilError(t, err) + assert.Check(t, is.Equal("content\n", string(content))) } func TestRunCopyFromContainerToFilesystemMissingDestinationDirectory(t *testing.T) { @@ -97,7 +97,7 @@ func TestRunCopyFromContainerToFilesystemMissingDestinationDirectory(t *testing. fakeClient := &fakeClient{ containerCopyFromFunc: func(container, srcPath string) (io.ReadCloser, types.ContainerPathStat, error) { - assert.Equal(t, "container", container) + assert.Check(t, is.Equal("container", container)) readCloser, err := archive.TarWithOptions(destDir.Path(), &archive.TarOptions{}) return readCloser, types.ContainerPathStat{}, err }, @@ -181,8 +181,8 @@ func TestSplitCpArg(t *testing.T) { skip.IfCondition(t, testcase.os != "" && testcase.os != runtime.GOOS) container, path := splitCpArg(testcase.path) - assert.Equal(t, testcase.expectedContainer, container) - assert.Equal(t, testcase.expectedPath, path) + assert.Check(t, is.Equal(testcase.expectedContainer, container)) + assert.Check(t, is.Equal(testcase.expectedPath, path)) }) } } diff --git a/cli/command/container/create_test.go b/cli/command/container/create_test.go index 6bbdb909c0..32beaa06ab 100644 --- a/cli/command/container/create_test.go +++ b/cli/command/container/create_test.go @@ -10,23 +10,23 @@ import ( "testing" "github.com/docker/cli/internal/test" - "github.com/docker/cli/internal/test/testutil" "github.com/docker/docker/api/types" "github.com/docker/docker/api/types/container" "github.com/docker/docker/api/types/network" + "github.com/google/go-cmp/cmp" + "github.com/gotestyourself/gotestyourself/assert" + is "github.com/gotestyourself/gotestyourself/assert/cmp" "github.com/gotestyourself/gotestyourself/fs" "github.com/pkg/errors" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" ) func TestCIDFileNoOPWithNoFilename(t *testing.T) { file, err := newCIDFile("") - require.NoError(t, err) - assert.Equal(t, &cidFile{}, file) + assert.NilError(t, err) + assert.DeepEqual(t, &cidFile{}, file, cmp.AllowUnexported(cidFile{})) - assert.NoError(t, file.Write("id")) - assert.NoError(t, file.Close()) + assert.Check(t, file.Write("id")) + assert.Check(t, file.Close()) } func TestNewCIDFileWhenFileAlreadyExists(t *testing.T) { @@ -34,7 +34,7 @@ func TestNewCIDFileWhenFileAlreadyExists(t *testing.T) { defer tempfile.Remove() _, err := newCIDFile(tempfile.Path()) - testutil.ErrorContains(t, err, "Container ID file found") + assert.ErrorContains(t, err, "Container ID file found") } func TestCIDFileCloseWithNoWrite(t *testing.T) { @@ -43,12 +43,12 @@ func TestCIDFileCloseWithNoWrite(t *testing.T) { path := tempdir.Join("cidfile") file, err := newCIDFile(path) - require.NoError(t, err) - assert.Equal(t, file.path, path) + assert.NilError(t, err) + assert.Check(t, is.Equal(file.path, path)) - assert.NoError(t, file.Close()) + assert.Check(t, file.Close()) _, err = os.Stat(path) - assert.True(t, os.IsNotExist(err)) + assert.Check(t, os.IsNotExist(err)) } func TestCIDFileCloseWithWrite(t *testing.T) { @@ -57,18 +57,18 @@ func TestCIDFileCloseWithWrite(t *testing.T) { path := tempdir.Join("cidfile") file, err := newCIDFile(path) - require.NoError(t, err) + assert.NilError(t, err) content := "id" - assert.NoError(t, file.Write(content)) + assert.Check(t, file.Write(content)) actual, err := ioutil.ReadFile(path) - require.NoError(t, err) - assert.Equal(t, content, string(actual)) + assert.NilError(t, err) + assert.Check(t, is.Equal(content, string(actual))) - assert.NoError(t, file.Close()) + assert.Check(t, file.Close()) _, err = os.Stat(path) - require.NoError(t, err) + assert.NilError(t, err) } func TestCreateContainerPullsImageIfMissing(t *testing.T) { @@ -108,11 +108,11 @@ func TestCreateContainerPullsImageIfMissing(t *testing.T) { HostConfig: &container.HostConfig{}, } body, err := createContainer(context.Background(), cli, config, "name", runtime.GOOS) - require.NoError(t, err) + assert.NilError(t, err) expected := container.ContainerCreateCreatedBody{ID: containerID} - assert.Equal(t, expected, *body) + assert.Check(t, is.DeepEqual(expected, *body)) stderr := cli.ErrBuffer().String() - assert.Contains(t, stderr, "Unable to find image 'does-not-exist-locally:latest' locally") + assert.Check(t, is.Contains(stderr, "Unable to find image 'does-not-exist-locally:latest' locally")) } type fakeNotFound struct{} diff --git a/cli/command/container/exec_test.go b/cli/command/container/exec_test.go index 492e3a558d..9e61eaa502 100644 --- a/cli/command/container/exec_test.go +++ b/cli/command/container/exec_test.go @@ -10,8 +10,9 @@ import ( "github.com/docker/cli/internal/test/testutil" "github.com/docker/cli/opts" "github.com/docker/docker/api/types" + "github.com/gotestyourself/gotestyourself/assert" + is "github.com/gotestyourself/gotestyourself/assert/cmp" "github.com/pkg/errors" - "github.com/stretchr/testify/assert" "golang.org/x/net/context" ) @@ -106,7 +107,7 @@ func TestParseExec(t *testing.T) { for _, testcase := range testcases { execConfig := parseExec(testcase.options, &testcase.configFile) - assert.Equal(t, testcase.expected, *execConfig) + assert.Check(t, is.DeepEqual(testcase.expected, *execConfig)) } } @@ -152,12 +153,12 @@ func TestRunExec(t *testing.T) { if testcase.expectedError != "" { testutil.ErrorContains(t, err, testcase.expectedError) } else { - if !assert.NoError(t, err) { + if !assert.Check(t, err) { return } } - assert.Equal(t, testcase.expectedOut, cli.OutBuffer().String()) - assert.Equal(t, testcase.expectedErr, cli.ErrBuffer().String()) + assert.Check(t, is.Equal(testcase.expectedOut, cli.OutBuffer().String())) + assert.Check(t, is.Equal(testcase.expectedErr, cli.ErrBuffer().String())) }) } } @@ -192,12 +193,12 @@ func TestGetExecExitStatus(t *testing.T) { for _, testcase := range testcases { client := &fakeClient{ execInspectFunc: func(id string) (types.ContainerExecInspect, error) { - assert.Equal(t, execID, id) + assert.Check(t, is.Equal(execID, id)) return types.ContainerExecInspect{ExitCode: testcase.exitCode}, testcase.inspectError }, } err := getExecExitStatus(context.Background(), client, execID) - assert.Equal(t, testcase.expectedError, err) + assert.Check(t, is.Equal(testcase.expectedError, err)) } } diff --git a/cli/command/container/list_test.go b/cli/command/container/list_test.go index 848d2a60a9..61abd885d3 100644 --- a/cli/command/container/list_test.go +++ b/cli/command/container/list_test.go @@ -9,9 +9,9 @@ import ( "github.com/docker/cli/internal/test" "github.com/docker/cli/internal/test/testutil" "github.com/docker/docker/api/types" - "github.com/stretchr/testify/assert" // Import builders to get the builder function as package function . "github.com/docker/cli/internal/test/builders" + "github.com/gotestyourself/gotestyourself/assert" "github.com/gotestyourself/gotestyourself/golden" ) @@ -69,7 +69,7 @@ func TestContainerListWithoutFormat(t *testing.T) { }, }) cmd := newListCommand(cli) - assert.NoError(t, cmd.Execute()) + assert.Check(t, cmd.Execute()) golden.Assert(t, cli.OutBuffer().String(), "container-list-without-format.golden") } @@ -84,7 +84,7 @@ func TestContainerListNoTrunc(t *testing.T) { }) cmd := newListCommand(cli) cmd.Flags().Set("no-trunc", "true") - assert.NoError(t, cmd.Execute()) + assert.Check(t, cmd.Execute()) golden.Assert(t, cli.OutBuffer().String(), "container-list-without-format-no-trunc.golden") } @@ -100,7 +100,7 @@ func TestContainerListNamesMultipleTime(t *testing.T) { }) cmd := newListCommand(cli) cmd.Flags().Set("format", "{{.Names}} {{.Names}}") - assert.NoError(t, cmd.Execute()) + assert.Check(t, cmd.Execute()) golden.Assert(t, cli.OutBuffer().String(), "container-list-format-name-name.golden") } @@ -116,20 +116,20 @@ func TestContainerListFormatTemplateWithArg(t *testing.T) { }) cmd := newListCommand(cli) cmd.Flags().Set("format", `{{.Names}} {{.Label "some.label"}}`) - assert.NoError(t, cmd.Execute()) + assert.Check(t, cmd.Execute()) golden.Assert(t, cli.OutBuffer().String(), "container-list-format-with-arg.golden") } func TestContainerListFormatSizeSetsOption(t *testing.T) { cli := test.NewFakeCli(&fakeClient{ containerListFunc: func(options types.ContainerListOptions) ([]types.Container, error) { - assert.True(t, options.Size) + assert.Check(t, options.Size) return []types.Container{}, nil }, }) cmd := newListCommand(cli) cmd.Flags().Set("format", `{{.Size}}`) - assert.NoError(t, cmd.Execute()) + assert.Check(t, cmd.Execute()) } func TestContainerListWithConfigFormat(t *testing.T) { @@ -145,7 +145,7 @@ func TestContainerListWithConfigFormat(t *testing.T) { PsFormat: "{{ .Names }} {{ .Image }} {{ .Labels }}", }) cmd := newListCommand(cli) - assert.NoError(t, cmd.Execute()) + assert.Check(t, cmd.Execute()) golden.Assert(t, cli.OutBuffer().String(), "container-list-with-config-format.golden") } @@ -160,6 +160,6 @@ func TestContainerListWithFormat(t *testing.T) { }) cmd := newListCommand(cli) cmd.Flags().Set("format", "{{ .Names }} {{ .Image }} {{ .Labels }}") - assert.NoError(t, cmd.Execute()) + assert.Check(t, cmd.Execute()) golden.Assert(t, cli.OutBuffer().String(), "container-list-with-format.golden") } diff --git a/cli/command/container/logs_test.go b/cli/command/container/logs_test.go index da64802454..91699317fd 100644 --- a/cli/command/container/logs_test.go +++ b/cli/command/container/logs_test.go @@ -10,7 +10,8 @@ import ( "github.com/docker/cli/internal/test/testutil" "github.com/docker/docker/api/types" "github.com/docker/docker/api/types/container" - "github.com/stretchr/testify/assert" + "github.com/gotestyourself/gotestyourself/assert" + is "github.com/gotestyourself/gotestyourself/assert/cmp" ) var logFn = func(expectedOut string) func(string, types.ContainerLogsOptions) (io.ReadCloser, error) { @@ -51,12 +52,12 @@ func TestRunLogs(t *testing.T) { if testcase.expectedError != "" { testutil.ErrorContains(t, err, testcase.expectedError) } else { - if !assert.NoError(t, err) { + if !assert.Check(t, err) { return } } - assert.Equal(t, testcase.expectedOut, cli.OutBuffer().String()) - assert.Equal(t, testcase.expectedErr, cli.ErrBuffer().String()) + assert.Check(t, is.Equal(testcase.expectedOut, cli.OutBuffer().String())) + assert.Check(t, is.Equal(testcase.expectedErr, cli.ErrBuffer().String())) }) } } diff --git a/cli/command/container/opts_test.go b/cli/command/container/opts_test.go index 9403898660..cfb53425e6 100644 --- a/cli/command/container/opts_test.go +++ b/cli/command/container/opts_test.go @@ -13,10 +13,10 @@ import ( "github.com/docker/docker/api/types/container" networktypes "github.com/docker/docker/api/types/network" "github.com/docker/go-connections/nat" + "github.com/gotestyourself/gotestyourself/assert" + is "github.com/gotestyourself/gotestyourself/assert/cmp" "github.com/pkg/errors" "github.com/spf13/pflag" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" ) func TestValidateAttach(t *testing.T) { @@ -67,12 +67,12 @@ func setupRunFlags() (*pflag.FlagSet, *containerOptions) { func parseMustError(t *testing.T, args string) { _, _, _, err := parseRun(strings.Split(args+" ubuntu bash", " ")) - assert.Error(t, err, args) + assert.ErrorContains(t, err, "", args) } func mustParse(t *testing.T, args string) (*container.Config, *container.HostConfig) { config, hostConfig, _, err := parseRun(append(strings.Split(args, " "), "ubuntu", "bash")) - assert.NoError(t, err) + assert.Check(t, err) return config, hostConfig } @@ -239,7 +239,7 @@ func TestRunFlagsParseWithMemory(t *testing.T) { testutil.ErrorContains(t, err, `invalid argument "invalid" for "-m, --memory" flag`) _, hostconfig := mustParse(t, "--memory=1G") - assert.Equal(t, int64(1073741824), hostconfig.Memory) + assert.Check(t, is.Equal(int64(1073741824), hostconfig.Memory)) } func TestParseWithMemorySwap(t *testing.T) { @@ -249,10 +249,10 @@ func TestParseWithMemorySwap(t *testing.T) { testutil.ErrorContains(t, err, `invalid argument "invalid" for "--memory-swap" flag`) _, hostconfig := mustParse(t, "--memory-swap=1G") - assert.Equal(t, int64(1073741824), hostconfig.MemorySwap) + assert.Check(t, is.Equal(int64(1073741824), hostconfig.MemorySwap)) _, hostconfig = mustParse(t, "--memory-swap=-1") - assert.Equal(t, int64(-1), hostconfig.MemorySwap) + assert.Check(t, is.Equal(int64(-1), hostconfig.MemorySwap)) } func TestParseHostname(t *testing.T) { @@ -373,13 +373,13 @@ func TestParseModes(t *testing.T) { // pid ko flags, copts := setupRunFlags() args := []string{"--pid=container:", "img", "cmd"} - require.NoError(t, flags.Parse(args)) + assert.NilError(t, flags.Parse(args)) _, err := parse(flags, copts) testutil.ErrorContains(t, err, "--pid: invalid PID mode") // pid ok _, hostconfig, _, err := parseRun([]string{"--pid=host", "img", "cmd"}) - require.NoError(t, err) + assert.NilError(t, err) if !hostconfig.PidMode.Valid() { t.Fatalf("Expected a valid PidMode, got %v", hostconfig.PidMode) } @@ -390,7 +390,7 @@ func TestParseModes(t *testing.T) { // uts ok _, hostconfig, _, err = parseRun([]string{"--uts=host", "img", "cmd"}) - require.NoError(t, err) + assert.NilError(t, err) if !hostconfig.UTSMode.Valid() { t.Fatalf("Expected a valid UTSMode, got %v", hostconfig.UTSMode) } @@ -406,7 +406,7 @@ func TestRunFlagsParseShmSize(t *testing.T) { // shm-size ok _, hostconfig, _, err := parseRun([]string{"--shm-size=128m", "img", "cmd"}) - require.NoError(t, err) + assert.NilError(t, err) if hostconfig.ShmSize != 134217728 { t.Fatalf("Expected a valid ShmSize, got %d", hostconfig.ShmSize) } diff --git a/cli/command/container/ps_test.go b/cli/command/container/ps_test.go index d5a51d92eb..a781c1f590 100644 --- a/cli/command/container/ps_test.go +++ b/cli/command/container/ps_test.go @@ -4,13 +4,14 @@ import ( "testing" "github.com/docker/cli/opts" - "github.com/stretchr/testify/assert" + "github.com/gotestyourself/gotestyourself/assert" + is "github.com/gotestyourself/gotestyourself/assert/cmp" ) func TestBuildContainerListOptions(t *testing.T) { filters := opts.NewFilterOpt() - assert.NoError(t, filters.Set("foo=bar")) - assert.NoError(t, filters.Set("baz=foo")) + assert.Check(t, filters.Set("foo=bar")) + assert.Check(t, filters.Set("baz=foo")) contexts := []struct { psOpts *psOptions @@ -101,12 +102,12 @@ func TestBuildContainerListOptions(t *testing.T) { for _, c := range contexts { options, err := buildContainerListOptions(c.psOpts) - assert.NoError(t, err) + assert.Check(t, err) - assert.Equal(t, c.expectedAll, options.All) - assert.Equal(t, c.expectedSize, options.Size) - assert.Equal(t, c.expectedLimit, options.Limit) - assert.Equal(t, len(c.expectedFilters), options.Filters.Len()) + assert.Check(t, is.Equal(c.expectedAll, options.All)) + assert.Check(t, is.Equal(c.expectedSize, options.Size)) + assert.Check(t, is.Equal(c.expectedLimit, options.Limit)) + assert.Check(t, is.Equal(len(c.expectedFilters), options.Filters.Len())) for k, v := range c.expectedFilters { f := options.Filters diff --git a/cli/command/container/run_test.go b/cli/command/container/run_test.go index ca08fb3362..71389bd6cf 100644 --- a/cli/command/container/run_test.go +++ b/cli/command/container/run_test.go @@ -6,7 +6,7 @@ import ( "github.com/docker/cli/internal/test" "github.com/docker/docker/api/types/container" "github.com/docker/docker/api/types/network" - "github.com/stretchr/testify/assert" + "github.com/gotestyourself/gotestyourself/assert" ) func TestRunLabel(t *testing.T) { @@ -21,5 +21,5 @@ func TestRunLabel(t *testing.T) { cmd := NewRunCommand(cli) cmd.Flags().Set("detach", "true") cmd.SetArgs([]string{"--label", "foo", "busybox"}) - assert.NoError(t, cmd.Execute()) + assert.Check(t, cmd.Execute()) } diff --git a/cli/command/container/stats_helpers_test.go b/cli/command/container/stats_helpers_test.go index 0425a3ba13..099f425d49 100644 --- a/cli/command/container/stats_helpers_test.go +++ b/cli/command/container/stats_helpers_test.go @@ -1,10 +1,11 @@ package container import ( + "fmt" "testing" "github.com/docker/docker/api/types" - "github.com/stretchr/testify/assert" + "github.com/gotestyourself/gotestyourself/assert" ) func TestCalculateMemUsageUnixNoCache(t *testing.T) { @@ -15,7 +16,7 @@ func TestCalculateMemUsageUnixNoCache(t *testing.T) { result := calculateMemUsageUnixNoCache(stats) // Then - assert.InDelta(t, 100.0, result, 1e-6) + assert.Assert(t, inDelta(100.0, result, 1e-6)) } func TestCalculateMemPercentUnixNoCache(t *testing.T) { @@ -27,10 +28,20 @@ func TestCalculateMemPercentUnixNoCache(t *testing.T) { // When and Then t.Run("Limit is set", func(t *testing.T) { result := calculateMemPercentUnixNoCache(someLimit, used) - assert.InDelta(t, 70.0, result, 1e-6) + assert.Assert(t, inDelta(70.0, result, 1e-6)) }) t.Run("No limit, no cgroup data", func(t *testing.T) { result := calculateMemPercentUnixNoCache(noLimit, used) - assert.InDelta(t, 0.0, result, 1e-6) + assert.Assert(t, inDelta(0.0, result, 1e-6)) }) } + +func inDelta(x, y, delta float64) func() (bool, string) { + return func() (bool, string) { + diff := x - y + if diff < -delta || diff > delta { + return false, fmt.Sprintf("%f != %f within %f", x, y, delta) + } + return true, "" + } +} diff --git a/cli/command/container/utils_test.go b/cli/command/container/utils_test.go index 13c43ff074..c4aa3eddc7 100644 --- a/cli/command/container/utils_test.go +++ b/cli/command/container/utils_test.go @@ -7,8 +7,9 @@ import ( "github.com/docker/cli/internal/test" "github.com/docker/docker/api" "github.com/docker/docker/api/types/container" + "github.com/gotestyourself/gotestyourself/assert" + is "github.com/gotestyourself/gotestyourself/assert/cmp" "github.com/pkg/errors" - "github.com/stretchr/testify/assert" "golang.org/x/net/context" ) @@ -64,6 +65,6 @@ func TestWaitExitOrRemoved(t *testing.T) { for _, testcase := range testcases { statusC := waitExitOrRemoved(context.Background(), client, testcase.cid, true) exitCode := <-statusC - assert.Equal(t, testcase.exitCode, exitCode) + assert.Check(t, is.Equal(testcase.exitCode, exitCode)) } } diff --git a/cli/command/formatter/checkpoint_test.go b/cli/command/formatter/checkpoint_test.go index e88c4d0132..26c517d580 100644 --- a/cli/command/formatter/checkpoint_test.go +++ b/cli/command/formatter/checkpoint_test.go @@ -5,7 +5,7 @@ import ( "testing" "github.com/docker/docker/api/types" - "github.com/stretchr/testify/assert" + "github.com/gotestyourself/gotestyourself/assert" ) func TestCheckpointContextFormatWrite(t *testing.T) { @@ -46,10 +46,7 @@ checkpoint-3: out := bytes.NewBufferString("") testcase.context.Output = out err := CheckpointWrite(testcase.context, checkpoints) - if err != nil { - assert.Error(t, err, testcase.expected) - } else { - assert.Equal(t, out.String(), testcase.expected) - } + assert.NilError(t, err) + assert.Equal(t, out.String(), testcase.expected) } } diff --git a/cli/command/formatter/config_test.go b/cli/command/formatter/config_test.go index 227f454ffa..3a5efb80d2 100644 --- a/cli/command/formatter/config_test.go +++ b/cli/command/formatter/config_test.go @@ -6,7 +6,8 @@ import ( "time" "github.com/docker/docker/api/types/swarm" - "github.com/stretchr/testify/assert" + "github.com/gotestyourself/gotestyourself/assert" + is "github.com/gotestyourself/gotestyourself/assert/cmp" ) func TestConfigContextFormatWrite(t *testing.T) { @@ -55,9 +56,9 @@ id_rsa out := bytes.NewBufferString("") testcase.context.Output = out if err := ConfigWrite(testcase.context, configs); err != nil { - assert.Error(t, err, testcase.expected) + assert.ErrorContains(t, err, testcase.expected) } else { - assert.Equal(t, out.String(), testcase.expected) + assert.Check(t, is.Equal(out.String(), testcase.expected)) } } } diff --git a/cli/command/formatter/container_test.go b/cli/command/formatter/container_test.go index cccd6cb62d..abe29f21f0 100644 --- a/cli/command/formatter/container_test.go +++ b/cli/command/formatter/container_test.go @@ -10,9 +10,9 @@ import ( "github.com/docker/docker/api/types" "github.com/docker/docker/pkg/stringid" + "github.com/gotestyourself/gotestyourself/assert" + is "github.com/gotestyourself/gotestyourself/assert/cmp" "github.com/gotestyourself/gotestyourself/golden" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" ) func TestContainerPsContext(t *testing.T) { @@ -244,9 +244,9 @@ size: 0B testcase.context.Output = out err := ContainerWrite(testcase.context, containers) if err != nil { - assert.EqualError(t, err, testcase.expected) + assert.Check(t, is.Error(err, testcase.expected)) } else { - assert.Equal(t, testcase.expected, out.String()) + assert.Check(t, is.Equal(testcase.expected, out.String())) } } } @@ -305,7 +305,7 @@ func TestContainerContextWriteWithNoContainers(t *testing.T) { for _, context := range contexts { ContainerWrite(context.context, containers) - assert.Equal(t, context.expected, out.String()) + assert.Check(t, is.Equal(context.expected, out.String())) // Clean buffer out.Reset() } @@ -359,8 +359,8 @@ func TestContainerContextWriteJSON(t *testing.T) { msg := fmt.Sprintf("Output: line %d: %s", i, line) var m map[string]interface{} err := json.Unmarshal([]byte(line), &m) - require.NoError(t, err, msg) - assert.Equal(t, expectedJSONs[i], m, msg) + assert.NilError(t, err, msg) + assert.Check(t, is.DeepEqual(expectedJSONs[i], m), msg) } } @@ -378,8 +378,8 @@ func TestContainerContextWriteJSONField(t *testing.T) { msg := fmt.Sprintf("Output: line %d: %s", i, line) var s string err := json.Unmarshal([]byte(line), &s) - require.NoError(t, err, msg) - assert.Equal(t, containers[i].ID, s, msg) + assert.NilError(t, err, msg) + assert.Check(t, is.Equal(containers[i].ID, s), msg) } } @@ -653,6 +653,6 @@ func TestDisplayablePorts(t *testing.T) { for _, port := range cases { actual := DisplayablePorts(port.ports) - assert.Equal(t, port.expected, actual) + assert.Check(t, is.Equal(port.expected, actual)) } } diff --git a/cli/command/formatter/custom_test.go b/cli/command/formatter/custom_test.go index a9f6ccdac9..02df8d9f85 100644 --- a/cli/command/formatter/custom_test.go +++ b/cli/command/formatter/custom_test.go @@ -4,7 +4,8 @@ import ( "strings" "testing" - "github.com/stretchr/testify/assert" + "github.com/gotestyourself/gotestyourself/assert" + is "github.com/gotestyourself/gotestyourself/assert/cmp" ) func compareMultipleValues(t *testing.T, value, expected string) { @@ -23,5 +24,5 @@ func compareMultipleValues(t *testing.T, value, expected string) { keyval := strings.Split(expected, "=") expMap[keyval[0]] = keyval[1] } - assert.Equal(t, expMap, entriesMap) + assert.Check(t, is.DeepEqual(expMap, entriesMap)) } diff --git a/cli/command/formatter/diff_test.go b/cli/command/formatter/diff_test.go index 1aa7b53056..2caf9447a5 100644 --- a/cli/command/formatter/diff_test.go +++ b/cli/command/formatter/diff_test.go @@ -6,7 +6,8 @@ import ( "github.com/docker/docker/api/types/container" "github.com/docker/docker/pkg/archive" - "github.com/stretchr/testify/assert" + "github.com/gotestyourself/gotestyourself/assert" + is "github.com/gotestyourself/gotestyourself/assert/cmp" ) func TestDiffContextFormatWrite(t *testing.T) { @@ -51,9 +52,9 @@ D: /usr/app/old_app.js testcase.context.Output = out err := DiffWrite(testcase.context, diffs) if err != nil { - assert.EqualError(t, err, testcase.expected) + assert.Check(t, is.Error(err, testcase.expected)) } else { - assert.Equal(t, testcase.expected, out.String()) + assert.Check(t, is.Equal(testcase.expected, out.String())) } } } diff --git a/cli/command/formatter/disk_usage_test.go b/cli/command/formatter/disk_usage_test.go index 293fe6d82a..dc206dea4c 100644 --- a/cli/command/formatter/disk_usage_test.go +++ b/cli/command/formatter/disk_usage_test.go @@ -4,8 +4,9 @@ import ( "bytes" "testing" + "github.com/gotestyourself/gotestyourself/assert" + is "github.com/gotestyourself/gotestyourself/assert/cmp" "github.com/gotestyourself/gotestyourself/golden" - "github.com/stretchr/testify/assert" ) func TestDiskUsageContextFormatWrite(t *testing.T) { @@ -101,9 +102,9 @@ Build Cache 0B out := bytes.NewBufferString("") testcase.context.Output = out if err := testcase.context.Write(); err != nil { - assert.Equal(t, testcase.expected, err.Error()) + assert.Check(t, is.Equal(testcase.expected, err.Error())) } else { - assert.Equal(t, testcase.expected, out.String()) + assert.Check(t, is.Equal(testcase.expected, out.String())) } } } diff --git a/cli/command/formatter/displayutils_test.go b/cli/command/formatter/displayutils_test.go index d0bdca9d26..0182d70759 100644 --- a/cli/command/formatter/displayutils_test.go +++ b/cli/command/formatter/displayutils_test.go @@ -3,7 +3,8 @@ package formatter import ( "testing" - "github.com/stretchr/testify/assert" + "github.com/gotestyourself/gotestyourself/assert" + is "github.com/gotestyourself/gotestyourself/assert/cmp" ) func TestEllipsis(t *testing.T) { @@ -25,6 +26,6 @@ func TestEllipsis(t *testing.T) { } for _, testcase := range testcases { - assert.Equal(t, testcase.expected, Ellipsis(testcase.source, testcase.width)) + assert.Check(t, is.Equal(testcase.expected, Ellipsis(testcase.source, testcase.width))) } } diff --git a/cli/command/formatter/history_test.go b/cli/command/formatter/history_test.go index dcbdc027da..d8e5dde1f6 100644 --- a/cli/command/formatter/history_test.go +++ b/cli/command/formatter/history_test.go @@ -10,7 +10,8 @@ import ( "github.com/docker/docker/api/types/image" "github.com/docker/docker/pkg/stringid" - "github.com/stretchr/testify/assert" + "github.com/gotestyourself/gotestyourself/assert" + is "github.com/gotestyourself/gotestyourself/assert/cmp" ) type historyCase struct { @@ -218,7 +219,7 @@ imageID4 24 hours ago /bin/bash grep for _, context := range contexts { HistoryWrite(context.context, true, histories) - assert.Equal(t, context.expected, out.String()) + assert.Check(t, is.Equal(context.expected, out.String())) // Clean buffer out.Reset() } diff --git a/cli/command/formatter/image_test.go b/cli/command/formatter/image_test.go index 20b73a52c1..a514eb7dde 100644 --- a/cli/command/formatter/image_test.go +++ b/cli/command/formatter/image_test.go @@ -9,7 +9,8 @@ import ( "github.com/docker/docker/api/types" "github.com/docker/docker/pkg/stringid" - "github.com/stretchr/testify/assert" + "github.com/gotestyourself/gotestyourself/assert" + is "github.com/gotestyourself/gotestyourself/assert/cmp" ) func TestImageContext(t *testing.T) { @@ -83,7 +84,7 @@ func TestImageContext(t *testing.T) { if strings.Contains(v, ",") { compareMultipleValues(t, v, c.expValue) } else { - assert.Equal(t, c.expValue, v) + assert.Check(t, is.Equal(c.expValue, v)) } } } @@ -293,9 +294,9 @@ image_id: imageID3 testcase.context.Output = out err := ImageWrite(testcase.context, images) if err != nil { - assert.EqualError(t, err, testcase.expected) + assert.Check(t, is.Error(err, testcase.expected)) } else { - assert.Equal(t, testcase.expected, out.String()) + assert.Check(t, is.Equal(testcase.expected, out.String())) } } } @@ -348,7 +349,7 @@ func TestImageContextWriteWithNoImage(t *testing.T) { for _, context := range contexts { ImageWrite(context.context, images) - assert.Equal(t, context.expected, out.String()) + assert.Check(t, is.Equal(context.expected, out.String())) // Clean buffer out.Reset() } diff --git a/cli/command/formatter/network_test.go b/cli/command/formatter/network_test.go index 201838cf74..1cc6284615 100644 --- a/cli/command/formatter/network_test.go +++ b/cli/command/formatter/network_test.go @@ -10,8 +10,8 @@ import ( "github.com/docker/docker/api/types" "github.com/docker/docker/pkg/stringid" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" + "github.com/gotestyourself/gotestyourself/assert" + is "github.com/gotestyourself/gotestyourself/assert/cmp" ) func TestNetworkContext(t *testing.T) { @@ -162,9 +162,9 @@ foobar_bar 2017-01-01 00:00:00 +0000 UTC testcase.context.Output = out err := NetworkWrite(testcase.context, networks) if err != nil { - assert.EqualError(t, err, testcase.expected) + assert.Check(t, is.Error(err, testcase.expected)) } else { - assert.Equal(t, testcase.expected, out.String()) + assert.Check(t, is.Equal(testcase.expected, out.String())) } } } @@ -188,8 +188,8 @@ func TestNetworkContextWriteJSON(t *testing.T) { msg := fmt.Sprintf("Output: line %d: %s", i, line) var m map[string]interface{} err := json.Unmarshal([]byte(line), &m) - require.NoError(t, err, msg) - assert.Equal(t, expectedJSONs[i], m, msg) + assert.NilError(t, err, msg) + assert.Check(t, is.DeepEqual(expectedJSONs[i], m), msg) } } @@ -207,7 +207,7 @@ func TestNetworkContextWriteJSONField(t *testing.T) { msg := fmt.Sprintf("Output: line %d: %s", i, line) var s string err := json.Unmarshal([]byte(line), &s) - require.NoError(t, err, msg) - assert.Equal(t, networks[i].ID, s, msg) + assert.NilError(t, err, msg) + assert.Check(t, is.Equal(networks[i].ID, s), msg) } } diff --git a/cli/command/formatter/node_test.go b/cli/command/formatter/node_test.go index 768f89f65b..c8bb7a34bd 100644 --- a/cli/command/formatter/node_test.go +++ b/cli/command/formatter/node_test.go @@ -10,8 +10,8 @@ import ( "github.com/docker/docker/api/types" "github.com/docker/docker/api/types/swarm" "github.com/docker/docker/pkg/stringid" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" + "github.com/gotestyourself/gotestyourself/assert" + is "github.com/gotestyourself/gotestyourself/assert/cmp" ) func TestNodeContext(t *testing.T) { @@ -203,9 +203,9 @@ foobar_boo Unknown testcase.context.Output = out err := NodeWrite(testcase.context, nodes, types.Info{Swarm: swarm.Info{Cluster: &testcase.clusterInfo}}) if err != nil { - assert.EqualError(t, err, testcase.expected) + assert.Check(t, is.Error(err, testcase.expected)) } else { - assert.Equal(t, testcase.expected, out.String()) + assert.Check(t, is.Equal(testcase.expected, out.String())) } } } @@ -255,8 +255,8 @@ func TestNodeContextWriteJSON(t *testing.T) { msg := fmt.Sprintf("Output: line %d: %s", i, line) var m map[string]interface{} err := json.Unmarshal([]byte(line), &m) - require.NoError(t, err, msg) - assert.Equal(t, testcase.expected[i], m, msg) + assert.NilError(t, err, msg) + assert.Check(t, is.DeepEqual(testcase.expected[i], m), msg) } } } @@ -275,8 +275,8 @@ func TestNodeContextWriteJSONField(t *testing.T) { msg := fmt.Sprintf("Output: line %d: %s", i, line) var s string err := json.Unmarshal([]byte(line), &s) - require.NoError(t, err, msg) - assert.Equal(t, nodes[i].ID, s, msg) + assert.NilError(t, err, msg) + assert.Check(t, is.Equal(nodes[i].ID, s), msg) } } @@ -344,5 +344,5 @@ data Issuer Subject: c3ViamVjdA== Issuer Public Key: cHViS2V5 ` - assert.Equal(t, expected, out.String()) + assert.Check(t, is.Equal(expected, out.String())) } diff --git a/cli/command/formatter/plugin_test.go b/cli/command/formatter/plugin_test.go index 607262dcc9..aa4062bae0 100644 --- a/cli/command/formatter/plugin_test.go +++ b/cli/command/formatter/plugin_test.go @@ -8,7 +8,8 @@ import ( "github.com/docker/docker/api/types" "github.com/docker/docker/pkg/stringid" - "github.com/stretchr/testify/assert" + "github.com/gotestyourself/gotestyourself/assert" + is "github.com/gotestyourself/gotestyourself/assert/cmp" ) func TestPluginContext(t *testing.T) { @@ -131,9 +132,9 @@ foobar_bar testcase.context.Output = out err := PluginWrite(testcase.context, plugins) if err != nil { - assert.EqualError(t, err, testcase.expected) + assert.Check(t, is.Error(err, testcase.expected)) } else { - assert.Equal(t, testcase.expected, out.String()) + assert.Check(t, is.Equal(testcase.expected, out.String())) } } } @@ -158,7 +159,7 @@ func TestPluginContextWriteJSON(t *testing.T) { if err := json.Unmarshal([]byte(line), &m); err != nil { t.Fatal(err) } - assert.Equal(t, expectedJSONs[i], m) + assert.Check(t, is.DeepEqual(expectedJSONs[i], m)) } } @@ -177,6 +178,6 @@ func TestPluginContextWriteJSONField(t *testing.T) { if err := json.Unmarshal([]byte(line), &s); err != nil { t.Fatal(err) } - assert.Equal(t, plugins[i].ID, s) + assert.Check(t, is.Equal(plugins[i].ID, s)) } } diff --git a/cli/command/formatter/search_test.go b/cli/command/formatter/search_test.go index 10e4a82ca0..e5a2d1a91a 100644 --- a/cli/command/formatter/search_test.go +++ b/cli/command/formatter/search_test.go @@ -7,8 +7,9 @@ import ( "testing" registrytypes "github.com/docker/docker/api/types/registry" + "github.com/gotestyourself/gotestyourself/assert" + is "github.com/gotestyourself/gotestyourself/assert/cmp" "github.com/gotestyourself/gotestyourself/golden" - "github.com/stretchr/testify/assert" ) func TestSearchContext(t *testing.T) { @@ -154,9 +155,9 @@ result2 5 testcase.context.Output = out err := SearchWrite(testcase.context, results, false, 0) if err != nil { - assert.Error(t, err, testcase.expected) + assert.Check(t, is.ErrorContains(err, testcase.expected)) } else { - assert.Equal(t, out.String(), testcase.expected) + assert.Check(t, is.Equal(out.String(), testcase.expected)) } } } @@ -191,9 +192,9 @@ result2 testcase.context.Output = out err := SearchWrite(testcase.context, results, true, 0) if err != nil { - assert.Error(t, err, testcase.expected) + assert.Check(t, is.ErrorContains(err, testcase.expected)) } else { - assert.Equal(t, out.String(), testcase.expected) + assert.Check(t, is.Equal(out.String(), testcase.expected)) } } } @@ -226,9 +227,9 @@ result1 testcase.context.Output = out err := SearchWrite(testcase.context, results, false, 6) if err != nil { - assert.Error(t, err, testcase.expected) + assert.Check(t, is.ErrorContains(err, testcase.expected)) } else { - assert.Equal(t, out.String(), testcase.expected) + assert.Check(t, is.Equal(out.String(), testcase.expected)) } } } @@ -254,7 +255,7 @@ func TestSearchContextWriteJSON(t *testing.T) { if err := json.Unmarshal([]byte(line), &m); err != nil { t.Fatal(err) } - assert.Equal(t, m, expectedJSONs[i]) + assert.Check(t, is.DeepEqual(m, expectedJSONs[i])) } } @@ -274,6 +275,6 @@ func TestSearchContextWriteJSONField(t *testing.T) { if err := json.Unmarshal([]byte(line), &s); err != nil { t.Fatal(err) } - assert.Equal(t, s, results[i].Name) + assert.Check(t, is.Equal(s, results[i].Name)) } } diff --git a/cli/command/formatter/secret_test.go b/cli/command/formatter/secret_test.go index 03f6ac1f57..c58a20b0f4 100644 --- a/cli/command/formatter/secret_test.go +++ b/cli/command/formatter/secret_test.go @@ -6,7 +6,8 @@ import ( "time" "github.com/docker/docker/api/types/swarm" - "github.com/stretchr/testify/assert" + "github.com/gotestyourself/gotestyourself/assert" + is "github.com/gotestyourself/gotestyourself/assert/cmp" ) func TestSecretContextFormatWrite(t *testing.T) { @@ -55,9 +56,9 @@ id_rsa out := bytes.NewBufferString("") testcase.context.Output = out if err := SecretWrite(testcase.context, secrets); err != nil { - assert.EqualError(t, err, testcase.expected) + assert.Check(t, is.Error(err, testcase.expected)) } else { - assert.Equal(t, testcase.expected, out.String()) + assert.Check(t, is.Equal(testcase.expected, out.String())) } } } diff --git a/cli/command/formatter/service_test.go b/cli/command/formatter/service_test.go index b05d806dfd..f37459100f 100644 --- a/cli/command/formatter/service_test.go +++ b/cli/command/formatter/service_test.go @@ -8,9 +8,9 @@ import ( "testing" "github.com/docker/docker/api/types/swarm" + "github.com/gotestyourself/gotestyourself/assert" + is "github.com/gotestyourself/gotestyourself/assert/cmp" "github.com/gotestyourself/gotestyourself/golden" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" ) func TestServiceContextWrite(t *testing.T) { @@ -126,9 +126,9 @@ bar testcase.context.Output = out err := ServiceListWrite(testcase.context, services, info) if err != nil { - assert.EqualError(t, err, testcase.expected) + assert.Check(t, is.Error(err, testcase.expected)) } else { - assert.Equal(t, testcase.expected, out.String()) + assert.Check(t, is.Equal(testcase.expected, out.String())) } } } @@ -192,8 +192,8 @@ func TestServiceContextWriteJSON(t *testing.T) { msg := fmt.Sprintf("Output: line %d: %s", i, line) var m map[string]interface{} err := json.Unmarshal([]byte(line), &m) - require.NoError(t, err, msg) - assert.Equal(t, expectedJSONs[i], m, msg) + assert.NilError(t, err, msg) + assert.Check(t, is.DeepEqual(expectedJSONs[i], m), msg) } } func TestServiceContextWriteJSONField(t *testing.T) { @@ -220,8 +220,8 @@ func TestServiceContextWriteJSONField(t *testing.T) { msg := fmt.Sprintf("Output: line %d: %s", i, line) var s string err := json.Unmarshal([]byte(line), &s) - require.NoError(t, err, msg) - assert.Equal(t, services[i].Spec.Name, s, msg) + assert.NilError(t, err, msg) + assert.Check(t, is.Equal(services[i].Spec.Name, s), msg) } } @@ -355,5 +355,5 @@ func TestServiceContext_Ports(t *testing.T) { }, } - assert.Equal(t, "*:97-98->97-98/sctp, *:60-61->60-61/tcp, *:62->61/tcp, *:80-81->80/tcp, *:90-95->90-95/tcp, *:90-96->90-96/udp", c.Ports()) + assert.Check(t, is.Equal("*:97-98->97-98/sctp, *:60-61->60-61/tcp, *:62->61/tcp, *:80-81->80/tcp, *:90-95->90-95/tcp, *:90-96->90-96/udp", c.Ports())) } diff --git a/cli/command/formatter/stack_test.go b/cli/command/formatter/stack_test.go index b18ae7f083..3fa73fefe0 100644 --- a/cli/command/formatter/stack_test.go +++ b/cli/command/formatter/stack_test.go @@ -4,7 +4,8 @@ import ( "bytes" "testing" - "github.com/stretchr/testify/assert" + "github.com/gotestyourself/gotestyourself/assert" + is "github.com/gotestyourself/gotestyourself/assert/cmp" ) func TestStackContextWrite(t *testing.T) { @@ -56,9 +57,9 @@ bar testcase.context.Output = out err := StackWrite(testcase.context, stacks) if err != nil { - assert.Error(t, err, testcase.expected) + assert.Check(t, is.ErrorContains(err, testcase.expected)) } else { - assert.Equal(t, out.String(), testcase.expected) + assert.Check(t, is.Equal(out.String(), testcase.expected)) } } } diff --git a/cli/command/formatter/stats_test.go b/cli/command/formatter/stats_test.go index fe99d33fd4..a2d023a912 100644 --- a/cli/command/formatter/stats_test.go +++ b/cli/command/formatter/stats_test.go @@ -5,7 +5,8 @@ import ( "testing" "github.com/docker/docker/pkg/stringid" - "github.com/stretchr/testify/assert" + "github.com/gotestyourself/gotestyourself/assert" + is "github.com/gotestyourself/gotestyourself/assert/cmp" ) func TestContainerStatsContext(t *testing.T) { @@ -116,9 +117,9 @@ container2 -- te.context.Output = &out err := ContainerStatsWrite(te.context, stats, "linux", false) if err != nil { - assert.EqualError(t, err, te.expected) + assert.Check(t, is.Error(err, te.expected)) } else { - assert.Equal(t, te.expected, out.String()) + assert.Check(t, is.Equal(te.expected, out.String())) } } } @@ -182,9 +183,9 @@ container2 -- -- te.context.Output = &out err := ContainerStatsWrite(te.context, stats, "windows", false) if err != nil { - assert.EqualError(t, err, te.expected) + assert.Check(t, is.Error(err, te.expected)) } else { - assert.Equal(t, te.expected, out.String()) + assert.Check(t, is.Equal(te.expected, out.String())) } } } @@ -221,7 +222,7 @@ func TestContainerStatsContextWriteWithNoStats(t *testing.T) { for _, context := range contexts { ContainerStatsWrite(context.context, []StatsEntry{}, "linux", false) - assert.Equal(t, context.expected, out.String()) + assert.Check(t, is.Equal(context.expected, out.String())) // Clean buffer out.Reset() } @@ -259,7 +260,7 @@ func TestContainerStatsContextWriteWithNoStatsWindows(t *testing.T) { for _, context := range contexts { ContainerStatsWrite(context.context, []StatsEntry{}, "windows", false) - assert.Equal(t, context.expected, out.String()) + assert.Check(t, is.Equal(context.expected, out.String())) // Clean buffer out.Reset() } @@ -293,7 +294,7 @@ func TestContainerStatsContextWriteTrunc(t *testing.T) { for _, context := range contexts { ContainerStatsWrite(context.context, []StatsEntry{{ID: "b95a83497c9161c9b444e3d70e1a9dfba0c1840d41720e146a95a08ebf938afc"}}, "linux", context.trunc) - assert.Equal(t, context.expected, out.String()) + assert.Check(t, is.Equal(context.expected, out.String())) // Clean buffer out.Reset() } diff --git a/cli/command/formatter/task_test.go b/cli/command/formatter/task_test.go index 7e8edd2990..b7d42d2546 100644 --- a/cli/command/formatter/task_test.go +++ b/cli/command/formatter/task_test.go @@ -7,8 +7,9 @@ import ( "testing" "github.com/docker/docker/api/types/swarm" + "github.com/gotestyourself/gotestyourself/assert" + is "github.com/gotestyourself/gotestyourself/assert/cmp" "github.com/gotestyourself/gotestyourself/golden" - "github.com/stretchr/testify/assert" ) func TestTaskContextWrite(t *testing.T) { @@ -74,9 +75,9 @@ foobar_bar foo2 testcase.context.Output = out err := TaskWrite(testcase.context, tasks, names, nodes) if err != nil { - assert.EqualError(t, err, testcase.expected) + assert.Check(t, is.Error(err, testcase.expected)) } else { - assert.Equal(t, testcase.expected, out.String()) + assert.Check(t, is.Equal(testcase.expected, out.String())) } } } @@ -100,6 +101,6 @@ func TestTaskContextWriteJSONField(t *testing.T) { if err := json.Unmarshal([]byte(line), &s); err != nil { t.Fatal(err) } - assert.Equal(t, tasks[i].ID, s) + assert.Check(t, is.Equal(tasks[i].ID, s)) } } diff --git a/cli/command/formatter/trust_test.go b/cli/command/formatter/trust_test.go index dd1a4ff75a..bd18c97b5a 100644 --- a/cli/command/formatter/trust_test.go +++ b/cli/command/formatter/trust_test.go @@ -5,7 +5,8 @@ import ( "testing" "github.com/docker/docker/pkg/stringid" - "github.com/stretchr/testify/assert" + "github.com/gotestyourself/gotestyourself/assert" + is "github.com/gotestyourself/gotestyourself/assert/cmp" ) func TestTrustTag(t *testing.T) { @@ -126,9 +127,9 @@ tag3 bbbbbbbb testcase.context.Output = out err := TrustTagWrite(testcase.context, signedTags) if err != nil { - assert.EqualError(t, err, testcase.expected) + assert.Check(t, is.Error(err, testcase.expected)) } else { - assert.Equal(t, testcase.expected, out.String()) + assert.Check(t, is.Equal(testcase.expected, out.String())) } } } @@ -152,8 +153,8 @@ func TestTrustTagContextEmptyWrite(t *testing.T) { out := bytes.NewBufferString("") emptyCase.context.Output = out err := TrustTagWrite(emptyCase.context, emptySignedTags) - assert.NoError(t, err) - assert.Equal(t, emptyCase.expected, out.String()) + assert.Check(t, err) + assert.Check(t, is.Equal(emptyCase.expected, out.String())) } func TestSignerInfoContextEmptyWrite(t *testing.T) { @@ -171,8 +172,8 @@ func TestSignerInfoContextEmptyWrite(t *testing.T) { out := bytes.NewBufferString("") emptyCase.context.Output = out err := SignerInfoWrite(emptyCase.context, emptySignerInfo) - assert.NoError(t, err) - assert.Equal(t, emptyCase.expected, out.String()) + assert.Check(t, err) + assert.Check(t, is.Equal(emptyCase.expected, out.String())) } func TestSignerInfoContextWrite(t *testing.T) { @@ -230,9 +231,9 @@ eve foobarbazquxquux, key31, key32 testcase.context.Output = out err := SignerInfoWrite(testcase.context, signerInfo) if err != nil { - assert.EqualError(t, err, testcase.expected) + assert.Check(t, is.Error(err, testcase.expected)) } else { - assert.Equal(t, testcase.expected, out.String()) + assert.Check(t, is.Equal(testcase.expected, out.String())) } } } diff --git a/cli/command/formatter/volume_test.go b/cli/command/formatter/volume_test.go index f2c21a83c2..cb876e1d31 100644 --- a/cli/command/formatter/volume_test.go +++ b/cli/command/formatter/volume_test.go @@ -9,8 +9,8 @@ import ( "github.com/docker/docker/api/types" "github.com/docker/docker/pkg/stringid" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" + "github.com/gotestyourself/gotestyourself/assert" + is "github.com/gotestyourself/gotestyourself/assert/cmp" ) func TestVolumeContext(t *testing.T) { @@ -133,9 +133,9 @@ foobar_bar testcase.context.Output = out err := VolumeWrite(testcase.context, volumes) if err != nil { - assert.EqualError(t, err, testcase.expected) + assert.Check(t, is.Error(err, testcase.expected)) } else { - assert.Equal(t, testcase.expected, out.String()) + assert.Check(t, is.Equal(testcase.expected, out.String())) } } } @@ -158,8 +158,8 @@ func TestVolumeContextWriteJSON(t *testing.T) { msg := fmt.Sprintf("Output: line %d: %s", i, line) var m map[string]interface{} err := json.Unmarshal([]byte(line), &m) - require.NoError(t, err, msg) - assert.Equal(t, expectedJSONs[i], m, msg) + assert.NilError(t, err, msg) + assert.Check(t, is.DeepEqual(expectedJSONs[i], m), msg) } } @@ -177,7 +177,7 @@ func TestVolumeContextWriteJSONField(t *testing.T) { msg := fmt.Sprintf("Output: line %d: %s", i, line) var s string err := json.Unmarshal([]byte(line), &s) - require.NoError(t, err, msg) - assert.Equal(t, volumes[i].Name, s, msg) + assert.NilError(t, err, msg) + assert.Check(t, is.Equal(volumes[i].Name, s), msg) } } diff --git a/cli/command/idresolver/idresolver_test.go b/cli/command/idresolver/idresolver_test.go index 98bd306d16..b64fca7c25 100644 --- a/cli/command/idresolver/idresolver_test.go +++ b/cli/command/idresolver/idresolver_test.go @@ -4,10 +4,11 @@ import ( "testing" "github.com/docker/docker/api/types/swarm" + "github.com/gotestyourself/gotestyourself/assert" + is "github.com/gotestyourself/gotestyourself/assert/cmp" // Import builders to get the builder function as package function . "github.com/docker/cli/internal/test/builders" "github.com/pkg/errors" - "github.com/stretchr/testify/assert" "golang.org/x/net/context" ) @@ -21,7 +22,7 @@ func TestResolveError(t *testing.T) { idResolver := New(cli, false) _, err := idResolver.Resolve(context.Background(), struct{}{}, "nodeID") - assert.EqualError(t, err, "unsupported type") + assert.Check(t, is.Error(err, "unsupported type")) } func TestResolveWithNoResolveOption(t *testing.T) { @@ -40,9 +41,9 @@ func TestResolveWithNoResolveOption(t *testing.T) { idResolver := New(cli, true) id, err := idResolver.Resolve(context.Background(), swarm.Node{}, "nodeID") - assert.NoError(t, err) - assert.Equal(t, "nodeID", id) - assert.False(t, resolved) + assert.Check(t, err) + assert.Check(t, is.Equal("nodeID", id)) + assert.Check(t, !resolved) } func TestResolveWithCache(t *testing.T) { @@ -59,11 +60,11 @@ func TestResolveWithCache(t *testing.T) { ctx := context.Background() for i := 0; i < 2; i++ { id, err := idResolver.Resolve(ctx, swarm.Node{}, "nodeID") - assert.NoError(t, err) - assert.Equal(t, "node-foo", id) + assert.Check(t, err) + assert.Check(t, is.Equal("node-foo", id)) } - assert.Equal(t, 1, inspectCounter) + assert.Check(t, is.Equal(1, inspectCounter)) } func TestResolveNode(t *testing.T) { @@ -103,8 +104,8 @@ func TestResolveNode(t *testing.T) { idResolver := New(cli, false) id, err := idResolver.Resolve(ctx, swarm.Node{}, tc.nodeID) - assert.NoError(t, err) - assert.Equal(t, tc.expectedID, id) + assert.Check(t, err) + assert.Check(t, is.Equal(tc.expectedID, id)) } } @@ -138,7 +139,7 @@ func TestResolveService(t *testing.T) { idResolver := New(cli, false) id, err := idResolver.Resolve(ctx, swarm.Service{}, tc.serviceID) - assert.NoError(t, err) - assert.Equal(t, tc.expectedID, id) + assert.Check(t, err) + assert.Check(t, is.Equal(tc.expectedID, id)) } } diff --git a/cli/command/image/build/context_test.go b/cli/command/image/build/context_test.go index a15b535ad7..8b615ba7ed 100644 --- a/cli/command/image/build/context_test.go +++ b/cli/command/image/build/context_test.go @@ -13,8 +13,8 @@ import ( "github.com/docker/cli/internal/test/testutil" "github.com/docker/docker/pkg/archive" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" + "github.com/gotestyourself/gotestyourself/assert" + is "github.com/gotestyourself/gotestyourself/assert/cmp" ) const dockerfileContents = "FROM busybox" @@ -38,7 +38,7 @@ func testValidateContextDirectory(t *testing.T, prepare func(t *testing.T) (stri defer cleanup() err := ValidateContextDirectory(contextDir, excludes) - require.NoError(t, err) + assert.NilError(t, err) } func TestGetContextFromLocalDirNoDockerfile(t *testing.T) { @@ -79,10 +79,10 @@ func TestGetContextFromLocalDirWithNoDirectory(t *testing.T) { defer chdirCleanup() absContextDir, relDockerfile, err := GetContextFromLocalDir(contextDir, "") - require.NoError(t, err) + assert.NilError(t, err) - assert.Equal(t, contextDir, absContextDir) - assert.Equal(t, DefaultDockerfileName, relDockerfile) + assert.Check(t, is.Equal(contextDir, absContextDir)) + assert.Check(t, is.Equal(DefaultDockerfileName, relDockerfile)) } func TestGetContextFromLocalDirWithDockerfile(t *testing.T) { @@ -92,10 +92,10 @@ func TestGetContextFromLocalDirWithDockerfile(t *testing.T) { createTestTempFile(t, contextDir, DefaultDockerfileName, dockerfileContents, 0777) absContextDir, relDockerfile, err := GetContextFromLocalDir(contextDir, "") - require.NoError(t, err) + assert.NilError(t, err) - assert.Equal(t, contextDir, absContextDir) - assert.Equal(t, DefaultDockerfileName, relDockerfile) + assert.Check(t, is.Equal(contextDir, absContextDir)) + assert.Check(t, is.Equal(DefaultDockerfileName, relDockerfile)) } func TestGetContextFromLocalDirLocalFile(t *testing.T) { @@ -130,10 +130,10 @@ func TestGetContextFromLocalDirWithCustomDockerfile(t *testing.T) { createTestTempFile(t, contextDir, DefaultDockerfileName, dockerfileContents, 0777) absContextDir, relDockerfile, err := GetContextFromLocalDir(contextDir, DefaultDockerfileName) - require.NoError(t, err) + assert.NilError(t, err) - assert.Equal(t, contextDir, absContextDir) - assert.Equal(t, DefaultDockerfileName, relDockerfile) + assert.Check(t, is.Equal(contextDir, absContextDir)) + assert.Check(t, is.Equal(DefaultDockerfileName, relDockerfile)) } func TestGetContextFromReaderString(t *testing.T) { @@ -161,7 +161,7 @@ func TestGetContextFromReaderString(t *testing.T) { t.Fatalf("Tar stream too long: %s", err) } - require.NoError(t, tarArchive.Close()) + assert.NilError(t, tarArchive.Close()) if dockerfileContents != contents { t.Fatalf("Uncompressed tar archive does not equal: %s, got: %s", dockerfileContents, contents) @@ -179,15 +179,15 @@ func TestGetContextFromReaderTar(t *testing.T) { createTestTempFile(t, contextDir, DefaultDockerfileName, dockerfileContents, 0777) tarStream, err := archive.Tar(contextDir, archive.Uncompressed) - require.NoError(t, err) + assert.NilError(t, err) tarArchive, relDockerfile, err := GetContextFromReader(tarStream, DefaultDockerfileName) - require.NoError(t, err) + assert.NilError(t, err) tarReader := tar.NewReader(tarArchive) header, err := tarReader.Next() - require.NoError(t, err) + assert.NilError(t, err) if header.Name != DefaultDockerfileName { t.Fatalf("Dockerfile name should be: %s, got: %s", DefaultDockerfileName, header.Name) @@ -203,7 +203,7 @@ func TestGetContextFromReaderTar(t *testing.T) { t.Fatalf("Tar stream too long: %s", err) } - require.NoError(t, tarArchive.Close()) + assert.NilError(t, tarArchive.Close()) if dockerfileContents != contents { t.Fatalf("Uncompressed tar archive does not equal: %s, got: %s", dockerfileContents, contents) @@ -243,8 +243,8 @@ func TestValidateContextDirectoryWithOneFileExcludes(t *testing.T) { // When an error occurs, it terminates the test. func createTestTempDir(t *testing.T, dir, prefix string) (string, func()) { path, err := ioutil.TempDir(dir, prefix) - require.NoError(t, err) - return path, func() { require.NoError(t, os.RemoveAll(path)) } + assert.NilError(t, err) + return path, func() { assert.NilError(t, os.RemoveAll(path)) } } // createTestTempFile creates a temporary file within dir with specific contents and permissions. @@ -252,7 +252,7 @@ func createTestTempDir(t *testing.T, dir, prefix string) (string, func()) { func createTestTempFile(t *testing.T, dir, filename, contents string, perm os.FileMode) string { filePath := filepath.Join(dir, filename) err := ioutil.WriteFile(filePath, []byte(contents), perm) - require.NoError(t, err) + assert.NilError(t, err) return filePath } @@ -262,9 +262,9 @@ func createTestTempFile(t *testing.T, dir, filename, contents string, perm os.Fi // When an error occurs, it terminates the test. func chdir(t *testing.T, dir string) func() { workingDirectory, err := os.Getwd() - require.NoError(t, err) - require.NoError(t, os.Chdir(dir)) - return func() { require.NoError(t, os.Chdir(workingDirectory)) } + assert.NilError(t, err) + assert.NilError(t, os.Chdir(dir)) + return func() { assert.NilError(t, os.Chdir(workingDirectory)) } } func TestIsArchive(t *testing.T) { @@ -295,6 +295,6 @@ func TestIsArchive(t *testing.T) { }, } for _, testcase := range testcases { - assert.Equal(t, testcase.expected, IsArchive(testcase.header), testcase.doc) + assert.Check(t, is.Equal(testcase.expected, IsArchive(testcase.header)), testcase.doc) } } diff --git a/cli/command/image/build_test.go b/cli/command/image/build_test.go index 2b672fdc1d..38451c6ea9 100644 --- a/cli/command/image/build_test.go +++ b/cli/command/image/build_test.go @@ -15,10 +15,10 @@ import ( "github.com/docker/cli/internal/test" "github.com/docker/docker/api/types" "github.com/docker/docker/pkg/archive" + "github.com/gotestyourself/gotestyourself/assert" + is "github.com/gotestyourself/gotestyourself/assert/cmp" "github.com/gotestyourself/gotestyourself/fs" "github.com/gotestyourself/gotestyourself/skip" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" "golang.org/x/net/context" ) @@ -28,7 +28,7 @@ func TestRunBuildResetsUidAndGidInContext(t *testing.T) { defer dest.Remove() fakeImageBuild := func(_ context.Context, context io.Reader, options types.ImageBuildOptions) (types.ImageBuildResponse, error) { - assert.NoError(t, archive.Untar(context, dest.Path(), nil)) + assert.Check(t, archive.Untar(context, dest.Path(), nil)) body := new(bytes.Buffer) return types.ImageBuildResponse{Body: ioutil.NopCloser(body)}, nil @@ -48,18 +48,18 @@ func TestRunBuildResetsUidAndGidInContext(t *testing.T) { options.context = dir.Path() err := runBuild(cli, options) - require.NoError(t, err) + assert.NilError(t, err) files, err := ioutil.ReadDir(dest.Path()) - require.NoError(t, err) + assert.NilError(t, err) for _, fileInfo := range files { - assert.Equal(t, uint32(0), fileInfo.Sys().(*syscall.Stat_t).Uid) - assert.Equal(t, uint32(0), fileInfo.Sys().(*syscall.Stat_t).Gid) + assert.Check(t, is.Equal(uint32(0), fileInfo.Sys().(*syscall.Stat_t).Uid)) + assert.Check(t, is.Equal(uint32(0), fileInfo.Sys().(*syscall.Stat_t).Gid)) } } func TestRunBuildDockerfileFromStdinWithCompress(t *testing.T) { dest, err := ioutil.TempDir("", "test-build-compress-dest") - require.NoError(t, err) + assert.NilError(t, err) defer os.RemoveAll(dest) var dockerfileName string @@ -67,11 +67,11 @@ func TestRunBuildDockerfileFromStdinWithCompress(t *testing.T) { buffer := new(bytes.Buffer) tee := io.TeeReader(context, buffer) - assert.NoError(t, archive.Untar(tee, dest, nil)) + assert.Check(t, archive.Untar(tee, dest, nil)) dockerfileName = options.Dockerfile header := buffer.Bytes()[:10] - assert.Equal(t, archive.Gzip, archive.DetectCompression(header)) + assert.Check(t, is.Equal(archive.Gzip, archive.DetectCompression(header))) body := new(bytes.Buffer) return types.ImageBuildResponse{Body: ioutil.NopCloser(body)}, nil @@ -85,7 +85,7 @@ func TestRunBuildDockerfileFromStdinWithCompress(t *testing.T) { cli.SetIn(command.NewInStream(ioutil.NopCloser(dockerfile))) dir, err := ioutil.TempDir("", "test-build-compress") - require.NoError(t, err) + assert.NilError(t, err) defer os.RemoveAll(dir) ioutil.WriteFile(filepath.Join(dir, "foo"), []byte("some content"), 0644) @@ -96,16 +96,16 @@ func TestRunBuildDockerfileFromStdinWithCompress(t *testing.T) { options.context = dir err = runBuild(cli, options) - require.NoError(t, err) + assert.NilError(t, err) files, err := ioutil.ReadDir(dest) - require.NoError(t, err) + assert.NilError(t, err) actual := []string{} for _, fileInfo := range files { actual = append(actual, fileInfo.Name()) } sort.Strings(actual) - assert.Equal(t, []string{dockerfileName, ".dockerignore", "foo"}, actual) + assert.Check(t, is.DeepEqual([]string{dockerfileName, ".dockerignore", "foo"}, actual)) } func TestRunBuildDockerfileOutsideContext(t *testing.T) { @@ -124,7 +124,7 @@ COPY data /data defer df.Remove() dest, err := ioutil.TempDir("", t.Name()) - require.NoError(t, err) + assert.NilError(t, err) defer os.RemoveAll(dest) var dockerfileName string @@ -132,7 +132,7 @@ COPY data /data buffer := new(bytes.Buffer) tee := io.TeeReader(context, buffer) - assert.NoError(t, archive.Untar(tee, dest, nil)) + assert.Check(t, archive.Untar(tee, dest, nil)) dockerfileName = options.Dockerfile body := new(bytes.Buffer) @@ -146,16 +146,16 @@ COPY data /data options.dockerfileName = df.Path() err = runBuild(cli, options) - require.NoError(t, err) + assert.NilError(t, err) files, err := ioutil.ReadDir(dest) - require.NoError(t, err) + assert.NilError(t, err) var actual []string for _, fileInfo := range files { actual = append(actual, fileInfo.Name()) } sort.Strings(actual) - assert.Equal(t, []string{dockerfileName, ".dockerignore", "data"}, actual) + assert.Check(t, is.DeepEqual([]string{dockerfileName, ".dockerignore", "data"}, actual)) } // TestRunBuildFromLocalGitHubDirNonExistingRepo tests that build contexts @@ -166,8 +166,7 @@ func TestRunBuildFromGitHubSpecialCase(t *testing.T) { cmd.SetArgs([]string{"github.com/docker/no-such-repository"}) cmd.SetOutput(ioutil.Discard) err := cmd.Execute() - assert.Error(t, err) - assert.Contains(t, err.Error(), "unable to prepare context: unable to 'git clone'") + assert.ErrorContains(t, err, "unable to prepare context: unable to 'git clone'") } // TestRunBuildFromLocalGitHubDirNonExistingRepo tests that a local directory @@ -175,19 +174,19 @@ func TestRunBuildFromGitHubSpecialCase(t *testing.T) { // case. func TestRunBuildFromLocalGitHubDir(t *testing.T) { tmpDir, err := ioutil.TempDir("", "docker-build-from-local-dir-") - require.NoError(t, err) + assert.NilError(t, err) defer os.RemoveAll(tmpDir) buildDir := filepath.Join(tmpDir, "github.com", "docker", "no-such-repository") err = os.MkdirAll(buildDir, 0777) - require.NoError(t, err) + assert.NilError(t, err) err = ioutil.WriteFile(filepath.Join(buildDir, "Dockerfile"), []byte("FROM busybox\n"), 0644) - require.NoError(t, err) + assert.NilError(t, err) client := test.NewFakeCli(&fakeClient{}) cmd := NewBuildCommand(client) cmd.SetArgs([]string{buildDir}) cmd.SetOutput(ioutil.Discard) err = cmd.Execute() - require.NoError(t, err) + assert.NilError(t, err) } diff --git a/cli/command/image/history_test.go b/cli/command/image/history_test.go index eb656e5cf4..0fb4e5e8be 100644 --- a/cli/command/image/history_test.go +++ b/cli/command/image/history_test.go @@ -9,9 +9,9 @@ import ( "github.com/docker/cli/internal/test" "github.com/docker/cli/internal/test/testutil" "github.com/docker/docker/api/types/image" + "github.com/gotestyourself/gotestyourself/assert" "github.com/gotestyourself/gotestyourself/golden" "github.com/pkg/errors" - "github.com/stretchr/testify/assert" ) func TestNewHistoryCommandErrors(t *testing.T) { @@ -47,7 +47,6 @@ func TestNewHistoryCommandSuccess(t *testing.T) { testCases := []struct { name string args []string - outputRegex string imageHistoryFunc func(img string) ([]image.HistoryResponseItem, error) }{ { @@ -64,16 +63,17 @@ func TestNewHistoryCommandSuccess(t *testing.T) { name: "quiet", args: []string{"--quiet", "image:tag"}, }, - // TODO: This test is failing since the output does not contain an RFC3339 date - //{ - // name: "non-human", - // args: []string{"--human=false", "image:tag"}, - // outputRegex: "\\d{4}-\\d{2}-\\d{2}T\\d{2}:\\d{2}:\\d{2}", // RFC3339 date format match - //}, { - name: "non-human-header", - args: []string{"--human=false", "image:tag"}, - outputRegex: "CREATED\\sAT", + name: "non-human", + args: []string{"--human=false", "image:tag"}, + imageHistoryFunc: func(img string) ([]image.HistoryResponseItem, error) { + return []image.HistoryResponseItem{{ + ID: "abcdef", + Created: time.Date(2017, 1, 1, 12, 0, 3, 0, time.UTC).Unix(), + CreatedBy: "rose", + Comment: "new history item!", + }}, nil + }, }, { name: "quiet-no-trunc", @@ -92,12 +92,8 @@ func TestNewHistoryCommandSuccess(t *testing.T) { cmd.SetOutput(ioutil.Discard) cmd.SetArgs(tc.args) err := cmd.Execute() - assert.NoError(t, err) + assert.Check(t, err) actual := cli.OutBuffer().String() - if tc.outputRegex == "" { - golden.Assert(t, actual, fmt.Sprintf("history-command-success.%s.golden", tc.name)) - } else { - assert.Regexp(t, tc.outputRegex, actual) - } + golden.Assert(t, actual, fmt.Sprintf("history-command-success.%s.golden", tc.name)) } } diff --git a/cli/command/image/import_test.go b/cli/command/image/import_test.go index 7f9bc2d8dc..0390663c55 100644 --- a/cli/command/image/import_test.go +++ b/cli/command/image/import_test.go @@ -9,8 +9,9 @@ import ( "github.com/docker/cli/internal/test" "github.com/docker/cli/internal/test/testutil" "github.com/docker/docker/api/types" + "github.com/gotestyourself/gotestyourself/assert" + is "github.com/gotestyourself/gotestyourself/assert/cmp" "github.com/pkg/errors" - "github.com/stretchr/testify/assert" ) func TestNewImportCommandErrors(t *testing.T) { @@ -67,7 +68,7 @@ func TestNewImportCommandSuccess(t *testing.T) { name: "double", args: []string{"-", "image:local"}, imageImportFunc: func(source types.ImageImportSource, ref string, options types.ImageImportOptions) (io.ReadCloser, error) { - assert.Equal(t, "image:local", ref) + assert.Check(t, is.Equal("image:local", ref)) return ioutil.NopCloser(strings.NewReader("")), nil }, }, @@ -75,7 +76,7 @@ func TestNewImportCommandSuccess(t *testing.T) { name: "message", args: []string{"--message", "test message", "-"}, imageImportFunc: func(source types.ImageImportSource, ref string, options types.ImageImportOptions) (io.ReadCloser, error) { - assert.Equal(t, "test message", options.Message) + assert.Check(t, is.Equal("test message", options.Message)) return ioutil.NopCloser(strings.NewReader("")), nil }, }, @@ -83,7 +84,7 @@ func TestNewImportCommandSuccess(t *testing.T) { name: "change", args: []string{"--change", "ENV DEBUG true", "-"}, imageImportFunc: func(source types.ImageImportSource, ref string, options types.ImageImportOptions) (io.ReadCloser, error) { - assert.Equal(t, "ENV DEBUG true", options.Changes[0]) + assert.Check(t, is.Equal("ENV DEBUG true", options.Changes[0])) return ioutil.NopCloser(strings.NewReader("")), nil }, }, @@ -92,6 +93,6 @@ func TestNewImportCommandSuccess(t *testing.T) { cmd := NewImportCommand(test.NewFakeCli(&fakeClient{imageImportFunc: tc.imageImportFunc})) cmd.SetOutput(ioutil.Discard) cmd.SetArgs(tc.args) - assert.NoError(t, cmd.Execute()) + assert.Check(t, cmd.Execute()) } } diff --git a/cli/command/image/inspect_test.go b/cli/command/image/inspect_test.go index 4e94d06231..320759ef51 100644 --- a/cli/command/image/inspect_test.go +++ b/cli/command/image/inspect_test.go @@ -8,8 +8,9 @@ import ( "github.com/docker/cli/internal/test" "github.com/docker/cli/internal/test/testutil" "github.com/docker/docker/api/types" + "github.com/gotestyourself/gotestyourself/assert" + is "github.com/gotestyourself/gotestyourself/assert/cmp" "github.com/gotestyourself/gotestyourself/golden" - "github.com/stretchr/testify/assert" ) func TestNewInspectCommandErrors(t *testing.T) { @@ -46,7 +47,7 @@ func TestNewInspectCommandSuccess(t *testing.T) { imageCount: 1, imageInspectFunc: func(image string) (types.ImageInspect, []byte, error) { imageInspectInvocationCount++ - assert.Equal(t, "image", image) + assert.Check(t, is.Equal("image", image)) return types.ImageInspect{}, nil, nil }, }, @@ -66,9 +67,9 @@ func TestNewInspectCommandSuccess(t *testing.T) { imageInspectFunc: func(image string) (types.ImageInspect, []byte, error) { imageInspectInvocationCount++ if imageInspectInvocationCount == 1 { - assert.Equal(t, "image1", image) + assert.Check(t, is.Equal("image1", image)) } else { - assert.Equal(t, "image2", image) + assert.Check(t, is.Equal("image2", image)) } return types.ImageInspect{}, nil, nil }, @@ -81,8 +82,8 @@ func TestNewInspectCommandSuccess(t *testing.T) { cmd.SetOutput(ioutil.Discard) cmd.SetArgs(tc.args) err := cmd.Execute() - assert.NoError(t, err) + assert.Check(t, err) golden.Assert(t, cli.OutBuffer().String(), fmt.Sprintf("inspect-command-success.%s.golden", tc.name)) - assert.Equal(t, imageInspectInvocationCount, tc.imageCount) + assert.Check(t, is.Equal(imageInspectInvocationCount, tc.imageCount)) } } diff --git a/cli/command/image/list_test.go b/cli/command/image/list_test.go index 1755bb3e3d..8fb4510255 100644 --- a/cli/command/image/list_test.go +++ b/cli/command/image/list_test.go @@ -9,9 +9,10 @@ import ( "github.com/docker/cli/internal/test" "github.com/docker/cli/internal/test/testutil" "github.com/docker/docker/api/types" + "github.com/gotestyourself/gotestyourself/assert" + is "github.com/gotestyourself/gotestyourself/assert/cmp" "github.com/gotestyourself/gotestyourself/golden" "github.com/pkg/errors" - "github.com/stretchr/testify/assert" ) func TestNewImagesCommandErrors(t *testing.T) { @@ -65,7 +66,7 @@ func TestNewImagesCommandSuccess(t *testing.T) { name: "match-name", args: []string{"image"}, imageListFunc: func(options types.ImageListOptions) ([]types.ImageSummary, error) { - assert.Equal(t, "image", options.Filters.Get("reference")[0]) + assert.Check(t, is.Equal("image", options.Filters.Get("reference")[0])) return []types.ImageSummary{{}}, nil }, }, @@ -73,7 +74,7 @@ func TestNewImagesCommandSuccess(t *testing.T) { name: "filters", args: []string{"--filter", "name=value"}, imageListFunc: func(options types.ImageListOptions) ([]types.ImageSummary, error) { - assert.Equal(t, "value", options.Filters.Get("name")[0]) + assert.Check(t, is.Equal("value", options.Filters.Get("name")[0])) return []types.ImageSummary{{}}, nil }, }, @@ -85,14 +86,14 @@ func TestNewImagesCommandSuccess(t *testing.T) { cmd.SetOutput(ioutil.Discard) cmd.SetArgs(tc.args) err := cmd.Execute() - assert.NoError(t, err) + assert.Check(t, err) golden.Assert(t, cli.OutBuffer().String(), fmt.Sprintf("list-command-success.%s.golden", tc.name)) } } func TestNewListCommandAlias(t *testing.T) { cmd := newListCommand(test.NewFakeCli(&fakeClient{})) - assert.True(t, cmd.HasAlias("images")) - assert.True(t, cmd.HasAlias("list")) - assert.False(t, cmd.HasAlias("other")) + assert.Check(t, cmd.HasAlias("images")) + assert.Check(t, cmd.HasAlias("list")) + assert.Check(t, !cmd.HasAlias("other")) } diff --git a/cli/command/image/load_test.go b/cli/command/image/load_test.go index 5f05bca47b..af5f669062 100644 --- a/cli/command/image/load_test.go +++ b/cli/command/image/load_test.go @@ -10,9 +10,9 @@ import ( "github.com/docker/cli/internal/test" "github.com/docker/cli/internal/test/testutil" "github.com/docker/docker/api/types" + "github.com/gotestyourself/gotestyourself/assert" "github.com/gotestyourself/gotestyourself/golden" "github.com/pkg/errors" - "github.com/stretchr/testify/assert" ) func TestNewLoadCommandErrors(t *testing.T) { @@ -96,7 +96,7 @@ func TestNewLoadCommandSuccess(t *testing.T) { cmd.SetOutput(ioutil.Discard) cmd.SetArgs(tc.args) err := cmd.Execute() - assert.NoError(t, err) + assert.Check(t, err) golden.Assert(t, cli.OutBuffer().String(), fmt.Sprintf("load-command-success.%s.golden", tc.name)) } } diff --git a/cli/command/image/prune_test.go b/cli/command/image/prune_test.go index 12f51b60fe..00138e1a90 100644 --- a/cli/command/image/prune_test.go +++ b/cli/command/image/prune_test.go @@ -9,9 +9,10 @@ import ( "github.com/docker/cli/internal/test/testutil" "github.com/docker/docker/api/types" "github.com/docker/docker/api/types/filters" + "github.com/gotestyourself/gotestyourself/assert" + is "github.com/gotestyourself/gotestyourself/assert/cmp" "github.com/gotestyourself/gotestyourself/golden" "github.com/pkg/errors" - "github.com/stretchr/testify/assert" ) func TestNewPruneCommandErrors(t *testing.T) { @@ -55,7 +56,7 @@ func TestNewPruneCommandSuccess(t *testing.T) { name: "all", args: []string{"--all"}, imagesPruneFunc: func(pruneFilter filters.Args) (types.ImagesPruneReport, error) { - assert.Equal(t, "false", pruneFilter.Get("dangling")[0]) + assert.Check(t, is.Equal("false", pruneFilter.Get("dangling")[0])) return types.ImagesPruneReport{}, nil }, }, @@ -63,7 +64,7 @@ func TestNewPruneCommandSuccess(t *testing.T) { name: "force-deleted", args: []string{"--force"}, imagesPruneFunc: func(pruneFilter filters.Args) (types.ImagesPruneReport, error) { - assert.Equal(t, "true", pruneFilter.Get("dangling")[0]) + assert.Check(t, is.Equal("true", pruneFilter.Get("dangling")[0])) return types.ImagesPruneReport{ ImagesDeleted: []types.ImageDeleteResponseItem{{Deleted: "image1"}}, SpaceReclaimed: 1, @@ -74,7 +75,7 @@ func TestNewPruneCommandSuccess(t *testing.T) { name: "force-untagged", args: []string{"--force"}, imagesPruneFunc: func(pruneFilter filters.Args) (types.ImagesPruneReport, error) { - assert.Equal(t, "true", pruneFilter.Get("dangling")[0]) + assert.Check(t, is.Equal("true", pruneFilter.Get("dangling")[0])) return types.ImagesPruneReport{ ImagesDeleted: []types.ImageDeleteResponseItem{{Untagged: "image1"}}, SpaceReclaimed: 2, @@ -88,7 +89,7 @@ func TestNewPruneCommandSuccess(t *testing.T) { cmd.SetOutput(ioutil.Discard) cmd.SetArgs(tc.args) err := cmd.Execute() - assert.NoError(t, err) + assert.Check(t, err) golden.Assert(t, cli.OutBuffer().String(), fmt.Sprintf("prune-command-success.%s.golden", tc.name)) } } diff --git a/cli/command/image/pull_test.go b/cli/command/image/pull_test.go index b0e9929abe..9d39e4bada 100644 --- a/cli/command/image/pull_test.go +++ b/cli/command/image/pull_test.go @@ -10,8 +10,9 @@ import ( "github.com/docker/cli/internal/test" "github.com/docker/cli/internal/test/testutil" "github.com/docker/docker/api/types" + "github.com/gotestyourself/gotestyourself/assert" + is "github.com/gotestyourself/gotestyourself/assert/cmp" "github.com/gotestyourself/gotestyourself/golden" - "github.com/stretchr/testify/assert" ) func TestNewPullCommandErrors(t *testing.T) { @@ -65,7 +66,7 @@ func TestNewPullCommandSuccess(t *testing.T) { for _, tc := range testCases { cli := test.NewFakeCli(&fakeClient{ imagePullFunc: func(ref string, options types.ImagePullOptions) (io.ReadCloser, error) { - assert.Equal(t, tc.expectedTag, ref, tc.name) + assert.Check(t, is.Equal(tc.expectedTag, ref), tc.name) return ioutil.NopCloser(strings.NewReader("")), nil }, }) @@ -73,7 +74,7 @@ func TestNewPullCommandSuccess(t *testing.T) { cmd.SetOutput(ioutil.Discard) cmd.SetArgs(tc.args) err := cmd.Execute() - assert.NoError(t, err) + assert.Check(t, err) golden.Assert(t, cli.OutBuffer().String(), fmt.Sprintf("pull-command-success.%s.golden", tc.name)) } } diff --git a/cli/command/image/push_test.go b/cli/command/image/push_test.go index 48d78b7d03..f2ca7e0a0f 100644 --- a/cli/command/image/push_test.go +++ b/cli/command/image/push_test.go @@ -9,8 +9,8 @@ import ( "github.com/docker/cli/internal/test" "github.com/docker/cli/internal/test/testutil" "github.com/docker/docker/api/types" + "github.com/gotestyourself/gotestyourself/assert" "github.com/pkg/errors" - "github.com/stretchr/testify/assert" ) func TestNewPushCommandErrors(t *testing.T) { @@ -72,6 +72,6 @@ func TestNewPushCommandSuccess(t *testing.T) { cmd := NewPushCommand(cli) cmd.SetOutput(ioutil.Discard) cmd.SetArgs(tc.args) - assert.NoError(t, cmd.Execute()) + assert.Check(t, cmd.Execute()) } } diff --git a/cli/command/image/remove_test.go b/cli/command/image/remove_test.go index ec8b34945d..35ad08535a 100644 --- a/cli/command/image/remove_test.go +++ b/cli/command/image/remove_test.go @@ -8,9 +8,10 @@ import ( "github.com/docker/cli/internal/test" "github.com/docker/cli/internal/test/testutil" "github.com/docker/docker/api/types" + "github.com/gotestyourself/gotestyourself/assert" + is "github.com/gotestyourself/gotestyourself/assert/cmp" "github.com/gotestyourself/gotestyourself/golden" "github.com/pkg/errors" - "github.com/stretchr/testify/assert" ) type notFound struct { @@ -27,9 +28,9 @@ func (n notFound) NotFound() bool { func TestNewRemoveCommandAlias(t *testing.T) { cmd := newRemoveCommand(test.NewFakeCli(&fakeClient{})) - assert.True(t, cmd.HasAlias("rmi")) - assert.True(t, cmd.HasAlias("remove")) - assert.False(t, cmd.HasAlias("other")) + assert.Check(t, cmd.HasAlias("rmi")) + assert.Check(t, cmd.HasAlias("remove")) + assert.Check(t, !cmd.HasAlias("other")) } func TestNewRemoveCommandErrors(t *testing.T) { @@ -48,7 +49,7 @@ func TestNewRemoveCommandErrors(t *testing.T) { args: []string{"-f", "image1"}, expectedError: "error removing image", imageRemoveFunc: func(image string, options types.ImageRemoveOptions) ([]types.ImageDeleteResponseItem, error) { - assert.Equal(t, "image1", image) + assert.Check(t, is.Equal("image1", image)) return []types.ImageDeleteResponseItem{}, errors.Errorf("error removing image") }, }, @@ -57,8 +58,8 @@ func TestNewRemoveCommandErrors(t *testing.T) { args: []string{"arg1"}, expectedError: "error removing image", imageRemoveFunc: func(image string, options types.ImageRemoveOptions) ([]types.ImageDeleteResponseItem, error) { - assert.False(t, options.Force) - assert.True(t, options.PruneChildren) + assert.Check(t, !options.Force) + assert.Check(t, options.PruneChildren) return []types.ImageDeleteResponseItem{}, errors.Errorf("error removing image") }, }, @@ -86,7 +87,7 @@ func TestNewRemoveCommandSuccess(t *testing.T) { name: "Image Deleted", args: []string{"image1"}, imageRemoveFunc: func(image string, options types.ImageRemoveOptions) ([]types.ImageDeleteResponseItem, error) { - assert.Equal(t, "image1", image) + assert.Check(t, is.Equal("image1", image)) return []types.ImageDeleteResponseItem{{Deleted: image}}, nil }, }, @@ -94,8 +95,8 @@ func TestNewRemoveCommandSuccess(t *testing.T) { name: "Image not found with force option", args: []string{"-f", "image1"}, imageRemoveFunc: func(image string, options types.ImageRemoveOptions) ([]types.ImageDeleteResponseItem, error) { - assert.Equal(t, "image1", image) - assert.Equal(t, true, options.Force) + assert.Check(t, is.Equal("image1", image)) + assert.Check(t, is.Equal(true, options.Force)) return []types.ImageDeleteResponseItem{}, notFound{"image1"} }, expectedStderr: "Error: No such image: image1\n", @@ -105,7 +106,7 @@ func TestNewRemoveCommandSuccess(t *testing.T) { name: "Image Untagged", args: []string{"image1"}, imageRemoveFunc: func(image string, options types.ImageRemoveOptions) ([]types.ImageDeleteResponseItem, error) { - assert.Equal(t, "image1", image) + assert.Check(t, is.Equal("image1", image)) return []types.ImageDeleteResponseItem{{Untagged: image}}, nil }, }, @@ -126,8 +127,8 @@ func TestNewRemoveCommandSuccess(t *testing.T) { cmd := NewRemoveCommand(cli) cmd.SetOutput(ioutil.Discard) cmd.SetArgs(tc.args) - assert.NoError(t, cmd.Execute()) - assert.Equal(t, tc.expectedStderr, cli.ErrBuffer().String()) + assert.Check(t, cmd.Execute()) + assert.Check(t, is.Equal(tc.expectedStderr, cli.ErrBuffer().String())) golden.Assert(t, cli.OutBuffer().String(), fmt.Sprintf("remove-command-success.%s.golden", tc.name)) }) } diff --git a/cli/command/image/save_test.go b/cli/command/image/save_test.go index f402da7e84..0ad4bdcd03 100644 --- a/cli/command/image/save_test.go +++ b/cli/command/image/save_test.go @@ -9,9 +9,9 @@ import ( "github.com/docker/cli/internal/test" "github.com/docker/cli/internal/test/testutil" + "github.com/gotestyourself/gotestyourself/assert" + is "github.com/gotestyourself/gotestyourself/assert/cmp" "github.com/pkg/errors" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" ) func TestNewSaveCommandErrors(t *testing.T) { @@ -69,8 +69,8 @@ func TestNewSaveCommandSuccess(t *testing.T) { args: []string{"-o", "save_tmp_file", "arg1"}, isTerminal: true, imageSaveFunc: func(images []string) (io.ReadCloser, error) { - require.Len(t, images, 1) - assert.Equal(t, "arg1", images[0]) + assert.Assert(t, is.Len(images, 1)) + assert.Check(t, is.Equal("arg1", images[0])) return ioutil.NopCloser(strings.NewReader("")), nil }, deferredFunc: func() { @@ -81,9 +81,9 @@ func TestNewSaveCommandSuccess(t *testing.T) { args: []string{"arg1", "arg2"}, isTerminal: false, imageSaveFunc: func(images []string) (io.ReadCloser, error) { - require.Len(t, images, 2) - assert.Equal(t, "arg1", images[0]) - assert.Equal(t, "arg2", images[1]) + assert.Assert(t, is.Len(images, 2)) + assert.Check(t, is.Equal("arg1", images[0])) + assert.Check(t, is.Equal("arg2", images[1])) return ioutil.NopCloser(strings.NewReader("")), nil }, }, @@ -96,7 +96,7 @@ func TestNewSaveCommandSuccess(t *testing.T) { })) cmd.SetOutput(ioutil.Discard) cmd.SetArgs(tc.args) - assert.NoError(t, cmd.Execute()) + assert.Check(t, cmd.Execute()) if tc.deferredFunc != nil { tc.deferredFunc() } diff --git a/cli/command/image/tag_test.go b/cli/command/image/tag_test.go index 0698522969..53576f81e7 100644 --- a/cli/command/image/tag_test.go +++ b/cli/command/image/tag_test.go @@ -6,7 +6,8 @@ import ( "github.com/docker/cli/internal/test" "github.com/docker/cli/internal/test/testutil" - "github.com/stretchr/testify/assert" + "github.com/gotestyourself/gotestyourself/assert" + is "github.com/gotestyourself/gotestyourself/assert/cmp" ) func TestCliNewTagCommandErrors(t *testing.T) { @@ -28,14 +29,14 @@ func TestCliNewTagCommand(t *testing.T) { cmd := NewTagCommand( test.NewFakeCli(&fakeClient{ imageTagFunc: func(image string, ref string) error { - assert.Equal(t, "image1", image) - assert.Equal(t, "image2", ref) + assert.Check(t, is.Equal("image1", image)) + assert.Check(t, is.Equal("image2", ref)) return nil }, })) cmd.SetArgs([]string{"image1", "image2"}) cmd.SetOutput(ioutil.Discard) - assert.NoError(t, cmd.Execute()) + assert.Check(t, cmd.Execute()) value, _ := cmd.Flags().GetBool("interspersed") - assert.False(t, value) + assert.Check(t, !value) } diff --git a/cli/command/image/testdata/history-command-success.non-human.golden b/cli/command/image/testdata/history-command-success.non-human.golden new file mode 100644 index 0000000000..4a83a3d837 --- /dev/null +++ b/cli/command/image/testdata/history-command-success.non-human.golden @@ -0,0 +1,2 @@ +IMAGE CREATED AT CREATED BY SIZE COMMENT +abcdef 2017-01-01T12:00:03Z rose 0 new history item! diff --git a/cli/command/image/trust_test.go b/cli/command/image/trust_test.go index 6071ebdea5..92b0c49cb1 100644 --- a/cli/command/image/trust_test.go +++ b/cli/command/image/trust_test.go @@ -8,8 +8,8 @@ import ( "github.com/docker/cli/cli/trust" registrytypes "github.com/docker/docker/api/types/registry" "github.com/docker/docker/registry" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" + "github.com/gotestyourself/gotestyourself/assert" + is "github.com/gotestyourself/gotestyourself/assert/cmp" "github.com/theupdateframework/notary/client" "github.com/theupdateframework/notary/passphrase" "github.com/theupdateframework/notary/trustpinning" @@ -64,12 +64,12 @@ func TestNonOfficialTrustServer(t *testing.T) { func TestAddTargetToAllSignableRolesError(t *testing.T) { tmpDir, err := ioutil.TempDir("", "notary-test-") - assert.NoError(t, err) + assert.Check(t, err) defer os.RemoveAll(tmpDir) notaryRepo, err := client.NewFileCachedRepository(tmpDir, "gun", "https://localhost", nil, passphrase.ConstantRetriever("password"), trustpinning.TrustPinConfig{}) - require.NoError(t, err) + assert.NilError(t, err) target := client.Target{} err = AddTargetToAllSignableRoles(notaryRepo, &target) - assert.EqualError(t, err, "client is offline") + assert.Check(t, is.Error(err, "client is offline")) } diff --git a/cli/command/inspect/inspector_test.go b/cli/command/inspect/inspector_test.go index 7d19fceda2..8eb818ee7d 100644 --- a/cli/command/inspect/inspector_test.go +++ b/cli/command/inspect/inspector_test.go @@ -6,8 +6,8 @@ import ( "testing" "github.com/docker/cli/templates" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" + "github.com/gotestyourself/gotestyourself/assert" + is "github.com/gotestyourself/gotestyourself/assert/cmp" ) type testElement struct { @@ -243,17 +243,17 @@ func TestTemplateInspectorRawFallbackNumber(t *testing.T) { } b := new(bytes.Buffer) tmpl, err := templates.Parse("{{.Size}} {{.Id}}") - require.NoError(t, err) + assert.NilError(t, err) i := NewTemplateInspector(b, tmpl) for _, tc := range testcases { err = i.Inspect(typedElem, tc.raw) - require.NoError(t, err) + assert.NilError(t, err) err = i.Flush() - require.NoError(t, err) + assert.NilError(t, err) - assert.Equal(t, tc.exp, b.String()) + assert.Check(t, is.Equal(tc.exp, b.String())) b.Reset() } } diff --git a/cli/command/manifest/annotate_test.go b/cli/command/manifest/annotate_test.go index ad80bf6e0a..dd05dd8977 100644 --- a/cli/command/manifest/annotate_test.go +++ b/cli/command/manifest/annotate_test.go @@ -6,9 +6,9 @@ import ( "github.com/docker/cli/internal/test" "github.com/docker/cli/internal/test/testutil" + "github.com/gotestyourself/gotestyourself/assert" + is "github.com/gotestyourself/gotestyourself/assert/cmp" "github.com/gotestyourself/gotestyourself/golden" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" ) func TestManifestAnnotateError(t *testing.T) { @@ -48,7 +48,7 @@ func TestManifestAnnotate(t *testing.T) { namedRef := ref(t, "alpine:3.0") imageManifest := fullImageManifest(t, namedRef) err := store.Save(ref(t, "list:v1"), namedRef, imageManifest) - require.NoError(t, err) + assert.NilError(t, err) cmd := newAnnotateCommand(cli) cmd.SetArgs([]string{"example.com/list:v1", "example.com/fake:0.0"}) @@ -65,14 +65,14 @@ func TestManifestAnnotate(t *testing.T) { testutil.ErrorContains(t, cmd.Execute(), expectedError) cmd.Flags().Set("arch", "arm") - require.NoError(t, cmd.Execute()) + assert.NilError(t, cmd.Execute()) cmd = newInspectCommand(cli) err = cmd.Flags().Set("verbose", "true") - require.NoError(t, err) + assert.NilError(t, err) cmd.SetArgs([]string{"example.com/list:v1", "example.com/alpine:3.0"}) - require.NoError(t, cmd.Execute()) + assert.NilError(t, cmd.Execute()) actual := cli.OutBuffer() expected := golden.Get(t, "inspect-annotate.golden") - assert.Equal(t, string(expected), actual.String()) + assert.Check(t, is.Equal(string(expected), actual.String())) } diff --git a/cli/command/manifest/create_test.go b/cli/command/manifest/create_test.go index a16ab5a073..058990b44b 100644 --- a/cli/command/manifest/create_test.go +++ b/cli/command/manifest/create_test.go @@ -8,10 +8,10 @@ import ( "github.com/docker/cli/internal/test" "github.com/docker/cli/internal/test/testutil" "github.com/docker/distribution/reference" + "github.com/gotestyourself/gotestyourself/assert" + is "github.com/gotestyourself/gotestyourself/assert/cmp" "github.com/gotestyourself/gotestyourself/golden" "github.com/pkg/errors" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" "golang.org/x/net/context" ) @@ -50,28 +50,28 @@ func TestManifestCreateAmend(t *testing.T) { namedRef := ref(t, "alpine:3.0") imageManifest := fullImageManifest(t, namedRef) err := store.Save(ref(t, "list:v1"), namedRef, imageManifest) - require.NoError(t, err) + assert.NilError(t, err) namedRef = ref(t, "alpine:3.1") imageManifest = fullImageManifest(t, namedRef) err = store.Save(ref(t, "list:v1"), namedRef, imageManifest) - require.NoError(t, err) + assert.NilError(t, err) cmd := newCreateListCommand(cli) cmd.SetArgs([]string{"example.com/list:v1", "example.com/alpine:3.1"}) cmd.Flags().Set("amend", "true") cmd.SetOutput(ioutil.Discard) err = cmd.Execute() - require.NoError(t, err) + assert.NilError(t, err) // make a new cli to clear the buffers cli = test.NewFakeCli(nil) cli.SetManifestStore(store) inspectCmd := newInspectCommand(cli) inspectCmd.SetArgs([]string{"example.com/list:v1"}) - require.NoError(t, inspectCmd.Execute()) + assert.NilError(t, inspectCmd.Execute()) actual := cli.OutBuffer() expected := golden.Get(t, "inspect-manifest-list.golden") - assert.Equal(t, string(expected), actual.String()) + assert.Check(t, is.Equal(string(expected), actual.String())) } // attempt to overwrite a saved manifest and get refused @@ -84,13 +84,13 @@ func TestManifestCreateRefuseAmend(t *testing.T) { namedRef := ref(t, "alpine:3.0") imageManifest := fullImageManifest(t, namedRef) err := store.Save(ref(t, "list:v1"), namedRef, imageManifest) - require.NoError(t, err) + assert.NilError(t, err) cmd := newCreateListCommand(cli) cmd.SetArgs([]string{"example.com/list:v1", "example.com/alpine:3.0"}) cmd.SetOutput(ioutil.Discard) err = cmd.Execute() - assert.EqualError(t, err, "refusing to amend an existing manifest list with no --amend flag") + assert.Check(t, is.Error(err, "refusing to amend an existing manifest list with no --amend flag")) } // attempt to make a manifest list without valid images @@ -113,5 +113,5 @@ func TestManifestCreateNoManifest(t *testing.T) { cmd.SetArgs([]string{"example.com/list:v1", "example.com/alpine:3.0"}) cmd.SetOutput(ioutil.Discard) err := cmd.Execute() - assert.EqualError(t, err, "No such image: example.com/alpine:3.0") + assert.Check(t, is.Error(err, "No such image: example.com/alpine:3.0")) } diff --git a/cli/command/manifest/inspect_test.go b/cli/command/manifest/inspect_test.go index 6dcf6deadd..0f879f3c9b 100644 --- a/cli/command/manifest/inspect_test.go +++ b/cli/command/manifest/inspect_test.go @@ -12,24 +12,24 @@ import ( "github.com/docker/distribution" "github.com/docker/distribution/manifest/schema2" "github.com/docker/distribution/reference" + "github.com/gotestyourself/gotestyourself/assert" + is "github.com/gotestyourself/gotestyourself/assert/cmp" "github.com/gotestyourself/gotestyourself/golden" "github.com/opencontainers/go-digest" "github.com/pkg/errors" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" "golang.org/x/net/context" ) func newTempManifestStore(t *testing.T) (store.Store, func()) { tmpdir, err := ioutil.TempDir("", "test-manifest-storage") - require.NoError(t, err) + assert.NilError(t, err) return store.NewStore(tmpdir), func() { os.RemoveAll(tmpdir) } } func ref(t *testing.T, name string) reference.Named { named, err := reference.ParseNamed("example.com/" + name) - require.NoError(t, err) + assert.NilError(t, err) return named } @@ -49,7 +49,7 @@ func fullImageManifest(t *testing.T, ref reference.Named) types.ImageManifest { }, }, }) - require.NoError(t, err) + assert.NilError(t, err) // TODO: include image data for verbose inspect return types.NewImageManifest(ref, digest.Digest("sha256:7328f6f8b41890597575cbaadc884e7386ae0acc53b747401ebce5cf0d62abcd"), types.Image{OS: "linux", Architecture: "amd64"}, man) } @@ -65,7 +65,7 @@ func TestInspectCommandLocalManifestNotFound(t *testing.T) { cmd.SetOutput(ioutil.Discard) cmd.SetArgs([]string{"example.com/list:v1", "example.com/alpine:3.0"}) err := cmd.Execute() - assert.EqualError(t, err, "No such manifest: example.com/alpine:3.0") + assert.Check(t, is.Error(err, "No such manifest: example.com/alpine:3.0")) } func TestInspectCommandNotFound(t *testing.T) { @@ -87,7 +87,7 @@ func TestInspectCommandNotFound(t *testing.T) { cmd.SetOutput(ioutil.Discard) cmd.SetArgs([]string{"example.com/alpine:3.0"}) err := cmd.Execute() - assert.EqualError(t, err, "No such manifest: example.com/alpine:3.0") + assert.Check(t, is.Error(err, "No such manifest: example.com/alpine:3.0")) } func TestInspectCommandLocalManifest(t *testing.T) { @@ -99,14 +99,14 @@ func TestInspectCommandLocalManifest(t *testing.T) { namedRef := ref(t, "alpine:3.0") imageManifest := fullImageManifest(t, namedRef) err := store.Save(ref(t, "list:v1"), namedRef, imageManifest) - require.NoError(t, err) + assert.NilError(t, err) cmd := newInspectCommand(cli) cmd.SetArgs([]string{"example.com/list:v1", "example.com/alpine:3.0"}) - require.NoError(t, cmd.Execute()) + assert.NilError(t, cmd.Execute()) actual := cli.OutBuffer() expected := golden.Get(t, "inspect-manifest.golden") - assert.Equal(t, string(expected), actual.String()) + assert.Check(t, is.Equal(string(expected), actual.String())) } func TestInspectcommandRemoteManifest(t *testing.T) { @@ -124,8 +124,8 @@ func TestInspectcommandRemoteManifest(t *testing.T) { cmd := newInspectCommand(cli) cmd.SetOutput(ioutil.Discard) cmd.SetArgs([]string{"example.com/alpine:3.0"}) - require.NoError(t, cmd.Execute()) + assert.NilError(t, cmd.Execute()) actual := cli.OutBuffer() expected := golden.Get(t, "inspect-manifest.golden") - assert.Equal(t, string(expected), actual.String()) + assert.Check(t, is.Equal(string(expected), actual.String())) } diff --git a/cli/command/manifest/push_test.go b/cli/command/manifest/push_test.go index 608dd2c23b..aa5581168f 100644 --- a/cli/command/manifest/push_test.go +++ b/cli/command/manifest/push_test.go @@ -8,13 +8,13 @@ import ( "github.com/docker/cli/internal/test" "github.com/docker/cli/internal/test/testutil" "github.com/docker/distribution/reference" + "github.com/gotestyourself/gotestyourself/assert" "github.com/pkg/errors" - "github.com/stretchr/testify/require" "golang.org/x/net/context" ) func newFakeRegistryClient(t *testing.T) *fakeRegistryClient { - require.NoError(t, nil) + assert.NilError(t, nil) return &fakeRegistryClient{ getManifestFunc: func(_ context.Context, _ reference.Named) (manifesttypes.ImageManifest, error) { @@ -64,10 +64,10 @@ func TestManifestPush(t *testing.T) { namedRef := ref(t, "alpine:3.0") imageManifest := fullImageManifest(t, namedRef) err := store.Save(ref(t, "list:v1"), namedRef, imageManifest) - require.NoError(t, err) + assert.NilError(t, err) cmd := newPushListCommand(cli) cmd.SetArgs([]string{"example.com/list:v1"}) err = cmd.Execute() - require.NoError(t, err) + assert.NilError(t, err) } diff --git a/cli/command/network/connect_test.go b/cli/command/network/connect_test.go index 064aa041c8..bdd382450a 100644 --- a/cli/command/network/connect_test.go +++ b/cli/command/network/connect_test.go @@ -7,8 +7,9 @@ import ( "github.com/docker/cli/internal/test" "github.com/docker/cli/internal/test/testutil" "github.com/docker/docker/api/types/network" + "github.com/gotestyourself/gotestyourself/assert" + is "github.com/gotestyourself/gotestyourself/assert/cmp" "github.com/pkg/errors" - "github.com/stretchr/testify/assert" "golang.org/x/net/context" ) @@ -54,7 +55,7 @@ func TestNetworkConnectWithFlags(t *testing.T) { } cli := test.NewFakeCli(&fakeClient{ networkConnectFunc: func(ctx context.Context, networkID, container string, config *network.EndpointSettings) error { - assert.Equal(t, expectedOpts, config.IPAMConfig, "not expected driver error") + assert.Check(t, is.DeepEqual(expectedOpts, config.IPAMConfig), "not expected driver error") return nil }, }) @@ -66,5 +67,5 @@ func TestNetworkConnectWithFlags(t *testing.T) { cmd.Flags().Set("ip-range", "192.168.4.0/24") cmd.Flags().Set("gateway", "192.168.4.1/24") cmd.Flags().Set("subnet", "192.168.4.0/24") - assert.NoError(t, cmd.Execute()) + assert.Check(t, cmd.Execute()) } diff --git a/cli/command/network/create_test.go b/cli/command/network/create_test.go index dda68046db..7ab03cc074 100644 --- a/cli/command/network/create_test.go +++ b/cli/command/network/create_test.go @@ -9,9 +9,9 @@ import ( "github.com/docker/cli/internal/test/testutil" "github.com/docker/docker/api/types" "github.com/docker/docker/api/types/network" + "github.com/gotestyourself/gotestyourself/assert" + is "github.com/gotestyourself/gotestyourself/assert/cmp" "github.com/pkg/errors" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" "golang.org/x/net/context" ) @@ -136,7 +136,7 @@ func TestNetworkCreateErrors(t *testing.T) { ) cmd.SetArgs(tc.args) for key, value := range tc.flags { - require.NoError(t, cmd.Flags().Set(key, value)) + assert.NilError(t, cmd.Flags().Set(key, value)) } cmd.SetOutput(ioutil.Discard) testutil.ErrorContains(t, cmd.Execute(), tc.expectedError) @@ -155,8 +155,8 @@ func TestNetworkCreateWithFlags(t *testing.T) { } cli := test.NewFakeCli(&fakeClient{ networkCreateFunc: func(ctx context.Context, name string, createBody types.NetworkCreate) (types.NetworkCreateResponse, error) { - assert.Equal(t, expectedDriver, createBody.Driver, "not expected driver error") - assert.Equal(t, expectedOpts, createBody.IPAM.Config, "not expected driver error") + assert.Check(t, is.Equal(expectedDriver, createBody.Driver), "not expected driver error") + assert.Check(t, is.DeepEqual(expectedOpts, createBody.IPAM.Config), "not expected driver error") return types.NetworkCreateResponse{ ID: name, }, nil @@ -170,6 +170,6 @@ func TestNetworkCreateWithFlags(t *testing.T) { cmd.Flags().Set("ip-range", "192.168.4.0/24") cmd.Flags().Set("gateway", "192.168.4.1/24") cmd.Flags().Set("subnet", "192.168.4.0/24") - assert.NoError(t, cmd.Execute()) - assert.Equal(t, "banana", strings.TrimSpace(cli.OutBuffer().String())) + assert.Check(t, cmd.Execute()) + assert.Check(t, is.Equal("banana", strings.TrimSpace(cli.OutBuffer().String()))) } diff --git a/cli/command/network/list_test.go b/cli/command/network/list_test.go index 63fc0a13cb..4c1a437c03 100644 --- a/cli/command/network/list_test.go +++ b/cli/command/network/list_test.go @@ -1,20 +1,19 @@ package network import ( - "testing" - "io/ioutil" - "strings" + "testing" "github.com/docker/cli/internal/test" . "github.com/docker/cli/internal/test/builders" - "github.com/docker/cli/internal/test/testutil" "github.com/docker/docker/api/types" "github.com/docker/docker/api/types/filters" + "github.com/google/go-cmp/cmp" + "github.com/gotestyourself/gotestyourself/assert" + is "github.com/gotestyourself/gotestyourself/assert/cmp" "github.com/gotestyourself/gotestyourself/golden" "github.com/pkg/errors" - "github.com/stretchr/testify/assert" "golang.org/x/net/context" ) @@ -38,23 +37,18 @@ func TestNetworkListErrors(t *testing.T) { }), ) cmd.SetOutput(ioutil.Discard) - testutil.ErrorContains(t, cmd.Execute(), tc.expectedError) - + assert.ErrorContains(t, cmd.Execute(), tc.expectedError) } } func TestNetworkListWithFlags(t *testing.T) { - - filterArgs := filters.NewArgs() - filterArgs.Add("image.name", "ubuntu") - expectedOpts := types.NetworkListOptions{ - Filters: filterArgs, + Filters: filters.NewArgs(filters.Arg("image.name", "ubuntu")), } cli := test.NewFakeCli(&fakeClient{ networkListFunc: func(ctx context.Context, options types.NetworkListOptions) ([]types.NetworkResource, error) { - assert.Equal(t, expectedOpts, options, "not expected options error") + assert.Check(t, is.DeepEqual(expectedOpts, options, cmp.AllowUnexported(filters.Args{}))) return []types.NetworkResource{*NetworkResource(NetworkResourceID("123454321"), NetworkResourceName("network_1"), NetworkResourceDriver("09.7.01"), @@ -64,6 +58,6 @@ func TestNetworkListWithFlags(t *testing.T) { cmd := newListCommand(cli) cmd.Flags().Set("filter", "image.name=ubuntu") - assert.NoError(t, cmd.Execute()) + assert.Check(t, cmd.Execute()) golden.Assert(t, strings.TrimSpace(cli.OutBuffer().String()), "network-list.golden") } diff --git a/cli/command/node/demote_test.go b/cli/command/node/demote_test.go index bf86e5227e..f96dedd18e 100644 --- a/cli/command/node/demote_test.go +++ b/cli/command/node/demote_test.go @@ -6,11 +6,11 @@ import ( "github.com/docker/cli/internal/test" "github.com/docker/docker/api/types/swarm" + "github.com/gotestyourself/gotestyourself/assert" "github.com/pkg/errors" // Import builders to get the builder function as package function . "github.com/docker/cli/internal/test/builders" "github.com/docker/cli/internal/test/testutil" - "github.com/stretchr/testify/assert" ) func TestNodeDemoteErrors(t *testing.T) { @@ -64,7 +64,7 @@ func TestNodeDemoteNoChange(t *testing.T) { }, })) cmd.SetArgs([]string{"nodeID"}) - assert.NoError(t, cmd.Execute()) + assert.Check(t, cmd.Execute()) } func TestNodeDemoteMultipleNode(t *testing.T) { @@ -81,5 +81,5 @@ func TestNodeDemoteMultipleNode(t *testing.T) { }, })) cmd.SetArgs([]string{"nodeID1", "nodeID2"}) - assert.NoError(t, cmd.Execute()) + assert.Check(t, cmd.Execute()) } diff --git a/cli/command/node/inspect_test.go b/cli/command/node/inspect_test.go index 739a4783be..fed37b9b79 100644 --- a/cli/command/node/inspect_test.go +++ b/cli/command/node/inspect_test.go @@ -12,8 +12,8 @@ import ( // Import builders to get the builder function as package function . "github.com/docker/cli/internal/test/builders" "github.com/docker/cli/internal/test/testutil" + "github.com/gotestyourself/gotestyourself/assert" "github.com/gotestyourself/gotestyourself/golden" - "github.com/stretchr/testify/assert" ) func TestNodeInspectErrors(t *testing.T) { @@ -113,7 +113,7 @@ func TestNodeInspectPretty(t *testing.T) { cmd := newInspectCommand(cli) cmd.SetArgs([]string{"nodeID"}) cmd.Flags().Set("pretty", "true") - assert.NoError(t, cmd.Execute()) + assert.Check(t, cmd.Execute()) golden.Assert(t, cli.OutBuffer().String(), fmt.Sprintf("node-inspect-pretty.%s.golden", tc.name)) } } diff --git a/cli/command/node/list_test.go b/cli/command/node/list_test.go index 2cbe96e766..3d57149a08 100644 --- a/cli/command/node/list_test.go +++ b/cli/command/node/list_test.go @@ -8,11 +8,12 @@ import ( "github.com/docker/cli/internal/test" "github.com/docker/docker/api/types" "github.com/docker/docker/api/types/swarm" + "github.com/gotestyourself/gotestyourself/assert" + is "github.com/gotestyourself/gotestyourself/assert/cmp" "github.com/gotestyourself/gotestyourself/golden" "github.com/pkg/errors" // Import builders to get the builder function as package function . "github.com/docker/cli/internal/test/builders" - "github.com/stretchr/testify/assert" ) func TestNodeListErrorOnAPIFailure(t *testing.T) { @@ -48,7 +49,7 @@ func TestNodeListErrorOnAPIFailure(t *testing.T) { }) cmd := newListCommand(cli) cmd.SetOutput(ioutil.Discard) - assert.EqualError(t, cmd.Execute(), tc.expectedError) + assert.Check(t, is.Error(cmd.Execute(), tc.expectedError)) } } @@ -71,7 +72,7 @@ func TestNodeList(t *testing.T) { }) cmd := newListCommand(cli) - assert.NoError(t, cmd.Execute()) + assert.Check(t, cmd.Execute()) golden.Assert(t, cli.OutBuffer().String(), "node-list-sort.golden") } @@ -85,8 +86,8 @@ func TestNodeListQuietShouldOnlyPrintIDs(t *testing.T) { }) cmd := newListCommand(cli) cmd.Flags().Set("quiet", "true") - assert.NoError(t, cmd.Execute()) - assert.Equal(t, cli.OutBuffer().String(), "nodeID1\n") + assert.Check(t, cmd.Execute()) + assert.Check(t, is.Equal(cli.OutBuffer().String(), "nodeID1\n")) } func TestNodeListDefaultFormatFromConfig(t *testing.T) { @@ -110,7 +111,7 @@ func TestNodeListDefaultFormatFromConfig(t *testing.T) { NodesFormat: "{{.ID}}: {{.Hostname}} {{.Status}}/{{.ManagerStatus}}", }) cmd := newListCommand(cli) - assert.NoError(t, cmd.Execute()) + assert.Check(t, cmd.Execute()) golden.Assert(t, cli.OutBuffer().String(), "node-list-format-from-config.golden") } @@ -135,6 +136,6 @@ func TestNodeListFormat(t *testing.T) { }) cmd := newListCommand(cli) cmd.Flags().Set("format", "{{.Hostname}}: {{.ManagerStatus}}") - assert.NoError(t, cmd.Execute()) + assert.Check(t, cmd.Execute()) golden.Assert(t, cli.OutBuffer().String(), "node-list-format-flag.golden") } diff --git a/cli/command/node/promote_test.go b/cli/command/node/promote_test.go index 4c66342346..4cefcba79e 100644 --- a/cli/command/node/promote_test.go +++ b/cli/command/node/promote_test.go @@ -6,11 +6,11 @@ import ( "github.com/docker/cli/internal/test" "github.com/docker/docker/api/types/swarm" + "github.com/gotestyourself/gotestyourself/assert" "github.com/pkg/errors" // Import builders to get the builder function as package function . "github.com/docker/cli/internal/test/builders" "github.com/docker/cli/internal/test/testutil" - "github.com/stretchr/testify/assert" ) func TestNodePromoteErrors(t *testing.T) { @@ -64,7 +64,7 @@ func TestNodePromoteNoChange(t *testing.T) { }, })) cmd.SetArgs([]string{"nodeID"}) - assert.NoError(t, cmd.Execute()) + assert.Check(t, cmd.Execute()) } func TestNodePromoteMultipleNode(t *testing.T) { @@ -81,5 +81,5 @@ func TestNodePromoteMultipleNode(t *testing.T) { }, })) cmd.SetArgs([]string{"nodeID1", "nodeID2"}) - assert.NoError(t, cmd.Execute()) + assert.Check(t, cmd.Execute()) } diff --git a/cli/command/node/ps_test.go b/cli/command/node/ps_test.go index 836a130f76..f2a3b59757 100644 --- a/cli/command/node/ps_test.go +++ b/cli/command/node/ps_test.go @@ -12,8 +12,9 @@ import ( "github.com/pkg/errors" // Import builders to get the builder function as package function . "github.com/docker/cli/internal/test/builders" + "github.com/gotestyourself/gotestyourself/assert" + is "github.com/gotestyourself/gotestyourself/assert/cmp" "github.com/gotestyourself/gotestyourself/golden" - "github.com/stretchr/testify/assert" ) func TestNodePsErrors(t *testing.T) { @@ -60,7 +61,7 @@ func TestNodePsErrors(t *testing.T) { cmd.Flags().Set(key, value) } cmd.SetOutput(ioutil.Discard) - assert.EqualError(t, cmd.Execute(), tc.expectedError) + assert.Check(t, is.Error(cmd.Execute(), tc.expectedError)) } } @@ -122,7 +123,7 @@ func TestNodePs(t *testing.T) { for key, value := range tc.flags { cmd.Flags().Set(key, value) } - assert.NoError(t, cmd.Execute()) + assert.Check(t, cmd.Execute()) golden.Assert(t, cli.OutBuffer().String(), fmt.Sprintf("node-ps.%s.golden", tc.name)) } } diff --git a/cli/command/node/remove_test.go b/cli/command/node/remove_test.go index 78fc4f76fa..0620103d2e 100644 --- a/cli/command/node/remove_test.go +++ b/cli/command/node/remove_test.go @@ -6,8 +6,8 @@ import ( "github.com/docker/cli/internal/test" "github.com/docker/cli/internal/test/testutil" + "github.com/gotestyourself/gotestyourself/assert" "github.com/pkg/errors" - "github.com/stretchr/testify/assert" ) func TestNodeRemoveErrors(t *testing.T) { @@ -41,5 +41,5 @@ func TestNodeRemoveErrors(t *testing.T) { func TestNodeRemoveMultiple(t *testing.T) { cmd := newRemoveCommand(test.NewFakeCli(&fakeClient{})) cmd.SetArgs([]string{"nodeID1", "nodeID2"}) - assert.NoError(t, cmd.Execute()) + assert.Check(t, cmd.Execute()) } diff --git a/cli/command/node/update_test.go b/cli/command/node/update_test.go index e1aa28a806..d929c6a13d 100644 --- a/cli/command/node/update_test.go +++ b/cli/command/node/update_test.go @@ -6,11 +6,11 @@ import ( "github.com/docker/cli/internal/test" "github.com/docker/docker/api/types/swarm" + "github.com/gotestyourself/gotestyourself/assert" "github.com/pkg/errors" // Import builders to get the builder function as package function . "github.com/docker/cli/internal/test/builders" "github.com/docker/cli/internal/test/testutil" - "github.com/stretchr/testify/assert" ) func TestNodeUpdateErrors(t *testing.T) { @@ -165,6 +165,6 @@ func TestNodeUpdate(t *testing.T) { for key, value := range tc.flags { cmd.Flags().Set(key, value) } - assert.NoError(t, cmd.Execute()) + assert.Check(t, cmd.Execute()) } } diff --git a/cli/command/plugin/create_test.go b/cli/command/plugin/create_test.go index 739e4197eb..793a439d09 100644 --- a/cli/command/plugin/create_test.go +++ b/cli/command/plugin/create_test.go @@ -9,8 +9,9 @@ import ( "github.com/docker/cli/internal/test" "github.com/docker/cli/internal/test/testutil" "github.com/docker/docker/api/types" + "github.com/gotestyourself/gotestyourself/assert" + is "github.com/gotestyourself/gotestyourself/assert/cmp" "github.com/gotestyourself/gotestyourself/fs" - "github.com/stretchr/testify/assert" ) func TestCreateErrors(t *testing.T) { @@ -109,6 +110,6 @@ func TestCreatePlugin(t *testing.T) { cmd := newCreateCommand(cli) cmd.SetArgs([]string{"plugin-foo", tmpDir.Path()}) - assert.NoError(t, cmd.Execute()) - assert.Equal(t, "plugin-foo\n", cli.OutBuffer().String()) + assert.Check(t, cmd.Execute()) + assert.Check(t, is.Equal("plugin-foo\n", cli.OutBuffer().String())) } diff --git a/cli/command/plugin/disable_test.go b/cli/command/plugin/disable_test.go index 96fce34646..c9876f574a 100644 --- a/cli/command/plugin/disable_test.go +++ b/cli/command/plugin/disable_test.go @@ -8,7 +8,8 @@ import ( "github.com/docker/cli/internal/test" "github.com/docker/cli/internal/test/testutil" "github.com/docker/docker/api/types" - "github.com/stretchr/testify/assert" + "github.com/gotestyourself/gotestyourself/assert" + is "github.com/gotestyourself/gotestyourself/assert/cmp" ) func TestPluginDisableErrors(t *testing.T) { @@ -53,6 +54,6 @@ func TestPluginDisable(t *testing.T) { }) cmd := newDisableCommand(cli) cmd.SetArgs([]string{"plugin-foo"}) - assert.NoError(t, cmd.Execute()) - assert.Equal(t, "plugin-foo\n", cli.OutBuffer().String()) + assert.Check(t, cmd.Execute()) + assert.Check(t, is.Equal("plugin-foo\n", cli.OutBuffer().String())) } diff --git a/cli/command/plugin/enable_test.go b/cli/command/plugin/enable_test.go index 68b50eae6f..f994830a68 100644 --- a/cli/command/plugin/enable_test.go +++ b/cli/command/plugin/enable_test.go @@ -8,7 +8,8 @@ import ( "github.com/docker/cli/internal/test" "github.com/docker/cli/internal/test/testutil" "github.com/docker/docker/api/types" - "github.com/stretchr/testify/assert" + "github.com/gotestyourself/gotestyourself/assert" + is "github.com/gotestyourself/gotestyourself/assert/cmp" ) func TestPluginEnableErrors(t *testing.T) { @@ -65,6 +66,6 @@ func TestPluginEnable(t *testing.T) { cmd := newEnableCommand(cli) cmd.SetArgs([]string{"plugin-foo"}) - assert.NoError(t, cmd.Execute()) - assert.Equal(t, "plugin-foo\n", cli.OutBuffer().String()) + assert.Check(t, cmd.Execute()) + assert.Check(t, is.Equal("plugin-foo\n", cli.OutBuffer().String())) } diff --git a/cli/command/plugin/remove_test.go b/cli/command/plugin/remove_test.go index cc179091b9..8053f3a308 100644 --- a/cli/command/plugin/remove_test.go +++ b/cli/command/plugin/remove_test.go @@ -8,7 +8,8 @@ import ( "github.com/docker/cli/internal/test" "github.com/docker/cli/internal/test/testutil" "github.com/docker/docker/api/types" - "github.com/stretchr/testify/assert" + "github.com/gotestyourself/gotestyourself/assert" + is "github.com/gotestyourself/gotestyourself/assert/cmp" ) func TestRemoveErrors(t *testing.T) { @@ -50,8 +51,8 @@ func TestRemove(t *testing.T) { }) cmd := newRemoveCommand(cli) cmd.SetArgs([]string{"plugin-foo"}) - assert.NoError(t, cmd.Execute()) - assert.Equal(t, "plugin-foo\n", cli.OutBuffer().String()) + assert.Check(t, cmd.Execute()) + assert.Check(t, is.Equal("plugin-foo\n", cli.OutBuffer().String())) } func TestRemoveWithForceOption(t *testing.T) { @@ -65,7 +66,7 @@ func TestRemoveWithForceOption(t *testing.T) { cmd := newRemoveCommand(cli) cmd.SetArgs([]string{"plugin-foo"}) cmd.Flags().Set("force", "true") - assert.NoError(t, cmd.Execute()) - assert.True(t, force) - assert.Equal(t, "plugin-foo\n", cli.OutBuffer().String()) + assert.Check(t, cmd.Execute()) + assert.Check(t, force) + assert.Check(t, is.Equal("plugin-foo\n", cli.OutBuffer().String())) } diff --git a/cli/command/registry/login_test.go b/cli/command/registry/login_test.go index 498e0267f2..11db1ba6b0 100644 --- a/cli/command/registry/login_test.go +++ b/cli/command/registry/login_test.go @@ -11,7 +11,8 @@ import ( "github.com/docker/docker/api/types" registrytypes "github.com/docker/docker/api/types/registry" "github.com/docker/docker/client" - "github.com/stretchr/testify/assert" + "github.com/gotestyourself/gotestyourself/assert" + is "github.com/gotestyourself/gotestyourself/assert/cmp" ) const userErr = "userunknownError" @@ -63,9 +64,9 @@ func TestLoginWithCredStoreCreds(t *testing.T) { cli.SetErr(errBuf) loginWithCredStoreCreds(ctx, cli, &tc.inputAuthConfig) outputString := cli.OutBuffer().String() - assert.Equal(t, tc.expectedMsg, outputString) + assert.Check(t, is.Equal(tc.expectedMsg, outputString)) errorString := errBuf.String() - assert.Equal(t, tc.expectedErr, errorString) + assert.Check(t, is.Equal(tc.expectedErr, errorString)) } } @@ -140,12 +141,12 @@ func TestRunLogin(t *testing.T) { } loginErr := runLogin(cli, tc.inputLoginOption) if tc.expectedErr != "" { - assert.Equal(t, tc.expectedErr, loginErr.Error()) + assert.Check(t, is.Equal(tc.expectedErr, loginErr.Error())) } else { - assert.Nil(t, loginErr) + assert.Check(t, loginErr) savedCred, credStoreErr := cli.ConfigFile().GetCredentialsStore(tc.inputStoredCred.ServerAddress).Get(tc.inputStoredCred.ServerAddress) - assert.Nil(t, credStoreErr) - assert.Equal(t, tc.expectedSavedCred, savedCred) + assert.Check(t, credStoreErr) + assert.Check(t, is.DeepEqual(tc.expectedSavedCred, savedCred)) } } } diff --git a/cli/command/registry_test.go b/cli/command/registry_test.go index 3672ae8d45..0c56c79737 100644 --- a/cli/command/registry_test.go +++ b/cli/command/registry_test.go @@ -5,8 +5,9 @@ import ( "fmt" "testing" + "github.com/gotestyourself/gotestyourself/assert" + is "github.com/gotestyourself/gotestyourself/assert/cmp" "github.com/pkg/errors" - "github.com/stretchr/testify/assert" "golang.org/x/net/context" // Prevents a circular import with "github.com/docker/cli/internal/test" @@ -80,12 +81,12 @@ func TestElectAuthServer(t *testing.T) { for _, tc := range testCases { cli := test.NewFakeCli(&fakeClient{infoFunc: tc.infoFunc}) server := ElectAuthServer(context.Background(), cli) - assert.Equal(t, tc.expectedAuthServer, server) + assert.Check(t, is.Equal(tc.expectedAuthServer, server)) actual := cli.ErrBuffer().String() if tc.expectedWarning == "" { - assert.Empty(t, actual) + assert.Check(t, is.Len(actual, 0)) } else { - assert.Contains(t, actual, tc.expectedWarning) + assert.Check(t, is.Contains(actual, tc.expectedWarning)) } } } @@ -136,11 +137,11 @@ func TestGetDefaultAuthConfig(t *testing.T) { serverAddress := tc.inputServerAddress authconfig, err := GetDefaultAuthConfig(cli, tc.checkCredStore, serverAddress, serverAddress == "https://index.docker.io/v1/") if tc.expectedErr != "" { - assert.NotNil(t, err) - assert.Equal(t, tc.expectedErr, err.Error()) + assert.Check(t, err != nil) + assert.Check(t, is.Equal(tc.expectedErr, err.Error())) } else { - assert.Nil(t, err) - assert.Equal(t, tc.expectedAuthConfig, *authconfig) + assert.Check(t, err) + assert.Check(t, is.DeepEqual(tc.expectedAuthConfig, *authconfig)) } } } diff --git a/cli/command/secret/create_test.go b/cli/command/secret/create_test.go index 383ed77660..8870c9a14b 100644 --- a/cli/command/secret/create_test.go +++ b/cli/command/secret/create_test.go @@ -11,8 +11,9 @@ import ( "github.com/docker/cli/internal/test/testutil" "github.com/docker/docker/api/types" "github.com/docker/docker/api/types/swarm" + "github.com/gotestyourself/gotestyourself/assert" + is "github.com/gotestyourself/gotestyourself/assert/cmp" "github.com/pkg/errors" - "github.com/stretchr/testify/assert" ) const secretDataFile = "secret-create-with-name.golden" @@ -52,7 +53,7 @@ func TestSecretCreateErrors(t *testing.T) { func TestSecretCreateWithName(t *testing.T) { name := "foo" data, err := ioutil.ReadFile(filepath.Join("testdata", secretDataFile)) - assert.NoError(t, err) + assert.Check(t, err) expected := swarm.SecretSpec{ Annotations: swarm.Annotations{ @@ -75,8 +76,8 @@ func TestSecretCreateWithName(t *testing.T) { cmd := newSecretCreateCommand(cli) cmd.SetArgs([]string{name, filepath.Join("testdata", secretDataFile)}) - assert.NoError(t, cmd.Execute()) - assert.Equal(t, "ID-"+name, strings.TrimSpace(cli.OutBuffer().String())) + assert.Check(t, cmd.Execute()) + assert.Check(t, is.Equal("ID-"+name, strings.TrimSpace(cli.OutBuffer().String()))) } func TestSecretCreateWithDriver(t *testing.T) { @@ -104,8 +105,8 @@ func TestSecretCreateWithDriver(t *testing.T) { cmd := newSecretCreateCommand(cli) cmd.SetArgs([]string{name}) cmd.Flags().Set("driver", expectedDriver.Name) - assert.NoError(t, cmd.Execute()) - assert.Equal(t, "ID-"+name, strings.TrimSpace(cli.OutBuffer().String())) + assert.Check(t, cmd.Execute()) + assert.Check(t, is.Equal("ID-"+name, strings.TrimSpace(cli.OutBuffer().String()))) } func TestSecretCreateWithTemplatingDriver(t *testing.T) { @@ -133,8 +134,8 @@ func TestSecretCreateWithTemplatingDriver(t *testing.T) { cmd := newSecretCreateCommand(cli) cmd.SetArgs([]string{name}) cmd.Flags().Set("template-driver", expectedDriver.Name) - assert.NoError(t, cmd.Execute()) - assert.Equal(t, "ID-"+name, strings.TrimSpace(cli.OutBuffer().String())) + assert.Check(t, cmd.Execute()) + assert.Check(t, is.Equal("ID-"+name, strings.TrimSpace(cli.OutBuffer().String()))) } func TestSecretCreateWithLabels(t *testing.T) { @@ -164,6 +165,6 @@ func TestSecretCreateWithLabels(t *testing.T) { cmd.SetArgs([]string{name, filepath.Join("testdata", secretDataFile)}) cmd.Flags().Set("label", "lbl1=Label-foo") cmd.Flags().Set("label", "lbl2=Label-bar") - assert.NoError(t, cmd.Execute()) - assert.Equal(t, "ID-"+name, strings.TrimSpace(cli.OutBuffer().String())) + assert.Check(t, cmd.Execute()) + assert.Check(t, is.Equal("ID-"+name, strings.TrimSpace(cli.OutBuffer().String()))) } diff --git a/cli/command/secret/inspect_test.go b/cli/command/secret/inspect_test.go index cb74e11ae2..8aadb1bc1f 100644 --- a/cli/command/secret/inspect_test.go +++ b/cli/command/secret/inspect_test.go @@ -12,8 +12,8 @@ import ( // Import builders to get the builder function as package function . "github.com/docker/cli/internal/test/builders" "github.com/docker/cli/internal/test/testutil" + "github.com/gotestyourself/gotestyourself/assert" "github.com/gotestyourself/gotestyourself/golden" - "github.com/stretchr/testify/assert" ) func TestSecretInspectErrors(t *testing.T) { @@ -98,7 +98,7 @@ func TestSecretInspectWithoutFormat(t *testing.T) { }) cmd := newSecretInspectCommand(cli) cmd.SetArgs(tc.args) - assert.NoError(t, cmd.Execute()) + assert.Check(t, cmd.Execute()) golden.Assert(t, cli.OutBuffer().String(), fmt.Sprintf("secret-inspect-without-format.%s.golden", tc.name)) } } @@ -135,7 +135,7 @@ func TestSecretInspectWithFormat(t *testing.T) { cmd := newSecretInspectCommand(cli) cmd.SetArgs(tc.args) cmd.Flags().Set("format", tc.format) - assert.NoError(t, cmd.Execute()) + assert.Check(t, cmd.Execute()) golden.Assert(t, cli.OutBuffer().String(), fmt.Sprintf("secret-inspect-with-format.%s.golden", tc.name)) } } @@ -168,7 +168,7 @@ func TestSecretInspectPretty(t *testing.T) { cmd := newSecretInspectCommand(cli) cmd.SetArgs([]string{"secretID"}) cmd.Flags().Set("pretty", "true") - assert.NoError(t, cmd.Execute()) + assert.Check(t, cmd.Execute()) golden.Assert(t, cli.OutBuffer().String(), fmt.Sprintf("secret-inspect-pretty.%s.golden", tc.name)) } } diff --git a/cli/command/secret/ls_test.go b/cli/command/secret/ls_test.go index 28b087a5ae..513988d66c 100644 --- a/cli/command/secret/ls_test.go +++ b/cli/command/secret/ls_test.go @@ -13,8 +13,9 @@ import ( // Import builders to get the builder function as package function . "github.com/docker/cli/internal/test/builders" "github.com/docker/cli/internal/test/testutil" + "github.com/gotestyourself/gotestyourself/assert" + is "github.com/gotestyourself/gotestyourself/assert/cmp" "github.com/gotestyourself/gotestyourself/golden" - "github.com/stretchr/testify/assert" ) func TestSecretListErrors(t *testing.T) { @@ -74,7 +75,7 @@ func TestSecretList(t *testing.T) { }, }) cmd := newSecretListCommand(cli) - assert.NoError(t, cmd.Execute()) + assert.Check(t, cmd.Execute()) golden.Assert(t, cli.OutBuffer().String(), "secret-list-sort.golden") } @@ -91,7 +92,7 @@ func TestSecretListWithQuietOption(t *testing.T) { }) cmd := newSecretListCommand(cli) cmd.Flags().Set("quiet", "true") - assert.NoError(t, cmd.Execute()) + assert.Check(t, cmd.Execute()) golden.Assert(t, cli.OutBuffer().String(), "secret-list-with-quiet-option.golden") } @@ -110,7 +111,7 @@ func TestSecretListWithConfigFormat(t *testing.T) { SecretFormat: "{{ .Name }} {{ .Labels }}", }) cmd := newSecretListCommand(cli) - assert.NoError(t, cmd.Execute()) + assert.Check(t, cmd.Execute()) golden.Assert(t, cli.OutBuffer().String(), "secret-list-with-config-format.golden") } @@ -127,15 +128,15 @@ func TestSecretListWithFormat(t *testing.T) { }) cmd := newSecretListCommand(cli) cmd.Flags().Set("format", "{{ .Name }} {{ .Labels }}") - assert.NoError(t, cmd.Execute()) + assert.Check(t, cmd.Execute()) golden.Assert(t, cli.OutBuffer().String(), "secret-list-with-format.golden") } func TestSecretListWithFilter(t *testing.T) { cli := test.NewFakeCli(&fakeClient{ secretListFunc: func(options types.SecretListOptions) ([]swarm.Secret, error) { - assert.Equal(t, "foo", options.Filters.Get("name")[0], "foo") - assert.Equal(t, "lbl1=Label-bar", options.Filters.Get("label")[0]) + assert.Check(t, is.Equal("foo", options.Filters.Get("name")[0]), "foo") + assert.Check(t, is.Equal("lbl1=Label-bar", options.Filters.Get("label")[0])) return []swarm.Secret{ *Secret(SecretID("ID-foo"), SecretName("foo"), @@ -155,6 +156,6 @@ func TestSecretListWithFilter(t *testing.T) { cmd := newSecretListCommand(cli) cmd.Flags().Set("filter", "name=foo") cmd.Flags().Set("filter", "label=lbl1=Label-bar") - assert.NoError(t, cmd.Execute()) + assert.Check(t, cmd.Execute()) golden.Assert(t, cli.OutBuffer().String(), "secret-list-with-filter.golden") } diff --git a/cli/command/secret/remove_test.go b/cli/command/secret/remove_test.go index accb3ea042..f9b4477baa 100644 --- a/cli/command/secret/remove_test.go +++ b/cli/command/secret/remove_test.go @@ -7,8 +7,9 @@ import ( "github.com/docker/cli/internal/test" "github.com/docker/cli/internal/test/testutil" + "github.com/gotestyourself/gotestyourself/assert" + is "github.com/gotestyourself/gotestyourself/assert/cmp" "github.com/pkg/errors" - "github.com/stretchr/testify/assert" ) func TestSecretRemoveErrors(t *testing.T) { @@ -52,9 +53,9 @@ func TestSecretRemoveWithName(t *testing.T) { }) cmd := newSecretRemoveCommand(cli) cmd.SetArgs(names) - assert.NoError(t, cmd.Execute()) - assert.Equal(t, names, strings.Split(strings.TrimSpace(cli.OutBuffer().String()), "\n")) - assert.Equal(t, names, removedSecrets) + assert.Check(t, cmd.Execute()) + assert.Check(t, is.DeepEqual(names, strings.Split(strings.TrimSpace(cli.OutBuffer().String()), "\n"))) + assert.Check(t, is.DeepEqual(names, removedSecrets)) } func TestSecretRemoveContinueAfterError(t *testing.T) { @@ -74,6 +75,6 @@ func TestSecretRemoveContinueAfterError(t *testing.T) { cmd := newSecretRemoveCommand(cli) cmd.SetOutput(ioutil.Discard) cmd.SetArgs(names) - assert.EqualError(t, cmd.Execute(), "error removing secret: foo") - assert.Equal(t, names, removedSecrets) + assert.Check(t, is.Error(cmd.Execute(), "error removing secret: foo")) + assert.Check(t, is.DeepEqual(names, removedSecrets)) } diff --git a/cli/command/service/generic_resource_opts_test.go b/cli/command/service/generic_resource_opts_test.go index 99217e9f36..3d64a99857 100644 --- a/cli/command/service/generic_resource_opts_test.go +++ b/cli/command/service/generic_resource_opts_test.go @@ -3,7 +3,8 @@ package service import ( "testing" - "github.com/stretchr/testify/assert" + "github.com/gotestyourself/gotestyourself/assert" + is "github.com/gotestyourself/gotestyourself/assert/cmp" ) func TestValidateSingleGenericResource(t *testing.T) { @@ -12,11 +13,11 @@ func TestValidateSingleGenericResource(t *testing.T) { for _, v := range incorrect { _, err := ValidateSingleGenericResource(v) - assert.Error(t, err) + assert.Check(t, is.ErrorContains(err, "")) } for _, v := range correct { _, err := ValidateSingleGenericResource(v) - assert.NoError(t, err) + assert.Check(t, err) } } diff --git a/cli/command/service/inspect_test.go b/cli/command/service/inspect_test.go index d464197202..7339dc968f 100644 --- a/cli/command/service/inspect_test.go +++ b/cli/command/service/inspect_test.go @@ -10,7 +10,8 @@ import ( "github.com/docker/cli/cli/command/formatter" "github.com/docker/docker/api/types" "github.com/docker/docker/api/types/swarm" - "github.com/stretchr/testify/assert" + "github.com/gotestyourself/gotestyourself/assert" + is "github.com/gotestyourself/gotestyourself/assert/cmp" ) func formatServiceInspect(t *testing.T, format formatter.Format, now time.Time) string { @@ -130,5 +131,5 @@ func TestJSONFormatWithNoUpdateConfig(t *testing.T) { if err := json.Unmarshal([]byte(s2), &m2); err != nil { t.Fatal(err) } - assert.Equal(t, m1, m2) + assert.Check(t, is.DeepEqual(m1, m2)) } diff --git a/cli/command/service/list_test.go b/cli/command/service/list_test.go index 679c733701..18e8f09fca 100644 --- a/cli/command/service/list_test.go +++ b/cli/command/service/list_test.go @@ -6,8 +6,8 @@ import ( "github.com/docker/cli/internal/test" "github.com/docker/docker/api/types" "github.com/docker/docker/api/types/swarm" + "github.com/gotestyourself/gotestyourself/assert" "github.com/gotestyourself/gotestyourself/golden" - "github.com/stretchr/testify/assert" "golang.org/x/net/context" ) @@ -23,6 +23,6 @@ func TestServiceListOrder(t *testing.T) { }) cmd := newListCommand(cli) cmd.Flags().Set("format", "{{.Name}}") - assert.NoError(t, cmd.Execute()) + assert.Check(t, cmd.Execute()) golden.Assert(t, cli.OutBuffer().String(), "service-list-sort.golden") } diff --git a/cli/command/service/opts_test.go b/cli/command/service/opts_test.go index f68cbb3c5a..8127d61d68 100644 --- a/cli/command/service/opts_test.go +++ b/cli/command/service/opts_test.go @@ -10,45 +10,45 @@ import ( "github.com/docker/docker/api/types" "github.com/docker/docker/api/types/container" "github.com/docker/docker/api/types/swarm" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" + "github.com/gotestyourself/gotestyourself/assert" + is "github.com/gotestyourself/gotestyourself/assert/cmp" ) func TestMemBytesString(t *testing.T) { var mem opts.MemBytes = 1048576 - assert.Equal(t, "1MiB", mem.String()) + assert.Check(t, is.Equal("1MiB", mem.String())) } func TestMemBytesSetAndValue(t *testing.T) { var mem opts.MemBytes - assert.NoError(t, mem.Set("5kb")) - assert.Equal(t, int64(5120), mem.Value()) + assert.Check(t, mem.Set("5kb")) + assert.Check(t, is.Equal(int64(5120), mem.Value())) } func TestNanoCPUsString(t *testing.T) { var cpus opts.NanoCPUs = 6100000000 - assert.Equal(t, "6.100", cpus.String()) + assert.Check(t, is.Equal("6.100", cpus.String())) } func TestNanoCPUsSetAndValue(t *testing.T) { var cpus opts.NanoCPUs - assert.NoError(t, cpus.Set("0.35")) - assert.Equal(t, int64(350000000), cpus.Value()) + assert.Check(t, cpus.Set("0.35")) + assert.Check(t, is.Equal(int64(350000000), cpus.Value())) } func TestUint64OptString(t *testing.T) { value := uint64(2345678) opt := Uint64Opt{value: &value} - assert.Equal(t, "2345678", opt.String()) + assert.Check(t, is.Equal("2345678", opt.String())) opt = Uint64Opt{} - assert.Equal(t, "", opt.String()) + assert.Check(t, is.Equal("", opt.String())) } func TestUint64OptSetAndValue(t *testing.T) { var opt Uint64Opt - assert.NoError(t, opt.Set("14445")) - assert.Equal(t, uint64(14445), *opt.Value()) + assert.Check(t, opt.Set("14445")) + assert.Check(t, is.Equal(uint64(14445), *opt.Value())) } func TestHealthCheckOptionsToHealthConfig(t *testing.T) { @@ -61,14 +61,14 @@ func TestHealthCheckOptionsToHealthConfig(t *testing.T) { retries: 10, } config, err := opt.toHealthConfig() - assert.NoError(t, err) - assert.Equal(t, &container.HealthConfig{ + assert.Check(t, err) + assert.Check(t, is.DeepEqual(&container.HealthConfig{ Test: []string{"CMD-SHELL", "curl"}, Interval: time.Second, Timeout: time.Second, StartPeriod: time.Second, Retries: 10, - }, config) + }, config)) } func TestHealthCheckOptionsToHealthConfigNoHealthcheck(t *testing.T) { @@ -76,10 +76,10 @@ func TestHealthCheckOptionsToHealthConfigNoHealthcheck(t *testing.T) { noHealthcheck: true, } config, err := opt.toHealthConfig() - assert.NoError(t, err) - assert.Equal(t, &container.HealthConfig{ + assert.Check(t, err) + assert.Check(t, is.DeepEqual(&container.HealthConfig{ Test: []string{"NONE"}, - }, config) + }, config)) } func TestHealthCheckOptionsToHealthConfigConflict(t *testing.T) { @@ -88,7 +88,7 @@ func TestHealthCheckOptionsToHealthConfigConflict(t *testing.T) { noHealthcheck: true, } _, err := opt.toHealthConfig() - assert.EqualError(t, err, "--no-healthcheck conflicts with --health-* options") + assert.Check(t, is.Error(err, "--no-healthcheck conflicts with --health-* options")) } func TestResourceOptionsToResourceRequirements(t *testing.T) { @@ -109,7 +109,7 @@ func TestResourceOptionsToResourceRequirements(t *testing.T) { for _, opt := range incorrectOptions { _, err := opt.ToResourceRequirements() - assert.Error(t, err) + assert.Check(t, is.ErrorContains(err, "")) } correctOptions := []resourceOptions{ @@ -123,8 +123,8 @@ func TestResourceOptionsToResourceRequirements(t *testing.T) { for _, opt := range correctOptions { r, err := opt.ToResourceRequirements() - assert.NoError(t, err) - assert.Len(t, r.Reservations.GenericResources, len(opt.resGenericResources)) + assert.Check(t, err) + assert.Check(t, is.Len(r.Reservations.GenericResources, len(opt.resGenericResources))) } } @@ -159,6 +159,6 @@ func TestToServiceNetwork(t *testing.T) { ctx := context.Background() flags := newCreateCommand(nil).Flags() service, err := o.ToService(ctx, client, flags) - require.NoError(t, err) - assert.Equal(t, []swarm.NetworkAttachmentConfig{{Target: "id111"}, {Target: "id555"}, {Target: "id999"}}, service.TaskTemplate.Networks) + assert.NilError(t, err) + assert.Check(t, is.DeepEqual([]swarm.NetworkAttachmentConfig{{Target: "id111"}, {Target: "id555"}, {Target: "id999"}}, service.TaskTemplate.Networks)) } diff --git a/cli/command/service/progress/progress_test.go b/cli/command/service/progress/progress_test.go index d1c118f7d7..198d29acf6 100644 --- a/cli/command/service/progress/progress_test.go +++ b/cli/command/service/progress/progress_test.go @@ -7,7 +7,8 @@ import ( "github.com/docker/docker/api/types/swarm" "github.com/docker/docker/pkg/progress" - "github.com/stretchr/testify/assert" + "github.com/gotestyourself/gotestyourself/assert" + is "github.com/gotestyourself/gotestyourself/assert/cmp" ) type mockProgress struct { @@ -36,9 +37,9 @@ func (u updaterTester) testUpdater(tasks []swarm.Task, expectedConvergence bool, u.p.clear() converged, err := u.updater.update(u.service, tasks, u.activeNodes, u.rollback) - assert.NoError(u.t, err) - assert.Equal(u.t, expectedConvergence, converged) - assert.Equal(u.t, expectedProgress, u.p.p) + assert.Check(u.t, err) + assert.Check(u.t, is.Equal(expectedConvergence, converged)) + assert.Check(u.t, is.DeepEqual(expectedProgress, u.p.p)) } func TestReplicatedProgressUpdaterOneReplica(t *testing.T) { diff --git a/cli/command/service/ps_test.go b/cli/command/service/ps_test.go index e3f30dcb5b..0f50edc0d0 100644 --- a/cli/command/service/ps_test.go +++ b/cli/command/service/ps_test.go @@ -8,8 +8,9 @@ import ( "github.com/docker/docker/api/types" "github.com/docker/docker/api/types/filters" "github.com/docker/docker/api/types/swarm" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" + "github.com/google/go-cmp/cmp" + "github.com/gotestyourself/gotestyourself/assert" + is "github.com/gotestyourself/gotestyourself/assert/cmp" "golang.org/x/net/context" ) @@ -26,22 +27,23 @@ func TestCreateFilter(t *testing.T) { } filter := opts.NewFilterOpt() - require.NoError(t, filter.Set("node=somenode")) + assert.NilError(t, filter.Set("node=somenode")) options := psOptions{ services: []string{"idmatch", "idprefix", "namematch", "notfound"}, filter: filter, } actual, notfound, err := createFilter(context.Background(), client, options) - require.NoError(t, err) - assert.Equal(t, notfound, []string{"no such service: notfound"}) + assert.NilError(t, err) + assert.Check(t, is.DeepEqual(notfound, []string{"no such service: notfound"})) - expected := filters.NewArgs() - expected.Add("service", "idmatch") - expected.Add("service", "idprefixmatch") - expected.Add("service", "cccccccc") - expected.Add("node", "somenode") - assert.Equal(t, expected, actual) + expected := filters.NewArgs( + filters.Arg("service", "idmatch"), + filters.Arg("service", "idprefixmatch"), + filters.Arg("service", "cccccccc"), + filters.Arg("node", "somenode"), + ) + assert.DeepEqual(t, expected, actual, cmpFilters) } func TestCreateFilterWithAmbiguousIDPrefixError(t *testing.T) { @@ -58,7 +60,7 @@ func TestCreateFilterWithAmbiguousIDPrefixError(t *testing.T) { filter: opts.NewFilterOpt(), } _, _, err := createFilter(context.Background(), client, options) - assert.EqualError(t, err, "multiple services found with provided prefix: aaa") + assert.Check(t, is.Error(err, "multiple services found with provided prefix: aaa")) } func TestCreateFilterNoneFound(t *testing.T) { @@ -68,7 +70,7 @@ func TestCreateFilterNoneFound(t *testing.T) { filter: opts.NewFilterOpt(), } _, _, err := createFilter(context.Background(), client, options) - assert.EqualError(t, err, "no such service: foo\nno such service: notfound") + assert.Check(t, is.Error(err, "no such service: foo\nno such service: notfound")) } func TestRunPSWarnsOnNotFound(t *testing.T) { @@ -87,7 +89,7 @@ func TestRunPSWarnsOnNotFound(t *testing.T) { format: "{{.ID}}", } err := runPS(cli, options) - assert.EqualError(t, err, "no such service: bar") + assert.Check(t, is.Error(err, "no such service: bar")) } func TestRunPSQuiet(t *testing.T) { @@ -102,16 +104,17 @@ func TestRunPSQuiet(t *testing.T) { cli := test.NewFakeCli(client) err := runPS(cli, psOptions{services: []string{"foo"}, quiet: true, filter: opts.NewFilterOpt()}) - require.NoError(t, err) - assert.Equal(t, "sxabyp0obqokwekpun4rjo0b3\n", cli.OutBuffer().String()) + assert.NilError(t, err) + assert.Check(t, is.Equal("sxabyp0obqokwekpun4rjo0b3\n", cli.OutBuffer().String())) } func TestUpdateNodeFilter(t *testing.T) { selfNodeID := "foofoo" - filter := filters.NewArgs() - filter.Add("node", "one") - filter.Add("node", "two") - filter.Add("node", "self") + filter := filters.NewArgs( + filters.Arg("node", "one"), + filters.Arg("node", "two"), + filters.Arg("node", "self"), + ) client := &fakeClient{ infoFunc: func(_ context.Context) (types.Info, error) { @@ -121,9 +124,12 @@ func TestUpdateNodeFilter(t *testing.T) { updateNodeFilter(context.Background(), client, filter) - expected := filters.NewArgs() - expected.Add("node", "one") - expected.Add("node", "two") - expected.Add("node", selfNodeID) - assert.Equal(t, expected, filter) + expected := filters.NewArgs( + filters.Arg("node", "one"), + filters.Arg("node", "two"), + filters.Arg("node", selfNodeID), + ) + assert.DeepEqual(t, expected, filter, cmpFilters) } + +var cmpFilters = cmp.AllowUnexported(filters.Args{}) diff --git a/cli/command/service/rollback_test.go b/cli/command/service/rollback_test.go index c063676645..bc97b349c0 100644 --- a/cli/command/service/rollback_test.go +++ b/cli/command/service/rollback_test.go @@ -10,7 +10,8 @@ import ( "github.com/docker/cli/internal/test/testutil" "github.com/docker/docker/api/types" "github.com/docker/docker/api/types/swarm" - "github.com/stretchr/testify/assert" + "github.com/gotestyourself/gotestyourself/assert" + is "github.com/gotestyourself/gotestyourself/assert/cmp" "golang.org/x/net/context" ) @@ -50,8 +51,8 @@ func TestRollback(t *testing.T) { cmd.SetArgs(tc.args) cmd.Flags().Set("quiet", "true") cmd.SetOutput(ioutil.Discard) - assert.NoError(t, cmd.Execute()) - assert.Equal(t, strings.TrimSpace(cli.ErrBuffer().String()), tc.expectedDockerCliErr) + assert.Check(t, cmd.Execute()) + assert.Check(t, is.Equal(strings.TrimSpace(cli.ErrBuffer().String()), tc.expectedDockerCliErr)) } } diff --git a/cli/command/service/update_test.go b/cli/command/service/update_test.go index e7e428192f..04e6e24edf 100644 --- a/cli/command/service/update_test.go +++ b/cli/command/service/update_test.go @@ -12,8 +12,8 @@ import ( "github.com/docker/docker/api/types/container" mounttypes "github.com/docker/docker/api/types/mount" "github.com/docker/docker/api/types/swarm" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" + "github.com/gotestyourself/gotestyourself/assert" + is "github.com/gotestyourself/gotestyourself/assert/cmp" "golang.org/x/net/context" ) @@ -30,7 +30,7 @@ func TestUpdateServiceArgs(t *testing.T) { cspec.Args = []string{"old", "args"} updateService(nil, nil, flags, spec) - assert.Equal(t, []string{"the", "new args"}, cspec.Args) + assert.Check(t, is.DeepEqual([]string{"the", "new args"}, cspec.Args)) } func TestUpdateLabels(t *testing.T) { @@ -44,9 +44,9 @@ func TestUpdateLabels(t *testing.T) { } updateLabels(flags, &labels) - assert.Len(t, labels, 2) - assert.Equal(t, "value", labels["tokeep"]) - assert.Equal(t, "newlabel", labels["toadd"]) + assert.Check(t, is.Len(labels, 2)) + assert.Check(t, is.Equal("value", labels["tokeep"])) + assert.Check(t, is.Equal("newlabel", labels["toadd"])) } func TestUpdateLabelsRemoveALabelThatDoesNotExist(t *testing.T) { @@ -55,7 +55,7 @@ func TestUpdateLabelsRemoveALabelThatDoesNotExist(t *testing.T) { labels := map[string]string{"foo": "theoldlabel"} updateLabels(flags, &labels) - assert.Len(t, labels, 1) + assert.Check(t, is.Len(labels, 1)) } func TestUpdatePlacementConstraints(t *testing.T) { @@ -68,9 +68,9 @@ func TestUpdatePlacementConstraints(t *testing.T) { } updatePlacementConstraints(flags, placement) - require.Len(t, placement.Constraints, 2) - assert.Equal(t, "container=tokeep", placement.Constraints[0]) - assert.Equal(t, "node=toadd", placement.Constraints[1]) + assert.Assert(t, is.Len(placement.Constraints, 2)) + assert.Check(t, is.Equal("container=tokeep", placement.Constraints[0])) + assert.Check(t, is.Equal("node=toadd", placement.Constraints[1])) } func TestUpdatePlacementPrefs(t *testing.T) { @@ -94,9 +94,9 @@ func TestUpdatePlacementPrefs(t *testing.T) { } updatePlacementPreferences(flags, placement) - require.Len(t, placement.Preferences, 2) - assert.Equal(t, "node.labels.row", placement.Preferences[0].Spread.SpreadDescriptor) - assert.Equal(t, "node.labels.dc", placement.Preferences[1].Spread.SpreadDescriptor) + assert.Assert(t, is.Len(placement.Preferences, 2)) + assert.Check(t, is.Equal("node.labels.row", placement.Preferences[0].Spread.SpreadDescriptor)) + assert.Check(t, is.Equal("node.labels.dc", placement.Preferences[1].Spread.SpreadDescriptor)) } func TestUpdateEnvironment(t *testing.T) { @@ -107,11 +107,11 @@ func TestUpdateEnvironment(t *testing.T) { envs := []string{"toremove=theenvtoremove", "tokeep=value"} updateEnvironment(flags, &envs) - require.Len(t, envs, 2) + assert.Assert(t, is.Len(envs, 2)) // Order has been removed in updateEnvironment (map) sort.Strings(envs) - assert.Equal(t, "toadd=newenv", envs[0]) - assert.Equal(t, "tokeep=value", envs[1]) + assert.Check(t, is.Equal("toadd=newenv", envs[0])) + assert.Check(t, is.Equal("tokeep=value", envs[1])) } func TestUpdateEnvironmentWithDuplicateValues(t *testing.T) { @@ -123,7 +123,7 @@ func TestUpdateEnvironmentWithDuplicateValues(t *testing.T) { envs := []string{"foo=value"} updateEnvironment(flags, &envs) - assert.Len(t, envs, 0) + assert.Check(t, is.Len(envs, 0)) } func TestUpdateEnvironmentWithDuplicateKeys(t *testing.T) { @@ -134,8 +134,8 @@ func TestUpdateEnvironmentWithDuplicateKeys(t *testing.T) { envs := []string{"A=c"} updateEnvironment(flags, &envs) - require.Len(t, envs, 1) - assert.Equal(t, "A=b", envs[0]) + assert.Assert(t, is.Len(envs, 1)) + assert.Check(t, is.Equal("A=b", envs[0])) } func TestUpdateGroups(t *testing.T) { @@ -149,10 +149,10 @@ func TestUpdateGroups(t *testing.T) { groups := []string{"bar", "root"} updateGroups(flags, &groups) - require.Len(t, groups, 3) - assert.Equal(t, "bar", groups[0]) - assert.Equal(t, "foo", groups[1]) - assert.Equal(t, "wheel", groups[2]) + assert.Assert(t, is.Len(groups, 3)) + assert.Check(t, is.Equal("bar", groups[0])) + assert.Check(t, is.Equal("foo", groups[1])) + assert.Check(t, is.Equal("wheel", groups[2])) } func TestUpdateDNSConfig(t *testing.T) { @@ -188,17 +188,17 @@ func TestUpdateDNSConfig(t *testing.T) { updateDNSConfig(flags, &config) - require.Len(t, config.Nameservers, 3) - assert.Equal(t, "1.1.1.1", config.Nameservers[0]) - assert.Equal(t, "2001:db8:abc8::1", config.Nameservers[1]) - assert.Equal(t, "5.5.5.5", config.Nameservers[2]) + assert.Assert(t, is.Len(config.Nameservers, 3)) + assert.Check(t, is.Equal("1.1.1.1", config.Nameservers[0])) + assert.Check(t, is.Equal("2001:db8:abc8::1", config.Nameservers[1])) + assert.Check(t, is.Equal("5.5.5.5", config.Nameservers[2])) - require.Len(t, config.Search, 2) - assert.Equal(t, "example.com", config.Search[0]) - assert.Equal(t, "localdomain", config.Search[1]) + assert.Assert(t, is.Len(config.Search, 2)) + assert.Check(t, is.Equal("example.com", config.Search[0])) + assert.Check(t, is.Equal("localdomain", config.Search[1])) - require.Len(t, config.Options, 1) - assert.Equal(t, config.Options[0], "ndots:9") + assert.Assert(t, is.Len(config.Options, 1)) + assert.Check(t, is.Equal(config.Options[0], "ndots:9")) } func TestUpdateMounts(t *testing.T) { @@ -212,9 +212,9 @@ func TestUpdateMounts(t *testing.T) { } updateMounts(flags, &mounts) - require.Len(t, mounts, 2) - assert.Equal(t, "/toadd", mounts[0].Target) - assert.Equal(t, "/tokeep", mounts[1].Target) + assert.Assert(t, is.Len(mounts, 2)) + assert.Check(t, is.Equal("/toadd", mounts[0].Target)) + assert.Check(t, is.Equal("/tokeep", mounts[1].Target)) } func TestUpdateMountsWithDuplicateMounts(t *testing.T) { @@ -228,10 +228,10 @@ func TestUpdateMountsWithDuplicateMounts(t *testing.T) { } updateMounts(flags, &mounts) - require.Len(t, mounts, 3) - assert.Equal(t, "/tokeep1", mounts[0].Target) - assert.Equal(t, "/tokeep2", mounts[1].Target) - assert.Equal(t, "/toadd", mounts[2].Target) + assert.Assert(t, is.Len(mounts, 3)) + assert.Check(t, is.Equal("/tokeep1", mounts[0].Target)) + assert.Check(t, is.Equal("/tokeep2", mounts[1].Target)) + assert.Check(t, is.Equal("/toadd", mounts[2].Target)) } func TestUpdatePorts(t *testing.T) { @@ -245,13 +245,13 @@ func TestUpdatePorts(t *testing.T) { } err := updatePorts(flags, &portConfigs) - assert.NoError(t, err) - require.Len(t, portConfigs, 2) + assert.Check(t, err) + assert.Assert(t, is.Len(portConfigs, 2)) // Do a sort to have the order (might have changed by map) targetPorts := []int{int(portConfigs[0].TargetPort), int(portConfigs[1].TargetPort)} sort.Ints(targetPorts) - assert.Equal(t, 555, targetPorts[0]) - assert.Equal(t, 1000, targetPorts[1]) + assert.Check(t, is.Equal(555, targetPorts[0])) + assert.Check(t, is.Equal(1000, targetPorts[1])) } func TestUpdatePortsDuplicate(t *testing.T) { @@ -269,9 +269,9 @@ func TestUpdatePortsDuplicate(t *testing.T) { } err := updatePorts(flags, &portConfigs) - assert.NoError(t, err) - require.Len(t, portConfigs, 1) - assert.Equal(t, uint32(80), portConfigs[0].TargetPort) + assert.Check(t, err) + assert.Assert(t, is.Len(portConfigs, 1)) + assert.Check(t, is.Equal(uint32(80), portConfigs[0].TargetPort)) } func TestUpdateHealthcheckTable(t *testing.T) { @@ -345,9 +345,9 @@ func TestUpdateHealthcheckTable(t *testing.T) { } err := updateHealthcheck(flags, cspec) if c.err != "" { - assert.EqualError(t, err, c.err) + assert.Check(t, is.Error(err, c.err)) } else { - assert.NoError(t, err) + assert.Check(t, err) if !reflect.DeepEqual(cspec.Healthcheck, c.expected) { t.Errorf("incorrect result for test %d, expected health config:\n\t%#v\ngot:\n\t%#v", i, c.expected, cspec.Healthcheck) } @@ -370,8 +370,8 @@ func TestUpdateHosts(t *testing.T) { expected := []string{"1.2.3.4 example.com", "4.3.2.1 example.org", "2001:db8:abc8::1 ipv6.net"} err := updateHosts(flags, &hosts) - assert.NoError(t, err) - assert.Equal(t, expected, hosts) + assert.Check(t, err) + assert.Check(t, is.DeepEqual(expected, hosts)) } func TestUpdateHostsPreservesOrder(t *testing.T) { @@ -382,8 +382,8 @@ func TestUpdateHostsPreservesOrder(t *testing.T) { hosts := []string{} err := updateHosts(flags, &hosts) - assert.NoError(t, err) - assert.Equal(t, []string{"127.0.0.2 foobar", "127.0.0.1 foobar", "127.0.0.3 foobar"}, hosts) + assert.Check(t, err) + assert.Check(t, is.DeepEqual([]string{"127.0.0.2 foobar", "127.0.0.1 foobar", "127.0.0.3 foobar"}, hosts)) } func TestUpdatePortsRmWithProtocol(t *testing.T) { @@ -404,10 +404,10 @@ func TestUpdatePortsRmWithProtocol(t *testing.T) { } err := updatePorts(flags, &portConfigs) - assert.NoError(t, err) - require.Len(t, portConfigs, 2) - assert.Equal(t, uint32(81), portConfigs[0].TargetPort) - assert.Equal(t, uint32(82), portConfigs[1].TargetPort) + assert.Check(t, err) + assert.Assert(t, is.Len(portConfigs, 2)) + assert.Check(t, is.Equal(uint32(81), portConfigs[0].TargetPort)) + assert.Check(t, is.Equal(uint32(82), portConfigs[1].TargetPort)) } type secretAPIClientMock struct { @@ -461,11 +461,11 @@ func TestUpdateSecretUpdateInPlace(t *testing.T) { updatedSecrets, err := getUpdatedSecrets(apiClient, flags, secrets) - assert.NoError(t, err) - require.Len(t, updatedSecrets, 1) - assert.Equal(t, "tn9qiblgnuuut11eufquw5dev", updatedSecrets[0].SecretID) - assert.Equal(t, "foo", updatedSecrets[0].SecretName) - assert.Equal(t, "foo2", updatedSecrets[0].File.Name) + assert.Check(t, err) + assert.Assert(t, is.Len(updatedSecrets, 1)) + assert.Check(t, is.Equal("tn9qiblgnuuut11eufquw5dev", updatedSecrets[0].SecretID)) + assert.Check(t, is.Equal("foo", updatedSecrets[0].SecretName)) + assert.Check(t, is.Equal("foo2", updatedSecrets[0].File.Name)) } func TestUpdateReadOnly(t *testing.T) { @@ -480,18 +480,18 @@ func TestUpdateReadOnly(t *testing.T) { flags := newUpdateCommand(nil).Flags() flags.Set("read-only", "true") updateService(nil, nil, flags, spec) - assert.True(t, cspec.ReadOnly) + assert.Check(t, cspec.ReadOnly) // Update without --read-only, no change flags = newUpdateCommand(nil).Flags() updateService(nil, nil, flags, spec) - assert.True(t, cspec.ReadOnly) + assert.Check(t, cspec.ReadOnly) // Update with --read-only=false, changed to false flags = newUpdateCommand(nil).Flags() flags.Set("read-only", "false") updateService(nil, nil, flags, spec) - assert.False(t, cspec.ReadOnly) + assert.Check(t, !cspec.ReadOnly) } func TestUpdateStopSignal(t *testing.T) { @@ -506,74 +506,74 @@ func TestUpdateStopSignal(t *testing.T) { flags := newUpdateCommand(nil).Flags() flags.Set("stop-signal", "SIGUSR1") updateService(nil, nil, flags, spec) - assert.Equal(t, "SIGUSR1", cspec.StopSignal) + assert.Check(t, is.Equal("SIGUSR1", cspec.StopSignal)) // Update without --stop-signal, no change flags = newUpdateCommand(nil).Flags() updateService(nil, nil, flags, spec) - assert.Equal(t, "SIGUSR1", cspec.StopSignal) + assert.Check(t, is.Equal("SIGUSR1", cspec.StopSignal)) // Update with --stop-signal=SIGWINCH flags = newUpdateCommand(nil).Flags() flags.Set("stop-signal", "SIGWINCH") updateService(nil, nil, flags, spec) - assert.Equal(t, "SIGWINCH", cspec.StopSignal) + assert.Check(t, is.Equal("SIGWINCH", cspec.StopSignal)) } func TestUpdateIsolationValid(t *testing.T) { flags := newUpdateCommand(nil).Flags() err := flags.Set("isolation", "process") - require.NoError(t, err) + assert.NilError(t, err) spec := swarm.ServiceSpec{ TaskTemplate: swarm.TaskSpec{ ContainerSpec: &swarm.ContainerSpec{}, }, } err = updateService(context.Background(), nil, flags, &spec) - require.NoError(t, err) - assert.Equal(t, container.IsolationProcess, spec.TaskTemplate.ContainerSpec.Isolation) + assert.NilError(t, err) + assert.Check(t, is.Equal(container.IsolationProcess, spec.TaskTemplate.ContainerSpec.Isolation)) } func TestUpdateIsolationInvalid(t *testing.T) { // validation depends on daemon os / version so validation should be done on the daemon side flags := newUpdateCommand(nil).Flags() err := flags.Set("isolation", "test") - require.NoError(t, err) + assert.NilError(t, err) spec := swarm.ServiceSpec{ TaskTemplate: swarm.TaskSpec{ ContainerSpec: &swarm.ContainerSpec{}, }, } err = updateService(context.Background(), nil, flags, &spec) - require.NoError(t, err) - assert.Equal(t, container.Isolation("test"), spec.TaskTemplate.ContainerSpec.Isolation) + assert.NilError(t, err) + assert.Check(t, is.Equal(container.Isolation("test"), spec.TaskTemplate.ContainerSpec.Isolation)) } func TestAddGenericResources(t *testing.T) { task := &swarm.TaskSpec{} flags := newUpdateCommand(nil).Flags() - assert.Nil(t, addGenericResources(flags, task)) + assert.Check(t, addGenericResources(flags, task)) flags.Set(flagGenericResourcesAdd, "foo=1") - assert.NoError(t, addGenericResources(flags, task)) - assert.Len(t, task.Resources.Reservations.GenericResources, 1) + assert.Check(t, addGenericResources(flags, task)) + assert.Check(t, is.Len(task.Resources.Reservations.GenericResources, 1)) // Checks that foo isn't added a 2nd time flags = newUpdateCommand(nil).Flags() flags.Set(flagGenericResourcesAdd, "bar=1") - assert.NoError(t, addGenericResources(flags, task)) - assert.Len(t, task.Resources.Reservations.GenericResources, 2) + assert.Check(t, addGenericResources(flags, task)) + assert.Check(t, is.Len(task.Resources.Reservations.GenericResources, 2)) } func TestRemoveGenericResources(t *testing.T) { task := &swarm.TaskSpec{} flags := newUpdateCommand(nil).Flags() - assert.Nil(t, removeGenericResources(flags, task)) + assert.Check(t, removeGenericResources(flags, task)) flags.Set(flagGenericResourcesRemove, "foo") - assert.Error(t, removeGenericResources(flags, task)) + assert.Check(t, is.ErrorContains(removeGenericResources(flags, task), "")) flags = newUpdateCommand(nil).Flags() flags.Set(flagGenericResourcesAdd, "foo=1") @@ -584,8 +584,8 @@ func TestRemoveGenericResources(t *testing.T) { flags = newUpdateCommand(nil).Flags() flags.Set(flagGenericResourcesRemove, "foo") - assert.NoError(t, removeGenericResources(flags, task)) - assert.Len(t, task.Resources.Reservations.GenericResources, 1) + assert.Check(t, removeGenericResources(flags, task)) + assert.Check(t, is.Len(task.Resources.Reservations.GenericResources, 1)) } func TestUpdateNetworks(t *testing.T) { @@ -618,38 +618,38 @@ func TestUpdateNetworks(t *testing.T) { flags := newUpdateCommand(nil).Flags() err := flags.Set(flagNetworkAdd, "aaa-network") - require.NoError(t, err) + assert.NilError(t, err) err = updateService(ctx, client, flags, &svc) - require.NoError(t, err) - assert.Equal(t, []swarm.NetworkAttachmentConfig{{Target: "id555"}, {Target: "id999"}}, svc.TaskTemplate.Networks) + assert.NilError(t, err) + assert.Check(t, is.DeepEqual([]swarm.NetworkAttachmentConfig{{Target: "id555"}, {Target: "id999"}}, svc.TaskTemplate.Networks)) flags = newUpdateCommand(nil).Flags() err = flags.Set(flagNetworkAdd, "aaa-network") - require.NoError(t, err) + assert.NilError(t, err) err = updateService(ctx, client, flags, &svc) - assert.EqualError(t, err, "service is already attached to network aaa-network") - assert.Equal(t, []swarm.NetworkAttachmentConfig{{Target: "id555"}, {Target: "id999"}}, svc.TaskTemplate.Networks) + assert.Check(t, is.Error(err, "service is already attached to network aaa-network")) + assert.Check(t, is.DeepEqual([]swarm.NetworkAttachmentConfig{{Target: "id555"}, {Target: "id999"}}, svc.TaskTemplate.Networks)) flags = newUpdateCommand(nil).Flags() err = flags.Set(flagNetworkAdd, "id555") - require.NoError(t, err) + assert.NilError(t, err) err = updateService(ctx, client, flags, &svc) - assert.EqualError(t, err, "service is already attached to network id555") - assert.Equal(t, []swarm.NetworkAttachmentConfig{{Target: "id555"}, {Target: "id999"}}, svc.TaskTemplate.Networks) + assert.Check(t, is.Error(err, "service is already attached to network id555")) + assert.Check(t, is.DeepEqual([]swarm.NetworkAttachmentConfig{{Target: "id555"}, {Target: "id999"}}, svc.TaskTemplate.Networks)) flags = newUpdateCommand(nil).Flags() err = flags.Set(flagNetworkRemove, "id999") - require.NoError(t, err) + assert.NilError(t, err) err = updateService(ctx, client, flags, &svc) - assert.NoError(t, err) - assert.Equal(t, []swarm.NetworkAttachmentConfig{{Target: "id555"}}, svc.TaskTemplate.Networks) + assert.Check(t, err) + assert.Check(t, is.DeepEqual([]swarm.NetworkAttachmentConfig{{Target: "id555"}}, svc.TaskTemplate.Networks)) flags = newUpdateCommand(nil).Flags() err = flags.Set(flagNetworkAdd, "mmm-network") - require.NoError(t, err) + assert.NilError(t, err) err = flags.Set(flagNetworkRemove, "aaa-network") - require.NoError(t, err) + assert.NilError(t, err) err = updateService(ctx, client, flags, &svc) - assert.NoError(t, err) - assert.Equal(t, []swarm.NetworkAttachmentConfig{{Target: "id999"}}, svc.TaskTemplate.Networks) + assert.Check(t, err) + assert.Check(t, is.DeepEqual([]swarm.NetworkAttachmentConfig{{Target: "id999"}}, svc.TaskTemplate.Networks)) } diff --git a/cli/command/stack/kubernetes/loader_test.go b/cli/command/stack/kubernetes/loader_test.go index a96e66d47b..84a53da6fe 100644 --- a/cli/command/stack/kubernetes/loader_test.go +++ b/cli/command/stack/kubernetes/loader_test.go @@ -5,7 +5,8 @@ import ( composetypes "github.com/docker/cli/cli/compose/types" apiv1beta1 "github.com/docker/cli/kubernetes/compose/v1beta1" - "github.com/stretchr/testify/require" + "github.com/google/go-cmp/cmp" + "github.com/gotestyourself/gotestyourself/assert" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) @@ -24,13 +25,13 @@ func TestLoadStack(t *testing.T) { }, }, }) - require.NoError(t, err) - require.Equal(t, &apiv1beta1.Stack{ + assert.NilError(t, err) + assert.DeepEqual(t, &apiv1beta1.Stack{ ObjectMeta: metav1.ObjectMeta{ Name: "foo", }, Spec: apiv1beta1.StackSpec{ - ComposeFile: string(`version: "3.1" + ComposeFile: `version: "3.1" services: bar: image: bar @@ -40,7 +41,15 @@ networks: {} volumes: {} secrets: {} configs: {} -`), +`, }, - }, s) + }, s, cmpKubeAPITime) } + +// TODO: this can be removed when k8s.io/apimachinery is updated to > 1.9.0 +var cmpKubeAPITime = cmp.Comparer(func(x, y *metav1.Time) bool { + if x == nil || y == nil { + return x == y + } + return x.Time.Equal(y.Time) +}) diff --git a/cli/command/stack/list_test.go b/cli/command/stack/list_test.go index 90d32e0f99..add6667ecd 100644 --- a/cli/command/stack/list_test.go +++ b/cli/command/stack/list_test.go @@ -10,9 +10,9 @@ import ( "github.com/docker/cli/internal/test/testutil" "github.com/docker/docker/api/types" "github.com/docker/docker/api/types/swarm" + "github.com/gotestyourself/gotestyourself/assert" "github.com/gotestyourself/gotestyourself/golden" "github.com/pkg/errors" - "github.com/stretchr/testify/assert" ) func TestListErrors(t *testing.T) { @@ -72,7 +72,7 @@ func TestListWithFormat(t *testing.T) { }) cmd := newListCommand(cli) cmd.Flags().Set("format", "{{ .Name }}") - assert.NoError(t, cmd.Execute()) + assert.Check(t, cmd.Execute()) golden.Assert(t, cli.OutBuffer().String(), "stack-list-with-format.golden") } @@ -88,7 +88,7 @@ func TestListWithoutFormat(t *testing.T) { }, }) cmd := newListCommand(cli) - assert.NoError(t, cmd.Execute()) + assert.Check(t, cmd.Execute()) golden.Assert(t, cli.OutBuffer().String(), "stack-list-without-format.golden") } @@ -141,7 +141,7 @@ func TestListOrder(t *testing.T) { }, }) cmd := newListCommand(cli) - assert.NoError(t, cmd.Execute()) + assert.Check(t, cmd.Execute()) golden.Assert(t, cli.OutBuffer().String(), uc.golden) } } diff --git a/cli/command/stack/loader/loader_test.go b/cli/command/stack/loader/loader_test.go index 29ccd4e7f5..c027371dda 100644 --- a/cli/command/stack/loader/loader_test.go +++ b/cli/command/stack/loader/loader_test.go @@ -6,9 +6,9 @@ import ( "strings" "testing" + "github.com/gotestyourself/gotestyourself/assert" + is "github.com/gotestyourself/gotestyourself/assert/cmp" "github.com/gotestyourself/gotestyourself/fs" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" ) func TestGetConfigDetails(t *testing.T) { @@ -22,11 +22,11 @@ services: defer file.Remove() details, err := getConfigDetails([]string{file.Path()}, nil) - require.NoError(t, err) - assert.Equal(t, filepath.Dir(file.Path()), details.WorkingDir) - require.Len(t, details.ConfigFiles, 1) - assert.Equal(t, "3.0", details.ConfigFiles[0].Config["version"]) - assert.Len(t, details.Environment, len(os.Environ())) + assert.NilError(t, err) + assert.Check(t, is.Equal(filepath.Dir(file.Path()), details.WorkingDir)) + assert.Assert(t, is.Len(details.ConfigFiles, 1)) + assert.Check(t, is.Equal("3.0", details.ConfigFiles[0].Config["version"])) + assert.Check(t, is.Len(details.Environment, len(os.Environ()))) } func TestGetConfigDetailsStdin(t *testing.T) { @@ -37,11 +37,11 @@ services: image: alpine:3.5 ` details, err := getConfigDetails([]string{"-"}, strings.NewReader(content)) - require.NoError(t, err) + assert.NilError(t, err) cwd, err := os.Getwd() - require.NoError(t, err) - assert.Equal(t, cwd, details.WorkingDir) - require.Len(t, details.ConfigFiles, 1) - assert.Equal(t, "3.0", details.ConfigFiles[0].Config["version"]) - assert.Len(t, details.Environment, len(os.Environ())) + assert.NilError(t, err) + assert.Check(t, is.Equal(cwd, details.WorkingDir)) + assert.Assert(t, is.Len(details.ConfigFiles, 1)) + assert.Check(t, is.Equal("3.0", details.ConfigFiles[0].Config["version"])) + assert.Check(t, is.Len(details.Environment, len(os.Environ()))) } diff --git a/cli/command/stack/ps_test.go b/cli/command/stack/ps_test.go index fb7055f09c..36813ca501 100644 --- a/cli/command/stack/ps_test.go +++ b/cli/command/stack/ps_test.go @@ -12,9 +12,10 @@ import ( "github.com/docker/cli/internal/test/testutil" "github.com/docker/docker/api/types" "github.com/docker/docker/api/types/swarm" + "github.com/gotestyourself/gotestyourself/assert" + is "github.com/gotestyourself/gotestyourself/assert/cmp" "github.com/gotestyourself/gotestyourself/golden" "github.com/pkg/errors" - "github.com/stretchr/testify/assert" ) func TestStackPsErrors(t *testing.T) { @@ -61,9 +62,8 @@ func TestStackPsEmptyStack(t *testing.T) { cmd.SetArgs([]string{"foo"}) cmd.SetOutput(ioutil.Discard) - assert.Error(t, cmd.Execute()) - assert.EqualError(t, cmd.Execute(), "nothing found in stack: foo") - assert.Equal(t, "", fakeCli.OutBuffer().String()) + assert.Check(t, is.Error(cmd.Execute(), "nothing found in stack: foo")) + assert.Check(t, is.Equal("", fakeCli.OutBuffer().String())) } func TestStackPsWithQuietOption(t *testing.T) { @@ -75,7 +75,7 @@ func TestStackPsWithQuietOption(t *testing.T) { cmd := newPsCommand(cli) cmd.SetArgs([]string{"foo"}) cmd.Flags().Set("quiet", "true") - assert.NoError(t, cmd.Execute()) + assert.Check(t, cmd.Execute()) golden.Assert(t, cli.OutBuffer().String(), "stack-ps-with-quiet-option.golden") } @@ -90,7 +90,7 @@ func TestStackPsWithNoTruncOption(t *testing.T) { cmd.SetArgs([]string{"foo"}) cmd.Flags().Set("no-trunc", "true") cmd.Flags().Set("format", "{{ .ID }}") - assert.NoError(t, cmd.Execute()) + assert.Check(t, cmd.Execute()) golden.Assert(t, cli.OutBuffer().String(), "stack-ps-with-no-trunc-option.golden") } @@ -109,7 +109,7 @@ func TestStackPsWithNoResolveOption(t *testing.T) { cmd.SetArgs([]string{"foo"}) cmd.Flags().Set("no-resolve", "true") cmd.Flags().Set("format", "{{ .Node }}") - assert.NoError(t, cmd.Execute()) + assert.Check(t, cmd.Execute()) golden.Assert(t, cli.OutBuffer().String(), "stack-ps-with-no-resolve-option.golden") } @@ -122,7 +122,7 @@ func TestStackPsWithFormat(t *testing.T) { cmd := newPsCommand(cli) cmd.SetArgs([]string{"foo"}) cmd.Flags().Set("format", "{{ .Name }}") - assert.NoError(t, cmd.Execute()) + assert.Check(t, cmd.Execute()) golden.Assert(t, cli.OutBuffer().String(), "stack-ps-with-format.golden") } @@ -137,7 +137,7 @@ func TestStackPsWithConfigFormat(t *testing.T) { }) cmd := newPsCommand(cli) cmd.SetArgs([]string{"foo"}) - assert.NoError(t, cmd.Execute()) + assert.Check(t, cmd.Execute()) golden.Assert(t, cli.OutBuffer().String(), "stack-ps-with-config-format.golden") } @@ -159,6 +159,6 @@ func TestStackPsWithoutFormat(t *testing.T) { }) cmd := newPsCommand(cli) cmd.SetArgs([]string{"foo"}) - assert.NoError(t, cmd.Execute()) + assert.Check(t, cmd.Execute()) golden.Assert(t, cli.OutBuffer().String(), "stack-ps-without-format.golden") } diff --git a/cli/command/stack/remove_test.go b/cli/command/stack/remove_test.go index 0ce5cdacfc..7770d47145 100644 --- a/cli/command/stack/remove_test.go +++ b/cli/command/stack/remove_test.go @@ -7,7 +7,8 @@ import ( "testing" "github.com/docker/cli/internal/test" - "github.com/stretchr/testify/assert" + "github.com/gotestyourself/gotestyourself/assert" + is "github.com/gotestyourself/gotestyourself/assert/cmp" ) func fakeClientForRemoveStackTest(version string) *fakeClient { @@ -45,11 +46,11 @@ func TestRemoveStackVersion124DoesNotRemoveConfigsOrSecrets(t *testing.T) { cmd := newRemoveCommand(test.NewFakeCli(client)) cmd.SetArgs([]string{"foo", "bar"}) - assert.NoError(t, cmd.Execute()) - assert.Equal(t, buildObjectIDs(client.services), client.removedServices) - assert.Equal(t, buildObjectIDs(client.networks), client.removedNetworks) - assert.Nil(t, client.removedSecrets) - assert.Nil(t, client.removedConfigs) + assert.Check(t, cmd.Execute()) + assert.Check(t, is.DeepEqual(buildObjectIDs(client.services), client.removedServices)) + assert.Check(t, is.DeepEqual(buildObjectIDs(client.networks), client.removedNetworks)) + assert.Check(t, is.Len(client.removedSecrets, 0)) + assert.Check(t, is.Len(client.removedConfigs, 0)) } func TestRemoveStackVersion125DoesNotRemoveConfigs(t *testing.T) { @@ -57,11 +58,11 @@ func TestRemoveStackVersion125DoesNotRemoveConfigs(t *testing.T) { cmd := newRemoveCommand(test.NewFakeCli(client)) cmd.SetArgs([]string{"foo", "bar"}) - assert.NoError(t, cmd.Execute()) - assert.Equal(t, buildObjectIDs(client.services), client.removedServices) - assert.Equal(t, buildObjectIDs(client.networks), client.removedNetworks) - assert.Equal(t, buildObjectIDs(client.secrets), client.removedSecrets) - assert.Nil(t, client.removedConfigs) + assert.Check(t, cmd.Execute()) + assert.Check(t, is.DeepEqual(buildObjectIDs(client.services), client.removedServices)) + assert.Check(t, is.DeepEqual(buildObjectIDs(client.networks), client.removedNetworks)) + assert.Check(t, is.DeepEqual(buildObjectIDs(client.secrets), client.removedSecrets)) + assert.Check(t, is.Len(client.removedConfigs, 0)) } func TestRemoveStackVersion130RemovesEverything(t *testing.T) { @@ -69,11 +70,11 @@ func TestRemoveStackVersion130RemovesEverything(t *testing.T) { cmd := newRemoveCommand(test.NewFakeCli(client)) cmd.SetArgs([]string{"foo", "bar"}) - assert.NoError(t, cmd.Execute()) - assert.Equal(t, buildObjectIDs(client.services), client.removedServices) - assert.Equal(t, buildObjectIDs(client.networks), client.removedNetworks) - assert.Equal(t, buildObjectIDs(client.secrets), client.removedSecrets) - assert.Equal(t, buildObjectIDs(client.configs), client.removedConfigs) + assert.Check(t, cmd.Execute()) + assert.Check(t, is.DeepEqual(buildObjectIDs(client.services), client.removedServices)) + assert.Check(t, is.DeepEqual(buildObjectIDs(client.networks), client.removedNetworks)) + assert.Check(t, is.DeepEqual(buildObjectIDs(client.secrets), client.removedSecrets)) + assert.Check(t, is.DeepEqual(buildObjectIDs(client.configs), client.removedConfigs)) } func TestRemoveStackSkipEmpty(t *testing.T) { @@ -100,19 +101,19 @@ func TestRemoveStackSkipEmpty(t *testing.T) { cmd := newRemoveCommand(fakeCli) cmd.SetArgs([]string{"foo", "bar"}) - assert.NoError(t, cmd.Execute()) + assert.Check(t, cmd.Execute()) expectedList := []string{"Removing service bar_service1", "Removing service bar_service2", "Removing secret bar_secret1", "Removing config bar_config1", "Removing network bar_network1\n", } - assert.Equal(t, strings.Join(expectedList, "\n"), fakeCli.OutBuffer().String()) - assert.Contains(t, fakeCli.ErrBuffer().String(), "Nothing found in stack: foo\n") - assert.Equal(t, allServiceIDs, fakeClient.removedServices) - assert.Equal(t, allNetworkIDs, fakeClient.removedNetworks) - assert.Equal(t, allSecretIDs, fakeClient.removedSecrets) - assert.Equal(t, allConfigIDs, fakeClient.removedConfigs) + assert.Check(t, is.Equal(strings.Join(expectedList, "\n"), fakeCli.OutBuffer().String())) + assert.Check(t, is.Contains(fakeCli.ErrBuffer().String(), "Nothing found in stack: foo\n")) + assert.Check(t, is.DeepEqual(allServiceIDs, fakeClient.removedServices)) + assert.Check(t, is.DeepEqual(allNetworkIDs, fakeClient.removedNetworks)) + assert.Check(t, is.DeepEqual(allSecretIDs, fakeClient.removedSecrets)) + assert.Check(t, is.DeepEqual(allConfigIDs, fakeClient.removedConfigs)) } func TestRemoveContinueAfterError(t *testing.T) { @@ -149,9 +150,9 @@ func TestRemoveContinueAfterError(t *testing.T) { cmd.SetOutput(ioutil.Discard) cmd.SetArgs([]string{"foo", "bar"}) - assert.EqualError(t, cmd.Execute(), "Failed to remove some resources from stack: foo") - assert.Equal(t, allServiceIDs, removedServices) - assert.Equal(t, allNetworkIDs, cli.removedNetworks) - assert.Equal(t, allSecretIDs, cli.removedSecrets) - assert.Equal(t, allConfigIDs, cli.removedConfigs) + assert.Check(t, is.Error(cmd.Execute(), "Failed to remove some resources from stack: foo")) + assert.Check(t, is.DeepEqual(allServiceIDs, removedServices)) + assert.Check(t, is.DeepEqual(allNetworkIDs, cli.removedNetworks)) + assert.Check(t, is.DeepEqual(allSecretIDs, cli.removedSecrets)) + assert.Check(t, is.DeepEqual(allConfigIDs, cli.removedConfigs)) } diff --git a/cli/command/stack/services_test.go b/cli/command/stack/services_test.go index 2f6d6e0e00..c1d5f99946 100644 --- a/cli/command/stack/services_test.go +++ b/cli/command/stack/services_test.go @@ -11,9 +11,10 @@ import ( "github.com/docker/cli/internal/test/testutil" "github.com/docker/docker/api/types" "github.com/docker/docker/api/types/swarm" + "github.com/gotestyourself/gotestyourself/assert" + is "github.com/gotestyourself/gotestyourself/assert/cmp" "github.com/gotestyourself/gotestyourself/golden" "github.com/pkg/errors" - "github.com/stretchr/testify/assert" ) func TestStackServicesErrors(t *testing.T) { @@ -88,9 +89,9 @@ func TestStackServicesEmptyServiceList(t *testing.T) { }) cmd := newServicesCommand(fakeCli) cmd.SetArgs([]string{"foo"}) - assert.NoError(t, cmd.Execute()) - assert.Equal(t, "", fakeCli.OutBuffer().String()) - assert.Equal(t, "Nothing found in stack: foo\n", fakeCli.ErrBuffer().String()) + assert.Check(t, cmd.Execute()) + assert.Check(t, is.Equal("", fakeCli.OutBuffer().String())) + assert.Check(t, is.Equal("Nothing found in stack: foo\n", fakeCli.ErrBuffer().String())) } func TestStackServicesWithQuietOption(t *testing.T) { @@ -102,7 +103,7 @@ func TestStackServicesWithQuietOption(t *testing.T) { cmd := newServicesCommand(cli) cmd.Flags().Set("quiet", "true") cmd.SetArgs([]string{"foo"}) - assert.NoError(t, cmd.Execute()) + assert.Check(t, cmd.Execute()) golden.Assert(t, cli.OutBuffer().String(), "stack-services-with-quiet-option.golden") } @@ -117,7 +118,7 @@ func TestStackServicesWithFormat(t *testing.T) { cmd := newServicesCommand(cli) cmd.SetArgs([]string{"foo"}) cmd.Flags().Set("format", "{{ .Name }}") - assert.NoError(t, cmd.Execute()) + assert.Check(t, cmd.Execute()) golden.Assert(t, cli.OutBuffer().String(), "stack-services-with-format.golden") } @@ -134,7 +135,7 @@ func TestStackServicesWithConfigFormat(t *testing.T) { }) cmd := newServicesCommand(cli) cmd.SetArgs([]string{"foo"}) - assert.NoError(t, cmd.Execute()) + assert.Check(t, cmd.Execute()) golden.Assert(t, cli.OutBuffer().String(), "stack-services-with-config-format.golden") } @@ -157,6 +158,6 @@ func TestStackServicesWithoutFormat(t *testing.T) { }) cmd := newServicesCommand(cli) cmd.SetArgs([]string{"foo"}) - assert.NoError(t, cmd.Execute()) + assert.Check(t, cmd.Execute()) golden.Assert(t, cli.OutBuffer().String(), "stack-services-without-format.golden") } diff --git a/cli/command/stack/swarm/deploy_bundlefile_test.go b/cli/command/stack/swarm/deploy_bundlefile_test.go index c259c60d2a..cc1535fc9b 100644 --- a/cli/command/stack/swarm/deploy_bundlefile_test.go +++ b/cli/command/stack/swarm/deploy_bundlefile_test.go @@ -2,38 +2,39 @@ package swarm import ( "bytes" - "fmt" "path/filepath" "testing" - "github.com/stretchr/testify/assert" + "github.com/gotestyourself/gotestyourself/assert" + is "github.com/gotestyourself/gotestyourself/assert/cmp" ) func TestLoadBundlefileErrors(t *testing.T) { testCases := []struct { namespace string path string - expectedError error + expectedError string }{ { namespace: "namespace_foo", - expectedError: fmt.Errorf("Bundle %s.dab not found", "namespace_foo"), + expectedError: "Bundle namespace_foo.dab not found", }, { namespace: "namespace_foo", path: "invalid_path", - expectedError: fmt.Errorf("Bundle %s not found", "invalid_path"), - }, - { - namespace: "namespace_foo", - path: filepath.Join("testdata", "bundlefile_with_invalid_syntax"), - expectedError: fmt.Errorf("Error reading"), + expectedError: "Bundle invalid_path not found", }, + // FIXME: this test never working, testdata file is missing from repo + //{ + // namespace: "namespace_foo", + // path: string(golden.Get(t, "bundlefile_with_invalid_syntax")), + // expectedError: "Error reading", + //}, } for _, tc := range testCases { _, err := loadBundlefile(&bytes.Buffer{}, tc.namespace, tc.path) - assert.Error(t, err, tc.expectedError) + assert.ErrorContains(t, err, tc.expectedError) } } @@ -44,6 +45,6 @@ func TestLoadBundlefile(t *testing.T) { path := filepath.Join("testdata", "bundlefile_with_two_services.dab") bundleFile, err := loadBundlefile(buf, namespace, path) - assert.NoError(t, err) - assert.Equal(t, len(bundleFile.Services), 2) + assert.Check(t, err) + assert.Check(t, is.Equal(len(bundleFile.Services), 2)) } diff --git a/cli/command/stack/swarm/deploy_composefile_test.go b/cli/command/stack/swarm/deploy_composefile_test.go index 7f3133148c..fc5c93b3b5 100644 --- a/cli/command/stack/swarm/deploy_composefile_test.go +++ b/cli/command/stack/swarm/deploy_composefile_test.go @@ -6,8 +6,8 @@ import ( "github.com/docker/cli/internal/test/network" "github.com/docker/cli/internal/test/testutil" "github.com/docker/docker/api/types" + "github.com/gotestyourself/gotestyourself/assert" "github.com/pkg/errors" - "github.com/stretchr/testify/assert" "golang.org/x/net/context" ) @@ -57,7 +57,7 @@ func TestValidateExternalNetworks(t *testing.T) { networks := []string{testcase.network} err := validateExternalNetworks(context.Background(), fakeClient, networks) if testcase.expectedMsg == "" { - assert.NoError(t, err) + assert.Check(t, err) } else { testutil.ErrorContains(t, err, testcase.expectedMsg) } diff --git a/cli/command/stack/swarm/deploy_test.go b/cli/command/stack/swarm/deploy_test.go index 73c91a0392..15199c3731 100644 --- a/cli/command/stack/swarm/deploy_test.go +++ b/cli/command/stack/swarm/deploy_test.go @@ -7,7 +7,8 @@ import ( "github.com/docker/cli/internal/test" "github.com/docker/docker/api/types" "github.com/docker/docker/api/types/swarm" - "github.com/stretchr/testify/assert" + "github.com/gotestyourself/gotestyourself/assert" + is "github.com/gotestyourself/gotestyourself/assert/cmp" "golang.org/x/net/context" ) @@ -22,7 +23,7 @@ func TestPruneServices(t *testing.T) { dockerCli := test.NewFakeCli(client) pruneServices(ctx, dockerCli, namespace, services) - assert.Equal(t, buildObjectIDs([]string{objectName("foo", "remove")}), client.removedServices) + assert.Check(t, is.DeepEqual(buildObjectIDs([]string{objectName("foo", "remove")}), client.removedServices)) } // TestServiceUpdateResolveImageChanged tests that the service's @@ -93,9 +94,9 @@ func TestServiceUpdateResolveImageChanged(t *testing.T) { }, } err := deployServices(ctx, client, spec, namespace, false, ResolveImageChanged) - assert.NoError(t, err) - assert.Equal(t, testcase.expectedQueryRegistry, receivedOptions.QueryRegistry) - assert.Equal(t, testcase.expectedImage, receivedService.TaskTemplate.ContainerSpec.Image) + assert.Check(t, err) + assert.Check(t, is.Equal(testcase.expectedQueryRegistry, receivedOptions.QueryRegistry)) + assert.Check(t, is.Equal(testcase.expectedImage, receivedService.TaskTemplate.ContainerSpec.Image)) receivedService = swarm.ServiceSpec{} receivedOptions = types.ServiceUpdateOptions{} diff --git a/cli/command/swarm/ca_test.go b/cli/command/swarm/ca_test.go index cb2668293a..a3ecb5430f 100644 --- a/cli/command/swarm/ca_test.go +++ b/cli/command/swarm/ca_test.go @@ -10,8 +10,8 @@ import ( "github.com/docker/cli/internal/test" "github.com/docker/cli/internal/test/testutil" "github.com/docker/docker/api/types/swarm" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" + "github.com/gotestyourself/gotestyourself/assert" + is "github.com/gotestyourself/gotestyourself/assert/cmp" ) func swarmSpecWithFullCAConfig() *swarm.Spec { @@ -35,13 +35,13 @@ func swarmSpecWithFullCAConfig() *swarm.Spec { func TestDisplayTrustRootNoRoot(t *testing.T) { buffer := new(bytes.Buffer) err := displayTrustRoot(buffer, swarm.Swarm{}) - assert.EqualError(t, err, "No CA information available") + assert.Check(t, is.Error(err, "No CA information available")) } func TestDisplayTrustRootInvalidFlags(t *testing.T) { // we need an actual PEMfile to test tmpfile, err := ioutil.TempFile("", "pemfile") - assert.NoError(t, err) + assert.Check(t, err) defer os.Remove(tmpfile.Name()) tmpfile.Write([]byte(` -----BEGIN CERTIFICATE----- @@ -95,7 +95,7 @@ PQQDAgNIADBFAiEAqD3Kb2rgsy6NoTk+zEgcUi/aGBCsvQDG3vML1PXN8j0CIBjj }, nil }, })) - assert.NoError(t, cmd.Flags().Parse(args)) + assert.Check(t, cmd.Flags().Parse(args)) cmd.SetOutput(ioutil.Discard) testutil.ErrorContains(t, cmd.Execute(), "flag requires the `--rotate` flag to update the CA") } @@ -109,8 +109,8 @@ func TestDisplayTrustRoot(t *testing.T) { TLSInfo: swarm.TLSInfo{TrustRoot: trustRoot}, }, }) - require.NoError(t, err) - assert.Equal(t, trustRoot+"\n", buffer.String()) + assert.NilError(t, err) + assert.Check(t, is.Equal(trustRoot+"\n", buffer.String())) } func TestUpdateSwarmSpecDefaultRotate(t *testing.T) { @@ -122,7 +122,7 @@ func TestUpdateSwarmSpecDefaultRotate(t *testing.T) { expected.CAConfig.ForceRotate = 2 expected.CAConfig.SigningCACert = "" expected.CAConfig.SigningCAKey = "" - assert.Equal(t, expected, spec) + assert.Check(t, is.DeepEqual(expected, spec)) } func TestUpdateSwarmSpecPartial(t *testing.T) { @@ -134,7 +134,7 @@ func TestUpdateSwarmSpecPartial(t *testing.T) { expected := swarmSpecWithFullCAConfig() expected.CAConfig.SigningCACert = "cacert" - assert.Equal(t, expected, spec) + assert.Check(t, is.DeepEqual(expected, spec)) } func TestUpdateSwarmSpecFullFlags(t *testing.T) { @@ -151,5 +151,5 @@ func TestUpdateSwarmSpecFullFlags(t *testing.T) { expected.CAConfig.SigningCACert = "cacert" expected.CAConfig.SigningCAKey = "cakey" expected.CAConfig.NodeCertExpiry = 3 * time.Minute - assert.Equal(t, expected, spec) + assert.Check(t, is.DeepEqual(expected, spec)) } diff --git a/cli/command/swarm/init_test.go b/cli/command/swarm/init_test.go index 24a1b90717..f7852ed948 100644 --- a/cli/command/swarm/init_test.go +++ b/cli/command/swarm/init_test.go @@ -8,9 +8,10 @@ import ( "github.com/docker/cli/internal/test" "github.com/docker/docker/api/types" "github.com/docker/docker/api/types/swarm" + "github.com/gotestyourself/gotestyourself/assert" + is "github.com/gotestyourself/gotestyourself/assert/cmp" "github.com/gotestyourself/gotestyourself/golden" "github.com/pkg/errors" - "github.com/stretchr/testify/assert" ) func TestSwarmInitErrorOnAPIFailure(t *testing.T) { @@ -74,7 +75,7 @@ func TestSwarmInitErrorOnAPIFailure(t *testing.T) { cmd.Flags().Set(key, value) } cmd.SetOutput(ioutil.Discard) - assert.EqualError(t, cmd.Execute(), tc.expectedError) + assert.Check(t, is.Error(cmd.Execute(), tc.expectedError)) } } @@ -119,7 +120,7 @@ func TestSwarmInit(t *testing.T) { for key, value := range tc.flags { cmd.Flags().Set(key, value) } - assert.NoError(t, cmd.Execute()) + assert.Check(t, cmd.Execute()) golden.Assert(t, cli.OutBuffer().String(), fmt.Sprintf("init-%s.golden", tc.name)) } } diff --git a/cli/command/swarm/join_test.go b/cli/command/swarm/join_test.go index 69546cd8cf..db59b5601a 100644 --- a/cli/command/swarm/join_test.go +++ b/cli/command/swarm/join_test.go @@ -9,8 +9,9 @@ import ( "github.com/docker/cli/internal/test/testutil" "github.com/docker/docker/api/types" "github.com/docker/docker/api/types/swarm" + "github.com/gotestyourself/gotestyourself/assert" + is "github.com/gotestyourself/gotestyourself/assert/cmp" "github.com/pkg/errors" - "github.com/stretchr/testify/assert" ) func TestSwarmJoinErrors(t *testing.T) { @@ -94,7 +95,7 @@ func TestSwarmJoin(t *testing.T) { }) cmd := newJoinCommand(cli) cmd.SetArgs([]string{"remote"}) - assert.NoError(t, cmd.Execute()) - assert.Equal(t, strings.TrimSpace(cli.OutBuffer().String()), tc.expected) + assert.Check(t, cmd.Execute()) + assert.Check(t, is.Equal(strings.TrimSpace(cli.OutBuffer().String()), tc.expected)) } } diff --git a/cli/command/swarm/join_token_test.go b/cli/command/swarm/join_token_test.go index 6ab503113a..0860cd4c7f 100644 --- a/cli/command/swarm/join_token_test.go +++ b/cli/command/swarm/join_token_test.go @@ -12,8 +12,8 @@ import ( // Import builders to get the builder function as package function . "github.com/docker/cli/internal/test/builders" "github.com/docker/cli/internal/test/testutil" + "github.com/gotestyourself/gotestyourself/assert" "github.com/gotestyourself/gotestyourself/golden" - "github.com/stretchr/testify/assert" ) func TestSwarmJoinTokenErrors(t *testing.T) { @@ -206,7 +206,7 @@ func TestSwarmJoinToken(t *testing.T) { for key, value := range tc.flags { cmd.Flags().Set(key, value) } - assert.NoError(t, cmd.Execute()) + assert.Check(t, cmd.Execute()) golden.Assert(t, cli.OutBuffer().String(), fmt.Sprintf("jointoken-%s.golden", tc.name)) } } diff --git a/cli/command/swarm/leave_test.go b/cli/command/swarm/leave_test.go index cd8aeb8297..db33e70d35 100644 --- a/cli/command/swarm/leave_test.go +++ b/cli/command/swarm/leave_test.go @@ -7,8 +7,9 @@ import ( "github.com/docker/cli/internal/test" "github.com/docker/cli/internal/test/testutil" + "github.com/gotestyourself/gotestyourself/assert" + is "github.com/gotestyourself/gotestyourself/assert/cmp" "github.com/pkg/errors" - "github.com/stretchr/testify/assert" ) func TestSwarmLeaveErrors(t *testing.T) { @@ -45,6 +46,6 @@ func TestSwarmLeaveErrors(t *testing.T) { func TestSwarmLeave(t *testing.T) { cli := test.NewFakeCli(&fakeClient{}) cmd := newLeaveCommand(cli) - assert.NoError(t, cmd.Execute()) - assert.Equal(t, "Node left the swarm.", strings.TrimSpace(cli.OutBuffer().String())) + assert.Check(t, cmd.Execute()) + assert.Check(t, is.Equal("Node left the swarm.", strings.TrimSpace(cli.OutBuffer().String()))) } diff --git a/cli/command/swarm/opts_test.go b/cli/command/swarm/opts_test.go index c694cc1bdd..5f31f4cb90 100644 --- a/cli/command/swarm/opts_test.go +++ b/cli/command/swarm/opts_test.go @@ -3,37 +3,38 @@ package swarm import ( "testing" - "github.com/stretchr/testify/assert" + "github.com/gotestyourself/gotestyourself/assert" + is "github.com/gotestyourself/gotestyourself/assert/cmp" ) func TestNodeAddrOptionSetHostAndPort(t *testing.T) { opt := NewNodeAddrOption("old:123") addr := "newhost:5555" - assert.NoError(t, opt.Set(addr)) - assert.Equal(t, addr, opt.Value()) + assert.Check(t, opt.Set(addr)) + assert.Check(t, is.Equal(addr, opt.Value())) } func TestNodeAddrOptionSetHostOnly(t *testing.T) { opt := NewListenAddrOption() - assert.NoError(t, opt.Set("newhost")) - assert.Equal(t, "newhost:2377", opt.Value()) + assert.Check(t, opt.Set("newhost")) + assert.Check(t, is.Equal("newhost:2377", opt.Value())) } func TestNodeAddrOptionSetHostOnlyIPv6(t *testing.T) { opt := NewListenAddrOption() - assert.NoError(t, opt.Set("::1")) - assert.Equal(t, "[::1]:2377", opt.Value()) + assert.Check(t, opt.Set("::1")) + assert.Check(t, is.Equal("[::1]:2377", opt.Value())) } func TestNodeAddrOptionSetPortOnly(t *testing.T) { opt := NewListenAddrOption() - assert.NoError(t, opt.Set(":4545")) - assert.Equal(t, "0.0.0.0:4545", opt.Value()) + assert.Check(t, opt.Set(":4545")) + assert.Check(t, is.Equal("0.0.0.0:4545", opt.Value())) } func TestNodeAddrOptionSetInvalidFormat(t *testing.T) { opt := NewListenAddrOption() - assert.EqualError(t, opt.Set("http://localhost:4545"), "Invalid proto, expected tcp: http://localhost:4545") + assert.Check(t, is.Error(opt.Set("http://localhost:4545"), "Invalid proto, expected tcp: http://localhost:4545")) } func TestExternalCAOptionErrors(t *testing.T) { @@ -64,7 +65,7 @@ func TestExternalCAOptionErrors(t *testing.T) { } for _, tc := range testCases { opt := &ExternalCAOption{} - assert.EqualError(t, opt.Set(tc.externalCA), tc.expectedError) + assert.Check(t, is.Error(opt.Set(tc.externalCA), tc.expectedError)) } } @@ -96,15 +97,15 @@ func TestExternalCAOption(t *testing.T) { } for _, tc := range testCases { opt := &ExternalCAOption{} - assert.NoError(t, opt.Set(tc.externalCA)) - assert.Equal(t, tc.expected, opt.String()) + assert.Check(t, opt.Set(tc.externalCA)) + assert.Check(t, is.Equal(tc.expected, opt.String())) } } func TestExternalCAOptionMultiple(t *testing.T) { opt := &ExternalCAOption{} - assert.NoError(t, opt.Set("protocol=cfssl,url=https://example.com")) - assert.NoError(t, opt.Set("protocol=CFSSL,url=anything")) - assert.Len(t, opt.Value(), 2) - assert.Equal(t, "cfssl: https://example.com, cfssl: anything", opt.String()) + assert.Check(t, opt.Set("protocol=cfssl,url=https://example.com")) + assert.Check(t, opt.Set("protocol=CFSSL,url=anything")) + assert.Check(t, is.Len(opt.Value(), 2)) + assert.Check(t, is.Equal("cfssl: https://example.com, cfssl: anything", opt.String())) } diff --git a/cli/command/swarm/unlock_key_test.go b/cli/command/swarm/unlock_key_test.go index 97c04fc628..d8d74e5e6d 100644 --- a/cli/command/swarm/unlock_key_test.go +++ b/cli/command/swarm/unlock_key_test.go @@ -12,8 +12,8 @@ import ( // Import builders to get the builder function as package function . "github.com/docker/cli/internal/test/builders" "github.com/docker/cli/internal/test/testutil" + "github.com/gotestyourself/gotestyourself/assert" "github.com/gotestyourself/gotestyourself/golden" - "github.com/stretchr/testify/assert" ) func TestSwarmUnlockKeyErrors(t *testing.T) { @@ -166,7 +166,7 @@ func TestSwarmUnlockKey(t *testing.T) { for key, value := range tc.flags { cmd.Flags().Set(key, value) } - assert.NoError(t, cmd.Execute()) + assert.Check(t, cmd.Execute()) golden.Assert(t, cli.OutBuffer().String(), fmt.Sprintf("unlockkeys-%s.golden", tc.name)) } } diff --git a/cli/command/swarm/unlock_test.go b/cli/command/swarm/unlock_test.go index c7aee0a3c7..998c302272 100644 --- a/cli/command/swarm/unlock_test.go +++ b/cli/command/swarm/unlock_test.go @@ -10,8 +10,8 @@ import ( "github.com/docker/cli/internal/test/testutil" "github.com/docker/docker/api/types" "github.com/docker/docker/api/types/swarm" + "github.com/gotestyourself/gotestyourself/assert" "github.com/pkg/errors" - "github.com/stretchr/testify/assert" ) func TestSwarmUnlockErrors(t *testing.T) { @@ -95,5 +95,5 @@ func TestSwarmUnlock(t *testing.T) { }) dockerCli.SetIn(command.NewInStream(ioutil.NopCloser(strings.NewReader(input)))) cmd := newUnlockCommand(dockerCli) - assert.NoError(t, cmd.Execute()) + assert.Check(t, cmd.Execute()) } diff --git a/cli/command/swarm/update_test.go b/cli/command/swarm/update_test.go index e2a0033916..81a3e19404 100644 --- a/cli/command/swarm/update_test.go +++ b/cli/command/swarm/update_test.go @@ -13,8 +13,8 @@ import ( // Import builders to get the builder function as package function . "github.com/docker/cli/internal/test/builders" "github.com/docker/cli/internal/test/testutil" + "github.com/gotestyourself/gotestyourself/assert" "github.com/gotestyourself/gotestyourself/golden" - "github.com/stretchr/testify/assert" ) func TestSwarmUpdateErrors(t *testing.T) { @@ -173,7 +173,7 @@ func TestSwarmUpdate(t *testing.T) { cmd.Flags().Set(key, value) } cmd.SetOutput(cli.OutBuffer()) - assert.NoError(t, cmd.Execute()) + assert.Check(t, cmd.Execute()) golden.Assert(t, cli.OutBuffer().String(), fmt.Sprintf("update-%s.golden", tc.name)) } } diff --git a/cli/command/system/info_test.go b/cli/command/system/info_test.go index 4291623d1a..7e2dd6bff8 100644 --- a/cli/command/system/info_test.go +++ b/cli/command/system/info_test.go @@ -10,8 +10,9 @@ import ( "github.com/docker/docker/api/types" "github.com/docker/docker/api/types/registry" "github.com/docker/docker/api/types/swarm" + "github.com/gotestyourself/gotestyourself/assert" + is "github.com/gotestyourself/gotestyourself/assert/cmp" "github.com/gotestyourself/gotestyourself/golden" - "github.com/stretchr/testify/assert" ) // helper function that base64 decodes a string and ignores the error @@ -226,12 +227,12 @@ func TestPrettyPrintInfo(t *testing.T) { }, } { cli := test.NewFakeCli(&fakeClient{}) - assert.NoError(t, prettyPrintInfo(cli, tc.dockerInfo)) + assert.NilError(t, prettyPrintInfo(cli, tc.dockerInfo)) golden.Assert(t, cli.OutBuffer().String(), tc.expectedGolden+".golden") if tc.warningsGolden != "" { golden.Assert(t, cli.ErrBuffer().String(), tc.warningsGolden+".golden") } else { - assert.Equal(t, "", cli.ErrBuffer().String()) + assert.Check(t, is.Equal("", cli.ErrBuffer().String())) } } } diff --git a/cli/command/system/prune_test.go b/cli/command/system/prune_test.go index 0d694ce066..a3133eebb6 100644 --- a/cli/command/system/prune_test.go +++ b/cli/command/system/prune_test.go @@ -4,12 +4,19 @@ import ( "testing" "github.com/docker/cli/internal/test" - "github.com/stretchr/testify/assert" + "github.com/gotestyourself/gotestyourself/assert" + is "github.com/gotestyourself/gotestyourself/assert/cmp" ) -func TestPrunePromptPre131(t *testing.T) { +func TestPrunePromptPre131DoesNotIncludeBuildCache(t *testing.T) { cli := test.NewFakeCli(&fakeClient{version: "1.30"}) cmd := newPruneCommand(cli) - assert.NoError(t, cmd.Execute()) - assert.NotContains(t, cli.OutBuffer().String(), "all build cache") + assert.Check(t, cmd.Execute()) + expected := `WARNING! This will remove: + - all stopped containers + - all networks not used by at least one container + - all dangling images +Are you sure you want to continue? [y/N] ` + assert.Check(t, is.Equal(expected, cli.OutBuffer().String())) + } diff --git a/cli/command/system/version_test.go b/cli/command/system/version_test.go index 98c0c1167d..c704ce2051 100644 --- a/cli/command/system/version_test.go +++ b/cli/command/system/version_test.go @@ -6,11 +6,12 @@ import ( "testing" "github.com/docker/cli/cli/command" + "github.com/gotestyourself/gotestyourself/assert" + is "github.com/gotestyourself/gotestyourself/assert/cmp" "github.com/docker/cli/internal/test" "github.com/docker/docker/api" "github.com/docker/docker/api/types" - "github.com/stretchr/testify/assert" "golang.org/x/net/context" ) @@ -22,12 +23,15 @@ func TestVersionWithoutServer(t *testing.T) { }) cmd := NewVersionCommand(cli) cmd.SetOutput(cli.Err()) - assert.Error(t, cmd.Execute()) - assert.Contains(t, cleanTabs(cli.OutBuffer().String()), "Client:") - assert.NotContains(t, cleanTabs(cli.OutBuffer().String()), "Server:") + assert.ErrorContains(t, cmd.Execute(), "no server") + out := cli.OutBuffer().String() + // TODO: use an assertion like e2e/image/build_test.go:assertBuildOutput() + // instead of contains/not contains + assert.Check(t, is.Contains(out, "Client:")) + assert.Assert(t, !strings.Contains(out, "Server:"), "actual: %s", out) } -func fakeServerVersion(ctx context.Context) (types.Version, error) { +func fakeServerVersion(_ context.Context) (types.Version, error) { return types.Version{ Version: "docker-dev", APIVersion: api.DefaultVersion, @@ -38,8 +42,8 @@ func TestVersionWithOrchestrator(t *testing.T) { cli := test.NewFakeCli(&fakeClient{serverVersion: fakeServerVersion}) cli.SetClientInfo(func() command.ClientInfo { return command.ClientInfo{Orchestrator: "swarm"} }) cmd := NewVersionCommand(cli) - assert.NoError(t, cmd.Execute()) - assert.Contains(t, cleanTabs(cli.OutBuffer().String()), "Orchestrator: swarm") + assert.NilError(t, cmd.Execute()) + assert.Check(t, is.Contains(cleanTabs(cli.OutBuffer().String()), "Orchestrator: swarm")) } func cleanTabs(line string) string { diff --git a/cli/command/task/print_test.go b/cli/command/task/print_test.go index 04ae1bb0ef..7803b799ef 100644 --- a/cli/command/task/print_test.go +++ b/cli/command/task/print_test.go @@ -12,8 +12,8 @@ import ( . "github.com/docker/cli/internal/test/builders" "github.com/docker/docker/api/types" "github.com/docker/docker/api/types/swarm" + "github.com/gotestyourself/gotestyourself/assert" "github.com/gotestyourself/gotestyourself/golden" - "github.com/stretchr/testify/assert" ) func TestTaskPrintWithQuietOption(t *testing.T) { @@ -24,7 +24,7 @@ func TestTaskPrintWithQuietOption(t *testing.T) { cli := test.NewFakeCli(apiClient) tasks := []swarm.Task{*Task(TaskID("id-foo"))} err := Print(context.Background(), cli, tasks, idresolver.New(apiClient, noResolve), trunc, quiet, formatter.TableFormatKey) - assert.NoError(t, err) + assert.Check(t, err) golden.Assert(t, cli.OutBuffer().String(), "task-print-with-quiet-option.golden") } @@ -38,7 +38,7 @@ func TestTaskPrintWithNoTruncOption(t *testing.T) { *Task(TaskID("id-foo-yov6omdek8fg3k5stosyp2m50")), } err := Print(context.Background(), cli, tasks, idresolver.New(apiClient, noResolve), trunc, quiet, "{{ .ID }}") - assert.NoError(t, err) + assert.Check(t, err) golden.Assert(t, cli.OutBuffer().String(), "task-print-with-no-trunc-option.golden") } @@ -52,7 +52,7 @@ func TestTaskPrintWithGlobalService(t *testing.T) { *Task(TaskServiceID("service-id-foo"), TaskNodeID("node-id-bar"), TaskSlot(0)), } err := Print(context.Background(), cli, tasks, idresolver.New(apiClient, noResolve), trunc, quiet, "{{ .Name }}") - assert.NoError(t, err) + assert.Check(t, err) golden.Assert(t, cli.OutBuffer().String(), "task-print-with-global-service.golden") } @@ -66,7 +66,7 @@ func TestTaskPrintWithReplicatedService(t *testing.T) { *Task(TaskServiceID("service-id-foo"), TaskSlot(1)), } err := Print(context.Background(), cli, tasks, idresolver.New(apiClient, noResolve), trunc, quiet, "{{ .Name }}") - assert.NoError(t, err) + assert.Check(t, err) golden.Assert(t, cli.OutBuffer().String(), "task-print-with-replicated-service.golden") } @@ -102,7 +102,7 @@ func TestTaskPrintWithIndentation(t *testing.T) { ), } err := Print(context.Background(), cli, tasks, idresolver.New(apiClient, noResolve), trunc, quiet, formatter.TableFormatKey) - assert.NoError(t, err) + assert.Check(t, err) golden.Assert(t, cli.OutBuffer().String(), "task-print-with-indentation.golden") } @@ -123,6 +123,6 @@ func TestTaskPrintWithResolution(t *testing.T) { *Task(TaskServiceID("service-id-foo"), TaskSlot(1)), } err := Print(context.Background(), cli, tasks, idresolver.New(apiClient, noResolve), trunc, quiet, "{{ .Name }} {{ .Node }}") - assert.NoError(t, err) + assert.Check(t, err) golden.Assert(t, cli.OutBuffer().String(), "task-print-with-resolution.golden") } diff --git a/cli/command/trust/helpers_test.go b/cli/command/trust/helpers_test.go index a13eae2d6e..8cd189c256 100644 --- a/cli/command/trust/helpers_test.go +++ b/cli/command/trust/helpers_test.go @@ -5,21 +5,21 @@ import ( "os" "testing" + "github.com/gotestyourself/gotestyourself/assert" + is "github.com/gotestyourself/gotestyourself/assert/cmp" "github.com/theupdateframework/notary/client" "github.com/theupdateframework/notary/passphrase" "github.com/theupdateframework/notary/trustpinning" - - "github.com/stretchr/testify/assert" ) func TestGetOrGenerateNotaryKeyAndInitRepo(t *testing.T) { tmpDir, err := ioutil.TempDir("", "notary-test-") - assert.NoError(t, err) + assert.Check(t, err) defer os.RemoveAll(tmpDir) notaryRepo, err := client.NewFileCachedRepository(tmpDir, "gun", "https://localhost", nil, passphrase.ConstantRetriever(passwd), trustpinning.TrustPinConfig{}) - assert.NoError(t, err) + assert.Check(t, err) err = getOrGenerateRootKeyAndInitRepo(notaryRepo) - assert.EqualError(t, err, "client is offline") + assert.Check(t, is.Error(err, "client is offline")) } diff --git a/cli/command/trust/inspect_test.go b/cli/command/trust/inspect_test.go index cb2ee800a8..b9d36de441 100644 --- a/cli/command/trust/inspect_test.go +++ b/cli/command/trust/inspect_test.go @@ -6,8 +6,8 @@ import ( "github.com/docker/cli/internal/test" "github.com/docker/cli/internal/test/testutil" + "github.com/gotestyourself/gotestyourself/assert" "github.com/gotestyourself/gotestyourself/golden" - "github.com/stretchr/testify/assert" ) func TestTrustInspectCommandErrors(t *testing.T) { @@ -85,7 +85,7 @@ func TestTrustInspectCommandEmptyNotaryRepo(t *testing.T) { cmd := newInspectCommand(cli) cmd.SetArgs([]string{"reg/img:unsigned-tag"}) cmd.SetOutput(ioutil.Discard) - assert.NoError(t, cmd.Execute()) + assert.Check(t, cmd.Execute()) golden.Assert(t, cli.OutBuffer().String(), "trust-inspect-empty-repo.golden") } @@ -94,7 +94,7 @@ func TestTrustInspectCommandFullRepoWithoutSigners(t *testing.T) { cli.SetNotaryClient(getLoadedWithNoSignersNotaryRepository) cmd := newInspectCommand(cli) cmd.SetArgs([]string{"signed-repo"}) - assert.NoError(t, cmd.Execute()) + assert.Check(t, cmd.Execute()) golden.Assert(t, cli.OutBuffer().String(), "trust-inspect-full-repo-no-signers.golden") } @@ -103,7 +103,7 @@ func TestTrustInspectCommandOneTagWithoutSigners(t *testing.T) { cli.SetNotaryClient(getLoadedWithNoSignersNotaryRepository) cmd := newInspectCommand(cli) cmd.SetArgs([]string{"signed-repo:green"}) - assert.NoError(t, cmd.Execute()) + assert.Check(t, cmd.Execute()) golden.Assert(t, cli.OutBuffer().String(), "trust-inspect-one-tag-no-signers.golden") } @@ -112,7 +112,7 @@ func TestTrustInspectCommandFullRepoWithSigners(t *testing.T) { cli.SetNotaryClient(getLoadedNotaryRepository) cmd := newInspectCommand(cli) cmd.SetArgs([]string{"signed-repo"}) - assert.NoError(t, cmd.Execute()) + assert.Check(t, cmd.Execute()) golden.Assert(t, cli.OutBuffer().String(), "trust-inspect-full-repo-with-signers.golden") } @@ -121,7 +121,7 @@ func TestTrustInspectCommandMultipleFullReposWithSigners(t *testing.T) { cli.SetNotaryClient(getLoadedNotaryRepository) cmd := newInspectCommand(cli) cmd.SetArgs([]string{"signed-repo", "signed-repo"}) - assert.NoError(t, cmd.Execute()) + assert.Check(t, cmd.Execute()) golden.Assert(t, cli.OutBuffer().String(), "trust-inspect-multiple-repos-with-signers.golden") } @@ -130,6 +130,6 @@ func TestTrustInspectCommandUnsignedTagInSignedRepo(t *testing.T) { cli.SetNotaryClient(getLoadedNotaryRepository) cmd := newInspectCommand(cli) cmd.SetArgs([]string{"signed-repo:unsigned"}) - assert.NoError(t, cmd.Execute()) + assert.Check(t, cmd.Execute()) golden.Assert(t, cli.OutBuffer().String(), "trust-inspect-unsigned-tag-with-signers.golden") } diff --git a/cli/command/trust/key_generate_test.go b/cli/command/trust/key_generate_test.go index faf6f31873..8d7b97beae 100644 --- a/cli/command/trust/key_generate_test.go +++ b/cli/command/trust/key_generate_test.go @@ -11,7 +11,8 @@ import ( "github.com/docker/cli/cli/config" "github.com/docker/cli/internal/test" "github.com/docker/cli/internal/test/testutil" - "github.com/stretchr/testify/assert" + "github.com/gotestyourself/gotestyourself/assert" + is "github.com/gotestyourself/gotestyourself/assert/cmp" "github.com/theupdateframework/notary" "github.com/theupdateframework/notary/passphrase" "github.com/theupdateframework/notary/trustmanager" @@ -36,7 +37,7 @@ func TestTrustKeyGenerateErrors(t *testing.T) { } tmpDir, err := ioutil.TempDir("", "docker-key-generate-test-") - assert.NoError(t, err) + assert.Check(t, err) defer os.RemoveAll(tmpDir) config.SetDir(tmpDir) @@ -51,11 +52,11 @@ func TestTrustKeyGenerateErrors(t *testing.T) { func TestGenerateKeySuccess(t *testing.T) { pubKeyCWD, err := ioutil.TempDir("", "pub-keys-") - assert.NoError(t, err) + assert.Check(t, err) defer os.RemoveAll(pubKeyCWD) privKeyStorageDir, err := ioutil.TempDir("", "priv-keys-") - assert.NoError(t, err) + assert.Check(t, err) defer os.RemoveAll(privKeyStorageDir) passwd := "password" @@ -63,25 +64,25 @@ func TestGenerateKeySuccess(t *testing.T) { // generate a single key keyName := "alice" privKeyFileStore, err := trustmanager.NewKeyFileStore(privKeyStorageDir, cannedPasswordRetriever) - assert.NoError(t, err) + assert.Check(t, err) pubKeyPEM, err := generateKeyAndOutputPubPEM(keyName, privKeyFileStore) - assert.NoError(t, err) + assert.Check(t, err) - assert.Equal(t, keyName, pubKeyPEM.Headers["role"]) + assert.Check(t, is.Equal(keyName, pubKeyPEM.Headers["role"])) // the default GUN is empty - assert.Equal(t, "", pubKeyPEM.Headers["gun"]) + assert.Check(t, is.Equal("", pubKeyPEM.Headers["gun"])) // assert public key header - assert.Equal(t, "PUBLIC KEY", pubKeyPEM.Type) + assert.Check(t, is.Equal("PUBLIC KEY", pubKeyPEM.Type)) // check that an appropriate ~//private/.key file exists expectedPrivKeyDir := filepath.Join(privKeyStorageDir, notary.PrivDir) _, err = os.Stat(expectedPrivKeyDir) - assert.NoError(t, err) + assert.Check(t, err) keyFiles, err := ioutil.ReadDir(expectedPrivKeyDir) - assert.NoError(t, err) - assert.Len(t, keyFiles, 1) + assert.Check(t, err) + assert.Check(t, is.Len(keyFiles, 1)) privKeyFilePath := filepath.Join(expectedPrivKeyDir, keyFiles[0].Name()) // verify the key content @@ -89,50 +90,46 @@ func TestGenerateKeySuccess(t *testing.T) { defer privFrom.Close() fromBytes, _ := ioutil.ReadAll(privFrom) privKeyPEM, _ := pem.Decode(fromBytes) - assert.Equal(t, keyName, privKeyPEM.Headers["role"]) + assert.Check(t, is.Equal(keyName, privKeyPEM.Headers["role"])) // the default GUN is empty - assert.Equal(t, "", privKeyPEM.Headers["gun"]) + assert.Check(t, is.Equal("", privKeyPEM.Headers["gun"])) // assert encrypted header - assert.Equal(t, "ENCRYPTED PRIVATE KEY", privKeyPEM.Type) + assert.Check(t, is.Equal("ENCRYPTED PRIVATE KEY", privKeyPEM.Type)) // check that the passphrase matches _, err = tufutils.ParsePKCS8ToTufKey(privKeyPEM.Bytes, []byte(passwd)) - assert.NoError(t, err) + assert.Check(t, err) // check that the public key exists at the correct path if we use the helper: returnedPath, err := writePubKeyPEMToDir(pubKeyPEM, keyName, pubKeyCWD) - assert.NoError(t, err) + assert.Check(t, err) expectedPubKeyPath := filepath.Join(pubKeyCWD, keyName+".pub") - assert.Equal(t, returnedPath, expectedPubKeyPath) + assert.Check(t, is.Equal(returnedPath, expectedPubKeyPath)) _, err = os.Stat(expectedPubKeyPath) - assert.NoError(t, err) + assert.Check(t, err) // check that the public key is the only file output in CWD cwdKeyFiles, err := ioutil.ReadDir(pubKeyCWD) - assert.NoError(t, err) - assert.Len(t, cwdKeyFiles, 1) + assert.Check(t, err) + assert.Check(t, is.Len(cwdKeyFiles, 1)) } func TestValidateKeyArgs(t *testing.T) { pubKeyCWD, err := ioutil.TempDir("", "pub-keys-") - assert.NoError(t, err) + assert.Check(t, err) defer os.RemoveAll(pubKeyCWD) err = validateKeyArgs("a", pubKeyCWD) - assert.NoError(t, err) + assert.Check(t, err) err = validateKeyArgs("a/b", pubKeyCWD) - assert.Error(t, err) - assert.Equal(t, err.Error(), "key name \"a/b\" must start with lowercase alphanumeric characters and can include \"-\" or \"_\" after the first character") + assert.Error(t, err, "key name \"a/b\" must start with lowercase alphanumeric characters and can include \"-\" or \"_\" after the first character") err = validateKeyArgs("-", pubKeyCWD) - assert.Error(t, err) - assert.Equal(t, err.Error(), "key name \"-\" must start with lowercase alphanumeric characters and can include \"-\" or \"_\" after the first character") + assert.Error(t, err, "key name \"-\" must start with lowercase alphanumeric characters and can include \"-\" or \"_\" after the first character") - assert.NoError(t, ioutil.WriteFile(filepath.Join(pubKeyCWD, "a.pub"), []byte("abc"), notary.PrivExecPerms)) + assert.Check(t, ioutil.WriteFile(filepath.Join(pubKeyCWD, "a.pub"), []byte("abc"), notary.PrivExecPerms)) err = validateKeyArgs("a", pubKeyCWD) - assert.Error(t, err) - assert.Equal(t, err.Error(), fmt.Sprintf("public key file already exists: \"%s/a.pub\"", pubKeyCWD)) + assert.Error(t, err, fmt.Sprintf("public key file already exists: \"%s/a.pub\"", pubKeyCWD)) err = validateKeyArgs("a", "/random/dir/") - assert.Error(t, err) - assert.Equal(t, err.Error(), "public key path does not exist: \"/random/dir/\"") + assert.Error(t, err, "public key path does not exist: \"/random/dir/\"") } diff --git a/cli/command/trust/key_load_test.go b/cli/command/trust/key_load_test.go index 5902b36667..e4da34e94f 100644 --- a/cli/command/trust/key_load_test.go +++ b/cli/command/trust/key_load_test.go @@ -11,7 +11,8 @@ import ( "github.com/docker/cli/cli/config" "github.com/docker/cli/internal/test" "github.com/docker/cli/internal/test/testutil" - "github.com/stretchr/testify/assert" + "github.com/gotestyourself/gotestyourself/assert" + is "github.com/gotestyourself/gotestyourself/assert/cmp" "github.com/theupdateframework/notary" "github.com/theupdateframework/notary/passphrase" "github.com/theupdateframework/notary/storage" @@ -51,7 +52,7 @@ func TestTrustKeyLoadErrors(t *testing.T) { }, } tmpDir, err := ioutil.TempDir("", "docker-key-load-test-") - assert.NoError(t, err) + assert.Check(t, err) defer os.RemoveAll(tmpDir) config.SetDir(tmpDir) @@ -61,7 +62,7 @@ func TestTrustKeyLoadErrors(t *testing.T) { cmd.SetArgs(tc.args) cmd.SetOutput(ioutil.Discard) testutil.ErrorContains(t, cmd.Execute(), tc.expectedError) - assert.Contains(t, cli.OutBuffer().String(), tc.expectedOutput) + assert.Check(t, is.Contains(cli.OutBuffer().String(), tc.expectedOutput)) } } @@ -118,48 +119,48 @@ func TestLoadKeyFromPath(t *testing.T) { func testLoadKeyFromPath(t *testing.T, privKeyID string, privKeyFixture []byte) { privKeyDir, err := ioutil.TempDir("", "key-load-test-") - assert.NoError(t, err) + assert.Check(t, err) defer os.RemoveAll(privKeyDir) privKeyFilepath := filepath.Join(privKeyDir, "privkey.pem") - assert.NoError(t, ioutil.WriteFile(privKeyFilepath, privKeyFixture, notary.PrivNoExecPerms)) + assert.Check(t, ioutil.WriteFile(privKeyFilepath, privKeyFixture, notary.PrivNoExecPerms)) keyStorageDir, err := ioutil.TempDir("", "loaded-keys-") - assert.NoError(t, err) + assert.Check(t, err) defer os.RemoveAll(keyStorageDir) passwd := "password" cannedPasswordRetriever := passphrase.ConstantRetriever(passwd) keyFileStore, err := storage.NewPrivateKeyFileStorage(keyStorageDir, notary.KeyExtension) - assert.NoError(t, err) + assert.Check(t, err) privKeyImporters := []trustmanager.Importer{keyFileStore} // get the privKeyBytes privKeyBytes, err := getPrivKeyBytesFromPath(privKeyFilepath) - assert.NoError(t, err) + assert.Check(t, err) // import the key to our keyStorageDir - assert.NoError(t, loadPrivKeyBytesToStore(privKeyBytes, privKeyImporters, privKeyFilepath, "signer-name", cannedPasswordRetriever)) + assert.Check(t, loadPrivKeyBytesToStore(privKeyBytes, privKeyImporters, privKeyFilepath, "signer-name", cannedPasswordRetriever)) // check that the appropriate ~//private/.key file exists expectedImportKeyPath := filepath.Join(keyStorageDir, notary.PrivDir, privKeyID+"."+notary.KeyExtension) _, err = os.Stat(expectedImportKeyPath) - assert.NoError(t, err) + assert.Check(t, err) // verify the key content from, _ := os.OpenFile(expectedImportKeyPath, os.O_RDONLY, notary.PrivExecPerms) defer from.Close() fromBytes, _ := ioutil.ReadAll(from) keyPEM, _ := pem.Decode(fromBytes) - assert.Equal(t, "signer-name", keyPEM.Headers["role"]) + assert.Check(t, is.Equal("signer-name", keyPEM.Headers["role"])) // the default GUN is empty - assert.Equal(t, "", keyPEM.Headers["gun"]) + assert.Check(t, is.Equal("", keyPEM.Headers["gun"])) // assert encrypted header - assert.Equal(t, "ENCRYPTED PRIVATE KEY", keyPEM.Type) + assert.Check(t, is.Equal("ENCRYPTED PRIVATE KEY", keyPEM.Type)) decryptedKey, err := tufutils.ParsePKCS8ToTufKey(keyPEM.Bytes, []byte(passwd)) - assert.NoError(t, err) + assert.Check(t, err) fixturePEM, _ := pem.Decode(privKeyFixture) - assert.Equal(t, fixturePEM.Bytes, decryptedKey.Private()) + assert.Check(t, is.DeepEqual(fixturePEM.Bytes, decryptedKey.Private())) } func TestLoadKeyTooPermissive(t *testing.T) { @@ -172,45 +173,45 @@ func TestLoadKeyTooPermissive(t *testing.T) { func testLoadKeyTooPermissive(t *testing.T, privKeyFixture []byte) { privKeyDir, err := ioutil.TempDir("", "key-load-test-") - assert.NoError(t, err) + assert.Check(t, err) defer os.RemoveAll(privKeyDir) privKeyFilepath := filepath.Join(privKeyDir, "privkey477.pem") - assert.NoError(t, ioutil.WriteFile(privKeyFilepath, privKeyFixture, 0477)) + assert.Check(t, ioutil.WriteFile(privKeyFilepath, privKeyFixture, 0477)) keyStorageDir, err := ioutil.TempDir("", "loaded-keys-") - assert.NoError(t, err) + assert.Check(t, err) defer os.RemoveAll(keyStorageDir) // import the key to our keyStorageDir _, err = getPrivKeyBytesFromPath(privKeyFilepath) - assert.Error(t, err) - assert.Contains(t, fmt.Sprintf("private key file %s must not be readable or writable by others", privKeyFilepath), err.Error()) + expected := fmt.Sprintf("private key file %s must not be readable or writable by others", privKeyFilepath) + assert.Error(t, err, expected) privKeyFilepath = filepath.Join(privKeyDir, "privkey667.pem") - assert.NoError(t, ioutil.WriteFile(privKeyFilepath, privKeyFixture, 0677)) + assert.Check(t, ioutil.WriteFile(privKeyFilepath, privKeyFixture, 0677)) _, err = getPrivKeyBytesFromPath(privKeyFilepath) - assert.Error(t, err) - assert.Contains(t, fmt.Sprintf("private key file %s must not be readable or writable by others", privKeyFilepath), err.Error()) + expected = fmt.Sprintf("private key file %s must not be readable or writable by others", privKeyFilepath) + assert.Error(t, err, expected) privKeyFilepath = filepath.Join(privKeyDir, "privkey777.pem") - assert.NoError(t, ioutil.WriteFile(privKeyFilepath, privKeyFixture, 0777)) + assert.Check(t, ioutil.WriteFile(privKeyFilepath, privKeyFixture, 0777)) _, err = getPrivKeyBytesFromPath(privKeyFilepath) - assert.Error(t, err) - assert.Contains(t, fmt.Sprintf("private key file %s must not be readable or writable by others", privKeyFilepath), err.Error()) + expected = fmt.Sprintf("private key file %s must not be readable or writable by others", privKeyFilepath) + assert.Error(t, err, expected) privKeyFilepath = filepath.Join(privKeyDir, "privkey400.pem") - assert.NoError(t, ioutil.WriteFile(privKeyFilepath, privKeyFixture, 0400)) + assert.Check(t, ioutil.WriteFile(privKeyFilepath, privKeyFixture, 0400)) _, err = getPrivKeyBytesFromPath(privKeyFilepath) - assert.NoError(t, err) + assert.Check(t, err) privKeyFilepath = filepath.Join(privKeyDir, "privkey600.pem") - assert.NoError(t, ioutil.WriteFile(privKeyFilepath, privKeyFixture, 0600)) + assert.Check(t, ioutil.WriteFile(privKeyFilepath, privKeyFixture, 0600)) _, err = getPrivKeyBytesFromPath(privKeyFilepath) - assert.NoError(t, err) + assert.Check(t, err) } var pubKeyFixture = []byte(`-----BEGIN PUBLIC KEY----- @@ -220,25 +221,25 @@ H3nzy2O6Q/ct4BjOBKa+WCdRtPo78bA+C/7t81ADQO8Jqaj59W50rwoqDQ== func TestLoadPubKeyFailure(t *testing.T) { pubKeyDir, err := ioutil.TempDir("", "key-load-test-pubkey-") - assert.NoError(t, err) + assert.Check(t, err) defer os.RemoveAll(pubKeyDir) pubKeyFilepath := filepath.Join(pubKeyDir, "pubkey.pem") - assert.NoError(t, ioutil.WriteFile(pubKeyFilepath, pubKeyFixture, notary.PrivNoExecPerms)) + assert.Check(t, ioutil.WriteFile(pubKeyFilepath, pubKeyFixture, notary.PrivNoExecPerms)) keyStorageDir, err := ioutil.TempDir("", "loaded-keys-") - assert.NoError(t, err) + assert.Check(t, err) defer os.RemoveAll(keyStorageDir) passwd := "password" cannedPasswordRetriever := passphrase.ConstantRetriever(passwd) keyFileStore, err := storage.NewPrivateKeyFileStorage(keyStorageDir, notary.KeyExtension) - assert.NoError(t, err) + assert.Check(t, err) privKeyImporters := []trustmanager.Importer{keyFileStore} pubKeyBytes, err := getPrivKeyBytesFromPath(pubKeyFilepath) - assert.NoError(t, err) + assert.Check(t, err) // import the key to our keyStorageDir - it should fail err = loadPrivKeyBytesToStore(pubKeyBytes, privKeyImporters, pubKeyFilepath, "signer-name", cannedPasswordRetriever) - assert.Error(t, err) - assert.Contains(t, fmt.Sprintf("provided file %s is not a supported private key - to add a signer's public key use docker trust signer add", pubKeyFilepath), err.Error()) + expected := fmt.Sprintf("provided file %s is not a supported private key - to add a signer's public key use docker trust signer add", pubKeyFilepath) + assert.Error(t, err, expected) } diff --git a/cli/command/trust/revoke_test.go b/cli/command/trust/revoke_test.go index ea93accdf9..1bb6b0f448 100644 --- a/cli/command/trust/revoke_test.go +++ b/cli/command/trust/revoke_test.go @@ -7,8 +7,8 @@ import ( "github.com/docker/cli/internal/test" "github.com/docker/cli/internal/test/testutil" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" + "github.com/gotestyourself/gotestyourself/assert" + is "github.com/gotestyourself/gotestyourself/assert/cmp" "github.com/theupdateframework/notary/client" "github.com/theupdateframework/notary/passphrase" "github.com/theupdateframework/notary/trustpinning" @@ -60,8 +60,8 @@ func TestTrustRevokeCommandOfflineErrors(t *testing.T) { cmd := newRevokeCommand(cli) cmd.SetArgs([]string{"reg-name.io/image"}) cmd.SetOutput(ioutil.Discard) - assert.NoError(t, cmd.Execute()) - assert.Contains(t, cli.OutBuffer().String(), "Please confirm you would like to delete all signature data for reg-name.io/image? [y/N] \nAborting action.") + assert.Check(t, cmd.Execute()) + assert.Check(t, is.Contains(cli.OutBuffer().String(), "Please confirm you would like to delete all signature data for reg-name.io/image? [y/N] \nAborting action.")) cli = test.NewFakeCli(&fakeClient{}) cli.SetNotaryClient(getOfflineNotaryRepository) @@ -83,8 +83,8 @@ func TestTrustRevokeCommandUninitializedErrors(t *testing.T) { cmd := newRevokeCommand(cli) cmd.SetArgs([]string{"reg-name.io/image"}) cmd.SetOutput(ioutil.Discard) - assert.NoError(t, cmd.Execute()) - assert.Contains(t, cli.OutBuffer().String(), "Please confirm you would like to delete all signature data for reg-name.io/image? [y/N] \nAborting action.") + assert.Check(t, cmd.Execute()) + assert.Check(t, is.Contains(cli.OutBuffer().String(), "Please confirm you would like to delete all signature data for reg-name.io/image? [y/N] \nAborting action.")) cli = test.NewFakeCli(&fakeClient{}) cli.SetNotaryClient(getUninitializedNotaryRepository) @@ -107,8 +107,8 @@ func TestTrustRevokeCommandEmptyNotaryRepo(t *testing.T) { cmd := newRevokeCommand(cli) cmd.SetArgs([]string{"reg-name.io/image"}) cmd.SetOutput(ioutil.Discard) - assert.NoError(t, cmd.Execute()) - assert.Contains(t, cli.OutBuffer().String(), "Please confirm you would like to delete all signature data for reg-name.io/image? [y/N] \nAborting action.") + assert.Check(t, cmd.Execute()) + assert.Check(t, is.Contains(cli.OutBuffer().String(), "Please confirm you would like to delete all signature data for reg-name.io/image? [y/N] \nAborting action.")) cli = test.NewFakeCli(&fakeClient{}) cli.SetNotaryClient(getEmptyTargetsNotaryRepository) @@ -130,19 +130,19 @@ func TestNewRevokeTrustAllSigConfirmation(t *testing.T) { cli.SetNotaryClient(getEmptyTargetsNotaryRepository) cmd := newRevokeCommand(cli) cmd.SetArgs([]string{"alpine"}) - assert.NoError(t, cmd.Execute()) + assert.Check(t, cmd.Execute()) - assert.Contains(t, cli.OutBuffer().String(), "Please confirm you would like to delete all signature data for alpine? [y/N] \nAborting action.") + assert.Check(t, is.Contains(cli.OutBuffer().String(), "Please confirm you would like to delete all signature data for alpine? [y/N] \nAborting action.")) } func TestGetSignableRolesForTargetAndRemoveError(t *testing.T) { tmpDir, err := ioutil.TempDir("", "notary-test-") - assert.NoError(t, err) + assert.Check(t, err) defer os.RemoveAll(tmpDir) notaryRepo, err := client.NewFileCachedRepository(tmpDir, "gun", "https://localhost", nil, passphrase.ConstantRetriever("password"), trustpinning.TrustPinConfig{}) - require.NoError(t, err) + assert.NilError(t, err) target := client.Target{} err = getSignableRolesForTargetAndRemove(target, notaryRepo) - assert.EqualError(t, err, "client is offline") + assert.Check(t, is.Error(err, "client is offline")) } diff --git a/cli/command/trust/sign_test.go b/cli/command/trust/sign_test.go index fdfaec739f..be6c27afb7 100644 --- a/cli/command/trust/sign_test.go +++ b/cli/command/trust/sign_test.go @@ -11,8 +11,8 @@ import ( "github.com/docker/cli/cli/trust" "github.com/docker/cli/internal/test" "github.com/docker/cli/internal/test/testutil" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" + "github.com/gotestyourself/gotestyourself/assert" + is "github.com/gotestyourself/gotestyourself/assert/cmp" "github.com/theupdateframework/notary" "github.com/theupdateframework/notary/client" "github.com/theupdateframework/notary/client/changelist" @@ -61,7 +61,7 @@ func TestTrustSignCommandErrors(t *testing.T) { } // change to a tmpdir tmpDir, err := ioutil.TempDir("", "docker-sign-test-") - assert.NoError(t, err) + assert.Check(t, err) defer os.RemoveAll(tmpDir) config.SetDir(tmpDir) for _, tc := range testCases { @@ -79,73 +79,72 @@ func TestTrustSignCommandOfflineErrors(t *testing.T) { cmd := newSignCommand(cli) cmd.SetArgs([]string{"reg-name.io/image:tag"}) cmd.SetOutput(ioutil.Discard) - assert.Error(t, cmd.Execute()) - testutil.ErrorContains(t, cmd.Execute(), "client is offline") + assert.ErrorContains(t, cmd.Execute(), "client is offline") } func TestGetOrGenerateNotaryKey(t *testing.T) { tmpDir, err := ioutil.TempDir("", "notary-test-") - assert.NoError(t, err) + assert.Check(t, err) defer os.RemoveAll(tmpDir) notaryRepo, err := client.NewFileCachedRepository(tmpDir, "gun", "https://localhost", nil, passphrase.ConstantRetriever(passwd), trustpinning.TrustPinConfig{}) - assert.NoError(t, err) + assert.Check(t, err) // repo is empty, try making a root key rootKeyA, err := getOrGenerateNotaryKey(notaryRepo, data.CanonicalRootRole) - assert.NoError(t, err) - assert.NotNil(t, rootKeyA) + assert.Check(t, err) + assert.Check(t, rootKeyA != nil) // we should only have one newly generated key allKeys := notaryRepo.GetCryptoService().ListAllKeys() - assert.Len(t, allKeys, 1) - assert.NotNil(t, notaryRepo.GetCryptoService().GetKey(rootKeyA.ID())) + assert.Check(t, is.Len(allKeys, 1)) + assert.Check(t, notaryRepo.GetCryptoService().GetKey(rootKeyA.ID()) != nil) // this time we should get back the same key if we ask for another root key rootKeyB, err := getOrGenerateNotaryKey(notaryRepo, data.CanonicalRootRole) - assert.NoError(t, err) - assert.NotNil(t, rootKeyB) + assert.Check(t, err) + assert.Check(t, rootKeyB != nil) // we should only have one newly generated key allKeys = notaryRepo.GetCryptoService().ListAllKeys() - assert.Len(t, allKeys, 1) - assert.NotNil(t, notaryRepo.GetCryptoService().GetKey(rootKeyB.ID())) + assert.Check(t, is.Len(allKeys, 1)) + assert.Check(t, notaryRepo.GetCryptoService().GetKey(rootKeyB.ID()) != nil) // The key we retrieved should be identical to the one we generated - assert.Equal(t, rootKeyA, rootKeyB) + assert.Check(t, is.DeepEqual(rootKeyA.Public(), rootKeyB.Public())) // Now also try with a delegation key releasesKey, err := getOrGenerateNotaryKey(notaryRepo, data.RoleName(trust.ReleasesRole)) - assert.NoError(t, err) - assert.NotNil(t, releasesKey) + assert.Check(t, err) + assert.Check(t, releasesKey != nil) // we should now have two keys allKeys = notaryRepo.GetCryptoService().ListAllKeys() - assert.Len(t, allKeys, 2) - assert.NotNil(t, notaryRepo.GetCryptoService().GetKey(releasesKey.ID())) + assert.Check(t, is.Len(allKeys, 2)) + assert.Check(t, notaryRepo.GetCryptoService().GetKey(releasesKey.ID()) != nil) // The key we retrieved should be identical to the one we generated - assert.NotEqual(t, releasesKey, rootKeyA) - assert.NotEqual(t, releasesKey, rootKeyB) + assert.Check(t, releasesKey != rootKeyA) + assert.Check(t, releasesKey != rootKeyB) } func TestAddStageSigners(t *testing.T) { tmpDir, err := ioutil.TempDir("", "notary-test-") - assert.NoError(t, err) + assert.Check(t, err) defer os.RemoveAll(tmpDir) notaryRepo, err := client.NewFileCachedRepository(tmpDir, "gun", "https://localhost", nil, passphrase.ConstantRetriever(passwd), trustpinning.TrustPinConfig{}) - assert.NoError(t, err) + assert.Check(t, err) // stage targets/user userRole := data.RoleName("targets/user") userKey := data.NewPublicKey("algoA", []byte("a")) err = addStagedSigner(notaryRepo, userRole, []data.PublicKey{userKey}) - assert.NoError(t, err) + assert.Check(t, err) // check the changelist for four total changes: two on targets/releases and two on targets/user cl, err := notaryRepo.GetChangelist() - assert.NoError(t, err) + assert.Check(t, err) changeList := cl.List() - assert.Len(t, changeList, 4) + assert.Check(t, is.Len(changeList, 4)) // ordering is determinstic: // first change is for targets/user key creation @@ -154,7 +153,7 @@ func TestAddStageSigners(t *testing.T) { NewThreshold: notary.MinThreshold, AddKeys: data.KeyList([]data.PublicKey{userKey}), }) - require.NoError(t, err) + assert.NilError(t, err) expectedChange := changelist.NewTUFChange( changelist.ActionCreate, userRole, @@ -162,14 +161,14 @@ func TestAddStageSigners(t *testing.T) { "", // no path for delegations expectedJSON, ) - assert.Equal(t, expectedChange, newSignerKeyChange) + assert.Check(t, is.DeepEqual(expectedChange, newSignerKeyChange)) // second change is for targets/user getting all paths newSignerPathsChange := changeList[1] expectedJSON, err = json.Marshal(&changelist.TUFDelegation{ AddPaths: []string{""}, }) - require.NoError(t, err) + assert.NilError(t, err) expectedChange = changelist.NewTUFChange( changelist.ActionCreate, userRole, @@ -177,7 +176,7 @@ func TestAddStageSigners(t *testing.T) { "", // no path for delegations expectedJSON, ) - assert.Equal(t, expectedChange, newSignerPathsChange) + assert.Check(t, is.DeepEqual(expectedChange, newSignerPathsChange)) releasesRole := data.RoleName("targets/releases") @@ -187,7 +186,7 @@ func TestAddStageSigners(t *testing.T) { NewThreshold: notary.MinThreshold, AddKeys: data.KeyList([]data.PublicKey{userKey}), }) - require.NoError(t, err) + assert.NilError(t, err) expectedChange = changelist.NewTUFChange( changelist.ActionCreate, releasesRole, @@ -195,14 +194,14 @@ func TestAddStageSigners(t *testing.T) { "", // no path for delegations expectedJSON, ) - assert.Equal(t, expectedChange, releasesKeyChange) + assert.Check(t, is.DeepEqual(expectedChange, releasesKeyChange)) // fourth change is for targets/releases getting all paths releasesPathsChange := changeList[3] expectedJSON, err = json.Marshal(&changelist.TUFDelegation{ AddPaths: []string{""}, }) - require.NoError(t, err) + assert.NilError(t, err) expectedChange = changelist.NewTUFChange( changelist.ActionCreate, releasesRole, @@ -210,19 +209,19 @@ func TestAddStageSigners(t *testing.T) { "", // no path for delegations expectedJSON, ) - assert.Equal(t, expectedChange, releasesPathsChange) + assert.Check(t, is.DeepEqual(expectedChange, releasesPathsChange)) } func TestGetSignedManifestHashAndSize(t *testing.T) { tmpDir, err := ioutil.TempDir("", "notary-test-") - assert.NoError(t, err) + assert.Check(t, err) defer os.RemoveAll(tmpDir) notaryRepo, err := client.NewFileCachedRepository(tmpDir, "gun", "https://localhost", nil, passphrase.ConstantRetriever(passwd), trustpinning.TrustPinConfig{}) - assert.NoError(t, err) + assert.Check(t, err) target := &client.Target{} target.Hashes, target.Length, err = getSignedManifestHashAndSize(notaryRepo, "test") - assert.EqualError(t, err, "client is offline") + assert.Check(t, is.Error(err, "client is offline")) } func TestGetReleasedTargetHashAndSize(t *testing.T) { @@ -233,36 +232,36 @@ func TestGetReleasedTargetHashAndSize(t *testing.T) { oneReleasedTgt = append(oneReleasedTgt, client.TargetSignedStruct{Role: mockDelegationRoleWithName(unreleasedRole), Target: unreleasedTgt}) } _, _, err := getReleasedTargetHashAndSize(oneReleasedTgt, "unreleased") - assert.EqualError(t, err, "No valid trust data for unreleased") + assert.Check(t, is.Error(err, "No valid trust data for unreleased")) releasedTgt := client.Target{Name: "released", Hashes: data.Hashes{notary.SHA256: []byte("released-hash")}} oneReleasedTgt = append(oneReleasedTgt, client.TargetSignedStruct{Role: mockDelegationRoleWithName("targets/releases"), Target: releasedTgt}) hash, _, _ := getReleasedTargetHashAndSize(oneReleasedTgt, "unreleased") - assert.Equal(t, data.Hashes{notary.SHA256: []byte("released-hash")}, hash) + assert.Check(t, is.DeepEqual(data.Hashes{notary.SHA256: []byte("released-hash")}, hash)) } func TestCreateTarget(t *testing.T) { tmpDir, err := ioutil.TempDir("", "notary-test-") - assert.NoError(t, err) + assert.Check(t, err) defer os.RemoveAll(tmpDir) notaryRepo, err := client.NewFileCachedRepository(tmpDir, "gun", "https://localhost", nil, passphrase.ConstantRetriever(passwd), trustpinning.TrustPinConfig{}) - assert.NoError(t, err) + assert.Check(t, err) _, err = createTarget(notaryRepo, "") - assert.EqualError(t, err, "No tag specified") + assert.Check(t, is.Error(err, "No tag specified")) _, err = createTarget(notaryRepo, "1") - assert.EqualError(t, err, "client is offline") + assert.Check(t, is.Error(err, "client is offline")) } func TestGetExistingSignatureInfoForReleasedTag(t *testing.T) { tmpDir, err := ioutil.TempDir("", "notary-test-") - assert.NoError(t, err) + assert.Check(t, err) defer os.RemoveAll(tmpDir) notaryRepo, err := client.NewFileCachedRepository(tmpDir, "gun", "https://localhost", nil, passphrase.ConstantRetriever(passwd), trustpinning.TrustPinConfig{}) - assert.NoError(t, err) + assert.Check(t, err) _, err = getExistingSignatureInfoForReleasedTag(notaryRepo, "test") - assert.EqualError(t, err, "client is offline") + assert.Check(t, is.Error(err, "client is offline")) } func TestPrettyPrintExistingSignatureInfo(t *testing.T) { @@ -271,12 +270,12 @@ func TestPrettyPrintExistingSignatureInfo(t *testing.T) { existingSig := trustTagRow{trustTagKey{"tagName", "abc123"}, signers} prettyPrintExistingSignatureInfo(buf, existingSig) - assert.Contains(t, buf.String(), "Existing signatures for tag tagName digest abc123 from:\nAlice, Bob, Carol") + assert.Check(t, is.Contains(buf.String(), "Existing signatures for tag tagName digest abc123 from:\nAlice, Bob, Carol")) } func TestSignCommandChangeListIsCleanedOnError(t *testing.T) { tmpDir, err := ioutil.TempDir("", "docker-sign-test-") - assert.NoError(t, err) + assert.Check(t, err) defer os.RemoveAll(tmpDir) config.SetDir(tmpDir) @@ -287,13 +286,13 @@ func TestSignCommandChangeListIsCleanedOnError(t *testing.T) { cmd.SetOutput(ioutil.Discard) err = cmd.Execute() - require.Error(t, err) + assert.Assert(t, is.ErrorContains(err, "")) notaryRepo, err := client.NewFileCachedRepository(tmpDir, "docker.io/library/ubuntu", "https://localhost", nil, passphrase.ConstantRetriever(passwd), trustpinning.TrustPinConfig{}) - assert.NoError(t, err) + assert.Check(t, err) cl, err := notaryRepo.GetChangelist() - require.NoError(t, err) - assert.Equal(t, len(cl.List()), 0) + assert.NilError(t, err) + assert.Check(t, is.Equal(len(cl.List()), 0)) } func TestSignCommandLocalFlag(t *testing.T) { diff --git a/cli/command/trust/signer_add_test.go b/cli/command/trust/signer_add_test.go index a27f161cb7..e11eff5598 100644 --- a/cli/command/trust/signer_add_test.go +++ b/cli/command/trust/signer_add_test.go @@ -10,7 +10,8 @@ import ( "github.com/docker/cli/cli/config" "github.com/docker/cli/internal/test" "github.com/docker/cli/internal/test/testutil" - "github.com/stretchr/testify/assert" + "github.com/gotestyourself/gotestyourself/assert" + is "github.com/gotestyourself/gotestyourself/assert/cmp" "github.com/theupdateframework/notary" ) @@ -51,7 +52,7 @@ func TestTrustSignerAddErrors(t *testing.T) { }, } tmpDir, err := ioutil.TempDir("", "docker-sign-test-") - assert.NoError(t, err) + assert.Check(t, err) defer os.RemoveAll(tmpDir) config.SetDir(tmpDir) @@ -67,12 +68,12 @@ func TestTrustSignerAddErrors(t *testing.T) { func TestSignerAddCommandNoTargetsKey(t *testing.T) { tmpDir, err := ioutil.TempDir("", "docker-sign-test-") - assert.NoError(t, err) + assert.Check(t, err) defer os.RemoveAll(tmpDir) config.SetDir(tmpDir) tmpfile, err := ioutil.TempFile("", "pemfile") - assert.NoError(t, err) + assert.Check(t, err) defer os.Remove(tmpfile.Name()) cli := test.NewFakeCli(&fakeClient{}) @@ -81,12 +82,12 @@ func TestSignerAddCommandNoTargetsKey(t *testing.T) { cmd.SetArgs([]string{"--key", tmpfile.Name(), "alice", "alpine", "linuxkit/alpine"}) cmd.SetOutput(ioutil.Discard) - assert.EqualError(t, cmd.Execute(), fmt.Sprintf("could not parse public key from file: %s: no valid public key found", tmpfile.Name())) + assert.Check(t, is.Error(cmd.Execute(), fmt.Sprintf("could not parse public key from file: %s: no valid public key found", tmpfile.Name()))) } func TestSignerAddCommandBadKeyPath(t *testing.T) { tmpDir, err := ioutil.TempDir("", "docker-sign-test-") - assert.NoError(t, err) + assert.Check(t, err) defer os.RemoveAll(tmpDir) config.SetDir(tmpDir) @@ -96,20 +97,20 @@ func TestSignerAddCommandBadKeyPath(t *testing.T) { cmd.SetArgs([]string{"--key", "/path/to/key.pem", "alice", "alpine"}) cmd.SetOutput(ioutil.Discard) - assert.EqualError(t, cmd.Execute(), "unable to read public key from file: open /path/to/key.pem: no such file or directory") + assert.Check(t, is.Error(cmd.Execute(), "unable to read public key from file: open /path/to/key.pem: no such file or directory")) } func TestSignerAddCommandInvalidRepoName(t *testing.T) { tmpDir, err := ioutil.TempDir("", "docker-sign-test-") - assert.NoError(t, err) + assert.Check(t, err) defer os.RemoveAll(tmpDir) config.SetDir(tmpDir) pubKeyDir, err := ioutil.TempDir("", "key-load-test-pubkey-") - assert.NoError(t, err) + assert.Check(t, err) defer os.RemoveAll(pubKeyDir) pubKeyFilepath := filepath.Join(pubKeyDir, "pubkey.pem") - assert.NoError(t, ioutil.WriteFile(pubKeyFilepath, pubKeyFixture, notary.PrivNoExecPerms)) + assert.Check(t, ioutil.WriteFile(pubKeyFilepath, pubKeyFixture, notary.PrivNoExecPerms)) cli := test.NewFakeCli(&fakeClient{}) cli.SetNotaryClient(getUninitializedNotaryRepository) @@ -118,20 +119,20 @@ func TestSignerAddCommandInvalidRepoName(t *testing.T) { cmd.SetArgs([]string{"--key", pubKeyFilepath, "alice", imageName}) cmd.SetOutput(ioutil.Discard) - assert.EqualError(t, cmd.Execute(), "Failed to add signer to: 870d292919d01a0af7e7f056271dc78792c05f55f49b9b9012b6d89725bd9abd") + assert.Check(t, is.Error(cmd.Execute(), "Failed to add signer to: 870d292919d01a0af7e7f056271dc78792c05f55f49b9b9012b6d89725bd9abd")) expectedErr := fmt.Sprintf("invalid repository name (%s), cannot specify 64-byte hexadecimal strings\n\n", imageName) - assert.Equal(t, expectedErr, cli.ErrBuffer().String()) + assert.Check(t, is.Equal(expectedErr, cli.ErrBuffer().String())) } func TestIngestPublicKeys(t *testing.T) { // Call with a bad path _, err := ingestPublicKeys([]string{"foo", "bar"}) - assert.EqualError(t, err, "unable to read public key from file: open foo: no such file or directory") + assert.Check(t, is.Error(err, "unable to read public key from file: open foo: no such file or directory")) // Call with real file path tmpfile, err := ioutil.TempFile("", "pemfile") - assert.NoError(t, err) + assert.Check(t, err) defer os.Remove(tmpfile.Name()) _, err = ingestPublicKeys([]string{tmpfile.Name()}) - assert.EqualError(t, err, fmt.Sprintf("could not parse public key from file: %s: no valid public key found", tmpfile.Name())) + assert.Check(t, is.Error(err, fmt.Sprintf("could not parse public key from file: %s: no valid public key found", tmpfile.Name()))) } diff --git a/cli/command/trust/signer_remove_test.go b/cli/command/trust/signer_remove_test.go index 890fbf37a8..f2a33f8ab1 100644 --- a/cli/command/trust/signer_remove_test.go +++ b/cli/command/trust/signer_remove_test.go @@ -6,7 +6,8 @@ import ( "github.com/docker/cli/internal/test" "github.com/docker/cli/internal/test/testutil" - "github.com/stretchr/testify/assert" + "github.com/gotestyourself/gotestyourself/assert" + is "github.com/gotestyourself/gotestyourself/assert/cmp" "github.com/theupdateframework/notary/client" "github.com/theupdateframework/notary/tuf/data" ) @@ -62,7 +63,7 @@ func TestTrustSignerRemoveErrors(t *testing.T) { cmd.SetArgs(tc.args) cmd.SetOutput(ioutil.Discard) cmd.Execute() - assert.Contains(t, cli.ErrBuffer().String(), tc.expectedError) + assert.Check(t, is.Contains(cli.ErrBuffer().String(), tc.expectedError)) } } @@ -71,30 +72,30 @@ func TestRemoveSingleSigner(t *testing.T) { cli := test.NewFakeCli(&fakeClient{}) cli.SetNotaryClient(getLoadedNotaryRepository) err := removeSingleSigner(cli, "signed-repo", "test", true) - assert.EqualError(t, err, "No signer test for repository signed-repo") + assert.Check(t, is.Error(err, "No signer test for repository signed-repo")) err = removeSingleSigner(cli, "signed-repo", "releases", true) - assert.EqualError(t, err, "releases is a reserved keyword and cannot be removed") + assert.Check(t, is.Error(err, "releases is a reserved keyword and cannot be removed")) } func TestRemoveMultipleSigners(t *testing.T) { cli := test.NewFakeCli(&fakeClient{}) cli.SetNotaryClient(getLoadedNotaryRepository) err := removeSigner(cli, signerRemoveOptions{signer: "test", repos: []string{"signed-repo", "signed-repo"}, forceYes: true}) - assert.EqualError(t, err, "Error removing signer from: signed-repo, signed-repo") - assert.Contains(t, cli.ErrBuffer().String(), - "No signer test for repository signed-repo") - assert.Contains(t, cli.OutBuffer().String(), "Removing signer \"test\" from signed-repo...\n") + assert.Check(t, is.Error(err, "Error removing signer from: signed-repo, signed-repo")) + assert.Check(t, is.Contains(cli.ErrBuffer().String(), + "No signer test for repository signed-repo")) + assert.Check(t, is.Contains(cli.OutBuffer().String(), "Removing signer \"test\" from signed-repo...\n")) } func TestRemoveLastSignerWarning(t *testing.T) { cli := test.NewFakeCli(&fakeClient{}) cli.SetNotaryClient(getLoadedNotaryRepository) err := removeSigner(cli, signerRemoveOptions{signer: "alice", repos: []string{"signed-repo"}, forceYes: false}) - assert.NoError(t, err) - assert.Contains(t, cli.OutBuffer().String(), + assert.Check(t, err) + assert.Check(t, is.Contains(cli.OutBuffer().String(), "The signer \"alice\" signed the last released version of signed-repo. "+ "Removing this signer will make signed-repo unpullable. "+ - "Are you sure you want to continue? [y/N]") + "Are you sure you want to continue? [y/N]")) } func TestIsLastSignerForReleases(t *testing.T) { @@ -104,7 +105,7 @@ func TestIsLastSignerForReleases(t *testing.T) { releaserole.Threshold = 1 allrole := []client.RoleWithSignatures{releaserole} lastsigner, _ := isLastSignerForReleases(role, allrole) - assert.Equal(t, false, lastsigner) + assert.Check(t, is.Equal(false, lastsigner)) role.KeyIDs = []string{"deadbeef"} sig := data.Signature{} @@ -113,12 +114,12 @@ func TestIsLastSignerForReleases(t *testing.T) { releaserole.Threshold = 1 allrole = []client.RoleWithSignatures{releaserole} lastsigner, _ = isLastSignerForReleases(role, allrole) - assert.Equal(t, true, lastsigner) + assert.Check(t, is.Equal(true, lastsigner)) sig.KeyID = "8badf00d" releaserole.Signatures = []data.Signature{sig} releaserole.Threshold = 1 allrole = []client.RoleWithSignatures{releaserole} lastsigner, _ = isLastSignerForReleases(role, allrole) - assert.Equal(t, false, lastsigner) + assert.Check(t, is.Equal(false, lastsigner)) } diff --git a/cli/command/trust/view_test.go b/cli/command/trust/view_test.go index a8a69d207b..152e87a9e5 100644 --- a/cli/command/trust/view_test.go +++ b/cli/command/trust/view_test.go @@ -9,8 +9,9 @@ import ( "github.com/docker/cli/internal/test" "github.com/docker/cli/internal/test/testutil" dockerClient "github.com/docker/docker/client" + "github.com/gotestyourself/gotestyourself/assert" + is "github.com/gotestyourself/gotestyourself/assert/cmp" "github.com/gotestyourself/gotestyourself/golden" - "github.com/stretchr/testify/assert" "github.com/theupdateframework/notary" "github.com/theupdateframework/notary/client" "github.com/theupdateframework/notary/tuf/data" @@ -93,18 +94,18 @@ func TestTrustViewCommandEmptyNotaryRepoErrors(t *testing.T) { cmd := newViewCommand(cli) cmd.SetArgs([]string{"reg/img:unsigned-tag"}) cmd.SetOutput(ioutil.Discard) - assert.NoError(t, cmd.Execute()) - assert.Contains(t, cli.OutBuffer().String(), "No signatures for reg/img:unsigned-tag") - assert.Contains(t, cli.OutBuffer().String(), "Administrative keys for reg/img:") + assert.Check(t, cmd.Execute()) + assert.Check(t, is.Contains(cli.OutBuffer().String(), "No signatures for reg/img:unsigned-tag")) + assert.Check(t, is.Contains(cli.OutBuffer().String(), "Administrative keys for reg/img:")) cli = test.NewFakeCli(&fakeClient{}) cli.SetNotaryClient(getEmptyTargetsNotaryRepository) cmd = newViewCommand(cli) cmd.SetArgs([]string{"reg/img"}) cmd.SetOutput(ioutil.Discard) - assert.NoError(t, cmd.Execute()) - assert.Contains(t, cli.OutBuffer().String(), "No signatures for reg/img") - assert.Contains(t, cli.OutBuffer().String(), "Administrative keys for reg/img:") + assert.Check(t, cmd.Execute()) + assert.Check(t, is.Contains(cli.OutBuffer().String(), "No signatures for reg/img")) + assert.Check(t, is.Contains(cli.OutBuffer().String(), "Administrative keys for reg/img:")) } func TestTrustViewCommandFullRepoWithoutSigners(t *testing.T) { @@ -112,7 +113,7 @@ func TestTrustViewCommandFullRepoWithoutSigners(t *testing.T) { cli.SetNotaryClient(getLoadedWithNoSignersNotaryRepository) cmd := newViewCommand(cli) cmd.SetArgs([]string{"signed-repo"}) - assert.NoError(t, cmd.Execute()) + assert.Check(t, cmd.Execute()) golden.Assert(t, cli.OutBuffer().String(), "trust-view-full-repo-no-signers.golden") } @@ -122,7 +123,7 @@ func TestTrustViewCommandOneTagWithoutSigners(t *testing.T) { cli.SetNotaryClient(getLoadedWithNoSignersNotaryRepository) cmd := newViewCommand(cli) cmd.SetArgs([]string{"signed-repo:green"}) - assert.NoError(t, cmd.Execute()) + assert.Check(t, cmd.Execute()) golden.Assert(t, cli.OutBuffer().String(), "trust-view-one-tag-no-signers.golden") } @@ -132,7 +133,7 @@ func TestTrustViewCommandFullRepoWithSigners(t *testing.T) { cli.SetNotaryClient(getLoadedNotaryRepository) cmd := newViewCommand(cli) cmd.SetArgs([]string{"signed-repo"}) - assert.NoError(t, cmd.Execute()) + assert.Check(t, cmd.Execute()) golden.Assert(t, cli.OutBuffer().String(), "trust-view-full-repo-with-signers.golden") } @@ -142,36 +143,36 @@ func TestTrustViewCommandUnsignedTagInSignedRepo(t *testing.T) { cli.SetNotaryClient(getLoadedNotaryRepository) cmd := newViewCommand(cli) cmd.SetArgs([]string{"signed-repo:unsigned"}) - assert.NoError(t, cmd.Execute()) + assert.Check(t, cmd.Execute()) golden.Assert(t, cli.OutBuffer().String(), "trust-view-unsigned-tag-with-signers.golden") } func TestNotaryRoleToSigner(t *testing.T) { - assert.Equal(t, releasedRoleName, notaryRoleToSigner(data.CanonicalTargetsRole)) - assert.Equal(t, releasedRoleName, notaryRoleToSigner(trust.ReleasesRole)) - assert.Equal(t, "signer", notaryRoleToSigner("targets/signer")) - assert.Equal(t, "docker/signer", notaryRoleToSigner("targets/docker/signer")) + assert.Check(t, is.Equal(releasedRoleName, notaryRoleToSigner(data.CanonicalTargetsRole))) + assert.Check(t, is.Equal(releasedRoleName, notaryRoleToSigner(trust.ReleasesRole))) + assert.Check(t, is.Equal("signer", notaryRoleToSigner("targets/signer"))) + assert.Check(t, is.Equal("docker/signer", notaryRoleToSigner("targets/docker/signer"))) // It's nonsense for other base roles to have signed off on a target, but this function leaves role names intact for _, role := range data.BaseRoles { if role == data.CanonicalTargetsRole { continue } - assert.Equal(t, role.String(), notaryRoleToSigner(role)) + assert.Check(t, is.Equal(role.String(), notaryRoleToSigner(role))) } - assert.Equal(t, "notarole", notaryRoleToSigner(data.RoleName("notarole"))) + assert.Check(t, is.Equal("notarole", notaryRoleToSigner(data.RoleName("notarole")))) } // check if a role name is "released": either targets/releases or targets TUF roles func TestIsReleasedTarget(t *testing.T) { - assert.True(t, isReleasedTarget(trust.ReleasesRole)) + assert.Check(t, isReleasedTarget(trust.ReleasesRole)) for _, role := range data.BaseRoles { - assert.Equal(t, role == data.CanonicalTargetsRole, isReleasedTarget(role)) + assert.Check(t, is.Equal(role == data.CanonicalTargetsRole, isReleasedTarget(role))) } - assert.False(t, isReleasedTarget(data.RoleName("targets/not-releases"))) - assert.False(t, isReleasedTarget(data.RoleName("random"))) - assert.False(t, isReleasedTarget(data.RoleName("targets/releases/subrole"))) + assert.Check(t, !isReleasedTarget(data.RoleName("targets/not-releases"))) + assert.Check(t, !isReleasedTarget(data.RoleName("random"))) + assert.Check(t, !isReleasedTarget(data.RoleName("targets/releases/subrole"))) } // creates a mock delegation with a given name and no keys @@ -188,7 +189,7 @@ func TestMatchEmptySignatures(t *testing.T) { emptyTgts := []client.TargetSignedStruct{} matchedSigRows := matchReleasedSignatures(emptyTgts) - assert.Empty(t, matchedSigRows) + assert.Check(t, is.Len(matchedSigRows, 0)) } func TestMatchUnreleasedSignatures(t *testing.T) { @@ -201,7 +202,7 @@ func TestMatchUnreleasedSignatures(t *testing.T) { } matchedSigRows := matchReleasedSignatures(unreleasedTgts) - assert.Empty(t, matchedSigRows) + assert.Check(t, is.Len(matchedSigRows, 0)) } func TestMatchOneReleasedSingleSignature(t *testing.T) { @@ -219,13 +220,13 @@ func TestMatchOneReleasedSingleSignature(t *testing.T) { } matchedSigRows := matchReleasedSignatures(oneReleasedTgt) - assert.Len(t, matchedSigRows, 1) + assert.Check(t, is.Len(matchedSigRows, 1)) outputRow := matchedSigRows[0] // Empty signers because "targets/releases" doesn't show up - assert.Empty(t, outputRow.Signers) - assert.Equal(t, releasedTgt.Name, outputRow.SignedTag) - assert.Equal(t, hex.EncodeToString(releasedTgt.Hashes[notary.SHA256]), outputRow.Digest) + assert.Check(t, is.Len(outputRow.Signers, 0)) + assert.Check(t, is.Equal(releasedTgt.Name, outputRow.SignedTag)) + assert.Check(t, is.Equal(hex.EncodeToString(releasedTgt.Hashes[notary.SHA256]), outputRow.Digest)) } func TestMatchOneReleasedMultiSignature(t *testing.T) { @@ -244,13 +245,13 @@ func TestMatchOneReleasedMultiSignature(t *testing.T) { } matchedSigRows := matchReleasedSignatures(oneReleasedTgt) - assert.Len(t, matchedSigRows, 1) + assert.Check(t, is.Len(matchedSigRows, 1)) outputRow := matchedSigRows[0] // We should have three signers - assert.Equal(t, outputRow.Signers, []string{"a", "b", "c"}) - assert.Equal(t, releasedTgt.Name, outputRow.SignedTag) - assert.Equal(t, hex.EncodeToString(releasedTgt.Hashes[notary.SHA256]), outputRow.Digest) + assert.Check(t, is.DeepEqual(outputRow.Signers, []string{"a", "b", "c"})) + assert.Check(t, is.Equal(releasedTgt.Name, outputRow.SignedTag)) + assert.Check(t, is.Equal(hex.EncodeToString(releasedTgt.Hashes[notary.SHA256]), outputRow.Digest)) } func TestMatchMultiReleasedMultiSignature(t *testing.T) { @@ -283,23 +284,23 @@ func TestMatchMultiReleasedMultiSignature(t *testing.T) { multiReleasedTgts = append(multiReleasedTgts, client.TargetSignedStruct{Role: mockDelegationRoleWithName("targets/c"), Target: targetC}) matchedSigRows := matchReleasedSignatures(multiReleasedTgts) - assert.Len(t, matchedSigRows, 3) + assert.Check(t, is.Len(matchedSigRows, 3)) // note that the output is sorted by tag name, so we can reliably index to validate data: outputTargetA := matchedSigRows[0] - assert.Equal(t, outputTargetA.Signers, []string{"a"}) - assert.Equal(t, targetA.Name, outputTargetA.SignedTag) - assert.Equal(t, hex.EncodeToString(targetA.Hashes[notary.SHA256]), outputTargetA.Digest) + assert.Check(t, is.DeepEqual(outputTargetA.Signers, []string{"a"})) + assert.Check(t, is.Equal(targetA.Name, outputTargetA.SignedTag)) + assert.Check(t, is.Equal(hex.EncodeToString(targetA.Hashes[notary.SHA256]), outputTargetA.Digest)) outputTargetB := matchedSigRows[1] - assert.Equal(t, outputTargetB.Signers, []string{"a", "b"}) - assert.Equal(t, targetB.Name, outputTargetB.SignedTag) - assert.Equal(t, hex.EncodeToString(targetB.Hashes[notary.SHA256]), outputTargetB.Digest) + assert.Check(t, is.DeepEqual(outputTargetB.Signers, []string{"a", "b"})) + assert.Check(t, is.Equal(targetB.Name, outputTargetB.SignedTag)) + assert.Check(t, is.Equal(hex.EncodeToString(targetB.Hashes[notary.SHA256]), outputTargetB.Digest)) outputTargetC := matchedSigRows[2] - assert.Equal(t, outputTargetC.Signers, []string{"a", "b", "c"}) - assert.Equal(t, targetC.Name, outputTargetC.SignedTag) - assert.Equal(t, hex.EncodeToString(targetC.Hashes[notary.SHA256]), outputTargetC.Digest) + assert.Check(t, is.DeepEqual(outputTargetC.Signers, []string{"a", "b", "c"})) + assert.Check(t, is.Equal(targetC.Name, outputTargetC.SignedTag)) + assert.Check(t, is.Equal(hex.EncodeToString(targetC.Hashes[notary.SHA256]), outputTargetC.Digest)) } func TestMatchReleasedSignatureFromTargets(t *testing.T) { @@ -309,12 +310,12 @@ func TestMatchReleasedSignatureFromTargets(t *testing.T) { releasedTgt := client.Target{Name: "released", Hashes: data.Hashes{notary.SHA256: []byte("released-hash")}} oneReleasedTgt = append(oneReleasedTgt, client.TargetSignedStruct{Role: mockDelegationRoleWithName(data.CanonicalTargetsRole.String()), Target: releasedTgt}) matchedSigRows := matchReleasedSignatures(oneReleasedTgt) - assert.Len(t, matchedSigRows, 1) + assert.Check(t, is.Len(matchedSigRows, 1)) outputRow := matchedSigRows[0] // Empty signers because "targets" doesn't show up - assert.Empty(t, outputRow.Signers) - assert.Equal(t, releasedTgt.Name, outputRow.SignedTag) - assert.Equal(t, hex.EncodeToString(releasedTgt.Hashes[notary.SHA256]), outputRow.Digest) + assert.Check(t, is.Len(outputRow.Signers, 0)) + assert.Check(t, is.Equal(releasedTgt.Name, outputRow.SignedTag)) + assert.Check(t, is.Equal(hex.EncodeToString(releasedTgt.Hashes[notary.SHA256]), outputRow.Digest)) } func TestGetSignerRolesWithKeyIDs(t *testing.T) { @@ -373,7 +374,7 @@ func TestGetSignerRolesWithKeyIDs(t *testing.T) { roleWithSigs = append(roleWithSigs, roleWithSig) } signerRoleToKeyIDs := getDelegationRoleToKeyMap(roles) - assert.Equal(t, expectedSignerRoleToKeyIDs, signerRoleToKeyIDs) + assert.Check(t, is.DeepEqual(expectedSignerRoleToKeyIDs, signerRoleToKeyIDs)) } func TestFormatAdminRole(t *testing.T) { @@ -384,7 +385,7 @@ func TestFormatAdminRole(t *testing.T) { Name: "targets/alice", } aliceRoleWithSigs := client.RoleWithSignatures{Role: aliceRole, Signatures: nil} - assert.Equal(t, "", formatAdminRole(aliceRoleWithSigs)) + assert.Check(t, is.Equal("", formatAdminRole(aliceRoleWithSigs))) releasesRole := data.Role{ RootRole: data.RootRole{ @@ -393,7 +394,7 @@ func TestFormatAdminRole(t *testing.T) { Name: "targets/releases", } releasesRoleWithSigs := client.RoleWithSignatures{Role: releasesRole, Signatures: nil} - assert.Equal(t, "", formatAdminRole(releasesRoleWithSigs)) + assert.Check(t, is.Equal("", formatAdminRole(releasesRoleWithSigs))) timestampRole := data.Role{ RootRole: data.RootRole{ @@ -402,7 +403,7 @@ func TestFormatAdminRole(t *testing.T) { Name: data.CanonicalTimestampRole, } timestampRoleWithSigs := client.RoleWithSignatures{Role: timestampRole, Signatures: nil} - assert.Equal(t, "", formatAdminRole(timestampRoleWithSigs)) + assert.Check(t, is.Equal("", formatAdminRole(timestampRoleWithSigs))) snapshotRole := data.Role{ RootRole: data.RootRole{ @@ -411,7 +412,7 @@ func TestFormatAdminRole(t *testing.T) { Name: data.CanonicalSnapshotRole, } snapshotRoleWithSigs := client.RoleWithSignatures{Role: snapshotRole, Signatures: nil} - assert.Equal(t, "", formatAdminRole(snapshotRoleWithSigs)) + assert.Check(t, is.Equal("", formatAdminRole(snapshotRoleWithSigs))) rootRole := data.Role{ RootRole: data.RootRole{ @@ -420,7 +421,7 @@ func TestFormatAdminRole(t *testing.T) { Name: data.CanonicalRootRole, } rootRoleWithSigs := client.RoleWithSignatures{Role: rootRole, Signatures: nil} - assert.Equal(t, "Root Key:\tkey11\n", formatAdminRole(rootRoleWithSigs)) + assert.Check(t, is.Equal("Root Key:\tkey11\n", formatAdminRole(rootRoleWithSigs))) targetsRole := data.Role{ RootRole: data.RootRole{ @@ -429,5 +430,5 @@ func TestFormatAdminRole(t *testing.T) { Name: data.CanonicalTargetsRole, } targetsRoleWithSigs := client.RoleWithSignatures{Role: targetsRole, Signatures: nil} - assert.Equal(t, "Repository Key:\tabc, key11, key99\n", formatAdminRole(targetsRoleWithSigs)) + assert.Check(t, is.Equal("Repository Key:\tabc, key11, key99\n", formatAdminRole(targetsRoleWithSigs))) } diff --git a/cli/command/volume/create_test.go b/cli/command/volume/create_test.go index d7c6cb5857..ad8f509d6b 100644 --- a/cli/command/volume/create_test.go +++ b/cli/command/volume/create_test.go @@ -10,8 +10,9 @@ import ( "github.com/docker/cli/internal/test/testutil" "github.com/docker/docker/api/types" volumetypes "github.com/docker/docker/api/types/volume" + "github.com/gotestyourself/gotestyourself/assert" + is "github.com/gotestyourself/gotestyourself/assert/cmp" "github.com/pkg/errors" - "github.com/stretchr/testify/assert" ) func TestVolumeCreateErrors(t *testing.T) { @@ -72,15 +73,15 @@ func TestVolumeCreateWithName(t *testing.T) { // Test by flags cmd := newCreateCommand(cli) cmd.Flags().Set("name", name) - assert.NoError(t, cmd.Execute()) - assert.Equal(t, name, strings.TrimSpace(buf.String())) + assert.Check(t, cmd.Execute()) + assert.Check(t, is.Equal(name, strings.TrimSpace(buf.String()))) // Then by args buf.Reset() cmd = newCreateCommand(cli) cmd.SetArgs([]string{name}) - assert.NoError(t, cmd.Execute()) - assert.Equal(t, name, strings.TrimSpace(buf.String())) + assert.Check(t, cmd.Execute()) + assert.Check(t, is.Equal(name, strings.TrimSpace(buf.String()))) } func TestVolumeCreateWithFlags(t *testing.T) { @@ -121,6 +122,6 @@ func TestVolumeCreateWithFlags(t *testing.T) { cmd.Flags().Set("opt", "baz=baz") cmd.Flags().Set("label", "lbl1=v1") cmd.Flags().Set("label", "lbl2=v2") - assert.NoError(t, cmd.Execute()) - assert.Equal(t, name, strings.TrimSpace(cli.OutBuffer().String())) + assert.Check(t, cmd.Execute()) + assert.Check(t, is.Equal(name, strings.TrimSpace(cli.OutBuffer().String()))) } diff --git a/cli/command/volume/inspect_test.go b/cli/command/volume/inspect_test.go index 934e9b27d8..a2ce14326a 100644 --- a/cli/command/volume/inspect_test.go +++ b/cli/command/volume/inspect_test.go @@ -11,8 +11,8 @@ import ( // Import builders to get the builder function as package function . "github.com/docker/cli/internal/test/builders" "github.com/docker/cli/internal/test/testutil" + "github.com/gotestyourself/gotestyourself/assert" "github.com/gotestyourself/gotestyourself/golden" - "github.com/stretchr/testify/assert" ) func TestVolumeInspectErrors(t *testing.T) { @@ -99,7 +99,7 @@ func TestVolumeInspectWithoutFormat(t *testing.T) { }) cmd := newInspectCommand(cli) cmd.SetArgs(tc.args) - assert.NoError(t, cmd.Execute()) + assert.Check(t, cmd.Execute()) golden.Assert(t, cli.OutBuffer().String(), fmt.Sprintf("volume-inspect-without-format.%s.golden", tc.name)) } } @@ -136,7 +136,7 @@ func TestVolumeInspectWithFormat(t *testing.T) { cmd := newInspectCommand(cli) cmd.SetArgs(tc.args) cmd.Flags().Set("format", tc.format) - assert.NoError(t, cmd.Execute()) + assert.Check(t, cmd.Execute()) golden.Assert(t, cli.OutBuffer().String(), fmt.Sprintf("volume-inspect-with-format.%s.golden", tc.name)) } } diff --git a/cli/command/volume/list_test.go b/cli/command/volume/list_test.go index 264e1010a1..0474497dca 100644 --- a/cli/command/volume/list_test.go +++ b/cli/command/volume/list_test.go @@ -13,8 +13,8 @@ import ( // Import builders to get the builder function as package function . "github.com/docker/cli/internal/test/builders" "github.com/docker/cli/internal/test/testutil" + "github.com/gotestyourself/gotestyourself/assert" "github.com/gotestyourself/gotestyourself/golden" - "github.com/stretchr/testify/assert" ) func TestVolumeListErrors(t *testing.T) { @@ -65,7 +65,7 @@ func TestVolumeListWithoutFormat(t *testing.T) { }, }) cmd := newListCommand(cli) - assert.NoError(t, cmd.Execute()) + assert.Check(t, cmd.Execute()) golden.Assert(t, cli.OutBuffer().String(), "volume-list-without-format.golden") } @@ -87,7 +87,7 @@ func TestVolumeListWithConfigFormat(t *testing.T) { VolumesFormat: "{{ .Name }} {{ .Driver }} {{ .Labels }}", }) cmd := newListCommand(cli) - assert.NoError(t, cmd.Execute()) + assert.Check(t, cmd.Execute()) golden.Assert(t, cli.OutBuffer().String(), "volume-list-with-config-format.golden") } @@ -107,6 +107,6 @@ func TestVolumeListWithFormat(t *testing.T) { }) cmd := newListCommand(cli) cmd.Flags().Set("format", "{{ .Name }} {{ .Driver }} {{ .Labels }}") - assert.NoError(t, cmd.Execute()) + assert.Check(t, cmd.Execute()) golden.Assert(t, cli.OutBuffer().String(), "volume-list-with-format.golden") } diff --git a/cli/command/volume/prune_test.go b/cli/command/volume/prune_test.go index d913f535db..5e21709dc4 100644 --- a/cli/command/volume/prune_test.go +++ b/cli/command/volume/prune_test.go @@ -12,10 +12,10 @@ import ( "github.com/docker/cli/internal/test/testutil" "github.com/docker/docker/api/types" "github.com/docker/docker/api/types/filters" + "github.com/gotestyourself/gotestyourself/assert" "github.com/gotestyourself/gotestyourself/golden" "github.com/gotestyourself/gotestyourself/skip" "github.com/pkg/errors" - "github.com/stretchr/testify/assert" ) func TestVolumePruneErrors(t *testing.T) { @@ -73,7 +73,7 @@ func TestVolumePruneForce(t *testing.T) { }) cmd := NewPruneCommand(cli) cmd.Flags().Set("force", "true") - assert.NoError(t, cmd.Execute()) + assert.Check(t, cmd.Execute()) golden.Assert(t, cli.OutBuffer().String(), fmt.Sprintf("volume-prune.%s.golden", tc.name)) } } @@ -89,7 +89,7 @@ func TestVolumePrunePromptYes(t *testing.T) { cli.SetIn(command.NewInStream(ioutil.NopCloser(strings.NewReader(input)))) cmd := NewPruneCommand(cli) - assert.NoError(t, cmd.Execute()) + assert.Check(t, cmd.Execute()) golden.Assert(t, cli.OutBuffer().String(), "volume-prune-yes.golden") } } @@ -105,7 +105,7 @@ func TestVolumePrunePromptNo(t *testing.T) { cli.SetIn(command.NewInStream(ioutil.NopCloser(strings.NewReader(input)))) cmd := NewPruneCommand(cli) - assert.NoError(t, cmd.Execute()) + assert.Check(t, cmd.Execute()) golden.Assert(t, cli.OutBuffer().String(), "volume-prune-no.golden") } } diff --git a/cli/command/volume/remove_test.go b/cli/command/volume/remove_test.go index fdfb1d788f..217af55757 100644 --- a/cli/command/volume/remove_test.go +++ b/cli/command/volume/remove_test.go @@ -6,8 +6,8 @@ import ( "github.com/docker/cli/internal/test" "github.com/docker/cli/internal/test/testutil" + "github.com/gotestyourself/gotestyourself/assert" "github.com/pkg/errors" - "github.com/stretchr/testify/assert" ) func TestVolumeRemoveErrors(t *testing.T) { @@ -41,5 +41,5 @@ func TestVolumeRemoveErrors(t *testing.T) { func TestNodeRemoveMultiple(t *testing.T) { cmd := newRemoveCommand(test.NewFakeCli(&fakeClient{})) cmd.SetArgs([]string{"volume1", "volume2"}) - assert.NoError(t, cmd.Execute()) + assert.Check(t, cmd.Execute()) } diff --git a/cli/compose/convert/compose_test.go b/cli/compose/convert/compose_test.go index 1392fce604..2963b96c01 100644 --- a/cli/compose/convert/compose_test.go +++ b/cli/compose/convert/compose_test.go @@ -6,14 +6,14 @@ import ( composetypes "github.com/docker/cli/cli/compose/types" "github.com/docker/docker/api/types" "github.com/docker/docker/api/types/network" + "github.com/gotestyourself/gotestyourself/assert" + is "github.com/gotestyourself/gotestyourself/assert/cmp" "github.com/gotestyourself/gotestyourself/fs" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" ) func TestNamespaceScope(t *testing.T) { scoped := Namespace{name: "foo"}.Scope("bar") - assert.Equal(t, "foo_bar", scoped) + assert.Check(t, is.Equal("foo_bar", scoped)) } func TestAddStackLabel(t *testing.T) { @@ -25,7 +25,7 @@ func TestAddStackLabel(t *testing.T) { "something": "labeled", LabelNamespace: "foo", } - assert.Equal(t, expected, actual) + assert.Check(t, is.DeepEqual(expected, actual)) } func TestNetworks(t *testing.T) { @@ -97,8 +97,8 @@ func TestNetworks(t *testing.T) { } networks, externals := Networks(namespace, source, serviceNetworks) - assert.Equal(t, expected, networks) - assert.Equal(t, []string{"special"}, externals) + assert.Check(t, is.DeepEqual(expected, networks)) + assert.Check(t, is.DeepEqual([]string{"special"}, externals)) } func TestSecrets(t *testing.T) { @@ -121,15 +121,15 @@ func TestSecrets(t *testing.T) { } specs, err := Secrets(namespace, source) - assert.NoError(t, err) - require.Len(t, specs, 1) + assert.Check(t, err) + assert.Assert(t, is.Len(specs, 1)) secret := specs[0] - assert.Equal(t, "foo_one", secret.Name) - assert.Equal(t, map[string]string{ + assert.Check(t, is.Equal("foo_one", secret.Name)) + assert.Check(t, is.DeepEqual(map[string]string{ "monster": "mash", LabelNamespace: "foo", - }, secret.Labels) - assert.Equal(t, []byte(secretText), secret.Data) + }, secret.Labels)) + assert.Check(t, is.DeepEqual([]byte(secretText), secret.Data)) } func TestConfigs(t *testing.T) { @@ -152,13 +152,13 @@ func TestConfigs(t *testing.T) { } specs, err := Configs(namespace, source) - assert.NoError(t, err) - require.Len(t, specs, 1) + assert.Check(t, err) + assert.Assert(t, is.Len(specs, 1)) config := specs[0] - assert.Equal(t, "foo_one", config.Name) - assert.Equal(t, map[string]string{ + assert.Check(t, is.Equal("foo_one", config.Name)) + assert.Check(t, is.DeepEqual(map[string]string{ "monster": "mash", LabelNamespace: "foo", - }, config.Labels) - assert.Equal(t, []byte(configText), config.Data) + }, config.Labels)) + assert.Check(t, is.DeepEqual([]byte(configText), config.Data)) } diff --git a/cli/compose/convert/service_test.go b/cli/compose/convert/service_test.go index 0f32997077..e3c72b68db 100644 --- a/cli/compose/convert/service_test.go +++ b/cli/compose/convert/service_test.go @@ -12,21 +12,21 @@ import ( "github.com/docker/docker/api/types/container" "github.com/docker/docker/api/types/swarm" "github.com/docker/docker/client" + "github.com/gotestyourself/gotestyourself/assert" + is "github.com/gotestyourself/gotestyourself/assert/cmp" "github.com/pkg/errors" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" "golang.org/x/net/context" ) func TestConvertRestartPolicyFromNone(t *testing.T) { policy, err := convertRestartPolicy("no", nil) - assert.NoError(t, err) - assert.Equal(t, (*swarm.RestartPolicy)(nil), policy) + assert.Check(t, err) + assert.Check(t, is.DeepEqual((*swarm.RestartPolicy)(nil), policy)) } func TestConvertRestartPolicyFromUnknown(t *testing.T) { _, err := convertRestartPolicy("unknown", nil) - assert.EqualError(t, err, "unknown restart policy: unknown") + assert.Check(t, is.Error(err, "unknown restart policy: unknown")) } func TestConvertRestartPolicyFromAlways(t *testing.T) { @@ -34,8 +34,8 @@ func TestConvertRestartPolicyFromAlways(t *testing.T) { expected := &swarm.RestartPolicy{ Condition: swarm.RestartPolicyConditionAny, } - assert.NoError(t, err) - assert.Equal(t, expected, policy) + assert.Check(t, err) + assert.Check(t, is.DeepEqual(expected, policy)) } func TestConvertRestartPolicyFromFailure(t *testing.T) { @@ -45,8 +45,8 @@ func TestConvertRestartPolicyFromFailure(t *testing.T) { Condition: swarm.RestartPolicyConditionOnFailure, MaxAttempts: &attempts, } - assert.NoError(t, err) - assert.Equal(t, expected, policy) + assert.Check(t, err) + assert.Check(t, is.DeepEqual(expected, policy)) } func strPtr(val string) *string { @@ -60,7 +60,7 @@ func TestConvertEnvironment(t *testing.T) { } env := convertEnvironment(source) sort.Strings(env) - assert.Equal(t, []string{"foo=bar", "key=value"}, env) + assert.Check(t, is.DeepEqual([]string{"foo=bar", "key=value"}, env)) } func TestConvertExtraHosts(t *testing.T) { @@ -69,7 +69,7 @@ func TestConvertExtraHosts(t *testing.T) { "alpha:127.0.0.1", "zulu:ff02::1", } - assert.Equal(t, []string{"127.0.0.2 zulu", "127.0.0.1 alpha", "ff02::1 zulu"}, convertExtraHosts(source)) + assert.Check(t, is.DeepEqual([]string{"127.0.0.2 zulu", "127.0.0.1 alpha", "ff02::1 zulu"}, convertExtraHosts(source))) } func TestConvertResourcesFull(t *testing.T) { @@ -84,7 +84,7 @@ func TestConvertResourcesFull(t *testing.T) { }, } resources, err := convertResources(source) - assert.NoError(t, err) + assert.Check(t, err) expected := &swarm.ResourceRequirements{ Limits: &swarm.Resources{ @@ -96,7 +96,7 @@ func TestConvertResourcesFull(t *testing.T) { MemoryBytes: 200000000, }, } - assert.Equal(t, expected, resources) + assert.Check(t, is.DeepEqual(expected, resources)) } func TestConvertResourcesOnlyMemory(t *testing.T) { @@ -109,7 +109,7 @@ func TestConvertResourcesOnlyMemory(t *testing.T) { }, } resources, err := convertResources(source) - assert.NoError(t, err) + assert.Check(t, err) expected := &swarm.ResourceRequirements{ Limits: &swarm.Resources{ @@ -119,7 +119,7 @@ func TestConvertResourcesOnlyMemory(t *testing.T) { MemoryBytes: 200000000, }, } - assert.Equal(t, expected, resources) + assert.Check(t, is.DeepEqual(expected, resources)) } func TestConvertHealthcheck(t *testing.T) { @@ -140,8 +140,8 @@ func TestConvertHealthcheck(t *testing.T) { } healthcheck, err := convertHealthcheck(source) - assert.NoError(t, err) - assert.Equal(t, expected, healthcheck) + assert.Check(t, err) + assert.Check(t, is.DeepEqual(expected, healthcheck)) } func TestConvertHealthcheckDisable(t *testing.T) { @@ -151,8 +151,8 @@ func TestConvertHealthcheckDisable(t *testing.T) { } healthcheck, err := convertHealthcheck(source) - assert.NoError(t, err) - assert.Equal(t, expected, healthcheck) + assert.Check(t, err) + assert.Check(t, is.DeepEqual(expected, healthcheck)) } func TestConvertHealthcheckDisableWithTest(t *testing.T) { @@ -161,7 +161,7 @@ func TestConvertHealthcheckDisableWithTest(t *testing.T) { Test: []string{"EXEC", "touch"}, } _, err := convertHealthcheck(source) - assert.EqualError(t, err, "test and disable can't be set at the same time") + assert.Check(t, is.Error(err, "test and disable can't be set at the same time")) } func TestConvertEndpointSpec(t *testing.T) { @@ -195,8 +195,8 @@ func TestConvertEndpointSpec(t *testing.T) { }, } - assert.NoError(t, err) - assert.Equal(t, expected, *endpoint) + assert.Check(t, err) + assert.Check(t, is.DeepEqual(expected, *endpoint)) } func TestConvertServiceNetworksOnlyDefault(t *testing.T) { @@ -212,8 +212,8 @@ func TestConvertServiceNetworksOnlyDefault(t *testing.T) { }, } - assert.NoError(t, err) - assert.Equal(t, expected, configs) + assert.Check(t, err) + assert.Check(t, is.DeepEqual(expected, configs)) } func TestConvertServiceNetworks(t *testing.T) { @@ -250,8 +250,8 @@ func TestConvertServiceNetworks(t *testing.T) { sortedConfigs := byTargetSort(configs) sort.Sort(&sortedConfigs) - assert.NoError(t, err) - assert.Equal(t, expected, []swarm.NetworkAttachmentConfig(sortedConfigs)) + assert.Check(t, err) + assert.Check(t, is.DeepEqual(expected, []swarm.NetworkAttachmentConfig(sortedConfigs))) } func TestConvertServiceNetworksCustomDefault(t *testing.T) { @@ -273,8 +273,8 @@ func TestConvertServiceNetworksCustomDefault(t *testing.T) { }, } - assert.NoError(t, err) - assert.Equal(t, expected, []swarm.NetworkAttachmentConfig(configs)) + assert.Check(t, err) + assert.Check(t, is.DeepEqual(expected, []swarm.NetworkAttachmentConfig(configs))) } type byTargetSort []swarm.NetworkAttachmentConfig @@ -294,8 +294,8 @@ func (s byTargetSort) Swap(i, j int) { func TestConvertDNSConfigEmpty(t *testing.T) { dnsConfig, err := convertDNSConfig(nil, nil) - assert.NoError(t, err) - assert.Equal(t, (*swarm.DNSConfig)(nil), dnsConfig) + assert.Check(t, err) + assert.Check(t, is.DeepEqual((*swarm.DNSConfig)(nil), dnsConfig)) } var ( @@ -305,74 +305,74 @@ var ( func TestConvertDNSConfigAll(t *testing.T) { dnsConfig, err := convertDNSConfig(nameservers, search) - assert.NoError(t, err) - assert.Equal(t, &swarm.DNSConfig{ + assert.Check(t, err) + assert.Check(t, is.DeepEqual(&swarm.DNSConfig{ Nameservers: nameservers, Search: search, - }, dnsConfig) + }, dnsConfig)) } func TestConvertDNSConfigNameservers(t *testing.T) { dnsConfig, err := convertDNSConfig(nameservers, nil) - assert.NoError(t, err) - assert.Equal(t, &swarm.DNSConfig{ + assert.Check(t, err) + assert.Check(t, is.DeepEqual(&swarm.DNSConfig{ Nameservers: nameservers, Search: nil, - }, dnsConfig) + }, dnsConfig)) } func TestConvertDNSConfigSearch(t *testing.T) { dnsConfig, err := convertDNSConfig(nil, search) - assert.NoError(t, err) - assert.Equal(t, &swarm.DNSConfig{ + assert.Check(t, err) + assert.Check(t, is.DeepEqual(&swarm.DNSConfig{ Nameservers: nil, Search: search, - }, dnsConfig) + }, dnsConfig)) } func TestConvertCredentialSpec(t *testing.T) { swarmSpec, err := convertCredentialSpec(composetypes.CredentialSpecConfig{}) - assert.NoError(t, err) - assert.Nil(t, swarmSpec) + assert.Check(t, err) + assert.Check(t, is.Nil(swarmSpec)) swarmSpec, err = convertCredentialSpec(composetypes.CredentialSpecConfig{ File: "/foo", }) - assert.NoError(t, err) - assert.Equal(t, swarmSpec.File, "/foo") - assert.Equal(t, swarmSpec.Registry, "") + assert.Check(t, err) + assert.Check(t, is.Equal(swarmSpec.File, "/foo")) + assert.Check(t, is.Equal(swarmSpec.Registry, "")) swarmSpec, err = convertCredentialSpec(composetypes.CredentialSpecConfig{ Registry: "foo", }) - assert.NoError(t, err) - assert.Equal(t, swarmSpec.File, "") - assert.Equal(t, swarmSpec.Registry, "foo") + assert.Check(t, err) + assert.Check(t, is.Equal(swarmSpec.File, "")) + assert.Check(t, is.Equal(swarmSpec.Registry, "foo")) swarmSpec, err = convertCredentialSpec(composetypes.CredentialSpecConfig{ File: "/asdf", Registry: "foo", }) - assert.Error(t, err) - assert.Nil(t, swarmSpec) + assert.Check(t, is.ErrorContains(err, "")) + assert.Check(t, is.Nil(swarmSpec)) } func TestConvertUpdateConfigOrder(t *testing.T) { // test default behavior updateConfig := convertUpdateConfig(&composetypes.UpdateConfig{}) - assert.Equal(t, "", updateConfig.Order) + assert.Check(t, is.Equal("", updateConfig.Order)) // test start-first updateConfig = convertUpdateConfig(&composetypes.UpdateConfig{ Order: "start-first", }) - assert.Equal(t, updateConfig.Order, "start-first") + assert.Check(t, is.Equal(updateConfig.Order, "start-first")) // test stop-first updateConfig = convertUpdateConfig(&composetypes.UpdateConfig{ Order: "stop-first", }) - assert.Equal(t, updateConfig.Order, "stop-first") + assert.Check(t, is.Equal(updateConfig.Order, "stop-first")) } func TestConvertFileObject(t *testing.T) { @@ -385,7 +385,7 @@ func TestConvertFileObject(t *testing.T) { Mode: uint32Ptr(0644), } swarmRef, err := convertFileObject(namespace, config, lookupConfig) - require.NoError(t, err) + assert.NilError(t, err) expected := swarmReferenceObject{ Name: "testing_source", @@ -396,7 +396,7 @@ func TestConvertFileObject(t *testing.T) { Mode: os.FileMode(0644), }, } - assert.Equal(t, expected, swarmRef) + assert.Check(t, is.DeepEqual(expected, swarmRef)) } func lookupConfig(key string) (composetypes.FileObjectConfig, error) { @@ -410,7 +410,7 @@ func TestConvertFileObjectDefaults(t *testing.T) { namespace := NewNamespace("testing") config := composetypes.FileReferenceConfig{Source: "source"} swarmRef, err := convertFileObject(namespace, config, lookupConfig) - require.NoError(t, err) + assert.NilError(t, err) expected := swarmReferenceObject{ Name: "testing_source", @@ -421,7 +421,7 @@ func TestConvertFileObjectDefaults(t *testing.T) { Mode: os.FileMode(0444), }, } - assert.Equal(t, expected, swarmRef) + assert.Check(t, is.DeepEqual(expected, swarmRef)) } func TestServiceConvertsIsolation(t *testing.T) { @@ -429,8 +429,8 @@ func TestServiceConvertsIsolation(t *testing.T) { Isolation: "hyperv", } result, err := Service("1.35", Namespace{name: "foo"}, src, nil, nil, nil, nil) - require.NoError(t, err) - assert.Equal(t, container.IsolationHyperV, result.TaskTemplate.ContainerSpec.Isolation) + assert.NilError(t, err) + assert.Check(t, is.Equal(container.IsolationHyperV, result.TaskTemplate.ContainerSpec.Isolation)) } func TestConvertServiceSecrets(t *testing.T) { @@ -449,8 +449,8 @@ func TestConvertServiceSecrets(t *testing.T) { } client := &fakeClient{ secretListFunc: func(opts types.SecretListOptions) ([]swarm.Secret, error) { - assert.Contains(t, opts.Filters.Get("name"), "foo_secret") - assert.Contains(t, opts.Filters.Get("name"), "bar_secret") + assert.Check(t, is.Contains(opts.Filters.Get("name"), "foo_secret")) + assert.Check(t, is.Contains(opts.Filters.Get("name"), "bar_secret")) return []swarm.Secret{ {Spec: swarm.SecretSpec{Annotations: swarm.Annotations{Name: "foo_secret"}}}, {Spec: swarm.SecretSpec{Annotations: swarm.Annotations{Name: "bar_secret"}}}, @@ -458,7 +458,7 @@ func TestConvertServiceSecrets(t *testing.T) { }, } refs, err := convertServiceSecrets(client, namespace, secrets, secretSpecs) - require.NoError(t, err) + assert.NilError(t, err) expected := []*swarm.SecretReference{ { SecretName: "bar_secret", @@ -479,7 +479,7 @@ func TestConvertServiceSecrets(t *testing.T) { }, }, } - require.Equal(t, expected, refs) + assert.DeepEqual(t, expected, refs) } func TestConvertServiceConfigs(t *testing.T) { @@ -498,8 +498,8 @@ func TestConvertServiceConfigs(t *testing.T) { } client := &fakeClient{ configListFunc: func(opts types.ConfigListOptions) ([]swarm.Config, error) { - assert.Contains(t, opts.Filters.Get("name"), "foo_config") - assert.Contains(t, opts.Filters.Get("name"), "bar_config") + assert.Check(t, is.Contains(opts.Filters.Get("name"), "foo_config")) + assert.Check(t, is.Contains(opts.Filters.Get("name"), "bar_config")) return []swarm.Config{ {Spec: swarm.ConfigSpec{Annotations: swarm.Annotations{Name: "foo_config"}}}, {Spec: swarm.ConfigSpec{Annotations: swarm.Annotations{Name: "bar_config"}}}, @@ -507,7 +507,7 @@ func TestConvertServiceConfigs(t *testing.T) { }, } refs, err := convertServiceConfigObjs(client, namespace, configs, configSpecs) - require.NoError(t, err) + assert.NilError(t, err) expected := []*swarm.ConfigReference{ { ConfigName: "bar_config", @@ -528,7 +528,7 @@ func TestConvertServiceConfigs(t *testing.T) { }, }, } - require.Equal(t, expected, refs) + assert.DeepEqual(t, expected, refs) } type fakeClient struct { diff --git a/cli/compose/convert/volume_test.go b/cli/compose/convert/volume_test.go index 1603e8453a..0cb3e72342 100644 --- a/cli/compose/convert/volume_test.go +++ b/cli/compose/convert/volume_test.go @@ -5,7 +5,8 @@ import ( composetypes "github.com/docker/cli/cli/compose/types" "github.com/docker/docker/api/types/mount" - "github.com/stretchr/testify/assert" + "github.com/gotestyourself/gotestyourself/assert" + is "github.com/gotestyourself/gotestyourself/assert/cmp" ) func TestConvertVolumeToMountAnonymousVolume(t *testing.T) { @@ -18,8 +19,8 @@ func TestConvertVolumeToMountAnonymousVolume(t *testing.T) { Target: "/foo/bar", } mount, err := convertVolumeToMount(config, volumes{}, NewNamespace("foo")) - assert.NoError(t, err) - assert.Equal(t, expected, mount) + assert.Check(t, err) + assert.Check(t, is.DeepEqual(expected, mount)) } func TestConvertVolumeToMountAnonymousBind(t *testing.T) { @@ -31,7 +32,7 @@ func TestConvertVolumeToMountAnonymousBind(t *testing.T) { }, } _, err := convertVolumeToMount(config, volumes{}, NewNamespace("foo")) - assert.EqualError(t, err, "invalid bind source, source cannot be empty") + assert.Check(t, is.Error(err, "invalid bind source, source cannot be empty")) } func TestConvertVolumeToMountUnapprovedType(t *testing.T) { @@ -40,7 +41,7 @@ func TestConvertVolumeToMountUnapprovedType(t *testing.T) { Target: "/foo/bar", } _, err := convertVolumeToMount(config, volumes{}, NewNamespace("foo")) - assert.EqualError(t, err, "volume type must be volume, bind, or tmpfs") + assert.Check(t, is.Error(err, "volume type must be volume, bind, or tmpfs")) } func TestConvertVolumeToMountConflictingOptionsBindInVolume(t *testing.T) { @@ -55,7 +56,7 @@ func TestConvertVolumeToMountConflictingOptionsBindInVolume(t *testing.T) { }, } _, err := convertVolumeToMount(config, volumes{}, namespace) - assert.EqualError(t, err, "bind options are incompatible with type volume") + assert.Check(t, is.Error(err, "bind options are incompatible with type volume")) } func TestConvertVolumeToMountConflictingOptionsTmpfsInVolume(t *testing.T) { @@ -70,7 +71,7 @@ func TestConvertVolumeToMountConflictingOptionsTmpfsInVolume(t *testing.T) { }, } _, err := convertVolumeToMount(config, volumes{}, namespace) - assert.EqualError(t, err, "tmpfs options are incompatible with type volume") + assert.Check(t, is.Error(err, "tmpfs options are incompatible with type volume")) } func TestConvertVolumeToMountConflictingOptionsVolumeInBind(t *testing.T) { @@ -85,7 +86,7 @@ func TestConvertVolumeToMountConflictingOptionsVolumeInBind(t *testing.T) { }, } _, err := convertVolumeToMount(config, volumes{}, namespace) - assert.EqualError(t, err, "volume options are incompatible with type bind") + assert.Check(t, is.Error(err, "volume options are incompatible with type bind")) } func TestConvertVolumeToMountConflictingOptionsTmpfsInBind(t *testing.T) { @@ -100,7 +101,7 @@ func TestConvertVolumeToMountConflictingOptionsTmpfsInBind(t *testing.T) { }, } _, err := convertVolumeToMount(config, volumes{}, namespace) - assert.EqualError(t, err, "tmpfs options are incompatible with type bind") + assert.Check(t, is.Error(err, "tmpfs options are incompatible with type bind")) } func TestConvertVolumeToMountConflictingOptionsBindInTmpfs(t *testing.T) { @@ -114,7 +115,7 @@ func TestConvertVolumeToMountConflictingOptionsBindInTmpfs(t *testing.T) { }, } _, err := convertVolumeToMount(config, volumes{}, namespace) - assert.EqualError(t, err, "bind options are incompatible with type tmpfs") + assert.Check(t, is.Error(err, "bind options are incompatible with type tmpfs")) } func TestConvertVolumeToMountConflictingOptionsVolumeInTmpfs(t *testing.T) { @@ -128,7 +129,7 @@ func TestConvertVolumeToMountConflictingOptionsVolumeInTmpfs(t *testing.T) { }, } _, err := convertVolumeToMount(config, volumes{}, namespace) - assert.EqualError(t, err, "volume options are incompatible with type tmpfs") + assert.Check(t, is.Error(err, "volume options are incompatible with type tmpfs")) } func TestConvertVolumeToMountNamedVolume(t *testing.T) { @@ -173,8 +174,8 @@ func TestConvertVolumeToMountNamedVolume(t *testing.T) { }, } mount, err := convertVolumeToMount(config, stackVolumes, namespace) - assert.NoError(t, err) - assert.Equal(t, expected, mount) + assert.Check(t, err) + assert.Check(t, is.DeepEqual(expected, mount)) } func TestConvertVolumeToMountNamedVolumeWithNameCustomizd(t *testing.T) { @@ -220,8 +221,8 @@ func TestConvertVolumeToMountNamedVolumeWithNameCustomizd(t *testing.T) { }, } mount, err := convertVolumeToMount(config, stackVolumes, namespace) - assert.NoError(t, err) - assert.Equal(t, expected, mount) + assert.Check(t, err) + assert.Check(t, is.DeepEqual(expected, mount)) } func TestConvertVolumeToMountNamedVolumeExternal(t *testing.T) { @@ -244,8 +245,8 @@ func TestConvertVolumeToMountNamedVolumeExternal(t *testing.T) { Target: "/foo", } mount, err := convertVolumeToMount(config, stackVolumes, namespace) - assert.NoError(t, err) - assert.Equal(t, expected, mount) + assert.Check(t, err) + assert.Check(t, is.DeepEqual(expected, mount)) } func TestConvertVolumeToMountNamedVolumeExternalNoCopy(t *testing.T) { @@ -273,8 +274,8 @@ func TestConvertVolumeToMountNamedVolumeExternalNoCopy(t *testing.T) { }, } mount, err := convertVolumeToMount(config, stackVolumes, namespace) - assert.NoError(t, err) - assert.Equal(t, expected, mount) + assert.Check(t, err) + assert.Check(t, is.DeepEqual(expected, mount)) } func TestConvertVolumeToMountBind(t *testing.T) { @@ -295,8 +296,8 @@ func TestConvertVolumeToMountBind(t *testing.T) { Bind: &composetypes.ServiceVolumeBind{Propagation: "shared"}, } mount, err := convertVolumeToMount(config, stackVolumes, namespace) - assert.NoError(t, err) - assert.Equal(t, expected, mount) + assert.Check(t, err) + assert.Check(t, is.DeepEqual(expected, mount)) } func TestConvertVolumeToMountVolumeDoesNotExist(t *testing.T) { @@ -308,7 +309,7 @@ func TestConvertVolumeToMountVolumeDoesNotExist(t *testing.T) { ReadOnly: true, } _, err := convertVolumeToMount(config, volumes{}, namespace) - assert.EqualError(t, err, "undefined volume \"unknown\"") + assert.Check(t, is.Error(err, "undefined volume \"unknown\"")) } func TestConvertTmpfsToMountVolume(t *testing.T) { @@ -325,8 +326,8 @@ func TestConvertTmpfsToMountVolume(t *testing.T) { TmpfsOptions: &mount.TmpfsOptions{SizeBytes: 1000}, } mount, err := convertVolumeToMount(config, volumes{}, NewNamespace("foo")) - assert.NoError(t, err) - assert.Equal(t, expected, mount) + assert.Check(t, err) + assert.Check(t, is.DeepEqual(expected, mount)) } func TestConvertTmpfsToMountVolumeWithSource(t *testing.T) { @@ -340,5 +341,5 @@ func TestConvertTmpfsToMountVolumeWithSource(t *testing.T) { } _, err := convertVolumeToMount(config, volumes{}, NewNamespace("foo")) - assert.EqualError(t, err, "invalid tmpfs source, source must be empty") + assert.Check(t, is.Error(err, "invalid tmpfs source, source must be empty")) } diff --git a/cli/compose/interpolation/interpolation_test.go b/cli/compose/interpolation/interpolation_test.go index 8f5d50db65..63e078c1d5 100644 --- a/cli/compose/interpolation/interpolation_test.go +++ b/cli/compose/interpolation/interpolation_test.go @@ -5,8 +5,9 @@ import ( "strconv" + "github.com/gotestyourself/gotestyourself/assert" + is "github.com/gotestyourself/gotestyourself/assert/cmp" "github.com/gotestyourself/gotestyourself/env" - "github.com/stretchr/testify/assert" ) var defaults = map[string]string{ @@ -46,8 +47,8 @@ func TestInterpolate(t *testing.T) { }, } result, err := Interpolate(services, Options{LookupValue: defaultMapping}) - assert.NoError(t, err) - assert.Equal(t, expected, result) + assert.Check(t, err) + assert.Check(t, is.DeepEqual(expected, result)) } func TestInvalidInterpolation(t *testing.T) { @@ -57,7 +58,7 @@ func TestInvalidInterpolation(t *testing.T) { }, } _, err := Interpolate(services, Options{LookupValue: defaultMapping}) - assert.EqualError(t, err, `invalid interpolation format for servicea.image: "${". You may need to escape any $ with another $.`) + assert.Check(t, is.Error(err, `invalid interpolation format for servicea.image: "${". You may need to escape any $ with another $.`)) } func TestInterpolateWithDefaults(t *testing.T) { @@ -74,8 +75,8 @@ func TestInterpolateWithDefaults(t *testing.T) { }, } result, err := Interpolate(config, Options{}) - assert.NoError(t, err) - assert.Equal(t, expected, result) + assert.Check(t, err) + assert.Check(t, is.DeepEqual(expected, result)) } func TestInterpolateWithCast(t *testing.T) { @@ -91,13 +92,13 @@ func TestInterpolateWithCast(t *testing.T) { LookupValue: defaultMapping, TypeCastMapping: map[Path]Cast{NewPath(PathMatchAll, "replicas"): toInt}, }) - assert.NoError(t, err) + assert.Check(t, err) expected := map[string]interface{}{ "foo": map[string]interface{}{ "replicas": 5, }, } - assert.Equal(t, expected, result) + assert.Check(t, is.DeepEqual(expected, result)) } func TestPathMatches(t *testing.T) { @@ -141,6 +142,6 @@ func TestPathMatches(t *testing.T) { }, } for _, testcase := range testcases { - assert.Equal(t, testcase.expected, testcase.path.matches(testcase.pattern)) + assert.Check(t, is.Equal(testcase.expected, testcase.path.matches(testcase.pattern))) } } diff --git a/cli/compose/loader/loader_test.go b/cli/compose/loader/loader_test.go index 09d3744e84..93f87cefa8 100644 --- a/cli/compose/loader/loader_test.go +++ b/cli/compose/loader/loader_test.go @@ -2,17 +2,17 @@ package loader import ( "bytes" - "fmt" "io/ioutil" "os" + "reflect" "sort" "testing" "time" "github.com/docker/cli/cli/compose/types" + "github.com/gotestyourself/gotestyourself/assert" + is "github.com/gotestyourself/gotestyourself/assert/cmp" "github.com/sirupsen/logrus" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" ) func buildConfigDetails(source map[string]interface{}, env map[string]string) types.ConfigDetails { @@ -168,17 +168,17 @@ var sampleConfig = types.Config{ func TestParseYAML(t *testing.T) { dict, err := ParseYAML([]byte(sampleYAML)) - require.NoError(t, err) - assert.Equal(t, sampleDict, dict) + assert.NilError(t, err) + assert.Check(t, is.DeepEqual(sampleDict, dict)) } func TestLoad(t *testing.T) { actual, err := Load(buildConfigDetails(sampleDict, nil)) - require.NoError(t, err) - assert.Equal(t, sampleConfig.Version, actual.Version) - assert.Equal(t, serviceSort(sampleConfig.Services), serviceSort(actual.Services)) - assert.Equal(t, sampleConfig.Networks, actual.Networks) - assert.Equal(t, sampleConfig.Volumes, actual.Volumes) + assert.NilError(t, err) + assert.Check(t, is.Equal(sampleConfig.Version, actual.Version)) + assert.Check(t, is.DeepEqual(serviceSort(sampleConfig.Services), serviceSort(actual.Services))) + assert.Check(t, is.DeepEqual(sampleConfig.Networks, actual.Networks)) + assert.Check(t, is.DeepEqual(sampleConfig.Volumes, actual.Volumes)) } func TestLoadV31(t *testing.T) { @@ -192,9 +192,9 @@ secrets: super: external: true `) - require.NoError(t, err) - assert.Len(t, actual.Services, 1) - assert.Len(t, actual.Secrets, 1) + assert.NilError(t, err) + assert.Check(t, is.Len(actual.Services, 1)) + assert.Check(t, is.Len(actual.Secrets, 1)) } func TestLoadV33(t *testing.T) { @@ -210,32 +210,29 @@ configs: super: external: true `) - require.NoError(t, err) - require.Len(t, actual.Services, 1) - assert.Equal(t, actual.Services[0].CredentialSpec.File, "/foo") - require.Len(t, actual.Configs, 1) + assert.NilError(t, err) + assert.Assert(t, is.Len(actual.Services, 1)) + assert.Check(t, is.Equal(actual.Services[0].CredentialSpec.File, "/foo")) + assert.Assert(t, is.Len(actual.Configs, 1)) } func TestParseAndLoad(t *testing.T) { actual, err := loadYAML(sampleYAML) - require.NoError(t, err) - assert.Equal(t, serviceSort(sampleConfig.Services), serviceSort(actual.Services)) - assert.Equal(t, sampleConfig.Networks, actual.Networks) - assert.Equal(t, sampleConfig.Volumes, actual.Volumes) + assert.NilError(t, err) + assert.Check(t, is.DeepEqual(serviceSort(sampleConfig.Services), serviceSort(actual.Services))) + assert.Check(t, is.DeepEqual(sampleConfig.Networks, actual.Networks)) + assert.Check(t, is.DeepEqual(sampleConfig.Volumes, actual.Volumes)) } func TestInvalidTopLevelObjectType(t *testing.T) { _, err := loadYAML("1") - require.Error(t, err) - assert.Contains(t, err.Error(), "Top-level object must be a mapping") + assert.ErrorContains(t, err, "Top-level object must be a mapping") _, err = loadYAML("\"hello\"") - require.Error(t, err) - assert.Contains(t, err.Error(), "Top-level object must be a mapping") + assert.ErrorContains(t, err, "Top-level object must be a mapping") _, err = loadYAML("[\"hello\"]") - require.Error(t, err) - assert.Contains(t, err.Error(), "Top-level object must be a mapping") + assert.ErrorContains(t, err, "Top-level object must be a mapping") } func TestNonStringKeys(t *testing.T) { @@ -245,8 +242,7 @@ version: "3" foo: image: busybox `) - require.Error(t, err) - assert.Contains(t, err.Error(), "Non-string key at top level: 123") + assert.ErrorContains(t, err, "Non-string key at top level: 123") _, err = loadYAML(` version: "3" @@ -256,8 +252,7 @@ services: 123: image: busybox `) - require.Error(t, err) - assert.Contains(t, err.Error(), "Non-string key in services: 123") + assert.ErrorContains(t, err, "Non-string key in services: 123") _, err = loadYAML(` version: "3" @@ -270,8 +265,7 @@ networks: config: - 123: oh dear `) - require.Error(t, err) - assert.Contains(t, err.Error(), "Non-string key in networks.default.ipam.config[0]: 123") + assert.ErrorContains(t, err, "Non-string key in networks.default.ipam.config[0]: 123") _, err = loadYAML(` version: "3" @@ -281,8 +275,7 @@ services: environment: 1: FOO `) - require.Error(t, err) - assert.Contains(t, err.Error(), "Non-string key in services.dict-env.environment: 1") + assert.ErrorContains(t, err, "Non-string key in services.dict-env.environment: 1") } func TestSupportedVersion(t *testing.T) { @@ -292,7 +285,7 @@ services: foo: image: busybox `) - require.NoError(t, err) + assert.NilError(t, err) _, err = loadYAML(` version: "3.0" @@ -300,7 +293,7 @@ services: foo: image: busybox `) - require.NoError(t, err) + assert.NilError(t, err) } func TestUnsupportedVersion(t *testing.T) { @@ -310,8 +303,7 @@ services: foo: image: busybox `) - require.Error(t, err) - assert.Contains(t, err.Error(), "version") + assert.ErrorContains(t, err, "version") _, err = loadYAML(` version: "2.0" @@ -319,8 +311,7 @@ services: foo: image: busybox `) - require.Error(t, err) - assert.Contains(t, err.Error(), "version") + assert.ErrorContains(t, err, "version") } func TestInvalidVersion(t *testing.T) { @@ -330,8 +321,7 @@ services: foo: image: busybox `) - require.Error(t, err) - assert.Contains(t, err.Error(), "version must be a string") + assert.ErrorContains(t, err, "version must be a string") } func TestV1Unsupported(t *testing.T) { @@ -339,7 +329,7 @@ func TestV1Unsupported(t *testing.T) { foo: image: busybox `) - assert.Error(t, err) + assert.ErrorContains(t, err, "unsupported Compose file version: 1.0") } func TestNonMappingObject(t *testing.T) { @@ -349,16 +339,14 @@ services: - foo: image: busybox `) - require.Error(t, err) - assert.Contains(t, err.Error(), "services must be a mapping") + assert.ErrorContains(t, err, "services must be a mapping") _, err = loadYAML(` version: "3" services: foo: busybox `) - require.Error(t, err) - assert.Contains(t, err.Error(), "services.foo must be a mapping") + assert.ErrorContains(t, err, "services.foo must be a mapping") _, err = loadYAML(` version: "3" @@ -366,16 +354,14 @@ networks: - default: driver: bridge `) - require.Error(t, err) - assert.Contains(t, err.Error(), "networks must be a mapping") + assert.ErrorContains(t, err, "networks must be a mapping") _, err = loadYAML(` version: "3" networks: default: bridge `) - require.Error(t, err) - assert.Contains(t, err.Error(), "networks.default must be a mapping") + assert.ErrorContains(t, err, "networks.default must be a mapping") _, err = loadYAML(` version: "3" @@ -383,16 +369,14 @@ volumes: - data: driver: local `) - require.Error(t, err) - assert.Contains(t, err.Error(), "volumes must be a mapping") + assert.ErrorContains(t, err, "volumes must be a mapping") _, err = loadYAML(` version: "3" volumes: data: local `) - require.Error(t, err) - assert.Contains(t, err.Error(), "volumes.data must be a mapping") + assert.ErrorContains(t, err, "volumes.data must be a mapping") } func TestNonStringImage(t *testing.T) { @@ -402,8 +386,7 @@ services: foo: image: ["busybox", "latest"] `) - require.Error(t, err) - assert.Contains(t, err.Error(), "services.foo.image must be a string") + assert.ErrorContains(t, err, "services.foo.image must be a string") } func TestLoadWithEnvironment(t *testing.T) { @@ -427,7 +410,7 @@ services: - QUX= - QUUX `, map[string]string{"QUX": "qux"}) - assert.NoError(t, err) + assert.Check(t, err) expected := types.MappingWithEquals{ "FOO": strPtr("1"), @@ -437,10 +420,10 @@ services: "QUUX": nil, } - assert.Equal(t, 2, len(config.Services)) + assert.Check(t, is.Equal(2, len(config.Services))) for _, service := range config.Services { - assert.Equal(t, expected, service.Environment) + assert.Check(t, is.DeepEqual(expected, service.Environment)) } } @@ -453,8 +436,7 @@ services: environment: FOO: ["1"] `) - require.Error(t, err) - assert.Contains(t, err.Error(), "services.dict-env.environment.FOO must be a string, number or null") + assert.ErrorContains(t, err, "services.dict-env.environment.FOO must be a string, number or null") } func TestInvalidEnvironmentObject(t *testing.T) { @@ -465,8 +447,7 @@ services: image: busybox environment: "FOO=1" `) - require.Error(t, err) - assert.Contains(t, err.Error(), "services.dict-env.environment must be a mapping") + assert.ErrorContains(t, err, "services.dict-env.environment must be a mapping") } func TestLoadWithEnvironmentInterpolation(t *testing.T) { @@ -492,7 +473,7 @@ volumes: "FOO": "foo", }) - require.NoError(t, err) + assert.NilError(t, err) expectedLabels := types.Labels{ "home1": home, @@ -501,9 +482,9 @@ volumes: "default": "default", } - assert.Equal(t, expectedLabels, config.Services[0].Labels) - assert.Equal(t, home, config.Networks["test"].Driver) - assert.Equal(t, home, config.Volumes["test"].Driver) + assert.Check(t, is.DeepEqual(expectedLabels, config.Services[0].Labels)) + assert.Check(t, is.Equal(home, config.Networks["test"].Driver)) + assert.Check(t, is.Equal(home, config.Volumes["test"].Driver)) } func TestLoadWithInterpolationCastFull(t *testing.T) { @@ -564,7 +545,7 @@ networks: attachable: $thebool `)) - require.NoError(t, err) + assert.NilError(t, err) env := map[string]string{ "theint": "555", "thefloat": "3.14", @@ -572,7 +553,7 @@ networks: } config, err := Load(buildConfigDetails(dict, env)) - require.NoError(t, err) + assert.NilError(t, err) expected := &types.Config{ Filename: "filename.yml", Version: "3.4", @@ -648,7 +629,7 @@ networks: }, } - assert.Equal(t, expected, config) + assert.Check(t, is.DeepEqual(expected, config)) } func TestUnsupportedProperties(t *testing.T) { @@ -667,15 +648,15 @@ services: build: context: ./db `)) - require.NoError(t, err) + assert.NilError(t, err) configDetails := buildConfigDetails(dict, nil) _, err = Load(configDetails) - require.NoError(t, err) + assert.NilError(t, err) unsupported := GetUnsupportedProperties(dict) - assert.Equal(t, []string{"build", "links", "pid"}, unsupported) + assert.Check(t, is.DeepEqual([]string{"build", "links", "pid"}, unsupported)) } func TestBuildProperties(t *testing.T) { @@ -692,10 +673,10 @@ services: build: context: ./db `)) - require.NoError(t, err) + assert.NilError(t, err) configDetails := buildConfigDetails(dict, nil) _, err = Load(configDetails) - require.NoError(t, err) + assert.NilError(t, err) } func TestDeprecatedProperties(t *testing.T) { @@ -710,17 +691,17 @@ services: container_name: db expose: ["5434"] `)) - require.NoError(t, err) + assert.NilError(t, err) configDetails := buildConfigDetails(dict, nil) _, err = Load(configDetails) - require.NoError(t, err) + assert.NilError(t, err) deprecated := GetDeprecatedProperties(dict) - assert.Len(t, deprecated, 2) - assert.Contains(t, deprecated, "container_name") - assert.Contains(t, deprecated, "expose") + assert.Check(t, is.Len(deprecated, 2)) + assert.Check(t, is.Contains(deprecated, "container_name")) + assert.Check(t, is.Contains(deprecated, "expose")) } func TestForbiddenProperties(t *testing.T) { @@ -737,14 +718,12 @@ services: service: foo `) - require.Error(t, err) - assert.IsType(t, &ForbiddenPropertiesError{}, err) - fmt.Println(err) - forbidden := err.(*ForbiddenPropertiesError).Properties + assert.ErrorType(t, err, reflect.TypeOf(&ForbiddenPropertiesError{})) - assert.Len(t, forbidden, 2) - assert.Contains(t, forbidden, "volume_driver") - assert.Contains(t, forbidden, "extends") + props := err.(*ForbiddenPropertiesError).Properties + assert.Check(t, is.Len(props, 2)) + assert.Check(t, is.Contains(props, "volume_driver")) + assert.Check(t, is.Contains(props, "extends")) } func TestInvalidResource(t *testing.T) { @@ -758,8 +737,7 @@ func TestInvalidResource(t *testing.T) { impossible: x: 1 `) - require.Error(t, err) - assert.Contains(t, err.Error(), "Additional property impossible is not allowed") + assert.ErrorContains(t, err, "Additional property impossible is not allowed") } func TestInvalidExternalAndDriverCombination(t *testing.T) { @@ -771,9 +749,8 @@ volumes: driver: foobar `) - require.Error(t, err) - assert.Contains(t, err.Error(), "conflicting parameters \"external\" and \"driver\" specified for volume") - assert.Contains(t, err.Error(), "external_volume") + assert.ErrorContains(t, err, "conflicting parameters \"external\" and \"driver\" specified for volume") + assert.ErrorContains(t, err, "external_volume") } func TestInvalidExternalAndDirverOptsCombination(t *testing.T) { @@ -786,9 +763,8 @@ volumes: beep: boop `) - require.Error(t, err) - assert.Contains(t, err.Error(), "conflicting parameters \"external\" and \"driver_opts\" specified for volume") - assert.Contains(t, err.Error(), "external_volume") + assert.ErrorContains(t, err, "conflicting parameters \"external\" and \"driver_opts\" specified for volume") + assert.ErrorContains(t, err, "external_volume") } func TestInvalidExternalAndLabelsCombination(t *testing.T) { @@ -801,9 +777,8 @@ volumes: - beep=boop `) - require.Error(t, err) - assert.Contains(t, err.Error(), "conflicting parameters \"external\" and \"labels\" specified for volume") - assert.Contains(t, err.Error(), "external_volume") + assert.ErrorContains(t, err, "conflicting parameters \"external\" and \"labels\" specified for volume") + assert.ErrorContains(t, err, "external_volume") } func TestLoadVolumeInvalidExternalNameAndNameCombination(t *testing.T) { @@ -816,9 +791,8 @@ volumes: name: external_name `) - require.Error(t, err) - assert.Contains(t, err.Error(), "volume.external.name and volume.name conflict; only use volume.name") - assert.Contains(t, err.Error(), "external_volume") + assert.ErrorContains(t, err, "volume.external.name and volume.name conflict; only use volume.name") + assert.ErrorContains(t, err, "external_volume") } func durationPtr(value time.Duration) *time.Duration { @@ -835,21 +809,21 @@ func uint32Ptr(value uint32) *uint32 { func TestFullExample(t *testing.T) { bytes, err := ioutil.ReadFile("full-example.yml") - require.NoError(t, err) + assert.NilError(t, err) homeDir := "/home/foo" env := map[string]string{"HOME": homeDir, "QUX": "qux_from_environment"} config, err := loadYAMLWithEnv(string(bytes), env) - require.NoError(t, err) + assert.NilError(t, err) workingDir, err := os.Getwd() - require.NoError(t, err) + assert.NilError(t, err) expectedConfig := fullExampleConfig(workingDir, homeDir) - assert.Equal(t, expectedConfig.Services, config.Services) - assert.Equal(t, expectedConfig.Networks, config.Networks) - assert.Equal(t, expectedConfig.Volumes, config.Volumes) + assert.Check(t, is.DeepEqual(expectedConfig.Services, config.Services)) + assert.Check(t, is.DeepEqual(expectedConfig.Networks, config.Networks)) + assert.Check(t, is.DeepEqual(expectedConfig.Volumes, config.Volumes)) } func TestLoadTmpfsVolume(t *testing.T) { @@ -864,7 +838,7 @@ services: tmpfs: size: 10000 `) - require.NoError(t, err) + assert.NilError(t, err) expected := types.ServiceVolumeConfig{ Target: "/app", @@ -874,9 +848,9 @@ services: }, } - require.Len(t, config.Services, 1) - assert.Len(t, config.Services[0].Volumes, 1) - assert.Equal(t, expected, config.Services[0].Volumes[0]) + assert.Assert(t, is.Len(config.Services, 1)) + assert.Check(t, is.Len(config.Services[0].Volumes, 1)) + assert.Check(t, is.DeepEqual(expected, config.Services[0].Volumes[0])) } func TestLoadTmpfsVolumeAdditionalPropertyNotAllowed(t *testing.T) { @@ -891,8 +865,7 @@ services: tmpfs: size: 10000 `) - require.Error(t, err) - assert.Contains(t, err.Error(), "services.tmpfs.volumes.0 Additional property tmpfs is not allowed") + assert.ErrorContains(t, err, "services.tmpfs.volumes.0 Additional property tmpfs is not allowed") } func TestLoadBindMountSourceMustNotBeEmpty(t *testing.T) { @@ -905,7 +878,7 @@ services: - type: bind target: /app `) - require.EqualError(t, err, `invalid mount config for type "bind": field Source must not be empty`) + assert.Error(t, err, `invalid mount config for type "bind": field Source must not be empty`) } func TestLoadBindMountWithSource(t *testing.T) { @@ -919,10 +892,10 @@ services: target: /app source: "." `) - require.NoError(t, err) + assert.NilError(t, err) workingDir, err := os.Getwd() - require.NoError(t, err) + assert.NilError(t, err) expected := types.ServiceVolumeConfig{ Type: "bind", @@ -930,9 +903,9 @@ services: Target: "/app", } - require.Len(t, config.Services, 1) - assert.Len(t, config.Services[0].Volumes, 1) - assert.Equal(t, expected, config.Services[0].Volumes[0]) + assert.Assert(t, is.Len(config.Services, 1)) + assert.Check(t, is.Len(config.Services[0].Volumes, 1)) + assert.Check(t, is.DeepEqual(expected, config.Services[0].Volumes[0])) } func TestLoadTmpfsVolumeSizeCanBeZero(t *testing.T) { @@ -947,7 +920,7 @@ services: tmpfs: size: 0 `) - require.NoError(t, err) + assert.NilError(t, err) expected := types.ServiceVolumeConfig{ Target: "/app", @@ -955,9 +928,9 @@ services: Tmpfs: &types.ServiceVolumeTmpfs{}, } - require.Len(t, config.Services, 1) - assert.Len(t, config.Services[0].Volumes, 1) - assert.Equal(t, expected, config.Services[0].Volumes[0]) + assert.Assert(t, is.Len(config.Services, 1)) + assert.Check(t, is.Len(config.Services[0].Volumes, 1)) + assert.Check(t, is.DeepEqual(expected, config.Services[0].Volumes[0])) } func TestLoadTmpfsVolumeSizeMustBeGTEQZero(t *testing.T) { @@ -972,8 +945,7 @@ services: tmpfs: size: -1 `) - require.Error(t, err) - assert.Contains(t, err.Error(), "services.tmpfs.volumes.0.tmpfs.size Must be greater than or equal to 0") + assert.ErrorContains(t, err, "services.tmpfs.volumes.0.tmpfs.size Must be greater than or equal to 0") } func TestLoadTmpfsVolumeSizeMustBeInteger(t *testing.T) { @@ -988,8 +960,7 @@ services: tmpfs: size: 0.0001 `) - require.Error(t, err) - assert.Contains(t, err.Error(), "services.tmpfs.volumes.0.tmpfs.size must be a integer") + assert.ErrorContains(t, err, "services.tmpfs.volumes.0.tmpfs.size must be a integer") } func serviceSort(services []types.ServiceConfig) []types.ServiceConfig { @@ -1013,7 +984,7 @@ networks: mynet2: driver: bridge `) - require.NoError(t, err) + assert.NilError(t, err) expected := map[string]types.NetworkConfig{ "mynet1": { @@ -1026,7 +997,7 @@ networks: }, } - assert.Equal(t, expected, config.Networks) + assert.Check(t, is.DeepEqual(expected, config.Networks)) } func TestLoadExpandedPortFormat(t *testing.T) { @@ -1047,7 +1018,7 @@ services: target: 22 published: 10022 `) - require.NoError(t, err) + assert.NilError(t, err) expected := []types.ServicePortConfig{ { @@ -1110,8 +1081,8 @@ services: }, } - assert.Len(t, config.Services, 1) - assert.Equal(t, expected, config.Services[0].Ports) + assert.Check(t, is.Len(config.Services, 1)) + assert.Check(t, is.DeepEqual(expected, config.Services[0].Ports)) } func TestLoadExpandedMountFormat(t *testing.T) { @@ -1128,7 +1099,7 @@ services: volumes: foo: {} `) - require.NoError(t, err) + assert.NilError(t, err) expected := types.ServiceVolumeConfig{ Type: "volume", @@ -1137,9 +1108,9 @@ volumes: ReadOnly: true, } - require.Len(t, config.Services, 1) - assert.Len(t, config.Services[0].Volumes, 1) - assert.Equal(t, expected, config.Services[0].Volumes[0]) + assert.Assert(t, is.Len(config.Services, 1)) + assert.Check(t, is.Len(config.Services[0].Volumes, 1)) + assert.Check(t, is.DeepEqual(expected, config.Services[0].Volumes[0])) } func TestLoadExtraHostsMap(t *testing.T) { @@ -1152,15 +1123,15 @@ services: "zulu": "162.242.195.82" "alpha": "50.31.209.229" `) - require.NoError(t, err) + assert.NilError(t, err) expected := types.HostsList{ "alpha:50.31.209.229", "zulu:162.242.195.82", } - require.Len(t, config.Services, 1) - assert.Equal(t, expected, config.Services[0].ExtraHosts) + assert.Assert(t, is.Len(config.Services, 1)) + assert.Check(t, is.DeepEqual(expected, config.Services[0].ExtraHosts)) } func TestLoadExtraHostsList(t *testing.T) { @@ -1174,7 +1145,7 @@ services: - "alpha:50.31.209.229" - "zulu:ff02::1" `) - require.NoError(t, err) + assert.NilError(t, err) expected := types.HostsList{ "zulu:162.242.195.82", @@ -1182,8 +1153,8 @@ services: "zulu:ff02::1", } - require.Len(t, config.Services, 1) - assert.Equal(t, expected, config.Services[0].ExtraHosts) + assert.Assert(t, is.Len(config.Services, 1)) + assert.Check(t, is.DeepEqual(expected, config.Services[0].ExtraHosts)) } func TestLoadVolumesWarnOnDeprecatedExternalNameVersion34(t *testing.T) { @@ -1198,15 +1169,15 @@ func TestLoadVolumesWarnOnDeprecatedExternalNameVersion34(t *testing.T) { }, } volumes, err := LoadVolumes(source, "3.4") - require.NoError(t, err) + assert.NilError(t, err) expected := map[string]types.VolumeConfig{ "foo": { Name: "oops", External: types.External{External: true}, }, } - assert.Equal(t, expected, volumes) - assert.Contains(t, buf.String(), "volume.external.name is deprecated") + assert.Check(t, is.DeepEqual(expected, volumes)) + assert.Check(t, is.Contains(buf.String(), "volume.external.name is deprecated")) } @@ -1229,15 +1200,15 @@ func TestLoadVolumesWarnOnDeprecatedExternalNameVersion33(t *testing.T) { }, } volumes, err := LoadVolumes(source, "3.3") - require.NoError(t, err) + assert.NilError(t, err) expected := map[string]types.VolumeConfig{ "foo": { Name: "oops", External: types.External{External: true}, }, } - assert.Equal(t, expected, volumes) - assert.Equal(t, "", buf.String()) + assert.Check(t, is.DeepEqual(expected, volumes)) + assert.Check(t, is.Equal("", buf.String())) } func TestLoadV35(t *testing.T) { @@ -1262,11 +1233,11 @@ secrets: name: barqux file: ./full-example.yml `) - require.NoError(t, err) - assert.Len(t, actual.Services, 1) - assert.Len(t, actual.Secrets, 2) - assert.Len(t, actual.Configs, 2) - assert.Equal(t, "process", actual.Services[0].Isolation) + assert.NilError(t, err) + assert.Check(t, is.Len(actual.Services, 1)) + assert.Check(t, is.Len(actual.Secrets, 2)) + assert.Check(t, is.Len(actual.Configs, 2)) + assert.Check(t, is.Equal("process", actual.Services[0].Isolation)) } func TestLoadV35InvalidIsolation(t *testing.T) { @@ -1281,9 +1252,9 @@ configs: super: external: true `) - require.NoError(t, err) - require.Len(t, actual.Services, 1) - assert.Equal(t, "invalid", actual.Services[0].Isolation) + assert.NilError(t, err) + assert.Assert(t, is.Len(actual.Services, 1)) + assert.Check(t, is.Equal("invalid", actual.Services[0].Isolation)) } func TestLoadSecretInvalidExternalNameAndNameCombination(t *testing.T) { @@ -1296,9 +1267,8 @@ secrets: name: external_name `) - require.Error(t, err) - assert.Contains(t, err.Error(), "secret.external.name and secret.name conflict; only use secret.name") - assert.Contains(t, err.Error(), "external_secret") + assert.ErrorContains(t, err, "secret.external.name and secret.name conflict; only use secret.name") + assert.ErrorContains(t, err, "external_secret") } func TestLoadSecretsWarnOnDeprecatedExternalNameVersion35(t *testing.T) { @@ -1316,15 +1286,15 @@ func TestLoadSecretsWarnOnDeprecatedExternalNameVersion35(t *testing.T) { Version: "3.5", } secrets, err := LoadSecrets(source, details) - require.NoError(t, err) + assert.NilError(t, err) expected := map[string]types.SecretConfig{ "foo": { Name: "oops", External: types.External{External: true}, }, } - assert.Equal(t, expected, secrets) - assert.Contains(t, buf.String(), "secret.external.name is deprecated") + assert.Check(t, is.DeepEqual(expected, secrets)) + assert.Check(t, is.Contains(buf.String(), "secret.external.name is deprecated")) } func TestLoadNetworksWarnOnDeprecatedExternalNameVersion35(t *testing.T) { @@ -1339,15 +1309,15 @@ func TestLoadNetworksWarnOnDeprecatedExternalNameVersion35(t *testing.T) { }, } networks, err := LoadNetworks(source, "3.5") - require.NoError(t, err) + assert.NilError(t, err) expected := map[string]types.NetworkConfig{ "foo": { Name: "oops", External: types.External{External: true}, }, } - assert.Equal(t, expected, networks) - assert.Contains(t, buf.String(), "network.external.name is deprecated") + assert.Check(t, is.DeepEqual(expected, networks)) + assert.Check(t, is.Contains(buf.String(), "network.external.name is deprecated")) } @@ -1363,15 +1333,15 @@ func TestLoadNetworksWarnOnDeprecatedExternalNameVersion34(t *testing.T) { }, } networks, err := LoadNetworks(source, "3.4") - require.NoError(t, err) + assert.NilError(t, err) expected := map[string]types.NetworkConfig{ "foo": { Name: "oops", External: types.External{External: true}, }, } - assert.Equal(t, expected, networks) - assert.Equal(t, "", buf.String()) + assert.Check(t, is.DeepEqual(expected, networks)) + assert.Check(t, is.Equal("", buf.String())) } func TestLoadNetworkInvalidExternalNameAndNameCombination(t *testing.T) { @@ -1384,7 +1354,6 @@ networks: name: external_name `) - require.Error(t, err) - assert.Contains(t, err.Error(), "network.external.name and network.name conflict; only use network.name") - assert.Contains(t, err.Error(), "foo") + assert.ErrorContains(t, err, "network.external.name and network.name conflict; only use network.name") + assert.ErrorContains(t, err, "foo") } diff --git a/cli/compose/loader/merge_test.go b/cli/compose/loader/merge_test.go index d9e8599359..b039231723 100644 --- a/cli/compose/loader/merge_test.go +++ b/cli/compose/loader/merge_test.go @@ -4,7 +4,7 @@ import ( "testing" "github.com/docker/cli/cli/compose/types" - "github.com/stretchr/testify/require" + "github.com/gotestyourself/gotestyourself/assert" ) func TestLoadTwoDifferentVersion(t *testing.T) { @@ -19,7 +19,7 @@ func TestLoadTwoDifferentVersion(t *testing.T) { }, } _, err := Load(configDetails) - require.EqualError(t, err, "version mismatched between two composefiles : 3.1 and 3.4") + assert.Error(t, err, "version mismatched between two composefiles : 3.1 and 3.4") } func TestLoadLogging(t *testing.T) { @@ -204,8 +204,8 @@ func TestLoadLogging(t *testing.T) { }, } config, err := Load(configDetails) - require.NoError(t, err) - require.Equal(t, &types.Config{ + assert.NilError(t, err) + assert.DeepEqual(t, &types.Config{ Filename: "base.yml", Version: "3.4", Services: []types.ServiceConfig{ @@ -323,8 +323,8 @@ func TestLoadMultipleServicePorts(t *testing.T) { }, } config, err := Load(configDetails) - require.NoError(t, err) - require.Equal(t, &types.Config{ + assert.NilError(t, err) + assert.DeepEqual(t, &types.Config{ Filename: "base.yml", Version: "3.4", Services: []types.ServiceConfig{ @@ -449,8 +449,8 @@ func TestLoadMultipleSecretsConfig(t *testing.T) { }, } config, err := Load(configDetails) - require.NoError(t, err) - require.Equal(t, &types.Config{ + assert.NilError(t, err) + assert.DeepEqual(t, &types.Config{ Filename: "base.yml", Version: "3.4", Services: []types.ServiceConfig{ @@ -575,8 +575,8 @@ func TestLoadMultipleConfigobjsConfig(t *testing.T) { }, } config, err := Load(configDetails) - require.NoError(t, err) - require.Equal(t, &types.Config{ + assert.NilError(t, err) + assert.DeepEqual(t, &types.Config{ Filename: "base.yml", Version: "3.4", Services: []types.ServiceConfig{ @@ -691,8 +691,8 @@ func TestLoadMultipleUlimits(t *testing.T) { }, } config, err := Load(configDetails) - require.NoError(t, err) - require.Equal(t, &types.Config{ + assert.NilError(t, err) + assert.DeepEqual(t, &types.Config{ Filename: "base.yml", Version: "3.4", Services: []types.ServiceConfig{ @@ -810,8 +810,8 @@ func TestLoadMultipleNetworks(t *testing.T) { }, } config, err := Load(configDetails) - require.NoError(t, err) - require.Equal(t, &types.Config{ + assert.NilError(t, err) + assert.DeepEqual(t, &types.Config{ Filename: "base.yml", Version: "3.4", Services: []types.ServiceConfig{ @@ -898,8 +898,8 @@ func TestLoadMultipleConfigs(t *testing.T) { }, } config, err := Load(configDetails) - require.NoError(t, err) - require.Equal(t, &types.Config{ + assert.NilError(t, err) + assert.DeepEqual(t, &types.Config{ Filename: "base.yml", Version: "3.4", Services: []types.ServiceConfig{ diff --git a/cli/compose/loader/types_test.go b/cli/compose/loader/types_test.go index f27539f88f..7ada6a1ab0 100644 --- a/cli/compose/loader/types_test.go +++ b/cli/compose/loader/types_test.go @@ -3,7 +3,8 @@ package loader import ( "testing" - "github.com/stretchr/testify/assert" + "github.com/gotestyourself/gotestyourself/assert" + is "github.com/gotestyourself/gotestyourself/assert/cmp" yaml "gopkg.in/yaml.v2" ) @@ -318,12 +319,12 @@ configs: {} ` actual, err := yaml.Marshal(cfg) - assert.NoError(t, err) - assert.Equal(t, expected, string(actual)) + assert.Check(t, err) + assert.Check(t, is.Equal(expected, string(actual))) // Make sure the expected still dict, err := ParseYAML([]byte("version: '3.6'\n" + expected)) - assert.NoError(t, err) + assert.Check(t, err) _, err = Load(buildConfigDetails(dict, map[string]string{})) - assert.NoError(t, err) + assert.Check(t, err) } diff --git a/cli/compose/loader/volume_test.go b/cli/compose/loader/volume_test.go index 90110133fa..d0a6373d62 100644 --- a/cli/compose/loader/volume_test.go +++ b/cli/compose/loader/volume_test.go @@ -6,16 +6,16 @@ import ( "github.com/docker/cli/cli/compose/types" "github.com/docker/cli/internal/test/testutil" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" + "github.com/gotestyourself/gotestyourself/assert" + is "github.com/gotestyourself/gotestyourself/assert/cmp" ) func TestParseVolumeAnonymousVolume(t *testing.T) { for _, path := range []string{"/path", "/path/foo"} { volume, err := ParseVolume(path) expected := types.ServiceVolumeConfig{Type: "volume", Target: path} - assert.NoError(t, err) - assert.Equal(t, expected, volume) + assert.Check(t, err) + assert.Check(t, is.DeepEqual(expected, volume)) } } @@ -23,22 +23,22 @@ func TestParseVolumeAnonymousVolumeWindows(t *testing.T) { for _, path := range []string{"C:\\path", "Z:\\path\\foo"} { volume, err := ParseVolume(path) expected := types.ServiceVolumeConfig{Type: "volume", Target: path} - assert.NoError(t, err) - assert.Equal(t, expected, volume) + assert.Check(t, err) + assert.Check(t, is.DeepEqual(expected, volume)) } } func TestParseVolumeTooManyColons(t *testing.T) { _, err := ParseVolume("/foo:/foo:ro:foo") - assert.EqualError(t, err, "invalid spec: /foo:/foo:ro:foo: too many colons") + assert.Check(t, is.Error(err, "invalid spec: /foo:/foo:ro:foo: too many colons")) } func TestParseVolumeShortVolumes(t *testing.T) { for _, path := range []string{".", "/a"} { volume, err := ParseVolume(path) expected := types.ServiceVolumeConfig{Type: "volume", Target: path} - assert.NoError(t, err) - assert.Equal(t, expected, volume) + assert.Check(t, err) + assert.Check(t, is.DeepEqual(expected, volume)) } } @@ -57,8 +57,8 @@ func TestParseVolumeBindMount(t *testing.T) { Source: path, Target: "/target", } - assert.NoError(t, err) - assert.Equal(t, expected, volume) + assert.Check(t, err) + assert.Check(t, is.DeepEqual(expected, volume)) } } @@ -75,8 +75,8 @@ func TestParseVolumeRelativeBindMountWindows(t *testing.T) { Source: path, Target: "d:\\target", } - assert.NoError(t, err) - assert.Equal(t, expected, volume) + assert.Check(t, err) + assert.Check(t, is.DeepEqual(expected, volume)) } } @@ -88,8 +88,8 @@ func TestParseVolumeWithBindOptions(t *testing.T) { Target: "/target", Bind: &types.ServiceVolumeBind{Propagation: "slave"}, } - assert.NoError(t, err) - assert.Equal(t, expected, volume) + assert.Check(t, err) + assert.Check(t, is.DeepEqual(expected, volume)) } func TestParseVolumeWithBindOptionsWindows(t *testing.T) { @@ -101,13 +101,13 @@ func TestParseVolumeWithBindOptionsWindows(t *testing.T) { ReadOnly: true, Bind: &types.ServiceVolumeBind{Propagation: "rprivate"}, } - assert.NoError(t, err) - assert.Equal(t, expected, volume) + assert.Check(t, err) + assert.Check(t, is.DeepEqual(expected, volume)) } func TestParseVolumeWithInvalidVolumeOptions(t *testing.T) { _, err := ParseVolume("name:/target:bogus") - assert.NoError(t, err) + assert.Check(t, err) } func TestParseVolumeWithVolumeOptions(t *testing.T) { @@ -118,8 +118,8 @@ func TestParseVolumeWithVolumeOptions(t *testing.T) { Target: "/target", Volume: &types.ServiceVolumeVolume{NoCopy: true}, } - assert.NoError(t, err) - assert.Equal(t, expected, volume) + assert.Check(t, err) + assert.Check(t, is.DeepEqual(expected, volume)) } func TestParseVolumeWithReadOnly(t *testing.T) { @@ -131,8 +131,8 @@ func TestParseVolumeWithReadOnly(t *testing.T) { Target: "/target", ReadOnly: true, } - assert.NoError(t, err) - assert.Equal(t, expected, volume) + assert.Check(t, err) + assert.Check(t, is.DeepEqual(expected, volume)) } } @@ -145,24 +145,24 @@ func TestParseVolumeWithRW(t *testing.T) { Target: "/target", ReadOnly: false, } - assert.NoError(t, err) - assert.Equal(t, expected, volume) + assert.Check(t, err) + assert.Check(t, is.DeepEqual(expected, volume)) } } func TestParseVolumeWindowsNamedPipe(t *testing.T) { volume, err := ParseVolume(`\\.\pipe\docker_engine:\\.\pipe\inside`) - require.NoError(t, err) + assert.NilError(t, err) expected := types.ServiceVolumeConfig{ Type: "bind", Source: `\\.\pipe\docker_engine`, Target: `\\.\pipe\inside`, } - assert.Equal(t, expected, volume) + assert.Check(t, is.DeepEqual(expected, volume)) } func TestIsFilePath(t *testing.T) { - assert.False(t, isFilePath("a界")) + assert.Check(t, !isFilePath("a界")) } // Preserve the test cases for VolumeSplitN @@ -209,7 +209,7 @@ func TestParseVolumeSplitCases(t *testing.T) { expected := len(x.expected) > 1 msg := fmt.Sprintf("Case %d: %s", casenumber, x.input) - assert.Equal(t, expected, parsed.Source != "", msg) + assert.Check(t, is.Equal(expected, parsed.Source != ""), msg) } } diff --git a/cli/compose/schema/schema_test.go b/cli/compose/schema/schema_test.go index bce6276dce..7dd9d296a9 100644 --- a/cli/compose/schema/schema_test.go +++ b/cli/compose/schema/schema_test.go @@ -3,7 +3,7 @@ package schema import ( "testing" - "github.com/stretchr/testify/assert" + "github.com/gotestyourself/gotestyourself/assert" ) type dict map[string]interface{} @@ -18,7 +18,7 @@ func TestValidate(t *testing.T) { }, } - assert.NoError(t, Validate(config, "3.0")) + assert.Check(t, Validate(config, "3.0")) } func TestValidateUndefinedTopLevelOption(t *testing.T) { @@ -32,8 +32,7 @@ func TestValidateUndefinedTopLevelOption(t *testing.T) { } err := Validate(config, "3.0") - assert.Error(t, err) - assert.Contains(t, err.Error(), "Additional property helicopters is not allowed") + assert.ErrorContains(t, err, "Additional property helicopters is not allowed") } func TestValidateAllowsXTopLevelFields(t *testing.T) { @@ -43,7 +42,7 @@ func TestValidateAllowsXTopLevelFields(t *testing.T) { } err := Validate(config, "3.4") - assert.NoError(t, err) + assert.Check(t, err) } func TestValidateSecretConfigNames(t *testing.T) { @@ -62,7 +61,7 @@ func TestValidateSecretConfigNames(t *testing.T) { } err := Validate(config, "3.5") - assert.NoError(t, err) + assert.Check(t, err) } func TestValidateInvalidVersion(t *testing.T) { @@ -76,8 +75,7 @@ func TestValidateInvalidVersion(t *testing.T) { } err := Validate(config, "2.1") - assert.Error(t, err) - assert.Contains(t, err.Error(), "unsupported Compose file version: 2.1") + assert.ErrorContains(t, err, "unsupported Compose file version: 2.1") } type array []interface{} @@ -101,7 +99,7 @@ func TestValidatePlacement(t *testing.T) { }, } - assert.NoError(t, Validate(config, "3.3")) + assert.Check(t, Validate(config, "3.3")) } func TestValidateIsolation(t *testing.T) { @@ -114,5 +112,5 @@ func TestValidateIsolation(t *testing.T) { }, }, } - assert.NoError(t, Validate(config, "3.5")) + assert.Check(t, Validate(config, "3.5")) } diff --git a/cli/compose/template/template_test.go b/cli/compose/template/template_test.go index 4fec57e8e8..7adef7b13a 100644 --- a/cli/compose/template/template_test.go +++ b/cli/compose/template/template_test.go @@ -1,11 +1,11 @@ package template import ( + "reflect" "testing" - "github.com/docker/cli/internal/test/testutil" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" + "github.com/gotestyourself/gotestyourself/assert" + is "github.com/gotestyourself/gotestyourself/assert/cmp" ) var defaults = map[string]string{ @@ -20,14 +20,14 @@ func defaultMapping(name string) (string, bool) { func TestEscaped(t *testing.T) { result, err := Substitute("$${foo}", defaultMapping) - assert.Nil(t, err) - assert.Equal(t, "${foo}", result) + assert.Check(t, err) + assert.Check(t, is.Equal("${foo}", result)) } func TestSubstituteNoMatch(t *testing.T) { result, err := Substitute("foo", defaultMapping) - require.NoError(t, err) - require.Equal(t, "foo", result) + assert.NilError(t, err) + assert.Equal(t, "foo", result) } func TestInvalid(t *testing.T) { @@ -43,51 +43,50 @@ func TestInvalid(t *testing.T) { for _, template := range invalidTemplates { _, err := Substitute(template, defaultMapping) - assert.Error(t, err) - assert.IsType(t, &InvalidTemplateError{}, err) + assert.ErrorContains(t, err, "Invalid template") } } func TestNoValueNoDefault(t *testing.T) { for _, template := range []string{"This ${missing} var", "This ${BAR} var"} { result, err := Substitute(template, defaultMapping) - assert.Nil(t, err) - assert.Equal(t, "This var", result) + assert.Check(t, err) + assert.Check(t, is.Equal("This var", result)) } } func TestValueNoDefault(t *testing.T) { for _, template := range []string{"This $FOO var", "This ${FOO} var"} { result, err := Substitute(template, defaultMapping) - assert.Nil(t, err) - assert.Equal(t, "This first var", result) + assert.Check(t, err) + assert.Check(t, is.Equal("This first var", result)) } } func TestNoValueWithDefault(t *testing.T) { for _, template := range []string{"ok ${missing:-def}", "ok ${missing-def}"} { result, err := Substitute(template, defaultMapping) - assert.Nil(t, err) - assert.Equal(t, "ok def", result) + assert.Check(t, err) + assert.Check(t, is.Equal("ok def", result)) } } func TestEmptyValueWithSoftDefault(t *testing.T) { result, err := Substitute("ok ${BAR:-def}", defaultMapping) - assert.Nil(t, err) - assert.Equal(t, "ok def", result) + assert.Check(t, err) + assert.Check(t, is.Equal("ok def", result)) } func TestEmptyValueWithHardDefault(t *testing.T) { result, err := Substitute("ok ${BAR-def}", defaultMapping) - assert.Nil(t, err) - assert.Equal(t, "ok ", result) + assert.Check(t, err) + assert.Check(t, is.Equal("ok ", result)) } func TestNonAlphanumericDefault(t *testing.T) { result, err := Substitute("ok ${BAR:-/non:-alphanumeric}", defaultMapping) - assert.Nil(t, err) - assert.Equal(t, "ok /non:-alphanumeric", result) + assert.Check(t, err) + assert.Check(t, is.Equal("ok /non:-alphanumeric", result)) } func TestMandatoryVariableErrors(t *testing.T) { @@ -119,9 +118,8 @@ func TestMandatoryVariableErrors(t *testing.T) { for _, tc := range testCases { _, err := Substitute(tc.template, defaultMapping) - assert.Error(t, err) - assert.IsType(t, &InvalidTemplateError{}, err) - testutil.ErrorContains(t, err, tc.expectedError) + assert.ErrorContains(t, err, tc.expectedError) + assert.ErrorType(t, err, reflect.TypeOf(&InvalidTemplateError{})) } } @@ -146,7 +144,7 @@ func TestDefaultsForMandatoryVariables(t *testing.T) { for _, tc := range testCases { result, err := Substitute(tc.template, defaultMapping) - assert.Nil(t, err) - assert.Equal(t, tc.expected, result) + assert.Check(t, err) + assert.Check(t, is.Equal(tc.expected, result)) } } diff --git a/cli/config/config_test.go b/cli/config/config_test.go index 25ed97cdf1..ca036ea0d6 100644 --- a/cli/config/config_test.go +++ b/cli/config/config_test.go @@ -12,13 +12,13 @@ import ( "github.com/docker/cli/cli/config/credentials" "github.com/docker/cli/internal/test/testutil" "github.com/docker/docker/pkg/homedir" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" + "github.com/gotestyourself/gotestyourself/assert" + is "github.com/gotestyourself/gotestyourself/assert/cmp" ) func setupConfigDir(t *testing.T) (string, func()) { tmpdir, err := ioutil.TempDir("", "config-test") - require.NoError(t, err) + assert.NilError(t, err) oldDir := Dir() SetDir(tmpdir) @@ -33,10 +33,10 @@ func TestEmptyConfigDir(t *testing.T) { defer cleanup() config, err := Load("") - require.NoError(t, err) + assert.NilError(t, err) expectedConfigFilename := filepath.Join(tmpHome, ConfigFileName) - assert.Equal(t, expectedConfigFilename, config.Filename) + assert.Check(t, is.Equal(expectedConfigFilename, config.Filename)) // Now save it and make sure it shows up in new form saveConfigAndValidateNewFormat(t, config, tmpHome) @@ -44,11 +44,11 @@ func TestEmptyConfigDir(t *testing.T) { func TestMissingFile(t *testing.T) { tmpHome, err := ioutil.TempDir("", "config-test") - require.NoError(t, err) + assert.NilError(t, err) defer os.RemoveAll(tmpHome) config, err := Load(tmpHome) - require.NoError(t, err) + assert.NilError(t, err) // Now save it and make sure it shows up in new form saveConfigAndValidateNewFormat(t, config, tmpHome) @@ -56,13 +56,13 @@ func TestMissingFile(t *testing.T) { func TestSaveFileToDirs(t *testing.T) { tmpHome, err := ioutil.TempDir("", "config-test") - require.NoError(t, err) + assert.NilError(t, err) defer os.RemoveAll(tmpHome) tmpHome += "/.docker" config, err := Load(tmpHome) - require.NoError(t, err) + assert.NilError(t, err) // Now save it and make sure it shows up in new form saveConfigAndValidateNewFormat(t, config, tmpHome) @@ -70,12 +70,12 @@ func TestSaveFileToDirs(t *testing.T) { func TestEmptyFile(t *testing.T) { tmpHome, err := ioutil.TempDir("", "config-test") - require.NoError(t, err) + assert.NilError(t, err) defer os.RemoveAll(tmpHome) fn := filepath.Join(tmpHome, ConfigFileName) err = ioutil.WriteFile(fn, []byte(""), 0600) - require.NoError(t, err) + assert.NilError(t, err) _, err = Load(tmpHome) testutil.ErrorContains(t, err, "EOF") @@ -83,15 +83,15 @@ func TestEmptyFile(t *testing.T) { func TestEmptyJSON(t *testing.T) { tmpHome, err := ioutil.TempDir("", "config-test") - require.NoError(t, err) + assert.NilError(t, err) defer os.RemoveAll(tmpHome) fn := filepath.Join(tmpHome, ConfigFileName) err = ioutil.WriteFile(fn, []byte("{}"), 0600) - require.NoError(t, err) + assert.NilError(t, err) config, err := Load(tmpHome) - require.NoError(t, err) + assert.NilError(t, err) // Now save it and make sure it shows up in new form saveConfigAndValidateNewFormat(t, config, tmpHome) @@ -107,7 +107,7 @@ email`: "Invalid auth configuration file", } tmpHome, err := ioutil.TempDir("", "config-test") - require.NoError(t, err) + assert.NilError(t, err) defer os.RemoveAll(tmpHome) homeKey := homedir.Key() @@ -119,7 +119,7 @@ email`: "Invalid auth configuration file", for content, expectedError := range invalids { fn := filepath.Join(tmpHome, oldConfigfile) err := ioutil.WriteFile(fn, []byte(content), 0600) - require.NoError(t, err) + assert.NilError(t, err) _, err = Load(tmpHome) testutil.ErrorContains(t, err, expectedError) @@ -128,7 +128,7 @@ email`: "Invalid auth configuration file", func TestOldValidAuth(t *testing.T) { tmpHome, err := ioutil.TempDir("", "config-test") - require.NoError(t, err) + assert.NilError(t, err) defer os.RemoveAll(tmpHome) homeKey := homedir.Key() @@ -141,10 +141,10 @@ func TestOldValidAuth(t *testing.T) { js := `username = am9lam9lOmhlbGxv email = user@example.com` err = ioutil.WriteFile(fn, []byte(js), 0600) - require.NoError(t, err) + assert.NilError(t, err) config, err := Load(tmpHome) - require.NoError(t, err) + assert.NilError(t, err) // defaultIndexserver is https://index.docker.io/v1/ ac := config.AuthConfigs["https://index.docker.io/v1/"] @@ -163,12 +163,12 @@ func TestOldValidAuth(t *testing.T) { } }` - assert.Equal(t, expConfStr, configStr) + assert.Check(t, is.Equal(expConfStr, configStr)) } func TestOldJSONInvalid(t *testing.T) { tmpHome, err := ioutil.TempDir("", "config-test") - require.NoError(t, err) + assert.NilError(t, err) defer os.RemoveAll(tmpHome) homeKey := homedir.Key() @@ -192,7 +192,7 @@ func TestOldJSONInvalid(t *testing.T) { func TestOldJSON(t *testing.T) { tmpHome, err := ioutil.TempDir("", "config-test") - require.NoError(t, err) + assert.NilError(t, err) defer os.RemoveAll(tmpHome) homeKey := homedir.Key() @@ -208,7 +208,7 @@ func TestOldJSON(t *testing.T) { } config, err := Load(tmpHome) - require.NoError(t, err) + assert.NilError(t, err) ac := config.AuthConfigs["https://index.docker.io/v1/"] if ac.Username != "joejoe" || ac.Password != "hello" { @@ -234,7 +234,7 @@ func TestOldJSON(t *testing.T) { func TestNewJSON(t *testing.T) { tmpHome, err := ioutil.TempDir("", "config-test") - require.NoError(t, err) + assert.NilError(t, err) defer os.RemoveAll(tmpHome) fn := filepath.Join(tmpHome, ConfigFileName) @@ -244,7 +244,7 @@ func TestNewJSON(t *testing.T) { } config, err := Load(tmpHome) - require.NoError(t, err) + assert.NilError(t, err) ac := config.AuthConfigs["https://index.docker.io/v1/"] if ac.Username != "joejoe" || ac.Password != "hello" { @@ -269,7 +269,7 @@ func TestNewJSON(t *testing.T) { func TestNewJSONNoEmail(t *testing.T) { tmpHome, err := ioutil.TempDir("", "config-test") - require.NoError(t, err) + assert.NilError(t, err) defer os.RemoveAll(tmpHome) fn := filepath.Join(tmpHome, ConfigFileName) @@ -279,7 +279,7 @@ func TestNewJSONNoEmail(t *testing.T) { } config, err := Load(tmpHome) - require.NoError(t, err) + assert.NilError(t, err) ac := config.AuthConfigs["https://index.docker.io/v1/"] if ac.Username != "joejoe" || ac.Password != "hello" { @@ -304,7 +304,7 @@ func TestNewJSONNoEmail(t *testing.T) { func TestJSONWithPsFormat(t *testing.T) { tmpHome, err := ioutil.TempDir("", "config-test") - require.NoError(t, err) + assert.NilError(t, err) defer os.RemoveAll(tmpHome) fn := filepath.Join(tmpHome, ConfigFileName) @@ -317,7 +317,7 @@ func TestJSONWithPsFormat(t *testing.T) { } config, err := Load(tmpHome) - require.NoError(t, err) + assert.NilError(t, err) if config.PsFormat != `table {{.ID}}\t{{.Label "com.docker.label.cpu"}}` { t.Fatalf("Unknown ps format: %s\n", config.PsFormat) @@ -333,7 +333,7 @@ func TestJSONWithPsFormat(t *testing.T) { func TestJSONWithCredentialStore(t *testing.T) { tmpHome, err := ioutil.TempDir("", "config-test") - require.NoError(t, err) + assert.NilError(t, err) defer os.RemoveAll(tmpHome) fn := filepath.Join(tmpHome, ConfigFileName) @@ -346,7 +346,7 @@ func TestJSONWithCredentialStore(t *testing.T) { } config, err := Load(tmpHome) - require.NoError(t, err) + assert.NilError(t, err) if config.CredentialsStore != "crazy-secure-storage" { t.Fatalf("Unknown credential store: %s\n", config.CredentialsStore) @@ -362,7 +362,7 @@ func TestJSONWithCredentialStore(t *testing.T) { func TestJSONWithCredentialHelpers(t *testing.T) { tmpHome, err := ioutil.TempDir("", "config-test") - require.NoError(t, err) + assert.NilError(t, err) defer os.RemoveAll(tmpHome) fn := filepath.Join(tmpHome, ConfigFileName) @@ -375,7 +375,7 @@ func TestJSONWithCredentialHelpers(t *testing.T) { } config, err := Load(tmpHome) - require.NoError(t, err) + assert.NilError(t, err) if config.CredentialHelpers == nil { t.Fatal("config.CredentialHelpers was nil") @@ -397,17 +397,17 @@ func TestJSONWithCredentialHelpers(t *testing.T) { // Save it and make sure it shows up in new form func saveConfigAndValidateNewFormat(t *testing.T, config *configfile.ConfigFile, configDir string) string { - require.NoError(t, config.Save()) + assert.NilError(t, config.Save()) buf, err := ioutil.ReadFile(filepath.Join(configDir, ConfigFileName)) - require.NoError(t, err) - assert.Contains(t, string(buf), `"auths":`) + assert.NilError(t, err) + assert.Check(t, is.Contains(string(buf), `"auths":`)) return string(buf) } func TestConfigDir(t *testing.T) { tmpHome, err := ioutil.TempDir("", "config-test") - require.NoError(t, err) + assert.NilError(t, err) defer os.RemoveAll(tmpHome) if Dir() == tmpHome { @@ -426,7 +426,7 @@ func TestJSONReaderNoFile(t *testing.T) { js := ` { "auths": { "https://index.docker.io/v1/": { "auth": "am9lam9lOmhlbGxv", "email": "user@example.com" } } }` config, err := LoadFromReader(strings.NewReader(js)) - require.NoError(t, err) + assert.NilError(t, err) ac := config.AuthConfigs["https://index.docker.io/v1/"] if ac.Username != "joejoe" || ac.Password != "hello" { @@ -439,7 +439,7 @@ func TestOldJSONReaderNoFile(t *testing.T) { js := `{"https://index.docker.io/v1/":{"auth":"am9lam9lOmhlbGxv","email":"user@example.com"}}` config, err := LegacyLoadFromReader(strings.NewReader(js)) - require.NoError(t, err) + assert.NilError(t, err) ac := config.AuthConfigs["https://index.docker.io/v1/"] if ac.Username != "joejoe" || ac.Password != "hello" { @@ -453,7 +453,7 @@ func TestJSONWithPsFormatNoFile(t *testing.T) { "psFormat": "table {{.ID}}\\t{{.Label \"com.docker.label.cpu\"}}" }` config, err := LoadFromReader(strings.NewReader(js)) - require.NoError(t, err) + assert.NilError(t, err) if config.PsFormat != `table {{.ID}}\t{{.Label "com.docker.label.cpu"}}` { t.Fatalf("Unknown ps format: %s\n", config.PsFormat) @@ -467,21 +467,21 @@ func TestJSONSaveWithNoFile(t *testing.T) { "psFormat": "table {{.ID}}\\t{{.Label \"com.docker.label.cpu\"}}" }` config, err := LoadFromReader(strings.NewReader(js)) - require.NoError(t, err) + assert.NilError(t, err) err = config.Save() testutil.ErrorContains(t, err, "with empty filename") tmpHome, err := ioutil.TempDir("", "config-test") - require.NoError(t, err) + assert.NilError(t, err) defer os.RemoveAll(tmpHome) fn := filepath.Join(tmpHome, ConfigFileName) f, _ := os.OpenFile(fn, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600) defer f.Close() - require.NoError(t, config.SaveToWriter(f)) + assert.NilError(t, config.SaveToWriter(f)) buf, err := ioutil.ReadFile(filepath.Join(tmpHome, ConfigFileName)) - require.NoError(t, err) + assert.NilError(t, err) expConfStr := `{ "auths": { "https://index.docker.io/v1/": { @@ -498,21 +498,21 @@ func TestJSONSaveWithNoFile(t *testing.T) { func TestLegacyJSONSaveWithNoFile(t *testing.T) { js := `{"https://index.docker.io/v1/":{"auth":"am9lam9lOmhlbGxv","email":"user@example.com"}}` config, err := LegacyLoadFromReader(strings.NewReader(js)) - require.NoError(t, err) + assert.NilError(t, err) err = config.Save() testutil.ErrorContains(t, err, "with empty filename") tmpHome, err := ioutil.TempDir("", "config-test") - require.NoError(t, err) + assert.NilError(t, err) defer os.RemoveAll(tmpHome) fn := filepath.Join(tmpHome, ConfigFileName) f, _ := os.OpenFile(fn, os.O_WRONLY|os.O_CREATE|os.O_TRUNC, 0600) defer f.Close() - require.NoError(t, config.SaveToWriter(f)) + assert.NilError(t, config.SaveToWriter(f)) buf, err := ioutil.ReadFile(filepath.Join(tmpHome, ConfigFileName)) - require.NoError(t, err) + assert.NilError(t, err) expConfStr := `{ "auths": { @@ -536,7 +536,7 @@ func TestLoadDefaultConfigFile(t *testing.T) { filename := filepath.Join(dir, ConfigFileName) content := []byte(`{"PsFormat": "format"}`) err := ioutil.WriteFile(filename, content, 0644) - require.NoError(t, err) + assert.NilError(t, err) configFile := LoadDefaultConfigFile(buffer) credStore := credentials.DetectDefaultStore("") @@ -544,5 +544,5 @@ func TestLoadDefaultConfigFile(t *testing.T) { expected.CredentialsStore = credStore expected.PsFormat = "format" - assert.Equal(t, expected, configFile) + assert.Check(t, is.DeepEqual(expected, configFile)) } diff --git a/cli/config/configfile/file_test.go b/cli/config/configfile/file_test.go index 75df18c49a..c769f53c26 100644 --- a/cli/config/configfile/file_test.go +++ b/cli/config/configfile/file_test.go @@ -6,8 +6,8 @@ import ( "github.com/docker/cli/cli/config/credentials" "github.com/docker/docker/api/types" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" + "github.com/gotestyourself/gotestyourself/assert" + is "github.com/gotestyourself/gotestyourself/assert/cmp" ) func TestEncodeAuth(t *testing.T) { @@ -17,8 +17,8 @@ func TestEncodeAuth(t *testing.T) { expected := &types.AuthConfig{} var err error expected.Username, expected.Password, err = decodeAuth(authStr) - require.NoError(t, err) - assert.Equal(t, expected, newAuthConfig) + assert.NilError(t, err) + assert.Check(t, is.DeepEqual(expected, newAuthConfig)) } func TestProxyConfig(t *testing.T) { @@ -50,7 +50,7 @@ func TestProxyConfig(t *testing.T) { "NO_PROXY": &noProxy, "no_proxy": &noProxy, } - assert.Equal(t, expected, proxyConfig) + assert.Check(t, is.DeepEqual(expected, proxyConfig)) } func TestProxyConfigOverride(t *testing.T) { @@ -88,7 +88,7 @@ func TestProxyConfigOverride(t *testing.T) { "NO_PROXY": &overrideNoProxy, "no_proxy": &noProxy, } - assert.Equal(t, expected, proxyConfig) + assert.Check(t, is.DeepEqual(expected, proxyConfig)) } func TestProxyConfigPerHost(t *testing.T) { @@ -133,14 +133,14 @@ func TestProxyConfigPerHost(t *testing.T) { "NO_PROXY": &extNoProxy, "no_proxy": &extNoProxy, } - assert.Equal(t, expected, proxyConfig) + assert.Check(t, is.DeepEqual(expected, proxyConfig)) } func TestConfigFile(t *testing.T) { configFilename := "configFilename" configFile := New(configFilename) - assert.Equal(t, configFilename, configFile.Filename) + assert.Check(t, is.Equal(configFilename, configFile.Filename)) } type mockNativeStore struct { @@ -182,11 +182,11 @@ func TestGetAllCredentialsFileStoreOnly(t *testing.T) { configFile.AuthConfigs["example.com/foo"] = exampleAuth authConfigs, err := configFile.GetAllCredentials() - require.NoError(t, err) + assert.NilError(t, err) expected := make(map[string]types.AuthConfig) expected["example.com/foo"] = exampleAuth - assert.Equal(t, expected, authConfigs) + assert.Check(t, is.DeepEqual(expected, authConfigs)) } func TestGetAllCredentialsCredsStore(t *testing.T) { @@ -207,12 +207,12 @@ func TestGetAllCredentialsCredsStore(t *testing.T) { } authConfigs, err := configFile.GetAllCredentials() - require.NoError(t, err) + assert.NilError(t, err) expected := make(map[string]types.AuthConfig) expected[testRegistryHostname] = expectedAuth - assert.Equal(t, expected, authConfigs) - assert.Equal(t, 1, testCredsStore.(*mockNativeStore).GetAllCallCount) + assert.Check(t, is.DeepEqual(expected, authConfigs)) + assert.Check(t, is.Equal(1, testCredsStore.(*mockNativeStore).GetAllCallCount)) } func TestGetAllCredentialsCredHelper(t *testing.T) { @@ -246,12 +246,12 @@ func TestGetAllCredentialsCredHelper(t *testing.T) { } authConfigs, err := configFile.GetAllCredentials() - require.NoError(t, err) + assert.NilError(t, err) expected := make(map[string]types.AuthConfig) expected[testCredHelperRegistryHostname] = expectedCredHelperAuth - assert.Equal(t, expected, authConfigs) - assert.Equal(t, 0, testCredHelper.(*mockNativeStore).GetAllCallCount) + assert.Check(t, is.DeepEqual(expected, authConfigs)) + assert.Check(t, is.Equal(0, testCredHelper.(*mockNativeStore).GetAllCallCount)) } func TestGetAllCredentialsFileStoreAndCredHelper(t *testing.T) { @@ -281,13 +281,13 @@ func TestGetAllCredentialsFileStoreAndCredHelper(t *testing.T) { tmpNewNativeStore := newNativeStore defer func() { newNativeStore = tmpNewNativeStore }() authConfigs, err := configFile.GetAllCredentials() - require.NoError(t, err) + assert.NilError(t, err) expected := make(map[string]types.AuthConfig) expected[testFileStoreRegistryHostname] = expectedFileStoreAuth expected[testCredHelperRegistryHostname] = expectedCredHelperAuth - assert.Equal(t, expected, authConfigs) - assert.Equal(t, 0, testCredHelper.(*mockNativeStore).GetAllCallCount) + assert.Check(t, is.DeepEqual(expected, authConfigs)) + assert.Check(t, is.Equal(0, testCredHelper.(*mockNativeStore).GetAllCallCount)) } func TestGetAllCredentialsCredStoreAndCredHelper(t *testing.T) { @@ -322,14 +322,14 @@ func TestGetAllCredentialsCredStoreAndCredHelper(t *testing.T) { } authConfigs, err := configFile.GetAllCredentials() - require.NoError(t, err) + assert.NilError(t, err) expected := make(map[string]types.AuthConfig) expected[testCredStoreRegistryHostname] = expectedCredStoreAuth expected[testCredHelperRegistryHostname] = expectedCredHelperAuth - assert.Equal(t, expected, authConfigs) - assert.Equal(t, 1, testCredsStore.(*mockNativeStore).GetAllCallCount) - assert.Equal(t, 0, testCredHelper.(*mockNativeStore).GetAllCallCount) + assert.Check(t, is.DeepEqual(expected, authConfigs)) + assert.Check(t, is.Equal(1, testCredsStore.(*mockNativeStore).GetAllCallCount)) + assert.Check(t, is.Equal(0, testCredHelper.(*mockNativeStore).GetAllCallCount)) } func TestGetAllCredentialsCredHelperOverridesDefaultStore(t *testing.T) { @@ -363,11 +363,11 @@ func TestGetAllCredentialsCredHelperOverridesDefaultStore(t *testing.T) { } authConfigs, err := configFile.GetAllCredentials() - require.NoError(t, err) + assert.NilError(t, err) expected := make(map[string]types.AuthConfig) expected[testRegistryHostname] = expectedCredHelperAuth - assert.Equal(t, expected, authConfigs) - assert.Equal(t, 1, testCredsStore.(*mockNativeStore).GetAllCallCount) - assert.Equal(t, 0, testCredHelper.(*mockNativeStore).GetAllCallCount) + assert.Check(t, is.DeepEqual(expected, authConfigs)) + assert.Check(t, is.Equal(1, testCredsStore.(*mockNativeStore).GetAllCallCount)) + assert.Check(t, is.Equal(0, testCredHelper.(*mockNativeStore).GetAllCallCount)) } diff --git a/cli/config/credentials/file_store_test.go b/cli/config/credentials/file_store_test.go index 0d4fbd6bdc..b849d62456 100644 --- a/cli/config/credentials/file_store_test.go +++ b/cli/config/credentials/file_store_test.go @@ -4,8 +4,8 @@ import ( "testing" "github.com/docker/docker/api/types" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" + "github.com/gotestyourself/gotestyourself/assert" + is "github.com/gotestyourself/gotestyourself/assert/cmp" ) type fakeStore struct { @@ -34,12 +34,12 @@ func TestFileStoreAddCredentials(t *testing.T) { ServerAddress: "https://example.com", } err := s.Store(auth) - require.NoError(t, err) - assert.Len(t, f.GetAuthConfigs(), 1) + assert.NilError(t, err) + assert.Check(t, is.Len(f.GetAuthConfigs(), 1)) actual, ok := f.GetAuthConfigs()["https://example.com"] - assert.True(t, ok) - assert.Equal(t, auth, actual) + assert.Check(t, ok) + assert.Check(t, is.DeepEqual(auth, actual)) } func TestFileStoreGet(t *testing.T) { diff --git a/cli/config/credentials/native_store_test.go b/cli/config/credentials/native_store_test.go index c85e3f0d18..337c3bf751 100644 --- a/cli/config/credentials/native_store_test.go +++ b/cli/config/credentials/native_store_test.go @@ -12,9 +12,9 @@ import ( "github.com/docker/docker-credential-helpers/client" "github.com/docker/docker-credential-helpers/credentials" "github.com/docker/docker/api/types" + "github.com/gotestyourself/gotestyourself/assert" + is "github.com/gotestyourself/gotestyourself/assert/cmp" "github.com/pkg/errors" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" ) const ( @@ -105,16 +105,16 @@ func TestNativeStoreAddCredentials(t *testing.T) { ServerAddress: validServerAddress, } err := s.Store(auth) - require.NoError(t, err) - assert.Len(t, f.GetAuthConfigs(), 1) + assert.NilError(t, err) + assert.Check(t, is.Len(f.GetAuthConfigs(), 1)) actual, ok := f.GetAuthConfigs()[validServerAddress] - assert.True(t, ok) + assert.Check(t, ok) expected := types.AuthConfig{ Email: auth.Email, ServerAddress: auth.ServerAddress, } - assert.Equal(t, expected, actual) + assert.Check(t, is.DeepEqual(expected, actual)) } func TestNativeStoreAddInvalidCredentials(t *testing.T) { @@ -130,7 +130,7 @@ func TestNativeStoreAddInvalidCredentials(t *testing.T) { ServerAddress: invalidServerAddress, }) testutil.ErrorContains(t, err, "program failed") - assert.Len(t, f.GetAuthConfigs(), 0) + assert.Check(t, is.Len(f.GetAuthConfigs(), 0)) } func TestNativeStoreGet(t *testing.T) { @@ -144,14 +144,14 @@ func TestNativeStoreGet(t *testing.T) { fileStore: NewFileStore(f), } actual, err := s.Get(validServerAddress) - require.NoError(t, err) + assert.NilError(t, err) expected := types.AuthConfig{ Username: "foo", Password: "bar", Email: "foo@example.com", } - assert.Equal(t, expected, actual) + assert.Check(t, is.DeepEqual(expected, actual)) } func TestNativeStoreGetIdentityToken(t *testing.T) { @@ -166,13 +166,13 @@ func TestNativeStoreGetIdentityToken(t *testing.T) { fileStore: NewFileStore(f), } actual, err := s.Get(validServerAddress2) - require.NoError(t, err) + assert.NilError(t, err) expected := types.AuthConfig{ IdentityToken: "abcd1234", Email: "foo@example2.com", } - assert.Equal(t, expected, actual) + assert.Check(t, is.DeepEqual(expected, actual)) } func TestNativeStoreGetAll(t *testing.T) { @@ -187,8 +187,8 @@ func TestNativeStoreGetAll(t *testing.T) { fileStore: NewFileStore(f), } as, err := s.GetAll() - require.NoError(t, err) - assert.Len(t, as, 2) + assert.NilError(t, err) + assert.Check(t, is.Len(as, 2)) if as[validServerAddress].Username != "foo" { t.Fatalf("expected username `foo` for %s, got %s", validServerAddress, as[validServerAddress].Username) @@ -228,7 +228,7 @@ func TestNativeStoreGetMissingCredentials(t *testing.T) { fileStore: NewFileStore(f), } _, err := s.Get(missingCredsAddress) - assert.NoError(t, err) + assert.Check(t, err) } func TestNativeStoreGetInvalidAddress(t *testing.T) { @@ -258,8 +258,8 @@ func TestNativeStoreErase(t *testing.T) { fileStore: NewFileStore(f), } err := s.Erase(validServerAddress) - require.NoError(t, err) - assert.Len(t, f.GetAuthConfigs(), 0) + assert.NilError(t, err) + assert.Check(t, is.Len(f.GetAuthConfigs(), 0)) } func TestNativeStoreEraseInvalidAddress(t *testing.T) { diff --git a/cli/flags/common_test.go b/cli/flags/common_test.go index a00cd7a6ca..1482c33f6c 100644 --- a/cli/flags/common_test.go +++ b/cli/flags/common_test.go @@ -5,8 +5,9 @@ import ( "testing" cliconfig "github.com/docker/cli/cli/config" + "github.com/gotestyourself/gotestyourself/assert" + is "github.com/gotestyourself/gotestyourself/assert/cmp" "github.com/spf13/pflag" - "github.com/stretchr/testify/assert" ) func TestCommonOptionsInstallFlags(t *testing.T) { @@ -19,10 +20,10 @@ func TestCommonOptionsInstallFlags(t *testing.T) { "--tlscert=\"/foo/cert\"", "--tlskey=\"/foo/key\"", }) - assert.NoError(t, err) - assert.Equal(t, "/foo/cafile", opts.TLSOptions.CAFile) - assert.Equal(t, "/foo/cert", opts.TLSOptions.CertFile) - assert.Equal(t, opts.TLSOptions.KeyFile, "/foo/key") + assert.Check(t, err) + assert.Check(t, is.Equal("/foo/cafile", opts.TLSOptions.CAFile)) + assert.Check(t, is.Equal("/foo/cert", opts.TLSOptions.CertFile)) + assert.Check(t, is.Equal(opts.TLSOptions.KeyFile, "/foo/key")) } func defaultPath(filename string) string { @@ -35,8 +36,8 @@ func TestCommonOptionsInstallFlagsWithDefaults(t *testing.T) { opts.InstallFlags(flags) err := flags.Parse([]string{}) - assert.NoError(t, err) - assert.Equal(t, defaultPath("ca.pem"), opts.TLSOptions.CAFile) - assert.Equal(t, defaultPath("cert.pem"), opts.TLSOptions.CertFile) - assert.Equal(t, defaultPath("key.pem"), opts.TLSOptions.KeyFile) + assert.Check(t, err) + assert.Check(t, is.Equal(defaultPath("ca.pem"), opts.TLSOptions.CAFile)) + assert.Check(t, is.Equal(defaultPath("cert.pem"), opts.TLSOptions.CertFile)) + assert.Check(t, is.Equal(defaultPath("key.pem"), opts.TLSOptions.KeyFile)) } diff --git a/cli/manifest/store/store_test.go b/cli/manifest/store/store_test.go index fdf51dd641..bd3ba419a7 100644 --- a/cli/manifest/store/store_test.go +++ b/cli/manifest/store/store_test.go @@ -7,8 +7,9 @@ import ( "github.com/docker/cli/cli/manifest/types" "github.com/docker/distribution/reference" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" + "github.com/google/go-cmp/cmp" + "github.com/gotestyourself/gotestyourself/assert" + is "github.com/gotestyourself/gotestyourself/assert/cmp" ) type fakeRef struct { @@ -29,20 +30,20 @@ func ref(name string) fakeRef { func sref(t *testing.T, name string) *types.SerializableNamed { named, err := reference.ParseNamed("example.com/" + name) - require.NoError(t, err) + assert.NilError(t, err) return &types.SerializableNamed{Named: named} } func newTestStore(t *testing.T) (Store, func()) { tmpdir, err := ioutil.TempDir("", "manifest-store-test") - require.NoError(t, err) + assert.NilError(t, err) return NewStore(tmpdir), func() { os.RemoveAll(tmpdir) } } func getFiles(t *testing.T, store Store) []os.FileInfo { infos, err := ioutil.ReadDir(store.(*fsStore).root) - require.NoError(t, err) + assert.NilError(t, err) return infos } @@ -52,11 +53,11 @@ func TestStoreRemove(t *testing.T) { listRef := ref("list") data := types.ImageManifest{Ref: sref(t, "abcdef")} - require.NoError(t, store.Save(listRef, ref("manifest"), data)) - require.Len(t, getFiles(t, store), 1) + assert.NilError(t, store.Save(listRef, ref("manifest"), data)) + assert.Assert(t, is.Len(getFiles(t, store), 1)) - assert.NoError(t, store.Remove(listRef)) - assert.Len(t, getFiles(t, store), 0) + assert.Check(t, store.Remove(listRef)) + assert.Check(t, is.Len(getFiles(t, store), 0)) } func TestStoreSaveAndGet(t *testing.T) { @@ -66,7 +67,7 @@ func TestStoreSaveAndGet(t *testing.T) { listRef := ref("list") data := types.ImageManifest{Ref: sref(t, "abcdef")} err := store.Save(listRef, ref("exists"), data) - require.NoError(t, err) + assert.NilError(t, err) var testcases = []struct { listRef reference.Reference @@ -92,32 +93,36 @@ func TestStoreSaveAndGet(t *testing.T) { } for _, testcase := range testcases { - actual, err := store.Get(testcase.listRef, testcase.manifestRef) - if testcase.expectedErr != "" { - assert.EqualError(t, err, testcase.expectedErr) - assert.True(t, IsNotFound(err)) - continue - } - if !assert.NoError(t, err, testcase.manifestRef.String()) { - continue - } - assert.Equal(t, testcase.expected, actual, testcase.manifestRef.String()) + t.Run(testcase.manifestRef.String(), func(t *testing.T) { + actual, err := store.Get(testcase.listRef, testcase.manifestRef) + if testcase.expectedErr != "" { + assert.Check(t, is.Error(err, testcase.expectedErr)) + assert.Check(t, IsNotFound(err)) + return + } + assert.NilError(t, err) + assert.DeepEqual(t, testcase.expected, actual, cmpReferenceNamed) + }) } } +var cmpReferenceNamed = cmp.Transformer("namedref", func(r reference.Named) string { + return r.String() +}) + func TestStoreGetList(t *testing.T) { store, cleanup := newTestStore(t) defer cleanup() listRef := ref("list") first := types.ImageManifest{Ref: sref(t, "first")} - require.NoError(t, store.Save(listRef, ref("first"), first)) + assert.NilError(t, store.Save(listRef, ref("first"), first)) second := types.ImageManifest{Ref: sref(t, "second")} - require.NoError(t, store.Save(listRef, ref("exists"), second)) + assert.NilError(t, store.Save(listRef, ref("exists"), second)) list, err := store.GetList(listRef) - require.NoError(t, err) - assert.Len(t, list, 2) + assert.NilError(t, err) + assert.Check(t, is.Len(list, 2)) } func TestStoreGetListDoesNotExist(t *testing.T) { @@ -126,6 +131,6 @@ func TestStoreGetListDoesNotExist(t *testing.T) { listRef := ref("list") _, err := store.GetList(listRef) - assert.EqualError(t, err, "No such manifest: list") - assert.True(t, IsNotFound(err)) + assert.Check(t, is.Error(err, "No such manifest: list")) + assert.Check(t, IsNotFound(err)) } diff --git a/cli/required_test.go b/cli/required_test.go index b70bafb57b..c82e3b965f 100644 --- a/cli/required_test.go +++ b/cli/required_test.go @@ -5,9 +5,8 @@ import ( "io/ioutil" "testing" + "github.com/gotestyourself/gotestyourself/assert" "github.com/spf13/cobra" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" ) func TestRequiresNoArgs(t *testing.T) { @@ -123,9 +122,7 @@ func runTestCases(t *testing.T, testCases []testCase) { cmd.SetOutput(ioutil.Discard) err := cmd.Execute() - - require.Error(t, err, "Expected an error: %s", tc.expectedError) - assert.Contains(t, err.Error(), tc.expectedError) + assert.ErrorContains(t, err, tc.expectedError) } } diff --git a/cli/trust/trust_test.go b/cli/trust/trust_test.go index ea5971482e..0cb1f1dd26 100644 --- a/cli/trust/trust_test.go +++ b/cli/trust/trust_test.go @@ -6,9 +6,9 @@ import ( "testing" "github.com/docker/distribution/reference" + "github.com/gotestyourself/gotestyourself/assert" + is "github.com/gotestyourself/gotestyourself/assert/cmp" digest "github.com/opencontainers/go-digest" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" "github.com/theupdateframework/notary/client" "github.com/theupdateframework/notary/passphrase" "github.com/theupdateframework/notary/trustpinning" @@ -16,46 +16,46 @@ import ( func TestGetTag(t *testing.T) { ref, err := reference.ParseNormalizedNamed("ubuntu@sha256:45b23dee08af5e43a7fea6c4cf9c25ccf269ee113168c19722f87876677c5cb2") - assert.NoError(t, err) + assert.Check(t, err) tag := getTag(ref) - assert.Equal(t, "", tag) + assert.Check(t, is.Equal("", tag)) ref, err = reference.ParseNormalizedNamed("alpine:latest") - assert.NoError(t, err) + assert.Check(t, err) tag = getTag(ref) - assert.Equal(t, tag, "latest") + assert.Check(t, is.Equal(tag, "latest")) ref, err = reference.ParseNormalizedNamed("alpine") - assert.NoError(t, err) + assert.Check(t, err) tag = getTag(ref) - assert.Equal(t, tag, "") + assert.Check(t, is.Equal(tag, "")) } func TestGetDigest(t *testing.T) { ref, err := reference.ParseNormalizedNamed("ubuntu@sha256:45b23dee08af5e43a7fea6c4cf9c25ccf269ee113168c19722f87876677c5cb2") - assert.NoError(t, err) + assert.Check(t, err) d := getDigest(ref) - assert.Equal(t, digest.Digest("sha256:45b23dee08af5e43a7fea6c4cf9c25ccf269ee113168c19722f87876677c5cb2"), d) + assert.Check(t, is.Equal(digest.Digest("sha256:45b23dee08af5e43a7fea6c4cf9c25ccf269ee113168c19722f87876677c5cb2"), d)) ref, err = reference.ParseNormalizedNamed("alpine:latest") - assert.NoError(t, err) + assert.Check(t, err) d = getDigest(ref) - assert.Equal(t, digest.Digest(""), d) + assert.Check(t, is.Equal(digest.Digest(""), d)) ref, err = reference.ParseNormalizedNamed("alpine") - assert.NoError(t, err) + assert.Check(t, err) d = getDigest(ref) - assert.Equal(t, digest.Digest(""), d) + assert.Check(t, is.Equal(digest.Digest(""), d)) } func TestGetSignableRolesError(t *testing.T) { tmpDir, err := ioutil.TempDir("", "notary-test-") - assert.NoError(t, err) + assert.Check(t, err) defer os.RemoveAll(tmpDir) notaryRepo, err := client.NewFileCachedRepository(tmpDir, "gun", "https://localhost", nil, passphrase.ConstantRetriever("password"), trustpinning.TrustPinConfig{}) - require.NoError(t, err) + assert.NilError(t, err) target := client.Target{} _, err = GetSignableRoles(notaryRepo, &target) - assert.EqualError(t, err, "client is offline") + assert.Check(t, is.Error(err, "client is offline")) } diff --git a/cmd/docker/docker_test.go b/cmd/docker/docker_test.go index cec08495a4..4165388b80 100644 --- a/cmd/docker/docker_test.go +++ b/cmd/docker/docker_test.go @@ -7,8 +7,9 @@ import ( "github.com/docker/cli/cli/command" "github.com/docker/cli/cli/debug" + "github.com/gotestyourself/gotestyourself/assert" + is "github.com/gotestyourself/gotestyourself/assert/cmp" "github.com/sirupsen/logrus" - "github.com/stretchr/testify/assert" ) func TestClientDebugEnabled(t *testing.T) { @@ -18,9 +19,9 @@ func TestClientDebugEnabled(t *testing.T) { cmd.Flags().Set("debug", "true") err := cmd.PersistentPreRunE(cmd, []string{}) - assert.NoError(t, err) - assert.Equal(t, "1", os.Getenv("DEBUG")) - assert.Equal(t, logrus.DebugLevel, logrus.GetLevel()) + assert.Check(t, err) + assert.Check(t, is.Equal("1", os.Getenv("DEBUG"))) + assert.Check(t, is.Equal(logrus.DebugLevel, logrus.GetLevel())) } func TestExitStatusForInvalidSubcommandWithHelpFlag(t *testing.T) { @@ -28,5 +29,5 @@ func TestExitStatusForInvalidSubcommandWithHelpFlag(t *testing.T) { cmd := newDockerCommand(command.NewDockerCli(os.Stdin, discard, discard)) cmd.SetArgs([]string{"help", "invalid"}) err := cmd.Execute() - assert.EqualError(t, err, "unknown help topic: invalid") + assert.Check(t, is.Error(err, "unknown help topic: invalid")) } diff --git a/e2e/container/run_test.go b/e2e/container/run_test.go index d0902b152a..716ca3726b 100644 --- a/e2e/container/run_test.go +++ b/e2e/container/run_test.go @@ -6,10 +6,10 @@ import ( "github.com/docker/cli/e2e/internal/fixtures" shlex "github.com/flynn-archive/go-shlex" + "github.com/gotestyourself/gotestyourself/assert" + is "github.com/gotestyourself/gotestyourself/assert/cmp" "github.com/gotestyourself/gotestyourself/golden" "github.com/gotestyourself/gotestyourself/icmd" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" ) func TestRunAttachedFromRemoteImageAndRemove(t *testing.T) { @@ -19,7 +19,7 @@ func TestRunAttachedFromRemoteImageAndRemove(t *testing.T) { "docker run --rm %s echo this is output", image)) result.Assert(t, icmd.Success) - assert.Equal(t, "this is output\n", result.Stdout()) + assert.Check(t, is.Equal("this is output\n", result.Stdout())) golden.Assert(t, result.Stderr(), "run-attached-from-remote-and-remove.golden") } @@ -36,6 +36,6 @@ func createRemoteImage(t *testing.T) string { // TODO: move to gotestyourself func shell(t *testing.T, format string, args ...interface{}) icmd.Cmd { cmd, err := shlex.Split(fmt.Sprintf(format, args...)) - require.NoError(t, err) + assert.NilError(t, err) return icmd.Cmd{Command: cmd} } diff --git a/e2e/stack/remove_test.go b/e2e/stack/remove_test.go index d5f1858c76..0ec8639073 100644 --- a/e2e/stack/remove_test.go +++ b/e2e/stack/remove_test.go @@ -7,10 +7,10 @@ import ( "github.com/docker/cli/internal/test/environment" shlex "github.com/flynn-archive/go-shlex" + "github.com/gotestyourself/gotestyourself/assert" "github.com/gotestyourself/gotestyourself/golden" "github.com/gotestyourself/gotestyourself/icmd" "github.com/gotestyourself/gotestyourself/poll" - "github.com/stretchr/testify/require" ) var pollSettings = environment.DefaultPollSettings @@ -70,6 +70,6 @@ func lines(out string) int { // TODO: move to gotestyourself func shell(t *testing.T, format string, args ...interface{}) icmd.Cmd { cmd, err := shlex.Split(fmt.Sprintf(format, args...)) - require.NoError(t, err) + assert.NilError(t, err) return icmd.Cmd{Command: cmd} } diff --git a/e2e/trust/revoke_test.go b/e2e/trust/revoke_test.go index e576bbc08f..36b401e67f 100644 --- a/e2e/trust/revoke_test.go +++ b/e2e/trust/revoke_test.go @@ -5,9 +5,10 @@ import ( "testing" "github.com/docker/cli/e2e/internal/fixtures" + "github.com/gotestyourself/gotestyourself/assert" + is "github.com/gotestyourself/gotestyourself/assert/cmp" "github.com/gotestyourself/gotestyourself/fs" "github.com/gotestyourself/gotestyourself/icmd" - "github.com/stretchr/testify/assert" ) const ( @@ -24,7 +25,7 @@ func TestRevokeImage(t *testing.T) { fixtures.WithPassphrase("root_password", "repo_password"), fixtures.WithNotary, fixtures.WithConfig(dir.Path())) result.Assert(t, icmd.Success) - assert.Contains(t, result.Stdout(), "Successfully deleted signature for registry:5000/revoke:v1") + assert.Check(t, is.Contains(result.Stdout(), "Successfully deleted signature for registry:5000/revoke:v1")) } func TestRevokeRepo(t *testing.T) { @@ -36,7 +37,7 @@ func TestRevokeRepo(t *testing.T) { fixtures.WithPassphrase("root_password", "repo_password"), fixtures.WithNotary, fixtures.WithConfig(dir.Path())) result.Assert(t, icmd.Success) - assert.Contains(t, result.Stdout(), "Successfully deleted signature for registry:5000/revoke") + assert.Check(t, is.Contains(result.Stdout(), "Successfully deleted signature for registry:5000/revoke")) } func setupTrustedImagesForRevoke(t *testing.T, dir fs.Dir) { diff --git a/e2e/trust/sign_test.go b/e2e/trust/sign_test.go index 37d9817917..83ba5a6983 100644 --- a/e2e/trust/sign_test.go +++ b/e2e/trust/sign_test.go @@ -5,9 +5,10 @@ import ( "testing" "github.com/docker/cli/e2e/internal/fixtures" + "github.com/gotestyourself/gotestyourself/assert" + is "github.com/gotestyourself/gotestyourself/assert/cmp" "github.com/gotestyourself/gotestyourself/fs" "github.com/gotestyourself/gotestyourself/icmd" - "github.com/stretchr/testify/assert" ) const ( @@ -25,7 +26,7 @@ func TestSignLocalImage(t *testing.T) { fixtures.WithPassphrase("root_password", "repo_password"), fixtures.WithConfig(dir.Path()), fixtures.WithNotary) result.Assert(t, icmd.Success) - assert.Contains(t, result.Stdout(), fmt.Sprintf("v1: digest: sha256:%s", fixtures.AlpineSha)) + assert.Check(t, is.Contains(result.Stdout(), fmt.Sprintf("v1: digest: sha256:%s", fixtures.AlpineSha))) } @@ -38,7 +39,7 @@ func TestSignWithLocalFlag(t *testing.T) { fixtures.WithPassphrase("root_password", "repo_password"), fixtures.WithConfig(dir.Path()), fixtures.WithNotary) result.Assert(t, icmd.Success) - assert.Contains(t, result.Stdout(), fmt.Sprintf("v1: digest: sha256:%s", fixtures.BusyboxSha)) + assert.Check(t, is.Contains(result.Stdout(), fmt.Sprintf("v1: digest: sha256:%s", fixtures.BusyboxSha))) } func setupTrustedImageForOverwrite(t *testing.T, dir fs.Dir) { @@ -49,7 +50,7 @@ func setupTrustedImageForOverwrite(t *testing.T, dir fs.Dir) { fixtures.WithPassphrase("root_password", "repo_password"), fixtures.WithConfig(dir.Path()), fixtures.WithNotary) result.Assert(t, icmd.Success) - assert.Contains(t, result.Stdout(), fmt.Sprintf("v1: digest: sha256:%s", fixtures.AlpineSha)) + assert.Check(t, is.Contains(result.Stdout(), fmt.Sprintf("v1: digest: sha256:%s", fixtures.AlpineSha))) icmd.RunCmd(icmd.Command("docker", "pull", fixtures.BusyboxImage)).Assert(t, icmd.Success) icmd.RunCommand("docker", "tag", fixtures.BusyboxImage, localImage).Assert(t, icmd.Success) } diff --git a/internal/test/testutil/assert.go b/internal/test/testutil/assert.go index cf5d2c9876..cc7cc886d5 100644 --- a/internal/test/testutil/assert.go +++ b/internal/test/testutil/assert.go @@ -1,15 +1,19 @@ package testutil import ( - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" + "github.com/gotestyourself/gotestyourself/assert" ) +type helperT interface { + Helper() +} + // ErrorContains checks that the error is not nil, and contains the expected // substring. -// TODO: replace with testify if https://github.com/stretchr/testify/pull/486 -// is accepted. -func ErrorContains(t require.TestingT, err error, expectedError string) { - require.Error(t, err) - assert.Contains(t, err.Error(), expectedError) +// Deprecated: use assert.Assert(t, cmp.ErrorContains(err, expected)) +func ErrorContains(t assert.TestingT, err error, expectedError string) { + if ht, ok := t.(helperT); ok { + ht.Helper() + } + assert.ErrorContains(t, err, expectedError) } diff --git a/kubernetes/check_test.go b/kubernetes/check_test.go index 0368e05228..792dc3e6a5 100644 --- a/kubernetes/check_test.go +++ b/kubernetes/check_test.go @@ -3,8 +3,8 @@ package kubernetes import ( "testing" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" + "github.com/gotestyourself/gotestyourself/assert" + is "github.com/gotestyourself/gotestyourself/assert/cmp" metav1 "k8s.io/apimachinery/pkg/apis/meta/v1" ) @@ -22,11 +22,11 @@ func TestGetStackAPIVersion(t *testing.T) { for _, test := range tests { version, err := getAPIVersion(test.groups) if test.err { - require.Error(t, err) + assert.ErrorContains(t, err, "") } else { - require.NoError(t, err) + assert.NilError(t, err) } - assert.Equal(t, test.expectedStack, version) + assert.Check(t, is.Equal(test.expectedStack, version)) } } diff --git a/kubernetes/labels/labels_test.go b/kubernetes/labels/labels_test.go index 454795e6fc..d99f881829 100644 --- a/kubernetes/labels/labels_test.go +++ b/kubernetes/labels/labels_test.go @@ -3,20 +3,21 @@ package labels import ( "testing" - "github.com/stretchr/testify/assert" + "github.com/gotestyourself/gotestyourself/assert" + is "github.com/gotestyourself/gotestyourself/assert/cmp" ) func TestForService(t *testing.T) { labels := ForService("stack", "service") - assert.Len(t, labels, 3) - assert.Equal(t, "stack", labels["com.docker.stack.namespace"]) - assert.Equal(t, "service", labels["com.docker.service.name"]) - assert.Equal(t, "stack-service", labels["com.docker.service.id"]) + assert.Check(t, is.Len(labels, 3)) + assert.Check(t, is.Equal("stack", labels["com.docker.stack.namespace"])) + assert.Check(t, is.Equal("service", labels["com.docker.service.name"])) + assert.Check(t, is.Equal("stack-service", labels["com.docker.service.id"])) } func TestSelectorForStack(t *testing.T) { - assert.Equal(t, "com.docker.stack.namespace=demostack", SelectorForStack("demostack")) - assert.Equal(t, "com.docker.stack.namespace=stack,com.docker.service.name=service", SelectorForStack("stack", "service")) - assert.Equal(t, "com.docker.stack.namespace=stack,com.docker.service.name in (service1,service2)", SelectorForStack("stack", "service1", "service2")) + assert.Check(t, is.Equal("com.docker.stack.namespace=demostack", SelectorForStack("demostack"))) + assert.Check(t, is.Equal("com.docker.stack.namespace=stack,com.docker.service.name=service", SelectorForStack("stack", "service"))) + assert.Check(t, is.Equal("com.docker.stack.namespace=stack,com.docker.service.name in (service1,service2)", SelectorForStack("stack", "service1", "service2"))) } diff --git a/opts/duration_test.go b/opts/duration_test.go index f766a1c74c..66db3aaefb 100644 --- a/opts/duration_test.go +++ b/opts/duration_test.go @@ -4,26 +4,27 @@ import ( "testing" "time" - "github.com/stretchr/testify/assert" + "github.com/gotestyourself/gotestyourself/assert" + is "github.com/gotestyourself/gotestyourself/assert/cmp" ) func TestDurationOptString(t *testing.T) { dur := time.Duration(300 * 10e8) duration := DurationOpt{value: &dur} - assert.Equal(t, "5m0s", duration.String()) + assert.Check(t, is.Equal("5m0s", duration.String())) } func TestDurationOptSetAndValue(t *testing.T) { var duration DurationOpt - assert.NoError(t, duration.Set("300s")) - assert.Equal(t, time.Duration(300*10e8), *duration.Value()) - assert.NoError(t, duration.Set("-300s")) - assert.Equal(t, time.Duration(-300*10e8), *duration.Value()) + assert.Check(t, duration.Set("300s")) + assert.Check(t, is.Equal(time.Duration(300*10e8), *duration.Value())) + assert.Check(t, duration.Set("-300s")) + assert.Check(t, is.Equal(time.Duration(-300*10e8), *duration.Value())) } func TestPositiveDurationOptSetAndValue(t *testing.T) { var duration PositiveDurationOpt - assert.NoError(t, duration.Set("300s")) - assert.Equal(t, time.Duration(300*10e8), *duration.Value()) - assert.EqualError(t, duration.Set("-300s"), "duration cannot be negative") + assert.Check(t, duration.Set("300s")) + assert.Check(t, is.Equal(time.Duration(300*10e8), *duration.Value())) + assert.Check(t, is.Error(duration.Set("-300s"), "duration cannot be negative")) } diff --git a/opts/mount_test.go b/opts/mount_test.go index aba18a226f..ff9435380d 100644 --- a/opts/mount_test.go +++ b/opts/mount_test.go @@ -6,8 +6,8 @@ import ( "github.com/docker/cli/internal/test/testutil" mounttypes "github.com/docker/docker/api/types/mount" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" + "github.com/gotestyourself/gotestyourself/assert" + is "github.com/gotestyourself/gotestyourself/assert/cmp" ) func TestMountOptString(t *testing.T) { @@ -26,7 +26,7 @@ func TestMountOptString(t *testing.T) { }, } expected := "bind /home/path /target, volume foo /target/foo" - assert.Equal(t, expected, mount.String()) + assert.Check(t, is.Equal(expected, mount.String())) } func TestMountOptSetBindNoErrorBind(t *testing.T) { @@ -39,15 +39,15 @@ func TestMountOptSetBindNoErrorBind(t *testing.T) { } { var mount MountOpt - assert.NoError(t, mount.Set(testcase)) + assert.Check(t, mount.Set(testcase)) mounts := mount.Value() - require.Len(t, mounts, 1) - assert.Equal(t, mounttypes.Mount{ + assert.Assert(t, is.Len(mounts, 1)) + assert.Check(t, is.DeepEqual(mounttypes.Mount{ Type: mounttypes.TypeBind, Source: "/source", Target: "/target", - }, mounts[0]) + }, mounts[0])) } } @@ -61,15 +61,15 @@ func TestMountOptSetVolumeNoError(t *testing.T) { } { var mount MountOpt - assert.NoError(t, mount.Set(testcase)) + assert.Check(t, mount.Set(testcase)) mounts := mount.Value() - require.Len(t, mounts, 1) - assert.Equal(t, mounttypes.Mount{ + assert.Assert(t, is.Len(mounts, 1)) + assert.Check(t, is.DeepEqual(mounttypes.Mount{ Type: mounttypes.TypeVolume, Source: "/source", Target: "/target", - }, mounts[0]) + }, mounts[0])) } } @@ -77,76 +77,76 @@ func TestMountOptSetVolumeNoError(t *testing.T) { // volume mount. func TestMountOptDefaultType(t *testing.T) { var mount MountOpt - assert.NoError(t, mount.Set("target=/target,source=/foo")) - assert.Equal(t, mounttypes.TypeVolume, mount.values[0].Type) + assert.Check(t, mount.Set("target=/target,source=/foo")) + assert.Check(t, is.Equal(mounttypes.TypeVolume, mount.values[0].Type)) } func TestMountOptSetErrorNoTarget(t *testing.T) { var mount MountOpt - assert.EqualError(t, mount.Set("type=volume,source=/foo"), "target is required") + assert.Check(t, is.Error(mount.Set("type=volume,source=/foo"), "target is required")) } func TestMountOptSetErrorInvalidKey(t *testing.T) { var mount MountOpt - assert.EqualError(t, mount.Set("type=volume,bogus=foo"), "unexpected key 'bogus' in 'bogus=foo'") + assert.Check(t, is.Error(mount.Set("type=volume,bogus=foo"), "unexpected key 'bogus' in 'bogus=foo'")) } func TestMountOptSetErrorInvalidField(t *testing.T) { var mount MountOpt - assert.EqualError(t, mount.Set("type=volume,bogus"), "invalid field 'bogus' must be a key=value pair") + assert.Check(t, is.Error(mount.Set("type=volume,bogus"), "invalid field 'bogus' must be a key=value pair")) } func TestMountOptSetErrorInvalidReadOnly(t *testing.T) { var mount MountOpt - assert.EqualError(t, mount.Set("type=volume,readonly=no"), "invalid value for readonly: no") - assert.EqualError(t, mount.Set("type=volume,readonly=invalid"), "invalid value for readonly: invalid") + assert.Check(t, is.Error(mount.Set("type=volume,readonly=no"), "invalid value for readonly: no")) + assert.Check(t, is.Error(mount.Set("type=volume,readonly=invalid"), "invalid value for readonly: invalid")) } func TestMountOptDefaultEnableReadOnly(t *testing.T) { var m MountOpt - assert.NoError(t, m.Set("type=bind,target=/foo,source=/foo")) - assert.False(t, m.values[0].ReadOnly) + assert.Check(t, m.Set("type=bind,target=/foo,source=/foo")) + assert.Check(t, !m.values[0].ReadOnly) m = MountOpt{} - assert.NoError(t, m.Set("type=bind,target=/foo,source=/foo,readonly")) - assert.True(t, m.values[0].ReadOnly) + assert.Check(t, m.Set("type=bind,target=/foo,source=/foo,readonly")) + assert.Check(t, m.values[0].ReadOnly) m = MountOpt{} - assert.NoError(t, m.Set("type=bind,target=/foo,source=/foo,readonly=1")) - assert.True(t, m.values[0].ReadOnly) + assert.Check(t, m.Set("type=bind,target=/foo,source=/foo,readonly=1")) + assert.Check(t, m.values[0].ReadOnly) m = MountOpt{} - assert.NoError(t, m.Set("type=bind,target=/foo,source=/foo,readonly=true")) - assert.True(t, m.values[0].ReadOnly) + assert.Check(t, m.Set("type=bind,target=/foo,source=/foo,readonly=true")) + assert.Check(t, m.values[0].ReadOnly) m = MountOpt{} - assert.NoError(t, m.Set("type=bind,target=/foo,source=/foo,readonly=0")) - assert.False(t, m.values[0].ReadOnly) + assert.Check(t, m.Set("type=bind,target=/foo,source=/foo,readonly=0")) + assert.Check(t, !m.values[0].ReadOnly) } func TestMountOptVolumeNoCopy(t *testing.T) { var m MountOpt - assert.NoError(t, m.Set("type=volume,target=/foo,volume-nocopy")) - assert.Equal(t, "", m.values[0].Source) + assert.Check(t, m.Set("type=volume,target=/foo,volume-nocopy")) + assert.Check(t, is.Equal("", m.values[0].Source)) m = MountOpt{} - assert.NoError(t, m.Set("type=volume,target=/foo,source=foo")) - assert.True(t, m.values[0].VolumeOptions == nil) + assert.Check(t, m.Set("type=volume,target=/foo,source=foo")) + assert.Check(t, m.values[0].VolumeOptions == nil) m = MountOpt{} - assert.NoError(t, m.Set("type=volume,target=/foo,source=foo,volume-nocopy=true")) - assert.True(t, m.values[0].VolumeOptions != nil) - assert.True(t, m.values[0].VolumeOptions.NoCopy) + assert.Check(t, m.Set("type=volume,target=/foo,source=foo,volume-nocopy=true")) + assert.Check(t, m.values[0].VolumeOptions != nil) + assert.Check(t, m.values[0].VolumeOptions.NoCopy) m = MountOpt{} - assert.NoError(t, m.Set("type=volume,target=/foo,source=foo,volume-nocopy")) - assert.True(t, m.values[0].VolumeOptions != nil) - assert.True(t, m.values[0].VolumeOptions.NoCopy) + assert.Check(t, m.Set("type=volume,target=/foo,source=foo,volume-nocopy")) + assert.Check(t, m.values[0].VolumeOptions != nil) + assert.Check(t, m.values[0].VolumeOptions.NoCopy) m = MountOpt{} - assert.NoError(t, m.Set("type=volume,target=/foo,source=foo,volume-nocopy=1")) - assert.True(t, m.values[0].VolumeOptions != nil) - assert.True(t, m.values[0].VolumeOptions.NoCopy) + assert.Check(t, m.Set("type=volume,target=/foo,source=foo,volume-nocopy=1")) + assert.Check(t, m.values[0].VolumeOptions != nil) + assert.Check(t, m.values[0].VolumeOptions.NoCopy) } func TestMountOptTypeConflict(t *testing.T) { @@ -163,18 +163,18 @@ func TestMountOptSetTmpfsNoError(t *testing.T) { } { var mount MountOpt - assert.NoError(t, mount.Set(testcase)) + assert.Check(t, mount.Set(testcase)) mounts := mount.Value() - require.Len(t, mounts, 1) - assert.Equal(t, mounttypes.Mount{ + assert.Assert(t, is.Len(mounts, 1)) + assert.Check(t, is.DeepEqual(mounttypes.Mount{ Type: mounttypes.TypeTmpfs, Target: "/target", TmpfsOptions: &mounttypes.TmpfsOptions{ SizeBytes: 1024 * 1024, // not 1000 * 1000 Mode: os.FileMode(0700), }, - }, mounts[0]) + }, mounts[0])) } } diff --git a/opts/network_test.go b/opts/network_test.go index d19823dc1d..18857448fc 100644 --- a/opts/network_test.go +++ b/opts/network_test.go @@ -4,7 +4,8 @@ import ( "testing" "github.com/docker/cli/internal/test/testutil" - "github.com/stretchr/testify/assert" + "github.com/gotestyourself/gotestyourself/assert" + is "github.com/gotestyourself/gotestyourself/assert/cmp" ) func TestNetworkOptLegacySyntax(t *testing.T) { @@ -23,8 +24,8 @@ func TestNetworkOptLegacySyntax(t *testing.T) { } for _, tc := range testCases { var network NetworkOpt - assert.NoError(t, network.Set(tc.value)) - assert.Equal(t, tc.expected, network.Value()) + assert.Check(t, network.Set(tc.value)) + assert.Check(t, is.DeepEqual(tc.expected, network.Value())) } } @@ -70,8 +71,8 @@ func TestNetworkOptCompleteSyntax(t *testing.T) { } for _, tc := range testCases { var network NetworkOpt - assert.NoError(t, network.Set(tc.value)) - assert.Equal(t, tc.expected, network.Value()) + assert.Check(t, network.Set(tc.value)) + assert.Check(t, is.DeepEqual(tc.expected, network.Value())) } } diff --git a/opts/port_test.go b/opts/port_test.go index fb4ffe47c2..ded63c3182 100644 --- a/opts/port_test.go +++ b/opts/port_test.go @@ -5,7 +5,8 @@ import ( "github.com/docker/cli/internal/test/testutil" "github.com/docker/docker/api/types/swarm" - "github.com/stretchr/testify/assert" + "github.com/gotestyourself/gotestyourself/assert" + is "github.com/gotestyourself/gotestyourself/assert/cmp" ) func TestPortOptValidSimpleSyntax(t *testing.T) { @@ -99,8 +100,8 @@ func TestPortOptValidSimpleSyntax(t *testing.T) { } for _, tc := range testCases { var port PortOpt - assert.NoError(t, port.Set(tc.value)) - assert.Len(t, port.Value(), len(tc.expected)) + assert.Check(t, port.Set(tc.value)) + assert.Check(t, is.Len(port.Value(), len(tc.expected))) for _, expectedPortConfig := range tc.expected { assertContains(t, port.Value(), expectedPortConfig) } @@ -190,8 +191,8 @@ func TestPortOptValidComplexSyntax(t *testing.T) { } for _, tc := range testCases { var port PortOpt - assert.NoError(t, port.Set(tc.value)) - assert.Len(t, port.Value(), len(tc.expected)) + assert.Check(t, port.Set(tc.value)) + assert.Check(t, is.Len(port.Value(), len(tc.expected))) for _, expectedPortConfig := range tc.expected { assertContains(t, port.Value(), expectedPortConfig) } @@ -278,7 +279,7 @@ func TestPortOptInvalidSimpleSyntax(t *testing.T) { } for _, tc := range testCases { var port PortOpt - assert.EqualError(t, port.Set(tc.value), tc.expectedError) + assert.Check(t, is.Error(port.Set(tc.value), tc.expectedError)) } } diff --git a/opts/quotedstring_test.go b/opts/quotedstring_test.go index 54dcbc19bc..ffef407db0 100644 --- a/opts/quotedstring_test.go +++ b/opts/quotedstring_test.go @@ -3,27 +3,28 @@ package opts import ( "testing" - "github.com/stretchr/testify/assert" + "github.com/gotestyourself/gotestyourself/assert" + is "github.com/gotestyourself/gotestyourself/assert/cmp" ) func TestQuotedStringSetWithQuotes(t *testing.T) { value := "" qs := NewQuotedString(&value) - assert.NoError(t, qs.Set(`"something"`)) - assert.Equal(t, "something", qs.String()) - assert.Equal(t, "something", value) + assert.Check(t, qs.Set(`"something"`)) + assert.Check(t, is.Equal("something", qs.String())) + assert.Check(t, is.Equal("something", value)) } func TestQuotedStringSetWithMismatchedQuotes(t *testing.T) { value := "" qs := NewQuotedString(&value) - assert.NoError(t, qs.Set(`"something'`)) - assert.Equal(t, `"something'`, qs.String()) + assert.Check(t, qs.Set(`"something'`)) + assert.Check(t, is.Equal(`"something'`, qs.String())) } func TestQuotedStringSetWithNoQuotes(t *testing.T) { value := "" qs := NewQuotedString(&value) - assert.NoError(t, qs.Set("something")) - assert.Equal(t, "something", qs.String()) + assert.Check(t, qs.Set("something")) + assert.Check(t, is.Equal("something", qs.String())) } diff --git a/opts/secret_test.go b/opts/secret_test.go index ad0005e4ad..3482ccc32a 100644 --- a/opts/secret_test.go +++ b/opts/secret_test.go @@ -4,77 +4,77 @@ import ( "os" "testing" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/require" + "github.com/gotestyourself/gotestyourself/assert" + is "github.com/gotestyourself/gotestyourself/assert/cmp" ) func TestSecretOptionsSimple(t *testing.T) { var opt SecretOpt testCase := "app-secret" - assert.NoError(t, opt.Set(testCase)) + assert.Check(t, opt.Set(testCase)) reqs := opt.Value() - require.Len(t, reqs, 1) + assert.Assert(t, is.Len(reqs, 1)) req := reqs[0] - assert.Equal(t, "app-secret", req.SecretName) - assert.Equal(t, "app-secret", req.File.Name) - assert.Equal(t, "0", req.File.UID) - assert.Equal(t, "0", req.File.GID) + assert.Check(t, is.Equal("app-secret", req.SecretName)) + assert.Check(t, is.Equal("app-secret", req.File.Name)) + assert.Check(t, is.Equal("0", req.File.UID)) + assert.Check(t, is.Equal("0", req.File.GID)) } func TestSecretOptionsSourceTarget(t *testing.T) { var opt SecretOpt testCase := "source=foo,target=testing" - assert.NoError(t, opt.Set(testCase)) + assert.Check(t, opt.Set(testCase)) reqs := opt.Value() - require.Len(t, reqs, 1) + assert.Assert(t, is.Len(reqs, 1)) req := reqs[0] - assert.Equal(t, "foo", req.SecretName) - assert.Equal(t, "testing", req.File.Name) + assert.Check(t, is.Equal("foo", req.SecretName)) + assert.Check(t, is.Equal("testing", req.File.Name)) } func TestSecretOptionsShorthand(t *testing.T) { var opt SecretOpt testCase := "src=foo,target=testing" - assert.NoError(t, opt.Set(testCase)) + assert.Check(t, opt.Set(testCase)) reqs := opt.Value() - require.Len(t, reqs, 1) + assert.Assert(t, is.Len(reqs, 1)) req := reqs[0] - assert.Equal(t, "foo", req.SecretName) + assert.Check(t, is.Equal("foo", req.SecretName)) } func TestSecretOptionsCustomUidGid(t *testing.T) { var opt SecretOpt testCase := "source=foo,target=testing,uid=1000,gid=1001" - assert.NoError(t, opt.Set(testCase)) + assert.Check(t, opt.Set(testCase)) reqs := opt.Value() - require.Len(t, reqs, 1) + assert.Assert(t, is.Len(reqs, 1)) req := reqs[0] - assert.Equal(t, "foo", req.SecretName) - assert.Equal(t, "testing", req.File.Name) - assert.Equal(t, "1000", req.File.UID) - assert.Equal(t, "1001", req.File.GID) + assert.Check(t, is.Equal("foo", req.SecretName)) + assert.Check(t, is.Equal("testing", req.File.Name)) + assert.Check(t, is.Equal("1000", req.File.UID)) + assert.Check(t, is.Equal("1001", req.File.GID)) } func TestSecretOptionsCustomMode(t *testing.T) { var opt SecretOpt testCase := "source=foo,target=testing,uid=1000,gid=1001,mode=0444" - assert.NoError(t, opt.Set(testCase)) + assert.Check(t, opt.Set(testCase)) reqs := opt.Value() - require.Len(t, reqs, 1) + assert.Assert(t, is.Len(reqs, 1)) req := reqs[0] - assert.Equal(t, "foo", req.SecretName) - assert.Equal(t, "testing", req.File.Name) - assert.Equal(t, "1000", req.File.UID) - assert.Equal(t, "1001", req.File.GID) - assert.Equal(t, os.FileMode(0444), req.File.Mode) + assert.Check(t, is.Equal("foo", req.SecretName)) + assert.Check(t, is.Equal("testing", req.File.Name)) + assert.Check(t, is.Equal("1000", req.File.UID)) + assert.Check(t, is.Equal("1001", req.File.GID)) + assert.Check(t, is.Equal(os.FileMode(0444), req.File.Mode)) } diff --git a/service/logs/parse_logs_test.go b/service/logs/parse_logs_test.go index 223323ea02..e0aee51bd7 100644 --- a/service/logs/parse_logs_test.go +++ b/service/logs/parse_logs_test.go @@ -3,8 +3,9 @@ package logs import ( "testing" + "github.com/gotestyourself/gotestyourself/assert" + is "github.com/gotestyourself/gotestyourself/assert/cmp" "github.com/pkg/errors" - "github.com/stretchr/testify/assert" ) func TestParseLogDetails(t *testing.T) { @@ -24,10 +25,10 @@ func TestParseLogDetails(t *testing.T) { t.Run(testcase.line, func(t *testing.T) { actual, err := ParseLogDetails(testcase.line) if testcase.err != nil { - assert.EqualError(t, err, testcase.err.Error()) + assert.Check(t, is.Error(err, testcase.err.Error())) return } - assert.Equal(t, testcase.expected, actual) + assert.Check(t, is.DeepEqual(testcase.expected, actual)) }) } } diff --git a/templates/templates_test.go b/templates/templates_test.go index 8355804d31..66fafa2f07 100644 --- a/templates/templates_test.go +++ b/templates/templates_test.go @@ -4,38 +4,39 @@ import ( "bytes" "testing" - "github.com/stretchr/testify/assert" + "github.com/gotestyourself/gotestyourself/assert" + is "github.com/gotestyourself/gotestyourself/assert/cmp" ) // GitHub #32120 func TestParseJSONFunctions(t *testing.T) { tm, err := Parse(`{{json .Ports}}`) - assert.NoError(t, err) + assert.Check(t, err) var b bytes.Buffer - assert.NoError(t, tm.Execute(&b, map[string]string{"Ports": "0.0.0.0:2->8/udp"})) + assert.Check(t, tm.Execute(&b, map[string]string{"Ports": "0.0.0.0:2->8/udp"})) want := "\"0.0.0.0:2->8/udp\"" - assert.Equal(t, want, b.String()) + assert.Check(t, is.Equal(want, b.String())) } func TestParseStringFunctions(t *testing.T) { tm, err := Parse(`{{join (split . ":") "/"}}`) - assert.NoError(t, err) + assert.Check(t, err) var b bytes.Buffer - assert.NoError(t, tm.Execute(&b, "text:with:colon")) + assert.Check(t, tm.Execute(&b, "text:with:colon")) want := "text/with/colon" - assert.Equal(t, want, b.String()) + assert.Check(t, is.Equal(want, b.String())) } func TestNewParse(t *testing.T) { tm, err := NewParse("foo", "this is a {{ . }}") - assert.NoError(t, err) + assert.Check(t, err) var b bytes.Buffer - assert.NoError(t, tm.Execute(&b, "string")) + assert.Check(t, tm.Execute(&b, "string")) want := "this is a string" - assert.Equal(t, want, b.String()) + assert.Check(t, is.Equal(want, b.String())) } func TestParseTruncateFunction(t *testing.T) { @@ -65,24 +66,24 @@ func TestParseTruncateFunction(t *testing.T) { for _, testCase := range testCases { tm, err := Parse(testCase.template) - assert.NoError(t, err) + assert.Check(t, err) t.Run("Non Empty Source Test with template: "+testCase.template, func(t *testing.T) { var b bytes.Buffer - assert.NoError(t, tm.Execute(&b, source)) - assert.Equal(t, testCase.expected, b.String()) + assert.Check(t, tm.Execute(&b, source)) + assert.Check(t, is.Equal(testCase.expected, b.String())) }) t.Run("Empty Source Test with template: "+testCase.template, func(t *testing.T) { var c bytes.Buffer - assert.NoError(t, tm.Execute(&c, "")) - assert.Equal(t, "", c.String()) + assert.Check(t, tm.Execute(&c, "")) + assert.Check(t, is.Equal("", c.String())) }) t.Run("Nil Source Test with template: "+testCase.template, func(t *testing.T) { var c bytes.Buffer - assert.Error(t, tm.Execute(&c, nil)) - assert.Equal(t, "", c.String()) + assert.Check(t, tm.Execute(&c, nil) != nil) + assert.Check(t, is.Equal("", c.String())) }) } } diff --git a/vendor.conf b/vendor.conf index cc33be3df5..67b87ddaf0 100755 --- a/vendor.conf +++ b/vendor.conf @@ -27,7 +27,7 @@ github.com/google/gofuzz 44d81051d367757e1c7c6a5a86423ece9afcf63c github.com/googleapis/gnostic e4f56557df6250e1945ee6854f181ce4e1c2c646 github.com/gorilla/context v1.1 github.com/gorilla/mux v1.1 -github.com/gotestyourself/gotestyourself v1.3.0 +github.com/gotestyourself/gotestyourself cf3a5ab914a2efa8bc838d09f5918c1d44d02909 # FIXME(vdemeester) try to deduplicate this with gojsonpointer github.com/go-openapi/jsonpointer 46af16f9f7b149af66e5d1bd010e3574dc06de98 # FIXME(vdemeester) try to deduplicate this with gojsonreference diff --git a/vendor/github.com/gotestyourself/gotestyourself/assert/assert.go b/vendor/github.com/gotestyourself/gotestyourself/assert/assert.go index 1896618861..d2b05f4165 100644 --- a/vendor/github.com/gotestyourself/gotestyourself/assert/assert.go +++ b/vendor/github.com/gotestyourself/gotestyourself/assert/assert.go @@ -32,9 +32,9 @@ The example below shows assert used with some common types. // errors assert.NilError(t, closer.Close()) - assert.Assert(t, is.Error(err, "the exact error message")) - assert.Assert(t, is.ErrorContains(err, "includes this")) - assert.Assert(t, is.ErrorType(err, os.IsNotExist)) + assert.Error(t, err, "the exact error message") + assert.ErrorContains(t, err, "includes this") + assert.ErrorType(t, err, os.IsNotExist) // complex types assert.DeepEqual(t, result, myStruct{Name: "title"}) @@ -87,7 +87,7 @@ const failureMessage = "assertion failed: " func assert( t TestingT, failer func(), - argsFilter astExprListFilter, + argSelector argSelector, comparison BoolOrComparison, msgAndArgs ...interface{}, ) bool { @@ -114,10 +114,10 @@ func assert( t.Log(format.WithCustomMessage(failureMessage+msg+check.Error(), msgAndArgs...)) case cmp.Comparison: - success = runComparison(t, argsFilter, check, msgAndArgs...) + success = runComparison(t, argSelector, check, msgAndArgs...) case func() cmp.Result: - success = runComparison(t, argsFilter, check, msgAndArgs...) + success = runComparison(t, argSelector, check, msgAndArgs...) default: t.Log(fmt.Sprintf("invalid Comparison: %v (%T)", check, check)) @@ -146,6 +146,9 @@ func runCompareFunc( } func logFailureFromBool(t TestingT, msgAndArgs ...interface{}) { + if ht, ok := t.(helperT); ok { + ht.Helper() + } const stackIndex = 3 // Assert()/Check(), assert(), formatFailureFromBool() const comparisonArgPos = 1 args, err := source.CallExprArgs(stackIndex) @@ -206,7 +209,7 @@ func Assert(t TestingT, comparison BoolOrComparison, msgAndArgs ...interface{}) if ht, ok := t.(helperT); ok { ht.Helper() } - assert(t, t.FailNow, filterExprArgsFromComparison, comparison, msgAndArgs...) + assert(t, t.FailNow, argsFromComparisonCall, comparison, msgAndArgs...) } // Check performs a comparison. If the comparison fails the test is marked as @@ -218,7 +221,7 @@ func Check(t TestingT, comparison BoolOrComparison, msgAndArgs ...interface{}) b if ht, ok := t.(helperT); ok { ht.Helper() } - return assert(t, t.Fail, filterExprArgsFromComparison, comparison, msgAndArgs...) + return assert(t, t.Fail, argsFromComparisonCall, comparison, msgAndArgs...) } // NilError fails the test immediately if err is not nil. @@ -227,7 +230,7 @@ func NilError(t TestingT, err error, msgAndArgs ...interface{}) { if ht, ok := t.(helperT); ok { ht.Helper() } - assert(t, t.FailNow, filterExprExcludeFirst, err, msgAndArgs...) + assert(t, t.FailNow, argsAfterT, err, msgAndArgs...) } // Equal uses the == operator to assert two values are equal and fails the test @@ -236,7 +239,7 @@ func Equal(t TestingT, x, y interface{}, msgAndArgs ...interface{}) { if ht, ok := t.(helperT); ok { ht.Helper() } - assert(t, t.FailNow, filterExprExcludeFirst, cmp.Equal(x, y), msgAndArgs...) + assert(t, t.FailNow, argsAfterT, cmp.Equal(x, y), msgAndArgs...) } // DeepEqual uses https://github.com/google/go-cmp/cmp to assert two values @@ -246,5 +249,41 @@ func DeepEqual(t TestingT, x, y interface{}, opts ...gocmp.Option) { if ht, ok := t.(helperT); ok { ht.Helper() } - assert(t, t.FailNow, filterExprExcludeFirst, cmp.DeepEqual(x, y, opts...)) + assert(t, t.FailNow, argsAfterT, cmp.DeepEqual(x, y, opts...)) +} + +// Error fails the test if err is nil, or the error message is not the expected +// message. +// Equivalent to Assert(t, cmp.Error(err, message)). +func Error(t TestingT, err error, message string, msgAndArgs ...interface{}) { + if ht, ok := t.(helperT); ok { + ht.Helper() + } + assert(t, t.FailNow, argsAfterT, cmp.Error(err, message), msgAndArgs...) +} + +// ErrorContains fails the test if err is nil, or the error message does not +// contain the expected substring. +// Equivalent to Assert(t, cmp.ErrorContains(err, substring)). +func ErrorContains(t TestingT, err error, substring string, msgAndArgs ...interface{}) { + if ht, ok := t.(helperT); ok { + ht.Helper() + } + assert(t, t.FailNow, argsAfterT, cmp.ErrorContains(err, substring), msgAndArgs...) +} + +// ErrorType fails the test if err is nil, or err is not the expected type. +// +// Expected can be one of: +// a func(error) bool which returns true if the error is the expected type, +// an instance of a struct of the expected type, +// a pointer to an interface the error is expected to implement, +// a reflect.Type of the expected struct or interface. +// +// Equivalent to Assert(t, cmp.ErrorType(err, expected)). +func ErrorType(t TestingT, err error, expected interface{}, msgAndArgs ...interface{}) { + if ht, ok := t.(helperT); ok { + ht.Helper() + } + assert(t, t.FailNow, argsAfterT, cmp.ErrorType(err, expected), msgAndArgs...) } diff --git a/vendor/github.com/gotestyourself/gotestyourself/assert/result.go b/vendor/github.com/gotestyourself/gotestyourself/assert/result.go index 3298bc7552..b685b7f3e5 100644 --- a/vendor/github.com/gotestyourself/gotestyourself/assert/result.go +++ b/vendor/github.com/gotestyourself/gotestyourself/assert/result.go @@ -11,7 +11,7 @@ import ( func runComparison( t TestingT, - exprFilter astExprListFilter, + argSelector argSelector, f cmp.Comparison, msgAndArgs ...interface{}, ) bool { @@ -31,7 +31,7 @@ func runComparison( if err != nil { t.Log(err.Error()) } - message = typed.FailureMessage(filterPrintableExpr(exprFilter(args))) + message = typed.FailureMessage(filterPrintableExpr(argSelector(args))) case resultBasic: message = typed.FailureMessage() default: @@ -50,9 +50,7 @@ type resultBasic interface { FailureMessage() string } -type astExprListFilter func([]ast.Expr) []ast.Expr - -// filterPrintableExpr filters the ast.Expr slice to only include nodes that are +// filterPrintableExpr filters the ast.Expr slice to only include Expr that are // easy to read when printed and contain relevant information to an assertion. // // Ident and SelectorExpr are included because they print nicely and the variable @@ -63,24 +61,42 @@ type astExprListFilter func([]ast.Expr) []ast.Expr func filterPrintableExpr(args []ast.Expr) []ast.Expr { result := make([]ast.Expr, len(args)) for i, arg := range args { - switch arg.(type) { - case *ast.Ident, *ast.SelectorExpr, *ast.IndexExpr, *ast.SliceExpr: + if isShortPrintableExpr(arg) { result[i] = arg - default: - result[i] = nil + continue } + + if starExpr, ok := arg.(*ast.StarExpr); ok { + result[i] = starExpr.X + continue + } + result[i] = nil } return result } -func filterExprExcludeFirst(args []ast.Expr) []ast.Expr { +func isShortPrintableExpr(expr ast.Expr) bool { + switch expr.(type) { + case *ast.Ident, *ast.SelectorExpr, *ast.IndexExpr, *ast.SliceExpr: + return true + case *ast.BinaryExpr, *ast.UnaryExpr: + return true + default: + // CallExpr, ParenExpr, TypeAssertExpr, KeyValueExpr, StarExpr + return false + } +} + +type argSelector func([]ast.Expr) []ast.Expr + +func argsAfterT(args []ast.Expr) []ast.Expr { if len(args) < 1 { return nil } return args[1:] } -func filterExprArgsFromComparison(args []ast.Expr) []ast.Expr { +func argsFromComparisonCall(args []ast.Expr) []ast.Expr { if len(args) < 1 { return nil } diff --git a/vendor/github.com/gotestyourself/gotestyourself/env/env.go b/vendor/github.com/gotestyourself/gotestyourself/env/env.go index 95a53bee9c..700430f1dd 100644 --- a/vendor/github.com/gotestyourself/gotestyourself/env/env.go +++ b/vendor/github.com/gotestyourself/gotestyourself/env/env.go @@ -45,7 +45,7 @@ func PatchAll(t assert.TestingT, env map[string]string) func() { os.Clearenv() for key, value := range env { - assert.NilError(t, os.Setenv(key, value)) + assert.NilError(t, os.Setenv(key, value), "setenv %s=%s", key, value) } return func() { if ht, ok := t.(helperT); ok { @@ -53,7 +53,7 @@ func PatchAll(t assert.TestingT, env map[string]string) func() { } os.Clearenv() for key, oldVal := range ToMap(oldEnv) { - assert.NilError(t, os.Setenv(key, oldVal)) + assert.NilError(t, os.Setenv(key, oldVal), "setenv %s=%s", key, oldVal) } } } @@ -63,17 +63,23 @@ func PatchAll(t assert.TestingT, env map[string]string) func() { func ToMap(env []string) map[string]string { result := map[string]string{} for _, raw := range env { - parts := strings.SplitN(raw, "=", 2) - switch len(parts) { - case 1: - result[raw] = "" - case 2: - result[parts[0]] = parts[1] - } + key, value := getParts(raw) + result[key] = value } return result } +func getParts(raw string) (string, string) { + // Environment variables on windows can begin with = + // http://blogs.msdn.com/b/oldnewthing/archive/2010/05/06/10008132.aspx + parts := strings.SplitN(raw[1:], "=", 2) + key := raw[:1] + parts[0] + if len(parts) == 1 { + return key, "" + } + return key, parts[1] +} + // ChangeWorkingDir to the directory, and return a function which restores the // previous working directory. func ChangeWorkingDir(t assert.TestingT, dir string) func() { diff --git a/vendor/github.com/gotestyourself/gotestyourself/golden/golden.go b/vendor/github.com/gotestyourself/gotestyourself/golden/golden.go index 2a036f3852..357edcfd44 100644 --- a/vendor/github.com/gotestyourself/gotestyourself/golden/golden.go +++ b/vendor/github.com/gotestyourself/gotestyourself/golden/golden.go @@ -40,13 +40,23 @@ func Path(filename string) string { return filepath.Join("testdata", filename) } -func update(filename string, actual []byte) error { +func update(filename string, actual []byte, normalize normalize) error { if *flagUpdate { - return ioutil.WriteFile(Path(filename), actual, 0644) + return ioutil.WriteFile(Path(filename), normalize(actual), 0644) } return nil } +type normalize func([]byte) []byte + +func removeCarriageReturn(in []byte) []byte { + return bytes.Replace(in, []byte("\r\n"), []byte("\n"), -1) +} + +func exactBytes(in []byte) []byte { + return in +} + // Assert compares the actual content to the expected content in the golden file. // If the `-test.update-golden` flag is set then the actual content is written // to the golden file. @@ -66,15 +76,23 @@ func Assert(t assert.TestingT, actual string, filename string, msgAndArgs ...int // String compares actual to the contents of filename and returns success // if the strings are equal. +// If the `-test.update-golden` flag is set then the actual content is written +// to the golden file. +// +// Any \r\n substrings in actual are converted to a single \n character +// before comparing it to the expected string. When updating the golden file the +// normalized version will be written to the file. This allows Windows to use +// the same golden files as other operating systems. func String(actual string, filename string) cmp.Comparison { return func() cmp.Result { - result, expected := compare([]byte(actual), filename) + actualBytes := removeCarriageReturn([]byte(actual)) + result, expected := compare(actualBytes, filename, removeCarriageReturn) if result != nil { return result } diff, err := difflib.GetUnifiedDiffString(difflib.UnifiedDiff{ A: difflib.SplitLines(string(expected)), - B: difflib.SplitLines(actual), + B: difflib.SplitLines(string(actualBytes)), FromFile: "expected", ToFile: "actual", Context: 3, @@ -110,9 +128,11 @@ func AssertBytes( // Bytes compares actual to the contents of filename and returns success // if the bytes are equal. +// If the `-test.update-golden` flag is set then the actual content is written +// to the golden file. func Bytes(actual []byte, filename string) cmp.Comparison { return func() cmp.Result { - result, expected := compare(actual, filename) + result, expected := compare(actual, filename, exactBytes) if result != nil { return result } @@ -121,8 +141,8 @@ func Bytes(actual []byte, filename string) cmp.Comparison { } } -func compare(actual []byte, filename string) (cmp.Result, []byte) { - if err := update(filename, actual); err != nil { +func compare(actual []byte, filename string, normalize normalize) (cmp.Result, []byte) { + if err := update(filename, actual, normalize); err != nil { return cmp.ResultFromError(err), nil } expected, err := ioutil.ReadFile(Path(filename)) diff --git a/vendor/github.com/stretchr/testify/LICENSE b/vendor/github.com/stretchr/testify/LICENSE deleted file mode 100644 index 473b670a7c..0000000000 --- a/vendor/github.com/stretchr/testify/LICENSE +++ /dev/null @@ -1,22 +0,0 @@ -Copyright (c) 2012 - 2013 Mat Ryer and Tyler Bunnell - -Please consider promoting this project if you find it useful. - -Permission is hereby granted, free of charge, to any person -obtaining a copy of this software and associated documentation -files (the "Software"), to deal in the Software without restriction, -including without limitation the rights to use, copy, modify, merge, -publish, distribute, sublicense, and/or sell copies of the Software, -and to permit persons to whom the Software is furnished to do so, -subject to the following conditions: - -The above copyright notice and this permission notice shall be included -in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, -EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES -OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. -IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, -DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT -OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE -OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/vendor/github.com/stretchr/testify/README.md b/vendor/github.com/stretchr/testify/README.md deleted file mode 100644 index e57b1811f0..0000000000 --- a/vendor/github.com/stretchr/testify/README.md +++ /dev/null @@ -1,332 +0,0 @@ -Testify - Thou Shalt Write Tests -================================ - -[![Build Status](https://travis-ci.org/stretchr/testify.svg)](https://travis-ci.org/stretchr/testify) [![Go Report Card](https://goreportcard.com/badge/github.com/stretchr/testify)](https://goreportcard.com/report/github.com/stretchr/testify) [![GoDoc](https://godoc.org/github.com/stretchr/testify?status.svg)](https://godoc.org/github.com/stretchr/testify) - -Go code (golang) set of packages that provide many tools for testifying that your code will behave as you intend. - -Features include: - - * [Easy assertions](#assert-package) - * [Mocking](#mock-package) - * [HTTP response trapping](#http-package) - * [Testing suite interfaces and functions](#suite-package) - -Get started: - - * Install testify with [one line of code](#installation), or [update it with another](#staying-up-to-date) - * For an introduction to writing test code in Go, see http://golang.org/doc/code.html#Testing - * Check out the API Documentation http://godoc.org/github.com/stretchr/testify - * To make your testing life easier, check out our other project, [gorc](http://github.com/stretchr/gorc) - * A little about [Test-Driven Development (TDD)](http://en.wikipedia.org/wiki/Test-driven_development) - - - -[`assert`](http://godoc.org/github.com/stretchr/testify/assert "API documentation") package -------------------------------------------------------------------------------------------- - -The `assert` package provides some helpful methods that allow you to write better test code in Go. - - * Prints friendly, easy to read failure descriptions - * Allows for very readable code - * Optionally annotate each assertion with a message - -See it in action: - -```go -package yours - -import ( - "testing" - "github.com/stretchr/testify/assert" -) - -func TestSomething(t *testing.T) { - - // assert equality - assert.Equal(t, 123, 123, "they should be equal") - - // assert inequality - assert.NotEqual(t, 123, 456, "they should not be equal") - - // assert for nil (good for errors) - assert.Nil(t, object) - - // assert for not nil (good when you expect something) - if assert.NotNil(t, object) { - - // now we know that object isn't nil, we are safe to make - // further assertions without causing any errors - assert.Equal(t, "Something", object.Value) - - } - -} -``` - - * Every assert func takes the `testing.T` object as the first argument. This is how it writes the errors out through the normal `go test` capabilities. - * Every assert func returns a bool indicating whether the assertion was successful or not, this is useful for if you want to go on making further assertions under certain conditions. - -if you assert many times, use the below: - -```go -package yours - -import ( - "testing" - "github.com/stretchr/testify/assert" -) - -func TestSomething(t *testing.T) { - assert := assert.New(t) - - // assert equality - assert.Equal(123, 123, "they should be equal") - - // assert inequality - assert.NotEqual(123, 456, "they should not be equal") - - // assert for nil (good for errors) - assert.Nil(object) - - // assert for not nil (good when you expect something) - if assert.NotNil(object) { - - // now we know that object isn't nil, we are safe to make - // further assertions without causing any errors - assert.Equal("Something", object.Value) - } -} -``` - -[`require`](http://godoc.org/github.com/stretchr/testify/require "API documentation") package ---------------------------------------------------------------------------------------------- - -The `require` package provides same global functions as the `assert` package, but instead of returning a boolean result they terminate current test. - -See [t.FailNow](http://golang.org/pkg/testing/#T.FailNow) for details. - - -[`http`](http://godoc.org/github.com/stretchr/testify/http "API documentation") package ---------------------------------------------------------------------------------------- - -The `http` package contains test objects useful for testing code that relies on the `net/http` package. Check out the [(deprecated) API documentation for the `http` package](http://godoc.org/github.com/stretchr/testify/http). - -We recommend you use [httptest](http://golang.org/pkg/net/http/httptest) instead. - -[`mock`](http://godoc.org/github.com/stretchr/testify/mock "API documentation") package ----------------------------------------------------------------------------------------- - -The `mock` package provides a mechanism for easily writing mock objects that can be used in place of real objects when writing test code. - -An example test function that tests a piece of code that relies on an external object `testObj`, can setup expectations (testify) and assert that they indeed happened: - -```go -package yours - -import ( - "testing" - "github.com/stretchr/testify/mock" -) - -/* - Test objects -*/ - -// MyMockedObject is a mocked object that implements an interface -// that describes an object that the code I am testing relies on. -type MyMockedObject struct{ - mock.Mock -} - -// DoSomething is a method on MyMockedObject that implements some interface -// and just records the activity, and returns what the Mock object tells it to. -// -// In the real object, this method would do something useful, but since this -// is a mocked object - we're just going to stub it out. -// -// NOTE: This method is not being tested here, code that uses this object is. -func (m *MyMockedObject) DoSomething(number int) (bool, error) { - - args := m.Called(number) - return args.Bool(0), args.Error(1) - -} - -/* - Actual test functions -*/ - -// TestSomething is an example of how to use our test object to -// make assertions about some target code we are testing. -func TestSomething(t *testing.T) { - - // create an instance of our test object - testObj := new(MyMockedObject) - - // setup expectations - testObj.On("DoSomething", 123).Return(true, nil) - - // call the code we are testing - targetFuncThatDoesSomethingWithObj(testObj) - - // assert that the expectations were met - testObj.AssertExpectations(t) - -} -``` - -For more information on how to write mock code, check out the [API documentation for the `mock` package](http://godoc.org/github.com/stretchr/testify/mock). - -You can use the [mockery tool](http://github.com/vektra/mockery) to autogenerate the mock code against an interface as well, making using mocks much quicker. - -[`suite`](http://godoc.org/github.com/stretchr/testify/suite "API documentation") package ------------------------------------------------------------------------------------------ - -The `suite` package provides functionality that you might be used to from more common object oriented languages. With it, you can build a testing suite as a struct, build setup/teardown methods and testing methods on your struct, and run them with 'go test' as per normal. - -An example suite is shown below: - -```go -// Basic imports -import ( - "testing" - "github.com/stretchr/testify/assert" - "github.com/stretchr/testify/suite" -) - -// Define the suite, and absorb the built-in basic suite -// functionality from testify - including a T() method which -// returns the current testing context -type ExampleTestSuite struct { - suite.Suite - VariableThatShouldStartAtFive int -} - -// Make sure that VariableThatShouldStartAtFive is set to five -// before each test -func (suite *ExampleTestSuite) SetupTest() { - suite.VariableThatShouldStartAtFive = 5 -} - -// All methods that begin with "Test" are run as tests within a -// suite. -func (suite *ExampleTestSuite) TestExample() { - assert.Equal(suite.T(), 5, suite.VariableThatShouldStartAtFive) -} - -// In order for 'go test' to run this suite, we need to create -// a normal test function and pass our suite to suite.Run -func TestExampleTestSuite(t *testing.T) { - suite.Run(t, new(ExampleTestSuite)) -} -``` - -For a more complete example, using all of the functionality provided by the suite package, look at our [example testing suite](https://github.com/stretchr/testify/blob/master/suite/suite_test.go) - -For more information on writing suites, check out the [API documentation for the `suite` package](http://godoc.org/github.com/stretchr/testify/suite). - -`Suite` object has assertion methods: - -```go -// Basic imports -import ( - "testing" - "github.com/stretchr/testify/suite" -) - -// Define the suite, and absorb the built-in basic suite -// functionality from testify - including assertion methods. -type ExampleTestSuite struct { - suite.Suite - VariableThatShouldStartAtFive int -} - -// Make sure that VariableThatShouldStartAtFive is set to five -// before each test -func (suite *ExampleTestSuite) SetupTest() { - suite.VariableThatShouldStartAtFive = 5 -} - -// All methods that begin with "Test" are run as tests within a -// suite. -func (suite *ExampleTestSuite) TestExample() { - suite.Equal(suite.VariableThatShouldStartAtFive, 5) -} - -// In order for 'go test' to run this suite, we need to create -// a normal test function and pass our suite to suite.Run -func TestExampleTestSuite(t *testing.T) { - suite.Run(t, new(ExampleTestSuite)) -} -``` - ------- - -Installation -============ - -To install Testify, use `go get`: - - * Latest version: go get github.com/stretchr/testify - * Specific version: go get gopkg.in/stretchr/testify.v1 - -This will then make the following packages available to you: - - github.com/stretchr/testify/assert - github.com/stretchr/testify/mock - github.com/stretchr/testify/http - -Import the `testify/assert` package into your code using this template: - -```go -package yours - -import ( - "testing" - "github.com/stretchr/testify/assert" -) - -func TestSomething(t *testing.T) { - - assert.True(t, true, "True is true!") - -} -``` - ------- - -Staying up to date -================== - -To update Testify to the latest version, use `go get -u github.com/stretchr/testify`. - ------- - -Version History -=============== - - * 1.0 - New package versioning strategy adopted. - ------- - -Contributing -============ - -Please feel free to submit issues, fork the repository and send pull requests! - -When submitting an issue, we ask that you please include a complete test function that demonstrates the issue. Extra credit for those using Testify to write the test code that demonstrates it. - ------- - -Licence -======= -Copyright (c) 2012 - 2013 Mat Ryer and Tyler Bunnell - -Please consider promoting this project if you find it useful. - -Permission is hereby granted, free of charge, to any person obtaining a copy of this software and associated documentation files (the "Software"), to deal in the Software without restriction, including without limitation the rights to use, copy, modify, merge, publish, distribute, sublicense, and/or sell copies of the Software, and to permit persons to whom the Software is furnished to do so, subject to the following conditions: - -The above copyright notice and this permission notice shall be included in all copies or substantial portions of the Software. - -THE SOFTWARE IS PROVIDED "AS IS", WITHOUT WARRANTY OF ANY KIND, EXPRESS OR IMPLIED, INCLUDING BUT NOT LIMITED TO THE WARRANTIES OF MERCHANTABILITY, FITNESS FOR A PARTICULAR PURPOSE AND NONINFRINGEMENT. IN NO EVENT SHALL THE AUTHORS OR COPYRIGHT HOLDERS BE LIABLE FOR ANY CLAIM, DAMAGES OR OTHER LIABILITY, WHETHER IN AN ACTION OF CONTRACT, TORT OR OTHERWISE, ARISING FROM, OUT OF OR IN CONNECTION WITH THE SOFTWARE OR THE USE OR OTHER DEALINGS IN THE SOFTWARE. diff --git a/vendor/github.com/stretchr/testify/assert/assertion_forward.go b/vendor/github.com/stretchr/testify/assert/assertion_forward.go deleted file mode 100644 index aa4311ff84..0000000000 --- a/vendor/github.com/stretchr/testify/assert/assertion_forward.go +++ /dev/null @@ -1,352 +0,0 @@ -/* -* CODE GENERATED AUTOMATICALLY WITH github.com/stretchr/testify/_codegen -* THIS FILE MUST NOT BE EDITED BY HAND - */ - -package assert - -import ( - http "net/http" - url "net/url" - time "time" -) - -// Condition uses a Comparison to assert a complex condition. -func (a *Assertions) Condition(comp Comparison, msgAndArgs ...interface{}) bool { - return Condition(a.t, comp, msgAndArgs...) -} - -// Contains asserts that the specified string, list(array, slice...) or map contains the -// specified substring or element. -// -// a.Contains("Hello World", "World", "But 'Hello World' does contain 'World'") -// a.Contains(["Hello", "World"], "World", "But ["Hello", "World"] does contain 'World'") -// a.Contains({"Hello": "World"}, "Hello", "But {'Hello': 'World'} does contain 'Hello'") -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) Contains(s interface{}, contains interface{}, msgAndArgs ...interface{}) bool { - return Contains(a.t, s, contains, msgAndArgs...) -} - -// Empty asserts that the specified object is empty. I.e. nil, "", false, 0 or either -// a slice or a channel with len == 0. -// -// a.Empty(obj) -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) Empty(object interface{}, msgAndArgs ...interface{}) bool { - return Empty(a.t, object, msgAndArgs...) -} - -// Equal asserts that two objects are equal. -// -// a.Equal(123, 123, "123 and 123 should be equal") -// -// Returns whether the assertion was successful (true) or not (false). -// -// Pointer variable equality is determined based on the equality of the -// referenced values (as opposed to the memory addresses). -func (a *Assertions) Equal(expected interface{}, actual interface{}, msgAndArgs ...interface{}) bool { - return Equal(a.t, expected, actual, msgAndArgs...) -} - -// EqualError asserts that a function returned an error (i.e. not `nil`) -// and that it is equal to the provided error. -// -// actualObj, err := SomeFunction() -// a.EqualError(err, expectedErrorString, "An error was expected") -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) EqualError(theError error, errString string, msgAndArgs ...interface{}) bool { - return EqualError(a.t, theError, errString, msgAndArgs...) -} - -// EqualValues asserts that two objects are equal or convertable to the same types -// and equal. -// -// a.EqualValues(uint32(123), int32(123), "123 and 123 should be equal") -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) EqualValues(expected interface{}, actual interface{}, msgAndArgs ...interface{}) bool { - return EqualValues(a.t, expected, actual, msgAndArgs...) -} - -// Error asserts that a function returned an error (i.e. not `nil`). -// -// actualObj, err := SomeFunction() -// if a.Error(err, "An error was expected") { -// assert.Equal(t, err, expectedError) -// } -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) Error(err error, msgAndArgs ...interface{}) bool { - return Error(a.t, err, msgAndArgs...) -} - -// Exactly asserts that two objects are equal is value and type. -// -// a.Exactly(int32(123), int64(123), "123 and 123 should NOT be equal") -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) Exactly(expected interface{}, actual interface{}, msgAndArgs ...interface{}) bool { - return Exactly(a.t, expected, actual, msgAndArgs...) -} - -// Fail reports a failure through -func (a *Assertions) Fail(failureMessage string, msgAndArgs ...interface{}) bool { - return Fail(a.t, failureMessage, msgAndArgs...) -} - -// FailNow fails test -func (a *Assertions) FailNow(failureMessage string, msgAndArgs ...interface{}) bool { - return FailNow(a.t, failureMessage, msgAndArgs...) -} - -// False asserts that the specified value is false. -// -// a.False(myBool, "myBool should be false") -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) False(value bool, msgAndArgs ...interface{}) bool { - return False(a.t, value, msgAndArgs...) -} - -// HTTPBodyContains asserts that a specified handler returns a -// body that contains a string. -// -// a.HTTPBodyContains(myHandler, "www.google.com", nil, "I'm Feeling Lucky") -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) HTTPBodyContains(handler http.HandlerFunc, method string, url string, values url.Values, str interface{}) bool { - return HTTPBodyContains(a.t, handler, method, url, values, str) -} - -// HTTPBodyNotContains asserts that a specified handler returns a -// body that does not contain a string. -// -// a.HTTPBodyNotContains(myHandler, "www.google.com", nil, "I'm Feeling Lucky") -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) HTTPBodyNotContains(handler http.HandlerFunc, method string, url string, values url.Values, str interface{}) bool { - return HTTPBodyNotContains(a.t, handler, method, url, values, str) -} - -// HTTPError asserts that a specified handler returns an error status code. -// -// a.HTTPError(myHandler, "POST", "/a/b/c", url.Values{"a": []string{"b", "c"}} -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) HTTPError(handler http.HandlerFunc, method string, url string, values url.Values) bool { - return HTTPError(a.t, handler, method, url, values) -} - -// HTTPRedirect asserts that a specified handler returns a redirect status code. -// -// a.HTTPRedirect(myHandler, "GET", "/a/b/c", url.Values{"a": []string{"b", "c"}} -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) HTTPRedirect(handler http.HandlerFunc, method string, url string, values url.Values) bool { - return HTTPRedirect(a.t, handler, method, url, values) -} - -// HTTPSuccess asserts that a specified handler returns a success status code. -// -// a.HTTPSuccess(myHandler, "POST", "http://www.google.com", nil) -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) HTTPSuccess(handler http.HandlerFunc, method string, url string, values url.Values) bool { - return HTTPSuccess(a.t, handler, method, url, values) -} - -// Implements asserts that an object is implemented by the specified interface. -// -// a.Implements((*MyInterface)(nil), new(MyObject), "MyObject") -func (a *Assertions) Implements(interfaceObject interface{}, object interface{}, msgAndArgs ...interface{}) bool { - return Implements(a.t, interfaceObject, object, msgAndArgs...) -} - -// InDelta asserts that the two numerals are within delta of each other. -// -// a.InDelta(math.Pi, (22 / 7.0), 0.01) -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) InDelta(expected interface{}, actual interface{}, delta float64, msgAndArgs ...interface{}) bool { - return InDelta(a.t, expected, actual, delta, msgAndArgs...) -} - -// InDeltaSlice is the same as InDelta, except it compares two slices. -func (a *Assertions) InDeltaSlice(expected interface{}, actual interface{}, delta float64, msgAndArgs ...interface{}) bool { - return InDeltaSlice(a.t, expected, actual, delta, msgAndArgs...) -} - -// InEpsilon asserts that expected and actual have a relative error less than epsilon -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) InEpsilon(expected interface{}, actual interface{}, epsilon float64, msgAndArgs ...interface{}) bool { - return InEpsilon(a.t, expected, actual, epsilon, msgAndArgs...) -} - -// InEpsilonSlice is the same as InEpsilon, except it compares each value from two slices. -func (a *Assertions) InEpsilonSlice(expected interface{}, actual interface{}, epsilon float64, msgAndArgs ...interface{}) bool { - return InEpsilonSlice(a.t, expected, actual, epsilon, msgAndArgs...) -} - -// IsType asserts that the specified objects are of the same type. -func (a *Assertions) IsType(expectedType interface{}, object interface{}, msgAndArgs ...interface{}) bool { - return IsType(a.t, expectedType, object, msgAndArgs...) -} - -// JSONEq asserts that two JSON strings are equivalent. -// -// a.JSONEq(`{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`) -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) JSONEq(expected string, actual string, msgAndArgs ...interface{}) bool { - return JSONEq(a.t, expected, actual, msgAndArgs...) -} - -// Len asserts that the specified object has specific length. -// Len also fails if the object has a type that len() not accept. -// -// a.Len(mySlice, 3, "The size of slice is not 3") -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) Len(object interface{}, length int, msgAndArgs ...interface{}) bool { - return Len(a.t, object, length, msgAndArgs...) -} - -// Nil asserts that the specified object is nil. -// -// a.Nil(err, "err should be nothing") -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) Nil(object interface{}, msgAndArgs ...interface{}) bool { - return Nil(a.t, object, msgAndArgs...) -} - -// NoError asserts that a function returned no error (i.e. `nil`). -// -// actualObj, err := SomeFunction() -// if a.NoError(err) { -// assert.Equal(t, actualObj, expectedObj) -// } -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) NoError(err error, msgAndArgs ...interface{}) bool { - return NoError(a.t, err, msgAndArgs...) -} - -// NotContains asserts that the specified string, list(array, slice...) or map does NOT contain the -// specified substring or element. -// -// a.NotContains("Hello World", "Earth", "But 'Hello World' does NOT contain 'Earth'") -// a.NotContains(["Hello", "World"], "Earth", "But ['Hello', 'World'] does NOT contain 'Earth'") -// a.NotContains({"Hello": "World"}, "Earth", "But {'Hello': 'World'} does NOT contain 'Earth'") -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) NotContains(s interface{}, contains interface{}, msgAndArgs ...interface{}) bool { - return NotContains(a.t, s, contains, msgAndArgs...) -} - -// NotEmpty asserts that the specified object is NOT empty. I.e. not nil, "", false, 0 or either -// a slice or a channel with len == 0. -// -// if a.NotEmpty(obj) { -// assert.Equal(t, "two", obj[1]) -// } -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) NotEmpty(object interface{}, msgAndArgs ...interface{}) bool { - return NotEmpty(a.t, object, msgAndArgs...) -} - -// NotEqual asserts that the specified values are NOT equal. -// -// a.NotEqual(obj1, obj2, "two objects shouldn't be equal") -// -// Returns whether the assertion was successful (true) or not (false). -// -// Pointer variable equality is determined based on the equality of the -// referenced values (as opposed to the memory addresses). -func (a *Assertions) NotEqual(expected interface{}, actual interface{}, msgAndArgs ...interface{}) bool { - return NotEqual(a.t, expected, actual, msgAndArgs...) -} - -// NotNil asserts that the specified object is not nil. -// -// a.NotNil(err, "err should be something") -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) NotNil(object interface{}, msgAndArgs ...interface{}) bool { - return NotNil(a.t, object, msgAndArgs...) -} - -// NotPanics asserts that the code inside the specified PanicTestFunc does NOT panic. -// -// a.NotPanics(func(){ -// RemainCalm() -// }, "Calling RemainCalm() should NOT panic") -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) NotPanics(f PanicTestFunc, msgAndArgs ...interface{}) bool { - return NotPanics(a.t, f, msgAndArgs...) -} - -// NotRegexp asserts that a specified regexp does not match a string. -// -// a.NotRegexp(regexp.MustCompile("starts"), "it's starting") -// a.NotRegexp("^start", "it's not starting") -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) NotRegexp(rx interface{}, str interface{}, msgAndArgs ...interface{}) bool { - return NotRegexp(a.t, rx, str, msgAndArgs...) -} - -// NotZero asserts that i is not the zero value for its type and returns the truth. -func (a *Assertions) NotZero(i interface{}, msgAndArgs ...interface{}) bool { - return NotZero(a.t, i, msgAndArgs...) -} - -// Panics asserts that the code inside the specified PanicTestFunc panics. -// -// a.Panics(func(){ -// GoCrazy() -// }, "Calling GoCrazy() should panic") -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) Panics(f PanicTestFunc, msgAndArgs ...interface{}) bool { - return Panics(a.t, f, msgAndArgs...) -} - -// Regexp asserts that a specified regexp matches a string. -// -// a.Regexp(regexp.MustCompile("start"), "it's starting") -// a.Regexp("start...$", "it's not starting") -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) Regexp(rx interface{}, str interface{}, msgAndArgs ...interface{}) bool { - return Regexp(a.t, rx, str, msgAndArgs...) -} - -// True asserts that the specified value is true. -// -// a.True(myBool, "myBool should be true") -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) True(value bool, msgAndArgs ...interface{}) bool { - return True(a.t, value, msgAndArgs...) -} - -// WithinDuration asserts that the two times are within duration delta of each other. -// -// a.WithinDuration(time.Now(), time.Now(), 10*time.Second, "The difference should not be more than 10s") -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) WithinDuration(expected time.Time, actual time.Time, delta time.Duration, msgAndArgs ...interface{}) bool { - return WithinDuration(a.t, expected, actual, delta, msgAndArgs...) -} - -// Zero asserts that i is the zero value for its type and returns the truth. -func (a *Assertions) Zero(i interface{}, msgAndArgs ...interface{}) bool { - return Zero(a.t, i, msgAndArgs...) -} diff --git a/vendor/github.com/stretchr/testify/assert/assertions.go b/vendor/github.com/stretchr/testify/assert/assertions.go deleted file mode 100644 index d1552e5e3f..0000000000 --- a/vendor/github.com/stretchr/testify/assert/assertions.go +++ /dev/null @@ -1,1069 +0,0 @@ -package assert - -import ( - "bufio" - "bytes" - "encoding/json" - "fmt" - "math" - "reflect" - "regexp" - "runtime" - "strings" - "time" - "unicode" - "unicode/utf8" - - "github.com/davecgh/go-spew/spew" - "github.com/pmezard/go-difflib/difflib" -) - -// TestingT is an interface wrapper around *testing.T -type TestingT interface { - Errorf(format string, args ...interface{}) -} - -// Comparison a custom function that returns true on success and false on failure -type Comparison func() (success bool) - -/* - Helper functions -*/ - -// ObjectsAreEqual determines if two objects are considered equal. -// -// This function does no assertion of any kind. -func ObjectsAreEqual(expected, actual interface{}) bool { - - if expected == nil || actual == nil { - return expected == actual - } - - return reflect.DeepEqual(expected, actual) - -} - -// ObjectsAreEqualValues gets whether two objects are equal, or if their -// values are equal. -func ObjectsAreEqualValues(expected, actual interface{}) bool { - if ObjectsAreEqual(expected, actual) { - return true - } - - actualType := reflect.TypeOf(actual) - if actualType == nil { - return false - } - expectedValue := reflect.ValueOf(expected) - if expectedValue.IsValid() && expectedValue.Type().ConvertibleTo(actualType) { - // Attempt comparison after type conversion - return reflect.DeepEqual(expectedValue.Convert(actualType).Interface(), actual) - } - - return false -} - -/* CallerInfo is necessary because the assert functions use the testing object -internally, causing it to print the file:line of the assert method, rather than where -the problem actually occurred in calling code.*/ - -// CallerInfo returns an array of strings containing the file and line number -// of each stack frame leading from the current test to the assert call that -// failed. -func CallerInfo() []string { - - pc := uintptr(0) - file := "" - line := 0 - ok := false - name := "" - - callers := []string{} - for i := 0; ; i++ { - pc, file, line, ok = runtime.Caller(i) - if !ok { - // The breaks below failed to terminate the loop, and we ran off the - // end of the call stack. - break - } - - // This is a huge edge case, but it will panic if this is the case, see #180 - if file == "" { - break - } - - f := runtime.FuncForPC(pc) - if f == nil { - break - } - name = f.Name() - - // testing.tRunner is the standard library function that calls - // tests. Subtests are called directly by tRunner, without going through - // the Test/Benchmark/Example function that contains the t.Run calls, so - // with subtests we should break when we hit tRunner, without adding it - // to the list of callers. - if name == "testing.tRunner" { - break - } - - parts := strings.Split(file, "/") - dir := parts[len(parts)-2] - file = parts[len(parts)-1] - if (dir != "assert" && dir != "mock" && dir != "require") || file == "mock_test.go" { - callers = append(callers, fmt.Sprintf("%s:%d", file, line)) - } - - // Drop the package - segments := strings.Split(name, ".") - name = segments[len(segments)-1] - if isTest(name, "Test") || - isTest(name, "Benchmark") || - isTest(name, "Example") { - break - } - } - - return callers -} - -// Stolen from the `go test` tool. -// isTest tells whether name looks like a test (or benchmark, according to prefix). -// It is a Test (say) if there is a character after Test that is not a lower-case letter. -// We don't want TesticularCancer. -func isTest(name, prefix string) bool { - if !strings.HasPrefix(name, prefix) { - return false - } - if len(name) == len(prefix) { // "Test" is ok - return true - } - rune, _ := utf8.DecodeRuneInString(name[len(prefix):]) - return !unicode.IsLower(rune) -} - -// getWhitespaceString returns a string that is long enough to overwrite the default -// output from the go testing framework. -func getWhitespaceString() string { - - _, file, line, ok := runtime.Caller(1) - if !ok { - return "" - } - parts := strings.Split(file, "/") - file = parts[len(parts)-1] - - return strings.Repeat(" ", len(fmt.Sprintf("%s:%d: ", file, line))) - -} - -func messageFromMsgAndArgs(msgAndArgs ...interface{}) string { - if len(msgAndArgs) == 0 || msgAndArgs == nil { - return "" - } - if len(msgAndArgs) == 1 { - return msgAndArgs[0].(string) - } - if len(msgAndArgs) > 1 { - return fmt.Sprintf(msgAndArgs[0].(string), msgAndArgs[1:]...) - } - return "" -} - -// Aligns the provided message so that all lines after the first line start at the same location as the first line. -// Assumes that the first line starts at the correct location (after carriage return, tab, label, spacer and tab). -// The longestLabelLen parameter specifies the length of the longest label in the output (required becaues this is the -// basis on which the alignment occurs). -func indentMessageLines(message string, longestLabelLen int) string { - outBuf := new(bytes.Buffer) - - for i, scanner := 0, bufio.NewScanner(strings.NewReader(message)); scanner.Scan(); i++ { - // no need to align first line because it starts at the correct location (after the label) - if i != 0 { - // append alignLen+1 spaces to align with "{{longestLabel}}:" before adding tab - outBuf.WriteString("\n\r\t" + strings.Repeat(" ", longestLabelLen +1) + "\t") - } - outBuf.WriteString(scanner.Text()) - } - - return outBuf.String() -} - -type failNower interface { - FailNow() -} - -// FailNow fails test -func FailNow(t TestingT, failureMessage string, msgAndArgs ...interface{}) bool { - Fail(t, failureMessage, msgAndArgs...) - - // We cannot extend TestingT with FailNow() and - // maintain backwards compatibility, so we fallback - // to panicking when FailNow is not available in - // TestingT. - // See issue #263 - - if t, ok := t.(failNower); ok { - t.FailNow() - } else { - panic("test failed and t is missing `FailNow()`") - } - return false -} - -// Fail reports a failure through -func Fail(t TestingT, failureMessage string, msgAndArgs ...interface{}) bool { - content := []labeledContent{ - {"Error Trace", strings.Join(CallerInfo(), "\n\r\t\t\t")}, - {"Error", failureMessage}, - } - - message := messageFromMsgAndArgs(msgAndArgs...) - if len(message) > 0 { - content = append(content, labeledContent{"Messages", message}) - } - - t.Errorf("\r" + getWhitespaceString() + labeledOutput(content...)) - - return false -} - -type labeledContent struct { - label string - content string -} - -// labeledOutput returns a string consisting of the provided labeledContent. Each labeled output is appended in the following manner: -// -// \r\t{{label}}:{{align_spaces}}\t{{content}}\n -// -// The initial carriage return is required to undo/erase any padding added by testing.T.Errorf. The "\t{{label}}:" is for the label. -// If a label is shorter than the longest label provided, padding spaces are added to make all the labels match in length. Once this -// alignment is achieved, "\t{{content}}\n" is added for the output. -// -// If the content of the labeledOutput contains line breaks, the subsequent lines are aligned so that they start at the same location as the first line. -func labeledOutput(content ...labeledContent) string { - longestLabel := 0 - for _, v := range content { - if len(v.label) > longestLabel { - longestLabel = len(v.label) - } - } - var output string - for _, v := range content { - output += "\r\t" + v.label + ":" + strings.Repeat(" ", longestLabel-len(v.label)) + "\t" + indentMessageLines(v.content, longestLabel) + "\n" - } - return output -} - -// Implements asserts that an object is implemented by the specified interface. -// -// assert.Implements(t, (*MyInterface)(nil), new(MyObject), "MyObject") -func Implements(t TestingT, interfaceObject interface{}, object interface{}, msgAndArgs ...interface{}) bool { - - interfaceType := reflect.TypeOf(interfaceObject).Elem() - - if !reflect.TypeOf(object).Implements(interfaceType) { - return Fail(t, fmt.Sprintf("%T must implement %v", object, interfaceType), msgAndArgs...) - } - - return true - -} - -// IsType asserts that the specified objects are of the same type. -func IsType(t TestingT, expectedType interface{}, object interface{}, msgAndArgs ...interface{}) bool { - - if !ObjectsAreEqual(reflect.TypeOf(object), reflect.TypeOf(expectedType)) { - return Fail(t, fmt.Sprintf("Object expected to be of type %v, but was %v", reflect.TypeOf(expectedType), reflect.TypeOf(object)), msgAndArgs...) - } - - return true -} - -// Equal asserts that two objects are equal. -// -// assert.Equal(t, 123, 123, "123 and 123 should be equal") -// -// Returns whether the assertion was successful (true) or not (false). -// -// Pointer variable equality is determined based on the equality of the -// referenced values (as opposed to the memory addresses). -func Equal(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool { - - if !ObjectsAreEqual(expected, actual) { - diff := diff(expected, actual) - expected, actual = formatUnequalValues(expected, actual) - return Fail(t, fmt.Sprintf("Not equal: \n"+ - "expected: %s\n"+ - "received: %s%s", expected, actual, diff), msgAndArgs...) - } - - return true - -} - -// formatUnequalValues takes two values of arbitrary types and returns string -// representations appropriate to be presented to the user. -// -// If the values are not of like type, the returned strings will be prefixed -// with the type name, and the value will be enclosed in parenthesis similar -// to a type conversion in the Go grammar. -func formatUnequalValues(expected, actual interface{}) (e string, a string) { - if reflect.TypeOf(expected) != reflect.TypeOf(actual) { - return fmt.Sprintf("%T(%#v)", expected, expected), - fmt.Sprintf("%T(%#v)", actual, actual) - } - - return fmt.Sprintf("%#v", expected), - fmt.Sprintf("%#v", actual) -} - -// EqualValues asserts that two objects are equal or convertable to the same types -// and equal. -// -// assert.EqualValues(t, uint32(123), int32(123), "123 and 123 should be equal") -// -// Returns whether the assertion was successful (true) or not (false). -func EqualValues(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool { - - if !ObjectsAreEqualValues(expected, actual) { - diff := diff(expected, actual) - expected, actual = formatUnequalValues(expected, actual) - return Fail(t, fmt.Sprintf("Not equal: \n"+ - "expected: %s\n"+ - "received: %s%s", expected, actual, diff), msgAndArgs...) - } - - return true - -} - -// Exactly asserts that two objects are equal is value and type. -// -// assert.Exactly(t, int32(123), int64(123), "123 and 123 should NOT be equal") -// -// Returns whether the assertion was successful (true) or not (false). -func Exactly(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool { - - aType := reflect.TypeOf(expected) - bType := reflect.TypeOf(actual) - - if aType != bType { - return Fail(t, fmt.Sprintf("Types expected to match exactly\n\r\t%v != %v", aType, bType), msgAndArgs...) - } - - return Equal(t, expected, actual, msgAndArgs...) - -} - -// NotNil asserts that the specified object is not nil. -// -// assert.NotNil(t, err, "err should be something") -// -// Returns whether the assertion was successful (true) or not (false). -func NotNil(t TestingT, object interface{}, msgAndArgs ...interface{}) bool { - if !isNil(object) { - return true - } - return Fail(t, "Expected value not to be nil.", msgAndArgs...) -} - -// isNil checks if a specified object is nil or not, without Failing. -func isNil(object interface{}) bool { - if object == nil { - return true - } - - value := reflect.ValueOf(object) - kind := value.Kind() - if kind >= reflect.Chan && kind <= reflect.Slice && value.IsNil() { - return true - } - - return false -} - -// Nil asserts that the specified object is nil. -// -// assert.Nil(t, err, "err should be nothing") -// -// Returns whether the assertion was successful (true) or not (false). -func Nil(t TestingT, object interface{}, msgAndArgs ...interface{}) bool { - if isNil(object) { - return true - } - return Fail(t, fmt.Sprintf("Expected nil, but got: %#v", object), msgAndArgs...) -} - -var numericZeros = []interface{}{ - int(0), - int8(0), - int16(0), - int32(0), - int64(0), - uint(0), - uint8(0), - uint16(0), - uint32(0), - uint64(0), - float32(0), - float64(0), -} - -// isEmpty gets whether the specified object is considered empty or not. -func isEmpty(object interface{}) bool { - - if object == nil { - return true - } else if object == "" { - return true - } else if object == false { - return true - } - - for _, v := range numericZeros { - if object == v { - return true - } - } - - objValue := reflect.ValueOf(object) - - switch objValue.Kind() { - case reflect.Map: - fallthrough - case reflect.Slice, reflect.Chan: - { - return (objValue.Len() == 0) - } - case reflect.Struct: - switch object.(type) { - case time.Time: - return object.(time.Time).IsZero() - } - case reflect.Ptr: - { - if objValue.IsNil() { - return true - } - switch object.(type) { - case *time.Time: - return object.(*time.Time).IsZero() - default: - return false - } - } - } - return false -} - -// Empty asserts that the specified object is empty. I.e. nil, "", false, 0 or either -// a slice or a channel with len == 0. -// -// assert.Empty(t, obj) -// -// Returns whether the assertion was successful (true) or not (false). -func Empty(t TestingT, object interface{}, msgAndArgs ...interface{}) bool { - - pass := isEmpty(object) - if !pass { - Fail(t, fmt.Sprintf("Should be empty, but was %v", object), msgAndArgs...) - } - - return pass - -} - -// NotEmpty asserts that the specified object is NOT empty. I.e. not nil, "", false, 0 or either -// a slice or a channel with len == 0. -// -// if assert.NotEmpty(t, obj) { -// assert.Equal(t, "two", obj[1]) -// } -// -// Returns whether the assertion was successful (true) or not (false). -func NotEmpty(t TestingT, object interface{}, msgAndArgs ...interface{}) bool { - - pass := !isEmpty(object) - if !pass { - Fail(t, fmt.Sprintf("Should NOT be empty, but was %v", object), msgAndArgs...) - } - - return pass - -} - -// getLen try to get length of object. -// return (false, 0) if impossible. -func getLen(x interface{}) (ok bool, length int) { - v := reflect.ValueOf(x) - defer func() { - if e := recover(); e != nil { - ok = false - } - }() - return true, v.Len() -} - -// Len asserts that the specified object has specific length. -// Len also fails if the object has a type that len() not accept. -// -// assert.Len(t, mySlice, 3, "The size of slice is not 3") -// -// Returns whether the assertion was successful (true) or not (false). -func Len(t TestingT, object interface{}, length int, msgAndArgs ...interface{}) bool { - ok, l := getLen(object) - if !ok { - return Fail(t, fmt.Sprintf("\"%s\" could not be applied builtin len()", object), msgAndArgs...) - } - - if l != length { - return Fail(t, fmt.Sprintf("\"%s\" should have %d item(s), but has %d", object, length, l), msgAndArgs...) - } - return true -} - -// True asserts that the specified value is true. -// -// assert.True(t, myBool, "myBool should be true") -// -// Returns whether the assertion was successful (true) or not (false). -func True(t TestingT, value bool, msgAndArgs ...interface{}) bool { - - if value != true { - return Fail(t, "Should be true", msgAndArgs...) - } - - return true - -} - -// False asserts that the specified value is false. -// -// assert.False(t, myBool, "myBool should be false") -// -// Returns whether the assertion was successful (true) or not (false). -func False(t TestingT, value bool, msgAndArgs ...interface{}) bool { - - if value != false { - return Fail(t, "Should be false", msgAndArgs...) - } - - return true - -} - -// NotEqual asserts that the specified values are NOT equal. -// -// assert.NotEqual(t, obj1, obj2, "two objects shouldn't be equal") -// -// Returns whether the assertion was successful (true) or not (false). -// -// Pointer variable equality is determined based on the equality of the -// referenced values (as opposed to the memory addresses). -func NotEqual(t TestingT, expected, actual interface{}, msgAndArgs ...interface{}) bool { - - if ObjectsAreEqual(expected, actual) { - return Fail(t, fmt.Sprintf("Should not be: %#v\n", actual), msgAndArgs...) - } - - return true - -} - -// containsElement try loop over the list check if the list includes the element. -// return (false, false) if impossible. -// return (true, false) if element was not found. -// return (true, true) if element was found. -func includeElement(list interface{}, element interface{}) (ok, found bool) { - - listValue := reflect.ValueOf(list) - elementValue := reflect.ValueOf(element) - defer func() { - if e := recover(); e != nil { - ok = false - found = false - } - }() - - if reflect.TypeOf(list).Kind() == reflect.String { - return true, strings.Contains(listValue.String(), elementValue.String()) - } - - if reflect.TypeOf(list).Kind() == reflect.Map { - mapKeys := listValue.MapKeys() - for i := 0; i < len(mapKeys); i++ { - if ObjectsAreEqual(mapKeys[i].Interface(), element) { - return true, true - } - } - return true, false - } - - for i := 0; i < listValue.Len(); i++ { - if ObjectsAreEqual(listValue.Index(i).Interface(), element) { - return true, true - } - } - return true, false - -} - -// Contains asserts that the specified string, list(array, slice...) or map contains the -// specified substring or element. -// -// assert.Contains(t, "Hello World", "World", "But 'Hello World' does contain 'World'") -// assert.Contains(t, ["Hello", "World"], "World", "But ["Hello", "World"] does contain 'World'") -// assert.Contains(t, {"Hello": "World"}, "Hello", "But {'Hello': 'World'} does contain 'Hello'") -// -// Returns whether the assertion was successful (true) or not (false). -func Contains(t TestingT, s, contains interface{}, msgAndArgs ...interface{}) bool { - - ok, found := includeElement(s, contains) - if !ok { - return Fail(t, fmt.Sprintf("\"%s\" could not be applied builtin len()", s), msgAndArgs...) - } - if !found { - return Fail(t, fmt.Sprintf("\"%s\" does not contain \"%s\"", s, contains), msgAndArgs...) - } - - return true - -} - -// NotContains asserts that the specified string, list(array, slice...) or map does NOT contain the -// specified substring or element. -// -// assert.NotContains(t, "Hello World", "Earth", "But 'Hello World' does NOT contain 'Earth'") -// assert.NotContains(t, ["Hello", "World"], "Earth", "But ['Hello', 'World'] does NOT contain 'Earth'") -// assert.NotContains(t, {"Hello": "World"}, "Earth", "But {'Hello': 'World'} does NOT contain 'Earth'") -// -// Returns whether the assertion was successful (true) or not (false). -func NotContains(t TestingT, s, contains interface{}, msgAndArgs ...interface{}) bool { - - ok, found := includeElement(s, contains) - if !ok { - return Fail(t, fmt.Sprintf("\"%s\" could not be applied builtin len()", s), msgAndArgs...) - } - if found { - return Fail(t, fmt.Sprintf("\"%s\" should not contain \"%s\"", s, contains), msgAndArgs...) - } - - return true - -} - -// Condition uses a Comparison to assert a complex condition. -func Condition(t TestingT, comp Comparison, msgAndArgs ...interface{}) bool { - result := comp() - if !result { - Fail(t, "Condition failed!", msgAndArgs...) - } - return result -} - -// PanicTestFunc defines a func that should be passed to the assert.Panics and assert.NotPanics -// methods, and represents a simple func that takes no arguments, and returns nothing. -type PanicTestFunc func() - -// didPanic returns true if the function passed to it panics. Otherwise, it returns false. -func didPanic(f PanicTestFunc) (bool, interface{}) { - - didPanic := false - var message interface{} - func() { - - defer func() { - if message = recover(); message != nil { - didPanic = true - } - }() - - // call the target function - f() - - }() - - return didPanic, message - -} - -// Panics asserts that the code inside the specified PanicTestFunc panics. -// -// assert.Panics(t, func(){ -// GoCrazy() -// }, "Calling GoCrazy() should panic") -// -// Returns whether the assertion was successful (true) or not (false). -func Panics(t TestingT, f PanicTestFunc, msgAndArgs ...interface{}) bool { - - if funcDidPanic, panicValue := didPanic(f); !funcDidPanic { - return Fail(t, fmt.Sprintf("func %#v should panic\n\r\tPanic value:\t%v", f, panicValue), msgAndArgs...) - } - - return true -} - -// NotPanics asserts that the code inside the specified PanicTestFunc does NOT panic. -// -// assert.NotPanics(t, func(){ -// RemainCalm() -// }, "Calling RemainCalm() should NOT panic") -// -// Returns whether the assertion was successful (true) or not (false). -func NotPanics(t TestingT, f PanicTestFunc, msgAndArgs ...interface{}) bool { - - if funcDidPanic, panicValue := didPanic(f); funcDidPanic { - return Fail(t, fmt.Sprintf("func %#v should not panic\n\r\tPanic value:\t%v", f, panicValue), msgAndArgs...) - } - - return true -} - -// WithinDuration asserts that the two times are within duration delta of each other. -// -// assert.WithinDuration(t, time.Now(), time.Now(), 10*time.Second, "The difference should not be more than 10s") -// -// Returns whether the assertion was successful (true) or not (false). -func WithinDuration(t TestingT, expected, actual time.Time, delta time.Duration, msgAndArgs ...interface{}) bool { - - dt := expected.Sub(actual) - if dt < -delta || dt > delta { - return Fail(t, fmt.Sprintf("Max difference between %v and %v allowed is %v, but difference was %v", expected, actual, delta, dt), msgAndArgs...) - } - - return true -} - -func toFloat(x interface{}) (float64, bool) { - var xf float64 - xok := true - - switch xn := x.(type) { - case uint8: - xf = float64(xn) - case uint16: - xf = float64(xn) - case uint32: - xf = float64(xn) - case uint64: - xf = float64(xn) - case int: - xf = float64(xn) - case int8: - xf = float64(xn) - case int16: - xf = float64(xn) - case int32: - xf = float64(xn) - case int64: - xf = float64(xn) - case float32: - xf = float64(xn) - case float64: - xf = float64(xn) - default: - xok = false - } - - return xf, xok -} - -// InDelta asserts that the two numerals are within delta of each other. -// -// assert.InDelta(t, math.Pi, (22 / 7.0), 0.01) -// -// Returns whether the assertion was successful (true) or not (false). -func InDelta(t TestingT, expected, actual interface{}, delta float64, msgAndArgs ...interface{}) bool { - - af, aok := toFloat(expected) - bf, bok := toFloat(actual) - - if !aok || !bok { - return Fail(t, fmt.Sprintf("Parameters must be numerical"), msgAndArgs...) - } - - if math.IsNaN(af) { - return Fail(t, fmt.Sprintf("Actual must not be NaN"), msgAndArgs...) - } - - if math.IsNaN(bf) { - return Fail(t, fmt.Sprintf("Expected %v with delta %v, but was NaN", expected, delta), msgAndArgs...) - } - - dt := af - bf - if dt < -delta || dt > delta { - return Fail(t, fmt.Sprintf("Max difference between %v and %v allowed is %v, but difference was %v", expected, actual, delta, dt), msgAndArgs...) - } - - return true -} - -// InDeltaSlice is the same as InDelta, except it compares two slices. -func InDeltaSlice(t TestingT, expected, actual interface{}, delta float64, msgAndArgs ...interface{}) bool { - if expected == nil || actual == nil || - reflect.TypeOf(actual).Kind() != reflect.Slice || - reflect.TypeOf(expected).Kind() != reflect.Slice { - return Fail(t, fmt.Sprintf("Parameters must be slice"), msgAndArgs...) - } - - actualSlice := reflect.ValueOf(actual) - expectedSlice := reflect.ValueOf(expected) - - for i := 0; i < actualSlice.Len(); i++ { - result := InDelta(t, actualSlice.Index(i).Interface(), expectedSlice.Index(i).Interface(), delta) - if !result { - return result - } - } - - return true -} - -func calcRelativeError(expected, actual interface{}) (float64, error) { - af, aok := toFloat(expected) - if !aok { - return 0, fmt.Errorf("expected value %q cannot be converted to float", expected) - } - if af == 0 { - return 0, fmt.Errorf("expected value must have a value other than zero to calculate the relative error") - } - bf, bok := toFloat(actual) - if !bok { - return 0, fmt.Errorf("expected value %q cannot be converted to float", actual) - } - - return math.Abs(af-bf) / math.Abs(af), nil -} - -// InEpsilon asserts that expected and actual have a relative error less than epsilon -// -// Returns whether the assertion was successful (true) or not (false). -func InEpsilon(t TestingT, expected, actual interface{}, epsilon float64, msgAndArgs ...interface{}) bool { - actualEpsilon, err := calcRelativeError(expected, actual) - if err != nil { - return Fail(t, err.Error(), msgAndArgs...) - } - if actualEpsilon > epsilon { - return Fail(t, fmt.Sprintf("Relative error is too high: %#v (expected)\n"+ - " < %#v (actual)", actualEpsilon, epsilon), msgAndArgs...) - } - - return true -} - -// InEpsilonSlice is the same as InEpsilon, except it compares each value from two slices. -func InEpsilonSlice(t TestingT, expected, actual interface{}, epsilon float64, msgAndArgs ...interface{}) bool { - if expected == nil || actual == nil || - reflect.TypeOf(actual).Kind() != reflect.Slice || - reflect.TypeOf(expected).Kind() != reflect.Slice { - return Fail(t, fmt.Sprintf("Parameters must be slice"), msgAndArgs...) - } - - actualSlice := reflect.ValueOf(actual) - expectedSlice := reflect.ValueOf(expected) - - for i := 0; i < actualSlice.Len(); i++ { - result := InEpsilon(t, actualSlice.Index(i).Interface(), expectedSlice.Index(i).Interface(), epsilon) - if !result { - return result - } - } - - return true -} - -/* - Errors -*/ - -// NoError asserts that a function returned no error (i.e. `nil`). -// -// actualObj, err := SomeFunction() -// if assert.NoError(t, err) { -// assert.Equal(t, actualObj, expectedObj) -// } -// -// Returns whether the assertion was successful (true) or not (false). -func NoError(t TestingT, err error, msgAndArgs ...interface{}) bool { - if err != nil { - return Fail(t, fmt.Sprintf("Received unexpected error:\n%+v", err), msgAndArgs...) - } - - return true -} - -// Error asserts that a function returned an error (i.e. not `nil`). -// -// actualObj, err := SomeFunction() -// if assert.Error(t, err, "An error was expected") { -// assert.Equal(t, err, expectedError) -// } -// -// Returns whether the assertion was successful (true) or not (false). -func Error(t TestingT, err error, msgAndArgs ...interface{}) bool { - - if err == nil { - return Fail(t, "An error is expected but got nil.", msgAndArgs...) - } - - return true -} - -// EqualError asserts that a function returned an error (i.e. not `nil`) -// and that it is equal to the provided error. -// -// actualObj, err := SomeFunction() -// assert.EqualError(t, err, expectedErrorString, "An error was expected") -// -// Returns whether the assertion was successful (true) or not (false). -func EqualError(t TestingT, theError error, errString string, msgAndArgs ...interface{}) bool { - if !Error(t, theError, msgAndArgs...) { - return false - } - expected := errString - actual := theError.Error() - // don't need to use deep equals here, we know they are both strings - if expected != actual { - return Fail(t, fmt.Sprintf("Error message not equal:\n"+ - "expected: %q\n"+ - "received: %q", expected, actual), msgAndArgs...) - } - return true -} - -// matchRegexp return true if a specified regexp matches a string. -func matchRegexp(rx interface{}, str interface{}) bool { - - var r *regexp.Regexp - if rr, ok := rx.(*regexp.Regexp); ok { - r = rr - } else { - r = regexp.MustCompile(fmt.Sprint(rx)) - } - - return (r.FindStringIndex(fmt.Sprint(str)) != nil) - -} - -// Regexp asserts that a specified regexp matches a string. -// -// assert.Regexp(t, regexp.MustCompile("start"), "it's starting") -// assert.Regexp(t, "start...$", "it's not starting") -// -// Returns whether the assertion was successful (true) or not (false). -func Regexp(t TestingT, rx interface{}, str interface{}, msgAndArgs ...interface{}) bool { - - match := matchRegexp(rx, str) - - if !match { - Fail(t, fmt.Sprintf("Expect \"%v\" to match \"%v\"", str, rx), msgAndArgs...) - } - - return match -} - -// NotRegexp asserts that a specified regexp does not match a string. -// -// assert.NotRegexp(t, regexp.MustCompile("starts"), "it's starting") -// assert.NotRegexp(t, "^start", "it's not starting") -// -// Returns whether the assertion was successful (true) or not (false). -func NotRegexp(t TestingT, rx interface{}, str interface{}, msgAndArgs ...interface{}) bool { - match := matchRegexp(rx, str) - - if match { - Fail(t, fmt.Sprintf("Expect \"%v\" to NOT match \"%v\"", str, rx), msgAndArgs...) - } - - return !match - -} - -// Zero asserts that i is the zero value for its type and returns the truth. -func Zero(t TestingT, i interface{}, msgAndArgs ...interface{}) bool { - if i != nil && !reflect.DeepEqual(i, reflect.Zero(reflect.TypeOf(i)).Interface()) { - return Fail(t, fmt.Sprintf("Should be zero, but was %v", i), msgAndArgs...) - } - return true -} - -// NotZero asserts that i is not the zero value for its type and returns the truth. -func NotZero(t TestingT, i interface{}, msgAndArgs ...interface{}) bool { - if i == nil || reflect.DeepEqual(i, reflect.Zero(reflect.TypeOf(i)).Interface()) { - return Fail(t, fmt.Sprintf("Should not be zero, but was %v", i), msgAndArgs...) - } - return true -} - -// JSONEq asserts that two JSON strings are equivalent. -// -// assert.JSONEq(t, `{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`) -// -// Returns whether the assertion was successful (true) or not (false). -func JSONEq(t TestingT, expected string, actual string, msgAndArgs ...interface{}) bool { - var expectedJSONAsInterface, actualJSONAsInterface interface{} - - if err := json.Unmarshal([]byte(expected), &expectedJSONAsInterface); err != nil { - return Fail(t, fmt.Sprintf("Expected value ('%s') is not valid json.\nJSON parsing error: '%s'", expected, err.Error()), msgAndArgs...) - } - - if err := json.Unmarshal([]byte(actual), &actualJSONAsInterface); err != nil { - return Fail(t, fmt.Sprintf("Input ('%s') needs to be valid json.\nJSON parsing error: '%s'", actual, err.Error()), msgAndArgs...) - } - - return Equal(t, expectedJSONAsInterface, actualJSONAsInterface, msgAndArgs...) -} - -func typeAndKind(v interface{}) (reflect.Type, reflect.Kind) { - t := reflect.TypeOf(v) - k := t.Kind() - - if k == reflect.Ptr { - t = t.Elem() - k = t.Kind() - } - return t, k -} - -// diff returns a diff of both values as long as both are of the same type and -// are a struct, map, slice or array. Otherwise it returns an empty string. -func diff(expected interface{}, actual interface{}) string { - if expected == nil || actual == nil { - return "" - } - - et, ek := typeAndKind(expected) - at, _ := typeAndKind(actual) - - if et != at { - return "" - } - - if ek != reflect.Struct && ek != reflect.Map && ek != reflect.Slice && ek != reflect.Array { - return "" - } - - e := spewConfig.Sdump(expected) - a := spewConfig.Sdump(actual) - - diff, _ := difflib.GetUnifiedDiffString(difflib.UnifiedDiff{ - A: difflib.SplitLines(e), - B: difflib.SplitLines(a), - FromFile: "Expected", - FromDate: "", - ToFile: "Actual", - ToDate: "", - Context: 1, - }) - - return "\n\nDiff:\n" + diff -} - -var spewConfig = spew.ConfigState{ - Indent: " ", - DisablePointerAddresses: true, - DisableCapacities: true, - SortKeys: true, -} diff --git a/vendor/github.com/stretchr/testify/assert/doc.go b/vendor/github.com/stretchr/testify/assert/doc.go deleted file mode 100644 index c9dccc4d6c..0000000000 --- a/vendor/github.com/stretchr/testify/assert/doc.go +++ /dev/null @@ -1,45 +0,0 @@ -// Package assert provides a set of comprehensive testing tools for use with the normal Go testing system. -// -// Example Usage -// -// The following is a complete example using assert in a standard test function: -// import ( -// "testing" -// "github.com/stretchr/testify/assert" -// ) -// -// func TestSomething(t *testing.T) { -// -// var a string = "Hello" -// var b string = "Hello" -// -// assert.Equal(t, a, b, "The two words should be the same.") -// -// } -// -// if you assert many times, use the format below: -// -// import ( -// "testing" -// "github.com/stretchr/testify/assert" -// ) -// -// func TestSomething(t *testing.T) { -// assert := assert.New(t) -// -// var a string = "Hello" -// var b string = "Hello" -// -// assert.Equal(a, b, "The two words should be the same.") -// } -// -// Assertions -// -// Assertions allow you to easily write test code, and are global funcs in the `assert` package. -// All assertion functions take, as the first argument, the `*testing.T` object provided by the -// testing framework. This allows the assertion funcs to write the failings and other details to -// the correct place. -// -// Every assertion function also takes an optional string message as the final argument, -// allowing custom error messages to be appended to the message the assertion method outputs. -package assert diff --git a/vendor/github.com/stretchr/testify/assert/errors.go b/vendor/github.com/stretchr/testify/assert/errors.go deleted file mode 100644 index ac9dc9d1d6..0000000000 --- a/vendor/github.com/stretchr/testify/assert/errors.go +++ /dev/null @@ -1,10 +0,0 @@ -package assert - -import ( - "errors" -) - -// AnError is an error instance useful for testing. If the code does not care -// about error specifics, and only needs to return the error for example, this -// error should be used to make the test code more readable. -var AnError = errors.New("assert.AnError general error for testing") diff --git a/vendor/github.com/stretchr/testify/assert/forward_assertions.go b/vendor/github.com/stretchr/testify/assert/forward_assertions.go deleted file mode 100644 index b867e95ea5..0000000000 --- a/vendor/github.com/stretchr/testify/assert/forward_assertions.go +++ /dev/null @@ -1,16 +0,0 @@ -package assert - -// Assertions provides assertion methods around the -// TestingT interface. -type Assertions struct { - t TestingT -} - -// New makes a new Assertions object for the specified TestingT. -func New(t TestingT) *Assertions { - return &Assertions{ - t: t, - } -} - -//go:generate go run ../_codegen/main.go -output-package=assert -template=assertion_forward.go.tmpl diff --git a/vendor/github.com/stretchr/testify/assert/http_assertions.go b/vendor/github.com/stretchr/testify/assert/http_assertions.go deleted file mode 100644 index fa7ab89b18..0000000000 --- a/vendor/github.com/stretchr/testify/assert/http_assertions.go +++ /dev/null @@ -1,106 +0,0 @@ -package assert - -import ( - "fmt" - "net/http" - "net/http/httptest" - "net/url" - "strings" -) - -// httpCode is a helper that returns HTTP code of the response. It returns -1 -// if building a new request fails. -func httpCode(handler http.HandlerFunc, method, url string, values url.Values) int { - w := httptest.NewRecorder() - req, err := http.NewRequest(method, url+"?"+values.Encode(), nil) - if err != nil { - return -1 - } - handler(w, req) - return w.Code -} - -// HTTPSuccess asserts that a specified handler returns a success status code. -// -// assert.HTTPSuccess(t, myHandler, "POST", "http://www.google.com", nil) -// -// Returns whether the assertion was successful (true) or not (false). -func HTTPSuccess(t TestingT, handler http.HandlerFunc, method, url string, values url.Values) bool { - code := httpCode(handler, method, url, values) - if code == -1 { - return false - } - return code >= http.StatusOK && code <= http.StatusPartialContent -} - -// HTTPRedirect asserts that a specified handler returns a redirect status code. -// -// assert.HTTPRedirect(t, myHandler, "GET", "/a/b/c", url.Values{"a": []string{"b", "c"}} -// -// Returns whether the assertion was successful (true) or not (false). -func HTTPRedirect(t TestingT, handler http.HandlerFunc, method, url string, values url.Values) bool { - code := httpCode(handler, method, url, values) - if code == -1 { - return false - } - return code >= http.StatusMultipleChoices && code <= http.StatusTemporaryRedirect -} - -// HTTPError asserts that a specified handler returns an error status code. -// -// assert.HTTPError(t, myHandler, "POST", "/a/b/c", url.Values{"a": []string{"b", "c"}} -// -// Returns whether the assertion was successful (true) or not (false). -func HTTPError(t TestingT, handler http.HandlerFunc, method, url string, values url.Values) bool { - code := httpCode(handler, method, url, values) - if code == -1 { - return false - } - return code >= http.StatusBadRequest -} - -// HTTPBody is a helper that returns HTTP body of the response. It returns -// empty string if building a new request fails. -func HTTPBody(handler http.HandlerFunc, method, url string, values url.Values) string { - w := httptest.NewRecorder() - req, err := http.NewRequest(method, url+"?"+values.Encode(), nil) - if err != nil { - return "" - } - handler(w, req) - return w.Body.String() -} - -// HTTPBodyContains asserts that a specified handler returns a -// body that contains a string. -// -// assert.HTTPBodyContains(t, myHandler, "www.google.com", nil, "I'm Feeling Lucky") -// -// Returns whether the assertion was successful (true) or not (false). -func HTTPBodyContains(t TestingT, handler http.HandlerFunc, method, url string, values url.Values, str interface{}) bool { - body := HTTPBody(handler, method, url, values) - - contains := strings.Contains(body, fmt.Sprint(str)) - if !contains { - Fail(t, fmt.Sprintf("Expected response body for \"%s\" to contain \"%s\" but found \"%s\"", url+"?"+values.Encode(), str, body)) - } - - return contains -} - -// HTTPBodyNotContains asserts that a specified handler returns a -// body that does not contain a string. -// -// assert.HTTPBodyNotContains(t, myHandler, "www.google.com", nil, "I'm Feeling Lucky") -// -// Returns whether the assertion was successful (true) or not (false). -func HTTPBodyNotContains(t TestingT, handler http.HandlerFunc, method, url string, values url.Values, str interface{}) bool { - body := HTTPBody(handler, method, url, values) - - contains := strings.Contains(body, fmt.Sprint(str)) - if contains { - Fail(t, fmt.Sprintf("Expected response body for \"%s\" to NOT contain \"%s\" but found \"%s\"", url+"?"+values.Encode(), str, body)) - } - - return !contains -} diff --git a/vendor/github.com/stretchr/testify/require/doc.go b/vendor/github.com/stretchr/testify/require/doc.go deleted file mode 100644 index 169de39221..0000000000 --- a/vendor/github.com/stretchr/testify/require/doc.go +++ /dev/null @@ -1,28 +0,0 @@ -// Package require implements the same assertions as the `assert` package but -// stops test execution when a test fails. -// -// Example Usage -// -// The following is a complete example using require in a standard test function: -// import ( -// "testing" -// "github.com/stretchr/testify/require" -// ) -// -// func TestSomething(t *testing.T) { -// -// var a string = "Hello" -// var b string = "Hello" -// -// require.Equal(t, a, b, "The two words should be the same.") -// -// } -// -// Assertions -// -// The `require` package have same global functions as in the `assert` package, -// but instead of returning a boolean result they call `t.FailNow()`. -// -// Every assertion function also takes an optional string message as the final argument, -// allowing custom error messages to be appended to the message the assertion method outputs. -package require diff --git a/vendor/github.com/stretchr/testify/require/forward_requirements.go b/vendor/github.com/stretchr/testify/require/forward_requirements.go deleted file mode 100644 index d3c2ab9bc7..0000000000 --- a/vendor/github.com/stretchr/testify/require/forward_requirements.go +++ /dev/null @@ -1,16 +0,0 @@ -package require - -// Assertions provides assertion methods around the -// TestingT interface. -type Assertions struct { - t TestingT -} - -// New makes a new Assertions object for the specified TestingT. -func New(t TestingT) *Assertions { - return &Assertions{ - t: t, - } -} - -//go:generate go run ../_codegen/main.go -output-package=require -template=require_forward.go.tmpl diff --git a/vendor/github.com/stretchr/testify/require/require.go b/vendor/github.com/stretchr/testify/require/require.go deleted file mode 100644 index fc567f140a..0000000000 --- a/vendor/github.com/stretchr/testify/require/require.go +++ /dev/null @@ -1,429 +0,0 @@ -/* -* CODE GENERATED AUTOMATICALLY WITH github.com/stretchr/testify/_codegen -* THIS FILE MUST NOT BE EDITED BY HAND - */ - -package require - -import ( - assert "github.com/stretchr/testify/assert" - http "net/http" - url "net/url" - time "time" -) - -// Condition uses a Comparison to assert a complex condition. -func Condition(t TestingT, comp assert.Comparison, msgAndArgs ...interface{}) { - if !assert.Condition(t, comp, msgAndArgs...) { - t.FailNow() - } -} - -// Contains asserts that the specified string, list(array, slice...) or map contains the -// specified substring or element. -// -// assert.Contains(t, "Hello World", "World", "But 'Hello World' does contain 'World'") -// assert.Contains(t, ["Hello", "World"], "World", "But ["Hello", "World"] does contain 'World'") -// assert.Contains(t, {"Hello": "World"}, "Hello", "But {'Hello': 'World'} does contain 'Hello'") -// -// Returns whether the assertion was successful (true) or not (false). -func Contains(t TestingT, s interface{}, contains interface{}, msgAndArgs ...interface{}) { - if !assert.Contains(t, s, contains, msgAndArgs...) { - t.FailNow() - } -} - -// Empty asserts that the specified object is empty. I.e. nil, "", false, 0 or either -// a slice or a channel with len == 0. -// -// assert.Empty(t, obj) -// -// Returns whether the assertion was successful (true) or not (false). -func Empty(t TestingT, object interface{}, msgAndArgs ...interface{}) { - if !assert.Empty(t, object, msgAndArgs...) { - t.FailNow() - } -} - -// Equal asserts that two objects are equal. -// -// assert.Equal(t, 123, 123, "123 and 123 should be equal") -// -// Returns whether the assertion was successful (true) or not (false). -// -// Pointer variable equality is determined based on the equality of the -// referenced values (as opposed to the memory addresses). -func Equal(t TestingT, expected interface{}, actual interface{}, msgAndArgs ...interface{}) { - if !assert.Equal(t, expected, actual, msgAndArgs...) { - t.FailNow() - } -} - -// EqualError asserts that a function returned an error (i.e. not `nil`) -// and that it is equal to the provided error. -// -// actualObj, err := SomeFunction() -// assert.EqualError(t, err, expectedErrorString, "An error was expected") -// -// Returns whether the assertion was successful (true) or not (false). -func EqualError(t TestingT, theError error, errString string, msgAndArgs ...interface{}) { - if !assert.EqualError(t, theError, errString, msgAndArgs...) { - t.FailNow() - } -} - -// EqualValues asserts that two objects are equal or convertable to the same types -// and equal. -// -// assert.EqualValues(t, uint32(123), int32(123), "123 and 123 should be equal") -// -// Returns whether the assertion was successful (true) or not (false). -func EqualValues(t TestingT, expected interface{}, actual interface{}, msgAndArgs ...interface{}) { - if !assert.EqualValues(t, expected, actual, msgAndArgs...) { - t.FailNow() - } -} - -// Error asserts that a function returned an error (i.e. not `nil`). -// -// actualObj, err := SomeFunction() -// if assert.Error(t, err, "An error was expected") { -// assert.Equal(t, err, expectedError) -// } -// -// Returns whether the assertion was successful (true) or not (false). -func Error(t TestingT, err error, msgAndArgs ...interface{}) { - if !assert.Error(t, err, msgAndArgs...) { - t.FailNow() - } -} - -// Exactly asserts that two objects are equal is value and type. -// -// assert.Exactly(t, int32(123), int64(123), "123 and 123 should NOT be equal") -// -// Returns whether the assertion was successful (true) or not (false). -func Exactly(t TestingT, expected interface{}, actual interface{}, msgAndArgs ...interface{}) { - if !assert.Exactly(t, expected, actual, msgAndArgs...) { - t.FailNow() - } -} - -// Fail reports a failure through -func Fail(t TestingT, failureMessage string, msgAndArgs ...interface{}) { - if !assert.Fail(t, failureMessage, msgAndArgs...) { - t.FailNow() - } -} - -// FailNow fails test -func FailNow(t TestingT, failureMessage string, msgAndArgs ...interface{}) { - if !assert.FailNow(t, failureMessage, msgAndArgs...) { - t.FailNow() - } -} - -// False asserts that the specified value is false. -// -// assert.False(t, myBool, "myBool should be false") -// -// Returns whether the assertion was successful (true) or not (false). -func False(t TestingT, value bool, msgAndArgs ...interface{}) { - if !assert.False(t, value, msgAndArgs...) { - t.FailNow() - } -} - -// HTTPBodyContains asserts that a specified handler returns a -// body that contains a string. -// -// assert.HTTPBodyContains(t, myHandler, "www.google.com", nil, "I'm Feeling Lucky") -// -// Returns whether the assertion was successful (true) or not (false). -func HTTPBodyContains(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, str interface{}) { - if !assert.HTTPBodyContains(t, handler, method, url, values, str) { - t.FailNow() - } -} - -// HTTPBodyNotContains asserts that a specified handler returns a -// body that does not contain a string. -// -// assert.HTTPBodyNotContains(t, myHandler, "www.google.com", nil, "I'm Feeling Lucky") -// -// Returns whether the assertion was successful (true) or not (false). -func HTTPBodyNotContains(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values, str interface{}) { - if !assert.HTTPBodyNotContains(t, handler, method, url, values, str) { - t.FailNow() - } -} - -// HTTPError asserts that a specified handler returns an error status code. -// -// assert.HTTPError(t, myHandler, "POST", "/a/b/c", url.Values{"a": []string{"b", "c"}} -// -// Returns whether the assertion was successful (true) or not (false). -func HTTPError(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values) { - if !assert.HTTPError(t, handler, method, url, values) { - t.FailNow() - } -} - -// HTTPRedirect asserts that a specified handler returns a redirect status code. -// -// assert.HTTPRedirect(t, myHandler, "GET", "/a/b/c", url.Values{"a": []string{"b", "c"}} -// -// Returns whether the assertion was successful (true) or not (false). -func HTTPRedirect(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values) { - if !assert.HTTPRedirect(t, handler, method, url, values) { - t.FailNow() - } -} - -// HTTPSuccess asserts that a specified handler returns a success status code. -// -// assert.HTTPSuccess(t, myHandler, "POST", "http://www.google.com", nil) -// -// Returns whether the assertion was successful (true) or not (false). -func HTTPSuccess(t TestingT, handler http.HandlerFunc, method string, url string, values url.Values) { - if !assert.HTTPSuccess(t, handler, method, url, values) { - t.FailNow() - } -} - -// Implements asserts that an object is implemented by the specified interface. -// -// assert.Implements(t, (*MyInterface)(nil), new(MyObject), "MyObject") -func Implements(t TestingT, interfaceObject interface{}, object interface{}, msgAndArgs ...interface{}) { - if !assert.Implements(t, interfaceObject, object, msgAndArgs...) { - t.FailNow() - } -} - -// InDelta asserts that the two numerals are within delta of each other. -// -// assert.InDelta(t, math.Pi, (22 / 7.0), 0.01) -// -// Returns whether the assertion was successful (true) or not (false). -func InDelta(t TestingT, expected interface{}, actual interface{}, delta float64, msgAndArgs ...interface{}) { - if !assert.InDelta(t, expected, actual, delta, msgAndArgs...) { - t.FailNow() - } -} - -// InDeltaSlice is the same as InDelta, except it compares two slices. -func InDeltaSlice(t TestingT, expected interface{}, actual interface{}, delta float64, msgAndArgs ...interface{}) { - if !assert.InDeltaSlice(t, expected, actual, delta, msgAndArgs...) { - t.FailNow() - } -} - -// InEpsilon asserts that expected and actual have a relative error less than epsilon -// -// Returns whether the assertion was successful (true) or not (false). -func InEpsilon(t TestingT, expected interface{}, actual interface{}, epsilon float64, msgAndArgs ...interface{}) { - if !assert.InEpsilon(t, expected, actual, epsilon, msgAndArgs...) { - t.FailNow() - } -} - -// InEpsilonSlice is the same as InEpsilon, except it compares each value from two slices. -func InEpsilonSlice(t TestingT, expected interface{}, actual interface{}, epsilon float64, msgAndArgs ...interface{}) { - if !assert.InEpsilonSlice(t, expected, actual, epsilon, msgAndArgs...) { - t.FailNow() - } -} - -// IsType asserts that the specified objects are of the same type. -func IsType(t TestingT, expectedType interface{}, object interface{}, msgAndArgs ...interface{}) { - if !assert.IsType(t, expectedType, object, msgAndArgs...) { - t.FailNow() - } -} - -// JSONEq asserts that two JSON strings are equivalent. -// -// assert.JSONEq(t, `{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`) -// -// Returns whether the assertion was successful (true) or not (false). -func JSONEq(t TestingT, expected string, actual string, msgAndArgs ...interface{}) { - if !assert.JSONEq(t, expected, actual, msgAndArgs...) { - t.FailNow() - } -} - -// Len asserts that the specified object has specific length. -// Len also fails if the object has a type that len() not accept. -// -// assert.Len(t, mySlice, 3, "The size of slice is not 3") -// -// Returns whether the assertion was successful (true) or not (false). -func Len(t TestingT, object interface{}, length int, msgAndArgs ...interface{}) { - if !assert.Len(t, object, length, msgAndArgs...) { - t.FailNow() - } -} - -// Nil asserts that the specified object is nil. -// -// assert.Nil(t, err, "err should be nothing") -// -// Returns whether the assertion was successful (true) or not (false). -func Nil(t TestingT, object interface{}, msgAndArgs ...interface{}) { - if !assert.Nil(t, object, msgAndArgs...) { - t.FailNow() - } -} - -// NoError asserts that a function returned no error (i.e. `nil`). -// -// actualObj, err := SomeFunction() -// if assert.NoError(t, err) { -// assert.Equal(t, actualObj, expectedObj) -// } -// -// Returns whether the assertion was successful (true) or not (false). -func NoError(t TestingT, err error, msgAndArgs ...interface{}) { - if !assert.NoError(t, err, msgAndArgs...) { - t.FailNow() - } -} - -// NotContains asserts that the specified string, list(array, slice...) or map does NOT contain the -// specified substring or element. -// -// assert.NotContains(t, "Hello World", "Earth", "But 'Hello World' does NOT contain 'Earth'") -// assert.NotContains(t, ["Hello", "World"], "Earth", "But ['Hello', 'World'] does NOT contain 'Earth'") -// assert.NotContains(t, {"Hello": "World"}, "Earth", "But {'Hello': 'World'} does NOT contain 'Earth'") -// -// Returns whether the assertion was successful (true) or not (false). -func NotContains(t TestingT, s interface{}, contains interface{}, msgAndArgs ...interface{}) { - if !assert.NotContains(t, s, contains, msgAndArgs...) { - t.FailNow() - } -} - -// NotEmpty asserts that the specified object is NOT empty. I.e. not nil, "", false, 0 or either -// a slice or a channel with len == 0. -// -// if assert.NotEmpty(t, obj) { -// assert.Equal(t, "two", obj[1]) -// } -// -// Returns whether the assertion was successful (true) or not (false). -func NotEmpty(t TestingT, object interface{}, msgAndArgs ...interface{}) { - if !assert.NotEmpty(t, object, msgAndArgs...) { - t.FailNow() - } -} - -// NotEqual asserts that the specified values are NOT equal. -// -// assert.NotEqual(t, obj1, obj2, "two objects shouldn't be equal") -// -// Returns whether the assertion was successful (true) or not (false). -// -// Pointer variable equality is determined based on the equality of the -// referenced values (as opposed to the memory addresses). -func NotEqual(t TestingT, expected interface{}, actual interface{}, msgAndArgs ...interface{}) { - if !assert.NotEqual(t, expected, actual, msgAndArgs...) { - t.FailNow() - } -} - -// NotNil asserts that the specified object is not nil. -// -// assert.NotNil(t, err, "err should be something") -// -// Returns whether the assertion was successful (true) or not (false). -func NotNil(t TestingT, object interface{}, msgAndArgs ...interface{}) { - if !assert.NotNil(t, object, msgAndArgs...) { - t.FailNow() - } -} - -// NotPanics asserts that the code inside the specified PanicTestFunc does NOT panic. -// -// assert.NotPanics(t, func(){ -// RemainCalm() -// }, "Calling RemainCalm() should NOT panic") -// -// Returns whether the assertion was successful (true) or not (false). -func NotPanics(t TestingT, f assert.PanicTestFunc, msgAndArgs ...interface{}) { - if !assert.NotPanics(t, f, msgAndArgs...) { - t.FailNow() - } -} - -// NotRegexp asserts that a specified regexp does not match a string. -// -// assert.NotRegexp(t, regexp.MustCompile("starts"), "it's starting") -// assert.NotRegexp(t, "^start", "it's not starting") -// -// Returns whether the assertion was successful (true) or not (false). -func NotRegexp(t TestingT, rx interface{}, str interface{}, msgAndArgs ...interface{}) { - if !assert.NotRegexp(t, rx, str, msgAndArgs...) { - t.FailNow() - } -} - -// NotZero asserts that i is not the zero value for its type and returns the truth. -func NotZero(t TestingT, i interface{}, msgAndArgs ...interface{}) { - if !assert.NotZero(t, i, msgAndArgs...) { - t.FailNow() - } -} - -// Panics asserts that the code inside the specified PanicTestFunc panics. -// -// assert.Panics(t, func(){ -// GoCrazy() -// }, "Calling GoCrazy() should panic") -// -// Returns whether the assertion was successful (true) or not (false). -func Panics(t TestingT, f assert.PanicTestFunc, msgAndArgs ...interface{}) { - if !assert.Panics(t, f, msgAndArgs...) { - t.FailNow() - } -} - -// Regexp asserts that a specified regexp matches a string. -// -// assert.Regexp(t, regexp.MustCompile("start"), "it's starting") -// assert.Regexp(t, "start...$", "it's not starting") -// -// Returns whether the assertion was successful (true) or not (false). -func Regexp(t TestingT, rx interface{}, str interface{}, msgAndArgs ...interface{}) { - if !assert.Regexp(t, rx, str, msgAndArgs...) { - t.FailNow() - } -} - -// True asserts that the specified value is true. -// -// assert.True(t, myBool, "myBool should be true") -// -// Returns whether the assertion was successful (true) or not (false). -func True(t TestingT, value bool, msgAndArgs ...interface{}) { - if !assert.True(t, value, msgAndArgs...) { - t.FailNow() - } -} - -// WithinDuration asserts that the two times are within duration delta of each other. -// -// assert.WithinDuration(t, time.Now(), time.Now(), 10*time.Second, "The difference should not be more than 10s") -// -// Returns whether the assertion was successful (true) or not (false). -func WithinDuration(t TestingT, expected time.Time, actual time.Time, delta time.Duration, msgAndArgs ...interface{}) { - if !assert.WithinDuration(t, expected, actual, delta, msgAndArgs...) { - t.FailNow() - } -} - -// Zero asserts that i is the zero value for its type and returns the truth. -func Zero(t TestingT, i interface{}, msgAndArgs ...interface{}) { - if !assert.Zero(t, i, msgAndArgs...) { - t.FailNow() - } -} diff --git a/vendor/github.com/stretchr/testify/require/require_forward.go b/vendor/github.com/stretchr/testify/require/require_forward.go deleted file mode 100644 index caa18793df..0000000000 --- a/vendor/github.com/stretchr/testify/require/require_forward.go +++ /dev/null @@ -1,353 +0,0 @@ -/* -* CODE GENERATED AUTOMATICALLY WITH github.com/stretchr/testify/_codegen -* THIS FILE MUST NOT BE EDITED BY HAND - */ - -package require - -import ( - assert "github.com/stretchr/testify/assert" - http "net/http" - url "net/url" - time "time" -) - -// Condition uses a Comparison to assert a complex condition. -func (a *Assertions) Condition(comp assert.Comparison, msgAndArgs ...interface{}) { - Condition(a.t, comp, msgAndArgs...) -} - -// Contains asserts that the specified string, list(array, slice...) or map contains the -// specified substring or element. -// -// a.Contains("Hello World", "World", "But 'Hello World' does contain 'World'") -// a.Contains(["Hello", "World"], "World", "But ["Hello", "World"] does contain 'World'") -// a.Contains({"Hello": "World"}, "Hello", "But {'Hello': 'World'} does contain 'Hello'") -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) Contains(s interface{}, contains interface{}, msgAndArgs ...interface{}) { - Contains(a.t, s, contains, msgAndArgs...) -} - -// Empty asserts that the specified object is empty. I.e. nil, "", false, 0 or either -// a slice or a channel with len == 0. -// -// a.Empty(obj) -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) Empty(object interface{}, msgAndArgs ...interface{}) { - Empty(a.t, object, msgAndArgs...) -} - -// Equal asserts that two objects are equal. -// -// a.Equal(123, 123, "123 and 123 should be equal") -// -// Returns whether the assertion was successful (true) or not (false). -// -// Pointer variable equality is determined based on the equality of the -// referenced values (as opposed to the memory addresses). -func (a *Assertions) Equal(expected interface{}, actual interface{}, msgAndArgs ...interface{}) { - Equal(a.t, expected, actual, msgAndArgs...) -} - -// EqualError asserts that a function returned an error (i.e. not `nil`) -// and that it is equal to the provided error. -// -// actualObj, err := SomeFunction() -// a.EqualError(err, expectedErrorString, "An error was expected") -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) EqualError(theError error, errString string, msgAndArgs ...interface{}) { - EqualError(a.t, theError, errString, msgAndArgs...) -} - -// EqualValues asserts that two objects are equal or convertable to the same types -// and equal. -// -// a.EqualValues(uint32(123), int32(123), "123 and 123 should be equal") -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) EqualValues(expected interface{}, actual interface{}, msgAndArgs ...interface{}) { - EqualValues(a.t, expected, actual, msgAndArgs...) -} - -// Error asserts that a function returned an error (i.e. not `nil`). -// -// actualObj, err := SomeFunction() -// if a.Error(err, "An error was expected") { -// assert.Equal(t, err, expectedError) -// } -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) Error(err error, msgAndArgs ...interface{}) { - Error(a.t, err, msgAndArgs...) -} - -// Exactly asserts that two objects are equal is value and type. -// -// a.Exactly(int32(123), int64(123), "123 and 123 should NOT be equal") -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) Exactly(expected interface{}, actual interface{}, msgAndArgs ...interface{}) { - Exactly(a.t, expected, actual, msgAndArgs...) -} - -// Fail reports a failure through -func (a *Assertions) Fail(failureMessage string, msgAndArgs ...interface{}) { - Fail(a.t, failureMessage, msgAndArgs...) -} - -// FailNow fails test -func (a *Assertions) FailNow(failureMessage string, msgAndArgs ...interface{}) { - FailNow(a.t, failureMessage, msgAndArgs...) -} - -// False asserts that the specified value is false. -// -// a.False(myBool, "myBool should be false") -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) False(value bool, msgAndArgs ...interface{}) { - False(a.t, value, msgAndArgs...) -} - -// HTTPBodyContains asserts that a specified handler returns a -// body that contains a string. -// -// a.HTTPBodyContains(myHandler, "www.google.com", nil, "I'm Feeling Lucky") -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) HTTPBodyContains(handler http.HandlerFunc, method string, url string, values url.Values, str interface{}) { - HTTPBodyContains(a.t, handler, method, url, values, str) -} - -// HTTPBodyNotContains asserts that a specified handler returns a -// body that does not contain a string. -// -// a.HTTPBodyNotContains(myHandler, "www.google.com", nil, "I'm Feeling Lucky") -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) HTTPBodyNotContains(handler http.HandlerFunc, method string, url string, values url.Values, str interface{}) { - HTTPBodyNotContains(a.t, handler, method, url, values, str) -} - -// HTTPError asserts that a specified handler returns an error status code. -// -// a.HTTPError(myHandler, "POST", "/a/b/c", url.Values{"a": []string{"b", "c"}} -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) HTTPError(handler http.HandlerFunc, method string, url string, values url.Values) { - HTTPError(a.t, handler, method, url, values) -} - -// HTTPRedirect asserts that a specified handler returns a redirect status code. -// -// a.HTTPRedirect(myHandler, "GET", "/a/b/c", url.Values{"a": []string{"b", "c"}} -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) HTTPRedirect(handler http.HandlerFunc, method string, url string, values url.Values) { - HTTPRedirect(a.t, handler, method, url, values) -} - -// HTTPSuccess asserts that a specified handler returns a success status code. -// -// a.HTTPSuccess(myHandler, "POST", "http://www.google.com", nil) -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) HTTPSuccess(handler http.HandlerFunc, method string, url string, values url.Values) { - HTTPSuccess(a.t, handler, method, url, values) -} - -// Implements asserts that an object is implemented by the specified interface. -// -// a.Implements((*MyInterface)(nil), new(MyObject), "MyObject") -func (a *Assertions) Implements(interfaceObject interface{}, object interface{}, msgAndArgs ...interface{}) { - Implements(a.t, interfaceObject, object, msgAndArgs...) -} - -// InDelta asserts that the two numerals are within delta of each other. -// -// a.InDelta(math.Pi, (22 / 7.0), 0.01) -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) InDelta(expected interface{}, actual interface{}, delta float64, msgAndArgs ...interface{}) { - InDelta(a.t, expected, actual, delta, msgAndArgs...) -} - -// InDeltaSlice is the same as InDelta, except it compares two slices. -func (a *Assertions) InDeltaSlice(expected interface{}, actual interface{}, delta float64, msgAndArgs ...interface{}) { - InDeltaSlice(a.t, expected, actual, delta, msgAndArgs...) -} - -// InEpsilon asserts that expected and actual have a relative error less than epsilon -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) InEpsilon(expected interface{}, actual interface{}, epsilon float64, msgAndArgs ...interface{}) { - InEpsilon(a.t, expected, actual, epsilon, msgAndArgs...) -} - -// InEpsilonSlice is the same as InEpsilon, except it compares each value from two slices. -func (a *Assertions) InEpsilonSlice(expected interface{}, actual interface{}, epsilon float64, msgAndArgs ...interface{}) { - InEpsilonSlice(a.t, expected, actual, epsilon, msgAndArgs...) -} - -// IsType asserts that the specified objects are of the same type. -func (a *Assertions) IsType(expectedType interface{}, object interface{}, msgAndArgs ...interface{}) { - IsType(a.t, expectedType, object, msgAndArgs...) -} - -// JSONEq asserts that two JSON strings are equivalent. -// -// a.JSONEq(`{"hello": "world", "foo": "bar"}`, `{"foo": "bar", "hello": "world"}`) -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) JSONEq(expected string, actual string, msgAndArgs ...interface{}) { - JSONEq(a.t, expected, actual, msgAndArgs...) -} - -// Len asserts that the specified object has specific length. -// Len also fails if the object has a type that len() not accept. -// -// a.Len(mySlice, 3, "The size of slice is not 3") -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) Len(object interface{}, length int, msgAndArgs ...interface{}) { - Len(a.t, object, length, msgAndArgs...) -} - -// Nil asserts that the specified object is nil. -// -// a.Nil(err, "err should be nothing") -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) Nil(object interface{}, msgAndArgs ...interface{}) { - Nil(a.t, object, msgAndArgs...) -} - -// NoError asserts that a function returned no error (i.e. `nil`). -// -// actualObj, err := SomeFunction() -// if a.NoError(err) { -// assert.Equal(t, actualObj, expectedObj) -// } -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) NoError(err error, msgAndArgs ...interface{}) { - NoError(a.t, err, msgAndArgs...) -} - -// NotContains asserts that the specified string, list(array, slice...) or map does NOT contain the -// specified substring or element. -// -// a.NotContains("Hello World", "Earth", "But 'Hello World' does NOT contain 'Earth'") -// a.NotContains(["Hello", "World"], "Earth", "But ['Hello', 'World'] does NOT contain 'Earth'") -// a.NotContains({"Hello": "World"}, "Earth", "But {'Hello': 'World'} does NOT contain 'Earth'") -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) NotContains(s interface{}, contains interface{}, msgAndArgs ...interface{}) { - NotContains(a.t, s, contains, msgAndArgs...) -} - -// NotEmpty asserts that the specified object is NOT empty. I.e. not nil, "", false, 0 or either -// a slice or a channel with len == 0. -// -// if a.NotEmpty(obj) { -// assert.Equal(t, "two", obj[1]) -// } -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) NotEmpty(object interface{}, msgAndArgs ...interface{}) { - NotEmpty(a.t, object, msgAndArgs...) -} - -// NotEqual asserts that the specified values are NOT equal. -// -// a.NotEqual(obj1, obj2, "two objects shouldn't be equal") -// -// Returns whether the assertion was successful (true) or not (false). -// -// Pointer variable equality is determined based on the equality of the -// referenced values (as opposed to the memory addresses). -func (a *Assertions) NotEqual(expected interface{}, actual interface{}, msgAndArgs ...interface{}) { - NotEqual(a.t, expected, actual, msgAndArgs...) -} - -// NotNil asserts that the specified object is not nil. -// -// a.NotNil(err, "err should be something") -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) NotNil(object interface{}, msgAndArgs ...interface{}) { - NotNil(a.t, object, msgAndArgs...) -} - -// NotPanics asserts that the code inside the specified PanicTestFunc does NOT panic. -// -// a.NotPanics(func(){ -// RemainCalm() -// }, "Calling RemainCalm() should NOT panic") -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) NotPanics(f assert.PanicTestFunc, msgAndArgs ...interface{}) { - NotPanics(a.t, f, msgAndArgs...) -} - -// NotRegexp asserts that a specified regexp does not match a string. -// -// a.NotRegexp(regexp.MustCompile("starts"), "it's starting") -// a.NotRegexp("^start", "it's not starting") -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) NotRegexp(rx interface{}, str interface{}, msgAndArgs ...interface{}) { - NotRegexp(a.t, rx, str, msgAndArgs...) -} - -// NotZero asserts that i is not the zero value for its type and returns the truth. -func (a *Assertions) NotZero(i interface{}, msgAndArgs ...interface{}) { - NotZero(a.t, i, msgAndArgs...) -} - -// Panics asserts that the code inside the specified PanicTestFunc panics. -// -// a.Panics(func(){ -// GoCrazy() -// }, "Calling GoCrazy() should panic") -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) Panics(f assert.PanicTestFunc, msgAndArgs ...interface{}) { - Panics(a.t, f, msgAndArgs...) -} - -// Regexp asserts that a specified regexp matches a string. -// -// a.Regexp(regexp.MustCompile("start"), "it's starting") -// a.Regexp("start...$", "it's not starting") -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) Regexp(rx interface{}, str interface{}, msgAndArgs ...interface{}) { - Regexp(a.t, rx, str, msgAndArgs...) -} - -// True asserts that the specified value is true. -// -// a.True(myBool, "myBool should be true") -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) True(value bool, msgAndArgs ...interface{}) { - True(a.t, value, msgAndArgs...) -} - -// WithinDuration asserts that the two times are within duration delta of each other. -// -// a.WithinDuration(time.Now(), time.Now(), 10*time.Second, "The difference should not be more than 10s") -// -// Returns whether the assertion was successful (true) or not (false). -func (a *Assertions) WithinDuration(expected time.Time, actual time.Time, delta time.Duration, msgAndArgs ...interface{}) { - WithinDuration(a.t, expected, actual, delta, msgAndArgs...) -} - -// Zero asserts that i is the zero value for its type and returns the truth. -func (a *Assertions) Zero(i interface{}, msgAndArgs ...interface{}) { - Zero(a.t, i, msgAndArgs...) -} diff --git a/vendor/github.com/stretchr/testify/require/requirements.go b/vendor/github.com/stretchr/testify/require/requirements.go deleted file mode 100644 index 41147562d8..0000000000 --- a/vendor/github.com/stretchr/testify/require/requirements.go +++ /dev/null @@ -1,9 +0,0 @@ -package require - -// TestingT is an interface wrapper around *testing.T -type TestingT interface { - Errorf(format string, args ...interface{}) - FailNow() -} - -//go:generate go run ../_codegen/main.go -output-package=require -template=require.go.tmpl