@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.
@@ -22,7 +22,18 @@ const execFileSyncMock = vi.fn(() => '');
22
22
 
23
23
  vi.mock('node:child_process', async (importOriginal) => {
24
24
  const actual = await importOriginal<typeof import('node:child_process')>();
25
- return { ...actual, execFileSync: (...args: unknown[]) => execFileSyncMock(...args) };
25
+ return { ...actual, execFileSync: (...args: unknown[]) => execFileSyncMock(...args),
26
+ execFile: (...args: unknown[]) => {
27
+ const callback = args.pop() as (error: unknown, stdout: string, stderr: string) => void;
28
+ queueMicrotask(() => {
29
+ try { callback(null, execFileSyncMock(...args), ''); }
30
+ catch (error) {
31
+ const failure = error as { status?: number; stdout?: string; stderr?: string };
32
+ callback({ code: failure.status ?? 1 }, failure.stdout ?? '', failure.stderr ?? '');
33
+ }
34
+ });
35
+ },
36
+ };
26
37
  });
27
38
 
28
39
  const { DockerTestManager } = await import('./docker-test-manager.js');
@@ -33,23 +44,59 @@ describe('DockerTestManager container removal', () => {
33
44
  execFileSyncMock.mockReturnValue('');
34
45
  });
35
46
 
