dockertest: github.com/oov/dockertest Index | Examples | Files

package dockertest

import "github.com/oov/dockertest"

Code:

c, err := dockertest.New(dockertest.Config{
    Image: "andyshinn/dnsmasq", // or "andyshinn/dnsmasq:latest"
    Name:  "dockertest-dnsmasq",
    Args: []string{
        "--user=root",
        "--address=/the-answer-to-life-the-universe-and-everything/42.42.42.42",
    },
    PortMapping: map[string]string{
        "53/udp": "auto",
        "53/tcp": "auto",
    },
})
if err != nil {
    panic(err)
}
defer c.Close()

// wait until the container has started listening
if err = c.Wait(nil); err != nil {
    panic(err)
}

var m dns.Msg
m.SetQuestion("the-answer-to-life-the-universe-and-everything.", dns.TypeA)

in, _, err := (&dns.Client{}).Exchange(&m, c.Mapped["53/udp"].String())
if err != nil {
    panic(err)
}
fmt.Println("UDP", in.Answer[0].(*dns.A).A)

in, _, err = (&dns.Client{Net: "tcp"}).Exchange(&m, c.Mapped["53/tcp"].String())
if err != nil {
    panic(err)
}
fmt.Println("TCP", in.Answer[0].(*dns.A).A)

Output:

UDP 42.42.42.42
TCP 42.42.42.42

Code:

c, err := dockertest.New(dockertest.Config{
    Image: "mongo", // or "mongo:latest"
    Name:  "dockertest-mongo",
    PortMapping: map[string]string{
        "27017/tcp": "auto",
    },
    Args: []string{"--storageEngine", "wiredTiger"},
})
if err != nil {
    panic(err)
}
defer c.Close()

// wait until the container has started listening
if err = c.Wait(nil); err != nil {
    panic(err)
}

session, err := mgo.Dial(c.Mapped["27017/tcp"].String())
if err != nil {
    panic(err)
}
defer session.Close()

type Data struct {
    S string
}
col := session.DB("test").C("data")
if err = col.Insert(&Data{S: "the answer to life the universe&everything"}); err != nil {
    panic(err)
}
var r Data
if err = col.Find(nil).One(&r); err != nil {
    panic(err)
}
fmt.Println(len(r.S))

Output:

42

Code:

const (
    User     = "dockertest"
    Password = "mypassword"
    DBName   = "dockertestdb"
)
c, err := dockertest.New(dockertest.Config{
    Image: "mysql", // or "mysql:latest"
    Name:  "dockertest-mysql",
    PortMapping: map[string]string{
        "3306/tcp": "auto",
    },
    Env: map[string]string{
        "MYSQL_ROOT_PASSWORD": Password,
        "MYSQL_DATABASE":      DBName,
        "MYSQL_USER":          User,
        "MYSQL_PASSWORD":      Password,
    },
})
if err != nil {
    panic(err)
}
defer c.Close()

// wait until the container has started listening
if err = c.Wait(nil); err != nil {
    panic(err)
}

dsn := fmt.Sprintf("%s:%s@tcp(%s)/%s?charset=utf8mb4",
    User, Password, c.Mapped["3306/tcp"], DBName)
db, err := sql.Open("mysql", dsn)
if err != nil {
    panic(err)
}
defer db.Close()

var r int
if err = db.QueryRow("SELECT LENGTH('the answer to life the universe&everything')").Scan(&r); err != nil {
    panic(err)
}
fmt.Println(r)

Output:

42

Code:

const (
    User     = "dockertestdb"
    Password = "mypassword"
    DBName   = User
)
c, err := dockertest.New(dockertest.Config{
    Image: "postgres", // or "postgres:latest"
    Name:  "dockertest-postgres",
    PortMapping: map[string]string{
        "5432/tcp": "auto",
    },
    Env: map[string]string{
        "POSTGRES_USER":     User,
        "POSTGRES_PASSWORD": Password,
    },
})
if err != nil {
    panic(err)
}
defer c.Close()

