stock-bot/scripts/test/backend-boundaries.test.ts
2026-10-20 14:35:45 -04:00

46 lines
2.5 KiB
TypeScript

import { expect, test } from 'bun:test';
import type { ServerWebSocket } from 'bun';
import { requireServices, type IServiceContainer } from '@stock-bot/services';
import { getLogger } from '@stock-bot/logger';
import { createWebSocketHandler, type RunSocketData } from '../../apps/stock/web-api/src/websocket/run-updates';
import { MonitoringService } from '../../apps/stock/web-api/src/services/monitoring.service';
import { defined, at } from '@stock-bot/invariants';
const logger = getLogger('boundary-tests');
test('required services reject missing capabilities before work starts', () => {
expect(() => requireServices({ logger }, 'mongodb')).toThrow("'mongodb' is unavailable");
expect(() => requireServices({ logger, postgres: null }, 'postgres')).toThrow("'postgres' is unavailable");
expect(requireServices({ logger }, 'logger').logger).toBe(logger);
expect(() => defined(undefined)).toThrow();
expect(() => at([], 0)).toThrow(RangeError);
expect(defined(0)).toBe(0);
});
test('Bun socket lifecycle dispatches messages and removes closed connections', () => {
const sent: string[] = [];
const socket = { data: { runId: 'run-1' }, send: (message: string) => sent.push(message), close() {} } as unknown as ServerWebSocket<RunSocketData>;
const handler = createWebSocketHandler({ logger });
handler.handleConnection(socket, 'run-1');
handler.handleMessage(socket, '{"type":"ping"}');
expect(JSON.parse(sent[0]!)).toMatchObject({ type: 'connected', runId: 'run-1' });
expect(JSON.parse(sent[1]!)).toEqual({ type: 'pong' });
handler.sendProgressUpdate('run-1', 25);
expect(JSON.parse(sent[2]!)).toMatchObject({ type: 'progress', data: { progress: 25 } });
handler.handleClose(socket);
expect(handler.getConnectionsCount('run-1')).toBe(0);
handler.cleanup();
});
test('monitoring uses manager-owned queues and public counters', async () => {
const names: string[] = [];
const queueManager = { getQueue(name: string) {
names.push(name);
return { async getStats() { return { waiting: 2, active: 1, completed: 4, failed: 0, delayed: 0, paused: false, workers: 3 }; }, getWorkerCount() { return 3; } };
} } as unknown as NonNullable<IServiceContainer['queueManager']>;
const stats = await new MonitoringService({ logger, queueManager }).getQueueStats();
expect(names).toContain('{data-pipeline_symbols}');
expect(names).toContain('{data-ingestion_qm}');
expect(stats.every(snapshot => snapshot.connected && snapshot.workers?.count === 3)).toBe(true);
expect(await new MonitoringService({ logger }).getQueueStats()).toEqual([]);
});