test(backtests): verify durable workbench in Chromium
This commit is contained in:
parent
95842c39d0
commit
550d8b769b
5 changed files with 900 additions and 4 deletions
563
test/e2e/fixture.ts
Normal file
563
test/e2e/fixture.ts
Normal file
|
|
@ -0,0 +1,563 @@
|
|||
import { randomUUID } from 'node:crypto';
|
||||
import { EventEmitter } from 'node:events';
|
||||
import { readFileSync } from 'node:fs';
|
||||
import type { ServerWebSocket } from 'bun';
|
||||
import { Pool } from 'pg';
|
||||
import { chromium, type Page } from 'playwright';
|
||||
import { createHttpSecurity } from '@stock-bot/di';
|
||||
import { HandlerRegistry } from '@stock-bot/handler-registry';
|
||||
import type { IServiceContainer } from '@stock-bot/handlers';
|
||||
import { getLogger, setLoggerConfig } from '@stock-bot/logger';
|
||||
import { PostgreSQLClient } from '@stock-bot/postgres';
|
||||
import { Queue } from '@stock-bot/queue';
|
||||
import { BacktestRunner } from '../../apps/stock/orchestrator/src/backtest/BacktestRunner';
|
||||
import { BacktestCancelledError } from '../../apps/stock/orchestrator/src/backtest/execution-engine';
|
||||
import type { NativeBacktestResult } from '../../apps/stock/orchestrator/src/backtest/native-result';
|
||||
import { PostgresBacktestRunRepository } from '../../apps/stock/orchestrator/src/backtest/PostgresBacktestRunRepository';
|
||||
import { RustBacktestAdapter } from '../../apps/stock/orchestrator/src/backtest/RustBacktestAdapter';
|
||||
import {
|
||||
loadDataset,
|
||||
type DatasetResolver,
|
||||
} from '../../apps/stock/orchestrator/src/data/historical-dataset';
|
||||
import type { StorageService } from '../../apps/stock/orchestrator/src/services/StorageService';
|
||||
import type { BacktestConfig } from '../../apps/stock/orchestrator/src/types';
|
||||
import { createRoutes } from '../../apps/stock/web-api/src/routes/create-routes';
|
||||
import {
|
||||
createWebSocketRoute,
|
||||
handleWebSocketConnection,
|
||||
} from '../../apps/stock/web-api/src/routes/websocket.routes';
|
||||
import { BacktestDispatcher } from '../../apps/stock/web-api/src/services/BacktestDispatcher';
|
||||
import {
|
||||
getWebSocketHandler,
|
||||
type RunSocketData,
|
||||
} from '../../apps/stock/web-api/src/websocket/run-updates';
|
||||
|
||||
setLoggerConfig({ logLevel: 'fatal', logConsole: false });
|
||||
const logger = getLogger('browser-fixture');
|
||||
export function gate() {
|
||||
let resolve!: () => void;
|
||||
const promise = new Promise<void>(done => {
|
||||
resolve = done;
|
||||
});
|
||||
return {
|
||||
promise,
|
||||
resolve,
|
||||
async wait(label: string) {
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
try {
|
||||
await Promise.race([
|
||||
promise,
|
||||
new Promise<never>((_, reject) => {
|
||||
timer = setTimeout(() => reject(new Error(`Timed out waiting for ${label}`)), 10000);
|
||||
}),
|
||||
]);
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
},
|
||||
};
|
||||
}
|
||||
export async function until(
|
||||
check: () => Promise<boolean> | boolean,
|
||||
label: string,
|
||||
timeout = 10000
|
||||
) {
|
||||
const deadline = Date.now() + timeout;
|
||||
while (Date.now() < deadline) {
|
||||
if (await check()) {
|
||||
return;
|
||||
}
|
||||
await Bun.sleep(25);
|
||||
}
|
||||
throw new Error(`Timed out waiting for ${label}`);
|
||||
}
|
||||
export async function visible(page: Page, text: string | RegExp) {
|
||||
try {
|
||||
await page
|
||||
.getByText(text, { exact: typeof text === 'string' })
|
||||
.first()
|
||||
.waitFor({ state: 'visible' });
|
||||
} catch (error) {
|
||||
throw new Error(`Expected visible ${text}; page: ${await page.locator('body').innerText()}`, {
|
||||
cause: error,
|
||||
});
|
||||
}
|
||||
}
|
||||
|
||||
const storage: Pick<StorageService, 'getHistoricalBars'> = {
|
||||
async getHistoricalBars(symbol, startDate, endDate) {
|
||||
const length = Math.min(70, Math.ceil((endDate.getTime() - startDate.getTime()) / 86400000));
|
||||
return Array.from({ length }, (_, index) => {
|
||||
const close = 100 + Math.sin((index * Math.PI) / 6) * 8;
|
||||
return {
|
||||
symbol,
|
||||
source: 'eod' as const,
|
||||
timestamp: new Date(startDate.getTime() + index * 86400000),
|
||||
open: close,
|
||||
high: close + 1,
|
||||
low: close - 1,
|
||||
close,
|
||||
volume: 1000000,
|
||||
};
|
||||
});
|
||||
},
|
||||
};
|
||||
|
||||
/** Fixed UI lifecycle data, NOT a financial simulator or correctness oracle. */
|
||||
class FixtureEngine extends EventEmitter {
|
||||
completion = gate();
|
||||
cancellation = gate();
|
||||
stopped = gate();
|
||||
mode: 'trades' | 'empty' | 'fail' = 'trades';
|
||||
private cancelled = false;
|
||||
async runBacktest(
|
||||
config: BacktestConfig,
|
||||
resolver?: DatasetResolver
|
||||
): Promise<NativeBacktestResult> {
|
||||
if (!resolver) {
|
||||
throw new Error('Fixture must exercise durable dataset resolution');
|
||||
}
|
||||
const dataset = await resolver(() => loadDataset(storage, config));
|
||||
this.cancelled = false;
|
||||
this.emit('progress', { progress: 25, currentDate: config.startDate });
|
||||
await this.completion.promise;
|
||||
if (this.cancelled) {
|
||||
throw new BacktestCancelledError();
|
||||
}
|
||||
if (this.mode === 'fail') {
|
||||
throw new Error('Injected fixture worker failure');
|
||||
}
|
||||
return {
|
||||
backtestId: config.backtestId!,
|
||||
status: 'completed',
|
||||
completedAt: '2024-03-15T00:00:00.000Z',
|
||||
config: {
|
||||
name: config.name!,
|
||||
symbols: config.symbols,
|
||||
startDate: config.startDate,
|
||||
endDate: config.endDate,
|
||||
initialCapital: config.initialCapital,
|
||||
},
|
||||
metrics: {
|
||||
totalReturn: 0,
|
||||
sharpeRatio: 0,
|
||||
maxDrawdown: 0,
|
||||
winRate: 0,
|
||||
totalTrades: 0,
|
||||
profitFactor: null,
|
||||
avgWin: 0,
|
||||
avgLoss: 0,
|
||||
},
|
||||
equity: [{ date: config.startDate, value: config.initialCapital }],
|
||||
trades:
|
||||
this.mode === 'empty'
|
||||
? []
|
||||
: [
|
||||
{
|
||||
id: 'fixture-fill',
|
||||
symbol: config.symbols[0]!,
|
||||
timestamp: config.startDate,
|
||||
side: 'buy',
|
||||
price: 100,
|
||||
quantity: 3,
|
||||
commission: 0,
|
||||
positionAfter: 3,
|
||||
},
|
||||
],
|
||||
positions: [],
|
||||
analytics: { exposureTime: 0 },
|
||||
executionTime: 0,
|
||||
ohlcData: Object.fromEntries(
|
||||
config.symbols.map(symbol => [symbol, dataset.bars.filter(bar => bar.symbol === symbol)])
|
||||
),
|
||||
};
|
||||
}
|
||||
async stopBacktest() {
|
||||
this.cancelled = true;
|
||||
this.stopped.resolve();
|
||||
await this.cancellation.promise;
|
||||
this.completion.resolve();
|
||||
}
|
||||
async pauseBacktest() {
|
||||
throw new Error('Unsupported fixture control');
|
||||
}
|
||||
async resumeBacktest() {
|
||||
throw new Error('Unsupported fixture control');
|
||||
}
|
||||
setSpeedMultiplier() {}
|
||||
getStatus() {
|
||||
return { isRunning: true, isPaused: false, progress: 25, currentTime: 0 };
|
||||
}
|
||||
async shutdown() {
|
||||
this.cancellation.resolve();
|
||||
this.completion.resolve();
|
||||
}
|
||||
}
|
||||
|
||||
export async function fixture(native = false) {
|
||||
const database = process.env.PIPELINE_TEST_DATABASE_URL;
|
||||
const redisUrl = process.env.BACKTEST_TEST_REDIS_URL;
|
||||
if (
|
||||
!database ||
|
||||
!new URL(database).pathname.startsWith('/stock_bot_safety') ||
|
||||
!redisUrl ||
|
||||
new URL(redisUrl).pathname !== '/15'
|
||||
) {
|
||||
throw new Error('Disposable stock_bot_safety PostgreSQL and dedicated Redis DB15 are required');
|
||||
}
|
||||
if (process.env.STOCK_BOT_E2E_BUILT !== '1') {
|
||||
throw new Error('Run bun run test:e2e (builds same-origin UI first)');
|
||||
}
|
||||
const cleanup: (() => Promise<unknown>)[] = [];
|
||||
const close = async () => {
|
||||
const errors = [];
|
||||
for (const dispose of cleanup.splice(0).reverse()) {
|
||||
let timer: ReturnType<typeof setTimeout> | undefined;
|
||||
try {
|
||||
await Promise.race([
|
||||
dispose(),
|
||||
new Promise<never>((_, reject) => {
|
||||
timer = setTimeout(
|
||||
() =>
|
||||
reject(
|
||||
new Error(
|
||||
`Fixture cleanup deadline exceeded: ${dispose.toString().slice(0, 150)}`
|
||||
)
|
||||
),
|
||||
5000
|
||||
);
|
||||
}),
|
||||
]);
|
||||
} catch (error) {
|
||||
errors.push(error);
|
||||
} finally {
|
||||
clearTimeout(timer);
|
||||
}
|
||||
}
|
||||
if (errors.length) {
|
||||
throw new AggregateError(errors, 'Browser fixture cleanup failed');
|
||||
}
|
||||
};
|
||||
try {
|
||||
const schema = `stock_bot_safety_browser_${randomUUID().replaceAll('-', '')}`;
|
||||
const admin = new Pool({ connectionString: database, connectionTimeoutMillis: 5000 });
|
||||
cleanup.push(() => admin.end());
|
||||
await admin.query(`CREATE SCHEMA ${schema}`);
|
||||
cleanup.push(() => admin.query(`DROP SCHEMA ${schema} CASCADE`));
|
||||
const pool = new Pool({
|
||||
connectionString: database,
|
||||
options: `-c search_path=${schema}`,
|
||||
connectionTimeoutMillis: 5000,
|
||||
});
|
||||
cleanup.push(() => pool.end());
|
||||
await pool.query(`CREATE TYPE run_status AS ENUM ('pending','running','completed','failed','cancelled','paused');
|
||||
CREATE TABLE backtests (id uuid PRIMARY KEY, name text NOT NULL, strategy text NOT NULL, symbols jsonb NOT NULL,
|
||||
start_date timestamptz NOT NULL, end_date timestamptz NOT NULL, initial_capital numeric NOT NULL, config jsonb,
|
||||
created_at timestamptz DEFAULT NOW(), updated_at timestamptz DEFAULT NOW());
|
||||
CREATE TABLE runs (id uuid PRIMARY KEY, backtest_id uuid REFERENCES backtests(id) ON DELETE CASCADE, run_number integer,
|
||||
status run_status DEFAULT 'pending', speed_multiplier numeric, progress numeric DEFAULT 0, error text,
|
||||
started_at timestamptz, completed_at timestamptz, paused_at timestamptz, current_simulation_date timestamptz,
|
||||
created_at timestamptz DEFAULT NOW(), updated_at timestamptz DEFAULT NOW(), UNIQUE(backtest_id, run_number));
|
||||
CREATE TABLE backtest_results (run_id uuid REFERENCES runs(id) ON DELETE CASCADE, completed_at timestamptz,
|
||||
metrics jsonb, equity_curve jsonb, ohlc_data jsonb, trades jsonb, positions jsonb, analytics jsonb, execution_time numeric);`);
|
||||
for (const name of [
|
||||
'09-backtest-run-contract.sql',
|
||||
'10-durable-backtest-dispatch.sql',
|
||||
'12-historical-datasets.sql',
|
||||
'14-backtest-submission.sql',
|
||||
]) {
|
||||
await pool.query(
|
||||
readFileSync(new URL(`../../database/postgres/init/${name}`, import.meta.url), 'utf8')
|
||||
);
|
||||
}
|
||||
const postgres = new PostgreSQLClient(
|
||||
{ host: 'unused', port: 5432, database: 'unused', username: 'unused', password: 'unused' },
|
||||
logger
|
||||
);
|
||||
Object.defineProperty(postgres, 'connectionPool', { get: () => pool });
|
||||
Object.defineProperty(postgres, 'query', { value: pool.query.bind(pool) });
|
||||
const redisEndpoint = new URL(redisUrl);
|
||||
const redis = {
|
||||
host: redisEndpoint.hostname,
|
||||
port: Number(redisEndpoint.port || 6379),
|
||||
db: 15,
|
||||
...(redisEndpoint.password ? { password: decodeURIComponent(redisEndpoint.password) } : {}),
|
||||
};
|
||||
const queueName = `stock-bot-safety-browser-${randomUUID()}`;
|
||||
const queue = new Queue(queueName, redis, {}, { workers: 0 }, logger);
|
||||
cleanup.push(async () => {
|
||||
try {
|
||||
await queue.getBullQueue().obliterate({ force: true });
|
||||
} finally {
|
||||
await queue.close();
|
||||
}
|
||||
});
|
||||
const ready = gate();
|
||||
const readiness = queue.getBullQueue().waitUntilReady();
|
||||
// Propagate a real connection failure, or a bounded diagnostic for an unavailable fixture.
|
||||
try {
|
||||
await Promise.race([readiness, ready.wait('dedicated browser Redis readiness')]);
|
||||
} finally {
|
||||
ready.resolve();
|
||||
}
|
||||
const dispatcher = new BacktestDispatcher(postgres, queue, logger, {
|
||||
intervalMs: 20,
|
||||
republishMs: 100,
|
||||
maxAttempts: 3,
|
||||
});
|
||||
const controlled = new FixtureEngine();
|
||||
const engine = native
|
||||
? new RustBacktestAdapter({ logger, storage }, { timeoutMs: 15000 })
|
||||
: controlled;
|
||||
const runner = new BacktestRunner({
|
||||
engine,
|
||||
engineName: 'native',
|
||||
repository: new PostgresBacktestRunRepository(postgres, 2000),
|
||||
logger,
|
||||
heartbeatMs: 50,
|
||||
});
|
||||
const registry = new HandlerRegistry();
|
||||
registry.registerConfiguration({
|
||||
name: 'orchestrator',
|
||||
operations: {
|
||||
'run-backtest': payload => runner.runQueued((payload as { runId: string }).runId),
|
||||
},
|
||||
});
|
||||
const worker = new Queue(
|
||||
queueName,
|
||||
redis,
|
||||
{},
|
||||
{ workers: 1, concurrency: 1, handlerRegistry: registry },
|
||||
logger
|
||||
);
|
||||
cleanup.push(async () => {
|
||||
controlled.cancellation.resolve();
|
||||
controlled.completion.resolve();
|
||||
try {
|
||||
await runner.shutdown();
|
||||
} finally {
|
||||
await worker.close();
|
||||
}
|
||||
});
|
||||
cleanup.push(() => dispatcher.shutdown());
|
||||
const container = { postgres, logger } as IServiceContainer;
|
||||
const token = randomUUID() + randomUUID();
|
||||
const security = createHttpSecurity({
|
||||
adminToken: token,
|
||||
serviceToken: randomUUID() + randomUUID(),
|
||||
browserSessions: true,
|
||||
environment: 'test',
|
||||
origins: [],
|
||||
});
|
||||
const routes = createRoutes(container, security);
|
||||
const wsRoute = createWebSocketRoute(container, security);
|
||||
const sockets = new Set<ServerWebSocket<RunSocketData>>();
|
||||
const unexpectedNetwork: string[] = [];
|
||||
let responseDelay:
|
||||
| {
|
||||
path: string;
|
||||
captured: ReturnType<typeof gate>;
|
||||
release: ReturnType<typeof gate>;
|
||||
delivered: ReturnType<typeof gate>;
|
||||
}
|
||||
| undefined;
|
||||
const delayResponse = (path: string) => {
|
||||
responseDelay = { path, captured: gate(), release: gate(), delivered: gate() };
|
||||
return responseDelay;
|
||||
};
|
||||
const server = Bun.serve<RunSocketData, {}>({
|
||||
hostname: '127.0.0.1',
|
||||
port: 0,
|
||||
async fetch(request, server) {
|
||||
const pathname = new URL(request.url).pathname;
|
||||
if (pathname === '/ws' && request.headers.get('upgrade') === 'websocket') {
|
||||
return wsRoute(request, server);
|
||||
}
|
||||
if (pathname.startsWith('/api/')) {
|
||||
if (
|
||||
(!pathname.startsWith('/api/v2/backtests') &&
|
||||
!pathname.startsWith('/api/v2/runs') &&
|
||||
pathname !== '/api/auth/session') ||
|
||||
/\/(pause|resume|speed)$/.test(pathname)
|
||||
) {
|
||||
unexpectedNetwork.push(pathname);
|
||||
return new Response('Endpoint outside browser fixture scope', { status: 403 });
|
||||
}
|
||||
const response = await routes.fetch(request);
|
||||
const delay = responseDelay;
|
||||
if (delay?.path === pathname) {
|
||||
responseDelay = undefined; // Only the selected read, not run-list metric reads.
|
||||
delay.captured.resolve();
|
||||
await delay.release.promise;
|
||||
delay.delivered.resolve();
|
||||
}
|
||||
return response;
|
||||
}
|
||||
if (pathname.startsWith('/assets/') && !pathname.includes('..')) {
|
||||
const file = Bun.file(
|
||||
new URL(`../../apps/stock/web-app/dist${pathname}`, import.meta.url)
|
||||
);
|
||||
return (await file.exists())
|
||||
? new Response(file)
|
||||
: new Response('Not found', { status: 404 });
|
||||
}
|
||||
return new Response(
|
||||
Bun.file(new URL('../../apps/stock/web-app/dist/index.html', import.meta.url))
|
||||
);
|
||||
},
|
||||
websocket: {
|
||||
open(socket) {
|
||||
sockets.add(socket);
|
||||
handleWebSocketConnection(socket);
|
||||
},
|
||||
message(socket, message) {
|
||||
getWebSocketHandler()?.handleMessage(socket, message);
|
||||
},
|
||||
close(socket) {
|
||||
sockets.delete(socket);
|
||||
getWebSocketHandler()?.handleClose(socket);
|
||||
},
|
||||
},
|
||||
});
|
||||
cleanup.push(async () => {
|
||||
getWebSocketHandler()?.cleanup();
|
||||
const report = setTimeout(
|
||||
() =>
|
||||
process.stderr.write(
|
||||
`browser server stop pending: requests=${server.pendingRequests} websockets=${server.pendingWebSockets} sockets=${sockets.size}\n`
|
||||
),
|
||||
4000
|
||||
);
|
||||
server.unref();
|
||||
try {
|
||||
await server.stop(true);
|
||||
} finally {
|
||||
clearTimeout(report);
|
||||
}
|
||||
});
|
||||
const origin = `http://127.0.0.1:${server.port}`;
|
||||
const browser = await chromium.launch({ headless: true });
|
||||
cleanup.push(() => browser.close());
|
||||
const context = await browser.newContext({ viewport: { width: 1440, height: 1080 } });
|
||||
await context.route('**/*', route => {
|
||||
const url = new URL(route.request().url());
|
||||
if (url.origin !== origin && !['data:', 'blob:'].includes(url.protocol)) {
|
||||
// Existing font imports remain offline; never permit external egress.
|
||||
if (
|
||||
!(
|
||||
route.request().resourceType() === 'stylesheet' &&
|
||||
url.origin === 'https://fonts.googleapis.com' &&
|
||||
url.pathname === '/css2' &&
|
||||
/^(Inter|JetBrains Mono):/.test(url.searchParams.get('family') ?? '')
|
||||
)
|
||||
) {
|
||||
unexpectedNetwork.push(url.origin);
|
||||
}
|
||||
return route.abort('blockedbyclient');
|
||||
}
|
||||
return route.continue();
|
||||
});
|
||||
// The HTTP interception API does not intercept WebSocket handshakes.
|
||||
await context.addInitScript(expectedOrigin => {
|
||||
const Original = window.WebSocket;
|
||||
const connections = new Set<WebSocket>();
|
||||
Object.defineProperty(window, '__disconnectFixtureSockets', {
|
||||
value: () => {
|
||||
for (const connection of connections) {
|
||||
connection.close();
|
||||
}
|
||||
},
|
||||
});
|
||||
window.WebSocket = class extends Original {
|
||||
constructor(url: string | URL, protocols?: string | string[]) {
|
||||
const endpoint = new URL(url, window.location.href);
|
||||
if (endpoint.origin !== expectedOrigin.replace(/^http/, 'ws')) {
|
||||
throw new Error('External fixture WebSocket blocked');
|
||||
}
|
||||
super(url, protocols);
|
||||
connections.add(this);
|
||||
this.addEventListener('close', () => connections.delete(this));
|
||||
}
|
||||
};
|
||||
}, origin);
|
||||
const page = await context.newPage();
|
||||
page.setDefaultTimeout(10000);
|
||||
const frames: { type: string; runId: string; data?: { progress?: number } }[] = [];
|
||||
page.on('websocket', socket =>
|
||||
socket.on('framereceived', frame => {
|
||||
try {
|
||||
frames.push(JSON.parse(frame.payload.toString()));
|
||||
} catch {
|
||||
/* Non-JSON cannot satisfy assertions. */
|
||||
}
|
||||
})
|
||||
);
|
||||
const login = async (target: Page = page) => {
|
||||
await target.goto(`${origin}/backtests`);
|
||||
await target.getByLabel('Access token').fill(token);
|
||||
await target.getByRole('button', { name: 'Sign in', exact: true }).click();
|
||||
await visible(target, 'Create and manage backtest configurations');
|
||||
};
|
||||
const request = async (path: string, method = 'GET', body?: unknown) => {
|
||||
const response = await fetch(origin + path, {
|
||||
method,
|
||||
headers: { Authorization: `Bearer ${token}`, 'Content-Type': 'application/json' },
|
||||
body: body === undefined ? undefined : JSON.stringify(body),
|
||||
});
|
||||
if (!response.ok) {
|
||||
throw new Error(
|
||||
`Fixture API ${method} ${path}: ${response.status} ${await response.text()}`
|
||||
);
|
||||
}
|
||||
return response.json();
|
||||
};
|
||||
return {
|
||||
pool,
|
||||
page,
|
||||
context,
|
||||
origin,
|
||||
frames,
|
||||
delayResponse,
|
||||
controlled,
|
||||
dispatcher,
|
||||
request,
|
||||
login,
|
||||
close,
|
||||
unexpectedNetwork,
|
||||
};
|
||||
} catch (error) {
|
||||
try {
|
||||
await close();
|
||||
} catch (cleanupError) {
|
||||
throw new AggregateError([error, cleanupError], 'Browser fixture startup and cleanup failed');
|
||||
}
|
||||
throw error;
|
||||
}
|
||||
}
|
||||
|
||||
export async function createInBrowser(page: Page, name: string, run = false) {
|
||||
await page.getByRole('button', { name: 'New Backtest', exact: true }).click();
|
||||
await page.getByPlaceholder('My Strategy Backtest').fill(name);
|
||||
await page.locator('select').first().selectOption('moving-average');
|
||||
await page.locator('input[type="date"]').nth(0).fill('2024-01-01');
|
||||
await page.locator('input[type="date"]').nth(1).fill('2024-03-15');
|
||||
await page.getByRole('button', { name: run ? 'Save and run' : 'Save', exact: true }).click();
|
||||
await page.waitForURL(run ? /\/backtests\/[^/]+\/run\/[^/]+$/ : /\/backtests\/[^/]+$/);
|
||||
}
|
||||
|
||||
export async function submitInBrowser(page: Page) {
|
||||
await page.getByRole('button', { name: 'New Run', exact: true }).click();
|
||||
const response = page.waitForResponse(
|
||||
response =>
|
||||
response.request().method() === 'POST' &&
|
||||
/\/api\/v2\/backtests\/[^/]+\/runs$/.test(response.url())
|
||||
);
|
||||
await page
|
||||
.getByRole('button', { name: 'Run current settings', exact: true })
|
||||
.filter({ hasText: 'Run current settings' })
|
||||
.click();
|
||||
const accepted = await response;
|
||||
const run = await accepted.json();
|
||||
await page.waitForURL(url => url.pathname.endsWith(`/run/${run.id}`));
|
||||
return accepted;
|
||||
}
|
||||
280
test/e2e/workbench.test.ts
Normal file
280
test/e2e/workbench.test.ts
Normal file
|
|
@ -0,0 +1,280 @@
|
|||
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();
|
||||
}
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue