T-16: tests

This commit is contained in:
Studio 2026-11-27 12:33:45 -05:00
parent 6fc3f8cd5c
commit c2e4f3b2bd
3 changed files with 312 additions and 0 deletions

View file

@ -0,0 +1,122 @@
import { EventEmitter } from 'events';
import { afterEach, describe, expect, it, mock } from 'bun:test';
import { Queue } from '../src/queue';
import { QueueManager } from '../src/queue-manager';
import type { RedisConfig } from '../src/types';
// Regression: an EventEmitter that emits 'error' with no listener throws synchronously,
// so an unreachable Redis used to surface as an unhandled error mid-suite.
// Non-QA loopback port; nothing is expected to listen here.
const unreachableRedis: RedisConfig = {
host: '127.0.0.1',
port: 16379,
maxRetriesPerRequest: 1,
retryDelay: 50,
};
function createLogger() {
return {
info: mock(() => {}),
error: mock(() => {}),
warn: mock(() => {}),
debug: mock(() => {}),
trace: mock(() => {}),
};
}
describe('Queue connection error handling', () => {
const queues: Queue[] = [];
afterEach(async () => {
await Promise.all(
queues.splice(0).map(async queue => {
// Stop reconnect timers on the unreachable socket before awaiting close()
(queue.getBullQueue() as any).connection?._client?.disconnect(false);
(queue as any).queueEvents?.connection?._client?.disconnect(false);
await queue.close().catch(() => {});
})
);
});
it('logs QueueEvents connection errors instead of throwing', () => {
const logger = createLogger();
const queue = new Queue(
'conn-error-queue',
unreachableRedis,
{},
{ workers: 1, startWorker: false },
logger as any
);
queues.push(queue);
const queueEvents = (queue as any).queueEvents as EventEmitter;
expect(queueEvents).toBeDefined();
expect(queueEvents.listenerCount('error')).toBeGreaterThanOrEqual(1);
const failure = new Error('connect ECONNREFUSED 127.0.0.1:16379');
expect(() => queueEvents.emit('error', failure)).not.toThrow();
expect(logger.error).toHaveBeenCalledWith('QueueEvents connection error', {
queueName: 'conn-error-queue',
error: failure,
});
});
it('does not create QueueEvents for a producer-only queue', () => {
const queue = new Queue('producer-only', unreachableRedis, {}, {}, createLogger() as any);
queues.push(queue);
expect((queue as any).queueEvents).toBeUndefined();
});
});
describe('QueueManager connection error handling', () => {
function createFakeRedis() {
const redis = new EventEmitter() as EventEmitter & {
quit: ReturnType<typeof mock>;
disconnect: ReturnType<typeof mock>;
};
redis.quit = mock(async () => 'OK');
redis.disconnect = mock(() => {});
return redis;
}
it('logs rate-limiter Redis errors instead of throwing', async () => {
const logger = createLogger();
const redis = createFakeRedis();
const manager = new QueueManager(
{ serviceName: 'conn-error-svc', redis: unreachableRedis },
undefined,
logger as any,
{ createRedis: () => redis as any }
);
try {
expect(redis.listenerCount('error')).toBe(1);
const failure = new Error('connect ECONNREFUSED 127.0.0.1:16379');
expect(() => redis.emit('error', failure)).not.toThrow();
expect(logger.error).toHaveBeenCalledWith('QueueManager Redis connection error', {
service: 'conn-error-svc',
error: failure,
});
} finally {
await manager.shutdown();
}
expect(redis.quit).toHaveBeenCalledTimes(1);
});
it('accepts an injected Redis client without an event API', async () => {
const quit = mock(async () => 'OK');
const manager = new QueueManager(
{ serviceName: 'no-events-svc', redis: unreachableRedis },
undefined,
createLogger() as any,
{ createRedis: () => ({ quit, disconnect: mock(() => {}) }) as any }
);
await manager.shutdown();
expect(quit).toHaveBeenCalledTimes(1);
});
});

View file

