github.com/demonoid81/moby@v0.0.0-20200517203328-62dd8e17c460/integration/internal/container/container.go (about)

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