// wait until the container has started listening
if err = c.Wait(nil); err != nil {
    panic(err)
}

dsn := fmt.Sprintf("postgres://%s:%s@%s/%s?sslmode=disable",
    User, Password, c.Mapped["5432/tcp"], DBName)
db, err := sql.Open("postgres", dsn)
if err != nil {
    panic(err)
}
defer db.Close()

ping:
if err = db.Ping(); err != nil {
    // Sometimes fails with this error, so we need ignore and retry later.
    if err.Error() == "pq: the database system is starting up" {
        time.Sleep(50 * time.Millisecond)
        goto ping
    }
    panic(err)
}

var r int
if err = db.QueryRow("SELECT LENGTH('the answer to life the universe&everything')").Scan(&r); err != nil {
    panic(err)
}
fmt.Println(r)

Output:

42

Code:

c, err := dockertest.New(dockertest.Config{
    Image: "redis", // or "redis:latest"
    Name:  "dockertest-redis",
    PortMapping: map[string]string{
        "6379/tcp": "auto",
    },
})
if err != nil {
    panic(err)
}
defer c.Close()

// wait until the container has started listening
if err = c.Wait(nil); err != nil {
    panic(err)
}

r := redis.NewClient(&redis.Options{
    Addr: c.Mapped["6379/tcp"].String(),
})
pong, err := r.Ping().Result()
if err != nil {
    panic(err)
}
fmt.Println(pong)

Output:

PONG

Index

Examples

Package Files

docker.go nsparse.go

Variables

var ErrTimeout = fmt.Errorf("dockertest: timeout")

ErrTimeout represents timeout error.

func SuggestMappingHost Uses

func SuggestMappingHost() string

type Config Uses

type Config struct {
    Image      string            // "image[:version]" such as "postgres:latest".
    Name       string            // used for to reuse existing container.
    Args       []string          // Additional parameters for the container.
    DockerArgs []string          // Additional parameters for the docker.
    Env        map[string]string // Env["ENV_NAME"] = "VALUE"

    // PortMapping["port/proto"] = "host:port"
    // You can use also "auto" in value.
    PortMapping map[string]string

    // If this is set to true, Close stops the container instead of removes.
    // But this behavior is applied to the created (= not reused) and named container only.
    StopOnClose bool
}

type Container Uses

type Container struct {
    ID          string
    Mapped      map[string]Mapped
    WaitTimeout time.Duration // it is set to 3 minutes as the default by New.
    // contains filtered or unexported fields
}

Container represents Docker container.

func New Uses

func New(conf Config) (*Container, error)

New runs new Docker container.

func (*Container) Close Uses

func (c *Container) Close() error

Close kills and removes the container. However if you are reusing existing container, it is not removed.

func (*Container) Reused Uses

func (c *Container) Reused() bool

Reused reports whenever the container was existed one.

func (*Container) RunArgs Uses

func (c *Container) RunArgs() []string

RunArgs returns parameters that was used for "docker run".

func (*Container) Wait Uses

func (c *Container) Wait(port []string) error

Wait waits until the container has started listening. If wait for all ports that passed at New, can pass nil to the port. When Wait has timed out, Wait returns ErrTimeout.

Internally, Wait reads "/proc/net/(tcp|udp)6?" that exists inside the container.

type Mapped Uses

type Mapped struct {
    Host       string
    DockerHost string
    Port       string
}

func (Mapped) DockerHostAndPort Uses

func (m Mapped) DockerHostAndPort() string

func (Mapped) HostAndPort Uses

func (m Mapped) HostAndPort() string

func (Mapped) String Uses

func (m Mapped) String() string

Package dockertest imports 9 packages (graph). Updated 2016-08-03. Refresh now. Tools for package owners. This is an inactive package (no imports and no commits in at least two years).