testcontainers

package module
v0.0.0-...-79823b6 Latest Latest
Warning

This package is not in the latest version of its module.

Go to latest
Published: Sep 8, 2023 License: MIT Imports: 46 Imported by: 0

README

Testcontainers

Open in GitHub Codespaces

Main pipeline Go Report Card GoDoc Reference

Testcontainers for Go is a Go package that makes it simple to create and clean up container-based dependencies for automated integration/smoke tests. The clean, easy-to-use API enables developers to programmatically define containers that should be run as part of a test and clean up those resources when the test is done.

You can find more information about Testcontainers for Go at golang.testcontainers.org, which is rendered from the ./docs directory.

Using Testcontainers for Go

Please visit the quickstart guide to understand how to add the dependency to your Go project.

Documentation

Index

Examples

Constants

View Source
const (
	Bridge        = "bridge" // Bridge network name (as well as driver)
	Podman        = "podman"
	ReaperDefault = "reaper_default" // Default network name when bridge is not available

)
View Source
const (
	// Deprecated: it has been replaced by the internal testcontainersdocker.LabelLang
	TestcontainerLabel = "org.testcontainers.golang"
	// Deprecated: it has been replaced by the internal testcontainersdocker.LabelSessionID
	TestcontainerLabelSessionID = TestcontainerLabel + ".sessionId"
	// Deprecated: it has been replaced by the internal testcontainersdocker.LabelReaper
	TestcontainerLabelIsReaper = TestcontainerLabel + ".reaper"

	ReaperDefaultImage = "docker.io/testcontainers/ryuk:0.5.1"
)
View Source
const StderrLog = "STDERR"

StderrLog is the log type for STDERR

View Source
const StdoutLog = "STDOUT"

StdoutLog is the log type for STDOUT

Variables

View Source
var (
	ErrDuplicateMountTarget   = errors.New("duplicate mount target detected")
	ErrContainerAlreadyExists = errors.New("container already exists")
)
View Source
var DefaultLoggingHook = func(logger Logging) ContainerLifecycleHooks {
	shortContainerID := func(c Container) string {
		return c.GetContainerID()[:12]
	}

	return ContainerLifecycleHooks{
		PreCreates: []ContainerRequestHook{
			func(ctx context.Context, req ContainerRequest) error {
				logger.Printf("🐳 Creating container for image %s", req.Image)
				return nil
			},
		},
		PostCreates: []ContainerHook{
			func(ctx context.Context, c Container) error {
				logger.Printf("✅ Container created: %s", shortContainerID(c))
				return nil
			},
		},
		PreStarts: []ContainerHook{
			func(ctx context.Context, c Container) error {
				logger.Printf("🐳 Starting container: %s", shortContainerID(c))
				return nil
			},
		},
		PostStarts: []ContainerHook{
			func(ctx context.Context, c Container) error {
				logger.Printf("✅ Container started: %s", shortContainerID(c))
				return nil
			},
		},
		PreStops: []ContainerHook{
			func(ctx context.Context, c Container) error {
				logger.Printf("🐳 Stopping container: %s", shortContainerID(c))
				return nil
			},
		},
		PostStops: []ContainerHook{
			func(ctx context.Context, c Container) error {
				logger.Printf("✋ Container stopped: %s", shortContainerID(c))
				return nil
			},
		},
		PreTerminates: []ContainerHook{
			func(ctx context.Context, c Container) error {
				logger.Printf("🐳 Terminating container: %s", shortContainerID(c))
				return nil
			},
		},
		PostTerminates: []ContainerHook{
			func(ctx context.Context, c Container) error {
				logger.Printf("🚫 Container terminated: %s", shortContainerID(c))
				return nil
			},
		},
	}
}
View Source
var (
	ErrReuseEmptyName = errors.New("with reuse option a container name mustn't be empty")
)

Functions

func DockerImageAuth

func DockerImageAuth(ctx context.Context, image string) (string, registry.AuthConfig, error)

DockerImageAuth returns the auth config for the given Docker image, extracting first its Docker registry. Finally, it will use the credential helpers to extract the information from the docker config file for that registry, if it exists.

func LogDockerServerInfo deprecated

func LogDockerServerInfo(ctx context.Context, client client.APIClient, logger Logging)

Deprecated: this function will be removed in a future release LogDockerServerInfo logs the docker server info using the provided logger and Docker client

func NewDockerClient deprecated

func NewDockerClient() (*client.Client, error)

Deprecated: Use NewDockerClientWithOpts instead.

func SkipIfDockerDesktop

func SkipIfDockerDesktop(t *testing.T, ctx context.Context)

SkipIfDockerDesktop is a utility function capable of skipping tests if tests are run using Docker Desktop.

func SkipIfProviderIsNotHealthy

func SkipIfProviderIsNotHealthy(t *testing.T)

SkipIfProviderIsNotHealthy is a utility function capable of skipping tests if the provider is not healthy, or running at all. This is a function designed to be used in your test, when Docker is not mandatory for CI/CD. In this way tests that depend on Testcontainers won't run if the provider is provisioned correctly.

Example
SkipIfProviderIsNotHealthy(&testing.T{})
Output:

Types

type BindMounter

type BindMounter interface {
	GetBindOptions() *mount.BindOptions
}

BindMounter can optionally be implemented by mount sources to support advanced scenarios based on mount.BindOptions

type Container

