@omnitron-dev/testing 0.4.5 → 0.4.8

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 (116) hide show
  1. package/README.md +36 -0
  2. package/dist/async/events.js.map +1 -1
  3. package/dist/async/retry.js.map +1 -1
  4. package/dist/async/wait.js.map +1 -1
  5. package/dist/docker/database-manager.js +13 -15
  6. package/dist/docker/database-manager.js.map +1 -1
  7. package/dist/docker/docker-test-manager.d.ts +12 -3
  8. package/dist/docker/docker-test-manager.js +286 -255
  9. package/dist/docker/docker-test-manager.js.map +1 -1
  10. package/dist/docker/redis-manager.js +68 -94
  11. package/dist/docker/redis-manager.js.map +1 -1
  12. package/dist/docker/types.d.ts +7 -2
  13. package/dist/env.d.ts +11 -0
  14. package/dist/env.js +21 -0
  15. package/dist/env.js.map +1 -0
  16. package/dist/errors.js.map +1 -1
  17. package/dist/helpers/assertions.js +3 -3
  18. package/dist/helpers/assertions.js.map +1 -1
  19. package/dist/index.d.ts +1 -1
  20. package/dist/runtime/bun-adapter.d.ts +23 -1
  21. package/dist/runtime/bun-adapter.js +14 -1
  22. package/dist/runtime/bun-adapter.js.map +1 -1
  23. package/dist/runtime/deno-adapter.d.ts +72 -15
  24. package/dist/runtime/deno-adapter.js +93 -78
  25. package/dist/runtime/deno-adapter.js.map +1 -1
  26. package/dist/runtime/node-adapter.d.ts +15 -3
  27. package/dist/runtime/node-adapter.js +1 -1
  28. package/dist/runtime/node-adapter.js.map +1 -1
  29. package/dist/runtime/test-adapter.d.ts +1 -1
  30. package/dist/runtime/test-adapter.js +12 -14
  31. package/dist/runtime/test-adapter.js.map +1 -1
  32. package/dist/titan/database/database-testing.module.d.ts +7 -6
  33. package/dist/titan/database/database-testing.module.js +39 -18
  34. package/dist/titan/database/database-testing.module.js.map +1 -1
  35. package/dist/titan/database/index.d.ts +1 -1
  36. package/dist/titan/database/index.js +1 -1
  37. package/dist/titan/database/index.js.map +1 -1
  38. package/dist/titan/database/test-utilities.d.ts +2 -2
  39. package/dist/titan/database/test-utilities.js +3 -2
  40. package/dist/titan/database/test-utilities.js.map +1 -1
  41. package/dist/titan/index.d.ts +4 -4
  42. package/dist/titan/index.js +3 -3
  43. package/dist/titan/index.js.map +1 -1
  44. package/dist/titan/nexus/mock-provider.js +6 -6
  45. package/dist/titan/nexus/mock-provider.js.map +1 -1
  46. package/dist/titan/nexus/test-container.js +10 -10
  47. package/dist/titan/nexus/test-container.js.map +1 -1
  48. package/dist/titan/nexus/test-utilities.js +9 -9
  49. package/dist/titan/nexus/test-utilities.js.map +1 -1
  50. package/dist/titan/pm/mock-process-spawner.d.ts +4 -3
  51. package/dist/titan/pm/mock-process-spawner.js +33 -14
  52. package/dist/titan/pm/mock-process-spawner.js.map +1 -1
  53. package/dist/titan/pm/mock-spawner.d.ts +2 -1
  54. package/dist/titan/pm/mock-spawner.js +3 -1
  55. package/dist/titan/pm/mock-spawner.js.map +1 -1
  56. package/dist/titan/pm/test-process-manager.d.ts +4 -4
  57. package/dist/titan/pm/test-process-manager.js +7 -3
  58. package/dist/titan/pm/test-process-manager.js.map +1 -1
  59. package/dist/titan/redis-test-utils.d.ts +8 -2
  60. package/dist/titan/redis-test-utils.js +147 -92
  61. package/dist/titan/redis-test-utils.js.map +1 -1
  62. package/dist/titan/test-application.d.ts +1 -1
  63. package/dist/titan/test-application.js +1 -1
  64. package/dist/titan/test-application.js.map +1 -1
  65. package/dist/titan/test-fixtures.js.map +1 -1
  66. package/dist/titan/test-mocks.d.ts +12 -11
  67. package/dist/titan/test-mocks.js +49 -49
  68. package/dist/titan/test-mocks.js.map +1 -1
  69. package/dist/titan/test-module.js.map +1 -1
  70. package/package.json +66 -40
  71. package/src/async/README.md +18 -328
  72. package/src/async/events.ts +1 -1
  73. package/src/docker/a-port-the-network-could-reach.spec.ts +66 -0
  74. package/src/docker/database-manager.ts +13 -15
  75. package/src/docker/docker-orphan-reaper.spec.ts +175 -0
  76. package/src/docker/docker-port-collision.spec.ts +97 -0
  77. package/src/docker/docker-test-manager.spec.ts +122 -0
  78. package/src/docker/docker-test-manager.ts +420 -326
  79. package/src/docker/docker-volume-cleanup.spec.ts +113 -0
  80. package/src/docker/redis-cluster-creation.spec.ts +52 -0
  81. package/src/docker/redis-manager.ts +80 -115
  82. package/src/docker/types.ts +11 -4
  83. package/src/env.spec.ts +20 -0
  84. package/src/env.ts +33 -0
  85. package/src/globals.d.ts +2 -2
  86. package/src/helpers/assertions.ts +3 -3
  87. package/src/index.ts +1 -1
  88. package/src/runtime/adapter-surface.spec.ts +83 -0
  89. package/src/runtime/bun-adapter.ts +36 -5
  90. package/src/runtime/deno-adapter.ts +167 -108
  91. package/src/runtime/node-adapter.ts +5 -5
  92. package/src/runtime/test-adapter.test.ts +1 -1
  93. package/src/runtime/test-adapter.ts +15 -17
  94. package/src/titan/database/database-testing.module.ts +63 -22
  95. package/src/titan/database/index.ts +2 -2
  96. package/src/titan/database/test-utilities.ts +6 -3
  97. package/src/titan/index.ts +8 -1
  98. package/src/titan/nexus/mock-provider.ts +12 -12
  99. package/src/titan/nexus/test-container.ts +12 -12
  100. package/src/titan/nexus/test-utilities.ts +13 -11
  101. package/src/titan/pm/mock-process-spawner.ts +74 -26
  102. package/src/titan/pm/mock-spawner.ts +10 -4
  103. package/src/titan/pm/test-process-manager.ts +26 -9
  104. package/src/titan/redis-test-utils.test.ts +102 -0
  105. package/src/titan/redis-test-utils.ts +191 -109
  106. package/src/titan/test-application.ts +2 -2
  107. package/src/titan/test-fixtures.ts +0 -1
  108. package/src/titan/test-mocks.ts +50 -50
  109. package/runtime/bun.d.ts +0 -2
  110. package/runtime/bun.js +0 -5
  111. package/runtime/bun.ts +0 -7
  112. package/runtime/deno.d.ts +0 -2
  113. package/runtime/deno.js +0 -4
  114. package/runtime/jest.d.ts +0 -2
  115. package/runtime/jest.js +0 -16
  116. package/runtime/jest.ts +0 -7
