941 lines
37 KiB
TypeScript
941 lines
37 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 type {
|
|
Backtest,
|
|
Run,
|
|
RunResult,
|
|
} from '../../apps/stock/web-app/src/features/backtest/services/backtestApiV2';
|
|
|
|
// Local to this file: no global preload, browser server or second test runner.
|
|
const browser = new GlobalWindow({ url: 'http://localhost:5173' });
|
|
const globals = ['window', 'document', 'WebSocket', 'IS_REACT_ACT_ENVIRONMENT'] as const;
|
|
const savedGlobals = new Map(
|
|
globals.map(key => [key, Object.getOwnPropertyDescriptor(globalThis, key)])
|
|
);
|
|
const realTimeout = globalThis.setTimeout;
|
|
const realClearTimeout = globalThis.clearTimeout;
|
|
const realInterval = globalThis.setInterval;
|
|
const realClearInterval = globalThis.clearInterval;
|
|
let createRoot: typeof import('react-dom/client').createRoot;
|
|
let useBacktestV2: typeof import('../../apps/stock/web-app/src/features/backtest/hooks/useBacktestV2').useBacktestV2;
|
|
let useWebSocket: typeof import('../../apps/stock/web-app/src/hooks/useWebSocket').useWebSocket;
|
|
let RunControlsCompact: typeof import('../../apps/stock/web-app/src/features/backtest/components/RunControlsCompact').RunControlsCompact;
|
|
let BacktestDetailPageV2: typeof import('../../apps/stock/web-app/src/features/backtest/BacktestDetailPageV2').BacktestDetailPageV2;
|
|
let CreateBacktestDialog: typeof import('../../apps/stock/web-app/src/features/backtest/components/CreateBacktestDialog').CreateBacktestDialog;
|
|
let BacktestListPageV2: typeof import('../../apps/stock/web-app/src/features/backtest/BacktestListPageV2').BacktestListPageV2;
|
|
let router: typeof import('react-router-dom');
|
|
let root: Root | undefined;
|
|
let host: HTMLDivElement;
|
|
let latest: ReturnType<typeof useBacktestV2>;
|
|
let renders = 0;
|
|
let pageLocation = '';
|
|
let navigatePage: ReturnType<typeof router.useNavigate>;
|
|
let now = 0;
|
|
let timerId = 0;
|
|
const timers = new Map<
|
|
number,
|
|
{ at: number; delay: number; callback: () => void; repeat: boolean }
|
|
>();
|
|
|
|
function deferred<T>() {
|
|
let resolve!: (value: T) => void;
|
|
let reject!: (reason: Error) => void;
|
|
const promise = new Promise<T>((yes, no) => {
|
|
resolve = yes;
|
|
reject = no;
|
|
});
|
|
return { promise, resolve, reject };
|
|
}
|
|
type Request = ReturnType<typeof deferred<Response>> & {
|
|
path: string;
|
|
method: string;
|
|
signal?: AbortSignal | null;
|
|
settled: boolean;
|
|
body?: string;
|
|
headers: Headers;
|
|
};
|
|
const requests: Request[] = [];
|
|
function request(path: string, method = 'GET') {
|
|
const found = requests.find(
|
|
item => item.path === path && item.method === method && !item.settled
|
|
);
|
|
if (!found) throw new Error(`No pending ${method} ${path}`);
|
|
return found;
|
|
}
|
|
function reply(pending: Request, body: unknown, status = 200) {
|
|
pending.settled = true;
|
|
pending.resolve(Response.json(body, { status }));
|
|
}
|
|
function fail(pending: Request) {
|
|
pending.settled = true;
|
|
pending.reject(new Error('Network unavailable'));
|
|
}
|
|
const run = (id: string, status: Run['status'] = 'running', extra: Partial<Run> = {}): Run => ({
|
|
id,
|
|
backtestId: 'definition',
|
|
runNumber: 1,
|
|
status,
|
|
speedMultiplier: null,
|
|
progress: 0,
|
|
createdAt: '2024-01-01',
|
|
updatedAt: '2024-01-01',
|
|
...extra,
|
|
});
|
|
const results = (id: string): RunResult => ({
|
|
runId: id,
|
|
backtestId: 'definition',
|
|
engine: 'typescript',
|
|
status: 'completed',
|
|
completedAt: '2024-02-01',
|
|
config: {
|
|
name: 'Fixture',
|
|
strategy: 'sma',
|
|
symbols: ['A.US'],
|
|
startDate: '2024-01-01',
|
|
endDate: '2024-02-01',
|
|
initialCapital: 1000,
|
|
commission: 0,
|
|
slippage: 0,
|
|
dataFrequency: '1d',
|
|
parameters: {},
|
|
},
|
|
metrics: {
|
|
totalReturn: 0,
|
|
sharpeRatio: null,
|
|
maxDrawdown: 0,
|
|
winRate: 0,
|
|
totalTrades: 0,
|
|
profitFactor: null,
|
|
},
|
|
equity: [],
|
|
ohlcData: {},
|
|
positions: [],
|
|
trades: [],
|
|
analytics: {},
|
|
executionTime: 0,
|
|
});
|
|
const definition = {
|
|
id: 'definition',
|
|
name: 'Fixture',
|
|
strategy: 'sma',
|
|
symbols: ['A.US'],
|
|
startDate: '2024-01-01',
|
|
endDate: '2024-02-01',
|
|
initialCapital: 1000,
|
|
config: {},
|
|
createdAt: '2024-01-01',
|
|
updatedAt: '2024-01-01',
|
|
};
|
|
|
|
class TestSocket {
|
|
static OPEN = 1;
|
|
static CONNECTING = 0;
|
|
static instances: TestSocket[] = [];
|
|
readyState = 0;
|
|
onopen: (() => void) | null = null;
|
|
onmessage: ((event: { data: string }) => void) | null = null;
|
|
onclose: (() => void) | null = null;
|
|
onerror: (() => void) | null = null;
|
|
constructor(readonly url: string) {
|
|
TestSocket.instances.push(this);
|
|
}
|
|
send() {}
|
|
open() {
|
|
this.readyState = 1;
|
|
this.onopen?.();
|
|
}
|
|
close() {
|
|
this.readyState = 3;
|
|
this.onclose?.();
|
|
}
|
|
message(value: unknown) {
|
|
this.onmessage?.({ data: JSON.stringify(value) });
|
|
}
|
|
}
|
|
|
|
async function flush(action: () => void = () => {}) {
|
|
await act(async () => {
|
|
action();
|
|
await Promise.resolve();
|
|
});
|
|
}
|
|
async function advance(ms: number) {
|
|
now += ms;
|
|
const due = [...timers].filter(([, timer]) => timer.at <= now);
|
|
await flush(() => {
|
|
for (const [id, timer] of due) {
|
|
if (!timers.has(id)) continue;
|
|
timers.delete(id);
|
|
if (timer.repeat) timers.set(id, { ...timer, at: now + timer.delay });
|
|
timer.callback();
|
|
}
|
|
});
|
|
}
|
|
const polls = () => [...timers.values()].filter(timer => timer.delay === 1000).length;
|
|
function click(label: string) {
|
|
const buttons = [...host.querySelectorAll('button')];
|
|
const button =
|
|
buttons.find(item => item.textContent?.trim() === label) ??
|
|
buttons.find(item => item.getAttribute('aria-label') === label);
|
|
if (!button) throw new Error(`Missing button ${label}`);
|
|
button.click();
|
|
}
|
|
function HookHost({ socket = false }: { socket?: boolean }) {
|
|
latest = useBacktestV2();
|
|
renders++;
|
|
useWebSocket({
|
|
runId: socket ? (latest.currentRun?.id ?? null) : null,
|
|
onMessage: message => {
|
|
if (message.type !== 'pong') void latest.refreshRun(message.runId);
|
|
},
|
|
});
|
|
return latest.currentRun
|
|
? createElement(RunControlsCompact, {
|
|
run: latest.currentRun,
|
|
cancelRequested: latest.cancelRequested,
|
|
onCancel: latest.cancelRun,
|
|
onRerun: () => {},
|
|
})
|
|
: null;
|
|
}
|
|
async function mount(element: ReactElement = createElement(HookHost)) {
|
|
root = createRoot(host);
|
|
await flush(() => root!.render(element));
|
|
}
|
|
async function select(id: string) {
|
|
await flush(() => {
|
|
void latest.selectRun(id);
|
|
});
|
|
}
|
|
async function selectRunning(id = 'A', status: Run['status'] = 'running') {
|
|
await select(id);
|
|
await flush(() => reply(request(`/api/v2/runs/${id}`), run(id, status)));
|
|
}
|
|
async function mountPage(status: Run['status']) {
|
|
await mount(
|
|
createElement(
|
|
router.MemoryRouter,
|
|
{ initialEntries: ['/backtests/definition/run/A'] },
|
|
createElement(
|
|
router.Routes,
|
|
null,
|
|
createElement(router.Route, {
|
|
path: '/backtests/:id/run/:runId',
|
|
element: createElement(BacktestDetailPageV2),
|
|
})
|
|
),
|
|
createElement(LocationProbe)
|
|
)
|
|
);
|
|
await flush(() => {
|
|
reply(request('/api/v2/backtests/definition'), definition);
|
|
reply(request('/api/v2/backtests/definition/runs'), []);
|
|
reply(
|
|
request('/api/v2/runs/A'),
|
|
run('A', status, status === 'failed' ? { error: 'Fixture failure' } : {})
|
|
);
|
|
});
|
|
}
|
|
|
|
function LocationProbe() {
|
|
pageLocation = router.useLocation().pathname;
|
|
navigatePage = router.useNavigate();
|
|
return null;
|
|
}
|
|
|
|
beforeAll(async () => {
|
|
for (const [key, value] of Object.entries({
|
|
window: browser,
|
|
document: browser.document,
|
|
WebSocket: TestSocket,
|
|
IS_REACT_ACT_ENVIRONMENT: true,
|
|
}))
|
|
Object.defineProperty(globalThis, key, { configurable: true, writable: true, value });
|
|
({ createRoot } = await import('react-dom/client'));
|
|
({ useBacktestV2 } = await import(
|
|
'../../apps/stock/web-app/src/features/backtest/hooks/useBacktestV2'
|
|
));
|
|
({ useWebSocket } = await import('../../apps/stock/web-app/src/hooks/useWebSocket'));
|
|
({ RunControlsCompact } = await import(
|
|
'../../apps/stock/web-app/src/features/backtest/components/RunControlsCompact'
|
|
));
|
|
({ BacktestDetailPageV2 } = await import(
|
|
'../../apps/stock/web-app/src/features/backtest/BacktestDetailPageV2'
|
|
));
|
|
({ CreateBacktestDialog } = await import(
|
|
'../../apps/stock/web-app/src/features/backtest/components/CreateBacktestDialog'
|
|
));
|
|
({ BacktestListPageV2 } = await import(
|
|
'../../apps/stock/web-app/src/features/backtest/BacktestListPageV2'
|
|
));
|
|
router = await import('react-router-dom');
|
|
});
|
|
beforeEach(() => {
|
|
requests.length = 0;
|
|
TestSocket.instances.length = 0;
|
|
renders = 0;
|
|
pageLocation = '';
|
|
now = 0;
|
|
timers.clear();
|
|
host = browser.document.createElement('div') as unknown as HTMLDivElement;
|
|
browser.document.body.append(host as never);
|
|
browser.fetch = ((input: RequestInfo | URL, init?: RequestInit) => {
|
|
const pending: Request = {
|
|
...deferred<Response>(),
|
|
path: new URL(String(input)).pathname,
|
|
method: init?.method ?? 'GET',
|
|
signal: init?.signal,
|
|
body: typeof init?.body === 'string' ? init.body : undefined,
|
|
headers: new Headers(init?.headers),
|
|
settled: false,
|
|
};
|
|
requests.push(pending);
|
|
// Deliberately ignore abort: guards must also reject a late server continuation.
|
|
return pending.promise;
|
|
}) as typeof browser.fetch;
|
|
const schedule = (repeat: boolean, original: typeof setTimeout) =>
|
|
((callback: () => void, delay?: number, ...args: unknown[]) => {
|
|
if (![1000, 3000, 30000].includes(delay ?? 0)) return original(callback, delay, ...args);
|
|
const id = ++timerId;
|
|
timers.set(id, { at: now + delay!, delay: delay!, callback, repeat });
|
|
return id;
|
|
}) as typeof setTimeout;
|
|
globalThis.setTimeout = schedule(false, realTimeout);
|
|
globalThis.setInterval = schedule(true, realInterval as typeof setTimeout) as typeof setInterval;
|
|
globalThis.clearTimeout = ((id: number) => {
|
|
if (!timers.delete(id)) realClearTimeout(id);
|
|
}) as typeof clearTimeout;
|
|
globalThis.clearInterval = ((id: number) => {
|
|
if (!timers.delete(id)) realClearInterval(id);
|
|
}) as typeof clearInterval;
|
|
});
|
|
afterEach(async () => {
|
|
let leakedTimers = 0;
|
|
try {
|
|
if (root) await flush(() => root!.unmount());
|
|
leakedTimers = timers.size;
|
|
} finally {
|
|
root = undefined;
|
|
globalThis.setTimeout = realTimeout;
|
|
globalThis.clearTimeout = realClearTimeout;
|
|
globalThis.setInterval = realInterval;
|
|
globalThis.clearInterval = realClearInterval;
|
|
timers.clear();
|
|
host?.remove();
|
|
}
|
|
expect(leakedTimers).toBe(0);
|
|
});
|
|
afterAll(async () => {
|
|
try {
|
|
await browser.happyDOM.close();
|
|
} finally {
|
|
for (const key of globals) {
|
|
const descriptor = savedGlobals.get(key);
|
|
if (descriptor) Object.defineProperty(globalThis, key, descriptor);
|
|
else Reflect.deleteProperty(globalThis, key);
|
|
}
|
|
}
|
|
});
|
|
|
|
describe('run selection and persisted status authority', () => {
|
|
for (const lateFailure of [false, true]) {
|
|
test(`stale_status_response: A ${lateFailure ? 'error' : 'success'}/finally cannot replace B loading`, async () => {
|
|
await mount();
|
|
await select('A');
|
|
const previous = request('/api/v2/runs/A');
|
|
await select('B');
|
|
expect(previous.signal?.aborted).toBe(true);
|
|
await flush(() => (lateFailure ? fail(previous) : reply(previous, run('A'))));
|
|
expect(latest.currentRun).toBeNull();
|
|
expect(latest.isLoading).toBe(true);
|
|
expect(latest.error).toBeNull();
|
|
await flush(() => reply(request('/api/v2/runs/B'), run('B')));
|
|
expect(latest.currentRun?.id).toBe('B');
|
|
expect(latest.isLoading).toBe(false);
|
|
expect(polls()).toBe(1);
|
|
});
|
|
test(`stale_results_response: A ${lateFailure ? 'error' : 'success'} cannot replace B results`, async () => {
|
|
await mount();
|
|
await select('A');
|
|
await flush(() => reply(request('/api/v2/runs/A'), run('A', 'completed')));
|
|
const previous = request('/api/v2/runs/A/results');
|
|
await select('B');
|
|
await flush(() => reply(request('/api/v2/runs/B'), run('B', 'completed')));
|
|
await flush(() => reply(request('/api/v2/runs/B/results'), results('B')));
|
|
await flush(() => (lateFailure ? fail(previous) : reply(previous, results('A'))));
|
|
expect(previous.signal?.aborted).toBe(true);
|
|
expect(latest.currentRun?.id).toBe('B');
|
|
expect(latest.runResults?.runId).toBe('B');
|
|
expect(latest.error).toBeNull();
|
|
expect(polls()).toBe(0);
|
|
});
|
|
}
|
|
|
|
test('one_poll_in_flight: invalidations coalesce, slow requests do not overlap, polling recovers', async () => {
|
|
await mount();
|
|
await selectRunning();
|
|
await advance(1000);
|
|
const first = request('/api/v2/runs/A');
|
|
await advance(10000);
|
|
await flush(() => {
|
|
void latest.refreshRun('A');
|
|
void latest.refreshRun('A');
|
|
});
|
|
expect(requests.filter(item => item.path === '/api/v2/runs/A')).toHaveLength(2);
|
|
await flush(() => reply(first, run('A', 'running', { progress: 20 })));
|
|
expect(requests.filter(item => item.path === '/api/v2/runs/A')).toHaveLength(3);
|
|
await flush(() => fail(request('/api/v2/runs/A')));
|
|
expect(latest.error).toContain('Network unavailable');
|
|
expect(latest.currentRun?.progress).toBe(20);
|
|
expect(polls()).toBe(1);
|
|
await advance(1000);
|
|
await flush(() => reply(request('/api/v2/runs/A'), run('A', 'completed')));
|
|
await flush(() => reply(request('/api/v2/runs/A/results'), results('A')));
|
|
expect(latest.error).toBeNull();
|
|
expect(latest.runResults?.runId).toBe('A');
|
|
expect(polls()).toBe(0);
|
|
});
|
|
|
|
test('stale results error/finally does not clear the newer selection loading state', async () => {
|
|
await mount();
|
|
await select('A');
|
|
await flush(() => reply(request('/api/v2/runs/A'), run('A', 'completed')));
|
|
const previous = request('/api/v2/runs/A/results');
|
|
await select('B');
|
|
await flush(() => fail(previous));
|
|
expect(latest.isLoading).toBe(true);
|
|
expect(latest.error).toBeNull();
|
|
expect(latest.currentRun).toBeNull();
|
|
await flush(() => reply(request('/api/v2/runs/B'), run('B', 'failed')));
|
|
expect(latest.currentRun?.id).toBe('B');
|
|
expect(latest.isLoading).toBe(false);
|
|
});
|
|
|
|
test('no_publish_after_unmount also ignores a late initial status failure', async () => {
|
|
await mount();
|
|
await select('A');
|
|
const pending = request('/api/v2/runs/A');
|
|
await flush(() => root!.unmount());
|
|
root = undefined;
|
|
const before = renders;
|
|
await flush(() => fail(pending));
|
|
expect(pending.signal?.aborted).toBe(true);
|
|
expect(renders).toBe(before);
|
|
expect(timers.size).toBe(0);
|
|
});
|
|
|
|
test('no_publish_after_unmount: abort results and remove pending poll/subscription work', async () => {
|
|
await mount(createElement(HookHost, { socket: true }));
|
|
await selectRunning();
|
|
const socket = TestSocket.instances[0]!;
|
|
await flush(() => socket.open());
|
|
await advance(1000);
|
|
await flush(() => reply(request('/api/v2/runs/A'), run('A', 'completed')));
|
|
const pending = request('/api/v2/runs/A/results');
|
|
await flush(() => root!.unmount());
|
|
root = undefined;
|
|
const before = renders;
|
|
await flush(() => reply(pending, results('A')));
|
|
await advance(30000);
|
|
expect(pending.signal?.aborted).toBe(true);
|
|
expect(socket.readyState).toBe(3);
|
|
expect(renders).toBe(before);
|
|
expect(timers.size).toBe(0);
|
|
});
|
|
|
|
for (const initial of ['pending', 'running'] as const) {
|
|
test(`pending_vs_active_cancel: ${initial} acknowledgement is not invented completion`, async () => {
|
|
await mount();
|
|
await selectRunning('A', initial);
|
|
await flush(() => click('Cancel run'));
|
|
expect(host.textContent).toContain('Cancellation requested');
|
|
await flush(() => reply(request('/api/v2/runs/A/cancel', 'POST'), { accepted: true }, 202));
|
|
expect(latest.currentRun?.status).toBe(initial);
|
|
const acknowledged = initial === 'pending' ? 'cancelled' : 'running';
|
|
await flush(() =>
|
|
reply(request('/api/v2/runs/A'), run('A', acknowledged, { cancelRequested: true }))
|
|
);
|
|
expect(latest.currentRun?.status).toBe(acknowledged);
|
|
if (initial === 'running') {
|
|
expect(latest.cancelRequested).toBe(true);
|
|
expect(host.textContent).toContain('Cancellation requested');
|
|
await advance(1000);
|
|
await flush(() => reply(request('/api/v2/runs/A'), run('A', 'cancelled')));
|
|
}
|
|
expect(host.textContent).toContain('Cancelled');
|
|
expect(latest.cancelRequested).toBe(false);
|
|
expect(latest.runResults).toBeNull();
|
|
expect(polls()).toBe(0);
|
|
});
|
|
}
|
|
|
|
test('late cancel failure cannot change a newer selection', async () => {
|
|
await mount();
|
|
await selectRunning();
|
|
await flush(() => click('Cancel run'));
|
|
const pending = request('/api/v2/runs/A/cancel', 'POST');
|
|
await selectRunning('B');
|
|
await flush(() => fail(pending));
|
|
expect(latest.currentRun?.id).toBe('B');
|
|
expect(latest.cancelRequested).toBe(false);
|
|
expect(latest.error).toBeNull();
|
|
});
|
|
|
|
test('failed cancellation is retriable and a racing persisted completion wins', async () => {
|
|
await mount();
|
|
await selectRunning();
|
|
await flush(() => click('Cancel run'));
|
|
await flush(() => fail(request('/api/v2/runs/A/cancel', 'POST')));
|
|
expect(latest.cancelRequested).toBe(false);
|
|
expect(latest.error).toContain('Network unavailable');
|
|
await flush(() => click('Cancel run'));
|
|
await flush(() => reply(request('/api/v2/runs/A/cancel', 'POST'), { accepted: true }, 202));
|
|
await flush(() => reply(request('/api/v2/runs/A'), run('A', 'completed')));
|
|
await flush(() => reply(request('/api/v2/runs/A/results'), results('A')));
|
|
expect(latest.currentRun?.status).toBe('completed');
|
|
expect(latest.cancelRequested).toBe(false);
|
|
expect(latest.error).toBeNull();
|
|
expect(latest.runResults?.runId).toBe('A');
|
|
expect(polls()).toBe(0);
|
|
});
|
|
|
|
test('unsupported_controls: server pause/resume/speed are absent for running and paused runs', async () => {
|
|
await mount();
|
|
await selectRunning();
|
|
expect([...host.querySelectorAll('button')].map(item => item.title)).toEqual([
|
|
'Cancel run',
|
|
'Run current settings',
|
|
]);
|
|
await selectRunning('B', 'paused');
|
|
expect([...host.querySelectorAll('button')].map(item => item.title)).toEqual([
|
|
'Cancel run',
|
|
'Run current settings',
|
|
]);
|
|
});
|
|
|
|
test('reconnect_or_poll_recovery: reconnect refetches persisted state and old sockets cannot publish', async () => {
|
|
await mount(createElement(HookHost, { socket: true }));
|
|
await selectRunning();
|
|
const first = TestSocket.instances[0]!;
|
|
await flush(() => first.open());
|
|
const lateMessage = first.onmessage!;
|
|
await flush(() => first.close());
|
|
await advance(3000);
|
|
expect(TestSocket.instances).toHaveLength(2);
|
|
const second = TestSocket.instances[1]!;
|
|
await flush(() => {
|
|
second.open();
|
|
second.message({ type: 'connected', runId: 'A' });
|
|
});
|
|
// The websocket invalidation coalesces with the already due fallback poll.
|
|
expect(requests.filter(item => !item.settled && item.path === '/api/v2/runs/A')).toHaveLength(
|
|
1
|
|
);
|
|
await selectRunning('B');
|
|
const count = requests.length;
|
|
await flush(() => lateMessage({ data: JSON.stringify({ type: 'completed', runId: 'A' }) }));
|
|
expect(requests).toHaveLength(count);
|
|
expect(latest.currentRun?.id).toBe('B');
|
|
expect(second.readyState).toBe(3);
|
|
});
|
|
});
|
|
|
|
describe('actual detail page result states', () => {
|
|
test('detail cancel control is wired to durable cancellation, not chart playback', async () => {
|
|
await mountPage('running');
|
|
await flush(() => click('Cancel run'));
|
|
expect(host.textContent).toContain('Cancellation requested');
|
|
await flush(() => reply(request('/api/v2/runs/A/cancel', 'POST'), {}, 202));
|
|
expect(host.textContent).not.toContain('Run cancelled');
|
|
await flush(() => reply(request('/api/v2/runs/A'), run('A', 'cancelled')));
|
|
expect(host.textContent).toContain('Run cancelled');
|
|
expect(host.textContent).not.toContain('No trades executed');
|
|
});
|
|
for (const status of ['failed', 'cancelled'] as const) {
|
|
test(`${status} is not successful zero-trade data`, async () => {
|
|
await mountPage(status);
|
|
await flush(() => click('Trades'));
|
|
expect(host.textContent).toContain(
|
|
status === 'failed' ? 'Run failed: Fixture failure' : 'Run cancelled'
|
|
);
|
|
expect(host.textContent).not.toContain('No trades executed');
|
|
expect(host.querySelector('[aria-label="Result provenance and limitations"]')).toBeNull();
|
|
expect(requests.some(item => item.path.endsWith('/results'))).toBe(false);
|
|
});
|
|
}
|
|
test('completed missing results differ from successful zero trades and retry uses saved results', async () => {
|
|
await mountPage('completed');
|
|
expect(host.textContent).toContain('Loading run data');
|
|
expect(host.querySelector('[aria-label="Result provenance and limitations"]')).toBeNull();
|
|
await flush(() => click('Trades'));
|
|
await flush(() => reply(request('/api/v2/runs/A/results'), { error: 'Not found' }, 404));
|
|
expect(host.textContent).toContain('saved results are unavailable');
|
|
expect(host.textContent).not.toContain('No trades executed');
|
|
expect(host.querySelector('[aria-label="Result provenance and limitations"]')).toBeNull();
|
|
await flush(() => click('Retry results'));
|
|
await flush(() => reply(request('/api/v2/runs/A'), run('A', 'completed')));
|
|
await flush(() => reply(request('/api/v2/runs/A/results'), results('A')));
|
|
expect(host.textContent).toContain('No trades executed in this backtest.');
|
|
expect(host.textContent).not.toContain('saved results are unavailable');
|
|
});
|
|
|
|
test('limitation_badge: completed detail shows unknown legacy provenance beside performance', async () => {
|
|
await mountPage('completed');
|
|
await flush(() => reply(request('/api/v2/runs/A/results'), results('A')));
|
|
const evidence = host.querySelector('[aria-label="Result provenance and limitations"]');
|
|
expect(evidence).not.toBeNull();
|
|
expect(evidence!.textContent).toContain('Research only · Unverified economics');
|
|
const details = evidence!.querySelector('details')!;
|
|
await flush(() => details.querySelector('summary')!.click());
|
|
expect(details.open).toBe(true);
|
|
expect(evidence!.textContent).toContain('Stored run configuration: Unknown');
|
|
expect(evidence!.textContent).toContain('Provenance metadata is unavailable from this API');
|
|
expect(host.textContent).toContain('Performance');
|
|
});
|
|
});
|
|
|
|
async function nameBacktest() {
|
|
await flush(() => {
|
|
const input = host.querySelector('input[placeholder="My Strategy Backtest"]')!;
|
|
Object.getOwnPropertyDescriptor(browser.HTMLInputElement.prototype, 'value')!.set!.call(
|
|
input,
|
|
'Fixture'
|
|
);
|
|
input.dispatchEvent(new browser.Event('input', { bubbles: true }) as unknown as Event);
|
|
});
|
|
}
|
|
|
|
async function loadDefinition(id = 'definition') {
|
|
await flush(() => {
|
|
void latest.loadBacktest(id);
|
|
});
|
|
await flush(() => {
|
|
reply(request(`/api/v2/backtests/${id}`), { ...definition, id });
|
|
reply(request(`/api/v2/backtests/${id}/runs`), []);
|
|
});
|
|
}
|
|
|
|
describe('explicit save and repeat-safe run submission', () => {
|
|
test('save_only: definition save explicitly disables auto-start and makes no run request', async () => {
|
|
const created: Backtest[] = [];
|
|
await mount(
|
|
createElement(CreateBacktestDialog, {
|
|
onClose: () => {},
|
|
onCreated: value => created.push(value),
|
|
})
|
|
);
|
|
await nameBacktest();
|
|
await flush(() => {
|
|
click('Save');
|
|
click('Save');
|
|
});
|
|
const saving = request('/api/v2/backtests', 'POST');
|
|
expect(JSON.parse(saving.body!).autoStart).toBe(false);
|
|
expect(requests.filter(item => item.method === 'POST')).toHaveLength(1);
|
|
await flush(() => reply(saving, definition));
|
|
expect(created).toEqual([definition]);
|
|
expect(requests.filter(item => item.method === 'POST')).toHaveLength(1);
|
|
});
|
|
|
|
for (const failure of ['rejection', 'lost successful response'] as const) {
|
|
test(`save_and_run_failure: ${failure} retries the saved definition, frozen body and key`, async () => {
|
|
const created: { definition: Backtest; run?: Run }[] = [];
|
|
await mount(
|
|
createElement(CreateBacktestDialog, {
|
|
onClose: () => {},
|
|
onCreated: (value, submitted) => created.push({ definition: value, run: submitted }),
|
|
})
|
|
);
|
|
await nameBacktest();
|
|
await flush(() => {
|
|
click('Save and run');
|
|
click('Save and run');
|
|
});
|
|
await flush(() => reply(request('/api/v2/backtests', 'POST'), definition));
|
|
const first = request('/api/v2/backtests/definition/runs', 'POST');
|
|
expect(first.headers.get('Idempotency-Key')).toBeTruthy();
|
|
expect(JSON.parse(first.body!)).toEqual({ speedMultiplier: null });
|
|
// In the lost-response case the server has accepted A; the transport fails.
|
|
await flush(() =>
|
|
failure === 'rejection'
|
|
? reply(first, { error: 'Submission unavailable' }, 503)
|
|
: fail(first)
|
|
);
|
|
expect(created).toHaveLength(0);
|
|
expect(host.textContent).toContain('Backtest saved, but run submission failed');
|
|
expect(host.querySelector('fieldset')!.disabled).toBe(true);
|
|
await flush(() => {
|
|
click('Retry submission');
|
|
click('Retry submission');
|
|
});
|
|
const retry = request('/api/v2/backtests/definition/runs', 'POST');
|
|
expect(retry.headers.get('Idempotency-Key')).toBe(first.headers.get('Idempotency-Key'));
|
|
expect(retry.body).toBe(first.body);
|
|
expect(requests.filter(item => item.path === '/api/v2/backtests')).toHaveLength(1);
|
|
expect(requests.filter(item => item.method === 'POST')).toHaveLength(3);
|
|
await flush(() => reply(retry, run('A', 'pending'), 202));
|
|
expect(created).toEqual([{ definition, run: run('A', 'pending') }]);
|
|
});
|
|
}
|
|
|
|
for (const boundary of ['definition', 'submission'] as const) {
|
|
test(`dialog unmount during ${boundary} ignores late completion and navigation`, async () => {
|
|
let navigated = false;
|
|
await mount(
|
|
createElement(CreateBacktestDialog, {
|
|
onClose: () => {},
|
|
onCreated: () => {
|
|
navigated = true;
|
|
},
|
|
})
|
|
);
|
|
await nameBacktest();
|
|
await flush(() => click('Save and run'));
|
|
if (boundary === 'submission') {
|
|
await flush(() => reply(request('/api/v2/backtests', 'POST'), definition));
|
|
}
|
|
await flush(() => root!.unmount());
|
|
root = undefined;
|
|
await flush(() =>
|
|
reply(
|
|
request(
|
|
boundary === 'definition' ? '/api/v2/backtests' : '/api/v2/backtests/definition/runs',
|
|
'POST'
|
|
),
|
|
boundary === 'definition' ? definition : run('A')
|
|
)
|
|
);
|
|
expect(navigated).toBe(false);
|
|
expect(requests.filter(item => item.method === 'POST')).toHaveLength(
|
|
boundary === 'definition' ? 1 : 2
|
|
);
|
|
});
|
|
}
|
|
|
|
test('closing cannot race the definition write and refresh a list before the row exists', async () => {
|
|
await mount(createElement(router.MemoryRouter, null, createElement(BacktestListPageV2)));
|
|
await flush(() => reply(request('/api/v2/backtests'), []));
|
|
await flush(() => click('New Backtest'));
|
|
await nameBacktest();
|
|
// The ref guard must work before the disabled state has rendered.
|
|
await flush(() => {
|
|
click('Save and run');
|
|
click('Close backtest dialog');
|
|
});
|
|
expect(host.querySelector('[aria-label="Close backtest dialog"]')).not.toBeNull();
|
|
expect(
|
|
requests.filter(item => item.path === '/api/v2/backtests' && item.method === 'GET')
|
|
).toHaveLength(1);
|
|
await flush(() => click('Close'));
|
|
expect(
|
|
requests.filter(item => item.path === '/api/v2/backtests' && item.method === 'GET')
|
|
).toHaveLength(1);
|
|
await flush(() => reply(request('/api/v2/backtests', 'POST'), definition));
|
|
const submitting = request('/api/v2/backtests/definition/runs', 'POST');
|
|
await flush(() => click('Close'));
|
|
await flush(() => reply(request('/api/v2/backtests'), [definition]));
|
|
await flush(() => reply(submitting, run('A', 'pending'), 202));
|
|
expect(host.textContent).toContain('Create and manage backtest configurations');
|
|
expect(host.querySelector('[aria-label="Close backtest dialog"]')).toBeNull();
|
|
});
|
|
|
|
test('closing saved-but-failed dialog reloads the real list without navigating', async () => {
|
|
await mount(createElement(router.MemoryRouter, null, createElement(BacktestListPageV2)));
|
|
await flush(() => reply(request('/api/v2/backtests'), []));
|
|
await flush(() => click('New Backtest'));
|
|
await nameBacktest();
|
|
await flush(() => click('Save and run'));
|
|
await flush(() => reply(request('/api/v2/backtests', 'POST'), definition));
|
|
await flush(() => fail(request('/api/v2/backtests/definition/runs', 'POST')));
|
|
await flush(() => click('Close'));
|
|
await flush(() => reply(request('/api/v2/backtests'), [definition]));
|
|
// Virtualized rows need real layout (W04). Here verify the refetch and that
|
|
// the real list, not a detail route, remains mounted after closing.
|
|
expect(
|
|
requests.filter(item => item.path === '/api/v2/backtests' && item.method === 'GET')
|
|
).toHaveLength(2);
|
|
expect(host.textContent).toContain('Create and manage backtest configurations');
|
|
expect(host.textContent).not.toContain('Retry submission');
|
|
});
|
|
|
|
for (const intent of ['Save', 'Save and run'] as const) {
|
|
test(`real list ${intent} navigates only after the requested operation succeeds`, async () => {
|
|
await mount(
|
|
createElement(
|
|
router.MemoryRouter,
|
|
{ initialEntries: ['/backtests'] },
|
|
createElement(
|
|
router.Routes,
|
|
null,
|
|
createElement(router.Route, {
|
|
path: '/backtests',
|
|
element: createElement(BacktestListPageV2),
|
|
}),
|
|
createElement(router.Route, {
|
|
path: '/backtests/:id',
|
|
element: createElement('p', null, 'Saved definition'),
|
|
}),
|
|
createElement(router.Route, {
|
|
path: '/backtests/:id/run/:runId',
|
|
element: createElement('p', null, 'Submitted run'),
|
|
})
|
|
),
|
|
createElement(LocationProbe)
|
|
)
|
|
);
|
|
await flush(() => reply(request('/api/v2/backtests'), []));
|
|
await flush(() => click('New Backtest'));
|
|
await nameBacktest();
|
|
await flush(() => click(intent));
|
|
expect(pageLocation).toBe('/backtests');
|
|
await flush(() => reply(request('/api/v2/backtests', 'POST'), definition));
|
|
if (intent === 'Save and run') {
|
|
expect(pageLocation).toBe('/backtests');
|
|
await flush(() =>
|
|
reply(request('/api/v2/backtests/definition/runs', 'POST'), run('A', 'pending'), 202)
|
|
);
|
|
}
|
|
expect(pageLocation).toBe(
|
|
`/backtests/definition${intent === 'Save and run' ? '/run/A' : ''}`
|
|
);
|
|
});
|
|
}
|
|
|
|
test('closing new-run confirmation prevents late successful submission from navigating', async () => {
|
|
await mountPage('failed');
|
|
await flush(() => click('Runs'));
|
|
await flush(() => click('New Run'));
|
|
await flush(() => click('Run current settings'));
|
|
const submitting = request('/api/v2/backtests/definition/runs', 'POST');
|
|
await flush(() => click('Cancel'));
|
|
await flush(() => reply(submitting, run('B', 'pending'), 202));
|
|
expect(pageLocation).toBe('/backtests/definition/run/A');
|
|
expect(host.textContent).not.toContain('Submit the current configuration');
|
|
});
|
|
|
|
test('changing the actual run route prevents late submission navigation', async () => {
|
|
await mountPage('failed');
|
|
await flush(() => click('Run current settings'));
|
|
const submitting = request('/api/v2/backtests/definition/runs', 'POST');
|
|
await flush(() => {
|
|
void navigatePage('/backtests/definition/run/B');
|
|
});
|
|
await flush(() => reply(request('/api/v2/runs/B'), run('B', 'failed')));
|
|
await flush(() => reply(submitting, run('C', 'pending'), 202));
|
|
expect(pageLocation).toBe('/backtests/definition/run/B');
|
|
expect(requests.some(item => item.path === '/api/v2/runs/C')).toBe(false);
|
|
});
|
|
|
|
test('submission errors remain visible after selecting another run and retry the same intent', async () => {
|
|
await mountPage('failed');
|
|
await flush(() => click('Run current settings'));
|
|
const submitting = request('/api/v2/backtests/definition/runs', 'POST');
|
|
await flush(() => {
|
|
void navigatePage('/backtests/definition/run/B');
|
|
});
|
|
await flush(() => reply(request('/api/v2/runs/B'), run('B', 'failed', { error: 'B failure' })));
|
|
await flush(() => fail(submitting));
|
|
expect(pageLocation).toBe('/backtests/definition/run/B');
|
|
expect(host.textContent).toContain('Run submission failed: Network unavailable');
|
|
expect(host.textContent).toContain('Run failed: B failure');
|
|
await flush(() => click('Retry submission'));
|
|
const retry = request('/api/v2/backtests/definition/runs', 'POST');
|
|
expect(retry.body).toBe(submitting.body);
|
|
expect(retry.headers.get('Idempotency-Key')).toBe(submitting.headers.get('Idempotency-Key'));
|
|
});
|
|
|
|
test('detail retries freeze payload/key across settings edits; acknowledged next intent has a fresh key', async () => {
|
|
await mount();
|
|
await loadDefinition();
|
|
await flush(() => {
|
|
void latest.createRun(2);
|
|
void latest.createRun(9);
|
|
});
|
|
const first = request('/api/v2/backtests/definition/runs', 'POST');
|
|
expect(requests.filter(item => item.method === 'POST')).toHaveLength(1);
|
|
expect(latest.isSubmitting).toBe(true);
|
|
await flush(() => fail(first));
|
|
expect(latest.submissionError).toContain('Network unavailable');
|
|
await flush(() => {
|
|
void latest.updateBacktest('definition', { initialCapital: 2000 });
|
|
});
|
|
await flush(() =>
|
|
reply(request('/api/v2/backtests/definition', 'PUT'), { ...definition, initialCapital: 2000 })
|
|
);
|
|
// A status reader may already have learned the run accepted before the lost response.
|
|
await selectRunning('A');
|
|
await flush(() => {
|
|
void latest.createRun(9);
|
|
});
|
|
const retry = request('/api/v2/backtests/definition/runs', 'POST');
|
|
expect(retry.body).toBe(first.body);
|
|
expect(retry.headers.get('Idempotency-Key')).toBe(first.headers.get('Idempotency-Key'));
|
|
await flush(() => reply(retry, run('A', 'pending'), 202));
|
|
expect(latest.runs.filter(item => item.id === 'A')).toHaveLength(1);
|
|
await flush(() => {
|
|
void latest.createRun(9);
|
|
});
|
|
const next = request('/api/v2/backtests/definition/runs', 'POST');
|
|
expect(next.headers.get('Idempotency-Key')).not.toBe(first.headers.get('Idempotency-Key'));
|
|
expect(JSON.parse(next.body!)).toEqual({ speedMultiplier: 9 });
|
|
await flush(() => reply(next, run('B', 'pending'), 202));
|
|
expect(latest.runs.map(item => item.id)).toEqual(['B', 'A']);
|
|
});
|
|
|
|
test('new-run form remains open and submission failure is visible alongside a polling failure', async () => {
|
|
await mountPage('running');
|
|
await advance(1000);
|
|
await flush(() => fail(request('/api/v2/runs/A')));
|
|
await flush(() => click('Runs'));
|
|
await flush(() => click('New Run'));
|
|
await flush(() => {
|
|
click('Run current settings');
|
|
click('Run current settings');
|
|
});
|
|
const first = request('/api/v2/backtests/definition/runs', 'POST');
|
|
expect(requests.filter(item => item.method === 'POST')).toHaveLength(1);
|
|
await flush(() => reply(first, { error: 'Submission unavailable' }, 503));
|
|
expect(host.textContent).toContain('Run submission failed');
|
|
expect(host.textContent).toContain('Network unavailable');
|
|
expect(host.textContent).toContain('Submit the current configuration');
|
|
await flush(() => click('Retry submission'));
|
|
const retry = request('/api/v2/backtests/definition/runs', 'POST');
|
|
expect(retry.headers.get('Idempotency-Key')).toBe(first.headers.get('Idempotency-Key'));
|
|
expect(retry.body).toBe(first.body);
|
|
});
|
|
|
|
for (const change of ['selection', 'backtest', 'unmount'] as const) {
|
|
test(`late submission completion cannot navigate or replace newer ${change}`, async () => {
|
|
await mount();
|
|
await loadDefinition();
|
|
let completed: Run | undefined;
|
|
await flush(() => {
|
|
void latest.createRun().then(value => {
|
|
completed = value;
|
|
});
|
|
});
|
|
const first = request('/api/v2/backtests/definition/runs', 'POST');
|
|
if (change === 'selection') {
|
|
await selectRunning('B');
|
|
} else if (change === 'backtest') {
|
|
await loadDefinition('other');
|
|
} else {
|
|
await flush(() => root!.unmount());
|
|
root = undefined;
|
|
}
|
|
const rendered = renders;
|
|
await flush(() => reply(first, run('A', 'pending'), 202));
|
|
expect(completed).toBeUndefined();
|
|
expect(latest.runs.some(item => item.id === 'A')).toBe(false);
|
|
if (change === 'selection') {
|
|
expect(latest.currentRun?.id).toBe('B');
|
|
} else if (change === 'backtest') {
|
|
expect(latest.backtest?.id).toBe('other');
|
|
} else {
|
|
expect(renders).toBe(rendered);
|
|
}
|
|
});
|
|
}
|
|
});
|