type Container interface {
	GetContainerID() string                                         // get the container id from the provider
	Endpoint(context.Context, string) (string, error)               // get proto://ip:port string for the first exposed port
	PortEndpoint(context.Context, nat.Port, string) (string, error) // get proto://ip:port string for the given exposed port
	Host(context.Context) (string, error)                           // get host where the container port is exposed
	MappedPort(context.Context, nat.Port) (nat.Port, error)         // get externally mapped port for a container port
	Ports(context.Context) (nat.PortMap, error)                     // get all exposed ports
	SessionID() string                                              // get session id
	IsRunning() bool
	Start(context.Context) error                 // start the container
	Stop(context.Context, *time.Duration) error  // stop the container
	Terminate(context.Context) error             // terminate the container
	Logs(context.Context) (io.ReadCloser, error) // Get logs of the container
	FollowOutput(LogConsumer)
	StartLogProducer(context.Context) error
	StopLogProducer() error
	Name(context.Context) (string, error)                        // get container name
	State(context.Context) (*types.ContainerState, error)        // returns container's running state
	Networks(context.Context) ([]string, error)                  // get container networks
	NetworkAliases(context.Context) (map[string][]string, error) // get container network aliases for a network
	Exec(ctx context.Context, cmd []string, options ...tcexec.ProcessOption) (int, io.Reader, error)
	ContainerIP(context.Context) (string, error)    // get container ip
	ContainerIPs(context.Context) ([]string, error) // get all container IPs
	CopyToContainer(ctx context.Context, fileContent []byte, containerFilePath string, fileMode int64) error
	CopyDirToContainer(ctx context.Context, hostDirPath string, containerParentPath string, fileMode int64) error
	CopyFileToContainer(ctx context.Context, hostFilePath string, containerFilePath string, fileMode int64) error
	CopyFileFromContainer(ctx context.Context, filePath string) (io.ReadCloser, error)
}

Container allows getting info about and controlling a single container instance

func GenericContainer

func GenericContainer(ctx context.Context, req GenericContainerRequest) (Container, error)

GenericContainer creates a generic container with parameters

func ParallelContainers

func ParallelContainers(ctx context.Context, reqs ParallelContainerRequest, opt ParallelContainersOptions) ([]Container, error)

ParallelContainers creates a generic containers with parameters and run it in parallel mode

type ContainerCustomizer

type ContainerCustomizer interface {
	Customize(req *GenericContainerRequest)
}

ContainerCustomizer is an interface that can be used to configure the Testcontainers container request. The passed request will be merged with the default one.

type ContainerFile

type ContainerFile struct {
	HostFilePath      string
	ContainerFilePath string
	FileMode          int64
}

type ContainerHook

type ContainerHook func(ctx context.Context, container Container) error

ContainerHook is a hook that will be called after a container is created It can be used to modify the state of the container after it is created, using the different lifecycle hooks that are available: - Created - Starting - Started - Stopping - Stopped - Terminating - Terminated For that, it will receive a Container, modify it and return an error if needed.

type ContainerLifecycleHooks

type ContainerLifecycleHooks struct {
	PreCreates     []ContainerRequestHook
	PostCreates    []ContainerHook
	PreStarts      []ContainerHook
	PostStarts     []ContainerHook
	PreStops       []ContainerHook
	PostStops      []ContainerHook
	PreTerminates  []ContainerHook
	PostTerminates []ContainerHook
}

ContainerLifecycleHooks is a struct that contains all the hooks that can be used to modify the container lifecycle. All the container lifecycle hooks except the PreCreates hooks will be passed to the container once it's created

func (ContainerLifecycleHooks) Created

func (c ContainerLifecycleHooks) Created(ctx context.Context) func(container Container) error

Created is a hook that will be called after a container is created

func (ContainerLifecycleHooks) Creating

func (c ContainerLifecycleHooks) Creating(ctx context.Context) func(req ContainerRequest) error

Creating is a hook that will be called before a container is created.

func (ContainerLifecycleHooks) Started

func (c ContainerLifecycleHooks) Started(ctx context.Context) func(container Container) error

Started is a hook that will be called after a container is started

func (ContainerLifecycleHooks) Starting

func (c ContainerLifecycleHooks) Starting(ctx context.Context) func(container Container) error

Starting is a hook that will be called before a container is started

func (ContainerLifecycleHooks) Stopped

func (c ContainerLifecycleHooks) Stopped(ctx context.Context) func(container Container) error

Stopped is a hook that will be called after a container is stopped

func (ContainerLifecycleHooks) Stopping

func (c ContainerLifecycleHooks) Stopping(ctx context.Context) func(container Container) error

Stopping is a hook that will be called before a container is stopped

func (ContainerLifecycleHooks) Terminated

func (c ContainerLifecycleHooks) Terminated(ctx context.Context) func(container Container) error

Terminated is a hook that will be called after a container is terminated

func (ContainerLifecycleHooks) Terminating

func (c ContainerLifecycleHooks) Terminating(ctx context.Context) func(container Container) error

Terminating is a hook that will be called before a container is terminated

type ContainerMount

type ContainerMount struct {
	// Source is typically either a GenericBindMountSource or a GenericVolumeMountSource
	Source ContainerMountSource
	// Target is the path where the mount should be mounted within the container
	Target ContainerMountTarget
	// ReadOnly determines if the mount should be read-only
	ReadOnly bool
}

ContainerMount models a mount into a container

func BindMount

func BindMount(hostPath string, mountTarget ContainerMountTarget) ContainerMount

