T-108: tests
This commit is contained in:
parent
f471c644f5
commit
7ea03c95ac
1 changed files with 364 additions and 0 deletions
364
apps/stock/data-pipeline/test/source-field-shapes-qa.test.ts
Normal file
364
apps/stock/data-pipeline/test/source-field-shapes-qa.test.ts
Normal file
|
|
@ -0,0 +1,364 @@
|
|||
import { describe, expect, test } from 'bun:test';
|
||||
import { BSON } from 'mongodb';
|
||||
import {
|
||||
createReadOnlyMongoSourceSymbolReader,
|
||||
MAX_EXAMPLES_CAP,
|
||||
parseProbeSourceFieldShapesArgs,
|
||||
readFieldShapes,
|
||||
renderFieldShapesMarkdown,
|
||||
runSourceFieldShapesProbe,
|
||||
summarizeFieldShapes,
|
||||
type ReadOnlyMongoCollectionClient,
|
||||
type ReadOnlySourceSymbolCursor,
|
||||
type ReadOnlySourceSymbolReader,
|
||||
type SourceSymbolFindOptions,
|
||||
} from '../src/security-master';
|
||||
|
||||
// QA coverage for T-108 beyond the programmer's suite: real BSON wire decoding,
|
||||
// option pass-through via the production read-only adapter, fail-fast safety,
|
||||
// and CLI/runner failure paths. No MongoDB connection is opened anywhere here.
|
||||
|
||||
const OBJECT_ID_HEX = '507f1f77bcf86cd799439011';
|
||||
|
||||
function serializeRealBsonDoc(): Uint8Array {
|
||||
return BSON.serialize({
|
||||
_id: new BSON.ObjectId(OBJECT_ID_HEX),
|
||||
i32: new BSON.Int32(7),
|
||||
dbl: new BSON.Double(1.0),
|
||||
lng: BSON.Long.fromString('9007199254740993'),
|
||||
dec: BSON.Decimal128.fromString('12.34'),
|
||||
flag: true,
|
||||
text: '2025-01-02',
|
||||
when: new Date('2025-01-02T00:00:00.000Z'),
|
||||
nothing: null,
|
||||
list: [1, 2],
|
||||
nested: { px: new BSON.Double(2.5), qty: new BSON.Int32(3) },
|
||||
bin: new BSON.Binary(new Uint8Array([1, 2, 3])),
|
||||
ts: new BSON.Timestamp({ t: 1, i: 1 }),
|
||||
min: new BSON.MinKey(),
|
||||
});
|
||||
}
|
||||
|
||||
function nonZeroTypes(counts: Record<string, number>): Record<string, number> {
|
||||
return Object.fromEntries(Object.entries(counts).filter(([, count]) => count > 0));
|
||||
}
|
||||
|
||||
function asyncCursor<T>(
|
||||
docs: readonly T[],
|
||||
onClose?: () => void
|
||||
): { [Symbol.asyncIterator](): AsyncIterator<T>; close(): Promise<void> } {
|
||||
return {
|
||||
async *[Symbol.asyncIterator]() {
|
||||
for (const doc of docs) {
|
||||
yield doc;
|
||||
}
|
||||
},
|
||||
async close() {
|
||||
onClose?.();
|
||||
},
|
||||
};
|
||||
}
|
||||
|
||||
describe('summarizeFieldShapes with real BSON wire documents', () => {
|
||||
test('promoteValues:false decoding keeps int/double/long/objectId distinct and maps other BSON types to other', () => {
|
||||
const doc = BSON.deserialize(serializeRealBsonDoc(), {
|
||||
promoteValues: false,
|
||||
promoteLongs: false,
|
||||
});
|
||||
|
||||
const summary = summarizeFieldShapes([doc]);
|
||||
const types = Object.fromEntries(summary.fields.map(f => [f.field, nonZeroTypes(f.typeCounts)]));
|
||||
|
||||
expect(types).toEqual({
|
||||
_id: { objectId: 1 },
|
||||
bin: { other: 1 },
|
||||
dbl: { double: 1 },
|
||||
dec: { other: 1 },
|
||||
flag: { bool: 1 },
|
||||
i32: { int: 1 },
|
||||
list: { array: 1 },
|
||||
lng: { int: 1 },
|
||||
min: { other: 1 },
|
||||
nested: { object: 1 },
|
||||
'nested.px': { double: 1 },
|
||||
'nested.qty': { int: 1 },
|
||||
nothing: { null: 1 },
|
||||
text: { string: 1 },
|
||||
ts: { other: 1 },
|
||||
when: { date: 1 },
|
||||
});
|
||||
|
||||
const examples = Object.fromEntries(summary.fields.map(f => [f.field, f.examples]));
|
||||
expect(examples._id).toEqual([]);
|
||||
expect(examples.dbl).toEqual(['1']);
|
||||
expect(examples.lng).toEqual(['9007199254740993']);
|
||||
expect(examples.dec).toEqual(['12.34']);
|
||||
expect(examples.when).toEqual(['2025-01-02T00:00:00.000Z']);
|
||||
expect(examples.bin).toEqual([]);
|
||||
});
|
||||
|
||||
test('default driver promotion collapses Double(1.0) into int, which is why the probe disables promotion', () => {
|
||||
const promoted = BSON.deserialize(serializeRealBsonDoc());
|
||||
const summary = summarizeFieldShapes([promoted]);
|
||||
const dbl = summary.fields.find(f => f.field === 'dbl')!;
|
||||
expect(nonZeroTypes(dbl.typeCounts)).toEqual({ int: 1 });
|
||||
});
|
||||
});
|
||||
|
||||
describe('readFieldShapes through the production read-only Mongo adapter', () => {
|
||||
test('forwards limit/promoteValues/promoteLongs verbatim to collection.find and classifies decoded BSON', async () => {
|
||||
const findCalls: Array<{ name: string; filter: unknown; options: unknown }> = [];
|
||||
const closed: string[] = [];
|
||||
const wireDoc = BSON.deserialize(serializeRealBsonDoc(), {
|
||||
promoteValues: false,
|
||||
promoteLongs: false,
|
||||
});
|
||||
|
||||
const client: ReadOnlyMongoCollectionClient = {
|
||||
isReadOnly: () => true,
|
||||
getCollection(name: string) {
|
||||
return {
|
||||
find(filter?: Record<string, unknown>, options?: SourceSymbolFindOptions) {
|
||||
findCalls.push({ name, filter, options });
|
||||
return asyncCursor(name === 'qmDividends' ? [wireDoc] : [], () => closed.push(name));
|
||||
},
|
||||
};
|
||||
},
|
||||
};
|
||||
|
||||
const reader = createReadOnlyMongoSourceSymbolReader(client);
|
||||
const result = await readFieldShapes(reader, {
|
||||
collections: ['qmDividends', 'qmSplits'],
|
||||
limit: 25,
|
||||
});
|
||||
|
||||
expect(findCalls).toEqual([
|
||||
{
|
||||
name: 'qmDividends',
|
||||
filter: {},
|
||||
options: { limit: 25, promoteValues: false, promoteLongs: false },
|
||||
},
|
||||
{
|
||||
name: 'qmSplits',
|
||||
filter: {},
|
||||
options: { limit: 25, promoteValues: false, promoteLongs: false },
|
||||
},
|
||||
]);
|
||||
expect(closed).toEqual(['qmDividends', 'qmSplits']);
|
||||
expect(result.totalDocsSampled).toBe(1);
|
||||
const dbl = result.collections[0]!.fields.find(f => f.field === 'dbl')!;
|
||||
expect(dbl.typeCounts.double).toBe(1);
|
||||
});
|
||||
|
||||
test('re-checks read-only before every collection and stops if the reader stops being read-only', async () => {
|
||||
let readOnly = true;
|
||||
const findCalls: string[] = [];
|
||||
const reader: ReadOnlySourceSymbolReader = {
|
||||
isReadOnly: () => readOnly,
|
||||
find<T extends Record<string, unknown>>(name: string): ReadOnlySourceSymbolCursor<T> {
|
||||
findCalls.push(name);
|
||||
readOnly = false; // simulate a reader that flips after its first query
|
||||
return asyncCursor<T>([]) as unknown as ReadOnlySourceSymbolCursor<T>;
|
||||
},
|
||||
};
|
||||
|
||||
await expect(
|
||||
readFieldShapes(reader, { collections: ['ceoShorts', 'qmSplits'] })
|
||||
).rejects.toThrow(/read-only/i);
|
||||
expect(findCalls).toEqual(['ceoShorts']);
|
||||
});
|
||||
|
||||
test('fails fast: an error on one collection prevents queries on later collections', async () => {
|
||||
const findCalls: string[] = [];
|
||||
const reader: ReadOnlySourceSymbolReader = {
|
||||
isReadOnly: () => true,
|
||||
find<T extends Record<string, unknown>>(name: string): ReadOnlySourceSymbolCursor<T> {
|
||||
findCalls.push(name);
|
||||
if (name === 'eodPrices') {
|
||||
throw new Error('not authorized on stock');
|
||||
}
|
||||
return asyncCursor<T>([]) as unknown as ReadOnlySourceSymbolCursor<T>;
|
||||
},
|
||||
};
|
||||
|
||||
let caught: unknown;
|
||||
try {
|
||||
await readFieldShapes(reader, { collections: ['qmSplits', 'eodPrices', 'ceoShorts'] });
|
||||
} catch (error) {
|
||||
caught = error;
|
||||
}
|
||||
// Collections are ASCII-sorted: ceoShorts, eodPrices, qmSplits.
|
||||
expect(findCalls).toEqual(['ceoShorts', 'eodPrices']);
|
||||
expect((caught as Error).message).toContain('eodPrices');
|
||||
expect((caught as Error).message).toContain('not authorized on stock');
|
||||
expect(((caught as Error).cause as Error).message).toBe('not authorized on stock');
|
||||
});
|
||||
|
||||
test('rejects non-integer limit and invalid batchSize before any query', async () => {
|
||||
let findCalls = 0;
|
||||
const reader: ReadOnlySourceSymbolReader = {
|
||||
isReadOnly: () => true,
|
||||
find<T extends Record<string, unknown>>(): ReadOnlySourceSymbolCursor<T> {
|
||||
findCalls += 1;
|
||||
return asyncCursor<T>([]) as unknown as ReadOnlySourceSymbolCursor<T>;
|
||||
},
|
||||
};
|
||||
|
||||
await expect(readFieldShapes(reader, { limit: 1.5 })).rejects.toThrow(RangeError);
|
||||
await expect(readFieldShapes(reader, { limit: Number.NaN })).rejects.toThrow(RangeError);
|
||||
await expect(readFieldShapes(reader, { batchSize: 0 })).rejects.toThrow(RangeError);
|
||||
await expect(readFieldShapes(reader, { collections: [] })).rejects.toThrow(RangeError);
|
||||
expect(findCalls).toBe(0);
|
||||
});
|
||||
});
|
||||
|
||||
describe('summarizeFieldShapes edge cases', () => {
|
||||
test('non-object documents count toward docCount and keep presence invariants', () => {
|
||||
const docs = [{ a: 1 }, null, 'oops', { a: 'x' }] as unknown as Record<string, unknown>[];
|
||||
const summary = summarizeFieldShapes(docs);
|
||||
expect(summary.docCount).toBe(4);
|
||||
const a = summary.fields.find(f => f.field === 'a')!;
|
||||
expect(a.presentCount).toBe(2);
|
||||
expect(a.missingCount).toBe(2);
|
||||
});
|
||||
|
||||
test('undefined values are treated as missing, not as a present type', () => {
|
||||
const summary = summarizeFieldShapes([{ a: undefined }, { a: 1 }]);
|
||||
const a = summary.fields.find(f => f.field === 'a')!;
|
||||
expect(a.presentCount).toBe(1);
|
||||
expect(a.missingCount).toBe(1);
|
||||
});
|
||||
|
||||
test('rejects near-miss dates and times as ymd/isoDatetime', () => {
|
||||
const values = [
|
||||
'2024-13-01', // month 13
|
||||
'2024-04-31', // April has 30 days
|
||||
'2025-01-01T24:00:00Z', // hour 24
|
||||
'2025-01-01T10:60:00Z', // minute 60
|
||||
'2025-01-01 10:00:00', // space separator
|
||||
'20250101', // compact date is numeric, not ymd
|
||||
];
|
||||
const summary = summarizeFieldShapes(values.map(s => ({ s })));
|
||||
const s = summary.fields.find(f => f.field === 's')!;
|
||||
expect(s.stringStats!.patterns).toEqual({
|
||||
ymd: 0,
|
||||
isoDatetime: 0,
|
||||
numeric: 1,
|
||||
emptyOrWhitespace: 0,
|
||||
other: 5,
|
||||
});
|
||||
});
|
||||
|
||||
test('examples are distinct, strip control characters, and honour maxExamples 0 and the cap', () => {
|
||||
const docs = [{ s: 'dup' }, { s: 'dup' }, { s: '\u0000\u001bbell\u0007' }];
|
||||
|
||||
expect(summarizeFieldShapes(docs).fields[0]!.examples).toEqual(['bell', 'dup']);
|
||||
expect(summarizeFieldShapes(docs, { maxExamples: 0 }).fields[0]!.examples).toEqual([]);
|
||||
|
||||
const many = Array.from({ length: 50 }, (_, i) => ({ s: `v${String(i).padStart(2, '0')}` }));
|
||||
const capped = summarizeFieldShapes(many, { maxExamples: MAX_EXAMPLES_CAP }).fields[0]!;
|
||||
expect(capped.examples.length).toBe(MAX_EXAMPLES_CAP);
|
||||
expect(capped.examples[0]).toBe('v00');
|
||||
});
|
||||
});
|
||||
|
||||
describe('renderFieldShapesMarkdown privacy and header', () => {
|
||||
test('never renders _id values and states the bounded sample in the header', async () => {
|
||||
const reader: ReadOnlySourceSymbolReader = {
|
||||
isReadOnly: () => true,
|
||||
find<T extends Record<string, unknown>>(): ReadOnlySourceSymbolCursor<T> {
|
||||
return asyncCursor<T>([
|
||||
{ _id: new BSON.ObjectId(OBJECT_ID_HEX), symbol: 'ABC' },
|
||||
{ _id: { ticker: 'SECRET-COMPOSITE' }, symbol: 'DEF' },
|
||||
] as unknown as T[]) as unknown as ReadOnlySourceSymbolCursor<T>;
|
||||
},
|
||||
};
|
||||
|
||||
const result = await readFieldShapes(reader, { collections: ['ceoShorts'], limit: 7 });
|
||||
const markdown = renderFieldShapesMarkdown(result);
|
||||
|
||||
expect(markdown).not.toContain(OBJECT_ID_HEX);
|
||||
expect(markdown).not.toContain('SECRET-COMPOSITE');
|
||||
expect(markdown).toContain('bounded sample, not a full scan');
|
||||
expect(markdown).toContain('**Sample limit per collection:** 7');
|
||||
expect(markdown).toContain('**Total documents sampled:** 2');
|
||||
expect(markdown).toContain('| `_id.ticker` | 50.0% (1/2) |');
|
||||
expect(markdown).not.toMatch(/\d{4}-\d{2}-\d{2}T\d{2}:\d{2}/); // no wall-clock stamp
|
||||
});
|
||||
});
|
||||
|
||||
describe('probe CLI parsing and runner failure paths', () => {
|
||||
test('rejects a flag in place of a value and empty inline values', () => {
|
||||
expect(() => parseProbeSourceFieldShapesArgs(['--out', '--limit', '5'])).toThrow(/--out/);
|
||||
expect(() => parseProbeSourceFieldShapesArgs(['--out=x.md', '--limit'])).toThrow(/--limit/);
|
||||
expect(() => parseProbeSourceFieldShapesArgs(['--out=x.md', '--collections='])).toThrow(
|
||||
/--collections/
|
||||
);
|
||||
expect(() => parseProbeSourceFieldShapesArgs(['--out=x.md', '--collections', ' , '])).toThrow(
|
||||
/--collections/
|
||||
);
|
||||
expect(() => parseProbeSourceFieldShapesArgs(['--out=x.md', '--limit=1e3'])).toThrow(/--limit/);
|
||||
});
|
||||
|
||||
test('merges repeated --collections, accepts boundary limits, and lets --help win', () => {
|
||||
expect(
|
||||
parseProbeSourceFieldShapesArgs([
|
||||
'--out=x.md',
|
||||
'--collections=qmSplits',
|
||||
'--collections',
|
||||
'ceoShorts,qmSplits',
|
||||
'--limit=10000',
|
||||
])
|
||||
).toEqual({ help: false, outPath: 'x.md', limit: 10_000, collections: ['ceoShorts', 'qmSplits'] });
|
||||
expect(parseProbeSourceFieldShapesArgs(['--out=x.md', '--limit=1'])).toMatchObject({ limit: 1 });
|
||||
expect(parseProbeSourceFieldShapesArgs(['--out=x.md', '--help'])).toEqual({ help: true });
|
||||
});
|
||||
|
||||
test('closes Mongo and surfaces the write error when the report cannot be written', async () => {
|
||||
let closeCalls = 0;
|
||||
const stdout: string[] = [];
|
||||
const client: ReadOnlyMongoCollectionClient = {
|
||||
isReadOnly: () => true,
|
||||
getCollection() {
|
||||
return { find: () => asyncCursor([{ a: 1 }]) };
|
||||
},
|
||||
};
|
||||
|
||||
await expect(
|
||||
runSourceFieldShapesProbe(
|
||||
{
|
||||
mongoCollectionClient: client,
|
||||
closeMongo: () => {
|
||||
closeCalls += 1;
|
||||
},
|
||||
writeFile: () => {
|
||||
throw new Error('EACCES: permission denied');
|
||||
},
|
||||
writeStdout: text => stdout.push(text),
|
||||
},
|
||||
{ outPath: './tmp/out.md', collections: ['qmSplits'] }
|
||||
)
|
||||
).rejects.toThrow('EACCES');
|
||||
expect(closeCalls).toBe(1);
|
||||
expect(stdout).toEqual([]);
|
||||
});
|
||||
|
||||
test('blank outPath is rejected before any collection is opened', async () => {
|
||||
let getCollectionCalls = 0;
|
||||
const client: ReadOnlyMongoCollectionClient = {
|
||||
isReadOnly: () => true,
|
||||
getCollection() {
|
||||
getCollectionCalls += 1;
|
||||
return { find: () => asyncCursor([]) };
|
||||
},
|
||||
};
|
||||
|
||||
await expect(
|
||||
runSourceFieldShapesProbe(
|
||||
{ mongoCollectionClient: client, writeFile: () => {}, writeStdout: () => {} },
|
||||
{ outPath: ' ' }
|
||||
)
|
||||
).rejects.toThrow(/outPath/);
|
||||
expect(getCollectionCalls).toBe(0);
|
||||
});
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue