forked from testcontainers/testcontainers-go
/
redis_test.go
72 lines (60 loc) · 1.56 KB
/
redis_test.go
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
23
24
25
26
27
28
29
30
31
32
33
34
35
36
37
38
39
40
41
42
43
44
45
46
47
48
49
50
51
52
53
54
55
56
57
58
59
60
61
62
63
64
65
66
67
68
69
70
71
72
package redis
import (
"context"
"fmt"
"testing"
"time"
"github.com/go-redis/redis/v8"
"github.com/google/uuid"
"github.com/stretchr/testify/require"
)
func TestIntegrationSetGet(t *testing.T) {
if testing.Short() {
t.Skip("Skipping integration test")
}
ctx := context.Background()
redisContainer, err := setupRedis(ctx)
if err != nil {
t.Fatal(err)
}
t.Cleanup(func() {
if err := redisContainer.Terminate(ctx); err != nil {
t.Fatalf("failed to terminate container: %s", err)
}
})
// You will likely want to wrap your Redis package of choice in an
// interface to aid in unit testing and limit lock-in throughtout your
// codebase but that's out of scope for this example
options, err := redis.ParseURL(redisContainer.URI)
if err != nil {
t.Fatal(err)
}
client := redis.NewClient(options)
defer flushRedis(ctx, *client)
t.Log("pinging redis")
pong, err := client.Ping(ctx).Result()
require.NoError(t, err)
t.Log("received response from redis")
if pong != "PONG" {
t.Fatalf("received unexpected response from redis: %s", pong)
}
// Set data
key := fmt.Sprintf("{user.%s}.favoritefood", uuid.NewString())
value := "Cabbage Biscuits"
ttl, _ := time.ParseDuration("2h")
err = client.Set(ctx, key, value, ttl).Err()
if err != nil {
t.Fatal(err)
}
// Get data
savedValue, err := client.Get(ctx, key).Result()
if err != nil {
t.Fatal(err)
}
if savedValue != value {
t.Fatalf("Expected value %s. Got %s.", savedValue, value)
}
}
func flushRedis(ctx context.Context, client redis.Client) error {
return client.FlushAll(ctx).Err()
}