dockertest

package module
v4.0.1 Latest Latest
Warning

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

Go to latest
Published: Oct 19, 2026 License: Apache-2.0 Imports: 36 Imported by: 0

README

ORY Dockertest

CI

Use Docker to run your Go integration tests against third party services on Windows, macOS, and Linux!

Dockertest supports running any Docker image from Docker Hub or from a Dockerfile.

Why should I use Dockertest?

When developing applications, it is often necessary to use services that talk to a database system. Unit testing these services can be cumbersome because mocking database/DBAL is strenuous. Making slight changes to the schema implies rewriting at least some, if not all mocks. The same goes for API changes in the DBAL.

To avoid this, it is smarter to test these specific services against a real database that is destroyed after testing. Docker is the perfect system for running integration tests as you can spin up containers in a few seconds and kill them when the test completes.

The Dockertest library provides easy to use commands for spinning up Docker containers and using them for your tests.

Installation

go get github.com/ory/dockertest/v4

Quick Start

package myapp_test

import (
    "testing"
    "time"

    dockertest "github.com/ory/dockertest/v4"
)

func TestPostgres(t *testing.T) {
    pool := dockertest.NewPoolT(t, "")

    // Container is automatically reused across test runs based on "postgres:14".
    postgres := pool.RunT(t, "postgres",
        dockertest.WithTag("14"),
        dockertest.WithEnv([]string{
            "POSTGRES_PASSWORD=secret",
            "POSTGRES_DB=testdb",
        }),
    )

    hostPort := postgres.GetHostPort("5432/tcp")
    // Connect to postgres://postgres:secret@hostPort/testdb

    // Wait for PostgreSQL to be ready
    err := pool.Retry(t.Context(), 30*time.Second, func() error {
        // try connecting...
        return nil
    })
    if err != nil {
        t.Fatalf("Could not connect: %v", err)
    }
}

Migration from v3

Version 4 introduces automatic container reuse, making tests significantly faster by reusing containers across test runs. Additionally, a lightweight docker client is used which reduces third party dependencies significantly.

See UPGRADE.md for the complete migration guide.

API overview

View the Go API documentation.

Pool creation

// For tests - auto-cleanup with t.Cleanup()
pool := dockertest.NewPoolT(t, "")

// With options
pool := dockertest.NewPoolT(t, "",
    dockertest.WithMaxWait(2*time.Minute),
)

// With a custom Docker client
pool := dockertest.NewPoolT(t, "",
    dockertest.WithMobyClient(myClient),
)

// For non-test code - requires manual Close()
ctx := context.Background()
pool, err := dockertest.NewPool(ctx, "")
if err != nil {
    panic(err)
}
defer pool.Close(ctx)

Running containers

// Test helper - fails test on error
resource := pool.RunT(t, "postgres",
    dockertest.WithTag("14"),
    dockertest.WithEnv([]string{"POSTGRES_PASSWORD=secret"}),
    dockertest.WithCmd([]string{"postgres", "-c", "log_statement=all"}),
)

// With error handling
resource, err := pool.Run(ctx, "postgres",
    dockertest.WithTag("14"),
    dockertest.WithEnv([]string{"POSTGRES_PASSWORD=secret"}),
)
if err != nil {
    panic(err)
}

See Cleanup for container lifecycle management.

Container configuration

Customize container settings with configuration options:

resource := pool.RunT(t, "postgres",
    dockertest.WithTag("14"),
    dockertest.WithUser("postgres"),
    dockertest.WithWorkingDir("/var/lib/postgresql/data"),
    dockertest.WithLabels(map[string]string{
        "test":    "integration",
        "service": "database",
    }),
    dockertest.WithHostname("test-db"),
    dockertest.WithEnv([]string{"POSTGRES_PASSWORD=secret"}),
)

Available configuration options:

  • WithTag(tag string) - Set the image tag (default: "latest")
  • WithEnv(env []string) - Set environment variables
  • WithCmd(cmd []string) - Override the default command
  • WithEntrypoint(entrypoint []string) - Override the default entrypoint
  • WithUser(user string) - Set the user to run commands as (supports "user" or "user:group")
  • WithWorkingDir(dir string) - Set the working directory
  • WithLabels(labels map[string]string) - Add labels to the container
  • WithHostname(hostname string) - Set the container hostname
  • WithName(name string) - Set the container name
  • WithMounts(binds []string) - Set bind mounts ("host:container" or "host:container:mode")
  • WithPortBindings(bindings network.PortMap) - Set explicit port bindings
  • WithReuseID(id string) - Set a custom reuse key (default: "repository:tag")
  • WithoutReuse() - Disable container reuse for this run
  • WithContainerConfig(modifier func(*container.Config)) - Modify the container config directly
  • WithHostConfig(modifier func(*container.HostConfig)) - Modify the host config (port bindings, volumes, restart policy, memory/CPU limits)

