testcontainers

package module
v0.2.2 Latest Latest
Warning

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

Go to latest
Published: Oct 20, 2022 License: MIT Imports: 12 Imported by: 11

README

testcontainers, pre-configured

GitHub GoDoc Test Coverage Release

A collection of pre-configured testcontainers for your golang integration tests.

Available containers (feel free to contribute):

Usage

Redis
// examples/redis/redis.go

package main

import (
	"context"
	"log"

	"github.com/go-redis/redis"
	tc "github.com/romnn/testcontainers"
	tcredis "github.com/romnn/testcontainers/redis"
)

func run() {
	container, err := tcredis.Start(context.Background(), tcredis.Options{
		ImageTag: "7.0.5", // you could use latest here
	})
	if err != nil {
		log.Fatalf("failed to start container: %v", err)
	}
	defer container.Terminate(context.Background())

	// start logger
	logger, err := tc.StartLogger(context.Background(), container.Container)
	if err != nil {
		log.Printf("failed to start logger: %v", err)
	} else {
		defer logger.Stop()
		go logger.LogToStdout()
	}

	// connect to redis
	db := redis.NewClient(&redis.Options{
		Addr:     container.ConnectionURI(),
		Password: container.Password,
		DB:       1,
	})

	// set some data
	db.HSet("my-hash-key", "key", "Hello World!")

	// get the data back
	value, err := db.HGet("my-hash-key", "key").Result()
	if err != nil {
		log.Fatalf("failed to get value: %v", err)
	}
	if value != "Hello World!" {
		log.Fatalf(`received %q instead of "Hello World!"`, value)
	}

	log.Printf("received %q from redis", value)
}

func main() {
	run()
}

MongoDB
// examples/mongo/mongo.go

package main

import (
	"context"
	"log"
	"time"

	tcmongo "github.com/romnn/testcontainers/mongo"
	"go.mongodb.org/mongo-driver/bson"
	"go.mongodb.org/mongo-driver/mongo"
	"go.mongodb.org/mongo-driver/mongo/options"
)

func run() {
	container, err := tcmongo.Start(context.Background(), tcmongo.Options{
		ImageTag: "6.0.2", // you could use latest here
	})
	if err != nil {
		log.Fatalf("failed to start container: %v", err)
	}
	defer container.Terminate(context.Background())

	// connect to the container
	uri := container.ConnectionURI()
	client, err := mongo.NewClient(options.Client().ApplyURI(uri))
	if err != nil {
		log.Fatalf("failed to create client: %v", err)
	}
	ctx, cancel := context.WithTimeout(context.Background(), 10*time.Second)
	defer cancel()
	client.Connect(ctx)

	// count documents in collection
	collection := client.Database("testdatabase").Collection("my-collection")
	opts := options.Count().SetMaxTime(2 * time.Second)
	count, err := collection.CountDocuments(
		context.TODO(),
		bson.D{},
		opts,
	)
	if err != nil {
		log.Fatalf("failed to count docs in collection %q: %v", collection.Name(), err)
	}
	log.Printf("collection %q contains %d documents", collection.Name(), count)
}

func main() {
	run()
}

For more examples, see examples/.

Development

Before you get started, make sure you have installed the following tools:

$ python3 -m pip install pre-commit bump2version invoke
$ go install golang.org/x/tools/cmd/goimports@latest
$ go install golang.org/x/lint/golint@latest
$ go install github.com/fzipp/gocyclo/cmd/gocyclo@latest

Remember: To be able to excecute the tools installed with go install, make sure to include $GOPATH/bin in your $PATH. If echo $GOPATH does not give you a path make sure to run (export GOPATH="$HOME/go" to set it). In order for your changes to persist, do not forget to add these to your shells .bashrc.

With the tools in place, it is strongly advised to install the git commit hooks to make sure checks are passing in CI:

invoke install-hooks

You can check if all checks pass at any time:

invoke pre-commit

Documentation

Index

Constants

This section is empty.

Variables

This section is empty.

Functions

func CreateNetwork

func CreateNetwork(request testcontainers.NetworkRequest, timeoutMin time.Duration) (net testcontainers.Network, err error)

CreateNetwork creates a docker container network

func MergeOptions

func MergeOptions(c interface{}, override interface{})

MergeOptions can merge generic options

func MergeRequest

func MergeRequest(c *testcontainers.ContainerRequest, override *testcontainers.ContainerRequest)

MergeRequest ...

func UniqueID

func UniqueID() string

UniqueID generates a unique uuid

Types

type CmdOutput added in v0.2.2

type CmdOutput struct {
	Stdin  string
	Stdout string
	Stderr string
}

CmdOutput holds decoded output of a command executed in a container

func ExecCmd added in v0.2.2

func ExecCmd(ctx context.Context, container testcontainers.Container, cmd []string) (CmdOutput, error)

ExecCmd executes a command in a container and collects its output

func ReadCmdOutput added in v0.2.2

func ReadCmdOutput(reader io.Reader) (CmdOutput, error)

ReadCmdOutput reads and decodes output of a command executed in a container

type ContainerConfig

type ContainerConfig struct {
}

ContainerConfig ...

type ContainerOptions

type ContainerOptions struct {
	testcontainers.ContainerRequest
	StartupTimeout time.Duration
}

ContainerOptions ...

type LogCollector

type LogCollector struct {
	LogChan chan testcontainers.Log
	// contains filtered or unexported fields
}

LogCollector ...

func StartLogger added in v0.2.2

func StartLogger(ctx context.Context, c testcontainers.Container) (LogCollector, error)

StartLogger ...

func (*LogCollector) Accept

func (logger *LogCollector) Accept(l testcontainers.Log)

Accept ...

func (*LogCollector) LogToStdout added in v0.2.2

func (logger *LogCollector) LogToStdout()

LogToStdout ...

func (*LogCollector) Stop added in v0.2.2

func (logger *LogCollector) Stop()

Stop ...

Directories

Path Synopsis
examples

Jump to

Keyboard shortcuts

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