Merge pull request #449 from dnephin/use-gotestyourself

Remove dependency on (most of) docker/docker/pkg/testutil
This commit is contained in:
Tibor Vass 2017-08-17 12:37:18 -07:00 committed by GitHub
commit e57842edb8
77 changed files with 1010 additions and 751 deletions

View File

@ -1,14 +1,13 @@
package checkpoint package checkpoint
import ( import (
"bytes"
"io/ioutil" "io/ioutil"
"testing" "testing"
"github.com/docker/cli/cli/internal/test" "github.com/docker/cli/cli/internal/test"
"github.com/docker/docker/api/types" "github.com/docker/docker/api/types"
"github.com/docker/docker/pkg/testutil" "github.com/docker/docker/pkg/testutil"
"github.com/docker/docker/pkg/testutil/golden" "github.com/gotestyourself/gotestyourself/golden"
"github.com/pkg/errors" "github.com/pkg/errors"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
) )
@ -37,9 +36,9 @@ func TestCheckpointListErrors(t *testing.T) {
} }
for _, tc := range testCases { for _, tc := range testCases {
cli := test.NewFakeCliWithOutput(&fakeClient{ cli := test.NewFakeCli(&fakeClient{
checkpointListFunc: tc.checkpointListFunc, checkpointListFunc: tc.checkpointListFunc,
}, &bytes.Buffer{}) })
cmd := newListCommand(cli) cmd := newListCommand(cli)
cmd.SetArgs(tc.args) cmd.SetArgs(tc.args)
cmd.SetOutput(ioutil.Discard) cmd.SetOutput(ioutil.Discard)
@ -49,8 +48,7 @@ func TestCheckpointListErrors(t *testing.T) {
func TestCheckpointListWithOptions(t *testing.T) { func TestCheckpointListWithOptions(t *testing.T) {
var containerID, checkpointDir string var containerID, checkpointDir string
buf := new(bytes.Buffer) cli := test.NewFakeCli(&fakeClient{
cli := test.NewFakeCliWithOutput(&fakeClient{
checkpointListFunc: func(container string, options types.CheckpointListOptions) ([]types.Checkpoint, error) { checkpointListFunc: func(container string, options types.CheckpointListOptions) ([]types.Checkpoint, error) {
containerID = container containerID = container
checkpointDir = options.CheckpointDir checkpointDir = options.CheckpointDir
@ -58,14 +56,12 @@ func TestCheckpointListWithOptions(t *testing.T) {
{Name: "checkpoint-foo"}, {Name: "checkpoint-foo"},
}, nil }, nil
}, },
}, buf) })
cmd := newListCommand(cli) cmd := newListCommand(cli)
cmd.SetArgs([]string{"container-foo"}) cmd.SetArgs([]string{"container-foo"})
cmd.Flags().Set("checkpoint-dir", "/dir/foo") cmd.Flags().Set("checkpoint-dir", "/dir/foo")
assert.NoError(t, cmd.Execute()) assert.NoError(t, cmd.Execute())
assert.Equal(t, "container-foo", containerID) assert.Equal(t, "container-foo", containerID)
assert.Equal(t, "/dir/foo", checkpointDir) assert.Equal(t, "/dir/foo", checkpointDir)
actual := buf.String() golden.Assert(t, cli.OutBuffer().String(), "checkpoint-list-with-options.golden")
expected := golden.Get(t, []byte(actual), "checkpoint-list-with-options.golden")
testutil.EqualNormalizedString(t, testutil.RemoveSpace, actual, string(expected))
} }

View File

@ -1,7 +1,6 @@
package checkpoint package checkpoint
import ( import (
"bytes"
"io/ioutil" "io/ioutil"
"testing" "testing"
@ -36,9 +35,9 @@ func TestCheckpointRemoveErrors(t *testing.T) {
} }
for _, tc := range testCases { for _, tc := range testCases {
cli := test.NewFakeCliWithOutput(&fakeClient{ cli := test.NewFakeCli(&fakeClient{
checkpointDeleteFunc: tc.checkpointDeleteFunc, checkpointDeleteFunc: tc.checkpointDeleteFunc,
}, &bytes.Buffer{}) })
cmd := newRemoveCommand(cli) cmd := newRemoveCommand(cli)
cmd.SetArgs(tc.args) cmd.SetArgs(tc.args)
cmd.SetOutput(ioutil.Discard) cmd.SetOutput(ioutil.Discard)
@ -48,14 +47,14 @@ func TestCheckpointRemoveErrors(t *testing.T) {
func TestCheckpointRemoveWithOptions(t *testing.T) { func TestCheckpointRemoveWithOptions(t *testing.T) {
var containerID, checkpointID, checkpointDir string var containerID, checkpointID, checkpointDir string
cli := test.NewFakeCliWithOutput(&fakeClient{ cli := test.NewFakeCli(&fakeClient{
checkpointDeleteFunc: func(container string, options types.CheckpointDeleteOptions) error { checkpointDeleteFunc: func(container string, options types.CheckpointDeleteOptions) error {
containerID = container containerID = container
checkpointID = options.CheckpointID checkpointID = options.CheckpointID
checkpointDir = options.CheckpointDir checkpointDir = options.CheckpointDir
return nil return nil
}, },
}, &bytes.Buffer{}) })
cmd := newRemoveCommand(cli) cmd := newRemoveCommand(cli)
cmd.SetArgs([]string{"container-foo", "checkpoint-bar"}) cmd.SetArgs([]string{"container-foo", "checkpoint-bar"})
cmd.Flags().Set("checkpoint-dir", "/dir/foo") cmd.Flags().Set("checkpoint-dir", "/dir/foo")

View File

@ -11,7 +11,7 @@ import (
"github.com/docker/docker/api/types" "github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/swarm" "github.com/docker/docker/api/types/swarm"
"github.com/docker/docker/pkg/testutil" "github.com/docker/docker/pkg/testutil"
"github.com/docker/docker/pkg/testutil/golden" "github.com/gotestyourself/gotestyourself/golden"
"github.com/pkg/errors" "github.com/pkg/errors"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
) )
@ -71,8 +71,7 @@ func TestConfigCreateWithName(t *testing.T) {
cmd := newConfigCreateCommand(cli) cmd := newConfigCreateCommand(cli)
cmd.SetArgs([]string{name, filepath.Join("testdata", configDataFile)}) cmd.SetArgs([]string{name, filepath.Join("testdata", configDataFile)})
assert.NoError(t, cmd.Execute()) assert.NoError(t, cmd.Execute())
expected := golden.Get(t, actual, configDataFile) golden.Assert(t, string(actual), configDataFile)
assert.Equal(t, string(expected), string(actual))
assert.Equal(t, "ID-"+name, strings.TrimSpace(cli.OutBuffer().String())) assert.Equal(t, "ID-"+name, strings.TrimSpace(cli.OutBuffer().String()))
} }

View File

@ -1,7 +1,6 @@
package config package config
import ( import (
"bytes"
"fmt" "fmt"
"io/ioutil" "io/ioutil"
"testing" "testing"
@ -13,7 +12,7 @@ import (
// Import builders to get the builder function as package function // Import builders to get the builder function as package function
. "github.com/docker/cli/cli/internal/test/builders" . "github.com/docker/cli/cli/internal/test/builders"
"github.com/docker/docker/pkg/testutil" "github.com/docker/docker/pkg/testutil"
"github.com/docker/docker/pkg/testutil/golden" "github.com/gotestyourself/gotestyourself/golden"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
) )
@ -53,11 +52,10 @@ func TestConfigInspectErrors(t *testing.T) {
}, },
} }
for _, tc := range testCases { for _, tc := range testCases {
buf := new(bytes.Buffer)
cmd := newConfigInspectCommand( cmd := newConfigInspectCommand(
test.NewFakeCliWithOutput(&fakeClient{ test.NewFakeCli(&fakeClient{
configInspectFunc: tc.configInspectFunc, configInspectFunc: tc.configInspectFunc,
}, buf), }),
) )
cmd.SetArgs(tc.args) cmd.SetArgs(tc.args)
for key, value := range tc.flags { for key, value := range tc.flags {
@ -95,17 +93,11 @@ func TestConfigInspectWithoutFormat(t *testing.T) {
}, },
} }
for _, tc := range testCases { for _, tc := range testCases {
buf := new(bytes.Buffer) cli := test.NewFakeCli(&fakeClient{configInspectFunc: tc.configInspectFunc})
cmd := newConfigInspectCommand( cmd := newConfigInspectCommand(cli)
test.NewFakeCliWithOutput(&fakeClient{
configInspectFunc: tc.configInspectFunc,
}, buf),
)
cmd.SetArgs(tc.args) cmd.SetArgs(tc.args)
assert.NoError(t, cmd.Execute()) assert.NoError(t, cmd.Execute())
actual := buf.String() golden.Assert(t, cli.OutBuffer().String(), fmt.Sprintf("config-inspect-without-format.%s.golden", tc.name))
expected := golden.Get(t, []byte(actual), fmt.Sprintf("config-inspect-without-format.%s.golden", tc.name))
testutil.EqualNormalizedString(t, testutil.RemoveSpace, actual, string(expected))
} }
} }
@ -135,18 +127,14 @@ func TestConfigInspectWithFormat(t *testing.T) {
}, },
} }
for _, tc := range testCases { for _, tc := range testCases {
buf := new(bytes.Buffer) cli := test.NewFakeCli(&fakeClient{
cmd := newConfigInspectCommand( configInspectFunc: tc.configInspectFunc,
test.NewFakeCliWithOutput(&fakeClient{ })
configInspectFunc: tc.configInspectFunc, cmd := newConfigInspectCommand(cli)
}, buf),
)
cmd.SetArgs(tc.args) cmd.SetArgs(tc.args)
cmd.Flags().Set("format", tc.format) cmd.Flags().Set("format", tc.format)
assert.NoError(t, cmd.Execute()) assert.NoError(t, cmd.Execute())
actual := buf.String() golden.Assert(t, cli.OutBuffer().String(), fmt.Sprintf("config-inspect-with-format.%s.golden", tc.name))
expected := golden.Get(t, []byte(actual), fmt.Sprintf("config-inspect-with-format.%s.golden", tc.name))
testutil.EqualNormalizedString(t, testutil.RemoveSpace, actual, string(expected))
} }
} }
@ -172,16 +160,14 @@ func TestConfigInspectPretty(t *testing.T) {
}, },
} }
for _, tc := range testCases { for _, tc := range testCases {
buf := new(bytes.Buffer) cli := test.NewFakeCli(&fakeClient{
cmd := newConfigInspectCommand( configInspectFunc: tc.configInspectFunc,
test.NewFakeCliWithOutput(&fakeClient{ })
configInspectFunc: tc.configInspectFunc, cmd := newConfigInspectCommand(cli)
}, buf))
cmd.SetArgs([]string{"configID"}) cmd.SetArgs([]string{"configID"})
cmd.Flags().Set("pretty", "true") cmd.Flags().Set("pretty", "true")
assert.NoError(t, cmd.Execute()) assert.NoError(t, cmd.Execute())
actual := buf.String() golden.Assert(t, cli.OutBuffer().String(), fmt.Sprintf("config-inspect-pretty.%s.golden", tc.name))
expected := golden.Get(t, []byte(actual), fmt.Sprintf("config-inspect-pretty.%s.golden", tc.name))
testutil.EqualNormalizedString(t, testutil.RemoveSpace, actual, string(expected))
} }
} }

View File

