feat(research): add strategy catalog and versioned backtest setup
This commit is contained in:
parent
8cca0ee588
commit
d929db707a
44 changed files with 4198 additions and 209 deletions
|
|
@ -75,7 +75,7 @@ async function fixture(
|
|||
});
|
||||
db.public
|
||||
.none(`CREATE TYPE run_status AS ENUM ('pending','running','completed','failed','cancelled','paused');
|
||||
CREATE TABLE backtests (id uuid PRIMARY KEY, name text, strategy text, symbols jsonb, archived_at timestamptz,
|
||||
CREATE TABLE backtests (id uuid PRIMARY KEY, name text, strategy text, symbols jsonb, archived_at timestamptz, strategy_version_id uuid, strategy_parameters jsonb,
|
||||
start_date timestamptz, end_date timestamptz, initial_capital numeric, 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), run_number integer,
|
||||
|
|
|
|||
138
test/integration/catalog-backtest-contract.test.ts
Normal file
138
test/integration/catalog-backtest-contract.test.ts
Normal file
|
|
@ -0,0 +1,138 @@
|
|||
import { randomUUID } from 'node:crypto';
|
||||
import { describe, expect, mock, test } from 'bun:test';
|
||||
import type { IServiceContainer } from '@stock-bot/services';
|
||||
import {
|
||||
backtestRequestFromDefinition,
|
||||
backtestSettingsFromDefinition,
|
||||
CatalogBacktestDefinitionSchema,
|
||||
parseBacktestRequest,
|
||||
} from '@stock-bot/stock-config/backtest';
|
||||
import {
|
||||
builtinCatalogDescriptors,
|
||||
parseStrategyVersionPackage,
|
||||
validateStrategyParameters,
|
||||
} from '@stock-bot/stock-config/strategy';
|
||||
import { PostgresBacktestRunRepository } from '../../apps/stock/orchestrator/src/backtest/PostgresBacktestRunRepository';
|
||||
import { BacktestService } from '../../apps/stock/web-api/src/services/backtest.service';
|
||||
|
||||
const definition = {
|
||||
name: 'Catalog setup',
|
||||
strategy: 'catalog',
|
||||
strategyVersionId: randomUUID(),
|
||||
strategyParameters: {},
|
||||
symbols: ['AAPL.US'],
|
||||
startDate: '2024-01-01T00:00:00.000Z',
|
||||
endDate: '2024-02-01T00:00:00.000Z',
|
||||
initialCapital: 1000,
|
||||
config: { dataFrequency: '1d', commission: 0.002 },
|
||||
};
|
||||
describe('catalog draft and execution contracts', () => {
|
||||
test('shared settings validation is independent of execution and never merges strategy parameters', () => {
|
||||
const parsed = CatalogBacktestDefinitionSchema.parse({
|
||||
...definition,
|
||||
strategyParameters: { commission: 99 },
|
||||
});
|
||||
const settings = backtestSettingsFromDefinition(parsed);
|
||||
expect(settings).toMatchObject({
|
||||
commission: 0.002,
|
||||
slippage: 0.0001,
|
||||
symbols: ['AAPL.US'],
|
||||
dataFrequency: '1d',
|
||||
});
|
||||
expect(settings).not.toHaveProperty('strategy');
|
||||
expect(settings).not.toHaveProperty('strategyParameters');
|
||||
expect(() => backtestRequestFromDefinition(parsed)).toThrow('Retained strategy versions');
|
||||
for (const config of [
|
||||
{ ...definition.config, lookback: 5 },
|
||||
{ ...definition.config, strategyVersionId: randomUUID() },
|
||||
]) {
|
||||
expect(() => CatalogBacktestDefinitionSchema.parse({ ...definition, config })).toThrow();
|
||||
}
|
||||
expect(() => backtestSettingsFromDefinition({ ...definition, initialCapital: 0 })).toThrow();
|
||||
expect(() =>
|
||||
backtestSettingsFromDefinition({ ...definition, endDate: definition.startDate })
|
||||
).toThrow();
|
||||
});
|
||||
test('legacy parsers and direct repository refuse markers even when null or nested', async () => {
|
||||
const legacy = {
|
||||
mode: 'backtest',
|
||||
name: 'Legacy',
|
||||
strategy: 'sma-crossover',
|
||||
symbols: definition.symbols,
|
||||
startDate: definition.startDate,
|
||||
endDate: definition.endDate,
|
||||
dataFrequency: '1d',
|
||||
initialCapital: 1000,
|
||||
};
|
||||
const database = {
|
||||
transaction: mock(async () => {
|
||||
throw new Error('Unexpected write');
|
||||
}),
|
||||
};
|
||||
const repository = new PostgresBacktestRunRepository(database);
|
||||
for (const marker of [
|
||||
{ strategy: 'catalog' },
|
||||
{ strategyVersionId: null },
|
||||
{ strategyVersionIds: [] },
|
||||
{ strategyParameters: {} },
|
||||
{ config: { strategyVersionId: null } },
|
||||
{ strategies: [{ name: 'sma-crossover', config: { strategyVersionId: 'retained' } }] },
|
||||
]) {
|
||||
const input = { ...legacy, ...marker };
|
||||
expect(() => parseBacktestRequest(input)).toThrow('Retained strategy versions');
|
||||
await expect(
|
||||
repository.start(input as ReturnType<typeof parseBacktestRequest>)
|
||||
).rejects.toThrow('Retained strategy versions');
|
||||
}
|
||||
expect(database.transaction.mock.calls).toHaveLength(0);
|
||||
const facade = new BacktestService({
|
||||
postgres: database,
|
||||
logger: { info() {} },
|
||||
} as unknown as IServiceContainer);
|
||||
await expect(facade.createBacktest(definition)).rejects.toThrow('Retained strategy versions');
|
||||
expect(database.transaction.mock.calls).toHaveLength(0);
|
||||
});
|
||||
test('builtin parameter validation preserves decimal strings and refuses invalid Unicode', () => {
|
||||
const descriptor = builtinCatalogDescriptors.find(
|
||||
item => item.program.strategyId === 'mean_reversion'
|
||||
)!;
|
||||
const pkg = parseStrategyVersionPackage({
|
||||
version: 1,
|
||||
program: descriptor.program,
|
||||
artifact: {
|
||||
format: 'esm-bundle/v1',
|
||||
entryExport: descriptor.entryExport,
|
||||
content: 'retained-not-executed',
|
||||
sha256: 'a'.repeat(64),
|
||||
},
|
||||
dependencyLock: { format: 'bun-lock/v1', content: '{}', sha256: 'b'.repeat(64) },
|
||||
parameterSchema: descriptor.parameterSchema,
|
||||
source: { revision: 'a'.repeat(40), dirty: false },
|
||||
build: { tool: 'bun', version: 'fixture', target: 'browser' },
|
||||
});
|
||||
const parameters = {
|
||||
lookbackPeriod: 2,
|
||||
trendPeriod: 3,
|
||||
momentumPeriod: 1,
|
||||
volatilityPeriod: 2,
|
||||
entryZScore: 1,
|
||||
exitZScore: 0,
|
||||
minTrendReturn: -0.9,
|
||||
minMomentumReturn: -0.9,
|
||||
maxVolatility: 0,
|
||||
minNotionalVolume: '0.01',
|
||||
regimeFilter: 'none',
|
||||
};
|
||||
expect(() => validateStrategyParameters(pkg, {})).toThrow('Missing parameter');
|
||||
expect(validateStrategyParameters(pkg, parameters).minNotionalVolume).toBe('0.01000000');
|
||||
expect(() =>
|
||||
validateStrategyParameters(pkg, { ...parameters, minNotionalVolume: 100 })
|
||||
).toThrow();
|
||||
expect(() =>
|
||||
validateStrategyParameters(pkg, { ...parameters, minNotionalVolume: '\ud800' })
|
||||
).toThrow('UTF-8');
|
||||
expect(() =>
|
||||
validateStrategyParameters(pkg, { ...parameters, minNotionalVolume: '1\u0000' })
|
||||
).toThrow('UTF-8');
|
||||
});
|
||||
});
|
||||
986
test/integration/strategy-workbench.test.tsx
Normal file
986
test/integration/strategy-workbench.test.tsx
Normal file
|
|
@ -0,0 +1,986 @@
|
|||
import { afterAll, afterEach, beforeAll, beforeEach, describe, expect, test } from 'bun:test';
|
||||
import { GlobalWindow } from 'happy-dom';
|
||||
import { act, createElement, useState, type ReactElement } from 'react';
|
||||
import type { Root } from 'react-dom/client';
|
||||
import type {
|
||||
StrategyParameterSchema,
|
||||
StrategyRecord,
|
||||
StrategyVersionPackage,
|
||||
StrategyVersionSummary,
|
||||
} from '@stock-bot/types';
|
||||
import type { CatalogSelection } from '../../apps/stock/web-app/src/features/strategies/components/StrategySelection';
|
||||
import type { Parameters } from '../../apps/stock/web-app/src/features/strategies/services/strategyApi';
|
||||
|
||||
const browser = new GlobalWindow({ url: 'http://localhost:5173' });
|
||||
const keys = ['window', 'document', 'IS_REACT_ACT_ENVIRONMENT'] as const;
|
||||
const originals = new Map(keys.map(key => [key, Object.getOwnPropertyDescriptor(globalThis, key)]));
|
||||
let createRoot: typeof import('react-dom/client').createRoot;
|
||||
let router: typeof import('react-router-dom');
|
||||
let StrategyListPage: typeof import('../../apps/stock/web-app/src/features/strategies').StrategyListPage;
|
||||
let StrategyDetailPage: typeof import('../../apps/stock/web-app/src/features/strategies').StrategyDetailPage;
|
||||
let StrategyParameterForm: typeof import('../../apps/stock/web-app/src/features/strategies/components/StrategyParameterForm').StrategyParameterForm;
|
||||
let StrategySelection: typeof import('../../apps/stock/web-app/src/features/strategies/components/StrategySelection').StrategySelection;
|
||||
let LegacyStrategySelect: typeof import('../../apps/stock/web-app/src/features/strategies/components/StrategySelection').LegacyStrategySelect;
|
||||
let CreateBacktestDialog: typeof import('../../apps/stock/web-app/src/features/backtest/components/CreateBacktestDialog').CreateBacktestDialog;
|
||||
let BacktestDetailPageV2: typeof import('../../apps/stock/web-app/src/features/backtest/BacktestDetailPageV2').BacktestDetailPageV2;
|
||||
let useBacktestV2: typeof import('../../apps/stock/web-app/src/features/backtest/hooks/useBacktestV2').useBacktestV2;
|
||||
let RunControlsCompact: typeof import('../../apps/stock/web-app/src/features/backtest/components/RunControlsCompact').RunControlsCompact;
|
||||
let root: Root | undefined;
|
||||
let host: HTMLDivElement;
|
||||
let navigate: ReturnType<typeof router.useNavigate>;
|
||||
let location = '';
|
||||
let latest: ReturnType<typeof useBacktestV2>;
|
||||
function deferred<T>() {
|
||||
let resolve!: (value: T) => void;
|
||||
let reject!: (error: Error) => void;
|
||||
const promise = new Promise<T>((yes, no) => {
|
||||
resolve = yes;
|
||||
reject = no;
|
||||
});
|
||||
return { promise, resolve, reject };
|
||||
}
|
||||
type Pending = ReturnType<typeof deferred<Response>> & {
|
||||
path: string;
|
||||
method: string;
|
||||
body: unknown;
|
||||
headers: Headers;
|
||||
settled: boolean;
|
||||
};
|
||||
const requests: Pending[] = [];
|
||||
function request(path: string, method = 'GET') {
|
||||
const found = requests.find(
|
||||
item => item.path === path && item.method === method && !item.settled
|
||||
);
|
||||
if (!found) {
|
||||
throw new Error(
|
||||
`No pending ${method} ${path}; requests: ${requests.map(item => `${item.method} ${item.path} ${item.settled}`).join(', ')}`
|
||||
);
|
||||
}
|
||||
return found;
|
||||
}
|
||||
function reply(item: Pending, body: unknown, status = 200) {
|
||||
item.settled = true;
|
||||
item.resolve(Response.json(body, { status }));
|
||||
}
|
||||
function fail(item: Pending) {
|
||||
item.settled = true;
|
||||
item.reject(new Error('Response lost'));
|
||||
}
|
||||
async function flush(action: () => void = () => {}) {
|
||||
await act(async () => {
|
||||
action();
|
||||
await Promise.resolve();
|
||||
});
|
||||
}
|
||||
function button(label: string) {
|
||||
const found = [...host.querySelectorAll('button')].find(
|
||||
item => item.textContent?.trim() === label || item.getAttribute('aria-label') === label
|
||||
);
|
||||
if (!found) {
|
||||
throw new Error(`Missing button ${label}: ${host.textContent}`);
|
||||
}
|
||||
return found;
|
||||
}
|
||||
function click(label: string) {
|
||||
button(label).click();
|
||||
}
|
||||
function field(label: string) {
|
||||
const found = host.querySelector(`[aria-label="${label}"]`) as
|
||||
| HTMLInputElement
|
||||
| HTMLSelectElement
|
||||
| HTMLTextAreaElement
|
||||
| null;
|
||||
if (!found) {
|
||||
throw new Error(`Missing field ${label}`);
|
||||
}
|
||||
return found;
|
||||
}
|
||||
function edit(label: string, value: string) {
|
||||
const input = field(label);
|
||||
const prototype =
|
||||
input.tagName === 'SELECT'
|
||||
? browser.HTMLSelectElement.prototype
|
||||
: input.tagName === 'TEXTAREA'
|
||||
? browser.HTMLTextAreaElement.prototype
|
||||
: browser.HTMLInputElement.prototype;
|
||||
Object.getOwnPropertyDescriptor(prototype, 'value')!.set!.call(input, value);
|
||||
input.dispatchEvent(
|
||||
new browser.Event(input.tagName === 'SELECT' ? 'change' : 'input', {
|
||||
bubbles: true,
|
||||
}) as unknown as Event
|
||||
);
|
||||
}
|
||||
function Probe() {
|
||||
location = router.useLocation().pathname + router.useLocation().search;
|
||||
navigate = router.useNavigate();
|
||||
return null;
|
||||
}
|
||||
async function mount(element: ReactElement, path = '/') {
|
||||
root = createRoot(host);
|
||||
await flush(() =>
|
||||
root!.render(
|
||||
createElement(router.MemoryRouter, { initialEntries: [path] }, element, createElement(Probe))
|
||||
)
|
||||
);
|
||||
}
|
||||
const family = (id = 'family', extra: Partial<StrategyRecord> = {}): StrategyRecord => ({
|
||||
id,
|
||||
name: `Strategy ${id}`,
|
||||
description: 'Reviewed fixture',
|
||||
ownerPrincipal: 'operator',
|
||||
updatedBy: 'operator',
|
||||
archived: false,
|
||||
createdAt: '2026-01-01',
|
||||
updatedAt: '2026-01-01',
|
||||
...extra,
|
||||
});
|
||||
const schema: StrategyParameterSchema = {
|
||||
version: 1,
|
||||
type: 'object',
|
||||
additionalProperties: false,
|
||||
required: [],
|
||||
properties: {
|
||||
fastPeriod: { type: 'integer', minimum: 1, default: 5 },
|
||||
slowPeriod: { type: 'integer', minimum: 2, default: 15 },
|
||||
},
|
||||
};
|
||||
const pkg = (
|
||||
content = 'globalThis.CATALOG_MUST_NOT_EXECUTE = true; <img src=x onerror=alert(1)>'
|
||||
): StrategyVersionPackage => ({
|
||||
version: 1,
|
||||
program: {
|
||||
strategyId: 'fixture',
|
||||
strategyVersion: 'v1',
|
||||
apiVersion: 'canonical-ts/v1',
|
||||
checkpointVersion: 'fixture/v1',
|
||||
},
|
||||
artifact: {
|
||||
format: 'esm-bundle/v1',
|
||||
entryExport: 'createFixture',
|
||||
content,
|
||||
sha256: 'a'.repeat(64),
|
||||
},
|
||||
dependencyLock: { format: 'bun-lock/v1', content: 'lock', sha256: 'b'.repeat(64) },
|
||||
parameterSchema: schema,
|
||||
source: { revision: 'c'.repeat(40), dirty: false },
|
||||
build: { tool: 'bun', version: '1.2.17', target: 'browser' },
|
||||
});
|
||||
const version = (
|
||||
id = 'version-one',
|
||||
extra: Partial<StrategyVersionSummary> = {}
|
||||
): StrategyVersionSummary => {
|
||||
const full = pkg();
|
||||
const { content: _artifact, ...artifact } = full.artifact;
|
||||
const { content: _lock, ...dependencyLock } = full.dependencyLock;
|
||||
return {
|
||||
id,
|
||||
strategyId: 'family',
|
||||
ordinal: 1,
|
||||
parentVersionId: null,
|
||||
createdBy: 'operator',
|
||||
origin: 'builtin',
|
||||
createdAt: '2026-01-01',
|
||||
package: { ...full, artifact, dependencyLock },
|
||||
reviewStatus: 'approved',
|
||||
runnable: false,
|
||||
reason: 'Execution unavailable',
|
||||
...extra,
|
||||
};
|
||||
};
|
||||
const definition = {
|
||||
id: 'definition',
|
||||
name: 'Catalog fixture',
|
||||
strategy: 'catalog',
|
||||
strategyVersionId: 'version-one',
|
||||
strategyParameters: { fastPeriod: 5, slowPeriod: 15 },
|
||||
symbols: ['AAPL.US'],
|
||||
startDate: '2024-01-01',
|
||||
endDate: '2024-03-01',
|
||||
initialCapital: 100000,
|
||||
config: {},
|
||||
archivedAt: null,
|
||||
createdAt: '2026-01-01',
|
||||
updatedAt: '2026-01-01',
|
||||
};
|
||||
async function detail(path = '/strategies/family/versions/version-one', versions = [version()]) {
|
||||
await mount(
|
||||
createElement(
|
||||
router.Routes,
|
||||
null,
|
||||
createElement(router.Route, {
|
||||
path: '/strategies/:strategyId/versions/:versionId',
|
||||
element: createElement(StrategyDetailPage),
|
||||
})
|
||||
),
|
||||
path
|
||||
);
|
||||
await flush(() => {
|
||||
reply(request('/api/v2/strategies/family'), { strategy: family() });
|
||||
reply(request('/api/v2/strategies/family/versions'), { versions });
|
||||
reply(request('/api/v2/strategy-versions/version-one'), { version: versions[0], reviews: [] });
|
||||
});
|
||||
}
|
||||
async function selected(archived = false) {
|
||||
await flush(() => {
|
||||
reply(request('/api/v2/strategies'), { strategies: [family('family', { archived })] });
|
||||
reply(request('/api/v2/strategy-versions/version-one'), { version: version(), reviews: [] });
|
||||
});
|
||||
await flush(() =>
|
||||
reply(request('/api/v2/strategies/family'), { strategy: family('family', { archived }) })
|
||||
);
|
||||
await flush(() =>
|
||||
reply(request('/api/v2/strategies/family/versions'), { versions: [version()] })
|
||||
);
|
||||
}
|
||||
beforeAll(async () => {
|
||||
for (const [key, value] of Object.entries({
|
||||
window: browser,
|
||||
document: browser.document,
|
||||
IS_REACT_ACT_ENVIRONMENT: true,
|
||||
})) {
|
||||
Object.defineProperty(globalThis, key, { configurable: true, writable: true, value });
|
||||
}
|
||||
({ createRoot } = await import('react-dom/client'));
|
||||
router = await import('react-router-dom');
|
||||
({ StrategyListPage, StrategyDetailPage } = await import(
|
||||
'../../apps/stock/web-app/src/features/strategies'
|
||||
));
|
||||
({ StrategyParameterForm } = await import(
|
||||
'../../apps/stock/web-app/src/features/strategies/components/StrategyParameterForm'
|
||||
));
|
||||
({ StrategySelection, LegacyStrategySelect } = await import(
|
||||
'../../apps/stock/web-app/src/features/strategies/components/StrategySelection'
|
||||
));
|
||||
({ CreateBacktestDialog } = await import(
|
||||
'../../apps/stock/web-app/src/features/backtest/components/CreateBacktestDialog'
|
||||
));
|
||||
({ BacktestDetailPageV2 } = await import(
|
||||
'../../apps/stock/web-app/src/features/backtest/BacktestDetailPageV2'
|
||||
));
|
||||
({ useBacktestV2 } = await import(
|
||||
'../../apps/stock/web-app/src/features/backtest/hooks/useBacktestV2'
|
||||
));
|
||||
({ RunControlsCompact } = await import(
|
||||
'../../apps/stock/web-app/src/features/backtest/components/RunControlsCompact'
|
||||
));
|
||||
});
|
||||
beforeEach(() => {
|
||||
requests.length = 0;
|
||||
location = '';
|
||||
host = browser.document.createElement('div') as unknown as HTMLDivElement;
|
||||
browser.document.body.append(host as never);
|
||||
Object.defineProperty(browser, 'confirm', {
|
||||
configurable: true,
|
||||
writable: true,
|
||||
value: () => true,
|
||||
});
|
||||
browser.fetch = ((url: RequestInfo | URL, init?: RequestInit) => {
|
||||
const item: Pending = {
|
||||
...deferred<Response>(),
|
||||
path: new URL(String(url)).pathname,
|
||||
method: init?.method ?? 'GET',
|
||||
headers: new Headers(init?.headers),
|
||||
body: typeof init?.body === 'string' ? JSON.parse(init.body) : undefined,
|
||||
settled: false,
|
||||
};
|
||||
requests.push(item);
|
||||
return item.promise; // Ignore abort deliberately: stale-response fences must still hold.
|
||||
}) as unknown as typeof browser.fetch;
|
||||
});
|
||||
afterEach(async () => {
|
||||
if (root) {
|
||||
await flush(() => root!.unmount());
|
||||
}
|
||||
root = undefined;
|
||||
host.remove();
|
||||
});
|
||||
afterAll(async () => {
|
||||
await browser.happyDOM.close();
|
||||
for (const key of keys) {
|
||||
const descriptor = originals.get(key);
|
||||
if (descriptor) {
|
||||
Object.defineProperty(globalThis, key, descriptor);
|
||||
} else {
|
||||
delete (globalThis as Record<string, unknown>)[key];
|
||||
}
|
||||
}
|
||||
});
|
||||
|
||||
describe('strategy workbench', () => {
|
||||
test('catalog_navigation: loading, failure, retry, empty and metadata create route', async () => {
|
||||
await mount(createElement(StrategyListPage), '/strategies');
|
||||
expect(host.textContent).toContain('Loading strategies...');
|
||||
await flush(() => reply(request('/api/v2/strategies'), { error: 'Catalog offline' }, 503));
|
||||
expect(host.textContent).toContain('Catalog offline');
|
||||
await flush(() => click('Retry strategies'));
|
||||
await flush(() => reply(request('/api/v2/strategies'), { strategies: [] }));
|
||||
expect(host.textContent).toContain('No strategies found');
|
||||
await flush(() => click('New strategy'));
|
||||
await flush(() => {
|
||||
edit('Strategy name', 'My hypothesis');
|
||||
edit('Strategy description', 'Research only');
|
||||
});
|
||||
expect(host.textContent).toContain('Unsaved strategy metadata');
|
||||
await flush(() => click('Create strategy'));
|
||||
expect(request('/api/v2/strategies', 'POST').body).toEqual({
|
||||
name: 'My hypothesis',
|
||||
description: 'Research only',
|
||||
});
|
||||
await flush(() =>
|
||||
reply(request('/api/v2/strategies', 'POST'), { strategy: family('new-family') }, 201)
|
||||
);
|
||||
expect(location).toBe('/strategies/new-family');
|
||||
});
|
||||
|
||||
test('metadata errors retain unsaved edits; local exit can be declined; archive is explicit', async () => {
|
||||
await detail();
|
||||
await flush(() => edit('Strategy name', 'Edited'));
|
||||
Object.defineProperty(browser, 'confirm', {
|
||||
configurable: true,
|
||||
writable: true,
|
||||
value: () => false,
|
||||
});
|
||||
await flush(() => click('Discard metadata changes'));
|
||||
expect(field('Strategy name').value).toBe('Edited');
|
||||
await flush(() => click('Save metadata'));
|
||||
await flush(() =>
|
||||
reply(request('/api/v2/strategies/family', 'PATCH'), { error: 'Write failed' }, 503)
|
||||
);
|
||||
expect(field('Strategy name').value).toBe('Edited');
|
||||
expect(host.textContent).toContain('Write failed');
|
||||
Object.defineProperty(browser, 'confirm', {
|
||||
configurable: true,
|
||||
writable: true,
|
||||
value: () => true,
|
||||
});
|
||||
await flush(() => click('Discard metadata changes'));
|
||||
await flush(() => click('Archive strategy'));
|
||||
expect(request('/api/v2/strategies/family', 'PATCH').body).toEqual({ archived: true });
|
||||
await flush(() =>
|
||||
reply(request('/api/v2/strategies/family', 'PATCH'), {
|
||||
strategy: family('family', { archived: true }),
|
||||
})
|
||||
);
|
||||
expect(button('Use in backtest').disabled).toBe(true);
|
||||
expect(button('Restore strategy')).toBeDefined();
|
||||
});
|
||||
|
||||
test('parameter_form_validation: false, zero, typed enums, optional omission and decimal strings survive', async () => {
|
||||
const mixed: StrategyParameterSchema = {
|
||||
version: 1,
|
||||
type: 'object',
|
||||
additionalProperties: false,
|
||||
required: ['enabled', 'budget'],
|
||||
properties: {
|
||||
enabled: { type: 'boolean', default: false },
|
||||
count: { type: 'integer', minimum: 0, default: 0 },
|
||||
budget: { type: 'string', default: '000.10' },
|
||||
choice: { type: 'number', enum: [0, 1], default: 0 },
|
||||
optional: { type: 'string' },
|
||||
},
|
||||
};
|
||||
let result: Parameters = {};
|
||||
let valid = false;
|
||||
await mount(
|
||||
createElement(StrategyParameterForm, {
|
||||
versionId: 'mixed',
|
||||
schema: mixed,
|
||||
onChange: (parameters, checked) => {
|
||||
result = parameters;
|
||||
valid = checked;
|
||||
},
|
||||
})
|
||||
);
|
||||
await flush(() => click('Validate parameters'));
|
||||
expect(request('/api/v2/strategy-versions/mixed/validate', 'POST').body).toEqual({
|
||||
parameters: { enabled: false, count: 0, budget: '000.10', choice: 0 },
|
||||
});
|
||||
await flush(() =>
|
||||
reply(request('/api/v2/strategy-versions/mixed/validate', 'POST'), {
|
||||
parameters: { enabled: false, count: 0, budget: '0.1', choice: 0 },
|
||||
runnable: false,
|
||||
reason: 'Unavailable',
|
||||
})
|
||||
);
|
||||
expect(valid).toBe(true);
|
||||
expect(result.budget).toBe('0.1');
|
||||
await flush(() => edit('count', '-1'));
|
||||
expect(valid).toBe(false);
|
||||
expect(host.textContent).toContain('outside the allowed range');
|
||||
expect(button('Validate parameters').disabled).toBe(true);
|
||||
});
|
||||
|
||||
test('parameter_form_validation: present empty strings survive defaults; omitted strings stay omitted', async () => {
|
||||
const strings: StrategyParameterSchema = {
|
||||
version: 1,
|
||||
type: 'object',
|
||||
additionalProperties: false,
|
||||
required: ['requiredText'],
|
||||
properties: {
|
||||
requiredText: { type: 'string' },
|
||||
optionalText: { type: 'string', default: 'fallback' },
|
||||
absent: { type: 'string' },
|
||||
},
|
||||
};
|
||||
let result: Parameters = {};
|
||||
await mount(
|
||||
createElement(StrategyParameterForm, {
|
||||
versionId: 'strings',
|
||||
schema: strings,
|
||||
initialParameters: { requiredText: '', optionalText: '' },
|
||||
onChange: next => {
|
||||
result = next;
|
||||
},
|
||||
})
|
||||
);
|
||||
expect((field('Include requiredText') as HTMLInputElement).checked).toBe(true);
|
||||
expect((field('Include optionalText') as HTMLInputElement).checked).toBe(true);
|
||||
expect((field('Include absent') as HTMLInputElement).checked).toBe(false);
|
||||
await flush(() => click('Validate parameters'));
|
||||
const payload = request('/api/v2/strategy-versions/strings/validate', 'POST');
|
||||
expect(payload.body).toEqual({ parameters: { requiredText: '', optionalText: '' } });
|
||||
await flush(() =>
|
||||
reply(payload, {
|
||||
parameters: { requiredText: '', optionalText: '' },
|
||||
runnable: false,
|
||||
reason: 'Unavailable',
|
||||
})
|
||||
);
|
||||
expect(result).toEqual({ requiredText: '', optionalText: '' });
|
||||
await flush(() => (field('Include optionalText') as HTMLInputElement).click());
|
||||
expect(result).toEqual({ requiredText: '' });
|
||||
await flush(() => click('Validate parameters'));
|
||||
expect(request('/api/v2/strategy-versions/strings/validate', 'POST').body).toEqual({
|
||||
parameters: { requiredText: '' },
|
||||
});
|
||||
});
|
||||
|
||||
test('parameter_form_validation: a missing required string can be explicitly included as empty', async () => {
|
||||
const required: StrategyParameterSchema = {
|
||||
version: 1,
|
||||
type: 'object',
|
||||
additionalProperties: false,
|
||||
required: ['text'],
|
||||
properties: { text: { type: 'string' } },
|
||||
};
|
||||
await mount(
|
||||
createElement(StrategyParameterForm, {
|
||||
versionId: 'required',
|
||||
schema: required,
|
||||
onChange: () => {},
|
||||
})
|
||||
);
|
||||
expect(button('Validate parameters').disabled).toBe(true);
|
||||
expect(host.textContent).toContain('text: Required');
|
||||
await flush(() => (field('Include text') as HTMLInputElement).click());
|
||||
expect(button('Validate parameters').disabled).toBe(false);
|
||||
await flush(() => click('Validate parameters'));
|
||||
expect(request('/api/v2/strategy-versions/required/validate', 'POST').body).toEqual({
|
||||
parameters: { text: '' },
|
||||
});
|
||||
});
|
||||
|
||||
test('create-family double click is coalesced and late completion cannot navigate after unmount', async () => {
|
||||
await mount(createElement(StrategyListPage), '/strategies');
|
||||
await flush(() => reply(request('/api/v2/strategies'), { strategies: [] }));
|
||||
await flush(() => click('New strategy'));
|
||||
await flush(() => edit('Strategy name', 'One family'));
|
||||
await flush(() => {
|
||||
click('Create strategy');
|
||||
click('Create strategy');
|
||||
});
|
||||
expect(requests.filter(item => item.method === 'POST')).toHaveLength(1);
|
||||
const pending = request('/api/v2/strategies', 'POST');
|
||||
await flush(() =>
|
||||
root!.render(
|
||||
createElement(router.MemoryRouter, { initialEntries: ['/elsewhere'] }, createElement(Probe))
|
||||
)
|
||||
);
|
||||
await flush(() => reply(pending, { strategy: family('late') }, 201));
|
||||
expect(location).not.toBe('/strategies/late');
|
||||
});
|
||||
|
||||
test('parameter_form_validation: stale success cannot approve edited inputs; server cross-field error is visible', async () => {
|
||||
let valid = false;
|
||||
await mount(
|
||||
createElement(StrategyParameterForm, {
|
||||
versionId: 'version-one',
|
||||
schema,
|
||||
onChange: (_parameters, checked) => {
|
||||
valid = checked;
|
||||
},
|
||||
})
|
||||
);
|
||||
await flush(() => click('Validate parameters'));
|
||||
const old = request('/api/v2/strategy-versions/version-one/validate', 'POST');
|
||||
await flush(() => edit('fastPeriod', '20'));
|
||||
await flush(() =>
|
||||
reply(old, {
|
||||
parameters: { fastPeriod: 5, slowPeriod: 15 },
|
||||
runnable: false,
|
||||
reason: 'Unavailable',
|
||||
})
|
||||
);
|
||||
expect(valid).toBe(false);
|
||||
expect(field('fastPeriod').value).toBe('20');
|
||||
await flush(() => click('Validate parameters'));
|
||||
await flush(() =>
|
||||
reply(
|
||||
request('/api/v2/strategy-versions/version-one/validate', 'POST'),
|
||||
{ error: 'fastPeriod must be below slowPeriod' },
|
||||
400
|
||||
)
|
||||
);
|
||||
expect(host.textContent).toContain('fastPeriod must be below slowPeriod');
|
||||
expect(valid).toBe(false);
|
||||
});
|
||||
|
||||
test('immutable_version_selection: late version response cannot replace current route', async () => {
|
||||
await detail('/strategies/family/versions/version-one', [
|
||||
version(),
|
||||
version('version-two', { ordinal: 2 }),
|
||||
]);
|
||||
await flush(() => edit('Strategy version', 'version-two'));
|
||||
const old = request('/api/v2/strategy-versions/version-two');
|
||||
await flush(() => navigate('/strategies/family/versions/version-one'));
|
||||
await flush(() =>
|
||||
reply(request('/api/v2/strategy-versions/version-one'), { version: version(), reviews: [] })
|
||||
);
|
||||
await flush(() => reply(old, { version: version('version-two', { ordinal: 2 }), reviews: [] }));
|
||||
expect(location).toBe('/strategies/family/versions/version-one');
|
||||
expect(host.textContent).toContain('Immutable version ID: version-one');
|
||||
expect(host.textContent).not.toContain('Immutable version ID: version-two');
|
||||
});
|
||||
|
||||
test('clone_revision_diff: clone retries exact frozen body/key and compares inert retained bundles to parent', async () => {
|
||||
await detail('/strategies/family/versions/version-one', [
|
||||
version('version-one', {
|
||||
origin: 'candidate',
|
||||
parentVersionId: 'parent',
|
||||
reviewStatus: 'pending',
|
||||
}),
|
||||
]);
|
||||
await flush(() => edit('Compare with version', 'parent'));
|
||||
await flush(() => {
|
||||
reply(request('/api/v2/strategy-versions/version-one/artifact'), { package: pkg() });
|
||||
reply(request('/api/v2/strategy-versions/parent/artifact'), { package: pkg() });
|
||||
});
|
||||
expect(host.textContent).toContain('Identical artifact bytes');
|
||||
expect(host.querySelector('img')).toBeNull();
|
||||
expect((globalThis as Record<string, unknown>).CATALOG_MUST_NOT_EXECUTE).toBeUndefined();
|
||||
expect(host.querySelector('[aria-label="Selected bundled JavaScript"]')?.textContent).toContain(
|
||||
'<img src=x'
|
||||
);
|
||||
await flush(() => click('Clone version'));
|
||||
await flush(() => edit('Clone name', 'Cloned hypothesis'));
|
||||
await flush(() => click('Create clone'));
|
||||
const first = request('/api/v2/strategy-versions/version-one/clone', 'POST');
|
||||
await flush(() => fail(first));
|
||||
expect(field('Clone name').disabled).toBe(true);
|
||||
await flush(() => click('Retry clone'));
|
||||
const second = request('/api/v2/strategy-versions/version-one/clone', 'POST');
|
||||
expect(second.headers.get('Idempotency-Key')).toBe(first.headers.get('Idempotency-Key'));
|
||||
expect(second.body).toEqual(first.body);
|
||||
await flush(() =>
|
||||
reply(
|
||||
second,
|
||||
{
|
||||
strategy: family('clone-family'),
|
||||
version: version('clone-version', {
|
||||
strategyId: 'clone-family',
|
||||
parentVersionId: 'version-one',
|
||||
origin: 'candidate',
|
||||
reviewStatus: 'pending',
|
||||
}),
|
||||
},
|
||||
201
|
||||
)
|
||||
);
|
||||
expect(location).toBe('/strategies/clone-family/versions/clone-version');
|
||||
});
|
||||
|
||||
test('clone source identity and retry key stay frozen across same-family history navigation', async () => {
|
||||
await detail('/strategies/family/versions/version-one', [
|
||||
version(),
|
||||
version('version-two', { ordinal: 2 }),
|
||||
]);
|
||||
await flush(() => click('Clone version'));
|
||||
await flush(() => edit('Clone name', 'Clone original version'));
|
||||
await flush(() => click('Create clone'));
|
||||
const first = request('/api/v2/strategy-versions/version-one/clone', 'POST');
|
||||
// Browser history can change the route even while the version select is disabled.
|
||||
await flush(() => navigate('/strategies/family/versions/version-two'));
|
||||
await flush(() =>
|
||||
reply(request('/api/v2/strategy-versions/version-two'), {
|
||||
version: version('version-two', { ordinal: 2 }),
|
||||
reviews: [],
|
||||
})
|
||||
);
|
||||
expect(host.textContent).toContain('Clone immutable version 1');
|
||||
expect(host.textContent).toContain('Clone source version ID: version-one');
|
||||
expect(host.textContent).toContain('even while you view version 2 (version-two)');
|
||||
const cloned = {
|
||||
strategy: family('clone-family'),
|
||||
version: version('clone-version', {
|
||||
strategyId: 'clone-family',
|
||||
parentVersionId: 'version-one',
|
||||
origin: 'candidate',
|
||||
reviewStatus: 'pending',
|
||||
}),
|
||||
};
|
||||
await flush(() => reply(first, cloned, 201));
|
||||
expect(location).toBe('/strategies/family/versions/version-two');
|
||||
expect(host.textContent).toContain('Clone immutable version 1');
|
||||
await flush(() => click('Retry clone'));
|
||||
const retry = request('/api/v2/strategy-versions/version-one/clone', 'POST');
|
||||
expect(retry.headers.get('Idempotency-Key')).toBe(first.headers.get('Idempotency-Key'));
|
||||
expect(retry.body).toEqual(first.body);
|
||||
expect(requests.some(item => item.path === '/api/v2/strategy-versions/version-two/clone')).toBe(
|
||||
false
|
||||
);
|
||||
await flush(() => reply(retry, cloned, 201));
|
||||
expect(location).toBe('/strategies/family/versions/version-two');
|
||||
expect(host.textContent).toContain('Clone source version ID: version-one');
|
||||
});
|
||||
|
||||
test('immutable_version_selection: create saves exact validated ID and parameters without any run request', async () => {
|
||||
let saved: unknown;
|
||||
await mount(
|
||||
createElement(CreateBacktestDialog, {
|
||||
initialSelection: {
|
||||
strategyVersionId: 'version-one',
|
||||
strategyParameters: { fastPeriod: 3, slowPeriod: 8 },
|
||||
},
|
||||
onClose: () => {},
|
||||
onCreated: value => {
|
||||
saved = value;
|
||||
},
|
||||
})
|
||||
);
|
||||
await selected();
|
||||
expect(button('Save').disabled).toBe(true);
|
||||
expect(button('Save and run').disabled).toBe(true);
|
||||
await flush(() => click('Validate parameters'));
|
||||
expect(request('/api/v2/strategy-versions/version-one/validate', 'POST').body).toEqual({
|
||||
parameters: { fastPeriod: 3, slowPeriod: 8 },
|
||||
});
|
||||
await flush(() =>
|
||||
reply(request('/api/v2/strategy-versions/version-one/validate', 'POST'), {
|
||||
parameters: { fastPeriod: 3, slowPeriod: 8 },
|
||||
runnable: false,
|
||||
reason: 'Unavailable',
|
||||
})
|
||||
);
|
||||
await flush(() => {
|
||||
const input = host.querySelector('input[placeholder="My Strategy Backtest"]')!;
|
||||
Object.getOwnPropertyDescriptor(browser.HTMLInputElement.prototype, 'value')!.set!.call(
|
||||
input,
|
||||
'Saved research draft'
|
||||
);
|
||||
input.dispatchEvent(new browser.Event('input', { bubbles: true }) as unknown as Event);
|
||||
});
|
||||
await flush(() => click('Save'));
|
||||
const post = request('/api/v2/backtests', 'POST');
|
||||
expect(post.body).toMatchObject({
|
||||
strategy: 'catalog',
|
||||
strategyVersionId: 'version-one',
|
||||
strategyParameters: { fastPeriod: 3, slowPeriod: 8 },
|
||||
autoStart: false,
|
||||
});
|
||||
expect((post.body as { config: object }).config).not.toHaveProperty('fastPeriod');
|
||||
await flush(() => reply(post, definition));
|
||||
expect(saved).toEqual(definition);
|
||||
expect(requests.some(item => item.path.endsWith('/runs'))).toBe(false);
|
||||
});
|
||||
|
||||
test('reopened catalog settings save exact version parameters without legacy pacing and keep notices outside heading', async () => {
|
||||
await mount(
|
||||
createElement(
|
||||
router.Routes,
|
||||
null,
|
||||
createElement(router.Route, {
|
||||
path: '/backtests/:id',
|
||||
element: createElement(BacktestDetailPageV2),
|
||||
})
|
||||
),
|
||||
'/backtests/definition'
|
||||
);
|
||||
await flush(() => {
|
||||
reply(request('/api/v2/backtests/definition'), {
|
||||
...definition,
|
||||
config: { commission: 0, slippage: 0 },
|
||||
});
|
||||
reply(request('/api/v2/backtests/definition/runs'), []);
|
||||
});
|
||||
expect(host.querySelector('h1 p')).toBeNull();
|
||||
expect(host.querySelector('h1')?.textContent).not.toContain('save-only');
|
||||
expect(host.querySelector('a[href="/strategies/versions/version-one"]')).not.toBeNull();
|
||||
await flush(() => click('Settings'));
|
||||
await selected();
|
||||
expect(host.querySelector('input[name="speedMultiplier"]')).toBeNull();
|
||||
await flush(() => edit('fastPeriod', '2'));
|
||||
await flush(() => click('Validate parameters'));
|
||||
await flush(() =>
|
||||
reply(request('/api/v2/strategy-versions/version-one/validate', 'POST'), {
|
||||
parameters: { fastPeriod: 2, slowPeriod: 15 },
|
||||
runnable: false,
|
||||
reason: 'Unavailable',
|
||||
})
|
||||
);
|
||||
await flush(() => click('Save'));
|
||||
const saved = request('/api/v2/backtests/definition', 'PUT');
|
||||
expect(saved.body).toMatchObject({
|
||||
strategy: 'catalog',
|
||||
strategyVersionId: 'version-one',
|
||||
strategyParameters: { fastPeriod: 2, slowPeriod: 15 },
|
||||
});
|
||||
expect((saved.body as { config: object }).config).not.toHaveProperty('speedMultiplier');
|
||||
expect((saved.body as { config: object }).config).toMatchObject({
|
||||
commission: 0,
|
||||
slippage: 0,
|
||||
dataFrequency: '1d',
|
||||
dataSource: 'auto',
|
||||
});
|
||||
await flush(() =>
|
||||
reply(saved, { ...definition, strategyParameters: { fastPeriod: 2, slowPeriod: 15 } })
|
||||
);
|
||||
await selected();
|
||||
expect(field('fastPeriod').value).toBe('2');
|
||||
await flush(() => click('Runs'));
|
||||
expect(button('New Run').disabled).toBe(true);
|
||||
expect(requests.some(item => item.method === 'POST' && item.path.endsWith('/runs'))).toBe(
|
||||
false
|
||||
);
|
||||
});
|
||||
|
||||
test('catalog authoritative archive/restore resets visible parameters and validation together', async () => {
|
||||
await mount(
|
||||
createElement(
|
||||
router.Routes,
|
||||
null,
|
||||
createElement(router.Route, {
|
||||
path: '/backtests/:id',
|
||||
element: createElement(BacktestDetailPageV2),
|
||||
})
|
||||
),
|
||||
'/backtests/definition'
|
||||
);
|
||||
await flush(() => {
|
||||
reply(request('/api/v2/backtests/definition'), {
|
||||
...definition,
|
||||
config: { commission: 0, slippage: 0 },
|
||||
});
|
||||
reply(request('/api/v2/backtests/definition/runs'), []);
|
||||
});
|
||||
await flush(() => click('Settings'));
|
||||
await selected();
|
||||
await flush(() => edit('fastPeriod', '2'));
|
||||
await flush(() => click('Validate parameters'));
|
||||
await flush(() =>
|
||||
reply(request('/api/v2/strategy-versions/version-one/validate', 'POST'), {
|
||||
parameters: { fastPeriod: 2, slowPeriod: 15 },
|
||||
runnable: false,
|
||||
reason: 'Unavailable',
|
||||
})
|
||||
);
|
||||
expect(button('Save').disabled).toBe(false);
|
||||
await flush(() => click('Validate parameters'));
|
||||
const staleValidation = request('/api/v2/strategy-versions/version-one/validate', 'POST');
|
||||
await flush(() => click('Archive backtest'));
|
||||
await flush(() => click('Confirm archive'));
|
||||
await flush(() =>
|
||||
reply(request('/api/v2/backtests/definition/archive', 'POST'), {
|
||||
...definition,
|
||||
config: { commission: 0, slippage: 0 },
|
||||
archivedAt: '2026-01-02',
|
||||
})
|
||||
);
|
||||
await selected();
|
||||
expect(field('fastPeriod').value).toBe('5');
|
||||
expect(field('fastPeriod').disabled).toBe(true);
|
||||
expect(button('Save').disabled).toBe(true);
|
||||
await flush(() => click('Restore backtest'));
|
||||
await flush(() => click('Confirm restore'));
|
||||
await flush(() =>
|
||||
reply(request('/api/v2/backtests/definition/archive', 'POST'), {
|
||||
...definition,
|
||||
config: { commission: 0, slippage: 0 },
|
||||
})
|
||||
);
|
||||
await selected();
|
||||
await flush(() =>
|
||||
reply(staleValidation, {
|
||||
parameters: { fastPeriod: 2, slowPeriod: 15 },
|
||||
runnable: false,
|
||||
reason: 'Unavailable',
|
||||
})
|
||||
);
|
||||
expect(field('fastPeriod').value).toBe('5');
|
||||
expect(field('fastPeriod').disabled).toBe(false);
|
||||
expect(button('Save').disabled).toBe(true);
|
||||
await flush(() => click('Validate parameters'));
|
||||
expect(request('/api/v2/strategy-versions/version-one/validate', 'POST').body).toEqual({
|
||||
parameters: { fastPeriod: 5, slowPeriod: 15 },
|
||||
});
|
||||
await flush(() =>
|
||||
reply(request('/api/v2/strategy-versions/version-one/validate', 'POST'), {
|
||||
parameters: { fastPeriod: 5, slowPeriod: 15 },
|
||||
runnable: false,
|
||||
reason: 'Unavailable',
|
||||
})
|
||||
);
|
||||
await flush(() => click('Save'));
|
||||
expect(request('/api/v2/backtests/definition', 'PUT').body).toMatchObject({
|
||||
strategyVersionId: 'version-one',
|
||||
strategyParameters: { fastPeriod: 5, slowPeriod: 15 },
|
||||
});
|
||||
});
|
||||
|
||||
test('legacy settings retain the existing pacing field and submitted speed', async () => {
|
||||
await mount(
|
||||
createElement(
|
||||
router.Routes,
|
||||
null,
|
||||
createElement(router.Route, {
|
||||
path: '/backtests/:id',
|
||||
element: createElement(BacktestDetailPageV2),
|
||||
})
|
||||
),
|
||||
'/backtests/definition'
|
||||
);
|
||||
await flush(() => {
|
||||
reply(request('/api/v2/backtests/definition'), {
|
||||
...definition,
|
||||
config: { commission: 0, slippage: 0 },
|
||||
strategy: 'moving-average',
|
||||
strategyVersionId: null,
|
||||
strategyParameters: null,
|
||||
});
|
||||
reply(request('/api/v2/backtests/definition/runs'), []);
|
||||
});
|
||||
await flush(() => click('Settings'));
|
||||
const speed = host.querySelector('input[name="speedMultiplier"]')!;
|
||||
expect(speed).not.toBeNull();
|
||||
await flush(() => {
|
||||
Object.getOwnPropertyDescriptor(browser.HTMLInputElement.prototype, 'value')!.set!.call(
|
||||
speed,
|
||||
'0.2'
|
||||
);
|
||||
speed.dispatchEvent(new browser.Event('input', { bubbles: true }) as unknown as Event);
|
||||
});
|
||||
await flush(() => click('Save'));
|
||||
expect(request('/api/v2/backtests/definition', 'PUT').body).toMatchObject({
|
||||
strategy: 'moving-average',
|
||||
config: { speedMultiplier: 0.2 },
|
||||
});
|
||||
});
|
||||
|
||||
test('retained archived family is readable but cannot validate a new selection; existing saved selection can', async () => {
|
||||
let checked = false;
|
||||
function Selection({ retained = false }: { retained?: boolean }) {
|
||||
const [value, setValue] = useState<CatalogSelection>({
|
||||
strategyVersionId: 'version-one',
|
||||
strategyParameters: {},
|
||||
});
|
||||
return createElement(StrategySelection, {
|
||||
value,
|
||||
onChange: setValue,
|
||||
onValidityChange: valid => {
|
||||
checked = valid;
|
||||
},
|
||||
allowArchivedSelection: retained,
|
||||
});
|
||||
}
|
||||
await mount(createElement(Selection));
|
||||
await selected(true);
|
||||
expect(host.textContent).toContain('archived');
|
||||
expect(field('Immutable strategy version').disabled).toBe(true);
|
||||
expect(button('Validate parameters').disabled).toBe(true);
|
||||
expect(checked).toBe(false);
|
||||
await flush(() =>
|
||||
root!.render(
|
||||
createElement(router.MemoryRouter, null, createElement(Selection, { retained: true }))
|
||||
)
|
||||
);
|
||||
// The retained selection stays loaded when its edit policy changes.
|
||||
expect(button('Validate parameters').disabled).toBe(false);
|
||||
});
|
||||
|
||||
test('missing selected version is not cleared; retry preserves exact ID and blocks saving', async () => {
|
||||
let selectedId: string | null | undefined = 'version-one';
|
||||
await mount(
|
||||
createElement(StrategySelection, {
|
||||
value: { strategyVersionId: selectedId },
|
||||
onChange: next => {
|
||||
selectedId = next.strategyVersionId;
|
||||
},
|
||||
onValidityChange: () => {},
|
||||
})
|
||||
);
|
||||
await flush(() => {
|
||||
reply(request('/api/v2/strategies'), { strategies: [] });
|
||||
reply(request('/api/v2/strategy-versions/version-one'), { error: 'Version missing' }, 404);
|
||||
});
|
||||
expect(host.textContent).toContain('selection has been retained');
|
||||
expect(selectedId).toBe('version-one');
|
||||
await flush(() => click('Retry strategy catalog'));
|
||||
expect(request('/api/v2/strategy-versions/version-one')).toBeDefined();
|
||||
});
|
||||
|
||||
test('legacy filtering preserves unsupported saved labels and offers only independently supported choices', async () => {
|
||||
await mount(createElement(LegacyStrategySelect, { value: 'custom', onChange: () => {} }));
|
||||
expect(field('Legacy strategy').value).toBe('custom');
|
||||
expect(host.querySelector('option[value="custom"]')?.hasAttribute('disabled')).toBe(true);
|
||||
expect(host.querySelector('option[value="pairs-trading"]')).toBeNull();
|
||||
expect(host.querySelector('option[value="ml-enhanced"]')).toBeNull();
|
||||
expect(host.querySelector('option[value="moving-average"]')).not.toBeNull();
|
||||
expect(host.querySelector('option[value="momentum"]')).not.toBeNull();
|
||||
});
|
||||
|
||||
test('catalog execution stays blocked in the hook and controls; accepted run cancellation remains enabled', async () => {
|
||||
function Hook() {
|
||||
latest = useBacktestV2();
|
||||
return null;
|
||||
}
|
||||
await mount(createElement(Hook));
|
||||
await flush(() => {
|
||||
void latest.loadBacktest('definition');
|
||||
});
|
||||
await flush(() => {
|
||||
reply(request('/api/v2/backtests/definition'), definition);
|
||||
reply(request('/api/v2/backtests/definition/runs'), []);
|
||||
});
|
||||
await flush(() => {
|
||||
void latest.createRun(null);
|
||||
});
|
||||
expect(latest.submissionError).toContain('save-only');
|
||||
expect(requests.some(item => item.method === 'POST')).toBe(false);
|
||||
let cancelled = false;
|
||||
await flush(() =>
|
||||
root!.render(
|
||||
createElement(RunControlsCompact, {
|
||||
run: {
|
||||
id: 'accepted',
|
||||
backtestId: 'definition',
|
||||
runNumber: 1,
|
||||
status: 'running',
|
||||
speedMultiplier: null,
|
||||
progress: 10,
|
||||
createdAt: '2026-01-01',
|
||||
updatedAt: '2026-01-01',
|
||||
},
|
||||
cancelRequested: false,
|
||||
onCancel: () => {
|
||||
cancelled = true;
|
||||
},
|
||||
onRerun: () => {},
|
||||
executionUnavailable: true,
|
||||
})
|
||||
)
|
||||
);
|
||||
expect(button('Run current settings').disabled).toBe(true);
|
||||
expect(button('Cancel run').disabled).toBe(false);
|
||||
await flush(() => click('Cancel run'));
|
||||
expect(cancelled).toBe(true);
|
||||
});
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue