github.com/lacework-dev/go-moby@v20.10.12+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  	specs "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         *specs.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.ContainerCreateCreatedBody, 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  	c, err := create(ctx, t, client, ops...)
    52  	assert.NilError(t, err)
    53  
    54  	return c.ID
    55  }
    56  
    57  // CreateExpectingErr creates a container, expecting an error with the specified message
    58  func CreateExpectingErr(ctx context.Context, t *testing.T, client client.APIClient, errMsg string, ops ...func(*TestContainerConfig)) {
    59  	_, err := create(ctx, t, client, ops...)
    60  	assert.ErrorContains(t, err, errMsg)
    61  }
    62  
    63  // Run creates and start a container with the specified options
    64  func Run(ctx context.Context, t *testing.T, client client.APIClient, ops ...func(*TestContainerConfig)) string {
    65  	t.Helper()
    66  	id := Create(ctx, t, client, ops...)
    67  
    68  	err := client.ContainerStart(ctx, id, types.ContainerStartOptions{})
    69  	assert.NilError(t, err)
    70  
    71  	return id
    72  }