All Projects → ory → Dockertest

ory / Dockertest

Licence: apache-2.0
Write better integration tests! Dockertest helps you boot up ephermal docker images for your Go tests with minimal work.

Programming Languages

go
31211 projects - #10 most used programming language

Projects that are alternatives of or similar to Dockertest

Automation Arsenal
Curated list of popular Java and Kotlin frameworks, libraries and tools related to software testing, quality assurance and adjacent processes automation.
Stars: ✭ 105 (-95.34%)
Mutual labels:  automation, unit-testing, integration-testing
Dredd
Language-agnostic HTTP API Testing Tool
Stars: ✭ 3,770 (+67.26%)
Mutual labels:  unit-testing, integration-testing, tests
Zunit
A powerful testing framework for ZSH projects
Stars: ✭ 140 (-93.79%)
Mutual labels:  ci, unit-testing
Xrautomatedtests
XRAutomatedTests is where you can find functional, graphics, performance, and other types of automated tests for your XR Unity development.
Stars: ✭ 77 (-96.58%)
Mutual labels:  automation, tests
Unit Threaded
Advanced unit test framework for D
Stars: ✭ 100 (-95.56%)
Mutual labels:  unit-testing, integration-testing
Aspnetcore Tests Sample
A project to help demonstrate how to do unit, integration and acceptance tests with an web api project using ASP.NET Core and Angular 7 front end.
Stars: ✭ 40 (-98.23%)
Mutual labels:  unit-testing, integration-testing
Kube Score
Kubernetes object analysis with recommendations for improved reliability and security
Stars: ✭ 1,128 (-49.96%)
Mutual labels:  automation, ci
Testing Workshop
A workshop for learning how to test JavaScript applications
Stars: ✭ 1,276 (-43.39%)
Mutual labels:  unit-testing, integration-testing
Cmockery
A lightweight library to simplify and generalize the process of writing unit tests for C applications.
Stars: ✭ 697 (-69.08%)
Mutual labels:  unit-testing, tests
Moderncppci
This is an example of doing a Modern C++ project with CI
Stars: ✭ 109 (-95.16%)
Mutual labels:  ci, unit-testing
Pipelines
Build pipelines for automation, deployment, testing...
Stars: ✭ 105 (-95.34%)
Mutual labels:  automation, ci
Movieapp
🎬 MovieApp is a Flutter application built to demonstrate the use of modern development tools with best practices implementation like Modularization, BLoC, Dependency Injection, Dynamic Theme, Cache, Shimmer, Testing, Flavor, CI/CD, etc.
Stars: ✭ 117 (-94.81%)
Mutual labels:  unit-testing, integration-testing
Capture Stream
Capture stream output.
Stars: ✭ 10 (-99.56%)
Mutual labels:  unit-testing, tests
Quixote
CSS unit and integration testing
Stars: ✭ 788 (-65.04%)
Mutual labels:  unit-testing, integration-testing
Redux Saga Test Plan
Test Redux Saga with an easy plan.
Stars: ✭ 1,135 (-49.65%)
Mutual labels:  unit-testing, integration-testing
Webhook
webhook is a lightweight incoming webhook server to run shell commands
Stars: ✭ 7,201 (+219.48%)
Mutual labels:  automation, ci
Cavy
An integration test framework for React Native.
Stars: ✭ 1,239 (-45.03%)
Mutual labels:  automation, integration-testing
Php Censor
PHP Censor is an open source self-hosted continuous integration server for PHP projects.
Stars: ✭ 619 (-72.54%)
Mutual labels:  ci, unit-testing
Shipjs
Take control of what is going to be your next release.
Stars: ✭ 668 (-70.36%)
Mutual labels:  automation, ci
Dcind
Docker image with Docker Compose. Useful as a base image for integration tests in Concourse CI.
Stars: ✭ 128 (-94.32%)
Mutual labels:  ci, integration-testing

ORY Dockertest

Build Status Coverage Status

Use Docker to run your Golang integration tests against third party services on Microsoft Windows, Mac OSX and Linux!

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 -u github.com/ory/dockertest/v3

or

dep ensure -add github.com/ory/[email protected]

