compose/pkg/compose/start_test.go
Nicolas De Loof 280f6a454d
Some checks are pending
ci / validate (lint) (push) Waiting to run
ci / validate (relay-lint) (push) Waiting to run
ci / validate (relay-test) (push) Waiting to run
ci / validate (validate-docs) (push) Waiting to run
ci / validate (validate-go-mod) (push) Waiting to run
ci / validate (validate-headers) (push) Waiting to run
ci / validate (validate-mocks) (push) Waiting to run
ci / binary (push) Waiting to run
ci / binary-finalize (push) Blocked by required conditions
ci / bin-image-test (push) Waiting to run
ci / relay-image-test (push) Waiting to run
ci / test (push) Waiting to run
ci / e2e (plugin, oldstable, graphdriver) (push) Waiting to run
ci / e2e (standalone, oldstable, graphdriver) (push) Waiting to run
ci / e2e (plugin, stable, containerd) (push) Waiting to run
ci / e2e (plugin, stable, graphdriver) (push) Waiting to run
ci / e2e (standalone, stable, containerd) (push) Waiting to run
ci / e2e (standalone, stable, graphdriver) (push) Waiting to run
ci / coverage (push) Blocked by required conditions
ci / ci-ok (push) Blocked by required conditions
ci / release (push) Blocked by required conditions
merge / bin-image-prepare (push) Waiting to run
merge / bin-image (push) Blocked by required conditions
merge / relay-image (push) Waiting to run
merge / module-image (push) Waiting to run
Scorecards supply-chain security / Scorecards analysis (push) Waiting to run
zizmor / zizmor (push) Waiting to run
test(start): pin how start() wires its plan and the provider start path
Cover what the removed imperative tests used to: a no-op start is silent and
only lists containers, --wait-timeout bounds the dependency waits, secrets and
configs are injected before ContainerStart, a failing post_start fails the
start, pre_start is skipped on a stale relay, deploy.replicas: 0 starts
nothing, and the project-wide no-container check. On the provider path: the
restart is a chain end, a relay gets no post_start, pre_start is gated on
running replicas and runs once, before the chain, after the dependencies.

Signed-off-by: Nicolas De Loof <nicolas.deloof@gmail.com>
2026-10-16 10:52:52 +02:00

209 lines
8 KiB
Go