BindMount returns a new ContainerMount with a GenericBindMountSource as source This is a convenience method to cover typical use cases.

func VolumeMount

func VolumeMount(volumeName string, mountTarget ContainerMountTarget) ContainerMount

VolumeMount returns a new ContainerMount with a GenericVolumeMountSource as source This is a convenience method to cover typical use cases.

type ContainerMountSource

type ContainerMountSource interface {
	// Source will be used as Source field in the final mount
	// this might either be a volume name, a host path or might be empty e.g. for Tmpfs
	Source() string

	// Type determines the final mount type
	// possible options are limited by the Docker API
	Type() MountType
}

ContainerMountSource is the base for all mount sources

type ContainerMountTarget

type ContainerMountTarget string

ContainerMountTarget represents the target path within a container where the mount will be available Note that mount targets must be unique. It's not supported to mount different sources to the same target.

func (ContainerMountTarget) Target

func (t ContainerMountTarget) Target() string

type ContainerMounts

type ContainerMounts []ContainerMount

ContainerMounts represents a collection of mounts for a container

func Mounts

func Mounts(mounts ...ContainerMount) ContainerMounts

Mounts returns a ContainerMounts to support a more fluent API

type ContainerOption

type ContainerOption func(*containerOptions)

functional option for setting the reaper image

func WithImageName

func WithImageName(imageName string) ContainerOption

WithImageName sets the reaper image name

func WithRegistryCredentials deprecated

func WithRegistryCredentials(registryCredentials string) ContainerOption

Deprecated: Testcontainers will detect registry credentials automatically WithRegistryCredentials sets the reaper registry credentials

type ContainerProvider

type ContainerProvider interface {
	Close() error                                                                // close the provider
	CreateContainer(context.Context, ContainerRequest) (Container, error)        // create a container without starting it
	ReuseOrCreateContainer(context.Context, ContainerRequest) (Container, error) // reuses a container if it exists or creates a container without starting
	RunContainer(context.Context, ContainerRequest) (Container, error)           // create a container and start it
	Health(context.Context) error
	Config() TestcontainersConfig
}

ContainerProvider allows the creation of containers on an arbitrary system

type ContainerRequest

type ContainerRequest struct {
	FromDockerfile
	Image                   string
	Entrypoint              []string
	Env                     map[string]string
	ExposedPorts            []string // allow specifying protocol info
	Cmd                     []string
	Labels                  map[string]string
	Mounts                  ContainerMounts
	Tmpfs                   map[string]string
	RegistryCred            string // Deprecated: Testcontainers will detect registry credentials automatically
	WaitingFor              wait.Strategy
	Name                    string // for specifying container name
	Hostname                string
	ExtraHosts              []string                                   // Deprecated: Use HostConfigModifier instead
	Privileged              bool                                       // For starting privileged container
	Networks                []string                                   // for specifying network names
	NetworkAliases          map[string][]string                        // for specifying network aliases
	NetworkMode             container.NetworkMode                      // Deprecated: Use HostConfigModifier instead
	Resources               container.Resources                        // Deprecated: Use HostConfigModifier instead
	Files                   []ContainerFile                            // files which will be copied when container starts
	User                    string                                     // for specifying uid:gid
	SkipReaper              bool                                       // Deprecated: The reaper is globally controlled by the .testcontainers.properties file or the TESTCONTAINERS_RYUK_DISABLED environment variable
	ReaperImage             string                                     // Deprecated: use WithImageName ContainerOption instead. Alternative reaper image
	ReaperOptions           []ContainerOption                          // options for the reaper
	AutoRemove              bool                                       // Deprecated: Use HostConfigModifier instead. If set to true, the container will be removed from the host when stopped
	AlwaysPullImage         bool                                       // Always pull image
	ImagePlatform           string                                     // ImagePlatform describes the platform which the image runs on.
	Binds                   []string                                   // Deprecated: Use HostConfigModifier instead
	ShmSize                 int64                                      // Amount of memory shared with the host (in bytes)
	CapAdd                  []string                                   // Deprecated: Use HostConfigModifier instead. Add Linux capabilities
	CapDrop                 []string                                   // Deprecated: Use HostConfigModifier instead. Drop Linux capabilities
	ConfigModifier          func(*container.Config)                    // Modifier for the config before container creation
	HostConfigModifier      func(*container.HostConfig)                // Modifier for the host config before container creation
	EnpointSettingsModifier func(map[string]*network.EndpointSettings) // Modifier for the network settings before container creation
	LifecycleHooks          []ContainerLifecycleHooks                  // define hooks to be executed during container lifecycle
}

ContainerRequest represents the parameters used to get a running container

func (*ContainerRequest) GetAuthConfigs

func (c *ContainerRequest) GetAuthConfigs() map[string]registry.AuthConfig

GetAuthConfigs returns the auth configs to be able to pull from an authenticated docker registry

func (*ContainerRequest) GetBuildArgs

func (c *ContainerRequest) GetBuildArgs() map[string]*string

GetBuildArgs returns the env args to be used when creating from Dockerfile

func (*ContainerRequest) GetContext

func (c *ContainerRequest) GetContext() (io.Reader, error)

GetContext retrieve the build context for the request

func (*ContainerRequest) GetDockerfile

func (c *ContainerRequest) GetDockerfile() string

GetDockerfile returns the Dockerfile from the ContainerRequest, defaults to "Dockerfile"

