testcontainers

package module
v0.3.0 Latest Latest
Warning

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

Go to latest
Published: Jun 7, 2022 License: MIT Imports: 9 Imported by: 0

README

Testcontainers-Go Booster

GitHub Releases Build Status codecov Go Report Card GoDevDoc Donate

Boost testcontainers/testcontainers-go with some jet fuel! 🚀

Prerequisites

  • Go >= 1.16

Install

go get github.com/nhatthm/testcontainers-go-extra

Callbacks

After successfully starting a container, you may want to do some extra operations to make it ready for your purposes. Then you could use the callbacks.

For example:

package example

import (
	"context"
	"time"

	"github.com/nhatthm/testcontainers-go-extra"
	"github.com/nhatthm/testcontainers-go-extra/wait"
)

func startPostgres(dbName, dbUser, dbPassword string) error {
	_, err := testcontainers.StartGenericContainer(context.Background(), testcontainers.ContainerRequest{
		Name:         "postgres",
		Image:        "postgres:12-alpine",
		ExposedPorts: []string{":5432"},
		Env: map[string]string{
			"LC_ALL":            "C.UTF-8",
			"POSTGRES_DB":       dbName,
			"POSTGRES_USER":     dbUser,
			"POSTGRES_PASSWORD": dbPassword,
		},
		WaitingFor: wait.ForHealthCheckCmd("pg_isready").
			WithRetries(3).
			WithStartPeriod(30 * time.Second).
			WithTestTimeout(5 * time.Second).
			WithTestInterval(10 * time.Second),
	}, testcontainers.WithCallback(func(ctx context.Context, c testcontainers.Container, r testcontainers.ContainerRequest) error {
		// Do your stuff here, for example, migration.

		return nil
	}))

	return err
}
Populating Host and Ports Envs

testcontainers.PopulateHostPortEnv is a callback that set the environment variables for the exposed ports.

For example:

package example

import (
	"context"
	"time"

	"github.com/nhatthm/testcontainers-go-extra"
	"github.com/nhatthm/testcontainers-go-extra/wait"
)

func startPostgres(dbName, dbUser, dbPassword string) error {
	_, err := testcontainers.StartGenericContainer(context.Background(), testcontainers.ContainerRequest{
		Name:         "postgres",
		Image:        "postgres:12-alpine",
		ExposedPorts: []string{":5432"},
		Env: map[string]string{
			"LC_ALL":            "C.UTF-8",
			"POSTGRES_DB":       dbName,
			"POSTGRES_USER":     dbUser,
			"POSTGRES_PASSWORD": dbPassword,
		},
		WaitingFor: wait.ForHealthCheckCmd("pg_isready").
			WithRetries(3).
			WithStartPeriod(30 * time.Second).
			WithTestTimeout(5 * time.Second).
			WithTestInterval(10 * time.Second),
	}, testcontainers.PopulateHostPortEnv)

	return err
}

After calling startPostgres(), there will be 2 variables POSTGRES_5432_HOST and POSTGRES_5432_PORT. The POSTGRES is from the container name in the request, 5432 is the exposed port. The values are

  • POSTGRES_5432_HOST: the hostname of the docker daemon where the container port is exposed.
  • POSTGRES_5432_PORT: the port that mapped to the exposed container port.

Wait Strategies

Health Check

The health check provides the same behavior as docker-compose with the configuration:

  • Start Period: Retry is only counted when time passes the start period. This is helpful for some containers that need time to get ready. The default value is 0.
  • Test Timeout: Timeout for executing the test.
  • Test Internal: If the container is unhealthy, the health check will wait for an amount of time before testing again.
  • Retries: The number of retries to test the container after start period ends.

hccmd

For example:

package example

import (
	"context"
	"time"

	"github.com/nhatthm/testcontainers-go-extra"
	"github.com/nhatthm/testcontainers-go-extra/wait"
)

func startPostgres(dbName, dbUser, dbPassword string) error {
	_, err := testcontainers.StartGenericContainer(context.Background(), testcontainers.ContainerRequest{
		Name:         "postgres",
		Image:        "postgres:12-alpine",
		ExposedPorts: []string{":5432"},
		Env: map[string]string{
			"LC_ALL":            "C.UTF-8",
			"POSTGRES_DB":       dbName,
			"POSTGRES_USER":     dbUser,
			"POSTGRES_PASSWORD": dbPassword,
		},
		WaitingFor: wait.ForHealthCheckCmd("pg_isready").
			WithRetries(3).
			WithStartPeriod(30 * time.Second).
			WithTestTimeout(5 * time.Second).
			WithTestInterval(10 * time.Second),
	})

	return err
}

