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
13
bun.lock
13
bun.lock
|
|
@ -30,6 +30,7 @@
|
|||
"mongodb-mcp-server": "^0.1.1",
|
||||
"mongodb-memory-server": "^9.1.6",
|
||||
"pg-mem": "^2.8.1",
|
||||
"playwright": "1.53.2",
|
||||
"prettier": "^3.5.3",
|
||||
"supertest": "^6.3.4",
|
||||
"ts-unused-exports": "^11.0.1",
|
||||
|
|
@ -1705,7 +1706,7 @@
|
|||
|
||||
"fs.realpath": ["fs.realpath@1.0.0", "", {}, "sha512-OO0pH2lK6a0hZnAdau5ItzHPI6pUlvI7jMVnxUQRtw4owF2wk8lOSabtGDCTP4Ggrg2MbGnWO9X8K1t4+fGMDw=="],
|
||||
|
||||
"fsevents": ["fsevents@2.3.3", "", { "os": "darwin" }, "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw=="],
|
||||
"fsevents": ["fsevents@2.3.2", "", { "os": "darwin" }, "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA=="],
|
||||
|
||||
"function-bind": ["function-bind@1.1.2", "", {}, "sha512-7XHNxH7qX9xG5mIwxkhumTox/MIRNcOgDrxWsMt2pAr23WHp6MrRlN7FBSFpCpr+oVO0F744iUgR82nJMfG2SA=="],
|
||||
|
||||
|
|
@ -2815,6 +2816,8 @@
|
|||
|
||||
"bl/readable-stream": ["readable-stream@3.6.2", "", { "dependencies": { "inherits": "^2.0.3", "string_decoder": "^1.1.1", "util-deprecate": "^1.0.1" } }, "sha512-9u/sniCrY3D5WdsERHzHE4G2YCXqoG5FTHUiCC4SIbr6XcLZBY05ya9EKjYek9O5xOAwjGq+1JdGBAS7Q9ScoA=="],
|
||||
|
||||
"chokidar/fsevents": ["fsevents@2.3.3", "", { "os": "darwin" }, "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw=="],
|
||||
|
||||
"chokidar/glob-parent": ["glob-parent@5.1.2", "", { "dependencies": { "is-glob": "^4.0.1" } }, "sha512-AOIgSQCepiJYwP3ARnGx+5VnTu2HBYdzbGP45eLw1vr3zB3vZLeyed1sC9hnbcOc9/SrMyM5RPQrkGz4aS9Zow=="],
|
||||
|
||||
"cliui/wrap-ansi": ["wrap-ansi@7.0.0", "", { "dependencies": { "ansi-styles": "^4.0.0", "string-width": "^4.1.0", "strip-ansi": "^6.0.0" } }, "sha512-YVGIj2kamLSTxw6NsZjoBxfSwsn0ycdesmc4p+Q21c5zPuZ1pl+NfxVdxPtdHvmNVOQ6XSYG4AUtyt/Fi7D16Q=="],
|
||||
|
|
@ -2943,8 +2946,6 @@
|
|||
|
||||
"pkg-dir/find-up": ["find-up@4.1.0", "", { "dependencies": { "locate-path": "^5.0.0", "path-exists": "^4.0.0" } }, "sha512-PpOwAdQ/YlXQ2vj8a3h8IipDuYRi3wceVQQGYWxNINccq40Anw7BlsEXCMbt1Zt+OLA6Fq9suIpIWD0OsnISlw=="],
|
||||
|
||||
"playwright/fsevents": ["fsevents@2.3.2", "", { "os": "darwin" }, "sha512-xiqMQR4xAeHTuB9uWm+fFRcIOgKBMiOBP+eXiyT7jsgVCq1bkVygt00oASowB7EdtpOHaaPgKt812P9ab+DDKA=="],
|
||||
|
||||
"prebuild-install/tar-fs": ["tar-fs@2.1.3", "", { "dependencies": { "chownr": "^1.1.1", "mkdirp-classic": "^0.5.2", "pump": "^3.0.0", "tar-stream": "^2.1.4" } }, "sha512-090nwYJDmlhwFwEW3QQl+vaNnxsO2yVsd45eTKRBzSzu+hlb1w2K9inVq5b0ngXuLVqQ4ApvsUHHnu/zQNkWAg=="],
|
||||
|
||||
"prop-types/react-is": ["react-is@16.13.1", "", {}, "sha512-24e6ynE2H+OKt4kqsOvNd8kBpV65zoxbA4BVsEOB3ARVWQki/DHzaUoC5KuON/BiccDaCCTZBuOcfZs70kR8bQ=="],
|
||||
|
|
@ -2965,6 +2966,8 @@
|
|||
|
||||
"rimraf/glob": ["glob@7.2.3", "", { "dependencies": { "fs.realpath": "^1.0.0", "inflight": "^1.0.4", "inherits": "2", "minimatch": "^3.1.1", "once": "^1.3.0", "path-is-absolute": "^1.0.0" } }, "sha512-nFR0zLpU2YCaRxwoCJvL6UvCH2JFyFVIvwTLsIf21AuHlMskA1hhTdk+LlYJtOlYt9v6dvszD2BGRqBL+iQK9Q=="],
|
||||
|
||||
"rollup/fsevents": ["fsevents@2.3.3", "", { "os": "darwin" }, "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw=="],
|
||||
|
||||
"run-applescript/execa": ["execa@5.1.1", "", { "dependencies": { "cross-spawn": "^7.0.3", "get-stream": "^6.0.0", "human-signals": "^2.1.0", "is-stream": "^2.0.0", "merge-stream": "^2.0.0", "npm-run-path": "^4.0.1", "onetime": "^5.1.2", "signal-exit": "^3.0.3", "strip-final-newline": "^2.0.0" } }, "sha512-8uSpZZocAZRBAPIEINJj3Lo9HyGitllczc27Eh5YYojjMFMn8yHMDMaUHE2Jqfq05D/wucwI4JGURyXt1vchyg=="],
|
||||
|
||||
"send/mime-types": ["mime-types@3.0.1", "", { "dependencies": { "mime-db": "^1.54.0" } }, "sha512-xRc4oEhT6eaBpU1XF7AjpOFD+xQmXNB5OVKwp4tqCuBpHLS/ZbBDrc07mYTDqVMg6PfxUjjNp85O6Cd2Z/5HWA=="],
|
||||
|
|
@ -2995,10 +2998,14 @@
|
|||
|
||||
"ts-unused-exports/chalk": ["chalk@4.1.2", "", { "dependencies": { "ansi-styles": "^4.1.0", "supports-color": "^7.1.0" } }, "sha512-oKnbhFyRIXpUuez8iBMmyEa4nbj4IOQyuhc/wy9kY7/WVPcwIO9VA668Pu8RkO7+0G76SLROeyw9CpQ061i4mA=="],
|
||||
|
||||
"tsx/fsevents": ["fsevents@2.3.3", "", { "os": "darwin" }, "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw=="],
|
||||
|
||||
"type-is/mime-types": ["mime-types@3.0.1", "", { "dependencies": { "mime-db": "^1.54.0" } }, "sha512-xRc4oEhT6eaBpU1XF7AjpOFD+xQmXNB5OVKwp4tqCuBpHLS/ZbBDrc07mYTDqVMg6PfxUjjNp85O6Cd2Z/5HWA=="],
|
||||
|
||||
"vite/esbuild": ["esbuild@0.18.20", "", { "optionalDependencies": { "@esbuild/android-arm": "0.18.20", "@esbuild/android-arm64": "0.18.20", "@esbuild/android-x64": "0.18.20", "@esbuild/darwin-arm64": "0.18.20", "@esbuild/darwin-x64": "0.18.20", "@esbuild/freebsd-arm64": "0.18.20", "@esbuild/freebsd-x64": "0.18.20", "@esbuild/linux-arm": "0.18.20", "@esbuild/linux-arm64": "0.18.20", "@esbuild/linux-ia32": "0.18.20", "@esbuild/linux-loong64": "0.18.20", "@esbuild/linux-mips64el": "0.18.20", "@esbuild/linux-ppc64": "0.18.20", "@esbuild/linux-riscv64": "0.18.20", "@esbuild/linux-s390x": "0.18.20", "@esbuild/linux-x64": "0.18.20", "@esbuild/netbsd-x64": "0.18.20", "@esbuild/openbsd-x64": "0.18.20", "@esbuild/sunos-x64": "0.18.20", "@esbuild/win32-arm64": "0.18.20", "@esbuild/win32-ia32": "0.18.20", "@esbuild/win32-x64": "0.18.20" }, "bin": { "esbuild": "bin/esbuild" } }, "sha512-ceqxoedUrcayh7Y7ZX6NdbbDzGROiyVBgC4PriJThBKSVPWnnFHZAkfI1lJT8QFkOwH4qOS2SJkS4wvpGl8BpA=="],
|
||||
|
||||
"vite/fsevents": ["fsevents@2.3.3", "", { "os": "darwin" }, "sha512-5xoDfX+fL7faATnagmWPpbFtwh/R77WmMMqqHGS65C3vvB0YHrgF+B1YmZ3441tMj5n63k0212XNoJwzlhffQw=="],
|
||||
|
||||
"win-export-certificate-and-key/node-addon-api": ["node-addon-api@3.2.1", "", {}, "sha512-mmcei9JghVNDYydghQmeDX8KoAm0FAiYyIcUt/N4nhyAipB17pllZQDOJD2fotxABnt4Mdz+dKTO7eftLg4d0A=="],
|
||||
|
||||
"wrap-ansi/ansi-styles": ["ansi-styles@6.2.1", "", {}, "sha512-bN798gFfQX+viw3R7yrGWRqnrN2oRkEkUjjl4JNn4E8GxxbjtG3FbrEIIY3l8/hrwUwIeCZvi4QuOTP4MErVug=="],
|
||||
|
|
|
|||
|
|
@ -28,7 +28,8 @@
|
|||
"test:postgres": "bun run scripts/test-postgres.ts",
|
||||
"test:analytics-api": "uv run --no-project --with fastapi==0.104.1 --with httpx==0.25.2 --with pydantic==2.5.0 python -m unittest discover -s apps/stock/analytics/test",
|
||||
"audit:secrets": "bun run scripts/audit-secrets.ts",
|
||||
"test:e2e": "bun test test/e2e",
|
||||
"test:e2e": "bun run scripts/test-e2e.ts",
|
||||
"test:e2e:install": "playwright install chromium",
|
||||
"test:libs": "turbo run test --filter='./libs/**'",
|
||||
"test:apps": "turbo run test --filter=./apps/*/*",
|
||||
"lint": "eslint apps/stock libs tools --ext .ts,.tsx",
|
||||
|
|
@ -105,6 +106,7 @@
|
|||
"mongodb-mcp-server": "^0.1.1",
|
||||
"mongodb-memory-server": "^9.1.6",
|
||||
"pg-mem": "^2.8.1",
|
||||
"playwright": "1.53.2",
|
||||
"prettier": "^3.5.3",
|
||||
"supertest": "^6.3.4",
|
||||
"ts-unused-exports": "^11.0.1",
|
||||
|
|
|
|||
44
scripts/test-e2e.ts
Normal file
44
scripts/test-e2e.ts
Normal file
|
|
@ -0,0 +1,44 @@
|
|||
import { createHash } from 'node:crypto';
|
||||
import { existsSync, readFileSync, realpathSync } from 'node:fs';
|
||||
import { resolve } from 'node:path';
|
||||
import { fileURLToPath } from 'node:url';
|
||||
import { chromium } from 'playwright';
|
||||
|
||||
const database = process.env.PIPELINE_TEST_DATABASE_URL;
|
||||
const redis = process.env.BACKTEST_TEST_REDIS_URL;
|
||||
if (!database || !new URL(database).pathname.startsWith('/stock_bot_safety')) {
|
||||
throw new Error('Set PIPELINE_TEST_DATABASE_URL to a disposable stock_bot_safety database');
|
||||
}
|
||||
if (!redis || new URL(redis).pathname !== '/15') {
|
||||
throw new Error('Set BACKTEST_TEST_REDIS_URL to a dedicated Redis fixture using database 15');
|
||||
}
|
||||
if (!existsSync(chromium.executablePath())) {
|
||||
throw new Error('Chromium is missing. Explicitly install it with bun run test:e2e:install');
|
||||
}
|
||||
for (const file of [
|
||||
'libs/core/di/dist/index.js',
|
||||
'apps/stock/engine/dist/engine.node',
|
||||
]) {
|
||||
if (!existsSync(file)) {
|
||||
throw new Error(`Missing ${file}. Build this worktree with bun run build before browser tests`);
|
||||
}
|
||||
}
|
||||
const expectedEngine = realpathSync(resolve('apps/stock/engine/index.mjs'));
|
||||
if (realpathSync(fileURLToPath(import.meta.resolve('@stock-bot/engine'))) !== expectedEngine) {
|
||||
throw new Error('Native engine resolves outside this worktree');
|
||||
}
|
||||
console.log(`Browser native addon SHA256: ${createHash('sha256').update(readFileSync('apps/stock/engine/dist/engine.node')).digest('hex')}`);
|
||||
// Always rebuild from this checkout. An empty override prevents a local .env from
|
||||
// silently directing browser requests to a development or live API.
|
||||
const build = Bun.spawn([process.execPath, 'run', '--cwd', 'apps/stock/web-app', 'build'], {
|
||||
env: { ...process.env, NODE_ENV: 'production', VITE_API_BASE_URL: '' },
|
||||
stdin: 'inherit', stdout: 'inherit', stderr: 'inherit',
|
||||
});
|
||||
if (await build.exited) {
|
||||
throw new Error('Browser application build failed');
|
||||
}
|
||||
const tests = Bun.spawn([process.execPath, 'test', 'test/e2e/workbench.test.ts', '--timeout', '60000'], {
|
||||
env: { ...process.env, STOCK_BOT_E2E_BUILT: '1' },
|
||||
stdin: 'inherit', stdout: 'inherit', stderr: 'inherit',
|
||||
});
|
||||
process.exitCode = await tests.exited;
|
||||
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