func (*ContainerRequest) GetRepo

func (c *ContainerRequest) GetRepo() string

GetRepo returns the Repo label for image from the ContainerRequest, defaults to UUID

func (*ContainerRequest) GetTag

func (c *ContainerRequest) GetTag() string

GetTag returns the Tag label for image from the ContainerRequest, defaults to UUID

func (*ContainerRequest) ShouldBuildImage

func (c *ContainerRequest) ShouldBuildImage() bool

func (*ContainerRequest) ShouldPrintBuildLog

func (c *ContainerRequest) ShouldPrintBuildLog() bool

func (*ContainerRequest) Validate

func (c *ContainerRequest) Validate() error

Validate ensures that the ContainerRequest does not have invalid parameters configured to it ex. make sure you are not specifying both an image as well as a context

type ContainerRequestHook

type ContainerRequestHook func(ctx context.Context, req ContainerRequest) error

ContainerRequestHook is a hook that will be called before a container is created. It can be used to modify container configuration before it is created, using the different lifecycle hooks that are available: - Creating For that, it will receive a ContainerRequest, modify it and return an error if needed.

type CustomizeRequestOption

type CustomizeRequestOption func(req *GenericContainerRequest)

CustomizeRequestOption is a type that can be used to configure the Testcontainers container request. The passed request will be merged with the default one.

func CustomizeRequest

func CustomizeRequest(src GenericContainerRequest) CustomizeRequestOption

CustomizeRequest returns a function that can be used to merge the passed container request with the one that is used by the container. Slices and Maps will be appended.

func WithConfigModifier

func WithConfigModifier(modifier func(config *container.Config)) CustomizeRequestOption

WithConfigModifier allows to override the default container config

func WithEndpointSettingsModifier

func WithEndpointSettingsModifier(modifier func(settings map[string]*network.EndpointSettings)) CustomizeRequestOption

WithEndpointSettingsModifier allows to override the default endpoint settings

func WithHostConfigModifier

func WithHostConfigModifier(modifier func(hostConfig *container.HostConfig)) CustomizeRequestOption

WithHostConfigModifier allows to override the default host config

func WithImage

func WithImage(image string) CustomizeRequestOption

WithImage sets the image for a container

func WithWaitStrategy

func WithWaitStrategy(strategies ...wait.Strategy) CustomizeRequestOption

WithWaitStrategy sets the wait strategy for a container, using 60 seconds as deadline

func WithWaitStrategyAndDeadline

func WithWaitStrategyAndDeadline(deadline time.Duration, strategies ...wait.Strategy) CustomizeRequestOption

WithWaitStrategyAndDeadline sets the wait strategy for a container, including deadline

func (CustomizeRequestOption) Customize

func (opt CustomizeRequestOption) Customize(req *GenericContainerRequest)

type DefaultNetwork

type DefaultNetwork string

func (DefaultNetwork) ApplyDockerTo

func (n DefaultNetwork) ApplyDockerTo(opts *DockerProviderOptions)

func (DefaultNetwork) ApplyGenericTo

func (n DefaultNetwork) ApplyGenericTo(opts *GenericProviderOptions)

type DeprecatedContainer

type DeprecatedContainer interface {
	GetHostEndpoint(ctx context.Context, port string) (string, string, error)
	GetIPAddress(ctx context.Context) (string, error)
	LivenessCheckPorts(ctx context.Context) (nat.PortSet, error)
	Terminate(ctx context.Context) error
}

DeprecatedContainer shows methods that were supported before, but are now deprecated Deprecated: Use Container

type DockerBindMountSource

type DockerBindMountSource struct {
	*mount.BindOptions

	// HostPath is the path mounted into the container
	// the same host path might be mounted to multiple locations within a single container
	HostPath string
}

func (DockerBindMountSource) GetBindOptions

func (s DockerBindMountSource) GetBindOptions() *mount.BindOptions

func (DockerBindMountSource) Source

func (s DockerBindMountSource) Source() string

func (DockerBindMountSource) Type

type DockerClient

type DockerClient struct {
	*client.Client // client is embedded into our own client
}

DockerClient is a wrapper around the docker client that is used by testcontainers-go. It implements the SystemAPIClient interface in order to cache the docker info and reuse it.

func NewDockerClientWithOpts

func NewDockerClientWithOpts(ctx context.Context, opt ...client.Opt) (*DockerClient, error)

func (*DockerClient) DiskUsage

func (c *DockerClient) DiskUsage(ctx context.Context, options types.DiskUsageOptions) (types.DiskUsage, error)

DiskUsage returns the disk usage of all images.

func (*DockerClient) Events

func (c *DockerClient) Events(ctx context.Context, options types.EventsOptions) (<-chan events.Message, <-chan error)

Events returns a channel to listen to events that happen to the docker daemon.

func (*DockerClient) Info

func (c *DockerClient) Info(ctx context.Context) (types.Info, error)

Info returns information about the docker server. The result of Info is cached and reused every time Info is called. It will also print out the docker server info, and the resolved Docker paths, to the default logger.

func (*DockerClient) Ping

func (c *DockerClient) Ping(ctx context.Context) (types.Ping, error)

Ping pings the docker server.

func (*DockerClient) RegistryLogin

RegistryLogin logs into a Docker registry.

type DockerContainer

type DockerContainer struct {
	// Container ID from Docker
	ID         string
	WaitingFor wait.Strategy
	Image      string
	// contains filtered or unexported fields
}