@@ -1,336 +1,26 @@
1
- # Async Testing Utilities
1
+ # Async test helpers
2
2
 
3
- Comprehensive utilities for testing asynchronous code in JavaScript/TypeScript.
3
+ Import these helpers from `@omnitron-dev/testing/async`. They coordinate asynchronous tests, observe events, and bound how long an assertion waits.
4
4
 
5
- ## Installation
5
+ ```ts
6
+ import { createDeferred, withTimeout } from '@omnitron-dev/testing/async';
6
7
 
7
- ```bash
8
- pnpm add -D @omnitron-dev/testing
8
+ const ready = createDeferred<string>();
9
+ const result = withTimeout(ready.promise, 1_000, 'Service did not become ready');
10
+ ready.resolve('ready');
11
+ await result;
9
12
  ```
10
13
 
11
- ## Usage
14
+ | Helper | Purpose |
15
+ | --- | --- |
16
+ | [`createDeferred`, `DeferredPromise`, `defer`](deferred.ts) | Explicitly resolve or reject a promise |
17
+ | [`waitFor`, `waitForCondition`, `delay`, `flushPromises`](wait.ts) | Poll a condition or advance asynchronous work |
18
+ | [`retry`, `withTimeout`](retry.ts) | Retry an operation or time out waiting for a promise |
19
+ | [Event trackers and collectors](events.ts) | Record calls and await event sequences |
20
+ | [Mock timer controller](mock-timer.ts) | Manage fake timers in a test |
12
21
 
13
- Import from the main package or the async submodule:
22
+ `withTimeout` rejects the wait; it does not cancel the underlying operation. `waitFor` checks its deadline between condition evaluations, so the condition must itself settle. Always release resources owned by the operation in teardown.
14
23
 
15
- ```typescript
16
- // Import from main package
17
- import { defer, waitFor, retry } from '@omnitron-dev/testing';
24
+ The current `retry` option named `retries` is the total attempt count, including the first attempt. Its default is three attempts. Choose explicit bounds for tests that exercise failure paths.
18
25
 
