@omnitron-dev/testing 0.4.4 → 0.4.6
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 +43 -0
- package/dist/async/events.js.map +1 -1
- package/dist/async/index.d.ts +5 -5
- package/dist/async/index.js +5 -5
- package/dist/async/index.js.map +1 -1
- package/dist/async/retry.js.map +1 -1
- package/dist/async/wait.js.map +1 -1
- package/dist/docker/database-manager.js +13 -15
- package/dist/docker/database-manager.js.map +1 -1
- package/dist/docker/docker-test-manager.d.ts +12 -3
- package/dist/docker/docker-test-manager.js +286 -255
- package/dist/docker/docker-test-manager.js.map +1 -1
- package/dist/docker/redis-manager.js +70 -95
- package/dist/docker/redis-manager.js.map +1 -1
- package/dist/docker/types.d.ts +7 -2
- package/dist/env.d.ts +11 -0
- package/dist/env.js +21 -0
- package/dist/env.js.map +1 -0
- package/dist/errors.js.map +1 -1
- package/dist/helpers/assertions.js +3 -3
- package/dist/helpers/assertions.js.map +1 -1
- package/dist/index.d.ts +1 -1
- package/dist/runtime/bun-adapter.d.ts +23 -1
- package/dist/runtime/bun-adapter.js +14 -1
- package/dist/runtime/bun-adapter.js.map +1 -1
- package/dist/runtime/deno-adapter.d.ts +72 -15
- package/dist/runtime/deno-adapter.js +93 -78
- package/dist/runtime/deno-adapter.js.map +1 -1
- package/dist/runtime/node-adapter.d.ts +15 -3
- package/dist/runtime/node-adapter.js +1 -1
- package/dist/runtime/node-adapter.js.map +1 -1
- package/dist/runtime/test-adapter.d.ts +1 -1
- package/dist/runtime/test-adapter.js +12 -14
- package/dist/runtime/test-adapter.js.map +1 -1
- package/dist/titan/database/database-testing.module.d.ts +7 -6
- package/dist/titan/database/database-testing.module.js +40 -26
- package/dist/titan/database/database-testing.module.js.map +1 -1
- package/dist/titan/database/index.d.ts +1 -1
- package/dist/titan/database/index.js +1 -1
- package/dist/titan/database/index.js.map +1 -1
- package/dist/titan/database/test-utilities.d.ts +2 -2
- package/dist/titan/database/test-utilities.js +3 -2
- package/dist/titan/database/test-utilities.js.map +1 -1
- package/dist/titan/index.d.ts +9 -9
- package/dist/titan/index.js +6 -6
- package/dist/titan/index.js.map +1 -1
- package/dist/titan/nexus/mock-provider.js +6 -6
- package/dist/titan/nexus/mock-provider.js.map +1 -1
- package/dist/titan/nexus/test-container.js +10 -10
- package/dist/titan/nexus/test-container.js.map +1 -1
- package/dist/titan/nexus/test-utilities.js +9 -9
- package/dist/titan/nexus/test-utilities.js.map +1 -1
- package/dist/titan/pm/mock-process-spawner.d.ts +4 -3
- package/dist/titan/pm/mock-process-spawner.js +37 -15
- package/dist/titan/pm/mock-process-spawner.js.map +1 -1
- package/dist/titan/pm/mock-spawner.d.ts +2 -1
- package/dist/titan/pm/mock-spawner.js +3 -1
- package/dist/titan/pm/mock-spawner.js.map +1 -1
- package/dist/titan/pm/test-process-manager.d.ts +4 -4
- package/dist/titan/pm/test-process-manager.js +7 -3
- package/dist/titan/pm/test-process-manager.js.map +1 -1
- package/dist/titan/redis-test-utils.d.ts +8 -2
- package/dist/titan/redis-test-utils.js +147 -92
- package/dist/titan/redis-test-utils.js.map +1 -1
- package/dist/titan/test-application.d.ts +1 -1
- package/dist/titan/test-application.js +1 -1
- package/dist/titan/test-application.js.map +1 -1
- package/dist/titan/test-fixtures.js.map +1 -1
- package/dist/titan/test-mocks.d.ts +12 -11
- package/dist/titan/test-mocks.js +49 -49
- package/dist/titan/test-mocks.js.map +1 -1
- package/dist/titan/test-module.js.map +1 -1
- package/package.json +66 -40
- package/src/async/events.ts +1 -1
- package/src/async/index.ts +5 -30
- package/src/async/retry.ts +1 -4
- package/src/async/wait.ts +1 -4
- package/src/docker/a-port-the-network-could-reach.spec.ts +66 -0
- package/src/docker/database-manager.ts +13 -15
- package/src/docker/docker-orphan-reaper.spec.ts +175 -0
- package/src/docker/docker-port-collision.spec.ts +97 -0
- package/src/docker/docker-test-manager.spec.ts +122 -0
- package/src/docker/docker-test-manager.ts +421 -327
- package/src/docker/docker-volume-cleanup.spec.ts +113 -0
- package/src/docker/redis-cluster-creation.spec.ts +52 -0
- package/src/docker/redis-manager.ts +87 -117
- package/src/docker/types.ts +11 -4
- package/src/env.spec.ts +20 -0
- package/src/env.ts +33 -0
- package/src/errors.ts +9 -2
- package/src/globals.d.ts +2 -2
- package/src/helpers/assertions.ts +4 -7
- package/src/index.ts +1 -1
- package/src/runtime/adapter-surface.spec.ts +83 -0
- package/src/runtime/bun-adapter.ts +36 -5
- package/src/runtime/deno-adapter.ts +167 -108
- package/src/runtime/node-adapter.ts +5 -5
- package/src/runtime/test-adapter.test.ts +1 -1
- package/src/runtime/test-adapter.ts +15 -17
- package/src/titan/database/database-testing.module.ts +73 -53
- package/src/titan/database/index.ts +2 -2
- package/src/titan/database/test-utilities.ts +6 -3
- package/src/titan/index.ts +13 -27
- package/src/titan/nexus/mock-provider.ts +12 -12
- package/src/titan/nexus/test-container.ts +25 -17
- package/src/titan/nexus/test-utilities.ts +13 -11
- package/src/titan/pm/mock-process-spawner.ts +80 -27
- package/src/titan/pm/mock-spawner.ts +10 -4
- package/src/titan/pm/test-process-manager.ts +26 -9
- package/src/titan/redis-test-utils.test.ts +102 -0
- package/src/titan/redis-test-utils.ts +191 -109
- package/src/titan/test-application.ts +2 -2
- package/src/titan/test-fixtures.ts +0 -1
- package/src/titan/test-mocks.ts +50 -50
- package/runtime/bun.d.ts +0 -2
- package/runtime/bun.js +0 -5
- package/runtime/bun.ts +0 -7
- package/runtime/deno.d.ts +0 -2
- package/runtime/deno.js +0 -4
- package/runtime/jest.d.ts +0 -2
- package/runtime/jest.js +0 -16
- package/runtime/jest.ts +0 -7
|
@@ -16,8 +16,9 @@ import {
|
|
|
16
16
|
* Test utility functions for Nexus testing
|
|
17
17
|
*/
|
|
18
18
|
|
|
19
|
-
//
|
|
20
|
-
|
|
19
|
+
// Vitest mock function type (declared for type checking but may not be used)
|
|
20
|
+
// eslint-disable-next-line @typescript-eslint/no-unused-vars
|
|
21
|
+
declare const vi: any;
|
|
21
22
|
|
|
22
23
|
/**
|
|
23
24
|
* Test mock configuration
|
|
@@ -53,6 +54,7 @@ export interface TestModuleConfig {
|
|
|
53
54
|
* Test harness configuration
|
|
54
55
|
*/
|
|
55
56
|
export interface TestHarnessConfig {
|
|
57
|
+
/** NOT READ — the harness never resolves or mounts this. */
|
|
56
58
|
component?: Constructor<any>;
|
|
57
59
|
providers?: Array<[InjectionToken<any>, ProviderDefinition<any>] | TestProvider<any>>;
|
|
58
60
|
zone?: {
|
|
@@ -190,7 +192,7 @@ export class IsolatedContainer extends Container {
|
|
|
190
192
|
try {
|
|
191
193
|
const value = source.resolve(token);
|
|
192
194
|
isolated.register(token, { useValue: value });
|
|
193
|
-
} catch (
|
|
195
|
+
} catch (_error) {
|
|
194
196
|
// Token not available in source
|
|
195
197
|
}
|
|
196
198
|
}
|
|
@@ -422,11 +424,11 @@ class RejectionExpectationImpl implements RejectionExpectation {
|
|
|
422
424
|
throw new Error('Expected resolution to throw');
|
|
423
425
|
} catch (error) {
|
|
424
426
|
if (this.expectedErrorType && !(error instanceof this.expectedErrorType)) {
|
|
425
|
-
throw new Error(`Expected ${this.expectedErrorType.name}, got ${(error as Error).constructor.name}
|
|
427
|
+
throw new Error(`Expected ${this.expectedErrorType.name}, got ${(error as Error).constructor.name}`, { cause: error });
|
|
426
428
|
}
|
|
427
429
|
|
|
428
430
|
if (this.expectedMessage && !(error as Error).message.includes(this.expectedMessage)) {
|
|
429
|
-
throw new Error(`Expected error message to contain "${this.expectedMessage}"
|
|
431
|
+
throw new Error(`Expected error message to contain "${this.expectedMessage}"`, { cause: error });
|
|
430
432
|
}
|
|
431
433
|
}
|
|
432
434
|
}
|
|
@@ -456,8 +458,8 @@ class DependencyExpectationImpl implements DependencyExpectation {
|
|
|
456
458
|
if (this.expectedToken) {
|
|
457
459
|
try {
|
|
458
460
|
this.container.resolve(this.expectedToken);
|
|
459
|
-
} catch (
|
|
460
|
-
throw new Error(`Dependency ${String(this.expectedToken)} not found
|
|
461
|
+
} catch (_error) {
|
|
462
|
+
throw new Error(`Dependency ${String(this.expectedToken)} not found`, { cause: _error });
|
|
461
463
|
}
|
|
462
464
|
}
|
|
463
465
|
}
|
|
@@ -597,18 +599,18 @@ export async function assertThrows<E extends Error>(
|
|
|
597
599
|
throw new Error('Expected function to throw');
|
|
598
600
|
} catch (error) {
|
|
599
601
|
if (errorType && !(error instanceof errorType)) {
|
|
600
|
-
throw new Error(`Expected error of type ${errorType.name}, got ${(error as Error).constructor.name}
|
|
602
|
+
throw new Error(`Expected error of type ${errorType.name}, got ${(error as Error).constructor.name}`, { cause: error });
|
|
601
603
|
}
|
|
602
604
|
|
|
603
605
|
if (message) {
|
|
604
606
|
const errorMessage = (error as Error).message;
|
|
605
607
|
if (typeof message === 'string') {
|
|
606
608
|
if (!errorMessage.includes(message)) {
|
|
607
|
-
throw new Error(`Expected error message to include "${message}", got "${errorMessage}"
|
|
609
|
+
throw new Error(`Expected error message to include "${message}", got "${errorMessage}"`, { cause: error });
|
|
608
610
|
}
|
|
609
611
|
} else if (message instanceof RegExp) {
|
|
610
612
|
if (!message.test(errorMessage)) {
|
|
611
|
-
throw new Error(`Expected error message to match ${message}, got "${errorMessage}"
|
|
613
|
+
throw new Error(`Expected error message to match ${message}, got "${errorMessage}"`, { cause: error });
|
|
612
614
|
}
|
|
613
615
|
}
|
|
614
616
|
}
|
|
@@ -636,7 +638,7 @@ export function verifyContainerState(
|
|
|
636
638
|
spies?: Array<{ token: Token<any>; method: string }>;
|
|
637
639
|
}
|
|
638
640
|
): void {
|
|
639
|
-
const
|
|
641
|
+
const _metadata = container.getTestMetadata();
|
|
640
642
|
|
|
641
643
|
if (expectations.registeredTokens) {
|
|
642
644
|
for (const token of expectations.registeredTokens) {
|
|
@@ -7,9 +7,9 @@
|
|
|
7
7
|
|
|
8
8
|
import { EventEmitter } from 'events';
|
|
9
9
|
import path from 'path';
|
|
10
|
-
import {
|
|
10
|
+
import { generateUuidV7 } from '@omnitron-dev/titan/utils';
|
|
11
11
|
import { Errors } from '@omnitron-dev/titan/errors';
|
|
12
|
-
import type { ProcessMethod } from '@omnitron-dev/titan
|
|
12
|
+
import type { ProcessMethod } from '@omnitron-dev/titan-pm';
|
|
13
13
|
import type { ILogger } from '@omnitron-dev/titan/module/logger';
|
|
14
14
|
import type {
|
|
15
15
|
IProcessSpawner,
|
|
@@ -18,9 +18,9 @@ import type {
|
|
|
18
18
|
IProcessManagerConfig,
|
|
19
19
|
IProcessMetrics,
|
|
20
20
|
IHealthStatus,
|
|
21
|
-
} from '@omnitron-dev/titan
|
|
22
|
-
import { ProcessStatus } from '@omnitron-dev/titan
|
|
23
|
-
import { PROCESS_METHOD_METADATA_KEY } from '@omnitron-dev/titan
|
|
21
|
+
} from '@omnitron-dev/titan-pm';
|
|
22
|
+
import { ProcessStatus } from '@omnitron-dev/titan-pm';
|
|
23
|
+
import { PROCESS_METHOD_METADATA_KEY } from '@omnitron-dev/titan-pm';
|
|
24
24
|
|
|
25
25
|
/**
|
|
26
26
|
* Mock worker that runs in the same thread
|
|
@@ -48,7 +48,7 @@ export class MockWorker extends EventEmitter {
|
|
|
48
48
|
// Create instance with options
|
|
49
49
|
try {
|
|
50
50
|
this.instance = new ProcessClass(options.config || {});
|
|
51
|
-
} catch (
|
|
51
|
+
} catch (_error) {
|
|
52
52
|
// If instantiation fails, create a simple object
|
|
53
53
|
this.instance = {};
|
|
54
54
|
}
|
|
@@ -61,7 +61,14 @@ export class MockWorker extends EventEmitter {
|
|
|
61
61
|
// Setup internal methods
|
|
62
62
|
this.setupInternalMethods();
|
|
63
63
|
|
|
64
|
-
//
|
|
64
|
+
// Don't emit ready here - let the spawner call notifyReady() after setup
|
|
65
|
+
this._status = ProcessStatus.STARTING;
|
|
66
|
+
}
|
|
67
|
+
|
|
68
|
+
/**
|
|
69
|
+
* Notify that the worker is ready (called by spawner after listener is attached)
|
|
70
|
+
*/
|
|
71
|
+
notifyReady(): void {
|
|
65
72
|
setImmediate(() => {
|
|
66
73
|
this._status = ProcessStatus.RUNNING;
|
|
67
74
|
this.emit('message', { type: 'ready' });
|
|
@@ -125,7 +132,6 @@ export class MockWorker extends EventEmitter {
|
|
|
125
132
|
const result = await this.publicMethods.get('checkHealth')!();
|
|
126
133
|
// Normalize the result to IHealthStatus format
|
|
127
134
|
if (result && typeof result === 'object') {
|
|
128
|
-
// eslint-disable-next-line @typescript-eslint/no-explicit-any
|
|
129
135
|
const healthResult = result as any;
|
|
130
136
|
// If it already has the correct format, return as-is
|
|
131
137
|
if ('status' in healthResult && 'checks' in healthResult && 'timestamp' in healthResult) {
|
|
@@ -167,8 +173,10 @@ export class MockWorker extends EventEmitter {
|
|
|
167
173
|
|
|
168
174
|
/**
|
|
169
175
|
* Call a method on the mock worker
|
|
176
|
+
* Note: This method returns Promise<unknown> but for async generators,
|
|
177
|
+
* it returns the generator directly (not wrapped in a promise)
|
|
170
178
|
*/
|
|
171
|
-
|
|
179
|
+
callMethod(methodName: string, args: unknown[]): unknown {
|
|
172
180
|
const method = this.publicMethods.get(methodName);
|
|
173
181
|
if (!method) {
|
|
174
182
|
if (this.metrics) this.metrics.errors = (this.metrics.errors || 0) + 1;
|
|
@@ -179,12 +187,23 @@ export class MockWorker extends EventEmitter {
|
|
|
179
187
|
if (this.metrics) this.metrics.requests = (this.metrics.requests || 0) + 1;
|
|
180
188
|
const result = method(...args);
|
|
181
189
|
|
|
182
|
-
//
|
|
183
|
-
|
|
184
|
-
|
|
190
|
+
// Check for async generator FIRST - it has Symbol.asyncIterator
|
|
191
|
+
// AsyncGenerators are thenable but we should NOT await them
|
|
192
|
+
if (result && typeof result === 'object' && typeof (result as any)[Symbol.asyncIterator] === 'function') {
|
|
193
|
+
return result;
|
|
194
|
+
}
|
|
195
|
+
|
|
196
|
+
// If the method returns a promise (but NOT an async generator), await it
|
|
197
|
+
if (
|
|
198
|
+
result &&
|
|
199
|
+
typeof result === 'object' &&
|
|
200
|
+
'then' in result &&
|
|
201
|
+
typeof (result as Promise<unknown>).then === 'function'
|
|
202
|
+
) {
|
|
203
|
+
return result as Promise<unknown>;
|
|
185
204
|
}
|
|
186
205
|
|
|
187
|
-
// Return as-is for
|
|
206
|
+
// Return as-is for sync values
|
|
188
207
|
return result;
|
|
189
208
|
} catch (error) {
|
|
190
209
|
if (this.metrics) this.metrics.errors = (this.metrics.errors || 0) + 1;
|
|
@@ -215,7 +234,7 @@ export class MockWorker extends EventEmitter {
|
|
|
215
234
|
if (this.publicMethods.has('onShutdown')) {
|
|
216
235
|
try {
|
|
217
236
|
await this.publicMethods.get('onShutdown')!();
|
|
218
|
-
} catch (
|
|
237
|
+
} catch (_error) {
|
|
219
238
|
// Ignore shutdown errors
|
|
220
239
|
}
|
|
221
240
|
}
|
|
@@ -331,22 +350,52 @@ export class MockWorkerHandle implements IWorkerHandle {
|
|
|
331
350
|
|
|
332
351
|
if (isStreamMethod) {
|
|
333
352
|
const workerInstance = this.worker;
|
|
334
|
-
//
|
|
335
|
-
|
|
336
|
-
|
|
337
|
-
|
|
338
|
-
//
|
|
353
|
+
// For streaming methods, we need to detect if the result is actually an async generator
|
|
354
|
+
// Some methods like "processStream" contain "stream" but return Promise<T>, not AsyncGenerator
|
|
355
|
+
|
|
356
|
+
return (...args: any[]): any => {
|
|
357
|
+
// Call the method
|
|
358
|
+
const result = workerInstance.callMethod(methodName, args);
|
|
359
|
+
|
|
339
360
|
const anyResult = result as any;
|
|
361
|
+
|
|
362
|
+
// If result is already an async iterable (AsyncGenerator), return it directly
|
|
340
363
|
if (anyResult && typeof anyResult[Symbol.asyncIterator] === 'function') {
|
|
341
364
|
return anyResult;
|
|
342
365
|
}
|
|
343
|
-
|
|
344
|
-
|
|
366
|
+
|
|
367
|
+
// If result is a sync iterable (but NOT a Promise), convert to async generator
|
|
368
|
+
if (
|
|
369
|
+
anyResult &&
|
|
370
|
+
typeof anyResult[Symbol.iterator] === 'function' &&
|
|
371
|
+
typeof anyResult.then !== 'function'
|
|
372
|
+
) {
|
|
373
|
+
// eslint-disable-next-line func-names
|
|
345
374
|
return (async function* () {
|
|
346
375
|
yield* anyResult;
|
|
347
376
|
})();
|
|
348
377
|
}
|
|
349
|
-
|
|
378
|
+
|
|
379
|
+
// If it's a Promise, we need to check what it resolves to
|
|
380
|
+
if (anyResult && typeof anyResult.then === 'function') {
|
|
381
|
+
// Return a Promise that resolves to the actual value
|
|
382
|
+
// If the resolved value is an async iterable, wrap it properly
|
|
383
|
+
return (async () => {
|
|
384
|
+
const resolved = await anyResult;
|
|
385
|
+
// If resolved is an async iterable, we can't return it directly from an async function
|
|
386
|
+
// because the caller expects to iterate over the result of the original call
|
|
387
|
+
// For methods that return Promise<AsyncIterable>, this is a limitation
|
|
388
|
+
// But for methods that return Promise<T> (like processStream -> Promise<number[]>),
|
|
389
|
+
// we just return the resolved value
|
|
390
|
+
if (resolved && typeof resolved[Symbol.asyncIterator] === 'function') {
|
|
391
|
+
// Can't properly handle Promise<AsyncIterable> in mock - return as-is
|
|
392
|
+
return resolved;
|
|
393
|
+
}
|
|
394
|
+
return resolved;
|
|
395
|
+
})();
|
|
396
|
+
}
|
|
397
|
+
|
|
398
|
+
// Otherwise return as-is
|
|
350
399
|
return result;
|
|
351
400
|
};
|
|
352
401
|
}
|
|
@@ -407,7 +456,7 @@ export class MockProcessSpawner implements IProcessSpawner {
|
|
|
407
456
|
processPathOrClass: string | (new (...args: any[]) => T),
|
|
408
457
|
options: ISpawnOptions = {}
|
|
409
458
|
): Promise<IWorkerHandle> {
|
|
410
|
-
const processId = options.processId ||
|
|
459
|
+
const processId = options.processId || generateUuidV7();
|
|
411
460
|
|
|
412
461
|
let ProcessClass: new (...args: any[]) => T;
|
|
413
462
|
let serviceName: string;
|
|
@@ -429,7 +478,7 @@ export class MockProcessSpawner implements IProcessSpawner {
|
|
|
429
478
|
}
|
|
430
479
|
}
|
|
431
480
|
serviceName = options.name || path.basename(processPathOrClass, '.js');
|
|
432
|
-
} catch (
|
|
481
|
+
} catch (_error) {
|
|
433
482
|
// If import fails in test, create a simple mock class
|
|
434
483
|
ProcessClass = class MockProcess {
|
|
435
484
|
constructor() {}
|
|
@@ -451,8 +500,8 @@ export class MockProcessSpawner implements IProcessSpawner {
|
|
|
451
500
|
// Create handle
|
|
452
501
|
const handle = new MockWorkerHandle(processId, worker, transportUrl, serviceName, serviceVersion, this.logger);
|
|
453
502
|
|
|
454
|
-
// Wait for ready
|
|
455
|
-
|
|
503
|
+
// Wait for ready - set up listener FIRST, then trigger ready
|
|
504
|
+
const readyPromise = new Promise<void>((resolve) => {
|
|
456
505
|
worker.once('message', (data) => {
|
|
457
506
|
if (data.type === 'ready') {
|
|
458
507
|
resolve();
|
|
@@ -460,6 +509,10 @@ export class MockProcessSpawner implements IProcessSpawner {
|
|
|
460
509
|
});
|
|
461
510
|
});
|
|
462
511
|
|
|
512
|
+
// Now trigger the ready event (after listener is attached)
|
|
513
|
+
worker.notifyReady();
|
|
514
|
+
|
|
515
|
+
await readyPromise;
|
|
463
516
|
return handle;
|
|
464
517
|
}
|
|
465
518
|
|
|
@@ -468,7 +521,7 @@ export class MockProcessSpawner implements IProcessSpawner {
|
|
|
468
521
|
*/
|
|
469
522
|
async cleanup(): Promise<void> {
|
|
470
523
|
// Terminate all workers
|
|
471
|
-
for (const [
|
|
524
|
+
for (const [_id, worker] of this.workers) {
|
|
472
525
|
await worker.terminate();
|
|
473
526
|
}
|
|
474
527
|
this.workers.clear();
|
|
@@ -8,10 +8,10 @@
|
|
|
8
8
|
import { EventEmitter } from 'events';
|
|
9
9
|
import { Netron } from '@omnitron-dev/titan/netron';
|
|
10
10
|
import { Errors } from '@omnitron-dev/titan/errors';
|
|
11
|
-
import type { ProcessMethod } from '@omnitron-dev/titan
|
|
11
|
+
import type { ProcessMethod } from '@omnitron-dev/titan-pm';
|
|
12
12
|
import type { ILogger } from '@omnitron-dev/titan/module/logger';
|
|
13
|
-
import type { IProcessOptions, IProcessManagerConfig } from '@omnitron-dev/titan
|
|
14
|
-
import { PROCESS_METHOD_METADATA_KEY } from '@omnitron-dev/titan
|
|
13
|
+
import type { IProcessOptions, IProcessManagerConfig } from '@omnitron-dev/titan-pm';
|
|
14
|
+
import { PROCESS_METHOD_METADATA_KEY } from '@omnitron-dev/titan-pm';
|
|
15
15
|
|
|
16
16
|
/**
|
|
17
17
|
* Mock worker that runs in the same thread
|
|
@@ -70,7 +70,13 @@ class MockWorker extends EventEmitter {
|
|
|
70
70
|
};
|
|
71
71
|
});
|
|
72
72
|
|
|
73
|
-
//
|
|
73
|
+
// Don't emit ready here - let the spawner call notifyReady() after setup
|
|
74
|
+
}
|
|
75
|
+
|
|
76
|
+
/**
|
|
77
|
+
* Notify that the worker is ready (called by spawner after listener is attached)
|
|
78
|
+
*/
|
|
79
|
+
notifyReady(): void {
|
|
74
80
|
setImmediate(() => {
|
|
75
81
|
this.emit('message', { type: 'ready' });
|
|
76
82
|
});
|
|
@@ -6,10 +6,11 @@
|
|
|
6
6
|
*/
|
|
7
7
|
|
|
8
8
|
import { Errors } from '@omnitron-dev/titan/errors';
|
|
9
|
-
import { ProcessManager } from '@omnitron-dev/titan
|
|
10
|
-
import { ProcessStatus } from '@omnitron-dev/titan
|
|
11
|
-
import type { IProcessOptions, IProcessInfo, ServiceProxy, IProcessManagerConfig } from '@omnitron-dev/titan
|
|
9
|
+
import { ProcessManager, ProcessSpawnerFactory } from '@omnitron-dev/titan-pm';
|
|
10
|
+
import { ProcessStatus } from '@omnitron-dev/titan-pm';
|
|
11
|
+
import type { IProcessOptions, IProcessInfo, ServiceProxy, IProcessManagerConfig } from '@omnitron-dev/titan-pm';
|
|
12
12
|
import { createNullLogger } from '@omnitron-dev/titan/module/logger';
|
|
13
|
+
import { MockProcessSpawner } from './mock-process-spawner.js';
|
|
13
14
|
|
|
14
15
|
/**
|
|
15
16
|
* Test process manager configuration
|
|
@@ -17,9 +18,19 @@ import { createNullLogger } from '@omnitron-dev/titan/module/logger';
|
|
|
17
18
|
export interface ITestProcessManagerConfig extends IProcessManagerConfig {
|
|
18
19
|
/** Use mock spawner for faster tests */
|
|
19
20
|
mock?: boolean;
|
|
20
|
-
/**
|
|
21
|
+
/**
|
|
22
|
+
* Control time for testing
|
|
23
|
+
*
|
|
24
|
+
* NOT IMPLEMENTED — read by nothing; no clock is installed or advanced.
|
|
25
|
+
*/
|
|
21
26
|
controlTime?: boolean;
|
|
22
|
-
/**
|
|
27
|
+
/**
|
|
28
|
+
* Record all operations for verification
|
|
29
|
+
*
|
|
30
|
+
* NOT READ as a toggle: recording is always on. The default object below
|
|
31
|
+
* sets it to `true` and nothing consults it, so setting `false` records
|
|
32
|
+
* anyway.
|
|
33
|
+
*/
|
|
23
34
|
recordOperations?: boolean;
|
|
24
35
|
}
|
|
25
36
|
|
|
@@ -50,6 +61,12 @@ export class TestProcessManager extends ProcessManager {
|
|
|
50
61
|
// Use null logger for tests - silent by default
|
|
51
62
|
const logger = createNullLogger();
|
|
52
63
|
|
|
64
|
+
// Register MockProcessSpawner before creating ProcessManager
|
|
65
|
+
// This ensures the factory can use it when useMockSpawner is true
|
|
66
|
+
if (config.mock !== false) {
|
|
67
|
+
ProcessSpawnerFactory.setMockSpawner(MockProcessSpawner);
|
|
68
|
+
}
|
|
69
|
+
|
|
53
70
|
super(logger, {
|
|
54
71
|
...config,
|
|
55
72
|
testing: {
|
|
@@ -66,14 +83,14 @@ export class TestProcessManager extends ProcessManager {
|
|
|
66
83
|
* Setup test-specific event handlers
|
|
67
84
|
*/
|
|
68
85
|
private setupTestHandlers(): void {
|
|
69
|
-
this.on('process:crash', (info, error) => {
|
|
86
|
+
this.on('process:crash', (info: IProcessInfo, error: Error) => {
|
|
70
87
|
const handler = this.crashHandlers.get(info.id);
|
|
71
88
|
if (handler) {
|
|
72
89
|
handler();
|
|
73
90
|
}
|
|
74
91
|
});
|
|
75
92
|
|
|
76
|
-
this.on('process:ready', (info) => {
|
|
93
|
+
this.on('process:ready', (info: IProcessInfo) => {
|
|
77
94
|
const handler = this.recoveryHandlers.get(info.id);
|
|
78
95
|
if (handler) {
|
|
79
96
|
handler();
|
|
@@ -117,7 +134,7 @@ export class TestProcessManager extends ProcessManager {
|
|
|
117
134
|
// Kill the actual process if it exists but preserve CRASHED status
|
|
118
135
|
try {
|
|
119
136
|
await this.kill(processId, 'SIGKILL');
|
|
120
|
-
} catch (
|
|
137
|
+
} catch (_e) {
|
|
121
138
|
// Ignore errors during simulated crash
|
|
122
139
|
}
|
|
123
140
|
|
|
@@ -288,7 +305,7 @@ export class TestProcessManager extends ProcessManager {
|
|
|
288
305
|
/**
|
|
289
306
|
* Create a spy for a process method
|
|
290
307
|
*/
|
|
291
|
-
spyOnMethod<T>(proxy: ServiceProxy<T>, methodName: keyof T):
|
|
308
|
+
spyOnMethod<T>(proxy: ServiceProxy<T>, methodName: keyof T): any {
|
|
292
309
|
const original = (proxy as any)[methodName];
|
|
293
310
|
const calls: any[] = [];
|
|
294
311
|
|
|
@@ -0,0 +1,102 @@
|
|
|
1
|
+
import { mkdtempSync, rmSync, writeFileSync } from 'node:fs';
|
|
2
|
+
import { tmpdir } from 'node:os';
|
|
3
|
+
import { join } from 'node:path';
|
|
4
|
+
import { afterEach, beforeEach, describe, expect, it, vi } from 'vitest';
|
|
5
|
+
|
|
6
|
+
const doubles = vi.hoisted(() => ({
|
|
7
|
+
clients: [] as Array<{ options: Record<string, unknown>; disconnect: ReturnType<typeof vi.fn>; flushdb: ReturnType<typeof vi.fn> }>,
|
|
8
|
+
init: vi.fn(),
|
|
9
|
+
destroy: vi.fn(),
|
|
10
|
+
connectionError: null as Error | null,
|
|
11
|
+
}));
|
|
12
|
+
|
|
13
|
+
vi.mock('ioredis', async () => {
|
|
14
|
+
const { EventEmitter } = await import('node:events');
|
|
15
|
+
return {
|
|
16
|
+
Redis: class extends EventEmitter {
|
|
17
|
+
status = 'connecting';
|
|
18
|
+
disconnect = vi.fn();
|
|
19
|
+
flushdb = vi.fn().mockResolvedValue('OK');
|
|
20
|
+
constructor(public options: Record<string, unknown>) {
|
|
21
|
+
super();
|
|
22
|
+
doubles.clients.push(this);
|
|
23
|
+
if (!options.lazyConnect) queueMicrotask(() => {
|
|
24
|
+
if (doubles.connectionError) this.emit('error', doubles.connectionError);
|
|
25
|
+
else this.emit('ready');
|
|
26
|
+
});
|
|
27
|
+
}
|
|
28
|
+
},
|
|
29
|
+
};
|
|
30
|
+
});
|
|
31
|
+
vi.mock('@omnitron-dev/titan-redis', () => ({
|
|
32
|
+
RedisManager: class {
|
|
33
|
+
onModuleInit = doubles.init;
|
|
34
|
+
onModuleDestroy = doubles.destroy;
|
|
35
|
+
},
|
|
36
|
+
RedisService: class {},
|
|
37
|
+
}));
|
|
38
|
+
|
|
39
|
+
import { createRedisTestFixture } from './redis-test-utils.js';
|
|
40
|
+
|
|
41
|
+
let directory: string;
|
|
42
|
+
beforeEach(() => {
|
|
43
|
+
directory = mkdtempSync(join(tmpdir(), 'titan-redis-fixture-'));
|
|
44
|
+
vi.stubEnv('TITAN_TEST_REDIS_INFO', join(directory, 'endpoint.json'));
|
|
45
|
+
vi.stubEnv('TEST_REDIS_HOST', '127.0.0.2');
|
|
46
|
+
vi.stubEnv('TEST_REDIS_PORT', '26379');
|
|
47
|
+
vi.stubEnv('USE_MOCK_REDIS', 'false');
|
|
48
|
+
vi.stubEnv('SKIP_DOCKER_TESTS', 'false');
|
|
49
|
+
doubles.clients.length = 0;
|
|
50
|
+
doubles.connectionError = null;
|
|
51
|
+
doubles.init.mockReset().mockResolvedValue(undefined);
|
|
52
|
+
doubles.destroy.mockReset().mockResolvedValue(undefined);
|
|
53
|
+
});
|
|
54
|
+
afterEach(() => {
|
|
55
|
+
vi.unstubAllEnvs();
|
|
56
|
+
rmSync(directory, { recursive: true, force: true });
|
|
57
|
+
});
|
|
58
|
+
|
|
59
|
+
describe('shared Redis test fixture', () => {
|
|
60
|
+
it('uses the isolated endpoint instead of a developer Redis on 6379', async () => {
|
|
61
|
+
const fixture = await createRedisTestFixture();
|
|
62
|
+
expect(fixture.options).toMatchObject({ host: '127.0.0.2', port: 26379, db: 15 });
|
|
63
|
+
await fixture.cleanup();
|
|
64
|
+
});
|
|
65
|
+
|
|
66
|
+
it('honors global setup and explicit overrides', async () => {
|
|
67
|
+
writeFileSync(join(directory, 'endpoint.json'), JSON.stringify({ port: 26380 }));
|
|
68
|
+
const selected = await createRedisTestFixture();
|
|
69
|
+
expect(selected.options.port).toBe(26380);
|
|
70
|
+
await selected.cleanup();
|
|
71
|
+
const explicit = await createRedisTestFixture({ host: '127.0.0.3', port: 26381, db: 12 });
|
|
72
|
+
expect(explicit.options).toMatchObject({ host: '127.0.0.3', port: 26381, db: 12 });
|
|
73
|
+
await explicit.cleanup();
|
|
74
|
+
});
|
|
75
|
+
|
|
76
|
+
it('does not open a real client when setup selected mock mode', async () => {
|
|
77
|
+
writeFileSync(join(directory, 'endpoint.json'), JSON.stringify({ isMock: true }));
|
|
78
|
+
await expect(createRedisTestFixture()).rejects.toThrow('setup selected mock mode');
|
|
79
|
+
expect(doubles.clients).toHaveLength(0);
|
|
80
|
+
});
|
|
81
|
+
|
|
82
|
+
it('closes the client if the initial connection fails', async () => {
|
|
83
|
+
doubles.connectionError = new Error('connection refused');
|
|
84
|
+
await expect(createRedisTestFixture()).rejects.toThrow('connection refused');
|
|
85
|
+
expect(doubles.clients[0]?.disconnect).toHaveBeenCalledOnce();
|
|
86
|
+
});
|
|
87
|
+
|
|
88
|
+
it('closes all allocated clients if manager initialization fails', async () => {
|
|
89
|
+
doubles.init.mockRejectedValue(new Error('manager unavailable'));
|
|
90
|
+
await expect(createRedisTestFixture({ withManager: true })).rejects.toThrow('manager unavailable');
|
|
91
|
+
expect(doubles.destroy).toHaveBeenCalledOnce();
|
|
92
|
+
expect(doubles.clients[0]?.disconnect).toHaveBeenCalledOnce();
|
|
93
|
+
});
|
|
94
|
+
|
|
95
|
+
it('releases connections and reports a failed cleanup instead of swallowing it', async () => {
|
|
96
|
+
const fixture = await createRedisTestFixture({ withManager: true });
|
|
97
|
+
doubles.clients[0]?.flushdb.mockRejectedValue(new Error('Redis disconnected'));
|
|
98
|
+
await expect(fixture.cleanup()).rejects.toThrow('Redis disconnected');
|
|
99
|
+
expect(doubles.destroy).toHaveBeenCalledOnce();
|
|
100
|
+
expect(doubles.clients[0]?.disconnect).toHaveBeenCalledOnce();
|
|
101
|
+
});
|
|
102
|
+
});
|