compose/pkg/compose/image_pruner_test.go
Nicolas De Loof aab5848391 test(down): cover ImagesToPrune's own invalid-mode rejection
down() validates options.Images upfront, but ImagePruner is exported
and can be driven directly with a hand-built ImagePruneOptions that
bypasses that check. Add a direct test for the Valid() guard added in
the previous commit, so the two checks can't silently drift without a
test catching it.

Signed-off-by: Nicolas De Loof <nicolas.deloof@gmail.com>
2026-10-06 11:31:22 +02:00

148 lines
6.6 KiB
Go

/*
Copyright 2026 Docker Compose CLI authors
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.
*/
package compose
import (
"testing"
"github.com/compose-spec/compose-go/v2/types"
"github.com/containerd/errdefs"
"github.com/moby/moby/api/types/image"
"github.com/moby/moby/client"
"go.uber.org/mock/gomock"
"gotest.tools/v3/assert"
)
// TestRemoveDanglingImages_FiltersKeepsAndToleratesFailures guards the
// shared helper used by both `down --rmi` and `watch --prune`: images the
// keep predicate spares must never be removed; an image already gone (a
// benign race with something else removing it concurrently) or still in
// use (the same tolerance removeResource already gives a tagged image in
// the same situation) is tolerated and not reported as a failure; a
// genuine removal error doesn't stop the others, but is joined into the
// returned error (preserving the actual daemon error, not just the image
// ID) for callers that need to surface it.
func TestRemoveDanglingImages_FiltersKeepsAndToleratesFailures(t *testing.T) {
mockCtrl := gomock.NewController(t)
defer mockCtrl.Finish()
apiClient, cli := prepareMocks(mockCtrl)
svcIface, err := NewComposeService(cli)
assert.NilError(t, err)
svc := svcIface.(*composeService)
apiClient.EXPECT().ImageList(gomock.Any(), client.ImageListOptions{
Filters: projectFilter("prj").Add("dangling", "true"),
}).Return(client.ImageListResult{Items: []image.Summary{
{ID: "sha256:keep"},
{ID: "sha256:removed"},
{ID: "sha256:already-gone"},
{ID: "sha256:in-use"},
{ID: "sha256:fails"},
}}, nil)
apiClient.EXPECT().ImageRemove(gomock.Any(), "sha256:removed", client.ImageRemoveOptions{}).
Return(client.ImageRemoveResult{}, nil)
apiClient.EXPECT().ImageRemove(gomock.Any(), "sha256:already-gone", client.ImageRemoveOptions{}).
Return(client.ImageRemoveResult{}, errdefs.ErrNotFound.WithMessage("already removed"))
apiClient.EXPECT().ImageRemove(gomock.Any(), "sha256:in-use", client.ImageRemoveOptions{}).
Return(client.ImageRemoveResult{}, errdefs.ErrConflict.WithMessage("image is being used"))
apiClient.EXPECT().ImageRemove(gomock.Any(), "sha256:fails", client.ImageRemoveOptions{}).
Return(client.ImageRemoveResult{}, errdefs.ErrPermissionDenied.WithMessage("permission denied"))
// no expectation for "sha256:keep" — a call to ImageRemove for it fails the test
keep := func(img image.Summary) bool { return img.ID == "sha256:keep" }
removed, err := svc.removeDanglingImages(t.Context(), "prj", keep)
assert.DeepEqual(t, removed, []string{"sha256:removed"})
assert.ErrorContains(t, err, "sha256:fails")
assert.ErrorContains(t, err, "permission denied")
}
// TestRemoveImages_BucketsStillInUseSeparatelyFromRemoved guards a
// regression caught by review: an image still in use (goal NOT achieved)
// must land in its own return bucket, not be folded into removed — a caller
// aggregating several images (removeDanglingImagesOp) needs the distinction
// to report the batch honestly. An already-gone image reaches the goal like
// an actual removal and a genuine failure is joined into err, so neither is
// exercised here beyond not corrupting the removed/stillInUse buckets.
func TestRemoveImages_BucketsStillInUseSeparatelyFromRemoved(t *testing.T) {
mockCtrl := gomock.NewController(t)
defer mockCtrl.Finish()
apiClient, cli := prepareMocks(mockCtrl)
svcIface, err := NewComposeService(cli)
assert.NilError(t, err)
svc := svcIface.(*composeService)
images := []image.Summary{
{ID: "sha256:removed"},
{ID: "sha256:already-gone"},
{ID: "sha256:in-use"},
{ID: "sha256:fails"},
}
apiClient.EXPECT().ImageRemove(gomock.Any(), "sha256:removed", client.ImageRemoveOptions{}).
Return(client.ImageRemoveResult{}, nil)
apiClient.EXPECT().ImageRemove(gomock.Any(), "sha256:already-gone", client.ImageRemoveOptions{}).
Return(client.ImageRemoveResult{}, errdefs.ErrNotFound.WithMessage("already removed"))
apiClient.EXPECT().ImageRemove(gomock.Any(), "sha256:in-use", client.ImageRemoveOptions{}).
Return(client.ImageRemoveResult{}, errdefs.ErrConflict.WithMessage("image is being used"))
apiClient.EXPECT().ImageRemove(gomock.Any(), "sha256:fails", client.ImageRemoveOptions{}).
Return(client.ImageRemoveResult{}, errdefs.ErrPermissionDenied.WithMessage("permission denied"))
removed, stillInUse, err := svc.removeImages(t.Context(), images, nil)
assert.DeepEqual(t, removed, []string{"sha256:removed"})
assert.DeepEqual(t, stillInUse, []string{"sha256:in-use"})
assert.ErrorContains(t, err, "sha256:fails")
assert.ErrorContains(t, err, "permission denied")
}
// TestRemoveDanglingImages_NoneFound guards that an empty dangling-image
// list is a no-op: no removal calls, no error.
func TestRemoveDanglingImages_NoneFound(t *testing.T) {
mockCtrl := gomock.NewController(t)
defer mockCtrl.Finish()
apiClient, cli := prepareMocks(mockCtrl)
svcIface, err := NewComposeService(cli)
assert.NilError(t, err)
svc := svcIface.(*composeService)
apiClient.EXPECT().ImageList(gomock.Any(), client.ImageListOptions{
Filters: projectFilter("prj").Add("dangling", "true"),
}).Return(client.ImageListResult{}, nil)
removed, err := svc.removeDanglingImages(t.Context(), "prj", func(image.Summary) bool { return false })
assert.NilError(t, err)
assert.Equal(t, len(removed), 0)
}
// TestImagesToPrune_RejectsInvalidMode guards the one check ImagesToPrune
// still makes on its own: down() validates options.Images upfront (see
// TestDownRejectsInvalidImagePruneModeUpfront), but ImagePruner is exported
// and can be driven directly with a hand-built ImagePruneOptions that
// bypasses that check — this is the defense-in-depth path Valid() must
// still reject. No API client call is expected: an invalid mode must be
// rejected before any engine call is made.
func TestImagesToPrune_RejectsInvalidMode(t *testing.T) {
mockCtrl := gomock.NewController(t)
defer mockCtrl.Finish()
apiClient, _ := prepareMocks(mockCtrl)
pruner := NewImagePruner(apiClient, &types.Project{Name: "prj"}, nil)
_, err := pruner.ImagesToPrune(t.Context(), ImagePruneOptions{Mode: ImagePruneMode("bogus")})
assert.ErrorContains(t, err, "unsupported image prune mode: bogus")
}