@omnitron-dev/testing 0.4.0 → 0.4.2

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 (89) hide show
  1. package/dist/async/deferred.d.ts +15 -0
  2. package/dist/async/deferred.js +35 -0
  3. package/dist/async/deferred.js.map +1 -0
  4. package/dist/async/events.d.ts +32 -0
  5. package/dist/async/events.js +176 -0
  6. package/dist/async/events.js.map +1 -0
  7. package/dist/async/index.d.ts +5 -0
  8. package/dist/async/index.js +6 -0
  9. package/dist/async/index.js.map +1 -0
  10. package/dist/async/mock-timer.d.ts +19 -0
  11. package/dist/async/mock-timer.js +87 -0
  12. package/dist/async/mock-timer.js.map +1 -0
  13. package/dist/async/retry.d.ts +8 -0
  14. package/dist/async/retry.js +36 -0
  15. package/dist/async/retry.js.map +1 -0
  16. package/dist/async/wait.d.ts +10 -0
  17. package/dist/async/wait.js +35 -0
  18. package/dist/async/wait.js.map +1 -0
  19. package/dist/docker/database-manager.d.ts +22 -0
  20. package/dist/docker/database-manager.js +97 -0
  21. package/dist/docker/database-manager.js.map +1 -0
  22. package/dist/docker/docker-test-manager.d.ts +44 -0
  23. package/dist/docker/docker-test-manager.js +805 -0
  24. package/dist/docker/docker-test-manager.js.map +1 -0
  25. package/dist/docker/index.d.ts +4 -0
  26. package/dist/docker/index.js +4 -0
  27. package/dist/docker/index.js.map +1 -0
  28. package/dist/docker/redis-manager.d.ts +12 -0
  29. package/dist/docker/redis-manager.js +453 -0
  30. package/dist/docker/redis-manager.js.map +1 -0
  31. package/dist/docker/types.d.ts +103 -0
  32. package/dist/docker/types.js +2 -0
  33. package/dist/docker/types.js.map +1 -0
  34. package/dist/errors.d.ts +15 -0
  35. package/dist/errors.js +28 -0
  36. package/dist/errors.js.map +1 -0
  37. package/dist/helpers/assertions.d.ts +6 -0
  38. package/dist/helpers/assertions.js +37 -0
  39. package/dist/helpers/assertions.js.map +1 -0
  40. package/dist/helpers/console.d.ts +1 -0
  41. package/dist/helpers/console.js +23 -0
  42. package/dist/helpers/console.js.map +1 -0
  43. package/dist/helpers/index.d.ts +3 -0
  44. package/dist/helpers/index.js +4 -0
  45. package/dist/helpers/index.js.map +1 -0
  46. package/dist/helpers/temp-dir.d.ts +2 -0
  47. package/dist/helpers/temp-dir.js +13 -0
  48. package/dist/helpers/temp-dir.js.map +1 -0
  49. package/dist/index.d.ts +2 -0
  50. package/dist/index.js +2 -0
  51. package/dist/index.js.map +1 -1
  52. package/dist/performance/index.d.ts +2 -0
  53. package/dist/performance/index.js +3 -0
  54. package/dist/performance/index.js.map +1 -0
  55. package/dist/performance/memory-detector.d.ts +9 -0
  56. package/dist/performance/memory-detector.js +61 -0
  57. package/dist/performance/memory-detector.js.map +1 -0
  58. package/dist/performance/perf-timer.d.ts +9 -0
  59. package/dist/performance/perf-timer.js +49 -0
  60. package/dist/performance/perf-timer.js.map +1 -0
  61. package/package.json +28 -2
  62. package/src/async/README.md +336 -0
  63. package/src/async/deferred.ts +98 -0
  64. package/src/async/events.ts +386 -0
  65. package/src/async/index.ts +48 -0
  66. package/src/async/mock-timer.ts +220 -0
  67. package/src/async/retry.ts +118 -0
  68. package/src/async/wait.ts +151 -0
  69. package/src/docker/database-manager.ts +242 -0
  70. package/src/docker/docker-test-manager.ts +1186 -0
  71. package/src/docker/index.ts +48 -0
  72. package/src/docker/redis-manager.ts +738 -0
  73. package/src/docker/types.ts +216 -0
  74. package/src/errors.ts +31 -0
  75. package/src/helpers/assertions.ts +171 -0
  76. package/src/helpers/console.ts +74 -0
  77. package/src/helpers/index.ts +15 -0
  78. package/src/helpers/temp-dir.ts +50 -0
  79. package/src/index.ts +2 -0
  80. package/src/performance/index.ts +11 -0
  81. package/src/performance/memory-detector.ts +166 -0
  82. package/src/performance/perf-timer.ts +146 -0
  83. package/src/titan/container-utils.ts +128 -0
  84. package/src/titan/index.ts +59 -0
  85. package/src/titan/redis-test-utils.ts +566 -0
  86. package/src/titan/test-application.ts +154 -0
  87. package/src/titan/test-fixtures.ts +304 -0
  88. package/src/titan/test-mocks.ts +336 -0
  89. package/src/titan/test-module.ts +231 -0
