280 lines
13 KiB
TypeScript
280 lines
13 KiB
TypeScript
import { randomUUID } from 'node:crypto';
|
|
import { expect, test } from 'bun:test';
|
|
import type { Request } from 'playwright';
|
|
import { createInBrowser, fixture, gate, submitInBrowser, until, visible } from './fixture';
|
|
|
|
// Serial by design: the production WebSocket projection has a process-local handler.
|
|
test('browser_saved_run_lifecycle', async () => {
|
|
const f = await fixture();
|
|
try {
|
|
await f.login();
|
|
expect(await f.page.locator('tbody tr').count()).toBe(0);
|
|
await createInBrowser(f.page, 'Saved browser lifecycle');
|
|
const definition = (await f.pool.query('SELECT * FROM backtests')).rows[0];
|
|
expect(definition.name).toBe('Saved browser lifecycle');
|
|
expect(Number(definition.initial_capital)).toBe(100000);
|
|
expect((await f.pool.query('SELECT * FROM runs')).rowCount).toBe(0);
|
|
expect((await f.pool.query('SELECT * FROM backtest_dispatch')).rowCount).toBe(0);
|
|
await f.page.getByRole('button', { name: 'Settings', exact: true }).click();
|
|
expect(await f.page.locator('input[type="date"]').first().inputValue()).toBe('2024-01-01');
|
|
await f.page.getByRole('button', { name: 'Runs', exact: true }).click();
|
|
const response = await submitInBrowser(f.page);
|
|
expect(response.status()).toBe(202);
|
|
const run = await response.json();
|
|
expect(response.headers().location).toBe(`/api/v2/runs/${run.id}`);
|
|
expect(response.request().headers()['idempotency-key']).toBeTruthy();
|
|
await visible(f.page, 'Pending');
|
|
expect((await f.pool.query('SELECT * FROM runs')).rowCount).toBe(1);
|
|
expect((await f.pool.query('SELECT * FROM backtest_dispatch')).rowCount).toBe(1);
|
|
expect(await f.page.getByRole('button', { name: /pause|resume/i }).count()).toBe(0);
|
|
expect(await f.page.getByRole('combobox').count()).toBe(0);
|
|
f.dispatcher.start();
|
|
await visible(f.page, 'Running');
|
|
await visible(f.page, '25%');
|
|
await until(
|
|
() =>
|
|
f.frames.some(
|
|
frame =>
|
|
frame.runId === run.id && frame.type === 'progress' && frame.data?.progress === 25
|
|
),
|
|
'committed progress WebSocket frame'
|
|
);
|
|
expect(
|
|
Number(
|
|
(await f.pool.query('SELECT progress FROM runs WHERE id=$1', [run.id])).rows[0].progress
|
|
)
|
|
).toBe(25);
|
|
f.controlled.completion.resolve();
|
|
await visible(f.page, 'Completed');
|
|
await visible(f.page, 'Research only · Unverified economics');
|
|
await f.page
|
|
.getByText('Configuration, provenance and simulation limitations', { exact: true })
|
|
.click();
|
|
const result = await f.request(`/api/v2/runs/${run.id}/results`);
|
|
expect(result.config.dataset.hash).toMatch(/^[a-f0-9]{64}$/);
|
|
await visible(f.page, result.config.dataset.hash);
|
|
expect(await f.page.locator('pre').textContent()).toContain('"initialCapital": 100000');
|
|
await f.page.getByRole('button', { name: 'Trades', exact: true }).click();
|
|
await visible(f.page, 'BUY');
|
|
await visible(f.page, '$100.00');
|
|
const savedUrl = f.page.url();
|
|
await f.page.reload();
|
|
await visible(f.page, 'Completed');
|
|
expect(f.page.url()).toBe(savedUrl);
|
|
await f.page.getByRole('button', { name: 'Trades', exact: true }).click();
|
|
await visible(f.page, 'BUY');
|
|
await f.page.getByRole('button', { name: 'Back to backtests', exact: true }).click();
|
|
await f.page.getByText('Saved browser lifecycle', { exact: true }).click();
|
|
await f.page.getByText('#1', { exact: true }).click();
|
|
await visible(f.page, 'Completed');
|
|
expect(f.page.url()).toBe(savedUrl);
|
|
expect(
|
|
(await f.pool.query('SELECT * FROM backtest_results WHERE run_id=$1', [run.id])).rowCount
|
|
).toBe(1);
|
|
expect((await f.pool.query('SELECT count(*) FROM backtest_datasets')).rows[0].count).toBe('1');
|
|
expect(f.unexpectedNetwork).toEqual([]);
|
|
} finally {
|
|
await f.close();
|
|
}
|
|
});
|
|
|
|
test('browser_cancel_failure', async () => {
|
|
const f = await fixture();
|
|
try {
|
|
await f.login();
|
|
await createInBrowser(f.page, 'Cancel browser run', true);
|
|
const runId = f.page.url().split('/').at(-1)!;
|
|
f.dispatcher.start();
|
|
await visible(f.page, 'Running');
|
|
const acknowledged = f.page.waitForResponse(response =>
|
|
response.url().endsWith(`/runs/${runId}/cancel`)
|
|
);
|
|
await f.page.getByRole('button', { name: 'Cancel run', exact: true }).click();
|
|
expect((await acknowledged).status()).toBe(202);
|
|
await visible(f.page, 'Cancellation requested. Waiting for the worker to stop.');
|
|
expect(
|
|
await f.page.getByRole('button', { name: 'Cancellation requested', exact: true }).isDisabled()
|
|
).toBe(true);
|
|
await f.controlled.stopped.wait('worker cancellation observation');
|
|
expect(
|
|
(await f.pool.query('SELECT status,cancel_requested FROM runs WHERE id=$1', [runId])).rows[0]
|
|
).toEqual({ status: 'running', cancel_requested: true });
|
|
f.controlled.cancellation.resolve();
|
|
await visible(f.page, 'Run cancelled. No completed results are available.');
|
|
expect(
|
|
(await f.pool.query('SELECT * FROM backtest_results WHERE run_id=$1', [runId])).rowCount
|
|
).toBe(0);
|
|
f.controlled.mode = 'fail';
|
|
await f.page.getByRole('button', { name: 'Back to backtests', exact: true }).click();
|
|
await createInBrowser(f.page, 'Failed browser run', true);
|
|
await visible(f.page, 'Run failed: Injected fixture worker failure');
|
|
const failedId = f.page.url().split('/').at(-1)!;
|
|
expect(
|
|
(await f.pool.query('SELECT status,error FROM runs WHERE id=$1', [failedId])).rows[0]
|
|
).toEqual({ status: 'failed', error: 'Injected fixture worker failure' });
|
|
expect(
|
|
(await f.pool.query('SELECT * FROM backtest_results WHERE run_id=$1', [failedId])).rowCount
|
|
).toBe(0);
|
|
f.controlled.mode = 'empty';
|
|
await f.page.getByRole('button', { name: 'Back to backtests', exact: true }).click();
|
|
await createInBrowser(f.page, 'Empty completed browser run', true);
|
|
await visible(f.page, 'Completed');
|
|
await f.page.getByRole('button', { name: 'Trades', exact: true }).click();
|
|
await visible(f.page, 'No trades executed in this backtest.');
|
|
const emptyId = f.page.url().split('/').at(-1)!;
|
|
expect((await f.request(`/api/v2/runs/${emptyId}/results`)).trades).toEqual([]);
|
|
// A saved completed row whose result is unavailable must not appear as zero trades.
|
|
await f.pool.query('DELETE FROM backtest_results WHERE run_id=$1', [emptyId]);
|
|
await f.page.reload();
|
|
await visible(f.page, 'Run completed, but saved results are unavailable.');
|
|
await visible(f.page, 'Retry results');
|
|
expect(
|
|
await f.page.getByText('No trades executed in this backtest.', { exact: true }).count()
|
|
).toBe(0);
|
|
expect(f.unexpectedNetwork).toEqual([]);
|
|
} finally {
|
|
await f.close();
|
|
}
|
|
});
|
|
|
|
test('browser_reopen_and_switch', async () => {
|
|
const f = await fixture();
|
|
let delayed: ReturnType<typeof f.delayResponse> | undefined;
|
|
const settledRequests = new WeakSet<Request>();
|
|
const settled = (request: Request) => {
|
|
settledRequests.add(request);
|
|
};
|
|
f.page.on('requestfinished', settled);
|
|
f.page.on('requestfailed', settled);
|
|
try {
|
|
await f.login();
|
|
await createInBrowser(f.page, 'Selection and reconnect', true);
|
|
const firstUrl = f.page.url();
|
|
const firstId = firstUrl.split('/').at(-1)!;
|
|
const definitionId = firstUrl.split('/')[4]!;
|
|
f.dispatcher.start();
|
|
await visible(f.page, '25%');
|
|
await until(
|
|
() => f.frames.some(frame => frame.type === 'connected' && frame.runId === firstId),
|
|
'initial real WebSocket connection'
|
|
);
|
|
// Close the actual client socket, then observe an authenticated reconnect and projection.
|
|
// Bun 1.2.17 leaks its pending-WebSocket counter on server-initiated close; client close
|
|
// exercises the real hook without leaving the fixture listener unable to shut down.
|
|
const connections = f.frames.filter(frame => frame.type === 'connected').length;
|
|
const reconnectIndex = f.frames.length;
|
|
await f.page.evaluate(() =>
|
|
(window as unknown as { __disconnectFixtureSockets: () => void }).__disconnectFixtureSockets()
|
|
);
|
|
await until(
|
|
() => f.frames.filter(frame => frame.type === 'connected').length > connections,
|
|
'WebSocket reconnect',
|
|
15000
|
|
);
|
|
await until(
|
|
() =>
|
|
f.frames
|
|
.slice(reconnectIndex)
|
|
.some(
|
|
frame =>
|
|
frame.runId === firstId && frame.type === 'progress' && frame.data?.progress === 25
|
|
),
|
|
'reconnected persisted progress'
|
|
);
|
|
f.controlled.completion.resolve();
|
|
await visible(f.page, 'Completed');
|
|
f.controlled.completion = gate();
|
|
await f.page.getByRole('button', { name: 'Runs', exact: true }).click();
|
|
await submitInBrowser(f.page);
|
|
const secondUrl = f.page.url();
|
|
const secondId = secondUrl.split('/').at(-1)!;
|
|
expect(secondId).not.toBe(firstId);
|
|
await until(
|
|
() => f.frames.some(frame => frame.type === 'connected' && frame.runId === secondId),
|
|
'second run subscription'
|
|
);
|
|
f.controlled.completion.resolve();
|
|
await visible(f.page, 'Completed');
|
|
await f.page.getByRole('button', { name: 'Runs', exact: true }).click();
|
|
await visible(f.page, '#1');
|
|
delayed = f.delayResponse(`/api/v2/runs/${firstId}/results`);
|
|
const selectionRequest = f.page.waitForRequest(
|
|
request => new URL(request.url()).pathname === `/api/v2/runs/${firstId}/results`
|
|
);
|
|
await f.page.getByText('#1', { exact: true }).click();
|
|
const requested = await selectionRequest;
|
|
await delayed.captured.wait('selected run A result request');
|
|
await visible(f.page, 'Loading run data...');
|
|
await f.page.getByRole('button', { name: 'Runs', exact: true }).click();
|
|
await f.page.getByText('#2', { exact: true }).click();
|
|
await visible(f.page, 'Completed');
|
|
delayed.release.resolve();
|
|
await delayed.delivered.wait('delayed result response settlement');
|
|
await until(
|
|
() => settledRequests.has(requested),
|
|
'browser finished or aborted the old result request'
|
|
);
|
|
await f.page.evaluate(
|
|
() => new Promise(resolve => requestAnimationFrame(() => requestAnimationFrame(resolve)))
|
|
);
|
|
await f.page
|
|
.getByText('Configuration, provenance and simulation limitations', { exact: true })
|
|
.click();
|
|
await visible(f.page, secondId);
|
|
expect(f.page.url()).toBe(secondUrl);
|
|
expect(await f.page.getByText(firstId, { exact: true }).count()).toBe(0);
|
|
// A real missing row, not an invented empty result.
|
|
await f.page.goto(`${f.origin}/backtests/${definitionId}/run/${randomUUID()}`);
|
|
await visible(f.page, 'Failed to get run: Not Found');
|
|
await visible(f.page, 'Retry run');
|
|
// Transport failure has a visible retry; restoring the real endpoint recovers.
|
|
await f.page.route(`**/api/v2/runs/${secondId}`, route => route.abort('failed'));
|
|
await f.page.goto(secondUrl);
|
|
await visible(f.page, /Failed to fetch|Load failed/);
|
|
await f.page.unroute(`**/api/v2/runs/${secondId}`);
|
|
await f.page.getByRole('button', { name: 'Retry run', exact: true }).click();
|
|
await visible(f.page, 'Completed');
|
|
expect(f.page.url()).toBe(secondUrl);
|
|
expect(f.unexpectedNetwork).toEqual([]);
|
|
} finally {
|
|
f.page.off('requestfinished', settled);
|
|
f.page.off('requestfailed', settled);
|
|
delayed?.release.resolve();
|
|
await f.close();
|
|
}
|
|
});
|
|
|
|
test('native_smoke', async () => {
|
|
const f = await fixture(true);
|
|
try {
|
|
await f.login();
|
|
await createInBrowser(f.page, 'Actual Rust browser smoke', true);
|
|
const runId = f.page.url().split('/').at(-1)!;
|
|
f.dispatcher.start();
|
|
await visible(f.page, 'Completed');
|
|
const result = await f.request(`/api/v2/runs/${runId}/results`);
|
|
expect(result.engine).toBe('native');
|
|
expect(result.config.dataset.barCount).toBe(70);
|
|
expect(result.config.dataset.hash).toMatch(/^[a-f0-9]{64}$/);
|
|
expect(result.trades.length).toBeGreaterThan(0);
|
|
expect(
|
|
(await f.pool.query('SELECT status,attempt_number FROM runs WHERE id=$1', [runId])).rows[0]
|
|
).toEqual({ status: 'completed', attempt_number: 1 });
|
|
expect(
|
|
(await f.pool.query('SELECT * FROM backtest_dispatch WHERE run_id=$1', [runId])).rowCount
|
|
).toBe(1);
|
|
await visible(f.page, 'Research only · Unverified economics');
|
|
await f.page.getByRole('button', { name: 'Trades', exact: true }).click();
|
|
await visible(f.page, result.trades[0].side.toUpperCase());
|
|
await visible(f.page, `$${result.trades[0].price.toFixed(2)}`);
|
|
await f.page.reload();
|
|
await visible(f.page, 'Completed');
|
|
await f.page
|
|
.getByText('Configuration, provenance and simulation limitations', { exact: true })
|
|
.click();
|
|
await visible(f.page, result.config.dataset.hash);
|
|
expect(f.unexpectedNetwork).toEqual([]);
|
|
} finally {
|
|
await f.close();
|
|
}
|
|
});
|