//go:build !windows
/*
Copyright 2020 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 (
"context"
"strconv"
"sync"
"testing"
"time"
"github.com/compose-spec/compose-go/v2/types"
"github.com/docker/cli/cli/config/configfile"
"github.com/moby/moby/api/types/container"
"github.com/moby/moby/client"
"go.uber.org/mock/gomock"
"gotest.tools/v3/assert"
"github.com/docker/compose/v5/pkg/api"
"github.com/docker/compose/v5/pkg/mocks"
)
// recordingEventProcessor captures progress events for sequence assertions.
// Shared by tests elsewhere in the package that exercise a single container
// operation in isolation (e.g. stopContainer's relay guard in down_test.go).
type recordingEventProcessor struct {
mu sync.Mutex
events []api.Resource
}
func (r *recordingEventProcessor) Start(context.Context, string) {}
func (r *recordingEventProcessor) On(events ...api.Resource) {
r.mu.Lock()
defer r.mu.Unlock()
r.events = append(r.events, events...)
}
func (r *recordingEventProcessor) Done(string, bool) {}
// summary renders recorded events as "ID: Text" strings.
func (r *recordingEventProcessor) summary() []string {
r.mu.Lock()
defer r.mu.Unlock()
out := make([]string, 0, len(r.events))
for _, e := range r.events {
out = append(out, e.ID+": "+e.Text)
}
return out
}
func (r *recordingEventProcessor) contains(entry string) bool {
for _, e := range r.summary() {
if e == entry {
return true
}
}
return false
}
// newStartTestService builds a composeService on gomock with a recording
// event processor. Any API call without a matching expectation fails the test,
// so "no expectation" doubles as a "no daemon interaction" assertion.
func newStartTestService(t *testing.T) (*composeService, *mocks.MockAPIClient, *recordingEventProcessor) {
t.Helper()
mockCtrl := gomock.NewController(t)
t.Cleanup(mockCtrl.Finish)
apiClient := mocks.NewMockAPIClient(mockCtrl)
cli := mocks.NewMockCli(mockCtrl)
cli.EXPECT().Client().Return(apiClient).AnyTimes()
apiClient.EXPECT().Ping(gomock.Any(), client.PingOptions{NegotiateAPIVersion: true}).
Return(client.PingResult{APIVersion: "1.44"}, nil).AnyTimes()
apiClient.EXPECT().ClientVersion().Return("1.44").AnyTimes()
// the generic pre_start inheritance goes through getCreateConfigs, which
// reads the CLI configuration and the daemon host
cli.EXPECT().ConfigFile().Return(&configfile.ConfigFile{}).AnyTimes()
apiClient.EXPECT().DaemonHost().Return("unix:///var/run/docker.sock").AnyTimes()
rec := &recordingEventProcessor{}
svc, err := NewComposeService(cli, WithEventProcessor(rec))
assert.NilError(t, err)
return svc.(*composeService), apiClient, rec
}
// serviceContainer builds a running container summary the way the daemon
// reports a project's first replica: canonical name, service and
// container-number labels.
func serviceContainer(service string) container.Summary {
name := "prj-" + service + "-1"
return container.Summary{
ID: name + "-id",
Names: []string{"/" + name},
State: container.StateRunning,
Labels: map[string]string{
api.ServiceLabel: service,
api.ContainerNumberLabel: "1",
},
}
}
// stoppedServiceContainer builds a container summary of the given state for
// replica num of service, carrying the labels collectObservedState reads.
func stoppedServiceContainer(service string, num int, state container.ContainerState) container.Summary {
ctr := serviceContainer(service)
name := "prj-" + service + "-" + strconv.Itoa(num)
ctr.ID = name + "-id"
ctr.Names = []string{"/" + name}
ctr.State = state
ctr.Labels[api.ProjectLabel] = "prj"
ctr.Labels[api.ContainerNumberLabel] = strconv.Itoa(num)
return ctr
}
// TestStart_NoOpStartIsSilentAndOnlyListsContainers pins how start() wires
// its plan: the observation is scoped to Start (only the container listing
// reaches the daemon -- gomock fails on any network or volume listing), the
// plan is start-only, and a no-op start (everything already running) starts
// nothing and emits no event, not even the synthetic "Running" ones
// up/create report.
func TestStart_NoOpStartIsSilentAndOnlyListsContainers(t *testing.T) {
svc, apiClient, rec := newStartTestService(t)
web := types.ServiceConfig{Name: "web", ContainerSpec: types.ContainerSpec{Image: "alpine"}}
project := &types.Project{Name: "prj", Services: types.Services{"web": web}}
apiClient.EXPECT().ContainerList(gomock.Any(), gomock.Any()).
Return(client.ContainerListResult{Items: []container.Summary{
stoppedServiceContainer("web", 1, container.StateRunning),
}}, nil)
err := svc.start(t.Context(), "prj", api.StartOptions{Project: project}, nil)
assert.NilError(t, err)
assert.Equal(t, len(rec.summary()), 0, "a no-op start must be silent: %v", rec.summary())
}
// TestStart_WaitTimeoutBoundsDependencyWaits pins that start() hands
// StartOptions.WaitTimeout to the executor: --wait-timeout bounds a
// depends_on wait even without --wait, and expiring reports the dependency
// timeout while the dependent is never started.
func TestStart_WaitTimeoutBoundsDependencyWaits(t *testing.T) {
svc, apiClient, _ := newStartTestService(t)
db := types.ServiceConfig{Name: "db", ContainerSpec: types.ContainerSpec{Image: "alpine"}}
db.HealthCheck = &types.HealthCheckConfig{Test: []string{"CMD", "true"}}
web := types.ServiceConfig{Name: "web", ContainerSpec: types.ContainerSpec{Image: "alpine"}}
web.DependsOn = types.DependsOnConfig{"db": {Condition: types.ServiceConditionHealthy, Required: true}}
project := &types.Project{Name: "prj", Services: types.Services{"db": db, "web": web}}
dbCtr := stoppedServiceContainer("db", 1, container.StateRunning)
apiClient.EXPECT().ContainerList(gomock.Any(), gomock.Any()).
Return(client.ContainerListResult{Items: []container.Summary{
dbCtr,
stoppedServiceContainer("web", 1, container.StateExited),
}}, nil)
// db never becomes healthy; no ContainerStart expectation for web
apiClient.EXPECT().ContainerInspect(gomock.Any(), dbCtr.ID, gomock.Any()).
Return(client.ContainerInspectResult{Container: container.InspectResponse{
ID: dbCtr.ID,
Name: "/prj-db-1",
State: &container.State{
Status: container.StateRunning,
Health: &container.Health{Status: container.Starting},
},
Config: &container.Config{Healthcheck: &container.HealthConfig{Test: []string{"CMD", "true"}}},
}}, nil).AnyTimes()
// the outer deadline only turns a missing wait-timeout into a prompt
// failure instead of a hang
ctx, cancel := context.WithTimeout(t.Context(), 10*time.Second)
defer cancel()
err := svc.start(ctx, "prj", api.StartOptions{Project: project, WaitTimeout: 200 * time.Millisecond}, nil)
assert.Error(t, err, "timeout waiting for dependencies")
}
// TestGetDependencyCondition locks the --wait condition selection: a service
// that others depend on with service_completed_successfully is waited on with
// that condition (or --wait would hang on one-shot services), anything else
// with running_or_healthy.
func TestGetDependencyCondition(t *testing.T) {
oneShot := types.ServiceConfig{Name: "migrate"}
web := types.ServiceConfig{
Name: "web", WorkloadSpec: types.WorkloadSpec{DependsOn: types.DependsOnConfig{
"migrate": {Condition: types.ServiceConditionCompletedSuccessfully},
}},
}
project := &types.Project{
Name: "prj",
Services: types.Services{"web": web, "migrate": oneShot},
}
assert.Equal(t, getDependencyCondition(oneShot, project), types.ServiceConditionCompletedSuccessfully)
assert.Equal(t, getDependencyCondition(web, project), ServiceConditionRunningOrHealthy)
}