Documentation ¶
Overview ¶
Package gnomock contains a framework to set up temporary docker containers for integration and end-to-end testing of other applications. It handles pulling images, starting containers, waiting for them to become available, setting up their initial state and cleaning up in the end.
Its power is in a variety of Presets, each implementing a specific database, service or other tools. Each preset provides ways of setting up its initial state as easily as possible: SQL schema creation, test data upload into S3, sending test events to Splunk, etc.
All containers created using Gnomock have a self-destruct mechanism that kicks-in right after the test execution completes.
To debug cases where containers don't behave as expected, there are options like `WithDebugMode()` or `WithLogWriter()`.
For the list of presets, please refer to https://pkg.go.dev/github.com/orlangure/gnomock/preset.
Each preset can then be used in the following way:
p := redis.Preset() // replace "redis" with whatever you need container, err := gnomock.Start(p) addr := container.DefaultAddress() // e.g localhost:54321
Index ¶
- Constants
- Variables
- func Stop(cs ...*Container) error
- type Container
- type HealthcheckFunc
- type InitFunc
- type NamedPorts
- type Option
- func WithCommand(cmd string, args ...string) Option
- func WithContainerName(name string) Option
- func WithContainerReuse() Option
- func WithContext(ctx context.Context) Option
- func WithCustomNamedPorts(namedPorts NamedPorts) Option
- func WithDebugMode() Option
- func WithDisableAutoCleanup() Option
- func WithEntrypoint(entrypoint string, args ...string) Option
- func WithEnv(env string) Option
- func WithExtraHosts(hosts []string) Option
- func WithHealthCheck(f HealthcheckFunc) Option
- func WithHealthCheckInterval(t time.Duration) Option
- func WithHostMounts(src, dst string) Option
- func WithInit(f InitFunc) Option
- func WithLogWriter(w io.Writer) Option
- func WithOptions(options *Options) Option
- func WithPrivileged() Option
- func WithRegistryAuth(auth string) Option
- func WithTimeout(t time.Duration) Option
- func WithUseLocalImagesFirst() Option
- type Options
- type Parallel
- type Port
- type Preset
Constants ¶
const DefaultPort = "default"
DefaultPort should be used with simple containers that expose only one TCP port. Use DefaultTCP function when creating a container, and use DefaultPort when calling Address().
Variables ¶
var ErrEnvClient = fmt.Errorf("can't connect to docker host")
ErrEnvClient means that Gnomock can't connect to docker daemon in the testing environment. See https://docs.docker.com/compose/reference/overview/ for information on required configuration.
var ErrPortNotFound = errors.New("port not found")
ErrPortNotFound means that a port with the requested name was not found in the created container. Make sure that the name used in Find method matches the name used in in NamedPorts. For default values, use DefaultTCP and DefaultPort.
Functions ¶
Types ¶
type Container ¶
type Container struct { // A unique identifier of this container. The format of this ID may change // in the future. ID string `json:"id,omitempty"` // Host name of bound ports // // Default: localhost Host string `json:"host,omitempty"` // A collections of ports exposed by this container. Each port has an alias // and an actual port number as exposed on the host Ports NamedPorts `json:"ports,omitempty"` // contains filtered or unexported fields }
Container represents a docker container created for testing. Host and Ports fields should be used to configure the connection to this container. ID matches the original docker container ID.
func Start ¶
Start creates a container using the provided Preset. The Preset provides its own Options to configure Gnomock container. Usually this is enough, but it is still possible to extend/override Preset options with new values. For example, wait timeout defined in the Preset, if at all, might be not enough for this particular usage, so it can't be changed during this call.
All provided Options are applied. First, Preset options are applied. Then, custom Options. If both Preset and custom Options change the same configuration, custom Options are used.
It is recommended, but not required, to call `gnomock.Stop()` when the tests complete to cleanup the containers.
func StartCustom ¶ added in v0.3.0
func StartCustom(image string, ports NamedPorts, opts ...Option) (*Container, error)
StartCustom creates a new container using provided image and binds random ports on the host to the provided ports inside the container. Image may include tag, which is set to "latest" by default. Optional configuration is available through Option functions. The returned container must be stopped when no longer needed using its Stop() method.
func (*Container) Address ¶
Address is a convenience function that returns host:port that can be used to connect to this container. If a container was created with DefaultTCP call, use DefaultPort as the name. Otherwise, use the name of one of the ports used during setup.
func (*Container) DefaultAddress ¶ added in v0.3.0
DefaultAddress return Address() with DefaultPort.
func (*Container) DefaultPort ¶ added in v0.3.0
DefaultPort returns Port() with DefaultPort.
type HealthcheckFunc ¶
HealthcheckFunc defines a function to be used to determine container health. It receives a host and a port, and returns an error if the container is not ready, or nil when the container can be used. One example of HealthcheckFunc would be an attempt to establish the same connection to the container that the application under test uses.
type InitFunc ¶
InitFunc defines a function to be called on a ready to use container to set up its initial state before running the tests. For example, InitFunc can take care of creating a SQL table and inserting test data into it.
type NamedPorts ¶ added in v0.1.0
NamedPorts is a collection of ports exposed by a container, where every exposed port is given a name. Some examples of names are "web" or "api" for a container that exposes two separate ports: one for web access and another for API calls.
func DefaultTCP ¶ added in v0.1.0
func DefaultTCP(port int) NamedPorts
DefaultTCP is a utility function to use with simple containers exposing a single TCP port. Use it to create default named port for the provided port number. Pass DefaultPort to Address() method to get the address of the default port.
func (NamedPorts) Find ¶ added in v0.1.0
func (p NamedPorts) Find(proto string, portNum int) (string, error)
Find returns the name of a port with the provided protocol and number. Use this method to find out the name of an exposed ports, when port number and protocol are known.
func (NamedPorts) Get ¶ added in v0.1.0
func (p NamedPorts) Get(name string) Port
Get returns a port with the provided name. An empty value is returned if there are no ports with the given name.
type Option ¶
type Option func(*Options)
Option is an optional Gnomock configuration. Functions implementing this signature may be combined to configure Gnomock containers for different use cases.
func WithCommand ¶ added in v0.11.0
WithCommand sets the command and its arguments to execute when container first runs. This command replaces the command defined in docker image.
func WithContainerName ¶ added in v0.9.2
WithContainerName allows to give a specific name to a new container. If a container with the same name already exists, it is killed.
func WithContainerReuse ¶ added in v0.23.0
func WithContainerReuse() Option
WithContainerReuse disables Gnomock default behaviour of automatic container cleanup and also disables the automatic replacement at startup of an existing container with the same name and image. Effectively this makes Gnomock reuse a container from a previous Gnomock execution.
func WithContext ¶
WithContext sets the provided context to be used for setting up a Gnomock container. Canceling this context will cause Start() to abort.
func WithCustomNamedPorts ¶ added in v0.20.0
func WithCustomNamedPorts(namedPorts NamedPorts) Option
WithCustomNamedPorts allows to define custom ports for a container. This option should be used to override the ports defined by presets.
func WithDebugMode ¶ added in v0.9.0
func WithDebugMode() Option
WithDebugMode allows Gnomock to output internal messages for debug purposes. Containers created in debug mode will not be automatically removed on failure to setup their initial state. Containers still might be removed if they are shut down from the inside. Use WithLogWriter to see what happens inside.
func WithDisableAutoCleanup ¶ added in v0.11.0
func WithDisableAutoCleanup() Option
WithDisableAutoCleanup disables auto-removal of this container when the tests complete. Automatic cleanup is a safety net for tests that for some reason fail to run `gnomock.Stop()` in the end, for example due to an unexpected `os.Exit()` somewhere.
func WithEntrypoint ¶ added in v0.24.0
WithEntrypoint overwrites the entrypoint, and its arguments, defined in the original docker image.
func WithEnv ¶ added in v0.1.1
WithEnv adds environment variable to the container. For example, `AWS_ACCESS_KEY_ID=FOOBARBAZ`.
func WithExtraHosts ¶ added in v0.25.0
WithExtraHosts allows to provide custom entries to the hosts file of the container. It is similar to the `--add-host` flag of docker.
func WithHealthCheck ¶
func WithHealthCheck(f HealthcheckFunc) Option
WithHealthCheck allows to define a rule to consider a Gnomock container ready to use. For example, it can attempt to connect to this container, and return an error on any failure, or nil on success. This function is called repeatedly until the timeout is reached, or until a nil error is returned.
func WithHealthCheckInterval ¶
WithHealthCheckInterval defines an interval between two consecutive health check calls. This is a constant interval.
func WithHostMounts ¶ added in v0.11.0
WithHostMounts allows to bind host path (`src`) inside the container under `dst` path.
func WithInit ¶
WithInit lets the provided InitFunc to be called when a Gnomock container is created, but before Start() returns. Use this function to run arbitrary code on the new container before using it. It can be useful to bring the container to a certain state (e.g create SQL schema).
func WithLogWriter ¶ added in v0.2.1
WithLogWriter sets the target where to write container logs. This can be useful for debugging.
func WithOptions ¶ added in v0.4.0
WithOptions allows to provide an existing set of Options instead of using optional configuration.
This way has its own limitations. For example, context or initialization functions cannot be set in this way.
func WithPrivileged ¶ added in v0.10.0
func WithPrivileged() Option
WithPrivileged starts a container in privileged mode (like `docker run --privileged`). This option should not be used unless you really need it. One use case for this option would be to run a Preset that has some kind of docker-in-docker functionality.
func WithRegistryAuth ¶ added in v0.15.0
WithRegistryAuth allows to access private docker images. The credentials should be passes as a Base64 encoded string, where the content is a JSON string with two fields: username and password.
For Docker Hub, if 2FA authentication is enabled, an access token should be used instead of a password.
For example: eyJ1c2VybmFtZSI6ImZvbyIsInBhc3N3b3JkIjoiYmFyIn0K which stands for {"username":"foo","password":"bar"}.
func WithTimeout ¶ added in v0.9.0
WithTimeout sets the amount of time to wait for a created container to become ready to use. All startup steps must complete before they time out: start, wait until healthy, init.
func WithUseLocalImagesFirst ¶ added in v0.18.0
func WithUseLocalImagesFirst() Option
WithUseLocalImagesFirst if possible to avoid hitting the Docker Hub pull rate limit.
type Options ¶ added in v0.4.0
type Options struct { // Timeout is an amount of time to wait before considering Start operation // as failed. Timeout time.Duration `json:"timeout"` // Env is a list of environment variable to inject into the container. Each // entry is in format ENV_VAR_NAME=value Env []string `json:"env"` // Debug flag allows Gnomock to be verbose about steps it takes Debug bool `json:"debug"` // Privileged starts a container in privileged mode. Privileged bool `json:"privileged"` // ContainerName allows to use a specific name for a new container. In case // a container with the same name already exists, Gnomock kills it. ContainerName string `json:"container_name"` // Cmd is an optional command with its arguments to execute on container // startup. This command replaces the default one set on docker image // level. Cmd []string `json:"cmd"` // Entrypoint is the binary that will always be executed when the container // is run. The difference between this and Cmd, is that Cmd will be given as an // argument to Entrypoint. Entrypoint []string `json:"entrypoint"` // HostMounts allows to mount local paths into the container. HostMounts map[string]string `json:"host_mounts"` // DisableAutoCleanup prevents the container from being automatically // stopped and removed after the tests are complete. By default, Gnomock // will try to stop containers created by it right after the tests exit. DisableAutoCleanup bool `json:"disable_cleanup"` // WithUseLocalImagesFirst allows to use existing local images if possible // instead of always pulling the images. UseLocalImagesFirst bool `json:"use_local_images_first"` // CustomNamedPorts allows to override the ports set by the presets. This // option is useful for cases when the presets need to be created with // custom port definitions. This is an advanced feature and should be used // with care. // // Note that when using this option, you should provide custom named ports // with names matching the original ports returned by the used preset. // // When calling StartCustom directly from Go, it is possible to provide the // ports directly to the function. CustomNamedPorts NamedPorts `json:"custom_named_ports"` // Base64 encoded JSON string with docker access credentials. JSON string // should include two fields: username and password. For Docker Hub, if 2FA // authentication is enabled, an access token should be used instead of a // password. // // For example: // eyJ1c2VybmFtZSI6ImZvbyIsInBhc3N3b3JkIjoiYmFyIn0K // which stands for // {"username":"foo","password":"bar"} Auth string `json:"auth"` // ExtraHosts allows to add entries to the hosts file of the container. // It is similar to the `--add-host` flag of docker. ExtraHosts []string `json:"extraHosts"` // Reuse prevents the container from being automatically stopped and enables // its re-use in posterior executions. Reuse bool `json:"reuse"` // contains filtered or unexported fields }
Options includes Gnomock startup configuration. Functional options (WithSomething) should be used instead of directly initializing objects of this type whenever possible.
type Parallel ¶ added in v0.3.0
type Parallel struct {
// contains filtered or unexported fields
}
Parallel is a builder object that configures parallel preset execution.
func InParallel ¶ added in v0.3.0
func InParallel() *Parallel
InParallel begins parallel preset execution setup. Use Start to add more presets with their configuration to parallel execution, and Go() in the end to kick-off everything.
func (*Parallel) Go ¶ added in v0.3.0
Go kicks-off parallel preset execution. Returned containers are in the same order as they were added with Start. An error is returned if any of the containers failed to start and become available. Even if Go() returns an errors, there still might be containers created in the process, and it is callers responsibility to Stop them.
type Port ¶ added in v0.1.0
type Port struct { // Protocol of the exposed port (TCP/UDP). Protocol string `json:"protocol"` // Port number of the exposed port. Port int `json:"port"` // HostPort is an optional value to set mapped host port explicitly. HostPort int `json:"host_port"` }
Port is a combination of port number and protocol that are exposed in a container.
type Preset ¶
type Preset interface { // Image returns a canonical docker image used to setup this Preset. Image() string // Ports returns a group of ports exposed by this Preset, where every port // is given a unique name. For example, if a container exposes API endpoint // on port 8080, and web interface on port 80, there should be two named // ports: "web" and "api". Ports() NamedPorts // Options returns a list of Option functions that allow to setup this // Preset implementation. Options() []Option }
Preset is a type that includes ready to use Gnomock configuration. Such configuration includes image and ports as well as options specific to this implementation. For example, well known services like Redis or Postgres may have Gnomock implementations, providing healthcheck functions and basic initialization options.
Source Files ¶
Directories ¶
Path | Synopsis |
---|---|
cmd
|
|
cleaner
Module
|
|
internal
|
|
cleaner
Package cleaner exposes an API to communicate with Gnomock Cleaner, a separate process that waits for incoming connections and terminates running containers when these connections are closed.
|
Package cleaner exposes an API to communicate with Gnomock Cleaner, a separate process that waits for incoming connections and terminates running containers when these connections are closed. |
errors
Package errors exposes errors types used by gnomockd endpoints.
|
Package errors exposes errors types used by gnomockd endpoints. |
gnomockd
Package gnomockd is an HTTP wrapper around Gnomock
|
Package gnomockd is an HTTP wrapper around Gnomock |
health
Package health includes common health check functions to use in other packages.
|
Package health includes common health check functions to use in other packages. |
israce
Package israce reports if the Go race detector is enabled.
|
Package israce reports if the Go race detector is enabled. |
registry
Package registry provides access to existing presets.
|
Package registry provides access to existing presets. |
testutil
Package testutil includes utilities used in test code of other packages.
|
Package testutil includes utilities used in test code of other packages. |
preset
|
|
azurite
Package azurite provides a Gnomock Preset for azurite project It allows to easily setup local Blobstorage for testing
|
Package azurite provides a Gnomock Preset for azurite project It allows to easily setup local Blobstorage for testing |
cassandra
Package cassandra includes Cassandra implementation of Gnomock Preset interface.
|
Package cassandra includes Cassandra implementation of Gnomock Preset interface. |
cockroachdb
Package cockroachdb includes CockroachDB implementation of Gnomock Preset interface.
|
Package cockroachdb includes CockroachDB implementation of Gnomock Preset interface. |
elastic
Package elastic provides a Gnomock Preset for Elasticsearch.
|
Package elastic provides a Gnomock Preset for Elasticsearch. |
influxdb
Package influxdb includes InfluxDB implementation of Gnomock Preset interface.
|
Package influxdb includes InfluxDB implementation of Gnomock Preset interface. |
k3s
Package k3s provides a Gnomock Preset for lightweight kubernetes (k3s).
|
Package k3s provides a Gnomock Preset for lightweight kubernetes (k3s). |
kafka
Package kafka provides a Gnomock Preset for Kafka.
|
Package kafka provides a Gnomock Preset for Kafka. |
localstack
Package localstack provides a Gnomock Preset for localstack project (https://github.com/localstack/localstack).
|
Package localstack provides a Gnomock Preset for localstack project (https://github.com/localstack/localstack). |
mariadb
Package mariadb provides a Gnomock Preset for MariaDB database
|
Package mariadb provides a Gnomock Preset for MariaDB database |
memcached
Package memcached includes Memcached implementation of Gnomock Preset interface.
|
Package memcached includes Memcached implementation of Gnomock Preset interface. |
mongo
Package mongo includes mongo implementation of Gnomock Preset interface.
|
Package mongo includes mongo implementation of Gnomock Preset interface. |
mssql
Package mssql provides a Gnomock Preset for Microsoft SQL Server database
|
Package mssql provides a Gnomock Preset for Microsoft SQL Server database |
mysql
Package mysql provides a Gnomock Preset for MySQL database.
|
Package mysql provides a Gnomock Preset for MySQL database. |
postgres
Package postgres provides a Gnomock Preset for PostgreSQL database.
|
Package postgres provides a Gnomock Preset for PostgreSQL database. |
rabbitmq
Package rabbitmq provides a Gnomock Preset for RabbitMQ.
|
Package rabbitmq provides a Gnomock Preset for RabbitMQ. |
redis
Package redis includes Redis implementation of Gnomock Preset interface.
|
Package redis includes Redis implementation of Gnomock Preset interface. |
splunk
Package splunk includes Splunk Enterprise implementation of Gnomock Preset interface.
|
Package splunk includes Splunk Enterprise implementation of Gnomock Preset interface. |
vault
Package vault includes vault implementation of Gnomock Preset interface.
|
Package vault includes vault implementation of Gnomock Preset interface. |