@omnitron-dev/testing 0.1.1

This diff represents the content of publicly available package versions that have been released to one of the supported registries. The information contained in this diff is provided for informational purposes only and reflects changes between package versions as they appear in their respective public registries.
Files changed (182) hide show
  1. package/LICENSE +21 -0
  2. package/README.md +19 -0
  3. package/dist/async/deferred.d.ts +15 -0
  4. package/dist/async/deferred.js +35 -0
  5. package/dist/async/deferred.js.map +1 -0
  6. package/dist/async/events.d.ts +32 -0
  7. package/dist/async/events.js +176 -0
  8. package/dist/async/events.js.map +1 -0
  9. package/dist/async/index.d.ts +5 -0
  10. package/dist/async/index.js +6 -0
  11. package/dist/async/index.js.map +1 -0
  12. package/dist/async/mock-timer.d.ts +19 -0
  13. package/dist/async/mock-timer.js +87 -0
  14. package/dist/async/mock-timer.js.map +1 -0
  15. package/dist/async/retry.d.ts +8 -0
  16. package/dist/async/retry.js +36 -0
  17. package/dist/async/retry.js.map +1 -0
  18. package/dist/async/wait.d.ts +10 -0
  19. package/dist/async/wait.js +35 -0
  20. package/dist/async/wait.js.map +1 -0
  21. package/dist/docker/database-manager.d.ts +22 -0
  22. package/dist/docker/database-manager.js +97 -0
  23. package/dist/docker/database-manager.js.map +1 -0
  24. package/dist/docker/docker-test-manager.d.ts +44 -0
  25. package/dist/docker/docker-test-manager.js +812 -0
  26. package/dist/docker/docker-test-manager.js.map +1 -0
  27. package/dist/docker/index.d.ts +4 -0
  28. package/dist/docker/index.js +4 -0
  29. package/dist/docker/index.js.map +1 -0
  30. package/dist/docker/redis-manager.d.ts +12 -0
  31. package/dist/docker/redis-manager.js +452 -0
  32. package/dist/docker/redis-manager.js.map +1 -0
  33. package/dist/docker/types.d.ts +103 -0
  34. package/dist/docker/types.js +2 -0
  35. package/dist/docker/types.js.map +1 -0
  36. package/dist/errors.d.ts +15 -0
  37. package/dist/errors.js +28 -0
  38. package/dist/errors.js.map +1 -0
  39. package/dist/helpers/assertions.d.ts +6 -0
  40. package/dist/helpers/assertions.js +37 -0
  41. package/dist/helpers/assertions.js.map +1 -0
  42. package/dist/helpers/console.d.ts +1 -0
  43. package/dist/helpers/console.js +23 -0
  44. package/dist/helpers/console.js.map +1 -0
  45. package/dist/helpers/index.d.ts +3 -0
  46. package/dist/helpers/index.js +4 -0
  47. package/dist/helpers/index.js.map +1 -0
  48. package/dist/helpers/temp-dir.d.ts +2 -0
  49. package/dist/helpers/temp-dir.js +13 -0
  50. package/dist/helpers/temp-dir.js.map +1 -0
  51. package/dist/index.d.ts +18 -0
  52. package/dist/index.js +22 -0
  53. package/dist/index.js.map +1 -0
  54. package/dist/performance/index.d.ts +2 -0
  55. package/dist/performance/index.js +3 -0
  56. package/dist/performance/index.js.map +1 -0
  57. package/dist/performance/memory-detector.d.ts +9 -0
  58. package/dist/performance/memory-detector.js +61 -0
  59. package/dist/performance/memory-detector.js.map +1 -0
  60. package/dist/performance/perf-timer.d.ts +9 -0
  61. package/dist/performance/perf-timer.js +49 -0
  62. package/dist/performance/perf-timer.js.map +1 -0
  63. package/dist/runtime/bun-adapter.d.ts +1 -0
  64. package/dist/runtime/bun-adapter.js +100 -0
  65. package/dist/runtime/bun-adapter.js.map +1 -0
  66. package/dist/runtime/deno-adapter.d.ts +27 -0
  67. package/dist/runtime/deno-adapter.js +221 -0
  68. package/dist/runtime/deno-adapter.js.map +1 -0
  69. package/dist/runtime/node-adapter.d.ts +16 -0
  70. package/dist/runtime/node-adapter.js +30 -0
  71. package/dist/runtime/node-adapter.js.map +1 -0
  72. package/dist/runtime/test-adapter.d.ts +22 -0
  73. package/dist/runtime/test-adapter.js +93 -0
  74. package/dist/runtime/test-adapter.js.map +1 -0
  75. package/dist/titan/container-utils.d.ts +20 -0
  76. package/dist/titan/container-utils.js +78 -0
  77. package/dist/titan/container-utils.js.map +1 -0
  78. package/dist/titan/database/database-testing.module.d.ts +82 -0
  79. package/dist/titan/database/database-testing.module.js +433 -0
  80. package/dist/titan/database/database-testing.module.js.map +1 -0
  81. package/dist/titan/database/index.d.ts +3 -0
  82. package/dist/titan/database/index.js +4 -0
  83. package/dist/titan/database/index.js.map +1 -0
  84. package/dist/titan/database/test-utilities.d.ts +31 -0
  85. package/dist/titan/database/test-utilities.js +146 -0
  86. package/dist/titan/database/test-utilities.js.map +1 -0
  87. package/dist/titan/index.d.ts +14 -0
  88. package/dist/titan/index.js +10 -0
  89. package/dist/titan/index.js.map +1 -0
  90. package/dist/titan/nexus/index.d.ts +3 -0
  91. package/dist/titan/nexus/index.js +4 -0
  92. package/dist/titan/nexus/index.js.map +1 -0
  93. package/dist/titan/nexus/mock-provider.d.ts +41 -0
  94. package/dist/titan/nexus/mock-provider.js +127 -0
  95. package/dist/titan/nexus/mock-provider.js.map +1 -0
  96. package/dist/titan/nexus/test-container.d.ts +120 -0
  97. package/dist/titan/nexus/test-container.js +559 -0
  98. package/dist/titan/nexus/test-container.js.map +1 -0
  99. package/dist/titan/nexus/test-utilities.d.ts +135 -0
  100. package/dist/titan/nexus/test-utilities.js +484 -0
  101. package/dist/titan/nexus/test-utilities.js.map +1 -0
  102. package/dist/titan/pm/index.d.ts +4 -0
  103. package/dist/titan/pm/index.js +4 -0
  104. package/dist/titan/pm/index.js.map +1 -0
  105. package/dist/titan/pm/mock-process-spawner.d.ts +61 -0
  106. package/dist/titan/pm/mock-process-spawner.js +343 -0
  107. package/dist/titan/pm/mock-process-spawner.js.map +1 -0
  108. package/dist/titan/pm/mock-spawner.d.ts +28 -0
  109. package/dist/titan/pm/mock-spawner.js +101 -0
  110. package/dist/titan/pm/mock-spawner.js.map +1 -0
  111. package/dist/titan/pm/test-process-manager.d.ts +49 -0
  112. package/dist/titan/pm/test-process-manager.js +192 -0
  113. package/dist/titan/pm/test-process-manager.js.map +1 -0
  114. package/dist/titan/redis-test-utils.d.ts +33 -0
  115. package/dist/titan/redis-test-utils.js +415 -0
  116. package/dist/titan/redis-test-utils.js.map +1 -0
  117. package/dist/titan/test-application.d.ts +21 -0
  118. package/dist/titan/test-application.js +90 -0
  119. package/dist/titan/test-application.js.map +1 -0
  120. package/dist/titan/test-fixtures.d.ts +97 -0
  121. package/dist/titan/test-fixtures.js +223 -0
  122. package/dist/titan/test-fixtures.js.map +1 -0
  123. package/dist/titan/test-mocks.d.ts +30 -0
  124. package/dist/titan/test-mocks.js +262 -0
  125. package/dist/titan/test-mocks.js.map +1 -0
  126. package/dist/titan/test-module.d.ts +47 -0
  127. package/dist/titan/test-module.js +120 -0
  128. package/dist/titan/test-module.js.map +1 -0
  129. package/package.json +146 -0
  130. package/runtime/bun.d.ts +2 -0
  131. package/runtime/bun.js +5 -0
  132. package/runtime/bun.ts +7 -0
  133. package/runtime/deno.d.ts +2 -0
  134. package/runtime/deno.js +4 -0
  135. package/runtime/vitest.d.ts +2 -0
  136. package/runtime/vitest.js +16 -0
  137. package/runtime/vitest.ts +7 -0
  138. package/src/async/README.md +336 -0
  139. package/src/async/deferred.ts +98 -0
  140. package/src/async/events.ts +386 -0
  141. package/src/async/index.ts +23 -0
  142. package/src/async/mock-timer.ts +220 -0
  143. package/src/async/retry.ts +115 -0
  144. package/src/async/wait.ts +148 -0
  145. package/src/docker/database-manager.ts +242 -0
  146. package/src/docker/docker-test-manager.ts +1198 -0
  147. package/src/docker/index.ts +48 -0
  148. package/src/docker/redis-manager.ts +741 -0
  149. package/src/docker/types.ts +216 -0
  150. package/src/errors.ts +38 -0
  151. package/src/globals.d.ts +24 -0
  152. package/src/helpers/assertions.ts +168 -0
  153. package/src/helpers/console.ts +74 -0
  154. package/src/helpers/index.ts +15 -0
  155. package/src/helpers/temp-dir.ts +50 -0
  156. package/src/index.ts +43 -0
  157. package/src/performance/index.ts +11 -0
  158. package/src/performance/memory-detector.ts +166 -0
  159. package/src/performance/perf-timer.ts +146 -0
  160. package/src/runtime/bun-adapter.ts +127 -0
  161. package/src/runtime/deno-adapter.ts +286 -0
  162. package/src/runtime/node-adapter.ts +40 -0
  163. package/src/runtime/test-adapter.test.ts +98 -0
  164. package/src/runtime/test-adapter.ts +122 -0
  165. package/src/titan/container-utils.ts +128 -0
  166. package/src/titan/database/database-testing.module.ts +851 -0
  167. package/src/titan/database/index.ts +30 -0
  168. package/src/titan/database/test-utilities.ts +340 -0
  169. package/src/titan/index.ts +128 -0
  170. package/src/titan/nexus/index.ts +3 -0
  171. package/src/titan/nexus/mock-provider.ts +189 -0
  172. package/src/titan/nexus/test-container.ts +895 -0
  173. package/src/titan/nexus/test-utilities.ts +797 -0
  174. package/src/titan/pm/index.ts +22 -0
  175. package/src/titan/pm/mock-process-spawner.ts +534 -0
  176. package/src/titan/pm/mock-spawner.ts +162 -0
  177. package/src/titan/pm/test-process-manager.ts +352 -0
  178. package/src/titan/redis-test-utils.ts +567 -0
  179. package/src/titan/test-application.ts +154 -0
  180. package/src/titan/test-fixtures.ts +304 -0
  181. package/src/titan/test-mocks.ts +336 -0
  182. package/src/titan/test-module.ts +233 -0
