Created
October 27, 2018 11:21
-
-
Save charithe/00bfbacbb2e99de90ae8dee9ed68bc39 to your computer and use it in GitHub Desktop.
Using Dockertest to launch Redis
This file contains bidirectional Unicode text that may be interpreted or compiled differently than what appears below. To review, open the file in an editor that reveals hidden Unicode characters.
Learn more about bidirectional Unicode characters
import ( | |
"net" | |
"testing" | |
"github.com/go-redis/redis" | |
"github.com/ory/dockertest" | |
) | |
func TestRedisStore(t *testing.T) { | |
addr, destroyFunc := startRedis(t) | |
defer destroyFunc() | |
// start our Redis store implementation using the address of the Redis container | |
rs := NewRedisStore(addr) | |
// test suite | |
t.Run("get_and_set", func(t *testing.T) { | |
// test GET and SET operations | |
}) | |
t.Run("get_non_existent", func(t *testing.T) { | |
// test GET on non-existent key | |
}) | |
// other tests using the Redis store | |
} | |
func startRedis(t *testing.T) (string, func()) { | |
t.Helper() | |
pool, err := dockertest.NewPool("") | |
if err != nil { | |
t.Fatalf("Failed to start Dockertest: %+v", err) | |
} | |
resource, err := pool.Run("redis", "5-alpine", nil) | |
if err != nil { | |
t.Fatalf("Failed to start redis: %+v", err) | |
} | |
// determine the port the container is listening on | |
addr := net.JoinHostPort("localhost", resource.GetPort("6379/tcp")) | |
// wait for the container to be ready | |
err = pool.Retry(func() error { | |
var e error | |
client := redis.NewClient(&redis.Options{Addr: addr}) | |
defer client.Close() | |
_, e = client.Ping().Result() | |
return e | |
}) | |
if err != nil { | |
t.Fatalf("Failed to ping Redis: %+v", err) | |
} | |
destroyFunc := func() { | |
pool.Purge(resource) | |
} | |
return addr, destroyFunc | |
} |
Sign up for free
to join this conversation on GitHub.
Already have an account?
Sign in to comment