For advanced container configuration, use WithContainerConfig:

stopTimeout := 30
resource := pool.RunT(t, "app",
    dockertest.WithContainerConfig(func(cfg *container.Config) {
        cfg.StopTimeout = &stopTimeout
        cfg.StopSignal = "SIGTERM"
        cfg.Healthcheck = &container.HealthConfig{
            Test:     []string{"CMD", "curl", "-f", "http://localhost/health"},
            Interval: 10 * time.Second,
            Timeout:  5 * time.Second,
            Retries:  3,
        }
    }),
)

For host-level configuration, use WithHostConfig:

resource := pool.RunT(t, "postgres",
    dockertest.WithTag("14"),
    dockertest.WithHostConfig(func(hc *container.HostConfig) {
        hc.RestartPolicy = container.RestartPolicy{
            Name:              container.RestartPolicyOnFailure,
            MaximumRetryCount: 3,
        }
    }),
)

Container reuse

Containers are automatically reused based on repository:tag. Reuse is reference-counted: each Run/RunT call increments the ref count, and each Close/cleanup decrements it. The container is only removed from Docker when the last reference is released.

// First test creates container
r1 := pool.RunT(t, "postgres", dockertest.WithTag("14"))

// Second test reuses the same container
r2 := pool.RunT(t, "postgres", dockertest.WithTag("14"))

// r1 and r2 point to the same container

Disable reuse if needed:

resource := pool.RunT(t, "postgres",
    dockertest.WithTag("14"),
    dockertest.WithoutReuse(), // Always create new container
)

Getting connection info

resource := pool.RunT(t, "postgres", dockertest.WithTag("14"))

// Get host:port (e.g., "127.0.0.1:54320")
hostPort := resource.GetHostPort("5432/tcp")

// Get just the port (e.g., "54320")
port := resource.GetPort("5432/tcp")

// Get just the IP (e.g., "127.0.0.1")
ip := resource.GetBoundIP("5432/tcp")

// Get container ID
id := resource.ID()

Waiting for readiness

Use pool.Retry to wait for a container to become ready:

err := pool.Retry(t.Context(), 30*time.Second, func() error {
    return db.Ping()
})
if err != nil {
    t.Fatalf("Container not ready: %v", err)
}

If timeout is 0, pool.MaxWait (default 60s) is used. The retry interval is fixed at 1 second.

For more control, use the package-level functions:

// Fixed interval retry
err := dockertest.Retry(ctx, 30*time.Second, 500*time.Millisecond, func() error {
    return db.Ping()
})

// Exponential backoff retry
err := dockertest.RetryWithBackoff(ctx,
    30*time.Second,       // timeout
    100*time.Millisecond, // initial interval
    5*time.Second,        // max interval
    func() error {
        return db.Ping()
    },
)

Executing commands

Run commands inside a running container:

result, err := resource.Exec(ctx, []string{"pg_isready", "-U", "postgres"})
if err != nil {
    t.Fatal(err)
}
if result.ExitCode != 0 {
    t.Fatalf("command failed: %s", result.StdErr)
}
t.Log(result.StdOut)

Container logs

// Get all logs with stdout and stderr separated
stdout, stderr, err := resource.Logs(ctx)
if err != nil {
    t.Fatal(err)
}
t.Log(stdout)
t.Log(stderr)

// Stream logs until container exits or ctx is cancelled
var buf bytes.Buffer
err = resource.FollowLogs(ctx, &buf, io.Discard)

Building from Dockerfile

Build a Docker image from a Dockerfile and run it:

version := "1.0.0"
resource, err := pool.BuildAndRun(ctx, "myapp:test",
    &dockertest.BuildOptions{
        ContextDir: "./testdata",
        Dockerfile: "Dockerfile.test",
        BuildArgs:  map[string]*string{"VERSION": &version},
    },
    dockertest.WithEnv([]string{"APP_ENV=test"}),
)
if err != nil {
    t.Fatal(err)
}

