import { existsSync, mkdtempSync, readFileSync, rmSync } from 'node:fs'; import { tmpdir } from 'node:os'; import { join } from 'node:path'; import { fileURLToPath } from 'node:url'; import { afterEach, describe, expect, test } from 'bun:test'; import { classifySourceExchanges, EXPLICIT_EXCHANGE_SOURCE_MAP_ROWS, generateExchangeSeedFromMongo, generateExchangeSeedSql, generateUnresolvedExchangesMarkdown, ISO_EXCHANGE_SEEDS, normalizeRawExchangeDoc, parseGenerateExchangeSeedArgs, resolveReadOnlyMongoClientConfig, type ExchangeSource, type ReadOnlyExchangeMongoClient, } from '../../apps/stock/data-pipeline/src/security-master'; const committedSeedPath = fileURLToPath( new URL('../../database/postgres/init/35-security-master-exchange-seed.sql', import.meta.url) ); const tempDirs: string[] = []; afterEach(() => { for (const dir of tempDirs.splice(0)) { rmSync(dir, { recursive: true, force: true }); } }); describe('Pass 1 classifier edge cases', () => { test('explicit rule matches after trim/uppercase even when the record carries a multi-valued OperatingMIC', () => { const result = classifySourceExchanges([ { source: 'eod', code: ' us ', operatingMic: 'XNAS, XNYS' }, ]); expect(result.unresolved).toEqual([]); expect(result.mapped).toEqual([ { source: 'eod', sourceCode: 'US', role: 'composite', mic: null, countryIso: 'US', method: 'explicit_rule', reviewedBy: null, }, ]); }); test('a repeated MIC inside one multi-valued string is still unresolved, not picked', () => { const result = classifySourceExchanges([ { source: 'eod', code: 'DUP', operatingMic: 'XNAS,XNAS' }, ]); expect(result.mapped).toEqual([]); expect(result.unresolved.map(row => row.reason)).toEqual(['multi_valued_operating_mic']); }); test('a multi-valued duplicate wins over a clean duplicate of the same code (no silent first pick)', () => { const result = classifySourceExchanges([ { source: 'eod', code: 'MIX', operatingMic: 'XNAS' }, { source: 'eod', code: 'mix', operatingMic: 'XNAS; XNYS' }, ]); expect(result.mapped).toEqual([]); expect(result.unresolved).toHaveLength(1); expect(result.unresolved[0]?.reason).toBe('multi_valued_operating_mic'); }); test('same code under different sources stays as separate rows; explicit rules are per-source', () => { const result = classifySourceExchanges([ { source: 'ceo', code: 'TSX' }, { source: 'qm', code: 'TSX' }, { source: 'ib', code: 'TSX', operatingMic: 'XTSE' }, ]); expect(result.mapped.map(row => [row.source, row.sourceCode, row.mic, row.method])).toEqual([ ['ceo', 'TSX', 'XTSE', 'explicit_rule'], ['ib', 'TSX', 'XTSE', 'operating_mic'], ]); // qm TSX has no explicit rule and no MIC: must not borrow the CEO mapping. expect(result.unresolved.map(row => [row.source, row.sourceCode, row.reason])).toEqual([ ['qm', 'TSX', 'missing_operating_mic'], ]); }); test('source names are case-sensitive and the error names both source and code', () => { expect(() => classifySourceExchanges([{ source: 'EOD' as unknown as ExchangeSource, code: 'US' }]) ).toThrow('Unknown exchange source "EOD" for exchange code "US"'); }); test('an unknown source anywhere in the batch throws even after valid records', () => { expect(() => classifySourceExchanges([ { source: 'eod', code: 'US' }, { source: 'bloomberg' as unknown as ExchangeSource, code: 'XNYS' }, ]) ).toThrow(/bloomberg.*XNYS/); }); test('a MIC outside the supplied knownExchanges is unknown even if it is a real ISO MIC', () => { const onlyTsx = ISO_EXCHANGE_SEEDS.filter(row => row.mic === 'XTSE'); const result = classifySourceExchanges( [ { source: 'eod', code: 'TO', operatingMic: 'XTSE' }, { source: 'eod', code: 'NASDAQ', operatingMic: 'XNAS' }, ], { knownExchanges: onlyTsx } ); expect(result.mapped.map(row => row.sourceCode)).toEqual(['TO']); expect(result.unresolved.map(row => [row.sourceCode, row.reason])).toEqual([ ['NASDAQ', 'unknown_operating_mic'], ]); }); test('routes source codes longer than 32 chars to unresolved and rejects them in SQL generation (T-44)', () => { const exact32 = 'A'.repeat(32); const tooLong33 = 'B'.repeat(33); const result = classifySourceExchanges([ { source: 'eod', code: exact32, operatingMic: 'XNAS' }, { source: 'eod', code: tooLong33, operatingMic: 'XNAS' }, ]); expect(result.mapped.map(row => row.sourceCode)).toEqual([exact32]); expect(result.unresolved.map(row => [row.sourceCode, row.reason])).toEqual([ [tooLong33, 'source_code_too_long'], ]); expect(() => generateExchangeSeedSql({ mappings: [ { source: 'eod', sourceCode: tooLong33, role: 'primary_venue', mic: 'XNAS', countryIso: 'US', method: 'operating_mic', }, ], }) ).toThrow(/length must be between 1 and 32/); }); test('deduplicates identical (source, source_code) rows and rejects conflicting duplicates in SQL generation (T-45)', () => { const row = { source: 'eod' as const, sourceCode: 'NASDAQ', role: 'primary_venue' as const, mic: 'XNAS', countryIso: 'US', method: 'operating_mic' as const, }; const sql = generateExchangeSeedSql({ mappings: [row, { ...row }] }); expect(sql.match(/'eod', 'NASDAQ'/g)).toHaveLength(1); expect(() => generateExchangeSeedSql({ mappings: [row, { ...row, mic: 'XNYS' }], }) ).toThrow(/Conflicting duplicate exchange_source_map row/); }); test('classification output is identical for every rotation of the input', () => { const records = [ { source: 'eod' as const, code: 'TO', operatingMic: 'XTSE', name: 'Toronto' }, { source: 'eod' as const, code: 'to', operatingMic: 'xtse', name: 'TSX' }, { source: 'ib' as const, code: 'IEX' }, { source: 'qm' as const, code: 'X1', operatingMic: 'XLON' }, { source: 'qm' as const, code: '', name: 'blank' }, ]; const baseline = classifySourceExchanges(records); for (let shift = 1; shift < records.length; shift++) { const rotated = [...records.slice(shift), ...records.slice(0, shift)]; expect(classifySourceExchanges(rotated)).toEqual(baseline); } }); }); describe('Pass 1 raw document normalization edge cases', () => { test('falls through non-string and blank aliases to the next field spelling', () => { expect(normalizeRawExchangeDoc('ib', { id: 42, exchange_id: 'NYSE' }).code).toBe('NYSE'); expect(normalizeRawExchangeDoc('eod', { Code: ' ', code: 'TO' }).code).toBe('TO'); }); test('a document with no recognised code field normalizes to an empty code that lands in unresolved', () => { const record = normalizeRawExchangeDoc('qm', { foo: 'bar', name: 'Orphan' }); expect(record.code).toBe(''); const result = classifySourceExchanges([record]); expect(result.mapped).toEqual([]); expect(result.unresolved).toEqual([ { source: 'qm', sourceCode: '', rawCode: '', name: 'Orphan', country: null, operatingMic: null, currency: null, reason: 'empty_code', }, ]); }); test('unknown source throws naming the source and the code found in the document', () => { expect(() => normalizeRawExchangeDoc('yahoo' as unknown as ExchangeSource, { Code: 'NYQ' }) ).toThrow(/yahoo.*NYQ/); }); }); describe('Pass 1 SQL generator and committed seed edge cases', () => { test('empty input emits only the header comment and no INSERT statements', () => { const sql = generateExchangeSeedSql({ mappings: [] }); expect(sql).not.toContain('INSERT'); expect(sql.endsWith('\n')).toBe(true); }); test('committed seed is self-contained: no meta-commands, no schema qualifiers, no CREATE DATABASE', () => { const committed = readFileSync(committedSeedPath, 'utf8'); expect(committed).not.toMatch(/^\s*\\/m); expect(committed).not.toMatch(/CREATE\s+DATABASE/i); expect(committed).not.toMatch(/\b(public|stock_bot\w*)\.(exchange|exchange_source_map)\b/i); expect(committed).not.toMatch(/now\(\)|current_timestamp/i); expect(committed).toContain('ON CONFLICT (mic) DO NOTHING;'); expect(committed).toContain('WHERE exchange_source_map.reviewed_by IS NULL;'); }); test('committed seed covers exactly the 11 MICs and 17 explicit mappings, all unreviewed', () => { const committed = readFileSync(committedSeedPath, 'utf8'); const exchangeRows = committed.match(/^ {2}\('[A-Z0-9]{4}', '/gm) ?? []; const mappingRows = committed.match(/^ {2}\('(eod|qm|ib|ceo)', /gm) ?? []; expect(exchangeRows).toHaveLength(11); expect(mappingRows).toHaveLength(17); expect(ISO_EXCHANGE_SEEDS).toHaveLength(11); expect(EXPLICIT_EXCHANGE_SOURCE_MAP_ROWS).toHaveLength(17); for (const row of EXPLICIT_EXCHANGE_SOURCE_MAP_ROWS) { expect(row.reviewedBy).toBeNull(); } }); test('every non-null mic in the explicit rules refers to a seeded exchange', () => { const seeded = new Set(ISO_EXCHANGE_SEEDS.map(row => row.mic)); for (const row of EXPLICIT_EXCHANGE_SOURCE_MAP_ROWS) { if (row.mic !== null) { expect(seeded.has(row.mic)).toBe(true); } } }); test('seed data is internally consistent: CA venues tsx_tiered/CAD/Toronto, US venues us_100/USD/New_York', () => { for (const row of ISO_EXCHANGE_SEEDS) { if (row.countryIso === 'CA') { expect([row.boardLotPolicy, row.currency, row.timezone]).toEqual([ 'tsx_tiered', 'CAD', 'America/Toronto', ]); } else { expect(row.countryIso).toBe('US'); expect([row.boardLotPolicy, row.currency, row.timezone]).toEqual([ 'us_100', 'USD', 'America/New_York', ]); } expect(row.calendarCode.length).toBeGreaterThan(0); } }); test('backslashes pass through untouched (standard_conforming_strings literal) while quotes double', () => { const sql = generateExchangeSeedSql({ mappings: [ { source: 'qm', sourceCode: "A\\B'C", role: 'primary_venue', mic: 'XNYS', countryIso: 'US', method: 'operating_mic', reviewedBy: "o'neil", }, ], }); expect(sql).toContain( "('qm', 'A\\B''C', 'primary_venue', 'XNYS', 'US', 'operating_mic', 'o''neil')" ); }); test('NUL byte in any mapping field aborts generation instead of emitting truncated SQL', () => { expect(() => generateExchangeSeedSql({ mappings: [ { source: 'eod', sourceCode: 'BAD\0', role: 'composite', mic: null, countryIso: null, method: 'explicit_rule', }, ], }) ).toThrow(/NUL/); }); test('Markdown report states that everything resolved when there are no unresolved rows', () => { const md = generateUnresolvedExchangesMarkdown( classifySourceExchanges([{ source: 'eod', code: 'US' }]) ); expect(md).toContain('- Mapped: 1'); expect(md).toContain('- Unresolved: 0'); expect(md).toContain('All source exchange records resolved cleanly.'); expect(md).not.toContain('| Source |'); }); }); describe('Pass 1 read-only generator wrapper edge cases', () => { test('a failing find propagates and leaves no partial output files behind', async () => { const dir = mkdtempSync(join(tmpdir(), 'pass1-seed-fail-')); tempDirs.push(dir); const sqlOutPath = join(dir, 'seed.sql'); const reportOutPath = join(dir, 'report.md'); const failing: ReadOnlyExchangeMongoClient = { isReadOnly: () => true, find: async >(collection: string): Promise => { if (collection === 'qmExchanges') { throw new Error('cursor killed'); } return []; }, }; await expect( generateExchangeSeedFromMongo(failing, { sqlOutPath, reportOutPath }) ).rejects.toThrow('cursor killed'); expect(existsSync(sqlOutPath)).toBe(false); expect(existsSync(reportOutPath)).toBe(false); }); test('an unrecognised raw document shape never makes the wrapper guess a mapping', async () => { const dir = mkdtempSync(join(tmpdir(), 'pass1-seed-shape-')); tempDirs.push(dir); const mongo: ReadOnlyExchangeMongoClient = { isReadOnly: () => true, find: async >(collection: string): Promise => (collection === 'ibExchanges' ? [{ unexpected: 'NYSE', OperatingMIC: 'XNYS' }] : []) as unknown as T[], }; const output = await generateExchangeSeedFromMongo(mongo, { sqlOutPath: join(dir, 'seed.sql'), reportOutPath: join(dir, 'report.md'), }); expect(output.classification.mapped).toEqual([]); expect(output.classification.unresolved.map(row => [row.source, row.reason])).toEqual([ ['ib', 'empty_code'], ]); expect(output.sql).not.toContain('INSERT INTO exchange_source_map'); }); test('CLI rejects a flag used as the value of another flag', () => { expect(() => parseGenerateExchangeSeedArgs(['--report-out', '--sql-out', 'a.sql'])).toThrow( 'Missing value for --report-out' ); expect(() => parseGenerateExchangeSeedArgs(['--sql-out='])).toThrow( 'Missing value for --sql-out' ); }); test('without readUri the config falls back to uri but is still forced read-only', () => { const resolved = resolveReadOnlyMongoClientConfig({ database: { mongodb: { enabled: true, host: 'localhost', port: 27018, database: 'stock_dev', uri: 'mongodb://localhost:27018/stock_dev', readOnly: false, poolSize: 5, }, postgres: {} as never, questdb: {} as never, dragonfly: {} as never, }, }); expect(resolved.readOnly).toBe(true); expect(resolved.uri).toBe('mongodb://localhost:27018/stock_dev'); expect(resolved.database).toBe('stock_dev'); }); });