cli/container_rename: Move to API validation

Signed-off-by: Paweł Gronowski <pawel.gronowski@docker.com>
This commit is contained in:
Paweł Gronowski
2025-10-30 00:06:27 +01:00
parent af255accaa
commit e636a2a069
3 changed files with 24 additions and 67 deletions

View File

@ -1,7 +1,6 @@
package container
import (
"errors"
"fmt"
"github.com/docker/cli/cli"
@ -19,10 +18,6 @@ func newRenameCommand(dockerCLI command.Cli) *cobra.Command {
Args: cli.ExactArgs(2),
RunE: func(cmd *cobra.Command, args []string) error {
oldName, newName := args[0], args[1]
if newName == "" {
// TODO(thaJeztah): remove once https://github.com/moby/moby/pull/51336 is merged and vendored.
return errors.New("new name cannot be blank")
}
_, err := dockerCLI.Client().ContainerRename(cmd.Context(), oldName, client.ContainerRenameOptions{
NewName: newName,
})

View File

@ -1,62 +0,0 @@
package container
import (
"context"
"errors"
"io"
"testing"
"github.com/docker/cli/internal/test"
"gotest.tools/v3/assert"
)
func TestRunRename(t *testing.T) {
testcases := []struct {
doc, oldName, newName, expectedErr string
}{
{
doc: "success",
oldName: "oldName",
newName: "newName",
expectedErr: "",
},
{
doc: "empty old name",
oldName: "",
newName: "newName",
expectedErr: "invalid container name or ID: value is empty",
},
{
doc: "empty new name",
oldName: "oldName",
newName: "",
expectedErr: "new name cannot be blank",
},
}
for _, tc := range testcases {
t.Run(tc.doc, func(t *testing.T) {
cli := test.NewFakeCli(&fakeClient{
containerRenameFunc: func(ctx context.Context, oldName, newName string) error {
if oldName == "" {
return errors.New("invalid container name or ID: value is empty")
}
return nil
},
})
cmd := newRenameCommand(cli)
cmd.SetOut(io.Discard)
cmd.SetErr(io.Discard)
cmd.SetArgs([]string{tc.oldName, tc.newName})
err := cmd.Execute()
if tc.expectedErr != "" {
assert.ErrorContains(t, err, tc.expectedErr)
} else {
assert.NilError(t, err)
}
})
}
}

View File

@ -26,3 +26,27 @@ func TestContainerRename(t *testing.T) {
res.Assert(t, icmd.Success)
assert.Equal(t, "/"+newName, strings.TrimSpace(res.Stdout()))
}
func TestContainerRenameEmptyOldName(t *testing.T) {
res := icmd.RunCommand("docker", "container", "rename", "", "newName")
res.Assert(t, icmd.Expected{
ExitCode: 1,
Err: "invalid container name or ID: value is empty",
})
}
func TestContainerRenameEmptyNewName(t *testing.T) {
oldName := "old_name_" + t.Name()
res := icmd.RunCommand("docker", "run", "-d", "--name", oldName, fixtures.AlpineImage, "sleep", "60")
res.Assert(t, icmd.Success)
cID := strings.TrimSpace(res.Stdout())
t.Cleanup(func() {
icmd.RunCommand("docker", "container", "rm", "-f", cID).Assert(t, icmd.Success)
})
res = icmd.RunCommand("docker", "container", "rename", oldName, "")
res.Assert(t, icmd.Expected{
ExitCode: 1,
Err: "new name cannot be blank",
})
}