BuildAndRunT is the test helper variant:

resource := pool.BuildAndRunT(t, "myapp:test",
    &dockertest.BuildOptions{
        ContextDir: "./testdata",
    },
)

The container is created from the immutable ID of the built image, so a changed build under the same tag never reuses an older container.

Built images remain available across runs. Images, builder cache, named volumes, and pre-existing unlabeled resources remain outside automatic cleanup. ForceRemove only removes intermediate build containers.

Networks

Create Docker networks for container-to-container communication:

net := pool.CreateNetworkT(t, "my-network", nil)

// Connect a container
err := resource.ConnectToNetwork(ctx, net)

// Get the container's IP in the network
ip := resource.GetIPInNetwork(net)

// Disconnect
err := resource.DisconnectFromNetwork(ctx, net)

With custom options:

net, err := pool.CreateNetwork(ctx, "my-network", &dockertest.NetworkCreateOptions{
    Driver:   "bridge",
    Internal: true,
})

Cleanup

NewPoolT + RunT (recommended): Cleanup is fully automatic. RunT registers cleanup via t.Cleanup, and the pool is closed when the test finishes. Nothing to do.

func TestDB(t *testing.T) {
    pool := dockertest.NewPoolT(t, "")
    resource := pool.RunT(t, "postgres", dockertest.WithTag("14"))
    // Use resource... cleanup happens automatically when t finishes.
}

NewPool + Run: Call resource.Close(ctx) to release individual containers, or pool.Close(ctx) to release everything:

ctx := context.Background()
pool, err := dockertest.NewPool(ctx, "")
if err != nil {
    panic(err)
}
defer pool.Close(ctx) // releases all tracked containers and networks

resource, err := pool.Run(ctx, "postgres", dockertest.WithTag("14"))
if err != nil {
    panic(err)
}
defer resource.Close(ctx) // or let pool.Close handle it

Each cleanup runs under a context deadline of the pool's cleanup timeout (60 seconds by default, see WithCleanupTimeout), or the caller's deadline if that is earlier. A failed removal is returned and retried by the next Close. Containers are force-removed together with their anonymous volumes; named volumes and images are left alone.

Process-wide cleanup with TestMain: a package's TestMain can hand control to dockertest.TestMain, which cleans up the package's owned containers and networks, even when a test hangs or the process is interrupted:

func TestMain(m *testing.M) {
    dockertest.TestMain(context.Background(), m)
}
  • TestMain owns process exit: it runs m.Run and exits with its status after cleanup. Cleanup failures and leftover resource IDs are printed to stderr but never change a passing or failing status.
  • On SIGINT or SIGTERM (Ctrl+C or Ctrl+Break on Windows), cleanup starts even if a test is stuck and the process exits with 130 or 143. A second signal terminates immediately.
  • WithShutdownTimeout (60 seconds by default) is the deadline of the whole shutdown, including the optional WithTeardown callback that runs before Docker resources are removed. TestMain exits shortly after the deadline even if a callback or a custom client ignores its context; whatever is left then is removed by a later run once it expires.
  • WithTeardown is only for state dockertest does not own. Pools, containers, and networks created through dockertest, including package-wide ones started before m.Run, are removed and their clients closed without it.
  • Containers and networks carry an io.ory.dockertest.expires label: the start time plus -test.timeout, the shutdown timeout, and a minute of margin. Once it has passed, go test has killed the process. At shutdown, TestMain also removes expired resources on every Docker daemon its pools used, so leftovers of a kill, a -timeout panic, or a power loss disappear with a later run. A failure to remove another run's expired resource is printed but is not reported as this run's cleanup failure. With -test.timeout=0, -test.bench, or -test.fuzz (which run after the test timeout stops) resources get no expiry and are never removed by other runs.
  • Pools may be created before TestMain as long as no container, network, or image was created yet. TestMain must be installed once per process.

Composing with Wrap: when the package needs code around m.Run, a leak check, or control over the exit status, dockertest.Wrap returns the same cleanup around any func() int. Its Run method returns the exit status instead of exiting, so it plugs into helpers such as goleak.VerifyTestMain:

func TestMain(m *testing.M) {
    goleak.VerifyTestMain(dockertest.Wrap(context.Background(), m.Run))
}
func TestMain(m *testing.M) {
    os.Exit(dockertest.Wrap(context.Background(), func() int {
        // Package setup, for example shared containers.
        return m.Run()
    }).Run())
}
  • Run installs the cleanup, calls the function, shuts down as TestMain does, and returns the function's status. Cleanup failures are printed, not returned.
  • Invalid options, a second TestMain or Wrap, or Docker resources created before it are printed and make Run return 1 without running the tests.
  • When Run returns, signal handling has stopped and the clients pools created are closed, so a leak check after it sees no dockertest goroutine.
  • Signals and expiry labels behave as under TestMain.

NewPoolT and RunT keep working without TestMain or Wrap, which add the guarantees above for abnormal exits.

Error handling

resource, err := pool.Run(ctx, "postgres", dockertest.WithTag("14"))
if errors.Is(err, dockertest.ErrImagePullFailed) {
    // Image could not be pulled
}
if errors.Is(err, dockertest.ErrContainerCreateFailed) {
    // Container creation failed
}
if errors.Is(err, dockertest.ErrContainerStartFailed) {
    // Container start failed
}
if errors.Is(err, dockertest.ErrClientClosed) {
    // Pool or client has been closed
}

Examples

See the examples directory for complete examples.

Troubleshoot & FAQ

Out of disk space

Try cleaning up unused containers, images, and volumes:

docker system prune -f

Running in CI

GitHub Actions

Docker is available by default on GitHub Actions ubuntu-latest runners, so no extra services are needed:

name: Test with Docker

on: [push]

jobs:
  test:
    runs-on: ubuntu-latest
    steps:
      - uses: actions/checkout@v4

      - uses: actions/setup-go@v5
        with:
          go-version: "1.24"

      - run: go test -v ./...

GitLab CI

Shared runners

Add the Docker dind service to your job which starts in a sibling container. The database will be available on host docker. Your app should be able to change the database host through an environment variable.

stages:
  - test
go-test:
  stage: test
  image: golang:1.24
  services:
    - docker:dind
  variables:
    DOCKER_HOST: tcp://docker:2375
    DOCKER_DRIVER: overlay2
    DOCKER_TLS_CERTDIR: ""
    YOUR_APP_DB_HOST: docker
  script:
    - go test ./...

In your pool.Retry callback, use $YOUR_APP_DB_HOST instead of localhost when connecting to the database.

Custom (group) runners

GitLab runner can be run in docker executor mode to save compatibility with shared runners:

gitlab-runner register -n \
 --url https://gitlab.com/ \
 --registration-token $YOUR_TOKEN \
 --executor docker \
 --description "My Docker Runner" \
 --docker-image "docker:27" \
 --docker-privileged

The DOCKER_TLS_CERTDIR: "" variable in the example above tells the Docker daemon to start on port 2375 over HTTP (TLS disabled).

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

Constants

This section is empty.

Variables

View Source
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.

View Source
var ErrContainerCreateFailed = errors.New("container creation failed")

ErrContainerCreateFailed is returned when container creation fails.

View Source
var ErrContainerStartFailed = errors.New("container start failed")

ErrContainerStartFailed is returned when starting a container fails.

View Source
var ErrImageBuildFailed = errors.New("image build failed")

ErrImageBuildFailed is returned when building a Docker image fails.

View Source
var ErrImagePullFailed = errors.New("image pull failed")

ErrImagePullFailed is returned when pulling a Docker image fails.

View Source
var ErrInvalidOption = errors.New("invalid option")

ErrInvalidOption is returned for invalid pool, build, TestMain, or Wrap options.

View Source
var ErrShuttingDown = errors.New("dockertest is shutting down")

ErrShuttingDown is returned when a new Docker resource is requested after TestMain or Wrap has started process shutdown.

Functions

func Register

func Register(reuseID string, r ClosableResource) error

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

func Retry(ctx context.Context, timeout, interval time.Duration, fn func() error) error

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).

func TestMain added in v4.0.1

func TestMain(ctx context.Context, m *testing.M, opts ...TestMainOption)

TestMain runs the tests of a package and cleans up its owned Docker resources, even when a test hangs or the process is interrupted. Images, builder cache, named volumes, and pre-existing unlabeled resources are outside automatic cleanup. Use it from the package's TestMain:

func TestMain(m *testing.M) {
	dockertest.TestMain(context.Background(), m)
}

TestMain owns process exit and never returns. It calls m.Run on the calling goroutine and exits with its status after cleanup; cleanup failures are printed to stderr but do not change the status. On SIGINT or SIGTERM, shutdown starts even if m.Run is stuck, and the process exits with 130 or 143 after cleanup. After the first signal the default signal behavior is restored, so a second signal terminates the process immediately.

