commit 2 refactor
This commit is contained in:
parent
588f666943
commit
32e43c9243
310 changed files with 33318 additions and 31189 deletions
46
scripts/test/backend-boundaries.test.ts
Normal file
46
scripts/test/backend-boundaries.test.ts
Normal file
|
|
@ -0,0 +1,46 @@
|
|||
import { expect, test } from 'bun:test';
|
||||
import type { ServerWebSocket } from 'bun';
|
||||
import { requireServices, type IServiceContainer } from '@stock-bot/services';
|
||||
import { getLogger } from '@stock-bot/logger';
|
||||
import { createWebSocketHandler, type RunSocketData } from '../../apps/stock/web-api/src/websocket/run-updates';
|
||||
import { MonitoringService } from '../../apps/stock/web-api/src/services/monitoring.service';
|
||||
import { defined, at } from '@stock-bot/invariants';
|
||||
|
||||
const logger = getLogger('boundary-tests');
|
||||
|
||||
test('required services reject missing capabilities before work starts', () => {
|
||||
expect(() => requireServices({ logger }, 'mongodb')).toThrow("'mongodb' is unavailable");
|
||||
expect(() => requireServices({ logger, postgres: null }, 'postgres')).toThrow("'postgres' is unavailable");
|
||||
expect(requireServices({ logger }, 'logger').logger).toBe(logger);
|
||||
expect(() => defined(undefined)).toThrow();
|
||||
expect(() => at([], 0)).toThrow(RangeError);
|
||||
expect(defined(0)).toBe(0);
|
||||
});
|
||||
|
||||
test('Bun socket lifecycle dispatches messages and removes closed connections', () => {
|
||||
const sent: string[] = [];
|
||||
const socket = { data: { runId: 'run-1' }, send: (message: string) => sent.push(message), close() {} } as unknown as ServerWebSocket<RunSocketData>;
|
||||
const handler = createWebSocketHandler({ logger });
|
||||
handler.handleConnection(socket, 'run-1');
|
||||
handler.handleMessage(socket, '{"type":"ping"}');
|
||||
expect(JSON.parse(sent[0]!)).toMatchObject({ type: 'connected', runId: 'run-1' });
|
||||
expect(JSON.parse(sent[1]!)).toEqual({ type: 'pong' });
|
||||
handler.sendProgressUpdate('run-1', 25);
|
||||
expect(JSON.parse(sent[2]!)).toMatchObject({ type: 'progress', data: { progress: 25 } });
|
||||
handler.handleClose(socket);
|
||||
expect(handler.getConnectionsCount('run-1')).toBe(0);
|
||||
handler.cleanup();
|
||||
});
|
||||
|
||||
test('monitoring uses manager-owned queues and public counters', async () => {
|
||||
const names: string[] = [];
|
||||
const queueManager = { getQueue(name: string) {
|
||||
names.push(name);
|
||||
return { async getStats() { return { waiting: 2, active: 1, completed: 4, failed: 0, delayed: 0, paused: false, workers: 3 }; }, getWorkerCount() { return 3; } };
|
||||
} } as unknown as NonNullable<IServiceContainer['queueManager']>;
|
||||
const stats = await new MonitoringService({ logger, queueManager }).getQueueStats();
|
||||
expect(names).toContain('{data-pipeline_symbols}');
|
||||
expect(names).toContain('{data-ingestion_qm}');
|
||||
expect(stats.every(snapshot => snapshot.connected && snapshot.workers?.count === 3)).toBe(true);
|
||||
expect(await new MonitoringService({ logger }).getQueueStats()).toEqual([]);
|
||||
});
|
||||
25
scripts/test/coverage-integrity.test.ts
Normal file
25
scripts/test/coverage-integrity.test.ts
Normal file
|
|
@ -0,0 +1,25 @@
|
|||
import { expect, test } from 'bun:test';
|
||||
import { loadConfig } from '../../tools/coverage-cli/src/config';
|
||||
import { CoverageProcessor } from '../../tools/coverage-cli/src/processor';
|
||||
import { CoverageRunner } from '../../tools/coverage-cli/src/runner';
|
||||
|
||||
test('missing coverage cannot become a passing synthetic percentage', () => {
|
||||
const config = loadConfig({ threshold: 80 });
|
||||
const processor = new CoverageProcessor(config);
|
||||
const report = processor.process({ files: [] }, []);
|
||||
expect(report.overall.lines.percentage).toBe(0);
|
||||
expect(processor.checkThresholds(report).passed).toBe(false);
|
||||
});
|
||||
|
||||
test('requesting no existing packages is a failed coverage run', async () => {
|
||||
const config = loadConfig({ packages: ['__missing_coverage_fixture__'] });
|
||||
const result = await new CoverageRunner(config).run();
|
||||
expect(result.success).toBe(false);
|
||||
expect(result.coverage.files).toEqual([]);
|
||||
});
|
||||
|
||||
test('coverage configuration does not mutate defaults and rejects unknown reporters', () => {
|
||||
expect(loadConfig({ thresholdLines: 17 }).thresholds.lines).toBe(17);
|
||||
expect(loadConfig({}).thresholds.lines).toBe(80);
|
||||
expect(() => loadConfig({ reporters: ['not-a-reporter'] })).toThrow('Unknown coverage reporter');
|
||||
});
|
||||
|
|
@ -1,6 +1,6 @@
|
|||
import { createRequire } from 'node:module';
|
||||
import { describe, expect, it } from 'bun:test';
|
||||
import { IncrementalSMA, TechnicalIndicators } from '@stock-bot/engine';
|
||||
import { BacktestEngine, IncrementalSMA, TechnicalIndicators } from '@stock-bot/engine';
|
||||
|
||||
describe('generated native bindings', () => {
|
||||
it('ESM loads the generated artifact and exposes the documented constructor aliases', () => {
|
||||
|
|
@ -15,4 +15,27 @@ describe('generated native bindings', () => {
|
|||
expect(binding.TechnicalIndicators).toBe(TechnicalIndicators);
|
||||
expect(binding.IncrementalSMA).toBe(IncrementalSMA);
|
||||
});
|
||||
|
||||
it('MACD keeps full-length EMA series aligned without out-of-bounds access', () => {
|
||||
const indicators = new TechnicalIndicators();
|
||||
const prices = Array.from({ length: 80 }, (_, index) => 100 + index);
|
||||
const result = JSON.parse(indicators.calculateMacd(prices, 12, 26, 9)) as {
|
||||
macd: number[]; signal: number[]; histogram: number[];
|
||||
};
|
||||
const fast = indicators.calculateEma(prices, 12);
|
||||
const slow = indicators.calculateEma(prices, 26);
|
||||
expect(result.macd).toHaveLength(prices.length);
|
||||
expect(result.signal).toHaveLength(prices.length);
|
||||
for (let index = 0; index < prices.length; index++) {
|
||||
expect(result.macd[index]).toBeCloseTo(fast[index]! - slow[index]!, 10);
|
||||
expect(result.histogram[index]).toBeCloseTo(result.macd[index]! - result.signal[index]!, 10);
|
||||
}
|
||||
});
|
||||
|
||||
it('invalid SMA periods throw before entering the native event loop', () => {
|
||||
const engine = new BacktestEngine({ name: 'validation', symbols: ['TEST'], startDate: '2023-01-01T00:00:00Z', endDate: '2023-02-01T00:00:00Z', initialCapital: 100000, commission: 0, slippage: 0, dataFrequency: '1d' });
|
||||
expect(() => engine.addTypescriptStrategy('unsupported', 'unsupported', {}, () => '{}')).toThrow('TypeScript strategy callbacks are not supported');
|
||||
expect(() => engine.addNativeStrategy('sma_crossover', 'invalid', 'invalid', { fastPeriod: 0, slowPeriod: 20 })).toThrow('SMA periods must satisfy');
|
||||
expect(() => engine.addNativeStrategy('sma_crossover', 'invalid', 'invalid', { fastPeriod: 20, slowPeriod: 10 })).toThrow('SMA periods must satisfy');
|
||||
});
|
||||
});
|
||||
|
|
|
|||
12
scripts/test/orchestrator-container.test.ts
Normal file
12
scripts/test/orchestrator-container.test.ts
Normal file
|
|
@ -0,0 +1,12 @@
|
|||
import { expect, test } from 'bun:test';
|
||||
import { createExampleRuntime } from '../../apps/stock/orchestrator/examples/example-runtime';
|
||||
|
||||
test('offline examples use the shared DI graph without starting a real-time feed', async () => {
|
||||
const runtime = await createExampleRuntime();
|
||||
expect(runtime.container.custom?.StorageService).toBe(runtime.storageService);
|
||||
expect(runtime.container.custom?.StrategyManager).toBe(runtime.strategyManager);
|
||||
expect(runtime.container.mongodb).toBeNull();
|
||||
expect(runtime.container.queueManager).toBeNull();
|
||||
expect(runtime.modeManager.getConfig()).toBeNull();
|
||||
expect(() => runtime.modeManager.getTradingEngine()).toThrow('Trading engine not initialized');
|
||||
});
|
||||
Loading…
Add table
Add a link
Reference in a new issue