@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,1198 @@
1
+ /**
2
+ * Generic Docker Test Manager
3
+ *
4
+ * Provides a unified interface for managing Docker containers in tests
5
+ * with robust lifecycle management, graceful shutdown, and reliable cleanup.
6
+ *
7
+ * Features:
8
+ * - Singleton pattern for centralized container management
9
+ * - Automatic port allocation with worker-aware ranges
10
+ * - Cross-platform Docker executable detection
11
+ * - Graceful shutdown with cleanup on exit
12
+ * - Health check support
13
+ * - Network management
14
+ */
15
+
16
+ import { execSync, execFileSync } from 'child_process';
17
+ import { randomBytes } from 'crypto';
18
+ import * as net from 'net';
19
+ import { EventEmitter } from 'events';
20
+ import type { DockerContainer, DockerContainerStatus, DockerTestManagerOptions, ContainerOptions } from './types.js';
21
+
22
+ /**
23
+ * Docker Test Manager
24
+ *
25
+ * Manages Docker containers for testing with automatic cleanup and port allocation.
26
+ * Uses singleton pattern to ensure proper cleanup across test suites.
27
+ *
28
+ * @example
29
+ * ```typescript
30
+ * const manager = DockerTestManager.getInstance();
31
+ * const container = await manager.createContainer({
32
+ * image: 'redis:7-alpine',
33
+ * ports: { 6379: 'auto' },
34
+ * healthcheck: {
35
+ * test: ['CMD', 'redis-cli', 'ping'],
36
+ * interval: '1s',
37
+ * },
38
+ * waitFor: { healthcheck: true },
39
+ * });
40
+ *
41
+ * // Use container...
42
+ * await container.cleanup();
43
+ * ```
44
+ */
45
+ export class DockerTestManager extends EventEmitter {
46
+ private static instance: DockerTestManager;
47
+ private containers: Map<string, DockerContainer> = new Map();
48
+ private usedPorts: Set<number> = new Set();
49
+ private networks: Set<string> = new Set();
50
+ private cleanupInProgress = false;
51
+
52
+ private dockerPath: string;
53
+ private basePort: number;
54
+ private maxRetries: number;
55
+ private startupTimeout: number;
56
+ private gracefulShutdownTimeout: number;
57
+ private maxCleanupRetries: number;
58
+ private cleanup: boolean;
59
+ private verbose: boolean;
60
+ private defaultNetwork?: string;
61
+
62
+ private constructor(options: DockerTestManagerOptions = {}) {
63
+ super();
64
+ this.dockerPath = options.dockerPath || this.findDockerPath();
65
+
66
+ // Worker-aware port allocation to prevent conflicts in parallel test execution
67
+ // Each vitest worker gets its own 10k port range
68
+ const workerId = parseInt(process.env['VITEST_POOL_ID'] || process.env['VITEST_WORKER_ID'] || '1', 10);
69
+ const basePortOffset = (workerId - 1) * 10000;
70
+ this.basePort = options.basePort || 10000 + basePortOffset;
71
+
72
+ this.maxRetries = options.maxRetries || 30;
73
+ this.startupTimeout = options.startupTimeout || 60000;
74
+ this.gracefulShutdownTimeout = options.gracefulShutdownTimeout || 10000;
75
+ this.maxCleanupRetries = options.maxCleanupRetries || 3;
76
+ this.cleanup = options.cleanup !== false;
77
+ this.verbose = options.verbose || false;
78
+ this.defaultNetwork = options.network;
79
+
80
+ if (this.verbose) {
81
+ this.log(`Initialized for Vitest worker ${workerId} with port range ${this.basePort}-${this.basePort + 10000}`);
82
+ }
83
+
84
+ // Verify Docker is available
85
+ this.verifyDocker();
86
+
87
+ // Register cleanup handlers with graceful shutdown
88
+ if (this.cleanup) {
89
+ // Increase max listeners to avoid warnings when multiple test managers are instantiated
90
+ // This is safe because signal handlers should be idempotent and cleanup is managed by the singleton pattern
91
+ process.setMaxListeners(Math.max(20, process.getMaxListeners()));
92
+
93
+ process.on('exit', () => this.cleanupSync());
94
+ process.on('SIGINT', () => {
95
+ this.log('SIGINT received - initiating graceful shutdown');
96
+ this.cleanupAllAsync()
97
+ .then(() => {
98
+ this.log('Cleanup completed, exiting');
99
+ process.exit(0);
100
+ })
101
+ .catch((error) => {
102
+ this.logError('Cleanup failed during SIGINT', error);
103
+ process.exit(1);
104
+ });
105
+ });
106
+ process.on('SIGTERM', () => {
107
+ this.log('SIGTERM received - initiating graceful shutdown');
108
+ this.cleanupAllAsync()
109
+ .then(() => {
110
+ this.log('Cleanup completed, exiting');
111
+ process.exit(0);
112
+ })
113
+ .catch((error) => {
114
+ this.logError('Cleanup failed during SIGTERM', error);
115
+ process.exit(1);
116
+ });
117
+ });
118
+ }
119
+ }
120
+
121
+ /**
122
+ * Get the singleton instance of DockerTestManager
123
+ *
124
+ * @param options - Configuration options (only used on first call)
125
+ * @returns The singleton DockerTestManager instance
126
+ */
127
+ static getInstance(options?: DockerTestManagerOptions): DockerTestManager {
128
+ if (!DockerTestManager.instance) {
129
+ DockerTestManager.instance = new DockerTestManager(options);
130
+ }
131
+ return DockerTestManager.instance;
132
+ }
133
+
134
+ /**
135
+ * Find Docker executable path across different platforms
136
+ *
137
+ * Detection strategy:
138
+ * 1. Try 'which docker' (Unix) or 'where docker' (Windows) to find in PATH
139
+ * 2. Check platform-specific common locations
140
+ * 3. Validate the found path works with 'docker version'
141
+ *
142
+ * Supported platforms:
143
+ * - macOS: /usr/local/bin/docker, /opt/homebrew/bin/docker, docker in PATH
144
+ * - Linux: /usr/bin/docker, /usr/local/bin/docker, /snap/bin/docker, docker in PATH
145
+ * - Windows: docker.exe in PATH, C:\Program Files\Docker\Docker\resources\bin\docker.exe
146
+ *
147
+ * @throws Error if Docker cannot be found
148
+ * @private
149
+ */
150
+ private findDockerPath(): string {
151
+ const isWindows = process.platform === 'win32';
152
+ const whichCommand = isWindows ? 'where' : 'which';
153
+ const dockerBinary = isWindows ? 'docker.exe' : 'docker';
154
+
155
+ // Strategy 1: Try to find Docker in PATH using which/where
156
+ try {
157
+ const result = execSync(`${whichCommand} ${dockerBinary}`, {
158
+ encoding: 'utf8',
159
+ stdio: ['pipe', 'pipe', 'ignore'],
160
+ }).trim();
161
+
162
+ // On Windows, 'where' can return multiple paths (one per line)
163
+ // Take the first one
164
+ const dockerPath = result.split('\n')[0]?.trim();
165
+
166
+ if (dockerPath && this.testDockerPath(dockerPath)) {
167
+ if (this.verbose) {
168
+ console.log(`Found Docker in PATH: ${dockerPath}`);
169
+ }
170
+ return dockerPath;
171
+ }
172
+ } catch {
173
+ // Command failed, continue to fallback paths
174
+ }
175
+
176
+ // Strategy 2: Check platform-specific common locations
177
+ const fallbackPaths = this.getDockerFallbackPaths();
178
+
179
+ for (const path of fallbackPaths) {
180
+ if (this.testDockerPath(path)) {
181
+ if (this.verbose) {
182
+ console.log(`Found Docker at fallback path: ${path}`);
183
+ }
184
+ return path;
185
+ }
186
+ }
187
+
188
+ // Strategy 3: If all else fails, try just 'docker' or 'docker.exe' and hope it's in PATH
189
+ if (this.testDockerPath(dockerBinary)) {
190
+ if (this.verbose) {
191
+ console.log(`Using Docker from PATH: ${dockerBinary}`);
192
+ }
193
+ return dockerBinary;
194
+ }
195
+
196
+ // No Docker found
197
+ throw new Error(
198
+ `Docker executable not found. Please install Docker and ensure it's in your PATH.\n` +
199
+ `Searched paths:\n` +
200
+ ` - PATH using '${whichCommand} ${dockerBinary}'\n` +
201
+ ` - ${fallbackPaths.join('\n - ')}\n` +
202
+ `\n` +
203
+ `Platform: ${process.platform}\n` +
204
+ `For more information, visit: https://docs.docker.com/get-docker/`
205
+ );
206
+ }
207
+
208
+ /**
209
+ * Get platform-specific fallback paths for Docker
210
+ * @private
211
+ */
212
+ private getDockerFallbackPaths(): string[] {
213
+ switch (process.platform) {
214
+ case 'darwin': // macOS
215
+ return [
216
+ '/usr/local/bin/docker', // Intel Mac / Docker Desktop
217
+ '/opt/homebrew/bin/docker', // Apple Silicon Mac / Homebrew
218
+ '/Applications/Docker.app/Contents/Resources/bin/docker', // Docker Desktop
219
+ ];
220
+
221
+ case 'linux':
222
+ return [
223
+ '/usr/bin/docker', // Most common Linux location
224
+ '/usr/local/bin/docker', // Alternative Linux location
225
+ '/snap/bin/docker', // Snap package
226
+ '/var/lib/snapd/snap/bin/docker', // Snap on some distros
227
+ '/opt/docker/bin/docker', // Custom installations
228
+ ];
229
+
230
+ case 'win32': // Windows
231
+ return [
232
+ 'docker.exe', // Should be in PATH
233
+ 'C:\\Program Files\\Docker\\Docker\\resources\\bin\\docker.exe',
234
+ 'C:\\ProgramData\\DockerDesktop\\version-bin\\docker.exe',
235
+ ];
236
+
237
+ default:
238
+ // Unknown platform, try generic paths
239
+ return ['/usr/local/bin/docker', '/usr/bin/docker', 'docker'];
240
+ }
241
+ }
242
+
243
+ /**
244
+ * Test if a Docker path is valid by running 'docker version'
245
+ * @private
246
+ */
247
+ private testDockerPath(dockerPath: string): boolean {
248
+ try {
249
+ // Use execFileSync to avoid shell quoting issues
250
+ execFileSync(dockerPath, ['version'], {
251
+ stdio: 'ignore',
252
+ timeout: 5000, // 5 second timeout
253
+ });
254
+ return true;
255
+ } catch {
256
+ return false;
257
+ }
258
+ }
259
+
260
+ /**
261
+ * Verify Docker is available and working
262
+ * @throws Error if Docker is not available
263
+ * @private
264
+ */
265
+ private verifyDocker(): void {
266
+ try {
267
+ // Use execFileSync to avoid shell quoting issues
268
+ execFileSync(this.dockerPath, ['version'], { stdio: 'ignore' });
269
+ } catch {
270
+ throw new Error(
271
+ `Docker is not available at path: ${this.dockerPath}\n` +
272
+ `Please install Docker or verify it's properly configured.\n` +
273
+ `Visit: https://docs.docker.com/get-docker/`
274
+ );
275
+ }
276
+ }
277
+
278
+ /**
279
+ * Find an available port for container mapping
280
+ * @private
281
+ */
282
+ private async findAvailablePort(): Promise<number> {
283
+ for (let i = 0; i < this.maxRetries; i++) {
284
+ const port = this.basePort + Math.floor(Math.random() * 10000);
285
+ if (!this.usedPorts.has(port) && (await this.isPortAvailable(port))) {
286
+ this.usedPorts.add(port);
287
+ return port;
288
+ }
289
+ }
290
+ throw new Error('Could not find available port for container');
291
+ }
292
+
293
+ /**
294
+ * Check if a port is available on localhost
295
+ * @private
296
+ */
297
+ private async isPortAvailable(port: number): Promise<boolean> {
298
+ return new Promise((resolve) => {
299
+ const server = net.createServer();
300
+ server.once('error', () => resolve(false));
301
+ server.once('listening', () => {
302
+ server.close();
303
+ resolve(true);
304
+ });
305
+ server.listen(port, '127.0.0.1');
306
+ });
307
+ }
308
+
309
+ /**
310
+ * Log a message if verbose mode is enabled
311
+ * @private
312
+ */
313
+ private log(message: string, data?: any): void {
314
+ if (this.verbose) {
315
+ const timestamp = new Date().toISOString();
316
+ const msg = data ? `[${timestamp}] ${message}: ${JSON.stringify(data)}` : `[${timestamp}] ${message}`;
317
+ console.log(msg);
318
+ }
319
+ }
320
+
321
+ /**
322
+ * Log an error message
323
+ * @private
324
+ */
325
+ private logError(message: string, error: any): void {
326
+ const timestamp = new Date().toISOString();
327
+ const err = error instanceof Error ? error.message : String(error);
328
+ const msg = `[${timestamp}] ERROR: ${message}: ${err}`;
329
+ if (this.verbose) {
330
+ console.error(msg);
331
+ }
332
+ }
333
+
334
+ /**
335
+ * Get the status of a container
336
+ * @private
337
+ */
338
+ private async getContainerStatus(name: string): Promise<DockerContainerStatus> {
339
+ try {
340
+ const inspectOutput = execFileSync(
341
+ this.dockerPath,
342
+ [
343
+ 'inspect',
344
+ '--format',
345
+ '{{.State.Running}}\t{{.State.Status}}\t{{.State.Health.Status}}\t{{.State.ExitCode}}',
346
+ name,
347
+ ],
348
+ {
349
+ encoding: 'utf8',
350
+ stdio: ['pipe', 'pipe', 'ignore'],
351
+ }
352
+ ).trim();
353
+
354
+ const [running, state, health, exitCode] = inspectOutput.split('\t');
355
+
356
+ return {
357
+ isRunning: running === 'true',
358
+ state: state || undefined,
359
+ health: health && health !== '<no value>' ? health : undefined,
360
+ exitCode: exitCode ? parseInt(exitCode) : undefined,
361
+ };
362
+ } catch (error) {
363
+ this.logError(`Failed to get container status for ${name}`, error);
364
+ return { isRunning: false };
365
+ }
366
+ }
367
+
368
+ /**
369
+ * Check if a container is healthy
370
+ * @private
371
+ */
372
+ private async isContainerHealthy(name: string): Promise<boolean> {
373
+ try {
374
+ const status = await this.getContainerStatus(name);
375
+ if (!status.isRunning) {
376
+ return false;
377
+ }
378
+ // If container has health check, wait for healthy state
379
+ if (status.health) {
380
+ return status.health === 'healthy';
381
+ }
382
+ // If no health check defined, just check if running
383
+ return true;
384
+ } catch {
385
+ return false;
386
+ }
387
+ }
388
+
389
+ /**
390
+ * Create and start a Docker container
391
+ *
392
+ * @param options - Container configuration
393
+ * @returns Promise resolving to DockerContainer instance
394
+ *
395
+ * @example
396
+ * ```typescript
397
+ * const container = await manager.createContainer({
398
+ * image: 'postgres:16-alpine',
399
+ * ports: { 5432: 'auto' },
400
+ * environment: { POSTGRES_PASSWORD: 'test' },
401
+ * healthcheck: {
402
+ * test: ['CMD', 'pg_isready'],
403
+ * interval: '1s',
404
+ * },
405
+ * waitFor: { healthcheck: true },
406
+ * });
407
+ * ```
408
+ */
409
+ async createContainer(options: ContainerOptions): Promise<DockerContainer> {
410
+ const id = `test-${randomBytes(8).toString('hex')}`; // 8 bytes for better uniqueness in parallel execution
411
+ const name = options.name || `container-${id}`;
412
+ const host = '127.0.0.1';
413
+
414
+ // Remove any existing container with the same name to avoid conflicts
415
+ try {
416
+ execFileSync(this.dockerPath, ['rm', '-f', name], { stdio: 'ignore' });
417
+ this.log(`Removed existing container: ${name}`);
418
+ } catch {
419
+ // Container doesn't exist, which is fine
420
+ }
421
+
422
+ // Process port mappings
423
+ const portMappings = new Map<number, number>();
424
+ if (options.ports) {
425
+ for (const [containerPort, hostPort] of Object.entries(options.ports)) {
426
+ const cPort = parseInt(containerPort);
427
+ const hPort = hostPort === 'auto' ? await this.findAvailablePort() : hostPort;
428
+ portMappings.set(cPort, hPort);
429
+ }
430
+ }
431
+
432
+ // Build docker run command
433
+ const dockerArgs: string[] = ['run', '-d', '--name', name];
434
+
435
+ // Add ports
436
+ portMappings.forEach((hostPort, containerPort) => {
437
+ dockerArgs.push('-p', `${hostPort}:${containerPort}`);
438
+ });
439
+
440
+ // Add environment variables
441
+ const environment = options.environment || {};
442
+ for (const [key, value] of Object.entries(environment)) {
443
+ dockerArgs.push('-e', `${key}=${value}`);
444
+ }
445
+
446
+ // Add labels
447
+ const labels = {
448
+ 'test.id': id,
449
+ 'test.cleanup': 'true',
450
+ ...options.labels,
451
+ };
452
+ for (const [key, value] of Object.entries(labels)) {
453
+ dockerArgs.push('--label', `${key}=${value}`);
454
+ }
455
+
456
+ // Add volumes
457
+ if (options.volumes) {
458
+ for (const volume of options.volumes) {
459
+ dockerArgs.push('-v', volume);
460
+ }
461
+ }
462
+
463
+ // Add networks
464
+ const networks = options.networks || (this.defaultNetwork ? [this.defaultNetwork] : []);
465
+ for (const network of networks) {
466
+ // Create network if it doesn't exist
467
+ await this.ensureNetwork(network);
468
+ dockerArgs.push('--network', network);
469
+ }
470
+
471
+ // Add healthcheck if provided
472
+ if (options.healthcheck) {
473
+ // Docker CLI --health-cmd expects a string that is executed by the shell
474
+ // The healthcheck.test array format from Docker Compose needs to be converted:
475
+ // - ['CMD', 'arg1', 'arg2'] -> execute command directly (no shell)
476
+ // - ['CMD-SHELL', 'command'] -> execute via shell
477
+ let healthCmd: string;
478
+ if (Array.isArray(options.healthcheck.test)) {
479
+ if (options.healthcheck.test[0] === 'CMD-SHELL') {
480
+ // CMD-SHELL format: join everything after the first element
481
+ healthCmd = options.healthcheck.test.slice(1).join(' ');
482
+ } else if (options.healthcheck.test[0] === 'CMD') {
483
+ // CMD format: join command parts without shell
484
+ // Docker CLI expects this as a single string that will be word-split
485
+ // For example: ['CMD', 'redis-cli', 'ping'] -> 'redis-cli ping'
486
+ healthCmd = options.healthcheck.test.slice(1).join(' ');
487
+ } else {
488
+ // No format specifier, join all parts
489
+ healthCmd = options.healthcheck.test.join(' ');
490
+ }
491
+ } else {
492
+ // String format
493
+ healthCmd = options.healthcheck.test;
494
+ }
495
+ dockerArgs.push('--health-cmd', healthCmd);
496
+ if (options.healthcheck.interval) {
497
+ dockerArgs.push('--health-interval', options.healthcheck.interval);
498
+ }
499
+ if (options.healthcheck.timeout) {
500
+ dockerArgs.push('--health-timeout', options.healthcheck.timeout);
501
+ }
502
+ if (options.healthcheck.retries) {
503
+ dockerArgs.push('--health-retries', options.healthcheck.retries.toString());
504
+ }
505
+ if (options.healthcheck.startPeriod) {
506
+ dockerArgs.push('--health-start-period', options.healthcheck.startPeriod);
507
+ }
508
+ }
509
+
510
+ // Add image and command
511
+ dockerArgs.push(options.image);
512
+ if (options.command) {
513
+ dockerArgs.push('sh', '-c', options.command);
514
+ }
515
+
516
+ if (this.verbose) {
517
+ console.log(`Starting container ${name}: docker ${dockerArgs.join(' ')}`);
518
+ }
519
+
520
+ // Start container using execFileSync to properly handle arguments with spaces
521
+ try {
522
+ this.log(`Starting container: ${name}`, { image: options.image });
523
+ const result = execFileSync(this.dockerPath, dockerArgs, {
524
+ encoding: 'utf8',
525
+ stdio: ['pipe', 'pipe', 'pipe'], // Always capture output for better error messages
526
+ });
527
+ if (this.verbose && result) {
528
+ console.log(result);
529
+ }
530
+ } catch (error) {
531
+ // Clean up allocated ports before throwing
532
+ portMappings.forEach((port) => {
533
+ this.usedPorts.delete(port);
534
+ });
535
+ const execError = error as {
536
+ stderr?: Buffer | string;
537
+ stdout?: Buffer | string;
538
+ message?: string;
539
+ status?: number;
540
+ };
541
+ const stderr = execError.stderr ? String(execError.stderr).trim() : '';
542
+ const stdout = execError.stdout ? String(execError.stdout).trim() : '';
543
+ const message = execError.message || String(error);
544
+
545
+ // Check if container already exists
546
+ if (stderr.includes('already in use') || stderr.includes('name is already') || stderr.includes('Conflict')) {
547
+ throw new Error(
548
+ `Container name conflict: ${name} already exists.\n` +
549
+ `Please ensure previous test containers are cleaned up.\n` +
550
+ `Stderr: ${stderr}`,
551
+ { cause: error }
552
+ );
553
+ }
554
+
555
+ throw new Error(
556
+ `Failed to start container ${name}:\n` +
557
+ `Command: docker ${dockerArgs.join(' ')}\n` +
558
+ `Exit code: ${execError.status || 'unknown'}\n` +
559
+ (stderr ? `Stderr: ${stderr}\n` : '') +
560
+ (stdout ? `Stdout: ${stdout}\n` : '') +
561
+ (message && !stderr && !stdout ? `Error: ${message}` : ''),
562
+ { cause: error }
563
+ );
564
+ }
565
+
566
+ // Wait for container to be ready
567
+ if (options.waitFor) {
568
+ try {
569
+ await this.waitForContainer(name, options.waitFor);
570
+ this.log(`Container ready: ${name}`);
571
+ } catch (error) {
572
+ // Container failed to start, attempt cleanup
573
+ this.logError(`Container ${name} failed to become ready, cleaning up`, error);
574
+ try {
575
+ execFileSync(this.dockerPath, ['stop', '-t', '5', name], { stdio: 'ignore' });
576
+ execFileSync(this.dockerPath, ['rm', '-f', name], { stdio: 'ignore' });
577
+ } catch {
578
+ // Ignore cleanup errors during rollback
579
+ }
580
+ // Clean up allocated ports
581
+ portMappings.forEach((port) => {
582
+ this.usedPorts.delete(port);
583
+ });
584
+ throw error;
585
+ }
586
+ }
587
+
588
+ // Get internal IP if container is on a network
589
+ let internalIp: string | undefined;
590
+ if (networks.length > 0) {
591
+ try {
592
+ const ipOutput = execFileSync(
593
+ this.dockerPath,
594
+ ['inspect', name, '--format', '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}'],
595
+ {
596
+ encoding: 'utf8',
597
+ stdio: ['pipe', 'pipe', 'ignore'],
598
+ }
599
+ ).trim();
600
+ if (ipOutput) {
601
+ internalIp = ipOutput;
602
+ this.log(`Container ${name} internal IP: ${internalIp}`);
603
+ }
604
+ } catch (error) {
605
+ this.logError(`Failed to get internal IP for ${name}`, error);
606
+ // Continue without internal IP
607
+ }
608
+ }
609
+
610
+ const container: DockerContainer = {
611
+ id,
612
+ name,
613
+ image: options.image,
614
+ host,
615
+ port: portMappings.values().next().value, // First port for convenience
616
+ ports: portMappings,
617
+ environment,
618
+ labels,
619
+ networks,
620
+ createdAt: new Date(),
621
+ internalIp,
622
+ getStatus: async () => this.getContainerStatus(name),
623
+ isHealthy: async () => this.isContainerHealthy(name),
624
+ cleanup: async () => {
625
+ await this.cleanupContainerWithRetry(name, id, portMappings);
626
+ },
627
+ };
628
+
629
+ this.containers.set(id, container);
630
+ return container;
631
+ }
632
+
633
+ /**
634
+ * Clean up a container with retry logic
635
+ * @private
636
+ */
637
+ private async cleanupContainerWithRetry(name: string, id: string, portMappings: Map<number, number>): Promise<void> {
638
+ this.log(`Starting cleanup for container: ${name}`);
639
+
640
+ let lastError!: Error | null;
641
+
642
+ for (let attempt = 1; attempt <= this.maxCleanupRetries; attempt++) {
643
+ try {
644
+ // Check if container exists
645
+ try {
646
+ const status = await this.getContainerStatus(name);
647
+ if (!status.isRunning) {
648
+ this.log(`Container ${name} is not running, force removing`, { attempt });
649
+ }
650
+ } catch {
651
+ // Container doesn't exist, nothing to clean up
652
+ this.log(`Container ${name} doesn't exist, skipping stop`, { attempt });
653
+ break;
654
+ }
655
+
656
+ // Gracefully stop the container first
657
+ try {
658
+ const stopTimeoutSecs = Math.ceil(this.gracefulShutdownTimeout / 1000).toString();
659
+ this.log(`Stopping container ${name}`, { attempt, timeout: this.gracefulShutdownTimeout });
660
+ execFileSync(this.dockerPath, ['stop', '-t', stopTimeoutSecs, name], {
661
+ stdio: 'ignore',
662
+ timeout: this.gracefulShutdownTimeout + 5000, // Add buffer to docker timeout
663
+ });
664
+ this.log(`Container stopped: ${name}`, { attempt });
665
+ } catch (error) {
666
+ this.logError(`Failed to gracefully stop container ${name}`, error);
667
+ // Continue to force remove
668
+ }
669
+
670
+ // Remove container
671
+ try {
672
+ this.log(`Removing container ${name}`, { attempt });
673
+ execFileSync(this.dockerPath, ['rm', '-f', name], { stdio: 'ignore' });
674
+ this.log(`Container removed: ${name}`, { attempt });
675
+ lastError = null; // Clear error on success
676
+ break;
677
+ } catch (error) {
678
+ lastError = error instanceof Error ? error : new Error(String(error));
679
+ if (attempt === this.maxCleanupRetries) {
680
+ throw lastError;
681
+ }
682
+ // Wait before retrying
683
+ await new Promise((resolve) => setTimeout(resolve, 1000 * attempt));
684
+ }
685
+ } catch (error) {
686
+ lastError = error instanceof Error ? error : new Error(String(error));
687
+ if (attempt === this.maxCleanupRetries) {
688
+ this.logError(`Final cleanup attempt failed for container ${name}`, lastError);
689
+ // Don't throw, continue with port cleanup
690
+ } else {
691
+ this.logError(`Cleanup attempt ${attempt} failed for container ${name}, retrying`, lastError);
692
+ await new Promise((resolve) => setTimeout(resolve, 1000 * attempt));
693
+ }
694
+ }
695
+ }
696
+
697
+ // Always release ports, even if cleanup failed
698
+ try {
699
+ portMappings.forEach((port) => {
700
+ this.usedPorts.delete(port);
701
+ this.log(`Released port: ${port}`);
702
+ });
703
+ } catch (error) {
704
+ this.logError('Failed to release ports', error);
705
+ }
706
+
707
+ // Remove from tracking
708
+ this.containers.delete(id);
709
+ this.log(`Container cleanup completed: ${name}`, { attempts: this.maxCleanupRetries });
710
+ }
711
+
712
+ /**
713
+ * Ensure a Docker network exists
714
+ * @private
715
+ */
716
+ private async ensureNetwork(network: string): Promise<void> {
717
+ if (!this.networks.has(network)) {
718
+ try {
719
+ execFileSync(this.dockerPath, ['network', 'create', network, '--label', 'test.cleanup=true'], {
720
+ stdio: 'pipe',
721
+ encoding: 'utf8',
722
+ });
723
+ this.networks.add(network);
724
+ this.log(`Created network: ${network}`);
725
+ } catch (error) {
726
+ const execError = error as { stderr?: string; stdout?: string; message?: string };
727
+ const stderr = execError.stderr || execError.message || String(error);
728
+ // Network might already exist - check if that's the case
729
+ if (stderr.includes('already exists') || stderr.includes('network with name')) {
730
+ this.log(`Network already exists: ${network}`);
731
+ this.networks.add(network);
732
+ } else if (stderr.includes('all predefined address pools have been fully subnetted')) {
733
+ // Docker network pool exhausted - try to clean up unused networks
734
+ this.log('Docker network pool exhausted, attempting cleanup...');
735
+ try {
736
+ // Prune unused networks
737
+ execFileSync(this.dockerPath, ['network', 'prune', '-f'], {
738
+ stdio: 'ignore',
739
+ });
740
+ this.log('Cleaned up unused networks, retrying network creation...');
741
+ // Retry network creation after cleanup
742
+ execFileSync(this.dockerPath, ['network', 'create', network, '--label', 'test.cleanup=true'], {
743
+ stdio: 'pipe',
744
+ encoding: 'utf8',
745
+ });
746
+ this.networks.add(network);
747
+ this.log(`Created network after cleanup: ${network}`);
748
+ } catch (_retryError) {
749
+ throw new Error(`Failed to create network ${network} even after cleanup: ${stderr}`, { cause: _retryError });
750
+ }
751
+ } else {
752
+ // Real error - throw it
753
+ throw new Error(`Failed to create network ${network}: ${stderr}`, { cause: error });
754
+ }
755
+ }
756
+ }
757
+ }
758
+
759
+ /**
760
+ * Remove a Docker network
761
+ * @private
762
+ */
763
+ private async removeNetwork(network: string): Promise<void> {
764
+ if (!this.networks.has(network)) {
765
+ return; // Network not tracked by this manager
766
+ }
767
+
768
+ try {
769
+ execFileSync(this.dockerPath, ['network', 'rm', network], {
770
+ stdio: 'ignore',
771
+ });
772
+ this.networks.delete(network);
773
+ this.log(`Removed network: ${network}`);
774
+ } catch (error) {
775
+ // Network might still be in use or already removed
776
+ this.networks.delete(network); // Remove from tracking anyway
777
+ this.logError(`Failed to remove network ${network}`, error);
778
+ }
779
+ }
780
+
781
+ /**
782
+ * Wait for a container to be ready
783
+ * @private
784
+ */
785
+ private async waitForContainer(name: string, options: ContainerOptions['waitFor']): Promise<void> {
786
+ const startTime = Date.now();
787
+ const timeout = options?.timeout || this.startupTimeout;
788
+
789
+ let lastError: Error | undefined;
790
+
791
+ while (Date.now() - startTime < timeout) {
792
+ try {
793
+ // First check if container is still running
794
+ const status = await this.getContainerStatus(name);
795
+ if (!status.isRunning) {
796
+ throw new Error(
797
+ `Container exited with status '${status.state}' and exit code ${status.exitCode}. ` +
798
+ `Check container logs with 'docker logs ${name}'`
799
+ );
800
+ }
801
+
802
+ // Check if container is healthy (if healthcheck is configured)
803
+ if (options?.healthcheck) {
804
+ if (status.health === 'healthy') {
805
+ this.log(`Container ${name} is healthy`);
806
+ return;
807
+ }
808
+
809
+ if (status.health === 'unhealthy') {
810
+ const elapsed = Date.now() - startTime;
811
+ this.logError(
812
+ `Container ${name} health check failed after ${elapsed}ms`,
813
+ new Error(`Health status: ${status.health}, State: ${status.state}`)
814
+ );
815
+ throw new Error(
816
+ `Container ${name} health check failed. ` + `Check container logs with 'docker logs ${name}'`
817
+ );
818
+ }
819
+
820
+ // Health check is still starting
821
+ if (status.health === 'starting') {
822
+ const elapsed = Date.now() - startTime;
823
+ this.log(`Waiting for health check on ${name}...`, {
824
+ elapsed,
825
+ remaining: timeout - elapsed,
826
+ state: status.state,
827
+ });
828
+ }
829
+ }
830
+
831
+ // Check if port is accessible
832
+ if (options?.port) {
833
+ const container = this.containers.get(name);
834
+ if (container) {
835
+ const hostPort = container.ports.get(options.port);
836
+ if (hostPort && (await this.isPortListening('127.0.0.1', hostPort))) {
837
+ this.log(`Port ${hostPort} is listening on ${name}`);
838
+ return;
839
+ }
840
+ }
841
+ }
842
+
843
+ // If no specific wait condition, just check container is running
844
+ if (!options?.healthcheck && !options?.port) {
845
+ this.log(`Container ${name} is running`);
846
+ return;
847
+ }
848
+
849
+ lastError = undefined;
850
+ } catch (error) {
851
+ lastError = error instanceof Error ? error : new Error(String(error));
852
+ this.logError(`Error waiting for container ${name}`, lastError);
853
+
854
+ // Check if this is a fatal error
855
+ if (
856
+ lastError.message.includes('exited') ||
857
+ lastError.message.includes('unhealthy') ||
858
+ lastError.message.includes('health check failed')
859
+ ) {
860
+ throw lastError;
861
+ }
862
+ }
863
+
864
+ await new Promise((resolve) => setTimeout(resolve, 200));
865
+ }
866
+
867
+ const elapsed = Date.now() - startTime;
868
+ const errorMsg = lastError ? `: ${lastError.message}` : '';
869
+ throw new Error(`Container ${name} failed to start within ${timeout}ms (${elapsed}ms elapsed)${errorMsg}`);
870
+ }
871
+
872
+ /**
873
+ * Check if a port is listening
874
+ * @private
875
+ */
876
+ private async isPortListening(host: string, port: number): Promise<boolean> {
877
+ return new Promise((resolve) => {
878
+ const socket = new net.Socket();
879
+
880
+ socket.setTimeout(100);
881
+ socket.on('connect', () => {
882
+ socket.destroy();
883
+ resolve(true);
884
+ });
885
+ socket.on('timeout', () => {
886
+ socket.destroy();
887
+ resolve(false);
888
+ });
889
+ socket.on('error', () => {
890
+ resolve(false);
891
+ });
892
+
893
+ socket.connect(port, host);
894
+ });
895
+ }
896
+
897
+ /**
898
+ * Get a container by ID
899
+ *
900
+ * @param id - Container ID
901
+ * @returns DockerContainer or undefined if not found
902
+ */
903
+ async getContainer(id: string): Promise<DockerContainer | undefined> {
904
+ return this.containers.get(id);
905
+ }
906
+
907
+ /**
908
+ * Clean up a specific container
909
+ *
910
+ * @param id - Container ID to clean up
911
+ */
912
+ async cleanupContainer(id: string): Promise<void> {
913
+ const container = this.containers.get(id);
914
+ if (container) {
915
+ await container.cleanup();
916
+ }
917
+ }
918
+
919
+ /**
920
+ * Clean up all containers managed by this instance
921
+ */
922
+ async cleanupAll(): Promise<void> {
923
+ if (this.cleanupInProgress) {
924
+ this.log('Cleanup already in progress, skipping');
925
+ return;
926
+ }
927
+
928
+ this.cleanupInProgress = true;
929
+
930
+ try {
931
+ this.log(`Starting cleanup of ${this.containers.size} containers`);
932
+
933
+ // Cleanup containers in parallel with Promise.allSettled to handle failures
934
+ const cleanupPromises = Array.from(this.containers.values()).map((container) =>
935
+ container
936
+ .cleanup()
937
+ .then(() => {
938
+ this.log(`Cleanup succeeded: ${container.name}`);
939
+ })
940
+ .catch((error) => {
941
+ this.logError(`Cleanup failed for ${container.name}`, error);
942
+ // Still continue cleaning up other containers
943
+ })
944
+ );
945
+
946
+ const results = await Promise.allSettled(cleanupPromises);
947
+
948
+ const failed = results.filter((r) => r.status === 'rejected').length;
949
+ if (failed > 0) {
950
+ this.log(`Cleanup completed with ${failed} failures`);
951
+ } else {
952
+ this.log('All containers cleaned up successfully');
953
+ }
954
+
955
+ // Cleanup networks
956
+ this.log(`Cleaning up ${this.networks.size} networks`);
957
+ const networkArray = Array.from(this.networks);
958
+ for (const network of networkArray) {
959
+ try {
960
+ this.log(`Removing network: ${network}`);
961
+ execFileSync(this.dockerPath, ['network', 'rm', network], { stdio: 'ignore' });
962
+ this.log(`Network removed: ${network}`);
963
+ } catch (error) {
964
+ this.logError(`Failed to remove network ${network}`, error);
965
+ // Continue with other networks
966
+ }
967
+ }
968
+
969
+ this.containers.clear();
970
+ this.usedPorts.clear();
971
+ this.networks.clear();
972
+
973
+ this.log('Final cleanup completed');
974
+ } finally {
975
+ this.cleanupInProgress = false;
976
+ }
977
+ }
978
+
979
+ /**
980
+ * Async cleanup - for signal handlers
981
+ * @private
982
+ */
983
+ private async cleanupAllAsync(): Promise<void> {
984
+ this.log('Initiating graceful cleanup of all test containers');
985
+ await this.cleanupAll();
986
+ }
987
+
988
+ /**
989
+ * Synchronous cleanup - for process exit
990
+ * @private
991
+ */
992
+ private cleanupSync(): void {
993
+ try {
994
+ this.log('Performing synchronous cleanup of remaining test containers');
995
+
996
+ const isWindows = process.platform === 'win32';
997
+
998
+ if (isWindows) {
999
+ // Windows-specific cleanup
1000
+ this.cleanupSyncWindows();
1001
+ } else {
1002
+ // Unix-like systems
1003
+ this.cleanupSyncUnix();
1004
+ }
1005
+
1006
+ this.log('Synchronous cleanup completed');
1007
+ } catch (error) {
1008
+ this.logError('Error during synchronous cleanup', error);
1009
+ // Don't throw during process exit cleanup
1010
+ }
1011
+ }
1012
+
1013
+ /**
1014
+ * Windows-specific synchronous cleanup
1015
+ * @private
1016
+ */
1017
+ private cleanupSyncWindows(): void {
1018
+ try {
1019
+ // Get container IDs with test.cleanup label
1020
+ const containerIds = execFileSync(this.dockerPath, ['ps', '-a', '--filter', 'label=test.cleanup=true', '-q'], {
1021
+ encoding: 'utf8',
1022
+ stdio: ['pipe', 'pipe', 'ignore'],
1023
+ }).trim();
1024
+
1025
+ if (containerIds) {
1026
+ const ids = containerIds.split('\n').filter((id) => id.trim());
1027
+ this.log(`Found ${ids.length} test containers to clean up`);
1028
+
1029
+ for (const id of ids) {
1030
+ try {
1031
+ const trimmedId = id.trim();
1032
+ this.log(`Stopping container: ${trimmedId}`);
1033
+ try {
1034
+ execFileSync(this.dockerPath, ['stop', '-t', '5', trimmedId], { stdio: 'ignore' });
1035
+ } catch {
1036
+ // Already stopped
1037
+ }
1038
+
1039
+ this.log(`Removing container: ${trimmedId}`);
1040
+ execFileSync(this.dockerPath, ['rm', '-f', trimmedId], { stdio: 'ignore' });
1041
+ this.log(`Container removed: ${trimmedId}`);
1042
+ } catch (error) {
1043
+ this.logError(`Failed to cleanup container ${id}`, error);
1044
+ // Continue with other containers
1045
+ }
1046
+ }
1047
+ }
1048
+
1049
+ // Remove test networks
1050
+ try {
1051
+ const networkIds = execFileSync(
1052
+ this.dockerPath,
1053
+ ['network', 'ls', '--filter', 'label=test.cleanup=true', '-q'],
1054
+ {
1055
+ encoding: 'utf8',
1056
+ stdio: ['pipe', 'pipe', 'ignore'],
1057
+ }
1058
+ ).trim();
1059
+
1060
+ if (networkIds) {
1061
+ const ids = networkIds.split('\n').filter((id) => id.trim());
1062
+ this.log(`Found ${ids.length} test networks to clean up`);
1063
+
1064
+ for (const id of ids) {
1065
+ try {
1066
+ this.log(`Removing network: ${id.trim()}`);
1067
+ execFileSync(this.dockerPath, ['network', 'rm', id.trim()], { stdio: 'ignore' });
1068
+ this.log(`Network removed: ${id.trim()}`);
1069
+ } catch (error) {
1070
+ this.logError(`Failed to cleanup network ${id}`, error);
1071
+ }
1072
+ }
1073
+ }
1074
+ } catch (error) {
1075
+ this.logError('Failed to cleanup networks', error);
1076
+ }
1077
+ } catch (error) {
1078
+ this.logError('Windows cleanup failed', error);
1079
+ }
1080
+ }
1081
+
1082
+ /**
1083
+ * Unix-specific synchronous cleanup
1084
+ * @private
1085
+ */
1086
+ private cleanupSyncUnix(): void {
1087
+ try {
1088
+ // Remove containers
1089
+ const containerCmd = `"${this.dockerPath}" ps -a --filter "label=test.cleanup=true" -q`;
1090
+ try {
1091
+ const ids = execSync(containerCmd, { encoding: 'utf8', stdio: ['pipe', 'pipe', 'ignore'] }).trim();
1092
+ if (ids) {
1093
+ const containerIds = ids.split('\n').filter((id) => id.trim());
1094
+ this.log(`Found ${containerIds.length} test containers to clean up`);
1095
+
1096
+ for (const id of containerIds) {
1097
+ try {
1098
+ const trimmedId = id.trim();
1099
+ this.log(`Stopping container: ${trimmedId}`);
1100
+ try {
1101
+ execFileSync(this.dockerPath, ['stop', '-t', '5', trimmedId], { stdio: 'ignore' });
1102
+ } catch {
1103
+ // Already stopped
1104
+ }
1105
+
1106
+ this.log(`Removing container: ${trimmedId}`);
1107
+ execFileSync(this.dockerPath, ['rm', '-f', trimmedId], { stdio: 'ignore' });
1108
+ this.log(`Container removed: ${trimmedId}`);
1109
+ } catch (error) {
1110
+ this.logError(`Failed to cleanup container ${id}`, error);
1111
+ }
1112
+ }
1113
+ }
1114
+ } catch (error) {
1115
+ this.logError('Failed to cleanup containers', error);
1116
+ }
1117
+
1118
+ // Remove test networks
1119
+ try {
1120
+ const networkCmd = `"${this.dockerPath}" network ls --filter "label=test.cleanup=true" -q`;
1121
+ const ids = execSync(networkCmd, { encoding: 'utf8', stdio: ['pipe', 'pipe', 'ignore'] }).trim();
1122
+ if (ids) {
1123
+ const networkIds = ids.split('\n').filter((id) => id.trim());
1124
+ this.log(`Found ${networkIds.length} test networks to clean up`);
1125
+
1126
+ for (const id of networkIds) {
1127
+ try {
1128
+ this.log(`Removing network: ${id.trim()}`);
1129
+ execFileSync(this.dockerPath, ['network', 'rm', id.trim()], { stdio: 'ignore' });
1130
+ this.log(`Network removed: ${id.trim()}`);
1131
+ } catch (error) {
1132
+ this.logError(`Failed to cleanup network ${id}`, error);
1133
+ }
1134
+ }
1135
+ }
1136
+ } catch (error) {
1137
+ this.logError('Failed to cleanup networks', error);
1138
+ }
1139
+
1140
+ // Remove test volumes
1141
+ try {
1142
+ const volumeCmd = `"${this.dockerPath}" volume ls --filter "label=test.cleanup=true" -q`;
1143
+ const ids = execSync(volumeCmd, { encoding: 'utf8', stdio: ['pipe', 'pipe', 'ignore'] }).trim();
1144
+ if (ids) {
1145
+ const volumeIds = ids.split('\n').filter((id) => id.trim());
1146
+ this.log(`Found ${volumeIds.length} test volumes to clean up`);
1147
+
1148
+ for (const id of volumeIds) {
1149
+ try {
1150
+ this.log(`Removing volume: ${id.trim()}`);
1151
+ execFileSync(this.dockerPath, ['volume', 'rm', '-f', id.trim()], { stdio: 'ignore' });
1152
+ this.log(`Volume removed: ${id.trim()}`);
1153
+ } catch (error) {
1154
+ this.logError(`Failed to cleanup volume ${id}`, error);
1155
+ }
1156
+ }
1157
+ }
1158
+ } catch (error) {
1159
+ this.logError('Failed to cleanup volumes', error);
1160
+ }
1161
+ } catch (error) {
1162
+ this.logError('Unix cleanup failed', error);
1163
+ }
1164
+ }
1165
+
1166
+ /**
1167
+ * Helper to run tests with a container
1168
+ *
1169
+ * @param options - Container configuration
1170
+ * @param testFn - Test function that receives the container
1171
+ * @returns Promise resolving to test function result
1172
+ *
1173
+ * @example
1174
+ * ```typescript
1175
+ * await DockerTestManager.withContainer(
1176
+ * { image: 'redis:7-alpine', ports: { 6379: 'auto' } },
1177
+ * async (container) => {
1178
+ * // Use container in tests
1179
+ * const port = container.port!;
1180
+ * // ...
1181
+ * }
1182
+ * );
1183
+ * ```
1184
+ */
1185
+ static async withContainer<T>(
1186
+ options: ContainerOptions,
1187
+ testFn: (container: DockerContainer) => Promise<T>
1188
+ ): Promise<T> {
1189
+ const manager = DockerTestManager.getInstance();
1190
+ const container = await manager.createContainer(options);
1191
+
1192
+ try {
1193
+ return await testFn(container);
1194
+ } finally {
1195
+ await container.cleanup();
1196
+ }
1197
+ }
1198
+ }