DockerContainer represents a container started using Docker

func (*DockerContainer) ContainerIP

func (c *DockerContainer) ContainerIP(ctx context.Context) (string, error)

ContainerIP gets the IP address of the primary network within the container.

func (*DockerContainer) ContainerIPs

func (c *DockerContainer) ContainerIPs(ctx context.Context) ([]string, error)

ContainerIPs gets the IP addresses of all the networks within the container.

func (*DockerContainer) CopyDirToContainer

func (c *DockerContainer) CopyDirToContainer(ctx context.Context, hostDirPath string, containerParentPath string, fileMode int64) error

CopyDirToContainer copies the contents of a directory to a parent path in the container. This parent path must exist in the container first as we cannot create it

func (*DockerContainer) CopyFileFromContainer

func (c *DockerContainer) CopyFileFromContainer(ctx context.Context, filePath string) (io.ReadCloser, error)

func (*DockerContainer) CopyFileToContainer

func (c *DockerContainer) CopyFileToContainer(ctx context.Context, hostFilePath string, containerFilePath string, fileMode int64) error

func (*DockerContainer) CopyToContainer

func (c *DockerContainer) CopyToContainer(ctx context.Context, fileContent []byte, containerFilePath string, fileMode int64) error

CopyToContainer copies fileContent data to a file in container

func (*DockerContainer) Endpoint

func (c *DockerContainer) Endpoint(ctx context.Context, proto string) (string, error)

Endpoint gets proto://host:port string for the first exposed port Will returns just host:port if proto is ""

func (*DockerContainer) Exec

func (c *DockerContainer) Exec(ctx context.Context, cmd []string, options ...tcexec.ProcessOption) (int, io.Reader, error)

func (*DockerContainer) FollowOutput

func (c *DockerContainer) FollowOutput(consumer LogConsumer)

FollowOutput adds a LogConsumer to be sent logs from the container's STDOUT and STDERR

func (*DockerContainer) GetContainerID

func (c *DockerContainer) GetContainerID() string

func (*DockerContainer) Host

func (c *DockerContainer) Host(ctx context.Context) (string, error)

Host gets host (ip or name) of the docker daemon where the container port is exposed Warning: this is based on your Docker host setting. Will fail if using an SSH tunnel You can use the "TC_HOST" env variable to set this yourself

func (*DockerContainer) IsRunning

func (c *DockerContainer) IsRunning() bool

func (*DockerContainer) Logs

Logs will fetch both STDOUT and STDERR from the current container. Returns a ReadCloser and leaves it up to the caller to extract what it wants.

func (*DockerContainer) MappedPort

func (c *DockerContainer) MappedPort(ctx context.Context, port nat.Port) (nat.Port, error)

MappedPort gets externally mapped port for a container port

func (*DockerContainer) Name

func (c *DockerContainer) Name(ctx context.Context) (string, error)

Name gets the name of the container.

func (*DockerContainer) NetworkAliases

func (c *DockerContainer) NetworkAliases(ctx context.Context) (map[string][]string, error)

NetworkAliases gets the aliases of the container for the networks it is attached to.

func (*DockerContainer) Networks

func (c *DockerContainer) Networks(ctx context.Context) ([]string, error)

Networks gets the names of the networks the container is attached to.

func (*DockerContainer) PortEndpoint

func (c *DockerContainer) PortEndpoint(ctx context.Context, port nat.Port, proto string) (string, error)

PortEndpoint gets proto://host:port string for the given exposed port Will returns just host:port if proto is ""

func (*DockerContainer) Ports

func (c *DockerContainer) Ports(ctx context.Context) (nat.PortMap, error)

Ports gets the exposed ports for the container.

func (*DockerContainer) SessionID

func (c *DockerContainer) SessionID() string

SessionID gets the current session id

func (*DockerContainer) SetLogger

func (c *DockerContainer) SetLogger(logger Logging)

SetLogger sets the logger for the container

func (*DockerContainer) SetProvider

func (c *DockerContainer) SetProvider(provider *DockerProvider)

SetProvider sets the provider for the container

func (*DockerContainer) Start

func (c *DockerContainer) Start(ctx context.Context) error

Start will start an already created container

func (*DockerContainer) StartLogProducer

func (c *DockerContainer) StartLogProducer(ctx context.Context) error

StartLogProducer will start a concurrent process that will continuously read logs from the container and will send them to each added LogConsumer

func (*DockerContainer) State

State returns container's running state

func (*DockerContainer) Stop

func (c *DockerContainer) Stop(ctx context.Context, timeout *time.Duration) error

Stop will stop an already started container

In case the container fails to stop gracefully within a time frame specified by the timeout argument, it is forcefully terminated (killed).

If the timeout is nil, the container's StopTimeout value is used, if set, otherwise the engine default. A negative timeout value can be specified, meaning no timeout, i.e. no forceful termination is performed.

func (*DockerContainer) StopLogProducer

func (c *DockerContainer) StopLogProducer() error

StopLogProducer will stop the concurrent process that is reading logs and sending them to each added LogConsumer

func (*DockerContainer) Terminate

func (c *DockerContainer) Terminate(ctx context.Context) error

Terminate is used to kill the container. It is usually triggered by as defer function.

type DockerNetwork

type DockerNetwork struct {
	ID     string // Network ID from Docker
	Driver string
	Name   string
	// contains filtered or unexported fields
}

DockerNetwork represents a network started using Docker