19
- // Or import from async submodule
20
- import { defer, waitFor, retry } from '@omnitron-dev/testing/async';
21
- ```
22
-
23
- ## API Reference
24
-
25
- ### Deferred Promises
26
-
27
- #### `DeferredPromise<T>`
28
- Class for creating a promise with external control over resolution/rejection.
29
-
30
- ```typescript
31
- const deferred = new DeferredPromise<string>();
32
- setTimeout(() => deferred.resolve('done'), 1000);
33
- await deferred.promise; // 'done'
34
- console.log(deferred.isSettled); // true
35
- ```
36
-
37
- #### `createDeferred<T>()`
38
- Factory function for creating deferred promises.
39
-
40
- ```typescript
41
- const deferred = createDeferred<number>();
42
- deferred.resolve(42);
43
- ```
44
-
45
- #### `defer<T>()`
46
- Lightweight deferred promise (backward compatible).
47
-
48
- ```typescript
49
- const deferred = defer<string>();
50
- deferred.resolve('success');
51
- await deferred.promise;
52
- ```
53
-
54
- ### Retry and Timeout
55
-
56
- #### `retry<T>(fn, options?)`
57
- Retry an async operation with exponential backoff.
58
-
59
- ```typescript
60
- const result = await retry(
61
- async () => fetchData(),
62
- {
63
- retries: 5,
64
- delay: 100,
65
- backoff: 2,
66
- onRetry: (error, attempt) => console.log(`Retry ${attempt}`)
67
- }
68
- );
69
- ```
70
-
71
- **Options:**
72
- - `retries`: Maximum retry attempts (default: 3)
73
- - `delay`: Initial delay in ms (default: 100)
74
- - `backoff`: Backoff multiplier (default: 2)
75
- - `onRetry`: Callback on each retry
76
-
77
- #### `withTimeout<T>(promise, timeout?, errorMessage?)`
78
- Race a promise against a timeout.
79
-
80
- ```typescript
81
- const result = await withTimeout(
82
- fetchData(),
83
- 5000,
84
- 'Data fetch timed out'
85
- );
86
- ```
87
-
88
- ### Wait Utilities
89
-
90
- #### `waitFor(condition, options?)`
91
- Wait for a condition to become true.
92
-
93
- ```typescript
94
- await waitFor(
95
- () => element.isVisible(),
96
- { timeout: 3000, interval: 100, message: 'Element not visible' }
97
- );
98
- ```
99
-
100
- #### `waitForCondition(condition, timeout?, interval?)`
101
- Alternative API for waiting on conditions.
102
-
103
- ```typescript
104
- await waitForCondition(
105
- () => counter > 10,
106
- 5000,
107
- 100
108
- );
109
- ```
110
-
111
- #### `delay(ms)`
112
- Simple async sleep utility.
113
-
114
- ```typescript
115
- await delay(1000); // Wait 1 second
116
- ```
117
-
118
- #### `nextTick()`
119
- Wait for the next event loop tick.
120
-
121
- ```typescript
122
- emitter.emit('event');
123
- await nextTick();
124
- // Event handlers have now executed
125
- ```
126
-
127
- #### `flushPromises()`
128
- Flush all pending promises in the event loop.
129
-
130
- ```typescript
131
- Promise.resolve().then(() => { executed = true });
132
- await flushPromises();
133
- expect(executed).toBe(true);
134
- ```
135
-
136
- ### Event Utilities
137
-
138
- #### `EventListenerTracker`
139
- Track event listeners for automatic cleanup.
140
-
141
- ```typescript
142
- const tracker = new EventListenerTracker();
143
- tracker.on(emitter, 'data', handler);
144
- tracker.once(emitter, 'error', errorHandler);
145
-
146
- // In cleanup
147
- tracker.cleanup(); // Removes all tracked listeners
148
- ```
149
-
150
- #### `EventCollector<T>`
151
- Collect events for inspection and assertions.
152
-
153
- ```typescript
154
- const collector = new EventCollector(emitter);
155
- collector.collect('data');
156
-
157
- // Trigger events...
158
-
159
- const events = collector.getEvents('data');
160
- expect(events).toHaveLength(3);
161
-
162
- collector.assertEmitted('data', 3);
163
- collector.clear();
164
- collector.stop();
165
- ```
166
-
167
- #### `waitForEvents(target, events, timeout?)`
168
- Wait for multiple events to be emitted.
169
-
170
- ```typescript
171
- const [userData, profileData] = await waitForEvents(
172
- emitter,
173
- ['user', 'profile'],
174
- 3000
175
- );
176
- ```
177
-
178
- #### `collectEvents<T>(target, event, condition, timeout?)`
179
- Collect events until a condition is met.
180
-
181
- ```typescript
182
- const events = await collectEvents(
183
- emitter,
184
- 'data',
185
- (events) => events.length >= 5,
186
- 3000
187
- );
188
- ```
189
-
190
- #### `createEventSpy(target, event)`
191
- Create a spy to record events.
192
-
193
- ```typescript
194
- const spy = createEventSpy(emitter, 'data');
195
- // Trigger events...
196
- expect(spy.events).toHaveLength(3);
197
- spy.clear();
198
- ```
199
-
200
- ### Mock Timers
201
-
202
- #### `MockTimerController`
203
- Manual control over timers for deterministic testing.
204
-
205
- ```typescript
206
- const timer = new MockTimerController();
207
- timer.install();
208
-
209
- let executed = false;
210
- setTimeout(() => { executed = true }, 1000);
211
-
212
- timer.tick(500); // executed is still false
213
- timer.tick(500); // executed is now true
214
-
215
- timer.restore();
216
- ```
217
-
218
- **Methods:**
219
- - `install()`: Replace native timers
220
- - `restore()`: Restore native timers
221
- - `tick(ms)`: Advance time by ms
222
- - `getCurrentTime()`: Get current mock time
223
- - `getPendingCount()`: Get number of pending timers
224
- - `clearAll()`: Clear all pending timers
225
- - `reset()`: Reset to initial state
226
-
227
- #### `createMockTimer()`
228
- Factory function for creating mock timers.
229
-
230
- ```typescript
231
- const timer = createMockTimer();
232
- timer.install();
233
- // ... test code ...
234
- timer.restore();
235
- ```
236
-
237
- ## Error Handling
238
-
239
- All async utilities use typed errors from `@omnitron-dev/testing/errors`:
240
-
241
- - `TimeoutError`: Thrown when operations timeout
242
- - `TestingError`: Base class for testing errors
243
-
244
- ```typescript
245
- import { TimeoutError } from '@omnitron-dev/testing';
246
-
247
- try {
248
- await waitFor(() => false, { timeout: 100 });
249
- } catch (error) {
250
- if (error instanceof TimeoutError) {
251
- console.log('Operation timed out');
252
- }
253
- }
254
- ```
255
-
256
- ## Examples
257
-
258
- ### Testing Event Sequences
259
-
260
- ```typescript
261
- import { EventCollector, delay } from '@omnitron-dev/testing/async';
262
-
263
- test('event sequence', async () => {
264
- const emitter = new EventEmitter();
265
- const collector = new EventCollector(emitter);
266
-
267
- collector.collect('start');
268
- collector.collect('data');
269
- collector.collect('end');
270
-
271
- // Trigger events
272
- await processData(emitter);
273
-
274
- collector.assertEmitted('start', 1);
275
- collector.assertEmitted('data', 5);
276
- collector.assertEmitted('end', 1);
277
-
278
- collector.stop();
279
- });
280
- ```
281
-
282
- ### Retrying Flaky Operations
283
-
284
- ```typescript
285
- import { retry } from '@omnitron-dev/testing/async';
286
-
287
- test('retry flaky operation', async () => {
288
- const result = await retry(
289
- async () => {
290
- const response = await fetch('/api/data');
291
- if (!response.ok) throw new Error('Failed');
292
- return response.json();
293
- },
294
- {
295
- retries: 3,
296
- delay: 100,
297
- backoff: 2,
298
- onRetry: (error, attempt) => {
299
- console.log(`Retry ${attempt}: ${error.message}`);
300
- }
301
- }
302
- );
303
-
304
- expect(result).toBeDefined();
305
- });
306
- ```
307
-
308
- ### Testing Time-Dependent Code
309
-
310
- ```typescript
311
- import { MockTimerController } from '@omnitron-dev/testing/async';
312
-
313
- test('debounce function', () => {
314
- const timer = new MockTimerController();
315
- timer.install();
316
-
317
- let count = 0;
318
- const debounced = debounce(() => { count++; }, 100);
319
-
320
- debounced();
321
- debounced();
322
- debounced();
323
-
324
- timer.tick(50);
325
- expect(count).toBe(0);
326
-
327
- timer.tick(50);
328
- expect(count).toBe(1);
329
-
330
- timer.restore();
331
- });
332
- ```
333
-
334
- ## License
335
-
336
- MIT
26
+ [The export list](index.ts) defines the available functions and types.
@@ -3,7 +3,7 @@
3
3
  */
4
4
 
5
5
  import { TimeoutError } from '../errors.js';
6
- import { defer, type Deferred } from './deferred.js';
6
+ import { defer } from './deferred.js';
7
7
 
8
8
  /**
9
9
  * Event listener tracker for cleanup
@@ -0,0 +1,66 @@
1
+ /**
2
+ * A port the network could reach.
3
+ *
4
+ * `createContainer` published every port as `-p <host>:<container>`, which
5
+ * docker binds on 0.0.0.0 — and docker's forwarding sits in front of the host
6
+ * firewall, so a test Postgres or Redis with its default credentials was a
7
+ * service the LAN could log into for as long as the suite ran. Measured on
8
+ * this machine in sample on 2026-09-16: its test Postgres answered a login from
9
+ * another address on the network. omni's own `docker-compose.test.yml`
10
+ * published `0.0.0.0:15432` (test/test) the same way until 2026-09-29.
11
+ *
12
+ * Held here, on a real container: what the manager publishes is bound to the
13
+ * loopback, which is also the address `isPortAvailable` probes. The compose
14
+ * files are held by `scripts/a-port-the-network-could-reach.mjs`.
15
+ */
16
+ import { describe, it, expect, afterAll } from 'vitest';
17
+ import { execFileSync } from 'node:child_process';
18
+
19
+ import { DockerTestManager } from './docker-test-manager.js';
20
+
21
+ /** Docker's time, not the behaviour's — see docker-port-collision.spec.ts. */
22
+ const DOCKER_BUDGET_MS = 300_000;
23
+
24
+ function docker(...args: string[]): string {
25
+ return execFileSync('docker', args, { encoding: 'utf-8', stdio: ['ignore', 'pipe', 'ignore'] }).trim();
26
+ }
27
+
28
+ function dockerAvailable(): boolean {
29
+ try {
30
+ docker('version', '--format', '{{.Server.Version}}');
31
+ return true;
32
+ } catch {
33
+ return false;
34
+ }
35
+ }
36
+
37
+ const describeOrSkip = dockerAvailable() ? describe : describe.skip;
38
+ if (!dockerAvailable()) {
39
+ console.log('⏭️ Skipping a-port-the-network-could-reach.spec.ts - requires Docker');
40
+ }
41
+
42
+ describeOrSkip('DockerTestManager publishes on the loopback only', () => {
43
+ const manager = new DockerTestManager();
44
+ const name = `loopback-probe-${process.pid}`;
45
+
46
+ afterAll(() => {
47
+ try {
48
+ docker('rm', '-f', name);
49
+ } catch {
50
+ // already gone
51
+ }
52
+ });
53
+
54
+ it('binds an auto port to 127.0.0.1, not to every interface', async () => {
55
+ await manager.createContainer({ name, image: 'redis:7-alpine', ports: { 6379: 'auto' } });
56
+
57
+ const bindings = JSON.parse(docker('inspect', '-f', '{{json .HostConfig.PortBindings}}', name)) as Record<
58
+ string,
59
+ Array<{ HostIp: string; HostPort: string }>
60
+ >;
61
+ expect(bindings['6379/tcp']?.map((b) => b.HostIp)).toEqual(['127.0.0.1']);
62
+ // What docker actually listens on, not only what it was asked for.
63
+ const published = docker('port', name, '6379/tcp').split('\n');
64
+ expect(published.every((line) => line.startsWith('127.0.0.1:'))).toBe(true);
65
+ }, DOCKER_BUDGET_MS);
66
+ });
@@ -86,18 +86,17 @@ export class DatabaseTestManager {
86
86
  POSTGRES_DB: database,
87
87
  POSTGRES_USER: user,
88
88
  POSTGRES_PASSWORD: password,
89
- POSTGRES_HOST_AUTH_METHOD: 'trust',
90
89
  },
91
90
  healthcheck: {
92
- test: ['CMD-SHELL', `pg_isready -U ${user}`],
91
+ test: ['CMD', 'pg_isready', '-h', '127.0.0.1', '-U', user, '-d', database],
93
92
  interval: '1s',
94
- timeout: '3s',
95
- retries: 5,
96
- startPeriod: '2s',
93
+ timeout: '5s',
94
+ retries: 30,
95
+ startPeriod: '5s',
97
96
  },
98
97
  waitFor: {
99
98
  healthcheck: true,
100
- timeout: 30000,
99
+ timeout: 45000,
101
100
  },
102
101
  });
103
102
  }
@@ -149,18 +148,17 @@ export class DatabaseTestManager {
149
148
  MYSQL_USER: user,
150
149
  MYSQL_PASSWORD: password,
151
150
  MYSQL_ROOT_PASSWORD: rootPassword,
152
- MYSQL_ALLOW_EMPTY_PASSWORD: 'yes',
153
151
  },
154
152
  healthcheck: {
155
- test: ['CMD', 'mysqladmin', 'ping', '-h', 'localhost'],
156
- interval: '1s',
157
- timeout: '3s',
158
- retries: 10,
159
- startPeriod: '5s',
153
+ test: ['CMD', 'mysqladmin', 'ping', '--protocol=tcp', '-h', '127.0.0.1'],
154
+ interval: '2s',
155
+ timeout: '10s',
156
+ retries: 25,
157
+ startPeriod: '20s',
160
158
  },
161
159
  waitFor: {
162
160
  healthcheck: true,
163
- timeout: 30000,
161
+ timeout: 90000, // MySQL 8.0 can take longer to initialize
164
162
  },
165
163
  });
166
164
  }
@@ -194,7 +192,7 @@ export class DatabaseTestManager {
194
192
  const database = options?.database || 'testdb';
195
193
  const user = options?.user || 'testuser';
196
194
  const password = options?.password || 'testpass';
197
- const connectionString = `postgresql://${user}:${password}@localhost:${port}/${database}`;
195
+ const connectionString = `postgresql://${encodeURIComponent(user)}:${encodeURIComponent(password)}@localhost:${port}/${encodeURIComponent(database)}`;
198
196
 