@@ -0,0 +1,741 @@
1
+ /**
2
+ * Redis Test Manager
3
+ *
4
+ * Provides specialized helpers for creating and managing Redis containers
5
+ * in tests. Supports standalone Redis, Redis Cluster, and Redis Sentinel.
6
+ */
7
+
8
+ import { execFileSync } from 'child_process';
9
+ import { randomBytes } from 'crypto';
10
+ import { DockerTestManager } from './docker-test-manager.js';
11
+ import type {
12
+ DockerContainer,
13
+ RedisContainerOptions,
14
+ RedisClusterOptions,
15
+ RedisClusterContainers,
16
+ RedisSentinelOptions,
17
+ RedisSentinelContainers,
18
+ } from './types.js';
19
+
20
+ /**
21
+ * Redis Test Manager
22
+ *
23
+ * Provides convenient methods for creating Redis containers with various
24
+ * configurations: standalone, cluster, and sentinel.
25
+ *
26
+ * @example
27
+ * ```typescript
28
+ * // Standalone Redis
29
+ * const redis = await RedisTestManager.createRedisContainer();
30
+ *
31
+ * // Redis Cluster
32
+ * const cluster = await RedisTestManager.createRedisCluster({
33
+ * masterCount: 3,
34
+ * replicasPerMaster: 1,
35
+ * });
36
+ *
37
+ * // Redis Sentinel
38
+ * const sentinel = await RedisTestManager.createRedisSentinel({
39
+ * replicaCount: 2,
40
+ * sentinelCount: 3,
41
+ * });
42
+ * ```
43
+ */
44
+ export class RedisTestManager {
45
+ private static _dockerManager: DockerTestManager | null = null;
46
+
47
+ /**
48
+ * Get the Docker manager instance
49
+ * @private
50
+ */
51
+ private static getDockerManager(): DockerTestManager {
52
+ if (!RedisTestManager._dockerManager) {
53
+ RedisTestManager._dockerManager = DockerTestManager.getInstance();
54
+ }
55
+ return RedisTestManager._dockerManager;
56
+ }
57
+
58
+ /**
59
+ * Create a standalone Redis container
60
+ *
61
+ * @param options - Redis configuration options
62
+ * @returns Promise resolving to DockerContainer
63
+ *
64
+ * @example
65
+ * ```typescript
66
+ * const container = await RedisTestManager.createRedisContainer({
67
+ * password: 'mypass',
68
+ * maxMemory: '512mb',
69
+ * });
70
+ *
71
+ * const port = container.ports.get(6379)!;
72
+ * const connStr = `redis://:mypass@localhost:${port}/0`;
73
+ * ```
74
+ */
75
+ static async createRedisContainer(options?: RedisContainerOptions): Promise<DockerContainer> {
76
+ const port = options?.port || 'auto';
77
+ const password = options?.password;
78
+ const _database = options?.database ?? 0;
79
+ const maxMemory = options?.maxMemory || '256mb';
80
+ const requirePass = options?.requirePass ?? Boolean(password);
81
+
82
+ const environment: Record<string, string> = {};
83
+ const command: string[] = ['redis-server'];
84
+
85
+ // Configure Redis settings
86
+ command.push('--maxmemory', maxMemory);
87
+ command.push('--maxmemory-policy', 'allkeys-lru');
88
+ command.push('--save', ''); // Disable RDB snapshots for tests
89
+ command.push('--appendonly', 'no'); // Disable AOF for tests
90
+
91
+ if (requirePass && password) {
92
+ command.push('--requirepass', password);
93
+ }
94
+
95
+ return RedisTestManager.getDockerManager().createContainer({
96
+ name: options?.name,
97
+ image: 'redis:7-alpine',
98
+ ports: { 6379: port },
99
+ environment,
100
+ command: command.join(' '),
101
+ healthcheck: {
102
+ test: password ? ['CMD', 'redis-cli', '-a', password, 'ping'] : ['CMD', 'redis-cli', 'ping'],
103
+ interval: '1s',
104
+ timeout: '3s',
105
+ retries: 20,
106
+ startPeriod: '2s',
107
+ },
108
+ waitFor: {
109
+ healthcheck: true,
110
+ timeout: 30000,
111
+ },
112
+ });
113
+ }
114
+
115
+ /**
116
+ * Create a Redis Cluster (3 masters + 3 replicas by default)
117
+ *
118
+ * @param options - Redis Cluster configuration options
119
+ * @returns Promise resolving to RedisClusterContainers
120
+ *
121
+ * @example
122
+ * ```typescript
123
+ * const cluster = await RedisTestManager.createRedisCluster({
124
+ * masterCount: 3,
125
+ * replicasPerMaster: 1,
126
+ * password: 'mypass',
127
+ * });
128
+ *
129
+ * // Use cluster nodes
130
+ * const nodes = cluster.nodes; // [{ host: '127.0.0.1', port: 12345 }, ...]
131
+ *
132
+ * // Cleanup when done
133
+ * await cluster.cleanup();
134
+ * ```
135
+ */
136
+ static async createRedisCluster(options?: RedisClusterOptions): Promise<RedisClusterContainers> {
137
+ const masterCount = options?.masterCount ?? 3;
138
+ const replicasPerMaster = options?.replicasPerMaster ?? 1;
139
+ const password = options?.password;
140
+ const networkName = options?.network || `redis-cluster-${randomBytes(8).toString('hex')}`;
141
+
142
+ // Create network
143
+ await RedisTestManager.getDockerManager()['ensureNetwork'](networkName);
144
+
145
+ const masters: DockerContainer[] = [];
146
+ const replicas: DockerContainer[] = [];
147
+ const nodes: Array<{ host: string; port: number }> = [];
148
+ const allocatedPorts: number[] = [];
149
+
150
+ // Extract unique ID from network name to ensure container names are unique
151
+ const networkId = networkName.split('-').pop() || randomBytes(4).toString('hex');
152
+
153
+ try {
154
+ // Create master nodes with dynamically allocated ports
155
+ for (let i = 0; i < masterCount; i++) {
156
+ // Use dynamic port allocation instead of fixed basePort to avoid conflicts
157
+ const port = await RedisTestManager.getDockerManager()['findAvailablePort']();
158
+ allocatedPorts.push(port);
159
+ const name = `redis-cluster-${networkId}-master-${i}`;
160
+
161
+ const command = [
162
+ 'redis-server',
163
+ '--cluster-enabled',
164
+ 'yes',
165
+ '--cluster-config-file',
166
+ 'nodes.conf',
167
+ '--cluster-node-timeout',
168
+ '5000',
169
+ '--appendonly',
170
+ 'no',
171
+ '--save',
172
+ '',
173
+ '--port',
174
+ '6379',
175
+ ];
176
+
177
+ if (password) {
178
+ command.push('--requirepass', password);
179
+ command.push('--masterauth', password);
180
+ }
181
+
182
+ const container = await RedisTestManager.getDockerManager().createContainer({
183
+ name,
184
+ image: 'redis:7-alpine',
185
+ ports: { 6379: port },
186
+ networks: [networkName],
187
+ command: command.join(' '),
188
+ healthcheck: {
189
+ test: password ? ['CMD', 'redis-cli', '-a', password, 'ping'] : ['CMD', 'redis-cli', 'ping'],
190
+ interval: '1s',
191
+ timeout: '5s',
192
+ retries: 30,
193
+ startPeriod: '10s',
194
+ },
195
+ waitFor: {
196
+ healthcheck: true,
197
+ timeout: 60000,
198
+ },
199
+ });
200
+
201
+ masters.push(container);
202
+ nodes.push({ host: container.host, port });
203
+ }
204
+
205
+ // Create replica nodes with dynamically allocated ports
206
+ for (let i = 0; i < masterCount * replicasPerMaster; i++) {
207
+ // Use dynamic port allocation
208
+ const port = await RedisTestManager.getDockerManager()['findAvailablePort']();
209
+ allocatedPorts.push(port);
210
+ const name = `redis-cluster-${networkId}-replica-${i}`;
211
+
212
+ const command = [
213
+ 'redis-server',
214
+ '--cluster-enabled',
215
+ 'yes',
216
+ '--cluster-config-file',
217
+ 'nodes.conf',
218
+ '--cluster-node-timeout',
219
+ '5000',
220
+ '--appendonly',
221
+ 'no',
222
+ '--save',
223
+ '',
224
+ '--port',
225
+ '6379',
226
+ ];
227
+
228
+ if (password) {
229
+ command.push('--requirepass', password);
230
+ command.push('--masterauth', password);
231
+ }
232
+
233
+ const container = await RedisTestManager.getDockerManager().createContainer({
234
+ name,
235
+ image: 'redis:7-alpine',
236
+ ports: { 6379: port },
237
+ networks: [networkName],
238
+ command: command.join(' '),
239
+ healthcheck: {
240
+ test: password ? ['CMD', 'redis-cli', '-a', password, 'ping'] : ['CMD', 'redis-cli', 'ping'],
241
+ interval: '1s',
242
+ timeout: '5s',
243
+ retries: 30,
244
+ startPeriod: '10s',
245
+ },
246
+ waitFor: {
247
+ healthcheck: true,
248
+ timeout: 60000,
249
+ },
250
+ });
251
+
252
+ replicas.push(container);
253
+ nodes.push({ host: container.host, port });
254
+ }
255
+
256
+ // Wait for all containers to be fully ready and connected to network
257
+ const preInitDelay = options?.preInitDelay ?? 5000;
258
+ await new Promise((resolve) => setTimeout(resolve, preInitDelay));
259
+
260
+ // Verify all nodes respond to PING before initializing cluster
261
+ const dockerPath = RedisTestManager.getDockerManager()['dockerPath'];
262
+ const allContainers = [...masters, ...replicas];
263
+ for (const container of allContainers) {
264
+ const maxPingRetries = 30;
265
+ for (let i = 0; i < maxPingRetries; i++) {
266
+ try {
267
+ const pingArgs = password
268
+ ? ['exec', container.name, 'redis-cli', '-a', password, 'ping']
269
+ : ['exec', container.name, 'redis-cli', 'ping'];
270
+ execFileSync(dockerPath, pingArgs, { stdio: 'pipe', timeout: 5000 });
271
+ break;
272
+ } catch {
273
+ if (i === maxPingRetries - 1) {
274
+ throw new Error(
275
+ `Container ${container.name} not responding to redis-cli ping after ${maxPingRetries} attempts`
276
+ );
277
+ }
278
+ await new Promise((r) => setTimeout(r, 1000));
279
+ }
280
+ }
281
+ }
282
+
283
+ // Initialize cluster
284
+ await RedisTestManager.initializeCluster(masters, replicas, password);
285
+
286
+ // Build NAT map for ioredis cluster connectivity
287
+ // Maps internal Docker IPs to external localhost:port addresses
288
+ const natMap: Record<string, { host: string; port: number }> = {};
289
+ for (const container of allContainers) {
290
+ if (container.internalIp) {
291
+ const hostPort = container.ports.get(6379);
292
+ if (hostPort) {
293
+ // Map internal IP:6379 to localhost:hostPort
294
+ natMap[`${container.internalIp}:6379`] = { host: 'localhost', port: hostPort };
295
+ }
296
+ }
297
+ }
298
+
299
+ return {
300
+ masters,
301
+ replicas,
302
+ network: networkName,
303
+ nodes,
304
+ natMap,
305
+ cleanup: async () => {
306
+ // Clean up containers first
307
+ await Promise.allSettled([...masters.map((c) => c.cleanup()), ...replicas.map((c) => c.cleanup())]);
308
+ // Then remove the network
309
+ try {
310
+ await RedisTestManager.getDockerManager()['removeNetwork'](networkName);
311
+ } catch (error) {
312
+ // Log but don't throw - network cleanup is best effort
313
+ console.warn(`Failed to remove network ${networkName}:`, error);
314
+ }
315
+ },
316
+ };
317
+ } catch (error) {
318
+ // Cleanup on failure - release allocated ports and clean up containers
319
+ allocatedPorts.forEach((port) => {
320
+ RedisTestManager.getDockerManager()['usedPorts'].delete(port);
321
+ });
322
+ await Promise.allSettled([
323
+ ...masters.map((c) =>
324
+ c.cleanup().catch((cleanupError) => {
325
+ // Log cleanup errors but don't fail the error flow - we're already handling a failure
326
+ console.error(`Failed to cleanup master container ${c.name}:`, cleanupError);
327
+ })
328
+ ),
329
+ ...replicas.map((c) =>
330
+ c.cleanup().catch((cleanupError) => {
331
+ // Log cleanup errors but don't fail the error flow - we're already handling a failure
332
+ console.error(`Failed to cleanup replica container ${c.name}:`, cleanupError);
333
+ })
334
+ ),
335
+ ]);
336
+ // Try to remove network on failure too
337
+ try {
338
+ await RedisTestManager.getDockerManager()['removeNetwork'](networkName);
339
+ } catch (networkError) {
340
+ // Log network cleanup errors but don't fail - network might be in use or already removed
341
+ console.error(`Failed to remove network ${networkName} during failure cleanup:`, networkError);
342
+ }
343
+ throw error;
344
+ }
345
+ }
346
+
347
+ /**
348
+ * Create Redis Sentinel setup (1 master + N replicas + M sentinels)
349
+ *
350
+ * @param options - Redis Sentinel configuration options
351
+ * @returns Promise resolving to RedisSentinelContainers
352
+ *
353
+ * @example
354
+ * ```typescript
355
+ * const sentinel = await RedisTestManager.createRedisSentinel({
356
+ * masterName: 'mymaster',
357
+ * replicaCount: 2,
358
+ * sentinelCount: 3,
359
+ * password: 'mypass',
360
+ * });
361
+ *
362
+ * // Use sentinel configuration
363
+ * const sentinelPorts = sentinel.sentinelPorts;
364
+ * const masterName = sentinel.masterName;
365
+ *
366
+ * // Cleanup when done
367
+ * await sentinel.cleanup();
368
+ * ```
369
+ */
370
+ static async createRedisSentinel(options?: RedisSentinelOptions): Promise<RedisSentinelContainers> {
371
+ const masterName = options?.masterName || 'mymaster';
372
+ const replicaCount = options?.replicaCount ?? 2;
373
+ const sentinelCount = options?.sentinelCount ?? 3;
374
+ const password = options?.password;
375
+ const networkName = options?.network || `redis-sentinel-${randomBytes(8).toString('hex')}`;
376
+
377
+ // Create network
378
+ await RedisTestManager.getDockerManager()['ensureNetwork'](networkName);
379
+
380
+ let master: DockerContainer | undefined;
381
+ const replicas: DockerContainer[] = [];
382
+ const sentinels: DockerContainer[] = [];
383
+ const sentinelPorts: number[] = [];
384
+ const allocatedPorts: number[] = [];
385
+
386
+ try {
387
+ // Create master with dynamic port allocation
388
+ const masterPort = await RedisTestManager.getDockerManager()['findAvailablePort']();
389
+ allocatedPorts.push(masterPort);
390
+ const command = ['redis-server', '--appendonly', 'no', '--save', ''];
391
+
392
+ if (password) {
393
+ command.push('--requirepass', password);
394
+ command.push('--masterauth', password);
395
+ }
396
+
397
+ master = await RedisTestManager.getDockerManager().createContainer({
398
+ name: `redis-sentinel-master`,
399
+ image: 'redis:7-alpine',
400
+ ports: { 6379: masterPort },
401
+ networks: [networkName],
402
+ command: command.join(' '),
403
+ healthcheck: {
404
+ test: password ? ['CMD', 'redis-cli', '-a', password, 'ping'] : ['CMD', 'redis-cli', 'ping'],
405
+ interval: '1s',
406
+ timeout: '3s',
407
+ retries: 5,
408
+ },
409
+ waitFor: {
410
+ healthcheck: true,
411
+ timeout: 30000,
412
+ },
413
+ });
414
+
415
+ // Create replicas
416
+ for (let i = 0; i < replicaCount; i++) {
417
+ const replicaPort = 6380 + i;
418
+ const replicaCommand = ['redis-server', '--appendonly', 'no', '--save', '', '--slaveof', master.name, '6379'];
419
+
420
+ if (password) {
421
+ replicaCommand.push('--requirepass', password);
422
+ replicaCommand.push('--masterauth', password);
423
+ }
424
+
425
+ const replica = await RedisTestManager.getDockerManager().createContainer({
426
+ name: `redis-sentinel-replica-${i}`,
427
+ image: 'redis:7-alpine',
428
+ ports: { 6379: replicaPort },
429
+ networks: [networkName],
430
+ command: replicaCommand.join(' '),
431
+ healthcheck: {
432
+ test: password ? ['CMD', 'redis-cli', '-a', password, 'ping'] : ['CMD', 'redis-cli', 'ping'],
433
+ interval: '1s',
434
+ timeout: '3s',
435
+ retries: 5,
436
+ },
437
+ waitFor: {
438
+ healthcheck: true,
439
+ timeout: 30000,
440
+ },
441
+ });
442
+
443
+ replicas.push(replica);
444
+ }
445
+
446
+ // Create sentinels with dynamic port allocation
447
+ for (let i = 0; i < sentinelCount; i++) {
448
+ const sentinelPort = await RedisTestManager.getDockerManager()['findAvailablePort']();
449
+ allocatedPorts.push(sentinelPort);
450
+ sentinelPorts.push(sentinelPort);
451
+
452
+ // Create sentinel config
453
+ const sentinelConfig = [
454
+ `sentinel monitor ${masterName} ${master.name} 6379 2`,
455
+ `sentinel down-after-milliseconds ${masterName} 5000`,
456
+ `sentinel parallel-syncs ${masterName} 1`,
457
+ `sentinel failover-timeout ${masterName} 10000`,
458
+ ];
459
+
460
+ if (password) {
461
+ sentinelConfig.push(`sentinel auth-pass ${masterName} ${password}`);
462
+ }
463
+
464
+ const sentinelCommand = [
465
+ 'sh',
466
+ '-c',
467
+ `echo "${sentinelConfig.join('\\n')}" > /tmp/sentinel.conf && redis-sentinel /tmp/sentinel.conf`,
468
+ ];
469
+
470
+ const sentinel = await RedisTestManager.getDockerManager().createContainer({
471
+ name: `redis-sentinel-${i}`,
472
+ image: 'redis:7-alpine',
473
+ ports: { 26379: sentinelPort },
474
+ networks: [networkName],
475
+ command: sentinelCommand.join(' '),
476
+ healthcheck: {
477
+ test: ['CMD', 'redis-cli', '-p', '26379', 'ping'],
478
+ interval: '1s',
479
+ timeout: '3s',
480
+ retries: 5,
481
+ },
482
+ waitFor: {
483
+ healthcheck: true,
484
+ timeout: 30000,
485
+ },
486
+ });
487
+
488
+ sentinels.push(sentinel);
489
+ }
490
+
491
+ return {
492
+ master,
493
+ replicas,
494
+ sentinels,
495
+ network: networkName,
496
+ masterName,
497
+ sentinelPorts,
498
+ cleanup: async () => {
499
+ await Promise.all(
500
+ [master?.cleanup(), ...replicas.map((c) => c.cleanup()), ...sentinels.map((c) => c.cleanup())].filter(
501
+ Boolean
502
+ ) as Promise<void>[]
503
+ );
504
+ },
505
+ };
506
+ } catch (error) {
507
+ // Cleanup on failure - release allocated ports
508
+ allocatedPorts.forEach((port) => {
509
+ RedisTestManager.getDockerManager()['usedPorts'].delete(port);
510
+ });
511
+ await Promise.all(
512
+ [
513
+ master?.cleanup().catch((cleanupError) => {
514
+ // Log cleanup errors but don't fail the error flow - we're already handling a failure
515
+ console.error(`Failed to cleanup master container ${master?.name}:`, cleanupError);
516
+ }),
517
+ ...replicas.map((c) =>
518
+ c.cleanup().catch((cleanupError) => {
519
+ // Log cleanup errors but don't fail the error flow - we're already handling a failure
520
+ console.error(`Failed to cleanup replica container ${c.name}:`, cleanupError);
521
+ })
522
+ ),
523
+ ...sentinels.map((c) =>
524
+ c.cleanup().catch((cleanupError) => {
525
+ // Log cleanup errors but don't fail the error flow - we're already handling a failure
526
+ console.error(`Failed to cleanup sentinel container ${c.name}:`, cleanupError);
527
+ })
528
+ ),
529
+ ].filter(Boolean)
530
+ );
531
+ throw error;
532
+ }
533
+ }
534
+
535
+ /**
536
+ * Helper to initialize Redis cluster
537
+ * @private
538
+ */
539
+ private static async initializeCluster(
540
+ masters: DockerContainer[],
541
+ replicas: DockerContainer[],
542
+ password?: string
543
+ ): Promise<void> {
544
+ if (masters.length === 0) {
545
+ return;
546
+ }
547
+
548
+ // Build cluster create command
549
+ // Note: Use container names as hostnames (not 127.0.0.1) because cluster init runs inside a container
550
+ // Docker network DNS resolves container names to their IPs, and Redis listens on port 6379 internally
551
+ const allNodes = [...masters, ...replicas];
552
+ const nodeAddresses = allNodes.map((c) => `${c.name}:6379`);
553
+
554
+ const clusterArgs = [
555
+ 'redis-cli',
556
+ '--cluster',
557
+ 'create',
558
+ ...nodeAddresses,
559
+ '--cluster-replicas',
560
+ String(Math.floor(replicas.length / masters.length)),
561
+ '--cluster-yes',
562
+ ];
563
+
564
+ if (password) {
565
+ clusterArgs.splice(1, 0, '-a', password);
566
+ }
567
+
568
+ // Execute cluster create inside the first master container
569
+ const firstMaster = masters[0];
570
+ if (!firstMaster) {
571
+ throw new Error('No master nodes available to initialize cluster');
572
+ }
573
+
574
+ try {
575
+ const dockerPath = DockerTestManager.getInstance()['dockerPath'];
576
+ const verbose = DockerTestManager.getInstance()['verbose'];
577
+
578
+ if (verbose) {
579
+ console.log('[RedisCluster] Initializing cluster with nodes:', nodeAddresses);
580
+ console.log('[RedisCluster] Running command:', ['exec', firstMaster.name, ...clusterArgs].join(' '));
581
+ }
582
+
583
+ const output = execFileSync(dockerPath, ['exec', firstMaster.name, ...clusterArgs], {
584
+ stdio: verbose ? 'inherit' : 'pipe',
585
+ timeout: 60000,
586
+ encoding: 'utf8',
587
+ });
588
+
589
+ if (verbose && output) {
590
+ console.log('[RedisCluster] Initialization output:', output);
591
+ }
592
+
593
+ // Wait for cluster to be ready - robust check
594
+ const maxWait = 30000; // 30 seconds
595
+ const startTime = Date.now();
596
+ let clusterReady = false;
597
+
598
+ while (!clusterReady && Date.now() - startTime < maxWait) {
599
+ try {
600
+ const clusterInfo = execFileSync(
601
+ dockerPath,
602
+ ['exec', firstMaster.name, 'redis-cli', ...(password ? ['-a', password] : []), 'cluster', 'info'],
603
+ { encoding: 'utf8', stdio: 'pipe' }
604
+ );
605
+
606
+ if (clusterInfo.includes('cluster_state:ok')) {
607
+ // Verify all slots are assigned
608
+ if (
609
+ clusterInfo.includes('cluster_slots_assigned:16384') &&
610
+ clusterInfo.includes('cluster_slots_ok:16384')
611
+ ) {
612
+ clusterReady = true;
613
+ if (verbose) {
614
+ console.log('[RedisCluster] Cluster is ready');
615
+ }
616
+ break;
617
+ }
618
+ }
619
+ } catch {
620
+ // Not ready yet, continue waiting
621
+ }
622
+
623
+ await new Promise((resolve) => setTimeout(resolve, 500));
624
+ }
625
+
626
+ if (!clusterReady) {
627
+ throw new Error('Redis cluster failed to reach ready state within timeout');
628
+ }
629
+
630
+ if (verbose) {
631
+ console.log('[RedisCluster] Cluster initialization complete');
632
+ }
633
+ } catch (error) {
634
+ const errorMsg = error instanceof Error ? error.message : String(error);
635
+ throw new Error(`Failed to initialize Redis cluster: ${errorMsg}`, { cause: error });
636
+ }
637
+ }
638
+
639
+ /**
640
+ * Helper: Run test with a standalone Redis container
641
+ *
642
+ * @param testFn - Test function that receives container and connection string
643
+ * @param options - Redis configuration options
644
+ * @returns Promise resolving to test function result
645
+ *
646
+ * @example
647
+ * ```typescript
648
+ * await RedisTestManager.withRedis(async (container, connectionString) => {
649
+ * const client = new Redis(connectionString);
650
+ * await client.set('key', 'value');
651
+ * // Run tests...
652
+ * await client.quit();
653
+ * });
654
+ * ```
655
+ */
656
+ static async withRedis<T>(
657
+ testFn: (container: DockerContainer, connectionString: string) => Promise<T>,
658
+ options?: RedisContainerOptions
659
+ ): Promise<T> {
660
+ const container = await RedisTestManager.createRedisContainer(options);
661
+
662
+ const port = container.ports.get(6379)!;
663
+ const password = options?.password;
664
+ const database = options?.database ?? 0;
665
+
666
+ let connectionString = `redis://`;
667
+ if (password) {
668
+ connectionString += `:${password}@`;
669
+ }
670
+ connectionString += `localhost:${port}/${database}`;
671
+
672
+ try {
673
+ return await testFn(container, connectionString);
674
+ } finally {
675
+ await container.cleanup();
676
+ }
677
+ }
678
+
679
+ /**
680
+ * Helper: Run test with Redis cluster
681
+ *
682
+ * @param testFn - Test function that receives cluster containers
683
+ * @param options - Redis Cluster configuration options
684
+ * @returns Promise resolving to test function result
685
+ *
686
+ * @example
687
+ * ```typescript
688
+ * await RedisTestManager.withRedisCluster(async (cluster) => {
689
+ * const client = new Redis.Cluster(cluster.nodes.map(n => ({ host: n.host, port: n.port })));
690
+ * await client.set('key', 'value');
691
+ * // Run tests...
692
+ * await client.quit();
693
+ * }, { masterCount: 3, replicasPerMaster: 1 });
694
+ * ```
695
+ */
696
+ static async withRedisCluster<T>(
697
+ testFn: (cluster: RedisClusterContainers) => Promise<T>,
698
+ options?: RedisClusterOptions
699
+ ): Promise<T> {
700
+ const cluster = await RedisTestManager.createRedisCluster(options);
701
+
702
+ try {
703
+ return await testFn(cluster);
704
+ } finally {
705
+ await cluster.cleanup();
706
+ }
707
+ }
708
+
709
+ /**
710
+ * Helper: Run test with Redis Sentinel
711
+ *
712
+ * @param testFn - Test function that receives sentinel containers
713
+ * @param options - Redis Sentinel configuration options
714
+ * @returns Promise resolving to test function result
715
+ *
716
+ * @example
717
+ * ```typescript
718
+ * await RedisTestManager.withRedisSentinel(async (sentinel) => {
719
+ * const client = new Redis({
720
+ * sentinels: sentinel.sentinelPorts.map(port => ({ host: '127.0.0.1', port })),
721
+ * name: sentinel.masterName,
722
+ * });
723
+ * await client.set('key', 'value');
724
+ * // Run tests...
725
+ * await client.quit();
726
+ * });
727
+ * ```
728
+ */
729
+ static async withRedisSentinel<T>(
730
+ testFn: (sentinel: RedisSentinelContainers) => Promise<T>,
731
+ options?: RedisSentinelOptions
732
+ ): Promise<T> {
733
+ const sentinel = await RedisTestManager.createRedisSentinel(options);
734
+
735
+ try {
736
+ return await testFn(sentinel);
737
+ } finally {
738
+ await sentinel.cleanup();
739
+ }
740
+ }
741
+ }