@omnitron-dev/testing 0.4.5 → 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.
Files changed (115) hide show
  1. package/README.md +43 -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/events.ts +1 -1
  72. package/src/docker/a-port-the-network-could-reach.spec.ts +66 -0
  73. package/src/docker/database-manager.ts +13 -15
  74. package/src/docker/docker-orphan-reaper.spec.ts +175 -0
  75. package/src/docker/docker-port-collision.spec.ts +97 -0
  76. package/src/docker/docker-test-manager.spec.ts +122 -0
  77. package/src/docker/docker-test-manager.ts +420 -326
  78. package/src/docker/docker-volume-cleanup.spec.ts +113 -0
  79. package/src/docker/redis-cluster-creation.spec.ts +52 -0
  80. package/src/docker/redis-manager.ts +80 -115
  81. package/src/docker/types.ts +11 -4
  82. package/src/env.spec.ts +20 -0
  83. package/src/env.ts +33 -0
  84. package/src/globals.d.ts +2 -2
  85. package/src/helpers/assertions.ts +3 -3
  86. package/src/index.ts +1 -1
  87. package/src/runtime/adapter-surface.spec.ts +83 -0
  88. package/src/runtime/bun-adapter.ts +36 -5
  89. package/src/runtime/deno-adapter.ts +167 -108
  90. package/src/runtime/node-adapter.ts +5 -5
  91. package/src/runtime/test-adapter.test.ts +1 -1
  92. package/src/runtime/test-adapter.ts +15 -17
  93. package/src/titan/database/database-testing.module.ts +63 -22
  94. package/src/titan/database/index.ts +2 -2
  95. package/src/titan/database/test-utilities.ts +6 -3
  96. package/src/titan/index.ts +8 -1
  97. package/src/titan/nexus/mock-provider.ts +12 -12
  98. package/src/titan/nexus/test-container.ts +12 -12
  99. package/src/titan/nexus/test-utilities.ts +13 -11
  100. package/src/titan/pm/mock-process-spawner.ts +74 -26
  101. package/src/titan/pm/mock-spawner.ts +10 -4
  102. package/src/titan/pm/test-process-manager.ts +26 -9
  103. package/src/titan/redis-test-utils.test.ts +102 -0
  104. package/src/titan/redis-test-utils.ts +191 -109
  105. package/src/titan/test-application.ts +2 -2
  106. package/src/titan/test-fixtures.ts +0 -1
  107. package/src/titan/test-mocks.ts +50 -50
  108. package/runtime/bun.d.ts +0 -2
  109. package/runtime/bun.js +0 -5
  110. package/runtime/bun.ts +0 -7
  111. package/runtime/deno.d.ts +0 -2
  112. package/runtime/deno.js +0 -4
  113. package/runtime/jest.d.ts +0 -2
  114. package/runtime/jest.js +0 -16
  115. package/runtime/jest.ts +0 -7
@@ -7,9 +7,9 @@
7
7
 
8
8
  import { EventEmitter } from 'events';
9
9
  import path from 'path';