Pools may be constructed before TestMain as long as they have created no Docker resources. Invalid options or a repeated TestMain or Wrap exit with status 1 before any test runs.

Containers and networks are labeled with an expiry derived from -test.timeout: once it has passed, go test has killed the process. At shutdown, TestMain also removes expired resources that earlier runs left behind on the daemons it used, for example after a kill or a power loss. With -test.timeout=0, -test.bench, or -test.fuzz resources get no expiry and are never removed by other runs.

Use Wrap to compose with other TestMain helpers or to keep control of the exit status.

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.
	// It does not remove intermediate images or builder cache.
	ForceRemove bool

	// Version specifies the builder to use. "1" for classic, "2" for BuildKit.
	// Defaults to the daemon's configured default if empty.
	Version string
}

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. Built images and builder cache are not automatically removed.

type ClosableNetwork

type ClosableNetwork interface {
	Network
	Close(ctx context.Context) error
	CloseT(t TestingTB)
}

ClosableNetwork extends Network with explicit lifecycle management. Returned by CreateNetwork; the caller is responsible for calling Close.

type ClosablePool

type ClosablePool interface {
	Pool
	Close(ctx context.Context) error
	CloseT(t TestingTB)
}

ClosablePool extends Pool with explicit lifecycle management. Returned by NewPool; the caller is responsible for calling Close.

func NewPool

func NewPool(ctx context.Context, endpoint string, opts ...PoolOption) (ClosablePool, error)

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.

The default maxWait is 60 seconds. This can be customized with WithMaxWait.

Example:

ctx := context.Background()
pool, err := dockertest.NewPool(ctx, "")
if err != nil {
	panic(err)
}
defer pool.Close(ctx)

type ClosableResource

type ClosableResource interface {
	Resource
	Close(ctx context.Context) error
	CloseT(t TestingTB)
	Cleanup(t TestingTB)
}

ClosableResource extends Resource with explicit lifecycle management. Returned by Run and BuildAndRun; the caller is responsible for calling Close.

func Get

func Get(reuseID string) (ClosableResource, bool)

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() []ClosableResource

GetAll returns a slice of all resources in the global registry. The order of resources in the returned slice is not guaranteed.

The registry only contains reusable containers that are currently referenced; it is not an inventory of everything dockertest created. Use TestMain for process-wide cleanup.

func NewResource

NewResource creates a Resource for testing purposes. This is intended for unit tests that need a Resource without a Docker container.

type ExecResult

type ExecResult struct {
	StdOut   string
	StdErr   string
	ExitCode int
}

ExecResult holds the output of a command executed inside a container.

type Network

type Network interface {
	ID() string
	Inspect() mobynetwork.Inspect
}

Network provides access to a Docker network. Returned by CreateNetworkT; does not expose Close or CloseT.

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 interface {
	Run(ctx context.Context, repository string, opts ...RunOption) (ClosableResource, error)
	RunT(t TestingTB, repository string, opts ...RunOption) Resource
	BuildAndRun(ctx context.Context, name string, buildOpts *BuildOptions, runOpts ...RunOption) (ClosableResource, error)
	BuildAndRunT(t TestingTB, name string, buildOpts *BuildOptions, runOpts ...RunOption) Resource
	CreateNetwork(ctx context.Context, name string, opts *NetworkCreateOptions) (ClosableNetwork, error)
	CreateNetworkT(t TestingTB, name string, opts *NetworkCreateOptions) Network
	Retry(ctx context.Context, timeout time.Duration, fn func() error) error
	Client() client.DockerClient
}

Pool is the interface for managing Docker resources in tests. Returned by NewPoolT; does not expose Close or CloseT.

func NewPoolT

func NewPoolT(t TestingTB, endpoint string, opts ...PoolOption) Pool

NewPoolT creates a new pool using t.Context() and registers cleanup with t.Cleanup(). The returned Pool does not expose Close or CloseT; the pool is automatically cleaned up when the test finishes.

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 WithCleanupTimeout added in v4.0.1

func WithCleanupTimeout(timeout time.Duration) PoolOption

WithCleanupTimeout sets the context deadline for removing the pool's resources, both in Close and in automatic cleanup registered with t.Cleanup. An earlier deadline of the caller's context is kept. The default is 60 seconds; NewPool rejects a timeout that is not positive.

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 Close().

