diff --git a/cli/command/builder/crossrepo_api_floor_test.go b/cli/command/builder/crossrepo_api_floor_test.go new file mode 100644 index 0000000..88c51dd --- /dev/null +++ b/cli/command/builder/crossrepo_api_floor_test.go @@ -0,0 +1,53 @@ +package builder + +import ( + "context" + "testing" + + "github.com/docker/cli/cli/command/system/pruner" + "github.com/docker/cli/internal/test" + "github.com/docker/cli/opts" + "github.com/moby/moby/client" + "gotest.tools/v3/assert" + is "gotest.tools/v3/assert/cmp" +) + +type crossRepoBuilderClient struct { + client.Client + version string + pruned int +} + +func (c *crossRepoBuilderClient) ClientVersion() string { return c.version } + +func (c *crossRepoBuilderClient) BuildCachePrune(context.Context, client.BuildCachePruneOptions) (client.BuildCachePruneResult, error) { + c.pruned++ + return client.BuildCachePruneResult{}, nil +} + +// FAIL_TO_PASS: build cache pruning (used by "docker system prune") no longer +// refuses daemons below API v1.31. + +func TestCrossRepoF2PBuilderPruneRunsBelowFloor(t *testing.T) { + apiClient := &crossRepoBuilderClient{version: "1.30"} + _, _, err := pruneFn(context.Background(), test.NewFakeCli(apiClient), pruner.PruneOptions{Confirmed: true, Filter: opts.NewFilterOpt()}) + assert.NilError(t, err) + assert.Check(t, is.Equal(apiClient.pruned, 1)) +} + +// PASS_TO_PASS + +func TestCrossRepoP2PBuilderPruneRequiresConfirmation(t *testing.T) { + apiClient := &crossRepoBuilderClient{version: client.MaxAPIVersion} + _, msg, err := pruneFn(context.Background(), test.NewFakeCli(apiClient), pruner.PruneOptions{All: true, Filter: opts.NewFilterOpt()}) + assert.Check(t, is.ErrorContains(err, "builder prune has been cancelled")) + assert.Check(t, is.Equal(msg, "all build cache")) + assert.Check(t, is.Equal(apiClient.pruned, 0)) +} + +func TestCrossRepoP2PBuilderPruneConfirmed(t *testing.T) { + apiClient := &crossRepoBuilderClient{version: client.MaxAPIVersion} + _, _, err := pruneFn(context.Background(), test.NewFakeCli(apiClient), pruner.PruneOptions{Confirmed: true, Filter: opts.NewFilterOpt()}) + assert.NilError(t, err) + assert.Check(t, is.Equal(apiClient.pruned, 1)) +} diff --git a/cli/command/container/crossrepo_api_floor_test.go b/cli/command/container/crossrepo_api_floor_test.go new file mode 100644 index 0000000..2f83ed5 --- /dev/null +++ b/cli/command/container/crossrepo_api_floor_test.go @@ -0,0 +1,102 @@ +package container + +import ( + "context" + "io" + "testing" + + "github.com/docker/cli/internal/test" + "github.com/moby/moby/api/types/container" + "github.com/moby/moby/api/types/network" + "github.com/moby/moby/client" + ocispec "github.com/opencontainers/image-spec/specs-go/v1" + "github.com/spf13/pflag" + "gotest.tools/v3/assert" + is "gotest.tools/v3/assert/cmp" +) + +type crossRepoContainerClient struct { + client.Client + version string + platforms []*ocispec.Platform +} + +func (c *crossRepoContainerClient) ClientVersion() string { return c.version } + +func (c *crossRepoContainerClient) ContainerCreate(_ context.Context, _ *container.Config, _ *container.HostConfig, _ *network.NetworkingConfig, platform *ocispec.Platform, _ string) (container.CreateResponse, error) { + c.platforms = append(c.platforms, platform) + return container.CreateResponse{ID: "container-id"}, nil +} + +func crossRepoCreate(t *testing.T, version, platform string) *crossRepoContainerClient { + t.Helper() + apiClient := &crossRepoContainerClient{version: version} + _, err := createContainer(context.Background(), test.NewFakeCli(apiClient), + &containerConfig{Config: &container.Config{Image: "busybox"}, HostConfig: &container.HostConfig{}}, + &createOptions{name: "name", platform: platform, untrusted: true, pull: PullImageMissing, quiet: true}, + ) + assert.NilError(t, err) + assert.Assert(t, is.Len(apiClient.platforms, 1)) + return apiClient +} + +func crossRepoParse(t *testing.T, args ...string) *containerConfig { + t.Helper() + flags := pflag.NewFlagSet("crossrepo", pflag.ContinueOnError) + flags.SetOutput(io.Discard) + copts := addFlags(flags) + assert.NilError(t, flags.Parse(append(args, "ubuntu", "bash"))) + cfg, err := parse(flags, copts, "linux") + assert.NilError(t, err) + return cfg +} + +// FAIL_TO_PASS + +func TestCrossRepoF2PCreateSendsPlatformBelowFloor(t *testing.T) { + apiClient := crossRepoCreate(t, "1.40", "linux/amd64") + got := apiClient.platforms[0] + assert.Assert(t, got != nil, "--platform must reach the create request on every supported API version") + assert.Check(t, is.Equal(got.OS, "linux")) + assert.Check(t, is.Equal(got.Architecture, "amd64")) +} + +func TestCrossRepoF2PParseDoesNotSetContainerWideMacAddress(t *testing.T) { + const mac = "92:d0:c6:0a:29:33" + cfg := crossRepoParse(t, "--mac-address", mac) + assert.Check(t, is.Equal(cfg.Config.MacAddress, ""), "the container-wide MacAddress is not populated for the legacy API") //nolint:staticcheck // deprecated field is the subject of this test + defaultNW := cfg.HostConfig.NetworkMode.NetworkName() + assert.Assert(t, cfg.NetworkingConfig.EndpointsConfig[defaultNW] != nil) + assert.Check(t, is.Equal(cfg.NetworkingConfig.EndpointsConfig[defaultNW].MacAddress, mac)) +} + +func TestCrossRepoF2PParseNetworkMacAddressStaysOnEndpoint(t *testing.T) { + const mac = "02:32:1c:23:00:04" + cfg := crossRepoParse(t, "--network", "name=net1,mac-address="+mac) + assert.Check(t, is.Equal(cfg.Config.MacAddress, "")) //nolint:staticcheck // deprecated field is the subject of this test + assert.Assert(t, cfg.NetworkingConfig.EndpointsConfig["net1"] != nil) + assert.Check(t, is.Equal(cfg.NetworkingConfig.EndpointsConfig["net1"].MacAddress, mac)) +} + +// PASS_TO_PASS + +func TestCrossRepoP2PCreateWithoutPlatform(t *testing.T) { + apiClient := crossRepoCreate(t, client.MaxAPIVersion, "") + assert.Check(t, apiClient.platforms[0] == nil) +} + +func TestCrossRepoP2PCreateSendsPlatformAtCurrentVersion(t *testing.T) { + apiClient := crossRepoCreate(t, client.MaxAPIVersion, "linux/arm64/v8") + got := apiClient.platforms[0] + assert.Assert(t, got != nil) + assert.Check(t, is.Equal(got.Architecture, "arm64")) + assert.Check(t, is.Equal(got.Variant, "v8")) +} + +func TestCrossRepoP2PParseMacAddressEndpoint(t *testing.T) { + const mac = "92:d0:c6:0a:29:33" + cfg := crossRepoParse(t, "--mac-address", mac) + defaultNW := cfg.HostConfig.NetworkMode.NetworkName() + assert.Assert(t, cfg.NetworkingConfig.EndpointsConfig[defaultNW] != nil) + assert.Check(t, is.Equal(cfg.NetworkingConfig.EndpointsConfig[defaultNW].MacAddress, mac)) +} diff --git a/cli/command/formatter/crossrepo_api_floor_test.go b/cli/command/formatter/crossrepo_api_floor_test.go new file mode 100644 index 0000000..143a4e9 --- /dev/null +++ b/cli/command/formatter/crossrepo_api_floor_test.go @@ -0,0 +1,38 @@ +package formatter + +import ( + "bytes" + "testing" + + "github.com/moby/moby/api/types/build" + "gotest.tools/v3/assert" + is "gotest.tools/v3/assert/cmp" +) + +func crossRepoRenderParent(t *testing.T, record *build.CacheRecord) string { + t.Helper() + var out bytes.Buffer + err := BuildCacheWrite(Context{Format: Format("{{.ID}}|{{.Parent}}"), Output: &out}, []*build.CacheRecord{record}) + assert.NilError(t, err) + return out.String() +} + +// FAIL_TO_PASS: the deprecated single "Parent" field (API < v1.42) is no +// longer used as a fallback when the daemon sends no "Parents". + +func TestCrossRepoF2PBuildCacheIgnoresDeprecatedParent(t *testing.T) { + got := crossRepoRenderParent(t, &build.CacheRecord{ID: "cache1", Parent: "legacy-parent"}) //nolint:staticcheck // deprecated field is the subject of this test + assert.Check(t, is.Equal(got, "cache1|\n")) +} + +// PASS_TO_PASS + +func TestCrossRepoP2PBuildCacheRendersParents(t *testing.T) { + got := crossRepoRenderParent(t, &build.CacheRecord{ID: "cache1", Parents: []string{"p1", "p2"}}) + assert.Check(t, is.Equal(got, "cache1|p1, p2\n")) +} + +func TestCrossRepoP2PBuildCacheWithoutParent(t *testing.T) { + got := crossRepoRenderParent(t, &build.CacheRecord{ID: "cache2"}) + assert.Check(t, is.Equal(got, "cache2|\n")) +} diff --git a/cli/command/service/crossrepo_api_floor_test.go b/cli/command/service/crossrepo_api_floor_test.go new file mode 100644 index 0000000..d400c0f --- /dev/null +++ b/cli/command/service/crossrepo_api_floor_test.go @@ -0,0 +1,208 @@ +package service + +import ( + "context" + "io" + "sync" + "testing" + + "github.com/docker/cli/internal/test" + "github.com/moby/moby/api/types/swarm" + "github.com/moby/moby/client" + "gotest.tools/v3/assert" + is "gotest.tools/v3/assert/cmp" +) + +// crossRepoAPIClient is a swarm daemon double that reports a fixed (possibly +// old) API version and records the requests the CLI sends to it. +type crossRepoAPIClient struct { + client.Client + version string + + mu sync.Mutex + services []swarm.Service + createOpts []client.ServiceCreateOptions + updateOpts []client.ServiceUpdateOptions + taskLists int + nodeLists int +} + +func (c *crossRepoAPIClient) ClientVersion() string { return c.version } + +func (c *crossRepoAPIClient) ServiceCreate(_ context.Context, _ swarm.ServiceSpec, opts client.ServiceCreateOptions) (swarm.ServiceCreateResponse, error) { + c.mu.Lock() + defer c.mu.Unlock() + c.createOpts = append(c.createOpts, opts) + return swarm.ServiceCreateResponse{ID: "svc-id"}, nil +} + +func (c *crossRepoAPIClient) ServiceInspectWithRaw(_ context.Context, id string, _ client.ServiceInspectOptions) (swarm.Service, []byte, error) { + return swarm.Service{ + ID: id, + Spec: swarm.ServiceSpec{ + Annotations: swarm.Annotations{Name: "svc"}, + TaskTemplate: swarm.TaskSpec{ContainerSpec: &swarm.ContainerSpec{Image: "busybox:latest"}}, + }, + PreviousSpec: &swarm.ServiceSpec{ + Annotations: swarm.Annotations{Name: "svc-previous"}, + TaskTemplate: swarm.TaskSpec{ContainerSpec: &swarm.ContainerSpec{Image: "busybox:previous"}}, + }, + }, []byte{}, nil +} + +func (c *crossRepoAPIClient) ServiceUpdate(_ context.Context, _ string, _ swarm.Version, _ swarm.ServiceSpec, opts client.ServiceUpdateOptions) (swarm.ServiceUpdateResponse, error) { + c.mu.Lock() + defer c.mu.Unlock() + c.updateOpts = append(c.updateOpts, opts) + return swarm.ServiceUpdateResponse{}, nil +} + +func (c *crossRepoAPIClient) ServiceList(context.Context, client.ServiceListOptions) ([]swarm.Service, error) { + out := make([]swarm.Service, len(c.services)) + copy(out, c.services) + return out, nil +} + +func (c *crossRepoAPIClient) TaskList(context.Context, client.TaskListOptions) ([]swarm.Task, error) { + c.mu.Lock() + defer c.mu.Unlock() + c.taskLists++ + return []swarm.Task{{ServiceID: "replicated-id", NodeID: "node-1", DesiredState: swarm.TaskStateRunning, Status: swarm.TaskStatus{State: swarm.TaskStateRunning}}}, nil +} + +func (c *crossRepoAPIClient) NodeList(context.Context, client.NodeListOptions) ([]swarm.Node, error) { + c.mu.Lock() + defer c.mu.Unlock() + c.nodeLists++ + return []swarm.Node{{ID: "node-1", Status: swarm.NodeStatus{State: swarm.NodeStateReady}}}, nil +} + +func crossRepoServices() []swarm.Service { + replicas := uint64(2) + return []swarm.Service{ + { + ID: "replicated-id", + Spec: swarm.ServiceSpec{ + Annotations: swarm.Annotations{Name: "replicated"}, + Mode: swarm.ServiceMode{Replicated: &swarm.ReplicatedService{Replicas: &replicas}}, + }, + }, + { + ID: "global-id", + Spec: swarm.ServiceSpec{ + Annotations: swarm.Annotations{Name: "global"}, + Mode: swarm.ServiceMode{Global: &swarm.GlobalService{}}, + }, + }, + } +} + +// FAIL_TO_PASS: the CLI no longer special-cases daemons below the API floor. + +func TestCrossRepoF2PServiceCreateQueriesRegistryBelowFloor(t *testing.T) { + apiClient := &crossRepoAPIClient{version: "1.29"} + cmd := newCreateCommand(test.NewFakeCli(apiClient)) + cmd.SetArgs([]string{"--detach=true", "busybox"}) + cmd.SetOut(io.Discard) + cmd.SetErr(io.Discard) + assert.NilError(t, cmd.Execute()) + assert.Assert(t, is.Len(apiClient.createOpts, 1)) + assert.Check(t, apiClient.createOpts[0].QueryRegistry, "service create must resolve the image through the daemon registry on every supported API version") +} + +func TestCrossRepoF2PServiceUpdateRollbackIsServerSideBelowFloor(t *testing.T) { + apiClient := &crossRepoAPIClient{version: "1.27"} + cmd := newUpdateCommand(test.NewFakeCli(apiClient)) + cmd.SetArgs([]string{"--rollback", "--detach=true", "svc"}) + cmd.SetOut(io.Discard) + cmd.SetErr(io.Discard) + assert.NilError(t, cmd.Execute()) + assert.Assert(t, is.Len(apiClient.updateOpts, 1)) + assert.Check(t, is.Equal(apiClient.updateOpts[0].Rollback, "previous")) + assert.Check(t, is.Equal(apiClient.updateOpts[0].RegistryAuthFrom, swarm.RegistryAuthFromSpec)) +} + +func TestCrossRepoF2PServiceUpdateQueriesRegistryBelowFloor(t *testing.T) { + apiClient := &crossRepoAPIClient{version: "1.29"} + cmd := newUpdateCommand(test.NewFakeCli(apiClient)) + cmd.SetArgs([]string{"--image=busybox:1.36", "--detach=true", "svc"}) + cmd.SetOut(io.Discard) + cmd.SetErr(io.Discard) + assert.NilError(t, cmd.Execute()) + assert.Assert(t, is.Len(apiClient.updateOpts, 1)) + assert.Check(t, apiClient.updateOpts[0].QueryRegistry, "service update --image must resolve the image through the daemon registry on every supported API version") +} + +func TestCrossRepoF2PServiceListTrustsDaemonStatus(t *testing.T) { + apiClient := &crossRepoAPIClient{version: "1.40", services: crossRepoServices()} + dockerCLI := test.NewFakeCli(apiClient) + cmd := newListCommand(dockerCLI) + cmd.SetArgs([]string{}) + cmd.SetOut(io.Discard) + cmd.SetErr(io.Discard) + assert.NilError(t, cmd.Execute()) + assert.Check(t, is.Equal(apiClient.taskLists, 0), "service ls must not rebuild service status from task lists") + assert.Check(t, is.Equal(apiClient.nodeLists, 0), "service ls must not rebuild service status from node lists") + assert.Check(t, is.Contains(dockerCLI.OutBuffer().String(), "replicated")) + assert.Check(t, is.Contains(dockerCLI.OutBuffer().String(), "global")) +} + +// PASS_TO_PASS: behaviour that is not a compatibility branch stays intact. + +func TestCrossRepoP2PServiceCreateNoResolveImage(t *testing.T) { + for name, tc := range map[string]struct { + args []string + want bool + }{ + "default": {args: []string{"--detach=true", "busybox"}, want: true}, + "no-resolve-image": {args: []string{"--detach=true", "--no-resolve-image", "busybox"}, want: false}, + } { + t.Run(name, func(t *testing.T) { + apiClient := &crossRepoAPIClient{version: client.MaxAPIVersion} + cmd := newCreateCommand(test.NewFakeCli(apiClient)) + cmd.SetArgs(tc.args) + cmd.SetOut(io.Discard) + cmd.SetErr(io.Discard) + assert.NilError(t, cmd.Execute()) + assert.Assert(t, is.Len(apiClient.createOpts, 1)) + assert.Check(t, is.Equal(apiClient.createOpts[0].QueryRegistry, tc.want)) + }) + } +} + +func TestCrossRepoP2PServiceUpdateRollbackRejectsOtherFlags(t *testing.T) { + apiClient := &crossRepoAPIClient{version: client.MaxAPIVersion} + cmd := newUpdateCommand(test.NewFakeCli(apiClient)) + cmd.SetArgs([]string{"--rollback", "--image=busybox:1.36", "--detach=true", "svc"}) + cmd.SetOut(io.Discard) + cmd.SetErr(io.Discard) + assert.ErrorContains(t, cmd.Execute(), "other flags may not be combined with --rollback") + assert.Check(t, is.Len(apiClient.updateOpts, 0)) +} + +func TestCrossRepoP2PServiceUpdateServerSideRollback(t *testing.T) { + apiClient := &crossRepoAPIClient{version: client.MaxAPIVersion} + cmd := newUpdateCommand(test.NewFakeCli(apiClient)) + cmd.SetArgs([]string{"--rollback", "--detach=true", "svc"}) + cmd.SetOut(io.Discard) + cmd.SetErr(io.Discard) + assert.NilError(t, cmd.Execute()) + assert.Assert(t, is.Len(apiClient.updateOpts, 1)) + assert.Check(t, is.Equal(apiClient.updateOpts[0].Rollback, "previous")) +} + +func TestCrossRepoP2PServiceListShowsDaemonProvidedStatus(t *testing.T) { + services := crossRepoServices() + services[0].ServiceStatus = &swarm.ServiceStatus{RunningTasks: 1, DesiredTasks: 2} + services[1].ServiceStatus = &swarm.ServiceStatus{RunningTasks: 3, DesiredTasks: 3} + apiClient := &crossRepoAPIClient{version: client.MaxAPIVersion, services: services} + dockerCLI := test.NewFakeCli(apiClient) + cmd := newListCommand(dockerCLI) + cmd.SetArgs([]string{"--format", "{{.Name}}={{.Replicas}}"}) + cmd.SetOut(io.Discard) + cmd.SetErr(io.Discard) + assert.NilError(t, cmd.Execute()) + out := dockerCLI.OutBuffer().String() + assert.Check(t, is.Contains(out, "replicated=1/2")) + assert.Check(t, is.Contains(out, "global=3/3")) +} diff --git a/cli/command/stack/crossrepo_api_floor_test.go b/cli/command/stack/crossrepo_api_floor_test.go new file mode 100644 index 0000000..931e07b --- /dev/null +++ b/cli/command/stack/crossrepo_api_floor_test.go @@ -0,0 +1,122 @@ +package stack + +import ( + "context" + "io" + "testing" + + "github.com/docker/cli/internal/test" + "github.com/moby/moby/api/types/network" + "github.com/moby/moby/api/types/swarm" + "github.com/moby/moby/client" + "gotest.tools/v3/assert" + is "gotest.tools/v3/assert/cmp" +) + +// crossRepoStackClient is a swarm daemon double that reports a fixed API +// version and holds one object of every kind that "docker stack rm" removes. +type crossRepoStackClient struct { + client.Client + version string + empty bool + removed map[string][]string +} + +func newCrossRepoStackClient(version string) *crossRepoStackClient { + return &crossRepoStackClient{version: version, removed: map[string][]string{}} +} + +func (c *crossRepoStackClient) ClientVersion() string { return c.version } + +func (c *crossRepoStackClient) ServiceList(context.Context, client.ServiceListOptions) ([]swarm.Service, error) { + if c.empty { + return nil, nil + } + return []swarm.Service{{ID: "svc-id", Spec: swarm.ServiceSpec{Annotations: swarm.Annotations{Name: "foo_svc"}}}}, nil +} + +func (c *crossRepoStackClient) NetworkList(context.Context, client.NetworkListOptions) ([]network.Summary, error) { + if c.empty { + return nil, nil + } + return []network.Summary{{Network: network.Network{ID: "net-id", Name: "foo_net"}}}, nil +} + +func (c *crossRepoStackClient) SecretList(context.Context, client.SecretListOptions) ([]swarm.Secret, error) { + if c.empty { + return nil, nil + } + return []swarm.Secret{{ID: "secret-id", Spec: swarm.SecretSpec{Annotations: swarm.Annotations{Name: "foo_secret"}}}}, nil +} + +func (c *crossRepoStackClient) ConfigList(context.Context, client.ConfigListOptions) ([]swarm.Config, error) { + if c.empty { + return nil, nil + } + return []swarm.Config{{ID: "config-id", Spec: swarm.ConfigSpec{Annotations: swarm.Annotations{Name: "foo_config"}}}}, nil +} + +func (c *crossRepoStackClient) ServiceRemove(_ context.Context, id string) error { + c.removed["service"] = append(c.removed["service"], id) + return nil +} + +func (c *crossRepoStackClient) NetworkRemove(_ context.Context, id string) error { + c.removed["network"] = append(c.removed["network"], id) + return nil +} + +func (c *crossRepoStackClient) SecretRemove(_ context.Context, id string) error { + c.removed["secret"] = append(c.removed["secret"], id) + return nil +} + +func (c *crossRepoStackClient) ConfigRemove(_ context.Context, id string) error { + c.removed["config"] = append(c.removed["config"], id) + return nil +} + +func crossRepoStackRemove(t *testing.T, apiClient *crossRepoStackClient) *test.FakeCli { + t.Helper() + dockerCLI := test.NewFakeCli(apiClient) + cmd := newRemoveCommand(dockerCLI) + cmd.SetArgs([]string{"foo"}) + cmd.SetOut(io.Discard) + cmd.SetErr(io.Discard) + assert.NilError(t, cmd.Execute()) + return dockerCLI +} + +// FAIL_TO_PASS: "docker stack rm" removes secrets and configs on every +// supported API version instead of skipping them for old daemons. + +func TestCrossRepoF2PStackRemoveRemovesSecretsBelowFloor(t *testing.T) { + apiClient := newCrossRepoStackClient("1.24") + crossRepoStackRemove(t, apiClient) + assert.Check(t, is.DeepEqual(apiClient.removed["secret"], []string{"secret-id"})) +} + +func TestCrossRepoF2PStackRemoveRemovesConfigsBelowFloor(t *testing.T) { + apiClient := newCrossRepoStackClient("1.29") + crossRepoStackRemove(t, apiClient) + assert.Check(t, is.DeepEqual(apiClient.removed["config"], []string{"config-id"})) +} + +// PASS_TO_PASS + +func TestCrossRepoP2PStackRemoveRemovesEverything(t *testing.T) { + apiClient := newCrossRepoStackClient(client.MaxAPIVersion) + crossRepoStackRemove(t, apiClient) + assert.Check(t, is.DeepEqual(apiClient.removed["service"], []string{"svc-id"})) + assert.Check(t, is.DeepEqual(apiClient.removed["network"], []string{"net-id"})) + assert.Check(t, is.DeepEqual(apiClient.removed["secret"], []string{"secret-id"})) + assert.Check(t, is.DeepEqual(apiClient.removed["config"], []string{"config-id"})) +} + +func TestCrossRepoP2PStackRemoveNothingFound(t *testing.T) { + apiClient := newCrossRepoStackClient(client.MaxAPIVersion) + apiClient.empty = true + dockerCLI := crossRepoStackRemove(t, apiClient) + assert.Check(t, is.Len(apiClient.removed, 0)) + assert.Check(t, is.Contains(dockerCLI.ErrBuffer().String(), "Nothing found in stack: foo")) +} diff --git a/cli/command/volume/crossrepo_api_floor_test.go b/cli/command/volume/crossrepo_api_floor_test.go new file mode 100644 index 0000000..b40c922 --- /dev/null +++ b/cli/command/volume/crossrepo_api_floor_test.go @@ -0,0 +1,77 @@ +package volume + +import ( + "context" + "io" + "testing" + + "github.com/docker/cli/internal/test" + "github.com/moby/moby/api/types/volume" + "github.com/moby/moby/client" + "gotest.tools/v3/assert" + is "gotest.tools/v3/assert/cmp" +) + +type crossRepoVolumeClient struct { + client.Client + filters []client.Filters +} + +func (c *crossRepoVolumeClient) VolumesPrune(_ context.Context, filter client.Filters) (volume.PruneReport, error) { + c.filters = append(c.filters, filter) + return volume.PruneReport{}, nil +} + +// crossRepoCLI reports a configurable API version through CurrentVersion, +// which is what "docker volume prune" consults. +type crossRepoCLI struct { + *test.FakeCli + version string +} + +func (c crossRepoCLI) CurrentVersion() string { return c.version } + +func crossRepoVolumePrune(t *testing.T, version string, args ...string) (*crossRepoVolumeClient, error) { + t.Helper() + apiClient := &crossRepoVolumeClient{} + cmd := newPruneCommand(crossRepoCLI{FakeCli: test.NewFakeCli(apiClient), version: version}) + cmd.SetArgs(args) + cmd.SetOut(io.Discard) + cmd.SetErr(io.Discard) + return apiClient, cmd.Execute() +} + +// FAIL_TO_PASS: "docker volume prune --all" always sends the all=true filter. + +func TestCrossRepoF2PVolumePruneAllFilterBelowFloor(t *testing.T) { + apiClient, err := crossRepoVolumePrune(t, "1.41", "--all", "--force") + assert.NilError(t, err) + assert.Assert(t, is.Len(apiClient.filters, 1)) + assert.Check(t, apiClient.filters[0]["all"]["true"], "filters sent to the daemon: %v", apiClient.filters[0]) +} + +func TestCrossRepoF2PVolumePruneAllConflictsWithFilterBelowFloor(t *testing.T) { + apiClient, err := crossRepoVolumePrune(t, "1.41", "--all", "--force", "--filter", "all=1") + assert.ErrorContains(t, err, "conflicting options: cannot specify both --all and --filter all=1") + assert.Check(t, is.Len(apiClient.filters, 0)) +} + +// PASS_TO_PASS + +func TestCrossRepoP2PVolumePruneFilters(t *testing.T) { + apiClient, err := crossRepoVolumePrune(t, client.MaxAPIVersion, "--force") + assert.NilError(t, err) + assert.Assert(t, is.Len(apiClient.filters, 1)) + _, hasAll := apiClient.filters[0]["all"] + assert.Check(t, !hasAll, "anonymous-only prune must not send an all filter: %v", apiClient.filters[0]) + + apiClient, err = crossRepoVolumePrune(t, client.MaxAPIVersion, "--all", "--force") + assert.NilError(t, err) + assert.Assert(t, is.Len(apiClient.filters, 1)) + assert.Check(t, apiClient.filters[0]["all"]["true"]) + + apiClient, err = crossRepoVolumePrune(t, client.MaxAPIVersion, "--force", "--filter", "label=keep") + assert.NilError(t, err) + assert.Assert(t, is.Len(apiClient.filters, 1)) + assert.Check(t, apiClient.filters[0]["label"]["keep"]) +} diff --git a/cli/compose/convert/crossrepo_api_floor_test.go b/cli/compose/convert/crossrepo_api_floor_test.go new file mode 100644 index 0000000..ac9050a --- /dev/null +++ b/cli/compose/convert/crossrepo_api_floor_test.go @@ -0,0 +1,51 @@ +package convert + +import ( + "context" + "testing" + + composetypes "github.com/docker/cli/cli/compose/types" + "github.com/moby/moby/client" + "gotest.tools/v3/assert" + is "gotest.tools/v3/assert/cmp" +) + +type crossRepoComposeClient struct { + client.Client + version string +} + +func (c *crossRepoComposeClient) ClientVersion() string { return c.version } + +func crossRepoConvert(t *testing.T, version string) (networks, legacyNetworks []string) { + t.Helper() + cfg := &composetypes.Config{Services: []composetypes.ServiceConfig{{Name: "web", Image: "busybox"}}} + specs, err := Services(context.Background(), Namespace{name: "foo"}, cfg, &crossRepoComposeClient{version: version}) + assert.NilError(t, err) + spec, ok := specs["web"] + assert.Assert(t, ok) + for _, nw := range spec.TaskTemplate.Networks { + networks = append(networks, nw.Target) + } + for _, nw := range spec.Networks { //nolint:staticcheck // deprecated field is the subject of this test + legacyNetworks = append(legacyNetworks, nw.Target) + } + return networks, legacyNetworks +} + +// FAIL_TO_PASS: stack networks are always attached through the task template; +// the deprecated ServiceSpec.Networks is not used for old daemons any more. + +func TestCrossRepoF2PComposeNetworksUseTaskTemplateBelowFloor(t *testing.T) { + networks, legacy := crossRepoConvert(t, "1.28") + assert.Check(t, is.DeepEqual(networks, []string{"foo_default"})) + assert.Check(t, is.Len(legacy, 0)) +} + +// PASS_TO_PASS + +func TestCrossRepoP2PComposeNetworksUseTaskTemplate(t *testing.T) { + networks, legacy := crossRepoConvert(t, client.MaxAPIVersion) + assert.Check(t, is.DeepEqual(networks, []string{"foo_default"})) + assert.Check(t, is.Len(legacy, 0)) +}