From c9a4adabad4c7f3a2f53e20b73699ad5886c2dbf Mon Sep 17 00:00:00 2001 From: Studio Date: Sat, 28 Nov 2026 04:42:46 -0500 Subject: [PATCH] T-86: tests --- ...ty-master-source-symbol-readers-qa.test.ts | 438 ++++++++++++++++++ 1 file changed, 438 insertions(+) create mode 100644 test/unit/security-master-source-symbol-readers-qa.test.ts diff --git a/test/unit/security-master-source-symbol-readers-qa.test.ts b/test/unit/security-master-source-symbol-readers-qa.test.ts new file mode 100644 index 00000000..105ba67c --- /dev/null +++ b/test/unit/security-master-source-symbol-readers-qa.test.ts @@ -0,0 +1,438 @@ +import { describe, expect, test } from 'bun:test'; +import { parseTickerDetailed } from '../../apps/stock/data-pipeline/src/normalization/ticker'; +import { + adaptCeoSymbolDoc, + adaptEodSymbolChangeDoc, + adaptEodSymbolDoc, + adaptIbSymbolDoc, + adaptQmSymbolDoc, + createExchangeSourceLookup, + createReadOnlyMongoSourceSymbolReader, + ISO_EXCHANGE_SEEDS, + readEodSymbols, + readIbSymbols, + readSecurityMasterSources, + SOURCE_SYMBOL_COLLECTIONS, + type ReadOnlyMongoCollectionClient, + type ReadOnlySourceSymbolReader, + type SourceCollectionReadStats, + type SourceSymbolFindOptions, +} from '../../apps/stock/data-pipeline/src/security-master'; + +// QA supplement for T-86: edge cases not covered by security-master-source-symbol-readers.test.ts. +// In-memory fakes only — no MongoDB or PostgreSQL connection is opened. + +const lookup = createExchangeSourceLookup(); +const micCurrencyMap = new Map(ISO_EXCHANGE_SEEDS.map(row => [row.mic, row.currency])); +const usCa: ReadonlySet = new Set(['US', 'CA']); + +function assertConservation(stats: SourceCollectionReadStats): void { + const skipped = Object.values(stats.skips).reduce((sum, n) => sum + n, 0); + expect(stats.docsRead).toBe(stats.emitted + skipped); +} + +function arrayReader( + collections: Readonly[]>> +): ReadOnlySourceSymbolReader & { calls: string[] } { + const calls: string[] = []; + return { + calls, + isReadOnly: () => true, + find>(name: string): AsyncIterable { + calls.push(name); + const docs = collections[name] ?? []; + return { + async *[Symbol.asyncIterator]() { + for (const doc of docs) { + yield doc as T; + } + }, + }; + }, + }; +} + +const MIXED_COUNTRY_EOD = [ + { + eodSearchCode: 'AAPL.US', + Code: 'AAPL', + Exchange: 'NASDAQ', + Country: 'USA', + Isin: 'US0378331005', + }, + { eodSearchCode: 'RY.TO', Code: 'RY', Exchange: 'TO', Country: 'Canada', Isin: 'CA7800871021' }, + { + eodSearchCode: 'SAP.XETRA', + Code: 'SAP', + Exchange: 'XETRA', + Country: 'Germany', + Isin: 'DE0007164600', + }, +]; + +describe('source-symbol-readers QA supplement', () => { + test('country option: [] emits nothing, null disables filtering, aliases like "usa" normalize', async () => { + const collections = { [SOURCE_SYMBOL_COLLECTIONS.eod]: MIXED_COUNTRY_EOD }; + const germanLookup = createExchangeSourceLookup([ + { + source: 'eod', + sourceCode: 'XETRA', + role: 'primary_venue', + mic: 'XETR', + countryIso: 'DE', + method: 'explicit_rule', + reviewedBy: 'qa', + }, + ]); + + const empty = await readEodSymbols(arrayReader(collections), { + exchangeLookup: germanLookup, + countries: [], + }); + expect(empty.stageARecords).toHaveLength(0); + expect(empty.stats.skips.outOfScopeCountry).toBe(3); + assertConservation(empty.stats); + + const all = await readEodSymbols(arrayReader(collections), { + exchangeLookup: germanLookup, + countries: null, + }); + expect(all.stageARecords.map(r => r.sourceId)).toEqual(['AAPL.US', 'RY.TO', 'SAP.XETRA']); + expect(all.stageARecords.find(r => r.sourceId === 'SAP.XETRA')?.country).toBe('DE'); + assertConservation(all.stats); + + const aliased = await readEodSymbols(arrayReader(collections), { + exchangeLookup: germanLookup, + countries: ['usa'], + }); + expect(aliased.stageARecords.map(r => r.sourceId)).toEqual(['AAPL.US']); + expect(aliased.stats.skips.outOfScopeCountry).toBe(2); + assertConservation(aliased.stats); + }); + + test('EOD: lowercase ISIN is uppercased, missing currency falls back to listing MIC currency, invalid-ISIN-only gives null issuer country', () => { + const ctx = { exchangeLookup: lookup, allowedCountries: usCa, micCurrencyMap }; + + const lower = adaptEodSymbolDoc( + { + eodSearchCode: 'AAPL.US', + Code: 'AAPL', + Exchange: 'NASDAQ', + Country: 'USA', + Isin: 'us0378331005', + }, + ctx + ); + expect(lower.ok).toBe(true); + if (lower.ok) { + expect(lower.stageARecord.isin).toBe('US0378331005'); + expect(lower.stageARecord.country).toBe('US'); + expect(lower.eodListing.currency).toBe('USD'); + expect(lower.eodListing.mic).toBe('XNAS'); + expect(lower.invalidIdentifiersNulled).toBe(0); + } + + // CA listing, bad ISIN check digit, no CUSIP -> issuer country unknown (never listing Country). + const bad = adaptEodSymbolDoc( + { + eodSearchCode: 'XX.TO', + Code: 'XX', + Exchange: 'TO', + Country: 'Canada', + Isin: 'CA52886N1024', + }, + ctx + ); + expect(bad.ok).toBe(true); + if (bad.ok) { + expect(bad.stageARecord.isin).toBeNull(); + expect(bad.stageARecord.country).toBeNull(); + expect(bad.eodListing.currency).toBe('CAD'); + expect(bad.invalidIdentifiersNulled).toBe(1); + } + }); + + test('IB: issuer country from ISIN beats listing country; CUSIP-only uses doc country; nothing valid gives null', () => { + const ctx = { exchangeLookup: lookup, allowedCountries: usCa }; + + // Irish-domiciled ADR listed in the US. + const ie = adaptIbSymbolDoc( + { + conid: 101, + symbol: 'ACN', + country: 'US', + currency: 'USD', + isin: 'IE00B4BNMY34', + exchangeId: 'NYSE', + }, + ctx + ); + expect(ie.ok && ie.stageARecord.country).toBe('IE'); + expect(ie.ok && ie.ibContract.primaryExchange).toBe('NYSE'); + + const cusipOnly = adaptIbSymbolDoc( + { + conid: 102, + symbol: 'AAPL', + country: 'US', + currency: 'USD', + cusip: '037833100', + exchangeId: 'AEQLIT', + }, + ctx + ); + expect(cusipOnly.ok && cusipOnly.stageARecord.country).toBe('US'); + expect(cusipOnly.ok && cusipOnly.ibContract.primaryExchange).toBeNull(); + + const nothing = adaptIbSymbolDoc( + { + conid: 103, + symbol: 'ZZZ', + country: 'CA', + currency: 'CAD', + isin: 'CATSETEST001', + cusip: '123456780', + }, + ctx + ); + expect(nothing.ok).toBe(true); + if (nothing.ok) { + expect(nothing.stageARecord.country).toBeNull(); + expect(nothing.stageARecord.isin).toBeNull(); + expect(nothing.invalidIdentifiersNulled).toBe(2); + } + + // Fractional conid and boolean conid are classified, not thrown. + expect(adaptIbSymbolDoc({ conid: 1.5, country: 'US' }, ctx)).toEqual({ + ok: false, + skipReason: 'invalidIdentifier', + }); + expect(adaptIbSymbolDoc({ conid: true, country: 'US' }, ctx)).toEqual({ + ok: false, + skipReason: 'invalidFieldType', + }); + expect(adaptIbSymbolDoc({ conid: 5, country: 'US', isin: 42 }, ctx)).toEqual({ + ok: false, + skipReason: 'invalidFieldType', + }); + }); + + test('CEO tickers round-trip through the Stage B parser without double-stripping .TO/.V', () => { + const ctx = { exchangeLookup: lookup, allowedCountries: usCa, micCurrencyMap }; + const cases: Array<[string, string, string, string]> = [ + // symbol, exchange, expected root, expected class suffix + ['BIP.UN.TO', 'TSX', 'BIP', 'UN'], + ['ABC.V', 'CDX', 'ABC', ''], + ['ABC.A.V', 'CDX', 'ABC', 'A'], + ['XYZ.TO.TO', 'TSX', 'XYZ', 'TO'], + ['RCI.B', 'TSX', 'RCI', 'B'], + ]; + for (const [symbol, exchange, root, suffix] of cases) { + const res = adaptCeoSymbolDoc({ ceoId: `ceo-${symbol}`, symbol, exchange }, ctx); + expect(res.ok).toBe(true); + if (!res.ok) { + continue; + } + const reparsed = parseTickerDetailed(res.tickerSource.ticker, 'ceo'); + expect(reparsed).toEqual({ ok: true, tickerRoot: root, classSuffix: suffix }); + expect(res.tickerSource.currency).toBe('CAD'); + } + const aql = adaptCeoSymbolDoc({ ceoId: 'n1', symbol: 'NEO1', exchange: 'aql' }, ctx); + expect(aql.ok && aql.tickerSource.mic).toBe('NEOE'); + }); + + test('CEO span: ceoSpans wins over lastSeen; lastSeen Date gives a single-day span; non-date lastSeen is invalidFieldType', () => { + const base = { exchangeLookup: lookup, allowedCountries: usCa, micCurrencyMap }; + const fromMap = adaptCeoSymbolDoc( + { ceoId: 'c1', symbol: 'RY.TO', exchange: 'TSX', lastSeen: '2024-05-01' }, + { + ...base, + ceoSpans: new Map([['c1', { firstBarDate: '2010-01-04', lastBarDate: '2024-04-30' }]]), + } + ); + expect(fromMap.ok && fromMap.tickerSource.span).toEqual({ + firstBarDate: '2010-01-04', + lastBarDate: '2024-04-30', + }); + + const fromDate = adaptCeoSymbolDoc( + { ceoId: 'c2', symbol: 'RY.TO', exchange: 'TSX', lastSeen: new Date('2024-05-01T12:00:00Z') }, + base + ); + expect(fromDate.ok && fromDate.tickerSource.span).toEqual({ + firstBarDate: '2024-05-01', + lastBarDate: '2024-05-01', + }); + + expect( + adaptCeoSymbolDoc({ ceoId: 'c3', symbol: 'RY', exchange: 'TSX', lastSeen: 12345 }, base) + ).toEqual({ + ok: false, + skipReason: 'invalidFieldType', + }); + }); + + test('QM: composite CCQ venue keeps null MIC and CAD fallback; ATS EDGX keeps routing role', () => { + const ctx = { exchangeLookup: lookup, allowedCountries: usCa, micCurrencyMap }; + const ccq = adaptQmSymbolDoc( + { qmSearchCode: 'RY:CCQ', symbol: 'RY', exchange: 'CCQ TSX' }, + ctx + ); + expect(ccq.ok && ccq.tickerSource).toMatchObject({ + mic: null, + role: 'composite', + currency: 'CAD', + }); + const edgx = adaptQmSymbolDoc( + { qmSearchCode: 'AACT.U:EGX', symbol: 'AACT.U', exchange: 'EDGX', countryCode: 'US' }, + ctx + ); + expect(edgx.ok && edgx.tickerSource).toMatchObject({ + mic: null, + role: 'ats_routing', + currency: 'USD', + }); + }); + + test('eodSymbolChange: Date effective, Country alias, validFrom ordering and NMFQS exclusion', () => { + const ctx = { exchangeLookup: lookup, allowedCountries: usCa }; + const ok = adaptEodSymbolChangeDoc( + { + oldSymbol: 'FB', + newSymbol: 'META', + exchange: 'US', + Country: 'USA', + effective: new Date('2022-06-09T00:00:00Z'), + validFrom: '2012-05-18', + }, + ctx + ); + expect(ok).toEqual({ + ok: true, + symbolChange: { + eodSourceId: 'META.US', + oldTicker: 'FB', + effectiveDate: '2022-06-09', + validFrom: '2012-05-18', + }, + }); + + const caChange = adaptEodSymbolChangeDoc( + { oldSymbol: 'OLD', newSymbol: 'NEW', exchange: 'TO', date: '2021-01-04' }, + ctx + ); + expect(caChange.ok && caChange.symbolChange.eodSourceId).toBe('NEW.TO'); + + expect( + adaptEodSymbolChangeDoc( + { + oldSymbol: 'FB', + newSymbol: 'META', + exchange: 'US', + effective: '2022-06-09', + validFrom: '2022-06-09', + }, + ctx + ) + ).toEqual({ ok: false, skipReason: 'invalidIdentifier' }); + expect( + adaptEodSymbolChangeDoc( + { oldSymbol: 'A', newSymbol: 'B', exchange: 'US', effective: 'not-a-date' }, + ctx + ) + ).toEqual({ + ok: false, + skipReason: 'invalidIdentifier', + }); + expect( + adaptEodSymbolChangeDoc( + { oldSymbol: 'A', newSymbol: 'B', exchange: 'NMFQS', Country: 'US', date: '2020-01-02' }, + ctx + ) + ).toEqual({ + ok: false, + skipReason: 'excludedMutualFund', + }); + expect( + adaptEodSymbolChangeDoc( + { oldSymbol: 'A', newSymbol: 'B', exchange: 'US', effective: 20220609 }, + ctx + ) + ).toEqual({ + ok: false, + skipReason: 'invalidFieldType', + }); + }); + + test('non-object cursor documents are counted as invalidFieldType, not thrown', async () => { + const reader = arrayReader({ + [SOURCE_SYMBOL_COLLECTIONS.ib]: [ + null as unknown as Record, + ['x'] as unknown as Record, + { conid: 7, country: 'US', currency: 'USD' }, + ], + }); + const res = await readIbSymbols(reader, { exchangeLookup: lookup }); + expect(res.stats.docsRead).toBe(3); + expect(res.stats.emitted).toBe(1); + expect(res.stats.skips.invalidFieldType).toBe(2); + assertConservation(res.stats); + }); + + test('readers reject buffered (array / sync iterable) find results with the collection name', async () => { + const buffered: ReadOnlySourceSymbolReader = { + isReadOnly: () => true, + find: (() => + Promise.resolve([ + { eodSearchCode: 'A.US' }, + ])) as unknown as ReadOnlySourceSymbolReader['find'], + }; + await expect(readEodSymbols(buffered, { exchangeLookup: lookup })).rejects.toThrow( + 'eodSymbols' + ); + }); + + test('aggregate entry point refuses a writable reader before issuing any find', async () => { + const reader = arrayReader({}); + const writable = { ...reader, isReadOnly: () => false }; + await expect(readSecurityMasterSources(writable, { exchangeLookup: lookup })).rejects.toThrow( + 'read-only' + ); + expect(reader.calls).toHaveLength(0); + }); + + test('Mongo cursor adapter closes the cursor on mid-stream error and when the client turns writable', async () => { + let closed = 0; + let readOnly = true; + const findCalls: Array<{ name: string; options: SourceSymbolFindOptions | undefined }> = []; + const client: ReadOnlyMongoCollectionClient = { + isReadOnly: () => readOnly, + getCollection: name => ({ + find: (_filter, options) => { + findCalls.push({ name, options }); + return { + async *[Symbol.asyncIterator]() { + yield { eodSearchCode: 'AAPL.US', Code: 'AAPL', Exchange: 'NASDAQ', Country: 'USA' }; + throw new Error('cursor killed'); + }, + close: async () => { + closed += 1; + }, + }; + }, + }), + }; + const reader = createReadOnlyMongoSourceSymbolReader(client); + await expect( + readEodSymbols(reader, { exchangeLookup: lookup, batchSize: 500 }) + ).rejects.toThrow(/eodSymbols.*cursor killed|cursor killed.*eodSymbols/); + expect(closed).toBe(1); + expect(findCalls[0]?.options?.batchSize).toBe(500); + expect(findCalls[0]?.options?.projection?._id).toBe(0); + + readOnly = false; + await expect(readEodSymbols(reader, { exchangeLookup: lookup })).rejects.toThrow('read-only'); + expect(findCalls).toHaveLength(1); + expect(() => createReadOnlyMongoSourceSymbolReader(client)).toThrow('read-only'); + }); +});