Files
wibosim/server/src/soakfixes.test.js
T

141 lines
7.2 KiB
JavaScript

// Regressionstests für Befunde der Prüf-Simulation (test/soak-run.js): je Befund ein gezielter Test.
import { test } from 'node:test';
import assert from 'node:assert/strict';
import os from 'node:os';
import fs from 'node:fs';
import path from 'node:path';
process.env.NODE_ENV = 'test';
process.env.TIME_MODE = 'turbo';
process.env.DATA_DIR = fs.mkdtempSync(path.join(os.tmpdir(), 'wibosim-sfix-'));
const { settings } = await import('./settings.js');
const { Store } = await import('./store.js');
const { Game } = await import('./game.js');
Object.assign(settings.game, { dayMs: 60_000, tickMs: 1000, rivalsEnabled: false, ipoEveryDays: 0, recallsEnabled: false, staticCorridor: 0.5, dynamicCorridor: 0.3 });
settings.news.enabled = false;
function setup() {
const dir = fs.mkdtempSync(path.join(os.tmpdir(), 'wibosim-sf-'));
const clock = { t: Date.UTC(2026, 0, 5, 7, 0) };
const store = new Store(dir);
const g = new Game({ store, now: () => clock.t });
return { g, clock, dir, store };
}
const step = ({ g, clock }, n = 1) => { for (let i = 0; i < n; i++) { clock.t += 1000; g.tick(); } };
const toContinuous = (ctx) => { for (let i = 0; i < 400 && ctx.g.market.phase !== 'continuous'; i++) step(ctx); assert.equal(ctx.g.market.phase, 'continuous'); };
const player = async (g, name) => (await g.register({ name, password: 'geheim123' })).player;
const reload = (ctx) => { ctx.g.flush(true); ctx.store.close(); ctx.store = new Store(ctx.dir); ctx.g = new Game({ store: ctx.store, now: () => ctx.clock.t }); return ctx.g; };
/** ruhende Kauforder weit unter dem Kurs mit Bracket → zwei wartende Beine */
function restingBracket(g, p, sym) {
const s = g.stocks.get(sym);
const lim = Math.round(s.last * 0.85 * 100) / 100;
const o = g.placeOrder(p, { symbol: sym, side: 'buy', type: 'limit', qty: 10, price: lim, tif: 'gtc', bracket: { stopTrigger: Math.round(lim * 0.95 * 100) / 100, tpTrigger: Math.round(lim * 1.1 * 100) / 100 } });
assert.equal(g.ex.condOrders.filter((c) => c.parent === o.id && c.status === 'pending').length, 2);
return o;
}
const legsOf = (g, o) => g.ex.condOrders.filter((c) => c.parent === o.id);
test('Nachschuss der Spielleitung: Buchung enthält den Betrag', async () => {
const { g } = setup();
const p = await player(g, 'Empfaenger');
const fills = [];
const orig = g.recordFill.bind(g); g.recordFill = (f) => { fills.push(f); return orig(f); };
const c0 = p.cash;
g.adminAction({ name: 'admin' }, 'cash', { id: p.id, value: 2500 });
g.adminAction({ name: 'admin' }, 'cash', { id: p.id, value: -400 });
assert.equal(p.cash, c0 + 2100);
assert.deepEqual(fills.map((f) => [f.kind, f.side, f.price]), [['admin', 'deposit', 2500], ['admin', 'withdraw', 400]]);
});
test('Börsengang: Zuteilung wird gebucht (Journal, Gebühr, Steuer) und der Neuling bekommt ein Indexsegment', async () => {
const ctx = setup();
const { g } = ctx;
const p = await player(g, 'Zeichner');
const fills = [];
const orig = g.recordFill.bind(g); g.recordFill = (f) => { fills.push(f); return orig(f); };
const x = g.ipo.announce({ sector: 'tech', name: 'Pruefwerk AG', source: 'admin' });
g.ipo.subscribe(p, x.id, 100);
x.fair = x.hi * 2; g.macro.sentiment = 1;
g.day = x.closeDay;
g.ipo.newDay();
const q = p.positions[x.symbol]?.qty;
assert.ok(q > 0, 'zugeteilt');
const f = fills.find((y) => y.kind === 'ipo');
assert.ok(f, 'Zuteilung im Journal');
assert.deepEqual([f.symbol, f.side, f.qty, f.price, f.account], [x.symbol, 'buy', q, x.price, p.id]);
assert.ok(Math.abs(f.fee - q * x.price * settings.game.feeRate) < 1e-9 && Math.abs(p.fees - f.fee) < 1e-9);
assert.equal(g.indices.st.seg[x.symbol], 'small', 'Segment sofort gesetzt (wie nach einem Neustart)');
const g2 = reload(ctx);
assert.equal(g2.indices.st.seg[x.symbol], 'small');
});
test('Bracket: wartende Beine entfallen mit ihrer Mutter-Order (Ex-Tag, Sanierung, Selbsthandel/Buch)', async () => {
const ctx = setup();
const { g } = ctx;
const a = await player(g, 'Brackets'), b = await player(g, 'Gegenseite');
toContinuous(ctx);
// Ex-Tag löscht ruhende Orders
const o1 = restingBracket(g, a, 'RHBK');
g.ex.exDividend(g.stocks.get('RHBK'), 0.5);
assert.equal(legsOf(g, o1).length, 0, 'Ex-Tag: Beine weg');
// Insolvenz mit Sanierung löscht ruhende Spielerorders
const o2 = restingBracket(g, a, 'MEDX');
g.credit.default(g.stocks.get('MEDX'), 0.4, { liquidate: false });
assert.ok(!g.stocks.get('MEDX').book.orders.has(o2.id));
assert.equal(legsOf(g, o2).length, 0, 'Sanierung: Beine weg');
// Das Buch streicht eine ruhende Order selbst (hier nachgestellt): die nächste Ausführung räumt die Beine ab
const o3 = restingBracket(g, a, 'KRMA');
g.stocks.get('KRMA').book.removeWhere((o) => o.id === o3.id, 'cancelled');
g.placeOrder(b, { symbol: 'KRMA', side: 'buy', type: 'market', qty: 1 });
assert.equal(legsOf(g, o3).length, 0, 'Buch: Beine weg');
});
test('Entfallene bedingte Order (Position schon weg) wird auch im gespeicherten Stand gelöscht', async () => {
const ctx = setup();
const { g } = ctx;
const a = await player(g, 'Stopper');
toContinuous(ctx);
const s = g.stocks.get('RHBK');
g.placeOrder(a, { symbol: 'RHBK', side: 'buy', type: 'market', qty: 5 });
g.placeOrder(a, { symbol: 'RHBK', side: 'sell', type: 'stop', qty: 5, trigger: Math.round(s.last * 0.97 * 100) / 100 });
g.placeOrder(a, { symbol: 'RHBK', side: 'sell', type: 'market', qty: 5 }); // Position weg, Stopp bleibt (reduce-only)
g.flush(true);
assert.equal(g.ex.condOrders.length, 1);
g.dirtyPlayers.clear();
g.ex.condOrders[0].trigger = s.last * 10; // Auslöser sicher erreicht (Bots bewegen den Kurs im Takt) → Stopp entfällt mangels Position
g.ex.tick(1000);
assert.equal(g.ex.condOrders.length, 0);
assert.ok(g.dirtyPlayers.has(a.id), 'Konto zum Speichern vorgemerkt');
const g2 = reload(ctx);
assert.equal(g2.ex.condOrders.length, 0, 'nach Neustart nicht wieder da');
});
test('Listen der Rückzüge, Unternehmensereignisse und Ausfälle überstehen einen Neustart in voller Länge', async () => {
const ctx = setup();
const { g } = ctx;
for (let i = 0; i < 70; i++) {
g.delist.history.unshift({ day: i, symbol: `X${i}` });
g.corp.history.unshift({ day: i, symbol: `X${i}`, title: 't' });
g.credit.defaults.unshift({ day: i, symbol: `X${i}` });
}
g.credit.history.push(...Array.from({ length: 90 }, (_, i) => ({ day: i, symbol: `X${i}` })));
g.metaSnapshot(); // kürzt auf die gespeicherte Länge
const lens = [g.delist.history.length, g.corp.history.length, Math.min(g.credit.history.length, 80), g.credit.defaults.length];
const g2 = reload(ctx);
assert.deepEqual([g2.delist.history.length, g2.corp.history.length, g2.credit.history.length, g2.credit.defaults.length], [Math.min(lens[0], 60), Math.min(lens[1], 60), lens[2], 30]);
assert.ok(g.credit.defaults.length <= 30, 'Ausfallliste wächst nicht unbegrenzt');
});
test('Eingestellte Aktie: keine Intraday-Kerzen im Spielstand', async () => {
const ctx = setup();
const { g } = ctx;
toContinuous(ctx);
step(ctx, 20);
const s = g.stocks.get('KRMA');
assert.ok(s.candles.length > 0);
g.delist.delist(s, { reason: 'admin' });
assert.deepEqual(g.metaSnapshot().stocks.KRMA.candles, []);
assert.ok(g.metaSnapshot().stocks.RHBK.candles.length > 0);
});