@ -13,7 +13,7 @@ import (
// Import builders to get the builder function as package function // Import builders to get the builder function as package function
. "github.com/docker/cli/cli/internal/test/builders" . "github.com/docker/cli/cli/internal/test/builders"
"github.com/docker/docker/pkg/testutil" "github.com/docker/docker/pkg/testutil"
"github.com/docker/docker/pkg/testutil/golden" "github.com/gotestyourself/gotestyourself/golden"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
) )
@ -68,9 +68,7 @@ func TestConfigList(t *testing.T) {
cmd := newConfigListCommand(cli) cmd := newConfigListCommand(cli)
cmd.SetOutput(cli.OutBuffer()) cmd.SetOutput(cli.OutBuffer())
assert.NoError(t, cmd.Execute()) assert.NoError(t, cmd.Execute())
actual := cli.OutBuffer().String() golden.Assert(t, cli.OutBuffer().String(), "config-list.golden")
expected := golden.Get(t, []byte(actual), "config-list.golden")
testutil.EqualNormalizedString(t, testutil.RemoveSpace, actual, string(expected))
} }
func TestConfigListWithQuietOption(t *testing.T) { func TestConfigListWithQuietOption(t *testing.T) {
@ -87,9 +85,7 @@ func TestConfigListWithQuietOption(t *testing.T) {
cmd := newConfigListCommand(cli) cmd := newConfigListCommand(cli)
cmd.Flags().Set("quiet", "true") cmd.Flags().Set("quiet", "true")
assert.NoError(t, cmd.Execute()) assert.NoError(t, cmd.Execute())
actual := cli.OutBuffer().String() golden.Assert(t, cli.OutBuffer().String(), "config-list-with-quiet-option.golden")
expected := golden.Get(t, []byte(actual), "config-list-with-quiet-option.golden")
testutil.EqualNormalizedString(t, testutil.RemoveSpace, actual, string(expected))
} }
func TestConfigListWithConfigFormat(t *testing.T) { func TestConfigListWithConfigFormat(t *testing.T) {
@ -108,9 +104,7 @@ func TestConfigListWithConfigFormat(t *testing.T) {
}) })
cmd := newConfigListCommand(cli) cmd := newConfigListCommand(cli)
assert.NoError(t, cmd.Execute()) assert.NoError(t, cmd.Execute())
actual := cli.OutBuffer().String() golden.Assert(t, cli.OutBuffer().String(), "config-list-with-config-format.golden")
expected := golden.Get(t, []byte(actual), "config-list-with-config-format.golden")
testutil.EqualNormalizedString(t, testutil.RemoveSpace, actual, string(expected))
} }
func TestConfigListWithFormat(t *testing.T) { func TestConfigListWithFormat(t *testing.T) {
@ -127,9 +121,7 @@ func TestConfigListWithFormat(t *testing.T) {
cmd := newConfigListCommand(cli) cmd := newConfigListCommand(cli)
cmd.Flags().Set("format", "{{ .Name }} {{ .Labels }}") cmd.Flags().Set("format", "{{ .Name }} {{ .Labels }}")
assert.NoError(t, cmd.Execute()) assert.NoError(t, cmd.Execute())
actual := cli.OutBuffer().String() golden.Assert(t, cli.OutBuffer().String(), "config-list-with-format.golden")
expected := golden.Get(t, []byte(actual), "config-list-with-format.golden")
testutil.EqualNormalizedString(t, testutil.RemoveSpace, actual, string(expected))
} }
func TestConfigListWithFilter(t *testing.T) { func TestConfigListWithFilter(t *testing.T) {
@ -157,7 +149,5 @@ func TestConfigListWithFilter(t *testing.T) {
cmd.Flags().Set("filter", "name=foo") cmd.Flags().Set("filter", "name=foo")
cmd.Flags().Set("filter", "label=lbl1=Label-bar") cmd.Flags().Set("filter", "label=lbl1=Label-bar")
assert.NoError(t, cmd.Execute()) assert.NoError(t, cmd.Execute())
actual := cli.OutBuffer().String() golden.Assert(t, cli.OutBuffer().String(), "config-list-with-filter.golden")
expected := golden.Get(t, []byte(actual), "config-list-with-filter.golden")
testutil.EqualNormalizedString(t, testutil.RemoveSpace, actual, string(expected))
} }

View File

@ -1,7 +1,6 @@
package config package config
import ( import (
"bytes"
"io/ioutil" "io/ioutil"
"strings" "strings"
"testing" "testing"
@ -31,11 +30,10 @@ func TestConfigRemoveErrors(t *testing.T) {
}, },
} }
for _, tc := range testCases { for _, tc := range testCases {
buf := new(bytes.Buffer)
cmd := newConfigRemoveCommand( cmd := newConfigRemoveCommand(
test.NewFakeCliWithOutput(&fakeClient{ test.NewFakeCli(&fakeClient{
configRemoveFunc: tc.configRemoveFunc, configRemoveFunc: tc.configRemoveFunc,
}, buf), }),
) )
cmd.SetArgs(tc.args) cmd.SetArgs(tc.args)
cmd.SetOutput(ioutil.Discard) cmd.SetOutput(ioutil.Discard)
@ -45,27 +43,25 @@ func TestConfigRemoveErrors(t *testing.T) {
func TestConfigRemoveWithName(t *testing.T) { func TestConfigRemoveWithName(t *testing.T) {
names := []string{"foo", "bar"} names := []string{"foo", "bar"}
buf := new(bytes.Buffer)
var removedConfigs []string var removedConfigs []string
cli := test.NewFakeCliWithOutput(&fakeClient{ cli := test.NewFakeCli(&fakeClient{
configRemoveFunc: func(name string) error { configRemoveFunc: func(name string) error {
removedConfigs = append(removedConfigs, name) removedConfigs = append(removedConfigs, name)
return nil return nil
}, },
}, buf) })
cmd := newConfigRemoveCommand(cli) cmd := newConfigRemoveCommand(cli)
cmd.SetArgs(names) cmd.SetArgs(names)
assert.NoError(t, cmd.Execute()) assert.NoError(t, cmd.Execute())
assert.Equal(t, names, strings.Split(strings.TrimSpace(buf.String()), "\n")) assert.Equal(t, names, strings.Split(strings.TrimSpace(cli.OutBuffer().String()), "\n"))
assert.Equal(t, names, removedConfigs) assert.Equal(t, names, removedConfigs)
} }
func TestConfigRemoveContinueAfterError(t *testing.T) { func TestConfigRemoveContinueAfterError(t *testing.T) {
names := []string{"foo", "bar"} names := []string{"foo", "bar"}
buf := new(bytes.Buffer)
var removedConfigs []string var removedConfigs []string
cli := test.NewFakeCliWithOutput(&fakeClient{ cli := test.NewFakeCli(&fakeClient{
configRemoveFunc: func(name string) error { configRemoveFunc: func(name string) error {
removedConfigs = append(removedConfigs, name) removedConfigs = append(removedConfigs, name)
if name == "foo" { if name == "foo" {
@ -73,7 +69,7 @@ func TestConfigRemoveContinueAfterError(t *testing.T) {
} }
return nil return nil
}, },
}, buf) })
cmd := newConfigRemoveCommand(cli) cmd := newConfigRemoveCommand(cli)
cmd.SetArgs(names) cmd.SetArgs(names)

View File

@ -1,8 +1,8 @@
ID: configID ID: configID
Name: configName Name: configName
Labels: Labels:
- lbl1=value1 - lbl1=value1
Created at: 0001-01-01 00:00:00+0000 utc Created at: 0001-01-01 00:00:00 +0000 utc
Updated at: 0001-01-01 00:00:00+0000 utc Updated at: 0001-01-01 00:00:00 +0000 utc
Data: Data:
payload here payload here

View File

@ -1,7 +1,7 @@
[ [
{ {
"ID": "ID-foo", "ID": "ID-foo",
"Version": {}, "Version": {},
"CreatedAt": "0001-01-01T00:00:00Z", "CreatedAt": "0001-01-01T00:00:00Z",
"UpdatedAt": "0001-01-01T00:00:00Z", "UpdatedAt": "0001-01-01T00:00:00Z",
"Spec": { "Spec": {
@ -13,7 +13,7 @@
}, },
{ {
"ID": "ID-bar", "ID": "ID-bar",
"Version": {}, "Version": {},
"CreatedAt": "0001-01-01T00:00:00Z", "CreatedAt": "0001-01-01T00:00:00Z",
"UpdatedAt": "0001-01-01T00:00:00Z", "UpdatedAt": "0001-01-01T00:00:00Z",
"Spec": { "Spec": {

View File

@ -1,9 +1,9 @@
[ [
{ {
"ID": "ID-foo", "ID": "ID-foo",
"Version": {}, "Version": {},
"CreatedAt": "0001-01-01T00:00:00Z", "CreatedAt": "0001-01-01T00:00:00Z",
"UpdatedAt": "0001-01-01T00:00:00Z", "UpdatedAt": "0001-01-01T00:00:00Z",
"Spec": { "Spec": {
"Name": "foo", "Name": "foo",
"Labels": null "Labels": null

View File

@ -73,7 +73,7 @@ func TestRunBuildDockerfileFromStdinWithCompress(t *testing.T) {
// starting with `github.com/` are special-cased, and the build command attempts // starting with `github.com/` are special-cased, and the build command attempts
// to clone the remote repo. // to clone the remote repo.
func TestRunBuildFromGitHubSpecialCase(t *testing.T) { func TestRunBuildFromGitHubSpecialCase(t *testing.T) {
cmd := NewBuildCommand(&command.DockerCli{}) cmd := NewBuildCommand(test.NewFakeCli(nil))
cmd.SetArgs([]string{"github.com/docker/no-such-repository"}) cmd.SetArgs([]string{"github.com/docker/no-such-repository"})
cmd.SetOutput(ioutil.Discard) cmd.SetOutput(ioutil.Discard)
err := cmd.Execute() err := cmd.Execute()

View File

@ -3,14 +3,13 @@ package image
import ( import (
"fmt" "fmt"
"io/ioutil" "io/ioutil"
"regexp"
"testing" "testing"
"time" "time"
"github.com/docker/cli/cli/internal/test" "github.com/docker/cli/cli/internal/test"
"github.com/docker/docker/api/types/image" "github.com/docker/docker/api/types/image"
"github.com/docker/docker/pkg/testutil" "github.com/docker/docker/pkg/testutil"
"github.com/docker/docker/pkg/testutil/golden" "github.com/gotestyourself/gotestyourself/golden"
"github.com/pkg/errors" "github.com/pkg/errors"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
) )
@ -96,11 +95,9 @@ func TestNewHistoryCommandSuccess(t *testing.T) {
assert.NoError(t, err) assert.NoError(t, err)
actual := cli.OutBuffer().String() actual := cli.OutBuffer().String()
if tc.outputRegex == "" { if tc.outputRegex == "" {
expected := string(golden.Get(t, []byte(actual), fmt.Sprintf("history-command-success.%s.golden", tc.name))[:]) golden.Assert(t, actual, fmt.Sprintf("history-command-success.%s.golden", tc.name))
testutil.EqualNormalizedString(t, testutil.RemoveSpace, actual, expected)
} else { } else {
match, _ := regexp.MatchString(tc.outputRegex, actual) assert.Regexp(t, tc.outputRegex, actual)
assert.True(t, match)
} }
} }
} }

View File

@ -1,7 +1,6 @@
package image package image
import ( import (
"bytes"
"io" "io"
"io/ioutil" "io/ioutil"
"strings" "strings"
@ -36,8 +35,7 @@ func TestNewImportCommandErrors(t *testing.T) {
}, },
} }
for _, tc := range testCases { for _, tc := range testCases {
buf := new(bytes.Buffer) cmd := NewImportCommand(test.NewFakeCli(&fakeClient{imageImportFunc: tc.imageImportFunc}))
cmd := NewImportCommand(test.NewFakeCliWithOutput(&fakeClient{imageImportFunc: tc.imageImportFunc}, buf))
cmd.SetOutput(ioutil.Discard) cmd.SetOutput(ioutil.Discard)
cmd.SetArgs(tc.args) cmd.SetArgs(tc.args)
testutil.ErrorContains(t, cmd.Execute(), tc.expectedError) testutil.ErrorContains(t, cmd.Execute(), tc.expectedError)
@ -91,8 +89,7 @@ func TestNewImportCommandSuccess(t *testing.T) {
}, },
} }
for _, tc := range testCases { for _, tc := range testCases {
buf := new(bytes.Buffer) cmd := NewImportCommand(test.NewFakeCli(&fakeClient{imageImportFunc: tc.imageImportFunc}))
cmd := NewImportCommand(test.NewFakeCliWithOutput(&fakeClient{imageImportFunc: tc.imageImportFunc}, buf))
cmd.SetOutput(ioutil.Discard) cmd.SetOutput(ioutil.Discard)
cmd.SetArgs(tc.args) cmd.SetArgs(tc.args)
assert.NoError(t, cmd.Execute()) assert.NoError(t, cmd.Execute())

View File

@ -1,7 +1,6 @@
package image package image
import ( import (
"bytes"
"fmt" "fmt"
"io/ioutil" "io/ioutil"
"testing" "testing"
@ -9,7 +8,7 @@ import (
"github.com/docker/cli/cli/internal/test" "github.com/docker/cli/cli/internal/test"
"github.com/docker/docker/api/types" "github.com/docker/docker/api/types"
"github.com/docker/docker/pkg/testutil" "github.com/docker/docker/pkg/testutil"
"github.com/docker/docker/pkg/testutil/golden" "github.com/gotestyourself/gotestyourself/golden"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
) )
@ -26,8 +25,7 @@ func TestNewInspectCommandErrors(t *testing.T) {
}, },
} }
for _, tc := range testCases { for _, tc := range testCases {
buf := new(bytes.Buffer) cmd := newInspectCommand(test.NewFakeCli(&fakeClient{}))
cmd := newInspectCommand(test.NewFakeCliWithOutput(&fakeClient{}, buf))
cmd.SetOutput(ioutil.Discard) cmd.SetOutput(ioutil.Discard)
cmd.SetArgs(tc.args) cmd.SetArgs(tc.args)
testutil.ErrorContains(t, cmd.Execute(), tc.expectedError) testutil.ErrorContains(t, cmd.Execute(), tc.expectedError)
@ -78,15 +76,13 @@ func TestNewInspectCommandSuccess(t *testing.T) {
} }
for _, tc := range testCases { for _, tc := range testCases {
imageInspectInvocationCount = 0 imageInspectInvocationCount = 0
buf := new(bytes.Buffer) cli := test.NewFakeCli(&fakeClient{imageInspectFunc: tc.imageInspectFunc})
cmd := newInspectCommand(test.NewFakeCliWithOutput(&fakeClient{imageInspectFunc: tc.imageInspectFunc}, buf)) cmd := newInspectCommand(cli)
cmd.SetOutput(ioutil.Discard) cmd.SetOutput(ioutil.Discard)
cmd.SetArgs(tc.args) cmd.SetArgs(tc.args)
err := cmd.Execute() err := cmd.Execute()
assert.NoError(t, err) assert.NoError(t, err)
actual := buf.String() golden.Assert(t, cli.OutBuffer().String(), fmt.Sprintf("inspect-command-success.%s.golden", tc.name))
expected := string(golden.Get(t, []byte(actual), fmt.Sprintf("inspect-command-success.%s.golden", tc.name))[:])
testutil.EqualNormalizedString(t, testutil.RemoveSpace, actual, expected)
assert.Equal(t, imageInspectInvocationCount, tc.imageCount) assert.Equal(t, imageInspectInvocationCount, tc.imageCount)
} }
} }

View File

@ -1,7 +1,6 @@
package image package image
import ( import (
"bytes"
"fmt" "fmt"
"io/ioutil" "io/ioutil"
"testing" "testing"
@ -10,7 +9,7 @@ import (
"github.com/docker/cli/cli/internal/test" "github.com/docker/cli/cli/internal/test"
"github.com/docker/docker/api/types" "github.com/docker/docker/api/types"
"github.com/docker/docker/pkg/testutil" "github.com/docker/docker/pkg/testutil"
"github.com/docker/docker/pkg/testutil/golden" "github.com/gotestyourself/gotestyourself/golden"
"github.com/pkg/errors" "github.com/pkg/errors"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
) )
@ -80,17 +79,14 @@ func TestNewImagesCommandSuccess(t *testing.T) {
}, },
} }
for _, tc := range testCases { for _, tc := range testCases {
buf := new(bytes.Buffer) cli := test.NewFakeCli(&fakeClient{imageListFunc: tc.imageListFunc})
cli := test.NewFakeCliWithOutput(&fakeClient{imageListFunc: tc.imageListFunc}, buf)
cli.SetConfigFile(&configfile.ConfigFile{ImagesFormat: tc.imageFormat}) cli.SetConfigFile(&configfile.ConfigFile{ImagesFormat: tc.imageFormat})
cmd := NewImagesCommand(cli) cmd := NewImagesCommand(cli)
cmd.SetOutput(ioutil.Discard) cmd.SetOutput(ioutil.Discard)
cmd.SetArgs(tc.args) cmd.SetArgs(tc.args)
err := cmd.Execute() err := cmd.Execute()
assert.NoError(t, err) assert.NoError(t, err)
actual := buf.String() golden.Assert(t, cli.OutBuffer().String(), fmt.Sprintf("list-command-success.%s.golden", tc.name))
expected := string(golden.Get(t, []byte(actual), fmt.Sprintf("list-command-success.%s.golden", tc.name))[:])
testutil.EqualNormalizedString(t, testutil.RemoveSpace, actual, expected)
} }
} }

View File

@ -1,7 +1,6 @@
package image package image
import ( import (
"bytes"
"fmt" "fmt"
"io" "io"
"io/ioutil" "io/ioutil"
@ -11,7 +10,7 @@ import (
"github.com/docker/cli/cli/internal/test" "github.com/docker/cli/cli/internal/test"
"github.com/docker/docker/api/types" "github.com/docker/docker/api/types"
"github.com/docker/docker/pkg/testutil" "github.com/docker/docker/pkg/testutil"
"github.com/docker/docker/pkg/testutil/golden" "github.com/gotestyourself/gotestyourself/golden"
"github.com/pkg/errors" "github.com/pkg/errors"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
) )
@ -92,14 +91,12 @@ func TestNewLoadCommandSuccess(t *testing.T) {
}, },
} }
for _, tc := range testCases { for _, tc := range testCases {
buf := new(bytes.Buffer) cli := test.NewFakeCli(&fakeClient{imageLoadFunc: tc.imageLoadFunc})
cmd := NewLoadCommand(test.NewFakeCliWithOutput(&fakeClient{imageLoadFunc: tc.imageLoadFunc}, buf)) cmd := NewLoadCommand(cli)
cmd.SetOutput(ioutil.Discard) cmd.SetOutput(ioutil.Discard)
cmd.SetArgs(tc.args) cmd.SetArgs(tc.args)
err := cmd.Execute() err := cmd.Execute()
assert.NoError(t, err) assert.NoError(t, err)
actual := buf.String() golden.Assert(t, cli.OutBuffer().String(), fmt.Sprintf("load-command-success.%s.golden", tc.name))
expected := string(golden.Get(t, []byte(actual), fmt.Sprintf("load-command-success.%s.golden", tc.name))[:])
testutil.EqualNormalizedString(t, testutil.RemoveSpace, actual, expected)
} }
} }

View File

@ -1,7 +1,6 @@
package image package image
import ( import (
"bytes"
"fmt" "fmt"
"io/ioutil" "io/ioutil"
"testing" "testing"
@ -10,7 +9,7 @@ import (
"github.com/docker/docker/api/types" "github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/filters" "github.com/docker/docker/api/types/filters"
"github.com/docker/docker/pkg/testutil" "github.com/docker/docker/pkg/testutil"
"github.com/docker/docker/pkg/testutil/golden" "github.com/gotestyourself/gotestyourself/golden"
"github.com/pkg/errors" "github.com/pkg/errors"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
) )
@ -37,10 +36,9 @@ func TestNewPruneCommandErrors(t *testing.T) {
}, },
} }
for _, tc := range testCases { for _, tc := range testCases {
buf := new(bytes.Buffer) cmd := NewPruneCommand(test.NewFakeCli(&fakeClient{
cmd := NewPruneCommand(test.NewFakeCliWithOutput(&fakeClient{
imagesPruneFunc: tc.imagesPruneFunc, imagesPruneFunc: tc.imagesPruneFunc,
}, buf)) }))
cmd.SetOutput(ioutil.Discard) cmd.SetOutput(ioutil.Discard)
cmd.SetArgs(tc.args) cmd.SetArgs(tc.args)
testutil.ErrorContains(t, cmd.Execute(), tc.expectedError) testutil.ErrorContains(t, cmd.Execute(), tc.expectedError)
@ -85,16 +83,12 @@ func TestNewPruneCommandSuccess(t *testing.T) {
}, },
} }
for _, tc := range testCases { for _, tc := range testCases {
buf := new(bytes.Buffer) cli := test.NewFakeCli(&fakeClient{imagesPruneFunc: tc.imagesPruneFunc})
cmd := NewPruneCommand(test.NewFakeCliWithOutput(&fakeClient{ cmd := NewPruneCommand(cli)
imagesPruneFunc: tc.imagesPruneFunc,
}, buf))
cmd.SetOutput(ioutil.Discard) cmd.SetOutput(ioutil.Discard)
cmd.SetArgs(tc.args) cmd.SetArgs(tc.args)
err := cmd.Execute() err := cmd.Execute()
assert.NoError(t, err) assert.NoError(t, err)
actual := buf.String() golden.Assert(t, cli.OutBuffer().String(), fmt.Sprintf("prune-command-success.%s.golden", tc.name))
expected := string(golden.Get(t, []byte(actual), fmt.Sprintf("prune-command-success.%s.golden", tc.name))[:])
testutil.EqualNormalizedString(t, testutil.RemoveSpace, actual, expected)
} }
} }

View File

@ -7,7 +7,7 @@ import (
"github.com/docker/cli/cli/internal/test" "github.com/docker/cli/cli/internal/test"
"github.com/docker/docker/pkg/testutil" "github.com/docker/docker/pkg/testutil"
"github.com/docker/docker/pkg/testutil/golden" "github.com/gotestyourself/gotestyourself/golden"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
) )
@ -68,8 +68,6 @@ func TestNewPullCommandSuccess(t *testing.T) {
cmd.SetArgs(tc.args) cmd.SetArgs(tc.args)
err := cmd.Execute() err := cmd.Execute()
assert.NoError(t, err) assert.NoError(t, err)
actual := cli.OutBuffer().String() golden.Assert(t, cli.OutBuffer().String(), fmt.Sprintf("pull-command-success.%s.golden", tc.name))
expected := string(golden.Get(t, []byte(actual), fmt.Sprintf("pull-command-success.%s.golden", tc.name))[:])
testutil.EqualNormalizedString(t, testutil.RemoveSpace, actual, expected)
} }
} }

View File

@ -8,7 +8,7 @@ import (
"github.com/docker/cli/cli/internal/test" "github.com/docker/cli/cli/internal/test"
"github.com/docker/docker/api/types" "github.com/docker/docker/api/types"
"github.com/docker/docker/pkg/testutil" "github.com/docker/docker/pkg/testutil"
"github.com/docker/docker/pkg/testutil/golden" "github.com/gotestyourself/gotestyourself/golden"
"github.com/pkg/errors" "github.com/pkg/errors"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
) )
@ -96,16 +96,14 @@ func TestNewRemoveCommandSuccess(t *testing.T) {
}, },
} }
for _, tc := range testCases { for _, tc := range testCases {
fakeCli := test.NewFakeCli(&fakeClient{imageRemoveFunc: tc.imageRemoveFunc}) cli := test.NewFakeCli(&fakeClient{imageRemoveFunc: tc.imageRemoveFunc})
cmd := NewRemoveCommand(fakeCli) cmd := NewRemoveCommand(cli)
cmd.SetOutput(ioutil.Discard) cmd.SetOutput(ioutil.Discard)
cmd.SetArgs(tc.args) cmd.SetArgs(tc.args)
assert.NoError(t, cmd.Execute()) assert.NoError(t, cmd.Execute())
if tc.expectedErrMsg != "" { if tc.expectedErrMsg != "" {
assert.Equal(t, tc.expectedErrMsg, fakeCli.ErrBuffer().String()) assert.Equal(t, tc.expectedErrMsg, cli.ErrBuffer().String())
} }
actual := fakeCli.OutBuffer().String() golden.Assert(t, cli.OutBuffer().String(), fmt.Sprintf("remove-command-success.%s.golden", tc.name))
expected := string(golden.Get(t, []byte(actual), fmt.Sprintf("remove-command-success.%s.golden", tc.name))[:])
testutil.EqualNormalizedString(t, testutil.RemoveSpace, actual, expected)
} }
} }

View File

@ -1,7 +1,6 @@
package image package image
import ( import (
"bytes"
"io" "io"
"io/ioutil" "io/ioutil"
"os" "os"
@ -90,11 +89,11 @@ func TestNewSaveCommandSuccess(t *testing.T) {
}, },
} }
for _, tc := range testCases { for _, tc := range testCases {
cmd := NewSaveCommand(test.NewFakeCliWithOutput(&fakeClient{ cmd := NewSaveCommand(test.NewFakeCli(&fakeClient{
imageSaveFunc: func(images []string) (io.ReadCloser, error) { imageSaveFunc: func(images []string) (io.ReadCloser, error) {
return ioutil.NopCloser(strings.NewReader("")), nil return ioutil.NopCloser(strings.NewReader("")), nil
}, },
}, new(bytes.Buffer))) }))
cmd.SetOutput(ioutil.Discard) cmd.SetOutput(ioutil.Discard)
cmd.SetArgs(tc.args) cmd.SetArgs(tc.args)
assert.NoError(t, cmd.Execute()) assert.NoError(t, cmd.Execute())

View File

@ -1,7 +1,6 @@
package node package node
import ( import (
"bytes"
"fmt" "fmt"
"io/ioutil" "io/ioutil"
"testing" "testing"
@ -13,7 +12,7 @@ import (
// Import builders to get the builder function as package function // Import builders to get the builder function as package function
. "github.com/docker/cli/cli/internal/test/builders" . "github.com/docker/cli/cli/internal/test/builders"
"github.com/docker/docker/pkg/testutil" "github.com/docker/docker/pkg/testutil"
"github.com/docker/docker/pkg/testutil/golden" "github.com/gotestyourself/gotestyourself/golden"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
) )
@ -67,12 +66,11 @@ func TestNodeInspectErrors(t *testing.T) {
}, },
} }
for _, tc := range testCases { for _, tc := range testCases {
buf := new(bytes.Buffer)
cmd := newInspectCommand( cmd := newInspectCommand(
test.NewFakeCliWithOutput(&fakeClient{ test.NewFakeCli(&fakeClient{
nodeInspectFunc: tc.nodeInspectFunc, nodeInspectFunc: tc.nodeInspectFunc,
infoFunc: tc.infoFunc, infoFunc: tc.infoFunc,
}, buf)) }))
cmd.SetArgs(tc.args) cmd.SetArgs(tc.args)
for key, value := range tc.flags { for key, value := range tc.flags {
cmd.Flags().Set(key, value) cmd.Flags().Set(key, value)
@ -109,16 +107,13 @@ func TestNodeInspectPretty(t *testing.T) {
}, },
} }
for _, tc := range testCases { for _, tc := range testCases {
buf := new(bytes.Buffer) cli := test.NewFakeCli(&fakeClient{
cmd := newInspectCommand( nodeInspectFunc: tc.nodeInspectFunc,
test.NewFakeCliWithOutput(&fakeClient{ })
nodeInspectFunc: tc.nodeInspectFunc, cmd := newInspectCommand(cli)
}, buf))
cmd.SetArgs([]string{"nodeID"}) cmd.SetArgs([]string{"nodeID"})
cmd.Flags().Set("pretty", "true") cmd.Flags().Set("pretty", "true")
assert.NoError(t, cmd.Execute()) assert.NoError(t, cmd.Execute())
actual := buf.String() golden.Assert(t, cli.OutBuffer().String(), fmt.Sprintf("node-inspect-pretty.%s.golden", tc.name))
expected := golden.Get(t, []byte(actual), fmt.Sprintf("node-inspect-pretty.%s.golden", tc.name))
testutil.EqualNormalizedString(t, testutil.RemoveSpace, actual, string(expected))
} }
} }

View File

