|
1 | 1 | import { PostgreSqlContainer, StartedPostgreSqlContainer } from "@testcontainers/postgresql"; |
2 | | -import { RedisContainer } from "@testcontainers/redis"; |
| 2 | +import { RedisContainer, StartedRedisContainer } from "@testcontainers/redis"; |
| 3 | +import Redis from "ioredis"; |
3 | 4 | import path from "path"; |
4 | 5 | import { GenericContainer, StartedNetwork, Wait } from "testcontainers"; |
5 | 6 | import { x } from "tinyexec"; |
@@ -40,24 +41,59 @@ export async function createPostgresContainer(network: StartedNetwork) { |
40 | 41 | return { url: container.getConnectionUri(), container, network }; |
41 | 42 | } |
42 | 43 |
|
43 | | -export async function createRedisContainer({ port }: { port?: number }) { |
44 | | - const container = await new RedisContainer() |
45 | | - .withExposedPorts(port ?? 6379) |
46 | | - .withStartupTimeout(120_000) // 2 minutes |
| 44 | +export async function createRedisContainer({ |
| 45 | + port, |
| 46 | + network, |
| 47 | +}: { |
| 48 | + port?: number; |
| 49 | + network?: StartedNetwork; |
| 50 | +}) { |
| 51 | + let container = new RedisContainer().withExposedPorts(port ?? 6379).withStartupTimeout(120_000); // 2 minutes |
| 52 | + |
| 53 | + if (network) { |
| 54 | + container = container.withNetwork(network).withNetworkAliases("redis"); |
| 55 | + } |
| 56 | + |
| 57 | + const startedContainer = await container |
47 | 58 | .withHealthCheck({ |
48 | 59 | test: ["CMD", "redis-cli", "ping"], |
49 | 60 | interval: 1000, |
50 | 61 | timeout: 3000, |
51 | 62 | retries: 5, |
52 | 63 | }) |
53 | | - .withWaitStrategy(Wait.forHealthCheck()) |
| 64 | + .withWaitStrategy( |
| 65 | + Wait.forAll([Wait.forHealthCheck(), Wait.forLogMessage("Ready to accept connections")]) |
| 66 | + ) |
54 | 67 | .start(); |
55 | 68 |
|
| 69 | + // Add a verification step |
| 70 | + await verifyRedisConnection(startedContainer); |
| 71 | + |
56 | 72 | return { |
57 | | - container, |
| 73 | + container: startedContainer, |
58 | 74 | }; |
59 | 75 | } |
60 | 76 |
|
| 77 | +async function verifyRedisConnection(container: StartedRedisContainer) { |
| 78 | + const redis = new Redis({ |
| 79 | + host: container.getHost(), |
| 80 | + port: container.getPort(), |
| 81 | + password: container.getPassword(), |
| 82 | + maxRetriesPerRequest: 3, |
| 83 | + connectTimeout: 10000, |
| 84 | + retryStrategy(times) { |
| 85 | + const delay = Math.min(times * 50, 2000); |
| 86 | + return delay; |
| 87 | + }, |
| 88 | + }); |
| 89 | + |
| 90 | + try { |
| 91 | + await redis.ping(); |
| 92 | + } finally { |
| 93 | + await redis.quit(); |
| 94 | + } |
| 95 | +} |
| 96 | + |
61 | 97 | export async function createElectricContainer( |
62 | 98 | postgresContainer: StartedPostgreSqlContainer, |
63 | 99 | network: StartedNetwork |
|
0 commit comments