From 9c4e87cdfda789df20a44dfbf4451111a420d470 Mon Sep 17 00:00:00 2001 From: Studio Date: Fri, 27 Nov 2026 12:01:06 -0500 Subject: [PATCH] =?UTF-8?q?T-16:=20M0.1b=20=E2=80=94=20Make=20repo-wide=20?= =?UTF-8?q?`bun=20test`=20green:=20fix=20queue,=20shutdown-signal=20and=20?= =?UTF-8?q?research-workflow=20test=20failures?= MIME-Version: 1.0 Content-Type: text/plain; charset=UTF-8 Content-Transfer-Encoding: 8bit --- libs/core/cache/test/redis-cache.test.ts | 56 ++++++++--- libs/core/config/test/config-manager.test.ts | 31 +++--- libs/core/config/test/env.loader.test.ts | 33 +++---- libs/core/config/test/file.loader.test.ts | 22 ++--- libs/core/di/test/handler-scanner.test.ts | 10 +- libs/core/di/test/registration.test.ts | 90 ++++------------- libs/core/di/test/service-application.test.ts | 96 ++++++++++--------- .../handlers/test/create-job-handler.test.ts | 20 ++-- libs/core/queue/src/queue-manager.ts | 8 ++ libs/core/queue/src/queue.ts | 16 +++- libs/core/queue/test/queue-class.test.ts | 46 ++++++--- libs/core/queue/test/queue.test.ts | 61 ++++++------ libs/core/shutdown/src/shutdown.ts | 39 +++++++- .../test/shutdown-comprehensive.test.ts | 21 ++-- .../shutdown/test/shutdown-signals.test.ts | 36 +++---- libs/core/shutdown/test/shutdown.test.ts | 33 ++++--- test/setup.ts | 14 ++- 17 files changed, 366 insertions(+), 266 deletions(-) diff --git a/libs/core/cache/test/redis-cache.test.ts b/libs/core/cache/test/redis-cache.test.ts index 601ae57c..ba28ba89 100644 --- a/libs/core/cache/test/redis-cache.test.ts +++ b/libs/core/cache/test/redis-cache.test.ts @@ -1,21 +1,48 @@ -import { beforeEach, describe, expect, it } from 'bun:test'; +import { afterEach, beforeEach, describe, expect, it } from 'bun:test'; import { RedisCache } from '../src/redis-cache'; -import type { CacheOptions } from '../src/types'; +import type { CacheOptions, RedisConfig } from '../src/types'; -const hasTestRedis = Boolean(process.env.BACKTEST_TEST_REDIS_URL); +const testRedisUrl = process.env.BACKTEST_TEST_REDIS_URL; -describe.skipIf(!hasTestRedis)('RedisCache', () => { +function parseTestRedisConfig(rawUrl: string): RedisConfig { + const parsed = new URL(rawUrl); + if (parsed.pathname !== '/15') { + throw new Error('BACKTEST_TEST_REDIS_URL must point to dedicated Redis database /15'); + } + return { + host: parsed.hostname, + port: parsed.port ? Number(parsed.port) : 6379, + db: 15, + ...(parsed.username ? { username: decodeURIComponent(parsed.username) } : {}), + ...(parsed.password ? { password: decodeURIComponent(parsed.password) } : {}), + }; +} + +if (!testRedisUrl) { + process.stderr.write( + 'Skipping RedisCache integration tests: set BACKTEST_TEST_REDIS_URL to a dedicated Redis fixture using database /15\n' + ); +} + +describe.skipIf(!testRedisUrl)('RedisCache', () => { let cache: RedisCache; + let redisConfig: RedisConfig; beforeEach(() => { + redisConfig = parseTestRedisConfig(testRedisUrl!); const options: CacheOptions = { keyPrefix: 'test:', ttl: 3600, - redisConfig: { host: 'localhost', port: 6379 }, + shared: false, + redisConfig, }; cache = new RedisCache(options); }); + afterEach(async () => { + await cache?.disconnect().catch(() => {}); + }); + describe('Core functionality', () => { it('should create cache instance', () => { expect(cache).toBeDefined(); @@ -148,16 +175,21 @@ describe.skipIf(!hasTestRedis)('RedisCache', () => { // Force an error by using invalid JSON const badCache = new RedisCache({ keyPrefix: 'bad:', - redisConfig: { host: 'localhost', port: 6379 }, + shared: false, + redisConfig, }); - // This would normally throw but should return null - const result = await badCache.get('non-existent'); - expect(result).toBeNull(); + try { + // This would normally throw but should return null + const result = await badCache.get('non-existent'); + expect(result).toBeNull(); - // Check stats updated - const stats = badCache.getStats(); - expect(stats.misses).toBe(1); + // Check stats updated + const stats = badCache.getStats(); + expect(stats.misses).toBe(1); + } finally { + await badCache.disconnect().catch(() => {}); + } }); }); diff --git a/libs/core/config/test/config-manager.test.ts b/libs/core/config/test/config-manager.test.ts index 1ec94406..e2be9463 100644 --- a/libs/core/config/test/config-manager.test.ts +++ b/libs/core/config/test/config-manager.test.ts @@ -1,19 +1,10 @@ -import { beforeEach, describe, expect, it, mock, spyOn } from 'bun:test'; +import { afterEach, beforeEach, describe, expect, it, mock, spyOn } from 'bun:test'; +import * as loggerModule from '@stock-bot/logger'; import { z } from 'zod'; import { ConfigManager } from '../src/config-manager'; import { ConfigError, ConfigValidationError } from '../src/errors'; import type { ConfigLoader, Environment } from '../src/types'; -// Mock the logger -mock.module('@stock-bot/logger', () => ({ - getLogger: () => ({ - info: mock(() => {}), - error: mock(() => {}), - warn: mock(() => {}), - debug: mock(() => {}), - }), -})); - // Mock loader class class MockLoader implements ConfigLoader { constructor( @@ -28,10 +19,28 @@ class MockLoader implements ConfigLoader { describe('ConfigManager', () => { let manager: ConfigManager; + let getLoggerSpy: ReturnType; + const originalNodeEnv = process.env.NODE_ENV; beforeEach(() => { // Reset environment delete process.env.NODE_ENV; + getLoggerSpy = spyOn(loggerModule, 'getLogger').mockReturnValue({ + info: mock(() => {}), + error: mock(() => {}), + warn: mock(() => {}), + debug: mock(() => {}), + trace: mock(() => {}), + } as any); + }); + + afterEach(() => { + getLoggerSpy?.mockRestore(); + if (originalNodeEnv === undefined) { + delete process.env.NODE_ENV; + } else { + process.env.NODE_ENV = originalNodeEnv; + } }); describe('constructor', () => { diff --git a/libs/core/config/test/env.loader.test.ts b/libs/core/config/test/env.loader.test.ts index b6c37589..0d51fae8 100644 --- a/libs/core/config/test/env.loader.test.ts +++ b/libs/core/config/test/env.loader.test.ts @@ -1,16 +1,12 @@ -import { readFileSync } from 'fs'; -import { afterEach, beforeEach, describe, expect, it, mock, spyOn } from 'bun:test'; +import * as fs from 'fs'; +import { afterEach, beforeEach, describe, expect, it, spyOn } from 'bun:test'; import { ConfigLoaderError } from '../src/errors'; import { EnvLoader } from '../src/loaders/env.loader'; import { queueConfigSchema } from '../src/schemas'; -// Mock fs module -mock.module('fs', () => ({ - readFileSync: mock(() => ''), -})); - describe('EnvLoader', () => { let loader: EnvLoader; + let readFileSync: ReturnType; const originalEnv = { ...process.env }; beforeEach(() => { @@ -18,9 +14,11 @@ describe('EnvLoader', () => { for (const key in process.env) { delete process.env[key]; } + readFileSync = spyOn(fs, 'readFileSync').mockReturnValue('' as any); }); afterEach(() => { + readFileSync?.mockRestore(); // Restore original environment for (const key in process.env) { delete process.env[key]; @@ -371,17 +369,20 @@ KEY_WITHOUT_VALUE= it('should warn on other file errors', () => { const consoleWarnSpy = spyOn(console, 'warn').mockImplementation(() => {}); + try { + (readFileSync as any).mockImplementation(() => { + const error: any = new Error('Permission denied'); + error.code = 'EACCES'; + throw error; + }); - (readFileSync as any).mockImplementation(() => { - const error: any = new Error('Permission denied'); - error.code = 'EACCES'; - throw error; - }); + loader = new EnvLoader(); + loader.load(); - loader = new EnvLoader(); - loader.load(); - - expect(consoleWarnSpy).toHaveBeenCalled(); + expect(consoleWarnSpy).toHaveBeenCalled(); + } finally { + consoleWarnSpy.mockRestore(); + } }); it('should try multiple env file paths', () => { diff --git a/libs/core/config/test/file.loader.test.ts b/libs/core/config/test/file.loader.test.ts index 27da55fd..47cada57 100644 --- a/libs/core/config/test/file.loader.test.ts +++ b/libs/core/config/test/file.loader.test.ts @@ -1,23 +1,23 @@ -import { existsSync, readFileSync } from 'fs'; -import { beforeEach, describe, expect, it, mock } from 'bun:test'; +import * as fs from 'fs'; +import { afterEach, beforeEach, describe, expect, it, spyOn } from 'bun:test'; import { ConfigLoaderError } from '../src/errors'; import { FileLoader } from '../src/loaders/file.loader'; -// Mock fs module -mock.module('fs', () => ({ - existsSync: mock(() => false), - readFileSync: mock(() => ''), -})); - describe('FileLoader', () => { let loader: FileLoader; + let existsSync: ReturnType; + let readFileSync: ReturnType; const configPath = '/app/config'; const environment = 'development'; beforeEach(() => { - // Reset mocks - (existsSync as any).mockReset(); - (readFileSync as any).mockReset(); + existsSync = spyOn(fs, 'existsSync').mockReturnValue(false); + readFileSync = spyOn(fs, 'readFileSync').mockReturnValue('' as any); + }); + + afterEach(() => { + existsSync?.mockRestore(); + readFileSync?.mockRestore(); }); describe('constructor', () => { diff --git a/libs/core/di/test/handler-scanner.test.ts b/libs/core/di/test/handler-scanner.test.ts index ce8b1dea..a468bf18 100644 --- a/libs/core/di/test/handler-scanner.test.ts +++ b/libs/core/di/test/handler-scanner.test.ts @@ -1,5 +1,5 @@ import { asFunction, createContainer, type AwilixContainer } from 'awilix'; -import { beforeEach, describe, expect, it, mock, spyOn } from 'bun:test'; +import { afterEach, beforeEach, describe, expect, it, mock, spyOn } from 'bun:test'; import type { HandlerRegistry } from '@stock-bot/handler-registry'; import * as logger from '@stock-bot/logger'; import type { ExecutionContext, IHandler } from '@stock-bot/types'; @@ -55,6 +55,7 @@ describe('HandlerScanner', () => { let mockRegistry: HandlerRegistry; let container: AwilixContainer; let mockLogger: any; + let getLoggerSpy: ReturnType; beforeEach(() => { // Create mock logger @@ -63,10 +64,11 @@ describe('HandlerScanner', () => { debug: mock(() => {}), error: mock(() => {}), warn: mock(() => {}), + trace: mock(() => {}), }; // Mock getLogger to return our mock logger - spyOn(logger, 'getLogger').mockReturnValue(mockLogger); + getLoggerSpy = spyOn(logger, 'getLogger').mockReturnValue(mockLogger); // Create mock registry mockRegistry = { @@ -87,6 +89,10 @@ describe('HandlerScanner', () => { }); }); + afterEach(() => { + getLoggerSpy?.mockRestore(); + }); + describe('scanHandlers', () => { it('should handle empty patterns gracefully', async () => { await scanner.scanHandlers([]); diff --git a/libs/core/di/test/registration.test.ts b/libs/core/di/test/registration.test.ts index d61e404f..ce644248 100644 --- a/libs/core/di/test/registration.test.ts +++ b/libs/core/di/test/registration.test.ts @@ -1,21 +1,28 @@ import { asFunction, asValue, createContainer } from 'awilix'; -import { describe, expect, it, mock } from 'bun:test'; +import { afterEach, beforeEach, describe, expect, it, mock, spyOn } from 'bun:test'; +import * as queueModule from '@stock-bot/queue'; import { registerApplicationServices, registerCacheServices, registerDatabaseServices, } from '../src/registrations'; -// Mock the queue module -mock.module('@stock-bot/queue', () => ({ - createServiceCache: mock(() => ({ - get: mock(() => Promise.resolve(null)), - set: mock(() => Promise.resolve()), - del: mock(() => Promise.resolve()), - })), -})); - describe('DI Registrations', () => { + let createServiceCacheSpy: ReturnType; + + beforeEach(() => { + createServiceCacheSpy = spyOn(queueModule, 'createServiceCache').mockImplementation( + (() => ({ + get: mock(() => Promise.resolve(null)), + set: mock(() => Promise.resolve()), + del: mock(() => Promise.resolve()), + })) as any + ); + }); + + afterEach(() => { + createServiceCacheSpy?.mockRestore(); + }); describe('registerCacheServices', () => { it('should register null cache when redis disabled', () => { const container = createContainer(); @@ -108,22 +115,6 @@ describe('DI Registrations', () => { it('should register MongoDB when config exists', () => { const container = createContainer(); - // Mock MongoDB client - const mockMongoClient = { - connect: mock(() => Promise.resolve()), - disconnect: mock(() => Promise.resolve()), - getDb: mock(() => ({})), - }; - - // Mock the MongoDB factory - mock.module('@stock-bot/mongodb', () => ({ - MongoDBClient: class { - constructor() { - return mockMongoClient; - } - }, - })); - const config = { mongodb: { enabled: true, @@ -140,22 +131,6 @@ describe('DI Registrations', () => { it('should register PostgreSQL when config exists', () => { const container = createContainer(); - // Mock Postgres client - const mockPostgresClient = { - connect: mock(() => Promise.resolve()), - disconnect: mock(() => Promise.resolve()), - query: mock(() => Promise.resolve({ rows: [] })), - }; - - // Mock the Postgres factory - mock.module('@stock-bot/postgres', () => ({ - PostgresClient: class { - constructor() { - return mockPostgresClient; - } - }, - })); - const config = { postgres: { enabled: true, @@ -175,22 +150,6 @@ describe('DI Registrations', () => { it('should register QuestDB when config exists', () => { const container = createContainer(); - // Mock QuestDB client - const mockQuestdbClient = { - connect: mock(() => Promise.resolve()), - disconnect: mock(() => Promise.resolve()), - query: mock(() => Promise.resolve({ data: [] })), - }; - - // Mock the QuestDB factory - mock.module('@stock-bot/questdb', () => ({ - QuestDBClient: class { - constructor() { - return mockQuestdbClient; - } - }, - })); - const config = { questdb: { enabled: true, @@ -281,21 +240,6 @@ describe('DI Registrations', () => { }), }); - // Mock queue manager - const mockQueueManager = { - getQueue: mock(() => ({})), - startAllWorkers: mock(() => {}), - shutdown: mock(() => Promise.resolve()), - }; - - mock.module('@stock-bot/queue', () => ({ - QueueManager: class { - constructor() { - return mockQueueManager; - } - }, - })); - const config = { service: { name: 'test-service', diff --git a/libs/core/di/test/service-application.test.ts b/libs/core/di/test/service-application.test.ts index 472f4281..c76525e5 100644 --- a/libs/core/di/test/service-application.test.ts +++ b/libs/core/di/test/service-application.test.ts @@ -1,25 +1,23 @@ -import { afterEach, describe, expect, it, mock } from 'bun:test'; +import { afterEach, beforeEach, describe, expect, it, mock, spyOn } from 'bun:test'; import type { BaseAppConfig } from '@stock-bot/config'; +import * as loggerModule from '@stock-bot/logger'; +import { Shutdown } from '@stock-bot/shutdown'; import { ServiceApplication } from '../src/service-application'; import type { ServiceApplicationConfig, ServiceLifecycleHooks } from '../src/service-application'; -// Mock logger module -const mockLogger = { +// Mock logger object used via spyOn in beforeEach (restored in afterEach) +const mockLogger: any = { info: mock(() => {}), error: mock(() => {}), warn: mock(() => {}), debug: mock(() => {}), - child: mock(() => mockLogger), + trace: mock(() => {}), }; +mockLogger.child = mock(() => mockLogger); -mock.module('@stock-bot/logger', () => ({ - getLogger: () => mockLogger, - setLoggerConfig: mock(() => {}), - shutdownLoggers: mock(() => Promise.resolve()), -})); - -// Mock shutdown module +// Mock shutdown instance used via spyOn(Shutdown, 'getInstance') in beforeEach const mockShutdownInstance = { + shutdown: mock(() => Promise.resolve()), onShutdown: mock(() => {}), onShutdownHigh: mock(() => {}), onShutdownMedium: mock(() => {}), @@ -30,24 +28,13 @@ const mockShutdownInstance = { executeCallbacks: mock(() => Promise.resolve()), }; -const mockShutdown = { - getInstance: mock(() => mockShutdownInstance), -}; - -mock.module('@stock-bot/shutdown', () => ({ - Shutdown: mockShutdown, -})); - -// Mock Bun.serve +// Mock server returned by spyOn(Bun, 'serve') const mockServer = { stop: mock(() => {}), port: 3000, hostname: '0.0.0.0', }; -const _originalBunServe = Bun.serve; -Bun.serve = mock(() => mockServer); - const mockConfig: BaseAppConfig = { name: 'test-service', version: '1.0.0', @@ -75,13 +62,44 @@ const mockConfig: BaseAppConfig = { describe('ServiceApplication', () => { let app: ServiceApplication; + let getLoggerSpy: ReturnType; + let setLoggerConfigSpy: ReturnType; + let shutdownLoggersSpy: ReturnType; + let shutdownGetInstanceSpy: ReturnType; + let bunServeSpy: ReturnType; + + beforeEach(() => { + getLoggerSpy = spyOn(loggerModule, 'getLogger').mockReturnValue(mockLogger); + setLoggerConfigSpy = spyOn(loggerModule, 'setLoggerConfig').mockImplementation(() => {}); + shutdownLoggersSpy = spyOn(loggerModule, 'shutdownLoggers').mockResolvedValue(undefined); + shutdownGetInstanceSpy = spyOn(Shutdown, 'getInstance').mockReturnValue( + mockShutdownInstance as any + ); + bunServeSpy = spyOn(Bun, 'serve').mockImplementation((() => mockServer) as any); + }); afterEach(() => { + // Clean up app if it exists before restoring spies + if (app) { + app.stop().catch(() => {}); + app = null as any; + } + + // Restore module/global spies so no state leaks to other test files + getLoggerSpy?.mockRestore(); + setLoggerConfigSpy?.mockRestore(); + shutdownLoggersSpy?.mockRestore(); + shutdownGetInstanceSpy?.mockRestore(); + bunServeSpy?.mockRestore(); + // Reset mocks mockLogger.info.mockReset(); mockLogger.error.mockReset(); mockLogger.warn.mockReset(); mockLogger.debug.mockReset(); + mockLogger.trace.mockReset(); + mockShutdownInstance.shutdown.mockReset(); + mockShutdownInstance.shutdown.mockImplementation(() => Promise.resolve()); mockShutdownInstance.onShutdown.mockReset(); mockShutdownInstance.onShutdownHigh.mockReset(); mockShutdownInstance.onShutdownMedium.mockReset(); @@ -90,12 +108,6 @@ describe('ServiceApplication', () => { mockShutdownInstance.registerAsync.mockReset(); mockShutdownInstance.handleTermination.mockReset(); mockShutdownInstance.executeCallbacks.mockReset(); - - // Clean up app if it exists - if (app) { - app.stop().catch(() => {}); - app = null as any; - } }); describe('constructor', () => { @@ -136,7 +148,7 @@ describe('ServiceApplication', () => { }; app = new ServiceApplication(mockConfig, serviceConfig); - expect(mockShutdown.getInstance).toHaveBeenCalledWith({ + expect(shutdownGetInstanceSpy).toHaveBeenCalledWith({ timeout: 30000, }); }); @@ -605,19 +617,14 @@ describe('ServiceApplication', () => { describe('stop method', () => { it('should trigger shutdown', async () => { - const mockShutdownInstance = { + const localShutdownInstance = { shutdown: mock(() => Promise.resolve()), onShutdown: mock(() => {}), onShutdownHigh: mock(() => {}), onShutdownMedium: mock(() => {}), onShutdownLow: mock(() => {}), }; - - mock.module('@stock-bot/shutdown', () => ({ - Shutdown: { - getInstance: () => mockShutdownInstance, - }, - })); + shutdownGetInstanceSpy.mockReturnValue(localShutdownInstance as any); const serviceConfig: ServiceApplicationConfig = { serviceName: 'test-service', @@ -627,7 +634,7 @@ describe('ServiceApplication', () => { await app.stop(); - expect(mockShutdownInstance.shutdown).toHaveBeenCalled(); + expect(localShutdownInstance.shutdown).toHaveBeenCalled(); expect(mockLogger.info).toHaveBeenCalledWith('Stopping test-service service...'); }); }); @@ -665,19 +672,14 @@ describe('ServiceApplication', () => { describe('shutdown handlers', () => { it('should register all shutdown handlers during start', async () => { - const mockShutdownInstance = { + const localShutdownInstance = { shutdown: mock(() => Promise.resolve()), onShutdown: mock(() => {}), onShutdownHigh: mock(() => {}), onShutdownMedium: mock(() => {}), onShutdownLow: mock(() => {}), }; - - mock.module('@stock-bot/shutdown', () => ({ - Shutdown: { - getInstance: () => mockShutdownInstance, - }, - })); + shutdownGetInstanceSpy.mockReturnValue(localShutdownInstance as any); const serviceConfig: ServiceApplicationConfig = { serviceName: 'test-service', @@ -731,10 +733,10 @@ describe('ServiceApplication', () => { ); // Should have registered shutdown handlers - expect(mockShutdownInstance.onShutdown).toHaveBeenCalledTimes(5); // Queue, HTTP, Custom, Services, Loggers + expect(localShutdownInstance.onShutdown).toHaveBeenCalledTimes(5); // Queue, HTTP, Custom, Services, Loggers // Test the handlers by calling them - const shutdownHandlers = (mockShutdownInstance.onShutdown as any).mock.calls; + const shutdownHandlers = (localShutdownInstance.onShutdown as any).mock.calls; // Find and execute queue shutdown handler (priority 9) const queueHandler = shutdownHandlers.find(call => call[2] === 'Queue System'); diff --git a/libs/core/handlers/test/create-job-handler.test.ts b/libs/core/handlers/test/create-job-handler.test.ts index b97e681d..fc6ddae3 100644 --- a/libs/core/handlers/test/create-job-handler.test.ts +++ b/libs/core/handlers/test/create-job-handler.test.ts @@ -96,9 +96,15 @@ describe('createJobHandler', () => { }); it('should support async operations', async () => { + let resolveStep!: () => void; + let asyncStepCompleted = false; + const stepGate = new Promise(resolve => { + resolveStep = resolve; + }); + const handler = createJobHandler(async job => { - // Simulate async operation - await new Promise(resolve => setTimeout(resolve, 10)); + await stepGate; + asyncStepCompleted = true; return { success: true, @@ -120,12 +126,14 @@ describe('createJobHandler', () => { updateProgress: async () => {}, }; - const startTime = Date.now(); - const result = await handler(mockJob as any); - const endTime = Date.now(); + const pending = handler(mockJob as any); + expect(asyncStepCompleted).toBe(false); + resolveStep(); + const result = await pending; + expect(asyncStepCompleted).toBe(true); expect(result.success).toBe(true); - expect(endTime - startTime).toBeGreaterThanOrEqual(10); + expect(result.processedBy).toBe('user-789'); }); it('should maintain type safety for complex payloads', () => { diff --git a/libs/core/queue/src/queue-manager.ts b/libs/core/queue/src/queue-manager.ts index 983270ab..31f6a07f 100644 --- a/libs/core/queue/src/queue-manager.ts +++ b/libs/core/queue/src/queue-manager.ts @@ -99,6 +99,14 @@ export class QueueManager { this.ioredisConnection = deps?.createRedis ? deps.createRedis(ioredisOptions) : new Redis(ioredisOptions); + if (typeof this.ioredisConnection.on === 'function') { + this.ioredisConnection.on('error', error => { + this.logger.error('QueueManager Redis connection error', { + service: this.serviceName, + error, + }); + }); + } // Rate limiter will be initialized when rules are added dynamically // No longer initialized from config diff --git a/libs/core/queue/src/queue.ts b/libs/core/queue/src/queue.ts index 46ac78f7..650613d0 100644 --- a/libs/core/queue/src/queue.ts +++ b/libs/core/queue/src/queue.ts @@ -123,7 +123,7 @@ export class Queue { // Initialize queue events if workers will be used if (config.workers && config.workers > 0) { - this.queueEvents = new QueueEvents(queueName, { connection }); + this.queueEvents = this.createQueueEvents(connection); } // Start workers if requested and not explicitly disabled @@ -262,12 +262,18 @@ export class Queue { return await this.bullQueue.getJob(jobId); } + private createQueueEvents(connection: ReturnType): QueueEvents { + const queueEvents = new QueueEvents(this.queueName, { connection }); + queueEvents.on('error', error => + this.logger.error('QueueEvents connection error', { queueName: this.queueName, error }) + ); + return queueEvents; + } + /** Wait for a result using a QueueEvents connection owned by this queue. */ async waitForJob(job: Job, timeout = 30000): Promise { if (!this.queueEvents) { - this.queueEvents = new QueueEvents(this.queueName, { - connection: getRedisConnection(this.redisConfig), - }); + this.queueEvents = this.createQueueEvents(getRedisConnection(this.redisConfig)); } await this.queueEvents.waitUntilReady(); return job.waitUntilFinished(this.queueEvents, timeout); @@ -589,7 +595,7 @@ export class Queue { // Initialize queue events if not already done if (!this.queueEvents) { const connection = getRedisConnection(this.redisConfig); - this.queueEvents = new QueueEvents(this.queueName, { connection }); + this.queueEvents = this.createQueueEvents(connection); } this.startWorkers(workerCount, concurrency); diff --git a/libs/core/queue/test/queue-class.test.ts b/libs/core/queue/test/queue-class.test.ts index 43b886fe..2433ba3b 100644 --- a/libs/core/queue/test/queue-class.test.ts +++ b/libs/core/queue/test/queue-class.test.ts @@ -1,17 +1,37 @@ -import { describe, expect, it, mock } from 'bun:test'; +import { afterEach, describe, expect, it, mock } from 'bun:test'; import { Queue, removeScheduledJobsFromBullQueue } from '../src/queue'; import { QueueManager } from '../src/queue-manager'; import type { QueueWorkerConfig, RedisConfig } from '../src/types'; describe('Queue Class', () => { + // Use a non-QA isolated loopback port so unit tests never touch QA Dragonfly (localhost:6379) const mockRedisConfig: RedisConfig = { - host: 'localhost', - port: 6379, + host: '127.0.0.1', + port: 16379, + maxRetriesPerRequest: 1, + retryDelay: 50, }; + const createdQueues: Queue[] = []; + + function trackQueue(queue: Queue): Queue { + createdQueues.push(queue); + return queue; + } + + afterEach(async () => { + await Promise.all( + createdQueues.splice(0).map(async queue => { + // Stop reconnect timers on unreachable test sockets before awaiting BullMQ close() + (queue.getBullQueue() as any).connection?._client?.disconnect(false); + (queue as any).queueEvents?.connection?._client?.disconnect(false); + await queue.close().catch(() => {}); + }) + ); + }); describe('basic functionality', () => { it('should create queue with minimal config', () => { - const queue = new Queue('test-queue', mockRedisConfig); + const queue = trackQueue(new Queue('test-queue', mockRedisConfig)); expect(queue).toBeDefined(); expect(queue.getName()).toBe('test-queue'); }); @@ -22,7 +42,7 @@ describe('Queue Class', () => { backoff: { type: 'exponential' as const, delay: 2000 }, }; - const queue = new Queue('test-queue', mockRedisConfig, defaultJobOptions); + const queue = trackQueue(new Queue('test-queue', mockRedisConfig, defaultJobOptions)); expect(queue).toBeDefined(); expect(queue.getName()).toBe('test-queue'); }); @@ -36,7 +56,7 @@ describe('Queue Class', () => { trace: mock(() => {}), }; - const queue = new Queue('test-queue', mockRedisConfig, {}, {}, mockLogger); + const queue = trackQueue(new Queue('test-queue', mockRedisConfig, {}, {}, mockLogger)); expect(queue).toBeDefined(); }); @@ -48,19 +68,19 @@ describe('Queue Class', () => { serviceName: 'test-service', }; - const queue = new Queue('test-queue', mockRedisConfig, {}, workerConfig); + const queue = trackQueue(new Queue('test-queue', mockRedisConfig, {}, workerConfig)); expect(queue).toBeDefined(); }); }); describe('queue naming and utilities', () => { it('should return queue name', () => { - const queue = new Queue('my-test-queue', mockRedisConfig); + const queue = trackQueue(new Queue('my-test-queue', mockRedisConfig)); expect(queue.getName()).toBe('my-test-queue'); }); it('should get bull queue instance', () => { - const queue = new Queue('test-queue', mockRedisConfig); + const queue = trackQueue(new Queue('test-queue', mockRedisConfig)); const bullQueue = queue.getBullQueue(); expect(bullQueue).toBeDefined(); }); @@ -83,7 +103,7 @@ describe('Queue Class', () => { child: mock(() => mockChildLogger), }; - const queue = new Queue('test-queue', mockRedisConfig, {}, {}, mockLogger); + const queue = trackQueue(new Queue('test-queue', mockRedisConfig, {}, {}, mockLogger)); const childLogger = queue.createChildLogger('batch', { batchId: '123' }); expect(childLogger).toBe(mockChildLogger); @@ -99,7 +119,7 @@ describe('Queue Class', () => { trace: mock(() => {}), }; - const queue = new Queue('test-queue', mockRedisConfig, {}, {}, mockLogger); + const queue = trackQueue(new Queue('test-queue', mockRedisConfig, {}, {}, mockLogger)); const childLogger = queue.createChildLogger('batch', { batchId: '123' }); expect(childLogger).toBe(mockLogger); @@ -108,7 +128,7 @@ describe('Queue Class', () => { describe('worker count methods', () => { it('should get worker count when no workers', () => { - const queue = new Queue('test-queue', mockRedisConfig); + const queue = trackQueue(new Queue('test-queue', mockRedisConfig)); expect(queue.getWorkerCount()).toBe(0); }); @@ -118,7 +138,7 @@ describe('Queue Class', () => { startWorker: false, // Don't actually start }; - const queue = new Queue('test-queue', mockRedisConfig, {}, workerConfig); + const queue = trackQueue(new Queue('test-queue', mockRedisConfig, {}, workerConfig)); // Workers aren't actually started with startWorker: false expect(queue.getWorkerCount()).toBe(0); }); diff --git a/libs/core/queue/test/queue.test.ts b/libs/core/queue/test/queue.test.ts index bd9d6f77..4f2c25c6 100644 --- a/libs/core/queue/test/queue.test.ts +++ b/libs/core/queue/test/queue.test.ts @@ -1,4 +1,4 @@ -import { describe, expect, it } from 'bun:test'; +import { afterEach, describe, expect, it } from 'bun:test'; import { createServiceCache, ServiceCache } from '../src/service-cache'; import { generateCachePrefix, @@ -78,39 +78,40 @@ describe('Service Utilities', () => { }); describe('ServiceCache', () => { - it('should create service cache', () => { - const mockRedisConfig = { - host: 'localhost', - port: 6379, - }; + // Use a non-QA isolated loopback port and non-shared clients so unit tests never touch QA Dragonfly (localhost:6379) + const mockRedisConfig = { + host: '127.0.0.1', + port: 16379, + maxRetriesPerRequest: 1, + retryDelay: 50, + }; + const createdCaches: ServiceCache[] = []; - // Since ServiceCache constructor internally creates a real cache, - // we can't easily test it without mocking the createCache function - // For now, just test that the function exists and returns something - const serviceCache = createServiceCache('myservice', mockRedisConfig); + afterEach(async () => { + await Promise.all(createdCaches.splice(0).map(cache => cache.disconnect().catch(() => {}))); + }); + + it('should create service cache', () => { + const serviceCache = createServiceCache('myservice', mockRedisConfig, { shared: false }); + createdCaches.push(serviceCache); expect(serviceCache).toBeDefined(); expect(serviceCache).toBeInstanceOf(ServiceCache); }); it('should handle cache prefix correctly', () => { - const mockRedisConfig = { - host: 'localhost', - port: 6379, - }; - - const serviceCache = createServiceCache('webApi', mockRedisConfig); + const serviceCache = createServiceCache('webApi', mockRedisConfig, { shared: false }); + createdCaches.push(serviceCache); expect(serviceCache).toBeDefined(); // The prefix is set internally as cache:web-api expect(serviceCache.getKey('test')).toBe('cache:web-api:test'); }); it('should support global cache option', () => { - const mockRedisConfig = { - host: 'localhost', - port: 6379, - }; - - const globalCache = createServiceCache('myservice', mockRedisConfig, { global: true }); + const globalCache = createServiceCache('myservice', mockRedisConfig, { + global: true, + shared: false, + }); + createdCaches.push(globalCache); expect(globalCache).toBeDefined(); // Global cache uses a different prefix expect(globalCache.getKey('test')).toBe('stock-bot:shared:test'); @@ -120,16 +121,16 @@ describe('ServiceCache', () => { describe('Batch Processing', () => { it('should handle batch job data types', () => { const batchJob: BatchJobData = { - items: [1, 2, 3], - options: { - batchSize: 10, - concurrency: 2, - }, + payloadKey: 'batch:payload:1', + batchIndex: 0, + totalBatches: 3, + itemCount: 10, + totalDelayHours: 1, }; - expect(batchJob.items).toHaveLength(3); - expect(batchJob.options.batchSize).toBe(10); - expect(batchJob.options.concurrency).toBe(2); + expect(batchJob.payloadKey).toBe('batch:payload:1'); + expect(batchJob.totalBatches).toBe(3); + expect(batchJob.itemCount).toBe(10); }); it('should process batch results', () => { diff --git a/libs/core/shutdown/src/shutdown.ts b/libs/core/shutdown/src/shutdown.ts index fbf8c6d9..4ffe4fba 100644 --- a/libs/core/shutdown/src/shutdown.ts +++ b/libs/core/shutdown/src/shutdown.ts @@ -15,6 +15,7 @@ export class Shutdown { private shutdownTimeout: number; private callbacks: CallbackEntry[] = []; private signalHandlersRegistered = false; + private registeredSignalHandlers = new Map void>(); private shutdownPromise: Promise | null = null; private triggerSignal: string | null = null; @@ -33,6 +34,37 @@ export class Shutdown { return Shutdown.instance; } + /** + * Dispose the singleton instance and remove its signal listeners. + */ + static reset(): void { + if (Shutdown.instance) { + Shutdown.instance.dispose(); + Shutdown.instance = null; + } + } + + /** + * Remove process signal handlers registered by this instance. + */ + removeSignalHandlers(): void { + for (const [signal, listener] of this.registeredSignalHandlers) { + process.off(signal, listener); + } + this.registeredSignalHandlers.clear(); + this.signalHandlersRegistered = false; + } + + /** + * Clean up signal listeners and clear singleton reference if this is the active singleton. + */ + dispose(): void { + this.removeSignalHandlers(); + if (Shutdown.instance === this) { + Shutdown.instance = null; + } + } + /** * Get current shutdown status */ @@ -153,7 +185,7 @@ export class Shutdown { signals.forEach(signal => { // Use process.on instead of process.once to handle multiple signals - process.on(signal, async () => { + const listener = async () => { this.logger.info(`Received ${signal} signal`); // If already shutting down, ignore the signal @@ -178,7 +210,10 @@ export class Shutdown { process.exit(1); } - }); + }; + + this.registeredSignalHandlers.set(signal, listener); + process.on(signal, listener); this.logger.debug(`Registered handler for ${signal}`); }); diff --git a/libs/core/shutdown/test/shutdown-comprehensive.test.ts b/libs/core/shutdown/test/shutdown-comprehensive.test.ts index e0d434f7..a3d8f6c2 100644 --- a/libs/core/shutdown/test/shutdown-comprehensive.test.ts +++ b/libs/core/shutdown/test/shutdown-comprehensive.test.ts @@ -6,14 +6,15 @@ describe('Shutdown Comprehensive Tests', () => { beforeEach(() => { // Reset singleton instance for each test - (Shutdown as any).instance = null; + Shutdown.reset(); // Create a fresh instance for each test shutdownInstance = new Shutdown({ autoRegister: false }); }); afterEach(() => { - // Clean up singleton - (Shutdown as any).instance = null; + // Clean up singleton and any signal listeners + shutdownInstance?.dispose(); + Shutdown.reset(); }); describe('Basic Functionality', () => { @@ -250,10 +251,18 @@ describe('Shutdown Comprehensive Tests', () => { }); it('should use default timeout', () => { - const _defaultShutdown = new Shutdown(); + const defaultShutdown = new Shutdown(); + let secondShutdown: Shutdown | undefined; - // Can't directly test timeout value, but we can verify it doesn't throw - expect(() => new Shutdown()).not.toThrow(); + try { + // Can't directly test timeout value, but we can verify it doesn't throw + expect(() => { + secondShutdown = new Shutdown(); + }).not.toThrow(); + } finally { + defaultShutdown.dispose(); + secondShutdown?.dispose(); + } }); }); }); diff --git a/libs/core/shutdown/test/shutdown-signals.test.ts b/libs/core/shutdown/test/shutdown-signals.test.ts index be3f4118..22fca3f0 100644 --- a/libs/core/shutdown/test/shutdown-signals.test.ts +++ b/libs/core/shutdown/test/shutdown-signals.test.ts @@ -1,46 +1,46 @@ -import { afterEach, beforeEach, describe, expect, it, mock } from 'bun:test'; +import { afterEach, beforeEach, describe, expect, it, mock, spyOn } from 'bun:test'; import { Shutdown } from '../src/shutdown'; describe('Shutdown Signal Handlers', () => { - let shutdown: Shutdown; - let processOnceSpy: any; - let processExitSpy: any; - const originalOn = process.on; - const originalExit = process.exit; + let shutdown: Shutdown | undefined; + let processOnceSpy: ReturnType; + let processExitSpy: ReturnType; beforeEach(() => { // Reset singleton instance - (Shutdown as any).instance = null; + Shutdown.reset(); + shutdown = undefined; // Mock process.on to capture signal handlers const listeners: Record = {}; - processOnceSpy = mock((event: string, handler: Function) => { + processOnceSpy = spyOn(process, 'on').mockImplementation(((event: string, handler: Function) => { if (!listeners[event]) { listeners[event] = []; } listeners[event].push(handler); return process; - }); - process.on = processOnceSpy as any; + }) as any); // Mock process.exit - processExitSpy = mock((_code?: number) => { + processExitSpy = spyOn(process, 'exit').mockImplementation(((_code?: number) => { // Just record the call, don't actually exit return undefined as never; - }); - process.exit = processExitSpy as any; + }) as any); // Store listeners for manual triggering (global as any).__testListeners = listeners; }); afterEach(() => { - // Restore original methods - process.on = originalOn; - process.exit = originalExit; + // Clean up any registered listeners and singleton before restoring process spies + shutdown?.dispose(); + shutdown = undefined; + Shutdown.reset(); + + // Restore original methods + processOnceSpy?.mockRestore(); + processExitSpy?.mockRestore(); - // Clean up - (Shutdown as any).instance = null; delete (global as any).__testListeners; }); diff --git a/libs/core/shutdown/test/shutdown.test.ts b/libs/core/shutdown/test/shutdown.test.ts index 6e4e5964..0faeb0bf 100644 --- a/libs/core/shutdown/test/shutdown.test.ts +++ b/libs/core/shutdown/test/shutdown.test.ts @@ -5,14 +5,14 @@ describe('Shutdown', () => { let shutdown: Shutdown; beforeEach(() => { - // Reset singleton instance for each test - (Shutdown as any).instance = null; - shutdown = Shutdown.getInstance({ timeout: 1000 }); + // Reset singleton instance and remove any prior signal listeners + Shutdown.reset(); + shutdown = Shutdown.getInstance({ timeout: 1000, autoRegister: false }); }); afterEach(() => { - // Clean up - (Shutdown as any).instance = null; + // Clean up listeners and singleton + Shutdown.reset(); }); describe('getInstance', () => { @@ -24,7 +24,8 @@ describe('Shutdown', () => { }); it('should use provided config on first call', () => { - const instance = Shutdown.getInstance({ timeout: 5000 }); + Shutdown.reset(); + const instance = Shutdown.getInstance({ timeout: 5000, autoRegister: false }); expect(instance).toBeDefined(); }); }); @@ -125,20 +126,28 @@ describe('Shutdown', () => { }); it('should respect timeout', async () => { + let slowTimer: ReturnType | undefined; const slowHandler = mock(async () => { - await new Promise(resolve => setTimeout(resolve, 2000)); + await new Promise(resolve => { + slowTimer = setTimeout(resolve, 2000); + }); }); - shutdown = Shutdown.getInstance({ timeout: 100 }); + Shutdown.reset(); + shutdown = Shutdown.getInstance({ timeout: 100, autoRegister: false }); shutdown.onShutdown(slowHandler, 10, 'Slow Handler'); const start = Date.now(); - await expect(shutdown.shutdown()).rejects.toThrow('Shutdown timeout'); + try { + await expect(shutdown.shutdown()).rejects.toThrow('Shutdown timeout'); + } finally { + clearTimeout(slowTimer); + } const duration = Date.now() - start; // Shutdown waits for timeout (100ms) plus some processing time expect(duration).toBeGreaterThan(90); - expect(duration).toBeLessThan(1500); // But not the full 2000ms + expect(duration).toBeLessThan(500); }); }); @@ -161,8 +170,8 @@ describe('Shutdown', () => { await shutdown.shutdown(); // Reset by creating new instance - (Shutdown as any).instance = null; - shutdown = Shutdown.getInstance({ timeout: 1000 }); + Shutdown.reset(); + shutdown = Shutdown.getInstance({ timeout: 1000, autoRegister: false }); shutdown.onShutdown(handler, 10, 'Handler'); await shutdown.shutdown(); diff --git a/test/setup.ts b/test/setup.ts index 9c786868..b145a4f7 100644 --- a/test/setup.ts +++ b/test/setup.ts @@ -9,7 +9,13 @@ // Bun.timeout = 30000; // Store original console methods to allow restoration -const originalConsole = global.console; +const originalConsoleMethods = { + log: console.log.bind(console), + debug: console.debug.bind(console), + info: console.info.bind(console), + warn: console.warn.bind(console), + error: console.error.bind(console), +}; // Mock console methods to reduce noise during tests // These can be restored with testHelpers.restoreConsole() @@ -98,7 +104,11 @@ global.testHelpers = { * Restore console methods */ restoreConsole: () => { - global.console = originalConsole; + console.log = originalConsoleMethods.log; + console.debug = originalConsoleMethods.debug; + console.info = originalConsoleMethods.info; + console.warn = originalConsoleMethods.warn; + console.error = originalConsoleMethods.error; } };