@ -1,7 +1,6 @@
package node package node
import ( import (
"bytes"
"io/ioutil" "io/ioutil"
"testing" "testing"
@ -9,8 +8,7 @@ import (
"github.com/docker/cli/cli/internal/test" "github.com/docker/cli/cli/internal/test"
"github.com/docker/docker/api/types" "github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/swarm" "github.com/docker/docker/api/types/swarm"
"github.com/docker/docker/pkg/testutil" "github.com/gotestyourself/gotestyourself/golden"
"github.com/docker/docker/pkg/testutil/golden"
"github.com/pkg/errors" "github.com/pkg/errors"
// Import builders to get the builder function as package function // Import builders to get the builder function as package function
. "github.com/docker/cli/cli/internal/test/builders" . "github.com/docker/cli/cli/internal/test/builders"
@ -58,9 +56,9 @@ func TestNodeList(t *testing.T) {
cli := test.NewFakeCli(&fakeClient{ cli := test.NewFakeCli(&fakeClient{
nodeListFunc: func() ([]swarm.Node, error) { nodeListFunc: func() ([]swarm.Node, error) {
return []swarm.Node{ return []swarm.Node{
*Node(NodeID("nodeID1"), Hostname("nodeHostname1"), Manager(Leader())), *Node(NodeID("nodeID1"), Hostname("node-2-foo"), Manager(Leader())),
*Node(NodeID("nodeID2"), Hostname("nodeHostname2"), Manager()), *Node(NodeID("nodeID2"), Hostname("node-10-foo"), Manager()),
*Node(NodeID("nodeID3"), Hostname("nodeHostname3")), *Node(NodeID("nodeID3"), Hostname("node-1-foo")),
}, nil }, nil
}, },
infoFunc: func() (types.Info, error) { infoFunc: func() (types.Info, error) {
@ -74,39 +72,25 @@ func TestNodeList(t *testing.T) {
cmd := newListCommand(cli) cmd := newListCommand(cli)
assert.NoError(t, cmd.Execute()) assert.NoError(t, cmd.Execute())
out := cli.OutBuffer().String() golden.Assert(t, cli.OutBuffer().String(), "node-list-sort.golden")
assert.Contains(t, out, `nodeID1 * nodeHostname1 Ready Active Leader`)
assert.Contains(t, out, `nodeID2 nodeHostname2 Ready Active Reachable`)
assert.Contains(t, out, `nodeID3 nodeHostname3 Ready Active`)
} }
func TestNodeListQuietShouldOnlyPrintIDs(t *testing.T) { func TestNodeListQuietShouldOnlyPrintIDs(t *testing.T) {
buf := new(bytes.Buffer) cli := test.NewFakeCli(&fakeClient{
cli := test.NewFakeCliWithOutput(&fakeClient{
nodeListFunc: func() ([]swarm.Node, error) { nodeListFunc: func() ([]swarm.Node, error) {
return []swarm.Node{ return []swarm.Node{
*Node(), *Node(NodeID("nodeID1")),
}, nil }, nil
}, },
}, buf) })
cmd := newListCommand(cli) cmd := newListCommand(cli)
cmd.Flags().Set("quiet", "true") cmd.Flags().Set("quiet", "true")
assert.NoError(t, cmd.Execute()) assert.NoError(t, cmd.Execute())
assert.Contains(t, buf.String(), "nodeID") assert.Equal(t, cli.OutBuffer().String(), "nodeID1\n")
} }
// Test case for #24090 func TestNodeListDefaultFormatFromConfig(t *testing.T) {
func TestNodeListContainsHostname(t *testing.T) { cli := test.NewFakeCli(&fakeClient{
buf := new(bytes.Buffer)
cli := test.NewFakeCliWithOutput(&fakeClient{}, buf)
cmd := newListCommand(cli)
assert.NoError(t, cmd.Execute())
assert.Contains(t, buf.String(), "HOSTNAME")
}
func TestNodeListDefaultFormat(t *testing.T) {
buf := new(bytes.Buffer)
cli := test.NewFakeCliWithOutput(&fakeClient{
nodeListFunc: func() ([]swarm.Node, error) { nodeListFunc: func() ([]swarm.Node, error) {
return []swarm.Node{ return []swarm.Node{
*Node(NodeID("nodeID1"), Hostname("nodeHostname1"), Manager(Leader())), *Node(NodeID("nodeID1"), Hostname("nodeHostname1"), Manager(Leader())),
@ -121,20 +105,17 @@ func TestNodeListDefaultFormat(t *testing.T) {
}, },
}, nil }, nil
}, },
}, buf) })
cli.SetConfigFile(&configfile.ConfigFile{ cli.SetConfigFile(&configfile.ConfigFile{
NodesFormat: "{{.ID}}: {{.Hostname}} {{.Status}}/{{.ManagerStatus}}", NodesFormat: "{{.ID}}: {{.Hostname}} {{.Status}}/{{.ManagerStatus}}",
}) })
cmd := newListCommand(cli) cmd := newListCommand(cli)
assert.NoError(t, cmd.Execute()) assert.NoError(t, cmd.Execute())
assert.Contains(t, buf.String(), `nodeID1: nodeHostname1 Ready/Leader`) golden.Assert(t, cli.OutBuffer().String(), "node-list-format-from-config.golden")
assert.Contains(t, buf.String(), `nodeID2: nodeHostname2 Ready/Reachable`)
assert.Contains(t, buf.String(), `nodeID3: nodeHostname3 Ready`)
} }
func TestNodeListFormat(t *testing.T) { func TestNodeListFormat(t *testing.T) {
buf := new(bytes.Buffer) cli := test.NewFakeCli(&fakeClient{
cli := test.NewFakeCliWithOutput(&fakeClient{
nodeListFunc: func() ([]swarm.Node, error) { nodeListFunc: func() ([]swarm.Node, error) {
return []swarm.Node{ return []swarm.Node{
*Node(NodeID("nodeID1"), Hostname("nodeHostname1"), Manager(Leader())), *Node(NodeID("nodeID1"), Hostname("nodeHostname1"), Manager(Leader())),
@ -148,32 +129,12 @@ func TestNodeListFormat(t *testing.T) {
}, },
}, nil }, nil
}, },
}, buf) })
cli.SetConfigFile(&configfile.ConfigFile{ cli.SetConfigFile(&configfile.ConfigFile{
NodesFormat: "{{.ID}}: {{.Hostname}} {{.Status}}/{{.ManagerStatus}}", NodesFormat: "{{.ID}}: {{.Hostname}} {{.Status}}/{{.ManagerStatus}}",
}) })
cmd := newListCommand(cli) cmd := newListCommand(cli)
cmd.Flags().Set("format", "{{.Hostname}}: {{.ManagerStatus}}") cmd.Flags().Set("format", "{{.Hostname}}: {{.ManagerStatus}}")
assert.NoError(t, cmd.Execute()) assert.NoError(t, cmd.Execute())
assert.Contains(t, buf.String(), `nodeHostname1: Leader`) golden.Assert(t, cli.OutBuffer().String(), "node-list-format-flag.golden")
assert.Contains(t, buf.String(), `nodeHostname2: Reachable`)
}
func TestNodeListOrder(t *testing.T) {
cli := test.NewFakeCli(&fakeClient{
nodeListFunc: func() ([]swarm.Node, error) {
return []swarm.Node{
*Node(Hostname("node-2-foo"), Manager(Leader())),
*Node(Hostname("node-10-foo"), Manager()),
*Node(Hostname("node-1-foo")),
}, nil
},
})
cmd := newListCommand(cli)
cmd.Flags().Set("format", "{{.Hostname}}: {{.ManagerStatus}}")
assert.NoError(t, cmd.Execute())
actual := cli.OutBuffer().String()
expected := golden.Get(t, []byte(actual), "node-list-sort.golden")
testutil.EqualNormalizedString(t, testutil.RemoveSpace, actual, string(expected))
} }

View File

@ -1,7 +1,6 @@
package node package node
import ( import (
"bytes"
"io/ioutil" "io/ioutil"
"testing" "testing"
@ -40,12 +39,11 @@ func TestNodePromoteErrors(t *testing.T) {
}, },
} }
for _, tc := range testCases { for _, tc := range testCases {
buf := new(bytes.Buffer)
cmd := newPromoteCommand( cmd := newPromoteCommand(
test.NewFakeCliWithOutput(&fakeClient{ test.NewFakeCli(&fakeClient{
nodeInspectFunc: tc.nodeInspectFunc, nodeInspectFunc: tc.nodeInspectFunc,
nodeUpdateFunc: tc.nodeUpdateFunc, nodeUpdateFunc: tc.nodeUpdateFunc,
}, buf)) }))
cmd.SetArgs(tc.args) cmd.SetArgs(tc.args)
cmd.SetOutput(ioutil.Discard) cmd.SetOutput(ioutil.Discard)
testutil.ErrorContains(t, cmd.Execute(), tc.expectedError) testutil.ErrorContains(t, cmd.Execute(), tc.expectedError)
@ -53,9 +51,8 @@ func TestNodePromoteErrors(t *testing.T) {
} }
func TestNodePromoteNoChange(t *testing.T) { func TestNodePromoteNoChange(t *testing.T) {
buf := new(bytes.Buffer)
cmd := newPromoteCommand( cmd := newPromoteCommand(
test.NewFakeCliWithOutput(&fakeClient{ test.NewFakeCli(&fakeClient{
nodeInspectFunc: func() (swarm.Node, []byte, error) { nodeInspectFunc: func() (swarm.Node, []byte, error) {
return *Node(Manager()), []byte{}, nil return *Node(Manager()), []byte{}, nil
}, },
@ -65,15 +62,14 @@ func TestNodePromoteNoChange(t *testing.T) {
} }
return nil return nil
}, },
}, buf)) }))
cmd.SetArgs([]string{"nodeID"}) cmd.SetArgs([]string{"nodeID"})
assert.NoError(t, cmd.Execute()) assert.NoError(t, cmd.Execute())
} }
func TestNodePromoteMultipleNode(t *testing.T) { func TestNodePromoteMultipleNode(t *testing.T) {
buf := new(bytes.Buffer)
cmd := newPromoteCommand( cmd := newPromoteCommand(
test.NewFakeCliWithOutput(&fakeClient{ test.NewFakeCli(&fakeClient{
nodeInspectFunc: func() (swarm.Node, []byte, error) { nodeInspectFunc: func() (swarm.Node, []byte, error) {
return *Node(), []byte{}, nil return *Node(), []byte{}, nil
}, },
@ -83,7 +79,7 @@ func TestNodePromoteMultipleNode(t *testing.T) {
} }
return nil return nil
}, },
}, buf)) }))
cmd.SetArgs([]string{"nodeID1", "nodeID2"}) cmd.SetArgs([]string{"nodeID1", "nodeID2"})
assert.NoError(t, cmd.Execute()) assert.NoError(t, cmd.Execute())
} }

View File

@ -1,7 +1,6 @@
package node package node
import ( import (
"bytes"
"fmt" "fmt"
"io/ioutil" "io/ioutil"
"testing" "testing"
@ -13,8 +12,7 @@ import (
"github.com/pkg/errors" "github.com/pkg/errors"
// Import builders to get the builder function as package function // Import builders to get the builder function as package function
. "github.com/docker/cli/cli/internal/test/builders" . "github.com/docker/cli/cli/internal/test/builders"
"github.com/docker/docker/pkg/testutil" "github.com/gotestyourself/gotestyourself/golden"
"github.com/docker/docker/pkg/testutil/golden"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
) )
@ -50,14 +48,13 @@ func TestNodePsErrors(t *testing.T) {
}, },
} }
for _, tc := range testCases { for _, tc := range testCases {
buf := new(bytes.Buffer) cli := test.NewFakeCli(&fakeClient{
cmd := newPsCommand( infoFunc: tc.infoFunc,
test.NewFakeCliWithOutput(&fakeClient{ nodeInspectFunc: tc.nodeInspectFunc,
infoFunc: tc.infoFunc, taskInspectFunc: tc.taskInspectFunc,
nodeInspectFunc: tc.nodeInspectFunc, taskListFunc: tc.taskListFunc,
taskInspectFunc: tc.taskInspectFunc, })
taskListFunc: tc.taskListFunc, cmd := newPsCommand(cli)
}, buf))
cmd.SetArgs(tc.args) cmd.SetArgs(tc.args)
for key, value := range tc.flags { for key, value := range tc.flags {
cmd.Flags().Set(key, value) cmd.Flags().Set(key, value)
@ -114,21 +111,18 @@ func TestNodePs(t *testing.T) {
}, },
} }
for _, tc := range testCases { for _, tc := range testCases {
buf := new(bytes.Buffer) cli := test.NewFakeCli(&fakeClient{
cmd := newPsCommand( infoFunc: tc.infoFunc,
test.NewFakeCliWithOutput(&fakeClient{ nodeInspectFunc: tc.nodeInspectFunc,
infoFunc: tc.infoFunc, taskInspectFunc: tc.taskInspectFunc,
nodeInspectFunc: tc.nodeInspectFunc, taskListFunc: tc.taskListFunc,
taskInspectFunc: tc.taskInspectFunc, })
taskListFunc: tc.taskListFunc, cmd := newPsCommand(cli)
}, buf))
cmd.SetArgs(tc.args) cmd.SetArgs(tc.args)
for key, value := range tc.flags { for key, value := range tc.flags {
cmd.Flags().Set(key, value) cmd.Flags().Set(key, value)
} }
assert.NoError(t, cmd.Execute()) assert.NoError(t, cmd.Execute())
actual := buf.String() golden.Assert(t, cli.OutBuffer().String(), fmt.Sprintf("node-ps.%s.golden", tc.name))
expected := golden.Get(t, []byte(actual), fmt.Sprintf("node-ps.%s.golden", tc.name))
testutil.EqualNormalizedString(t, testutil.RemoveSpace, actual, string(expected))
} }
} }

View File

@ -1,7 +1,6 @@
package node package node
import ( import (
"bytes"
"io/ioutil" "io/ioutil"
"testing" "testing"
@ -29,11 +28,10 @@ func TestNodeRemoveErrors(t *testing.T) {
}, },
} }
for _, tc := range testCases { for _, tc := range testCases {
buf := new(bytes.Buffer)
cmd := newRemoveCommand( cmd := newRemoveCommand(
test.NewFakeCliWithOutput(&fakeClient{ test.NewFakeCli(&fakeClient{
nodeRemoveFunc: tc.nodeRemoveFunc, nodeRemoveFunc: tc.nodeRemoveFunc,
}, buf)) }))
cmd.SetArgs(tc.args) cmd.SetArgs(tc.args)
cmd.SetOutput(ioutil.Discard) cmd.SetOutput(ioutil.Discard)
testutil.ErrorContains(t, cmd.Execute(), tc.expectedError) testutil.ErrorContains(t, cmd.Execute(), tc.expectedError)
@ -41,8 +39,7 @@ func TestNodeRemoveErrors(t *testing.T) {
} }
func TestNodeRemoveMultiple(t *testing.T) { func TestNodeRemoveMultiple(t *testing.T) {
buf := new(bytes.Buffer) cmd := newRemoveCommand(test.NewFakeCli(&fakeClient{}))
cmd := newRemoveCommand(test.NewFakeCliWithOutput(&fakeClient{}, buf))
cmd.SetArgs([]string{"nodeID1", "nodeID2"}) cmd.SetArgs([]string{"nodeID1", "nodeID2"})
assert.NoError(t, cmd.Execute()) assert.NoError(t, cmd.Execute())
} }

View File

@ -1,10 +1,10 @@
ID: nodeID ID: nodeID
Name: defaultNodeName Name: defaultNodeName
Hostname: defaultNodeHostname Hostname: defaultNodeHostname
Joined at: 2009-11-10 23:00:00 +0000 utc Joined at: 2009-11-10 23:00:00 +0000 utc
Status: Status:
State: Ready State: Ready
Availability: Active Availability: Active
Address: 127.0.0.1 Address: 127.0.0.1
Manager Status: Manager Status:
Address: 127.0.0.1 Address: 127.0.0.1
@ -15,11 +15,10 @@ Platform:
Architecture: x86_64 Architecture: x86_64
Resources: Resources:
CPUs: 0 CPUs: 0
Memory: 20 MiB Memory: 20MiB
Plugins: Plugins:
Network: bridge, overlay Network: bridge, overlay
Volume: local Volume: local
Engine Version: 1.13.0 Engine Version: 1.13.0
Engine Labels: Engine Labels:
- engine = label - engine=label

View File

@ -1,10 +1,10 @@
ID: nodeID ID: nodeID
Name: defaultNodeName Name: defaultNodeName
Hostname: defaultNodeHostname Hostname: defaultNodeHostname
Joined at: 2009-11-10 23:00:00 +0000 utc Joined at: 2009-11-10 23:00:00 +0000 utc
Status: Status:
State: Ready State: Ready
Availability: Active Availability: Active
Address: 127.0.0.1 Address: 127.0.0.1
Manager Status: Manager Status:
Address: 127.0.0.1 Address: 127.0.0.1
@ -15,11 +15,10 @@ Platform:
Architecture: x86_64 Architecture: x86_64
Resources: Resources:
CPUs: 0 CPUs: 0
Memory: 20 MiB Memory: 20MiB
Plugins: Plugins:
Network: bridge, overlay Network: bridge, overlay
Volume: local Volume: local
Engine Version: 1.13.0 Engine Version: 1.13.0
Engine Labels: Engine Labels:
- engine = label - engine=label

View File

@ -1,23 +1,22 @@
ID: nodeID ID: nodeID
Name: defaultNodeName Name: defaultNodeName
Labels: Labels:
- lbl1 = value1 - lbl1=value1
Hostname: defaultNodeHostname Hostname: defaultNodeHostname
Joined at: 2009-11-10 23:00:00 +0000 utc Joined at: 2009-11-10 23:00:00 +0000 utc
Status: Status:
State: Ready State: Ready
Availability: Active Availability: Active
Address: 127.0.0.1 Address: 127.0.0.1
Platform: Platform:
Operating System: linux Operating System: linux
Architecture: x86_64 Architecture: x86_64
Resources: Resources:
CPUs: 0 CPUs: 0
Memory: 20 MiB Memory: 20MiB
Plugins: Plugins:
Network: bridge, overlay Network: bridge, overlay
Volume: local Volume: local
Engine Version: 1.13.0 Engine Version: 1.13.0
Engine Labels: Engine Labels:
- engine = label - engine=label

View File

@ -0,0 +1,2 @@
nodeHostname1: Leader
nodeHostname2: Reachable

View File

@ -0,0 +1,3 @@
nodeID1: nodeHostname1 Ready/Leader
nodeID2: nodeHostname2 Ready/Reachable
nodeID3: nodeHostname3 Ready/

View File

@ -1,3 +1,4 @@
node-1-foo: ID HOSTNAME STATUS AVAILABILITY MANAGER STATUS
node-2-foo: Leader nodeID3 node-1-foo Ready Active
node-10-foo: Reachable nodeID1 * node-2-foo Ready Active Leader
nodeID2 node-10-foo Ready Active Reachable

View File

@ -1,2 +1,2 @@
ID NAME IMAGE NODE DESIRED STATE CURRENT STATE ERROR PORTS ID NAME IMAGE NODE DESIRED STATE CURRENT STATE ERROR PORTS
taskID rl02d5gwz6chzu7il5fhtb8be.1 myimage:mytag defaultNodeName Ready Ready 2 hours ago *:80->80/tcp taskID rl02d5gwz6chzu7il5fhtb8be.1 myimage:mytag defaultNodeName Ready Ready 2 hours ago *:80->80/tcp

View File

@ -1,4 +1,4 @@
ID NAME IMAGE NODE DESIRED STATE CURRENT STATE ERROR PORTS ID NAME IMAGE NODE DESIRED STATE CURRENT STATE ERROR PORTS
taskID1 failure.1 myimage:mytag defaultNodeName Ready Ready 2 hours ago "a task error" taskID1 failure.1 myimage:mytag defaultNodeName Ready Ready 2 hours ago "a task error"
taskID2 \_ failure.1 myimage:mytag defaultNodeName Ready Ready 3 hours ago "a task error" taskID2 \_ failure.1 myimage:mytag defaultNodeName Ready Ready 3 hours ago "a task error"
taskID3 \_ failure.1 myimage:mytag defaultNodeName Ready Ready 4 hours ago "a task error" taskID3 \_ failure.1 myimage:mytag defaultNodeName Ready Ready 4 hours ago "a task error"

View File

@ -1,7 +1,6 @@
package secret package secret
import ( import (
"bytes"
"io/ioutil" "io/ioutil"
"path/filepath" "path/filepath"
"reflect" "reflect"
@ -12,7 +11,7 @@ import (
"github.com/docker/docker/api/types" "github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/swarm" "github.com/docker/docker/api/types/swarm"
"github.com/docker/docker/pkg/testutil" "github.com/docker/docker/pkg/testutil"
"github.com/docker/docker/pkg/testutil/golden" "github.com/gotestyourself/gotestyourself/golden"
"github.com/pkg/errors" "github.com/pkg/errors"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
) )
@ -54,9 +53,8 @@ func TestSecretCreateErrors(t *testing.T) {
func TestSecretCreateWithName(t *testing.T) { func TestSecretCreateWithName(t *testing.T) {
name := "foo" name := "foo"
buf := new(bytes.Buffer)
var actual []byte var actual []byte
cli := test.NewFakeCliWithOutput(&fakeClient{ cli := test.NewFakeCli(&fakeClient{
secretCreateFunc: func(spec swarm.SecretSpec) (types.SecretCreateResponse, error) { secretCreateFunc: func(spec swarm.SecretSpec) (types.SecretCreateResponse, error) {
if spec.Name != name { if spec.Name != name {
return types.SecretCreateResponse{}, errors.Errorf("expected name %q, got %q", name, spec.Name) return types.SecretCreateResponse{}, errors.Errorf("expected name %q, got %q", name, spec.Name)
@ -68,14 +66,13 @@ func TestSecretCreateWithName(t *testing.T) {
ID: "ID-" + spec.Name, ID: "ID-" + spec.Name,
}, nil }, nil
}, },
}, buf) })
cmd := newSecretCreateCommand(cli) cmd := newSecretCreateCommand(cli)
cmd.SetArgs([]string{name, filepath.Join("testdata", secretDataFile)}) cmd.SetArgs([]string{name, filepath.Join("testdata", secretDataFile)})
assert.NoError(t, cmd.Execute()) assert.NoError(t, cmd.Execute())
expected := golden.Get(t, actual, secretDataFile) golden.Assert(t, string(actual), secretDataFile)
assert.Equal(t, expected, actual) assert.Equal(t, "ID-"+name, strings.TrimSpace(cli.OutBuffer().String()))
assert.Equal(t, "ID-"+name, strings.TrimSpace(buf.String()))
} }
func TestSecretCreateWithLabels(t *testing.T) { func TestSecretCreateWithLabels(t *testing.T) {
@ -85,8 +82,7 @@ func TestSecretCreateWithLabels(t *testing.T) {
} }
name := "foo" name := "foo"
buf := new(bytes.Buffer) cli := test.NewFakeCli(&fakeClient{
cli := test.NewFakeCliWithOutput(&fakeClient{
secretCreateFunc: func(spec swarm.SecretSpec) (types.SecretCreateResponse, error) { secretCreateFunc: func(spec swarm.SecretSpec) (types.SecretCreateResponse, error) {
if spec.Name != name { if spec.Name != name {
return types.SecretCreateResponse{}, errors.Errorf("expected name %q, got %q", name, spec.Name) return types.SecretCreateResponse{}, errors.Errorf("expected name %q, got %q", name, spec.Name)
@ -100,12 +96,12 @@ func TestSecretCreateWithLabels(t *testing.T) {
ID: "ID-" + spec.Name, ID: "ID-" + spec.Name,
}, nil }, nil
}, },
}, buf) })
cmd := newSecretCreateCommand(cli) cmd := newSecretCreateCommand(cli)
cmd.SetArgs([]string{name, filepath.Join("testdata", secretDataFile)}) cmd.SetArgs([]string{name, filepath.Join("testdata", secretDataFile)})
cmd.Flags().Set("label", "lbl1=Label-foo") cmd.Flags().Set("label", "lbl1=Label-foo")
cmd.Flags().Set("label", "lbl2=Label-bar") cmd.Flags().Set("label", "lbl2=Label-bar")
assert.NoError(t, cmd.Execute()) assert.NoError(t, cmd.Execute())
assert.Equal(t, "ID-"+name, strings.TrimSpace(buf.String())) assert.Equal(t, "ID-"+name, strings.TrimSpace(cli.OutBuffer().String()))
} }

View File

@ -1,7 +1,6 @@
package secret package secret
import ( import (
"bytes"
"fmt" "fmt"
"io/ioutil" "io/ioutil"
"testing" "testing"
@ -13,7 +12,7 @@ import (
// Import builders to get the builder function as package function // Import builders to get the builder function as package function
. "github.com/docker/cli/cli/internal/test/builders" . "github.com/docker/cli/cli/internal/test/builders"
"github.com/docker/docker/pkg/testutil" "github.com/docker/docker/pkg/testutil"
"github.com/docker/docker/pkg/testutil/golden" "github.com/gotestyourself/gotestyourself/golden"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
) )
@ -53,11 +52,10 @@ func TestSecretInspectErrors(t *testing.T) {
}, },
} }
for _, tc := range testCases { for _, tc := range testCases {
buf := new(bytes.Buffer)
cmd := newSecretInspectCommand( cmd := newSecretInspectCommand(
test.NewFakeCliWithOutput(&fakeClient{ test.NewFakeCli(&fakeClient{
secretInspectFunc: tc.secretInspectFunc, secretInspectFunc: tc.secretInspectFunc,
}, buf), }),
) )
cmd.SetArgs(tc.args) cmd.SetArgs(tc.args)
for key, value := range tc.flags { for key, value := range tc.flags {
@ -95,17 +93,13 @@ func TestSecretInspectWithoutFormat(t *testing.T) {
}, },
} }
for _, tc := range testCases { for _, tc := range testCases {
buf := new(bytes.Buffer) cli := test.NewFakeCli(&fakeClient{
cmd := newSecretInspectCommand( secretInspectFunc: tc.secretInspectFunc,
test.NewFakeCliWithOutput(&fakeClient{ })
secretInspectFunc: tc.secretInspectFunc, cmd := newSecretInspectCommand(cli)
}, buf),
)
cmd.SetArgs(tc.args) cmd.SetArgs(tc.args)
assert.NoError(t, cmd.Execute()) assert.NoError(t, cmd.Execute())
actual := buf.String() golden.Assert(t, cli.OutBuffer().String(), fmt.Sprintf("secret-inspect-without-format.%s.golden", tc.name))
expected := golden.Get(t, []byte(actual), fmt.Sprintf("secret-inspect-without-format.%s.golden", tc.name))
testutil.EqualNormalizedString(t, testutil.RemoveSpace, actual, string(expected))
} }
} }
@ -135,18 +129,14 @@ func TestSecretInspectWithFormat(t *testing.T) {
}, },
} }
for _, tc := range testCases { for _, tc := range testCases {
buf := new(bytes.Buffer) cli := test.NewFakeCli(&fakeClient{
cmd := newSecretInspectCommand( secretInspectFunc: tc.secretInspectFunc,
test.NewFakeCliWithOutput(&fakeClient{ })
secretInspectFunc: tc.secretInspectFunc, cmd := newSecretInspectCommand(cli)
}, buf),
)
cmd.SetArgs(tc.args) cmd.SetArgs(tc.args)
cmd.Flags().Set("format", tc.format) cmd.Flags().Set("format", tc.format)
assert.NoError(t, cmd.Execute()) assert.NoError(t, cmd.Execute())
actual := buf.String() golden.Assert(t, cli.OutBuffer().String(), fmt.Sprintf("secret-inspect-with-format.%s.golden", tc.name))
expected := golden.Get(t, []byte(actual), fmt.Sprintf("secret-inspect-with-format.%s.golden", tc.name))
testutil.EqualNormalizedString(t, testutil.RemoveSpace, actual, string(expected))
} }
} }
@ -171,16 +161,13 @@ func TestSecretInspectPretty(t *testing.T) {
}, },
} }
for _, tc := range testCases { for _, tc := range testCases {
buf := new(bytes.Buffer) cli := test.NewFakeCli(&fakeClient{
cmd := newSecretInspectCommand( secretInspectFunc: tc.secretInspectFunc,
test.NewFakeCliWithOutput(&fakeClient{ })
secretInspectFunc: tc.secretInspectFunc, cmd := newSecretInspectCommand(cli)
}, buf))
cmd.SetArgs([]string{"secretID"}) cmd.SetArgs([]string{"secretID"})
cmd.Flags().Set("pretty", "true") cmd.Flags().Set("pretty", "true")
assert.NoError(t, cmd.Execute()) assert.NoError(t, cmd.Execute())
actual := buf.String() golden.Assert(t, cli.OutBuffer().String(), fmt.Sprintf("secret-inspect-pretty.%s.golden", tc.name))
expected := golden.Get(t, []byte(actual), fmt.Sprintf("secret-inspect-pretty.%s.golden", tc.name))
testutil.EqualNormalizedString(t, testutil.RemoveSpace, actual, string(expected))
} }
} }

View File

@ -14,7 +14,7 @@ import (
// Import builders to get the builder function as package function // Import builders to get the builder function as package function
. "github.com/docker/cli/cli/internal/test/builders" . "github.com/docker/cli/cli/internal/test/builders"
"github.com/docker/docker/pkg/testutil" "github.com/docker/docker/pkg/testutil"
"github.com/docker/docker/pkg/testutil/golden" "github.com/gotestyourself/gotestyourself/golden"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
) )
@ -36,11 +36,10 @@ func TestSecretListErrors(t *testing.T) {
}, },
} }
for _, tc := range testCases { for _, tc := range testCases {
buf := new(bytes.Buffer)
cmd := newSecretListCommand( cmd := newSecretListCommand(
test.NewFakeCliWithOutput(&fakeClient{ test.NewFakeCli(&fakeClient{
secretListFunc: tc.secretListFunc, secretListFunc: tc.secretListFunc,
}, buf), }),
) )
cmd.SetArgs(tc.args) cmd.SetArgs(tc.args)
cmd.SetOutput(ioutil.Discard) cmd.SetOutput(ioutil.Discard)
@ -50,7 +49,7 @@ func TestSecretListErrors(t *testing.T) {
func TestSecretList(t *testing.T) { func TestSecretList(t *testing.T) {
buf := new(bytes.Buffer) buf := new(bytes.Buffer)
cli := test.NewFakeCliWithOutput(&fakeClient{ cli := test.NewFakeCli(&fakeClient{
secretListFunc: func(options types.SecretListOptions) ([]swarm.Secret, error) { secretListFunc: func(options types.SecretListOptions) ([]swarm.Secret, error) {
return []swarm.Secret{ return []swarm.Secret{
*Secret(SecretID("ID-foo"), *Secret(SecretID("ID-foo"),
@ -67,18 +66,15 @@ func TestSecretList(t *testing.T) {
), ),
}, nil }, nil
}, },
}, buf) })
cmd := newSecretListCommand(cli) cmd := newSecretListCommand(cli)
cmd.SetOutput(buf) cmd.SetOutput(buf)
assert.NoError(t, cmd.Execute()) assert.NoError(t, cmd.Execute())
actual := buf.String() golden.Assert(t, cli.OutBuffer().String(), "secret-list.golden")
expected := golden.Get(t, []byte(actual), "secret-list.golden")
testutil.EqualNormalizedString(t, testutil.RemoveSpace, actual, string(expected))
} }
func TestSecretListWithQuietOption(t *testing.T) { func TestSecretListWithQuietOption(t *testing.T) {
buf := new(bytes.Buffer) cli := test.NewFakeCli(&fakeClient{
cli := test.NewFakeCliWithOutput(&fakeClient{
secretListFunc: func(options types.SecretListOptions) ([]swarm.Secret, error) { secretListFunc: func(options types.SecretListOptions) ([]swarm.Secret, error) {
return []swarm.Secret{ return []swarm.Secret{
*Secret(SecretID("ID-foo"), SecretName("foo")), *Secret(SecretID("ID-foo"), SecretName("foo")),
@ -87,18 +83,15 @@ func TestSecretListWithQuietOption(t *testing.T) {
})), })),
}, nil }, nil
}, },
}, buf) })
cmd := newSecretListCommand(cli) cmd := newSecretListCommand(cli)
cmd.Flags().Set("quiet", "true") cmd.Flags().Set("quiet", "true")
assert.NoError(t, cmd.Execute()) assert.NoError(t, cmd.Execute())
actual := buf.String() golden.Assert(t, cli.OutBuffer().String(), "secret-list-with-quiet-option.golden")
expected := golden.Get(t, []byte(actual), "secret-list-with-quiet-option.golden")
testutil.EqualNormalizedString(t, testutil.RemoveSpace, actual, string(expected))
} }
func TestSecretListWithConfigFormat(t *testing.T) { func TestSecretListWithConfigFormat(t *testing.T) {
buf := new(bytes.Buffer) cli := test.NewFakeCli(&fakeClient{
cli := test.NewFakeCliWithOutput(&fakeClient{
secretListFunc: func(options types.SecretListOptions) ([]swarm.Secret, error) { secretListFunc: func(options types.SecretListOptions) ([]swarm.Secret, error) {
return []swarm.Secret{ return []swarm.Secret{
*Secret(SecretID("ID-foo"), SecretName("foo")), *Secret(SecretID("ID-foo"), SecretName("foo")),
@ -107,20 +100,17 @@ func TestSecretListWithConfigFormat(t *testing.T) {
})), })),
}, nil }, nil
}, },
}, buf) })
cli.SetConfigFile(&configfile.ConfigFile{ cli.SetConfigFile(&configfile.ConfigFile{
SecretFormat: "{{ .Name }} {{ .Labels }}", SecretFormat: "{{ .Name }} {{ .Labels }}",
}) })
cmd := newSecretListCommand(cli) cmd := newSecretListCommand(cli)
assert.NoError(t, cmd.Execute()) assert.NoError(t, cmd.Execute())
actual := buf.String() golden.Assert(t, cli.OutBuffer().String(), "secret-list-with-config-format.golden")
expected := golden.Get(t, []byte(actual), "secret-list-with-config-format.golden")
testutil.EqualNormalizedString(t, testutil.RemoveSpace, actual, string(expected))
} }
func TestSecretListWithFormat(t *testing.T) { func TestSecretListWithFormat(t *testing.T) {
buf := new(bytes.Buffer) cli := test.NewFakeCli(&fakeClient{
cli := test.NewFakeCliWithOutput(&fakeClient{
secretListFunc: func(options types.SecretListOptions) ([]swarm.Secret, error) { secretListFunc: func(options types.SecretListOptions) ([]swarm.Secret, error) {
return []swarm.Secret{ return []swarm.Secret{
*Secret(SecretID("ID-foo"), SecretName("foo")), *Secret(SecretID("ID-foo"), SecretName("foo")),
@ -129,18 +119,15 @@ func TestSecretListWithFormat(t *testing.T) {
})), })),
}, nil }, nil
}, },
}, buf) })
cmd := newSecretListCommand(cli) cmd := newSecretListCommand(cli)
cmd.Flags().Set("format", "{{ .Name }} {{ .Labels }}") cmd.Flags().Set("format", "{{ .Name }} {{ .Labels }}")
assert.NoError(t, cmd.Execute()) assert.NoError(t, cmd.Execute())
actual := buf.String() golden.Assert(t, cli.OutBuffer().String(), "secret-list-with-format.golden")
expected := golden.Get(t, []byte(actual), "secret-list-with-format.golden")
testutil.EqualNormalizedString(t, testutil.RemoveSpace, actual, string(expected))
} }
func TestSecretListWithFilter(t *testing.T) { func TestSecretListWithFilter(t *testing.T) {
buf := new(bytes.Buffer) cli := test.NewFakeCli(&fakeClient{
cli := test.NewFakeCliWithOutput(&fakeClient{
secretListFunc: func(options types.SecretListOptions) ([]swarm.Secret, error) { secretListFunc: func(options types.SecretListOptions) ([]swarm.Secret, error) {
assert.Equal(t, "foo", options.Filters.Get("name")[0], "foo") assert.Equal(t, "foo", options.Filters.Get("name")[0], "foo")
assert.Equal(t, "lbl1=Label-bar", options.Filters.Get("label")[0]) assert.Equal(t, "lbl1=Label-bar", options.Filters.Get("label")[0])
@ -159,12 +146,10 @@ func TestSecretListWithFilter(t *testing.T) {
), ),
}, nil }, nil
}, },
}, buf) })
cmd := newSecretListCommand(cli) cmd := newSecretListCommand(cli)
cmd.Flags().Set("filter", "name=foo") cmd.Flags().Set("filter", "name=foo")
cmd.Flags().Set("filter", "label=lbl1=Label-bar") cmd.Flags().Set("filter", "label=lbl1=Label-bar")
assert.NoError(t, cmd.Execute()) assert.NoError(t, cmd.Execute())
actual := buf.String() golden.Assert(t, cli.OutBuffer().String(), "secret-list-with-filter.golden")
expected := golden.Get(t, []byte(actual), "secret-list-with-filter.golden")
testutil.EqualNormalizedString(t, testutil.RemoveSpace, actual, string(expected))
} }

View File

