Documentation
¶
Overview ¶
Package dockertest provides Docker container orchestration for Go testing.
Dockertest v4 uses the official github.com/moby/moby/client and provides a modern, context-aware API with automatic container reuse for fast tests.
Quick Start ¶
func TestDatabase(t *testing.T) {
pool := dockertest.NewPoolT(t, "")
db := pool.RunT(t, "postgres",
dockertest.WithTag("14"),
dockertest.WithEnv([]string{"POSTGRES_PASSWORD=secret"}),
)
db.Cleanup(t)
hostPort := db.GetHostPort("5432/tcp")
connStr := fmt.Sprintf("postgres://postgres:secret@%s/postgres?sslmode=disable", hostPort)
err := pool.Retry(t.Context(), 30*time.Second, func() error {
conn, err := sql.Open("postgres", connStr)
if err != nil {
return err
}
defer conn.Close()
return conn.Ping()
})
if err != nil {
t.Fatalf("Database not ready: %v", err)
}
}
Features ¶
- Container reuse: Containers are reused by default based on repository:tag for 2-3x faster tests - Context support: All operations accept context.Context for cancellation and timeouts - Test helpers: *T methods use t.Context() and t.Cleanup() for simplified test lifecycle - Networks: Create networks for container-to-container communication - Custom images: Build and run custom Docker images from Dockerfiles
See https://github.com/ory/dockertest for more examples and documentation.
Index ¶
- Variables
- func Register(reuseID string, r *Resource) error
- func ResetRegistry()
- func Retry(ctx context.Context, timeout, interval time.Duration, fn func() error) error
- func RetryWithBackoff(ctx context.Context, timeout, initialInterval, maxInterval time.Duration, ...) error
- type BuildOptions
- type ExecResult
- type Network
- type NetworkCreateOptions
- type Pool
- func (p *Pool) BuildAndRun(ctx context.Context, name string, buildOpts *BuildOptions, ...) (*Resource, error)
- func (p *Pool) BuildAndRunT(t TestingTB, name string, buildOpts *BuildOptions, runOpts ...RunOption) *Resource
- func (p *Pool) Close(ctx context.Context) error
- func (p *Pool) CreateNetwork(ctx context.Context, name string, opts *NetworkCreateOptions) (*Network, error)
- func (p *Pool) CreateNetworkT(t TestingTB, name string, opts *NetworkCreateOptions) *Network
- func (p *Pool) Retry(ctx context.Context, timeout time.Duration, fn func() error) error
- func (p *Pool) Run(ctx context.Context, repository string, opts ...RunOption) (*Resource, error)
- func (p *Pool) RunT(t TestingTB, repository string, opts ...RunOption) *Resource
- type PoolOption
- type Resource
- func (r *Resource) Cleanup(t TestingTB)
- func (r *Resource) Close(ctx context.Context) error
- func (r *Resource) CloseT(t TestingTB)
- func (r *Resource) ConnectToNetwork(ctx context.Context, net *Network) error
- func (r *Resource) DisconnectFromNetwork(ctx context.Context, net *Network) error
- func (r *Resource) Exec(ctx context.Context, cmd []string) (ExecResult, error)
- func (r *Resource) GetBoundIP(portID string) string
- func (r *Resource) GetHostPort(portID string) string
- func (r *Resource) GetIPInNetwork(net *Network) string
- func (r *Resource) GetPort(portID string) string
- func (r *Resource) ID() string
- func (r *Resource) Logs(ctx context.Context) (string, error)
- type RunOption
- func WithCmd(cmd []string) RunOption
- func WithContainerConfig(modifier func(*container.Config)) RunOption
- func WithEntrypoint(entrypoint []string) RunOption
- func WithEnv(env []string) RunOption
- func WithHostConfig(modifier func(*container.HostConfig)) RunOption
- func WithHostname(hostname string) RunOption
- func WithLabels(labels map[string]string) RunOption
- func WithReuseID(id string) RunOption
- func WithTag(tag string) RunOption
- func WithUser(user string) RunOption
- func WithWorkingDir(dir string) RunOption
- func WithoutReuse() RunOption
- type TestingTB
Constants ¶
This section is empty.
Variables ¶
var ErrClientClosed = errors.New("client is closed")
ErrClientClosed is returned when an operation is attempted on a resource whose pool or client has already been closed.
var ErrContainerCreateFailed = errors.New("container creation failed")
ErrContainerCreateFailed is returned when container creation fails.
var ErrContainerStartFailed = errors.New("container start failed")
ErrContainerStartFailed is returned when starting a container fails.
var ErrImagePullFailed = errors.New("image pull failed")
ErrImagePullFailed is returned when pulling a Docker image fails.
Functions ¶
func Register ¶
Register stores a resource with the given reuseID in the global registry.
If a resource with the same reuseID already exists, the existing resource is kept and no error is returned. This ensures that concurrent registration attempts result in exactly one resource being stored. The race winner's resource becomes the canonical one in the registry, which is safe because both resources represent containers with the same configuration (same image, tag, env, etc.).
The global registry enables container reuse across tests. Containers registered here can be retrieved with Get.
Note: This function is called automatically by Pool.Run when container reuse is enabled. You typically don't need to call it directly.
func ResetRegistry ¶
func ResetRegistry()
ResetRegistry clears all resources from the global registry. This does NOT stop or remove the containers themselves.
func Retry ¶
Retry retries fn with a fixed interval until it succeeds, the context is cancelled, or the timeout is reached. The interval is deterministic (no jitter).
func RetryWithBackoff ¶
func RetryWithBackoff(ctx context.Context, timeout, initialInterval, maxInterval time.Duration, fn func() error) error
RetryWithBackoff retries fn with exponential backoff until it succeeds, the context is cancelled, or the timeout is reached.
The interval starts at initialInterval and doubles after each attempt, capped at maxInterval. The backoff is deterministic (no jitter).
Types ¶
type BuildOptions ¶
type BuildOptions struct {
// Dockerfile is the name of the Dockerfile within the ContextDir.
// Defaults to "Dockerfile" if empty.
Dockerfile string
// ContextDir is the directory containing the Dockerfile and build context.
// This directory will be archived and sent to the Docker daemon.
// REQUIRED - build will fail if empty.
ContextDir string
// Tags are the tags to apply to the built image.
// If empty, the image name from BuildAndRun will be used.
Tags []string
// BuildArgs are build-time variables passed to the Dockerfile.
// Use pointers to distinguish between empty string and unset.
// Example: map[string]*string{"VERSION": &versionStr}
BuildArgs map[string]*string
// Labels are metadata to apply to the built image.
// Example: map[string]string{"version": "1.0", "env": "test"}
Labels map[string]string
// NoCache disables build cache when set to true.
// Useful for ensuring a clean build.
NoCache bool
// ForceRemove always removes intermediate containers, even on build failure.
// Useful for keeping the build environment clean.
ForceRemove bool
}
BuildOptions configures image building from a Dockerfile. Use with Pool.BuildAndRun to build and run custom Docker images.
Only ContextDir is required. All other fields are optional and have sensible defaults.
type ExecResult ¶
ExecResult holds the output of a command executed inside a container.
type Network ¶
Network represents a Docker network managed by dockertest. Networks allow containers to communicate with each other using container names as hostnames, isolated from other networks.
Create networks with Pool.CreateNetwork and connect containers with Resource.ConnectToNetwork.
type NetworkCreateOptions ¶
type NetworkCreateOptions struct {
Driver string // Network driver (e.g., "bridge", "overlay")
Labels map[string]string // User-defined metadata
Options map[string]string // Driver-specific options
Internal bool // Restrict external access to the network
Attachable bool // Enable manual container attachment
Ingress bool // Create an ingress network (swarm mode)
EnableIPv6 bool // Enable IPv6 networking
}
NetworkCreateOptions holds options for creating a network. This is a subset of mobyclient.NetworkCreateOptions from github.com/moby/moby/client to provide a simpler API while allowing common customizations.
All fields are optional. If not specified, Docker's defaults are used:
- Driver defaults to "bridge"
- Internal defaults to false (network has external access)
- Attachable defaults to false
- EnableIPv6 defaults to false
type Pool ¶
type Pool struct {
MaxWait time.Duration // maximum wait time for operations
// contains filtered or unexported fields
}
Pool manages Docker resources and operations. It provides methods for running containers, building images, creating networks, and managing the lifecycle of Docker resources in tests.
A Pool instance owns a Docker client connection and manages resources through that connection. Use NewPool or NewPoolT to create a Pool, and Close to clean up.
func NewPool ¶
NewPool creates a new Pool with the given endpoint and options.
The endpoint parameter must be empty. The Docker client is created from environment variables (DOCKER_HOST, DOCKER_TLS_VERIFY, DOCKER_CERT_PATH) or provided via WithMobyClient option.
To specify a custom Docker endpoint, set the DOCKER_HOST environment variable before calling NewPool, or provide a custom client with WithMobyClient.
The default MaxWait is 60 seconds. This can be customized with WithMaxWait.
The Pool creates and owns a Docker client by default. Call Close when done to release resources. If you need to provide your own client, use WithMobyClient.
Example:
ctx := context.Background()
pool, err := dockertest.NewPool(ctx, "")
if err != nil {
panic(err)
}
defer pool.Close(ctx)
func NewPoolT ¶
func NewPoolT(t *testing.T, endpoint string, opts ...PoolOption) *Pool
NewPoolT creates a new Pool using t.Context() and registers cleanup with t.Cleanup().
func (*Pool) BuildAndRun ¶
func (p *Pool) BuildAndRun(ctx context.Context, name string, buildOpts *BuildOptions, runOpts ...RunOption) (*Resource, error)
BuildAndRun builds a Docker image from a Dockerfile and runs it as a container.
The name parameter is used as the image tag. buildOpts.ContextDir is required. The built image is cleaned up on error, but not on success - it will be reused for subsequent runs with the same name, making repeated test runs faster.
Example:
resource, err := pool.BuildAndRun(ctx, "myapp:test",
&dockertest.BuildOptions{
ContextDir: "./testdata",
Dockerfile: "Dockerfile.test",
},
)
if err != nil {
panic(err)
}
defer resource.Close(ctx)
func (*Pool) BuildAndRunT ¶
func (p *Pool) BuildAndRunT(t TestingTB, name string, buildOpts *BuildOptions, runOpts ...RunOption) *Resource
BuildAndRunT is a test helper that uses t.Context() and calls t.Fatalf on error.
func (*Pool) Close ¶
Close cleans up all tracked containers and networks, then closes the Pool's Docker client if it was created by the Pool. If a custom client was provided via WithMobyClient, it is not closed (the caller remains responsible for closing it).
It is safe to call Close multiple times.
func (*Pool) CreateNetwork ¶
func (p *Pool) CreateNetwork(ctx context.Context, name string, opts *NetworkCreateOptions) (*Network, error)
CreateNetwork creates a new Docker network with the given name and options. If opts is nil, default network options are used (bridge driver, external access allowed).
func (*Pool) CreateNetworkT ¶
func (p *Pool) CreateNetworkT(t TestingTB, name string, opts *NetworkCreateOptions) *Network
CreateNetworkT creates a network using t.Context() and calls t.Fatalf on error.
func (*Pool) Retry ¶
Retry is a convenience method that wraps the package-level Retry function. If timeout is 0, Pool.MaxWait is used as the default. The interval is fixed at 1 second.
func (*Pool) Run ¶
Run starts a container with the given repository and options. Containers are reused by default based on repository:tag to speed up tests.
Example:
resource, err := pool.Run(ctx, "postgres",
dockertest.WithTag("14"),
dockertest.WithEnv([]string{"POSTGRES_PASSWORD=secret"}),
)
if err != nil {
panic(err)
}
defer resource.Close(ctx)
type PoolOption ¶
type PoolOption func(*Pool)
PoolOption is a functional option for configuring a Pool. Use with NewPool or NewPoolT to customize Pool behavior.
func WithMaxWait ¶
func WithMaxWait(d time.Duration) PoolOption
WithMaxWait sets the maximum wait time for operations. The default MaxWait is 60 seconds.
func WithMobyClient ¶
func WithMobyClient(c client.DockerClient) PoolOption
WithMobyClient sets a custom Docker client. When a custom client is provided, the Pool will not close it on Pool.Close().
type Resource ¶
type Resource struct {
Container container.InspectResponse
// contains filtered or unexported fields
}
Resource represents a Docker container managed by dockertest. It provides methods for interacting with the container (getting ports, closing, etc.) and accessing the underlying Docker container details.
func Get ¶
Get retrieves a resource from the global registry by reuseID. Returns the resource and true if found, nil and false otherwise.
The global registry stores containers for reuse. By default, containers are registered with a reuseID of "repository:tag".
Note: This function is called automatically by Pool.Run when checking for existing containers. You typically don't need to call it directly.
func GetAll ¶
func GetAll() []*Resource
GetAll returns a slice of all resources in the global registry. The order of resources in the returned slice is not guaranteed.
This is useful for cleanup operations that need to process all registered containers:
func cleanupAll(ctx context.Context) {
for _, resource := range dockertest.GetAll() {
_ = resource.Close(ctx)
}
dockertest.ResetRegistry()
}
func (*Resource) Cleanup ¶
Cleanup registers container cleanup with t.Cleanup. The container will be removed when the test finishes.
func (*Resource) Close ¶
Close stops and removes the container. Anonymous volumes created by the container are also removed.
func (*Resource) ConnectToNetwork ¶
ConnectToNetwork connects the container to the given network. The resource's Container field is automatically updated with the latest network settings after connection.
func (*Resource) DisconnectFromNetwork ¶
DisconnectFromNetwork disconnects the container from the given network. The resource's Container field is automatically updated with the latest network settings after disconnection.
func (*Resource) GetBoundIP ¶
GetBoundIP returns the host IP bound to the given container port. The portID parameter should include the protocol (e.g., "5432/tcp").
func (*Resource) GetHostPort ¶
GetHostPort returns the host:port combination for the given container port. The portID parameter should include the protocol (e.g., "5432/tcp").
func (*Resource) GetIPInNetwork ¶
GetIPInNetwork returns the container's IP address in the given network. Returns empty string if the container is not connected to the network.
type RunOption ¶
type RunOption func(*runConfig) error
RunOption configures container creation. Use with Pool.Run or Pool.RunT to customize how containers are started.
func WithContainerConfig ¶
WithContainerConfig allows direct modification of the container.Config. This is useful for advanced options not covered by other WithXxx functions. The modifier is applied after all other options are processed.
func WithEntrypoint ¶
WithEntrypoint sets the container entrypoint, overriding the image's default ENTRYPOINT.
func WithEnv ¶
WithEnv sets environment variables for the container. Each string should be in "KEY=value" format.
func WithHostConfig ¶
func WithHostConfig(modifier func(*container.HostConfig)) RunOption
WithHostConfig allows direct modification of the container.HostConfig. Use this to set host-level options like port bindings, volume mounts, restart policies, memory/CPU limits, or AutoRemove. The modifier is applied after the default HostConfig is constructed.
func WithHostname ¶
WithHostname sets the container's hostname.
func WithLabels ¶
WithLabels sets labels on the container. Labels are useful for marking test containers or adding metadata.
func WithReuseID ¶
WithReuseID sets a custom reuse ID for container reuse. By default, containers are reused based on "repository:tag".
func WithUser ¶
WithUser sets the user that will run commands inside the container. Supports both "user" and "user:group" formats.
func WithWorkingDir ¶
WithWorkingDir sets the working directory for commands run in the container.
func WithoutReuse ¶
func WithoutReuse() RunOption
WithoutReuse disables container reuse for this run. A new container will be created every time.
type TestingTB ¶
type TestingTB interface {
Helper()
Context() context.Context
Cleanup(func())
Logf(format string, args ...any)
Fatalf(format string, args ...any)
}
TestingTB is a subset of testing.TB for dependency injection. This interface allows methods to work with test helpers without directly depending on the testing package.