func (*DockerNetwork) Remove

func (n *DockerNetwork) Remove(ctx context.Context) error

Remove is used to remove the network. It is usually triggered by as defer function.

type DockerProvider

type DockerProvider struct {
	*DockerProviderOptions
	// contains filtered or unexported fields
}

DockerProvider implements the ContainerProvider interface

func NewDockerProvider

func NewDockerProvider(provOpts ...DockerProviderOption) (*DockerProvider, error)

NewDockerProvider creates a Docker provider with the EnvClient

func (*DockerProvider) BuildImage

func (p *DockerProvider) BuildImage(ctx context.Context, img ImageBuildInfo) (string, error)

BuildImage will build and image from context and Dockerfile, then return the tag

func (*DockerProvider) Client

func (p *DockerProvider) Client() client.APIClient

Client gets the docker client used by the provider

func (*DockerProvider) Close

func (p *DockerProvider) Close() error

Close closes the docker client used by the provider

func (*DockerProvider) Config

Config provides the TestcontainersConfig read from $HOME/.testcontainers.properties or the environment variables

func (*DockerProvider) CreateContainer

func (p *DockerProvider) CreateContainer(ctx context.Context, req ContainerRequest) (Container, error)

CreateContainer fulfills a request for a container without starting it

Example
ctx := context.Background()
req := ContainerRequest{
	Image:        "docker.io/nginx:alpine",
	ExposedPorts: []string{"80/tcp"},
	WaitingFor:   wait.ForHTTP("/").WithStartupTimeout(10 * time.Second),
}
nginxC, _ := GenericContainer(ctx, GenericContainerRequest{
	ContainerRequest: req,
	Started:          true,
})
defer func() {
	if err := nginxC.Terminate(ctx); err != nil {
		log.Fatalf("failed to terminate container: %s", err)
	}
}()
Output:

func (*DockerProvider) CreateNetwork

func (p *DockerProvider) CreateNetwork(ctx context.Context, req NetworkRequest) (Network, error)

CreateNetwork returns the object representing a new network identified by its name

func (*DockerProvider) DaemonHost

func (p *DockerProvider) DaemonHost(ctx context.Context) (string, error)

DaemonHost gets the host or ip of the Docker daemon where ports are exposed on Warning: this is based on your Docker host setting. Will fail if using an SSH tunnel You can use the "TC_HOST" env variable to set this yourself

func (*DockerProvider) GetGatewayIP

func (p *DockerProvider) GetGatewayIP(ctx context.Context) (string, error)

func (*DockerProvider) GetNetwork

GetNetwork returns the object representing the network identified by its name

func (*DockerProvider) Health

func (p *DockerProvider) Health(ctx context.Context) (err error)

Health measure the healthiness of the provider. Right now we leverage the docker-client Info endpoint to see if the daemon is reachable.

func (*DockerProvider) ReuseOrCreateContainer

func (p *DockerProvider) ReuseOrCreateContainer(ctx context.Context, req ContainerRequest) (Container, error)

func (*DockerProvider) RunContainer

func (p *DockerProvider) RunContainer(ctx context.Context, req ContainerRequest) (Container, error)

RunContainer takes a RequestContainer as input and it runs a container via the docker sdk

func (*DockerProvider) SetClient

func (p *DockerProvider) SetClient(c client.APIClient)

SetClient sets the docker client to be used by the provider

type DockerProviderOption

type DockerProviderOption interface {
	ApplyDockerTo(opts *DockerProviderOptions)
}

DockerProviderOption defines a common interface to modify DockerProviderOptions These can be passed to NewDockerProvider in a variadic way to customize the returned DockerProvider instance

func Generic2DockerOptions

func Generic2DockerOptions(opts ...GenericProviderOption) []DockerProviderOption

func WithDefaultBridgeNetwork

func WithDefaultBridgeNetwork(bridgeNetworkName string) DockerProviderOption

type DockerProviderOptionFunc

type DockerProviderOptionFunc func(opts *DockerProviderOptions)

DockerProviderOptionFunc is a shorthand to implement the DockerProviderOption interface

func (DockerProviderOptionFunc) ApplyDockerTo

func (f DockerProviderOptionFunc) ApplyDockerTo(opts *DockerProviderOptions)

type DockerProviderOptions

type DockerProviderOptions struct {
	*GenericProviderOptions
	// contains filtered or unexported fields
}

DockerProviderOptions defines options applicable to DockerProvider

type DockerTmpfsMountSource

type DockerTmpfsMountSource struct {
	GenericTmpfsMountSource
	*mount.TmpfsOptions
}

func (DockerTmpfsMountSource) GetTmpfsOptions

func (s DockerTmpfsMountSource) GetTmpfsOptions() *mount.TmpfsOptions

type DockerVolumeMountSource

type DockerVolumeMountSource struct {
	*mount.VolumeOptions

	// Name refers to the name of the volume to be mounted
	// the same volume might be mounted to multiple locations within a single container
	Name string
}

func (DockerVolumeMountSource) GetVolumeOptions

func (s DockerVolumeMountSource) GetVolumeOptions() *mount.VolumeOptions

func (DockerVolumeMountSource) Source

func (s DockerVolumeMountSource) Source() string

func (DockerVolumeMountSource) Type

type FileFromContainer

type FileFromContainer struct {
	// contains filtered or unexported fields
}

func (*FileFromContainer) Close

func (fc *FileFromContainer) Close() error

func (*FileFromContainer) Read