@ -1,7 +1,6 @@
package secret package secret
import ( import (
"bytes"
"io/ioutil" "io/ioutil"
"strings" "strings"
"testing" "testing"
@ -31,11 +30,10 @@ func TestSecretRemoveErrors(t *testing.T) {
}, },
} }
for _, tc := range testCases { for _, tc := range testCases {
buf := new(bytes.Buffer)
cmd := newSecretRemoveCommand( cmd := newSecretRemoveCommand(
test.NewFakeCliWithOutput(&fakeClient{ test.NewFakeCli(&fakeClient{
secretRemoveFunc: tc.secretRemoveFunc, secretRemoveFunc: tc.secretRemoveFunc,
}, buf), }),
) )
cmd.SetArgs(tc.args) cmd.SetArgs(tc.args)
cmd.SetOutput(ioutil.Discard) cmd.SetOutput(ioutil.Discard)
@ -45,27 +43,25 @@ func TestSecretRemoveErrors(t *testing.T) {
func TestSecretRemoveWithName(t *testing.T) { func TestSecretRemoveWithName(t *testing.T) {
names := []string{"foo", "bar"} names := []string{"foo", "bar"}
buf := new(bytes.Buffer)
var removedSecrets []string var removedSecrets []string
cli := test.NewFakeCliWithOutput(&fakeClient{ cli := test.NewFakeCli(&fakeClient{
secretRemoveFunc: func(name string) error { secretRemoveFunc: func(name string) error {
removedSecrets = append(removedSecrets, name) removedSecrets = append(removedSecrets, name)
return nil return nil
}, },
}, buf) })
cmd := newSecretRemoveCommand(cli) cmd := newSecretRemoveCommand(cli)
cmd.SetArgs(names) cmd.SetArgs(names)
assert.NoError(t, cmd.Execute()) assert.NoError(t, cmd.Execute())
assert.Equal(t, names, strings.Split(strings.TrimSpace(buf.String()), "\n")) assert.Equal(t, names, strings.Split(strings.TrimSpace(cli.OutBuffer().String()), "\n"))
assert.Equal(t, names, removedSecrets) assert.Equal(t, names, removedSecrets)
} }
func TestSecretRemoveContinueAfterError(t *testing.T) { func TestSecretRemoveContinueAfterError(t *testing.T) {
names := []string{"foo", "bar"} names := []string{"foo", "bar"}
buf := new(bytes.Buffer)
var removedSecrets []string var removedSecrets []string
cli := test.NewFakeCliWithOutput(&fakeClient{ cli := test.NewFakeCli(&fakeClient{
secretRemoveFunc: func(name string) error { secretRemoveFunc: func(name string) error {
removedSecrets = append(removedSecrets, name) removedSecrets = append(removedSecrets, name)
if name == "foo" { if name == "foo" {
@ -73,7 +69,7 @@ func TestSecretRemoveContinueAfterError(t *testing.T) {
} }
return nil return nil
}, },
}, buf) })
cmd := newSecretRemoveCommand(cli) cmd := newSecretRemoveCommand(cli)
cmd.SetOutput(ioutil.Discard) cmd.SetOutput(ioutil.Discard)

View File

@ -1,6 +1,6 @@
ID: secretID ID: secretID
Name: secretName Name: secretName
Labels: Labels:
- lbl1=value1 - lbl1=value1
Created at: 0001-01-01 00:00:00+0000 utc Created at: 0001-01-01 00:00:00 +0000 utc
Updated at: 0001-01-01 00:00:00+0000 utc Updated at: 0001-01-01 00:00:00 +0000 utc

View File

@ -1,7 +1,7 @@
[ [
{ {
"ID": "ID-foo", "ID": "ID-foo",
"Version": {}, "Version": {},
"CreatedAt": "0001-01-01T00:00:00Z", "CreatedAt": "0001-01-01T00:00:00Z",
"UpdatedAt": "0001-01-01T00:00:00Z", "UpdatedAt": "0001-01-01T00:00:00Z",
"Spec": { "Spec": {
@ -13,7 +13,7 @@
}, },
{ {
"ID": "ID-bar", "ID": "ID-bar",
"Version": {}, "Version": {},
"CreatedAt": "0001-01-01T00:00:00Z", "CreatedAt": "0001-01-01T00:00:00Z",
"UpdatedAt": "0001-01-01T00:00:00Z", "UpdatedAt": "0001-01-01T00:00:00Z",
"Spec": { "Spec": {

View File

@ -1,9 +1,9 @@
[ [
{ {
"ID": "ID-foo", "ID": "ID-foo",
"Version": {}, "Version": {},
"CreatedAt": "0001-01-01T00:00:00Z", "CreatedAt": "0001-01-01T00:00:00Z",
"UpdatedAt": "0001-01-01T00:00:00Z", "UpdatedAt": "0001-01-01T00:00:00Z",
"Spec": { "Spec": {
"Name": "foo", "Name": "foo",
"Labels": null "Labels": null

View File

@ -3,14 +3,12 @@ package service
import ( import (
"testing" "testing"
"golang.org/x/net/context"
"github.com/docker/cli/cli/internal/test" "github.com/docker/cli/cli/internal/test"
"github.com/docker/docker/api/types" "github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/swarm" "github.com/docker/docker/api/types/swarm"
"github.com/docker/docker/pkg/testutil" "github.com/gotestyourself/gotestyourself/golden"
"github.com/docker/docker/pkg/testutil/golden"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"golang.org/x/net/context"
) )
func TestServiceListOrder(t *testing.T) { func TestServiceListOrder(t *testing.T) {
@ -26,7 +24,5 @@ func TestServiceListOrder(t *testing.T) {
cmd := newListCommand(cli) cmd := newListCommand(cli)
cmd.Flags().Set("format", "{{.Name}}") cmd.Flags().Set("format", "{{.Name}}")
assert.NoError(t, cmd.Execute()) assert.NoError(t, cmd.Execute())
actual := cli.OutBuffer().String() golden.Assert(t, cli.OutBuffer().String(), "service-list-sort.golden")
expected := golden.Get(t, []byte(actual), "service-list-sort.golden")
testutil.EqualNormalizedString(t, testutil.RemoveSpace, actual, string(expected))
} }

View File

@ -3,8 +3,6 @@ package service
import ( import (
"testing" "testing"
"bytes"
"github.com/docker/cli/cli/internal/test" "github.com/docker/cli/cli/internal/test"
"github.com/docker/cli/opts" "github.com/docker/cli/opts"
"github.com/docker/docker/api/types" "github.com/docker/docker/api/types"
@ -82,8 +80,7 @@ func TestRunPSWarnsOnNotFound(t *testing.T) {
}, },
} }
out := new(bytes.Buffer) cli := test.NewFakeCli(client)
cli := test.NewFakeCliWithOutput(client, out)
options := psOptions{ options := psOptions{
services: []string{"foo", "bar"}, services: []string{"foo", "bar"},
filter: opts.NewFilterOpt(), filter: opts.NewFilterOpt(),

View File

@ -8,7 +8,7 @@ import (
"github.com/docker/cli/cli/internal/test/network" "github.com/docker/cli/cli/internal/test/network"
"github.com/docker/docker/api/types" "github.com/docker/docker/api/types"
"github.com/docker/docker/pkg/testutil" "github.com/docker/docker/pkg/testutil"
"github.com/docker/docker/pkg/testutil/tempfile" "github.com/gotestyourself/gotestyourself/fs"
"github.com/pkg/errors" "github.com/pkg/errors"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
@ -22,12 +22,12 @@ services:
foo: foo:
image: alpine:3.5 image: alpine:3.5
` `
file := tempfile.NewTempFile(t, "test-get-config-details", content) file := fs.NewFile(t, "test-get-config-details", fs.WithContent(content))
defer file.Remove() defer file.Remove()
details, err := getConfigDetails(file.Name()) details, err := getConfigDetails(file.Path())
require.NoError(t, err) require.NoError(t, err)
assert.Equal(t, filepath.Dir(file.Name()), details.WorkingDir) assert.Equal(t, filepath.Dir(file.Path()), details.WorkingDir)
assert.Len(t, details.ConfigFiles, 1) assert.Len(t, details.ConfigFiles, 1)
assert.Len(t, details.Environment, len(os.Environ())) assert.Len(t, details.Environment, len(os.Environ()))
} }

View File

@ -1,7 +1,6 @@
package stack package stack
import ( import (
"bytes"
"io/ioutil" "io/ioutil"
"testing" "testing"
@ -11,7 +10,7 @@ import (
"github.com/docker/docker/api/types" "github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/swarm" "github.com/docker/docker/api/types/swarm"
"github.com/docker/docker/pkg/testutil" "github.com/docker/docker/pkg/testutil"
"github.com/docker/docker/pkg/testutil/golden" "github.com/gotestyourself/gotestyourself/golden"
"github.com/pkg/errors" "github.com/pkg/errors"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
) )
@ -61,8 +60,7 @@ func TestListErrors(t *testing.T) {
} }
func TestListWithFormat(t *testing.T) { func TestListWithFormat(t *testing.T) {
buf := new(bytes.Buffer) cli := test.NewFakeCli(&fakeClient{
cmd := newListCommand(test.NewFakeCliWithOutput(&fakeClient{
serviceListFunc: func(options types.ServiceListOptions) ([]swarm.Service, error) { serviceListFunc: func(options types.ServiceListOptions) ([]swarm.Service, error) {
return []swarm.Service{ return []swarm.Service{
*Service( *Service(
@ -71,17 +69,15 @@ func TestListWithFormat(t *testing.T) {
}), }),
)}, nil )}, nil
}, },
}, buf)) })
cmd := newListCommand(cli)
cmd.Flags().Set("format", "{{ .Name }}") cmd.Flags().Set("format", "{{ .Name }}")
assert.NoError(t, cmd.Execute()) assert.NoError(t, cmd.Execute())
actual := buf.String() golden.Assert(t, cli.OutBuffer().String(), "stack-list-with-format.golden")
expected := golden.Get(t, []byte(actual), "stack-list-with-format.golden")
testutil.EqualNormalizedString(t, testutil.RemoveSpace, actual, string(expected))
} }
func TestListWithoutFormat(t *testing.T) { func TestListWithoutFormat(t *testing.T) {
buf := new(bytes.Buffer) cli := test.NewFakeCli(&fakeClient{
cmd := newListCommand(test.NewFakeCliWithOutput(&fakeClient{
serviceListFunc: func(options types.ServiceListOptions) ([]swarm.Service, error) { serviceListFunc: func(options types.ServiceListOptions) ([]swarm.Service, error) {
return []swarm.Service{ return []swarm.Service{
*Service( *Service(
@ -90,11 +86,10 @@ func TestListWithoutFormat(t *testing.T) {
}), }),
)}, nil )}, nil
}, },
}, buf)) })
cmd := newListCommand(cli)
assert.NoError(t, cmd.Execute()) assert.NoError(t, cmd.Execute())
actual := buf.String() golden.Assert(t, cli.OutBuffer().String(), "stack-list-without-format.golden")
expected := golden.Get(t, []byte(actual), "stack-list-without-format.golden")
testutil.EqualNormalizedString(t, testutil.RemoveSpace, actual, string(expected))
} }
func TestListOrder(t *testing.T) { func TestListOrder(t *testing.T) {
@ -140,15 +135,13 @@ func TestListOrder(t *testing.T) {
} }
for _, uc := range usecases { for _, uc := range usecases {
buf := new(bytes.Buffer) cli := test.NewFakeCli(&fakeClient{
cmd := newListCommand(test.NewFakeCliWithOutput(&fakeClient{
serviceListFunc: func(options types.ServiceListOptions) ([]swarm.Service, error) { serviceListFunc: func(options types.ServiceListOptions) ([]swarm.Service, error) {
return uc.swarmServices, nil return uc.swarmServices, nil
}, },
}, buf)) })
cmd := newListCommand(cli)
assert.NoError(t, cmd.Execute()) assert.NoError(t, cmd.Execute())
actual := buf.String() golden.Assert(t, cli.OutBuffer().String(), uc.golden)
expected := golden.Get(t, []byte(actual), uc.golden)
testutil.EqualNormalizedString(t, testutil.RemoveSpace, actual, string(expected))
} }
} }

View File

@ -12,7 +12,7 @@ import (
"github.com/docker/docker/api/types" "github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/swarm" "github.com/docker/docker/api/types/swarm"
"github.com/docker/docker/pkg/testutil" "github.com/docker/docker/pkg/testutil"
"github.com/docker/docker/pkg/testutil/golden" "github.com/gotestyourself/gotestyourself/golden"
"github.com/pkg/errors" "github.com/pkg/errors"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
) )
@ -75,9 +75,7 @@ func TestStackPsWithQuietOption(t *testing.T) {
cmd.SetArgs([]string{"foo"}) cmd.SetArgs([]string{"foo"})
cmd.Flags().Set("quiet", "true") cmd.Flags().Set("quiet", "true")
assert.NoError(t, cmd.Execute()) assert.NoError(t, cmd.Execute())
actual := cli.OutBuffer().String() golden.Assert(t, cli.OutBuffer().String(), "stack-ps-with-quiet-option.golden")
expected := golden.Get(t, []byte(actual), "stack-ps-with-quiet-option.golden")
testutil.EqualNormalizedString(t, testutil.RemoveSpace, actual, string(expected))
} }
@ -92,9 +90,7 @@ func TestStackPsWithNoTruncOption(t *testing.T) {
cmd.Flags().Set("no-trunc", "true") cmd.Flags().Set("no-trunc", "true")
cmd.Flags().Set("format", "{{ .ID }}") cmd.Flags().Set("format", "{{ .ID }}")
assert.NoError(t, cmd.Execute()) assert.NoError(t, cmd.Execute())
actual := cli.OutBuffer().String() golden.Assert(t, cli.OutBuffer().String(), "stack-ps-with-no-trunc-option.golden")
expected := golden.Get(t, []byte(actual), "stack-ps-with-no-trunc-option.golden")
testutil.EqualNormalizedString(t, testutil.RemoveSpace, actual, string(expected))
} }
func TestStackPsWithNoResolveOption(t *testing.T) { func TestStackPsWithNoResolveOption(t *testing.T) {
@ -113,9 +109,7 @@ func TestStackPsWithNoResolveOption(t *testing.T) {
cmd.Flags().Set("no-resolve", "true") cmd.Flags().Set("no-resolve", "true")
cmd.Flags().Set("format", "{{ .Node }}") cmd.Flags().Set("format", "{{ .Node }}")
assert.NoError(t, cmd.Execute()) assert.NoError(t, cmd.Execute())
actual := cli.OutBuffer().String() golden.Assert(t, cli.OutBuffer().String(), "stack-ps-with-no-resolve-option.golden")
expected := golden.Get(t, []byte(actual), "stack-ps-with-no-resolve-option.golden")
testutil.EqualNormalizedString(t, testutil.RemoveSpace, actual, string(expected))
} }
func TestStackPsWithFormat(t *testing.T) { func TestStackPsWithFormat(t *testing.T) {
@ -128,9 +122,7 @@ func TestStackPsWithFormat(t *testing.T) {
cmd.SetArgs([]string{"foo"}) cmd.SetArgs([]string{"foo"})
cmd.Flags().Set("format", "{{ .Name }}") cmd.Flags().Set("format", "{{ .Name }}")
assert.NoError(t, cmd.Execute()) assert.NoError(t, cmd.Execute())
actual := cli.OutBuffer().String() golden.Assert(t, cli.OutBuffer().String(), "stack-ps-with-format.golden")
expected := golden.Get(t, []byte(actual), "stack-ps-with-format.golden")
testutil.EqualNormalizedString(t, testutil.RemoveSpace, actual, string(expected))
} }
func TestStackPsWithConfigFormat(t *testing.T) { func TestStackPsWithConfigFormat(t *testing.T) {
@ -145,9 +137,7 @@ func TestStackPsWithConfigFormat(t *testing.T) {
cmd := newPsCommand(cli) cmd := newPsCommand(cli)
cmd.SetArgs([]string{"foo"}) cmd.SetArgs([]string{"foo"})
assert.NoError(t, cmd.Execute()) assert.NoError(t, cmd.Execute())
actual := cli.OutBuffer().String() golden.Assert(t, cli.OutBuffer().String(), "stack-ps-with-config-format.golden")
expected := golden.Get(t, []byte(actual), "stack-ps-with-config-format.golden")
testutil.EqualNormalizedString(t, testutil.RemoveSpace, actual, string(expected))
} }
func TestStackPsWithoutFormat(t *testing.T) { func TestStackPsWithoutFormat(t *testing.T) {
@ -169,7 +159,5 @@ func TestStackPsWithoutFormat(t *testing.T) {
cmd := newPsCommand(cli) cmd := newPsCommand(cli)
cmd.SetArgs([]string{"foo"}) cmd.SetArgs([]string{"foo"})
assert.NoError(t, cmd.Execute()) assert.NoError(t, cmd.Execute())
actual := cli.OutBuffer().String() golden.Assert(t, cli.OutBuffer().String(), "stack-ps-without-format.golden")
expected := golden.Get(t, []byte(actual), "stack-ps-without-format.golden")
testutil.EqualNormalizedString(t, testutil.RemoveSpace, actual, string(expected))
} }

View File

@ -11,7 +11,7 @@ import (
"github.com/docker/docker/api/types" "github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/swarm" "github.com/docker/docker/api/types/swarm"
"github.com/docker/docker/pkg/testutil" "github.com/docker/docker/pkg/testutil"
"github.com/docker/docker/pkg/testutil/golden" "github.com/gotestyourself/gotestyourself/golden"
"github.com/pkg/errors" "github.com/pkg/errors"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
) )
@ -103,9 +103,7 @@ func TestStackServicesWithQuietOption(t *testing.T) {
cmd.Flags().Set("quiet", "true") cmd.Flags().Set("quiet", "true")
cmd.SetArgs([]string{"foo"}) cmd.SetArgs([]string{"foo"})
assert.NoError(t, cmd.Execute()) assert.NoError(t, cmd.Execute())
actual := cli.OutBuffer().String() golden.Assert(t, cli.OutBuffer().String(), "stack-services-with-quiet-option.golden")
expected := golden.Get(t, []byte(actual), "stack-services-with-quiet-option.golden")
testutil.EqualNormalizedString(t, testutil.RemoveSpace, actual, string(expected))
} }
func TestStackServicesWithFormat(t *testing.T) { func TestStackServicesWithFormat(t *testing.T) {
@ -120,9 +118,7 @@ func TestStackServicesWithFormat(t *testing.T) {
cmd.SetArgs([]string{"foo"}) cmd.SetArgs([]string{"foo"})
cmd.Flags().Set("format", "{{ .Name }}") cmd.Flags().Set("format", "{{ .Name }}")
assert.NoError(t, cmd.Execute()) assert.NoError(t, cmd.Execute())
actual := cli.OutBuffer().String() golden.Assert(t, cli.OutBuffer().String(), "stack-services-with-format.golden")
expected := golden.Get(t, []byte(actual), "stack-services-with-format.golden")
testutil.EqualNormalizedString(t, testutil.RemoveSpace, actual, string(expected))
} }
func TestStackServicesWithConfigFormat(t *testing.T) { func TestStackServicesWithConfigFormat(t *testing.T) {
@ -139,9 +135,7 @@ func TestStackServicesWithConfigFormat(t *testing.T) {
cmd := newServicesCommand(cli) cmd := newServicesCommand(cli)
cmd.SetArgs([]string{"foo"}) cmd.SetArgs([]string{"foo"})
assert.NoError(t, cmd.Execute()) assert.NoError(t, cmd.Execute())
actual := cli.OutBuffer().String() golden.Assert(t, cli.OutBuffer().String(), "stack-services-with-config-format.golden")
expected := golden.Get(t, []byte(actual), "stack-services-with-config-format.golden")
testutil.EqualNormalizedString(t, testutil.RemoveSpace, actual, string(expected))
} }
func TestStackServicesWithoutFormat(t *testing.T) { func TestStackServicesWithoutFormat(t *testing.T) {
@ -164,7 +158,5 @@ func TestStackServicesWithoutFormat(t *testing.T) {
cmd := newServicesCommand(cli) cmd := newServicesCommand(cli)
cmd.SetArgs([]string{"foo"}) cmd.SetArgs([]string{"foo"})
assert.NoError(t, cmd.Execute()) assert.NoError(t, cmd.Execute())
actual := cli.OutBuffer().String() golden.Assert(t, cli.OutBuffer().String(), "stack-services-without-format.golden")
expected := golden.Get(t, []byte(actual), "stack-services-without-format.golden")
testutil.EqualNormalizedString(t, testutil.RemoveSpace, actual, string(expected))
} }

View File

@ -1,4 +1,4 @@
NAME SERVICES NAME SERVICES
service-name-1-foo 1 service-name-1-foo 1
service-name-2-foo 1 service-name-2-foo 1
service-name-10-foo 1 service-name-10-foo 1

View File

@ -1,2 +1,2 @@
ID NAME IMAGE NODE DESIRED STATE CURRENT STATE ERROR PORTS ID NAME IMAGE NODE DESIRED STATE CURRENT STATE ERROR PORTS
id-foo service-id-foo.1 myimage:mytag node-name-bar Ready Failed 2 hours ago id-foo service-id-foo.1 myimage:mytag node-name-bar Ready Failed 2 hours ago

View File

@ -1,7 +1,6 @@
package swarm package swarm
import ( import (
"bytes"
"fmt" "fmt"
"io/ioutil" "io/ioutil"
"testing" "testing"
@ -9,8 +8,7 @@ import (
"github.com/docker/cli/cli/internal/test" "github.com/docker/cli/cli/internal/test"
"github.com/docker/docker/api/types" "github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/swarm" "github.com/docker/docker/api/types/swarm"
"github.com/docker/docker/pkg/testutil" "github.com/gotestyourself/gotestyourself/golden"
"github.com/docker/docker/pkg/testutil/golden"
"github.com/pkg/errors" "github.com/pkg/errors"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
) )
@ -65,14 +63,13 @@ func TestSwarmInitErrorOnAPIFailure(t *testing.T) {
}, },
} }
for _, tc := range testCases { for _, tc := range testCases {
buf := new(bytes.Buffer)
cmd := newInitCommand( cmd := newInitCommand(
test.NewFakeCliWithOutput(&fakeClient{ test.NewFakeCli(&fakeClient{
swarmInitFunc: tc.swarmInitFunc, swarmInitFunc: tc.swarmInitFunc,
swarmInspectFunc: tc.swarmInspectFunc, swarmInspectFunc: tc.swarmInspectFunc,
swarmGetUnlockKeyFunc: tc.swarmGetUnlockKeyFunc, swarmGetUnlockKeyFunc: tc.swarmGetUnlockKeyFunc,
nodeInspectFunc: tc.nodeInspectFunc, nodeInspectFunc: tc.nodeInspectFunc,
}, buf)) }))
for key, value := range tc.flags { for key, value := range tc.flags {
cmd.Flags().Set(key, value) cmd.Flags().Set(key, value)
} }
@ -112,20 +109,17 @@ func TestSwarmInit(t *testing.T) {
}, },
} }
for _, tc := range testCases { for _, tc := range testCases {
buf := new(bytes.Buffer) cli := test.NewFakeCli(&fakeClient{
cmd := newInitCommand( swarmInitFunc: tc.swarmInitFunc,
test.NewFakeCliWithOutput(&fakeClient{ swarmInspectFunc: tc.swarmInspectFunc,
swarmInitFunc: tc.swarmInitFunc, swarmGetUnlockKeyFunc: tc.swarmGetUnlockKeyFunc,
swarmInspectFunc: tc.swarmInspectFunc, nodeInspectFunc: tc.nodeInspectFunc,
swarmGetUnlockKeyFunc: tc.swarmGetUnlockKeyFunc, })
nodeInspectFunc: tc.nodeInspectFunc, cmd := newInitCommand(cli)
}, buf))
for key, value := range tc.flags { for key, value := range tc.flags {
cmd.Flags().Set(key, value) cmd.Flags().Set(key, value)
} }
assert.NoError(t, cmd.Execute()) assert.NoError(t, cmd.Execute())
actual := buf.String() golden.Assert(t, cli.OutBuffer().String(), fmt.Sprintf("init-%s.golden", tc.name))
expected := golden.Get(t, []byte(actual), fmt.Sprintf("init-%s.golden", tc.name))
testutil.EqualNormalizedString(t, testutil.RemoveSpace, actual, string(expected))
} }
} }

View File

@ -1,7 +1,6 @@
package swarm package swarm
import ( import (
"bytes"
"io/ioutil" "io/ioutil"
"strings" "strings"
"testing" "testing"
@ -49,12 +48,11 @@ func TestSwarmJoinErrors(t *testing.T) {
}, },
} }
for _, tc := range testCases { for _, tc := range testCases {
buf := new(bytes.Buffer)
cmd := newJoinCommand( cmd := newJoinCommand(
test.NewFakeCliWithOutput(&fakeClient{ test.NewFakeCli(&fakeClient{
swarmJoinFunc: tc.swarmJoinFunc, swarmJoinFunc: tc.swarmJoinFunc,
infoFunc: tc.infoFunc, infoFunc: tc.infoFunc,
}, buf)) }))
cmd.SetArgs(tc.args) cmd.SetArgs(tc.args)
cmd.SetOutput(ioutil.Discard) cmd.SetOutput(ioutil.Discard)
testutil.ErrorContains(t, cmd.Execute(), tc.expectedError) testutil.ErrorContains(t, cmd.Execute(), tc.expectedError)
@ -91,13 +89,12 @@ func TestSwarmJoin(t *testing.T) {
}, },
} }
for _, tc := range testCases { for _, tc := range testCases {
buf := new(bytes.Buffer) cli := test.NewFakeCli(&fakeClient{
cmd := newJoinCommand( infoFunc: tc.infoFunc,
test.NewFakeCliWithOutput(&fakeClient{ })
infoFunc: tc.infoFunc, cmd := newJoinCommand(cli)
}, buf))
cmd.SetArgs([]string{"remote"}) cmd.SetArgs([]string{"remote"})
assert.NoError(t, cmd.Execute()) assert.NoError(t, cmd.Execute())
assert.Equal(t, strings.TrimSpace(buf.String()), tc.expected) assert.Equal(t, strings.TrimSpace(cli.OutBuffer().String()), tc.expected)
} }
} }

View File

@ -1,7 +1,6 @@
package swarm package swarm
import ( import (
"bytes"
"fmt" "fmt"
"io/ioutil" "io/ioutil"
"testing" "testing"
@ -13,7 +12,7 @@ import (
// Import builders to get the builder function as package function // Import builders to get the builder function as package function
. "github.com/docker/cli/cli/internal/test/builders" . "github.com/docker/cli/cli/internal/test/builders"
"github.com/docker/docker/pkg/testutil" "github.com/docker/docker/pkg/testutil"
"github.com/docker/docker/pkg/testutil/golden" "github.com/gotestyourself/gotestyourself/golden"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
) )
@ -90,14 +89,13 @@ func TestSwarmJoinTokenErrors(t *testing.T) {
}, },
} }
for _, tc := range testCases { for _, tc := range testCases {
buf := new(bytes.Buffer) cli := test.NewFakeCli(&fakeClient{
cmd := newJoinTokenCommand( swarmInspectFunc: tc.swarmInspectFunc,
test.NewFakeCliWithOutput(&fakeClient{ swarmUpdateFunc: tc.swarmUpdateFunc,
swarmInspectFunc: tc.swarmInspectFunc, infoFunc: tc.infoFunc,
swarmUpdateFunc: tc.swarmUpdateFunc, nodeInspectFunc: tc.nodeInspectFunc,
infoFunc: tc.infoFunc, })
nodeInspectFunc: tc.nodeInspectFunc, cmd := newJoinTokenCommand(cli)
}, buf))
cmd.SetArgs(tc.args) cmd.SetArgs(tc.args)
for key, value := range tc.flags { for key, value := range tc.flags {
cmd.Flags().Set(key, value) cmd.Flags().Set(key, value)
@ -198,20 +196,17 @@ func TestSwarmJoinToken(t *testing.T) {
}, },
} }
for _, tc := range testCases { for _, tc := range testCases {
buf := new(bytes.Buffer) cli := test.NewFakeCli(&fakeClient{
cmd := newJoinTokenCommand( swarmInspectFunc: tc.swarmInspectFunc,
test.NewFakeCliWithOutput(&fakeClient{ infoFunc: tc.infoFunc,
swarmInspectFunc: tc.swarmInspectFunc, nodeInspectFunc: tc.nodeInspectFunc,
infoFunc: tc.infoFunc, })
nodeInspectFunc: tc.nodeInspectFunc, cmd := newJoinTokenCommand(cli)
}, buf))
cmd.SetArgs(tc.args) cmd.SetArgs(tc.args)
for key, value := range tc.flags { for key, value := range tc.flags {
cmd.Flags().Set(key, value) cmd.Flags().Set(key, value)
} }
assert.NoError(t, cmd.Execute()) assert.NoError(t, cmd.Execute())
actual := buf.String() golden.Assert(t, cli.OutBuffer().String(), fmt.Sprintf("jointoken-%s.golden", tc.name))
expected := golden.Get(t, []byte(actual), fmt.Sprintf("jointoken-%s.golden", tc.name))
testutil.EqualNormalizedString(t, testutil.RemoveSpace, actual, string(expected))
} }
} }

View File

@ -3,3 +3,4 @@ Successfully rotated manager join token.
To add a manager to this swarm, run the following command: To add a manager to this swarm, run the following command:
docker swarm join --token manager-join-token 127.0.0.1 docker swarm join --token manager-join-token 127.0.0.1

View File

@ -1,3 +1,4 @@
To add a manager to this swarm, run the following command: To add a manager to this swarm, run the following command:
docker swarm join --token manager-join-token 127.0.0.1 docker swarm join --token manager-join-token 127.0.0.1

View File

@ -1,3 +1,4 @@
To add a worker to this swarm, run the following command: To add a worker to this swarm, run the following command:
docker swarm join --token worker-join-token 127.0.0.1 docker swarm join --token worker-join-token 127.0.0.1

View File

@ -12,7 +12,7 @@ import (
// Import builders to get the builder function as package function // Import builders to get the builder function as package function
. "github.com/docker/cli/cli/internal/test/builders" . "github.com/docker/cli/cli/internal/test/builders"
"github.com/docker/docker/pkg/testutil" "github.com/docker/docker/pkg/testutil"
"github.com/docker/docker/pkg/testutil/golden" "github.com/gotestyourself/gotestyourself/golden"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
) )
@ -167,8 +167,6 @@ func TestSwarmUnlockKey(t *testing.T) {
cmd.Flags().Set(key, value) cmd.Flags().Set(key, value)
} }
assert.NoError(t, cmd.Execute()) assert.NoError(t, cmd.Execute())
actual := cli.OutBuffer().String() golden.Assert(t, cli.OutBuffer().String(), fmt.Sprintf("unlockkeys-%s.golden", tc.name))
expected := golden.Get(t, []byte(actual), fmt.Sprintf("unlockkeys-%s.golden", tc.name))
testutil.EqualNormalizedString(t, testutil.RemoveSpace, actual, string(expected))
} }
} }

