@@ -7,25 +7,63 @@ import (
7
7
"time"
8
8
9
9
"github.com/redis/go-redis/v9"
10
+ "github.com/testcontainers/testcontainers-go"
11
+ "github.com/testcontainers/testcontainers-go/wait"
10
12
)
11
13
12
- func setupRedisClient (t * testing.T ) * redis.Client {
14
+ func setupRedisContainer (t * testing.T ) (testcontainers.Container , * redis.Client ) {
15
+ ctx := context .Background ()
16
+
17
+ // Container request
18
+ req := testcontainers.ContainerRequest {
19
+ Image : "redis:7.2" ,
20
+ ExposedPorts : []string {"6379/tcp" },
21
+ WaitingFor : wait .ForLog ("Ready to accept connections" ),
22
+ }
23
+
24
+ // Start container
25
+ redisC , err := testcontainers .GenericContainer (ctx , testcontainers.GenericContainerRequest {
26
+ ContainerRequest : req ,
27
+ Started : true ,
28
+ })
29
+ if err != nil {
30
+ t .Fatalf ("failed to start container: %s" , err )
31
+ }
32
+
33
+ // Get mapped port
34
+ mappedPort , err := redisC .MappedPort (ctx , "6379" )
35
+ if err != nil {
36
+ t .Fatalf ("failed to get container external port: %s" , err )
37
+ }
38
+
39
+ // Get host
40
+ host , err := redisC .Host (ctx )
41
+ if err != nil {
42
+ t .Fatalf ("failed to get container host: %s" , err )
43
+ }
44
+
45
+ // Create Redis client
13
46
client := redis .NewClient (& redis.Options {
14
- Addr : "localhost:6379" ,
47
+ Addr : fmt . Sprintf ( "%s:%s" , host , mappedPort . Port ()) ,
15
48
})
16
49
17
50
// Test connection
18
- ctx := context .Background ()
19
51
if err := client .Ping (ctx ).Err (); err != nil {
20
52
t .Fatalf ("failed to connect to Redis: %s" , err )
21
53
}
22
54
23
- return client
55
+ return redisC , client
24
56
}
25
57
26
58
func TestRedisStorage (t * testing.T ) {
27
- client := setupRedisClient (t )
28
- defer client .Close ()
59
+ t .Parallel ()
60
+ redisC , client := setupRedisContainer (t )
61
+ defer func () {
62
+ client .Close ()
63
+ if err := redisC .Terminate (context .Background ()); err != nil {
64
+ t .Fatalf ("failed to terminate container: %s" , err )
65
+ }
66
+ }()
29
67
30
68
// Clean up any existing data
31
69
ctx := context .Background ()
@@ -86,8 +124,14 @@ func TestRedisStorage(t *testing.T) {
86
124
}
87
125
88
126
func TestRedisStorageExpiration (t * testing.T ) {
89
- client := setupRedisClient (t )
90
- defer client .Close ()
127
+ t .Parallel ()
128
+ redisC , client := setupRedisContainer (t )
129
+ defer func () {
130
+ client .Close ()
131
+ if err := redisC .Terminate (context .Background ()); err != nil {
132
+ t .Fatalf ("failed to terminate container: %s" , err )
133
+ }
134
+ }()
91
135
92
136
// Clean up any existing data
93
137
ctx := context .Background ()
0 commit comments