Donation

If this project help you reduce time to develop, you can give me a cup of coffee :)

Paypal donation

paypal

       or scan this

Documentation

Overview

Package testcontainers provides extra functionalities for testcontainers-go.

Index

Constants

This section is empty.

Variables

View Source
var PopulateHostPortEnv = ContainerCallback(func(ctx context.Context, c Container, r ContainerRequest) error {
	ports, err := c.Ports(ctx)
	if err != nil {
		return fmt.Errorf("could not get container %q ports: %w", r.Name, err)
	}

	if len(ports) == 0 {
		return nil
	}

	ip, err := c.Host(ctx)
	if err != nil {
		return fmt.Errorf("could not get container %q ip: %w", r.Name, err)
	}

	for p, bindings := range ports {
		for _, b := range bindings {
			if err := setEnvVar(r.Name, p, "HOST", ip); err != nil {
				return err
			}

			if err := setEnvVar(r.Name, p, "PORT", b.HostPort); err != nil {
				return err
			}
		}
	}

	return nil
})

PopulateHostPortEnv sets the hostname and public port for each exposed port.

Functions

func StopGenericContainers

func StopGenericContainers(ctx context.Context, containers ...Container) error

StopGenericContainers stops multiple containers at once.

Types

type Container

type Container = testcontainers.Container

Container is an alias of testcontainers.Container to avoid extra import.

func StartGenericContainer

func StartGenericContainer(ctx context.Context, request ContainerRequest, opts ...GenericContainerOption) (Container, error)

StartGenericContainer starts a new generic container.

func StartGenericContainers

func StartGenericContainers(ctx context.Context, requests ...StartGenericContainerRequest) (containers []Container, _ error)

StartGenericContainers starts multiple generic containers at once.

type ContainerCallback

type ContainerCallback func(ctx context.Context, c Container, r ContainerRequest) error

ContainerCallback is called after a container is successfully created and started.

type ContainerRequest

type ContainerRequest = testcontainers.ContainerRequest

ContainerRequest is an alias of testcontainers.ContainerRequest to avoid extra import.

type ContainerStatus

type ContainerStatus string

ContainerStatus is status of a container.

const (
	ContainerStatusCreated    ContainerStatus = "created"
	ContainerStatusRunning    ContainerStatus = "running"
	ContainerStatusPaused     ContainerStatus = "paused"
	ContainerStatusRestarting ContainerStatus = "restarting"
	ContainerStatusRemoving   ContainerStatus = "removing"
	ContainerStatusExited     ContainerStatus = "exited"
	ContainerStatusDead       ContainerStatus = "dead"
)

Container statuses.

func (ContainerStatus) Equal

func (s ContainerStatus) Equal(target string) bool

Equal checks if two statuses are the same.

type GenericContainerOption

type GenericContainerOption interface {
	// contains filtered or unexported methods
}

GenericContainerOption is option for starting a new generic container.

func WithCallback

WithCallback adds a new callback to run after the container is ready.

func WithImageName

func WithImageName(name string) GenericContainerOption

WithImageName sets the image name.

func WithImageTag

func WithImageTag(tag string) GenericContainerOption

WithImageTag sets the image tag.

func WithNamePrefix

func WithNamePrefix(prefix string) GenericContainerOption

WithNamePrefix sets a prefix for the request name.

func WithNameSuffix

func WithNameSuffix(suffix string) GenericContainerOption

WithNameSuffix sets a suffix for the request name.

func WithProviderType

func WithProviderType(providerType testcontainers.ProviderType) GenericContainerOption

WithProviderType sets the provider type.

type StartGenericContainerRequest

type StartGenericContainerRequest struct {
	Request ContainerRequest
	Options []GenericContainerOption
}

StartGenericContainerRequest is request for starting a new generic container.

Directories

Path Synopsis
Package mock provides functionalities for mocking testcontainers-go.
Package mock provides functionalities for mocking testcontainers-go.
wait
Package wait provides functionalities for mocking testcontainers-go/wait.
Package wait provides functionalities for mocking testcontainers-go/wait.
Package wait provides strategies for checking if a container is ready.
Package wait provides strategies for checking if a container is ready.

Jump to

Keyboard shortcuts

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