199
197
  try {
200
198
  return await testFn(container, connectionString);
@@ -231,7 +229,7 @@ export class DatabaseTestManager {
231
229
  const database = options?.database || 'testdb';
232
230
  const user = options?.user || 'testuser';
233
231
  const password = options?.password || 'testpass';
234
- const connectionString = `mysql://${user}:${password}@localhost:${port}/${database}`;
232
+ const connectionString = `mysql://${encodeURIComponent(user)}:${encodeURIComponent(password)}@localhost:${port}/${encodeURIComponent(database)}`;
235
233
 
236
234
  try {
237
235
  return await testFn(container, connectionString);
@@ -0,0 +1,175 @@
1
+ /**
2
+ * A test run that is killed leaves its containers running forever.
3
+ *
4
+ * `cleanup` is wired to `process.on('exit')`, `SIGINT` and `SIGTERM`, which
5
+ * covers every ending the process gets to observe. It does not cover SIGKILL,
6
+ * and that is the ending vitest uses when a worker overruns its teardown — so
7
+ * the containers of a killed run keep their ports, their memory and their
8
+ * anonymous volumes, and nothing on the machine is left holding a reference to
9
+ * them.
10
+ *
11
+ * Measured on this machine: `docker ps -a --filter label=test.cleanup=true`
12
+ * returned 67 containers, some `Up 7 hours`, some still in `Created` — from
13
+ * runs that had ended hours earlier. Their layers and volumes were a large part
14
+ * of a Docker VM at 93% (191.2 G of 205.4 G), which is what turned
15
+ * `titan-redis` (45 failures, 112 × "no space") and every `test/security` file
16
+ * in payments (19 failures, all `TRUNCATE` in `beforeEach`) red. None of those
17
+ * failures were in the code they named.
18
+ *
19
+ * The `test.manager` label already carries the creating process's pid, so an
20
+ * orphan is identifiable without guessing: the process that owns it is gone.
21
+ * Two conditions, both required, because either one alone can be wrong —
22
+ *
23
+ * - the owner pid is not alive. A pid can be REUSED, so this alone could call
24
+ * a live manager's container someone else's;
25
+ * - the container is older than a grace period. A container seconds old
26
+ * belongs to a run that is starting, whatever the pid table says.
27
+ *
28
+ * Reaping needs both, so a container is removed only when it is both
29
+ * unclaimed and not new. The failure direction of each condition is to leave
30
+ * a container behind, which the next run reaps — never to remove a live one.
31
+ */
32
+ import { describe, it, expect, vi, beforeEach } from 'vitest';
33
+
34
+ const execFileSyncMock = vi.fn<(...args: any[]) => any>(() => '');
35
+
36
+ vi.mock('node:child_process', async (importOriginal) => {
37
+ const actual = await importOriginal<typeof import('node:child_process')>();
38
+ return { ...actual, execFileSync: (...args: unknown[]) => execFileSyncMock(...args) };
39
+ });
40
+ vi.mock('child_process', async (importOriginal) => {
41
+ const actual = await importOriginal<typeof import('child_process')>();
42
+ return { ...actual, execFileSync: (...args: unknown[]) => execFileSyncMock(...args) };
43
+ });
44
+
45
+ const { DockerTestManager } = await import('./docker-test-manager.js');
46
+
47
+ /** A pid above Linux/macOS pid_max: `kill(pid, 0)` is guaranteed ESRCH. */
48
+ const DEAD_PID = 9_999_999;
49
+
50
+ /** `docker ps --format` renders this shape; the reaper has to read it back. */
51
+ function psRow(id: string, ageMs: number, managerId: string): string {
52
+ const created = new Date(Date.now() - ageMs);
53
+ const pad = (n: number) => String(n).padStart(2, '0');
54
+ const stamp =
55
+ `${created.getFullYear()}-${pad(created.getMonth() + 1)}-${pad(created.getDate())} ` +
56
+ `${pad(created.getHours())}:${pad(created.getMinutes())}:${pad(created.getSeconds())} ` +
57
+ `${offset(created)} MSK`;
58
+ return `${id}\t${stamp}\ttest.cleanup=true,test.id=${id},test.manager=${managerId}`;
59
+ }
60
+
61
+ function offset(d: Date): string {
62
+ const mins = -d.getTimezoneOffset();
63
+ const sign = mins < 0 ? '-' : '+';
64
+ const abs = Math.abs(mins);
65
+ return `${sign}${String(Math.floor(abs / 60)).padStart(2, '0')}${String(abs % 60).padStart(2, '0')}`;
66
+ }
67
+
68
+ function removedIds(): string[] {
69
+ return execFileSyncMock.mock.calls
70
+ .map((c) => c[1] as string[])
71
+ .filter((args) => Array.isArray(args) && args[0] === 'rm')
72
+ .flatMap((args) => args.filter((a) => a.startsWith('orphan') || a.startsWith('live') || a.startsWith('fresh')));
73
+ }
74
+
75
+ function armPs(rows: string[]) {
76
+ execFileSyncMock.mockImplementation((_bin: string, args: string[]) => {
77
+ if (args?.[0] === 'ps') return rows.join('\n');
78
+ return '';
79
+ });
80
+ }
81
+
82
+ describe('DockerTestManager orphan reaper', () => {
83
+ beforeEach(() => {
84
+ execFileSyncMock.mockReset();
85
+ execFileSyncMock.mockReturnValue('');
86
+ (DockerTestManager as any).orphanReapDone = false;
87
+ });
88
+
89
+ it('removes a container whose owning process is gone', () => {
90
+ armPs([psRow('orphan-1', 2 * 60 * 60 * 1000, `${DEAD_PID}-abc-def`)]);
91
+
92
+ new DockerTestManager();
93
+
94
+ expect(removedIds()).toEqual(['orphan-1']);
95
+ });
96
+
97
+ it('keeps a container whose owning process is still running', () => {
98
+ // A parallel vitest run is exactly this: another worker, alive, with
99
+ // containers this manager must not touch. Removing them is how the
100
+ // previous label-wide cleanup broke parallel runs.
101
+ armPs([psRow('live-1', 2 * 60 * 60 * 1000, `${process.pid}-abc-def`)]);
102
+
103
+ new DockerTestManager();
104
+
105
+ expect(removedIds()).toEqual([]);
106
+ });
107
+
108
+ it('keeps a container that is younger than the grace period', () => {
109
+ // Pids are reused. A container created a minute ago belongs to a run that
110
+ // is starting, whatever the pid table now says about its creator.
111
+ armPs([psRow('fresh-1', 30 * 1000, `${DEAD_PID}-abc-def`)]);
112
+
113
+ new DockerTestManager();
114
+
115
+ expect(removedIds()).toEqual([]);
116
+ });
117
+
118
+ it('reaps in one call rather than one call per container', () => {
119
+ // 67 orphans at ~200 ms per `docker rm` is 13 s added to the start of a
120
+ // test file, paid by every worker at once.
121
+ armPs([
122
+ psRow('orphan-1', 2 * 60 * 60 * 1000, `${DEAD_PID}-a-b`),
123
+ psRow('orphan-2', 2 * 60 * 60 * 1000, `${DEAD_PID}-c-d`),
124
+ psRow('orphan-3', 2 * 60 * 60 * 1000, `${DEAD_PID}-e-f`),
125
+ ]);
126
+
127
+ new DockerTestManager();
128
+
129
+ const rmCalls = execFileSyncMock.mock.calls
130
+ .map((c) => c[1] as string[])
131
+ .filter((args) => Array.isArray(args) && args[0] === 'rm');
132
+
133
+ expect(rmCalls.length, 'one removal call expected for all orphans').toBe(1);
134
+ expect(removedIds()).toEqual(['orphan-1', 'orphan-2', 'orphan-3']);
135
+ });
136
+
137
+ it('removes anonymous volumes along with the orphan', () => {
138
+ // The orphan holds the same anonymous volume a normal removal would drop;
139
+ // reaping without -v converts a container leak into a volume leak.
140
+ armPs([psRow('orphan-1', 2 * 60 * 60 * 1000, `${DEAD_PID}-a-b`)]);
141
+
142
+ new DockerTestManager();
143
+
144
+ const rmArgs = execFileSyncMock.mock.calls
145
+ .map((c) => c[1] as string[])
146
+ .find((args) => Array.isArray(args) && args[0] === 'rm');
147
+
148
+ expect(rmArgs).toContain('-v');
149
+ expect(rmArgs).toContain('-f');
150
+ });
151
+
152
+ it('runs once per process, not once per manager', () => {
153
+ armPs([]);
154
+
155
+ new DockerTestManager();
156
+ const afterFirst = execFileSyncMock.mock.calls.filter((c) => (c[1] as string[])?.[0] === 'ps').length;
157
+ new DockerTestManager();
158
+ const afterSecond = execFileSyncMock.mock.calls.filter((c) => (c[1] as string[])?.[0] === 'ps').length;
159
+
160
+ expect(afterFirst).toBe(1);
161
+ expect(afterSecond).toBe(1);
162
+ });
163
+
164
+ it('survives docker being unavailable', () => {
165
+ // The reaper runs in a constructor. A machine without a reachable docker
166
+ // must still get a manager — the failure belongs to the first container
167
+ // command, with its own message, not to construction.
168
+ execFileSyncMock.mockImplementation((_bin: string, args: string[]) => {
169
+ if (args?.[0] === 'ps') throw new Error('Cannot connect to the Docker daemon');
170
+ return '';
171
+ });
172
+
173
+ expect(() => new DockerTestManager()).not.toThrow();
174
+ });
175
+ });