func (fc *FileFromContainer) Read(b []byte) (int, error)

type FromDockerfile

type FromDockerfile struct {
	Context        string                         // the path to the context of the docker build
	ContextArchive io.Reader                      // the tar archive file to send to docker that contains the build context
	Dockerfile     string                         // the path from the context to the Dockerfile for the image, defaults to "Dockerfile"
	Repo           string                         // the repo label for image, defaults to UUID
	Tag            string                         // the tag label for image, defaults to UUID
	BuildArgs      map[string]*string             // enable user to pass build args to docker daemon
	PrintBuildLog  bool                           // enable user to print build log
	AuthConfigs    map[string]registry.AuthConfig // Deprecated. Testcontainers will detect registry credentials automatically. Enable auth configs to be able to pull from an authenticated docker registry
}

FromDockerfile represents the parameters needed to build an image from a Dockerfile rather than using a pre-built one

type GenericBindMountSource

type GenericBindMountSource struct {
	// HostPath is the path mounted into the container
	// the same host path might be mounted to multiple locations within a single container
	HostPath string
}

GenericBindMountSource implements ContainerMountSource and represents a bind mount Optionally mount.BindOptions might be added for advanced scenarios

func (GenericBindMountSource) Source

func (s GenericBindMountSource) Source() string

func (GenericBindMountSource) Type

type GenericContainerRequest

type GenericContainerRequest struct {
	ContainerRequest              // embedded request for provider
	Started          bool         // whether to auto-start the container
	ProviderType     ProviderType // which provider to use, Docker if empty
	Logger           Logging      // provide a container specific Logging - use default global logger if empty
	Reuse            bool         // reuse an existing container if it exists or create a new one. a container name mustn't be empty
}

GenericContainerRequest represents parameters to a generic container

type GenericNetworkRequest

type GenericNetworkRequest struct {
	NetworkRequest              // embedded request for provider
	ProviderType   ProviderType // which provider to use, Docker if empty
}

GenericNetworkRequest represents parameters to a generic network

type GenericProvider

type GenericProvider interface {
	ContainerProvider
	NetworkProvider
}

GenericProvider represents an abstraction for container and network providers

type GenericProviderOption

type GenericProviderOption interface {
	ApplyGenericTo(opts *GenericProviderOptions)
}

GenericProviderOption defines a common interface to modify GenericProviderOptions These options can be passed to GetProvider in a variadic way to customize the returned GenericProvider instance

type GenericProviderOptionFunc

type GenericProviderOptionFunc func(opts *GenericProviderOptions)

GenericProviderOptionFunc is a shorthand to implement the GenericProviderOption interface

func (GenericProviderOptionFunc) ApplyGenericTo

func (f GenericProviderOptionFunc) ApplyGenericTo(opts *GenericProviderOptions)

type GenericProviderOptions

type GenericProviderOptions struct {
	Logger         Logging
	DefaultNetwork string
}

GenericProviderOptions defines options applicable to all providers

type GenericTmpfsMountSource

type GenericTmpfsMountSource struct{}

GenericTmpfsMountSource implements ContainerMountSource and represents a TmpFS mount Optionally mount.TmpfsOptions might be added for advanced scenarios

func (GenericTmpfsMountSource) Source

func (s GenericTmpfsMountSource) Source() string

func (GenericTmpfsMountSource) Type

type GenericVolumeMountSource

type GenericVolumeMountSource struct {
	// Name refers to the name of the volume to be mounted
	// the same volume might be mounted to multiple locations within a single container
	Name string
}

GenericVolumeMountSource implements ContainerMountSource and represents a volume mount

func (GenericVolumeMountSource) Source

func (s GenericVolumeMountSource) Source() string

func (GenericVolumeMountSource) Type

type ImageBuildInfo

type ImageBuildInfo interface {
	GetContext() (io.Reader, error)                 // the path to the build context
	GetDockerfile() string                          // the relative path to the Dockerfile, including the fileitself
	GetRepo() string                                // get repo label for image
	GetTag() string                                 // get tag label for image
	ShouldPrintBuildLog() bool                      // allow build log to be printed to stdout
	ShouldBuildImage() bool                         // return true if the image needs to be built
	GetBuildArgs() map[string]*string               // return the environment args used to build the from Dockerfile
	GetAuthConfigs() map[string]registry.AuthConfig // return the auth configs to be able to pull from an authenticated docker registry
}

ImageBuildInfo defines what is needed to build an image

type Log

type Log struct {
	LogType string
	Content []byte
}

Log represents a message that was created by a process, LogType is either "STDOUT" or "STDERR", Content is the byte contents of the message itself

type LogConsumer

type LogConsumer interface {
	Accept(Log)
}

LogConsumer represents any object that can handle a Log, it is up to the LogConsumer instance what to do with the log

type LoggerOption

type LoggerOption struct {
	// contains filtered or unexported fields
}

func WithLogger

func WithLogger(logger Logging) LoggerOption

WithLogger is a generic option that implements GenericProviderOption, DockerProviderOption It replaces the global Logging implementation with a user defined one e.g. to aggregate logs from testcontainers with the logs of specific test case

func (LoggerOption) ApplyDockerTo

func (o LoggerOption) ApplyDockerTo(opts *DockerProviderOptions)

func (LoggerOption) ApplyGenericTo

func (o LoggerOption) ApplyGenericTo(opts *GenericProviderOptions)

type Logging