type Resource

type Resource interface {
	ID() string
	Container() container.InspectResponse
	GetPort(portID string) string
	GetBoundIP(portID string) string
	GetHostPort(portID string) string
	Logs(ctx context.Context) (stdout, stderr string, err error)
	FollowLogs(ctx context.Context, stdout, stderr io.Writer) error
	Exec(ctx context.Context, cmd []string) (ExecResult, error)
	ConnectToNetwork(ctx context.Context, net Network) error
	DisconnectFromNetwork(ctx context.Context, net Network) error
	GetIPInNetwork(net Network) string
}

Resource provides access to a Docker container. Returned by *T variants; does not expose Close, CloseT, or Cleanup.

type RunFunc added in v4.0.1

type RunFunc func() int

RunFunc runs tests and returns their exit code. It satisfies goleak.TestingM.

func Wrap added in v4.0.1

func Wrap(ctx context.Context, run func() int, opts ...TestMainOption) RunFunc

Wrap returns run wrapped in the cleanup of TestMain, for a TestMain that composes with other helpers or keeps control of its exit status:

func TestMain(m *testing.M) {
	goleak.VerifyTestMain(dockertest.Wrap(context.Background(), m.Run))
}

The returned Run installs the cleanup, calls run, shuts down as TestMain does, and returns the status of run. Invalid options, a repeated TestMain or Wrap, or resources created earlier are printed to stderr and return 1 without calling run. Cleanup failures are printed but do not change the status. Before Run returns, signal handling has stopped and the Docker clients pools created are closed, so leak checks after it see no dockertest goroutines. Signals and expiry labels behave as under TestMain.

func (RunFunc) Run added in v4.0.1

func (f RunFunc) Run() int

Run calls f.

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 WithCmd

func WithCmd(cmd []string) RunOption

WithCmd sets the container command, overriding the image's default CMD.

func WithContainerConfig

func WithContainerConfig(modifier func(*container.Config)) RunOption

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

func WithEntrypoint(entrypoint []string) RunOption

WithEntrypoint sets the container entrypoint, overriding the image's default ENTRYPOINT.

func WithEnv

func WithEnv(env []string) RunOption

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

func WithHostname(hostname string) RunOption

WithHostname sets the container's hostname.

func WithLabels

func WithLabels(labels map[string]string) RunOption

WithLabels sets labels on the container. Labels are useful for marking test containers or adding metadata.

func WithMounts

func WithMounts(binds []string) RunOption

WithMounts sets bind mounts for the container. Each string should be in "host:container" or "host:container:mode" format.

func WithName

func WithName(name string) RunOption

WithName sets the container name.

func WithPortBindings

func WithPortBindings(bindings network.PortMap) RunOption

WithPortBindings sets explicit port bindings for the container. Use network.PortMap to specify the bindings.

func WithReuseID

func WithReuseID(id string) RunOption

WithReuseID sets a custom reuse ID for container reuse. By default, containers are reused based on "repository:tag".

func WithTag

func WithTag(tag string) RunOption

WithTag sets the image tag. Default is "latest".

func WithUser

func WithUser(user string) RunOption

WithUser sets the user that will run commands inside the container. Supports both "user" and "user:group" formats.

func WithWorkingDir

func WithWorkingDir(dir string) RunOption

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 TestMainOption added in v4.0.1

type TestMainOption func(*mainOptions)

TestMainOption configures TestMain and Wrap.

func WithShutdownTimeout added in v4.0.1

func WithShutdownTimeout(d time.Duration) TestMainOption

WithShutdownTimeout sets the deadline of the whole shutdown, including the teardown set with WithTeardown. Shutdown ends shortly after it even if a teardown or client ignores its context. Defaults to 60 seconds; negative values are rejected.

func WithTeardown added in v4.0.1

func WithTeardown(fn func(context.Context) error) TestMainOption

WithTeardown sets a package teardown that runs once, before Docker resources are removed, under the shutdown deadline. Its error is reported but does not change the exit status.

It is not needed for pools, containers, and networks created through dockertest: shutdown removes them and closes the Docker clients pools created. Use it only for state dockertest does not own.

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.

Directories

Path Synopsis
internal
client
Package client provides Docker client abstraction for testability.
Package client provides Docker client abstraction for testability.

Jump to

Keyboard shortcuts

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