423 lines
16 KiB
TypeScript
423 lines
16 KiB
TypeScript
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
|
|
import { GlobalWindow } from 'happy-dom';
|
|
import { act, createElement, type ReactElement } from 'react';
|
|
import type { Root } from 'react-dom/client';
|
|
import { createDatasetV2FromLegacy, validateDatasetV2 } from '@stock-bot/research/datasets';
|
|
import type { CanonicalDatasetCatalogEntry } from '@stock-bot/stock-config/canonical-research';
|
|
import type { Backtest } from '../../apps/stock/web-app/src/features/backtest/services/backtestApiV2';
|
|
import { datasetInput } from '../fixtures/historical-v2/dataset';
|
|
import { nativeReplayFixture } from '../fixtures/native-replay';
|
|
|
|
const browser = new GlobalWindow({ url: 'http://localhost:5173' });
|
|
const keys = ['window', 'document', 'Event', 'IS_REACT_ACT_ENVIRONMENT'] as const;
|
|
const originals = new Map(keys.map(key => [key, Object.getOwnPropertyDescriptor(globalThis, key)]));
|
|
const createUrlDescriptor = Object.getOwnPropertyDescriptor(URL, 'createObjectURL');
|
|
const revokeUrlDescriptor = Object.getOwnPropertyDescriptor(URL, 'revokeObjectURL');
|
|
const clickDescriptor = Object.getOwnPropertyDescriptor(
|
|
browser.HTMLAnchorElement.prototype,
|
|
'click'
|
|
);
|
|
let createRoot: typeof import('react-dom/client').createRoot;
|
|
let DatasetDownload: typeof import('../../apps/stock/web-app/src/features/backtest/components/DatasetDownload').DatasetDownload;
|
|
let CanonicalSetup: typeof import('../../apps/stock/web-app/src/features/backtest/components/CanonicalSetup').CanonicalSetup;
|
|
let backtestApiV2: typeof import('../../apps/stock/web-app/src/features/backtest/services/backtestApiV2').backtestApiV2;
|
|
let root: Root | undefined;
|
|
let host: HTMLDivElement;
|
|
const blobs: Blob[] = [];
|
|
const revoked: string[] = [];
|
|
const downloads: { href: string; filename: string; connected: boolean }[] = [];
|
|
let clickFailure = false;
|
|
|
|
function deferred<T>() {
|
|
let resolve!: (value: T) => void;
|
|
let reject!: (cause: Error) => void;
|
|
const promise = new Promise<T>((yes, no) => {
|
|
resolve = yes;
|
|
reject = no;
|
|
});
|
|
return { promise, resolve, reject };
|
|
}
|
|
type Pending = ReturnType<typeof deferred<Response>> & { path: string; init?: RequestInit };
|
|
const requests: Pending[] = [];
|
|
const dataset = nativeReplayFixture().dataset;
|
|
const hash = dataset.manifest.hash;
|
|
const other = nativeReplayFixture(4).dataset;
|
|
const exportPath = (identity: string) => `/api/v2/datasets/canonical/${identity}/export`;
|
|
const entry = (value = dataset): CanonicalDatasetCatalogEntry => ({
|
|
hash: value.manifest.hash,
|
|
createdAt: '2026-01-01T00:00:00Z',
|
|
available: true,
|
|
reason: null,
|
|
manifest: value.manifest,
|
|
});
|
|
const definition: Backtest = {
|
|
id: 'definition',
|
|
name: 'Dataset download fixture',
|
|
strategy: 'catalog',
|
|
strategyVersionId: null,
|
|
strategyParameters: {},
|
|
symbols: ['X0.US'],
|
|
startDate: new Date(dataset.manifest.bounds.tradeStart).toISOString(),
|
|
endDate: new Date(dataset.manifest.bounds.tradeEnd).toISOString(),
|
|
initialCapital: 10000,
|
|
config: { canonical: {}, datasetHash: hash },
|
|
archivedAt: null,
|
|
createdAt: '2026-01-01T00:00:00Z',
|
|
updatedAt: '2026-01-01T00:00:00Z',
|
|
};
|
|
async function flush(action: () => void = () => {}) {
|
|
await act(async () => {
|
|
action();
|
|
await Promise.resolve();
|
|
});
|
|
}
|
|
async function mount(element: ReactElement = createElement(DatasetDownload, { hash })) {
|
|
root = createRoot(host);
|
|
await flush(() => root!.render(element));
|
|
}
|
|
function button(name = 'Download retained dataset') {
|
|
const value = [...host.querySelectorAll('button')].find(el => el.textContent?.trim() === name);
|
|
if (!value) {
|
|
throw new Error(`Missing button ${name}: ${host.textContent}`);
|
|
}
|
|
return value;
|
|
}
|
|
function request(path = exportPath(hash)) {
|
|
const value = requests.find(item => item.path === path);
|
|
if (!value) {
|
|
throw new Error(`Missing request ${path}`);
|
|
}
|
|
return value;
|
|
}
|
|
function json(text = JSON.stringify(dataset), status = 200, type = 'application/json') {
|
|
return new Response(text, { status, headers: { 'Content-Type': type } });
|
|
}
|
|
const tick = () => new Promise(resolve => setTimeout(resolve, 0));
|
|
|
|
beforeAll(async () => {
|
|
for (const [key, value] of Object.entries({
|
|
window: browser,
|
|
document: browser.document,
|
|
Event: browser.Event,
|
|
IS_REACT_ACT_ENVIRONMENT: true,
|
|
})) {
|
|
Object.defineProperty(globalThis, key, { configurable: true, writable: true, value });
|
|
}
|
|
({ createRoot } = await import('react-dom/client'));
|
|
({ DatasetDownload } = await import(
|
|
'../../apps/stock/web-app/src/features/backtest/components/DatasetDownload'
|
|
));
|
|
({ CanonicalSetup } = await import(
|
|
'../../apps/stock/web-app/src/features/backtest/components/CanonicalSetup'
|
|
));
|
|
({ backtestApiV2 } = await import(
|
|
'../../apps/stock/web-app/src/features/backtest/services/backtestApiV2'
|
|
));
|
|
});
|
|
beforeEach(() => {
|
|
requests.length = blobs.length = revoked.length = downloads.length = 0;
|
|
clickFailure = false;
|
|
host = browser.document.createElement('div') as unknown as HTMLDivElement;
|
|
browser.document.body.append(host as never);
|
|
browser.fetch = ((url: RequestInfo | URL, init?: RequestInit) => {
|
|
const value = { ...deferred<Response>(), path: new URL(String(url)).pathname, init };
|
|
requests.push(value);
|
|
return value.promise; // Deliberately ignore abort to exercise the caller's late-response fences.
|
|
}) as unknown as typeof browser.fetch;
|
|
Object.defineProperty(URL, 'createObjectURL', {
|
|
configurable: true,
|
|
value: (blob: Blob) => {
|
|
blobs.push(blob);
|
|
return `blob:dataset-${blobs.length}`;
|
|
},
|
|
});
|
|
Object.defineProperty(URL, 'revokeObjectURL', {
|
|
configurable: true,
|
|
value: (url: string) => revoked.push(url),
|
|
});
|
|
Object.defineProperty(browser.HTMLAnchorElement.prototype, 'click', {
|
|
configurable: true,
|
|
value: function (this: HTMLAnchorElement) {
|
|
if (clickFailure) {
|
|
throw new Error('Browser download failed');
|
|
}
|
|
downloads.push({ href: this.href, filename: this.download, connected: this.isConnected });
|
|
},
|
|
});
|
|
});
|
|
afterEach(async () => {
|
|
if (root) {
|
|
await flush(() => root!.unmount());
|
|
}
|
|
root = undefined;
|
|
await tick();
|
|
host.remove();
|
|
});
|
|
afterAll(async () => {
|
|
await browser.happyDOM.close();
|
|
for (const [target, key, descriptor] of [
|
|
[URL, 'createObjectURL', createUrlDescriptor],
|
|
[URL, 'revokeObjectURL', revokeUrlDescriptor],
|
|
[browser.HTMLAnchorElement.prototype, 'click', clickDescriptor],
|
|
...keys.map(key => [globalThis, key, originals.get(key)] as const),
|
|
] as const) {
|
|
if (descriptor) {
|
|
Object.defineProperty(target, key, descriptor);
|
|
} else {
|
|
Reflect.deleteProperty(target, key);
|
|
}
|
|
}
|
|
});
|
|
|
|
describe('retained dataset download', () => {
|
|
test('does no network or download work without an explicit click', async () => {
|
|
await mount();
|
|
expect(button().type).toBe('button');
|
|
expect(button().disabled).toBe(false);
|
|
expect(host.querySelector('[role="alert"]')).toBeNull();
|
|
expect(requests).toHaveLength(0);
|
|
expect(blobs).toHaveLength(0);
|
|
expect(downloads).toHaveLength(0);
|
|
});
|
|
|
|
test('downloads exact received text with converted parent identity, delayed availability and null VWAP', async () => {
|
|
const source = datasetInput();
|
|
const converted = createDatasetV2FromLegacy(
|
|
{
|
|
metadata: {
|
|
...source.metadata,
|
|
series: source.metadata.series.map(series => ({ ...series, availability: 'explicit' })),
|
|
},
|
|
bars: source.bars.map((bar, index) => ({
|
|
...bar,
|
|
vwap: null,
|
|
sourceSequence: index + 101,
|
|
availableAt: source.metadata.calendars[0]!.sessions[index]!.close + 123,
|
|
})),
|
|
},
|
|
'c'.repeat(64)
|
|
);
|
|
const bytes = ` \n${JSON.stringify(converted, null, 3)}\n `;
|
|
let submits = 0;
|
|
await mount(
|
|
createElement(
|
|
'form',
|
|
{ onSubmit: () => submits++ },
|
|
createElement(DatasetDownload, { hash: converted.manifest.hash })
|
|
)
|
|
);
|
|
await flush(() => {
|
|
button().click();
|
|
button().click();
|
|
});
|
|
expect(requests).toHaveLength(1);
|
|
expect(requests[0]!.init?.credentials).toBe('include');
|
|
expect(requests[0]!.init?.method ?? 'GET').toBe('GET');
|
|
expect(requests[0]!.init?.body).toBeUndefined();
|
|
expect(button().disabled).toBe(true);
|
|
expect(host.querySelector('[role="status"]')?.textContent).toBe(
|
|
'Downloading retained dataset...'
|
|
);
|
|
await flush(() =>
|
|
request(exportPath(converted.manifest.hash)).resolve(
|
|
json(bytes, 200, 'application/json; charset=UTF-8')
|
|
)
|
|
);
|
|
expect(blobs).toHaveLength(1);
|
|
expect(blobs[0]!.type.split(';')[0]).toBe('application/json');
|
|
expect(await blobs[0]!.text()).toBe(bytes);
|
|
expect(validateDatasetV2(JSON.parse(await blobs[0]!.text()))).toEqual(converted);
|
|
expect(downloads).toEqual([
|
|
{
|
|
href: 'blob:dataset-1',
|
|
filename: `dataset-${converted.manifest.hash}.json`,
|
|
connected: true,
|
|
},
|
|
]);
|
|
expect(browser.document.querySelector('a[download]')).toBeNull();
|
|
expect(submits).toBe(0);
|
|
expect(button().disabled).toBe(false);
|
|
expect(host.querySelector('[role="status"]')).toBeNull();
|
|
await tick();
|
|
expect(revoked).toEqual(['blob:dataset-1']);
|
|
});
|
|
|
|
for (const status of [400, 401, 403, 404, 409, 422, 500]) {
|
|
test(`keeps HTTP ${status} errors on the page without a file or automatic retry`, async () => {
|
|
await mount();
|
|
await flush(() => button().click());
|
|
await flush(() =>
|
|
request().resolve(Response.json({ error: `Rejected (${status})` }, { status }))
|
|
);
|
|
expect(host.querySelector('[role="alert"]')?.textContent).toBe(`Rejected (${status})`);
|
|
expect(button('Retry dataset download').disabled).toBe(false);
|
|
expect(requests).toHaveLength(1);
|
|
expect(blobs).toHaveLength(0);
|
|
expect(downloads).toHaveLength(0);
|
|
});
|
|
}
|
|
|
|
const invalidResponses = [
|
|
['HTML body', () => json('<html>Login</html>')],
|
|
['HTML type', () => json(JSON.stringify(dataset), 200, 'text/html')],
|
|
['missing type', () => new Response(JSON.stringify(dataset), { headers: {} })],
|
|
['unexpected accepted status', () => json(JSON.stringify(dataset), 202)],
|
|
['partial status', () => json(JSON.stringify(dataset), 206)],
|
|
['metadata envelope', () => json(JSON.stringify({ dataset: entry() }))],
|
|
['extra envelope property', () => json(JSON.stringify({ ...dataset, unexpected: true }))],
|
|
['wrong identity', () => json(JSON.stringify(other))],
|
|
['missing bars', () => json(JSON.stringify({ manifest: dataset.manifest }))],
|
|
['bars not an array', () => json(JSON.stringify({ ...dataset, bars: {} }))],
|
|
['wrong count', () => json(JSON.stringify({ ...dataset, bars: [] }))],
|
|
[
|
|
'invalid manifest',
|
|
() => json(JSON.stringify({ ...dataset, manifest: { ...dataset.manifest, bounds: null } })),
|
|
],
|
|
] as const;
|
|
for (const [name, response] of invalidResponses) {
|
|
test(`rejects ${name} before creating a download`, async () => {
|
|
await mount();
|
|
await flush(() => button().click());
|
|
await flush(() => request().resolve(response()));
|
|
expect(host.querySelector('[role="alert"]')?.textContent).toContain('could not be verified');
|
|
expect(button('Retry dataset download').disabled).toBe(false);
|
|
expect(blobs).toHaveLength(0);
|
|
expect(downloads).toHaveLength(0);
|
|
expect(requests).toHaveLength(1);
|
|
});
|
|
}
|
|
|
|
for (const failure of ['fetch', 'body'] as const) {
|
|
test(`explicitly retries a lost ${failure} response with the same hash`, async () => {
|
|
await mount();
|
|
await flush(() => button().click());
|
|
const body = deferred<string>();
|
|
const response = json();
|
|
Object.defineProperty(response, 'text', { value: () => body.promise });
|
|
if (failure === 'fetch') {
|
|
await flush(() => request().reject(new Error('Connection lost')));
|
|
} else {
|
|
await flush(() => request().resolve(response));
|
|
await flush(() => body.reject(new Error('Body lost')));
|
|
}
|
|
expect(host.querySelector('[role="alert"]')).not.toBeNull();
|
|
expect(requests).toHaveLength(1);
|
|
expect(downloads).toHaveLength(0);
|
|
await flush(() => button('Retry dataset download').click());
|
|
expect(requests).toHaveLength(2);
|
|
expect(requests[1]!.path).toBe(exportPath(hash));
|
|
expect(host.querySelector('[role="alert"]')).toBeNull();
|
|
await flush(() => requests[1]!.resolve(json()));
|
|
expect(downloads).toHaveLength(1);
|
|
expect(button().disabled).toBe(false);
|
|
});
|
|
}
|
|
|
|
for (const change of ['hash', 'unmount'] as const) {
|
|
for (const late of ['response', 'body'] as const) {
|
|
test(`${change} fences a late ${late} even when transport ignores cancellation`, async () => {
|
|
await mount();
|
|
await flush(() => button().click());
|
|
const old = request();
|
|
const body = deferred<string>();
|
|
const response = json();
|
|
Object.defineProperty(response, 'text', { value: () => body.promise });
|
|
if (late === 'body') {
|
|
await flush(() => old.resolve(response));
|
|
}
|
|
await flush(() => {
|
|
if (change === 'hash') {
|
|
root!.render(createElement(DatasetDownload, { hash: other.manifest.hash }));
|
|
} else {
|
|
root!.unmount();
|
|
root = undefined;
|
|
}
|
|
});
|
|
expect(old.init?.signal?.aborted).toBe(true);
|
|
await flush(() => {
|
|
old.resolve(response);
|
|
body.resolve(JSON.stringify(dataset));
|
|
});
|
|
expect(blobs).toHaveLength(0);
|
|
expect(downloads).toHaveLength(0);
|
|
expect(host.querySelector('[role="alert"]')).toBeNull();
|
|
if (change === 'hash') {
|
|
expect(button().disabled).toBe(false);
|
|
await flush(() => button().click());
|
|
await flush(() =>
|
|
request(exportPath(other.manifest.hash)).resolve(json(JSON.stringify(other)))
|
|
);
|
|
expect(downloads[0]!.filename).toBe(`dataset-${other.manifest.hash}.json`);
|
|
}
|
|
});
|
|
}
|
|
}
|
|
|
|
test('releases the Blob URL and allows retry if the browser click fails', async () => {
|
|
clickFailure = true;
|
|
await mount();
|
|
await flush(() => button().click());
|
|
await flush(() => request().resolve(json()));
|
|
expect(host.querySelector('[role="alert"]')?.textContent).toBe('Browser download failed');
|
|
expect(button('Retry dataset download').disabled).toBe(false);
|
|
expect(browser.document.querySelector('a[download]')).toBeNull();
|
|
await tick();
|
|
expect(revoked).toEqual(['blob:dataset-1']);
|
|
});
|
|
|
|
test('invalid hashes and already cancelled requests never fetch', async () => {
|
|
await expect(backtestApiV2.downloadCanonicalDataset('../invalid')).rejects.toThrow(
|
|
'dataset hash'
|
|
);
|
|
const controller = new AbortController();
|
|
controller.abort();
|
|
await expect(backtestApiV2.downloadCanonicalDataset(hash, controller.signal)).rejects.toThrow();
|
|
expect(requests).toHaveLength(0);
|
|
});
|
|
|
|
test('setup exposes only verified selection and cancels export when selection changes', async () => {
|
|
const saves: unknown[] = [];
|
|
await mount(
|
|
createElement(CanonicalSetup, {
|
|
backtest: definition,
|
|
onSave: async value => {
|
|
saves.push(value);
|
|
},
|
|
})
|
|
);
|
|
expect(host.textContent).not.toContain('Download retained dataset');
|
|
await flush(() =>
|
|
request('/api/v2/datasets/canonical').resolve(
|
|
Response.json({ datasets: [entry(), entry(other)] })
|
|
)
|
|
);
|
|
expect(host.textContent).not.toContain('Download retained dataset');
|
|
await flush(() =>
|
|
request(`/api/v2/datasets/canonical/${hash}`).resolve(Response.json({ dataset: entry() }))
|
|
);
|
|
expect(button().disabled).toBe(false);
|
|
await flush(() => button().click());
|
|
const pending = request();
|
|
const select = host.querySelector('[aria-label="Canonical dataset"]') as HTMLSelectElement;
|
|
await flush(() => {
|
|
select.value = other.manifest.hash;
|
|
select.dispatchEvent(new browser.Event('change', { bubbles: true }) as unknown as Event);
|
|
});
|
|
expect(host.textContent).not.toContain('Download retained dataset');
|
|
expect(pending.init?.signal?.aborted).toBe(true);
|
|
await flush(() => pending.resolve(json()));
|
|
expect(downloads).toHaveLength(0);
|
|
await flush(() =>
|
|
request(`/api/v2/datasets/canonical/${other.manifest.hash}`).resolve(
|
|
Response.json({ dataset: entry(other) })
|
|
)
|
|
);
|
|
await flush(() => button().click());
|
|
await flush(() =>
|
|
request(exportPath(other.manifest.hash)).resolve(json(JSON.stringify(other)))
|
|
);
|
|
expect(downloads[0]!.filename).toBe(`dataset-${other.manifest.hash}.json`);
|
|
expect(saves).toHaveLength(0);
|
|
expect(requests.every(item => (item.init?.method ?? 'GET') === 'GET')).toBe(true);
|
|
});
|
|
});
|