Documentation ¶
Index ¶
- Constants
- Variables
- func AddGenericLabels(target map[string]string)
- func CleanupContainer(tb testing.TB, ctr Container, options ...TerminateOption)
- func CleanupNetwork(tb testing.TB, network Network)
- func DockerImageAuth(ctx context.Context, image string) (string, registry.AuthConfig, error)
- func ExtractDockerSocket() stringdeprecated
- func GenericLabels() map[string]string
- func LogDockerServerInfo(ctx context.Context, client client.APIClient, logger Logging)deprecated
- func MustExtractDockerSocket(ctx context.Context) string
- func NewDockerClient() (*client.Client, error)deprecated
- func SessionID() string
- func SkipIfDockerDesktop(t *testing.T, ctx context.Context)
- func SkipIfProviderIsNotHealthy(t *testing.T)
- func TerminateContainer(container Container, options ...TerminateOption) error
- type BindMounterdeprecated
- type Container
- type ContainerCustomizer
- type ContainerFile
- type ContainerHook
- type ContainerLifecycleHooks
- func (c ContainerLifecycleHooks) Created(ctx context.Context) func(container Container) error
- func (c ContainerLifecycleHooks) Creating(ctx context.Context) func(req ContainerRequest) error
- func (c ContainerLifecycleHooks) Readied(ctx context.Context) func(container Container) error
- func (c ContainerLifecycleHooks) Started(ctx context.Context) func(container Container) error
- func (c ContainerLifecycleHooks) Starting(ctx context.Context) func(container Container) error
- func (c ContainerLifecycleHooks) Stopped(ctx context.Context) func(container Container) error
- func (c ContainerLifecycleHooks) Stopping(ctx context.Context) func(container Container) error
- func (c ContainerLifecycleHooks) Terminated(ctx context.Context) func(container Container) error
- func (c ContainerLifecycleHooks) Terminating(ctx context.Context) func(container Container) error
- type ContainerMount
- type ContainerMountSource
- type ContainerMountTarget
- type ContainerMounts
- type ContainerOptiondeprecated
- type ContainerProvider
- type ContainerRequest
- func (c *ContainerRequest) BuildOptions() (types.ImageBuildOptions, error)
- func (c *ContainerRequest) GetAuthConfigs() map[string]registry.AuthConfigdeprecated
- func (c *ContainerRequest) GetBuildArgs() map[string]*string
- func (c *ContainerRequest) GetContext() (io.Reader, error)
- func (c *ContainerRequest) GetDockerfile() string
- func (c *ContainerRequest) GetRepo() string
- func (c *ContainerRequest) GetTag() string
- func (c *ContainerRequest) ShouldBuildImage() bool
- func (c *ContainerRequest) ShouldKeepBuiltImage() bool
- func (c *ContainerRequest) ShouldPrintBuildLog() bool
- func (c *ContainerRequest) Validate() error
- type ContainerRequestHook
- type CustomHubSubstitutor
- type CustomizeRequestOption
- func CustomizeRequest(src GenericContainerRequest) CustomizeRequestOption
- func WithAfterReadyCommand(execs ...Executable) CustomizeRequestOption
- func WithConfigModifier(modifier func(config *container.Config)) CustomizeRequestOption
- func WithEndpointSettingsModifier(modifier func(settings map[string]*network.EndpointSettings)) CustomizeRequestOption
- func WithEnv(envs map[string]string) CustomizeRequestOption
- func WithHostConfigModifier(modifier func(hostConfig *container.HostConfig)) CustomizeRequestOption
- func WithHostPortAccess(ports ...int) CustomizeRequestOption
- func WithImage(image string) CustomizeRequestOptiondeprecated
- func WithImageSubstitutors(fn ...ImageSubstitutor) CustomizeRequestOption
- func WithLogConsumers(consumer ...LogConsumer) CustomizeRequestOption
- func WithStartupCommand(execs ...Executable) CustomizeRequestOption
- func WithWaitStrategy(strategies ...wait.Strategy) CustomizeRequestOption
- func WithWaitStrategyAndDeadline(deadline time.Duration, strategies ...wait.Strategy) CustomizeRequestOption
- type DefaultNetworkdeprecated
- type DeprecatedContainer
- type DockerBindMountSourcedeprecated
- type DockerClient
- func (c *DockerClient) DiskUsage(ctx context.Context, options types.DiskUsageOptions) (types.DiskUsage, error)
- func (c *DockerClient) Events(ctx context.Context, options events.ListOptions) (<-chan events.Message, <-chan error)
- func (c *DockerClient) Info(ctx context.Context) (system.Info, error)
- func (c *DockerClient) Ping(ctx context.Context) (types.Ping, error)
- func (c *DockerClient) RegistryLogin(ctx context.Context, auth registry.AuthConfig) (registry.AuthenticateOKBody, error)
- type DockerContainer
- func (c *DockerContainer) ContainerIP(ctx context.Context) (string, error)
- func (c *DockerContainer) ContainerIPs(ctx context.Context) ([]string, error)
- func (c *DockerContainer) CopyDirToContainer(ctx context.Context, hostDirPath string, containerParentPath string, ...) error
- func (c *DockerContainer) CopyFileFromContainer(ctx context.Context, filePath string) (io.ReadCloser, error)
- func (c *DockerContainer) CopyFileToContainer(ctx context.Context, hostFilePath string, containerFilePath string, ...) error
- func (c *DockerContainer) CopyToContainer(ctx context.Context, fileContent []byte, containerFilePath string, ...) error
- func (c *DockerContainer) Endpoint(ctx context.Context, proto string) (string, error)
- func (c *DockerContainer) Exec(ctx context.Context, cmd []string, options ...tcexec.ProcessOption) (int, io.Reader, error)
- func (c *DockerContainer) FollowOutput(consumer LogConsumer)deprecated
- func (c *DockerContainer) GetContainerID() string
- func (c *DockerContainer) GetLogProductionErrorChannel() <-chan error
- func (c *DockerContainer) Host(ctx context.Context) (string, error)
- func (c *DockerContainer) Inspect(ctx context.Context) (*types.ContainerJSON, error)
- func (c *DockerContainer) IsRunning() bool
- func (c *DockerContainer) Logs(ctx context.Context) (io.ReadCloser, error)
- func (c *DockerContainer) MappedPort(ctx context.Context, port nat.Port) (nat.Port, error)
- func (c *DockerContainer) Name(ctx context.Context) (string, error)deprecated
- func (c *DockerContainer) NetworkAliases(ctx context.Context) (map[string][]string, error)
- func (c *DockerContainer) Networks(ctx context.Context) ([]string, error)
- func (c *DockerContainer) PortEndpoint(ctx context.Context, port nat.Port, proto string) (string, error)
- func (c *DockerContainer) Ports(ctx context.Context) (nat.PortMap, error)deprecated
- func (c *DockerContainer) SessionID() string
- func (c *DockerContainer) SetLogger(logger Logging)
- func (c *DockerContainer) SetProvider(provider *DockerProvider)
- func (c *DockerContainer) SetTerminationSignal(signal chan bool)
- func (c *DockerContainer) Start(ctx context.Context) error
- func (c *DockerContainer) StartLogProducer(ctx context.Context, opts ...LogProductionOption) errordeprecated
- func (c *DockerContainer) State(ctx context.Context) (*types.ContainerState, error)
- func (c *DockerContainer) Stop(ctx context.Context, timeout *time.Duration) error
- func (c *DockerContainer) StopLogProducer() errordeprecated
- func (c *DockerContainer) Terminate(ctx context.Context) error
- type DockerNetwork
- type DockerProvider
- func (p *DockerProvider) BuildImage(ctx context.Context, img ImageBuildInfo) (string, error)
- func (p *DockerProvider) Client() client.APIClient
- func (p *DockerProvider) Close() error
- func (p *DockerProvider) Config() TestcontainersConfig
- func (p *DockerProvider) CreateContainer(ctx context.Context, req ContainerRequest) (con Container, err error)
- func (p *DockerProvider) CreateNetwork(ctx context.Context, req NetworkRequest) (net Network, err error)deprecated
- func (p *DockerProvider) DaemonHost(ctx context.Context) (string, error)
- func (p *DockerProvider) GetGatewayIP(ctx context.Context) (string, error)
- func (p *DockerProvider) GetNetwork(ctx context.Context, req NetworkRequest) (network.Inspect, error)
- func (p *DockerProvider) Health(ctx context.Context) error
- func (p *DockerProvider) ListImages(ctx context.Context) ([]ImageInfo, error)
- func (p *DockerProvider) PullImage(ctx context.Context, img string) error
- func (p *DockerProvider) ReuseOrCreateContainer(ctx context.Context, req ContainerRequest) (con Container, err error)
- func (p *DockerProvider) RunContainer(ctx context.Context, req ContainerRequest) (Container, error)
- func (p *DockerProvider) SaveImages(ctx context.Context, output string, images ...string) error
- func (p *DockerProvider) SetClient(c client.APIClient)
- type DockerProviderOption
- type DockerProviderOptionFunc
- type DockerProviderOptions
- type DockerTmpfsMountSource
- type DockerVolumeMountSource
- type ExecOptions
- type Executable
- type FileFromContainer
- type FromDockerfile
- type GenericBindMountSourcedeprecated
- type GenericContainerRequest
- type GenericNetworkRequestdeprecated
- type GenericProvider
- type GenericProviderOption
- type GenericProviderOptionFunc
- type GenericProviderOptions
- type GenericTmpfsMountSource
- type GenericVolumeMountSource
- type ImageBuildInfo
- type ImageInfo
- type ImageProvider
- type ImageSubstitutor
- type Log
- type LogConsumer
- type LogConsumerConfig
- type LogProductionOption
- type LoggerOption
- type Logging
- type MountType
- type Networkdeprecated
- type NetworkProvider
- type NetworkRequestdeprecated
- type ParallelContainerRequest
- type ParallelContainersError
- type ParallelContainersOptions
- type ParallelContainersRequestError
- type PortForwarder
- type ProviderType
- type RawCommand
- type Reaper
- type ReaperProvider
- type StdoutLogConsumer
- type TerminateOption
- type TestcontainersConfig
- type TmpfsMounter
- type VolumeMounter
Examples ¶
Constants ¶
const ( Bridge = "bridge" // Bridge network name (as well as driver) Podman = "podman" ReaperDefault = "reaper_default" // Default network name when bridge is not available )
const ( // Deprecated: it has been replaced by the internal core.LabelLang TestcontainerLabel = "org.testcontainers.golang" // Deprecated: it has been replaced by the internal core.LabelSessionID TestcontainerLabelSessionID = TestcontainerLabel + ".sessionId" // Deprecated: it has been replaced by the internal core.LabelReaper TestcontainerLabelIsReaper = TestcontainerLabel + ".reaper" )
const ( // HostInternal is the internal hostname used to reach the host from the container, // using the SSHD container as a bridge. HostInternal string = "host.testcontainers.internal" )
const StderrLog = "STDERR"
StderrLog is the log type for STDERR
const StdoutLog = "STDOUT"
StdoutLog is the log type for STDOUT
Variables ¶
var ( ErrDuplicateMountTarget = errors.New("duplicate mount target detected") ErrInvalidBindMount = errors.New("invalid bind mount") )
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 }, }, PostReadies: []ContainerHook{ func(ctx context.Context, c Container) error { logger.Printf("🔔 Container is ready: %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 }, }, } }
DefaultLoggingHook is a hook that will log the container lifecycle events
var (
ErrReuseEmptyName = errors.New("with reuse option a container name mustn't be empty")
)
var ( // Deprecated: it has been replaced by an internal value ReaperDefaultImage = config.ReaperDefaultImage )
Functions ¶
func AddGenericLabels ¶ added in v0.34.0
AddGenericLabels adds the generic labels to target.
func CleanupContainer ¶ added in v0.34.0
func CleanupContainer(tb testing.TB, ctr Container, options ...TerminateOption)
CleanupContainer is a helper function that schedules the container to be stopped / terminated when the test ends.
This should be called as a defer directly after (before any error check) of GenericContainer(...) or a modules Run(...) in a test to ensure the container is stopped when the function ends.
before any error check. If container is nil, its a no-op.
func CleanupNetwork ¶ added in v0.34.0
CleanupNetwork is a helper function that schedules the network to be removed when the test ends. This should be the first call after NewNetwork(...) in a test before any error check. If network is nil, its a no-op.
func DockerImageAuth ¶ added in v0.19.0
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 ExtractDockerSocket
deprecated
added in
v0.28.0
func ExtractDockerSocket() string
Deprecated: use MustExtractDockerHost instead.
func GenericLabels ¶ added in v0.26.0
GenericLabels returns a map of labels that can be used to identify resources created by this library. This includes the standard LabelSessionID if the reaper is enabled, otherwise this is excluded to prevent resources being incorrectly reaped.
func MustExtractDockerSocket ¶ added in v0.34.0
MustExtractDockerSocket Extracts the docker socket from the different alternatives, removing the socket schema. Use this function to get the docker socket path, not the host (e.g. mounting the socket in a container). This function does not consider Windows containers at the moment. The possible alternatives are:
- Docker host from the "tc.host" property in the ~/.testcontainers.properties file.
- The TESTCONTAINERS_DOCKER_SOCKET_OVERRIDE environment variable.
- Using a Docker client, check if the Info().OperativeSystem is "Docker Desktop" and return the default docker socket path for rootless docker.
- Else, Get the current Docker Host from the existing strategies: see MustExtractDockerHost.
- If the socket contains the unix schema, the schema is removed (e.g. unix:///var/run/docker.sock -> /var/run/docker.sock)
- Else, the default location of the docker socket is used (/var/run/docker.sock)
It panics if a Docker client cannot be created, or the Docker host cannot be discovered.
func NewDockerClient
deprecated
added in
v0.14.0
func SessionID ¶ added in v0.26.0
func SessionID() string
SessionID returns a unique session ID for the current test session. Because each Go package will be run in a separate process, we need a way to identify the current test session. By test session, we mean:
- a single "go test" invocation (including flags)
- a single "go test ./..." invocation (including flags)
- the execution of a single test or a set of tests using the IDE
As a consequence, with the sole goal of aggregating test execution across multiple packages, this variable will contain the value of the parent process ID (pid) of the current process and its creation date, to use it to generate a unique session ID. We are using the parent pid because the current process will be a child process of:
- the process that is running the tests, e.g.: "go test";
- the process that is running the application in development mode, e.g. "go run main.go -tags dev";
- the process that is running the tests in the IDE, e.g.: "go test ./...".
Finally, we will hash the combination of the "testcontainers-go:" string with the parent pid and the creation date of that parent process to generate a unique session ID.
This sessionID will be used to:
- identify the test session, aggregating the test execution of multiple packages in the same test session.
- tag the containers created by testcontainers-go, adding a label to the container with the session ID.
func SkipIfDockerDesktop ¶ added in v0.21.0
SkipIfDockerDesktop is a utility function capable of skipping tests if tests are run using Docker Desktop.
func SkipIfProviderIsNotHealthy ¶ added in v0.7.0
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:
func TerminateContainer ¶ added in v0.34.0
func TerminateContainer(container Container, options ...TerminateOption) error
TerminateContainer calls [Container.Terminate] on the container if it is not nil.
This should be called as a defer directly after GenericContainer(...) or a modules Run(...) to ensure the container is terminated when the function ends.
Types ¶
type BindMounter
deprecated
added in
v0.13.0
type BindMounter interface {
GetBindOptions() *mount.BindOptions
}
Deprecated: use Files or HostConfigModifier in the ContainerRequest, or copy files container APIs to make containers portable across Docker environments 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 lowest exposed port PortEndpoint(ctx context.Context, port nat.Port, proto 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 Inspect(context.Context) (*types.ContainerJSON, error) // get container info MappedPort(context.Context, nat.Port) (nat.Port, error) // get externally mapped port for a container port Ports(context.Context) (nat.PortMap, error) // Deprecated: Use c.Inspect(ctx).NetworkSettings.Ports instead SessionID() string // get session id IsRunning() bool // IsRunning returns true if the container is running, false otherwise. Start(context.Context) error // start the container Stop(context.Context, *time.Duration) error // stop the container // Terminate stops and removes the container and its image if it was built and not flagged as kept. Terminate(ctx context.Context) error Logs(context.Context) (io.ReadCloser, error) // Get logs of the container FollowOutput(LogConsumer) // Deprecated: it will be removed in the next major release StartLogProducer(context.Context, ...LogProductionOption) error // Deprecated: Use the ContainerRequest instead StopLogProducer() error // Deprecated: it will be removed in the next major release Name(context.Context) (string, error) // Deprecated: Use c.Inspect(ctx).Name instead 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) GetLogProductionErrorChannel() <-chan 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
Example (BuildFromDockerfile) ¶
ctx := context.Background() // buildFromDockerfileWithModifier { c, err := GenericContainer(ctx, GenericContainerRequest{ ContainerRequest: ContainerRequest{ FromDockerfile: FromDockerfile{ Context: "testdata", Dockerfile: "target.Dockerfile", KeepImage: false, BuildOptionsModifier: func(buildOptions *types.ImageBuildOptions) { buildOptions.Target = "target2" }, }, }, Started: true, }) // } defer func() { if err := TerminateContainer(c); err != nil { log.Printf("failed to terminate container: %s", err) } }() if err != nil { log.Printf("failed to start container: %v", err) return } r, err := c.Logs(ctx) if err != nil { log.Printf("failed to get logs: %v", err) return } logs, err := io.ReadAll(r) if err != nil { log.Printf("failed to read logs: %v", err) return } fmt.Println(string(logs))
Output: target2
Example (WithSubstitutors) ¶
ctx := context.Background() // applyImageSubstitutors { ctr, err := testcontainers.GenericContainer(ctx, testcontainers.GenericContainerRequest{ ContainerRequest: testcontainers.ContainerRequest{ Image: "alpine:latest", ImageSubstitutors: []testcontainers.ImageSubstitutor{dockerImageSubstitutor{}}, }, Started: true, }) defer func() { if err := testcontainers.TerminateContainer(ctr); err != nil { log.Printf("failed to terminate container: %s", err) } }() // } if err != nil { log.Printf("could not start container: %v", err) return } // enforce the concrete type, as GenericContainer returns an interface, // which will be changed in future implementations of the library dockerContainer := ctr.(*testcontainers.DockerContainer) fmt.Println(dockerContainer.Image)
Output: docker.io/alpine:latest
func ParallelContainers ¶ added in v0.14.0
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 ¶ added in v0.20.0
type ContainerCustomizer interface {
Customize(req *GenericContainerRequest) error
}
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 ¶ added in v0.14.0
type ContainerHook ¶ added in v0.20.0
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 - Readied - Stopping - Stopped - Terminating - Terminated For that, it will receive a Container, modify it and return an error if needed.
type ContainerLifecycleHooks ¶ added in v0.20.0
type ContainerLifecycleHooks struct { PreCreates []ContainerRequestHook PostCreates []ContainerHook PreStarts []ContainerHook PostStarts []ContainerHook PostReadies []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 ¶ added in v0.20.0
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 ¶ added in v0.20.0
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) Readied ¶ added in v0.28.0
func (c ContainerLifecycleHooks) Readied(ctx context.Context) func(container Container) error
Readied is a hook that will be called after a container is ready
func (ContainerLifecycleHooks) Started ¶ added in v0.20.0
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 ¶ added in v0.20.0
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 ¶ added in v0.20.0
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 ¶ added in v0.20.0
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 ¶ added in v0.20.0
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 ¶ added in v0.20.0
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 ¶ added in v0.13.0
type ContainerMount struct { // Source is typically either a GenericVolumeMountSource, as BindMount is not supported by all Docker environments 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
deprecated
added in
v0.13.0
func BindMount(hostPath string, mountTarget ContainerMountTarget) ContainerMount
Deprecated: use Files or HostConfigModifier in the ContainerRequest, or copy files container APIs to make containers portable across Docker environments BindMount returns a new ContainerMount with a GenericBindMountSource as source This is a convenience method to cover typical use cases.
func VolumeMount ¶ added in v0.13.0
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 ¶ added in v0.13.0
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 ¶ added in v0.13.0
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 ¶ added in v0.13.0
func (t ContainerMountTarget) Target() string
type ContainerMounts ¶ added in v0.13.0
type ContainerMounts []ContainerMount
ContainerMounts represents a collection of mounts for a container
func Mounts ¶ added in v0.13.0
func Mounts(mounts ...ContainerMount) ContainerMounts
Mounts returns a ContainerMounts to support a more fluent API
func (ContainerMounts) PrepareMounts ¶ added in v0.29.0
func (m ContainerMounts) PrepareMounts() []mount.Mount
PrepareMounts maps the given []ContainerMount to the corresponding []mount.Mount for further processing
type ContainerOption
deprecated
added in
v0.18.0
type ContainerOption func(*containerOptions)
Deprecated: it will be removed in the next major release functional option for setting the reaper image
func WithImageName
deprecated
added in
v0.18.0
func WithImageName(imageName string) ContainerOption
Deprecated: it will be removed in the next major release WithImageName sets the reaper image name
func WithRegistryCredentials
deprecated
added in
v0.18.0
func WithRegistryCredentials(registryCredentials string) ContainerOption
Deprecated: Testcontainers will detect registry credentials automatically, and it will be removed in the next major release 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 HostAccessPorts []int Image string ImageSubstitutors []ImageSubstitutor 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 WorkingDir string // specify the working directory of the container 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 // Deprecated: the reaper is configured at the properties level, for an entire test session 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 LogConsumerCfg *LogConsumerConfig // define the configuration for the log producer and its log consumers to follow the logs }
ContainerRequest represents the parameters used to get a running container
func (*ContainerRequest) BuildOptions ¶ added in v0.27.0
func (c *ContainerRequest) BuildOptions() (types.ImageBuildOptions, error)
BuildOptions returns the image build options when building a Docker image from a Dockerfile. It will apply some defaults and finally call the BuildOptionsModifier from the FromDockerfile struct, if set.
func (*ContainerRequest) GetAuthConfigs
deprecated
added in
v0.16.0
func (c *ContainerRequest) GetAuthConfigs() map[string]registry.AuthConfig
Deprecated: Testcontainers will detect registry credentials automatically, and it will be removed in the next major release. GetAuthConfigs returns the auth configs to be able to pull from an authenticated docker registry. Panics if an error occurs.
func (*ContainerRequest) GetBuildArgs ¶ added in v0.11.0
func (c *ContainerRequest) GetBuildArgs() map[string]*string
GetBuildArgs returns the env args to be used when creating from Dockerfile
func (*ContainerRequest) GetContext ¶ added in v0.0.8
func (c *ContainerRequest) GetContext() (io.Reader, error)
GetContext retrieve the build context for the request Must be closed when no longer needed.
func (*ContainerRequest) GetDockerfile ¶ added in v0.0.8
func (c *ContainerRequest) GetDockerfile() string
GetDockerfile returns the Dockerfile from the ContainerRequest, defaults to "Dockerfile"
func (*ContainerRequest) GetRepo ¶ added in v0.24.0
func (c *ContainerRequest) GetRepo() string
GetRepo returns the Repo label for image from the ContainerRequest, defaults to UUID
func (*ContainerRequest) GetTag ¶ added in v0.24.0
func (c *ContainerRequest) GetTag() string
GetTag returns the Tag label for image from the ContainerRequest, defaults to UUID
func (*ContainerRequest) ShouldBuildImage ¶ added in v0.0.9
func (c *ContainerRequest) ShouldBuildImage() bool
func (*ContainerRequest) ShouldKeepBuiltImage ¶ added in v0.26.0
func (c *ContainerRequest) ShouldKeepBuiltImage() bool
func (*ContainerRequest) ShouldPrintBuildLog ¶ added in v0.11.0
func (c *ContainerRequest) ShouldPrintBuildLog() bool
func (*ContainerRequest) Validate ¶ added in v0.0.8
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 ¶ added in v0.20.0
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 CustomHubSubstitutor ¶ added in v0.33.0
type CustomHubSubstitutor struct {
// contains filtered or unexported fields
}
CustomHubSubstitutor represents a way to substitute the hub of an image with a custom one, using provided value with respect to the HubImageNamePrefix configuration value.
func NewCustomHubSubstitutor ¶ added in v0.33.0
func NewCustomHubSubstitutor(hub string) CustomHubSubstitutor
NewCustomHubSubstitutor creates a new CustomHubSubstitutor
func (CustomHubSubstitutor) Description ¶ added in v0.33.0
func (c CustomHubSubstitutor) Description() string
Description returns the name of the type and a short description of how it modifies the image.
func (CustomHubSubstitutor) Substitute ¶ added in v0.33.0
func (c CustomHubSubstitutor) Substitute(image string) (string, error)
Substitute replaces the hub of the image with the provided one, with certain conditions:
- if the hub is empty, the image is returned as is.
- if the image already contains a registry, the image is returned as is.
- if the HubImageNamePrefix configuration value is set, the image is returned as is.
type CustomizeRequestOption ¶ added in v0.20.0
type CustomizeRequestOption func(req *GenericContainerRequest) error
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 ¶ added in v0.20.0
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 WithAfterReadyCommand ¶ added in v0.28.0
func WithAfterReadyCommand(execs ...Executable) CustomizeRequestOption
WithAfterReadyCommand will execute the command representation of each Executable into the container. It will leverage the container lifecycle hooks to call the command right after the container is ready.
func WithConfigModifier ¶ added in v0.20.0
func WithConfigModifier(modifier func(config *container.Config)) CustomizeRequestOption
WithConfigModifier allows to override the default container config
func WithEndpointSettingsModifier ¶ added in v0.20.0
func WithEndpointSettingsModifier(modifier func(settings map[string]*network.EndpointSettings)) CustomizeRequestOption
WithEndpointSettingsModifier allows to override the default endpoint settings
func WithEnv ¶ added in v0.29.0
func WithEnv(envs map[string]string) CustomizeRequestOption
WithEnv sets the environment variables for a container. If the environment variable already exists, it will be overridden.
func WithHostConfigModifier ¶ added in v0.20.0
func WithHostConfigModifier(modifier func(hostConfig *container.HostConfig)) CustomizeRequestOption
WithHostConfigModifier allows to override the default host config
func WithHostPortAccess ¶ added in v0.31.0
func WithHostPortAccess(ports ...int) CustomizeRequestOption
WithHostPortAccess allows to expose the host ports to the container
func WithImage
deprecated
added in
v0.20.0
func WithImage(image string) CustomizeRequestOption
Deprecated: the modules API forces passing the image as part of the signature of the Run function. WithImage sets the image for a container
func WithImageSubstitutors ¶ added in v0.26.0
func WithImageSubstitutors(fn ...ImageSubstitutor) CustomizeRequestOption
WithImageSubstitutors sets the image substitutors for a container
func WithLogConsumers ¶ added in v0.28.0
func WithLogConsumers(consumer ...LogConsumer) CustomizeRequestOption
WithLogConsumers sets the log consumers for a container
func WithStartupCommand ¶ added in v0.25.0
func WithStartupCommand(execs ...Executable) CustomizeRequestOption
WithStartupCommand will execute the command representation of each Executable into the container. It will leverage the container lifecycle hooks to call the command right after the container is started.
func WithWaitStrategy ¶ added in v0.20.0
func WithWaitStrategy(strategies ...wait.Strategy) CustomizeRequestOption
WithWaitStrategy sets the wait strategy for a container, using 60 seconds as deadline
func WithWaitStrategyAndDeadline ¶ added in v0.20.0
func WithWaitStrategyAndDeadline(deadline time.Duration, strategies ...wait.Strategy) CustomizeRequestOption
WithWaitStrategyAndDeadline sets the wait strategy for a container, including deadline
func (CustomizeRequestOption) Customize ¶ added in v0.20.0
func (opt CustomizeRequestOption) Customize(req *GenericContainerRequest) error
type DefaultNetwork
deprecated
added in
v0.14.0
type DefaultNetwork string
Deprecated: will be removed in the future.
func (DefaultNetwork) ApplyDockerTo
deprecated
added in
v0.14.0
func (n DefaultNetwork) ApplyDockerTo(opts *DockerProviderOptions)
Deprecated: will be removed in the future.
func (DefaultNetwork) ApplyGenericTo
deprecated
added in
v0.14.0
func (n DefaultNetwork) ApplyGenericTo(opts *GenericProviderOptions)
Deprecated: will be removed in the future.
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
deprecated
added in
v0.13.0
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 }
Deprecated: use Files or HostConfigModifier in the ContainerRequest, or copy files container APIs to make containers portable across Docker environments
func (DockerBindMountSource) GetBindOptions
deprecated
added in
v0.13.0
func (s DockerBindMountSource) GetBindOptions() *mount.BindOptions
Deprecated: use Files or HostConfigModifier in the ContainerRequest, or copy files container APIs to make containers portable across Docker environments
func (DockerBindMountSource) Source
deprecated
added in
v0.13.0
func (s DockerBindMountSource) Source() string
Deprecated: use Files or HostConfigModifier in the ContainerRequest, or copy files container APIs to make containers portable across Docker environments
func (DockerBindMountSource) Type
deprecated
added in
v0.13.0
func (DockerBindMountSource) Type() MountType
Deprecated: use Files or HostConfigModifier in the ContainerRequest, or copy files container APIs to make containers portable across Docker environments
type DockerClient ¶ added in v0.24.0
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 ¶ added in v0.24.0
func (*DockerClient) DiskUsage ¶ added in v0.24.0
func (c *DockerClient) DiskUsage(ctx context.Context, options types.DiskUsageOptions) (types.DiskUsage, error)
DiskUsage returns the disk usage of all images.
func (*DockerClient) Events ¶ added in v0.24.0
func (c *DockerClient) Events(ctx context.Context, options events.ListOptions) (<-chan events.Message, <-chan error)
Events returns a channel to listen to events that happen to the docker daemon.
func (*DockerClient) Info ¶ added in v0.24.0
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) RegistryLogin ¶ added in v0.24.0
func (c *DockerClient) RegistryLogin(ctx context.Context, auth registry.AuthConfig) (registry.AuthenticateOKBody, error)
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 ¶ added in v0.5.0
func (c *DockerContainer) ContainerIP(ctx context.Context) (string, error)
ContainerIP gets the IP address of the primary network within the container.
func (*DockerContainer) ContainerIPs ¶ added in v0.15.0
func (c *DockerContainer) ContainerIPs(ctx context.Context) ([]string, error)
ContainerIPs gets the IP addresses of all the networks within the container.
func (*DockerContainer) CopyDirToContainer ¶ added in v0.14.0
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 ¶ added in v0.12.0
func (c *DockerContainer) CopyFileFromContainer(ctx context.Context, filePath string) (io.ReadCloser, error)
func (*DockerContainer) CopyFileToContainer ¶ added in v0.8.0
func (*DockerContainer) CopyToContainer ¶ added in v0.13.0
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 ¶
Endpoint gets proto://host:port string for the lowest numbered exposed port Will returns just host:port if proto is ""
func (*DockerContainer) Exec ¶ added in v0.0.9
func (c *DockerContainer) Exec(ctx context.Context, cmd []string, options ...tcexec.ProcessOption) (int, io.Reader, error)
Exec executes a command in the current container. It returns the exit status of the executed command, an io.Reader containing the combined stdout and stderr, and any encountered error. Note that reading directly from the io.Reader may result in unexpected bytes due to custom stream multiplexing headers. Use tcexec.Multiplexed option to read the combined output without the multiplexing headers. Alternatively, to separate the stdout and stderr from io.Reader and interpret these headers properly, github.com/docker/docker/pkg/stdcopy.StdCopy from the Docker API should be used.
func (*DockerContainer) FollowOutput
deprecated
added in
v0.3.0
func (c *DockerContainer) FollowOutput(consumer LogConsumer)
Deprecated: use the ContainerRequest.LogConsumerConfig field instead.
func (*DockerContainer) GetContainerID ¶
func (c *DockerContainer) GetContainerID() string
func (*DockerContainer) GetLogProductionErrorChannel ¶ added in v0.28.0
func (c *DockerContainer) GetLogProductionErrorChannel() <-chan error
GetLogProductionErrorChannel exposes the only way for the consumer to be able to listen to errors and react to them.
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 "TESTCONTAINERS_HOST_OVERRIDE" env variable to set this yourself
func (*DockerContainer) Inspect ¶ added in v0.31.0
func (c *DockerContainer) Inspect(ctx context.Context) (*types.ContainerJSON, error)
Inspect gets the raw container info
func (*DockerContainer) IsRunning ¶ added in v0.14.0
func (c *DockerContainer) IsRunning() bool
func (*DockerContainer) Logs ¶
func (c *DockerContainer) Logs(ctx context.Context) (io.ReadCloser, error)
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 ¶
MappedPort gets externally mapped port for a container port
func (*DockerContainer) NetworkAliases ¶ added in v0.0.7
NetworkAliases gets the aliases of the container for the networks it is attached to.
func (*DockerContainer) Networks ¶ added in v0.0.7
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) SessionID ¶
func (c *DockerContainer) SessionID() string
SessionID gets the current session id
func (*DockerContainer) SetLogger ¶ added in v0.17.0
func (c *DockerContainer) SetLogger(logger Logging)
SetLogger sets the logger for the container
func (*DockerContainer) SetProvider ¶ added in v0.17.0
func (c *DockerContainer) SetProvider(provider *DockerProvider)
SetProvider sets the provider for the container
func (*DockerContainer) SetTerminationSignal ¶ added in v0.31.0
func (c *DockerContainer) SetTerminationSignal(signal chan bool)
SetTerminationSignal sets the termination signal for the container
func (*DockerContainer) Start ¶
func (c *DockerContainer) Start(ctx context.Context) error
Start will start an already created container
func (*DockerContainer) StartLogProducer
deprecated
added in
v0.3.0
func (c *DockerContainer) StartLogProducer(ctx context.Context, opts ...LogProductionOption) error
Deprecated: use the ContainerRequest.LogConsumerConfig field instead.
func (*DockerContainer) State ¶ added in v0.12.0
func (c *DockerContainer) State(ctx context.Context) (*types.ContainerState, error)
State returns container's running state.
func (*DockerContainer) Stop ¶ added in v0.13.0
Stop stops the 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.
All hooks are called in the following order:
- [ContainerLifecycleHooks.PreStops]
- [ContainerLifecycleHooks.PostStops]
If the container is already stopped, the method is a no-op.
func (*DockerContainer) StopLogProducer
deprecated
added in
v0.3.0
func (c *DockerContainer) StopLogProducer() error
Deprecated: it will be removed in the next major release.
func (*DockerContainer) Terminate ¶
func (c *DockerContainer) Terminate(ctx context.Context) error
Terminate calls stops and then removes the container including its volumes. If its image was built it and all child images are also removed unless the [FromDockerfile.KeepImage] on the ContainerRequest was set to true.
The following hooks are called in order:
- [ContainerLifecycleHooks.PreTerminates]
- [ContainerLifecycleHooks.PostTerminates]
type DockerNetwork ¶ added in v0.0.7
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 ¶ added in v0.0.7
func (n *DockerNetwork) Remove(ctx context.Context) error
Remove is used to remove the network. It is usually triggered by as defer function.
func (*DockerNetwork) SetTerminationSignal ¶ added in v0.31.0
func (n *DockerNetwork) SetTerminationSignal(signal chan bool)
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 ¶ added in v0.0.8
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 ¶ added in v0.17.0
func (p *DockerProvider) Client() client.APIClient
Client gets the docker client used by the provider
func (*DockerProvider) Close ¶ added in v0.20.0
func (p *DockerProvider) Close() error
Close closes the docker client used by the provider
func (*DockerProvider) Config ¶ added in v0.14.0
func (p *DockerProvider) Config() TestcontainersConfig
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) (con Container, err error)
CreateContainer fulfils 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, err := GenericContainer(ctx, GenericContainerRequest{ ContainerRequest: req, Started: true, }) defer func() { if err := TerminateContainer(nginxC); err != nil { log.Printf("failed to terminate container: %s", err) } }() if err != nil { log.Printf("failed to create container: %s", err) return } state, err := nginxC.State(ctx) if err != nil { log.Printf("failed to get container state: %s", err) return } fmt.Println(state.Running)
Output: true
func (*DockerProvider) CreateNetwork
deprecated
added in
v0.0.7
func (p *DockerProvider) CreateNetwork(ctx context.Context, req NetworkRequest) (net Network, err error)
Deprecated: use network.New instead CreateNetwork returns the object representing a new network identified by its name
func (*DockerProvider) DaemonHost ¶ added in v0.18.0
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 "TESTCONTAINERS_HOST_OVERRIDE" env variable to set this yourself
func (*DockerProvider) GetGatewayIP ¶ added in v0.8.0
func (p *DockerProvider) GetGatewayIP(ctx context.Context) (string, error)
func (*DockerProvider) GetNetwork ¶ added in v0.0.7
func (p *DockerProvider) GetNetwork(ctx context.Context, req NetworkRequest) (network.Inspect, error)
GetNetwork returns the object representing the network identified by its name
func (*DockerProvider) Health ¶ added in v0.7.0
func (p *DockerProvider) Health(ctx context.Context) 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) ListImages ¶ added in v0.25.0
func (p *DockerProvider) ListImages(ctx context.Context) ([]ImageInfo, error)
ListImages list images from the provider. If an image has multiple Tags, each tag is reported individually with the same ID and same labels
func (*DockerProvider) PullImage ¶ added in v0.25.0
func (p *DockerProvider) PullImage(ctx context.Context, img string) error
PullImage pulls image from registry
func (*DockerProvider) ReuseOrCreateContainer ¶ added in v0.14.0
func (p *DockerProvider) ReuseOrCreateContainer(ctx context.Context, req ContainerRequest) (con Container, err 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) SaveImages ¶ added in v0.25.0
SaveImages exports a list of images as an uncompressed tar
func (*DockerProvider) SetClient ¶ added in v0.17.0
func (p *DockerProvider) SetClient(c client.APIClient)
SetClient sets the docker client to be used by the provider
type DockerProviderOption ¶ added in v0.13.0
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 ¶ added in v0.13.0
func Generic2DockerOptions(opts ...GenericProviderOption) []DockerProviderOption
func WithDefaultBridgeNetwork ¶ added in v0.14.0
func WithDefaultBridgeNetwork(bridgeNetworkName string) DockerProviderOption
type DockerProviderOptionFunc ¶ added in v0.13.0
type DockerProviderOptionFunc func(opts *DockerProviderOptions)
DockerProviderOptionFunc is a shorthand to implement the DockerProviderOption interface
func (DockerProviderOptionFunc) ApplyDockerTo ¶ added in v0.13.0
func (f DockerProviderOptionFunc) ApplyDockerTo(opts *DockerProviderOptions)
type DockerProviderOptions ¶ added in v0.13.0
type DockerProviderOptions struct { *GenericProviderOptions // contains filtered or unexported fields }
DockerProviderOptions defines options applicable to DockerProvider
type DockerTmpfsMountSource ¶ added in v0.13.0
type DockerTmpfsMountSource struct { GenericTmpfsMountSource *mount.TmpfsOptions }
func (DockerTmpfsMountSource) GetTmpfsOptions ¶ added in v0.13.0
func (s DockerTmpfsMountSource) GetTmpfsOptions() *mount.TmpfsOptions
type DockerVolumeMountSource ¶ added in v0.13.0
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 ¶ added in v0.13.0
func (s DockerVolumeMountSource) GetVolumeOptions() *mount.VolumeOptions
func (DockerVolumeMountSource) Source ¶ added in v0.13.0
func (s DockerVolumeMountSource) Source() string
func (DockerVolumeMountSource) Type ¶ added in v0.13.0
func (DockerVolumeMountSource) Type() MountType
type ExecOptions ¶ added in v0.27.0
type ExecOptions struct {
// contains filtered or unexported fields
}
ExecOptions is a struct that provides a default implementation for the Options method of the Executable interface.
func (ExecOptions) Options ¶ added in v0.27.0
func (ce ExecOptions) Options() []tcexec.ProcessOption
type Executable ¶ added in v0.25.0
type Executable interface { AsCommand() []string // Options can container two different types of options: // - Docker's ExecConfigs (WithUser, WithWorkingDir, WithEnv, etc.) // - testcontainers' ProcessOptions (i.e. Multiplexed response) Options() []tcexec.ProcessOption }
Executable represents an executable command to be sent to a container, including options, as part of the different lifecycle hooks.
type FileFromContainer ¶ added in v0.12.0
type FileFromContainer struct {
// contains filtered or unexported fields
}
func (*FileFromContainer) Close ¶ added in v0.12.0
func (fc *FileFromContainer) Close() error
type FromDockerfile ¶ added in v0.0.8
type FromDockerfile struct { Context string // the path to the context of the docker build ContextArchive io.ReadSeeker // 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 // KeepImage describes whether DockerContainer.Terminate should not delete the // container image. Useful for images that are built from a Dockerfile and take a // long time to build. Keeping the image also Docker to reuse it. KeepImage bool // BuildOptionsModifier Modifier for the build options before image build. Use it for // advanced configurations while building the image. Please consider that the modifier // is called after the default build options are set. BuildOptionsModifier func(*types.ImageBuildOptions) }
FromDockerfile represents the parameters needed to build an image from a Dockerfile rather than using a pre-built one
type GenericBindMountSource
deprecated
added in
v0.13.0
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 }
Deprecated: use Files or HostConfigModifier in the ContainerRequest, or copy files container APIs to make containers portable across Docker environments GenericBindMountSource implements ContainerMountSource and represents a bind mount Optionally mount.BindOptions might be added for advanced scenarios
func (GenericBindMountSource) Source
deprecated
added in
v0.13.0
func (s GenericBindMountSource) Source() string
Deprecated: use Files or HostConfigModifier in the ContainerRequest, or copy files container APIs to make containers portable across Docker environments
func (GenericBindMountSource) Type
deprecated
added in
v0.13.0
func (GenericBindMountSource) Type() MountType
Deprecated: use Files or HostConfigModifier in the ContainerRequest, or copy files container APIs to make containers portable across Docker environments
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
deprecated
added in
v0.5.0
type GenericNetworkRequest struct { NetworkRequest // embedded request for provider ProviderType ProviderType // which provider to use, Docker if empty }
Deprecated: will be removed in the future. GenericNetworkRequest represents parameters to a generic network
type GenericProvider ¶ added in v0.0.7
type GenericProvider interface { ContainerProvider NetworkProvider ImageProvider }
GenericProvider represents an abstraction for container and network providers
type GenericProviderOption ¶ added in v0.13.0
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 ¶ added in v0.13.0
type GenericProviderOptionFunc func(opts *GenericProviderOptions)
GenericProviderOptionFunc is a shorthand to implement the GenericProviderOption interface
func (GenericProviderOptionFunc) ApplyGenericTo ¶ added in v0.13.0
func (f GenericProviderOptionFunc) ApplyGenericTo(opts *GenericProviderOptions)
type GenericProviderOptions ¶ added in v0.13.0
GenericProviderOptions defines options applicable to all providers
type GenericTmpfsMountSource ¶ added in v0.13.0
type GenericTmpfsMountSource struct{}
GenericTmpfsMountSource implements ContainerMountSource and represents a TmpFS mount Optionally mount.TmpfsOptions might be added for advanced scenarios
func (GenericTmpfsMountSource) Source ¶ added in v0.13.0
func (s GenericTmpfsMountSource) Source() string
func (GenericTmpfsMountSource) Type ¶ added in v0.13.0
func (GenericTmpfsMountSource) Type() MountType
type GenericVolumeMountSource ¶ added in v0.13.0
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 ¶ added in v0.13.0
func (s GenericVolumeMountSource) Source() string
func (GenericVolumeMountSource) Type ¶ added in v0.13.0
func (GenericVolumeMountSource) Type() MountType
type ImageBuildInfo ¶ added in v0.0.8
type ImageBuildInfo interface { BuildOptions() (types.ImageBuildOptions, error) // converts the ImageBuildInfo to a types.ImageBuildOptions 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 // Deprecated. Testcontainers will detect registry credentials automatically. Return the auth configs to be able to pull from an authenticated docker registry }
ImageBuildInfo defines what is needed to build an image
type ImageProvider ¶ added in v0.25.0
type ImageProvider interface { ListImages(context.Context) ([]ImageInfo, error) SaveImages(context.Context, string, ...string) error PullImage(context.Context, string) error }
ImageProvider allows manipulating images
type ImageSubstitutor ¶ added in v0.26.0
type ImageSubstitutor interface { // Description returns the name of the type and a short description of how it modifies the image. // Useful to be printed in logs Description() string Substitute(image string) (string, error) }
ImageSubstitutor represents a way to substitute container image names
type Log ¶ added in v0.3.0
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 ¶ added in v0.3.0
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 LogConsumerConfig ¶ added in v0.28.0
type LogConsumerConfig struct { Opts []LogProductionOption // options for the production of logs Consumers []LogConsumer // consumers for the logs }
LogConsumerConfig is a configuration object for the producer/consumer pattern
type LogProductionOption ¶ added in v0.28.0
type LogProductionOption func(*DockerContainer)
func WithLogProductionTimeout ¶ added in v0.28.0
func WithLogProductionTimeout(timeout time.Duration) LogProductionOption
WithLogProductionTimeout is a functional option that sets the timeout for the log production. If the timeout is lower than 5s or greater than 60s it will be set to 5s or 60s respectively.
type LoggerOption ¶ added in v0.13.0
type LoggerOption struct {
// contains filtered or unexported fields
}
LoggerOption is a generic option that sets the logger to be used.
It can be used to set the logger for providers and containers.
func WithLogger ¶ added in v0.13.0
func WithLogger(logger Logging) LoggerOption
WithLogger returns a generic option that sets the logger to be used.
Consider calling this before other "With functions" as these may generate logs.
This can be given a TestLogger to collect the logs from testcontainers into a test case.
func (LoggerOption) ApplyDockerTo ¶ added in v0.13.0
func (o LoggerOption) ApplyDockerTo(opts *DockerProviderOptions)
ApplyDockerTo implements DockerProviderOption.
func (LoggerOption) ApplyGenericTo ¶ added in v0.13.0
func (o LoggerOption) ApplyGenericTo(opts *GenericProviderOptions)
ApplyGenericTo implements GenericProviderOption.
func (LoggerOption) Customize ¶ added in v0.29.0
func (o LoggerOption) Customize(req *GenericContainerRequest) error
Customize implements ContainerCustomizer.
type Logging ¶ added in v0.13.0
type Logging interface {
Printf(format string, v ...interface{})
}
Logging defines the Logger interface
func TestLogger ¶ added in v0.13.0
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 Network
deprecated
added in
v0.0.7
Deprecated: will be removed in the future Network allows getting info about a single network instance
func GenericNetwork
deprecated
added in
v0.5.0
func GenericNetwork(ctx context.Context, req GenericNetworkRequest) (Network, error)
Deprecated: use network.New instead GenericNetwork creates a generic network with parameters
type NetworkProvider ¶ added in v0.0.7
type NetworkProvider interface { CreateNetwork(context.Context, NetworkRequest) (Network, error) // create a network GetNetwork(context.Context, NetworkRequest) (network.Inspect, error) // get a network }
NetworkProvider allows the creation of networks on an arbitrary system
type NetworkRequest
deprecated
added in
v0.0.7
type NetworkRequest struct { Driver string CheckDuplicate bool // Deprecated: CheckDuplicate is deprecated since API v1.44, but it defaults to true when sent by the client package to older daemons. 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 // Deprecated: the reaper is configured at the properties level, for an entire test session }
Deprecated: will be removed in the future NetworkRequest represents the parameters used to get a network
type ParallelContainerRequest ¶ added in v0.14.0
type ParallelContainerRequest []GenericContainerRequest
type ParallelContainersError ¶ added in v0.14.0
type ParallelContainersError struct {
Errors []ParallelContainersRequestError
}
func (ParallelContainersError) Error ¶ added in v0.14.0
func (gpe ParallelContainersError) Error() string
type ParallelContainersOptions ¶ added in v0.14.0
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 ¶ added in v0.14.0
type ParallelContainersRequestError struct { Request GenericContainerRequest Error error }
ParallelContainersRequestError represents error from parallel request
type PortForwarder ¶ added in v0.31.0
type PortForwarder struct {
// contains filtered or unexported fields
}
func NewPortForwarder ¶ added in v0.31.0
func NewPortForwarder(sshDAddr string, sshConfig *ssh.ClientConfig, remotePort, localPort int) *PortForwarder
func (*PortForwarder) Close ¶ added in v0.31.0
func (pf *PortForwarder) Close(ctx context.Context)
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 RawCommand ¶ added in v0.27.0
type RawCommand struct { ExecOptions // contains filtered or unexported fields }
RawCommand is a type that implements Executable and represents a command to be sent to a container
func NewRawCommand ¶ added in v0.27.0
func NewRawCommand(cmds []string) RawCommand
func (RawCommand) AsCommand ¶ added in v0.27.0
func (r RawCommand) AsCommand() []string
AsCommand returns the command as a slice of strings
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 any more. Compose module uses this method to create a reaper for the compose stack.
The caller must call Connect at least once on the returned Reaper and use the returned result otherwise the reaper will be kept open until the process exits.
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 StdoutLogConsumer ¶ added in v0.28.0
type StdoutLogConsumer struct{}
StdoutLogConsumer is a LogConsumer that prints the log to stdout
func (*StdoutLogConsumer) Accept ¶ added in v0.28.0
func (lc *StdoutLogConsumer) Accept(l Log)
Accept prints the log to stdout
type TerminateOption ¶ added in v0.34.0
type TerminateOption func(*terminateOptions)
TerminateOption is a type that represents an option for terminating a container.
func RemoveVolumes ¶ added in v0.34.0
func RemoveVolumes(volumes ...string) TerminateOption
RemoveVolumes returns a TerminateOption that sets additional volumes to remove. This is useful when the container creates named volumes that should be removed which are not removed by default. Default: nil.
func StopContext ¶ added in v0.34.0
func StopContext(ctx context.Context) TerminateOption
StopContext returns a TerminateOption that sets the context. Default: context.Background().
func StopTimeout ¶ added in v0.34.0
func StopTimeout(timeout time.Duration) TerminateOption
StopTimeout returns a TerminateOption that sets the timeout. Default: See [Container.Stop].
type TestcontainersConfig ¶ added in v0.20.0
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 ¶ added in v0.20.0
func ReadConfig() TestcontainersConfig
ReadConfig reads from testcontainers properties file, storing the result in a singleton instance of the TestcontainersConfig struct
type TmpfsMounter ¶ added in v0.13.0
type TmpfsMounter interface {
GetTmpfsOptions() *mount.TmpfsOptions
}
TmpfsMounter can optionally be implemented by mount sources to support advanced scenarios based on mount.TmpfsOptions
type VolumeMounter ¶ added in v0.13.0
type VolumeMounter interface {
GetVolumeOptions() *mount.VolumeOptions
}
VolumeMounter can optionally be implemented by mount sources to support advanced scenarios based on mount.VolumeOptions
Source Files ¶
Directories ¶
Path | Synopsis |
---|---|
examples
|
|
bigtable
Module
|
|
cockroachdb
Module
|
|
consul
Module
|
|
datastore
Module
|
|
firestore
Module
|
|
mongodb
Module
|
|
mysql
Module
|
|
nats
Module
|
|
nginx
Module
|
|
postgres
Module
|
|
pubsub
Module
|
|
pulsar
Module
|
|
redis
Module
|
|
spanner
Module
|
|
toxiproxy
Module
|
|
modulegen
module
|
|
modules
|
|
artemis
Module
|
|
azurite
Module
|
|
cassandra
Module
|
|
chroma
Module
|
|
clickhouse
Module
|
|
cockroachdb
Module
|
|
compose
Module
|
|
consul
Module
|
|
couchbase
Module
|
|
databend
Module
|
|
dolt
Module
|
|
dynamodb
Module
|
|
elasticsearch
Module
|
|
etcd
Module
|
|
gcloud
Module
|
|
grafana-lgtm
Module
|
|
inbucket
Module
|
|
influxdb
Module
|
|
k3s
Module
|
|
k6
Module
|
|
kafka
Module
|
|
localstack
Module
|
|
mariadb
Module
|
|
meilisearch
Module
|
|
milvus
Module
|
|
minio
Module
|
|
mockserver
Module
|
|
mongodb
Module
|
|
mssql
Module
|
|
mysql
Module
|
|
nats
Module
|
|
neo4j
Module
|
|
ollama
Module
|
|
openfga
Module
|
|
openldap
Module
|
|
opensearch
Module
|
|
postgres
Module
|
|
pulsar
Module
|
|
qdrant
Module
|
|
rabbitmq
Module
|
|
redis
Module
|
|
redpanda
Module
|
|
registry
Module
|
|
surrealdb
Module
|
|
valkey
Module
|
|
vault
Module
|
|
vearch
Module
|
|
weaviate
Module
|
|
yugabytedb
Module
|
|