View File

@ -13,7 +13,7 @@ import (
// Import builders to get the builder function as package function // Import builders to get the builder function as package function
. "github.com/docker/cli/cli/internal/test/builders" . "github.com/docker/cli/cli/internal/test/builders"
"github.com/docker/docker/pkg/testutil" "github.com/docker/docker/pkg/testutil"
"github.com/docker/docker/pkg/testutil/golden" "github.com/gotestyourself/gotestyourself/golden"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
) )
@ -174,8 +174,6 @@ func TestSwarmUpdate(t *testing.T) {
} }
cmd.SetOutput(cli.OutBuffer()) cmd.SetOutput(cli.OutBuffer())
assert.NoError(t, cmd.Execute()) assert.NoError(t, cmd.Execute())
actual := cli.OutBuffer().String() golden.Assert(t, cli.OutBuffer().String(), fmt.Sprintf("update-%s.golden", tc.name))
expected := golden.Get(t, []byte(actual), fmt.Sprintf("update-%s.golden", tc.name))
testutil.EqualNormalizedString(t, testutil.RemoveSpace, actual, string(expected))
} }
} }

View File

@ -1,7 +1,6 @@
package task package task
import ( import (
"bytes"
"testing" "testing"
"time" "time"
@ -13,8 +12,7 @@ import (
. "github.com/docker/cli/cli/internal/test/builders" . "github.com/docker/cli/cli/internal/test/builders"
"github.com/docker/docker/api/types" "github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/swarm" "github.com/docker/docker/api/types/swarm"
"github.com/docker/docker/pkg/testutil" "github.com/gotestyourself/gotestyourself/golden"
"github.com/docker/docker/pkg/testutil/golden"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
) )
@ -22,75 +20,60 @@ func TestTaskPrintWithQuietOption(t *testing.T) {
quiet := true quiet := true
trunc := false trunc := false
noResolve := true noResolve := true
buf := new(bytes.Buffer)
apiClient := &fakeClient{} apiClient := &fakeClient{}
cli := test.NewFakeCliWithOutput(apiClient, buf) cli := test.NewFakeCli(apiClient)
tasks := []swarm.Task{ tasks := []swarm.Task{*Task(TaskID("id-foo"))}
*Task(TaskID("id-foo")),
}
err := Print(context.Background(), cli, tasks, idresolver.New(apiClient, noResolve), trunc, quiet, formatter.TableFormatKey) err := Print(context.Background(), cli, tasks, idresolver.New(apiClient, noResolve), trunc, quiet, formatter.TableFormatKey)
assert.NoError(t, err) assert.NoError(t, err)
actual := buf.String() golden.Assert(t, cli.OutBuffer().String(), "task-print-with-quiet-option.golden")
expected := golden.Get(t, []byte(actual), "task-print-with-quiet-option.golden")
testutil.EqualNormalizedString(t, testutil.RemoveSpace, actual, string(expected))
} }
func TestTaskPrintWithNoTruncOption(t *testing.T) { func TestTaskPrintWithNoTruncOption(t *testing.T) {
quiet := false quiet := false
trunc := false trunc := false
noResolve := true noResolve := true
buf := new(bytes.Buffer)
apiClient := &fakeClient{} apiClient := &fakeClient{}
cli := test.NewFakeCliWithOutput(apiClient, buf) cli := test.NewFakeCli(apiClient)
tasks := []swarm.Task{ tasks := []swarm.Task{
*Task(TaskID("id-foo-yov6omdek8fg3k5stosyp2m50")), *Task(TaskID("id-foo-yov6omdek8fg3k5stosyp2m50")),
} }
err := Print(context.Background(), cli, tasks, idresolver.New(apiClient, noResolve), trunc, quiet, "{{ .ID }}") err := Print(context.Background(), cli, tasks, idresolver.New(apiClient, noResolve), trunc, quiet, "{{ .ID }}")
assert.NoError(t, err) assert.NoError(t, err)
actual := buf.String() golden.Assert(t, cli.OutBuffer().String(), "task-print-with-no-trunc-option.golden")
expected := golden.Get(t, []byte(actual), "task-print-with-no-trunc-option.golden")
testutil.EqualNormalizedString(t, testutil.RemoveSpace, actual, string(expected))
} }
func TestTaskPrintWithGlobalService(t *testing.T) { func TestTaskPrintWithGlobalService(t *testing.T) {
quiet := false quiet := false
trunc := false trunc := false
noResolve := true noResolve := true
buf := new(bytes.Buffer)
apiClient := &fakeClient{} apiClient := &fakeClient{}
cli := test.NewFakeCliWithOutput(apiClient, buf) cli := test.NewFakeCli(apiClient)
tasks := []swarm.Task{ tasks := []swarm.Task{
*Task(TaskServiceID("service-id-foo"), TaskNodeID("node-id-bar"), TaskSlot(0)), *Task(TaskServiceID("service-id-foo"), TaskNodeID("node-id-bar"), TaskSlot(0)),
} }
err := Print(context.Background(), cli, tasks, idresolver.New(apiClient, noResolve), trunc, quiet, "{{ .Name }}") err := Print(context.Background(), cli, tasks, idresolver.New(apiClient, noResolve), trunc, quiet, "{{ .Name }}")
assert.NoError(t, err) assert.NoError(t, err)
actual := buf.String() golden.Assert(t, cli.OutBuffer().String(), "task-print-with-global-service.golden")
expected := golden.Get(t, []byte(actual), "task-print-with-global-service.golden")
testutil.EqualNormalizedString(t, testutil.RemoveSpace, actual, string(expected))
} }
func TestTaskPrintWithReplicatedService(t *testing.T) { func TestTaskPrintWithReplicatedService(t *testing.T) {
quiet := false quiet := false
trunc := false trunc := false
noResolve := true noResolve := true
buf := new(bytes.Buffer)
apiClient := &fakeClient{} apiClient := &fakeClient{}
cli := test.NewFakeCliWithOutput(apiClient, buf) cli := test.NewFakeCli(apiClient)
tasks := []swarm.Task{ tasks := []swarm.Task{
*Task(TaskServiceID("service-id-foo"), TaskSlot(1)), *Task(TaskServiceID("service-id-foo"), TaskSlot(1)),
} }
err := Print(context.Background(), cli, tasks, idresolver.New(apiClient, noResolve), trunc, quiet, "{{ .Name }}") err := Print(context.Background(), cli, tasks, idresolver.New(apiClient, noResolve), trunc, quiet, "{{ .Name }}")
assert.NoError(t, err) assert.NoError(t, err)
actual := buf.String() golden.Assert(t, cli.OutBuffer().String(), "task-print-with-replicated-service.golden")
expected := golden.Get(t, []byte(actual), "task-print-with-replicated-service.golden")
testutil.EqualNormalizedString(t, testutil.RemoveSpace, actual, string(expected))
} }
func TestTaskPrintWithIndentation(t *testing.T) { func TestTaskPrintWithIndentation(t *testing.T) {
quiet := false quiet := false
trunc := false trunc := false
noResolve := false noResolve := false
buf := new(bytes.Buffer)
apiClient := &fakeClient{ apiClient := &fakeClient{
serviceInspectWithRaw: func(ref string, options types.ServiceInspectOptions) (swarm.Service, []byte, error) { serviceInspectWithRaw: func(ref string, options types.ServiceInspectOptions) (swarm.Service, []byte, error) {
return *Service(ServiceName("service-name-foo")), nil, nil return *Service(ServiceName("service-name-foo")), nil, nil
@ -99,7 +82,7 @@ func TestTaskPrintWithIndentation(t *testing.T) {
return *Node(NodeName("node-name-bar")), nil, nil return *Node(NodeName("node-name-bar")), nil, nil
}, },
} }
cli := test.NewFakeCliWithOutput(apiClient, buf) cli := test.NewFakeCli(apiClient)
tasks := []swarm.Task{ tasks := []swarm.Task{
*Task( *Task(
TaskID("id-foo"), TaskID("id-foo"),
@ -120,16 +103,13 @@ func TestTaskPrintWithIndentation(t *testing.T) {
} }
err := Print(context.Background(), cli, tasks, idresolver.New(apiClient, noResolve), trunc, quiet, formatter.TableFormatKey) err := Print(context.Background(), cli, tasks, idresolver.New(apiClient, noResolve), trunc, quiet, formatter.TableFormatKey)
assert.NoError(t, err) assert.NoError(t, err)
actual := buf.String() golden.Assert(t, cli.OutBuffer().String(), "task-print-with-indentation.golden")
expected := golden.Get(t, []byte(actual), "task-print-with-indentation.golden")
testutil.EqualNormalizedString(t, testutil.RemoveSpace, actual, string(expected))
} }
func TestTaskPrintWithResolution(t *testing.T) { func TestTaskPrintWithResolution(t *testing.T) {
quiet := false quiet := false
trunc := false trunc := false
noResolve := false noResolve := false
buf := new(bytes.Buffer)
apiClient := &fakeClient{ apiClient := &fakeClient{
serviceInspectWithRaw: func(ref string, options types.ServiceInspectOptions) (swarm.Service, []byte, error) { serviceInspectWithRaw: func(ref string, options types.ServiceInspectOptions) (swarm.Service, []byte, error) {
return *Service(ServiceName("service-name-foo")), nil, nil return *Service(ServiceName("service-name-foo")), nil, nil
@ -138,13 +118,11 @@ func TestTaskPrintWithResolution(t *testing.T) {
return *Node(NodeName("node-name-bar")), nil, nil return *Node(NodeName("node-name-bar")), nil, nil
}, },
} }
cli := test.NewFakeCliWithOutput(apiClient, buf) cli := test.NewFakeCli(apiClient)
tasks := []swarm.Task{ tasks := []swarm.Task{
*Task(TaskServiceID("service-id-foo"), TaskSlot(1)), *Task(TaskServiceID("service-id-foo"), TaskSlot(1)),
} }
err := Print(context.Background(), cli, tasks, idresolver.New(apiClient, noResolve), trunc, quiet, "{{ .Name }} {{ .Node }}") err := Print(context.Background(), cli, tasks, idresolver.New(apiClient, noResolve), trunc, quiet, "{{ .Name }} {{ .Node }}")
assert.NoError(t, err) assert.NoError(t, err)
actual := buf.String() golden.Assert(t, cli.OutBuffer().String(), "task-print-with-resolution.golden")
expected := golden.Get(t, []byte(actual), "task-print-with-resolution.golden")
testutil.EqualNormalizedString(t, testutil.RemoveSpace, actual, string(expected))
} }

View File

@ -1,3 +1,3 @@
ID NAME IMAGE NODE DESIRED STATE CURRENT STATE ERROR PORTS ID NAME IMAGE NODE DESIRED STATE CURRENT STATE ERROR PORTS
id-foo service-name-foo.1 myimage:mytag node-name-bar Ready Failed 2 hours ago id-foo service-name-foo.1 myimage:mytag node-name-bar Ready Failed 2 hours ago
id-bar \_ service-name-foo.1 myimage:mytag node-name-bar Ready Failed 2 hours ago id-bar \_ service-name-foo.1 myimage:mytag node-name-bar Ready Failed 2 hours ago

View File

@ -1,7 +1,6 @@
package volume package volume
import ( import (
"bytes"
"io/ioutil" "io/ioutil"
"reflect" "reflect"
"strings" "strings"
@ -57,8 +56,7 @@ func TestVolumeCreateErrors(t *testing.T) {
func TestVolumeCreateWithName(t *testing.T) { func TestVolumeCreateWithName(t *testing.T) {
name := "foo" name := "foo"
buf := new(bytes.Buffer) cli := test.NewFakeCli(&fakeClient{
cli := test.NewFakeCliWithOutput(&fakeClient{
volumeCreateFunc: func(body volumetypes.VolumesCreateBody) (types.Volume, error) { volumeCreateFunc: func(body volumetypes.VolumesCreateBody) (types.Volume, error) {
if body.Name != name { if body.Name != name {
return types.Volume{}, errors.Errorf("expected name %q, got %q", name, body.Name) return types.Volume{}, errors.Errorf("expected name %q, got %q", name, body.Name)
@ -67,7 +65,9 @@ func TestVolumeCreateWithName(t *testing.T) {
Name: body.Name, Name: body.Name,
}, nil }, nil
}, },
}, buf) })
buf := cli.OutBuffer()
// Test by flags // Test by flags
cmd := newCreateCommand(cli) cmd := newCreateCommand(cli)
@ -95,8 +95,7 @@ func TestVolumeCreateWithFlags(t *testing.T) {
} }
name := "banana" name := "banana"
buf := new(bytes.Buffer) cli := test.NewFakeCli(&fakeClient{
cli := test.NewFakeCliWithOutput(&fakeClient{
volumeCreateFunc: func(body volumetypes.VolumesCreateBody) (types.Volume, error) { volumeCreateFunc: func(body volumetypes.VolumesCreateBody) (types.Volume, error) {
if body.Name != "" { if body.Name != "" {
return types.Volume{}, errors.Errorf("expected empty name, got %q", body.Name) return types.Volume{}, errors.Errorf("expected empty name, got %q", body.Name)
@ -114,7 +113,7 @@ func TestVolumeCreateWithFlags(t *testing.T) {
Name: name, Name: name,
}, nil }, nil
}, },
}, buf) })
cmd := newCreateCommand(cli) cmd := newCreateCommand(cli)
cmd.Flags().Set("driver", "foo") cmd.Flags().Set("driver", "foo")
@ -123,5 +122,5 @@ func TestVolumeCreateWithFlags(t *testing.T) {
cmd.Flags().Set("label", "lbl1=v1") cmd.Flags().Set("label", "lbl1=v1")
cmd.Flags().Set("label", "lbl2=v2") cmd.Flags().Set("label", "lbl2=v2")
assert.NoError(t, cmd.Execute()) assert.NoError(t, cmd.Execute())
assert.Equal(t, name, strings.TrimSpace(buf.String())) assert.Equal(t, name, strings.TrimSpace(cli.OutBuffer().String()))
} }

View File

@ -1,7 +1,6 @@
package volume package volume
import ( import (
"bytes"
"fmt" "fmt"
"io/ioutil" "io/ioutil"
"testing" "testing"
@ -12,7 +11,7 @@ import (
// Import builders to get the builder function as package function // Import builders to get the builder function as package function
. "github.com/docker/cli/cli/internal/test/builders" . "github.com/docker/cli/cli/internal/test/builders"
"github.com/docker/docker/pkg/testutil" "github.com/docker/docker/pkg/testutil"
"github.com/docker/docker/pkg/testutil/golden" "github.com/gotestyourself/gotestyourself/golden"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
) )
@ -54,11 +53,10 @@ func TestVolumeInspectErrors(t *testing.T) {
}, },
} }
for _, tc := range testCases { for _, tc := range testCases {
buf := new(bytes.Buffer)
cmd := newInspectCommand( cmd := newInspectCommand(
test.NewFakeCliWithOutput(&fakeClient{ test.NewFakeCli(&fakeClient{
volumeInspectFunc: tc.volumeInspectFunc, volumeInspectFunc: tc.volumeInspectFunc,
}, buf), }),
) )
cmd.SetArgs(tc.args) cmd.SetArgs(tc.args)
for key, value := range tc.flags { for key, value := range tc.flags {
@ -96,17 +94,13 @@ func TestVolumeInspectWithoutFormat(t *testing.T) {
}, },
} }
for _, tc := range testCases { for _, tc := range testCases {
buf := new(bytes.Buffer) cli := test.NewFakeCli(&fakeClient{
cmd := newInspectCommand( volumeInspectFunc: tc.volumeInspectFunc,
test.NewFakeCliWithOutput(&fakeClient{ })
volumeInspectFunc: tc.volumeInspectFunc, cmd := newInspectCommand(cli)
}, buf),
)
cmd.SetArgs(tc.args) cmd.SetArgs(tc.args)
assert.NoError(t, cmd.Execute()) assert.NoError(t, cmd.Execute())
actual := buf.String() golden.Assert(t, cli.OutBuffer().String(), fmt.Sprintf("volume-inspect-without-format.%s.golden", tc.name))
expected := golden.Get(t, []byte(actual), fmt.Sprintf("volume-inspect-without-format.%s.golden", tc.name))
testutil.EqualNormalizedString(t, testutil.RemoveSpace, actual, string(expected))
} }
} }
@ -136,17 +130,13 @@ func TestVolumeInspectWithFormat(t *testing.T) {
}, },
} }
for _, tc := range testCases { for _, tc := range testCases {
buf := new(bytes.Buffer) cli := test.NewFakeCli(&fakeClient{
cmd := newInspectCommand( volumeInspectFunc: tc.volumeInspectFunc,
test.NewFakeCliWithOutput(&fakeClient{ })
volumeInspectFunc: tc.volumeInspectFunc, cmd := newInspectCommand(cli)
}, buf),
)
cmd.SetArgs(tc.args) cmd.SetArgs(tc.args)
cmd.Flags().Set("format", tc.format) cmd.Flags().Set("format", tc.format)
assert.NoError(t, cmd.Execute()) assert.NoError(t, cmd.Execute())
actual := buf.String() golden.Assert(t, cli.OutBuffer().String(), fmt.Sprintf("volume-inspect-with-format.%s.golden", tc.name))
expected := golden.Get(t, []byte(actual), fmt.Sprintf("volume-inspect-with-format.%s.golden", tc.name))
testutil.EqualNormalizedString(t, testutil.RemoveSpace, actual, string(expected))
} }
} }

View File

@ -1,7 +1,6 @@
package volume package volume
import ( import (
"bytes"
"io/ioutil" "io/ioutil"
"testing" "testing"
@ -14,7 +13,7 @@ import (
// Import builders to get the builder function as package function // Import builders to get the builder function as package function
. "github.com/docker/cli/cli/internal/test/builders" . "github.com/docker/cli/cli/internal/test/builders"
"github.com/docker/docker/pkg/testutil" "github.com/docker/docker/pkg/testutil"
"github.com/docker/docker/pkg/testutil/golden" "github.com/gotestyourself/gotestyourself/golden"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
) )
@ -37,11 +36,10 @@ func TestVolumeListErrors(t *testing.T) {
}, },
} }
for _, tc := range testCases { for _, tc := range testCases {
buf := new(bytes.Buffer)
cmd := newListCommand( cmd := newListCommand(
test.NewFakeCliWithOutput(&fakeClient{ test.NewFakeCli(&fakeClient{
volumeListFunc: tc.volumeListFunc, volumeListFunc: tc.volumeListFunc,
}, buf), }),
) )
cmd.SetArgs(tc.args) cmd.SetArgs(tc.args)
for key, value := range tc.flags { for key, value := range tc.flags {
@ -53,8 +51,7 @@ func TestVolumeListErrors(t *testing.T) {
} }
func TestVolumeListWithoutFormat(t *testing.T) { func TestVolumeListWithoutFormat(t *testing.T) {
buf := new(bytes.Buffer) cli := test.NewFakeCli(&fakeClient{
cli := test.NewFakeCliWithOutput(&fakeClient{
volumeListFunc: func(filter filters.Args) (volumetypes.VolumesListOKBody, error) { volumeListFunc: func(filter filters.Args) (volumetypes.VolumesListOKBody, error) {
return volumetypes.VolumesListOKBody{ return volumetypes.VolumesListOKBody{
Volumes: []*types.Volume{ Volumes: []*types.Volume{
@ -66,17 +63,14 @@ func TestVolumeListWithoutFormat(t *testing.T) {
}, },
}, nil }, nil
}, },
}, buf) })
cmd := newListCommand(cli) cmd := newListCommand(cli)
assert.NoError(t, cmd.Execute()) assert.NoError(t, cmd.Execute())
actual := buf.String() golden.Assert(t, cli.OutBuffer().String(), "volume-list-without-format.golden")
expected := golden.Get(t, []byte(actual), "volume-list-without-format.golden")
testutil.EqualNormalizedString(t, testutil.RemoveSpace, actual, string(expected))
} }
func TestVolumeListWithConfigFormat(t *testing.T) { func TestVolumeListWithConfigFormat(t *testing.T) {
buf := new(bytes.Buffer) cli := test.NewFakeCli(&fakeClient{
cli := test.NewFakeCliWithOutput(&fakeClient{
volumeListFunc: func(filter filters.Args) (volumetypes.VolumesListOKBody, error) { volumeListFunc: func(filter filters.Args) (volumetypes.VolumesListOKBody, error) {
return volumetypes.VolumesListOKBody{ return volumetypes.VolumesListOKBody{
Volumes: []*types.Volume{ Volumes: []*types.Volume{
@ -88,20 +82,17 @@ func TestVolumeListWithConfigFormat(t *testing.T) {
}, },
}, nil }, nil
}, },
}, buf) })
cli.SetConfigFile(&configfile.ConfigFile{ cli.SetConfigFile(&configfile.ConfigFile{
VolumesFormat: "{{ .Name }} {{ .Driver }} {{ .Labels }}", VolumesFormat: "{{ .Name }} {{ .Driver }} {{ .Labels }}",
}) })
cmd := newListCommand(cli) cmd := newListCommand(cli)
assert.NoError(t, cmd.Execute()) assert.NoError(t, cmd.Execute())
actual := buf.String() golden.Assert(t, cli.OutBuffer().String(), "volume-list-with-config-format.golden")
expected := golden.Get(t, []byte(actual), "volume-list-with-config-format.golden")
testutil.EqualNormalizedString(t, testutil.RemoveSpace, actual, string(expected))
} }
func TestVolumeListWithFormat(t *testing.T) { func TestVolumeListWithFormat(t *testing.T) {
buf := new(bytes.Buffer) cli := test.NewFakeCli(&fakeClient{
cli := test.NewFakeCliWithOutput(&fakeClient{
volumeListFunc: func(filter filters.Args) (volumetypes.VolumesListOKBody, error) { volumeListFunc: func(filter filters.Args) (volumetypes.VolumesListOKBody, error) {
return volumetypes.VolumesListOKBody{ return volumetypes.VolumesListOKBody{
Volumes: []*types.Volume{ Volumes: []*types.Volume{
@ -113,11 +104,9 @@ func TestVolumeListWithFormat(t *testing.T) {
}, },
}, nil }, nil
}, },
}, buf) })
cmd := newListCommand(cli) cmd := newListCommand(cli)
cmd.Flags().Set("format", "{{ .Name }} {{ .Driver }} {{ .Labels }}") cmd.Flags().Set("format", "{{ .Name }} {{ .Driver }} {{ .Labels }}")
assert.NoError(t, cmd.Execute()) assert.NoError(t, cmd.Execute())
actual := buf.String() golden.Assert(t, cli.OutBuffer().String(), "volume-list-with-format.golden")
expected := golden.Get(t, []byte(actual), "volume-list-with-format.golden")
testutil.EqualNormalizedString(t, testutil.RemoveSpace, actual, string(expected))
} }

View File

@ -1,7 +1,6 @@
package volume package volume
import ( import (
"bytes"
"fmt" "fmt"
"io/ioutil" "io/ioutil"
"runtime" "runtime"
@ -13,7 +12,8 @@ import (
"github.com/docker/docker/api/types" "github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/filters" "github.com/docker/docker/api/types/filters"
"github.com/docker/docker/pkg/testutil" "github.com/docker/docker/pkg/testutil"
"github.com/docker/docker/pkg/testutil/golden" "github.com/gotestyourself/gotestyourself/golden"
"github.com/gotestyourself/gotestyourself/skip"
"github.com/pkg/errors" "github.com/pkg/errors"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
) )
@ -41,9 +41,9 @@ func TestVolumePruneErrors(t *testing.T) {
} }
for _, tc := range testCases { for _, tc := range testCases {
cmd := NewPruneCommand( cmd := NewPruneCommand(
test.NewFakeCliWithOutput(&fakeClient{ test.NewFakeCli(&fakeClient{
volumePruneFunc: tc.volumePruneFunc, volumePruneFunc: tc.volumePruneFunc,
}, ioutil.Discard), }),
) )
cmd.SetArgs(tc.args) cmd.SetArgs(tc.args)
for key, value := range tc.flags { for key, value := range tc.flags {
@ -68,60 +68,45 @@ func TestVolumePruneForce(t *testing.T) {
}, },
} }
for _, tc := range testCases { for _, tc := range testCases {
buf := new(bytes.Buffer) cli := test.NewFakeCli(&fakeClient{
cmd := NewPruneCommand( volumePruneFunc: tc.volumePruneFunc,
test.NewFakeCliWithOutput(&fakeClient{ })
volumePruneFunc: tc.volumePruneFunc, cmd := NewPruneCommand(cli)
}, buf),
)
cmd.Flags().Set("force", "true") cmd.Flags().Set("force", "true")
assert.NoError(t, cmd.Execute()) assert.NoError(t, cmd.Execute())
actual := buf.String() golden.Assert(t, cli.OutBuffer().String(), fmt.Sprintf("volume-prune.%s.golden", tc.name))
expected := golden.Get(t, []byte(actual), fmt.Sprintf("volume-prune.%s.golden", tc.name))
testutil.EqualNormalizedString(t, testutil.RemoveSpace, actual, string(expected))
} }
} }
func TestVolumePrunePromptYes(t *testing.T) { func TestVolumePrunePromptYes(t *testing.T) {
if runtime.GOOS == "windows" { // FIXME(vdemeester) make it work..
// FIXME(vdemeester) make it work.. skip.IfCondition(t, runtime.GOOS == "windows", "TODO: fix test on windows")
t.Skip("skipping this test on Windows")
}
for _, input := range []string{"y", "Y"} { for _, input := range []string{"y", "Y"} {
buf := new(bytes.Buffer) cli := test.NewFakeCli(&fakeClient{
cli := test.NewFakeCliWithOutput(&fakeClient{
volumePruneFunc: simplePruneFunc, volumePruneFunc: simplePruneFunc,
}, buf) })
cli.SetIn(command.NewInStream(ioutil.NopCloser(strings.NewReader(input)))) cli.SetIn(command.NewInStream(ioutil.NopCloser(strings.NewReader(input))))
cmd := NewPruneCommand( cmd := NewPruneCommand(cli)
cli,
)
assert.NoError(t, cmd.Execute()) assert.NoError(t, cmd.Execute())
actual := buf.String() golden.Assert(t, cli.OutBuffer().String(), "volume-prune-yes.golden")
expected := golden.Get(t, []byte(actual), "volume-prune-yes.golden")
testutil.EqualNormalizedString(t, testutil.RemoveSpace, actual, string(expected))
} }
} }
func TestVolumePrunePromptNo(t *testing.T) { func TestVolumePrunePromptNo(t *testing.T) {
if runtime.GOOS == "windows" { // FIXME(vdemeester) make it work..
// FIXME(vdemeester) make it work.. skip.IfCondition(t, runtime.GOOS == "windows", "TODO: fix test on windows")
t.Skip("skipping this test on Windows")
}
for _, input := range []string{"n", "N", "no", "anything", "really"} { for _, input := range []string{"n", "N", "no", "anything", "really"} {
buf := new(bytes.Buffer) cli := test.NewFakeCli(&fakeClient{
cli := test.NewFakeCliWithOutput(&fakeClient{
volumePruneFunc: simplePruneFunc, volumePruneFunc: simplePruneFunc,
}, buf) })
cli.SetIn(command.NewInStream(ioutil.NopCloser(strings.NewReader(input)))) cli.SetIn(command.NewInStream(ioutil.NopCloser(strings.NewReader(input))))
cmd := NewPruneCommand( cmd := NewPruneCommand(cli)
cli,
)
assert.NoError(t, cmd.Execute()) assert.NoError(t, cmd.Execute())
actual := buf.String() golden.Assert(t, cli.OutBuffer().String(), "volume-prune-no.golden")
expected := golden.Get(t, []byte(actual), "volume-prune-no.golden")
testutil.EqualNormalizedString(t, testutil.RemoveSpace, actual, string(expected))
} }
} }

View File

@ -1,7 +1,6 @@
package volume package volume
import ( import (
"bytes"
"io/ioutil" "io/ioutil"
"testing" "testing"
@ -29,11 +28,10 @@ func TestVolumeRemoveErrors(t *testing.T) {
}, },
} }
for _, tc := range testCases { for _, tc := range testCases {
buf := new(bytes.Buffer)
cmd := newRemoveCommand( cmd := newRemoveCommand(
test.NewFakeCliWithOutput(&fakeClient{ test.NewFakeCli(&fakeClient{
volumeRemoveFunc: tc.volumeRemoveFunc, volumeRemoveFunc: tc.volumeRemoveFunc,
}, buf)) }))
cmd.SetArgs(tc.args) cmd.SetArgs(tc.args)
cmd.SetOutput(ioutil.Discard) cmd.SetOutput(ioutil.Discard)
testutil.ErrorContains(t, cmd.Execute(), tc.expectedError) testutil.ErrorContains(t, cmd.Execute(), tc.expectedError)
@ -41,8 +39,7 @@ func TestVolumeRemoveErrors(t *testing.T) {
} }
func TestNodeRemoveMultiple(t *testing.T) { func TestNodeRemoveMultiple(t *testing.T) {
buf := new(bytes.Buffer) cmd := newRemoveCommand(test.NewFakeCli(&fakeClient{}))
cmd := newRemoveCommand(test.NewFakeCliWithOutput(&fakeClient{}, buf))
cmd.SetArgs([]string{"volume1", "volume2"}) cmd.SetArgs([]string{"volume1", "volume2"})
assert.NoError(t, cmd.Execute()) assert.NoError(t, cmd.Execute())
} }

View File

@ -6,7 +6,7 @@ import (
composetypes "github.com/docker/cli/cli/compose/types" composetypes "github.com/docker/cli/cli/compose/types"
"github.com/docker/docker/api/types" "github.com/docker/docker/api/types"
"github.com/docker/docker/api/types/network" "github.com/docker/docker/api/types/network"
"github.com/docker/docker/pkg/testutil/tempfile" "github.com/gotestyourself/gotestyourself/fs"
"github.com/stretchr/testify/assert" "github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require" "github.com/stretchr/testify/require"
) )
@ -107,12 +107,12 @@ func TestSecrets(t *testing.T) {
namespace := Namespace{name: "foo"} namespace := Namespace{name: "foo"}
secretText := "this is the first secret" secretText := "this is the first secret"
secretFile := tempfile.NewTempFile(t, "convert-secrets", secretText) secretFile := fs.NewFile(t, "convert-secrets", fs.WithContent(secretText))
defer secretFile.Remove() defer secretFile.Remove()
source := map[string]composetypes.SecretConfig{ source := map[string]composetypes.SecretConfig{
"one": { "one": {
File: secretFile.Name(), File: secretFile.Path(),
Labels: map[string]string{"monster": "mash"}, Labels: map[string]string{"monster": "mash"},
}, },
"ext": { "ext": {
@ -138,12 +138,12 @@ func TestConfigs(t *testing.T) {
namespace := Namespace{name: "foo"} namespace := Namespace{name: "foo"}
configText := "this is the first config" configText := "this is the first config"
configFile := tempfile.NewTempFile(t, "convert-configs", configText) configFile := fs.NewFile(t, "convert-configs", fs.WithContent(configText))
defer configFile.Remove() defer configFile.Remove()
source := map[string]composetypes.ConfigObjConfig{ source := map[string]composetypes.ConfigObjConfig{
"one": { "one": {
File: configFile.Name(), File: configFile.Path(),
Labels: map[string]string{"monster": "mash"}, Labels: map[string]string{"monster": "mash"},
}, },
"ext": { "ext": {

View File

@ -23,14 +23,6 @@ type FakeCli struct {
server command.ServerInfo server command.ServerInfo
} }
// NewFakeCliWithOutput returns a Cli backed by the fakeCli
// Deprecated: Use NewFakeCli
func NewFakeCliWithOutput(client client.APIClient, out io.Writer) *FakeCli {
cli := NewFakeCli(client)
cli.out = command.NewOutStream(out)
return cli
}
// NewFakeCli returns a fake for the command.Cli interface // NewFakeCli returns a fake for the command.Cli interface
func NewFakeCli(client client.APIClient) *FakeCli { func NewFakeCli(client client.APIClient) *FakeCli {
outBuffer := new(bytes.Buffer) outBuffer := new(bytes.Buffer)

View File

@ -22,6 +22,7 @@ github.com/docker/swarmkit 79381d0840be27f8b3f5c667b348a4467d866eeb
github.com/flynn-archive/go-shlex 3f9db97f856818214da2e1057f8ad84803971cff github.com/flynn-archive/go-shlex 3f9db97f856818214da2e1057f8ad84803971cff
github.com/gogo/protobuf 7efa791bd276fd4db00867cbd982b552627c24cb github.com/gogo/protobuf 7efa791bd276fd4db00867cbd982b552627c24cb
github.com/golang/protobuf 7a211bcf3bce0e3f1d74f9894916e6f116ae83b4 github.com/golang/protobuf 7a211bcf3bce0e3f1d74f9894916e6f116ae83b4
github.com/gotestyourself/gotestyourself v1.0.0
github.com/gorilla/context v1.1 github.com/gorilla/context v1.1
github.com/gorilla/mux v1.1 github.com/gorilla/mux v1.1
github.com/inconshreveable/mousetrap 76626ae9c91c4f2a10f34cad8ce83ea42c93bb75 github.com/inconshreveable/mousetrap 76626ae9c91c4f2a10f34cad8ce83ea42c93bb75

View File

@ -1,28 +0,0 @@
// Package golden provides function and helpers to use golden file for
// testing purpose.
package golden
import (
"flag"
"io/ioutil"
"path/filepath"
"testing"
)
var update = flag.Bool("test.update", false, "update golden file")
// Get returns the golden file content. If the `test.update` is specified, it updates the
// file with the current output and returns it.
func Get(t *testing.T, actual []byte, filename string) []byte {
golden := filepath.Join("testdata", filename)
if *update {
if err := ioutil.WriteFile(golden, actual, 0644); err != nil {
t.Fatal(err)
}
}
expected, err := ioutil.ReadFile(golden)
if err != nil {
t.Fatal(err)
}
return expected
}

View File

@ -1,56 +0,0 @@
package tempfile
import (
"io/ioutil"
"os"
"github.com/stretchr/testify/require"
)
// TempFile is a temporary file that can be used with unit tests. TempFile
// reduces the boilerplate setup required in each test case by handling
// setup errors.
type TempFile struct {
File *os.File
}
// NewTempFile returns a new temp file with contents
func NewTempFile(t require.TestingT, prefix string, content string) *TempFile {
file, err := ioutil.TempFile("", prefix+"-")
require.NoError(t, err)
_, err = file.Write([]byte(content))
require.NoError(t, err)
file.Close()
return &TempFile{File: file}
}
// Name returns the filename
func (f *TempFile) Name() string {
return f.File.Name()
}
// Remove removes the file
func (f *TempFile) Remove() {
os.Remove(f.Name())
}
// TempDir is a temporary directory that can be used with unit tests. TempDir
// reduces the boilerplate setup required in each test case by handling
// setup errors.
type TempDir struct {
Path string
}
// NewTempDir returns a new temp file with contents
func NewTempDir(t require.TestingT, prefix string) *TempDir {
path, err := ioutil.TempDir("", prefix+"-")
require.NoError(t, err)
return &TempDir{Path: path}
}
// Remove removes the file
func (f *TempDir) Remove() {
os.Remove(f.Path)
}

202
vendor/github.com/gotestyourself/gotestyourself/LICENSE generated vendored Normal file
View File

@ -0,0 +1,202 @@
Apache License
Version 2.0, January 2004
http://www.apache.org/licenses/
TERMS AND CONDITIONS FOR USE, REPRODUCTION, AND DISTRIBUTION
1. Definitions.
"License" shall mean the terms and conditions for use, reproduction,
and distribution as defined by Sections 1 through 9 of this document.
"Licensor" shall mean the copyright owner or entity authorized by
the copyright owner that is granting the License.
"Legal Entity" shall mean the union of the acting entity and all
other entities that control, are controlled by, or are under common
control with that entity. For the purposes of this definition,
"control" means (i) the power, direct or indirect, to cause the
direction or management of such entity, whether by contract or
otherwise, or (ii) ownership of fifty percent (50%) or more of the
outstanding shares, or (iii) beneficial ownership of such entity.
"You" (or "Your") shall mean an individual or Legal Entity
exercising permissions granted by this License.
"Source" form shall mean the preferred form for making modifications,
including but not limited to software source code, documentation
source, and configuration files.
"Object" form shall mean any form resulting from mechanical
transformation or translation of a Source form, including but
not limited to compiled object code, generated documentation,
and conversions to other media types.
"Work" shall mean the work of authorship, whether in Source or
Object form, made available under the License, as indicated by a
copyright notice that is included in or attached to the work
(an example is provided in the Appendix below).
"Derivative Works" shall mean any work, whether in Source or Object
form, that is based on (or derived from) the Work and for which the
editorial revisions, annotations, elaborations, or other modifications
represent, as a whole, an original work of authorship. For the purposes
of this License, Derivative Works shall not include works that remain
separable from, or merely link (or bind by name) to the interfaces of,
the Work and Derivative Works thereof.
"Contribution" shall mean any work of authorship, including
the original version of the Work and any modifications or additions
to that Work or Derivative Works thereof, that is intentionally
submitted to Licensor for inclusion in the Work by the copyright owner
or by an individual or Legal Entity authorized to submit on behalf of
the copyright owner. For the purposes of this definition, "submitted"
means any form of electronic, verbal, or written communication sent
to the Licensor or its representatives, including but not limited to
communication on electronic mailing lists, source code control systems,
and issue tracking systems that are managed by, or on behalf of, the
Licensor for the purpose of discussing and improving the Work, but
excluding communication that is conspicuously marked or otherwise
designated in writing by the copyright owner as "Not a Contribution."
"Contributor" shall mean Licensor and any individual or Legal Entity
on behalf of whom a Contribution has been received by Licensor and
subsequently incorporated within the Work.
2. Grant of Copyright License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
copyright license to reproduce, prepare Derivative Works of,
publicly display, publicly perform, sublicense, and distribute the
Work and such Derivative Works in Source or Object form.
3. Grant of Patent License. Subject to the terms and conditions of
this License, each Contributor hereby grants to You a perpetual,
worldwide, non-exclusive, no-charge, royalty-free, irrevocable
(except as stated in this section) patent license to make, have made,
use, offer to sell, sell, import, and otherwise transfer the Work,
where such license applies only to those patent claims licensable
by such Contributor that are necessarily infringed by their
Contribution(s) alone or by combination of their Contribution(s)
with the Work to which such Contribution(s) was submitted. If You
institute patent litigation against any entity (including a
cross-claim or counterclaim in a lawsuit) alleging that the Work
or a Contribution incorporated within the Work constitutes direct
or contributory patent infringement, then any patent licenses
granted to You under this License for that Work shall terminate
as of the date such litigation is filed.
4. Redistribution. You may reproduce and distribute copies of the
Work or Derivative Works thereof in any medium, with or without
modifications, and in Source or Object form, provided that You
meet the following conditions:
(a) You must give any other recipients of the Work or
Derivative Works a copy of this License; and
(b) You must cause any modified files to carry prominent notices
stating that You changed the files; and
(c) You must retain, in the Source form of any Derivative Works
that You distribute, all copyright, patent, trademark, and
attribution notices from the Source form of the Work,
excluding those notices that do not pertain to any part of
the Derivative Works; and
(d) If the Work includes a "NOTICE" text file as part of its
distribution, then any Derivative Works that You distribute must
include a readable copy of the attribution notices contained
within such NOTICE file, excluding those notices that do not
pertain to any part of the Derivative Works, in at least one
of the following places: within a NOTICE text file distributed
as part of the Derivative Works; within the Source form or
documentation, if provided along with the Derivative Works; or,
within a display generated by the Derivative Works, if and
wherever such third-party notices normally appear. The contents
of the NOTICE file are for informational purposes only and
do not modify the License. You may add Your own attribution
notices within Derivative Works that You distribute, alongside
or as an addendum to the NOTICE text from the Work, provided
that such additional attribution notices cannot be construed
as modifying the License.
You may add Your own copyright statement to Your modifications and
may provide additional or different license terms and conditions
for use, reproduction, or distribution of Your modifications, or
for any such Derivative Works as a whole, provided Your use,
reproduction, and distribution of the Work otherwise complies with
the conditions stated in this License.
5. Submission of Contributions. Unless You explicitly state otherwise,
any Contribution intentionally submitted for inclusion in the Work
by You to the Licensor shall be under the terms and conditions of
this License, without any additional terms or conditions.
Notwithstanding the above, nothing herein shall supersede or modify
the terms of any separate license agreement you may have executed
with Licensor regarding such Contributions.
6. Trademarks. This License does not grant permission to use the trade
names, trademarks, service marks, or product names of the Licensor,
except as required for reasonable and customary use in describing the
origin of the Work and reproducing the content of the NOTICE file.
7. Disclaimer of Warranty. Unless required by applicable law or
agreed to in writing, Licensor provides the Work (and each
Contributor provides its Contributions) on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or
implied, including, without limitation, any warranties or conditions
of TITLE, NON-INFRINGEMENT, MERCHANTABILITY, or FITNESS FOR A
PARTICULAR PURPOSE. You are solely responsible for determining the
appropriateness of using or redistributing the Work and assume any
risks associated with Your exercise of permissions under this License.
8. Limitation of Liability. In no event and under no legal theory,
whether in tort (including negligence), contract, or otherwise,
unless required by applicable law (such as deliberate and grossly
negligent acts) or agreed to in writing, shall any Contributor be
liable to You for damages, including any direct, indirect, special,
incidental, or consequential damages of any character arising as a
result of this License or out of the use or inability to use the
Work (including but not limited to damages for loss of goodwill,
work stoppage, computer failure or malfunction, or any and all
other commercial damages or losses), even if such Contributor
has been advised of the possibility of such damages.
9. Accepting Warranty or Additional Liability. While redistributing
the Work or Derivative Works thereof, You may choose to offer,
and charge a fee for, acceptance of support, warranty, indemnity,
or other liability obligations and/or rights consistent with this
License. However, in accepting such obligations, You may act only
on Your own behalf and on Your sole responsibility, not on behalf
of any other Contributor, and only if You agree to indemnify,
defend, and hold each Contributor harmless for any liability
incurred by, or claims asserted against, such Contributor by reason
of your accepting any such warranty or additional liability.
END OF TERMS AND CONDITIONS
APPENDIX: How to apply the Apache License to your work.
To apply the Apache License to your work, attach the following
boilerplate notice, with the fields enclosed by brackets "[]"
replaced with your own identifying information. (Don't include
the brackets!) The text should be enclosed in the appropriate
comment syntax for the file format. We also recommend that a
file or class name and description of purpose be included on the
same "printed page" as the copyright notice for easier
identification within third-party archives.
Copyright [yyyy] [name of copyright owner]
Licensed under the Apache License, Version 2.0 (the "License");
you may not use this file except in compliance with the License.
You may obtain a copy of the License at
http://www.apache.org/licenses/LICENSE-2.0
Unless required by applicable law or agreed to in writing, software
distributed under the License is distributed on an "AS IS" BASIS,
WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
See the License for the specific language governing permissions and
limitations under the License.

View File

@ -0,0 +1,32 @@
# Go Test Yourself
A collection of packages compatible with `go test` to support common testing
patterns.
[![GoDoc](https://godoc.org/github.com/gotestyourself/gotestyourself?status.svg)](https://godoc.org/github.com/gotestyourself/gotestyourself)
[![CircleCI](https://circleci.com/gh/gotestyourself/gotestyourself/tree/master.svg?style=shield)](https://circleci.com/gh/gotestyourself/gotestyourself/tree/master)
[![Go Reportcard](https://goreportcard.com/badge/github.com/gotestyourself/gotestyourself)](https://goreportcard.com/report/github.com/gotestyourself/gotestyourself)
## Packages
* [fs](http://godoc.org/github.com/gotestyourself/gotestyourself/fs) -
create test files and directories
* [golden](http://godoc.org/github.com/gotestyourself/gotestyourself/golden) -
compare large multi-line strings
* [testsum](http://godoc.org/github.com/gotestyourself/gotestyourself/testsum) -
a program to summarize `go test` output and test failures
* [icmd](http://godoc.org/github.com/gotestyourself/gotestyourself/icmd) -
execute binaries and test the output
* [skip](http://godoc.org/github.com/gotestyourself/gotestyourself/skip) -
skip tests based on conditions
## Related
* [testify/assert](https://godoc.org/github.com/stretchr/testify/assert) and
[testify/require](https://godoc.org/github.com/stretchr/testify/require) -
assertion libraries with common assertions
* [golang/mock](https://github.com/golang/mock) - generate mocks for interfaces
* [testify/suite](https://godoc.org/github.com/stretchr/testify/suite) -
group test into suites to share common setup/teardown logic

View File

@ -0,0 +1,81 @@
/*Package fs provides tools for creating and working with temporary files and
directories.
*/
package fs
import (
"io/ioutil"
"os"
"path/filepath"
"github.com/stretchr/testify/require"
)
// Path objects return their filesystem path. Both File and Dir implement Path.
type Path interface {
Path() string
}
// File is a temporary file on the filesystem
type File struct {
path string
}
// NewFile creates a new file in a temporary directory using prefix as part of
// the filename. The PathOps are applied to the before returning the File.
func NewFile(t require.TestingT, prefix string, ops ...PathOp) *File {
tempfile, err := ioutil.TempFile("", prefix+"-")
require.NoError(t, err)
file := &File{path: tempfile.Name()}
require.NoError(t, tempfile.Close())
for _, op := range ops {
require.NoError(t, op(file))
}
return file
}
// Path returns the full path to the file
func (f *File) Path() string {
return f.path
}
// Remove the file
func (f *File) Remove() {
// nolint: errcheck
os.Remove(f.path)
}
// Dir is a temporary directory
type Dir struct {
path string
}
// NewDir returns a new temporary directory using prefix as part of the directory
// name. The PathOps are applied before returning the Dir.
func NewDir(t require.TestingT, prefix string, ops ...PathOp) *Dir {
path, err := ioutil.TempDir("", prefix+"-")
require.NoError(t, err)
dir := &Dir{path: path}
for _, op := range ops {
require.NoError(t, op(dir))
}
return dir
}
// Path returns the full path to the directory
func (d *Dir) Path() string {
return d.path
}
// Remove the directory
func (d *Dir) Remove() {
// nolint: errcheck
os.RemoveAll(d.path)
}
// Join returns a new path with this directory as the base of the path
func (d *Dir) Join(parts ...string) string {
return filepath.Join(append([]string{d.Path()}, parts...)...)
}

View File

@ -0,0 +1,94 @@
package fs
import (
"io/ioutil"
"os"
"path/filepath"
)
// PathOp is a function which accepts a Path to perform some operation
type PathOp func(path Path) error
// WithContent writes content to a file at Path
func WithContent(content string) PathOp {
return func(path Path) error {
return ioutil.WriteFile(path.Path(), []byte(content), 0644)
}
}
// WithBytes write bytes to a file at Path
func WithBytes(raw []byte) PathOp {
return func(path Path) error {
return ioutil.WriteFile(path.Path(), raw, 0644)
}
}
// AsUser changes ownership of the file system object at Path
func AsUser(uid, gid int) PathOp {
return func(path Path) error {
return os.Chown(path.Path(), uid, gid)
}
}
// WithFile creates a file in the directory at path with content
func WithFile(filename, content string) PathOp {
return func(path Path) error {
return createFile(path.Path(), filename, content)
}
}
func createFile(dir, filename, content string) error {
fullpath := filepath.Join(dir, filepath.FromSlash(filename))
return ioutil.WriteFile(fullpath, []byte(content), 0644)
}
// WithFiles creates all the files in the directory at path with their content
func WithFiles(files map[string]string) PathOp {
return func(path Path) error {
for filename, content := range files {
if err := createFile(path.Path(), filename, content); err != nil {
return err
}
}
return nil
}
}
// FromDir copies the directory tree from the source path into the new Dir
func FromDir(source string) PathOp {
return func(path Path) error {
return copyDirectory(source, path.Path())
}
}
func copyDirectory(source, dest string) error {
entries, err := ioutil.ReadDir(source)
if err != nil {
return err
}
for _, entry := range entries {
sourcePath := filepath.Join(source, entry.Name())
destPath := filepath.Join(dest, entry.Name())
if entry.IsDir() {
if err := os.Mkdir(destPath, 0755); err != nil {
return err
}
if err := copyDirectory(sourcePath, destPath); err != nil {
return err
}
continue
}
if err := copyFile(sourcePath, destPath); err != nil {
return err
}
}
return nil
}
func copyFile(source, dest string) error {
content, err := ioutil.ReadFile(source)
if err != nil {
return err
}
return ioutil.WriteFile(dest, content, 0644)
}

View File

@ -0,0 +1,71 @@
/*Package golden provides tools for comparing large mutli-line strings.
Golden files are files in the ./testdata/ subdirectory of the package under test.
*/
package golden
import (
"flag"
"fmt"
"io/ioutil"
"path/filepath"
"github.com/pmezard/go-difflib/difflib"
"github.com/stretchr/testify/assert"
"github.com/stretchr/testify/require"
)
var flagUpdate = flag.Bool("test.update-golden", false, "update golden file")
// Get returns the golden file content
func Get(t require.TestingT, filename string) []byte {
expected, err := ioutil.ReadFile(Path(filename))
require.NoError(t, err)
return expected
}
// Path returns the full path to a golden file
func Path(filename string) string {
return filepath.Join("testdata", filename)
}
func update(t require.TestingT, filename string, actual []byte) {
if *flagUpdate {
err := ioutil.WriteFile(Path(filename), actual, 0644)
require.NoError(t, err)
}
}
// Assert compares the actual content to the expected content in the golden file.
// If `--update-golden` is set then the actual content is written to the golden
// file.
// Returns whether the assertion was successful (true) or not (false)
func Assert(t require.TestingT, actual string, filename string, msgAndArgs ...interface{}) bool {
expected := Get(t, filename)
update(t, filename, []byte(actual))
if assert.ObjectsAreEqual(expected, []byte(actual)) {
return true
}
diff, err := difflib.GetUnifiedDiffString(difflib.UnifiedDiff{
A: difflib.SplitLines(string(expected)),
B: difflib.SplitLines(actual),
FromFile: "Expected",
ToFile: "Actual",
Context: 3,
})
require.NoError(t, err, msgAndArgs...)
return assert.Fail(t, fmt.Sprintf("Not Equal: \n%s", diff), msgAndArgs...)
}
// AssertBytes compares the actual result to the expected result in the golden
// file. If `--update-golden` is set then the actual content is written to the
// golden file.
// Returns whether the assertion was successful (true) or not (false)
// nolint: lll
func AssertBytes(t require.TestingT, actual []byte, filename string, msgAndArgs ...interface{}) bool {
expected := Get(t, filename)
update(t, filename, actual)
return assert.Equal(t, expected, actual, msgAndArgs...)
}

View File

@ -0,0 +1,133 @@
/*Package skip provides functions for skipping based on a condition.
*/
package skip
import (
"bytes"
"fmt"
"go/ast"
"go/format"
"go/parser"
"go/token"
"io/ioutil"
"path"
"reflect"
"runtime"
"strings"
"github.com/pkg/errors"
)
type skipT interface {
Skip(args ...interface{})
Log(args ...interface{})
}
// If skips the test if the check function returns true. The skip message will
// contain the name of the check function. Extra message text can be passed as a
// format string with args
func If(t skipT, check func() bool, msgAndArgs ...interface{}) {
if check() {
t.Skip(formatWithCustomMessage(
getFunctionName(check),
formatMessage(msgAndArgs...)))
}
}
func getFunctionName(function func() bool) string {
funcPath := runtime.FuncForPC(reflect.ValueOf(function).Pointer()).Name()
return strings.SplitN(path.Base(funcPath), ".", 2)[1]
}
// IfCondition skips the test if the condition is true. The skip message will
// contain the source of the expression passed as the condition. Extra message
// text can be passed as a format string with args.
func IfCondition(t skipT, condition bool, msgAndArgs ...interface{}) {
if !condition {
return
}
source, err := getConditionSource()
if err != nil {
t.Log(err.Error())
t.Skip(formatMessage(msgAndArgs...))
}
t.Skip(formatWithCustomMessage(source, formatMessage(msgAndArgs...)))
}
func getConditionSource() (string, error) {
const callstackIndex = 3
lines, err := getSourceLine(callstackIndex)
if err != nil {
return "", err
}
for i := range lines {
source := strings.Join(lines[len(lines)-i-1:], "\n")
node, err := parser.ParseExpr(source)
if err == nil {
return getConditionArgFromAST(node)
}
}
return "", errors.Wrapf(err, "failed to parse source")
}
// maxContextLines is the maximum number of lines to scan for a complete
// skip.If() statement
const maxContextLines = 10
// getSourceLines returns the source line which called skip.If() along with a
// few preceding lines. To properly parse the AST a complete statement is
// required, and that statement may be split across multiple lines, so include
// up to maxContextLines.
func getSourceLine(stackIndex int) ([]string, error) {
_, filename, line, ok := runtime.Caller(stackIndex)
if !ok {
return nil, errors.New("failed to get caller info")
}
raw, err := ioutil.ReadFile(filename)
if err != nil {
return nil, errors.Wrapf(err, "failed to read source file: %s", filename)
}
lines := strings.Split(string(raw), "\n")
if len(lines) < line {
return nil, errors.Errorf("file %s does not have line %d", filename, line)
}
firstLine := line - maxContextLines
if firstLine < 0 {
firstLine = 0
}
return lines[firstLine:line], nil
}
func getConditionArgFromAST(node ast.Expr) (string, error) {
switch expr := node.(type) {
case *ast.CallExpr:
buf := new(bytes.Buffer)
err := format.Node(buf, token.NewFileSet(), expr.Args[1])
return buf.String(), err
}
return "", errors.New("unexpected ast")
}
func formatMessage(msgAndArgs ...interface{}) string {
switch len(msgAndArgs) {
case 0:
return ""
case 1:
return msgAndArgs[0].(string)
default:
return fmt.Sprintf(msgAndArgs[0].(string), msgAndArgs[1:]...)
}
}
func formatWithCustomMessage(source, custom string) string {
switch {
case custom == "":
return source
case source == "":
return custom
}
return fmt.Sprintf("%s: %s", source, custom)
}