type Logging interface {
	Printf(format string, v ...interface{})
}

Logging defines the Logger interface

var Logger Logging = log.New(os.Stderr, "", log.LstdFlags)

Logger is the default log instance

func TestLogger

func TestLogger(tb testing.TB) Logging

TestLogger returns a Logging implementation for testing.TB This way logs from testcontainers are part of the test output of a test suite or test case

type MountType

type MountType uint
const (
	MountTypeBind MountType = iota
	MountTypeVolume
	MountTypeTmpfs
	MountTypePipe
)

type Network

type Network interface {
	Remove(context.Context) error // removes the network
}

Network allows getting info about a single network instance

func GenericNetwork

func GenericNetwork(ctx context.Context, req GenericNetworkRequest) (Network, error)

GenericNetwork creates a generic network with parameters

type NetworkProvider

type NetworkProvider interface {
	CreateNetwork(context.Context, NetworkRequest) (Network, error)            // create a network
	GetNetwork(context.Context, NetworkRequest) (types.NetworkResource, error) // get a network
}

NetworkProvider allows the creation of networks on an arbitrary system

type NetworkRequest

type NetworkRequest struct {
	Driver         string
	CheckDuplicate bool
	Internal       bool
	EnableIPv6     bool
	Name           string
	Labels         map[string]string
	Attachable     bool
	IPAM           *network.IPAM

	SkipReaper    bool              // Deprecated: The reaper is globally controlled by the .testcontainers.properties file or the TESTCONTAINERS_RYUK_DISABLED environment variable
	ReaperImage   string            // Deprecated: use WithImageName ContainerOption instead. Alternative reaper registry
	ReaperOptions []ContainerOption // Reaper options to use for this network
}

NetworkRequest represents the parameters used to get a network

type ParallelContainerRequest

type ParallelContainerRequest []GenericContainerRequest

type ParallelContainersError

type ParallelContainersError struct {
	Errors []ParallelContainersRequestError
}

func (ParallelContainersError) Error

func (gpe ParallelContainersError) Error() string

type ParallelContainersOptions

type ParallelContainersOptions struct {
	WorkersCount int // count of parallel workers. If field empty(zero), default value will be 'defaultWorkersCount'
}

ParallelContainersOptions represents additional options for parallel running

type ParallelContainersRequestError

type ParallelContainersRequestError struct {
	Request GenericContainerRequest
	Error   error
}

ParallelContainersRequestError represents error from parallel request

type ProviderType

type ProviderType int

ProviderType is an enum for the possible providers

const (
	ProviderDefault ProviderType = iota // default will auto-detect provider from DOCKER_HOST environment variable
	ProviderDocker
	ProviderPodman
)

possible provider types

func (ProviderType) GetProvider

func (t ProviderType) GetProvider(opts ...GenericProviderOption) (GenericProvider, error)

GetProvider provides the provider implementation for a certain type

type Reaper

type Reaper struct {
	Provider  ReaperProvider
	SessionID string
	Endpoint  string
	// contains filtered or unexported fields
}

Reaper is used to start a sidecar container that cleans up resources

func NewReaper

func NewReaper(ctx context.Context, sessionID string, provider ReaperProvider, reaperImageName string) (*Reaper, error)

NewReaper creates a Reaper with a sessionID to identify containers and a provider to use Deprecated: it's not possible to create a reaper anymore.

func (*Reaper) Connect

func (r *Reaper) Connect() (chan bool, error)

Connect runs a goroutine which can be terminated by sending true into the returned channel

func (*Reaper) Labels

func (r *Reaper) Labels() map[string]string

Labels returns the container labels to use so that this Reaper cleans them up

type ReaperProvider

type ReaperProvider interface {
	RunContainer(ctx context.Context, req ContainerRequest) (Container, error)
	Config() TestcontainersConfig
}

ReaperProvider represents a provider for the reaper to run itself with The ContainerProvider interface should usually satisfy this as well, so it is pluggable

type TestcontainersConfig

type TestcontainersConfig struct {
	Host           string `properties:"docker.host,default="`                    // Deprecated: use Config.Host instead
	TLSVerify      int    `properties:"docker.tls.verify,default=0"`             // Deprecated: use Config.TLSVerify instead
	CertPath       string `properties:"docker.cert.path,default="`               // Deprecated: use Config.CertPath instead
	RyukDisabled   bool   `properties:"ryuk.disabled,default=false"`             // Deprecated: use Config.RyukDisabled instead
	RyukPrivileged bool   `properties:"ryuk.container.privileged,default=false"` // Deprecated: use Config.RyukPrivileged instead
	Config         config.Config
}

TestcontainersConfig represents the configuration for Testcontainers

func ReadConfig

func ReadConfig() TestcontainersConfig

ReadConfig reads from testcontainers properties file, storing the result in a singleton instance of the TestcontainersConfig struct

type TmpfsMounter

type TmpfsMounter interface {
	GetTmpfsOptions() *mount.TmpfsOptions
}

TmpfsMounter can optionally be implemented by mount sources to support advanced scenarios based on mount.TmpfsOptions

type VolumeMounter

type VolumeMounter interface {
	GetVolumeOptions() *mount.VolumeOptions
}

VolumeMounter can optionally be implemented by mount sources to support advanced scenarios based on mount.VolumeOptions

Directories

Path Synopsis

Jump to

Keyboard shortcuts

? : This menu
/ : Search site
f or F : Jump to
y or Y : Canonical URL