Using Dockertest

package dockertest_test

import (
	"database/sql"
	"fmt"
	"log"
	"os"
	"testing"

	_ "github.com/go-sql-driver/mysql"
	"github.com/ory/dockertest/v3"
)

var db *sql.DB

func TestMain(m *testing.M) {
	// uses a sensible default on windows (tcp/http) and linux/osx (socket)
	pool, err := dockertest.NewPool("")
	if err != nil {
		log.Fatalf("Could not connect to docker: %s", err)
	}

	// pulls an image, creates a container based on it and runs it
	resource, err := pool.Run("mysql", "5.7", []string{"MYSQL_ROOT_PASSWORD=secret"})
	if err != nil {
		log.Fatalf("Could not start resource: %s", err)
	}

	// exponential backoff-retry, because the application in the container might not be ready to accept connections yet
	if err := pool.Retry(func() error {
		var err error
		db, err = sql.Open("mysql", fmt.Sprintf("root:secret@(localhost:%s)/mysql", resource.GetPort("3306/tcp")))
		if err != nil {
			return err
		}
		return db.Ping()
	}); err != nil {
		log.Fatalf("Could not connect to database: %s", err)
	}

	code := m.Run()
	
	// You can't defer this because os.Exit doesn't care for defer
	if err := pool.Purge(resource); err != nil {
		log.Fatalf("Could not purge resource: %s", err)
	}
	
	os.Exit(code)
}

func TestSomething(t *testing.T) {
	// db.Query()
}

Examples

We provide code examples for well known services in the examples directory, check them out!

Troubleshoot & FAQ

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. You may also set an absolute lifetime on containers:

resource.Expire(60) // Tell docker to hard kill the container in 60 seconds

To let stopped containers removed from file system automatically, use pool.RunWithOptions() instead of pool.Run() with config.AutoRemove set to true, e.g.:

postgres, err := pool.RunWithOptions(&dockertest.RunOptions{
	Repository: "postgres",
	Tag:        "11",
	Env: []string{
		"POSTGRES_USER=test",
		"POSTGRES_PASSWORD=test",
		"listen_addresses = '*'",
	},
}, func(config *docker.HostConfig) {
	// set AutoRemove to true so that stopped container goes away by itself
	config.AutoRemove = true
	config.RestartPolicy = docker.RestartPolicy{
		Name: "no",
	}
})

Running dockertest in Gitlab CI

How to run dockertest on shared gitlab runners?

You should add docker dind service to your job which starts in sibling container. That means database will be available on host docker.
You app should be able to change db host through environment variable.

Here is the simple example of gitlab-ci.yml:

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

Plus in the pool.Retry method that checks for connection readiness, you need to use $YOUR_APP_DB_HOST instead of localhost.

How to run dockertest on group(custom) gitlab runners?

Gitlab runner can be run in docker executor mode to save compatibility with shared runners.
Here is the simple register command:

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

You only need to instruct docker dind to start with disabled tls.
Add variable DOCKER_TLS_CERTDIR: "" to gitlab-ci.yml above. It will tell docker daemon to start on 2375 port over http.

How to run dockertest with remote Docker

Use-case: locally installed docker CLI (client), docker daemon somewhere remotely, environment properly set (ie: DOCKER_HOST, etc..). For example, remote docker can be provisioned by docker-machine.

Currently, dockertest in case of resource.GetHostPort() will return docker host binding address (commonly - localhost) instead of remote docker host. Universal solution is:

func getHostPort(resource *dockertest.Resource, id string) string {
	dockerURL := os.Getenv("DOCKER_HOST")
	if dockerURL == "" {
		return resource.GetHostPort(id)
	}
	u, err := url.Parse(dockerURL)
	if err != nil {
		panic(err)
	}
	return u.Hostname() + ":" + resource.GetPort(id)
}

It will return the remote docker host concatenated with the allocated port in case DOCKER_HOST env is defined. Otherwise, it will fall back to the embedded behavior.

Note that the project description data, including the texts, logos, images, and/or trademarks, for each open source project belongs to its rightful owner. If you wish to add or remove any projects, please contact us at [email protected].