10
- import { v4 as uuidv4 } from 'uuid';
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/module/pm';
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/module/pm';
22
- import { ProcessStatus } from '@omnitron-dev/titan/module/pm';
23
- import { PROCESS_METHOD_METADATA_KEY } from '@omnitron-dev/titan/module/pm';
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 (error) {
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
- // Emit ready immediately
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
- async callMethod(methodName: string, args: unknown[]): Promise<unknown> {
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,17 +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
- // If the method returns a promise, await it
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
183
197
  if (
184
198
  result &&
185
199
  typeof result === 'object' &&
186
200
  'then' in result &&
187
201
  typeof (result as Promise<unknown>).then === 'function'
188
202
  ) {
189
- return await (result as Promise<unknown>);
203
+ return result as Promise<unknown>;
190
204
  }
191
205
 
192
- // Return as-is for async generators and other values
206
+ // Return as-is for sync values
193
207
  return result;
194
208
  } catch (error) {
195
209
  if (this.metrics) this.metrics.errors = (this.metrics.errors || 0) + 1;
@@ -220,7 +234,7 @@ export class MockWorker extends EventEmitter {
220
234
  if (this.publicMethods.has('onShutdown')) {
221
235
  try {
222
236
  await this.publicMethods.get('onShutdown')!();
223
- } catch (error) {
237
+ } catch (_error) {
224
238
  // Ignore shutdown errors
225
239
  }
226
240
  }
@@ -336,22 +350,52 @@ export class MockWorkerHandle implements IWorkerHandle {
336
350
 
337
351
  if (isStreamMethod) {
338
352
  const workerInstance = this.worker;
339
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
340
- return async (...args: any[]): Promise<any> => {
341
- const result = await workerInstance.callMethod(methodName, args);
342
- // If result is already an async iterable, return it directly
343
- // eslint-disable-next-line @typescript-eslint/no-explicit-any
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
+
344
360
  const anyResult = result as any;
361
+
362
+ // If result is already an async iterable (AsyncGenerator), return it directly
345
363
  if (anyResult && typeof anyResult[Symbol.asyncIterator] === 'function') {
346
364
  return anyResult;
347
365
  }
348
- // If result is a sync iterable, convert to async
349
- if (anyResult && typeof anyResult[Symbol.iterator] === 'function') {
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
350
374
  return (async function* () {
351
375
  yield* anyResult;
352
376
  })();
353
377
  }
354
- // Otherwise return as normal async result
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
355
399
  return result;
356
400
  };
357
401
  }
@@ -412,7 +456,7 @@ export class MockProcessSpawner implements IProcessSpawner {
412
456
  processPathOrClass: string | (new (...args: any[]) => T),
413
457
  options: ISpawnOptions = {}
414
458
  ): Promise<IWorkerHandle> {
415
- const processId = options.processId || uuidv4();
459
+ const processId = options.processId || generateUuidV7();
416
460
 
417
461
  let ProcessClass: new (...args: any[]) => T;
418
462
  let serviceName: string;
@@ -434,7 +478,7 @@ export class MockProcessSpawner implements IProcessSpawner {
434
478
  }
435
479
  }
436
480
  serviceName = options.name || path.basename(processPathOrClass, '.js');
437
- } catch (error) {
481
+ } catch (_error) {
438
482
  // If import fails in test, create a simple mock class
439
483
  ProcessClass = class MockProcess {
440
484
  constructor() {}
@@ -456,8 +500,8 @@ export class MockProcessSpawner implements IProcessSpawner {
456
500
  // Create handle
457
501
  const handle = new MockWorkerHandle(processId, worker, transportUrl, serviceName, serviceVersion, this.logger);
458
502
 
459
- // Wait for ready
460
- await new Promise<void>((resolve) => {
503
+ // Wait for ready - set up listener FIRST, then trigger ready
504
+ const readyPromise = new Promise<void>((resolve) => {
461
505
  worker.once('message', (data) => {
462
506
  if (data.type === 'ready') {
463
507
  resolve();
@@ -465,6 +509,10 @@ export class MockProcessSpawner implements IProcessSpawner {
465
509
  });
466
510
  });
467
511
 
512
+ // Now trigger the ready event (after listener is attached)
513
+ worker.notifyReady();
514
+
515
+ await readyPromise;
468
516
  return handle;
469
517
  }
470
518
 
@@ -473,7 +521,7 @@ export class MockProcessSpawner implements IProcessSpawner {
473
521
  */
474
522
  async cleanup(): Promise<void> {
475
523
  // Terminate all workers
476
- for (const [id, worker] of this.workers) {
524
+ for (const [_id, worker] of this.workers) {
477
525
  await worker.terminate();
478
526
  }
479
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/module/pm';
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/module/pm';
14
- import { PROCESS_METHOD_METADATA_KEY } from '@omnitron-dev/titan/module/pm';
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
- // Emit ready after a small delay
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/module/pm';
10
- import { ProcessStatus } from '@omnitron-dev/titan/module/pm';
11
- import type { IProcessOptions, IProcessInfo, ServiceProxy, IProcessManagerConfig } from '@omnitron-dev/titan/module/pm';
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
- /** Control time for testing */
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
- /** Record all operations for verification */
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 (e) {
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): jest.SpyInstance | any {
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
+ });