From 297a7615bb56fa54ecf4fea05d94c507f7465fe4 Mon Sep 17 00:00:00 2001 From: Studio Date: Sat, 28 Nov 2026 06:33:12 -0500 Subject: [PATCH] T-89: tests --- test/unit/security-master-run-cli.test.ts | 456 ++++++++++++++++++++++ 1 file changed, 456 insertions(+) diff --git a/test/unit/security-master-run-cli.test.ts b/test/unit/security-master-run-cli.test.ts index 01d9a32a..66cdad87 100644 --- a/test/unit/security-master-run-cli.test.ts +++ b/test/unit/security-master-run-cli.test.ts @@ -1062,3 +1062,459 @@ describe('runSecurityMaster', () => { expect(parsedStats.reportSummary.conflicts).toBe(0); }); }); + +describe('runSecurityMaster (QA edge cases)', () => { + async function captureRejection(promise: Promise): Promise { + try { + await promise; + } catch (error) { + expect(error).toBeInstanceOf(Error); + return error as Error; + } + throw new Error('expected promise to reject'); + } + + function buildPgConfig(overrides: { + environment?: 'development' | 'qa'; + enabled?: boolean; + port: number; + database: string; + }) { + const environment = overrides.environment ?? 'development'; + return stockAppSchema.parse({ + name: 'stock-bot', + version: '1.0.0', + environment, + service: { name: 'data-pipeline', port: 2002 }, + log: { level: 'info' }, + database: { + postgres: { + enabled: overrides.enabled ?? true, + host: 'localhost', + port: overrides.port, + database: overrides.database, + user: 'trading_user', + password: 'dev_password', + }, + mongodb: { + enabled: true, + uri: 'mongodb://localhost:27018/stock_dev', + readUri: 'mongodb://studio_stock_bot_read:pass@localhost:27017/stock?authSource=stock', + readOnly: true, + database: 'stock_dev', + }, + questdb: { enabled: false }, + dragonfly: { enabled: false }, + }, + providers: {}, + features: {}, + }); + } + + test('failing env-safety guard runs before any MongoDB read', async () => { + const fakeMongo = createStrictReadOnlyFakeMongo(buildUsCaFixture()); + let mongoClosed = 0; + + const error = await captureRejection( + runSecurityMaster( + { + mongoCollectionClient: fakeMongo.mongoCollectionClient, + barSpanReader: fakeMongo.barSpanReader, + closeMongo: () => { + mongoClosed += 1; + }, + assertSafety: () => { + throw new Error('blocked'); + }, + createPostgresClient: () => { + throw new Error('must not be called'); + }, + writeStdout: () => {}, + }, + { asOfDate: '2026-01-15', outDir: createTempDir(), persist: true } + ) + ); + + expect(error.message).toContain('env-safety'); + expect(fakeMongo.findCalls).toHaveLength(0); + expect(fakeMongo.aggregateCalls).toHaveLength(0); + expect(mongoClosed).toBe(1); + }); + + test('--persist without guard or PostgreSQL factory rejects at env-safety with no reads or writes', async () => { + for (const missing of ['assertSafety', 'createPostgresClient'] as const) { + const fakeMongo = createStrictReadOnlyFakeMongo(buildUsCaFixture()); + const writes: string[] = []; + let mongoClosed = 0; + + const error = await captureRejection( + runSecurityMaster( + { + mongoCollectionClient: fakeMongo.mongoCollectionClient, + barSpanReader: fakeMongo.barSpanReader, + closeMongo: () => { + mongoClosed += 1; + }, + ...(missing === 'assertSafety' + ? { + createPostgresClient: () => { + throw new Error('must not be called'); + }, + } + : { assertSafety: () => {} }), + writeFile: filePath => { + writes.push(filePath); + }, + writeStdout: () => {}, + }, + { asOfDate: '2026-01-15', outDir: createTempDir(), persist: true } + ) + ); + + expect(error.message).toContain('env-safety'); + expect(error.message).toContain(missing); + expect(fakeMongo.findCalls).toHaveLength(0); + expect(writes).toHaveLength(0); + expect(mongoClosed).toBe(1); + } + }); + + test('invalid asOfDate or empty outDir passed programmatically rejects at validate-options before Mongo', async () => { + const cases = [ + { asOfDate: '2023-02-29', outDir: '/tmp/x' }, + { asOfDate: '20260115', outDir: '/tmp/x' }, + { asOfDate: '2026-01-15', outDir: ' ' }, + ]; + for (const options of cases) { + const fakeMongo = createStrictReadOnlyFakeMongo(buildUsCaFixture()); + let mongoClosed = 0; + const error = await captureRejection( + runSecurityMaster( + { + mongoCollectionClient: fakeMongo.mongoCollectionClient, + barSpanReader: fakeMongo.barSpanReader, + closeMongo: () => { + mongoClosed += 1; + }, + writeStdout: () => {}, + }, + options + ) + ); + expect(error.message).toContain('validate-options'); + expect(fakeMongo.findCalls).toHaveLength(0); + expect(mongoClosed).toBe(1); + } + }); + + test('exchange collection read failure rejects at read-exchanges, writes nothing, closes Mongo', async () => { + const fakeMongo = createStrictReadOnlyFakeMongo(buildUsCaFixture(), { + failCollection: 'ibExchanges', + }); + const writes: string[] = []; + const stdout: string[] = []; + let mongoClosed = 0; + + const error = await captureRejection( + runSecurityMaster( + { + mongoCollectionClient: fakeMongo.mongoCollectionClient, + barSpanReader: fakeMongo.barSpanReader, + closeMongo: () => { + mongoClosed += 1; + }, + writeFile: filePath => { + writes.push(filePath); + }, + writeStdout: text => stdout.push(text), + }, + { asOfDate: '2026-01-15', outDir: createTempDir() } + ) + ); + + expect(error.message).toContain('read-exchanges'); + expect((error.cause as Error).message).toContain('ibExchanges'); + expect(writes).toHaveLength(0); + expect(stdout).toHaveLength(0); + expect(mongoClosed).toBe(1); + }); + + test('write failure on a later file never opens PostgreSQL under --persist', async () => { + const fakeMongo = createStrictReadOnlyFakeMongo(buildUsCaFixture()); + const writes: string[] = []; + let pgFactoryCalls = 0; + let mongoClosed = 0; + + const error = await captureRejection( + runSecurityMaster( + { + mongoCollectionClient: fakeMongo.mongoCollectionClient, + barSpanReader: fakeMongo.barSpanReader, + closeMongo: () => { + mongoClosed += 1; + }, + assertSafety: () => {}, + createPostgresClient: () => { + pgFactoryCalls += 1; + throw new Error('must not be called'); + }, + writeFile: filePath => { + writes.push(filePath); + if (writes.length === 3) { + throw new Error('EACCES'); + } + }, + writeStdout: () => {}, + }, + { asOfDate: '2026-01-15', outDir: '/virtual/out', persist: true } + ) + ); + + expect(error.message).toContain('write-files'); + expect(writes).toEqual([ + join('/virtual/out', 'match-report.md'), + join('/virtual/out', 'conflicts.csv'), + join('/virtual/out', 'override-template.sql'), + ]); + expect(pgFactoryCalls).toBe(0); + expect(mongoClosed).toBe(1); + }); + + test('PostgreSQL factory failure rejects at persist after artifacts exist and closes Mongo', async () => { + const fakeMongo = createStrictReadOnlyFakeMongo(buildUsCaFixture()); + const outDir = createTempDir(); + const stdout: string[] = []; + let mongoClosed = 0; + let persistCalls = 0; + const connectErr = new Error('ECONNREFUSED 127.0.0.1:5433'); + + const error = await captureRejection( + runSecurityMaster( + { + mongoCollectionClient: fakeMongo.mongoCollectionClient, + barSpanReader: fakeMongo.barSpanReader, + closeMongo: () => { + mongoClosed += 1; + }, + assertSafety: () => {}, + createPostgresClient: async () => { + throw connectErr; + }, + persistFn: async () => { + persistCalls += 1; + return makeFakePersistResult(); + }, + writeStdout: text => stdout.push(text), + }, + { asOfDate: '2026-01-15', outDir, persist: true } + ) + ); + + expect(error.message).toContain('"persist"'); + expect(error.cause).toBe(connectErr); + expect(persistCalls).toBe(0); + expect(mongoClosed).toBe(1); + expect(stdout).toHaveLength(0); + for (const filename of Object.values(SECURITY_MASTER_OUTPUT_FILES)) { + expect(readFileSync(join(outDir, filename), 'utf8').length).toBeGreaterThan(0); + } + }); + + test('PostgreSQL close failure after successful persist rejects and suppresses the summary', async () => { + const fakeMongo = createStrictReadOnlyFakeMongo(buildUsCaFixture()); + const stdout: string[] = []; + let mongoClosed = 0; + const closeErr = new Error('pool end failed'); + + const error = await captureRejection( + runSecurityMaster( + { + mongoCollectionClient: fakeMongo.mongoCollectionClient, + barSpanReader: fakeMongo.barSpanReader, + closeMongo: () => { + mongoClosed += 1; + }, + assertSafety: () => {}, + createPostgresClient: () => ({ + queryable: { + async query() { + return { rows: [] }; + }, + }, + close: () => { + throw closeErr; + }, + }), + persistFn: async () => makeFakePersistResult(), + writeStdout: text => stdout.push(text), + }, + { asOfDate: '2026-01-15', outDir: createTempDir(), persist: true } + ) + ); + + expect(error.message).toContain('"persist"'); + expect(error.cause).toBe(closeErr); + expect(mongoClosed).toBe(1); + expect(stdout).toHaveLength(0); + }); + + test('persist failure is not masked by a secondary PostgreSQL close failure', async () => { + const fakeMongo = createStrictReadOnlyFakeMongo(buildUsCaFixture()); + const persistErr = new Error('unique violation'); + let pgClosed = 0; + + const error = await captureRejection( + runSecurityMaster( + { + mongoCollectionClient: fakeMongo.mongoCollectionClient, + barSpanReader: fakeMongo.barSpanReader, + assertSafety: () => {}, + createPostgresClient: () => ({ + queryable: { + async query() { + return { rows: [] }; + }, + }, + close: () => { + pgClosed += 1; + throw new Error('secondary close error'); + }, + }), + persistFn: async () => { + throw persistErr; + }, + writeStdout: () => {}, + }, + { asOfDate: '2026-01-15', outDir: createTempDir(), persist: true } + ) + ); + + expect(error.cause).toBe(persistErr); + expect(pgClosed).toBe(1); + }); + + test('bar spans are targeted to sorted in-scope EOD and QM ids and stats reconcile', async () => { + const fakeMongo = createStrictReadOnlyFakeMongo(buildUsCaFixture()); + const outDir = createTempDir(); + + const result = await runSecurityMaster( + { + mongoCollectionClient: fakeMongo.mongoCollectionClient, + barSpanReader: fakeMongo.barSpanReader, + writeStdout: () => {}, + }, + { asOfDate: '2026-01-15', outDir } + ); + + const requested = new Map( + fakeMongo.aggregateCalls.map(call => [ + call.collectionName, + [...(extractRequestedIdsFromPipeline(call.pipeline) ?? new Set(['']))], + ]) + ); + expect([...requested.keys()].sort()).toEqual(['eodPrices', 'qmPrices']); + expect(requested.get('eodPrices')).toEqual(['AAPL.US', 'SHOP.TO']); + expect(requested.get('qmPrices')).toEqual(['AAPL:US', 'MYSTERY:CA']); + + const stats = JSON.parse( + readFileSync(join(outDir, SECURITY_MASTER_OUTPUT_FILES.runStatsJson), 'utf8') + ) as { + exchanges: { + countsByCollection: Record; + mapped: number; + unresolved: number; + total: number; + }; + barSpans: { totalSpans: number; totalRowsRead: number }; + reportSummary: { instruments: number; listings: number; conflicts: number }; + }; + expect(stats.exchanges.countsByCollection).toEqual({ ceo: 0, eod: 2, ib: 2, qm: 2 }); + expect(stats.exchanges.total).toBe(stats.exchanges.mapped + stats.exchanges.unresolved); + expect(stats.barSpans.totalSpans).toBe(4); + expect(stats.reportSummary.instruments).toBe(result.composed.stageA.instruments.length); + expect(stats.reportSummary.listings).toBe(result.composed.stageB.listings.length); + expect(stats.reportSummary.conflicts).toBe(result.composed.report.conflicts.length); + expect(result.runStatsJson).toBe( + readFileSync(join(outDir, SECURITY_MASTER_OUTPUT_FILES.runStatsJson), 'utf8') + ); + }); + + test('summary is written exactly once and only after Mongo closes', async () => { + const fakeMongo = createStrictReadOnlyFakeMongo(buildUsCaFixture()); + const events: string[] = []; + + const result = await runSecurityMaster( + { + mongoCollectionClient: fakeMongo.mongoCollectionClient, + barSpanReader: fakeMongo.barSpanReader, + closeMongo: () => { + events.push('closeMongo'); + }, + writeStdout: text => { + events.push(`stdout:${text}`); + }, + }, + { asOfDate: '2026-01-15', outDir: createTempDir() } + ); + + expect(events).toEqual(['closeMongo', `stdout:${result.summary}`]); + }); + + test('assertSecurityMasterPersistSafety accepts dev safety DB and rejects disabled or non-dev targets', () => { + expect(() => + assertSecurityMasterPersistSafety( + buildPgConfig({ port: 5433, database: 'stock_bot_safety_qa' }), + {} + ) + ).not.toThrow(); + expect(() => + assertSecurityMasterPersistSafety(buildPgConfig({ port: 5433, database: 'analytics' }), {}) + ).toThrow(/isolated dev PostgreSQL database/); + expect(() => + assertSecurityMasterPersistSafety( + buildPgConfig({ enabled: false, port: 5433, database: 'trading_bot_dev' }), + {} + ) + ).toThrow(/PostgreSQL is disabled/); + expect(() => + assertSecurityMasterPersistSafety( + buildPgConfig({ environment: 'qa', port: 5433, database: 'trading_bot_dev' }), + {} + ) + ).toThrow(/qa environment/); + }); +}); + +describe('run-security-master CLI process', () => { + function runCliProcess(args: readonly string[]) { + const proc = Bun.spawnSync([process.execPath, 'run', cliSourcePath, ...args], { + stdout: 'pipe', + stderr: 'pipe', + env: { PATH: process.env.PATH ?? '', HOME: process.env.HOME ?? '' }, + }); + return { + exitCode: proc.exitCode, + stdout: proc.stdout.toString(), + stderr: proc.stderr.toString(), + }; + } + + test('--help exits 0 and prints usage without connecting to MongoDB', () => { + const result = runCliProcess(['--help']); + expect(result.exitCode).toBe(0); + expect(result.stdout).toContain(RUN_SECURITY_MASTER_USAGE); + }); + + test('usage errors exit non-zero with an Error line on stderr and no success summary', () => { + for (const args of [ + ['--as-of', '2026-02-30', '--out-dir', 'x'], + ['--bogus'], + ['--out-dir', 'x'], + ]) { + const result = runCliProcess(args); + expect(result.exitCode).toBe(1); + expect(result.stderr.startsWith('Error: ')).toBe(true); + expect(result.stdout).not.toContain('Security master run complete'); + } + }); +});