github.com/rawahars/moby@v24.0.4+incompatible/integration/internal/container/container.go (about) 1 package container 2 3 import ( 4 "context" 5 "runtime" 6 "testing" 7 8 "github.com/docker/docker/api/types" 9 "github.com/docker/docker/api/types/container" 10 "github.com/docker/docker/api/types/network" 11 "github.com/docker/docker/client" 12 ocispec "github.com/opencontainers/image-spec/specs-go/v1" 13 "gotest.tools/v3/assert" 14 ) 15 16 // TestContainerConfig holds container configuration struct that 17 // are used in api calls. 18 type TestContainerConfig struct { 19 Name string 20 Config *container.Config 21 HostConfig *container.HostConfig 22 NetworkingConfig *network.NetworkingConfig 23 Platform *ocispec.Platform 24 } 25 26 // create creates a container with the specified options 27 func create(ctx context.Context, t *testing.T, client client.APIClient, ops ...func(*TestContainerConfig)) (container.CreateResponse, error) { 28 t.Helper() 29 cmd := []string{"top"} 30 if runtime.GOOS == "windows" { 31 cmd = []string{"sleep", "240"} 32 } 33 config := &TestContainerConfig{ 34 Config: &container.Config{ 35 Image: "busybox", 36 Cmd: cmd, 37 }, 38 HostConfig: &container.HostConfig{}, 39 NetworkingConfig: &network.NetworkingConfig{}, 40 } 41 42 for _, op := range ops { 43 op(config) 44 } 45 46 return client.ContainerCreate(ctx, config.Config, config.HostConfig, config.NetworkingConfig, config.Platform, config.Name) 47 } 48 49 // Create creates a container with the specified options, asserting that there was no error 50 func Create(ctx context.Context, t *testing.T, client client.APIClient, ops ...func(*TestContainerConfig)) string { 51 t.Helper() 52 c, err := create(ctx, t, client, ops...) 53 assert.NilError(t, err) 54 55 return c.ID 56 } 57 58 // CreateExpectingErr creates a container, expecting an error with the specified message 59 func CreateExpectingErr(ctx context.Context, t *testing.T, client client.APIClient, errMsg string, ops ...func(*TestContainerConfig)) { 60 _, err := create(ctx, t, client, ops...) 61 assert.ErrorContains(t, err, errMsg) 62 } 63 64 // Run creates and start a container with the specified options 65 func Run(ctx context.Context, t *testing.T, client client.APIClient, ops ...func(*TestContainerConfig)) string { 66 t.Helper() 67 id := Create(ctx, t, client, ops...) 68 69 err := client.ContainerStart(ctx, id, types.ContainerStartOptions{}) 70 assert.NilError(t, err) 71 72 return id 73 }