36
- it('passes -v everywhere it removes a container', async () => {
37
- const manager = new DockerTestManager();
47
+ it('removes anonymous volumes using the immutable ID returned by Docker', async () => {
48
+ const dockerId = 'a'.repeat(64);
49
+ execFileSyncMock.mockImplementation((_exe, args) => args[0] === 'run' ? dockerId : '');
50
+ const manager = DockerTestManager.getInstance({ dockerPath: 'docker', cleanup: false });
51
+ const container = await manager.createContainer({ name: 'volume-flag-probe', image: 'redis:7-alpine' });
52
+ await container.cleanup();
53
+ const removals = execFileSyncMock.mock.calls.map(call => call[1]).filter(args => args[0] === 'rm');
54
+ expect(removals).toEqual([['rm', '-f', '-v', dockerId]]);
55
+ });
38
56
 
39
- // Any path that removes a container will do; createContainer clears a stale
40
- // one by name before starting, which is the first of the six call sites.
41
- await manager
42
- .createContainer({ name: 'volume-flag-probe', image: 'redis:7-alpine' })
43
- .catch(() => undefined);
57
+ it('leaves existing containers and networks owned by another caller alone', async () => {
58
+ const collision = Object.assign(new Error('fixture'), { status: 125, stderr: 'The container name "/foreign" is already in use' });
59
+ execFileSyncMock.mockImplementation((_exe, args) => {
60
+ if (args[0] === 'network' && args[1] === 'create') throw Object.assign(new Error('fixture'), { stderr: 'network already exists' });
61
+ if (args[0] === 'run') throw collision;
62
+ return '';
63
+ });
64
+ const manager = DockerTestManager.getInstance({ dockerPath: 'docker', cleanup: false });
65
+ await expect(manager.createContainer({ name: 'foreign', image: 'redis:7-alpine', networks: ['shared'] })).rejects.toThrow('name conflict');
66
+ await manager.cleanupAll();
67
+ expect(execFileSyncMock.mock.calls.map(call => call[1]).filter(args => args.includes('rm') || args.includes('stop'))).toEqual([]);
68
+ });
44
69
 
45
- const removals = execFileSyncMock.mock.calls
46
- .map((c) => c[1] as string[])
47
- .filter((args) => Array.isArray(args) && args[0] === 'rm');
70
+ it.skipIf(process.platform === 'win32')('keeps CMD input literal and reserves owner labels', async () => {
71
+ const id = 'b'.repeat(64);
72
+ let run: string[] = [];
73
+ execFileSyncMock.mockImplementation((_exe, args) => {
74
+ if (args[0] === 'run') { run = args; return id; }
75
+ return '';
76
+ });
77
+ const manager = DockerTestManager.getInstance({ dockerPath: 'docker', cleanup: false });
78
+ const literal = "a' b; $(echo INJECTED)";
79
+ const container = await manager.createContainer({ image: 'fixture', labels: { 'test.id': 'foreign' },
80
+ healthcheck: { test: ['CMD', 'printf', '%s', literal] } });
81
+ expect(container.labels['test.id']).toBe(container.id);
82
+ const command = run[run.indexOf('--health-cmd') + 1];
83
+ const { execFileSync } = await vi.importActual<typeof import('node:child_process')>('node:child_process');
84
+ expect(execFileSync('/bin/sh', ['-c', command], { encoding: 'utf8' })).toBe(literal);
85
+ await container.cleanup();
86
+ });
48
87
 
49
- expect(removals.length, 'no container removal was issued').toBeGreaterThan(0);
50
- for (const args of removals) {
51
- expect(args, `container removal without -v: ${args.join(' ')}`).toContain('-v');
52
- }
88
+ it('passes command argv without losing empty arguments or evaluating shell syntax', async () => {
89
+ const id = 'c'.repeat(64);
90
+ let run: string[] = [];
91
+ execFileSyncMock.mockImplementation((_exe, args) => {
92
+ if (args[0] === 'run') { run = args; return id; }
93
+ return '';
94
+ });
95
+ const manager = DockerTestManager.getInstance({ dockerPath: 'docker', cleanup: false });
96
+ const command = ['redis-server', '--save', '', '--requirepass', "a' b; $(echo INJECTED)"];
97
+ const container = await manager.createContainer({ image: 'fixture', command });
98
+ expect(run.slice(run.indexOf('fixture') + 1)).toEqual(command);
99
+ await container.cleanup();
53
100
  });
54
101
 
55
102
  it('never passes -v to a network removal', () => {
@@ -0,0 +1,52 @@
1
+ import { afterEach, expect, it, vi } from 'vitest';
2
+ import { RedisTestManager } from './redis-manager.js';
3
+
4
+ const original = Reflect.get(RedisTestManager, '_dockerManager');
5
+ afterEach(() => Reflect.set(RedisTestManager, '_dockerManager', original));
6
+
7
+ it('drains delayed container creation and cleans every returned peer before its network', async () => {
8
+ const failure = Error('first node refused');
9
+ const events: string[] = [];
10
+ let release!: () => void;
11
+ const delayed = new Promise<void>(resolve => { release = resolve; });
12
+ const manager = {
13
+ usedPorts: new Set<number>(),
14
+ ensureNetwork: vi.fn(async () => {}),
15
+ findAvailablePort: vi.fn(async () => 24000 + manager.findAvailablePort.mock.calls.length),
16
+ createContainer: vi.fn(async (options) => {
17
+ const number = manager.createContainer.mock.calls.length;
18
+ if (number === 1) throw failure;
19
+ if (number === 6) await delayed;
20
+ events.push('created-' + number);
21
+ return { name: options.name, host: '127.0.0.1', ports: new Map([[6379, options.ports[6379]]]),
22
+ cleanup: vi.fn(async () => { events.push('removed-' + number); }) };
23
+ }),
24
+ removeNetwork: vi.fn(async () => { events.push('network-removed'); }),
25
+ };
26
+ Reflect.set(RedisTestManager, '_dockerManager', manager);
27
+ const result = RedisTestManager.createRedisCluster().catch(error => error);
28
+ await vi.waitFor(() => expect(manager.createContainer).toHaveBeenCalledTimes(6));
29
+ expect(manager.removeNetwork).not.toHaveBeenCalled();
30
+ expect(events.every(event => event.startsWith('created-'))).toBe(true);
31
+ release();
32
+ const error = await result;
33
+ expect(error).toBeInstanceOf(AggregateError);
34
+ expect(error.errors).toEqual([failure]);
35
+ expect(events.slice(-6)).toEqual(['removed-2', 'removed-3', 'removed-4', 'removed-5', 'removed-6', 'network-removed']);
36
+ for (const [options] of manager.createContainer.mock.calls) {
37
+ expect(options.command.slice(options.command.indexOf('--save'), options.command.indexOf('--save') + 2)).toEqual(['--save', '']);
38
+ }
39
+ });
40
+
41
+ it('keeps startup and cleanup failures visible together', async () => {
42
+ const startup = Error('node refused'), cleanup = Error('network still owned');
43
+ Reflect.set(RedisTestManager, '_dockerManager', {
44
+ usedPorts: new Set(), ensureNetwork: vi.fn(async () => {}), findAvailablePort: vi.fn(async () => 24001),
45
+ createContainer: vi.fn(async () => { throw startup; }),
46
+ removeNetwork: vi.fn(async () => { throw cleanup; }),
47
+ });
48
+ const error = await RedisTestManager.createRedisCluster({ masterCount: 1, replicasPerMaster: 0 }).catch(error => error);
49
+ expect(error).toBeInstanceOf(AggregateError);
50
+ expect(error.errors[0].errors).toEqual([startup]);
51
+ expect(error.errors[1].errors).toEqual([cleanup]);
52
+ });
@@ -85,7 +85,7 @@ export class RedisTestManager {
85
85
  // Configure Redis settings
86
86
  command.push('--maxmemory', maxMemory);
87
87
  command.push('--maxmemory-policy', 'allkeys-lru');
88
- command.push("--save ''"); // Disable RDB snapshots for tests
88
+ command.push('--save', ''); // Disable RDB snapshots for tests
89
89
  command.push('--appendonly', 'no'); // Disable AOF for tests
90
90
 
91
91
  if (requirePass && password) {
@@ -97,7 +97,7 @@ export class RedisTestManager {
97
97
  image: 'redis:7-alpine',
98
98
  ports: { 6379: port },
99
99
  environment,
100
- command: command.join(' '),
100
+ command,
101
101
  healthcheck: {
102
102
  test: password ? ['CMD', 'redis-cli', '-a', password, 'ping'] : ['CMD', 'redis-cli', 'ping'],
103
103
  interval: '1s',
@@ -140,13 +140,21 @@ export class RedisTestManager {
140
140
  const networkName = options?.network || `redis-cluster-${randomBytes(8).toString('hex')}`;
141
141
 
142
142
  // Create network
143
- await RedisTestManager.getDockerManager()['ensureNetwork'](networkName);
143
+ await RedisTestManager.getDockerManager().ensureNetwork(networkName);
144
144
 
145
145
  const masters: DockerContainer[] = [];
146
146
  const replicas: DockerContainer[] = [];
147
147
  const nodes: Array<{ host: string; port: number }> = [];
148
148
  const allocatedPorts: number[] = [];
149
149
 
150
+ const cleanup = async () => {
151
+ const settled = await Promise.allSettled([...masters, ...replicas].map(container => container.cleanup()));
152
+ const errors = settled.filter(result => result.status === 'rejected').map(result => result.reason);
153
+ try { await RedisTestManager.getDockerManager().removeNetwork(networkName); }
154
+ catch (error) { errors.push(error); }
155
+ if (errors.length) throw new AggregateError(errors, 'Redis cluster cleanup was not confirmed');
156
+ };
157
+
150
158
  // Extract unique ID from network name to ensure container names are unique
151
159
  const networkId = networkName.split('-').pop() || randomBytes(4).toString('hex');
152
160
 
@@ -191,7 +199,7 @@ export class RedisTestManager {
191
199
  image: 'redis:7-alpine',
192
200
  ports: { 6379: port },
193
201
  networks: [networkName],
194
- command: command.join(' '),
202
+ command,
195
203
  healthcheck: {
196
204
  test: password
197
205
  ? (['CMD', 'redis-cli', '-a', password, 'ping'] as string[])
@@ -221,7 +229,9 @@ export class RedisTestManager {
221
229
  plan.push({ kind: 'replica', index: i, port });
222
230
  }
223
231
 
224
- const created = await Promise.all(
232
+ // Drain every creation before cleanup: an early rejection must not lose
233
+ // ownership of peers that finish starting after that rejection.
234
+ const created = await Promise.allSettled(
225
235
  plan.map(async ({ kind, index, port }) => ({
226
236
  kind,
227
237
  port,
@@ -231,10 +241,14 @@ export class RedisTestManager {
231
241
  }))
232
242
  );
233
243
 
234
- for (const { kind, port, container } of created) {
244
+ for (const result of created) {
245
+ if (result.status !== 'fulfilled') continue;
246
+ const { kind, port, container } = result.value;
235
247
  (kind === 'master' ? masters : replicas).push(container);
236
248
  nodes.push({ host: container.host, port });
237
249
  }
250
+ const failures = created.filter(result => result.status === 'rejected').map(result => result.reason);
251
+ if (failures.length) throw new AggregateError(failures, 'Could not start every Redis cluster node');
238
252
 
239
253
  // Wait for all containers to be fully ready and connected to network
240
254
  const preInitDelay = options?.preInitDelay ?? 5000;
@@ -285,44 +299,16 @@ export class RedisTestManager {
285
299
  network: networkName,
286
300
  nodes,
287
301
  natMap,
288
- cleanup: async () => {
289
- // Clean up containers first
290
- await Promise.allSettled([...masters.map((c) => c.cleanup()), ...replicas.map((c) => c.cleanup())]);
291
- // Then remove the network
292
- try {
293
- await RedisTestManager.getDockerManager()['removeNetwork'](networkName);
294
- } catch (error) {
295
- // Log but don't throw - network cleanup is best effort
296
- console.warn(`Failed to remove network ${networkName}:`, error);
297
- }
298
- },
302
+ cleanup,
299
303
  };
300
304
  } catch (error) {
301
- // Cleanup on failure - release allocated ports and clean up containers
305
+ // A container releases its own reservation only after confirmed cleanup.
306
+ const ownedPorts = new Set([...masters, ...replicas].flatMap(container => [...container.ports.values()]));
302
307
  allocatedPorts.forEach((port) => {
303
- RedisTestManager.getDockerManager()['usedPorts'].delete(port);
308
+ if (!ownedPorts.has(port)) RedisTestManager.getDockerManager()['usedPorts'].delete(port);
304
309
  });
305
- await Promise.allSettled([
306
- ...masters.map((c) =>
307
- c.cleanup().catch((cleanupError) => {
308
- // Log cleanup errors but don't fail the error flow - we're already handling a failure
309
- console.error(`Failed to cleanup master container ${c.name}:`, cleanupError);
310
- })
311
- ),
312
- ...replicas.map((c) =>
313
- c.cleanup().catch((cleanupError) => {
314
- // Log cleanup errors but don't fail the error flow - we're already handling a failure
315
- console.error(`Failed to cleanup replica container ${c.name}:`, cleanupError);
316
- })
317
- ),
318
- ]);
319
- // Try to remove network on failure too
320
- try {
321
- await RedisTestManager.getDockerManager()['removeNetwork'](networkName);
322
- } catch (networkError) {
323
- // Log network cleanup errors but don't fail - network might be in use or already removed
324
- console.error(`Failed to remove network ${networkName} during failure cleanup:`, networkError);
325
- }
310
+ try { await cleanup(); }
311
+ catch (cleanupError) { throw new AggregateError([error, cleanupError], 'Redis cluster startup and cleanup failed', { cause: cleanupError }); }
326
312
  throw error;
327
313
  }
328
314
  }
@@ -358,7 +344,7 @@ export class RedisTestManager {
358
344
  const networkName = options?.network || `redis-sentinel-${randomBytes(8).toString('hex')}`;
359
345
 
360
346
  // Create network
361
- await RedisTestManager.getDockerManager()['ensureNetwork'](networkName);
347
+ await RedisTestManager.getDockerManager().ensureNetwork(networkName);
362
348
 
363
349
  let master: DockerContainer | undefined;
364
350
  const replicas: DockerContainer[] = [];
@@ -382,7 +368,7 @@ export class RedisTestManager {
382
368
  image: 'redis:7-alpine',
383
369
  ports: { 6379: masterPort },
384
370
  networks: [networkName],
385
- command: command.join(' '),
371
+ command,
386
372
  healthcheck: {
387
373
  test: password ? ['CMD', 'redis-cli', '-a', password, 'ping'] : ['CMD', 'redis-cli', 'ping'],
388
374
  interval: '1s',
@@ -410,7 +396,7 @@ export class RedisTestManager {
410
396
  image: 'redis:7-alpine',
411
397
  ports: { 6379: replicaPort },
412
398
  networks: [networkName],
413
- command: replicaCommand.join(' '),
399
+ command: replicaCommand,
414
400
  healthcheck: {
415
401
  test: password ? ['CMD', 'redis-cli', '-a', password, 'ping'] : ['CMD', 'redis-cli', 'ping'],
416
402
  interval: '1s',
@@ -444,18 +430,16 @@ export class RedisTestManager {
444
430
  sentinelConfig.push(`sentinel auth-pass ${masterName} ${password}`);
445
431
  }
446
432
 
447
- const sentinelCommand = [
448
- 'sh',
449
- '-c',
450
- `echo "${sentinelConfig.join('\\n')}" > /tmp/sentinel.conf && redis-sentinel /tmp/sentinel.conf`,
451
- ];
433
+ const sentinelCommand = ['sh', '-c',
434
+ 'printf "%s\\n" "$1" > /tmp/sentinel.conf && exec redis-sentinel /tmp/sentinel.conf',
435
+ 'sentinel-config', sentinelConfig.join('\n')];
452
436
 
453
437
  const sentinel = await RedisTestManager.getDockerManager().createContainer({
454
438
  name: `redis-sentinel-${i}`,
455
439
  image: 'redis:7-alpine',
456
440
  ports: { 26379: sentinelPort },
457
441
  networks: [networkName],
458
- command: sentinelCommand.join(' '),
442
+ command: sentinelCommand,
459
443
  healthcheck: {
460
444
  test: ['CMD', 'redis-cli', '-p', '26379', 'ping'],
461
445
  interval: '1s',
@@ -63,7 +63,7 @@ export interface DockerTestManagerOptions {
63
63
  basePort?: number;
64
64
  /** Maximum retries for port allocation (default: 20) */
65
65
  maxRetries?: number;
66
- /** Timeout in ms for container startup (default: 30000) */
66
+ /** Timeout in ms for the Docker start command and readiness (default: 60000). */
67
67
  startupTimeout?: number;
68
68
  /** Whether to cleanup containers on exit (default: true) */
69
69
  cleanup?: boolean;
@@ -85,8 +85,8 @@ export interface ContainerOptions {
85
85
  name?: string;
86
86
  /** Docker image to use */
87
87
  image: string;
88
- /** Command to run in container */
89
- command?: string;
88
+ /** Literal argv, or an explicitly shell-interpreted command string. */
89
+ command?: string | string[];
90
90
  /** Port mappings: container port -> host port or 'auto' */
91
91
  ports?: Record<number, number | 'auto'>;
92
92
  /** Environment variables */
@@ -100,7 +100,7 @@ export interface ContainerOptions {
100
100
  /** Health check configuration */
101
101
  healthcheck?: {
102
102
  /** Health check command (array format: ['CMD', 'arg1', ...] or ['CMD-SHELL', 'command']) */
103
- test: string[];
103
+ test: string | string[];
104
104
  /** Interval between checks (e.g., "1s") */
105
105
  interval?: string;
106
106
  /** Timeout for each check (e.g., "3s") */
@@ -0,0 +1,20 @@
1
+ import { afterEach, expect, it, vi } from 'vitest';
2
+
3
+ afterEach(() => { vi.unstubAllEnvs(); vi.resetModules(); });
4
+
5
+ it('keeps an explicit PostgreSQL endpoint when selecting a test database', async () => {
6
+ const endpoint = 'postgresql://tester:encoded%40secret@127.0.0.1:25432/source?sslmode=require';
7
+ vi.stubEnv('TEST_POSTGRES_URL', endpoint);
8
+ vi.stubEnv('TEST_DATABASE_URL', 'postgresql://unused:unused@127.0.0.1:15432/unused');
9
+ const { TEST_POSTGRES_URL, testPostgresUrl } = await import('./env.js');
10
+ expect(TEST_POSTGRES_URL).toBe(endpoint);
11
+ expect(testPostgresUrl()).toBe(endpoint);
12
+ expect(testPostgresUrl('worker/2')).toBe('postgresql://tester:encoded%40secret@127.0.0.1:25432/worker%2F2?sslmode=require');
13
+ });
14
+
15
+ it('resolves the existing CI database variable in the shared environment', async () => {
16
+ vi.stubEnv('TEST_POSTGRES_URL', undefined);
17
+ vi.stubEnv('TEST_DATABASE_URL', 'postgresql://tester:secret@127.0.0.1:35432/ci');
18
+ const { TEST_POSTGRES_URL } = await import('./env.js');
19
+ expect(TEST_POSTGRES_URL).toBe('postgresql://tester:secret@127.0.0.1:35432/ci');
20
+ });
package/src/env.ts CHANGED
@@ -16,7 +16,7 @@ export const TEST_POSTGRES_USER = process.env['TEST_POSTGRES_USER'] ?? 'test';
16
16
  export const TEST_POSTGRES_PASSWORD = process.env['TEST_POSTGRES_PASSWORD'] ?? 'test';
17
17
  export const TEST_POSTGRES_DB = process.env['TEST_POSTGRES_DB'] ?? 'test';
18
18
  export const TEST_POSTGRES_URL =
19
- process.env['TEST_POSTGRES_URL'] ??
19
+ process.env['TEST_POSTGRES_URL'] ?? process.env['TEST_DATABASE_URL'] ??
20
20
  `postgresql://${TEST_POSTGRES_USER}:${TEST_POSTGRES_PASSWORD}@${TEST_POSTGRES_HOST}:${TEST_POSTGRES_PORT}/${TEST_POSTGRES_DB}`;
21
21
 
22
22
  /** Build a Redis URL for a specific DB index */
@@ -26,6 +26,8 @@ export function testRedisUrl(db = 0): string {
26
26
 
27
27
  /** Build a Postgres URL for a specific database name */
28
28
  export function testPostgresUrl(database?: string): string {
29
- const db = database ?? TEST_POSTGRES_DB;
30
- return `postgresql://${TEST_POSTGRES_USER}:${TEST_POSTGRES_PASSWORD}@${TEST_POSTGRES_HOST}:${TEST_POSTGRES_PORT}/${db}`;
29
+ if (database === undefined) return TEST_POSTGRES_URL;
30
+ const url = new URL(TEST_POSTGRES_URL);
31
+ url.pathname = '/' + encodeURIComponent(database);
32
+ return url.toString();
31
33
  }
package/src/index.ts CHANGED
@@ -1,5 +1,5 @@
1
1
  /**
2
- * @devgrid/testing - Cross-runtime testing utilities
2
+ * @omnitron-dev/testing - Cross-runtime testing utilities
3
3
  */
4
4
 
5
5
  export * from './runtime/test-adapter.js';
@@ -67,7 +67,7 @@ function mockFn(implementation?: (...args: any[]) => any) {
67
67
  // `map.forEach(mock, context)` — or any callback whose contract includes a
68
68
  // receiver — silently ran with the wrong one, and the assertion inside the
69
69
  // callback failed in a way that pointed at the code under test.
70
- const fn = function (this: any, ...args: any[]) {
70
+ const fn = function spy(this: any, ...args: any[]) {
71
71
  calls.push(args);
72
72
  const result = implementation ? implementation.apply(this, args) : undefined;
73
73
  results.push(result);
@@ -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
+ });