@ -0,0 +1,136 @@
import { afterEach, beforeEach, describe, expect, it } from 'bun:test';
import { Shutdown } from '../src/shutdown';
// These tests use the real `process` listener registry (no stubs) because the
// regression being guarded is listeners leaking across test files in one bun process.
const SIGNALS = ['SIGTERM', 'SIGINT'] as const;
function listenerCounts(): Record<(typeof SIGNALS)[number], number> {
return {
SIGTERM: process.listenerCount('SIGTERM'),
SIGINT: process.listenerCount('SIGINT'),
};
}
describe('Shutdown signal listener cleanup', () => {
const created: Shutdown[] = [];
let baseline: ReturnType<typeof listenerCounts>;
function track(instance: Shutdown): Shutdown {
created.push(instance);
return instance;
}
beforeEach(() => {
Shutdown.reset();
baseline = listenerCounts();
});
afterEach(() => {
for (const instance of created.splice(0)) {
instance.dispose();
}
Shutdown.reset();
});
it('autoRegister adds exactly one SIGTERM and one SIGINT listener and dispose removes them', () => {
const shutdown = track(new Shutdown());
expect(listenerCounts()).toEqual({
SIGTERM: baseline.SIGTERM + 1,
SIGINT: baseline.SIGINT + 1,
});
shutdown.dispose();
expect(listenerCounts()).toEqual(baseline);
});
it('autoRegister: false adds no process listeners', () => {
track(new Shutdown({ autoRegister: false }));
expect(listenerCounts()).toEqual(baseline);
});
it('removeSignalHandlers leaves listeners owned by other code in place', () => {
const foreign = () => {};
process.on('SIGTERM', foreign);
try {
const shutdown = track(new Shutdown());
shutdown.removeSignalHandlers();
expect(process.listeners('SIGTERM')).toContain(foreign);
expect(listenerCounts()).toEqual({ SIGTERM: baseline.SIGTERM + 1, SIGINT: baseline.SIGINT });
} finally {
process.off('SIGTERM', foreign);
}
});
it('dispose and reset are idempotent', () => {
const shutdown = track(new Shutdown());
shutdown.dispose();
shutdown.dispose();
Shutdown.reset();
Shutdown.reset();
expect(listenerCounts()).toEqual(baseline);
});
it('repeatedly creating and disposing instances never accumulates listeners', () => {
for (let i = 0; i < 25; i++) {
new Shutdown().dispose();
}
expect(listenerCounts()).toEqual(baseline);
});
it('Shutdown.reset removes singleton listeners and the next getInstance builds a fresh instance', () => {
const first = Shutdown.getInstance();
expect(listenerCounts().SIGTERM).toBe(baseline.SIGTERM + 1);
Shutdown.reset();
expect(listenerCounts()).toEqual(baseline);
const second = Shutdown.getInstance({ autoRegister: false });
track(second);
expect(second).not.toBe(first);
expect(listenerCounts()).toEqual(baseline);
});
it('disposing a non-singleton instance keeps the active singleton and its listeners', () => {
const singleton = Shutdown.getInstance();
const other = track(new Shutdown());
other.dispose();
expect(Shutdown.getInstance()).toBe(singleton);
expect(listenerCounts()).toEqual({
SIGTERM: baseline.SIGTERM + 1,
SIGINT: baseline.SIGINT + 1,
});
});
it('disposing the singleton directly clears it so getInstance returns a new one', () => {
const singleton = Shutdown.getInstance({ autoRegister: false });
singleton.dispose();
const next = Shutdown.getInstance({ autoRegister: false });
expect(next).not.toBe(singleton);
});
it('a disposed instance keeps its shutdown callbacks usable without process listeners', async () => {
const shutdown = track(new Shutdown({ timeout: 1000 }));
const calls: string[] = [];
shutdown.onShutdown(() => {
calls.push('ran');
}, 10, 'probe');
shutdown.dispose();
await shutdown.shutdown();
expect(calls).toEqual(['ran']);
expect(listenerCounts()).toEqual(baseline);
});
});