Categorygithub.com/miko-code/dockertest
modulepackage
2.1.1+incompatible
Repository: https://github.com/miko-code/dockertest.git
Documentation: pkg.go.dev

# README

ory.am/dockertest

Build Status Coverage Status

Use Docker to run your Go language integration tests against third party services on Microsoft Windows, Mac OSX and Linux! Dockertest uses docker-machine (aka Docker Toolbox) to spin up images on Windows and Mac OSX as well. Dockertest is based on docker.go from camlistore.

This fork detects automatically, if Docker Toolbox is installed. If it is, Docker integration on Windows and Mac OSX can be used without any additional work. To avoid port collisions when using docker-machine, Dockertest chooses a random port to bind the requested image.

Dockertest ships with support for these backends:

  • PostgreSQL
  • MySQL
  • MongoDB
  • NSQ
  • Redis
  • Elastic Search
  • RethinkDB
  • RabbitMQ
  • Mockserver

Table of Contents

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 of the 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 unit 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.

Installing and using Dockertest

Using Dockertest is straightforward and simple. Check the releases tab for available releases.

To install dockertest, run

go get gopkg.in/ory-am/dockertest.vX

where X is your desired version. For example:

go get gopkg.in/ory-am/dockertest.v2

Note:
When using the Docker Toolbox (Windows / OSX), make sure that the VM is started by running docker-machine start default.

Start a container

package main

import (
	"gopkg.in/ory-am/dockertest.v2"
	"gopkg.in/mgo.v2"
	"time"
)

func main() {
	var db *mgo.Session
	c, err := dockertest.ConnectToMongoDB(15, time.Millisecond*500, func(url string) bool {
	    // This callback function checks if the image's process is responsive.
	    // Sometimes, docker images are booted but the process (in this case MongoDB) is still doing maintenance
	    // before being fully responsive which might cause issues like "TCP Connection reset by peer".	
		var err error
		db, err = mgo.Dial(url)
		if err != nil {
			return false
		}
		
		// Sometimes, dialing the database is not enough because the port is already open but the process is not responsive.
		// Most database conenctors implement a ping function which can be used to test if the process is responsive.
		// Alternatively, you could execute a query to see if an error occurs or not.
		return db.Ping() == nil
	})
	
	if err != nil {
	    log.Fatalf("Could not connect to database: %s", err)
	}
	
	// Close db connection and kill the container when we leave this function body.
    defer db.Close()
	defer c.KillRemove()
	
	// The image is now responsive.
}

You can start PostgreSQL and MySQL in a similar fashion.

It is also possible to start a custom container (in this example, a RabbitMQ container):

	c, ip, port, err := dockertest.SetupCustomContainer("rabbitmq", 5672, 10*time.Second)
	if err != nil {
		log.Fatalf("Could not setup container: %s", err
	}
	defer c.KillRemove()

	err = dockertest.ConnectToCustomContainer(fmt.Sprintf("%v:%v", ip, port), 15, time.Millisecond*500, func(url string) bool {
		amqp, err := amqp.Dial(fmt.Sprintf("amqp://%v", url))
		if err != nil {
			return false
		}
		defer amqp.Close()
		return true
	})

	...

Write awesome tests

It is a good idea to start up the container only once when running tests.


import (
	"fmt"
	"testing"
    "log"
	"os"

	"database/sql"
	_ "github.com/lib/pq"
	"gopkg.in/ory-am/dockertest.v2"
)

var db *sql.DB

func TestMain(m *testing.M) {
	if c, err := dockertest.ConnectToPostgreSQL(15, time.Second, func(url string) bool {
	    // Check if postgres is responsive...
		var err error
		db, err = sql.Open("postgres", url)
		if err != nil {
			return false
		}
		return db.Ping() == nil
	}); err != nil {
		log.Fatalf("Could not connect to database: %s", err)
	}
	
	// Execute tasks like setting up schemata.
	
	// Run tests
	result := m.Run()
	
	// Close database connection.
	db.Close()
	
	// Clean up image.
	c.KillRemove()
	
	// Exit tests.
	os.Exit(result)
}

func TestFunction(t *testing.T) {
    // db.Exec(...
}

Setting up Travis-CI

You can run the Docker integration on Travis easily:

# Sudo is required for docker
sudo: required

# Enable docker
services:
  - docker

# In Travis, we need to bind to 127.0.0.1 in order to get a working connection. This environment variable
# tells dockertest to do that.
env:
  - DOCKERTEST_BIND_LOCALHOST=true

Troubleshoot & FAQ

I need to use a specific container version for XYZ

You can specify a container version by setting environment variables or globals. For more information, check vars.go.

My build is broken!

With v2, we removed all Open* methods to reduce duplicate code, unnecessary dependencies and make maintenance easier. If you relied on these, run go get gopkg.in/ory-am/dockertest.v1 and replace import "github.com/ory-am/dockertest" with import "gopkg.in/ory-am/dockertest.v1".

Out of disk space

Try cleaning up the images with docker-cleanup-volumes.

Removing old containers

Sometimes container clean up fails. Check out this stackoverflow question on how to fix this.

Customized database

I am using postgres (or mysql) driver, how do I use customized database instead of default one? You can alleviate this helper function to do that, see testcase or example below:


func TestMain(m *testing.M) {
	if c, err := dockertest.ConnectToPostgreSQL(15, time.Second, func(url string) bool {
        customizedDB := "cherry" // here I am connecting cherry database
        newURL, err := SetUpPostgreDatabase(customizedDB, url)

        // or use SetUpMysqlDatabase for mysql driver

        if err != nil {
                log.Fatal(err)
        }
        db, err := sql.Open("postgres", newURL)
        if err != nil {
            return false
        }
        return db.Ping() == nil
    }); err != nil {
        log.Fatal(err)
    }

Thanks to our sponsors: Ory GmbH & Imarum GmbH

# Functions

ConnectToCustomContainer attempts to connect to a custom container until successful or the maximum number of tries is reached.
ConnectToElasticSearch starts an ElasticSearch image and passes the database url to the connector callback function.
ConnectToMockserver starts a Mockserver image and passes the mock and proxy urls to the connector callback functions.
ConnectToMongoDB starts a MongoDB image and passes the database url to the connector callback.
ConnectToMySQL starts a MySQL image and passes the database url to the connector callback function.
ConnectToNSQd starts a NSQ image with `/nsqd` running and passes the IP, HTTP port, and TCP port to the connector callback function.
ConnectToNSQLookupd starts a NSQ image with `/nsqlookupd` running and passes the IP, HTTP port, and TCP port to the connector callback function.
ConnectToPostgreSQL starts a PostgreSQL image and passes the database url to the connector callback.
ConnectToRabbitMQ starts a RabbitMQ image and passes the amqp url to the connector callback.
ConnectToRedis starts a Redis image and passes the database url to the connector callback function.
ConnectToRethinkDB starts a RethinkDB image and passes the database url to the connector callback.
GenerateContainerID generated a random container id.
HaveImage reports if docker have image 'name'.
IP returns the IP address of the container.
KillContainer runs docker kill on a container.
Pull retrieves the docker image with 'docker pull'.
RandomPort returns a random non-priviledged port.
SetupContainer sets up a container, using the start function to run the given image.
SetupCustomContainer sets up a real an instance of the given image for testing purposes, using a Docker container.
SetupElasticSearchContainer sets up a real ElasticSearch instance for testing purposes using a Docker container.
SetupMockserverContainer sets up a real Mockserver instance for testing purposes using a Docker container.
SetupMongoContainer sets up a real MongoDB instance for testing purposes, using a Docker container.
SetupMultiportContainer sets up a container, using the start function to run the given image.
SetupMySQLContainer sets up a real MySQL instance for testing purposes, using a Docker container.
SetUpMySQLDatabase connects mysql container with given $connectURL and also creates a new database named $databaseName A modified url used to connect the created database will be returned.
SetupNSQdContainer sets up a real NSQ instance for testing purposes using a Docker container and executing `/nsqd`.
SetupNSQLookupdContainer sets up a real NSQ instance for testing purposes using a Docker container and executing `/nsqlookupd`.
SetUpPostgreDatabase connects postgre container with given $connectURL and also creates a new database named $databaseName A modified url used to connect the created database will be returned.
SetupPostgreSQLContainer sets up a real PostgreSQL instance for testing purposes, using a Docker container.
SetupRabbitMQContainer sets up a real RabbitMQ instance for testing purposes, using a Docker container.
SetupRedisContainer sets up a real Redis instance for testing purposes using a Docker container.
SetupRethinkDBContainer sets up a real RethinkDB instance for testing purposes, using a Docker container.

# Variables

BindDockerToLocalhost if set, forces docker to bind the image to localhost.
ContainerPrefix will be prepended to all containers started by dockertest to make identification of these "test images" hassle-free.
Debug if set, prevents any container from being removed.
DockerMachineAvailable if true, uses docker-machine to run docker commands (for running tests on Windows and Mac OS).
DockerMachineName is the machine's name.
ElasticSearchImageName is the ElasticSearch image name on dockerhub.
MockserverImageName name is the Mockserver image name on dockerhub.
MongoDBImageName is the MongoDB image name on dockerhub.
MySQLImageName is the MySQL image name on dockerhub.
MySQLPassword must be passed as password when connecting to mysql.
MySQLUsername must be passed as username when connecting to mysql.
NSQImageName is the NSQ image name on dockerhub.
PostgresImageName is the PostgreSQL image name on dockerhub.
PostgresPassword must be passed as password when connecting to postgres.
PostgresUsername must be passed as username when connecting to postgres.
RabbitMQImage name is the RabbitMQ image name on dockerhub.
RedisImageName is the Redis image name on dockerhub.
RethinkDBImageName is the RethinkDB image name on dockerhub.

# Type aliases

ContainerID represents a container and offers methods like Kill or IP.