@@ -0,0 +1,805 @@
1
+ import { execSync, execFileSync } from 'child_process';
2
+ import { randomBytes } from 'crypto';
3
+ import * as net from 'net';
4
+ import { EventEmitter } from 'events';
5
+ export class DockerTestManager extends EventEmitter {
6
+ constructor(options = {}) {
7
+ super();
8
+ this.containers = new Map();
9
+ this.usedPorts = new Set();
10
+ this.networks = new Set();
11
+ this.cleanupInProgress = false;
12
+ this.dockerPath = options.dockerPath || this.findDockerPath();
13
+ const workerId = parseInt(process.env['JEST_WORKER_ID'] || '1', 10);
14
+ const basePortOffset = (workerId - 1) * 10000;
15
+ this.basePort = options.basePort || (10000 + basePortOffset);
16
+ this.maxRetries = options.maxRetries || 20;
17
+ this.startupTimeout = options.startupTimeout || 30000;
18
+ this.gracefulShutdownTimeout = options.gracefulShutdownTimeout || 10000;
19
+ this.maxCleanupRetries = options.maxCleanupRetries || 3;
20
+ this.cleanup = options.cleanup !== false;
21
+ this.verbose = options.verbose || false;
22
+ this.defaultNetwork = options.network;
23
+ if (this.verbose) {
24
+ this.log(`Initialized for Jest worker ${workerId} with port range ${this.basePort}-${this.basePort + 10000}`);
25
+ }
26
+ this.verifyDocker();
27
+ if (this.cleanup) {
28
+ process.setMaxListeners(Math.max(20, process.getMaxListeners()));
29
+ process.on('exit', () => this.cleanupSync());
30
+ process.on('SIGINT', () => {
31
+ this.log('SIGINT received - initiating graceful shutdown');
32
+ this.cleanupAllAsync()
33
+ .then(() => {
34
+ this.log('Cleanup completed, exiting');
35
+ process.exit(0);
36
+ })
37
+ .catch((error) => {
38
+ this.logError('Cleanup failed during SIGINT', error);
39
+ process.exit(1);
40
+ });
41
+ });
42
+ process.on('SIGTERM', () => {
43
+ this.log('SIGTERM received - initiating graceful shutdown');
44
+ this.cleanupAllAsync()
45
+ .then(() => {
46
+ this.log('Cleanup completed, exiting');
47
+ process.exit(0);
48
+ })
49
+ .catch((error) => {
50
+ this.logError('Cleanup failed during SIGTERM', error);
51
+ process.exit(1);
52
+ });
53
+ });
54
+ }
55
+ }
56
+ static getInstance(options) {
57
+ if (!DockerTestManager.instance) {
58
+ DockerTestManager.instance = new DockerTestManager(options);
59
+ }
60
+ return DockerTestManager.instance;
61
+ }
62
+ findDockerPath() {
63
+ const isWindows = process.platform === 'win32';
64
+ const whichCommand = isWindows ? 'where' : 'which';
65
+ const dockerBinary = isWindows ? 'docker.exe' : 'docker';
66
+ try {
67
+ const result = execSync(`${whichCommand} ${dockerBinary}`, {
68
+ encoding: 'utf8',
69
+ stdio: ['pipe', 'pipe', 'ignore'],
70
+ }).trim();
71
+ const dockerPath = result.split('\n')[0]?.trim();
72
+ if (dockerPath && this.testDockerPath(dockerPath)) {
73
+ if (this.verbose) {
74
+ console.log(`Found Docker in PATH: ${dockerPath}`);
75
+ }
76
+ return dockerPath;
77
+ }
78
+ }
79
+ catch {
80
+ }
81
+ const fallbackPaths = this.getDockerFallbackPaths();
82
+ for (const path of fallbackPaths) {
83
+ if (this.testDockerPath(path)) {
84
+ if (this.verbose) {
85
+ console.log(`Found Docker at fallback path: ${path}`);
86
+ }
87
+ return path;
88
+ }
89
+ }
90
+ if (this.testDockerPath(dockerBinary)) {
91
+ if (this.verbose) {
92
+ console.log(`Using Docker from PATH: ${dockerBinary}`);
93
+ }
94
+ return dockerBinary;
95
+ }
96
+ throw new Error(`Docker executable not found. Please install Docker and ensure it's in your PATH.\n` +
97
+ `Searched paths:\n` +
98
+ ` - PATH using '${whichCommand} ${dockerBinary}'\n` +
99
+ ` - ${fallbackPaths.join('\n - ')}\n` +
100
+ `\n` +
101
+ `Platform: ${process.platform}\n` +
102
+ `For more information, visit: https://docs.docker.com/get-docker/`);
103
+ }
104
+ getDockerFallbackPaths() {
105
+ switch (process.platform) {
106
+ case 'darwin':
107
+ return [
108
+ '/usr/local/bin/docker',
109
+ '/opt/homebrew/bin/docker',
110
+ '/Applications/Docker.app/Contents/Resources/bin/docker',
111
+ ];
112
+ case 'linux':
113
+ return [
114
+ '/usr/bin/docker',
115
+ '/usr/local/bin/docker',
116
+ '/snap/bin/docker',
117
+ '/var/lib/snapd/snap/bin/docker',
118
+ '/opt/docker/bin/docker',
119
+ ];
120
+ case 'win32':
121
+ return [
122
+ 'docker.exe',
123
+ 'C:\\Program Files\\Docker\\Docker\\resources\\bin\\docker.exe',
124
+ 'C:\\ProgramData\\DockerDesktop\\version-bin\\docker.exe',
125
+ ];
126
+ default:
127
+ return ['/usr/local/bin/docker', '/usr/bin/docker', 'docker'];
128
+ }
129
+ }
130
+ testDockerPath(dockerPath) {
131
+ try {
132
+ execFileSync(dockerPath, ['version'], {
133
+ stdio: 'ignore',
134
+ timeout: 5000,
135
+ });
136
+ return true;
137
+ }
138
+ catch {
139
+ return false;
140
+ }
141
+ }
142
+ verifyDocker() {
143
+ try {
144
+ execFileSync(this.dockerPath, ['version'], { stdio: 'ignore' });
145
+ }
146
+ catch {
147
+ throw new Error(`Docker is not available at path: ${this.dockerPath}\n` +
148
+ `Please install Docker or verify it's properly configured.\n` +
149
+ `Visit: https://docs.docker.com/get-docker/`);
150
+ }
151
+ }
152
+ async findAvailablePort() {
153
+ for (let i = 0; i < this.maxRetries; i++) {
154
+ const port = this.basePort + Math.floor(Math.random() * 10000);
155
+ if (!this.usedPorts.has(port) && (await this.isPortAvailable(port))) {
156
+ this.usedPorts.add(port);
157
+ return port;
158
+ }
159
+ }
160
+ throw new Error('Could not find available port for container');
161
+ }
162
+ async isPortAvailable(port) {
163
+ return new Promise((resolve) => {
164
+ const server = net.createServer();
165
+ server.once('error', () => resolve(false));
166
+ server.once('listening', () => {
167
+ server.close();
168
+ resolve(true);
169
+ });
170
+ server.listen(port, '127.0.0.1');
171
+ });
172
+ }
173
+ log(message, data) {
174
+ if (this.verbose) {
175
+ const timestamp = new Date().toISOString();
176
+ const msg = data ? `[${timestamp}] ${message}: ${JSON.stringify(data)}` : `[${timestamp}] ${message}`;
177
+ console.log(msg);
178
+ }
179
+ }
180
+ logError(message, error) {
181
+ const timestamp = new Date().toISOString();
182
+ const err = error instanceof Error ? error.message : String(error);
183
+ const msg = `[${timestamp}] ERROR: ${message}: ${err}`;
184
+ if (this.verbose) {
185
+ console.error(msg);
186
+ }
187
+ }
188
+ async getContainerStatus(name) {
189
+ try {
190
+ const inspectOutput = execFileSync(this.dockerPath, [
191
+ 'inspect',
192
+ '--format',
193
+ '{{.State.Running}}\t{{.State.Status}}\t{{.State.Health.Status}}\t{{.State.ExitCode}}',
194
+ name,
195
+ ], {
196
+ encoding: 'utf8',
197
+ stdio: ['pipe', 'pipe', 'ignore'],
198
+ }).trim();
199
+ const [running, state, health, exitCode] = inspectOutput.split('\t');
200
+ return {
201
+ isRunning: running === 'true',
202
+ state: state || undefined,
203
+ health: health && health !== '<no value>' ? health : undefined,
204
+ exitCode: exitCode ? parseInt(exitCode) : undefined,
205
+ };
206
+ }
207
+ catch (error) {
208
+ this.logError(`Failed to get container status for ${name}`, error);
209
+ return { isRunning: false };
210
+ }
211
+ }
212
+ async isContainerHealthy(name) {
213
+ try {
214
+ const status = await this.getContainerStatus(name);
215
+ if (!status.isRunning) {
216
+ return false;
217
+ }
218
+ if (status.health) {
219
+ return status.health === 'healthy';
220
+ }
221
+ return true;
222
+ }
223
+ catch {
224
+ return false;
225
+ }
226
+ }
227
+ async createContainer(options) {
228
+ const id = `test-${randomBytes(8).toString('hex')}`;
229
+ const name = options.name || `container-${id}`;
230
+ const host = '127.0.0.1';
231
+ try {
232
+ execFileSync(this.dockerPath, ['rm', '-f', name], { stdio: 'ignore' });
233
+ this.log(`Removed existing container: ${name}`);
234
+ }
235
+ catch {
236
+ }
237
+ const portMappings = new Map();
238
+ if (options.ports) {
239
+ for (const [containerPort, hostPort] of Object.entries(options.ports)) {
240
+ const cPort = parseInt(containerPort);
241
+ const hPort = hostPort === 'auto' ? await this.findAvailablePort() : hostPort;
242
+ portMappings.set(cPort, hPort);
243
+ }
244
+ }
245
+ const dockerArgs = ['run', '-d', '--name', name];
246
+ portMappings.forEach((hostPort, containerPort) => {
247
+ dockerArgs.push('-p', `${hostPort}:${containerPort}`);
248
+ });
249
+ const environment = options.environment || {};
250
+ for (const [key, value] of Object.entries(environment)) {
251
+ dockerArgs.push('-e', `${key}=${value}`);
252
+ }
253
+ const labels = {
254
+ 'test.id': id,
255
+ 'test.cleanup': 'true',
256
+ ...options.labels,
257
+ };
258
+ for (const [key, value] of Object.entries(labels)) {
259
+ dockerArgs.push('--label', `${key}=${value}`);
260
+ }
261
+ if (options.volumes) {
262
+ for (const volume of options.volumes) {
263
+ dockerArgs.push('-v', volume);
264
+ }
265
+ }
266
+ const networks = options.networks || (this.defaultNetwork ? [this.defaultNetwork] : []);
267
+ for (const network of networks) {
268
+ await this.ensureNetwork(network);
269
+ dockerArgs.push('--network', network);
270
+ }
271
+ if (options.healthcheck) {
272
+ let healthCmd;
273
+ if (Array.isArray(options.healthcheck.test)) {
274
+ if (options.healthcheck.test[0] === 'CMD-SHELL') {
275
+ healthCmd = options.healthcheck.test.slice(1).join(' ');
276
+ }
277
+ else if (options.healthcheck.test[0] === 'CMD') {
278
+ healthCmd = options.healthcheck.test.slice(1).join(' ');
279
+ }
280
+ else {
281
+ healthCmd = options.healthcheck.test.join(' ');
282
+ }
283
+ }
284
+ else {
285
+ healthCmd = options.healthcheck.test;
286
+ }
287
+ dockerArgs.push('--health-cmd', healthCmd);
288
+ if (options.healthcheck.interval) {
289
+ dockerArgs.push('--health-interval', options.healthcheck.interval);
290
+ }
291
+ if (options.healthcheck.timeout) {
292
+ dockerArgs.push('--health-timeout', options.healthcheck.timeout);
293
+ }
294
+ if (options.healthcheck.retries) {
295
+ dockerArgs.push('--health-retries', options.healthcheck.retries.toString());
296
+ }
297
+ if (options.healthcheck.startPeriod) {
298
+ dockerArgs.push('--health-start-period', options.healthcheck.startPeriod);
299
+ }
300
+ }
301
+ dockerArgs.push(options.image);
302
+ if (options.command) {
303
+ dockerArgs.push('sh', '-c', options.command);
304
+ }
305
+ if (this.verbose) {
306
+ console.log(`Starting container ${name}: docker ${dockerArgs.join(' ')}`);
307
+ }
308
+ try {
309
+ this.log(`Starting container: ${name}`, { image: options.image });
310
+ const result = execFileSync(this.dockerPath, dockerArgs, {
311
+ encoding: 'utf8',
312
+ stdio: ['pipe', 'pipe', 'pipe'],
313
+ });
314
+ if (this.verbose && result) {
315
+ console.log(result);
316
+ }
317
+ }
318
+ catch (error) {
319
+ portMappings.forEach((port) => {
320
+ this.usedPorts.delete(port);
321
+ });
322
+ const execError = error;
323
+ const stderr = execError.stderr ? String(execError.stderr).trim() : '';
324
+ const stdout = execError.stdout ? String(execError.stdout).trim() : '';
325
+ const message = execError.message || String(error);
326
+ if (stderr.includes('already in use') || stderr.includes('name is already') || stderr.includes('Conflict')) {
327
+ throw new Error(`Container name conflict: ${name} already exists.\n` +
328
+ `Please ensure previous test containers are cleaned up.\n` +
329
+ `Stderr: ${stderr}`);
330
+ }
331
+ throw new Error(`Failed to start container ${name}:\n` +
332
+ `Command: docker ${dockerArgs.join(' ')}\n` +
333
+ `Exit code: ${execError.status || 'unknown'}\n` +
334
+ (stderr ? `Stderr: ${stderr}\n` : '') +
335
+ (stdout ? `Stdout: ${stdout}\n` : '') +
336
+ (message && !stderr && !stdout ? `Error: ${message}` : ''));
337
+ }
338
+ if (options.waitFor) {
339
+ try {
340
+ await this.waitForContainer(name, options.waitFor);
341
+ this.log(`Container ready: ${name}`);
342
+ }
343
+ catch (error) {
344
+ this.logError(`Container ${name} failed to become ready, cleaning up`, error);
345
+ try {
346
+ execFileSync(this.dockerPath, ['stop', '-t', '5', name], { stdio: 'ignore' });
347
+ execFileSync(this.dockerPath, ['rm', '-f', name], { stdio: 'ignore' });
348
+ }
349
+ catch {
350
+ }
351
+ portMappings.forEach((port) => {
352
+ this.usedPorts.delete(port);
353
+ });
354
+ throw error;
355
+ }
356
+ }
357
+ let internalIp;
358
+ if (networks.length > 0) {
359
+ try {
360
+ const ipOutput = execFileSync(this.dockerPath, ['inspect', name, '--format', '{{range .NetworkSettings.Networks}}{{.IPAddress}}{{end}}'], {
361
+ encoding: 'utf8',
362
+ stdio: ['pipe', 'pipe', 'ignore'],
363
+ }).trim();
364
+ if (ipOutput) {
365
+ internalIp = ipOutput;
366
+ this.log(`Container ${name} internal IP: ${internalIp}`);
367
+ }
368
+ }
369
+ catch (error) {
370
+ this.logError(`Failed to get internal IP for ${name}`, error);
371
+ }
372
+ }
373
+ const container = {
374
+ id,
375
+ name,
376
+ image: options.image,
377
+ host,
378
+ port: portMappings.values().next().value,
379
+ ports: portMappings,
380
+ environment,
381
+ labels,
382
+ networks,
383
+ createdAt: new Date(),
384
+ internalIp,
385
+ getStatus: async () => this.getContainerStatus(name),
386
+ isHealthy: async () => this.isContainerHealthy(name),
387
+ cleanup: async () => {
388
+ await this.cleanupContainerWithRetry(name, id, portMappings);
389
+ },
390
+ };
391
+ this.containers.set(id, container);
392
+ return container;
393
+ }
394
+ async cleanupContainerWithRetry(name, id, portMappings) {
395
+ this.log(`Starting cleanup for container: ${name}`);
396
+ let lastError = null;
397
+ for (let attempt = 1; attempt <= this.maxCleanupRetries; attempt++) {
398
+ try {
399
+ try {
400
+ const status = await this.getContainerStatus(name);
401
+ if (!status.isRunning) {
402
+ this.log(`Container ${name} is not running, force removing`, { attempt });
403
+ }
404
+ }
405
+ catch {
406
+ this.log(`Container ${name} doesn't exist, skipping stop`, { attempt });
407
+ break;
408
+ }
409
+ try {
410
+ const stopTimeoutSecs = Math.ceil(this.gracefulShutdownTimeout / 1000).toString();
411
+ this.log(`Stopping container ${name}`, { attempt, timeout: this.gracefulShutdownTimeout });
412
+ execFileSync(this.dockerPath, ['stop', '-t', stopTimeoutSecs, name], {
413
+ stdio: 'ignore',
414
+ timeout: this.gracefulShutdownTimeout + 5000,
415
+ });
416
+ this.log(`Container stopped: ${name}`, { attempt });
417
+ }
418
+ catch (error) {
419
+ this.logError(`Failed to gracefully stop container ${name}`, error);
420
+ }
421
+ try {
422
+ this.log(`Removing container ${name}`, { attempt });
423
+ execFileSync(this.dockerPath, ['rm', '-f', name], { stdio: 'ignore' });
424
+ this.log(`Container removed: ${name}`, { attempt });
425
+ lastError = null;
426
+ break;
427
+ }
428
+ catch (error) {
429
+ lastError = error instanceof Error ? error : new Error(String(error));
430
+ if (attempt === this.maxCleanupRetries) {
431
+ throw lastError;
432
+ }
433
+ await new Promise((resolve) => setTimeout(resolve, 1000 * attempt));
434
+ }
435
+ }
436
+ catch (error) {
437
+ lastError = error instanceof Error ? error : new Error(String(error));
438
+ if (attempt === this.maxCleanupRetries) {
439
+ this.logError(`Final cleanup attempt failed for container ${name}`, lastError);
440
+ }
441
+ else {
442
+ this.logError(`Cleanup attempt ${attempt} failed for container ${name}, retrying`, lastError);
443
+ await new Promise((resolve) => setTimeout(resolve, 1000 * attempt));
444
+ }
445
+ }
446
+ }
447
+ try {
448
+ portMappings.forEach((port) => {
449
+ this.usedPorts.delete(port);
450
+ this.log(`Released port: ${port}`);
451
+ });
452
+ }
453
+ catch (error) {
454
+ this.logError('Failed to release ports', error);
455
+ }
456
+ this.containers.delete(id);
457
+ this.log(`Container cleanup completed: ${name}`, { attempts: this.maxCleanupRetries });
458
+ }
459
+ async ensureNetwork(network) {
460
+ if (!this.networks.has(network)) {
461
+ try {
462
+ execFileSync(this.dockerPath, ['network', 'create', network, '--label', 'test.cleanup=true'], {
463
+ stdio: 'pipe',
464
+ encoding: 'utf8',
465
+ });
466
+ this.networks.add(network);
467
+ this.log(`Created network: ${network}`);
468
+ }
469
+ catch (error) {
470
+ const execError = error;
471
+ const stderr = execError.stderr || execError.message || String(error);
472
+ if (stderr.includes('already exists') || stderr.includes('network with name')) {
473
+ this.log(`Network already exists: ${network}`);
474
+ this.networks.add(network);
475
+ }
476
+ else if (stderr.includes('all predefined address pools have been fully subnetted')) {
477
+ this.log('Docker network pool exhausted, attempting cleanup...');
478
+ try {
479
+ execFileSync(this.dockerPath, ['network', 'prune', '-f'], {
480
+ stdio: 'ignore',
481
+ });
482
+ this.log('Cleaned up unused networks, retrying network creation...');
483
+ execFileSync(this.dockerPath, ['network', 'create', network, '--label', 'test.cleanup=true'], {
484
+ stdio: 'pipe',
485
+ encoding: 'utf8',
486
+ });
487
+ this.networks.add(network);
488
+ this.log(`Created network after cleanup: ${network}`);
489
+ }
490
+ catch (retryError) {
491
+ throw new Error(`Failed to create network ${network} even after cleanup: ${stderr}`);
492
+ }
493
+ }
494
+ else {
495
+ throw new Error(`Failed to create network ${network}: ${stderr}`);
496
+ }
497
+ }
498
+ }
499
+ }
500
+ async removeNetwork(network) {
501
+ if (!this.networks.has(network)) {
502
+ return;
503
+ }
504
+ try {
505
+ execFileSync(this.dockerPath, ['network', 'rm', network], {
506
+ stdio: 'ignore',
507
+ });
508
+ this.networks.delete(network);
509
+ this.log(`Removed network: ${network}`);
510
+ }
511
+ catch (error) {
512
+ this.networks.delete(network);
513
+ this.logError(`Failed to remove network ${network}`, error);
514
+ }
515
+ }
516
+ async waitForContainer(name, options) {
517
+ const startTime = Date.now();
518
+ const timeout = options?.timeout || this.startupTimeout;
519
+ let lastError;
520
+ while (Date.now() - startTime < timeout) {
521
+ try {
522
+ const status = await this.getContainerStatus(name);
523
+ if (!status.isRunning) {
524
+ throw new Error(`Container exited with status '${status.state}' and exit code ${status.exitCode}. ` +
525
+ `Check container logs with 'docker logs ${name}'`);
526
+ }
527
+ if (options?.healthcheck) {
528
+ if (status.health === 'healthy') {
529
+ this.log(`Container ${name} is healthy`);
530
+ return;
531
+ }
532
+ if (status.health === 'unhealthy') {
533
+ throw new Error(`Container ${name} health check failed. ` + `Check container logs with 'docker logs ${name}'`);
534
+ }
535
+ if (status.health === 'starting') {
536
+ this.log(`Waiting for health check on ${name}...`, { elapsed: Date.now() - startTime });
537
+ }
538
+ }
539
+ if (options?.port) {
540
+ const container = this.containers.get(name);
541
+ if (container) {
542
+ const hostPort = container.ports.get(options.port);
543
+ if (hostPort && (await this.isPortListening('127.0.0.1', hostPort))) {
544
+ this.log(`Port ${hostPort} is listening on ${name}`);
545
+ return;
546
+ }
547
+ }
548
+ }
549
+ if (!options?.healthcheck && !options?.port) {
550
+ this.log(`Container ${name} is running`);
551
+ return;
552
+ }
553
+ lastError = undefined;
554
+ }
555
+ catch (error) {
556
+ lastError = error instanceof Error ? error : new Error(String(error));
557
+ this.logError(`Error waiting for container ${name}`, lastError);
558
+ if (lastError.message.includes('exited') ||
559
+ lastError.message.includes('unhealthy') ||
560
+ lastError.message.includes('health check failed')) {
561
+ throw lastError;
562
+ }
563
+ }
564
+ await new Promise((resolve) => setTimeout(resolve, 200));
565
+ }
566
+ const elapsed = Date.now() - startTime;
567
+ const errorMsg = lastError ? `: ${lastError.message}` : '';
568
+ throw new Error(`Container ${name} failed to start within ${timeout}ms (${elapsed}ms elapsed)${errorMsg}`);
569
+ }
570
+ async isPortListening(host, port) {
571
+ return new Promise((resolve) => {
572
+ const socket = new net.Socket();
573
+ socket.setTimeout(100);
574
+ socket.on('connect', () => {
575
+ socket.destroy();
576
+ resolve(true);
577
+ });
578
+ socket.on('timeout', () => {
579
+ socket.destroy();
580
+ resolve(false);
581
+ });
582
+ socket.on('error', () => {
583
+ resolve(false);
584
+ });
585
+ socket.connect(port, host);
586
+ });
587
+ }
588
+ async getContainer(id) {
589
+ return this.containers.get(id);
590
+ }
591
+ async cleanupContainer(id) {
592
+ const container = this.containers.get(id);
593
+ if (container) {
594
+ await container.cleanup();
595
+ }
596
+ }
597
+ async cleanupAll() {
598
+ if (this.cleanupInProgress) {
599
+ this.log('Cleanup already in progress, skipping');
600
+ return;
601
+ }
602
+ this.cleanupInProgress = true;
603
+ try {
604
+ this.log(`Starting cleanup of ${this.containers.size} containers`);
605
+ const cleanupPromises = Array.from(this.containers.values()).map((container) => container
606
+ .cleanup()
607
+ .then(() => {
608
+ this.log(`Cleanup succeeded: ${container.name}`);
609
+ })
610
+ .catch((error) => {
611
+ this.logError(`Cleanup failed for ${container.name}`, error);
612
+ }));
613
+ const results = await Promise.allSettled(cleanupPromises);
614
+ const failed = results.filter((r) => r.status === 'rejected').length;
615
+ if (failed > 0) {
616
+ this.log(`Cleanup completed with ${failed} failures`);
617
+ }
618
+ else {
619
+ this.log('All containers cleaned up successfully');
620
+ }
621
+ this.log(`Cleaning up ${this.networks.size} networks`);
622
+ const networkArray = Array.from(this.networks);
623
+ for (const network of networkArray) {
624
+ try {
625
+ this.log(`Removing network: ${network}`);
626
+ execFileSync(this.dockerPath, ['network', 'rm', network], { stdio: 'ignore' });
627
+ this.log(`Network removed: ${network}`);
628
+ }
629
+ catch (error) {
630
+ this.logError(`Failed to remove network ${network}`, error);
631
+ }
632
+ }
633
+ this.containers.clear();
634
+ this.usedPorts.clear();
635
+ this.networks.clear();
636
+ this.log('Final cleanup completed');
637
+ }
638
+ finally {
639
+ this.cleanupInProgress = false;
640
+ }
641
+ }
642
+ async cleanupAllAsync() {
643
+ this.log('Initiating graceful cleanup of all test containers');
644
+ await this.cleanupAll();
645
+ }
646
+ cleanupSync() {
647
+ try {
648
+ this.log('Performing synchronous cleanup of remaining test containers');
649
+ const isWindows = process.platform === 'win32';
650
+ if (isWindows) {
651
+ this.cleanupSyncWindows();
652
+ }
653
+ else {
654
+ this.cleanupSyncUnix();
655
+ }
656
+ this.log('Synchronous cleanup completed');
657
+ }
658
+ catch (error) {
659
+ this.logError('Error during synchronous cleanup', error);
660
+ }
661
+ }
662
+ cleanupSyncWindows() {
663
+ try {
664
+ const containerIds = execFileSync(this.dockerPath, ['ps', '-a', '--filter', 'label=test.cleanup=true', '-q'], {
665
+ encoding: 'utf8',
666
+ stdio: ['pipe', 'pipe', 'ignore'],
667
+ }).trim();
668
+ if (containerIds) {
669
+ const ids = containerIds.split('\n').filter((id) => id.trim());
670
+ this.log(`Found ${ids.length} test containers to clean up`);
671
+ for (const id of ids) {
672
+ try {
673
+ const trimmedId = id.trim();
674
+ this.log(`Stopping container: ${trimmedId}`);
675
+ try {
676
+ execFileSync(this.dockerPath, ['stop', '-t', '5', trimmedId], { stdio: 'ignore' });
677
+ }
678
+ catch {
679
+ }
680
+ this.log(`Removing container: ${trimmedId}`);
681
+ execFileSync(this.dockerPath, ['rm', '-f', trimmedId], { stdio: 'ignore' });
682
+ this.log(`Container removed: ${trimmedId}`);
683
+ }
684
+ catch (error) {
685
+ this.logError(`Failed to cleanup container ${id}`, error);
686
+ }
687
+ }
688
+ }
689
+ try {
690
+ const networkIds = execFileSync(this.dockerPath, ['network', 'ls', '--filter', 'label=test.cleanup=true', '-q'], {
691
+ encoding: 'utf8',
692
+ stdio: ['pipe', 'pipe', 'ignore'],
693
+ }).trim();
694
+ if (networkIds) {
695
+ const ids = networkIds.split('\n').filter((id) => id.trim());
696
+ this.log(`Found ${ids.length} test networks to clean up`);
697
+ for (const id of ids) {
698
+ try {
699
+ this.log(`Removing network: ${id.trim()}`);
700
+ execFileSync(this.dockerPath, ['network', 'rm', id.trim()], { stdio: 'ignore' });
701
+ this.log(`Network removed: ${id.trim()}`);
702
+ }
703
+ catch (error) {
704
+ this.logError(`Failed to cleanup network ${id}`, error);
705
+ }
706
+ }
707
+ }
708
+ }
709
+ catch (error) {
710
+ this.logError('Failed to cleanup networks', error);
711
+ }
712
+ }
713
+ catch (error) {
714
+ this.logError('Windows cleanup failed', error);
715
+ }
716
+ }
717
+ cleanupSyncUnix() {
718
+ try {
719
+ const containerCmd = `"${this.dockerPath}" ps -a --filter "label=test.cleanup=true" -q`;
720
+ try {
721
+ const ids = execSync(containerCmd, { encoding: 'utf8', stdio: ['pipe', 'pipe', 'ignore'] }).trim();
722
+ if (ids) {
723
+ const containerIds = ids.split('\n').filter((id) => id.trim());
724
+ this.log(`Found ${containerIds.length} test containers to clean up`);
725
+ for (const id of containerIds) {
726
+ try {
727
+ const trimmedId = id.trim();
728
+ this.log(`Stopping container: ${trimmedId}`);
729
+ try {
730
+ execFileSync(this.dockerPath, ['stop', '-t', '5', trimmedId], { stdio: 'ignore' });
731
+ }
732
+ catch {
733
+ }
734
+ this.log(`Removing container: ${trimmedId}`);
735
+ execFileSync(this.dockerPath, ['rm', '-f', trimmedId], { stdio: 'ignore' });
736
+ this.log(`Container removed: ${trimmedId}`);
737
+ }
738
+ catch (error) {
739
+ this.logError(`Failed to cleanup container ${id}`, error);
740
+ }
741
+ }
742
+ }
743
+ }
744
+ catch (error) {
745
+ this.logError('Failed to cleanup containers', error);
746
+ }
747
+ try {
748
+ const networkCmd = `"${this.dockerPath}" network ls --filter "label=test.cleanup=true" -q`;
749
+ const ids = execSync(networkCmd, { encoding: 'utf8', stdio: ['pipe', 'pipe', 'ignore'] }).trim();
750
+ if (ids) {
751
+ const networkIds = ids.split('\n').filter((id) => id.trim());
752
+ this.log(`Found ${networkIds.length} test networks to clean up`);
753
+ for (const id of networkIds) {
754
+ try {
755
+ this.log(`Removing network: ${id.trim()}`);
756
+ execFileSync(this.dockerPath, ['network', 'rm', id.trim()], { stdio: 'ignore' });
757
+ this.log(`Network removed: ${id.trim()}`);
758
+ }
759
+ catch (error) {
760
+ this.logError(`Failed to cleanup network ${id}`, error);
761
+ }
762
+ }
763
+ }
764
+ }
765
+ catch (error) {
766
+ this.logError('Failed to cleanup networks', error);
767
+ }
768
+ try {
769
+ const volumeCmd = `"${this.dockerPath}" volume ls --filter "label=test.cleanup=true" -q`;
770
+ const ids = execSync(volumeCmd, { encoding: 'utf8', stdio: ['pipe', 'pipe', 'ignore'] }).trim();
771
+ if (ids) {
772
+ const volumeIds = ids.split('\n').filter((id) => id.trim());
773
+ this.log(`Found ${volumeIds.length} test volumes to clean up`);
774
+ for (const id of volumeIds) {
775
+ try {
776
+ this.log(`Removing volume: ${id.trim()}`);
777
+ execFileSync(this.dockerPath, ['volume', 'rm', '-f', id.trim()], { stdio: 'ignore' });
778
+ this.log(`Volume removed: ${id.trim()}`);
779
+ }
780
+ catch (error) {
781
+ this.logError(`Failed to cleanup volume ${id}`, error);
782
+ }
783
+ }
784
+ }
785
+ }
786
+ catch (error) {
787
+ this.logError('Failed to cleanup volumes', error);
788
+ }
789
+ }
790
+ catch (error) {
791
+ this.logError('Unix cleanup failed', error);
792
+ }
793
+ }
794
+ static async withContainer(options, testFn) {
795
+ const manager = DockerTestManager.getInstance();
796
+ const container = await manager.createContainer(options);
797
+ try {
798
+ return await testFn(container);
799
+ }
800
+ finally {
801
+ await container.cleanup();
802
+ }
803
+ }
804
+ }
805
+ //# sourceMappingURL=docker-test-manager.js.map