T-74: tests
This commit is contained in:
parent
06f14c8730
commit
acbcb0ab7a
2 changed files with 331 additions and 0 deletions
|
|
@ -419,4 +419,68 @@ describe.skipIf(!url)('security master override seed SQL', () => {
|
|||
).rows[0]?.count;
|
||||
expect(count).toBe(0);
|
||||
});
|
||||
|
||||
test('multi-statement seed file round-trips special characters, class suffix keys, and distinct valid_from rows', async () => {
|
||||
const f = await createIsolatedFixture();
|
||||
const aaplListingId = await seedSingleListing(f.pool);
|
||||
const brk = await f.pool.query<{ instrument_id: number }>(
|
||||
`INSERT INTO instrument (primary_isin, canonical_name, security_type, issuer_country)
|
||||
VALUES ('US0846707026', 'Berkshire Hathaway', 'common', 'US') RETURNING instrument_id`
|
||||
);
|
||||
const brkA = await f.pool.query<{ listing_id: number }>(
|
||||
`INSERT INTO listing (instrument_id, mic, ticker_root, class_suffix, currency)
|
||||
VALUES ($1, 'XNYS', 'BRK', 'A', 'USD') RETURNING listing_id`,
|
||||
[brk.rows[0]?.instrument_id]
|
||||
);
|
||||
const brkB = await f.pool.query<{ listing_id: number }>(
|
||||
`INSERT INTO listing (instrument_id, mic, ticker_root, class_suffix, currency)
|
||||
VALUES ($1, 'XNYS', 'BRK', 'B', 'USD') RETURNING listing_id`,
|
||||
[brk.rows[0]?.instrument_id]
|
||||
);
|
||||
const trickyReason = "line1\nO'Brien \\ back\r\nslash -- not a comment; DROP TABLE override;";
|
||||
|
||||
const sql = generateOverrideSeedSql([
|
||||
{ source: 'eod', sourceId: 'BRK-B.US', validFrom: '2021-01-01', validTo: null, primaryIsin: 'US0846707026', mic: 'XNYS', tickerRoot: 'BRK', classSuffix: 'B', currency: 'USD', reason: trickyReason, createdBy: 'director' },
|
||||
{ source: 'eod', sourceId: 'BRK-B.US', validFrom: '2020-01-01', validTo: '2020-12-31', primaryIsin: 'US0846707026', mic: 'XNYS', tickerRoot: 'BRK', classSuffix: 'A', currency: 'USD', reason: 'pre-split mapping', createdBy: 'director' },
|
||||
{ source: 'qm', sourceId: "AAPL'Q", primaryIsin: 'US0378331005', mic: 'XNAS', tickerRoot: 'AAPL', classSuffix: '', currency: 'USD', reason: 'default dates', createdBy: 'qa' },
|
||||
]);
|
||||
await f.pool.query(sql);
|
||||
|
||||
const rows = (
|
||||
await f.pool.query<{ source: string; source_id: string; valid_from: string; valid_to: string | null; listing_id: number; reason: string }>(
|
||||
`SELECT source, source_id, to_char(valid_from, 'YYYY-MM-DD') AS valid_from,
|
||||
to_char(valid_to, 'YYYY-MM-DD') AS valid_to, listing_id, reason
|
||||
FROM override ORDER BY source, source_id, valid_from`
|
||||
)
|
||||
).rows;
|
||||
expect(rows).toEqual([
|
||||
{ source: 'eod', source_id: 'BRK-B.US', valid_from: '2020-01-01', valid_to: '2020-12-31', listing_id: brkA.rows[0]?.listing_id ?? -1, reason: 'pre-split mapping' },
|
||||
{ source: 'eod', source_id: 'BRK-B.US', valid_from: '2021-01-01', valid_to: null, listing_id: brkB.rows[0]?.listing_id ?? -1, reason: trickyReason },
|
||||
{ source: 'qm', source_id: "AAPL'Q", valid_from: '1900-01-01', valid_to: null, listing_id: aaplListingId, reason: 'default dates' },
|
||||
]);
|
||||
});
|
||||
|
||||
test('re-seeding an existing override key keeps the originally stored listing_id (DO NOTHING, no overwrite)', async () => {
|
||||
const f = await createIsolatedFixture();
|
||||
const aaplListingId = await seedSingleListing(f.pool);
|
||||
await f.pool.query(
|
||||
`INSERT INTO override (source, source_id, valid_from, listing_id, reason, created_by)
|
||||
VALUES ('eod', 'AAPL.US', DATE '1900-01-01', $1, 'original', 'director')`,
|
||||
[aaplListingId]
|
||||
);
|
||||
const instrumentId = (await f.pool.query<{ instrument_id: number }>(`SELECT instrument_id FROM instrument`)).rows[0]?.instrument_id;
|
||||
await f.pool.query(
|
||||
`INSERT INTO listing (instrument_id, mic, ticker_root, class_suffix, currency) VALUES ($1, 'XNYS', 'AAPL', '', 'USD')`,
|
||||
[instrumentId]
|
||||
);
|
||||
|
||||
await f.pool.query(
|
||||
generateOverrideSeedSql([
|
||||
{ source: 'eod', sourceId: 'AAPL.US', primaryIsin: 'US0378331005', mic: 'XNYS', tickerRoot: 'AAPL', classSuffix: '', currency: 'USD', reason: 'replacement', createdBy: 'qa' },
|
||||
])
|
||||
);
|
||||
|
||||
const rows = (await f.pool.query<{ listing_id: number; reason: string }>('SELECT listing_id, reason FROM override')).rows;
|
||||
expect(rows).toEqual([{ listing_id: aaplListingId, reason: 'original' }]);
|
||||
});
|
||||
});
|
||||
|
|
|
|||
267
test/unit/security-master-match-report-edge.test.ts
Normal file
267
test/unit/security-master-match-report-edge.test.ts
Normal file
|
|
@ -0,0 +1,267 @@
|
|||
import { describe, expect, test } from 'bun:test';
|
||||
import {
|
||||
buildMatchReport,
|
||||
generateOverrideSeedSql,
|
||||
generateOverrideTemplateSql,
|
||||
renderConflictsCsv,
|
||||
renderMatchReportMarkdown,
|
||||
sourceCountryKey,
|
||||
type MatchReport,
|
||||
type OverrideSeedRow,
|
||||
type StageAMatchResult,
|
||||
type StageBMatchResult,
|
||||
type UnifiedConflictRow,
|
||||
} from '../../apps/stock/data-pipeline/src/security-master';
|
||||
|
||||
function makeEmptyStageA(): StageAMatchResult {
|
||||
return {
|
||||
instruments: [],
|
||||
unresolved: [],
|
||||
conflicts: [],
|
||||
stats: {
|
||||
totalInputRecords: 0,
|
||||
totalInstruments: 0,
|
||||
bySource: {
|
||||
ib: { total: 0, tier1Isin: 0, tier2Cusip: 0, unresolved: 0, conflict: 0 },
|
||||
eod: { total: 0, tier1Isin: 0, tier2Cusip: 0, unresolved: 0, conflict: 0 },
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function makeEmptyStageB(): StageBMatchResult {
|
||||
return {
|
||||
listings: [],
|
||||
providerMappings: [],
|
||||
unresolved: [],
|
||||
conflicts: [],
|
||||
stats: {
|
||||
totalListings: 0,
|
||||
totalProviderMappings: 0,
|
||||
listingsWithIbConid: 0,
|
||||
excludedFunds: 0,
|
||||
bySource: {
|
||||
eod: { total: 0, matched: 0, unresolved: 0, conflict: 0 },
|
||||
ib: { total: 0, matched: 0, unresolved: 0, conflict: 0 },
|
||||
qm: { total: 0, matched: 0, unresolved: 0, conflict: 0 },
|
||||
ceo: { total: 0, matched: 0, unresolved: 0, conflict: 0 },
|
||||
},
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
function reportWithConflicts(conflicts: UnifiedConflictRow[]): MatchReport {
|
||||
return {
|
||||
...buildMatchReport({ stageA: makeEmptyStageA(), stageB: makeEmptyStageB() }),
|
||||
conflicts,
|
||||
};
|
||||
}
|
||||
|
||||
const validRow: OverrideSeedRow = {
|
||||
source: 'eod',
|
||||
sourceId: 'BRK-B.US',
|
||||
validFrom: '2020-01-15',
|
||||
validTo: null,
|
||||
primaryIsin: 'US0846707026',
|
||||
mic: 'XNYS',
|
||||
tickerRoot: 'BRK',
|
||||
classSuffix: 'B',
|
||||
currency: 'USD',
|
||||
reason: 'class share mapping',
|
||||
createdBy: 'director',
|
||||
};
|
||||
|
||||
describe('buildMatchReport edge cases', () => {
|
||||
test('empty exchange classification yields null mappedPct and fails exchangesMapped100', () => {
|
||||
const report = buildMatchReport({
|
||||
exchanges: { mapped: [], unresolved: [] },
|
||||
stageA: makeEmptyStageA(),
|
||||
stageB: makeEmptyStageB(),
|
||||
});
|
||||
|
||||
expect(report.exchangeCoverage).toEqual({ mapped: 0, unresolved: 0, total: 0, mappedPct: null });
|
||||
expect(report.meetsExitThresholds.exchangesMapped100).toBe(false);
|
||||
});
|
||||
|
||||
test('one failing eligible source fails equitiesResolved95 even when others pass', () => {
|
||||
const stageB = makeEmptyStageB();
|
||||
stageB.stats.bySource.eod = { total: 100, matched: 100, unresolved: 0, conflict: 0 };
|
||||
stageB.stats.bySource.qm = { total: 100, matched: 94, unresolved: 6, conflict: 0 };
|
||||
|
||||
const report = buildMatchReport({ stageA: makeEmptyStageA(), stageB });
|
||||
|
||||
expect(report.meetsExitThresholds.equitiesResolved95).toBe(false);
|
||||
expect(buildMatchReport({ stageA: makeEmptyStageA(), stageB }, { minResolvedPct: 0.94 }).meetsExitThresholds.equitiesResolved95).toBe(true);
|
||||
});
|
||||
|
||||
test('minResolvedPct boundaries 0 and 1 are accepted; 1 requires every eligible record matched', () => {
|
||||
const stageB = makeEmptyStageB();
|
||||
stageB.stats.bySource.eod = { total: 10, matched: 10, unresolved: 0, conflict: 0 };
|
||||
stageB.stats.bySource.ib = { total: 10, matched: 0, unresolved: 10, conflict: 0 };
|
||||
|
||||
expect(buildMatchReport({ stageA: makeEmptyStageA(), stageB }, { minResolvedPct: 0 }).meetsExitThresholds.equitiesResolved95).toBe(true);
|
||||
expect(buildMatchReport({ stageA: makeEmptyStageA(), stageB }, { minResolvedPct: 1 }).meetsExitThresholds.equitiesResolved95).toBe(false);
|
||||
expect(() => buildMatchReport({ stageA: makeEmptyStageA(), stageB }, { minResolvedPct: Number.POSITIVE_INFINITY })).toThrow(/minResolvedPct/);
|
||||
});
|
||||
|
||||
test('non-excluded unresolved reasons stay in the eligible denominator', () => {
|
||||
const stageB = makeEmptyStageB();
|
||||
stageB.stats.bySource.ceo = { total: 4, matched: 2, unresolved: 2, conflict: 0 };
|
||||
stageB.unresolved = [
|
||||
{ source: 'ceo', sourceId: 'C1', reason: 'missing_mic', primaryIsin: null },
|
||||
{ source: 'ceo', sourceId: 'C2', reason: 'forex_venue', primaryIsin: null },
|
||||
];
|
||||
|
||||
const ceo = buildMatchReport({ stageA: makeEmptyStageA(), stageB }).resolutionBySource.find(r => r.source === 'ceo');
|
||||
|
||||
expect(ceo?.excludedByDesign).toBe(1);
|
||||
expect(ceo?.eligibleTotal).toBe(3);
|
||||
expect(ceo?.eligibleResolvedPct).toBeCloseTo(2 / 3, 12);
|
||||
});
|
||||
|
||||
test('sourceCountries accepts a plain record, NUL-separated fallback keys, and normalizes case', () => {
|
||||
const stageB = makeEmptyStageB();
|
||||
stageB.unresolved = [
|
||||
{ source: 'eod', sourceId: 'X.TO', reason: 'missing_mic', primaryIsin: null },
|
||||
{ source: 'qm', sourceId: 'Y:US', reason: 'excluded_fund', primaryIsin: null },
|
||||
{ source: 'ib', sourceId: 'UNKNOWN', reason: 'missing_mic', primaryIsin: null },
|
||||
];
|
||||
|
||||
const report = buildMatchReport({
|
||||
stageA: makeEmptyStageA(),
|
||||
stageB,
|
||||
sourceCountries: {
|
||||
[sourceCountryKey('eod', 'X.TO')]: ' ca ',
|
||||
'qm\u0000Y:US': 'us',
|
||||
},
|
||||
});
|
||||
|
||||
expect(report.resolutionByCountry).toEqual([
|
||||
{ country: 'CA', total: 1, matched: 0, unresolved: 1, conflict: 0, excludedByDesign: 0, eligibleTotal: 1, resolvedPct: 0, eligibleResolvedPct: 0 },
|
||||
{ country: 'US', total: 1, matched: 0, unresolved: 1, conflict: 0, excludedByDesign: 1, eligibleTotal: 0, resolvedPct: 0, eligibleResolvedPct: null },
|
||||
]);
|
||||
});
|
||||
|
||||
test('does not mutate input pass results and copies stats objects', () => {
|
||||
const stageA = makeEmptyStageA();
|
||||
stageA.conflicts = [
|
||||
{ source: 'eod', sourceId: 'Z', conflictKind: 'duplicate_source_id', detail: { isin: 'B', cusip: null, country: 'US', derivedIsin: null } },
|
||||
{ source: 'eod', sourceId: 'A', conflictKind: 'duplicate_source_id', detail: { isin: 'A', cusip: null, country: 'US', derivedIsin: null } },
|
||||
];
|
||||
const before = JSON.stringify(stageA);
|
||||
|
||||
const report = buildMatchReport({ stageA, stageB: makeEmptyStageB() });
|
||||
|
||||
expect(JSON.stringify(stageA)).toBe(before);
|
||||
expect(report.conflicts.map(c => c.sourceId)).toEqual(['A', 'Z']);
|
||||
});
|
||||
});
|
||||
|
||||
describe('render edge cases', () => {
|
||||
test('canonical detail JSON sorts nested keys, drops undefined, normalizes -0 identically in CSV and Markdown', () => {
|
||||
const a = reportWithConflicts([
|
||||
{ pass: 'stage_b', source: 'ib', sourceId: '1', conflictKind: 'k', detail: { z: { b: 1, a: [{ y: 2, x: -0 }] }, a: undefined } },
|
||||
]);
|
||||
const b = reportWithConflicts([
|
||||
{ pass: 'stage_b', source: 'ib', sourceId: '1', conflictKind: 'k', detail: { z: { a: [{ x: 0, y: 2 }], b: 1 } } },
|
||||
]);
|
||||
|
||||
const csv = renderConflictsCsv(a);
|
||||
|
||||
expect(csv).toBe(renderConflictsCsv(b));
|
||||
expect(csv).toContain('"{""z"":{""a"":[{""x"":0,""y"":2}],""b"":1}}"');
|
||||
expect(renderMatchReportMarkdown(a)).toBe(renderMatchReportMarkdown(b));
|
||||
});
|
||||
|
||||
test('CSV uses CRLF terminators and an empty report is header-only', () => {
|
||||
expect(renderConflictsCsv(reportWithConflicts([]))).toBe('pass,source,source_id,conflict_kind,detail_json\r\n');
|
||||
});
|
||||
|
||||
test('Markdown sample exactly at maxConflictRows reports no remaining CSV rows', () => {
|
||||
const rows: UnifiedConflictRow[] = [1, 2, 3].map(i => ({ pass: 'pass4', source: 'qm', sourceId: `S${i}`, conflictKind: 'k', detail: {} }));
|
||||
|
||||
const md = renderMatchReportMarkdown(reportWithConflicts(rows), { maxConflictRows: 3 });
|
||||
|
||||
expect(md).toContain('Showing 3 of 3 conflicts.');
|
||||
expect(md).not.toContain('more in CSV');
|
||||
});
|
||||
|
||||
test('Markdown escapes lone CR in reason column of unresolved breakdown', () => {
|
||||
const report = buildMatchReport({ stageA: makeEmptyStageA(), stageB: makeEmptyStageB() });
|
||||
report.unresolvedByReason.stageB = [{ source: 'a|b', reason: 'x\ry', count: 2 }];
|
||||
|
||||
const md = renderMatchReportMarkdown(report);
|
||||
|
||||
expect(md).toContain('| a\\|b | x y | 2 |');
|
||||
});
|
||||
});
|
||||
|
||||
describe('override SQL edge cases', () => {
|
||||
test('accepts leap day 2000-02-29 and validTo == validFrom; rejects 1900-02-29 and month 13', () => {
|
||||
const sql = generateOverrideSeedSql([{ ...validRow, validFrom: '2000-02-29', validTo: '2000-02-29' }]);
|
||||
|
||||
expect(sql).toContain("DATE '2000-02-29',\n DATE '2000-02-29',");
|
||||
expect(() => generateOverrideSeedSql([{ ...validRow, validFrom: '1900-02-29' }])).toThrow(/validFrom/);
|
||||
expect(() => generateOverrideSeedSql([{ ...validRow, validFrom: '2024-13-01' }])).toThrow(/validFrom/);
|
||||
expect(() => generateOverrideSeedSql([{ ...validRow, validTo: '2024-01-01T00:00:00Z' }])).toThrow(/validTo/);
|
||||
});
|
||||
|
||||
test('exact boundary lengths (16-char source, 64-char sourceId) are accepted', () => {
|
||||
const sql = generateOverrideSeedSql([{ ...validRow, source: 's'.repeat(16), sourceId: 'i'.repeat(64) }]);
|
||||
|
||||
expect(sql).toContain(`'${'s'.repeat(16)}'`);
|
||||
expect(sql).toContain(`'${'i'.repeat(64)}'`);
|
||||
});
|
||||
|
||||
test('undefined validFrom and explicit default are treated as the same key (exact dup dedup; conflicting dup throws)', () => {
|
||||
const explicit = { ...validRow, validFrom: '1900-01-01', validTo: undefined };
|
||||
const implicit = { ...validRow, validFrom: undefined, validTo: null };
|
||||
|
||||
expect(generateOverrideSeedSql([explicit, implicit]).match(/INSERT INTO override/g)?.length).toBe(1);
|
||||
expect(() => generateOverrideSeedSql([explicit, { ...implicit, mic: 'XNAS' }])).toThrow(/Conflicting duplicate/);
|
||||
});
|
||||
|
||||
test('same source/sourceId with different validFrom yields two statements sorted by validFrom', () => {
|
||||
const sql = generateOverrideSeedSql([{ ...validRow, validFrom: '2022-01-01' }, { ...validRow, validFrom: '2021-01-01' }]);
|
||||
|
||||
const first = sql.indexOf("DATE '2021-01-01'");
|
||||
const second = sql.indexOf("DATE '2022-01-01'");
|
||||
expect(first).toBeGreaterThan(-1);
|
||||
expect(second).toBeGreaterThan(first);
|
||||
});
|
||||
|
||||
test('NUL in natural-key and date fields is rejected', () => {
|
||||
expect(() => generateOverrideSeedSql([{ ...validRow, mic: 'XN\0S' }])).toThrow(/NUL/);
|
||||
expect(() => generateOverrideSeedSql([{ ...validRow, classSuffix: '\0' }])).toThrow(/NUL/);
|
||||
expect(() => generateOverrideSeedSql([{ ...validRow, createdBy: 'a\0' }])).toThrow(/NUL/);
|
||||
expect(() => generateOverrideSeedSql([{ ...validRow, validFrom: '2020-01-0\0' }])).toThrow(/NUL/);
|
||||
});
|
||||
|
||||
test('template warns and emits NULL marker for overlong source, and escapes newline in conflictKind', () => {
|
||||
const tpl = generateOverrideTemplateSql(
|
||||
reportWithConflicts([{ pass: 'stage_b', source: 'x'.repeat(17), sourceId: 'ok', conflictKind: "evil\nDROP TABLE override; '", detail: {} }])
|
||||
);
|
||||
|
||||
for (const line of tpl.split('\n')) {
|
||||
if (line.trim().length > 0) {
|
||||
expect(line.startsWith('--')).toBe(true);
|
||||
}
|
||||
}
|
||||
expect(tpl).toContain('-- WARNING: Cannot store raw source in PostgreSQL (length (17) exceeds 16-character limit)');
|
||||
expect(tpl).toContain('-- NULL /* TODO: replace with valid source */,');
|
||||
expect(tpl).toContain("-- 'ok',");
|
||||
expect(tpl).not.toContain('\nDROP');
|
||||
});
|
||||
|
||||
test('template has one candidate per source-attributed conflict including duplicates of the same sourceId', () => {
|
||||
const tpl = generateOverrideTemplateSql(
|
||||
reportWithConflicts([
|
||||
{ pass: 'stage_a', source: 'eod', sourceId: 'DUP', conflictKind: 'duplicate_source_id', detail: { n: 1 } },
|
||||
{ pass: 'stage_a', source: 'eod', sourceId: 'DUP', conflictKind: 'duplicate_source_id', detail: { n: 2 } },
|
||||
{ pass: 'pass6', source: null, sourceId: null, conflictKind: 'invalid_listing_dates', detail: {} },
|
||||
])
|
||||
);
|
||||
|
||||
expect(tpl.match(/-- INSERT INTO override/g)?.length).toBe(2);
|
||||
});
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue