1package dockertest
2
3import (
4	"errors"
5	"fmt"
6	"log"
7	"time"
8)
9
10// SetupRedisContainer sets up a real Redis instance for testing purposes
11// using a Docker container. It returns the container ID and its IP address,
12// or makes the test fail on error.
13func SetupRedisContainer() (c ContainerID, ip string, port int, err error) {
14	port = RandomPort()
15	forward := fmt.Sprintf("%d:%d", port, 6379)
16	if BindDockerToLocalhost != "" {
17		forward = "127.0.0.1:" + forward
18	}
19	c, ip, err = SetupContainer(RedisImageName, port, 15*time.Second, func() (string, error) {
20		return run("--name", GenerateContainerID(), "-d", "-P", "-p", forward, RedisImageName)
21	})
22	return
23}
24
25// ConnectToRedis starts a Redis image and passes the database url to the connector callback function.
26// The url will match the ip:port pattern (e.g. 123.123.123.123:6379)
27func ConnectToRedis(tries int, delay time.Duration, connector func(url string) bool) (c ContainerID, err error) {
28	c, ip, port, err := SetupRedisContainer()
29	if err != nil {
30		return c, fmt.Errorf("Could not set up Redis container: %v", err)
31	}
32
33	for try := 0; try <= tries; try++ {
34		time.Sleep(delay)
35		url := fmt.Sprintf("%s:%d", ip, port)
36		if connector(url) {
37			return c, nil
38		}
39		log.Printf("Try %d failed. Retrying.", try)
40	}
41	return c, errors.New("Could not set up Redis container.")
42}
43