@omnitron-dev/testing 0.3.1 → 0.3.3
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.
- package/README.md +24 -0
- package/dist/docker/database-manager.js +4 -6
- package/dist/docker/database-manager.js.map +1 -1
- package/dist/docker/docker-test-manager.d.ts +4 -3
- package/dist/docker/docker-test-manager.js +126 -268
- package/dist/docker/docker-test-manager.js.map +1 -1
- package/dist/docker/redis-manager.js +38 -36
- package/dist/docker/redis-manager.js.map +1 -1
- package/dist/docker/types.d.ts +2 -2
- package/dist/env.js +6 -3
- package/dist/env.js.map +1 -1
- package/dist/runtime/deno-adapter.js +1 -1
- package/dist/runtime/deno-adapter.js.map +1 -1
- package/dist/titan/redis-test-utils.js +80 -54
- package/dist/titan/redis-test-utils.js.map +1 -1
- package/package.json +33 -31
- package/src/docker/database-manager.ts +4 -6
- package/src/docker/docker-test-manager.ts +113 -353
- package/src/docker/docker-volume-cleanup.spec.ts +62 -15
- package/src/docker/redis-cluster-creation.spec.ts +52 -0
- package/src/docker/redis-manager.ts +33 -49
- package/src/docker/types.ts +4 -4
- package/src/env.spec.ts +20 -0
- package/src/env.ts +5 -3
- package/src/index.ts +1 -1
- package/src/runtime/deno-adapter.ts +1 -1
- package/src/titan/redis-test-utils.test.ts +102 -0
- package/src/titan/redis-test-utils.ts +86 -71
package/README.md
CHANGED
|
@@ -14,6 +14,30 @@ pnpm add -D @omnitron-dev/testing
|
|
|
14
14
|
|
|
15
15
|
Shared testing helpers, fixtures, and utilities used across Omni packages. Provides runtime-agnostic test infrastructure that works with both Vitest and Jest.
|
|
16
16
|
|
|
17
|
+
## Redis fixtures
|
|
18
|
+
|
|
19
|
+
`createRedisTestFixture` from `@omnitron-dev/testing/titan` uses the same
|
|
20
|
+
`resolveTestRedisEndpoint()` as the integration suites. It reads the endpoint
|
|
21
|
+
published by global setup, then the test environment. Without setup, configure
|
|
22
|
+
`TEST_REDIS_HOST` and `TEST_REDIS_PORT`; the default test port is **16379**, never
|
|
23
|
+
the developer's Redis on 6379.
|
|
24
|
+
|
|
25
|
+
```ts
|
|
26
|
+
import { createRedisTestFixture } from '@omnitron-dev/testing/titan';
|
|
27
|
+
|
|
28
|
+
const fixture = await createRedisTestFixture({ withManager: true, db: 15 });
|
|
29
|
+
try {
|
|
30
|
+
await fixture.client.ping();
|
|
31
|
+
} finally {
|
|
32
|
+
await fixture.cleanup();
|
|
33
|
+
}
|
|
34
|
+
```
|
|
35
|
+
|
|
36
|
+
Cleanup flushes the selected scratch database and closes the clients even when
|
|
37
|
+
flushing fails. Use a dedicated test Redis. Initialization failure also closes
|
|
38
|
+
allocated connections. Mock mode requires a mock fixture or an explicit real
|
|
39
|
+
endpoint; it does not silently connect to a developer service.
|
|
40
|
+
|
|
17
41
|
## License
|
|
18
42
|
|
|
19
43
|
MIT
|
|
@@ -20,10 +20,9 @@ export class DatabaseTestManager {
|
|
|
20
20
|
POSTGRES_DB: database,
|
|
21
21
|
POSTGRES_USER: user,
|
|
22
22
|
POSTGRES_PASSWORD: password,
|
|
23
|
-
POSTGRES_HOST_AUTH_METHOD: 'trust',
|
|
24
23
|
},
|
|
25
24
|
healthcheck: {
|
|
26
|
-
test: ['CMD
|
|
25
|
+
test: ['CMD', 'pg_isready', '-h', '127.0.0.1', '-U', user, '-d', database],
|
|
27
26
|
interval: '1s',
|
|
28
27
|
timeout: '5s',
|
|
29
28
|
retries: 30,
|
|
@@ -50,10 +49,9 @@ export class DatabaseTestManager {
|
|
|
50
49
|
MYSQL_USER: user,
|
|
51
50
|
MYSQL_PASSWORD: password,
|
|
52
51
|
MYSQL_ROOT_PASSWORD: rootPassword,
|
|
53
|
-
MYSQL_ALLOW_EMPTY_PASSWORD: 'yes',
|
|
54
52
|
},
|
|
55
53
|
healthcheck: {
|
|
56
|
-
test: ['CMD', 'mysqladmin', 'ping', '-h', '
|
|
54
|
+
test: ['CMD', 'mysqladmin', 'ping', '--protocol=tcp', '-h', '127.0.0.1'],
|
|
57
55
|
interval: '2s',
|
|
58
56
|
timeout: '10s',
|
|
59
57
|
retries: 25,
|
|
@@ -71,7 +69,7 @@ export class DatabaseTestManager {
|
|
|
71
69
|
const database = options?.database || 'testdb';
|
|
72
70
|
const user = options?.user || 'testuser';
|
|
73
71
|
const password = options?.password || 'testpass';
|
|
74
|
-
const connectionString = `postgresql://${user}:${password}@localhost:${port}/${database}`;
|
|
72
|
+
const connectionString = `postgresql://${encodeURIComponent(user)}:${encodeURIComponent(password)}@localhost:${port}/${encodeURIComponent(database)}`;
|
|
75
73
|
try {
|
|
76
74
|
return await testFn(container, connectionString);
|
|
77
75
|
}
|
|
@@ -85,7 +83,7 @@ export class DatabaseTestManager {
|
|
|
85
83
|
const database = options?.database || 'testdb';
|
|
86
84
|
const user = options?.user || 'testuser';
|
|
87
85
|
const password = options?.password || 'testpass';
|
|
88
|
-
const connectionString = `mysql://${user}:${password}@localhost:${port}/${database}`;
|
|
86
|
+
const connectionString = `mysql://${encodeURIComponent(user)}:${encodeURIComponent(password)}@localhost:${port}/${encodeURIComponent(database)}`;
|
|
89
87
|
try {
|
|
90
88
|
return await testFn(container, connectionString);
|
|
91
89
|
}
|
|
@@ -1 +1 @@
|
|
|
1
|
-
{"version":3,"file":"database-manager.js","sourceRoot":"","sources":["../../src/docker/database-manager.ts"],"names":[],"mappings":"AAOA,OAAO,EAAE,iBAAiB,EAAE,MAAM,0BAA0B,CAAC;AAwB7D,MAAM,OAAO,mBAAmB;aACf,mBAAc,GAA6B,IAAI,CAAC;IAMvD,MAAM,CAAC,gBAAgB;QAC7B,IAAI,CAAC,mBAAmB,CAAC,cAAc,EAAE,CAAC;YACxC,mBAAmB,CAAC,cAAc,GAAG,iBAAiB,CAAC,WAAW,EAAE,CAAC;QACvE,CAAC;QACD,OAAO,mBAAmB,CAAC,cAAc,CAAC;IAC5C,CAAC;IAoBD,MAAM,CAAC,KAAK,CAAC,uBAAuB,CAAC,OAWpC;QACC,MAAM,IAAI,GAAG,OAAO,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AAC,KAAK,CAAC,GAAG,CAAC,IAAI,CAAE,CAAC;QACxC,MAAM,QAAQ,GAAG,OAAO,EAAE,QAAQ,IAAI,QAAQ,CAAC;QAC/C,MAAM,IAAI,GAAG,OAAO,EAAE,IAAI,IAAI,UAAU,CAAC;QACzC,MAAM,QAAQ,GAAG,OAAO,EAAE,QAAQ,IAAI,UAAU,CAAC;QACjD,MAAM,gBAAgB,GAAG,WAAW,kBAAkB,CAAC,IAAI,CAAC,IAAI,kBAAkB,CAAC,QAAQ,CAAC,cAAc,IAAI,IAAI,kBAAkB,CAAC,QAAQ,CAAC,EAAE,CAAC;QAEjJ,IAAI,CAAC;YACH,OAAO,MAAM,MAAM,CAAC,SAAS,EAAE,gBAAgB,CAAC,CAAC;QACnD,CAAC;gBAAS,CAAC;YACT,MAAM,SAAS,CAAC,OAAO,EAAE,CAAC;QAC5B,CAAC;IACH,CAAC;CACF"}
|
|
@@ -5,7 +5,7 @@ export declare class DockerTestManager extends EventEmitter {
|
|
|
5
5
|
private containers;
|
|
6
6
|
private usedPorts;
|
|
7
7
|
private networks;
|
|
8
|
-
private
|
|
8
|
+
private activeCleanup?;
|
|
9
9
|
private dockerPath;
|
|
10
10
|
private static readonly PORT_COLLISION_RETRIES;
|
|
11
11
|
private basePort;
|
|
@@ -37,13 +37,14 @@ export declare class DockerTestManager extends EventEmitter {
|
|
|
37
37
|
private isContainerHealthy;
|
|
38
38
|
createContainer(options: ContainerOptions): Promise<DockerContainer>;
|
|
39
39
|
private cleanupContainerWithRetry;
|
|
40
|
-
|
|
41
|
-
|
|
40
|
+
ensureNetwork(network: string): Promise<void>;
|
|
41
|
+
removeNetwork(network: string): Promise<void>;
|
|
42
42
|
private waitForContainer;
|
|
43
43
|
private isPortListening;
|
|
44
44
|
getContainer(id: string): Promise<DockerContainer | undefined>;
|
|
45
45
|
cleanupContainer(id: string): Promise<void>;
|
|
46
46
|
cleanupAll(): Promise<void>;
|
|
47
|
+
private cleanupOwnedResources;
|
|
47
48
|
private cleanupAllAsync;
|
|
48
49
|
private cleanupSync;
|
|
49
50
|
private cleanupSyncWindows;
|
|
@@ -1,4 +1,4 @@
|
|
|
1
|
-
import { execSync, execFileSync } from 'child_process';
|
|
1
|
+
import { execSync, execFileSync, execFile } from 'child_process';
|
|
2
2
|
import { randomBytes } from 'crypto';
|
|
3
3
|
import { hostname } from 'os';
|
|
4
4
|
import * as net from 'net';
|
|
@@ -12,6 +12,15 @@ function parseDockerLabels(labels) {
|
|
|
12
12
|
}
|
|
13
13
|
return out;
|
|
14
14
|
}
|
|
15
|
+
function dockerHealthCommand(test) {
|
|
16
|
+
if (typeof test === 'string')
|
|
17
|
+
return test;
|
|
18
|
+
const [mode, ...args] = test;
|
|
19
|
+
if (mode === 'CMD-SHELL')
|
|
20
|
+
return args.join(' ');
|
|
21
|
+
const argv = mode === 'CMD' ? args : test;
|
|
22
|
+
return argv.map(arg => "'" + arg.replaceAll("'", "'\\''") + "'").join(' ');
|
|
23
|
+
}
|
|
15
24
|
function pidFromManagerId(managerId) {
|
|
16
25
|
const pid = Number.parseInt(managerId.split('-')[0] ?? '', 10);
|
|
17
26
|
return Number.isInteger(pid) && pid > 0 ? pid : null;
|
|
@@ -41,8 +50,7 @@ export class DockerTestManager extends EventEmitter {
|
|
|
41
50
|
super();
|
|
42
51
|
this.containers = new Map();
|
|
43
52
|
this.usedPorts = new Set();
|
|
44
|
-
this.networks = new
|
|
45
|
-
this.cleanupInProgress = false;
|
|
53
|
+
this.networks = new Map();
|
|
46
54
|
this.managerId = `${process.pid}-${Date.now().toString(36)}-${Math.random().toString(36).slice(2, 8)}`;
|
|
47
55
|
this.dockerPath = options.dockerPath || this.findDockerPath();
|
|
48
56
|
const workerId = parseInt(process.env['VITEST_POOL_ID'] || process.env['VITEST_WORKER_ID'] || '1', 10);
|
|
@@ -69,7 +77,7 @@ export class DockerTestManager extends EventEmitter {
|
|
|
69
77
|
this.cleanupAllAsync()
|
|
70
78
|
.then(() => {
|
|
71
79
|
this.log('Cleanup completed, exiting');
|
|
72
|
-
process.exit(
|
|
80
|
+
process.exit(130);
|
|
73
81
|
})
|
|
74
82
|
.catch((error) => {
|
|
75
83
|
this.logError('Cleanup failed during SIGINT', error);
|
|
@@ -81,7 +89,7 @@ export class DockerTestManager extends EventEmitter {
|
|
|
81
89
|
this.cleanupAllAsync()
|
|
82
90
|
.then(() => {
|
|
83
91
|
this.log('Cleanup completed, exiting');
|
|
84
|
-
process.exit(
|
|
92
|
+
process.exit(143);
|
|
85
93
|
})
|
|
86
94
|
.catch((error) => {
|
|
87
95
|
this.logError('Cleanup failed during SIGTERM', error);
|
|
@@ -344,12 +352,6 @@ export class DockerTestManager extends EventEmitter {
|
|
|
344
352
|
const id = `test-${randomBytes(8).toString('hex')}`;
|
|
345
353
|
const name = options.name || `container-${id}`;
|
|
346
354
|
const host = '127.0.0.1';
|
|
347
|
-
try {
|
|
348
|
-
execFileSync(this.dockerPath, ['rm', '-f', '-v', name], { stdio: 'ignore' });
|
|
349
|
-
this.log(`Removed existing container: ${name}`);
|
|
350
|
-
}
|
|
351
|
-
catch {
|
|
352
|
-
}
|
|
353
355
|
const autoPorts = new Set();
|
|
354
356
|
const portMappings = new Map();
|
|
355
357
|
if (options.ports) {
|
|
@@ -380,11 +382,11 @@ export class DockerTestManager extends EventEmitter {
|
|
|
380
382
|
dockerArgs.push('-e', `${key}=${value}`);
|
|
381
383
|
}
|
|
382
384
|
const labels = {
|
|
385
|
+
...options.labels,
|
|
383
386
|
'test.id': id,
|
|
384
387
|
'test.cleanup': 'true',
|
|
385
388
|
'test.manager': this.managerId,
|
|
386
389
|
'test.host': DockerTestManager.hostId,
|
|
387
|
-
...options.labels,
|
|
388
390
|
};
|
|
389
391
|
for (const [key, value] of Object.entries(labels)) {
|
|
390
392
|
dockerArgs.push('--label', `${key}=${value}`);
|
|
@@ -400,22 +402,7 @@ export class DockerTestManager extends EventEmitter {
|
|
|
400
402
|
dockerArgs.push('--network', network);
|
|
401
403
|
}
|
|
402
404
|
if (options.healthcheck) {
|
|
403
|
-
|
|
404
|
-
if (Array.isArray(options.healthcheck.test)) {
|
|
405
|
-
if (options.healthcheck.test[0] === 'CMD-SHELL') {
|
|
406
|
-
healthCmd = options.healthcheck.test.slice(1).join(' ');
|
|
407
|
-
}
|
|
408
|
-
else if (options.healthcheck.test[0] === 'CMD') {
|
|
409
|
-
healthCmd = options.healthcheck.test.slice(1).join(' ');
|
|
410
|
-
}
|
|
411
|
-
else {
|
|
412
|
-
healthCmd = options.healthcheck.test.join(' ');
|
|
413
|
-
}
|
|
414
|
-
}
|
|
415
|
-
else {
|
|
416
|
-
healthCmd = options.healthcheck.test;
|
|
417
|
-
}
|
|
418
|
-
dockerArgs.push('--health-cmd', healthCmd);
|
|
405
|
+
dockerArgs.push('--health-cmd', dockerHealthCommand(options.healthcheck.test));
|
|
419
406
|
if (options.healthcheck.interval) {
|
|
420
407
|
dockerArgs.push('--health-interval', options.healthcheck.interval);
|
|
421
408
|
}
|
|
@@ -431,73 +418,56 @@ export class DockerTestManager extends EventEmitter {
|
|
|
431
418
|
}
|
|
432
419
|
dockerArgs.push(options.image);
|
|
433
420
|
if (options.command) {
|
|
434
|
-
|
|
435
|
-
|
|
436
|
-
|
|
437
|
-
|
|
438
|
-
}
|
|
439
|
-
|
|
440
|
-
|
|
441
|
-
|
|
442
|
-
|
|
443
|
-
|
|
444
|
-
|
|
445
|
-
|
|
446
|
-
|
|
447
|
-
|
|
448
|
-
}
|
|
421
|
+
if (Array.isArray(options.command))
|
|
422
|
+
dockerArgs.push(...options.command);
|
|
423
|
+
else
|
|
424
|
+
dockerArgs.push('sh', '-c', options.command);
|
|
425
|
+
}
|
|
426
|
+
let containerId;
|
|
427
|
+
for (let attempt = 0;; attempt++) {
|
|
428
|
+
this.log(`Starting container: ${name}`, { image: options.image });
|
|
429
|
+
const result = await new Promise(resolve => {
|
|
430
|
+
execFile(this.dockerPath, dockerArgs, { encoding: 'utf8', timeout: this.startupTimeout, maxBuffer: 2 * 1024 * 1024 }, (error, stdout, stderr) => resolve({ status: error ? (typeof error.code === 'number' ? error.code : null) : 0,
|
|
431
|
+
stdout, stderr, ...(error && typeof error.code !== 'number' ? { error } : {}) }));
|
|
432
|
+
});
|
|
433
|
+
containerId = (result.stdout ?? '').trim();
|
|
434
|
+
if (result.status === 0 && /^[a-f0-9]{64}$/.test(containerId))
|
|
449
435
|
break;
|
|
450
|
-
|
|
451
|
-
|
|
452
|
-
|
|
453
|
-
|
|
454
|
-
|
|
455
|
-
|
|
456
|
-
|
|
457
|
-
|
|
458
|
-
|
|
459
|
-
|
|
460
|
-
|
|
461
|
-
|
|
462
|
-
|
|
463
|
-
|
|
464
|
-
|
|
465
|
-
|
|
466
|
-
|
|
467
|
-
|
|
468
|
-
|
|
469
|
-
|
|
470
|
-
|
|
471
|
-
|
|
472
|
-
|
|
473
|
-
|
|
474
|
-
const hPort = await this.findAvailablePort();
|
|
475
|
-
portMappings.set(cPort, hPort);
|
|
476
|
-
}
|
|
477
|
-
rebuildPortArgs();
|
|
478
|
-
this.log(`Host port collision for ${name}, retrying with fresh ports`, {
|
|
479
|
-
attempt: portAttempt + 1,
|
|
480
|
-
});
|
|
481
|
-
continue;
|
|
482
|
-
}
|
|
483
|
-
throw new Error(`Failed to start container ${name}:\n` +
|
|
484
|
-
`Command: docker ${dockerArgs.join(' ')}\n` +
|
|
485
|
-
`Exit code: ${execError.status || 'unknown'}\n` +
|
|
486
|
-
(stderr ? `Stderr: ${stderr}\n` : '') +
|
|
487
|
-
(stdout ? `Stdout: ${stdout}\n` : '') +
|
|
488
|
-
(message && !stderr && !stdout ? `Error: ${message}` : ''), { cause: error });
|
|
489
|
-
}
|
|
436
|
+
portMappings.forEach(port => this.usedPorts.delete(port));
|
|
437
|
+
let diagnostic = (result.stderr ?? '').trim();
|
|
438
|
+
for (const value of Object.values(environment)) {
|
|
439
|
+
if (value)
|
|
440
|
+
diagnostic = diagnostic.replaceAll(value, '[redacted]');
|
|
441
|
+
}
|
|
442
|
+
if (/container name .*already in use|name is already in use/i.test(diagnostic)) {
|
|
443
|
+
throw new Error(`Container name conflict: ${name} already exists`);
|
|
444
|
+
}
|
|
445
|
+
const residue = execFileSync(this.dockerPath, ['ps', '-aq', '--no-trunc',
|
|
446
|
+
'--filter', `label=test.id=${id}`, '--filter', `label=test.manager=${this.managerId}`], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim();
|
|
447
|
+
if (/^[a-f0-9]{64}$/.test(residue)) {
|
|
448
|
+
execFileSync(this.dockerPath, ['rm', '-f', '-v', residue], { stdio: 'ignore' });
|
|
449
|
+
}
|
|
450
|
+
if (result.error)
|
|
451
|
+
throw new Error(`Could not execute Docker for ${name}: ${result.error.code ?? 'unknown'}`);
|
|
452
|
+
if (!/port is already allocated|address already in use|Bind for /.test(diagnostic)
|
|
453
|
+
|| !autoPorts.size || attempt >= DockerTestManager.PORT_COLLISION_RETRIES) {
|
|
454
|
+
throw new Error(`Failed to start container ${name} (${options.image}), exit ${result.status ?? 'unknown'}: ${diagnostic.slice(0, 2000) || 'Docker did not confirm creation'}`);
|
|
455
|
+
}
|
|
456
|
+
for (const port of autoPorts)
|
|
457
|
+
portMappings.set(port, await this.findAvailablePort());
|
|
458
|
+
rebuildPortArgs();
|
|
459
|
+
this.log(`Host port collision for ${name}, retrying with fresh ports`, { attempt: attempt + 1 });
|
|
490
460
|
}
|
|
491
461
|
if (options.waitFor) {
|
|
492
462
|
try {
|
|
493
|
-
await this.waitForContainer(
|
|
463
|
+
await this.waitForContainer(containerId, options.waitFor, portMappings);
|
|
494
464
|
this.log(`Container ready: ${name}`);
|
|
495
465
|
}
|
|
496
466
|
catch (error) {
|
|
497
467
|
this.logError(`Container ${name} failed to become ready, cleaning up`, error);
|
|
498
468
|
try {
|
|
499
|
-
execFileSync(this.dockerPath, ['stop', '-t', '5',
|
|
500
|
-
execFileSync(this.dockerPath, ['rm', '-f', '-v',
|
|
469
|
+
execFileSync(this.dockerPath, ['stop', '-t', '5', containerId], { stdio: 'ignore' });
|
|
470
|
+
execFileSync(this.dockerPath, ['rm', '-f', '-v', containerId], { stdio: 'ignore' });
|
|
501
471
|
}
|
|
502
472
|
catch {
|
|
503
473
|
}
|
|
@@ -535,181 +505,97 @@ export class DockerTestManager extends EventEmitter {
|
|
|
535
505
|
networks,
|
|
536
506
|
createdAt: new Date(),
|
|
537
507
|
internalIp,
|
|
538
|
-
getStatus: async () => this.getContainerStatus(
|
|
539
|
-
isHealthy: async () => this.isContainerHealthy(
|
|
508
|
+
getStatus: async () => this.getContainerStatus(containerId),
|
|
509
|
+
isHealthy: async () => this.isContainerHealthy(containerId),
|
|
540
510
|
cleanup: async () => {
|
|
541
|
-
await this.cleanupContainerWithRetry(
|
|
511
|
+
await this.cleanupContainerWithRetry(containerId, id, portMappings);
|
|
542
512
|
},
|
|
543
513
|
};
|
|
544
514
|
this.containers.set(id, container);
|
|
545
515
|
return container;
|
|
546
516
|
}
|
|
547
|
-
async cleanupContainerWithRetry(
|
|
548
|
-
this.
|
|
549
|
-
|
|
550
|
-
|
|
551
|
-
try {
|
|
552
|
-
try {
|
|
553
|
-
const status = await this.getContainerStatus(name);
|
|
554
|
-
if (!status.isRunning) {
|
|
555
|
-
this.log(`Container ${name} is not running, force removing`, { attempt });
|
|
556
|
-
}
|
|
557
|
-
}
|
|
558
|
-
catch {
|
|
559
|
-
this.log(`Container ${name} doesn't exist, skipping stop`, { attempt });
|
|
560
|
-
break;
|
|
561
|
-
}
|
|
562
|
-
try {
|
|
563
|
-
const stopTimeoutSecs = Math.ceil(this.gracefulShutdownTimeout / 1000).toString();
|
|
564
|
-
this.log(`Stopping container ${name}`, { attempt, timeout: this.gracefulShutdownTimeout });
|
|
565
|
-
execFileSync(this.dockerPath, ['stop', '-t', stopTimeoutSecs, name], {
|
|
566
|
-
stdio: 'ignore',
|
|
567
|
-
timeout: this.gracefulShutdownTimeout + 5000,
|
|
568
|
-
});
|
|
569
|
-
this.log(`Container stopped: ${name}`, { attempt });
|
|
570
|
-
}
|
|
571
|
-
catch (error) {
|
|
572
|
-
this.logError(`Failed to gracefully stop container ${name}`, error);
|
|
573
|
-
}
|
|
574
|
-
try {
|
|
575
|
-
this.log(`Removing container ${name}`, { attempt });
|
|
576
|
-
execFileSync(this.dockerPath, ['rm', '-f', '-v', name], { stdio: 'ignore' });
|
|
577
|
-
this.log(`Container removed: ${name}`, { attempt });
|
|
578
|
-
lastError = null;
|
|
579
|
-
break;
|
|
580
|
-
}
|
|
581
|
-
catch (error) {
|
|
582
|
-
lastError = error instanceof Error ? error : new Error(String(error));
|
|
583
|
-
if (attempt === this.maxCleanupRetries) {
|
|
584
|
-
throw lastError;
|
|
585
|
-
}
|
|
586
|
-
await new Promise((resolve) => setTimeout(resolve, 1000 * attempt));
|
|
587
|
-
}
|
|
588
|
-
}
|
|
589
|
-
catch (error) {
|
|
590
|
-
lastError = error instanceof Error ? error : new Error(String(error));
|
|
591
|
-
if (attempt === this.maxCleanupRetries) {
|
|
592
|
-
this.logError(`Final cleanup attempt failed for container ${name}`, lastError);
|
|
593
|
-
}
|
|
594
|
-
else {
|
|
595
|
-
this.logError(`Cleanup attempt ${attempt} failed for container ${name}, retrying`, lastError);
|
|
596
|
-
await new Promise((resolve) => setTimeout(resolve, 1000 * attempt));
|
|
597
|
-
}
|
|
598
|
-
}
|
|
599
|
-
}
|
|
517
|
+
async cleanupContainerWithRetry(containerId, id, portMappings) {
|
|
518
|
+
if (!this.containers.has(id))
|
|
519
|
+
return;
|
|
520
|
+
const seconds = Math.ceil(this.gracefulShutdownTimeout / 1000).toString();
|
|
600
521
|
try {
|
|
601
|
-
|
|
602
|
-
this.
|
|
603
|
-
this.log(`Released port: ${port}`);
|
|
522
|
+
execFileSync(this.dockerPath, ['stop', '-t', seconds, containerId], {
|
|
523
|
+
stdio: 'ignore', timeout: this.gracefulShutdownTimeout + 5000,
|
|
604
524
|
});
|
|
605
525
|
}
|
|
606
526
|
catch (error) {
|
|
607
|
-
this.logError(
|
|
527
|
+
this.logError(`Could not stop test container ${containerId} gracefully`, error);
|
|
608
528
|
}
|
|
609
|
-
|
|
610
|
-
this.log(`Container cleanup completed: ${name}`, { attempts: this.maxCleanupRetries });
|
|
611
|
-
}
|
|
612
|
-
async ensureNetwork(network) {
|
|
613
|
-
if (!this.networks.has(network)) {
|
|
529
|
+
for (let attempt = 1;; attempt++) {
|
|
614
530
|
try {
|
|
615
|
-
execFileSync(this.dockerPath, ['
|
|
616
|
-
|
|
617
|
-
encoding: 'utf8',
|
|
618
|
-
});
|
|
619
|
-
this.networks.add(network);
|
|
620
|
-
this.log(`Created network: ${network}`);
|
|
531
|
+
execFileSync(this.dockerPath, ['rm', '-f', '-v', containerId], { stdio: ['ignore', 'ignore', 'pipe'] });
|
|
532
|
+
break;
|
|
621
533
|
}
|
|
622
534
|
catch (error) {
|
|
623
|
-
|
|
624
|
-
|
|
625
|
-
if (
|
|
626
|
-
|
|
627
|
-
|
|
628
|
-
}
|
|
629
|
-
else if (stderr.includes('all predefined address pools have been fully subnetted')) {
|
|
630
|
-
this.log('Docker network pool exhausted, attempting cleanup...');
|
|
631
|
-
try {
|
|
632
|
-
execFileSync(this.dockerPath, ['network', 'prune', '-f', '--filter', `label=test.manager=${this.managerId}`], {
|
|
633
|
-
stdio: 'ignore',
|
|
634
|
-
});
|
|
635
|
-
this.log('Cleaned up unused networks, retrying network creation...');
|
|
636
|
-
execFileSync(this.dockerPath, ['network', 'create', network, '--label', 'test.cleanup=true', '--label', `test.manager=${this.managerId}`, '--label', `test.host=${DockerTestManager.hostId}`], {
|
|
637
|
-
stdio: 'pipe',
|
|
638
|
-
encoding: 'utf8',
|
|
639
|
-
});
|
|
640
|
-
this.networks.add(network);
|
|
641
|
-
this.log(`Created network after cleanup: ${network}`);
|
|
642
|
-
}
|
|
643
|
-
catch (_retryError) {
|
|
644
|
-
throw new Error(`Failed to create network ${network} even after cleanup: ${stderr}`, { cause: _retryError });
|
|
645
|
-
}
|
|
646
|
-
}
|
|
647
|
-
else {
|
|
648
|
-
throw new Error(`Failed to create network ${network}: ${stderr}`, { cause: error });
|
|
649
|
-
}
|
|
535
|
+
if (/no such (container|object)/i.test(String(error.stderr)))
|
|
536
|
+
break;
|
|
537
|
+
if (attempt >= this.maxCleanupRetries)
|
|
538
|
+
throw error;
|
|
539
|
+
await new Promise(resolve => setTimeout(resolve, 1000 * attempt));
|
|
650
540
|
}
|
|
651
541
|
}
|
|
542
|
+
portMappings.forEach(port => this.usedPorts.delete(port));
|
|
543
|
+
this.containers.delete(id);
|
|
544
|
+
}
|
|
545
|
+
async ensureNetwork(network) {
|
|
546
|
+
const create = () => {
|
|
547
|
+
const networkId = execFileSync(this.dockerPath, ['network', 'create', network,
|
|
548
|
+
'--label', 'test.cleanup=true', '--label', `test.manager=${this.managerId}`,
|
|
549
|
+
'--label', `test.host=${DockerTestManager.hostId}`], { stdio: 'pipe', encoding: 'utf8' }).trim();
|
|
550
|
+
this.networks.set(network, networkId);
|
|
551
|
+
};
|
|
552
|
+
try {
|
|
553
|
+
create();
|
|
554
|
+
}
|
|
555
|
+
catch (error) {
|
|
556
|
+
const reason = String(error.stderr ?? error);
|
|
557
|
+
if (reason.includes('already exists'))
|
|
558
|
+
return;
|
|
559
|
+
if (!reason.includes('all predefined address pools have been fully subnetted'))
|
|
560
|
+
throw error;
|
|
561
|
+
execFileSync(this.dockerPath, ['network', 'prune', '-f', '--filter', `label=test.manager=${this.managerId}`], { stdio: 'ignore' });
|
|
562
|
+
create();
|
|
563
|
+
}
|
|
652
564
|
}
|
|
653
565
|
async removeNetwork(network) {
|
|
654
|
-
|
|
566
|
+
const id = this.networks.get(network);
|
|
567
|
+
if (!id)
|
|
655
568
|
return;
|
|
656
|
-
}
|
|
657
569
|
try {
|
|
658
|
-
execFileSync(this.dockerPath, ['network', 'rm',
|
|
659
|
-
stdio: 'ignore',
|
|
660
|
-
});
|
|
661
|
-
this.networks.delete(network);
|
|
662
|
-
this.log(`Removed network: ${network}`);
|
|
570
|
+
execFileSync(this.dockerPath, ['network', 'rm', id], { stdio: ['ignore', 'ignore', 'pipe'] });
|
|
663
571
|
}
|
|
664
572
|
catch (error) {
|
|
665
|
-
|
|
666
|
-
|
|
573
|
+
if (!/not found|no such network/i.test(String(error.stderr)))
|
|
574
|
+
throw error;
|
|
667
575
|
}
|
|
576
|
+
this.networks.delete(network);
|
|
668
577
|
}
|
|
669
|
-
async waitForContainer(name, options) {
|
|
578
|
+
async waitForContainer(name, options, ports) {
|
|
670
579
|
const startTime = Date.now();
|
|
671
580
|
const timeout = options?.timeout || this.startupTimeout;
|
|
672
581
|
let lastError;
|
|
673
582
|
while (Date.now() - startTime < timeout) {
|
|
674
583
|
try {
|
|
675
584
|
const status = await this.getContainerStatus(name);
|
|
585
|
+
if (!status.state)
|
|
586
|
+
throw new Error('Container status is unavailable');
|
|
676
587
|
if (!status.isRunning) {
|
|
677
|
-
throw new Error(`Container exited with status '${status.state}' and exit code ${status.exitCode}
|
|
678
|
-
`Check container logs with 'docker logs ${name}'`);
|
|
588
|
+
throw new Error(`Container ${name} exited with status '${status.state}' and exit code ${status.exitCode}`);
|
|
679
589
|
}
|
|
680
|
-
if (options?.healthcheck) {
|
|
681
|
-
|
|
682
|
-
|
|
683
|
-
|
|
684
|
-
}
|
|
685
|
-
if (status.health === 'unhealthy') {
|
|
686
|
-
const elapsed = Date.now() - startTime;
|
|
687
|
-
this.logError(`Container ${name} health check failed after ${elapsed}ms`, new Error(`Health status: ${status.health}, State: ${status.state}`));
|
|
688
|
-
throw new Error(`Container ${name} health check failed. ` + `Check container logs with 'docker logs ${name}'`);
|
|
689
|
-
}
|
|
690
|
-
if (status.health === 'starting') {
|
|
691
|
-
const elapsed = Date.now() - startTime;
|
|
692
|
-
this.log(`Waiting for health check on ${name}...`, {
|
|
693
|
-
elapsed,
|
|
694
|
-
remaining: timeout - elapsed,
|
|
695
|
-
state: status.state,
|
|
696
|
-
});
|
|
697
|
-
}
|
|
698
|
-
}
|
|
699
|
-
if (options?.port) {
|
|
700
|
-
const container = this.containers.get(name);
|
|
701
|
-
if (container) {
|
|
702
|
-
const hostPort = container.ports.get(options.port);
|
|
703
|
-
if (hostPort && (await this.isPortListening('127.0.0.1', hostPort))) {
|
|
704
|
-
this.log(`Port ${hostPort} is listening on ${name}`);
|
|
705
|
-
return;
|
|
706
|
-
}
|
|
707
|
-
}
|
|
590
|
+
if (options?.healthcheck && status.health === 'unhealthy') {
|
|
591
|
+
const probes = execFileSync(this.dockerPath, ['inspect', '--format',
|
|
592
|
+
'{{with .State.Health}}{{.FailingStreak}} failed probes{{range .Log}}; exit={{.ExitCode}} at {{.End}}{{end}}{{end}}', name], { encoding: 'utf8', stdio: ['ignore', 'pipe', 'ignore'] }).trim();
|
|
593
|
+
throw new Error(`Container ${name} health check failed after ${Date.now() - startTime} ms (${probes})`);
|
|
708
594
|
}
|
|
709
|
-
|
|
710
|
-
|
|
595
|
+
const hostPort = options?.port && ports.get(options.port);
|
|
596
|
+
if ((!options?.healthcheck || status.health === 'healthy') &&
|
|
597
|
+
(!options?.port || (hostPort && await this.isPortListening('127.0.0.1', hostPort))))
|
|
711
598
|
return;
|
|
712
|
-
}
|
|
713
599
|
lastError = undefined;
|
|
714
600
|
}
|
|
715
601
|
catch (error) {
|
|
@@ -754,50 +640,22 @@ export class DockerTestManager extends EventEmitter {
|
|
|
754
640
|
await container.cleanup();
|
|
755
641
|
}
|
|
756
642
|
}
|
|
757
|
-
|
|
758
|
-
|
|
759
|
-
|
|
760
|
-
|
|
761
|
-
|
|
762
|
-
|
|
763
|
-
|
|
764
|
-
|
|
765
|
-
|
|
766
|
-
.cleanup()
|
|
767
|
-
.then(() => {
|
|
768
|
-
this.log(`Cleanup succeeded: ${container.name}`);
|
|
769
|
-
})
|
|
770
|
-
.catch((error) => {
|
|
771
|
-
this.logError(`Cleanup failed for ${container.name}`, error);
|
|
772
|
-
}));
|
|
773
|
-
const results = await Promise.allSettled(cleanupPromises);
|
|
774
|
-
const failed = results.filter((r) => r.status === 'rejected').length;
|
|
775
|
-
if (failed > 0) {
|
|
776
|
-
this.log(`Cleanup completed with ${failed} failures`);
|
|
777
|
-
}
|
|
778
|
-
else {
|
|
779
|
-
this.log('All containers cleaned up successfully');
|
|
643
|
+
cleanupAll() {
|
|
644
|
+
return this.activeCleanup ??= this.cleanupOwnedResources().finally(() => { this.activeCleanup = undefined; });
|
|
645
|
+
}
|
|
646
|
+
async cleanupOwnedResources() {
|
|
647
|
+
const results = await Promise.allSettled(Array.from(this.containers.values(), container => container.cleanup()));
|
|
648
|
+
const errors = results.flatMap(result => result.status === 'rejected' ? [result.reason] : []);
|
|
649
|
+
for (const network of this.networks.keys()) {
|
|
650
|
+
try {
|
|
651
|
+
await this.removeNetwork(network);
|
|
780
652
|
}
|
|
781
|
-
|
|
782
|
-
|
|
783
|
-
for (const network of networkArray) {
|
|
784
|
-
try {
|
|
785
|
-
this.log(`Removing network: ${network}`);
|
|
786
|
-
execFileSync(this.dockerPath, ['network', 'rm', network], { stdio: 'ignore' });
|
|
787
|
-
this.log(`Network removed: ${network}`);
|
|
788
|
-
}
|
|
789
|
-
catch (error) {
|
|
790
|
-
this.logError(`Failed to remove network ${network}`, error);
|
|
791
|
-
}
|
|
653
|
+
catch (error) {
|
|
654
|
+
errors.push(error);
|
|
792
655
|
}
|
|
793
|
-
this.containers.clear();
|
|
794
|
-
this.usedPorts.clear();
|
|
795
|
-
this.networks.clear();
|
|
796
|
-
this.log('Final cleanup completed');
|
|
797
|
-
}
|
|
798
|
-
finally {
|
|
799
|
-
this.cleanupInProgress = false;
|
|
800
656
|
}
|
|
657
|
+
if (errors.length)
|
|
658
|
+
throw new AggregateError(errors, 'Some Docker test resources could not be removed');
|
|
801
659
|
}
|
|
802
660
|
async cleanupAllAsync() {
|
|
803
661
|
this.log('Initiating graceful cleanup of all test containers');
|